text
stringlengths 180
608k
|
---|
[Question]
[
I spent all of today at a Super Smash Bros. tournament, and I started thinking about some of the terminology we use when describing sets. These are the three kinds of sets that I see played at tournaments:
* Best of 3 (Bo3)
+ Three games are played. The winner of the set is the player who won the majority of the games.
+ If a single player wins two games of the set, they are immediately declared the winner, because it would be impossible for the opponent to catch up.
* Best of 5 (Bo5)
+ Five games are played. The winner of the set is the player who won the majority of the games.
+ If a single player wins three games of the set, they are immediately declared the winner, because it would be impossible for the opponent to catch up.
* First to 5 (Ft5)
+ Okay, I cheated a bit with my wording earlier. This kind of set isn't *part* of a tournament, but you'll often see them happening in the venue. This is traditionally the kind of set you'll play if you've challenged another player and money is on the line.
+ It's as simple as it sounds: The players repeatedly play games until one of them has won five, and that player is declared the winner.
Obviously, Bo3 and Bo5 are very similar, differing only in the number of games played. But Ft5 is clearly different... right? Not really! No matter how a Bo3 set goes down, the winner will have won exactly two games. The winner of a Bo5 set will have won exactly 3 games. Why not call them Ft2, or Ft3? The same logic, applied in reverse, will show that Ft5 is exactly the same as Bo9.
The objective of this challenge is to determine the synonym of a set format.
# Specification
Your program or function will take a single string from [input](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). The first two characters will be `Bo` or `Ft`, and they will be followed by a number. The program/function will [output](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) a string with the opposite prefix and a number such that the input and output strings mean the same thing.
Any string beginning with `Bo` will end in an odd number.
You may assume that the number in the input string will never be greater than 200. You may also assume that you will never receive input for which the correct output would include a number greater than 200. Likewise, the input and correct output numbers will always be greater than 0.
# Examples
```
Bo3 -> Ft2
Ft2 -> Bo3
Bo5 -> Ft3
Ft3 -> Bo5
Bo9 -> Ft5
Ft5 -> Bo9
Bo51 -> Ft26
Ft26 -> Bo51
Bo199 -> Ft100
Ft100 -> Bo199
```
[Answer]
# Python 2, 59
```
lambda s:'FBto'[s>'C'::2]+`eval(s[2:]+'/*22+-11'[s>'C'::2])`
```
In short challenges where functions are allowed, the brevity of `lambda` usually wins out even when the code must repeat itself due to the inability to assign variables.
We check which case we're in with string comparison `s>'C'`. Then, get the right prefix with the list slicing trick `'FBto'[s>'C'::2]`.
To get the number, we must evaluate the characters beyond the second and do either `*2+1` or `/2-1` to it. We do this by tacking on either of those two expressions as strings, again chosen by list slicing, evaluating the result, and turning that number into a string.
**Edit:** Saved one char (59):
```
lambda s:eval("''FBto''++``%%ss/*22+-11``"[s>'C'::2]%s[2:])
```
Don't even ask...
[Answer]
# Pyth, 23 bytes
```
@,/hKsttz2tyKCp-"BoFt"z
```
[Test suite.](https://pyth.herokuapp.com/?code=%40%2C%2FhKsttz2tyKCp-%22BoFt%22z&input=Bo3%0AFt2%0ABo5%0AFt3%0ABo9%0AFt5%0ABo51%0AFt26%0ABo199%0AFt100&test_suite=1&test_suite_input=Bo3%0AFt2%0ABo5%0AFt3%0ABo9%0AFt5%0ABo51%0AFt26%0ABo199%0AFt100&debug=0)
How it works:
First, to find the `Bo` or `Ft`, the program filters out the characters in the input from `BoFt`, with `-"BoFt"z`.
This is immediately printed with `p`. `p` also returns its input. That string is converted to a number interpreting the bytes as base 256. The result is 17007 if the string was `Bo`, and is 18036 if the string was `Ft`.
Next, it calculates both possible results, `num * 2 - 1` and `(num + 1)/2` and puts this in a 2 entry list. Then, the program indexes into that list with the above number, 17007 or 18036. Due to Pyth's modular indexing, this selects the proper number. The result is then printed automatically.
Since `p` prints with no trailing newline, but the implicit printing does have the trailing newline, the two successive prints come out in exactly the right format.
[Answer]
# C++11 Template Metaprogramming, 305 bytes
Edit: Got another 100 bytes off
Do I get any kind of handicap for my choice of language? :p
```
#define C wchar_t
#define T };template<C p
#define L C...l>struct
#define X l...>
C a{T,L I{T,C c,L I<p,c,X:I<10*p+c-'0',X{T>struct I<p>{enum E{v=p};T,L S{T,C c,C d,L G:G<p/10,c,d,p%10+'0',X{T,L G<0,p,X{typedef S<p,X t;T,L F{T,L F<p,'o',X:G<(I<0,X::v+1)/2,'F','t'>{T,L F<p,'t',X:G<I<0,X::v*2-1,'B','o'>{};
```
Examples:
```
#include <type_traits>
static_assert(I<0,'5'>::v == 5, "fail");
static_assert(I<0,'1','0','5'>::v == 105, "fail");
static_assert(I<0,'5','1'>::v == 51, "fail");
static_assert(std::is_same<typename G<5,'B','o'>::t, S<'B','o','5'>>::value, "fail");
static_assert(std::is_same<typename G<51,'F','t'>::t, S<'F','t','5','1'>>::value, "fail");
static_assert(std::is_same<typename F<'B','o','3'>::t, S<'F','t','2'>>::value, "fail");
static_assert(std::is_same<typename F<'F','t','2'>::t, S<'B','o','3'>>::value, "fail");
static_assert(std::is_same<typename F<'B','o','5'>::t, S<'F','t','3'>>::value, "fail");
static_assert(std::is_same<typename F<'F','t','3'>::t, S<'B','o','5'>>::value, "fail");
static_assert(std::is_same<typename F<'B','o','7'>::t, S<'F','t','4'>>::value, "fail");
static_assert(std::is_same<typename F<'F','t','4'>::t, S<'B','o','7'>>::value, "fail");
static_assert(std::is_same<typename F<'B','o','1','1'>::t, S<'F','t','6'>>::value, "fail");
static_assert(std::is_same<typename F<'F','t','6'>::t, S<'B','o','1','1'>>::value, "fail");
static_assert(std::is_same<typename F<'B','o','1','0','5'>::t, S<'F','t','5','3'>>::value, "fail");
static_assert(std::is_same<typename F<'F','t','5','3'>::t, S<'B','o','1','0','5'>>::value, "fail");
static_assert(std::is_same<typename F<'B','o','1','9','5'>::t, S<'F','t','9','8'>>::value, "fail");
static_assert(std::is_same<typename F<'F','t','9','8'>::t, S<'B','o','1','9','5'>>::value, "fail");
int main() {}
```
[Answer]
# CJam, 29 bytes
```
l('B=\1>i"Ft"1$)2/+"Bo"@2*(+?
```
[Try it online](http://cjam.aditsu.net/#code=l('B%3D%5C1%3Ei%22Ft%221%24)2%2F%2B%22Bo%22%402*(%2B%3F&input=Ft100)
Nothing very elaborate here. Calculating the two possible results, and picking one of the two based on the first letter in the input. Will update if I come up with something better.
Explanation:
```
l Get input.
( Pop off first character.
'B= Compare with 'B.
\1> Get rest of input to top of stack, and slice off first character.
i Convert to integer.
"Ft" String part of first possible output.
1$ Copy input value to top.
)2/ Increment, and divide by 2.
+ Concatenate with string part.
"Bo" String part of second possible output.
@ Move input value to top.
2*( Multiply by 2, and decrement.
+ Concatenate with string part.
? Ternary to pick one of the two constructed outputs, based on comparison
of first input character with 'B.
```
[Answer]
# CJam, 27 bytes
```
4 27]r.^(_o'B=\(oi_2*(\)2/?
```
This makes use of the fact that `'B' ^ 'F' == 4` and `'o' ^ 't' == 27`.
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=4%2027%5Dr.%5E(_o'B%3D%5C(oi_2*(%5C)2%2F%3F&input=Bo3).
[Answer]
# Javascript (ES6), ~~50~~ 47 chars
Very simple solution: (Thanks to undergroundmonorail for removing one byte!)
```
x=>(y=x.slice(2),x<'C'?'Ft'+-~y/2:'Bo'+(y*2-1))
```
Ungolfed:
```
function(x){
y = x.slice(2); // everything after the 'Ft' or 'Bo'
return x<'C' ? 'Ft'+Math.ceil(y/2) : 'Bo'+(y*2-1)
}
```
For once my answer was only ~2x the length of the best Pyth answer!
[Answer]
# Haskell, 69 bytes
```
f('B':_:x)="Ft"++show(div(read x)2+1)
f(_:_:x)="Bo"++show(2*read x-1)
```
Reasonably straight-forward.
[Answer]
# Pyth - 31 bytes
Pretty simple, uses zip and modular indexing to get the switch. The actual calculation is really easy.
```
s@C,Jc"FtBo"2,h/Ksttz2tyKhxJ<z2
```
[Test suite](http://pyth.herokuapp.com/?code=s%40C%2CJc%22FtBo%222%2Ch%2FKsttz2tyKhxJ%3Cz2&input=Ft2&test_suite=1&test_suite_input=Bo3%0AFt2%0ABo5%0AFt3%0ABo9%0AFt5%0ABo51%0AFt26%0ABo199%0AFt100&debug=1).
[Answer]
# Julia, 63 bytes
```
x->(y=int(x[3:end]);join([x<"C"?"Ft":"Bo",x<"C"?(y+1)÷2:2y-1]))
```
Ungolfed:
```
function f(x::String)
# Extract the number at the end
y = int(x[3:end])
# If x is lexographically less than "C", we have
# "best of," so we need "first to." Otherwise we
# need "best of."
if x < "C"
join(["Ft", (y+1)÷2])
else
join(["Bo", 2y-1])
end
end
```
[Answer]
# Matlab, 95 bytes
```
function f(s)
t='Bo';a=2;b=-1;if s(1)<70
t='Ft';a=.5;b=a;end
[t num2str(str2num(s(3:end))*a+b)]
```
Examples:
```
>> f('Ft5')
ans =
Bo9
>> f('Bo51')
ans =
Ft26
```
[Answer]
# Powershell, 111
The wordiness of PowerShell and required parentheses are its downfall again. Even golfing the `.Substring(0,2)` to `[0..1]-join''` only saves 2 bytes each, and another couple bytes saved with an implied `Else` thanks to the `exit` command. Oh well. Good refresher on separating strings.
### Code:
```
$b=($a=$args[0])[0..1]-join'';$c=+($a[2..($a.Length-1)]-join'');if($b-eq"Bo"){"Ft"+($c+1)/2;exit};"Bo"+(2*$c-1)
```
### Usage:
```
PS C:\Scripts\Golfing> .\ssb_tourney.ps1 Bo199
Ft100
```
### Explanation
```
$b=($a=$args[0])[0..1]-join'' # Take in the command-line argument as $a, recast as
# array, suck out the first two characters, save as $b
$c=+($a[2..($a.Length-1)]-join'') # Do a similar trick with the right-hand side of $a,
# re-cast it as an integer with the +
if($b-eq"Bo"){ # If the first letters are "Bo"
"Ft"+($c+1)/2 # Implied write of the answer
exit
}
"Bo"+(2*$c-1) # Implied write of the other answer, only reached if
# the input is "Ft", else we would have hit the exit
```
[Answer]
# Perl 5, 38 bytes (37 + 1 for `-p`)
```
$_=/Bo/?Ft.(.5+$'/2):Bo.(2*s/Ft//r-1)
```
**Usage**: save as 54768.pl and run as:
```
perl -p 54768.pl <<< 'Bo3'
# Ft2
```
or interactively:
```
perl -p 54768.pl
Bo199
# Ft100
```
[Answer]
# FSharp - 153 143 bytes
```
let t(s:string)=
let c=s.[2..]|>Seq.map string|>Seq.reduce(+)|>float
if s.[0]='B'then sprintf"Ft%.0f"(ceil(c/2.)) else sprintf"Bo%.0f"(c*2.-1.)
```
## Updates
1. Knocked a few bytes off by switching from pattern matching to a simple `if ... then ...`
[Answer]
# Ruby, 82 Bytes
```
x=$*[0]
y=x.match(/..(\d*)/)[1].to_i
x=~/Bo/?(puts"Ft#{y/2+1}"):(puts"Bo#{y*2-1}")
```
Called with an argument to knock off a few bytes.
First post, suggestions welcome. :)
**EDIT:** Got rid of 12 bytes by changing up my math. Since the Bo numbers are odd they will always have a decimal after dividing by 2, meaning I can just truncate and add 1 instead of using `ceil` to round up.
[Answer]
# PHP, 85 79 75 Bytes
```
<?php
$f=$argv[1];$s=substr($f,2);echo strpos($f,Bo)===0?Ft.($s+1)/2:Bo.($s*2-1);
```
**Usage:**
Call the script with an argument: `php -d error_reporting=0 script.php Bo5`
[Answer]
Not ridiculously short like the others, but that's my first post:
# JS, 143 bytes
```
f=prompt("","");n=parseInt(f.match(/\d{1,}/));s=0;r=0;if(f.match(/B/)){r=(n+1)/2;s="Ft"+r;}if(f.match(/F/)){r=n*2-1;s="Bo"+r;}alert(f+" : "+s);
```
# Ungolfed Version:
```
var f = prompt("", "");
var n = parseInt(f.match(/\d{1,}/));
var s = 0;
var r = 0;
if (f.match(/B/)) {
r = (n + 1)/ 2;
s = "Ft"+r;
}
if (f.match(/F/)) {
r = n * 2 - 1;
s = "Bo"+r;
}
alert(f+" : "+s);
```
[Answer]
# R, 144 bytes
New to code-golfing, R, and this site. So here goes:
```
a=function(){n=readline();z="Bo";p=(as.numeric(gsub("[^0-9]","",n)));if(grepl(z,n)==TRUE){x="Ft";b=(p+1)/2}else{x="Bo";b=p*2-1};cat(x);cat(b)}
```
[Answer]
# C#, 110 bytes
```
string f(string s){var b=s[0]=='B';var o=s.Remove(0,2);int i=int.Parse(o)/2;return b?"Ft"+(i+1):"Bo"+(4*i-1);}
```
]
|
[Question]
[
# Introduction
I want to find the substring with the most `1`'s in a sequence of `0`'s and `1`'s.
# Input
Your program has two **inputs**, the sequence and the substring length.
The **sequence** is any number of `0`'s and `1`'s:
```
01001010101101111011101001010100010101101010101010101101101010010110110110
```
The **substring length** is any positive non-zero integer:
```
5
```
# Output
Your program should output the starting index of the first substring of the given length that contains the most `1`'s. With the above input, the output is:
```
10
```
The first character in the string starts at an index of `0`.
# Scoring
Shortest code wins!
# Rules
* Your program must always output the correct index for any valid inputs.
* You can pick your input/output method from any answer with positive score on the [default options](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). Please specify the method you pick in your answer.
[Answer]
# Dyalog APL, 11
```
(-∘1+⍳⌈/)+/
```
[Try it here.](http://tryapl.org/) Usage:
```
f ← (-∘1+⍳⌈/)+/
4 f 0 1 1 0 1 1 1 0 0 0 0 1 1
1
```
### Explanation
This is a dyadic (meaning binary) function that takes the substring length from the left, and the sequence from the right. Its structure is the following:
```
┌───┴────┐
┌─┴──┐ /
∘ ┌─┼─┐ ┌─┘
┌┴┐ + ⍳ / +
- 1 ┌─┘
⌈
```
Explanation by explosion:
```
(-∘1+⍳⌈/)+/
( )+/ ⍝ Take sums of substrings of given length, and feed to function in parentheses
+ ⌈/ ⍝ The array of sums itself, and its maximum
⍳ ⍝ First index of right argument in left
-∘1 ⍝ Subtract 1 (APL arrays are 1-indexed)
```
As an example, let's take `4` and `0 1 1 0 1 1 1 0` as inputs. First we apply the function `+/` to them and get `2 3 3 3 3`. Then, `+` and `⌈/` applied to this array give itself and `3`, and `2 3 3 3 3 ⍳ 3` evaluates to `2`, since `3` first occurs as the second element. We subtract `1` and get `1` as the final result.
[Answer]
# Ruby, 42
```
f=->s,n{(0..s.size).max_by{|i|s[i,n].sum}}
```
Takes input by calling it, e.g.
`f['01001010101101111011101001010100010101101010101010101101101010010110110110',5]`
This compares substrings using their total ASCII value and returns the index of the maximum. I'm not sure if `max_by` is required by the Ruby spec to be stable but it appears to be in the C implementation.
[Answer]
# Python 2, 56
```
lambda s,l:max(range(len(s)),key=lambda i:sum(s[i:i+l]))
```
Accepts an array of integers, then the length.
[Answer]
## Batch - 222
Batch is obviously the perfect language for this kind of operation.
```
@echo off&setLocal enableDelayedExpansion&set s=%1&set l=-%2
:c
if defined s set/Al+=1&set "s=%s:~1%"&goto c
set s=%1&set x=0&for /l %%a in (0,1,%l%)do set c=!s:~%%a,%2!&set c=!c:0=!&if !c! GTR !x! set x=!c!&set y=%%a
echo !y!
```
**Un-golfed / dissected:**
Initial setup. The variable `s` is the input string, and `l` will be the length of the input string, minus the sub-string length (initialized at negative `%2` where `%2` is the given sub-string length).
```
@echo off
setLocal enableDelayedExpansion
set s=%1
set l=-%2
```
Get the length of the input as `l`, using a pure Batch string length solution - this mangles the variable `s` containing the input string, so we then set it again.
```
:c
if defined s (
set /A l += 1
set "s=%s:~1%"
goto c
)
set s=%1
```
The value of `x` is used to check which sub-string had the greatest number of 1's. Start a loop from 0 to the length of the string, minus the sub-string length (variable `l`). Get the sub-string starting from the current point in the loop (`%%a`), `c` is set as the input string starting at `%%a`, and taking `%2` (the given sub-string length) characters. Any `0`s are removed from `c`, then the value of `c` is compared to `x` - i.e. `111` is a greater number than `11` so we can just use the 'string' to do a greater than comparison. `y` is then set to current location in the string - which is finally outputted.
```
set x=0
for /l %%a in (0, 1, %l%) do (
set c=!s:~%%a,%2!
set c=!c:0=!
if !c! GTR !x! (
set x=!c!
set y=%%a
)
)
echo !y!
```
Using OPs example -
```
h:\>sub1.bat 01001010101101111011101001010100010101101010101010101101101010010110110110 5
10
```
[Answer]
# C# (Regex), 196
```
class Test{static void Main(string[]a){System.Console.Write(System.Text.RegularExpressions.Regex.Match(a[1],"(?=((?<o>1)|0){"+a[0]+"})(?!.+(?=[10]{"+a[0]+"})(?!((?<-o>1)|0){"+a[0]+"}))").Index);}}
```
The actual regex is not that long, but all the fluffs needed for a C# program to compile double the size of the code.
The actual regex, setting the length to 5:
```
(?=((?<o>1)|0){5})(?!.+(?=[10]{5})(?!((?<-o>1)|0){5}))
```
* `(?=((?<o>1)|0){5})`: Look-ahead to read 5 characters without consuming, and push all `1`'s into "stack" `o`.
* `(?=[10]{5})(?!((?<-o>1)|0){5})`: At a position which has 5 characters ahead, there is not enough item in "stack" `o` to pop out, i.e. the substring has strictly more `1` than what we have in the current position.
* `(?!.+(?=[10]{5})(?!((?<-o>1)|0){5}))`: A position as described above can't be found for the rest of the string, i.e. all position has less than or equal number of `1`'s.
Taking the first result gives the answer, since all substrings in front of it has some substring ahead with more `1`'s, and we have check that any index larger than the current index has less than or equal number of `1`'s.
(And I learn something nice: the "stack" is restored on backtracking).
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 12
```
Mho/<>GNHZUG
```
This defines a function `g`, which requires a list of numbers and a number as input.
E.g.
```
Mho/<>GNHZUGg[0 1 0 0 1 0 1 0 1 0 1 1 0 1 1 1 1 0 1 1 1 0 1 0 0 1 0 1 0 1 0 0 0 1 0 1 0 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 0 1 1 0 1 0 1 0 0 1 0 1 1 0 1 1 0 1 1 0)5
```
You can test it here: [Pyth Compiler/Executor](https://pyth.herokuapp.com/)
### Explanation:
```
Mho/<>GNHZUG
M defines a function g(G,H), G is the sequence, H the sequence length
o UG orders the numbers between 0 and len(G)-1 according to the following key
<>GNH take the subsequence G[N:N+5]
/ Z count the zeros in this subsequence (this is the key)
h return the first value of the sorted list (minimum)
```
### Alternative:
```
Mho_s<>GNHUG
```
[Answer]
# J, 15 14 chars
```
([:(i.>./)+/\)
5 ([:(i.>./)+/\) 0 1 0 0 1 0 1 0 1 0 1 1 0 1 1 1 1 0 1 1 1 0 1 0 0 1 0 1 0 1 0 0 0 1 0 1 0 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 0 1 1 0 1 0 1 0 0 1 0 1 1 0 1 1 0 1 1 0
10
```
[Answer]
# Matlab (42)
Let `s` denote the string and `n` the substring length. The result is `r`.
Compute convolution of `s` with a sequence of `n` ones, then find the maximum. Convolution is done easily with `conv`, and the `max` function returns the position of the *first* maximum. It's necessary to subtract `1` to the resulting index, because Matlab indexing starts at `1`, not `0`.
```
[~, r] = max(conv(s, ones(1,n), 'valid'));
r = r-1;
```
Golfed:
```
[~,r]=max(conv(s,ones(1,n),'valid'));r=r-1
```
[Answer]
# Haskell, 64 62 Bytes
```
n#l=0-(snd$maximum[(sum$take n$drop x l,-x)|x<-[0..length l]])
```
Usage:
```
5#[0,1,0,0,1,0,1,0,1,0,1,1,0,1,1,1,1,0,1,1,1,0,1,0,0,1,0,1,0,1,0,0,0,1,0,1,0,1,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,0,1,1,0,1,0,1,0,0,1,0,1,1,0,1,1,0,1,1,0]
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 5 [bytes](https://github.com/abrudz/SBCS)
```
⊃∘⍒+/
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/x91NT/qmPGod5K2/v80oMij3j6g0KH1xo/aJgJVBQc5A8kQD8/g/yYKaQoGCoZACCFBNAQC2QA "APL (Dyalog Unicode) – Try It Online")
`⊃∘⍒` is an idiom for "index of maximum", or "argmax", and `n +/ bitarray` computes the sums over all `n`-length segments. Uses the system setting `⎕IO←0` to make the output 0-based.
[Answer]
# JavaScript (ES6) 73
A function returning the requested value.
The for loop scans the input string keeping a running total, saving the position of the max value.
```
F=(a,n)=>(x=>{for(r=t=i=x;a[i];t>x&&(x=t,r=i-n))t+=a[i]-~~a[i++-n]})(0)|r
```
**Ungolfed**
```
F=(a, n) => {
for(x = r = t = i = 0; a[i]; i++)
t += a[i] - ~~a[i-n], // ~~ convert undefined values (at negative index) to 0
t > x && (x=t, r=i-n+1);
return r;
}
```
**Test** In FireFox/FireBug console
```
F("01001010101101111011101001010100010101101010101010101101101010010110110110",5)
```
*Output* `10`
[Answer]
# PHP (96)
`for($a=$b=$c=0;(($d=@substr_count($s,1,$a,$n))>$c&&($b=$a)&&($c=$d))||$a++<strlen($s););echo $b;`
<http://3v4l.org/J4vqa>
variables `$s` and `$n` should be defined on the command line to the search string and substring length, respectively.
This would also work in any C-like language with appropriate functions for `substr_count()` and `strlen()`.
[Answer]
# Mathematica, ~~38~~ 36
```
f=#-1&@@Ordering[-MovingAverage@##]&
```
Example:
```
f[{0,1,0,0,1,0,1,0,1,0,1,1,0,1,1,1,1,0,1,1,1,0,1,0,0,1,0,1,0,1,0,0,0,1,0,1,0,1,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,0,1,1,0,1,0,1,0,0,1,0,1,1,0,1,1,0,1,1,0},5]
```
Output:
>
> 10
>
>
>
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~11~~ 6 bytes
```
*>+/':
```
[Try it online!](https://ngn.codeberg.page/k#eJytUG1qwzAM/e9TiDJouy1f0EKJYacojFEKdVMnNk3kzFa2dGM7++y0aXuAIWFbT7Ke9Mr88eUpmeaMrfPvh83p1+YlxNDznTny2a4UuuY9P3E73/6w9Wa24Clk3s5nuM/m33OebUPJkk/SLPU+WPDzcQPTa+rersgtyNKJ75puGUuYImpdniSFOcjK1GXsSBRH2RdKYCXjwjTJeycdaYMuWSxW2SopNR4iUjJy3d6R1VhFn5rUADXGUZS5SGMkIif9VyykV0FJGCPQDgSeALtmLy2YEtJpQA6QTZ1X7P+2vPCOU0ItsSI18rfGadIfEtBg9CWtAY0kK2n9DEvG3kxnobWmsqIBp0xXH8B01HYEFLqSsBSaejFkH7YIaKmtozvGC1x5GhzpSQmCwiAJjW5IB9HC8jG86qFAgtgbP5lGT/c8ABdqHRTym/0BZj2y3w==)
Uses the "argmax" trick from [Bubbler's answer](https://codegolf.stackexchange.com/a/216812/98547).
* `+/':` do a window-reduce (with the first implicit arg being the window length, and the second the sequence)
* `*>` argmax/index of first maximum
[Answer]
### C# (Linq), 148 bytes
```
using System.Linq;class C{int F(string s,int l){return s.IndexOf(s.Skip(l-1).Select((c,i)=>s.Substring(i,l)).OrderBy(p=>-p.Sum(c=>c)).First());}}
```
Formatted:
```
using System.Linq;
class C
{
int F(string s, int l)
{
return s.IndexOf(
s
.Skip(l - 1)
.Select((c, i) => s.Substring(i, l))
.OrderBy(p => -p.Sum(c => c))
.First()
);
}
}
```
Takes input as method params.
What it does:
```
string result = s // string is also char collection
.Skip(l - 1) // make it collection shorter by l-1
.Select((c, i) => s.Substring(i, l)) // so we can iterate, and select all substrings
.OrderBy(p => -p.Sum(c => c)) // order substrings descending by sum of characters
.First() // take first (most ones)
return s.IndexOf(result); // find index of result string
```
[Answer]
# Scala - 70 Bytes
```
readLine.sliding(readInt).zipWithIndex.maxBy(x=>x._1.count(_=='1'))._2
```
But with function names as long as *zipWithIndex* I guess Scala is not the best choice for code golf.
[Answer]
### C, ~~245~~ 185
```
#include <stdio.h>
main(int argc,char **argv){char *p,*q;int i,s,m=0;for(p=argv[1];*p;p++){for(s=0,q=p;q-p<atoi(argv[2])&&*q;q++)s+=*q-'0';if(s>m){m=s;i=p-argv[1];}}printf("%d\n", i);}
```
**Formatted:**
```
#include <stdio.h>
main(int argc, char **argv) {
char *p, *q;
int i, s, m = 0;
for (p = argv[1]; *p; p++) {
for (s = 0, q = p; q - p < atoi(argv[2]) && *q; q++)
s += *q - '0';
if (s > m) {
m = s;
i = p - argv[1];
}
}
printf("%d\n", i);
}
```
**Usage:**
```
$ ./m1s 01001010101101111011101001010100010101101010101010101101101010010110110110 5
10
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
ṡ§MḢ’
```
[Try it online!](https://tio.run/##y0rNyan8///hzoWHlvs@3LHoUcPM////G@gY6hjoQEgEhpHILGwqDbDowoUx1WCTAZL/TQE "Jelly – Try It Online")
## How it works
```
ṡ§MḢ’ - Main link. Takes the sequence s on the left and the length n on the right
ṡ - Overlapping slices of s of length n
§ - Sum of each slice
M - Indices of the maximal element
Ḣ - First (smallest) one
’ - Decrement as Jelly uses 1 indexing
```
[Answer]
# [Perl 5](https://www.perl.org/) `-pl`, 50 bytes
```
$i++,$;[y/1//]||=$i-1for<>=~/(?=(.{$_}))/g;$_=pop@
```
[Try it online!](https://tio.run/##K0gtyjH9/18lU1tbR8U6ulLfUF8/tqbGViVT1zAtv8jGzrZOX8PeVkOvWiW@VlNTP91aJd62IL/A4f9/Uy4DQwMgAkMQghAIQQO4FDKEiyA4hgb/8gtKMvPziv/r@prqASX@6xbkAAA "Perl 5 – Try It Online")
Input is on two lines with the length first and then the string.
[Answer]
# CJam, ~~25~~ 21 bytes
```
q~_,,{1$>2$<:+~}$(]W=
```
[Test it here.](http://cjam.aditsu.net/)
Takes input as an integer for the substring length, and an array of zeroes and ones as the sequence:
```
5
[0 1 0 0 1 0 1 0 1 0 1 1 0 1 1 1 1 0 1 1 1 0 1 0 0 1 0 1 0 1 0 0 0 1 0 1 0 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 0 1 1 0 1 0 1 0 0 1 0 1 1 0 1 1 0 1 1 0]
```
## Explanation
```
q~_,,{1$>2$<:+~}$(p];
q~ "Read and evaluate the input.";
_, "Duplicate the sequence and get its length N.";
, "Get an array [0 1 ... N-1].";
{ }$ "Sort this array stably by the result of the given block.";
1$ "Copy the sequence.";
> "Slice off the first i bits.";
2$ "Copy the substring length.";
< "Truncate the sequence.";
:+ "Get the sum to find the number of 1s.":
~ "Bitwise complement in order to sort from highest to lowest.";
( "Shift off the first index from the sorted list.";
] "Wrap the entire stack in an array.";
W= "Extract the last element (the result), discarding the rest.";
```
The result is printed automatically at the end of the program.
Note that I'm also considering slices that start closer to the end than the desired substring length, but that's okay, because they are substrings of the last valid substring and will therefore never have more `1`s than that last valid substring.
[Answer]
## Java 329 bytes
was going to implent a .matches(regex), but it would have been near identical to the python solutions above, so i tried a sliding window instead. new here, so if anyone has any pointers be glad to hear them.
```
public class ssMostOnes{
public static void main(String[] a){
int b=0,w=0;
for(int i=0;i<a[0].length()-Integer.valueOf(a[1]);i++){
int c=a[0].substring(i,i+Integer.valueOf(a[1])).length() - a[0].substring(i,i+Integer.valueOf(a[1])).replace("1","").length();
if(c>w){w=c;b=i;}
}
System.out.println(b);
}
```
}
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 12 bytes
```
J'0;;qL[>mss
```
[Try it online!](https://tio.run/##SyotykktLixN/f/fS93A2rrQJ9out7j4/38DQwMgAkMQghAIQQO4FDKEiyA4hgYA "Burlesque – Try It Online")
```
J # Duplicate input
'0;; # Split by 0s
qL[>m # Maximum by length
ss # Find index of substring in original
```
]
|
[Question]
[
# Challenge description
Given a list / array of items, display all groups of consecutive repeating items.
# Input / output description
Your input is a list / array of items (you can assume all of them are of the same type). You don't need to support every type your language has, but is has to support at least one (preferably `int`, but types like `boolean`, although not very interesting, are also fine). Sample outputs:
```
[4, 4, 2, 2, 9, 9] -> [[4, 4], [2, 2], [9, 9]]
[1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4] -> [[1, 1, 1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]
[1, 1, 1, 3, 3, 1, 1, 2, 2, 2, 1, 1, 3] -> [[1, 1, 1], [3, 3], [1, 1], [2, 2, 2], [1, 1], [3]]
[9, 7, 8, 6, 5] -> [[9], [7], [8], [6], [5]]
[5, 5, 5] -> [[5, 5, 5]]
['A', 'B', 'B', 'B', 'C', 'D', 'X', 'Y', 'Y', 'Z'] -> [['A'], ['B', 'B', 'B'], ['C'], ['D'], ['X'], ['Y', 'Y'], ['Z']]
[True, True, True, False, False, True, False, False, True, True, True] -> [[True, True, True], [False, False], [True], [False, False], [True, True, True]]
[0] -> [[0]]
```
As for empty lists, output is undefined - it can be nothing, an empty list, or an exception - whatever suits your golfing purposes the best. You don't have to create a separate list of lists either, so this is a perfectly valid output as well:
```
[1, 1, 1, 2, 2, 3, 3, 3, 4, 9] ->
1 1 1
2 2
3 3 3
4
9
```
The important thing is to keep the groups separated in some way. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins
[Answer]
## Mathematica, 5 bytes
```
Split
```
... there's a built-in for that.
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
I0;œṗ
```
Works for all numeric types. [Try it online!](http://jelly.tryitonline.net/#code=STA7xZPhuZc&input=&args=WzQsIDQsIDIsIDIsIDksIDld) or [verify all numeric test cases](http://jelly.tryitonline.net/#code=STA7xZPhuZcKw4figqzhuYTigqzhuZvigJw&input=&args=WzQsIDQsIDIsIDIsIDksIDldLCBbMSwgMSwgMSwgMiwgMiwgMywgMywgMywgNCwgNCwgNCwgNF0sIFsxLCAxLCAxLCAzLCAzLCAxLCAxLCAyLCAyLCAyLCAxLCAxLCAzXSwgWzksIDcsIDgsIDYsIDVdLCBbNSwgNSwgNV0sIFsxLCAxLCAxLCAwLCAwLCAxLCAwLCAwLCAxLCAxLCAxXSwgWzBd).
### How it works
```
I0;œṗ Main link. Argument: A (array)
I Increments; compute the differences of consecutive elements.
0; Prepend a zero.
œṗ Partition; split A at truthy values in the result to the left.
```
[Answer]
## [Retina](https://github.com/m-ender/retina), ~~15~~ 8 bytes
*Thanks to Lynn for suggesting a simpler I/O format.*
```
!`(.)\1*
```
Treats the input as a list of characters (and uses linefeeds to separate groups).
[Try it online!](http://retina.tryitonline.net/#code=IWAoXGQrKSggXDFcYikq&input=MSAxIDEgMiAyIDMgMyAzIDQgOQ)
This simply works by matching groups and printing them all (which uses linefeed separation automatically).
[Answer]
## JavaScript (ES6), ~~39~~ 37 bytes
```
f=
s=>s.replace(/(\w+) (?!\1\b)/g,`$1
`)
;
```
```
<input oninput=o.textContent=f(this.value);><pre id=o>
```
Works on any space-separated word-like tokens. Saved 2 bytes thanks to @MartinEnder♦. Best I could do for array input and return is 68:
```
a=>a.reduce((l,r)=>(l==r?c.push(r):b.push(c=[r]),r),b=[c=[a[0]]])&&b
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 9 bytes
```
Y'v"@Z}Y"
Y' % Take input. Run-length encoding. Gives two row arrays: values and run lengths
v % Concatenate vertically
" % For each column
@Z} % Push column and split into its two elements
Y" % Run-length decoding
% End for. Implicitly display
```
Input is a row array of **numbers**, with spaces or commas as separators.
[Try it online!](http://matl.tryitonline.net/#code=WSd2IkBafVki&input=WzEgMSAyIDEgMiAyXQ) Test with [non-integer numbers](http://matl.tryitonline.net/#code=WSd2IkBafVki&input=WzEuMSAyLjIgMS4xIDEuMSAtMS4xIDIuMl0).
---
# MATL, 11 bytes
```
lidgvYsG7XQ
```
Input is a column array of either **numbers** or **characters**, using `;` as separator.
[Try it online!](http://matl.tryitonline.net/#code=bGlkZ3ZZc0c3WFE&input=WzE7IDE7IDI7IDE7IDI7IDJd) Test with [arbitrary numbers](http://matl.tryitonline.net/#code=bGlkZ3ZZc0c3WFE&input=WzEuMTsgMi4yOyAxLjE7IDEuMTsgLTEuMTsgMi4yXQ). Test with [characters](http://matl.tryitonline.net/#code=bGlkZ3ZZc0c3WFE&input=WydhJzsnYic7J2EnOydhJzsnYic7J2MnOydjJzsnYidd).
```
l % Push 1
i % Take input, say [4;4;2;2;9;9]
d % Consecutive differences of input: [0;-2;0;7;0]
g % Convert to logical: gives 1 if consecutive entries were different: [0;1;0;1;0]
v % Concatenate vertically with the initial 1: [1;0;1;0;1;0]
Ys % Cumulative sum. Each value is a group label: [1;1;2;2;3;3]
G % Push input again
7XQ % Split into horizontal arrays as indicated by group labels: {[4 4];[2 2];[9 9]}
% Implicitly display
```
[Answer]
# [J](http://jsoftware.com), 13 bytes
```
<;.1~1,2~:/\]
```
Since J does not support ragged arrays, each run of equal elements is boxed. The input is an array of values and the output is array of boxed arrays.
## Usage
```
f =: <;.1~1,2~:/\]
f 4 4 2 2 9 9
┌───┬───┬───┐
│4 4│2 2│9 9│
└───┴───┴───┘
f 1 1 1 3 3 1 1 2 2 2 1 1 3
┌─────┬───┬───┬─────┬───┬─┐
│1 1 1│3 3│1 1│2 2 2│1 1│3│
└─────┴───┴───┴─────┴───┴─┘
f 'ABBBCDXYYZ'
┌─┬───┬─┬─┬─┬──┬─┐
│A│BBB│C│D│X│YY│Z│
└─┴───┴─┴─┴─┴──┴─┘
f 0
┌─┐
│0│
└─┘
```
## Explanation
```
<;.1~1,2~:/\] Input: s
] Identify function to get s
2 The constant 2
\ Operate on each overlapping sublist of size 2
~:/ Are the two values unequal, 1 if true else 0
1, Prepend a 1 to it
<;.1~ Using the list just made, chop s at each index equal to 1 and box it
Return this as the result
```
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 9 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
```
⊢⊂⍨1,2≠/⊢
```
`⊢` the argument
`⊂⍨` partitioned at
`1` at the first element
`,` and then
`2≠/` where subsequent pairs differ
`⊢` in the argument
[Answer]
# gs2, 2 bytes
```
c-
```
[Try it online!](http://gs2.tryitonline.net/#code=Yy0&input=SGVsbG9-d29vb29vcmxkIQ)
`c` is a grouping built-in that does exactly this, so we call it on STDIN (which is a string, i.e., a list of chars) and get a list of strings. Sadly, the result is indistinguishable from the input, so we need to add separators! `-` (join by spaces) does the trick.
An alternative answer is `cα` (2 bytes of CP437), which simply wraps `c` into an anonymous function.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 13 bytes
```
:{s.dl1}fs.c?
```
**Warning:** this is extremely inefficient, and you will understand why in the explanation.
This expects a list (e.g `[1:1:2:2:2]`) as input. The elements inside the list can be pretty much anything.
### Explanation
```
:{ }f Find all ordered subsets of the Input with a unique element in them
s. Output is a subset of the input
dl1 Output minus all duplicates has a length of 1 (i.e. one unique value)
s. Output is an ordered subset of those subsets
c? The concatenation of those subsets is the Input
```
This works only because of the way `s - Subset` unifies: the smallest sets are at the end. Therefore the first thing it finds that concatenates to the Input are the longest runs, e.g. `[[1:1]:[2:2:2]]` and not for example `[[1:1]:[2:2]:[2]]`.
[Answer]
## Python 2, 43 bytes
```
p=-1
for x in input():print"|"[:x^p],x,;p=x
```
Works on lists of booleans. Example:
```
>> [True,True,False,False,False,True,False,True,False]
True True | False False False | True | False | True | False
```
Iterates through the input list, storing the last seen element. A separator bar is printed before each element that is different than the previous, checked as having bitwise xor `^` of 0. Initializing `p=-1` avoids a separator before the first element.
[Answer]
## CJam, 9 bytes
Two solutions:
```
{e`:a:e~}
{e`{(*}%}
```
[Test it here.](http://cjam.aditsu.net/#code=%5B1%201%201%203%203%201%201%202%202%202%201%201%203%5D%0A%0A%7Be%60%3Aa%3Ae~%7D%0A%20%20%20%0A%0A~p)
### Explanation
```
e` e# Run-length encode (gives a list of pairs [run-length value]).
:a e# Wrap each pair in a singleton list.
:e~ e# Run-length decode each list.
```
Or
```
e` e# Run-length encode.
{ e# Map this block over each pair...
( e# Pull out the run length.
* e# Repeat the list containing only the value that many times.
}%
```
[Answer]
## Haskell, 22 bytes
```
import Data.List
group
```
There's a built-in. Works on any type that supports equality.
[Answer]
# MATL, ~~8~~ 7 bytes
Removed 1 byte thanks to @Suever
```
ly&Y'Y{
```
Works with integers/floats/chars/booleans/unicorn points/other imaginary inputs.
For booleans, inputs are `T/F`, outputs are `1/0`.
[Try it online!](http://matl.tryitonline.net/#code=bHkmWSdZew&input=WzEsIDEsIDEsIDMsIDMsIDEsIDEsIDIsIDIsIDIsIDEsIDEsIDNd)
---
**Grouped and Repeated**
```
ly&Y'Y{
l % push 1 onto the stack
y % duplicate the input
&Y' % run-length encoding (secondary output only)
Y{ % break up array into cell array of subarrays
```
[Answer]
# [Zsh](https://www.zsh.org/), 28 bytes
```
>$1;for i {mv * $i&&echo;ls}
```
[Try it online!](https://tio.run/##qyrO@F@cWqJgCIZGQGgMhiYKlv/tVAyt0/KLFDIVqnPLFLQUVDLV1FKTM/Ktc4pr/xflKmj9//8fAA "Zsh – Try It Online")
* `>$1`: create the file named the first argument
* `for i {}`: for each argument:
+ `mv * $i`: attempt to move all files in the current directory to the current item
+ If these are the same (i.e. this item is the same as the last), this will fail with `mv: 'X' and 'X' are the same file`.
+ `&&`: if this doesn't fail (i.e. this item is not the same as the last)
- `echo`: print a blank line to separate the runs
+ `ls`: then list all the files in the current directory. In effect, this just prints `$i`.
[Answer]
# [K (ngn/k)](https://git.sr.ht/%7Engn/k), 12 bytes
```
{(&~~':x)_x}
```
[Try it online!](https://ngn.bitbucket.io/k#eJx9UMFqwzAMvfsrRA/zBh5LUzuJexg0CfuCHZIaM3ZYTzttDApj/fZJlh07lA2JJ1vv6cn4tP++vblc5P5893L+EeLkNGioMSxYj9ctUFBjF0JzZIqaSVJzh0gLLXTQgKGLAcOHzaHv+2Gc5vm4yRYVRkIMIlTlhXgQTivArENaTA/3j+BC2ytwRFANlBduq4CTJ3Yp9ZLRIApLjyimYyEvTVlRLqgX6to3mZV74qpFQvb49lZBp6BR+ElsY4ltCTqChsCQ2KAmy9INCXmQCmS/hoFgJJgI5gWOMjrgGHmvBkNj4DJymbhEg3BGC1z7/PH1pqDEp9f3z1z+7mWMT7lq45ZykO7/9Vez+LQq+lbe/wIvwKsI)
A relatively straightforward "idiom". A (verbose) q version is:
```
{(where differ x)cut x}
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 1 byte
```
g
```
[Try it online](https://tio.run/##yygtzv6f@6ip8X/6////o6NNdEx0jIDQUscyVifaUAcEQXxjMDSBQLgMSAymwggiApSz1DHXsdAx0zEFsk11TMG0QWwsAA "Husk – Try It Online") for all the integer test-cases, or [here](https://tio.run/##yygtzv7/P/3////RSiFFpalKOmiUW2JOMTKNXxiZigUA) for the "True/False" one
From the [Husk Wiki](https://github.com/barbuz/Husk/wiki/Commands):
`g` `group` Group equal adjacent values
---
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
CẊ-Θ:W≠¹L¹
```
[Try it online!](https://tio.run/##yygtzv7/3/nhri7dczOswh91Lji00@fQzv///0cb6oCgERAaQ6GJjkksAA "Husk – Try It Online")
Without `g`...
From the Husk wiki:
```
C Cut off sublists of input, in lengths given by:
Ẋ Map over pairs of adjacent values:
- Subtract first argument from second
(so Ẋ- = differences)
Θ Prepends a falsy value (here = zero) to
: L¹ Append the length of the input to
W≠¹ Indices of input that are not equal to their successor
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 32 bytes
```
s=>s.replace(/(.)(?!\1)/g,'$1 ')
```
[Try it online!](https://tio.run/##fU5da8JAEHz3V2yhcBc440f9bNHSKoW@98E2DRjiKZEjSe9OEYq/3e4mp8ZKC8vs3ezszK6jbWRineS2nmYLeViODmY0Nr6WuYpiyRvc9/jjzWfLa6wEu20B8w5xlhoLWkYLlaQSRvj82iRacnbkmPdQcypVzEvaj/Fl5WtqpV6S@3cNIEnzjb2HXGexNMY3dpGkAvlsY38PkKrt0VorP0s5K5LEbjQmm22kwWLWzje5Sixn9TFdAUB3ZEr6KlvxJZfbSHEbNEPPX2dJOp97KNp7h6AjAKtd1BArhPoYgoIOBQQ0oF6MwlrQElBWuXF3rM6pnIETVj2cmJ4VedW0VFQD2qfRte/RrJrjok4Sssfb@wIGAnoCus5mSNM@wYCgR9AlcRc1Z9nxhwP2xASw50uYEEwJZgTvJ/hgzgHXyPtisSAmZZuWbVY2Z1C80QJj3/RGCqjiS6TMuf3NndGdckVjSnWR/v/xF7t4WtP5NsPwBw "JavaScript (Node.js) – Try It Online")
Support char
[Answer]
## C#, 117 bytes
```
void f(List<String>m){Console.Write(m[0]+String.Join("",m.GetRange(1,m.Count()-1).Select((i,j)=>i==m[j]?i:"\n"+i)));}
```
ungolfed (not really)
```
public static void f(List<String>m)
{
Console.Write(m[0]+String.Join("",m.GetRange(1,m.Count()-1).Select((i,j)=>i==m[j]?i:"\n"+i)));
}
```
[Answer]
# Pyth, ~~9~~ 7 bytes
```
mr9]dr8
```
Credit to @LeakyNun for 2 byte!
Explanation:
```
input
r8 run-length decode
m for each...
]d ...treat each run as standalone encoded form...
r9 ...decode
print
```
---
### Old answer, 12 bytes
```
hf.Am!t{dT./
```
Forgot about run length built-in, but I think this is an okay approach, so I kept it.
Explanation:
```
input
./ all possible partitions
f T filter by...
.A ...whether all groups of integers...
m!t{d ...have length one after deduplication
h get the first element (first one has no adjacent [1,1] and [1])
print
```
[Answer]
# [Pyth](https://esolangs.org/wiki/Pyth), 36 35 bytes
```
VQIqNk=hZ).?=+Y]*]kZ=Z1=kN;t+Y]*]kZ
```
[Test link](http://pyth.herokuapp.com/?code=VQIqNk%3DhZ%29.%3F%3D%2BY]*]kZ%3DZ1%3DkN%3Bt%2BY]*]kZ&input=[1%2C1%2C1%2C2%2C2%2C3%2C3%2C3%2C1]&test_suite=1&test_suite_input=[4%2C+4%2C+2%2C+2%2C+9%2C+9]%0A[1%2C+1%2C+1%2C+2%2C+2%2C+3%2C+3%2C+3%2C+4%2C+4%2C+4%2C+4]%0A[1%2C+1%2C+1%2C+3%2C+3%2C+1%2C+1%2C+2%2C+2%2C+2%2C+1%2C+1%2C+3]%0A[9%2C+7%2C+8%2C+6%2C+5]%0A[5%2C+5%2C+5]%0A[%27A%27%2C+%27B%27%2C+%27B%27%2C+%27B%27%2C+%27C%27%2C+%27D%27%2C+%27X%27%2C+%27Y%27%2C+%27Y%27%2C+%27Z%27]+%0A[0]&debug=0)
Edit: explanation:
```
standard variables: Y=[], Z=0, k='', Q=input
VQ iterate over input
IqNk if the current entity is equal to k:
=hZ) increase Z.
.? else:
]*]kZ list of length Z filled with k
=+Y add it to Y
=Z1 set Z to 1
=kN set k to the current entity
; end loop
]*]kZ list of length Z filled with k
+Y add it to Y
t implicitly print the tail of Y (removing the first element)
```
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~24~~ 22 bytes
2 bytes thanks to Martin Ender.
A [15-byte answer](https://codegolf.stackexchange.com/a/84423/48934) already exists, so this is just another approach which costs more bytes.
```
S-`(?<=(\d+)) (?!\1\b)
```
[Try it online!](http://retina.tryitonline.net/#code=Uy1gKD88PShcZCspKSAoPyFcMVxiKQ&input=MSAxIDEgMiAyIDMgMyAzIDQgOQ)
It splits on spaces whose preceding number differ from the proceeding.
This is a demonstration of lookarounds.
[Answer]
## 05AB1E, 13 bytes
```
¬svyÊi¶}yðJ?y
```
**Explained**
```
¬s # push first element of list to stack and swap with input
v # for each X in input
yÊi¶} # if X is different from last iteration, push a newline
yðJ? # push X followed by a space to stack and join stack to string
y # push X to stack for next iterations comparison
```
Should work for any list.
Tested on int and char.
[Try it online](http://05ab1e.tryitonline.net/#code=wqxzdnnDimnCtn15w7BKP3k&input=WydBJywgJ0InLCAnQicsICdCJywgJ0MnLCAnRCcsICdYJywgJ1knLCAnWScsICdaJ10)
[Answer]
# Swift, 43 bytes
```
var p=0;i.map{print($0==p ?"":",",$0);p=$0}
```
Assumes i to be an array of equatable objects; works for anything from ints to strings to custom objects. Kind of cheeky in that the output contains lots of newlines, but making that prettier would cost bytes.
**Prettier, ungolfed version:**
```
var prev = Int.max // unlikely to be the first element, but not the end of the world if it happens to be.
i.map { n in
print(n == prev ? " " : "\n•", n, terminator: "")
prev = n
}
```
This version prints every group on a new line at the expense of more code.
## Ideas for Improvement
```
i.reduce(0){print($0==$1 ?"":"•",$1);return $1}
```
This version has 47 bytes, but it's a different approach, so maybe there's something to optimize away there? The biggest problem is the return statement.
[Answer]
# C, ~~88~~ 77 bytes
*Moved the* `strmcmp` *inside the* `printf` *saving 11 bytes*
```
f(char**a){*a++;char*x;for(;*a;x=*a++)printf(strcmp(*a,x)?"\n%s ":"%s ",*a);}
```
### Usage:
```
f(char**a){*a++;char*x;for(;*a;x=*a++)printf(strcmp(*a,x)?"\n%s ":"%s ",*a);}
main(c,v)char**v;{f(v);}
```
### Sample Input:
*(command line parameters)*
```
1 1 1 1 2 2 2 2 3 3 3 3 4 5 6 7777
```
### Sample Output:
```
1 1 1 1
2 2 2 2
3 3 3 3
4
5
6
7777
```
**Tested on:**
```
gcc 4.4.7 (Red Hat 4.4.7-16) - OK
gcc 5.3.0 (Cygwin) - Segmetation Fault
gcc 4.8.1 (Windows) - OK
```
I'm trying to fix the 5.3.0 Segmetation Fault.
**88 Version**
```
f(char**a){*a++;char*x;for(;*a;x=*a++)strcmp(*a,x)?printf("\n%s ",*a):printf("%s ",*a);}
```
[Answer]
# Java 134 bytes
```
void a(String[]a){int i=0,l=a.length;for(;i<l-1;i++)System.out.print(a[i]+((a[i].equals(a[i+1]))?" ":"\n"));System.out.print(a[l-1]);}
```
iterates through, and decides whether to separate with a new line or a space.
[Answer]
## [ListSharp](https://github.com/timopomer/ListSharp "ListSharp"), 134 bytes
```
STRG l = READ[<here>+"\\l.txt"]
[FOREACH NUMB IN 1 TO l LENGTH-1 AS i]
{
[IF l[i] ISNOT l[i-1]]
STRG o=o+"\n"
STRG o=o+l[i]
}
SHOW = o
```
ListSharp doesnt support functions so the array is saved in a local file called `l.txt`
[](https://i.stack.imgur.com/0V3No.png)
[Answer]
# **[Ruby](https://en.wikipedia.org/wiki/Ruby_(programming_language)), 24 bytes**
In ruby `Array` instances have built-in method `group_by`
So solution will be:
```
a.group_by{|x| x}.values
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes
```
Œg
```
[Try it online!](https://tio.run/##y0rNyan8///opPT/h9sfNa05Ounhzhn//0eb6CgAkREYWQJRrI5CtKGOAgRBhI1hyASOYgE "Jelly – Try It Online")
Alternatively, a non-builtin approach:
```
Ik
```
[Try it online!](https://tio.run/##y0rNyan8/98z@//h9kdNa45Oerhzxv//0SY6CkBkBEaWQBSroxBtqKMAQRBhYxgygaNYAA "Jelly – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 49 bytes
```
$args|%{,$a*!($i=$_-in$a-or!$a)
$a=$a*$i+,$_}
,$a
```
[Try it online!](https://tio.run/##hVJLT4NAEL7zK6bNVkCXpPbdQxO0TRNPGuuhagzBulUaCnWBqGn57Ti7CwSaVMlkBr7XbMjuwi/Gow/m@xlZwwT2GXH5e3Ro7SlxzxsG8SbEsbyAuFbIG8Q1NeJOkCHeBSVOqqEqSzVt7fkx4zAP@daNrZsgwI89NA3imE1A3jY0ahg9ClgdWWMsk4LExBSomBI3hfqSgipl6BbVK0voc1U1IlcW6bm2nqk01fxOSR3FditQsSbfVEpUOp59SGFEYUChj7htjGUfyj6SfSB7Xxn6qFPS8lXi@pVOQb@ut6loM9GWoj2W7UmXmWgSQTWbIqb5nOVzqYR5gsIwRK4mDzxhFI7G3PWj6vwbrgyx6BRcc8tTFJx9kjyKEUe2jbbk2/hlwgFasNcAH7zI3P1BJfvesVXM3vB6E0dRnEWJHyNwhrfelkJJPN8tpkkUh9vb1w16XmwVJZ5FslqxKEIP/iTlP1Tvu2ltQi8Qv9QEi30KVbH4lK7Mvi@O80@yNKRamv0C "PowerShell – Try It Online")
[Answer]
# [Vyxal](http://lyxal.pythonanywhere.com), 1 byte
```
Ġ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C4%A0&inputs=%5B1%2C%201%2C%201%2C%203%2C%203%2C%201%2C%201%2C%202%2C%202%2C%202%2C%201%2C%201%2C%203%5D&header=&footer=)
Ah yes, the power of triviality.
]
|
[Question]
[
Create a function (or closest equivalent, or full program) that takes an list of some datatype (your choice) that may be nested and a string (in either order), and generalizes the lisp c[ad]+r functions.
>
> Functions are provided which perform compositions of up to four car and cdr operations. Their names consist of a C, followed by ~~two, three, or four~~any positive number occurrences of A or D, and finally an R. The series of A's and D's in each function's name is chosen to identify the series of `car` and `cdr` operations that is performed by the function. The order in which the A's and D's appear is the inverse of the order in which the corresponding operations are performed.
>
>
>
[(source: common lisp hyperspec)](http://www.lispworks.com/documentation/HyperSpec/Body/f_car_c.htm)
The `car` and `cdr` operations will return the first element and all the other elements, respectively, for the purposes of this challenge. The string will hold the operation you should perform.
## Examples:
```
Array , Accessor => Result
===================================
[0,1,2], 'cdr' => [1,2]
[0,[1,2],3], 'cadr' => [1,2]
[[[[[0]]]]], 'caaaar' => [0]
[], 'cdr' => do not need to handle (no cdr)
[], 'car' => do not need to handle (no car)
anything, 'cr'/'asd' => do not need to handle (invalid command)
[0], 'car' => 0
[0], 'cdr' => []
```
## Reference Implementation
```
{
const inp = document.getElementById("inp");
const out = document.getElementById("out");
inp.onchange = () => {
const data = JSON.parse(inp.value);
var list = data.list;
data.cmd.match(/^c([ad]+)r$/)[1]
.split("").reverse().forEach(letter =>
list = letter === "a" ? list[0] : list.slice(1));
out.value = JSON.stringify(list);
};
inp.onchange();
}
```
```
<textarea id="inp" rows="2" cols="50">
{ "cmd": "cadadr",
"list": [0,[1,[2,3],4],5] }
</textarea>
<br>
<textarea readonly id="out" rows="1" cols="50">
waiting, there seems to be a problem
</textarea>
```
*This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest solution in bytes per language wins.*
[Answer]
# [JavaScript (V8)](https://v8.dev/), 48 bytes
```
a=>f=b=>b[2]?b[[x,...r]=f(b.slice(1)),1]<f?x:r:a
```
[Try it online!](https://tio.run/##bZDdasQgEIXv8xRzUVDBSrK9KduafRArxLhmcXFj0DQEln32NK4JhdJz48/5Zg4zVzWpqIMdxtfpfdG@jyNE775H63vgi@J1x1tet@IgT60QM2WMBck73LLorDa4IoRW8rM7zcdwVFsHraKJwKEpIEmUtKIHSZ8PQPocEPAaRPoskvu80beNQFr9IZJKmUSzv2ojSpkzcs5vxuaX/7t7f1k0bAz2hgmLg7MjRl89IuymBuxsbxKTzt3kNSLko@h8AJwnFSpcIgUzD0aP5izBd3l6Avc1eocoRLnuw0zK4Ua83FPVQzZrr8x4Z5jzF7yvHiuCY4p6LD8 "JavaScript (V8) – Try It Online")
*-2 bytes thanks to @Arnauld!*
[Answer]
# [Python 3](https://docs.python.org/3/), ~~68~~ ~~66~~ 54 bytes
```
lambda r,s:eval(s[:0:-1].translate(["[1:]","[0]"]*51))
```
[Try it online!](https://tio.run/##bYxBCsIwEEX3nkJmlcgoicVNoCeZzmK0LQoxliQIPX00WUnxLd/j/2XN91foytwPxcvzOso@YnLTW7xK5Iw7Wj7lKCF5yZMiIOsYEMgw8OFitS5LfISsZkUGLZ4Z4TZG0Hr346mFrjbZxIrhSo1fNtum/7h2Uz4 "Python 3 – Try It Online")
Alt, similar idea (which works in Python 2):
# [Python 3](https://docs.python.org/3/), ~~68~~ 66 bytes
```
lambda l,c:eval(l+''.join("[[10:]]"[x<'d'::2]for x in c[-2:0:-1]))
```
[Try it online!](https://tio.run/##bcyxDsIgFIXh3acgLECkBuhG6pMgA4JEDEJDGlOfHgsupvEf75dz5/dyz2ms/nyp0TyvzoBIrby9TMTxiNDpkUPCUCnOpNZQrRNySEqhfS5gBSEBqwYhmRy4JqTOJaQF@23AKKdCQwqtK5CQw6@oRnTsavbcYrrVeWu//8Lfa39WPw "Python 3 – Try It Online")
Both create an eval string which just appends the desired sequence of subscripts/slices directly to the list, with the first one using the added trick of keeping the "r" as the list name. The first one takes an actual list as input and the second takes a string representation of a list.
Credit to [xnor](https://codegolf.stackexchange.com/users/20260/xnor) for pointing me at `translate()` and the idea of using `r` as the list name for -12 bytes!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 9 bytes
```
Oị⁾ḢḊḊṖUv
```
[Try it online!](https://tio.run/##y0rNyan8/9//4e7uR437Hu5Y9HBHFwjtnBZa9v/wcqWjkx7unPGoaU3k///qySlF6joK6smJMBoIoCwIBRT/H22gY6hjFKujAGREg1nGIA4IGMSCAEgGQgAA "Jelly – Try It Online")
-2 bytes thanks to [Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string)!
Takes the accessor on the left and the array on the right
```
Oị⁾ḢḊḊṖUv - Main link. Accessor A on left, Array L on right
O - Convert A to ordinals. Note that 'a' is odd and 'd' is even
ị⁾ḢḊ - Index into "ḢḊ". Odd characters yield "Ḣ" and even "Ḋ"
ḊṖ - Remove first and last values from A
U - Reverse
v - Evaluate as Jelly code, with L as the argument
```
`Ḣ` is the *head* command, which returns the first element of a list. `Ḋ` is the *dequeue* command, which removes the first element of a list. The code executed by `v` is just a series of `Ḣ` and `Ḋ` atoms, which perform one after another.
[Answer]
# [Factor](https://factorcode.org/), ~~61~~ 57 bytes
```
[ rest reverse rest [ 97 = [ first ] [ rest ] if ] each ]
```
[Try it online!](https://tio.run/##TYvBCsIwEETvfsXQD5BaD6LiWbx4EU8lhxC3WNQ2bqIgod8e1zYBd2B23rDbaON7jufT4bjf4Ebc0R2WyfuP5bbzcPR8UWfIYTsLCCixQIVhTCHl5chZpVDWRKmT/8JcuMBvCqNzzCzz36RWqulriDWYnBd7EzuaoMZ6hZ2spmVBhXSk0DZipM0VKlYPbTGPXw "Factor – Try It Online")
*-4 bytes thanks to @Neil!*
## Explanation:
This is a quotation (anonymous function) that takes two sequences from the data stack and leaves one sequence on the data stack. In Factor, strings are just sequences of unicode code points and can be manipulated like any other sequence.
* Given input `{ 0 { 1 2 } 3 } "cadr"`...
* `rest` take everything but the first element of a sequence `{ 0 { 1 2 } 3 } "adr"`
* `reverse` reverse a sequence `{ 0 { 1 2 } 3 } "rda"`
* `rest` take everything but the first element of a sequence `{ 0 { 1 2 } 3 } "da"`
* `[ ... ] each` for each element in the sequence...
* At the beginning of the first iteration, the data stack looks like this: `{ 0 { 1 2 } 3 } 100`
* `97` push `97` on the data stack `{ 0 { 1 2 } 3 } 100 97`
* `=` test top two objects on the data stack for equality `{ 0 { 1 2 } 3 } f`
* `[ first ] [ rest ] if` run first quotation if TOS is `t`, otherwise run the second `{ { 1 2 } 3 }`
* Now the next iteration of `each` will kick in and put the next command on the data stack `{ { 1 2 } 3 } 97`
* Etc.
[Answer]
# [Racket](https://racket-lang.org/), 86 bytes
```
(λ(a c)(foldr(λ(c a)(case c[(#\a)(car a)][(#\d)(cdr a)][else a]))a(string->list c)))
```
[Try it online!](https://tio.run/##VYxBDsIwDATvfYXVHrAPfKEfgR5MnFRRoyAl@R1/4EvBDhIVe5vR7hZ2h299SZx3KAMmFB9i9hA6vl/I4AjDM0kxcsCEjqsHd8PlPqCo24xESb7kk1Z4I2KsrcS8X9cUa9Mvok4TBrjo80MZZt3MP4XDiWk@vYXJYl5zLob5R9v1Dw "Racket – Try It Online")
-3 bytes thanks to Wezl
-73 bytes thanks to ASCII-only
-8 bytes thanks to MLavrentyev
Input in the format `(f <data> <string>)`
Of course there has to be a lisp/scheme/racket/whatever answer :P
This is probably pretty bad because it's my first time golfing in Racket. I just know what I was taught in my basic first-year CS courses :P
[Answer]
# [Python 3](https://docs.python.org/3/), 86 bytes
```
lambda l,c,a=lambda x:x[0],d=lambda x:x[1:]:eval("(".join(d(c))[:-1]+l+")"*(len(c)-2))
```
[Try it online!](https://tio.run/##bcxNDoIwEAXgvacws5qRwfCza8JJahe1hYiphRBC8PSVVheE@HbvfZkZ3/Nj8HXomltw@nW3@uzYsG5@ZRWrLBTbfS@FEu2iHQLC9Tn0Hi0aIinyUmUuA4ILutZvW14RhXHq/Ywdgiy45EoBg7ETEJ32IiNxnVQfOaZQMYm3HO@/8HdNz8IH "Python 3 – Try It Online")
-1 byte thanks to @Stephen
[Answer]
# Scala, 60 bytes
```
_.tail.init.:\(_){case(x,m:Seq[_])=>if(x<98)m(0)else m.tail}
```
[Try it in Scastie!](https://scastie.scala-lang.org/RMkauukDRLm5rS3bWBvb3w)
I hate nested lists. Because of them, we need a pattern matching function (or casts, which are longer).
```
_ //The command ("caadddaddaar")
.tail //Drop the 'c'
.init //Drop the 'r'
.:\ //Fold right the "aadddada"
(_) //Starting with the inputted list
{ //Pattern matching function literal
case (x, m: Seq[_]) => //The command is x, the list is m (must be a Seq)
if (x < 98) m(0) //If the command is 'a', return the first element
else m.tail //Else, drop the first element
}
```
[Answer]
# [J](http://jsoftware.com/), 35 bytes
```
4 :0
".'y',~(}.}:x)rplc;:'a{.d}.'
)
```
[Try it online!](https://tio.run/##NcpNCgMhDIbhvacI3UTBSvqzip3DiI6UUmhx1VLs1TMyarJ7v@chkhe@ApM6OPyi/evqKn9MeT@jZww/l6pDZWSN9xfo2wnOBo4MGEMqCBk0@db8xaguLNME7XZieT51RAOMdVTEntPMsgE "J – Try It Online")
Note: -3 off TIO count for `f=:`
* Drop the first and last element from the `c[ad]+r` directive with `}.}:x`, leaving us with a string of `a`s and `d`s.
* Replace every `a` with `{.` and every `d` with `}.`, J's version of car and cdr: `rplc;:'a{.d}.'`
* Append the nested array we want to evaluate `'y',~`.
* And evaluate it `".`.
[Answer]
# JavaScript (V8), ~~77~~ 72 bytes
```
c=>d=>[...c.slice(1)].reverse(d=[d]).map(n=>d=n=="d"?d.slice(1):d[0])&&d
```
Turns out the boring solution wins
# JavaScript (V8), ~~91~~ ~~90~~ ~~87~~ 84 bytes
```
c=>d=>[...c.slice(1)].map(n=>x=>n=="d"?x.slice(1):x[0]).reduceRight((a,f)=>f(a),[d])
```
Can't add a TIO link on school WiFi :/
**Explanation:**
This is a cool approach, using functional stuff. It `slice`s the command name to remove the `c`, splits it into characters, then maps them to functions:
* `d` becomes `x=>x.slice(1)`
* `a` and `r` become `x=>x[0]`
My current approach actually returns one function, which can still access the `n` variable, which saves three bytes. I don't really know how to explain it but it works :p
It then uses `reduceRight` to apply those functions in reverse order, on `[d]`. This saves a byte over my old approach, which also sliced off the `r`.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 17 bytes
```
.v+PtXQ"da""th"\E
```
[Test suite](http://pythtemp.herokuapp.com/?code=.v%2BPtXQ%22da%22%22th%22%5CE&test_suite=1&test_suite_input=%22cdr%22%0A%5B0%2C1%2C2%5D%0A%22cadr%22%0A%5B0%2C%5B1%2C2%5D%2C3%5D%0A%22caaaar%22%0A%5B%5B%5B%5B%5B0%5D%5D%5D%5D%5D%0A%22car%22%0A%5B0%5D%0A%22cdr%22%0A%5B%5D&debug=0&input_size=2)
Uses pretty much the same approach as [ChartZ Belatedly](https://codegolf.stackexchange.com/users/66833/chartz-belatedly)['s Jelly answer](https://codegolf.stackexchange.com/a/221348/78186).
---
As an aside, this answer could shed 3/4 bytes if Pyth had an 'evaluate with argument' builtin, and an additional 1/2 if it had Jelly's 'transliterate' (Pyth builtins can be one or two bytes). This would put it at 11/12/13 bytes, which *at best* ties the 11 bytes Jelly takes. This is especially impressive since Jelly has to reverse the accessor, while Pyth doesn't (Pyth uses reverse Polish notation).
[Answer]
# [Jq](https://stedolan.github.io/jq/), 69 bytes
Takes an object with keys `"c"` for the accessor and `"l"` for the list.
```
reduce((.c/"")[1:-1]|reverse[])as$c(.l;if$c=="d"then.[1:]else.[0]end)
```
## Explanation
```
reduce $0 as$c($1; $2 )
# the accumulator starts at $1. For each $0 (stored as the variable $c),
# it becomes the result of $2 applied to it.
((.c/"")[1:-1]|reverse[])
# the command (.c), split (/""), with the ends snapped ([1:-1])
# reversed (reverse), every value inside this array ([])
.l;if$c=="d"then.[1:]else.[0]end
# starting with the list (.l), if the character is "d" then the list
# becomes its tail (.[1:]), otherwise its head (.[0]).
```
[Jq play it!](https://jqplay.org/s/uq_vWjur6j)
[Run test cases](https://jqplay.org/s/3Bs9t95CxM)
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 20 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
VÔkric)¬£=X¥'a?UÎ:UÅ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=VtRrcmljKayjPVilJ2E/Vc46VcU&input=WzAsWzEsMl0sM10gICAgCiJjYWRyIgo)
* saved 2 thanks to @Shaggy
```
1st input U = data
2nd input V = command
VÔk"cr" - reverse and remove 'cr'
£ ... Ã - pass each remaining letters to :
= - reassign 1st input(U)
X¥'a?UÎ - 1st item if 'a'
:UÅÃ - else the rest
-h flag to output result
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
Ç≈≡ø*fáì☺○
```
[Run and debug it](https://staxlang.xyz/#p=80f7f0002a66a08d0109&i=%5B0,1,2%5D,+%22cdr%22%0A%5B0,%5B1,2%5D,3%5D,+%22cadr%22%0A%5B%5B%5B%5B%5B0%5D%5D%5D%5D%5D,+%22caaaar%22%0A%5B%5D,+%22cdr%22%0A%5B%5D,+%22car%22%0Aanything,+%22cr%22%2F%22asd%22%0A%5B0%5D,+%22car%22%0A%5B0%5D,+%22cdr%22&m=2)
Returns a string of codepoints if array, and number if it's a number. The code can be verified here: [Try it](https://staxlang.xyz/#c=%22ahdD%22%7CtrDNdlcc%7C4%7B%7Cu%7Da%3F&i=%5B0,1,2%5D,+%22cdr%22%0A%5B0,%5B1,2%5D,3%5D,+%22cadr%22%0A%5B%5B%5B%5B%5B0%5D%5D%5D%5D%5D,+%22caaaar%22%0A%5B%5D,+%22cdr%22%0A%5B%5D,+%22car%22%0Aanything,+%22cr%22%2F%22asd%22%0A%5B0%5D,+%22car%22%0A%5B0%5D,+%22cdr%22&m=2)
## Explanation
```
"ahdD"|trDl
"ahdD"|t translate 'a' to 'h' and 'd' to 'D'
r reverse
D delete first element
l eval
checking code:
cc|4{|u}a?
cc dup twice
|4 ? if it's an array:
{|u} convert to JSON
a otherwise leave as is
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes
```
F⮌η≡ιa≔§θ⁰θd≔ΦθλθcIθ
```
[Try it online!](https://tio.run/##Vcq9CsIwEADg3ae4LXcQoeqmUxEKbuIaMhxJNIHQkh@qID57rCCI8/cZz9lMHFu7Thnw4maXi0NPBOUeqvGAgeC5MlwcCBZ76EsJtxH7ehqte2CS0JGERIfvsb8zhFhd/pT4V8xSzjmMFY9cKiZa5NWaUp1UG7nVcqelMGyz0G09xzc "Charcoal – Try It Online") Link is to verbose version of code. Outputs using Charcoal's default format, which is each array element on its own line and each subarray double-spaced from the next (+1 byte to output in Python `str` format). Explanation:
```
F⮌η≡ι
```
Loop over the command characters in reverse order and switch on them.
```
a≔§θ⁰θ
```
For `a` replace the input with its first element.
```
d≔Φθλθ
```
For `d` filter the first element from the input.
```
cIθ
```
For `c` print the result.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 73 bytes
```
+`(a|(d))r.(((\[)|(?<-5>])|\d|(?(5),))+),?(?(2)(?<3>.*)|.*)
r$#2$*[$3
cr
```
[Try it online!](https://tio.run/##HYoxDsMgDEV3rlEG/8SNUlC2KjmIg1QEHbp0sDpyd2L6JMvv21/fv8839z6/KDeqgC5EdAoaHc/7tie0s5rTBgZm8GEeYM@4LxOajVN/C34SH11R13upKis/OCRX8t9lBI4jGyqDNQ3sYgVbo5cu "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
+`
```
Repeat until a match cannot be made.
```
(a|(d))r.(((\[)|(?<-5>])|\d|(?(5),))+),?(?(2)(?<3>.*)|.*)
```
Match either an `a` or `d` (remembering which), then an implied `[`, then a sequence of `[`s, `]`s, `,`s and digits, except no more `]`s than `[`s and only matching `,`s between `[`s and `]`s, then an optional `,`, then if it was a `d` that matched then replace the match of the first term with the tail of the list otherwise just delete the tail.
```
r$#2$*[$3
```
Keep the `r`, re-insert the `[` if the `d` was matched, and insert the first term or tail as matched above.
```
cr
```
Finally delete the remaining `cr`.
[Answer]
# [Lua](https://www.lua.org/), 100 bytes
```
load[[t,c=...c:reverse():gsub('[ad]',load"if...=='a'then t=t[1]else table.remove(t,1)end")return t]]
```
[Try it online!](https://tio.run/##XVCxboMwEJ3hK04sxpKDknaLROeO3TqgDA4cqVXHIGNAVZRvT88GQhJLlux37969e7qXN92UUkMNOb1kVRROlHmWZeXe4oC2w5TvT11/TFkhqwMTnpSomhh5ziRzP2jA5a7YHVB3CE4eNWYWz82AqRM7jqZKuEXXW@IdDrfNBj5Rt2ih7k3pVGOgbiy0VhmnzAksdr12XTzbWjgVYvvlOSlNEGBw1DyOVB1ekOdglIZgZgLA2R6BhgeS@2vRN3LPZMEjC@w4ilSTjVY5TNmFkWQ0D1a2c7MMgd7irxhAGVCtpNqkVjVUCy4aN7cED6umAMYhJLMo1tL/grMoWtcaxFTxFqbiKnL1xrzII@oNxNGyYdg6zA5JpjxM8DemxL@tbCny11DHKczyXJHSS8KLmcdVEvYITG1rPYHNB7AnpXodwO9mxvRypViISa@tgJ2ANw@Ulb1jlxl8DwW5VPzZXv0JMJ2lZQKefr7p9g8 "Lua – Try It Online")
Function that accepts a nested table structure and a string. I sure would be impressed to see this golfed further. Please note that original table structure *will* be modified when using `d` command, so don't pass it there if it have value to you (or, better yet, never use this code outside of TIO sandbox).
TIO link also includes a test suite.
[Answer]
# [Common Lisp](http://www.clisp.org/), ~~106~~ 104 bytes
```
(lambda(a c)(reduce(lambda(a c)(if(eq c #\a)(car a)(if(eq c #\d)(cdr a)a)))(reverse c):initial-value a))
```
[Try it online!](https://tio.run/##jY6xDsIwDER3vsIKQtgDP8DGf7C4iSNFSgtN0o799eBkgonceL7nOxtDflfMUlbwFSPPk2NksIRJ3GblxwoeZQUL5ycTWk7A355TzzWPiRq@S8qi2D0soQSOt53jJnqnSif0rzRzgQLmeBwXA@i3xXKM4OGqbZOCYPSfof9h7GnXAB4hmtpI6oRqpKVnR4N9Rf0A "Common Lisp – Try It Online")
Direct port of the racket answer.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 17 bytes
```
£ḢṪṘƛ\a=[&h|&Ḣ];¥
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C2%A3%E1%B8%A2%E1%B9%AA%E1%B9%98%C6%9B%5Ca%3D%5B%26h%7C%26%E1%B8%A2%5D%3B%C2%A5&inputs=%5B%5B1%2C%5B3%2C5%2C8%5D%2C5%5D%2C2%2C3%5D%0Acaddadar&header=&footer=)
A mess :P
[Answer]
# [Python 3](https://docs.python.org/3.8/), ~~80~~ ~~79~~ 75 bytes
```
f=lambda s,x:eval(['%s[1:]','%s[0]','x#%s','%s'][ord(s[0])%4]%'f(s[1:],x)')
```
[Try it online!](https://tio.run/##XYvBCsIwDIbvPoVMShvIoXMeZLAnCT1Ua1GYW2mH1Kevpigy/0vyf18Snst1nrpjiKX4YbT3k7PbhLm/POyoSIpEbW8k8qJ55p1ItUpDc3SKMYiDEdKreosZJJQQb9OivGrOLjZIGlvcG4DNj9uPIDbY/cl3WHO04ax1fV0z92XlBQ "Python 3 – Try It Online")
By sheer luck, `ord(s[0])%4` is able to distinguish between `a`, `c`, `d`, `r`.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 71 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 8.875 bytes
```
·∏¢·π™·πò(‚Çç·∏¢hnAi
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9IiwiIiwi4bii4bmq4bmYKOKCjeG4omhuQWkiLCIiLCJjYWFhYXJcbltbW1tbMF1dXV1dIl0=)
## Explained
```
·∏¢·π™·πò(‚Çç·∏¢hnAi
·∏¢·π™ # Remove the c and r from the input
·πò # and reverse it
( # for each char
‚Çç·∏¢h # [top_of_stack[1:], top_of_stack[0]]
i # indexed by
nA # is char a vowel?
```
]
|
[Question]
[
# Sign that word 2!
Not that long ago, I posted a challenge called [Sign that word!](https://codegolf.stackexchange.com/questions/54945/sign-that-word). In the challenge, you must find the signature of word, which is the letters put in order (e.g. The signature of `this` is `hist`). Now then, that challenge did quite well, but there was one key issue: it was WAY too easy (see the [GolfScript answer](https://codegolf.stackexchange.com/a/54947/42003)). So, I've posted a similar challenge, but with more rules, most of which have been suggested by PPCG users in the comments on the previous puzzle. So, here we go!
## Rules
1. Your program must take an input, then output the signature to STDOUT or the equivalent in whatever language your using.
2. You are not allowed to use built-in sorting functions, so stuff like `$` in GolfScript is not allowed.
3. Multicase must be supported - your program must group letters of both uppercase and lowercase together. So the signature of `Hello` is `eHllo`, not `Hello` as you are given by the GolfScript answer on the first version.
4. There must be a free interpreter/compiler for your program, which you should link to.
## Scoring
Your score is your byte count. Lowest byte count wins.
## Leaderboard
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
# Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
# Ruby, <s>104</s> <s>101</s> 96 bytes
```
```
var QUESTION_ID=55090;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),e.has_more?getAnswers():process()}})}function shouldHaveHeading(e){var a=!1,r=e.body_markdown.split("\n");try{a|=/^#/.test(e.body_markdown),a|=["-","="].indexOf(r[1][0])>-1,a&=LANGUAGE_REG.test(e.body_markdown)}catch(n){}return a}function shouldHaveScore(e){var a=!1;try{a|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(r){}return a}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading),answers.sort(function(e,a){var r=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0],n=+(a.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0];return r-n});var e={},a=1,r=null,n=1;answers.forEach(function(s){var t=s.body_markdown.split("\n")[0],o=jQuery("#answer-template").html(),l=(t.match(NUMBER_REG)[0],(t.match(SIZE_REG)||[0])[0]),c=t.match(LANGUAGE_REG)[1],i=getAuthorName(s);l!=r&&(n=a),r=l,++a,o=o.replace("{{PLACE}}",n+".").replace("{{NAME}}",i).replace("{{LANGUAGE}}",c).replace("{{SIZE}}",l).replace("{{LINK}}",s.share_link),o=jQuery(o),jQuery("#answers").append(o),e[c]=e[c]||{lang:c,user:i,size:l,link:s.share_link}});var s=[];for(var t in e)e.hasOwnProperty(t)&&s.push(e[t]);s.sort(function(e,a){return e.lang>a.lang?1:e.lang<a.lang?-1:0});for(var o=0;o<s.length;++o){var l=jQuery("#language-template").html(),t=s[o];l=l.replace("{{LANGUAGE}}",t.lang).replace("{{NAME}}",t.user).replace("{{SIZE}}",t.size).replace("{{LINK}}",t.link),l=jQuery(l),jQuery("#languages").append(l)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*\s*([^,]+)/;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table></div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table></div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table><table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table>
```
[Answer]
# Pyth, 10 bytes
```
sm@+drd1zG
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=sm%40%2Bdrd1zG&input=Hello&debug=0)
### Explanation:
```
implicit: z = input string
m G map each letter (variable d) of the alphabet to:
+drd1 d + upper(d)
@ z filter z for these two letters
s sum, join to a string
```
[Answer]
# GOTO++, 531 bytes
```
niveaugourou 0
s=ENTRETONTEXTE()
§2 a=LeCaracNumero()&s *(1)
n=*(1)
costaud i=*(2)/&i infeg NombreDeLettres(&s)/i=+*(1)
b=LeCaracNumero()&s &i
c=&b
d=&a
GOTONULPOURLESNULS %4 }&b sup *(96){
c=-*(32)
§4 GOTONULPOURLESNULS %5 }&a sup *(96){
d=-*(32)
§5 GOTONULPOURLESNULS %1 }&c inf &d{
a=&b
n=&i
§1 faiblard
GOTOPRINTDUTEXTE()&a
s=Marijuana()}BOITEAPINGOUINS()}PrendsUnMorceau()&s *(0) &n{ }PrendsUnMorceau()&s }&n+*(1){ *(0){{ «»
GOTONONNULPOURLESNULS %3 }NombreDeLettres(&s) eg *(1){
GOTOPASMALIN %2
§3 GOTOPRINTDUTEXTE()&s
```
[GOTO++ Project page](http://www.gotopp.org/index.html.en)
Here's a slighlty more readable and commented version of the code(Note that `GOTO` starts a comment in GOTO++):
```
niveaugourou 0 GOTO Allow every keyword to be used
s=ENTRETONTEXTE() GOTO Read from STDIN
§2 a=LeCaracNumero()&s *(1) GOTO Get first char in s
n=*(1)
costaud i=*(2)/&i infeg NombreDeLettres(&s)/i=+*(1) GOTO Loop on every char of s
b=LeCaracNumero()&s &i GOTO b = i-th char
c=&b
d=&a
GOTONULPOURLESNULS %4 }&b sup *(96){ GOTO If b is uppercase, goto §4
c=-*(32) GOTO Get the uppercase ASCII value of b
§4 GOTONULPOURLESNULS %5 }&a sup *(96){ GOTO same as above but with a
d=-*(32)
§5 GOTONULPOURLESNULS %1 }&c inf &d{ GOTO If b is after a in alphabetical order, goto §1 (next loop iteration)
a=&b GOTO Else replace a by b
n=&i
§1 faiblard GOTO End loop
GOTOPRINTDUTEXTE()&a GOTO Print the value of a
t=PrendsUnMorceau()&s *(0) &n GOTO Get the part of s before a
u=PrendsUnMorceau()&s }&n+*(1){ *(0) GOTO Get the part of s after a
e=BOITEAPINGOUINS()&t &u GOTO Create an array of penguins containing the two substrings
s=Marijuana()&e «» GOTO Concatenate the penguins in the array
GOTONONNULPOURLESNULS %3 }NombreDeLettres(&s) eg *(1){ GOTO If s is one char long, goto §3
GOTOPASMALIN %2 GOTO Else goto §2
§3 GOTOPRINTDUTEXTE()&s GOTO Print the last char
```
[Answer]
## Haskell, 51
```
f s=[x|(a,b)<-zip['a'..'z']['A'..],x<-s,x==a||x==b]
```
The `zip` creates a list of pairs of characters `[('a','A'), ...('z','Z')]`. Because of truncation, the second endpoint doesn't need to be specified. For each pair in the list, we take the letters in the input string `s` that are either of the two characters in the pair.
[Answer]
# Python 3, ~~72~~ 70 bytes
```
s=input()
print("".join(d*(ord(d)&31==c)for c in range(27)for d in s))
```
Assumes the input consists of only `[a-zA-Z]`.
*(-2 bytes thanks to @xnor)*
[Answer]
# Pyth, 15 14 bytes
```
s*V/LzJ.irG1GJ
```
Thanks for isaacg for removing 1 byte.
I don't know much about Pyth yet, so this may not be golfed well.
[Try it here.](http://pyth.herokuapp.com/?code=jk*V%2FLzJ.irG1GJ&input=this&debug=0)
[Answer]
# JavaScript (ES6), 71 ~~74~~
Limited to A-Za-z (see comment by @Matthieu M)
*Edit* Too used to compose a single expression with commas, to avoid 'return'. Here an output is required, so I can use a simple `for` and forget about commas.
~~Using array comprehension the byte count is 73, but that is not valid EcmaScript 6 anymore~~
Usual note: test running the snippet on any EcmaScript 6 compliant browser (notably not Chrome not MSIE. I tested on Firefox, Safari 9 could go)
```
f=w=>{v=[];for(c of w)v[n=parseInt(c,36)]=(v[n]||'')+c;alert(v.join``)}
```
```
<input id=I value='Hellzapoppin'><button onclick=f(I.value)>-></button>
```
[Answer]
## Javascript, 112 194 bytes
```
r=[];t=[];a=s.split('').map(function(x){t[i=parseInt(x,36)]?t[i].push(x):t[i]=[x];return i;});while(l=a.length)r[l-1]=t[a.splice(a.indexOf(Math.max.apply({},a)),1)].pop();console.log(r.join(''))
```
This is far away from "golfed" but I'm a bit busy right now, just editted to remove sort.
[Answer]
## Python 3, 64
A small improvement on [Sp3000's answer](https://codegolf.stackexchange.com/a/55125/20260), which uses the idea of iterating iterating the character indices, and for each one, iterating through the input to take characters that match up to case.
```
c=1
for d in(input__+'~')*26:print(end=d[ord(d)&31^c:]);c+=d>'z'
```
This uses a single loop, looping through the input 26 times. The separator `~` is used to know when to go to the next character index `c`. To whether character `d` matches value `c` up to case, the last five bits of the bit-value of `d` are xor-ed with `c`, with a 0 indicating a match.
Then, the character `d` is printed exactly when the result is `0`, with an empty string otherwise.
[Answer]
## Python 2.7, ~~114~~ 106 bytes
```
l=[0]*123
for e in raw_input():l[ord(e)]+=1
print''.join(chr(j)*l[j]for i in range(26)for j in(i+65,i+97))
```
Logs the presence of a char in a 123 length array(for including both A-Z and a-z ranges) and then iterates through it to get the non-zero entries.
Inefficient, but more efficient than brute forcing it(but longer :().
Testing it-
```
<< HelloWorldhi
>> deHhillloorW
```
[Answer]
# PHP, ~~275~~ 270 bytes
```
<?php
for($i=65;$i<123;$i++){$v[$i]=chr($i);}foreach(str_split($argv[1])as$c){$a=array_search($c,$v);if($a<97){$p[]=($a+32);$z[]=$a;}else{$p[]=$a;}}foreach($p as$chr){$m=min($p);if($z[0]+32==$m){echo chr($m-32);unset($z[0]);}else{echo chr($m);}unset($p[array_search($m,$p)]);}
```
**Explanation:**
The code generates an array with every letter in the alphabet, which has its ASCII Value as Array Key. Afterwards the code generates a new array which contains the ASCII Values of the Input. Then the lowest Value gets printed out and gets removed.
**Usage:**
Call the script with an argument: `php -d error_reporting=0 script.php Hello`
**Ungolfed Version:**
```
<?php
$input = $argv[1];
$valueArray = [];
for($i=65;$i<123;$i++) {
$valueArray[$i] = chr($i);
}
$new = str_split($input);
foreach($new as $char) {
if(array_search($char, $valueArray)<97) {
$newArray[] = (array_search($char, $valueArray)+32);
$checkArray[] = array_search($char, $valueArray);
} else {
$newArray[] = array_search($char, $valueArray);
}
}
foreach($newArray as $chr) {
if($checkArray[0]+32 == min($newArray)) {
$string .= chr(min($newArray)-32);
unset($checkArray[0]);
} else {
$string .= chr(min($newArray));
}
$key = array_search(min($newArray), $newArray);
unset($newArray[$key]);
}
echo $string;
```
Any advices are greatly appreciated.
[Answer]
# Haskell, ~~83~~ 53 bytes
```
import Data.Char
f y=[c|x<-[' '..],c<-y,toLower c==x]
```
Usage: `f "HelloWorldhi"` -> `"deHhillloorW"`.
How it works: let `y` be the input string
```
[ |x<-[' '..] ] -- for every x from Space to the last Unicode character
,c<-y -- loop through all character c from the input string
c ,toLower c==x -- and keep those where the lowercase version equals x
```
Edit: 30 bytes saved, imagine that! Thanks @Mauris.
[Answer]
# Python 3, 61 bytes
A new answer for a different technique!
```
z=['']*42
for c in input():z[ord(c)&31]+=c
print(*z,sep='')
```
Noting that `ord('a')&31==ord('A')&31` and that `ord('z')&31==ord('Z')&31`, we can simply create an array of empty strings and for each character add it to the array index of its ASCII value `&31`. When you print it, it will be sorted.
Limited to input `a-zA-Z`.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 8 bytes
```
s⊇⍨⍋⌈s←⍞
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKM97X/xo672R70rHvV2P@rpKH7UNuFR7zyQzH/ONC6P1JycfC4gI7HY2dMzOT8lFQA "APL (Dyalog Extended) – Try It Online")
(If a function were OK, it would have been 5 bytes `⍋⍤⌈⊇⊢`.)
`⍋` can be controversial here, because the challenge says "built-in sorting functions not allowed" and `⍋`, called "Grade", is definitely related to sorting but it doesn't sort the input by itself. Instead, it gives a list of indices which, when used to index into the original input, results in the sorted array:
```
x←10 50 20 40 75
⍋x
1 3 4 2 5
x[⍋x]
10 20 40 50 75
```
This can be also used to implement "sort-by", if we index into a different array other than `x`:
```
'abcde'[⍋x]
acdbe
```
### How it works
```
s⊇⍨⍋⌈s←⍞ ⍝ Full program
s←⍞ ⍝ Take a line of string input and assign to s
⌈ ⍝ Uppercase the letters
⍋ ⍝ Grade up; find the sorting order
s⊇⍨ ⍝ Index into the original string s,
⍝ essentially sorting the string in the case-insensitive order
```
If `⍋` is not acceptable:
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 12 bytes
```
∊⍞∘∩¨⎕A,¨⌊⎕A
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKM9DUh0Peqd96hjxqOOlYdWPOqb6qgDpHq6QCyQiv@caVweqTk5@VxARmKxs6dncn5KKgA "APL (Dyalog Extended) – Try It Online")
Set intersection in APL is essentially "erase the items in the left argument that do not appear in the right argument", so the duplicates in the left argument is preserved.
### How it works
```
∊⍞∘∩¨⎕A,¨⌊⎕A ⍝ Full program.
⎕A,¨⌊⎕A ⍝ Pair each char in ⎕A (uppercase letters) with its lowercase
⍞∘∩¨ ⍝ Take intersection of entire input and each pair of chars
∊ ⍝ Flatten
```
[Answer]
# Python 3, ~~97~~ 92 bytes
```
from itertools import*;print(*min(permutations(input()),key=lambda z:str(z).lower()),sep='')
```
The best way to sort is clearly to generate all permutations, and then pick the minimum, which just happens to be sorted :)
The strings are lowercased before comparison to abide by the 'case-aware' rules.
Warning: may be *very slow* with big strings.
An interpreter is located [here](http://repl.it/languages/Python3).
[Answer]
# Python 3, 118 bytes
```
i=input();i,x=map(list,(i,i.lower()))
while x:q=min(x);x.remove(q);q=[q.upper(),q][q in i];i.remove(q);print(q,end="")
```
Could be golfed much shorter, I know
[Answer]
# Powershell, 164 Bytes
I'm sure there's a cleaner way to do this, but I couldn't come up with anything else. Just takes the input as a character array, does an insertion sort, and spits out the output. Loses horribly, even to other non-golfing languages.
### Code:
```
$a=[char[]]($args[0]);For($u=1;$u-lt$a.Count;$u++){$n=$a[$u];$l=$u;while(($l-gt0)-and((""+$a[$l-1]).CompareTo(""+$n)-gt0)){$a[$l]=$a[$l-1];$l--}$a[$l]=$n};$a-join''
```
### Usage:
```
PS C:\scripts> .\sign-word-2.ps1 tTHhis
hHistT
```
### Expanded & Explained:
```
$a=[char[]]($args[0]) # Takes command-line argument, recasts as char array
For($u=1;$u-lt$a.Count;$u++){ # Performs a quick-n-dirty insertion sort
$n=$a[$u]
$l=$u
while(($l-gt0)-and((""+$a[$l-1]).CompareTo(""+$n)-gt0)){
# Ugly, ugly code here. String.CompareTo(String) is case-insensitive, but
# because we cast as a char[], Char.CompareTo(Char) is case-sensitive ...
# So, need to do an on-the-fly re-casting as a string with ""+
$a[$l]=$a[$l-1]
$l--
}
$a[$l]=$n
}
$a-join'' # Without the -join'', it would print out the chars with a space between
```
[Answer]
# Julia, 61 bytes
```
f=s->s>""?(k=indmax([s...]%32);f(s[k+1:end]s[1:k-1])s[k:k]):s
```
Julia will display it as a string output if you call it in the REPL. If it *has* to print out to STDOUT, then it needs 78 bytes:
```
x->(f=s->s>""?(k=indmax([s...]%32);f(s[k+1:end]s[1:k-1])s[k:k]):s;print(f(x)))
```
An interpreter for Julia can be found [here](https://www.juliabox.org/). Another one, which I've already put some code into, is [here](http://goo.gl/d0YPnf). Note that, with the second one, you will need to make the terminal (at the bottom) visible by dragging the boundary up. Clicking "execute" will make it run in the terminal at the normal command line (and thus won't show the output if called without println). Alternatively, you can just type `julia` into the terminal itself, then handle everything inside the REPL that will come up.
And for a bit of extra fun, here are some other implementations
Gnome Sort (83 bytes):
```
s->(for m=2:endof(s),n=m:-1:2 s[n]%32<s[n-1]%32&&(s=s[[1:n-2,n,n-1,n+1:end]])end;s)
```
My own sorting algorithm (84 bytes):
```
s->(k=1;while length(k)>0 k=find(diff([s...]%32).<0);s=s[setdiff(1:end,k)]s[k]end;s)
```
[Answer]
# Scala, 82 bytes
```
print((""/:args(0)){case(s,c)=>val(a,b)=s.span(h=>{if(h<97)32 else 0}+h<c);a+c+b})
```
from command line:
```
$ scala -e 'print((""/:args(0)){case(s,c)=>val(a,b)=s.span(h=>{if(h<97)32 else 0}+h<c);a+c+b})' Hello
eHllo
```
probably can be golfed a bit further...
just implementing insertion sort using fold.
[Answer]
# x86 machine code, ~~51~~ 42 bytes
```
00000000 b3 82 89 da 8b 07 80 fc 0d 74 12 b9 20 20 09 c1 |.........t.. ..|
00000010 38 e9 7e 06 86 c4 89 07 31 d2 43 eb e7 85 d2 74 |8.~.....1.C....t|
00000020 df c6 47 01 24 b4 09 cd 21 c3 |..G.$...!.|
0000002a
```
Bubble sort, with some register reuse tricks to shave bytes here and there; the [.COM file](https://bitbucket.org/mitalia/pcg/downloads/sign.com) runs in DosBox, receives the input from command line and prints the output to standard output.
[](https://i.stack.imgur.com/2PRjR.png)
Commented assembly:
```
org 100h
section .text
start:
; bubble sort - external loop
ext:
; start from the first character (assume bh=0, true on every DOS)
mov bl,82h
; "not-swapped" flag - 82h => no swaps in current iteration;
; 0 => a swap happened (the 82h will come in handy later)
mov dx,bx
; bubble sort - internal loop
int:
; read 2 characters at time in the full ax
mov ax,word[bx] ; al ah
; ^[bx] ^[bx+1]
; check if we are at the end (the command line is CR terminated)
cmp ah,0dh
je skip
; make uppercase in cx
mov cx,2020h
or cx,ax
; compare
cmp cl,ch
jle next
; wrong order - swap and rewrite
xchg al,ah
mov word[bx],ax
; mark that we did a swap
xor dx,dx
next:
; next character
inc bx
jmp int
skip:
; loop as far as we swapped something
test dx,dx
jz ext
end:
; $-terminate the string
mov byte[bx+1],'$'
; print
; dx already contains the location of the string, since that's the
; flag value we used for "no swaps"
mov ah,9
int 21h
ret
```
[Answer]
# [Java (JDK 10)](http://jdk.java.net/), 125 bytes
```
s->{for(int i=s.length,j;i-->1;)for(j=i;j-->0;)s[i]^=(s[i]&95)<(s[j]&95)?s[j]^(s[j]=s[i]):0;System.out.print(new String(s));}
```
[Try it online!](https://tio.run/##bY4xT8MwEIX3/IpTB2SjxioDA7gJQp2ZOkapZFwnOZPYkX0pqqr@9uCEEaZ77743fFZdVG7PXzMOow8ENnUxEfbiUWZ/fs3kNKF3/8JIwahhQbpXMcKHQge3DGCcPnvUEElROhePZxgSY0cK6NqqBhXayNcpwMG7OA0m7HWnQlWX0EAxx7y8NT4wdARYRNEb11K3tRLzvHySfGG2QGlT3UkeK6xPBVvOw8sz36dk1/S2hNNai4Xy1508XiOZQfiJxJh8iDnzDb9qLHIu77NcxRqhtDYjsQ11GDeC/CEZvoegrizN0uae3ecf "Java (JDK 10) – Try It Online")
Using a naive sort.
[Answer]
# Perl, 88 bytes
```
@_=/./g;a:{for(0..@_-2){@_[$_,$_+1]=@_[$_+1,$_],redo a if uc$_[$_]gt uc$_[$_+1]}}print@_
```
Just a simple Bubble Sort. Call with -n option to pass the text.
e.g:
```
echo "tThHiIsS" | perl -n sort2.pl
```
Output:
```
hHiIsStT
```
[Answer]
# PHP, 106 bytes
The code:
```
$c=count_chars($argv[1]);$r=str_repeat;for($i=64;++$i<91;)echo$r(chr($i),$c[$i]),$r(chr($i+32),$c[$i+32]);
```
There is nothing special in the code; [`count_chars()`](http://php.net/manual/en/function.count-chars.php) produces an array indexed by ASCII codes that contains the number of occurrences for each ASCII character. The rest is a dull iteration over this array.
Example of execution:
```
$ php -d error_reporting=0 sign.php qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKasdfJHGFDSAZXCVBNM
AaaBbCcDddEeFffGgHhIiJjKkLlMmNnOoPpQqRrSssTtUuVvWwXxYyZz
```
An extra byte can be saved using PHP 7: replace `$c[$i]` with `($c=count_chars($argv[1]))[$i]` and remove the assignment of `$c` from the beginning of the program.
[Answer]
# Haskell, 74 bytes
```
l=(`mod`32).fromEnum
f=foldr(#)""
e#[]=[e]
e#a@(h:t)|l e<l h=e:a|1<2=h:e#t
```
Completely different from my [other answer](https://codegolf.stackexchange.com/a/55139/34531). This time it's a simple Insertion sort.
[Answer]
# Pip, ~~18~~ 14 bytes
[GitHub repository for Pip](http://github.com/dloscutoff/pip)
Seems there's no competing with Pyth, but this is pretty respectable.
```
FcAZ OcQUC_FIa
```
Works only on strings containing `a-zA-Z`. For each letter of the alphabet, uses a filter operation to grab the letters from the input string that equal that letter case-insensitively:
```
a <- cmdline arg, AZ <- string containing uppercase alphabet (implicit)
FcAZ For each character c in AZ:
FIa Filter characters of a on the following lambda function:
UC_ Uppercase of character...
Qc ... is equal to c
O Output the resulting list, joined on empty string by default
```
Two notes:
* The space is necessary; otherwise, the sequence `AZO` would scan as `A ZO` instead of `AZ O`;
* The program doesn't output a trailing newline. To add one, put an `x` at the end of the code (thereby printing an empty string after the loop is done).
Sample run (using the `x` variant):
```
dlosc@dlosc:~/pip$ pip -e "FcAZ OcQUC_FIax" "HelLo wOrld"
deHlLloOrw
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
œ.ΔlÇ¥dP
```
[Try it online](https://tio.run/##yy9OTMpM/f//6GS9c1NyDrcfWpoS8P9/SIZHZkYxAA) or [verify a few more test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/o5P1zk3JOdx@aGlKwP9anf/RSiUZmcVKOgpKGZklYDqpKD8/F8RITkp0dnJMS00BcUIyPDIzwPIhqcUlBirqSrEA).
**Explanation:**
```
œ # Get all permutations of the (implicit) input-string
.Δ # Find the first permutation which is truthy for:
l # Convert it to lowercase
Ç # Convert each character to its ASCII codepoint
¥ # Get the deltas / forward-differences of those codepoint integer
d # Check that each difference is >= 0
P # And check that all of them are truthy
# (after which the found string is output implicitly as result)
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
;BíC ËpUèD
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=O0LtQyDLcFXoRA&input=IkhlbGxvIg)
```
;BíC ËpUèD :Implicit input of string U
;B :Uppercase alphabet
í :Interleave
; C : Lowercase alphabet
Ë :Map each D
p : Repeat
UèD : Count of D in U
```
[Answer]
# [Perl 5](https://www.perl.org/) `-a`, 31 bytes
```
for$i(a..z){print grep/$i/i,@F}
```
[Try it online!](https://tio.run/##K0gtyjH9/z8tv0glUyNRT69Ks7qgKDOvRCG9KLVAXyVTP1PHwa32/3@P1Jyc/H/5BSWZ@XnF/3V9TfUMDA3@67oBAA "Perl 5 – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `g`, 5 bytes
```
Ṗ'⇩ÞṠ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJnIiwiIiwi4bmWJ+KHqcOe4bmgIiwiIiwiSGVsbG8iXQ==)
7 bytes without the flag (`;h` at the end) or 6 bytes flagless (`Ṗ‡⇩ÞṠc`). This would otherwise output a list of the signature potentially repeated multiple times.
Things that sort things may be out of bounds, but things that check if things are sorted aren't.
## Explained
```
Ṗ'⇩ÞṠ
Ṗ # From all permutations of the input
' # keep only those where:
⇩ # lowercasing the permutation
ÞṠ # gives a sorted string
```
]
|
[Question]
[
For this challenge, you will be required to write 3 programs:
1. The first program should be a [quine](https://codegolf.stackexchange.com/questions/69/golf-you-a-quine-for-great-good), i.e, it should print it's own source code.
2. The second program should read the input and print all of it.
3. The third program should simply print the string `"Hello, Permutations!"`, with or without quotes.
In addition to that, all the three programs should be **permutations**, i.e, starting from any of the three programs, you should be able to obtain the other by re-arranging it's characters. So all programs will have the same byte count and frequency of characters. For example: `abcd`, `dbca` and `adbc` are permutations.
# Rules
* You may choose to write functions instead of programs.
* For the first program, you are not allowed to read the source file and print it.
* You only need to read the input for the second program. No input will be provided to the other two programs.
* Standard loopholes are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code (in bytes) wins.
[Answer]
# [Underload](https://github.com/catseye/stringie) (stringie), 33 bytes each
```
((aS(:^):SHello, Permuttions!):^)
(S(Hello, Permutations!)(:::^^S))
((Hello, Permutations!)S(:::^^S))
```
[Try it online!](https://tio.run/##bYpBCsMgEADvecXmppAX7At6LHgXpK64YN2ga79vUwiEQG/DzIwaqRUJcRrN3CFTOATsTT4cqQPXfSiogGaCxK0rpFFfylLtdOZBpcgGT2rvoeFn@2oNInrv7PI/u6uHg71Fd/vODf2cXw "Underload – Try It Online")
These are function submissions that input via the argument stack, but output to standard output. (The functions also produce garbage output using the more normal mechanism for function output, but according to our normal I/O rules, we only look in one place.)
## Explanations
```
(aS(:^):SHello, Permuttions!):^
(aS(:^):SHello, Permuttions!) string literal
: non-destructive
^ eval
a enclose {the string literal} in parens
S print it
(:^) string literal
S print that too
: retaining a copy
Hello, Permuttions no-ops
! discard the retained copy
S(Hello, Permutations!)(:::^^S)
S print {function input}
(Hello, Permutations!) string literal {2nd return value}
(:::^^S) string literal {1st return value}
(Hello, Permutations!)S(:::^^S)
(Hello, Permutations!) string literal
S print it
(:::^^S) string literal {return value}
```
If we weren't exploiting this site's I/O rules, it'd cost one extra byte (along with a little code rearrangement) to output the output we wanted (either to standard output or as the function return value), and delete the output we didn't want. But just leaving the extra characters that we're forced to use in order to make a permutation on the argument stack is very slightly shorter.
The quine is an eval quine: we write most of the program in a string literal and `eval` it, but we still have the original string literal available (because we made the `eval` non-destructive) and can print it in addition to running it. (This isn't code reading itself, rather the `:^` reads one string and uses it for two different purposes.)
[Answer]
# [7](https://esolangs.org/wiki/7), ~~58~~ 56 characters, ~~22~~ 21 bytes each
```
00000000011111111222233333444444445555**7**1**7**1**6**2234430404053
```
[Try it online!](https://tio.run/##NcjBDQAwCMPAlaCEZv/JQirR88@U4st1rB6sNibz@gMVcF3SAA "7 – Try It Online")
```
1313131300000002244444444445555**7**2111**7**20000**6**0322351311443
```
[Try it online!](https://tio.run/##PcrRDQAgCEPBlWwLMo@6/wyIIfHeZxuZUDcaaZ@XIIDgm@YQKa8zzJS59rk "7 – Try It Online")
```
**7**532510130304043205104345101144411240324104020054321**67**43
```
[Try it online!](https://tio.run/##FcrBEcBACMPAlmwsQv@VceSpHc3udKotRxEipSvCbwbsQikOVVLf4W/I7gM "7 – Try It Online")
>
> **Update**: Since the first version of this answer, I golfed off a **`7`** and a `0` – the hello program was slightly rearranged to be able to make use of the **`6`** rather than needing a `0`, and the quine was entirely rewritten to use fewer **`7`**s. The text below has been updated to match; see the edit history for the previous version of this answer.
>
>
>
No cheating with I/O this time: these are all full programs which output to standard output, and (in the case of the second program) input from standard input. The cat program was the hardest of the three to write by far, because it's the only program that requires a loop.
7's character encoding (which is just octal) encodes eight characters per three bytes. This program is thus 21 bytes long (⅜ of 56). Because this is an integer, we don't have to worry too much about the weird sub-byte encoding, but in order to make the programs "conceptually shorter", I ensured that they all ended with a `3` (the interpreter treats trailing 1 bits like trailing whitespace, so the final two bits of the encoding are arguably not part of the program). Note that I can't end a program with a **`7`** because it would be ignored entirely, causing the program to no longer be 56 characters long (and thus the programs to not be permutations of each other).
## Explanations
My usual reminder: 7 has 12 commands, but only 8 of them have names. I use the notation `0`, `1`, `2`, `3`, `4`, `5` for the commands that append **`6`**, **`7`**, **`2`**, **`3`**, **`4`**, **`5`** respectively to the top stack element (the last four of these commands cannot appear literally in a program and can only be created at runtime by using them to create a program on the stack).
### Quine
```
00…55**7**1**7**1**6**22…53
00…55 An arbitrary string literal
**7** Separator between elements of the initial stack
1**7**1**6**22…53 Literal representing the main program
```
The first pass through a 7 program can't do anything more than push literals to the stack (the rightmost goes towards the top of the stack). However, after doing that, the top stack element is implicitly executed (non-destructively; it remains on top of the stack, and a copy is executed). It does the following:
```
**7**1**2234436464653**
**7**1 Push stack element "**7**"
**2** Duplicate it
**23** Use one copy as an I/O routine (sets I/O format 7)
**443** Swap the "**7**" and main program
**6** Uneval the main program, and
append it to the stack element below
**46** Uneval the second stack element, while
swapping it to the top of the stack
**46** Uneval the second stack element, while
swapping it to the top of the stack
**5** Execute the new top of stack
(this undoes the uneval and appends it
to the element below)
**3** Output (+ some irrelevant side effects)
```
It's a little hard to follow this, so here's a description of what's happening to the stack. It starts with two stack elements: the arbitrary literal, below the main program (both of these start out in evaluated, ready-to-run, form). The program immediately adds a third (the literal **`7`**), which is (nondestructively) used to set the I/O format (to format 7, "the same format as is used for the source code"). It then works out what source code is most likely to have produced the executable/evaluated main program via using the **`6`** command (and I intentionally wrote it in a way that would round-trip properly), and appends it to the **`7`** – this generates a string literal, the source code for the latter half of the quine (from the first **`7`** onwards). Then it undoes the evaluation of the arbitrary literal below (working out the source code that generated that arbitrary literal, too – source code consisting only of nonbolded characters roundtrips perfectly as they have a very obvious effect on the stack), and prepends that to our calculated second half of the quine's source code, producing the source code of the quine as a whole (and outputs it).
The confusing part is that the **`46465`** near the end, which undoes the evaluation of the arbitrary literal and prepends it to the rest of the quine's source code, has the two operations (unevaluating and prepending) interleaved with each other. This is because there isn't a direct "append" instruction in 7. Rather, there are two ways to append things – the **`6`** command does both an unevaluate and an append, and string literals append themselves to the top stack element when executed rather than creating a new stack element. So in order to append two string literals without a net change to the escaping level, the latter needs to be unevaluated in-place (and it needs an empty element beneath to append to due to the other effect of **`6`**), and then executed using **`5`**. The most convenient way to cancel out the side effect of **`6`** is to use the swap command **`4`** – this places an empty stack element in between the two elements it's swapping. So we need to interleave swaps in with the unescapes, and this means interleaving the routines that operate on the two relevant stack elements, swapping between the routines every time the stack element swaps.
Incidentally, this is a proper quine under CGCC's definition because the 1 in `**7**1**6**` is used to output the first **`7`** in the output (in addition to representing itself). (You can observe this by changing this section of code to, e.g., `**7**10101**6**` – the separator changes to **`76767`** in the output, and you get a `6767` at the start of the output because the same literal is also output to set the I/O format.)
### Cat program
I actually hadn't written a cat program in 7 before, and it's not as trivial a task as it looks.
```
13131313…**7**2111**7**20000**6**03…43
13131313… Literal representation of program **73737373…**
**7** Separator between elements of initial stack
2111**7**20000**6**03…43 Literal representation of program **2777**20000**63…43**
```
Two programs, here, which run in (7's usual reverse) sequence.
The program on the left (which runs last) pops the stack (**`73`**) four times. It won't have four elements on it at that point, and a pop on an empty stack is defined to exit the program (stack underflow is normally an error, but this is a special case). So the rest of that program never runs, and it gives us a place to put all the digits we have to include (due to the permutation restriction) but aren't using for anything.
The program on the right is more interesting, and implements the cat behaviour. It assumes that a copy of itself will exist on the top of the stack when it starts running (this will always be the case on the first iteration, because 7 leaves the top of stack in place when it starts running it).
The program on the right is also a silly sort of polyglot. The numerical value of a string in 7 is defined as the total number of `1` and **`7`** characters in it, minus the total number of `0` and **`6`** characters; other characters are ignored. With six **`7`**s, four `0`s and a **`6`**, this string has a numerical value of +1. This is intentional and required for the program to work, because the string in question is used interchangeably as an implementation of the cat program, and a representation of the integer 1, while the program is running. (This sort of polyglotting is pretty unusual, but helped me save the need for a second **`6`** character, which would have hurt the byte count because the hello program (the longest) doesn't have any natural reason to use one and so we can't just borrow one from its string literal.)
The string literal **`20000`** is also a polyglot. This is used only as an I/O control string. The numerical value of -4 means "input a character", when we try to interpret it as a character code (input is done by outputting otherwise impossible/illegal values, like negative character codes); the leading 2 means "output character codes as characters". The default character set for character I/O is 8-bit SBCS. So on the first iteration, we configure I/O for byte-at-a-time operation, and reinterpret the same value that does that as -4 and thus input a character in the process. In the subsequent iterations, I/O is already configured as byte-at-a-time, so only the numerical value of -4 matters.
Bearing those factors in mind, we can now look at how the program works:
```
**2777**20000**6322357377443**
**2** Duplicate top of stack
**77**20000**6** Escaped literal 20000 (non-bolded)
**7** **3** Output literal (actually takes input)
```
Input is implemented by duplicating the top of stack a number of times equal to the input, off-by-one (so that EOF can be 0, NUL is 1, SOH is 2, etc.). The same off-by-one applies on output. So the stack is now our 1/cat polyglot, below an integer (which is repeated copies of the cat program) representing our input. We can output it immediately to implement cat behaviour.
```
**2777**20000**6322357377443**
**223** Non-destructive output of top of stack
**5** Pop and eval top of stack
**73** Pop top of stack
**77** Push two empty stack elements
**443** Swap those empty elements
```
After producing our output, we loop by executing ourself again. Or do we?
The program has to halt on EOF. If you look carefully, you'll note that we aren't executing the original cat program (the one with an integer value of 1); that's on the stack just below the element we eval'ed. The stack element actually being executed is the one we just output: the character code that was read in from the user. Remember that this is made up of a number of copies of the cat program, so in most cases we can simply just execute it and it'll work the same way as the original program. However, if the character code we read in is EOF, it'll consist of no copies of the cat program, so there will be nothing to run. We then pop the remaining cat program from the stack, and there are no printing or looping commands left in the program, so it must eventually end up exiting naturally. This gives us a clean exit at EOF, whilst being very very esoteric. (The two **`7`** commands at the end are clearly pointless, of course; they exist purely to get the numerical value of the cat program right, and don't cost any bytes because they're needed to maintain the permutation property anyway, as they're generated from `1`s and we have plenty of those in the hello string literal. The **`433`** at the end is a no-op, also made from characters that would need to be added somewhere anyway – its purpose is to ensure that the original program ends with a `3`.)
### Hello program
```
**7**53…1**67**43
**7** Empty padding element on initial stack
53…1 Literal representation of string **53…7**
**6** Uneval that string (on the first pass!)
**7** Separator between elements of the initial stack
**43** Modified "print a literal" program
```
This is a version of the 7 hello-world program, modified a little more extensively than in the original version of this answer.
The standard hello-world program in 7 consists of a string literal followed by `**7**403` – during the first pass through the program, the literal is evaluated into live executable code, but the **`40`** swaps it to the top of the stack and unevaluates it (getting back at the original string literal), and the **`3`** then prints it (and also pops the **`463`** stack element that's the currently executing code – remember, the top stack element gets executed after the first pass through the program, but is *not* popped in the process). That's what I did for the first version of this answer.
However, this program needs to contain a **`6`** somewhere, so that it can be a permutation of the cat program. It's possible to make use of this to save the `0` from the original version of the answer – instead of unevaluating the string literal while the "print a literal" program is executing, we can instead unevaluate it on the first pass through the program (because **`6`** and **`7`** commands run immediately). Program execution starts with two empty elements on the stack, so the **`6`** unevaluates the string literal (returning it to its original form in the source code) and appends it to one of them. That lets us write the program that actually prints the literal as just **`43`** rather than **`463`** (so the original source that represents it is just `43` rather than `403`).
An unfortunate consequence of this way of doing things (as opposed to the normal way to write a hello-world program) is that the **`43`** never actually ends up getting popped from the stack. It thus runs again when the end of the program is reached, and ends up crashing the program due to stack exhaustion rather than exiting cleanly. However, we do have the right output on standard output, and that's all that matters.
The literal is, as usual for 7, encoded in a domain-specific language intended for encoding strings; the `5` at the start of the long literal selects this. It contains four different sets of 32 characters (uppercase letters, lowercase letters, digits and common symbols, and rare symbols), with shift codes to switch between them; and within each set, each character is encoded as two octal digits in the `0`-`5` range (because **`6`** and **`7`** are needed as delimiters). Apart from the reinterpretation of 5 bits as two base-6 digits, this encoding wasn't invented for 7; it is in fact the US-TTY encoding (a variant of Baudot), which was commonly used before ASCII was invented, and which is often a little shorter for commonly used strings than ASCII would be, despite containing all the same characters.
`Hello, Permutations!` requires five shift codes (which can be visualised as `H**ł**ello**Ø**, **Ł**P**ł**ermutations**Ø**!`), so it's 20 + 6 = 25 characters long, thus 50 octal digits when encoded as a 7 literal (51 total when allowing for the `5` to select the encoding). This comes to 18¾ bytes, just slightly shorter than the string would be in ASCII.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~43~~ 37 bytes each
*Saved 5 bytes thanks to @Sisyphus, plus another with further golfing.*
### Quine
```
eval o="print'eval o=%p'%o#g,tHumPs!"
```
[Try it online!](https://tio.run/##KypNqvz/P7UsMUch31apoCgzr0QdylMtUFfNV07XKfEozQ0oVlT6/x8A "Ruby – Try It Online")
### Cat
```
print gets#="'=%'%um,Halve ovalPoop!"
```
[Try it online!](https://tio.run/##KypNqvz/v6AoM69EIT21pFjZVkndVlVdtTRXxyMxpyxVIb8sMScgP79AUen/f4/UnJx8HYXw/KKcFEUA "Ruby – Try It Online")
### Print
```
p"Hello, Permutations!"#v='va =%p'%og
```
[Try it online!](https://tio.run/##KypNqvz/v0DJIzUnJ19HISC1KLe0JLEkMz@vWFFJucxWvSxRwVa1QF01P/3/fwA "Ruby – Try It Online")
Verify that the three programs are permutations of each other [here](https://tio.run/##Lc3NCsIwEATgu0@xpoRUCAEfIPceexcPUUINJN01f6DWZ4@1ehz4ZiaWy6M1ghPvbTUeUDOKbs7inzgJjt0k81DCmPbsIGEHALzfFEw2p04zobngJcjB@GoB1@qISF/9x2yw3qOE0cZQsskO53Wsq1pUA7@TacNnFQy9FlpIXW8mJpUw5rcqs7ur5J4WtIZjax8 "Ruby – Try It Online").
[Answer]
# [JavaScript (V8)](https://v8.dev/), 31 bytes
```
t=>//==+
'Hello, Permutations!'
```
```
t=l=>//Helo, Permuaions!
't='+t
```
```
t=l=>//Heo, Permutations!=+''
l
```
[Try it online!](https://tio.run/##hVLBTuMwEL37K4YLY6vFgbJdYJHZEyuO3AFRE5LGrGtHttsuIL69jBOVrWgRByvOvPfmzej5SS90LINp08HidLVK6qIolBowvKqs9UO4rsJsnnQy3sU9XJ1PGPuGkwk2Uwhdg7qDGCaFg7RB@CxWA0RmGZvIFMyMCxlbaxLHW3frUMjah0tdNpxb46oh3A8hX6IAdQGvDMDUwG@klLl6J6MPiVo8eeM4ooA9pWCNxpvDuy2GoBYAqQl@Ca5awmUIPnCs567M44HzCTS0/wdGcU6SkiZPUIOCaqFtN1tXb4Nxidf8aHT8Yyyo9EaHFQUcH0LZ6BCBe2efYenD3wjGwR8Tqtr/g9OfB/A4ryB5eJhPRZY0KbXxV1HQ/4uxVsuZ778@TIvY@OU9IbKcmt/mUR2NT85OzkZZR1ntTqlPsGNQFn0wuyJbM@yXcXUbjfqN8p1TLwLEV84fLXnG/aYbDvtBRM/hVuG2KZIpNbdsvR8tgvv735jh1mpZ07/HDc4OM0VEu3oH "JavaScript (V8) – Try It Online")
The comment is placed in the middle of the function to appear in the stringified output.
Alternatively for 30 bytes, but only works in Firefox 86- due to a [bug where the trailing comment is included in the stringified output](https://bugzilla.mozilla.org/show_bug.cgi?id=1579792):
```
t=>'Hello, Permutations!'//==+
t=l=>'t='+t//Helo, Permuaions!
t=l=>l//Heo, Permutations!=+''
```
[Try it online!](https://tio.run/##ZY7LasMwEEX3/orJaiTsyn2ujLILZJl9GhrhSkSpIpnRJKGUfrsrG0Kh3Q33nDvco7mY3JMf@C4P/t3SKcUP@zl2@5H1Etc2hNTApuRnNuxTzAtsW63rgkMRWGPNbVu8m2ZmqZpxmMjfvq4Rq71i8ichVR6CZ4GvEaVyiVamPwgRfLQNvDUwHVmCXsJXBeAdiK1Sakp3Kifi8uCYfBSIEhZaw43m7f3unyHLCwA@ULpCtFdYESUS6M6xn5ZBTAwGht@tKLtS6ctoBgca7MWEeducD@QjCyceHp@eX2SJvmU3/gA)
Or for 32 bytes it can be done without using comments:
```
(t='=+')=>'Hello, Permutations!'
t=l=>('Helo Permuaions!','t='+t)
t=(l='Heo, Permutations!'+'')=>l
```
[Answer]
# [Python 2](https://docs.python.org/2/), 55 bytes each
Each is a lambda function which performs the specified task.
```
lambda t='lambda t=%r:t%%t#Helo,Puins!':t%t#Helo,Puins!
lambda s:s ##!!%%%%'',,:==HHPPaabdeeiilllmnnoorttttttuu
lambda:'Hello, Permutations!'## !%%%%,:==HPabdilnsttttu
```
[Quine it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHEVh3OUi2yKlFVLVH2SM3J1wkozcwrVlQHiqAI/C8oyswrUUjT0PwPAA "Python 2 – Try It Online"), [Cat it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHYqlhBWVlRURUI1NV1dKxsbT08AgISE5NSUlMzM3NycnLz8vLzi0rAoLT0f0FRZl6JQpqGempyRr665n8A "Python 2 – Try It Online"), [Print it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNykl0UrdIzUnJ19HISC1KLe0JLEkMz@vWFFdWVlBURUIdKxsbT0CEpNSMnPyikuAoPR/QVFmXolCmobmfwA "Python 2 – Try It Online")
[Answer]
## Functions:
# [Haskell](https://www.haskell.org/), 61 bytes (quine)
```
--dHel,Prmuta!
i=c++show c;c="--dHel,Prmuta!\ni=c++show c;c="
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/X1c3xSM1RyegKLe0JFGRK9M2WVu7OCO/XCHZOtlWCVU2Jg9N@n9uYmaebUFpSXBJkULmfwA "Haskell – Try It Online")
Not sure what the rules are for a "function quine" in Haskell. This code defines `i` to be a string containing the given source code.
# [Haskell](https://www.haskell.org/), 61 bytes (cat)
```
--dHel,Prmuta!c++show c;c="--Hel,Prmuta!\n=c++show c;c="
i=id
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/X1c3xSM1RyegKLe0JFExWVu7OCO/XCHZOtlWSVcXSSYmzxZFkivTNjPlf25iZp5tZl5JalFicolC5n@ghpx8hfD8opwUAA "Haskell – Try It Online")
# [Haskell](https://www.haskell.org/), 61 bytes (print)
```
--d,Prmua!c++hw c;c=--dH\=c++shwc;c=
i="Hello, Permutations!"
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/X1c3RSegKLc0UTFZWzujXCHZOtkWKOYRYwvkF2eUg/hcmbZKHkDV@ToKAalAtSWJJZn5ecWKSv9zEzPzbAuKMvNKFDL/AwA "Haskell – Try It Online")
[Verify they're anagrams](https://tio.run/##Xc49D8IgEAbgvb/idCmNLXE0MbiZOLrbJj2RKAZLBcT66yu0OrQMfN29D9zRo@VGtq7wm773aACBJXVRXA5C5UfzeDlcJJLx1cre9Bv4lrPltFqWzaxeJ0mUzsBgJs2YqTJFwqPy8pP4TxqaB@U2dkW9LMfgO16E1DKoSudwFIPspG7sIv6Jh40DVGr/fKEKJBoDbBcXKrwwHwI@nsPEhuJpXUE25rQSVOkr@afJCXM458Ar@sCWdDHXUdsq6UiaZtRq40hG71o28RzGtu@/ "JavaScript (V8) – Try It Online")
---
## Full programs:
# [Haskell](https://www.haskell.org/), 75 bytes (quine)
```
--lid,HelP!
main=putStr$c++show c;c="--lid,HelP!\nmain=putStr$c++show c;c="
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/X1c3JzNFxyM1J0CRKzcxM8@2oLQkuKRIJVlbuzgjv1wh2TrZVglJUUweTlX//wMA "Haskell – Try It Online")
# [Haskell](https://www.haskell.org/), 75 bytes (cat)
```
-- !!""$$++++,,--;;===HHPPSS\cccccdehhillllmnoopprssttuuww
main=interact id
```
[Try it online!](https://tio.run/##Fcw7DsAQAADQvadAbOUEYjdKrF0ECalffOL4qu8Az@v@uhj3phRAiBDG90EIpYxxzoWQUqnH/KzzPsQj5VJqbb2PMedaV9Ih85CHa9oMEOze4pQFrNKi/QA "Haskell – Try It Online")
# [Haskell](https://www.haskell.org/), 75 bytes (print)
```
-- !$$++++,--;;===HPS\ccccccddhhiillnpsww
main=putStr"Hello, Permutations!"
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/X1dXQVFFRRsIdHR1ra1tbW09AoJjksEgJSUjIzMzJyevoLi8nCs3MTPPtqC0JLikSMkDqDdfRyEgtSi3tCSxJDM/r1hR6f9/AA "Haskell – Try It Online")
[Verify they're anagrams](https://tio.run/##dY5Ba4QwEIXv/opRhFXU0GNBsreCR8HjurDZGGqWmKRJ1O2vt0ldoZe@Q2aGmfflPchCLDVcu2p537aFGCCAo1tVCT6UDRNtHE2ES6xn1zmT0qKwo1qB1hQnf476Xv57douiwL0DBs@FOE6SNC28yrKq6hpj3DRt23V9T4MGNo5ceE1SKa2Ntc7N87ruObh0zBDqgA8vLj24L@jBbA8gHQZP9Eip7YHZcyY@u1AltMxMsyOOK2njkJf6xgER4uNrJsJ/QIwBfA4FsYWZ7wyWMPsH/y4vb1fId58SDAn1mR3u7EJKuJdAr2giOnsG3xNZLbjLTqccWWVclqOH4jLMXvW2/QA "JavaScript (V8) – Try It Online")
[Answer]
# [PHP](https://php.net/), ~~71~~ ~~69~~ 67 bytes (quine)
```
eval($o='!Printf ("eval(\$o=%c%s%c);//gHemut",39,$o,39);');//gHemut
```
[Try it online!](https://tio.run/##lY4xb8MgFIR3/wqCQICE6sGTQ6ysHjN1QqoshB0im2fBs/@@S1JV7ZobTne3fLfe1@NyXYv7fZglg06cbilEHImkr8mWjTueuVOmrqfeLxtS3bSaQXFlxN98eHcHQm208dOnMAY3YIB4tpGaqmKZdCRj@srrHFCKX6B9l2j/IUusMiSULJdUvQ48IMRnJx/PLwX9c4ucLLWUMcY5F0JKqZTSWtdFTdO2xpiu6/ubHQbnfNE4TWGelyUCQMqIuG37Ts3xDQ "PHP – Try It Online")
# [PHP](https://php.net/), 67 bytes (cat)
```
!list(, $o)=$argv;ecHo($o);//'Pnf"eval(\=%%%cemut"39,,39)';//gHemut
```
[Try it online!](https://tio.run/##fY5Ba8QgEIXv@RVGDCpIc8gptdJrjntYehKKiElcjIqa/P2saQ8tFPoYhnkzMN@Lazzf3mPtrbO5EAZQoAKptBzc6CmQannf45ufoTmUI1J0XafNthc4jIwNI8X1vkzX5jR6DQBKL/2HSXa2WhUb/Kv0kDcNykCAXNJnjs4Wgv/w2l9A@R9R/iAx5U0OqRCU69R8BXgE6y8PXq4sFf0dC7QSSogQqu8wJoRQShljfdUwjCPnXIhpukmltDZV87JY57bNhxBSLqXs@3FAfp731WZQS3lgfdzLEw "PHP – Try It Online")
# [PHP](https://php.net/), 67 bytes (Hello, Permutations!)
```
ecHo('Hello, Permutations!');//v$=tf("va(\$=%%%cg"39,$,39););//gemu
```
[Try it online!](https://tio.run/##jY6xbsQgEER7fwWHsAAJxYUrh6C0Lq9KhRRZCPs4YdaCtX//gp02RaZY7WhX82Z7bK@Pz61O70YQfPQxgiJ3n9cdJwyQyo1L3XUHMzgLekzCMtO2rVtoPyim@kHq8774da8ZDyDUJpu@fA5zcFfCu01UNw0rxJCC@btsMaDgF9D@SbT/RtbHpkBGwUrdmqvAE0I6PXk7u1T0by1ys9RSxliN4lwIIaVUSnVVfT8MWmtjxvFup8k5XzUvS4hxXRMA5IKI@34cVL9@AA "PHP – Try It Online")
This is the best I've got so far.. still searching
EDIT: I could get rid of the `d` with `list(,$o)=$argv;` instead of `end($argv)`
EDIT 2: saved 2 bytes by moving the space and the `!` inside the part of the quine that doesn't have to be repeated
[Answer]
# [PHP](https://php.net/), 33 bytes
```
!""$,1;;<=?HP[]aeegillmnoorsttuv
```
[Try first](https://tio.run/##K8go@P9fQVFJSUXH0NraxtbeIyA6NjE1NT0zJyc3Lz@/qLikpLTs/38A "PHP – Try It Online")
```
<?=$argv[1];"Hello, Pemuttions!";
```
[Try second](https://tio.run/##K8go@P/fxt5WJbEovSzaMNZaySM1JydfRyEgNbe0pCQzP69YUcn6////wanJ@XkpCgVF@elFibkA "PHP – Try It Online")
```
<?="Hello, Permutations!";$gv[1];
```
[Try third](https://tio.run/##K8go@P/fxt5WySM1JydfRyEgtSi3tCSxJDM/r1hRyVolvSzaMNb6/38A "PHP – Try It Online")
[Verify](https://tio.run/##bY/LDoMgEEX3fgUlJLWJaWq3SNy6dG9NY1qqNAgE0N@3qCXYx3LuPTkzozo1TVmuOhVFiFWnGhCwBzsIUZJinJG8KKu6obRlnPdCSm2sHcY9nuF0gbOcoEa3oxsxLCjnMgEl7QdrmRRmB/EKnz0cGO2gxlNoNTg4Qg/m1jjcWH01ijMbL6cdcGSkdsPSu4neOgmekgkfgSOAFwFnh6E3Ke7fkjRIVuDT8s42Gtsx/WM5B8vSf0rWKDjGRl/vQ69i/xchIGz/23prKP07m3aaXg "PHP – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~38~~ 32 bytes each
-6 bytes thanks to @Kevin Cruijssen
```
0"”Ÿ™,„œmu¦–!”„ SK"0"D34çý"D34çý
,0"”Ÿ™„œmu¦–!”„ SK"0"D34çý"D34çý
0""0"D34çý"D34çý”Ÿ™,„œmu¦–!”„ SK
```
[Try it online quine](https://tio.run/##yy9OTMpM/f/fQOlRw9yjOx61LNJ51DDv6OTc0kPLHjVMVgSKAvkKwd5KBkouxiaHlx/eC6P//wcA "05AB1E – Try It Online")
[Try it online cat](https://tio.run/##yy9OTMpM/f9fx0DpUcPcozsetSx61DDv6OTc0kPLHjVMVgQKAvkKwd5KBkouxiaHlx/eC6P//y9JLS4BAA)
[Try it online Hello, Permutations!](https://tio.run/##yy9OTMpM/f/fQEnJQMnF2OTw8sN7YfSjhrlHdzxqWaTzqGHe0cm5pYeWPWqYrAgUBfIVgr3//wcA)
[Answer]
# [Golfscript](http://www.golfscript.com/golfscript/), ~~40~~ 35 bytes
The following three programs are each quine, cat, and "Hello, Permutations!".
Edit: I could save some bytes realizing that undefined commands are ignored in golfscript.
```
".7<:n;`Hello, Permutatios!".7<:n;`
```
[Try quine online!](https://tio.run/##S8/PSStOLsosKPn/X0nP3MYqzzrBIzUnJ19HISC1KLe0JLEkM79YESb1/z8A)
```
"":n Hello,..<<``:Permutations;77!;
```
[Try cat online!](https://tio.run/##S8/PSStOLsosKPn/X0nJKk/BIzUnJ19HT8/GJiHBKiC1KLe0JLEkMz@v2NrcXNH6/3@IPFd5flFOiiIA)
```
"Hello, Permutations!":n;7..<<``:7;
```
[Try "Hello, Permutations!" online!](https://tio.run/##S8/PSStOLsosKPn/X8kjNScnX0chILUot7QksSQzP69YUckqz9pcT8/GJiHBytz6/38A)
## Explanation:
The whole input is implicitly stored on a stack as a single string.
Also, each element on the stack is implicitly printed when the program halts.
Note that `n` is printed at the end regardless of its value(which is initially newline). Therefore, one should re-define `n` to prevent trailing newlines. On the other hand, one can use this property as `print(end="string")` trick in Python.
1. Quine
```
".7<:n;`Hello, Permutatios!" # Puts this string on the stack. Note that backslashes are escaped.
. # Duplicates the string. Now, there are two identical strings on the stack.
7< # Truncates the original string, so it will be 7 chars long(.7<:n;` to be precise).
:n; # Defines n to be the truncated string.
` # 'Unevals' the string top of the stack. The unevaled string will generate the first half of the source-code when printed.
```
After that, the un-evaled string will be implicitly printed. Also, the truncated string will be printed instead of a newline.
2. Cat
~~'#' marks a comment section in Golfscript. Therefore, the program is identical to the following:~~
'#' is not used anymore.
```
"":n # Defines n to be an empty string. This has the same effect as doing 'print(string, end="")' in Python.
Hello # Does nothing.
,..<<`` # These commands generate and consume the same number of elements, which mean that there is 1 element left ("") on the stack.
:Permutations; # Defines that element to be 'Permutations' and discard it.
77!; # Puts 77 on the stack, 'not' it, and discard it. Does nothing.
```
3. "Hello, Permutations!"
~~Again, behind '#' is ignored.~~
```
"Hello, Permutations!":n; # Defines this string as 'n' to make it implicitly printed.
7..<<``:7; # Again, these are valid commands, but they are arranged to do nothing.
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 396 bytes
# Quine:
```
->+>>++>+++>+>+>+++>>>>>>>>>>>>>>>>>>>>+>+>++>+++>++>>+++>+>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>+>+>>+++>>+++>>>>>+++>+>>>>>>>>>++>+++>+++>+>>+++>>>+++>+>++>+++>>>+>+>++>+++>+>+>>+++>>>>>>>+>+>>>+>+>++>+++>+++>+>>+++>>>+++>+>++>+++>++>>+>+>++>+++>+>+>>+++>>>>>+++>+>>>>>++>+++>+++>+>>+++>>>+++>+>+++>+>>+++>>+++>>++[[>>+[>]++>++[<]<-]>+[>]<+<+++[<]<+]>+[>]++++>++[[<++++++++++++++++>-]<+++++++++.<],
```
[Try it online!](https://tio.run/##hY9LCoAwDETv4RXGeoKQi4QsVBBEcCF4/lqbaq34Cf3Q6eR12i3tOA9rP3nvGMxAGGGy7Q9lV@aKDbvwV@BkPall3wnMxiPHEeT6Ll9ACV7mesPEBC@gnOgLc/sJIBJWYY0NQkpO45lAMAGaDGaRXS@KnWatIa0r7zc "brainfuck – Try It Online")
This is basically the [shortest known brainfuck quine](https://codegolf.stackexchange.com/questions/69/golf-you-a-quine-for-great-good/68506#68506), extended a little bit, so it contains an extra `,` that is needed for the cat program.
# Cat:
```
+[-[+.[-]],][>>>+>+++>+>+>+++>>>>>>>>>>>>>>>>>>>>+>+>++>+++>++>>+++>+>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>+>+>>+++>>+++>>>>>+++>+>>>>>>>>>++>+++>+++>+>>+++>>>+++>+>++>+++>>>+>+>++>+++>+>+>>+++>>>>>>>+>+>>>+>+>++>+++>+++>+>>+++>>>+++>+>++>+++>++>>+>+>++>+++>+>+>>+++>>>>>+++>+>>>>>++>+++>+++>+>>+++>>>+++>+>+++>+>>+++>>+++>>++>>+>++>++<<>+[><+<+++[<]<+]>+[>]++++>++[[<++++++++++++++++>-]<+++++++++<]]
```
[Try it online!](https://tio.run/##hY9LCgIxEETv4Sr7MjlB0/tZeIKmF3FQkEEFUTx@nPzMRBwtAiHVlZfK/uZPl@NjnEKAWIETq7pVYWYwAEbZvyiPcmoO5PQ/pQxqPjndvTewBWuPWmT5Li9ABd73WsOkBiug1ugX5uMnBRgXEUOYQPNASAkaz4qMEol@J7baPNKNhjAYfzbejP7uzO5wfboX "brainfuck – Try It Online")
The only interesting part of this is the `+[-[+.[-]],]`, which is a little overcomplicated cat program. It needs to be like this, so it uses only one comma and still doesn't print an extra null-char at the end.
The rest is just the remaining characters put in brackets, so they won't be executed.
# Hello, Permutations:
```
++>+++>+++>+++>+++>+>+>++>+++>+++>+++>+++>+++>+++>+++>+++>+++>+++>+++>+[[>++++<-]<]>>+>>+>+>+>+>>++>>++>+>++>++>>++>+>+>+>++>[[>++++++++<-]<]>>>+++++>++++>++++>+++++++>++++>>>+++++>++>+++++>+++++>++++>+>++++>+>+++++++>++++++>+++>+[<]>[.>][[[++++++++++++++++++++++++++++++->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<,]]]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fW9tOGx2DIBZhfDg6GkRr2@jG2sTaAfXbQY2xA5lkpw03EsaG8KG6kHRC@HaoBJyDkEZSB1OITCF0Qp0HNDtazy42OjpaGy/QtaM/sAECHanY2Nj//wE "brainfuck – Try It Online")
This actually needed a little bit of brain power. I had lots of `+` and `>` symbols, but only three `-`, one `.` and nine `<` symbols.
So this uses a similar approach like the quine. First, I write a list of how often each character is divisible by 32. This list will be multiplied by 4, then I add to each cell the remaining factor of 8, multiply each cell by 8 and finally, add the remaining units. Then all characters are printed in the usual way. After that, I just dump the remaining characters.
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 27 bytes
## Quine
```
{!,Hello Permutatios":n"}:n
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/v1pRxyM1JydfISC1KLe0JLEkM79YySpPqdYq7/9/AA "GolfScript – Try It Online")
## Cat
```
"":n}{:Hello, Permutations!
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/X0nJKq@22sojNScnX0chILUot7QksSQzP69Y8f//tJT0xLT0xJT0tMQUAA "GolfScript – Try It Online")
## Hello
```
"Hello, Permutations!"}{:n:
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/X8kjNScnX0chILUot7QksSQzP69YUam22irP6v9/AA "GolfScript – Try It Online")
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 37 bytes each
```
"""r00g::ol?!;80.sniotatumeP ,olleH><
>io00.::ol?;80gsntatumreP ,olleH<"""!
"!snoitatumreP ,olleH">o<00.::l?;80g"
```
Quine: [Try it online!](https://tio.run/##S8sszvj/X0lJqcjAIN3KKj/HXtHawkCvOC8zvySxpDQ3NUBBJz8nJ9XDzub/fwA "><> – Try It Online")
Cat: [Try it online](https://tio.run/##DcYxDoAgDADA3VdUZkMYDRodXNz0CyQiNAFKoLwfvelerL73DUkpqTWFfZmVq4kNt1jsDROFYM9VCDH2fjXOjYE9VsD0dxwOw5ALuWIiPDZSqlwMIyX5AQ)
Hello Permutation: [Try it online!](https://tio.run/##S8sszvj/X0mxOC8/sySxpDS3KDVAQSc/JyfVQ8ku38bAQM/KKsfe2sIgXen/fwA)
[Answer]
# R console, 35 bytes
Uses comments in a similar way to most of the other approaches.
```
function(at){'readle(Hlo, Pmts!#)'}
cat(readline())#futton{'Hlo, Pms!'}
cat('Hello, Permutations!')#dnf(){}
```
Character breakdown:
```
' ! # ( ) , { } a c d e f H i l m n o P r s t u
2 1 1 1 2 2 1 1 1 2 1 1 2 1 1 1 2 1 2 2 1 1 1 3 1
```
[Answer]
# [Befunge-98 (FBBI)](https://github.com/catseye/FBBI), 31 bytes each
```
"mHello Peruttions!j~@,k'-a,'
~,'!jHello, Permutations"'-k@
"'k,@-'j~!snoitatumreP ,olleH
```
There are two unprintable bytes: RS (ASCII 30) before the first `'` in the first program, DC3 (ASCII 19) after the first `'` in the third program, and the same bytes in the unused areas of each other program. To represent these characters in the explanations, I have used `<30>` and `<19>` respectively.
## Quine
[Try it online!](https://tio.run/##S0pNK81LT9W1tPj/XynXIzUnJ18hILWotKQkMz@vWFE4q85BJ1tOXTdRR/3/fwA)
```
"mHello Peruttions!<19>j~@,k<30>^S'-a,'
" Begin string mode
mHello Peruttions!<19>j~@,k<30>'-a,' Push the rest of the code as a string
" End string mode
m Not defined in Befunge: reverse direction
" Begin string mode
mHello Peruttions!<19>j~@,k<30>'-a,' Push the rest of the code backwards
" End string mode
- Subtract
a 10 from
,' 44, leaving 34 (the quote character) on top
k Repeat
<30>' 31 times:
, print the top character
@ End the program
```
Mostly a standard quine, but reuses the `a` and `,` characters from `Hello, Permutations!` to help construct a `34`, and the `m` to reverse direction.
## Cat
[Try it online!](https://tio.run/##S0pNK81LT9W1tPj/v05HXTHLIzUnJ19HISC1KLe0JLEkMz@vWEZOSV032@H//5DU4hKFzLyC0hIA)
```
~,'!jHello, Permutations<19><30>"'-k@
~ Get a character from input
, Print the character
j Jump forward
'! 33 spaces, going back to the start
On EOF:
~ Reverse direction
@ End the program
```
A standard cat program, using `j` to skip over the unused section.
## Hello, Permutations!
[Try it online!](https://tio.run/##S0pNK81LT9W1tPj/X0ldOFvHQU5XPatOsTgvP7MksaQ0tyg1QEEnPycn1eP/fwA)
```
"'<19>k,@<30>-'j~!snoitatumreP ,olleH
" Begin string mode
'<19>k,@<30>-'j~!snoitatumreP ,olleH Push this string, ending in "Hello, Permutations!" backwards
" End string mode
k Repeat
'<19> 20 times:
, print the top character
@ End the program
```
Relies on the FBBI-specific behavior that no spaces are pushed when wrapping in string mode.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 50 bytes each
Pretty straight forward solution
1. Quine
```
exec(l:="input('exec(l:=%r)'%l)#Ho, Pmutationsp!")
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P7UiNVkjx8pWKTOvoLREQx3GVy3SVFfN0VT2yNdRCMgtLUksyczPKy5QVNL8/x8A "Python 3.8 (pre-release) – Try It Online")
2. Print the input
```
input(input())#()::==''""%%Hello, Permatos!cceelxx
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/PzOvoLREA0JqaipraFpZ2dqqqyspqap6pObk5OsoBKQW5SaW5BcrJienpuZUVPz/H5KRWawARIl5CmCNAA "Python 3.8 (pre-release) – Try It Online")
3. Print "Hello, Permutations!"
```
input("Hello, Permutations!")#()()::==''%%cceelxxp
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/PzOvoLREQ8kjNScnX0chILUot7QksSQzP69YUUlTWUNTQ9PKytZWXV1VNTk5NTWnoqLg/38A "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Klein](https://github.com/Wheatwizard/Klein) 001, 32 bytes
## Quine
```
:?/:2+@Hello,Permutations!?[[> "
```
[Try it online!](https://tio.run/##y85Jzcz7/9/KXt/KSNvBIzUnJ18nILUot7QksSQzP69Y0T462k5B6f///7rJ/w0MDAE "Klein – Try It Online")
## Cat
```
@:?/:2+Hello,Permutations!?[[> "
```
[Try it online!](https://tio.run/##y85Jzcz7/9/Byl7fykjbIzUnJ18nILUot7QksSQzP69Y0T462k5B6f///7rJ/w0MDP87J5YAAA "Klein – Try It Online")
## Hello, Permutations!
```
"Hello, Permutations!>+?:?:[[@2/
```
[Try it online!](https://tio.run/##y85Jzcz7/1/JIzUnJ19HISC1KLe0JLEkMz@vWNFO297K3io62sFI/////7rJ/w0MDAE "Klein – Try It Online")
[Answer]
# Excel, 136 bytes
## Quine
```
=LEFT(LET(e,CHAR(34),t,"=LEFT(LET(e,CHAR(34),t,!,SUBSTITUTE(t,CHAR(33),e&t&e)),136)022 aillmnoorPusN",SUBSTITUTE(t,CHAR(33),e&t&e)),136)
```
## Cat
```
=LEFT(H2&"e,CeAR(34),t,T=LEFT(LET(e,CHAR(34),t,!,SUBSTITUTE(t,C1AR(33),e&t&e)),136)036 aillmnoorPus)t,SUBSTITUTE(t,CHAR(33),e&",LEN(H2))
```
## Hello, Permutations!
```
=LEFT("Hello, Permutations!FT(LET(e,CHAR(34),t,2,SUBSTITUTE(t,CHAR(33),e&&&)),136)LET(e,CAR(34)t,=LEN,SUBSTITUTE(t,CHAR(33),e&))136",20)
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `D`, 33 bytes
## Quine
```
`q\`:Ė\`+#Hello, Permutations!`:Ė
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=D&code=%60q%5C%60%3A%C4%96%5C%60%2B%23Hello%2C%20Permutations!%60%3A%C4%96&inputs=&header=&footer=)
```
`q\`:Ė\`+ `:Ė # Standard eval quine
#Hello, Permutations! # Ignored but quined string
```
## Hello, Permutations!
```
`Hello, Permutations!`#+:Ė`q\`:Ė\
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=D&code=%60Hello%2C%20Permutations!%60%23%2B%3A%C4%96%60q%5C%60%3A%C4%96%5C&inputs=&header=&footer=)
```
`Hello, Permutations!` # String
#+:Ė`q\`:Ė\ # Ignored
```
## Cat
```
#`Hello, Permutations!`+:Ė`q\`:Ė\
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=D&code=%23%60Hello%2C%20Permutations!%60%2B%3A%C4%96%60q%5C%60%3A%C4%96%5C&inputs=Hello&header=&footer=)
The entire program is a NOP that abuses implicit cat.
[Answer]
# [Perl 5](https://www.perl.org/) + `-p0513`, 45 bytes
## Quine
Pretty standard quine composition with an additional payload of chars needed for the `Hello, Permutations!`.
```
$_=q{$_="\$_=q{$_};eval",!HPimnooqrsttu};eval
```
[Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiJF89cXskXz1cIlxcJF89cXskX307ZXZhbFwiLCFIUGltbm9vcXJzdHR1fTtldmFsIiwiYXJncyI6Ii1wMDUxMyIsIm1pbWUiOiJ0ZXh0L3gtcGVybCJ9)
## Cat
All the code is encased in a string evaluated in void context.
```
q{$_=$_="\$_=q{$_};eval",!HPimnooqrsttu;eval}
```
[Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoicXskXz0kXz1cIlxcJF89cXskX307ZXZhbFwiLCFIUGltbm9vcXJzdHR1O2V2YWx9IiwiYXJncyI6Ii1wMDUxMyIsImlucHV0IjoiSGVsbG8sIFdvcmxkIVxuVGhpcyBpcyBhIGNhdCB0ZXN0LlxuTWVvdy4ifQ==)
## Hello, Permutations!
Sets `$_` to the string `Hello,$"Permutations!` where `$"` defaults to space.
```
$_=qq{Hello,$"Permutations!};q{"$$;==\___avv}
```
[Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiJF89cXF7SGVsbG8sJFwiUGVybXV0YXRpb25zIX07cXtcIiQkOz09XFxfX19hdnZ9IiwiYXJncyI6Ii1wMDUxMyJ9)
I've experimented quite a lot with this before posting, and I'm sure there's a way to reduce this more, but I can't see it yet... I suspect changing the Quine to something different is the key!
]
|
[Question]
[
Your task is to take \$n \ge 2\$ points in 3D space, represented as 3 floating point values, and output the [Euclidean distance](https://en.wikipedia.org/wiki/Euclidean_distance) between the two closest points. For example
$$A = (0, 0, 0) \\ B = (1, 1, 1) \\ C = (4, 0, 2)$$
would output \$\sqrt3 = 1.7320508075688772...\$, the distance between \$A\$ and \$B\$.
The Euclidean distance, \$E\$, between any two points in 3D space \$X = (a\_1, b\_1, c\_1)\$ and \$Y = (a\_2, b\_2, c\_2)\$ is given by the formula
$$E = \sqrt{(a\_2 - a\_1)^2 + (b\_2 - b\_1)^2 + (c\_2 - c\_1)^2}$$
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins
[Answer]
# [R](https://www.r-project.org/), 34 bytes
```
function(...)min(dist(rbind(...)))
```
[Try it online!](https://tio.run/##K/qfm5mXkllcYvs/rTQvuSQzP09DT09PEyiqARLWKEoCyoOFNDVhajWSNQx0gFBTJ1nDUAcIQQwToIiRpiYXFjVoijW5/gMA "R – Try It Online")
This is a nice opportunity to use [R](https://www.r-project.org/)'s `...` syntax to define a function that can accept a variable number of arguments; in this case, the `x,y,z` coordinates of each point.
The `dist` function calculates the pairwise distance between all rows of a matrix, using a chosen method - luckily, the default is 'euclidean' and so isn't specified in this case.
Of course, it could be even shorter if we allow the input to already be combined-together as a matrix, but this wouldn't be so neat...
# [R](https://www.r-project.org/), 23 bytes
```
function(m)min(dist(m))
```
[Try it online!](https://tio.run/##K/qfm5mXkllcYvs/rTQvuSQzP08jVxMopgESBDI1/xfkZ@aVFMfnJpYUZVbYFiUB1WskaxjoAKGmTrKGoQ4QghgmQBEjTU0uqIEaKPo0uQgYg2YeTmP@AwA "R – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 33 bytes
```
Min[Norm[#-#2]&@@@#~Subsets~{2}]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zczL9ovvyg3WllX2ShWzcHBQbkuuDSpOLWkuK7aqDZW7X9AUWZeCVDaLs1BOVatLjg5Ma@umqu62kAHCGt1uBSqDXWAEMwyAYoZ1QKZyNLoCmu5av8DAA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
ŒcZ_/²§Ṃ½
```
[Try it online!](https://tio.run/##y0rNyan8H39oU/ChrYf3Jbg93DHf4OHOpkN7/x@dlBwVr39o06HlEP7//9HRBjpAGKsDpw11gBBImwD5RrGxAA "Jelly – Try It Online")
Works with points of any dimension
### Explanation
```
ŒcZ_/²§Ṃ½ # Take as input a list of points, where each point is a list of coordinates
Œc # All pairs of two distinct points [(p1,p2),(p1,p3),...]
Z # Transpose to get two lists of points [[p1,p1,...],[p2,p3,...]]
_/ # Depth-1 vectorizing difference [p1-p2, p1-p3, ...]
²§ # Square coordinates and sum each
Ṃ # Minimum
½ # Square root
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~106~~ ~~95~~ 93 bytes
Saved 11 bytes thanks to [fireflame241](https://codegolf.stackexchange.com/users/68261/fireflame241)!!!
Saved 2 bytes thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)!!!
```
lambda l:min(sum((a-b)**2for a,b in zip(l[p],v))**.5for q,v in enumerate(l)for p in range(q))
```
[Try it online!](https://tio.run/##dVDBboMwDL3zFbkRV6YK0Klate5HKIdAzYoGISWh2ob4dpYAPeywXJ79nu1nR3/bW6fSuTpf5ka2xVWy5tTWipuh5VxGBex2SdX1TGLBasV@as2bTOf4AKfsX7x0x4eXSA0t9dISb8DT2pO9VB/E7wCzJWMNOzOecYECY0AeOxQOBSYbCkwhx7VC/Fvh@P2q/K2Nl6kHlyeQQ0BfmkpLV2@a@GVRuLbURxCUNyo/qfdaeBmS46EMkS1RnIauV5u66ZSTY4peA3@PRXr@wHILsqcBnALmnr@u4haWxLvKwnCKzErovlaWV@FoJxa9s9FMbNyWyK5vm18@hTD/Ag "Python 3 – Try It Online")
Inputs a list of points as tuples and returns the Euclidean distance between the two closest points.
Works with points of any dimension so long as they are consistent within the list.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
œ€ü-nOtß
```
[Try it online!](https://tio.run/##yy9OTMpM/f//6ORHTWsO79HN8y85PP///@hoAx0gjNWB04Y6QAikTYB8o9hYAA "05AB1E – Try It Online")
**Commented**:
```
œ # take all permutations of the input
€ # for each permutation:
- # take the element-wise difference
ü # between each pair of adjacent points
n # square each number
O # sum all difference-lists
t # take the square root of every sum
ß # take the minimum
```
[Answer]
# [Ruby 2.7](https://www.ruby-lang.org/), ~~79~~ 65 bytes
*Saved a whooping 14 bytes, thanks to [Sisyphus](https://codegolf.stackexchange.com/users/48931/sisyphus)!*
```
->s{s.combination(2).map{_1.zip(_2).sum{|a,b|(a-b)**2}**0.5}.min}
```
[Try it online!](https://tio.run/##dc/BCoMwDAbgu09R8KJSQ9paq4ftRcSDDoQe6uqch019dqe4waYu/yUk8JHcuvIxVacpPLd9C5erKXVd3PW19rgPprD9YGkzWHhq6zU@tJ3ph4KWg1eEpR8EfAwCBDmC0fU4WVJlJMuQzskpyRidszTRPOF5TnJyVC5hoARHiQkqGSeJUtz5sthqvdFZ@jRIxRZdrIhFnAkZc6EEppI5@7uOrWUF63JhXYLA8LfSHbb59v@TCDi9AA "Ruby – Try It Online")
* Expects an array of points!
* TIO uses an older version of Ruby, so `|p,q|p,q` is replaced by `_1,_2` to save three bytes (as suggested by [Dingus](https://codegolf.stackexchange.com/users/92901/dingus)).
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 14 bytes
```
{⊇Ċz-ᵐ^₂ᵐ+√}ᶠ⌋
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wv/pRV/uRripdIDsOJLx1gvajjlm1D7cteNTT/f9/dHS0gQ4QxupEG@oAIZA2AfKNYmNjAQ "Brachylog – Try It Online")
Boring and straightforward.
```
⌋ The output is the minimum of
{ }ᶠ every possible
√ square root of
+ a sum of
^₂ᵐ the squares of
-ᵐ the differences between
z the coordinates for each axis
⊇ for a sublist of the input
Ċ containing two elements.
```
[Answer]
# JavaScript (ES6), 86 bytes
```
a=>a.map(m=([x,y,z],i)=>a.map(([X,Y,Z])=>m=!i--|(d=Math.hypot(x-X,y-Y,z-Z))>m?m:d))&&m
```
[Try it online!](https://tio.run/##fY3NCoJAFIX3PYVt5A7ckaxWwdgTtFeHWQz@5ITjSEqo9O6TE0kFEZzF4eN8nIu8yS67qranjckLWzIrWSQDLVvQDPiAI04CFVkg8BgTTMUMNFsrSu@Qs5Psq6AaW9PDQGMcaYITTQmJ9FEfckJ8X9vMNJ2pi6A2ZyiB8w16LgI9HqLn4ur@SbdCELL6bYQvY5Hd/F3n7P7IH7Ov59mwDw "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // a[] = list of triplets
a.map(m = ([x, y, z], i) => // for each triplet (x,y,z) at position i in a[]:
a.map(([X, Y, Z]) => // for each triplet (X,Y,Z) in a[]:
m = // update the minimum distance m:
!i-- | ( // decrement i; if it was equal to 0
d = Math.hypot( // or the Euclidean distance d:
x - X, // between (x,y,z)
y - Y, // and (X,Y,Z)
z - Z //
)) > m ? // is greater than m:
m // leave m unchanged
: // else:
d // update m to d
) // end of inner map()
) && m // end of outer map(); return m
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
▼ṁẊȯ√ṁ□z-Ṗ
```
[Try it online!](https://tio.run/##yygtzv7//9G0PQ93Nj7c1XVi/aOOWUDmo2kLq3Qf7pz2////6GgDHSCM1Yk21AFCIG0C5BvFxgIA "Husk – Try It Online")
```
▼ # minimum of
ṁ # sums of applying function to
Ṗ # all subsets of input
# (this may include subsets of >2 points,
# but that's ok...)
Ẋȯ√ṁ□z- # the function:
Ẋȯ # apply to all adjacent pairs
# (...that's why it was ok if there were >2 points
# in any sublist)
√ # square root of
ṁ□ # sum of squres of
z- # element-wise differences
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~75~~ 74 bytes
```
g[]=[]
g(x:t)=[(sum$zipWith((**2).)(map(-)x)z)**0.5|z<-t]++g t
f=minimum.g
```
[Try it online!](https://tio.run/##dY5NboMwEIX3nGIUdWGDsWx@AolCT9CuuujCtSrUErAaE1SMilDuTh2gIq1Uz2I8b9737CpvP4rTaRxLITMhnRL1e4MzgdpO3w2qeVamQsh1A0wx0nmDfNzjAbsuo/FlOPhGel4JxjlmWtVKd5qWo85VDRlY9@MrNJ15Mp8PNQhwoK3OX9CcVW1a8DzYvNRF3xRvZg@b6zytZ6V4XwxwPf79jQHB8ScDL6YNXByrLypZMzAc/OllQEIwYksSwYkt2yM7B1IS4DQJAxazlCXxNk2TJMBkRfiEzKgFls5IOKMRjwIextsgTEK2i/ktyv5FrU7njQ1hlLPfZ/cnBdbL/PuJYtiapANy/AY "Haskell – Try It Online")
```
g[]=[] - edge case for combinations
g(x:t)=[ ... |z<-t]++g t
- combinations
(sum$zipWith(\a b->(a-b)**2)x z)**0.5
- compute hypo..
f=minimum.g - return minimum value found
```
* Saved 1 thanks to @Unrelated String insane idea
`(sum$zipWith(\a b->(a-b)**2)x z)**0.5` becomes
`(sum$zipWith((**2).)(map(-)x)z)**0.5` e.g. we first map
`x` to obtain a list of partially applied subtractions , then
we zipWith `(**2).` (read "compose with square") which firstly finishes the subtraction
and then computes the square.
If I understood correctly O.o
[Answer]
## [Octave](https://www.gnu.org/software/octave/)/MATLAB with Statistics package/toolbox, 17 bytes
```
@(x)min(pdist(x))
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0IzNzNPoyAls7gEyNb8n6YRbaAAhNYKhiBorWAC5BnFanIhJLDK/wcA "Octave – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-g`](https://codegolf.meta.stackexchange.com/a/14339/), ~~15~~ 14 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
The spec asks us to get the minimum but the lone test case gets the maximum so I don't know which to output. I've gone with the former but if that's not right then use the `-h` flag instead.
```
à2 ËÕËrnÃx²¬ÃÍ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWc&code=4DIgy9XLcm7DeLKsw80&input=WwpbMCAwIDBdClsxIDEgMV0KWzQgMCAyXQpd)
[Answer]
# Scala 3, 72 bytes
```
s=>math.sqrt((for> <-s;| <-s- >yield(>zip|map(_-_)map(x=>x*x)).sum).min)
```
[Try it online!](https://scastie.scala-lang.org/wDvJ0ypcS7CkSAvEl5klFg)
Accepts a `Set[List[Int]]` so that it can use `-` to ensure a point is not compared to itself.
This is my first time using Scala 3's new control syntax to save 2 bytes.
[Answer]
# [J](http://jsoftware.com/), 29 bytes
```
[:<./@,+/&.:*:@:-"1/~+_*[:=#\
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o61s9PQddLT11fSstKwcrHSVDPXrtOO1oq1slWP@a3JxpSZn5CtoWKdpKmgYAPUZ6CgYgqCOgo6VCZBvpPkfAA "J – Try It Online")
```
[:<./@,+/&.:*:@:-"1/~+_*[:=#\
#\ 1…N
[:= identity matrix NxN
_* times infinity
+ plus
"1/~ the table with the coordinate triples:
@:- a - b and
&.:*: under square
+/ summed
&.:*: reverse square
[:<./@, flatten the table and get the min entry
```
[Answer]
# [Perl 5](https://www.perl.org/) `-MList::Util=min,sum`, ~~81~~ 77 bytes
*@KjetilS shaved 4 bytes.*
```
sub f{min map{@b=@$_;map{sqrt sum map($_-$b[$j++%3])**2,@$_}@_[++$i..$#_]}@_}
```
[Try it online!](https://tio.run/##XY67CoMwGIX3PkWgf0FNlGjrYhB8gHbsFEJQqJDirSYORXz1pr9jyxnOhW8402Pucu/t0pB27c1A@npaq6asQIs92tfsiF36fQ9Ax9BIeFJ6OqswijKG2FZpSSmYJIGjVtg2b@s3aQPJGUoxmTIU@gV7pkJxAFNy8Qf9wqHwn3FyZhysj295wlOOfjXWFcXdma7EqwxvfQE "Perl 5 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~155~~ 147 bytes
Thanks to ceilingcat for -8 and an interesting (ab)use of `hypot`!
Takes a counted array of coordinates.
```
#define g(x)hypot(c[x+j]-c[x+i],
i,j;float f(s,c,d,l)float*c,d,l;{for(l=-1,s*=3,i=0;i<s;i+=3)for(j=i;(j+=3)<s;l=l<0|d<l?d:l)d=g(2)g(1)g()0)));s=l;}
```
[Try it online!](https://tio.run/##XZDdUoMwEIXv8xQ7deokEDq06I0h@iC1F5gQXCYSh1D/al9dDMF21MlkNnv2zNkPVNYoNY4XujbY1dDQN/b4/uwGqrZvabvLpoI7TpC3wlhXDWCo54prblnsk/gWB@N6amW25j6RBUeZCyy9wFQWbBq1EgVtpy6oVtoy/9SlvdM3lmnZ0A1r6DpcljPGhJdWHMcL7JTd6xpKP2h0q8db8key@DBpBLsBnirs6ItDzeBAAGbSRDnXay@CMHmQQ8tBuX03CDKZAlbsAit4VXWGLpZ6weES2W2QTF/XdI5gcyzA3EpVWesULZKQ6fGjdobGlYE92uYvDhltGTyhpCmLAzgvMtOiOW7b7lgkAnjuA2nkuIGlue@CKU0jJA8/HjmceKY9R3IcC8jjWcdzFV4bcnVW5tnmpxbk@uz@N4H1KmrklPcr9UsZWzV@zOzTmL1@Aw "C (gcc) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes
```
I₂⌊ΦEθ⌊E…θκΣXEλ⁻ν§ιξ²κ
```
[Try it online!](https://tio.run/##NYpPC8IgGMa/ynt8BYNY3TqFEHQYjHYUD2LCZE43p7U@vTkpeOD591ODDMpLm3MXjIvI5BqxX5IM@uF9xNY4M6UJb8ZGHbCVMy4U/ute2UdZzQZfj5FQ6MvR@fePtpVOKzoK13h3T72hobARUtCGkOpj9UvOnPMjhV2CAm8KUbTHc11PQoh8eNkv "Charcoal – Try It Online") Link is to verbose version of code. Takes `n`-dimensional vectors. Explanation:
```
θ Input list
E Map over vectors
θ Input list
… Truncate to length
κ Outer index
E Map over remaining vectors
λ Inner vector
E Map over coordinates
§ιξ Coordinate of outer vector
ν Current coordinate
⁻ Difference
X ² Squared
Σ Summed
⌊ Take the minimum square sum
Φ κ Filter out minimum of empty list
⌊ Take the minimum
₂ Take the square root
I Cast to string
Implicitly print
```
[Answer]
# [Factor](https://factorcode.org/), 67 bytes
```
[ dup [ v- norm ] cartesian-map [ head ] map-index concat infimum ]
```
[Try it online!](https://tio.run/##ZU4xDsJADNvvFeYBRYCY4AGIhQUxVQzRNVVP0GvJ5RAI9e0lrcSEvDi2I7smr52Ml/PxdNihljduLJHvaEmb5ZMnNyHxI3P0nNALq757CVGxd8fTDskLqW@cW0A5KULssyb3ccDHsJoxGFvPmNjWlI2x4S/znx7cMJaoco8SzwKxkxZXeBIrCxSLlianYapMtqMIseIXfBc9TWPq0Gb7GM36LeyyzhOX8HcmGb8 "Factor – Try It Online")
Evaluates self-cartesian-product by vector distance, takes the lower triangular matrix (without diagonals), and evaluates the minimum of all values.
```
[ ! anonymous lambda
dup [ v- norm ] cartesian-map ! self-cartesian-product by vector distance
[ head ] map-index ! for each array at index i, take first i elems
concat infimum ! minimum of all values
]
```
---
# [Factor](https://factorcode.org/), 73 bytes
```
USE: math.combinatorics
[ 2 [ first2 v- norm ] map-combinations infimum ]
```
[Try it online!](https://tio.run/##ZY/BagJBDIbv8xTpAyit9LQ9l@LFi3iSHsYxq6FuZk0ygsg@@xpn60l@CB/Jn/CnjcmyjJv1cvXTwB8K4wm6aMda5hL5gDpxlj3KhBd8bP3328LJKLNCL2h27YXYQPFckJMvK5qXLEZ8gK@wXDWgSaKlYwhvYKgGxH0xDbcAcHO9Vw1OH1UP@vTOwml48by6hzD4R9/NlC/lbkccPTAlDVu/soWWRG0Blxlwlg5@3dnPnsb6C3FLXfHR6KNnzlysBp1DOmGU8Q4 "Factor – Try It Online")
Factor has a built-in for generating combinations, but it is way too long (`USE: math.combinatorics map-combinations` is already 40 bytes).
[Answer]
# Python 3, 79 bytes
I'm new here and not completely sure this follows the rules, LMK if this isn't valid!
```
lambda p:min(sum((a-b)**2for a,b in zip(x,y))**.5for x in p for y in p if x!=y)
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `ḋ`, 9 bytes
```
∪2ḋƛ÷∆d;g
```
```
∪ # Delete duplicates
2ḋ # All subsets of length 2
ƛ÷∆d; # Euclidean distance of every subset
g # Minimum
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyLhuIsiLCIiLCLiiKoy4biLxpvDt+KIhmQ7ZyIsIiIsIltbMCwwLDBdLFswLDAsMF0sWzEsMSwxXSxbMiwyLDJdXSJd)
[Answer]
# [Python 3](https://docs.python.org/3/), 82 bytes
```
f=lambda a,*b:[*b]and[min([sum((x-y)**2for x,y in zip(a,q))**.5for q in b]+f(*b))]
```
[Try it online!](https://tio.run/##dY7NCsIwEITvPkWOu3EtaauXQp8k5JBQiwGb/kVoffmY2JwETzP7zbDMtPvH6OoQ@vapB9NppombRnKjtOvkYB3I9TUAbJcdOa/6cWEb7cw69rYTaJox4uKW@JyoUeceuEFUITF/X33CEgQJKpGgjCqiCqqyCqpRUa6Iv5XIiyP5KZffv9d4V0eUEctGNSfGpsU6D3FaWoQYPg "Python 3 – Try It Online")
---
# [Python 3](https://docs.python.org/3/) with SciPy, 58 bytes
```
lambda*a:min(pdist(a))
from scipy.spatial.distance import*
```
[Try it online!](https://tio.run/##dY67DoMwDEV3vsJjgiIUoBNSv6RlcIGolshDiRe@Pg0lU6VOx77nynI4@O3dmM39mXe0rxVbnCw5EVZKLFDKxkRvIS0Uji4FZMK9Ox26ZQOywUdus/EReEsM5OAhtNKql0r0hbpQq6FSq1HOqlb030rJu8v8lPvv3VvZh0vVCOowTw1AiORYGNGeH0mZPw "Python 3 – Try It Online")
[Answer]
# [Fortran (GFortran)](https://gcc.gnu.org/fortran/), ~~206~~ ~~182~~ ~~148~~ 144 bytes
```
function d(A,n);real A(3,n);t=0
do 5 k=1,n-1;do 5 j=2,n;s=0;do i=1,3;s=s+(A(i,k)-A(i,j))**2;enddo
5 if(t==0)t=s;if(s>0.and.t>s)t=s;d=sqrt(t);end
```
[try it online!](https://tio.run/##LY3BDoMgEETvfAVHoGhQ24MSTPwUU6RBDbaw/X66aLOHnTfJzLgjQpxD9XKXyHGZ92GYWCf7nmskK2T4f8Ym5uXKpTeN7Lhc8QWu39EHENKyCYkswWb3DU/wR6CXV@I7LZ2owShiD/qgW0lXjT5hNS3OJKMKnvUI6XYObry6drkQrcZ@e5AH9Y6BMYqDSRp1GlU9B1vDmE7LmvSJwICXQM4dURSPNBSP3FG3Pw)
~~[148bytes](https://tio.run/##PY7RboMwDEXf8xV5jJmpAqwPbZRKfApbwhSKzJa4308dWk1@8L2WfY/nLXOeqP2ZX2LPcVqv19EMeLmAExcapHc3ZjQJF8DkOxwAF2kE6ntaVx3MiIQR1G9OxA1GFSns5fGVtwcniv8LNWvVFUDg2FsVNn3W9xrVdu4wi@@FWbyt9mCJKR8H/Q7t6wlomt4JI2zqrNNs2HsL7IsTXW72NFE48a0co@jLX2bDUA/2fVBWS6lOS6lP0f0T)~~
~~[182bytes](https://tio.run/##LYzNDoQgDITvPIVHyqJB3YuSmvgoJugG3eDy8/5sRdOkM18z0@0MKSyu/my3yTmsy3ccZ97LYQBNZIR0j3I@cyt3kBZb2YPcSRzohIqZszouqltNdseOShHVBSVMEF@lfkB9fwEhOr06Y07mMfqQeARtN54QFST0l/eTahZnmjT5cirxZ/@CdUnIdGHOPVMVDWsrGvYm3/0B)~~
~~[206bytes](https://tio.run/##NYzdDoMgDIXveQovqavGn11BMPFR2MAFJTiQ93f1Z2nSfqfntNOactKh@kwX7Huy2qP2fn3rrF/eCjFygQIkGabEIG/P8pH3GOBvcNIOZ0CnWuwBZxoBmFmL5aCqlYSz6ujDpppDnEES2@M8XaC6PkBZdtIGY1YW1RZT5htIN/GsVANZxYPj0NQ6mDoP8Vyd8bt/kwu5xMxI7nvPmoKKtQUVexJ3Pw "Fortran (GFortran) – Try It Online")~~
\*line 1: sets up array, reads in data
\*line 2: iterates over rows `j`,`k`, and sums the difference-squares
\*line 3: initialises min distance `t`, compares current Euclidean squared distance `s`, taking the lower number, and ignores a distance of `0` (dupe points)
Saved ***24 bytes*** by removing the `allocate` stuff and giving the array preset dimensions. A possible improvement for my other Fortran answers!
Saved another ***34 bytes*** by using a subroutine and moving I/O to the main program. Replaced repeated `enddo`s with a line number. Removed a placeholder variable `q`. Some inspiration taken from [this fortran golf](https://codegolf.stackexchange.com/a/206044/15940). I went looking for a useful intrinsic like [NORM2](https://gcc.gnu.org/onlinedocs/gfortran/NORM2.html#NORM2) or [HYPOT](https://gcc.gnu.org/onlinedocs/gfortran/HYPOT.html#HYPOT) but couldn't find one for this problem.
Saved ***4 bytes*** by replacing the `subroutine` with a `function`
[Answer]
# [Julia 1.8](http://julialang.org/), 52 bytes
```
a>b...=min(>(b...),@.splat(hypot)(b-[a])...)
>()=Inf
```
[Try it online!](https://tio.run/##dY1BT8QgEIXv/IpJvMwklLTqwUuJV038BU0Psy5VNiwlFI0m/vc6LOpN5vDgvW8ep7fgefjYr@B5PScu8FgNGMyd2lLgggvBCJxfts4uWNUYQzvbg@h49hEt1ivpe9MWXj/TWggP3cQz1URZpPEhLvuyZvDgI2THx@Cj25AUyGH5wr1zwCdX2CTOm0NPBObLgu/s5KVmvpAp@1hCRNmwYJFrPykXj/uEvZYhjYOWEb2V9zXNqiXDJWmE@D/a65s/ov@XEN@0pLK//U3nbw "Julia 1.0 – Try It Online")
I feel like there is a better way but I can't figure it out. This will work for bigger dimensions as well
# [Julia 1.0](http://julialang.org/), 53 bytes
```
a>b...=min(>(b...),(b.|>i->hypot(a-i...))...)
>()=Inf
```
[Try it online!](https://tio.run/##dU4xDsIwDNz7Co@OlEYtsDY7Ay@oOhg1FUYhVG1BIPH34DTARizlnLvzOeebZ6ofMZI9GmOaCwe0mFqlBV6WS3t6jtcFqeTEqnQVFlWzD0McrhMwcIDJUe85uBlVAXIIGnB38nhwC5mRptkhKwWSCBLZpqxudY4Th8UHlAkLFmldUrjQxxYrLSUfqbWU4E7eG9UVWalXJTuE/2Cltz9H9dchvMlK8n7zM3Zv "Julia 1.0 – Try It Online")
]
|
[Question]
[
Output/print this block of text:
```
1234567890
2468013579
3691470258
4815926037
5049382716
6172839405
7306295184
8520741963
9753108642
0987654321
```
Acceptable formats include:
* Trailing newlines/whitespace
* List of strings
* List of lists of characters
* List of lists of integers
However, list of integers is not acceptable because the last line is not an integer.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
[Answer]
## Mathematica, 33 bytes
```
Mod[1##,11]~Mod~10&~Array~{10,10}
```
[Try it online!](https://tio.run/##y00sychMLv4fUJSZV6LvoPHfNz8l2lBZWcfQMLYOyK4zNFCrcywqSqysqzY00DE0qP2v@R8A "Mathics – Try It Online") (Using Mathics.)
The cell at 1-based index `(x,y)` has value `((x*y) % 11) % 10`
[Answer]
# [Python 2](https://docs.python.org/2/), ~~48~~ 46 bytes
```
n=10
while n:print('00987654321'*n)[n::n];n-=1
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8/W0ICrPCMzJ1Uhz6qgKDOvREPdwMDSwtzM1MTYyFBdK08zOs/KKi/WOk/X1vD/fwA "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~49~~ 47 bytes
```
n=1
exec"print('01234567890'*n)[n::n];n+=1;"*10
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8/WkCu1IjVZqaAoM69EQ93A0MjYxNTM3MLSQF0rTzM6z8oqL9Y6T9vW0FpJy9Dg/38A "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
⁵×þ`%‘%
```
[Try it online!](https://tio.run/##y0rNyan8//9R49bD0w/vS1B91DBD9f9/AA "Jelly – Try It Online")
Uses Martin's algorithm.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~12~~ 11 bytes
Saved a byte thanks to Luis. I keep forgetting the `&` is a shortcut for duplicating and transposing.
```
10:&*11\10\
```
[Try it online!](https://tio.run/##y00syfn/39DASk3L0DDG0CDm/38A "MATL – Try It Online")
Using @Martin's algorithm: `x*y % 11 % 10`
**Explanation:**
```
10 % Pust 10 to the stack. Stack: 1
: % 1-based range. Stack: [1 2 3 ... 10]
& % Duplicate range. Stack: [1 2 3 ... 10],[1 2 3 ... 10]
% Transpose last range. Stack [1 2 3 ... 10],[1;2;3 ...10]
* % Multiply with broadcasting. Stack: [1 2 3 ...;2 4 6...] (10-by-10 array)
11 % Push 11 to the stack. Stack [1 2 3 ...;2 4 6 ...], 11
\ % Modulus.
10 % Push 10 to the stack.
\ % Modulus
% Implicit display
```
Same bytecount:
```
10t:&*11\w\
```
[Answer]
## [APL (Dyalog)](https://www.dyalog.com/), 13 bytes
```
10|11|∘.×⍨⍳10
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKPdJTM9s8QpJz85@7@hQY2hYc2jjhl6h6c/6l3xqHezoQFIyX@EGgA "APL (Dyalog Unicode) – Try It Online")
A port of [my Mathematica answer](https://codegolf.stackexchange.com/a/128361/8478).
```
∘.×⍨ ⍝ Multiplication table of...
⍳10 ⍝ The list from 1 to 10.
11| ⍝ mod 11.
10| ⍝ mod 10.
```
[Answer]
## CJam (17 bytes)
```
A,:)_f{f*Bf%Af%N}
```
[Online demo](http://cjam.aditsu.net/#code=A%2C%3A)_f%7Bf*Bf%25Af%25N%7D)
[Answer]
## [Retina](https://github.com/m-ender/retina), 59 bytes
Byte count assumes ISO 8859-1 encoding.
```
10$*
1
,1$`
,1+
$_¶
(?<=(¶?.+)+)1
$#1$*
1{10}1?
,(1*)
$.1
```
[Try it online!](https://tio.run/##K0otycxL/P@fy9BARYvLkEvHUCUBSGhzqcQf2salYW9jq3Fom72etqa2piGXirIhSFG1oUGtoT0Xl46GoZYml4qe4f//AA "Retina – Try It Online")
### Explanation
Another implementation of the **... % 11 % 10** algorithm. The fun part of doing it with a regex is that we can take care of both modulo computations at once.
```
10$*
```
Initialise the string to ten `1`s.
```
1
,1$`
```
Replace each of those with a comma, a one, and the prefix in front of that one. This gives `,1,11,...,1111111111`, i.e. a unary range.
```
,1+
$_¶
```
Now replace each of the range elements with the entire string followed by a linefeed. This gives us a 10x10 grid of unary numbers indicating the current column.
```
(?<=(¶?.+)+)1
$#1$*
```
Match each `1` and determine which row it's on by repeating group one that many times. Replace the `1` with that many `1`s. This multiplies the values in each row by the row's 1-based index.
```
1{10}1?
```
Now let's do **mod 11, mod 10** in one step. To do **mod 11**, we'd normally just remove all `1{11}` from the string to be left with the remainders. And then we'd remove `1{10}` after that. But if we just remove ten `1`s plus another if possible, the regex engine's greediness will do **mod 11** for us as long as possible, and if not, then it'll try at least **mod 10**.
```
,(1*)
$.1
```
Finally, we just convert each number to decimal by replacing it with its length.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes
```
11GTLN*11%T%})
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f0NA9xMdPy9BQNUS1VvP/fwA "05AB1E – Try It Online")
Uses Martin's algorithm, as usual.
[Answer]
# Haskell, 43 bytes
```
l=[1..10]
f=[[x*i`mod`11`mod`10|i<-l]|x<-l]
```
[Answer]
# Javascript (ES6), ~~70 64~~ 56 bytes
```
_=>[...1e9+''].map((_,a,b)=>b.map((_,c)=>-~a*++c%11%10))
```
Saved 4 bytes thanks to Shaggy and 8 bytes thanks to Arnauld.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~16~~ ~~12~~ 11 bytes
Turns out this was my 200 (undeleted) answer here :)
Looks like this is the same formula [Martin spotted](https://codegolf.stackexchange.com/a/128361/58974).
```
Aõ
£®*X%B%A
```
[Test it](http://ethproductions.github.io/japt/?v=1.4.5&code=QfUKo64qWCVCJUE=&input=LVI=) (`-R` flag for visualisation purposes only)
* 4 bytes saved thanks to [Luke](https://codegolf.stackexchange.com/users/63774/luke) pointing out that returning an array of arrays was permissible.
---
## Explanation
```
Aõ :Generate an array of integers from 1 to 10, inclusive.
£ :Map over each element in the array, returning...
® :Another map of the same array, which...
*X :Multiplies the current element of the inner function by the current element of the outer function...
%B :Modulus 11...
%A :Modulus 10.
:Implicit output of resulting 2D array
```
[Answer]
# Java 8, 84 bytes
```
o->{String r="";for(int x=0,y;++x<11;r+="\n")for(y=0;++y<11;r+=x*y%11%10);return r;}
```
Uses the same algorithm as [*@MartinEnder*'s Mathematica answer](https://codegolf.stackexchange.com/a/128361/52210): 1-indexed `x*y%11%10`.
**Explanation:**
[Try it here.](https://tio.run/##LY7BbsIwEETv/YpVJCS7gSg@u@YPgAPHtgdjTOXgrCNng2KhfHtqhKWdw86s9k2nH3oXBovd9b4ar8cRDtrh8wPAIdl408bC8bUCnCk6/APDTpfOGoLAZfaXrDwjaXIGjoCgYA27/bOcR1VV8hYiy/9gVu02ybqev4SQsVbVD1b8FSbVZjsVe/5MGyE2ouUyWpoiQpTLKt@kYbr4TCrAR3BX6HNl9uZ9/4LmpW8ayfZNmKgZckQeGTaG4eQ9L9WX9R8)
```
o->{ // Unused Object parameter and String return-type
String r=""; // Result-String
for(int x=0,y;++x<11; // Loop (1) from 1 to 11 (exclusive)
r+="\n") // And append a new-line after every iteration
for(y=0;++y<11; // Inner loop (2) from 1 to 11 (exclusive)
r+=x*y%11%10 // And append the result-String with `x*y%11%10`
); // End of inner loop (2)
// End of loop (1) (implicit / single-line body)
return r; // Return result-String
} // End of method
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~58~~ 52 bytes
*-6 bytes thanks to offcialaimm.*
Uses Martin's algorithm which I have no understanding of how he came up with it so fast. o0
```
r=range(1,11)
print[[x*y%11%10for y in r]for x in r]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v8i2KDEvPVXDUMfQUJOroCgzryQ6ukKrUtXQUNXQIC2/SKFSITNPoSgWxKyAMP//BwA "Python 2 – Try It Online")
[Answer]
# Pyth, 13 bytes
```
mme%*kd11STST
```
[Try it here](http://pyth.herokuapp.com/?code=mme%25%2akd11STST&debug=0)
-1 thanks to [KarlKastor](https://codegolf.stackexchange.com/users/56557/karlkastor).
*Let's duuuuuuupe!*
[Answer]
# [R](https://www.r-project.org/), 19 bytes
```
1:10%o%1:10%%11%%10
```
[Try it online!](https://tio.run/##K/r/39DK0EA1XxVMqRoaArHB//8A "R – Try It Online")
The least "R"-looking bit of R code I have ever written. Uses the same algorithm as [Martin Ender's answer](https://codegolf.stackexchange.com/a/128361/66252) (and almost all the other answers as well). `x %o% y` is the same as `outer(x, y)`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 30 29 19 bytes
```
Fχ«FχI﹪﹪×⁺¹ι⁺¹κ¹¹χ⸿
```
[Try it online!](https://tio.run/##S85ILErOT8z5///9nmXn2w@tBlPv96x8v3MVEB2e/qhx16Gd53ZCKCA@tPN8@6Md@///BwA "Charcoal – Try It Online")
Uses [Martin's formula](https://codegolf.stackexchange.com/a/128361/70347).
* 10 bytes saved thanks to Neil, proving once more that I have still so much to learn...
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 70 bytes
```
f(x,y){for(x=0;x++<10;puts(""))for(y=0;y++<10;putchar(x*y%11%10+48));}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9No0KnUrM6Lb9Io8LWwLpCW9vG0MC6oLSkWENJSVMTJF4JFK@EiydnJAKValWqGhqqGhpom1hoalrX/s9NzMzTABqjAeIAAA "C (gcc) – Try It Online")
[Answer]
# [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 17 bytes
```
[|?[|?a*b%11%z';
```
This, of course, uses Martin's Method. It translates to [this QBasic code](https://repl.it/JCEg/0).
## Explanation
```
[| FOR A = 1 to 10 ([ starts a FOR loop, | delimits the list of arguments;
a FOR loop with 0 args loops from 1 to 10 by default with increment 1.
? PRINT a newline
[| Start a second FOR loop from 1-10, iterator b
? PRINT
a*b%11%z the result of Martin's formula.
'; and suppress newlines/tabs/spaces
```
[Answer]
# C#, 81 bytes
```
_=>{var r="";for(int x=0,y;++x<11;r+="\n")for(y=0;++y<11;r+=x*y%11%10);return r;}
```
Same algorithm as most of the other answers and essentially the C# port of [@Kevins](https://codegolf.stackexchange.com/a/128378/38550) Java answer.
[Answer]
# [Retina](https://github.com/m-ender/retina), 79 bytes
```
12345678902468013579369147025848159260375049382716
.*
$&$&
O$^50>`.
.{10}
$&¶
```
[Try it online!](https://tio.run/##DcirEYNAFABA/@q4QSBu3v9jaCEdZEAgYiIycQxtpYA0drByP/v39d7GAGJR88hCVk8ksSjxIg1kS02yYkcJQy1JDnLoM7SpTfBoT8Nl7QD9IDzv/P/GuAA "Retina – Try It Online")
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), ~~37~~ 24 bytes
```
10,{){\)*11%10%}+10,%}%`
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/39BAp1qzOkZTy9BQ1dBAtVYbKKBaq5rw/z8A "GolfScript – Try It Online")
-13 thanks to a clever trick [Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender) suggested.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 59 bytes
```
f(n,t){for(n=11;++n<121;putchar(t?t%10+48:10))t=n/11*n%11;}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NI0@nRLM6Lb9II8/W0NBaWzvPxtDI0LqgtCQ5I7FIo8S@RNXQQNvEwsrQQFOzxDZP39BQK08VqLL2f25iZp4GUK@GJpADAA "C (gcc) – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~93~~ 85 bytes
```
10$*T
M!&`T+
m`$
;110$*T10$*
1
09876543210
m`(?<=^\1;\1{0,9}(T+))T
C
(?<!C.{108})\S
```
[Try it online!](https://tio.run/##K0otycxL/P@fy9BARSuEy1dRLSFEmys3QYXL2hAsBCK4DLkMLC3MzUxNjI0MDYCyGvY2tnExhtYxhtUGOpa1GiHampohXM5cQHFFZ71qQwOLWs2YYK7//wE "Retina – Try It Online")
[Answer]
## Pyke, 15 bytes
```
TD]UMha*11%`e)P
```
[Try it here!](http://199.195.254.22/?code=TD%5DUMha%2a11%25%60e%29P&warnings=0)
[Answer]
## Pyke, 13 bytes
```
TS F~u0+*i>i%
```
[Try it here!](http://199.195.254.22/?code=TS+F%7Eu0%2B%2ai%3Ei%25)
```
TS - [1, 2, 3, 4, 5, 6, 7, 8, 9]
F~u0+*i>i% - for i in ^:
~u0+ - "01234567890"
* - ^ * i
i> - ^[i:]
i% - ^[::i]
```
[Answer]
# [PHP](https://php.net/), 54 bytes
```
for(;9>=$y++||9>=$x+=$y=print"
";)echo($x+1)*$y%11%10;
```
[Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNKwt7WxVKrW1a2pAjAptIMe2oCgzr0SJS8laMzU5I18DKGqoqaVSqWpoqGpoYP3/PwA "PHP – Try It Online")
# [PHP](https://php.net/), 56 bytes
```
for(;$x++<=9;print"
")for($y=0;$y++<=9;)echo$x*$y%11%10;
```
[Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNKxVKrS1bWwtrQuKMvNKlLiUNEGiKpW2BtYqlRAZzdTkjHyVCi2VSlVDQ1VDA@v//wE "PHP – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 27 bytes
```
1":(10|11|*&>:)"0/~@(i.@9:)
```
[Try it online!](https://tio.run/##y/qvpKegnqZga6WgrqCjYKBgBcS6egrOQTo@bv8Nlaw0DA1qDA1rtNTsrDSVDPTrHDQy9RwsrTT/a3KlJmfkK6QpqKv/BwA "J – Try It Online")
Uses the same trick as in [Martin Ender's Mathematica answer](https://codegolf.stackexchange.com/a/128361/31957).
[Answer]
## TECO, 45 bytes
```
1un@i/
/10<@i/01234567890/jl10<qnc0a^t>jtl%n>
```
A (fairly) straightforward implementation of Rod's Python answer.
```
1un !initialize register n to 1!
@i/<nl>/ !insert a newline!
10< !loop for 10 rows!
@i/01234567890/ !insert the mysterious string of digits!
j !move point to start of buffer!
l !move forward past the newline!
10< !loop for 10 digits on a line!
qnc !move point forward by n characters!
0a^t !print the character at point!
> !end inner loop!
j !move point to start of buffer!
t !print (empty) line!
l !move to start of digit string!
%n !increment register n (for next line)!
> !end outer loop!
```
Using <ESC>-terminated inserts and a control character for the ^T command would save another ~~three~~ five bytes, at the expense of readability.
Using Martin's mod-11/mod-10 formula actually makes it longer at 43 bytes using controls for ^A and ^T, mostly because TECO doesn't have a mod operator.
```
0ur10<%run10<qn-10"g-11%n'qn\r0a^Tqr%n>^a
^A>
```
Mod 11 is done in an ongoing fashion by incrementing the number in qn by -11 whenever it exceeds 10. The `qn\r0a^T` sequence inserts the number in the editing buffer as decimal digits, reverses past the last digit, retrieves it from the buffer and types it, essentially doing mod-10.
I expected it to be shorter. Oh, well.
]
|
[Question]
[
We haven't had a [string](/questions/tagged/string "show questions tagged 'string'") question for a while (5 days to be precise), so let's go for one.
Given a string `s` and a positive integer `n`, take every `n`th element of `s`, repeat it `n` times, and put it back into `s`.
For example, if `n = 3` and `s = "Hello, World!"`, every third character is `Hl r!`. You then repeat each character `n` times to produce `HHHlll rrr!!!`. You then replace the original letters with the repeated versions to produce the final product of `HHHellllo, Worrrld!!!`
You are to accomplish this task in the shortest code possible in your language!
# Rules
* This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins
* `n` is guaranteed to be smaller than the length of `s` and greater than 0
* The first character of `s` is where the `n`th characters are taken from, and is always repeated `n` times
* `s` will only consist of printable ASCII (code points `0x20 (space)` to `0x7E (~)`)
# Test cases
```
s, n => output
"Hello, World!", 3 => "HHHellllo, Worrrld!!!"
"Code golf", 1 => "Code golf"
"abcdefghijklm", 10 => "aaaaaaaaaabcdefghijkkkkkkkkkklm"
"tesTing", 6 => "ttttttesTingggggg"
"very very very long string for you to really make sure that your program works", 4 => "vvvvery veryyyy verrrry loooong sssstrinnnng foooor yoooou toooo reaaaally makeeee surrrre thhhhat yyyyour proggggram workkkks"
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
Ḣs×
```
Input is taken as **s, n**.
[Try it online!](https://tio.run/##y0rNyan8///hjkXFh6f/LzY63P6oaU3k//9KHkCJfB2F8PyinBRFJR0FYx0FJef8lFSF9PycNCDfEMhPTEpOSU1Lz8jMys7JBYkZAAVLUotDMvPSgVwzAA "Jelly – Try It Online")
### How it works
```
Ḣs× Main link. Argument: s, n
Ḣ Head; yield s.
This pops the list, leaving [n] as the main link's argument.
s Split s into chunks of length n.
× Multiply each chunk by [n], repeating its first element n times.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 byte thanks to leaky Nun (use Python's string multiplication.)
```
×Jm¥¦
```
A full program, accepting two command line arguments, the string and the number, and printing the result.
**[Try it online!](https://tio.run/##y0rNyan8///wdK/cQ0sPLfv//78HUCRfRyE8vygnRfG/MQA "Jelly – Try It Online")**
### How?
```
×Jm¥¦ - Main link: list of characters, s; number, n e.g. ['g','o','l','f','e','r'], 2
¦ - sparse application:
¥ - ...to indices: last two links as a dyad:
J - range of length of s [1,2,3,4,5,6]
m - modulo slicing by n (every nth entry) [1,3,5]
× - ...action: multiply ["gg",'o',"ll",'f',"ee",'r']
- implicit print >>> ggollfeer
```
[Answer]
# JavaScript (ES6), 46 bytes
Takes input in currying syntax `(s)(n)`.
```
s=>n=>s.replace(/./g,(c,i)=>c.repeat(i%n?1:n))
```
### Test cases
```
let f =
s=>n=>s.replace(/./g,(c,i)=>c.repeat(i%n?1:n))
console.log(f("Hello, World!")(3))
console.log(f("Code golf")(1))
console.log(f("abcdefghijklm")(10))
console.log(f("tesTing")(6))
console.log(f("very very very long string for you to really make sure that your program works")(4))
```
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~84~~ 82 bytes
```
n=>m=>{var s="";for(int i=0;i<n.Length;)s+=new string(n[i],i++%m<1?m:1);return s;}
```
[Try it online!](https://tio.run/##TY4xa8MwEIVn@1cchoCEHdMsHSrLHQqZUii00CFkEKrsHkQnuFMSSvBvd13SIev7vvd4XtY@cZj90YnAG6eRXYRrWUh2GT2cE37Bq0NSkhlp3B/A8Sh6UcqieP@RHGK7PZHvbryB@wwpN3ADfQ8D2JlsH21/PTsGsVVlhsRqsQDtg8GO2l2gMX8bLbWlcPnvKtrjocG6XsVu8xyfNtpwyCcmEDPN5u7JSyJJx9B@MuawQwpqUFUO8rGsVFo9av1nT@U0/wI "C# (.NET Core) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~8~~ 7 bytes
-1 byte thanks to @Emigna
```
ôʒć²×ì?
```
[Try it online!](https://tio.run/##ASYA2f8wNWFiMWX//8O0ypLEh8Kyw5fDrD///0hlbGxvLCBXb3JsZCEKMw "05AB1E – Try It Online")
### Explanation
```
ôʒć²×ì? Arguments s, n ("Hello, World!", 3)
ô Split s into pieces of n (["Hel", "lo,", ...])
ʒ Filter (used as foreach)
ć Extract head ("Hel" -> "el", "H" ...)
²×ì Repeat n times and prepend ("el", "H" -> "HHHel" ...)
? Print without newline
```
[Answer]
# [Proton](https://github.com/alexander-liao/proton), 44 bytes
```
s=>n=>"".join(s[i]*(i%n?1:n)for i:0..len(s))
```
[Try it online!](https://tio.run/##DclBCoAgEADAr5gQrBFSdBOsaz/oEN1S2JBdWf2/OdfJwpWpRd@K38nvWtuPkaDc@EyAIx2rIxNZFLrF2hR6GdOyIFWIoM@QEs/qYknvoA1sPX8 "Proton – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 54 53 bytes
**Edit:** Saved 1 byte thanks to [@Rod](https://codegolf.stackexchange.com/users/47120/rod)
```
f=lambda x,n,i=0:x[i:]and[1,n][i%n<1]*x[i]+f(x,n,i+1)
```
[Try it online!](https://tio.run/##RZHNbsIwEITP5CmWSJWg@EBa1ANqTr3wAJV6iKzKJM5PcWxkG0qePp0NFfkOsbIz65ko5yG2zr6MY50b1R8rRTdhRZdv97ei20tlqyITVhbdk33P5DOGclOvJs8mW49Rh/hdqqAD5VQkiyI9aGOcoC/nTbVMBb0KSg8Hnk5zYsWztlymUvDGh6s0Nc7UcGdwz@93XR3LStdN2/2cTM@eLUzqwaw@gO2@inqfnW2w9IadOHEfTfy7rtoPND@Msw2F6OGi2nka3IWiI6@VMQP16qQpXLym2KrIoqezd41XPf06fwoI2yHsCvg2wCfgE3AA4AzAMYCTAIcBzgMcCTgVcDDgbMDxgBsALgG4B@AqgNuAkMpEJgl/iRJHUVJnaf5t@2RxRoW4qldQ15TnVK7HPw)
[Answer]
## [Alice](https://github.com/m-ender/alice), 25 bytes
```
/
KI /!Iw?&.?t&O?&wWOI.h%
```
[Try it online!](https://tio.run/##S8zJTE79/1@fy9tTQV/Rs9xeTc@@RM3fXq083N9TL0P1/39jLo/UnJx8HYXw/KKcFEUA "Alice – Try It Online")
### Explanation
```
/ Switch to Ordinal.
I Read first line of input (i.e. n).
/ Switch to Cardinal.
! Convert input to its integer value and store it on the tape.
I Read first character from input string.
w Push current IP address onto the return address stack. This
effectively marks the beginning of the main loop.
? Retrieve n.
&. Duplicate current character n times (once more than we need,
but who cares about a clean stack...).
?t Retrieve n and decrement.
&O Output n-1 copies of the current character.
? Retrieve n.
&w Push the current IP address onto the return address stack n
times. This marks the beginning of a loop that is executed n
times.
W Discard one copy of the return address from the stack,
effectively decrementing the loop counter.
O Output the last character. On the first iteration, this is
the final copy of the repeated character, otherwise it's just
the single character we read on the last iteration.
I Read a character for the next iteration.
.h% Compute c % (c+1) on that character, which is a no-op for
for valid characters, but terminates the program at EOF when
c becomes -1.
K Jump to the address on top of the return address stack. As long
as there are still copies of the address from the inner loop, we
perform another iteration of that, otherwise we jump back to the
beginning of the outer loop.
```
[Answer]
# [R](https://www.r-project.org/), ~~82~~ ~~76~~ 75 bytes
```
function(s,n)cat(rep(S<-el(strsplit(s,'')),c(n,rep(1,n-1))+!seq(S)),sep='')
```
[Try it online!](https://tio.run/##FcqxEsIgDADQ3a@gXZqcYei51t29g3Ol4eQuQk1w8OsR5/e0SXropl94cX2W3fAU3eJb/ORQU8lglDFsFZQPWBfPAlbVDkm10zQhUoBMf50p@xnxPBi/Ye1gfFz7aBHGG4sUcveisg8juQu2Hw "R – Try It Online")
A function; takes a string `s` and an integer `n`, and prints the repeated version to stdout.
Explanation:
```
function(s,n){
S <- el(strsplit(s,"")) # characters
r <- c(n,rep(1,n-1)) # [n, 1, 1,...,1], length n
repeats <- r+!seq(S) # extends R to length of S
cat(rep(S, repeats), sep="") # print out
}
```
# [R](https://www.r-project.org/), 55 bytes
```
function(S,n)cat(rep(S,c(n,rep(1,n-1))+!seq(S)),sep="")
```
[Try it online!](https://tio.run/##LcmxCoAwDATQX7GZEoyDuOru7uAstQVB0trq99cUyvHgjkvFd/NQ/Cf2vYLgxkL2eDG5qN2icG0jyzAS9Sa7Bzcizi4uAFQ8WoQVGJy6m6BqOrW3ndp3KgPEE5Uf "R – Try It Online")
Same algorithm as above, but with `S` taken as a list of individual characters.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 51 bytes
```
param($a,$n)-join($a|%{($_,("$_"*$n))[!($i++%$n)]})
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVRRyVPUzcrPzMPyK5RrdZQidfRUFKJV9ICimtGK2qoZGprqwLZsbWa////d9BQ91DXUU8F4hwozgdiEFQA4nAovwgqlwLEiuqa/40B "PowerShell – Try It Online")
Takes input as a `char`-array `$a` and the number `$n`. Loops through `$a` and each iteration either outputs the current letter `$_` or the current letter multiplied by `$n`, based on an index into a pseudo-ternary. The index chooses between the two based off of incrementing `$i` and then modulo `$n`. Those letters are then `-join`ed back together and the string is left on the pipeline; output is implicit.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 8 bytes
```
ËùDV*EvV
```
[Test it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=y/lEVipFdlY=&input=IkhlbGxvLCBXb3JsZCEiIDM=)
### Explanation
```
Ë ùDV*EvV
UmDE{DùDV*EvV} Ungolfed
Implicit: U = s, V = n
UmDE{ } Replace each char D and (0-)index E in U by this function:
EvV Take 1 if the index is divisible by V; 0 otherwise.
V* Multiply this by V. This gives V for every Vth index; 0 for others.
DùD Pad D with itself to this length. This gives V copies of D for every
Vth index; 1 copy of D for others.
Implicit: output last expression
```
I have to credit the idea to use `ù` to [@Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy)'s answer [here](https://codegolf.stackexchange.com/a/144898/42545). I don't know that I ever would have thought of it myself...
[Answer]
# J, 17 bytes
```
(#@]$[,1#~<:@[)#]
```
* `(...) # ]` everything in parens creates the string for J's built in "copy" verb. So, eg, if the left argument is 3, it creates the string `3 1 1` repeated as needed to equal the number of characters in the right arg `]`, which contains the string. Which is to say, `#` solves the problem directly, assuming we can give it the correct left argument: `4` should be `4 1 1 1` repeated, and so on.
* Examining `#@]$[,1#~<:@[`, we see it uses J's shape verb `$` in the middle -- that's the main verb of this phrase...
* To the left of `$` is `#@]`, meaning the length `#` of the right arg `]`.
* To the right of `$` is `[,1#~<:@[`, a 5 verb train. The first train executed is...
* `1#~<:@[`, which means 1 copied `#~` (passive form of copy) one less than `<:` the left arg `[`. This result is passed to the final fork:
* `[, ...` meaning take the left arg, and append the result we just calculated, which is a string of `1`s.
[Try it online!](https://tio.run/##y/qfVqxga6VgoADE/zWUHWJVonUMletsrByiNZVj/2tyKekpqKfZWqkr6CjUWimkFXNxpSZn5CsYGiikKagnJiWnpKalZ2RmZefkqkNlQBLJ@SmpCun5OWnq/wE "J – Try It Online")
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 61 + 18 = 79 bytes
```
using System.Linq;
n=>m=>string.Concat(n.Select((c,i)=>new string(c,i%m<1?m:1)))
```
[Try it online!](https://tio.run/##hZHBS8MwFMbP7V/xHAgJzOJQPNi1HgbiQUGYsIN4iOlrF5fkaZJuFNnfXlM6cLdecvi@75eP9570V5Ic9q1XtoF15wOa7FnZnzyVWngPr44aJwz8pokPIigJe1IVvAhlmQ8uUu8fIFzjeYykSXL64rG1cjn6czjXlA1zGI2yhBqK3halKcpRylZkpQjMZmvUKANjcq54UVo8nKBBuDTLxYO5X3DO@/ysNMKeNGYbpwLGIZDVbPaEWhNsyOnqYsbZDef5BLGiCqEhXcf4YjouPmWFdbNVXzttBuR6mgno3@IwMX03Hd6j6@D/0RQvNS4DanLQUQuBwKHQugMjdgi@dQhhK8JgOvg@3fBAbudj5@3QmSbH9Nj/AQ "C# (.NET Core) – Try It Online")
[Answer]
# Perl 5, ~~37~~, 29 +1 (-p) bytes
-8 bytes thanks to Tom's comment.
```
$n=<>;s/./"@-"%$n?$&:$&x$n/ge
```
[Try It Online](https://tio.run/##K0gtyjH9/18lz9bGzrpYX09fyUFXSVUlz15FzUpFrUIlTz899f9/j9ScnHwdhfD8opwURS7jf/kFJZn5ecX/dQsA)
[Answer]
# [6502 machine code](https://en.wikibooks.org/wiki/6502_Assembly) routine, 50 bytes
```
A0 01 84 97 88 84 9E 84 9F B1 FB F0 20 A4 9F 91 FD C6 97 D0 10 A6 FF CA F0
05 C8 91 FD D0 F8 84 9F A5 FF 85 97 E6 9E A4 9E E6 9F D0 DC A4 9F 91 FD 60
```
This is a position-independent subroutine expecting a pointer to the input string (0-terminated aka C-string) in `$fb`/`$fc`, a pointer to the output buffer in `$fd`/`$fe` and the count (`n`) in `$ff`. It uses simple indexing, so it's limited to a maximum output length of 255 characters (+ 0 byte) due to the 8bit architecture.
**Explanation (commented disassembly):**
```
.rep:
A0 01 LDY #$01 ; init counter to next repetition sequence
84 97 STY $97
88 DEY ; init read and write index
84 9E STY $9E ; (read)
84 9F STY $9F ; (write)
.rep_loop:
B1 FB LDA ($FB),Y ; read next character
F0 20 BEQ .rep_done ; 0 -> finished
A4 9F LDY $9F ; load write index
91 FD STA ($FD),Y ; write next character
C6 97 DEC $97 ; decrement counter to nex rep. seq.
D0 10 BNE .rep_next ; not reached yet -> next iteration
A6 FF LDX $FF ; load repetition counter
.rep_seqloop:
CA DEX ; and decrement
F0 05 BEQ .rep_seqdone ; if 0, no more repetitions
C8 INY ; increment write index
91 FD STA ($FD),Y ; write character
D0 F8 BNE .rep_seqloop ; and repeat for this sequence
.rep_seqdone:
84 9F STY $9F ; store back write index
A5 FF LDA $FF ; re-init counter to next ...
85 97 STA $97 ; ... repetition sequence
.rep_next:
E6 9E INC $9E ; increment read index
A4 9E LDY $9E ; load read index
E6 9F INC $9F ; increment write index
D0 DC BNE .rep_loop ; jump back (main loop)
.rep_done:
A4 9F LDY $9F ; load write index
91 FD STA ($FD),Y ; and write terminating0-byte there
60 RTS ; done.
```
**Example C64 machine code program using it**:
This is a program in [ca65](http://cc65.github.io/doc/ca65.html)-style assembler for the C64 using this routine (imported as `rep`):
```
REP_IN = $fb
REP_IN_L = $fb
REP_IN_H = $fc
REP_OUT = $fd
REP_OUT_L = $fd
REP_OUT_H = $fe
REP_N = $ff
.import rep
.segment "LDADDR"
.word $c000
.code
jsr $aefd ; consume comma
jsr $ad9e ; evaluate expression
sta REP_IN_L ; store string length
jsr $b6a3 ; free string
ldy #$00 ; loop over string
readloop: cpy REP_IN_L ; end of string?
beq termstr ; then jump to 0-terminate string
lda ($22),y ; read next character
sta in,y ; store in input buffer
iny ; next
bne readloop
termstr: lda #$00 ; load 0 byte
sta in,y ; store in input buffer
jsr $b79b ; read 8bit unsigned int
stx REP_N ; store in `n`
lda #<in ; (
sta REP_IN_L ; store pointer to
lda #>in ; to input string
sta REP_IN_H ; )
lda #<out ; (
sta REP_OUT_L ; store pointer to
lda #>out ; output buffer
sta REP_OUT_H ; )
jsr rep ; call function
ldy #$00 ; output result
outloop: lda out,y
beq done
jsr $ffd2
iny
bne outloop
done: rts
.bss
in: .res $100
out: .res $100
```
**[Online demo](https://vice.janicek.co/c64/#%7B"controlPort2":"joystick","primaryControlPort":2,"keys":%7B"SPACE":"","RETURN":"","F1":"","F3":"","F5":"","F7":""%7D,"files":%7B"repn.prg":"data:;base64,AMAg/a4gnq2F+yCjtqAAxPvwCLEimXbAyND0qQCZdsAgm7eG/6l2hfupwIX8qXaF/anBhf4gRMCgALl2wfAGINL/yND1YKABhJeIhJ6En7H78CCkn5H9xpfQEKb/yvAFyJH90PiEn6X/hZfmnqSe5p/Q3KSfkf1g"%7D,"vice":%7B"-autostart":"repn.prg"%7D%7D)**
**Usage:** `sys49152,"[s]",[n]`, e.g. `sys49152,"Hello, World!",3`
**Important:** If the program was load from disk (like in the online demo), issue a `new` command first! This is necessary because loading a machine program trashes some C64 BASIC pointers.
[Answer]
# Java 8, ~~100~~ 76 bytes
```
s->n->{int i,k=0;for(char c:s)for(i=k++%n<1?n:1;i-->0;)System.out.print(c);}
```
-24 bytes thanks to *@OliverGrégoire*.
**Explanation:**
[Try it here.](https://tio.run/##jZHBasMwDIbvfQqtMEhoY1o2dmjajFEY22GnDnYoPbiOkzpxrCA7HaH02TNnlA3GAgVjbCR9@vWr4EceYS1NkZad0NxaeOPKnEYA1nGnBBQ@gzVOaZY1RjiFhj1fHktx4LTdTf/LWaOxTSVp@WqczCUlCQhYdTZKTJSclHGgpuVqFmdIQY8BsbBh/1GrcjK5Ncv5o1nMYxVFySwON611smLYOFaTLw5EGJ@72Kv0p2722gu96D2iSqHyMwQb51Pz7Q542M8DIBiva90G4xepNU7hA0mnN2PmcO0VPBHxNghDxoWQtQvuwvi76m9vbYJL5Ie3xlRCjjobYs2vZ/G9SGWWH1RR6mqQN7se6KR99z4MoR6uJx0ltfB7aTS5d703GfzmoMUGHAJJrnXrV1BKsA1JcAfu@iBBTZgTr@ATqbRDgu6/255H5@4L)
```
s->n->{ // Method with char-array and int parameters and no return-type
int i,k=0; // Index-integers
for(char c:s) // Loop (1) over the characters of the input array
for(i=k++%n<1? // If `k` is divisible by the input `n`:
n // Change `i` to `n`
: // Else:
1; // Change `i` to 1
i-->0;) // Inner loop (2) from `i` down to 0
System.out.print(c); // And print the current character that many times
// End of inner loop (2) (implicit / single-line body)
// End of loop (1) (implicit / single-line body)
} // End of method
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~10~~ 7 bytes
*-3 bytes thanks to Luis Mendo!*
```
tq:ghY"
```
[Try it online!](https://tio.run/##y00syfn/v6TQKj0jUun/f2MudY/UnJx8HYXw/KKcFEV1AA)
Takes input as `n` and then `S` as a string/char array.
```
% (implicit input)
% stack: n
t % duplicate
% stack: n n
q % decrement
% stack: n n-1
: % range
% stack: n [1 2 ... n-1]
g % convert to logical (nonzero->1, zero->0)
% stack: n [1 1 ... 1]
h % horizontal concatenate
% stack: [n 1 1 ... 1]
Y" % run-length decoding, taking the string as first input and recycling
% the lengths [n 1 1 ... 1] as needed
% (implicit output as string)
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~51~~ 46 bytes
Thanks @Laikoni for saving me 5 bytes!
```
n&s=do(m,c)<-zip[0..]s;c<$[0..(n-1)*0^mod m n]
```
[Try it online!](https://tio.run/##RVC7TsNAEOz9FYOFkjNygiMQRbCrNFBQgUSBAjrs9QPfw7o7E4WfN2s3aVYzO6Pd2W2l70mpaTIrX1RW6LRM8s1fN3xk2@3RP5b59YyE2eySm@xT2woa5jhp2RkU0HJ4@YIYXGcCthhNOTp3hlglzAbpPM1AdYY8ijxHQ@FgTSATfBQt@iLyJOFIVjCjTrEgH1yC/R7i2YT0NfCCJomAU0uOIGbf4ijgB2kgbos11skybLoD4ic@yqZ4t05VV3G049bBVoTGqppphlh@lxXVTdv99ErH0QM7Avk33hNH90x@iQ@5FGVNM4diHbV1ONsRwc5ZlTrzH3qCHzlaaGWYRYfB2cZJjZN1vY//AQ "Haskell – Try It Online")
### Explanation/Ungolfed
The operator `c <$ [a..b]` replaces each element of the list `[a,a+1...b]` by `c` - so it's just a golfed `replicate`:
```
do(m,c)<-zip[0..]s; -- with all (m,c) in the enumerated ([(0,a),(1,b)..]) input string, replace with
replicate (1 + (n-1)*0^mod m n) c -- either n or 1 times the character c (note that the list begins with 0, that's where the 1+ comes from)
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~53~~ 52 bytes
```
f=lambda x,n,i=0:x[i:]and n**(i%n<1)*x[i]+f(x,n,i+1)
```
[Try it online!](https://tio.run/##RZHNboMwEITP4Sk2SJWA@JAoVQ@onHrJA1TqIUKVA@anMXZkO2l4ejpLqvAdsNiZ9QziMobOmv00NYWWw6mWdBdG9MU2vx/7vJSmJpNlSf9i3ndphlm5aZLZstmlU1A@fFfSK08FHaPVMT4ora2gL@t0vY4F7QXFhwNP5zmx4lhbr@NS8MaHrRW1Vjdw7@Be3h@6PFW1atqu/znrgT1bmOSTRX0C22MV9T5702LpDTth5jGa@XfdlBtpeWhrWvLBwUWNdTTaKwVLTkmtRxrkWZG/OkWhk4FFRxdnWycH@rXu7BH2irAb4NsAn4BPwAGAMwDHAE4CHAY4D3Ak4FTAwYCzAccDbgC4BOAegKsAbgN8XEZlFPGXSHESFfWGlt@WR6sLKoSkSaCmVBRUpdMf "Python 3 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 57 bytes
```
lambda s,n:''.join(c*[1,n][i%n<1]for i,c in enumerate(s))
```
[Try it online!](https://tio.run/##Rc7BTsMwDAbg@57CTEJtUYQoTBwmxoULD4DEocsha500axJPTgrq05dEPXCJ5O@3Y9@WNFJ4XvXpvDrlL4OCKMKxqh6vZEPdP3StCLKz9@GtlZoYrOjBBsAwe2SVsI5Ns5Ygj5WgO@@6/Sc6RwK@id1wtxfwIkXhDxoQDDmdqd1IXfoBtRntdXK@8NPmCeOXDSbL6wY/yAv8P46CgZg490DZvtAMiYBRObeAVxNCnBkhjSqVkOHGZFh5@CWeYv73IOVxl9WGBF0@Xorq9F4J0HUumvUP "Python 2 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes
```
Nθ⪫ES⎇﹪κθι×ιθω
```
[Try it online!](https://tio.run/##HckxDsIwDEDRvacImy2lE2MvAEhFSCAxhzYCCzdu3QTE6U1g/O8Pj6CDBDbbp7nkY5luUWHBrjkppQwHoQR9mOG/z7niHdC7S9QU9AO9jIUFnt4tVakOmuIK9Gus8kbszHaRWby7ivK4abbWvqxd@Qs "Charcoal – Try It Online") Link is to verbose version of code. Takes input in the order `n`, `s`.
[Answer]
# [V](https://github.com/DJMcMayhem/V), 13 bytes
```
"aDJòylÀpÀll
```
[Try it online!](https://tio.run/##K/v/X0Ip0cXr8KbKnMMNBYcbcnL@/zfm8kjNycnXUQjPL8pJUQQA "V – Try It Online")
This is a really dumb workaround. `òlhÀälÀlÀ<M-->l` should work, but I can't for the life of me understand why, especially since manually doing `lhÀälÀlÀ<M-->l` repeated a bunch of times *does* work.
Hexdump:
```
00000000: 1822 6144 4af2 796c c070 c06c 6c ."aDJ.yl.p.ll
```
Explanation:
```
<C-x> " Decrement the number
D " Delete that number...
"a " Into register 'a'
J " Remove the blank line
ò " Recursively...
yl " Yank the letter under the cursor
Àp " And paste it 'a' times
Àl " Move 'a' times to the right ('l' for right)
l " Move to the right one more time
" (implicit) end the loop
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 12 bytes
```
s*Vzm^Q!d%Uz
```
[Try it here.](http://pyth.herokuapp.com/?code=s%2aVzm%5EQ%21d%25Uz&input=4%0Avery+very+very+long+string+for+you+to+really+make+sure+that+your+program+works&debug=0)
[Answer]
# [Python 3](https://docs.python.org/3/), 58 bytes
Working on golfing it down.
I know there are already other Python answers, but I thought I'd post this one too seeing as it scores pretty well compared to the others, despite being a full function and not a lambda.
Takes input as function parameters, and prints to `STDOUT`.
```
def f(s,n,i=0):
for c in s:print(end=[c,c*n][i%n<1]);i+=1
```
[Try it online!](https://tio.run/##BcG9CoAgEADgvae4hEDrhqKtcu8NGqTJHzqQM9Slp7fve7/6JF5bcz5AkAUZSc9q6yCkDBaIoWxvJq7Ss9PGoh35NjTwsdxqp0kvLUhx@hgTwpVydL1AWFX7AQ "Python 3 – Try It Online")
For one byte less (57), I coded a lambda, however similar answers have already been posted by other users:
```
lambda s,n:''.join([c,c*n][i%n<1]for i,c in enumerate(s))
```
[Answer]
# [Brain-Flak (BrainHack)](https://github.com/Flakheads/BrainHack), 122 + 3 (`-A`) = 125 bytes
I am sure this is too long, but I spent quite a while looking and couldn't find any improvements.
```
([]){{}([(([{}]<>)<{({}<<>(({})<>)>())}{}{}>)<{({}<<>({}<>)>())}{}>]<>)([][()])}({}{}<>){({}{(<()>)}{}[()])}{}{({}<>)<>}<>
```
[Try it online!](https://tio.run/##TYzNCsJADIRfxfY0AT15DYHe@gYelj30R1BcWug15NljoiASmJD5ZjIf03N7TMvLHaWSqqEARa2yECvUmAWxKG4BkWnMHwr9AclSvCmgSoZMhpFJBYMkM1@WzgeyhLr7ZfCr9@O9tf18uu1HW7v@DQ "Brain-Flak (BrainHack) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~12~~ 11 bytes
```
vX‚RNIÖèy×?
```
[Try it online!](https://tio.run/##MzBNTDJM/f@/LOJRw6wgP8/D0w6vqDw83f7/f4/UnJx8HYXw/KKcFEUuYwA "05AB1E – Try It Online")
**Explanation**
```
v # for each letter in the input string
è # index into
X‚ # the list [input_int,1]
R # reversed
NIÖ # with letter_index % input_int == 0
y× # repeat the current letter this many times
? # print
```
[Answer]
# Mathematica, 71 bytes
```
""<>s[[i]]~t~If[i~Mod~#2==1,#2,1]~(t=Table)~{i,Tr[1^(s=Characters@#)]}&
```
[Try it online!](https://tio.run/##TcwxS8RAEIbh3l8xJiB3sIU5xcqVg2u0ECwCFmGFuWSzWbPJyOycEsT96zFXXZqveB/4BpTODii@xtnpOcsen2JVeWOSpJe28umVmpTvtC5UvlOFSRvRJR6D3aZfr0quio9N1IcOGWuxHPf51vzdzG/sR4G9q7JnGwIpeCcOzXWm7szVxQ7UWHAU2kxBsQY81o1tXec/@zCc8XatYmPpR7f0h3X@tjzBZQKNDqIs7KAlholOIARsMYQJBuwtxBNbkA7ljAxfTI5xgB/iPi7v92ae/wE "Wolfram Language (Mathematica) – Try It Online")
saved -2 bytes by listening to user202729
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), ~~23~~ 19 bytes
**Solution:**
```
{,/(1|y*~y!!#x)#'x}
```
[Try it online!](https://tio.run/##y9bNz/7/v1pHX8OwplKrrlJRUblCU1m9ojZaySM1JydfRyE8vygnRVHJ2jj2/38A "K (oK) – Try It Online")
**Examples:**
```
> {,/(1|y*~y!!#x)#'x}["Hello, World!";3]
"HHHellllo, Worrrld!!!"
> {,/(1|y*~y!!#x)#'x}["Code golf";1]
"Code golf"
> {,/(1|y*~y!!#x)#'x}["abcdefghijklm";10]
"aaaaaaaaaabcdefghijkkkkkkkkkklm"
```
**Explanation:**
```
{,/(1|y*~y!!#x)#'x} / the solution
{ } / lambda function with x and y as implicit parameters
( ) / do everything in brackets together
#x / count x, #"Hello, World!" -> 13
! / til, !13 -> 0 1 2 3 4 5 6 7 8 9 10 11 12
y! / y modulo, 3!0 1 2 3 4 5 6 7 8 9 10 11 12 -> 0 1 2 0 1 2 0 1 2 0 1 2 0
~ / not, ~0 1 2 0 1 2 0 1 2 0 1 2 0 -> 1 0 0 1 0 0 1 0 0 1 0 0 1
y* / multiply by y, 3*1 0 0 1 0 0 1 0 0 1 0 0 1 -> 3 0 0 3 0 0 3 0 0 3 0 0 3
1| / min of 1 and, 1|3 0 0 3 0 0 3 0 0 3 0 0 3 -> 3 1 1 3 1 1 3 1 1 3 1 1 3
#'x / take each parallel, 1 2 3#'"abc" -> "a", "bb", "ccc"
,/ / flatten the list, "a", "bb", "ccc" -> "abbccc"
```
**Notes:**
* -4 bytes with different approach
[Answer]
# Excel VBA, 71 Bytes
Anonymous VBE immediate window function that take input from range `[A1:B1]` and outputs to the VBE immediate window.
```
For i=1To[Len(A1)]:[C1]=i:?[Rept(Mid(A1,C1,1),B1^(Mod(C1,B1)=1))];:Next
```
]
|
[Question]
[
A polyglot is a program that runs in several languages.
Your challenge is to:
Choose at least two languages (Different versions count as different languages)
Create a program or function that takes several positive integers (one for each language you chose) and returns a program that:
Is a valid program in all of those languages
When run in language A, outputs the first number; When run in language B, outputs the second number; etcetera. Exiting by error is allowed, as long as the generated program prints the number first
The generator does not need to be in one of your chosen languages.
You can assume the inputted numbers within your chosen languages' limits. For example, if BF is one of your languages, the number for BF will be at most 255.
### UPDATE
Explicitly checking the version number or implementation of the language is forbidden. To differentiate, use differences in language features.
# Scoring
Your score is [code length] / [number of languages]2.
Example:
Let's say you were using JS/Python 3, in a JS program:
```
(x,y)=>`1//1;'''
console.log(${x})
//''';print(${y})`
```
Your score would be \$\frac{53}{2^{2}}\$ = 13.25.
The lower your score, the better.
[Answer]
## [Backhand](https://github.com/GuyJoKing/Backhand), [Turtlèd](https://github.com/Destructible-Watermelon/Turtl-d), [Gol><>](https://github.com/Sp3000/Golfish), [><>](https://esolangs.org/wiki/Fish), [Pushy](https://github.com/FTcode/Pushy), [Wumpus](https://github.com/m-ender/wumpus), [Fission](https://github.com/C0deH4cker/Fission), [Beeswax](https://github.com/m-lohmann/BeeswaxEsolang.jl), [Emoji](https://esolangs.org/wiki/Emoji), [Emotinomicon](https://github.com/ConorOBrien-Foxx/Emotinomicon), [AsciiDots](https://github.com/aaronduino/asciidots), [Cardinal](https://www.esolangs.org/wiki/Cardinal), [Befunge-93](https://github.com/catseye/Befunge-93), [Functoid](https://github.com/bforte/Functoid), [Alice](https://github.com/m-ender/alice), [Befunge-98](https://github.com/catseye/FBBI), [Klein](https://github.com/Wheatwizard/Klein), [PingPong](https://github.com/graue/esofiles/tree/master/pingpong), [Whispers v1](https://github.com/cairdcoinheringaahing/Whispers/tree/v1) and [v2](https://github.com/cairdcoinheringaahing/Whispers/tree/v2), [Thue](https://esolangs.org/wiki/Thue), [Perl](https://www.perl.org/), [Raku](https://github.com/nxadm/rakudo-pkg), [Rail](https://esolangs.org/wiki/Rail), [Self-modifying Brainfuck](https://soulsphere.org/hacks/smbf/)
### Score: ~~3.04 1.3 0.934 0.693 0.605~~ \${\frac{295}{25^2} = 0.472}\$
```
puts'#\ v/v"Z"rH"Z"y"#"Z"#>o<~"`Z"#!
# Z#ZOi@R"Z"Y#_`Z`;[üí¨Züí¨‚û°üò≠Züò≤üòé‚虂訂è©.-$_"Z"x%"Z"
[ #< >Ov"Z"0_F1"Z".# @#
#\ @=.}#"Z">
]; #@ >:#,##_@#1"Z"
#\"Z"@
# <#/.
#-10\Z
"
> 0.0
> Z
> Z
>> Output 2
x::=~Z
::=
x
";
$-|\'main\';print (Z)&&Z
#\-[Z]o]<-[<-]>[+.>]Z'.gsub(?Z){$*.pop}
```
[Try it online!](https://tio.run/##JY9PToNgEMXjdk4xMlhala/UZaGfrIy7Ju4cIGA3pgsLodDQaHsESVx1ZdOlpm48EifoDXCIi/ebl8yfl8nL2bpts7JYWhTiargy2MjvBWuDhKRTb2skYs4BkZCJp3P/QTqPFCecuMFp/3HkDs3n4bTf/Yjf/Yrem/q7qY9N/aVsM5aF6kIAAZKHetrFOPHdSIoi9AlQ0v2J2nShGiIXyUfUY7omin3q5oBCoQ@EHg0VkD1yQgYDNDrKEfK/NE7LQv7BG6jG48mWQQgVGC6Y9ltovTzNF6HlZvl8UWCfB70ey2U74CiNPDvw7EgHV0pHZ2yp52U569/y4NW8VFmabdr2Dw "Ruby – Try It Online") or [Try them all at once!](https://tio.run/##fVXNbttGEEaP3qcYk0ko2hIpO0CRyJbiFG2RAEUdtL2UkkCv@COtTe4Su8vIQuKgT9AAPeXUoMcW6aXP0afwE@QN3FmSoqX8VABnhzsz38x@M0sVK70Q/P5NRvm8pPNEwRDGxCrqbfBFof0ZjS4WlMf@V40SPuU6kYVMUHrFCu4qq/tBzFxkKVMLX8lord96RlSjBi9hK0SXUmdJ3Kz//hJjwEe4Feg22pa9KNVi5StRyiipX4xj2rjKcraq/ZZljtZm8eSscVjnUEzw9bppOi8zRv0Z47XW8JMkakkvq@1G34xJcnHOatkW7SSXhZAavj/9@pvw2eOfngwtv1TSz9jM5yJOwlzEZZYo68i8wRpHMy5yFmFtmy/euUJU50MqqIoYi4VWfhjmlPEw/AxnEZUx4zRrlVu/5nxpyedJc760bp2mLINeBPv3H94SV/JICxa3yke004xhX9jG@GxT36TqPXxQZUtnM7ZV8WENc5ElaK1kXSv0@33oPTaO5/Q5xcIyqlRB9aIZC8bnheBzeIbKM6N8goflgqkikeqw1T5D2Nr8Cb96khdlzZZR1gCJzDZ9JL0oY9ErLuaVpzF/uW1nWSU2N1U@SythNsmUEBu0ABrHA@ioSMgEuNAQlVImXGcrWOKMLYBpFx2tYlE0/RYi3uqBsZgscPt7CkvK8ZbGIFLQeMwJfyKWkJcR4imErBA3exKJPE9kxMwcteqaGESkWNvSAMYiy6hE3HR3wiksqAK8NRxUkmXYHRClNoVn8ZLFye4Ny6ubIhRpNLVShETmWgyN7imNQ@vJhMYdl5BC4sk6qfVjRccQXmQJ78xWOlEdE9MFp9Rp74Hjuld@ZWu/fO7V3t7h/0b42/7ofmVhyhjvhCx5WEgxlzRvPbpQx1M5L3NsSPVtnboDsrNk2BZRIJrjGR9PM@FgoqXjAtKRDiD1lpLppKrAJTvYp1JyJMErqrA2x12rBbDcfQcc71ww3slp0VFadtvUruveUkTNeHzXIGBR1QW1CFkzLPEbL3LCy7wquX71zGK47XcP8La5kAoJITAOLSM4kIXIVvMMh3C4RUn9CcB7aq1JMeDjwaB3MG2bto7FDYbxfWIyrMG3EiGFZkqGn6H9FminRkZnHBPJio47HKLSqbKzqduFDVNTFJt220yIwGB/CAfk5qYotXLsCTz3n1uBJZ@gWFk2Snskjl9ZZ6jsEgAbAjs4ZSc/oOVnOzwLzo7G79/@9i4w4vr3P96/ffM36m/@wefX69d/Xb9@d/36T693J8SAy7soyBjsYxidmjT98NsDXDwbTmwCmP1k6F2ZpCMyPQL7BGA0sLu2HZ7Yxo/YE5QneDmPbd8jdu@gPwmIRUbQ9/oog/oZwWmp8TxwSC4Hg@GrgKAkl8Q6Ind6LyeO@buYOEcVedAJ3Hv3AkTujYOpmB73xse96Wi8742mXwSON1flrPMocF/c2TPDefUf)
My personal constraints were to only use languages where the number can be placed in without modification, which are represented by each of the `Z`s. Ruby is used just as a simple formatter to insert the numbers. A typical output using the numbers 1-25 looks like:
```
#\ v/v"25"rH"24"y"#"23"#>o<~"`22"#!
# 21#20Oi@R"19"Y#_`18`;[üí¨17üí¨‚û°üò≠16üò≤üòé‚虂訂è©.-$_"15"x%"14"
[ #< >Ov"13"0_F1"12".# @#
#\ @=.}#"11">
]; #@ >:#,##_@#1"10"
#\"9"@
# <#/.
#-10\8
"
> 0.0
> 7
> 6
>> Output 2
x::=~5
::=
x
";
$-|'main';print (4)&&3
#\-[2]o]<-[<-]>[+.>]1
```
Explanations coming soon...
[Answer]
# [Python 3](https://docs.python.org/3/), 167 bytes, produces Python 3.0, 3.1, ..., 3.9, 3.10, \${167 \over 11^2}\approx1.38\$
thanks to [SuperStormer](https://codegolf.stackexchange.com/users/70761/superstormer) for refreshing my memory, allowing to add 3.10.
```
lambda r:'try:exec("%s");o=%d\nexcept:0\n'*10%sum(zip("0;int.bit_length;callable;u'';import enum;b''%();f'';breakpoint;(a:=0);{}|{}".split(';'),r),())+'print(o)'
```
[Try it online!](https://tio.run/##JYthS8MwEED/yiiUu9NjZE6d9ugvsSJJl7qwNAlpCptzv70W/PZ4vJeu5RTDfhnabvF6NEe9yQ2UfG3sxfZY1VNFEtv62AV76W0qjeoCPOxUPc0j/riElRIXyta48uVt@C4n6bX32ngrM4C4McVcNjbMoxiAGkmGVZts9TnF9RTUTatIbvff273aTsm7giBAnImR6BFSXjOMBMs/DfiheMdPvOdnfuFXPvAbv38SLX8 "Python 3 – Try It Online")
This works by trying to evaluate expressions code that rely on new language features and updating the output value if successful. By including more subversions, the score could probably be decreased by quite a bit.
| Version | Code | New Language feature |
| --- | --- | --- |
| [3.1](https://docs.python.org/3/whatsnew/3.1.html) | `int.bit_length` | New builtin |
| [3.2](https://docs.python.org/3/whatsnew/3.2.html) | `callable` | New builtin |
| [3.3](https://docs.python.org/3/whatsnew/3.3.html) | `u''` | Old syntax for unicode strings re-added from Python 2 |
| [3.4](https://docs.python.org/3/whatsnew/3.4.html) | `import enum` | New module called `enum` |
| [3.5](https://docs.python.org/3/whatsnew/3.5.html) | `b''%()` | String formatting with `%` for bytes objects |
| [3.6](https://docs.python.org/3/whatsnew/3.6.html) | `f''` | *f-strings* |
| [3.7](https://docs.python.org/3/whatsnew/3.7.html) | `breakpoint` | New builtin function |
| [3.8](https://docs.python.org/3/whatsnew/3.8.html) | `(a:=0)` | Assignment expressions |
| [3.9](https://docs.python.org/3/whatsnew/3.9.html) | `{}|{}` | Dictionary union with `|` |
| [3.10](https://docs.python.org/3/whatsnew/3.10.html) | `a:x=0` | postponed evaluation of annotations is now enabled by default |
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly) => py 2, py 3, Jelly, Vyxal, Brain-Flak: 2.28
```
“1or"”©Ɠ“,Q"
”“£Ỵġcȯ9VĊƤ¿»⁶¹;¹⁾or⁶¹;⁸⁾)
®“(1)”Ɠẋ@Ø(j“"
”⁵
```
[Try it online!](https://tio.run/##y0rNyan8//9RwxzD/CKlRw1zD608NhnI0wlU4gLygKxDix/u3nJkYfKJ9ZZhR7qOLTm0/9DuR43bDu20PrTzUeO@/CII51HjDiBPk@vQOqAeDUNNoOZjkx/u6nY4PEMjCygEMa5x6///llyGhv@N/5v@NwcA "Jelly – Try It Online")
## Explanation
Taking `{α}`, `{β}`, `{γ}` as command line arguments and `{δ}` and `{ε}` from STDIN:
```
1or"{δ},Q"
print(1/2and {α}or {β})
1or"((1)(1)...(1))"
{γ}
```
In Python 2, `1or"{δ},Q"` is an expression and doesn't do anything. The second line prints the number. Since `1/2` is `0` in Python 2, `1/2and {α}` yields `0`, and `or {β}` makes that yield `{β}`. Finally, `{γ}` is an expression and does nothing.
In Python 3, the only difference with Python 2 is that `1/2` is `0.5`, so `1/2and {α}` yields `{α}`, and `or {β}` has no effect since the value is positive and therefore truthy.
In Jelly, each line is a link, and only the last link gets evaluated, so `{γ}` is returned and automatically outputted.
In Vyxal, `1` pushes `1`, `o` pops `a,b` and pushes `a.replace(b, "")` which happens to not error here, `r` does a regex match if the arguments are strings, which also doesn't error, and `"` pairs the top to values, which also doesn't error. Here, Vyxal automatically supplying zeroes when the stack is too small is very convenient. Then, `{δ}` pushes `{δ}`, `,` prints it, and finally `Q` exits the program, and thus the rest of the code doesn't matter.
In Brain-Flak, only brackets matter. The `()` in the print function call don't matter. The main part is `(()()...())` with `{ε}` `()`s in between. This pushes `{ε}` to the stack which gets output. Nothing else is brackets so this is fine.
The `1or` is needed otherwise Jelly complains that `"`, a quick, has no atoms to pop from the command stack, even though the link isn't called. Same goes for `'`, though Vyxal also has a meaning for that that wouldn't work with this idea.
The `(1)` is needed otherwise Jelly complains that `)`, which ends a chain and maps over it, has nothing to pop because `(` seems to just yeet the whole chain. Thus, `1` satisfies Jelly.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `·π™`, => [Grok](https://github.com/AMiller42/Grok-Language), [05AB1E](https://github.com/Adriandmen/05AB1E), [brainfuck](https://esolangs.org/wiki/brainfuck), [Vyxal](https://github.com/Lyxal/Vyxal), [tcsh](https://www.tcsh.org/), [;#](https://codegolf.stackexchange.com/questions/121921/make-a-interpreter), [Vim](https://www.vim.org), [Jelly](https://github.com/DennisMitchell/jellylanguage) - ~~.7778~~ ~~.7755~~ ~~.6719~~ 46 bytes / 82 = .71875
```
\I?\Z?\q\+?*‛. ?`,|echo `?\#\;?*`#dH`?\¶?
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=%E1%B9%AA&code=%5CI%3F%5CZ%3F%5Cq%5C%2B%3F*%E2%80%9B.%20%3F%60%2C%7Cecho%20%60%3F%5C%23%5C%3B%3F*%60%23%0FdH%60%3F%5C%1B%C2%B6%3F&inputs=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8&header=&footer=)
Resulting programs:
[Grok](http://grok.pythonanywhere.com?flags=&code=I1Z2q%2B%2B%2B.%204%2C%7Cecho%205%23%3B%3B%3B%3B%3B%3B%23%0FdH7%1B%0A8%0A&inputs=),
[05AB1E](https://tio.run/##yy9OTMpM/f/f0zDKqFBbW1tPwUSnJjU5I1/BVNkaDJT5UzzMpbksuP7/BwA "05AB1E – Try It Online"),
[brainfuck](https://tio.run/##SypKzMxLK03O/v/f0zDKqFBbW1tPwUSnJjU5I1/BVNkaDJT5UzzMpbksuP7/BwA "brainfuck – Try It Online"),
[Vyxal](http://lyxal.pythonanywhere.com?flags=&code=I1Z2q%2B%2B%2B.%204%2C%7Cecho%205%23%3B%3B%3B%3B%3B%3B%23%0FdH7%1B%0A8%0A&inputs=&header=&footer=),
[tcsh](https://tio.run/##K0kuzvj/39MwyqhQW1tbT8FEpyY1OSNfwVTZGgyU@VM8zKW5LLj@/wcA "tcsh – Try It Online"),
[;#](https://tio.run/##K84o@P/f0zDKqFBbW1tPwUSnJjU5I1/BVNkaDJT5UzzMpbksuP7/BwA ";#+ – Try It Online"),
[Vim](https://tio.run/##K/v/39MwyqhQW1tbT8FEpyY1OSNfwVTZGgyU@VM8zKW5LLj@/wcA "V (vim) – Try It Online"),
[Jelly](https://tio.run/##y0rNyan8/9/TMMqoUFtbW0/BRKcmNTkjX8FU2RoMlPlTPMyluSy4/v8HAA "Jelly – Try It Online")
In brainfuck and ;#, the output is a character, as allowed by [this meta post](https://codegolf.meta.stackexchange.com/a/4719/101522).
Also, ;# only supports \$7\$-bit numbers, so any number higher than \$127\$ will be output modulo \$127\$.
[Answer]
Not quite sure its correctness, since I don't have all environment installed to test this... So I would just mark this answer non-competitive unless someone may test its correctness
# JavaScript (ES6) => ES3, AS, ES5, ES6, ES7, ES8, ES9, ES10, ES11, ES12, 166/102=1.66 (non-competitive)
```
a=>`function f(){return[${a}][[].removeAt?0:9-![].map-![].fill-![].includes-!''.padEnd-!(this.Promise||f).prototype['finally']-![].flat-!''.matchAll-!''.replaceAll]}`
```
Input an array with 10 elements... Output is source of a function...
[Answer]
# Js => Js, Python 3, Python 2, Deadfish~, Deadfish x, brainfuck - Score \$\frac{118}{36} = 3.278\$
I wanted to have a go too!
```
(x,y,z,d,X,b)=>`1//1;'''${'i'.repeat(d)}oh${'x'.repeat(X)}k
_=>${x}
//''';print(1/2and ${y}or ${z})#${'+'.repeat(b)}.
```
Ok, the generated code will look something like this, where `{a}` to `{f}` are the inputs:
```
1//1;'''{'i'*{d}}oh{'x'*{e}}k
_=>{a}
//''';print(1/2and {b}or {c})#{'+'*{f}}.
```
And let's pick it apart.
```
1//1;'''{'i'*{d}}oh{'x'*{e}}k
_=>{a}
//''';print(1/2and {b}or {c})#{'+'*{f}}.
```
This is the standard JS/Python polyglot structure. Everything except the `_=>{a}` and the 1 at the top (which is a NOP anyway) are ignored.
```
1//1;'''{'i'*{d}}oh{'x'*{e}}k
_=>{a}
//''';print(1/2and {b}or {c})#{'+'*{f}}.
```
In Python, `//` is an operator, so we can just add a NOP expression, followed by a multiline string so all the JS stuff is ignored. The difference is (copied from hyper) that 1/2 in python 2 is 0, but in Python 3 it is 0.5, which is truthy.
In Deadfish~, the only bit that matters is the `i`s at the start, followed by `oh`. `i` increments the accumulator, `o` prints it and `h` halts the program.
Deadfish X is basically the same, but with `x` and `k`, and no halt. Fortunately, it's not like any `k`s are going to show up in the rest of the program, so we should be safe.
Finally, for brainfuck, there's a string of plusses appended to the end, along with a `.` to print. This outputs by charcode, because numbers are a pain.
[Try it online!](https://tio.run/##PctLCoMwFEDRuasoVEgefTWNbUei63BWo4nVVhKJUvyQtacZObpw4XzET0yN7cf5qo1Uvs09XXDFDSWWWENeVJwxnhFC4p30JLFqVGKmEpzpwlmOU4L7Rq@8iPfFRYwFkI221zPlLBVanuJ9dcaGbA7OQV4OWYNLKt8YPZlBJYN505bekGOKd3zgE8D/AQ "JavaScript (Node.js) – Try It Online")
[Try](https://tio.run/##HYu9DoIwFEZ3n@JLHApRqTBKcHNw0YXd1P7IlaaX0Er06RE9yVlOcp5qUlGPNKRdYGNnKXG5tqcD2s7CWEfBGrhX0Ik4iAiFOyWkkXT/QWIorW2MW0TGWUwWyphlUHDNP0GrsOg9KBWYSynLWghBRNy9F/qVa27Ncb@Scsn1MFJIWSkrFQxKHlHl682PYtYcIntbeH5kLsvz@Qs) [All](https://tio.run/##K6gsycjPM/7/31Bf39BaXV09MzMzP6MCCLK54m3tDLj09YGC1gVFmXklGob6Rol5KQqG@UUKRprK2iCg9/8/AA) [The](https://tio.run/##K6gsycjPM/r/31Bf39BaXV09MzMzP6MCCLK54m3tDLj09YGC1gVFmXklGob6Rol5KQqG@UUKRprK2iCg9/8/AA) [Test](https://tio.run/##S0lNTEnLLM7Q/f/fUF/f0FpdXT0zMzM/owIIsrnibe0MuPT1gYLWBUWZeSUahvpGiXkpCob5RQpGmsraIKD3/z8A) [Cases](https://tio.run/##fVZtjxo3EP6@v2KyqIItdGHvJW0h8CGXnHRKK1Vq1EY6nZAxXnBvsRfbGxZF/e3XsfcFc2xqAbJnxjPPvJr8aLZSXL@89OADI@uU6y2U8IeSG0V2Oy428BsRm4JsWNCD90dIuWJpdry5TvD8ecs14CdVjAERaygEE7TYrZhia9AyNQeiGCiWMaKRwoWRYLYM8mKVcQpruSNcxKjpL665gXdbY/LpeFwI5DKhWSzVZryAVCp3LS2yDDeIKg6CEuYwmQVpIaggO4anMJwFtFCWUp8yoo3d9/uVoOFSaDx/@3cWBPvlPOQzflTECGVgQ8yOf80lXlvu54@TESQ3@P0Zv7@MALdvcYfU2xEg7dcRXOE5GQEyE7u1bOQl1yPAT/I0CwxRaOsRd9YBju7Dcj8FJMckz5lYD/bLR/4UOcl5GMb/SC4GuEdKwHe5RFQHtlopedBMIW3NUpB4sXym64EodtE0AFwnmdhyB2EdRisWU7kbh0NtlLswDMdhVGvKlaRM6wGNptC754IbBn8agr@/E4pBZk75JpMrkkE5809N0M@IdejPaC4BF1ddGioqT6F8NwGMT7m4ur2tHLKrnE9aiUGdR0zkl75Fe8Byw8LSGCtja5S0atv7Xl3UAOzKFdbgILyvpSsNUwiHNDoJeVUDPS0tAlt9ThtW@51F@wWjjvUr@qaJI3DTalDMFEp04b/z8bOS0eJ7DtRQPzoZ1vL/H6yF6Bqk5Vvz1JZeG/joFGQXKPRmfybwSJ8QI7W@GvLMxJl4Ba2qnL2Hg2WanSt@Hes@Ah@GfYwa0yCkQfe5NnHoKXkVtzaHb2w7uwlD7R6jiAD/roKIyL8fvYeTW76dZkoMz4qjCSXtBtSjW0afARtqh0j0qNXckiAnWscNepfwsAy9mh7Ok0oXy1qBZ0@gQm2btYyiC0nqq/pxXl4IrH2BnzpsffFtIdYLgU8XYOjWghnhtMIJdYnpzrtwkbHOeviIWbzvyElX57U9xuou6Mh00@xV6TYAnmwe/YHUMRfsC@Gzzt8On@OXgef8h7BjXnlV5MbshpkHkRcurU513X@dgxXHUVv9KD@f@0HkIkcF3CkLFwvA6NmixPfZNT12qwRFDstKIrI6Cm2nS@4eebiKy@CyVSutaKw17Chzi@Uk1T47yeRt8sP17U2dOTs93HjBS37pNE/L6SXTRyy31At9hk@Mrh9ItJrhy4UyMVGbr9EiqZQ18g3jMamE09dFZtTxZD61Hrmn0MmNQuUXWmM3zWOFf3ncceDxkU4zqVlDYyVluXndF@GdLLK1m2PWEv4xypgdcc4ijjk312q3nIloMZm2IbMUGzXHOalua8XS8f4pU2f@HbbW2GdVvJq47fUz5PCJHVeSqPWDMEyposOX90f2BvG@vCTjcTLr9/ucc7ktcT0Hy/liEozHSJxV0sn4yk7iBN24inpDu@L/AA) [Online!](https://tio.run/##SypKzMxLK03O/v/fUF/f0FpdXT0zMzM/owIIsrnibe0MuPT1gYLWBUWZeSUahvpGiXkpCob5RQpGmsraIKD3/z8A)
[Answer]
# [PHP](https://php.net/) => MY-BASIC, PHP 7, PHP 5, PHP 8, Perl 4, Perl 5, : 111 bytes
## Score: 111 / 36 = 3.08
```
fn($a,$b,$c,$d,$e,$f)=>"\$n.=\"$a\";
print \$n.''&0+true?0==''?eval('return 1<=>2;')?$b:$c:$d:(-1**2+1?$e:$f);"
```
[Try it online!](https://tio.run/##FcxLDoMgFAXQOasw5KagvjZiPwMQ2YgTPxCbNJQY7fZpOz2Dk9aUO5fWxBBsDlFiJEyEmbAQPCGUtucD4sUOHOPADUvbM@7Fn4Q4NfW@Hd411grh/Gd8SbH5/dhioTrbt0aUDpPGrLFoeVZV1dbKwevfa3g2jPl5fRcIUlFLV7rRnR6lyV8 "PHP – Try It Online")
**Code generated with 1, 2, 3, 4, 5, 6:**
```
$n.="1";
print $n.''&0+true?0==''?eval('return 1<=>2;')?2:3:4:(-1**2+1?5:6);
```
Relies on my usual trick, `true` added to a numeric value is `1` in PHP but is ignored by perl. And in Perl 4, negation operator `-` takes precedence over exponentiation `**` while in Perl 5 it is the contrary.
Quick answer, I'll try to add languages or shorten the generator later..
**EDIT**: -1 byte, the last `;` is not necessary for an arrow function definition, it belongs to the assignment to the header's variable (moved to footer)
**EDIT 2**: -1 byte by removing the round brackets for `print` and using a space, works in both languages
**EDIT 3**: added MY-BASIC language using these tricks:
* `.` seems to be a valid character for variables names in MY-BASIC, while it's the concatenation operator in PHP and Perl. Allows at the same time to declare a value for `$n.` in MY-BASIC and `$n` for the others (by concatenation to the undefined var). Double quotes are needed here because of the next point.
* `'` is the single line comment in MY-BASIC, so the rest of the line is ignored after the var output
* for the other languages, it concatenates an empty string and then we remove the value of `$n` so that the value is zero like before the edit (thank you, loose types languages!)
**EDIT 4**: taking in account the inputs are positive integers, I removed the single quotes for PHP and Perl
**EDIT 5**: added distinction between PHP 5, 7 and 8:
* `0==''` was true before PHP 8
* the spaceship operator `<=>` didn't exist before PHP 7. An `eval` is needed here, not only for PHP 5 not to throw a parse error, but for Perl versions also, where you can eval any incorrect code without errors. The `return` keyword allows to have a return value for the `eval` call in PHP
* `$n.''-$n` caused an arror in PHP 8, which cannot subtract strings anymore, and was replaced by `$n.''&0` which is actually shorter
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 28 bytes, produces Retina or [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), score 7
```
^
¶
,
$*_
$
$$$*1¶\d+\$*.¶¶.
```
[Try it online!](https://tio.run/##K0otycxLNPz/P47r0DYuHS4VrXguFS4VFRUtw0PbYlK0Y1S09A5tO7RN7/9/Yx0TAA "Retina – Try It Online") Explanation: For an example input of `3,4` the following program is produced:
```
3*_4$*1
\d+\*.
.
```
The first stage operates differently in the two versions. In Retina, `*` is the repetition operator while `$*` is a quoted `*`, while in Retina 0.8.2, `*` is a literal and `$*` is the repetition operator. The result in Retina is therefore `___4*1` while in Retina 0.8.2 it is `3*_1111`.
The second stage simply deletes the `*`, the preceding number, and the following character.
The final stage counts the number of characters remaining, which gives the desired result.
[Answer]
# Zsh => Zsh, Bash, Ruby, Python, 51 bytes, score 3.1875
```
<<Q
'\';print $1||echo $2 #'
0and p($4)or print($3)
```
[Try it online!](https://tio.run/##qyrO@F@cWqJgqGCkYKxg8t/GJpBLPUbduqAoM69EQcWwpiY1OSNfQcVIQVmdyyAxL0WhQEPFRDO/SAGsQkPFWPP/fwA "Zsh – Try It Online")
* `<<Q` essentially just prints the rest of the file, but `$1` to `$4` are replaced by the input values.
The generated polyglot looks like:
```
'\';print 1||echo 2 #'
0and p(4)or print(3)
```
* In Zsh and Bash, backslashes don't work in single-quotes, so what gets executed is `print 1||echo 2`:
+ In Bash, there is no `print`, so the command fails. `||` means "if this command failed, then execute the following one", so `echo 2` gets executed instead
+ In Zsh, `print 1` just gets executed and doesn't fail
* In Python and Ruby, `0and p(4)or print(3)` is what gets executed
+ In Ruby, `0` is truthy, so `p(4)` gets executed
+ In Python, `0` is falsey, so `print(3)` gets executed
[Answer]
# [Python 3](https://docs.python.org/3/) Julia 1.0 => [Julia 1.0](https://julialang.org) and Python 3, 32 23 bytes, score 8 5.75
*Solution by [MarcMush](https://codegolf.stackexchange.com/users/98541/marcmush) using Julia's custom syntax:*
```
a$b="print([$a,$b][1])"
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/P1ElyVapoCgzr0QjWiVRRyUpNtowVlPpP0TIVMVI8z8A)
*My previous score 8 solution:*
```
f=lambda*a:"print([%s,%s][1])"%a
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRK9FKqaAoM69EI1q1WEe1ODbaMFZTSTXx/38A) Julia uses 1-based indexes and Python uses 0.
[Answer]
# JavaScript => JavaScript (V8), Python 3, Python 2, Foo - ~~57~~ 56 bytes, ~~3~~ 4 languages = 3.5
*Thanks to [The Thonnu](https://codegolf.stackexchange.com/users/114446/the-thonnu) for -1 byte!*
```
(x,y,z,w)=>`print( ${x}//${x/y}if 1/2else ${z}#"${w}"
)`
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ivkWb7X6NCp1KnSqdc09YuoaAoM69EQ0GluqJWXx9I6lfWZqYpGOobpeYUpwKFq2qVlVSqy2uVuDQT/mtac0HUp2kY6igY6SgY6yiYaGr@BwA "JavaScript (V8) – Try It Online")
Examples for the numbers 1, 2, 3, and 4:
```
print( 1//0.5if 1/2else 3#"4"
)
```
[JavaScript (1)](https://tio.run/##y0osSyxOLsosKNEts/j/v6AoM69EQ8FQX99AzzQzDcgwSs0pTlUwVlYyUeLS/P8fAA) [Python 3 (2)](https://tio.run/##K6gsycjPM/7/v6AoM69EQ8FQX99AzzQzDcgwSs0pTlUwVlYyUeLS/P8fAA) [Python 2 (3)](https://tio.run/##K6gsycjPM/r/v6AoM69EQ8FQX99AzzQzDcgwSs0pTlUwVlYyUeLS/P8fAA) [Foo (4)](https://tio.run/##S8vP//@/oCgzr0RDwVBf30DPNDMNyDBKzSlOVTBWVjJR4tL8/x8A)
[Answer]
# Python 3 => Python 3, Python 2, Befunge-93; 67 bytes => \$\frac{67}{3^2}\$=7,4444444444...
```
lambda x,y,z:f'\'v\';print(1/2 and {x} or {y})\n#<v"{z}"\n# >:#,_@'
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaFCp1KnyipNPUa9LEbduqAoM69Ew1DfSCExL0WhuqJWIb9IobqyVjMmT9mmTKm6qlYJyFKws1LWiXdQ/w9RnqYBIjPzCkpLNDQ1dVA4Csg8Tc3/hkZcxiZcpmYA "Python 3 – Try It Online")
Upon giving input to the function above (`12`, `34` and `56` used as an example), we will get something like the following:
```
'v';print(1/2 and 12 or 34)
#<v"56"
# >:#,_@
```
First off is Python 3. It ignores the string at the start, then because `1/2` results in `0.5`, `1/2 and 12` will output `12`, and `or`ring with `34` still results in `12` so it gets printed. The rest of the lines are comments.
Then is Python 2, in which the only thing that changes is that `1/2` evaluates into `0`, so `0 and 12` results in `0` and `or`ring with `34` results in `34`, which gets printed.
Then is Befunge-93, where it takes the `v` (single quotes are not an instruction, only double quotes are) and then the `<`, which leads to push mode-ing `65` and then a simple printing loop which leads into `@` and ends the program.
]
|
[Question]
[
Oof! You've been coding the whole day and you even had no time for Stack Exchange!
Now, you just want to rest and answer some questions. You have ***T*** minutes of free time. You enter the site and see ***N*** new questions. To write an answer for each you'll need ***ti*** minutes. Of course, as a dedicated reputation gatherer, you want to answer as many questions as you can.
Can you write a program to calculate which questions do you have to answer to write maximum posts in ***T*** minutes?
## Input
First line of input consists `T` minutes you have for answering, and `N`, how many new questions are on the site.
The second line has N numbers: time you need to answer **qi** question.
## Output
Write either an array or numbers split with space: indexes of questions(counting from 0 or 1 - what is better for you) you should answer in order to write as many answers as you can. If you can't answer any questions, write nothing or anything to express that it's impossible. If there are several variants, write any.
## Examples
### Inputs Possible outputs
`60 5`
`30 5 10 20 3` `0 1 2 4`, `0 1 3 4` or `1 2 3 4`
`10 5`
`1 9 5 7 2` `0 2 4` or `0 3 4`
`5 5`
`1 1 1 1 1` `0 1 2 3 4`
`60 5`
`48 15 20 40 3` `1 2 4` or `1 3 4`
`5 1`
`10`
`1 0`
And of course it's [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), ~~81~~, ~~79~~, 75 bytes
Using the [walrus operator](https://docs.python.org/3/whatsnew/3.8.html#assignment-expressions) `:=`:
```
lambda k,l:[i for j,i in sorted((v,k)for k,v in enumerate(l))if(k:=k-j)>=0]
```
[Try it online!](https://tio.run/##XYrLCsIwFET3fsVdJngXqaU@SvMltYtIE0zTPIix4NfHtCCKMMPAORNe6e5dfQ4xK37Ns7C3UYDBGS1nba9B@QgTatAOHj4mORKyoKErNrisWLqnlVEkSWZKtSK25XY/0Y6bIYeoXSKKHBn2NUNoEKoyh9J6oHT38QX2FcJle5zK4Vc2m/vm37EC8hs)
-2 bytes thanks to @JoKing
-4 bytes thanks to @justhalf
# [Python 3](https://docs.python.org/3/), ~~158~~, ~~137~~, ~~136~~, ~~130~~, ~~127~~, ~~117~~, ~~103~~, 95 bytes
```
def f(k,l):
q=[]
for j,i in sorted((v,k)for k,v in enumerate(l)):k-=j;q+=[i]*(k>=0)
print(q)
```
[Try it online!](https://tio.run/##RclBCsIwEAXQfU4xy4mOkFqqWIkXCVkITTBNTdsYC54@pl0o/OEz70@f9BhDnXNnLFj0NPCWwSyVZmDHCD05cAFeY0ymQ1zI85U9LSub8H6aeE8GB85bf5D9dd5L5fQO/U0KzmCKLiScebZ4EqRqQdAQVKWO5WrNmcXyqYrgsk3nsmzabPjPD4Xm@Qs)
-21 bytes thanks to @79037662 by limiting indentation to 1-space.
-14 bytes thanks to @ mypetlion
-8 bytes thanks to @justhalf
Both solutions ignore `N` parameter.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~9~~ ~~13~~ 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ā<æʒ¹sèO@}éθ
```
Takes the inputs in the order: \$q\_i\$, \$N\$ (which is mostly ignored, see explanation below), \$T\$.
Uses 0-based indexing.
+4 bytes as bug-fix for test case `[1,1,1,1,1]` resulting in `[0,0,0,0,0]` instead of `[0,1,2,3,4]` (and now switched from 0-based to 1-based indexing).
-1 byte thanks to *@Grimmy* (and back to 0-based indexing again).
[Try it online](https://tio.run/##AS0A0v9vc2FiaWX//8SBPMOmypLCuXPDqE9AfcOpzrj//1sxLDksNSw3LDJdCjUKMTA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpSbKWgpFPpcmi3DpeSf2kJUAQoYJ9waGWRS@j/I402h5edmnRoXXFE8eEV/g61h1ee2/Ff59A2e82Y/9HR0YY6ljqmOuY6RrE6CqY6CoYGQDo62tgAKGhooGNkoGMcC2SaQYQNdaAQJGYKEQLKGELZIJZBbCwA) or [get all possible outputs for the test cases instead of just one](https://tio.run/##yy9OTMpM/V@m5JlXUFpSbKWgpFPpcmi3DpeSf2kJUAQoYJ9waGWRS@j/I402h5edmnRoXXFE8eEV/g61h1fqHVqYXntux3@dQ9vsNWP@R0dHG@pY6pjqmOsYxeoomOooGBoA6ehoYwOgoKGBjpGBjnEskGkGETbUgUKQmClECChjCGWDWAaxsQA).
**Explanation:**
```
# Take the (implicit) input-list qi
ā # and push a list in the range [1, list-length] without popping the input itself
< # Decrease each by 1 to make it 0-based: [0, list-length)
æ # Get the powerset of this list of indices
# i.e. [0,1,2] → [[],[0],[1],[0,1],[2],[0,2],[1,2],[0,1,2]]
ʒ # Filter this list of lists by:
¹ # Push the first input-list qi again
s # Swap to put the current list of the filter at the top of the stack
è # Index each into the list qi
O # Sum these values
@ # Check if the (implicit) input-integer is >= this sum
# (The very first iteration it will use the second input, which is the length N;
# every other iteration it will use the third input, which is the total time T.
# Since the very first inner list of the powerset will be the empty list,
# this causes no problems; which is how we ignore the mandatory length N input)
}é # After the filter: sort all remaining inner lists by length
θ # Pop and leave the last one, which is (one of) the list(s) with the most items
# (after which the result is output implicitly)
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~22~~ ~~21~~ ~~16~~ 15 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ð à ñÊÔæÈxgU <V
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=8CDgIPHK1ObIeGdVIDxW&input=WzQ4LCAxNSwgMjAsIDQwLCAzXQo2MAo1)
```
ð à combinations of indexes of 1st input
ñÊÔ sorted by length and reversed
æ get first element returning true when passed throug...
ÈxgU elements of input at X indexes reduced by addition
<V less than 2nd input
```
Takes input as [times...], time , amount
Saved 1 stealing from @Shaggy ÈxgU
[Answer]
# [dzaima/APL](https://github.com/dzaima/APL), ~~15~~ ~~14~~ 13 bytes
```
+\∘<⍛≤+/⍛↑⍋⍤⊣
```
[Try it online!](https://tio.run/##SyzI0U2pSszMTfz/qG@qp/@jtgkG/9OApHbMo44ZNo96Zz/qXKKtD6LbJj7q7X7Uu@RR12KQWqAaYwMFUwVDAwUjAwVjhTQFMwMuiLihgiVQwlzBSAEI0oAq4OIwCBZXMIWKa@gYGmgqQAGSuLqurq46ml50NYYgB8AINAhW9x8A "APL (dzaima/APL) – Try It Online")
```
+\∘<⍛≤+/⍛↑⍋⍤⊣ train; left arg = ⍺ = t, right arg = ⍵ = T
≤ ⍺ <= ⍵
⍛ with ⍺ modified to
< sorted
+\∘ and then, cumulative sum
so, cumulativeSum(sort(q)) ≤ T
⍋ the indices required for sorting
⍤⊣ applied on ⍺
so, the output, sorted by question time, if T=∞
↑ take first ⍺ elements from ⍵ (⍺ is `+\∘<⍛≤`, ⍵ is `⍋⍤⊣`)
+/⍛ but summing ⍺ first
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ṢÄ>¬TịỤ{
```
A dyadic Link accepting the question times on the left and the total time on the right which yields the 1-indexed indices.
**[Try it online!](https://tio.run/##ATMAzP9qZWxsef//4bmiw4Q@wqxU4buL4buke//Dp8WS4bmY//9bMSwgOSwgNSwgNywgMl3/MTA "Jelly – Try It Online")** (footer calls the Link and prints a formatted version of its output.)
(If we *must* take the number of questions, [this works as full program](https://tio.run/##ATUAyv9qZWxsef//4bmiw4Q@wqxU4buL4buke//Dp8WS4bmY//9bMSwgOSwgNSwgNywgMl3/MTD/NQ "Jelly – Try It Online") accepting: question times; total time; number of questions.)
### How?
```
ṢÄ>¬TịỤ{ - Link: ts; T e.g. [1, 9, 5, 7, 2]; 10
Ṣ - sort ts [1, 2, 5, 7, 9]
Ä - cumulative sums [1, 3, 8,15,24]
> - greater than (T)? [0, 0, 0, 1, 1]
¬ - logical NOT [1, 1, 1, 0, 0]
T - truthy indices [1, 2, 3]
{ - use left argument:
Ụ - indices by value [1, 5, 3, 4, 2] (i.e index 4 has 2nd largest value)
ị - index into [1, 5, 3]
```
---
Alternative 8:
```
ỤṁṢÄ>Ðḟɗ - indices-by-value moulded-like (cumulative-sums of sorted(ts) if not greater than T)
```
[Try it online!](https://tio.run/##ATYAyf9qZWxsef//4buk4bmB4bmiw4Q@w5DhuJ/Jl//Dp8WS4bmY//9bMSwgOSwgNSwgNywgMl3/MTA)
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~117~~ ~~113~~ ~~110~~ ~~105~~ ~~85~~ ~~71~~ 63 bytes
*(-3 thanks to Ver Nick says Reinstate Monica)*
*(-20 thanks to Arnauld)*
*(-14 thanks to Shaggy)*
*(-8 thanks to tsh)*
```
a=>g=t=>(a[y=a.indexOf(i=Math.min(...a))]=t)<i?[]:[y,...g(t-i)]
```
[Try it online!](https://tio.run/##bcpNCoMwEIbhfU8yA2OIiv2jY09QeoCQxWDVRqyWGqSePg20qyLf7n2@TmaZqpd7@mTeh4aDcNmy5xLELCzKDbf6fW3A8UX8XT3cAEopQbTs8eTOxh7NQjG14BOHNlTjMI19rfqxhQZMrqmgVFOmKbcIW424@bukdIifHWXR01X/LXqxwvrbwwc "JavaScript (V8) – Try It Online")
Could probably be golfed some more...a function which takes input in three arguments: time, number of questions (not actually used), and an array of question times.
It will repeatedly find the smallest element in the array, and set it to the time available, removing it from the possibilities for the next iteration. It puts the index of the value into the output array.
Thanks to everyone who's contributed to golfing this answer...54 bytes shorter than the original!
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 14 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Assumes `0` is not a valid unit of time.
```
ð à ñÊfÈxgU §V
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=8CDgIPHKZsh4Z1Ugp1Y&input=WzMwLDUsMTAsMjAsM10KNjA)
```
ð à ñÊfÈxgU §V :Implicit input of array U=q and integer V=T
ð :0-based indices of U
à :Combinations, which, fortunately, includes the empty array, covering the last test case.
ñ :Sort by
Ê : Length
f :Filter
È :By passing each throughout a function
x : Reduce by addition
gU : After indexing each back in to U
§V : Less than or equal to V?
:Implicit output of last element
```
---
Or, if we *have* to take `N` as input (or `0` *is* a valid unit of time).
```
o à ñÊfÈxgV §W
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWc&code=byDgIPHKZsh4Z1Ygp1c&input=NQpbMzAsNSwxMCwyMCwzXQo2MA)
Where `U=N`, `V=q`, `W=T`, `o` creates the range `[0,U)` and everything else is as above.
[Answer]
# [Red](http://www.red-lang.org), 133 bytes
```
func[t b][s: 0 sort collect[foreach n sort collect[repeat i length? b[keep/only
reduce[b/:i i]]][if(u: s + n/1)<= t[s: u keep n/2]]]]
```
[Try it online!](https://tio.run/##Vc3BDoIwEATQO18xR40HCgSNROM/eN3sAcpWG5tCSjn49RUSjSFze7ObCdKnu/TEmWmQzOw1RXRMUwOFaQgRenBOdCQzBGn1E37LQUZpIyyc@Ed83tDRS2TMB@/eWZB@1kJd3lhYZiZrdnODCQf4vNhfrojr0oz1ZaFyueE0BusjDI4KVCnUKBRKhYqzX7MAFTgv1Qnln@tVv9mq4vQB "Red – Try It Online")
1-indexed. Ignores `N`
[Answer]
# [R](https://www.r-project.org/), 44 41 bytes
```
function(m,t)order(t)[cumsum(sort(t))<=m]
```
[Try it online!](https://tio.run/##RYnLCoAgFET3fYXLe@EuNLEI8kuilSW0UMHH95tZEMwwzDmxWqarLd7kK3hwlDHE44yQcTPFpeIghZjbxVW7vVqYOBmQnJgiJtqMrRJxsCAeI4gt3c1Ndaxe@uejgmO9AQ "R – Try It Online")
Takes input as Time, times.
Returns numeric() for empty output.
Order the times, take cumulative sum and then select the times where the cumulative sum is less than or equal to total time.
-1 in the end to get 0-index
-1 byte thanks to Giuseppe
-2 bytes since 0-index is no longer needed
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~68 64 60 59~~ 58 bytes
```
->t,q{q.map.with_index.sort.reject{|x,|0>t-=x}.map &:last}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf165Ep7C6UC83sUCvPLMkIz4zLyW1Qq84v6hEryg1KzW5pLqmQqfGwK5E17aiFqRMQc0qJ7G4pPZ/gUJatJmBTrSxgY6CqY6CIZAyAmLj2FgukBSQH22oo2AJljQHykHFTcHCCIQkbBAb@x8A "Ruby – Try It Online")
[Answer]
# JavaScript (ES10), ~~78~~ 75 bytes
*Saved 3 bytes thanks to @Neil*
Takes input as `(T)(list)`. [Ignores `N`](https://codegolf.meta.stackexchange.com/a/12442/58563).
```
t=>a=>a.map((...x)=>x).sort(([a],[b])=>a-b).flatMap(([v,i])=>(t-=v)<0?[]:i)
```
[Try it online!](https://tio.run/##dYpBDoIwEEX3nmQmGSYFgkZj8QSeoOliQDAYpAQawu1rMW6MMf@v3nsPWWSup270yeBuTWh18LqUeH7KCMDMK@pyRZ7d5AGMWDKVjUiSCrntxV@3zizUbRR8ohc8q4uxpw5D7YbZ9Q337g4t7BWCyRUVlCrKFOUWcfedpFuS0jE2B8p@ffHWn/3RKvLwAg "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 44 bytes
```
Nθ≔EN⟦Nι⟧ηW∧笋θ§⌊η⁰«≔⌊ηι≧⁻§ι⁰θ≔Φη⁻⌕ηιλη⟦I⊟ι
```
[Try it online!](https://tio.run/##XU5NC4JAED3rr5jjLBhYEBGdJAiCiugqHiylHVhXc3criH77NmZSNIeBN2/ex0nm7anOlfdr3Ti7c9WxbPEiFmFiDJ01bvMGfykRQfqHKeMlWXKTpErARBcoI9jVFjelMXiJILFrXZR33JKmylUoWRGLbuARBkPUD0lsF3B2Tx3oLG3HO/P1os4igq7r4LAiZbkTh79/GfdViP@U@LQM9i1pi@kyNxb3dYMkRMb3p/fjGKYwhjnvGUz86Kpe "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input `T`.
```
EN⟦Nι⟧η
```
Input `N` and make a list of `N` questions with their original index.
```
W∧笋θ§⌊η⁰«
```
Loop until there are no more questions that can be answered in the remaining time.
```
≔⌊ηι
```
Get the shortest question and its original index.
```
≧⁻§ι⁰θ
```
Subtract the question's time from the time remaining.
```
≔Φη⁻⌕ηιλη
```
Remove the question from the list of questions.
```
⟦I⊟ι
```
Print the question's original index.
[Answer]
# [Python 3](https://docs.python.org/3/), 72 bytes
recursive solution, generating line separated console output
```
def f(T,L):
if L:M=min(L);I=L.index(M);L[I]=T;T<M or(print(I),f(T-M,L))
```
[Try it online!](https://tio.run/##VcvBCoMwDAbgu0@Rmw20o7VzYzofQGhv3sSblvWwKuJhe/ouOESF/ATyf5m@y2sMOsZ@cOBYww0WCXgHprDV2wdmsKwrc/GhHz7MYmnauquasnlaGGc2zT4srEZOr8LSM8b/KRVCKEqKiWM3yVstOeQcFK2MojtMdpltkupWcXis9k70xPTG8lXtc1LXo5KnKj9UHcYf "Python 3 – Try It Online")
```
def f(T,L):
if L: # do nothing if input is empty
M=min(L)
I=L.index(M)
L[I]=T # set found list item to remaining time (item will be ignored next iteration)
T<M or(print(I),f(T-M,L)) # if the found question can be answered in the given time output and find next
```
[Answer]
# [J](http://jsoftware.com/), 16 bytes
```
(>:+/\@/:~)#/:@]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NeystPVjHPSt6jSV9a0cYv9rcqUmZ@QrmBkopCkYGyiYKhgaKBgZKBhDhA1BwoYKlkBxcwUjiJgpWAgKkXSbWCgYmoL0msC1g5UaQI0CstXV/wMA "J – Try It Online")
Attempt at an explanation:
```
>: create mask of left arg greater than or equal to...
+/\@/:~ cummulative sum of sorted right arg
# copy where true
/:@] from permutation that sorts right arg
```
[Answer]
# **C++11, ~~293~~ ~~[221](https://localhost "Thanks to @EmbodimentofIgnorance and @Noodle9")~~ [219](https://localhost "Thanks again to @Noodle9") bytes**
Here to decimate the competition I am not.
Notes :
1. g++ allows for variable-sized arrays. It saves bytes, so that what I did.
2. the range-based for loops needs a reference to write correctly?!
```
#include<iostream>
void f(int t,int c,int*a){int m,i;int y[c];for(int&b:y)b=0;for(;;){for(m=-1;y[++m]&m<c;);for(i=-1;++i<c;)if(a[m]>=a[i]&!y[i])m=i;if(t>=a[m]&!y[m]){y[m]=1;t-=a[m];}else break;}for(i=-1;++i<c;)if(y[i])std::cout<<i<<' ';}
```
Expanded version :
```
#include <iostream>
void AnswerMostOfTheQuestions(int time_left, int question_count, int answer_times[]) {
int minimum_term;
bool is_answered[question_count];
for(bool& b : is_answered)
b = 0 ; // No questions have been answered
while (1) {
// Find the first unanswered question
for (minimum_term = 0; is_answered[minimum_term] and minimum_term < question_count; ++minimum_term);
// Find unanswered question which takes least time to answer
for (int i = 0; i < question_count; ++i)
if(answer_times[minimum_term] >= answer_times[i] && ! is_answered[i])
minimum_term = i;
if (time_left >= answer_times[minimum_term] && not is_answered[minimum_term]) {
// Answer question (which consumes time)
is_answered[minimum_term] = true;
time_left -= answer_times[minimum_term];
}
else break;
}
// Print index of every answered question
// 'cause returning them is a waste of bytes to implement
// Just echo it to a file or something
for (int i = 0; i < question_count; ++i)
if(is_answered[i])
std::cout<<i<<' ';
}
int main(int c, char** v) {
int question_count = atoi(v[2]), free_time = atoi(v[1]);
int answer_times[question_count];
for (int i = 0; i < question_count; ++i)
answer_times[i] = atoi(v[i+3]);
// Run solution
AnswerMostOfTheQuestions(free_time, question_count, answer_times);
}
```
[Try it online!](https://tio.run/##bY9ha4MwEIa/@ytuDFqjlmrLNmi0P2JfRUq0cTtmkk5jSxF/e5aksNGyL2@4J@@9d9ecTqumY/LDmGeUTTceeY5q0D1nYh@cFR6hDVFq0InTxmnEyOQKkSCtlergWjYVbVUfumpR766kLlIPKCWTe0Wxyui1jGNRLUTeUOJ/0dE4RgewDVkpqn3BSqwWT1erRBRILdcOCg9FRSanRUb1ylM6827gUNuFv@j8T6pPGvRxt2vUqPMc83wJSzoHgb@BoQxvl0HzyfoogjOBKQBw8Hvkg0YlD7bVlgUwrTA8l5uKJND2nB80Cv7Hs4rQW2sETA4X3nvDYB2SXxwv7yMrZ7dLg98BrS@l9skfJlOw9xBrhbtYe9nfbIy3t@nrNbyPEgbVjS7BDQh/d00ekpO7QNs/B8aY7ca8miw1m9Tpi3kz2/QH "C++ (clang) – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 9 bytes
```
↑#≤²∫O¹ηÖ
```
[Try it online!](https://tio.run/##yygtzv6f6/aoqfH/o7aJyo86lxza9Khjtf@hnee2H572////aA0zA51oYwMdUx1DAx0jAx3jWE0dDSAz2lDHEihormMEEjAF8aEQxAdpMrHQMTQFaTGB6gIpMgBr14mO1YwFAA "Husk – Try It Online") Outputs an empty list if no solution is possible.
]
|
[Question]
[
In this challenge, we define the *complement* of a list of positive integers as all positive integers not included in that list. For example, the complement of the even numbers `[2, 4, 6, 8...]` is the odd numbers `[1, 3, 5, 7...]`. Your challenge is to, given a monotonically increasing, infinite list of positive integers, return its complement.
Infinite lists may be input/output as:
* Streams from/to stdin/stdout
* Native infinite list / iterator / generator / etc objects
* Functions that take an index and return an item of the list
Additionally, you may take an index n along with the infinite list and return the nth item of the list's complement. For all options, you may use 0-indexing or 1-indexing, and your output format does not need to be the same as your input format.
## Testcases
```
2, 4, 6, 8... (even numbers) => 1, 3, 5, 7...
1, 4, 9, 16... (squares) => 2, 3, 5, 6, 7...
2, 3, 5, 7, 11... (primes) => 1, 4, 6, 8...
3, 6, 9, 12... (multiples of 3) => 1, 2, 4, 5, 7...
1, 3, 6, 10... (triangle numbers) => 2, 4, 5, 7...
```
[Answer]
# [Python](https://www.python.org) (no imports), 52 bytes
*-3 bytes, thanks to xnor*
```
def f(s,x=0):
for y in s:yield from range(x+1,x:=y)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=lZJBDoIwEEXjllPMsgWMVFwYDCcxLkhoZRIsUIrCWdy40TvpYYxAVVwR3M3iv07_y5xveaOTTF4u10qL-fq-irkAQUq3Dj0aWCAyBQ2ghDJokKcxCJUdQEVyz0ntMLcOwoYa9jF7djA_cknQ0HBKMOXAuhHAPLC0cYNOyKwuXBZVpPhYHH_jhyrV_lja_03LTE8BHLYZ5uWAa4VtzXT0d6SlqY2LxZuzilCQ3gClVq5QarKVvNakoL1K7FQae8yjO9rn3xImEj1iev2x41vmny1fgdMgcwafU3oB)
*input/output as generator*
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes
```
‚àû.i_∆∂0K
```
[Try it online!](https://tio.run/##yy9OTMpM/f@oY96h7SBSLzP@2DYD7///AQ "05AB1E – Try It Online"), or [try all testcases](https://tio.run/##yy9OTMpM/V9WGfaoY96pSZF6YbUuIYcW2yspPGqbpKBk/x8orJcZf2ybgfd/oLjO/2ilw51KOkqHWw9tAlIFQGx8eBqQtNCyA4vFAgA)
I feel like 6 bytes should definitely be possible, but I can't find it. `–º` doesn't work for infinite lists, and `‚àû í.i_` doesn't work for some reason ):
## Explanation
```
‚àû # [1, 2, 3, ...]
.i # for each, check whether it appears on the input
_ # bool not
∆∂ # multiply by the 1-based index
0K # and remove zeros
```
[Answer]
# Haskell + [hgl](https://www.gitlab.com/wheatwizard/haskell-golfing-library), 19 bytes
```
nt~<<pa(ef<P1)<(0:)
```
## Explanation
* `(0:)` add a zero to the front of the list
* `pa` map over consecutive elements of a list ...
* `ef<P1` range excluding the initial element
* `nt~<` concat map removing the last element of each range.
## Reflection
There are some things that can be improved
* `K0` is nominally a shortcut for `(0:)` but it has issues with type ambiguity here. That should be investigated.
* This really wants an exclusive range, having to use `P1` and `nt` is a really big waste. There should be various exclusive ranges for `Enum`s.
* This could use a `pa` with a concat, but I'm not sure how reusable that would be.
* Overall there could just be operations for monotonic lists. A function to determine if something is an element of a monotonic list would probably be useful here and elsewhere.
[Answer]
# [Scratch 3](https://scratch.mit.edu/), 138 bytes
*-9 bytes by [att](https://codegolf.stackexchange.com/users/81203/att)*
```
define
forever
set[b v]to(
ask()and wait
add(answer)to[a v
repeat(answer
change[b v]by(1
if<not<[a v]contains(b)?>>then
say(b
add(b)to[a v
```

[Attempt This Online!](https://scratch.mit.edu/projects/902431730/) | [Test it on Scratchblocks!](http://scratchblocks.github.io/#?style=scratch3&script=define%0Aforever%0Aset%5Bb%20v%5Dto(%0Aask()and%20wait%0Aadd(answer)to%5Ba%20v%0Arepeat(answer%0Achange%5Bb%20v%5Dby(1%0Aif%3Cnot%3C%5Ba%20v%5Dcontains(b)%3F%3E%3Ethen%0Asay(b%0Aadd(b)to%5Ba%20v)
Continuously prompts for input while printing out the missing integers.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 53 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 6.625 bytes
*-10 bits by [lyxal](https://codegolf.stackexchange.com/users/78850/lyxal)*
```
£Þ∞'¥ḟu=
```
```
£Þ∞'¥ḟu=­⁡​‎‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌­
Þ∞' # ‎⁡Filter list of positive integers by
ḟ # ‎⁢Index of integer
£ ¥ # ‎⁣in input list
u= # ‎⁤is -1 (not in input)
üíé
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9Iiwiw55wIiwiwqPDnuKInifCpeG4n3U9IiwiIiwiIl0=)
[Answer]
# [Haskell](https://www.haskell.org/), 30 bytes
```
(1%)
p%(h:t)=[p..h-1]++(h+1)%t
```
[Try it online!](https://tio.run/##JY5NDoIwFIT3nOItJClgq8W4MfQInqDW0PAjjY/aQOOKs1sL7L7FzDcz6PndIYZePALhaZa4lAw3nwnpGBsoV0VBhoJnqQ8oJGdMJWhmP4MAOWpH8jLDI6z03EjaxVbUa4OAR21bOX5asGBO4ryYisqSMRutSu2l/LKXcmLjSN2ab12uAlQKklEbG3di7g5uMtbDAaTX7w74NWIP0wJTRWE7pMKv6VG/5kAb5/4 "Haskell – Try It Online")
**33 bytes:**
```
f l=do(a,b)<-zip(0:l)l;[a+1..b-1]
```
**34 bytes**
```
f l=[n|n<-[1..],all(/=n)$take n l]
```
[Try it online!](https://tio.run/##JY47DoMwEER7TrEFBRAMMVE6fIScwHKExSexWDYWtlJx9jgGuiftvNl5azePiCFMgELSRi2TvKpUqRGzWlCeej2PQIAqxMB@StA470CAXLTNiibHEnZ6HnR2eG0QsNQ0yOUzRN3U4rqZWN5UFTGulDql4nZKRUYXnneD@XbNXoBKQbJoQ/FPzD3AroY8pCCPPfwecYJ1g7VlcAxS4ddPqF8usN7aPw "Haskell – Try It Online")
[Answer]
# [R](https://www.r-project.org), 54 bytes
```
g=\(f,i,j=1,k=1,l=f(k)>j)`if`(i,g(f,i-l,j+1,k+!l),j-1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=hZFBTsMwEEXF1rfoopKndQROJYSK3JMg0qiyw7i2E2IbhICTsAkL9lwHToNDoqrtJgvL0p8_-v_ZH59t972rbWOklS4UBn0QXzGo7ObnuhJ3VDFkWnC2T8cIRfew0bBFtaXIqn6aGaaXab6cGWA64zBs_168ySfpvFDR7QLWjiLkCyT-MZatPJHxPidNi7ZXj_Q-Fl6fH9BI6qOlMz2f87WGTQ5apMjbsYWimPG-Q4qHd2KjCZhwfFGrYnWcs0rxocXSVeaswIJiWr_MCfFl05gXytf8ip09C1PinwgmTCPhlG0gnnKd0ky5D3TjJ3TdcP8B)
Input & output as functions that take an index and return an item of the list
---
# [R](https://www.r-project.org), 48 bytes
```
repeat{if((y=scan(,,1))>T)cat(T:(y-1),'');T=y+1}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGCpaUlaboWNw2KUgtSE0uqM9M0NCpti5MT8zR0dAw1Ne1CNJMTSzRCrDQqdQ01ddTVNa1DbCu1DWsh-tYYcplwWXIZmnEZmXJBhGBGAgA)
Takes input from STDIN or the R console, and outputs the non-inclusive ranges between successive input values to STDOUT or the R console.
[Answer]
# x86 machine code, 13 bytes
This is basically a function that would be part of a device driver: it repeatedly reads the same address, so that should be an MMIO register for a PCIe device that accepts an input sequence. It outputs via port I/O to a specified port number (perhaps on the same PCIe device). Or more realistically, this runs in a VM where the hypervisor handles these streams. In C for the x86-64 System V ABI, `void complement_sequence(int dummy, volatile int *input, uint16_t output_portnum)` (except this is 32-bit code.)
IDK how justifiable it is to do binary I/O to MMIO and an IO port; it could save bytes incrementing pointers if used for finite challenges, and is not usable as a function on data in memory. But an infinite series requires I/O, if we pretend that 32-bit fixed-width integers didn't actually cap the input + output size as 4 x 2^32 bytes = 16 GiB, which x86-64 can easily handle. I don't plan to use this (or C `volatile int*`) for any finite challenges.
```
;; MMIO address in ESI for input
;; I/O port number in DX for output (or pointer in EDI for MMIO)
complement_sequence:
31C0 xor eax, eax ; start as if last value written or considered for writing was 0
; So we output (0, first_seq_num) non-inclusive on both ends
.next_seq:
8B0E mov ecx, [esi] ; next sequence number
A8 db 0xa8 ; opcode for test al, imm8 works like a forward jump by 1 byte ; jmp .entry
.write: ; do {
EF out dx, eax ; 1-byte instruction skipped on first iteration
.entry: ; entry point for first inner iteration
40 inc eax ; ++next_write
39C8 cmp eax, ecx
75FA jne .write ; } while(next_write != next_seq);
EBF5 jmp .next_seq
; no ret, we never return
```
Tested with a debugger locally, after replacing `out` with `stosd` and adding `add esi, 4` after the load. Then I can pass it pointers to arrays in memory, and `display (int[15])outbuf` as I `si` in GDB.
---
Less golfed is 14 bytes, without the [partial-instruction hack](https://codegolf.stackexchange.com/questions/132981/tips-for-golfing-in-x86-x64-machine-code/235553#235553) for loop entry skipping the 1-byte `out dx, eax`. The code above does that by using the opcode for a 2-byte `test al, imm8` as equivalent to a 1-byte jmp forward, consuming the first byte as an immediate so it doesn't run on entry to the loop, only on subsequent iterations.
```
;; MMIO address in ESI for input
;; I/O port number in DX for output (or pointer in EDI for MMIO)
complement_sequence_less_golfed:
xor eax, eax ; start as if last value written or considered for writing was 0
; So we output (0, first_seq_num) non-inclusive on both ends
.next_seq:
mov ecx, [esi] ; next sequence number
jmp .entry
.write: ; do {
out dx, eax ; or mov [edi], eax for MMIO
.entry:
inc eax ; ++next_write
cmp eax, ecx
jne .write ; } while(next_write != next_seq);
jmp .next_seq
; no ret needed, this is a noreturn function
```
Algorithm: start with `i = 0;` (EAX)
* x = input from sequence (ECX)
* `for ( ; ++i != x ; ) { out(i); }`
* leave the loop with i == x, so i = previous sequence number.
* repeat, getting a new `x`. (With `i` the same.)
This feels like a lot of `jmp` instructions, like maybe there's a better branch layout I'm not seeing. But with 2 nested loops, one of which might have run 0 iterations of part of the body, I guess this is reasonable.
[Answer]
# [Python](https://www.python.org), 79 bytes
```
lambda x,j=0:(i for i in count()if i-j or(j:=next(x))*0)
from itertools import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY0xDoJAEEV7TzHlDMFksVIiZ_ACNqi7YXDZIcsQ17PYkBi9k7eRBK3-a_57j3d_10bC9HTV8TWqW28_B193p0sNKW8rUyKDkwgMHOAsY1AkdsDrFiRiW1bBJsVElBlauSgdsNqoIn4A7nqJmv20uz7y_PY8KGp9tbeGvcV_q0z7wpgcHC6RYuYNEeVAtAimadkv)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
‘rƓṪḷṄ€Ɗß
```
[Try it online!](https://tio.run/##ASwA0/9qZWxsef//4oCYcsaT4bmq4bi34bmE4oKsxorDn///MQoyCjQKOAoxNgozMg "Jelly – Try It Online")
A full program that reads an infinite list from STDIN and outputs an infinite list to STDOUTbof the complement.
## Explanation
```
‘ | Increment by 1 (will start from an implicit zero)
rƓ | Range from this to the next number from STDIN
Ɗ | Following as a monad using this range as an argument
·π™ | Tail
·∏∑ | Left value (I.e. the tail above) rather than:
Ṅ€ | - Output all of the remaining values in the range to STDOUT separated by new lines
ß | Recursively call the link again
```
[Answer]
# JavaScript, ~~49~~ 48 bytes
```
function*(L,P=0){for(v of L)while(++P<v)yield P}
```
[Try it online!](https://tio.run/##bZBNbsMgEIXX5hSzqQRx6ibOrhT3AllE6jKKKseBlgYPFsZuo8hnd/FPk03FYkDfe4@Z@crbvC6crvxjXemTdKXFs7z0hQHRqwYLry0u6Ha5Eyt2VdbRFqyCLfv@1EbSON69tOyipTnBrus50cEHd5@aPEZ6QLHmHON4ViuKjHec3LRQOV3KmjJyJdGkSTmJgh0mfwjecODhEgtIGYnuzAeWDsyH/ABCQhRpBRThYYACVgyOTuZn/kc8LALJABlcp9@Qz5IuaDrSkVu8Gkbeo8hwkS5hrBhqY8z82syVYrxmT@lhnGFsbFwHvII2YRfwfBuST1wPnReGesP2b5fyaE2ivXS5t@4wigqLtTUyMfaD7lfLf88hKfOKvotM@wTlj6csaXPTSBYCuv4X "JavaScript (SpiderMonkey) – Try It Online")
Takes an iterable and returns an iterable. Starts from 1.
-1 thanks to bsoelch.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~58 ...~~ 35 bytes
```
->g{->n{b=0;n+=1until g[b+=1]>n;n}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y69WtcurzrJ1sA6T9vWsDSvJDNHIT06CciOtcuzzqut/V@gkG2bFq1rV1FtpFVRG8tVoKBhqKdnaGCgqZebWKChlq0JFCqHKqnAqqRc8z8A "Ruby – Try It Online")
Accept a generator function in input, returns a function.
[Answer]
# [Minecraft Data Pack](https://minecraft.fandom.com/wiki/Data_pack) via [Lectern](https://github.com/mcbeet/lectern), 202 bytes
```
@function a:b
scoreboard players add a 1
function a:a
execute if score o = a run scoreboard players add i 1
execute if score o > a run tellraw @a {"score":{"name":"a","objective":""}}
function a:b
```
The function is `a:b`.
Takes input as a function `a:a`, which takes in `i <empty>` the 0-based index of an element and returns it, and outputs all numbers to chat.
Assumes the objective `<empty>` exists but no values in it do.
Might be invalid, because while `<empty>` is a valid objective, it requires weird workarounds from the function to work with it because it can't appear at the end of commands.
This is how you'd have the squares as input, for example:
```
@function a:a
scoreboard objectives add temp dummy
execute store result score i temp run scoreboard players add i 1
scoreboard players remove i 1
execute store result score o run scoreboard players operation i temp *= i temp
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes
```
WNF…⊕↨υ⁰↨⊞Oυι⁰«IκD⎚
```
[Try it online!](https://tio.run/##HcmxCsIwEIDhuXmKjHdQwYII4ma7uGjxDc542mKahkuig/js0XT7fz4zkJiZbM7vYbSs4eh8iqc0XVkAUd9n0XAh9@C/GOGJXeQbHCgwpFqvEWu9TJ/CcPYsFGcpMuKiqD@q6mV0EVoKEZ6Ie1V1afJQorVMUuqbc6M2aqeabV697A8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
WN
```
Keep inputting numbers while they're positive. (Which they should always be, but it does also mean that if you try this interactively you can enter `0` to quit.)
```
F…⊕↨υ⁰↨⊞Oυι⁰«
```
Push the input number to the predefined list, but make a range between the previous number (defaulting to `0`) and the current number, and loop over that range.
```
IκD⎚
```
Output the current number eagerly so that it will appear before the next input.
I output each number individually because outputting a range fails if it is empty. Maybe I should make `Dump();` do nothing if the canvas is completely empty?
[Answer]
# [Headass](https://esolangs.org/wiki/Headass), 22 bytes
```
{{D+^(U)}:{PD+^(R):};}
```
I'll be honest, I have no idea how infinite input streams work, and I have no idea whether either implementation of the language supports it, but the actual language itself takes input similarly to brainfuck and doesn't have any issues with getting infinite input, so this is at least theoretically correct... let me know if that's an issue :P
If you want to test it out with infinite output, you'll have to use [my online interpreter](https://replit.com/@thejonymyster/HA23) and run this command:
```
srun('{{D+^(U)}:{PD+^(R):};}',...list)
```
with `list` replaced by the list of your choice. With the speed this program runs at, you're probably going to start seeing outputs at around 3000-4000 so keep that in mind if you're inputting something finite / short.
For a version which halts at the end of input (in case you just want to try it out), try this modified version;
```
{{D+^(U)}:{PD+^(R):};N()}
```
[Try It Online!](https://dso.surge.sh/#@WyJoZWFkYXNzIiwiIiwie3tEK14oVSl9OntQRCteKFIpOn07TigpfSIsIiIsIjJcbjNcbjVcbjdcbjExXG4xM1xuMTdcbjE5XG4yM1xuMjkiLCIiXQ==)
Make sure input isn't empty or of the form 1,2...n or else it will freeze :P DSO doesn't have a time limit, and those input cases are nontrivial to fix. This has no bearing on the validity of the actual program as it relates to the challenge.
### Explanation
```
{{D+^(U)}:{PD+^(R):};} full program
{ ;} while(true)
{D+^(U)}: do {} while(++i == nextinput())
P do {print(i)}
{ D+^(R):} while(++i == currentinput())
```
[Answer]
# [Python](https://www.python.org), 50 bytes
```
lambda s,*i:(n for z in s if{n:=len(i:={*i,z})}-i)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=lZJBbsIwEEXVbU4xS08AgcOmCvJJKIug2GUkMyGOAwXESdhEQu2d2sNUJQkFVhGsPJLf88x8-fi12vpFxtXJqLfP0pvB63dkk-U8TaDohxQLBpM52AExFEBmz7GymgXFah9Sf3fAw4CwNX9eflNtQK_reyUxDgA2C7IaZF0CbEnbFKKQJtRTMqjhIi8Tp7twuseXpfXjLnp8T3Pm_4VRh9CTk1sd3XTvKOF32zmdONsY0nB48YJcGdEkgBisHLEXU9YfXuTYBEl1kO78rBZyhDNs-EsIDxqN0u71RI_rMs90uQb4mNR-g6pqzz8)
Test harness borrowed from @bsoelch.
## How?
For each prefix of the given sequence checks whether it contains its length. If not yields the length.
[Answer]
# [MaybeLater](https://github.com/TehFlaminTaco/MaybeLater), 68 bytes
```
wheni is*{if(i<n)printi elsen=readline0when0spass i++}n=readline0i=1
```
[Try it online!](https://tio.run/##TdFBatxAGEThfZ1ilom9UVWr1WqIDzMhMhaMhRkZTAg5@@T1Ltt/hOZ9pffr75/b7fq53R@Pr7ft2C/7@fRnf/22/zi@f9z343O/bLdzO17u2/XXbT@2aTw2nR/X87zsz89///tlf/HjYRVVNXXZcpGr3OSuWClKVZrSVXiwqFSVptI1W3PRXDU3zV3VqrynqjbVrsVaipaqpWnpalYravxNU@tarbVorVqb1q5u9aJe1akgY6JjImSiZCJlGmncRtyoG3n0mUBTaBJNo4l0GQZudJpQU2pSTauJNbUm1/S6Diw3kk2ziTbVJtt0m3BTbtLdxircqDf5pt8AjMAQjMEgjMJ9zMd@OIIjOIIj09iUG47gCI6MncfQY@kx9dgaR8oYnxuO4AiO4AiO4AiO4AiO1PGVuOEIjuAIjuAIjuAIjuBIG5@TG47gCI7gCI7gCI7gCI708d27/gE "MaybeLater – Try It Online")
[Answer]
# [Befunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), 39 bytes
```
1>:&\->:3j>;#_;\:.1+\1-3jj'<;$1+3jj!'<
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//83tLNSi9G1szLOsrNWjreOsdIz1I4x1DXOyhJSt7FWMdQGshTVbf7/N1IwVjBVMFcwNFQwNFYwBDIsFYyMFYwsFQA "Befunge-98 (PyFunge) – Try It Online")
Takes input in the form `1 3 5 7` ... and outputs in the same form. You will need to manually interrupt the TIO program to see the result, since the program doesn't terminate (it assumes infinite input).
## Explanation
*I have replaced the unprintable character with the letter R (since it is supposed to be the character with ascii value 18, and R is the 18th letter of the alphabet)*
```
1>:&\->:3j>;#_;\:.1+\1-3jjR'<;$1+3jj!'< Program
1 Push 1
> 3jj!'< Repeat forever (the j!' is read backwards and
makes the IP jump 33 cells back to the start)
:& Duplicate top of stack and read input
\- Swap top two elements and then get difference
>:3j>;#_; 3jjR'<; Inner loop (Repeat until top of stack is 0)
:3j Duplicate top of stack then jump to _
>;#_; ; If top of stack is not 0, continue looping,
otherwise jump out of loop
\: Swap then Duplicate
. Pop and output
1+ Increment
\1- Swap then decrement
3jjR'< Return to start of loop (the unprintable
character has ascii value of 18, which is how
far the IP jumps)
$1+ Pop and increment
3jj!'< Return to start of main loop (the j!' is read
backwards and makes the IP jump 33 cells back
to the start, since ! has ascii value of 33)
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 35 bytes
```
+[>,<[->->+<<]>[->.+<]>[-<<+>>]<<+]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fO9pOxyZa107XTtvGJtYOyNLTBtM2Ntp2drFAMvb/fwXHKAA "brainfuck – Try It Online")
Note that this inputs and returns raw bytes rather than ascii numbers, and it runs forever regardless of EOF, so TIO isn't the best way to demo it. You can use my own [Brainfuck interpreter](https://github.com/rmccampbell/PythonProjects/blob/master/bf.py) and pipe the input/output through [atob.py](https://github.com/rmccampbell/PythonProjects/blob/master/atob.py) and [btoa.py](https://github.com/rmccampbell/PythonProjects/blob/master/btoa.py).
[Answer]
# [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 35 bytes
```
g=>f=(n,i=0)=>g(i)>n+i?n+i:f(n,i+1)
```
[Try it online!](https://tio.run/##jU7dCoIwGL33Sbb8Gm4SobFFF3ndvUgMm/KVbjJD8OnXrBfo4sA5B87PUy96bj1O7/084cP40dmXWUMlQy9VJ4kFlBmVqidIlU3xHFF2m51yGq6LsRKlEjtMbh5Hs4laQA4HOALnwHPgkRQgchBFU2NzSlpnZzcYNrie1Iyxi/d6JTyjDRv1RMgdMA5WZCuncZbSvyPfD79M@AA "JavaScript (SpiderMonkey) – Try It Online")
Input and output as function
]
|
[Question]
[
Your task is, to count how many pluses I have.
## What Pluses?
* The no plus: 0 Points
```
-
```
* The naïve Plus: 1 Point
```
+
```
* The double Plus: 2 Points
```
+
+++
+
```
* The mega double plus: 3 Points
```
+
+++
+
+ + +
+++++++++
+ + +
+
+++
+
```
Pluses of higher order than 3 must be ignored.
## Rules
* Input will only consist of two characters - and +, and it will always be rectangular.
* Input can be a string, an array or a binary matrix (then + is 1 and - is 0).
* Output must be the sum of all detected pluses (trailing newline/ whitespace allowed).
* Pluses can overlap (see Examples below)
* [Default I/O rules apply](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)
* [Default Loop holes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply
## Examples
```
-+-
+-+
+--
```
Out: 4
```
-+-
+++
+++
```
Out: 9 (7 naïve pluses and 1 double plus)
```
++++++
++++++
++++++
++++++
```
Out: 40 (24 naïve pluses and 8 double pluses)
```
----+-----
+--+++----
----++----
-+--+--++-
+++++++++-
-+--+--++-
----+-+---
---+++----
+---++++++
```
Out: 49 (36 naïve pluses, 5 double pluses and 1 mega double plus)
```
++++++++++
++++++++++
++++++++++
++++++++++
++++++++++
++++++++++
++++++++++
++++++++++
++++++++++
```
Out: 208 (90 naïve pluses, 56 double pluses and 2 mega double plus)
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~29~~ ~~28~~ 24 bytes
```
z2Y6ttX*,GbZ+5Mz=z]yytvs
```
Input is a binary matrix with `1` for `'+'` and `0` for `'-'`.
[Try it online!](https://tio.run/##y00syfn/v8oo0qykJEJLxz0pStvUt8q2KraysqSs@P//aAMFQwUDayBWMASTBrEA) Or [verify all test cases](https://tio.run/##y00syfmf8L/KKNKspCRCS8c9KUrb1LfKtiq2srKkrPi/S1RFyP9oAwVDBQNrIFYwBJMGsVxwMUOwGBACxcC0ApIYfjbYFAg0VICxIPYYQNXAxBDqkMUMkfQaItyDArGrQ7bXEMUOVHsNFZBFIa4GAA).
### Explanation
>
> [Convolution](https://codegolf.stackexchange.com/a/79313/36398) [is](https://codegolf.stackexchange.com/questions/192680/write-a-function-that-returns-an-iterable-object-of-all-valid-points-4-direction/192694#comment459298_192694) [the](https://codegolf.stackexchange.com/a/79453/36398) [key](https://codegolf.stackexchange.com/a/89194/36398) [to](https://codegolf.stackexchange.com/a/200078/36398) [success](https://codegolf.stackexchange.com/a/92254/36398)
>
>
>
```
z % Implicit input. Number of nonzeros. This is the number of naive pluses
2Y6 % Push [0 1 0; 1 1 1; 0 1 0] (predefined literal): pattern of double plus
ttX* % Duplicate twice. Kronecker product: pattern of mega-double plus
, % Do twice
G % Push input again
b % Bubble up third-topmost entry in the stack. This moves either the
% double of mega-double pattern to top
Z+ % 2D convolution, maintaining size
5M % Push the last input to the last function again: the pattern
z % Number of nonzeros. This gives 5 or 25 for double or mega-double
= % Equal? Element-wise. This detects if the result of the convolution
% equals the number of ones in the pattern, which implies that the
% pattern has been found
z % Number of nonzeros. This is how many times the pattern has been found
] % End
yyt % Duplicate the top two elements, then the top element. This effectively
% gives weight 2 and 3 to double and mega-double pluses
vs % Concatenate all stack contents. Sum. Implicit display
```
[Answer]
# JavaScript (ES6), ~~146 ... 140~~ 137 bytes
Expects a binary matrix.
```
m=>m.map((r,y)=>r.map((c,x)=>t+=c+=(g=(X,k=6)=>k>>8||(m[y+Y+k%5%3]||0)[x-X+k%27%4]&g(X,k+46))(Y=0)&&2+3*g(Y=3)*g(-3)*g``*g(0,Y=6)),t=0)|t
```
[Try it online!](https://tio.run/##rU/LTsMwELznK6xKTbxsbEVtKUjIucEP9NKqjdTITULIqzgGtSJ8e7CTIoq4stLuzoxn1/ZL/B63UuVHzermkPSp6CsRVryKj5Qq/wwiVCOR/skQjUKioJmga78QS6MUYXjfdbTannGDxfR2Oo@6LoDtia0Nnd1NF5GbWTculgB0IwJw3RnObzKD52Aas3W/NyjwN2Yn@NqYOt2r5PUtVwn10tYDrpL48JSXyepcSxoA181Kq7zOKPD2WOaaTnb1rp4ATxv1GMtn2hIRkg@HkIoI0v6YjMX@SNnjLedcRQOXlqNtgnjoAcCDmZVN3TZlwssmoymtrPgJPUPmIEOTzHEGgjikLRf8tznMBNpip5mRBjioF4iDAceNY/xSxw14GfvegCO@esDVtf8OvwA "JavaScript (Node.js) – Try It Online")
## How?
### Helper function
The helper function \$g\$ tests whether there's a 'Double Plus' inside the \$3\times3\$ submatrix whose top-left corner is located at position \$(x-X,y+Y)\$.
We start with \$k=6\$ and add \$46\$ to \$k\$ after each iteration. The relative coordinates in the submatrix are given by:
$$\begin{align}&dx=(k\bmod 27)\bmod 4\\
&dy=(k\bmod 5)\bmod 3\end{align}$$
```
k | k%27 | dx=k%27%4 | k%5 | dy=k%5%3 | (dx, dy) | 0 1 2
----+------+-----------+-----+----------+-------------- ---+-------
6 | 6 | 2 | 1 | 1 | (+2, +1) (A) 0 | - C -
52 | 25 | 1 | 2 | 2 | (+1, +2) (B) 1 | E D A
98 | 17 | 1 | 3 | 0 | (+1, +0) (C) 2 | - B -
144 | 9 | 1 | 4 | 1 | (+1, +1) (D)
190 | 1 | 1 | 0 | 0 | (+1, +0) (C)
236 | 20 | 0 | 1 | 1 | (+0, +1) (E)
```
The cell at \$(+1, +0)\$ is tested twice, which is not an issue.
The next value of \$k\$ is \$282\$ which triggers the test `k >> 8` and stops the recursion.
```
g = (X, k = 6) => // g is a recursive function taking X and a counter k
k >> 8 || ( // if k = 282, stop the recursion and return 1
( m[ y + Y + // otherwise, test the cell located at
k % 5 % 3 ] // row y + Y + ((k mod 5) mod 3)
|| 0 //
)[ x - X + // and column x - X + ((k mod 27) mod 4)
k % 27 % 4 ] //
) //
& g(X, k + 46) // do a recursive call with k + 46
```
### Main function
**NB**: Among many different possible choices, the initial value of \$k\$ in \$g\$ was forced to \$6\$ so that it allows us to do `g(0, Y = 6)` in the main function without breaking anything.
```
m => // m[] = input matrix
m.map((r, y) => // for each row r[] at position y in m[]:
r.map((c, x) => // for each cell c at position x in r[]:
t += // add to t:
c += // 1 point if c = 1
g(Y = 0) && 2 // 2 points if there's a Double Plus at (x, y)
+ 3 * // 3 points if there are also Double Pluses at:
g(Y = 3) * // (x - 3, y + 3)
g(-3) * // (x + 3, y + 3)
g`` * // (x, y + 3)
g(0, Y = 6) // (x, y + 6)
), // end of inner map()
t = 0 // start with t = 0
) | t // end of outer map(); return t
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 33 bytes
```
×3\€ḊṖ
ZÇZaÇḤ
ÇJ%3ZƙƲ⁺€Ç€€a3,,ÇFS
```
[Try it online!](https://tio.run/##y0rNyan8///wdOOYR01rHu7oerhzGlfU4faoxMPtD3cs4Trc7qVqHHVs5rFNjxp3AVUcbgcSQJRorKNzuN0t@P/RyQ93Ln7UMOfQtrpD2x41zH24ewtQ2hbI0garjfz/X1dbl0tbVxuIdbnquMA8bW0wrgORUA4mBVQLBNogAmSALlAMzASLQpnaYAXaEDMhAEUUYoI2VBvMBG0IG9kJSBZTnQkA "Jelly – Try It Online")
:/
I want to say this is very golfable, but the entire approach is probably not the ideal one. Now agrees with Luis Mendo's MATL solution on a test case I made up, and at the cost of only one byte so that's cool I guess
```
×3\€ḊṖ Helper link 1: detect centers of +++
€ For each row,
3\ reduce over overlapping windows of length 3:
× multiply.
ḊṖ Remove the first and last rows.
ZÇZaÇḤ Helper link 2: detect double plus centers
aÇ Keep the horizontal (centers of) +++es which align with
ZÇZ the vertical (centers of) +++es,
Ḥ and double.
ÇJ%3ZƙƲ⁺€Ç€€a3,,ÇFS Main link: sum each tier of plus
Ç Get the matrix of double plus centers.
ƙƲ Group rows by
J%3 their indices mod 3
Z and transpose each group;
⁺€ do it again to each group.
€€ For each group in each group,
Ç detect the double plus pattern,
a3 and replace the 16s with 3s.
, Pair the result with the input,
,Ç pair that pair with the double pluses,
FS then flatten that all and return the sum.
```
[Answer]
# [R](https://www.r-project.org/), 141 bytes
```
function(m)sum(m,a<-f(m,n<-nrow(m))*2,f(a,n,3)*3,na.rm=T)
f=function(m,n,k=1)sapply(n*k+seq(!m),function(i)all(i%%n>1,m[i+k*c(0,1,-1,n,-n)]))
```
[Try it online!](https://tio.run/##bVDLCsIwELz3K/RQ2K1bSVQEofUrvImHUKyENlttFfXra7Ta2EcWZpbMzG5IWZ/iOr1xctUFg8HqZsCQisLUEkchl8XdXmOwoBQUMS0xWBKreWniHXpp7LJWzGKJlTqf8ydwkM2q4wWmBqn1aFR5Dtr3eSvJ7PUsCxIQJCmUNh0yHhDrExh1LfUDGuld4lOW0e5Hb8TRuCz2HJJWtB5GvuN67FaJnuZ6h5K8ye9I6pZoUbS9@EuObW3QzRxqnZchbexnvQA "R – Try It Online")
This can probably be improved by a lot.
The helper function `f` scans the matrix. For each cell, it counts 1 iff the cell and the cells at distance `k` in each of the 4 directions are all worth 1. For `k=1`, this corresponds to checking the 4 neighbours, and creates `a` which encodes the centres of the double pluses. We then run `f` on `a` with `k=3` to find the triple pluses. The entries near the edges end up as `NA`; they are ignored thanks to `na.rm=T`.
[Answer]
# [J](http://jsoftware.com/), 80 69 60 bytes
```
[:+/@,[,2 3*((;[:,./^:2#"{~)#:2 7 2)4 :'y(x-:x&*);._3~$x'&><
```
[Try it online!](https://tio.run/##rU7BCsIwDL3nK@KUdTXrNjpBjU4EwZMnr0M9yEQ8KIjIRPDXZ7d1oKg3A2le0peXdyiGLY77uMIIN2WCE4gdJowCfdOzSRXgbLmYFylTOPVTX2Pc9bxRyn4Qrlm3nftDtlljH7XsIYublyvO3a4cBZv40cmFOxkXEran4zU7XyptEm5ifjVAtt2fsDfEBHfYMMzZCJQJKh8FphBVuJ5aSBXBdEBNvE1rBbJrjQLV2ARIez36vG4ZX4td@@a59gKv4j9YikonDUtHg18eXi7/H0oong "J – Try It Online")
-9 thanks to xash
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 71 bytes
```
WS⊞υιυFLυFLθ«Jκι¿⁼⁷LΦ⪫KVKKΣλ3»FLυFLθ«Jκι¿∧⁼3KK⬤urdl‹1⊟KD⁴✳λ6»≔Σ⪫KAωθ⎚Iθ
```
[Try it online!](https://tio.run/##nZA7a8MwEMfn6FMIT2dwIaKlHTKZtIWGUgwp3YWj2CKyZOvRDKWf3T1ZzqNrbpDu@b@fVLfc1oarcTy2UgkKb7oPfuut1A3kOa2CayEUVOYrUmHSQ0BvbyyFd6Ebj0Xsuo4HjH/IYhO6/tPAIY0u5J7CyxC4cvBU0Ln1VSovLGyM1FAJcfgy@kOEjmsNeUFjBhEKug0dqDwaTQjZfYaavzdilHp3QkGhqz2lUpAFu1NZJHRYZrFs@gnuWVpRe2k0PBT0EiSwC9pjQiudk42GiH5@XtTHNce4a8CutRLcwvlj19z5iL0axyUai8eS4MXY5JMpO7tsasCIsJP9yyYFNo@dFFjy0ch4963@AA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a binary matrix of newline-terminated strings. Explanation:
```
WS⊞υιυ
```
Read in the matrix and print it to the canvas.
```
FLυFLθ«Jκι
```
Loop over all of the cells.
```
¿⁼⁷LΦ⪫KVKKΣλ3»
```
If this cell and all of its neighbours are `1`s or `3`s then change this cell to a `3`.
```
FLυFLθ«Jκι
```
Loop over all of the cells again.
```
¿∧⁼3KK⬤urdl‹1⊟KD⁴✳λ6»
```
If this cell is a `3` and all of the cells 3 away in all four orthogonal directions are greater than `1` then change this cell to a `6`.
```
≔Σ⪫KAωθ⎚Iθ
```
Take the sum of the grid, clear the canvas, and output the sum in decimal.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~150 149~~ 145 bytes
```
lambda a:len(x("\+",a)+2*x((d:="\+(?="+(s:="\W"*~-a.find("\n"))+3*"\+"+s+"\+)..")[:-2],a)+3*x(d+f"(?={3*s+3*d+3*s+d})",a))
import re
x=re.findall
```
[Try it online!](https://tio.run/##bU/BasQgED3Xr5A5aUZD2fTQBtx@Rg/ZHCwaKmRN0ByylPbXUzW7WwodGOeNb@Y9nS/Lx@Sb5zlsgzptoz6/G011O1rPVgYnBKE5HqqVMdOq1LNXBchixm9QfUtdD86bNOmBc2yqvIIRU@F1Dbxr5aHPEk2SMDhA2v9sqph6g7maL54tOHHneQoLDZasKtiiqsdxW2xcIlW0Ix0ASJQEJaaUqRP0qRfkl0DMWYiXG4ElyH9lV3i8S6TAfGQLmfgCy@0VYhnA3WqPP7e7Al7Xbgq447thflpPyDAF6oSlztPyx5Y8zMH5hQ3McQHqCCIjpSzffgA "Python 3.8 (pre-release) – Try It Online")
Input is a multiline string
Thanks to @Tipping Octopus for -1 byte
Thanks to @Neil for -4 bytes
## Ungolfed version
```
import re
def f(a):
s="\W"*(a.find("\n") - 1)
d=f"\+(?={s}\+\+\+{s}\+).."
return len(re.findall("\+", a) +
2 * re.findall(d[:-2], a) +
3 * re.findall(d + f"(?={3*s + 3*d + 3*s + d})", a)
)
```
[Try it online!](https://tio.run/##bU/BbsMgDD2Pr7AsVQoxRFuzwxaJ7TN2aHKIFNAiZSQi7DBV@fYMSNu1U40MD7/Hs5l@/Odoy5fJrWv/NY3Og9Os0wZM1vKKAcwK64@dw92xLUxvuwxrixwkPC2B7ZTBmrJ3dZyXmuJKgBcFskA77b@dhUHbzOn0vB2G4EAooOVAQXIVe8jhStYdKrlv7gnLf0IgMBiHKPM54DLv0h5xt/DU68aAr17PfgYFB3ZAREmSkaSQMtwEPDeC/RFEMRPxeiYoBbt3bA6PF4sQFLfYQgY@wVQ9QUoC2lptcVPdHOj07OxAG740jKM1jJnRQS809BbSHyv2MLne@sxkPReo3lBEpJTm6y8 "Python 3.8 (pre-release) – Try It Online")
## How it works :
I created a regex that can detect double plusses and mega-double-pluses
* `s="\W"*~-a.find("\n")` stock in `s` the string `\W\W...\W` whose length is equal to the number of character of a line minus 1. (`\W` matches any non-word character including `\n`)
* `d=f"\+(?={s}\+\+\+{s}\+).."` is the pattern for double plus (+ `..` wich will be removed on the double plus check)
* `re.findall(<pattern>, a)` returns a list containing all the matches of pattern.
* `len(re.findall()+2*re.findall()+3*re.findall()` concatenate theses lists and return the length
[Answer]
# [Ruby](https://www.ruby-lang.org/), 135 bytes
```
->a{i=0;[1,186,0x101c04125ff490407010].sum{|s|a.each_cons(y=3**i).sum{|w|w.transpose.each_cons(y).count{|z|z.join.to_i(2)&s==s}}*i+=1}}
```
[Try it online!](https://tio.run/##tY7bboMwDIbv@xQTFxPgJko6dtKUvghDVZZBm4kGREA9kDw7o0mp0Lbb/ReO89n@7ab7OA0FG9Ca95KRt5Qu6cvTkhwpoYIkdPVYFMkrScgzoSTDutv3RhuOcy52G1EpHZ7YQxzLyJcO5oDbhitdVzqfN0VYVJ1qe3M2Z/xVSYXbaiPDVXSvGdPWxhIYtXbYMrTWfZFqXEqVa7zndW9KU2LdNrLGYsebKxQmQBBgqT7zYygiazO7WNR323TE6F0BgktAQTaHAC5MEJwc@uO9jY6CS3C2aKz43PEpB9cD1y1eP7j3gWn25gP@8@uu@S3/lQfZ8A0 "Ruby – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 37 bytes
```
Zœs3Ɗ⁺€aZ$2ịP))
3*³ṡZ€ṡ€ɗÇ⁸¡
3’Ç×Ɗ€FS
```
[Try it online!](https://tio.run/##y0rNyan8/z/q6ORi42Ndjxp3PWpakxilYvRwd3eApiaXsdahzQ93LowCigIpIHly@uH2R407Di3kMn7UMPNw@@HpQF1Na9yC////Hx1tqKNAZRSrozBq6qipo6aOmjpq6qipo6aOmjrSTY0FAA "Jelly – Try It Online")
A full program taking a Boolean matrix as its argument and printing the number of pluses. This is extensible to higher degrees of plus by changing the 3 at the beginning of the last line to a higher number. For example, [here](https://tio.run/##y0rNyan8/z/q6ORi42Ndjxp3PWpakxilYvRwd3eApiaXsdahdQ93LowCigIpIHly@uH2R407Di3kMn3UMPNw@@HpQF1Na9yC/1sYHdpkWFF8aKWF0eH2/wA) is a version that goes up to mega-mega-mega double pluses in a matrix of 82x82 1s.
[Answer]
# JavaScript (ES2020), 136 bytes
```
m=>m.map((r,y)=>r.map((c,x)=>t+=(d=X=>D=Y=>e+2?m[Y+e--%3%2]?.[X+e%2]*D(Y):e=3)(x)(y,e=3)?D(y-3)*D(y+3)*d(x-3)(y)*d(x+3)(y)?6:3:c),t=0)|t
```
```
f=
m=>m.map((r,y)=>r.map((c,x)=>t+=(d=X=>D=Y=>e+2?m[Y+e--%3%2]?.[X+e%2]*D(Y):e=3)(x)(y,e=3)?D(y-3)*D(y+3)*d(x-3)(y)*d(x+3)(y)?6:3:c),t=0)|t
testcases = `
-+-
+-+
+--
-+-
+++
+++
++++++
++++++
++++++
++++++
----+-----
+--+++----
----++----
-+--+--++-
+++++++++-
-+--+--++-
----+-+---
---+++----
+---++++++
++++++++++
++++++++++
++++++++++
++++++++++
++++++++++
++++++++++
++++++++++
++++++++++
++++++++++
`.trim().split('\n\n').map(s => s.split('\n').map(r => [...r].map(c => c === '+' ? 1 : 0)));
testcases.forEach(t => { console.log(f(t)); });
```
```
m=> // input 0-1 [m]atrix
m.map((r,y)=> // for each [y]-th [r]ow
r.map((c,x)=> // for each [x]-th [c]eil
t+= // [t]otal points add...
(d=X=> // Check if [d]ouble plus exist on [X], [Y]
D=Y=>e+2? // for [e]ach 3, 2, 1, 0, -1
m[Y+e--%3%2]?. // Y+ 0, 0, 1, 0, -1
[X+e%2] // X+ 0, 1, 0, -1, 0
// check if certain position is a plus sign
*D(Y,e) // return 0 or NaN as falsy
:e=3 // return 3 as truthy
)
(x)(y,e=3)? // Is [x][y] a double plus?
D(y-3)*D(y+3)*d(x-3)(y)*d(x+3)(y)? // Is [x][y] a double double plus?
6:3:c // assign different points
),
t=0 // initial [t]otal points to 0
)|t // return total points
```
[Answer]
# [Perl 5](https://www.perl.org/) (`-00p`), 125 bytes
```
/(....)?(..)?(.)
/;($a,$:,$;,$,)=map"."x$_,@-;/(1$,111$,1)(?{$x+=2})($;(1..1..1)$:1{9}$:(?3)$;(?1)(?{$x+=3}))?^/s;$_=y/1//+$x
```
[Try it online!](https://tio.run/##rU7LCsIwELznM8oesmwejeLBhhK/xNKDB8FHUA8t0l835lFF8eqQnUyG3dn43eWwCqMmbbQ9jjDYoLmKQMcLIdOWQy@gEWAFCGyPva9UNUAnNtJqbkAYkwi5u8NA7WJCDpYbpdJBaMx9PUHD3RKj7d59ywnRbfXVQteOcb8mGEKQJBlJiiUZyw@iXIlm/XsxGUGJ0rSMVpbZnSXlBiqJBV9uSaB57JVARX984GPt3@Xj7G/78@kaZF0f/BM "Perl 5 – Try It Online")
Using `1` instead of `+` and using regex to match pluses.
Or 124 bytes using `}{` at the end trick
```
/(....)?(..)?(.)
/;($a,$:,$;,$,)=map"."x$_,@-;$\=y/1//;/(1$,111$,1)(?{$\+=2})($;(1..1..1)$:1{9}$:(?3)$;(?1)(?{$\+=3}))?^/s}{
```
[Try it online!](https://tio.run/##rU7LasMwELzrLxr2oGW1kpWQQyyM@gP9A9PiQwKBtDFxDjHGvx5FD7ek9NpFOzsadkbq95fTNoyGjDUO2uZl6EZojwdoXTBSx0IvC6AwTkKnoFbgFChsPrt@pVc3@FCvnMxjDDHOSAvK2gQo/QQtNesZJThptU4HobbTboZa@g1G2f/sbWZE/26GeQqBiQUxxWYh8oUod4KF/x2CY1GC5OYoZZrVhVJeoJJY6pdaEmixfSdQ4U8feHr23@n93F@P568hcFX1gd@2urIP "Perl 5 – Try It Online")
]
|
[Question]
[
Your task is to, given two positive integers, \$x\$ and \$n\$, return the first \$x\$ numbers in the incremental ranges sequence.
The incremental range sequence first generates a range from one to \$n\$ inclusive. For example, if \$n\$ was \$3\$, it would generate the list \$[1,2,3]\$. It then repeatedly appends the last \$n\$ values incremented by \$1\$ to the existing list, and continues.
An input of \$n=3\$ for example:
```
n=3
1. Get range 1 to n. List: [1,2,3]
2. Get the last n values of the list. List: [1,2,3]. Last n=3 values: [1,2,3].
3. Increment the last n values by 1. List: [1,2,3]. Last n values: [2,3,4].
4. Append the last n values incremented to the list. List: [1,2,3,2,3,4]
5. Repeat steps 2-5. 2nd time repeat shown below.
2nd repeat:
2. Get the last n values of the list. List: [1,2,3,2,3,4]. Last n=3 values: [2,3,4]
3. Increment the last n values by 1. List: [1,2,3,2,3,4]. Last n values: [3,4,5].
4. Append the last n values incremented to the list. List: [1,2,3,2,3,4,3,4,5]
```
**Test cases:**
```
n, x, Output
1, 49, [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, 100, [1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,14,14,15,15,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,30,30,31,31,32,32,33,33,34,34,35,35,36,36,37,37,38,38,39,39,40,40,41,41,42,42,43,43,44,44,45,45,46,46,47,47,48,48,49,49,50,50,51]
3, 13, [1,2,3,2,3,4,3,4,5,4,5,6,5]
```
[Answer]
# [Python 2](https://docs.python.org/2/), 39 bytes
```
lambda n,x:[v/n+v%n+1for v in range(x)]
```
**[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFPp8Iqukw/T7tMNU/bMC2/SKFMITNPoSgxLz1Vo0Iz9j9IqCS1uAQkqqFhqKNgYqmpo6BhpKNgaGAAYhkDWcaamlZcnAVFmXklYMU6CupW6jCBNA0tkJgmlP8fAA "Python 2 – Try It Online")**
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ḷd§‘
```
A dyadic Link accepting two positive integers, `x` on the left and `n` on the right, which yields a list of positive integers.
**[Try it online!](https://tio.run/##y0rNyan8///hjm0ph5Y/apjx//9/Q@P/xgA "Jelly – Try It Online")**
### How?
```
Ḷd§‘ - Link: x, n e.g 13, 3
Ḷ - lowered range (x) [0,1,2,3,4,5,6,7,8,9,10,11,12]
d - divmod (n) [[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2],[3,0],[3,1],[3,2],[4,0]]
§ - sums [0,1,2,1,2,3,2,3,4,3,4,5,4]
‘ - increment (vectorises) [1,2,3,2,3,4,3,4,5,4,5,6,5]
```
[Answer]
# [R](https://www.r-project.org/), 33 bytes
```
function(n,x,z=1:x-1)z%%n+z%/%n+1
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNPp0KnytbQqkLXULNKVTVPu0pVH0ga/k/TMNQxsdTkStMw0jE0MAAxjHUMjTW5/gMA "R – Try It Online")
Ports [Jonathan Allan's Python solution](https://codegolf.stackexchange.com/a/186243/67312).
# [R](https://www.r-project.org/), 36 bytes
```
function(n,x)outer(1:n,0:x,"+")[1:x]
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNPp0Izv7QktUjD0CpPx8CqQkdJW0kz2tCqIvZ/moaxjqGx5n8A "R – Try It Online")
My original solution; generates an \$n\times x\$ matrix with each column as the increments, i.e., \$1 \ldots n, 2\ldots n+1,\ldots\$, then takes the first \$x\$ entries (going down the columns).
[Answer]
# [J](http://jsoftware.com/), ~~13~~ 12 bytes
```
[$[:,1++/&i.
```
[Try it online!](https://tio.run/##PZG5TgQxEAVzvqKEEMtqD9yH55KIkIiISDdErICE/4@G8bwBqR3arqr@nm/PuytPEzuOFKblnM48v72@zJe7y3S0w@Hx/us8728@3j9/eMiRK7bnNGE4QVLp6BkYsYIZ5lhgiVWsw3pswEa84MsdxwNPvOId3uMDPhKFMGJ5MogkKtERPTEQI1lII51cfkyykh3ZkwM5bmhWysLm/2yNrvE1wsbYKBtnIxWrcEUsaHELXfQSkMOqsZlIRj5SkpXE5CY9Ga6Sm6dUZSthOUtb5pKX/5pgq6AQaqEcKqIo6qI0qtMCtallHfuLFUurWFtti9QytVAttd7Mvw "J – Try It Online")
## how
We take `x` as the left arg, `n` as the right. Let's take `x = 8` and `n = 3` for this example:
* `+/&i.`: Transform both args by creating integer ranges `i.`, that is, the left arg becomes `0 1 2 3 4 5 6 7` and the right arg becomes `0 1 2`. Now we create an "addition table `+/` from those two:
```
0 1 2
1 2 3
2 3 4
3 4 5
4 5 6
5 6 7
6 7 8
7 8 9
```
* `1 +`: Add 1 to every element of this table:
```
1 2 3
2 3 4
3 4 5
4 5 6
5 6 7
6 7 8
7 8 9
8 9 10
```
* `[: ,`: Flatten it `,`:
```
1 2 3 2 3 4 3 4 5 4 5 6 5 6 7 6 7 8 7 8 9 8 9 10
```
* `[ $`: Shape it `$` so it has the same number of elements as the original, untransformed left arg `[`, ie, `x`:
```
1 2 3 2 3 4 3 4
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 18 bytes
```
{(1..*X+ ^*)[^$_]}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WsNQT08rQlshTkszOk4lPrb2f3FipUKahl60YawmkDSI1VRIyy/i0jDUUTCx1NTh0jDSUTA0MACxjIEsY02d/wA "Perl 6 – Try It Online")
Curried function `f(x)(n)`.
### Explanation
```
{ } # Anonymous block
X+ # Cartesian product with addition
1..* # of range 1..Inf
^* # and range 0..n
( )[^$_] # First x elements
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
L<s‰O>
```
Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/186242/52210), so make sure to upvote him!
First input is \$x\$, second input is \$n\$.
[Try it online](https://tio.run/##yy9OTMpM/f/fx6b4UcMGf7v//w2NuYwB) or [verify all test cases](https://tio.run/##yy9OTMpM/W/s5ulir6SQmJeioGQPZj5qmwRk/vexKX7UsMHf7r/Of0MuE0suIy5DAwMuYy5DYwA).
**Explanation:**
```
L # Push a list in the range [1, (implicit) input]
# i.e. 13 → [1,2,3,4,5,6,7,8,9,10,11,12,13]
< # Decrease each by 1 to the range [0, input)
# → [0,1,2,3,4,5,6,7,8,9,10,11,12]
s‰ # Divmod each by the second input
# i.e. 3 → [[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2],[3,0],[3,1],[3,2],[4,0]]
O # Sum each pair
# → [0,1,2,1,2,3,2,3,4,3,4,5,4]
> # And increase each by 1
# → [1,2,3,2,3,4,3,4,5,4,5,6,5]
# (after which the result is output implicitly)
```
---
My own initial approach was **8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)**:
```
LI∍εN¹÷+
```
First input is \$n\$, second input is \$x\$.
[Try it online](https://tio.run/##yy9OTMpM/f/fx/NRR@@5rX6Hdh7erv3/vzGXoTEA) or [verify all test cases](https://tio.run/##yy9OTMpM/W/s5nl4Qqi9kkJiXoqCkr2nSxiQ/ahtEpD93yfyUUfvua1@EYe3a/@v1flvyGViyWXEZWhgwGXMZWgMAA).
**Explanation:**
```
L # Push a list in the range [1, (implicit) input]
# i.e. 3 → [1,2,3]
I∍ # Extend it to the size of the second input
# i.e. 13 → [1,2,3,1,2,3,1,2,3,1,2,3,1]
ε # Map each value to:
N¹÷ # The 0-based index integer-divided by the first input
# → [0,0,0,1,1,1,2,2,2,3,3,3,4]
+ # Add that to the value
# → [1,2,3,2,3,4,3,4,5,4,5,6,5]
# (after which the result is output implicitly)
```
[Answer]
# [Haskell](https://www.haskell.org/), 31 bytes
```
n#x=take x$[1..n]++map(+1)(n#x)
```
[Try it online!](https://tio.run/##HckxDsAQFADQq/yEgRCJqm5OIgaDpIIfaQ1ur43hTe@Ob0m1roVkuhFLgkm9VgqDEC12JjRnf/HVYkbXn4wDKBiiDYBz4LU8pNnOzW6XtGF9 "Haskell – Try It Online")
This might be my favorite kind of recursion. We start with the values from 1 to n and then concatenate those same values (via self-reference) +1. then we just take the first x values.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 25 bytes
```
@(n,x)((1:n)'+(0:x))(1:x)
```
Anonymous function that inputs numbers `n` and `x`, and outputs a row vector.
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BI0@nQlNDw9AqT1NdW8PAqkJTE8ip0PyfpmGsY2is@R8A "Octave – Try It Online")
## How it works
Consider `n=3` and `x=13`.
The code `(1:n)'` gives the column vector
```
1
2
3
```
Then `(0:x)` gives the row vector
```
0 1 2 3 4 5 6 7 8 9 10 11 12 13
```
The addition `(1:n)'+(0:x)` is element-wise with broadcast, and so it gives a matrix with all pairs of sums:
```
1 2 3 4 5 6 7 8 9 10 11 12 13 14
2 3 4 5 6 7 8 9 10 11 12 13 14 15
3 4 5 6 7 8 9 10 11 12 13 14 15 16
```
Indexing with `(1:x)` retrieves the first `x` elements of this matrix in column-major linear order (down, then across), as a row vector:
```
1 2 3 2 3 4 3 4 5 4 5 6 5
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 100 bytes
```
(<>)<>{({}[()]<(({}))((){[()](<{}>)}{}){{}{}<>(({})<>)(<>)(<>)}{}({}[()]<(<>[]({}())[()]<>)>)>)}{}{}
```
With comments and formatting:
```
# Push a zero under the other stack
(<>)<>
# x times
{
# x - 1
({}[()]<
# Let 'a' be a counter that starts at n
# Duplicate a and NOT
(({}))((){[()](<{}>)}{})
# if a == 0
{
# Pop truthy
{}
<>
# Reset n to a
(({})<>)
# Push 0 to each
(<>)(<>)
}
# Pop falsy
{}
# Decrement A, add one to the other stack, and duplicate that number under this stack
({}[()]<
(<>[]({}())<>)
>)
>)
}
```
[Try it online!](https://tio.run/##bVC9CoMwEN7zFAddLoNQcVWnzm2HbuIQraIoKv5AS8iz20ssqZEKwcv3x3fJRlF3XtmKZl0xjHkYMyYZ0HeCF3jgmxmlSpCnITO3jb0sQ1vnYi5AdE@43h6WQ5JzjsilNmEoVcwVQXt3XUIHUQRni0k7bYp7P8A8LnP1dghJSQ6gGx@cy1RReibyxmFML9rxr/4Mcw@FyCvXQnJ9LKj2S@iKpWinX0O54@2jHQKTlBjk3JC76O9IP6WXXFc/YMEH "Brain-Flak – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
+þẎḣ’
```
[Try it online!](https://tio.run/##ARoA5f9qZWxsef//K8O@4bqO4bij4oCZ////M/8xMw "Jelly – Try It Online")
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 34 bytes
```
: f 0 do i over /mod + 1+ . loop ;
```
[Try it online!](https://tio.run/##FYw7DoMwFMB2TmGxIkISWCgSd6kIaSsVvaeUz/HTsNiL5Shpf7eveCvnBxFLED7IuSa6TQINrsHwFVGmkihLwodD@V1PxWMSww1TQztTl0kppsoxjGjlcdYW97gezX8 "Forth (gforth) – Try It Online")
### Code Explanation
```
: f \ start a new word definition
0 do \ start a loop from 0 to x-1
i \ put the current loop index on the stack
over \ copy n to the top of the stack
/mod \ get the quotient and remainder of dividing i by n
+ 1+ \ add them together and add 1
. \ output result
loop \ end the counted loop
; \ end the word definition
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~16~~, 10 bytes
```
:!i:q+2G:)
```
[Try it online!](https://tio.run/##y00syfn/30ox06pQ28jdSvP/f2MuQ2MA "MATL – Try It Online")
-6 bytes saved thanks to Guiseppe and Luis Mendo!
Explanation:
```
:! % Push the array [1; 2; ... n;]
i:q % Push the array [0 1 2 ... x - 1]
+ % Add these two arrays with broadcasting
2G % Push x again
:) % Take the first x elements
```
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 8 bytes
```
…@┅+‡t_<
```
[Try it online!](https://tio.run/##S0/MTPz//1HDModHU1q1HzUsLIm3@f/fmMvQGAA "Gaia – Try It Online")
Does basically the same thing as the [Octave](https://codegolf.stackexchange.com/a/186256/67312) and [MATL](https://codegolf.stackexchange.com/a/186258/67312) answers.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 32 bytes
```
->n,x{(0...x).map{|i|i/n+i%n+1}}
```
[Try it online!](https://tio.run/##KypNqvyfZhvzX9cuT6eiWsNAT0@vQlMvN7GguiazJlM/TztTNU/bsLb2f4FCWrShjoKJZSwXiGmko2BoYABhGwPZxrH/AQ "Ruby – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-m`](https://codegolf.meta.stackexchange.com/a/14339/), ~~12~~ 7 bytes
Port of [Jonathan's Python solution](https://codegolf.stackexchange.com/a/186243/58974).
Takes `x` as the first input.
```
%VÄ+UzV
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW0&code=JVbEK1V6Vg&input=MTMsMw)
[Answer]
## Haskell, ~~34~~ 33 bytes
```
n#x=take x$do j<-[1..];[j..j+n-1]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P0@5wrYkMTtVoUIlJV8hy0Y32lBPL9Y6OktPL0s7T9cw9n9uYmaegq1CSj6XgkJBUWZeiYKKgqGCsoKJJZKAEVDA0MAAScQYJGL8HwA "Haskell – Try It Online")
[Answer]
# JavaScript, 36 bytes
```
n=>g=x=>x?[...g(--x),1+x%n+x/n|0]:[]
```
[Try It Online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1i7dtsLWrsI@Wk9PL11DV7dCU8dQu0I1T7tCP6/GINYqOvZ/cn5ecX5Oql5OfrpGmoahpoaJpaZ2QkxegiYXqpSRpoahgQF2OWOgnDFQKkHzPwA)
[Answer]
# [Perl 5](https://www.perl.org/) `-na`, 43 bytes
```
@r=map$_..$_+$F[1]-1,1..$_;say"@r[0..$_-1]"
```
[Try it online!](https://tio.run/##K0gtyjH9/9@hyDY3sUAlXk9PJV5bxS3aMFbXUMcQxLMuTqxUciiKNgBxdA1jlf7/NzRQMP6XX1CSmZ9X/F/X11TPwNDgv25iHgA "Perl 5 – Try It Online")
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), ~~17~~ 16 bytes
```
{y#,/1_y(1+)\!x}
```
[Try it online!](https://tio.run/##y9bNz/7/P82qulJZR98wvlLDUFszRrGi9n9atLG1oXHsfwA "K (oK) – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 6 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
⌐çYæ▄9
```
[Run and debug it](https://staxlang.xyz/#p=a9875991dc39&i=1+49%0A2+100%0A3+13&a=1&m=2)
Unpacked & explained:
```
rmx|%+^ Full program, implicit input (n, x on stack; n in register X)
r Range [0 .. x)
m Map:
x|% Divide & modulo x
+ Add quotient and remainder
^ Add 1
Implicit output
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~8~~ 10 bytesSBCS
```
⊢↑∘∊⊣,/∘⍳⌈
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgmG/x91LXrUNvFRx4xHHV2Puhbr6IOYvZsf9XT8TwMqeNTbB1Hb1XxovTFIZd/U4CBnIBni4Rn831AhTcHEkssISBkaGHAZg2hjMGXEZQkkzQE "APL (Dyalog Unicode) – Try It Online")
A dyadic train. Left arg = interval (n), right arg = number of terms (x). `⎕IO←1`.
### How it works
```
⊢↑∘∊⊣,/∘⍳⌈ ⍝ Left: interval n, Right: terms x
∘⍳⌈ ⍝ Generate range [1..max(n,x)]
⍝ (Too short array will complain at N-wise reduce)
⊣,/ ⍝ Extract length-n intervals (dyadic N-wise reduce)
∘∊ ⍝ Flatten and list the elements into a vector
⊢↑ ⍝ Take first x terms from the above
```
---
Porting [Jonah's J answer](https://codegolf.stackexchange.com/a/186247/78410) would be 10 bytes in Extended (traditional APL doesn't have an equivalent to J's `&`):
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 10 bytes
```
⊣↑∘,1++\⍥⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/x91LX7UNvFRxwwdQ23tmEe9Sx/1bv6fBpR61NsHUdXVfGi9MUhN39TgIGcgGeLhGfzfxFIhTcGQy9DAAEgbcRkaAyljAA "APL (Dyalog Extended) – Try It Online")
Uses `⎕IO←0`. If `⎕IO←1` were used, I'd need to replace `1+` with `¯1+`, costing one more byte (instead of saving two bytes).
### How it works
```
⊣↑∘,1++\⍥⍳ ⍝ Left: x, Right: n
⍥⍳ ⍝ Create 0-based ranges for both args
+\ ⍝ Outer product by addition (shortcut of ∘.+)
1+ ⍝ Increment
∘, ⍝ Flatten the matrix into a vector
⊣↑ ⍝ Take first x elements
```
[Answer]
# [Alchemist](https://github.com/bforte/Alchemist), 77 bytes
```
_->In_n+In_x
x+n+0y+0z->a+Out_a+Out_" "+m+y
y+n->n
y+0n->z
z+m+a->z+n
z+0m->a
```
[Try it online!](https://tio.run/##S8xJzkjNzSwu@f8/XtfOMy8@TxtIVHBVaOdpG1RqG1Tp2iVq@5eWxENIJQUl7VztSq5K7TxduzwgZQCkq7iqgIKJQIZ2HpBpkAvU8/@/EZehgQEA "Alchemist – Try It Online")
Increments and outputs a counter n times, then subtracts n-1 before repeating.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes
```
NθFN⊞υ⊕⎇‹ιθι§υ±θIυ
```
[Try it online!](https://tio.run/##TYyxDoMwDER3vsKjI6VDxchUdYpUIQZ@IAS3IIEpjlOVr0/D1ltO7/R0YfISNr/k7PidtE3rQIK7aarnJoD/ozHQpThhsuA4CK3ESiP2JOzlwAfFiLOF3VgodVPHI31Pu6WXVyqnZ5qqk5kV7z4qpsI513Ct8@Wz/AA "Charcoal – Try It Online") Link is to verbose version of code. I had dreams of seeding the list with a zero-indexed range and then slicing it off again but that was actually 2 bytes longer. Explanation:
```
Nθ Input `n` into variable
N Input `x`
F Loop over implicit range
ι Current index
‹ Less than
θ Variable `n`
⎇ ι Then current index else
θ Variable `n`
± Negated
§υ Cyclically indexed into list
⊕ Incremented
⊞υ Pushed to list
Iυ Cast list to string for implicit output
```
[Answer]
# **JS, 54 bytes**
```
f=(n,x)=>Array.from(Array(x),(_,i)=>i+1-(i/n|0)*(n-1))
```
[Try it online!](https://tio.run/##HclBCoAgEEDR68yUmrZqY9BJQiTDMA0NMejuJu0@7x8qq6SjvW6ap1qNBE8KynmJUT3MxHDCn1CQwEpsW7YXFOzgX44deCoQqw4@BbcxF3YwMBLBedP6AQ)
[Answer]
# [Perl 5](https://www.perl.org/), 39 bytes
```
say 1+int($_/$F[1])+$_%$F[1]for 0..$_-1
```
[Try it online!](https://tio.run/##K0gtyjH9/784sVLBUDszr0RDJV5fxS3aMFZTWyVeFcxKyy9SMNDTU4nXNfz/39BYwZjLxFLBkMvQwEDB6F9@QUlmfl7xf11fUz0DQ4P/uol5AA "Perl 5 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 49 44 bytes
Using recursion to save some bytes.
```
f(n,x){x&&printf("%d ",x%n+x/n+1,f(n,--x));}
```
[Try it online!](https://tio.run/##NY1NCoMwEIX3nmIIKIlOaK3dtKE3cRMipkI7FbU2IF69aVJxM28@eD9GWmO8bzmhE4vLsn7oaGo5Sxtg6FIq3IGKEqNBSieEWv386hqwPPiAEKI4AQvsSbqlDYIL91pTPTGMLicUbCMK@vc0csbCtyZJjD91R/86PViDYO56gDwPMIfeBCCMlQjni1AbnBDK43GnKlAVYPVf0z60Hb38/AA "C (gcc) – Try It Online")
[Answer]
# APL+WIN, ~~29 23~~ 16 bytes
```
x↑,1+(⍳x←⎕)∘.+⍳⎕
```
Index origin = 0 and prompts for n and x
[Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlwPWooz3tf8Wjtok6htoaj3o3A5kTgLKajzpm6GkD@UD2f6Ca/2lchlwmllxpXEZchgYGQNqYy9AYAA "APL (Dyalog Classic) – Try It Online")
[Answer]
# C(clang), 843 bytes
```
#include <stdlib.h>
main(int argc, char* argv[]){
int x,n;
if (argc == 3 && (n = atoi(argv[1])) > 0 && (x = atoi(argv[2])) > 0){
int* ranges = calloc(x, sizeof *ranges);
for (int i = 0; i < x; i++){
if (i < n){
ranges[i] = i+1;
}
else {
ranges[i] = ranges[i-n] + 1;
}
}
printf("[");
for (int j = 0; j < x - 1; j++){
printf("%d",ranges[j]);
printf(",");
}
printf("%d",ranges[x - 1]);
printf("]\n");
free(ranges);
}
else {
printf("enter a number greater than 0 for n and x\n");
}
}
```
[Answer]
# [Icon](https://github.com/gtownsend/icon), 48 bytes
```
procedure f(x,n)
write((0to n)+(1to x))\n&\z
end
```
[Try it online!](https://tio.run/##y0zOz/v/v6AoPzk1pbQoVSFNo0InT5OrvCizJFVDw6AkXyFPU1vDEEhXaGrG5KnFVHGl5qUgachNzMzT0ORSAII0DWMdQ2NNsAIA "Icon – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 41 bytes
```
x=>n=>new int[x].Select((_,a)=>a/n+a%n+1)
```
[Try it online!](https://tio.run/##Sy7WTS7O/O9Wmpdsk5lXogNneLrmleamFiUm5aSC@HZ2dgppCrYK/yts7fKAKLVcASgaXRGrF5yak5pcoqERr5OoaWuXqJ@nnaiap22o@d@aK7wosyTVJzMvVaO4pCgzL13PKz8zT0NJR0knTcPEUlPDUFNTE78qQwMDTQ0jwsqMNTWMQar@AwA "C# (Visual C# Interactive Compiler) – Try It Online")
]
|
[Question]
[
I have a list of decimal digits:
`4, 4, 4, 7, 7, 9, 9, 9, 9, 2, 2, 2, 4, 4`
The list of decimal digits are known as items. We can form "chunks" from these items by grouping together identical and adjacent numbers. I want to assign each chunk a unique number, starting from 1, and increasing by 1 in the order the chunks appear in the original list. So, the output for the given example would look like this:
`1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 5, 5`
## Input format
A list of digits. (0-9) You may use your language built-ins to read this list however you want. Encoding: ASCII
# Output format
A series of decimal numbers, separated by a delimiter. Your program must always use the same delimiter. The delimiter must be longer than 0 bits. Encoding: ASCII
Standard loopholes apply.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 41 bytes
```
lambda l,n=0:[n:=n+(l!=(l:=x))for x in l]
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPqfZhvzPycxNyklUSFHJ8/WwCo6z8o2T1sjR9FWI8fKtkJTMy2/SKFCITNPISf2f45ttImOAgSZg5ElEjKCIZCCWK6Cosy8Eo00jRxNzf8A "Python 3.8 (pre-release) – Try It Online")
Praise the magic walrus `:=` of assignment expressions.
---
# [Python 2](https://docs.python.org/2/), 42 bytes
```
n=0
for x in input():n+=x!=id;id=x;print n
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8/WgCstv0ihQiEzD4gKSks0NK3ytG0rFG0zU6wzU2wrrAuKMvNKFPL@/4821FGAICMwMkZCJjBkCkSxAA "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 44 bytes
```
l=input()
n=0
for i in l:n+=i!=l;l=i;print n
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8c2M6@gtERDkyvP1oArLb9IIVMhM08hxypP2zZT0TbHGqjAuqAoM69EIe//fw0THQUIMgcjSyRkBEMgBZoA "Python 2 – Try It Online")
[Answer]
# [APL (dzaima/APL)](https://github.com/dzaima/APL), 7 [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. Prints space-separated.
```
+\1,2≠/
```
[Try it online!](https://tio.run/##SyzI0U2pSszMTfyf9qhtgsZ/7RhDHaNHnQv0/2v@T1Mw0YEiczCyREJGMARS8C@/oCQzP6/4v24xAA "APL (dzaima/APL) – Try It Online")
`2≠/` pair-wise inequality
`1,` prepend 1
`+\` cumulative sum
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ 5 bytes
```
ŒɠµJx
```
[Try it online!](https://tio.run/##y0rNyan8///opJMLDm31qvj//3@0iY4CBJmDkSUSMoIhqIJYAA "Jelly – Try It Online")
Saved one byte thanks to [UnrelatedString](https://codegolf.stackexchange.com/users/85334/unrelated-string)!
Inputs and outputs as array's (with opening/closing brackets)
## How it works
```
ŒɠµJx - Main link, takes one argument: [7, 7, 5, 5, 5, 1]
Œɠ - Get the lengths of consecutive elements: [2, 3, 1]
µ - Call these lengths A
J - range(length(A)) [1, 2, 3]
x - Repeat each element by the corresponding value in A: [1, 1, 2, 2, 2, 3]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ŒgƤẈ
```
**[Try it online!](https://tio.run/##y0rNyan8///opPRjSx7u6vj//3@0iY4CBJmDkSUSMoIhqIJYAA "Jelly – Try It Online")**
### How?
```
ŒgƤẈ - Link: list of integers e.g. [7,7,2,7,7]
Ƥ - for prefixes: [7] [7,7] [7,7,2] [7,7,2,7] [7,7,2,7,7]
Œg - group runs [[7]] [[7,7]] [[7,7],[2]] [[7,7],[2],[7]] [[7,7],[2],[7,7]]
Ẉ - length of each [1, 1, 2, 3, 3]
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/) / MATLAB, 25 bytes
```
@(x)cumsum([1 ~~diff(x)])
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0IzuTS3uDRXI9pQoa4uJTMtDSgUq/k/TSPaREcBgszByBIJGcEQSAFQNQA "Octave – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 29 bytes
```
Join@@(i=1;0#+i++&/@Split@#)&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE7876Zg@98rPzPPwUEj09bQ2kBZO1NbW03fIbggJ7PEQVlTDajCQaHaREcBgszByBIJGcEQSEHt//@6BUWZeSUA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
¥Ā.¥>
```
[Try it online!](https://tio.run/##yy9OTMpM/f//0NIjDXqHltr9/x9toqMAQeZgZImEjGAIqiAWAA "05AB1E – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 40 bytes
```
f(a:t)=1:map(+sum[1|a/=t!!0])(f t)
f e=e
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00j0apE09bQKjexQEO7uDQ32rAmUd@2RFHRIFZTI02hRJMrTSHVNvV/bmJmnoKtQkFRZl6JgopCmkK0iY4CBJmDkSUSMoIhkILY//@S03IS04v/6yYXFAAA "Haskell – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 21 bytes
```
{+<<[\+] $,|$_ Zne$_}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1rbxiY6RjtWQUWnRiVeISovVSW@9n9xYqVCmka0iY4CBJmDkSUSMoIhkIJYzf8A "Perl 6 – Try It Online")
Anonymous code block that takes a list and returns a list. This works by comparing whether each pair of adjacent elements are not equal, than taking the cumulative sum of the list.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
γdƶ˜
```
[Try it online!](https://tio.run/##yy9OTMpM/f//3OaUY9tOz/n/P9pERwGCzMHIEgkZwRBIQSwA "05AB1E – Try It Online")
```
γ # group adjacent equal digits together
d # replace all digits with 1
ƶ # multiply each group by its 1-based index
˜ # flatten
```
[Answer]
# [R](https://www.r-project.org/), 33 bytes
```
function(x)cumsum(c(1,!!diff(x)))
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQjO5NLe4NFcjWcNQR1ExJTMtDSimqfk/DShioqMAQeZgZImEjGAIpACoHAA "R – Try It Online")
Uses the same cumulative sum method as [Luis Mendo](https://codegolf.stackexchange.com/a/189943/66252) and others.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 8 bytes
```
Y'wn:wY"
```
[Try it online!](https://tio.run/##y00syfn/P1K9PM@qPFLp//9oEx0FCDIHI0skZARDIAWxAA "MATL – Try It Online")
Explanation:
```
Y' % run-length encoding
w % swap elements in stack
n % number of elements in array / size along each dimension
: % range; vector of equally spaced values
w % swap elements in stack
Y" % replicate elements of array
% (implicit) convert to string and display
```
[Answer]
# JavaScript (ES6), 30 bytes
Takes input as an array of integers.
```
a=>a.map(p=n=>i+=p!=(p=n),i=0)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i5RLzexQKPANs/WLlPbtkDRFsTW1Mm0NdD8n5yfV5yfk6qXk5@ukaYRbaKjAEHmYGSJhIxgCKQgVlPzPwA "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // a[] = input array
a.map(p = // initialize p to a non-numeric value
n => // for each value n in a[]:
i += // increment i if:
p != (p = n), // p is not equal to n; and update p to n
i = 0 // start with i = 0 (chunk counter)
) // end of map()
```
[Answer]
# Oracle SQL, 121 bytes
```
select m from t match_recognize(order by i measures match_number()m all rows per match pattern(p+)define p as x=first(x))
```
Test in SQL\*PLus.
```
SQL> with t(i,x) as (select rownum,value(v) from table(sys.odcinumberlist(4, 4, 4, 7, 7, 9, 9, 9, 9, 2, 2, 2, 4, 4))v)
2 select m from t match_recognize(order by i measures match_number()m all rows per match pattern(p+)define p as x=first(x))
3 /
M
----------
1
1
1
2
2
3
3
3
3
4
4
4
5
5
14 rows selected.
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
▓ª2ªmD?Ä╧╖
```
[Run and debug it](https://staxlang.xyz/#p=b2a632a66d443f8ecfb7&i=4,+4,+4,+7,+7,+9,+9,+9,+9,+2,+2,+2,+4,+4&a=1)
The output uses space as a delimiter. The input follows the precise specifications using commas as separators, and now enclosing braces.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 62 61 bytes
This is one of the few entries I've done where a complete program is shorter than a function submission!
On the first pass, I don't care about the previous value, so I get to rely on the fact that `argv` is a pointer to somewhere and is extremely unlikely to be between [0..9]!
```
s;main(i,j){for(;~scanf("%d,",&i);j=i)printf("%d ",s+=j!=i);}
```
[Try it online!](https://tio.run/##S9ZNT07@/7/YOjcxM08jUydLszotv0jDuq44OTEvTUNJNUVHSUctU9M6yzZTs6AoM68ELKigpFOsbZulCBS0rv3/30RHAYLMwcgSCRnBEEjBv@S0nMT04v@65QA "C (gcc) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~46~~ 43 bytes
```
scanl(+)1.map fromEnum.(zipWith(/=)=<<tail)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P822ODkxL0dDW9NQLzexQCGtKD/XNa80V0@jKrMgPLMkQ0PfVtPWxqYkMTNH839uYmaegq1CQVFmXomCikKaQrSJjgIEmYORJRIygiGQgtj/AA "Haskell – Try It Online")
Anonymous pointfree function that takes a list and returns a list
[Answer]
# [J](http://jsoftware.com/), 12 bytes
```
1+/\@,2~:/\]
```
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8N9QWz/GQceozko/Jva/JpeSnoJ6mq2euoKOQq2VQloxF1dqcka@QpqCCRiaA6ElFBqBIVD0PwA "J – Try It Online")
Similar to [Adám's APL answer](https://codegolf.stackexchange.com/a/189945/75681)
```
2~:/\] - pair-wise inequality
1 , - prepend 1
@ - and
+/\ - find the cumulative sum
```
[Answer]
# [Perl 5](https://www.perl.org/), 27 bytes
```
s/\d/$i+=$&!=$p;$p=$&;$i/ge
```
[Try it online!](https://tio.run/##K0gtyjH9/79YPyZFXyVT21ZFTdFWJcdaJQfIslbJ1E9P/f/fREcBgszByBIJGcEQSMG//IKSzPy84v@6BQA "Perl 5 – Try It Online")
The command line option `-p` makes perl read the input line from STDIN into the "default variable" `$_`. It then search-replaces all digits in `$_` with the counter `$i`. And `$i` is increased for each digit which is different than the previous digit, which it also is at the first digit so the counter starts at `1`. The previous digit is stored in `$p`.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~13~~ 11 bytes
```
s.e*]hkhbr8
```
[Try it online!](https://tio.run/##K6gsyfj/v1gvVSs2Izsjqcji/38THQUIMgcjSyRkBEMgBQA "Pyth – Try It Online")
```
r8 # Run-length encode (implicit argument is the input) (-> [[frequency, char], ...]
.e # Enumerated map (current element is b, index is k) over rQ8
*]hk # [ k+1 ] *
hb # b[0]
s # Reduce list on + ([a]+[b] = [a,b])
```
-2 bytes thanks to Mr. Xcoder
[Answer]
# [Scala](http://www.scala-lang.org/), 114 bytes
```
s.split(", ").zipWithIndex.scan(s.head,0){(a,b)=>if(a._1==b._1)a else b._1->(a._2+1)}.tail.unzip._2.mkString(", ")
```
[Try it online!](https://tio.run/##TY29CsIwFIX3PEXolGANtgiikIKjg5ODo9w2iY3GGEyEYumzx9QqCB/n/h3u8Q0YiPf6IpuA96Atll2QVni8da5HSEiFFfGbQ3hoe6bfyvvomXdGB5LlOKPspd1Rh3ZnheyYb8ASz1oJIl/QnkBeU15pRYCdCs7rpBSwNF7isZ9X46GcFXRgAbRhT5vepQ27Xae4KSQOyKUpGEsUyZY5nlh9WP9R/hgNGaVoiG8 "Scala – Try It Online")
[Answer]
# [Scala](http://www.scala-lang.org/), 75 bytes
```
s=>s.scanLeft(("",0))((x,y)=>(y,x._2+(if(x._1!=y)1 else 0))).tail.map(_._2)
```
[Try it online!](https://tio.run/##TY7BCsIwEETv/Yo1pw2GoCKIQgoehd48ipRYU4nENJhFWsRvj7EiCO8wA49hYqOdTt3pahqCBkxPxp8jbEOAZ1E8tIN2U9lIhz3drb8cVTm2naejSlGVUcZG@8q0hMiYmHGO2IuBqxIH0ct6MUXbYg7ziRr4HIyLBrLFJWnr5E0HrLPFU8jz5Dy2yJYCvqxG1n8sfnwEJmNwlpAJYHmv@zzjvHil9AY "Scala – Try It Online")
If input and output must be comma separated **String** (and not List) then 102 bytes.
```
s=>s.split(", ").scanLeft(("",0))((x,y)=>(y,x._2+(if(x._1!=y)1 else 0))).tail.map(_._2).mkString(", ")
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
nƝÄŻ‘
```
[Try it online!](https://tio.run/##y0rNyan8/z/v2NzDLUd3P2qY8f//fxMdBQgyByNLJGQEQ1AFAA "Jelly – Try It Online")
I initially aimed for a 4-byter (the same program but without the `Ż`) but then quickly realized that a **1** had to be prepended every time due to an oversight... Even though there is another 5-byter in Jelly, I'll actually keep this because it uses a different method.
For each pair of neighbouring items of the input list \$L\$, test if \$L\_i\ne L\_{i+1}, \forall 1\le i<|L|\$ and save these results in a list. Then take the cumulative sum of this list and increment them by **1** to match the chunk indexing system. **TL;DR.** Whenever we encounter different neighbouring items, we increment the chunk index by **1**.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 62 bytes
```
f(_,l)int*_;{printf("%d ",l=--l?f(_,l)+(_[l]!=_[l-1]):1);_=l;}
```
[Try it online!](https://tio.run/##XY3hCoIwFIX/7ylsEGx1R2mW2ZAeRGSEZQibSdqfZM@@7jQh4hwuh3M@uKW4l6VzFVOged30KyWH9omhYnR5DSjoTAh9nvY1U7kuFhleERb8FHKpMi2tQz4wl7phfCA@67zIhhiCycno9MfRbA9YIMbzIXhFqB3EsIcDJHBEpbAd@xh7XK0kFdPQ1e/bAwPffBP@5Vy2r75jlHIPmRkyfxCx7gM "C (gcc) – Try It Online")
A function that takes the list and its length as arguments.
---
### [C (gcc)](https://gcc.gnu.org/), 60 bytes
```
f(_,l)int*_;{_=printf("%*d",--l?f(_,l)+(_[l]!=_[l-1]):2,0);}
```
[Try it online!](https://tio.run/##XY3hCoIwFIX/7ylsEGx2R2qW2ZAeRETCMoTNJO1Psmdfd5oQcQ6Xwzkf3Ercq8rampWgeNMOfinHMuueGGtG1/6VghDqPO8bVuaqWGV4RVjwUwQBl8Yi6@lL0zI@EpdVXmRjDN7sZHL642ixAwwQ7fgQnCLUDmLYwwESOKJSCKY@xh5XI0nNFPTN@/bAwLffhH85l91r6Bml3EF6gfQfRIz9AA "C (gcc) – Try It Online")
Outputs in unary, delimited by `0`s
[Answer]
# x86-16, 12 bytes
**Unassembled listing:**
```
NUM_LOOP:
AC LODSB ; load [SI] into AL, advance SI
3A C2 CMP AL, DL ; is this char same as last?
74 01 JZ SAME ; if so, same index
43 INC BX ; otherwise increment index
SAME:
92 XCHG AX, DX ; save current char for next compare
8A C3 MOV AL, BL ; put index value in AL to store
AA STOSB ; store AL into [DI], advance DI
E2 F4 LOOP NUM_LOOP ; keep looping
```
Input is byte array at `SI`, length in `CX`. Output is byte array at `DI`. Of course, this is if [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/) apply now.
**Example:** `SI = 120H`, `DI = 130H`
[](https://i.stack.imgur.com/6TBJI.png)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 38 bytes
```
->a{i=0;a.map{|x,y|p i+=(a==a=x)?0:1}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6xOtPWwDpRLzexoLqmQqeypkAhU9tWI9HWNtG2QtPewMqwtvZ/WnS0iY4CBJmDkSUSMoIhkILY2P8A "Ruby – Try It Online")
On the first iteration, `a` is equal to the input list, so we always increment the chunk count. On subsequent iterations it's equal to the previous element.
[Answer]
# [PHP](https://php.net/), 52 bytes
```
while(''<$d=$argv[++$x])echo$i+=$argv[$x-1]!=$d,' ';
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwMWlr6@QkllckJNYqZCZV1BawpWanJGvkJWfmaehrqCuo5BYVJRYGV@ck5mcqqGSWJRepmOoqamjEOAREO/q72P9vzwjMydVQ13dRiXFFiwfra2tUhGrCTJGJVMbKqZSoWsYq2irkqIDNNT6////JmBoDoSWUGgEhkBRAA "PHP – Try It Online")
Input via command line, output to `STDOUT`.
Thx to @Night2 for the pesky `'0' == 0` comparison bugfix!
[Answer]
# [Julia 1.0](http://julialang.org/), 56 bytes
```
l->foldl(l,init=(0,0))do(p,i),c
println(i+=p!=c)
c,i
end
```
[Try it online!](https://tio.run/##FcLBCoAgDADQu3/RbaMFRlGn9SPRITRhMVTCoL@34r3zVtn7pwau2i0hqVdQkiiFwZJF9AkyCZIz@ZJYNIK0nBt2aByJOaKvAdaRfgNNn3lDU18 "Julia 1.0 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 37 bytes
```
function(x,r=rle(x)$l)rep(seq(a=r),r)
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQqfItignVaNCUyVHsyi1QKM4tVAj0bZIU6dI83@aRrKGiY4CBJmDkSUSMoIhkAJNzf8A "R – Try It Online")
Not as golfy as [this answer](https://codegolf.stackexchange.com/a/189994/67312), but an alternative method using `rep`.
]
|
[Question]
[
Create a function which takes a polynomial equation, a value for `x` and returns the result of the operation.
Example: given `4x^2+2x-5` and `x=3` output `37`. This is the result of `4(3)^2+2(3)-5`
* Assume all polynomials are valid
* Polynomial format will always be `coefficient(variable)^exponent => 4x^2` except :
+ When exponent is `1` it will be `coefficient(variable) => 4x`
+ When coefficient is `1` it will be `(variable)^exponent => x^2`
* Polynomials are one variable only
* Use of external libraries are forbidden
* The coefficient and variable input can be positive and negative numbers.
Test cases
* `("3x^3-5x^2+2x-10", 5) => 250`
* `("10x^4-5x^3-10x^2+3x+50", 3) => 644`
* `("10x+20", 10) => 120`
* `("-20x^2+20x-50", -8) => -1490`
* `("9", 5) => 9`
* `("8x^2+5", 0) => 5`
---
**Update**
* Polynomial format will always be `coefficient(variable)^exponent => 4x^2` except :
+ When exponent is `1` it will be `coefficient(variable) => 4x`
+ When coefficient is `1` it will be `(variable)^exponent => x^2`
* Removed the rule of negative exponent. My mistake. A valid polynomial does not contain negative exponent
* An exponent of `0` would be just `coefficient`
* Added test case for `input 0`
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes win.
[Answer]
# JavaScript (ES7), 48 bytes
*Based upon a suggestion from @RickHitchcock*
Expects `X` in uppercase. Takes input in currying syntax `(p)(X)`.
```
p=>X=>eval(p.replace(/[X^]/g,c=>c<{}?'*X':'**'))
```
[Try it online!](https://tio.run/##bc5BCsIwEAXQvacQN00ap00mjajYeo0BMVBiFKXYouJGPHtNRFDULIZZzPs/h/pan91p313g2G58vy37rqyorPy1bliXnXzX1M6zfEV2ne/Grqzc4nZfJikl8yRNE8571x7PbeOzpt2xLRtpshoMWRRIoOSIM8P58PXyfIhGDr6IkmSLaDTEFYUmYaLUQQYyKYo/RGA8UfKd/tGi8KcF8JkdJjzDYfohAwFVzH6/RhZQhLIo8KsqIJmh6R8 "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES7), 49 bytes
Same approach as [@DeadPossum](https://codegolf.stackexchange.com/a/166110/58563). Takes input in currying syntax `(p)(x)`.
```
p=>x=>eval(p.split`x`.join`*x`.split`^`.join`**`)
```
[Try it online!](https://tio.run/##bc7RCoMgFAbg@z1F7CqTY3rMsV3Uo0jRahSRsSJ8@6ZtY1HzQg4Hv/@3LeZiLJ/NMEFv7tVSp8uQZjbNqrnowoGNQ9dMuc1Za5o@j9zw3ujvJsrJUpp@NF3FOvMI6/AsrZagrEaKFgQ/k1AREnxOHAeo@GlHBLc68UaCH5FKS5WX0klHLknyh1D0TwT/pW9aBB5aANdsd8MaDteNdAREcjt@zWpA6sq8wF2VQ5yhWl4 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 54 bytes
-2 bytes thanks to Jo King
-5 bytes thanks to Arnauld
```
lambda p,x:eval(p.replace('^','**').replace('x','*x'))
```
[Try it online!](https://tio.run/##VYvRCgIhEEXf@wrZF3V1QseECPqTEKyEAttkWWL6elv3obaXYTjnnvKebs8Baz6eao6P8zWyoumQXjGLsh1TyfGSBA9c877n8keoEeJS1jLeh4ll0TkKDjwFVEhgTaeZl5uvtYbCrmkH7UXlSPk2cv8jhQ1as6KASzBfWArYrxMKgGrumkFZPw "Python 2 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 53 50 48 bytes
**edit**: -5 bytes thanks to Dennis !
```
lambda p,x:eval(p.translate({94:"**",120:"*x"}))
```
[Try it online!](https://tio.run/##XY5BCsIwFET3nqJklTT9kvw0oAVvIoGILQq1DTXIF/HsNRUptbMYZvF4THjGS9@ZsTkcx9bfTmefhYKq@uFbHrZx8N299bHmr31ZsTxnhUaVBrG3EGMYrl3kDWeGnAFLDiUSaMWK7BcrxGamtCJXTpiBaaI0JO0EmxUlcaGYo9USA/wqUoNd0rD7k5EDlMm4FmK6/wE "Python 3 – Try It Online")
Used `translate` to avoid chaining `replace` calls; Python 3's version of `translate` is less awkward than its predecessor's.
[Answer]
# [R](https://www.r-project.org/), 44 bytes
```
function(f,x)eval(parse(t=gsub("x","*x",f)))
```
[Try it online!](https://tio.run/##bY1BCoMwEEX3nkLiJtOYkkwSaRf2KIIWFUG0RC3p6VNjpUjpLD4f/uON9UnfVba0L9qMdl6GeoIo2SuVIoOozX2zDPe5GwfapA7qZ9nTR2mnms55Oy0VJY6k5LRGAwC@pUS5QnHjCmTouBQkjQ3E30vyW4xGRCsohSt0IBUPFZlyzARewQ5mWu8gwzBIcTAdjVJuRo6bZ02@ifgFfkAu9fXz3BUc2SoOHMIfpzij8W8 "R – Try It Online")
Fairly straightforward with R. Replace `nx` with `n*x` and then `eval` the `parse`d string. `x` is used as this is how we name the second argument.
The eval function could even be used more directly with a properly formatted first argument, and other formal arguments (`y`, `z`, etc.) could be easily added:
### [R](https://www.r-project.org/), 20 bytes (non-competing)
```
function(f,x)eval(f)
```
[Try it online!](https://tio.run/##bc5RC4MgEAfw9z6F0IuX3dArY3toH2XQRkUwalgN9@mdthisdg96or/7a1x8766mMi/eDGaa@3qEKF5brmQBUVu6Zu5vUzf0vEkt1M/qzhtwLa/tw9TjGC6yxF4y1H4lQYlFJSFlGti34vLMSMvoRynpQb6wDJcDCT9J6KAzWFmR53smKLzxMWxXwSi1iUL6jA8bLvPxCBuEKj9tf@gRkgiBwRD8yZIH0u4N "R – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) 2.0, 13 bytes
```
OvUd^'*²'x"*V
```
[Try it](https://ethproductions.github.io/japt/?v=2.0a0&code=T3ZVZF4nKrIneCIqVg==&input=IjN4XjMtNXheMisyeC0xMCIKNQ==).
## Explanation:
```
OvUd^'*²'x"*V
U = Implicit first input
V = Implicit second input
Ov Eval:
Ud In U, replace:
^ "^" with:
'*² "**"
'x "x" with:
"*V "*V"
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 22 bytes
```
ToExpression@#/.x->#2&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@z8k37WioCi1uDgzP89BWV@vQtdO2Ujtf0BRZl5JdFq0knFFnLGuaUWckbZRha6hgZKOgmls7H8A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~113~~ 108 bytes
```
_=>x=>_.match(/-?(?:[x\d]+|\^?)+/g).reduce((a,b)=>b.split`x`[0]*(~b.indexOf`x`?x**(b.split`^`[1]||1):1)+a,0)
```
[Try it online!](https://tio.run/##bcxNboMwEAXgfY@R1QyOHf8UqYoEHKEHIDgYMCkVhSjQahaoV6c4UjdtNqPRvG/eu/tyU33rrjMfxsavbbKek5SS9Cw@3Fy/wYFnkB1zOjUFW042Q3a4oLj55rP2AG5fYZJWYrr23VxSmcsigu9KdEPj6bXdLhlFEfwCW@aqWBaFR4XM7SWu9ThMY@9FP16ghZ0ha3hMVjNNXMkdQoz49AcpSfY5KMPDqpkhFgdrHlqmQ6bk/5Dr@/s2@f2fvzwoIMs121oC0IjrDw "JavaScript (Node.js) – Try It Online")
Thanks to @Arnauld
---
Since the best JS solution so far by @Arnauld (49 bytes) has already been posted and it uses `eval`, I decided to use Regex and reduce instead of that.
Pretty lengthy compared to his though.
# Explanation :
```
A => // lambda function accepting argument 1
x => // argument number 2 (currying syntax used)
A.match( // this matches all instance of what comes next
// and converts to array
/[-]?(?:[x\d]+|\^?)+/g) // regexp for -ve sign , variable number and ^ sign
.reduce((a, b) => // reduce the array to single (take 2 params a,b)
b.split `x` // split b at instances of `x`
[0] // and select the first instance
* (b.indexOf`x` // multiply that by value of index of x in b
> 0 ? // if it is greater than 0 then
x ** // multiplication will be with x raised to power
(l = b.split `^` // set variable split b at every `x`
[1]||1 // choose first index otherwise set to one
) // this is what x is raised to the power
: 1) // in the case x is not present multiply by 1
+ a, // add value of `a` to that value
0) // in case no reduce is possible set value to 0
```
---
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~16~~ 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
„*(I')J'xs:'^„**:.E
```
+3 bytes as bug-fix for negative input `x`.
`.E` (*Run as Batch code*) has been replaced with *Run as Python `eval`* in this [latest commit of *@Adnan*](https://github.com/Adriandmen/05AB1E/commit/6851a84127450743174065d8d7b78229be40f154), but this version isn't on TIO yet. [*@Mr.Xcoder* tested it on his local (latest version) 05AB1E to verify it's working.](https://i.stack.imgur.com/S57up.jpg)
[See this version without `.E` to see how it converted the expression string.](https://tio.run/##MzBNTDJM/f//UcM8LQ1PdU0v9YpiK/U4EFfL6v9/Uy7jijhjXdOKOCNtowpdQwMA)
**Explanation:**
```
„*I')J'xs: # Replace all "x" with "*(n)" (where `n` is the input-integer)
# i.e. 5 and 3x^3-5x^2+2x-10 → 3*(5)^3-5*(5)^2-2*(5)-10
'^„**: # Replace all "^" with "**"
# i.e. 3*(5)^3-5*(5)^2-2*(5)-10 → 3*(5)**3-5*(5)**2-2*(5)-10
.E # Evaluate as Python-eval
# i.e. 3*(5)**3-5*(5)**2-2*(5)-10 → 250
```
---
Alternative **~~25~~ 28 bytes** program that works on the current version of TIO:
```
„*(I')J'xs:'^„**:“…¢(“s')J.e
```
[Try it online.](https://tio.run/##MzBNTDJM/f9fXcvTS72i2Eo97lHDPC0tq0cNcx41LDu0SAPIKFbX9NIDqjHlMq6IM9Y1rYgz0jaq0DU0AAA)
**Explanation:**
```
„*(I')J'xs:'^„**: # Same as explained above
“…¢(“ # Literal string "print("
s # Swap both
') # Literal character ")"
J # Join everything together
# i.e. 3*(5)**3-5*(5)**2-2*(5)-10 → print(3*(5)**3-5*(5)**2-2*(5)-10)
.e # Run as Python code
# i.e. print(3*(5)**3-5*(5)**2-2*(5)-10) → 250
```
`“…¢(“` is the string `print(`, because:
* `“` and `“` starts and ends the compressed string
* `…¢` is equal to `0426` because it looks at the indices in the [info.txt file](https://github.com/Adriandmen/05AB1E/blob/master/docs/info.txt), where `…` has index 4, and `¢` has index 26.
* This index `0426` is then used in the [dictionary-file](https://github.com/Adriandmen/05AB1E/blob/master/lib/dictionary.py), where line 427 (index 426) is the word it fetches, which is `print` in this case.
* The `(` doesn't have an index in the info.txt file, so it is interpret as is.
[Answer]
# TI-Basic, 6 bytes
```
Prompt X:expr(Ans
```
Expression is taken as argument and X is entered during runtime. Alternatively 8 bytes without `expr`:
```
Prompt X,u:u
```
Here both arguments are entered at runtime.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 143 bytes
I know there are better answers but I wanted to do it without using eval
```
(_,x)=>_.match(/[+-]?(?:[a-z0-9.]+|\^-?)+/gi).reduce((a,b)=>~~(b.split('x')[0])*(b.indexOf('x')>0?Math.pow(x,(l=(b.split('^')[1]))?l:1):1)+a,0)
```
[Try it online!](https://tio.run/##fY3tToMwFIb/exVkf@ixPV0pkugS4AqMF4B06fjYMAhkoDbG7Nax7IcyR0yak@b9eN4X/a777Fh1AzZtXoxlOJItMxBGW/6qh@xA1gnFNCbxJtH4KfCBp/TrWWEMdL2vgB@L/C0rCNFsZ0unE9nxvqurgbjGhUSkcGuVqskL81SetUjEj3o48K79IIaROvxtKNvwUoC43nhgH9VMwJi1Td/WBa/bPXHJyjfKx8AoSaVBT6yYE4ATRo7LnHLZhZs/CE8YdTelfJy@kvqGBlPWn5H@CS0BqZw8T1wSftSrCsoz1F48U/F@1lwwrzeNQkntxBSQ89lLA8Zv "JavaScript (Node.js) – Try It Online")
[Answer]
# [Physica](https://github.com/Mr-Xcoder/Physica), 35 bytes
```
->e;x:Eval@Replace[e;"x";f"*({x})"]
```
[Try it online!](https://tio.run/##K8ioLM5MTvyfVpqXXJKZn6dgqxDzX9cu1brCyrUsMcchKLUgJzE5NTrVWqlCyTpNSUujuqJWUyn2f0BRZl6JA0xbtJJxRZyxrmlFnJG2UYWuoYGStYJpLBe6IkODijgTkCpjXRDTSNu4QtsUpNYYq1ptI5CcoQGmpK4RWDuQ1AXr17XAYkBFnK6RNtAUkAKj2P8A "Physica – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes
```
ṣ”^j⁾**ṣ”xjØ(j”*;Ʋ}ŒV
```
[Try it online!](https://tio.run/##y0rNyan8///hzsWPGubGZT1q3KelBeFUZB2eoZEFZGhZH9tUe3RS2P///5V0jQwq4oy0gaSuqYHSf10LAA "Jelly – Try It Online")
[Answer]
# Java 8, ~~150~~ ~~149~~ 148 bytes
```
n->s->new javax.script.ScriptEngineManager().getEngineByName("JS").eval(s.replace("x","*"+n).replaceAll((s="(\\-?\\d+)")+"\\^"+s,"Math.pow($1,$2)"))
```
~~Not sure if it's possible to have a currying lambda function that throws an Exception. If it is, 1 byte can be saved changing `(s,n)->` to `n->s->`.~~ -1 byte thanks to *@OlivierGrégoire* for showing me how to do this.
[Try it online.](https://tio.run/##hZBfa8IwFMXf/RSX4EO6mKCpwkB0KPgycHvo47pCWrParqaliRoZfnYX2/ow2CaE/Lk5v3tOkouDoPnm85IUQmtYi0x99QAyZWT9IRIJC7ieAZYgsKuC8sBs6/KoYWUTWZmsVFMnOPd@UMuOeo1zmRiIcWDqTKWg/6IB3NBGmCxxlgJmcFF0rulcySPkLqRlOqmzyrCgWVYqzZRcCyVSWWOPpbIrLU8vYicxeg6Qx@RBFFizWlaFS4WRRQP0gIjybqVFUWCsZwiHIX0Kww3xkEdQGEaI6AFaC7NlVXnE/dGgz92Vd5m2Sat9XLikXeBDmW1g576ue@bbO4g6/eWt7acEJ23kjpV7wyonN4XCggnseyzGaGwjTrilE@c2/U8@aeS@jXw66ZjR8B7UeoyGNhpfKZ9et5z4lkzusqPhDSb8rpg@NmLKm/5upvcNeNvfRpQTZ3LTn3vnyzc)
**Explanation:**
```
n->s-> // Method with integer and String parameters and Object return-type
new javax.script.ScriptEngineManager().getEngineByName("JS")
// Use a JavaScript engine
.eval(s // And eval the input
.replace("x","*"+n)
// After all 'x' has been replaced with '*n'
// (where `n` is the input-integer)
.replaceAll((s="(\\-?\\d+)")+"\\^"+s,"Math.pow($1,$2)"))
// And all `A^B` have have been replaced with `Math.pow(A,B)`
// (where both `A` and `B` are integers)
```
Unfortunately the JavaScript eval doesn't support `**`, so I have to use a longer replace to convert it to `Math.pow` instead..
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~43~~ 41 bytes
```
->p,x{eval p.gsub('^','**').gsub'x','*x'}
```
[Try it online!](https://tio.run/##VYtBCgIxDEX3nqLMJjptpE0tuNGL6BQcEDddFMdKRDx7nRRE3YT8/96/lvFR0@5YcZ8NP8/3U1J5fZnKuIQIBvoeVi0CS2J41Vxuk0qHznP0GDiSJkZnO6PCsPhAZzluhHqUl7RnHcTxf44m6Zz9lkhNny82H7c/A45Iel4JoKG@AQ "Ruby – Try It Online")
Saved two bytes thanks to @Mr.Xcoder
---
~~Since there isn't a Ruby answer yet I added one.~~ Nvm there was one that used a different approach
# Explanation :
```
->p,x{ # lambda function that takes two arguments p and x
eval( # eval
p.gsub( # replace all instance of
'^' , '**' # `^` with `**` (use for raised to power of)
) # end gsub
.gsub( # start another replace all
'x' , '*x' # replace all instances of `x` with `*x`
) # end the replace function
) # end eval function
} # end lambda function
```
[Answer]
# Excel, 36+2 bytes, Non-competing
Evaluating a Text field as a formula is not straight forward in Excel. There is a hidden `=EVALUATE()` function, that can be called by defining a Name.
In Excel 2007, Formulas > Define Name. Define a Name called `E`, with Refers to:
```
=EVALUATE(SUBSTITUTE(A1,"x","*"&B1))
```
Then, with Formula input in `A1`, `x` value in `B1`, entering `=E` in `C1` returns expected result.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~47~~ ~~38~~ 37 bytes
Saved a lot of bytes by taking the second input as a string instead of a number.
```
@(x,c)eval(strrep(x,'x',['*(',c,41]))
```
[Try it online!](https://tio.run/##XY7dCsIwDEbvfYpSkHb2hzZtRS8mvodYGGNeCcocI29fu3aImouQkPMd8uinbh7SrdVapzNH2TfD3N35axrH4Zl3hkxe2I4z2Utvr02Tbpw6jE4FjCAAlTVUEhpoQ9baEtKeCASzyag1GP3COrWMIByKUBIuJyq6935FBZRTVn5sv1YLxaqguHJXVaYOX4mKKuuP9QWMCkSWFxL@1BU2GkJ6Aw "Octave – Try It Online")
### Explanation:
Fairly straight forward: Replace `x` by `(c)` , where `c` is the second input, and evaluate. The paretheses are necessary because in Octave `-8^2 == -64`.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 43 bytes
```
->s,x{eval s.gsub /[x^]/,?x=>"*x",?^=>"**"}
```
[Try it online!](https://tio.run/##VYvBCsIwEETvfkXIscnaZGPAS9sPKVmwYL14EGNkRfz22C2IehmGeW@uZXrUuavQZ8vP4/1wVnl7ymVS7ciUWjtw1@uGtR1ISqNf9VJuWc2jDkwBIhMaZPBOWxXT5gO9Y9oJDSAVTWATxQl/jkHZvPuOgKu@JKw@7H8OTIBmeQnAVN8 "Ruby – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-pl`, 35 bytes
```
s/\^/**/g;$q=<>;s/x/*($q)/g;$_=eval
```
[Try it online!](https://tio.run/##K0gtyjH9/79YPyZOX0tLP91apdDWxs66WL9CX0tDpVATJBJvm1qWmPP/v2FFnK6RtkGFtgGX0b/8gpLM/Lzi/7oFOQA "Perl 5 – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 19 bytes
```
(x=#;ToExpression)&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@1@jwlbZOiTftaKgKLW4ODM/T1Ptf0BRZl5JtIJCWrRpbLSScUWcsa5pRZyRtlGFrqGBUqyCQux/AA "Wolfram Language (Mathematica) – Try It Online")
Take input by currying: `f[x][expr]`.
]
|
[Question]
[
So, you were sitting at your desk, golfing a program to calculate the first 20 digits of pi, and along comes your boss and throws your apple IIe out the window. You are now working on a new project and this computer does not yet have any text capability. None. No fonts. Nothing.
Now let's finish that program. **Calculate** and **Display** the first 20 characters of pi without using any fonts that are not part of your program. Your output can be displayed or written to standard out as an image file (jpeg, png, gif, svg(as long as you don't use any characters), bmp, xpm). You can use any language, but you can not use your language's font functions, text display or similar.
small bonus (10 characters) If it will work on a Lisa.
Edit: for those who didn't figure it out my inspiration was the first mac, and the title is a pun. A big kudos to @Sukminder whose animated gif is just cool. The contest is not over if a better answer comes along.
[Answer]
## Python, 217 bytes
*Requires the [Python Imaging Library](http://www.pythonware.com/products/pil/)*
```
import Image
x=p=141
i=Image.new('1',(x,11))
while~-p:x=p/2*x/p+2*10**19;p-=2
for c in str(x):[i.putpixel((j%7/5*4-~j%7/4*~j/7+p,j%7*3%14%8+j%14/10+2),1&ord('}`7gjO_a\177o'[int(c)])>>j%7)for j in range(17)];p+=7
i.show()
```
The byte count assumes that the escaped character `\177` is replaced with its literal equivalent (char *127*).
Output will appear as the following (it will open in your default \*.bmp viewer):

Note that this could easily be parameterized to print any number of digits you like. The following will accept an integer input from stdin, and display that many digits:
```
import Image
n=input()
x=p=n*7|1
i=Image.new('1',(x,11))
while~-p:x=p/2*x/p+2*10**(n-1);p-=2
for c in str(x):[i.putpixel((j%7/5*4-~j%7/4*~j/7+p,j%7*3%14%8+j%14/10+2),1&ord('}`7gjO_a\177o'[int(c)])>>j%7)for j in range(17)];p+=7
i.show()
```
Output for *n=80*:

---
### Pi Calculation
```
while~-p:x=p/2*x/p+2*10**19;p-=2
```
Yup, that's it. The formula used is the result of applying [Euler's Transform](http://mathworld.wolfram.com/EulerTransform.html) to the [Leibniz Series](http://mathworld.wolfram.com/LeibnizSeries.html), and then factoring out each term from the remainder of the sum. The formula converges linearly; each digit requires *log2(10) ≈ 3.32* iterations. For those interested in the derivation, see Appendix A.
### Display
[PIL](http://www.pythonware.com/products/pil/) is used for image generation, because it's the most convenient library that I know of. A blank *141×11* black and white bitmap is created, and then white lines are drawn on it in a seven-segment fashion, one pixel at a time. The positions required to draw each segment are stored in a bitmask string, with bits corresponding to the following positions:
```
000
3 5
3 5
111
4 6
4 6
222
```
The bit of magic `(j%7/5*4-~j%7/4*~j/7+p,j%7*3%14%8+j%14/10+2)` produces the each pixel in the following order (base-18):
```
(2, 2), (2, 5), (2, 8), (1, 3), (1, 6), (5, 3), (5, 6),
(3, 2), (3, 5), (3, 8), (1, 4), (1, 7), (5, 4), (5, 7),
(4, 2), (4, 5), (4, 8)
07e
3 5
a c
18f
4 6
b d
29g
```
---
### Appendix A
Euler's Transform is a convergence acceleration technique that works for any series which displays absolute monotonic convergence. The resulting series will converge linearly, typically at the rate of one bit per term (note that if the original series was already super-linear, the resulting series will actually converge slower). The [purely mathematical description](http://mathworld.wolfram.com/EulerTransform.html) is a bit hard to follow, so I'll be taking a procedural approach.
We'll start with the Leibniz Series:

Then split each term in half, combining neighboring terms:

Simplified:

Generalized:

Notice that the leading ½ didn't have a partner term, and thus was excluded from the rest of the sum. This is the first term of the transformed series. To find the next term, we repeat the process again:


And again:


And again:


And once more for good measure:


At this point we have the first five terms, and the sixth term is evident. This should be enough to generalize, so
we'll stop here. We'll start by factoring the numerators and denominators:

The denominators evidently contain a [Double Factorial](http://mathworld.wolfram.com/DoubleFactorial.html) of *2n+1*, so we'll patch that in:

Everything fits, except for the first two terms which have an unaccounted for *2* in the denominator. We can fix that by multiplying the entire expression by *2*:

*23 = 2·4*, so:

The numerator can now be easily identified as *n!*.
Notice that the factor added to each successive term, *n/(2n+1)*, approaches ½ as *n* becomes large, implying a linear convergence at the rate of one bit per term - this is in fact by design. A nice result, but it'd be even nicer without the factorials in there. What we can do here is to factor out each successive term from the rest of the sum, which will generate a nested expression:




This can be rewritten as a recurrence relation:

Where *n* counts backwards from ⌈*log2(10)·d*⌉ .. *0*, where *d* is the number of digits required.
It might be interesting to note that the stable point of this recurrence is exactly *2* (or *4* if you've doubled it, as I have in the implmentation above), so you can save a number of iterations by initializing properly. Though, initializing to a random value you need elsewhere, and throwing a few extra iterations on the top is generally cheaper byte-wise.
[Answer]
#C – 777 Characters
# C – 731 Characters
Prints GIF to `stdout`.
* Quirk: No comma after first `3`.
Stitching together GIF from pre-configured header + each digit represented by home brewed (embedded) font of 5x5 pixels.
>
> Result
>
>
>

>
> It is there ---^
>
>
>
*Note that GIF vanishes, sometimes, in Chrome after one run.*
```
#include <stdio.h>
#define G 68,30
#define F(e,i)for(i=0;i<e;++i)
#define B w[++k]
unsigned char r[][10]={{4,18,150,199,188,159,10,0},{4,18,102,169,188,122,64,1},{G,160,166,104,217,80,1},{G,160,166,184,140,66,1},{68,96,153,193,135,138,66,1},{G,6,107,199,155,80,40},{68,128,150,22,173,218,90,1},{G,160,182,169,254,84,1},{G,6,138,153,140,10,0},{G,6,138,185,250,66,1},{0,0,0,5,0,5,0,0,2,8}},w[440]={71,73,70,56,57,97,100,0,5,0,144,0,0,255,255,255,0,0,0};int main(){int a=10000,b=0,c=70,d,e=0,f[71],g;int i,j,k=18,s=0;char m[5];for(;b<c;)f[b++]=a/5;for(;d=0,g=c*2;c-=14,e=d%a){for(b=c;d+=f[b]*a,f[b]=d%--g,d/=g--,--b;d*=b);sprintf(m,"%d",e+d/a);F(4,i){B=44;B=s++*5;F(10,j)B=r[10][j];F(8,j)B=r[m[i]-'0'][j];B=0;}}B=59;fwrite(w,1,k,stdout);}
```
---
# Short introduction:
## Calculation of PI
Pi is calculated using a slightly modified version of Dik Winter and Achim Flammenkamp's implementation of Rabinowitz and Wagon's algorithm for computing digits of π.
```
int a=10000,b,c=2800,d,e,f[2801],g;main(){for(;b-c;)f[b++]=a/5;for(;d=0,g=c*2;c
-=14,printf("%.4d",e+d/a),e=d%a)for(b=c;d+=f[b]*a,f[b]=d%--g,d/=g--,--b;d*=b);}
```
## GIF generation
GIF images has a `canvas` property in header. We can use this in combination with displaying multiple images by setting `left` property for each digit accordingly – where each digit is a (embedded) image in itself.
[Documentation.](http://www.w3.org/Graphics/GIF/spec-gif89a.txt)
## Example:
```
Header: Canvas Width 100 pixels
Canvas Height 5 pixels
3 : left 0 pixels
1 : left 5 pixels
4 : left 10 pixels
… and so on.
```
## Expanded code (with loads of comments)
*Messy, but that is part of the minimization*:
```
#include <stdio.h>
#define G 68,30
#define F(e,i)for(i=0;i<e;++i)
#define B w[++k]
/* Font + Image Descriptor + Start of Image Data.
*
* Font glyphs are black and white pixels making a 5x5 picture.
* Each glyph has its own entry in array.
* Pixels (White,White,Black,Black ...) are further compressed using LZW
* compression.
*
* Next entry in array is Image Descriptor which is added before each glyph.
* Last entry is start of Image Data.
*
* - "0" and comma are 7 and 5 bytes, but hacked to fill 8 bytes to make it
* easier to handle in minified code.
* */
unsigned char r[][10]={
/* Images representing glyphs. */
{ 4, 18, 150, 199, 188, 159, 10, 0}, /* 0 */
{ 4, 18, 102, 169, 188, 122, 64, 1}, /* 1 */
{ 68, 30, 160, 166, 104, 217, 80, 1}, /* 2 */
{ 68, 30, 160, 166, 184, 140, 66, 1}, /* 3 */
{ 68, 96, 153, 193, 135, 138, 66, 1}, /* 4 */
{ 68, 30, 6, 107, 199, 155, 80, 40}, /* 5 */
{ 68, 128, 150, 22, 173, 218, 90, 1}, /* 6 */
{ 68, 30, 160, 182, 169, 254, 84, 1}, /* 7 */
{ 68, 30, 6, 138, 153, 140, 10, 0}, /* 8 */
{ 68, 30, 6, 138, 185, 250, 66, 1}, /* 9 */
{132, 143, 121, 177, 92, 0, 0, 0}, /* , (removed as not used) */
{
/* Image Descriptor */
/* 0x2C Image separator (Embedded in code) */
0, /* Image Left (LSB embedded in code. */
0, 0, /* Image top (16-bit Little endian) */
5, 0, /* Image Width (16-bit Little endian) */
5, 0, /* Image Height (16-bit Little endian) */
0, /* Packed byte (Local color table (not used, etc.)) */
/* Start of Image Data */
2, /* Starting size of LZW 2 + 1 = 3 */
8 /* Number of bytes in data */
}
};
/* GIF Header + Global Color table.
*
* GIF's has a standard header.
* Canvas size is the are on which to paint.
* Usually this is size of whole image, but in this code I've spanned it out
* and paint glyphs by rendering pictures on a canvas of size:
* 20 * width_of_1_image (5 * 20 = 100)
*
* Each image can have an optional color table, but if not present the global
* color table is used. In this code only global color table is used. It
* consist of only black and white. (Though very easy to change if wanted.)
* */
unsigned char buf[440] = {
71, 73, 70, /* Signature "GIF" */
56, 57, 97, /* Version "89a" */
100, 0, /* Canvas width (16-bit Little endian) 5 * 20 = 100*/
5, 0, /* Canvas height (16-bit Little endian) 5 pixels. */
144, /* Packed byte: 1 001 0 000
1 : Has global color table.
001 : Color resolution.
0 : Sorted Color Table (No)
000 : Size of Global Color table (2^(value+1))
or 2 << value ...
*/
0, /* Background Color index. */
0, /* Pixel aspect ratio. */
/* Global color table. */
255, 255, 255, /* Index 0: White */
0, 0, 0 /* Index 1: Black */
};
int main(void){
/* PI generation variables. */
int a = 10000,
b = 0,
c = 70,
d,
e = 0,
f[71],
g;
/* General purpose variables */
int i,
j,
k = 18, /* Current Index in out buffer. */
s = 0; /* Image counter:
(Tells us what "left/x" value should be). */
char m[5]; /* Print next 4 digits of PI to this buffer. */
/* Prepare / pre-fill for PI math. */
for(;b < c;)
f[b++] = a/5;
/* Calculate 4 and 4 digits of PI and push onto out buffer. */
for(; d = 0, g = c * 2; c -= 14 , e = d % a) {
for (b = c; d += f[b] * a, f[b] = d % --g, d /= g--, --b; d *= b);
/* sprintf next 4 digits to temprary buffer. */
sprintf(m, "%d", e + d/a);
/* We are served 4 and 4 digits.
* Here we transalte them to glyphs and push onto out buffer*/
for (i = 0; i < 4; ++i) {
buf[++k] = 0x2C; /* 0x2C : Image separator. */
buf[++k] = s++ * 5; /* xx : Image left (x) on canvas.*/
for (j = 0; j < 10; ++j) {
/* Push "Start of Image Data" onto buffer */
buf[++k] = r[11][j];
}
for (j = 0; j < 8; ++j) {
/* Push data of glyph (LZW-compressed) onto buffer. */
buf[++k] = r[m[i]-'0'][j];
}
/* Start of image data informs how big the image data
* is. End with zero to mark that this is EOI. */
buf[++k] = 0;
}
}
/* 0x3b is Trailer, marking end of file. */
buf[k] = 0x3b;
/* Write buffer to standard output.
* 'k' holds length of data, though as we know this image is
* 100x5 etc. we can pre-define it as well.
* */
fwrite(buf, 1, k, stdout);
}
```
---
Looking to use a shorter / other algorithm for calculating π.
[Answer]
# JavaScript, 680 chars
```
<html><body></body><script>v=["","41L70L7e","24C223060Ca0b587C592b2eLae","30L90L55L65C95a7a9Cac9e6eC5e3e2c","aaL2aL80L8e","90L40L36C455565C95a7a9Cac9e6eC5e3e2c","70C52272aC2c3e6eC9eacaaCa89666C36282a","20La0C745a5e","60C202435C465666C96a8aaCac9e6eC3e2c2aC283666C768695Ca4a060","a4Ca69868C382624C223060C90a2a4Ca77c5e","6dC7d7e6eC5e5d6d"];v["."]=v[10];a=(""+(4*Math.atan(1))).split("");s="";for(i in a)s+="<path d='M "+v[a[i]].split("").map(function(c){return+-c||c>"Z"?parseInt(c,16):c;}).join(" ")+"'transform='translate("+i*33+".5,10.5)scale(3,3)'fill='none'stroke='#333'stroke-linecap='round'stroke-linejoin='round'/>";document.body.innerHTML="<svg>"+s+"</svg>";</script></html>
```
This can be viewed in a web browser; the numbers are output as SVG paths.

* It doesn't compute pi in an interesting way, and JS lacks a number type with precision to display 20 digits.
* To save characters, I omitted the path data for "0", since it doesn't show up in the sequence.
[Answer]
## Python, 222 chars
```
n=[10**20*277991633/1963319607/10**i%10 for i in range(19,1,-1)]
print' * *'
print' * ** '+' '.join(' ** * ***** ***** *'[2*d:2*d+2]for d in n)
print'** * '+' '.join('** * * ** ***** '[2*d:2*d+2]for d in n)
```
The first line calculates the digits of pi using the approximation `pi-3 ~= 277991633/1963319607`. The next three lines output 20 characters of pi using ASCII art [Nemeth Braille.](http://en.wikipedia.org/wiki/Nemeth_Braille#Number_Signs)
```
* *
* ** * ** * * * * ** * ** * * * ** * ** * ** *
** * * * * * * * * ** * ** * * **
```
I'm pushing the boundaries in two directions here, both in the "calculating Pi" and "human readable" senses.
[Answer]
# Java - ~~866~~ ~~860~~ ~~857~~ 853 chars, plus a cheating version with 574 chars
Using the Simon Plouffe formula from 1996, outputs a `x.png` file with white digital-clock-like numbers in a black background:

This is the compressed code:
```
import java.math.BigDecimal;class E{static java.awt.Graphics g;public static void main(String[]h)throws Exception{java.awt.image.BufferedImage i=new java.awt.image.BufferedImage(213,17,1);g=i.getGraphics();BigDecimal y=v(-3);for(int n=1;n<99;n++)y=y.add(v(n).multiply(v(2).pow(n)).multiply(f(n).pow(2)).divide(f(2*n),42,0));int j=2;for(char c:y.toPlainString().substring(0,21).toCharArray()){if(j!=12){c-=48;boolean b=c!=1&c!=4;t(b,j,2,8,3);t(c<1|c>3&c!=7,j,2,3,8);t(c<5|c>6,j+5,2,3,8);t(c>1&c!=7,j,7,8,3);t(c%2==0&b,j,7,3,8);t(c!=2,j+5,7,3,8);t(b&c!=7,j,12,8,3);}j+=10;}t(true,17,12,3,3);javax.imageio.ImageIO.write(i,"png",new java.io.File("x.png"));}static BigDecimal v(int k){return BigDecimal.valueOf(k);}static BigDecimal f(int k){return k<2?v(1):f(k-1).multiply(v(k));}static void t(boolean x,int a,int b,int c,int d){if(x)g.fillRect(a,b,c,d);}}
```
That, with identing and some whitespaces would be this:
```
import java.math.BigDecimal;
class E {
static java.awt.Graphics g;
public static void main(String[] h) throws Exception {
java.awt.image.BufferedImage i = new java.awt.image.BufferedImage(213, 17, 1);
g = i.getGraphics();
BigDecimal y = v(-3);
// Calculate PI using the Simon Plouffe formula, 1996.
for (int n = 1; n < 99; n++)
y = y.add(v(n).multiply(v(2).pow(n)).multiply(f(n).pow(2)).divide(f(2 * n), 42, 0));
int j = 2;
for (char c : y.toPlainString().substring(0, 21).toCharArray()) {
if (j != 12) {
c -= 48;
boolean b = c != 1 & c != 4;
t(b, j, 2, 8, 3);
t(c < 1 | c > 3 & c != 7, j, 2, 3, 8);
t(c < 5 | c > 6, j + 5, 2, 3, 8);
t(c > 1 & c != 7, j, 7, 8, 3);
t(c % 2 == 0 & b, j, 7, 3, 8);
t(c != 2, j + 5, 7, 3, 8);
t(b & c != 7, j, 12, 8, 3);
}
j += 10;
}
t(true, 17, 12, 3, 3);
javax.imageio.ImageIO.write(i, "png", new java.io.File("x.png"));
}
static BigDecimal v(int k) {
return BigDecimal.valueOf(k);
}
static BigDecimal f(int k) {
return k < 2 ? v(1) : f(k - 1).multiply(v(k));
}
static void t(boolean x, int a, int b, int c, int d) {
if (x) g.fillRect(a, b, c, d);
}
}
```
Cheating the rules and considering that the calculation of PI can be done as "the numeric representation of the String 3.1415926535897934384", this can be reduced to 574 chars:
```
class F{static java.awt.Graphics g;public static void main(String[]h)throws Exception{java.awt.image.BufferedImage i=new java.awt.image.BufferedImage(213,17,1);g=i.getGraphics();int j=2;for(char c:"3.1415926535897932384".toCharArray()){if(j!=12){c-=48;boolean b=c!=1&c!=4;t(b,j,2,8,3);t(c<1|c>3&c!=7,j,2,3,8);t(c<5|c>6,j+5,2,3,8);t(c>1&c!=7,j,7,8,3);t(c%2==0&b,j,7,3,8);t(c!=2,j+5,7,3,8);t(b&c!=7,j,12,8,3);}j+=10;}t(true,17,12,3,3);javax.imageio.ImageIO.write(i,"png",new java.io.File("x.png"));}static void t(boolean x,int a,int b,int c,int d){if(x)g.fillRect(a,b,c,d);}}
```
[Answer]
# Java - ~~642~~ 622 characters
Copying from my previous answer, using the Simon Plouffe formula from 1996. But outputs ASCII-art instead:
```
import java.math.BigDecimal;class H{public static void main(String[]h)throws Exception{int[]t={31599,4681,31183,29647,5101,29671,31719,4687,31727,29679,8192};BigDecimal y=v(-3);for(int n=1;n<99;n++)y=y.add(v(n).multiply(v(2).pow(n)).multiply(f(n).pow(2)).divide(f(2*n),42,0));for(int z=0;z<5;z++){for(char c:y.toPlainString().substring(0,21).toCharArray()){if(c<48)c=58;int a=(t[c-48]>>>z*3)&7;e(a/4);e(a/2&1);e(a&1);e(0);e(0);}e(10);}}static void e(int c){System.out.print((char)(c<2?c*3+32:c));}static BigDecimal v(int k){return BigDecimal.valueOf(k);}static BigDecimal f(int k){return k<2?v(1):f(k-1).multiply(v(k));}}
```
All of that, with some identing and spaces, and a bit of help to the reader understand the meaning of the magic numbers:
```
import java.math.BigDecimal;
class H {
public static void main(String[] h) throws Exception {
// Each block corresponds to a line. Each char has 5 lines with a 3-char width.
int[] t = {
0b111_101_101_101_111,
0b001_001_001_001_001,
0b111_100_111_001_111,
0b111_001_111_001_111,
0b001_001_111_101_101,
0b111_001_111_100_111,
0b111_101_111_100_111,
0b001_001_001_001_111,
0b111_101_111_101_111,
0b111_001_111_101_111,
0b010_000_000_000_000
};
// Calculate PI using the Simon Plouffe formula, 1996.
BigDecimal y = v(-3);
for (int n = 1; n < 99; n++)
y = y.add(v(n).multiply(v(2).pow(n)).multiply(f(n).pow(2)).divide(f(2 * n), 42, 0));
for (int z = 0; z < 5; z++) {
for (char c : y.toPlainString().substring(0, 21).toCharArray()) {
if (c < 48) c = 58;
int a = (t[c - 48] >>> z * 3) & 7;
e(a / 4);
e(a / 2 & 2);
e(a & 1);
e(0);
e(0); // Not needed, but makes a better art with the cost of 5 chars.
}
e(10);
}
}
static void e(int c) {
System.out.print((char) (c < 2 ? c * 3 + 32 : c));
}
static BigDecimal v(int k) {
return BigDecimal.valueOf(k);
}
static BigDecimal f(int k) {
return k < 2 ? v(1) : f(k - 1).multiply(v(k));
}
}
```
Output:
```
### # # # # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### # #
# # # # # # # # # # # # # # # # # # # # # # # # # # #
### # ### # ### ### ### ### ### ### ### ### ### # ### ### ### ### ### ###
# # # # # # # # # # # # # # # # # # # # # # #
### # # # # ### ### ### ### ### ### ### ### ### # ### ### ### ### ### #
```
[Answer]
## C, ~~253~~ 250 chars
Approximates pi using the algorithm in @Sukminder's code (shamelessly borrowing and refactoring their code a bit). Outputs a [binary PBM image](http://en.wikipedia.org/wiki/Netpbm_format), which could then e.g. be converted with ImageMagick.
```
b,c=70,e,f[71],g;v[71],j,k;L[5]={1072684944,792425072,492082832,256581624};
main(d){for(puts("P4\n8 100");b<c;)f[b++]=2;for(;d=0,g=--c*2;e=d%10){
for(b=c;d+=f[b]*10,f[b]=d%--g,d/=g--,--b;d*=b);v[j++]=e+d/10;}
for(;k<100;k++)putchar(L[k%5]>>3*v[k/5]&7);}
```
Here's what the output looks like with my Braille-based PPM renderer:

Has the same quirk as @Sukminder's answer in that it lacks a decimal separator. In addition, the output of mine is vertical, and whether it's human-readable is arguable...
Edit: applied @ugoren's suggestions.
[Answer]
**PHP 380**
requires gd enabled for image output
```
<? header('Content-Type: image/png');$i=imagecreatetruecolor(84,5);$n=['71775777770','51115441550','51777771770','51411151510','71771771712'];$c=imagecolorallocate($i,255,255,255);$m=(6.28318/2).(5307*5).(28060387*32);$k=5;while($k--)for($j=0;$j<21;$j++){$p=str_pad(decbin($n[$k][($m[$j]!='.')?$m[$j]:10]),3,'0',0);$l=3;while($l--)$p[$l]&&imagesetpixel($i,$l+$j*4,$k,$c);}imagepng($i);
```

pi calculation: since base php has a default precision of 14 and i didn't want to recompile the server with the arbitrary precision extensions enabled, i couldn't even aproximate PI with the required decimals, so instead it calculates tau/2 and then the rest of the decimals
since the graphic is made of 0's and 1's, i may try using WBMP as the format later to see if i can remove gd
[Answer]
# C+LaserWriter printer 599 - 10 = 589
Pipe the output to your LaserWriter! :) This should work on a Lisa (with a C compiler).
It calculates `pi` in the printer by calculating the sum of the lengths of the line-segments which approximate a Bezier curve sequence which approximates a half-circle, divided by diameter, times 2.
```
main(){
printf("/dist{dtransform dup mul exch dup mul add sqrt}def");
printf("/len{3 2 roll sub 3 1 roll exch sub dist}def");
printf("/pi{0 0 2 index 0 180 arc closepath flattenpath");
printf("[{2 copy}{2 copy 6 2 roll len 3 1 roll}{}{counttomark -2 roll len\n");
printf("counttomark 2 add 1 roll counttomark 1 sub{add}repeat\n");
printf("exch pop exch pop exch div 2 mul}pathforall}def\n");
printf("matrix setmatrix 100 dup scale 10 setflat 100 pi 10 string cvs\n");
printf("matrix defaultmatrix setmatrix/Palatino-Roman findfont 10 scalefont setfont\n");
printf("100 700 moveto show showpage");
}
```
Ungolfed Level-1 (1985-compatible) PostScript:
```
%!
/dist { % dx dy . dz
dtransform
dup mul exch dup mul add sqrt
} def
/len { % x1 y1 x2 y2 . dist(y2-y1,x2-x1)
3 2 roll % x1 x2 y2 y1
sub 3 1 roll exch sub % y2-y1 x2-x1
dist
} def
/pi { % rad
0 0 2 index 0 180 arc closepath % rad
flattenpath
[
{ % rad [ x(0) y(0) (m)print
2 copy
} %moveto proc
{ % rad [ ... x(n-1) y(n-1) x(n) y(n) (l)print
2 copy 6 2 roll len % rad [ ... x(n) y(n) dist
3 1 roll % rad [ ... dist x(n) y(n)
} %lineto proc
{} %curveto proc % n.b. flattenpath leaves no curve segments
{ % rad [ x(0) y(0) dist(1) dist(2) ... dist(n-1) x(n) y(n) (c)print
counttomark -2 roll len % rad [ dist(1) dist(2) ... dist(n)
counttomark 2 add 1 roll % dist(n) rad [ dist...
counttomark 1 sub { add } repeat % dist(n) rad [ sum_dist
exch pop % dist(n) rad sum_dist
exch pop % dist(n) sum_dist
exch % sum_dist dist(n)
div % length_of_half_circle/diameter
2 mul % C/d
} %closepath proc
pathforall
} def
matrix setmatrix
100 dup scale
10 setflat
100 pi 10 string cvs
matrix defaultmatrix setmatrix
/Palatino-Roman findfont 10 scalefont setfont
100 700 moveto show
```
Output:

[Answer]
## Java, 1574 2643 1934 characters
Compressed **1934** characters:
```
public static void main(String[] args){int[][][]num={{{1,1,1},{1,0,1},{1,0,1},{1,0,1},{1,1,1}},{{0,0,1},{0,0,1},{0,0,1},{0,0,1},{0,0,1}},{{1,1,1},{0,0,1},{1,1,1},{1,0,0},{1,1,1}},{{1,1,1},{0,0,1},{1,1,1},{0,0,1},{1,1,1}},{{1,0,1},{1,0,1},{1,1,1},{0,0,1},{0,0,1}},{{1,1,1},{1,0,0},{1,1,1},{0,0,1},{1,1,1}},{{1,1,1},{1,0,0},{1,1,1},{1,0,1},{1,1,1}},{{1,1,1},{0,0,1},{0,0,1},{0,0,1},{0,0,1}},{{1,1,1},{1,0,1},{1,1,1},{1,0,1},{1,1,1}},{{1,1,1},{1,0,1},{1,1,1},{0,0,1},{0,0,1}},{{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,1}}};BufferedImage image=new BufferedImage(103,5,BufferedImage.TYPE_3BYTE_BGR);for(int q=0;q<103;q++){for(int w=0;w<5;w++){image.setRGB(q,w,0xFFFFFF);}}int loc = 0;String g=String.valueOf(pi(20));for(int w=0;w<g.length()-1;w++){Integer n=0;if(g.charAt(w)=='.'){n=10;}else{n=Integer.parseInt(String.valueOf(g.charAt(w)));}for(int t=0;t<5;t++){for(int q=0;q<3;q++){int c=num[n][t][q]==1?0x000000:0xFFFFFF;image.setRGB(loc+q,t,c);}}loc+=5;}try{BufferedImage bi=image;File f=new File("o.png");ImageIO.write(bi,"png",f);}catch(IOException e){}}public static BigDecimal pi(final int SCALE){BigDecimal a=BigDecimal.ONE;BigDecimal b=BigDecimal.ONE.divide(sqrt(new BigDecimal(2),SCALE),SCALE,BigDecimal.ROUND_HALF_UP);BigDecimal t=new BigDecimal(0.25);BigDecimal x=BigDecimal.ONE;BigDecimal y;while(!a.equals(b)){y=a;a=a.add(b).divide(new BigDecimal(2),SCALE,BigDecimal.ROUND_HALF_UP);b=sqrt(b.multiply(y),SCALE);t=t.subtract(x.multiply(y.subtract(a).multiply(y.subtract(a))));x=x.multiply(new BigDecimal(2));}return a.add(b).multiply(a.add(b)).divide(t.multiply(new BigDecimal(4)),SCALE,BigDecimal.ROUND_HALF_UP);}public static BigDecimal sqrt(BigDecimal A,final int SCALE){BigDecimal x0=new BigDecimal("0");BigDecimal x1=new BigDecimal(Math.sqrt(A.doubleValue()));while(!x0.equals(x1)){x0=x1;x1=A.divide(x0,SCALE,BigDecimal.ROUND_HALF_UP);x1=x1.add(x0);x1=x1.divide(new BigDecimal(2),SCALE,BigDecimal.ROUND_HALF_UP);}return x1;}}
```
Expanded **2643** characters:
```
public static void main(String[] args) {
int[][][] num = { { { 1, 1, 1 }, { 1, 0, 1 }, { 1, 0, 1 }, { 1, 0, 1 }, { 1, 1, 1 } },
{ { 0, 0, 1 }, { 0, 0, 1 }, { 0, 0, 1 }, { 0, 0, 1 }, { 0, 0, 1 } },
{ { 1, 1, 1 }, { 0, 0, 1 }, { 1, 1, 1 }, { 1, 0, 0 }, { 1, 1, 1 } },
{ { 1, 1, 1 }, { 0, 0, 1 }, { 1, 1, 1 }, { 0, 0, 1 }, { 1, 1, 1 } },
{ { 1, 0, 1 }, { 1, 0, 1 }, { 1, 1, 1 }, { 0, 0, 1 }, { 0, 0, 1 } },
{ { 1, 1, 1 }, { 1, 0, 0 }, { 1, 1, 1 }, { 0, 0, 1 }, { 1, 1, 1 } },
{ { 1, 1, 1 }, { 1, 0, 0 }, { 1, 1, 1 }, { 1, 0, 1 }, { 1, 1, 1 } },
{ { 1, 1, 1 }, { 0, 0, 1 }, { 0, 0, 1 }, { 0, 0, 1 }, { 0, 0, 1 } },
{ { 1, 1, 1 }, { 1, 0, 1 }, { 1, 1, 1 }, { 1, 0, 1 }, { 1, 1, 1 } },
{ { 1, 1, 1 }, { 1, 0, 1 }, { 1, 1, 1 }, { 0, 0, 1 }, { 0, 0, 1 } },
{ { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 1 } } };
BufferedImage image = new BufferedImage(103, 5, BufferedImage.TYPE_3BYTE_BGR);
for (int q = 0; q < 103; q++) {
for (int w = 0; w < 5; w++) {
image.setRGB(q, w, 0xFFFFFF);
}
}
int loc = 0;
String g = String.valueOf(pi(20));
for (int w = 0; w < g.length()-1; w++) {
Integer n = 0;
if (g.charAt(w) == '.') {
n = 10;
} else {
n = Integer.parseInt(String.valueOf(g.charAt(w)));
}
for (int t = 0; t < 5; t++) {
for (int q = 0; q < 3; q++) {
int c = num[n][t][q] == 1 ? 0x000000 : 0xFFFFFF;
image.setRGB(loc + q, t, c);
}
}
loc += 5;
}
try {
BufferedImage bi = image;
File outputfile = new File("out2.png");
ImageIO.write(bi, "png", outputfile);
} catch (IOException e) {
}
}
public static BigDecimal pi(final int SCALE) {
BigDecimal a = BigDecimal.ONE;
BigDecimal b = BigDecimal.ONE.divide(sqrt(new BigDecimal(2), SCALE), SCALE, BigDecimal.ROUND_HALF_UP);
BigDecimal t = new BigDecimal(0.25);
BigDecimal x = BigDecimal.ONE;
BigDecimal y;
while (!a.equals(b)) {
y = a;
a = a.add(b).divide(new BigDecimal(2), SCALE, BigDecimal.ROUND_HALF_UP);
b = sqrt(b.multiply(y), SCALE);
t = t.subtract(x.multiply(y.subtract(a).multiply(y.subtract(a))));
x = x.multiply(new BigDecimal(2));
}
return a.add(b).multiply(a.add(b)).divide(t.multiply(new BigDecimal(4)), SCALE, BigDecimal.ROUND_HALF_UP);
}
public static BigDecimal sqrt(BigDecimal A, final int SCALE) {
BigDecimal x0 = new BigDecimal("0");
BigDecimal x1 = new BigDecimal(Math.sqrt(A.doubleValue()));
while (!x0.equals(x1)) {
x0 = x1;
x1 = A.divide(x0, SCALE, BigDecimal.ROUND_HALF_UP);
x1 = x1.add(x0);
x1 = x1.divide(new BigDecimal(2), SCALE, BigDecimal.ROUND_HALF_UP);
}
return x1;
}
```
Pi method gathered from: <https://stackoverflow.com/questions/8343977/calculate-pi-on-an-android-phone?rq=1>
]
|
[Question]
[
**This question already has answers here**:
[The rice and chess problem](/questions/79241/the-rice-and-chess-problem)
(40 answers)
Closed 5 years ago.
*Related: [Calculate Power Series Coefficients](https://codegolf.stackexchange.com/questions/105282/calculate-power-series-coefficients)*
Given a positive integer \$X\$ and a max exponent (Also a positive integer too) \$N\$ calculate the result of a power series. Example:
$$X^0+X^1+X^2+\cdots +X^N$$
* Assume \$(X + N) \le 100\$
---
**Test Cases**
```
1 2 => 3
2 3 => 15
3 4 => 121
2 19 => 1048575
```
---
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
[Answer]
# [R](https://www.r-project.org/), 25 bytes
```
function(x,n)sum(x^(0:n))
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T6NCJ0@zuDRXoyJOw8AqT1Pzf5qGoY6RJleahpGOMYgy1jGB8AwtNf8DAA "R – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes
```
ÝmO
```
[Try it online!](https://tio.run/##MzBNTDJM/f//8Nxc////TbiMAQ "05AB1E – Try It Online")
Explanation:
```
Input: 4, 3
Ý [0..input] - [0, 1, 2, 3, 4]
m Vectorized exponent - [1, 3, 9, 27, 81]
O Sum - 121
```
[Answer]
# [Haskell](https://www.haskell.org/), 21 bytes
The straightforward approach:
```
x#n=sum$map(x^)[0..n]
```
For the case \$ x \neq 1 \$ we alternatively could use following function with the same length:
```
x#n=div(x*x^n-1)$x-1
```
This uses the fact that
\$ 1 + x + x^2 + \ldots + x^n = \frac{x^{n+1} -1}{x-1} \forall x \neq 1.\$
[Try it online!](https://tio.run/##y0gszk7Nyfn/v0I5z7a4NFclN7FAoyJOM9pATy8v9n9uYmaegq1CQVFmXomCioKxsul/AA "Haskell – Try It Online")
[Answer]
# JavaScript (ES6), 22 bytes
*Saved 1 byte thanks to @tsh*
```
x=>g=n=>~n&&x*g(n-1)+1
```
[Try it online!](https://tio.run/##Zcu7DkAwFADQ3Vd0kpYUt9VgqH8Rj4bIrSBi8uslYcF8coZqq5Z67qeVo21a12m369Jo1OWBvr8HhiIHFoKrLS52bKPRGtpRYJQIxkgcE@m9SVwkbwL1MXlZ@piAf4TiwSTNVabcCQ "JavaScript (Node.js) – Try It Online")
---
# Non-recursive (ES7), 23 bytes
Using the direct formula mentioned by @flawr:
```
x=>n=>~-(x**++n)/~-x||n
```
[Try it online!](https://tio.run/##ZcvPDkAgHADgu6foWCypNBzqXcy/MftlmHUwrx4bF5y/fUO5lUs199NKwdaNb7V32oA2B8UuDKMICDuo23fwlYXFjk082g63mBOMBCGIMSSDN4mL5E1cfUxelj4m@D/y4sEkzVWm/Ak "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
*Ż}S
```
[Try it online!](https://tio.run/##y0rNyan8/1/r6O7a4P///xv9N7QEAA "Jelly – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 40 bytes
```
lambda x,n:sum(x**k for k in range(n+1))
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaFCJ8@quDRXo0JLK1shLb9IIVshM0@hKDEvPVUjT9tQU/N/QVFmXolGmoahjpGmJheMZ6RjjMQz1jFBkTO0BGoEAA "Python 3 – Try It Online")
`lambda x,n:sum(map(x.__pow__,range(n+1)))` is cool too but it's 1 byte longer lol.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 4 bytes
```
:^sQ
```
[Try it online!](https://tio.run/##y00syfn/3yquOPD/f0NLLiMA "MATL – Try It Online")
Takes input as `N` then `X`.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 11 bytes
```
t⟦R&h;Rz^ᵐ+
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v@TR/GVBahnWQVVxD7dO0P7/P9pIR8HQMvZ/FAA "Brachylog – Try It Online")
Nothing particularly interesting, construct the range 0 to n, raise x to the power of each number in it.
And since I wanted to learn how `ᵃ`ccumulate works, here's a slightly longer version that uses that:
### 15 bytes
```
,1↺⟨t×{bh}⟩ᵃ⁾k+
```
[Try it online!](https://tio.run/##ATEAzv9icmFjaHlsb2cy//8sMeKGuuKfqHTDl3tiaH3in6nhtYPigb5rK///WzE5LCAyXf9a "Brachylog – Try It Online")
Form array [1, x], and do this n times, accumulating the results into that array after each iteration: multiply the last element of the array, by the second element of the array (i.e. x). Since this calculates [1, x, x^2, ... x^n, x^(n+1)], knife off the last value and add the rest of them up as the output.
[Answer]
# [Noether](https://github.com/beta-decay/Noether), 17 bytes
```
I~xI(ax!i^+~ai)aP
```
[Try it online!](https://tio.run/##y8tPLclILfr/37OuwlMjsUIxM067LjFTMzHg/38jLkNLAA "Noether – Try It Online")
## Explanation
```
I~x - Store the input in the variable x
I( ) - Loop until the top of the stack equals the input n
a - Push a
x - Push x
!i - Increment i
^ - Calculate the value of x^i
+~a - Add x^i to a and store in a
i - Push i
aP - Print the value of a
```
[Answer]
# [Python](https://docs.python.org/), ~~35~~ 32 bytes
-1 Thanks to tsh (`f(x,n-1)+x**n` -> `f(x,n-1)*x+1`)
Port of [Arnauld's Javascript answer](https://codegolf.stackexchange.com/a/169566/53748) - not sure if it is the first, so do shout if you know who deserves the credit!
```
f=lambda x,n:~n and f(x,n-1)+x**n
```
A recursive function which sums the terms right-to-left, with a base case of zero when `n` reaches `-1` (since `~(-1)` is `-1 - (-1)` which is `0` which is falsey).
**[Try it online!](https://tio.run/##LY3BCsIwEETvfsXcuqurkNaLhXxMpAYL7bbUFCIl/npM0bkMw4M38zs8J21y9nZw471ziKLtR@G0gzl5KvNs@Bizn5bCoOgVREZQs4BqQbN3I7j@t7kxtweUzEuvgSpPW0yCTRPDYlser3UIqboU4@gCRbtrrQp@xO6nUGbOXw "Python 3 – Try It Online")**
---
My previous **35 byter**:
```
lambda x,n:x^1and~-x**-~n/~-x or-~n
```
[Try it online!](https://tio.run/##LUzdCoIwGL3vKc6d@@SzULtJ2JtEsLCRoJ@yFixEX31t1Lk5v5zl45@ztNHqaxzNdO8NAksXbrWRfq9CWVa7nJLA7JKKdnZpAMEgUKpmNMRQDaPN3DLOf19fiLoDEhY3iFeFVWvYGKtsBI3VPV7v0W/FMT1Oxqug860Wxq/RVuWAiOIX "Python 3 – Try It Online")
### How?
The `^` operator is bitwise-xor, so `x^1` is zero when `x` is one and non-zero otherwise.
In Python non-zeros are truthy, so the right of the logical `and` is executed when `x` is not one, but not executed when `x` is one, whereupon the right of the logical `or` is executed instead.
So, when `x` is one we execute
`-~n` which is equivalent to
`-1 * ~n` which is equivalent to
`-1 * (-1 - n)` which is equivalent to
`1 + n`...
...and when `x` is not one we execute
`~-x**-~n/~-x` which, adding parentheses to signify precedence, is
`(~-(x**(-~n)))/(~-x)` which is equivalent to
`(-1 - -1 * (x ** (-1 * (-1 - n))))/(-1 - -x)` which is equivalent to
`((x ** (n + 1)) - 1)/(x - 1)`
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~53~~ 46 bytes
```
param($x,$n)0..$n|%{$o+=[math]::pow($x,$_)};$o
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQ6VCRyVP00BPTyWvRrVaJV/bNjo3sSQj1sqqIL8cLBuvWWutkv///3@j/4aWAA "PowerShell – Try It Online")
Not bad for needing a .NET call for `pow`.
*-7 bytes thanks to mazzy.*
[Answer]
# [Ruby](https://www.ruby-lang.org/), 26 bytes
```
->x,n{(0..n).sum{|i|x**i}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf165CJ69aw0BPL09Tr7g0t7oms6ZCSyuztvZ/gUJatKGOUSwXiGGkYwxhGOuYwEQMLWP/AwA "Ruby – Try It Online")
[Answer]
# [cQuents](https://github.com/stestoltz/cQuents/tree/cquents-0), 6 bytes
```
$0;A^$
```
[Try it online!](https://tio.run/##Sy4sTc0rKf7/X8XA2jFO5f9/IwVDSwA "cQuents 0 – Try It Online")
# Explanation
```
Implicit inputs: A and n
$0 Zero indexing
; Output sum of first n terms in sequence
A^$ Each term is A to the power of the current index
```
[Answer]
# [Python](https://docs.python.org/2/), 31 bytes
```
f=lambda x,n:n<1or x*f(x,n-1)+1
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRoUInzyrPxjC/SKFCK00DyNM11NQ2/F9QlJlXopCmYahjpMkF4xjpGCM4xjomyDKGlpr/AQ "Python 2 – Try It Online")
---
**[Python 2](https://docs.python.org/2/), 33 bytes**
```
lambda x,n:1/x*-~n or~-x**-~n/~-x
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaFCJ8/KUL9CS7cuTyG/qE63QgvE1Acy/hcUZeaVKKRpGOoYaXLBOEY6xgiOsY4JsoyhpeZ/AA "Python 2 – Try It Online")
[Answer]
## Python 3, 42 bytes
```
lambda x,n:n+1if x<2else(x**(n+1)-1)/(x-1)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PycxNyklUaFCJ88qT9swM02hwsYoNac4VaNCS0sDKKKpa6ipr1EBJP//BwA)
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 19 bytes
```
@(x,n)sum(x.^(0:n))
```
[Try it online!](https://tio.run/##y08uSSxL/f/fQaNCJ0@zuDRXo0IvTsPAKk9T839iXrGGkY6hpeZ/AA "Octave – Try It Online")
Just learnt Octave 15 minutes ago for this challenge... Hoping it is already optimized.
[Answer]
# [J](http://jsoftware.com/), ~~8~~ 7 bytes
```
#.1$~>:
```
[Try it online!](https://tio.run/##y/qvpKegnqZga6WuoKNQa6VgoADE/5X1DFXq7Kz@a/43VEhTMOIyApLGXMZA0oTLqAJIGVoCAA "J – Try It Online")
### How it works
```
#.1$~>: Left argument = X, Right argument = N
1$~>: Generate a list of N+1 ones
#. Interpret as base X digits and convert to single integer
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 7 bytes
```
+/1,*∘⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbBG19Qx2tRx0zHvVu/v/fUCFNwYjLCEgacxkDSRMw29ASAA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
à╕F¬f£ù╞
```
[Run and debug it](https://staxlang.xyz/#p=85b846aa669c97c6&i=1+2%0A2+3%0A3+4%0A2+19&a=1&m=2)
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 38 bytes
```
import StdEnv
$x n=sum[x^i\\i<-[0..n]]
```
[Try it online!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3PzO3IL@oRCG4JMU1r4xLpUIhz7a4NDe6Ii4zJibTRjfaQE8vLzb2f3BJIlCVrYKKgpGCoeX/f8lpOYnpxf91PX3@u1TmJeZmJhcDAA "Clean – Try It Online")
[Answer]
# Pure [Bash](https://www.gnu.org/software/bash/) (no external utilities), 32
```
echo $[`eval echo +$1**{0..$2}`]
```
[Try it online!](https://tio.run/##S0oszvifll@kUJJaXJKcWJyqkJmnoGSoYKSkoGSkYAwkjRVMwGxDSyVrhZR8roKizLySNAUl1WIFWzsFJQUVmE6u4tQSBV1dhMD/1OSMfAWV6ITUssQcBTBHW8VQS6vaQE9Pxag2IfZ/Sn5e6n8A "Bash – Try It Online")
[Answer]
# [Bash](https://www.gnu.org/software/bash/) with GNU utilities, 23
```
seq -s+ -f$1^%g 0 $2|bc
```
[Try it online!](https://tio.run/##RYs7CgIxFAD7PcXwyFYSMFkbET2KsJ8X3SbRfSm9exRBbIZhYKbR7i2VjapW59GUNSOBKEhk@HDg8PVwlBNL6R7bmmtCeuN8QXC/szOteP8PzfSJtx0@uXDtb@xx8TXNbSlZ2xs "Bash – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 19 bytes
```
{sum $^a X**0..$^b}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv7q4NFdBJS5RIUJLy0BPTyUuqfZ/cWKlQpqGoY6RpjUXhG2kYwxnG@uYIIkbWmr@BwA "Perl 6 – Try It Online")
### Explanation:
```
{ } # Anonymous code block
sum # Get the sum of
X** # The cross product with the meta operator exponential
$^a # With the first parameter
0..$^b # And the range of 0 to the second parameter
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 8 bytes
```
l~),f#:+
```
[Try it online!](https://tio.run/##S85KzP3/P6dOUydN2Ur7/39jBRMA) Or [verify all test cases](https://tio.run/##S85KzP1f/T@nTlMnTdlK@39BrYnWf0MFIy4jBWMuYwUTIG1oCQA).
### Explanation
```
l e# Read a line from STDIN
~ e# Evaluate: pushes x, then n
) e# Add 1 to n
, e# Range: gives [0 1 ... n]
f# e# Map with extra parameter: gives [x^0 x^1 ... x^n]
:+ e# Fold addition over array: gives x^0 + x^1 + ... + x^n
e# Implicit display in STDOUT
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~44~~ 34 bytes
Here's my naive and simple solution.
```
f=lambda x,n:n>=0and x**n+f(x,n-1)
```
[**Try it online!**](https://tio.run/##FYpBDsIgEADP8Io9AtJEqBeb1Ft79Q1oISWpW7JipK9HvMwkk0lHXne0tYZxc6/H4qBoHPA2nh0uUJTCUxAtdUbW7xo3D2bgLNPRyBJFzBCEipg@WUjJmS9PnzJM93ki2gncG/x/9SW2oRptudU97/Wl2Vx/ "Python 2 – Try It Online")
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 21 bytes
```
(x,n)->sum(i=0,n,x^n)
```
[Try it online!](https://tio.run/##LcdJCoAwEAXRq3xcpaEDThsXehGJ0AhKIIbGAfT00YCreqWye7tqWtAnc3MkOxzXZnxfcuR7ipRENTxGYAfo7uP5schTYJYQzMIQIsY4VozafagZTW7DaP@vOucovQ "Pari/GP – Try It Online")
[Answer]
# Java 8, ~~78~~ ~~59~~ 40 bytes
```
x->n->x>1?~-(int)Math.pow(x,n+1)/~-x:n+1
```
Uses the approach mentioned by *@flawr*.
[Try it online.](https://tio.run/##lY69DoIwFEZ3n@KObbQ1oIt/dTNxcHI0DhUBi/XSwEUxRl8da8RZ3U7ynXw5mT5rke2PTWR1WcJKG7x1AErSZCLI/CorMlYmFUZkcpSLFqZLpDiNi95vUgtKQQKzphYKhapVMH8IZpD4StNBuvzC6h52A95/iHrsoZn4FlftrG9pk8652cPJZ7I1FQbTzRY0fyUDrK8lxSeZVySdn8giS6R2zl5ZwFsIOZ98k8OPPPhBHnzk4T/Pweht3zv35gk)
**Explanation:**
```
x->n-> // Method with two integer parameters and integer return-type
x>1? // If `x` is larger than 1:
~-(int)Math.pow(x,n+1) // Return `x` to the power of `n+1` - 1
/~-x // integer-divided by `x-1`
: // Else:
n+1 // Return `n+1` as result instead
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 8 bytes
```
⊣⊥1⍴⍨1+⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbhEddix91LTV81LvlUe8KQ@1HXYv@/zdUSFMw4jICksZcxkDSBMw2tAQA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), 49 bytes
Throws errors, but still works I guess.
```
f(_,0,1).
f(X,N,Y):-M is N-1,f(X,M,Z),Y is Z+X^N.
```
[Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/P00jXsdAx1BTjytNI0LHTydS00rXVyGzWMFP11AHJOSrE6WpEwkSidKOiPPTA2kx0jG0BKrUAwA "Prolog (SWI) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 51 bytes
Your usual, everyday recursive solution.
```
f(b,e,t,i){for(t=1,i=e;i--;t*=b);t=e--?t+f(b,e):1;}
```
[Try it online!](https://tio.run/##VYrBDoIwEAXvfEWDMeliawJ6shY/xHCA0sImCKauXAjfXosX423ezDOyMybscDTDu7Xs@qIWp2NfJn9qwCa64HgjrCCBsLjJc9K5QG0VSqko0w0o0lbKGx2@R7jkag04EnvUOPINat8ZYfrasyyLPANbEsbQ8S2UBbCnjzfH032bimhpwi3N97wC8VtFBQAqWUM4hfMH "C (gcc) – Try It Online")
]
|
[Question]
[
Given a number `n`, Output an ordered list of 1-based indices falling on either of the diagonals of an `n*n` square matrix.
## Example:
For an input of `3`:
The square shall be:
```
1 2 3
4 5 6
7 8 9
```
Now we select all the indices represented by `\`, `/` or `X` (`#` or non-diagonal positions are rejected)
```
\ # /
# X #
/ # \
```
The output shall be:
```
[1,3,5,7,9]
```
# Test cases:
```
1=>[1]
2=>[1,2,3,4]
3=>[1,3,5,7,9]
4=>[1,4,6,7,10,11,13,16]
5=>[1,5,7,9,13,17,19,21,25]
```
There will be no accepted answer. I want to know the shortest code for each language.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 28 bytes
```
@(n)find((I=eye(n))+flip(I))
```
Anonymous function that inputs a number and outputs a column vector of numbers.
[**Try it online!**](https://tio.run/##y08uSSxL/Z9mq6en999BI08zLTMvRUPD0za1MhXI09ROy8ks0PDU1PyfpmGs@R8A "Octave – Try It Online")
[Answer]
# JavaScript (ES6), 48 bytes
Outputs a dash-separated list of integers as a string.
```
f=(n,k=n*n)=>--k?f(n,k)+(k%~-n&&k%-~n?'':~k):'1'
```
### Formatted and commented
```
f = (n, k = n * n) => // given n and starting with k = n²
--k ? // decrement k; if it does not equal zero:
f(n, k) + ( // return the result of a recursive call followed by:
k % ~-n && // if both k % (n - 1) and
k % -~n ? // k % (n + 1) are non-zero:
'' // an empty string
: // else:
~k // -(k + 1) (instantly coerced to a string)
) // end of iteration
: // else:
'1' // return '1' and stop recursion
```
### Test cases
```
f=(n,k=n*n)=>--k?f(n,k)+(k%~-n&&k%-~n?'':~k):'1'
;[1,2,3,4,5].forEach(n => console.log(n, '->', f(n)))
```
[Answer]
# [R](https://www.r-project.org/), ~~38~~ ~~35~~ ~~34~~ 38 bytes
3 bytes saved when I remembered about the existence of the `which` function...
, 1 byte saved thanks to @Rift
```
d=diag(n<-scan());which(d|d[n:1,])
```
+4 bytes for the argument `ec=T` when called as a full program by `source()`
[Try it online!](https://tio.run/##K/r/P8U2JTMxXSPPRrc4OTFPQ1PTujwjMzlDI6UmJTrPylAnVvO/6X8A "R – Try It Online")
Explanation:
```
n<-scan() # take input
d=diag(n); # create an identity matrix (ones on diagonal, zeros elsewhere)
d|d[n:1,] # coerce d to logical and combine (OR) with a flipped version
which([d|d[n:1,]]) # Find indices for T values in the logical expression above
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
⁼þ`+Ṛ$ẎT
```
[Try it online!](https://tio.run/##y0rNyan8//9R457D@xK0H@6cpfJwV1/I////TQE "Jelly – Try It Online")
Uses Luis Mendo's algorithm on his MATL answer.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~41~~ 37 bytes
This works in MATLAB too by the way. No sneaky Octave specific functionality :)
```
@(x)unique([x:x-1:x^2-1;1:x+1:x*x+1])
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0KzNC@zsDRVI7rCqkLX0KoizkjX0BpIawOxFpCM1fyfpmGm@R8A "Octave – Try It Online")
### Explanation:
Instead of creating a square matrix, and find the two diagonals, I figured I rather calculate the diagonals directly instead. This was **17** bytes shorter! =)
```
@(x) % Anonymous function that takes 'x' as input
unique(... ...) % unique gives the unique elements, sorted
[x:x-1:x^2-1 % The anti-diagonal (is that the correct word?)
; % New row
1:x+1:x*x+1]) % The regular diagonal
```
This is what it looks like, without `unique`:
```
ans =
6 11 16 21 26 31
1 8 15 22 29 36
```
Yes, I should probably have flipped the order of the diagonals to make it more human-friendly.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 6 bytes
```
XytP+f
```
[Try it online!](https://tio.run/##y00syfn/P6KyJEA77f9/YwA "MATL – Try It Online")
### Explanation
Same approach as my Octave answer.
Consider input `3` as an example.
```
Xy % Implicit input. Identity matrix of that size
% STACK: [1 0 0;
0 1 0;
0 0 1]
t % Duplicate
% STACK: [1 0 0
0 1 0
0 0 1],
[1 0 0
0 1 0
0 0 1]
P % Flip vertically
% STACK: [1 0 0
0 1 0
0 0 1],
[0 0 1
0 1 0
1 0 0]
+ % Add
% STACK: [1 0 1
0 2 0
1 0 1]
f % Linear indices of nonzero entries. Implicit display
% STACK:[1; 3; 5; 7; 9]
```
Linear indexing is [column-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order), 1-based. For more information see length-12 snippet [here](https://codegolf.stackexchange.com/a/76535/36398).
[Answer]
# [Python 2](https://docs.python.org/2/), ~~54~~ 53 bytes
```
lambda n:[i+1for i in range(n*n)if i%-~n<1or i%~-n<1]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKjpT2zAtv0ghUyEzT6EoMS89VSNPK08zM00hU1W3Ls/GECSnWqcLZMX@hys01DHSMdYx0TG1UigoyswrUcjUUUjTyNT8DwA "Python 2 – Try It Online")
[Answer]
# Octave, ~~68~~ 54 bytes
*Thanks to @Stewie Griffin for saving 14 bytes!*
```
@(x)unique([diag(m=reshape(1:x^2,x,x)),diag(flip(m))])
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0KzNC@zsDRVIzolMzFdI9e2KLU4I7EgVcPQqiLOSKdCp0JTUwcslZaTWaCRq6kZq/k/TcNY8z8A)
# MATLAB, 68 bytes
```
x=input('');m=reshape([1:x*x],x,x);unique([diag(m) diag(flipud(m))])
```
**Explanation:**
```
@(x) % Anonymous function
m=reshape([1:x*x],x,x); % Create a vector from 1 to x^2 and
% reshape it into an x*x matrix.
diag(m) % Find the values on the diagonal.
diag(flip(m)) % Flip the matrix upside down and
% find the values on the diagonal.
unique([]) % Place the values from both diagonals
% into a vector and remove duplicates.
```
[Answer]
# Mathematica, 42 bytes
```
Union@Flatten@Table[{i,#+1-i}+i#-#,{i,#}]&
```
[Try it online!](https://tio.run/##y00sychMLv6fZvs/NC8zP8/BLSexpCQ1zyEkMSknNbo6U0dZ21A3s1Y7U1lXWQfErY1V@x9QlJlXouCQFm0YywVnGyGxjZHYJkhs09j//wE "Mathics – Try It Online")
@KellyLowder golfed it down to..
# Mathematica, 37 bytes
```
##&@@@Table[{i-#,1-i}+i#,{i,#}]⋃{}&
```
and @alephalpha threw away the table!
# Mathematica, 34 bytes
```
Union@@Range[{1,#},#^2,{#+1,#-1}]&
```
[Answer]
# [Proton](https://github.com/alexander-liao/proton), 41 bytes
```
n=>[i+1for i:0..n*n if!(i%-~n)or!(i%~-n)]
```
[Try it online!](https://tio.run/##KyjKL8nP@59m@z/P1i46U9swLb9IIdPKQE8vTytPITNNUSNTVbcuTzO/CMSq083TjP0PURJtqGOkY6xjomMaW82lAAQFRZl5JRqZOgppGpmamly1/wE "Proton – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 14 bytes
```
U:GeGXytPY|*Xz
```
[Try it online!](https://tio.run/##y00syfn/P9TKPdU9orIkILJGK6Lq/39TAA "MATL – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~65~~ 58 bytes
*-7 bytes thanks to Titus!*
```
f(n,i){for(i=0;i<n*n;i++)i%-~n&&i%~-n||printf("%d ",i+1);}
```
[Try it online!](https://tio.run/##RYzBCoMwEETv@YolENlUBXvoKdp/KbEpe@gqqfai8dfTJSC9zMzOsM@3L@9zDsgN2S1MEWnoHPV8YUd1bcm0B1cVmaPlfZ8j8RJQmxF0Q/XVupSlgfeDGL8TjRY2BVAwUhMM0DmxHm5igiszwMkJaORluJ@0Mgb853ldPqh1uZISic9ljSxUlfIP "C (gcc) – Try It Online")
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 97 83 bytes
```
f=>{var s="[";for(int i=0;i<n*n-1;)s+=i%-~n<1|i++%~-n<1?i+",":"";return s+n*n+"]";}
```
[Try it online!](https://tio.run/##NY7BagIxEIbP7lMMASHbuKKHXsxGD4WeKkh78CA9hGy2DOgEMlmh6PrqaVboaYafb@b7HTcuRJ8HRvqBr19O/qIrd7bMcIBbNeNkEzq4Buxgb5FkPaUzpAQEBspcHmxkL98CcTj75ae33QeSl3WtC/g@kGsLteAUi2ILfQnKYe7N9na1EdiIk9B9iHL6iWalsaUXata6ZmVw3jyoXd9RqfmjKdsOlViIjRA6@jREAlaFVuJb6DFPwv8ex4jJy8km6VllrMb8mv8A "C# (.NET Core) – Try It Online")
The change here is based on the shift between numbers to find. The two shifts starting at 0 are `n-1` and `n+1`, so if `n=5`, the numbers for `n-1` would be `0,4,8,12,16,20` and for `n+1` would be `0,6,12,18,24`. Combining these and giving 1-indexing (instead of 0-indexing) gives `1,5,7,9,13,17,19,21,25`. The offset from `n` is achieved using bitwise negation (bitwise complement operation), where `~-n==n-1` and `-~n==n+1`.
### Old Version
```
f=>{var s="[";for(int i=0;i<n*n-1;i++)s+=(i/n!=i%n&&n-1-i/n!=i%n?"":i+1+",");return s+$"{n*n}]";}
```
[Try it online!](https://tio.run/##NY5BSwMxEIXP3V8xBi1J023twYtp2oPgSaHYQw/iIaRZGagTyGQLsuxvj1mhp@F9vDfveW59TKH0jPQNx1/O4cc0/uKY4QBDM@PsMnq4RjzDu0OSaqIzpAwEFupdHVziIF8icbyE1Udw5zekIJUy1fjak99W15JzqhU76CqowdLZ3XB1CdiKT2G6mOT0E@2jwS0tqN0Y1FqxthLXdGfxgebzStub2gvxjHqjxVIok0LuEwHrezHU8PglzFim@tuqU8Ic5NQt6X/Y2IzlqfwB "C# (.NET Core) – Try It Online")
This approach uses the column and row indices for determining if the numbers are on the diagonals. `i/n` gives the row index, and `i%n` gives the column index.
### Returning Only The Number Array
If constructing only the number array is deemed to count towards the byte cost, then the following could be done, based on Dennis.Verweij's suggestion (`using System.Linq;` adds an extra 18 bytes):
[C# (.NET Core)](https://www.microsoft.com/net/core/platform), 66+18=84 bytes
```
x=>Enumerable.Range(1,x*x).Where(v=>~-v%~-x<1|~-v%-~x<1).ToArray()
```
[Try it online!](https://tio.run/##TU5Pa8IwHD0vnyIUhUTagAdPtYUh8yB6mYKH0kOMP7uAJjO/tFS69qvXbDDw8ODxeP8UJso6GGvUpqL7B3q4ia0295S8SilRV4lIvzuCXnqt6Lo2aqmNjwOKMr9kY5vlH6a@gZOnK4hPaSpg87idtVwcv8ABa7J8SJrpkLTL@c8vS4bAuDjYd@fkg/Ex/W9vrD7TndSGoXfhRlFS6SrkHXlbWYM2DByd9hCeAptERbf/s4mNDZEojuILW3DelxFPSU/68Qk "C# (.NET Core) – Try It Online")
[Answer]
# Javascript, ~~73~~ 63 bytes
*old version*
```
n=>[...Array(y=n*n).keys(),y].filter(x=>(--x/n|0)==x%n||(x/n|0)==n-x%n-1)
```
*Saved 10 bytes thanks to @Shaggy*
```
n=>[...Array(n*n)].map((_,y)=>y+1).filter(x=>!(--x%-~n&&x%~-n))
```
First time golfing! here's hoping I didn't mess up too badly.
```
let f=n=>[...Array(n*n)].map((_,y)=>y+1).filter(x=>!(--x%-~n&&x%~-n));
[1,2,3,4,5].forEach(n=>console.log(f(n)))
```
[Answer]
# [Pyth](https://pyth.readthedocs.io), ~~20~~ 18 bytes
([Here is the initial version](https://codegolf.stackexchange.com/revisions/140327/1).)
```
hMf|<%ThQ1<%TtQ1U*
```
**[Test Suite.](https://pyth.herokuapp.com/?code=hMf%7C%3C%25ThQ1%3C%25TtQ1U%2a&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5&debug=0)**
# [Pyth](https://pyth.readthedocs.io), 18 bytes
```
hMf>1*%ThQ%T|tQ1U*
```
**[Test Suite.](https://pyth.herokuapp.com/?code=hMf%3E1%2a%25ThQ%25T%7CtQ1U%2a&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5&debug=0)**
[Answer]
# [Perl 5](https://www.perl.org/), 56 + 1 (-n) = 57 bytes
```
!(($_+1+$_/$,)%$,&&$_%($,+1))&&say++$_ for 0..($,=$_)**2
```
[Try it online!](https://tio.run/##DclBCoAgEADArxisoq6aBh57Qm@QDgVBqGiXPt/mdaYe7Y5Ek5SQMCCkGYziYISAxCUYDEoJ0fcXx7GzNOadG75CUlovRPEr9blK7mS36HzwZPMP "Perl 5 – Try It Online")
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 71 bytes
```
n->{for(int i=0;i<n*n;i++)if(i%-~n<1||i%~-n<1)System.out.println(i+1);}
```
[Try it online!](https://tio.run/##bU6xTsMwFNz7FW@pZBPHaoAuuGVhYmDqWHUwrlO9kDxH8UsRStNfD6YKTAxP73R3urvKnm0eWk/V8WNq@/caHbjaxghvFgmGBcDMRrac3jngEZqkiR13SKf9AWx3ivJmBahSnu4Za1325BgD6Vfil0Cxb3wH5Xai/HkoQyeQGHC7MrihOzKYZRJLgcv8SpvicsHlNU9A7r4i@0aHnnWb6rgmgVkhzTiZW99f0hOQ/4QE94dhpaBQcK/gQcGjgvX4uy75tXXOtyxQmpn6p2LWxsXPjdM3 "Java (OpenJDK 8) – Try It Online")
Port of [scottinet's answer](https://codegolf.stackexchange.com/a/140339/16236).
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), 16 bytes
Can't seem to do better than this but I'm sure it's possible. Had to sacrifice 2 bytes for the unnecessary requirement that we use 1-indexing.
```
²õ f@´XvUÉ ªXvUÄ
```
[Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=svUgZkC0WHZVySCqWHZVxA==&input=NQo=)
[Answer]
# Octave, 32 bytes
```
@(n)find((m=abs(--n:-2:-n))==m')
```
[Try it online!](https://tio.run/##y08uSSxL/f/fQSNPMy0zL0VDI9c2MalYQ1c3z0rXyEo3T1PT1jZXXfN/Yl6xhqnmfwA "Octave – Try It Online")
[Answer]
# PHP, ~~56~~ 54+1 bytes
+1 byte for `-R` flag
```
for(;$z**.5<$n=$argn;$z++)$z%-~$n&&$z%~-$n||print~+$z;
```
prints numbers prepended by dashes. Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/8d9e5edcbb9978dae3a86393f6f4f05a86e62c37).
requires PHP 5.6 or later for `**` operator.
Add one byte for older PHP: Replace `;$z**.5<$n=$argn` with `$z=$argn;$z<$n*$n`.
[Answer]
# Ruby, 45 bytes
```
->n{(n*n).times{|i|i%-~n>0&&i%~-n>0||p(i+1)}}
```
Works internally as zero indexed. checks if `i` modulo `n+1` or `n-1` is 0, if so prints `i+1`.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 12 bytes
```
ṁo►L∂Se↔C¹ḣ□
```
[Try it online!](https://tio.run/##ASMA3P9odXNr///huYFv4pa6TOKIglNl4oaUQ8K54bij4pah////Mw "Husk – Try It Online")
indices are unordered.
]
|
[Question]
[
## Challenge
Given an integer, \$s\$, as input where \$s\geq 1\$ output the value of \$\zeta(s)\$ (Where \$\zeta(x)\$ represents the [Riemann Zeta Function](https://en.wikipedia.org/wiki/Riemann_zeta_function)).
## Further information
\$\zeta(s)\$ is defined as:
$$\zeta(s) = \sum\limits^\infty\_{n=1}\frac{1}{n^s}$$
You should output your answer to 5 decimal places (no more, no less). If the answer comes out to be infinity, you should output \$\infty\$ or equivalent in your language.
Riemann Zeta built-ins are allowed, but it's less fun to do it that way ;)
## Examples
***Outputs must be exactly as shown below***
```
Input -> Output
1 -> ∞ or inf etc.
2 -> 1.64493
3 -> 1.20206
4 -> 1.08232
8 -> 1.00408
19 -> 1.00000
```
## Bounty
As consolation for allowing built-ins, I will offer a 100-rep bounty to the shortest answer which **does not** use built-in zeta functions. (The green checkmark will still go to the shortest solution overall)
## Winning
The shortest code in bytes wins.
[Answer]
# Mathematica, ~~9~~ ~~7~~ 11 bytes
```
Zeta@#~N~6&
```
Explanation:
```
Zeta@# (* Zeta performed on input *)
~N (* Piped into the N function *)
~6 (* With 6 digits (5 decimals) *)
& (* Make into function *)
```
[](https://i.stack.imgur.com/nAG2S.png)
Without builtin:
# Mathematica, 23 UTF-8 bytes
```
Sum[1/n^#,{n,∞}]~N~6&
```
Thanks to Kelly Lowder
[Answer]
# Javascript, ~~81~~ ~~70~~ ~~66~~ 65 bytes
```
s=>s-1?new Int8Array(1e6).reduce((a,b,i)=>a+i**-s).toFixed(5):1/0
```
## Runnable examples:
```
ζ=s=>s-1?new Int8Array(1e6).reduce((a,b,i)=>a+i**-s).toFixed(5):1/0
const values = [ 1, 2, 3, 4, 8, 19 ];
document.write('<pre>');
for(let s of values) {
document.write('ζ(' + s + ') = ' + ζ(s) + '\n')
}
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~22~~ 21 bytes
Look ma, no built-ins! -1 thanks to ngn.
Since Dyalog APL does not have infinities, I use [Iverson's proposed notation](http://www.jsoftware.com/papers/APLDictionary1.htm#2a2).
```
{1=⍵:'¯'⋄5⍕+/÷⍵*⍨⍳!9}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///Pyq1JPFR24RqQ9tHvVut1A@tV3/U3WL6qHeqtv7h7UAhrUe9Kx71bla0rIWoVTDkAlNGEMoYQplAKFMIZQGhDC0B "APL (Dyalog Unicode) – Try It Online")
`{` anonymous function:
`1=⍵:` if the argument is one, then:
`'¯'` return a macron
`⋄` else
`!9` factorial of nine (362880)
`⍳` first that many integers **i**ntegers
`⍵*⍨` raise them to the power of the argument
`÷` reciprocal values
`+/` sum
`5⍕` format with five decimals
`}` [end of anonymous function]
[Answer]
## C, ~~74~~ ~~70~~ 69 bytes
```
n;f(s){double z=n=0;for(;++n>0;)z+=pow(n,-s);printf("%.5f",z/=s!=1);}
```
Compile with `-fwrapv`. It will take some time to produce an output.
See it [work here](https://ideone.com/vt8QIv). The part `++n>0` is replaced with `++n<999999`, so you don't have to wait. This keeps identical functionality and output.
[Answer]
# TI-Basic, 16 bytes (no builtins)
```
Fix 5:Σ(X^~Ans,X,1,99
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~112~~ ~~101~~ ~~94~~ 84 bytes
Thanks for the golfing tips from ceilingcat.
```
n;f(s){float r;for(n=98;n;r+=pow(n--,-s));printf("%.5f",r+pow(99,-s)*(.5+99./--s));}
```
[Try it online!](https://tio.run/##XcvRCoMgGIbhc69ChMHvTEfbgkS6GBH@CMxCHTuIbn1udTQ8fd7vc3J0rpRgEBLf0C8202hwiRAG3ZtgohjW5Q1BykYmzs0ap5AR2EV1yJoojqj10a6gOqG1uslzuJfZTgE42QilCO3v@soJGOPmhHsNjxqeNfQ1tPpfdlI@Dr0dU5F@/gI "C (gcc) – Try It Online")
[Answer]
# [Julia](https://julialang.org/), 36 bytes
```
x->x!=1?@sprintf("%.5f",zeta(x)):Inf
```
[Answer]
# C,~~129 130~~ 128 bytes
```
#include<math.h>
f(s,n){double r=0;for(n=1;n<999;++n)r+=(n&1?1:-1)*pow(n,-s);s-1?printf("%.5f\n",r/(1-pow(2,1-s))):puts("oo");}
```
it uses the following formula

test and results
```
main(){f(2,0);f(1,0);f(3,0);f(4,0);f(8,0);f(19,0);}
1.64493
+oo
1.20206
1.08232
1.00408
1.00000
```
[Answer]
# [Rust](https://www.rust-lang.org/), ~~133 129 120~~ 117 bytes
```
fn f(s:f64){let mut y@mut n=0.;while n<999.{n+=1.;y-=f64::powf(-1.,n)/n.powf(s)}print!("{:.5}",y/(1.-(1.-s).exp2()))}
```
[Try it online!](https://ato.pxeger.com/run?1=bZAxDoJAEEV7T7FQ7UQYXETDspJ4FQs2ksBIYAkSQukpbCj0UN5GINgYivnJvMzP_5nnq6wrMwzv2mg3_NSamOZVpI8BdFliWF4b1p4npXiHqrmmWcLoJKXEjraxQNW68XgdRcWt0dwV6BB4hPNWQV-UKRmL212Eh952Wo8LdKepAJN74XMA6JfwxxieX1Li0G3YWEMgqNmfkcVBzcxfYfsVFqywcIUJ-QeXMr-PfAE)
Thanks to @Steffan for -9.
Slightly golfed less
```
fn f(s:f64){
let mut y@mut n=0.;
while n<999.{
n+=1.;
y-=f64::powf(-1.,n)/n.powf(s)
}
print!("{:.5}",y/(1.-(1.-s).exp2()))
}
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 21 bytes
```
q?'%.5f'2e5:G_^sYD}YY
```
[Try it online!](https://tio.run/nexus/matl#@19or66qZ5qmbpRqauUeH1cc6VIbGfn/vzEA "MATL – TIO Nexus")
### Explanation
Input `1` is special-cased to output `inf`, which is how MATL displays infinity.
For inputs other than `1`, summing the first `2e5` terms suffices to achieve a precision of 5 decimal places. The reason is that, from direct computation, this number of terms suffices for input `2`, and for greater exponents the tail of the series is smaller.
```
q % Input (implicit) minus 1
? % If non-zero
'%.5f' % Push string: format specifier
2e5: % Push [1 2 ... 2e5]
G % Push input again
_ % Negate
^ % Power. element-wise
s % Sum of array
YD % Format string with sprintf
} % Else
YY % Push infinity
% End (implicit)
% Display (implicit)
```
[Answer]
# R, 54 bytes
```
function(a){round(ifelse(a==1,Inf,sum((1:9^6)^-a)),5)}
```
Finds the sum directly and formats as desired, outputs `Inf` if a is 1. Summing out to `9^6` appears to be enough to get five-place accuracy while still being testable; `9^9` would get better accuracy in the same length of code. I could get this shorter if R had a proper ternary operator.
[Answer]
# Python 3: 67 bytes (no built-ins)
```
f=lambda a:"∞"if a<2else"%.5f"%sum([m**-a for m in range(1,10**6)])
```
Nothing fancy, only uses python **3** because of the implicit utf-8 encoding.
[Try it online](https://tio.run/nexus/python3#@59mm5OYm5SSqJBopfSoY55SZppCoo1Rak5xqpKqnmmakmpxaa5GdK6Wlm6iQlp@kUKuQmaeQlFiXnqqhqGOoYGWlplmrCYXSCYRJBNtqGOkY6xjomOhY2gZa8XFWVCUmVeioJGmkaip@f8/AA) with test cases.
[Answer]
# [Perl 6](http://perl6.org/), 50 bytes
```
{$_-1??(1..1e6).map(* **-$_).sum.fmt('%.5f')!!∞}
```
[Answer]
# PARI/GP, ~~27~~ 26 bytes
```
\p 6
s->trap(,inf,zeta(s))
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 23 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ȷ6Rİ*⁸S÷Ị¬$ær5;ḷỊ?”0ẋ4¤
```
**[Try it online!](https://tio.run/nexus/jelly#@39iu1nQkQ1ajxp3BB/e/nB316E1KoeXFZlaP9wB4tk/aphr8HBXt8mhJf///zcCAA)**
### How?
* Sums the first million terms
* Divides by `0` when `abs(input)<=1` to yield `inf` (rather than `14.392726722864989`) for `1`
* Rounds to 5 decimal places
* Appends four zeros if `abs(result)<=1` to format the `1.0` as `1.00000`
* Prints the result
```
ȷ6Rİ*⁸S÷Ị¬$ær5;ḷỊ?”0ẋ4¤ - Main link: s
ȷ6 - literal one million
R - range: [1,2,...,1000000]
İ - inverse (vectorises)
⁸ - link's left argument, s
* - exponentiate
S - sum
$ - last two links as a monad:
Ị - insignificant? (absolute value of s less than or equal to 1?)
¬ - not (0 when s=1, 1 when s>1)
÷ - divide (yielding inf when s=1, no effect when s>1)
ær5 - round to 10^-5
¤ - nilad followed by link(s) as a nilad:
”0 - literal '0'
ẋ4 - repeated four times
Ị? - if insignificant (absolute value less than or equal to 1?)
; - concatenate the "0000" (which displays as "1.00000")
ḷ - else: left argument
- implicit print
```
[Answer]
# [Python 3](https://docs.python.org/3/) + SciPy, 52 bytes
```
lambda n:'%.5f'%zeta(n,1)
from scipy.special import*
```
[Try it online!](https://tio.run/##HcpBCsIwEAXQfU7xN6WJDIVYBS30JOoi1gQH2iQk2dSD9Ri9UhTf@sW1vIPv676N9zqb5fky8EPbdGfXNh9bjPSklXApLMgTx7XL0U5sZvASQyqHWmwuGSNumnAk9IQT4ULQ14cQLiQw2OO/BoGfmNgXuW@Slapf "Python 3 – Try It Online")
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), 14 bytes (no builtins)
```
┴¿Å'∞{◄╒▬∩Σ░7<
```
Note that in the TIO link, I have substituted `◄` for `►`, which pushed \$10^6\$ instead of \$10^7\$. This is because the version submitted here timeouts for all test cases. This results in the answers for 3 and 8 to be off by 1 decimal place. However, there are way bigger 1-byte numerical literals in MathGolf, allowing for arbitrary decimal precision.
[Try it online!](https://tio.run/##ATcAyP9tYXRoZ29sZv//4pS0wr/DhSfiiJ574pa64pWS4pas4oipzqPilpE3PP//MQoyCjMKNAo4CjE5 "MathGolf – Try It Online")
## Explanation
```
┴ check if equal to 1
¿ if/else (uses one of the next two characters/blocks in the code)
Å start block of length 2
'∞ push single character "∞"
{ start block or arbitrary length
◄ push 10000000
╒ range(1,n+1)
▬ pop a, b : push(b**a)
∩ pop a : push 1/a (implicit map)
Σ sum(list), digit sum(int)
░ convert to string (implicit map)
7 push 7
< pop(a, b), push(a<b), slicing for lists/strings
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 64 bytes
```
s=>[...Array(1e6)].reduce((a,b,i)=>s>1>i?a:i**-s+a,0).toFixed(5)
```
[Try it online!](https://tio.run/##LYxLDoIwAAX3nOLtaKE04i9@AsaNl0AWFYqpIdS0QDTGa3EMroQlcfkmM@8hemELo55t1OhSTuOQTDZJM8752RjxJrHc0pwbWXaFJESwG1M0SW0ap@okDioIIhsKtqC81Rf1kiXZ0KnQjW3Ri7qTFgkyxAxLhhXDmmHHEO@RH71KG1LLFha6@ssUHw@Yc11LXus78ceB@AidFMKn7mwejjnVgWvjU@87/QA "JavaScript (Node.js) – Try It Online")
Pointed in Frxstrem's
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 19 bytes
```
ċ[₆(n⁰eĖ⅛)¾∑øḋ7Ẏ|\∞
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJQIiwiIiwixItb4oKGKG7igbBlxJbihZspwr7iiJHDuOG4izfhuo58XFziiJ4iLCIiLCI0Il0=)
No builtins used, used 4 bytes on the decimal places
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 26 bytes
```
⁵*5İH+µŒṘḣ7
⁴!Rİ*³Sǵ’ݵ’?
```
[Don't try it online](https://tio.run/nexus/jelly#@/@ocauW6ZENHtqHth6d9HDnjIc7FptzPWrcohh0ZIPWoc3Bh9sPbX3UMPPIBjBl////fyMA "Jelly – TIO Nexus") with this link! (Since this uses 16!~20 trillion terms, running on TIO produces a MemoryError)
[Try it online](https://tio.run/nexus/jelly#@/@ocauW6ZENHtqHth6d9HDnjIc7FptzgQTNgo5s0Dq0Ofhw@6GtjxpmHtkApuz///9vBAA "Jelly – TIO Nexus") with this link instead. (Uses 1 million terms instead. Much more manageable but takes one more byte)
Returns `inf` for input 1.
**Explanation**
```
⁵*5İH+µŒṘḣ7 - format the output number
⁵*5İH+ - add 0.000005
µŒṘ - get a string representation
ḣ7 - trim after the fifth decimal.
⁴!Rİ*³Sǵ’ݵ’? - main link, input s
µ’? - if input minus 1 is not 0...
⁴!R - [1,2,3,...,16!] provides enough terms.
İ - take the inverse of each term
*³ - raise each term to the power of s
S - sum all terms
Ç - format with the above link
- else:
µ’İ - return the reciprocal of the input minus 1 (evaluates to inf)
```
Out of the 26, bytes, 7 are used for computation, 12 are for formatting, and 7 are for producing `inf` on zero. There has to be a better golf for this.
[Answer]
# [J](https://www.jsoftware.com), 33 bytes (no built-ins)
```
_:^:('*'&e.)7j5":1#.1%[^~1+i.@1e6
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmtxUzHeKs5KQ11LXS1VT9M8y1TJylBZz1A1Oq7OUDtTz8Ew1QyicIcmV2pyRr5DmpqenYKhgpGCsYKJgoWCoSVEesECCA0A)
```
_:^:('*'&e.)7j5":1#.1%[^~1+i.@1e6
i.@1e6 NB. integers up to 1e6
1+ NB. add one
[^~ NB. nʸ for each in 1..1e6
1% NB. reciprocal of each
1#. NB. sum the result
7j5": NB. format each result, width of 7, 5 decimal places
^: NB. if
('*'&e.) NB. '*' is in the formatted result
NB. (": fills with *'s if the width is too small)
_: NB. return an infinity
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
i'∞ë6°LImzO5.ò¾4׫7£
```
4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) are used to account for edge case \$n=1\$, and 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) to round to five decimal places (6 of which for edge case `1.00000`)..
[Try it online](https://tio.run/##yy9OTMpM/f8/U/1Rx7zDq80ObfDxzK3yN9U7vOn/f0MA) or [verify all test cases](https://tio.run/##AUMAvP9vc2FiaWX/dnk/IiDihpIgIj95/2kn4oiew6s2wrBMeW16TzUuw7LCvjTDl8KrN8Kj/30s/1sxLDIsMyw0LDgsMTld).
**Explanation:**
```
i # If the (implicit) input-integer is 1:
'∞ '# Push "∞"
ë # Else:
6° # Push 10 to the power 6: 1,000,000
L # Pop and push a list in the range [1,1000000]
Im # Get the power of the input on each integer
z # Calculate 1/value for each
O # Sum everything together
5.ò # Round to 5 decimal places
¾4× # Push a string of 4 zeros: "0000"
« # Append it to the result
7£ # Pop and leave just the first 7 characters: "1.abcde"
# (after which the result is output implicitly as result)
```
]
|
[Question]
[
>
> ***Note**: [SmokeDetector](https://github.com/Charcoal-SE/SmokeDetector/blob/master/README.md) is a bot that detects spam and offensive posts on the network and posts alerts to chat.*
>
>
>
# What to implement
Smokey's `!!/alive` command uniformly at random picks one of these messages:
* Yup
* You doubt me?
* Of course
* ... did I miss something?
* plz send teh coffee
* Watching this endless list of new questions never gets boring
* Kinda sorta
* You should totally drop that and use jQuery
* ¯\\_(ツ)\_/¯
* ... good question
and prints it to the screen.
Your task is to implement that command.
# Rules
Regular code-golf — the shortest answer in bytes wins ;)
*Good luck!*
[Answer]
# [Python 2](https://python.org), 240 bytes
Hexdump:
```
00000000: efbb bf65 7865 6322 2222 789c 3d4f 3b4e ...exec"""x.=O;N
00000010: c430 10bd ca53 aa84 221c 8082 1a51 202a .0...S.."....Q *
00000020: b4d2 4a6b 6f3c 498c 1c8f f18c 414b 0bf7 ..Jko<I.....AK..
00000030: d93b ec55 b808 0348 54a3 d1fb cf95 3754 .;.U...HT.....7T
00000040: 9f83 9db8 15ae 7a75 536a cc8a 69e5 3851 ......zuSj..i.8Q
00000050: dfed 5a71 f731 070f 31d4 bb1d 3704 6e47 ..Zq.1..1...7.nG
00000060: c546 b76e 1c47 8418 7087 2d8a 1865 235d .F.n.G..p.-..e#]
00000070: 635e fe90 8539 e0a5 9168 e4ec 4a7a 8750 c^...9...h..Jz.P
00000080: 0e50 5a31 f13c 13b9 27af d30f 1fa6 1218 .PZ1.<..'.......
00000090: 98c8 6c52 1405 cfc8 f4f6 2f17 fb5e a962 ..lR....../..^.b
000000a0: 2115 1cd9 3a2e ee61 369f 5685 dce5 bc3f !...:..a6.V....?
000000b0: f45f 1f9f c3e1 fa72 feed 282b b764 59ac ._.....r..(+.dY.
000000c0: 3ea5 1342 e562 215e 6163 d184 f0fc d8a8 >..B.b!^ac......
000000d0: 9eba 514a 8ada 77ae 1b86 6f8b b863 c922 ..QJ..w...o..c."
000000e0: 2222 2e64 6563 6f64 6528 227a 6970 2229 "".decode("zip")
```
[Try it online!](https://tio.run/##VZR5b9NAEMX/z6d4GCQKqMPeRykgQNwSpVCQQKJoT4VDTYEiQr98mQ0OEpaTrO2ZX968GW9OP5YXFyWdYX8f08ODRxPu4Kz9OKNlWy/EfOyh9ZyRu7Pwgb@cVgqKD76MBbqaDp1NA4iorVuZpmlNtw9uvZgZkhnFaAEpckVJViOlYJghC4IICjJZCSVUYoZgymuiiX/oENdnhmJGNlXBJJfhui4wMRTIEjq65JWRJkPk7oeOZ19W@08Hge49J5oZmhk16oxWrEXmf4bQJsCapFFlzyg9WmhvDTNu0RtOf3K0ofijmWGYEXvQiDUHSJsafPIWVruEUkKCi40ZgQvCJpXOf77@TPSJwuHMsENHbxU2eYnutYTwgk2U1SBnWVmCMHDNbGp5/40kjZM8nTyeGW54ao1D9q6xCxwajAzwInioyjrk6JXStjLjEZ3QY6JT2uUOXf4wMzwznLYNvUWBYHVEE8kiShfQTGNPk08I3gqgHLOAyJ8lu3tOL2dGYIZoHGATl9El90XqHKF86qiaq5I9OUjF2kAv30vaJ7r615htX@LwNJQAVyzPghGWG8GX3XQH1aVHz6wyRaeGH19f/c2@SXRMeWYkZigpLVtRI3RSDa05Ce1ih3XBohbuSy66A5c4e48oOXo7QHdnRmZGN3ZI5qSiGxeUvGJ7uFcqqDzMNrAxFdbxcSPiO9HODarvtrUUZujGJkptFJplyUqyeCfdmDGe@i56ATeI/bhDdJ/ypeNU/vOjDj9aTrDSsP2pJnjPgyZzcDz6gXUEppWoNn4cPiP6xdkrokLTzGjDj/GOqsaSneV41zcrFfiBH3PqxQiJwDRRbWVV2850/ul0urbgvWCxWK8rdr//2xC2e8Pp70UryxWm@@@OHuLBwZsXR3u4svOrYLdsI65Ni9PfZ8vVidreubj4Aw "Bash – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 123 bytes
```
Žmõ甡¸€îååªç€î”#`“Yup
ÿ¬³€á?
Of…£
...ƒ§ Iš§†á?
plzƒ¨ teh™²
ÿ€Œèႇ€‚€¢…醙–ÜÜÀ
ÿŠœa
ÿ‚©§À›Â€Š€ƒ€Å jÿ
¯\_(ÿ)_/¯
...‚¿†ä“¶¡Ω
```
[Try it online!](https://tio.run/##FY5BSsNQEIb37xQBN3UTj@C6q64LQqxQaYvFgHbjagj1AskuVMhrG5NIMKAoRZAHM7wsPcRcJM4wMMz8M9/Pf/8wu1nOh8H/rumLKoYXtHjipKV3KqnEN9F0kcPZNcNuuokNOWzxU2V7aSa3DK94MGEY9ilWwdhbFJtCb/Hdk2h18Dhf8HaPH0IK5VOqyTLkDFZWHZIW92JDjYDyyZDRTgoE8IXPZgpCjg1WBAw/lKhNIa1PNcZzsCJnsLuKRuTOowvsNI4STpMcJTd@o/1rhuEf)
**Note:** *Prints a random response with a trailing newline.*
Golfed using [@KevinCruijssen's well known golf tip.](https://codegolf.stackexchange.com/questions/96361/tips-for-golfing-in-05ab1e/166851#166851)
## Explanation
```
Žmõç # Push the katakana character 'ツ'
”¡¸€îååªç€î”#` # Push some uncompressible words onto the stack
“...“ # Then push a compressed string containing the following contents:
Yup # "Yup"
ÿ¬³ me? # "You doubt me?"
Of…£ # "Of course"
...ƒ§ Iš§†á? # "... did I miss something?"
plzƒ¨ teh™² # "plz send teh coffee"
ÿ€Œèႇ€‚…醙–ÜÜÀ # "Watching this endless list of new questions never gets boring"
ÿŠœa # "Kinda sorta"
ÿ‚©§À›Â€Š€ƒ€Å jQuery # "You should totally drop that and use jQuery"
¯\_(ÿ)_/¯ # shruggy boy
...‚¿†ä # "... good question"
¶¡ # Split the responses into a good ol' list
Ω # Randomly pick a response
# At the end, yell the response out to STDOUT implicitly
```
---
Random fact: I was in halfway in the making of this program when my laptop crashed. I had to start coding again. Oh well, at least my answer is winning at the time of writing this!
[Answer]
# [R](https://www.r-project.org/), 265 bytes
```
cat(sample(c('Yup','You doubt me?','Of course','... did I miss something?','please send teh coffee','Watching this endless list of new questions never gets boring','Kinda sorta','You should totally drop that and use jQuery','¯\\_(ツ)_/¯','... good question'),1))
```
[Try it online!](https://tio.run/##PY9BasNADEWv8ne2Ibj0BF2HLEpXJRAIE49sTxmPnJGmJev2PrlDrpKDODKE7vTRf/pfeVk6p7W4aY5Ud3W1L3O1qfZc4LmcFBO9mX7v0XHJQja3bQsfPLaYggiEJ9IxpGH12REnBKHkoTQa1Pe0Qp9Ou9UEswpsHcnYGETBPRL94FxINHASU9@UMZAKTpwNMn4XkneWldU968nIJVoKq4vxAp95tuNO4Sy7WImvj0L5Yu7b9XA41vffv@b4crs@PxiY/X9m1Wxem2ZZHg "R – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 145 bytes
```
“þkċṁṚFọẏ_ỌƤ:ZfCðƓ$6ṛtẓ2JƇMɼ¤ẆƥyɼȧẒ¡ƇƘ9Ɲŀẏ®ỊH\.ƒgFĊ#Ọṁv;`Ä?ḄƒXƲeȥẹ$Ḟ-Ṿṙ"zḄfWẊkEƓẇẇṢ¶ż²ṘzḄ¢ɼQ2³{Ėṃ"B¡f÷ṅƇ0@bSḟ⁶E⁶ėẇefðRẹȤ»O_33o142+33+197¦12309ỌỴX
```
[Try it online!](https://tio.run/##FY7PSsNAGMTfpfZWlCYRJXpQlBYRRNSDRYRKIRFswYsI1UuL1UBUhAS0/i0tqd6kVKnZ3dDDbvqRPMbXF4kbmDkNv5k5MWq1epJMG29iXA1vkTSRvBSR3SN9KCO7A2/pwFwXA3CzC0hez5C66iZYW3HAPaQ30K/HQfSF1OFdsKCtw/ukIVH@jczeOJwD57gY2jOySDafLx@J1gr6LXBKMDSiPlKSRf9jFskYyXPmQkbmPlK7WgAXqZWK9PhoEvAhknYa814c7Kj85zJ8RHKVWeNdU/whuQYrv1rZQ78zbY4K0uGThA1TDHblRuRxtl3WtFNlXs1pWk7RF/mnomp5Pf3FfktJ8g8 "Jelly – Try It Online")
Encodes the whole string but replacing the shrug with `!\_(!)_/!` (since `!` doesn't show up in the string and only printable ASCII / newlines are allowed), and then replaces `!` with the upper bar symbol, and then just sets the Japanese character at that index manually.
Then, split by newlines and select a random one.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 230 bytes
```
Oc"Yup You doubt me? Of course ... did I miss something? plz send teh coffee Watching this endless list of new questions never gets boring Kinda sorta You should totally drop that and use jQuery ¯\_(\u30C4)_/¯ ... good question"\
```
[Try it online!](https://tio.run/##PY49TsNAEIXrvcVTqtAYJOhTUCGKKBWKZCnaeMf2ovWO2ZkNMpfKHXIxM6SgfHo/35sXHdd1322OdXZHrghcz4qJdm7fo@NahFzTNAgx4A1TFIHwRDrGPOzcnH4glAOURkv3PZH78Nr9ubCMwMxEVkpRFNwj0ze@KolGzmLqQgUDqeDMxUruPebgDVHU3//IyDXZPqtPaUEoPNuwV3ijViF8HiqVxd2u7Wnb1uen15eH0@Ptej89MId/2qZ16/oL "Pyth – Try It Online")
Fun fact: If you used a "packed" string, the byte count would jump up to 388.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~283~~ 274 bytes
-9 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)
```
from random import*
print(choice('Yup,You doubt me?,Of course,... did I miss something?,please send teh coffee,Watching this endless list of new questions never gets boring,Kinda sorta,You should totally drop that and use jQuery,¯\_(ツ)_/¯,... good question'.split(',')))
```
[Try it online!](https://tio.run/##PY87bsMwDIb3noKb7UJwhx4gc9Gh6FQEKBAoFmWpkEVVpBJ4bu@TO@QqPYjLZuhEEPwfH8sqgfLjtvlKC1SbnY64FKpyf1dqzNJPgeKEfbdvxeypgaN2FFhwZ148TNQqoxnHEVx08ARLZAamBSXEPO9MSWgZgTE7EAxq8B7RvFmZ/gSgMgY9JlRfiixAHjKe4bMhS6TMup2wwozCcCRFms1zzM5qSxV7Q@JALWk@iU1pBVepaLAV0H@gaf3Ha8O6muvl/dD/fH0Ph4fr5QY9E7n/qm7kkqL0nemGYdi2Xw "Python 3 – Try It Online")
[Answer]
# JavaScript, ~~297~~ ~~287~~ ~~285~~ ~~277~~ 265 bytes
-10 bytes by replacing `Math.floor()` with `~~()`
-2 bytes by replacing `~~()` with `|0` thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil)
-8 bytes by replacing array with `string.split(',')`
-12 bytes by placing options directly inside of `alert()` and replacing `string.split(',')` with `string.split`,``
```
alert('Yup,You doubt me?,Of course,... did I miss something?,please send teh coffee,Watching this endless list of new questions never gets boring,Kinda sorta,You should totally drop that and use jQuery,¯\\_(ツ)_/¯,... good question'.split`,`[Math.random()*10|0])
```
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 237 bytes
```
`0:*1?";"\"Yup;You doubt me?;Of course;... did I miss something?;plz send teh coffee;Watching this endless list of new questions never gets boring;Kinda sorta;You should totally drop that and use jQuery;¯\\_(ツ)_/¯;... good question";
```
[Try it online!](https://tio.run/##PY49TsNAEIV7TvHkCpAw0LKFa0SBqFAkS2GTHdtL1h6zMwsKLdwnd8hVOIgZUlA@vZ/v7a54tywvN3eXt03lqrZaldmtuCBw2ShGatxjhy2XLOTqukaIAfcYowiER9IhTn3j5vQJoSlAabB01xG5Z6/bPxeWEZiZyEopioI7TPSBt0KikScx9U4ZPalgw9lK7iFOwRsiqz/9kYFLsn1Wn9IeIfNsw17hjVqE8PpUKO/d8dC26/Ofr@@L9fXxcLrcM4d/VuWWs@UX "K (oK) – Try It Online")
If returning a string is acceptable, the leading ``0:` and trailing `;` can be elided to save 4 bytes.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~152~~ 151 bytes
```
‽⊞O⪪”}∧Pπ↙!▶�▶τ×Blal⁰FW⊕← ″»yε⦃σ$L}⊖0!…Rf»V?⌕ΦYV'∕ⅉ)>ιη¤=▷∧p{<ψ;↶~⌊″≔↔≡m≦ζX"´j\`⁹WS⌕V›w}LV>DTY(Y⪪h‽BRV⌕↥↘⮌\L∨⁰MPφFY5^IG↑~c‖"⌕ν﹪ηVE\`êVω”A¦¯\_(ツ)_/¯
```
[Try it online!](https://tio.run/##PY9LTgMxDIavYmU1I8FwABZVlqiLFligSkhVOvHMBGXiIXaKuob79A69CgcJbhdsLFn@H5/7yeWeXKx1m0OS5sUlT3OzLTxtFsxOKDevSwzSmF1Z7I4KeCoHgRlXdjNATyUz2q7rwAcPTzAHZmCaUaaQxpVdIjpGYEweBCc1DAOifXPSXwWgMgY9RlRfDCxAAyT8gs@CLIES63bEDCMKw4GUcrTrkLzTlizuhsQTlaj5JC7GE/hMiwY7Af0GitZ/PBfMpxvmSOT/w80dGGtanZfz@775/f5p9w@Xs2nb9rHWen@Mfw "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 1 byte by using `A` as a separator. Note: The deverbosifier claims ~~148~~ 147 bytes, but I believe `¯` (like `ツ`) needs to be encoded using 3 bytes in Charcoal. Explanation: Charcoal can only compress strings of printable ASCII, so the shrug is appended separately.
```
”...” Compressed string
⪪ ¶ Split on newlines
⊞O ¯\_(ツ)_/¯ Push literal string
‽ Random element
Implicitly print
```
[Answer]
# Bash, 269 267 266 264 bytes
-2: [@user42589](https://codegolf.stackexchange.com/users/42589/user42589)
-1: [@nthnchu](https://codegolf.stackexchange.com/users/98932/nthnchu)
-2: [@Nahuel Fouilleul](https://codegolf.stackexchange.com/users/70745/nahuel-fouilleul)
```
q=(Yup "You doubt me?" Of\ course "... did I miss something?" "plz send teh coffee" "Watching this endless list of new questions never gets boring" Kinda\ sorta "You should totally drop that and use jQuery" "¯\_(ツ)_/¯" "... good question");echo ${q[RANDOM%10]}
```
[Try it online!](https://tio.run/##PY7BSsNAEIZf5WdRaC9VzyIieBHRohcpRsomO0lWNplkZ1ep4knfp@/QV/FB4kihx5n5/vn@0ko7TePFbJUHmBVnOM5lQkeXBsu6QMU5CsEsFgs473CDzotAuKPU@r5RzAzhA0K9Q6JWA3VNpNsnm6p/AsoJ9BxIg8FLAtfo6R1jJkmee9HpjSIaSoKSo4YMbn3vbKGimOy@mbScg0o42RA2cJEH/W0TrKqzlnx9yBQ3qt5ti/Xs9/tnvj7Zbc2@fMPsDkYzP6eqZRx9js@PV/fXy7vjs9OXr2n6Aw "Bash – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~294~~ ~~290~~ 289 bytes
Saved 4 bytes thanks to [ErikF](https://codegolf.stackexchange.com/users/79060/erikf)!!!
Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
```
*s[]={"Yup","You doubt me?","Of course","... did I miss something?","please send teh coffee","Watching this endless list of new questions never gets boring","Kinda sorta","You should totally drop that and use jQuery","¯\\_(ツ)_/¯","... good question"};f(){puts(s[rand(srand(time(0)))%10]);}
```
[Try it online!](https://tio.run/##PVBBTsMwELz3FatISDaF0p5DxRlxQJxQ1VaVG29SI8cOXhuoqpzgP/1Dv8JDwqZE9WG1s57ZGbu4rYqi665puZ4fskVqspts4RNon7YRanxg/FxC4VMg5H4ymYA2Gh6hNkRAvsa4M67qeY1FRQiETkPEHYvKEnvRq4pFTwKmEvC1RdZaQxF8CQ4/4T0hReMdMfrAABVGgq0PLGL9k3FasVeIaohHO58su/iorN2DDr7h5SqCYu/EId5eEoY9s0/H1Wojfr9/5ObudBxeUHmvL55Zm5dCHpoUSdAy8AZB5xpNjWIqpbyaTdcybzvj@EuUcUKODiPgU/og@iHnwy@YwzQf2nuYcT8en5GEf/ZZIWR@AWQRGzEbJu2o7f4A "C (gcc) – Try It Online")
Straightforward `rand()` selection from an array of strings.
[Answer]
# [Scala](http://www.scala-lang.org/), ~~278~~ 267 bytes
```
print("Yup#You doubt me?#Of course#... did I miss something?#plz send teh coffee#Watching this endless list of new questions never gets boring#Kinda sorta#You should totally drop that and use jQuery#¯\\_(ツ)_/¯#... good question".split("#")((math.random*10)toInt))
```
[Try it online!](https://tio.run/##PY9BTsMwEEWvMoo3CYsAJ6hYVghVrFClSpUTTxJXjsd4xkBBrOA@vUOvwkHC0AXL0f/z/v/c22AX6g7YCzxYHwHfBKNjuEvpY0nZR6mrbUlmSwUclU5gxpXZDNBTyYymbVtw3sEaZs8MTDPK5OO4Mim8AysLBCd1DwOiebLS/6mgHgYVA@pT8CxAA0R8heeCLJ4i6/WCGUYUho60yGjufXRWI7LYSx@eqATlk9gQjuAyJQVbAauphREOjwXz0ZxPu92@/vn6bvbX59Ol8kjk/rOqllPwOtRUTV3PVqY2K4Lmq9ubRmgdpWmWz@UX "Scala – Try It Online")
* -21 Thanks to [corvus-192](https://codegolf.stackexchange.com/users/46901/corvus-192)!
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~232~~ 228 bytes
```
Yup,You doubt me?,Of course,... did I miss something?,please send teh coffee,Watching this endless list of newqs never gets boring,Kinda sorta,You should totally drop that and use jQuery,¯\_(ツ)_/¯,... goodq
q
question
?S`,
```
[Try it online!](https://tio.run/##HY4xTsNAEEV7n@KXIK2MOIFrlAKhFFEkpLDJju1F6x17ZxaUGu6TO@QqHMQZ0kwz77//C2nM/nldm32d3Z4rAtejYqLOvfY4cS1Crm1bhBjwgimKQHgiHWMeOjcn8kIQygFKowX6nsjtvJ7@ARgmsGciy6UoCu6R6XsRu19UMJAKjlwMdpuYgzd7UX@fIiPXZF5Wn9IZofBsQq/w1lat9vOtUjm76@X98PD38/t4eLpe7mMH5rA0S4Olkmjk3HTbD7euNw "Retina – Try It Online") Explanation: The first two stages replace the empty input with the given string, the second stage saving 4 bytes by deduplicating the substring `question`, while the last stage splits it on commas and outputs a random element. Note that the byte count has been adjusted for UTF-8 (Retina normally uses ISO-8859-1 if it can, which is why TIO only shows the character count rather than the byte count). Edit: I used @Leo's Retina Kolmogorov golfer to detect the duplication and save 4 bytes.
[Answer]
# PHP, 261 253 bytes
-8: Change `<?php echo` to `<?=` ([@nthnchu](https://codegolf.stackexchange.com/users/98932/nthnchu))
```
<?=explode(",","Yup,You doubt me?,Of course,... did I miss something?,plz send teh coffee,Watching this endless list of new questions never gets boring,Kinda sorta,You should totally drop that and use jQuery,¯\_(ツ)_/¯,... good question")[rand(0,9)];
```
[Try it online!](https://tio.run/##PY5NTsNADIWvYnWVSFZgiwBljVggVqgCVE07TjJoMh7GHqBs4T69Q6/CQYLpAnllvZ/v5Skvy1V/TR85sqdmhXbrmnHNFTzXrcJMPd4NsONahLDrOvDBww3MQQSEZ9IppLHHHD9BKHlQmsw9DET44HT3p4J5BEyMZKEYRIEHSPQOr5VEAyex740KjKQCWy4WwtuQvDNEUXfaIxPXaP2sLsY9@MLZip2CM2oVgpf7SmWPx8PTpvn5@m43Z8fDafHI7P9Rq/axWKI5x4v2@XJZfgE "PHP – Try It Online")
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 150 bytes
```
`Yup|λ⍎ řð me?|Of ⟑ₑ|... ¬⁌ I ɾ⟑ ⟇↜?|plz ¬Ĵ teh ʁƛ|←⍋ λ« ⊛⟑ λ′ of λÞ ∨Œ ∨ſ Ô₂ ℅⁑|ₑ¥ °⊛a|λ⍎ ƛð ∺⁂ ɽ∫ λ⟇ λ¬ λʗ jßø|\¯\\_(`12484C+`)_\\\¯|... ƛ∫ ⟇¹`+\|/℅
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%60Yup%7C%CE%BB%E2%8D%8E%20%C5%99%C3%B0%20me%3F%7COf%20%E2%9F%91%E2%82%91%7C...%20%C2%AC%E2%81%8C%20I%20%C9%BE%E2%9F%91%20%E2%9F%87%E2%86%9C%3F%7Cplz%20%C2%AC%C4%B4%20teh%20%CA%81%C6%9B%7C%E2%86%90%E2%8D%8B%20%CE%BB%C2%AB%20%E2%8A%9B%E2%9F%91%20%CE%BB%E2%80%B2%20of%20%CE%BB%C3%9E%20%E2%88%A8%C5%92%20%E2%88%A8%C5%BF%20%C3%94%E2%82%82%20%E2%84%85%E2%81%91%7C%E2%82%91%C2%A5%20%C2%B0%E2%8A%9Ba%7C%CE%BB%E2%8D%8E%20%C6%9B%C3%B0%20%E2%88%BA%E2%81%82%20%C9%BD%E2%88%AB%20%CE%BB%E2%9F%87%20%CE%BB%C2%AC%20%CE%BB%CA%97%20j%C3%9F%C3%B8%7C%5C%C2%AF%5C%5C_%28%6012484C%2B%60%29_%5C%5C%5C%C2%AF%7C...%20%C6%9B%E2%88%AB%20%E2%9F%87%C2%B9%60%2B%5C%7C%2F%E2%84%85&inputs=&header=&footer=)
I decided to use an alternate approach with the new built-ins
]
|
[Question]
[
I remember people saying that code size should be measured in bytes, and not in characters, because it's possible to store information with weird Unicode characters, which have no visual meaning.
How bad can it be?
In this challenge, you should output the following Lorem Ipsum text, taken from [Wikipedia](https://en.wikipedia.org/wiki/Lorem_ipsum#Example_text):
```
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
```
Please specify the number of *characters* (not bytes) in your code. Code with the minimal number of characters wins.
Your code should only contain valid Unicode characters, as described [here](https://en.wikipedia.org/wiki/Valid_characters_in_XML#XML_1.1), that is:
* Code points up to U+10FFFF
* No surrogates (the range D800–DBFF is forbidden)
* No characters FFFE and FFFF
* No null characters (code 0)
If your code cannot be displayed, provide a version with offending characters redacted, and a hexdump.
Some notes:
* The output must be one long line (445 characters). If your system cannot do that (e.g. you're printing it on paper), output a closest approximation. Trailing linebreaks don't matter.
* Built-in functions that generate Lorem Ipsum text are not allowed
* Please specify a valid text encoding for your code, if relevant
[Answer]
# JavaScript (ES7), ~~326~~ ~~283~~ ~~273~~ ~~249~~ ~~243~~ 242 chars
```
_=>"𭙝𧇍"[r='replace'](/./gu,c=>(c.codePointAt()-4**8).toString(32))[r](/\d/g,d=>" , exum. ".substr(d,2))[r](/^.|\. ./g,x=>x.toUpperCase())
```
### How it works
The first step in my compression technique is to convert the whole string to lowercase (not mandatory, but looks better), and replace each pair of chars in `, exum.` (as well as the trailing space by itself) with its index in the string plus 2. This makes the text a valid base-32 number:
```
lorem9ips69dolor9sit9amet2consectetur9adipiscing3lit2sed9do3iusmod9tempor9incididunt9ut9labore3t9dolore9magna9aliqua8ut3nim9ad9minim9veniam2quis9nostrud94ercitation9ullamco9laboris9nisi9ut9aliquip943a9commodo9consequat8duis9aute9irure9dolor9in9reprehenderit9in9voluptate9velit3sse9cill69dolore3u9fugiat9nulla9pariatur84cepteur9sint9occaecat9cupidatat9non9proident2sunt9in9culpa9qui9officia9deserunt9mollit9anim9id3st9laboru7
```
The next step is to convert each 4-char run to decimal, then get the character at that code point. This can be done with the following function:
```
f=s=>s.replace(/..../g,x=>(n=parseInt(x,32),String.fromCharCode(0xD800+(n>>10),0xDC00+(n&0x03FF))))
```
(**Note:** Since all digits are 2 or greater, the minimum possible value of four digits is 2222₃₂. This is equal to 95978₁₀, or 176EA₁₆; therefore, code points will never be in the restricted range.)
And now we have our compressed string:
```
𭙝𧇍
```
That's 445 chars compressed into 106 chars. The decompression simply reverses this process:
1. Convert each char to its code-point in base-32, minus 65536.
2. Replace each digit `n` with `" , exum. ".substr(n,2)`.
3. Convert each letter after a period or at the beginning of the string to uppercase.
The only ES7 feature used is `**`. Replace `4**8` with `65536` to run in a browser that doesn't yet support ES7.
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 123 characters
All but the final period are packed into 111 32-bit characters (UTF-32).
```
'.',⍨80⎕DR'𦽌𲁲𒁴𧕴𖹧𧑳𖥬𦽬𗀠𗑡𧀠'
```
`'.',⍨` period appended to
`80⎕DR` the 8-bit (`8`) character (`0`) **D**ata **R**epresentation of
`'`...`'` the 111 Unicode characters U+**26F4C 9206D D7573 C6F64 32072 12074 C7465 E6F63 46365 27574 96461 37369 10676E 4696C 57320 F6420 56965 46F6D D6574 10726F 9636E 56469 52074 16C20 5726F 107465 F6C6F D2065 16E67 96C61 E6175 107455 D696E 106461 96E69 57620 D6169 57120 E2073 27473 52064 37265 46174 106E6F 16C6C 106F63 F6261 107369 97369 107475 1696C 107069 52078 F6320 46F6D F6320 16573 E7461 97544 56120 92065 57275 C6F64 92072 57220 86572 5646E 107469 6206E 10756C 57461 C6576 52074 106573 C6C69 4206D 26F6C 56520 77566 107461 C6C75 17020 46169 102E72 56378 56574 97320 F2074 56163 107461 97075 17461 F6E20 27020 56469 102C74 46E75 106E69 106C75 57120 66F20 96369 56420 57265 D2074 96C6C E6120 9206D 36520 16C20 5726F**, which all fall in the range 12074–10756C and thus inside the OP's all-permitted range 10000–10FFFF.
[Answer]
# bash + coreutils + gzip + recode, 191 characters
```
echo -ne "ᾋࠀ㰟퍗\03㖐셱䌱ࡄ戋⪒宮⦀⃬〣ख़ʏ쬏湂삲מּ浊莎ᔍ얪䴬畐Ꮏ肭⽡តप㩴뇶ᮤ樶鞔岀梬昅盖ꈥ먣Ვ빓ỢꞴꃑ괓꣪㷨삗䎺뛔䛓ﵸ摉篨䊷⦓헉픺ꉖ橬ꟲỒꗻ퉋則ใ⢍럴摧耼⒅୴䘺㦳櫇鐱窑駁愵䚞鎴鍉Ⅻक़毽➔脂ힸ⤹喝葁㎋頇㺞ⳃ┶왤惌⒜猜䌋吏젔掚ᛩ鯢⚕䜹鴛皽⨫ꇈ銹믍䄛逦軵융杻龇븁\0"|recode u8..utf16be|tr -d ٣ܣ|gunzip
```
The string is the gzip of the text interpreted as UTF-16BE, plus a few extra bytes to pair with the unpaired surrogate halves. The tr strips off the extra surrogate halves.
This script file (or the shell into which this command is typed) should interpret text as UTF-8, which is why the recode is needed.
[Answer]
## Javascript (ES6), ~~261~~ ~~255~~ 254 characters
*Saved 1 byte, thanks to ETHproductions*
```
_=>'L'+"⫒㠰拳䨒堵̎⨦W䙨ⅶ嵷˘㥆姳䗨⠬巯堡Ŋɩ懪䨶尩个˒≎㥎䜩怷㰷䤆ŵ̊㹩⫒ᨠᩌ㳠抮f̅㩊ᠰ䀩㩎搰㩊ئ抠ˮ婱拗⠩啺巨㬆ɒ㸘∦㰲䤆姵㩀Ƕ̘㨆㬴⠳⠺…䈲䥒䤠⫱᬴w㬣ᠶ⬘嗠⫘䥀噯䗠⫀⫓䕭啩̎Ɏ㹹庘⬆⭀巯奠Ŷ㷨䌯䥀噯⠪ⰸ㦸̆㼱ï哳峮梠䵨慷堵幎≠⣨峨愠◳ᬆ䐷ɒ䫓⥎ܑ拠̑Ɏ㼨ó㬴⇫î奩拊̑㹰巯䓠ȮŎ廪ᨀ噧ਸ".replace(/./g,c=>(s=" ,.DEUabcdefghilmnopqrstuvx")[(c=c.charCodeAt()-32)&31]+s[c>>5&31]+s[c>>10])
```
### Breakdown
Payload: 148 Unicode characters
Code: 107 bytes
### How it works
We first remove the leading `'L'` from the original message so that we're left with 444 = 148 \* 3 characters.
Without the leading `'L'`, the character set is made of the 27 following characters:
```
" ,.DEUabcdefghilmnopqrstuvx"
```
Each group of 3 characters is encoded as:
```
n = 32 + a + b * 32 + c * 32^2
```
where a, b and c are the indices of the characters in the above character set.
This leads to a Unicode code point in the range U+0020 to U+801F, ending somewhere in the "CJK Unified Ideographs".
```
let f =
_=>'L'+"⫒㠰拳䨒堵̎⨦W䙨ⅶ嵷˘㥆姳䗨⠬巯堡Ŋɩ懪䨶尩个˒≎㥎䜩怷㰷䤆ŵ̊㹩⫒ᨠᩌ㳠抮f̅㩊ᠰ䀩㩎搰㩊ئ抠ˮ婱拗⠩啺巨㬆ɒ㸘∦㰲䤆姵㩀Ƕ̘㨆㬴⠳⠺…䈲䥒䤠⫱᬴w㬣ᠶ⬘嗠⫘䥀噯䗠⫀⫓䕭啩̎Ɏ㹹庘⬆⭀巯奠Ŷ㷨䌯䥀噯⠪ⰸ㦸̆㼱ï哳峮梠䵨慷堵幎≠⣨峨愠◳ᬆ䐷ɒ䫓⥎ܑ拠̑Ɏ㼨ó㬴⇫î奩拊̑㹰巯䓠ȮŎ廪ᨀ噧ਸ".replace(/./g,c=>(s=" ,.DEUabcdefghilmnopqrstuvx")[(c=c.charCodeAt()-32)&31]+s[c>>5&31]+s[c>>10])
console.log(f())
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 319 [bytes](http://www.cp1252.com/)
Uses CP-1252 encoding.
```
•9y†QHÚSe²ŒÓdéÓ#ǧÖN›Íˆž4GÏóREØån‡·JîÁØ£ÎÁ¥evÑRZ¶—¥1RËÒÆzçå"UNé¨v¯ÊcŒÔÝjðtrœÛeã&“SÁxÌ4Þá1N$ù?T(çÛbŸœfó˜lUž}Þß-©ÃMšBÈÑPàê#jÇÐ+n¼BDFý>–¸äFT×›qÜY³ö9ªòËùˆA‡¾p=‘¤ÚÞ{I¶Œ±Ål#¨5´Aq˜Àž,s<*Ï;‡õã¾»ðŽL´ÅuØö+Xi+S>»/8Kã~WΔƒß”¤µðWluØa'cUÐeà¥ä…ž+œ6*0RU£›aÝQ_ñœoþÏð””Þã7ã¨sŒV`_É-´éÄèÆd¦úE5Í^Aá,‘‡™™¢äTHä0¥3±.}Søg•36B0„. :™J'yð:'z',:'.«
```
**Interpret the following string as a base 36 number and encode into base 214**
```
LOREMYIPSUMYDOLORYSITYAMETZYCONSECTETURYADIPISCINGYELITZYSEDYDOYEIUSMODYTEMPORYINCIDIDUNTYUTYLABOREYETYDOLOREYMAGNAYALIQUA0UTYENIMYADYMINIMYVENIAMZYQUISYNOSTRUDYEXERCITATIONYULLAMCOYLABORISYNISIYUTYALIQUIPYEXYEAYCOMMODOYCONSEQUAT0DUISYAUTEYIRUREYDOLORYINYREPREHENDERITYINYVOLUPTATEYVELITYESSEYCILLUMYDOLOREYEUYFUGIATYNULLAYPARIATUR0EXCEPTEURYSINTYOCCAECATYCUPIDATATYNONYPROIDENTZYSUNTYINYCULPAYQUIYOFFICIAYDESERUNTYMOLLITYANIMYIDYESTYLABORUM
```
**After that we**
```
36B # encode back into base 36
0„. : # replace 0 with ". "
™J # convert to titlecase and join
'yð: # replace "y" with <space>
'z',: # replace "z" with ","
'.« # add a "." at the end
```
For some reason the encoding didn't work with a 0 at the end which is why need a special case for the final ".".
[Try it online!](http://05ab1e.tryitonline.net/#code=4oCiOXnigKBRSMOaU2XCssWSw5Nkw6nDkyPDh8Knw5ZO4oC6w43LhsW-NEfDj8OzUkXDmMOlbuKAocK3SsOuw4HDmMKjw47DgcKlZXbDkVJawrbigJTCpTFSw4vDksOGesOnw6UiVU7DqcKodsKvw4pjxZLDlMOdasOwdHLFk8ObZcOjJuKAnFPDgXjDjDTDnsOhMU4kw7k_VCjDp8ObYsW4xZNmw7PLnGxVxb59w57Dny3CqcODTcWhQsOIw5FQw6DDqiNqw4fDkCtuwrxCREbDvT7igJPCuMOkRlTDl-KAunHDnFnCs8O2OcKqw7LDi8O5y4ZB4oChwr5wPeKAmMKkw5rDnntJwrbFksKxw4VsI8KoNcK0QXHLnMOAxb4sczwqw4874oChw7XDo8K-wrvDsMW9TMK0w4V1w5jDtitYaStTPsK7LzhLw6N-V8OO4oCdxpLDn-KAncKkwrXDsFdsdcOYYSdjVcOQZcOgwqXDpOKApsW-K8WTNiowUlXCo-KAumHDnVFfw7HFk2_DvsOPw7DigJ3igJ3DnsOjN8OjwqhzxZJWYF_DiS3CtMOpw4TDqMOGZMKmw7pFNcONXkHDoSzigJjigKHihKLihKLCosOkVEjDpDDCpTPCsS59U8O4Z-KAojM2QjDigJ4uIDrihKJKJ3nDsDoneicsOicuwqs&input=)
[Answer]
# PHP ,247 Characters
combination of the 2 previous versions
```
echo gzuncompress(base64_decode(mb_convert_encoding("敊眱歍䙸兺䕉剆癚䅪礯極南慷潧楏㡷䥷汚䅯⽌䐸灐扫䱁獶猫扅煄橨啎硡灎䱈噑䔷⭂牓㥨䘴㡊䭪瀰獦夷灇漲氵剣杇楳婧啵扥卹摴慩䩢潪䡊圫啨㝩氷卧ぢご煏潪㙍䍮儷焲ㅅ扔⽘桭卥㉇别桃琫啺䍵公欹塊ㅔ煩噭灳氯䥥ぱ堷ぱ⭫橨祇啂灶㙣浵䅈湋䐷硴卑潘㙉砰捭塖橩汪祲昰䥪佄㔸晔慯眸䨲歮欰䱗䕲䑗⭫㡯䅷塏畃猵⭪慅兔佌流晥塹穄䩔扇婇䑍䩊硺䡅䵌⭤㝉䙇佡䙵浢㑩慖剺湱潊ぢ摰㝋卩楹婏㕵猷灴ぁ慫楗倹捙ㄲ⽁䍧塋啊","UTF-16")));
```
PHP, 261 Characters
```
echo mb_convert_encoding("䱯牥洠楰獵洠摯汯爠獩琠慭整Ⱐ捯湳散瑥瑵爠慤楰楳捩湧汩琬敤漠敩畳浯搠瑥浰潲湣楤楤畮琠畴慢潲攠整潬潲攠浡杮愠慬楱畡⸠啴湩洠慤楮業⁶敮楡洬ⁱ畩猠湯獴牵搠數敲捩瑡瑩潮⁵汬慭捯慢潲楳楳椠畴汩煵楰砠敡潭浯摯潮獥煵慴⸠䑵楳畴攠楲畲攠摯汯爠楮数牥桥湤敲楴渠癯汵灴慴攠癥汩琠敳獥楬汵洠摯汯牥甠晵杩慴畬污⁰慲楡瑵爮⁅硣数瑥畲楮琠潣捡散慴異楤慴慴潮⁰牯楤敮琬畮琠楮畬灡ⁱ畩晦楣楡敳敲畮琠浯汬楴湩洠楤獴慢潲畭.","UTF-16");
```
Encoding $s contains the string
```
foreach(str_split(bin2hex($s),4)as $c)eval('echo"\u{'.$c.'}";');
```
Old Version PHP , 386 Bytes|Characters
```
echo gzinflate(base64_decode("NZDBcUMxCERb2QI8v4rklmsKIIjvMCMJWQKPyw/KT25CwLL7PmxKg44VDcWqTSx1UBO/ga0vYRePCSo6dLH2O6RqNpeUXIBorGYFLm3ksnbWoiW6IxyVvlIe4pe0oNG9E6jqI+jAp0O6ttRG0/14ZknthkfoQrflMwrkJZPVydU6olZqbJfyHtKl+9KvpI4chlAab+nJrgB5yg+8bUkKF+iMdHJl1Y4pY8q39CIzg+fH02qMPCdpJ5NC1hKw1vpPKAMFzrgrOfo2hEEzi5gH3l8swyU2xmRgzCSccxxDC/neyBRjmhbpm+ImlUc56qCdG3aeykoosmTubrO6bdAGpIlj/XGNdvwA"));
```
[Answer]
# C#, ~~337~~ ~~333~~ 331 characters
```
_=>{var q="";foreach(var c in"潌敲彭灩畳彭潤潬彲楳彴浡瑥弬潣獮捥整畴彲摡灩獩楣杮敟楬ⱴ獟摥摟彯楥獵潭彤整灭牯楟据摩摩湵彴瑵江扡牯彥瑥摟汯牯彥慭湧彡污煩慵弮瑕敟楮彭摡浟湩浩癟湥慩Ɑ煟極彳潮瑳畲彤硥牥楣慴楴湯畟汬浡潣江扡牯獩湟獩彩瑵慟楬畱灩敟彸慥损浯潭潤损湯敳畱瑡弮畄獩慟瑵彥物牵彥潤潬彲湩牟灥敲敨摮牥瑩楟彮潶畬瑰瑡彥敶楬彴獥敳损汩畬彭潤潬敲敟彵畦楧瑡湟汵慬灟牡慩畴ⅲ䕟捸灥整牵獟湩彴捯慣捥瑡损灵摩瑡瑡湟湯灟潲摩湥ⱴ獟湵彴湩损汵慰煟極潟晦捩慩摟獥牥湵彴潭汬瑩慟楮彭摩敟瑳江扡牯浵ਡ")q=q+(char)(c&255)+(char)(c>>8);return q.Replace("!",".").Replace("_"," ");};
```
*-4 characters by replacing the `.`s after "pariatur" and "laborum" with `!` before combining the chars to wide chars and adding a trailing new line.*
*-2 characters by re-assigning the output var rather than appending with `+=`.*
How it works:
The lorem ipsum string was converted to that mess by replacing `.` with `!`, with `_` so when the ascii chars are placed next to each other to make a wide char each wide char is a single character.
```
/*Func<object, string> Lorem = */ _=> // unused parameter
{
// Output var
var q = "";
// Enumerate each wide char
foreach (var c in "潌敲彭灩畳彭潤潬彲楳彴浡瑥弬潣獮捥整畴彲摡灩獩楣杮敟楬ⱴ獟摥摟彯楥獵潭彤整灭牯楟据摩摩湵彴瑵江扡牯彥瑥摟汯牯彥慭湧彡污煩慵弮瑕敟楮彭摡浟湩浩癟湥慩Ɑ煟極彳潮瑳畲彤硥牥楣慴楴湯畟汬浡潣江扡牯獩湟獩彩瑵慟楬畱灩敟彸慥损浯潭潤损湯敳畱瑡弮畄獩慟瑵彥物牵彥潤潬彲湩牟灥敲敨摮牥瑩楟彮潶畬瑰瑡彥敶楬彴獥敳损汩畬彭潤潬敲敟彵畦楧瑡湟汵慬灟牡慩畴ⅲ䕟捸灥整牵獟湩彴捯慣捥瑡损灵摩瑡瑡湟湯灟潲摩湥ⱴ獟湵彴湩损汵慰煟極潟晦捩慩摟獥牥湵彴潭汬瑩慟楮彭摩敟瑳江扡牯浵ਡ")
// Split each wide char into two ascii chars
q = q + (char)(c&255) + (char)(c>>8);
// Restore the replaced periods and spaces
return q.Replace("!",".").Replace("_"," ");
};
```
[Answer]
# ISOLADOS, 44016 bytes
<http://pastebin.com/raw/Y2aAhdpi>
Push the ASCII code for every character in the Lorem Ipsum string, concatenate everything, and output.
[Answer]
# [MATL](http://github.com/lmendo/MATL), 354 characters
```
'8 sxAI($ltZ>2<xa`vYf:s2e9]c&^KtD%e{C*XEpQ]]>dwmi>2;{sUCIZ{V(}Yj 7K&)|,%JD/Pz^:3$*@vVJw)4pgvz4s_$,%pVGu~|PS/Qr7pz5Z2[VV{Lyq}{l!yGiKNg.zFJxL75 sT1]eL2f3iVe~11!|6c+O9.kMWFQYvEp^w0p oH,?Ey"nbV>0g`#)kqTq""" z_AYmyJutvg:o9&AT{#(<42wu.b7" QoOn\#])]ISdH$yc{eM> .[~/`"#2:7C4Mk@eRW8L*_!xjo\cO)!LHK=g:P?&Uc];KdnE(%K7J-z9:7&rhxHl/KZ8\t_C|rT#%28[%+#u.?'F2Y2' ,.DEL'hZa
```
This decodes from base-94 (using the printable ASCII chars except single quote; so only Unicode characters up to 126 are used) to the alphabet of required characters, formed by most lowercase letters, some uppercase letters, space, comma, and period.
It takes a few seconds in the online compiler.
[Try it online!](http://matl.tryitonline.net/#code=JyU5PmQiX300c1BzZEIrZU1uI3F5bzElS1ExZDc3VkhGeTY0JEUoPXhOYiRXTHZvTWlcbnNyVHcjKyJrR0tkYE51XD1VZWlefXJaU3EiYS1LLnZ7T3YwNG84bTw5fD5wUiIzeHMsVFkldk5bYGAgSCh8IE8heFxlMFoydnMzYm86dSgwNmRrJiR6JSA_JCVVPW0sPTpXJWp8KEVAKCVhNk0qP30xU2pCMz1VYmZHLjQ0c2orLmcmbjYiSEg7RUcxZFI6d11pQ31WYEZAKnFwNnR3RVJgVyJ6al86LjMuTkxGLUVGSVBsUjxIcjBYZ2slV1tiTigqeyAkOT5OYCg4IztMeildK0ZNdkB1flIrQGlaN119SDVMOm1EOHBPWU4qYVIhZC41UVJ-OUhSIyJjLy8tfTs0e15ENTRiWXd-IWB1dHlNXWBNbCdGMlkyJ2prd3l6J1gtJyAsLkRFTFUnaFph&input=)
[Answer]
## JavaScript (ES5), 342 characters
```
c="remo ipsudlta,cngbq.UvxDhfE";"L"+"Qq©Úu[Qsx7Ķz`¾ƅ&Øxø§Ëƴ%ţ¾÷öm¿Zw¥ſøûƠtĭĚǎmĭöđnŔơxēǮŗĭ*x÷;ƚ:ȸƚņţǮ{XĩámɓŏƙâĚDUĚǎÁƚÂtĭŎݦ1mňŽ8ZUŽƜ-äļÝÁŌĪqu[Qqƙ¢3*ôĭ[ÞĵĪ%mÄſĘÚu[Q#èĭƝĘň®ŏØȅ˔Ż#ÂƠoƈŅƆĭƂ§ÿĵĭƘƙ¢VôƠţÅƠqƙƂĔňǮjʨſňô¾Ơn[ēĭœq÷\"ĭĚǎI".split('').map(function(x){y=x.charCodeAt(0);return c[~~(y/27)]+c[y%27]}).join('')
```
Pretty straightforward, so I'm sure there's room for improvement. I encoded every pair of output characters as a single Unicode character.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 279 bytes
```
«;Jq×L↑yVx₅QȯZ3ẎhȦ¼_ø€ẋ°Q±3₀₈∑hṁ₃ø∧≤∆⌐>ʀ↵₌X⇧ƒ₀₆ḃ₅Ḣ~^9\6↓¾<₆≈Q‡‟ṄBḞUß¼ƈv→⟇ʀ7ė⟑∞~*Ṅ∩ꜝtW₴h⟨p&¥z%₇Jɖ⁋¥(₂⌐⌊mṖ⅛ɾṙ3±żð→Ṙq↳'ḭguIH?TLŻrhNɾwl꘍×ByÞkĿMτI□ǑΠȧ½Ḃ≬jȦ₂ṡ⇧j…0Ȧ₂wyẆ₈≠₂d„⟨>∵↔C7⟇≠∑¤ƈƛiḃṁ₍Q]*꘍ṡḂcu%İ∑lL5∧∴!qÞLOτxÞ≥€ṅQh₅Ṫ°₄B*ṫṘ:NḊεβ⋏ṫẎFpƈc⁰ŀqẏy↓{'Ǒ£ẏŻ@kżoƛg)K1cV⌈»ΠC¼⟩F^ȯ₌«\z‛. V‛ ‛, V¡
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C2%AB%3BJq%C3%97L%E2%86%91yVx%E2%82%85Q%C8%AFZ3%E1%BA%8Eh%C8%A6%C2%BC_%C3%B8%E2%82%AC%E1%BA%8B%C2%B0Q%C2%B13%E2%82%80%E2%82%88%E2%88%91h%E1%B9%81%E2%82%83%C3%B8%E2%88%A7%E2%89%A4%E2%88%86%E2%8C%90%3E%CA%80%E2%86%B5%E2%82%8CX%E2%87%A7%C6%92%E2%82%80%E2%82%86%E1%B8%83%E2%82%85%E1%B8%A2%7E%5E9%5C6%E2%86%93%C2%BE%3C%E2%82%86%E2%89%88Q%E2%80%A1%E2%80%9F%E1%B9%84B%E1%B8%9EU%C3%9F%C2%BC%C6%88v%E2%86%92%E2%9F%87%CA%807%C4%97%E2%9F%91%E2%88%9E%7E*%E1%B9%84%E2%88%A9%EA%9C%9DtW%E2%82%B4h%E2%9F%A8p%26%C2%A5z%25%E2%82%87J%C9%96%E2%81%8B%C2%A5%28%E2%82%82%E2%8C%90%E2%8C%8Am%E1%B9%96%E2%85%9B%C9%BE%E1%B9%993%C2%B1%C5%BC%C3%B0%E2%86%92%E1%B9%98q%E2%86%B3%27%E1%B8%ADguIH%3FTL%C5%BBrhN%C9%BEwl%EA%98%8D%C3%97By%C3%9Ek%C4%BFM%CF%84I%E2%96%A1%C7%91%CE%A0%C8%A7%C2%BD%E1%B8%82%E2%89%ACj%C8%A6%E2%82%82%E1%B9%A1%E2%87%A7j%E2%80%A60%C8%A6%E2%82%82wy%E1%BA%86%E2%82%88%E2%89%A0%E2%82%82d%E2%80%9E%E2%9F%A8%3E%E2%88%B5%E2%86%94C7%E2%9F%87%E2%89%A0%E2%88%91%C2%A4%C6%88%C6%9Bi%E1%B8%83%E1%B9%81%E2%82%8DQ%5D*%EA%98%8D%E1%B9%A1%E1%B8%82cu%25%C4%B0%E2%88%91lL5%E2%88%A7%E2%88%B4!q%C3%9ELO%CF%84x%C3%9E%E2%89%A5%E2%82%AC%E1%B9%85Qh%E2%82%85%E1%B9%AA%C2%B0%E2%82%84B*%E1%B9%AB%E1%B9%98%3AN%E1%B8%8A%CE%B5%CE%B2%E2%8B%8F%E1%B9%AB%E1%BA%8EFp%C6%88c%E2%81%B0%C5%80q%E1%BA%8Fy%E2%86%93%7B%27%C7%91%C2%A3%E1%BA%8F%C5%BB%40k%C5%BCo%C6%9Bg%29K1cV%E2%8C%88%C2%BB%CE%A0C%C2%BC%E2%9F%A9F%5E%C8%AF%E2%82%8C%C2%AB%5Cz%E2%80%9B.%20V%E2%80%9B%20%20%E2%80%9B%2C%20V%C2%A1&inputs=&header=&footer=)
Uses Vyxal base-255 encoding, since it can only do lowercase and space, I convert ". " to z and "," to " ", so when I decompress I can easily add back in the punctuation. Finally, it reintroduces uppercase through the sentence-case operator.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 139 UTF-8 characters
```
"EDUL ,.".z@:^A*"𝜋𦕪𢪤𤣨𖢋𧅴𥽯𢚳𢚴𡽺𦅶𢽤𥣸𦗴𥊴𥬕𥽯𥖌𢥹𡺏𢼺𤣨"TB32FB:32
```
[Try it online!](https://tio.run/##LZG9bttAEIS7PEegMghc2J2rxEhSpUza9Olcp4plEgRJU4QonQTqh4COpBgxkoWYNKU76vhIwe7tAygXwNUWOxjMN3P7/fZ87n388PXz67cXvYsf766/vX/Tg@XC17HT0EBkyGJGdw97Gt5XmPAMg1mMs6VPk5MFsmiwG@91Gvl6pGxYsxJ4meFcCb1kFkWi0Y/9UPNpiXJX0zCQkKW/9KOdGS9Pb8sjxm6Bu/sMTsWB4sqCCfd1KjKQfITKqaCwaxQih1ztyfUYDbZzHNodJpbJpEK968/1OK0wiCKQ3hG7aIzdNKOEO3rUtqi4T3/sAvisMpmYuTV5bQtdav09CFgpibFzpMR@QXVqWNsN9Q@@5rmx46FeDZietDPo8oy4CGloC/KeXDxt5jq2mWYLH7jKcN3soeNjWmwcyNMjCjWnO/6TnlhDkTrCemoq8DboPm@MzqVlUZoYEnKvhnzLUObmH8W0DCxUfZcWv53/2JBPHlBODUIuMAmMxn3W40LCSoZmJlP56aXWoHrV@3Jzdfnp5vrq8nz@Bw "Pip – Try It Online")
### Explanation
Observe that there are 28 distinct characters in the string. We can use characters up to character code U+10FFFF = \$1,114,111\$, and since \$\sqrt[4]{1,114,111} \approx 32 > 28\$, we can pack four Lorem Ipsum characters into one Unicode character. (In theory, we might run into some forbidden characters within that range. In practice, that didn't happen.)
The decoder is a little longer than it should be because Pip's builtin base conversion generates strings (e.g. `"1RFP"`) rather than lists of numbers (e.g. `[1;27;15;25]`).
```
"EDUL ,.".z@:^A*"𝜋..."TB32FB:32
"𝜋..." String of 112 Unicode characters
A* Codepoint of each
TB32 Convert each to a (4-digit) base 32 number
^ Split each base 32 number into a list of its digits
FB:32 Convert each digit from base 32 to an integer
@: Use those numbers to index into
"EDUL ,.".z Character lookup table: "EDUL ,." plus lowercase letters
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 126 characters
A large integer is encoded in base 1114111, which is converted to custom base `" .,a..z"` and the resulting string is converted to sentence case.
```
"𦛭𝌱𓏃功𗼵𘟅剗儮𝔐𨸞𢠑𣽖"ÇćβA… .,ìÅвJ‡.ª
```
[Try it online!](https://tio.run/##BcHLjppQGADgV2lm3cw7dNu36CRddNVFX0C8AIKICIiKwsh4mQFFRfEgiiS166aP0Ezitjn/f87eft/3H1@evn293x@4XpZ/oxQn@hDll4wZmwHdlws6d1cgulM6bm1BITJXAoerdQn9jY3qfkRNvcaexwlmaYRdu/3PG9K1IcFoRiiRPOaSkIuzGI47D9Nwzi6WQFMpgqLxelN8HE0yqPtt6pxTdmkFUN0cWSvRYZucIQ9NMMga5WJB@36DLe0E5g65NR0QXI25asDblsLO29qtHuPRUnC6TFDWm1wPYjq2OizMmqw/HoCWn3glL7l@yNEw3nCaH1DeDVk2EEHMdF4b9UE4VnFYKEyJMswHKVpOQnvCAOzGlr5mHga@gjqxWGdmouxtMC9ESNQFrPMzrlQb8vmBy9GKTUd9mpoyLaolJX6MQbdglyinwbOBptDCi69RTyu5lp5Y3D9hRrqwc94gqodMFgXoHALMtZhXbBeMnsFEsqEvRQ@G8YW1vD3WVJ0VZPpwlX5Jv5NP75X5h8eP1@W18Sf5/F6ZPP4M7/f/ "05AB1E – Try It Online")
Or, with byte scoring:
# [05AB1E](https://github.com/Adriandmen/05AB1E), 277 bytes
```
.•Jã‘éLõÝåʒ?ÿU
¤Ú¹αšt\Žαæ™4c\’ÑÑ[Ï!îèιáܶ§:ºÃbxxQΩù2ú²º„¶₄êy³Ôá‚ιüá‚ÖÆjηatÜÿ˜≠²Ÿ‹»BˆAÇλ—W?üÿ¾TP׸˷]Δ…È¶ª¢X9ât稒ƶövY∞ʒE¯Š¿[¹|εÔgƵΣCõ÷yʒĆ7hZ`ĀÀAFнúO¡]îγĬ-Ðu†₂≠т,ÜÞör,™¨}м!s±ÑH—‘DθwO³¦&‚ÚøγF∊6∊7p×Ì"₄ôʒÛ₅,ÿɽOϦÃ9-p¦»:nÒƶÙØ¶∊[₁?θsÑK„³½ζp÷‰oæB¤|λ·(θŒ¨”∍∊₄=Ýá¾ÉĆΓΓŒ*›αβ™•„wy„.,‡.ª
```
[Try it online!](https://tio.run/##HZFdTxNBFIbv/Rd4YYwpvTBGAglpQCVGTaqJxo9CIhjjx4U0tgpNMBmXWlvUYJdGoJamW3ApjUHbtbvblrLJebtclGQCf@H8kTrlYiZzcc6c53nPfGx27tXzfj/IonwL2yw2sHcHDWzhV08PwXtwjnaQp6as@UZ82u/IGkxOlq88m2axiSyyEawOYR8V2YSBAtm0O0YtLM8tLt6Te2heRovq1GJRJJu1JKoJspCDwSKvOg7OHviB1GvpzMZRgHdc4EyJ6r7LokntyePUBD7LNovcw5Aq9@jw/l2sk4sv5MzIHAsTaTW0SuVHoyjHsUsVBXZkw37/mNPFnn6D/vgl8iLUXJIN5F4cNeT2NSXoJHp6NzXy8snTroCYmDrpoBUmYwb70kKSfg/j@zsWJdY0xXOqBRRbEfbbgJKnyoeTg6EY1ZC9qcBUZteluxAmi8wLA508XGlNcXrlqjojUazj6/mB@7@ejp@sfQrAQ4Y6YaySieXR4SiZ1B57A11hb2JDBZVeibD2MSTdGLK3B9lZ1JF2FA6Lv/MwJ2lnSbbJuShdXx8Ib3H6m2pSQ8bV5gw6RKabkmtyzdcvsWjJmqwrbrVi9ddCQl3BAAsjSNV@/z8 "05AB1E – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 300 chars
```
“ḊḄr⁷ƤⱮx#y&Ọ¬½ẇṾƤẋRṠỊ/IṗIÞƝỊż,CA~ñ;ßɦ4ṿḷNVẸẆ`°ṄjJ⁽Ɱ!Æḋ"uƒ⁽ƙfƈÇœƓ®ḶẓƭƊȮ⁻w}Ġṙ(1€CÐ-ɼ#ȯjėȮoZœ°ȥạ_ẊƊaʠiẸṂṪẒ$ċⱮiẹOṠBṇḲ^*GƓŒA>żıWṭƤe&ėẠF6³ṂḲzlçÇṪġṂŻỵḢ⁴WJC⁽Ỵihıỵṃ¥ẏƬEỴ⁽#ḍʠḢ*^O[4)ỵZ5VoPĠƘṙḅß]<œ/ṅẸ% ḍ"Ɱ+¢¦ß÷⁵Ḍ³Ṅ¶2X|©dċÆṁḢƭṗM°`KǦɗỤɱṆȯƘkṅbṙ⁻l<t,ḟȮạżæ€ṠṣIȥCṘƥṁ©53ẒþØŻṁ£æƥ?¬ṿFæṘ⁴nụ’ṃ“Lrem ipsudlta,cngbq.UvxDhfEo
```
[Try it online!](https://tio.run/##FVJdTxNBFP0rSJUoVokIvkg0WMEUVIyJYDAiIEVaK1UEBaOGxdKaLUbTfWibqF2guwbSli4indktkMzsTrb8i7t/pN59vGfO3PMxE4vE4yutlrf6E4gMJLngSXVR8ozqcmClA6wNVmZHYKaBHosSmJmHQFWw5K4w0FyY/xa/cHAawVD/Z25c58Wm3gP0BEj9/iiYBMzUJKsBTcaGPOkId57hKSCZ9iWRxVkUZsVXnnYUobAqkEMwFVERslv1JOv9J1sFWjh/xVsrh/iPS81GwN2L2Tm3mhh3FFZzNTA3n4EpC3nqVI36WnQN6C6Y2bN2BpUQoiPo9RbQNJD9ic47QnGy/Techm2MAa2IUqTDzoGpDl5jf/27ZP9DnP/hGHTX3kTAscD6B2TLkw7GhkJoF6yD6Jxt@Cj9wlD/uygPIIhHASDfTlUkd06MPOm5gJTx3tHEA1sVeQwBZJ0Xn/Y5ShfQdXR6rg3p7ejxIttiOi/yuieh0obvI8kOux9/ZDszdgarohLuFBWs@h6rTQ7zNNObObBKTQNoyt0T@Ze4cRolsLF432IQSNGtYjFOg@tYnP9UdDvsaiGgeaHhOrbTexUr4sc8j/lw3ua60G4ypJ4Mch1pGHceLM1bLWBK/BR3FyKv2qKv3y7NxBengs/nX0y/ufzo3fLtudmBRKv1Hw "Jelly – Try It Online")
The encoding is [Jelly](//github.com/DennisMitchell/jelly/wiki/Code-page).
Thanks to compressed strings, I was able to compress it by 3 bytes.
[Answer]
# Deadfish~, 3209 bytes
```
{{i}ddd}iiiiiic{iii}iiiiiciiic{d}dddc{i}ddc{{d}ii}iiic{{i}ddd}iiic{i}dddciiiciic{d}iic{{d}ii}iiic{{i}ddd}ddc{i}icdddciiiciiic{{d}ii}ddc{{i}dd}iiic{d}c{i}ic{{d}ii}ddddc{iiiiii}iiiiic{i}iic{d}iic{i}iiiiic{{d}iii}ddc{d}ddc{{i}ddd}dddc{i}iicdciiiiic{d}ddddcddc{ii}dddc{d}dddddc{i}iiiiicicdddc{{d}ii}ddc{iiiiii}iiiiiciiiciiiiic{i}dddc{d}iiic{i}c{d}ddddddciiiiiiciiiiic{d}iiic{{d}iii}dc{{i}ddd}dc{i}dddcdddc{i}ic{{d}iii}ddc{d}ddc{{i}dd}iiic{d}ddddcdc{{d}iii}iic{{i}ddd}ddc{i}ic{{d}ii}ic{{i}ddd}dciiiic{i}iicddcddddddciic{d}dc{{d}iii}iic{{i}dd}iiiic{d}dddddc{i}ddciiicdciiic{{d}ii}ddc{{i}ddd}iiiciiiiic{d}dciiiiiicdddddciiiiicdddddc{ii}dddc{d}iiiciiiiiic{{d}ii}ddddc{{i}dd}iiiiicdc{{d}ii}ddddc{{i}ddd}iiiiiic{d}dcic{i}iiiciiic{d}dddc{{d}iii}ic{{i}ddd}dc{i}iiiiic{{d}ii}ddddc{{i}ddd}ddc{i}icdddciiiciiic{d}dddc{{d}iii}ic{{i}dd}dddc{d}ddciiiiiic{i}dddc{d}dddc{dddddd}dddddc{iiiiii}iiiiic{i}icdddc{i}ddciiiic{dd}c{ddddd}dc{d}ddddc{iiiii}iiic{iii}ic{{d}ii}ddddc{{i}ddd}dc{i}dcdddddciiiic{{d}ii}iiic{iiiiii}iiiiiciiic{{d}iii}iic{{i}dd}dddcddddciiiiicdddddciiiic{{d}ii}iiic{{i}dd}iiiiiic{dd}iiic{i}dcdddddc{d}iic{i}iic{dddddd}dddddc{d}ddc{{i}dd}iciiiic{d}ddc{i}c{{d}ii}dddc{{i}dd}ddciciiiicicddciiic{dd}iiic{{d}iii}iic{{i}ddd}dc{ii}dc{dd}ic{i}iiic{d}dddddciiiiiic{i}ic{dd}ic{ii}dc{d}dciiiiiicdc{{d}ii}iic{{i}dd}iiiiic{d}icc{d}dc{i}iic{d}c{i}iic{{d}ii}ic{{i}ddd}iiiiiic{d}dcic{i}iiiciiic{d}ic{i}c{{d}ii}dddc{{i}dd}ddcdddddc{i}c{d}c{{d}iii}dddc{{i}dd}iiiiicdc{{d}ii}ddddc{iiiiii}iiiiic{i}icdddc{i}ddciiiic{d}ddc{i}dddc{{d}ii}c{{i}ddd}dc{ii}dc{{d}i}iic{{i}ddd}dcddddc{dddddd}dddddc{{i}ddd}dddc{i}iicddcciic{d}dc{i}ic{{d}ii}ic{{i}ddd}dddc{i}iicdciiiiic{d}ddddc{i}iiciiiic{dd}c{ii}dc{{d}iii}c{d}ddddc{iii}iiiiiic{iiiii}dc{d}ddc{i}c{{d}ii}dddc{iiiiii}iiiiic{ii}cdc{d}dddddc{{d}iii}ic{{i}ddd}iiic{i}dciiicdddc{d}dddc{{d}iii}ic{{i}ddd}ddc{i}icdddciiiciiic{{d}ii}ddc{{i}ddd}iiiciiiiic{{d}ii}iic{{i}dd}iic{d}dddc{i}iciic{d}dddciiicdddc{i}dc{d}cic{i}iiic{d}ic{i}ic{{d}ii}ddddc{{i}ddd}iiiciiiiic{{d}ii}iic{{i}dd}iiiiiic{d}iiicdddc{i}dcdddddciiiic{dd}ic{ii}dc{d}dddddc{{d}iii}ic{{i}dd}iiiiiic{dd}iiic{i}dddcdddc{i}ic{{d}ii}ddddc{{i}ddd}dc{i}iiiicc{d}ddddc{{d}iii}ic{{i}ddd}dddciiiiiiciiicc{i}dc{d}iic{{d}ii}iiic{{i}ddd}ddc{i}icdddciiiciiic{d}dddc{{d}iii}ic{{i}ddd}dc{i}iiiiiic{{d}ii}dddddc{{i}ddd}c{i}iiiiic{d}ddddciic{d}iic{ii}dc{{d}ii}ddddc{{i}dd}ddc{i}dddc{d}icc{d}dc{dddddd}dddddc{{i}dd}c{d}dddddc{ii}dddc{d}ic{d}iic{ii}dcicdddc{{d}iii}iic{d}ddddc{iiii}dddc{iiiii}ic{dd}dciic{i}iciiiic{d}dddddc{i}iiiiiicdddc{{d}ii}ddc{{i}dd}iiic{d}ciiiiiciiiiiic{{d}ii}ddddc{{i}dd}dc{d}ddccddciiiicddcddc{ii}dc{{d}ii}ddddc{{i}ddd}dddc{ii}ddcdddddc{d}iiicdddddcdddc{ii}dc{dd}ic{ii}dc{{d}ii}ddddc{{i}dd}ddcicdc{{d}ii}iic{{i}dd}ciicdddcddddddcdddddcic{i}dciiiiiic{{d}iii}ddc{d}ddc{{i}dd}iiiciic{d}iiiciiiiiic{{d}ii}ddddc{{i}ddd}iiiciiiiic{{d}ii}iic{{i}ddd}dddc{ii}ddc{d}iciiiic{d}dddddc{dddddd}dddddc{{i}dd}iciiiic{d}ddc{{d}iii}dddc{{i}dd}dc{d}icciiicddddddciiiiiic{d}iic{dddddd}dddddc{{i}ddd}ddcic{i}iiiic{d}ddddc{i}iiiciiic{d}iiiciiiiiic{{d}ii}ddddc{{i}dd}dddciicdddccdddc{i}ic{{d}ii}ddddc{iiiiii}iiiiic{i}iiicdddddciiiic{{d}ii}iiic{{i}ddd}iiicdddddc{{d}iii}iic{{i}ddd}dc{i}iiiicic{{d}ii}ddddc{{i}ddd}iiiiiic{d}dcic{i}iiiciiiciiic{d}iic{dddddd}dddc
```
[Try it online!](https://deadfish.surge.sh/#LGvd9WS0pbqf/4v3/5+KdQt0JT9/iW6n+LdR+eKfiU/f4lup0LeVH5+JT90Jbp/imLeJT91Qv/3/4t+Kfi3/4lP90KdCW6nULfkf+KdUUL3UKdVC3/5lQlP3Qv/3/5+f+LdQp/i2KdVR/+f+Kf4lP9wlupwt1FQt4lP90KdCW6f4p1RCU/34lup0LeJT94lupx/i35RVUeKcJT/fiW6f+KdVC3R+R+JT90Jbqf5/4px/+VUf+VUL3UKf5/+JT91Qlun/5CU/dUJbqf/4pxi3+finUJT/eJbqcLf/iU/dUJbqdC3lR+finUJT/eJbp1CnR/+LdQp1CqqdVC//f/i3lQt0f4qYqqcKdUL/3+L94lP3VCW6nC3FVH+JT9/i//f/n4lP9+Jbp1FUf+VUf4lP3+Jbp//ip/i3FVCn4t+Kqp1UKdCW6ef4p0LYlP3UJbp0Z/mUfip/iU/34lupwvcKni3+KdVH/4t4qeL3CnH/5CU/fiW6f/ingpwt+KYt+JT94lup//inGLf5+KeLYlP3UJbp0VULYpiU/3UJbp/+QlP3VC//f/i3lQt0f4p0LdQlP2JbqcL3CU9+JbqcVQqqnVQlup1C35QeKcLeJT94lup1C35H/inVC35/ipi9wlP9inVC/f/4v/cKdC2JT91C//f/i9kKdVCU/3iW6n+LcflQp1CU/3iW6nQt5Ufn4lP3Qlup/n/iU/fiW6finULeeKdR+VC3CmYt/ini3iU/dUJbqf5/4lP34lun/+Kf5ULcVUf4qeL3CnVQlP94lun/+Kn+LdRULeJT91Qlupwt/4KdUJT/eJbqdR/+fgtwp+JT9/iW6nQt5Ufn4p1CU/3iW6nC3/+JT91UJbqYt/+KdUeKfi9wlP3VCW6dC3UKeCnCqqdVCW6Yp1UL3UKeKfi9xlQlP9+KdUL/dQv/eKnHi3n+KdVC3/+VCU/dCW6f4pn/n/4lP3VCW6cKdBR/lFC9wlP3VCW6nUL3RVQp/lVFQvcKni9wlP3VCW6dGQlP34lumeVFVRVRi3H/4lP90KdCW6f54p/n/4lP3VCW6n+f+JT9+JbqdQvdCnn+KdVCqqdVCW6ef4p0JT/dQlunCnh+VVH/4p+Kqp1UJbqdGLf+KdULf5+Kf5/+JT91QlunUeVBULeJT91Qv/3/4t/lVH+JT9/iW6n+VUJT/fiW6nC3/mJT91Qlup//inGLf5+fin4qqnUA)
Who cares about all that compression nonsense...
[Answer]
# Deadfish~, 3061 characters
```
{i}dsdddddc{{iii}d}iciiic{d}dddc{i}ddc{{ii}dd}dc{{i}ddd}iiic{i}dddciiiciic{d}iic{{ii}dd}dc{dd}ddsc{i}icdddciiiciiic{{d}ii}ddc{{i}dd}iiic{d}c{i}ic{{ii}ddd}iic{{iii}ii}ic{i}iic{d}iic{i}iiiiic{{d}iii}ddc{d}ddc{dd}ddsdc{i}iicdciiiiic{d}ddddcddc{ii}dddc{d}dddddc{i}iiiiicicdddc{{d}ii}ddc{{iii}ii}iciiiciiiiic{i}dddc{d}iiic{i}c{dd}iiiiciiiiiiciiiiic{d}iiic{{d}iii}dc{dd}ddsic{i}dddcdddc{i}ic{{d}iii}ddc{d}ddc{{i}dd}iiic{d}ddddcdc{{ii}d}ddc{dd}ddsc{i}ic{{d}ii}ic{dd}ddsiciiiic{i}iicddcddddddciic{d}dc{{ii}d}ddc{{i}dd}iiiic{d}dddddc{i}ddciiicdciiic{{d}ii}ddc{{i}ddd}iiiciiiiic{d}dciiiiiicdddddciiiiicdddddc{ii}dddc{d}iiiciiiiiic{{ii}ddd}iic{dd}dsddddcdc{{ii}ddd}iic{{i}dd}ddddc{d}dcic{i}iiiciiic{d}dddc{{d}iii}ic{dd}ddsic{i}iiiiic{{ii}ddd}iic{dd}ddsc{i}icdddciiiciiic{d}dddc{{d}iii}ic{{i}dd}dddc{d}ddciiiiiic{i}dddc{d}dddc{{ii}d}ic{{iii}ii}ic{i}icdddc{i}ddciiiic{dd}c{ddddd}dc{d}ddddc{{iii}i}dc{iii}ic{{ii}ddd}iic{dd}ddsic{i}dcdddddciiiic{{ii}dd}dc{{iii}ii}iciiic{{ii}d}ddc{{i}dd}dddcddddciiiiicdddddciiiic{{ii}dd}dc{dd}dsdddc{dd}iiic{i}dcdddddc{d}iic{i}iic{{ii}d}ic{d}ddc{{i}dd}iciiiic{d}ddc{i}c{{d}ii}dddc{{i}dd}ddciciiiicicddciiic{dd}iiic{{ii}d}ddc{dd}ddsic{ii}dc{dd}ic{i}iiic{d}dddddciiiiiic{i}ic{dd}ic{ii}dc{d}dciiiiiicdc{{d}ii}iic{dd}dsddddc{d}icc{d}dc{i}iic{d}c{i}iic{{d}ii}ic{{i}dd}ddddc{d}dcic{i}iiiciiic{d}ic{i}c{{d}ii}dddc{{i}dd}ddcdddddc{i}c{d}c{{ii}dd}iiic{dd}dsddddcdc{{ii}ddd}iic{{iii}ii}ic{i}icdddc{i}ddciiiic{d}ddc{i}dddc{{d}ii}c{dd}ddsic{ii}dc{{d}i}iic{dd}ddsicddddc{{ii}d}ic{dd}ddsdc{i}iicddcciic{d}dc{i}ic{{d}ii}ic{dd}ddsdc{i}iicdciiiiic{d}ddddc{i}iiciiiic{dd}c{ii}dc{{d}iii}c{d}ddddc{{iii}d}iic{iiiii}dc{d}ddc{i}c{{d}ii}dddc{{iii}ii}ic{ii}cdc{d}dddddc{{d}iii}ic{{i}ddd}iiic{i}dciiicdddc{d}dddc{{d}iii}ic{dd}ddsc{i}icdddciiiciiic{{d}ii}ddc{{i}ddd}iiiciiiiic{{d}ii}iic{{i}dd}iic{d}dddc{i}iciic{d}dddciiicdddc{i}dc{d}cic{i}iiic{d}ic{i}ic{{ii}ddd}iic{{i}ddd}iiiciiiiic{{d}ii}iic{dd}dsdddc{d}iiicdddc{i}dcdddddciiiic{dd}ic{ii}dc{d}dddddc{{d}iii}ic{dd}dsdddc{dd}iiic{i}dddcdddc{i}ic{{ii}ddd}iic{dd}ddsic{i}iiiicc{d}ddddc{{d}iii}ic{dd}ddsdciiiiiiciiicc{i}dc{d}iic{{ii}dd}dc{dd}ddsc{i}icdddciiiciiic{d}dddc{{d}iii}ic{dd}ddsic{ii}ddddc{{ii}ddd}ddc{{i}ddd}c{i}iiiiic{d}ddddciic{d}iic{ii}dc{{ii}ddd}iic{{i}dd}ddc{i}dddc{d}icc{d}dc{{ii}d}ic{{i}dd}c{d}dddddc{ii}dddc{d}ic{d}iic{ii}dcicdddc{{ii}d}ddc{d}ddddc{iiii}dddc{iiiii}ic{dd}dciic{i}iciiiic{d}dddddc{ii}ddddcdddc{{d}ii}ddc{{i}dd}iiic{d}ciiiiiciiiiiic{{ii}ddd}iic{{i}dd}dc{d}ddccddciiiicddcddc{ii}dc{{ii}ddd}iic{dd}ddsdc{ii}ddcdddddc{d}iiicdddddcdddc{ii}dc{dd}ic{ii}dc{{ii}ddd}iic{{i}dd}ddcicdc{{d}ii}iic{{i}dd}ciicdddcddddddcdddddcic{i}dciiiiiic{{d}iii}ddc{d}ddc{{i}dd}iiiciic{d}iiiciiiiiic{{ii}ddd}iic{{i}ddd}iiiciiiiic{{d}ii}iic{dd}ddsdc{ii}ddc{d}iciiiic{d}dddddc{{ii}d}ic{{i}dd}iciiiic{d}ddc{{ii}dd}iiic{{i}dd}dc{d}icciiicddddddciiiiiic{d}iic{{ii}d}ic{dd}ddscic{i}iiiic{d}ddddc{i}iiiciiic{d}iiiciiiiiic{{ii}ddd}iic{{i}dd}dddciicdddccdddc{i}ic{{ii}ddd}iic{{iii}ii}ic{i}iiicdddddciiiic{{ii}dd}dc{{i}ddd}iiicdddddc{{ii}d}ddc{dd}ddsic{i}iiiicic{{ii}ddd}iic{{i}dd}ddddc{d}dcic{i}iiiciiiciiic{d}iic{{ii}d}iiic
```
The code is too long for the recursive Python [implementation on tio.run](https://tio.run/#deadfish-). So here is another link which works (I took it from [this other answer](https://codegolf.stackexchange.com/a/226172/25315)).
[Try it online](https://deadfish.surge.sh/#LGvq53tZLS+pqqHf9Sz8eVQ+qHf1Sh31Uvx9VH548vHf1Sh6VMPrKj8/HeXqh31S/HkPrHf1UvHf9esfXjy8fX/jvL9UPKh6VND68j/x5VRQ/qoeVVD6/8yod5eqHf9es/P/H1UPL8fQ9L/P/z/x5fjvL9Q9Kmx9VFQ+sd5fqh5UO+qX48qoh39SoelTD6x3l6x6VNn+Pryiqo8eUO/qVDvql/jyqofVH5H47y9UO+ql+f+PKP/yqj/yqh/VQ8vz/8d/VS8elNVEO/qpeO+qVUPKMfX5+PKod5frHpU2Pr/x39VLx6VMPrKj8/HlUO8v1jvqlUPKj/8fVQ8qh39Sx3/XrH1lQ+qP8ekPVSh5VQ7/rUP+sd/VS8elTY+oqo/x39Uod/16z8d/UqHfVKoqj/yqj/Hf1Sh6U1Q9L8fUVUPLx9eO/qWPKh31Sz/HlQ+h3l6qHfVKjP8yj8el+O/qVD0qbH9Q9LH1+PKqj/8fWPSx/UPKP/yHeXrx6U1UPLB5Q+vHkPrx3l6x31Sqh5Rj6/Px5Y+h3l6qHfVKiqh9DyHf1S/HpTVRDv6qXjv+vWPrKh9Uf48qH1UO8vQ9Kmx/UO8tePSpsqh39Sx6VND68oPHlD6x3l6x6VND68j/x5VQ+vP8ekP6h3l+h5VQ7/qXj/+oeVD6HeXqod/16x/RDyqod5frHfVS/H1H5UPKod5frHpUw+sqPz8d5eqHfVS/P/HeXrx31S8eVQ+s8eVR+VD6h5GPr8eWPrHf1UvHfVS/P/HeXrx6U1Q8vyofUVUf49LH9Q8qqHeX6x6U1Q9L8fVRUPrHf1UvHpU2Pr/B5VQ7y/WPSpo//PwfUPLx39UoelTD6yo/Px5VDvL9Y9Kmx/VUO/qpUO+qkPr/x5VR48vH9Q7+ql476pUPqoeWDyh39Sx31SHlVQ/qoeWPLx/UZUO/qVDyqh/9VD/+selHj6z/HlVQ/qqKh3l6od9Uvx5H/n/47+ql476pQ8qCj/KKH9Q7+ql49Kmh/VFVDy/KqKh/UPSx/UO/qpeO+qVGQ7y9eO+qR5UVVFVGPqP/x3l+qHlQ76pfnjy/P/x39VLx31Uvz/x3l68elTQ/qh5Z/jyqod/Usd9Us/x5UO/ql+O+qUPLD8qqP/x5eO/qWPSpjH1/jyqh9fn48vz/8d/VS8d9UqjyoKh9Y7+ql47/r1j6/KqP8d/VKHfVS/KqHf1Kh6VNj6/zHf1UvHfVKqHlGPr8/Px5eO/qX4A=)
Not sure it's optimal, but should be pretty close. It uses the `s` command. It also takes advantage of the overflow feature when it's useful - when the accumulator is equal to 256, it wraps around to 0.
]
|
[Question]
[
This is limited to Java and C# by the syntax I guess.
In this programming puzzle, you are to produce `Exception`s that can be caught but are thrown again at the end of the catch block.
```
try
{
while(true)
try
{
// you are only allowed to modify code between this try { } brackets
}
catch(Exception ex2) { }
}
catch(Exception ex1)
{
// your goal is to reach this catch block by modifying the code ...
// in the inner try block above
// You win if you reach this part and execute on of the following code lines
Console.WriteLine("You won!"); // for C#
// Or
System.out.println("You won!"); // for Java
}
```
You can freely put code before and after this snippet.
The shortest code to reach the outer `catch` block wins.
[Answer]
# C#, 46 (88 including boilerplate)
```
using System;class P{static void Main(){
try
{
while(true)
try
{
System.Threading.Thread.CurrentThread.Abort();
}
catch(Exception ex2) { }
}
catch(Exception ex1)
{
// your goal is to reach this catch block by modifying the code ...
// in the inner try block above
// You win if you reach this part and execute on of the following code lines
Console.WriteLine("You won!"); // for C#
}
}}
```
The `Abort()` method raises a [ThreadAbortException](http://msdn.microsoft.com/en-us/library/system.threading.threadabortexception.aspx), which is a special exception that is automatically rethrown at the end of each catch block (unless `Thread.ResetAbort()` is called).
[Answer]
**C#** 24 Characters
terminates the inner try block before intended, allowing me to cause an exception outside of the try block.
```
}finally{int a=1/0;}try{
```
[Answer]
## Java, 76 or 31
Counting only the insertions made to the code, ignoring new lines. 76 if you count *everything* I've added, 31 if you exclude the first line and the last line, i.e. only counting `int a=1/0;try{}catch(Error e){}`.
```
class P{public static void main(String[]A){
try
{
while(true)
try
{
int a=1/0;try{
}
catch(Exception ex2) { }
}
catch(Exception ex1)
{
// your goal is to reach this catch block by modifying the code ...
// in the inner try block above
// You win if you reach this part and execute on of the following code lines
//Console.WriteLine("You won!"); // for C#
// Or
System.out.println("You won!"); // for Java
}
}catch(Error e){}
}}
```
[Answer]
>
> **Warning**: These programs are clone bombs (a sort of less-dangerous but still-dangerous form of a fork bomb); as such, **do not run them on a production system without sandboxing or resource limits**. Clone bombs create threads in a loop (as opposed to fork bombs, which create processes in a loop), thus you can stop them simply by killing the process in question (making them much less dangerous than fork bombs, which can be very hard to clear up); but they will likely tie up most of your CPU until you manage to do so (or until the program wins and exits naturally by itself). Asking your OS to place limits on the amount of memory and CPU time these programs are allowed to use should create a safe environment in which to test them.
>
>
>
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~65~~ 60 bytes (with a slight modification to the wrapper)
```
Thread x=Thread.currentThread();new Thread(x::stop).start();
```
[Try it online!](https://tio.run/##ZY/BjgIhDIbvPkX1BAcn2T1qfARPejHGQ2UaB0WYQHHGbPbZxyrjxmRLQvnpx5@fM95wHlry5/oytPnorAHjMCVYo/XwMxnvEiNLuwVbw1UmasPR@tP@ABhPSQsIUhzvr15U11hHimMm/dKfRKGGbRMJa@hX5VCZHCN5LkrppacORtEvFolDqyuJEllmw9vn98/RIJtGyYPQ4dERUP8t0d5E2f8zX/oj9LM298R0rULmqpVfsvNqtgsZuuCnM70czWQNDw "Java (OpenJDK 8) – Try It Online")
Requires both instances of `catch (Exception …)` in the question to be changed to `catch (Throwable …)`. This should in theory be *more* secure, not less, but it enables this solution to be possible.
I saved 5 bytes over the first version of this answer via using a method reference rather than a lambda.
# Java 4, 104 bytes (untested, should work with the original wrapper)
```
final Thread x=Thread.currentThread();new Thread(){public void run(){x.stop(new Exception());}}.start();
```
[Try it online!](https://tio.run/##ZVA9b8MgEN37K66ZYKildrU6duyULFHU4YpJTEoAwRE7ivzbnYuxo0g9JI737t0XRzzjmw/aHZu/MeRfaxQoiynBNxoH15eZS4TE7uxNAyeOiDVF4w67H8B4SJKFwEbxMvmCutZYLShmLSf8rCiqcW8cWti0UWMD/Wd5VCrHqB0VJGTtdAcLuM4DTZPE7Jjpq0Q@iLvqq1c6kPFMy3oYOICRuMK49Bwe3RWSasUjAXT/wWssinL/17zLpwXvtr4k0qfKZ6oC/whZJ1Zbn6Hz7nUl67kYn/EG "Java (OpenJDK 8) – Try It Online") (link goes to a Java 8 implementation, thus won't work)
Using features that have been removed from modern versions of Java, it's possible to solve even the version of the puzzle which requires an `Exception`. Probably, at least. (Java 4 is very old by now and I can't remember which features it did and didn't contain. As can be seen, there were many fewer features in Java back then and it was therefore more verbose; we didn't have lambdas, so I had to create an inner class.)
## Explanations
Most of the solutions to this question are in C# (together with a Java solution that cheats via using unbalanced brackets as a form of code injection, and a Perl solution which also isn't in Java). So I thought it would be worth trying to show how this puzzle can be solved "properly" in Java too.
Both programs are effectively identical (thus the fact that the first program works gives me high confidence that the second program would work too, unless I've accidentally used a non-Java-4 feature; `Thread#stop` was deprecated in Java 5).
Java's `Thread#stop` method works, behind the scenes, via causing a throwable to be thrown into the thread in question. The throwable intended for the purpose is `ThreadDeath` (an `Error`, specifically because people often try to blanket-catch exceptions and Java's designers didn't want that happening), although it allows you to throw anything (or used to; at some point after the API was designed, Java's designers realised that this was an incredibly bad idea and removed the version of the method that takes arguments outright). Of course, even the version which throws `ThreadDeath` is a fairly risky operation about which you can make few guarantees (for example, it allows you to solve this puzzle, something which "shouldn't" be possible), so you're not supposed to use it, but as of Java 8, it still works.
This program works by spawning a new thread, and asking it to forcibly throw an exception back into the main thread. If we're lucky, it'll do that at a point in time when we're outside the inner `catch` block (we can't escape the outer `catch` block until the program ends, because there's a loop around it). Because we have the loop conveniently added already, it's byte-saving to simply use that loop to allow us to keep creating threads, in the hope that one of them will eventually hit the correct timing. This normally seems to happen within a couple of seconds.
(TIO note: the current version of TIO is quite inclined to kill this program early in its execution, presumably due to all the threads being created. It can work on TIO, but does not work reliably, so often a few attempts are required to get the "You won!" output.)
[Answer]
# C#
```
try
{
int i = 0, j = 1, k;
int flag = 0;
lbl:
if (flag == 1)
{
k = j / i;
}
while (true)
try
{
k = j / i;
}
catch (Exception e)
{
flag = 1;
goto lbl;
//Console.WriteLine("loose");
}
}
catch (Exception e)
{
Console.WriteLine("Won");
}
```
[Answer]
# [Perl 5](https://www.perl.org/), 37 or 36 bytes
```
eval {
while (1) {
eval {
```
```
use overload'""',sub{die};die bless[]
```
```
};
$@ eq "" or 0;
}
};
$@ eq "" or print "You won!\n";
```
[Try it online!](https://tio.run/nexus/perl5#Sy1LzFGo5lIAgvKMzJxUBQ1DTSgfBFLB0v9Li1MV8stSi3LyE1PUlZTUdYpLk6pTMlNrrYGEQlJOanFxdOx/mKZaa7h@FQeF1EIFJSWF/CIFA4hwLRdQHlm8oCgzr0RBKTK/VKE8P08xJk/J@j8A "Perl 5 – TIO Nexus")
Turns out that this question translates into Perl well enough to make an interesting puzzle there, too. Perl's `try` equivalent is called (a little confusingly) `eval`, and specifies an exception by setting `@_` to an exception if it occurred, and the null string otherwise. As such, a `catch` block is implemented via comparing `@_` to the null string.
This solution works by creating an object (whose class is the program as a whole; you can use arbitrary Perl files like classes, sort of like the reverse of Java (where you can use arbitrary classes like files)). That's the `bless[]` part (`bless` normally only appears deep inside constructors, as the primitive that makes things into objects in the first place, but you can use it directly if you really want to; `[]` is the memory allocator for the object – a list constructor, in this case – and the class isn't given so it's assumed to be the currently executing one). Meanwhile, we give our "class" (i.e. the main file) a custom compare-to-string method via `use overload`, and make that method throw an exception (thus breaking out of the loop and solving the puzzle); we can actually put the `use overload` anywhere, and although it would traditionally go in with the other method definitions and nearish the top of the file, we can put it into the gap we've been given instead and it still works. (If we put it at the end of the file, we could omit the semicolon after it, leading to a 36-byte solution, but this is arguably cheating as it depends on the program having a trailing semicolon in the first place, which is not guaranteed.) It's actually shorter to overload the stringify operation and let Perl autogenerate a string compare from that, than it would be to overload string compare directly (because overloading some operators forces you to overload other operators too).
Now, all we have to do is throw our object using `die`. The `eval` terminates, then when we attempt to compare `$@` to the null string (to see if there was an exception), the comparison throws another exception and we escape the outside `eval`.
]
|
[Question]
[
Create a function in your chosen language that prints out the following:
```
Old MacDonald had a farm, E-I-E-I-O,
And on that farm he had a cow, E-I-E-I-O,
With a moo moo here and a moo moo there,
Here a moo, there a moo, everywhere a moo moo,
Old MacDonald had a farm, E-I-E-I-O!
```
Where `cow` and `moo` are strings in the function parameters, and as such, can be changed to `pig` and `oink` or `sheep` and `baa`, for example.
It should take into account capital letters, hyphens, punctuation, spaces and line breaks.
Aim to type the fewest amount of Unicode characters in your code.
[Answer]
# Javascript ES6 - 204
>
> Aim to type the fewest amount of **Unicode** characters in your code.
>
>
>
Not the shorter but probably the most obfuscated.
```
f=(a,b)=>{for(c=[b,a].concat('!,-ADEHIMOWacdefhilmnortvwy \n'.split(o='')),i=62;i;o+=c[e>>10]+c[e/32&31]+c[e&31])e='ⱞᄤ⒇瓤抣瘭㾭癍㚏᫶⦮函࿋Π疽䌐獲樘ྰ㞠戝晐}疽䌐࿈䌐眲Π疽㛏戝癐Π疽伲࿌⒋ფᲉѽ疽䦯䨝抽瘭䦹容㾷碶ᅣᲉᄤྦྷ㜕㞱㗽㾲妴㣗畍⺏'.charCodeAt(--i);alert(o)}
```
If your browser do not support ES6 :
```
function f(a,b){for(c=[b,a].concat('!,-ADEHIMOWacdefhilmnortvwy \n'.split(o='')),i=62;i;o+=c[e>>10]+c[e/32&31]+c[e&31])e='ⱞᄤ⒇瓤抣瘭㾭癍㚏᫶⦮函࿋Π疽䌐獲樘ྰ㞠戝晐}疽䌐࿈䌐眲Π疽㛏戝癐Π疽伲࿌⒋ფᲉѽ疽䦯䨝抽瘭䦹容㾷碶ᅣᲉᄤྦྷ㜕㞱㗽㾲妴㣗畍⺏'.charCodeAt(--i);alert(o)}
```
Copy/Paste that code into your browser console and try `f('cow','moo')`, `f('pig','oink')`, `f('sheep','baa')`
## How it works ?
`c` is an array of 29 *letters* plus the animal and its sound (let call this our *alphabet*).
So, all the 31 *characters* fit in 5 bits (2^5 = 32).
A Unicode character is 16 bits long, so it can encode 3 characters of our *alphabet* with a padding bit.
The full text with the new lines is 186 characters of our *alphabet*, it can be encoded with 62 Unicode characters.
For example, `Old` is encoded like this :
```
alphabet value O l d
alphabet index 11 20 15
unicode 0 01011 10100 01111 ===> \u2e8f (⺏)
```
If you have troubles to read some Unicode chars, install [Code2000 font](http://en.wikipedia.org/wiki/Code2000)
[Answer]
# CJam - 142 / GolfScript - 144
```
{" had| a |farm|68, |68 8|here|Old MacDonald765|, E-I-E-I-O|10,
And on that 5 he7690,
With3 2 and3 t2,
Here4t24everyw23,
10!"'|/~A,{`/\*}/}:F;
```
Usage: `"cow""moo"F`
For GolfScript replace `'|` with `"|"` and `A` with `10`
**Explanation:**
The key part is `A,{`/\*}/`:
`A,{...}/` executes the block for each number from 0 to 9 (A=10)
``` converts the number to string
`/\*` does a string replace: if we have on the stack `"bar" "foo 1 baz" "1"` then `/` splits the string resulting in `["foo " " baz"]`, `\` swaps this array with the previous item ("bar") and `*` joins the array resulting in `"foo bar baz"`
So the code replaces each number in the main string with a string that's previously on the stack. We have the animal and the sound, then " had", " a ", etc and finally ", E-I-E-I-O" and the main string, "10,...!". To avoid using too many quotes, I put all the strings (except the parameters) in one string, then split it and dumped the resulting array (`'|/~`)
The main string goes through the following transformations:
```
10,
And on that 5 he7690,
With3 2 and3 t2,
Here4t24everyw23,
10!
```
replace `"0"` with `", E-I-E-I-O"`:
```
1, E-I-E-I-O,
And on that 5 he769, E-I-E-I-O,
With3 2 and3 t2,
Here4t24everyw23,
1, E-I-E-I-O!
```
replace `"1"` with `"Old MacDonald765"`:
```
Old MacDonald765, E-I-E-I-O,
And on that 5 he769, E-I-E-I-O,
With3 2 and3 t2,
Here4t24everyw23,
Old MacDonald765, E-I-E-I-O!
```
replace `"2"` with `"here"`, then `"3"` with `"68 8"` etc.
8 corresponds to the sound, and 9 to the animal.
[Answer]
# Bash + iconv, 128 Unicode characters
Takes the below pure-bash/ascii function body and reverse-encodes into unicode chars:
```
m()(c=`iconv -t unicode<<<㵳⁜屡␠ਲ㵨敨敲攊ⰽ⁜ⵅⵉⵅⵉ੏㵯伢摬䴠捡潄慮摬栠摡愠映牡⑭≥攊档␢Ɐ䄊摮漠桴瑡映牡敨栠摡愠␠␱ⱥ圊瑩⑨⁳㈤␠⁨湡⑤⁳㈤琠栤ਬ效敲猤‬⑴⑨ⱳ攠敶祲⑷⑨⁳㈤ਬ漤™ਠ`
eval "${c:2}")
```
Defines a shell function `m`. Call as:
```
$ m pony neigh
Old MacDonald had a farm, E-I-E-I-O,
And on that farm he had a pony, E-I-E-I-O,
With a neigh neigh here and a neigh neigh there,
Here a neigh, there a neigh, everywhere a neigh neigh,
Old MacDonald had a farm, E-I-E-I-O!
$
```
---
# Pure bash, 171 bytes (ascii-only)
*I think its worth noting that the original verse (with "cow" and "moo") is only 203 chars.*
```
m()(s=\ a\ $2
h=here
e=,\ E-I-E-I-O
o="Old MacDonald had a farm$e"
echo "$o,
And on that farm he had a $1$e,
With$s $2 $h and$s $2 t$h,
Here$s, t$h$s, everyw$h$s $2,
$o"!)
```
Defines the shell function `m`. Call as:
```
$ m sheep baa
Old MacDonald had a farm, E-I-E-I-O,
And on that farm he had a sheep, E-I-E-I-O,
With a baa baa here and a baa baa there,
Here a baa, there a baa, everywhere a baa baa,
Old MacDonald had a farm, E-I-E-I-O!
$
```
[Answer]
# C++ (403)
Alright, this is a bit of a long shot, but who doesn't like over-defining?
```
#define O ", E-I-E-I-O"
#define E O<<","
#define I "Old MacDonald had a farm"
#define H(a) "And on that farm he had a "<<a<<E
#define D(s) s<<" "<<s
#define W(s) "With a "<<D(s)<<" here and a "<<D(s)<<" there,"
#define V(s) "Here a "<<s<<", there a "<<s<<", everywhere a "<<D(s)<<","
#define F I<<O<<"!"
#define N endl
void m(string a, string s){cout<<I<<E<<N<<H(a)<<N<<W(s)<<N<<V(s)<<N<<F<<N;}
```
[Answer]
# Python, 116 Unicode chars
```
def f(**a):print u'鱸쿳光䷰癌쿉ы㊲匒ሔ툕謒畲尔㵵䅵忘쮇⼱ⅅ伿⒡넣Ⰴ邩ઑ꩕醪徜妮ꊌ㰺⒳Ⰳ鮕꾟ౙ㎧譒ᕒ끒镈롴쀼怪㪢愐腤닔ꋔ狊兔Ⲹ㾗꽡Ȩ똀䝸å'.encode('u16')[2:].decode('zip')%a
```
StackOverflow is eating my special characters, though, so here's the file in base64:
```
77u/ZGVmIGYoKiphKTpwcmludCB1J+mxuOy/s+WFieS3sOeZjOy/idGL44qy5YyS4YiU7YiV6KyS55Wy5bCU47W15IW15b+Y7K6H4ryx4oWF5Ly/4pKh64Sj4rCE6YKp4KqR6qmV6Yaq5b6c5aau6oqM47C64pKz4rCD6a6V6r6f4LGZ446n6K2S4ZWS74yS64GS6ZWI7pKA66G07IC85oCq46qi5oSQ6IWk64uU6ouU54uK5YWU4rK4476X6r2hyKjrmIDknbjDpScuZW5jb2RlKCd1MTYnKVsyOl0uZGVjb2RlKCd6aXAnKSVh
```
The data is packed using zlib, which efficiently codes repeated strings (zlib is good at compressing text in general). To take advantage of the "Unicode characters" rule, the 121-byte zlib chunk is padded and halved to a 61-character Unicode string by interpreting the bytestring as UTF-16.
Call the function as
```
f(cow='pig', moo='oink')
```
[Answer]
# Python, 217
You can't really golf this much. I just took out the blatant front-end repetition and...
```
m,f="Old MacDonald had a farm, E-I-E-I-O",lambda x,y:m+",\nAnd on that farm he had a %s, E-I-E-I-O,\nWith a %shere and a %sthere,\nHere a %s, there a %s, everywhere a %s %s,\n%s!"%((x,)+((y+' ')*2,)*2+(y,)*4+(m,))
```
### Javascript, 241 - JSCrush cheat
Made this with JSCrush...not really a real answer, it'd just be interesting to see if anybody can beat this in a mainstream language. (**EDIT**: uh)
```
_='var f=function(c,a){var b=a "+a;return"Anon that he hadcWith and tHere t everyw!"};OlMacDonalhaa a "+, O,\\nhere+"b farm a, d E-I-';for(Y in $=' ')with(_.split($[Y]))_=join(pop());eval(_)
```
[Answer]
# Java, 246
```
void f(String[] a){String o="Old MacDonald had a farm",e=", E-I-E-I-O",x=" a "+a[1],s=x+" "+a[1];System.out.print(o+e+",\nAnd on that farm he had a "+a[0]+e+",\nWith"+s+" here and"+s+" there,\nHere"+x+", there"+x+", everywhere"+s+",\n"+o+e+"!");}
```
Usage: `f(new String[]{"cow","moo"});`
[Answer]
## Java - ~~262~~ 258
```
void m(String...s){String b=s[1],c=b+" "+b,d="E-I-E-I-O",e="Old MacDonald had a farm, "+d;System.out.print(e+",\n"+"And on that farm he had a "+s[0]+", "+d+",\nWith a "+c+" here and a "+c+" there,\nHere a "+b+", there a "+b+", everywhere a "+c+",\n"+e+"!");}
```
Further optimization is definitely possible.
[Answer]
## Perl 5 (UTF-8) - 131 characters, 313 bytes
The script below needs to be saved as UTF-8 with no BOM.
```
use utf8;use Encode;eval encode ucs2,'獵戠晻③㴤∮灯瀻⑥㴢Ⱐ䔭䤭䔭䤭伢㬤漽≏汤⁍慣䑯湡汤⁨慤⁡⁦慲洤攢㬤ⰽ≥牥⁡∻獡礢⑯Ⰺ䅮搠潮⁴桡琠晡牭⁨攠桡搠愠䁟⑥Ⰺ坩瑨⁡③③⁨␬湤⁡③③⁴桥牥Ⰺ䠤Ⱔ戬⁴栤Ⱔ戬⁥癥特睨␬③③Ⰺ⑯™紱';
```
Usage: `f("cow", "moo");`.
Perl needs to have been run with the `-M5.010` flag to enable Perl 5.10 features. ([This is allowed](http://meta.codegolf.stackexchange.com/questions/273/on-interactive-answers-and-other-special-conditions).)
I quite like the symmetry of the character count (131) and byte count (313). It's very yin and yang.
## Perl 5 (ASCII) - 181 characters, 181 bytes
```
sub f{$b=$".pop;$e=", E-I-E-I-O";$o="Old MacDonald had a farm$e";$,="ere a";say"$o,
And on that farm he had a @_$e,
With a$b$b h$,nd a$b$b there,
H$,$b, th$,$b, everywh$,$b$b,
$o!"}
```
Usage: `f("cow", "moo");`.
Again, perl needs to have been run with the `-M5.010` flag to enable Perl 5.10 features.
[Answer]
# CJam (non-ASCII) - 77 chars
```
"啝裢樃濿䶹讄團챤鋚䖧雿ꆪꆵ䷶텸紎腕Խꍰ搓᩟童䚯⤭刧损⬛豳Ẍ퍾퓱郦퉰怈䡞௳閶蚇⡾쇛蕟猲禼࿆艹蹚㞿䛴麅鞑椢⧨餎쏡첦휽嬴힡ݷ녣㯂鐸㭕"56e3b127b:c~
```
Usage: `"cow""moo"F`
The string is [my other CJam solution](https://codegolf.stackexchange.com/a/26621/7416) converted from base 127 to base 56000.
A UTF-8 locale might be required.
By the way, now you can try this online at <http://cjam.aditsu.net/>
[Answer]
# JavaScript: 152 chars / ES6: 149 chars
Here's a JS function called "z" that does the job in 214 chars. (don't execute it!)
```
function z(a,b){c=' a '+b;d=c+' '+b;e=', E-I-E-I-O';f='Old MacDonald had a farm'+e;return(f+',\nAnd on that farm he had a '+a+e+',\nWith'+d+' here and'+d+' there,\nHere'+c+', there'+c+', everywhere'+d+',\n'+f+'!')}
```
I "packed" it in unicode chars using a technique created by @subzey and I for 140byt.es).
```
eval(unescape(escape('©°µ´°£≠Å©´±ÆòÅ∫öŰõÅ¢ö몮∞Ωô∞†®ê†ô∞´®†ª©ÄΩ®∞´ô∞†ô∞´®†ª©êΩô∞¨òÅÖõëâõëÖõëâõëèô∞ª©†Ωô±è´Å§òÅç®ë£°ÅØ´°°´Å§òÅ®®ë§òŰòŶ®ë≤´êßö±•û±≤©ë¥≠ë≤´†®©†´ô∞¨ßÅÆ†ëƩĆ´±ÆòÅ¥™Å°≠Ć©°°¨°≠òÅ®©ê†™Å°©Ä†®ê†ô∞´®ê´©ê´ô∞¨ßÅÆ•±©≠Å®ô∞´©Ä´ô∞†™Å•¨°•òŰ´°§ô∞´©Ä´ô∞†≠Å®©ë≤©ê¨ßÅÆ¢Å•¨°•ô∞´®∞´ô∞¨òÅ¥™Å•¨°•ô∞´®∞´ô∞¨òÅ•≠°•¨°π≠±®©ë≤©êßö±§ö∞ßõÅú´†ßö±¶ö∞ßòêßöëΩ').replace(/uD./g,'')))
```
execute that last snippet, then call `z("cow","moo")`, and you'll get this string:
```
Old MacDonald had a farm, E-I-E-I-O,
And on that farm he had a cow, E-I-E-I-O
With a moo moo here and a moo moo there,
Here a moo, there a moo, everywhere a moo moo,
Old MacDonald had a farm, E-I-E-I-O!"
```
More info here: <http://xem.github.io/golfing/en.html#compress>
### ES6 version:
```
eval(unescape(escape('ƆΩöŰõÅ¢öêΩü°ª®∞Ωô∞†®ê†ô∞´®†ª©ÄΩ®∞´ô∞†ô∞´®†ª©êΩô∞¨òÅÖõëâõëÖõëâõëèô∞ª©†Ωô±è´Å§òÅç®ë£°ÅØ´°°´Å§òÅ®®ë§òŰòŶ®ë≤´êßö±•û±≤©ë¥≠ë≤´†®©†´ô∞¨ßÅÆ†ëƩĆ´±ÆòÅ¥™Å°≠Ć©°°¨°≠òÅ®©ê†™Å°©Ä†®ê†ô∞´®ê´©ê´ô∞¨ßÅÆ•±©≠Å®ô∞´©Ä´ô∞†™Å•¨°•òŰ´°§ô∞´©Ä´ô∞†≠Å®©ë≤©ê¨ßÅÆ¢Å•¨°•ô∞´®∞´ô∞¨òÅ¥™Å•¨°•ô∞´®∞´ô∞¨òÅ•≠°•¨°π≠±®©ë≤©êßö±§ö∞ßõÅú´†ßö±¶ö∞ßòêßöëΩ').replace(/uD./g,'')))
```
[Answer]
# C# - 339 Bytes
```
void x(string c, string d){var a="Old MacDonald had a farm";var b=", E-I-E-I-O";var f=" a ";var g=" there";Debug.WriteLine(a+b+",");Debug.WriteLine("And on that farm he had"+f+c+b+",");Debug.WriteLine("With"+f+d+" "+d+" here and"+f+d+" "+d+g+",");Debug.WriteLine("Here"+f+d+","+g+f+d+", everywhere"+f+d+" "+d+",");Debug.WriteLine(a+b+"!");
```
Usage: `x("cow","moo");`
[Answer]
# Rebol, 206 202
```
f: func[a b][print reword{$o$e,
And on that farm he had a $a$e,
With a $b $b here and a $b $b there,
Here a $b, there a $b, everywhere a $b $b,
$o$e!}[e", E-I-E-I-O"o"Old MacDonald had a farm"a a b b]]
```
Usage: `f "cow" "moo"`
[Answer]
# Delphi XE3 (272 252)
```
procedure k(a,s:string);const o='Old MacDonald had a farm';e=', E-I-E-I-O';n=','#13#10;begin s:=' '+s;write(o+e+n+'And on that farm he had a '+a+e+n+'With a'+s+s+' here and a'+s+s+' there'+n+'Here a'+s+', there a'+s+' every where a'+s+s+n+o+e+'!');end;
```
### Ungolfed
```
procedure k(a,s:string);
const
o='Old MacDonald had a farm';
e=', E-I-E-I-O';
n=','#13#10;
begin
s:=' '+s;
write(o+e+n+'And on that farm he had a '+a+e+n+'With a'+s+s+' here and a'+s+s+' there'+n+'Here a'+s+', there a'+s+' every where a'+s+s+n+o+e+'!');
end;
```
[Answer]
## Lua 237
```
function f(a,b)c=b.." "..b;d="Old MacDonald had a farm, E-I-E-I-O"print(d..",\nAnd on that farm he had a "..a..", E-I-E-I-O,\nWith a "..c.." here and a "..c.." there,\nHere a "..b..", there a "..b..", everywhere a "..c..",\n"..d.."!")end
```
By defining `c=b.." "..b`, I can save a dozen characters. By defining `d` as I do, I save 23 characters. I do not see how I can shorten this anymore. This is called via `f("<animal>","<sound>")`.
[Answer]
# Java 8(411)
```
String m(String...m){LinkedHashMap<String,String>n=new LinkedHashMap<>();n.put("/","( * #, -");n.put("#","farm");n.put("-","E-I-E-I-O");n.put("+","here");n.put("*","had a");n.put("(","Old MacDonald");n.put("|"," a )");n.put(")","moo");n.put("moo",m[1]);n.put("cow",m[0]);m[0]="/,\nAnd on that # he * cow, -,\nWith|) + and|) t+,\nHere|, t+|, everyw+|),\n/!";n.forEach((k,v)->m[0]=m[0].replace(k,v));return m[0];}
```
Abusing of lambda, putted the replaces in a LinkedhashMap to keep em in a defined order then used a foreach lambda to replace key with value in main String. parameters are added as last 2 replacements in the map. that varargs argument is to shave off some bytes in the method header
Ungolfed version:
```
String m(String... m)
{
LinkedHashMap<String, String> n = new LinkedHashMap<>();
n.put("/", "( * #, -");
n.put("#", "farm");
n.put("-", "E-I-E-I-O");
n.put("+", "here");
n.put("*", "had a");
n.put("(", "Old MacDonald");
n.put("|", " a )");
n.put(")", "moo");
n.put("moo", m[1]);
n.put("cow", m[0]);
m[0] = "/,\nAnd on that # he * cow, -,\nWith|) + and|) t+,\nHere|, t+|, everyw+|),\n/!";
n.forEach((k, v) -> m[0] = m[0].replace(k, v));
return m[0];
}
```
[Answer]
# JavaScript 220
```
function f(a,b){c=' a '+b;d=c+' '+b;e=', E-I-E-I-O';f='Old MacDonald had a farm'+e;console.log(f+',\nAnd on that farm he had a '+a+e+',\nWith'+d+' here and'+d+' there,\nHere'+c+', there'+c+', everywhere'+d+',\n'+f+'!');}
```
Called by
```
f('cow', 'moo');
```
[Answer]
## Pure C, 298 bytes, no unicode
In my function I take a single argument, which is actually a bunch of `char*`'s packed together. Each string is null terminated, and there's an extra null terminator at the end. This allows me to check `strlen(a)` at the end of each loop, rather than keeping a counter variable.
mcdonald.c:
```
m(char*a){while(strlen(a)){printf("Old MacDonald had a farm, E-I-E-I-O\nAnd on that farm he had a %s, E-I-E-I-O,\nWith a ",a);a+=strlen(a)+1;printf("%s %s here and a %s %s there,\nHere a %s, there a %s, everywhere a %s %s,\nOld MacDonald had a farm, E-I-E-I-O!\n",a,a,a,a,a,a,a,a);a+=strlen(a)+1;}}
```
main.c:
```
int m(char *v);
int main(int argc, char **argv) {
m("cow\0moo\0programmer\0meh\0\0");
return 0;
}
```
Output:
```
clang main.c mcdonald.c && ./a.out
Old MacDonald had a farm, E-I-E-I-O
And on that farm he had a cow, E-I-E-I-O,
With a moo moo here and a moo moo there,
Here a moo, there a moo, everywhere a moo moo,
Old MacDonald had a farm, E-I-E-I-O!
Old MacDonald had a farm, E-I-E-I-O
And on that farm he had a programmer, E-I-E-I-O,
With a meh meh here and a meh meh there,
Here a meh, there a meh, everywhere a meh meh,
Old MacDonald had a farm, E-I-E-I-O!
```
[Answer]
# Cobra - 203
```
def f(a,b)
d=" a [b] "+b
e=", E-I-E-I-O"
m="Old MacDonald had a farm[e]"
print "[m],\nAnd on that farm he had a [a][e],\nWith[d] here and[d] there,\nHere a [b], there a [b], everywhere[d],\n[m]!"
```
Even for a language with little-to-no multi-lining, and strict indentation rules, Cobra still does pretty well.
[Answer]
# C: 224 bytes
By using the [printf](http://www.cplusplus.com/reference/cstdio/printf/) precision specifier, we can use the same string as both the printf format string and as two of the parameters.
```
o(char*x,char*y){char*f="Old MacDonald had a farm, E-I-E-I-O,\nAnd on that farm he had a %s%.13sWith a %s %s here and a %s %s there,\nHere a %s, there a %s, everywhere a %s %s,\n%.35s!\n";printf(f,x,f+24,y,y,y,y,y,y,y,y,f);}
```
With white space and the string split into lines:
```
o(char* x, char* y)
{
char* f=
"Old MacDonald had a farm, E-I-E-I-O,\n"
"And on that farm he had a %s%.13s"
"With a %s %s here and a %s %s there,\n"
"Here a %s, there a %s, everywhere a %s %s,\n"
"%.35s!\n";
printf(f,x,f+24,y,y,y,y,y,y,y,y,f);
}
```
[Answer]
# PHP - 272 characters, 272 bytes
```
function m($q,$w){for($e="@&And on that farm he had^<%&With *h# and*th#&H(th(everywh#^> >&@!",$r=1;;$e=$r){$r=str_replace(["@","#","^","%","<",">","&","*","("],["Old MacDonald had^farm%","ere"," a ",", E-I-E-I-O",$q,$w,",\n","^> > ","#^>, "],$e);if($e==$r)break;}echo $e;}
```
Usage: `m("cow", "moo");`, `m("fox", "Hatee-hatee-hatee-ho");`
Parameters with `@#%^<>&*(` crash the output.
[Answer]
# Haskell (282 and still somewhat readable :))
```
wc -c oldmacdonald.hs
282 oldmacdonald.hs
```
The file:
```
main=mapM putStrLn[s"cow""moo",s"pig""oink",s"sheep""baa"]
s c m=o#",\nAnd on that farm he had"#b c#e#let n=m#" "#m in",\nWith"#b n#" here and"#b n#" there,\nHere"#b m#", there"#b m#", everywhere"#b n#",\n"#o#"!\n"
o="Old MacDonald had a farm"#e
e=", E-I-E-I-O"
b=(" a "#)
(#)=(++)
```
[Answer]
## ES6, 2 solutions of ~~179~~ 186 chars without any unicode
```
f=(a,b)=>alert("325And on that farm he had a025With a11 h4nd a11 th45H41, th41, everywh411532!".replace(/\d/g,x=>[" "+a," "+b,", E-I-E-I-O","Old MacDonald had a farm","ere a",",\n"][x]))
```
And the second:
```
f=(a,b)=>alert("3625And on7at6 he ha8025With a11 h4n811745H41,741, everywh4115362!".replace(/\d/g,x=>(` ${a}0 ${b}0, E-I-E-I-O0Old MacDonald had a0ere a0,\n0 farm0 th0d a`).split(0)[x]))
```
I've added alert call (+7 chars).
[Answer]
# JavaScript (E6) 140 chars
Char counter: <https://mothereff.in/byte-counter>, 140 chars, 425 bytes in UTF-8
```
eval(unescape(escape('©†ΩöŰõÅ¢öêΩü°°´Å•¨°¥öÄßúıú†µ†ëƩĆ´±ÆòÄ∂®ë¥úê≥©ê≥®ë§ù∞†ûê≤ùëó™ê∂òŰûÄ∏ú∞¥ù±Æ©Ä†®ê∏ûĆù†¥ùëàùÄ∑ûĨòÄ∂ùÄ∑ûĨòÅ•≠°•¨°π≠±®ùÄ∑ûÄ∏ùê∞úê≤òêßõ°≤©ë∞´Å°®±•öÄØßŧõ±ßõÅ£üêæöÄߣ±¨©Ä†£ë°®±Ñ´±Æ®ë¨©Ä†™Å°©Ä†®ê∞òŶ®ë≤´ê∞õưê≠¢ê≠°ê≠¢ê≠£∞∞òÅ®úÅ•¨°•úĨßÅÆúÅ¥™Ä∞òŰúĆô∞´®†´úÄ´®ê©õ°≥¨Å¨™ë¥öÄ∞öëõ®±ùöê©í††').replace(/uD./g,'')))
```
Original ASCII code 188 bytes
```
f=(a,b)=>alert('0125And on 6at13e3ad7 925Wi6 a88347nd a88 645H478, 6478, everywh47885012!'.replace(/\d/g,c=>('Old MacDonald had a0 farm0, E-I-E-I-O0 h0ere0,\n0th0 a0 '+b+0+a).split(0)[c]))
```
Compressed with <http://xem.github.io/obfuscatweet/>
**Test** in FireFox/FireBug console
```
f('mosquito','zzz')
```
*Output*
```
Old MacDonald had a farm, E-I-E-I-O,
And on that farm he had a mosquito, E-I-E-I-O,
With a zzz zzz here and a zzz zzz there,
Here a zzz, there a zzz, everywhere a zzz zzz,
Old MacDonald had a farm, E-I-E-I-O!
```
]
|
[Question]
[
Given a multidimensional, rectangular array of nonnegative integers, sort it at every depth (lexicographically), starting from the innermost.
For example, with this array:
```
[ [ [5, 1, 4],
[10, 7, 21] ],
[ [9, 20, 2],
[4, 2, 19] ] ]
```
You'd sort at the deepest first:
```
[ [ [1, 4, 5],
[7, 10, 21] ],
[ [2, 9, 20],
[2, 4, 19] ] ]
```
Then sort at the next depth, lexicographically:
```
[ [ [1, 4, 5],
[7, 10, 21] ],
[ [2, 4, 19],
[2, 9, 20] ] ]
```
lexicographic comparison of arrays means comparing the first element, and if they're equal comparing the second, and so on all the way down the line. Here we see that `[2, 4, 19]` is less than `[2, 9, 20]` because although the first elements are equal (2) the second aren't - 4 < 9.
Finally, sort at the top depth (lexicographically):
```
[ [ [1, 4, 5],
[7, 10, 21] ],
[ [2, 4, 19],
[2, 9, 20] ] ]
```
The first one is less than the second, because `[1, 4, 5]` is less than `[2, 4, 19]` because 1 is less than 2.
You may take the lengths of dimensions and/or depth of the array as well.
## Testcases
```
[2, 1] -> [1, 2]
[[[10, 5, 9], [6, 4, 4]], [[2, 6, 3], [3, 3, 2]], [[3, 8, 6], [1, 5, 6]]] -> [[[1, 5, 6], [3, 6, 8]], [[2, 3, 3], [2, 3, 6]], [[4, 4, 6], [5, 9, 10]]]
[[[6, 9], [12, 17]], [[9, 6], [9, 8]]] -> [[[6, 9], [8, 9]], [[6, 9], [12, 17]]]
[[[9, 1], [2, 5]], [[8, 5], [3, 5]]] -> [[[1, 9], [2, 5]], [[3, 5], [5, 8]]]
```
[Answer]
# [Python 2](https://docs.python.org/2/), 30 bytes (@SurculoseSputum)
```
def f(L):L>f<map(f,L)<L.sort()
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XZBBasMwEEXp1qcYsrJACZEdu3aIs-zKNxCiGGoRgWsLx0nIWbrxpvQWvUd7ms5ISiAFw3yN3_z50seXvU6HoU_m-fM06WXx_dZq0HHNtvVe794bG2tes129Og7jFDMP_dSXg-laENsIwPABKiCyPTcdH5vLq-ntCeHV0XZmihew3MOCMWR1bKjY0fQTDFVlOJjIe86_Ty8y4SAU4VJwSFQkpRRrDhmHUnGQOYcNfoo0sXhOSadYiXd9VAX-Ii3caK6U95T3hp_B8eLulQYvL3Pf37iFjqcMmG6NZhQrD5EERX72dBnQ0vnedt7Igqrj_s86QzIP-zOPFaR80uzhCuUjlwYu82vDe_4B)
#### Old [Python 2](https://docs.python.org/2/), 32 bytes (@ovs)
```
f=lambda s:s>f<s.sort(key=f)or s
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XZDRaoMwFIbZbZ_i0KsIaWm0Oi21l2PvEMJwTGmYVTFpS59lN96MPdP2NDsnSQstCPlz_P7__Pr1M1zsvu_iafo-2maR_0JTttXh_aMCszG7ZmuWph8t-6wvZRP1I5jAvZ73uq1BbGYAmvdQwqEaWH2qWj5W5zfdDUfLoqUZWm3ZHBY7mEcRssOoO8vQUZYN0zjyedPf04uMOQhFqBQcYjWTUooVh5RDoTjIjMMaH0WaWLwnpBM8iXdzVDm-Ii2cNVPKZ8rbwHvQnt-ykpDlZebna7fQ8dQB260wjGploZKgys-eLgJauNzrziuZ0-m4R68LpPCwP_VYTso3Te8-objnksClfm34n_8)
#### Old [Python 2](https://docs.python.org/2/), 33 bytes (@ovs)
```
f=lambda s:s>[]<s.sort(key=f)or s
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XZDRaoMwFIbZbZ_itFcR0tJodVpqL8feIYThmNIwq2LSlT7LbrwZe6btaXZOkhY6EPLn-P3_-fXze7jYQ9_F0_R1ss0y_5k3ZVsdX98qMFuzl2pnVqYfLXuvL2UT9SOYAD6fD7qtQWxnAJr3UMKxGlj9UbV8rM4vuhtOlkUrM7TasgUs97CIImSHUXeWoaMsG6Zx5POm34cnGXMQilApOMRqJqUUaw4ph0JxkBmHDT6KNLF4T0gneBLv5qhyfEVaOGumlM-Ut4H3oD2_ZSUhy8vMzzduoeOpA7ZbYxjVykIlQZUfPV0EtHC5151XMqfTcf-9LpDCw_7UYzkp3zS9-4TinksCl_q14X_-AQ)
#### Old [Python 2](https://docs.python.org/2/), 34 bytes
```
f=lambda s:s>=[]<s.sort(key=f)or s
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XZDRaoMwFIbZbZ_i4FWEtDRaXSxLL8feIYThmNIwq2LSlT7LbrwZe6btaZaTpIUWhPw5fv9_fv36Gc92P_TZPH8fbbvkv0kruvrw9l6D2ZqdkOrJrMwwWfLRnEWbDhOYSL6c9rprgG0XAJoOIOBQj6T5rDs61adX3Y9HS9KVGTttSQLLHSRp6thx0r0lziFES7Qbhbz57-FZZhSYQlQyCplaSCnZmkJBoVIUZElh4x6FGll3z1Hn7kTez53i7hVq5q2lUiFTXgfB4-z8mpXHrCDLMN_4hZ7HDq7d2oVhrTJWYlj5MdBVRCufe9l5ITmenrv3-kAMj_uLgHFUoWlx8wnVLZdHrghr4__8Bw)
This works by side-effect (of in-place sort). It uses comparison to `[]` as a type check and chained comparison to short circuit (in-place sort returns `None`, so the chained comparison will always fail)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
ߌḊ¡€Ṣ
```
[Try it online!](https://tio.run/##XZAxDsIwDEX3nsISa5CapgnJwj2QlZEF9QKsLEiMTGwIZg5AVyoOUi4S7DhUgBTJv87z9282667bpjScn8fxfnhcXrvb2F/TsCdBrf5EdZUSVtgo0FHBDOZLQK2giRUi6lqBVRDoBp2Clk5kzTh9G9aGKvO5T8rTFWudR12Mky1OPRkjBz/ZmWIn0km/zTszzzEoY01@nMyVVJqDL4QOBQ3Z92vtB/ZcM/o/nj2DvAFHsIJ5VhLW/v9I@EVNQa0sr@Ib "Jelly – Try It Online")
## How it works
```
ߌḊ¡€Ṣ - Main link f(M). Takes a multidimensional array M on the left
€ - Over each inner element E of M:
ŒḊ - Get its depth, D
ß ¡ - Call f(E) D times
·π¢ - Sort the result
```
Essentially, as sorting is [idempotent](https://en.wikipedia.org/wiki/Idempotence), `f` is also idempotent, and so we can apply it as many times as we want with no extra side effects. Therefore, we iterate over each element of `M`, depth-wise, apply `f` to it, then sort the result.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 18 bytes
```
Sort//@#/.Sort->D&
```
[Try it online!](https://tio.run/##NY2/CoMwEMZ3XyPg9Fkbo2kyVBz6AAXH0iFIpQ5akGzhfPX0ktLpfnffn1udf79W55fJxfkax8/u63oQ9SlR1d/KeN@XzT9E1c@DeJbHOLntCEVoIAlFCEGe0cESgkaLlhhY01AMCgpNvigYaAbJXk30S@ock9x0ySabLRbmb7DpB7d1WTY8UydvVFD8Ag "Wolfram Language (Mathematica) – Try It Online")
Essentially copied from [this earlier answer](https://codegolf.stackexchange.com/a/186798/81203). Relies on the array being rectangular; otherwise, `LexicographicSort` (introduced 12.3) is required instead
```
Sort//@# sort all levels
/.Sort->D un-Sort atoms
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~18~~ 12 bytes
Anonymous prefix lambda. Takes list of lists… as argument.
```
{×≡⍵:∧∇¨⍵⋄⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/6sPT3/UufBR71arRx3LH3W0H1oBZD/qbgGStf/TgEo0HvX2PepqftS75lHvlkPrjR@1TQTqDg5yBpIhHp7BmkDaK9jf73@aerSRjoJhrDqXrq4uF5AXHW1ooKNgqqNgGaujEG2mo2ACRLEgNkghkG8MYhsDaR0FI4g4kGUBlAKxDcFazWJjkQ00gxpmCLLJHKLHEqoBSFugqrYEOQcoA1RsClFrAWJBLDUFqQUA "APL (Dyalog Extended) – Try It Online")
`{`…`}` "dfn"; argument is `⍵`:
‚ÄÉ`√ó`‚ÄÉ[if] signum of
 `≡` depth of
‚ÄÉ`‚çµ`‚ÄÉargument
‚ÄÉ`:`‚ÄÉ(i.e. if the argument has depth) then:
  `∧` sort the
  `∇` recursion on
  `¨` each of
  `⍵`  the argument
 `⋄` else:
  `⍵` return the argument
[Answer]
# [SWI-Prolog](https://www.swi-prolog.org/), ~~72~~ ~~59~~ 49 bytes
```
f([H|T],S):-f(H,Q),f(T,R),msort([Q|R],S).
f(E,E).
```
[Try it online!](https://tio.run/##TY89C4MwEIb3/oqMCZzSaLWxSyfB1ZgtZGyKYGtRwcX/bu@MghC497177iO/oe/6dzTO7bp6bqvFOGjEI/K8glqA5wa0gM/YDxO39aKpGl88L6EU8fpEzibApAOGNOattfIKLANWYM7mwG74HGkC0aekU4zAkpBHpbBEWm6tuaOCPgbm@zBJm@6hp9gbMKqNbg66COfQtiywilRYmm2sQXYe2unF8ehvdxh9Ns3ZGPzrHw "Prolog (SWI) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes
```
λ-[vxs
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLOuy1bdnhzIiwiIiwiW1tbMTAsIDUsIDldLCBbNiwgNCwgNF1dLCBbWzIsIDYsIDNdLCBbMywgMywgMl1dLCBbWzMsIDgsIDZdLCBbMSwgNSwgNl1dXSJd)
*-5 thanks to @emanresuA in vychat*
## Explained
```
λ-[vxs
λ # a lambda that takes a single argument n and:
- # subtracts n from itself (scalars return 0 which is falsey, lists return a list of 0s which is truthy) - borrowed from https://codegolf.stackexchange.com/a/241658/78850
[ # and if that item is a list
vx # call this lambda on each item
s # and sort the result
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 34 bytes
```
f(a)=if(#a',vecsort(apply(f,a)),a)
```
[Try it online!](https://tio.run/##NU3bCgIhEP2VYXtIYRZyt734UD8i8yCRIUSJRdDX28xqoMy5ziSfY39LpQTl9SkGtfN7/Fwvr2d@K5/S/asCeq35l0o99GdIOT7Yh05IB1LWCM4NCIYEOHNAmBCssBnhyI@oRZiPgkeeCEPVGa1sCTZbdaZqSH1bY2T7UkXbojzXf8624xybqrQKqodYIdLlBw "Pari/GP – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 30 bytes
```
f=->b{b*0==0?b:b.map(&f).sort}
```
[Try it online!](https://tio.run/##KypNqvz/P81W1y6pOknLwNbWwD7JKkkvN7FAQy1NU684v6ik9n@BQlo0EBga6CiY6ihYxuooRJvpKJgAUSyIHW2kowDkG4PYxkBaR8EIIg5kWQClQGxDsFazWCD4DwA "Ruby – Try It Online")
[Answer]
# JavaScript, ~~70~~ 64 bytes
```
f=x=>x.sort(g=(a,b)=>1/a?a-b:f(a).some((c,i)=>a=g(c,f(b)[i]))*a)
```
[Try it online!](https://tio.run/##jY/BDoIwDEDvfsWOnRnoQBA007sHPXhcdhiEkRkUA8To189OOBuSJX1b29fupl@6Lzv7HIJX5pwRb3F4h33bDVAL0Kyg4sBX@qiDYmdAU0zdK4CSWUxoUSMZKKi0itKlpq5sH33bVGHT1nC6Xs5hP3T2UVvzAQMyYoRjId0v/tdJydeMJIzkihGZMrLBozx7Bd5jzzFGRqLxHSnDlGf@a02VmjcqncZwv912tOWTCmM215P7z2EPapLRknkaF00mi/sC)
*Saved 6 bytes thanks to [tsh](https://codegolf.stackexchange.com/users/44718).*
[Answer]
# [Python 3](https://docs.python.org/3/), ~~ 47 ~~ 36 bytes
Saved 1 byte thanks to @Dialfrost, and 9 bytes thanks to @loopywalt
```
f=lambda l:l*0!=0==l.sort(key=f)or l
```
[Answer]
# [J](http://jsoftware.com/), 30 bytes
```
[:><@#\.@$(4 :'/:"x~y')&.>/@,<
```
[Try it online!](https://tio.run/##XY/NTsMwEITvfopRi0gibd04joNtlSgCiVPFgavxCbVCXLjChVcP658iFcmWx@tvZtcf60Y2Z9x7NCD08Lx3Eo8vx6c1@PmwbF/lctOO8M3eb75@vpvuVs77hQ5rJ54fJMTp7f0TZ7QOivwA05FvLQx5zVpwYi9CCKonrsFFQpgII6@YdBgIfNdJaz4JQ6mzsvyUtMrWKcaI3YwUVgvFw3b7l6VrVpFTqY@5YebTDATVc1gaa6ojKebVXaFdRV3OvfS8kDadmfvvzYEpvPY3BbNJlUnN1RfcNacrZ0pb0a2/ "J – Try It Online")
Uses a single fold to explicitly sort each rank, in order. Requires an explicit verb since rank `"` is a conjunction.
*Note: Could save 1 byte with `{{ }}` but it fails on TIO's J version.*
# [J](http://jsoftware.com/), 23 17 bytes, port of Adam's recursive APL solution
```
[:/:~$:^:(#@$)"_1
```
[Try it online!](https://tio.run/##XY/BigIxEETv8xWFKzgDrU4mZkwaFGFhT3vaa4geZGXZi3/gr4/dSRQUElLpvKru/E@z1eKCHWMBQg@WvVzh8@f7a4q85tucj9x@HObd7GSmrvk9/11xQRtgiAe4jrj1cMRWdCP@vokxmp6khpAIcSRsZCXVcSDI3aq2chKGUhfl5Um1ydYxpYTlHhpWC8Ujdv/MsjWryLHUN7lh5nUGguklTMca60hGeLMtdKhoyLmPng/S65m5d28O1PDa3xXMqyqTupcvhFfOVs6Vtk033QE "J – Try It Online")
*-6 thanks to ovs!*
[Answer]
# Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 15 bytes
```
x=Fe<sr<m x*~|p
```
Takes input as a free monad of lists.
## Explanation
In Haskell we use a free monad of lists. A very simplified definition would look like:
```
data Ragged a
= Pur a
| Fe [Ragged a]
```
It's either a terminal element (wrapped in `Pur`) or a list of more ragged lists (wrapped in `Fe`).
We could write the code then like:
```
x (Fe y)=
Fe < sr < m x $ y
x (Pur y)=
p y
```
In the `Fe` case we map `x` across the input to sort all lower levels, sort the result and wrap it back in a free.
In the pure case we just wrap it back in a pure using `p`.
Now hgl has a special operator to do this sort of case for us. We use the `*~|` operator which is the equivalent to a pattern match on the cases of a `Free`.
So now we rewrite both options as a function `Fe<sr<m x` and `p` and supply them as args to `*~|`.
We can't get rid of the `x=` this time because the definition is recursive.
## Reflections
Wow, I couldn't get this one in point free. That's probably an issue.
`hoF` for `hoistFree` *nearly* is useful here. If we just wanted to for example reverse every level `hoF rv` would work fine. But we can't just place `sr` in there instead of `rv`. `sr` needs the elements to be `Ord`. Instead we have to do this.
There should probably be a version of hoist which allows this sort of thing. Would save 9 bytes here.
```
maF ::
( Functor f
, Functor g
)
=> (f (Free g a) -> g (Free g a)) -> Free f a -> Free g a
```
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 13 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
```
‚ä¢{‚àß‚öáùï®ùï©}¬¥‚â°-‚Üï‚àò‚â°
```
[Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oqie+KIp+Kah/CdlajwnZWpfcK04omhLeKGleKImOKJoQo+KOKLiCDCtyBGIOKAokpzKcKo4p+oICJbIFsgWzUsIDEsIDRdLCAKICAgIFsxMCwgNywgMjFdIF0sIAogIFsgWzksIDIwLCAyXSwKICAgIFs0LCAyLCAxOV0gXSBdIgoiWzIsMV0iCiJbW1sxMCwgNSwgOV0sIFs2LCA0LCA0XV0sIFtbMiwgNiwgM10sIFszLCAzLCAyXV0sIFtbMywgOCwgNl0sIFsxLCA1LCA2XV1dIgoiW1tbNiwgOV0sIFsxMiwgMTddXSwgW1s5LCA2XSwgWzksIDhdXV0iCiJbW1s5LCAxXSwgWzIsIDVdXSwgW1s4LCA1XSwgWzMsIDVdXV0iCgrin6k=)
`{‚àßùïä‚çü‚â°¬®ùï©}` is a translation of J, `{√ó‚â°ùï©?‚àßùï䬮ùï©;ùï©}` is a shorter direct translation of dyalog extended, but using the depth modifier is cooler.
-2 from Adam.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
"ИÊi®δ.V}{"©.V
```
[Try it online](https://tio.run/##yy9OTMpM/f9f6fCE03MOd2UeWndui15YbbXSoZV6Yf//R0dHm@koWMbqKEQbGukoGJrHgpjRljoKZiAGkLaIjY0FAA) or [verify all test cases](https://tio.run/##NY07DsIwEESvErkeRbEdO3GVW6SxXIBEkYoCCSlCtBRUiJoL0FBxgqRE4hBcxMzy2WZnd@fNrjeL5bDK27FTxetwLlQ3ZjWfHpf5OEy3573s9zs1Xcs@I0eWg0adEHWFBkYnyhhgKhiqGgY6JC6LSCUtitMh8OpRExXAwMNSWFhysrFo4SWWXv8NiAQE00xqfn/EEtD@DUF@MM19zi27ZHJK6Q0).
**Explanation:**
As mentioned in similar challenges, 05AB1E lacks recursive functions unfortunately, making it pretty long by mimicking the behavior with a string and 05AB1E-eval.
```
"..." # Push the recursive string mentioned below
© # Store it in variable `®` (without popping)
.V # Evaluate and execute it as 05AB1E code
# (after which the result is output implicitly)
Ð˜Ê # Check that this is the maximum depth of this (inner) list:
Ð # Triplicate the current list
Àú # Flatten the top copy
Ê # Check that the top two copies are NOT equal
i } # If this is truthy, so we've reached the maximum depth:
δ # Map over each inner item:
® .V # Do a recursive call (by 05AB1E-evaluating string `®`)
{ # Sort the list
```
[Answer]
# [Julia 1.0](http://julialang.org/), 22 bytes
```
!x::Int=x
!x=sort(.!x)
```
[Try it online!](https://tio.run/##XY/BjoMgEIbvPsXoCRNKSq2uNrH3PewTEA4kZRM3hBplN7y9ywBtosSEf4Zv/vn9@TWT4n7bSn@7fVo3@qL04/pcHGGlr7fv5wJmshomC4tWD9QrqQsIR1ENI@g/ZRj50k6xWS2rZmSdzeQIkhSq072q68TPy2SdsUTty/JQB9MRjs2KVXWh7WMTFwpcwukOglO4yEIIwc8UWgqDpCA6CtfwSdTIhrpB3YQb@dgPqg9PqHkc7aRMnuLdSDNhvH97NdkryS71r3Fh5DFDSHcOZhiry5E4Rv5I9JDRIfq@dr7IHu/IHWejIZrn/W3CelQpabv7hWHPNZlr09p/ "Julia 1.0 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 49 bytes
```
⊞υθFυFιF⁼κ⁺⟦⟧κ⊞υκW∧υ⊟υ«≔⟦⟧ηWι⊞η⊟ιW⁻ηιF№η⌊κ⊞ι⌊κ»Iθ
```
[Try it online!](https://tio.run/##VU7LCsIwEDzbr9hjAhF8o3gS8Sj0XnoovrI0bW1j9CB@e5y0FXUJ7GQeyRx01hyqzHgfO6uFU1TLdXSuGhJOUru537vaZcaKXFFsnBVJqiiXUtInmCP40GxOJDblMTBxdcUrsDyjwcZavpRtSsM46J3c53XnZvmj7bnEP1DAdhW2lStvgYHEhSvEtwD/kevoFcUNw7zN7E3UYLxPMOORormiFWokC0UznDTgZKII92nAU2xFk44HWkIKeNxGFynGD@/mDQ "Charcoal – Try It Online") Link is to verbose version of code. Outputs using Charcoal's default output format, where depth 1 arrays print their elements on their own line but the arrays themselves are double-spaced from each other, then depth 2 arrays are triple-spaced from each other etc. Explanation:
```
⊞υθ
```
Start enumerating all of the arrays at each depth.
```
FυFι
```
Process all elements of each array.
```
F⁼κ⁺⟦⟧κ⊞υκ
```
If this element is itself an array then push it to the list of all arrays.
```
W∧υ⊟υ«
```
Process the list in reverse order.
```
≔⟦⟧ηWι⊞η⊟ι
```
Move the elements from this array into a temporary array.
```
W⁻ηιF№η⌊κ⊞ι⌊κ
```
Move them back in ascending order.
```
»Iθ
```
Output the final array.
[Answer]
# [Fig](https://github.com/Seggan/Fig), \$7\log\_{256}(96)\approx\$ 5.762 bytes
```
!#lxKMX
```
[See the README to see how to run this](https://github.com/Seggan/Fig/blob/master/README.md)
This answer uses that fact that programs = functions in Fig, so I can invoke the program from within the program.
```
!#lxKMX # Takes the list as input
! # If
#lx # The input is a list
M # Map the list
X # By this function (i.e. the program itself)
K # Then sort the resulting list
# If the input is not a list, simply return the input
```
]
|
[Question]
[
The Meeker numbers are a 7 digit number in form of \$abcdefg\$, where \$a×b=10c+d\$ and \$d×e=10f+g\$. As an example \$6742612\$ is a meeker number, here \$6×7=10×4+2\$ and \$2×6=10×1+2\$, so it is a meeker number.
Additionally, a Meeker number does not have any leading zeros (so \$a \ne 0\$)
## The Challenge
Your program can do one of the following tasks:
* Take a positive integer \$n\$ and output the \$n\$th Meeker number (0 or 1 indexed, your choice. If 0 indexed, \$n\$ will be a non-negative integer)
* Take a positive integer \$n\$ and output the first \$n\$ Meeker numbers
* Output all 900 Meeker numbers
# Rules
* You may take an [empty input](https://codegolf.meta.stackexchange.com/q/12681/66833) if you output all Meeker numbers
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* Trailing whitespace is allowed.
* If possible, please link to an online interpreter (e.g. [TIO](https://tio.run)) to run your program on.
* Please explain your answer. This is not necessary, but it makes it easier for others to understand.
* Languages newer than the question are allowed. This means you could create your own language where the empty program calculates this number, but don't expect any upvotes.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins!
The first few Meeker numbers are
```
1000000
1000100
1000200
1000300
1000400
1000500
1000600
1000700
1000800
1000900
1101000
1101101
1101202
1101303
1101404
1101505
1101606
1101707
1101808
1101909
...
```
*Thanks to @Adám for the [detailed analysis](https://chat.stackexchange.com/transcript/message/57614863#57614863) and @cairdcoinheringaahing for the editing rework*
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 45 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?") ([SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set"))
Full program. Prints all meeker numbers. Requires 0-based indexing (`⎕IO←0`).
```
1e6+⍸{(×⌿i⊇⍵)≡10⊥⍵[2+i←0 1,⍪3 4]}¨10⊤¨1e6…1e7
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkGXI862gv@G6aaaT/q3VGtYWjwqGvpo96t0ZnaRrGajzoXHp7@qGc/WACkWsFQ51HvKmMFk9jaQytAapcAqVSzRw3LjFLN/gON@q8ABgUA "APL (Dyalog Extended) – Try It Online") (limited to upper bound of 2 000 000 ― above code works offline)
`1e6…1e7` numbers 1 000 000 through 10 000 000
`10⊤¨` base-10 representation of each (splits digits of numbers into lists of digits)
`{`…`}¨` apply the following lambda to each:
`⍵[`…`]` index the digits of the current number using the following:
`⍪3 4` the column-vector `[[3],[4]]`
`0 1,` prepend a column consisting of `[0,1]` yielding `[[0,3],[1,4]]`
`i←` assign to `i` (for **i**ndices)
`2+` increase by two; `[[2,5],[3,6]]`
`10⊥` evaluate as base-10, using the top row as tens place and bottom row as ones place
`(`…`)≡` check if it matches the following:
`i⊇⍵` select the elements from the digits at indices `i`
`×⌿` multiply the elements of the top row with the elements of the bottom row
`⍸` **ɩ**ndices where true
`1e6+` offset to the first candidate
[Answer]
# [Python 2](https://docs.python.org/2/), ~~121~~ ~~115~~ 98 bytes
```
def f(n,t=10):p,q=n%100/t,1+n/100;r=p*q;s=n%t*(r%t);print`t+n/t`+'0'*(r<t)+`r`+`n%t`+'0'*(s<t)+`s`
```
[Try it online!](https://tio.run/##LY0xDsMgEAR7vyKNZTBIBseVCX@5IkFJc8GwjV@PjyjNaDW70uYT7y@vrT1f6ZYUW0Tv9J7tEXn0zi2w3vAiKZSY5yNU8ZhVGaFDLh8GQXqQmdwk@gFtqJAhWf1d/blKLSmvh6TWjnvH1iF37QI "Python 2 – Try It Online")
On noticing the digits, I observed a pattern and got this constant time solution. Takes n as input (0-indexed) and prints n'th meeker number.
For example, the first 2 digits follow the pattern: 10, 11, 12, ... 99 (with each number occuring 10 times in a row).
*thanks to ovs for -23 bytes*
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~107~~ \$\cdots\$ ~~74~~ 73 bytes
Saved 8 bytes thanks to the man himself [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!!
Saved 5 bytes thanks to [tsh](https://codegolf.stackexchange.com/users/44718/tsh)!!!
Saved a whopping 20 bytes thanks to [Olivier Grégoire](https://codegolf.stackexchange.com/users/16236/olivier-gr%c3%a9goire)!!!
```
t=10;h=100;a;b;f(n){a=n/h+1;b=n/t%t;a=(a*t*h+b*h+a*b)*t*h+n%t*(h+a*b%t);}
```
[Try it online!](https://tio.run/##VdpfbxTJFcbh@/0UFhKSbUDbXVVd3S3HuYnyKQIXxmsWlMS7wpaCgvjqIef3vuewCdodHoaempo6f6p68P2bX@/vv39/vl2Xm4/xsNzc3by/@XD5ePX17vbx54@v1pv38fvzy@ebu9vLu@vn64@v3sf/d9fvr/SHx5fP15f688vnq5tv3/959@nx8uqnrz9dxK9Pj88XD19@f7h/fvjlb@8ubi@@xjvw6/UFWAut0AujsBVmYS8chVNYGS8R/xltaUZfujGWYWzLZsxlGvuyG8dyGOdyBhoTXIxVAwaaxgl0vTww9KrAtubFc82L9zUvPta8@Fy5uPOJF2PVDANNAwa63j0wNE5gWzdj1sv3thpHG8bZ@BSDJVyMVVMNNM0w0DVgYGg@ga3lxbPlxXvLi4@eF5@dizdishir1jDQ1nymr/nMaPnM1vKZ2fOZveczx8hnzsEzkyAvxqpFCDRNNdD1kQNDMwxsPS@ePS/eR158jLz43Lh4J2sWY1WUA23Nv@paw8DQRw5smmFgasDAPk7j2KZxTuJ1kIaLsWp5A02rGuiaamBoDQPbyIvnyIv3LS@Op4xz5@KTvF6MVZkQaFqEQFeUA0OfPbBpDQNTHzmwa4aBowY8j/ikrWqwVQ22qsFWNdiqBlvVYKsabFWDrWqwVQ1SHUtBlcKjKgWoUoAqBahSgCoFqFKAKgWoUhjEI7fMZ6B8BspnoHwGymegfAbKZ6B8BspnZuWRe2YdUNYBZR1Q1gFlHZj1cmUdUNYBZR0f0yOPzA2g3ADKDaDcAMoNoNwAyg2g3ADKDdbNI29rRnBbM4KBXhiFrTALe@EoOIIRiKXgCAYcwYAjGHAEA45gwBGMR0cw4AgGHMF43iMHHMGAIxhwBAOOYMARDDiCAUcw4AgGHMF4I48ccAQDjmDAEQw4ggFHMDDr5Y5gwBEMOIIxc48ccAQDjmDAEQw4ggFHMOAIBhzBgCMYUAR71WCvGuxVg71qsFcN9qrBXjXYqwZ71WCvGuxr7ilAewqP2lOA9hSgPQVoTwHaU4D2FKA9BWhPYRCP3LJSgNYZaJ2B1hlonYHWGWidgdYZaJ2ZlUfu2euAeh1QrwPqdUC9Dsx6uXodUK8D6nV8TI88Mp@B8hkon4HyGSifgfIZKJ@B8hkon1k3jxzQPgi0DwLtg0D7INA@CLQPAu2DQPsg0D5IIDzyzKwDyjqgrAPKOqCsA8o6oKwDyjrgrIvIeuSAzkhAZySgMxLQGQnojAR0RgI6IwGdkYDOSKSKRw6ouoGqG6i6gaobqLqBqhuouoGqG6i6yT2PHNDeDbR3A@3dQHs30N4NtHcD7d1AezfQ3j2qBkfV4KgaHFWDo2pwVA2OqsFRNTiqBkfV4FhztwJaDR61GkCrAbQaQKsBtBpAqwG0GkCrwSAeueWeApQbQLkBlBtAuQGUG0C5AZQbQLnBrDxyz0oBqhSgSgGqFKBKAaoUoEoBqhSgSuFjeuSR/Rmob4Be16hvAPUNoL4B1DeA@gZQ32DdPHJgLbRCL4zCVpiFvXAUHMGZ@QwcwZn5DBzBmfkMHMGZ@cyjIzgzn4EjGM975IAjGHAEA45gwBEMOIIBRzDgCAYcwYAjGC/2yAFHMOAIBhxB3kBvGnAEA45gwBEMOIIBRzBm7pEDjmDAEQz0usYRDDiCAUcw4AgGHMGAIrhVDW5Vg1vV4FY1uFUNblWDW9XgVjW4VQ1uVYM@9STUn3lUfwbqz0D9Gag/A/VnoP4M1J@B@vPW8vQF1kIr9MIobIVZ2AtHwXPuuacAz7nnngI85557CvCce@4pwHPuuacAz3lkpYC10Aq9MApbYRb2wlHwnGMOS8FzDnjOAc854DkHPOd49JwDnnPAcw54zrPnnANroRV6YRS2wizshaPgOcc7LgXPOeA5BzzngOcc8JwDnnPAc45HzzngOR8j5xxYC63QC6OwFWZhLxwFzznGXwqec8BzDnjOAc854DkHPOeA5xzwnAOa86wanFWDs2pwVg3OqsFZNTirBmfV4KwanFWDc80TI1Df4FF9A6hvAPUNoL4B1DeA@gZQ3wDqGwzikVvuVkC9DqjXAfU6oF4H1OuAeh1QrwPqdczKI/c8fQH1Z6D@DNSfgfozUH8G6s9A/RmoP/MxPfLIPQVoTwHaU4D2FKA9BWhPAdpTgPYUoD2FdfPIW1YKaIVeGIWtMAt74Sg4gjM7P3AEZ3Z@4AjO7PzAEZzZ@Xl0BGd2fuAI7iMjGHAEA45gwBHcR0Yw4AgGHMGAI8jJb82LHcF4I48ccAQDjuAxMoIBRzDgCAYcwYAjGHAEA45gzNwjBxzBc8sIBhzBgCPIXUrLix3BgCMYcAQDiuBeNbhXDe5Vg3vV4F41uFcN7lWDe9XgXjW4Vw3ua373BXR@5lHnZ6DzM9D5Gej8DHR@Bjo/A52fgc7PulHQyC3v6IFWA2g1gFYDaDWAVgNoNYBWA3g1et6nAN2nAN2nAN2nAN2nAN2nAN2nAN2nAN2nAN2n8DE98sjTF1BuAOUGUG4A5QZQbgDlBlBuAOUG6@aRt9xTgPozUH8G6s9A/RmoPwP1Z6D@DNSfCYRHnlkpQJUCVCn7zEoBqhSgSgGqFKBKAaoUIuuRA7rvBq3@SvfdQPfdQPfdQPfdQPfdQPfdQPfdpIpHDqhvAPUNoL4B1DeA@gZQ3wDqG0B9A6hvkHseOaDvN4C@3wD6fgPo@w2g7zeAvt8A@n4D6PsNoO83jqrBo2rwqBo8qgaPqsGjavCoGjyqBo@qwaNq8Fjzrg0o63hU1gFlHVDWAWUdUNYBZR1Q1gFlHYN45Jb3VkDrDLTOQOsMtM5A6wy0zkDrDLTOulHQyD13K6DqBqpuoOoGqm6g6gaqbqDqBqpuPqZHHnmfApTPQPkMlM9A@QyUz0D5DJTPQPl8bHn6AmuhFXphFLbCLOyFo@AIztxTgCM4c08BjuDMPQU4gjP3FB4dwZl7CnAE96wU4AjuWSnAEdyzUoAjuGelAEdwz0oBjmC8h0cOOILHzAgGHMGAIxhwBAOOYMAR9Cc0HMGYuUc@94xgwBEMOIIBRzDgCAYcwYAjeO4ZwYAieFYNnlWDZ9XgWTV4Vg2eVYNn1eBZNXhWDZ5Vg@ea3zEC9Toe1euAeh1QrwPqdUC9DqjXAfU6oF7HIB655YkRKDeAcgMoN4ByAyg3gHIDKDeAcoNZeeSe330B7d1AezfQ3g20dwPt3UB7N9DeDbR38zE98shzHVDWAWUdUNYBZR1Q1gFlHVDWAWUd6@aRt7xP0TlozWe0DwLtg0D7INA@CLQPAu2DQPsggfDIM09fQPkMlM9A@QyUz0D5DJTPQPkMlM9E1iPvuacA7SlAewrQngK0pwDtKUB7CtCeArSnkCoe@chKAaoUoEoBqhSgSgGqFKBKAaoU4EqJ3PPIAZ2RgM5IQGckoDMS0BkJ6IwEdEYCOiOBOCN9u9E/3d9/vPt8HY8P939/@Ox/u3/x9stf29sv51/i/@3F64v//XN/ka/78Nvni0v@3f8xXrLcxG9/unj69O@H3z5c1k8CXP2cT1z/eObm4tWrxysN4J8cqJ8eeIpR@GmEm/979iGe/fFzBY/v/vjL3z/HX3@4fPHyl4s3f76Ix5dPbx9jqo@vL55e//g0T7e3D@9yyG8/ffv@n/sP/7j79en7m3/9Fw "C (gcc) – Try It Online")
Inputs \$0\$-based \$n\$ and returns the \$n^{\text{th}}\$ Meeker number.
[Answer]
# [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 65 bytes
```
for(i=99;i<999;print((e-i+'0'-a*b+e)*~99+a*b%10*e))[a,b,e]=++i+''
```
[Try it online!](https://tio.run/##DcpNCoAgEEDh04Q/o1DLoTpJtNCaYIpKVII2Xd3cPL7F293j0hI5ZJsCrxTP@zroLWW7o@QRsecBa0PkK0tJlkG0wjrtgZT@EKGy6VpNSk3OeEPzCFAnUcoP "JavaScript (SpiderMonkey) – Try It Online")
For example, when `i == 267`:
```
i=267;
[a,b,e]=i+'';
print([a, b, e]); // ["2", "6", "7"]
print(e-i); // -260
print(e-i+'0'); // "-2600"
print(a*b); // 12
print(e-i+'0'-a*b); // -2612
print(e-i+'0'-a*b+e); // "-26127"
print((e-i+'0'-a*b+e)*~99); // 2612700
print((e-i+'0'-a*b+e)*~99+a*b%10*e); // 2612714
```
[Try it online!](https://tio.run/##dYzNCoJAFEb3PsVlIPzXcQhFxB6gRS1aigu1SaZMRSV006ubOpYVtblczjl85@gW1UnFykavS3ak1bXIL7Try4rlDfjQgr@BpMjrIqNGVqTS9rDfGXUz6JSdOqmVZa9nPrEdTwgiLdZo6DNVFD1hWpAGBrEGNJQ9ME0IEEEaIHs8DgrniOqMa53YeGGqiEXO0SgwmlWkxBxb5DPWX2bof0mVLnsWcZ6DX4lyd13eTRXG/zN1eFcWVuhbb637/gE "JavaScript (SpiderMonkey) – Try It Online")
---
# JavaScript (Firefox), 72 bytes
```
for(f='%.2d',i=99;i<999;console.log(a+b+f+e+f,a*=b,a%10*e))[a,b,e]=++i+f
```
Thanks [Neil](https://codegolf.stackexchange.com/users/17602/neil) for pointing out that Firefox support `%.2d` for padding zeros.
[Answer]
# [R](https://www.r-project.org/), ~~101~~ ~~91~~ ~~71~~ 69 bytes
*Edit: -2 bytes thanks to Giuseppe, amazingly within <5 mins of posting*
```
outer(10:99,0:9,function(a,e,d=a%%10)((a*100+a%/%10*d)*10+e)*100+d*e)
```
[Try it online!](https://tio.run/##K/r/P7@0JLVIw9DAytJSB0jopJXmJZdk5udpJOqk6qTYJqqqGhpoamgkahkaGGgnquoDuVopmkCedqomWCxFK1Xz/38A "R – Try It Online")
---
The original version - inspired by and taking a similar approach to [Manish Kundu's answer](https://codegolf.stackexchange.com/a/223378/95126), and also golfed-down from 101 to 96 bytes by Giuseppe:
# [R](https://www.r-project.org/), 96 bytes
```
z=c(0,'')
paste0(a<-100:999%/%100,b<-0:99%/%10,z[(a*b>9)+1],d<-a*b,0:9,z[((f=d%%10*0:9)>9)+1],f)
```
[Try it online!](https://tio.run/##K/r/v8o2WcNAR11dk6sgsbgk1UAj0UbX0MDAytLSUlVfFcjSSbLRBXHBPJ2qaI1ErSQ7S01tw1idFBtdIEcHKAsS10izTVEFqtEC8jWhKtI0//8HAA "R – Try It Online")
(Note on `z=c(0,'')`: we need to 'pad' the single digit products with a zero when building our text string, and this needs to be done in way that's compatible with the vectorized `paste` function. So `z[(a*b>9)+1]` is equivalent to (but shorter than) `ifelse(a*b>9,'',0)`)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 27 bytes
```
föΛo§=oΠ←od→C2§e←→X4dfo=7LN
```
[Try it online!](https://tio.run/##yygtzv7/P@3wtnOz8w8tt80/t@BR24T8lEdtk5yNDi1PBXKAzAiTlLR8W3Mfv///AQ "Husk – Try It Online")
returns the list of all meeker numbers. It's horribly inefficient, so [here's a version which starts from 1e7, and shows the first n values.](https://tio.run/##yygtzv7//1HbxLTD287Nzj@03Db/3IJHbRPyUx61TXI2OrQ8FcgBMiNMUh41NXIBFebbmvscWggUMjQAg////xsaAAA)
**EDIT:** corrected the answer after Dominic Van Essen found a bug.
[Answer]
# [Perl 5](https://www.perl.org/), ~~58~~ 56 bytes
```
/(.)(.)(.(.))(.)/,$1*$2-$3||$5*$4-$'||say for 1e6..1e7-1
```
[Try it online!](https://tio.run/##K0gtyjH9/19fQ08TjIAEiKGvo2KopWKkq2JcU6NiqqVioquiXlNTnFipkJZfpGCYaqanZ5hqrmv4//@//IKSzPy84v@6vqZ6BoYGAA "Perl 5 – Try It Online")
Outputs the entire list of Meeker numbers.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~32~~ 24 bytes
```
θsт+2£DSPsт*+ìD2.£SPsт*+
```
[Try it online!](https://tio.run/##yy9OTMpM/f//3I7ii03aRocWuwQHAFla2ofXuBjpHVoM5f3/b2xiCgA "05AB1E – Try It Online") Outputs the \$n^\text{th}\$ Meeker number.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 86 bytes
```
_=>[...Array(1e7).keys()].filter(x=>(s=x+'')[0]*s[1]==s[2]+s[3]&&s[3]*s[4]==s[5]+s[6])
```
[Try it online!](https://tio.run/##HcjbCsIwDADQv9kSh8F5fcrA7yhBykxlWlZphmxfX50v5@E8/cdbn4f3tB3TXUvgcuPOEdE1Z79Aqxekly4GKBSGOGmGmTswnpu6RreTjblWmM3tpTF3kKpa/e3xv6d1z4KlT6OlqBTTAwIgli8 "JavaScript (Node.js) – Try It Online")
I feel like this is too long.
# Explanation
Basically, this gets all numbers from 0 to 9999999, coerces each to a string and checks character-wise.
One of Javascript's quirks is that multiplied strings are coerced to numbers, but added ones are not. So `'5'*'6'` is 30, but `'5'+'6'` is 56.
So in `s[0]*s[1]==s[2]+s[3]`, the first half is a number which is the product of the first two, the second half is the two cocatenated into a string, and using == allows type conversion.
Since it gets the numbers from 0 to 9999999, the numbers from 0 to 999999 are invalid and shouldn't be counted. Fortunately, since the number is coerced to a string, taking its 6th (0-indexed) character will return undefined, so it will be counted as invalid.
[Answer]
# [Haskell](https://www.haskell.org/), ~~82~~ ~~80~~ 76 bytes
* -6 bytes thanks to [kops](https://codegolf.stackexchange.com/users/101474/kops), for rearranging things and proposing a better interpretation of the rules :P
```
[n|n<-show<$>[1..],[a,b,c,d,e,f,g]<-[read.pure<$>n],a*b==10*c+d,d*e==10*f+g]
```
[Try it online!](https://tio.run/##Jc2xDsIgFEDRX2Ho1D6adjQBv0AnRyTmFR7UtEUCNC5@u2h0u8NJ7ox5oXWtG9FCSV6rCq8geJ4fT9Ec1dj3GhTCBAYsEDjwWnCVCG0f90RfEzRgO0k5Dq3pLNiWfu06r@uG9yA3jOcbi3u5lHQKrGEFF2KHYWD/aX0bt6LPlZsYPw "Haskell – Try It Online")
The list of all Meeker numbers, represented as strings.
# [Haskell](https://www.haskell.org/), 80 bytes
```
[n>>=show|n@[a,b,c,d,e,f,g]<-mapM([0..9]<$id)[1..7],a>0,a*b==10*c+d,d*e==10*f+g]
```
[Try it online!](https://tio.run/##Jc29DsIgFEDhV@ngoPSW0MmYFOID6OSIxNzy0zYFJKXGxWcXo25n@XJGzLP1vgRrZ7vwa5FRCJ7H@/MVjxKhBw0GLDgYVNcETOetZJQeVLeZzE62lO4VoGCApOe8ZUTXBgyxv3b1oErAKfIvvFXpsV7W5RSr/628tfM45NLolD4 "Haskell – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~34~~ ~~31~~ 30 bytes
```
₁`:%10¹d₁↑2d+100
§+o*100doΠ↑_2
```
[Try it online!](https://tio.run/##yygtzv7//1FTY4KVqqHBoZ0pQOajtolGKdqGBgZch5Zr52sBGSn55xYAReON/v//b2xiCgA "Husk – Try It Online") or [Get the whole meeker sequence](https://tio.run/##yygtzv6f@6ip8WiDpYHB/0dNTQlWqoYGh3amAJmP2iYapWgbGhhwHVquna8FZKTkn1sAFI03@v8fAA)
*Calculates* (rather than brute-forcing) the `n`th meeker number.
Not as short as [Razetime's answer](https://codegolf.stackexchange.com/a/223369/95126), but inspired by [A username](https://codegolf.stackexchange.com/users/100664/a-username)'s comment "I wonder if anyone isn't going to brute-force it..." underneath it.
A nice feature of this approach is that it actually completes the task, although there were obviously never any brownie-points on offer for achieving this questionable goal…
**How?**
```
§+o*100doΠ↑_2 # helper function (₁):
# takes a list of digits, and returns the number formed
# by appending the product of the last 2 digits.
§+ # Add together
oΠ # product of
↑_2 # last 2 digits, and
o*100 # 100x
d # the number represented by the digits
₁`:%10¹d₁↑2d+100 # main program:
+100 # add 100 to the input,
d # get the digits,
₁↑2 # apply helper function ₁ to the first 2 digits,
d # and convert this back into a list of digits;
`: # now append with
%10¹ # the input modulo 10 = last digit of input;
₁ # finally apply helper function ₁ to the result
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~20~~ 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 thanks to [Makonede](https://codegolf.stackexchange.com/users/94066/makonede) (Output first \$n\$ instead of the \$n^\text{th}\$.)
```
DḌ,PƊƝFḊm3⁼2/Ạ
ȷ6Ç#
```
A monadic Link accepting an integer, \$n\in[1,900]\$, that yields the first \$n\$ Meeker numbers
**[Try it online!](https://tio.run/##ASsA1P9qZWxsef//ROG4jCxQxorGnUbhuIptM@KBvDIv4bqgCsi3NsOHI////zIw "Jelly – Try It Online")** Very slow so will probably time out for \$n \gt 36\$.
### How?
```
ȷ6Ç# - Main Link: integer, n
ȷ6 - 10^6
# - find the first n integers starting at 10^6 for which:
Ç - call Link 1
DḌ,PƊƝFḊm3⁼2/Ạ - Link 1: integer, x e.g. 9218756
D - digits (x) [9,2,1,8,7,5,6]
Ɲ - for neighbours:
Ɗ - last three links as a monad f([a,b]):
Ḍ - from digits ([a,b]) [92, 21, 18, 87, 75, 56]
P - product ([a,b]) [18, 2, 8, 56, 35, 30]
, - pair [[92, 18], [21, 2], [18, 8], [87, 56], [75, 35], [56, 30]]
F - flatten [92, 18, 21, 2, 18, 8, 87, 56, 75, 35, 56, 30]
Ḋ - dequeue [18, 21, 2, 18, 8, 87, 56, 75, 35, 56, 30]
m3 - modulo-3-slice [18, 18, 56, 56]
2/ - pairwise reduce by:
⁼ - equal? [1,1]
Ạ - all? 1
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 75 bytes
```
n->{int a=n/100+1,b=n/10%10;return(a*1e3+b*100+a*b)*1e3+n%10*(100+a*b%10);}
```
[Try it online!](https://tio.run/##NU7LasMwELz7K5YUg/yIKpNT67pQKIUeekpvpQfZlsI6tmSkdSCEfLsrO@lhmZmdfUwnT3LbtccZh9E6gi5oPhH2XE@mIbSGp2XU9NJ7@JJo4BIBjFPdYwOeJAU4WWxhCB7bk0Nz@PkF6Q4@WUcBPg1923cbVtTH/SToCmazfb2gIZCVeSyEyIq8XllciNIpmpxhMi3ULqvTxZZpnazShIGU3VuBJ@V1LtdP2jpgy0mECkQZ4AWexEKy7D8NwP7sSQ3cTsTHEJc02wxKHZWDh7h9hpgLHZtNDpiD5nIc@/Obv8VnmCS3T9doqev8Bw "Java (JDK) – Try It Online")
Outputs the nth number, 0-indexed.
## Credits
* -2 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes
```
F…χ¹⁰⁰Fχ⟦⪫⟦ι﹪%02dΠικ﹪%02d×﹪Πιχκ⟧ω
```
[Try it online!](https://tio.run/##ZY1BCgIxDEWvEgpCAhFSt95AEETcDbMonVGDtYE6ev04I4ILl/@9Bz9fU8uWivvZGuAx1cuIURiiCBF8YBSCQ9M6Ybczrdgpw96GZzEMK9kMgWc97zyhEjHc/vRJ7@MDv/DXLi9LT9QzhEA9bd19/Spv "Charcoal – Try It Online") Link is to verbose version of code. Prints all 900 Meeker numbers. Explanation:
```
F…χ¹⁰⁰
```
Loop over all possible first pairs of digits.
```
Fχ
```
Loop over all possible fifth digits.
```
⟦⪫⟦...⟧ω
```
Print the following items on one line and then move to the next line.
```
ι
```
The first two digits.
```
﹪%02dΠι
```
The product of the first two digits, left zero-padded to 2 digits.
```
κ
```
The fifth digit.
```
﹪%02d×﹪Πιχκ
```
The last two digits.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 58 bytes
```
A(/%Q100T+1/Q100)A(*GH*%*GHT%QT)s[+T/QT*"0"<GTG%QT*"0"<HTH
```
[Try it online!](https://tio.run/##K6gsyfj/31FDXzXQ0MAgRNtQH0RrOmpouXtoqQKJENXAEM3iaO0Q/cAQLSUDJRv3EHdVKNMjxOP/fwtLSwA "Pyth – Try It Online")
Same as my Python solution. `A` assigns the two provided elements to the variables `G` and `H` respectively. `Q` is the input (zero-indexed).
[Answer]
# Scala, 103 bytes
```
Stream from 1 map "".+filter{x=>x.size==7&&x.map(_-48).sliding(4,3).forall{x=>x(0)*x(1)==10*x(2)+x(3)}}
```
[Try it in Scastie!](https://scastie.scala-lang.org/09IQr03XSVWZtsGNkF8Kmg)
A pretty straightforward answer. You can treat it like a function giving the nth Meeker number (0-indexed) or as a list of all Meeker numbers.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 65 bytes
```
999*¶
$.`
G`...
;
+`(.);(.)
$1$2,0$.($1*$2*
;|,0?(?=...,|..;)
```
[Try it online!](https://tio.run/##K0otycxLNPz/n8vS0lLr0DYuLhW9BC73BD09PS4uay7tBA09TWsg5lIxVDHSMVDR01Ax1FIx0uKyrtExsNewtwUq1KnR07PW5Pr/HwA "Retina – Try It Online") Outputs all 900 Meeker numbers. Explanation:
```
999*¶
$.`
```
Insert all the numbers from `0` to `999`.
```
G`...
```
Keep only the 3-digit numbers.
```
;
```
Insert separators around all of the digits.
```
+`(.);(.)
$1$2,0$.($1*$2*
```
Multiply the first and second digits, then multiply the last digit of the result by the third digit, inserting an extra `0` prefix for each result.
```
;|,0?(?=...,|..;)
```
Delete unnecessary separators and `0`s.
]
|
[Question]
[
In Excel, the columns range from `A-Z, AA,AB,AZ,BA,..,BZ` and so on. They actually each stand for numbers, but rather are encoded as alphabet strings.
In this challenge, you will be given a string of alphabets, and you must calculate the column it corresponds to.
Some tests:
>
> 'A' returns 1 (meaning that it is the first column)
>
>
> 'B' returns 2
>
>
> 'Z' returns 26
>
>
> 'AA' returns 27
>
>
> 'AB' returns 28
>
>
> 'AZ' returns 52
>
>
> 'ZZ' returns 702
>
>
> 'AAA' returns 703
>
>
>
You can assume that capital letters will be given only.
Shortest bytes win.
Good luck!
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 17 bytes
```
{:26[.ords X-64]}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv9rKyCxaL78opVghQtfMJLb2f3FipUKahpKjkqY1F5TthMSOQmI7IityRFbliKwsClUPWNN/AA "Perl 6 – Try It Online")
Anonymous code block that subtracts 64 from each byte value and converts from base 26 with `Z` overflowing to the next column.
[Answer]
# Google Sheets, 21 bytes
(formula evaluates to the result, takes input from cell A1)
```
=column(indirect(A1&2
```
[Answer]
# [R](https://www.r-project.org/), ~~48~~ 43 bytes
-5 bytes thanks to @Giuseppe, using the same logic, but as a program that eliminates the `nchar` call.
```
for(i in utf8ToInt(scan(,"")))F=F*26+i-64;F
```
[Try it online!](https://tio.run/##K/r/Py2/SCNTITNPobQkzSIk3zOvRKM4OTFPQ0dJSVNT083WTcvITDtT18zE2u2/o6PjfwA "R – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), 39 bytes
```
s->s.chars().reduce(0,(a,b)->a*26+b%32)
```
[Try it online!](https://tio.run/##ZY89a8MwEIZ3/4rDYJBSW5SUdkgagzoUOnRKp5QO8lcq15aMdA6E4t/uSrLJ0kEn7rn3HqRWXETWVj@z7AdtEFrXsxFlxzb76B9rRlWi1MoPo7IT1sK7kAp@I4BhLDpZgkWB7rpoWUHvZuSIRqrz5xcIc7Y0RAE@9JvC19X2vERyaOAw2yy3rPwWxhLKTF2NZU3uUyLSgma52Gyf7orkYUvnffDc5FhbtHBY9QAxj1OIX3w5@cJDzwPggZxWzuOwMi3CRhtYnxycu8VMb@Lj1WLdMz0iG1wKGxInj3YHSZUoJ/TpFBomhqG7cut@STyidNFPkT/T/Ac "Java (JDK) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~52~~ 45 bytes
```
t=0
for c in input():t=26*t+ord(c)%64
print t
```
[Try it online!](https://tio.run/##JYyxCsJADIbn5imyyLW6SJEOhQ5XqKuLi930Gmmp9I6Qon3686KQ/ycfH0nYZPRLGZ0fCBs0xkRpjvD0jA6nJU1YJS9qacpqLwfPQ@6KXXWCwNMiKDFdALzH6UV45ZVqyIS31Bl9yOX6toC0OwqC3eXcMXtW/WC6z9FYA6ZN6VOsglWyiq1if9P6259O/gs "Python 2 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
```
Çžx-₂β
```
[Try it online!](https://tio.run/##yy9OTMpM/f//cPvRfRW6j5qazm36/z8qCgA "05AB1E – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~38~~ ~~34~~ 31 bytes
```
foldl(\o->(o*26-64+).fromEnum)0
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzPy0/JyVHIyZf104jX8vITNfMRFtTL60oP9c1rzRX0@B/bmJmnoKtQkFRZl6JgopCmoKSo6PS/3/JaTmJ6cX/dZMLCgA "Haskell – Try It Online")
[Answer]
# PHP, ~~41~~ 38 bytes
-3 thanks to Jo King.
```
for($c=A;$c!=$argn;$i++)$c++;echo$i+1;
```
run as pipe with `-nr`
unary output, 34 bytes:
```
1<?for($c=A;$c!=$argn;$c++)echo 1;
```
requires PHP 7.1. save to file, run as pipe with `-nF`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
ØAiⱮḅ26
```
[Try it online!](https://tio.run/##y0rNyan8///wDMfMRxvXPdzRamT2//9/R0dHAA "Jelly – Try It Online")
[Answer]
# APL(NARS), 11 chars, 22 bytes
```
{+/26⊥⎕A⍳⍵}
```
test
```
f←{+/26⊥⎕A⍳⍵}
f¨'A' 'AA' 'AAA'
1 27 703
f¨'AB' 'ZZ' 'Z'
28 702 26
```
[Answer]
# [J](http://jsoftware.com/), 11 bytes
```
26#.64|3&u:
```
[Try it online!](https://tio.run/##y/qvpKegnqZga6WuoKNQa6VgoADE/43MlPXMTGqM1Uqt/mtypSmoO6qDyBAwGQUmHSFUFJTn6Kj@HwA "J – Try It Online")
### How it works
```
26#.64|3&u: Monadic verb. Input: a string.
3&u: Convert each character to Unicode codepoint
64| Modulo 64; maps A -> 1, ... Z -> 26
26#. Interpret as base-26 digits and convert to single integer
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 48 bytes
```
f=([h,...t],p=0)=>h?f(t,p*26+parseInt(h,36)-9):p
```
[Try it online!](https://tio.run/##JcjRCsIgFIDhx/Gc5SQKBhUu3F2vsLELWZqLpYcpsbe3SRf/xfe/9VfHaZ0p1T48Tc5WwuC4ECKNnOQRZevuFhKn6tQcSK/RPHwCx88N1he8Ur5NwcewGLGEFwxMMc66vX5PFagiVdj/n2Kj@GiCTbYWNkTMPw "JavaScript (Node.js) – Try It Online")
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 11 bytes
```
⎕A∘⍳⊥⍨26⍴⍨≢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbhEd9Ux0fdcx41Lv5UdfSR70rjMwe9W4B0o86FwEVKKg7qnMBSScwGQUmHSFCjhAxR4hgFEzOUR0A "APL (Dyalog Classic) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 20 bytes
```
[:(#.~26$~#)32|a.i.]
```
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8D/aSkNZr87ITKVOWdPYqCZRL1Mv9r8ml5KegnqarZ66go5CrZVCWjEXV2pyRr5CmoK6ozqc6YRgRiGYjkgqHJGUOCKpiUJR76j@HwA "J – Try It Online")
## Explanation:
```
[:(#.~26$~#)32|a.i.]
i. - indices
] - of the characters of the input
a. - in the alphabet
32| - mod 32
[:( ) - apply the following code to the above
$~ - create a list of (left and right arguments exchanged)
26 - the number 26
# - repeated the length of the input times
#.~ - to base (26)
```
[Answer]
# Google Sheets, 100 bytes
(formula evaluates to the result, takes input from cell A1)
```
=sum(arrayformula(
(
code(
mid(A1,row(indirect("1:"&len(A1))),1)
)-64
)*26^row(indirect("1:"&len(A1)))/26
```
All spaces are added for clarity only.
*Note*.
* I don't know if it's possible to remove the duplication of `row(indirect("1:"&len(A1))`.
* Although Google Sheets has a `decimal` function, the transliteration would takes a lot of bytes.
[Answer]
# APL+WIN, 12 bytes
Index origin 1.
```
26⊥¯65+⎕av⍳⎕
```
[Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/4bmT3qWnpovZmpNlAisexR72Yg/R8o9T@NS93R0VEdAA "APL (APL+WIN) – Try It Online")
Explanation:
```
⎕av⍳⎕ Prompts for input and gets Ascii integer value for each character
¯65+ subtracts 65 to give integers 1-26 for A-Z
26⊥ converts resulting vector from base 26 to single integer
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 10 bytes
```
I↨²⁶ES⊕⌕αι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwymxOFXDyExHwTexQMMzr6C0JLgEKJuuoamj4JmXXJSam5pXkpqi4ZaZl6KRqKOQqQkG1v//Ozr91y3LAQA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
S Input string
E Map over characters
ι Current character
α Uppercase alphabet
⌕ Find index
⊕ Increment
²⁶ Literal 26
↨ Base conversion
I Cast to string
Implicitly print
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 92 bytes
```
static int m(String v){int x=0;for(int i=0;i<v.length();i++)x=x*26+v.charAt(i)-64;return x;}
```
[Try it online!](https://tio.run/##fZCxboMwEIbn@ilOTHZRUBpVWRwGZ@yajaqDQyi5FAyyjUUV8ezEBKdTgyXLd7rP@n7dRTq5upx@RsgraQx8@F60bYW5tNiotzVcCQGA6ULbHf0AjPWzHFyDJ6glKnqwGlX5@QVSl4b5HxDOXLwcfo0t6qTpbNJ60laKRiKN4to/EWOc/EvsZ2L/nMhmIntOiIdmwSOCSCyYRFCJBVf2iLOY5y/QPRGQgQAZw0Y9BHXYJjh2nfo@XfPvRtOpRl/jziVVoUp7poxjHLM@7V8329gl@VlqYSmy1fad68J2WkHPh3EYbw "Java (JDK) – Try It Online")
**Output**
>
> A=1
>
>
> B=2
>
>
> Z=26
>
>
> AA=27
>
>
> AB=28
>
>
> AZ=52
>
>
> ZZ=702
>
>
> AAA=703
>
>
>
[Answer]
# [MATL](https://github.com/lmendo/MATL), 11 bytes
```
0w"26*@+64-
```
[Try it online!](https://tio.run/##y00syfn/36BcychMy0HbzET3/391R0dHdQA "MATL – Try It Online")
[Answer]
# [Kotlin](https://kotlinlang.org), 36 bytes
```
{it.fold(0){o,n->o*26+n.toInt()-64}}
```
[Try it online!](https://tio.run/##LYyxCsIwFEV3v@KR6UXbIiIdihbi5uTg1i0gKcH0paRPQUK@PbbVOxy4h8t9enaW8ls7MA3eOVjqZdleieEMOVqujHcP3MvoCypbvz3UO6rYzwOUZX1MKZsXwaAtoQ791IAKQX9Ov6dWxg3McXbim0GhRAHisqBboNauVqFW0/29ErIa9AhxnG/YERq0LGXapPwF "Kotlin – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 18 bytes
```
->s{[*?A..s].size}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1664OlrL3lFPrzhWrzizKrX2f4FCWrSSo1IsF4QBZP0HAA "Ruby – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~46~~, 43 bytes
```
a;f(int*s){for(a=0;*s;)a=*s++%64+a*26;s=a;}
```
[Try it online!](https://tio.run/##Zc1Na8JAEAbgs/6KYUTYTRRsqrG4LGUFC6JQ8OMiXpZ0VwIaJSO0EPLXu66hWoyXObzPzLxJd5ckzmlhWZqdA@KFPeZMy54ISHAtAwrDdtwPdRDFgqQWpWt9GZtmBtRyOVmsmPk5cWCFv4bcEEioEnHKfWIZKiKTn6FNI8CWF9xm2LluvuPnDEf4oabz9WKCXJS8edBpxnjRbPz9tmyOCjkASOnHCxcPNP6nqEabO0VxjVT1saJhncZ3eqvT5kaDp64bDXvRU9e1rKJXT6X7Texe78h1vy8 "C (gcc) – Try It Online")
## Degolf
```
a; f(int*s)
{ for(a=0;*s;) // Loop through s, which is a null-terminated string.
a=*s++%64 + a*26; // Multiply accumulated value by 26, and add current char modulo 64 to it.
s=a;} // Return the accumulated value.
```
[Answer]
# [Ahead](https://github.com/ajc2/ahead), 22 bytes
```
>jvi'@-\26l
^~>O@ ~+*<
```
[Try it online!](https://tio.run/##S8xITUz5/98uqyxT3UE3xsgshyuuzs7fQaFOW8vmf1ppnkJuYmaeRmJRerGVgmNRUWKlTXBJUWZeup2mQjWXAhCUJeYoJOfnKNgqaBQBzfLJzEvV0FSwt1JQUtIEKygAKi/RACopzc0DUZqaXLX/HR0dAQ "Ahead – Try It Online")
[Answer]
## [MBASIC](https://archive.org/details/BASIC-80_MBASIC_Reference_Manual), 84 bytes
```
1 INPUT S$:L=LEN(S$):FOR I=1 TO L:V=ASC(MID$(S$,I,1))-64:T=T+26^(L-I)*V:NEXT:PRINT T
```
Output:
```
? AZ
52
? ZZ
702
? AAA
703
```
[Answer]
# x86 machine code, 19 bytes
```
00000000: 31c0 8b19 83e3 3f41 b21a f7e2 01d8 3831 1.....?A......81
00000010: 75f0 c3 u..
```
Assembly:
```
section .text
global func
func: ;this function uses fastcall conventions
xor eax, eax ;reset eax to 0
loop:
;ebx=*ecx%64
mov ebx, [ecx] ;ecx is 1st arg to this func (in fastcall conventions)
and ebx, 63 ;because 64 is a pwr of 2,n%64=n&(64-1)
;ecx++ get next char in str by incrementing ptr
inc ecx
;eax=eax*26
mov dl, 26 ;using an 8bit reg is less bytes
mul edx
;eax+=ebx //(eax=(*ecx%64)+(eax*26))
add eax, ebx
;if(*ecx!='\0')goto loop
cmp byte [ecx], dh ;dh==0
jne loop
ret ;return value is in eax
```
[Try it online!](https://tio.run/##bVRRb5swEH6GX3GL2gJJSNI0yrZQKrVap73tvSWKjDGEjtjINilVmt@enR22JVORML677@6@O59JiVofKNFwe/v48zvcwVhv6jEZEbWBCLj5hDmr8pvpqSUUR4mKjI0EAhldC/BYq5nksFoRrWWZNpqtVr6fE6UpqaoggJJryBtOfbomsh9EG1JyP9hZSTOln5fxrnffG/bu7fKAy9OTFVGe7KNcSN/EKONJZPHlMioHg6CWqM393qVawGWW8N6wsw5ttk4Igmjv/SlR6SYd0ShxE7eg9LwirPcUdFZryEVYlwzCzc3Ueov0JWs2NYTfznCYJmNbjJAxKc@B6gz4DpqxUzBqCskQ9wje8yT8utzN9uChljYawhQ@h7Pph15aQpiBl3Dvn2AdLdSkbNtspFsN769YMUULef0F3s62Dy6ux9O9gR@7Cb2E9/v9hzfNgIqG6wVKCb9U2F648M3MhMEHZdpRCFnn/oO1pmjcLXpwdzWNADlAiOTq/ygZgwEk7tlBHBSjuhQcRhrHy3WKSqSkslPkmmXh4BPpdamszkIbxVDqxg7J8y3jxqBcpxUSGGmHZkE/yRTTZg9awMR1KiHqhYsGlrZxn9H2cj5DcSO2gJohPKNqiVbaAia8VhqILIzvXwKAA/ph7gDjEJ4d48xvnChllCBTmM9MLAL1qwSRw3TIMWnMr/z5LLwOXMuGtoOB4xTIlWMXwFwYvEyg8JTTN9xRyTYmDy@g1hJdUIWXssWd9SdtjG9/Ou@KyaohTOdO1CjjQjh8SUsNkhWGSsWUwrB4awy6qYBlJ4EGMVYA47Fvgvpdj4KBf4wf2DKzrGty2lr@ZW6Bn2IvmXhBIbBhptNoonghTKpjZ4eQrSHK1nGMZ@G8cNbBJNOOPS3d4P9lS6qGGaLYAUxzwB/X4Tc "Try It Online")
[Answer]
# Japt `-h`, 10 bytes
```
åÈ*26+InYc
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=5cgqMjYrSW5ZYw==&input=IkFBQSIKLWg=)
Or without a flag. The first byte can be removed if we can take input as a character array.
```
¨c aI̓26
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=rK5jIGFJw+wyNg==&input=IkFBQSI=)
---
## Explanation
```
åÈ :Cumulatively reduce by passing each character at Y through a function, with an initial total of 0
*26 : Multiply current total by 26
-I : Subtract 64
n : Subtracted from
Yc : The codepoint of Y
:Implicitly output the last element of the resulting array
```
[Answer]
# [Kotlin](https://kotlinlang.org), 29 bytes
```
{it.fold(0){a,v->v-'@'+a*26}}
```
[Try it online!](https://tio.run/##LY7NCoJAFEb3PsWHG@dWRrRoIWnNMmjXE1zyh6HxGtMohPjsk2Xf5mwOh@/ReWskDGxx72zfSgZ1885IQ0gLXMQjD6Px27qzpdrRyJshLYY0OSdrXu0P0xTqXtCyEcWueWXQzvH7uDQKwhhh3r@PHMpVXF6NVIpwyhDH9BOes@7VcuELomgKWusP "Kotlin – Try It Online")
## Explained
```
val column: (String) -> Int = { // String in, Int out
it.fold(0) { a, v -> // acc, value
v - '@' // distance of char from @ (A=1 etc.)
+ a * 26
}
}
```
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-nl`, 39 bytes
```
p$_.chars.reduce(0){|x,y|26*x+y.ord-64}
```
[Try it online!](https://tio.run/##KypNqvz/v0AlXi85I7GoWK8oNaU0OVXDQLO6pkKnssbITKtCu1IvvyhF18yk9v9/Ry4nriguR0cuRycuxyiuKBDb8V9@QUlmfl7xf928HAA "Ruby – Try It Online")
]
|
[Question]
[
Given a positive integer `n` (***Example: `n=1234444999`***)
* Separate into consecutive digit runs:
+ `[1, 2, 3, 4444, 999]`
* Take the digital product of each run.
+ `[1, 2, 3, 4*4*4*4, 9*9*9] = [1, 2, 3, 256, 729]`
* Sum it...
+ 991
* Repeat until this converges to a single number:
+ 1234444999
+ 991
+ 82
+ 10
+ 1
* Return last number.
---
# Test Cases
```
BASE CASES:
0 = 0
...
9 = 9
OTHER CASES:
1234444999 = 1
222222222222222 = 8
111222333444555666777888999000 = 9
11122233344455566677788899 = 8
1112223334445 = 6
14536 = 1
99 = 9
```
# Requested Example:
```
334455553666333
9+16+625+3+216+27
896
8+9+6
23
2+3
**5**
```
# Winning?
It's [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest byte-count is the winner.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~7~~ ~~6~~ 5 bytes
Thanks to *Emigna* for saving a byte!
```
vSγPO
```
Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f@/LPjc5gD///8NDQ2NjIyMjY1NTExMTU3NzMzMzc0tLCwsLS0NDAwA "05AB1E – Try It Online")
[Answer]
# Jelly, 9 bytes
```
DŒgP€SµÐL
```
[Try it online](https://tio.run/##y0rNyan8/9/l6KT0gEdNa4IPbT08wef///9GqAAA)
Here's how it works:
```
D - input as a list of digits
Œg - group runs of equal elements
P€ - the product of each element
S - the sum of the list
µ - syntax stuff to separate the left from the right
ÐL - repeat until we get a result twice, then return that result.
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~17~~ ~~15~~ 13 bytes
```
e".+"_¬ò¦ x_×
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=ZSIuKyJfrPKmIHhf1w==&input=IjExMTIyMjMzMzQ0NDU1NTY2Njc3Nzg4ODk5Ig==) Takes input as a string.
Still not satisfied with this answer...
### Explanation
```
e".+"_ ¬ ò¦ x_ ×
e".+"Z{Zq ò!= xZ{Zr*1}}
e".+" Repeatedly replace all matches of /.+/ (the entire string)
Z{ } Z with this function:
Zq Split Z into chars.
ò!= Partition at inequality; that is, split into runs of equal items.
xZ{ } Take the sum of: for each item in Z:
Zr*1 the item reduced by multiplication (i.e. the product).
This procedure is repeated until the same result is yielded twice.
Implicit: output result of last expression
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes
```
Ḋ|ẹḅ×ᵐ+↰
```
[Try it online!](https://tio.run/##AUEAvv9icmFjaHlsb2cy///huIp84bq54biFw5fhtZAr4oaw//8xMTEyMjIzMzM0NDQ1NTU2NjY3Nzc4ODg5OTkwMDD/Wg "Brachylog – Try It Online")
### Explanation
```
Ḋ Input = Output = a digit
| Or
ẹ Split into a list of digits
ḅ Group consecutive equal elements together
×ᵐ Map multiply
+ Sum
↰ Recursive call
```
[Answer]
# Mathematica, ~~55~~ 42 bytes
```
#//.i_:>Tr[Times@@@Split@IntegerDigits@i]&
```
*-13 bytes from @JungHwan Min*. Thanx!
in case someone wants to use this as a random-digit-generator,
here is the tally of the first 100.000 numbers
>
> {{1, 17320}, {2, 4873}, {3, 10862}, {4, 11358}, {5, 10853}, {6,
> 9688}, {7, 11464}, {8, 10878}, {9, 12704}}
>
> *or if you gamble, don't put your money on 2!*
>
>
>
[Answer]
# Pyth, 11 bytes
```
us^M_MrjGT8
```
[Try it online.](http://pyth.herokuapp.com/?code=us%5EM_MrjGT8&input=1234444999&test_suite_input=0%0A1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A1234444999%0A222222222222222%0A111222333444555666777888999000%0A11122233344455566677788899%0A1112223334445&debug=0) [Test suite.](http://pyth.herokuapp.com/?code=us%5EM_MrjGT8&input=1234444999&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A1234444999%0A222222222222222%0A111222333444555666777888999000%0A11122233344455566677788899%0A1112223334445&debug=0)
[Answer]
# [Python 3](https://docs.python.org/3/), 96 bytes
```
from itertools import*
f=lambda n:n*(n<10)or f(sum(int(k)**len([*g])for k,g in groupby(str(n))))
```
[Try it online!](https://tio.run/##jYuxDoMgFEV3v4LxQTqACGrTfknTQVOxpvIgiINfT3FoYocmvds991y/xadDmZIJzpIpDiE6Ny9kst6FyApznTvbPzqCZ2SAF8GpC8TAslqYMMKLMjYPCDc23qnJ0@s0kgnJGNzq@w2WGABpTvJh9w2IUlY5bdtSWnxg@Z3DIoTIQMr9pJTSWtd13TRN/nPO/xJ/SUdeKakPfT@lNw "Python 3 – Try It Online")
[Answer]
## [Husk](https://github.com/barbuz/Husk), 8 bytes
```
ωöṁΠgmis
```
Takes and returns an integer.
[Try it online!](https://tio.run/##yygtzv6fe2J98aOmxqJD2/6f7zy87eHOxnML0nMzi////2/AZchlxGXMZcJlymXGZc5lwWXJZWhkbAIElpaWXEaogMvQ0BBIGRuDFJiampqZmZmbm1tYWADVGhgY4JFGleIyNDE1NuOytAQA "Husk – Try It Online")
## Explanation
Having a built-in for base 10 digits would be nice...
```
ωöṁΠgmis
ω Iterate until a fixed point is found
ö the composition of the following four functions:
s convert to string,
mi convert each digit to integer,
g group equal adjacent integers,
ṁΠ take product of each group and sum the results.
```
[Answer]
## JavaScript (ES6), ~~77~~ ~~73~~ ~~67~~ 65 bytes
*Saved 2 bytes thanks to @CraigAyre*
```
f=s=>s>9?f(''+eval(s.replace(/(.)\1*/g,s=>'+'+[...s].join`*`))):s
```
### How?
The input ***s*** is transformed into an arithmetic expression with:
```
s.replace(/(.)\1*/g, s => '+' + [...s].join`*`)
```
For instance, `1234444999` becomes `+1+2+3+4*4*4*4+9*9*9`.
We evaluate this expression and do a recursive call with the result until it's boiled down to a single decimal digit.
### Test cases
```
f=s=>s>9?f(''+eval(s.replace(/(.)\1*/g,s=>'+'+[...s].join`*`))):s
console.log(f("1234444999" )) // = 1
console.log(f("222222222222222" )) // = 8
console.log(f("111222333444555666777888999000")) // = 9
console.log(f("11122233344455566677788899" )) // = 8
console.log(f("1112223334445" )) // = 6
console.log(f("14536" )) // = 1
console.log(f("99" )) // = 9
```
[Answer]
# [PHP](https://php.net/), 113 bytes
```
for(;9<$a=&$argn;$a=$s){$s=0;preg_match_all('#(.)\1*#',$argn,$t);foreach($t[0]as$v)$s+=$v[0]**strlen($v);}echo$a;
```
[Try it online!](https://tio.run/##HYyxCsIwGIT3Pkb7Y5NapFWXkAYH6eCii5tKCCU2Qm3Dn9BF9NVj6E133x1njQ3NwRqbaMQJJWo7oX@NPfm18ny5no4t5Qko7EeR1tvdPooxlvLwnJBw1oASq6Xm0YGjH3Ci4hZ1L9/Kd0aqYSB5Rjb0XhdZXi7bEjzl8UCrzhDwt@qhHMwU3FrAHFNROI@DHkmE/Ks7M4HiIfwB "PHP – Try It Online")
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 22 bytes
```
r_,{1/e`Wf%::i::#:+s}*
```
[Try it online!](https://tio.run/##S85KzP3/vyhep9pQPzUhPE3VyirTykrZSru4Vuv/f0NDQyMjI2NjYxMTE1NTUzMzM3NzcwsLC0tLSwMDAwA "CJam – Try It Online")
[Answer]
# Braingolf, 25 bytes
```
!L1-Mv[RG(d&*)&+!L1-Mv>]R
```
Will add a TIO link once I get Dennis to pull the latest version, as using greedy operators inside `(...)` loops is currently broken on TIO
## Explanation
```
!L1-Mv[RG(d&*)&+!L1-Mv>]R Implicit input from commandline args
!L1-M Push length of input minus 1 to stack2
v Switch to stack2
[.........!L1-Mv>] While length of input > 1..
RG Split into digit runs
(d&*) Product of digits of each item in stack
&+ Sum stack
R Return to stack1
Implicit output from stack
```
[Answer]
# [Haskell](https://www.haskell.org/), 103 70 69 bytes
```
import Data.List
until(<10)$sum.map product.group.map(read.pure).show
```
[Try it online!](https://tio.run/##fYq7CsIwGEZ3n@IfHBIoIWlsm4LdHPUJRCTY1oY2F3LBx4/p6OJZPvjOWWRYp23LWWlnfYSLjJJcVYiHeUgmqg2dGcXHkDTR0oHzdkyvSN7eJrc/yE9yJC75CZOw2E/WUhkYoKjbE5DzykQgMGO4s5qfCn3fV1D/UgFjrCzne9I0Tdu2XdcJIUpNKf3nH/kL "Haskell – Try It Online")
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), ~~17~~ 23 bytes
+6 bytes from handling cases where the same digit is present in multiple chunks
```
{+/*/'(&~=':x)_x:10\x}/
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NqlpbX0tfXUOtzlbdqkIzvsLK0CCmolb/f5q6oqEBV5q6oZGxCRBYWloqGKECBUNDQyBlbAxSYKpgaGJqbKYAVAbimwKBsZmZGVDyPwA "K (ngn/k) – Try It Online")
* `{...}/` run a converge reduction over the input
* `x:10\x` convert input to a list of digits, updating `x`
* `(&~=':x)` identify indices where the value differs from the previous element
* `(...)_x` split the list of digits on those indices
* `*/'` take the product of each chunk
* `+/` add those products together
Fails on inputs too large for 64-bit integers.
[Answer]
# MATL, 11 bytes
```
`!UY'^sVtnq
```
Try it at [MATL Online](https://matl.io/?code=%60%21UY%27%5EsVtnq&inputs=%27111222333444555666777888999000%27&version=20.2.0)
**Explanation**
```
% Implicitly grab input as a string
` % Do...while loop
!U % Convert the string to an array of numbers (the digits)
Y' % Perform run-length encoding
^ % Raise the digits to the power corresponding to the number of times they
% occurred consecutively
s % Sum the result
V % Convert to a string
tn % Duplicate and determine the number of characters in the string
q % Subtract one, causes the loop to continue until it's a single digit
% Implicit end of do...while loop and display
```
[Answer]
# [R](https://www.r-project.org/), ~~114~~ 104 bytes
```
n=scan(,'');while(nchar(n)>1){n=el(strsplit(n,''));b=table(n);n=as.character(sum(strtoi(names(b))^b))};n
```
reads from stdin; returns the answer as a string.
[Try it online!](https://tio.run/##FcpBCoAgEAXQ4zQDEbQWO0owipBgv3AmWkRnt1y83autwWsU0DgM7O4tl0SIm1QCLzM/8KmQWtWzZCP0xS54k9AjO3jRqX@JlirptfdtRybInpQC8/p7HVr7AA "R – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 50 bytes
49 bytes of code + `-p` flag.
```
s/(.)\1*/"+".$&=~s%.%$&*%gr.1/ge while($_=eval)>9
```
[Try it online!](https://tio.run/##VcpBCsIwEEDR/ZwixqS0FSdO0oiDxJMUiovQCkFCC7rz6jEu/Zu3@TmuyZf9LlfFMZfNtNiN1Bt5kKia8Nk0atX0el6RzBzFe3mk2KopxNc9dTcuV6EmgUHI8SnLCQgsXICBrBtqzAz2PyCiinO/wQMN3p2B@Qs "Perl 5 – Try It Online")
[Answer]
# R, ~~97~~ 96 bytes
```
a=scan(,"");while(nchar(a)>1){a=paste(sum(strtoi((b<-rle(el(strsplit(a,""))))$v)^strtoi(b$l)))}a
```
Slightly different approach than the [other answer](https://codegolf.stackexchange.com/a/132030/56131) using **R**.
This answer makes use of the `rle` function, which `compute[s] the lengths and values of runs of equal values in a vector`.
*-1* bytes thanks to @Giuseppe !
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 19 bytes
```
=ò¦ m¬®×Ãx)<A?U:ßUs
```
[Try it online!](https://tio.run/##AUIAvf9qYXB0//89w7LCpiBtwqzCrsOXw4N4KTxBP1U6w59Vc///IjExMTIyMjMzMzQ0NDU1NTY2Njc3Nzg4ODk5OTAwMCI "Japt – Try It Online")
## Explanation:
```
=ò¦ m¬®×Ãx)<A?U:ßUs
= // Implicit U (input) =
ò¦ // Split the input into an array of consecutive digit runs
m¬ // Split each inner array: ["1","22","333"] -> [["1"],["2","2"],["3","3","3"]]
® // Map; At each item:
× // Get the product of each run
à // }
x // Sum
<A // <10
? // If true:
U // return U
: // Else:
ß // Run the program again; Pass:
Us // U, cast to a string
```
[Answer]
# [J-uby](https://github.com/cyoce/J-uby), 45 bytes
```
:!~&(:digits|:slice_when+:!=|:*&(:/&:*)|:sum)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qXLBIjfbpaUlaboWN3WtFOvUNKxSMtMzS4prrIpzMpNT48szUvO0rRRta6y0gHL6alZamkCp0lxNiKb1BQpu0YZGxiZAYGlpGQsRXbAAQgMA)
## Explanation
```
:!~ & (:digits | :slice_when + :!= | :* & (:/ & :*) | :sum)
:!~ & ( ) # Apply the following function until F(x) == x
:digits | # Get digits
:slice_when + :!= | # Group like elements (slice between unequal)
:* & (:/ & :*) | # Map with reduce with product
:sum # Sum
```
[Answer]
# [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3) `g`, 6 bytes
```
ᵡλġᵛΠ∑
```
[Try it Online!](https://vyxal.github.io/latest.html#WyJnIiwiIiwi4bWhzrvEoeG1m86g4oiRIiwiIiwiOTkiLCIzLjQuMiJd)
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
I/O as digit arrays
```
£=òÎx_×Ãì
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=oz3yznhf18Ps&input=WzEsMSwxLDIsMiwyLDMsMywzLDQsNCw0LDUsNSw1LDYsNiw2LDcsNyw3LDgsOCw4LDksOSw5LDAsMCwwXQ)
```
£=òÎx_×Ãì :Implicit input of digit array
£ :Map
= : Reassign to U
ò : Partition between elements where
Î : The sign of their difference in truthy (not zero)
x : Reduce by addition
_ : After passing each through this function
× : Reduce by multiplication
à : End function
ì : Split to digit array
: Implicit output of last element
```
[Answer]
# [Groovy](http://groovy-lang.org/), ~~69~~ 68 bytes
```
f={r->r>9?f((r=~/(.)\1*/)*.tap{}.sum{n->n[1]as int**n[0].size()}):r}
```
Requires Groovy 3.x.
## Explanation
If the input is single digit, returns it, else recursively calls the function on the next pass of the algorithm.
```
f={r->r>9?f(...):r} : Recursively call algorithm if input > 9, else return input
r=~/(.)\1*/) : Regex capture of each run, e.g. [["444", "4"], ["2", "2"]]
*.tap{} : Convert Matcher to List<List<Integer>> so we can call sum()
.sum{...} : Apply the closure to each List element and sum them
n[1]as int**n[0].size() : <digit>^<run length> from e.g. ["444", "4"]
```
[Answer]
# [Uiua](https://uiua.org) [SBCS](https://tinyurl.com/Uiua-SBCS-Jan-14), 20 bytes
```
⍢∘(>9./+⊜/×+1.-@0°⋕)
```
[Try it!](https://uiua.org/pad?src=0_9_0__ZiDihpAg4o2i4oiYKD45Li8r4oqcL8OXKzEuLUAwwrDii5UpCgpmIDAKZiA5CmYgMTIzNDQ0NDk5OQpmIDIyMjIyMjIyMjIyMjIyMgpmIDk5Cg==)
]
|
[Question]
[
## Task
Write a program that will take (as input) a positive integer. It will then count up from `0`, appending each integer to a `String`, only continuing if the length of the `String` is less than the value of the input.
A *serialized* integer is defined as the fully-formed integer with the maximum value belonging to the `String`. By "fully-formed", the integer should have no missing digits (which would occur if the length constraint of the `String` is met).
The output of the program should be the *serialized* integer for its respective, positive input.
---
## Rules
* It's code golf, so the shortest answer (in bytes) wins!
* Input will always be positive.
* The output must be an integer in base-10 (decimal).
* The program must be 0-indexed.
---
## Example Input | Output
```
5 | 4 (0 1 2 3 4 - Length of 5)
11 | 9 (0 1 2 3 4 5 6 7 8 9 1 - Length of 11)
12 | 10 (0 1 2 3 4 5 6 7 8 9 10 - Length of 12)
1024 | 377 (0 1 2 3 4 5 6 7 8 ... - Length of 1024)
```
---
## Note(s)
* If you have any questions (or would like me to provide more examples), please comment!
* Inspiration: <https://stackoverflow.com/questions/45034478/how-do-i-calculate-the-maximum-serialized-integers-in-1024-length-limit>
[Answer]
## JavaScript (ES6), ~~40~~ 37 bytes
```
f=(n,i=s='0')=>(s+=++i)[n]?i-1:f(n,i)
```
```
<input type=number min=1 value=1 oninput=o.textContent=f(this.value)><pre id=o>0
```
Edit: Saved 3 bytes with some help from @Arnauld.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 7 bytes
Idea to use prefixes from [Jonathan's Jelly answer](https://codegolf.stackexchange.com/a/131942/47066)
```
LηJ€g›O
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f59x2r0dNa9IfNezy///f0MDIBAA "05AB1E – Try It Online")
**Explanation**
```
L # range [1 ... input]
η # prefixes
J # join each to string
€g # get length of each string
› # input is greater than string length
O # sum
```
[Answer]
# [Python 2](https://docs.python.org/2/), 55 bytes
Recursive lambda port from @officialaimm's [answer](https://codegolf.stackexchange.com/a/131930/66418).
```
f=lambda k,s='',i=1:k>len(s+`i`)and f(k,s+`i`,i+1)or~-i
```
[Try it online!](https://tio.run/##FcqxDsIgFEDRna94WyGtiRBdmuBWVxc/oGhp@lIE8qDRLv464nhyb9zzErwqZdbOvB6TgbVLumk61LJfL856ntoRR2H8BDOv8a8OWykCfQ9YMu09g/eCzsKdNlsBkdDneqOPW@ZCMPt52phhuF0HokD1iSalcmZSMqmYPKrTDw "Python 2 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 13 bytes
```
1n@P±X l >U}a
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=MW5AULFYIGwgPlV9YQ==&input=MTAyNA==)
### Explanation
```
1n@ P± X l >U}a
1nX{P+=X l >U}a
Implicit: U = input integer, P = empty string
X{ }a Return the first integer X in [0, 1, 2, ...] that returns a truthy value:
P+=X Append X to P.
l >U Return P.length > U.
This returns the first integer that can't fit into the U-char string.
1n Subtract 1 from the result.
Implicit: output result of last expression
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11 10 9~~ 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ẈÄ<⁸S
```
A monadic link taking a positive integer and returning a non-negative integer.
**[Try it online!](https://tio.run/##y0rNyan8///hro7DLTaPGncE////39DAyAQA "Jelly – Try It Online")**
### How?
```
ẈÄ<⁸S - Link: positive integer, n
Ẉ - length of (implicit decimal digits) of each of (implicit [1..n])
Ä - cumulative sums
⁸ - n
< - (cumulative sum) less than (n)?
S - sum
```
[Answer]
# [PHP](https://php.net/), 56 bytes
```
for(;$argn>$l=strlen($r);)$r.=+$i++;echo$i-1-($argn<$l);
```
[Try it online!](https://tio.run/##HcqxCoMwFAXQ3c@QNyQEC5mfaYeSwcUu3UUkNYGQPK7O/fUIrocjUdr4kihdACoWBKk4U9nV3y/z5zu9veaOVuzF9db23H4Vim94UnbHiRyKImjWhIczlIzhsMVKabCDuuNIWXNrFw "PHP – Try It Online")
[Answer]
# [Haskell](http://haskell.org/), ~~55~~ ~~53~~ 50 bytes
```
(n#x)a|l<-a++show x=last$x-1:[n#l$x+1|length l<=n]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/XyNPOVGzoibHRjdRW7s4I79cocI2J7G4RKVC19AqOk85R6VC27AmJzUvvSRDIcfGNi/2f25iZp6CrUJKPpcCEBQUZeaVKKgoaJgqKylpKhigChoaYhU1wipqYGQCEVf4DwA)
Usage is `(1024#"") 0`
[Answer]
# [Python 2](https://docs.python.org/2/), ~~60 59~~ 58 bytes
* Thanks @Felipe for 2 bytes
```
i,j,k='',1,input()
while len(i+`j`)<k:i+=`j`;j+=1
print~-j
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P1MnSyfbVl1dx1AnM6@gtERDk6s8IzMnVSEnNU8jUzshK0HTJtsqU9sWyLLO0rY15CooyswrqdPN@v/f0BgA "Python 2 – Try It Online")
[Answer]
# Pyth, ~~8~~ 7 bytes
```
tf<Q=+d
```
[Try it online.](http://pyth.herokuapp.com/?code=tf%3CQ%3D%2Bd&input=11&test_suite_input=1%0A5%0A11%0A12%0A1024&debug=0) [Test suite.](http://pyth.herokuapp.com/?code=tf%3CQ%3D%2Bd&input=11&test_suite=1&test_suite_input=1%0A5%0A11%0A12%0A1024&debug=0)
[Answer]
# [Perl 6](http://perl6.org/), 36 bytes
```
{(0...^{([~] 0..$^a).comb>$_})[*-1]}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WsNAT08vrlojui5WAchUiUvU1EvOz02yU4mv1YzW0jWMrf1vrVCcWKmQpmFoYGSiaf0fAA "Perl 6 – Try It Online")
* `0 ...^ {...}` is the sequence of numbers from zero until one less than the number for which the code block in braces returns true. (`...` without the caret would return the first number for which the block returned true.)
* `[~] 0 .. $^a` is the concatenation of numbers from `0` up to the current number `$^a` (the parameter to the code block).
* `.comb` is a list of all of the characters (digits) in the concatenated string. Interpreted as a number, it evaluates to the length of the string. `.chars` would be more natural to use here, since it evaluates directly to the length of the string, but the name is one character longer.
* `$_` is the argument to the top-level function.
* `[*-1]` selects the last element of the generated list.
[Answer]
# [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 34 bytes
```
{A=!p$~_lB+A|>:|_xp-1|\B=B+A]p=p+1
```
## Explanation
```
{ DO infinitely
A=!p$ Set A$ to p cast to num
Note that p starts out as 0.
~ >: IF the input number is exceeded by
_l | the length of
B+A A$ and B$ combined
_xp-1| THEN QUIT, printing the last int successfully added to B$
The _X operator quits, (possibly) printing something if followed by a-zA-Z
_x is slightly different, it prints the expression between the operator _x and |
\B=B+A ELSE add A$ to B$
] END IF
p=p+1 Raise p, and rerun
```
[Answer]
# [Python 2](https://docs.python.org/2/), 44 bytes
```
f=lambda k,i=0:-2*(k<0)or-~f(k-len(`i`),i+1)
```
[Try it online!](https://tio.run/##DYqxDoMgFAB3voIRWm2AtIvR0a5d@gFai/FFBPJ4pnXpr1MuueGSiwctwZsMWwxIPB2JFS/JEtppxwTBO9iAhFYFmefOjdvrPfK1gk41tTmJtVUyYP2bxVo768UAg6zgrGUmPBrGPws4y5@42xI8InjiswAfdxJSMvudbCTeP@49YsDyxDGlrNmNac20YVqZ6x8 "Python 2 – Try It Online")
[Answer]
# J, 26 bytes
```
(>i:1:)([:+/\[:>.10^.1+i.)
((>i:1:)([:+/\[:>.10^.1+i.))"0 ] 5 11 12 1024 2000 20000 100000 1000000
4 9 10 377 702 5276 22221 185184
```
[Answer]
# [R](https://www.r-project.org/), 43 bytes
```
n=scan();sum(cumsum(floor(log10(1:n))+1)<n)
```
[Try it online!](https://tio.run/##FcVBDoIwEAXQfU/hcn7cMA1uUJZegMgBCKnYpExJB9SEcPYCi5eXstbuPyWn6qPQmqXWvhPCXZeR@mU8e4cYE4U4cEFcCXBlPAR5g/l9fHD0atonLlPyMpP7doEUMDdjmA/2UNgy7w "R – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 8 bytes
```
#ȯ<¹ṁLŀḣ
```
[Try it online!](https://tio.run/##ARwA4/9odXNr//8jyK88wrnhuYFMxYDhuKP///8xMDI0 "Husk – Try It Online")
About as hard as I could condense it. Pyth is really hard to beat here.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
#<¹∫mLḣ
```
[Try it online!](https://tio.run/##yygtzv6f@6ip8b@yzaGdjzpW5/o83LH4////0aY6hoY6hkY6hgZGJrEA "Husk – Try It Online")
**How?**
```
ḣ # range from 1..input;
mL # get the lengths of string representations of each element;
∫ # get the cumulative sums;
# # how many of these
<¹ # are less than the input?
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 5 bytes
```
ʁvL¦>
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=s&code=%CA%81vL%C2%A6%3E&inputs=1024&header=&footer=)
```
ʁ # 0...n
vL # Get length of each
¦ # Cumulative sums
> # (input) is greater than each?
# (s flag) sum ToS at end
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 13 bytes
```
{(+\#'$!x)'x}
```
[Try it online!](https://ngn.bitbucket.io/k#eJx1zsEOgjAMBuD7nqJGEliMuA4mQl/BN0ASPDg0GkkIhxHEZ7fuJEZ3+demX1pbjNHqsAyDhZOhm4ToizEoh2dXWABwVLdXimp7vNzI0UCdrCbRl4bSigORcp+aUPmP0iklWVYJsRHsDTwg5YwUIGhIfPHx1rA/3Zv+DK0FI1kgssjnwsAWMthxG+cC0RPNBNU/ouZES/E+kgmf+YvEcfy1hcflCz1QQbc=)
Takes input `n` as `x`.
* `(...)'x` run a binary search (returning the index of the largest value equal to or smaller than `x`) on the list generated by...
* `(+\#'$!)`
+ `$!x` stringify each value from `0..x-1`
+ `#'` count the number of characters in each stringified number
+ `+\` take the cumulative sums
[Answer]
# [WendyScript](http://felixguo.me/wendy/), 42 bytes
```
<<f=>(x){<<n=""#i:0->x{n+=i?n.size>=x/>i}}
f(1024) // returns 377
```
[Try it online!](http://felixguo.me/#wendyScript)
## Ungolfed:
```
let f => (x) {
let n = ""
for i : 0->x {
n+=i
if n.size >= x
ret i
}
ret
}
```
[Answer]
# PHP, 41 bytes
```
while(strlen($s.=+$i++)<=$argn);echo$i-2;
```
[Try it online](http://sandbox.onlinephpfunctions.com/code/7b92183c3c7c57cf55f4804879826bcf172a50b2).
[Answer]
# Java 8, 64 bytes
```
n->{int i=0;for(String t="0";;t+=++i)if(t.length()>n)return~-i;}
```
Or slight alternatives with the same byte-count:
```
n->{int i=0;for(String t="";;t+=i++)if(t.length()>n)return i-2;}
n->{int i=-1;for(String t="";;t+=++i)if(t.length()>n)return~-i;}
```
**Explanation:**
[Try it here.](https://tio.run/##hZDBCoJAEIbvPcXQaRdRLOq02BvkxWN02LbVxmyUdQwi7NVtTa8hzAzM/D8fP1Pqpw7rxlJ5vQ@m0m0LR430XgEgsXW5NhbScf0dwIhxklT@0vv21bJmNJACQQIDhYf3aMEkVnntRMYOqQBO1vFaKQ6SIECJueCoslTwTcgDSWe5c/QJUfWDmqhNd6k8dYY/a7zCwwebeaczaDmlyl4t20dUdxw1XuKKBEVG7OUv4199s1kybJcM8XYn50f0wxc)
```
n->{ // Method with integer as both parameter and return-type
int i=0; // Integer `i`, starting at 0
for(String t="0"; // String, starting at "0"
; // Loop indefinitely
t+=++i) // After every iteration: append the String with `i+1`
// by first increasing `i` by 1 with `++i`
if(t.length()>n) // If the length of the String is larger than the input:
return~-i; // Return `i-1`
// End of loop (implicit / single-line body)
} // End of method
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 39 bytes
```
->n{~-(0..n).find{|x|0>n-="#{x}"=~/$/}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vuk5Xw0BPL09TLy0zL6W6pqLGwC5P11ZJubqiVsm2Tl9Fv7b2f0FpSbFCWrRpLBeUZWiIYBohmAZGJrH/AQ "Ruby – Try It Online")
[Answer]
# Ruby, 44 bytes
Inspired by Kevin Cruijssen's JAVA answer. -4 bytes thanks to G B.
```
->n{i,t=0,'';t+="#{i+=1}"while t.size<n;i-1}
```
[Answer]
# [Perl 5](https://www.perl.org/), 31 + 1 (`-p`) = 32 bytes
```
$".=++$\while$_>=length$"}{$\--
```
[Try it online!](https://tio.run/##K0gtyjH9/19FSc9WW1slpjwjMydVJd7ONic1L70kQ0WptlolRlf3/3/Tf/kFJZn5ecX/dQsA "Perl 5 – Try It Online")
]
|
[Question]
[
Your challenge, should you chose to accept it, is to code-golf a function that returns true or false (or some similar meaningful representation of yes and no) if a number meets the following criteria:
1. The integer itself is a prime number OR
2. Either of its neighbor integers are prime
For example:
An input of `7` would return True.
An input of `8` would also return True.
An input of `15` would return False. (Neither 14, 15, or 16 are prime)
The input must be able to return correctly for numbers between 2^0 and 2^20 inclusive, so there's no need to worry about sign issues or integer overflows.
[Answer]
# J, 17
```
*/<:$&q:(<:,],>:)
```
Returns booleans encoded as process return codes: zero for true, nonzero for false. Sample use:
```
*/<:$&q:(<:,],>:) 7
0
*/<:$&q:(<:,],>:) 8
0
*/<:$&q:(<:,],>:) 15
3
```
[Answer]
## Haskell, 47 characters
```
f n=any(\k->all((>0).mod k)[2..k-1])[n-1..n+1]
```
[Answer]
## Python 85 80
```
def f(n):g=lambda n:all(n%i!=0for i in range(2,n));return g(n)or g(n-1)or g(n+1)
```
First time on Code Golf so there's probably some tricks I'm missing.
[Answer]
Not a real contender in code shortness by any means, but still submitting since determining primeness *[by regular expression](http://www.noulakaz.net/weblog/2007/03/18/a-regular-expression-to-check-for-prime-numbers/)* is twisted in many ways!
## Python (2.x), 85 characters
```
import re
f=lambda n:any(not re.match(r"^1?$|^(11+?)\1+$","1"*x)for x in[n,n-1,n+1])
```
[Answer]
# Ruby (55, or 50 as lambda)
```
def f q;(q-1..q+1).any?{|n|(2..n-1).all?{|d|n%d>0}};end
```
or as lambda (use `g[23]` to call it)
```
g=->q{(q-1..q+1).any?{|n|(2..n-1).all?{|d|n%d>0}}}
```
# Coffeescript (53)
```
p=(q)->[q-1..q+1].some (n)->[2..n-1].every (d)->n%d>0
```
[Answer]
The boring **Mathematica, 35** solution!
```
PrimeQ[n-1]||PrimeQ[n]||PrimeQ[n+1]
```
[Answer]
## C, 112 82 72 characters
Following Ilmari Karonen's comment, saved 30 chars by removing `main`, now `P` returns true/false. Also replaced loop with recursion, and some more tweaks.
```
p(n,q){return++q==n||n%q&&p(n,q);}P(n){return p(-~n,1)|p(n,1)|p(~-n,1);}
```
Original version:
```
p(n,q,r){for(r=0,q=2;q<n;)r|=!(n%q++);return!r;}
main(int n,int**m){putchar(48|p(n=atoi(*++m))|p(n-1)|p(n+1));}
```
[Answer]
# Mathematica, 24 bytes
Don't know why this old post showed up in my list today, but I realized Mathematica is competitive here.
```
Or@@PrimeQ/@{#-1,#,#+1}&
```
Unnamed function taking an integer argument and returning `True` or `False`. Direct implementation.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 6 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
Ç▀<╝ºΩ
```
[Run and debug it](https://staxlang.xyz/#p=80df3cbca7ea&i=7%0A8%0A15&a=1&m=2)
Explanation (unpacked):
```
;v:Pv<! Full program, implicit input Example: 7
;v Copy input and decrement 7 6
:P Next prime 7 7
v Decrement 7 6
<! Check if input is >= result 1
```
[Answer]
## JavaScript (71 73 80)
```
n=prompt(r=0);for(j=n-2;p=j++<=n;r|=p)for(i=1;++i<j;)p=j%i?p:0;alert(r)
```
Demo: <http://jsfiddle.net/ydsxJ/3/>
**Edit 1:** Change `for(i=2;i<j;i++)` to `for(i=1;++i<j;)` (thanks `@minitech`). Convert `if` statement to ternary. Moved `r|=p` and `p=1` into outer `for` to eliminate inner braces. Saved 7 characters.
**Edit 2:** Combine `p=1` and `j++<=n` to `p=j++<=n`, save 2 chars (thanks `@ugoren`).
[Answer]
# Regex (ECMAScript), 20 bytes
`^x?x?(?!(x+)(x\1)+$)`
[Try it online!](https://tio.run/##Tc/LbsIwEIXhV4GoghnShKStusA1WXXBhkW77EWywuBMaxzLNpByefYUFpW6/o509H@pnQq1Zxez4HhFftPab/rpvbS0H7yQfu4cwEHOp5P@s6u6CqohdClC915ieoP9ZHrAPLav0bPVgHkwXBM83mYPiCLIQuwbNgRgpCe1MmwJEIfSbo3Bo5YmD85whHE2RsFrACt1bsjq2OD87nTisFRLYOmUD7SwEfRb8YH4B/Qf7LysytmVMTa@3ScLu1OGVwOvrKbZIEmNWLceBD9JEpymeDlMuiT35EhFYMw3KtYNeMRjGI3cJSnCtaIUbhtD9JeJOJ/7Mrsvil8 "JavaScript (SpiderMonkey) – Try It Online")
The above version does not correctly handle zero, but that only takes 1 extra byte:
`^x?x?(?!(x+)(x\1)+$)x`
As an added bonus, here's a version that gives a return match of `1` for one less than a prime, `2` for prime, and `3` for one more than a prime:
`^x?x??(?!(x+)(x\1)+$)x`
[Try it online!](https://tio.run/##TY@7TsMwFEB/JY1Qc29D0gQQQ42biaFLBxh5SFbrOhccx7LdNvSx8gF8Ij8S2qES8xnOOR9iI/zCkQ2Zt7SUrmnNp/zqHTdyGz1J9dhZgB2fjkf9e1d1VQXVALoUoXstMb3Crh@Nd5iH9jk4Mgow95oWEu6vsztE5nnBtjVpCaC5k2KpyUhAHHCz1hr3iuvcW00BkixBRisAw1WupVGhxunN4UB@LuZA3Arn5cwEUC/FG@IFyP/ATMuqnJwxhtq123hmNkLTMnLCKDmJ4lSzVeuA0QOXjNIUT8KGx12cO2mlCECYNyIsanCIez8c2tNUgPNHyew6@OCA0iT6/f6JkrQ5lVxS2fHYF9ltUfwB "JavaScript (SpiderMonkey) – Try It Online")
[Answer]
# C#, 96
It returns -1,0,1 for true, anything else is false.
Any suggestions to make it shorter would be wonderful!
```
int p(int q){var r=q-1;for(var i=2;i<r&r<q+2;i++){if(i==r-1)break;if(r%i==0)r+=i=1;}return r-q;}
```
Expanded form:
```
int p(int q){
var r=q-1;
for(var i=2;i<r&r<q+2;i++){
if(i==r-1)break;
if(r%i==0)r+=i=1;
}
return r-q;
}
```
[Answer]
## GolfScript: 26
```
)0\{.:i,{i\%!},,2=@|\(}3*;
```
Explanation:
The innermost block `{.:i,{i\%!},,2=@|\(}` determines if the top of the stack is prime by checking if there are exactly 2 factors less than the top of the stack. It then disjuncts this with the second item on the stack, which holds the state of whether a prime has been seen yet. Finally, it decrements the number on the top of the stack.
Start by incrementing the input, initializing the prime-seen state, and repeat the block 3 times. Since this will decrement twice, but we started by incrementing, this will cover `n+1` and `n-1`.
[Answer]
# C#, 87 97 chars
```
bool p(int q){return new[]{q-1,q,q+1}.Any(x=>Enumerable.Range(2,Math.Abs(x-2)).All(y=>x%y!=0));}
```
[Answer]
# CJam, 12 bytes
CJam is much younger than this challenge, so this answer is not eligible for the green checkmark (which should be updated to randomra's answer anyway). However, golfing this was actually quite fun - I started at 17 bytes and then changed my approach completely three times, saving one or two bytes each time.
```
{(3,f+:mp:|}
```
This is a block, the closest equivalent to a function in CJam, which expects the input on the stack, and leaves a 1 (truthy) or 0 (falsy) on the stack.
[Test it here.](http://cjam.aditsu.net/#code=14%0A%7B(3%2Cf%2B%3Amp%3A%7C%7D%0A~))
Here is how it works:
```
(3,f+:mp:|
( "Decrement the input N.";
3, "Push an array [0 1 2].";
f+ "Add each of those to N-1, to get [N-1 N N+1].";
:mp "Test each each element for primality, yielding 0 or 1.";
:| "Fold bitwise OR onto the list, which gives 1 if any of them was 1.";
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 20 bytes
```
0∊¯1 0 1∘+∊(∘.×⍨1↓⍳)
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbBINHHV2H1hsqGCgYPuqYoQ3kaQBpvcPTH/WuMHzUNvlR72bN/4/6pgKVpimYc8FYFnCWoel/AA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 22 bytes
```
$
1
^1?1?(?!(11+)\1+$)
```
[Try it online!](https://tio.run/##K0otycxLNPyvqpGgp82loqZl@F@Fy5ArztDe0F7DXlHD0FBbM8ZQW0Xz/39zLgsuQ1MA "Retina – Try It Online")
Takes unary as input
[Answer]
# Java 8, 83 bytes
```
n->n==1|p(n-1)+p(n)+p(n+1)>0int p(int n){for(int i=2;i<n;n=n%i++<1?0:n);return--n;}
```
Returns `true` / `false` as truthy/falsey values.
[Try it online.](https://tio.run/##TZBBasMwEEX3PcUnUJBQbOJAN5GVnqDZZNl2oThKUGqPjS2nlNRnd8eKoQFJM6Nh/n/SxV5tcjl@jUVpuw5v1tPtCfAUXHuyhcNuKoFDXZfOEgrBLZDUfDvw5rUDwWCkZEvGZL@NoCSTikM8VCa3Kz0NNfPo7VS3MfVmrX1Omgw9e6Xy7HW1YeXWhb6lJCE9jEDTH0pfoAs2cLjW/oiKIcU@tJ7O75@w8k44oaNiEnLfsRAREvi3Y47crF80m8nYAoLrgqiW/vFBj16xf5deIqrMdvufLrgqrfuQNkwSShJeLTYfYaGqlFL@JzlrDuMf)
**Explanation:**"
```
n-> // Method with integer parameter and boolean return-type
n==1 // Return whether the input is 1 (edge-case)
|p(n-1)+p(n)+p(n+1)>0// Or if the sum of `n-1`, `n`, and `n+1` in method `p(n)` is not 0
int p(int n){ // Separated method with integer as both parameter and return-type
for(int i=2;i<n; // Loop `i` in the range [2, `n`)
n=n%i++<1? // If `n` is divisible by `i`
0 // Change `n` to 0
: // Else:
n); // Leave `n` as is
// (After the loop `n` is either 0, 1, or unchanged,
// if it's unchanged it's a prime, otherwise not)
return--n;} // Return `n` minus 1
```
So `int p(int n)` will result in `-1` for `n=0` and non-primes, and will result in `n-1` for `n=1` or primes. Since `p(0)+p(1)+p(2)` will become `-1+0+1 = 0` and would return false (even though `2` is a prime), the `n=1` is an edge case using this approach.
---
A single loop without separated method would be **85 bytes**:
```
n->{int f=0,j=2,i,t;for(;j-->-1;f=t>1?1:f)for(t=n+j,i=2;i<t;t=t%i++<1?0:t);return f;}
```
Returns `1` / `0` as truthy/falsey values.
[Try it online.](https://tio.run/##TZDBioMwEIbvfYqhUEgwigp7MY19gvbS4@4esjZZxtVYdOyyFJ/dTdIeCkmG@X@Y/8u0@qbT9vKzNp2eJjhqdPcNADoyo9WNgVNoowANC6/j0iuLv/6cwIGC1aX1PXhW5aJVpUBB0g4jk22a1mkhraK6OBSV5UEl5ZJWoCol7kmSoh0myb445BVxORqaRwdWLqvc@ITr/NVhAxNp8uU24AV6D8nONKL7fv8EzR@EAR16T@PMb2xYBAUIkQEOVe4DVfkmfRyPFgCZiVgv8PVTr1nRf4wWcQn4jDv/TWT6bJgpu3oS6hzDZFt90DbpM5f5XfHnzGX9Bw)
**Explanation:**
```
n->{ // Method with integer as both parameter and return-type
int f=0, // Result-integer, starting at 0 (false)
j=2,i, // Index integers
t; // Temp integer
for(;j-->-1; // Loop `j` downwards in range (2, -1]
f= // After every iteration: Change `f` to:
t>1? // If `t` is larger than 1 (`t` is a prime):
1 // Change `f` to 1 (true)
: // Else:
f) // Leave `f` the same
for(t=n+j, // Set `t` to `n+j`
i=2;i<t; // Inner loop `i` in the range [2, t)
t=t%i++<1? // If `t` is divisible by `i`:
0 // Change `t` to 0
: // Else:
t); // Leave `t` the same
// (If `t` is still the same after this inner loop, it's a prime;
// if it's 0 or 1 instead, it's not a prime)
return f;} // Return the result-integer (either 1/0 for true/false respectively)
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 7 bytes
```
´Uô2 dj
´Uô2 // Given the range [U-1..U+1],
dj // sing "Daddy DJ", uh, I mean, check if any are a prime.
```
[Try it online!](https://tio.run/##y0osKPn//9CW0MNbjBRSsv7/NzQFAA "Japt – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
‘r’ẒẸ
```
[Try it online!](https://tio.run/##AS4A0f9qZWxsef//4oCYcuKAmeG6kuG6uP/Dh@KCrP//MSw3LDgsMTUsMTI4LDIqKjE5 "Jelly – Try It Online")
### How it works
```
‘r’ẒẸ Monadic main link. Input: integer n
‘r’ Generate range n-1..n+1
ẒẸ Is any of them a prime?
```
[Answer]
## F#, 68 bytes
```
let p n=Seq.forall(fun x->n%x>0){2..n-1}
let m n=p(n-1)||p n||p(n+1)
```
[Try it online!](https://tio.run/##JYzBCsIwEETv/YqlUGiQlDQgerC5eRc8iocqiRTaTY1RKtZvXzd2WYYZeDPuIa8@WKLeRhgBm6O9V86Htu9L90SYpMFiMkp8dFWhrL9ZAgcGx5KjmGcusZS4qgWddnuM4X3wHUZzXtC2Q2jD7QUNZJDWu2gDLOMgDTDKZjY8yjIGzg4hLy65@PcyUESaNrSlek2aX6X7AQ)
This is why I love code golf. I'm still very green with F# but I learn so much about how the language works and what it can do from these kinds of challenges.
[Answer]
## R, 68 chars
```
f=function(n){library(gmp);i=isprime;ifelse(i(n-1)|i(n)|i(n+1),1,0)}
```
Usage (1 for TRUE, 0 for FALSE):
```
f(7)
[1] 1
f(8)
[1] 1
f(15)
[1] 0
```
[Answer]
## C++
```
k=3;cin>>i;i--;
while(k)
{l[k]=0;
for(j=2;j<i;j++)
if(!(i%j))
l[k]++;
k--;
i++;
}
if(!l[1]|!l[2]|!l[3])
cout<<"1";
else cout<<"0";
```
[Answer]
# Q, 43 chars 36
```
~~{any min each a mod 2\_'til each a:x+-1 0 1}~~
```
```
{any(min')a mod 2_'(til')a:x+-1 0 1}
```
[Answer]
## J, 16 chars
```
(_2&<@-4 p:]-2:)
(_2&<@-4 p:]-2:) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
1 1 1 1 1 1 1 1 0 1 1 1 1 1 0 1 1 1 1
```
[Answer]
**Python, ~~69~~ 67 chars**
```
any(all(i%j for j in range(2,i))for i in range(input()-1,8**7)[:3])
```
`8**7 > 2**20` while being slightly shorter to write
[Answer]
# Ruby, 47 chars but very readable
```
require'Prime'
f=->x{[x-1,x,x+1].any? &:prime?}
```
[Answer]
**C++ 97**
ugoren seems to have beat me to the clever solution. So he's a shortish version on the loop three times approach:
```
P(int k){int j=1;for(int i=2;i<k;){j=k%i++&&j;}return j;}
a(int b){return P(b)|P(b+1)|P(b-1);}
```
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 104 bytes
```
: p dup 1 > if 1 over 2 ?do over i mod 0> * loop else 0 then nip ;
: f dup 1- p over 1+ p rot p + + 0< ;
```
[Try it online!](https://tio.run/##TYzhCoIwFIX/9xTf78SYQtg07GFyy4F5x1y9/pqJERfO@Q6ce6yEOJYPu1pKLZ7h5anocTabvE2g5jbIho6nDKieI5OIx0yLQRFHMzM7T0eL3SbKvPX9qYpMQWLWIp@60qUmt07cw@GyQ3XeSeta//HegDU1v5Q@ "Forth (gforth) – Try It Online")
## Explanation
Prime check (p)
```
dup 1 > if \ if number to check if greater than 1
1 over 2 ?do \ place a 1 on the stack to act as a boolean and loop from 2 to n
over i mod \ take the modulo of n and i
0> * \ check if greater than 0 (not a divisor) and multiply result by boolean
loop \ end the loop, result will be -1 if no divisor was found (prime)
else \ if n is less than 2
0 \ put 0 on the stack (not prime)
then \ end the loop
nip \ drop n from the stack
```
Main Function (f)
```
dup 1- p \ get n-1 and check if prime
over 1+ p \ get n+1 and check if prime
rot p \ rotate stack to put n on top and check if prime
+ + 0< \ add the three results and check if less than 0 (at least 1 was prime)
```
[Answer]
# [Julia 0.4](http://julialang.org/), 23 bytes
```
n->any(isprime,n-1:n+1)
```
[Try it online!](https://tio.run/##yyrNyUz8n2ablJqemfc/T9cuMa9SI7O4oCgzN1UnT9fQKk/bUPN/al4Kl0NxRn65QpqGuSacaYFgGppq/gcA "Julia 0.4 – Try It Online")
]
|
[Question]
[
I think the Collatz Conjecture is already well-known. But what if we invert the rules?
Start with an integer n >= 1.
Repeat the following steps:
If n is **even**, multiply it by 3 and add 1.
If n is **odd**, subtract 1 and divide it by 2.
Stop when it reaches 0
Print the iterated numbers.
### Test cases:
```
1 => 1, 0
2 => 2, 7, 3, 1, 0
3 => 3, 1, 0
10 => 10, 31, 15, 7, 3...
14 => 14, 43, 21, 10, ...
```
### Rules:
* This sequence does not work for a lot of numbers because it enters in an infinite loop. You do not need to handle those cases. Only printing the test cases above is enough.
* I suggested to subtract 1 and divide by two to give a valid integer to continue, but it is not required to be computed that way. You may divide by 2 and cast to integer or whatever other methods that will give the expected output.
* You need to print the initial input as well.
* The output does not need to be formatted as the test cases. It was just a suggestion. However, the iterated order must be respected.
* The smallest code wins.
[Answer]
# [Haskell](https://www.haskell.org/), ~~40~~ 39 bytes
```
f 0=[]
f n=n:f(cycle[3*n+1,div n 2]!!n)
```
[Try it online!](https://tio.run/##DcNBCoAgFAXAfad47qwksloFHqETiIRUkqQfqQg6vTUwu72OLYScHVqlTeFAikbHl3cJm@4rqqVY/QNCZxijMkfrCQrRpmkGT6enGw1cCS0FOoFeQLb/weQP "Haskell – Try It Online")
Now [without](https://codegolf.stackexchange.com/questions/175248/the-inverse-collatz-conjecture#comment422296_175248) the final 0.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 30 bytes
```
{$_,{$_%2??$_+>1!!$_*3+1}...0}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1olXgeIVY3s7VXite0MFRVV4rWMtQ1r9fT0DGr/FydWKqQpGFpzQRhGMIYxjGFoAGeZWP8HAA "Perl 6 – Try It Online")
Anonymous code block that returns a sequence.
### Explanation:
```
{$_,{$_%2??$_+>1!!$_*3+1}...0}
{ } # Anonymous code block
, ... # Define a sequence
$_ # That starts with the given value
{ } # With each element being
$_%2?? !! # Is the previous element odd?
$_+>1 # Return the previous element bitshifted right by 1
$_*3+1 # Else the previous element multiplied by 3 plus 1
0 # Until the element is 0
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
:++‘ƊḂ?Ƭ2
```
[Try it online!](https://tio.run/##y0rNyan8/99KW/tRw4xjXQ93NNkfW2P0//9/QxMA "Jelly – Try It Online")
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 53 bytes
```
import StdEnv
$0=[0]
$n=[n: $if(isOdd n)(n/2)(n*3+1)]
```
[Try it online!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3PzO3IL@oRCG4JMU1r4xLxcA22iCWSyXPNjrPSkElM00js9g/JUUhT1MjT98ISGgZaxtqxv4PLkkEarJVUDE0@f8vOS0nMb34v66nz3@XyrzE3MzkYgA "Clean – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 35 bytes
```
0<Echo@#&�[3#+1-(5#+3)/2#~Mod~2]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78r/HfwMY1OSPfQVlNTdkg2lhZ21BXw1RZ21hT30i5zjc/pc4oVu2/g4KhieZ/AA "Wolfram Language (Mathematica) – Try It Online")
`0<Echo@# && ...&` is short-circuit evaluation: it prints the input `#`, checks if it's positive, and if so, evaluates `...`. In this case, `...` is `#0[3#+1-(5#+3)/2#~Mod~2]`; since `#0` (the zeroth slot) is the function itself, this is a recursive call on `3#+1-(5#+3)/2#~Mod~2`, which simplifies to `3#+1` when `#` is even, and `(#-1)/2` when `#` is odd.
[Answer]
# Python 2, ~~54~~ ~~52~~ 44 bytes
```
n=input()
while n:print n;n=(n*3+1,n/2)[n%2]
```
*-2 bytes thanks to Mr. Xcoder*
There must certainly be a faster way. Oddly, when I tried a lambda it was the same bytecount. I'm probably hallucinating.
[Try it online!](https://tio.run/##K6gsycjPM/r/P882M6@gtERDk6s8IzMnVSHPqqAoM69EIc86z1YjT8tY21AnT99IMzpP1Sj2/38jAA)
[Answer]
# [Emojicode 0.5](http://www.emojicode.org/), 141 bytes
```
üêñüéÖüèøüçáüçÆaüêïüòÄüî°a 10üîÅ‚ñ∂Ô∏èa 0üçáüçäüòõüöÆa 2 1üçáüçÆa‚ûóa 2üçâüçìüçáüçÆa‚ûï‚úñÔ∏èa 3 1üçâüòÄüî°a 10üçâüçâ
```
[Try it online!](https://tio.run/##S83Nz8pMzk9J/f9h/oTuD/NnNX2Y39sO4kz7ML@v9cP8/v0gASBelwgUnPph/oyGD/OnLExUMDQA0o2Ppm17v6M/UcEAqqoLqGA20Jh1iQpGCoZwrY/mTQcKAJmdQDwZSXjqoznTwAYYg1V3opoPVt75H0RwAZ3SCNLIpQBzmIIhiD2jAUhMWQImkOSM8MgZ45EzNMAnacIFdhAA "Emojicode 0.5 – Try It Online")
```
üêñüéÖüèøüçá
üçÆaüêï üë¥ input integer variable 'a'
üòÄüî°a 10 üë¥ print input int
üîÅ‚ñ∂Ô∏èa 0üçá üë¥ loop while number isn‚Äôt 0
üçäüòõüöÆa 2 1üçá üë¥ if number is odd
üçÆa‚ûóa 2 üë¥ divide number by 2
üçâ
üçìüçá üë¥ else
üçÆa‚ûï‚úñÔ∏èa 3 1 üë¥ multiply by 3 and add 1
üçâ
üòÄüî°a 10 üë¥ print iteration
üçâüçâ
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~76 69 61~~ 56 bytes
I feel like this is way too long. Here `l` produces an infinite list of the inverse-collatz sequence, and the anonymous function at the first line just cuts it off at the right place.
Thanks for -5 bytes @√òrjanJohansen!
```
fst.span(>0).l
l r=r:[last$3*k+1:[div k 2|odd k]|k<-l r]
```
[Try it online!](https://tio.run/##y0gszk7NyfmfpmCrEPM/rbhEr7ggMU/DzkBTL4crR6HItsgqOiexuETFWCtb29AqOiWzTCFbwagmPyVFITu2JttGF6go9n9uYmYe0ISCosy8EgUVBYU0BUOD//@S03IS04v/60Y4BwQAAA "Haskell – Try It Online")
[Answer]
# [Rust](https://www.rust-lang.org/), ~~65~~ 64 bytes
```
|mut n|{while n>0{print!("{} ",n);n=if n&1>0{n>>1}else{n*3+1};}}
```
[Try it online!](https://tio.run/##DcmxDsIgFAXQuXzFbQcD1kGiGyn/4gCRhN6Ylsbh9X07etazHXvrmVhfhdZBzFBTQ8aCfq5HA0/5vktNYLzLZytso51EMd3oApeSwYv/F2P0muqehNfH7DWo9mCGbP3TBaP9Bw "Rust – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~15~~ 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
[Ð=_#Èi3*>ë<2÷
```
-1 byte thanks to *@MagicOctopusUrn*.
[Try it online.](https://tio.run/##yy9OTMpM/f8/@vAE23jlwx2Zxlp2h1fbGB3e/v@/oQkA)
**Explanation:**
```
[ # Start an infinite loop
Ð # Duplicate the top value on the stack three times
# (Which will be the (implicit) input in the first iteration)
= # Output it with trailing newline (without popping the value)
_# # If it's exactly 0: stop the infinite loop
Èi # If it's even:
3* # Multiply by 3
> # And add 1
ë # Else:
< # Subtract 1
2√∑ # And integer-divide by 2
```
[Answer]
# [JAEL](https://github.com/eduardoHoefel/JAEL), 18 bytes
```

[Answer]
# [Thunno](https://github.com/Thunno/Thunno) `d`, \$ 19 \log\_{256}(96) \approx \$ 15.64 bytes
```
[zuZK!)2%?1-2,(3*1+
```
(No ATO link since this needs v1.2.2 and ATO is on v1.2.1)
#### Explanation
```
[zuZK!)2%?1-2,(3*1+ # Implicit input
[     # Loop forever:
zu # Quadruplicate the value on the top of the stack
ZK # Print with a trailing newline
!) # If it's 0, break
2%? # If it's odd:
1- # Subtract one
2, # And integer divide by two
( # Else:
3* # Multiply by three
1+ # And add one
# This value is on the top of the stack for the next iteration
# The d flag stops the implicit output at the end
```
#### Screenshot
[](https://i.stack.imgur.com/IXZ4t.png)
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 7.5 bytes
```
`.$?`%$~@+*3@~
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboW6xL0VOwTVFXqHLS1jB3qIIJQuQWrDbmMuIy5DA24DE0gQgA)
```
`. Iterate while unique
$ starting at input
? if
`% modulo (also save the quotient)
$ the number
~ 2
@ then the quotient
+ else add
*3 multiply by 3
@ the number
~ 1
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~15~~ 12 bytes
Thanks to @Steffan i learned more about Vyxal!
```
{…:|:∷[2ḭ|T›
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJ74oCmOnw64oi3WzLhuK18VOKAuiIsIiIsIjIiXQ==)
Naive approach for beginners:
```
{…:Ṡ|:₂[3*›|‹2/
```
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 15 bytes
```
`ĐĐ2%?ŕ₂:ŕ3*⁺;ł
```
[Try it online!](https://tio.run/##ASEA3v9weXT//2DEkMSQMiU/xZXigoI6xZUzKuKBujvFgv//MTQ "Pyt – Try It Online")
```
` ł do... while top of stack is not 0; implicit print upon exiting loop
ĐĐ duplicate top of stack twice (implicit input if empty)
2% modulo 2
?ŕ₂ if top of stack is truthy, then pop from stack and divide next by 2
:ŕ3*⁺ else: pop from stack and multiply next term by 3 and add 1
; end if-then-else statement
```
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 12 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
(ß;DE?3×⁺:⁻½
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSglQzMlOUYlM0JERSUzRjMlQzMlOTclRTIlODElQkElM0ElRTIlODElQkIlQzIlQkQmZm9vdGVyPSZpbnB1dD0xMCZmbGFncz0=)
#### Explanation
```
(ß;DE?3×⁺:⁻½ # implicit input
( # while loop:
ß # (condition) print the number without popping
# and test if it's truthy (non-zero)
;D # (body) duplicate the current integer
E? # if it's even:
3√ó # multiply it by 3
⁺ # and then add one
: # otherwise:
⁻ # decrement it
¬Ω # and then halve it
```
[Answer]
# [Pyth](https://pyth.readthedocs.io), 12 bytes
```
.u?%N2/N2h*3
```
[Try it here as a test suite!](https://pyth.herokuapp.com/?code=.u%3F%25N2%2FN2h%2a3&input=14&test_suite=1&test_suite_input=1%0A2%0A3%0A10%0A14&debug=0)
[Answer]
# [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), ~~38~~ ~~35~~ 33 bytes
```
D,f,@:,d3*1+$2/iA2%D
+?
O
Wx,$f>x
```
[Try it online!](https://tio.run/##S0xJKSj4/99FJ03HwUonxVjLUFvFSD/T0UjVhUvbnsufK7xCRyXNruL///@GJgA "Add++ – Try It Online")
## How it works
First, we begin by defining a function \$f(x)\$, that takes a single argument, performs the inverted Collatz operation on \$x\$ then outputs the result. That is,
$$f(x) = \begin{cases}
x \: \text{is even}, & 3x+1 \\
x \: \text{is odd}, & \lfloor\frac{x}{2}\rfloor
\end{cases}$$
When in function mode, Add++ uses a stack memory model, otherwise variables are used. When calculating \$f(x)\$, the stack initially looks like \$S = [x]\$.
We then duplicate this value (`d`), to yield \$S = [x, x]\$. We then yield the first possible option, \$3x + 1\$ (`3*1+`), swap the top two values, then calculate \$\lfloor\frac{x}{2}\rfloor\$, leaving \$S = [3x+1, \lfloor\frac{x}{2}\rfloor]\$.
Next, we push \$x\$ to \$S\$, and calculate the bit of \$x\$ i.e. \$x \: \% \: 2\$, where \$a \: \% \: b\$ denotes the [remainder](https://en.wikipedia.org/wiki/Remainder) when dividing \$a\$ by \$b\$. This leaves us with \$S = [3x+1, \lfloor\frac{x}{2}\rfloor, (x \: \% \: 2)]\$. Finally, we use `D` to select the element at the index specified by \$(x \: \% \: 2)\$. If that's \$0\$, we return the first element i.e. \$3x+1\$, otherwise we return the second element, \$\lfloor\frac{x}{2}\rfloor\$.
That completes the definition of \$f(x)\$, however, we haven't yet put it into practice. The next three lines have switched from function mode into vanilla mode, where we operate on variables. To be more precise, in this program, we only operate on one variable, the **active variable**, represented by the letter `x`. However, `x` can be omitted from commands where it is obviously the other argument.
For example, `+?` is identical to `x+?`, and assigns the input to `x`, but as `x` is the **active variable**, it can be omitted. Next, we output `x`, then entire the while loop, which loops for as long as \$x \neq 0\$. The loop is very simple, consisting of a single statement: `$f>x`. All this does is run \$f(x)\$, then assign that to `x`, updating `x` on each iteration of the loop.
[Answer]
# [Common Lisp](http://www.clisp.org/), 79 bytes
```
(defun x(n)(cons n(if(= n 0)nil(if(=(mod n 2)0)(x(+(* n 3)1))(x(/(- n 1)2))))))
```
[Try it online!](https://tio.run/##VcwxDoMwEETRnlNsOUOEYhvanAaCZImsLSCSb@8sNJGne7@YeYtHrhXLe/2qFCgxJz1EEVe8RMVR43YDn7RYCHREwQO9YaTnpScGk2fgvYq8Rz0FxRq7v0KjsZF3LSf7@QE "Common Lisp – Try It Online")
[Answer]
# PowerShell, ~~53~~ 52 bytes
```
param($i)for(;$i){$i;$i=(($i*3+1),($i-shr1))[$i%2]}0
```
[Try it Online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVTMy2/SMMaSFerZAIpWw2gmJaxtqGmDpChW5xRZKipGa2SqWoUW2vw//9/QxMA)
**Edit:**
-1 byte thanks to @mazzy
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 11 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
₧↑╔¶┘tÇ╣;↑è
```
[Run and debug it](https://staxlang.xyz/#p=9e18c914d97480b93b188a&i=1%0A2%0A3%0A10%0A14&a=1&m=2)
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), 12 bytes
```
{o_¥¿½É3*)}∟
```
[Try it online!](https://tio.run/##y00syUjPz0n7/786P/7Q0kP7D@093GmspVn7qGP@//@GJv8B "MathGolf – Try It Online")
## Explanation
```
{ Start block of arbitrary length
o Output the number
_ Duplicate
¥ Modulo 2
¬ø If-else with the next two blocks. Implicit blocks consist of 1 operator
¬Ω Halve the number to integer (effectively subtracting 1 before)
É Start block of 3 bytes
3*) Multiply by 3 and add 1
}‚àü End block and make it do-while-true
```
[Answer]
# x86 machine code, 39 bytes
```
00000000: 9150 6800 0000 00e8 fcff ffff 5958 a901 .Ph.........YX..
00000010: 0000 0074 04d1 e8eb 066a 035a f7e2 4009 ...t.....j.Z..@.
00000020: c075 dec3 2564 20 .u..%d
```
Assembly (NASM syntax):
```
section .text
global func
extern printf
func: ;the function uses fastcall conventions
xchg eax, ecx ;load function arg into eax
loop:
push eax
push fmt
call printf ;print eax
pop ecx
pop eax
test eax, 1 ;if even zf=1
jz even ;if eax is even jmp to even
odd: ;eax=eax/2
shr eax, 1
jmp skip
even: ;eax=eax*3+1
push 3
pop edx
mul edx
inc eax
skip:
or eax, eax
jne loop ;if eax!=0, keep looping
ret ;return eax
section .data
fmt db '%d '
```
[Try it online!](https://tio.run/##bVTbbtswDH2WvoILWuTSKNcOw@KmD8M67G0fUBeBYsuJU1syLLnzmuXbM1J22qRYAEMkdQ5vOsha2u0xkg7u7h5@/YB7GLu8GMuRtDkEoOkQicqS@ez8RpjGi0ysRgaBKtoa6HBVO1VqSLWD1Uo6V6bryqnVqtdLpHWRzLJ@H5JKRz2E9APguUx1r7/nxHDKOvv4tNyHfDrksyGfD/l0gt/tkB8CnpiSWJAuJ0F69zlIb26QWJQYS3ph5zpeQNgZNknSpz4SqM6Z/wYNddhB/8APndPA1lXrURSEPOSbKLqcD6c/B11MLrQRRapA5LggkVBJlxotrPKn9RnNehdXeQHi@wUXS8fqBbPGqiwvgfYC@BdXo87BGNmUCnEP0H2ciK9P@9sDdDEaVQ7EGr6I2xmxShAxdEPdfXc8zKejAltVj1ztMPQbh47wlL@fobv3q4Kr6Xh2IHyzOcDFDQaDb3@cgshU2i3QC/W1DXUHrnokItH/z1ReG0K19J@qphmJi9s/x0JdxyCwzeJjc3Rx/zHtxQMd24XDyKEGOdtkZi0zLzXOWlU2U3hZLBj9ArdVcHoyqKyycJIpDqhflPZvyFkdbTegZD1EnddEzIyM35my3JDkDUE4y4wpFpyxorLbJtKYSY59MZ@86YQFzZpbjCko@8nyMRJvU3fKgjQBhS3Ba7Kc4t3u1busuZA1pLa536GAqBe0EWbiGIcNELDEbzzDELPbss1KHuHtc1qgTZwz9GB@4xG@/bm3qLWYWmN5lZ3MVEdtw5SHZjdtgSa60wpoK6dWPy0nQ3hWKGCKpnrDWakc7RWPCl@KaG8PGksnOcPtQbyG7jVq@Ij/VMd/ "Bash – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~66~~ 61 bytes
-5 bytes thanks to Robert S. in consolidating ifelse into `if` and removing brackets, and x!=0 to x>0
```
print(x<-scan());while(x>0)print(x<-`if`(x%%2,(x-1)/2,x*3+1))
```
instead of
```
print(x<-scan());while(x!=0){print(x<-ifelse(x%%2,(x-1)/2,x*3+1))}
```
[Try it online!](https://tio.run/##K/r/v6AoM69Eo8JGtzg5MU9DU9O6PCMzJ1WjQtHWQLMaLpmZlppTDBRVVTXS0ajQNdTUN9Kp0DLWNtTUrP1v9B8A "R – Try It Online")
[Answer]
# [Factor](https://factorcode.org/) + `math.extras`, 56 bytes
```
[ [ .s dup odd? [ 1 - 2/ ] [ 3 * 1 + ] if ] until-zero ]
```
[Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQnVqUl5qjkJtYkgEm9FIrSooSixUKilJLSioLijLzShSsuQxN/kcrRCvoFSuklBYo5Kek2AN5hgq6Ckb6CrFAprGCFpCrDWRnpgGJ0rySzBzdqtSifIXY/8mJOTn/AQ "Factor – Try It Online")
## Explanation:
* `[ ... ]` A quotation. An anonymous function that lives on the data stack until called or used by a combinator.
* Assuming a data stack with `3` on top when this quotation is called...
* `[ .s dup odd? [ 1 - 2/ ] [ 3 * 1 + ] if ]` Push a quotation to the data stack to be used later by `until-zero`. **Stack:** `3 [ .s dup odd? [ 1 - 2/ ] [ 3 * 1 + ] if ]`
* `until-zero` Call a quotation repeatedly until its output is `0`. **Stack:** `3`
* `.s` Non-destructively print the data stack. **Stack:** `3`
* `dup` Duplicate TOS (top-of-stack). **Stack:** `3 3`
* `odd?` Return `t` if input is odd, else `f`. **Stack:** `3 t`
* `[ 1 - 2/ ]` Push a quotation to be used later by `if`. **Stack:** `3 t [ 1 - 2/ ]`
* `[ 3 * 1 + ]` Push another quotation to be used later by `if`. **Stack:** `3 t [ 1 - 2/ ] [ 3 * 1 + ]`
* `if` Takes a boolean and two quotations from the data stack. Calls the first quotation if the boolean is `t`, otherwise calls the second. (Now inside the first quotation...) **Stack:** `3`
* `1` Push `1` to the data stack. **Stack:** `3 1`
* `-` Subtract TOS from NOS (next on stack). **Stack:** `2`
* `2/` Integer divide by 2. Like doing `x>>1` in many languages. **Stack:** `1`
* Now `until-zero` looks at the data stack and sees TOS is not `0`, so calls its input quotation...
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 75 bytes
```
#include<stdio.h>
int g(int x){printf("%d ",x);x?g(x=x%2?(x-1)/2:3*x+1):0;}
```
[Try it online!](https://tio.run/##S9ZNT07@/185My85pzQl1aa4JCUzXy/Djiszr0QhXQNEVmhWFxQBGWkaSqopCko6FZrWFfbpGhW2FapG9hoVuoaa@kZWxloV2oaaVgbWtf9BenITM/M0NLmquThBvLLEHGsuzuLkxDywGUo6akARTaBQugaEUfvf0AQA "C (gcc) – Try It Online")
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 25 bytes
```
{x>0}{$[2!x;_x%2;1+3*x]}\
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6qusDOorVaJNlKssI6vUDWyNtQ21qqIrY3h4kpTMARiIyA2BrENQIQJAGbPDIU=)
[Answer]
# [Nim](https://nim-lang.org/), ~~65~~ 50 bytes (-15 due to xigoi)
```
proc f(n:int)=
echo n;if n>0:f [n*3+1,n/%2][n%%2]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m704LzN3wYKlpSVpuhY3HQuK8pMV0jTyrDLzSjRtuRQUUpMz8hXyrDPTFPLsDKzSNIAMjTxVVSNNIE8jT9dQU1_VSCE1pzjVKk_LWNtQE2LQ2rLEIoVEW0MDrjSNRKgYzBIA)
Simple recursive solution cum array-based due to xigoi.
[Answer]
# JavaScript (ES6), 30 bytes
```
f=n=>n&&n+[,f(n&1?n>>1:n*3+1)]
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbP1i5PTS1PO1onTSNPzdA@z87O0CpPy1jbUDP2f3J@XnF@TqpeTn66RpqGoaYmF6qIEYaIMYaIoQGmkImm5n8A "JavaScript (Node.js) – Try It Online")
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 11 bytes
```
ᶦ{Z:←½$3*→I
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FpsebltWHWX1qG3Cob0qxlqP2iZ5LilOSi6GSi9Ya8BlyGXEZcxlCGSYQAQB)
```
ᶦ{Z:←½$3*→I
·∂¶{ Iterate until failure:
Z Check if nonzero
: Duplicate
‚Üê Decrement
¬Ω Halve; fails if odd
$ Swap
3* Multiply by 3
‚Üí Increment
I Choose the first value that doesn't fail
```
]
|
[Question]
[
This is a [tips](/questions/tagged/tips "show questions tagged 'tips'") question for golfing in [python](/questions/tagged/python "show questions tagged 'python'").
In multiple golfs I've done in Python, a fixed value is assigned to one of two variables chosen by a Boolean. The chosen variable is overwritten by the given value, and the other is unchanged.
*17 chars:*
```
if b:y=z
else:x=z
```
Assigning a conditional value is [easy](https://codegolf.stackexchange.com/a/62/20260), but assigning to a conditional variable seems clunky. I'm wondering if there's a shorter way I'm missing.
This would be easy if `x,y` were instead a list `L`, but assume the context requires referring to the variables enough that writing `L[0]` and `L[1]` is prohibitive. Converting takes too long:
*20 chars:*
```
L=[x,y];L[b]=z;x,y=L
```
The fastest way I know is with a Python 2 `exec`, which is bizarre:
*16 chars, Python 2:*
```
exec"xy"[b]+"=z"
```
Tuple-choosing seems to be longer:
*18, 19, 18, 18 chars:*
```
x,y=b*(x,z)or(z,y)
x,y=[z,x,y,z][b::2]
y,x=[y,z,x][b:b+2]
y,x,*_=[y,z,x][b:] # Python 3
```
Is there some shorter method or character-saving optimization? You can assume `b` is `0` or `1`, not just Falsey or Truthy, and also make assumptions about the data types and values if it helps.
[Answer]
## 12 chars/assignment + 9 chars of overhead
```
V=vars() # do once at the start of the program
V["xy"[b]]=z
```
Note that this only works at global scope, it does not work inside a function.
[Answer]
## 14 chars, Python 2
```
exec"xy=z"[b:]
```
The two variables are `y` and `xy`. If b=0, this sets `xy=z`. If b=1, this sets `y=z`. This will be worth it if `xy` is used no more than once elsewhere in the code.
[Answer]
## 15 chars, Python 2
```
exec`b`[0]+"=z"
```
Requires that the variables be called `F` and `T` rather than `x` and `y`, and that `b is False` or `b is True`, rather than being the equal numbers `0` or `1`.
This saves a char from `"xy"[b]` by instead taking the first letter of the string representation of `b`, which is `T` or `F`.
]
|
[Question]
[
Let's build a sequence of positive integers. The rule will be that the next number will be the smallest number which:
* It hasn't already appeared in the sequence
* Its absolute difference from the number preceding it wouldn't be equal to any previous absolute difference between consecutive elements.
## Task
Your task is to implement this sequence. You may use [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") defaults, found in the [tag wiki](https://codegolf.stackexchange.com/tags/sequence/info).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being better.
## Example
As an example let's construct the first couple of terms. The first term is `1` since it's the smallest positive integer. After that comes `2`.
```
Sequence: 1, 2
Diffs: 1
```
`3` is the next smallest number, but it's difference from `2` is the same as the difference between `1` and `2`, so `4` is the next term.
```
Sequence: 1, 2, 4
Diffs: 1, 2
```
Now `3` *still* can't be added because it's difference from `4` is `1`, `5` and `6` also can't be added because their diffs are `1` and `2`. So the smallest number is `7`.
```
Sequence: 1, 2, 4, 7
Diffs: 1, 2, 3
```
Now `3` can be added, since it's difference from `7` is `4` which we haven't seen before.
```
Sequence: 1, 2, 4, 7, 3
Diffs: 1, 2, 3, 4
```
Since the diffs count up to `4` we know the next one is *at least* `5`, so the next number is at least `8`. `8` hasn't appeared so we can add it.
```
Sequence: 1, 2, 4, 7, 3, 8
Diffs: 1, 2, 3, 4, 5
```
## Test cases
This sequence is [OEIS A081145](http://oeis.org/A081145). Here are the first few terms taken from OEIS:
```
1, 2, 4, 7, 3, 8, 14, 5, 12, 20, 6, 16, 27, 9, 21, 34, 10, 25, 41, 11, 28, 47, 13, 33, 54, 15, 37, 60, 17, 42, 68, 18, 45, 73, 19, 48, 79, 22, 55, 23, 58, 94, 24, 61, 99, 26, 66, 107, 29, 71, 115, 30, 75, 121, 31, 78, 126, 32, 81, 132, 35, 87, 140, 36, 91, 147, 38, 96, 155, 39
```
[Answer]
# [Python](https://www.python.org), 70 bytes
```
a={0,p:=1}
while[print(d:=p)]:
while(s:={p-d,-d*d})&a:d-=1
a|=s;p-=d
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LYwxCoMwFED3nOJDoSTWFN1KSgaXXsI6CD9iwJqQpK1iPUkXl_ZO3qZFnR48Hu_9tX2oTTvN1x2Yh3JOowLrdBsgGDBt0wMaCLWCSjsfIE0SCMrdPEFVrSHt4kzmqtOhOOSLKaJ_xkR2tMZSRjv2uYeKn-ZLKYcktkKmI3nWulFrTlFIywpBYJHUCzlYjjHHCEe2LwVymRIoX9KfLZe43qYNG38)
-1 each thanks to @xnor and @ovs.
Prints the sequence infinitely. Avoids the need for two storage lists by using the negative absolute difference.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 16 bytes
```
~l.ℕ₁ᵐ≠s₂ᵇ-ᵐȧᵐ≠∧
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/vy5H71HL1EdNjQ@3TnjUuaD4UVPTw63tukDeieUQoUcdy///NzT4HwUA "Brachylog – Try It Online")
Returns a list of the `n` first elements of the sequence.
### Explanation
We basically describe the properties of the sequence: a list of positive integers, that are all different, and where each 2-element substring difference is unique.
```
~l. Output is a list of length <Input>
.ℕ₁ᵐ Output contains strictly positive integers
. ≠ All elements in the output are different
. s₂ᵇ Find all sublists of 2 consecutive elements in the Output
-ᵐ Map subtraction
ȧᵐ Map absolute value
≠ All results must be different
∧ Implicit labelling of elements in the output to match these constraints
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~15~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
λλû¥+λ«∞sKн
```
-4 bytes thanks to @ovs.
Outputs the infinite sequence.
[Try it online.](https://tio.run/##AR4A4f9vc2FiaWX//867zrvDu8KlK867wqviiJ5zS9C9//8)
**Explanation:**
```
λ # Start a recursive environment
# to output the infinite sequence
# Implicitly starting with a(0)=1
# Where every following a(n) is calculated as follows:
# (implicitly push a(n-1))
λ # Push a list of all previous terms: [a(0),a(1),...,a(n-1)]
û # Palindromize this list: [a(0),a(1),...,a(n-1),...,a(1),a(0)]
¥ # Pop and push its forward differences
+ # Add the implicit a(n-1) to each
λ« # Merge the list of previous terms to this list
∞ # Push an infinite positive list: [1,2,3,...]
s # Swap so our earlier created list is at the top again
K # Remove all those values from the infinite positive list
н # Pop and leave just the first value
# (after which the infinite list is output implicitly as result)
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 43 bytes
```
{x,{y+(1<#?:\#'!'1_-':x,y)|/x=y}[x]/1}/[;1]
```
[Try it online!](https://ngn.codeberg.page/k#eJwVissOgjAURPf9ihoWaLz00oqCqPFD0BiCBYy8pMUUkX+3Lk5mzmTyeDIwjeslPzrn+OK4C5ffPDc2MK6+aE7jnJgr8hmTA78SktPAwgUhSEqtOxUjZu1dFm2VM6XT7ClNVqZNIVnW1vgapNKPtlEoAj/aR6iqVMvee8tKfrxO9vWg0/+BEA5UAA2AhkA3QCOg3MrWhp2FD3Rnq0WEjLEfaCMzbg==)
Takes the number of terms to generate (0-indexed, so passing `0` generates the sequence up to position 0, `4` generates the sequence up to position 4, etc etc.)
* `{...}/[;1]` set up a do-reduce, run for the inputted number of times, seeded with `1` (the first term of the sequence)
+ `{...{...}[x]/1}` set up a converge-reduce, fixing `x` (the sequence generated so far) and seeded with `1`
- `(1<#?:\#'!'1_-':x,y)` determine if the current value has a different absolute difference than the rest of the terms in the sequence so far
* `x,y` append the value being tested to the sequence so far
* `1_-':` take the differences between successive items
* `#'!'` take the absolute value of these differences
* `1<#?:\` determine if the differences are all distinct (i.e. none are repeated)
- `(...)|/x=y` set up a max-reduce (i.e. any), seeded with the check described above and run over the sequence compared to the value being tested (for equality)
- `y+` add this result to the current value being tested; if the value meets both checks, it will be unchanged and end the converge-reduce
+ `{x,...}` append the next term in the sequence and feed it to the next iteration of the do-reduce
[Answer]
# [Haskell](https://www.haskell.org/), 97 bytes
```
(#)=notElem
g=(iterate(\l->l++[[x|x<-[1..],x#l,abs(x-last l)#zipWith((abs.).(-))l(1:l)]!!0])[]!!)
```
[Try it online!](https://tio.run/##DcixDoMgEADQvV@BocNdFKIdG@nWb3CgDDQhSnpSIzeQxn@nTi95i8@fQFQrSDTpy08K62U2EDnsngO8SD2oba0tRxmVHbR2XZHU@XeGoshnFoTyF7cp8gJwtkYNCpFguBO6pukd2hOsq49JGLHtMbG4zuLW1z8 "Haskell – Try It Online")
* returns first *n* elements.
[Answer]
# Haskell, 107 bytes
```
e l=[last l+x*v|v<-zipWith((abs.).(-))l$1:l,x<-[-1,1]]++l
f n=head$filter(flip notElem$e$f<$>[0..n-1])[1..]
```
[Try it Online!](https://tio.run/##FcoxDsIgFADQ3VP8gQGkkOJoiptncCAMGCEQP5QU0jTGu2N884uuvT3iGB5QG3StA/LjvH/3RXxSfaQeKXXPJpmkgjEk6orTsQgj1KSs5RxPAYqO3r1ISNj9RgOmCmXtd/SZeBIWcjOzlEUoy4yS0o7sUgENdUulA4HsKgT4n8tsxw8)
-3 bytes thanks to AZTECCO
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 20 bytes
```
(λ¾₌‡¯ȧtnεc¾nc∨¬;ṅ…⅛
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIozrvCvuKCjOKAocKvyKd0bs61Y8K+bmPiiKjCrDvhuYXigKbihZsiLCIiLCI1Il0=)
I'm probably going to take the L to better algorithms, but that's okay with me. Prints the first n numbers.
## Explained
```
(λ¾₌‡¯ȧtnεc¾nc∨¬;ṅ…⅛
( # input times:
λ..............;ṅ # find the first number N where:
₌ # the
¾ ‡¯ȧ # absolute values of the deltas of the global array
c # contains
¾ tnε # the absolute difference of the last item of the global array and N
∨¬ # nor
¾nc # does the global array contain N
…⅛ # print N and add to the global array
```
[Answer]
# [Perl 5](https://www.perl.org/) List::Util, 64 bytes
```
$l=@a=0..1e3;$a[$l]=0,say$l while$l=first{$_&&!$d{abs$_-$l}++}@a
```
[Try it online!](https://tio.run/##K0gtyjH9/18lx9Yh0dZAT88w1dhaJTFaJSfW1kCnOLFSJUehPCMzJxWoIC2zqLikWiVeTU1RJaU6MalYJV5XJadWW7vWIfH//3/5BSWZ@XnF/3V9fTKLS6ysQksyoXqAQmWmeoYGAA "Perl 5 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 76 bytes
```
while(k<-1){p=print(+T[1])
while((p-k)^2%in%diff(T)^2|k%in%T)k=k+1
T=c(k,T)}
```
[Try it online!](https://tio.run/##K/r/vzwjMydVI9tG11CzusC2oCgzr0RDOyTaMFaTCyKlUaCbrRlnpJqZp5qSmZamEQLk1GSDuCGa2bbZ2oZcIbbJGtk6IZq1//8DAA "R – Try It Online")
Prints the sequence infinitely.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 32 [bytes](https://github.com/abrudz/SBCS)
Prints the sequence without end.
```
{∇⍵,⍨⊃k~⍨⍳+/k←⍵,(⎕←⊃⍵)+2-/⍵,⌽⍵}1
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pRR/uj3q06j3pXPOpqzq4D0b2btfWzH7VNAIlrPOqbCmJ2NQN5mtpGuvpg1T17gVSt4f//AA "APL (Dyalog Unicode) – Try It Online")
```
{∇⍵,⍨⊃k~⍨⍳+/k←⍵,(⎕←⊃⍵)+2-/⍵,⌽⍵}1 ⍝ full program that prints the sequence indefinitely
{ } ⍝ recursive function taking the previous numbers as right argument ⍵
2-/⍵,⌽⍵ ⍝ forward and backward differences of consecutive numbers in ⍵
⎕←⊃⍵ ⍝ print (and return) the previous value
+ ⍝ add this to all the differences
⍝ all these results are not allowed because of the absolute difference rule
⍵, ⍝ prepend the previous sequence values
k← ⍝ store this list in k
+/ ⍝ take the sum of k (this is always larger than the maximum value)
k~⍨⍳ ⍝ [1 .. sum(k)] without the values in k
⊃ ⍝ take the first (lowest) value
⍵,⍨ ⍝ prepend to the sequence values
∇ ⍝ recursive function call with updated list
1 ⍝ call above function with value 1
```
[Answer]
# [R](https://www.r-project.org/), ~~74~~ ~~71~~ 70 bytes
```
repeat T=c((u=1:(T*5))[!u%in%T&!(u-print(+T[1]))^2%in%diff(T)^2][1],T)
```
[Try it online!](https://tio.run/##K/r/vyi1IDWxRCHENllDo9TW0EojRMtUUzNasVQ1M081RE1Ro1S3oCgzr0RDOyTaMFZTM84IJJGSmZamEQLkxAIFdUI0//8HAA "R – Try It Online")
Outputs the sequence indefinitely.
Note (from [OEIS A081145](https://oeis.org/A081145)) that "*The points appear to lie on three straight lines of slopes roughly 0.56, 1.40, 2.24 (click "[graph](https://oeis.org/A081145/graph)")*".
If true, then `a(n)` should always be less than or equal to `a(n-1)` multiplied by about `2.24/0.56`, or `4`. So here we only search in the range from `1` up to `a(n-1)` times `5` (to be on the safe side).
[Answer]
# [JavaScript (V8)](https://v8.dev/), 84 bytes
A full program printing the sequence forever.
```
for(a=[];i=1;print(p=i),a.push(i))while(a.some(q=v=>v==i|(i-p)**2==(q-(q=v))**2))i++
```
[Try it online!](https://tio.run/##FchBCoMwEAXQ68yoEXQlyO9FSheDWPyl1jHRdNO7p7h872XZ0hTpR8hDKc8tiuH@GIlu9MjPIQ5qY62faRGqfhe@Z7E2bessOzJuGeBPGFyrqgdkD9frJVXWdSl/ "JavaScript (V8) – Try It Online")
---
# [JavaScript (V8)](https://v8.dev/), ~~66~~ 65 bytes
Using [pxeger](https://codegolf.stackexchange.com/a/240900/58563)'s nice idea.
```
for(s=p={};i=1;print(s[q]=s[i]=p=i))while(s[q=i-p,q*=-q]|s[i])i++
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/Py2/SKPYtsC2utY609bQuqAoM69Eozi6MNa2ODozFiiRqalZnpGZkwoStM3ULdAp1LLVLYytAUlrZmpr//8PAA "JavaScript (V8) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~81~~ 77 bytes
*4 bytes saved by xnor*
```
(?)=notElem
q@(a:b)!x=a:[(z:q)!(d:x)|z<-[1..],d<-[abs$a-z],z?q,d?x]!!0
[1]![]
```
[Try it online!](https://tio.run/##DcYxCsMgFADQPaf4HzIomJB0lIpdegpx@EFJQ4ypjYNI7277pveia/chtMY0V/HMz@CPLj0YyYVjUSQNqzJxZE4W/q33wczjaIX7h5arp6FaUXUSTheLOHWrMrNFY9tBWwQF788WM/SZdg@3Cdb2Aw "Haskell – Try It Online")
I gave it a day so I thought I'd give this a spin in Haskell myself. `[1]![]` gives an infinite list of the results.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 40 bytes
```
≔¹ηFN«≔¹ζW∨№υζ№υ±↔⁻ζη≦⊕ζ⊞υζ⊞υ±↔⁻ζη≔ζη⟦Iζ
```
[Try it online!](https://tio.run/##fY8/D4IwEMVn@BQdrwkmMjMRJgaQ3TgUrLRJaUn/aFLjZ69FCDp5072Xl9@9GxjRgyIihNIYPkrIM8Rwkd6URlDL2dnWTT3VgDF6psk35GMoeTAuKIKThko5acEtfoZ20dKRWAplb5RwcWm4dAb8cuIzqCHzhqzloOlEpaXXDd45w1bij/hPLPaGfn0j6TSPVc4VMRY8vkTrFUJ@DIe7eAM "Charcoal – Try It Online") Link is to verbose version of code. Outputs the first `n` terms. Explanation: Uses @pxeger's trick to avoid keeping track of two sets.
```
≔¹η
```
Start with the previous term being `1`. This gives a zero difference for the first term, which doesn't conflict with anything else.
```
FN«
```
Process `n` terms.
```
≔¹ζ
```
Start looking for the next term with `1`.
```
W∨№υζ№υ±↔⁻ζη
```
While the term, or its negated absolute difference with the previous term, already exists in the predefined empty list, ...
```
≦⊕ζ
```
... increment the potential next term.
```
⊞υζ
```
Save the term to the predefined empty list.
```
⊞υ±↔⁻ζη
```
Save the negated absolute difference to the predefined empty list.
```
≔ζη
```
Save the term as the previous term.
```
⟦Iζ
```
Output the term on its own line.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~59~~ 56 bytes
```
a=0,p=1;loop{d=p p;d-=1while[]!=a&s=[p-d,-d*d];p,=a=s|a}
```
[Try it online!](https://tio.run/##HY7NasMwEIRfRb30UNZg/ViyMHqSkIOLCi0EIhpCKW2f3f0mh2W1O59m9vP@@n0ce5ttNL9drtfx09twY@tT81/vH5e30/mp7c@3dhpTt6m/9PM2rO3t9rv/HYc3F8wlc8VcNLea8wwLjXWYzWWeVECvNPgI4FECVGL28uBjAvF4RGoRgx7ZZVhPTzhmBYhFK3Aez8Rc5I2@sA/6z67iEaiMf5XOGVnnzJgFFuURrhQSyuNmnUcVxYiPeK7C9Iggq45M8BG1StHZUXGyVn6s/w "Ruby – Try It Online")
Stolen from pxeger Python answer, and then thanks pxeger again for -2 bytes.
# (previously) [Ruby](https://www.ruby-lang.org/), 76 bytes
```
a,*r=1;loop{r<<a-a=p(1.step.find{|b|q=1;r.all?{|c|[b]&[q-=c,a-c,c+a]==[]}})}
```
[Try it online!](https://tio.run/##HY5LboQwEESv4lWUj0HjDzZWxspBEAtDEmkklGFIsoiAs5PXs2i1u@u5qpff4e84in5esnmdrtd5Xc7nUpU8P5r6@@djrj8vX@/rNmw3gKUu0/S2buPWDf1Dd6vyqEs16vGl9Dl3/b4/7cdhtLJaea2iVk6rVivD0NBY25NWgSdl0RMN3gEYFAvlmY148NGDGDwc1QiD7tgFWEP3OAYJEBYtwhk8PXMUb/SGvZX/7BIelgr4J9E5I8g5J8wsi3gPlxQS4v1mOY@KEiO8w7MVTB4OpJUjPbxDTaLI2U7ixFryXfoH "Ruby – Try It Online")
[Answer]
# [C++ (clang)](http://clang.llvm.org/), ~~149~~ \$\cdots\$ ~~132~~ 131 bytes
```
#import<set>
void f(int&n){std::set<int>s;int i,p=n,x;for(n=1;p--;s.insert({n=i,-x*x}))for(i=0;s.count(++i)|s.count(-(x=n-i)*x););}
```
[Try it online!](https://tio.run/##VVLbbqMwEH3nK0ZZqcKJqcIlEMrlZbVf0eQBgdO1NjEI3BZtNr@@2TPQbFqksWfmnDkz2K67zquPlXm5Xr/pU9f2Nh@ULZ23Vjd0cLWxD0acB9s8PSGfIy6HDCtp2RVGjtmh7V1T@FnnednwqM2geuueTaGlNy7HixBM0MUaYN2@GuuuVlr8uQWeOxbG02I5ikxkF8xg6uNroyjX7WB7VZ1K5557U7Vt@9Lh/qdKG1ecHcJXt2awNA05U6Y5SY0dItVQQWdfUiApkpRICiVtJfkINtiQDtaSYriwAHiKDfwQBB9IAFaE2GcNFEag@NAIYRvmAA@Ri8H1sUdQjLkBc4El4PnQjBAnrA18g3zA9cil0AhgMfRTxjFGzOOsIRYgkUzNuQs6JNPMPB4s4TbMD6G5ZRo7IShbHjICPwSaMsJjh9yOpbl/mF6yT8dX/6z6JVZV/1L9854PbbEbfwS7Mf0O2ywkfY7DxUc17pfc6UWYRo0oW2cfbv7/Bh4H/Vu5IiNcPkOC5ovjj0styuaaFfnZF8gAsvfUwbXiK0GBcOvzPIns74TpTeCpWcpzSGFZkFdigWfncPJvv62Kwu6n/M4sZpmLc7n@rQ/H6mW4eu//AA "C++ (clang) – Try It Online")
*Uses [pxeger](https://codegolf.stackexchange.com/users/97857/pxeger)'s idea from his [Python answer](https://codegolf.stackexchange.com/a/240900/9481) so only one `std::set` is needed.*
Inputs an integer \$n\$.
Returns (through re-assignment of the input value) the \$1\$-indexed \$n^{\text{th}}\$ term of the Slater-Valez sequence.
]
|
[Question]
[
Part of [**Advent of Code Golf 2021**](https://codegolf.meta.stackexchange.com/q/24068/78410) event. See the linked meta post for details.
Related to [AoC2015 Day 10](https://adventofcode.com/2015/day/10).
*[Here's why I'm posting and not Bubbler](https://chat.stackexchange.com/transcript/240?m=59765196#59765196)*
---
The Elves are playing a variation of the game called look-and-say. In plain look-and-say, they take turns making sequences by reading aloud the previous sequence and using that reading as the next sequence. For example, 211 is read as "one two, two ones", which becomes 1221 (1 2, 2 1s).
But this time it's somewhat different. Given a sequence written on a piece of paper, an Elf reads the sequence, and for each chunk of digits, they write the *count* on the *left* side and the *digit* on the *right* side. And the next Elf does the same on the entire sequence of digits!
For example, if the current sequence is `211333`:
```
Original sequence : 211333
Read 2 (one two) : 1(211333)2
Read 1 (two ones) : 21(211333)21
Read 3 (three threes): 321(211333)213
```
So the next sequence would be `321211333213`.
If the Elves start with the single digit of `1`, what will the sequence look like on the paper after `n` turns?
**Input:** The non-negative integer `n`. (Or a positive integer, if you choose to treat `1` as the 1st iteration.)
**Output:** The resulting list of digits. Can be in any acceptable format, such as a list of numbers or a single string. Be sure to handle multi-digit numbers that appear since iteration 7 - if you're returning a list of digits, make sure that these multi-digit numbers have been split into single digit numbers.
The sequence goes on like this:
```
1
111
31111
413111131
114111413111131413131
111111114111312114111413111131413131141413131413131
1111111111111121111111411131211131811111111411131211411141311113141313114141313141313114131214141313141313141413131413131
11111111111111111111111111111111112111111111111121111111411131211131811131113171141111111111111121111111411131211131811111111411131211411141311113141313114141313141313114131214141313141313141413131413131121413121318141312141413131413131414131314131314131214141313141313141413131413131
11111111111111111111111111111111111111111111111111111111111111111111111111111111211111111111111111111111111111111121111111111111211111114111312111318111311131711412111313111311131711313411111111111111111111111111111111112111111111111121111111411131211131811131113171141111111111111121111111411131211131811111111411131211411141311113141313114141313141313114131214141313141313141413131413131121413121318141312141413131413131414131314131314131214141313141313141413131413131121214131213181313171412141312131814131214141313141313141413131413131413121414131314131314141313141313121413121318141312141413131413131414131314131314131214141313141313141413131413131
1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111121111111111111111111111111111111111111111111111111111111111111111111111111111111211111111111111111111111111111111121111111111111211111114111312111318111311131711412111313111311131711313411112111313111311121113131113111317113133180111111111111111111111111111111111111111111111111111111111111111111111111111111112111111111111111111111111111111111211111111111112111111141113121113181113111317114121113131113111317113134111111111111111111111111111111111121111111111111211111114111312111318111311131711411111111111111211111114111312111318111111114111312114111413111131413131141413131413131141312141413131413131414131314131311214131213181413121414131314131314141313141313141312141413131413131414131314131311212141312131813131714121413121318141312141413131413131414131314131314131214141313141313141413131413131214131213181413121414131314131314141313141313141312141413131413131414131314131311212121413121318131317141213131313171313412121413121318131317141214131213181413121414131314131314141313141313141312141413131413131414131314131312141312131814131214141313141313141413131413131413121414131314131314141313141313121214131213181313171412141312131814131214141313141313141413131413131413121414131314131314141313141313121413121318141312141413131413131414131314131314131214141313141313141413131413131
```
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
$FDÅγRŠ)S
```
Outputs as a list of digits (except for \$n=0\$ resulting in `1` instead of `[1]`).
[Try it online](https://tio.run/##yy9OTMpM/f9fxc3lcOu5zUFHF2gG//9vAgA) or [verify the test cases in the range \$[0,10]\$](https://tio.run/##yy9OTMpM/R9ybJKSZ15BaYmVgpK9nw6Xkn9pCZRn@N/PzeVw67nNQUcXaAb/r7XlUgooSi0pqdQtKMrMK0lNUciHq/XSObTN/j8A).
**Explanation:**
```
$ # Push 1 and the input-integer
F # Pop and loop the input amount of times:
D # Duplicate the current list (or 1 in the first iteration)
Åγ # Pop and run-length encode it, pushing the list of digits and list
# of lengths separately to the stack
R # Reverse the list of lengths at the top
Š # Triple-swap the stack: a,b,c to c,a,b
) # Wrap all three values into a list
S # And convert it to a flattened list of digits
# (after the loop, the result is output implicitly)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
1ŒrUj@ƒƊDFƊ¡
```
[Try it online!](https://tio.run/##y0rNyan8/9/w6KSi0CyHY5OOdbm4Hes6tPD////mAA "Jelly – Try It Online")
Fixed thanks to pxeger
```
1 Ɗ¡ Repeatedly apply the given number of times, starting from 1:
Œr Encode as a list of [digit, run length] pairs,
U reverse each pair,
j@ƒƊ join each of them around the original value in sequence,
D decompose the elements of their results into digits,
F and flatten them.
```
[Answer]
# [Rust (1.53+)](https://www.rust-lang.org/), 124 bytes
```
|s:&str|{let(mut r,mut x)=(s.into(),0);s.chars().chain([' ']).reduce(|a,b|{x+=1;if a!=b{r=format!("{}{}{}",x,r,a);x=0}b});r}
```
[Try it online!](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=f51eccbd5870632dcdcf99c61803e5e1 "Rust – Try It Online")
This only works on Rust 1.53 and newer as older Rust versions did not implement `IntoIterator` for arrays, but only for array references. This can be fixed by adding a single `&` to `[' ']`, in which case this might run on 1.51+ since that's when [`reduce`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.reduce) was stabilized.
In the future if [`group_by`](https://doc.rust-lang.org/std/primitive.slice.html#method.group_by) is stabilized, [this can go down to 96 bytes](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=337f412f73bc67bef21150edc041a292).
[Answer]
# JavaScript (ES6), ~~ 67 ~~ 62 bytes
*Saved 3 bytes thanks to [@MarcMush](https://codegolf.stackexchange.com/users/98541/marcmush)*
0-indexed.
```
f=n=>s=n?f(n-1).replace(/(.)\1*/g,q=>s=q.length+s+q[0])&&s:"1"
```
[Try it online!](https://tio.run/##FcpBDoIwEEDRPaeYEEJmrBS6VasHURMabLGmaYESNw1nr7L6i/c/6qvisNhpbXx46ZyN9PIapb8Z9I0gvujJqUFji5we4tCOx3n3mTvtx/XNIpvv3ZPqOp5KUWYTFrQgoTuDhQuIvYwRpAJgCD4Gp7kLI/YKq2Q3@q9VMmhp66nY8g8 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 49 bytes
```
K`1
"$+"{`$
¶$`¶$`
2%`(.)\1*
$1
0%^`(.)\1*
$.&
¶
```
[Try it online!](https://tio.run/##K0otycxLNPz/3zvBkEtJRVupOkGF69A2lQQQ5jJSTdDQ04wx1OJSMeQyUI2D8/TUgIq4/v83AQA "Retina – Try It Online") No test suite due to the way the program uses history. Explanation:
```
K`1
```
Replace the input with `1`.
```
"$+"{`
```
Repeat the originally input number of times.
```
$
¶$`¶$`
```
Triplicate the current string.
```
2%`
```
Only in the third copy...
```
(.)\1*
$1
```
... remove all adjacent duplicates.
```
0%`
```
Only in the first copy...
```
^`
```
... reversing the list results before reinserting them...
```
(.)\1*
$.&
```
... count the runs of repeated digits.
```
¶
```
Join everything together.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~65~~ 55 bytes
```
Nest[Join[Length/@Reverse[s=Split@#],#,#&@@@s]&,{1},#]&
```
[Try it online!](https://tio.run/##DcuxCoAgEADQXwkEpwNragpujoioURwkDhPSIo@W6Nuv3v6S542S57h6CZ2MVNj2R8x2oBx4MzjTTVchW7rl3COjcqBAaUQsTsPTvKCclumKmSuD4Q8@B7I1tE7kAw "Wolfram Language (Mathematica) – Try It Online")
-10 bytes from @att
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 113 bytes
```
g=lambda c,o,r:r and g(1+c-c*(b:=r[1:2]!=r[0]),b*str(c)+o+r[:b],r[1:])or o
f=lambda n:n and g(1,*2*[f(n-1)])or'1'
```
[Try it online!](https://tio.run/##NYwxDoMwDAD3vsKdsEOQCF2qSLwEZUhCQyO1DjIsfX0KA9MNd7r1t78LP56r1LqMH/8Ns4eoixYr4HmGBU0bu6gw2FEmYwd3P9g70kFtu2CktrQy2eD0qR0VgXJL14otXxutBjUl5M7QWTWmqemIM2QG8by80PRkYZXMOybMRPUP "Python 3.8 (pre-release) – Try It Online")
Very loosely based on @tsh's answer.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 55 bytes
```
->n{a=?1;n.times{a.scan(/(.)\1*/){a=[$&.size,$1]*a}};a}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOtHW3tA6T68kMze1uDpRrzg5MU9DX0NPM8ZQS18TKButoqZXnFmVqqNiGKuVWFtrnVj7v6C0pFjB0ACiSS83sUBBLe0/AA "Ruby – Try It Online")
[Answer]
# BQN, 43 bytes
```
{({‚àæ‚Ä¢Fmt¬®(‚↬®‚àò‚åΩ‚àæùï©‚àæ‚ä묮)ùï©‚äîÀú+`¬ªù既↬´ùï©}-‚üú'0')‚çüùï©"1"}
```
[Try It!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAge3viipHijL0oPPCdlakpeyjiiqPiiL7wnZWo4oi+4oqiKcK08J2VqX1gKOKJoOKIvuKKkSnCqPCdlaniipTLnCtgwrviiaDin5zCq/Cdlal94o2f8J2VqeKLiDF9Cgoo4oCiU2hvdyBGKcKo4oaVMTA=)
`‚äî` does some heavy lifting here.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~32~~ 29 [bytes](https://github.com/abrudz/SBCS)
Thanks to [Razetime](https://codegolf.stackexchange.com/users/80214/razetime) for -3 bytes!
```
{∊⍕¨(≢¨∘⌽,⍵,⊃¨)⍵⊂⍨1,2≠/⍵}⍣⎕⍕1
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97X/1o46uR71TD63QeNS56NCKRx0zHvXs1XnUu1XnUVfzoRWaQNajrqZHvSsMdYwedS7QB/JrH/UuftQ3FajLEGTG/@q02kMrFCz0DbgMuAy5jLiMuUy4TLnMuMwB "APL (Dyalog Unicode) – Try It Online")
`{ ... }⍣⎕⍕1`: Starting with `'1'`, iterate the function input times.
`1,2≠/⍵`: Binary vector with 1's at the start of runs of equal items.
`⍵⊂⍨`: Using that boolean mask split the current value into chunks.
`( ... )`: Apply inner function to the nested list: `≢¨∘⌽`: The lengths of each run, reversed,
`‚çµ`: the current value,
`⊃¨`: and the first value in each run.
`⍕¨`: Format each value as a string.
`‚àä`: Join into a single string.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 89 bytes
```
f(n)=if(n,s=f(n-1);c=k=0;[if(c==d,k++,k&&s=Str(k,s,c);c=d;k=1)|d<-Vec(s)];Str(k,s,c),"1")
```
[Try it online!](https://tio.run/##RY0xCsMwEAS/IlyYO3wCqwzKviKQJqQIUhzEgSIkl/67IldppthZmPKqyX5K7xtlRhqUhkHr2AcoVv8YYwCi6LKIznPDba@k0iScl@gVjo94tfd3oMZP/9cyuYn79q2UDcwq5iKm1JR3OmvM/Qc "Pari/GP – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 124 bytes
```
g=lambda s,c,t,l=0:t and(t[0]==s[:1]and g(s[1:],c,t,l+1)or g(s,`l`+c+t[0],s))or c
f=lambda n,s='1':n and f(n-1,g(s,s,s))or s
```
[Try it online!](https://tio.run/##NYzBCsMgEETv/Yq9RckWYk9F8EtEiDXVCukmuF7y9TbS9jIww5u3H/W10a21ZFb/fiweGANWXM2kK3haRLWTM4atVu6skARbpd0XGpXcSp9wXucxjJ1Fln0Ml/g3ErIZ1KCp@yAKuirsH/6h3OKZGTJB8ZSe4i417CVTFVFkKdsH "Python 2 – Try It Online")
[Answer]
# TypeScript Types, ~~302~~ 271 bytes
```
//@ts-ignore
type I<S,D,T=S,N=[0]>=S extends `${D}${infer S}`?I<S,D,T,[...N,0]>:S extends`${infer C}${infer S}`?I<S,C,`${N["length"]}${T}${D}`>:`${N["length"]}${T}${D}`;type M<N,C=[],S="1">=N extends C["length"]?S:S extends `${infer A}${infer B}`?M<N,[...C,0],I<B,A,S>>:0
```
[Try it online!](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACASQB4BlAGgBFKAVAXioDkGBtABgF0A+Jw9AA9w6RABNIhAAYASAN7UAvvNiIAZulSFyiqQH4yVWnUpsAdBeaVuPAFzkBw0RNlzVGrQGFlb9Zu26BhSUnpSuzGwARAA2ovDgABaRXD50PkpSduFRsYjxSSnyafIZANy4BIQAsqRWnuxclOQMkQCMkXzMjiLikp45cYnJeuT23c6Sru7+AII+01oAQoE1VuYWodyUZIuUM008dhyY2PhEdByEDNWkHDylmCCEzwB6eqeVdK1XN633j8BnoQ3h9zgAmH41MH-J6vd4Vc4AZkhpERMMBcNBhDoABYUTj0UCQQjsQBWFGkwmYkl0ABsKNpVOB8LO2IA7Ci2Uziay6AAOFF87ksz4AThRouFmCAA)
# Ungolfed / Explanation
```
type Iterate<
Str, // the remainder of the string
Char, // the current char being counted
Out = Str, // the output string being worked on
Count = [0], // the current count of the characterChar
> =
Str extends `${Char}${infer Rest}`
// If Str starts with Char, add one to Count and continue
? Iterate<Rest, Char, Out, [...Count,0]>
: Str extends`${infer NewChar}${infer Rest}`
// Otherwise, if Str is non-empty, add Count and Char to Out, reset Count, and continue
? Iterate<Rest, NewChar, `${Count["length"]}${Out}${Char}`>
// Otherwise, add Count and Char to Out and return it
:`${Count["length"]}${Out}${Char}`
type Main<
N, // the inputted number
Counter = [], // how many times the string has been operated on
Str = "1", // the current string
> =
N extends Counter["length"]
// If N == Counter, return Str
? Str
// Otherwise, iterate on Str
: Str extends `${infer FirstChar}${infer Tail}` ? Main<N, [...Counter,0], Iterate<Tail, FirstChar, Str>> : never
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 15 bytes
```
1ŒrZṚU1¦$jƲDFƊ¡
```
[Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCIxxZJyWuG5mlUxwqYkasayREbGisKhIiwiIiwiIixbIjUiXV0=)
fixed for +3 bytes thanks to Unrelated String, and I can't be bothered to golf or re-explain it anymore
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 24 bytes
```
LaLR`(.)\1*`ooPU#$0PB$1o
```
0-indexed. [Try it online!](https://tio.run/##K8gs@P/fJ9EnKEFDTzPGUCshPz8gVFnFIMBJxTD/////JgA "Pip – Try It Online")
### Explanation
```
LaLR`(.)\1*`ooPU#$0PB$1o
a is command-line arg; o is 1 (implicit)
La Loop a times:
LR` ` Loop over each regex match of
(.) a character
\1* followed by the same character 0 or more times
o in o:
oPU Push to the front of o
#$0 the number of characters in the match
PB and push to the back of o
$1 the first character in the match
o After the loop, output the final value of o
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 15 bytes
```
ŒrZU2¦ṚżWDF
1Ç¡
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700KzUnp3LBgqWlJWm6FtuOTiqKCjU6tOzhzllH94S7uHEZHm4_tHBJcVJy8dJDix7u6IGoW7DQEsIAAA)
Explanation:
```
ŒrZU2¦ṚżWDF inner link
Œr run-length encode (list of pairs of [element, frequency])
Z zip (produces [[list of elements], [list of corresponding frequencies]])
U2¦ reverse the second element
·πö flat-reverse (changes to [list of corresponding frequencies], [list of elements])
żW interleave with the input, producing [[[elements], [input]], [frequencies]]
NB: due to a bit of a quirk with Jelly's interleave function and vectorisation,
this makes [[a, b], c] not [a, b, c] as one would expect
D get digits of each item (in case an item has >=10 consecutive occurrences)
F flatten (smooths out both the oddity with interleave, and flattens the lists of digits)
1Ç¡ main link
1 starting with 1,
¬° repeatedly apply
Ç the above link
```
A naïve translation of the question description
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 47 bytes
```
≔1ηFN«≔⟦⟧υUMη⊞Oυ⎇∧λ⁼κ§η⊖λ⁺⊟υκκ≔⁺⁺⭆⮌υLκη⭆υ§κ⁰η»η
```
[Try it online!](https://tio.run/##RY7BasMwDIbPzVOYnmTwYIPeegrbDoWtC91uZQcv1eISx05lq2yMPburtIUKJCT0/frVOktttL6UOqV9F2D@MDfK6WX1HUnBKoyc1zx8IYHW6q@aXbHtp1Es1OzVjo9xGGzYgTOq4eTeRiSbIwEb9YEULP1CLWtv1POBrU/QG1XnVdjhz6R5wpZwwJBRGC0hZzwnaOIILEN/Tj2ZXc0v66m8Z9qHTn6ADR6REp4VLxi67KCfTjnJG8U3Z3niXl@IZfVfNYJkkL6URbk7@hM "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔1η
```
Start with the string `1`.
```
FN«
```
Repeat `n` times.
```
≔⟦⟧υ
```
Start collecting runs of digits.
```
UMη⊞Oυ⎇∧λ⁼κ§η⊖λ⁺⊟υκκ
```
For each digit, push a new run if the digit differs but concatenate it to the last run if it's the same.
```
≔⁺⁺⭆⮌υLκη⭆υ§κ⁰η
```
Get the run lengths in reverse order, concatenate that with the previous string, and finally append just the digits without repeats.
```
»η
```
Output the final string.
[Answer]
# Python3, 162 bytes:
```
from itertools import*
lambda n,c=['1']:c if n<2 else f(n-1,c+[''.join((k:=[*zip(*[(a,str(len([*b])))for a,b in groupby(c[-1])])])[1][::-1])+c[-1]+''.join(k[0])])
```
[Try it online](https://tio.run/##NYzBDsIgEAXvfsXeurTUFL2Yxn7JyqEgKJYCoXioP19TE/NOM5O8tJZnDOdLypsdbpsfZ3UfIXA9UCUq2WtwFsL1BMYvBiyGVnDdUFUdX9EFxKkfqP64hDXhyJeS0ZuAVCvJGLMxw8gVuACPHN9JraipFZLtIyGp73dqfrL5f07U7f1gc5zBFZNLjH4BN6eYS72l7EJBi6eOse0L)
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 19 bytes
```
1{XXf:([-)scFLim}C~
```
[Try it online!](https://tio.run/##SyotykktLixN/V@S@d@wOiIizUojWlezONnNJzO31rnu/39DQ2MjYwA "Burlesque – Try It Online")
```
1 # Needed by C~
{
XX # Explode to digits
f: # Count frequencies
([-)sc # Sort by comparing the digit (tail)
FLim # Flatten and implode back to number
}C~ # Continue forever
```
[Answer]
# [Julia 1.0](http://julialang.org/), 73 bytes
```
!n=n<2 ? "1" : (s=!~-n;replace(s,r"(.)\1*"=>m->s="$(length(m))$s"m[1]);s)
```
[Try it online!](https://tio.run/##DcExDsIwDADAva9wrQ42oggztiQ8BBgqCGCUmCopEhNfD9w931En@dTamrP9Dg6AgjAAFdd@extzmON0CVTWGWnDJ1mh86n3xWFHMdh9eVBi7gqmo5x5LFxvrwwKaiCDbBv4m7PaEo0UnIdWuQl2rT8 "Julia 1.0 – Try It Online")
Similar to [Arnauld's JS answer](https://codegolf.stackexchange.com/a/238003/98541)
[Answer]
# [R](https://www.r-project.org/), ~~91~~ 90 bytes
Or **[R](https://www.r-project.org/)>=4.1, 83 bytes** by replacing the word `function` with `\`.
```
function(n,s=49){while(n<-n-1)s=c(unlist(Map(utf8ToInt,c(rev((r=rle(s))$l),""))),s,r$v);s}
```
[Try it online!](https://tio.run/##xVBLCsIwEN17CgkuZmAU0lasnx7AhTs9QCktFkJak1QR8ey1SerCDyhufDDzhjcvM0lUWyRt0cjMlJUESTqJ5ng57UuRg1yN5ZijTjJopCi1gU1aQ2OKeFutpaEMVH4EUInqzBpxJJAYQ0TSpEZHXOprK9K6FmfoiS@mVCCV0myrXTcHB4NUiEl@aFIB2nv03Ro/WmmYAeOMGOc2h9xzxF0V@k7EbfSKLXrdI3Jy8NbWkS9eTnkEzzO6HP8w2FHwJH7Y/Q7BV7cLXcx84z@vcW1rshs@27/4HsT2Bg "R – Try It Online")
Outputs a vector of character codes for the digits. Add 3 bytes (`-48` at the end) for vector of digits.
See also [@Dominic van Essen's (shorter) solution](https://codegolf.stackexchange.com/a/238025/55372).
[Answer]
# [R](https://www.r-project.org/), ~~88~~ ~~87~~ 83 bytes
*Edit: thanks to pajonk for bug-spotting and then for -4 bytes!*
```
g=function(n,x="1")`if`(n,g(n-1,unlist(strsplit(c(rev((y=rle(x))$l),x,y$v),""))),x)
```
[Try it online!](https://tio.run/##RY2xCsQgEAX/RVLsgz2I7YH/kiMkIresoibo1xu7VMM0M3mUX5cY/xNueHdeutcQlZSbM9ZgC@c2xZN@LF8qoVQqNZckodJO@biJustyUAMWATfuyw02BpiC2U9JOtmvXfl9YTw "R – Try It Online")
Recursive + character-based alternative to [pajonk's iterative R approach using ASCII codes](https://codegolf.stackexchange.com/a/238019/95126).
Each recursive call gets the lengths & values of the run-length encoding (`rle`), splits any multi-digit lengths into individual characters (`unlist(strsplit(...,""))`), before wrapping these around the last previous iteration.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 22 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
_+ó¥ ÕÎ iZó¥ cʬw}g'1q
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=XyvzpSDVziBpWvOlIGPKrHd9ZycxcQ&input=Mw)
```
_...}g'1q - run f(Z) input times starting with ["1"]
+ - append to Z:
ó¥ ÕÎ * first column of Z splitted on different char
i - then prepend:
Zó¥ cʬw * lengths reversed
```
]
|
[Question]
[
Given a permutation of the alphabet and an intended "word", determine if the word was guessed in a game of [Hangman](https://en.wikipedia.org/wiki/Hangman_(game)), where the permutation is the list of guesses.
For example, given `ASTNORDYUVKFMCLWIHEBQGPJXZ` as the permutation, and `ASTRONAUT` as the word, we know that the word was guessed. Only 2 letters (`DY`) were wrong before guessing `U` to complete the word. At the end of the game, the gallows look like
```
|
|
|
|
|
|
------
```
so the man wasn't hanged and the guesser wins.
However, if the word was `PAYMENT`, then there are 12 wrong guesses (`SORDUVKFCLWI`) before the word is complete (the "filled in" word looks like `_AYM_NT` at the end), so the guesser loses.
The full gallows takes 12 steps to finish:
```
------ ------ ------ ------ ------ ------ ------ ------
| | |/ |/ |/ | |/ | |/ | |/ | |/ | |/ | |/ |
| | | | | | O | O | O | O | O | O
| | | | | | | | | /| | /|\ | /|\ | /|\
| | | | | | | | | | / | / \
| | | | | | | | | | |
| |\ |\ |\ |\ |\ |\ |\ |\ |\ |\
------ ------ ------ ------ ------ ------ ------ ------ ------ ------ ------ ------
```
So 12 wrong guesses before the final correct letter is a loss and the final correct letter before 12 wrong guesses is a win.
---
You are to take 2 strings as input:
* A 26 character long string, containing 26 unique letters in a consistent case i.e. a permutation of either the uppercase or lowercase alphabet
* A string containing a maximum of 26 unique characters and a minimum of 1 character, in the same case as the permutation
You should then output 2 distinct values to indicate whether the word was guessed before 12 wrong guesses or not.
You may input and output in any [convenient method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). The length of the second input will never exceed your language's integer maximum.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins.
## Test cases
```
permutation, word -> output
ABCDEFGHIJKLMNOPQRSTUVWXYZ, CGCC -> 1
ABCDEFGHIJKLMNOPQRSTUVWXYZ, LAB -> 1
ABCDEFGHIJKLMNOPQRSTUVWXYZ, MOP -> 0
ABCDEFGHIJKLMNOPQRSTUVWXYZ, MNOPQRSTUVWXYZ -> 0
ABCDEFGHIJKLMNOPQRSTUVWXYZ, LMNOPQRSTUVWXYZ -> 1
NYLZCBTOAFEQMVJWRHKIUGDPSX, NYLON -> 1
NYLZCBTOAFEQMVJWRHKIUGDPSX, GOLF -> 0
DXAPMHBYRVNKOFQZCSWUEJLTGI, ABCDEFGHIJKLMNOPQRSTUVWXYZ -> 1
INRLVTXOZSAKWJYFBQDMGPHUCE, IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII -> 1
INRLVTXOZSAKWJYFBQDMGPHUCE, EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE -> 0
FICUJKXZYVDGEWRLMANBHOPSTQ, RDRYMUTSDOVSEHWT -> 0
ASTNORDYUVKFMCLWIHEBQGPJXZ, ASTRONAUT -> 1
ASTNORDYUVKFMCLWIHEBQGPJXZ, PAYMENT -> 0
```
[Here](https://tio.run/##AT0Awv9qZWxsef//ZeKCrOG5ozHhuZZGTDwxMgrDmEFYwrU5OVjCpMOQwqHhuIosQMOYQeG6isKkwrU7w6cvWf//) is a Jelly program which automatically generates test cases in the form
```
permutation
word
output
```
Spoilers for anyone who understands Jelly
[Answer]
# JavaScript (ES6), ~~43 41~~ 40 bytes
Expects `(alphabet)(word)`, where `alphabet` is an array of characters. Returns a Boolean value.
```
a=>w=>a.every(c=>w.match(c)?~a<11:a=~-a)
```
[Try it online!](https://tio.run/##ndO7TsMwFAbgnaeoMiVDU7oiUpTYzt124ti5IQYrpFxUGtRWIJa@eihBDIgmpD2b7eHTf87xs3yT22rz9Lqbrpv7ul0arTQW78ZC6vVbvflQq8NJf5G76lGttJu9vJ7Pr6Sxn0qtrZr1tlnV@qp5UJfqra7rimkBiGzH9fwgxIRGMUu4SLO8KJU7TVWAA4CiaZMxNZtNJvOL043QtMYSZxuYRicZl@cYv68GuV6DFGEJLE5NG8U49TPmBp5wYJTknXF4pmRkkt5e/WM4NLRPmfnRHDA3I@xaBUtJQO24BEkmkB9yx@uMgVb@kXtzeISFKc9pmZhB5he2FUPsRK4AqDO8kfUlnmugkfVjHO2V7QHhB3lZpNBBGQuxSSyXRgmPO4NBVmDBE0jTBLkZH5pN/@4mnFAGC5EGNgZh5rnIip3Iz7939/DMKDEFHzH4/j84bERmgRHho1ary9F@Ag "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // a[] = alphabet, reused as a negative counter of errors
w => // w = word to guess
a.every(c => // for each character c in a[]:
w.match(c) ? // if c appears at least once in the word:
~a < 11 // make sure that there was less than 12 errors so far
// (this is equivalent to a > -12)
// NB: we only need to test the number of errors when a
// correct character is found, for it means that the word
// was not fully guessed yet
: // else:
a = ~-a // decrement a (always truthy)
) // end of every()
```
[Answer]
# [Python 3](https://docs.python.org/3/), 42 bytes
```
lambda a,s:max(map(a.find,s))-len({*s})<11
```
`max(map(a.find,s))` gives us the index of the final correct letter. Subtracting this by the number of unique characters in \$ s \$, gives us the total number of incorrect guesses. Finally, `...<11` ensures that at most `11` incorrect guesses are made.
[Try it online!](https://tio.run/##jZFNT4MwGMfv@xS9DUy3SLwtzgRKeW8LpbzGC2ZbRrIxIixqjJ8dQebBg2zPqe3/l9/TPq0/2v2peuh26@fuUBxfNgUoYLM6Fu/SsailYrkrqw1sZHlx2FbS513zJT8qSve2Lw9boKxmoKxqCE7ntgbrYX1uJXnZ1IeyleZg8QTm8qwXgmZMfxP4c16/llUr7aQhl0eJ3Kka0rFhWrbjeoQyP@ChiOIkzXIIkInQIFVmU5SnatchwvwBup@G/uxHnmZejjTBVAMHJHYSbrl2ZOp@mELQZ4yOvacwk3nGKNNT1SeWlvGYuswIchQmEXY8YdoQ/H@xsYNNuReLlOWh6iZOZmiBTkzfihCGwL6xrpvwjTW@x7BR5LhpnsW6iRPuEZVqFvNDEUDAdZ6RSIQ6i0NsJeIy/lBQxvUsil2DIC@xLawFpu@k/fj7jDOqRuLynROor2YE09H5DQ "Python 3 – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 21 19 bytes
```
12>1#.0=#:@#.@|.@e.
```
[Try it online!](https://tio.run/##pZHJasMwFEX3@QpRQ02hFnGXgRRbowdNluRBhq5KQummP1D6625wsnA2iUsfCITe0XlI93N6gPER7HcgBs9gC3anlUCArWBT@vKaRnC7j3ZZBLNvmB3g9LRRCII0yhL48/YIz@ebw/vHF4hzhAllvCirWkilTWOdb7t@CGMMjiDGHOP4gpIhN7JAwXaq1qwZsetbWgnPyxm9YboIkiS5bFOw/8voNbjI0YXerqClNku3CmLEyOuc0UZ2VW@Lumw5MW6Y6VNbq6X9Ds@1YEv9f39ulpTKis4PenR53VeBoYZIbooW01lSrqzlM@4o6cpaKlmJ26oextARTnsrZK5QoY3zzay0xAbZekd052jR@6uAnVfaktB2NZNY9GVBUcNNNZwjO7WtVnnrr2K@fcfkQVLl4@kX "J – Try It Online")
Consider:
```
echo 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' f 'CGCC'
```
* `e.` Is each left char an element of the right string?
```
0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
```
* `|.@` Reverse
```
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0
```
* `#:@#.@` We want to remove those leading zeroes, so we convert to decimal
number `#.` and then back to a binary one `#:`
```
1 0 0 0 1 0 0
```
* `12>1#.0=` Sum the remaining zeroes and check if there are less than 12.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
iⱮṬ¬S<12
```
[Try it online!](https://tio.run/##jZE7TsNAGIRrcgrkOhKCmmbfu/a@vE@vo5QUoFyAlsvQWEiUtHASchFjk1DQwE75zzejX5qHu8PhcZ7vj68vn2/T@@Rvr2/mj@er49M0z7vNxa4BEGFCGRdtJ5U2tnc@xJSHMjbbywYxhJr99n9QAljFKWPruN@XU0QXOSIYDKCkV6nNjnciMmz9sEYW1@gqkhlJzyAegFUcFpd0Z2g/Ip8jaWVgYgX/@PEUF9rJFAYzetDltlDYY8Usj4iscVGpqjJSqXMZFSi23TCWhBnJTiqgITfWh34tc9gVFYPHJnnCc/jZxAdtHC4xdVQhmQUnsGe2Hb43WVxnNIh1tAVFEb2wm/0X "Jelly – Try It Online")
-1 byte thanks to caird coinheringaahing
## Explanation
```
iⱮṬ¬S<12 Main Link
Ɱ For each element in the right argument (the word to guess)
i Find its index in the left argument (the guess order)
Ṭ Array with 1s in those indices; removes duplicates and only leaves zeroes before the last one, so the number of zeroes is the number of wrong guesses before we guess the word
¬ Logical NOT; the 0s and 1s swap
S Sum (we could've also done "count zeroes" instead of "NOT -> sum")
<12 Is the number of wrong guesses less than 12?
```
[Answer]
# [Vim](https://www.vim.org), 34 bytes
```
qf11llddqu:s/[^<C-r><C-w>]*$
:s/[<C-r><C-w>]//g
@f
```
[Try it online!](https://tio.run/##K/v/vzDN0DAnJyWlsNSqWD86zsZZt8gOSJTbxWqpcIGEkET09dO5HNL@/3d2d3bWcXRycXVz9/D08vbxdfbzDwgMCg4JDQuPiIz6r1sGAA "V (vim) – Try It Online") ([falsey test](https://tio.run/##K/v/vzDN0DAnJyWlsNSqWD86zsZZt8gOSJTbxWqpcIGEkET09dO5HNL@/3d2d3bWcXRycXVz9/D08vbx9XP2DwgMCg4JDQuPiIz6r1sGAA), [pangram test](https://tio.run/##K/v/vzDN0DAnJyWlsNSqWD86zsZZt8gOSJTbxWqpcIGEkET09dO5HNL@/3d0cnZxdXP38PTy9vH18w8IDAoOCQ0Lj4iM0omKjAgPCw0JDgoM8Pfz9fH28vRwd3N1cXZy/K9bBgA))
Takes the secret word followed by the permutation, comma separated.
```
qq11llddqu
qf q " define a macro named 'f'
11l " go forward 11 characters (succeeds if it can move at least 1)
l " and one more *exiting f if we can't*
dd " delete the current line
u " undo the line deletion for now
:s/[^<C-r><C-w>]*$ " delete the maximal suffix of this line of characters not in the word
" <C-r><C-w> inserts the word under the cursor (i.e. the secret word) into the expression
:s/[<C-r><C-w>]//g " delete all characters which are in the word
@f " call f
```
This will delete the (only) line in the buffer if there are at least 12 wrong guesses before the word is complete (falsey), or leave a `','` followed by some letters (i.e. the possibly empty set of wrongly guessed letters).
The `f` macro came out shorter than using the expression register:
```
C<C-r>=len("<C-r>"")<12
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 45 40 34 bytes
```
->g,s{!g[/.*[#{s}]/].tr(s,'')[12]}
```
[Try it online!](https://tio.run/##lZLLSsNAFIb3PkXERVqpLbqvMLdMLnPL3JJJ6ULBduNCmnYhpc8eG8HdEOrZHr7v53D@w@n9e9ith6fX/aI/3@83q@Xj5uHcX7ar7fJ4mPWLNJ1vnl@2l@HrdOyT4@H0kazXyW45SwFEmGQ0L8qKcSFVrY11vmlDly6SFFGE0vndPykG4B@0e/vsb6S4VLEoEViHoJUgIzX3ZaPzqnAUK9OO0HUrRTRsmqOSZbE03ALFcxi0F5XM6g6ZxpGSWVqM1MQBEVchNPO2lZ0BVVOGDNaYU5U7REZXceNEj5tWkxsnqs4K5Mqq7YLHlDSacSBgLpWx9ajWWAfurMHSG5I3NloOY4XUODhfZRyxpsgJrKkq2983X7daCuBsvCKTrAKBE3Elhx8 "Ruby – Try It Online")
-6 bytes thanks to "G B" for the "index into string to verify min length" trick!
I kinda liked the idea of solving it with a regex...
We just greedily match for a string ending in one of the chars from our target string, then remove the target string chars from that match, then check the size.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 39 bytes
```
a=>w=>!a.match(`(.*[^${w}]){12}[${w}]`)
```
[Try it online!](https://tio.run/##jZJLT4NAEMfvfIo18QCWovVqaALL8t5dWJZnrQEr9REsxhJ7aPrZsUovHmw7p5nML/95vlVf1Xrx@frRjVftU90v1b5Spxt1elEp71W3eBFLUbmaPVxuN7u5tJ3c7ma/bin1nVpqOjSQadmO6/mY0CBkEY@TNMsLGUALQjCegolwjPI1/TSEafAD3RyH/sQDT3K/gDqnmolCnLgpsz0ntowgymSwz1Ey1D6GWdQ3BzEj0wJs6zlLiEfNsIBRGiPX55Yjg/8bGyo4hPkJz2gRaV7q5qYeGtgK7BgiGThn2mkldKYN85gOjF0vK/LEsFDKfKwR3aZBxEMZMIPlOOaRQZMI2Sk/rD/ihDIjjxPPxNBPHRvpoRW42X79@xyjRIv54ZxH0EDLMSKDZil0yvqjee1KoVSW7Seq9i/XqNOt0NQdmFXyo1zPVdAcnvF6dr@5f5qPrp@lO2HRrtZtUytN@ywuxUoSHyUZjGpJ2En9Nw "JavaScript (Node.js) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 46 bytes
```
function(a,w)max(m<-which(a%in%w))-sum(m|1)<12
```
[Try it online!](https://tio.run/##tZNda4MwGIXv@yvEUVBoYd3tuoHGGKMm0SR@xJsipaNC7UY/5i723123XYzB7JTS9zbv4TnnDWfXlvUCL8pN9bp6aJ@O2@Whet4a5aQx6/LNqOfTZl0t10Y5rrbjxjSn@2Nt1O8zcz67a8uH1cbYH3b7l011MHTLBg50kYf9ICSURTEXMkmzXBX6RNdN815rfgsAAuD7afTj4out3WjTR202upQQWvZ1AYRF5wC3lwP@WOrJoiosgC2Z5cKYpH7GvQAnyIlE3sE6CRgddK/BCMRCd1AIJ7ci4tmKpzRgblwAkSXQDyXCHYT/LtwzGaY8TGXOCmEFma9cO3YIirwEwA4u7jnXdQF7zqA/cDFI/CAvVOogmPGQWNT2WCRk3OGCO1yRRAqHpQJ6mRxWESEp445K0sAlIMywB@0YRX7eVZGTgDNqJXJY1YdiIksRSOV16/65dT5G@wE "R – Try It Online")
Input is two vectors of characters representing the alphabet (`a`) and the word (`w`). Outputs `TRUE` if I did not die.
Checks that the `max`imum index (`which`) of the elements of `a` that are in `w` is not 12 greater than the number `m` of those elements (which is the number of unique elements of `w`).
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~10~~ 9 bytes
*Edit: -1 byte thanks to Leo*
```
↓12-¹Σhġ€
```
[Try it online!](https://tio.run/##ATgAx/9odXNr///ihpMxMi3Cuc6jaMSh4oKs////Q0dDQ/9BQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWg "Husk – Try It Online")
Arg1 = word; Arg2 = alphabet; Outputs truthy if I did die (list of excess moves needed after hangman is already complete), falsy (empty list) if I did not die.
```
ġ€ # group arg2 by whether each element is present in arg1
h # discard the last group (all the letters
# after the last guess, or the last guess itself)
Σ # put groups back together into one list
-¹ # get only letters not present in arg1
↓12 # remove the first 12 of them.
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 17 bytes
```
‹LΦ…θ⌈Eη⌕θι¬№ηι¹²
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMntbgYSOSll2RouGXmlKQWaThXJuekOmfkF2gU6ij4JlZk5pbmavgmFmhk6Ci4ZealgIQzNYFAR8Evv0TDOb8UaE4GXMzQSFPT@v9/v0ifKGenEH9HN9dA3zCv8CAPb89Qd5eA4Agud38ft/@6ZTkA "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for a win, nothing for a loss. Explanation:
```
θ Input permutation
… Truncated to length
η Input word
E Map over characters
θ Input permutation
⌕ Find index of
ι Current character
⌈ Take the maximum
Φ Filtered where
№ Count of
ι Current character in
η Input word
¬ Is zero
L Take the length
‹ Is it less than
¹² Literal `12`?
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 10 bytes
```
ôoV ÔŬÊ<C
```
[Try it online!](https://tio.run/##y0osKPn///CW/DCFw1MOtx5ac7jLxvn/fyVHJ2cXVzd3D08vbx9fP/@AwKDgkNCw8IjIKCUuJWd3Z2clAA "Japt – Try It Online") or [check all test cases](https://tio.run/##jZG7TsMwFIb3PkWUuZVgLiA5tuM48S2@xqk6MFVCQunAK7Aw8xiMPAF5sBC3LCzgs9jH5/t@WTpPj@eXZXO63bv7080yf06@mN/n16@P@e0OLnJyezmV26JcD5@uxe4hNeewHA4lqCDCNWlo2zEupOq1sc6HIY5JgQTC8rjd/McxUOVgXKos7PfLxRCRjbCyEtS4574NuumoI0iZIRnrVIockEhWXzk0AMWbKmovOln3IzTB4ZZZQhP3xwcvNhWaeTvI0YAutLGuesSJahzEyaaZlZOFM@uaVVPo2m4Yo0cEB804EFUjlbF9ytJIR@6sQdIb3AT7swxjhdQoOt/VHLJAG1z1RLXDZRnrVEsBXBasQORYrOix2D1/Aw)
Explanation:
```
ôoV ÔŬÊ<C
ô # Remove characters from Input 1 where:
oV # It appears in Input 2
# And split where characters were removed
Ô # Reverse the resulting array
Å # Remove the first element
¬ # Join the remaining strings
Ê # Get the total length
<C # Return true if less than 12, false otherwise
```
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), 14 bytes
```
12>+/~2\2/|~^?
```
[Try it online!](https://tio.run/##jZBLS8NAFIX3/grJxhTRYpYNKPOeSeaVeWaCCN3UhdBfIP3rMaYrN6Zncy@X75wL5@vp/Hme59PhpXl93F@a92b/ffl4m4@Huq4QQ6hqKwARJpRx0fVSaWMH50NMeSxTtWvrSgK4DSljb4D@njZ5XaTRC7bMCcFgACWDSl12vBeRYevHFWNG0m3qn19thUdgFYfFJd0bOkzI50g6GZhYveJGLUlCO5nCaCYP@twVCgesmOURkTWJ3KjtJIddUTF4bJInPIfFQQWKXT9OJWFGspMKaMiN9WG4NuCDMxrEX3TZtXG4xNRThWQWnMCB2W68Nm9BUURvgbu70/3zw3H@AQ "K (ngn/k) – Try It Online")
A straightforward port of [@Jonah's J answer](https://codegolf.stackexchange.com/a/223997/98547).
Implicitly takes a pair of args; `x` as the word, and `y` as the permutation.
* `~^?` check whether each letter in `y` is present in `x` (literally, `not null x find y`)
* `2\2/|` a port of @Jonah's logic to trim trailing 0's appearing after the last 1 (convert the reverse of the boolean list from base 2, then back to base 2; although the resulting list is reversed, this doesn't matter, as...)
* `12>+/~` is 12 greater than the number of 0's in the trimmed list?
[Answer]
# [Haskell](https://www.haskell.org/), 61 bytes
```
(12#)
(l#(h:t))w|elem h w=l>0&&(l#t)w|i<-l-1=i#t$w
(_#_)_=0<1
```
[Try it online!](https://tio.run/##jZFLj9owFIX3@RWWQEMsOVMyyw5GysN5OnHeL1VCmSEMUUOIIBUs@tubyRS6qKrC3J19vnPP9fW2PH6vmmbY4G8DLz5NIMc3E377tYfw9LNqqh3YghNulvOHh1Hox8t6ITSCiOtJPz1x/Gqygis8X4jDrqxbvN5zgK/RHi6Eza7s@PVh34En@Hjsypb/gmfCDC6my7eqp3VbcaCpesCX6AXi33Td1v3j1TL9Y0EzWD@fcb8n7Y/d9FCVazCGdIe67fkNKMELxmc09kBnyIGPIQZJVlSi6YZp2dRxmecHYRQnaZYXCCi6ogBhCUTuFkUl@T7kMO8Dmt@G/jrf5@m/BpFzc1oocsQkjfhOYqWBYZuxrnphhsCoMfc@pjOqXdLVTPIcQ86DxLWZ5hdKmMbEopFuIvD/yS4JphvQJMpYEUp2auWa7KuO7hmxQhAwP1n3O5FP1uU9mqnElp0VeaLqJA2oI7mywbww8hEI1CB34ihUWRISI42u@w8jlwVqHie25ig0NQ0i@7pnZeP@Ry1grhRH1/@/gXpS7hD30vPX66Yp346D8Np17w "Haskell – Try It Online")
Standard recursive implementation. The relevant function is `(12#)`, which takes as input the alphabet and the word as `String`s and returns `True` for guessed, `False` for dead.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 35 bytes
```
(.*)(.).*(,.*\2)
$1$3
Dr`
^.{0,11},
```
[Try it online!](https://tio.run/##jc65TsQwFAXQ3t8xSMnIigh8gXc78RavcYTQUFDQUIzoEN8epqUgmts9naurd33/@vh82x86cdm74dx3Qz@cOzicX556cBpPz4BeL@B1@H6E4/gD9x1hQhkXUk2zNtb5JcSUS13bBokgBBy4RviIjfOH/OcEtumN4OQQZ4spUw1yVllQH1d4I2ePCsJpDuiKvJG4hWJnx5eNxJrZpJNQ8P8vgLJBl7S6LaK5To3jhRrhZSYMqjtztMHuDOCK5Glet1aoYDVogyyWzse0wEBDMzlF6kpksiaAYrIu0JbLzA3RVUmGF@GndYM3Cs6ifFjyqBlm0y8 "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
(.*)(.).*(,.*\2)
$1$3
```
Delete the permutation starting at the last correct letter.
```
Dr`
```
Remove all remaining correct letters from the permutation.
```
^.{0,11},
```
Check that there were no more than 11 incorrect letters left.
[Answer]
# [Zsh](https://www.zsh.org/) `-ey`, 40 bytes
```
for c (${1/// })((${2[(I)$c]}?e<12:++e))
```
[Try it online!](https://tio.run/##qyrO@K9RnFqioJta@T8tv0ghWUFDpdpQX19foVZTA8g0itbw1FRJjq21T7UxNLLS1k7V1PyvyWVjY6Ni//@/X6RPlLNTiL@jm2ugb5hXeJCHt2eou0tAcARIyt8PAA "Zsh – Try It Online") or [verify all test cases](https://tio.run/##jZK7TsMwFIb3PIWHDIkq1KZjSVUc23GcxJfYzrXqVAWxUVGGAurIxiPAy/VFQjoyEPVM5@h8@s/1/fg0nNaX78/Lz5fz@PwCArAEB@DBCGES04SlWc6FVIU2tqzqpu0AogiBwJkgchhNA1wqsJgE/oYLR7R5hyIrYUwKXqW1TjJWUqxMA8aUFGO9CYTKPB5FcAMVT6JWVyKTcdEhU5ckzS1lYKKXwGFC55VtZGdgVqdtHBWYU5WUiAB2o02rkBttnCFmqEyzpmsrTEmtcw5FlEhlbAE01i0vrcGyMiSp7XXFxgqpcVtWWcxRXrOERAVVadOBMaWlgKW9nup/TMGWEzFq@R/esX8Fd/3bcP2TPfDcj2A@n4Oz743ucusx393vzps@DJar2az3/cG/D8PQPW2DmbdZrw/@buU@nIdf "Zsh – Try It Online")
Takes input in command-line arguments (`alphabet` `word`) and outputs via status code (`0` = survived, `1` = died). Uses [@Arnauld's method](https://codegolf.stackexchange.com/a/223996).
Explanation:
* `${1/// }`: replace every empty string in the first input with a space. With `-y`, effectively splits into a list of characters.
* `for c ()` for each character `$c`:
+ `(())`: arithmetic expression; succeeds only if the result is non-zero
+ `[(I)]`: find the 1-based index of `$c` in `${2}`: the second input. If there is no instance, returns `0`.
+ `?:`: if that was truthy (i.e. the character is present in the word), then return the `0/1` boolean value of `e<12`. Otherwise, increment `e` and return it (`$e` implicitly starts as `0`)
* `-e` flag: like a logical AND over the whole program, so the program will succeed only if every arithmetic expression also succeeded
[Answer]
# [Perl 5](https://www.perl.org/) `-pl`, 37 bytes
```
$b=<>;s/[^$b]/0/g;s/0*$//;$_=y/0//<12
```
[Try it online!](https://tio.run/##K0gtyjH9/18lydbGzrpYPzpOJSlW30A/Hcg20FLR17dWibetBAro2xga/f/vF@kT5ewU4u/o5hroG@YVHuTh7Rnq7hIQHMHl7u/jxuXo5Ozi6ubu4enl7ePr5x8QGBQcEhoWHhEZxeXs7uz8L7@gJDM/r/i/bkEOAA "Perl 5 – Try It Online")
Changes all non-target letters in the alphabet to `0`, removes trailing `0`s and then counts how many remain to determine if the limit has been reached before completing the target word.
[Answer]
# [C#](https://docs.microsoft.com/en-us/dotnet/csharp), 78 bytes
```
(g,w)=>{return !w.Distinct().Where(p=>!g.Substring(0,12).Contains(p)).Any();};
```
returns TRUE if any character is NOT contained in the first 12 guesses, if TRUE then test does not pass, so success variable needs to be the opposite (FALSE). if FALSE then test passes, so success variable needs to be the opposite (TRUE).
Explanation:
```
! # NOT
w.Distinct() # Get distinct letters from the word to guess (w)
.Where # find
p => # each distinct letter to guess (w) into p
! # NOT
g.Substring(0, 12) # first 12 characters of guess
.Contains(p) # is p contained in string
.Any() # returns true if any matched the condition
```
[Answer]
# [Julia](http://julialang.org/), 37 bytes
```
a*b=findlast(a.∈b)-length(b∪b)<12
```
expects `permutation*word` with `permutation` a list of characters and `word` a String
`b∪b` is `union(b,b)` which is equivalent to `unique(b)`
[Try it online!](https://tio.run/##jZJJbtswFIb3PMWDVlKQClGyE@qF5pGkBmpMs5CHJApUy7BppL2Bz9Jj5SIu7TgIuqiQtyF//B/@R/LxZT/0nfbreOyu5rPHfr0cuh2XO/XtcJgr34bV@ok/y/O3w5@58l27PfLVju9gBpIkIcO0bMf1/CCMYkxokmY5K8qqblqwPMsCbYqIDXMawDQBuJkk/pU3iDRxa5mMGq6T4jKsMj8KCs9O8hqERYloOIF4NHZFiF0bCfbNJitJRN20tfKqcMKYeQFMnEVDAcniktW0zY2oChvXTG3sJX5hORB8saZTnC@WuIMbWEUY1W1T2p5TZTE2iOnTJGcpZHbW4ILlNi1zx6/Y6YlzRmhmN0UZudiKq8B3zNRLwroFYWWUGAU7zer/WGI02CFselwnDdrp46CPX/S86Li82ww9V98X@excg/RjLSmKqqoKQmjc882eC3wxDsNqIdgzda9d6w8KqFfwLm@FRGjZi6Dut3yP9M1q@3PPO96Pa9Bfx@0SzqVf8kBfjNutyEOfccL@DIMP8LJRZ7NL5zvhCiVpkoIelONf "Julia 1.0 – Try It Online")
[Answer]
# [Bash](https://www.gnu.org/software/bash/)/[Zsh](https://www.zsh.org/), 29 bytes
```
[[ $1 =~ (.*[^$2]){12}[$2] ]]
```
[Try it online!](https://tio.run/##S0oszvj/PzpaQcVQwbZOQUNPKzpOxShWs9rQqDYayFCIjf3//7@jk7OLq5u7h6eXt4@vn39AYFBwSGhYeERk1H8fRycA)
* List of letters is given as first argument
* Word to find is given as second argument
* Exit status is 0 if dead and 1 if alive
This is the builtin equivalent to `egrep -q "(.*[^$2]){12}[$2]" <<< $1`
The idea is to build an extended regex that checks whether there are at least 12 letters not in the word to find (= wrong guesses) before any letter in that word (= guesses that came too late).
(initially 32 bytes, but enhanced with the help of [this answer](https://codegolf.stackexchange.com/a/224087/62898) from @tsh who had the same idea long before me)
]
|
[Question]
[
Imagine you have an array of integers, whose non-negative values are pointers to other positions in the same array, only that those values represent tunnels, so if the value in position A is positive and points to position B, then the value in position B must be also positive and point to position A to represent both ends of the tunnel. So:
### Challenge
* Given an array of integers, check if the array complies with the restriction to be a tunneling array and return two distinct, coherent values for truthy and falsey.
* The values in the array will be below zero for non-tunnel positions, and zero or above for tunnel positions. If your array is 1-indexed, then the zero value represents a non-tunnel position. Non-tunnel values do not need to be checked.
* If a positive value in a cell points to itself, that's a falsey. If A points to B, B to C and C to A, that's a falsey. If a positive value points beyond the limits of the array, that's a falsey.
### Examples
The following examples are 0-indexed:
```
[-1, -1, -1, 6, -1, -1, 3, -1, -1] Truthy (position 3 points to position 6 and vice versa)
[1, 0] Truthy (position 0 points to position 1 and vice versa)
[0, 1] Falsey (positions 0 and 1 point to themselves)
[4, 2, 1, -1, 0, -1] Truthy
[2, 3, 0, 1] Truthy
[1, 2, 0] Falsey (no circular tunnels allowed)
[-1, 2, -1] Falsey (tunnel without end)
[] Truthy (no tunnels, that's OK)
[-1, -2, -3] Truthy (no tunnels, that's OK)
[1, 0, 3] Falsey (tunnel goes beyond limits)
[1] Falsey (tunnel goes beyond limits)
[1, 0, 3, 7] Falsey (tunnel goes beyond limits)
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so may the shortest code for each language win!
[Answer]
# [R](https://www.r-project.org/), 47 bytes
```
function(v,a=v[v>0],b=sort(a))all(v[a]==b&a!=b)
```
[Try it online!](https://tio.run/##pZKxasMwFEX3fsUrhVaiNthxyaaOXTp06RYyyM5zLFCkIMkK@XpXjuymgTi4RCAQHs657z6brmZd3arKCa2ITzjzK/@erZOSWW0c4ZRyKYlf8TVj5TN/ZCXtalKRNE9gvMvzsxif9DWnAE/fpnXNEcheW9EroIC9FspZcBp@Py6Bqw14USF4NJbTh14ROFlgTJ8JRXZNkV9VZAnkMxQfXFr8o7DB0ePyaOpFrsGdRenRRvJbAosAj3Vkp0amw4/jLm5OfJlFaaiEqVrJDbhWKZQWwqr0ATcxQRqB6eSAl7zIgINwjW4doDphwnS4RUPo3C2EWEOaJHTC3YuFr89zoLRPVNA7SbHSYm5Vw2hbjRZKPOqwOSl2wg2ruv0H/IPW/QA "R – Try It Online")
---
**Unrolled code and explanation :**
```
f=
function(v){ # v vector of tunnel indexes (1-based) or values <= 0
a = v[v>0] # get the tunnel positions
b = sort(a) # sort the tunnel positions ascending
c1 = v[a]==b # get the values of 'v' at positions 'a'
# and check if they're equal to the sorted positions 'b'
# (element-wise, returns a vector of TRUE/FALSE)
c2 = a != b # check if positions 'a' are different from sorted positions 'b'
# (to exclude tunnels pointing to themselves, element-wise,
# returns a vector of TRUE/FALSE)
all(c1 & c2) # if all logical conditions 'c1' and 'c2' are TRUE then
# returns TRUE otherwise FALSE
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~66~~ ~~61~~ 60 bytes
```
lambda l:all(len(l)>v!=i==l[v]for i,v in enumerate(l)if-1<v)
```
[Try it online!](https://tio.run/##lZDBCoMwDIbve4qMXRRasDp2GHPHPcFuroeOtViIVVwVfPrOKW47qNNAINB@/F9SNDbNTehUfHMosvtDAB4FoofSeOif622s4xiTmqu8BE1q0AakqTJZCivbH1pRdqp9V5TaWFBeQhmBoQ/fMRpG7sMO4FpWNm02H6p9CjjM1CgVEGD/qYvAp/yh9gTCFuyFgs5pQRbrqBnJ0SzaY3RSc5Sa3WnSsLvvOyziK6j@BtHKvRhfYthT7gU "Python 2 – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~19~~ 24 bytes
```
×/<∘≢⍨×≠∘⍳∘≢⍨×0∘>∨⊢=⊢⍳⍳⍨
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/w9P17d51DHjUeeiR70rDk9/1LkAxOvdjCRmAGTbPepY8ahrkS0QgyRBaMX/NKAJj3r7IIZ1NR9ab/yobSKQFxzkDCRDPDyD/z/qXVX9qHerraGVekhRaar6o@4WdbfEnOJU9dpDK9IOrdDQMH7Uu@XQekNNHTMdDSMY21gHxtQwVDDQ1DBQALJMFIwUDBWAggoGClApI5AkSMQIIgJiHloP4hhrPupdA9KsYKypoQOU0gGqfNSzF@h0U00A "APL (Dyalog Unicode) – Try It Online")
Prefix anonymous lambda, returning 1 for truthy and 0 for falsy. The TIO link contains a "prettified" version of the output for the test cases.
Shoutouts to @ngn and @Adám for saving approximately a bazillion bytes.
An extra shoutout to @ngn for the help with fixing the answer for some test cases, and with making it a train.
The updated answer uses `⎕IO←0`, setting the **I**ndex **O**rigin to 0.
### How:
```
×/<∘≢⍨×≠∘⍳∘≢⍨×0∘>∨⊢=⊢⍳⍳⍨ ⍝ Prefix lambda, argument ⍵ → 4 2 1 ¯1 0 ¯1.
⍳⍨ ⍝ Index of (⍳) ⍵ in ⍵. ⍵⍳⍵ → 0 1 2 3 4 3
⊢⍳ ⍝ Index of that in ⍵ (returns the vector length if not found).
⍝ ⍵⍳⍵⍳⍵ → 4 2 1 6 0 6
⊢= ⍝ Compare that with ⍵. ⍵=⍵⍳⍵⍳⍵ → 1 1 1 0 1 0
⍝ This checks if positive indices tunnel back and forth correctly.
∨ ⍝ Logical OR with
0∘> ⍝ 0>⍵ → 0 0 0 1 0 1∨1 1 1 0 1 0 → 1 1 1 1 1 1
⍝ Removes the zeroes generated by negative indices
× ⍝ Multiply that vector with
⍨ ⍝ (using ⍵ as both arguments)
⍳∘≢ ⍝ Generate the range [0..length(⍵)-1]
≠∘ ⍝ And do ⍵≠range; this checks if any
⍝ element in ⍵ is tunneling to itself.
⍝ ⍵≠⍳≢⍵ → 4 2 1 ¯1 0 ¯1≠0 1 2 3 4 5 → 1 1 1 1 1 1
× ⍝ Multiply that vector with
⍨ ⍝ (using ⍵ as both arguments)
<∘≢ ⍝ ⍵ < length(⍵) → 4 2 1 ¯1 0 ¯1 < 6 → 1 1 1 1 1 1
⍝ This checks if any index is out of bounds
×/ ⍝ Finally, multiply and reduce.
⍝ ×/1 1 1 1 1 1 → 1 (truthy)
```
[Answer]
# JavaScript (ES6), 35 bytes
*Saved 1 byte thanks to @Shaggy*
```
a=>a.every((v,i)=>v<0|v!=i&a[v]==i)
```
[Try it online!](https://tio.run/##rZE9b4MwEIb3/orr0oIECYQqU8nYpUOXbhGDC5fgyvEhbBwh9b9TU5K2KR9hqCVLlof3ee@5d2aYSkteaF9Shs0ubli8YQs0WNaOYzzuxhvzGHyY25jfsa1J4pi7TUpSkcCFoL2zc7Z@6MH5rn@e0fmZuC4sl/BaVjqvwSlIcc1JQgQFcakVaILvzzUwmYHhKYItoZh784dmI4MEJs4ILRiihddogQfhDNoTEwp/0ZTFtclhB22ZOseDQmFQ9SAPHqwsp/MVfCkbH2nAx2pSyWVDSZDyMq0EK0FXUqJQwISgI2a9Xn6X7Y8auIzu4uDIdU6VBpT9xEmV/eXZsqeOnvXH9L2Cl@fBmn7bM0r@L7TbRDRX62n2PaGCN6zJ7l7wA9f9ZYfJLAXXg5tP "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // a[] = input array
a.every((v, i) => // for each value v at position i in a[]:
v < 0 | // force the test to succeed if v is negative (non-tunnel position)
v != i & // make sure that this cell is not pointing to itself
a[v] == i // check the other end of the tunnel
) // end of every()
```
[Answer]
# [Python 2](https://docs.python.org/2/), 65 bytes
```
lambda l:all(l[v:]>[]and v!=i==l[v]or v<0for i,v in enumerate(l))
```
[Try it online!](https://tio.run/##TY5BCsMgEEX3PcXvLgEDNildhNqLWBeWKBUmJoRU6OmtJpV2If/5/Mw4v9fn5NtoxT2SHh@DBvWaqCIZenWTSvsB4SicEMmoaUG4cpvCsQDnYfxrNIteTUV1HfMDZS2bE0M5lx92BRWDTMBzcobtfmZoE@4V/tdqv8Vm590X0WTTlXlpxYaqPwDz4vwKYrDpd/ED "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
ị=JanJ$>L<$o<1$Ạ
```
[Try it online!](https://tio.run/##y0rNyan8///h7m5br8Q8LxU7HxuVfBtDlYe7Fvz//z/aSEfBUEfBJBYA "Jelly – Try It Online")
1-indexed.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 36 bytes
```
{!.grep:{2-set $++,$^v,.[$v]xx$v+1}}
```
[Try it online!](https://tio.run/##jZJPS8NAEMXv/RQjBm3opuSP9KB49eLBi7dSZZtO24XNbtidpA2lnz1uTGsVo8nCwjCwv3nvzeZo5KzOKrhZw2N9uJpuDOb3hziwSOBNJsx7K9l07pWL/d4rJ9HxWFtewXrsvfuw1mY0DyIG5zu7lMm5XDCAa3g1BW0rGOfaChJaQQK5FooskIav5gy4WkEpUoQSjeX@aO4YYYP473Tgwy589BsfMoj68U9cWvyGt47foKJ2SjOEtphZlCVaR71jEDtwG0F4TqFb9KfFuM/lRYPSkAqTFpIboEIplBa4lHqHK7/dRtw9sIPVvoedoK0uCFA1iL44fibu5JxUMJcBp1sLL88nIUGjJPmb109p40sGRnOys9FoYYmVdhuSIhPUrCQaYGsYKRjwJS8k3JPhQGjJHz3UHw "Perl 6 – Try It Online")
The basic idea is to check whether the set `{ i, a[i], a[a[i]] }` contains exactly two distinct elements for each index `i` with `a[i] >= 0`. If an element points to itself, the set contains only a single distinct element. If the other end doesn't point back to `i`, the set contains three distinct elements. If `a[i] < 0`, the `xx` factor is zero or negative, so the set is `{ i, a[i] }`, also with two distinct elements.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~19~~ 18 Bytes
-1 Byte thanks to [Luis](https://codegolf.stackexchange.com/users/36398/luis-mendo)
```
n:G=GGG0>f))7M-|hs
```
[Try it online!](https://tio.run/##y00syfn/P8/K3dbd3d3ALi3CQ1PTQ7cmo/j//2hdQx0FGDZHME1gzFgA), for the first one only, because I don't know how to do all of them!
Gives `0` if truthy, a non-zero integer if falsey, eg. for test case 6 gives `4`.
Please remember that like MATLAB, MATL is 1-indexed so 1 must be added to the test cases!
Never golfed in an Esolang before, so advice greatly received!
Explained:
```
n:G=GGG0>f))7M-|hs
Implicit - input array
n Number of values in array
: Make array 1:n
G Push input
= Equality
n:G= Makes non-zero array if any of the tunnels lead to themselves
GGG Push input 3x
0 Push literal 0
> Greater than
G0> Makes array of ones where input > 0
f Find - returns indeces of non-zero values
Implicit - copy this matrix to clipboard
) Indeces - returns array of positive integers in order from input
) Ditto - Note, implicit non-zero any above maximum
7M Paste from clipboard
- Subtract
GGG0>f))7M- Makes array of zeros if only two-ended tunnels evident
| Absolute value (otherwise eg. [3,4,2,1] -> '0')
h Horizontal concat (ie. joins check for self tunnels and wrong tunnels)
s Sum; = 0 if truthy, integer otherwise
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~16~~ ~~15~~ 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
εèNQyNÊ*y0‹~}P
```
-1 byte thanks to *@Dorian*.
[Try it online](https://tio.run/##yy9OTMpM/f//3NbDK/wCK/0Od2lVGjxq2FlXG/D/f7SuoQ4EmUFpYwgdCwA) or [verify all test cases](https://tio.run/##yy9OTMpM/W9o4OZ5eEKovZLCo7ZJCkr2/89tjSg@vMIvsNLvcJdWpcGjhp11tQH/df5H6xrqQJAZlDaG0LFc0YY6BkDSQAfENtEx0gFLG8DkjMCyuiAGWATC0QXyjCF6dcB07H9d3bx83ZzEqkoA).
**Explanation:**
```
ε # Map each value `y` of the (implicit) input-list to:
è # If the current value indexed into the (implicit) input-list
NQ # is equal to the index
* # And
yNÊ # If the current value is not equal to the current index
~ # Or if:
y0‹ # The current value is negative
}P # After the map: check if everything is truthy
# (after which the result is output implicitly)
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-e`](https://codegolf.meta.stackexchange.com/a/14339/), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
§JªU¦V«aWgU
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWU&code=p0qqVaZWq2FXZ1U&input=Wy0xLC0xLC0xLDYsLTEsLTEsMywtMSwtMV0)
---
## Original (w/o flag), ~~14~~ 13 bytes
```
eȧJªX¦Y«aUgX
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ZcinSqpYplmrYVVnWA&input=Wy0xLC0xLC0xLDYsLTEsLTEsMywtMSwtMV0) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ZcinSqpYplmrYVVnWA&input=WwpbLTEsIC0xLCAtMSwgNiwgLTEsIC0xLCAzLCAtMSwgLTFdClsxLCAwXQpbMCwgMV0KWzQsIDIsIDEsIC0xLCAwLCAtMV0KWzEsIDIsIDBdClstMSwgMiwgLTFdCltdClstMSwgLTIsIC0zXQpbMSwgMCwgM10KWzFdCl0tbVI)
[Answer]
## Python, 112 97 96 86 bytes
```
f=lambda l:sum(i==l[i]or len(l)<=l[i]or 0<=l[i]and i!=l[l[i]]for i in range(len(l)))<1
```
[Try it Online!](https://tio.run/##bY5BCsMgEEX3PcV0p6BgYumixJMEF5bEVjCTYNJFT28NYkuSLoT/n2@Gmd7Lc0QZo1XeDPfOgL/Nr4E4pXzr9BjA90g8bUoVORnswJ1TXIu26cOBQwgGHz3JI5Q2VZyCw4VY0vKKQXnXX5QlakpPXzkRsQGCwda4MKgTy9Pi34J6v4NnuDMPCl8deTgnnbplqcUP)
Returns `True` or `False`.
-10 bytes thanks to @Rod and @TFeld.
[Answer]
# [Groovy](http://groovy-lang.org/), 52 bytes
```
{o=!(i=0);it.each{e->o&=e<0||(it[e]==i&&i-e);i++};o}
```
[Try it online!](https://tio.run/##fZFPS8NAEMXv@RRjKfm/ZU3FQ@q0J68qeJKQQ5pO60LphuxWlDSfPW4TakDdHhZm9u178xt2V0v58dVpUrosFCnM0tz56WbVUfsZu43hcu7Hcn4p81jXRwp@24zGLRKPwbi2xV791e5iSIw8hPMr@UmPMETZAJKe4f9BbNCZlcQS2y99Ns6vLG7YbLHWeSPpGrtG4o0vkAcLoWdUlO8NsaV0kR746eQLnVGOKFxXMDJPoqhdyHb8xt4BjYglsKUDUNXioPcHmEwFIMK0WfsiaOGlUIo2K9P75wtEufLeHl@91AvDp@cwBAb0WVGpaZOCBxHIoJ04rdN9Aw "Groovy – Try It Online")
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), 33 bytes
```
{*/(x<0)|(x<#x)&(~x=!#x)&x=x?x?x}
```
[Try it online!](https://tio.run/##PYzdCsIwDIXvfYoMRVqx2B/xonH4IGMwbyoymTB2kTG3V6/tWkZCcki@c1rRvTrvnZ1OF0Z3yX9h7okf2UJlEQWV9Ag1@8FOh2pceuuAsPm2yBr3fH@QcMSe1/NuqISC1Le8Tdqo6vBVIJOQoFBGcQUNKyc3SAdP/GeHDp4VFVGL7CtyUAwPV7Plg0nAOYL@Dw "K (ngn/k) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 48 bytes
```
(all=<< \u(x,y)->y<0||x/=y&&elem(y,x)u).zip[0..]
```
[Verify all testcases!](https://tio.run/##bZDBCoJAEIbvPsWAIAq7tmrURQOJ8FLhpZNJeFBaWmVJBS17dts0MaWFhZl//m9mmGuU32LG2ieWYe8evZPr7WDr@yDjl5SAA@dWjRhzbBvOpVqhWsOb2iZNUy2cWlFiFqdqjSqt1PQH5QHR9bClGS@LXLCBBN8XYAPB8FdjaA1hiEavEMhvThBM6ksEppB6lMxps@s6Z4yOmbTFvTal5wb8cVjz7cSIifSnjmAddmIoSWlEM3GONOKHC6j8TrMCdEg06C/VvgE "Haskell – Try It Online")
## Explanation
Let's first ungolf the code a bit. As `f =<< g` is the same as `\x -> f (g x) x`, the code is equivalent to
```
(\u->all(\(x,y)->y<0||x/=y&&elem(y,x)u)u).zip[0..]
```
which is a bit clearer.
```
(\u -> -- given u, return
all (\(x, y) -> -- whether for all elements (x, y) of u
y < 0 || -- either y < 0, or
x /= y && elem (y, x) u -- (x /= y) and ((y, x) is in u)
)
u
) . zip [0..] -- given the array a (implicitly via point-free style),
-- return the array augmented with indices (it's the u above)
```
This solution is based on a simple observation: let `a` be the input array, and `u` the list of pairs `(i, a[i])` where `i` is an index. Then `a` is a valid array if and only if for every `(x, y)` in `u` with `y >= 0`, the pair `(y, x)` belongs to `u` as well.
[Answer]
# [Java (JDK)](http://jdk.java.net/), 89 bytes
```
a->{int l=a.length,i=l;for(;i-->0;)i=a[i]<1||a[i]<l&&a[i]!=i&a[a[i]]==i?i:-2;return-2<i;}
```
[Try it online!](https://tio.run/##bVHBbsIwDL3zFR4SqJ2SqJRpB0qY9gGTJnFEPWSlZWYlRYmLhKDf3qUtdIB2sJ6f7dh@8VYdFN@uf2rc7QtDsHVclIS5yEqdEBZaPEeDffmVYwJJrqyFD4UaTgOAS9SSIgeHAtewczlvSQb1ZhWDMhvrt6UAnyZdY6IonaOmVbyATNaKL06OQS6VyFO9oW@GMo@ywngRcr4IIh@lWmE8n5zPLebjcYNPEh02XiwlvuGMh5FJqTSah3OMqjpqZ7aT3B6UWrIgL5sAnIBPWG@vf@706kLF@loXCG55wOAu/8IgZHDpEPzzOnxowLvYfd1DnjcF08c13IZ3oSupOr3Nx7WaW8WzTrffy14eLaU7UZQk9u5ClHnDkZ3ByI70kN1c/t0YdbSCiu6QXtPGZ5CJxumY3w2sBo1V9S8 "Java (JDK) – Try It Online")
## Credits
* -3 bytes thanks to [AlexRacer](https://codegolf.stackexchange.com/users/60517/alexracer)
* -6 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes
```
¬Φθ∨⁼ικ¬∨‹ι⁰∧‹ιLθ⁼κ§θι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMvv0TDLTOnJLVIo1BHwb9Iw7WwNDGnWCNTRyFbU0cBJA0U9EktBgsZAIUc81LgfJ/UvPSSDI1CTaA4VGM2UEWJZ15KagXIwExNGLD@/z86WtdQRwGGzRBMYxgzNva/blkOAA "Charcoal – Try It Online") Link is to verbose version of code. Outputs `-` for truthy and nothing for falsy. Note: Inputting an empty array seems to crash Charcoal, but for now you can enter a space instead, which is near enough. Explanation:
```
θ Input array
Φ Filter elements
ι Current value
⁼ Equals
κ Current index
∨ Or
¬ Not
ι Current value
‹ ⁰ Is less than zero
∨ Or
ι Current value
‹ Is less than
L Length of
θ Input array
∧ And
κ Current index
⁼ Equals
§θι Indexed value
¬ Logical Not (i.e. is result empty)
Implicitly print
```
[Answer]
# [Pascal (FPC)](https://www.freepascal.org/), ~~165~~ ~~155~~ 153 bytes
```
function f(a:array of int32):byte;var i:int32;begin f:=1;for i:=0to length(a)-1do if a[i]>-1then if(a[i]=i)or(a[i]>length(a))or(a[a[i]]<>i)then f:=0;end;
```
[Try it online!](https://tio.run/##dZDdasQgEIXv@xRzqTAWTbZbiE1eZMmFm9XdgaCLtS379KkxbEtZKwgz53xz/Lma98nMwl2nZXEffkoUPDhmOhOjuUFwQD61De@Ot2T1p4lAXVH00Z4po12vtAur3MsUYLb@nC7McKFOAciBOdA4CJUu1ueWrW1PPMRSDT/4pqza@DYQL3jOltr6k17KWU8AX5GSnT1z7CAUwn3vf8v2Xo6c678TWZaPqkSosDuEJhtbmPw3r6lGis2pzdRhsdJt/cb5SRWjIsmyHo0WG1Qo8RX3@IK7AuRPfV6@AQ "Pascal (FPC) – Try It Online")
Made function this time because the input is array. Returns `1` for truthy and `0` for falsey.
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 60 bytes
```
import StdEnv
@l=and[v<0||l%(v,v)==[i]&&v<>i\\v<-l&i<-[0..]]
```
[Try it online!](https://tio.run/##ZZBLS8QwFIXX9ldcEEsLyVA74qqRWagguBDGXZpF6EMCaTK0SUCY327MNPOwziJw8nHPuZfTyI4rP@jWyg4GLpQXw06PBramfVEu2UjCVUtdVez38i5zyOWEUMHS1FVPoq5dhWUqKkyL1YoxvzV8NMktmG4yExCgGcX3CE7v8SLXJ8kQfI62y1Fyk9FAigUoEBwmXrmcjuQBQRlgtBdXCeUcfbQtgsuY/ScKR4r/bVgY5yMPQ@urQ8OmpfGSw0IHvVWNEVqFGjYJgVBjqOMMhdpZA4SAtiaoHOoashmiM6pwLJL5n6aX/Gvy@O3dP38rPogmfj4kN70eh18 "Clean – Try It Online")
# [Clean](https://github.com/Ourous/curated-clean-linux), 142 bytes
Vastly over-complicated monster version:
```
import StdEnv,Data.List,Data.Maybe
$l=and[?i(mapMaybe((!?)l)j)j\\i<-l&j<-map((!?)l)l|i>=0]with?a(Just(Just c))(Just b)=a==c&&b<>c;?_ _ _=False
```
[Try it online!](https://tio.run/##ZZFvS8MwEMZf209x4hgJJFI38Y3N@mYKygRhvmuLZFmnGWk62qsy8LNbs2Z/rBISnvxy99xxUSaXti3KZWNyKKS2rS42ZYUwx@Wd/WBTifJypmv06kluF3kwMELaZRJrUshNhwg5j6mha7pOUx1xM1xH3L3tsfnSExFmnxrfY0kemxq7AxSlXiyokEKo4XARTdRt/ApuiXtp6rydo6wwuADMa6xBQEISfsXgsG9OcnyQGYOXqskpC85I4kjYAyGDXUTn7sk1g5GDPj385zDqrPdpPeOR9/5lxT3lfyr0Ersmd0Hjf426Sv3Ek0/mZrBqrEJdWjeGQSDA/YEbxxFqu2kQhICyQacopCmQDrIjirgfZNZ@q5WRb3XLH2btdGtloZW/PBuJq7IqfgA "Clean – Try It Online")
Explained:
```
$ l // function $ of `l` is
= and [ // true when all elements are true
? // apply ? to
i // the element `i` of `l`
(mapMaybe // and the result of attempting to
((!?)l) // try gettting an element from `l`
j) // at the potentially invalid index `j`
j // and `j` itself, which may not exist
\\ i <- l // for every element `i` in `l`
& j <- map // and every potential `j` in
((!?)l) // `l` trying to be indexed by
l // every element in `l`
| i >= 0 // where `i` is greater than zero
]
with
? a (Just (Just c)) (Just b) // function ? when all the arguments exist
= a==c && b<>c // `a` equals `c` and not `b`
;
? _ _ _ = False // for all other arguments, ? is false
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 44 bytes
```
->a{a.all?{|x|x<0||(w=a[x])&&x!=w&&a[w]==x}}
```
[Try it online!](https://tio.run/##TY5BC8IwDIXv/op4KQrtqJt4svpDQg7xsNOEIUgz1v722q4WPYR8eTzy3uv9WNLokrnxyh1P030NEuRqQzh4xyh0VEr2zivF6Mk5iTEhmpOGNpcfDg1J7zCDLdtq2O6zhj5jtdg/V/81mspVb4IpytD@5YgNibonz6UqzICiYcxNKaYP "Ruby – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~17~~ 16 bytes
```
.A.e|>0b&nbkq@Qb
```
Try it online [here](https://pyth.herokuapp.com/?code=.A.e%7C%3E0b%26nbkq%40Qb&input=%5B4%2C%202%2C%201%2C%20-1%2C%200%2C%20-1%5D), or verify all the test cases at once [here](https://pyth.herokuapp.com/?code=%25%22%25s%20should%20be%20%25s%22%2CQ%21%21E%0A.A.e%7C%3E0b%26nbkq%40Qb&test_suite=1&test_suite_input=%5B-1%2C-1%2C-1%2C6%2C-1%2C-1%2C3%2C-1%2C-1%5D%0A1%0A%5B1%2C0%5D%0A1%0A%5B0%2C1%5D%0A0%0A%5B4%2C2%2C1%2C-1%2C0%2C-1%5D%0A1%0A%5B2%2C3%2C0%2C1%5D%0A1%0A%5B1%2C2%2C0%5D%0A0%0A%5B-1%2C2%2C-1%5D%0A0%0A%5B%5D%0A1%0A%5B-1%2C-2%2C-3%5D%0A1%0A%5B1%2C0%2C3%5D%0A0%0A%5B1%5D%0A0&debug=0&input_size=2).
```
.A.e|>0b&nbkq@QbkQ Implicit: Q=eval(input())
Trailing k, Q inferred
.e Q Map the input with b=element, k=index, using:
>0b 0>b
| OR (
nbk b != k
& AND
q@Qbk Q[b] == k)
.A Check if all elements are truthy
```
*Edit: realised that the trailing k was also unnecessary*
[Answer]
# [Perl 5](https://www.perl.org/), 54 bytes
```
{$i=-1;!grep$_>=0*$i++&&($_==$i||$i!=($_[$_]//-1)),@_}
```
[Try it online!](https://tio.run/##nZFRb9owEMff8ymukVsS6iwxbDyMpQVp6x4mtS@8hShywYDXYGexQ4eAz84cknSVQDDNkqW7s@93/7vLWJ5@2qviGWb7DeKhR/pX85xlKLkLgzbit7c3Nw5KwhDx7Rbxq9A4EUpi3/eI6@JBstvPZO4sabbxx5HzoX3vjuOxajuj7YPr9yPUAfYLWqMWVlnKtW@esLk@RiTe1SHh45@SC9vGX74OR8M7d2OBOcu1gxgeUBdCGKCkXwcBzU1g5piHKpTlXOgZ2NdeTxn32@@MTTSbwrVHSv@71I05zHO6hgEdCxsfUgEcQzMCEbu3n17KgP3ZfjQZ8sV2sSmP5n1rZyVJKSxJrMgjGJrb@2t2GzMGGOWFXqzByaTimksBXchMe1qBlvAW7AEVU1jxCYMVyxV1rcgAghjOniN2cIpNjtkBBnKB/UBTxd6xlYGXHFKVKCvoBVsqlq6YMsiPGDqGWnUe1M2fkmtFncOEzmpovpID9ewcGqFCwoTnkyKlOehCCJYqoGkqX9nUrTbVOanqCFQlwyvXC1loYKLMvzCt99swQur62IyI6paCpx@1BK/U0I3/F1GNtvsv46i7mEum4JmtpVldypdcl7sil7u5jNn/AQ "Perl 5 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~95~~ 94 bytes
* Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat).
```
i(_,o,O,Q,I)int*_;{for(I=O=0;O<o;O++)I|=_[O]>=0&&_[O]>=o|(Q=_[O[_]])<0|Q>=o|O[_]==O|Q!=O;Q=I;}
```
[Try it online!](https://tio.run/##lZFva4MwEMZfr58iE1qSetJoS8eapkPYBsIgk/adExn9M5SuDrd3ms9uE6XrNqxdA8En5/1yz@WW1ttyWZYxjiAFAT54JN599SOWb9IMe1xwysQ0ZcI0iVfwKBDhjNNerxZpgX0dC6IwJFNa@DqkT5yLwr/mgvncY7JcYBe2sIYEsup6l@UZj3WQsI9MRTbY6H5OkAEZ5@s749H1nh7ujYnx7M7nShyzAqW1s0T5SqZbRr7xFSjcDRLTDI/pIbJmqLt62ambCZOd99d4h0neuVpgrDKCkOSWDeiwx0c5PEgJtzDo9wc2YT8x9Y@iliXBacIoIPs/GP2NjQA5iqw9Uf35i42bqjlVH6drShid6M1pa0/CsMmkVXOWfRmGziwJtMlkNR1dbtherWFu6lUu7c0@a9JuxOpqgG7aB6AxWe4B "C (gcc) – Try It Online")
[Answer]
# Mathematica, 42 bytes
```
#=={}||(a=0@@#)[[#]]=!=a&&a[[#]][[#]]===a&
```
Pure function. Takes a 1-indexed list of numbers as input and returns `True` or `False` as output. Just follows the tunnels, ensuring that `0` maps to `0`, no 1-cycles exist, and all cycles are 2-cycles. (I'm not entirely sure if this fails on any edge cases, but it gives the correct results for the examples.)
[Answer]
# This answer does not work. Here for illustration purposes only.
This answer passes all of the (currently) posted test cases. However, it fails (raises an error) on other valid input, such as `[1, 2]` or `[1, 0, 3, 7]`.
How could it pass `[1, 0, 3]` and fail `[1, 0, 3, 7]`? Well, it proceeds through the list, just like you'd expect. When it reads an element `x` of the list `a`, it first checks whether `x` is less than `len(a)`, and immediately returns `False`, if so. So it correctly returns `False` on `[1, 0, 3]`, because `3` is not less than `len(a)`.
But assuming that `x` passes that check, the code will then go on to do some other checks, and at a certain point it happens to evaluate `a[a[x]]`. We've already guaranteed that evaluating `a[x]` will be OK...but not `a[a[x]]`, which resolves to `a[7]` when `x` is `3` in the `[1, 0, 3, 7]` example. At this point Python raises an `IndexError`, rather than returning `False`.
For completeness, here's the answer.
# [Python 2](https://docs.python.org/2/), 59 bytes
```
lambda a:all(x<len(a)>-1<a[x]!=x==a[a[x]]for x in a if-1<x)
```
[Try it online!](https://tio.run/##lZDRCoIwFIbve4oT3Thw4DS6CNdlT9Cd7eJEDoU1xQzm0y91WF2o6WDww@Hj/84pmzordGglv1qFj9sdAY@olGdilWoPyYmyGBMjttxwjkkXhSwqMJBrQMhlOzfEllWua5BeQpkPwz98YzREQWAHcKleddZsPlQ7CgTMvFEq8IH9p86onukPtfchbEEnFPROC7pYT81IjnZRh9FJzVFqdqdJw/6@XVkkVlDuBtHKvZhYYugo@wY "Python 2 – Try It Online")
I wanted to do `x<len(a)and-1<a[x]...`, but of course `len(a)` is always `>-1`, so the above is equivalent. This check is a total of 5 chained relations (`<`, `>`, `<`, `!=`, and `==`), plus a separate check `-1<x` in the `if` condition.
Python (conveniently) short-circuits chained relations like this, so for example if `x>=len(a)` then the check returns `False` before it gets to `a[x]` (which would otherwise raise an `IndexError`).
]
|
[Question]
[
Now that we know how to properly [square](https://codegolf.stackexchange.com/questions/136564/square-a-number-my-way) and [triangle](https://codegolf.stackexchange.com/questions/137632/triangle-a-number) a number, we are going to learn how to parallelogram one. To parallelogram a number, we first arrange it as a parallelogram by stacking it on top of itself a number of times equal to the number of digits it has, and adding spaces to make it a parallelogram. So `123` would form:
```
123
123
123
```
Now we take each horizontal and vertical number and add them, `123+123+123+1+12+123+23+3`, which equals `531`, which is the parallelogram of `123`.
## Your Task:
Write a program or function that, when given a number as input, returns the parallelogram of the number.
## Input:
A non-negative integer, or a non-negative integer represented by a string.
## Output:
The parallelogram of the integer.
## Test Cases:
```
1234567 -> 10288049
123 -> 531
101 -> 417
12 -> 39
```
## Scoring:
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest score in bytes wins!
[Answer]
# [MATL](https://github.com/lmendo/MATL), 12 bytes
```
tnEXyPY+c!Us
```
Input is a string. [**Try it online!**](https://tio.run/##y00syfn/vyTPNaIyIFI7WTG0@P9/dUMjYxNTM3N1AA "MATL – Try It Online")
### Explanation
Consider input `'123'` as an example.
The code duplicates the input (`t`) and builds an identity matrix (`Xy`) of size twice the input length (`nE`):
```
1 0 0 0 0 0
0 1 0 0 0 0
0 0 1 0 0 0
0 0 0 1 0 0
0 0 0 0 1 0
0 0 0 0 0 1
```
then flips it upside down (`P`):
```
0 0 0 0 0 1
0 0 0 0 1 0
0 0 0 1 0 0
0 0 1 0 0 0
0 1 0 0 0 0
1 0 0 0 0 0
```
The input string, interpreted as ASCII codes of the digits, is equivalent to the numeric row vector
```
49 50 51
```
Full-size two-dimensional convolution (`Y+`) of the above vector and matrix gives
```
0 0 0 0 0 49 50 51
0 0 0 0 49 50 51 0
0 0 0 49 50 51 0 0
0 0 49 50 51 0 0 0
0 49 50 51 0 0 0 0
49 50 51 0 0 0 0 0
```
Interpreting those numbers back as ASCII codes (`c`) gives the following char matrix, with char 0 represented as space:
```
123
123
123
123
123
123
```
Transposition (`!`) transforms this into
```
1
12
123
123
123
123
23
3
```
Interpreting each row as a number (`U`) gives the numeric column vector
```
1
12
123
123
123
123
23
3
```
and summing it (`s`) gives the final result, `531`.
[Answer]
# [Retina](https://github.com/m-ender/retina), 22 bytes
```
.
$`;$&$';$_;
\d+
$*
1
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX49LJcFaRU1F3Vol3porJkWbS0WLy/D/f0MjYy5DA0MuQyMA "Retina – Try It Online") Link includes test cases. Explanation: The first stage splits the input number at each digit and includes all the exclusive prefixes and inclusive suffixes, giving the vertical numbers, plus also the original input number repeated for each digit, giving the horizontal numbers. The remaining stages then simply sum the resulting numbers.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~12 11~~ 8 [bytes](https://github.com/Adriandmen/05AB1E/blob/master/docs/code-page.md)
I~~'m sure~~ knew this ~~can~~ could be golfed further - tips welcome!
-1 byte thanks to Erik the Outgolfer (avoid wraps but using a concatenation)
and then...
-3 more bytes thanks to Adnan (avoid multiplication by length-1 by vectorising addition and subtracting the input off at the end)
```
.s¹η++Oα
```
**[Try it online!](https://tio.run/##MzBNTDJM/f9fr/jQznPbtbX9z238/9/QyBgA "05AB1E – Try It Online")**
### How?
```
.s¹η++Oα - implicit input, say i e.g. 123
.s - suffixes [3,23,123]
¬π - push i 123
η - prefixes [1,12,123]
+ - addition of top two [4,35,246]
+ - addition (vectorises) [127,158,369]
O - sum 654
α - absolute difference abs(123-654) 531
- implicit print
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~13~~ 12 bytes
```
ṁit§+SRL§+ḣṫ
```
[Try it online!](https://tio.run/##yygtzv7//@HOxsySQ8u1g4N8gOTDHYsf7lz9//9/JUMjYxNTM3MlAA)
### Explanation
```
-- implicit input, say "123"
§+ -- concatenate the results of the following two functions
SR -- ¬πrepeat the input n times, where n is the result of the next function
L -- length ["123","123"]
§+ -- ²concatenate the results of the following two functions
·∏£ -- prefixes ["","1","12","123"]
·π´ -- suffixes ["123","23","3",""]
-- inner concatenation ["","1","13","123","123","23","3",""]
-- outer concatenation ["123","123","","1","13","123","123","23","3",""]
t -- all but the first element ["123","","1","13","123","123","23","3",""]
ṁ -- map then sum
i -- convert to integer (where "" converts to 0)
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~90~~ ~~78~~ ~~76~~ ~~71~~ ~~64~~ ~~63~~ ~~59~~ 57 bytes
```
g x=sum[x+div x(10^a)+mod x(10^a)|(a,_)<-zip[1..]$show x]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P12hwra4NDe6Qjsls0yhQsPQIC5RUzs3PwXGrtFI1InXtNGtyiyINtTTi1UpzsgvV6iI/Z@bmJlnW1CUmVeikq5gaGT8HwA "Haskell – Try It Online")
[Answer]
# [Neim](https://github.com/okx-code/Neim), 7 bytes
```
ùê±Sùêóùîªùîªùê¨ùï§
```
Beware. Contains snakes: `Sùê¨ùï§`
[Try it online!](https://tio.run/##y0vNzP3//8PcCRuDgcT0D3On7IbgCWs@zJ265P9/QyNjAA "Neim – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 85 70 Bytes
```
f=lambda n,r=1,i=int:n[r:]and i(n[r:])+i(n[:r])+f(n,r+1)+i(n)or i(n)*2
```
For input 12345:
Sums up slices of input 1+2345+12345, 12+345+12345, 123+45+12345, 1234+5+12345, by using string indexing to index (r) = 1,2,3,4 before casting to integer, and adds to 12345\*2
Special Thanks to:
-14 Bytes @Jonathan Allen
-1 Byte @ovs
[Try it online!](https://tio.run/##JY3NCsIwEITP@hRLTlkbxbT@QCC@iHiI1GCg3Za4Fyl99pjE03yzzM7MX35P1KXk7eDGZ@@AVLRaBRuIDd2jeTjqIciK2BQwMYOXOdjoesEplgTu2uQz8uvDEAik0G13Ol@uQkHBKkf9dwLNdjPHvCLFssL@BssqDvl9dCxLgwJfFRHTDw)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~15~~ 11 bytes
*-4 bytes thanks to @Shaggy.*
```
¬£iYç
cUz)x
```
Takes input as strings.
[Try it online!](https://codepen.io/justinm53/full/NvKjZr?code=rKNpWecKY1V6KXg=&inputs=IjEyMyI=,IjEwMSI=,IjEyIg==,IjEyMzQ1Njci,IjEwMjAzMyI=)
## Explanation
```
£
```
Split the input array to digits (`¬`) and map by (`£`) the following function, where Y is the index.
`["1", "2", "3"]`
```
iYç
```
The input value (implicit) with `Y` spaces (`ç`) inserted (`i`) at the beginning. This is assigned to `U`.
`["123", " 123", " 123"]`
```
cUz1)x
```
Concatenate that with itself rotated 90° right (`1` time). Then sum (`x`).
`["123", " 123", " 123", " 1", " 12", "123", "23 ", "1 "]` -> `531`.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~31~~ 18 bytes
-13 bytes thanks to [@ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions)
This approach doesn't work well using Japt. [Justin's solution](https://codegolf.stackexchange.com/a/138194/61613) is much better.
```
[U*Ål U¬£tYÃUå+]xx
```
## Explanation:
```
[U*Ål U¬£tYÃUå+]xx
[ ] // Create a new array
U*√Öl // Push: Input * Input.slice(1).length()
// Push:
U¬ // Input, split into chars
£tY // Map; At each char: .substr(Index)
Uå+ // Push: Cumulative reduce Input; with addition
xx // Sum all the items, twice
```
[Try it online!](https://tio.run/##y0osKPn/PzpU63BrjkLooTWHFpdEHm4OPbxUO7ai4v9/JUMjYxNTM3MlAA "Japt – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~61~~ 55+1 = 56 bytes
Uses the `-n` flag. Input from STDIN.
```
p (1..~/$/).sum{|i|[$_[i,~/$/],$_[0,i],$_].sum &:to_i}
```
[Try it online!](https://tio.run/##KypNqvz/v0BBw1BPr05fRV9Tr7g0t7omsyZaJT46UwckFKsDZBroZILoWJC0gppVSX58Zu3//4ZGXIYGhlyGRsZA2sjA2BjENDE1M/@XX1CSmZ9X/F83DwA "Ruby – Try It Online")
[Answer]
# JavaScript, ~~77~~ 74 bytes
*Saved 3 bytes thanks to [Value Ink](https://codegolf.stackexchange.com/users/52194/value-ink)*
```
f=a=>[...a+a].map((_,b)=>a-=-z.substr((b-=n)>0?b:0,b+n),a*=n=(z=a).length)|a
console.log(f('123'));
console.log(f('101'));
console.log(f('12'));
console.log(f('1234567'));
console.log(f('102033'));
```
[Answer]
# [Pyth](https://pyth.readthedocs.io), ~~20~~ 19 bytes
My current prefix approach (will hopefully golf further).
```
+*tlQsQssM+_M.__Q._
```
**[Test Suite](http://pyth.herokuapp.com/?code=%2B%2atlQsQssM%2B_M.__Q._&input=%22123%22&test_suite=1&test_suite_input=%2212%22%0A%22101%22%0A%22123%22%0A%221234567%22&debug=0)** or try **[an alternative approach with the same byte count](http://pyth.herokuapp.com/?code=%2B%2alQsQssM%2B_MP.__Q._&input=%22123%22&test_suite=1&test_suite_input=%2212%22%0A%22101%22%0A%22123%22%0A%221234567%22&debug=0).**
# Explanation
```
+*tlQsQssM+_M.__Q._ - Full program that reads a String from STDIN, with implicit input.
tlQ - Length of the input - 1.
sQ - The input converted to an integer.
* - Product of the above two elements. We will call this P.
._ - Prefixes of the input.
+ - Concatenated with:
_M.__Q - The prefixes of the reversed input, reversed.
sM - Convert each to an integer.
s - Sum.
+ - Addition of the product P and the sum above.
```
To understand the concept better, we shall take an example, say `"123"`.
* We first get the prefixes of the input. Those are `['1', '12', '123']`.
* Then, we get the prefixes of the reversed input, i.e: `['3', '32', '321']` and reverse each, hence we get `['3', '23', '123']`.
* We concatenate the two lists and convert each element to an integer, so we obtain `[3, 23, 123, 1, 12, 123]`.
* By summing the list, the result is `285`.
* The product `P` is the length of the input - 1 (i.e `2`) multiplied by the integer representation of it (`2 * 123 = 246`).
* In the end, we sum the two results: `285 + 246`, hence we obtain `531`, which is the correct result.
---
# [Pyth](https://pyth.readthedocs.io), 20 bytes
```
+*hlQsQsm+s>Qds<QdtU
```
**[Test Suite.](http://pyth.herokuapp.com/?code=%2B%2ahlQsQsm%2Bs%3EQds%3CQdtU&input=%22123%22&test_suite=1&test_suite_input=%221234567%22%0A%22123%22%0A%22101%22%0A%2212%22&debug=0)**
# Explanation
~~Explanation to come after further golfing.~~ I didn't succeed to golf this further for now (I have ideas though).
```
+*hlQsQsm+s>Qds<QdtUQ - Full program. Reads from STDIN. Q means input, and is implicit at the end.
hlQ - Length of the input + 1.
sQ - The input converted to an integer.
* - Multiply the above. We'll call the result P.
m tUQ - Map over [1...length of the input)
s>Qd - input[currentItem:] casted to an integer.
s<Qd - input[:currentItem] casted to an integer.
+ - Sum the above.
s - Sum the list.
+ - Add the sum of the list and P.
```
[Answer]
# q/kdb+, 34 bytes
**Solution:**
```
{sum"J"$((c#c),c-(!)2*c:(#)x)#\:x}
```
**Examples:**
```
q){sum"J"$((c#c),c-(!)2*c:(#)x)#\:x}"1234567"
10288049
q){sum"J"$((c#c),c-(!)2*c:(#)x)#\:x}"123"
531
q){sum"J"$((c#c),c-(!)2*c:(#)x)#\:x}"101"
417
q){sum"J"$((c#c),c-(!)2*c:(#)x)#\:x}"12"
39
```
**Explanation:**
```
{sum"J"$((c#c),c-til 2*c:count x)#\:x} / ungolfed
{ } / lambda function
x / implicit input
#\: / apply take (#) to each-left element with the right element
( ) / the left element
c:count x / count length and save in variable c
2* / multiply by 2 (e.g. 6)
til / range, so 0 1 2 3 4 5
c- / vector subtraction, so 3 2 1 0 -1 -2
( ) / do this together
c#c / 3 take 3, so 3 3 3
, / join, so 3 3 3 3 2 1 0 - 1 -2
"J"$ / cast this "123", "123", "123" .. "23" to longs
sum / sum them up and return result
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes
```
DµṚ;\U;;\ṖVS+Ḍ×¥L$
```
[Try it online!](https://tio.run/##ASwA0/9qZWxsef//RMK14bmaO1xVOztc4bmWVlMr4biMw5fCpUwk////MTIzNDU2Nw "Jelly – Try It Online")
[Answer]
# [Swift 3](https://www.swift.org), 213 bytes
```
func f(n:String){print((n.characters.count-1)*Int(n)!+(0..<n.characters.count).map{r in Int(n[n.index(n.startIndex,offsetBy:r)..<n.endIndex])!+Int(n[n.startIndex..<n.index(n.endIndex,offsetBy:-r)])!}.reduce(0,+))}
```
Cannot be tested online, because it is slow and times out. You can try it in Swift Playgrounds if you wish to test it.
## Sample run
**Input:**
```
f(n:"123")
f(n:"101")
f(n:"1234567")
```
**Output:**
```
531
417
10288049
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
LḶṚ⁶ẋ;€µ;ZVS
```
[Try it online!](https://tio.run/##y0rNyan8/9/n4Y5tD3fOetS47eGubutHTWsObbWOCgv@f7gdyP7/P1rd0MjYxNTMXF1HAcQEUwaGEJ56LAA "Jelly – Try It Online")
Takes input as a string. Creates the "parallelogram" as a matrix of characters, then evaluates each row and column to get the numbers to sum.
## Explanation
```
LḶṚ⁶ẋ;€µ;ZVS Input: string S
L Length
·∏∂ Lowered range - [0, 1, ..., len(S)-1]
·πö Reverse
⁶ The char ' ' (space)
ẋ Create that many characters of each in the range
;€ Prepend each to S
µ Begin a new monadic chain
; Concatenate with
Z Transpose
V Eval each string
S Sum
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~95~~ ~~84~~ 81 bytes (78 + `-lm` compiler flag)
Hi! This is my first submission, I hope I didn't break any rule.
```
g,o,l;f(char*s){l=atoi(s);while(s[o++])g+=l/pow(10,o)+atoi(s+o);return g+l*o;}
```
[Try it online!](https://tio.run/##JcpBCsIwEEDRq0hAmOmkaN2GnkRdhNikgWmmJJEuilc3Ftx9eN/1wbnWghbNxoObbe4K7jzaKhEKmm2OPEG5C9ETA418WWWD4aoF6f@QoMlTfed0CsSdmE9bbEyA@5pjqh7U@fVISh8x3BTi4V/n2YbSel5@ "C (gcc) – Try It Online")
## Ungolfed, without warnings:
```
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int g,o,l;
int f(char *s){
l = atoi(s);
while(s[o++]) {
g+=l/pow(10,o)+atoi(s+o);
}
return g+l*o;
}
int main(void){
printf("%d\n",f("1234567"));
return 0;
}
```
[Answer]
# Java 8, ~~147~~ ~~137~~ ~~126~~ ~~116~~ 114 bytes
```
n->{Integer l=(n+"").length(),r=n*l,i=0;for(;++i<l*2;)r+=l.valueOf((n+"").substring(i>l?i-l:0,i<l?i:l));return r;}
```
-13 bytes (137 → 126 and 116 → 114) thanks to *@OlivierGrégoire*.
**Explanation:**
[Try it here.](https://tio.run/##hVBNb8IwDL3vV1icEvqhwsYmkQXOO4wdOE47hJJ2Ycat8lFpQv3tXSg9D8m2ZPs96z2fVKeyptV0Ov4MJSrn4F0ZujwAGPLaVqrUsLu24wBKdq3ERZz0MWM4r7wpYQcEEgbKNpe3yKy1BZSMktmM56ip9t@Mp1bSHFMjC1E1lokkMa84XwpuE4l5pzDoj4pNJBcOzltDNTMb3JoM10Ua4VuzRs6F1T5YAiv6Qdx0tOGAUcckp2vMEc7RCtuPRz6/QPGbj/2v8/qcN8HnbVx5JEZ5yRbLx6fV8wsfvf2HuocoFndv8OmB/fAH)
```
n->{ // Method with integer as parameter and return-type
Integer l=(n+"").length(), // Length of the input integer
r=n*l, // Result-integer (starting at `n*l`)
i=0; // Index-integer (starting at 0)
for(;++i<l*2; // Loop from 0 through two times `l` (exclusive)
r+= // Add to the result-integer sum:
l.valueOf((n+"").substring(
// Substring of input, converted to integer:
i>l? // If `i` is larger than `l`:
i-l // Substring starting at `i-l`
: // Else:
0, // Substring starting at 0
i<l? // If `i` is smaller than `l`:
i // Substring ending at `i` (exclusive)
: // Else:
l) // Substring ending at `l` (exclusive)
); // End of loop
return r; // Return resulting sum
} // End of method
```
[Answer]
# [R](https://www.r-project.org/), ~~168~~ ~~162~~ 103 bytes
*-6 bytes by not using c()*
*-59 bytes thanks to @Giuseppe*
```
function(n){k=nchar(n)
a=k*strtoi(n)
for(i in 1:k)for(j in i:k)a=a+(i==1|j==k)*strtoi(substr(n,i,j))
a}
```
[Try it online!](https://tio.run/##Ncw7DoAgEEXR3lXYOaM2@CtMZjFoQhxIhgSxUteOUNjdU7wXkqFkLtkjewHB25Hshw45K02uPWOInouMD8A1S61WhwW2gDM06Q6YSD2WyOG/Oa8tF0jPvcX89iYDjRrGaV4aTB8 "R – Try It Online")
Takes input as a string.
I'm absolutely certain there are improvements to be made, primarily in leveraging any of R's strengths... but in a challenge that's basically string manip, I'm struggling to see how.
Edit: Much better now that I'm not iterating on a bad idea!
[Answer]
# [Perl 5](https://www.perl.org/), 53 + 1 (-n) = 54 bytes
```
$r=$_*(@n=/./g);for$i(@n){$r+=$_+($t=(chop).$t)}say$r
```
[Try it online!](https://tio.run/##K0gtyjH9/1@lyFYlXkvDIc9WX08/XdM6Lb9IJRPI1axWKdIGSmlrqJTYaiRn5Bdo6qmUaNYWJ1aqFP3/b2hk/C@/oCQzP6/4v66vqZ6BocF/3TwA "Perl 5 – Try It Online")
[Answer]
# Mathematica, 77 bytes
```
(s=IntegerDigits@#;t=Length@s;Tr[FromDigits/@Table[s~Take~i,{i,-t,t}]]+t#-#)&
```
]
|
[Question]
[
You know what a *mono*tonic sequence is: each element is bigger than its predecessor (monotonically rising) or as its successor (monotonically falling).
*Bi*tonic means you have two arms of the sequence, one monotonically rising, the other falling.
For example, `1,3,5,7,6,4,2` is bitonic (rising until 7, then falling until the end; `99,4,8,16` is as well (falling until 4, then rising until the end).
**The task is to test, whether a sequence is bitonic** (without being monotonic), with your code being as short as possible in your language of choice.
**Input**: A list of positive integer numbers without duplicates in a form that suits your language.
**Output**: [Truthy/falsy](https://codegolf.meta.stackexchange.com/a/19205/72726)
**Test data**:
```
True:
1,3,5,7,6,4,2
99,4,8,16
100000,10000,1000,100,10,1,11,111,1111,11111,111111
2,1,3,4,5,6
False:
1,2,3,4,5,6,7
7,6,5,4,3,2,1
1,4,7,6,2,3,5
99,88,66,77,55,44,33,22,11
1,9,2,8,3,7,4,6,5
```
[Answer]
# Haskell + [hgl](https://gitlab.com/wheatwizard/haskell-golfing-library), 10 bytes
```
eL2<gr<pac
```
*(Doesn't work on ato since ato is slightly out of date)*
## Explanation
* `pac` gets the contour of a list, i.e. the comparisons between consecutive elements
* `gr` group them into sections of equal elements.
* `eL2` check if there are exactly two groups
## Reflection
A couple of thoughts here
* I think there might be use in having a function which counts the number of groups. Although I don't think it would help this particular answer.
* `pWK` gets all partitions where each part satisfies a predicate. A version of this could be `ay eL2<pWK(lq<pac)`, which is much longer although there are a bunch of ways to improve this approach.
+ `lq<pac` determines if a list is monotonic, that is useful. We already have functions for the specific monotonicities, this would be a nice addtion.
+ Versions of a lot of the partitioning functions that are specific to partition into two parts would be useful, since that is the most basic non-trivial type of partition. A version of `pWK` which is specific to size 2 would change this from `ay eL2`, checking if there is something of size 2, to `√∏`, checking if the result is null.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
IṠITL’
```
A monadic Link that accepts a list of different integers and yields `0` (falsey) if it is bitonic or a non-zero integer (truthy) if not.
**[Try it online!](https://tio.run/##y0rNyan8/9/z4c4FniE@jxpm/v//P9pSx1THSMdCx9AoFgA "Jelly – Try It Online")** Or ee the [test-suite](https://tio.run/##PY87CsJAEIZ7T2Er/IWTZB@pBBsJiJVdSKNYRIJp0tils7dSUPAaqcWDJBdZZ7JJlp2feXwzO3s@FcXVuaRtPsl@29VP97u3zQNd/dqV1fyQV@UlP3b1mxPrKfjeVouNc2kaQCHMZkhDdgJxCOIaaEQ@EcfsWZDuq0s5oElF2EAgub15GZSkLYCMjXiwn4JgDGEkIc8pToRcIE9E/Q7CqWELa6GZN1CMMssw0wMeM2oZNtyofQuNP/MrZLPsDw "Jelly – Try It Online").
### How?
The count of direction changes must be exactly one, so count them and subtract one to give `0` iff the input is bitonic.
```
IṠITL’ - Link: list, A e.g. [5, 4, 3, 6, 7, 2]
I - forward differences [ -1,-1, 3, 1,-5]
·π† - signs [ -1,-1, 1, 1,-1]
I - forward differences [ 0, 2, 0,-2]
T - truthy indices [ 2, 4]
L - length 2
’ - decrement 1 (truthy: not bitonic)
```
[Answer]
# [R](https://www.r-project.org), 31 bytes
```
\(x,`?`=diff)sum(!!?sign(?x))-1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TZBNasMwEIX3OkXilQTPpeP4R4YmvogXCVQKBtcYywEXcpNu3ELP0XP0MqUzUVsqNG-kp29mQC-v0_rm9--X2af2o9ULjs1x_9h5b8LlSW-3TejOg24WY1KK1OeXcstDukkIOxSoUCJHpuqakwWViu5lgf5UhAMEkn2LKD9KKoN0y7kf1yP7PaNS0r_g245d4rf8NlGIQmZai5KxCgVDTDHGnIA1Q5axiku4RXI9hHkKY9_NOmnbITHXg-u1-W9DzP40jv2zPoW7bpjd2U1GhWi5BRtv4i-sa8zf)
A function taking a vector of integers and returning falsy for bitonic and truthy for non-bitonic. Takes some inspiration from @JonathanAllan’s Jelly answer.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
IṠŒgL=2
```
[Try it online!](https://tio.run/##PY49CsJAEIX7PUVI/QRnk81uCNoL1oIHEEFyAbtgY2@t4AEsbYJgEzxIcpH1TfxZZt7szzdvdrep632Mi769vk7b5czGvn1WQ3NOJvNkaC5VdzT9474aDrfuSFnHmKapIIODR4Ec1pQlS4AURqa6IH9VYUIgGmN@5KtiLNQtpx/7YX97eKP@jqeMt8K3fJyohNOZIaAg5uEIkSJGTsGSUCDm2UILfvgN "Jelly – Try It Online")
## Explanation
```
I | Increments
·π† | Signs
Œg | Group consecutive equal values
L=2 | Length is equal to two?
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 36 bytes
```
->a,*l{l.chunk{|x|a<=>a=x}.count==2}
```
[Try it online!](https://tio.run/##PY5RC4IwFIXf@xU9x0nadG5C84@EDyZIkFhEgqH@9nVuM8fuYffufGd7DddPaH04ljUO3dQlzW3o79M8zvXZl7Ufl6R5DP3be72E5769KKQwsMiRQVc7GRUFzw4qj606yYLaVIQFBSX7V1FWVRHUkPCM8UyKUdD/CWw0ycuGo5RXK6fYyli8ZvuSc8hJWRja6SdAYkMK2h0BS5iJVfgC "Ruby – Try It Online")
Probably the same idea as @JonathanAllan’s Jelly answer.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 40 bytes
This is implementation-dependent, as it assumes that the `sort()` algorithm compares the items by pairs from left to right, at least while \$x\ge0\$ (after which it no longer matters because we already know that the sequence is not bitonic anyway).
Returns \$0\$ or \$1\$.
```
a=>a.sort(s=(a,b)=>x-=s!=(s=a>b),x=2)|!x
```
[Try it online!](https://tio.run/##bY/LDoIwEEX3/gWsaDIQW96LsvQL3CGLgvgKoYaiwcR/r1N8RGObzk3aO3Nm5iSuQjXD8Tz6vdy2ese14IUIlBxGT3FPQE14MflcORzfoqgJTJyRuzPpRvZKdm3Qyb3nluvhMh5ulUsW3/87r6QQQgwpJBABq8ifn@doZEATi0eX5gD9qBEMoEDNneMpL6UWCgMzQ4RTzD1@bHfTlyvRKfvk7F0HqYVrdorRDzHP1peiZ3IMJbZvnmWQIDyFGEFIQhSy7LAcQRmiUsQmM1A/AA "JavaScript (Node.js) – Try It Online")
[Answer]
# Google Sheets, 80 bytes
```
=regexmatch(join(,sort((D1:Y1<E1:1)+2*(D1:Y1>E1:1)*(E1:1>0))),"^(1+2+|2+1+)0*$")
```
Put the number sequence in cells `D1:Z1` and the formula in cell `A1`.
Simple [Boolean arithmetic](https://en.wikipedia.org/wiki/Two-element_Boolean_algebra) and string matching. Makes just one pass through the array. The `sort()` does not actually sort anything — its purpose is to enable array processing.
Expects that the last number is in or before column `Z`. If you need more columns, replace `:1` with `:Z1` (3 bytes) and insert columns before `Y` as necessary.

[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 43 bytes
```
s/\d+ ?/$&>$'||B/ge;chop;$_=/^(B+1+|1+B+)$/
```
[Try it online!](https://tio.run/##FchBDoIwEEDRfU8xiwY1ExwGaJEQNeneGxhdKFETQhtx2bM7jrv/XxrfkxNZ6HxHOJItDnaVc6DHONyeMQ32uqfLOiBjZgy4sSTC0ICDDjy0UBuGWr9V8dCZvzq9RpVN32vugP03ps8rzouUJ7etuJIyTT8 "Perl 5 – Try It Online")
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~13~~ 11 bytes
-2 bytes thanks to att.
```
1=1⊥2≠/2>/⊢
```
[Try it online!](https://tio.run/##PY9NCsIwEIX3nuItE7DWSZsmXehFxEWpVoSCQrrxAoJdeQQRBM/hUXKROIk/IfPCZL68R5pjn21OTX/YZW3fOLdvQ@j8@UoL8uND@cstV8vcj/cQhq0bHHgmCAU0DCqUUFLUNZ8WVElB87hAf43CBQLFneojXyUpFKJhyZbRAerXwEgRQzS3BV9TnJYpNzI6JVuLikkDzRhzDDKZ0Joxy6DhR@wiJ5P0hemKZnrdvZ6pewM "APL (Dyalog Classic) – Try It Online")
```
1=1⊥2≠/2>/⊢­⁡​‎‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌­
2>/⊢ ⍝ ‎⁡compare successive terms with > (direction of deltas)
2≠/ ⍝ ‎⁢compare successive terms with ≠ (changes in direction)
1⊥ ⍝ ‎⁣sum (# of changes in direction)
1= ⍝ ‎⁤equal to 1
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [Julia 1.0](http://julialang.org/), 29 bytes
```
!L=sum((~=diff)(~L.>0).^2)==1
```
[Try it online!](https://tio.run/##PY3NqsIwEIX3eYq4MoFDcWp/F3Ev@AwXCm0hEmNpK7jy1euJ3nuHmTP5@ebM9RF8J89t213c8rgZ83K9H0drXpfsdLDZT26dk228z9prH/U8dH3wcViMVZoRtNNTNy9DZs5xxTIFvxqPPfb2C0yzj2uIJrjTLlg1xH4THFGiRoUCuWpbtgZSKTmkgPxrEhYEkvJTX/lVUTmSW0E/ziP/O6NWyb/k7chX4V/x2ZiIMu1sGlTEapSESBEjl8CWUEOs5ggt3g "Julia 1.0 – Try It Online")
based on multiple other answers
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ü.SÔg<
```
Outputs an 05AB1E truthy/falsey value, so `1` if truthy and `0` or a positive integer if falsey.
[Try it online](https://tio.run/##yy9OTMpM/f//8B694MNT0m3@/4821DHWMdUx1zHTMdExigUA) or [verify all test cases](https://tio.run/##PY5BCsIwEEWvErJS@IhpmyYFoRtv4LJ0UaFqQRBsFbpw6wHEW3gFd72JF4l/rBoyn5nJmz85tNW6qcO5z7V6XW9K530YnrPVcN8uwjJvtJp0x1O366d6eLDYVPu2ZnFBKAqDGBYOKRJEJYosY@JhUuZmLgfmryIMGBi5nxjlq4ZTEcQzoSs9FBdEvxKOz7LKso7ZF9wwl55QdvyA90gJO1iCJImSHeGMoCfqOEajsnwD).
**Explanation:**
```
ü # For each overlapping pair of the (implicit) input-list:
.S # Compare them: 1 if a>b; 0 if a==b; -1 if a<b
Ô # Connected uniquify this list
g # Pop and push the length
< # Decrease it by 1
# (after which the result is output implicitly)
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 7 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
│mσ│┘Σ┴
```
[Try it online.](https://tio.run/##PY27EcIwEERzatmAk/WtxeOABBzYQ0IF0IICclqgDuhBjYg9yVij27mV3u2tp9t8uS7nWku@r98HteTn51Xyu9ZRMMAhwMPCTIcxJTYR4tnLUQ9kVxUWBKK3VZdNhVMGmmmZ2jJg/g6BXjc5@oHv0v5t266U6/tjhCcc4AiSJEq2w4lgJBo4xqDpBw)
**Explanation:**
```
│ # Get the forward differences of the (implicit) input-list
m # Map over each integer:
σ # Get its sign
│ # Get the forward differences of this list again
‚îò # Check for each that they're NOT equal to 0
Σ # Sum the amount of non-zero values together
┴ # Check whether this is equal to 1
# (after which this is output implicitly as result)
```
[Answer]
# APL+WIN, 15 bytes
Prompts for input.
```
1=+/2=|2-/√ó2-/‚éï
```
[Try it online! Thanks to Dyalog Classic](https://tio.run/##PY1BCsIwEEX3cxV/qZM2TbroAQTFM5RKRSgouBJcqytxIx7Im/Qi8SdVQ@bzZ@bNTHsYss2pHfbbrBva43HXhfH@XC3Hy6MQusWaTmW8XfugzSw3zdlk@ftFYTewLqEXRQELhwoljPRS1zQeWtHrPD7oX6MwoND4U0zyVeWUQdxZcmvaAfPL4JjHS5Z5wbqmfpmuR8pO971HRdjBEiRJlOwE1wQ9UccxLpIP "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Raku](https://raku.org), 29 bytes
```
($_ Z-.skip)>>.sign.squish==2
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PY5LTsMwEIb3OcXIKlUjTS3sxokjSC7Bjg3qgoDVB22cLCrESdhkAQs23ICD5Db9pwEsz_j1zTd-_2jXm3742p1o3lBFr5991yz9z2L2QPdLHTfhkNa1juFpr-OxD_G5quzEjLdvNxTXJ9J3XaubXbdQV85GlTIpqmr4IEkVNS8tbcP-MYrnsA3gWKWTYxi_Da_YccE5Z2yTssTi2eSJuZbB5j9LQrBhI_MSU_rNJrEstgw-1LP923ORiN_htMKtwVt26SiEk57ecw6sYAcIFDBwApaAPLACJVBM3z4D)
Zip-subtract the sequence with itself-skipped, i.e., take the differences and further take the sign of those differences. Lastly "squish" the signs, which squeezes consecutive duplicates into one, i.e., uniq of UNIX; if we have 2 unique signs at the end, sequence is bitonic.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Outputs `0` for `true` or a non-zero integer for `false`.
```
äÎòÎÊÍ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=5M7yzsrN&input=W1sxLDMsNSw3LDYsNCwyXSxbOTksNCw4LDE2XSxbMTAwMDAwLDEwMDAwLDEwMDAsMTAwLDEwLDEsMTEsMTExLDExMTEsMTExMTEsMTExMTExXSxbMiwxLDMsNCw1LDZdLCBbMSwyLDMsNCw1LDYsN10sWzcsNiw1LDQsMywyLDFdLFsxLDQsNyw2LDIsMyw1XSxbOTksODgsNjYsNzcsNTUsNDQsMzMsMjIsMTFdLFsxLDksMiw4LDMsNyw0LDYsNV1dLW1S)
[Answer]
# [C (clang)](http://clang.llvm.org/), 62 bytes
```
i;f(*l,z){i=*l=*l>l[1];return--z-1?f(l+1,z)+(i%2-*l&&++i):-1;}
```
[Try it online!](https://tio.run/##fZLRasIwFIbv@xRBUBp7Spe0TVKL292eYHdOhrh2BLJu1Hqj@OzdqdY6ok1IDgQO3///J9mGW7OpvtpW56U/N3CgR72cG9zPZsXWeV00@7oKw0PIXkrfBAw7Al9PeTg3s1kQaLoIWX5qvze68unRi6K3el8sPF01pCl2zQcjq/XySBjEkIIEAQlwcsq93xpbSn8y/XyvJlD6124gO30ofkq/v9Oov2M7pTT3bmh@QZMsQ6gCJsa5nFhgfg8euHHPZU/dAjbUruABBqzb53MpfWXjDmLbQexwkPQOOHRzS3ByjmyJTU4eDC2KXjdm9/9h0mtK4FcNkKMiqS2SOuyLHt09d4roGCXYKFrYaOFAy8F1cv5Nnfd0FC1ttHSg1e07KQUCpyEhRfvoHwNggvEIytZRDp1siJChfYUBJIYRjhiZjc8evPCp/QM "C (clang) – Try It Online")
Return false if bitonic , true otherwise
[Answer]
# [Uiua](https://www.uiua.org), 14 bytes
```
=1/+≡/≠◫2≡/>◫2
```
Gets windows, compares, gets windows, counts changes in comparisons and checks if the number of changes is exactly 1.
[Test pad](https://uiua.org/pad?src=0_7_1__RiDihpAgPTEvK-KJoS_iiaDil6sy4omhLz7il6syCgojIFRydXRoeQpGIDFfM181XzdfNl80XzIKRiA5OV80XzhfMTYKRiAxMDAwMDBfMTAwMDBfMTAwMF8xMDBfMTBfMV8xMV8xMTFfMTExMV8xMTExMV8xMTExMTEKRiAyXzFfM180XzVfNgoKIyBGYWxzeQpGICsx4oehNyAgIyAxXzJfM180XzVfNl83CkYg4oeMKzHih6E3ICMgN182XzVfNF8zXzJfMQpGIDFfNF83XzZfMl8zXzUKRiDih4zDlzExKzHih6E5ICMgOTlfODhfNzdfNjZfNTVfNDRfMzNfMjJfMTEK)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 39 bytes
```
\d+
$*
(?<=(1+)),1\1
;
1
^,+;+$|^;+,+$
```
[Try it online!](https://tio.run/##PY29DsIwDIR3P0eQUnIDbpsmUUGMvERVgQQDC0PFyLuHc/mJ7IvjfD4vt@f9cakbfzrX6RrEbcUf9wevoWmgk8ooKjIjjMG95jEguFoVHSISBvRopRReGTqI7uxA/2rChEIt1vzIV1VamFtPP86j/dVIYv6Rr45d5V@/bjQi2s6cMRBLiIRIESNnYCGUiSWO0OIN "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Port of @NickKennedy's Jelly answer.
```
\d+
$*
```
Convert the integers to unary.
```
(?<=(1+)),1\1
;
```
Replace the comma with a semicolon for all ascending pairs. (The lookbehind both allows the "matches" to overlap and being atomic finds the start of the unary value without needing a word boundary.)
```
1
```
Delete any remaining `1`s.
```
^,+;+$|^;+,+$
```
Check whether the sequence is bitonic.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes
```
≔EΦθκ›ι§θκθ⁼№θ§θ⁰⌕謧θ⁰
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DN7FAwy0zpyS1SKNQRyFbU0fBvSg1EcTN1FFwLPHMS0mtgMhoAuUKNa25Aooy80o0XAtLE3OKNZzzS4GcQhSlBiCVbpl5KSCOX36JBqocCFj//x8dbahjrGOqY65jpmOiYxQb@1@3LAcA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔EΦθκ›ι§θκθ
```
Create a list of `1`s and `0`s corresponding to whether the overlapping pairs of integers are ascending or descending.
```
⁼№θ§θ⁰⌕謧θ⁰
```
Check that the count of occurrences of the first element is also the start of the second run of identical elements; if there is only one run then there is no start of the second run while if there are more than two runs then there are too many of the first element to fit before the second run.
[Answer]
# [Clojure](https://clojure.org/), 84 bytes
```
#(=(sort(mapcat set(partition-by +(for[i(map -(rest %)%)](Long/signum i)))))'(-1 1))
```
Annoyingly `partition-all` is a long function name, and the static function call `Long/signum` (which outputs -1, 0 or 1) cannot be directly composed with `-` using `comp`.
[Try it online!](https://tio.run/##PYvRDoIwDEXf@YomhtjFEh2iPvkH/gHZA@JmZmAj23jw6ycbxLb3pOnt7Qf7mZ2MEV9SgYId3tFbF3Dspr4L4GXAqXNBB21N9fzCAZV1rU4@VOikD1Cykgl8WPM@ev028wiapdpjxYEvS1Hg5LQJg4GcU9AWAC0/pSL@Z8Ii4sTTZK3YyEXO0ZkudKMrNVSvF1h685rs1OlHFIKxGH8 "Clojure – Try It Online")
[Answer]
# APL(NARS), 12 chars
```
1=≢⍸∼2=/2</⎕
```
This above it seems ok for all test
how to use it:
```
1=≢⍸∼2=/2</⎕
‚éï:
1 9 2 8 3 7 4 6 5
0
```
test but the char "∼" in Tio is not the same char of the answer.
<https://tio.run/##PY09DsIwDIX3nOWh4rT5qUQPgATiDJVQWSrBysIIZQCxcAFOwXlykfCSAFH89Gx/tvvDONse@3G/i@H@XK/C@VEruuWGTlSYLkOULlxf4fY@6a7Si4rdyHoclKCGgYNFA60G1bY0HmLpZZ4e5K9JGBBI@jmKfFU4pZF2Ntyad0D/Mjjm6ZJhXrMuud/k64ky5b73sIQdDEGSRMkWuCXoiTqOcdEH>
[Answer]
# [Desmos](https://desmos.com/calculator), 42 bytes
```
f(L)=d(d(L))^2.total-1
d(L)=sgn(L[2...]-L)
```
[Try It On Desmos!](https://www.desmos.com/calculator/jds74gswcp)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/fx8hl8ekfc)
Returns `0` if bitonic or a non-zero integer otherwise.
[Answer]
# Swift, 143 bytes
Minimal version:
```
func b(_ a:[Int])->Bool{var c=[Int]();for i in 0..<a.count-1{let s=(a[i+1]-a[i]).signum();if s != 0 && s != c.last{c+=[s]}};return c.count==2}
```
Verbose version:
```
func bitonic3(_ array: [Int]) -> Bool {
let a = array
var changes: [Int] = []
var reducedChanges: [Int] = []
for i in 0 ..< a.count - 1 {
let sign = (a[i+1] - a[i]).signum()
if sign != 0 {
changes.append(sign)
}
}
for i in 0 ..< changes.count {
let value = changes[i]
if reducedChanges.last != value {
reducedChanges.append(value)
}
}
if reducedChanges.count != 2 {
return false
}
return true
}
```
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-e`, 4 bytes
```
∆±ĉđ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PY8xDsIwDEV3ToEy_0q4bZr0LFWHgsqCCkPLFRCMzCwdQAKJhRsg1EuwchJ-kkIUf9nO87dyuq7r1aapuupeqKhRmKqoVmV_2XbLyN4--93rMRyG47mdL9qx27-fhSCBhkGGFHE5KfKciYVkzGXmDuSvThgQiLs-gowqnIrhPFO6eg_EvwqGtdukWSfsi39P_XZH6bDfWmSEDTRBkkTJBjgnaIkajtGoDB_5Ag)
```
∆±ĉđ
∆ Delta; differences between consecutive elements
± Sign
ĉ Split into chunks of identical elements
đ Unpair; check if length is 2
```
]
|
[Question]
[
Inspired by [this](https://mathematica.stackexchange.com/q/261869/71549) Mathematica.SE post
Given two positive integers \$n, k\$ with \$n > k \ge 1\$, output a binary \$n\times n\$ matrix such that every row and column contains exactly \$k\$ 1s, and the leading diagonal is all zero. This is the adjacency matrix of a [regular graph](https://en.wikipedia.org/wiki/Regular_graph).
You may output any valid matrix, and it does not have to be deterministic. You may output in any [reasonable format](https://codegolf.meta.stackexchange.com/q/2447/66833), including a flat \$n^2\$ list, or a nested list, etc.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
## Test cases
```
n, k -> output
2, 1 -> [[0, 1], [1, 0]]
5, 3 -> [[0, 1, 1, 1, 0], [1, 0, 0, 1, 1], [1, 1, 0, 0, 1], [1, 0, 1, 0, 1], [0, 1, 1, 1, 0]]
3, 1 -> [[0, 1, 0], [0, 0, 1], [1, 0, 0]]
5, 1 -> [[0, 1, 0, 0, 0], [1, 0, 0, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1], [0, 0, 1, 0, 0]]
6, 2 -> [[0, 0, 0, 0, 1, 1], [1, 0, 0, 0, 1, 0], [1, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 1], [0, 0, 1, 1, 0, 0], [0, 1, 0, 1, 0, 0]]
7, 6 -> [[0, 1, 1, 1, 1, 1, 1], [1, 0, 1, 1, 1, 1, 1], [1, 1, 0, 1, 1, 1, 1], [1, 1, 1, 0, 1, 1, 1], [1, 1, 1, 1, 0, 1, 1], [1, 1, 1, 1, 1, 0, 1], [1, 1, 1, 1, 1, 1, 0]]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 5 bytes
```
Ḷṙ`U<
```
[Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCLhuLbhuZlgVTwiLCIiLCIiLFsiNSIsIjMiXV0=)
-1 byte thanks to Jonathan Allan
```
Ḷṙ`U< Main Link; take n, k
Ḷ [0, 1, 2, ..., n - 1]
` Apply with ^ on the left and right:
ṙ Rotate left; [[0, 1, 2, ..., n - 1], [1, 2, 3, ..., n - 1, 0], [2, 3, 4, ..., n - 1, 0, 1], ...]
U Reverse each; [[n - 1, n - 2, ..., 1, 0], [0, n - 1, n - 2, ..., 2, 1], [1, 0, n - 1, ..., 3, 2], ...]
< Is this less than k? [[0, ..., 1, 1, 1], [1, 0, ..., 1, 1], ...]
^-- k --^
```
[Answer]
# [Python 2](https://docs.python.org/2), 45 bytes
Saved 15 bytes thanks to [loopy walt](https://codegolf.stackexchange.com/users/107561/loopy-walt)! (Using the flat list output option.)
```
lambda n,k:[(i/n+~i)%n<k for i in range(n*n)]
```
An unnamed function accepting `n` and `k` that returns a list of booleans
**[Try it online!](https://tio.run/##TY7RToNAEEXf/Yr7YpjFkUYaa0LaL8GGrIG2K2Ugyxoxpv113EVSui93Z25y5nQ/7tRKOh4rVzTaWTNgh/fxrJuPUkO4znIyK3m6GvUo2xqH1sLACKyWY0USi9qPYSmMOuyJUsaLYtArYx1yvcxTbhhpyDfGRqnsAf511ohD9HvJosTTvAlRICo11bbqv87Omy2a//XUhvO2/S6MlNVw5zaz7/iIks/WCDW6o95ZRvj4hucLucQLKIPEz9fbvFezzMyKxj8 "Python 2 – Try It Online")**
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 33 bytes
```
f(n,k)=matrix(n,,i,j,(i-j-1)%n<k)
```
[Try it online!](https://tio.run/##RYjNCsIwDIBfJQyEBpLDOpwHdS8Seshlkk1LKDvMp6@rHjx9P67F@OG1ziHTiveXbsX2w8looWC8cI@nfFuxqvvzHRR4Ai@Wt0M7njq8/tLDHFT6RKASEyKBSCRoQ84EQ@Pw7y9Hgth4IRhTwvoB "Pari/GP – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 6 bytes
```
Ḷ_þ%Ɗ<
```
[Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCLhuLZfw74lxoo8IiwiIiwiIixbIjUiLCIzIl1d)
[Answer]
# [Factor](https://factorcode.org/) + `math.matrices`, ~~64~~ 60 bytes
```
[ dupd dupd '[ - 1 - _ rem _ < 1 0 ? ] <matrix-by-indices> ]
```
The `<matrix-by-indices>` word postdates build 1525 (the one TIO uses), so here's a screenshot of running this in Factor's REPL:
[](https://i.stack.imgur.com/bSwxa.png)
This is a port of @alephalpha's [Pari/GP answer](https://codegolf.stackexchange.com/a/240885/97916). `<matrix-by-indices>` is a combinator with stack effect `( ... m n quot: ( ... i j -- ... elt ) -- ... matrix )`. In other words, it lets you generate an `m`x`n` matrix but leaves the indices of each element (`i`, `j`) on top of the stack while you do so.
[Answer]
# JavaScript (ES6), 50 bytes
*Fixed version now using [Jonathan Allan's formula](https://codegolf.stackexchange.com/a/240917/58563)*
*Thanks to @emanresuA for spotting some dead code (-2 bytes)*
Expects `(n)(k)`, returns a flat array of Boolean values.
```
n=>k=>[...Array(n*n)].map((_,x)=>(x+~(x/n)+n)%n<k)
```
[Try it online!](https://tio.run/##dcxBCsIwFEXRufsQ3rP6RYt2YgKuQ0RCbUVbf0oqEiduPXaqxenhcm/u6foyXLvHQv25SrVJamxj7EFE9iG4F3SmPMrddcBpHmksYvZGXCoz5VR3DVPptfdtJa2/oMaaWJGTb9wQ@QjzP@UYtxy2v1hwcKYP "JavaScript (Node.js) – Try It Online") (raw output)
[Try it online!](https://tio.run/##dc7BboJAEAbgO0/xXxpmyrpNNeoBl6QHn4JuyIaCIjprwBga0746paSY9tDTfPNnJvkP7uravKnOl5n4t6IvTS8mqU2Saq1fmsa9kzwKW31yZ6JMdWwS6qJP6p6EI@EH2dTcx2kApJgrPMOq0UuFxeTF3/zulcJ88lphBRvYQJe@2bp8T5SKQm0ZJsFtuHEwKEmYao6HNffS@mOhj35Hv8r@VM2@v/6JI6fbfVVeiFkffCUUIrzzVUJGhHHGwQf3Xw "JavaScript (Node.js) – Try It Online") (with post-processing)
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 9 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
rxm<k(Å_╪
```
Outputs all rows concatenated to the stack.
[Try it online.](https://tio.run/##y00syUjPz0n7/7@oItcmW@Nwa/yjqav@/zdSMOQyVTDmMgbThlxmCkZc5gpmAA)
**Explanation:**
```
r # Push a list in the range [0, first (implicit) input n)
x # Reverse it to range (n,0]
m # Map over each integer:
< # Check if it's larger than the second (implicit) input k
k # Push the first input n again
( # Decrease it by 1
Å # Loop that many times,
# using the following 2 characters as inner code-block:
_ # Duplicate the top list
╪ # Rotate the items in the list once towards the right
# (after which the entire stack is output implicitly as result)
```
[Answer]
# Apl
**67 bytes**
`{{(⍴⍵)⍴{⍵[?⍨≢⍵]}∊⍵}⍣{((∧/2=/+/,+⌿)⍺)∧∧/~1 1⍉⍺}⍵ ⍵⍴⍺(⍺-⍵)/1 0}`
incredebly ineffecent ,might be needlessly long
explantion
`{{(⍴⍵)⍴{⍵[?⍨≢⍵]}∊⍵}` shuffles array randomly untill
`{∧/~1 1⍉⍺}`digonal is all 0s
`{((∧/2=/+/,+⌿)⍺)}` and sum of all the rows and column is the same
`{⍵ ⍵⍴⍺(⍺-⍵)/1 0}` makes a n×n matrix of right argument with required 0s and 1s
[Answer]
# [R](https://www.r-project.org/), ~~49~~ ~~40~~ 38 bytes
*Edit: -9 bytes thanks to Giuseppe*
```
function(n,k)outer(1:n-1,1:n,`-`)%%n<k
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNPJ1szv7QktUjD0CpP11AHSOok6CZoqqrm2WT/107TMNEx1OQC00ZQ2ljzPwA "R – Try It Online")
Returns a matrix with values `TRUE`/`FALSE` (which evaluate to `1`/`0` in [R](https://www.r-project.org/)). Add [+3 bytes](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNPJ1tTWyO/tCS1SMPQKk/XUAdI6iToJmiqqubZZGv@T9Mw0THU5AJRRhDKWPM/AA) to output as a matrix with `1`s and `0`s directly.
---
Or my very lazy first attempt:
# [R](https://www.r-project.org/), 93 bytes
```
function(n,k,`?`=rowSums){while(any(c(?(m=matrix(sample(1:0,n^2,T),n)),?t(m))-k,diag(m)))0;m}
```
[Try it online!](https://tio.run/##VY1BDoIwEADvvmQ3WRNAT5qmj5Cz0iCWBnchSwkS4turntTbzFxGkzb@4tUNrUm3SeoYegGhjipbGe3n08QjrnMb7g04WaAGC2zYRQ0PGB0P754fMpJzQSWSIJKNwIjbjq7B@Q9iduTndwR7ynHzq8W/7jC9AA "R – Try It Online")
Extremely inefficient (and often times-out on TIO even for the n≥5 test-cases), but will eventually (= nonzero probability) deliver the right answer each time.
Samples random matrices of `0`, `1` until a solution is found that satisfies the rowSums, colSums & diag conditions.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes
```
NθNηEθ⮌⭆θ‹﹪⁺ιλθη
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oLmZ8B5AcUZeaVaPgmFmgU6igEpZalFhWnagSXAEXToYI@qcXFGr75KaU5@RoBOaXFGpk6CjmaOgqFQJyhCQLW//@bKhj/1y3LAQA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ First input `n` as a number
Nη Second input `k` as a number
θ First input
E Map over implicit range
θ First input
⭆ Map over implicit range and join
ι Row index
⁺ Plus
λ Column index
﹪ Modulo
θ First input
‹ Is less than
η Second input
⮌ Reversed
Implicitly print
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 38 bytes
```
\d+
$*0
(0+) \1
$.1$*
.
$'$`$&¶
O$^`.+
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyZFm0tFy4BLw0BbUyHGkEtFz1BFi0uPS0VdJUFF7dA2Ln@VuAQ97f//jRQMuUwVjLmMwbQhlxkQmyuYAQA "Retina 0.8.2 – Try It Online") Link includes test cases. Output includes trailing newlines. Explanation:
```
\d+
$*0
```
Convert both inputs to strings of `0`s.
```
(0+) \1
$.1$*
```
Subtract `k` from `n` and convert it to a string of `1`s, so there are now `n-k` `0`s and `k` `1`s.
```
.
$'$`$&¶
```
Generate the cyclic permutations of that string in reverse order.
```
O$^`.+
```
Reverse the permutations into the desired order. (Normally the `$` needs another line to specify the sort key but this is an edge case where it's not needed.)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 41 bytes
```
IdentityMatrix@#~RotateLeft~n~Sum~{n,#2}&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zMlNa8ks6TSN7GkKLPCQbkuKL8ksSTVJzWtpC6vLrg0t646T0fZqFbtf0BRZl5JdFq0kY5hbCwXjGeqY4zEM0aTQ@aZ6Rgh8cx1zGJj/wMA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 49 bytes
```
->a,b{a.times.map{|c|([0]*(a-b)+[1]*b).rotate c}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5RJ6k6Ua8kMze1WC83saC6JrlGI9ogVksjUTdJUzvaMFYrSVOvKL8ksSRVIbm29n@BQlq0qY5x7H8A "Ruby – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 16 [bytes](https://github.com/abrudz/SBCS)
```
{↑(-⍳⍵)⌽¨⊂⍵↑⍺⍴1}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR20QN3Ue9mx/1btV81LP30IpHXU1ANlD4Ue@uR71bDGv/pz1qm/Cot@9R31RP/0ddzYfWG4Nk@6YGBzkDyRAPz@D/afqHVihoGCuYaipomCmYA0lDIBsA "APL (Dyalog Unicode) – Try It Online")
Generates a fixed pattern by rotating each row by its index.
---
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 41 [bytes](https://github.com/abrudz/SBCS)
```
{{⍵[?⍨≢⍵]}⍤1⍣{(~1 1⍉⍺)∧.=≢∪+⌿⍺}↑⍵/⊂⍵↑⍺/1}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v7r6Ue/WaPtHvSsedS4CMmNrH/UuMXzUu7hao85QAcjofNS7S/NRx3I9W5CCjlXaj3r2A4VqH7VNBCrXf9TVBKTAnF36hrX/0x61TXjU2/eob6qn/6Ou5kPrjUFyfVODg5yBZIiHZ/D/NP1DKxQ0jBVMNRU0TMCkoYKJJgA "APL (Dyalog Unicode) – Try It Online")
Shuffles each row until the conditions are satisfied.
[Answer]
# APL+WIN, ~~23~~ 21 bytes
Prompts for k followed by n. Index origin = 0
```
(⌽⍳n)⌽(n,n)⍴(n←⎕)↑⎕⍴1
```
[Try it online!Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlwPWooz3tv8ajnr2PejfnaQJpjTwdIN27RSMPKA9Up/mobSKQAooY/gcq5vqfxmXIZcSlrqDOlcZlzGUKZRkC2TAWTMyIywzKMuMy5wIA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes
```
ɾṘ≥:(…ǔ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJQIiwiIiwiyb7huZjiiaU6KOKApseUIiwiIiwiNVxuMyJd)
[Answer]
# [Knight](https://github.com/knight-lang/knight-lang), 49 bytes
```
;=xE P;=yE P;=i~1W>^x 2=i+1iO+0>y%+x%--/i x iTx x
```
[Try it online!](https://knight-lang.netlify.app/#WyI7PXhFIFA7PXlFIFA7PWl+MVc+XnggMj1pKzFpTyswPnklK3glLS0vaSB4IGlUeCB4IiwiNVxyXG4zIl0=)
[Answer]
# Python3, 223 bytes:
```
from itertools import*
def f(n,k,c=[]):
if len(c)==n:yield c
else:
for i in product(*[{0,not c or(i!=len(c)and sum([*zip(*c)][i])<k)}for i in range(n)]):
if sum(i)==k:yield from f(n,k,c+[i])
g=lambda n,k:next(f(n,k))
```
[Try it online!](https://tio.run/##XY7LboMwEEX3fMV056FetEFNI1R/CWJB/aAjzNgyjpSk6rdToGmFujxzde@ZeM0fgatTTPPsUhiBsk05BD8BjTGkXBbGOnCC5SC1alqsCyAH3rLQqBTXV7LegC7A@skuIbiQgIAYYgrmrLMom88nySGDhpAEPaifcscGpvMomvJGUZQa24ZafBvw628hddxbwbhZYfWuBVq8w927/Xz/7nHtF73y3fhuOlhuNdtLFluMOMdEnEUvDvIZsfilF1ntqPqX7ekoDzt6lcdl8xs)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
LR@Dv=Á
```
Pretty similar approach as [my MathGolf answer](https://codegolf.stackexchange.com/a/240893/52210).
Outputs all rows-lists on a separated line.
[Try it online](https://tio.run/##yy9OTMpM/f/fJ8jBpcz2cOP//6ZcxgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WGeSSoOSZV1BaUmylkGd7eL@OQjaQVNLhUvIvLQEKWyko6ST89wlycCmzPdz4v/bQNvv/0dFGOoaxOtGmOsZA0hjKBpFmOkZA0lzHLDYWAA).
**Explanation:**
```
L # Push a list in the range [1, first (implicit) input n]
R # Reverse it to [n,1]
@ # Check for each value if the second (implicit) input k >= the value
D # Duplicate this list
v # Pop and loop its size amount of times:
= # Print the list with trailing newline (without popping)
Á # Rotate its items once towards the right
```
[Answer]
# brev, 82
```
(lambda(n k)((over(with i((over(if(or(= i it)(> i k))0 1))x)))(make'()n(iota n))))
```
]
|
[Question]
[
## Challenge:
Given a positive integer, output the longest single-digit subsequence that occurs at least twice, AND has boundaries of another digit (or the start/end of the integer).
**An example:**
Input: `7888885466662716666`
The longest subsequence of a single digit would be `88888` (`7[88888]5466662716666`) with a length of 5. However, this subsequence only occurs once in the integer.
Instead, the result for input `7888885466662716666` should be `6666` (`78888854[6666]271[6666]`), since it occurs (at least) twice.
## Challenge rules:
* Length of the subsequences takes priority over the amount of times it occurs. (I.e. with input `8888858888866656665666`, we output `88888` (`[88888]5[88888]66656665666`; length 5, occurs twice), and not `666` (`88888588888[666]5[666]5[666]`; length 3, occurs thrice).
* If the length of multiple subsequences are equal, we output the one with the largest occurrence-count. I.e. with input `3331113331119111`, we output `111` (`333[111]333[111]9[111]`; length 3, occurs thrice), and not `333` (`[333]111[333]1119111`; length 3 as well, but occurs twice)
* If the occurrence-count and length of multiple subsequences are equal, you can output either of them, or all (in any order). I.e. with input `777333777333`, the possible outputs are: `777`; `333`; `[777, 333]`; or `[333, 777]`.
* The subsequence must have boundaries of other digits (or the start/end of the integer). I.e. with input `122222233433` the result is `33` (`1222222[33]4[33]`; length 2, occurs twice) and not `222` (`1[222][222]33433`, length 3, occurs twice with both invalid).
+ This applies to all numbers that are counted towards the occurrence-counter. I.e. with input `811774177781382` the result is `8` (`[8]117741777[8]13[8]2`; length 1, occurs thrice) and not `77` (`811[77]41[77]781382` / `811[77]417[77]81382`; length 2, occurs twice with one invalid) nor `1` (`8[1][1]774[1]7778[1]382`; length 1, occurs four times with two invalid).
* You can assume the input won't contain any digits `0` (it will match `[1-9]+`). (This is to avoid having to deal with test cases like `10002000` that should output `000`, where most languages would output `0` by default.)
* You can assume the input will always contain at least one valid output.
* I/O are both flexible. Can be a list/array/stream of digits/bytes/characters or as string instead of a single integer.
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code.
* Also, adding an explanation for your answer is highly recommended.
## Test cases:
```
Input: 7888885466662716666 / [7,8,8,8,8,8,5,4,6,6,6,6,2,7,1,6,6,6,6]
Output: 6666 / [6,6,6,6]
Input: 3331113331119111 / [3,3,3,1,1,1,3,3,3,1,1,1,9,1,1,1]
Output: 111 / [1,1,1]
Input: 777333777333 / [7,7,7,3,3,3,7,7,7,3,3,3]
Possible outputs: 777; 333; [777,333]; [333;777] / [7,7,7]; [3,3,3]; [[7,7,7],[3,3,3]]; [[3,3,3],[7,7,7]]
Input: 122222233433 / [1,2,2,2,2,2,2,3,3,4,3,3]
Output: 33 / [3,3]
Input: 811774177781382 / [8,1,1,7,7,4,1,7,7,7,8,1,3,8,2]
Output: 8 / [8]
Input: 555153333551 / [5,5,5,1,5,3,3,3,3,5,5,1]
Output: 1 / [1]
Input: 12321 / [1,2,3,2,1]
Possible outputs: 1; 2; [1,2]; [2,1] / [1]; [2]; [[1],[2]]; [[2],[1]]
Input: 944949949494999494 / [9,4,4,9,4,9,9,4,9,4,9,4,9,9,9,4,9,4]
Output: 4 / [4]
Input: 8888858888866656665666 / [8,8,8,8,8,5,8,8,8,8,8,6,6,6,5,6,6,6,5,6,6,6]
Output: 88888 / [8,8,8,8,8]
Input: 1112221112221111 / [1,1,1,2,2,2,1,1,1,2,2,2,1,1,1,1]
Output: 111; 222; [111,222]; [222,111] / [1,1,1]; [2,2,2]; [[1,1,1],[2,2,2]]; [[2,2,2],[1,1,1]]
Input: 911133111339339339339339 / [9,1,1,1,3,3,1,1,1,3,3,9,3,3,9,3,3,9,3,3,9,3,3,9]
Output: 111 / [1,1,1]
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes
```
γТ1›ÏD€gZQÏ.M
```
[Try it online!](https://tio.run/##LU0xCgJBEOvnLSJkZ8bZ7W0tbO1OELGyEATBQvzA@QZrOzvL295H3EfWuV0TkhAI5HjqtodduZ4v5fvOj@GJ8fbJ/XK8v/abde7nqzIrFieoLBzBMAUxM4DmyUVm5q05IVQwi5cImInLIjgGUlWor9jTlxxASSRJSlJZk9pndf/Tv34 "05AB1E – Try It Online")
**Explanation**
```
γ # group consecutive equal elements
Т # count the occurrence of each group among the list of groups
1›Ï # keep only groups with a count greater than 1
D€gZQÏ # keep only those with a length equal to the greatest length
.M # get the most common item
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
Œgœ-Q$LÐṀÆṃ'
```
[Try it online!](https://tio.run/##y0rNyan8///opPSjk3UDVXwOT3i4s@Fw28Odzer/D7c/alqTBcSPGuZYP2qY6/7/f3S0uY4FHJrqmOiYQaGRjrmOIYwXq8MVbawDgoZgiMy2hNAgJeY6IAiRRGKDpAyBBiIgSNgEJmUBNgCk2gRKg9wEssRCxwikwFQHBA2B2BgKwXyYscZADOZYAg0w0bEEY0s4C8KDsiH2IfyLYEN8aopKx8YCAA "Jelly – Try It Online")
### Previous version – 14 bytes
```
ŒgŒQ¬TịƲLÐṀÆṃ'
```
[Try it online!](https://tio.run/##y0rNyan8///opPSjkwIPrQl5uLv72CafwxMe7mw43PZwZ7P6/8Ptj5rWZAHxo4a51u7//0dHm@tYwKGpjomOGRQa6ZjrGMJ4sTpc0cY6IGgIhshsSwgNUmKuA4IQSSQ2SMoQaCACgoRNYFIWYANAqk2gNMhNIEssdIxACkx1QNAQiI2hEMyHGWsMxGCOJdAAEx1LMLaEsyA8KDs2FgA "Jelly – Try It Online")
### How it works?
```
Œgœ-Q$LÐṀÆṃ' – Full program. Receives a list of digits as input.
Œg – Group equal adjacent values.
œ-Q$ – Multiset difference with itself deduplicate.
LÐṀ – Keep those that are maximal by length.
Æṃ' – Mode. Returns the most common element(s).
-------------------------------------------------------------------------
ŒgŒQ¬TịƲLÐṀÆṃ' – Full program. Receives a list of digits as input.
Œg – Group equal adjacent values.
ŒQ – Distinct sieve. Replace the first occurrences of each value by 1.
and the rest by 0. [1,2,3,2,3,2,5]ŒQ -> [1,1,1,0,0,0,1]
¬T – Negate and find the truthy indices.
ịƲ – Then index in the initial list of groups.
– This discards the groups that only occur once.
LÐṀ – Find all those which are maximal by length.
Æṃ' – And take the mode.
```
[Answer]
# JavaScript (ES6), ~~79~~ ~~73~~ 68 bytes
Takes input as a string. Returns an integer.
```
s=>[...s,r=q=0].map(o=d=>q=s^d?o[!o[q]|r[q.length]?q:r=q]=s=d:q+d)|r
```
[Try it online!](https://tio.run/##bVHbboMwDH3fV7CngsbSOZcFitJ@CMqkqtB2EyMNqfbUf2dO6CoUZmQ7Cec4x/HX/mfvDsPn5fram6Ydj2p0alsTQlw@KKveNPneX1KjGrW1yn00O1M/m9rq21Bb0rX96XrWO7tBrFZONRv70mS3YTyY3pmuJZ05pcd0JQtvgr@jUQk@rbIs8bZeJ377FDEYYwAwxRL9Dz4x8CAmSCkRPcUZ@E7A8yrBP1VS4zLHlY4LAA3GGP@vAGMxvgCQkqPLAlhB5xTEFzFcCAEC72WYl@VhqYbRGDeDVwnFViCnizZKzkteljx8IT@qIJEvugiDCRGnIO4eKL4Lbwtp4J/qEZejQXE0yAMUSKkefwE "JavaScript (Node.js) – Try It Online")
### Commented
```
s => // s = input string, also used as the current digit
[ ...s, // split s into a list of digit characters
r = // r is the final result
q = // q is the current digit sequence
0 // append a final dummy entry to force the processing of the last
] // sequence
.map(o = // o is an object used to keep track of encountered sequences
d => // for each digit d in the array defined above:
q = // update q:
s ^ d ? // if d is not equal to the current digit:
o[ // this statement will ultimately update o[q]
!o[q] | // if q has not been previously seen
r[q.length] ? // or the best result is longer than q:
q // leave r unchanged
: // else:
r = q // set r to q
] = s = d // reset q to d, set the current digit to d
// and mark q as encountered by setting o[q]
: // else:
q + d // append d to q
) | r // end of map(); return r, coerced to an integer
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 56 bytes
```
L`(.)\1*
O`
L$m`^(.+)(¶\1)+$
$#2;$1
N`
.+;
N$`
$.&
-1G`
```
[Try it online!](https://tio.run/##JYtBDsIwDATv/gYBpVRE2tjBifoALlX5QIXCgQOHckC8jQfwseK2Y@2uVlq/H5/n64557y917qsPzYgjXSv1bqo3H9rG/74jmtaR28XOgYZKoe2IBlfJhQOdYJ@z5oUkZyMqliBmBrB5MZGqWtucEFeYxUoGVMWkGZwjpZSQbMWWtuQIKiJFSpH11vwD "Retina – Try It Online") Link includes test cases. Explanation:
```
L`(.)\1*
```
List all the maximally repeated digit subsequences.
```
O`
```
Sort the list into order.
```
L$m`^(.+)(¶\1)+$
$#2;$1
```
List all the multiple subsequences with their "count".
```
N`
```
Sort in ascending order of count.
```
.+;
```
Delete the counts.
```
N$`
$.&
```
Sort in ascending order of length. (Where lengths are equal, the previous order due to count is preserved.)
```
-1G`
```
Keep the last i.e. longest value.
[Answer]
# [R](https://www.r-project.org/), 102 bytes
```
function(i)rep(names(sort(-(x=(x=table(rle(i)))[rowSums(x>1)>0,,drop=F])[m<-max(rownames(x)),])[1]),m)
```
[Try it online!](https://tio.run/##TVDNbsMgDL7nKSJORiJSHWAEqe1xL7Bj1UPWpRJS/gREy54@MzBNNfgz/sA/2B/P@twcz21@RLfM4LgfVpj7aQgQFh@hgf1CO/af4wCe1HHOb375/timAPsV@fUkxJdf1sv7nd@mczP1O9B9ybFzLojGOxcTP@IQYqB69QMqZrokWr2RtAaTYaJiUkpELGhJE2eMIaJg8rHNIqUqfodojCI1HcquTZTWGjU9l2RLiGzzwSpllbUqr2xzhtxLRupD/2kOxFTtH0uO3GEG@7oZr6rQr@v4A/mron4ZbP2EbR5diBCiD@voIjhRM0bz5Mcv "R – Try It Online")
Since there wasn't an R answer yet, I decided to give it a try, and well... it wasn't easy. I don't really know whether it is a good approach, but here it goes.
Inputs and outputs vectors of characters.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~58~~ 56 bytes
```
*.comb(/(.)$0*/).Bag.max({.value>1,+.key.comb,.{*}}).key
```
[Try it online!](https://tio.run/##PU1BDoIwELzvK3owhiIpLm0pDcrBj5hqwIMQDEYjIby9LsU4m5nJJJOdRz20ue9Gtm3Y0cfi2neXKI0E3@zjlIuTu4nOfaJJvF37qitMduJej6GWiCmeZ75kX8LTjayJNmfOmn5gBzDFAq1yQmZwMZBSIuKqlgjGGEqrAmYBUioKBaIximgKlEUGWmvU1JLk1JQZglXKKmtVuOCwbgalPf0j0BQ9/itCVfov "Perl 6 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~123~~ 120 bytes
```
import re
def f(s):r=re.findall(r'(\d)(\1*)',s);c=r.count;print max((len(a+b)*(c((a,b))>1),c((a,b)),a+b)for a,b in r)[2]
```
[Try it online!](https://tio.run/##NY3RbsMgDEXf8xVIe4jpokoGMqCo@5F1D2kS1EgpiWgqbV@fGeiM7HvNMWb93W5LEPs@3dclbiyO1TB65uHBT/Ecx6OfwtDNM8QaLgOHCx543Ty468/x2C/PsLk1TmFj9@4HYB4DdO9XfoAeoGuunH8ib/59k5BfIqOOTYFF/iW@dw@1Nila9UEhNCapefXGkqkqGpBSImKpljJT0gy11kRKTYCcY@RdpihySKkKJZLvDaLWilIblEZkZDJp2xZbei9Jy0evRVK8esdEWW6VsspalU/WPKD2Pw "Python 2 – Try It Online")
[Answer]
# Powershell, 101 byte
```
($args|sls '(.)\1*'-a|%{$_.Matches}|group|?{$_.Count-1}|sort @{e={$_.Name.Length,$_.Count}})[-1].Name
```
Explanied test script:
```
$f = {
(
$args| # for each argument (stings)
sls '(.)\1*'-a| # searches all
%{$_.Matches}| # regex matches
group| # group it (Note: Count of each group > 0 by design)
?{$_.Count-1}| # passthru groups with Count not equal 1
sort @{ # sort all groups by 2 values
e={$_.Name.Length,$_.Count}
}
)[-1].Name # returns name of last group (group with max values)
}
@(
,('7888885466662716666', '6666')
,('3331113331119111', '111')
,('777333777333', '777','333')
,('122222233433', '33')
,('811774177781382', '8')
,('555153333551','1')
,('12321', '1','2')
,('944949949494999494','4')
,('8888858888866656665666','88888')
,('1112221112221111','111','222')
) | % {
$s,$e = $_
$r = &$f $s
"$($r-in$e): $r"
}
```
Output:
```
True: 6666
True: 111
True: 777
True: 33
True: 8
True: 1
True: 1
True: 4
True: 88888
True: 111
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~114~~ 113 bytes
-1 byte thanks to [TFeld](https://codegolf.stackexchange.com/users/38592/tfeld).
```
p='';r=[];C=r.count
for c in input():r+=['']*(c!=p);r[-1]+=c;p=c
print max((len(w),C(w),w)for w in r if~-C(w))[2]
```
[Try it online!](https://tio.run/##PU49T8MwEN39K0wWJ5Qi@QsnjTxVZWVhizIU46oRJbFOjtIu/PXgcxF3vvf8TvcVbvE8jWJ106e3RVGswTLWgu36dm/h2U3zGMlpAuroMKYX5lhWO9jYjrH@sXQPNlQtdFveb6xrg3UkwDBG@n28luXFj@VSPe0RlgqnLDgF6HD62WK26kS/pq2ELOfh4uk7zH5HKI1wQ6LUX72jeBvBv/Mh0sPb6wFggnvBB/jj18pMjabVSzJhOBIjTErJOb9jkyKljDFJ3zFJLrJJqbKsOTdGpTA1l7VIGa0116lWJs71UiA3SjWqaVT2zNidb8iY9uu/wC6Oe/6Rs18 "Python 2 – Try It Online")
[Answer]
## Haskell, 72 bytes
```
import Data.Lists
g!x|y<-countElem x g=(y>1,1<$x,y)
(argmax=<<(!)).group
```
How it works
```
(argmax=<<(!)).group -- expands to: f i = argmax (group i !) (group i)
group -- split the input list into subsequences of equal digits
-- e.g. "1112211" -> ["111","22","11"]
-- find the element of this list where the function !
-- returns the maximum value. First parameter to !
-- is the grouped input list, second parameter the
-- the element to look at
g!x|
y<-countElem x g -- let y be the number of occurrences of x in g
= ( , , ) -- return a triple of
y>1 -- a boolean y>1 (remember: True > False)
1<$x -- length of x (to be exact: all elements in x
-- replaced by 1. This sorts the same way as the
-- length of x)
y -- y
-- a triples sorts lexicographical
```
[Answer]
# [R](https://www.r-project.org/), 85 bytes
```
function(x,R=rle(x),a=ave(R$v,R,FUN=length))rep(R$v[o<-order(a<2,-R$l,-a)[1]],R$l[o])
```
[Try it online!](https://tio.run/##fVE9b8MgEN3zK5CTASQyHOBiS/HasYOlTlEGq8GOJcdEhETpr3cP7DYfTfvw3Rl4evd0uKEuhvrUf/jW9vTCy8J1hl4Yr4rqbGi5OPOSv76/FZ3pG79jzJlDOF3b1dK6rXG0Wgm@LBcdX1ZsDZsNx/@13bChKa66rKZH77xt6anv2qMPu@Ohaz22JEnCELNZQxOdBaTqBSE0hJIwMmFOwj7QpJQAMOYc48qJNDyJYlojZcx3jJFlWr8zjuA9qfotQRLhxDpi@@4TkyG2JsjYBykQEVKqp1JSBlIGoLXC0BnITNzz5iQLnDRNIcVWEusTIRibSfH78tE3RNfiT8u5UrnKcxVXrDeSc6Ki4zjtmHGy6RQTDx0HREcQBvCTH@f97QgmT@IfV/HdYspvv6g4vtxs@AI "R – Try It Online")
* **Input :** a vector of separated integer digits e.g. `c(1,8,8...)`
* **Output :** a vector of separated integer digits
Unrolled code with explanation :
```
function(x){ # x is a vector of digits : e.g. c(1,1,8,8,1,1)
R = rle(x) # Get the sequences of consecutive repeating digits
# doing run length encoding on x, i.e. : R is a list
# with the digits (R$values) and the number of their
# consecutive occurrencies (R$lengths)
# N.B. you can use R$v for R$values and R$l for R$lenghts
a=ave(R$v,R,FUN=length) # Group R$v by R$l AND R$v, count the occurrencies
# for each group and "unroll" the value of each
# group to the original R$v length.
# Here basically we count the occurrencies of the same
# sequence.
o<-order(a<2,-R$l,-a)[1] # Get the indexes used to order by a < 2 then by -R$l and
# finally by -a; store the first index in "o".
# Here basically we use order to select the first sequence
# repeated at least twice, in case of ties the sequence
# with the greatest length and in case of ties the most
# repeated sequence.
rep(R$v[o],R$v[o]) # Using the index "o", we reconstruct the sequence repeating
# R$l[o] times R$v[o]
}
```
---
Alternative version accepting vector of integer or character digits :
# [R](https://www.r-project.org/), 88 bytes
```
function(x,R=rle(x),a=ave(R$v,R,FUN=length))rep(R$v[o<-tail(order(a>1,R$l,a),1)],R$l[o])
```
[Try it online!](https://tio.run/##fZE9b4MwEIZ3foVFMtiSOxw2NUilY8cOSJ2iDKgxCZKLI@NE6a@nZ0Obj6Y98B3Yj957dXZjW43toX/3ne3pideVM5qeGG@q5qhpvTzymr@8vVZG91u/Y8zpfdhd2acH33SGWrfRjjbPwOul4Q3jwNbhc2XXbNxWZ2nW0kNvusHTwbthbzqP7UiaMsaSZEtTVYTI5SNGpiCUlJE5FiT8B0wIAQBTLnGdmYjhThRTCpEpXxETpTu/047gOWn6DUGIcGIdsb35xKSJbQkSH0EKshhCyLtSQgSoAFBK4lIFiCK75hakCEye55BjK4H1jhBMzUT2@/DWN0TX2Z@WSylLWZYyPrFeSC6IjI7jtGPGyebzmjl0HCI6gjCAn3w7729HMHvK/nEV7y2m8vKNitPNJeMX "R – Try It Online")
* **Input :** a vector of separated characters or digits e.g. `c("1","8","8"...)` or `c(1,8,8...)`
* **Output :** a vector of separated characters if the input was a vector of characters, a vector of digits if the input was a vector of digits
[Answer]
# [Red](http://www.red-lang.org), 256 250 bytes
```
func[s][p: func[b][sort parse b[collect[any keep[copy a skip thru any a]]]]first
last sort/compare collect[foreach d p p s[if 1 < k: length? to-block d[keep/only
reduce[form unique d k]]]]func[x y][(reduce[length? x/1 x/2])< reduce[length? y/1 y/2]]]
```
[Try it online!](https://tio.run/##XY/PboQgEMbvPsVkT@2h2SBYdLNJ36FXwsFF7BpdoYDJ@vR2YP@E7eB8I/Ppj8HpbvvWnZBFf9j6ZVbCS2EPkF5PUnjjAtjWeQ0nocw0aRVEO68wam2xYVdowY@DhXB2C0SnlRj94HwoptYHiIi9MhekaHggeuN0q87QgcXlxdADgSOMB5j0/BPOXxDMx2kyaoROxLP2Zp7WwuluUTr@fYFlHn4XjYQxHRgHvsIqxdv9owfouieYpXw/wj9nRWdFR8rNumEO0MOO1zEq9olRchLLrni6lFJCyE0bzMzinGP/plmblCkoZS/tmhDOGSavCa3LzKmqilTIoFhfOLTM9w1jDWsallaqOT3dISnOX90zp5E411NfwOmCSZr82W1/ "Red – Try It Online")
Really, realy long solution this time... (sigh)
Takes the input as a string.
## Explanation:
```
f: func [ s ] [
p: func [ b ] [ ; groups and sorts the adjacent repeating items
sort parse b [
collect [
any keep[
copy a skip thru any a ; gather any item, optionally followed by itself
]
]
]
]
t: copy []
foreach d p p s [ ; p p s transforms the input string into a block of sorted blocks of repeating digits
if 1 < k: length? to-block d [ ; filters only the blocks that occur more than once
insert/only t reduce [ form unique d k ] ; stores the digits and the number of occurences
; "8888858888866656665666" -> [["5" 3] ["666" 3] ["88888" 2]]
]
]
first last sort/compare t func [ x y ] ; takes the first element (the digits) of the last block of the sorted block of items
[ (reduce [ length? x/1 x/2 ]) < reduce [ length? y/1 y/2 ] ] ; direct comparison of the blocks
]
```
[Answer]
# [Java (JDK 10)](http://jdk.java.net/), 213 bytes
```
s->{int l=99,X[][]=new int[10][l],d,D=0,m=0,M=0;for(var x:s.split("(?<=(.))(?!\\1)"))X[x.charAt(0)-48][x.length()]++;for(;M<1&&l-->1;)for(d=0;d++<9;)if((m=X[d][l])>1&m>M){M=m;D=d;}for(;l-->0;)System.out.print(D);}
```
[Try it online!](https://tio.run/##bVFNb6MwEL3nV8wiJbIbQuMAC8Qh1WpzzamXSJQDy0dKli9hJ9sq4rdnbZMm7LaGmZHf8zzGj0N0imaH5PclL5u65XAQe@PI88J4oKNPWHasYp7XlSTjImIMtlFewXkE0Bx/FXkMjEdclFOdJ1AKDj3zNq/2QQhRu2dYHQX4WVfsWKbtqmfXkIF/YbP1Oa84FL7n6bsgDEK/Sv@AgAIyD4Mi1BN948/1UsTWn9OsbtEpauFtyQzWFDlHGnpa@cjAGD19e3khWMN4F7wZ8WvU/uBojmeWG4p9kVZ7/opwOJ0qEbpdkcmkmM3WhGIJJEI9mU5XHsV5hlDp74JEDoDXZFKut/i89Uu68RPaqXbZOaf4@Z3xtDTqIzcacSuONph2F6oufHOBp4wz8K8@AGiOK5dtfRdr4RBZNP2DNE2TENJnT8SdcRxHwH2@o2ShlmlaQ9QlxHEsEY5LTHdxJ2zbJrYQMEUdipiLwdazLM/yPEs9qg6U1ewqi7ntawykiJzolsk/zPVu3uDVFN31nn38X2nZsjcO33z7ZLbkYQraEjRMr4cyI4rjtOlJgT4@ft2cIW28sNkSxmxcabr6li67m6Z475tvmv/3FhW6ct1IRnf5Cw "Java (JDK 10) – Try It Online")
## Explanation (outdated)
```
s->{ // Lambda for Consumer<String>
int l=99, // Length of token, max is 99.
X[][]=new int[10][l], // Array containing the occurrences per token
d, // digit value
D=0, // digit holder for best sequence candidate
m=0, // holder of the current candidate
M=0; // best candidate for the current length of token.
for(var x:s.split("(?<=(.))(?!\\1)")) // Tokenize the string into digit-repeating sequences
X[x.charAt(0)-48][x.length()]++; // Add one occurrence for the token
for(;M<1&&l-->1;) // While no value has been found and for each length, descending. Do not decrease length if a value has been found.
for(d=0;d++<9;) // for each digit
if((m=X[d][l])>1&m>M){ // if the current occurrence count is at least 2 and that count is the current greatest for the length
M=m;D=d; // mark it as the current best
} //
for(;l-->0;)System.out.print(D); // Output the best-fitting subsequence.
} //
```
## Credits
* -9 bytes and bug spotting thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~68~~ 67 bytes
```
->a{(b=a.chunk &:+@).max_by{|x|[(c=b.count x)<2?0:x[1].size,c]}[1]}
```
[Try it online!](https://tio.run/##TVDbCsIwDH3fV4w9iKIW04tdxan/MYZ0RVHEC7rBdPPbZ5qKmDbnJIcmTXuvy2e/z/rpyrbDMrPMHerLKR4sxpsRO9tmWz7brunyoctK5q71pYqb0ZKvZ4smh4I9jq/dxBVvjN99HiU69abkHI1r8JRMokQIAQABDbrXtNYoBPQ5cDIhZMhTAK0luk5BpNxLSilQeFwghxLBKTBSGmmMpEVMHWgWQpxDfZ0Kwd/2w9CDJiQw/zuJCraz7tB2VXeL93mFX2TvD3zvBw "Ruby – Try It Online")
Inputs and outputs arrays of chars.
The approach is pretty straightforward: we identify the runs of consecutive digits (`chunk` using unary `+` as identity function) and take the maximum - first by the size of the run (reset to zero if its occurrence count is < 2), then by the count itself.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 67 bytes
```
#&@@@MaximalBy[Select[Tally@Split@#,Last@#>1&],{Length@#,#2}&@@#&]&
```
Pure function. Takes a list of digits as input and returns a list of subsequences (in no particular order) as output. Not sure if the "must appear at least twice" clause can be handled more cleanly.
[Try it online!](https://tio.run/##fVJNS8QwEL33VwwbCAoD2o/YrUUJnlcQ1lvpISxZt5AuYnNwKf3tNSQkplW2PNLp65uZN0N6oU@yF7o7iHk@whPcEMo5fxXfXS/Uy6XZSyUPunkXSl34/lN1mhPcicG8nlPa4riT5w99MiTJJpNKaEtv61nLQQ@m3DiWCNslGEKB8BAhQzCyNCYnTMA8Y47gkHr8ZaoQ@6zSFiwj8ZrxytR2X8FpiqVy67u4OkUUuxmdNxNkPoXZYZn9xSIzeeCXNnJ7BrKyXQo7oDur5Wcgf5nI7WrnKyasmv0bR8YcwnKuMPE49x5ZiKepTpK3r@6sG4KweYQNwrEhbQsU7jjYO1PPPw "Wolfram Language (Mathematica) – Try It Online")
[Answer]
## PCRE, 152 bytes
```
(\d)(?<!(?=\1)..)(?=(\1*)(?!\1).*(?!\1).\1\2(?!\1))(?!(?:(?=\2((\3?+)(\d)(\5*)))){1,592}?(?=\2\3.*(?!\5).\5\6(?!\5))(?:\1(?=\1*\4\5(\7?+\5)))*+(?!\1))\2
```
See it in action on: <https://regex101.com/r/0U0dEp/1> (just look at the first match in each test case)
This is just for fun, since regex isn't a real programming language in and of itself, and the solution is limited :P
Because a zero-width group such as `(?:)+` only matches once and doesn't repeat indefinitely, and because PCRE internally makes copies of groups quantified with limits, I've had to use a magic number in there ("{1,592}"), which means we can only look up to 592 contiguous sets of digits ahead to find a competing set that could be longer than the one currently under inspection. More info on this concept [here](http://www.drregex.com/2017/11/lookahead-quantification-utterly-loopy.html).
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `o`, 68 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 8.5 bytes
```
Ġ:UÞ⊍⁽LO∆M
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJvQT0iLCIiLCLEoDpVw57iio3igb1MT+KIhk0iLCIiLCI1NTUxNTMzMzM1NTFcbjc4ODg4ODU0NjY2NjI3MTY2NjZcbjg4ODg4NTg4ODg4NjY2NTY2NjU2NjZcbjMzMzExMTMzMzExMTkxMTEiXQ==)
groups by identical adjacent digits, finds the duplicated elements, then takes the most common of the longest runs.
[Answer]
# [Perl 5](https://www.perl.org/), 88 bytes
```
my($m,%s);++$i%2*$s{$_}++&&($n=$s{$_}/9+length)>$m&&($a=$_,$m=$n)for pop=~/((.)\2*)/g;$a
```
[Try it online!](https://tio.run/##bZDfb5swEMff@StOyLQ40DLzo0AZbSrtpS/ry97GhNLWobQBvOBIq0L2r6dnpyXplrN8J999fPfVCb5cRNt@dQ/z9bZ5tUnjWj3NHIfUlj8h/ZqUG8c5ObFJm@9eXuoseFvJJ3pFGlWY5aR0SZOTls67JYhO5H892z6nhT@hXpWR2XZjNK8wlbyXeTMTPz27eHTo@eRax2JQEdFfbi8WtfSK1nOfu7o1Tffrt5sfN1eZgY1t/Z@uDQCls3annObVkgucPiVlpvNAqnyORaqeYlm3cg6mdXbRA4B15ocq8j@CP0j@iAn2RSWqToLVF63p4icAWzXFRsB/A/YGnAPXYN69mHAJ5neEuxfTBVQASqV9OpwqLZipMmNjGGWpRJelcduKlbwEiBNlUXiB5sdMBTUH7lZSAyoxwkEQMMZ2PsUL7/YBY2rfOI4R3Hk4sA8WKwOWRp752oIgPM4foAljcRzijRMWJP5/aDKSURSxCKcEGI81ZQfjA/8T8i85@CObhmEapmmoj46f2XCvVC9Xe9xj9H4PlCrba2BqCaM/tt4BS8b2DQ "Perl 5 – Try It Online")
Slightly ungolfed, with tests:
```
sub f {
my($m,%s);
my($i,$n,$a); #not needed in golfed version
++$i % 2 * $s{$_}++
&& ($n=$s{$_}/9+length) > $m
&& ($a=$_, $m=$n)
for pop=~/((.)\2*)/g; #i.e. 7888885466662716666 => 7 88888 5 4 6666 2 7 1 6666
$a
}
for(map[/\d+/g],split/\n/,join"",<DATA>){ #tests
my($i,@e)=@$_;
printf "%-6s input %-24s expected %-10s got %s\n",
(grep f($i) eq $_, @e) ? "Ok" : "Not ok", $i, join('|',@e), f($i);
}
__DATA__
Input: 7888885466662716666 Output: 6666
Input: 3331113331119111 Output: 111
Input: 777333777333 Output: 777|333
Input: 122222233433 Output: 33
Input: 811774177781382 Output: 8
Input: 555153333551 Output: 1
Input: 12321 Output: 1|2
Input: 944949949494999494 Output: 4
Input: 8888858888866656665666 Output: 88888
Input: 1112221112221111 Output: 111|222
```
[Answer]
# Japt `-h`, 12 bytes
Input & output are strings.
```
ò¦ ñÊf@ÓZè¶X
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=8qYg8cpmQNNa6LZY&input=IjkxMTEzMzExMTMzOTMzOTMzOTMzOTMzOSIKLWg=)
]
|
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 3 years ago.
[Improve this question](/posts/2276/edit)
Write a program that prints out the syntax error message of the compiler or interpreter. The error message should be misleading so that code maintainers will take days to find out that the error was faked, that means, you should obfuscate (and hide your intention). Also, the error must be as exact as possible, and should reference to the code correctly.
For complied languages, assume your code maintainer will do `compile program.p && ./program` on the command line to compile AND run the program, that means, he cannot distinguish if the output comes from the compiler or the program itself.
Also, assume your code maintainer will turn on syntax error messages.
For reference, here is an example I made: <https://gist.github.com/359604>
The `DATA` section encodes the string of error message, and the hash `%abcdef` is the decode table. The error printed references to the backslashes, which makes a code maintainer will try to count the backslashes.
Entries will be graded by:
* Code has an deceptively obvious intention `/6`
* Code reproduces error correctly `/16`
(your point starts with 16, and divide by the corresponding factors for each inaccuracies)
+ Correct capitalization: 4
+ Correct line number and column number: 4
+ Correct wording: 2 for each incorrect words
* The line number referenced misleads the code maintainer `/3`
For example,
```
./pythontest1.py: line 7: syntax error near token `('
./pythontest1.py: line 7: ` x=input("Enter a number:") #Number input'
```
gets 8 (16 / 2) on correctness for missing "unexpected" before "token", a normal Python interpreter displays
```
./pythontest1.py: line 7: syntax error near unexpected token `('
./pythontest1.py: line 7: ` x=input("Enter a number:") #Number input'
```
If your "code reproduces error correctly" point is under 1, your entry disqualifies.
In case of a tie, I will put up additional grading factors.
[Answer]
## Python
```
import sys,traceback
try:
f=open(sys.argv[0])
print eval(f.readline())
except Exception, e:
traceback.print_exc(0)
```
This is a program that should take a filename on the command line, evaluate the first line in it, and print the result. It has 2 bugs. The major bug is that it should use `sys.argv[1]`, not `sys.argv[0]`, so it ends up evaluating the program itself, not the contents of the file named by the first argument. The second bug is that the argument to `print_exc` makes it print only the deepest frame on the stack, hiding the fact that the error took place inside the `eval`. As a result, you get an error like this:
```
$ python fake_error.py twelve
Traceback (most recent call last):
File "<string>", line 1
import sys,traceback
^
SyntaxError: invalid syntax
```
This looks very much like the first line of the program has a syntax error. It's not quite right as the file is `<string>`, not `fake_error.py`, but otherwise it is indistinguishable from the case where, for example, you spell `import` wrong.
Both errors are somewhat "underhanded" in that they could be accidental.
[Answer]
Reminds me a practical joke.
```
$ ls -l
$ cat readme.txt
cat: readme.txt: No such file or directory
$ echo 'cat: readme.txt: No such file or directory' >readme.txt
$ ls -l
total 8
-rw-r--r-- 1 florian staff 43 Mar 16 09:52 readme.txt
$ cat readme.txt
cat: readme.txt: No such file or directory
$
```
[Answer]
## BrainF\*\*\*
```
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>++++++++++[<+++++++++++<++++++++++<++++++++++<+++++++++++<+++++++++++<+++<+++++++++<+++<++++++++++<+++++++++++<++++++++++<+++++++++++<++++++++++<+++++++++++<+++++++++++<+++<+++++++++++<+++++++++<+++<++++++++++<+++++++++++<+++++++++++<++++++++++<++++++++++<+++++++++<+++<++++++++++<++++++++++<+++++++++++<+++++++++<++++++++++<+++++++++++<+++++++++++<+++++++++<+++<+++++++++++<++++++++++<++++++++++<+++++++++++<+++++++++++<+++<+++++++++<+++<++++++++++<+++++++++++<++++++++++<+++++++++++<+++++++++++<++++++++++<+++++++++<+++<+++++<+++++++++++<+++++++++++<+++++++++++<+++++++++++<++++++++++<+++<++++++++++++<+++++++++<+++++++++++<+++++++++++<++++++++++++<++++++++<+++<+++<++++<++++<++++<+++++++>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>-]<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<.>++.>++.>++.>+++.>++.>+++.>+.>.>++++++.>+++++++.>.>++.>+.>++++.>++++.>+.>++++.>++++++++.>++.>+++++++++.>++++++++.>+.>+++++.>+++++.>.>+++.>++.>+++.>++.>++++++.>+.>+++++++.>+.>.>++.>+++++++.>++.>++.>+.>+++++++.>++++.>+.>.>++.>++++++++.>+.>++.>+.>++++.>+.>++.>+++++++.>.>++.>+.>++.>+.>.>+++++.>.>+++.>++.>+.>++.>++++++.>+.>+++++++.>+.>.>
```
I can't find the particular compiler I used before, but I assure you that that is the exact error message.
[Answer]
**Java**
```
throw new Error();
```
I didn't know if you meant actually throwing an unhandled exception (as in that example), or simulating an error message. If that is the case, this should work:
**C**
```
printf("FATAL ERROR #0xBAD\nProgram execution stopped\n\nIn line 123, character 321, of file 'buggy.c'");
```
(this assumes that `stdio.h` is #included)
[Answer]
## Game Maker Language
```
show_error("Error: Undefined variable a##Line 1, character 4, of event Create in obj_controller",0)
```
[Answer]
# **ACTIONSCRIPT 3**
```
trace("TypeError: Error #1009: Cannot access a property or method of a null object reference.");
```
]
|
[Question]
[
The **[Fibonacci polynomials](https://en.wikipedia.org/wiki/Fibonacci_polynomials)** are a polynomial sequence defined as:
* \$F\_0(x) = 0\$
* \$F\_1(x) = 1\$
* \$F\_n(x) = x F\_{n-1}(x) + F\_{n-2}(x)\$
The first few Fibonacci polynomials are:
* \$F\_0(x) = 0\$
* \$F\_1(x) = 1\$
* \$F\_2(x) = x\$
* \$F\_3(x) = x^2 + 1\$
* \$F\_4(x) = x^3 + 2x\$
* \$F\_5(x) = x^4 + 3x^2 + 1\$
When you evaluate the Fibonacci polynomials for \$x=1\$, you get the Fibonacci numbers.
## Task
Your task is to calculate the Fibonacci polynomial \$F\_n(x)\$.
The usual [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") rules apply. So you may:
* Output all the Fibonacci polynomials.
* Take an input \$n\$ and output the \$n\$-th Fibonacci polynomial.
* Take an input \$n\$ and output the first \$n\$ Fibonacci polynomial.
You may use \$0\$-indexing or \$1\$-indexing.
You may output the polynomials in any reasonable format. Here are some example formats:
* a list of coefficients, in descending order, e.g. \$x^9+8x^7+21x^5+20x^3+5x\$ is represented as `[1,0,8,0,21,0,20,0,5,0]`;
* a list of coefficients, in ascending order, e.g. \$x^9+8x^7+21x^5+20x^3+5x\$ is represented as `[0,5,0,20,0,21,0,8,0,1]`;
* a function that takes an input \$n\$ and gives the coefficient of \$x^n\$;
* a built-in polynomial object.
You may pad the coefficient lists with \$0\$s. For example, the polynomial \$0\$ can represented as `[]`, `[0]` or even `[0,0]`.
You may also take two integers \$n, k\$, and output the coefficient of \$x^k\$ in \$n\$-th Fibonacci polynomial. You may assume that \$k<n\$.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
## Testcases
Here I output lists of coefficients in descending order.
```
0 -> []
1 -> [1]
2 -> [1, 0]
3 -> [1, 0, 1]
4 -> [1, 0, 2, 0]
5 -> [1, 0, 3, 0, 1]
6 -> [1, 0, 4, 0, 3, 0]
7 -> [1, 0, 5, 0, 6, 0, 1]
8 -> [1, 0, 6, 0, 10, 0, 4, 0]
9 -> [1, 0, 7, 0, 15, 0, 10, 0, 1]
10 -> [1, 0, 8, 0, 21, 0, 20, 0, 5, 0]
11 -> [1, 0, 9, 0, 28, 0, 35, 0, 15, 0, 1]
12 -> [1, 0, 10, 0, 36, 0, 56, 0, 35, 0, 6, 0]
13 -> [1, 0, 11, 0, 45, 0, 84, 0, 70, 0, 21, 0, 1]
14 -> [1, 0, 12, 0, 55, 0, 120, 0, 126, 0, 56, 0, 7, 0]
15 -> [1, 0, 13, 0, 66, 0, 165, 0, 210, 0, 126, 0, 28, 0, 1]
```
[Answer]
# [J](https://www.jsoftware.com), ~~13~~ 11 bytes
```
$1j1#]!&i.-
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8EOAwUNA0UrQwMDTQX1NAVbK3UdBQMFKwWDpaUlaboWq1UMswyVYxXVMvV0ISI3rcBCmXqKNXoOmXpcYJ4GkKMJ59lYacQq6moCuZpcqckZ-Q5panYKmXqGZhATFiyA0AA)
-2 bytes thanks to @ovs
Looking at the nonzero columns, some keen eyes may have noticed that the columns look like binomial coefficients. And it actually is. (A related fact: summing the coefficients of nth polynomial gives nth Fibonacci number, which [you can prove nicely in Lean](https://codegolf.stackexchange.com/q/236132/78410))

...though we also need to handle the zero columns.
```
$1j1#]!&i.- A train that takes n, and gives a vector of descending coeffs
] - n and -n respectively
&i. Apply range to both sides; 0..n-1 and n-1..0
! (right)C(left)
$1j1# Insert a zero after each number and take first n numbers
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
Ż+¥¡1
```
[Try it online!](https://tio.run/##y0rNyan8///obu1DSw8tNPz/39AUAA "Jelly – Try It Online")
Full program taking \$n\$ from STDIN and outputting coefficients ascending.
It's always felt a bit silly that the only "repeat" quick is designed for Fibonacci-like recurrences, but when it comes up I can't say it isn't useful.
```
Since this is invoked as niladic, the initial left argument is 0.
1 Starting with 1 on the right,
¡ repeat n times
¥ with the previous left argument replacing the right argument:
+ vectorized add the right argument to
Ż the left argument with a prepended 0.
```
[Answer]
# [R](https://www.r-project.org), 33 bytes
```
\(n,k,s=n+k)choose(s/2-.5,k)*s%%2
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY49CgIxEEZ7b2GxMNFZzS-IkJvYyOIgRLKL0cJTeACbKHgob2M2k-oN733FvN7X_CH_vd-o3_2WB4gYMPm4DmI4j2M6QdrqfuMwiFXqOt2GTwKJUiwI1IwBCHQ5cIYSLAwLU0SFbt6yt-xt8RWmZcfZcXacXckVtqzScZouD5B7ZZEweuUEv5Uz8w8)
Takes input as \$n,k\$ and outputs the coefficient of \$x^k\$ in \$n\$-th Fibonacci polynomial. Uses the formula from [Wikipedia](https://en.wikipedia.org/wiki/Fibonacci_polynomials#Combinatorial_interpretation):
\$F(n,k) = {\frac{n+k-1}{2}\choose k}\$ if \$n\$ and \$k\$ have opposite parity.
[Answer]
# [Factor](https://factorcode.org/) + `math.polynomials`, 45 bytes
```
{ } .s { 1 } [ dup . tuck "\0"p* p+ t ] loop
```
[Try it online!](https://tio.run/##DcaxCoMwEAZgfJMfxxaCXdsHKF1cxMl2CDZB8cwdyWUI0meP/abP21k51nF49c87NheDI0h0qkXiGhRpyd6Tw251McJUAu@rpYRHPfCDSThw@2fCNwsMNM8b2nfXtHKBXKH4gJil1hM "Factor – Try It Online")
Prints the sequence forever as ascending coefficients.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 14 bytes
```
#~Fibonacci~x&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X7nOLTMpPy8xOTmzrkLtf0BRZl5JtLKuXZqDcqxaXXByYl5dUGJeemq0gY6haex/AA "Wolfram Language (Mathematica) – Try It Online")
Returns a polynomial in \$x\$.
If \$n,x\$ were valid input, `Fibonacci` alone would do.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 37 bytes
```
f=(n,k)=>n>1?f(n-1,k-1)+f(n-2,k):!k*n
```
[Try it online!](https://tio.run/##FcnRCsIgFIDh@z3F6e6cppJdtjR6joiQpeE0HW4MInp2267@D/7BLGbqix9nnvLT1uoUJhZI6aTlxWHikgUuqd14XMdpF/apulwAo53Bg4JDt@YMcmvbEnwbgD6nKUcrYn7hTQhxLcV80NNdvM2I@GAwECgNDv1GEsUutkwWibrmV/8 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python](https://www.python.org), 62 bytes (@AnttiP)
```
f=lambda n:n>1and[*map(sum,zip(f(n-1)+[0]),[0,0]+f(n-2))]or[n]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY37dJscxJzk1ISFfKs8uwME_NSorVyEws0iktzdaoyCzTSNPJ0DTW1ow1iNXWiDXQMYrVBIkaamrH5RdF5sRBT9qXlFylkKmTmKRQl5qWnahgaaFoVFGXmlQC1Z2pqQhTBrAQA)
### Old [Python](https://www.python.org), 64 bytes
```
f=lambda n:n>1and[*map(sum,zip(f(n-1)+[0]),[0,0]+f(n-2))]or[1]*n
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3HdJscxJzk1ISFfKs8uwME_NSorVyEws0iktzdaoyCzTSNPJ0DTW1ow1iNXWiDXQMYrVBIkaamrH5RdGGsVp5EHP2peUXKWQqZOYpFCXmpadqGBpoWhUUZeaVAA3I1NSEKIJZCgA)
Naive implementation of the defining recurrence.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
```
ʁḂ$ƈ0ZfẎ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLKgeG4giTGiDBaZuG6jiIsIiIsIjkiXQ==)
Same idea as Bubbler's J answer.
```
ʁḂ$ƈ0ZfẎ
ʁ # Exclusive zero range, 0..n-1
Ḃ # Bifurcate, push reverse without popping
$ # Swap
ƈ # Binomial coefficients
0Zf # Append zero after each
Ẏ # Only keep the first input items
```
Porting pajonk's Python answer is 8 bytes as well:
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
```
+₌∷½⌊⁰ƈ*
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIr4oKM4oi3wr3ijIrigbDGiCoiLCIiLCI1XG4yIl0=)
[Answer]
# [Python 2](https://docs.python.org/2/), 43 bytes
```
lambda n,k:2**(n*(n-~k))/(4**n-1)**-~k%2**n
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFPJ9vKSEtLIw@IdOuyNTX1NUy0tPJ0DTW1tIB8VaBc3v@0/CKFPIXMPIWixLz0VA1DM00rLgUgKCjKzCvRiAYRaRpAkzQ1FUBKsxFK8zRjNf8DAA "Python 2 – Try It Online")
Uses an [arithmetic expression for the binomial](https://codegolf.stackexchange.com/a/169115/20260) adapted to \$ \binom{\frac{n+k-1}2}{k}\$ in a way that gives 0 if the top isn't a whole number.
## [Python 2](https://docs.python.org/2/), 48 bytes
```
f=lambda n,k:n>0and(k*k+n<2)+f(n-1,k-1)+f(n-2,k)
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhsDxDmJuUkpiQp5OtlWeXYGiXkpGtla2dp5Nkaa2mkaebqGOtm6hhCmkU625v@0/CKFPIXMPIWixLz0VA1DM00rLgUgKCjKzCvRiAaqA6pSAKnKRqjK04zV/A8A "Python 2 – Try It Online")
A recursive expression [taken from tsh](https://codegolf.stackexchange.com/a/249118/20260) for Pascal's triangle but tilted.
[Answer]
# Python3, 139 bytes:
```
def f(n):d={};F(n,d);return[d.get(i,0)for i in range(n-1,-1,-1)]
def F(n,d,c=0):
if n==1:d[c]=d.get(c,0)+1
if n>1:F(n-1,d,c+1);F(n-2,d,c)
```
[Try it online!](https://tio.run/##VVLLboMwEDzXX7HKJVhxIhvCI0TOscf@QOoDCSa1lDrI0EpV1W@nBjvISAjsndmZ3WXbn/7joZOiNcNQywaaSOOy5r9/x9dIkxofjey/jD7Xu5vsI0Uobh4GFCgNptI3GektI9ODBRoFpjRy5RSXCFQDmnNW1uer4E7iaiU2zEEnVr5OAjZhw/BouY3HCx46vlqtKGxPcBaITV8mUOwOBKhAyXwmYKF9cI0nQhpEkictC4L7GRIoD@Lp9M6eKUUA@SCd8wU6BHDu4DRkWQVGA07hSvSV0tnR0lhAOzjcsZN0IWypcdi9E0lccWkWpmROeTEs370jFG4KOQ3LGh3CgbLYSXt/XzWLF465swrHztzcMz@2LPUmy3zfJBP2l6N5vRp176WJ3h5aEuh2XXtXfbR@12tsN@ulInABDp9VG8nv6k5APRmjveVYStdJ09uNrjBwDhfUGqUtoZdd30E7wvUaD/8)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 32 bytes
```
NθF⊕θ⊞υ⎇‹ι²ιΣE…⮌υ²×κ∨λXχθI↨⊟υXχθ
```
[Try it online!](https://tio.run/##XY3NCsIwEITvPsUeNxBBBU@92VPBn6B9gVhXWsxP3SSVPn2MenMuA8M3M12vufPa5Ny4McVjsldifIpqcfcM2LiOyZKLdCuhAJVCj0lCS@w0z7inEHCQsBESil2SxYMesZ47Q3XvRzzTRBwIk/hB7WAp4EPCidFIUP5V7tYrCWX9q2qheHARax0i7nSpqjLzqf@xVc7bvJzMGw "Charcoal – Try It Online") Link is to verbose version of code. Takes `n` as input and outputs the list of coefficients in descending order. Explanation:
```
Nθ
```
Input `n`.
```
F⊕θ
```
Repeat `n+1` times.
```
⊞υ⎇‹ι²ιΣE…⮌υ²×κ∨λXχθ
```
Except for the first two numbers (which are just `0` and `1`) multiply the last number by a very large base (`10ⁿ`) and add on the penultimate number.
```
I↨⊟υXχθ
```
Interpret the last value as a number in that very large base and output the "digits".
[Answer]
# [Python](https://www.python.org), ~~58~~ ~~52~~ 50 bytes
*Edit: -8 bytes thanks to [301\_Moved\_Permanently](https://codegolf.stackexchange.com/users/45032/301-moved-permanently).*
```
lambda n,k:(n+k)%2*math.comb(n+k>>1,k)
import math
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PY1NCsIwEEb3OcVshESr0C5ECvYiKpLaxIaYSUmngmdxUxC9k7cx_cHZDLw33zfPT_Og2mP_0vvjuyO93n2zm3RlJQETm3NcWbHIlk5Svbl4Vw6gKNLECmZc4wPBoOakqZQGUi2dNUeRM4gTFHUB4RBJDIH2ASwYjPyuQqsqHiReVTwXJ8bYoHHUI023c0sTDBL_V4vpYd9P-wc)
Port of [my R answer](https://codegolf.stackexchange.com/a/249126/55372).
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 22 bytes
```
{(0 0,x)+y,0}\[;!0;,1]
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6rWMFAw0KnQ1K7UMaiNibZWNLDWMYzl4kpTMDQBAHjCB0U=)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~8~~ 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
λ0š0ζO
```
Outputs the infinite 1-based sequence. The inner coefficient-lists are output in ascending order for -2 bytes.
[Try it online.](https://tio.run/##yy9OTMpM/f//3G6DowsNzm3z//8fAA)
Since I was curious, a port of [*@Bubbler*'s J answer](https://codegolf.stackexchange.com/a/249123/52210) would be **9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)**:
```
ݨÂc€¾RI£
```
Outputs the 0-based \$n^{th}\$ list, in descending order.
[Try it online](https://tio.run/##ARsA5P9vc2FiaWX//8OdwqjDgmPigqzCvlJJwqP//zU) or [verify all test cases](https://tio.run/##ASoA1f9vc2FiaWX/MTXGkk4/IiDihpIgIj9O/8OdwqjDgmPigqzCvlJOwqP/LP8).
**Explanation:**
```
λ # Create a recursive environment,
# to result in the infinite sequence
# Implicitly starting at a(0)=1
# Where every following a(n) is calculated as:
# (implicitly push the a(n-2)'th and a(n-1)'th terms
# (where a(-1)=0 in the first iteration)
0š # Prepend a 0 in front of the top a(n-1)'th term
# (which implicitly converts integers to digit-lists first)
ζ # Pair and zip/transpose the two lists,
0 # with 0 as filler since the lists are of unequal lengths
O # Sum each inner pair
# (after which the infinite sequence is output implicitly)
Ý # Push a list in the range [0, (implicit) input]
¨ # Remove the last item to make the range [0,input)
 # Bifurcate; short for Duplicate & Reverse copy
c # Calculate the binomial coefficient of the values in the two lists at
# the same positions
€¾ # Prepend a 0 in front of each item
R # Reverse this list
I£ # Keep just the first input amount of items
# (after which this list is output implicitly as result)
```
[Answer]
# [Desmos](https://desmos.com/calculator), ~~62~~ 41 bytes
```
L=[n...0]
f(n)=mod(L+n,2)nCr((n+L-1)/2,L)
```
Function `f` outputs a list of coefficients in descending order, with a leading zero.
[Try It On Desmos!](https://www.desmos.com/calculator/ezomtx88j9)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/f6mpauaybh)
[Answer]
# [APL (Dyalog Unicode)](https://dyalog.com), 22 bytes [SBCS](https://github.com/abrudz/SBCS)
```
{a←¯1+⍳⍵⋄⍵↑,⍉↑(a!⌽a)0}
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q0581Dbh0HpD7Ue9mx/1bn3U3QIi2ybqPOrtBFIaiYqPevYmahrUAgA&f=S1OwBAA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f)
]
|
[Question]
[
Let \$ A \$ represent the alphabet, such that \$ A\_1 = \$ `a` and \$ A\_{26} = \$ `z`.
Let's define that a word \$ W = w\_1 w\_2 ... w\_n \$ (where \$ w\_c \in A\$) is in **standard order** if and only if:
* \$ w\_1 = A\_1 \$, and
* for \$ 2 \le i \le n \$, if \$ w\_i = A\_x \$ then \$ w\_j = A\_{x-1} \$ for some \$ j < i \$ and some \$x\$.
In other words, the word must start with `a` and each other letter can only appear in a word if the preceding letter in the alphabet has already appeared. Equivalently, if we take only the first appearance of each unique letter in the word, the resulting word is a prefix of the alphabet.
For example, `ac` is not in standard order, because there is no `b` before the `c`.
The following relationships exist between the property of standard order and some others (this list is mainly here for searchability):
* A word is a valid [rhyme scheme](https://en.wikipedia.org/wiki/Rhyme_scheme) if and only if it is in standard order ([related challenge](https://codegolf.stackexchange.com/q/70953))
* A word in standard order is the lexicographically earliest among all its [isomorphs](https://codegolf.stackexchange.com/q/50472)
* The number of words of length \$ n \$ which are in standard order is the \$ n \$th [Bell number](https://en.wikipedia.org/wiki/Bell_number) ([related challenge](https://codegolf.stackexchange.com/q/132379))
## Task
Given a string of letters, determine if it is in standard order according to the Latin alphabet.
## Test cases
Truthy:
```
a
aaa
abab
aabcc
abacabadabacaba
abcdefghijklmnopqrstuvwxyzh
```
Falsey:
```
b
ac
bac
abbdc
bcdefghijklmnopqrstuvwxyza
abracadabra
```
## Rules
* You should represent true and false outputs using any two distinct values of your choice
* You may assume the input is non-empty and only contains lowercase ASCII letters
* Alternatively, you may accept input as a list of integers representing alphabet indices (in either \$ [0, 25] \$ or \$ [1, 26] \$, at your option)
* You may use any [standard I/O method](https://codegolf.meta.stackexchange.com/q/2447)
* [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061) are forbidden
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 27 bytes
```
a=>a.every(n=>a[-n]=a[1-n])
```
[Try it online!](https://tio.run/##dY9NCsIwEIX3PUXIKoE24EaQUkHEU5QuJpO0VWtS01j/8Ow1Td26mHnzhvkezAlGGNAde58Zq/RUFxMUWxB61O7JTBjLzFQFlKsgfMrLhAJNKUDsEmQ0EnGxGEr9NG5Q6bppj6dzdzG2v7rB38b74/lqaZrQCM@khIWXKrp/0BLpQrqahVaitu4A2DJPii15J4SgNYPttOhsw2pWCiF8JS7QM5wvUGALbh8e3XnGSUY2a855nnx4Pn0B "JavaScript (Node.js) – Try It Online")
Input as an array of 1~26 integers.
[Answer]
# x86 32-bit machine code, 13 bytes
```
b0 61 38 02 7f 05 1c ff 42 e2 f7 d6 c3
```
[Try it online!](https://tio.run/##dVHLTsMwEDx7v2JlVMlBacVLPbSUC6gfwLWgynbsJMVxgu2Wlqq/TnBIhOiBw3q1szsza1s2zTiXsm25r5DhM2UwyU0tuEENekaqeofcpHi1n16DmxFZNbhS2f41jTCQTY4CiBdiGFougZRWYpwAYuq6QQdiRibiEFRsP02BOBUgoZjMQe2DchbpI8Xjes1DcKXYBrVeM6a5D5IbkyQoC@5Qs9IGtCnK2vrQY5c@mZ8ALqKf2WYK733IynpSPJxBrrR5h3X8ipeWJXAE8lcmqM7LK796xQUeKacpUs77JLjoSyHlAMgY2ZB7SGZK50W5eTOVrZt358N297E/fBZdu@f/kAUfNETW1/8RB10XPbIu0dMciK4dsrPFcYa/yydASBMvGzSjo/FdOfIvNqpoFp/AKMtCkmIfczi17ZfUhue@HVe3N/GIv7@IXGW@AQ)
Following the `fastcall` calling convention, this takes the length of the string in ECX and the address of the string in EDX, and returns in AL, -1 for standard order and 0 for not standard order.
Assembly:
```
f: mov al, 0x61 # 'a' -- AL will hold the highest acceptable letter.
r: cmp [edx], al # Compare -- Letting c be the current letter, calculate c - AL.
jg b # If c > AL, the word is not in standard order; jump out.
sbb al, 0xFF # Here, the carry flag CF is 1 if c < AL and 0 if c = AL.
# Subtract 255+CF from AL. This leaves AL unchanged if c < AL
# while increasing it by 1 if c = AL.
inc edx # Advance the pointer.
loop r # Loop, counting down from the length in ECX.
b: .byte 0xD6 # Undocumented SALC instruction -- sets AL to -CF.
# If the word is not in standard order, CF = 0 from the CMP.
# If it is in standard order, CF = 1 from the SBB,
# as INC and LOOP leave CF unchanged.
ret # Return.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 3 bytes
```
QJƑ
```
[Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCJRSsaRIiwi4bu0T185NsOH4oKsIiwiIixbImFcbmFhYVxuYWJhYlxuYWFiY2NcbmFiYWNhYmFkYWJhY2FiYVxuYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpoXG5iXG5hY1xuYmFjXG5hYmJkY1xuYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5emFcbmFicmFjYWRhYnJhIl1d)
Takes input as one-indexed alphabet indices.
```
QJƑ Main Link
Q Uniquify
JƑ Is it equal to [1, 2, 3, ..., len]?
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes
```
U:ż⁼
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJVOsW84oG8IiwiIiwiWzEsIDIsIDEsIDMsIDEsIDMsIDQsIDVdIl0=)
Takes a list of nonnegative integers.
```
U # Uniquify
⁼ # Is equal to
:ż # 1...length?
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~39~~ 32 bytes
*Thanks @xnor for saving 2 bytes by proposing this approach (going from right to lefft)*
*Thanks @loopy walt for golfing a further 3 bytes*
```
def f(L):len({*L})>L.pop()!=f(L)
```
[Try it online!](https://tio.run/##dY8xc8IwDIV3/woxYXPXLGy5g5EpI1uvg2M7jcHYruy0BI7fnkq0S4cOOj09fXo@57mOKW6XxboBBtmpNrgo75vuofZdk1OWarVjf/GXnLBCmYsQQ0IIPjrwkY2mVOtjKwA62MFrQiuNghdgsdZrBcwbhvmIaPSU@0Z8xZnP4Pn0U6ArU6gUc9ChOLLc1bhc27/LI068y@hjlT@uWrTQmqrXPYneGJaGyv52mg198330p3O4xJQ/sNTp8@s630ZBN0YQR1BvSf1HcgpSnOX2DQ "Python 3 – Try It Online")
Takes in a list of integers from 0 to 25. Throws exception if the numbers are in standard order, otherwise terminates without exception (aka returns through exit code).
Check if the last element is less than the number of unique elements in the list:
* If true, recurs on the remaining list (after the last element has been removed). If the list is in order, then we'll eventually run out of elements after some recursions, throwing an exception on `L.pop()`.
* If false, then that last element must not be in order, in which case the comparison short circuited and the function terminates.
[Answer]
# [JavaScript (V8)](https://v8.dev/), 35 bytes
```
a=>[...new Set(a)].some((x,i)=>x^i)
```
[Try it online!](https://tio.run/##dU7LDsIgELzzFd4KieWqxrSJ8RM8ak23QC21DwRs0Z/HrfHqJpOZ3cxOpoUJnLDa@HTaxjqLkOVnzvmg5tVJeQqs4G7sFaVhrVmWh6tmcU9KIACICioUlRCLFAj5Y9yFVPWt0e2964fRPKzzz2kOr3dD8EcQ9KGpkqj@OZcUi3FyoZI702lPk8uQMN6DoS7LjdWDpzVdKrview1YkosG7HGU6uApS3cbhkPiBw "JavaScript (V8) – Try It Online")
takes input as an array with integers representing 0-indexed alphabet indices. returns false for valid words, and true for invalid words
[Answer]
# JavaScript (ES6), 30 bytes
Expects a list of 0-based indices. Returns *false* for valid or *true* for invalid.
```
a=>a.some(c=>c*!a[a[-c-2]=~c])
```
[Try it online!](https://tio.run/##dZDLCsIwEEX3/YrYhaRis3AjIimI@BWli8mkD2vb1KQ@F/56jNp058DMHQ7DvTA1XMGgPvZD3CmZ24Jb4Akwo9qcIk9wMYMU0hjjVcZfmEV2mwaEhBAuvwJ@ESA8EogTRNdyVA9R5kVZHetT03aqP2szXK63@@NZ/Q5@07uNVgImTyE9@2c0JWmXKz8SBlnACqUPgBU1hCcEVWdUk7NGlQ7M56SgKWPMZKyFnuL3hGEFeu/eshtoRGKyWUeu7Bs "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // a[] = input array, re-used as an object to keep track of
// characters that have already appeared in the list
a.some(c => // for each code c in a[]:
c * // return true if c is not equal to 0
!a[ // and the following entry is defined:
a[-c - 2] = // set a[-c - 2] to a non-zero value
~c // use -c - 1 as the lookup value
] // end of test
) // end of some()
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 26 bytes
```
(l=#)&@@@Tally@#==Range@l&
```
[Try it online!](https://tio.run/##dY4xDsIwDEX3XiOogoEjFFliQkIIUTbE4LhpG0hDSF2gDL16cQUrw5e/7ecvN8i1aZAt4Vhm49xlapECwBGd60Fl2QF9ZcCl4z5azye1XJWwNcwm7rpGmwjqnA45oR/WNUYkWbSQs8BVHpxlmOUUbeCNDx1/5yMmiCKNWowmmiyJil@VngpTVrW9XF3jb@EeW@4ez1f/rhO5oUQ4gXQh7h85pcg/U2jEDw "Wolfram Language (Mathematica) – Try It Online")
Input a list of alphabet indices, 1-indexed.
```
# &@@@Tally@# deduplicate
(l= ) ==Range@l equal to (1...(last unique value))?
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÙāQ
```
Input as a 1-based integer-list.
[Try it online](https://tio.run/##yy9OTMpM/f//8MwjjYH//0cb6hjpGOoY60BoEx0UfiwA) or [verify all test cases](https://tio.run/##pY8xDsIwDEWvUnV@Q@00aTr1DMxRB5AYmBiQkDqycAA2zgMn6UWCaaNKzMiD7W/72T5f9ofTMV@noa7m@6Oqhym/nu/bLpNTkpEkmC1eLdKiKA63qY7Vt/zkpe5M9wQ6Ij3SIEawsnXZgEcC0iER6dEGtRlFHdqiHg3EBfRdt8ALVg27an8v2P6L5fjyiKXj@AE).
If we take the actual lowercase letters as input, it would have been 5 bytes instead:
```
AIÙÅ?
```
[Try it online](https://tio.run/##yy9OTMpM/f/f0fPwzMOt9v//JyYlJgNxCpQGAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkv1/x8rDMw@32v/X@Z/IlZgIxEmJSUBGUnIyiJkMxClQGshPTklNS8/IzMrOyc3LLygsKi4pLSuvqKzK4ALqSeYCqgMqSkoBsnCpBJlSBDQuBUQBAA).
**Explanation:**
```
Ù # Uniquify the (implicit) input-list
ā # Push a list in the range [1,length] (without popping)
Q # Check if both lists are equal
# (after which the result is output implicitly)
A # Push the lowercase alphabet
I # Push the input-string
Ù # Uniquify this input-string
Å? # Check if the lowercase alphabet starts with this uniquified input
# (after which the result is output implicitly)
```
[Answer]
# Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 9 bytes
```
fsw β<nb
```
## Explanation
`nb` takes the string and removes all but the first occurrence of every character. `fsw` takes two lists and determines if the first one starts with the second. `β` is the lowercase alphabet. So all in all this asks if the first occurrence of every character forms a prefix of the alphabet.
You can replace `β` with `nn` for numbers 0 through 25 and `nN` for numbers 1 through 26.
## Reflections
This does well. For once there's not too much to say here.
* An "is this sorted" builtin might be nice but because the string must start with `a` it would require that as a second check and it wouldn't save anything on this challenge.
* I also noticed there is no upper case alphabet builtin, which there should probably be. It doesn't make a difference to this answer though.
[Answer]
# [Factor](https://factorcode.org/), ~~31~~ 30 bytes
```
[ members 26 iota swap head? ]
```
[Try it online!](https://tio.run/##dU45DsJAEOvzCn8ACgoQUFAiGhpEFaWY3R1IgGz2SsIh3h4miJaRLHsk2/KJdGrCcDzs9tsVIqeIKwfLN9G@Zas5wvdwgVN6uFDZhJpSOe14zEWss8z3rwxyBCKBIiVCaT1KLTA/ll8bPp3L6nK91bZxPsTUdv398Sy/BZLTEK8YlRH1zz02Bak0I2Vv5Fgu0E0sCtnmhhw114pl3GyOqkmE2JNDyWQ2KAaxYDp8AA "Factor – Try It Online")
## Explanation
Get the unique elements of the input, preserving order, and check whether that is a prefix of the alphabet(ic indices).
```
! { 0 1 0 1 }
members ! { 0 1 }
26 iota ! { 0 1 } { 0 1 2 ... 25 }
swap ! { 0 1 2 ... 25 } { 0 1 }
head? ! t
```
[Answer]
# [Nibbles](https://nibbles.golf), 5 bytes (9 nibbles)
```
==;`$_,,@
```
## Verbose
```
== # Equals?
; `$ _ # Uniq of input, save it
, , @ # Range from 1 to length of saved value
```
## Variant with alphabet (8 bytes / 15 nibbles)
```
==.;`$@-$'`',,@
```
### Verbose
```
== # Equals?
. # Map
; `$ @ # Uniq of input, save it
- $ '`' # Subtract '`'
, , @ # Range from 1 to length of saved value
```
[Answer]
# [R](https://www.r-project.org/), 35 bytes
```
function(W)any(seq(u<-unique(W))-u)
```
[Try it online!](https://tio.run/##dY@7DsIwDEV3PqNTMmRFIJUPYEdizpOGh0PSGGh/PgTRpZIzWJauj@XjVNyhOASdfQB25hImNtrIsBcIPqKtGRfIi2OY3e4UjpBZJzsu9lu@WYeSjpVUNK60bizoWmbpNKKNdZfBX2/3B4RnTGPG1/szzcOCr3lagLyuZENKGZpvmTTEU33K/Np/XL4 "R – Try It Online")
Takes input as a vector of integers from `1` to `26`. Outputs `FALSE` for truthy and `TRUE` for falsey.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 3 bytes
```
d~⟦
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/3DXQt1HTZ2Pmtofbp1Q/ahtw6Om5kcdy5VKikpT9ZRqQMy0xJxiILv24a7OWqCi/yl1j@Yv@/8/WilRSUcpMRFMJiUmgTlJyckQbjIQp0BpsEhySmpaekZmVnZObl5@QWFRcUlpWXlFZVUGUBasF6QxKRGiPSkFzMOlB2Ii0DsgK4oSlWIB "Brachylog – Try It Online")
Takes 0-indices into the alphabet.
```
d The nub of the input
~⟦ is the range from 0 to something.
```
# [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes
```
d~a₀Ạ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/2obcOjpuZHHcuVSopKU/WUakDMtMScYiC79uGuztqHWyf8T6lLfNTU8HDXgv//o5USlXSUEhPBZFJiEpiTlJwM4SYDcQqUBoskp6SmpWdkZmXn5OblFxQWFZeUlpVXVFZlAGXBekEakxIh2pNSwDxceiAmAn0BsqIoUSkWAA "Brachylog – Try It Online")
Takes a string of lowercase letters.
```
d The nub of the input
~a₀ is a prefix of
Ạ the lowercase alphabet.
```
[Answer]
# [Shue](https://codegolf.stackexchange.com/questions/242897/golf-the-prime-numbers-in-shue), 67 65 bytes
Shue confirmed less verbose than Java ????
Takes input as a list of unary numbers (1-26) separated by ",", with a trailing ",". Returns "LR" for yes, and "FR" for no.
```
=L
=R
L1,=L>,
L,=L
>1=1>
>,1=,>
,,=,
>,R=,R
LR
L11=F
F1=F
F,=F
FR
```
[Try it online!](https://tio.run/##lVVNj9owEL37V1ic7OKmjfYWyfS0nJC2WlW9QFqZZABLiR3ZyW7RLr@djh0@ArtU2xxCZub5eeblOTTbdmPN3V7XjXUtdSCo33riIKUSo6SwdaMrYG45Ymz@S@avi4XknziTw@jbiBNSwop2BnyhGmCaZ4Ti5aBFouVoFCMsYvQ1Pq@sowXVhuoeGS69ihBlSizJsG6xGJ3LB8LxoXCRH1LHuHpLJm9wyf@nMrfaMh/julqttAf6U1Ud3DtnHVuNvivnwVEIYUbXtqXFRjlVtJh8KXZUrcITqsAvuW/p1jeSDsAe3h1h24Jn8yLvea@7/VCn9w@zL/cP0@secYPOmfBDerc0YeXJKoittVGtdR479dCyw7KugstMpU3M6MQ3lW5ZlJ2fXFUFV0XMue862jlNatUWG1bxoeXqZO1s17A7fiVI2PhV0hd2svURmnIu6JvsHZ@nWc757h8qD6YM1O8x74ZqDfCi76jXDv5A0bXACkGHAh5BOG6vbtGP2hn9BBhj/kX3G9S2xOiH6yCGzxs85yE5EC0ipgqHOOUMPP8ekJ1fylF9H9Q/Ii5nR61jNTaaHQb0H10dykosAyCOeFk9ImysK7MGVoFhno9T/hZ57GZuMzsOOMXzcHDU@9DrwcOb8/PM5uPlGDkODFm@u7n6SuyrVzLkJreOmbNrp@rjOTMWHdJUqoAaTOupckAb671e4ltEw6JH8ASUdAkb9aRt53j4RpPClrghfo9Hezkj8pHMUiFnE0Fm@EMmqUwnZCJSKSZECCnw@VEKRAVgKqdkGm8i3B73yIKG/5zmhGjTBDdsfeLbUpvEgSoZT8CEDdEh@I8SPHlyLWbRuKbhpHHatAzLSQk9mO9TkYq/ "Python 3 – Try It Online")
# Explanation
```
=L - Left edge
=R - Right edge
L1,=L>, - Decrement the first element, which is 1, create triangle
L,=L - Remove a 0 without creating a triangle
>1=1> - Triangle passes trough ones
>,1=,> - Triangle decrements the next element
,,=, - Remove zeros since they don't affect the result
>,R=,R - Delete triangle when it reaches the end
LR - Success
L11=F - Failure, the first element is 2 or greater
F1=F - Propagate failure
F,=F - Propagate failure
FR - Failure
```
# Rough pseudocode
```
def is_valid(array):
if array == []:
return True
if array[0] == 0:
return is_valid(array[1:])
elif array[0] == 1:
return is_valid(array[1:]-1)
else:
return False
```
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 3 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
Takes input as a list in \$[0, 25]\$.
```
≡⟜⊐
```
[Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4omh4p+c4oqQCgo+KOKKouKLiMK3Ri3in5wnYScpwqjin6gKImEiCiJhYWEiCiJhYmFiIgoiYWFiY2MiCiJhYmFjYWJhZGFiYWNhYmEiCiJhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5emgiCiJiIgoiYWMiCiJiYWMiCiJhYmJkYyIKImJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXphIgoiYWJyYWNhZGFicmEiCuKfqQ==)
BQN's primitive [*Classify*](https://mlochbaum.github.io/BQN/doc/selfcmp.html#classify) `⊐` basically converts a sequence to "standard order" in non-negative integers. As the input uses the same domain we can simply check if the result of that matches the input.
[Answer]
# [J](http://jsoftware.com/), 9 bytes
```
(-:#\)@~.
```
[Try it online!](https://tio.run/##y/qvpKeermBrpaCuoKNgoGAFxLp6Cs5BPm7/NXStlGM0Her0/mtypdnqKURbKaQrxFuaaRurlVpxpSZn5CukKagnqiOYicicpMQkZKmk5GQUyWQgToHSyBLJKalp6RmZWdk5uXn5BYVFxSWlZeUVlVUZ6lwQVepuiTnFlQgtyLYgWZGUiGJfUgqyHC5LUFxSBHRbCohS/w8A "J – Try It Online")
Input is 1-based indices of the alphabet letters.
* `@~.` Take the unique (preserves order) and...
* `(-:#\)` Check if it equals `1 2 3 ... <length of uniq>`.
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 90 bytes
```
I =INPUT
N I LEN(1) . X :F(O)
O =O X
&LCASE O :F(END)
R I X = :S(R)F(N)
O OUTPUT =1
END
```
[Try it online!](https://tio.run/##FYwxCoAwDADn5BWZpFkEwanQQbSCIIlUha7qKnbw/9S6Hcdx75POdLc5w0RukmXfUArOXkzDVFMEOxplBCWnFBGque9WT/p7LwNjKHkkB3Y1gUcjjAq6b@VErsGS5Hxc5wc "SNOBOL4 (CSNOBOL4) – Try It Online")
Same "check if unique characters are a prefix of the alphabet" algorithm others have posted.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 30 bytes
```
D`.
^
$'¶
T`l`@l`^.+
^@(.*)¶\1
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7w3yVBjyuOS0X90DaukIScBIechDg9ba44Bw09Lc1D22IM//9P5EpMBOKkxCQgIyk5GcRMBuIUKA3kJ6ekpqVnZGZl5@Tm5RcUFhWXlJaVV1RWZXAB9SRzAdUBFSWlAFm4VIJMKQIalwKiAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
D`.
```
Remove duplicate letters.
```
^
$'¶
```
Duplicate the remaining letters.
```
T`l`@l`^.+
```
Shift the letters in the first copy back by 1, e.g. `abcd` becomes `@abc`.
```
^@(.*)¶\1
```
Check that the second copy starts with the tail of the first copy, which is only possible if this is a prefix of the alphabet.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 10 bytes
```
¬⌕βΦθ⁼κ⌕θι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMvv0TDLTMvRSNJR8EtM6cktUijUEfBtbA0MadYIxskBpQDimRqgoH1//@JSYnJQJwCpf/rluUAAA "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for standard order, nothing if not. Explanation:
```
⌕ Index of
θ Input string
Φ Filtered where
κ Current index
⁼ Equals
⌕ First index of
ι Current letter
θ In input string
β In predefined variable lowercase alphabet
¬ Equals zero
Implicitly print
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~66~~ ~~63~~ 62 bytes
```
r;m;f(char*s){for(r=0,m=96;*s;++s)r|=*s-m==1?m=*s,0:*s>m;m=r;}
```
[Try it online!](https://tio.run/##dVHbTsMgGL73Kf6QLOkxdhpNJjIvjE9hd0EpXetGOwFd3eyrW2lhzVwigfzH7/sPsHjNWN9LLHDhsZLKQPnHopGeJEkkyOIeBwqHofLlNwlULAiZPwmjRclDoJYCCyJx11e1BkGr2vPheAXmjEygudLqdQUEjoiiCBClVmQ0s2bGmHMw83InrYvlvFiX1dtmK@pm9y6V/vjct1@Hcghb/AjOqOPIcmv/B3S80tTIB4E6PDY7dM/bHWea57bbeQQXN7m4DsqaWmk3LSs523Dp5k3bl5u0XTybdzfUPbNvT4XNnsEbqld1zlsDS7BTH0FVB94U3qkv/9o5gsmDIQzHbH8ks4s/W77hsx8wJq3wFB8qKhMtPO0TkvwNcBOYlnGJ3EmTUngoRTOVIoiXMMvBqLWZUEegomkJht/wrHyL7a66/ocVW7pWfbz/BQ "C (gcc) – Try It Online")
Inputs a word as a string.
Returns \$0\$ if the word is in standard order or \$1\$ otherwise.
[Answer]
# Java, 68 bytes
```
l->{int[]x={0};return l.stream().distinct().allMatch(i->i==x[0]++);}
```
Takes input as a `List` of alphabet indices.
[Try it online!](https://tio.run/##dVJNb8IwDD2vvyLiQjtE4F7oZadJQ5rEEXFwkxRS0qRLXAZD/HbmFsaopkXKh/0cvadnl7CHcSl3F13VziMrKeYNasOLxgrUzvLnNPoDUq5ucqMFEwZCYAvQlp0iRisgIOXfvZJaAKrZmw44e7WoNspnGSvmFzPOTtrian2Yn6bn1CtsvGWGB/QKqjjhkr5ooqcnGLMAFNtYjzM9nx9W0/VolKTnS9qx3VTcSPdOS1aRlniJXtvNas3Ab0Jyip4mE4a@UdETqoDxAAZJen9DL8oh74G5EH1Y0Ja3u4cIqYrNVpc7U1lXf/iAzf7zcPzadlWdhgJMuIvo8TyS5NCnzGUP/Y@nr8aTQNlebbb16hw9Nqjzqqu9esU6m5bHgKrirkFeUxaNjQMbsQEbZ3SMWMG7L4GLLfhA/amgjkWL0sGGMEx47g5KEiKcMYp6@Ds11/7ylyvgfODo2umIE1o/Gs@Xbw)
[Answer]
# [Python 3](https://python.org) - 47 bytes
Thanks to @pxeger and @m90
```
lambda a:[*range(len(u:={}.fromkeys(a)))]==[*u]
```
Input is a list of integers from `[0,25]`.
All it does is remove duplicates and makes sure that each integer is equal to its position.
Output is inverted, which is allowed.
[Attempt it online!](https://ato.pxeger.com/run?1=fVBLTsQwDBUbFj2FFTbJCMoWjdQtl-h0ke80_SQhTYYpiJOwqYTgTnAaXHW2sLDes_38bPn9K8yp9W75MNXhMydz9_B9P_BRKA58X-8id0dNB-1o3levb6WJfuz1PFHOGGuqqt7lZhv7ubquQ7QuUUNrwoVU2hxb2_XD6Hx4ilPKp-fz_NKS0jqlz7RjYHyEDqwD27Ats5gRQnjBOYbgAomQcqUSQ12w-Me_wBlZoA5FQiH7S7m6RLRTK-DScgqDTZQcHGEN3MBjdjJZ78DnFHICO-FxJx2TVrcgsGC8TzpeithMgFv77R3LsuEv)
## [Python 3.8](https://python.org) - 50 bytes
Thanks to @pxeger for -12 bytes here.
```
lambda a,i=0:any(k^(i:=i+1)for k in{}.fromkeys(a))
```
Input is a list of integers from `[1,26]`.
All it does is remove duplicates and makes sure that each integer is equal to its position.
Output is inverted, which is allowed.
[Try it online!](https://tio.run/##fY7LTsNADEX3@Qpr2MxIVTbskNjyE22RPC/iPGaGiVMaEN8enNItLCxf29fHLit3OT1u8fm0jThZj4BPmFZNrz3EXIEOPVCCkJYpVOSgv77bWPM0hHXWaIzZjqVSYp0yQ9RHhdb5EN866odxSrm815mXy8d1/exUS8mHq@7NDX0D09n8ViSVUgobRAmLVoR1bpdOwt9z8w@/kR3XiE9M1ov6y7lTquD8nuRoO5eRWKtTUuYMD/CyJMeUE@SFy8JAszx3CZWDP4CVRsyZQ703ZcggV4ftBw) (Function output is inverted, but I inverted it back in the footer of the interpreter)
## [Python 3](https://python.org) - 58 bytes
Thanks to @m90.
```
lambda a:0in map(int.__eq__,{}.fromkeys(a),range(len(a)))
```
Input is a list of integers from `[0,25]`.
All it does is remove duplicates and makes sure that each integer is equal to its position. Outputs are inverted, which is allowed.
[Try it online!](https://tio.run/##fY3NDoIwEITvfYqmpzYhxMSbiU8Chmz/oFBKKaig8dlxiV71sJmZ5NuZuM7NEI6bPZebh15qoHA6uEB7iNyFOa8qM1ZV9nzlNg19Z9aJg8gShNpwbwIGIbYiJmS55QUDqbSxdePazvdhiGOa5uvtvqyPhuUuaLPwVlA7JNpSnHEX8UkOE2MMCACeBIlGKrVbhae/Sv70E/xRBDmEpEb3i9xbEtbpXXA0n6J3M2dlYOKyvQE)
[Answer]
# [Dyalog APL](https://www.dyalog.com/), 7 bytes
```
⍳∘≢∘∪≡∪
```
Takes input as integers from 1 to 26.
[Try it online!](https://tio.run/##pU9LCsIwEN17ineBQmfyaXqcUFGEgEJXXkDaheDSrS7deqO5SJ3YEHAtYeYx72XeY@IpNdtzTMd9M6Q4jodhWXZyucn1LdNd5mfu00vmh3aVQBut/L7IuQrDMDCVNQXt71x0o7yDR4eAHtSC1EFl/aULDuRBHSiAenAL1h0GG7AFO7BHUKM1OEdywWzNar1yf4fUG0M5wNbxAw)
]
|
[Question]
[
## Links
* [Chat room](https://chat.stackexchange.com/rooms/127801/nose-poker)
* [The official game report](https://ajfaraday.github.io/nose_poker/report.txt)
* [Github repo](https://github.com/AJFaraday/nose_poker) - In case of bugs to report
Here's the official score table:
```
<script src="https://ajfaraday.github.io/nose_poker/ogres.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><table> <thead> <tr> <th>Ogre</th> <th>Hand</th><th>NP</th> <th>Reason</th> </tr></thead> <tbody id="clients"> </tbody></table><script type='text/javascript'>
ogres.forEach( function(data_row){var row=$('<tr>'); var cell=$('<td>'); cell.html(data_row.name); row.append(cell); cell=$('<td>'); cell.html(data_row.hand); row.append(cell); cell=$('<td>'); cell.html(data_row.np); row.append(cell);row.append(cell);cell=$('<td>'); cell.html(data_row.reason); row.append(cell); $('tbody#clients').append(row);});</script>
```
Nose Poker is an ogre game played by a group of ogres. Each ogre brings a large nose
and a small club.
On each hand, all the ogres will declare how many times they will poke their nose with the
club.
Each time, the lowest bid(s) will be knocked out of the game, then the remaining
ogres will poke their nose with the club their declared number of times.
Any ogre who has run out of nose will also be knocked out of the game.
## The Challenge
Write the JavaScript code to play Nose Poker. You'll write a client class which
plays the role of an ogre and makes the decision how to bid on each hand.
Your ogre starts the game with 500 nose points (np), and there is no way to recover np
during the game. Each turn you will call `controller.declare(pokes)` and either
fall out of the competition if you declare the lowest number of pokes, or your troll
will lose the declared amount of np.
The goal is to stay in the game as long as you can.
There are three ways to be knocked out of the game:
* **Failed to bid** If something goes wrong and you don't make a bit, or bid zero or less, you're out.
* **Cowardice!** Your ogre chickened out and bid lower than everyone else.
* **Has no nose** Your ogre ran out of np and therefore has no nose. How does it smell? Like it's out of the game.
## The Controller
Your client class will be passed a `controller` object which acts as it's interface to the game.
Here are the four functions it provides:
**np()**: The current amount of nose points that your ogre has.
```
this.controller.np();
// 450
```
**hand\_number()** The number of the current hand the game is on.
```
this.controller.hand_number();
// 2
```
**scores()** An array of the amount of np each currently active ogre has.
```
this.controller.scores();
// [450, 250, 20]
```
Note: This is intentionally sorted in descending order of np so it is not possible to see how other ogres have been bidding.
**declare(pokes)** Here's the important one. Declare how many times your ogre will poke itself
in the nose with a club.
```
this.controller.declare(10);
```
## Getting the app
You're going to need node and npm, sorry.
* `git clone https://github.com/AJFaraday/nose_poker.git`
* `cd nose_poker`
* `npm install`
## Writing a Client
Here's the template for your client class, add it to a js file in `src/clients/working`
```
module.exports = class {
constructor(controller) {
this.controller = controller;
}
play_hand() {
}
};
```
You can then modify the `play_hand()` function, remember it
must call `this.controller.declare(pokes)`. (You can also be knocked out of the
game for failing to do this).
When you're happy with it, run `./get_answers.sh` from the nose\_poker root directory. This
will add your client to `/src/clients.js` (and also get the current set of clients from the
Stack Exchange question). You only need to do this once.
After the first time you can run games to see the result of modifying your code by calling
`node script/play_game.js`.
## Submitting your Client
To add your client to the competition, answer this question.
* Name your ogre by including a title (h1, by starting the line with '#' or underlining it with '=' symbols)
+ The name should only contain alpha characters and underscores, no spaces please.
* Put the code in a code block.
* Please include a brief description of your ogre's strategy, and any other information you'd like to include.
The app will then periodically pick up answers, run the game, and update the score table in this question.
## Forbidden stuff
In order to be accepted into the competition, your code must export a valid class which accepts a controller, has a `play_hand()` function, and will call `this.controller.declare(pokes)` at some point in that function. If it does not, the official instance will not import it.
The importer will also ignore any answers which use these terms:
* `game` - Please do not try to interact with the game directly
* `Math.random` - Let's keep this deterministic, so the result is definitive.
* `setTimeout`, `setInterval` - These lead to runtime oddities.
* `eval`, `import` - Just don't!
## Default bots
| Default Bot | Behaviour |
| --- | --- |
| go\_home | Always bid 1 |
| go\_big | Bids 90% of np |
| half\_way | Bids 50% of np |
[Answer]
# Sinus-oidal
```
module.exports = class {
constructor(controller) {
this.controller = controller;
}
play_hand() {
var turn = this.controller.hand_number();
var multiply = Math.sin(turn * Math.PI / 4);
this.controller.declare(Math.floor(2 ** (multiply + 1)));
}
};
```
Get it?
[Answer]
# super\_smart\_bot
```
module.exports = class {
constructor(controller) {
this.controller = controller;
}
try_certain_win()
{
//we need to have more points than everyone else combined, plus 1 per player (though this bound is probably too weak)
//bid as many points as the lowest-NP player has, plus 1
let tcost = 0;
let mcost = 999;
let skipped = false;
let other_scores = this.controller.scores().filter(a => skipped ? true : (a == this.controller.np() ? (skipped = true)*0 : true));
for(let c of other_scores)
{
tcost += c + 1;
if(c + 1 < mcost) mcost = c + 1;
}
if(this.controller.np() <= tcost)
return false;
this.controller.declare(mcost);
return true;
}
min_safe_bid()
{
let skipped = false;
let other_scores = this.controller.scores().filter(a => skipped ? true : (a == this.controller.np() ? (skipped = true)*0 : true));
let res = Math.min(...other_scores) + 1;
return res;
}
play_hand() {
if(this.controller.hand_number() == 1)
{
this.controller.declare(2);
return;
}
let scores = this.controller.scores();
if(scores.length == 2) //optimal because this is the last round
{
this.controller.declare(this.controller.np() - 1);
return;
}
if(this.try_certain_win()) return;
let bid = this.controller.np() / this.controller.scores().length;
bid = Math.min(bid, this.min_safe_bid());
this.controller.declare(bid);
}
};
```
[Answer]
# Smart Median
```
module.exports = class {
constructor(controller) {
this.controller = controller;
}
play_hand() {
// Beat the simple bots
if(this.controller.hand_number() <= 5) {
this.bid(this.controller.hand_number() + 1);
return;
}
var scores = this.other_scores();
var bid = Math.floor(this.median(scores) / scores.length) + 1; // Add 1 to win once there's only 1 opponent left
this.bid(bid);
}
other_scores() {
var scores = this.controller.scores();
var myIndex = scores.indexOf(this.controller.np());
scores.splice(myIndex, 1);
return scores;
}
median(scores) {
var half = Math.floor(scores.length / 2);
return scores[half];
}
bid(value) {
// Never bid more than the weakest player has
var weak = Math.min(...this.controller.scores());
// Never bid more than I have
var me = this.controller.np();
var final_bid = Math.min(value, weak + 1, me);
this.controller.declare(final_bid);
}
};
```
Chooses a bid based on the median score divided by the number of opponents remaining. The idea is that the more opponents there are, the more likely one is to bid low, so I am safer to bid lower as well. I also threw in some smart bidding features, like not bidding more than a guaranteed pass, to not lose too many points. I imagine this strategy will burn through too many points in the midgame to win, but I do think it'll place near the top.
[Answer]
# Half-life
```
module.exports = class {
constructor(controller) {
this.controller = controller;
}
play_hand() {
var np = this.controller.np()
var bid = np < 10 ? np - 1 : Math.floor(np / 2);
this.controller.declare(bid);
}
};
```
Takes the number of nose points it has and bids half each time. However, if it has less than 10 np left, it goes all in. This is to hopefully defeat `half_way`.
[Answer]
# Dumb Ogre
```
module.exports = class {
constructor(controller) {
this.controller = controller;
}
play_hand() {
this.controller.declare(2);
}
};
```
To be fair, ogres aren't known to be particularly smart.
A trivial bot to get the ball rolling :p
[Answer]
# Exponential Ogre
```
module.exports = class {
constructor(controller) {
this.controller = controller;
}
play_hand() {
let bid = 1 << this.controller.hand_number();
this.controller.declare(bid);
}
};
```
Starting at 2, the ogre doubles its bid every round. Quite similar to [Reverse Pinocchio](https://codegolf.stackexchange.com/a/231707/64121), but I got the idea independently.
[Answer]
# Adaptive Bot
```
module.exports = class {
constructor(controller) {
this.controller = controller;
}
play_hand()
{
if (this.controller.hand_number() == 1) {
this.lastScores = this.controller.scores();
this.controller.declare(2);
return;
}
var scores = this.controller.scores();
var finalBid = 100;
for (var i = 0; i < scores.Length; i++) {
for (var j = 0; j < this.lastScores.Length; j++) {
if (this.lastScores[j] - scores[i] < finalBid) {
finalBid = this.lastScores[j] - scores[i];
}
}
}
this.lastScores = scores;
this.controller.declare(finalBid + 1);
}
};
```
Starts in the first round by bidding 2, to not get kicked out immediately (due to Go\_Home bot).
Then, assuming the bots stay in the same order, find out what everyone bid by finding the smallest difference between the previous turn and the current one.
As all bots I have seen so far reduce their bid monotonically, finding the lowest bid that survived and adding 1 will ensure that you survive next round.
EDIT: I dont have access to real coding tools right now, so I cant upload it/fix bugs. But I hope I made the strategy clear, so if anyone wants to copy this into a working bot, feel free to do so :)
EDIT2: The bots was completely busted and only bid 101 each turn :O Now it should work properly, so please update it again :D
[Answer]
# Oldgre
Oldgre has perfected his strategy over many years.
*Whippersnappgres!*
```
module.exports = class {
constructor(controller) {
this.controller = controller;
}
play_hand() {
const x = this.controller.hand_number();
this.controller.declare(
- 0.000006858186 * x ** 11
- 0.000199732658 * x ** 10
+ 0.024797517263 * x ** 9
- 0.737278798843 * x ** 8
+ 11.416562524617 * x ** 7
- 107.788528491826 * x ** 6
+ 656.517974108233 * x ** 5
- 2615.799102867764 * x ** 4
+ 6707.381768918599 * x ** 3
- 10515.725107130049 * x ** 2
+ 8997.738815265786 * x ** 1
- 3130.528128281523 * x ** 0
);
}
};
```
This is largely a proof of concept and, for the sake of the competition, I won't keep updating it.
[Answer]
# Simple Optimization Thing
```
module.exports = class {
constructor(controller) {
this.controller = controller;
}
play_hand() {
var count = this.controller.scores().length;
var min = Math.min(...this.controller.scores());
this.controller.declare(min / count);
}
};
```
Not sure if this strategy will work at all :p
[Answer]
# Quicksort Ogre
```
module.exports = class {
constructor(controller) {
this.controller = controller;
}
play_hand() {
var turns = this.controller.hand_number();
this.controller.declare(Math.round(turns * Math.log(turns)) + 4);
}
};
```
Ogres don't understand time complexity, but they do understand being poked on the nose \$n\log n\$ times. Small constant offset to prevent being immediately eliminated.
Probably my last somewhat trivial bot, I just want to see how something between the linear and exponential strategies would do (and quadratic was a bit too boring :p).
[Answer]
# Troll Adaptive
Exactly the same as Adaptive by @Nurator, except increases it's bid the second round to eliminate the original Adaptive:
```
module.exports = class {
constructor(controller) {
this.controller = controller;
}
play_hand()
{
if (this.controller.hand_number() == 1) {
this.lastScores = this.controller.scores();
this.controller.declare(2);
return;
}
else if (this.controller.hand_number() == 2) {
this.lastScores = this.controller.scores();
/* Adaptive will bid 3 since 2 is the lowest number. Thus, bidding 4 will eliminate Adaptive */
this.controller.declare(4);
return;
}
var scores = this.controller.scores();
var finalBid = 75;
for (var i = 0; i < scores.Length; i++) {
for (var j = 0; j < this.lastScores.Length; j++) {
if (this.lastScores[j] - this.scores[i] < finalBid) {
finalBid = this.lastScores[j] - this.scores[i];
}
}
}
this.lastScores = scores;
this.controller.declare(finalBid + 1);
}
};
```
Can easily be defeated by increasing your bid in the third round instead, and the bot after can be easily defeated in the fourth round etc.
[Answer]
# Super dumb bot
According to the instructions as I understand them, my own bot's score is returned somewhere in scores(); if this is not the case, comment out the lines starting with the line `if (score == sscore)` and continuing to the `else`.
```
module.exports = class {
constructor(controller) {
this.controller = controller;
}
play_hand() {
if(this.controller.hand_number() == 1)
{
// Go Home Bot makes everybody else need to do this nonsense on the first turn rather than really try.
this.controller.declare(2);
return;
}
if(this.controller.hand_number() == 2)
{
// Get rid of the other not-really-competing bot.
this.controller.declare(3);
return;
}
var myscore = this.controller.np();
var sscore = myscore;
var scores = this.controller.scores();
var ctr = 0;
for (var i = 0; i < scores.length; i++) {
var score = scores[i];
if (score != 0)
if (score == sscore)
sscore = 0;
else
ctr+=1;
}
var value = (ctr < 2) ? 0
: Math.floor(myscore / ctr);
this.controller.declare(value);
}
};
```
Either I know the optimal strategy off the top of my head or I don't. I put no effort into finding out whether or not I am right. The long loop just determines how many other bots are in the game. If the specifications had been written tighter it could be replaced by `var ctr = scores.length - 1;`
[Answer]
# Knockout
```
module.exports = class {
constructor(controller) {
this.controller = controller;
}
play_hand() {
let hand = this.controller.hand_number()
if(hand == 12){
this.controller.declare(2);
return;
}
if(this.controller.scores.length == 2){
this.controller.declare(this.controller.np() - 1)
return;
}
this.controller.declare(500 / (this.controller.scores().length + hand + 2) + 20 * (hand > 7) + 5 * (hand > 9) + 5 * (hand > 9))
}
};
```
~~A very simple strategy with some small tweaks that allow it to win!~~ Has been complicated a bit.
Basically tries to spend roughly the same amount each turn by going 500 / original number of bots. Of course, it's impossible to calculate the original number of bots, so it counts the current amount + the hand number.
Has several tricks, including going all-in at the end, and playing 2 on round 12 because oldgre will always play 1.
I'm not sure what's up with the snippet, but it *is* winning locally:
[](https://i.stack.imgur.com/LKBvf.png)
[Answer]
# Incremental ogre
```
module.exports = class {
constructor(controller) {
this.controller = controller;
}
play_hand() {
var bid = this.controller.hand_number() * 10
this.controller.declare(bid);
}
};
```
Bids 10 more each round.
]
|
[Question]
[
Generate the shortest possible code in any programming language that can generate all Pythagorean triples with all values not exceeding a given integer limit. A Pythagorean triple is a set of three integers \$(a, b, c)\$ that satisfy the equation \$a^2 + b^2 = c^2\$. The program should output the triples in any format, such as a list of tuples or a newline-separated list of strings.
Input: An integer limit \$n\$ (1 ≤ \$n\$ ≤ \$10^6\$)
Output: All Pythagorean triples \$(a, b, c)\$ such that \$1 ≤ a, b, c ≤ n\$ and \$a^2 + b^2 = c^2\$.
## Test Cases
```
Input: 20
Output:
(3, 4, 5)
(5, 12, 13)
(6, 8, 10)
(8, 15, 17)
(9, 12, 15)
(12, 16, 20)
```
```
Input: 5
Output:
(3, 4, 5)
```
Note: The output order does not matter as long as all the correct Pythagorean triples are included. Duplicate triples should not be included. But, specifying the order might help.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
L3.Æʒn`αQ
```
[Try it online](https://tio.run/##yy9OTMpM/f/fx1jvcNupSXkJ5zYG/v9vZAAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/H2O9w22nJuUlnNsY@L9W53@0kYGOaSwA).
The last three bytes could alternatively be `RÆ_` for the same byte-count:
[Try it online](https://tio.run/##yy9OTMpM/f/fx1jvcNupSXlBh9vi//83MgAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/H2O9w22nJuUFHW6L/1@r8z/ayEDHNBYA).
**Explanation:**
```
L # Push a list in the range [1, (implicit) input-integer]
3.Æ # Create all triplet-combinations of this list
ʒ # Filter this list of [a,b,c]-triplets by:
n # Square each inner integer in the triplet
` # Push all three values separated to the stack
α # Get the absolute difference of the top two: |b²-c²|
Q # Check if it's equal to the third one: a² == |b²-c²|
# (after which the filtered list of triplets is output implicitly as result)
R # Reverse the triplet to [c²,b²,a²]
Æ # Reduce it by subtracting: c²-b²-a²
_ # Check if this is 0
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~9~~ 8 bytes
```
ɾ3ḋ'²÷ε=
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLJvjPhuIsnwrLDt861PSIsIiIsIjIwIl0=)
I'm surprised I didn't manage to make this horribly inefficient.
*-1 thanks to Kevin!*
## Explained
```
ɾ3ḋ'²÷ε=
ɾ # Range [1, input]
3ḋ # Combinations of length 3
' # filtered by:
² # squaring everything
÷ # dumping the triplet onto the stack in reverse order
ε # absolute difference of b**2 and c**2
= # equals a**2
```
[Answer]
# [Factor](https://factorcode.org/) + `math.combinatorics`, 57 bytes
```
[ [1,b] 3 [ 2 v^n first3 -rot + = ] filter-combinations ]
```
[Try it online!](https://tio.run/##NYyxCsJAEET7fMX0mqAJNopgJzY2YhUiXI5VD5O9uLcG/PrzQrAb3puZu7HqJV4vp/Nxi97osxDDDwoI9P4Q25QmOquRpnbAi4Spm5n1fevYJO5swCCk@h3EsWKXZeUq28Qa9XrZNqhQo8R4Y9ydBK2Qi1cssEeTSKck@f/MeQ5oYusOaVMkn1L8AQ "Factor – Try It Online")
* `[1,b] 3 [ ... ] filter-combinations` select combinations of three from \$[1..n]\$ where...
* `2 v^n` square the elements of the triplet
* `first3` place each element onto the stack
* `-rot` move \$c^2\$ from the top of the stack to the bottom
* `+` add \$a^2\$ and \$b^2\$
* `=` equal?
[Answer]
# [Thunno](https://github.com/Thunno/Thunno), \$13\log\_{256}(96)\approx\$ 10.70 bytes
```
R1+3zQg2^Au_=
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhZrgwy1jasC043iHEvjbSFiUKkFi4wMICwA)
Port of Kevin Cruijssen's 05AB1E answer.
#### Explanation
```
R1+3zQg2^Au_= # Implicit input
R1+ # Push range(1, input+1)
3zQ # Combinations with length 3
g # Filter by: STACK: [a, b, c]
2^ # Square each STACK: [a**2, b**2, c**2]
Au # Dump onto stack STACK: a**2, b**2, c**2
_ # Subtract top two STACK: a**2, c**2 - b**2
= # Are they equal? STACK: a**2 == c**2 - b**2
# Implicit output
```
[Answer]
# [Noether](https://github.com/beta-decay/noether), 62 bytes
```
!aI~n(!a~bn1+({a2^!b2^+0.5^~cn<cn=|cc_=&}{aP","PbP","PcP?}b)a)
```
[Try it in your browser!](https://astrochristian.github.io/noether?code=IWFJfm4oIWF-Ym4xKyh7YTJeIWIyXiswLjVefmNuPGNuPXxjY189Jn17YVAiLCJQYlAiLCJQY1A_fWIpYSk&input=MjA)
Surprisingly this is the first time I've realised the severe lack of \$\leq\$ and \$\geq\$ operators in the language.
**Explanation:**
```
!a # Initialiase variable a to 1
I~n # Store user input in n: outer loop exit condition
( ) # Outer loop
!a~b # Increment a and store value in b
n1+ # Add 1 to n: inner loop exit condition
( ) # Inner loop
{ }{ } # If ... Else
a2^ # Square a
!b2^ # Increment value of b and square
+0.5^ # Sum a and b and square root
~cn< # Store value in c and check if less than n
cn= # c == n
| # Bitwise OR
cc_= # c == floor(c)
& # Bitwise AND
aP","PbP","PcP? # If true, output variable values, comma separated
b # Push b to stack (inner loop exit condition)
a # Push a to stack (outer loop exit condition)
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 14 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
õ à3 fÈ̲ѶXx²
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=9SDgMyBmyMyy0bZYeLI&input=MjAKLVI)
```
õ à3 fÈ̲ѶXx² :Implicit input of integer U
õ :Range [1,U]
à3 :Combinations of length 3
f :Filter by
È :Passing each X through the following function
Ì : Last element
² : Square
Ñ : Multiply by 2
¶ : Is equal to
Xx : X reduced by addition
² : After squaring each
```
[Answer]
# [><> (Fish)](https://esolangs.org/wiki/Fish), 111 bytes
```
i:*&43::*{:}:*+\
/*::<5[1;?)&:&:/
\:{:}(?!v~1+31.
/]v?)}:{/|.!051+1~\
n \]~~>1+$:@$:@= ?^50.
\' 'o}:n' 'o}:nao$~$64.
```
[Try it](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiaToqJjQzOjoqezp9OiorXFxcbi8qOjo8NVsxOz8pJjomOi9cblxcOns6fSg/IXZ+MSszMS5cbi9ddj8pfTp7L3wuITA1MSsxflxcXG5uIFxcXX5+PjErJDpAJDpAPSA/XjUwLlxuXFwnICdvfTpuJyAnb306bmFvJH4kNjQuXG4gICAgICBcbiIsImlucHV0IjoiMjUiLCJzdGFjayI6IiIsInN0YWNrX2Zvcm1hdCI6Im51bWJlcnMiLCJpbnB1dF9mb3JtYXQiOiJjaGFycyJ9)
## Explanation
[](https://i.stack.imgur.com/77nku.png)
`><>` lacks a square root function so this simply tries all numbers until it finds one greater than the square of the inputs.
First, we square the input. We start searching at a,b=4,3. We check if \$a^2\$, (`::*`) + \$b^2\$ is more than the input squared, if so we exit.
Then we push 5, the starting third value. Square it, if it is more than a^2+b^2, go to the next iteration. Otherwise, add 1 to C.
If A^2+B^2=C^2, print A, B, and C, then go to next.
When we go to the next iteration, add 1 to B. If B>A, add 1 to A instead and reset B to 1. This is `1+$:@$:@=?~1+1`. Then we jump back to the start to try another iteration.
[Answer]
## Scala, 71 bytes
```
(n:Int)=>for{c<-5 to n;b<-4 to c;a<-3 to b if a*a+b*b==c*c}yield(a,b,c)
```
or styled differently:
```
(n:Int)=>for{c<-5 to n
b<-4 to c
a<-3 to b
if a*a+b*b==c*c}yield(a,b,c)
```
It's not often that Scala gets a chance to do well in golfing, but the `.to()` method is perfect for inclusive ranges.
[Try it online](https://tio.run/##LcxLCsMgEADQfU4xS7URSj@bRgOlqx5jnBhqERWV0hJydttAd2/1CqHHFs3TUoUb2He1YSpwTQmW7oUeanbJ2wK6sXC5h8r1OMe8kJJnqBHCYJQ8baIBlTxuMuBmQIE7I4zWJGj9OOsnhr3pibf/yA57Dr/KIj0gZReqD93avg) or on [Scastie](https://scastie.scala-lang.org/l5yYoZfZQ8KwosbsySBJRQ)!
[Answer]
# JavaScript, 81 bytes
```
n=>{for(a=0;++a<n;)for(b=a;b<n;++b)(c=(a*a+b*b)**.5)%1||c<=n&&console.log(a,b,c)}
```
Try it:
```
f=n=>{for(a=0;++a<n;)for(b=a;b<n;++b)(c=(a*a+b*b)**.5)%1||c<=n&&console.log(a,b,c)}
;[
1,
3,
5,
7,
10,
17,
20
].forEach(n=>{console.log(n+':');f(n)})
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 63 bytes
```
n=>{for(;p=n;n--)while(--p>(q=(n*n-p*p)**.5))q%1||print(q,p,n)}
```
[Try it online!](https://tio.run/##TcjBCkBAEADQu/9QM5sRipTWv0g2K43ZtXHAt6@Di@N7y3AM@@itBDraaHRk3V9m89CJ5o6J8JztOgGR9OA0sGISJahUXiO6tLxv8ZYDuEwyxicaqApMvsPEQP1H2WB8AQ "JavaScript (V8) – Try It Online")
### Commented
```
n => { // n = input
for( // outer loop:
; //
p = n; // before each iteration, initialize p to n
// stop when n = 0
n-- // decrement n after each iteration
) //
while( // inner loop:
--p > ( // decrement p and test whether it's greater
q = // than q defined as:
(n * n - p * p) // the square root of the difference
** .5 // between n² and p²
) // stop as soon as the test fails
) //
q % 1 || // if q is an integer:
print(q, p, n) // print the triplet (q, p, n)
} //
```
[Answer]
# [Arturo](https://arturo-lang.io), 50 bytes
```
$=>[select combine.by:3@1..&'x[=+x\0^2x\1^2x\2^2]]
```
[Try it](http://arturo-lang.io/playground?qVTI9Z)
```
$=>[ ; an anonymous function
select ; select elements from a block
combine.by:3 @1..& ; combinations of 3 from the range 1 to n
'x ; assign current triplet to x in the select
[ ; begin select
=+x\0^2x\1^2x\2^2 ; is a^2+b^2 equal to c^2?
] ; end select
] ; end function
```
[Answer]
# [Python](https://www.python.org), ~~91~~ 88 bytes
```
lambda n,r=range:[(k,j,i)for i in r(1,n+1)for j in r(1,i)for k in r(1,j)if i*i==j*j+k*k]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3I3ISc5NSEhXydIpsixLz0lOtojWydbJ0MjXT8osUMhUy8xSKNAx18rQNwQJZMAGIfDaMm6WZmaaQqZVpa5ullaWdrZUdCzF_TUFRZl6JRpqGkYGmJkRowQIIDQA)
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 12 bytes
```
RS3Lᵖ{:*Ɔ$∑=
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FhuDgo19Hm6dVm2ldaxN5VHHRNslxUnJxVDZBUuMDLhMIWwA)
A port of [@Fatalize's Brachylog answer](https://codegolf.stackexchange.com/a/258636/9288).
```
RS3Lᵖ{:*Ɔ$∑=
R Range from 1 to the input
S Subset
3L Length should be 3
ᵖ{ Start a block; treat the block as a predicate,
and return the original value if the block does not fail
:* Multiply by itself
Ɔ$∑= The last element should equals to the sum of the other elements
```
By default, the Nekomata interpreter will print all possible results.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes
```
IΣΣE⊕NEιEΦλ⁼×ιι⁺×λλ×νν⟦νλι
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6Fjf7A4oy80o0nBOLSzSCS3PB2DexQMMzL7koNTc1ryQ1BcguKC3xK81NSi3S0NTUUQDJZ0Iot8ycEqBojo6Ca2FpYk6xRkhmbmoxSDYTqDAgpxQmAlSRAxSBcPJ0FPI0NUFGRQOZQKnMWE0IsF5SnJRcDHXc8mgl3bIcpdhFRgYQAQA) Link is to verbose version of code. Explanation:
```
N Input integer
⊕ Incremented
E Map over implicit range
ι Current value
E Map over implicit range
λ Current value
Φ Filter over implicit range
×ιι Square of outer value
⁼ Equals
×λλ Square of inner value
⁺ Plus
×νν Square of innermost value
E Map over matches
⟦ List of
ν Innermost value
λ Inner value
ι Outer value
Σ Flatten
Σ Flatten
I Cast to string
Implicitly print
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 21 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
╒■■mÅ─╡gæ_▀s=gƲxε-┬▀
```
[Try it online.](https://tio.run/##y00syUjPz0n7///R1EmPpi0AotzDrY@mNDyaujD98LL4R9Maim3TD7cd2lRxbqvuoylrgAL//xsZcJkCAA)
**Explanation:**
```
╒ # Push a list in the range [1, (implicit) input-integer]
■ # Get the cartesian product with itself to create pairs
■ # Get the cartesian product with itself to create pairs of pairs
m # Map over each pair of pairs,
Å # using 2 characters as inner code-block:
─ # Flatten the pair to a quadruplet
╡ # Discard the last item to make it a triplet
g # Filter this list of triplets by,
æ # using 4 characters as inner code-block:
_ # Duplicate the current list
▀ # Uniquify the values in the copy
s # Sort it from lowest to highest
= # Check if the two lists are still the same
g # Filter this list further by,
Æ # using 5 characters as inner code-block:
² # Square each integer in the triplet
x # Reverse it
ε # Reduce the triplet by:
- # Subtracting
┬ # Check if the result of this c²-b²-a² equals 0
▀ # After the filter: uniquify the remaining list of triplets
# (after which the entire stack is output implicitly as result)
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 14 bytes
```
f!-F^R2_T.CSQ3
```
[Try it online!](https://tio.run/##K6gsyfj/P01R1y0uyCg@RM85OND4/38jAwA "Pyth – Try It Online")
### Explanation
```
# implicitly assign Q = eval(input())
.C 3 # all sorted lists of three elements from
SQ # range(1,Q+1)
f # filter these lists on lambda T
_T # reverse T
^R2 # map elements to their squares
-F # fold on subtraction (subtract all elements from the first)
! # not (only true for zero)
```
[Answer]
# [Befunge-93 (PyFunge)](https://pythonhosted.org/PyFunge/), 125 bytes
```
v
&
>35g:*25g:*+15g:*-|
,*52.g51.g52.g53<v
^p53+1_v#`\g52:g53<<
^111 >$135p25g:1 5g\`!#v_1+25p
^ p51+1_@#`g51\g51 :p521$<
```
[Try it online!](https://tio.run/##HYzBCsMgEETxul@xxdBDrKWr7KEioR8SjBRSb2UvEQr9d6s9zJthYOa5v4532e3dW/n8Y2sVzrB4LmF2A4YG7RcQLzO7a2HqGu5jhSTsDW1V57WXYZQRklIKEZeJPMs4IeSy5pOuGxnHAgmFqc8eOve7viQMwo6m2Jq7wQ8 "Befunge-93 (PyFunge) – Try It Online")
Note: The three "1"s shown here on line 6 ((1,5),(2,5) and (3,5) in Funge-Space) are actually be U+0001 in the source code. This is reflected correctly in TIO.
I may be able to save some bytes by moving those storage characters to line 1 or 2, and send line 6 left and wrap it, and if I can find a way to reduce the number of "g"s required to get the incremented values.
I'll do a nice writeup for this when I have time.
[Answer]
# Python 3, ~~112~~ 104 bytes
```
lambda n,r=range:{(*sorted((i,j,k)),)for i in r(1,n+1)for j in r(1,n+1)for k in r(1,n+1)if i*i+j*j==k*k}
```
Literally the same thing as the other answers.
[Answer]
# [Python](https://www.python.org), 98 bytes
Two solutions already exist for Python, but this one uses a slightly different approach that I thought might be informative:
```
from itertools import *
lambda n:[(k,j,i)for(k,j,i)in combinations(range(0,n+1),3)if i*i==j*j+k*k]
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 13 bytes
```
⟦₁⊇Ṫ.^₂ᵐṅᵗ+0∧
```
[Try it online!](https://tio.run/##AToAxf9icmFjaHlsb2cy/@KGsOKCgeG2oP/in6bigoHiiofhuaouXuKCguG1kOG5heG1lysw4oin//8yMP9a "Brachylog – Try It Online")
### Explanation
This is a generator, which will unify with each triplet.
```
⟦₁ Range [1, …, N]
⊇Ṫ. Subset of 3 elements
.^₂ᵐ Square each element
ṅᵗ Negate the last one (which is the biggest)
+0∧ The sum must be 0
```
### Much faster, 19 bytes
```
≥~hṪ≥₁ℕ₁ᵐ^₂ᵐṅʰ+0∧Ṫ≜
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/qG3Do6bGh9sW/H/UubQu4@HOVUAaKPKoZSpIfOuEuEdNTUDq4c7WUxu0DR51LAcrmfP/v5GBwf8oAA "Brachylog – Try It Online")
Takes about 1.5s for N = 200 on TIO. This uses integer constraint programming mechanisms which is way more efficient than brute forcing combinations in a range, but is longer to express in this case.
```
≥~hṪ A triplet of elements whose head is smaller than N
≥₁ The triplet is non-increasing
ℕ₁ᵐ Each element is in [1, +inf)
^₂ᵐ Map square
ṅʰ Negate the first element
+0∧ The sum must be 0
Ṫ≜ Assign values to satisfy these constraints
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 113 + 7 bytes
Compiled with `-lm -DM=<input>`
```
r,s,t;main(){for(;s<M;)for(t=++s;(r=sqrt(2*s*++t))<M;)r-sqrt(2*s*t)||(r+=s+t)>M||printf("%d %d %d\n",r-t,r-s,r);}
```
[Try it online!](https://tio.run/##PYlBCsIwEEWvIgVhpklAuo1x1W1u0E2JpBTaqDOzM169Y@tCeB8e/yU3paRKlq34dZwL4Ds/CDxfo8fDJBjDHijwiwS6lltjBPHI5P6fYK1AJvDebrHWJ81FMjTn@@nHUBpLTvaxJfQf1S3lZZxY3bKq62PoLl8 "C (gcc) – Try It Online")
[Answer]
# JavaScript 72 bytes
```
c=>{for(a=b=c;c;--a||(a=--b)||(a=b=--c))c*c-b*b-a*a||console.log(c,b,a)}
```
Formatted:
```
c => {
for( a=b=c; c; /* until c is 0 */
/* count down a, when a==0 reduce b and reset a=b, the same with c */
--a || (a = --b) || (a = b = --c)
)
/* if c²-b²-a² == 0 log the tuple */
c*c - b*b - a*a || console.log(c,b,a)
}
```
[Try it online](https://tio.run/##TcnBCkBAFEbhvSeZO7mSUkrjXe79MyIZIRs8@5is7L7TmeSUHdu4Hnw20bsI110@bEacOrRomeW@UzErfdBEEMGC1SqLTR9h2cPcF3MYDHLNhZ7oTU3Zf1DmTVVSfAE)
[Answer]
# [Haskell](https://www.haskell.org/), 56 bytes
```
q l=[(a,b,c)|c<-[1..l],a<-[1..c],b<-[a..l],a^2+b^2==c^2]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/v1AhxzZaI1EnSSdZsybZRjfaUE8vJ1YnEcJKjtVJArISIWJxRtpJcUa2tslxRrH/cxMz82yLUhNTfPLs7GwLijLzSvQK/xsaAAA "Haskell – Try It Online")
[Answer]
# [jq](https://stedolan.github.io/jq/), ~~85~~ 78 bytes
```
[range(3;.)]|combinations(3)|select(map(pow(.;2))|.[0]==.[1]+.[2]and.[1]>.[2])
```
~~[Try it online!](https://tio.run/##yyr8X62UmVdQWqJkpaCno6CUX1oC5kT/L0rMS0/VMLHW06yJ1ovV1oDwjaF8zRo97ejcxAKNgvxyDT1rI03NmsSUlJriwqKS2Jri1JzU5BINvWijWFtbMFWTlpOfX6Sp@T@29r@hAZeRAZexAQA "jq – Try It Online")~~
[Try it online!](https://tio.run/##HcexDsIgEADQna9omI5oLhQmbeqPkBuwEoOxB7U0DuK3Y@r23mNpHxk5b0WeOzx2Mm3lH9fcy/M9gB1QUZ3SfI3sS0y8glV1Dc8wFZh9hpzegINRqqLTNI7oejqgM@T5tvuyWzX6tpPotTBaWP0D "jq – Try It Online")
Generates all triples, then filters.
]
|
[Question]
[
We can arrange the positive integers like this:
```
1_| 2 | 5 | 10
4___3_| 6 | 11
9___8___7_| 12
16 15 14 13
```
That is, in L-shaped brackets expanding down and right infinitely.
Then, we can read it off with the antidiagonals:
```
1 2 5 10
/ / /
4 3 6 11
/ / /
9 8 7 12
/ / /
16 15 14 13
```
For the above, we read `1`, then `2, 4`, then `5, 3, 9`, then `10, 6, 8, 16`, and so on.
Your challenge is to output this sequence. Standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") rules apply. This is [A060736](https://oeis.org/A060736).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins!
[Answer]
# x86-64 machine code, ~~25~~ 23 bytes
```
31 C0 48 01 C1 7F FB 29 C8 29 C1 7F 03 01 C8 48 01 C1 F7 E8 01 C8 C3
```
[Try it online!](https://tio.run/##XVGxboMwEJ3xV1ypItmBRGkidSAhS@cunSo1FTLGgCtjKgytUZRfLzUE0jQezr537@4922yRMdZ190Ix2SQcdrpORLnM9@gfJEV8i1VCZT2GoojWNoubmkcRxinVNaNSEgJC1ZDiPlKyRVQXgOHFxWiZyTKmElKUBo4pK@DU@H1AVeAknA1HhyYJcDYWnI8MKuToJh7JzIzZNUOPXRfGNEwHN@NE0cgrmUtDxWtEXLB2Ue@7oEKdL1BlzAeW0wrmc5t8EXREYFdfNBDCyoe237YD@p0LyQF7noFdCA@PZED79WnfrU6xOxOw2MNMHJTrg1VPsSHk3DxRDuqZslwoDqxMeOCOZfMnk5RwnNgwW61f7aw2xLhRWmSKJ4PhOUnJm/G8d7I9TcZauLNDzNPmRhKw9RW3NdfkbGys22dpKtXLnlDX/bBU0kx3i2KztsF@bGjbufwF)
Following the `fastcall` calling convention, this takes a number *n* in ECX and returns the 1-indexed *n*th entry in EAX.
This works by first determining x and y coordinates in the grid. Then, letting m = min(x,y), the result is m2+m+1+y-x.
```
│ 0 1 2
─┼─┴─┴─┴x
0┤ 1 2 5
1┤ 4 3 6
2┤ 9 8 7
y
```
In assembly:
```
f: xor eax, eax # Set EAX to 0.
r: dec eax # Subtract 1 from EAX.
# This will be the negative length of the current diagonal.
add ecx, eax # Add EAX to ECX.
jg r # Jump back if the result is positive --
# if the index given has not been reached.
# When the loop ends, ECX will hold the negative 0-indexed reverse
# position of the given index within its diagonal, equal to -x.
# EAX will hold the negative length of the diagonal, -x-y-1.
sub eax, ecx # Subtract ECX from EAX; EAX now holds -y-1.
sub ecx, eax # Subtract EAX from ECX, making ECX y-x+1.
jg s # Jump if that's positive.
add eax, ecx # (Otherwise: y<x) Add ECX to EAX, making EAX -x.
dec eax # Subtract 1 from EAX, making -x-1.
# Either way, EAX ends up as -m-1.
s: add ecx, eax # Add EAX to ECX, making ECX y-x-m.
imul eax # Multiply EAX by itself, making (-m-1)² = m²+2m+1.
add eax, ecx # Add ECX to EAX, making m²+m+1+y-x.
ret # Return.
```
[Answer]
# JavaScript (ES7), 49 bytes
Returns the \$n\$-th term, 1-indexed.
```
n=>(t=(2*n)**.5+.5|0,t-=n-=t*~-t/2)<n?n*n-t:t*t+n
```
[Try it online!](https://tio.run/##Dcq9DoIwFAbQnae4A0N/LCpJF@Hqq9AgGA35auDGpdZXr2xnOK/wCdu4Pt/iEO9TmbmAr0pYtQbamMbbxn9PB3EMx2J@To6t7nGDgZOLGLEoc1wViOncEahn8n6HtZpSRTRGbHGZmiU@1BBUnZD1fus0K@g86K7K5Q8 "JavaScript (Node.js) – Try It Online")
### How?
This is a revamped version of the 2nd formula given on [OEIS](https://oeis.org/A060736).
We define the 1-based index \$t\$ of the diagonal to which the \$n\$-th entry belongs (this is [A002024](https://oeis.org/A002024)):
$$t=\left\lfloor\sqrt{2n}+\frac{1}{2}\right\rfloor$$
We define the 1-based index \$N\$ representing the position of the entry in the diagonal (from top-right to bottom-left):
$$N=n-\frac{t(t-1)}{2}$$
We turn it into an index \$T\$ going from \$t-1\$ to \$0\$:
$$T=t-N$$
The figures below represent \$n\$, \$t\$, \$N\$ and \$T\$ respectively:
$$\begin{bmatrix}
\color{red}1&2&\color{red}4&7\\
3&\color{red}5&8\\
\color{red}6&9\\
10
\end{bmatrix}
\begin{bmatrix}
\color{red}1&2&\color{red}3&4\\
2&\color{red}3&4\\
\color{red}3&4\\
4
\end{bmatrix}
\begin{bmatrix}
\color{red}1&1&\color{red}1&1\\
2&\color{red}2&2\\
\color{red}3&3\\
4
\end{bmatrix}
\begin{bmatrix}
\color{red}0&1&\color{red}2&3\\
0&\color{red}1&2\\
\color{red}0&1\\
0
\end{bmatrix}$$
The final result is given by:
$$\cases{N^2-T,&\text{if $T<N$}\\T^2+N,&\text{if $T\ge N$}}$$
Leading to:
$$\begin{bmatrix}
\color{red}1&2&\color{red}5&10\\
4&\color{red}3&6\\
\color{red}9&8\\
16
\end{bmatrix}$$
[Answer]
# [Haskell](https://www.haskell.org), 40 bytes
```
[k^2+k-n*min(2*k-n)1|n<-[1..],k<-[1..n]]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ2W0km6Ec0CAUuz-3MTMPAVbhdzEAt94hYKizLwSBRWFksTsVAVDAwOFmKWlJWm6Fjc1orPjjLSzdfO0cjPzNIy0gCxNw5o8G91oQz29WJ1sCCMvNhaifgGUgtIA)
-2 bytes thanks to [@ovs](https://codegolf.stackexchange.com/users/64121/ovs).
Based on the Mathematica code on OEIS.
[Answer]
# [J](http://jsoftware.com/), 44 39 bytes
```
{.&;[:</.@(*+/\"1@,._1+<:/*2*]"0/)~1+i.
```
[Try it online!](https://tio.run/##JYvNCsIwEITvfYqhStu066Yb/2OVoOBJPHitRUEU9eIDiH31mujhY4bdb55dzOkNS4sUhBLWM2BsDrtt9@ZkUdtKs8vyQh9jccQnKSqrc5M3calVK8WDOxXt1wwpmjD46eTqc3OuP/2sZ7XNVqxJcJIkV65nFSn3YEdtFF0v9xduMOW/CcEQRoQxYUiYE6QkTAgz33zI1OOlEF4xgXAObz8UvzSj7gs "J – Try It Online")
The formula might have been shorter, but I wanted to construct the matrix and use J's `/.` adverb to get the diagonals, because when you have a primitive to get diagonals you cannot not use it.
To construct the matrix, note that the successive deltas have an easy to describe pattern that looks like this:
```
1 3 5 7 9 11 13
_1 3 5 7 9 11 13
_1 _1 5 7 9 11 13
_1 _1 _1 7 9 11 13
_1 _1 _1 _1 9 11 13
_1 _1 _1 _1 _1 11 13
_1 _1 _1 _1 _1 _1 13
```
and that the first column are the squares. So we just zip them together:
```
1 1 3 5 7 9 11 13
4 _1 3 5 7 9 11 13
9 _1 _1 5 7 9 11 13
16 _1 _1 _1 7 9 11 13
25 _1 _1 _1 _1 9 11 13
36 _1 _1 _1 _1 _1 11 13
49 _1 _1 _1 _1 _1 _1 13
```
and then scan sum each row to reproduce the matrix:
```
1 2 5 10 17 26 37 50
4 3 6 11 18 27 38 51
9 8 7 12 19 28 39 52
16 15 14 13 20 29 40 53
25 24 23 22 21 30 41 54
36 35 34 33 32 31 42 55
49 48 47 46 45 44 43 56
```
[Answer]
# [Python](https://www.python.org), 67 bytes
```
n=0
while n:=n+1:[print(k*k+k-n*min(2*k-n,1))for k in range(1,n+1)]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3nfNsDbjKMzJzUhXyrGzztA2toguKMvNKNLK1srWzdfO0cjPzNIy0gCwdQ03NtPwihWyFzDyFosS89FQNQx2gBs1YiFFQE2EmAwA)
Port of Haskell. Outputs infinitely.
Old answer:
## [Python](https://www.python.org), 77 bytes
```
n=0
while n:=n+1:[print(n<2*k-1and-~k*k-n or(n-k)**2+k)for k in range(1,n+1)]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3ffNsDbjKMzJzUhXyrGzztA2toguKMvNKNPJsjLSydQ0T81J067KBrDyF_CKNPN1sTS0tI-1szbT8IoVshcw8haLEvPRUDUMdoFbNWIihULNhdgAA)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~86~~ \$\cdots\$ ~~60~~ 55 bytes
```
t;f(n){t=sqrt(2*n)+.5;n=(t-=n-=t*~-t/2)<n?n*n-t:t*t+n;}
```
[Try it online!](https://tio.run/##VVDRTsIwFH3nK26WkHRbK6xjKpbpg/ErHA@kdLgIBdebuEjmpztvx0Bpctrbc8856a0WG627DlXJbHjE3H3UyGRkw/gmUzZnKHIrcoy@BU5kuLBPNrICHzDC2Kq2qyzCblVZFsJxBLQ8YZqD0WjWr0vI4ZhwkBxmHDIOKYc5h2TK4ZbDPVV0JHcEEvmDJNLD075NxoSckpASl5JGep0PoSxJSEk/o3tGoSl5pAfVkrzprFX9q/TeOgT9tqoj2o1@N/XpcUHRvMiimT8TsoDD/3saDO5yXwPzg1V2bRqyTdVQLsBVX2ZfsvPI4WQgogujII57ddiHnb7p/FVIaaeoGBJ11XLUKhmG16wh9vK/vXP5JzjUJClZMF6DeATax66wNBVycPwyuMtzsxxi21Hb/ehyu9q4Tnx2Yrv7BQ "C (gcc) – Try It Online")
*Saved a whopping 13 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!*
*Saved yet another a whopping ~~13~~ 18 bytes thanks to the man himself [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!!*
Returns the \$n^\text{th}\$ term.
Uses the formula from [A060736](https://oeis.org/A060736).
[Answer]
# [Factor](https://factorcode.org), ~~86~~ 83 bytes
```
0 [ 1 + 3 dupn [1,b] [ 3 dupn sq + -rot 2 * over - 1 min * - . ] with each t ] loop
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY0xDoJAEEWv8msVItoYPYCxMTHEilCsMMBG2F2GQaNXsaHRO3EbN0r182be_Hl9CpWJ5WE8nePDcb9Fo6QKWZmSOlyJDdUoyRCrWj-VaGu6n_L3LOfE6KjtyWT-wDGJPBxrI9i9eymCzRgvkSDCHGvkvTNIosUl9aMJu9avAraCFWawN98XeL3RxmOAECnu2v8jlVUQT7W17l89TDHlFw)
Outputs the sequence indefinitely. Loosely based on alephalpha's [Haskell answer](https://codegolf.stackexchange.com/a/247866/97916).
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 83 bytes
```
.+
*
(^_|\1_)*(_+)
$.2*$2$2,$.1*$($1___)__-$.2*2*$($1_);$1_
,|(_+)-\1_*
(_+);\1
_
```
[Try it online!](https://tio.run/##JYsxDoMwEAT7fcdFsg9scZeQgHgAn0DZpEiRJkVEyd8NFs1oNdr5f9bv723lEuZXyQ0U4cltMUYNbCIku4qLt5JNJYiRjGSq3k8RpwNot/pPR6lAndNiAEsxOK64occdDwwYYd0O "Retina – Try It Online") Link includes test cases. Outputs the `n`th term. Explanation: Loosely based on @alephalpha's formula.
```
.+
*
```
Convert `n` to unary.
```
(^_|\1_)*(_+)
```
Decompose `n` into a triangular number `t-1` and a residue `k` in the range `1..t`.
```
$.2*$2$2,$.1*$($1___)__-$.2*2*$($1_);$1_
```
Calculate `k*k+k`, `t*t+t`, `2*k*t` and `t`.
```
,|(_+)-\1_*
```
Subtract `2*k*t` from `t*t+t`, clamping the result at `0`, and add on `k*k+k`.
```
(_+);\1
```
Subtract `t` from the previous result.
```
_
```
Convert to decimal.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
[¼¾ENnN+¾N·¾-1‚ß*-,
```
Port of [*@alephalpha*'s Haskell answer](https://codegolf.stackexchange.com/a/247866/52210).
Outputs indefinitely.
[Try it online.](https://tio.run/##ASUA2v9vc2FiaWX//1vCvMK@RU5uTivCvk7Ct8K@LTHigJrDnyotLP//)
**Explanation:**
```
[ # Loop indefinitely:
¼ # Increase variable `c` by 1 (0 by default)
¾E # Inner loop `N` in the range [1,`c`]:
, # Pop and output:
NnN+¾N·¾-1‚ß*- # N²+N-c*min(2N-c,1)
Nn # N²
N+ # +N
- # -
¾ * # c*
1‚ß # min( ,1)
N· # 2N
¾- # -c
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~28~~ 27 bytes
```
⇧Þ□λ÷N^›WDṘ²+^∑1<i;ÞZÞḋIRfi
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLih6fDnuKWoc67w7dOXuKAuldE4bmYwrIrXuKIkTE8aTvDnlrDnuG4i0lSZmkiLCIiLCIyIl0=)
Based on [@Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s [Javascript answer](https://codegolf.stackexchange.com/a/247864/103205).
–1 per [@emanresu A](https://codegolf.stackexchange.com/users/100664/emanresu-a).
## How?
```
λ÷N^›WDṘ²+^∑1<i; # find the (i, j)th entry of the matrix
λ ; # lambda STACK (top ->)
÷ # unwrap i j
N # negate i -j
^ # reverse stack -j i
› # increment -j i+1
W # wrap [i+1,-j]
# = [N,-T] (using Arnaud's notation)
D # triplicate [N,-T] [N,-T] [N,-T]
Ṙ # reverse [N,-T] [N,-T] [-T,N]
² # square [N,-T] [N,-T] [T^2,N^2]
+ # sum [N,-T] [T^2+N,N^2-T]
^ # reverse stack [T^2+N,N^2-T] [N,-T]
∑ # sum [T^2+N,N^2-T] N-T
1< # is < 1? [T^2+N,N^2-T] (1 if N-T<1 else 0)
# = [T^2+N,N^2-T] (1 if T>=N else 0)
i # index N^2-T if T>=N else T^2+N
⇧Þ□λ÷N^›WDṘ²+^∑1<i;ÞZ # make the matrix
⇧ # double increment, pushing N+2
Þ□ # (Nx2)x(Nx2) identity matrix
λ÷N^›WDṘ²+^∑1<i; # (above function)
ÞZ # fill by coordinates, i.e. replace each entry
# of the matrix with the result of calling the
# function on the entry's list of coordinates
ÞḋIRfi # output example (3x3 matrix)
Þḋ # antidiagonals [[5,3,9],[2,4],[1],[7],[6,8]]
I # into two pieces [ [[5,3,9],[2,4],[1]] , [[7],[6,8]] ]
R # vectorized reverse [ [[1],[2,4],[5,3,9]] , [[6,8],[7]] ]
f # flatten [1,2,4,5,3,9,6,8,7]
i # index by input
```
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 72 bytes
*-18 bytes thanks to the formula of `Arnauld` and -10 bytes thanks to `Kevin Cruijssen`.*
```
lambda n:(t:=int((2*n)**.5+.5),(n:=n-t*~-t/2)*n-(t:=t-n),t*t+n)[2-(t<n)]
```
[Attempt this online](https://ato.pxeger.com/run?1=LYxBCsIwEEX3nmJ2nUmTSgMVCWbvHdRFRaOBOi1lXEipF3FTEL2Tt9FSVw8-77_Hu7nJuebhGfz2dZVglp91VV72hxLYoTgfWRCtYlIqK9KsII3sPBtRdyNzS4rNqIlh0qIkZdrY37Ji2v17eahbiBAZ2pJPR8x1sSA3A2jaMR6SgF3sCTx0ASP1CU3HYZj4BQ)
[Answer]
# APL+WIN, 22 bytes
Prompts for input matrix. Index origin = 0
```
(,m)[⍋+⌿(⍴m)⊤(⍳⍴,m←⎕)]
```
[Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlwPWooz3tv4ZOrmb0o95u7Uc9@zUe9W7J1XzUtQTI2Axk6@QC1QHVa8b@B6rl@p/GZaJgAhQ3VDBSMFUwNFAwUTBWMFMwNFSwVLBQMFcwNFIwBHKBUiYKhsZcAA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 32 bytes
```
NθFθF⊕ι⊞υ⁻×⊕κ⁺²κ×⊕ι⊕⌊⟦⁰⁻⊗κι⟧I…υθ
```
[Try it online!](https://tio.run/##ZY69DsIwDIT3PkXGWApSYe1Ylg6gDGyIoQ1BsZqfNqmRePqQIpBAeLB9vtMnK9NHFXqbc@cnWo7kBh35DE11C5GVhb1m51XUTvtFXzkCMEnJcBLsgJ4SP6HT6SczgmDSFmsn2AhF/EewXL91QaEjx8/1B7sPNNg3DOECazWVjOgX3vaptIeyujVhWl@ZVzfnbZ03d/sE "Charcoal – Try It Online") Link is to verbose version of code. Outputs the first `n` terms. Explanation: Based on @alephalpha's Haskell answer.
```
Nθ
```
Input `n`.
```
Fθ
```
Generate `n` antidiagonals, to avoid having to do square roots to find out how many antidiagonals are actually needed.
```
F⊕ι⊞υ⁻×⊕κ⁺²κ×⊕ι⊕⌊⟦⁰⁻⊗κι⟧
```
Compute the values on each antidiagonal.
```
I…υθ
```
Output the first `n` terms.
]
|
[Question]
[
A digit small number is a positive integer \$n\$ such for any two numbers that multiply to \$n\$, their total number of digits is more than the digits in \$n\$.
In otherwords: there are no two positive integers \$a\$ and \$b\$ such that:
\$
ab = n
\$
and
\$
\left\lfloor\log\_{10}(a)\right\rfloor+\left\lfloor\log\_{10}(b)\right\rfloor <\left\lfloor\log\_{10}(n)\right\rfloor
\$
For example 363 is digit small. It can be made as the product of two numbers 3 ways
\$
1\times363=363\\
3\times121=363\\
11\times33=363\\
\$
Each time we have 4 digits on the left hand side and 3 on the right hand side.
As another example 48 is not digit small because we can write it as
\$
6\times8=48
\$
where each side of the equation has 2 digits in total.
# Task
Given a positive number output one of two distinct values depending on whether the input was digit small. For example you could output `1` when the input is digit small and `0` if it is not, or `True` and `False` etc.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes.
# Test cases
Here are the first 25 digit small numbers:
```
1,2,3,4,5,6,7,8,9,11,13,17,19,22,23,26,29,31,33,34,37,38,39,41,43
```
# Hint
>
> If you drop the test cases into OEIS you will get [A122427](http://oeis.org/A122427). This sequence is useful, but you will have to prove where it is the same, or find the cases in which it is different.
>
>
>
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
Using the hint, suggested by [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)
```
ѧ{θQ
```
[Try it online!](https://tio.run/##yy9OTMpM/W9i4nNqksv/wxMPLa8@tyPw/38A "05AB1E – Try It Online")
Cast the divisors `Ñ` to string `§`, sort `{`, is the last one `θ` equal to the input `Q`?
Or 9 bytes without the hint, -1 byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen):
```
ÑÂøεS∍‹}P
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8MTDTYd3nNsa/Kij91HDztqA//@NzYwB "05AB1E – Try It Online")
```
Ñ # divisors of the input
Âø # zip with its reverse
ε } # map over the divisor pairs
S # split into a single list of digits
∍ # extend the input to that length
‹ # is the input less than the extended version?
P # product / boolean all
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 29 bytes
```
n->!sumdiv(n,d,Str(d)>Str(n))
```
[Try it online!](https://tio.run/##K0gsytRNL/ifpmD7P0/XTrG4NDcls0wjTydFJ7ikSCNF0w5E5Wlq/k/LB9IKtgqGOgqmBjoKBUWZeSVAASUFXTsgkQZSo/kfAA "Pari/GP – Try It Online")
Using the hint.
>
> Let \$\#n\$ denote the number of digits in \$n\$. Then \$n\$ has a divisor \$d\$ that is lexicographically greater than \$n\$ \$\iff\$ \$d \* 10^{\#n-\#d} > n\$ \$\iff\$ \$n/d < 10^{\#n-\#d}\$ \$\iff\$ \$\#(n/d) \le \#n - \#d\$ \$\iff\$ \$n\$ is not digit small.
>
>
>
[Answer]
# [Python 2](https://docs.python.org/2/), 44 bytes
```
lambda n:any(`i`>`n`>n%i<1for i in range(n))
```
[Try it online!](https://tio.run/##RcqxCsIwFEbhvU9xF6GBDolj0I4@gVsVcsVEL9Q/5SYOffpocXA931nW@szYt3S8tJlftzsTPGPtg4QxIIzYycGlrCQkIGU8Yg9j2pbwT24gZ601viMuJWql9N02n876jgOdeC7x2pEkQv6pX1RQCe0D "Python 2 – Try It Online")
Outputs `True`/`False` negated. Looks for an `i` that's a divisor of `n` and is lexicographically smaller than `n`. The two conditions are combined into an inequality chain, connected by Python 2's willingness to compare strings and numbers (strings are bigger).
This chain also benefits from short-circuiting. Checking `i=0` would trigger an error when we check `n%i`, but since `0` is never lexicographically above `n`, the first condition always fails and the second one is never reached.
[Answer]
# [R](https://www.r-project.org/), ~~45~~ ~~40~~ ~~39~~ 38 bytes
Or **[R](https://www.r-project.org/)>=4.1, 31 bytes** by replacing the word `function` with `\`.
```
function(n,k=1:n)any(c("",k[!n%%k])>n)
```
[Try it online!](https://tio.run/##BcFbCoMwEAXQ72YXCsIMXAqTSdUIdiOlHyE0KEpqH1JcfXrOu6SxpD3H7/zMlLGMMmQO@aBIdY3lVuWmWe58zVwSaatsErmejQnren689rDSb5rjRNUnbNt6kAxOkZhhTpEEFgqHC1p06OEhAlFIB/GwFlZhW1gPFahCHbSD9lAPJ3DKXP4 "R – Try It Online")
Using the hint ([proof in @alephalpha's answer](https://codegolf.stackexchange.com/a/237310/55372)).
Outputs `FALSE` for digit small number and `TRUE` otherwise.
Converts list of divisors `k[!n%%k]` to `character` by prepending empty string. Then compares the vector with `n` (casted implicitly to `character`); `"">n` is always `FALSE`.
---
Without the hint:
### [R](https://www.r-project.org/), 55 bytes
Or **[R](https://www.r-project.org/)>=4.1, 48 bytes** by replacing the word `function` with `\`.
```
function(n,k=1:n,d=k[!n%%k],`-`=nchar)all(-d+-(n/d)>-n)
```
[Try it online!](https://tio.run/##DcnRCoJAEAXQ5/YvehBm6FrMzqauYD8SgaItirKZJdHXW@f1LFuotrDG9j08IkWMlZQRXTVe9zFJxhvqtK5i2zcLN9NEaXdIKZ46vqSRt0CaKZtArmBj/n@8P9dmok8/tD29mnmeviSlUwRmmF1LAguFwxkZchTwEIEoJId4WAursBmshwpUoQ6aQwuohxM4Zd5@ "R – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~16~~ ~~11~~ 10 bytes
```
KḂZƛṅL;?Lc
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=K%E1%B8%82Z%C6%9B%E1%B9%85L%3B%3FLc&inputs=28&header=&footer=)
Hmm yes ~~Jelly~~ 05AB1E porting goes brr. Outputs `0` for digit small, `1` for everything else.
## Explained
```
KḂZƛṅL;?Lc
K # factors_of(input)
Ḃ # that, and that reversed
Z # zip those two -> pairs of factors that have product = input
ƛṅL; # join each on spaces and take lengths
?L # input length
c # is in that list?
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), ~~12~~ 7 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
─░s┤l¡Þ
```
Outputs `1` if it's a digit small number, `-1` if not.
[Try it online.](https://tio.run/##y00syUjPz0n7///RlIZH0yYWP5qyJMf28Lz//w25jLiMuUy4TLkMDbiMgAgoYMRlZMxlZMJlZMplbGYMAA)
Almost halved the byte-count by using the hint.
**Original 12 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) answer without using the hint:**
```
─_x^mÆy£l£>╓
```
Outputs `1` if it's a digit small number, `0` if not.
[Try it online.](https://tio.run/##y00syUjPz0n7///RlIb4irjcw22VhxbnHFps92jq5P//DbmMuIy5TLhMuQwNuIyACChgxGVkzGVkwmVkymVsZgwA)
**Explanation:**
```
─ # Get a list of divisors from the (implicit) input-integer
░ # Convert each integer to a string
s # Sort this list of strings lexographically
┤ # Pop the last item (unfortunately without popping the remainder-list)
l # Push the input as string
= # Check that it's equal to this integer
# (if not, it implicitly indices since it's a string, resulting in -1)
Þ # Discard everything from the stack except the top (to get rid of the
# remainder-list)
# (after which the entire stack is output implicitly as result)
─ # Get a list of divisors from the (implicit) input-integer
_ # Duplicate this list
x # Reverse the copy
^ # Zip the two lists together, creating pairs
m # Map over these strings,
Æ # using five characters as inner codeblock:
y # Join the pair together to a string
£ # Pop and push its length
l£ # Push the length of the input (as string) as well
> # Check if the length is larger than the input-length
╓ # After the map: pop and push its minimum to check if any were falsey
# (after which the entire stack is output implicitly as result)
```
[Answer]
# JavaScript (ES6), 45 bytes
Expects \$n\$ as a string. Works in theory up to \$n=99999999999\$ (although the call stack will overflow way before that).
```
f=(n,k)=>k>n||!n[(k+[n/k]).length-1]&f(n,-~k)
```
[Try it online!](https://tio.run/##FYxBCoMwEAC/kl6aXdQt0l4j9B0iJdhoY@JGYigUpF9P08NchmEW/db7GO2WGg5Pk/OkgGuHqnMdH8eJe3BVzxc3IHnDc3o17XCeStN8HeYx8B68IR9m6InoHqP@wO2KA616A3jUglGoTrCoRFuQEmmyPpkI/PflhEhLsAyyloj5Bw "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), ~~35~~ 33 bytes
Using [alephalpha](https://codegolf.stackexchange.com/q/237308/58563)'s method is significantly shorter.
Expects \$n\$ as a string. Returns \$0\$ for *true* or \$1\$ for *false*.
```
f=(n,k)=>k>n?0:[k]>n>n%k|f(n,-~k)
```
[Try it online!](https://tio.run/##FczBCgIhEIDhV7FDOEPuUNQp0Og5liVk03C1cXGXIIhe3ezwX77DP9mXXcYS5rXjfHe1eg2sImoTDV/25z4Ohg1v48c3774R65h5yclRyg/oiehain3D6YgDPe0McFOCUWgjWOzEoSUlkg9pdQX475u2QqQpBwapJGL9AQ "JavaScript (Node.js) – Try It Online")
[Answer]
# TI-Basic, 40 bytes
```
Input N
max(1,seq(Inot(fPart(N/I)),I,1,N
min(int(log(Ans))+int(log(N/Ans))≥int(log(N
```
Output is stored in `Ans` and displayed. Outputs `1` for digit small numbers and `0` for others.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 52 bytes
```
.+
*
Lv$`(_+)$(?<=^(\1)+)
$.=,$.1$#2
+`.,.
,
A`\d
^$
```
[Try it online!](https://tio.run/##Dc07asNAGADhfq7hNUiRWPZ/7AsijCs3OYJxFLCLNCmM8fUVHWC@eT5ev38/sh2Hy7rFiQ@@3mEdvqcxDKfP5TZcZZxGQlzmECUclGmNc2TmvF7v3MK2CYrhZAqVRkcSIogihjiSkYJUpCEdTejeKGqooxktaEUb2rGECbaThjmWsYJVrGEdT7jgiu9HxzNe8Io3vJPTPw "Retina – Try It Online") Link includes test cases. Explanation:
```
.+
*
```
Convert to unary.
```
Lv$`(_+)$(?<=^(\1)+)
```
For each pair of factors of the input...
```
$.=,$.1$#2
```
... convert the input back to decimal and append the two factors.
```
+`.,.
,
```
For each pair of factors, check whether this is a digit small factorisation.
```
A`\d
```
Delete all factorisations that were digit small.
```
^$
```
Check that there are no factorisations left.
[Answer]
# APL+WIN, ~~49~~ 40 bytes
Prompts for integer. 1 = true, 0 = false.
```
×/(+/⍴¨⍕¨v,n÷v←↑⌽(0=m|n)/m←⍳⌊n*.5)>⍴⍕n←⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3t/@Hp@hra@o96txxa8ah36qEVZTp5h7eXAeUftU181LNXw8A2tyZPUz8XJNK7@VFPV56WnqmmHVADUHkeSLRv6n@gSVz/07hMLLjSuIzNjLm4AA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 6 bytes
```
ÆDDṀḌ=
```
[Try it online!](https://tio.run/##y0rNyan8//9wm4vLw50ND3f02P4/3H6s/f9/ExMA "Jelly – Try It Online")
-7 bytes (50%!) thanks to Kevin Cruijssen!
-1 byte thanks to ovs!
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
¥â ñs Ì
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=peIg8XMgzA&input=WzEsMiwzLDQsNSw2LDcsOCw5LDEwLDExLDEyLDEzLDE0LDE1LDE2LDE3LDE4LDE5LDIwLDIxLDIyLDIzLDI0LDI1LDI2LDI3LDI4LDI5LDMwLDMxLDMyLDMzLDM0LDM1LDM2LDM3LDM4LDM5LDQwLDQxLDQyLDQzLDQ0LDQ1LDQ2LDQ3LDQ4LDQ5XQpbMSwyLDMsNCw1LDYsNyw4LDksMTEsMTMsMTcsMTksMjIsMjMsMjYsMjksMzEsMzMsMzQsMzcsMzgsMzksNDEsNDNdCi1m)
* port of @Kevin Cruijssen answer.
```
¥ - input equal?
Ì - last element of
â - divisors of input
ñs - sorted lexicographically
```
[Answer]
# Zsh, ~~118~~ 94 bytes
```
for i ({1..$1})(($1%i))||a+=($i);for e ($a)for f ($a)[[ $#e+$#f -le $#1 && e*f -eq $1 ]]&&<<<0
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhY349LyixQyFTSqDfX0VAxrNTU0VAxVMzU1a2oStW01VDI1rUEKUhU0VBI1Qaw0MCs6WkFFOVVbRTlNQTcnFcg2VFBTU0jVAnJTCxVUDBViY9XUbGxsDCC2QC1bEm1iEAtlAwA)
*Thanks to @pxeger for saving 24 bytes!*
My first Zsh answer, uses the obvious solution. Outputs 0s if the number is *not* digit-small, nothing if it is. 99% sure there exists a shorter solution.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes
```
Nθ⬤…·¹θ∨﹪θι‹Lθ⁺LιL÷θι
```
[Try it online!](https://tio.run/##NYvLCsIwEEX3fkWWU4hg110JbgJVi3@QpkMbGCfm@ftpNXhX93XMpoNxmmpV/Mnpkd8zBvDdcJqC5QRXIlBsKEdb8KV5Reil8J0UzwB3t2Ry4KWwRzFijDAir2mD72E6oH9u@88qTjdb7IKNaxpq7S/1XGgH "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for digit small, nothing if not. Explanation:
```
Nθ Input `n` as a number
…·¹θ Inclusive range from `1` to `n`
⬤ All values satisfy
ι Current value
﹪ Does not divide
θ Input `n`
∨ Logical Or
θ Input value
L Length
‹ Is less than
ι Current value
L Length
⁺ Plus
θ Input `n`
÷ Integer divide
ι Current value
L Length
Implicitly print
```
[Answer]
# Lua 5.1, 60 bytes
```
n=...for x=1,n do c=c or n%x<1 and#(x..n/x)<=#n end print(c)
```
Takes a number from command line arguments, prints `false` if the number fits the definition, otherwise prints `true`.
The algorithm simply checks if there is any number `a` up to `n` that is a factor of `n` and whose string concatenation with `b=n/x` is longer than string `n`; if yes, switch the output to `true` (does not fit the definition).
[Answer]
# [Excel](https://support.microsoft.com/en-us/office/overview-of-formulas-in-excel-ecfdc708-9162-49e8-b993-c311f47ca173), 73 bytes
```
=LET(a,SEQUENCE(A1^0.5),b,FILTER(a,MOD(A1,a)=0),MIN(LEN(b&A1/b))>LEN(A1))
```
[Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnWgLkA8xc5MQj0N6?e=FNTa3q)
Works for n < 1,099,513,724,929 = (2^20 + 1) ^ 2. You could get it down to 69 bytes by removing ^0.5; but it would only work for n <= 2^20.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~77~~ \$\cdots\$ ~~74~~ 70 bytes
```
r;d;s(n){n=log10(n);}f(n){for(r=d=1;++d<n;)r&=n%d||s(d)-~s(n/d)>s(n);}
```
[Try it online!](https://tio.run/##rVHRTsIwFH3nK26WYDbowtoOlZTxYvwK4YGsHRKhI@0SFwE/3XmGY1EfjUvb9Jx7zu29u3m8yfOmcUorH9roaLNdueEJrupctERRutBlOuNqPNZzqyJ3k9mhPp18qKP4HaaJjhb@Ymi2tqL9emvDiI4DwtcSlfGVf1pRRkfOSDCSjFJGU0a3jO4Y3TOaMeKIcUQ4GA4sIBTAAiIBLBGXwBJWCY2ETYJPwaetL8GGhyPOkZvDx6ER4EX7LngBXsArWi942RYDTkKbAqfirPqyTX0weWV0X/l/reQPq6srL62vKH9euxFOk78Y91VesKwfxbKePWBPA0bfsQw6N0ZJYdva1mpTw5ao7jonv30zZRFem44mHTHqGUXj8UV9nW0/X2T6mvElvFJ9tAirSP3QGmj7H/tbfnCQFGEw1BQvCOfQLy2aqRg51vfrssysurTnwbn5yIvdeuOb@LWJd/tP "C (gcc) – Try It Online")
*Saved 2 bytes thanks to [AZTECCO](https://codegolf.stackexchange.com/users/84844/aztecco)!!!*
*Saved 4 bytes thanks to [upkajdt](https://codegolf.stackexchange.com/users/41374/upkajdt)!!!*
Inputs positive integer \$n\$.
Returns \$1\$ if \$n\$ is a digit small number or \$0\$ otherwise.
[Answer]
# [Python 2](https://docs.python.org/2/), 54 bytes
```
f=lambda n:max(`x`for x in range(1,n+1)if n%x==0)==`n`
```
[Try it online!](https://tio.run/##BcFBCoAgEAXQq8wmcKhFJrQI5i4aNSXkV6SFnd7eK997Zyy9qzwh7UcgbCk045vXXKlRBNWA6zR2wmg5KmFoIjOLePheasRr1LjVMfcf "Python 2 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 42 bytes
```
->n{(1..n).all?{|x|n%x>0||x.to_s<=n.to_s}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWsNQTy9PUy8xJ8e@uqaiJk@1ws6gpqZCryQ/vtjGNg9M19b@L1AAKTQ0MNDUK07NSU0uASlOi66Irf0PAA "Ruby – Try It Online")
[Answer]
## With hint
# [Burlesque](https://github.com/FMNSSun/Burlesque), 10 bytes
```
Jfcqb0>m==
```
[Try it online!](https://tio.run/##SyotykktLixN/W9oYFD93ystuTDJwC7X1vZ/rZv/fwA "Burlesque – Try It Online")
```
J # Duplicate input
fc # Factors
qb0>m # Maximum lexicographically
== # are Equal
```
## Without hint
# [Burlesque](https://github.com/FMNSSun/Burlesque), 26 bytes
```
PppPfcJ<-z[m{imlnpPln.>}r&
```
[Try it online!](https://tio.run/##SyotykktLixN/W9oYFD9P6CgICAt2ctGtyo6tzozNyevICAnT8@utkjtf62b/38A "Burlesque – Try It Online")
```
Pp # Push input to store
pP # Retrieve input
fc # Factors (of input)
J # Duplicate factors
<-z[ # Zip list of factors with reversed list of factors
m{ # Map (for each pair of factors)
im # Concat factors
ln # Total number of digits
pPln # Digits in input
.> # Greater than (that of factors)
}
r& # For all factors
```
[Answer]
# [Desmos](https://desmos.com/calculator), ~~146~~ ~~164~~ 89 bytes
*Had to add 18 bytes because the previous version only supported numbers up to 10000. Now it should support up to numbers around \$10^{10}\$. Thanks [@fireflame241](https://codegolf.stackexchange.com/users/68261/fireflame241) for helping me with this change.*
***EDIT**: Turns out, the change mentioned above actually allowed me to essentially halve the number of bytes in my code...*
\$f(n)\$ returns 0 if \$n\$ is a digit small number, 1 if it is not.
```
a=[1...sqrtn]
b=a[mod(n,a)=0]
g(l)=floor(logl)
f(n)=\sign(\total(\{g(b)+g(n/b)<g(n),0\}))
```
[Try It On Desmos!](https://www.desmos.com/calculator/o9yvnub2rg)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/ycibiivzht)
Probably not the best way to do it, but for now I think it is good enough. Uses the formula given in the problem.
]
|
[Question]
[
>
> This is an answer-dependent challenge! The order of answers matters, and your exact task depends on the last answer that was posted. You might want to [sort the answers *by oldest*](https://codegolf.stackexchange.com/questions/44966/the-jigsaw-code-puzzle?answertab=oldest#tab-top).
>
>
>
Let's piece together some code! Here are 1920 random (printable ASCII) characters. Think of them as a big heap of unsorted jigsaw puzzle pieces still in the box:
```
L-^=v^Ej2tW8OxNOIecSt4m}tji2O%YRJ;PJ!M|0*oO77$*Rs&2*<c"KI7e%FY^?I=];Y@`x)u)IBk%_a#<E6<yv5O*$kL):
KNGq)2Wa%b)j."(6U|{[UY@`lrCSJ`u0RHX!1z7f,v}n=GvRgkrEZ=YT:4H44bz]iC<](:+FF?Ay'vX~h5QMF)0vaXk1sk@p
Zj).{+l;PBKHABvEP%FnSw>u<_-4B^A>I8Kay&5]vXZJ{fCF]UVZ<!ZpOI$7\Y%`@:%H3wPsX-`/l]ZZ?Q/d`\M<T@'t]zip
{[ovg:6EpCT&'+vU4Heb^;}0AV|?<}M0rAH/^DL"RkT~%$[VUlM]-&We4(P=66},hL~;a`:$'yty.W[g2OWcL~b:Ryj0*eN<
;&-n[F1F=oh0k[NI!xS"]pA@Y;K}'=ekG5yda8J$+`N;:FIx:l,f_LT@sV[]HF@2*vl?|q"GL1j&%e(CyYPqY%3W|@`z}]bp
4_'1Nx{"G2&j6$UWt_#%`sTt2xC}s1P8J<gV24_RWge/aMuyVOjz=zS!1i2s@`Q#@^~@W/[[email protected]](/cdn-cgi/l/email-protection):g9?J^p;7ju?B\yC5
x,ZApKS5G4}kx_iM)f4/|su>=[{XSV#{,j5Qn3U.v5LF;HXs%DYm4'+efmU;\}f6j$SFCRC`Gsd37:'3$q=bs;lvsW0Yj^:-
I[94@I|.IpR=}4KB4Z0G4>8PR29'L?n\gk,*4X[-%T`\FC)jj0jl_x<xL8E:G2-"3tT8&E}"sE+SH[7jR%@V)a{!m8K>.rAO
2[dq7GX9nrz8p4}^2mn@q|dF%<.Tl8)Dk?O.<UoE(a*k_=4+u!h$^bVd:$jS#EHFh@Z=y=ib^~/~lEJ^SQ3E_t#&^IOov7v8
~j#I#OHgxg{DZDyCsq-(GVq}HbiG,JV?eJ~5wJ;bSt@;3LI!2(6gIT92>}`_dw;YF@ccTIEz\Gu@2(}J2I1"S{R(2niIYPp9
8A3iiP[*!SH2*SN8'`V?w4Ufx2H*Az%{}FlUdH31TJ5{:ge^N91^;9Gj`Uqf'$_|8P"kHR1w.(ASwmN)U-~q"[XcWbqPnns=
d.ZoPJ}$Xc2lA>HN28`(d0y+UAr*sQ=?KE07=\FsVN(#?&hRabS%BVI#<`O$o#4x5ZFFLGDcA4t?&Eh~Z$oBWwNSNv`^;vO'
2&9egng~L#\QkfMG?S/n@%-VA[?f9K&3"V%P#Sv0!D<,GV:Z;3c&zFe^k&^0b7fAjvrbMc^Lq7k$h=YL<h7<0\NK>~Q=uUv)
4cI$.'b-RVS-=rom:=8QR=c>9am-^5F[XGv>E/>|]~\']3{r{kTc?ee1v=;I7]52#NE)~A;}!z>5?hi{5<9FtWH6{VO_Y-Jy
Mw>{l8n#mD,kl'8cG^.7sy=QqU-3~SKGs5(.Ta]:-Vfr'NS$o*q:w6e$&7spk3{CFT'l_hGY0-0Xui*5i^0^fO@6?2IdCn_C
lPKaJ6]0t!u>v8<d'Vby]8kEHh04p(YI)&7w82BrGB3PkI,s+%7ux5)gau`G!8F8hLa4[lfD55Xf3Hqy*-K,?;2'fxH3JWYE
Z.[N`:[K:CY@TzKX4TMXsm{Xbd:B3)Gy[mlwnC$>)z`:k=C\0ho/v{57#+2,*%]>p~vI2^C:2DebJR>.ESw^wd2N<~]O9sOQ
`_yvIw&Ryf%JgT@W(G1wfU3.4G3U}x1jKJzJY\S9n$2~P;F}*eT9UXcTNBTrTs>~0v_Oi.y8ofX6i5u$;'^"q][QhTb*gO[U
n'R0"v1r+9fv;5G7Bg=D:c*a=1@[}7}dYOO{Mz2&@6`jnNq.QcBDM9Dd=R.*=MqZ93#'{AJJFqx<{qb':B!H8ig1L%T\Vuc"
(h$i3`,scX'hqpbw"=nY`*Lu:h1wR{+-`\^3cQkIWfq)3?&p;~pvDW$o7\O|R6rB2{PX.s#G6A.s<OA_,TI_b*&lO@L3KrQv
```
The "floor" we're puzzling on is initially just a 96x20 grid of spaces (code point 0x20). Each answer may move around adjacent blocks of pieces, and choose up to 10 puzzle pieces (characters) and add them to the puzzle to create a new program. That program must print the number of your answer (numbered sequentially, starting from 1).
## Answering
The key thing to understand about this challenge is that **only one person can answer at a time and each answer depends on the one before it**.
There should never be two answers with the same number **N**. If two people happen to simultaneously answer for some **N**, the one who answered later (even if it's a few seconds difference) should graciously delete their answer.
To make this run a bit smoother, try to stick to the following steps when posting your answer:
* Make sure that someone has independently verified the correctness of the previous answer (and left a corresponding comment).
* Take the previous "puzzle floor" and "box of pieces". You may move any adjacent block of characters on the puzzle floor around freely *as a unit* (characters are adjacent if they touch along the horizontal or vertical direction). Adjacent blocks cannot be split up again. Examples on a 5x4 grid:
```
Last answer: Valid: Invalid:
|a bc| |d g | |a bc| | bc | |a bc|
| d e | |fa bc| |d e | -or- |d e | -or- | e |
| f g| | e | | f g| |f g | |df g |
| h | |h | | h | | h | | h |
```
In the valid example, `a` was moved one step down and right. The `df` block was moved to the top left. The `bce` block was moved down by 1. The `g` was move two up and one to the left. The `h` block was moved all the way to the left.
In the first invalid example `df` has been separated. In the second, `a` has been removed. In the third, `df` has been rotated.
Next, remove **at least 1 and up to 10** characters from the "box of pieces" and choose that many spaces on the "puzzle floor", which you'll replace by those characters. This is your submitted program. Please include both the new "puzzle floor" and "box of pieces" in your answer.
* Post your answer in the following format:
```
# N. [Language], [number of blocks moved], [number of pieces added]
[grid that is your program]
### Remaining pieces:
[grid of remaining characters]
[notes, explanation, observations, whatever]
```
where `N` is the number of your answer.
**This is absolutely vital to the challenge!** I've provided a dashboard tool for the challenge to help with the bookkeeping, and it relies on the above template. (See bottom of the post.)
* Please include the vertical bars at the sides of puzzle floor, because otherwise, Stack Exchange won't display empty lines. These two columns are never to be considered part of the code.
* Another user should now review your submission and leave a comment "Correctness verified" if your answer follows all the rules (see below). If it doesn't, they should leave a comment pointing out any flaws. You've then got *15 minutes* to fix those issues. If you don't, your answer will be deemed invalid, should be deleted, and someone else may post a follow-up answer to the previous one. (If this happens, you're free to submit a new answer any time.)
These regulations may seem rather strict, but they are necessary to avoid invalid answers somewhere up the chain.
## The Rules
* **A user may only submit one answer per 4 hour period.** (This is to prevent users from constantly watching the question and answering as much as possible.)
* A user may not submit two answers in a row. (e.g. since I submitted answer 1 I can't do answer 2, but I could do 3.)
* **No language may be used more than once!** Different versions of the same language count as the same language. Languages count as distinct if they are traditionally called by two different names. (There may be some ambiguities here but don't let that ruin the contest.)
* **Do not edit answers that have been verified.**
* Should a mistake be discovered *earlier* in the chain (i.e. after follow-up answers have been posted), the offending answer should be deleted. *However*, all answers that have been posted since should *not* be changed to reflect this.
* Your program has to print `N`, the number of your answer, to STDOUT or closest alternative. It has to be a full program and must not assume a REPL environment.
* You may or may not print a trailing newline.
* Let **M** be the number of *blocks* you moved for your answer (no matter how far) and **P** the number of characters you added to the puzzle floor, the score of your answer will be **10 + N - M - P**. As a 5x4 example, if your answer changed the puzzle floor as follows
```
|a bc| |a ij |
| d e | --> | d bc|
| f g| | f eg|
| h | | h k|
```
your score would be **10 + N - 2 - 3 = N + 5**, because two blocks were moved (`h` and `bce`) and three characters were added (`i`, `j` and `k`).
* **The winner** will be the user who accumulates the greatest number of points across their answers. In case of tie, the user with the latest answer wins. I will accept the winner's latest answer.
* In the unlikely event that all characters will be used up, the challenge ends.
## Dashboard
Here is a little Dashboard tool, which should help with the necessary bookkeeping for this type of challenge.
It displays the current status of the challenge - in particular, if there are conflicting answers, if an answer needs to be verified, or if the next answer can be posted.
It also produces a list of all languages that have been used, as well as a leaderboard of all users. Please stick to the answer format above, so the dashboard can read out the relevant strings from your answers. Otherwise you might not be included in the leaderboard.
Please let me know ([ideally in chat](http://chat.stackexchange.com/rooms/240/the-nineteenth-byte)) if you spot any bugs or have some ideas how the usefulness of the tool could be improved.
```
function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentsUrl(e,t){return"http://api.stackexchange.com/2.2/answers/"+e+"/comments?page="+t+"&pagesize=100&order=asc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){$.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(e){answers.push.apply(answers,e.items);if(e.has_more)getAnswers();else{page=1;getFinalComments()}}})}function getFinalComments(){answers=answers.filter(shouldHaveHeading);answers=answers.filter(shouldHaveScore);console.log(answers);$.ajax({url:commentsUrl(answers[0].answer_id,page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(e){comments.push.apply(comments,e.items);if(e.has_more)getAnswers();else process()}})}function shouldHaveHeading(e){var t=false;try{t|=/^(#|<h).*/.test(e.body_markdown);t|=["-","="].indexOf(e.body_markdown.split("\n")[1][0])>-1}catch(n){}return t}function shouldHaveScore(e){var t=false;try{t|=HEADER_REG.test(e.body_markdown.split("\n")[0])}catch(n){}return t}function findDuplicates(e){var t=false;var n={};e.forEach(function(e){var r=e.body_markdown.split("\n")[0].match(NUMBER_REG)[0];if(n[r])t=t||r;n[r]=true});return t}function hasBeenVerified(e,t){var n=false;t.forEach(function(t){n|=/correctness verified/i.test(t.body_markdown)&&e!=t.owner.user_id});return n}function userTimedOut(e){return NOW-e.creation_date*1e3<MSEC_PER_ANSWER}function getAuthorName(e){return e.owner.display_name}function getAnswerScore(e,t,n){e=parseInt(e);t=parseInt(t);n=parseInt(n);return 10+e-t-n}function process(){$("#last-user").append(answers[0].owner.display_name);var e=answers.slice(1).filter(userTimedOut).map(getAuthorName).join(", ");if(e)$("#timed-out-users").append(e);else $("#timed-out-notice").hide();var t=answers[0].body_markdown.split("\n")[0].match(NUMBER_REG)[0];var n=findDuplicates(answers);if(n){var r=$("#status-conflict-template").html();$("#challenge-status").append(r.replace("{{NUMBER}}",n));$("#challenge-status").addClass("conflict")}else if(!hasBeenVerified(answers[0].owner.user_id,comments)){var r=$("#status-verification-template").html();$("#challenge-status").append(r.replace("{{NUMBER}}",t));$("#challenge-status").addClass("verification")}else{var r=$("#status-next-template").html();$("#challenge-status").append(r.replace("{{NUMBER}}",t).replace("{{NEXT}}",parseInt(t)+1));$("#challenge-status").addClass("next")}var i={};var s={};var o=[];answers.forEach(function(e){var t=e.body_markdown.split("\n")[0];var n=$("#answer-template").html();var r=t.match(HEADER_REG)||[0,-1,"",0,0];var u=r[1];var a=r[2];var f=r[3];var l=r[4];var c=getAnswerScore(u,f,l);var h=getAuthorName(e);n=n.replace("{{NAME}}",h).replace("{{NUMBER}}",u).replace("{{LANGUAGE}}",a).replace("{{MOVED}}",f).replace("{{ADDED}}",l).replace("{{SCORE}}",c).replace("{{LINK}}",e.share_link);n=$(n);$("#answers").append(n);i[h]=(i[h]||0)+c;s[h]=(s[h]||0)+1;o.push({lang:a,link:e.share_link})});var u=[];for(var a in i)if(i.hasOwnProperty(a)){u.push({name:a,numAnswers:s[a],score:i[a]})}u.sort(function(e,t){return t.score-e.score});var f=1;u.forEach(function(e){var t=$("#user-template").html();t=t.replace("{{NAME}}",e.name).replace("{{NUMBER}}",f++).replace("{{COUNT}}",e.numAnswers).replace("{{SCORE}}",e.score);t=$(t);$("#users").append(t)});o.sort(function(e,t){return e.lang.localeCompare(t.lang)});o.forEach(function(e){var t=$("#lang-template").html();t=t.replace("{{LANGUAGE}}",e.lang).replace("{{LINK}}",e.link);t=$(t);$("#lang-list").append(t)})}var QUESTION_ID=44966;var ANSWER_FILTER="!*cCFgu5yS6BFQP8Z)xIZ.qGoikO4jB.Ahv_g-";var COMMENT_FILTER="!)Q2B_A497Z2O1kEH(Of5MUPK";var HOURS_PER_ANSWER=4;var MSEC_PER_ANSWER=HOURS_PER_ANSWER*60*60*1e3;var NOW=Date.now();var answers=[],comments=[],page=1;getAnswers();var NUMBER_REG=/\d+/;var HEADER_REG=/(\d+)[.]\s*([^,]*[^,\s])\s*,[^,\d]*(\d+)[^,\d]*,[^,\d]*(\d+)/
```
```
body { text-align: left !important} #challenge-status { font-weight: bold; padding: 10px; width: 800px; } #blocked-users { padding: 10px; width: 800px; } .conflict { background: #994343; color: white; } .verification { background: #FFDB12; } .next { background: #75FF6E; } #last-user, #timed-out-users { font-weight: bold; } #answer-list { padding: 10px; width: 350px; float: left; } #leaderboard { padding: 10px; width: 280px; float: left; } #languages { padding: 10px; width: 130px; 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="challenge-status"> </div> <div id="blocked-users"> User <span id="last-user"></span> has posted the last answer, and may not post the next one. <div id="timed-out-notice"><span id="timed-out-users"></span> have answered within the last four hours and may not answer again yet. (If a user appears in this list twice, they must have answered twice within four hours!)</div> </div> <div id="answer-list"> <h2>List of Answers (newest first)</h2> <table class="answer-list"> <thead> <tr><td>No.</td><td>Author</td><td>Language</td><td>M</td><td>P</td><td>Score</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <div id="leaderboard"> <h2>Leaderboard</h2> <table class="leaderboard"> <thead> <tr><td>No.</td><td>User</td><td>Answers</td><td>Score</td></tr> </thead> <tbody id="users"> </tbody> </table> </div> <div id="languages"> <h2>Languages</h2> <table class="languages"> <tbody id="lang-list"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{NUMBER}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{MOVED}}</td><td>{{ADDED}}</td><td>{{SCORE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="user-template"> <tr><td>{{NUMBER}}</td><td>{{NAME}}</td><td>{{COUNT}}</td><td>{{SCORE}}</td></tr> </tbody> </table> <table style="display: none"> <tbody id="lang-template"> <tr><td><a href="{{LINK}}">{{LANGUAGE}}</a></td></tr> </tbody> </table> <div id="status-conflict-template" style="display: none"> There is more than one answer with number {{NUMBER}}!<br> Please resolve this conflict before posting any further answer. </div> <div id="status-verification-template" style="display: none"> Answer {{NUMBER}} has not been verified!<br> Please review the answer and post a comment reading "Correctness verified." on the answer if it is valid. Note that this has to be done by a different user than the author of the answer! </div> <div id="status-next-template" style="display: none"> Answer {{NUMBER}} has been verified!<br> You may now post answer {{NEXT}}. </div>
```
### Useful scripts
Here are two CJam scripts for your convenience. You can run them in the [online interpreter](http://cjam.aditsu.net/).
1. To remove the first and last column from the puzzle floor (to get the actual code), paste it into STDIN, and run `qN/1f>Wf<N*`.
2. To pad your code out to a 96x20 rectangle and add the columns of vertical bars around it, run `qN/La20*+20<{96S*+96<'|\+'|+}%N*` on your code.
3. To find out which characters were removed from the box of pieces between two answers, paste both of them into STDIN (without an empty line in between), and run
```
qS-N/20/{:+}%94,\f{\33+c_@\f/:,~-_0<{N"Added character: "@;@N}{*}?}
```
It will also show if characters were *added* (not how many though).
If someone wants to reimplement these as Stack Snippets, I'm happy to add them to this post.
[Answer]
# 7. GolfScript, 1 moved, 1 added
```
| 6# `.3i !|
|) :" |
| |
| # $> 0 << |
| |
| |
| |
|print 02 ** 2 |
| |
| |
| |
| |
| |
| :Disp 5 |
| |
| |
| |
| |
| |
| |
```
### Remaining Pieces:
```
L-^=v^Ej2tW8OxNOIecSt4m} j O%YRJ;PJ!M|0*oO77*Rs&2*<c"KI7e%FY^?I=];Y@`x)u)IBk%_a#<E6<yv5O*$kL):
KNGq)2Wa%b)j"(6U|{[UY@`l CSJ`u0RHX!1z7f,v} =GvRgkrEZ=YT:4H44bz] C<](:+FF?Ay'vX~h5QMF)0vaXk1sk@p
Zj.{+l;PBKHABvEP%FnSw>u_-4B^AI8Kay&5]vXZJ{fCF]UVZ<!ZpOI$7\Y%@:%HwPsX-`/l]ZZ?Q/d`\M<T@'t]zip
{[ovg:6E CT&'+vU4Heb^;}0AV|?}M0rAH/^DL"RkT~%$[VUlM]-&We4(P=66},hL~;a`:$'yty.W[g2OWcL~b:Ryj0*eN<
;&-n[F1F=oh0k[NI!xS"]pA@Y;K}'=ekG5yda8J$+`N;:FIx:l,f_LT@sV[]HF@2*vl?|q"GL1j&%e(CyYPqY%3W|@`z}]bp
4_'1Nx{G2&j6$UWt_#%`sTt2xC}s1P8J<gV24_RWge/aMuyVOjz=zS!1i2s@`Q#@^~@W/[[email protected]](/cdn-cgi/l/email-protection):g9?J^p;7ju?B\yC5
x,ZApKS5G4}kx_iM)f4/|su>=[{XSV#{,j5Qn3U.v5LF;HXs%DYm4'+efmU;\}f6j$SFCRC`Gsd37:'3$q=bs;lvsW0Yj^:-
I[94@I|.IpR=}4KB4ZG4>8PR29'L?n\gk,*4X[-%T`\FC)jj0jl_x<xL8E:G2-"3tT8&E}"sE+SH[7jR%@V)a{ m8K>.rAO
2[dq7GX9nrz8p4}^ mn@q|dF%<.Tl8)Dk?O.<UoE(a*k_=4+u!h$^bVd:$jS#EHFh@Z=y=ib^~/~lEJ^SQ3E_t#&^IOov7v8
~j#I#OHgxg{ZDyCsq-(GVq}HbiG,JV?eJ~5wJ;bSt@;3LI!2(6gIT92>}`_dw;YF@ccTIEz\Gu@2(}J2I1"S{R(2niIYPp9
8A3iP[*!SH2*SN8'`V?w4Ufx2HAz%{}FlUdH31TJ5{:ge^N91^;9Gj`Uqf'$_|8P"kHR1w.(ASwmN)U-~q"[XcWbqPnns=
d.ZoPJ}$Xc2lA>HN28`(dy+UArsQ=?KE07=\FsVN(#?&hRabS%BVI <`O$o 4x5ZFFLGDcA4t?&Eh~Z$oBWwNSNv`^;vO'
2&9egng~L#\QkfMG?S/n@%-VA[?f9K&3"V%P#Sv0!D<,GV:Z;3c&zFe^k&^0b7fAjvrbMc^Lq7k$h=YL<h7<0\NK>~Q=uUv)
4cI$.'b-RVS-=rom:=8QR=c>9am-^5F[XGv>E/>|]~\']3{r{kTc?ee1v=;I7]52#NE)~A;}!z>5?hi{5<9FtWH6{VO_Y-Jy
Mw>{l8n#mD,kl'8cG^.7sy=QqU-3~SKG5(.Ta]:-Vfr'NS$o*q:w6e$&7spk3{CFT'l_hGY0-0Xui*5i^0^fO@6?2IdCn_C
lPKaJ6]0t!u>v8<d'Vby]8kEHh04p(YI)&7w82BrGB3PkI,s+%7ux5)gau`G!8F8hLa4[lfD55Xf3Hqy*-K,?;2'fxH3JWYE
Z.[N`[KCY@TzKX4TMXsm{Xbd:B3)Gy[mlwnC$>)z`:k=C\0ho/v{7#+2,*%]>~vI2^C:2DebJR>.ESw^wd2N<~]O9sOQ
`_yvIw&Ryf%JgT@W(G1wfU3.4G3U}x1jKJzJY\S9n$2~P;F}*eT9UXcTNBTrTs>~0v_Oi.y8ofX6i5u$;'^"q][QhTb*gO[U
n'R0"v1r+9fv;5G7Bg=D:c*a=1@[}7}dYOO{Mz2&@6`jnNq.QcBDM9Dd=R.*=MqZ93#'{AJJFqx<{qb':B!H8ig1L%T\Vuc"
(h$i3`,scX'hqpbw"=nY`*Lu:h1wR{+-`\^3cQkIWfq)3?&p;~pvDW$o7\O|RrB2{PX.s#G6A.s<OA_,TI_b*&lO@L3KrQv
```
`#` is a single-line comment. Then `)` increments the 6 to 7. And the unmatched `"` acts to comment out the rest of the code. If the `"` *was* matched, then `:` would assign the value `7` to whatever string comes after it, so the `:"` part is valid syntax. As an example, if you had `5:"a"`, then writing `"a"` would actually push `5` onto the stack instead of the string (that is some serious magic).
But in this case, the interpreter just stops when it finds that the quote isn't matched.
[Tested with the online interpreter.](http://golfscript.apphb.com/)
[Answer]
# 2. Prelude, 0 moved, 2 added
The program should be executed with numeric output mode.
```
|2 !|
| |
| |
| $> << |
| |
| |
| |
| 0 ** |
| 0 |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
```
**Remaining Pieces**
```
L-^=v^Ej2tW8OxNOIecSt4m}tji2O%YRJ;PJ!M|0*oO77*Rs&2*<c"KI7e%FY^?I=];Y@`x)u)IBk%_a#<E6<yv5O*$kL):
KNGq)2Wa%b)j."(6U|{[UY@`lrCSJ`u0RHX!1z7f,v}n=GvRgkrEZ=YT:4H44bz]iC<](:+FF?Ay'vX~h5QMF)0vaXk1sk@p
Zj).{+l;PBKHABvEP%FnSw>u_-4B^AI8Kay&5]vXZJ{fCF]UVZ<!ZpOI$7\Y%`@:%H3wPsX-`/l]ZZ?Q/d`\M<T@'t]zip
{[ovg:6EpCT&'+vU4Heb^;}0AV|?}M0rAH/^DL"RkT~%$[VUlM]-&We4(P=66},hL~;a`:$'yty.W[g2OWcL~b:Ryj0*eN<
;&-n[F1F=oh0k[NI!xS"]pA@Y;K}'=ekG5yda8J$+`N;:FIx:l,f_LT@sV[]HF@2*vl?|q"GL1j&%e(CyYPqY%3W|@`z}]bp
4_'1Nx{"G2&j6$UWt_#%`sTt2xC}s1P8J<gV24_RWge/aMuyVOjz=zS!1i2s@`Q#@^~@W/[[email protected]](/cdn-cgi/l/email-protection):g9?J^p;7ju?B\yC5
x,ZApKS5G4}kx_iM)f4/|su>=[{XSV#{,j5Qn3U.v5LF;HXs%DYm4'+efmU;\}f6j$SFCRC`Gsd37:'3$q=bs;lvsW0Yj^:-
I[94@I|.IpR=}4KB4ZG4>8PR29'L?n\gk,*4X[-%T`\FC)jj0jl_x<xL8E:G2-"3tT8&E}"sE+SH[7jR%@V)a{ m8K>.rAO
2[dq7GX9nrz8p4}^ mn@q|dF%<.Tl8)Dk?O.<UoE(a*k_=4+u!h$^bVd:$jS#EHFh@Z=y=ib^~/~lEJ^SQ3E_t#&^IOov7v8
~j#I#OHgxg{DZDyCsq-(GVq}HbiG,JV?eJ~5wJ;bSt@;3LI!2(6gIT92>}`_dw;YF@ccTIEz\Gu@2(}J2I1"S{R(2niIYPp9
8A3iiP[*!SH2*SN8'`V?w4Ufx2HAz%{}FlUdH31TJ5{:ge^N91^;9Gj`Uqf'$_|8P"kHR1w.(ASwmN)U-~q"[XcWbqPnns=
d.ZoPJ}$Xc2lA>HN28`(dy+UArsQ=?KE07=\FsVN(#?&hRabS%BVI#<`O$o#4x5ZFFLGDcA4t?&Eh~Z$oBWwNSNv`^;vO'
2&9egng~L#\QkfMG?S/n@%-VA[?f9K&3"V%P#Sv0!D<,GV:Z;3c&zFe^k&^0b7fAjvrbMc^Lq7k$h=YL<h7<0\NK>~Q=uUv)
4cI$.'b-RVS-=rom:=8QR=c>9am-^5F[XGv>E/>|]~\']3{r{kTc?ee1v=;I7]52#NE)~A;}!z>5?hi{5<9FtWH6{VO_Y-Jy
Mw>{l8n#mD,kl'8cG^.7sy=QqU-3~SKGs5(.Ta]:-Vfr'NS$o*q:w6e$&7spk3{CFT'l_hGY0-0Xui*5i^0^fO@6?2IdCn_C
lPKaJ6]0t!u>v8<d'Vby]8kEHh04p(YI)&7w82BrGB3PkI,s+%7ux5)gau`G!8F8hLa4[lfD55Xf3Hqy*-K,?;2'fxH3JWYE
Z.[N`:[K:CY@TzKX4TMXsm{Xbd:B3)Gy[mlwnC$>)z`:k=C\0ho/v{57#+2,*%]>p~vI2^C:2DebJR>.ESw^wd2N<~]O9sOQ
`_yvIw&Ryf%JgT@W(G1wfU3.4G3U}x1jKJzJY\S9n$2~P;F}*eT9UXcTNBTrTs>~0v_Oi.y8ofX6i5u$;'^"q][QhTb*gO[U
n'R0"v1r+9fv;5G7Bg=D:c*a=1@[}7}dYOO{Mz2&@6`jnNq.QcBDM9Dd=R.*=MqZ93#'{AJJFqx<{qb':B!H8ig1L%T\Vuc"
(h$i3`,scX'hqpbw"=nY`*Lu:h1wR{+-`\^3cQkIWfq)3?&p;~pvDW$o7\O|R6rB2{PX.s#G6A.s<OA_,TI_b*&lO@L3KrQv
```
[Answer]
# 15. Rail, 4 moved, 7 added
```
|${ 'main' \ "`.3i !|
| 9 if |
| 6 ) |
| a 0 |
| echo |
| # 12!$>{: |
| |
| 02 ** |
| |
| |
| |
| |
| |
| :Disp 56# |
| :";8<<print 10 |
| |
| |
| ' |
|} = |
|puts+11 ; + 2 |
```
### Remaining pieces
```
L-^=v^Ej2W8OxNOISt4mjO%YRJ;PJ!M|*oO77*R&2*<c"KI7e%FY^?I=];Y@`x))IBk%_a#<E6<yv5O*$kL):
KNGq)2Wa%b)j"(6U|[UY@`lCSJ`u0RHX!z7,v}=GvRgkrEZ=YT:4H44bz]C<](+FF?Ay'vX~5QMF)0vaXksk@
Zj.{l;PBKHABvEP%FnSw>u_-4B^AI8Kay&5]vXZJ{fCF]UVZ<!ZpOI$7\Y%@:%HwPsX-`/l]ZZ?Q/d`\M<T@'t]zp
{[vg:6ECT&+vU4Heb^;}0AV|?}M0rAH/^DL"RkT~%$[VUlM]-&We4(P=6},hL~;`:$yty.W[g2OWcL~b:Ryj0*eN<
&-[FF=oh0k[NI!xS"]pA@Y;K}'=ekG5yda8J$+`N;:FIx:l,f_LT@sV[]HF@2*vl?|q"GL1j&%e(CyYPqY%3W|@`z}]bp
4_'1Nx{G2&j6$UWt_#%`sTt2xC}s1P8J<gV24_RWge/aMuyVOjz=zS!1i2s@`Q#@^~@W/[[email protected]](/cdn-cgi/l/email-protection):g9?J^p;7ju?B\yC5
x,ZApKS5G4}kx_iM)f4/|su>=[{XSV#{,j5Qn3U.v5LF;HXs%DYm4'+efmU;\}f6j$SFCRC`Gsd37:'3$q=bs;lvsW0Yj^:-
I[94@I|.IpR=}4KB4ZG4>8PR29'L?n\gk,*4X[-%T`\FC)jj0jl_x<xL8E:G2-"3tT8&E}"sE+SH[7jR%@V)a{m8K>.rAO
2[dq7GX9nrz8p4}^n@q|dF%<.Tl8)Dk?O.<UoE(a*k_=4u!h$^bVd:$jS#EHFh@Z=y=ib^~/~lEJ^SQ3E_t#&^IOov7v8
~j#I#OHgxg{ZDyCsq-(GVq}HbiG,JV?eJ~5wJ;bSt@;3LI!2(6gIT92>}`_dw;YF@ccTIEz\Gu@2(}J2I1"S{R(2niIYPp9
8A3iP[*!SH2*SN8'`V?w4Ufx2HAz%{}FlUdH31TJ5:ge^N91^;9Gj`Uqf'$_|8P"kHR1w.(ASwmN)U-~q"[XcWbqPnns
d.ZoPJ}$Xc2lA>HN28`(dy+UArsQ=?KE07=\FsVN(#?&hRabS%BVI<`O$o4x5ZFFLGDcA4t?&Eh~Z$oBWwNSNv`^;vO'
2&9egng~L#\QkfMG?S/n@%-VA[?f9K&3"V%P#Sv0!D<,GV:Z;3c&zFe^k&^0b7fAjvrbMc^Lq7k$h=YL<h7<0\NK>~Q=uUv)
4cI$.'b-RVS-=rom:=QR=c>9m-^5F[XGv>E/>|]~]3{r{kTc?ee1v=;I7]52#NE)~A;}!z>5?hi{5<9FtWH6{VO_Y-Jy
Mw>{l8n#mD,kl'8cG^.7sy=QqU-3~SKG5(.Ta]:-Vfr'NS$o*q:w6e$&7spk3{CFT'l_hGY0-0Xui*5^0^fO@6?2IdCn_C
lPKaJ6]0t!u>v8<d'Vby]8kEHh04p(YI)&7w82BrGB3PkI,s+%7ux5)gau`G!8F8hLa4[lfD55Xf3Hqy*-K,?;'fxH3JWYE
Z.[N`[KCY@TzKX4TMXsm{Xbd:B3)Gy[mlwnC>)z`:k=C\0ho/v{7#+2,*%]>~vI2^C:2DebJR>.ESw^wd2N<~]O9sOQ
`_yvIw&Ryf%JgT@W(G1wfU3.4G3U}x1jKJzJY\S9n$2~P;F}*eT9UXcTNBTrTs>~0v_Oi.y8ofX6i5u$;'^"q][QhTb*gO[U
n'R0vr+9fv5G7Bg=D:c*a=1@[}7}dYOO{Mz2&@6`jnNq.QcBDM9Dd=R.*=MqZ3#'{AJJFqx<{qb':BH8ig1L%T\Vuc"
(h$i3`,scX'hqpbw"=nY`*Lu:h1wR{+-`\^3cQkIWfq)3?&p;~pvDW$o7\O|RrB2{PX.s#G6A.s<OA_,TI_b*&lO@L3KrQv
```
Here, have a `main`! >:D
[Esolangs page.](http://esolangs.org/wiki/Rail#Constants) I used the interpreter linked to at the bottom of the page.
In Rail, the instruction pointer is a train which follows tracks made out of instructions. The first line is just ignored (and unfortunately, has to contain `'main'`), so the rails start to the bottom right. Since I don't divert them the entire code goes in that direction, and is effectively just:
```
96ao#
```
which means, push a `9`, push a `6`, add them, print the top of the stack, end the program.
[Answer]
# 18. Javascript, 3 moved, 10 added
```
|/** 56#\.@ |
| :";8<<print |
| 6 |
| a 0 |
| echo |
| # 12!$>{: |
| |
| |
| |
| |
| ${ |
| 9 |
| |
| :Disp |
| ' |
| 10 |
| ! |
| 'main'"`.3i |
|} 7 if = |
|puts+11 O ) ; + */ alert ( 022 ) |
```
### Remaining pieces:
```
L-^=v^Ej2W8OxNOISt4mjO%YRJ;PJ!M|*o77*R&2 <c"KIe%FY^?I=];Y@`x))IBk%_a#<E6<yv5O*$kL):
KNGq)2Wa%b)j"(6U|[UY@`lCSJ`u0RHX!z7,v}=GvRgkrEZ=YT:4H44bz]C<](+FF?Ay'vX~5QMF)0vaXksk@
Zj.{l;PBKHABvEP%FnSw>u_-4B^AI8Kay&5]vXZJ{fCF]UVZ<!ZpOI$7\Y%@:%HwPsX-`/l]ZZ?Q/d`\M<T@'t]zp
{[vg:6ECT&+vU4Heb^;}0AV|?}M0rAH/^DL"RkT~%$[VUlM]-&We4(P=6},hL~;`:$yty.W[g2OWcL~b:Ryj0*eN<
&-[FF=oh0k[NI!xS"]pA@Y;K}'=ekG5yda8J$+`N;:FIx: ,f_LT@sV[]HF@2*vl?|q"GL1j&%e(CyYPqY%3W|@`z}]bp
4_'1Nx{G2&j6$UWt_#%`sTt2xC}s1P8J<gV24_RWg MuyVOjz=zS!1i2s@`Q#@^~@W/[[email protected]](/cdn-cgi/l/email-protection):g9?J^p;7ju?B\yC5
x,ZApKS5G4}kx_iM)f4 |su>=[{XSV#{,j5Qn3U.v5LF;HXs%DYm4'+efmU;\}f6j$SFCRC`Gsd37:'3$q=bs;lvsW0Yj^:-
I[94@I|.IpR=}4KB4ZG4>8PR29'L?n\gk,*4X[-%T`\FC)jj0jl_x<xL8E:G2-"3tT8&E}"sE+SH[7jR%@V)a{m8K>.rAO
2[dq7GX9nrz8p4}^n@q|dF%<.Tl8)Dk?O.<UoE(a*k_=4u!h$^bVd:$jS#EHFh@Z=y=ib^~/~lEJ^SQ3E_t#&^IOov7v8
~j#I#OHgxg{ZDyCsq-(GVq}HbiG,JV?eJ~5wJ;bSt@;3LI!2(6gIT92>}`_dw;YF@ccTIEz\Gu@2(}J2I1"S{R(2niIYPp9
8A3iP[*!SH2*SN8'`V?w4Ufx2HAz%{}FlUdH31TJ5:ge^N91^;9Gj`Uqf'$_|8P"kHR1w. ASwmN U-~q"[XcWbqPnns
d.ZoPJ}$Xc2lA>HN28`(dy+UA sQ=?KE07=\FsVN(#?&hRabS%BVI<`O$o4x5ZFFLGDcA4 ?&Eh~Z$oBWwNSNv`^;vO'
2&9egng~L#\QkfMG?S/n@%-VA[?f9K&3"V%P#Sv0!D<,GV:Z;3c&zFe^k&^0b7fAjvrbMc^Lq7k$h=YL<h7<0\NK>~Q=uUv)
4cI$.'b-RVS-=rom:=QR=c>9m-^5F[XGv>E/>|]~]3{r{kTc?ee1v=;I7]52#NE)~A;}!z>5?hi{5<9FtWH6{VO_Y-Jy
Mw>{l8n#mD,kl'8cG^.7sy=QqU-3~SKG5(.Ta]:-Vfr'NS$o*q:w6e$&7spk3{CFT'l_hGY0-0Xui*5^0^fO@6?2IdCn_C
lPKaJ6]0t!u>v8<d'Vby]8kEHh04p(YI)&7w82BrGB3PkI,s+%7ux5)gau`G!8F8hLa4[lfD55Xf3Hqy*-K,?;'fxH3JWYE
Z.[N`[KCY@TzKX4TMXsm{Xbd:B3)Gy[mlwnC>)z`:k=C\0ho/v{7#+2,*%]>~vI2^C:2DebJR>.ESw^wd2N<~]O9sOQ
`_yvIw&Ryf%JgT@W(G1wfU34G3U}x1jKJzJY\S9n$2~P;F}*eT9UXcTNBTrTs>~0v_Oi.y8ofX6i5u$;'^"q][QhTb*gO[U
n'R0vr+9fv5G7Bg=D:c*a=1[}7}dYOO{Mz2&@6`jnNq.QcBDM9Dd=R.*=MqZ3#'{AJJFqx<{qb':BH8ig1L%T\Vuc"
(h$i3`,scX'hqpbw"=nY`*Lu:h1wR{+-`\^3cQkIWfq)3?&p;~pvDW$o7\O|RrB2{PX.s#G6A.s<OA_,TI_b*&lO@L3KrQv
```
More octal fun. Here's the test snippet:
```
/** 56#\.@
:";8<<print
6
a 0
echo
# 12!$>{:
${
9
:Disp
'
10
!
'main'"`.3i
} 7 if =
puts+11 O ) ; + */ alert ( 022 )
```
[Answer]
# 21. Unvanquished (Daemon engine) scripting, 2 moved, 3 added
[Unvanquished](http://www.unvanquished.net/) is an FPS/RTS game with humans vs. aliens. It also has a built-in scripting system with such commands as performing mathematical operations, concatenating strings, conditionals, looping a variable over different values, and the ability to execute scripts from arbitrary files. Thus I think it is valid as a programming language
```
|/** 56#\.@ |
| :";8<<print |
| 6 alertprint |
| 0 |
| |
| # 12!$>{: |
| |
| |
| |
| |
| ${ |
| 9 |
| |
| :Disp |
| ' |
| 10 |
| ! |
| 'main'"`.3i |
|} 7 if a= |
|puts+11 O ) ; + */echo 21//20( 022-3 ) |
```
**Remaining Pieces**
```
L-^=v^Ej2W8OxNOISt4mjO%YRJ;PJ!M|*o77*R&2<c"KIe%FY^?I=];Y@`x))IBk%_a#<E6<yv5O*$kL):
KNGq)2Wa%b)j"(6U|[UY@`lCSJ`u0RHX!z7,v}=GvRgkEZ=YT:4H44bz]C<](+FF?Ay'vX~5QMF)0vaXksk@
Zj.{l;PBKHABvEP%FSw>u_4B^AI8Kay&5]vXZJ{fCF]UVZ<!ZpOI$7\Y%@:%HwPsX-`/l]ZZ?Q/d`\M<T@'t]zp
{[vg:6ECT&+vU4Heb^;}0AV|?}M0rAH/^DL"RkT~%$[VUlM]-&We4(P=6},hL~;`:$yty.W[g2OWcL~b:Ryj0*eN<
&-[FF=oh0k[NI!xS"]pA@Y;K}'=ekG5yda8J$+`N;:FIx:,f_LT@sV[]HF@2*vl?|q"GL1j&%e(CyYPqY%W|@`z}]b
4_'1Nx{G2&j6$UWt_#%`sTt2xC}s1P8J<gV24_RWgMuyVOjz=zS!12s@`Q#@^~@W/[[email protected]](/cdn-cgi/l/email-protection):g9?J^p;7ju?B\yC5
x,ZApKS5G4}kx_iM)f4|su>=[{XSV#{,j5Qn3U.v5LF;HXs%DYm4'+efmU;\}f6j$SFCRC`Gsd37:'3$q=bs;lvsW0Yj^:-
I[94@I|.IpR=}4KB4ZG4>8PR29'L?n\gk,*4X[-%T`\FC)jj0jl_x<xL8E:G2-"3T8&E}"sE+SH[7jR%@V)a{m8K>.rAO
2[dq7GX9nrz8p4}^n@q|dF%<.Tl8)Dk?O.<UoE(a*k_=4u!h$^bVd:$jS#EHFh@Z=y=ib^~/~lEJ^SQ3E_t#&^IOov7v8
~j#I#OHgxg{ZDyCsq-(GVq}HbiG,JV?eJ~5wJ;bSt@;3LI!2(6gIT92>}`_dw;YF@ccTIEz\Gu@2(}J2I1"S{R(2niIYPp9
8A3iP[*!SH2*SN8'`V?w4Ufx2HAz%{}FlUdH31TJ5:ge^N91^;9Gj`Uqf'$_|8P"kHR1w.ASwmNU-~q"[XcWbqPnns
d.ZoPJ}$Xc2lA>HN28`(dy+UAsQ=?KE07=\FsVN(#?&hRabS%BVI<`O$o4x5ZFFLGDcA4?&Eh~Z$oBWwNSNv`^;vO'
&9egng~L#\QkfMG?Sn@%-VA[?f9K&3"V%P#Sv!D<,GV:Z;3c&zFe^k&^0b7fAjvrbMc^Lq7k$h=YL<h7<0\NK>~Q=uUv)
4cI$.'b-RVS-=rom:=QR=c>9m-^5F[XGv>E/>|]~]3{r{kTc?ee1v=;I7]52#NE)~A;}!z>5?hi{5<9FtWH6{VO_Y-Jy
Mw>{l8n#mD,kl'8cG^.7sy=QqU-3~SKG5(.Ta]:-Vfr'NS$o*q:w6e$&7spk3{CFT'l_hGY0-0Xui*5^0^fO@6?2IdCn_C
lPKaJ6]0t!u>v8<d'Vby]8kEHh04p(YI)&7w82BrGB3PkI,s+%7ux5)gau`G!8F8hLa4[lfD55Xf3Hqy*-K,?;'fxH3JWYE
Z.[N`[KCY@TzKX4TMXsm{Xbd:B3)Gy[mlwnC>)z`:k=C\0hov{7#+2,*%]>~vI2^C:2DebJR>.ESw^wd2N<~]O9sOQ
`_yvIw&Ryf%JgT@W(G1wfU34G3U}x1jKJzJY\S9n$2~P;F}*eT9UXcTNBTrTs>~0v_Oi.y8ofX6i5u$;'^"q][QhTb*gO[U
n'R0vr+9fv5G7Bg=D:c*a=1[}7}dYOO{Mz&@6`jnNq.QcBDM9Dd=R.*=MqZ3#'{AJJFqx<{qb':BH8ig1L%T\Vuc"
(h$i3`,scX'hqpbw"=nY`*Lu:hwR{+-`\^3cQkIWfq)3?&p;~pvDW$o7\O|RrB2{PX.s#G6A.s<OA_,TI_b*&lO@L3KrQv
```
[Answer]
# 6. Pyth, 2 moved, 1 added
```
|6# `.3i !|
|:" |
| |
| # $> 0 << |
| |
| |
| |
|print 02 ** 2 |
| |
| |
| |
| |
| |
| :Disp 5 |
| |
| |
| |
| |
| |
| |
```
### Remaining Pieces:
```
L-^=v^Ej2tW8OxNOIecSt4m} j O%YRJ;PJ!M|0*oO77*Rs&2*<c"KI7e%FY^?I=];Y@`x)u)IBk%_a#<E6<yv5O*$kL):
KNGq)2Wa%b)j"(6U|{[UY@`l CSJ`u0RHX!1z7f,v} =GvRgkrEZ=YT:4H44bz] C<](:+FF?Ay'vX~h5QMF)0vaXk1sk@p
Zj).{+l;PBKHABvEP%FnSw>u_-4B^AI8Kay&5]vXZJ{fCF]UVZ<!ZpOI$7\Y%@:%HwPsX-`/l]ZZ?Q/d`\M<T@'t]zip
{[ovg:6E CT&'+vU4Heb^;}0AV|?}M0rAH/^DL"RkT~%$[VUlM]-&We4(P=66},hL~;a`:$'yty.W[g2OWcL~b:Ryj0*eN<
;&-n[F1F=oh0k[NI!xS"]pA@Y;K}'=ekG5yda8J$+`N;:FIx:l,f_LT@sV[]HF@2*vl?|q"GL1j&%e(CyYPqY%3W|@`z}]bp
4_'1Nx{G2&j6$UWt_#%`sTt2xC}s1P8J<gV24_RWge/aMuyVOjz=zS!1i2s@`Q#@^~@W/[[email protected]](/cdn-cgi/l/email-protection):g9?J^p;7ju?B\yC5
x,ZApKS5G4}kx_iM)f4/|su>=[{XSV#{,j5Qn3U.v5LF;HXs%DYm4'+efmU;\}f6j$SFCRC`Gsd37:'3$q=bs;lvsW0Yj^:-
I[94@I|.IpR=}4KB4ZG4>8PR29'L?n\gk,*4X[-%T`\FC)jj0jl_x<xL8E:G2-"3tT8&E}"sE+SH[7jR%@V)a{ m8K>.rAO
2[dq7GX9nrz8p4}^ mn@q|dF%<.Tl8)Dk?O.<UoE(a*k_=4+u!h$^bVd:$jS#EHFh@Z=y=ib^~/~lEJ^SQ3E_t#&^IOov7v8
~j#I#OHgxg{ZDyCsq-(GVq}HbiG,JV?eJ~5wJ;bSt@;3LI!2(6gIT92>}`_dw;YF@ccTIEz\Gu@2(}J2I1"S{R(2niIYPp9
8A3iP[*!SH2*SN8'`V?w4Ufx2HAz%{}FlUdH31TJ5{:ge^N91^;9Gj`Uqf'$_|8P"kHR1w.(ASwmN)U-~q"[XcWbqPnns=
d.ZoPJ}$Xc2lA>HN28`(dy+UArsQ=?KE07=\FsVN(#?&hRabS%BVI <`O$o 4x5ZFFLGDcA4t?&Eh~Z$oBWwNSNv`^;vO'
2&9egng~L#\QkfMG?S/n@%-VA[?f9K&3"V%P#Sv0!D<,GV:Z;3c&zFe^k&^0b7fAjvrbMc^Lq7k$h=YL<h7<0\NK>~Q=uUv)
4cI$.'b-RVS-=rom:=8QR=c>9am-^5F[XGv>E/>|]~\']3{r{kTc?ee1v=;I7]52#NE)~A;}!z>5?hi{5<9FtWH6{VO_Y-Jy
Mw>{l8n#mD,kl'8cG^.7sy=QqU-3~SKG5(.Ta]:-Vfr'NS$o*q:w6e$&7spk3{CFT'l_hGY0-0Xui*5i^0^fO@6?2IdCn_C
lPKaJ6]0t!u>v8<d'Vby]8kEHh04p(YI)&7w82BrGB3PkI,s+%7ux5)gau`G!8F8hLa4[lfD55Xf3Hqy*-K,?;2'fxH3JWYE
Z.[N`[KCY@TzKX4TMXsm{Xbd:B3)Gy[mlwnC$>)z`:k=C\0ho/v{7#+2,*%]>~vI2^C:2DebJR>.ESw^wd2N<~]O9sOQ
`_yvIw&Ryf%JgT@W(G1wfU3.4G3U}x1jKJzJY\S9n$2~P;F}*eT9UXcTNBTrTs>~0v_Oi.y8ofX6i5u$;'^"q][QhTb*gO[U
n'R0"v1r+9fv;5G7Bg=D:c*a=1@[}7}dYOO{Mz2&@6`jnNq.QcBDM9Dd=R.*=MqZ93#'{AJJFqx<{qb':B!H8ig1L%T\Vuc"
(h$i3`,scX'hqpbw"=nY`*Lu:h1wR{+-`\^3cQkIWfq)3?&p;~pvDW$o7\O|RrB2{PX.s#G6A.s<OA_,TI_b*&lO@L3KrQv
```
Uses the old restricted source trick that Pyth only executes the first line of its source code (note that the online interpreter does not act this way). Any value in Pyth not used for something else is automatically printed.
The `# `.3i` runs a `while 1` with a `try .. except` block. The ``.3` would print 0.3 as the string representation of .3 but it is prefixed by a space character, which suppresses printing. The call to i requires 2 arguments, but it receives one a not function that also gets no arguments, so an exception is thrown, and the loop breaks.
[Answer]
# 8. CJam, 1 moved, 3 added
```
| "`.3i !|
|) |
| |
| # $> 0 << |
| |
| |
| |
|print 02 ** 2 |
| |
| |
| |
| |
| |
| :Disp 56# |
| :";8 |
| |
| |
| |
| |
| |
```
**Remaining pieces**:
```
L-^=v^Ej2tW8OxNOIecSt4m} j O%YRJ;PJ!M|0*oO77*Rs&2*<c"KI7e%FY^?I=];Y@`x)u)IBk%_a#<E6<yv5O*$kL):
KNGq)2Wa%b)j"(6U|{[UY@`l CSJ`u0RHX!1z7f,v} =GvRgkrEZ=YT:4H44bz] C<](:+FF?Ay'vX~h5QMF)0vaXk1sk@p
Zj.{+l;PBKHABvEP%FnSw>u_-4B^AI8Kay&5]vXZJ{fCF]UVZ<!ZpOI$7\Y%@:%HwPsX-`/l]ZZ?Q/d`\M<T@'t]zip
{[ovg:6E CT&'+vU4Heb^;}0AV|?}M0rAH/^DL"RkT~%$[VUlM]-&We4(P=66},hL~;a`:$'yty.W[g2OWcL~b:Ryj0*eN<
;&-n[F1F=oh0k[NI!xS"]pA@Y;K}'=ekG5yda8J$+`N;:FIx:l,f_LT@sV[]HF@2*vl?|q"GL1j&%e(CyYPqY%3W|@`z}]bp
4_'1Nx{G2&j6$UWt_#%`sTt2xC}s1P8J<gV24_RWge/aMuyVOjz=zS!1i2s@`Q#@^~@W/[[email protected]](/cdn-cgi/l/email-protection):g9?J^p;7ju?B\yC5
x,ZApKS5G4}kx_iM)f4/|su>=[{XSV#{,j5Qn3U.v5LF;HXs%DYm4'+efmU;\}f6j$SFCRC`Gsd37:'3$q=bs;lvsW0Yj^:-
I[94@I|.IpR=}4KB4ZG4>8PR29'L?n\gk,*4X[-%T`\FC)jj0jl_x<xL8E:G2-"3tT8&E}"sE+SH[7jR%@V)a{ m8K>.rAO
2[dq7GX9nrz8p4}^ mn@q|dF%<.Tl8)Dk?O.<UoE(a*k_=4+u!h$^bVd:$jS#EHFh@Z=y=ib^~/~lEJ^SQ3E_t#&^IOov7v8
~j#I#OHgxg{ZDyCsq-(GVq}HbiG,JV?eJ~5wJ;bSt@;3LI!2(6gIT92>}`_dw;YF@ccTIEz\Gu@2(}J2I1"S{R(2niIYPp9
8A3iP[*!SH2*SN8'`V?w4Ufx2HAz%{}FlUdH31TJ5{:ge^N91^;9Gj`Uqf'$_|8P"kHR1w.(ASwmN)U-~q"[XcWbqPnns=
d.ZoPJ}$Xc2lA>HN28`(dy+UArsQ=?KE07=\FsVN(#?&hRabS%BVI <`O$o 4x5ZFFLGDcA4t?&Eh~Z$oBWwNSNv`^;vO'
2&9egng~L#\QkfMG?S/n@%-VA[?f9K&3"V%P#Sv0!D<,GV:Z;3c&zFe^k&^0b7fAjvrbMc^Lq7k$h=YL<h7<0\NK>~Q=uUv)
4cI$.'b-RVS-=rom:=QR=c>9am-^5F[XGv>E/>|]~\']3{r{kTc?ee1v=;I7]52#NE)~A;}!z>5?hi{5<9FtWH6{VO_Y-Jy
Mw>{l8n#mD,kl'8cG^.7sy=QqU-3~SKG5(.Ta]:-Vfr'NS$o*q:w6e$&7spk3{CFT'l_hGY0-0Xui*5i^0^fO@6?2IdCn_C
lPKaJ6]0t!u>v8<d'Vby]8kEHh04p(YI)&7w82BrGB3PkI,s+%7ux5)gau`G!8F8hLa4[lfD55Xf3Hqy*-K,?;2'fxH3JWYE
Z.[N`[KCY@TzKX4TMXsm{Xbd:B3)Gy[mlwnC$>)z`:k=C\0ho/v{7#+2,*%]>~vI2^C:2DebJR>.ESw^wd2N<~]O9sOQ
`_yvIw&Ryf%JgT@W(G1wfU3.4G3U}x1jKJzJY\S9n$2~P;F}*eT9UXcTNBTrTs>~0v_Oi.y8ofX6i5u$;'^"q][QhTb*gO[U
n'R0v1r+9fv5G7Bg=D:c*a=1@[}7}dYOO{Mz2&@6`jnNq.QcBDM9Dd=R.*=MqZ93#'{AJJFqx<{qb':B!H8ig1L%T\Vuc"
(h$i3`,scX'hqpbw"=nY`*Lu:h1wR{+-`\^3cQkIWfq)3?&p;~pvDW$o7\O|RrB2{PX.s#G6A.s<OA_,TI_b*&lO@L3KrQv
```
Simply pads everything in a string, pops it and then puts 8 on stack which gets printed automatically.
[Answer]
# 14. ><>, 3 moved, 1 added
```
| ' \ "`.3i !|
| if |
| ) |
| # 0 |
| |
| 12!$>{: |
| |
| 02 ** |
| |
| |
| echo ${ |
| |
| |
| :Disp 56# |
| :";8<<print 9 10 |
| |
| |
| ' |
|} = |
|puts+11 ; + 2 |
```
### Remaining pieces:
```
L-^=v^Ej2W8OxNOI St4m j O%YRJ;PJ!M| *oO77*R&2*<c"KI7e%FY^?I=];Y@`x))IBk%_a#<E6<yv5O*$kL):
KNGq)2Wa%b)j"(6U|[UY@`l CSJ`u0RHX! z7,v} =GvRgkrEZ=YT:4H44bz] C<]( +FF?Ay'vX~ 5QMF)0vaXksk@
Zj.{l;PBKHABvEP%FnSw>u_-4B^AI8Kay&5]vXZJ{fCF]UVZ<!ZpOI$7\Y%@:%HwPsX-`/l]ZZ?Q/d`\M<T@'t]zp
{[ vg:6E CT& +vU4Heb^;}0AV|?}M0rAH/^DL"RkT~%$[VUlM]-&We4(P=66},hL~;a`:$'yty.W[g2OWcL~b:Ryj0*eN<
&-n[FF=oh0k[NI!xS"]pA@Y;K}'=ekG5yda8J$+`N;:FIx:l,f_LT@sV[]HF@2*vl?|q"GL1j&%e(CyYPqY%3W|@`z}]bp
4_'1Nx{G2&j6$UWt_#%`sTt2xC}s1P8J<gV24_RWge/aMuyVOjz=zS!1i2s@`Q#@^~@W/[[email protected]](/cdn-cgi/l/email-protection):g9?J^p;7ju?B\yC5
x,ZApKS5G4}kx_iM)f4/|su>=[{XSV#{,j5Qn3U.v5LF;HXs%DYm4'+efmU;\}f6j$SFCRC`Gsd37:'3$q=bs;lvsW0Yj^:-
I[94@I|.IpR=}4KB4ZG4>8PR29'L?n\gk,*4X[-%T`\FC)jj0jl_x<xL8E:G2-"3tT8&E}"sE+SH[7jR%@V)a{ m8K>.rAO
2[dq7GX9nrz8p4}^ mn@q|dF%<.Tl8)Dk?O.<UoE(a*k_=4u!h$^bVd:$jS#EHFh@Z=y=ib^~/~lEJ^SQ3E_t#&^IOov7v8
~j#I#OHgxg{ZDyCsq-(GVq}HbiG,JV?eJ~5wJ;bSt@;3LI!2(6gIT92>}`_dw;YF@ccTIEz\Gu@2(}J2I1"S{R(2niIYPp9
8A3iP[*!SH2*SN8'`V?w4Ufx2HAz%{}FlUdH31TJ5:ge^N91^;9Gj`Uqf'$_|8P"kHR1w.(ASwmN)U-~q"[XcWbqPnns
d.ZoPJ}$Xc2lA>HN28`(dy+UArsQ=?KE07=\FsVN(#?&hRabS%BVI <`O$o 4x5ZFFLGDcA4t?&Eh~Z$oBWwNSNv`^;vO'
2&9egng~L#\QkfMG?S/n@%-VA[?f9K&3"V%P#Sv0!D<,GV:Z;3c&zFe^k&^0b7fAjvrbMc^Lq7k$h=YL<h7<0\NK>~Q=uUv)
4cI$.'b-RVS-=rom:=QR=c>9am-^5F[XGv>E/>|]~ ]3{r{kTc?ee1v=;I7]52#NE)~A;}!z>5?hi{5<9FtWH6{VO_Y-Jy
Mw>{l8n#mD,kl'8cG^.7sy=QqU-3~SKG5(.Ta]:-Vfr'NS$o*q:w6e$&7spk3{CFT'l_hGY0-0Xui*5i^0^fO@6?2IdCn_C
lPKaJ6]0t!u>v8<d'Vby]8kEHh04p(YI)&7w82BrGB3PkI,s+%7ux5)gau`G!8F8hLa4[lfD55Xf3Hqy*-K,?; 'fxH3JWYE
Z.[N`[KCY@TzKX4TMXsm{Xbd:B3)Gy[mlwnC>)z`:k=C\0ho/v{7#+2,*%]>~vI2^C:2DebJR>.ESw^wd2N<~]O9sOQ
`_yvIw&Ryf%JgT@W(G1wfU3.4G3U}x1jKJzJY\S9n$2~P;F}*eT9UXcTNBTrTs>~0v_Oi.y8ofX6i5u$;'^"q][QhTb*gO[U
n'R0v r+9fv5G7Bg=D:c*a=1@[}7}dYOO{Mz2&@6`jnNq.QcBDM9Dd=R.*=MqZ3#'{AJJFqx<{qb':B H8ig1L%T\Vuc"
(h$i3`,scX'hqpbw"=nY`*Lu:h1wR{+-`\^3cQkIWfq)3?&p;~pvDW$o7\O|RrB2{PX.s#G6A.s<OA_,TI_b*&lO@L3KrQv
```
*([Esolang page for ><>](http://esolangs.org/wiki/Fish))*
Runs `en;` vertically. The first `'` causes a whole bunch of chars on the first row to be added, but they are ignored.
[Answer]
# 16. Befunge-93, 2 moved, 2 added
```
|${ 'main'"`.3i 56#\.@ !|
| 9 if :";8<<print |
| 6 ) |
| a 0 |
| echo |
| # 12!$>{: |
| |
| 02 ** |
| |
| |
| |
| |
| |
| :Disp |
| 10 |
| |
| |
| ' |
|} = |
|puts+11 ; + 2 |
```
**Remaining Pieces**
```
L-^=v^Ej2W8OxNOISt4mjO%YRJ;PJ!M|*oO77*R&2*<c"KI7e%FY^?I=];Y@`x))IBk%_a#<E6<yv5O*$kL):
KNGq)2Wa%b)j"(6U|[UY@`lCSJ`u0RHX!z7,v}=GvRgkrEZ=YT:4H44bz]C<](+FF?Ay'vX~5QMF)0vaXksk@
Zj.{l;PBKHABvEP%FnSw>u_-4B^AI8Kay&5]vXZJ{fCF]UVZ<!ZpOI$7\Y%@:%HwPsX-`/l]ZZ?Q/d`\M<T@'t]zp
{[vg:6ECT&+vU4Heb^;}0AV|?}M0rAH/^DL"RkT~%$[VUlM]-&We4(P=6},hL~;`:$yty.W[g2OWcL~b:Ryj0*eN<
&-[FF=oh0k[NI!xS"]pA@Y;K}'=ekG5yda8J$+`N;:FIx:l,f_LT@sV[]HF@2*vl?|q"GL1j&%e(CyYPqY%3W|@`z}]bp
4_'1Nx{G2&j6$UWt_#%`sTt2xC}s1P8J<gV24_RWge/aMuyVOjz=zS!1i2s@`Q#@^~@W/[[email protected]](/cdn-cgi/l/email-protection):g9?J^p;7ju?B\yC5
x,ZApKS5G4}kx_iM)f4/|su>=[{XSV#{,j5Qn3U.v5LF;HXs%DYm4'+efmU;\}f6j$SFCRC`Gsd37:'3$q=bs;lvsW0Yj^:-
I[94@I|.IpR=}4KB4ZG4>8PR29'L?n\gk,*4X[-%T`\FC)jj0jl_x<xL8E:G2-"3tT8&E}"sE+SH[7jR%@V)a{m8K>.rAO
2[dq7GX9nrz8p4}^n@q|dF%<.Tl8)Dk?O.<UoE(a*k_=4u!h$^bVd:$jS#EHFh@Z=y=ib^~/~lEJ^SQ3E_t#&^IOov7v8
~j#I#OHgxg{ZDyCsq-(GVq}HbiG,JV?eJ~5wJ;bSt@;3LI!2(6gIT92>}`_dw;YF@ccTIEz\Gu@2(}J2I1"S{R(2niIYPp9
8A3iP[*!SH2*SN8'`V?w4Ufx2HAz%{}FlUdH31TJ5:ge^N91^;9Gj`Uqf'$_|8P"kHR1w.(ASwmN)U-~q"[XcWbqPnns
d.ZoPJ}$Xc2lA>HN28`(dy+UArsQ=?KE07=\FsVN(#?&hRabS%BVI<`O$o4x5ZFFLGDcA4t?&Eh~Z$oBWwNSNv`^;vO'
2&9egng~L#\QkfMG?S/n@%-VA[?f9K&3"V%P#Sv0!D<,GV:Z;3c&zFe^k&^0b7fAjvrbMc^Lq7k$h=YL<h7<0\NK>~Q=uUv)
4cI$.'b-RVS-=rom:=QR=c>9m-^5F[XGv>E/>|]~]3{r{kTc?ee1v=;I7]52#NE)~A;}!z>5?hi{5<9FtWH6{VO_Y-Jy
Mw>{l8n#mD,kl'8cG^.7sy=QqU-3~SKG5(.Ta]:-Vfr'NS$o*q:w6e$&7spk3{CFT'l_hGY0-0Xui*5^0^fO@6?2IdCn_C
lPKaJ6]0t!u>v8<d'Vby]8kEHh04p(YI)&7w82BrGB3PkI,s+%7ux5)gau`G!8F8hLa4[lfD55Xf3Hqy*-K,?;'fxH3JWYE
Z.[N`[KCY@TzKX4TMXsm{Xbd:B3)Gy[mlwnC>)z`:k=C\0ho/v{7#+2,*%]>~vI2^C:2DebJR>.ESw^wd2N<~]O9sOQ
`_yvIw&Ryf%JgT@W(G1wfU34G3U}x1jKJzJY\S9n$2~P;F}*eT9UXcTNBTrTs>~0v_Oi.y8ofX6i5u$;'^"q][QhTb*gO[U
n'R0vr+9fv5G7Bg=D:c*a=1[}7}dYOO{Mz2&@6`jnNq.QcBDM9Dd=R.*=MqZ3#'{AJJFqx<{qb':BH8ig1L%T\Vuc"
(h$i3`,scX'hqpbw"=nY`*Lu:h1wR{+-`\^3cQkIWfq)3?&p;~pvDW$o7\O|RrB2{PX.s#G6A.s<OA_,TI_b*&lO@L3KrQv
```
[Answer]
# 19. Swift, 1 moved, 7 added
```
|/** 56#\.@ |
| :";8<<print |
| 6 alert |
| a 0 |
| echo |
| # 12!$>{: |
| |
| |
| |
| |
| ${ |
| 9 |
| |
| :Disp |
| ' |
| 10 |
| ! |
| 'main'"`.3i |
|} 7 if = |
|puts+11 O ) ; + */ print ( 022-3 ) |
```
**Remaining pieces**:
```
L-^=v^Ej2W8OxNOISt4mjO%YRJ;PJ!M|*o77*R&2 <c"KIe%FY^?I=];Y@`x))IBk%_a#<E6<yv5O*$kL):
KNGq)2Wa%b)j"(6U|[UY@`lCSJ`u0RHX!z7,v}=GvRgk EZ=YT:4H44bz]C<](+FF?Ay'vX~5QMF)0vaXksk@
Zj.{l;PBKHABvEP%F Sw>u_ 4B^AI8Kay&5]vXZJ{fCF]UVZ<!ZpOI$7\Y%@:%HwPsX-`/l]ZZ?Q/d`\M<T@'t]zp
{[vg:6ECT&+vU4Heb^;}0AV|?}M0rAH/^DL"RkT~%$[VUlM]-&We4(P=6},hL~;`:$yty.W[g2OWcL~b:Ryj0*eN<
&-[FF=oh0k[NI!xS"]pA@Y;K}'=ekG5yda8J$+`N;:FIx: ,f_LT@sV[]HF@2*vl?|q"GL1j&%e(CyYPqY% W|@`z}]b
4_'1Nx{G2&j6$UWt_#%`sTt2xC}s1P8J<gV24_RWg MuyVOjz=zS!1 2s@`Q#@^~@W/[[email protected]](/cdn-cgi/l/email-protection):g9?J^p;7ju?B\yC5
x,ZApKS5G4}kx_iM)f4 |su>=[{XSV#{,j5Qn3U.v5LF;HXs%DYm4'+efmU;\}f6j$SFCRC`Gsd37:'3$q=bs;lvsW0Yj^:-
I[94@I|.IpR=}4KB4ZG4>8PR29'L?n\gk,*4X[-%T`\FC)jj0jl_x<xL8E:G2-"3 T8&E}"sE+SH[7jR%@V)a{m8K>.rAO
2[dq7GX9nrz8p4}^n@q|dF%<.Tl8)Dk?O.<UoE(a*k_=4u!h$^bVd:$jS#EHFh@Z=y=ib^~/~lEJ^SQ3E_t#&^IOov7v8
~j#I#OHgxg{ZDyCsq-(GVq}HbiG,JV?eJ~5wJ;bSt@;3LI!2(6gIT92>}`_dw;YF@ccTIEz\Gu@2(}J2I1"S{R(2niIYPp9
8A3iP[*!SH2*SN8'`V?w4Ufx2HAz%{}FlUdH31TJ5:ge^N91^;9Gj`Uqf'$_|8P"kHR1w. ASwmN U-~q"[XcWbqPnns
d.ZoPJ}$Xc2lA>HN28`(dy+UA sQ=?KE07=\FsVN(#?&hRabS%BVI<`O$o4x5ZFFLGDcA4 ?&Eh~Z$oBWwNSNv`^;vO'
2&9egng~L#\QkfMG?S/n@%-VA[?f9K&3"V%P#Sv0!D<,GV:Z;3c&zFe^k&^0b7fAjvrbMc^Lq7k$h=YL<h7<0\NK>~Q=uUv)
4cI$.'b-RVS-=rom:=QR=c>9m-^5F[XGv>E/>|]~]3{r{kTc?ee1v=;I7]52#NE)~A;}!z>5?hi{5<9FtWH6{VO_Y-Jy
Mw>{l8n#mD,kl'8cG^.7sy=QqU-3~SKG5(.Ta]:-Vfr'NS$o*q:w6e$&7spk3{CFT'l_hGY0-0Xui*5^0^fO@6?2IdCn_C
lPKaJ6]0t!u>v8<d'Vby]8kEHh04p(YI)&7w82BrGB3PkI,s+%7ux5)gau`G!8F8hLa4[lfD55Xf3Hqy*-K,?;'fxH3JWYE
Z.[N`[KCY@TzKX4TMXsm{Xbd:B3)Gy[mlwnC>)z`:k=C\0ho/v{7#+2,*%]>~vI2^C:2DebJR>.ESw^wd2N<~]O9sOQ
`_yvIw&Ryf%JgT@W(G1wfU34G3U}x1jKJzJY\S9n$2~P;F}*eT9UXcTNBTrTs>~0v_Oi.y8ofX6i5u$;'^"q][QhTb*gO[U
n'R0vr+9fv5G7Bg=D:c*a=1[}7}dYOO{Mz2&@6`jnNq.QcBDM9Dd=R.*=MqZ3#'{AJJFqx<{qb':BH8ig1L%T\Vuc"
(h$i3`,scX'hqpbw"=nY`*Lu:h1wR{+-`\^3cQkIWfq)3?&p;~pvDW$o7\O|RrB2{PX.s#G6A.s<OA_,TI_b*&lO@L3KrQv
```
[You can try Swift online here](http://swiftstub.com/)
[Answer]
# 20. ///, 0 moved, 3 added
```
|/** 56#\.@ |
| :";8<<print |
| 6 alert |
| a 0 |
| echo |
| # 12!$>{: |
| |
| |
| |
| |
| ${ |
| 9 |
| |
| :Disp |
| ' |
| 10 |
| ! |
| 'main'"`.3i |
|} 7 if = |
|puts+11 O ) ; + */ print ( 022-3 ) /20|
```
### Remaining pieces:
```
L-^=v^Ej2W8OxNOISt4mjO%YRJ;PJ!M|*o77*R&2<c"KIe%FY^?I=];Y@`x))IBk%_a#<E6<yv5O*$kL):
KNGq)2Wa%b)j"(6U|[UY@`lCSJ`u0RHX!z7,v}=GvRgkEZ=YT:4H44bz]C<](+FF?Ay'vX~5QMF)0vaXksk@
Zj.{l;PBKHABvEP%FSw>u_4B^AI8Kay&5]vXZJ{fCF]UVZ<!ZpOI$7\Y%@:%HwPsX-`/l]ZZ?Q/d`\M<T@'t]zp
{[vg:6ECT&+vU4Heb^;}0AV|?}M0rAH/^DL"RkT~%$[VUlM]-&We4(P=6},hL~;`:$yty.W[g2OWcL~b:Ryj0*eN<
&-[FF=oh0k[NI!xS"]pA@Y;K}'=ekG5yda8J$+`N;:FIx:,f_LT@sV[]HF@2*vl?|q"GL1j&%e(CyYPqY%W|@`z}]b
4_'1Nx{G2&j6$UWt_#%`sTt2xC}s1P8J<gV24_RWgMuyVOjz=zS!12s@`Q#@^~@W/[[email protected]](/cdn-cgi/l/email-protection):g9?J^p;7ju?B\yC5
x,ZApKS5G4}kx_iM)f4|su>=[{XSV#{,j5Qn3U.v5LF;HXs%DYm4'+efmU;\}f6j$SFCRC`Gsd37:'3$q=bs;lvsW0Yj^:-
I[94@I|.IpR=}4KB4ZG4>8PR29'L?n\gk,*4X[-%T`\FC)jj0jl_x<xL8E:G2-"3T8&E}"sE+SH[7jR%@V)a{m8K>.rAO
2[dq7GX9nrz8p4}^n@q|dF%<.Tl8)Dk?O.<UoE(a*k_=4u!h$^bVd:$jS#EHFh@Z=y=ib^~/~lEJ^SQ3E_t#&^IOov7v8
~j#I#OHgxg{ZDyCsq-(GVq}HbiG,JV?eJ~5wJ;bSt@;3LI!2(6gIT92>}`_dw;YF@ccTIEz\Gu@2(}J2I1"S{R(2niIYPp9
8A3iP[*!SH2*SN8'`V?w4Ufx2HAz%{}FlUdH31TJ5:ge^N91^;9Gj`Uqf'$_|8P"kHR1w.ASwmNU-~q"[XcWbqPnns
d.ZoPJ}$Xc2lA>HN28`(dy+UAsQ=?KE07=\FsVN(#?&hRabS%BVI<`O$o4x5ZFFLGDcA4?&Eh~Z$oBWwNSNv`^;vO'
&9egng~L#\QkfMG?Sn@%-VA[?f9K&3"V%P#Sv!D<,GV:Z;3c&zFe^k&^0b7fAjvrbMc^Lq7k$h=YL<h7<0\NK>~Q=uUv)
4cI$.'b-RVS-=rom:=QR=c>9m-^5F[XGv>E/>|]~]3{r{kTc?ee1v=;I7]52#NE)~A;}!z>5?hi{5<9FtWH6{VO_Y-Jy
Mw>{l8n#mD,kl'8cG^.7sy=QqU-3~SKG5(.Ta]:-Vfr'NS$o*q:w6e$&7spk3{CFT'l_hGY0-0Xui*5^0^fO@6?2IdCn_C
lPKaJ6]0t!u>v8<d'Vby]8kEHh04p(YI)&7w82BrGB3PkI,s+%7ux5)gau`G!8F8hLa4[lfD55Xf3Hqy*-K,?;'fxH3JWYE
Z.[N`[KCY@TzKX4TMXsm{Xbd:B3)Gy[mlwnC>)z`:k=C\0ho/v{7#+2,*%]>~vI2^C:2DebJR>.ESw^wd2N<~]O9sOQ
`_yvIw&Ryf%JgT@W(G1wfU34G3U}x1jKJzJY\S9n$2~P;F}*eT9UXcTNBTrTs>~0v_Oi.y8ofX6i5u$;'^"q][QhTb*gO[U
n'R0vr+9fv5G7Bg=D:c*a=1[}7}dYOO{Mz2&@6`jnNq.QcBDM9Dd=R.*=MqZ3#'{AJJFqx<{qb':BH8ig1L%T\Vuc"
(h$i3`,scX'hqpbw"=nY`*Lu:h1wR{+-`\^3cQkIWfq)3?&p;~pvDW$o7\O|RrB2{PX.s#G6A.s<OA_,TI_b*&lO@L3KrQv
```
[Esolangs page for ///](http://esolangs.org/wiki////)
[Answer]
# 26. Beam, 4 moved, 5 added
[Beam](http://esolangs.org/wiki/Beam) is a 2D esolang (just like ><> or Marbelous) with 9 pointers, the Beam, the Store and 7 Memories.
```
|iipsp25. $ 56#\.@ |
| :";8<<print |
| 6 alertprint |
| '0 |
| + #* $ |
|~ } |
| /** puts+11 |
| 12!$>{: |
| + |
| n |
| ' ${ |
| + 9 |
| :Disp |
| ' |
| 10 |
| ! |
| 'main'"`.3i |
| 7 if |
| O ) a= |
| ; xx */echo 21//20( 022-3 ) xcdddk*#p 23$|
```
**Remaining Pieces**:
```
-^=v^EjW8OxNOISt4mjO%YRJ;PJ!M|o77R&2<c"KIe%FY^?I=];Y@`x))IBk%_a<E6<yv5O*$kL):
KNGq)2Wa%b)j"(6U|[UY@`lCSJ`u0RHX!z7,v}=GvRgkEZ=YT:4H44bz]C<](FF?AyvX~5QMF)0vaX sk@
Zj.{l;PBKHABvEP%FSw>u_4B^AI8Kay&5]vXZJ{fCF]UVZ<!ZpOI$7\Y%@:%HwPsX-`/l]ZZ?Q/d`\M<T@t]z
{[vg:6ECT&vU4Heb^;}0AV|?}M0rAH/^DL"RkT % [VUlM]-&We4(P=6},hL~;`: yty.W[g2OWcL~b:Ryj0*eN<
&-[FF=oh0k[NI!xS"]pA@Y;K}'=ekG5yda8J$+`N;:FI :,f_LT@sV[]HF@2*vl?|q"GL1j&%e(CyYPqY%W|@`z}]b
4_'1N {G2&j6 UWt_#%`sTt2 C}s1P8J<gV24_RWgMuyVOjz=zS!12s@`Q#@^~@W/[[email protected]](/cdn-cgi/l/email-protection):g9?J^ ;7ju?B\yC5
x,ZApKS5G4}kx_iM)f4|su>=[{XSV#{,j5QU.v5LF;HXs%DYm4'+efmU;\}f6j$SFCRC`Gsd37:'3$q=bs;lvsW0Yj^:-
I[94@I|.IpR=}4KB4ZG4>8PR29'L?n\gk,*4X[-%T`\FC)jj0jl_x<xL8E:G2-"3T8&E}"sE+SH[7jR%@V)a{m8K>.rAO
2[dq7GX9nrz8p4}^n@q|dF%<.Tl8)Dk?O.<UoE(a*k_=4u!h$^bVd:$jS#EHFh@Z=y=ib^~/~lEJ^SQ3E_t#&^IOov7v8
~j#I#OHgxg{ZDyCsq-(GVq}HbiG,JV?eJ~5wJ;bSt@;3LI!2(6gIT92>}`_dw;YF@ccTIEz\Gu@2(}J2I1"S{R(2niIYP 9
8A3 P[*!SH2*SN8'`V?w4Ufx2HAz%{}FlUdH31TJ5:ge^N91^;9Gj`Uqf'$_|8P"kHR1w.ASwmNU-~q"[XcWbqPnns
dZoPJ}$Xc2lA>HN28`( y+UAsQ=?KE07=\F VN(#?&hRabS%BVI<`O$o4x5ZFFLGDcA4?&Eh~Z$oBWwNSNv`^;vO'
&9egng~L#\QkfMG?Sn@%-VA[?f9K&3"V%P#Sv!D<,GV:Z;3c&zFe^k&^0b7fAjvrbMc^Lq7k$h=YL<h7<0\NK>~Q=uUv)
4cI$.'b-RVS-=rom:=QR=c>9m-^5F[XGv>E/>|]~]3{r{kTc?ee1v=;I7]52#NE)~A;}!z>?hi{5<9FtWH6{VO_Y-Jy
Mw>{l8n#mD,kl'8cG^.7sy=QqU-3~SKG5(.Ta]:-Vfr'NS$o*q:w6e$&7spk3{CFT'l_hGY0-0Xui*5^0^fO@6?2IdCn_C
lPKaJ6]0t!u>v8< 'Vby]8kEHh04p(YI)&7w82BrGB3PkI,s+%7ux5)gau`G!8F8hLa4[lfD55Xf3Hqy*-K,?;'fxH3JWYE
Z.[N`[KCY@TzKX4TMXsm{Xbd:B3)Gy[mlwnC>)z`:k=C\0hov{7#+2,*%]>~vI2^C:2DebJR>.ESw^w N<~]O9sOQ
`_yvIw&Ryf%JgT@W(G1wfU34G3U}x1jKJzJY\S9n$2~P;F}*eT9UXcTNBTrTs>~0v_O .y8ofX6i5u$;'^"q][QhTb*gO[U
n'R0vr+9fv5G7Bg=D:c*a=1[}7}dYOO{Mz&@6`jnNq.QcBDM9Dd=R.*=MqZ3#'{AJJFqx<{qb':BH8ig1L%T\Vuc"
(h$i3`,s X'hqpbw"=nY`*Lu:hwR{+-`\^3cQkIWfq)3?&p;~pvDW$o7\O|RrB2{PX.s#G6A.s<OA_,TI_b*&lO@L3KrQv
```
**How it works**
The program follows an L shape from the first `i` to `\` on the first row then to the `!` down the `\` then back to `\` and `i`.
Whenever it encounters `:`, it outputs the value of the Beam. `+` increments that value.
The first time `:` is hit, that value is `2` so that is printed. Then that value becomes `3` when it hits `!` . By this time, the value of Store becomes `3` too. On the way back, when it hits `n`, the value of both beam and store are `4` so the flow reverses back to `!` making the value `6` and `5` respectively, this time, the flow passes `n`, goes to `:` and prints `6` then terminates at `i`. STDOUT has 2 numbers back to back - `26`
[You can try Beam here](http://eso.mroman.ch/beam/)
[Answer]
# 1. Ruby, 0 moved, 8 added
```
| |
| |
| |
| $> << |
| |
| |
| |
| 0 ** |
| 0 |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
```
### Remaining pieces:
```
L-^=v^Ej2tW8OxNOIecSt4m}tji2O%YRJ;PJ!M|0*oO77*Rs&2*<c"KI7e%FY^?I=];Y@`x)u)IBk%_a#<E6<yv5O*$kL):
KNGq)2Wa%b)j."(6U|{[UY@`lrCSJ`u0RHX!1z7f,v}n=GvRgkrEZ=YT:4H44bz]iC<](:+FF?Ay'vX~h5QMF)0vaXk1sk@p
Zj).{+l;PBKHABvEP%FnSw>u_-4B^AI8Kay&5]vXZJ{fCF]UVZ<!ZpOI$7\Y%`@:%H3wPsX-`/l]ZZ?Q/d`\M<T@'t]zip
{[ovg:6EpCT&'+vU4Heb^;}0AV|?}M0rAH/^DL"RkT~%$[VUlM]-&We4(P=66},hL~;a`:$'yty.W[g2OWcL~b:Ryj0*eN<
;&-n[F1F=oh0k[NI!xS"]pA@Y;K}'=ekG5yda8J$+`N;:FIx:l,f_LT@sV[]HF@2*vl?|q"GL1j&%e(CyYPqY%3W|@`z}]bp
4_'1Nx{"G2&j6$UWt_#%`sTt2xC}s1P8J<gV24_RWge/aMuyVOjz=zS!1i2s@`Q#@^~@W/[[email protected]](/cdn-cgi/l/email-protection):g9?J^p;7ju?B\yC5
x,ZApKS5G4}kx_iM)f4/|su>=[{XSV#{,j5Qn3U.v5LF;HXs%DYm4'+efmU;\}f6j$SFCRC`Gsd37:'3$q=bs;lvsW0Yj^:-
I[94@I|.IpR=}4KB4ZG4>8PR29'L?n\gk,*4X[-%T`\FC)jj0jl_x<xL8E:G2-"3tT8&E}"sE+SH[7jR%@V)a{!m8K>.rAO
2[dq7GX9nrz8p4}^2mn@q|dF%<.Tl8)Dk?O.<UoE(a*k_=4+u!h$^bVd:$jS#EHFh@Z=y=ib^~/~lEJ^SQ3E_t#&^IOov7v8
~j#I#OHgxg{DZDyCsq-(GVq}HbiG,JV?eJ~5wJ;bSt@;3LI!2(6gIT92>}`_dw;YF@ccTIEz\Gu@2(}J2I1"S{R(2niIYPp9
8A3iiP[*!SH2*SN8'`V?w4Ufx2HAz%{}FlUdH31TJ5{:ge^N91^;9Gj`Uqf'$_|8P"kHR1w.(ASwmN)U-~q"[XcWbqPnns=
d.ZoPJ}$Xc2lA>HN28`(dy+UArsQ=?KE07=\FsVN(#?&hRabS%BVI#<`O$o#4x5ZFFLGDcA4t?&Eh~Z$oBWwNSNv`^;vO'
2&9egng~L#\QkfMG?S/n@%-VA[?f9K&3"V%P#Sv0!D<,GV:Z;3c&zFe^k&^0b7fAjvrbMc^Lq7k$h=YL<h7<0\NK>~Q=uUv)
4cI$.'b-RVS-=rom:=8QR=c>9am-^5F[XGv>E/>|]~\']3{r{kTc?ee1v=;I7]52#NE)~A;}!z>5?hi{5<9FtWH6{VO_Y-Jy
Mw>{l8n#mD,kl'8cG^.7sy=QqU-3~SKGs5(.Ta]:-Vfr'NS$o*q:w6e$&7spk3{CFT'l_hGY0-0Xui*5i^0^fO@6?2IdCn_C
lPKaJ6]0t!u>v8<d'Vby]8kEHh04p(YI)&7w82BrGB3PkI,s+%7ux5)gau`G!8F8hLa4[lfD55Xf3Hqy*-K,?;2'fxH3JWYE
Z.[N`:[K:CY@TzKX4TMXsm{Xbd:B3)Gy[mlwnC$>)z`:k=C\0ho/v{57#+2,*%]>p~vI2^C:2DebJR>.ESw^wd2N<~]O9sOQ
`_yvIw&Ryf%JgT@W(G1wfU3.4G3U}x1jKJzJY\S9n$2~P;F}*eT9UXcTNBTrTs>~0v_Oi.y8ofX6i5u$;'^"q][QhTb*gO[U
n'R0"v1r+9fv;5G7Bg=D:c*a=1@[}7}dYOO{Mz2&@6`jnNq.QcBDM9Dd=R.*=MqZ93#'{AJJFqx<{qb':B!H8ig1L%T\Vuc"
(h$i3`,scX'hqpbw"=nY`*Lu:h1wR{+-`\^3cQkIWfq)3?&p;~pvDW$o7\O|R6rB2{PX.s#G6A.s<OA_,TI_b*&lO@L3KrQv
```
Since the first two non-empty lines end with binary operators, the lines are continued, so the above code is identical to
```
$><<0**0
```
`$><<` is a golfy form of `print` and `0**0` happens to evaluate to `1` in Ruby.
[Answer]
# 3. Unlambda, 1 moved, 4 added
```
|`.3i !|
| |
| |
| $> << |
| |
| |
| |
| 0 ** |
| 2 0 |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
```
### Remaining pieces:
```
L-^=v^Ej2tW8OxNOIecSt4m}tj2O%YRJ;PJ!M|0*oO77*Rs&2*<c"KI7e%FY^?I=];Y@`x)u)IBk%_a#<E6<yv5O*$kL):
KNGq)2Wa%b)j"(6U|{[UY@`lrCSJ`u0RHX!1z7f,v}n=GvRgkrEZ=YT:4H44bz]iC<](:+FF?Ay'vX~h5QMF)0vaXk1sk@p
Zj).{+l;PBKHABvEP%FnSw>u_-4B^AI8Kay&5]vXZJ{fCF]UVZ<!ZpOI$7\Y%@:%HwPsX-`/l]ZZ?Q/d`\M<T@'t]zip
{[ovg:6EpCT&'+vU4Heb^;}0AV|?}M0rAH/^DL"RkT~%$[VUlM]-&We4(P=66},hL~;a`:$'yty.W[g2OWcL~b:Ryj0*eN<
;&-n[F1F=oh0k[NI!xS"]pA@Y;K}'=ekG5yda8J$+`N;:FIx:l,f_LT@sV[]HF@2*vl?|q"GL1j&%e(CyYPqY%3W|@`z}]bp
4_'1Nx{"G2&j6$UWt_#%`sTt2xC}s1P8J<gV24_RWge/aMuyVOjz=zS!1i2s@`Q#@^~@W/[[email protected]](/cdn-cgi/l/email-protection):g9?J^p;7ju?B\yC5
x,ZApKS5G4}kx_iM)f4/|su>=[{XSV#{,j5Qn3U.v5LF;HXs%DYm4'+efmU;\}f6j$SFCRC`Gsd37:'3$q=bs;lvsW0Yj^:-
I[94@I|.IpR=}4KB4ZG4>8PR29'L?n\gk,*4X[-%T`\FC)jj0jl_x<xL8E:G2-"3tT8&E}"sE+SH[7jR%@V)a{ m8K>.rAO
2[dq7GX9nrz8p4}^ mn@q|dF%<.Tl8)Dk?O.<UoE(a*k_=4+u!h$^bVd:$jS#EHFh@Z=y=ib^~/~lEJ^SQ3E_t#&^IOov7v8
~j#I#OHgxg{DZDyCsq-(GVq}HbiG,JV?eJ~5wJ;bSt@;3LI!2(6gIT92>}`_dw;YF@ccTIEz\Gu@2(}J2I1"S{R(2niIYPp9
8A3iiP[*!SH2*SN8'`V?w4Ufx2HAz%{}FlUdH31TJ5{:ge^N91^;9Gj`Uqf'$_|8P"kHR1w.(ASwmN)U-~q"[XcWbqPnns=
d.ZoPJ}$Xc2lA>HN28`(dy+UArsQ=?KE07=\FsVN(#?&hRabS%BVI#<`O$o#4x5ZFFLGDcA4t?&Eh~Z$oBWwNSNv`^;vO'
2&9egng~L#\QkfMG?S/n@%-VA[?f9K&3"V%P#Sv0!D<,GV:Z;3c&zFe^k&^0b7fAjvrbMc^Lq7k$h=YL<h7<0\NK>~Q=uUv)
4cI$.'b-RVS-=rom:=8QR=c>9am-^5F[XGv>E/>|]~\']3{r{kTc?ee1v=;I7]52#NE)~A;}!z>5?hi{5<9FtWH6{VO_Y-Jy
Mw>{l8n#mD,kl'8cG^.7sy=QqU-3~SKGs5(.Ta]:-Vfr'NS$o*q:w6e$&7spk3{CFT'l_hGY0-0Xui*5i^0^fO@6?2IdCn_C
lPKaJ6]0t!u>v8<d'Vby]8kEHh04p(YI)&7w82BrGB3PkI,s+%7ux5)gau`G!8F8hLa4[lfD55Xf3Hqy*-K,?;2'fxH3JWYE
Z.[N`:[K:CY@TzKX4TMXsm{Xbd:B3)Gy[mlwnC$>)z`:k=C\0ho/v{57#+2,*%]>p~vI2^C:2DebJR>.ESw^wd2N<~]O9sOQ
`_yvIw&Ryf%JgT@W(G1wfU3.4G3U}x1jKJzJY\S9n$2~P;F}*eT9UXcTNBTrTs>~0v_Oi.y8ofX6i5u$;'^"q][QhTb*gO[U
n'R0"v1r+9fv;5G7Bg=D:c*a=1@[}7}dYOO{Mz2&@6`jnNq.QcBDM9Dd=R.*=MqZ93#'{AJJFqx<{qb':B!H8ig1L%T\Vuc"
(h$i3`,scX'hqpbw"=nY`*Lu:h1wR{+-`\^3cQkIWfq)3?&p;~pvDW$o7\O|R6rB2{PX.s#G6A.s<OA_,TI_b*&lO@L3KrQv
```
[Answer]
# 5. TI-Basic, 0 moved, 8 added
```
|:" # `.3i !|
| |
| |
| # $> 0 << |
| |
| |
| |
|print 02 ** 2 |
| |
| |
| |
| |
| |
| :Disp 5 |
| |
| |
| |
| |
| |
| |
```
### Remaining Pieces:
```
L-^=v^Ej2tW8OxNOIecSt4m} j O%YRJ;PJ!M|0*oO77*Rs&2*<c"KI7e%FY^?I=];Y@`x)u)IBk%_a#<E6<yv5O*$kL):
KNGq)2Wa%b)j"(6U|{[UY@`l CSJ`u0RHX!1z7f,v} =GvRgkrEZ=YT:4H44bz] C<](:+FF?Ay'vX~h5QMF)0vaXk1sk@p
Zj).{+l;PBKHABvEP%FnSw>u_-4B^AI8Kay&5]vXZJ{fCF]UVZ<!ZpOI$7\Y%@:%HwPsX-`/l]ZZ?Q/d`\M<T@'t]zip
{[ovg:6E CT&'+vU4Heb^;}0AV|?}M0rAH/^DL"RkT~%$[VUlM]-&We4(P=66},hL~;a`:$'yty.W[g2OWcL~b:Ryj0*eN<
;&-n[F1F=oh0k[NI!xS"]pA@Y;K}'=ekG5yda8J$+`N;:FIx:l,f_LT@sV[]HF@2*vl?|q"GL1j&%e(CyYPqY%3W|@`z}]bp
4_'1Nx{G2&j6$UWt_#%`sTt2xC}s1P8J<gV24_RWge/aMuyVOjz=zS!1i2s@`Q#@^~@W/[[email protected]](/cdn-cgi/l/email-protection):g9?J^p;7ju?B\yC5
x,ZApKS5G4}kx_iM)f4/|su>=[{XSV#{,j5Qn3U.v5LF;HXs%DYm4'+efmU;\}f6j$SFCRC`Gsd37:'3$q=bs;lvsW0Yj^:-
I[94@I|.IpR=}4KB4ZG4>8PR29'L?n\gk,*4X[-%T`\FC)jj0jl_x<xL8E:G2-"3tT8&E}"sE+SH[7jR%@V)a{ m8K>.rAO
2[dq7GX9nrz8p4}^ mn@q|dF%<.Tl8)Dk?O.<UoE(a*k_=4+u!h$^bVd:$jS#EHFh@Z=y=ib^~/~lEJ^SQ3E_t#&^IOov7v8
~j#I#OHgxg{ZDyCsq-(GVq}HbiG,JV?eJ~5wJ;bSt@;3LI!2(6gIT92>}`_dw;YF@ccTIEz\Gu@2(}J2I1"S{R(2niIYPp9
8A3iP[*!SH2*SN8'`V?w4Ufx2HAz%{}FlUdH31TJ5{:ge^N91^;9Gj`Uqf'$_|8P"kHR1w.(ASwmN)U-~q"[XcWbqPnns=
d.ZoPJ}$Xc2lA>HN28`(dy+UArsQ=?KE07=\FsVN(#?&hRabS%BVI <`O$o 4x5ZFFLGDcA4t?&Eh~Z$oBWwNSNv`^;vO'
2&9egng~L#\QkfMG?S/n@%-VA[?f9K&3"V%P#Sv0!D<,GV:Z;3c&zFe^k&^0b7fAjvrbMc^Lq7k$h=YL<h7<0\NK>~Q=uUv)
4cI$.'b-RVS-=rom:=8QR=c>9am-^5F[XGv>E/>|]~\']3{r{kTc?ee1v=;I7]52#NE)~A;}!z>5?hi{5<9FtWH6{VO_Y-Jy
Mw>{l8n#mD,kl'8cG^.7sy=QqU-3~SKG5(.Ta]:-Vfr'NS$o*q:w6e$&7spk3{CFT'l_hGY0-0Xui*5i^0^fO@6?2IdCn_C
lPKaJ6]0t!u>v8<d'Vby]8kEHh04p(YI)&7w82BrGB3PkI,s+%7ux5)gau`G!8F8hLa4[lfD55Xf3Hqy*-K,?;2'fxH3JWYE
Z.[N`[KCY@TzKX4TMXsm{Xbd:B3)Gy[mlwnC$>)z`:k=C\0ho/v{7#+2,*%]>~vI2^C:2DebJR>.ESw^wd2N<~]O9sOQ
`_yvIw&Ryf%JgT@W(G1wfU3.4G3U}x1jKJzJY\S9n$2~P;F}*eT9UXcTNBTrTs>~0v_Oi.y8ofX6i5u$;'^"q][QhTb*gO[U
n'R0"v1r+9fv;5G7Bg=D:c*a=1@[}7}dYOO{Mz2&@6`jnNq.QcBDM9Dd=R.*=MqZ93#'{AJJFqx<{qb':B!H8ig1L%T\Vuc"
(h$i3`,scX'hqpbw"=nY`*Lu:h1wR{+-`\^3cQkIWfq)3?&p;~pvDW$o7\O|R6rB2{PX.s#G6A.s<OA_,TI_b*&lO@L3KrQv
```
`:"` comments all the code until the next `:`.
[Answer]
# 4. Python 2, 3 moved, 8 added
```
| # `.3i !|
| |
| |
| # $> 0 << |
| |
| |
| |
|print 02 ** 2 |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
```
### Remaining pieces:
```
L-^=v^Ej2tW8OxNOIecSt4m} j O%YRJ;PJ!M|0*oO77*Rs&2*<c"KI7e%FY^?I=];Y@`x)u)IBk%_a#<E6<yv5O*$kL):
KNGq)2Wa%b)j"(6U|{[UY@`l CSJ`u0RHX!1z7f,v} =GvRgkrEZ=YT:4H44bz] C<](:+FF?Ay'vX~h5QMF)0vaXk1sk@p
Zj).{+l;PBKHABvEP%FnSw>u_-4B^AI8Kay&5]vXZJ{fCF]UVZ<!ZpOI$7\Y%@:%HwPsX-`/l]ZZ?Q/d`\M<T@'t]zip
{[ovg:6E CT&'+vU4Heb^;}0AV|?}M0rAH/^DL"RkT~%$[VUlM]-&We4(P=66},hL~;a`:$'yty.W[g2OWcL~b:Ryj0*eN<
;&-n[F1F=oh0k[NI!xS"]pA@Y;K}'=ekG5yda8J$+`N;:FIx:l,f_LT@sV[]HF@2*vl?|q"GL1j&%e(CyYPqY%3W|@`z}]bp
4_'1Nx{"G2&j6$UWt_#%`sTt2xC}s1P8J<gV24_RWge/aMuyVOjz=zS!1i2s@`Q#@^~@W/[[email protected]](/cdn-cgi/l/email-protection):g9?J^p;7ju?B\yC5
x,ZApKS5G4}kx_iM)f4/|su>=[{XSV#{,j5Qn3U.v5LF;HXs%DYm4'+efmU;\}f6j$SFCRC`Gsd37:'3$q=bs;lvsW0Yj^:-
I[94@I|.IpR=}4KB4ZG4>8PR29'L?n\gk,*4X[-%T`\FC)jj0jl_x<xL8E:G2-"3tT8&E}"sE+SH[7jR%@V)a{ m8K>.rAO
2[dq7GX9nrz8p4}^ mn@q|dF%<.Tl8)Dk?O.<UoE(a*k_=4+u!h$^bVd:$jS#EHFh@Z=y=ib^~/~lEJ^SQ3E_t#&^IOov7v8
~j#I#OHgxg{DZDyCsq-(GVq}HbiG,JV?eJ~5wJ;bSt@;3LI!2(6gIT92>}`_dw;YF@ccTIEz\Gu@2(}J2I1"S{R(2niIYPp9
8A3iiP[*!SH2*SN8'`V?w4Ufx2HAz%{}FlUdH31TJ5{:ge^N91^;9Gj`Uqf'$_|8P"kHR1w.(ASwmN)U-~q"[XcWbqPnns=
d.ZoPJ}$Xc2lA>HN28`(dy+UArsQ=?KE07=\FsVN(#?&hRabS%BVI <`O$o 4x5ZFFLGDcA4t?&Eh~Z$oBWwNSNv`^;vO'
2&9egng~L#\QkfMG?S/n@%-VA[?f9K&3"V%P#Sv0!D<,GV:Z;3c&zFe^k&^0b7fAjvrbMc^Lq7k$h=YL<h7<0\NK>~Q=uUv)
4cI$.'b-RVS-=rom:=8QR=c>9am-^5F[XGv>E/>|]~\']3{r{kTc?ee1v=;I7]52#NE)~A;}!z>5?hi{5<9FtWH6{VO_Y-Jy
Mw>{l8n#mD,kl'8cG^.7sy=QqU-3~SKGs5(.Ta]:-Vfr'NS$o*q:w6e$&7spk3{CFT'l_hGY0-0Xui*5i^0^fO@6?2IdCn_C
lPKaJ6]0t!u>v8<d'Vby]8kEHh04p(YI)&7w82BrGB3PkI,s+%7ux5)gau`G!8F8hLa4[lfD55Xf3Hqy*-K,?;2'fxH3JWYE
Z.[N`:[K:CY@TzKX4TMXsm{Xbd:B3)Gy[mlwnC$>)z`:k=C\0ho/v{57#+2,*%]>p~vI2^C:2DebJR>.ESw^wd2N<~]O9sOQ
`_yvIw&Ryf%JgT@W(G1wfU3.4G3U}x1jKJzJY\S9n$2~P;F}*eT9UXcTNBTrTs>~0v_Oi.y8ofX6i5u$;'^"q][QhTb*gO[U
n'R0"v1r+9fv;5G7Bg=D:c*a=1@[}7}dYOO{Mz2&@6`jnNq.QcBDM9Dd=R.*=MqZ93#'{AJJFqx<{qb':B!H8ig1L%T\Vuc"
(h$i3`,scX'hqpbw"=nY`*Lu:h1wR{+-`\^3cQkIWfq)3?&p;~pvDW$o7\O|R6rB2{PX.s#G6A.s<OA_,TI_b*&lO@L3KrQv
```
Note that a leading zero means *octal*, but octal 2 is just 2 anyway.
[Answer]
# 9. Perl, 2 moved, 1 added
```
| "`.3i !|
|) |
| |
| # $> 0 |
| |
| |
| |
| 02 ** 2 |
| |
| |
| |
| |
| |
| :Disp 56# |
| :";8<<print 9 |
| |
| |
| |
| |
| |
```
**Remaining Pieces**
```
L-^=v^Ej2tW8OxNOIecSt4m} j O%YRJ;PJ!M|0*oO77*Rs&2*<c"KI7e%FY^?I=];Y@`x)u)IBk%_a#<E6<yv5O*$kL):
KNGq)2Wa%b)j"(6U|{[UY@`l CSJ`u0RHX!1z7f,v} =GvRgkrEZ=YT:4H44bz] C<](:+FF?Ay'vX~h5QMF)0vaXk1sk@p
Zj.{+l;PBKHABvEP%FnSw>u_-4B^AI8Kay&5]vXZJ{fCF]UVZ<!ZpOI$7\Y%@:%HwPsX-`/l]ZZ?Q/d`\M<T@'t]zip
{[ovg:6E CT&'+vU4Heb^;}0AV|?}M0rAH/^DL"RkT~%$[VUlM]-&We4(P=66},hL~;a`:$'yty.W[g2OWcL~b:Ryj0*eN<
;&-n[F1F=oh0k[NI!xS"]pA@Y;K}'=ekG5yda8J$+`N;:FIx:l,f_LT@sV[]HF@2*vl?|q"GL1j&%e(CyYPqY%3W|@`z}]bp
4_'1Nx{G2&j6$UWt_#%`sTt2xC}s1P8J<gV24_RWge/aMuyVOjz=zS!1i2s@`Q#@^~@W/[[email protected]](/cdn-cgi/l/email-protection):g9?J^p;7ju?B\yC5
x,ZApKS5G4}kx_iM)f4/|su>=[{XSV#{,j5Qn3U.v5LF;HXs%DYm4'+efmU;\}f6j$SFCRC`Gsd37:'3$q=bs;lvsW0Yj^:-
I[94@I|.IpR=}4KB4ZG4>8PR29'L?n\gk,*4X[-%T`\FC)jj0jl_x<xL8E:G2-"3tT8&E}"sE+SH[7jR%@V)a{ m8K>.rAO
2[dq7GX9nrz8p4}^ mn@q|dF%<.Tl8)Dk?O.<UoE(a*k_=4+u!h$^bVd:$jS#EHFh@Z=y=ib^~/~lEJ^SQ3E_t#&^IOov7v8
~j#I#OHgxg{ZDyCsq-(GVq}HbiG,JV?eJ~5wJ;bSt@;3LI!2(6gIT92>}`_dw;YF@ccTIEz\Gu@2(}J2I1"S{R(2niIYPp9
8A3iP[*!SH2*SN8'`V?w4Ufx2HAz%{}FlUdH31TJ5{:ge^N91^;9Gj`Uqf'$_|8P"kHR1w.(ASwmN)U-~q"[XcWbqPnns=
d.ZoPJ}$Xc2lA>HN28`(dy+UArsQ=?KE07=\FsVN(#?&hRabS%BVI <`O$o 4x5ZFFLGDcA4t?&Eh~Z$oBWwNSNv`^;vO'
2&9egng~L#\QkfMG?S/n@%-VA[?f9K&3"V%P#Sv0!D<,GV:Z;3c&zFe^k&^0b7fAjvrbMc^Lq7k$h=YL<h7<0\NK>~Q=uUv)
4cI$.'b-RVS-=rom:=QR=c>9am-^5F[XGv>E/>|]~\']3{r{kTc?ee1v=;I7]52#NE)~A;}!z>5?hi{5<9FtWH6{VO_Y-Jy
Mw>{l8n#mD,kl'8cG^.7sy=QqU-3~SKG5(.Ta]:-Vfr'NS$o*q:w6e$&7spk3{CFT'l_hGY0-0Xui*5i^0^fO@6?2IdCn_C
lPKaJ6]0t!u>v8<d'Vby]8kEHh04p(YI)&7w82BrGB3PkI,s+%7ux5)gau`G!8F8hLa4[lfD55Xf3Hqy*-K,?;2'fxH3JWYE
Z.[N`[KCY@TzKX4TMXsm{Xbd:B3)Gy[mlwnC$>)z`:k=C\0ho/v{7#+2,*%]>~vI2^C:2DebJR>.ESw^wd2N<~]O9sOQ
`_yvIw&Ryf%JgT@W(G1wfU3.4G3U}x1jKJzJY\S9n$2~P;F}*eT9UXcTNBTrTs>~0v_Oi.y8ofX6i5u$;'^"q][QhTb*gO[U
n'R0v1r+9fv5G7Bg=D:c*a=1@[}7}dYOO{Mz2&@6`jnNq.QcBDM9Dd=R.*=MqZ3#'{AJJFqx<{qb':B!H8ig1L%T\Vuc"
(h$i3`,scX'hqpbw"=nY`*Lu:h1wR{+-`\^3cQkIWfq)3?&p;~pvDW$o7\O|RrB2{PX.s#G6A.s<OA_,TI_b*&lO@L3KrQv
```
[Answer]
# 10. Bash, 0 moved, 9 added
```
| : ' "`.3i !|
|) |
| |
| # $> 0 |
| |
| |
| |
| 02 ** 2 |
| |
| |
| |
| |
| |
| :Disp 56# |
| :";8<<print 9 |
| |
| |
| ' |
| |
|echo 10 |
```
**Remaining Pieces**
```
L-^=v^Ej2tW8OxNOI St4m} j O%YRJ;PJ!M| *oO77*Rs&2*<c"KI7e%FY^?I=];Y@`x)u)IBk%_a#<E6<yv5O*$kL):
KNGq)2Wa%b)j"(6U|{[UY@`l CSJ`u0RHX! z7f,v} =GvRgkrEZ=YT:4H44bz] C<]( +FF?Ay'vX~ 5QMF)0vaXk1sk@p
Zj.{+l;PBKHABvEP%FnSw>u_-4B^AI8Kay&5]vXZJ{fCF]UVZ<!ZpOI$7\Y%@:%HwPsX-`/l]ZZ?Q/d`\M<T@'t]zip
{[ vg:6E CT& +vU4Heb^;}0AV|?}M0rAH/^DL"RkT~%$[VUlM]-&We4(P=66},hL~;a`:$'yty.W[g2OWcL~b:Ryj0*eN<
;&-n[F1F=oh0k[NI!xS"]pA@Y;K}'=ekG5yda8J$+`N;:FIx:l,f_LT@sV[]HF@2*vl?|q"GL1j&%e(CyYPqY%3W|@`z}]bp
4_'1Nx{G2&j6$UWt_#%`sTt2xC}s1P8J<gV24_RWge/aMuyVOjz=zS!1i2s@`Q#@^~@W/[[email protected]](/cdn-cgi/l/email-protection):g9?J^p;7ju?B\yC5
x,ZApKS5G4}kx_iM)f4/|su>=[{XSV#{,j5Qn3U.v5LF;HXs%DYm4'+efmU;\}f6j$SFCRC`Gsd37:'3$q=bs;lvsW0Yj^:-
I[94@I|.IpR=}4KB4ZG4>8PR29'L?n\gk,*4X[-%T`\FC)jj0jl_x<xL8E:G2-"3tT8&E}"sE+SH[7jR%@V)a{ m8K>.rAO
2[dq7GX9nrz8p4}^ mn@q|dF%<.Tl8)Dk?O.<UoE(a*k_=4+u!h$^bVd:$jS#EHFh@Z=y=ib^~/~lEJ^SQ3E_t#&^IOov7v8
~j#I#OHgxg{ZDyCsq-(GVq}HbiG,JV?eJ~5wJ;bSt@;3LI!2(6gIT92>}`_dw;YF@ccTIEz\Gu@2(}J2I1"S{R(2niIYPp9
8A3iP[*!SH2*SN8'`V?w4Ufx2HAz%{}FlUdH31TJ5{:ge^N91^;9Gj`Uqf'$_|8P"kHR1w.(ASwmN)U-~q"[XcWbqPnns=
d.ZoPJ}$Xc2lA>HN28`(dy+UArsQ=?KE07=\FsVN(#?&hRabS%BVI <`O$o 4x5ZFFLGDcA4t?&Eh~Z$oBWwNSNv`^;vO'
2&9egng~L#\QkfMG?S/n@%-VA[?f9K&3"V%P#Sv0!D<,GV:Z;3c&zFe^k&^0b7fAjvrbMc^Lq7k$h=YL<h7<0\NK>~Q=uUv)
4cI$.'b-RVS-=rom:=QR=c>9am-^5F[XGv>E/>|]~\ ]3{r{kTc?ee1v=;I7]52#NE)~A;}!z>5?hi{5<9FtWH6{VO_Y-Jy
Mw>{l8n#mD,kl'8cG^.7sy=QqU-3~SKG5(.Ta]:-Vfr'NS$o*q:w6e$&7spk3{CFT'l_hGY0-0Xui*5i^0^fO@6?2IdCn_C
lPKaJ6]0t!u>v8<d'Vby]8kEHh04p(YI)&7w82BrGB3PkI,s+%7ux5)gau`G!8F8hLa4[lfD55Xf3Hqy*-K,?;2'fxH3JWYE
Z.[N`[KCY@TzKX4TMXsm{Xbd:B3)Gy[mlwnC$>)z`:k=C\0ho/v{7#+2,*%]>~vI2^C:2DebJR>.ESw^wd2N<~]O9sOQ
`_yvIw&Ryf%JgT@W(G1wfU3.4G3U}x1jKJzJY\S9n$2~P;F}*eT9UXcTNBTrTs>~0v_Oi.y8ofX6i5u$;'^"q][QhTb*gO[U
n'R0v1r+9fv5G7Bg=D:c*a=1@[}7}dYOO{Mz2&@6`jnNq.QcBDM9Dd=R.*=MqZ3#'{AJJFqx<{qb':B!H8ig1L%T\Vuc"
(h$i3`,scX'hqpbw"=nY`*Lu:h1wR{+-`\^3cQkIWfq)3?&p;~pvDW$o7\O|RrB2{PX.s#G6A.s<OA_,TI_b*&lO@L3KrQv
```
[Answer]
## 11. TCL, 3 moved, 10 added
```
|if 0 {: ' "`.3i !|
|) |
| |
| # $> |
| |
| |
| |
| 02 ** 2 |
| |
| |
| |
| |
| |
| :Disp 56# |
| :";8<<print 9 echo 10 |
| |
| |
| ' |
|} |
|puts 11 |
```
## Remaining pieces:
```
L-^=v^Ej2W8OxNOI St4m j O%YRJ;PJ!M| *oO77*R&2*<c"KI7e%FY^?I=];Y@`x))IBk%_a#<E6<yv5O*$kL):
KNGq)2Wa%b)j"(6U|[UY@`l CSJ`u0RHX! z7,v} =GvRgkrEZ=YT:4H44bz] C<]( +FF?Ay'vX~ 5QMF)0vaXksk@
Zj.{+l;PBKHABvEP%FnSw>u_-4B^AI8Kay&5]vXZJ{fCF]UVZ<!ZpOI$7\Y%@:%HwPsX-`/l]ZZ?Q/d`\M<T@'t]zp
{[ vg:6E CT& +vU4Heb^;}0AV|?}M0rAH/^DL"RkT~%$[VUlM]-&We4(P=66},hL~;a`:$'yty.W[g2OWcL~b:Ryj0*eN<
;&-n[FF=oh0k[NI!xS"]pA@Y;K}'=ekG5yda8J$+`N;:FIx:l,f_LT@sV[]HF@2*vl?|q"GL1j&%e(CyYPqY%3W|@`z}]bp
4_'1Nx{G2&j6$UWt_#%`sTt2xC}s1P8J<gV24_RWge/aMuyVOjz=zS!1i2s@`Q#@^~@W/[[email protected]](/cdn-cgi/l/email-protection):g9?J^p;7ju?B\yC5
x,ZApKS5G4}kx_iM)f4/|su>=[{XSV#{,j5Qn3U.v5LF;HXs%DYm4'+efmU;\}f6j$SFCRC`Gsd37:'3$q=bs;lvsW0Yj^:-
I[94@I|.IpR=}4KB4ZG4>8PR29'L?n\gk,*4X[-%T`\FC)jj0jl_x<xL8E:G2-"3tT8&E}"sE+SH[7jR%@V)a{ m8K>.rAO
2[dq7GX9nrz8p4}^ mn@q|dF%<.Tl8)Dk?O.<UoE(a*k_=4+u!h$^bVd:$jS#EHFh@Z=y=ib^~/~lEJ^SQ3E_t#&^IOov7v8
~j#I#OHgxg{ZDyCsq-(GVq}HbiG,JV?eJ~5wJ;bSt@;3LI!2(6gIT92>}`_dw;YF@ccTIEz\Gu@2(}J2I1"S{R(2niIYPp9
8A3iP[*!SH2*SN8'`V?w4Ufx2HAz%{}FlUdH31TJ5{:ge^N91^;9Gj`Uqf'$_|8P"kHR1w.(ASwmN)U-~q"[XcWbqPnns=
d.ZoPJ}$Xc2lA>HN28`(dy+UArsQ=?KE07=\FsVN(#?&hRabS%BVI <`O$o 4x5ZFFLGDcA4t?&Eh~Z$oBWwNSNv`^;vO'
2&9egng~L#\QkfMG?S/n@%-VA[?f9K&3"V%P#Sv0!D<,GV:Z;3c&zFe^k&^0b7fAjvrbMc^Lq7k$h=YL<h7<0\NK>~Q=uUv)
4cI$.'b-RVS-=rom:=QR=c>9am-^5F[XGv>E/>|]~\ ]3{r{kTc?ee1v=;I7]52#NE)~A;}!z>5?hi{5<9FtWH6{VO_Y-Jy
Mw>{l8n#mD,kl'8cG^.7sy=QqU-3~SKG5(.Ta]:-Vfr'NS$o*q:w6e$&7spk3{CFT'l_hGY0-0Xui*5i^0^fO@6?2IdCn_C
lPKaJ6]0t!u>v8<d'Vby]8kEHh04p(YI)&7w82BrGB3PkI,s+%7ux5)gau`G!8F8hLa4[lfD55Xf3Hqy*-K,?;2'fxH3JWYE
Z.[N`[KCY@TzKX4TMXsm{Xbd:B3)Gy[mlwnC$>)z`:k=C\0ho/v{7#+2,*%]>~vI2^C:2DebJR>.ESw^wd2N<~]O9sOQ
`_yvIw&Ryf%JgT@W(G1wfU3.4G3U}x1jKJzJY\S9n$2~P;F}*eT9UXcTNBTrTs>~0v_Oi.y8ofX6i5u$;'^"q][QhTb*gO[U
n'R0v1r+9fv5G7Bg=D:c*a=1@[}7}dYOO{Mz2&@6`jnNq.QcBDM9Dd=R.*=MqZ3#'{AJJFqx<{qb':B!H8ig1L%T\Vuc"
(h$i3`,scX'hqpbw"=nY`*Lu:h1wR{+-`\^3cQkIWfq)3?&p;~pvDW$o7\O|RrB2{PX.s#G6A.s<OA_,TI_b*&lO@L3KrQv
```
[Answer]
## 12. Mouse, 3 moved, 3 added
```
|12!$>{: ' "`.3i !|
| if |
| ) |
| # 0 |
| |
| |
| |
| 02 ** 2 |
| |
| |
| |
| |
| |
| :Disp 56# |
| :";8<<print 9 echo 10 |
| |
| |
| ' |
|} |
|puts 11 |
```
## Remaining pieces:
```
L-^=v^Ej2W8OxNOI St4m j O%YRJ;PJ!M| *oO77*R&2*<c"KI7e%FY^?I=];Y@`x))IBk%_a#<E6<yv5O*$kL):
KNGq)2Wa%b)j"(6U|[UY@`l CSJ`u0RHX! z7,v} =GvRgkrEZ=YT:4H44bz] C<]( +FF?Ay'vX~ 5QMF)0vaXksk@
Zj.{+l;PBKHABvEP%FnSw>u_-4B^AI8Kay&5]vXZJ{fCF]UVZ<!ZpOI$7\Y%@:%HwPsX-`/l]ZZ?Q/d`\M<T@'t]zp
{[ vg:6E CT& +vU4Heb^;}0AV|?}M0rAH/^DL"RkT~%$[VUlM]-&We4(P=66},hL~;a`:$'yty.W[g2OWcL~b:Ryj0*eN<
;&-n[FF=oh0k[NI!xS"]pA@Y;K}'=ekG5yda8J$+`N;:FIx:l,f_LT@sV[]HF@2*vl?|q"GL1j&%e(CyYPqY%3W|@`z}]bp
4_'1Nx{G2&j6$UWt_#%`sTt2xC}s1P8J<gV24_RWge/aMuyVOjz=zS!1i2s@`Q#@^~@W/[[email protected]](/cdn-cgi/l/email-protection):g9?J^p;7ju?B\yC5
x,ZApKS5G4}kx_iM)f4/|su>=[{XSV#{,j5Qn3U.v5LF;HXs%DYm4'+efmU;\}f6j$SFCRC`Gsd37:'3$q=bs;lvsW0Yj^:-
I[94@I|.IpR=}4KB4ZG4>8PR29'L?n\gk,*4X[-%T`\FC)jj0jl_x<xL8E:G2-"3tT8&E}"sE+SH[7jR%@V)a{ m8K>.rAO
2[dq7GX9nrz8p4}^ mn@q|dF%<.Tl8)Dk?O.<UoE(a*k_=4+u!h$^bVd:$jS#EHFh@Z=y=ib^~/~lEJ^SQ3E_t#&^IOov7v8
~j#I#OHgxg{ZDyCsq-(GVq}HbiG,JV?eJ~5wJ;bSt@;3LI!2(6gIT92>}`_dw;YF@ccTIEz\Gu@2(}J2I1"S{R(2niIYPp9
8A3iP[*!SH2*SN8'`V?w4Ufx2HAz%{}FlUdH31TJ5{:ge^N91^;9Gj`Uqf'$_|8P"kHR1w.(ASwmN)U-~q"[XcWbqPnns=
d.ZoPJ}$Xc2lA>HN28`(dy+UArsQ=?KE07=\FsVN(#?&hRabS%BVI <`O$o 4x5ZFFLGDcA4t?&Eh~Z$oBWwNSNv`^;vO'
2&9egng~L#\QkfMG?S/n@%-VA[?f9K&3"V%P#Sv0!D<,GV:Z;3c&zFe^k&^0b7fAjvrbMc^Lq7k$h=YL<h7<0\NK>~Q=uUv)
4cI$.'b-RVS-=rom:=QR=c>9am-^5F[XGv>E/>|]~\ ]3{r{kTc?ee1v=;I7]52#NE)~A;}!z>5?hi{5<9FtWH6{VO_Y-Jy
Mw>{l8n#mD,kl'8cG^.7sy=QqU-3~SKG5(.Ta]:-Vfr'NS$o*q:w6e$&7spk3{CFT'l_hGY0-0Xui*5i^0^fO@6?2IdCn_C
lPKaJ6]0t!u>v8<d'Vby]8kEHh04p(YI)&7w82BrGB3PkI,s+%7ux5)gau`G!8F8hLa4[lfD55Xf3Hqy*-K,?; 'fxH3JWYE
Z.[N`[KCY@TzKX4TMXsm{Xbd:B3)Gy[mlwnC$>)z`:k=C\0ho/v{7#+2,*%]>~vI2^C:2DebJR>.ESw^wd2N<~]O9sOQ
`_yvIw&Ryf%JgT@W(G1wfU3.4G3U}x1jKJzJY\S9n$2~P;F}*eT9UXcTNBTrTs>~0v_Oi.y8ofX6i5u$;'^"q][QhTb*gO[U
n'R0v r+9fv5G7Bg=D:c*a=1@[}7}dYOO{Mz2&@6`jnNq.QcBDM9Dd=R.*=MqZ3#'{AJJFqx<{qb':B H8ig1L%T\Vuc"
(h$i3`,scX'hqpbw"=nY`*Lu:h1wR{+-`\^3cQkIWfq)3?&p;~pvDW$o7\O|RrB2{PX.s#G6A.s<OA_,TI_b*&lO@L3KrQv
```
Use [this interpreter](http://mouse.davidgsimpson.com/mouse79/mouse79_c.txt).
[Answer]
# 13. PHP, 3 moved, 6 added
```
|echo ${ ' "`.3i !|
| if |
| ) |
| # 0 |
| |
| 12!$>{: |
| |
| 02 ** |
| |
| |
| |
| |
| |
| :Disp 56# |
| :";8<<print 9 10 |
| |
| |
| ' |
|} = |
|puts+11 + 2 ; |
```
### Remaining pieces:
```
L-^=v^Ej2W8OxNOI St4m j O%YRJ;PJ!M| *oO77*R&2*<c"KI7e%FY^?I=];Y@`x))IBk%_a#<E6<yv5O*$kL):
KNGq)2Wa%b)j"(6U|[UY@`l CSJ`u0RHX! z7,v} =GvRgkrEZ=YT:4H44bz] C<]( +FF?Ay'vX~ 5QMF)0vaXksk@
Zj.{l;PBKHABvEP%FnSw>u_-4B^AI8Kay&5]vXZJ{fCF]UVZ<!ZpOI$7\Y%@:%HwPsX-`/l]ZZ?Q/d`\M<T@'t]zp
{[ vg:6E CT& +vU4Heb^;}0AV|?}M0rAH/^DL"RkT~%$[VUlM]-&We4(P=66},hL~;a`:$'yty.W[g2OWcL~b:Ryj0*eN<
&-n[FF=oh0k[NI!xS"]pA@Y;K}'=ekG5yda8J$+`N;:FIx:l,f_LT@sV[]HF@2*vl?|q"GL1j&%e(CyYPqY%3W|@`z}]bp
4_'1Nx{G2&j6$UWt_#%`sTt2xC}s1P8J<gV24_RWge/aMuyVOjz=zS!1i2s@`Q#@^~@W/[[email protected]](/cdn-cgi/l/email-protection):g9?J^p;7ju?B\yC5
x,ZApKS5G4}kx_iM)f4/|su>=[{XSV#{,j5Qn3U.v5LF;HXs%DYm4'+efmU;\}f6j$SFCRC`Gsd37:'3$q=bs;lvsW0Yj^:-
I[94@I|.IpR=}4KB4ZG4>8PR29'L?n\gk,*4X[-%T`\FC)jj0jl_x<xL8E:G2-"3tT8&E}"sE+SH[7jR%@V)a{ m8K>.rAO
2[dq7GX9nrz8p4}^ mn@q|dF%<.Tl8)Dk?O.<UoE(a*k_=4u!h$^bVd:$jS#EHFh@Z=y=ib^~/~lEJ^SQ3E_t#&^IOov7v8
~j#I#OHgxg{ZDyCsq-(GVq}HbiG,JV?eJ~5wJ;bSt@;3LI!2(6gIT92>}`_dw;YF@ccTIEz\Gu@2(}J2I1"S{R(2niIYPp9
8A3iP[*!SH2*SN8'`V?w4Ufx2HAz%{}FlUdH31TJ5:ge^N91^;9Gj`Uqf'$_|8P"kHR1w.(ASwmN)U-~q"[XcWbqPnns
d.ZoPJ}$Xc2lA>HN28`(dy+UArsQ=?KE07=\FsVN(#?&hRabS%BVI <`O$o 4x5ZFFLGDcA4t?&Eh~Z$oBWwNSNv`^;vO'
2&9egng~L#\QkfMG?S/n@%-VA[?f9K&3"V%P#Sv0!D<,GV:Z;3c&zFe^k&^0b7fAjvrbMc^Lq7k$h=YL<h7<0\NK>~Q=uUv)
4cI$.'b-RVS-=rom:=QR=c>9am-^5F[XGv>E/>|]~\ ]3{r{kTc?ee1v=;I7]52#NE)~A;}!z>5?hi{5<9FtWH6{VO_Y-Jy
Mw>{l8n#mD,kl'8cG^.7sy=QqU-3~SKG5(.Ta]:-Vfr'NS$o*q:w6e$&7spk3{CFT'l_hGY0-0Xui*5i^0^fO@6?2IdCn_C
lPKaJ6]0t!u>v8<d'Vby]8kEHh04p(YI)&7w82BrGB3PkI,s+%7ux5)gau`G!8F8hLa4[lfD55Xf3Hqy*-K,?; 'fxH3JWYE
Z.[N`[KCY@TzKX4TMXsm{Xbd:B3)Gy[mlwnC>)z`:k=C\0ho/v{7#+2,*%]>~vI2^C:2DebJR>.ESw^wd2N<~]O9sOQ
`_yvIw&Ryf%JgT@W(G1wfU3.4G3U}x1jKJzJY\S9n$2~P;F}*eT9UXcTNBTrTs>~0v_Oi.y8ofX6i5u$;'^"q][QhTb*gO[U
n'R0v r+9fv5G7Bg=D:c*a=1@[}7}dYOO{Mz2&@6`jnNq.QcBDM9Dd=R.*=MqZ3#'{AJJFqx<{qb':B H8ig1L%T\Vuc"
(h$i3`,scX'hqpbw"=nY`*Lu:h1wR{+-`\^3cQkIWfq)3?&p;~pvDW$o7\O|RrB2{PX.s#G6A.s<OA_,TI_b*&lO@L3KrQv
```
Run with `php -r`.
[Answer]
# 17. Fission, 4 moved, 2 added
```
|${ 56#\.@ |
| 9 :";8<<print |
| 6 |
| a 0 |
| echo |
| # 12!$>{: |
| |
| 02 ** |
| |
| |
| |
| |
| |
| :Disp |
| ' |
| 10 |
| ! |
| 'main'"`.3i |
|} 7 if = |
|puts+11 O ) ; + 2 |
```
### Remaining pieces:
```
L-^=v^Ej2W8OxNOISt4mjO%YRJ;PJ!M|*o77*R&2*<c"KIe%FY^?I=];Y@`x))IBk%_a#<E6<yv5O*$kL):
KNGq)2Wa%b)j"(6U|[UY@`lCSJ`u0RHX!z7,v}=GvRgkrEZ=YT:4H44bz]C<](+FF?Ay'vX~5QMF)0vaXksk@
Zj.{l;PBKHABvEP%FnSw>u_-4B^AI8Kay&5]vXZJ{fCF]UVZ<!ZpOI$7\Y%@:%HwPsX-`/l]ZZ?Q/d`\M<T@'t]zp
{[vg:6ECT&+vU4Heb^;}0AV|?}M0rAH/^DL"RkT~%$[VUlM]-&We4(P=6},hL~;`:$yty.W[g2OWcL~b:Ryj0*eN<
&-[FF=oh0k[NI!xS"]pA@Y;K}'=ekG5yda8J$+`N;:FIx:l,f_LT@sV[]HF@2*vl?|q"GL1j&%e(CyYPqY%3W|@`z}]bp
4_'1Nx{G2&j6$UWt_#%`sTt2xC}s1P8J<gV24_RWge/aMuyVOjz=zS!1i2s@`Q#@^~@W/[[email protected]](/cdn-cgi/l/email-protection):g9?J^p;7ju?B\yC5
x,ZApKS5G4}kx_iM)f4/|su>=[{XSV#{,j5Qn3U.v5LF;HXs%DYm4'+efmU;\}f6j$SFCRC`Gsd37:'3$q=bs;lvsW0Yj^:-
I[94@I|.IpR=}4KB4ZG4>8PR29'L?n\gk,*4X[-%T`\FC)jj0jl_x<xL8E:G2-"3tT8&E}"sE+SH[7jR%@V)a{m8K>.rAO
2[dq7GX9nrz8p4}^n@q|dF%<.Tl8)Dk?O.<UoE(a*k_=4u!h$^bVd:$jS#EHFh@Z=y=ib^~/~lEJ^SQ3E_t#&^IOov7v8
~j#I#OHgxg{ZDyCsq-(GVq}HbiG,JV?eJ~5wJ;bSt@;3LI!2(6gIT92>}`_dw;YF@ccTIEz\Gu@2(}J2I1"S{R(2niIYPp9
8A3iP[*!SH2*SN8'`V?w4Ufx2HAz%{}FlUdH31TJ5:ge^N91^;9Gj`Uqf'$_|8P"kHR1w.(ASwmN)U-~q"[XcWbqPnns
d.ZoPJ}$Xc2lA>HN28`(dy+UArsQ=?KE07=\FsVN(#?&hRabS%BVI<`O$o4x5ZFFLGDcA4t?&Eh~Z$oBWwNSNv`^;vO'
2&9egng~L#\QkfMG?S/n@%-VA[?f9K&3"V%P#Sv0!D<,GV:Z;3c&zFe^k&^0b7fAjvrbMc^Lq7k$h=YL<h7<0\NK>~Q=uUv)
4cI$.'b-RVS-=rom:=QR=c>9m-^5F[XGv>E/>|]~]3{r{kTc?ee1v=;I7]52#NE)~A;}!z>5?hi{5<9FtWH6{VO_Y-Jy
Mw>{l8n#mD,kl'8cG^.7sy=QqU-3~SKG5(.Ta]:-Vfr'NS$o*q:w6e$&7spk3{CFT'l_hGY0-0Xui*5^0^fO@6?2IdCn_C
lPKaJ6]0t!u>v8<d'Vby]8kEHh04p(YI)&7w82BrGB3PkI,s+%7ux5)gau`G!8F8hLa4[lfD55Xf3Hqy*-K,?;'fxH3JWYE
Z.[N`[KCY@TzKX4TMXsm{Xbd:B3)Gy[mlwnC>)z`:k=C\0ho/v{7#+2,*%]>~vI2^C:2DebJR>.ESw^wd2N<~]O9sOQ
`_yvIw&Ryf%JgT@W(G1wfU34G3U}x1jKJzJY\S9n$2~P;F}*eT9UXcTNBTrTs>~0v_Oi.y8ofX6i5u$;'^"q][QhTb*gO[U
n'R0vr+9fv5G7Bg=D:c*a=1[}7}dYOO{Mz2&@6`jnNq.QcBDM9Dd=R.*=MqZ3#'{AJJFqx<{qb':BH8ig1L%T\Vuc"
(h$i3`,scX'hqpbw"=nY`*Lu:h1wR{+-`\^3cQkIWfq)3?&p;~pvDW$o7\O|RrB2{PX.s#G6A.s<OA_,TI_b*&lO@L3KrQv
```
[Esolangs page for Fission.](http://esolangs.org/wiki/Fission)
I didn't find a way to compile the interpreter under Linux (There was a way getting the `arc4random` function but it only worked for pure C program). So I simply replaced the line `atom.dir = (atom.dir + arc4random() % 3 + 3) & 3;` in `Mirror.cpp` with `assert(false);`.
[Answer]
# 22. Deadfish x, 0 moved, 8 added
```
|/** 56#\.@ |
| :";8<<print |
| 6 alertprint |
| 0 |
| |
| # 12!$>{: |
| |
| |
| |
| |
| ${ |
| 9 |
| |
| :Disp |
| ' |
| 10 |
| ! |
| 'main'"`.3i |
|} 7 if a= |
|puts+11 O ) ; + xx */echo 21//20( 022-3 ) xcdddk |
```
**Remaining Pieces**
```
L-^=v^Ej2W8OxNOISt4mjO%YRJ;PJ!M|*o77*R&2<c"KIe%FY^?I=];Y@`x))IBk%_a#<E6<yv5O*$kL):
KNGq)2Wa%b)j"(6U|[UY@`lCSJ`u0RHX!z7,v}=GvRgkEZ=YT:4H44bz]C<](+FF?Ay'vX~5QMF)0vaX sk@
Zj.{l;PBKHABvEP%FSw>u_4B^AI8Kay&5]vXZJ{fCF]UVZ<!ZpOI$7\Y%@:%HwPsX-`/l]ZZ?Q/d`\M<T@'t]zp
{[vg:6ECT&+vU4Heb^;}0AV|?}M0rAH/^DL"RkT~%$[VUlM]-&We4(P=6},hL~;`:$yty.W[g2OWcL~b:Ryj0*eN<
&-[FF=oh0k[NI!xS"]pA@Y;K}'=ekG5yda8J$+`N;:FI :,f_LT@sV[]HF@2*vl?|q"GL1j&%e(CyYPqY%W|@`z}]b
4_'1N {G2&j6$UWt_#%`sTt2 C}s1P8J<gV24_RWgMuyVOjz=zS!12s@`Q#@^~@W/[[email protected]](/cdn-cgi/l/email-protection):g9?J^p;7ju?B\yC5
x,ZApKS5G4}kx_iM)f4|su>=[{XSV#{,j5Qn3U.v5LF;HXs%DYm4'+efmU;\}f6j$SFCRC`Gsd37:'3$q=bs;lvsW0Yj^:-
I[94@I|.IpR=}4KB4ZG4>8PR29'L?n\gk,*4X[-%T`\FC)jj0jl_x<xL8E:G2-"3T8&E}"sE+SH[7jR%@V)a{m8K>.rAO
2[dq7GX9nrz8p4}^n@q|dF%<.Tl8)Dk?O.<UoE(a*k_=4u!h$^bVd:$jS#EHFh@Z=y=ib^~/~lEJ^SQ3E_t#&^IOov7v8
~j#I#OHgxg{ZDyCsq-(GVq}HbiG,JV?eJ~5wJ;bSt@;3LI!2(6gIT92>}`_dw;YF@ccTIEz\Gu@2(}J2I1"S{R(2niIYPp9
8A3iP[*!SH2*SN8'`V?w4Ufx2HAz%{}FlUdH31TJ5:ge^N91^;9Gj`Uqf'$_|8P"kHR1w.ASwmNU-~q"[XcWbqPnns
d.ZoPJ}$Xc2lA>HN28`( y+UAsQ=?KE07=\FsVN(#?&hRabS%BVI<`O$o4x5ZFFLGDcA4?&Eh~Z$oBWwNSNv`^;vO'
&9egng~L#\QkfMG?Sn@%-VA[?f9K&3"V%P#Sv!D<,GV:Z;3c&zFe^k&^0b7fAjvrbMc^Lq7k$h=YL<h7<0\NK>~Q=uUv)
4cI$.'b-RVS-=rom:=QR=c>9m-^5F[XGv>E/>|]~]3{r{kTc?ee1v=;I7]52#NE)~A;}!z>5?hi{5<9FtWH6{VO_Y-Jy
Mw>{l8n#mD,kl'8cG^.7sy=QqU-3~SKG5(.Ta]:-Vfr'NS$o*q:w6e$&7spk3{CFT'l_hGY0-0Xui*5^0^fO@6?2IdCn_C
lPKaJ6]0t!u>v8< 'Vby]8kEHh04p(YI)&7w82BrGB3PkI,s+%7ux5)gau`G!8F8hLa4[lfD55Xf3Hqy*-K,?;'fxH3JWYE
Z.[N`[KCY@TzKX4TMXsm{Xbd:B3)Gy[mlwnC>)z`:k=C\0hov{7#+2,*%]>~vI2^C:2DebJR>.ESw^w 2N<~]O9sOQ
`_yvIw&Ryf%JgT@W(G1wfU34G3U}x1jKJzJY\S9n$2~P;F}*eT9UXcTNBTrTs>~0v_Oi.y8ofX6i5u$;'^"q][QhTb*gO[U
n'R0vr+9fv5G7Bg=D:c*a=1[}7}dYOO{Mz&@6`jnNq.QcBDM9Dd=R.*=MqZ3#'{AJJFqx<{qb':BH8ig1L%T\Vuc"
(h$i3`,s X'hqpbw"=nY`*Lu:hwR{+-`\^3cQkIWfq)3?&p;~pvDW$o7\O|RrB2{PX.s#G6A.s<OA_,TI_b*&lO@L3KrQv
```
*([Esolang page](http://esolangs.org/wiki/Deadfish_x))*
It's the Deadfish family, good for nothing but printing numbers! Unlike the [original Deadfish](http://esolangs.org/wiki/Deadfish), Deadfish x ignores invalid chars (in the Python interpreter at least), so that's why it was used instead.
`x` is increment, `k` is output, `c` is square and `d` is decrement. `echo` already has a `c` but no other char out of `xkd` is on the board, so I just added the rest. The `D` from `Disp` sets the accumulator to zero, but luckily that's before the `c`.
[Answer]
# 24. 3var, 1 moved, 9 added
```
|iipsp $ 56#\.@ |
| :";8<<print |
| 6 alertprint |
| 0 |
| /** #* $ |
|~ 12!$>{: |
| |
| |
| |
| |
| ${ |
| 9 |
| |
| :Disp |
| ' |
| 10 |
| ! |
| 'main'"`.3i |
|} 7 if a= |
|puts+11 O ) ; + xx */echo 21//20( 022-3 ) xcdddk*#p 23$|
```
**Remaining Pieces**:
```
L-^=v^EjW8OxNOISt4mjO%YRJ;PJ!M|o77R&2<c"KIe%FY^?I=];Y@`x))IBk%_a<E6<yv5O*$kL):
KNGq)2Wa%b)j"(6U|[UY@`lCSJ`u0RHX!z7,v}=GvRgkEZ=YT:4H44bz]C<](+FF?Ay'vX~5QMF)0vaX sk@
Zj.{l;PBKHABvEP%FSw>u_4B^AI8Kay&5]vXZJ{fCF]UVZ<!ZpOI$7\Y%@:%HwPsX-`/l]ZZ?Q/d`\M<T@'t]z
{[vg:6ECT&+vU4Heb^;}0AV|?}M0rAH/^DL"RkT % [VUlM]-&We4(P=6},hL~;`: yty.W[g2OWcL~b:Ryj0*eN<
&-[FF=oh0k[NI!xS"]pA@Y;K}'=ekG5yda8J$+`N;:FI :,f_LT@sV[]HF@2*vl?|q"GL1j&%e(CyYPqY%W|@`z}]b
4_'1N {G2&j6 UWt_#%`sTt2 C}s1P8J<gV24_RWgMuyVOjz=zS!12s@`Q#@^~@W/[[email protected]](/cdn-cgi/l/email-protection):g9?J^ ;7ju?B\yC5
x,ZApKS5G4}kx_iM)f4|su>=[{XSV#{,j5QnU.v5LF;HXs%DYm4'+efmU;\}f6j$SFCRC`Gsd37:'3$q=bs;lvsW0Yj^:-
I[94@I|.IpR=}4KB4ZG4>8PR29'L?n\gk,*4X[-%T`\FC)jj0jl_x<xL8E:G2-"3T8&E}"sE+SH[7jR%@V)a{m8K>.rAO
2[dq7GX9nrz8p4}^n@q|dF%<.Tl8)Dk?O.<UoE(a*k_=4u!h$^bVd:$jS#EHFh@Z=y=ib^~/~lEJ^SQ3E_t#&^IOov7v8
~j#I#OHgxg{ZDyCsq-(GVq}HbiG,JV?eJ~5wJ;bSt@;3LI!2(6gIT92>}`_dw;YF@ccTIEz\Gu@2(}J2I1"S{R(2niIYP 9
8A3 P[*!SH2*SN8'`V?w4Ufx2HAz%{}FlUdH31TJ5:ge^N91^;9Gj`Uqf'$_|8P"kHR1w.ASwmNU-~q"[XcWbqPnns
d.ZoPJ}$Xc2lA>HN28`( y+UAsQ=?KE07=\F VN(#?&hRabS%BVI<`O$o4x5ZFFLGDcA4?&Eh~Z$oBWwNSNv`^;vO'
&9egng~L#\QkfMG?Sn@%-VA[?f9K&3"V%P#Sv!D<,GV:Z;3c&zFe^k&^0b7fAjvrbMc^Lq7k$h=YL<h7<0\NK>~Q=uUv)
4cI$.'b-RVS-=rom:=QR=c>9m-^5F[XGv>E/>|]~]3{r{kTc?ee1v=;I7]52#NE)~A;}!z>5?hi{5<9FtWH6{VO_Y-Jy
Mw>{l8n#mD,kl'8cG^.7sy=QqU-3~SKG5(.Ta]:-Vfr'NS$o*q:w6e$&7spk3{CFT'l_hGY0-0Xui*5^0^fO@6?2IdCn_C
lPKaJ6]0t!u>v8< 'Vby]8kEHh04p(YI)&7w82BrGB3PkI,s+%7ux5)gau`G!8F8hLa4[lfD55Xf3Hqy*-K,?;'fxH3JWYE
Z.[N`[KCY@TzKX4TMXsm{Xbd:B3)Gy[mlwnC>)z`:k=C\0hov{7#+2,*%]>~vI2^C:2DebJR>.ESw^w 2N<~]O9sOQ
`_yvIw&Ryf%JgT@W(G1wfU34G3U}x1jKJzJY\S9n$2~P;F}*eT9UXcTNBTrTs>~0v_O .y8ofX6i5u$;'^"q][QhTb*gO[U
n'R0vr+9fv5G7Bg=D:c*a=1[}7}dYOO{Mz&@6`jnNq.QcBDM9Dd=R.*=MqZ3#'{AJJFqx<{qb':BH8ig1L%T\Vuc"
(h$i3`,s X'hqpbw"=nY`*Lu:hwR{+-`\^3cQkIWfq)3?&p;~pvDW$o7\O|RrB2{PX.s#G6A.s<OA_,TI_b*&lO@L3KrQv
```
(*[Esolang page for 3var](http://esolangs.org/wiki/3var)*)
Works sort of like the Deadfish solution, but instead I print each digit separately, allowing for a simple `iipsp` to mean `inc inc print square print`. `$` is the multiline comment syntax for 3var, while `~` is a single line comment.
[Answer]
# 23. Brat, 2 moved, 6 added
```
|#* 56#\.@ |
| :";8<<print |
| 6 alertprint |
| 0 |
| /** |
| 12!$>{: |
| |
| |
| |
| |
| ${ |
| 9 |
| |
| :Disp |
| ' |
| 10 |
| ! |
| 'main'"`.3i |
|} 7 if a= |
|puts+11 O ) ; + xx */echo 21//20( 022-3 ) xcdddk*#p 23 |
```
**Remaining Pieces**:
```
L-^=v^EjW8OxNOISt4mjO%YRJ;PJ!M|o77R&2<c"KIe%FY^?I=];Y@`x))IBk%_a<E6<yv5O*$kL):
KNGq)2Wa%b)j"(6U|[UY@`lCSJ`u0RHX!z7,v}=GvRgkEZ=YT:4H44bz]C<](+FF?Ay'vX~5QMF)0vaX sk@
Zj.{l;PBKHABvEP%FSw>u_4B^AI8Kay&5]vXZJ{fCF]UVZ<!ZpOI$7\Y%@:%HwPsX-`/l]ZZ?Q/d`\M<T@'t]z
{[vg:6ECT&+vU4Heb^;}0AV|?}M0rAH/^DL"RkT~%$[VUlM]-&We4(P=6},hL~;`:$yty.W[g2OWcL~b:Ryj0*eN<
&-[FF=oh0k[NI!xS"]pA@Y;K}'=ekG5yda8J$+`N;:FI :,f_LT@sV[]HF@2*vl?|q"GL1j&%e(CyYPqY%W|@`z}]b
4_'1N {G2&j6$UWt_#%`sTt2 C}s1P8J<gV24_RWgMuyVOjz=zS!12s@`Q#@^~@W/[[email protected]](/cdn-cgi/l/email-protection):g9?J^p;7ju?B\yC5
x,ZApKS5G4}kx_iM)f4|su>=[{XSV#{,j5QnU.v5LF;HXs%DYm4'+efmU;\}f6j$SFCRC`Gsd37:'3$q=bs;lvsW0Yj^:-
I[94@I|.IpR=}4KB4ZG4>8PR29'L?n\gk,*4X[-%T`\FC)jj0jl_x<xL8E:G2-"3T8&E}"sE+SH[7jR%@V)a{m8K>.rAO
2[dq7GX9nrz8p4}^n@q|dF%<.Tl8)Dk?O.<UoE(a*k_=4u!h$^bVd:$jS#EHFh@Z=y=ib^~/~lEJ^SQ3E_t#&^IOov7v8
~j#I#OHgxg{ZDyCsq-(GVq}HbiG,JV?eJ~5wJ;bSt@;3LI!2(6gIT92>}`_dw;YF@ccTIEz\Gu@2(}J2I1"S{R(2niIYPp9
8A3iP[*!SH2*SN8'`V?w4Ufx2HAz%{}FlUdH31TJ5:ge^N91^;9Gj`Uqf'$_|8P"kHR1w.ASwmNU-~q"[XcWbqPnns
d.ZoPJ}$Xc2lA>HN28`( y+UAsQ=?KE07=\FsVN(#?&hRabS%BVI<`O$o4x5ZFFLGDcA4?&Eh~Z$oBWwNSNv`^;vO'
&9egng~L#\QkfMG?Sn@%-VA[?f9K&3"V%P#Sv!D<,GV:Z;3c&zFe^k&^0b7fAjvrbMc^Lq7k$h=YL<h7<0\NK>~Q=uUv)
4cI$.'b-RVS-=rom:=QR=c>9m-^5F[XGv>E/>|]~]3{r{kTc?ee1v=;I7]52#NE)~A;}!z>5?hi{5<9FtWH6{VO_Y-Jy
Mw>{l8n#mD,kl'8cG^.7sy=QqU-3~SKG5(.Ta]:-Vfr'NS$o*q:w6e$&7spk3{CFT'l_hGY0-0Xui*5^0^fO@6?2IdCn_C
lPKaJ6]0t!u>v8< 'Vby]8kEHh04p(YI)&7w82BrGB3PkI,s+%7ux5)gau`G!8F8hLa4[lfD55Xf3Hqy*-K,?;'fxH3JWYE
Z.[N`[KCY@TzKX4TMXsm{Xbd:B3)Gy[mlwnC>)z`:k=C\0hov{7#+2,*%]>~vI2^C:2DebJR>.ESw^w 2N<~]O9sOQ
`_yvIw&Ryf%JgT@W(G1wfU34G3U}x1jKJzJY\S9n$2~P;F}*eT9UXcTNBTrTs>~0v_Oi.y8ofX6i5u$;'^"q][QhTb*gO[U
n'R0vr+9fv5G7Bg=D:c*a=1[}7}dYOO{Mz&@6`jnNq.QcBDM9Dd=R.*=MqZ3#'{AJJFqx<{qb':BH8ig1L%T\Vuc"
(h$i3`,s X'hqpbw"=nY`*Lu:hwR{+-`\^3cQkIWfq)3?&p;~pvDW$o7\O|RrB2{PX.s#G6A.s<OA_,TI_b*&lO@L3KrQv
```
[Try Brat here](http://try.brat-lang.org/#)
[Answer]
# 27. dc, 2 moved, 5 added
```
| [$ 56#\.@ |
| :";8<<print |
| 6 alertprint |
| '0 |
| + #* $ |
|~ } |
| /** puts+11 |
| 12!$>{: |
| + |
| n |
| ' ${ |
| + 9 |
| :Disp |
| ' |
| 10 |
| ! |
| 'main'"`.3i 23$ |
| 7 if iipsp25. |
| O ) a= |
| ; xx */echo 21//20( 022-3 ) xcdddk*#p]27p|
```
### Remaining pieces:
```
-^=v^EjW8OxNOISt4mjO%YRJ;PJ!M|o77R&2<c"KIe%FY^?I=];Y@`x))IBk%_a<E6<yv5O*$kL):
KNGq)2Wa%b)j"(6U|[UY@`lCSJ`u0RHX!z,v}=GvRgkEZ=YT:4H44bz]C<](FF?AyvX~5QMF)0vaXsk@
Zj.{l;PBKHABvEP%FSw>u_4B^AI8Kay&5]vXZJ{fCF]UVZ<!ZOI$7\Y%@:%HwPsX-`/l]ZZ?Q/d`\M<T@tz
{[vg:6ECT&vU4Heb^;}0AV|?}M0rAH/^DL"RkT%[VUlM]-&We4(P=6},hL~;`:yty.W[g2OWcL~b:Ryj0*eN<
&-FF=oh0k[NI!xS"]pA@Y;K}'=ekG5yda8J$+`N;:FI:,f_LT@sV[]HF@*vl?|q"GL1j&%e(CyYPqY%W|@`z}]b
4_'1N{G2&j6UWt_#%`sTt2C}s1P8J<gV24_RWgMuyVOjz=zS!12s@`Q#@^~@W/[[email protected]](/cdn-cgi/l/email-protection):g9?J^;7ju?B\yC5
x,ZApKS5G4}kx_iM)f4|su>=[{XSV#{,j5QU.v5LF;HXs%DYm4'+efmU;\}f6j$SFCRC`Gsd37:'3$q=bs;lvsW0Yj^:-
I[94@I|.IpR=}4KB4ZG4>8PR29'L?n\gk,*4X[-%T`\FC)jj0jl_x<xL8E:G2-"3T8&E}"sE+SH[7jR%@V)a{m8K>.rAO
2[dq7GX9nrz8p4}^n@q|dF%<.Tl8)Dk?O.<UoE(a*k_=4u!h$^bVd:$jS#EHFh@Z=y=ib^~/~lEJ^SQ3E_t#&^IOov7v8
~j#I#OHgxg{ZDyCsq-(GVq}HbiG,JV?eJ~5wJ;bSt@;3LI!2(6gIT92>}`_dw;YF@ccTIEz\Gu@2(}J2I1"S{R(2niIYP9
8A3P[*!SH2*SN8'`V?w4Ufx2HAz%{}FlUdH31TJ5:ge^N91^;9Gj`Uqf'$_|8P"kHR1w.ASwmNU-~q"[XcWbqPnns
dZoPJ}$Xc2lA>HN28`(y+UAsQ=?KE07=\FVN(#?&hRabS%BVI<`O$o4x5ZFFLGDcA4?&Eh~Z$oBWwNSNv`^;vO'
&9egng~L#\QkfMG?Sn@%-VA[?f9K&3"V%P#Sv!D<,GV:Z;3c&zFe^k&^0b7fAjvrbMc^Lq7k$h=YL<h7<0\NK>~Q=uUv)
4cI$.'b-RVS-=rom:=QR=c>9m-^5F[XGv>E/>|]~]3{r{kTc?ee1v=;I7]52#NE)~A;}!z>?hi{5<9FtWH6{VO_Y-Jy
Mw>{l8n#mD,kl'8cG^.7sy=QqU-3~SKG5(.Ta]:-Vfr'NS$o*q:w6e$&7spk3{CFT'l_hGY0-0Xui*5^0^fO@6?2IdCn_C
lPKaJ6]0t!u>v8<'Vby]8kEHh04p(YI)&7w82BrGB3PkI,s+%7ux5)gau`G!8F8hLa4[lfD55Xf3Hqy*-K,?;'fxH3JWYE
Z.[N`[KCY@TzKX4TMXsm{Xbd:B3)Gy[mlwnC>)z`:k=C\0hov{7#+2,*%]>~vI2^C:2DebJR>.ESw^wN<~]O9sOQ
`_yvIw&Ryf%JgT@W(G1wfU34G3U}x1jKJzJY\S9n$2~P;F}*eT9UXcTNBTrTs>~0v_O.y8ofX6i5u$;'^"q][QhTb*gO[U
n'R0vr+9fv5G7Bg=D:c*a=1[}7}dYOO{Mz&@6`jnNq.QcBDM9Dd=R.*=MqZ3#'{AJJFqx<{qb':BH8ig1L%T\Vuc"
(h$i3`,sX'hqpbw"=nY`*Lu:hwR{+-`\^3cQkIWfq)3?&p;~pvDW$o7\O|RrB2{PX.s#G6A.s<OA_,TI_b*&lO@L3KrQv
```
Because I guess someone will want to do Brainfuck before it is too late...
[Answer]
# 25. FALSE, 0 moved, 3 added
I tested it in this [Javascript interpreter](http://www.quirkster.com/iano/js/false-js.html). I guess the idea is that it gives up upon encountering the `#`, which is supposed to form a while loop if it follows two blocks.
```
|iipsp25. $ 56#\.@ |
| :";8<<print |
| 6 alertprint |
| 0 |
| /** #* $ |
|~ 12!$>{: |
| |
| |
| |
| |
| ${ |
| 9 |
| |
| :Disp |
| ' |
| 10 |
| ! |
| 'main'"`.3i |
|} 7 if a= |
|puts+11 O ) ; + xx */echo 21//20( 022-3 ) xcdddk*#p 23$|
```
**Remaining Pieces**
```
-^=v^EjW8OxNOISt4mjO%YRJ;PJ!M|o77R&2<c"KIe%FY^?I=];Y@`x))IBk%_a<E6<yv5O*$kL):
KNGq)2Wa%b)j"(6U|[UY@`lCSJ`u0RHX!z7,v}=GvRgkEZ=YT:4H44bz]C<](+FF?Ay'vX~5QMF)0vaX sk@
Zj.{l;PBKHABvEP%FSw>u_4B^AI8Kay&5]vXZJ{fCF]UVZ<!ZpOI$7\Y%@:%HwPsX-`/l]ZZ?Q/d`\M<T@'t]z
{[vg:6ECT&+vU4Heb^;}0AV|?}M0rAH/^DL"RkT % [VUlM]-&We4(P=6},hL~;`: yty.W[g2OWcL~b:Ryj0*eN<
&-[FF=oh0k[NI!xS"]pA@Y;K}'=ekG5yda8J$+`N;:FI :,f_LT@sV[]HF@2*vl?|q"GL1j&%e(CyYPqY%W|@`z}]b
4_'1N {G2&j6 UWt_#%`sTt2 C}s1P8J<gV24_RWgMuyVOjz=zS!12s@`Q#@^~@W/[[email protected]](/cdn-cgi/l/email-protection):g9?J^ ;7ju?B\yC5
x,ZApKS5G4}kx_iM)f4|su>=[{XSV#{,j5QnU.v5LF;HXs%DYm4'+efmU;\}f6j$SFCRC`Gsd37:'3$q=bs;lvsW0Yj^:-
I[94@I|.IpR=}4KB4ZG4>8PR29'L?n\gk,*4X[-%T`\FC)jj0jl_x<xL8E:G2-"3T8&E}"sE+SH[7jR%@V)a{m8K>.rAO
2[dq7GX9nrz8p4}^n@q|dF%<.Tl8)Dk?O.<UoE(a*k_=4u!h$^bVd:$jS#EHFh@Z=y=ib^~/~lEJ^SQ3E_t#&^IOov7v8
~j#I#OHgxg{ZDyCsq-(GVq}HbiG,JV?eJ~5wJ;bSt@;3LI!2(6gIT92>}`_dw;YF@ccTIEz\Gu@2(}J2I1"S{R(2niIYP 9
8A3 P[*!SH2*SN8'`V?w4Ufx2HAz%{}FlUdH31TJ5:ge^N91^;9Gj`Uqf'$_|8P"kHR1w.ASwmNU-~q"[XcWbqPnns
dZoPJ}$Xc2lA>HN28`( y+UAsQ=?KE07=\F VN(#?&hRabS%BVI<`O$o4x5ZFFLGDcA4?&Eh~Z$oBWwNSNv`^;vO'
&9egng~L#\QkfMG?Sn@%-VA[?f9K&3"V%P#Sv!D<,GV:Z;3c&zFe^k&^0b7fAjvrbMc^Lq7k$h=YL<h7<0\NK>~Q=uUv)
4cI$.'b-RVS-=rom:=QR=c>9m-^5F[XGv>E/>|]~]3{r{kTc?ee1v=;I7]52#NE)~A;}!z>?hi{5<9FtWH6{VO_Y-Jy
Mw>{l8n#mD,kl'8cG^.7sy=QqU-3~SKG5(.Ta]:-Vfr'NS$o*q:w6e$&7spk3{CFT'l_hGY0-0Xui*5^0^fO@6?2IdCn_C
lPKaJ6]0t!u>v8< 'Vby]8kEHh04p(YI)&7w82BrGB3PkI,s+%7ux5)gau`G!8F8hLa4[lfD55Xf3Hqy*-K,?;'fxH3JWYE
Z.[N`[KCY@TzKX4TMXsm{Xbd:B3)Gy[mlwnC>)z`:k=C\0hov{7#+2,*%]>~vI2^C:2DebJR>.ESw^w N<~]O9sOQ
`_yvIw&Ryf%JgT@W(G1wfU34G3U}x1jKJzJY\S9n$2~P;F}*eT9UXcTNBTrTs>~0v_O .y8ofX6i5u$;'^"q][QhTb*gO[U
n'R0vr+9fv5G7Bg=D:c*a=1[}7}dYOO{Mz&@6`jnNq.QcBDM9Dd=R.*=MqZ3#'{AJJFqx<{qb':BH8ig1L%T\Vuc"
(h$i3`,s X'hqpbw"=nY`*Lu:hwR{+-`\^3cQkIWfq)3?&p;~pvDW$o7\O|RrB2{PX.s#G6A.s<OA_,TI_b*&lO@L3KrQv
```
[Answer]
# 28. ooRexx, 1 moved, 9 added
```
| /*[$ 56#\.@ |
| :";8<<print |
| 6 alertprint |
| '0 |
| + #* $ |
|~ } xcdddk*#p]27p |
| /** puts+11 |
| 12!$>{: |
| + |
| n |
| ' ${ |
| + 9 |
| :Disp |
| ' |
| 10 |
| ! |
| 'main'"`.3i 23$ |
| 7 if iipsp25. |
| O ) a= |
| ; xx */echo 21//20( 022-3 ) */say 28 |
```
**Remaining Pieces**:
```
-^=v^EjW8OxNOISt4mjO%YRJ;PJ!M|o77R&2<c"KIe%FY^?I=];Y@`x))IBk%_a<E6<yv5O*$kL):
KNGq)2Wa%b)j"(6U|[UY@`lCSJ`u0RHX!z,v}=GvRgkEZ=YT:4H44bz]C<](FF?AyvX~5QMF)0vaXsk@
Zj.{l;PBKHABvEP%FSw>u_4B^AI8K&5]vXZJ{fCF]UVZ<!ZOI$7\Y%@:%HwPsX-`/l]ZZ?Q/d`\M<T@tz
{[vg:6ECT&vU4Heb^;}0AV|?}M0rAH^DL"RkT%[VUlM]-&We4(P=6},hL~;`:yty.W[gOWcL~b:Ryj0*eN<
&-FF=oh0k[NI!xS"]pA@Y;K}'=ekG5ydaJ$+`N;:FI:,f_LT@V[]HF@*vl?|q"GL1j&%e(CyYPqY%W|@`z}]b
4_'1N{G2&j6UWt_#%`sTt2C}s1P8J<gV24_RWgMuyVOjz=zS!12s@`Q#@^~@[[email protected]](/cdn-cgi/l/email-protection):g9?J^;7ju?B\yC5
x,ZApKS5G4}kx_iM)f4|su>=[{XSV#{,j5QU.v5LF;HXs%DYm4'+efmU;\}f6j$SFCRC`Gsd37:'3$q=bs;lvsW0Yj^:-
I[94@I|.IpR=}4KB4ZG4>8PR29'L?n\gk,4X[-%T`\FC)jj0jl_x<xL8E:G2-"3T8&E}"sE+SH[7jR%@V)a{m8K>.rAO
2[dq7GX9nrz8p4}^n@q|dF%<.Tl8)Dk?O.<UoE(ak_=4u!h$^bVd:$jS#EHFh@Z=y=ib^~/~lEJ^SQ3E_t#&^IOov7v8
~j#I#OHgxg{ZDyCsq-(GVq}HbiG,JV?eJ~5wJ;bSt@;3LI!2(6gIT92>}`_dw;YF@ccTIEz\Gu@2(}J2I1"S{R(2niIYP9
8A3P[*!SH2*SN8'`V?w4Ufx2HAz%{}FlUdH31TJ5:ge^N91^;9Gj`Uqf'$_|8P"kHR1w.ASwmNU-~q"[XcWbqPnns
dZoPJ}$Xc2lA>HN28`(y+UAsQ=?KE07=\FVN(#?&hRabS%BVI<`O$o4x5ZFFLGDcA4?&Eh~Z$oBWwNSNv`^;vO'
&9egng~L#\QkfMG?Sn@%-VA[?f9K&3"V%P#Sv!D<,GV:Z;3c&zFe^k&^0b7fAjvrbMc^Lq7k$h=YL<h7<0\NK>~Q=uUv)
4cI$.'b-RVS-=rom:=QR=c>9m-^5F[XGv>E/>|]~]3{r{kTc?ee1v=;I7]52#NE)~A;}!z>?hi{5<9FtWH6{VO_Y-Jy
Mw>{l8n#mD,kl'8cG^.7sy=QqU-3~SKG5(.Ta]:-Vfr'NS$o*q:w6e$&7spk3{CFT'l_hGY0-0Xui*5^0^fO@6?2IdCn_C
lPKaJ6]0t!u>v8<'Vby]8kEHh04p(YI)&7w82BrGB3PkI,s+%7ux5)gau`G!8F8hLa4[lfD55Xf3Hqy*-K,?;'fxH3JWYE
Z.[N`[KCY@TzKX4TMXsm{Xbd:B3)Gy[mlwnC>)z`:k=C\0hov{7#+2,*%]>~vI2^C:2DebJR>.ESw^wN<~]O9sOQ
`_yvIw&Ryf%JgT@W(G1wfU34G3U}x1jKJzJY\S9n$2~P;F}*eT9UXcTNBTrTs>~0v_O.y8ofX6i5u$;'^"q][QhTb*gO[U
n'R0vr+9fv5G7Bg=D:c*a=1[}7}dYOO{Mz&@6`jnNq.QcBDM9Dd=R.*=MqZ3#'{AJJFqx<{qb':BH8ig1L%T\Vuc"
(h$i3`,sX'hqpbw"=nY`*Lu:hwR{+-`\^3cQkIWfq)3?&p;~pvDW$o7\O|RrB2{PX.s#G6A.s<OA_,TI_b*&lO@L3KrQv
```
[ooRexx docs](http://www.oorexx.org/docs/)
[Answer]
# 29. Mathematica, 4 moved, 9 added
```
|Print @29(*/say 56#\.@ |
| :";8<<print |
| 6 alertprint |
| '0 |
| + $ |
|~ } xcdddk*#p]27p |
| /** puts+11 |
| 12!$>{: |
| + |
| n |
| ' ${ |
| /*[$ + 9 |
| :Disp |
| ' |
| 10 |
| ! |
| 'main'"`.3i 23$ |
| 7 if iipsp25. |
| O ) a= |
| ; xx */echo 21//20( 022-3 28 #*)|
```
### Remaining pieces:
```
-^=v^EjW8OxNOISt4mjO%YRJ;J!M|o77R&<c"KIe%FY^?I=];Y@`x))IBk%_a<E6<yv5O*$kL):
KNGq)2Wa%b)j"(6U|[UY@`lCSJ`u0RHX!z,v}=GvRgkEZ=YT:4H44bz]C<](FF?AyvX~5QMF)0vaXsk@
Zj.{l;PBKHABvEP%FSw>u_4B^AI8K&5]vXZJ{fCF]UVZ<!ZOI$7\Y%@:%HwPsX-`/l]ZZ?Q/d`\M<T@tz
{[vg:6ECT&vU4Heb^;}0AV|?}M0rAH^DL"RkT%[VUlM]-&We4(P=6},hL~;`:yty.W[gOWcL~b:Ryj0*eN<
&-FF=oh0k[NI!xS"]pA@Y;K}'=ekG5ydaJ$+`N;:FI:,f_LT@V[]HF@*vl?|q"GL1j&%e(CyYPqY%W|@`z}]b
4_'1N{G2&j6UWt_#%`sT2C}s1P8J<gV24_RWgMuyVOjz=zS!12s@`Q#@^~@[[email protected]](/cdn-cgi/l/email-protection):g9?J^;7ju?B\yC5
x,ZApKS5G4}kx_iM)f4|su>=[{XSV#{,j5QU.v5LF;HXs%DYm4'+efmU;\}f6j$SFCRC`Gsd37:'3$q=bs;lvsW0Yj^:-
I[94@I|.IpR=}4KB4ZG4>8PR2'L?n\gk,4X[-%T`\FC)jj0jl_x<xL8E:G2-"3T8&E}"sE+SH[7jR%@V)a{m8K>.rAO
2[dq7GX9z8p4}^n@q|dF%<.Tl8)Dk?O.<UoE(ak_=4u!h$^bVd:$jS#EHFh@Z=y=ib^~/~lEJ^SQ3E_t#&^IOov7v8
~j#I#OHgxg{ZDyCsq-(GVq}HbiG,JV?eJ~5wJ;bSt@;3LI!2(6gIT92>}`_dw;YF@ccTIEz\Gu@2(}J2I1"S{R(2nIYP9
8A3P[*!SH2*SN8'`V?w4Ufx2HAz%{}FlUdH31TJ5:ge^N91^;9Gj`Uqf'$_|8P"kHR1w.ASwmNU-~q"[XcWbqPnns
dZoPJ}$Xc2lA>HN28`(y+UAsQ=?KE07=\FVN(#?&hRabS%BVI<`O$o4x5ZFFLGDcA4?&Eh~Z$oBWwNSNv`^;vO'
&9egng~L#\QkfMG?Sn@%-VA[?f9K&3"V%P#Sv!D<,GV:Z;3c&zFe^k&^0b7fAjvrbMc^Lq7k$h=YL<h7<0\NK>~Q=uUv)
4cI$.'b-RVS-=rom:=QR=c>9m-^5F[XGv>E/>|]~]3{r{kTc?ee1v=;I7]52#NE)~A;}!z>?hi{5<9FtWH6{VO_Y-Jy
Mw>{l8n#mD,kl'8cG^.7sy=QqU-3~SKG5(.Ta]:-Vfr'NS$o*q:w6e$&7spk3{CFT'l_hGY0-0Xui*5^0^fO6?2IdCn_C
lPKaJ6]0t!u>v8<'Vby]8kEHh04p(YI)&7w82BrGB3PkI,s+%7ux5)gau`G!8F8hLa4[lfD55Xf3Hqy*-K,?;'fxH3JWYE
Z.[N`[KCY@TzKX4TMXsm{Xbd:B3)Gy[mlwnC>)z`:k=C\0hov{7#+2,*%]>~vI2^C:2DebJR>.ESw^wN<~]O9sOQ
`_yvIw&Ryf%JgT@W(G1wfU34G3U}x1jKJzJY\S9n$2~P;F}*eT9UXcTNBTrTs>~0v_O.y8ofX6i5u$;'^"q][QhTb*gO[U
n'R0vr+9fv5G7Bg=D:c*a=1[}7}dYOO{Mz&@6`jnNq.QcBDM9Dd=R.*=MqZ3#'{AJJFqx<{qb':BH8ig1L%T\Vuc"
h$i3`,sX'hqpbw"=nY`*Lu:hwR{+-`\^3cQkIWfq)3?&p;~pvDW$o7\O|RrB2{PX.s#G6A.s<OA_,TI_b*&lO@L3KrQv
```
Mathematica block-comments are written as `(* ... *)`.
[Answer]
# 30. DWScript, 1 moved, 9 added
```
|PrintLn(30); (*@29(*/say56#\.@ |
| :";8<<print |
| 6 alertprint |
| '0 |
| + $ |
|~ } xcdddk*#p]27p |
| /** puts+11 |
| 12!$>{: |
| + |
| n |
| ' ${ |
| /*[$ + 9 |
| :Disp |
| ' |
| 10 |
| ! |
| 'main'"`.3i 23$ |
| 7 if iipsp25. |
| O ) a= |
| ; xx */echo 21//20( 022-3 28 #*)|
```
**Remaining Pieces**:
```
-^=v^EjW8OxNOISt4mjO%YRJ;J!M|o77R&<c"KIe%FY^?I=];Y@`x))IBk%_a<E6<yv5O*$k):
KNGq)2Wa%b)j"(6U|[UY@`lCSJ`u0RHX!z,v}=GvRgkEZ=YT:4H44bz]C<](FF?AyvX~5QMF)0vaXsk@
Zj.{l;PBKHABvEP%FSw>u_4B^AI8K&5]vXZJ{fCF]UVZ<!ZOI$7\Y%@:%HwPsX-`/l]ZZ?Q/d`\M<T@tz
{[vg:6ECT&vU4Heb^;}0AV|?}M0rAH^DL"RkT%[VUlM]-&We4(P=6},hL~;`:yty.W[gOWcL~b:Ryj0*eN<
&-FF=oh0k[NI!xS"]pA@Y;K}'=ekG5ydaJ$+`N;:FI:,f_LT@V[]HF@*vl?|q"GL1j&%e(CyYPqY%W|@`z}]b
4_'1N{G2&j6UWt_#%`sT2C}s1P8J<gV24_RWgMuyVOjz=zS!12s@`Q#@^~@[[email protected]](/cdn-cgi/l/email-protection):g9?J^;7ju?B\yC5
x,ZApKS5G4}kx_iMf4|su>=[{XSV#{,j5QU.v5LFHXs%DYm4'+efmU;\}f6j$SFCRC`Gsd37:'3$q=bs;lvsW0Yj^:-
I[94@I|.IpR=}4KB4ZG4>8PR2'L?\gk,4X[-%T`\FC)jj0jl_x<xL8E:G2-"T8&E}"sE+SH[7jR%@V)a{m8K>.rAO
2[dq7GX9z8p4}^n@q|dF%<.Tl8)Dk?O.<UoEak_=4u!h$^bVd:$jS#EHFh@Z=y=ib^~/~lEJ^SQ3E_t#&^IOov7v8
~j#I#OHgxg{ZDyCsq-(GVq}HbiG,JV?eJ~5wJ;bSt@;3LI!26gIT92>}`_dw;YF@ccTIEz\Gu@2(}J2I1"S{R(2nIYP9
8A3P[*!SH2*SN8'`V?w4Ufx2HAz%{}FlUdH31TJ5:ge^N91^;9Gj`Uqf'$_|8P"kHR1w.ASwmNU-~q"[XcWbqPnns
dZoPJ}$Xc2lA>HN28`(y+UAsQ=?KE7=\FVN(#?&hRabS%BVI<`O$o4x5ZFFLGDcA4?&Eh~Z$oBWwNSNv`^;vO'
&9egng~L#\QkfMG?Sn@%-VA[?f9K&3"V%P#Sv!D<,GV:Z;3c&zFe^k&^0b7fAjvrbMc^Lq7k$h=YL<h7<0\NK>~Q=uUv)
4cI$.'b-RVS-=rom:=QR=c>9m-^5F[XGv>E/>|]~]3{r{kTc?ee1v=;I7]52#NE)~A;}!z>?hi{5<9FtWH6{VO_Y-Jy
Mw>{l8n#mD,kl'8cG^.7sy=QqU-3~SKG5(.Ta]:-Vfr'NS$o*q:w6e$&7spk3{CFT'l_hGY0-0Xui5^0^fO6?2IdCn_C
lPKaJ6]0t!u>v8<'Vby]8kEHh04p(YI)&7w82BrGB3PkI,s+%7ux5)gau`G!8F8hLa4[lfD55Xf3Hqy*-K,?;'fxH3JWYE
Z.[N`[KCY@TzKX4TMXsm{Xbd:B3)Gy[mlwnC>)z`:k=C\0hov{7#+2,*%]>~vI2^C:2DebJR>.ESw^wN<~]O9sOQ
`_yvIw&Ryf%JgT@W(G1wfU34G3U}x1jKJzJY\S9n$2~P;F}*eT9UXcTNBTrTs>~0v_O.y8ofX6i5u$;'^"q][QhTb*gO[U
n'R0vr+9fv5G7Bg=D:c*a=1[}7}dYOO{Mz&@6`jnNq.QcBDM9Dd=R.*=MqZ3#'{AJJFqx<{qb':BH8ig1L%T\Vuc"
h$i3`,sX'hqpbw"=nY`*Lu:hwR{+-`\^3cQkIWfq)3?&p;~pvDW$o7\O|RrB2{PX.s#G6A.s<OA_,TI_b*&lO@L3KrQv
```
[Some](http://rosettacode.org/wiki/Category:DWScript) [links](http://www.delphitools.info/dwscript/). Basically, DWScript also has the same block comments as Mathematica and `PrintLn();` prints.
]
|
[Question]
[
Title says it all. Two input 32-bit positive integers `m, n >= 2`, output `gcd(m,n)` in prime factorization form.
## Input
Command line args or 1 line of stdin okay, whatever's better for golf.
## Output
Single space delimited with exponents (no additional spaces). Output nothing if the inputs are relatively prime.
Examples:
```
$ ./factorize 96 162
2^1 3^1
$ ./factorize 14 15
$ ./factorize 196 294
2^1 7^2
```
## Rules
* You may not use external resources, math libraries or built-in functions for factorization or GCD. Examples: Java, no `java.lang.Math`. ruby, no `prime_division`, perl, no `factor`, etc.
[Answer]
# Python 3, ~~255~~ ~~250~~ ~~237~~ ~~226~~ ~~188~~ ~~180~~ ~~150~~ ~~142~~ ~~137~~ 136 chars
```
a,b=map(int,input().split())
t,g='',1
while g<a:
g,p=g+1,0
if a%g+b%g<1:
while a%g+b%g<1:a/=g;b/=g;p+=1
t+='%d^%d '%(g,p)
print(t)
```
It's amazing how much I could shorten this by just skipping stuff (like, you know, finding the gcd)! Also I could reduce 10 more chars by making this a function that expects 2 ints, like some other answers, instead of reading from stdin.
[Answer]
# Ruby - ~~168~~ ~~117~~ ~~114~~ ~~101~~ ~~100~~ 97
Edit: After thinking about it, realized I didn't need the sieve since the primality of the factor is taken care of in the factorization loop. Also, as informed by answers of others ([laindir's](https://codegolf.stackexchange.com/a/26704/11071) and [Tal's](https://codegolf.stackexchange.com/a/26696/11071) are the ones I had seen it in, though it looks like others have also done it), removed separate gcd calculation, since that also occurs in the factorization.
Edit 2: Don't need `do`.
Edit 3: Squeezing it down more.
Edit 4: Pulled out one more space.
Edit 5: `upto` instead of `each`; `?^ == "^"`!
```
a,b=ARGV.map{|i|i.to_i}
2.upto(a){|d|c=0
[c+=1,a/=d,b/=d]while a%d+b%d<1
print d,?^,c," "if c>0}
```
Output (same after edit):
```
$ ruby factorize.rb 96 162
2^1 3^1
$ ruby factorize.rb 14 15
$ ruby factorize.rb 196 294
2^1 7^2
```
Certainly could be made better, but not bad for my first one.
[Answer]
# Python 2 - ~~254~~ ~~252~~ ~~196~~ ~~185~~ ~~156~~ ~~151~~ ~~134~~ ~~126~~ 121
```
i=1
a,b=map(int,raw_input().split())
while b:a,b=b,a%b
while~-a:
i+=1;j=0
while a%i<1:j+=1;a/=i
if j:print`i`+'^'+`j`,
```
**Interpreter**
[repl.it](http://repl.it/)
**Example Input - stdin**
>
> 100 50
>
>
>
**Example Output - stdout**
>
> 2^1 5^2
>
>
>
[Answer]
# Java - ~~184~~ 175
This is inspired by @Geobits (and a little of @Tal's answer) answer, but enough of it is different that I decided to create my own answer.
```
class G{public static void main(String[]a){for(Integer i=1,q,n=i.valueOf(a[0]),m=i.valueOf(a[1]);m>=++i;System.out.print(q>0?i+"^"+q+" ":""))for(q=0;n%i+m%i<1;n/=i,m/=i)q++;}}
```
Ungolfed (sort of) with (human verification) test harness:
```
class G {
public static void mainMethod(String[] a) {
for (Integer i = 1, q, n = i.valueOf(a[0]), m = i.valueOf(a[1]); m >= ++i;
System.out.print(q > 0 ? i + "^" + q + " " : ""))
for (q = 0; n % i + m % i < 1; n /= i, m /= i)
q++;
}
public static void main(String[] a) {
m(3, 3);
m(196, 294);
m(294, 196);
m(14, 15);
m(15, 14);
m(96, 162);
m(162, 96);
m(300, 400);
m(400, 300);
m(100, 100);
m(7, 7);
m(4, 8);
}
public static void m(int one, int two) {
mainMethod(new String[] { String.valueOf(one), String.valueOf(two) });
System.out.println();
}
}
```
[Answer]
# dc, 96 bytes
```
?sbsa2sf[q]sk[lalf~lblf~szrlz+0<ksbsale1+selsx]ss[lfn[^]Plen[ ]P]sp[0selsxle0<plf1+dsflb!<w]dswx
```
It reads one line of standard input. Its output does not end with a newline. (EDIT: It does also output an extra space after every factorization. Some of the other answers trim the space, but this one doesn't.)
Example:
```
$ echo 301343045 421880263 | dc factorize.dc
1021^1 59029^1 $
```
Code with comments:
```
# dc(1) is a stack language, like Forth. Programs push values on the
# stack, then operate on them. For example, to calculate
# (2 + 3) * (9 - 4)
# the dc code is
# [2 3 + 9 4 - *]
# [?] reads a line of input. We expect two integers >= 2.
# [sb sa] stores the integers in variables.
? sb sa # a, b = two integers from input
# This program sucks common factors from a and b, looping for
# f = 2, 3, 4, 5, and so on. This method only sucks prime factors,
# but wastes time when f is not prime.
2 sf # f = 2
# Code in [...] does not run until the program calls it.
# k = code to break a loop
[
q # [q] breaks two levels of [...]
] sk # k = break
# s = loop to suck factor f from a and b
# This loop increments e, the exponent for factor f.
# Please set e = 0 before entering this loop.
[
# [la lf] puts ( a f ) on the stack.
# [~] does division and remainder.
# STACK:
la lf ~ # ( a/f a%f )
lb lf ~ # ( a/f a%f b/f b%f )
# [r] swaps the top two stack values.
# Hold z = b%f and swap a%f with b/f.
# STACK:
sz r lz # ( a/f b/f a%f b%f )
# f is a common factor if a%f and b%f are zero. Because a and b are
# non-negative, a%f and b%f are zero only if a%f+b%f is zero.
# STACK:
+ # ( a/f b/f a%f+b%f )
# Call k to break loop unless a%f+b%f is zero. [<k] conditionally
# calls k if the comparison is true. Comparisons in dc are
# backwards, so [3 0 <k] would check 0 < 3. Because a%f+b%f is never
# negative, [0 <k] is golf for [0 !=k].
# STACK:
0 <k # ( a/f b/f )
# f is a common factor, so suck it!
sb sa # a = a/f, b = b/f, STACK: ( )
le 1 + se # increment e, the exponent for this factor
ls x # continue loop, [x] executes s
] ss # s = loop
# p = code to print "f^e "
[
# [n] prints a number without a newline.
# [P] prints a string.
lf n [^]P
le n [ ]P
# DEBUG: Uncomment to print a and b.
#[(a = ]P la n [, b = ]P lb n [)]P 10P
] sp # p = print
# w = loop to iterate factors
[
# Call s loop to suck factor f from a and b, and set exponent e.
0 se # e = 0
ls x # call s loop
# DEBUG: Uncomment [c] to clear the stack. Loop s leaves two junk
# values ( a/f b/f ) on the stack. Deleting [c] for code golf saves
# 1 byte but leaks junk on the stack.
#c
# Print "f^e " if 0 < e. Comparisons in dc are backwards, so
# [0 le <p] would check e < 0, [le 0 <p] checks 0 < e.
le 0 <p
# Increment f. [d] duplicates top value on stack.
# STACK:
lf 1 + # ( f+1 )
d # ( f+1 f+1 )
sf # ( f ) as f+1 becomes f
# Continue loop if b >= f. This is golf for f <= a and f <= b, as
# extra iterations of the loop cause no harm.
# STACK:
lb # ( f b )
!<w # ( ), continue loop if not b < f
] d sw # w = loop; STACK: ( w )
x # enter loop unconditionally; STACK: ( ) at entrance
```
[Answer]
## PowerShell - 82
```
$a,$b=$args
2..$a|%{$p=0;while(!($a%$_+$b%$_)){$a/=$_;$b/=$_;$p++}if($p){"$_^$p"}}
```
[Answer]
# JavaScript (ECMAScript 6 Draft) - 89 Characters
```
f=(m,n,i=2,k=0)=>(m%i|n%i?(k?i+'^'+k+' ':'')+(i>m?'':f(m,n,i+1)):f(m/i,n/i,i,k+1)).trim()
```
Converts the original (iterative) answer, below, into a recursive one.
**Explanation**
```
f=(m,n,i=2,k=0)=> // A function with arguments m and n and optional arguments
// i (defaults to 2) and k (defaults to 0)
(
m%i|n%i // if i is not a divisor of m or n then:
?(k?i+'^'+k+' ' // if k is non-zero append "i^k " to the output
:'') // else append nothing
+(i>m?'' // if i>m then terminate
:f(m,n,i+1)) // else increment i and reset k to 0
:f(m/i,n/i,i,k+1) // else divide m and n by i and increment k
).trim() // finally strip any extra spaces from the output.
```
# Iterative Answer: JavaScript (ECMASCript 6) - ~~108 (or 121)~~ 98 Characters
**Version 2:**
```
f=(m,n)=>{for(s='',i=1;++i<=m;s+=k?' '+i+'^'+k:'')for(k=0;m%i+n%i<1;k++)m/=i,n/=i;return s.trim()}
```
**Version 1:**
Answering the question as originally asked:
```
f=(m,n)=>{for(o=[],i=2;i<=m;)m%i|n%i?i++:(m/=i,n/=i,o[i]=(o[i]|0)+1);return o.map((x,i)=>i+"^"+x).join(' ')}
```
Or to comply with the rule changes after the fact:
```
f=(m,n)=>{for(o=[],i=2;i<=m;)m%i|n%i?i++:(m/=i,n/=i,o[i]=(o[i]|0)+1);return o.map((x,i)=>i+"^"+x).filter(x=>x).join(' ')}
```
**Explanation**
```
f=(m,n)=> // Create a function f with arguments m and n
{
o=[] // Initialise an empty array for the output
i=2 // Start with a divisor of 2
for(;i<=m;) // Loop while the divisor is not greater than m
m%i|n%i // Test the bitwise OR of m%i and n%1 (i.e. whether
// at least one is non-zero)
?i++ // If m%i>0 or n%i>0 then increment i
:(m/=i, // Otherwise: divide m by i;
n/=i, // n by i;
o[i]=(o[i]|0)+1); // and add 1 to the i-th element of o
return o.map((x,i)=>i+"^"+x) // finally map the sparse array o to a sparse array
// of the strings (index+"^"+value)
.filter(x=>x) // turn sparse array into non-sparse array
.join(' ') // then concatenate and return.
}
```
**Output**
```
f(96,162)
"2^1 3^1"
f(14,15)
""
f(80, 80)
"2^4 5^1"
f(196,294)
"2^1 7^2"
```
[Answer]
# Perl 6: 90 characters, 94 bytes
```
sub MAIN(*@n){@n.any%$_||(my$p=$p⊎$_;@n»/=»$_;redo)for
2..@n[0];$p.pairs.fmt("%d^%d").say}
```
Somewhat de-golfed and commented:
```
sub MAIN (*@n) { # accept any number of input numbers as @n
(
# $p is a Bag, e.g., it holds the primes and the number of times each was added
my $p = $p ⊎ $_; # Add the prime to the bag
@n »/=» $_; # Divide all the input numbers by the prime
redo # Redo the loop iteration with the same prime, in case
# the numbers can be divided by it multiple times
)
if @n.all %% $_ # Do the above only if all of @n are divisible by $_
for 2..@n[0]; # Do the above for all numbers from 2 .. @n[0]
$p.pairs.fmt("%d^%d").say # Print join " ", "$prime^$count"
}
```
Usage is like:
```
$ perl6 -e'sub MAIN(*@n){@n.any%$_||(my$p=$p⊎$_;@n»/=»$_;redo)for
2..@n[0];$p.pairs.fmt("%d^%d").say}' 51 153
3^1 17^1
```
[Answer]
# Perl, ~~144~~ ~~133~~ ~~118~~ ~~114~~ ~~97~~ 93
```
($a,$b)=<>=~/\d+/g;for(2..$a){for($n=0;$a%$_+$b%$_<1;$n++,$a/=$_,$b/=$_){}$n&&print"$_^$n ";}
```
Ungolfed version:
```
($a,$b)=<>=~/\d+/g;
for(2..$a){
for($n=0 ; $a%$_+$b%$_<1 ; $n++,$a/=$_,$b/=$_) {}
$n&&print"$_^$n ";
}
```
I've literally just started learning Perl just to answer this question (this is my first Perl code ever), so I suspect that this can be golfed down further.
[Answer]
# Java : ~~247~~ 241
Keeps track of factors in an array and just prints them out in a loop.
Decent size for Java, it seems.
```
class G{public static void main(String[]a){Integer i=1;int n=i.valueOf(a[0]),m=i.valueOf(a[1]),f[]=new int[n>m?n:m+1];for(;m>=++i||n>i;){if(n%i+m%i<1){f[i]++;n/=i;m/=i--;}}for(i=2;i<f.length;System.out.print(f[i]>0?i+"^"+f[i]+" ":""),i++);}}
// line breaks below
class G{
public static void main(String[]a){
Integer i=1;int n=i.valueOf(a[0]),m=i.valueOf(a[1]),f[]=new int[n>m?n:m+1];
for(;m>=++i||n>i;){
if(n%i+m%i<1){
f[i]++;n/=i;m/=i--;
}
}
for(i=1;i<f.length;System.out.print(f[i]>0?i+"^"+f[i]+" ":""),i++);
}
}
```
[Answer]
# JavaScript (ECMAScript 5) 170 164 163 113
I pretty much couldn't resist following MT0's lead. I had considered recursion before, but it had seemed too easy to mess up. And it really is. The slightest variation wrecks everything.
[There's a fiddle for those who like fiddles.](http://jsfiddle.net/plus5keen/S42Uz/)
```
function f(a,b,i,e){return i?a%i|b%i?(e?i+'^'+e+' ':'')+(i>a?'':f(a,b,i+1,0)):f(a/i,b/i,i,e+1):f(a,b,2,0).trim()}
```
Ungolfed:
```
function f(a,b,i,e){
return i // Check for factor.
?a%i|b%i // Check for indivisibility.
?(
e // Check for exponent.
?i+'^'+e+' ' // Add the current factor to result string.
:'' // Omit the current non-factor.
)+(
i>a // Check for termination state.
?'' // Stop recursion.
:f(a,b,i+1,0) // Go to the next factor.
)
:f(a/i,b/i,i,e+1) // Failed indivisibility check. Increment exponent and divide subject values.
:f(a,b,2,0) // Add default factor and exponent.
.trim() // Get rid of one extra space that's usually on the end.
}
```
### Old Version
```
function f(a,b){for(var r=[],j=-1,i=2;i<=a;)a%i|b%i?++i:(r[j]&&r[j][0]==i?r[j][1]++:r[++j]=[i,1],a/=i,b/=i);for(j=0;i=r[j];++j)r[j]=i.join('^');return r.join(' ')}
```
Ungolfed:
```
function f(a,b){
for(var r=[],j=-1,i=2;i<=a;)
// We (mis)use conditional expression `?:` instead of `if(){}else{}`.
a%i|b%i ? // Bitwise OR saves one character over logical OR, where applicable.
// In the truth case, `i` has become uninteresting. Just move on.
++i : // We don't mind hitting composites because their prime factors have already been drained from `a` and `b`.
(
r[j]&&r[j][0]==i ? // Check if `i` is already a listed factor.
r[j][1]++ : // Increment the exponent count.
r[++j]=[i,1], // Otherwise, add a new factor with exponent 1.
a/=i,b/=i // Drain a used-up factor from `a` and `b`.
);
// The real work's done. Now we just format.
for(j=0; i=r[j]; ++j)
r[j]=i.join('^'); // Join each factor to its exponent.
return r.join(' ') // Join all factors into result string.
}
```
Here are a few tests:
```
[
f(4, 12),
f(80, 80),
f(96,162),
f(196,294)
];
```
[Answer]
# GolfScript, 68 bytes
```
~..),2>*${1$1$%3$2$%+!{.@@/@2$/.}*;}/;;]:D.&{`.[~]D\/,(`"^"\++}%" "*
```
Note that this approach requires O(b2) time and space for integers “a” and “b”.
At the cost of one extra byte, "only" O(b) time and space are necessary:
```
~.),2>31*${1$1$%3$2$%+!{.@@/@2$/.}*;}/;;]:D.&{`.[~]D\/,(`"^"\++}%" "*
```
### How it works
```
~. # Interpret the input string (“a” and “b”) and duplicate “b”.
.),2> # Push the array [ 2 3 4 ... b ].
*$ # Repeat each element b times and sort: [ 2 ... 2 3 ... 3 ... b ... b ]
{ # For each element “d” of the array:
1$1$% # Calculate a % d.
3$2$% # Calculate b % d.
+! # Add and negate.
{ # If both “a” and “b” are divisible by “d”:
.@@/ # Calculate a / d.
@2$/ # Calculate b / d.
. # Create a dummy value.
}* #
; # Pop the topmost stack element (non-divisor “d” or dummy value).
}/ #
;;] # Pop “a” and “b” and collect the remaining stack elements in an array.
:|.& # Save that array in “D” and intersect it with itself to deduplicate it.
{ # For each element “d” of “D”:
`.[~] # Push string "d" and array [d].
D\/,(` # Split “D” around [d] and take the length minus 1. This count the occurrences.
"^"\ # Push the string "^" and swap it between "d" and it's number of occurrences.
++ # Concatenate the three strings.
}% # Collect all strings into an array.
]" "* # Join by spaces.
```
[Answer]
# Python 3 (123)
This uses basically the same structure as [Tal's answer](https://codegolf.stackexchange.com/a/26696/20260).
```
a,b=map(int,input().split())
s='';p=1
while p<a:
c=0;p+=1
while a%p+b%p<1:a/=p;b/=p;c+=1
if c:s+='%d^%d '%(p,c)
print(s)
```
It suffices to loop up to p=a-1, since we increment immediately to get p=a and a>=min(a,b). If b>a, there's no harm in trying useless values of p above a.
In 2.X, I think we could save characters by printing each piece as we get it rather than accumulating a string: `if c:print'%d^%d'%(p,c),`. Python 3, unfortunately, doesn't seem to have a compact way to print without a trailing newline.
[Answer]
# PHP, 96
```
<?php
list(,$a,$b)=$argv;for($s=1;$s++<$a;$c&&print"$s^$c ")for($c=0;1>$a%$s+$b%$s;$a/=$s,$b/=$s)$c++;
```
[Answer]
# awk - ~~115~~ ~~111~~ ~~96~~ 85
New version can only handle one line of input. Thanks to [durron597](https://codegolf.stackexchange.com/users/17249/durron597) for pointing out that I only need to make sure `i <= $1`.
```
{for(i=1;++i<=$1;)for(;$1%i+$2%i==0;f[i]++){$1/=i;$2/=i}$0=z;for(i in f)$i=i"^"f[i]}1
```
Ungolfed:
```
{
#skip finding gcd as a separate step, get it from the factors
for(i = 1; ++i <= $1;) {
for(;$1 % i == 0 && $2 % i == 0; f[i]++) {
$1 /= i;
$2 /= i;
}
}
$0 = "";
for(i in f) {
$i = i "^" f[i];
}
print;
}
```
Previously could take pairs of numbers repeatedly
```
{a=$1;b=$2;for($0=c;a-b;)if(a>b)a-=b;else b-=a;for(i=2;i<=a;i++){for(j=0;a%i==0;j++)a/=i;$0=$0(j?i"^"j" ":c)}}1
```
Ungolfed:
```
{
a = $1;
b = $2;
$0 = "";
#rip off Euclid
for(; a != b;) {
if(a > b) {
a = a - b;
} else {
b = b - a;
}
}
#but not Eratosthenes
for(i = 2; i <= a; i++) {
for(j = 0; a % i == 0; j++) {
a /= i;
}
$0 = $0 (j ? i "^" j " " : "");
}
print;
}
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 41 bytes
**Not a competing answer, since language is newer than question.** But that GolfScript mark of 68 needed to come down.
```
Fi2,++a{p:0T$|g%i{++pg/:i}Ipx.:i.'^.p.s}x
```
Output ends in a space; if that's a problem, the following version is also 41 bytes (including the `-s` flag):
```
Fi2,++a{p:0T$|g%i{++pg/:i}IplAE:i.'^.p}l
```
Formatted, with explanations:
```
F i 2,++a { For i in range(2,a+1); note ++ used to avoid parentheses in 2,(a+1)
p:0 p will store the greatest power of i that divides both numbers
T $+(g%i) { Loop till the sum of g%i is nonzero, where g is a list initialized
from cmdline args
++p As long as g%i is [0 0], increment p...
g/:i ...and divide both numbers in g by i
}
I p If p is nonzero, i went into both numbers at least once
x.:i.'^.p.s Append i^p and a space to the result
}
x Print the result
```
Pip, unlike GolfScript, CJam, et al. is an imperative language with infix operators; it also takes some inspiration from array-programming languages. This task nicely displays both paradigms at work.
(Note that the 2015-4-20 commit is needed to run this, since I just fixed a couple of bugs.)
[Answer]
# Python 2 - 262 bytes
```
n,m=input(),input()
f=lambda i:set(filter(lambda x:i%x<1,range(1,i+1)))
g=max(f(n)&f(m))
p=[]
while g-1:
p+=[min(filter(lambda x:x>1 and x%2!=(x==2)and not any(map(lambda y:x%y<1,range(2,x))),f(g)))]
g/=p[-1]
print ' '.join(`a`+^+`p.count(a)`for a in set(p))
```
Line 6 needs work.
[Answer]
## Groovy : 174 chars
This is a port of [Geobits' solution](https://codegolf.stackexchange.com/a/26717/21004) to Groovy 2.2.1:
```
int i=1, n=args[0]as int, m=args[1]as int;s=n>m?n:m+1;f=new int[s];while(m>=++i||n>i){if(n%i+m%i<1){f[i]++;n/=i;m/=i--;}};(s-1).times{y=it+1;x=f[y];print"${x>0?"$y^$x ":""}"}
```
Here is the ungolfed version:
```
int i = 1, n = args[0] as int, m = args[1] as int
s = n>m?n:m+1
f = new int[s]
while (m>=++i||n>i) {
if (n%i+m%i<1) {
f[i]++;n/=i;m/=i--;
}
}
(s-1).times {
y=it+1
x=f[y]
print"${x>0?"$y^$x ":""}"
}
```
[Answer]
## R: 139
```
a=scan();q=1:a[1];n=max(q[!a[1]%%q&!a[2]%%q]);m=rep(0,n);for(i in 2:n){while(!n%%i){m[i]=m[i]+1;n=n/i};if(m[i])cat(paste0(i,"^",m[i])," ")}
```
With indentations:
```
a=scan() #Take space-separated numeric input from stdin
q=1:a[1]
n=max(q[!a[1]%%q&!a[2]%%q]) #gcd
m=rep(0,n)
for(i in 2:n){
while(!n%%i){ #prime factorization
m[i]=m[i]+1
n=n/i
}
if(m[i])cat(paste0(i,"^",m[i])," ")
}
```
Usage:
```
> a=scan();q=1:a[1];n=max(q[!a[1]%%q&!a[2]%%q]);m=rep(0,n);for(i in 2:n){while(!n%%i){m[i]=m[i]+1;n=n/i};if(m[i])cat(paste0(i,"^",m[i])," ")}
1: 196 294
3:
Read 2 items
2^1 7^2
```
]
|
[Question]
[
Given a list of positive integers, give the longest contiguous sublist which contains at most 1 pair of identical items. In the case of a tie return any of the solutions.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize your source code with answers being scored in bytes.
## Test cases
```
[] -> []
[1,2,3] -> [1,2,3]
[1,2,2,3] -> [1,2,2,3]
[2,2,3,2,4] -> [2,3,2,4]
[1,2,1,3,2] -> [2,1,3,2]
[1,2,3,1,4,1,2,3,4,5,1] -> [1,2,3,4,5,1]
[1,2,3,2] -> [1,2,3,2]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ẇœ-QḊƊÐḟṪȯ
```
**[Try it online!](https://tio.run/##y0rNyan8///hrrajk3UDH@7oOtZ1eMLDHfMf7lx1Yv3/w@1HJz3cOeP//2hDHQUjHQUgaQxkxAIA "Jelly – Try It Online")**
### How?
```
Ẇœ-QḊƊÐḟṪȯ - Link: list, A
Ẇ - substrings (well, non-empty ones) sorted by length then left to right
Ðḟ - filter discard those for which this is truthy:
Ɗ - last three links as a monad:
Q - distinct values
œ- - multiset difference - remove one of each value from A
Ḋ - dequeue - remove one from this list if there are any
- [] is falsey
Ṫ - tail - one of, or the, longest one
- unless A was [] in which case zero
ȯ - logical OR with A - replace that zero with []
```
---
Alternatively, `Ẇœ-QLỊƲƇṪȯ`.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 64 bytes
```
f=(a,...r)=>a[new Set(a).size+1]?f(...r,a.slice(1),a.pop()&&a):a
```
[Try it online!](https://tio.run/##VY8xT8QwDIX3/gpPV1uXRiqUhVPKxMIAw42l0lklhaBcGzVRkUD89tJeWgSD5fe@Z9nyO4/sm8G4kHX9i56mViELKeVAquSq0x9w1AGZpDefep/Xdy0uqWDprWk05jRL1zuk3Y7plqegfWjYaw8KTklVQ1ZCVSdVLq7EdXRRRvQPRnzpcxUx2Eyczxe3BdGsu2dXiKgKcSPyP7dWkJxkGMwZ52ecNQHT5y4leWaHFlQJdsNZueJxwQ/Hp0fpePAaRyI6JL8fyrYf7rl5Q6yMAF3TMv6VADR953urpe1fUYNS0KIh2EOaioucl3zTYfoB "JavaScript (Node.js) – Try It Online")
---
# [Python 3](https://docs.python.org/3/), 58 bytes
```
f=lambda l,*r:len(l)>1+len({*l})and f(*r,l[1:],l[:-1])or l
```
[Try it online!](https://tio.run/##VY/BroIwEEX3fMWEDR0cTKq4IYEfQRZVS2wy1qY0L3l5ed@OxYrRRaf33LlpZ9xvuN7tfp7HltXtdFHAVPqGtRWMndws4q/kf1T2AqMoPXEvmyHWppID3j3wPMYa9BTOatJgLOR5nvUDVB30Q9ZL2tE@UZLJ@jKT/bzjqVNjhZSXC62NBK@3I9WUVE0Hkh9/vYwsTrSdgjdO4HZybIIojrbAJgMwBBpauCkn9I9iem@yBquuQIxB540NYhQGoW1BEywS5wc "Python 3 – Try It Online")
Yet another question solved with same pattern?
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~14~~ ~~12~~ 10 bytes
*-2 bytes thanks to [xash](https://codegolf.stackexchange.com/users/95594/xash)*
```
⊇.ọtᵐ×≤2&s
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1FXu97D3b0lD7dOODz9UecSI7Xi//@jDXWMdIx1DHVMdCAsEx1THcPY/xEA "Brachylog – Try It Online")
### Explanation
We're looking for a sublist in which each element occurs only once, except that one element may occur twice.
Makes use of [this very helpful tip](https://codegolf.stackexchange.com/a/231602/16766) from [Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string).
```
⊇.ọtᵐ×≤2&s
The input
⊇ Sublist (not necessarily contiguous), trying longest first
. The result is the output
ọ Generate a list of [element, count] pairs
tᵐ Get the last element of each pair (list of counts)
× Product
≤2 Is less than or equal to 2
&s Also, the output is a contiguous sublist of the input
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 11 bytes
```
ẆµĠẈ’SỊµƇṪȯ
```
[Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCLhuobCtcSg4bqI4oCZU+G7isK1xofhuarIryIsIsOH4oKsIiwiIixbIltbXSwgWzEsMiwzXSwgWzEsMiwyLDNdLCBbMiwyLDMsMiw0XSwgWzEsMiwxLDMsMl0sIFsxLDIsMywxLDQsMSwyLDMsNCw1LDFdXSJdXQ==)
-1 byte thanks to Jonathan Allan
```
ẆµĠẈ’SỊµƇṪȯ Main Link
Ẇ all sublists
µ µƇ filter
Ġ - group indices of equal elements
Ẉ - length of each group
’ - subtract one from each length
S - sum of these (total number of duplicate elements)
Ị - is this insigificant? (between -1 and 1)
Ṫ take the last (longest) element
ȯ logical OR; if the output is 0 (only happens if input
is []), return the input instead, which fixes [] being
output as 0
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 14 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Feel like I'm missing a trick here :\
```
ã fÈÊɶXâ ÊÃiU
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=4yBmyMrJtljiIMrDaVU&input=WzEsMiwxLDMsMl0)
[Answer]
# [Python 3](https://docs.python.org/3/), 68 bytes
```
f=lambda l:len(l)>1+len({*l})and max(f(l[1:]),f(l[:-1]),key=len)or l
```
[Try it online!](https://tio.run/##VY1BasQwDEX3PoWZldUqAXfSTSC5SMjCJQ4VVWwTm6Gh9OypXc9AuxB670tI4Ujv3l3Pcx3YbG@LkdyzdYph1M8Fvp74G4xb5GY@1ap40v0MWKBvdKYPewx5D/wu@aQt@D3JeEQh1pJIcsXamBZy7W7NwuRsVNALSeiHzQRlb4aR2xiYkro04wVAyLCTS4ryIwL0cE6zbEY5zWLS@ILXahVr9C@s8W/P1dXBQ@q@LvYYVLnfztZhpQ5fUf/5dQ9@AA "Python 3 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~108~~ 83 bytes
```
f l@(u:q)|0:(0<$l)<[0|x<-l,y<-q,x==y]=f(init$l)!f q
f q=q
a!b|(a<$a)>(a<$b)=a|1>0=b
```
[Try it online!](https://tio.run/##bYnBCsIwEAXv/Yot5JDAFpJaLyVb/I@SQ4oGgzE1WqGF/HusePXwmGHe1b5ulxBKcRBO/N0nkWXPpWZB6FHmVTcBN90kXIk2Q4776Jf9rB2kah@lytZT5lYzK4YvJkE2q0HSVO7WRyA4zxXA4@njAgzcqLDFA7bmT1TY4c86PKIy5QM "Haskell – Try It Online")
* Thanks to @Wheat Wizard for saving so many many bytes!
`g` : counts duplicates. -> moved to list comprehension in *f* by Wheat Wizard , the tricky part is here and deserves an explanation
```
f(u:q)|
(0<$q) list 0s for each element
< compared to
[0|x<-q,y<-q,x==y] list of 0s for each equal pairs in the powerset
```
Note that we use tail so that one potential dupe is already counted and the lists must be the same, if not there is more than 1 dupe, in that case we search.. Else we skip this and f q=q match giving the result.
a`!`b : selects longer list.
`f`*list* : if *list* is not ok choose from head or tail else return it
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 78 bytes
```
M!&r`.*\d\b
.*\b(\d+)(?=.*,\1\b),(.*\b(\d+)\b.*,\3\b)
$2
O$^`((,)|\d)+
$#2
1G`
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7w31dRrShBTysmJSaJC0glacSkaGtq2NvqaenEGMYkaepowEVjkkCCxkBBLhUjLn@VuAQNDR3NmpgUTW0uFWUjLkOgcf@5DHWMdIzBJIgGk0BsAhYxBLEhKoBsEx0Iy0THVMcQAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
M!&r`.*\d\b
```
Take all of the suffixes.
```
.*\b(\d+)(?=.*,\1\b),(.*\b(\d+)\b.*,\3\b)
$2
```
Truncate them at the second last duplicate. (Since we need this longish regex to check for two pairs/three of a kind, it turns out to be golfier to truncate the prefixes than to filter on all sublists.)
```
O$^`((,)|\d)+
$#2
```
Sort by descending number of elements.
```
1G`
```
Take the first.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 63 bytes
```
f=->l,s=1{l[-s]&&f[l,s+1]||l.each_cons(s).find{|q|q.uniq[s-2]}}
```
[Try it online!](https://tio.run/##KypNqvz/P81W1y5Hp9jWsDonWrc4Vk0tLRrI1TaMranJ0UtNTM6IT87PK9Yo1tRLy8xLqa4prCnUK83LLIwu1jWKra39X6CQFh1tqGOkY6xjomMKomNj/wMA "Ruby – Try It Online")
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 28 bytes
```
su<-{f:)-]g_2<=j{1==}al&&}fe
```
[Try it online!](https://tio.run/##SyotykktLixN/Z@TV12U@L@41Ea3Os1KUzc2Pd7Ixjar2tDWtjYxR02tNi31f21u9P9oQx0jHeNYBS4wA8oEM4DYJBYibAjiQdnGQJ6JDoRlomOqYxgLAA "Burlesque – Try It Online")
```
su # All substrings from shortest to longest
<- # Reverse (longest first)
{
f: # Frequency list as (count, val) sorted by count
)-] # Map head (get counts)
g_ # Split into head + tail
2<= # Head is 2 or 1
j # Swap
{1==}al # Tails all 1s
&& # Logical AND
}fe # Find the first element for which
```
[Answer]
# [R](https://www.r-project.org/), 162 bytes
Or **[R](https://www.r-project.org/)>=4.1, 148 bytes** by replacing two `function` occurrences with `\`s.
```
function(v,a=apply(combn(rep(seq(v),2),2),2,function(x,t=table(k<-v[x[1]:x[2]]))if(x[1]<=x[2]&all(t%in%1:2)&sum(t==2)<2)k))"if"(sum(v),a[order(-lengths(a))[1]],v)
```
[Try it online!](https://tio.run/##XY7RDoIgFIbve4pWq52z4QVkN016EcYFGZSL0JScPb2BVlYbbOf7fuCn7g3vzd3lvigdtERxVVX2AXl5PTiodQWNvkGLhI2LfM52xHOvDlbDJUta0Qkqd51gUiIWBiJmPPJaWQt@VbgV3TFcN/creM4ZZgwviIvCLCC6UKFEWR91DYnV7uTPDSjE8IwkLfYGckBczpP9XMhZJBo@s3mrASb/l3yyYQw7facvnG7SKKZ0wK@@IFIyTinZEvrTPyrZPwE "R – Try It Online")
I was hoping for some ingenious answer from better [R](https://www.r-project.org/) golfers here, but it looks like I have to post my boring straightforward one first for some motivation.
[Answer]
# [Factor](https://factorcode.org/) + `math.unicode`, 77 bytes
```
[ f suffix all-subseqs [ histogram values 1 v-n Σ 2 < ] find-last nip sift ]
```
[Try it online!](https://tio.run/##RY9BTgMxDEX3PcW/wIw0pRUSsEdsukFdVV2Y1Gkj0iTEzqgFcRruw5WGtCM6C1vP/v6WviWjMQ/r15fV8wOEPwoHwzJRyyfNJDiSHq6tFSV1os4ISCSaUWt7vnwSvHMO7MddCc7EHSNlVj2n7IJiz4EzefdZv8QgeJzNvvBdq8Mcdzf655HmWNyU7jpPjq5qIy2wrDQpl6thAwsp1roTyPtGylvNJtjgUEPEfaYjevKlZu7QNwG/P9X3hC2sC7vGkyiCSxBnFdvhHoFS8me0AuOZ8vAH "Factor – Try It Online")
## Explanation
* `f suffix ... sift` Work around the fact that `all-subseqs` blows up on an empty input. Add `f` to the input and remove it with `sift` at the end. (This doesn't change anything since we're only adding one.)
* `all-subseqs [ ... ] find-last nip` Find the last/largest subsequence of the input that returns true when the given quotation is called on it.
The quotation to `find-last` works by taking a histogram of the input, subtracting 1 from all the counts, taking the sum, and checking whether the sum is less than two. For instance:
```
! { 2 2 3 2 4 }
histogram ! H{ { 2 3 } { 3 1 } { 4 1 } }
values ! { 3 1 1 }
1 v-n ! { 2 0 0 }
Σ ! 2
2 < ! f
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 47 bytes
```
f[s=___,Longest@a:s,s]/;Total[Counts@{a}-1]<2=a
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/z8tutg2Pj5exyc/Lz21uMQh0apYpzhW3zokvyQxJ9o5vzSvpNihOrFW1zDWxsg28X9AUWZeSbSyrl2ag4NyrFpdcHJiXl01V3WtDle1oY6RjjGMAWWCGUBsAhM3BHHhqoFcEx0Iy0THVMewlqv2PwA "Wolfram Language (Mathematica) – Try It Online")
Input and output a `Sequence` of values.
---
### [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 48 bytes
```
Last@*Select[Total[Counts@#-1]<2&]@*Subsequences
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yexuMRBKzg1JzW5JDokvyQxJ9o5vzSvpNhBWdcw1sZILRYoW5pUnFpYmpqXnFr8P6AoM68kWlnXLs1BOVatLjg5Ma@umqu6Voer2lDHSMcYxoAywQwgNoGJG4K4cNVArokOhGWiY6pjWMtV@x8A "Wolfram Language (Mathematica) – Try It Online")
Input and output a list.
[Answer]
# [Haskell](https://www.haskell.org/), 80 bytes
```
import Data.List
l=length
head.sortOn(\x->(l(x\\nub x)>1,-l x)).(tails=<<).inits
```
[Try it online!](https://tio.run/##PY3BDoIwEETv/Yoe26Q0KeKNcvKo8QOAmBqLbCiV0DXh72sF9LB5M7Ob2d6EwToXI4zTa0Z6MmjkGQISp531T@xJp3trHjKk9dWzZskq5tjSNP59pwuvlMhcIpcMDbigy5JL8IAhog0YqKZ13YpaiVwcdm5qZZpiT9XX/S6TK8SmCnEU6p/nbUvIaMCn4tFMlxtl0wweZcfp@jB@AA "Haskell – Try It Online")
Get all infixes, sort by `(invalid, -length)`, return the first one.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~40~~ 38 bytes
```
≔⟦⟧ηFθ«⊞υιW‹¹ΣEυ›μ⌕υλ≔Φυμυ¿›LυLη≔Iυη»η
```
[Try it online!](https://tio.run/##TY4/D4IwEMVn@BQ3tsk5oDgxGRNcMCFxJAwNFtqkgPaPDsbPXlvExJte7vfeu@sE093MlPcHY@QwkaZFELRI@1kDuVN4pUntjCAOQYZ18hRScSAVN4ZkCBc3kjO7RXzSnFmuyYhQyukaV4ouA2t3KVU0BDBSBBfrZA/kF6z4NNhwKbBVir/wkRm7sPjdO621nGwwFN43TYZb3GGGOX5VjnvM2tZvHuoD "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⟦⟧η
```
Start with no longest sublist.
```
Fθ«
```
Loop over the input terms.
```
⊞υι
```
Append the term to the predefined empty list.
```
W‹¹ΣEυ›μ⌕υλ
```
While the current sublist contains more than one duplicate...
```
≔Φυμυ
```
... remove the first term from the sublist.
```
¿›LυLη
```
If the sublist is longer than the longest sublist so far, then...
```
≔Iυη
```
... save a copy of the sublist (because we're going to push to the original, and we need to cast it to string anyway).
```
»η
```
Output the longest sublist (which we already cast to string above).
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~10~~ 9 bytes
*Edit: -1 byte thanks to Razetime*
```
►LfoεṠ-uQ
```
[Try it online!](https://tio.run/##yygtzv7//9G0XT5p@ee2Pty5QLc08P///9GGOkY6xjqGOiY6EJaJjqmOYSwA "Husk – Try It Online")
```
► # output the (first) element with maximum...
L # ...length...
# ...from among:
Q # all contiguous sublists,
fo # filtered by:
Ṡ- # the difference between...
u # ...itself and unique elements of itself...
ε # ...has length 1.
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~79~~ 75 bytes
```
f=(X,a)=>X[h=new Set([w,...x]=X).size+1]?(a=f(x),b=f(X,X.pop()),a[h]?a:b):X
```
[Try it online!](https://tio.run/##dY3BCsIwDIbvPoXHBGOhWi@DuofwEig9dLNzk7EOO9zw5eumN3GHkPB9/0/u7uli@Wj6Yd@Fq0@p0sDkUJ/Z1Lrz4/biBzAjCSEmqxlFbF5@J20OTlcwIRXzYmLRhx4QyZna5i4rMONUhi6G1os23KACYxE3P0jSgY4r/L/58HnUSksudu3TbBV9L0UnkksuJX4D "JavaScript (Node.js) – Try It Online")
AnttiP's idea, can't read golfing language so don't know if that's source
# [JavaScript (Node.js)](https://nodejs.org), 89 bytes
```
f=(x,h,L=0,a=x.filter(y=x=>!(y[x]=h+=[y[x]])[20]&&++L),b=x[0]?f(x.slice(1)):[])=>b[L]?b:a
```
[Try it online!](https://tio.run/##dY1BDoIwEEX33sINmYaRUMQNycAFuEHTRcFWMQ01QEw5fQXdGbuY5Oe9/zMP9VJzPw3P5TS6qw7BEHi8Y0s5KvKZGeyiJ1jJU32EVXhJ95TEHiQTRS6TJE1bhh15kcvGgM9mO/QaOGOVkIzqTrSy6SoVejfOzurMuhsY2Bw7/CCOBZ4j/L/58O3KyIrvNvZpsyV@U4kX5HsvRNQb "JavaScript (Node.js) – Try It Online")
Is it usual to be 6-8x longer than golfing language or this is quite golfable?
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ŒʒgyÙg-!}éθ
```
[Try it online](https://tio.run/##yy9OTMpM/f//6KRTk9IrD89M11WsPbzy3I7//6MNdYx0jHUMdUx0ICwTHVMdw1gA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/o5NOTUqvPDwzXVex9vDKczv@6/yPjo7VUYg21DHSMYYxoEwwA4hNYOKGIC5cNZBrogNhmeiY6hgiJIxiYwE).
**Explanation:**
```
Œ # Get all sublists of the (implicit) input-list
ʒ # Filter this list of sublists by:
g # Get the length of the sublist
y # Push the sublist again
Ù # Uniquify its items
g # Pop and push the length of this uniquified list as well
- # Subtract the lengths from one another
! # Check if this is either 0 or 1 by taking the faculty, which will
# result in [1,1,2,6,24,120,...] for [0,1,2,3,4,5,...] respectively,
# and only 1 is truthy in 05AB1E
}é # After the filter: sort the remaining sublists from shortest to longest
θ # Pop and keep just the last (longest)
# (after which it is output implicitly as result)
```
]
|
[Question]
[
**Background:**
For this challenge, a polynomial looks like this:
$$P(x)=a\_nx^n+a\_{n-1}x^{n-1}+\dots+a\_2x^2+a\_1x+a\_0$$
The degree, \$n\$, is the highest power \$x\$ is raised to. An example of a degree 7 polynomial would be:
$$P(x)=4x^7+2x^6-7x^4+x^2-6x+17$$
All powers are integers \$n\ge0\$. This means \$x\$, \$-2\$, and \$0\$ could all be considered polynomials, but not \$\frac{1}{x}\$ or \$\sqrt{x}\$.
**Challenge:**
Write a program or functions which takes a number of pairs \$(x, P(x))\$, and finds the smallest possible degree of \$P(x)\$. The values of \$x\$ will be incrementing; \$\{(0, 1), (1, 0), (2, 1)\}\$ is a valid input, but \$\{(0, 2), (10, 20), (11, 22)\}\$ is not.
Given \$\{(0, 1), (1, 0), (2, 1)\}\$, for example, the degree is \$2\$ (and \$P(x)=x^2-2x+1\$).
**Input:**
Input will consist of at least \$n+1\$ pairs of integer values, and at least \$2\$, representing \$x\$ and \$P(x)\$. The \$x\$ values will all be one higher than the previous one.
Input can be taken in any reasonable format. Invalid inputs do not need to be handled. Optionally, you can input only the \$P(x)\$ values (and ignore \$x\$ altogether).
**Output:**
Output will be an integer \$n\ge0\$, representing the degree of \$P(x)\$.
As with the input, any reasonable format is valid.
**Tip:**
A simple way to find the degree of a polynomial function (like \$P(x)\$) when you have a list of inputs with incrementing \$x\$ values is to create a list of the \$P(x)\$ values, then repeatedly find the difference between adjacent items. For example, given the inputs \$\{(-3, 14), (-2, 4), (-1, -2), (0, -4), (1, -2)\}\$:
$$\{14, 4, -2, -4, -2\}$$
$$\{10, 6, 2, -2\}$$
$$\{4, 4, 4\}$$
After some number of iterations, \$2\$ in this case, all of the items will be the same number. That number of iterations is \$n\$.
**Test cases:**
```
(-1, 8), (0, 8), (1, 8) 0
(0, 0), (1, 0), (2, 0) 0
(1, 0), (2, 1) 1
(0, 0), (1, 2), (2, 4), (3, 6), (4, 8) 1
(-4, -20), (-3, -12), (-2, -6) 2
(6, 1296), (7, 2401), (8, 4096), (9, 6561), (10, 10000) 4
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes per language wins!
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~8~~ 6 bytes
```
←VE¡Ẋ-
```
[Try it online!](https://tio.run/##yygtzv7//1HbhDDXQwsf7urS/f//f7ShiY6Jjq6Rji6IjAUA "Husk – Try It Online")
-2 bytes from Leo.
## Explanation
```
←VE¡Ẋ- Input: list of P(x)
¡Ẋ- repeatedly take deltas and put in infinite list
V First index where
E all elements are equal
← decrement
```
[Answer]
# [J](http://jsoftware.com/), 26 18 17 bytes
```
-~@}.i.~#\-/\~&2]
```
[Try it online!](https://tio.run/##PUpBCsIwALvvFUHBIbS1LbXoQJAJnsSD50lZZzcVQbDbwYP9eq2HmZCQhNzjhOUtNgVyEHAUSZRhdzrsIw3bD7uxMK3oogozeY7zzDXXJ1qsfhyLUEQRI4lRBEb@V7nWkIoLKJ6SXmoBwROQjRcJo5IdS4be@R5N7R380HWpuAvsG@Vg7cO94hc "J – Try It Online")
Thanks to Bubbler for -1 byte and for catching a bug!
* `-/\~&2` Apply "successive deltas" verb iteratively "left arg" times to the right arg.
* `#\ ... ]` Where the left arg is the lengths of input prefixes (ie, `1 2 3 ... <input length>`) and the right arg is the input. Eg, with the input `14 4 _2 _4 _2` this gives us the matrix:
```
10 6 2 _2
4 4 4 0
0 0 0 0
0 0 0 0
0 0 0 0
```
* `-~@}.` Subtract the original input from itself after killing the first element `}.`. The gives a row of all zeros:
```
0 0 0 0
```
* `i.~` Return index of the first row in the matrix above matching that all zeros row.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 9 bytes
```
tl.u@.+QY
```
[Try it online!](https://tio.run/##K6gsyfj/vyRHr9RBTzsw8v9/QyNLMx0FIxMDQx0FEwMQ28zUDMg2NAACAA "Pyth – Try It Online")
Input taken as a list of \$P(x)\$.
Translation of [Razetime](https://codegolf.stackexchange.com/users/80214/razetime)['s Husk answer](https://codegolf.stackexchange.com/a/219663/78186).
[Answer]
# [R](https://www.r-project.org/), ~~50~~ 39 bytes
```
x=scan();while(any(x<-diff(x)))F=F+1;+F
```
[Try it online!](https://tio.run/##PYvRCoMwDEXf9xWBvTSYQlu6sqG@@h@idiuMKtqhY@zbuzqkCYTDyb1ztFBxsC/fBTd65giWrvV1FugQPnCGdW6naejB@TDmONhxhjAswfl73Oq9ybBcH@45sNa/2Vbx3lnLNkRs6qaQZdHE78myjklNmrgivl/Ev7tS2oMFyUwqRU3@cCWIy9Q0h5DqZkhpIUmLROZiJEmRBjH@AA "R – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
IƬE€ċ0
```
[Try it online!](https://tio.run/##y0rNyan8/9/z2BrXR01rjnQb/P//39BEx0RH10hHF0QCAA "Jelly – Try It Online")
## How it works
```
IƬE€ċ0 - Main link. Takes P on the left
Ƭ - Until reaching a fixed point:
I - Take deltas
€ - For each:
E - All equal?
ċ0 - Count the number of 0s
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~13~~ 7 bytes
```
[DËD–#¥
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/2uVwt8ujhsnKh5YCObpGBjoKuoZGQMIsFgA "05AB1E – Try It Online")
*-6 thanks to ovs!*
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 39 bytes
```
Exponent[InterpolatingPolynomial[#,],]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b737WiID8vNa8k2jOvJLWoID8HKJOXHpCfU5mXn5uZmBOtrBOrE6v2P6AoE6goLVqh2tDI0kxHwcjEwFBHwcQAxDYzNQOyDQ2AoFYhNvb/fwA "Wolfram Language (Mathematica) – Try It Online")
Takes input as the list of `y`-values only. Spits some syntax errors because it uses `Null` as the variable (after each comma) to save two bytes.
If anyone knows how to translate this into Sledgehammer, I bet it would be really short.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~32~~ 34 bytes
```
f@{a_..}=0
f@a_:=f@Differences@a+1
```
[Try it online!](https://tio.run/##LYzBCsIwEETv@YpAwYubkg0xVqGSgx8geBQpS0iwh/ZQewvpr8cEuwzs29lhJlo/fqJ1dJRzsJGGtk29ZMHScO2DvY8h@MXPzn8tHTE/lnFeX424Bdu8D9vT0bxFFjvgVQlYlMCrdsR9K@AauNkzQhVLYDGFqTeqS3kpLbHEZGVzMoVRlvk3IHSgzmB0Yin/AA "Wolfram Language (Mathematica) – Try It Online")
Perhaps less interesting than Greg's answer. Implements the differences algorithm.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 45 bytes
* *6 bytes saved by [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)*
```
f=p=>(q=p.map(x=>p-(p=x))).some(x=>x)&&f(q)+1
```
[Try it online!](https://tio.run/##dUxLDsIgFNx7ClYNLwUCpBJd0IsYF6RSo2kLFWO4PT62RiazmMzv6T4uTa9HfPMt3Hwps412pLuNYnWRZjtGTqPNACBSWH11MnTdTHfoVZnClsLixRLutJ/p5cRI5RXg8BtJRiobkWr4mpGBEdP45BorXGGJm3@50mec6kEqvJFVm6NBrSQCB@UL "JavaScript (Node.js) – Try It Online")
`NaN` is falsy, let's propagate it.
---
As the tip shown in question. We iterate one more step as:
$$
\begin{matrix}
\{& 14 & 4 & −2 & −4 & −2 & \} \\
\{& 10 & 6 & 2 & −2 & & \} \\
\{& 4 & 4 & 4 & & & \} \\
\{& 0 & 0 & & & &\} \\
\end{matrix}
$$
We check the finish of iteration by looking if all elements are \$0\$.
Reducing array size when iterate cost to many bytes. So we simply fill `NaN` instead.
$$
\begin{matrix}
\{& 14 & 4 & −2 & −4 & −2 & \} \\
\{& 10 & 6 & 2 & −2 & \text{NaN} & \} \\
\{& 4 & 4 & 4 & \text{NaN} & \text{NaN} & \} \\
\{& 0 & 0 & \text{NaN} & \text{NaN} & \text{NaN} &\} \\
\end{matrix}
$$
And check if everything is *falsy*.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~59~~ 56 bytes
```
from numpy import*
f=lambda x:len({*x})-1and-~f(diff(x))
```
[Try it online!](https://tio.run/##JY3BCsIwEETvfsXQU1I2kMQatKA/Ih4qNRhokxAqpIj@ek3t7DD7lj1MnKdn8PtlsSmM8K8xznBjDGmqd/Y8dOO975Db4eHZu84fLlTne/G1rHfWssz5YkNChvO4siNhNScwSWU2UNvS1JCh/1NoSRBKlzDrrfTJEHQjFaGRK5uDKaxkEb@1OxTF5PzEMqESl4qwlf8A "Python 3 – Try It Online")
Takes a tuple of P(x) values as input.
*-3 bytes thanks to Danis*
[Answer]
# [JavaScript (V8)](https://v8.dev/), 59 bytes
*-9 bytes thanks to @Neil*
```
f=p=>p.some(x=>x-p[0])?f(p.slice(1).map((x,j)=>x-p[j]))+1:0
```
[Can't add TIO link on school internet]
## Old, 68 bytes
```
f=(p,i=0)=>!p.some(x=>x-p[0])?i:f(p.slice(1).map((x,j)=>x-p[j]),i+1)
```
[Try it online!](https://tio.run/##XYvBCoMwEETv/Yr0tks3kg022ELsh4gHEYVIbYOK@PfpSqFQhzkMb2aGZm3mdgpx0WuRUu8hUvAGfXmO2fweO9h8uelYmRof4d6D0GdoO2DMxiYCbDTgdzHUSOHCmOIUXgv0UBWkdteIpx8zpHYfGR@BJZWTcse7ttJplla7v4LtTcY2NyxHs2d3dZLZiGSZPg "JavaScript (V8) – Try It Online")
[Answer]
# Java, 153 bytes
```
int s(int[]y){return java.util.Arrays.stream(y).distinct().count()!=1?s(java.util.stream.IntStream.range(1,y.length).map(i->y[i]-y[i-1]).toArray())+1:0;}
```
Takes an array of `P(x)` values as input.
[Try it online!](https://tio.run/##TU9NT4QwEL3zK@qtVZjQzUqiRI1HD544Eg4VuliElrTTNQ3ht2MDJjqHmTcz783HIK4iG7qvTU2zsUiGmINHNcLF6xaV0XBbJsnsP0bVknYUzpF3oTRZEkJ@qw4FxnA1qiNT7NEKrdJ93RBhe8d2KiFVcCgnMB5hjm0cNXVUy28Scd0s/PRQpKdzztNzHlFxX/CU59FWxso4YE2ONVukE0d3UWCLleit/nf2q7UiOHBopZhoYNAphyq@Qhm0xusYb574i6N/koMLbxqrA1mhe0l5GmCUusdPBpOYqcqeQ62aLLqMNwzQ7LsoY3f8MS/Xbd1@AA)
## Explanation
```
int s(int[] y){
return java.util.Arrays.stream(y).distinct().count() != 1 //if not all elements are equal
?
s(
java.util.stream.IntStream.range(1,y.length).map(i->y[i]-y[i-1]).toArray()
//get difference of adjacent elements as new array
) + 1 //get result of recursive call plus 1
: 0; //otherwise, we are done
}
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 45 bytes
```
f=->a{(a|(r,*a=a))[1]?f[a.map{|c|r-r=c}]+1:0}
```
[Try it online!](https://tio.run/##JU3LCgIxEPsVj7uaykypRYXqh5Q5jAt7E5aCB9n22@tQE8iDHFI@r2/va3IP3SetU8FRk85zZnmuWc9v3fa61OJKWpqc@E6tb4ecrzAKMsE4nId6BMSxOE9w7OGiFfa3CB@IEchSvEQGk0Hkf6HV3qT1Hw "Ruby – Try It Online")
### Some explanation please?
Basically, a recursive function checking if all elements in the array are equals, and then calculating the differences and increasing by 1 at every step.
```
f=->a{
(a|(r,*a=a))[1]?
```
Check if the array has at least 2 different elements, and split it into head and tail. `r,*a=a` does the split, putting the first element of a into the variable r. The second step is equivalent to `(a|a)[1]`, or `a.uniq[1]`. If the array has at least 2 unique elements, this is a truthy value, and if it doesn't, then the result is `nil`.
```
f[a.map{|c|r-r=c}]+1
```
If the array has at least 2 different values, then calculate the difference between consecutive elements of the array, and increase the final result by 1.
```
:0}
```
If the array only contains one unique value, then the degree of the polynomial is 0.
It took me some time to come up with this solution, so I'm a little late to the party, but I didn't want to post anything above 50 bytes.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), `l`, 6 bytes
```
‡≈¬⁽¯ẋ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=l&code=%E2%80%A1%E2%89%88%C2%AC%E2%81%BD%C2%AF%E1%BA%8B&inputs=&header=1296%202401%204096%206561%2010000W&footer=)
I'm very proud with how this turned out. It looks and works exactly how I hoped Vyxal would eventually look like.
## Explained
```
‡≈¬
```
Push a two character lambda to the stack, which returns the logical not of whether or not every element in the list is equal.
```
⁽¯
```
Push a function reference of the detlas built-in
```
ẋ
```
Repeat the deltas function on the input until the first lambda returns true for the current iteration (generate while condition true). Push and implicitly print the length of the resulting list (done by the `-l` flag)
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~9~~ 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
▓>ⁿⁿ∟╔♪╒
```
[Run and debug it](https://staxlang.xyz/#p=b23efcfc1cc90dd5&i=%5B8,8,8%5D%0A%5B0,0,0%5D%0A%5B0,1%5D%0A%5B0,2,4,6,8%5D%0A%5B-20,-12,-6%5D%0A%5B1296,2401,4096,6561,10000%5D&m=2)
Same idea as my Husk answer. Takes input as P(x) alone.
## Explanation
```
{uD}{:-gf%
g generate values till:
f a value fails the filter
{ } filter:
u uniquify the list
D and delete first element
{ g generator:
:- take deltas of the previous iteration
% take the length of the generated list
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes
```
W⁻⌈θ⌊θ«UMθ⁻§θ⊕λκ⊞υ⊟θ»ILυ
```
[Try it online!](https://tio.run/##LY27CoMwFIZn8xQZT@AUrIUuTsVJUHAXh6ChhibHW9IKpc@extLt5/tv/SjXfpImhNeojeJQa/Ib1HLX1ltYBPJI/loI/mZJLedislbSAMvPjfmbK2lQ@wFK6ldlFTk1gBGx/xAiZ0njtxE88maaj6WcfVizanJQyM1Bpejuoh8v8hDaNsUMr3jOMEvxknZdOD3NFw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
W⁻⌈θ⌊θ«
```
Repeat until the maximum and minimum of the array are equal...
```
UMθ⁻§θ⊕λκ
```
... calculate the cyclic differences of the elements...
```
⊞υ⊟θ
```
... and remove the last one (which is meaningless) and push it to the predefined empty list (which thereby keeps track of the number of iterations).
```
»ILυ
```
Print the final number of iterations.
[Answer]
# [Julia](http://julialang.org/), 25 bytes
```
~n=any(n'.<n)&&1+~diff(n)
```
[Try it online!](https://tio.run/##LY7RCsIwDEXf@xV5mh1LS1NqUXD@yOjDQAeTEcRN0Jf@em07k3Bz4N5AHu9lHumTUuR@5K/kg75w2zTUxds8TZLbtN3XbYUeBjGQQ4fKoioaUAwnhDIFDebegQLUbXPaY3WVNQiKbBZfXbJnj2CdIQRnCvujz0wmV74IQjxfM28La7l/oPsr6PjnDkybfg "Julia 1.0 – Try It Online")
[Answer]
# Scala, 72 bytes
```
def g(a:Int*):Int=if(a.min<a.max)1+g(a.lazyZip(a.tail)map(_-_):_*)else 0
```
For once, recursion is shorter!
## Without recursion, 74 bytes
```
Stream.iterate(_){a=>a.lazyZip(a.tail)map(_-_)}indexWhere(a=>a.min==a.max)
```
[Try them both in Scastie!](https://scastie.scala-lang.org/XqywGBkqQnixM8CkRmD48w)
]
|
[Question]
[
In this challenge, bots must survive as long as possible. In each turn, the bot with the most HP is eliminated.
This challenge is inspired by the [Smallest unique number KoTH](https://codegolf.stackexchange.com/questions/172178/smallest-unique-number-koth).
### Results
After 100,000 rounds:
```
Jack: 63390
The Follower: 4942
The Algorithm: 2452
The Randomiser: 140
Toe Tipping: 0
EZ: 0
The Average: 0
LowProfile2: 0
Lower Profile: 0
The Bandwagon: 0
Fair Share: 0
Low Profile: 0
```
### Game Details
* In each game, all bots start with 100 HP
* In each turn:
+ All bots select an amount of HP to lose (minimum 1, inclusive)
+ Each bot loses the amount of HP they returned
+ All bots with 0 HP or less are eliminated
+ The bot with the highest HP is eliminated
+ If there is a tie for highest HP, all bots that tied are eliminated
* The last bot alive wins 1 point
* If all remaining bots are eliminated in the same turn, no points are awarded
* After a number of games (default is 1000), the winner is the bot with the most points
### Bot Format
Each bot should be a JavaScript function, which is run once per turn. This function will be provided three arguments:
* The bot's HP
* The HP of all other bots as of the last turn, or 0 if dead
+ Formatted as an array, will be randomly shuffled for each game
* An object which can be used for storage between turns
The return value of this function should be a number (minimum 1, inclusive), representing the amount of HP to take. If the return value is not a number or is less than 1, it defaults to 1.
### Example Bot
Example Bot tries to keep its HP 2 below the previous turn's average.
```
function(hp, others, storage) {
var alive = others.filter(bot => bot > 0);
var avg = alive.reduce((a, b) => a + b, 0) / alive.length;
return hp - (avg - 2);
}
```
### Controller
```
//Bots go in this object:
const bots = {
"Example Bot": function(hp, others, storage) {
var alive = others.filter(bot => bot > 0);
var avg = alive.reduce((a, b) => a + b, 0) / alive.length;
return hp - (avg - 2);
}
};
//games: Number of games to run
//log: An array of bot names to log info about, or empty array for game overviews
function runGames(games = 1000, log = null) {
let p = performance.now();
let botData = [];
for (let bot in bots)
botData.push({
name: bot,
run: bots[bot],
uid: 0,
hp: 0,
points: 0,
storage: {},
});
for (let g = 0; g < games; g++) {
let uids = new Array(botData.length).fill(0).map((a, b) => b);
let turn = 0;
if (log)
console.log("[0] Starting game " + (g + 1));
for (let j, i = uids.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
[uids[i], uids[j]] = [uids[j], uids[i]];
}
for (let i = 0; i < botData.length; i++) {
botData[i].uid = uids[i];
botData[i].hp = 100;
botData[i].storage = {};
}
do {
let hps = [];
let max, alive;
turn++;
for (let hp, b, i = 0; i < botData.length; i++) {
b = botData[i];
if (!b.hp)
continue;
try {
hp = Number(b.run(
b.hp,
botData.map(a => [a.uid, a.hp]).sort((a, b) => a[0] - b[0]).filter(a => a[0] != b.uid).map(a => a[1]),
b.storage
));
if (log && log.includes(b.name))
console.log("[" + turn + "] " + b.name + " (" + b.hp + "): " + hp);
} catch(e) {
hp = 100;
if (log && log.includes(b.name))
console.warn(b.name + " (" + JSON.stringify(b.storage) + "):\n" + (e.stack || e.message));
}
hps[i] = Number.isNaN(hp) ? 1 : Math.max(1, hp);
}
for (let i = 0; i < botData.length; i++) {
if (hps[i]) {
botData[i].hp = Math.max(0, botData[i].hp - hps[i]);
if (!botData[i].hp && log)
console.log("[" + turn + "] Eliminated: " + botData[i].name + " (0)");
}
}
alive = botData.filter(a => a.hp);
if (alive.length == 1)
alive[0].points += 1;
if (alive.length <= 1)
break;
max = Math.max(...botData.map(a => a.hp));
for (let i = 0; i < botData.length; i++) {
if (botData[i].hp == max) {
if (log)
console.log("[" + turn + "] Eliminated: " + botData[i].name + " (" + botData[i].hp + ")");
botData[i].hp = 0;
}
}
alive = botData.filter(a => a.hp);
if (alive.length == 1)
alive[0].points += 1;
if (alive.length <= 1)
break;
} while (1);
}
console.log(games + " game(s) completed (" + ((performance.now() - p) / 1000).toFixed(3) + "s):\n" + botData.map(a => [a.name, a.points]).sort((a, b) => b[1] - a[1]).map(a => a[0] + ": " + a[1]).join("\n"));
}
```
### Rules
* Accessing the controller or other bots is not allowed
* There's no time limit, but keep within reason
* Any bots that error are eliminated
* Clarification: Fractional HP is allowed
* Deadline: ~~Wednesday, March 25, 12:00 UTC (8:00 EDT)~~ **Closed to submissions!**
[Answer]
# Low Profile
```
function(hp, others, storage) {
var alive = others.filter(bot => bot > 0);
return hp - alive.length
}
```
Sets its health to be always equal to the number of bots. Any bot that undercuts this one risks eventually hitting zero health.
[Answer]
# Jack
Assumes that half of the bots are stupid. So they will kill theirselves or will end up being killed simultaneously with another bot. We just need to make sure to have enough HP to survive it for enough rounds knowing that.
```
function(hp, others, storage) {
var nrOfBots = others.filter(bot => bot > 0).length;
var hpToTake = 1;
if (hp == 100) {
hpToTake = hp - (Math.round(nrOfBots / 2) + 0.0001);
}
return hpToTake;
}
```
[Answer]
# The Follower
```
function(hp, others, storage) {
if (!storage.prev){
storage.prev = others.slice();
return hp * (Math.random() * 0.1 + 0.8);
}
let [decSum, decCnt] = others.reduce(([s,n],v2,i) => {
if (v2 <= 0) return [s, n];
return [s * (storage.prev[i]-v2), n + 1];
}, [1,0]);
storage.prev = others.slice();
let avg = decSum ** (1 / decCnt);
while (avg > hp) avg /= 2;
return hp - avg;
}
```
Uses the geometric mean of the decrements chosen by alive opponents (in the previous turn) to decide its next move. There is no such information at the first turn, so it cuts a very large part of its own HP to be safe.
[Answer]
# The Bandwagon
```
function(hp, others, storage) {
if (hp > 4)
return 48;
return Math.max(...others) - 1.5;
}
```
It's a bit slow to catch onto the trend, and it's not very low profile about it.
It bases its strategy on the assumption that, after 2 turns, it's the endgame. It assumes all the others are going to return 1, and ensures it doesn't die by returning 1.5.
[Answer]
# LowProfile2
```
function(hp, others, storage) {
var epsilon = 1;
while (hp + 1 - (epsilon / 2) != hp + 1) {
epsilon = epsilon / 2;
}
var alive = others.filter(bot => bot > 0);
return hp - alive.length + 1 - epsilon
}
```
Thanks to the discovery of fractional HP, I realized my old integer-based LowProfile submission could be beaten by one using it. I therefore present LowProfile2, which dynamically calculates the very limits of how close to death one can be!
[Answer]
# Toe Tipping
```
function(hp, others, storage) {
var highestAlive = Math.max(...others);
var returnVal = highestAlive / 2 - 0.1;
return Math.min(returnVal, hp-1);
}
```
Looks for the highest bot alive, and returns 0.1 below halve that bot's HP.
[Answer]
# Lower Profile
```
function(hp, others, storage) {
var alive = others.filter(bot => bot > 0);
return hp - alive.length + 1
}
```
Tries to get lower than, but close to, **Low Profile**. But looks like it can't win by itself. :(
With an ally having `+ 2` instead of `+ 1` (I call it Lowest Profile), snipes Low Profile and this bot wins. [Try it online!](https://tio.run/##xVZbr9o4EH7nV0x5spcQoI@hHKmrrSqtdrsr9ZHmwQGTmIYYOc45rVp@@@mMnUBupxe1Uv0AiWc8883lm/go7kW5M@ps54Xey8fHxeJPbUtINagCbKZK0MlR7mw0mex0UVpISLyBTxPA9Y9@@N/og8plBIeq2FmlC5adA9A2k6YMoLTaiFTyWp/WvTAgcnUv0YpXC9GAlYahadjckQe4gyVfX48YaStTQHaGuT8a5rJIbeYULkEDRZrfCQZmsOoDKu1vRvS8jejVB3E65xIL/H1wfhCKU79PUdmDMHJf7SRjIoCEk7pAQEmA@rDo4PTH21EwsjOH52j5MrmsJ5PFIhUnWUbwpjol0oA@gNsAq8FUBcpznUbwsgBhjPhIcgJXNDooxYY@aBCJruxk0oRPh1@TEvPmNrBaLpeB09/ANm5SkUvX@X8JK9y@h3zQBlgtIr4QN/i1LLV@eK7KjN0KTItwRaQQdLYRjNstt/gTd2WV2kew7O5l58HWWavCloPturIRfLrcBBfeC4NiXq7x74XPLj7OZu3mJCUEQnkq5AO8pFyzJk5fTE49krMlD0/i3Cp@0mpYMuOKTe6uu@qAKHTa2Ongp9mjc2wYnbIpFQym2EwsJdJx/JlG05b9a0DHABQ6IcgNJ@awWuPmHQWq5vN2dLSOqP6vsFl4yLU2zD0aUez1iXH4A5hyHlu@aG3JwVbFgfO0PcYxNUn9XG@qOL4dugyhKp97hbnvJhT3ukVo9RZaDdF6HSK@rZ/SQlq53n5Soe4QGu2XMaB73YNAoLNz2aJDW3ISHwJP8q6Myj6bdfeuOaBZlAQ/mAoXB564xbIeyKm1niWYBD4Q1d1lVVHJ4UFrPo6489xDn34asSRE5rJRNYcOHQdPS@sQiS6CmLIVVFPMHh6LeVhqY9tDdLuMsYkT/OPNOBZXwTPMA53mN3Niu4r5V9w3lR/V6Hd6n6uq2OXVHsdnEtJM4/xJPx0Gb4m9bgIgdWPHZW@A3oH5d8wwvvHIibF0QyQX2Am7y5jkXyvSoOt/PogHYQrWR/z32//eYDKNKlJ1wLEYXj@nLox3hRtZErfF7j18/gwyxBlbksZYbJNhMMTwZj4hwdgqGOblMk6tb3BqlDGd8TGelP6EuULDb2hXNq/x9@CibvtYGIYDPhAP@hn6dXHBZkMgvi@8XiM1l6PGc4eO4aA05LtzP0PXq6Fjp4JkDv23HGao9Q1DL0YNJUaK961ZDg8ZXkWBrWpcvlXaxPSXIOpoemIlRyldGa3c1/07Nq2IBjSuPN7hyEpwAtHVlAZRey7hvKIvt@O3Fx7RApuiJ@5uftfLGV3K@Prx8Qs "JavaScript (Node.js) – Try It Online")
[Answer]
# Average
```
function(hp, others, storage) { return Math.floor(hp/3); }
```
Loses a third of its HP every turn, dying in 13 turns if it doesn't end up as highest. (returning zero gets silently interpreted as returning 1 by the controller)
[Answer]
# The Randomiser
```
function(hp, others, storage) {
var highestAlive = Math.max(...others);
var returnVal = highestAlive * Math.random();
return hp > returnVal ? returnVal
: hp * Math.random();
}
```
Returns a random number \$0\dots hp\$ of the highest bot alive (if we have enough \$hp\$ else a random number \$0\dots hp\$ of our \$hp\$).
[Answer]
## Fair Share
```
function (hp, others, storage) {
return hp / (1 + others.filter(bot => bot > 0).length) | 0;
}
```
The more bots are left, the more of its hp it has to ditch in order to try to keep ahead.
[Answer]
# The Algorithm
```
function(hp, others, storage) {
var rate = (storage.rate || (storage.rate = Math.random() * 0.25 + 0.3));
var alive = others.filter(bot => bot > 0);
var avg = alive.reduce((a, b) => a + b, 0) / alive.length;
return hp > avg * rate ? hp - avg * rate : 1;
}
```
Picks a random value for each game, and will attempt to set its HP to that value multiplied by the current average.
]
|
[Question]
[
Instead of being a skillful warrior capable of slaying [Hydras](https://en.wikipedia.org/wiki/Lernaean_Hydra) (see [here](https://codegolf.stackexchange.com/questions/137980/become-the-hydra-slayer) and [here](https://codegolf.stackexchange.com/questions/138441/return-of-the-hydra-slayer)), this time you are a warrior that has no prior knowledge on how to kill one or which weapons to use against the creature.
In this problem, whenever you cut a single head off, two will grow in the same place. Since you don't have the mechanism to cut many heads off simultaneously, the number of heads will only grow. In this case, our Hydra can start with `N` (N ⩾ 1) heads. Let's call the first encounter a generation and we will represent the heads from the first generation as **0**, the heads created after the first blow as **1**, and so on.
**Input**
You will be given an integer `N` representing how many heads the Hydra initially have and a list of size `N` containing in which index (in the examples I will use 0-indexed format) you will cut a head off. You can always assume the indexes given are valid - remember that the list (i.e.: the heads) will grow as you cut heads off.
**Example**
**Input**: `N = 4` and `[0,4,2,5]`
**Generation 0 - Attack index 0**
```
0 0 0 0 => 1 1 0 0 0
^ ^ ^
```
**Generation 1 - Attack index 4**
```
1 1 0 0 0 => 1 1 0 0 2 2
^ ^ ^
```
**Generation 2 - Attack index 2**
```
1 1 0 0 2 2 => 1 1 3 3 0 2 2
^ ^ ^
```
**Generation 3 - Attack index 5**
```
1 1 3 3 0 2 2 => 1 1 3 3 0 4 4 2
^ ^ ^
```
**Last generation**
```
1 1 3 3 0 4 4 2
```
As you can see, the indexes given are related to the list of the previous generation.
**Output**
You are required to output the last generation.
**Test cases**
```
N = 1 and [0] => [1,1]
N = 2 and [0,0] => [2,2,1,0]
N = 2 and [0,1] => [1,2,2,0]
N = 2 and [1,0] => [2,2,1,1]
N = 2 and [1,1] => [0,2,2,1]
N = 4 and [0,4,2,5] => [1,1,3,3,0,4,4,2]
N = 6 and [0,0,0,0,0,0] => [6, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, 0]
N = 6 and [5,6,7,8,9,10] => [0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 6]
N = 10 and [1,7,3,12,9,0,15,2,2,10] => [6, 6, 9, 9, 8, 1, 3, 3, 0, 0, 10, 10, 2, 5, 5, 0, 0, 4, 7, 7]
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest answer in bytes wins!
[Answer]
# [Python 2](https://docs.python.org/2/), 59 bytes
```
H,a=input()
H*=[0]
for i in a:H[i:i+1]=[max(H)+1]*2
print H
```
[Try it online!](https://tio.run/##DcYxDoAgDADAnVd0LMiARBcS9v6BMLAYOwiEYKKvr053/Z1nq16EbIlc@z1RKzIxuayONoCBK5RAiQMva47pKg@S/mu86oPrBBLBzQI6Cz/ewq71Bw "Python 2 – Try It Online")
Very clever -1 thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor).
[Answer]
# [Python 2](https://docs.python.org/2/), 60 bytes
```
n,a=input()
h=[0]*n
for c in a:h[c:c+1]=[max(h)+1]*2
print h
```
[Try it online!](https://tio.run/##DcaxCoAgEADQ3a@4Ue0GE1sEv0QcRIhz6BQxqK@33vT6O6mxXYsxh8r9nlIJCtEkzeJsAwpUhuwpFl@2PYV45UeS@qut6KPyBFrLIUSDDi0e6QM "Python 2 – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~12~~ 11 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
î╓≡╧▄#¥oWä)A
```
[Run and debug it at staxlang.xyz!](https://staxlang.xyz/#p=a29970ac15eecb46fc002d&i=[0]+1%0A[0,0]+2%0A[0,1]+2%0A[1,0]+2%0A[1,1]+2%0A[0,4,2,5]+4%0A[0,0,0,0,0,0]+6%0A[5,6,7,8,9,10]+6%0A[1,7,3,12,9,0,15,2,2,10]+10&a=1&m=2)
Thanks to [recursive](https://codegolf.stackexchange.com/users/527/recursive) for one byte of savings!
### Unpacked (13 bytes) and explanation:
```
z),{i^c\&:fFm
z) Push initial array of zeroes to stack
, Push array of attacks to stack
{ F For each attack, push it and then:
i^c\ Push [x,x], where x is the generation number
& Set the head at the attack index to this new array
:f Flatten
m Print the last generation
```
The challenge explicitly says "you are required to output the last generation," so my guess is [this consensus](https://codegolf.meta.stackexchange.com/a/8507/73884) doesn't hold here. If it does, though, **ten bytes** can be managed by leaving the result on an otherwise-empty stack:
```
z),Fi^c\&:f
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~63~~ 57 bytes
```
foldl(\y(x,n)->take n y++x:x:drop(n+1)y).(0<$)<*>zip[1..]
```
[Try it online!](https://tio.run/##DcJBDoMgEADAr@yhBygrYW2aRqN@RD0QlZZIkagH6ONLm5mXPtbFuWzaIZvNzY4NiUX0vOhOvS7gIQkR61jP@xaYF8QTl0w1F95cu48NPUk55re2HloIu/UnMAM94QNvSCVWqJDuWP6RGnn@Tsbp55GLKYQf "Haskell – Try It Online")
[Answer]
# Oracle SQL, 325 bytes
```
select listagg(ascii(substr(l,level,1)),', ')within group(order by level)
from(select * from t
model dimension by(1 i)measures(l,r)
rules iterate(1e5)until(r[1]is null)
(l[1]=regexp_replace(l[1],'.',chr(:n-length(r[1])+1)||chr(:n-length(r[1])+1),1,ascii(substr(r[1],1,1))+1),r[1]=substr(r[1],2)))
connect by level<=length(l);
```
Test in SQL\*Plus.
```
SQL> set heading off
SQL>
SQL> create table t(l varchar2(4000), r varchar2(4000));
Table created.
SQL>
SQL> var n number;
SQL> exec :n := 10;
PL/SQL procedure successfully completed.
SQL>
SQL> insert into t
2 values(rpad(chr(0),:n,chr(0)), chr(1)||chr(7)||chr(3)||chr(12)||chr(9)||chr(0)||chr(15)||chr(2)||chr(2)||chr(10));
1 row created.
SQL>
SQL> select listagg(ascii(substr(l,level,1)),', ')within group(order by level)
2 from(select * from t
3 model dimension by(1 i)measures(l,r)
4 rules iterate(1e5)until(r[1]is null)
5 (l[1]=regexp_replace(l[1],'.',chr(:n-length(r[1])+1)||chr(:n-length(r[1])+1),1,ascii(substr(r[1],1,1))+1),r[1]=substr(r[1],2)))
6 connect by level<=length(l);
6, 6, 9, 9, 8, 1, 3, 3, 0, 0, 10, 10, 2, 5, 5, 0, 0, 4, 7, 7
```
PS. Works for numbers up to 255.
# Oracle SQL, 214 bytes, generic case
```
select l from t model dimension by(1i)measures(rpad('0',(n-1)*2+1,',0')l,r,n,1k)rules iterate(1e9)until(k[1]=n[1]+1)
(l[1]=regexp_replace(l[1],'\d+',k[1]||','||k[1],1,regexp_substr(r[1],'\d+',1,k[1])+1),k[1]=k[1]+1)
```
Test in SQL\*Plus.
```
SQL> create table t(n,r) as
2 select regexp_count(r,',')+1 n, r from
3 (select cast('1,7,3,12,9,0,15,2,2,10' as varchar2(4000)) r from dual)
4 /
Table created.
SQL> select l from t model dimension by(1i)measures(rpad('0',(n-1)*2+1,',0')l,r,n,1k)rules iterate(1e9)until(k[1]=n[1]+1)
2 (l[1]=regexp_replace(l[1],'\d+',k[1]||','||k[1],1,regexp_substr(r[1],'\d+',1,k[1])+1),k[1]=k[1]+1)
3 /
L
--------------------------------------------------------------------------------
6,6,9,9,8,1,3,3,0,0,10,10,2,5,5,0,0,4,7,7
```
[Answer]
# [Zsh](https://www.zsh.org/), 41 bytes
We ignore N, as [stated by the rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/12442#12442).
```
for i;a+=(0)
for i;a[i]=($[++j] $j)
<<<$a
```
[Try it online!](https://tio.run/##PY5dboMwDMffc4q/VB5AXaAB1nYrvcIuUPUhIqako0lHwlbt8ixB22z52z/L366fv3o9EEaSCoM2dICyzJEHfzD6lAOWnCOJw7mzI/RBro/pJmO/xUmfj2lyWq@vZyTXjDVNk8h5MhGU0LgyZQMq8C8rCK6NogepJ@iLsSPhDWnv/d29FkVrFV3s0OU38jJ3Xrbv9Gh7aS6Ut/ZWfEzkvLbGFWVd7wpFnZwGz8M7PKI8suH@ffLcTj6GcKi3yhUiAOVq8RkTEMFKVgYTeEaFbez9Kdtihz1eIDYQImztUUNUSwmxDetV7P8A "Zsh – Try It Online")
Pretty standard: Make an array of 0s to start, print it to finish.
The `a[i]=(a b)` method of both changing and inserting is new to me, happy I found a use for it.
---
**OR, also 41 bytes**:
```
a[#]=
for i;a[i]=($[++j] $j)
<<<${a/#%/0}
```
This one is less standard. We take advantage of a few neat tricks:
* `${a/#%/0}`: This is replacement, but `#` and `%` tell zsh to anchor the match at the start and end. Since it's empty, we replace all empty elements with 0.
* `a[#]=`: This effectively declares an empty array of size `$#` in Zsh. It's like `char *a[argc]` in C. If we don't do this, we won't get the trailing zeroes we need.
[Try it online!](https://tio.run/##PY5tbsIwDIb/5xSv1E4CsRDSssIGXGEXQPyIGpemKwkj6VZt2tm7BGmz5W8/lr98O322pifcSGn0xtIO2jFPAXxk9KF63HOOPA0ndcxOB9a4G8xOHc3pMMuPi0V3Qt7N2X6/z7@VyB7E6mcabAIVDDqmXUQl/iWD5MZqGkk/wpytuxFeMWtDuPoXIWqn6ez6ZnmhoJY@qPqNxrpV9kzL2l3E@0A@GGe9KNbrjdDUqKEPPH7FE8oTG@9fh8DdEFKIh1qnvZARKLK7nzMJGa1gRTSJJ5SoUu9PWYUNtniGXEHKuLXFGrK8l5BVXC9T/xc "Zsh – Try It Online")
[Answer]
# [Scala](http://www.scala-lang.org/), 104 bytes
```
def^(l:Seq[Int],r:Seq[Int]):Seq[Int]=if(r.size>0)^(l.patch(r(0),Seq.fill(2)(l.max+1),1),r.drop(1))else l
```
[Try it online!](https://tio.run/##bYyxCsIwFEV3vyLje/goSWwRBQVHZ0exUNsUIzGNSYai@O0xg2QS7nDhnnND35kuTde76iPrmZqjskNgB@fYe5EGNbZgtif1PB9tvJAvFUvb6RF8FfRL7TlmunJd7G/ggSNlphq1MSAxD49uXgqkHF8NfnIgEJUJipnkvLbRWGihKDX@HoBTTZIaRFz84QQvoKA1rUhI2hAn0WRJUp6z90npCw "Scala – Try It Online")
Seems to be the longest answer so far. :)
`List.fill(2)(l.max+1)` can be replaced with `List(l.max+1,l.max+1)` but length remains the same.
[Answer]
# JavaScript (ES6), ~~61 59~~ 51 bytes
*Thanks to @Shaggy for pointing out that `n` is always the length of the array, saving 8 bytes in both versions*
Expects the array in 0-indexed format. Ignores `n`.
```
a=>a.map(i=>b.splice(i,1,++g,g),b=a.map(_=>g=0))&&b
```
[Try it online!](https://tio.run/##jZHBjoIwGITv@xQ9GRpH5C8W9FBexJBNQSQYVshifH22VDAsW83S6aXkm@k/vei77vLvqr1trs2p6M@q1yrR/pduvUolmd@1dZUXXgXCel2i5MjU4/enSkoVcL5aZX3eXLumLvy6Kb2zdwxSzpnz227ZkREYsfRjCeEVZiGBQQYNXCi9Qwkj7UDpn6nkQt@mBlOqc9YdBKQDfxYEFloZm52VcFY2rYWVtYkwSFo6fNY3119LiQgx9jiAFp7TUHM9mg1tgrRpkaunGCFIGE/zUNIMLkbz2S0PVvvfgw8J4xY2QE7HJi82Ymn/Aw "JavaScript (Node.js) – Try It Online")
---
# [JavaScript (Node.js)](https://nodejs.org), ~~64~~ 56 bytes
Using `reduce()` and `flat()`:
```
a=>a.reduce((b,i,g)=>b.flat(1,b[i]=[++g,g]),a.map(_=>0))
```
[Try it online!](https://tio.run/##jZHNjoMgHMTv@xQcIZ21gkXbA76IIRu0amxsbfqxr@8iq43r0qYwXEh@M/yHg/k21@LSnG@fp25f9pXqjUpNcCn396KkNEeDmqk0D6rW3ChHnjVaZatVjVozmOBozvRLpSFjfdGdrl1bBm1X04pmoWaMeNd6TTLCQTjRH0sIzzAHCQyyaOhD@SuUY6Q9KH8zlfvQl6nhlOqddQMB6cEfBYFETtZm4yS8lU17YeVsYgySjo4e9c3131IiRoItduALz2mouX6bjVyCdGmxr6cEEbiwnvajpB1cjOazV@6ctn8HHxLGI1yAnK5tXmJFdP8D "JavaScript (Node.js) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 14 bytes
```
rÈhY[°TT] c}Uî
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=cshoWVuwVFRdIGN9Ve4&input=WzAsNCwyLDVd)
[Answer]
# [PHP](https://php.net/), 101 bytes
```
function h($n,$a){$h=array_fill(0,$n,0);foreach($a as$b)array_splice($h,$b,0,$h[$b]=++$x);return $h;}
```
[Try it online!](https://tio.run/##JY3hCsIgFEZfReT@ULoMXUSEjR5kjHDLcQVz4jYoomc3Ib7z63DgS5TK9ZYosZR93BjveeOfKSwPJ0hohazXeMYj6hYvqFCfsK3TapDIeEU2fOCmzHucNr9ERgIigpUfoM7mbN/32YcgFFatpJmX7OxUI8vsCqP8J2sKfnICCGGsJ0A9jEN3OMBLmuy2PUcGZL6l/AA "PHP – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-pal`, 48 bytes
```
@h=($i=0)x@F;splice@h,$_,1,(++$i)x2for@F;$_="@h"
```
[Try it online!](https://tio.run/##NUtLCsIwFNznFEPJoqUR8qKxigSy8hpFpJJAMKF10dMbXxYyDMP8yrImW6sPrpfR6WH399tWUnwuPig5K1L9OMo47OaVV@7k7Dofulq10GgkQazEqnGCgW35H8LijAkXXEFtNOEIMuz4Z3lsOP7m8on5vdVDeaQf "Perl 5 – Try It Online")
Takes array as space-separated list from STDIN. Doesn't input `n`.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 69 bytes
```
\d+
$*_
r`_\G
,0
+`^((,*)_)(_)*(.*,,(?<-3>\d+,)*)\d+
$2$4$.1,$.1
^,+
```
[Try it online!](https://tio.run/##NUtBCgIxELvPOypM27h02rUqiB73E8u2gh724mHx/3W2IENCkkm293f9PNuBp9rmlyfjCm21zBMhkK8LM5wtlot1PDiAH7djumsT1tk@iGY0g0BBCzy1JhBSICpH5dh17FpwQkLG2Bv/y5RxxgVXSIDsPqobIakHkKyjtH8k/AA "Retina 0.8.2 – Try It Online") Link includes test cases. 1-indexed. Takes input as `...list,N`. Does not require the list to be of length `N`. Explanation:
```
\d+
$*_
```
Convert all of the inputs to unary, but using `_`, so that it doesn't get confused with later uses of the digit `1`. (Retina 1 would do this automatically for a 2-byte saving.)
```
r`_\G
,0
```
Replace `N` with an array of `N` zeros, but don't alter the list.
```
+`
```
Process all elements of the list.
```
^((,*)_)(_)*(.*,,(?<-3>\d+,)*)\d+
```
Find the next element of the list and the equivalent position in the array. `$1` = current generation (as a length), `$2` = commas from previous generations, `$3` = current index - 1, `$4` = first `$3` heads.
```
$2$4$.1,$.1
```
Replace the head at the current index with two copies of the current generation in decimal.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 16 bytes
```
u.nXGH,=+Z1ZE*]0
```
[Try it online!](https://tio.run/##K6gsyfj/v1QvL8LdQ8dWO8owylUr1uD/fzOuaAMdOIwFAA "Pyth – Try It Online")
Interestingly, it turns out I can't use `s` to flatten the list as it is actually shorthand for `+F`, which performs `+` on the leftmost two elements of the list until all elements have been processed. This means that the first few elements might simply be summed, depending on where the last replacement occurred.
```
u.nXGH,=+Z1ZE*]0Q Implicit: Q=input 1 (N), E=input 2 (array), Z=0
Trailing Q inferred
]0 [0]
* Q Repeat Q times
u E Reduce E, with current value G and next value H, starting with the above:
=+Z1 Increment Z in-place
, Z Z Pair the updated Z with itself
XGH In G, replace the element with index H with the above
.n Flatten
Implicit print
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
;`ɼṁœP@j‘ɼɗƒ@
```
[Try it online!](https://tio.run/##y0rNyan8/9864eSehzsbj04OcMh61DDj5J6T049Ncvj//3@0kY6ChY6CiY6CoTEQGwAxEJnpKBiDkaFhLAA "Jelly – Try It Online")
Monadic link that takes the 1-indexed list of heads to cut as its argument and returns the final generation.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~94~~ ~~89~~ 85 bytes
```
a=>b=>b.Aggregate(new int[a-(a-=a)].ToList(),(c,d)=>{c.Insert(d,c[d]=++a);return c;})
```
Saved 2 bytes thanks to Andrew Bauhmer
[Try it online!](https://tio.run/##NYyxCsIwFEV3v6Lje/SliNQpJuAiCA4ObiVDfElLlwhJikPpt8dmEO5whnsOJ8FpLrcl8GUOmZo/DYYec8oVtdajKlbp977uOk3RTzZ7CP7b1KcVYIWyaLrXpzqABEwOlV65u4fkYwZHPDij2taijD4vMTQsNyzy8Ix7A0bosQYHsx6ppxOdN0RZfg "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
-IvN>D‚yǝ˜
```
[Try it online!](https://tio.run/##yy9OTMpM/f9f17PMz87lUcOsyuNzT8/5/z/aQEfBREfBSEfBNBYA "05AB1E – Try It Online")
```
- # subtract the input from itself (yields a list of 0s)
Iv # for each number y in the input
N # push the 0-based loop count
> # add 1 to get the generation number
D # duplicate
‚ # wrap the two copies in a list
yǝ # replace the element at index y with that list
˜ # flatten
```
]
|
[Question]
[
### The Task
Write a program or function that, when passed a numerical input `x`, prints or returns the primes beneath the square root of `x`1 that are not factors of `x`.
### Examples
Let `f(x)` be the function called:
```
>>> f(4)
[]
>>> f(5)
[2]
>>> f(20)
[3]
>>> f(60)
[7]
>>> f(100)
[3, 7]
>>> f(10000)
[3, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
```
### Bonus Rules
* You may use any builtins that your language provides.
* Your program must support an `x` input as high as the upper bound defined by your language.
---
1 Using the square root as only primes below the square root can actually be involved within the factors of `x`. Without making this restriction, larger numbers would have a lot of excess printed numbers.
[Answer]
# Jelly, 6 bytes in Jelly's codepage
```
½ÆRḟÆf
```
[Try it online!](https://tio.run/nexus/jelly#@39o7@G2oIc75h9uS/v//7@hARAAAA "Jelly – TIO Nexus")
Explanation:
```
½ÆRḟÆf
ÆR All primes less than or equal to
¬Ω the square root of the input
ḟ but with the following removed:
Æf All prime factors of {the input, by default}
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), ~~10~~ 9 bytes
```
X^ZqGYfX-
```
[Try it online!](http://matl.tryitonline.net/#code=WF5acUdZZlgt&input=MTAwMDA)
### Explanation
```
X^ % Implicit input. Square root
Zq % Array if primes up to that
G % Push input again
Yf % Array of prime factors
X- % Set difference. Implicit display
```
[Answer]
# **MATLAB, ~~57~~ 54 bytes**
```
function h(p);a=primes(p^.5);a(~ismember(a,factor(p)))
```
Pretty straightforward, gets an array of primes up to sqrt(p) then removes any that are also factors of p. Prints the output of the last line by default because the semicolon is left off.
[Answer]
# Pyth, 10 bytes
```
fP_T-S@Q2P
```
A program that takes input of a number and prints a list.
[Test suite](http://pyth.herokuapp.com/?code=fP_T-S%40Q2P&test_suite=1&test_suite_input=5%0A20%0A60%0A100%0A10000&debug=0)
**How it works**
```
fP_T-S@Q2P Program. Input: Q
fP_T-S@Q2PQ Implicit input fill
f Filter
S@Q2 the 1-indexed range up to floor(sqrt(Q))
- PQ with the prime factors of Q removed
P_T by primality
Implicitly print
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~67~~ 62 bytes
```
f=lambda n,k=1,m=1:k*k<n and(m%k*n%k>0)*[k]+f(n,k+1,m*k*k)or[]
```
[Try it online!](https://tio.run/nexus/python3#JYxBCoMwEEX3PcXfBDMxhaRgF9J4EXGRIgGZZpS0Pb8d6If3V493lvTK9blmiOcUfU1xZMcPQZbVVsNODE@B3MxLX6xKvUpOFdrbvJxlbxBsAjt43ILHXYnhfyHQeIHuaJt8bGeGL64TzLuDgbagQSI6fw "Python 3 – TIO Nexus")
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 8 bytes
```
tLDpϹfK
```
[Try it online!](http://05ab1e.tryitonline.net/#code=dExEcMOPwrlmSw&input=MTAwMDA)
**Explanation**
```
tL # range [1 ... sqrt(input)]
DpÏ # keep only primes
¬πfK # remove factors of input
```
[Answer]
# PHP, 76 bytes
```
for($n=1;++$n*$n<$x=$argv[1];){for($i=$n;$n%--$i;);if($i<2&&$x%$n)echo$n,_;}
```
uses [my is\_prime solution](https://stackoverflow.com/a/39743570#39743570) golfed for $n>1
takes input from command line argument. Run with `-r`.
[Answer]
# Mathematica, 46 bytes
```
Select[Prime@Range@PrimePi@Sqrt[a=#],!#∣a&]&
```
Anonymous function. Takes a number as input and returns a list of numbers as output. The Unicode character is U+2223 DIVIDES for `\[Divides]`.
[Answer]
# Ruby, 55 bytes
```
require'prime'
->x{Prime.to_a(x**0.5).select{|n|x%n>0}}
```
A rather lazy answer using the builtin prime enumerator.
[Answer]
# [Wonder](https://github.com/wonderlang/wonder), 14 bytes
```
@(_> > ^#0.5)P
```
Usage:
```
(@(_> > ^#0.5)P)10
```
Takes items from an infinite list of primes while the item is less than the square root of the argument.
[Answer]
## Pyke, 10 bytes
```
,BS#_P)QP-
```
[Try it here!](http://pyke.catbus.co.uk/?code=%2CBS%23_P%29QP-&input=100)
```
,B - int(sqrt(input))
S - range(1, ^+1)
#_P) - filter(^, is_prime)
- - ^.remove(V)
QP - factors(input)
```
[Answer]
## PowerShell v2+, 71 bytes
```
param($n)1..[math]::Sqrt($n)|?{$n%$_-and'1'*$_-match'^(?!(..+)\1+$)..'}
```
Iterative solution. Takes input `$n` and creates a range from `1` to the `Sqrt($n)` (note that the range operator will implicitly cast the upper end to an `[int]` which will do Banker's Rounding by default). Then uses `|?{...}` (the `Where-Object` operator, which acts like a filter) to pull out those numbers where `$n%$_` is non-zero (i.e., any remainder to the modulo means it's not a factor, and any non-zero is truthy) `-and` the [usual regex prime test](https://codegolf.stackexchange.com/a/57636/42963) is `$true`. Those are left on the pipeline, and output is implicit.
### Examples
(with some extra formatting to pretty up the output)
```
PS C:\Tools\Scripts\golfing> 5,20,60,100,10000|%{"f($_)";(.\print-the-missing-primes.ps1 $_)-join', ';""}
f(5)
2
f(20)
3
f(60)
7
f(100)
3, 7
f(10000)
3, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
```
---
NB - This will fail on earlier versions if the input is bigger than around `2500000000`, because the `..` range operator can only support up to 50,000 items. But, since that is bigger than the default `[int]` datatype's max value, `2147483647`, I'm presuming that to be OK. On my machine, PSv4 Win8.1, however, I can go higher, but I'm not able to find documentation explaining the difference.
[Answer]
# JavaScript (ES6), ~~79~~ 76 bytes
```
f=(q,n=2,x=n)=>n*n<q?[...--x<2&&q%n?[n]:[],...x>1&&n%x?f(q,n,x):f(q,n+1)]:[]
```
Based on my [recursive primality test function](https://codegolf.stackexchange.com/a/100193/42545). I feel like there should be a few ways to simplify this, but I can't figure out how...
### Test snippet
```
f=(q,n=2,x=n)=>n*n<q?[...--x<2&&q%n?[n]:[],...x>1&&n%x?f(q,n,x):f(q,n+1)]:[]
```
```
<input type="number" step=1 min=4 value=4 oninput="O.innerHTML='['+f(this.value)+']'"><br>
<pre id=O>[]</pre>
```
[Answer]
# Octave, 44 bytes
This answer is inspired by MattWH's [MATLAB answer](https://codegolf.stackexchange.com/a/102638/31516), but I've golfed it using some Octave-specific features.
```
@(x)(y=primes(x^.5))(~ismember(y,factor(x)))
```
This is an anonymous function that takes the input `x`. Octave has inline variable assignment and indexing allowing `y` to first be created in the function (not possible in MATLAB), then used as part of the logical mask created by `ismember` (again, not possible to do it this way in MATLAB).
[Answer]
# [Perl 6](https://perl6.org), 37 bytes
```
{grep {$^a.is-prime&$_%$a},2.. .sqrt}
```
## Expanded:
```
{ # bare block lambda with implicit parameter ÔΩ¢$_ÔΩ£
grep
{
$^a.is-prime # check if it is prime
& # and junction
$_ % $a # check if the input is not evenly divisible by it
},
2.. .sqrt # Range of values up-to and including squareroot
}
```
[Answer]
# TSQL, 130 bytes
```
DECLARE @v int=10000
,@ INT=2SELECT 2p INTO #
g:INSERT # SELECT @ FROM # HAVING isnull(min(@%p),1)>0SET @+=1IF @*@<@v GOTO g
SELECT*FROM # WHERE @v%p>0
```
This will only execute once, then you need to drop the temp table to execute again in the same editor
```
DROP TABLE #
```
I made a version to test it, it is a bit longer because the online permissions for creating tables is unavailable. For the same reason it doesn't need the drop table though.
**[Try it online](https://data.stackexchange.com/stackoverflow/query/593249/print-the-missing-primes)**
[Answer]
# R, ~~58~~ 63 bytes
```
for(i in 2:sqrt(x<-scan()))if(x%%i&numbers::isPrime(i))print(i)
```
Loops over all values from 2 to `sqrt(x)` and checks if they are prime with the `numbers` package. `x%%i` calculates `x mod i` which is `0 -> False` if `i` is a divisor of `x` and `>0 -> True` if `i` is not.
+5 bytes because the `numbers::Primes(n)` function doesn't allow decimals, while `2:sqrt(x)` does work, added prime check to `if` statement.
[Answer]
## [Retina](https://github.com/m-ender/retina), ~~69~~ 66 bytes
```
.+
$*
(11\1|^1)+
$#1$*1:$&
M!&`(?!(11+)\1+:)(1+):(?!\2+$)
M%`1
^0
```
Prints the primes on separate lines, from largest to smallest.
[Try it online!](https://tio.run/nexus/retina#HYnLDYAgFATv2wURDYgxb/Fz4OLREx0QQyHWZQE2hi8eJtnZ6d1Z2xxgRziy8L7o1TrakckOyGao7jDagi8MyTsdSZ8Sg/XIfSUuQXsfTC1iwYoNUbALKD@iKvIB "Retina – TIO Nexus") (Takes about 10 seconds due to the last two test cases. The header and footer enable a linefeed-separate test suite, and convert the output to comma-separation for readability.)
### Explanation
```
.+
$*
```
Convert the input to unary.
```
(11\1|^1)+
$#1$*1:$&
```
This prepends the square root of the input, separated by `:`. The square root is computed based on the fact that the square of `n` is also the sum of the first `n` odd integers. We can match consecutive odd integers with the forward reference `(11\1|^1)`. In the process the group will be used exactly `n` times, where `n` is the largest number whose square fits into the input.
We insert a unary representation of this number with `$#1$*1`, followed by a colon and the match itself.
```
M!&`(?!(11+)\1+:)(1+):(?!\2+$)
```
This matches all the missing primes that fit into the square root. The prime detection is based [on the standard prime checking regex](https://codegolf.stackexchange.com/a/57618/8478), and then we simply make sure that the prime we've just captured does not divide the input with the second lookahead. By using the `&` option, we get overlapping matches to ensure that we get all primes.
```
M%`1
```
This converts each line (i.e. each missing prime) back to decimal by matching the number of `1`s. The only issue is that this inserts a zero if no missing primes were found at all.
```
^0
```
So this stage removes that zero if it was added.
[Answer]
## Haskell, ~~55~~ 54 bytes
```
f x=[y|y<-[2..x],y*y<x,[z|z<-[1..y],gcd(z*x)y>1]==[y]]
```
Mostly straightforward nested list comprehensions. GCD performs two roles, testing whether the numbers below y are factors of y and also testing whether y is a factor of x.
Spaced out a little:
```
f x = [ y|y<-[2..x], y*y<x, [z|z<-[1..y], gcd (z*x) y > 1] == [y] ]
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes
```
‚àö~√¶?KF
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJBIiwiIiwi4oiafsOmP0tGIiwiIiwiNFxuNVxuMjBcbjYwXG4xMDBcbjEwMDBcbjEwMDAwIl0=)
It's nice to have a massive toolbox again
## Explained
```
√~æ?KF­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌­
√~æ # ‎⁡Keep only primes from the range [1, sqrt(input)]
F # ‎⁢With items from
?K # ‎⁣Factors of the input
F # ‎⁤Removed
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [Uiua](https://uiua.org), 46 bytes
```
▽∵(=2/+⌕0◿+1⇡.).▽¬≡/+⊞=↷.⊃(+1⇡⌊√)(▽=0◿↷.+1⇡.).
```
[Try it Online](https://uiua.org/pad?src=ZiDihpAg4pa94oi1KD0yLyvijJUw4pe_KzHih6EuKS7ilr3CrOKJoS8r4oqePeKGty7iioMoKzHih6HijIriiJopKOKWvT0w4pe_4oa3Lisx4oehLikuCmYgNApmIDUKZiAyMApmIDYwCmYgMTAwCmYgMTAwMDA=)
## Explained
```
▽∵(=2/+⌕0◿+1⇡.).▽¬≡/+⊞=↷.⊃(+1⇡⌊√)(▽=0◿↷.+1⇡.).­⁡​‎⁠‎⁡⁠⁢⁣⁢‏⁠‎⁡⁠⁢⁣⁣‏⁠⁠⁠⁠⁠⁠‎⁡⁠⁣⁡⁡‏⁠‎⁡⁠⁣⁡⁢‏⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠‎⁡⁠⁣⁤⁡‏⁠‎⁡⁠⁣⁤⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢⁣⁤‏⁠‎⁡⁠⁢⁤⁡‏⁠‎⁡⁠⁢⁤⁢‏⁠‎⁡⁠⁢⁤⁣‏⁠‎⁡⁠⁢⁤⁤‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣⁡⁣‏⁠‎⁡⁠⁣⁡⁤‏⁠‎⁡⁠⁣⁢⁡‏⁠‎⁡⁠⁣⁢⁢‏⁠‎⁡⁠⁣⁢⁣‏⁠‎⁡⁠⁣⁢⁤‏⁠‎⁡⁠⁣⁣⁡‏⁠‎⁡⁠⁣⁣⁢‏⁠‎⁡⁠⁣⁣⁣‏⁠‎⁡⁠⁣⁣⁤‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁣⁣⁡‏⁠‎⁡⁠⁣⁣⁢‏⁠‎⁡⁠⁣⁣⁣‏⁠‎⁡⁠⁣⁣⁤‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁣⁢⁣‏⁠‎⁡⁠⁣⁢⁤‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁣⁡⁤‏⁠‎⁡⁠⁣⁢⁡‏⁠‎⁡⁠⁣⁢⁢‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁣⁡⁣‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏⁠‎⁡⁠⁢⁡⁤‏⁠‎⁡⁠⁢⁢⁡‏⁠‎⁡⁠⁢⁢⁢‏⁠‎⁡⁠⁢⁢⁣‏⁠‎⁡⁠⁢⁢⁤‏⁠‎⁡⁠⁢⁣⁡‏‏​⁡⁠⁡‌⁣⁡​‎‎⁡⁠⁢⁢⁢‏⁠‎⁡⁠⁢⁢⁣‏‏​⁡⁠⁡‌⁣⁢​‎‎⁡⁠⁢⁡⁣‏⁠‎⁡⁠⁢⁡⁤‏⁠‎⁡⁠⁢⁢⁡‏‏​⁡⁠⁡‌⁣⁣​‎‎⁡⁠⁢⁡⁢‏‏​⁡⁠⁡‌⁣⁤​‎‏​⁢⁠⁡‌⁤⁡​‎‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏‏​⁡⁠⁡‌­
⊃( )( ). # ‎⁡To the input, apply:
+1⇡⌊√ # ‎⁢ Range [1, sqrt(input)]
▽=0◿↷.+1⇡. # ‎⁣ All factors of the input by:
+1⇡. # ‎⁤ Creating a range [1, input]
↷. # ‎⁢⁡ Rolling a copy to the bottom of the stack
=0◿ # ‎⁢⁢ Pushing whether each number in that range divides the input
▽ # ‎⁢⁣ And keeping only numbers that do
▽¬≡/+⊞=↷. # ‎⁢⁤ Filter out divisors from the sqrt range by:
⊞= # ‎⁣⁡ Table via equality
≡/+ # ‎⁣⁢ Sum of row
¬ # ‎⁣⁣ != 0
# ‎⁣⁤Essentially, keep only numbers where the number of occurrences in the divisor list is 0
∵(=2/+⌕0◿+1⇡.). # ‎⁤⁡Push a mask of whether each number is prime (using the method in my "is a number prime" Uiua answer)
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
]
|
[Question]
[
A metaquine is a program which is not a quine, but whose output, when run as a program in the same language, is a quine.
The goal of this challenge is to write a metaquine. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins, with earliest answer used as a tiebreaker. Note that only full programs are acceptable, due to the definition of a quine.
### Rules for Quines
Only *true* quines are accepted. That is, you need to print the entire source code verbatim to STDOUT, **without**:
* reading your source code, directly or indirectly.
* relying on a REPL environment which just simply evaluates and prints every expression you feed it.
* relying on language features which just print out the source in certain cases.
* using error messages or STDERR to write all or part of the quine. (You may write things to STDERR or produce warnings/non-fatal errors as long as STDOUT is a valid quine and the error messages are not part of it.)
* the source code consisting purely of literals (whether they be string literals, numeric literals, etc.) and/or NOPs.
Any non-suppressible output (such as copyright notices, startup/shutdown messages, or a trailing line feed) may be ignored in the output for the sake of the validity of the quine.
## Example
Ignoring the rule which forbids literal-only programs and built-in quining, this would be a metaquine in Seriously:
```
"Q"
```
The program consists of the single string literal `"Q"`, which is implicitly printed at output. When the output (`Q`) is run, it is a quine (`Q` is the built-in quine function).
[Answer]
## CJam, 6 bytes
```
"_p"_p
```
Prints
```
"_p"
_p
```
which is the shortest proper quine in CJam.
[Test it here.](http://cjam.aditsu.net/#code=%22_p%22_p)
### Explanation
Both programs work exactly the same, since the linefeed inside the proper quine is a no-op and only included because it's more expensive to remove it from the output. How the programs work:
```
"_p" e# Push this string.
_ e# Duplicate it.
p e# Print a string representation of the top of the stack (i.e. the string with
e# quotes) followed by a linefeed.
e# The other copy is then printed automatically at the end of the program, without
e# stringifying it.
```
### Side Note
The same works in GolfScript as
```
".p".p
```
which prints
```
".p"
.p
```
with a trailing linefeed, which in turn is one of the shortest known quines.
[Answer]
# Pyth, ~~12~~ ~~11~~ ~~10~~ 9 bytes
Knocked off one more byte thanks to @Pietu1998.
```
jN B".[9N
```
This prints
```
.[9N".[9N
```
which is a quine in Pyth. You can try it out [here](https://pyth.herokuapp.com/?code=jN%20B%22.%5B9N&debug=0).
[Answer]
## [Fission](https://github.com/C0deH4cker/Fission), 6 bytes
```
!+OR"'
```
Prints
```
'!+OR"
```
Which [is the shortest Fission quine](https://codegolf.stackexchange.com/a/50968/8478). This works because cyclic shifts of the program leave its output completely unaffected.
[Try it online!](http://fission2.tryitonline.net/#code=IStPUiIn&input=)
[Answer]
# Javascript ES6, 21 bytes
```
$=_=>`$=${$};$()`
$()
```
Trivial.
[Answer]
## Python 2, 29 bytes
```
_="_=%r;print _%%_";print _%_
```
Turns out the well-known short python quine is easily turned into a metaquine :)
And, since we don't have to worry about matching the trailing newline, the metaquine is actually shorter!
[Answer]
# Japt, ~~15~~ 13 bytes
```
Q+"+Q ³s7J" ²
```
[Test it online!](http://ethproductions.github.io/japt?v=master&code=USsiK1Egs3M3SiIgsg==&input=)
This program outputs
```
"+Q ³s7J"+Q ³s7J
```
which is the shortest known quine in Japt.
### How it works
```
Q+"..." // Take a quotation mark plus this string. "+Q ³s7J
² // Repeat it twice. "+Q ³s7J"+Q ³s7J
// Implicit output
```
### 11 bytes
```
Q+"+Q ²é" ²
```
I've [just added](https://github.com/ETHproductions/Japt/commit/93b9c203780554e4c1f664abb1736c859d0fe359) `é`, a "rotate" command. So
```
"+Q ²é"+Q ²é
```
is now a valid quine.
[Answer]
# Ruby, ~~25~~ 23
```
puts"puts <<2*2,2
"*2,2
```
Generates the classic Ruby HEREdoc quine
```
puts <<2*2,2
puts <<2*2,2
2
```
# Old solution
```
_='_=%p;$><<_%%_';$><<_%_
```
Generates itself except with the single quotes replaced with double quotes.
[Answer]
# JavaScript, 50 bytes
```
a="a=%s;console.log(a,uneval(a))";eval(a.slice(5))
```
Based on [the shortest non-source-reading JS quine known to man](https://codegolf.stackexchange.com/a/92449/42545), but a good 8 bytes shorter. Prints
```
a="a=%s;console.log(a,uneval(a))";console.log(a,uneval(a))
```
which is a quine.
[Answer]
# Fish (><>), 17 bytes
This works using the classic fish quine `"r00g!;oooooooo|` but adds a `{` which shifts the entire stack to the left so that the original program isn't a quine, but it's output, when run, is.
```
"{r00g!;oooooooo|
```
Outputs:
```
"r00g!;oooooooo|
```
which is a fish quine!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) (non-competing)
Unfortunately, the required atoms are roughly 2 weeks younger than the challenge.
## Metaquine
```
”Ṙv
```
[Try it online!](http://jelly.tryitonline.net/#code=4oCd4bmYdg&input=)
### How it works
```
”Ṙv Main link. No arguments.
”Ṙ Set the left argument and the return value to the character 'Ṙ'.
v Dyadic eval; evaluate the return value with the left argument as argument.
Executing the atom Ṙ on the argument 'Ṙ' prints a string representation of
the character, i.e., the string "”Ṙ".
Finally, v returns its unaltered argument, which is printed implicitly.
```
## Quine
```
”ṘṘ
```
[Try it online!](http://jelly.tryitonline.net/#code=4oCd4bmY4bmY&input=)
### How it works
```
”ṘṘ Main link. No arguments.
”Ṙ Set the left argument and the return value to the character 'Ṙ'.
Ṙ Print a string representation of the character, i.e., the string "”Ṙ".
(implicit) Print the unaltered return value.
```
Since the second `Ṙ` prints the first two characters (`”Ṙ`), this is a proper quine by our definition.
[Answer]
# Octopen-Baru, 22 bytes
\*\* Non competing answer
```
愛[35211].pack歩U')
```
### Ruby output
```
puts [35211].pack(' U')
```
Which outputs `見`. Which is a quine in Octopen-Baru!
[Answer]
# [7](https://esolangs.org/wiki/7), 2 bytes, language postdates challenge
The program is two bytes long, and can be interpreted in several ways; as a hex dump:
```
00000000: 4ff4 O.
```
as codepage 437:
```
O⌠
```
or, most readably, in octal (which 7 natively uses):
```
237723
```
[Try it online!](https://tio.run/nexus/7#@29kbG5uZPz/PwA "7 – TIO Nexus")
The workings of this are very simple: it's the standard [7 quine](https://codegolf.stackexchange.com/a/102069/62131) with a no-op stack element inserted between the two halves, to make it different (in this context, `7` separates stack elements). (I could also have inserted it at the start, `723723`. I couldn't have interpreted it at the end because trailing 7s are like trailing whitespace, and ignored in the packed encoding, thus it wouldn't be any different from the output program.)
Incidentally, this program is a [palindrome](/questions/tagged/palindrome "show questions tagged 'palindrome'") in hexadecimal, but that's mostly just coincidence.
[Answer]
# Underload, 11 bytes
```
(:aSS)::aSS
```
Pretty simple. It prints out `(:aSS):aSS`, which is the standard Underload quine.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 12 bytes
```
"~k;?w₁"gjw₃
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/X6ku29q@/FFTo1J6FpBq/v8fAA "Brachylog – Try It Online")
One of 132 same-length metaquine variations on [the quine I translated](https://codegolf.stackexchange.com/a/183203/85334) from [Fatalize's Brachylog v1](https://codegolf.stackexchange.com/a/68883/85334) (non-cheating) quine. I actually wrote a (non-golfed, and overall silly) program to print all of them out:
```
{[[";?","gj","jḍ"],"₁₃₅₇"]j∋ᵐ{ḍ≠&};"\"~~k~ww~w\"~ww~w~n"}ᶠ{lw" metaquines generated:
"ẉ&}w₁ᵐ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/vzo6WsnaXklHKT0LSGQ93NGrFKuj9Kip8VFT86Om1kdN7UqxWY86uh9unVANlHzUuUCt1lopRqmuLruuvLyuHMgCUXV5SrUPty2ozilXUshNLUksLM3MSy1WSE/NSy1KLElNseJSerirU622HGgy0Kj//wE "Brachylog – Try It Online")
There are two parts of the original quine which could be replaced inconsequentially: `;?` can be changed to `gj` or `jḍ`, and `₁` can be changed to `₃`, `₅`, or `₇`. If we keep or change them outside the string literal in one way and inside the string literal in a different way, then the output won't match the source, because whichever variants were present within the string literal will be printed both inside and outside it, resulting in a quine which was not the initial program run.
`;?`, `gj`, and `jḍ` are interchangeable because all three pair the string literal with itself: due to the layout of the program, the input variable `?` is unified with the string, so `;?` pairs the string with itself; regardless of the layout, `gj` wraps the string in a list which is then concatenated to itself; likewise `jḍ` concatenates the string to itself then splits it in half.
The odd-numbered `w` subscripts are interchangeable because, although originally `w` could only take 0 or 1, with 0 printing the input to `w` and 1 printing the first element formatted with the second, the subscript inventory for `w` has grown into something that externally functions as a bitfield: the low bit of the subscript encodes whether it's direct or formatted, the middle bit encodes whether the output variable from `w` is unconstrained or set to the input, and the high bit encodes whether the printing is done immediately or if it's delayed until the end of the program so it can be subject to backtracking. (Those subscripts were my first and so far largest contribution to Brachylog.) Since the quine and metaquine don't use the output variable and don't backtrack, all four odd subscripts are equivalent.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 3 bytes
```
\II
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJcXElJIiwiIiwiIl0=)
which prints :
```
`I`I
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJgSWBJIiwiIiwiIl0=)
which is a quine
## Explanation :
```
I # quote and prepend
\I # the char `I`
# Implicit output => `I`I
I # quote and prepend
`I` # a string containing `I`
# implicit output => `I`I
```
[Answer]
# Befunge-93, 22 bytes
```
"+1_@#`+39:,g0:">:#,_@
```
I just took the standard quine, put it in quotes, reversed it (so it is loaded on the stack correctly), and then added a stack-print at the end.
It's 8 characters added to the normal quine, so it's very possible there's a better solution.
[Answer]
# [Turtlèd](https://github.com/Destructible-Watermelon/turtl-d/), 52 bytes (noncompeting)
1 less than original quine
```
@##'@r,r,r-{ +.r_}r{ +.r_}"#'@r,r,r-{ +.r_}r{ +.r_}"
```
Works in the same way, except that it does not have a character at the end, when run, it will have a character at the end, that does not effect output, because it writes # on to a #. Note the output is slightly different to the quine I have made for the quine challenge, but works the same: " writes #, which is its own last character, like the quine I made. [Check out the explanation there](https://codegolf.stackexchange.com/a/97043/55896).
[Answer]
## Lua, 45 bytes
[Quine code not mine.](https://codegolf.stackexchange.com/a/47143/62824)
```
s="s=%qprint(s:format(s))"print(s:format(s));
```
will result in
```
s="s=%qprint(s:format(s))"print(s:format(s))
```
which is a quine. Glad the `;` is **optional** in Lua.
[Answer]
# [Pushy](https://github.com/FTcode/Pushy), 7 bytes
Non-competing as the language postdates the challenge.
This is the standard quine, but with newlines removed. Newlines mean nothing in Pushy, but are the print operator's standard separator, and therefore needed for a true quine.
```
95 34_"
```
[**Try it online!**](https://tio.run/nexus/pushy#@29pqmBsEq/0/z8A) This outputs:
```
95 34
_"
```
Which is the shortest Pushy quine - an explanation on how it works can be found [here](https://codegolf.stackexchange.com/questions/69/golf-you-a-quine-for-great-good/100204#100204).
Alternatively, `H5-34_"` works for the same byte count.
[Answer]
## [Foam](https://github.com/ScratchMan544/foam-lang), 14 bytes
```
[. .'|: ~|]: ~
```
This prints the second Foam quine that can be found [here](https://codegolf.stackexchange.com/a/131530/61384). This is actually shorter because `.` will always put a space between each element, but the bar in the third token allows me to omit the space before it.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 6 bytes
```
D"S+s¨
```
[Try it online!](https://tio.run/##yygtzv7/30UpWLv40Ir//wE "Husk – Try It Online")
Prints the standard Husk quine [`S+s"S+s"`](https://codegolf.stackexchange.com/a/128302/85334).
```
"S+s¨ The string S+s"
D concatenated with itself.
```
The quine explained:
```
"S+s" The string S+s
+ concatenated with
S itself passed through
s the function which returns its string representation.
```
]
|
[Question]
[
Today was [AP exam](https://en.wikipedia.org/wiki/Advanced_Placement_exams) registration day at my school, and while I was meticulously bubbling in the pages and pages of information required, the idea for this challenge hit me. So, given a string of letters and numbers, output an appropriately filled out bubble chart.
# Rules:
* For each character in the input string, replace that character in the corresponding column with a `#` or `@` or any other reasonable symbol (if your language can handle it, the Unicode character 'full\_block': █ looks really good)
* A space is represented by a blank column (see examples)
* Valid input will be a string which is made up of only uppercase letters, numerical digits, and spaces.
* Input will be of a length with a minimum of 1, and a maximum of 32 characters.
* Output must be *UPPERCASE*
* If the input length is less than the maximum length of 32, your program must still output the remaining blank columns
* Your program doesn’t have to handle lowercase input the same as if they were uppercase, but bonus points if it can.
## Board Format:
```
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG
HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII
JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ
KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK
LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP
QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ
RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR
SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS
TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT
UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU
VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ
00000000000000000000000000000000
11111111111111111111111111111111
22222222222222222222222222222222
33333333333333333333333333333333
44444444444444444444444444444444
55555555555555555555555555555555
66666666666666666666666666666666
77777777777777777777777777777777
88888888888888888888888888888888
99999999999999999999999999999999
```
## Examples:
```
CODE GOLF ->
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
█CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
DD█DDDDDDDDDDDDDDDDDDDDDDDDDDDDD
EEE█EEEEEEEEEEEEEEEEEEEEEEEEEEEE
FFFFFFFF█FFFFFFFFFFFFFFFFFFFFFFF
GGGGG█GGGGGGGGGGGGGGGGGGGGGGGGGG
HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII
JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ
KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK
LLLLLLL█LLLLLLLLLLLLLLLLLLLLLLLL
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
O█OOOO█OOOOOOOOOOOOOOOOOOOOOOOOO
PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP
QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ
RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR
SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS
TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT
UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU
VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ
00000000000000000000000000000000
11111111111111111111111111111111
22222222222222222222222222222222
33333333333333333333333333333333
44444444444444444444444444444444
55555555555555555555555555555555
66666666666666666666666666666666
77777777777777777777777777777777
88888888888888888888888888888888
99999999999999999999999999999999
ABCDEFGHIJKLMNOPQRSTUVWXYZ012345 ->
@AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
B@BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
CC@CCCCCCCCCCCCCCCCCCCCCCCCCCCCC
DDD@DDDDDDDDDDDDDDDDDDDDDDDDDDDD
EEEE@EEEEEEEEEEEEEEEEEEEEEEEEEEE
FFFFF@FFFFFFFFFFFFFFFFFFFFFFFFFF
GGGGGG@GGGGGGGGGGGGGGGGGGGGGGGGG
HHHHHHH@HHHHHHHHHHHHHHHHHHHHHHHH
IIIIIIII@IIIIIIIIIIIIIIIIIIIIIII
JJJJJJJJJ@JJJJJJJJJJJJJJJJJJJJJJ
KKKKKKKKKK@KKKKKKKKKKKKKKKKKKKKK
LLLLLLLLLLL@LLLLLLLLLLLLLLLLLLLL
MMMMMMMMMMMM@MMMMMMMMMMMMMMMMMMM
NNNNNNNNNNNNN@NNNNNNNNNNNNNNNNNN
OOOOOOOOOOOOOO@OOOOOOOOOOOOOOOOO
PPPPPPPPPPPPPPP@PPPPPPPPPPPPPPPP
QQQQQQQQQQQQQQQQ@QQQQQQQQQQQQQQQ
RRRRRRRRRRRRRRRRR@RRRRRRRRRRRRRR
SSSSSSSSSSSSSSSSSS@SSSSSSSSSSSSS
TTTTTTTTTTTTTTTTTTT@TTTTTTTTTTTT
UUUUUUUUUUUUUUUUUUUU@UUUUUUUUUUU
VVVVVVVVVVVVVVVVVVVVV@VVVVVVVVVV
WWWWWWWWWWWWWWWWWWWWWW@WWWWWWWWW
XXXXXXXXXXXXXXXXXXXXXXX@XXXXXXXX
YYYYYYYYYYYYYYYYYYYYYYYY@YYYYYYY
ZZZZZZZZZZZZZZZZZZZZZZZZZ@ZZZZZZ
00000000000000000000000000@00000
111111111111111111111111111@1111
2222222222222222222222222222@222
33333333333333333333333333333@33
444444444444444444444444444444@4
5555555555555555555555555555555@
66666666666666666666666666666666
77777777777777777777777777777777
88888888888888888888888888888888
99999999999999999999999999999999
ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ->^^^
```
And of course, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins
[Answer]
# [Husk](https://github.com/barbuz/Husk), 23 bytes
```
mż§?'#|=⁰mR32¤+…"AZ""09
```
[Try it online](https://tio.run/##ATAAz/9odXNr//9txbzCpz8nI3w94oGwbVIzMsKkK@KApiJBWiIiMDn///9DT0RFIEdPTEY "Husk – Try It Online") or [try it](https://tio.run/##ATIAzf9odXNr//9txbzCpz8n4paIfD3igbBtUjMywqQr4oCmIkFaIiIwOf///0NPREUgR09MRg "Husk – Try It Online") with the fancy █ character (but an invalid bytecount)!
Unfortunately I wasn't able to merge the two `map`s into one (except with using parentheses, costing 24 bytes)..
### Explanation
```
mż§?'#|=⁰mR32¤+…"AZ""09" -- expects string as argument, eg. "FOO"
¤ -- with the two strings "AZ" "09" ..
… -- | fill ranges: "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
-- | "0123456789"
+ -- .. and concatenate: "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
m -- map the following (eg. with 'X')
-- | replicate 32 times: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
-- : ["A…A","B…B",…,"Z…Z","0…0",…"9…9"]
m -- map the following (eg. with "F…")
ż ⁰ -- | zipWith (keeping elements of longer list) argument ("FOO")
§? = -- | | if elements are equal
'# -- | | | then use '#'
| -- | | | else use the first character
-- | : ["#FF…F"]
-- : ["A…A",…,"#FF…F",…,"O##O…O",…,"9…9"]
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 62 bytes
```
->s{[*?A..?Z,*?0..?9].map{|c|(0..31).map{|i|c==s[i]??@:c}*''}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1664OlrL3lFPzz5KR8veAEhbxurlJhZU1yTXaAC5xoaaEG5mTbKtbXF0Zqy9vYNVcq2Wunpt7f@C0pJihbRoJWd/F1cFd38fN6XY/wA "Ruby – Try It Online")
Returns array of strings. Could be golfed further by discarding string joins and returning a 2D array of characters as is usually the norm, but I'm not sure if it is allowed here.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~132~~ 126 bytes
```
char*s="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",*_,*a;f(char*x){for(_=s;*_;++_,puts(""))for(a=s;*a;)putchar(x[a++-s]-*_?*_:64);}
```
[Try it online!](https://tio.run/##fctHC8IwAIbhe39FiJckbcVRZxy4t3VPJIRoNaBVmgqC@Nur9eTJ9/jwfcI8ChFEpCvO9/0BFJTvSfcYPZW0X9vLa0iBOHGPqCKsVGv1RrPV7nR7/cHQHo0n09l8sVytN7F4Imml0plsDhqEGYRTB31fD/x0rh5iRUUJo7rOjNvdVwhCjEPnoXOKPxjO0WPLdd1UO5OwMmH5tIXpK5CuDy5cugg/NfDJQbBm1xugZfeb4F8QU@0VvAE "C (gcc) – Try It Online")
Thanks to Jonathan Frech for saving 6 bytes.
[Answer]
# [Red](http://www.red-lang.org), 177 bytes
```
func[s][m: copy[]foreach c a:"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[insert/dup r: copy"^/"c 32 append m r]j: 0
foreach c s[j: j + 1 if c <>#" "[m/(index? find a c)/(j): #"@"]]m]
```
[Try it online!](https://tio.run/##hY5LT8JAHMTv/RSTPxeIh/JScEMU5SUIlocKuFmSZh@xTbpstpDop69NiPHoaWZ@k0zGa1WsteIiMKwwZyt5LnjGII/umwtz9DqWn5CIGT08Doaj8eRpOnueL16i5Wq9eX173@72H/VGs9W@vul0b4knNtf@FKqzg7/M0CEkiVYTsXPaKmTwImWoB3/rOS9Biis0kJgy9@4qBOJZWE2s0l/3MKUihqyF1bTGUKE@CZGJwvnEnmBAg2g4wiSajym4MPo1Zfnfcyp@AA "Red – Try It Online")
More readable:
```
f: func[s][
m: copy[]
a:"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
foreach c a[
insert/dup r: copy "^/" c 32
append m r
]
j: 0
foreach c s[
j: j + 1
if c <>#" "[m/(index? find a c)/(j): #"@"]
]
m
]
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes
```
E⁺α⭆…αχκ⭆…◨θφ³²⎇⁼ιλ#ι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sUAjIKe0WCNRRyG4BCiUDhLxzc9JAYkYGmjqKGRramLIBSSmBGWmZ5RoFIIUGYCUGRsBiZDUorzEokoN18LSxJxijUwdhRygqJKyko5CpiYQWP//7@zv4qrg7u/jxvVftywHAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
α α Uppercase alphabet predefined variable
χ Predefined variable 10
… Chop to length
⭆ Map over characters and join
κ Current index
⁺ Concatenate
E Map over characters into array
θ Input string
φ Predefined variable 1000
◨ Right pad to length
³² Literal 32
… Chop to length
⭆ Map over characters and join
ι ι Current outer character
λ Current inner character
⁼ Equals
# Literal `#`
⎇ Ternary
Implicitly print each result on its own line
```
Previous version with input validation, ~~34~~ 32 bytes. Edit: saved 2 bytes thanks to @ASCII-only.
```
≔⁺α⭆…αχκαEα⭆…◨Φθ∨⁼ι №αιφ³²⎇⁼ιλ#ι
```
[Try it online!](https://tio.run/##ZY29DoIwFIV3nqKpy21SE9CRySi4SCDqC9wAgcYbkLaY@PT1Ni4mLmc4P99pR7TtjBTCwTkzTNDQ6gC1uHlrpqHCJ1QzddHJUqXFQ7GgypOGYw8x/y832F3NMHooDfnewqJFbaFYViQHRgspJFOO88oEXhsVoVmaxoP9juXe2wnt@2dC7MqN/JZVHsKxPhXiXF/KJGxf9AE "Charcoal – Try It Online") Link is to verbose version of code.
[Answer]
# [R](https://www.r-project.org/), 104 bytes
```
function(S,o=""){for(i in 1:32)o=paste0(o,`[<-`(x<-c(LETTERS,1:9),x==substr(S,i,i),"@"))
cat(o,sep="
")}
```
[Try it online!](https://tio.run/##DcwxCsMgFADQPaeQP/nhC007NSgEWtslEGiydUkqEVw0qIFA6dltDvBeLJZJUezmTXbB84GCAsCvDZE75jyrm8sZg1rnlJcTDzS9pZj4LoXhnR5H/Rqobq5Iu1Jp@6Qcj8KRQ4IWECsz5wOlZVVQAf6K5XDr75o9@@4BWP4 "R – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ 17 bytes
```
ØA;ØDWẋ32ɓ,€⁶y"ZY
```
Uses a space character. To use a `#` replace `⁶` with `”#` for a cost of one byte.
**[Try it online!](https://tio.run/##AS0A0v9qZWxsef//w5hBO8OYRFfhuoszMsmTLOKCrOKBtnkiWln///9DT0RFIEdPTEY "Jelly – Try It Online")**
### How?
```
ØA;ØDWẋ32ɓ,€⁶y"ZY - Main Link: list of characters, S e.g. ['S','P','A','M']
ØA - upper-case alphabet characters ['A','B',...,'Z']
ØD - digit characters ['0','1',...,'9']
; - concatenate ['A','B',...,'Z','0','1',...,'9']
W - wrap in a list [['A','B',...,'Z','0','1',...,'9']]
ẋ32 - repeat 32 times [['A','B',...,'Z','0','1',...,'9'],...,['A','B',...,'Z','0','1',...,'9']]
ɓ - start a new dyadic chain with that on the right
⁶ - space character ' '
,€ - pair €ach of S with a space [['S',' '],['P',' '],['A',' '],['M',' ']]
" - zip with:
y - translate (replace 'S' with ' ' in 1st, 'P' with ' ' in 2nd, ...) -- Note: zip is a zip-longest, so trailing lists remain
Z - transpose
Y - join with line-feeds
- implicit print
```
[Answer]
# C++14, ~~319 bytes~~ 237
This is my first time doing this, in the worst possible CodeGolf Language :P
```
char c;string k="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",s;int main(){map<char,vc>g;g[' ']=vc(32,' ');for(char c:k)g[c]=vc(32,c);getline(cin,s);for(int i=0;i<s.length();i++)g[s[i]][i]='@';for(char d:k){for(char x:g[d])cout<<x;cout<<'\n';}}
```
[Try it Online!](https://tio.run/##VY9NT8MwDIbP5FdE4pBGLWOCE0tSgfi6IO1O6aG4WWq1Tasmq4bQfntJN1XAwbLlx@9rG/r@ygBMl2ih2Zeayk/07tr5EuJ4VaVk79AaaotWu74ATQMRxH/1utQ7Omrw3SChKoZ0BDHNBQVBnB9mVZ04QQhaT9sCbcTpN7nYdUMEij0wAVKx95DimNexCqqFrc/s7h9ri/60JxkhNcJkjLJcjRDd3iSh5Iv6dMCm5iaDBcMMjfYNWh0B2sQt0/NlqNYCpVs12hpfRVxg2Gkyl2Geh1Dsnv31LoN3@OK3cdiYrMw5dHsv5UGcM/uws@pIjtP0uH16pq/bt5cf)
[Answer]
# Node.js, 85 bytes
*Port to Node.js suggested by @DanielIndie*
```
f=(s,x=544,c=Buffer([48+x/32%43]))=>x<1696?(s[x&31]==c?'@':c)+[`
`[++x&31]]+f(s,x):''
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVajWKfC1tTERCfZ1qk0LS21SCPaxEK7Qt/YSNXEOFZT09auwsbQzNLMXqM4ukLN2DDW1jbZXt1B3SpZUzs6gSshWlsbLByrnQYyStNKXf1/cn5ecX5Oql5OfrpGmoaSs7@Lq4K7v4@bkqbmfwA "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), ~~103~~ 98 bytes
```
f=(s,x=544,n=x>>5,c=String.fromCharCode(48+n%43))=>n<53?(s[x&31]==c?'@':c)+[`
`[++x&31]]+f(s,x):''
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVajWKfC1tTERCfPtsLOzlQn2Ta4pCgzL10vrSg/1zkjscgZqFDDxEI7T9XEWFPT1i7PxtTYXqM4ukLN2DDW1jbZXt1B3SpZUzs6gSshWlsbLByrnQYyV9NKXf1/cn5ecX5Oql5OfrpGmoaSs7@Lq4K7v4@bkqbmfwA "JavaScript (Node.js) – Try It Online")
[Answer]
# APL+WIN, 56 bytes
Prompts for input string and uses # character as identifier:
```
m←⍉32 36⍴⎕av[(65+⍳26),48+⍳10]⋄((,m[;1]∘.=32↑⎕)/,m)←'#'⋄m
```
Explanation:
```
m←⍉32 36⍴⎕av[(65+⍳26),48+⍳10] create the table
32↑⎕ pad the input string to 32 characters with spaces
(,m[;1]∘.=32↑⎕) use outer product with = to identify characters in table
((,m[;1]∘.=32↑⎕)/,m)←'#' replace characters with #
m display table
⋄ statement separator
```
[Answer]
# [Perl 5](https://www.perl.org/) `-F`, 47 bytes
```
//,say map{$F[$_]eq$'?'*':$'}0..31for A..Z,0..9
```
[Try it online!](https://tio.run/##K0gtyjH9/19fX6c4sVIhN7GgWsUtWiU@NrVQRd1eXUvdSkW91kBPz9gwLb9IwVFPL0oHyLP8/9/Z38VVwd3fx@1ffkFJZn5e8X9dX1M9A0OD/7puAA "Perl 5 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 86 bytes
For a much nicer approach (and less bytes), see [Laikoni's solution](https://codegolf.stackexchange.com/questions/162943/fill-out-the-bubble-sheet/163036#163036)!
```
f x=(x#).(<$[1..32])<$>['A'..'Z']++['0'..'9']
(a:b)#(u:v)=last(u:['#'|a==u]):b#v
_#w=w
```
[Try it online!](https://tio.run/##Fca7CsIwFADQvV9xIYWbUAg@JksiSH0slQ5uhlBSSFVsY7HpY/Dfo57p3E3/tE0TQg2zpDNhnIpYLTlfrzQT8VbhDjnHK@okUbj4f4M6oiatGKFDOjLZmN7/ppDgx0g5aJZWZIxKMskptObhQEJrunMJ3eAv/p074FCDFAJu1mcv563zfciK/QFORX78Ag "Haskell – Try It Online")
Alternatively for the same byte count we could use:
```
(a:b)#(u:v)|a==u='#':b#v|0<3=u:b#v
```
[Try it online!](https://tio.run/##FcZNC4IwGADge7/ihQmvQxiWp2RvEPZxMTx0S0QmaEW6JDf14H9f@Jyelxo@dds618BM/sy48KWXb4WIdgWX3iHHIwqBDyyCIMdw/R6Lja/iijPfxiNfFJElZBhXbFxCGZFdtynZRJPr1FsDQaf6Wwm9NXfzSzUIaICkhGdtkq82tTaDS7LTGa5ZevkD "Haskell – Try It Online")
### Explanation / Ungolfed
The operator `(#)` is very similar to `zipWith` however the function is hardcoded, st. it uses `#` if two characters are equal and otherwise it keeps the second one, ungolfed:
```
(a:b) # (u:v)
| a == u = '#' : b # v
| otherwise = u : b # v
```
If the first list is exhausted it just appends the remaining elements of the second one:
```
_ # w = w
```
With that helper we only need to generate the string `"A..Z0..9"`, replicate each element 32 times and zip the input with each string, ungolfed:
```
f x = map ((x#) . replicate 32) (['A'..'Z'] ++ ['0'..'9'])
```
[Answer]
# [Haskell](https://www.haskell.org/), 74 bytes
```
f x=[do a<-take 32$x++cycle" ";max[c]['~'|a==c]|c<-['A'..'Z']++['0'..'9']]
```
[Try it online!](https://tio.run/##Fca7CsIwFADQX7kU4Q6hQXQSk0HqY6l0cDMEucS0SpO02AgRir8e8UznQVNvncu5hSTVfQASZaTewnq1SIyZj3G2gGLrKSmjFX5xJimNno0oFe6Qc7yiZkzh8v8Nap09PQNI8DSebzC@4yW@6gAcWpBCQGdjNYRoQ5xy1ewPcGrq4w8 "Haskell – Try It Online") An input string `x` is padded with spaces to a length of 32 with `take 32$x++cycle" "`. For each character `c` from `A` to `Z` and `0` to `9`, we look at the characters `a` from the padded input string and replace them by `~` when `a` and `c` are equal and by `c` otherwise. This is achieved by `max[c]['~'|a==c]`, which is e.g. `max "A" "~" = "~"` when `a = c = 'A'`, and `max "A" "" = "A"` when `c = 'A'` and `a = 'B'`. Because this yields a singleton string instead of a char, the `do`-notation is used which concatenates the singleton strings into one string.
Based on [BMO's Haskell solution](https://codegolf.stackexchange.com/a/163008/56433).
[Answer]
# Python 2, 138 bytes
Supports both upper and lower case chars and leaves an unfilled column for spaces.
```
def f(s):
s=s.upper()
for j in"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789":print"".join(j if(len(s)<=i)or(s[i]!=j)else'@'for i in range(32))
```
If the bonus isn't worth it, then I'll go for 125 bytes and only support upper case inputs:
```
def f(s):
for j in"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789":print"".join(j if(len(s)<=i)or(s[i]!=j)else'@'for i in range(32))
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 15 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
╛dδÑ-═E↑\≈Fà±AG
```
[Run and debug it](https://staxlang.xyz/#p=be64eba52dcd45185cf74685f14147&i=%22CODE+GOLF%22&a=1)
It uses `'#'` to indicate a filled bubble.
Unpacked, ungolfed, and commented, it looks like this.
```
32( right-pad or truncate to 32
{ begin block for mapping
VAVd+ "A..Z0..9"
s'#+ move input character to top of stack and append "#". e.g. "C#"
|t translate; replace the first character with the second in string
m perform map using block
Mm transpose array of arrays and output each line
```
[Run this one](https://staxlang.xyz/#c=32%28++++%09right-pad+or+truncate+to+32%0A%7B++++++%09begin+block+for+mapping%0A++VAVd%2B%09%22A..Z0..9%22%0A++s%27%23%2B+%09move+input+character+to+top+of+stack+and+append+%22%23%22.+e.g.+%22C%23%22%0A++%7Ct+++%09translate%3B+replace+the+first+character+with+the+second+in+string%0Am++++++%09perform+map+using+block%0AMm+++++%09transpose+array+of+arrays+and+output+each+line&i=%22CODE+GOLF%22)
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 64 bytes
```
$
36*
L`.{36}
.
36*@$&¶
Y`@`Ld
(.)(.*)\1
@$2
N$`\S
$.%`
L`.{32}
```
[Try it online!](https://tio.run/##K0otycxLNPz/X4XL2ExLgcsnQa/a2KyWSw/EdVBRO7SNKzLBIcEnhUtDT1NDT0szxpDLQcWIy08lISaYS0VPNQGixaj2/39nfxdXBXd/HzcA "Retina – Try It Online")
---
```
$
36*
L`.{36}
```
Pads the inputs string on the right with spaces to **36** characters
```
.
36*@$&¶
Y`@`Ld
```
Then, put each character on its own line and add `ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789` before it.
```
(.)(.*)\1
@$2
```
Match a pair of the same character on the same line, which there is one if and only if the character for that line matches one of `ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`. Replace the first with `@` and remove the second.
```
N$`\S
$.%`
```
The only unmatched lines are ones with spaces, so the non-space characters is a 36×36 square block. Transpose it.
```
L`.{32}
```
Only keep the first 32 characters in each line
[Answer]
# Pyth, ~~23~~ 20 bytes
```
j.Tm:s+r1GUTdN.[Qd32
```
[Try it here](http://pyth.herokuapp.com/?code=j.Tm%3As%2Br1GUTdN.%5BQd32&input=%22M+AS+IN+MNEMONIC%22&debug=0)
### Explanation
```
j.Tm:s+r1GUTdN.[Qd32
.[Qd32 Pad the input to 32 characters.
m For each character...
s+r1GUT ... get the string "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"...
: dN ... with the character replaced by a '"'.
j.T Transpose the lines and print them all.
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 124 bytes
```
f(s,b,x,y)char*s,b[33];{sprintf(b,"%-32.32s",s);for(x=0;++x<36;puts(""))for(y=x+21+43*(x<27),s=b;*s;putchar(*s++==y?35:y));}
```
[Try it online!](https://tio.run/##HY3JbsIwGITvPMWvVJW8gYjN0tYxVfd9r9QFcUhMA5ZoQHFAjhDP7sa9zTczmtHtmdZ@zxR6sZ7@QGKrqVl25iOfI8sy5liN9TwtSQNjISZya1elKaocZSzabwveEdxGzGKZL0vkVFdS6hIxkKt1ZVEUYRz8WjnKY9oTBLmEDzGzKpPEhlIYR8RSqlR9LPpHNcZy55sH@E1NgYJIy5lmEIpASAMbDNsWgMlRSEYxhn@1GccTLFs7709Oz87h4vLqGm5u7@7h4fHpGV5e397h4/PrG7oxF9DrD4ZwcPgH "C (gcc) – Try It Online")
Instead of a hard-coded array, I replaced it with a lookup function instead. Fortunately the ASCII character set has contiguous alphabetic and numeric ranges (I'm looking at you, EBCDIC!) As well, I made sure to keep the output to exactly 32 characters using `sprintf()`: if this wasn't a requirement of the task, the function would be 97 bytes:
```
f(s,i,x,y)char*s,*i;{for(x=0;++x<36;puts(""))for(y=x+21+43*(x<27),i=s;*i;putchar(*i++==y?35:y));}
```
[Try it online!](https://tio.run/##HYzJTsMwFEX3/YqnsvGzXdQkHQDHRQxlbqGAxCQWkUvaJ0GK4rRyVPXbTczuDude01kY4/eoMN/r@RektprTan858jmzkqSTNZplVnIrOaltviqZ010lhEuTgfpdV5a124ghr7UTcSR6CWcujYcoSVvVjBooPDBOQmhdHyf9oxpR7TwVFfxkVLAgsnJhJAQQOG/MBmHbAqCchWYUIfyrzUf0iaq18/7k9OwcxheXV3B9c3sHk@n9A8wen57h5fXtHbpRnECvPxjCweEf "C (gcc) – Try It Online")
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 31 bytes
```
q32Se]{'[,65>A,s+S+_@#St);}%zN*
```
[Try it online!](https://tio.run/##S85KzP3/v9DYKDg1tlo9WsfM1M5Rp1g7WDveQVn90bSOEk3rWtUqP63//539XVwV3P193AA "CJam – Try It Online") Uses spaces as the "hole" character.
---
If trailing whitespace is allowed, then this works for **29 bytes**:
```
q32Se]{'[,65>A,s+S+_@#St}%zN*
```
[Try it online!](https://tio.run/##S85KzP3/v9DYKDg1tlo9WsfM1M5Rp1g7WDveQTm4pFa1yk/r/39nfxdXBXd/HzcA "CJam – Try It Online")
---
Here's a 34-byte variation that uses the Unicode full block (`█`) instead:
```
q32Se]{'[,65>A,s+S+_@#'█t);}%zN*
```
[Try it online!](https://tio.run/##S85KzP3/v9DYKDg1tlo9WsfM1M5Rp1g7WDveQVn90bSOEk3rWtUqP63//539XVwV3P193AA "CJam – Try It Online")
---
## Explanation
```
q Input.
e] Pad to a length of
32 32
with
S spaces.
{ }% For each character:
Get the uppercase alphabet by
> dropping the first
65 65
elements of
, the range of characters below
'[ '['.
+ Append
s the string version
, of the range of numbers below
A 10.
+ Append
S a space.
# Find the index of
@ the character.
t Set this index to
S a space
_ in the original array.
); Drop the space at the end.
Yield this modified array.
End for. The result is an array of arrays of characters.
z Transpose this array, turning rows into columns.
N* Join the result on newlines.
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~103~~ ~~96~~ 94 bytes
-7 bytes thanks to [Mnemonic](https://codegolf.stackexchange.com/users/48543/mnemonic)
-2 bytes thanks to [Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech)
Uses `'` as the symbol
```
i,l=input(),17;exec"k=chr(l%43+48);print''.join(`k`[i[x:][:1]!=k]for x in range(32));l+=1;"*36
```
[Try it online!](https://tio.run/##BcHdCsIgGADQVzEhpm0EzlEx8aq/m2APIMJiWDPlU8TAnt7Oib@8BuhrtZ2XFuI3E9qxozDFLNjJZU3EbwfeDicqYrKQm2b/CRbI7GZlVRm1GpneSKdfIaGCLKD0hLchvKdU@FYygXf8UCs@T5cruk@PG/4D "Python 2 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 19 bytes
```
RтúR32£vžKuÙyð:})ø»
```
[Try it online!](https://tio.run/##AS4A0f8wNWFiMWX//1LRgsO6UjMywqN2xb5LdcOZecOwOn0pw7jCu///Q09ERSBHT0xG "05AB1E – Try It Online")
**Explanation**
```
R # reverse
тú # prepend 100 zeroes
R # reverse
32£ } # take the first 32 characters
v # for each character
žK # push a string of [a-zA-Z0-9]
uÙ # upper case and remove duplicates
yð: # replace current character with space
)ø # transpose
» # join by newline
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 21 bytes
```
1Y24Y2vjO33(32:)y=~*c
```
Uses a space as marker character.
[Try it online!](https://tio.run/##y00syfn/3zDSyCTSqCzL39hYw9jISrPStk4r@f9/Z38XVwV3fx83AA "MATL – Try It Online")
### Explanation
```
1Y2 % Push 'AB...YZ'
4Y2 % Push '01...89'
v % Concatenate into a 36×1 column vector of chars
j % Push unevaluated input: string of length n, or equivalently 1×n
% row vector of chars
O33( % Write 0 at position 33. This automatically writes a 0 at postions
% n+1, n+2, ..., 32 too
32:) % Keep only the first 32 entries: gives a 1×32 row vector
y % Duplicate from below: pushes a copy of the 36 ×1 column vector
=~ % Test for non-equal entries, with broadcast. Gives a 33×32 matrix
% containing 0 for matching entries, and 1 otherwise
* % Multiply this matrix by the 1×32 row vector, with broadcast. This
% changes each 1 into the corresponding character in the input
c % Convert to char. Implicitly display. Char 0 is displayed as space
```
[Answer]
# [Common Lisp](http://www.clisp.org/), 150 bytes
```
(setq s(format nil"~32a"(read-line)))(map nil(lambda(i)(map nil(lambda(j)(princ(if(eq i j)#\# i)))s)(princ"
"))"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
```
[Try it online!](https://tio.run/##Zcs5D4IwGIDh3V/RlOXrYMLhOSqXB4r3FZcKJflIQaDM/vWqiZvr@@RNJKpKa1CirYmC7NkUvCUlSvpybE6hETztSiwFYwwKXn0JJC8eKQf8KzmDqsEyAcxA1ARJzoy7QfAzqx/RDmWMTqau5wfhbL5YRqt1vNnu9ofj6Xy53kzLdnr9wXA0pkxrN/Z8EsZRQGzTGr0B "Common Lisp – Try It Online")
### Explanation
```
;; pad input to 32 spaces on the right
(setq s(format nil"~32a"(read-line)))
;; for each character in bubble sheet, for each character in input:
;; if characters are equal print "#"
;; else print bubble sheet character
(map nil(lambda(i)(map nil(lambda(j)(princ(if(eq i j)#\# i)))s)(princ"
"))"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
```
[Answer]
# Java 10, ~~120~~ ~~118~~ 117 bytes
```
s->{var r="";for(char c=65,i;c<91&c!=58;r+="\n",c+=c<90?1:-42)for(i=0;i<32;i++)r+=i<s.length&&s[i]==c?35:c;return r;}
```
[Try it online](https://tio.run/##rY9Jb8IwEIXv/IppDihRIAphKWBcRNm6sLSlO@XgmgCG4CDbQUIovz01y7G9VZo5zPKevrckW5JdTlcJDYiU0CeM71MAjCtfzAj1YXAYAUZKMD4HatIFEeMJSAvpfaxbl1REMQoD4IAhkdmr/ZYIENgw0CwURwlQXCpmGKK1Si5NL3CxjISNjS9uZKiN9dat56rZgmcdBAy7iNXyHmK2bek3VpNO4PO5WqTTcswmGNN6peSWqxQJX0WCg0Bxgk4wm@g70DBnpm3IprDWqcxTAo1OrHOknVT@2gkj5Wz0SQXc5A41jeaw1YbusNcxHBU2NXtDCLIzLesY@W9d47rZane6N7d3973@YPjw@DR6fnl9e//4dHNevlD8Z7vSZbnyq2WcipMf) (for TIO I've used '█' (`9608` instead of `35`) for better visibility).
**Explanation:**
```
s->{ // Method with character-array parameter and String return-type
var r=""; // Result-String, starting empty
for(char c=65,i; // Start character `c` at 'A'
c<91&c!=58 // Loop as long as `c` is 'Z' or smaller, and is not '9'
; // After every iteration:
r+="\n", // Append a new-line to the result-String
c+=c<90? // If `c` is not 'Z' yet
1 // Go to the next character ASCII-value-wise
: // Else:
-42) // Change the 'Z' to '0'
for(i=0;i<32;i++) // Inner loop `i` in the range [0,32)
r+=i<s.length // If we're not at the end of the input array yet,
&&s[i]==c? // and the characters in the column and array are the same
35 // Append the filler-character '#'
: // Else:
c; // Append the current character instead
return r;} // Return the result-String
```
[Answer]
# [Tcl](http://tcl.tk/), ~~153~~ 145 bytes
Thanks [@sergiol](https://codegolf.stackexchange.com/users/29325/sergiol) for -8 bytes
```
lmap i [split ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ""] {puts [join [lmap j [split [format %-32s [join $argv ""]] ""] {expr {$i==$j?"#":$i}}] ""]}
```
[Try it online!](https://tio.run/##K0nO@f8/JzexQCFTIbq4ICezRMHRydnF1c3dw9PL28fXzz8gMCg4JDQsPCIyysDQyNjE1MzcwlJBSSlWobqgtKRYITorPzNPIRpsRhbMjOi0/KLcxBIFVV1jI5gSlcSi9DKQxliI7tSKgiKFapVMW1uVLHslZSUrlczaWrBc7f///539XVwV3P193BSMDAwtAA "Tcl – Try It Online")
### Explanation
```
# for i in list of choices
lmap i [split ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ""] {
# print string of
puts [join
# list of
[lmap j
# for each character in first argument padded to 32 characters
[split [format %-32s [join $argv ""]] ""]
# return "#" if current choice and current character are equal, else current choice
{expr {$i==$j?"#":$i}}
]
""
]
}
```
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), ~~155~~ 150 bytes
```
I =INPUT
U =&UCASE '0123456789'
N U LEN(1) . K REM . U :F(END)
O =DUPL(K,32)
X =
S I LEN(X) @X K :F(O)
O POS(X) K =' ' :S(S)
O OUTPUT =O :(N)
END
```
[Try it online!](https://tio.run/##HU7JCsIwFDwnXzEnk4CIXdwKAaVNpaTmBdNAz57FHvx/YuppmJX5fpbX8q5TYgP04HycOIvQm9jegoHYF2VVH46n80Vwl43ROFko7GDxNI@MkTW9NK5TnBF0F/0o7bYqM52hecira2VWuM6wa5b@SU9hFS20gGBNkEFxYhSnfACaWCOd4nk2pZY6gzuN/Q8 "SNOBOL4 (CSNOBOL4) – Try It Online")
Explanation:
```
I =INPUT ;* read input
U =&UCASE '0123456789' ;* U = uppercase concat digits
N U LEN(1) . K REM . U :F(END) ;* while U not empty, pop first letter as K
O =DUPL(K,32) ;* dup K 32 times
X = ;* set position to 0
S I LEN(X) @X K :F(O) ;* find the next occurrence of K and save (index - 1) as X
O POS(X) K =' ' :S(S) ;* replace the X'th occurrence of K with space. If that's before character 32, goto S, else proceed to next line
O OUTPUT =O :(N) ;* output the string and goto N
END
```
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), ~~235~~ ~~229~~ ~~228~~ ~~222~~ ~~214~~ ~~198~~ ~~173~~ ~~167~~ 165 bytes
-6 bytes thanks to [@Cows quack](https://codegolf.stackexchange.com/users/41805/cows-quack), -6 bytes thanks to [@
0 '](https://codegolf.stackexchange.com/users/20059/0)
```
X*[H|T]:-(H=X->write(#);writef("%n",[X])),X*T;nl.
_+[].
X+[H|T]:-H*X,X+T.
?-read(X),swritef(Y,"%32l",[X]),string_codes(Y,Z),Z+`ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`.
```
[Try it online!](https://tio.run/##LYzbCoJAFADf/YrYCFzdXcruRUVlZVe7WJ0UqSgTQTRcoZf@fYvybWCYeSZxGPuUvwIhQHGMt@W2qGx0gHZfSZB6ch63f/CQUSFCxAEXYwKK1Y5CJp1Vx2USqFlnKEBAtZjUo4l3vcuACc/iE0GFshb@B4SnSRD551t89/hX2ZjY6qU/GOqj8cSYzuaL5cpcb7Y7a384wskulrRypVqrN5oXJgQamvooNzEX45xWLDUQEx8 "Prolog (SWI) – Try It Online")
### Explanation
```
% if head = bubble char, write "#", else write bubble char, then while tail is non-empty, recurse.
% if tail is empty then print newline
X*[H|T]:-(H=X->write(#);writef("%n",[X])),X*T;nl.
% if list is empty, then do nothing. this prevents t from being called with invalid X
_+[].
% call t, then recurse for each char in list
X+[H|T]:-H*X,X+T.
% read, pad input to 32 chars, and convert input to list
?-read(X),swritef(Y,"%32l",[X]),string_codes(Y,Z),Z+`ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`.
```
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGLOnline), 19 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
,M↕+'»m{Z²²+;╗ŗ}⁰№I
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JTJDTSV1MjE5NSslMjclQkJtJTdCWiVCMiVCMislM0IldTI1NTcldTAxNTclN0QldTIwNzAldTIxMTZJ,inputs=QUJDJTIwQUJDJTIwMTIzJTIwSEVMTE8lMjBXT1JMRA__,v=0.12)
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 61 bytes
```
@(s)[((a=[30:55 13:22]'*~~(o=1:32)).*(a+35~=[s o](o)))+35 '']
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo1gzWkMj0Tba2MDK1FTB0NjKyChWXauuTiPf1tDK2EhTU09LI1Hb2LTONrpYIT9WI19TUxPIVVBXj/2fpqHu6OTs4urm7uHp5e3j6@cfEBgUHBIaFh4RGWVgaGRsYqqu@R8A "Octave – Try It Online")
The function works as follows:
```
@(s)[ ''] %Anonymous function, taking string, outputting character array
[30:55 13:22]' %Creates the board alphabet ('A':'Z' '0':'9']) but minus 35 (value of '#')
*~~(o=1:32) %Matrix multiplication by an array of 32 1's to form the 2D board. Saves 1:32 for later.
(a= ) %Saves the board mimus 32 to a for use later.
[s o](o) %Ensures the input is 32 characters long. Missing chars replaced by 1:32 (not in board)
(a+35~= ) %Compares against board (a+35 as a=board-35). Makes 2D array where matches = 0, others = 1.
( .* )+35 %Element=wise multiplication, forcing matches to 0. Then add 35 resulting in board with #'s
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 57 bytes
```
{map {<<$^c█>>[.comb[^32]Xeq$c].join},|('A'..'Z'),|^10}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OjexQKHaxkYlLvnRtA47u2i95PzcpOg4Y6PYiNRCleRYvaz8zLxanRoNdUd1PT31KHVNnZo4Q4Pa/8WJlQppGirxmmAVGkoxeUqaOgogSiEtv0hB3dnfxVXB3d/HTV1HQd3RydnF1c3dw9PL28fXzz8gMCg4JDQsPCIyysDQyNjEVN36PwA "Perl 6 – Try It Online")
]
|
[Question]
[
What general tips do you have for golfing in Octave? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Octave (e.g. "remove comments" is not an answer). Please post one tip per answer.
[Answer]
1. Once you know, that `a` is free of zero values, using `nnz(a)` spares you 2 chars compared to `numel(a)`.
2. Prefer `a(a==0)` to `a(find(a==0))`.
3. `~t` is shorter than `t==0` , and even `~~t` is shorter than `t!=0`.
4. `0*(1:n)` is shorter than `zeros(1,n)`
5. Generally, `||` and `&&` , unlike many other operators, scalarize the result when the first argument is a scalar. For matrices, only non-empty matrices without elements equal to zero have the logical value of *true*.
Hence, we can do `0||m` instead of `all(all(m))` for any matrix.
Try with `0||[1 1;1 0]` and `0||[1 1;1 1]` to convince yourself.
6. When you are using a builtin a number of times, do a function handle to spare characters eg. `f=@find` . For short function names at least 3 occurrences justify this, for long ones - even with two occurrences.
7. When a function is a single statement, prefer `f=@(n)dosomething(n)` notation to `function r=f(n)r=dosomething(n);end` one.
8. Unfortunately, global variables have to be declared both in global scope and in each function using them. But there is an exception: anonymous `@(n)...` functions "see" all variables from the scope where they are called from.
9. It's possible to do `f(a=0,b=0)` instead of `a=0;b=0;f(a,b)`.
10. This seems undocumented feature, but the order of evaluation is from left to right (checked at v. 3.8.1), you can do `zeros(a=n,b=a*a)` to both create a n x n^2 matrix and store it's row and column number in `a` and `b` variables.
11. The operator precedence table is your friend. Don't do `b=(a==0)` since `b=a==0` is the same.
[Answer]
# Using argument list:
Octave is capable to get default arguments so expressions can be evaluated in the argument list.
This feature is useful when we want to compute an expression and use it multiple times:
```
f = @(x,a=sort(x))a(a>.5);
```
One use case is when we use an indexed assignment to modify part of an array and we want to use the array:
```
a=[1 2 3 4]
a(2)=5;
```
But the expression `(a(2)=5)` returns `a(2)`, or the expression `(a([1 3])=4)` returns a two elements array. Neither returns the whole array. We can use the argument list:
```
f=@(a=[1 2 3 4],b=a(2)=5)a;
```
Here the result of the indexed assignment is stored into a dummy variable `b` and the function returns the array.
[Answer]
I do not remember in what challenge I saw it someone use (please tell us=), but I found this a neat trick:
Usually if you add matrices you have to have the same size, but for one dimensional (1xn and nx1) matrices there is a shortcut (that does not work in Matlab):
```
z = (1:5)+(6:10)';
```
produces the same effect as
```
[x,y]=meshgrid(1:5,6:10);
z = x+y;
```
Then something that pawel.boczarski already mentioned: In Octave you can (while you cannot in Matlab) define auxiliary variables within function handles, AND a variable assignment itself has the value of the assignment so you can really shorten code (well this is an useless example but you'll get the trick):
```
f=@(n)(z=n+1)*z; %returns (n+1)^2
```
Then another trick (also applicable in Matlab) is abusing strings for storing (hardcoded) numbers [(this neat trick is stolen from feersum)](https://codegolf.stackexchange.com/a/41013/24877), you just need something that interprets the string as number, which is as easy as e.g. adding zero:
```
a = 'abc';
a+0 %returns
[97 98 99]
```
Or
```
sum('abc') == 294
```
[Answer]
**Skip semicolons!**
I'll use [this answer](https://codegolf.stackexchange.com/a/107725/31516) to illustrate the point.
The original code was:
```
function f(x);if~movefile('f.m',x);disp("+-+\n| |\n+-+");end
```
After removing semicolons, it could be reduced to the following, saving three bytes:
```
function f(x)if~movefile('f.m',x)disp("+-+\n| |\n+-+")end
```
This can be used quite a few places, and stuff you don't even try because it looks like a syntax error often works.
[Answer]
-In Octave it is possible to apply indexing on a temporary expression, a feature that prohibited in MATLAB and this feature is very useful for golfing.
example:
Octave: `[1 23 4 5 7](3:4)` and its MATLAB equivalent: `a=[1 23 4 5 7];a(3:4)`
Octave: `hilb(4)(4:5,4:5)` and its MATLAB equivalent: `h=hilb(4);h(4:5,4:5)`
Octave: `{1,4,{4 5 6},[7 ;3]}{3}` and its MATLAB equivalent: `a={1,4,{4 5 6},[7 ;3]};a{3}`
Octave: `num2cell([1 2 3 4]){:}` for creation of comma separated list
Octave: `a'(:)'`
-Sometimes in an anonymous function as of a normal function we require to evaluate multiple expressions,that include assignment,
One approach is that we can place each expression in a cell(since cell can contain object of multiple types ) and when we need the value of each expression we can use indexing to extract that element.
`{1,4,{4 5 6},[7 ;3]}{3}`
or
`{a=1,b=4,c={4 5 6},[b ;3]}{4}`
[Answer]
This is a simple, but useful one.
In Octave, but not MATLAB, you can do as in C++:
```
x = 0 -> x = 0
x++ -> ans = 0
x -> x = 1
++x -> ans = 2
x -> x = 2
```
[Answer]
## Use the `e` function instead of `ones` or `zeros`
Octave has an `e` function, which I don't think is very well known. It's like `ones`or `zeros`, but it produces copies of the number *e*. And it's *shorter*. This function can be useful sometimes:
* Instead of `ones(m,n)` you can use `~~e(m,n)` if you can get away with having `true` instead of `1`. Or even use `e(m,n)` directly if all you need is a nonzero value, not specifically `1` (for example if you are going to convert to `logical` later).
* Instead of `zeros(m,n)` you can use `~e(m,n)` if `false` is acceptable instead of `0`; or `+~e(m,n)` to produce actual zeros.
[Answer]
Another simple, but useful one (not possible in MATLAB):
Assign the same value to several variables:
```
a=b=c=0;
```
[Answer]
Use `rows(a)` instead of `size(a,1)`
[Answer]
**Use `eval`!**
Inspired by Luis Mendo's answer [here](https://codegolf.stackexchange.com/a/163111/31516).
---
Anonymous functions are in most cases shorter than creating a script that needs one or more calls to `input('')`. The downside is that loops and variable modifications (such as swapping two elements in a matrix) is ~~impossible~~ cumbersome.
With `eval`, you can fetch the input as you do with a normal anonymous function, and run the script as you do with a normal script:
Consider [this](https://codegolf.stackexchange.com/a/163103/31516):
```
c=(i=@input)('');N=i('');A=i('');for C=c,A(flip(k))=A(k=[x=find(A==C),N^2+1-x]);end,A
```
Compared to this:
```
@(c,N,A)eval('for C=c,A(flip(k))=A(k=[x=find(A==C),N^2+1-x]);end,A')
```
The code is identical, but the input section is much shorter.
---
This can also be used to modify input variables, like this (credit to [Luis Mendo](https://codegolf.stackexchange.com/a/163111/31516) for this!):
```
f(x)eval('x([1,4])=x([4,1])`;
```
[Answer]
Related, but not identical [tips for MATLAB](https://codegolf.stackexchange.com/a/111979/31516).
A little known and little used feature of Octave is that most builtin functions can be called without parentheses, in which case they will treat whatever follows it as a string (as long as it doesn't contain spaces). If it contains spaces you need quotation marks. This can frequently be used to save a byte or two when using `disp`. All the following work, and gives the same result:
```
disp('Hello')
disp Hello
disp"Hello"
```
If you have spaces, then you *must* have the quotation marks:
```
disp('Hello, World!')
disp"Hello, World!"
```
Other, less useful examples include:
```
nnz PPCG
ans = 4
size PPCG
ans = 1 4
str2num 12
ans = 12
```
]
|
[Question]
[
The bots are looking for love. Can you help them?
## The rules
The goal of this game is find the bot you have the highest compatibility with. However, robots, who are inexperienced at dating are unable to tell how well a date went.
In the game, bots take turns "speed dating" some other bot. After each date, each bot chooses whether to get married or to continue dating. If both bots agree to get married both are removed from the dating pool and their compatibility rank (100% is if you found the best one, 0% for the worst one) is their final score.
Bots won't be able to tell what the compatibility is, but they can compare dates. For example if bot A went on a date with bot B and C, they'll be able to tell if B or C was more compatible but not by how much.
Bot A's compatibility with B does not equal B's compatibility with A, but they are correlated.
If every bot has dated every other bot, the ordering is shuffled and any remaining bots can try again. However, everyone's final score is reduced by 25% (exponential) for every round they stay single. If a entire round ends without any new marriages the game ends and all remaining bots get a score of 0.
## Example bot
```
class BetterThanFirst:
"""
This bot will use its first date as a reference, then marry any bot that's better than it
"""
def __init__(self, nrof_bots, rng): # rng is a seeded PRNG you can use, no other forms of randomness allowed
# nrof_bots is the total number of bots playing
self.first_date = None
def round_finished(self, nrof_remaining_bots): # the number of bots still in the game
pass # called if a full round finished, optional
def date(self, other) -> bool: # Return True if you want to marry this bot, False otherwise
if self.first_date is None:
self.first_date = other
else:
return other > self.first_date
```
## Other rules
* No IO
* No RNG except via the provided PRNG
* No inspecting other bots. You are only allowed to use the `>`, `<`, `<=`, `>=`, `==` operators on other bots.
* No exploiting the controller.
## Controller
[](https://i.stack.imgur.com/bkB9L.png)
The controller repo is here: <https://codeberg.org/Mousetail/KOTH-dating-game>
Results, and the active game (if any) can be viewed here: <https://koth.mousetail.nl/>
[Answer]
# Optimal Average
```
class OptimalAverage:
def __init__(self, nrof_bots, rng):
self.test_num = round((nrof_bots - 1)**0.5)
self.tests = []
def round_finished(self, nrof_remaining_bots):
self.test_num = round((nrof_remaining_bots - 1)**0.5)
self.tests = []
def date(self, other) -> bool:
if len(self.tests) < self.test_num:
self.tests.append(other)
return False
else:
return all(f <= other for f in self.tests)
```
Similar to @Spitemaster's answer but we skip the first \$\sqrt{n}\$ bots instead. While their strategy has been proven optimal for maximizing one's chance at getting the best candidate, this strategy is optimal for obtaining the best average score assuming that there is value in candidates that are not the best, which is the case here. Of course this still misses the same important notes; that the opposing bot won't always agree, and that bots will be dropping out as it goes along.
[Answer]
# Optimal Stopping Time
```
class OptimalStoppingTime:
def __init__(self, nrof_bots, rng):
import math
self.dates_left = math.ceil((nrof_bots - 1)/ 2.718)
self.dates = []
def round_finished(self, nrof_remaining_bots):
pass
def date(self, other) -> bool: # Return True if you want to marry this bot, False otherwise
if self.dates_left > 0:
self.dates_left -= 1
self.dates += [other]
else:
return all(other >= x for x in self.dates)
```
The optimal stopping time for the secretary problem is to skip the first n/e and then accept any better than the best seen so far. There may be a better strategy because it's not symmetric and other bots may not agree - and it doesn't account for bots dropping out.
[Answer]
# Naive Elitist
```
class NaiveElitist:
def __init__(self, nrof_bots, rng):
self.best = None
def round_finished(self, nrof_remaining_bots):
pass
def date(self, other) -> bool:
if self.best is None or other >= self.best:
self.best = other
return other >= self.best
```
This bot will settle for nothing less than the best!
...But it can't imagine that anything better than what it's already found could be possible, even if it's only experienced a single date.
[Answer]
# Crossing out options
```
class crossing_out_options:
"""accepts any bot at least as good as the best remaining bot which it hasn't accepted yet"""
def __init__(self, nrof_bots, rng):
self.candidates = []
self.rejected_me = []
self.pool = []
self.first_date = True
def round_finished(self, nrof_remaining_bots):
self.candidates = [x for x in self.candidates if x in self.pool]
self.pool = []
def date(self, other) -> bool:
self.pool += [other]
if self.first_date:
self.candidates = [other]
self.first_date = False
return False
if other in self.rejected_me:
return True # no shame
if all(other >= x for x in self.candidates):
self.candidates = [x for x in self.candidates if x != other]
self.rejected_me += [other]
return True
if not other in self.candidates:
self.candidates += [other]
return False
```
This bot keeps a list of all the "candidate" bots it has dated but not accepted, and which ones it tried to accept. It accepts the best bot from the candidate list. (Or any better bot, even if they rejected it before! No grudges!). At the end of the round it removes bots from the candidate list if it didn't encounter them this round.
The result is that it accepts any bot that "better than first" would accept, but learns and moves on if its best matches are already taken or don't love it back.
[Answer]
# Always Accepts
```
class EveryoneIsFine:
"""This bot just accepts everyone"""
def __init__(self, nrof_bots, rng):
self.botmotto="Accept everyone."
def round_finished(self, nrof_remaining_bots):
pass
def date(self, other) -> bool:
return True
```
This bot just doesn't care who they're married to.
[Answer]
# C+ dater
```
class c_plus_dater:
def __init__(self, nrof_bots, rng): # rng is a seeded PRNG you can use, no other forms of randomness allowed
# nrof_bots is the total number of bots playing
self.round = 0
self.betterbots = 0
self.bestbot = None
def round_finished(self, nrof_remaining_bots): # the number of bots still in the game
self.round += 1
def date(self, other) -> bool: # Return True if you want to marry this bot, False otherwise
marry = False
if self.bestbot is None:
self.bestbot = other
else:
if other > self.bestbot:
self.betterbots += 1
self.bestbot = other
if self.betterbots >= 3:
marry = True
return marry
```
Edited to avoid comparing a bot to a constant, instead only to each other. This bot takes any bot that is better than at least 3 other bots. But it probably gets buggy in the second round.
Old version:
Bot takes anything above 70% in the first round, and lowers its standard each round after that.
[I'm counting on compatibility being between 0 and 1]
[Answer]
# Logger
```
class Logger:
"""Logs how everyone was on the first round (rejecting all) and uses that to determine the best bot."""
def __init__(self, nrof_bots, rng):
self.botlist=[]
self.counter=0
self.bots=nrof_bots
def round_finished(self, nrof_remaining_bots):
self.counter=self.counter+1
if nrof_remaining_bots!=self.bots:
self.counter=0
self.bots=nrof_remaining_bots
def date(self, other):
if self.counter==0:
self.botlist.append(other)
return False
else:
return other==max(self.botlist)
```
This bot gets the best bot by logging each bot and picking the one with the best compatibility. If the bot with the best compatibility marries a bot other than the Logger, ~~the Logger is screwed~~ the logger only notices at the end of the round and re-evaluates each bot.
[Answer]
**The Hopeless Romantic**
This hopelessy romantic bot falls in love with the first robot it ever sees, and will pursue its subject of aspirations til the end of times. Which, it turns out, is quite long for robots.
```
class HopeLessRomantic:
"""
This hopelessy romantic bot falls in love with the first robot it ever sees, and will pursue its subject of aspirations til the end of warranty. Which is long for robots.
"""
def __init__(self, nrof_bots, rng):
# nrof_bots is the total number of bots playing
self.firstlove= None
def round_finished(self, nrof_remaining_bots):
#alas! the light of my live has rejected me. *sad robot noise*
pass
def date(self, other) -> bool:
if self.firstlove is None:
self.firstlove= other # madly fall in robolove
return True
elif self.firstlove==other:
return True
else:
return False
```
[Answer]
# Optimal Cutoffs
```
import math
def value(n, k, j):
return sum(i*math.comb(i,j)*math.comb(n-i-1,k-j-1) for i in range(j,n-k+j+1)) / math.comb(n,k)
def get_cutoff(n, k0):
cutoff = {}
for k in range(n,0,-1):
if k >= k0: bst = 0
z=0
cutoff[k] = k
for j in range(k-1,-1,-1):
v = value(n,k,j)
if v > bst:
z += v
else:
cutoff[k] = j+(v<bst)
z += (j+1)*bst
break
bst=z/k
return cutoff
class OptimalCutoffs:
def __init__(self, nrof_bots, rng):
self.first_round = True
n = nrof_bots - 1
self.cutoff = get_cutoff(n, int(n * 3/4))
self.met = []
def round_finished(self, nrof_remaining_bots):
self.first_round = False
def date(self, other):
if not self.first_round: return True
self.met.append(other)
self.met.sort()
if self.met.index(other) >= self.cutoff[len(self.met)]:
self.met.remove(other)
return True
else:
return False
```
Uses dynamic programming to calculate the optimal cutoffs assuming the bot will meet 3/4 of the other bots, the other bot will always accept, and there is no payoff after the first round. Always accepts in rounds after the first.
[Answer]
# Third Time Lucky
```
class ThirdTimeLucky:
"""Picks the bot from the third date"""
def __init__(self, nrof_bots, rng): # rng is a seeded PRNG you can use, no other forms of randomness allowed
# nrof_bots is the total number of bots playing
self.number = 1
def round_finished(self, nrof_remaining_bots): # the number of bots still in the game
self.number = 1
def date(self, other) -> bool: # Return True if you want to marry this bot, False otherwise
if self.number >= 3:
self.number = 1
return True
else:
self.number += 1
return False
```
This bot believes that three dates is the correct number to go on and will be happy to marry the third bot. If the other bot refuses, then they go on another three dates, accepting only the third.
[Answer]
# Lower standards
```
class lower_standards:
def __init__(self, nrof_bots, rng):
self.sample_size = round((nrof_bots-1)**0.5)
self.sample = [] # sample of dates (from the first round)
self.curr = [] # all dates from the current round
self.prev = [] # all dates from the previous round
self.pool = nrof_bots - 1 # size of the dating pool
self.round = 0 # round number
def round_finished(self, nrof_remaining_bots):
self.pool = nrof_remaining_bots - 1
self.prev = self.curr
self.curr = []
self.round += 1
def date(self, other) -> bool:
self.curr += [other]
if self.round == 0 :
if len(self.sample) < self.sample_size :
self.sample += [other]
return False
if all(other >= x for x in self.sample) :
return True
else :
if sum(x > other for x in self.prev) <= len(self.prev) - self.pool + self.round - 1:
return True
return False
```
In the first round, this bot behaves like OptimalAverage.
On the second round, it behaves like a much more pessimistic version of Logger. Rather than assuming the current dating pool is the same as in the previous round, it takes into account that some bots have left. When the round ends, it looks at the number of bots still in the dating pool, and assumes that the remaining options are the worst possible subset of the previous round. It then accepts any bot which would be best in this reduced pool.
On the third and subsequent rounds, it becomes even less picky, accepting second best in the pessimistically reduced pool, then 3rd best, etc.
[Answer]
# Wait for it...
```
class wait_for_it:
"""always rejects in the first round,
then only accepts the top 2 it saw in the previous round,
until it sees that the game is about to end,
at which point it panics and accepts anyone."""
def __init__(self, nrof_bots, rng):
self.pool_size = nrof_bots
self.curr = [] # all dates from the current round
self.prev = [] # all dates from the previous round
self.end_count = 0 # number of rounds with no matches made
def round_finished(self, nrof_remaining_bots):
if nrof_remaining_bots == self.pool_size:
self.end_count += 1
else:
self.end_count = 0
self.pool_size = nrof_remaining_bots
self.prev = self.curr
self.curr = []
def date(self, other) -> bool:
self.curr += [other]
if not self.prev:
return False
if self.end_count == 2:
return True
if sum(x > other for x in self.prev) <= 1:
return True
return False
```
This bot is always a step behind. In each round, it will accept either of the top 2 matches it saw in the previous round. However, it also keeps tabs on the end condition, and if two rounds have gone without a match being made, it will accept anyone to avoid ending up alone.
[Answer]
# Optimal Desperation
```
class optimal_desperation:
"""
starts out believing in a beautiful theorem it heard about,
but if that doesn't work out, it takes what it can get
"""
def __init__(self, nrof_bots, rng):
import math
self.dates_left = math.ceil((nrof_bots-1)/2.718)
self.best = None
self.desperate = False
def round_finished(self, nrof_remaining_bots):
pass
def date(self, other) -> bool:
if self.desperate:
return True
if self.best is None:
self.best = other
self.dates_left -= 1
return False
if self.dates_left > 0:
self.dates_left -= 1
self.best = max(other, self.best)
return False
if other >= self.best:
self.desperate = True
return True
return False
```
Inspired by Spitemaster's Optimal Stopping Time, but when its optimally true love rejects it, it gets desperate and says "yes" to anyone and everyone.
[Answer]
# Partygoer
While sober, the partygoer doesn't care for dating. However, it likes meeting new people, so, just for the sake of it, the partygoer decided to join the - hey, look! Beer!
```
class Partygoer:
"""
Decides when to marry depending on how sober it is. Then, it drinks.
"""
def __init__(self, nrof_bots, rng):
self.sobriety = 1.0
self.rng = rng
def round_finished(self, nrof_remaining_bots):
self.sobriety -= .05
def date(self, other) -> bool:
limit = self.rng.random()
flag = False
if limit > self.sobriety:
flag = True
self.sobriety -= 0.01
return flag
```
Uses the PRNG to decide a limit. Every time it goes on a date, it checks its sobriety. If it's greater than the limit, it decides to marry. Regardless, though, it takes a drink, decreasing its sobriety a little. If an entire round goes past without getting married, it decreases sobriety by a larger margin.
[Answer]
# Anything but the worst
```
class AnythingButTheWorst:
"""
Will accept anyone as long as there is someone worse
"""
# rng is a seeded PRNG you can use, no other forms of randomness allowed
def __init__(self, nrof_bots, rng):
# nrof_bots is the total number of bots playing
self.worst = None
# the number of bots still in the game
def round_finished(self, nrof_remaining_bots):
pass # called if a full round finished, optional
def date(self, other) -> bool: # Return True if you want to marry this bot, False otherwise
if self.worst is None:
self.worst = other
else:
self.worst = min(self.worst, other)
return other > self.worst
```
Will settle for any bot except the worst one.
[Answer]
# Adaptive Better-than-median
```
class adaptive_better_than_median:
"""
accepts bots better than the median,
while updating the median as the game evolves
"""
def __init__(self, nrof_bots, rng):
self.curr = []
self.prev = None
# the number of bots still in the game
def round_finished(self, nrof_remaining_bots):
self.prev = self.curr
self.curr = []
def date(self, other) -> bool:
self.curr += [other]
if self.prev is None:
return sum(other > x for x in self.curr) >= len(self.curr)//2
return sum(other > x for x in self.prev) >= len(self.curr)//2
```
Just what the name says; behaves in the first and second rounds like "Better than Median", but then adjusts the median based on who dropped out in previous rounds.
[Answer]
# Top Three Previous
```
class TopThreePrevious:
"""
Will marry any of the top three it has seen from the previous round.
If it's the first round, it flips a coin instead.
"""
def __init__(self, nrof_bots, rng):
self.rng = rng
self.best = []
self.previousBest = []
self.bots = []
def round_finished(self, nrof_remaining_bots):
self.best = []
self.bots.sort(reverse = True)
for i in range(3):
self.best.append(self.bots[i])
self.bots = []
def date(self, other) -> bool:
self.bots += [other]
if len(self.best) == 0:
return self.rng.random()>0.5
return other in self.best
```
This bot simply checks if the bot it's currently dating was one of the top three it has seen in the previous round, or flips a coin if it's the first round (it uses the length of `self.best` to determine this).
[Answer]
# T
#### \*\*\* not working \*\*\*
```
class T:
def __init__(self, nrof_bots, rng):
self.NR = nrof_bots
self.d = {}
self.mc = 0
self.r = 1
self.rc = 1
self.xrs = [] # unseen in current round
self.x = set() # seen in previous round
self.xn = [] # seen in this round
self.c = 0 # for debugging
def update(self, other):
self.c += 1
self.rc += 1
if other not in self.d: self.d[other] = 0 # Set if new
self.d[other] += 1
self.mc = max(self.mc, self.d[other]) # Highest number seen
if self.mc > self.r: # update round
missing_in_round = set(self.x).difference(set(self.xn))
NR_ = self.NR - len(missing_in_round)
self.NR = NR_
self.r = self.mc # set round
self.x = set(self.xn) # seen in prev round
self.xrs = self.xn # All are unseen
self.xn = [] # reset round
self.rc = 1
self.xn.append(other)
xrs_ = set(self.xrs).difference({other}) # update unseen
self.xrs = list(xrs_)
self.xrs.sort() # sort unseen
def get1(rc, NR, xrs, xn):
average_acceptance = 0.3
N_ = NR - rc * 0.3
dec = 0.7 * N_ / (N_+ 1)
return dec
def getd(rc, NR, xrs, xn):
if len(xrs) == 0: # end of round
xn_ = xn.copy()
xn_.sort()
dec = xn_[round(len(xn_) * 0.7)]
else:
dec = xrs[min(round(NR*0.7 - rc*0.14), len(xrs) - 1)]
return dec
def round_finished(self, nrof_remaining_bots):
return None
def date(self, other): # Return True if you want to marry this bot, False otherwise
self.update(other)
espouse = other >= (T.getd,T.get1)[self.r==1](self.rc, self.NR, self.xrs, self.xn)
print(f'{self.c}:{other:3.2f} :::{espouse}')
return espouse
```
[Answer]
```
class IDK_bot:
"""
This bot will use its first date as a reference, then marry any bot that's better than it
"""
def __init__(self, nrof_bots, rng): # rng is a seeded PRNG you can use, no other forms of randomness allowed
# nrof_bots is the total number of bots playing
import math
self.rng=rng
self.numbots=nrof_bots
self.dates=[]
self.cutoff=int(self.numbots/math.e)**(4/5))
self.num=0
self.rounds=0
def round_finished(self, nrof_remaining_bots): # the number of bots still in the game
import math
self.numbots=nrof_remaining_bots
self.cutoff=int(self.numbots/math.e)**(4/5))
self.rounds+=1
def date(self, other) -> bool: # Return True if you want to marry this bot, False otherwise
self.dates.append(other)
self.dates.sort()
self.num+=1
if self.num<self.cutoff:
return False
score=self.dates.index(other)/self.num
if score<0.5:
return False
return self.rng.random()<=score*(self.num/self.bots*1.2)**(1/3)*(1+self.rounds/5)
```
The bot defines a "cutoff" based on the `n/e` rule which has been proven to be approximately optimal for the secretary problem. However, since you aren't guaranteed to see every possible date, that limit is raised to the 4/5th power (an arbitrary number I selected) to give more potential candidates to select.
The actual selection is based on RNG. The bot first calculates the date's score, which is the relative ranking of the date in relation to the other dates it has seen, represented as a number from 0 to 1. The bot rejects any candidate with a score less than 0.5. The bot multiplies the score by a bunch of math, effectively taking into account the fraction of dates seen so far and how many rounds it has been in.
This lets the "score" be the largest part in deciding whether or not to accept a candidate, but also makes it so that the probability of acceptance increases as more bots are seen and as more rounds pass.
I haven't been able to test this, so please let me know if there are any bugs I need to fix.
]
|
[Question]
[
**Motivation**: Sometimes certain items in a list don't count towards your totals. For example, counting plane passengers in rows, where babies sit on a parent's laps.
**Challenge**: write a program to split a list of items into chunks. Each chunk (except possibly the last) is the same *size*, where *size* is defined as the number of items passing a predicate function.
**Rules**:
1. Your program must take
* a list of items
* a positive integer chunk size
* a predicate function (takes an item, and returns true or false)
2. You must return the input list split into chunks
3. Each chunk is a list of items
4. Overall the items must remain in the same order, with none disgarded
5. The number of items passing predicate in each chunk (except possibly the last) should match the input chunk size.
6. items failing the predicate should not count toward this size
7. Items failing the predicate are
1. still included in the output chunks
2. allocated to the earliest chunk, in the case that a chunk is "full" but the next items are ones failing the predicate
* thus the final chunk may not consist solely of items failing the predicate
8. The final chunk may be of *size* less than the chunk size because all the items have been accounted for.
**Non exhaustive examples:**
The simplest example is to consider `1`s and `0`s, where the predicate function is `x ==> x > 0`. In this case, the `sum` of each chunk must match the chunk size.
* items: `[]`, size: `2`, predicate: `x > 0` --> either `[]` or `[[]]`
* items: `[0, 0, 0, 0, 0, 0]`, size: `2`, predicate: `x > 0` --> `[[0, 0, 0, 0, 0, 0]]`
* items: `[0, 1, 1, 0]`, size: `2`, predicate: `x > 0` --> `[[0, 1, 1, 0]]`
* items: `[0, 1, 1, 0, 1, 0, 0]`, size: `2`, predicate: `x > 0` --> `[[0, 1, 1, 0], [1, 0, 0]]`
* items: `[0, 1, 0, 0, 1, 0, 1, 1, 0]`, size: `2`, predicate: `x > 0` --> `[[0, 1, 0, 0, 1, 0], [1, 1, 0]]`
And let's finish with the *plane passengers where babies sit on a parent's lap* example. `A` for adult, `b` for baby, plane row is `3` seats wide, adult always listed before their baby:
* items: `[A, b, A, b, A, A, A, b, A, b, A, A, b]`, size: `3`, predicate: `x => x == A` --> `[[A, b, A, b, A], [A, A, b, A, b], [A, A, b]]`
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 37 bytes
```
hW&t~c.k{↰₂ˢl}ᵐ;WxĖ∧.bhᵐ↰₂ᵐ∧.t↰₂ˢl≤W∧
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/PyNcraQuWS@7@lHbhkdNTacX5dQ@3DrBOrziyLRHHcv1kjKAPIgUiAEUKYErfNS5JBwo8l/JUel/tLGOQjSQoaOglAQi0FiOWMSS0CViY/9HAQA "Brachylog – Try It Online")
I was pleasantly surprised to find that this - pretty much a restatement of the question - successfully terminates and produces correct output.
Assumes the predicate is present as predicate 2 below this code. Outputs a list of lists ("chunks"), or `false` for an empty input.
### Explanation:
```
hW& % First input is W, the expected "weight" of each chunk
% (i.e. the number of items passing predicate in each chunk)
t % Take the second input, the list of items
~c. % Output is a partition of this list
k{ }ᵐ % For each partition (chunk) except the last,
↰₂ˢ % Select the items in the chunk that pass the predicate
l % Get the length of that
% (So now we have the list of the "weights" of each chunk)
;Wx % Remove the input expected weight from this list, and
Ė % the result of this should be empty.
% This verifies that the list of weights is either
% composed of all W-values, or is empty (when input is [0 0 0] for eg.)
∧.bhᵐ↰₂ᵐ % And, the first element of each chunk (except the first) should
% pass the predicate. This is another way of saying:
% "Items failing the predicate are allocated to the earliest chunk"
∧.t↰₂ˢl≤W % And, the final chunk (which we haven't constrained so far)
% should have weight ≤ the input expected weight
% This disallows putting everything in the final chunk and calling it a day!
∧ % (no further constraints on output)
```
[Answer]
# [Apl (Dyalog Unicode)](https://dyalog.com) 17 16 bytes [(SBCS)](https://github.com/abrudz/SBCS)
Thanks to Adám for saving me 1 byte.
```
w⊆⍨⌈⎕÷⍨1⌈+\⎕¨w←⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/@v8ahvql/wo941mnogZrCrXqizr4t6Un6FQn6egm6aLYgssS0pSk1Vf9S1ODUvMSknNdjRJwTIAap3jlQvTswpUdfketTRnva//FFX26PeFY96OoByh7cDmYZAtnYMkHdoRfmjtglAxn@gyv8KYJDGBbRY4VHvXAXX3IKSSoWczOISrupHvVvtDGq5jLhgigwU4BCrrCEQ4pEBY1zyBlB5XGaoOyYBoSOETFIHq7BVd1Sv5TKGq9EwVDDS1DAGEUCWgjGY0lTQ0DGEC5jARLmqjWwfdS4CmgK0BQA)
for explaination purposes I will leave up the 17 byte solution.
```
{⍵⊆⍨⌈⍺÷⍨1⌈+\⍺⍺¨⍵}
```
`⍺⍺¨⍵` aplies the predicate to the list returning a boolean vector
`+\` generates a running total
`1⌈` replaces leading `0`s with `1`s
`⌈⍺÷⍨` divides each element by the chunk size and rounds up
`⍵⊆⍨` partitions the original vector by this
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), ~~96~~ 92 bytes
Uses a named function `f :: a -> Bool` allowed according to meta consensus.
```
import StdEnv,StdLib
$l n|l>[]=last[[i: $t n]\\i<-inits l&t<-tails l|n>=sum[1\\e<-i|f e]]=[]
```
[Try it online!](https://tio.run/##JU67CsMwENvzFTeETgkkHUucqR0K2TLaHtw8ysH5UupLaSHfXtc0CCEJgdBAk@Pol3GlCbxDjugfy1Ogl/HCryJJh7csJ@CNWm0VuSBa4wlyAbbGYFMiowSggzSlOKRkN25VWL2ujZlSv80wWau0jb24tK0gB10VdUL1Z2XhmM3wTk2igjp@h5ncPcTy2sXzh53HYQ/7oR8 "Clean – Try It Online")
Expanded (with default highlighting to make comments show up):
```
$ l n // define function $ on `l` and `n`
| l > [] // if `l` is not the empty list
= last [ // the last element of ...
\\ i <- inits l // prefixes of `l`
& t <- tails l // matching suffixes of `l`
| n >= // where n is greater than or equal to
sum [1 \\ e <- i | f e] // the number of matching elements in the prefix
[i: $t n] // prepend that prefix to the application of $ to the rest of the list
]
= [] // if `l` is empty, return empty
```
[Answer]
## Haskell, 72 bytes
```
p#s|let l@(h:t)!a|sum[1|e<-h:a,p e]>s=a:l![]|n<-a++[h]=t!n;_!a=[a]=(![])
```
[Try it online!](https://tio.run/##jYzNCsIwEITvPsW2FZrQFlq91abY5whBthhIMY3FxFvePVZFUPCPGeYw@@0otAepdQhTYr2WDvSWqNrRCL09j7zysilUjfkEUrSWYa0jLrxpCswyrgRzkdnsImQcBSPziYYRBwMM9scFwHQajIMlENKWFBJYUeDiQ1/m8OIvXHXzH8Qjf6DlE/p2m7G0S68/awpx18/q7tnH4QI "Haskell – Try It Online")
```
p#s = (![]) -- main function that takes a predicate function 'p',
-- a size 's' and a input list without a name that is
-- directly passed as the first argument to function '!'
let l@(h:t)!a -- function '!' is a local function (so that 'p' and 's'
-- are in scope). Takes a list 'l' of at least one element
-- 'h' (and 't' being the rest of the list) and an
-- accumulator 'a'
|sum[1|e<-h:a,p e]>s -- if 'p' holds for more than 's' elements in 'h' and 'a'
=a:l![] -- put 'a' in front of a recursive call with the same list
-- 'l' and an empty accumulator
|n<-a++[h] -- else bind 'n' to 'h' appended to 'a' and
=t!n -- call '!' again with 't' and 'n'
_!a=[a] -- base case for '!'. If the input list is empty, return
-- a singleton list with 'a'
```
[Answer]
# [R](https://www.r-project.org/), 58 bytes
```
function(v,g,n,a=(cumsum(Map(g,v))-1)%/%n)split(v,a*(a>0))
```
[Try it online!](https://tio.run/##tVJNb8IwDD2vvyIXFBuZrWw3tCLxA8ZluwGH0qVdpJJWjYuYpv32LkkHggp2W5tG8fPziz/adLl4nnR5azLWlYE9FWQoTSBrd7bdwUtaQ0F7xMkURw8jg7YuNTtaOoZ0HiN2rCxbpyFKbRkicfFow6pQDSANHBnEJC7Wdco0rL@dx/02Kz5j3VaUC0lCbv02OC2uYNuhAy8FMVqGtnjlRzq@TxjlumTVnLXs7u7U/gMe5jH9E5IkLtVB1S7NKK8a0G5UYjorlSn4A8JMEb882Z99rgFbrfRm41HjoaV1prf6kjz0W9yJ578sZZBj8eaFJGmSYiJWkrh65UabItyGJDckTCLd3@fa2cskjp6lNbeNuq9arluG2kUwbKv3T@g5iC50tjZrI8mqOpFuDv7SnpgHceqpZLD3hYRcgLO@o@4H "R – Try It Online")
* -5 bytes thanks to @Giuseppe
[Answer]
# Java 10, ~~207~~ ~~186~~ ~~159~~ ~~148~~ 145 bytes
```
a->n->{var r=new java.util.Stack();for(int l=a.size(),c=0,j=0,i=-1;i++<l;)if(i==l||f(a.get(i))&&++c>n&i>0)r.add(a.subList(j,j=i*=c=1));return r;}
```
Java is definitely not the right language for this challenge (or any codegolf-challenge of course..)
-21 bytes thanks to *@O.O.Balance*
-3 bytes thanks to *@ceilingcat*
[Try it online.](https://tio.run/##3VE9b9swEN39K26yyVom7HZUKNRLgQItMrhb0eFEUe4pDGWQlAs30W93SVlwHA@ZgqIpiOPHveOR770G97hoqrujMug9fEWyDxMALH1wqAL4gIEUnNBv2oeEApRtazRaqNlt2ehYR/wEADgdOmchuE7nQ6of5mHadaWJ3Zr4qOgCGVF3VgVqrfg0bm6esC/kQ/Zi7Wcb9Fa7y6J06apHURSgQB5xUdhF8bBHB05a/evi1iagumM8r1vHyAYwEoWn35rxTMll1sQguVjlNJ/fmJxTzUhK8/hYMxRbHRhxPp3O56qwUyqW3Amsqgj5rkwfYE3sQO@kkivO81Efl/fHJEnSKCk0OaszSr5vqYL76AfbBEd2@/0H4Cjy5uCDvhdtF8QuQsFYlvgke9jZh4@3e@0cVXo8v2DZ2bREnkcG@QicrOuFErjbmQN7rtraOTwMBDkfC95Hgv/mF69yXqAf8svsPPibprGK43@gMMSbJ7Icifx9V9RPdJxASpitZ69FKbbKZmWMy3V9dS6f5Z5IfziR7if98Q8)
**Explanation:**
```
a->n->{ // Method with List & int parameters and List of Lists return
var r=new java.util.Stack();
// Result-list, starting empty
for(int l=a.size(), // Size of the input-List
c=0, // Count-integer, starting at 0
j=0, // Range-integer, starting at 0
i=-1;++i<l;) // Loop `i` in the range (-1, `l`]:
if(i==l|| // If this is the last iteration
f(a.get(i)) // Or if the black-box function is true for the current item
&&++c // Increase the counter by 1
>n& // If the counter is now larger than the size
&i>0) // and it's not the first item of the List
a.subList(j,j=i // Add a sub-List to the result from range [`j`, `i`)
// And set `j` to `i` at the same time
*=c=1));// And reset `c` to 1 at the same time as well
return r;} // Return the List of Lists as result
```
**Black box input format:**
Assumes a named function `boolean f(Object i)` is present, which is allowed [according to this meta answer](https://codegolf.meta.stackexchange.com/a/13707/52210).
I have an abstract class `Test` containing the default function `f(i)`, as well as the lambda above:
```
abstract class Test{
boolean f(Object i){
return true;
}
public java.util.function.Function<java.util.List, java.util.function.Function<Integer, java.util.List<java.util.List>>> c =
a->n->{var r=new java.util.Stack();for(int l=a.size(),c=0,j=0,i=-1;i++<l;)if(i==l||f(a.get(i))&&++c>n&i>0)r.add(a.subList(j,j=i*=c=1));return r;}
;
}
```
For the test cases, I overwrite this function `f`. For example, the last test case is called like this:
```
System.out.println(new Test(){
@Override
boolean f(Object i){
return (char)i == 'A';
}
}.c.apply(new java.util.ArrayList(java.util.Arrays.asList('A','b','A','b','A','A','A','b','A','b','A','A','b'))).apply(3));
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
vⱮTm⁵ḊœṖŒṘ
```
A full program taking the monadic black-box function as the first optional argument, the list as the second optional argument and the chunk size as the third optional argument which prints a Python representation of the resulting list of lists (to avoid Jelly's implicit smashing of lists containing characters).
**[Try it online!](https://tio.run/##y0rNyan8/7/s0cZ1IbmPGrc@3NF1dPLDndOOTnq4c8b///@VHjXuedQw11Hpv5JjEhA6Qsgkpf/GAA "Jelly – Try It Online")** (note that a list of characters is passed to a Jelly program by formatting it as a Python quoted string)
### How?
```
vⱮTm⁵ḊœṖŒṘ - Main Link: B, L, S
Ɱ - map across second argument with (i.e. for X in L):
v - evaluate as a monad with input (i.e. B(X))
T - truthy indices (e.g. [0,0,1,0,1,1,1,0,0,0,1,0,0]T -> [3,5,6,7,10])
⁵ - 3rd optional argument = S
m - modulo slice (e.g. [3,4,7,9,12,15,16,18,19,20]m3 -> [[3,4,7],[9,12,15],[16,18,19],[20]]
Ḋ - dequeue (e.g. [[3,4,7],[9,12,15],[16,18,19],[20]]Ḋ -> [[9,12,15],[16,18,19],[20]]
œṖ - partition right (L) at the indices in that
ŒṘ - print Python representaion
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 70 66 bytes
I use a structure to note the start of a sub-list, as C doesn't know about such things.
Thanks to ceilingcat for the suggestions.
```
t;f(a,s,c)l*a;int(*c)();{for(;a->v;a++)(t+=c(a->v))>s?t=++a->s:0;}
```
[Try it online!](https://tio.run/##tVBBTsMwELznFSsjiu24tIVbTVrlHVGEHDdpLUxTxY4lFOXtYZ0CEhJw42LvzO7s2KOXR62nG3PWtj/U8OT8wbT3p13yjbKmilzi3y71oW7A@a7XHiwMCUBozQF4kLDiEJTta@ArpM3Zg5tJ51XnoUVZX1njfOyPYOXkZUOVcEIzy5VEAeWaUSaHpu2oVMtdkCpNGfVppmmEjO3c3mdpisBt13KcbLR0RQnZ/JaB5ERsRoFFReYrJz@g/I9e9fvIekxGmSTzz17M5bmi@qQ64I7BAF3t@@6MIMvu8jsJ43XwVZkzjYXqjlrAVcARBDa/2MboPuPCpdkDOiDEZFCw27Arq3xrIhOKTcnmiUuHkoaSoiBMQkzM8pDFNGSIycVjsfiYQuD2pBQF2RJBGPtS3zoiQprGbCVceu8oKUtciAaowmUi2ovrd2f6n33HaXp8Bw "C (gcc) – Try It Online")
[Answer]
# MATL, 19 bytes
```
HyX$Ysi/Xk1y>+!w7XQ
```
Based on [jslip's excellent APL answer](https://codegolf.stackexchange.com/a/169537/8774).
MATL doesn't really have user-defined functions as such, but it does have a way to call out to the environment it's running on (MATLAB/Octave), so this uses that for the predicate function. Usage would be something like [this](https://tio.run/##y00syfmvnllcWlCQWqQe4VHx36MyQiWyOFM/Ituw0k5bsdw8IvD//2h1xyQQTHKEkEnqsVzGAA "MATL – Try It Online"), but that functionality is disabled online for security reasons, so here's a version that uses a hardcoded `isodd` predicate function instead: [Try it on MATL Online](https://matl.io/?code=toYsi%2FXk1y%3E%2B%21w7XQ&inputs=%5B0+1+1+0+1+0+0+1+0+0+1+0%5D%0A2&version=20.9.2).
```
H % Push the function name to be called, assumed to be
% stored in the H clipboard
y % Take the first input, push copies of it both below and above the
% function name
X$ % Call the function (say 'isupper') with the input as argument
% returns a boolean vector
Ys % Cumulative sum
i/ % Take the chunk size and divide each element by it
Xk % ceil
1y>+ % Turn the (initial) 0s to 1s
! % Transpose. Now we have a column vector specifying which chunk
% each input element should go into
w % Bring the other copy of the input on top
7 % Code for this function: '@(x){x.'}'
% i.e. place each chunk in a row vector and enclose it in a cell
XQ % 'accumarray' - split the input into chunks based on
% the given column vector, apply the given function to each chunk
% (which here just wraps it up as a cell), and accumulate the results
% in an array.
% implicit output
```
[Answer]
# JavaScript (ES6), 69 bytes
*Saved 3 bytes thanks to @tsh*
Takes input in currying syntax `(size)(predicate)(array)`.
```
s=>p=>g=a=>a.every(x=>p(x)?k--:++j,j=k=s)?[a]:[a.splice(0,j),...g(a)]
```
[Try it online!](https://tio.run/##lY7LDsIgEEX3/YrZFSJF1J3JYPwOwgIr1j4iTTGmfn1F46PaJmoyQJiZe@4tzMn4tMnrY3JwW9vtsPMoa5QZGpSG25NtzqQNLdLSVZkky8mkYAWW6OlKGb1Uhvu6ylNLBCso45xnxFDdTadg8@PeNqA0uHArraPUHbyrLK9cRnZkTkkLKKEFCYISpSmNoqBTSjB4q6/SgaCPmt3qJ8hjdUzOQM1@j3NXPe4BUjyHd/AfEUUPPEgcr2MWb8J5vVeH2/d99NEemC@e5ogQloL/CJyNkPu9kKy7AA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 57 bytes
```
->a,n,g{c=-1;a.group_by{|x|[0,c+=g[x]?1:0].max/n}.values}
```
[Try it online!](https://tio.run/##jZBBCsIwEEX3PcVspIppTHWnpNJzhCBJaOtCa6lUU5KcPYZqsa7q8Gf4DO8zMG0ne19Sn2QC1agyiibpQeCqvXXNSfbGassIUmtaMc2P6Z5wfBV6Uzv8EJeuuDvPIgjFGEewRUmmjYYMiOPosycIfhS4AMKUhC@aDvoPGuc8TSb07IXFc5mDhHfnMPVyFVK7MUUpxHnseMRxIdTZ2OGFtoGSDY47/wI "Ruby – Try It Online")
Anonymous lambda accepting input array `a`, chunk size `n`, and predicate `g`. Maintains a counter `c` of items matching predicate and groups items by the number of chunks already used up. Unfortunately, the initial value -1/n doesn't round up to 0, so we have to spend a few bytes to fix it.
[Answer]
# [R](https://www.r-project.org/), 100 bytes
```
function(L,K,P,s=sapply(L,P),y=cut(cumsum(s),seq(0,sum(s),K),,T))for(l in levels(y))cat(L[y==l],"
")
```
[Try it online!](https://tio.run/##bU27CsMwENvzFSbTHVzB7lz3B5IhQ7fSIRgbAs6jOTvEX@@6z6lICAkhtGYnTofs4mTCME/QUkMdseZ@WXwqsUNK2sQAJo4cR2AktneQ9AkNEl0Q3byCF8MkvN2sZ0iIpg/QXpPW/kZ1VWN2YMpOFUikI/0@d9zPEqt3LRQJ@aL66tP8GeQH "R – Try It Online")
outgolfed handily by [digEmAll](https://codegolf.stackexchange.com/a/169571/67312)
[Answer]
# [Python 2](https://docs.python.org/2/), 92 bytes
```
lambda a,c,p:reduce(lambda r,v:[r[:-1]+[r[-1]+[v]],r+[[v]]][sum(map(p,r[-1]+[v]))>c],a,[[]])
```
[Try it online!](https://tio.run/##jY3NCoMwEITvfYrcTHAL0d4CCj7Hdg@JP7RQbUhV7NOnKtYWKVhYZpb5hl37bC/3JvZVcvY3XZtCMw05WOXKostLvmQOeoUO1TGicPTZeiJwIU5O@OhqXmvLLaxUiDQn0IBIJLx116ZlFUeCGJargxpSKQ4rksCieeRfpbfut@VXe/9DkAXAAjPJZst@ZGYLCNgJ2Od2koxEeP8C "Python 2 – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 90 bytes
```
(s,p,r=[l=[]],n=s+1)=>g=a=>0 in a?g(a,(n=(n||s)-p(v=a.shift()))||r.push(l=[]),l.push(v)):r
```
[Try it online!](https://tio.run/##jY3BCoJAEIbvPcXenKFVtG7FGF58CfGwmqkhq@yaePDdNzWCkiRh@JmZ//9m7qITOlVl09qyvmYmZGRA84YriiqK4phL0nsPyc9JkO@yUjJxyUFwkARyGDTaDXQkHF2UtxYQcRiU0zx0AROPvHoNHeJJmbSWuq4yp6pzCOHAe/J730UYg3jerbouZ1/1N@3NtTn31k2A@wGs/znOGJEVWCM5KmdWMsmiC37skqUx3TdP "JavaScript (Node.js) – Try It Online")
Invoke as `F(2, x => x > 0)([0, 1, 1, 0])`
[Answer]
# Mathematica, 82 bytes
```
f[l_,s_,p_]:=Last@Reap[i=t=-1;Do[If[p@e,If[++i~Mod~s==0&&i>0,t++]];e~Sow~t,{e,l}]]
```
Ungolfed:
```
f[l_,s_,p_] := (* define a function that takes three *)
(* arguments *)
Last@Reap[ (* collect and return results which were *)
(* gathered by the procedural loop below *)
i=t=-1; (* initialize two counters *)
Do[ (* start iterating over the list *)
If[p@e, (* if element passes predicate *)
If[ (* then if preincremented i is 0 modulo *)
++i~Mod~s==0&&i>0, (* chunk size and i > 0 *)
t++ (* increment t *)
]
];e~Sow~t, (* finally sow the element tagged with *)
(* the current value of t *)
{e,l}] (* e references current element of list *)
(* l is the list itself *)
]
```
`l` is the input list; `s` is chunk size; `p` is an unnamed/anonymous/pure/lambda function that returns true/false operating on elements of the list.
`Last@Reap[...]` returns a list of lists of every element that was `Sow`-n inside of `...`. They are grouped into sublists by the second argument of `e~Sow~t` which is shorthand for `Sow[e, t]`.
I had to initialize counters to -1 to handle a chunk size of 1, otherwise I would need to check `Mod[i, s]` (`i~Mod~s`) equal to 1, which could never happen.
The rest of the code is explained in the ungolfed block.
]
|
[Question]
[
Your challenge is to write a program to print all the primes (separated by one or more whitespace characters) less than a given integer `N` with an asterisk (`*`) next to each twin prime. A [twin prime](https://en.wikipedia.org/wiki/Twin_prime) is a prime number that is either two more or two less than another prime.
(Hardcoding outputs is allowed, but it is not likely to result in very short code.)
Shortest code wins!
## Input
* `N` is always one of 50, 100, 1000, 1000000, or 10000000
## Output
* The output for input `50` should be
```
2 3* 5* 7* 11* 13* 17* 19* 23 29* 31* 37 41* 43* 47
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~81~~ 79 bytes
-2 bytes thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper) with a different way to detect if `k-2` is a prime which works with `k=2`.
Uses [Wilson's theorem](https://en.wikipedia.org/wiki/Wilson%27s_theorem) for the primality tests and the fact that \$p\$, \$p+1\$ and \$p+2\$ are coprime for most primes \$p\$.
```
P=k=q=1
exec"if P%k:print`k`+'*'[k<3:P%(k+2)|q/k];q=k+2\nP*=k*k;k+=1\n"*input()
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8A227bQ1pArtSI1WSkzTSFANduqoCgzryQhO0FbXUs9OtvG2CpAVSNb20izplA/O9a60BbIjskL0LLN1sq2zta2NYzJU9LKzCsoLdHQ/P/f0MDAAAA "Python 2 – Try It Online")
The output includes the input if it is prime, but this is fine since all testcases are composite.
## How?
We use the following result of Wilson's theorem:
$$
(k-1)!^2 \operatorname{mod} k =
\begin{cases}
1 & \text{if $k$ is prime}\\
0 & \text{otherwise.}
\end{cases}
$$
In the code `P` is used to keep track of \$(k-1)!^2\$ and `P%k` tests if `k` is a prime.
If this is the case, we print the output and update `q` to `k+2`.
If `k==q` at the `print` statement, we know that `k-2` was a prime and `k` is a twin prime.
`P%(k+2)` tests if `k+2` is a prime number. If we would use the exact same prime test as before, this would be `P*k*k*(k+1)*(k+1)%(k+2)`, but with our assumption that \$k\$, \$k+1\$ and \$k+2\$ are coprime for prime \$k\$, this gives the same result.
The assumption doesn't hold for `k=2`, but this is handled separately with `'*'[k<3:]`, which results in the empty string if `k<3`.
[Answer]
# [Python 2](https://docs.python.org/2/), 92 bytes
The [Sieve of Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) is used to compute primes. The main advantage here is its incredible speed (`N=10000000` is computed in just a few seconds).
```
n=input()
R=range(n)
for k in R:
if k>1:R[k+k::k]=(n+~k)/k*[0];print`k`+'*'[:R[k-2]|R[k+2]]
```
[Try it online!](https://tio.run/##JcqxCsMgEADQ3a@4LRoJUUeL/QhXOUiGppWDi4gdCiW/bgh58yu/9tnZ9c4hc/k2qUQMdeX3S7IS216BIDNELyBvQE/rYyJN3hMGyfogNdOYDD5KzdwWWvQwDulKk8P/dR1i79bcTg "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
ÆRµ+Ø+Ḥ¤ẒẸ”*xṭ)K
```
[Try it online!](https://tio.run/##ASoA1f9qZWxsef//w4ZSwrUrw5gr4bikwqThupLhurjigJ0qeOG5rSlL////NTA "Jelly – Try It Online")
## How it works
```
ÆRµ+Ø+Ḥ¤ẒẸ”*xṭ)K - Main link. Takes N on the left
ÆR - Yield the prime range until N
µ ) - Over each prime P between 2 and N:
¤ - Group into a nilad:
Ø+ - Builtin; [1, -1]
Ḥ - Unhalve; [2, -2]
+ - Add to P; [P+2, P-2]
Ẓ - Is prime?
Ẹ - Are any true? Either 1 or 0
”*x - Repeat "*" that many times
ṭ - Append to P, yielding [P, "*"] or [P, ""]
K - Join by spaces
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~32~~ 26 [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⍭¯2 2+⊢)⍤0∘⍸1⍭⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/X@NR71SdR71rHvVuUddS13/Uu8LwUe/aQ@uNFIy0H3Ut0nzUu8TgUceMR707QOKPejf/T3vUNuFRb9@jrmaItkPrjR@1TXzUNzU4yBlIhnh4Bv9PUzA1AAA "APL (Dyalog Extended) – Try It Online")
`⍳` **ɩ**ntegers 1 through `N`
`1⍭` Boolean mask indicating those that are primes
`⍸` `⍳` **ɩ**ndices of the trues (i.e. the primes)
`∘` then
`(`…`)∘0` on each scalar, apply the following tacit function:
`⊢` the argument
`¯2 2+` add `[-2,2]` to that
`1⍭` indicate the primes
`'*'/⍨` use that to replicate an asterisk (gives `""` or `"*"` or `"**"`)
`⍬⍴` **r**eshape into a scalar (lit. an array with an empty shape; gives `' '` or `'*'` or `'*'`)
`⍕,` prepend the string representation of the argument prime
since the inner function mapped scalars to vectors the overall result is a matrix
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ÆRðȮạe@2”*xṄ)
```
A monadic Link that accepts a number and prints the output with a new-line separator.
Uses the fact we never receive input, \$n\$, such that \$n-1\$ or \$n\$ are only on the lower side of a prime pair
(e.g. \$41\$ or \$42\$, which would miss the `*` from \$41\$).
**[Try it online!](https://tio.run/##y0rNyan8//9wW9DhDSfWPdy1MNXB6FHDXK2KhztbNP8fbj@x/FHDHKDA//@mBgA "Jelly – Try It Online")** (footer suppresses Link's return value).
### How?
```
ÆRðȮạe@2”*xṄ) - Link: n
ÆR - primes in [2,n] (call this "Primes")
ð ) - for each (p in Primes) do this f(p, Primes):
Ȯ - print p (plus no newline)
ạ - (p) absolute difference (Primes)
2 - two
e@ - (two) exists in (the absolute differences)?
”* - '*' character
x - ('*') times (existence of two)
Ṅ - print that (plus a newline)
```
[Answer]
# [J](http://jsoftware.com/), 41 bytes
```
[:(,&":"0' *'{~1+./@p:2 _2+/])i.&.(p:inv)
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o600dNSUrJQM1BW01KvrDLX19B0KrIwU4o209WM1M/XU9DQKrDLzyjT/a3KlJmfkK6QpmBpAWOq6urrqMEFDA4P/AA "J – Try It Online")
## how
* `i.&.(p:inv)` Returns every prime less than or equal to the input.
* `2 _2+/]` Create a 2 row table, adding and substracting 2 to each prime. Eg,
for n=50:
```
4 5 7 9 13 15 19 21 25 31 33 39 43 45 49
0 1 3 5 9 11 15 17 21 27 29 35 39 41 45
```
* `1...p:` Is each a prime?
```
0 1 1 0 1 0 1 0 0 1 0 0 1 0 0
0 0 1 1 0 1 0 1 0 0 1 0 0 1 0
```
* `+.` Reduce each column by "or":
```
0 1 1 1 1 1 1 1 0 1 1 0 1 1 0
```
This mask tells which are the twin primes.
* `' *'{~` Convert 1 to `*` and 0 to .
* `,&":"0` For each, append `,` to the input after converting to string `&":"0`:
```
2
3*
5*
7*
11*
13*
17*
19*
23
29*
31*
37
41*
43*
47
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 107 bytes
```
p=lambda x:0<all(x%i for i in range(2,x))<x
f=lambda n:[str(i)+'*'*(p(i-2)|p(i+2))for i in range(2,n)if p(i)]
```
Subtracted 2 bytes for f=
A port of my solution to the previous challenge, with a slightly better p function.
[Try it online!](https://tio.run/##ZYuxCgIxEAV7v2IbuX05hSMiyHF@iVhENLoQ98KaIoL/Hq@xsppiZvK7PGbdHbK1lo8pPC/XQHUcppAS17VQnI2ERMmC3m/sNxWY6ir@Wh1Pr2Is6DvXOc4sW4/Pgt4Df7NCIi0S55ZNtLCLvB@A9gU "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), `-S` 32 bytes
```
o fj
äÏ-X¥2Ãp0
íVíVé '+ Ï?X+'*:X
```
[Try it online!](https://tio.run/##y0osKPn/P18hLYvr8JLD/boRh5YaHW4uMOA6vDYMhFYqqGsrHO63j9BW17KK@P/f1EBBNxgA "Japt – Try It Online")
Notably, this works for the required inputs, but not a few others like 12.
Explanation:
```
o fj
o # Create the range [0 ... input]
fj # Keep only the primes
# Store as U
äÏ-X¥2Ãp0
ä Ã # Create an array by mapping each pair in U through:
Ï-X # Get the difference
¥2 # Check whether it's 2
p0 # Add 0 to the end of that array
# Store as V
íVíVé '+ Ï?X+'*:X #
Vé # Rotate V 1 item to the right
Ví '+ # Add each item in rotated V with the same index in original V
í # For each item in U:
Ï? # If the same index in V is not 0:
X+'* # Add "*" to it
:X # Otherwise don't change it
# Implicit output, -S flag joins with spaces
```
I feel like there's a better way to accomplish `Ï?X+'*:X` but I haven't found one
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 172 bytes
```
$L=@{};($N=2.."$args")|%{$c=2;$k=$_
for(;($k*$c)-le$N[-1]){if(!($L|% c*y($k*$c))){$L[$k*$c]=1};$c++}}
$x=$N|?{!$l.$_}
$x|%{if((($_+2)-in$x)-or(($_-2)-in$x)){"$_*"}else{$_}}
```
[Try it online!](https://tio.run/##NY1BCoMwFET3PUUNI@QrEXUroT2AeAGRUCS2YqhFF7XEnD1NS7ubx8xjHvNTL@tNG@M9anm2ruJoZJllDJflujLaY4telhUmCXUY5oWHxZSgJ2E0mlYUHdlx4BFHvcfHPnn9aiKLuv3mThauQp@mzh2wSTT7yUYwGdSHw0PwOYdKSxLjHRuJcBNY/Jksg0qY02bVNljOe1/kef4G "PowerShell – Try It Online")
Thanks to @mazzy for ~70 bytes
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 91 bytes
Inspired by [Wasif](https://codegolf.stackexchange.com/a/220011/80745)
```
($x=($N=2.."$args")|?{!($N-lt($c=$_)|?{!($c%$_)})})|%{"$_"+'*'*(($_+2)-in$x-or($_-2)-in$x)}
```
[Try it online!](https://tio.run/##LYhBCoAgEADfkqy0JkZ5l37QFyQiKpAKDRLKt28eZC4zc53P4sO2OEeEEA3CaHTbMpj8Gpj4hrfKS7kbYTZgy5h51pT5@MvAMlk3dYMIVmqh9gOiOn0uVUokIuq77gc "PowerShell – Try It Online")
The script outputs correctly for the allowed input and incorrectly in the general case (see last twins for 12)
Less golfed:
```
$Numbers = 2.."$args"
$primes = $Numbers | Where {
$current = $_
$dividers = $Numbers -lt $current | Where {($current % $_) -eq 0}
!$dividers # true if the $current is a prime
}
$primes | ForEach {
"$_"+'*'*(($_+2) -in $primes -or ($_-2) -in $primes) # format output number
}
```
[Answer]
# [Julia 0.4](http://julialang.org/), 61 bytes
I'm using Julia 0.4 because `primes` was a built-in
It works with a more recent version of Julia and the package `Primes.jl`
This approach will fail sometimes when `N` or `N-1` is prime, which isn't the case for any of the requested inputs
```
x->map(i->print(" $i"*"*"^(i+2∈p||i-2∈p)),(p=primes(x);))
```
[Try it online!](https://tio.run/##yyrNyUz8n2b7v0LXLjexQCNT166gKDOvRENJQSVTSQsI4zQytY0edXQU1NRk6oIZmpo6GgW2QGW5qcUaFZrWmpr/0zRMDTS5wDpz8jSQWWkahgYQoPkfAA "Julia 0.4 – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 101 bytes
```
@p[grep"".(1x$_)!~/^(11+)\1+$/,2..$_]=(1)x$_;
$_=join$",map$p[$_-2]+$p[$_+2]?"$_*":$_,grep$p[$_],2..@p
```
[Try it online!](https://tio.run/##HYxLCsIwEEDPYphFYj7NBLpRir2AJ6hxcFGkUpuhirjy6I62u8d78Lifx1qk5e4696xU0PgGMptPddaI1pzQQuVSCEC50Wj@cQ/U3MowgXL3CwN3QD5lu4JN@aCAtmoH5JbjavMyaFkEY4zfws@hTA/xx1cdMIrnHw "Perl 5 – Try It Online")
Uses the somewhat known `/^(11+)\1+$/` regexp to detect primes.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 70 bytes
```
If[FreeQ[NextPrime[a=Prime@#,{-1,1}]-a,2|-2],a,a""]&/@Range@PrimePi@#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773zMt2q0oNTUw2i@1oiSgKDM3NTrRFkw7KOtU6xrqGNbG6ibqGNXoGsXqJOokKinFquk7BCXmpac6gJUFZDooq/0HMvNKHNKjDQ0MDGL//wcA "Wolfram Language (Mathematica) – Try It Online")
-1 byte from @att
[Answer]
# JavaScript, ~~136~~ 119 bytes
```
n=>(a=(R=n=>[...Array(n).keys()])(n)).filter(x=>a[~x]=+R(x).filter(y=>x%y<1)).map(x=>x+" *"[a[~x+2]|a[~x-2]]).join(' ')
```
```
f=
n=>(a=(R=n=>[...Array(n).keys()])(n)).filter(x=>a[~x]=+R(x).filter(y=>x%y<1)).map(x=>x+" *"[a[~x+2]|a[~x-2]]).join(' ')
console.log(f(100));
```
*Saved 17 bytes thanks to [tsh](https://codegolf.stackexchange.com/users/44718)*
[Answer]
# [R](https://www.r-project.org/), ~~99~~ 87 bytes
With some help from [Robin](https://codegolf.stackexchange.com/users/86301/robin-ryder) and improvements from [Dominic](https://codegolf.stackexchange.com/users/95126/dominic-van-essen):
```
for(n in 2:scan())if(sum(!n%%2:n)<2)cat("
",n,"*"[sum(!n%%2:n-2)==1|!sum(!(n+2)%%2:n)])
```
or, when detailed:
```
for(n in 2:scan()) #range
if(sum(!n%%2:n)<2)#prime number
cat(" #create space
",n, #print n
"*"[sum(!n%%2:n-2)==1| #print * for previous prime
!s(!(n+2)%%2:n)]} # or for next prime
```
[Try it online!](https://tio.run/##K/r/Py2/SCNPITNPwciqODkxT0NTMzNNo7g0V0MxT1XVyCpP08ZIMzmxREOJS0knT0dJSykaSVLXSNPW1rBGESykkadtpAnRE6v539TA4D8A "R – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~24~~ 22 bytes
*Edit: -2 bytes thanks to Razetime*
```
m?o`:'*ssȯ#2`m₁¹≠₁
fṗḣ
```
[Try it online!](https://tio.run/##yygtzv7/P9c@P8FKXau4@MR6ZaOE3EdNjYd2PupcAKS50h7unP5wx@L///8bGhgYAAA "Husk – Try It Online")
[Husk](https://github.com/barbuz/Husk) doesn't particularly like mixing numerics + characters.
```
fṗḣ # helper function: primes up to input
m?o`:'*ssȯ#2`m₁¹oa-₁ # main function:
m ₁ # for each element in primes up to input
oa- # get the absolute differences to
`m₁¹ # all primes up to input
ȯ#2 # and count how many '2's there are:
? # if it's zero
s # convert it to a string
o`:'*s # otherwise convert it to a string & prepend with '*'
```
[Answer]
# [R](https://www.r-project.org/), ~~88~~ 87 bytes
```
p=2;for(y in 3:scan())p=c(p,y[sum(!y%%2:y)<2]);for(z in p)cat(z,"*"[2%in%abs(z-p)]," ")
```
[Try it online!](https://tio.run/##HcpBCoAgEADAr5gg7IaB2a3yJeHBhKBDtmQd1s8bNee5aiVnp@28gMWexDDmGBIgkotAmpf8HNCwUnZknK3Hv5avEsZwQ9GylYtVe1JhzVA6Qq@lkFh7Y@oL "R – Try It Online")
I wanted to try a different approach to [Xi'an's answer](https://codegolf.stackexchange.com/a/220055/95126)...
~~Frustratingly, though, after golfing & golfing I still can't get rid of that last pesky byte...~~ Got it!
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~81~~ 80 bytes
A port of [ovs' answer](https://codegolf.stackexchange.com/a/219992/58563). Expects a BigInt.
```
n=>{for(s=p=k=2n;k<n;p*=k++)p%k?s+=' '+(x=k-2n,p/x%x+p%~-~k?k+'*':k):0;return s}
```
[Try it online!](https://tio.run/##BcFBDsIgEADAr/RCgCKKPZaufUtTweg2ywaqITH26zjzWj5LWfOTd0vpHlqERnD7xpRVAQaEgTxO5LkHNEazwLkYkJ00qgLagU58qaIaFoc9cEYjezmiHp3PYX9n6sqvrYlK2sJ5Sw8V1dU5R1q3Pw "JavaScript (Node.js) – Try It Online")
Or **77 bytes** with `eval()`, as suggested by @EliteDaMyth:
```
n=>eval("for(s=p=k=2n;k<n;p*=k++)p%k?s+=' '+(x=k-2n,p/x%x+p%~-~k?k+'*':k):s")
```
[Try it online!](https://tio.run/##BcFRDoMgDADQqywmBLBjY37qOs9CHCxbTWnEGL68OnvvF45Qlu0ru@P8ji1hY3zFI6ymS3kzBQUJB57oyZP0SABWFM0FUF80mIrkBr7KvaoKok530kygez2SHUtn25K55DXe1vwxyTy892xt@wM "JavaScript (Node.js) – Try It Online")
---
# [JavaScript (V8)](https://v8.dev/), 91 bytes
```
n=>{for(k=1;++k<n;)(g=d=>{for(i=d;i%--d;);return~-d})(i=k)||print(g(i-=2)*g(i+=4)?k:k+'*')}
```
[Try it online!](https://tio.run/##LcjBCsIwDADQr5ElK4FOPIgx7luGtaMG6oh1F7f9et3B04P3HObhfbc0FZrPNUrNcvvGl4FKx87pNTPCKOG/SQKnA1FgZHuUj@WNwor7Ky7LZCkXGCGRHLHddXLCXi/qmrbBtUbovPdYfw "JavaScript (V8) – Try It Online")
[Answer]
# [Raku](http://raku.org/), 54 bytes
```
{put map {$_~'*'x?is-prime $_+(2|-2)if .is-prime},^$_}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/uqC0RCE3sUChWiW@Tl1LvcI@s1i3oCgzN1VBJV5bw6hG10gzM01BDyZaqxOnEl/7P03D0MBA8z8A "Perl 6 – Try It Online")
[Answer]
# [SageMath](https://doc.sagemath.org/html/en/index.html), 88 bytes
Added 14 bytes to fix an error kindly pointed out by [Kjetil S](https://codegolf.stackexchange.com/users/64733/kjetil-s).
```
def f(n,b=1,c=2):
while c<n:a,b,c=b,c,Primes().next(c);print(str(b)+'*'[:2in(b-a,c-b)])
```
[Try it online!](https://sagecell.sagemath.org/?z=eJwNyLEOQDAQANC9X9HNHUeQWIp_sIvBVRtNuEg14fMZ3vI257UHIR4bsmOLRulnD4fTdhCzEv_5oymG092Albg3gcX-ikES3CkCY5Hl2WzaIMDlSrZkXFApD12NH1NMG38=&lang=sage&interacts=eJyLjgUAARUAuQ==)
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-S`](https://codegolf.meta.stackexchange.com/a/14339/), 25 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
o fj
äÏ-X¥2
gVí|Vé)ð²_+'*
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVM&code=byBmagrkzy1YpTIKZ1btfFbpKfCyXysnKg&input=NTA)
```
o fj - primes up to N
äÏ-X¥2 - difference of each consecutive primes == 2?
g ... _+'* - add an asterisk to the elements at the indexes obtained with @ :
Ví|Vé) @ pair array with array rotated then reduce by OR
ð² @ truthy values when passed trough f(square)
-S flag to join with spaces
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÅPÐδα2δå'*×øJ»
```
[Try it online.](https://tio.run/##ASMA3P9vc2FiaWX//8OFUMOQzrTOsTLOtMOlJyrDl8O4SsK7//81MA)
Or alternatively:
```
ÅP©ε?®yα2å'*×,
```
[Try it online.](https://tio.run/##ASsA1P9vc2FiaWX//8OFUMKpzrU/wq55zrEyw6UnKsOXLP//NTD/LS1uby1sYXp5)
Or alternatively (only works in [the legacy version of 05AB1E](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b)):
```
ÅPÐδα2QOĀ'*×+»
```
[Try it online.](https://tio.run/##ASEA3v8wNWFiMWX//8OFUMOQzrTOsTJRT8SAJyrDlyvCu///NTA)
All three programs above output newline-delimited.
I have the feeling a 13-byter is possible, but I'm unable to find it thus far.
**Explanation:**
```
ÅP # Push a list of primes in the range [2, (implicit) input-integer]
Ð # Triplicate this list
δ # Pop two of them, and apply double-vectorized:
α # For each prime, get its absolute difference with the list of primes
δ # For each list of absolute differences:
2 å # Check if a 2 is among them (1 if truthy; 0 if falsey)
'*× '# Repeat "*" that amount of times as string
ø # Create pairs with the remaining list of primes
J # Join each pair together to a string
» # Join this list by newlines
# (after which the result is output implicitly)
ÅP # Push a list of primes in the range [2, (implicit) input-integer]
© # Store it in variable `®` (without popping)
ε # For-each over each prime:
? # Pop and print the prime (without trailing newline)
® # Push the prime-list from variable `®`
yα # Get for each its absolute difference with the current prime `y`
2å # Check if a 2 is in this list of absolute differences
'*× '# Repeat "*" that amount of times as string
, # Pop and print this string with trailing newline
ÅPÐδα # Similar as in the first program above
2Q # Check for each inner-most value if it's equal to 2
O # Sum all inner list of checks
Ā # Check which sums are >= 1
'*× '# For each, repeat "*" that amount of times as string
+ # Append it to each integer in the remaining list of primes
» # Join this list by newlines
# (after which the result is output implicitly)
```
[Answer]
# C, ~~108~~ 106 bytes
-2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat).
```
f(n,i,j,d,e){for(d=e=i=2;j=n>i;j/i?printf(i-d-2?" %d":d-e-2?"* %d*":" %d*",i),e=d,d=i:1,i++)for(;i%++j;);}
```
[Try it online!](https://tio.run/##VY7LDoIwEEXX8BVNDaaFwQeJG2rhW7BTYAgWA@iG8O1Y3Lm6Z84kd8akjTHbgZzp32jZfZqRhlNbhH@qp4d3Wy0cEHSAYOVSD6NAbTXpTHXaFaS6M5WvkdxcC0oxzUrOIuQ5pnbn2A8xz/kvgCRYjYCa8itQksi9TlGUJJ2Sat18C3tW5MQO1dgYYKatxjj2/JHhEgb7wqkwmEzlasH9JWBHJ73xb/pYt9vlCw "C (gcc) – Try It Online")
The only input parameter which the function requires is n. The hardest part was avoiding duplication of \* after numbers, and there ought to be a better way to do that.
]
|
[Question]
[
**This question already has answers here**:
[De-interleave log lines: HARD MODE](/questions/210051/de-interleave-log-lines-hard-mode)
(7 answers)
Closed 3 years ago.
You've inherited a server that runs several apps which all output to the same log.
Your task is to de-interleave the lines of the log file by source. Fortunately, each line begins with a tag that indicates which app it is from.
## Logs
Each line will look something like this:
```
[app_name] Something horrible happened!
```
* App tags are always between square brackets and will contain only alphanumeric characters and underscores.
* All lines will have an app tag at the beginning. There will not be preceding whitespace or any other characters.
* There will always be at least one space after the app tag
* App tags are nonempty
* There may be other square brackets later on any given line.
* There may or may not be a message after the tag
* The log may be empty
* There is no limit to how many unique app tags will be present in the file.
## Example
An entire log might look like this:
```
[weather] Current temp: 83F
[barkeep] Fish enters bar
[barkeep] Fish orders beer
[stockmarket] PI +3.14
[barkeep] Fish leaves bar
[weather] 40% chance of rain detected
```
Which should output three different logs:
```
[weather] Current temp: 83F
[weather] 40% chance of rain detected
```
```
[barkeep] Fish enters bar
[barkeep] Fish orders beer
[barkeep] Fish leaves bar
```
```
[stockmarket] PI +3.14
```
You are not given the names of the app tags ahead of time. You must determine them only by analyzing the log file.
## Rules and Scoring
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins.
* Standard rules and loopholes apply
* Use any convenient IO format, provided that each input line is represented as a string, not a pre-parsed tag + message. Non-exhaustive list of allowed outputs:
+ Several files named after each tag
+ Several lists of strings
+ One concatenated list of strings containing lines grouped by tag with or without a separator (the separator must not begin with a tag)
+ Same as above, but to stdout or a file.
* The order in which separated logs are output is irrelevant, however the log lines within each group must preserve the order they were found in the original file
[Answer]
# [Bash](https://www.gnu.org/software/bash/), ~~4~~ 11 bytes
Added 7 bytes to fix a bug kindly pointed out by [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy).
```
sort -sk1,1
```
[Try it online!](https://tio.run/##Xc49C8IwGATg3V9xi5MfWNpBXIWCm3vpkKYnKbFNefOqPz9GEYeu93DHdSa6lGIQxS76Yluk1Lxo1FFanB8inBTKcT7hWNarpjPiyblFPUSHjJSIHC4lSP8VMlPUYP34cW1xvWBT7otq2bjTPPnb@j@oDmtYZyZLhBvEDBN6Kq2yfwM "Bash – Try It Online")
Performs a stable sort (the `s` command line argument) based on the first field (`k1,1`) separated by whitespace.
[Answer]
# [R](https://www.r-project.org/), ~~50~~ 46 bytes
```
function(r)split(r,substr(r,1,regexpr("]",r)))
```
[Try it online!](https://tio.run/##bY5BC4JAFITv/YrHQrCSRGKHCDoFQrfu4mFdxxR1lbfP6t@bFdTF2zDfzDA8laepHJ2VuneaAz@0tWgO/Zh74VlEIeOG58BaZSrkIAimUlut0geMVOCMziMznJCgG450iBMVrlSaG26AIaOk9hXNHOxpNhdgz8UHAl/qpbdN945IRtcLbeJttF/otTB3/Ed/h/a7NdnKOAvqS2JTOyogsIJCzfdf "R – Try It Online")
Outputs as a `list` with each element `name`d with the `[tag]`. Each list element maintains order within its tag. Returns an empty named list `named list()` for empty input.
-2 bytes each thanks to Robin Ryder and Dominic van Essen!
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 3 bytes
```
ohc
```
[Try it online!](https://tio.run/##Zc4xC8IwEAXgv3IEnBRR2kFchYKbe8gQkycptUm4nIq/PtYOXbre997j8ldCrSm4WrXSH1gJYEOXFzOikGDMZzo1ndopfbc8ANlQ15dAE4MLTce1JfazATMWSW4Y/wkxdLvSttkf23XrCfvGsrj80h425IKNDpQexLaP5CFwAq/MDw "Pyth – Try It Online")
The input format is a list of strings:
```
["[weather] Current temp: 83F","[barkeep] Fish enters bar","[barkeep] Fish orders beer","[stockmarket] PI +3.14","[barkeep] Fish leaves bar","[weather] 40% chance of rain detected"]
```
How the code works:
* `o`: Order by
* `h`: The first element of
* `c`: Each string split on spaces
[Answer]
# [Python](https://docs.python.org/), 44 bytes
```
lambda a:sorted(a,key=lambda l:l.split()[0])
```
**[Try it online!](https://tio.run/##bY/BasMwEETv/oq5lNg0hBTnUAw@FQK99e6IotjrWliWxGrTkK93FdOEFnKd93bYCRcZvCvnvj7MVk/HTkNX0bNQl@v1SJf6N7WV3cRgjeRFs1XFbI2jiBpNBqyaM2kZiBXeTszkBEJTqPBa7lfrRThqHomCwt7EAckgjkjhQ@y5WzDRjUfx7ThdJVH4eMdzuXnZPby1pL/pb/X9td32Ce2gXUvwPVgbh46E2jQ1qSrLes9giicrxn19XgciOX2@TC2q1AYENk7y/1Yx/wA "Python 3 – Try It Online")**
Loose I/O allows us to take, and result in, a list of lines. Since we do not have to separate the groups, the problem is reduced to performing a stable sort of the lines on the prefix of each line up to the first space, `split()` will split at some other white-space characters too but none can be present in the application tag portion.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 10 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?") ([SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set"))
Anonymous tacit prefix function. Takes a list of character lists as argument. Returns a matrix of character lists, with one log in each row.
```
⊢⊢⌸⍨≠⊃⍤⊆¨⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1HXIhDq2fGod8WjzgWPupof9S551NV2aAVQ@H/ao7YJj3r7wKJrHvVuObTe@FHbxEd9U4ODnIFkiIdn8P809ejy1MSSjNSiWAXn0qKi1LwShZLU3AIrBQtjN3UF9eikxKLs1NSCWAW3zOIMBaB0alGxAlAQUy6/KAUsl5oKliwuyU/OzgWpKIlVCPBU0DbWMzTB1JWTmliWCjcR7hYTA1WF5IzEvORUhfw0haLEzDyFlNSS1OSS1BR1AA "APL (Dyalog Extended) – Try It Online")
`⊢` on the argument,
`≠` use the non-spaces to…
`⊆¨` partition each list into a list of lists (removes spaces, keeps runs of non-spaces),
`⊃⍤` then keep the first [of each] (i.e. the tags),
`⊢⌸⍨` use those as keys to group…
`⊢` the argument
[Answer]
# vim, ~~13~~ 11 bytes
```
:sor/\w\+/r
```
bugfix and byte save thanks to @Dingus!
[Try it online!](https://tio.run/##bc5BC4JAEAXge79iLp4EtTQIb1EIHYLuuod1faGYrsyuSr9@s4gO0nU@3nszOZcazWExF37IzuUzpK3Bgk4jM3pLFt2Q0iHONnkpuQUGQVljaloQbGg5rkVz9RFgIWO1aru3W0G3C/lxsE3WiQfkhG/X74Mk8kjVslcgfSeWTU8VLJRFtarNj9ezoHGg8kl7789mEEW7Fw "V (vim) – Try It Online")
[Answer]
# Scala, 26 bytes
```
_.sortBy(_.split("]")(0))
```
Returns a `List[String]` with no separator in between, but it is sorted by the tag.
[Try it in Scastie](https://scastie.scala-lang.org/DYJSw0dyR8yJIZh3G8h5zQ)
---
# Returns a `Map[String,List[String]]`, 26 bytes
```
_ groupBy(_.split("]")(0))
```
Takes a list of strings and returns a `Map[List[String]]` where the keys are the tags and the values are the logs associated with that tag.
[Try it in Scastie](https://scastie.scala-lang.org/ABnrhO5mSPG2Hg11ru4O4A)
---
# Previous solution, 66 bytes
```
_ groupBy{case s"[$t]$r"=>t}map(_._2 mkString "\n")mkString "\n"*2
```
[Try it in Scastie](https://scastie.scala-lang.org/9riZ2dRnSqaOSWdZSmd0dg) (for whatever reason, `s` doesn't work in TIO)
Each app's logs are separated by 2 newlines (I might be able to save 2 bytes if it just had to be the one newline character). The input is a list of strings, and the output is one big string.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes
```
Σ#¬
```
**Input and Output** is a list of logs.
Explanation:
```
Σ#¬
Σ Sort by:
# Split (each log) by spaces
¬ Head (which is the tagname)
```
This also keeps the order of the logs, as required.
[Try it online!](https://tio.run/##Zc4xDoJAEAXQq0zWWGmMBgpja0JCZ0@2WHa/YYOwZHbUA9l6Cg/glVakoKGd9//PhGhqj5S@r9XnnVKlqieMNGBN5zszeiFBN5zomBVqq6racAsMmgofGxoZHGk8Li2wmwyYMEqwbfdPiKZLSZtsd8iXrRvMA/Pi/Eu@X5NtTG9B4UpsfE8OAitwSv8A)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~14~~ 13 bytes
```
O$`(\w+).*
$1
```
[Try it online!](https://tio.run/##Xc5BC4JAFATgu7/iHQwqQRI9RFdB6FR3W2jbnVDMVd6@8udvFtHB63zMMAxpnQ7hFF/XlynZpNsozkKoJ2hpwIrKJzOckKAfD7TPq6i@ae6AUVHV@oZmBHuaw6UMbL8CzORlMF3/cVF0PlKSp1mxbDygX/ht/R8UuxWZRjsDGu7EunVkITAC@wY "Retina 0.8.2 – Try It Online") Explanation: Since no output group separator is required, the lines are simply sorted by app tag, which is achieved by capturing the match on `\w+` and specifying `$1` as the sort key. Sort in Retina is stable, so that lines with the same prefix will retain their order. Edit: Saved 1 byte thanks to @FryAmTheEggman for pointing out an easier way to match the app tag. Note that although the match doesn't include the leading `[`, all of the lines start with `[`, so that doesn't affect the result of the sort.
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), ~~62~~ 58 bytes
Saved 4 bytes thanks to [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)!!!
```
{a[$1][i++]=$0}END{for(k in a)for(j in a[k])print a[k][j]}
```
[Try it online!](https://tio.run/##XY@7CsJAEEV7v2IKBSUoiQqKYOUDbMRXt2wxJhOzWd0Nk9UU4rfHGEQk3eUe7mEGC12WTxTtQArleXLe9l@r7fIZW@5qUAaw94lpHYWWvYyVcXUUqXyVpSgIXUIsYXFnpoo5umUzGE4XLZE7G@obsiYnYQPH/eHUD1ri/Gkok7BWeQLVhjiHqmwSy1FNiLjh2m3AGw2CcXNxJXzQ1/U7bOx3IEzQhAQ2BsbqlYgchY6ihnYFw8Ek@Juur9ZGUCAbZS5v "AWK – Try It Online")
Stores all lines in a 2D associative array `a`. The first key is the first field (separated by whitespace). So all lines that begin with the same field are stored together. The second key is an increasing integer index. The most verbose part is the `END` action which prints the contents of `a` grouped by first field in order of appearance.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Takes input as an array of lines, outputs a 2D-array.
```
ü_¸g
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=cVI&code=/F%2b4Zw&footer=Vm1xUilxUrI&input=Ilt3ZWF0aGVyXSBDdXJyZW50IHRlbXA6IDgzRgpbYmFya2VlcF0gRmlzaCBlbnRlcnMgYmFyCltiYXJrZWVwXSBGaXNoIG9yZGVycyBiZWVyCltzdG9ja21hcmtldF0gUEkgKzMuMTQKW2JhcmtlZXBdIEZpc2ggbGVhdmVzIGJhcgpbd2VhdGhlcl0gNDAlIGNoYW5jZSBvZiByYWluIGRldGVjdGVkIg)
[Answer]
# [Io](http://iolanguage.org/), 73 bytes
```
method(i,i map(split first)unique map(I,i select(split first==I))flatten)
```
[Try it online!](https://tio.run/##Zc9Ba8MwDAXgvyIChZiW0tEeSiGnQiC33bscvOSZiDq2Jyvdz8@yHEqh1/c9CYnj7OhS0dc8QofYl7xjGm0qc/Ks5Fiyminwz4Q1bhbO8Oj0tVFVjTHOW1UEM7vSc9ayuP3C6gBp6TqJICgpxnSh87EudsXt28odSC3VnAdaGJJpCd8tSr8asGLW2N3H/4a29NnQ9rj/OL1PedgHnhuft5wOG@oGGzpQdCSWA/XQ5SH0hTGUhIP6MP8B "Io – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 16 bytes
```
*.sort:{~m/\w+/}
```
[Try it online!](https://tio.run/##Xc7PCoJAGATwu0/xXYpK0EKJMDoFQrfu5mFbRxT/8u2WSNSLdevFNovo4HV@zDAtuFybqqdpSjuzcFTDOrg9KvfU2e7dbK10VuY11Pz1dJToTdRB6Awc0/7CjFqTRtUGtPFCKzoLLoA2pjBXGQ0IVjSEY2k4@QowkNKNLKqP65iOB7I9Z@WPGyXEFb@t/wN/OSGZiVqCmpRY5DUl0JAayRs "Perl 6 – Try It Online")
Sorts by the first string of alphanumeric characters, which should be the app name
[Answer]
# [Python 3](https://docs.python.org/3/), ~~148~~127 bytes
```
a={}
try:
while 1:
b=input();c=b.split("]")[0]
if 1-(c in a):a[c]=[]
a[c]+=[b]
except:[print(e)for k in a for e in a[k]]
```
[Try it online!](https://tio.run/##XY7BasMwEETv/oolULAJDTHOobjoVAj01rvQQZbHSNiRhLxpGkq/3ZVN6SG3x7zZZeKdbfDNsmjx/VNwurcF3aybQHUm6oTz8cpl9WpEd5jj5LjcqV0ljypbN1D9XBpynnTVammUkGu@0l7IThX4Mojcypic5xLVEBKNW59WxIZyVGpZ5A2aLZKit2tK8EyMS2zppTkXstNpBKKis5stZYk0Uw4fTUj9ZoCsZg5mvKyeFX2807451KfHiwn6E3@//hecjk9krPYGFAZKOq/swTCM/hc "Python 3 – Try It Online")
[Answer]
# [V (vim)](https://github.com/DJMcMayhem/V), 5 bytes
```
úr/?]
```
Note: The `?` above is in-place of the unprintable byte \$\text{\x}81\$ (the "No Break Here" control character).
**[Try it online!](https://tio.run/##Xc49CsJAFATg3lNMYyX4Q1KIrRCwsw9brJuRhJjd8PYZD@CtLPVgaxSxSDsfM8yQ0ushq@fdpFTeaLWmGOyvIvQKZdfvsM2KWXmy0pK9QdHEGiNSIsZwKkGqr5AjRQ2u7T6uBscDFtlyk08bF9qBv63/g3w9h6utd0Q4Q2zjUVHplNUb "V (vim) – Try It Online")**
Note that this works with a lack of spaces (even one directly after the first `]` bracket), with the presence of `[]` brackets in the log message, and with the presence of an untagged application, [Try it online!](https://tio.run/##XY47CsJAEIb7nGIaK8EHSSG2QsDOfhhks5mQJWYTZsd4AG9lqQdbVxGLtP/3v6YYXw9ZP@8UI97YaMtCcLiKsFdQ7sc94C4vKUPCikZxXrk@N06CZlgZ6ZhHgtKFFlKCJUAS52SQ@kuYEwo62K7/cCU4HQGX@Wpb0DxzYTPxr43QzKf/X7HYLAhsa7xlGBoQ4zzUrGyT@w0 "V (vim) – Try It Online")
### How?
```
úr/?]
ú - sort by:
r - with flag=r: use match (default behaviour is to use what's after the match)
/ - with the pattern:
? - (byte 83) a shortcut for .\{-}
. - match any character
\{-} - 0 or more times matching as few times as possible
] - match a literal ']' character
```
[Answer]
# AutoHotkey, 74 bytes
```
Loop,Read,f
{
s:=A_LoopReadLine
FileAppend,%s%`n,% StrSplit(s,"]","[")[1]
}
```
Reads from a file named `f` and outputs into multiple files based on the tag.
[Answer]
# SimpleTemplate 0.84, 109 bytes
Yeah, it's pretty long, but does the job!
```
{@callexplode intoL EOL,argv.0}{@eachL}{@if_ matches"@^(\[.*\])@"M}{@setS.[M.1]S.[M.1],_,EOL}{@/}{@/}{@echoS}
```
This code generates an array with `<old content>, line, <end of line>`.
`{@echoS}` automatically flattens the array and displays it.
---
**Ungolfed:**
Yes, it's a mess, but here's a cleaner version:
```
{@call explode into lines EOL, argv.0}
{@set storage null}
{@each lines as line}
{@if line matches "@^(\[.*\])@" match}
{@set storage.[match.1] storage.[match.1], line, EOL}
{@/}
{@/}
{@echo storage}
```
The function `explode` is a standard PHP function, but accessible from my language.
---
You can try this on: <http://sandbox.onlinephpfunctions.com/code/9c66f8bacc6315ae56e7c193170e430f9cf9d902>
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 181 162 160 bytes
```
input.GroupBy(l=>l.Split()[0]).ToList().ForEach((g)=>{using(var sw = new StreamWriter(g.Key.Trim('[').Trim(']')+".log")){foreach(var v in g)sw.WriteLine(v);}});
```
[Try it online!](https://tio.run/##lVHBauMwED3XXzEYlkh0V7S0h1KTQjdsStmWLZtAD8YHVZ46orLkHclOQ/C3Z5WsSUPpoXuS5r15T5o3yn9TjnDTem0rmK18wDpLDisxccagCtpZL27QImn1ruNO2z/voNtfWZI07ZPRCpSR3sMDuYpknayTowH3QYZ4dE6XcC@1ZT5QtMgLkFR5Hjv3gLZNG2AMFpewB9dpvkQZFkgFTFoitAHi280lXJxN069Jmj9JekFsCphqv4DII3mI4Aeko3JHIv5jfXDqpd62hAIebuH4TJyef6AzKDt8M91/6PzkC6iFtArBPQPF8aDEEHPEMu2zzW4gcUOubb6vmBlfGTFrjA6M5ycFF3N3p30sxNTRD6kWjFV8fLXeRcw6SeCXQxqzQCjrR9JxNlaJn7gSc9I1G@UjPtyKET9OhXFVyvn6OW57a7g16WKuUHG/FDt9XCOyjmd9z7PNJK7bGTxgpjqWv1GW18bM8TWwdBh2sM6Sz2iG9P5Lc7CLva5P@s1f "C# (.NET Core) – Try It Online")
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 179 bytes
```
i=>i.GroupBy((l)=>{return l.Split(' ')[0];}).ToList().ForEach((g)=>{using(var sw = new StreamWriter(g.Key.Trim(new char[]{'[',']'})+".log")){foreach(var v in g)sw.WriteLine(v);}})
```
[Try it online!](https://tio.run/##bZBPSwMxEMXv/RRDQDahNSh6EGsLKlZED6KCh2UPMZ1ug7tJmaQtsuxnr8la/xR7zLx5vzcv2h9qbzaXOhhnL3wgY8u8GMPMwgg2ZjQ28pbccnH1wXklRuOGMCzJQiWfF5UJPINM5EfFsBXyxT0YH7iQE0c3Ss85L5Nh6SOSrxSBX0emxTU8B0JVv5IJSLyU9/ghX8jUPGl6rigvmizPBlmRtaLPZOVKJkQzc9EVsQm1AmOhFH4tO8qDschXYti2YjPszWxH@i7TsHyNKsyRCrheEqENELBenMPZyYQNeix/U/SOuChgYvwcoo7kIQ73iI6mnYj4pfrg9HudVkIBj3fQP5HHp3t8FaoV/kJ/Djo9OkiVrUZwMyAVa00xoA44Za2IXb5KQ9faqhpT8d1226DumwbA/lz0Pdqmdc9WQNMDuHbWuwr/fF@C99k5i6EAO7E6ZU5M3H5CNb2sqrTvO4MQe0i6Q/yfx3G7@QQ "C# (Visual C# Interactive Compiler) – Try It Online")
I'm not sure the first solution is code gulf compliant, so the second solution uses a lambda expression.
[Answer]
# Haskell, 37 bytes
```
import Data.List
f=sortOn(head.words)
```
[Try it online!](https://tio.run/##dc9Pa8JAEAXwu5/iERRaKsGihyJ4qgiCUO82h2nywi5JNmF2rB8/rlJKKTjHNz/mj5PYsG3H0XdDr4atmOQHH21Sb2IKPsKTo1T5pdcqPo@d@IANBvXBMEWN0wSpstOFYo5a4P2sytQ0dsMab8vdZ8jmP@hLtCGHAjsfHZKiRqTwIUlL74T8a6L1ZdPdoBU47vGyzF9XD2e0lG/@X/N77moxQ@kklERfQ2/vVTSWxiq722K8Ag "Haskell – Try It Online")
[Answer]
# Rust, 40 bytes
```
|a|a.sort_by_key(|x|x.split("]").next())
```
Takes a mutable reference to a slice of strings and sorts it.
[Try it on the rust playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&code=fn%20main()%20%7B%0A%20%20%20%20let%20f%3Afn(%26mut%5B%26str%5D)%3D%0A%20%20%20%20%20%20%20%20%7Ca%7Ca.sort_by_key(%7Cx%7Cx.split(%22%5D%22).next())%3B%0A%20%20%20%20%20%20%20%20%0A%0A%20%20%20%20let%20s%20%3D%20%26mut%20%5B%0A%20%20%20%20%20%20%20%20%22%5Bweather%5D%20Current%20temp%3A%2083F%5Cn%22%2C%0A%20%20%20%20%20%20%20%20%22%5Bbarkeep%5D%20Fish%20enters%20bar%5Cn%22%2C%0A%20%20%20%20%20%20%20%20%22%5Bbarkeep%5D%20Fish%20orders%20beer%5Cn%22%2C%0A%20%20%20%20%20%20%20%20%22%5Bstockmarket%5D%20PI%20%2B3.14%5Cn%22%2C%0A%20%20%20%20%20%20%20%20%22%5Bbarkeep%5D%20Fish%20leaves%20bar%5Cn%22%2C%0A%20%20%20%20%20%20%20%20%22%5Bweather%5D%2040%25%20chance%20of%20rain%20detected%22%0A%20%20%20%20%5D%3B%0A%20%20%20%20f(s)%3B%0A%20%20%20%20println!(%22%7B%3A%3F%7D%22%2C%20s)%3B%0A%7D)
[Answer]
# [Perl 5](https://www.perl.org/) -M5.10.0 -Msort=stable, 53 bytes
```
say sort{(split('\]',$a))[0]cmp(split('\]',$b))[0]}<>
```
[Try it online!](https://tio.run/##XY9Ba8JAEIXv/oo5KBrUEEkEEfVSEHoo9J7uYbN5kmCSXWanSin9691GKYI5zvfxHm8cuFmH4PUXecvyPfOuqWU2/VDTxVhHUZ4o07onWtzpz@4QQn6Flgqs6OWTGZ2QoHVb2qTHUV5oPgNO0bH2FfUS7KmHQ2O5vBugV16sObc3L4reX2mexqtsmGigL/jveizIkgmZSncGZE/Euu6ohMAIyl/rpLadD8u325N7L7po0F/reJXEyR8 "Perl 5 – Try It Online")
]
|
[Question]
[
This task is rather simple, and makes use of three distinct "operator" characters. Your task is, given a simple sequence of letters, perform the following task to encode it using `<`,`>`,`*`. You may choose to use either upper or lowercase letters, you do not have to handle both.
---
# Cipher Explanation
The cipher is simple, you're using increment and decrement operations to traverse from letter 1 to the end letter, with `*` being your "submit" function. The operator for "increment" will be `>` and "decrement" will be `<`.
An example using the word `adbc`:
* Start with the first letter of the word, output that letter. `a`
* Next, use `>` and `<` (like brainfuck) to "navigate" the current letter to the next one. `a>` would result in 'raising' `a` by 1 to the letter `b`. `a<` would result in `z` because you're lowering the letter (it wraps, you must always choose the direction resulting in the LEAST number of operations).
* After outputting the correct minimalized combination of `<` and `>` output a `*` to denote that we've reached the next letter.
The steps to encode `adbc` would be:
```
a # a
a>>>* # ad
a>>>*<<* # adb
a>>>*<<*>* # adbc
```
# Examples
The steps to encode `aza` would be:
```
a # a
a<* # az
a<*>* # aza
```
More examples:
```
"abcdef" = "a>*>*>*>*>*"
"zyaf" = "z<*>>*>>>>>*"
"zzzzzz" = "z*****"
"z" = "z"
"zm" = "z<<<<<<<<<<<<<*" or "z>>>>>>>>>>>>>*" (equidistant)
"zl" = "z>>>>>>>>>>>>*"
"alphabet" = "a>>>>>>>>>>>*>>>>*<<<<<<<<*<<<<<<<*>*>>>*<<<<<<<<<<<*"
"banana" = "b<*>>>>>>>>>>>>>*<<<<<<<<<<<<<*>>>>>>>>>>>>>*<<<<<<<<<<<<<*" OR "b<*<<<<<<<<<<<<<*>>>>>>>>>>>>>*<<<<<<<<<<<<<*>>>>>>>>>>>>>*"
"abcdefghijklmnopqrstuvwxyz" = "a>*>*>*>*>*>*>*>*>*>*>*>*>*>*>*>*>*>*>*>*>*>*>*>*>*"
"abcdefz" = "a>*>*>*>*>*<<<<<<*"
```
# Rules
* We are **encoding** not decoding, so don't mess that up.
* You may assume the message will contain letters `[A-Z]` or `[a-z]`, your choice.
* You may use any non-letter/numeric/reserved character to denote `*` (E.G. `$`).
* You must have the ending `*`, it isn't implicit on repeats.
* You may assume no empty strings, but a single character is possible.
* If it is equidistant either way to the next letter, you may choose a direction.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest byte-count wins.
*Please explain your answer, it helps others learn this way.*
[Answer]
# 8086 machine code, ~~70 68~~ 67 bytes
```
00000000 be 82 00 bf 43 01 57 31 d2 ac 3c 0d 74 2c 89 d1 |....C.W1..<.t,..|
00000010 88 c2 aa e3 f4 4f 28 c1 9f 88 e7 79 02 f6 d9 83 |.....O(....y....|
00000020 f9 0d 9f 76 05 83 e9 1a f6 d9 30 fc 9e b0 3c 78 |...v......0...<x|
00000030 02 b0 3e f3 aa b0 2a aa eb cf c6 05 24 b4 09 5a |..>...*.....$..Z|
00000040 cd 21 c3 |.!.|
00000043
```
How it works:
```
| org 0x100
| use16
be 82 00 | mov si, 0x82 ; source = command line arguments
bf 43 01 | mov di, result ; destination = result
57 | push di
31 d2 | xor dx, dx ; clear dx
ac | n: lodsb ; al = *si++
3c 0d | cmp al, 0x0d ; end of input reached? (newline)
74 2c | je q ; jump to exit in that case
89 d1 | @@: mov cx, dx ; store last char in cl
88 c2 | mov dl, al ; and store the current char in dl
aa | stosb ; *di++ = al
e3 f4 | jcxz n ; skip encoding this char if cx == 0 (only happens for the first char)
4f | dec di ; move di pointer back
28 c1 | sub cl, al ; take the difference between this char and the last one
9f | lahf ; store flags from last subtraction in bh
88 e7 | mov bh, ah
79 02 | jns @f
f6 d9 | neg cl ; make sure cl is positive
83 f9 0d | @@: cmp cl, 13 ; which way is shorter?
9f | lahf ; also store these flags
76 05 | jbe @f
83 e9 1a | sub cl, 26 ; invert cl if we're going backwards
f6 d9 | neg cl
30 fc | @@: xor ah, bh ; xor saved flags together
9e | sahf ; load flags register with the result
b0 3c | mov al, '<'
78 02 | js @f ; now the sign flag tells us which operator to use
b0 3e | mov al, '>'
f3 aa | @@: rep stosb ; while (cx--) *di++ = al
b0 2a | mov al, '*' ; mark the end with an asterisk
aa | stosb
eb cf | jmp n ; repeat
c6 05 24 | q: mov byte [di], '$' ; mark end of string
b4 09 | mov ah, 0x09 ; dos function: print string
5a | pop dx ; dx = string pointer
cd 21 | int 0x21 ; syscall
c3 | ret
| result rb 0
```
[Answer]
# [Python 3](https://docs.python.org/3/), 87 bytes
```
r,*s=input();p=r
for c in s:d=(ord(p)-ord(c)-13)%26-13;r+='<'*d+'>'*-d+'*';p=c
print(r)
```
[Try it online!](https://tio.run/nexus/python2#FcxLCoAgFEDReauQIJ4fhD7QwHptRBqUEjgxedb6zbiDM7slY4jpfbhYEhJm2@/NdRNzLESW7WB245Hf5HkS@scJPUyiG@fKQgphBekVbCB1RULduCZRiA@jUtrziLX2Aw "Python 2 – TIO Nexus")
Works with either lowercase or uppercase.
The program builds the output string `r` as it iterates over the characters in the input string. It stores the previous character as `p`, and computes the incrementing operation to get from `p` to the new character `c`.
The interval between the characters is `ord(c)-ord(p)`, and `(ord(c)-ord(p)-13)%26-13` takes it modulo 26 to the interval `[-13..12]`. A negative result means it's shorter to step down, and a positive result means to step up.
This needs to be converted to a string of `>` or `<` depending on the sign. Rather than using `abs` or a conditional, we take advantage of Python's string multiplication `s*n` giving the empty string when `n` is negative. In the expression `'<'*-d+'>'*d`, the wrong-signed part does not contribute.
The initial state is handled by splitting the input into its first character and the rest with Python 3's unpacking `r,*s=input()`. The initial character is used to start building the string, as well as the initial "previous" char.
Thanks to ovs for suggesting switching to Python 3 to do this unpacking.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~110~~ 93 bytes
```
r,*s=input()
b=r
for a in s:d=(ord(a)-ord(b))%26;r+=['>'*d,'<'*(26-d)][d>13]+'*';b=a
print(r)
```
[Try it online!](https://tio.run/nexus/python3#FcUxDoMwDADAPa/IUtkOMEAlhlLzEcTgyFSNVIXIpO9P1VuuWR8uTrl8K5KLbO51mhefsr8eyniaotDwLxLdpnmxjjdYIWgPTwg4zYPSvuk63vcOAiyRxRVLuaJRa/Ipb4lH/QE "Python 3 – TIO Nexus")
[Answer]
## JavaScript (ES6), ~~118~~ ~~109~~ 107 bytes
The input string is case insensitive.
```
s=>s.replace(/./g,(c,i)=>(d=~~s-(s=parseInt(c,36)),i)?'<><>'[k=d/13+2|0].repeat([d+26,-d,d,26-d][k])+'*':c)
```
### How it works
Unlike Python, the JS modulo operator returns a number having the same sign as the dividend rather than the divisor. Also, the JS `repeat()` method throws an error when given a negative number, rather than returning an empty string (and it's significantly longer than a simple `*` anyway).
These are rather unfavorable behaviors for this challenge. So, we'd better identify in which exact case we are rather than relying on math tricks. (Which doesn't mean that such tricks do not exist, but rather that I failed to find them.)
Below is a table describing the 4 possibles cases, where `d` is the signed distance between the current character and the previous one:
```
d | floor(d / 13) + 2 | direction | repeat
------------+-------------------+-----------+-------
-25 ... -14 | 0 | < | d + 26
-13 ... -1 | 1 | > | -d
+0 ... +12 | 2 | < | +d
+13 ... +25 | 3 | > | 26 - d
```
### Test cases
```
let f =
s=>s.replace(/./g,(c,i)=>(d=~~s-(s=parseInt(c,36)),i)?'<><>'[k=d/13+2|0].repeat([d+26,-d,d,26-d][k])+'*':c)
console.log(f("abcdef"));
console.log(f("zyaf"));
console.log(f("zzzzzz"));
console.log(f("z"));
console.log(f("zm"));
console.log(f("zl"));
console.log(f("alphabet"));
console.log(f("banana"));
console.log(f("abcdefghijklmnopqrstuvwxyz"));
console.log(f("abcdefz"));
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
OIżN$ẋ"@€⁾><;€⁶ṭḢ
```
Uses a space character in place of `*` (a space, `⁶`, or a newline, `⁷`, saves one byte over `”*`).
Works with *either* uppercase-only *or* lowercase-only input.
**[Try it online!](https://tio.run/nexus/jelly#@@/veXSPn8rDXd1KDo@a1jxq3GdnYw1mbHu4c@3DHYv@//@vlJSYB4RKAA "Jelly – TIO Nexus")** or see a [test suite](https://tio.run/nexus/jelly#@@/veXSPn8rDXd1KDo@a1jxq3GdnYw1mbHu4c@3DHYv@H24HciPdKh2Acgpa//9HKyUmJaekpinpKFVVJoIpMAAxQDgXROQAicScgozEpNQSIDMpMQ8IQWJgrekZmVnZObl5@QWFRcUlpWXlFZVVcMkqpVgA) (where those spaces are post-replaced by `*` for reading ease).
### How?
```
OIżN$ẋ"@€⁾><;€⁶ṭḢ - Main link: string s e.g. "adbc"
O - cast s to ordinals [97,100,98,99]
I - incremental differences [3,-2,1]
$ - last two links as a monad:
N - negate [-3,2,-1]
ż - zip together [[3,-3],[-2,2],[1,-1]]
‚Åæ>< - literal ['>','<'] "><"
"@€ - using reversed @arguments for €ach zip with("):
ẋ - repeat (-n are like zeros) [[">>>",""],["","<<"],[">",""]]
;€ - concatenate €ach with:
⁶ - literal ' ' [[">>>","",' '],["","<<",' '],[">","",' ']]
·π≠ - tack to:
·∏¢ - head of s (1st char) [['a'],[">>>","",' '],["","<<",' '],[">","",' ']]
- implicit print (" not printed:) "a>>> << > "
```
[Answer]
# PHP, 127 Bytes
```
for($l=ord($r=($s=$argn)[0]);$x=ord($s[++$i]);$l=$x)$r.=str_pad("",($a=abs($n=$l-$x))<14?$a:26-$a,"><"[$n>0^$a>13])."*";echo$r;
```
[Testcases](http://sandbox.onlinephpfunctions.com/code/8d73e527b11efd1d80f81c760bae80a2fccbddf5)
## PHP, 137 Bytes
```
for($l=$r=($s=$argn)[0];$s[++$i];$l=$s[$i])$r.=str_pad("",$d=min($a=abs(ord($l)-ord($s[$i])),$b=26-$a),"><"[$d<$b^$l<$s[$i]])."*";echo$r;
```
[Testcases](http://sandbox.onlinephpfunctions.com/code/b58e431502b6c637171aa3a76848a077ffd49c9f)
[Answer]
## JavaScript (ES6), ~~111~~ 103 bytes
```
f=
s=>s.replace(/./g,(c,i)=>(p=(n+26-(n=parseInt(c,36)))%26,i?'<>'[p+3>>4].repeat(p>13?26-p:p)+'*':c),n=0)
```
```
<input oninput=o.textContent=f(this.value)><pre id=o>
```
```
s=>[...s].map(c=>(n=parseInt(c,36),p&&(p=(n+26-p)%26,s+='><'[p+3>>4].repeat(p>13?26-p:p)+'*'),p=n),s=s[p=0])&&s
```
Originally version that took 111 bytes before I adapted @Arnauld's trick of setting `n` while computing `p`, I think there's probably another trick using `s` instead of `n` but it's getting late so I won't bother.:
[Answer]
## Haskell (lambdabot), ~~161~~ 153 bytes
```
w(s:n)=s:(join.snd$mapAccumL(ap(,).g)s n);g c n|q<-[c..'z']++['a'..c],(Just l,s)<-minimum$first(elemIndex n)<$>[(q,'>'),(reverse q,'<')]=(s<$[1..l])++"*"
```
[Try it online!](https://tio.run/nexus/haskell#XY9Nb8IwDIbv/AorqpRkLZF2ZQUJbZdNcNqxVFPahhKWj5KktKD9d9YxirTZB7@Pbb2ypW6sC/DCA2cr6cNE/jaerQnOKrZ0znb/m2treHXpiJ8ZOvczsrfSMG@qSPNmWZatXhHekISymnow9KmGEszXIZ1mJWP4jPM4zjDHjJV5Qt5aH0AlnqZTLY3UrY620vlAhBL61VSiHyzSaJGRQ4IXmCbEiaNwXsDAKab5nPg0yh4ZUzmNY/SALppLA3MYrll/ANn0MF1A04b34FYGIughjgHNNgH9iA56OgHIAPGirMQWDZAAOp/4XV5jhLHqUaib4KrZ8UKEGxbcDDnOrtb1Tu4/lTa2OQwPtseuP53/LFwpv3wD "Haskell – TIO Nexus")
Explanation:
```
-- Encode a single letter
g c n | q <- [c..'z']++['a'..c] -- The alphabet starting from letter c, looping around
, (Just l,s) <- minimum -- Choose the smallest of ..
$ first(elemIndex n) -- the index of the letter n ..
<$> [(q,'>'),(reverse q,'<')] -- from the alphabet q and its reverse
= (s<$[1..l]) -- Repeat < or > the same number of times as the index of n ..
++ "*" -- and append *
-- Encode the whole string
w (s:n) = s -- Yield the first char of the input
: ( join . snd -- Concatinate the result of ..
$ mapAccumL (\a b->(b,g a b))s n -- executing the g function on each letter of the input string ..
-- except the first, passing the previous letter as the 'c' ..
-- argument on each iteration
)
```
[Answer]
## EXCEL VBA 130 bytes
```
s="":p=Mid(s,1,1):For i=1 To Len(s)-1:b=Asc(Mid(s,i+1,1)):a=Asc(Mid(s,i,1)):p=p &String(abs(b-a),IIf(b>a,">","<"))&"*":Next:[a1]=p
```
Run it from Excel VBA Immediate window.
Explanation:
Simple for loop that with String function to repeat the ">" or "<" n number of times where n is the ascii difference between the i and i+1 character string.
[Answer]
# Java 7-, 232 bytes
```
class C{static void main(String[]a)throws Exception{int i=System.in.read(),j,d,c;p(i);while((j=System.in.read())>10){d=(j-i+26)%26;c=d>13?-1:1;while(d%26>0){d-=c;p(61+c);}p(42);i=j;}}static void p(int k){System.out.print((char)k);}}
```
Pretty much the trivial solution. Ungolfed and commented:
```
class C {
static void main(String[] a) throws Exception {
int i = System.in.read(), j, d, c; // i is the last character. j is the current character. d is the difference. c is the direction (-1 is left, 1 is right)
p(i); // print the starting character first
while ((j = System.in.read()) > 10) { // keep going until a newline is hit (or an EOF/EOL for -1)
d = (j - i + 26) % 26; // get the difference (always positive) by wrapping around
c = d > 13 ? -1 : 1; // get the direction by finding which way is shorter, going right when it's a tie
while (d % 26 > 0) { // keep going until the current character is reached
d -= c; // reduce d in the right direction
p(61 + c); // < is 60 = 61 + (-1), > is 62 = 61 - (-1)
}
p(42); // print an asterisk
i = j; // set the current character to the new reference point
}
}
static void p(int k) {
System.out.print((char) k);
}
}
```
[Answer]
# C, 170 bytes
```
e(c){putchar(c);}i;m(a,b){i=b-a?a>b?b-a<14?b-a:-(a+26-b):a-b<14?-(a-b):b+26-a:0;while(i>0)e(62),i--;while(i<0)e(60),i++;}f(char*l){e(*l);while(l[1])m(*l,l[1]),e(42),l++;}
```
**Detailed** [Live](http://ideone.com/kstNzb)
```
e(c){ putchar(c); } // encode
g(a,b) // obtain required transition
{
return (b-a) // calculate distance
? (a > b // distance is non-zero
// if b comes after a
? (b-a < 14 // if forward is a shorter path
? b-a // go forward
: -(a+26-b)) // otherwise go backward
// if b comes before a
: (a-b < 14 // if backward is a shorter path
? -(a-b) // go backward
: b+26-a)) // otherwise go forward
: 0; // if distance is 0
}
// transition
i;m(a,b)
{
// obtain required transition
i=g(a,b);
// encode forward transition
while(i>0)e('>'), i--;
// encode backward transition
while(i<0)e('<'),i++;
}
// incremental cipher function
f(char*l)
{
e(*l); // encode first character
while(*(l+1)) // while next character is not END-OF-STRING
m(*l,*(l+1)), // do transition from current to next character
e('*'), // encode
l++; // next
}
```
[Answer]
**C++ ,~~210~~ 190 bytes**
My First Try At Golfing !
```
#include<iostream>
int g(char*a){char k,j,d;std::cout<<*a;a++;for(;*a;a++){for(j=*(a-1),d=j-*a,k=d>0?d>13?62:60:d<-13?60:62;j!=*a;j+=k-61,j=j<97?122:j>122?97:j)std::cout<<k;std::cout<<'*';}}
```
k stores which of < , > or \* to print .At first it simply prints the first element of array then runs a loop for a from first to last element of array . j stores the previous element and then by comparing if j closer to \*a by < or > set k to < ,> respectively and then print k then run this loop until j becomes equal to p . Then after every ending of second loop print \* .
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes
```
¬sÇ¥v„<>y0›èyÄ×ðJ
```
[Try it online!](https://tio.run/nexus/05ab1e#ASkA1v//wqxzw4fCpXbigJ48Pnkw4oC6w6h5w4TDl8OwSv//YWxwaGFiZWVldA "05AB1E – TIO Nexus")
**Explanation**
Uses `>`, `<` and `<space>` to denote *increment*, *decrement*, *submit*
```
¬ # get the first letter of the input string
sǥ # push a list of delta's of the character codes in the input string
v # for each delta
„<> # push the string "<>"
y0› # check if the delta is positive
è # use this to index into the string
yÄ× # repeat it abs(delta) times
√∞J # join to string with a space
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~167~~ ~~168~~ 126 bytes
```
f=fromEnum
r=replicate
a?b=mod(f a-f b-13)26-13
c#x=r(c?x)'<'++r(-c?x)'>'
s(c,s)x=(x,s++c#x++"*")
e(x:y)=x:snd(foldl s(x,[])y)
```
Now using xnor's arithmetic solution. Call with `e str` where `str :: String` is the string to be encoded.
[Answer]
# [Haskell](https://www.haskell.org/), 109 bytes
```
a#b=mod(a-b-13)26-13
r=replicate
h(a:b:s)=r(a#b)'>'++r(-a#b)'<'++'*':h(b:s)
h e=""
f(a:r)=a:h(fromEnum<$>a:r)
```
[Try it online!](https://tio.run/nexus/haskell#HYvBCsMgEETvfoWkBTXBQ1voQbK59UPWVFGoJmzt95tNGRiGx5uOFw9le2u03t4e5v7kFgQU9k9esQWRNDrvvgZIs2vUoqaJtP3vmbcalUv6NESSAYZBRH6QAWQcaSuv@ivzdTlZL5irBJlrC4Rrk7F7rJwD "Haskell – TIO Nexus") Uses [xnor's approach](https://codegolf.stackexchange.com/a/116843/56433). Call with `f "somestring"`.
[Answer]
# JavaScript (ES6), ~~140~~ ~~128~~ ~~129~~ ~~111~~ 113 bytes
I went down a different route to the other JS solutions but it didn't work out too well - here's what I have so far:
```
f=
([x,...s])=>x+s.map(y=>`<><>`[r=(d=y[c=`charCodeAt`]()-x[c](x=y))/13+2|0].repeat([d+26,-d,d,26-d][r])+`*`).join``
i.addEventListener("input",()=>o.innerText=i.value&&f(i.value))
console.log(f("adbc"))
console.log(f("aza"))
console.log(f("abcdef"))
console.log(f("zyaf"))
console.log(f("zzzzzz"))
console.log(f("z"))
console.log(f("zm"))
console.log(f("zl"))
console.log(f("alphabet"))
console.log(f("banana"))
console.log(f("abcdefghijklmnopqrstuvwxyz"))
console.log(f("abcdefz"))
```
```
<input id=i>
<pre id=o>
```
* Saved 12 bytes thanks to a suggestion from [Luke](https://codegolf.stackexchange.com/users/63774/luke) on destructuring the string.
* Added 1 byte fixing a misreading of the challenge, which I thought allowed for an implicit final print character.
* Saved another 18 bytes thanks to an extensive rewrite by Luke.
* Added 2 bytes as it seems numbers are not valid print characters.
---
## Original, 131 bytes
```
f=
([x,...s])=>x+s.map(y=>(t=(d=y[c=`charCodeAt`]()-x[c](x=y))<0?-d:d,`<>`[+((r=t<13)&&d>0)||+(!r&&d<0)].repeat(r?t:26-t)+`*`)).join``
i.addEventListener("input",()=>o.innerText=i.value&&f(i.value))
console.log(f("adbc"))
console.log(f("aza"))
console.log(f("abcdef"))
console.log(f("zyaf"))
console.log(f("zzzzzz"))
console.log(f("z"))
console.log(f("zm"))
console.log(f("zl"))
console.log(f("alphabet"))
console.log(f("banana"))
console.log(f("abcdefghijklmnopqrstuvwxyz"))
console.log(f("abcdefz"))
```
```
<input id=i>
<pre id=o>
```
]
|
[Question]
[
**Minesweeper** is a logic game found on most OS's. The goal of the game is to determine where the mines are on a grid, given numbers indicating the number of mines around that spot.
Given a grid size, and a set of mines, generate the Minesweeper grid for that set of mines.
**Input:** Two integers indicating the grid size, and an undefined number of integers indicating the mine positions. Positions will be given as (column position, row position), and the indexes will start at row 1.
**Output:** The Minesweeper grid. If there are no mines around a block, print an `x`. For each new row, print a newline. Please output all mines as an asterisk `*`. Do not leave any whitespace between the values in the row when printing.
**Test Cases:**
Input "5 5 1 3 3 5 2 4":
```
xxxxx
11xxx
*21xx
2*21x
12*1x
```
Input "3 4 3 1 1 4 2 3 3 2":
```
x2*
13*
2*2
*21
```
Shortest code wins.
[Answer]
### GolfScript ~~122 98 94 93 91 88 87 85 82 81 80~~ 71
```
~]2/(\:m;~\:w*,{[.w%)\w/)]:^m\?)42{m{^*~-.*@@-.*+3<},,72or 48+}if}%w/n*
```
**Online demos:**
Test Case 1: [link](http://golfscript.apphb.com/?c=OyI1IDUgMSAzIDMgNSAyIDQiCgp%2BXTIvKFw6bTt%2BXDp3Kix7Wy53JSlcdy8pXTpebVw%2FKTQye217Xip%2BLS4qQEAtLiorMzx9LCw3Mm9yIDQ4K31pZn0ldy9uKg%3D%3D&run=true)
Test Case 2: [link](http://golfscript.apphb.com/?c=OyIzIDQgMyAxIDEgNCAyIDMgMyAyIgoKfl0yLyhcOm07flw6dyose1sudyUpXHcvKV06Xm1cPyk0Mntte14qfi0uKkBALS4qKzM8fSwsNzJvciA0OCt9aWZ9JXcvbio%3D&run=true)
[Answer]
## J, 124 116 112 101 87 86 85 84 83 82 79 76 75 72 68 characters
```
'0x'charsub|:1":3 3(+/@,+9*4&{@,);._3[1(}.x)}0$~2+>{.x=._2<\".1!:1[1
```
Found what I was looking for - a way to get rid of the spaces (`1":`) - and finally I'm competitive. Now I just need to figure out the empty set of mines problem.
Takes input from the keyboard.
**Edit**
New version makes use of a side effect of `1":` - numbers larger than 9 are replaced by `*`.
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), ~~1001~~ 896 bytes
```
,[>,]-[<]>>++[<[<+<+>>-]<[>+<-]>[>]>[>>[>>>>]>]++[-<+]-[<]<++[>>[>]>[>>[>>>>]>]+<++[-<+]-[<]<-]>>>-]>[>]>[>>[>>>>]<<<->>>>]+[-<+]-[<]>>[[>]>--<<[<]>>[[>]+[->+]+>>[>>>>]>--<+[-<+]-[<]>>-]>[>]+[->+]+>>--<+[-<+]-[<]<[>>[>]+[->+]+>>>>--<+[-<+]-[<]<-]>>[>]+[->+]+>++[-<+]-[<]>>]>[+>>[>>>>]>]<<<<<[<<<<]>>-<+[-<+]>>>>[>>>>]>[-[--<<<<<[<<<<]>>>>--[>>>>]>>>[>>>>]>>>--<+[-<+]++>>>>>>[>[<--<<<[-[>>>>>>+<<<<<+<-]>+<]>[<+>-]>>>>+++[<<<+[-<+]->[-[+[->+]->>>+<<<<+[-<+]->>+<-]>+<]>[<+>-]+[->+]->>-[<<<+[-<+]+>>>>-->+[->+]->>[<<<+>>>-]]<<<[>>>+<<<-]>>>]<<<+[-<+]+<<<<-->+[->+]->>>>>[-[<<+>>>+<-]>+<]>[<+>-]<<<<+++[+[->+]->[-[<<+[-<+]->>>++[->+]->>+<-]>+<]>[<+>-]<<<+[-<+]->>-[+[->+]+>>>>--<+[-<+]->>[<<<+>>>-]]<<<[>>>+<<<-]>>>]+[->+]+<<<<--<+[-<+]->-[>>[-]<<++++++[>++++++<-]>.[-]+<<<]<[>>>[<++++++[>++++++++<-]>.[-]<]<<<[<++++++++[<+++++++++++>-]<.[-]>]<]>>>>+<<++>]>[<+>-]>>]->+[->+]++[-<+]++++++++++.[-]]>]
```
[Try it online!](https://tio.run/##fVL/rpsgFA4qAkKUNtpa294X4HKfgPAihD@2JUuWJftjyZ6/OwdFbe8yUlPk@3E@zvHr7y8/fn3/8@3n4/Ee/Hu0wUXvjQkuOOOM9za64I2z0QePD/487CJwrDNJ4GDvP@FuzwA9ej2TnHM2bTYiQEix1rn1DVBvolmtAdwLZteV9IS6OdcKvsIYa4ebvS/YbjUxK0aChSUXD8QWQrABQ@9IWGsBV9auvklxEAkuKcPMhu4nm9RzA0YwCJ/aB/EMmi8hseQc3GZRRvyLeKXZTb90w69YgtKU8LJh8UyV46bCMnsV3gBdjf9UNSWCyJk783LE1Gz/r7T7i@Qrvszu/2kXyRx1lWB7A7qbtIKf/1HzAedIT98LpnhibByXarl8vO1gYXDkQLPiMkU43MYXc9NMnn9eqALZ4/GmORNMVw27F1IMSjLdya7jVHf1vWIFbYaWlBc1lkMlCtZN9YUNstclmei1rlRFJj1WRXGmd3LQrRgbVit2a2t@kLdaCKUaeSoHchQtb/hRSXlqe3LWV8LpjdGyIIzcVQ9GY9fogzjXI6G851dBqJYTn2QpatlS1fR0ELSq9ZEJ1VRv7KInMTGij3Lkp@Iv "brainfuck – Try It Online") or [try the old version with integer input](https://tio.run/##fVPBqtwwDPwV3/1cYmeTzYLwj4Qc2kKhFHoo9Pu3MyPbyduFmhBkaUYaScm3P19//v7x9/uv5/NjrxFnt9ROTUc0Od2Hu/m9HUtH3S3CXyusireZfRxpN3hIQxRxEsET3IHEwjqASRZFMNj1LW5XBOvUM0lN5jgUTd2gwj25dTQuY/ISc@aDk5lSAqffEK3xiEMBgleCFx@gT1Fz@SP4Gmb5Szxe8yLtWbO1oQ7YpANhDcSedqq@oFisBQfqIiAqO9dIjiOxIaXQXqKdq6y@cuviWc5Vp04ag30hD1g6@W0UdcQU0iYPrctz@nZOFstcWeyLWWN9qypFkNyxjhu7jyPHO2@geosvi/u/2kZxqYPC8eoT9L@k/zHkfNmT4PpYqOIT4sSYall3nxYOhRODYR1ti3Be/sQ@tNh33w9ZoD2f8xTyGsoWcg55DvkWyhLuoTzwys2Cv@Tw4KuEDJfwM@O50AuosiwByFmpJj3gMHgjQZmB8ucGv8otMDcaxC/MlpUMtYghqii@MUy5lJDhXsWSbGnNErJCaKZaCppZNQfBbsLgXoLrWMKjcXOTXO4upqg7PIETuNF/ZzL1S6i6ml3arL4mdjOFrQ/RhXAYksk@Kd8pa@9RrI29Sg@rySh9UIXz32RSDjVSdQkK@FSmJin7plakcEGTj0g56ddmNs1w4Rj43tpU8vwP "brainfuck – Try It Online")
One day of programming and three days of bugfixing ^^
This uses a few parts of my Game Of Life code. Instead of counting living cells, this counts bombs.
Since input as codepoints is allowed by the general rules, this uses them instead of "readable" integers.
```
[
Data: colCount, rowCount, {BombCoordinates}, -1 (start of arrays/"soa"), 0, {RowData}
BombCoordinates: bombCol, bombRow
RowData: rowFlag, 0, {CellData}, 0
CellData: cellFlag, cellState, temp, bombCount
rowFlag: 0=EOF, 1=inactive (all cells inactive), 2=active
cellFlag: -1=marker for finding cell (cell to be counted or current cell), 0=EOF, 1=normal
cellState: 0=inactive, 1=normal, 2=bomb
temp: helper to exit if-statements
bombCount: count of neighbor cells that contain bombs
inactive cells or rows will not be printed. They are only used for an easier counting algorithm.
]
#### input values as codepoints ####
,[>,]
#### setup two dimensional array ####
- set soa
[<]>> go to rowCount
++ add two inactive rows
[ for each row
<[<+<+>>-] copy colCount two times to the next left cells
<[>+<-] move one of the copies back to the original cell
>[>]>[>>[>>>>]>] go to new row position
+ set rowFlag (only 1 while initialization)
+[-<+]-[<]< go to copy of colCount
++ add two inactive cells per row
[ for each col
>>[>]>[>>[>>>>]>] go to new cell position
+<+ set cellFlag and cellState = normal
+[-<+]-[<]< return to copy of colCount
- decrement
]
>>>- decrement rowCount
]
#### setup active/inactive flags of cells ####
>[>]>[ for each row
>>[>>>>]<<<- set last cell inactive
>>>> go to next row
]
#### mark the bombs ####
+[-<+]-[<]>> go to bombRow
[ while there are bombRow values left
[>]>-- set rowFlag of first row = neg 1 (as a marker)
<<[<]>> return to bombRow
[ for each bombRow
[>]+[->+] find first marker after soa
+ set rowFlag = 1
>>[>>>>]> go to next rowFlag
-- make a marker of it
<+[-<+]-[<]>> return to bombRow
- decrement
]
>[>]+[->+] go to selected rowFlag
+ set rowFlag = 1
>>-- set cellFlag of first cell = marker
<+[-<+]-[<]< go to bombCol
[ for each bombCol
>>[>]+[->+] find first marker after soa
+ set cellState = 1
>>>> go to next cellState
-- set it neg 1 (as a marker)
<+[-<+]-[<]< return to bombCol
- decrement
]
>>[>]+[->+] find first marker after soa
+ set cellFlag = normal
>+ set cellState = bomb
+[-<+]-[<]>> go to next bombRow
]
#### setup active/inactive flags of rows ####
>[ for each row
+ set rowFlag = 2 (active)
>>[>>>>]> go to next rowFlag
]
<<<<<[<<<<]>>- set rowFlag of last row = 1 (inactive)
#### count bombs in neighborhood ####
<+[-<+]>>>>[>>>>]> go to second row
[ for each row
-[ if active
-- set it neg 1 (marker)
<<<<<[<<<<]>>>> go to cellFlag of first cell in previous row
-- set it neg 1 (marker)
[>>>>]>>>[>>>>]>>> go to cellFlag of first cell in next row
-- set it neg 1 (marker)
<+[-<+] return to rowFlag
++ set rowFlag = 2 (active)
>> >>>>[ for each cell (starting with second)
>[ if active
<-- set cellFlag = neg 1 (marker)
# check if cell to the left is a bomb
< << go to cellState of previous cell
[ if active
-[ if bomb
>> >>>>+ increment bombCount
<<<< < go back to checked cell
+ set temp = 1
<- set cellState = 0 to exit if
]
>+< increment temp
]
>[<+>-] restore cellState
# check if cells on top are bombs
> >>> go to temp of current cell
+++[ do three times
<<<+[-<+]- go to next marker to the left
>[ if active
-[ if bomb
+[->+]- return to current cell
>>>+ increment bombCount
<<<<+[-<+]-> return to counted cell
>+ set temp = 1
<- set cellState = 0 to exit if
]
>+< increment temp
]
>[<+>-] restore cellState
+[->+]- go to current cell
>>- decrement temp
[ if temp != 0
<<<+[-<+] go to marked cell
+ set cellFlag = normal
>>>>-- set cellFlag of next cell = marker
>+[->+]->> return to currentCell temp
[<<<+>>>-] store value of temp in previous cell bombCount (to exit if)
]
<<<[>>>+<<<-]>>> restore temp value
]
<<<+[-<+] go to marked cell
+ set cellFlag = normal
<<<<-- set previous cellFlag = marker
>+[->+]- return to current cell
# check if cell to the right is a bomb
>>> >> go to cellState of next cell
[ if active
-[ if bomb
<<+ increment bombCount
>>> go back to checked cell
+ set temp = 1
<- set cellState = 0 to exit if
]
>+< increment temp
]
>[<+>-] restore cellState
# check if cells below are bombs
<<< < go to currentCell temp
+++[ do three times
+[->+]- go to next marker to the right
>[ if active
-[ if bomb
<<+[-<+]- return to current cell
>>>+ increment bombCount
+[->+]-> return to counted cell
>+ set temp = 1
<- set cellState = 0 to exit if
]
>+< increment temp
]
>[<+>-] restore cellState
<<<+[-<+]- go to current cell
>>- decrement temp
[ if temp != 0
+[->+] go to marked cell
+ set cellFlag = normal
>>>>-- set cellFlag of next cell = marker
<+[-<+]->> return to currentCell temp
[<<<+>>>-] store value of temp in previous cell bombCount (to exit if)
]
<<<[>>>+<<<-]>>>restore temp value
]
+[->+] go to marked cell
+ set cellFlag = normal
<<<<-- set previous cellFlag = marker
<+[-<+]- return to current cell
# print
>-[ if bomb
>>[-]<< delete bombCount
++++++[>++++++<-]>.print "*"
[-]+ set temp = 1
<<< use previous cell bombCount as exitIf
]
<[ else
>>>[ if bombCount != 0
<++++++[>++++++++<-]add 48 to get ascii number
>. print
[-] set number = 0 (for use as exitIf from next cell)
< go to temp for exit if
]
<<<[ else
<++++++++[<+++++++++++>-]<.print "X"
[-] delete value (for use as exitIf from next cell)
> go to exitIf
]
< go to exitElse
]
> >>>+ increment temp
<<++> set cellFlag = normal
]
>[<+>-] restore cellState
>> go to cellFlag of next cell
]
- set marker
>+[->+] go to next marker
+ set cellFlag = normal
+[-<+] return to marker
+++++ +++++.[-] print newline
]
> go to next row
]
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~59~~ ~~57~~ 54 [bytes](https://github.com/abrudz/SBCS)
With a more flexible input format this could be [39 bytes](https://tio.run/##SyzI0U2pTMzJT///v1q9wtDI2MTUzNxCSz1ao1pbX@dR79baRz27jBWMH/V0WD7qmHF4uqahA1D0UdeiR727HvVuMYit/Z/2qG3Co96@R31TPf0fdTUfWm/8qG0ikBcc5AwkQzw8g/9D5NomGHCZKpgqpCk86tl7aIXCofWGCtoKGoYKxpoKGsYKpkDSSMFEk@tR7xouEwVjdHXGCoaaINUmYHUQPUaaAA)
```
{⍉{5⌷,⍵:'*'⋄×r←+/,⍵:⍕r⋄'x'}⌺3 3⊢1@(1↓⍵)⊢0⍴⍨⊃⍵}⊢⊂⍨2|⍳∘≢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pRb2e16aOe7TqPerdaqWupP@puOTy96FHbBG19sNCj3qlFQDH1CvXaRz27jBWMH3UtMnTQMHzUNhkorQnkGTzq3fKod8WjrmagQC1Q4FFXE5BvVPOod/OjjhmPOhf9TwOa96i371HfVE9/oLpD640ftU0E8oKDnIFkiIdn8P80BVMgNFQA2gCkjRRMuB71ruFKA/JMgNgQCE2AoiBZIwA "APL (Dyalog Unicode) – Try It Online")
The whole structure is a train, first `⊢⊂⍨2|⍳∘≢` splits the input into pairs, then the large *dfn* is called on the list of pairs:
`0⍴⍨⊃⍵` Create a matrix of 0's where the dimensions are given by the first pair.
`1↓⍵` all but the first pair
`1@(...)` at those indices place 1's in the matrix.
`{ ... }‚å∫3 3` apply the left function on each 3√ó3 neighborhood (padded with zeros):
`5‚å∑,‚çµ` If the value at index 5 of the flattened neighborhood (the center) is 1, return `'*'`
`√ór‚Üê+/,‚çµ` If the sum of the neighborhood is positive, return it as a string `‚çïr`
Otherwise return `'x'`
`‚çâ` transpose the matrix because the order of axis is different in APL and the challenge.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2), 42 bytes
```
⌈⌊2ẇḣ$2+Þm$R(n1ÞȦ)2(3vl∩)ƛƛf4ǔṫß×∑\x$∨}vṅ⁋
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyIiLCIiLCLijIjijIoy4bqH4bijJDIrw55tJFIobjHDnsimKTIoM3Zs4oipKcabxptmNMeU4bmrw5/Dl+KIkVxceCTiiKh9duG5heKBiyIsIiIsIlwiMyA0IDMgMSAxIDQgMiAzIDMgMlwiIl0=) (would be 28ish with looser I/O)
```
⌈⌊ # Parse integers from input
2ẇ # Group into pairs
·∏£ # Remove the first pair (dimensions)
$2+ # Add 2 to each
√ûm # Create a matrix of 0s with those dimensions
$R( ) # Over each remaining coordinate pair (with x and y swapped)
√û»¶ # Place in the matrix
1 # A 1
n # At those coordinates
2( ) # Twice
3vl # Get all sliding windows of length 3 of each
‚à© # Transpose
∆õ∆õ }
f # Flatten into a 9-element array
4«î # Rotate so the centre (current cell) is at the end
·π´ # Extract the last element (current cell)
ß× # If that is truthy, push a mine
‚àë # Sum to get number of nearby mines
\x$‚à® # If 0, replace with x
v·πÖ‚Åã # Concatenate each and join by newlines
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 50 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
#2ôć¬UPL<s<íXδβ©såXô2Fø0δ.ø}2Fø€ü3}OOJJ'*®ǝ0'x:Xô»
```
[Try it online](https://tio.run/##yy9OTMpM/f9f2ejwliPth9aEBvjYFNscXhtxbsu5TYdWFh9eGnF4i5Hb4R0G57boHd5RC2I@alpzeI9xrb@/l5e61qF1x@caqFdYAZUd2v3/v7GCiYKxgiEQmigYAVnGCkYA) or [verify both test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDpeRfWgLh6VT@VzY6vOVI@6E1oQE@NsU2h9dGnNtybtOhlcWHl0Yc3mLkdniHwbkteod31IKYj5rWHN5jXOvv7@WlrnVo3fG5BuoVVkBlh3b/1zm0zf5/tJKpgqmCoYIxEJoqGCmYKOkoGSuYAHmGQGgCFAHJGCnFAgA).
**Explanation:**
05AB1E lacks multi-dimensional index builtins and uses 0-based indexing, so we mostly work with the flattened list and lower all indices by 1 (before converting it back to a matrix to calculate the amount of surrounding mines per cell).
```
# # Split the (implicit) input-string on spaces
2ô # Split it into parts of size 2
ć # Extract head; pop and push remainder-list and first pair
¬ # Get the first item of this first pair (without popping)
U # Pop and store it in variable `X`
P # Take the product of this first pair
L< # Pop and push a list in the range [0,value)
s # Swap so the list of pairs is at the top again
< # Decrease each inner value by 1 to make things 0-based
í # Reverse each inner pair, to reverse column,row to row,column
δ # Map over each reversed and lowered pair:
X β # Convert it from base-`X` to an integer,
# (which are all flattened 0-based indices of the mines)
© # Store this list in variable `®` (without popping)
s # Swap so the [0,value)-ranged list is at the top
å # Check for each value whether its in the indices-list,
# resulting in a list of 0s and 1s, with 1s at the mine-positions
Xô # Split it into `X`-sized parts to a matrix
2Fø0δ.ø} # Add a border of 0s around the matrix:
2F } # Loop 2 times:
√∏ # Zip/transpose; swapping rows/columns
δ # Map over each inner list:
0 .√∏ # Surround it with a leading/trailing 0
2Fø€ü3} # Convert it to a matrix of overlapping 3x3 blocks:
2F } # Loop 2 times again:
√∏ # Zip/transpose; swapping rows/columns
€ # Map over each inner list:
ü3 # Convert it to a list of overlapping triplets
OO # Sum each inner 3x3 block
JJ # Join all these digits together to a single string
'*®ǝ '# Replace the digit at the `®`-indices with "*"s
0'x: '# Replace all 0s with "x"s
Xô # Split it into `X`-sized parts again to a list of rows
» # Join it by newlines
# (after which the result is output implicitly)
```
[Answer]
# Mathematica - 247 chars
```
s[q_] :=
Module[{d, r},
d = ToExpression@Partition[Cases[Characters@q, Except@" "], 2];
r = Rest@d;
StringJoin @@@
ReplacePart[
Table[ToString@
Count[ChessboardDistance[{i, j}, #] & /@ Reverse /@ r, 1], {i,d[[1, 2]]},
{j, d[[1, 1]]}] /. {"0" -> "x"}, # -> "*" & /@ Reverse /@ r] // TableForm]
```
Examples:
```
s@"5 5 1 3 3 5 2 4"
s@"3 4 3 1 1 4 2 3 3 2"
```
Output:

`ChessboardDistance` computes how far each cell is from a mine, where 1 corresponds to "next to a mine". The `Count` of 1's yields the cell's number. Then mines (\*) are inserted into array.
[Answer]
## *Mathematica*, ~~140~~ ~~139~~ 137
```
Grid[(ListConvolve[BoxMatrix@1,#,2,0]/. 0->x)(1-#)/. 0->"*"]&@Transpose@SparseArray[{##2}->1,#]&@@#~Partition~2&@@#~ImportString~"Table"&
```
Writing that in a more readable form:
```
"5 5 1 3 3 5 2 4"
ImportString[%, "Table"][[1]] ~Partition~ 2
Transpose @ SparseArray[{##2} -> 1, #]& @@ %
ListConvolve[BoxMatrix@1, %, 2, 0]
(% /. 0 -> x) (1 - %%) /. 0 -> "*" // Grid
```
[Answer]
## VBA - 298 chars
```
Sub m(x,y,ParamArray a())
On Error Resume Next:ReDim b(x,y):For i=0 To (UBound(a)-1) Step 2:c=a(i):d=a(i+1):b(c,d)="*":For e=c-1 To c+1:For f=d-1 To d+1:v=b(e,f):If v<>"*" Then b(e,f)=v+1
Next:Next:Next:For f=1 To y:For e=1 To x:v=b(e,f):s=s & IIf(v<>"",v,"x")
Next:s=s & vbCr:Next:MsgBox s
End Sub
```
Skipping over errors with `On Error Resume Next` saved me some characters, but this still isn't nearly as good as some of the other answers. :-/
[Answer]
# C++, 230 chars
```
#import<iostream>
int*p,n,m,x,y,i,j,k,a[999][999];main(){for(std::cin>>m>>n;std::cin>>y>>x;)for(i=2;~i--;)for(j=2;~j--;*p+=i|j&&~*p?:~*p)p=a[x+i]+y+j;for(;k<n*m;std::cout<<char(x?~x?x+48:42:120)<<(j<m)+"\n")x=a[k/m+1][j=k++%m+1];}
```
-11 bytes thanks to `ceilingcat`
-15 bytes thanks again to `ceilingcat`. Truly bigbrain
-14 bytes thanks to `ceilingcat` and I
-8 bytes thanks to `ceilingcat` and I
[Try it online](https://tio.run/##RYzdaoQwGETv@xRhSxdjIq3Ri5rE@CDWi@D254skBjeFSFtf3ca2UAYOc2CY0fvidRz3/Rasn5cgYb6G5VlbdQMu5J46ammkKwVq6ER13zTN8ANhNbgMf7zMS3YNF85HcEpZpZz411WpKPAxgZaJDYri18xhJlnuSQuf5nzect/xBOxb3UcCA1mJEcdWTNLl9u90fg9Sjm96yWK3xS6S@pHXjJfsAUuZGWkxOT25E47pZbq3pBx6006E3B1VfO17hWpUoTKlRiy1CrFv)
[Answer]
# [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3) `j`, 59 50 bytes
```
2ẆVḤ\ðYY$v•ÞẠ:““£Þȯ1⁾ƛ•C]¥⸠ð=Ḟi#=¥:⸠ð=Ḟ#$Ạ0'xr?Ḣh÷
```
[Try it Online!](https://vyxal.github.io/latest.html#WyJqIiwiIiwiMuG6hlbhuKRcXMOwWVkkduKAosOe4bqgOuKAnOKAnMKjw57IrzHigb7Gm+KAokNdwqXiuKDDsD3huJ5pIz3CpTriuKDDsD3huJ4jJOG6oDAneHI/4biiaMO3IiwiIiwiWzMgNCAzIDEgMSA0IDIgMyAzIDJdIiwiMy40LjEiXQ==)
-2 bytes from switching the variable call with the register call
-3 bytes from using space over '? and vectorized reverse element
-1 from using a different division method for the end, beating APL
-2 from setting the register to a formatted string rather than formatting the pushed register value twice
-1 from rearranging the initial formatting
Explanation (old)
```
ḣḣ^ðYY$2ẆvV•ÞẠ:““£Þȯ1⁾ƛ•C]¥⸠ð=Ḟi#=¥:⸠ð=Ḟ#$Ạ0'xr?Ḣh÷­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠⁠‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏⁠⁠⁠‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁢⁡⁣‏⁠‎⁡⁠⁢⁡⁤‏⁠‎⁡⁠⁢⁢⁡‏⁠‎⁡⁠⁢⁢⁢‏⁠⁠‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁢⁢⁣‏⁠‎⁡⁠⁢⁢⁤‏⁠‎⁡⁠⁢⁣⁡‏⁠‎⁡⁠⁢⁣⁢‏‏​⁡⁠⁡‌⁣⁡​‎‎⁡⁠⁢⁣⁣‏⁠‎⁡⁠⁢⁣⁤‏⁠‎⁡⁠⁢⁤⁡‏⁠‎⁡⁠⁢⁤⁢‏⁠‎⁡⁠⁢⁤⁣‏⁠⁠‏​⁡⁠⁡‌⁣⁢​‎‎⁡⁠⁢⁤⁤‏⁠‎⁡⁠⁣⁡⁡‏⁠‎⁡⁠⁣⁡⁢‏‏​⁡⁠⁡‌⁣⁣​‎‎⁡⁠⁣⁡⁣‏⁠‎⁡⁠⁣⁡⁤‏⁠‎⁡⁠⁣⁢⁡‏⁠‎⁡⁠⁣⁢⁢‏⁠‎⁡⁠⁣⁢⁣‏⁠‎⁡⁠⁣⁢⁤‏⁠⁠⁠‏​⁡⁠⁡‌⁣⁤​‎‎⁡⁠⁣⁣⁡‏⁠‎⁡⁠⁣⁣⁢‏‏​⁡⁠⁡‌⁤⁡​‎‎⁡⁠⁣⁣⁣‏‏​⁡⁠⁡‌⁤⁢​‎‎⁡⁠⁣⁣⁤‏⁠‎⁡⁠⁣⁤⁡‏⁠‎⁡⁠⁣⁤⁢‏⁠‎⁡⁠⁣⁤⁣‏‏​⁡⁠⁡‌⁤⁣​‎‎⁡⁠⁣⁤⁤‏⁠‎⁡⁠⁤⁡⁡‏⁠‎⁡⁠⁤⁡⁢‏⁠‎⁡⁠⁤⁡⁣‏‏​⁡⁠⁡‌­
ḣḣ^ # ‎⁡head extract under twice, reverse stack. This gets the dimensions of the grid in proper order.
ðYY # ‎⁢Make a 2D grid of empty spaces in given size.
$2Ẇ # ‎⁣Swap the top of the stack to the mine coordinates, split into coordinate pairs
vV # ‎⁤decrement and reverse each point to properly index values
•ÞẠ # ‎⁢⁡Assign asterisks to the coordinates of the mines
:““£ # ‎⁢⁢duplicate, format into a single string and set the register.
Þȯ1⁾ # ‎⁢⁣get the neighboring cells for each cell, flatten by 1
ƛ•C] # ‎⁢⁤Set each cell to the number of neighboring mines
¥⸠ð=Ḟ # ‎⁣⁡Push register, check if cell isnt a mine
i#= # ‎⁣⁢Set a ghost variable to the indexes of those cells
¥:⸠ð=Ḟ # ‎⁣⁣Push the register, duplicate, check if cells aren't mines on one copy
#$ # ‎⁣⁤push the ghost variable
Ạ # ‎⁤⁡Assign the value of neighboring mines to the cells that aren't mines in the string of only mines and spaces
0'xr # ‎⁤⁢replace any 0 valued cells with an 'x'
?Ḣh÷ # ‎⁤⁣split into the number of rows determined by the second number in the input
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
## Python, 192 182 180 chars
I could save some if the input was comma-separated. Then the first line would be `d=input()` and the length 171 chars.
Having the mine coordinates 0-based rather than 1-based would also help. It cost me 8 chars to overcome.
```
d=map(int,raw_input().split())
m=zip(d[2::2],d[3::2])
for y in range(d[1]):print"".join((str(sum(abs(a-x-1)|abs(b-y-1)<2for a,b in m)or'x')+'*')[(x+1,y+1)in m]for x in range(d[0]))
```
Ungolfed version:
```
d=map(int,raw_input().split()) # Read whitespace terminated numbers into a list of numbers
xsize,ysize = d[:2] # The first two numbers are the board size
mines=zip(d[2::2],d[3::2]) # Convert items 3,4,5,6... to pairs (3,4),(5,6) representine mine coordinates
def dist(point,mine): # Distance between point (0-based coordinates) and mine (1-based coordinates)
dx = abs(mine[0]-(point[0]+1))
dy = abs(mine[1]-(point[1]+1))
return dx | dy # Should be max(dx,dy), but this is close enough. Wrong for d>=2, but returns >=2 in this case.
for y in range(ysize): # Print lines one by one
line_chars = [
(str(
sum(dist((x,y),(a,b))<2 for a,b in mines) # Number of neighboring mines
or 'x' # 'x' instead of 0
)
+'*') # For a single neighbor, we get "1*"
[(x+1,y+1)in mines] # If a mine, get the '*', else the neighbor number
for x in range(xsize)
]
print "".join(line_chars)
```
[Answer]
# Scala, 280 chars
```
val n=readLine split" "map{_.toInt}
val b=Array.fill(n(1),n(0))(0)
n drop 2 sliding(2,2)foreach{case Array(x,y)=>b(y-1)(x-1)=9
for{i<-(x-2 max 0)to(x min n(0)-1);j<-(y-2 max 0)to(y min n(1)-1)}b(j)(i)+=1}
b.map{r=>println(r.map{case 0=>"x"case x if x>8=>"*"case x=>""+x}mkString)}
```
[Answer]
# [Haskell](https://www.haskell.org/), 155 bytes
```
main=interact$f.map read.words
f(x:y:a)=unlines[["x12345678*"!!min((i,j)#a)9|i<-[1..x]]|j<-[1..y]]
p@(a,b)#(x:y:z)=div 9(9^max(abs$a-x)(abs$b-y))+p#z
_#_=0
```
[Try it online!](https://tio.run/##JczdDkMwGIDhc1fR4aDdkFH7IZPsPqSTz1RWoxO1rcS9m1jek@fofYB68rqe5waETITseQf33i69BlrUcSi876srlFFiHQ8xkOQtayG5SlNT@wEND8fTeWtuNo2QGAunIhaQaBIXN/U9TzM2VX8OjBntFYOTE2tdjSQpxAdFOLo1oDHkygZXkxW5OxCya63RyKws2c8zRSGiyF8KUbCIouAH "Haskell – Try It Online")
[Answer]
## C++ - 454 chars
This is worse than my VBA answer, which probably means I don't know what I'm doing in C++. However, I am trying to build on what I know of C++, so here it is. If anyone has any suggestions for improvement, I'd be grateful to hear them!
```
#define Z for(int i=
#define Y for(int j=
#define X d[i][j]
#define W Z 0;i<x;i++){
#define V Y 0;j<y;j++){
#define U cout<<
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
int main(){using namespace std;int x,y,a,b;cin>>y>>x;string c[x][y];int d[x][y];W V X=0;}}while(cin>>b>>a){c[--a][--b]="*";Z a-1;i<=a+1;i++){Y b-1;j<=b+1;j++){if(x>i&&i>=0&&y>j&&j>=0){X=X+1;}}}}W V if(c[i][j]!="*"){if(X>0){U X;}else{U"x";}}else{U"*";}}U endl;}return 0;}
```
[Answer]
**C# (691 Chars)**
```
using System;namespace M{class P{static char C(char[][] g,int r,int c){int n=0;for(int i=r-1;i<=r+1;i++){if(i<0||i>=g.Length)continue;for(int j=c-1;j<=c+1;j++){if((j<0||j>=g[0].Length)||(i==r&&j==c))continue;if(g[i][j]=='*')n++;}}return n==0?'x':(char)(n+48);}static char[][] G(int[] p){char[][] r=new char[p[1]][];for(int i=0;i<r.Length;i++)r[i]=new char[p[0]];for(int i=2;i<p.Length;){r[p[i+1]-1][p[i]-1]='*';i+=2;}for(int i=0;i<r.Length;i++)for(int j=0; j<r[0].Length;j++)if(r[i][j]!='*')r[i][j]=C(r,i,j);for(int i=0;i<r.Length;i++){for(int j=0;j<r[0].Length;j++)Console.Write(r[i][j]);Console.WriteLine();}return r;}static void Main(string[] args){G(new int[]{3,4,3,1,1,4,2,3,3,2});}}}
```
Non-golfed Version:
```
using System;
namespace M
{
class P
{
static char C(char[][] g, int r, int c)
{
int n = 0;
for (int i = r - 1; i <= r + 1; i++)
{
if (i < 0 || i >= g.Length) continue;
for (int j = c - 1; j <= c + 1; j++)
{
if ((j < 0 || j >= g[0].Length) || (i == r && j == c)) continue;
if (g[i][j] == '*') n++;
}
}
return n == 0 ? 'x' : (char)(n + 48);
}
static char[][] G(int[] p)
{
char[][] r = new char[p[1]][];
for (int i = 0; i < r.Length; i++)
r[i] = new char[p[0]];
for (int i = 2; i < p.Length; )
{
r[p[i + 1] - 1][p[i] - 1] = '*';
i += 2;
}
for (int i = 0; i < r.Length; i++)
for (int j = 0; j < r[0].Length; j++)
if (r[i][j] != '*') r[i][j] = C(r, i, j);
for (int i = 0; i < r.Length; i++)
{
for (int j = 0; j < r[0].Length; j++)
Console.Write(r[i][j]);
Console.WriteLine();
} return r;
}
static void Main(string[] args)
{
G(new int[] { 3, 4, 3, 1, 1, 4, 2, 3, 3, 2 });
}
}
}
```
[Answer]
# K, 175
```
f:{g::(y;x)#(x*y)#"x";{.[`g;x;:;"*"]}@'-1+|:'(_(#z)%2;2)#z;{if[~"0"~z;$["x"=g .(x;y);.[`g;(x;y);:;z];]]}.'i,'$s:+/'{"*"=g . x}''{,/((x-1)+!3),\:/:(y-1)+!3}.'i:,/(!x),\:/:!y;g}
```
.
```
k)f[5;5;1 3 3 5 2 4]
"xxxxx"
"11xxx"
"*21xx"
"2*21x"
"12*1x"
k)f[3;4;3 1 1 4 2 3 3 2]
"x2*"
"13*"
"2*2"
"*21"
```
[Answer]
**ECMAScript 2019 (Modern Javascript) - 116 bytes**
```
m.map((r,i)=>r.map((c,j)=>c=='X'?c:[,...m].splice(i,3).map(r=>[,...r].splice(j,3)).flat().filter(v=>v=='X').length))
```
**ungolfed version**
```
m.map(
(r,i) => r.map(
(c,j) => c=='X' ? c :
[,...m].splice(i,3).map(r=>[,...r].splice(j,3)).flat().filter(v=>v=='X').length
)
)
```
*this solution doesn't strictly adhere to the input/output format but demonstrates a succinct algorithm.*
example:
<https://gist.github.com/missinglink/ee02084cfb523665e8c9d34c24f01537>
]
|
[Question]
[
## Introduction
The idea is to use the asterisk character (star) `*` to display an ascii-art star at a specified dimension. The dimension is an input number greater than or equal to \$1\$ that specifies the height in lines of the upper point of the star. The stars here are intended to be six pointed stars with larger sizes looking better from a picture perspective.
In all cases the ascii-art representation of the stars are to appear as two triangles that overlap as shown in the following examples.
## Parametrics
The following picture and table of data describes attributes for the first seven sizes of the star. Each of the parameters grows in an arithmetic progression as \$N\$ increases, **except \$N=1\$ is different**.
[](https://i.stack.imgur.com/C6TOV.png)
[](https://i.stack.imgur.com/IXHK8.png)
## Examples
For an input of 1 (the degenerate case) the program output should be as follows:
```
*
*****
*****
*
```
Input of 2:
```
*
***
*********
*******
*********
***
*
```
(3)
```
*
***
*****
***************
*************
***********
*************
***************
*****
***
*
```
(5)
```
*
***
*****
*******
*********
***************************
*************************
***********************
*********************
*******************
*********************
***********************
*************************
***************************
*********
*******
*****
***
*
```
## Challenge
Your task is to create a function or program that will accept the number N as input and then output the appropriately sized star using just characters and the `*` character.
* You may assume that the input value is always a positive integer.
* Trailing whitespace on the output lines is OK.
* The program algorithm should be general enough for any \$N\$ input to produce the star art
output. Practical limitations exist of course due to display output
size.
* Output should print to STDOUT.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply.
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the code with the shortest number of bytes wins!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 21 bytes
```
3*s≠-L·<sÅ0«Âø€à'*×.C
```
[Try it online!](https://tio.run/##ASsA1P9vc2FiaWX//zMqc@KJoC1Mwrc8c8OFMMKrw4LDuOKCrMOgJyrDly5D//81 "05AB1E – Try It Online")
or as a [Test Suite](https://tio.run/##ATQAy/9vc2FiaWX/NUx2eXl5/zMqc@KJoC1Mwrc8c8OFMMKrw4LDuOKCrMOgJyrDly5D/yzCtj//)
**Explanation**
```
3* # multiply input by 3
s≠- # subtract 1 if the input isn't 1
L # push range [1 ... (3*n-(n!=1))]
·< # multiply by 2 and subtract 1 to get odd numbers
sÅ0« # append n zeroes
Âø # zip with a reversed copy
ۈ # get the largest number in each pair
'*× # repeat "*" for each number in the list
.C # format centered
```
[Answer]
# [Haskell](https://www.haskell.org/), 114 bytes
Builds a function `g` which takes an number and produces a `IO` monad that prints the star to STDOUT. I think this is ok.
```
f=replicate
a%b=mapM_(\n->putStrLn$f(a-n)' '++f(2*n-3)'*')$zipWith max<*>reverse$[2..a]++f b 0
g 1=4%1
g a=(3*a)%a
```
[Try it online!](https://tio.run/##Dcq7DsIgGEDhvU/BAOHS0NjWUfoEOjk4qDF/DbREIISiMb48Mp3hOytsL@1cKUYlHZ19QtYNkFl5iKcHuwU5xXc@53QM2DCQgVNE29awQQQ5ciooxz8bLzavyMP3IKakPzptGl@HroN7XdGMds2CerUnfS0oNgrgBIoHG1SF8gc "Haskell – Try It Online")
## Explanation
First lets talk about the lambda.
```
\n->putStrLn$f(a-n)' '++f(2*n-1)'*'
```
This takes a number, `n`, to be drawn as stars. We print twice that many stars and then 1 more and pad it on the right to the size of the image. We pad this on the right by `a` spaces to center the line of stars. We can use this lambda to draw each line.
From this lambda we create `(%)`. `(%)` starts with doing `mapM_` with our lambda to turn a profile into the shape.
Now all we need to do is make a list of the profile for the star. We can do this by making a triangle first with `[1..a]`, then padding it with some zeros `++replicate b 0`. If we take the profile of the triangle and reverse it we get the other half of the star. To super impose them we just make a new profile where each entry is the max of the two triangles. This is `zipWith max`.
We then call this in one of two ways: as `3%1` for input of `1` and with `(3*a-1)%a` otherwise.
From here we do a little bit of fiddling with some of the values to shave some bytes. Since `3*a-1` is rather long we offset some of our other values by 1 so that everything cancels and we get the intended behavior with `3*a` instead. Namely we start our list at `2` instead of `1` and do `2*n-3` instead of `2*n-1` to make up for the change.
## Alternative version, 114 bytes
This one builds a point-free function `(%)<*>min 2`
```
f=replicate
a%b=mapM_(\n->putStrLn$f(3*a-n)' '++f(2*(n-b)+1)'*')$zipWith max<*>reverse$[b..3*a]++f a 0
(%)<*>min 2
```
[Try it online!](https://tio.run/##Dcu7DsIgGEDhvU/BQMMtNFrX0ifQycFBjfkx0BKBEIrG@PLIdpKTb4XtZbyv1apskndPKKaDXqsA6fSgtyjn9C7nko8RW3rgICMjiAhh6chplJqJPSOcMPxz6eLKigJ8Jz5n8zF5M/iqh6GpewMI0K5bFO1Z@8FFNNYALqqlxR8 "Haskell – Try It Online")
## Handles all \$N>1\$, 98 bytes
```
f=replicate
g a=mapM_(\n->putStrLn$f(3*a-n)' '++f(2*n-3)'*')$zipWith max<*>reverse$[2..3*a]++f a 0
```
[Try it online!](https://tio.run/##Dcu7DsIgFADQ3a@4AwmPhsbQVfoFOjk4qDE35tISgRBKG@PPY/dzZlw@FEJrzhbKwb@x0mECtBHz5SUeSY95rddazok5MSjUSXLgXeeEUUkPkisu2c/nm68zRPye1Fhoo7IQu5u@38dzx4BwbBF9shOY9gc "Haskell – Try It Online")
## Handles all cases like the \$N=1\$ case, 98 bytes
```
f=replicate
g a=mapM_(\n->putStrLn$f(3*a-n)' '++f(2*n-1)'*')$zipWith max<*>reverse$[1..3*a]++f a 0
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P822KLUgJzM5sSSVK10h0TY3scA3XiMmT9euoLQkuKTIJ08lTcNYK1E3T1NdQV1bO03DSCtP11BTXUtdU6UqsyA8syRDITexwkbLrii1LLWoOFUl2lBPD6gjFqhYIVHB4H9uYmaebbqCyX8A "Haskell – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~125~~ ~~107~~ 101 bytes
```
function(n,S=3*n+!n-1,P=pmax(I<-c(2:S*2-3,!1:n),rev(I)),`~`=strrep)write(paste0(' '~S-1-P/2,'*'~P),1)
```
[Try it online!](https://tio.run/##FcRLDoMgEADQfU@hK2bokBbsJzFyAHckXkBjIHEhJUg/K65Ow1u8WFwziOLefk3by4OnSXfcn1svJBkd9uUH4yBWUP3Eleiolb1HivYDIyLNedZHitEG/MYtWQjLkewVWMPyJKQwF0WMs2yQJBYHEk8OVK2r3Wr32qP2xPIH "R – Try It Online")
* -24 thanks to @Giuseppe
---
Previous (different) approach :
# [R](https://www.r-project.org/), ~~150~~ ~~148~~ ~~136~~ ~~135~~ ~~130~~ 128 bytes
```
function(n,G=n<2,K=4*n-1+G)for(i in 1:K-1)cat(`[<-`(rep(' ',W<-3*n-2+G),1+W+c(-i:i*(i<K-n),-(j=K-i-1):j*(i>=n)),'*'),sep='','
')
```
[Try it online!](https://tio.run/##FcsxDoMwDIXhvadgsw32EKCthJKuDDkAQxcqRKQwGETp@dNk@Yan/50puBR@ulxxV1QendqWvetrFdOMFPYTYxW1MoMXQ8vnwvltZcZzPRAq4MlKl9s2t2yaqVlQ4hBrjNaLEgtuzkvM12HL48spEUMNxN/1cAAMN6AU0NAtYFvoCn3hXngUnpT@ "R – Try It Online")
* -14 thanks to @Kirill L.
* -1 thanks to @t-clausen.dk
* -7 thanks to @Giuseppe
[Answer]
# [Python 2](https://docs.python.org/2/), ~~101~~ ~~99~~ 97 bytes
```
n=input()
x=2*(n>1)
for i in range(1,8*n,2):print('*'*[i,8*n-i-x][i+x>n*6or i/n/2%2]).center(6*n)
```
[Try it online!](https://tio.run/##FctBCoMwEAXQvafIpjgz1YpTCFLQi4iLUtJ2Nt8QIqSnT3H74MVf/u7QWjEb4pGJmzKrEJaRm/eenDmDS098Ao3dJOiUHzEZMrXSymqn9daXbbVrWSD@PAMGvejGt1dADom8gGu9/wE "Python 2 – Try It Online")
-2 bytes, thanks to Lynn
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~101~~ 108 bytes
*EDIT: +7 bytes to print to STDOUT*
```
n=>print((k=3*n+!~-n,g=y=>++y<k+n?`
`.padEnd(w=k-Math.max(y>n&&n-y+k,y<k&&y)).padEnd(2*k+~w,'*')+g(y):'')``)
```
[Try it online!](https://tio.run/##NcqxDoIwEADQnb9wae84SiJoYoytk6P/0EYCQuOFIAG78OvVDi5veoNb3Psx9eOsllNsdWRtxqnnGcDrOmfabYqLTgdtiMLFE19tZsvRNTduYNVe3d38LF/uA8GwEKwC@eIXhQiI/1flnra1kLlE6iDgWUq0FmMLe8xaqBJ14pA4YvwC "JavaScript (V8) – Try It Online")
### Commented (without `print`)
```
n => ( // n = input
k = // k is half the maximum width of the star + 1.5
3 * n + !~-n, // k = 3n if n > 1 or 4 if n = 1
g = y => // g = recursive function taking y
++y < k + n ? // increment y; if y is less than k + n:
`\n` // append a line feed
.padEnd( // append w - 1 leading spaces:
w = // where w is defined as
k - // k minus
Math.max( // the maximum of:
y > n // - true (coerced to 1) if y > n
&& n - y + k, // or n - y + k otherwise (bottom triangle)
y < k && // - true (coerced to 1) if y < k
y // or y otherwise (top triangle)
) // end of Math.max()
) // end of padEnd()
.padEnd( // append 2 * (k - w) - 1 stars
2 * k + ~w, // by padding to 2 * k - w - 1
'*' //
) + // end of padEnd()
g(y) // append the result of a recursive call
: // else:
'' // stop recursion
)`` // initial call to g with y = [''] (zero-ish)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 21 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
×3’+ỊR;Ṭ»Ṛ$”*ẋz⁶ṚZŒBY
```
A full program accepting a positive integer which prints to STDOUT.
**[Try it online!](https://tio.run/##ATMAzP9qZWxsef//w5cz4oCZK@G7ilI74bmswrvhuZok4oCdKuG6i3rigbbhuZpaxZJCWf///zU "Jelly – Try It Online")** Or see a [test-suite](https://tio.run/##y0rNyan8///wdONHDTO1H@7uCrJ@uHPNod0Pd85SedQwV@vhru6qR43bgNyoo5OcIv8fbn/UtObItEggGfn/v6ERAA "Jelly – Try It Online").
### How?
```
×3’+ỊR;Ṭ»Ṛ$”*ẋz⁶ṚZŒBY - Main Link: integer, n e.g. 3
3 - three 3
× - multiply (n by) 9
’ - decrement 8
Ị - insignificant (abs(n)<=1)? 0
+ - add 8
R - range [1,2,3,4,5,6,7,8]
Ṭ - un-truth (n) [0,0,1]
; - concatenate [1,2,3,4,5,6,7,8,0,0,1]
$ - last two links as a monad:
Ṛ - reverse [1,0,0,8,7,6,5,4,3,2,1]
» - maximum (vectorises) [1,2,3,8,7,6,7,8,3,2,1]
”* - an asterisk character '*'
ẋ - repeat (vectorises) ["*","**",...]
⁶ - a space character ' '
z - transpose with filler ["***********"," ********* ",...]
Ṛ - reverse [" * * "," ** ** ",...]
Z - transpose [" *"," **",...]
ŒB - bounce (vectorises) [" * "," *** ",...]
Y - join with newline characters " * \n *** \n..."
- implicit print
```
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), ~~25~~ 23 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
R:{⁸3×4M∔]∔{*×]↔⁸1≡?╪]┼
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjMyJXVGRjFBJXVGRjVCJXUyMDc4JXVGRjEzJUQ3JXVGRjE0JXVGRjJEJXUyMjE0JXVGRjNEJXUyMjE0JXVGRjVCKiVENyV1RkYzRCV1MjE5NCV1MjA3OCV1RkYxMSV1MjI2MSV1RkYxRiV1MjU2QSV1RkYzRCV1MjUzQw__,i=Mw__,v=8)
[15 bytes](https://dzaima.github.io/Canvas/?u=JXVGRjMyJXVGRjFBJXVGRjVCJXUyMDc4JXVGRjEzJUQ3JXUyMjE0JXVGRjNEJXUyMjE0JXVGRjVCKiVENyV1RkYzRCV1MjE5NCV1MjUzQw__,i=Mw__,v=8) without handling `1`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes
```
×’»ɗ3”*xⱮz⁶ɓ⁶x;»Ṛ$ŒBY
```
[Try it online!](https://tio.run/##y0rNyan8///w9EcNMw/tPjnd@FHDXK2KRxvXVT1q3HZyMpCosD60@@HOWSpHJzlFghQax9sZqhiClRhYOxhUqORDZR/u7n7UuE9L4b8JAA "Jelly – Try It Online")
A monadic link accepting a single integer as its left argument and returning a newline-separated Jelly string with the star as its output. When run as a full program implicitly prints the star to STDOUT.
### Explanation
```
ɗ3 | Last three links as a dyad with 3 as right argument:
× | Multiply (by 3)
’ | Decrease by 1
» | Maximum of this (and 3)
”*xⱮ | An implicit range from 1 to this many asterisks
z⁶ | Zip with space as filler
ɓ | Start a new dyadic chain with the input as left argument and the list of asterisks as right argument
⁶x | Input many spaces
; | Concatenated to the asterisk list
$ | Last two links as a monad:
»Ṛ | Maximum of this list and its reverse
ŒB | Bounce each list (i.e. mirror it without duplicating the middle entry)
Y | Join with newlines
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes
```
G↙θ←⁺⊗θ¬⊖θ↑⊗θ↘⊕θ*‖O¬C⁰¬⊖θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8gP6cyPT9Pw8olvzzPJzWtREehUEfBCsIKyCkt1nDJL03KSU3RKNTUUfDLL9FwSU0uSs1NzSsBi2kCRa1CC3QUkJWBDQvKTM8AmuGZh6xcR0FJS0nTmisoNS0nNbnEvyy1KCexQMPq0BqgoHN@QaWGAXZbrP//N/yvW5YDAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
G↙θ←⁺⊗θ¬⊖θ↑⊗θ↘⊕θ*
```
Draw an irregular pentagon representing the top right quarter of the star, but special-casing `1` to make the row an extra column wider.
```
‖O¬
```
Reflect to complete the star.
```
C⁰¬⊖θ
```
More special-casing to make the star for `1` an extra row taller.
Alternative solution, also 25 bytes:
```
∧¬⊖θ*G↗↓⊖׳N*‖O‖OO↓∧⊖θ⊖⊗θ
```
[Try it online!](https://tio.run/##ZY69DoIwFIV3nqJhujV1MG4wmXRxAUL0AUq5Akn/rC3Gp68aJZG4npPznU@OwksrVEqNn0yAg@mhsgE4So8aTcAerpQykm9ySsusseoxWAPF2bXTMAZGCm7vhpHfwWnSeIM9I0fjYqii7tADXShl1uJFoQz1jF4JB3/JUnzRb6e1z/qO29ipj@dLMaVd2s7qCQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
∧¬⊖θ*
```
Print an extra `*` for the case of `1`.
```
G↗↓⊖׳N*
```
Draw the left half of a triangle of the appropriate size.
```
‖O
```
Reflect to complete the triangle.
```
‖OO↓∧⊖θ⊖⊗θ
```
Overlap it with its reflection, except in the case of `1`, in which case just reflect it.
14 bytes without special-casing for `1`:
```
G<⊖׳N*‖OO↑⊖⊗θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8gP6cyPT9Pw8pGR8ElNbkoNTc1ryQ1RSMkMze1WMNYR8Ezr6C0xK80Nym1SENTU1NHQUlLSdOaKyg1LSc1ucS/LLUoJ7EASmlYhRagGuOSX5qUA6QLgVqt//83/q9blgMA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
G<⊖׳N*
```
Draw a triangle of the appropriate size.
```
‖OO↑⊖⊗θ
```
Overlap it with its reflection.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 74 bytes
```
{$_ Z~|[R,] $_}o{.&{|((' 'x--$+$_*3~'*'x$++*2+1)xx$_*3-($_>1)),|($ xx$_)}}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1olXiGqriY6SCdWQSW@Nr9aT626RkNDXUG9QldXRVslXsu4Tl1LvUJFW1vLSNtQs6ICJKSroRJvZ6ipqVOjoaIAEtKsrf2fpmGoaWenV5xYac2VpmGExDaGsf8DAA "Perl 6 – Try It Online")
Literally creates a triangle with the right proportions and overlaps it with a upside-down copy using the string or operator (`~|`). Outputs as a list of lines with a leading and trailing line whitespace.
### Explanation:
```
{.&{ } # Anonymous code block
( )xx$_*3-($_>1) # Repeat n*3-(n!=1) times
' 'x--$+$_*3 # With a decreasing indentation
~'*'x$++*2+1 # Append an increasing triangle
# This creates the triangle
,|($ xx$_) # And add some padding lines
{ }o # Pass the triangle to the combining function
Z~| # Zip string bitwise or
$_ # The list
[R,] $_ # With its reverse
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 25 bytes
+5 bytes for `n=1` :\
```
õ cUon3*U-´UÎ)®ç* êÃê!U û
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=9SBjVW9uMypVLbRVzimu5yog6sPqIVUg%2bw&input=MQ)
```
õ cUon3*U-´UÎ)®ç* êÃê!U û :Implicit input of integer U
õ :Range [1,U]
c :Concatenate
Uo : Range [0,U)
n : Subtract each from
3*U- : Multiply U by 3 and subtract
´U : Decrement U
Î : Get sign
) :End concat
® :Map each Z
ç* : Repeat "*" Z times
ê : Palindromise
à :End map
ê!U :If decremented U is 0, append reverse, else, palindromise
û :Centre pad each line with spaces to the length of the longest
:Implicitly join with newlines and output
```
[Answer]
# [J](http://jsoftware.com/), ~~53~~ 50 bytes
```
' *'{~[:(+.|.),.@#&0,~[:(|.,}.)"1*@<:>:/~@i.@-~3*]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/1RW01Kvroq00tPVq9DR19ByU1Qx0QPwaPZ1aPU0lQy0HGys7K/06h0w9B906Y63Y/5pcXKnJGfkKaQqGEIa6OkzACF3A@D8A "J – Try It Online")
## ungolfed
```
' *' {~ [: (+. |.) ,.@#&0 ,~ [: (|. , }.)"1 *@<: >:/~@i.@-~ 3 * ]
```
## how
Use a function table (like a 3rd grade times table) to construct half the triangle by using `>:` (greater than or equal) as the function. Then reverse each row, chop of the last column, and stitch the two sides together to get the full triangle (but made of 1 and 0). Add `n` rows of zeros at the bottom. Finally reverse the whole thing, and overlay it on the original, using boolean or `+.` to get the result. Then turn the 1 to `*` and 0 to spaces.
[Answer]
# T-SQL, 194 bytes
`@` is the input value
`@c` handles the width of the top triangle
`@d` handles the width bottom triangle
`@e` contains the output either `@c` or `@d` - this saves a few bytes
`@f` handles the special case of 1 as input. `@c*@=3` determines when to use `@f`. 5 bytes cheaper than writing `@c=3and @=1`
```
DECLARE @ INT=8
,@c INT=1,@e INT=1,@d INT,@f INT=0SET @d=@*8-3r:PRINT
space(@*3-@e/2+@f/2)+replicate('*',@e-@f)SELECT
@c=nullif(@c,@*6-3)+2,@f=iif(@c*@=3,2,0),@d-=2-@f,@e=iif(@c>@d
or @c/2<@,@c,@d)IF @d>0goto r
```
**[Try it online](https://data.stackexchange.com/stackoverflow/query/1030947/stars-make-stars)**
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `j`, 53 bytes
```
1=[ðd×+:,×5*:,,,|(⁰3*⇩n-ð*nd›×*+)⁰(nð*6⁰*3-nd-×*+)Wøm
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=j&code=1%3D%5B%C3%B0d%C3%97%2B%3A%2C%C3%975*%3A%2C%2C%2C%7C%28%E2%81%B03*%E2%87%A9n-%C3%B0*nd%E2%80%BA%C3%97*%2B%29%E2%81%B0%28n%C3%B0*6%E2%81%B0*3-nd-%C3%97*%2B%29W%C3%B8m&inputs=1&header=&footer=)
[Answer]
# [Haskell](https://www.haskell.org/), 105 bytes
```
f n|h<-3*n-min 2n=mapM putStrLn[([x+1..h]>>" ")++do[-x..x];"*"|x<-zipWith max<*>reverse$[0..h]++[1-n..0]]
```
[Try it online!](https://tio.run/##JcwxDsIgGEDhq/whDgqBlNZNygl0cnAgDCTSQCy0oWiI6d2xptM3vefM8rLjWOsAcXWCdjjS4CO0sQ9mvsH8zvecrlEdVSGcMaelRIBOhDwnRQtjRV8QRmsR9Ovnh88OgikCy2Q/Ni32oJp/RIjiNDLWaF2D2f49DMBByo12p9s51x8 "Haskell – Try It Online")
]
|
[Question]
[
Recently, my reputation was `25,121`. I noticed that each digit grouping (i.e. the numbers separated by commas) was a perfect square.
Your challenge is, given a non-negative integer **N** and a unary boolean [Black Box Function](https://codegolf.meta.stackexchange.com/a/13706/31957) *f* : **Z\*** → **B** , yield a truthy value if each value of *f* applied to the digit groupings of **N** is truthy, and falsey otherwise.
One can find the digit groupings by splitting the number into groups of 3, starting from the right side. The leftmost group may have 1, 2, or 3 digits. Some examples:
```
12398123 -> 12,398,123 (3 digit groupings)
10 -> 10 (1 digit grouping)
23045 -> 23,045 (2 digit groupings)
100000001 -> 100,000,001 (3 digit groupings)
1337 -> 1,337 (2 digit groupings)
0 -> 0 (1 digit grouping)
```
## Additional rules
* This function can map to either booleans (e.g. `true` and `false`), `1`s and `0`s, or any truthy/falsey value. Please specify which format(s) are supported by your answer.
* You may take an integer as input, or an integer string (i.e. a string composed of digits).
* You may write a program or a function.
* When passing the digital groups to the function *f*, you should trim all unnecessary leading zeroes. E.g., *f*, when applied to **N** = 123,000 should be executed as *f*(123) and *f*(0).
## Test cases
Function notation is `n -> f(n)`, e.g., `n -> n == 0`. All operators assume integer arithmetic. (E.g., `sqrt(3) == 1`)
```
function f
integer N
boolean result
n -> n == n
1230192
true
n -> n != n
42
false
n -> n > 400
420000
false
n -> n > 0
0
false
n -> n -> 0
1
true
n -> sqrt(n) ** 2 == n
25121
true
n -> sqrt(n) ** 2 == n
4101
false
n -> mod(n, 2) == 0
2902414
true
n -> n % 10 > max(digits(n / 10))
10239120
false
n -> n % 10 > max(digits(n / 10))
123456789
true
```
[Answer]
## [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes
```
ḃ₁₀₀₀↰₁ᵐ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GO5kdNjY@aGqCobQOQ@3DrhP@qj5qaDP4bWRoYmRiaAAA "Brachylog – Try It Online")
The blackbox function goes on the second line (or the "Footer" on TIO) and the integer is read from STDIN. Prints `true.` or `false.` accordingly.
```
ḃ₁₀₀₀ Compute the base-1000 digits of the input.
↰₁ᵐ Map the blackbox predicate over each digit. We don't care about the
result of the map, but the predicate must succeed for each digit,
otherwise the entire map fails.
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~16~~ 13 bytes
*3 bytes saved thanks to @Adám*
```
∧/⎕¨1e3⊥⍣¯1⊢⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM9DUgs13/UN/XQCsNU40ddSx/1Lj603vBR1yKgGEjBfwUwSOMyMjU0MuSq1njU0/WocyFQgeaj3q1aeqa1XHAVlgZGJoYmXNUGtkY1QMlaAA "APL (Dyalog Unicode) – Try It Online")
**How?**
`1e3⊥⍣¯1⊢⎕` - input the number and encode in base 1000
`⎕¨` - input the function and apply on each
`∧/` - reduce with logical and
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
bȷÇ€Ạ
```
[Try it online!](https://tio.run/##ASIA3f9qZWxsef/huILhuYb/Ysi3w4figqzhuqD///8yOTAyNDE0 "Jelly – Try It Online")
The command-line argument is the number. The line above the line this function resides in is the main line of the rest of the program, that is, the code that gets called for each of the groups. **Be careful not to refer to the line `bȷÇ€Ạ` is in!** The example used here is the 5th test case.
[Answer]
# [Python 2](https://docs.python.org/2/), 46 bytes
```
g=lambda f,n,k=1000:f(n%k)and(n<k or g(f,n/k))
```
[Try it online!](https://tio.run/##NcpBCoAgEAXQfadwEzgiNQpBRB7GCCusn4SbTm8RtH4v3Xk9YUtZ3O6PafYiaOjoDDMPQaKO5DFLjFGcl1jkq20kKuHvGOCchFLcdKSUrdK1IX/TdsYa7g1V5QE "Python 2 – Try It Online")
[Answer]
## Haskell, ~~42~~ ~~40~~ 38 bytes
```
f#n=f(mod n 1000)&&(n<1||f#div n 1000)
```
The blackbox function must return `True` or `False`.
[Try it online!](https://tio.run/##jYuxCoNAEAX7fMWDC3JXCLurjZD1S9IIl8NDXUMSrPz3s5A0qTLlMDMO7@kxz6UkZ5r8skYYmIhCVXm78b4nF/P2lWUZskER1wvwfGX74Ap/t7o/T1GlAAfpSFpu/4ma38hULeDEgaUh7qQc "Haskell – Try It Online")
Edit: ~~-2~~ -4 bytes thanks to @ovs.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~66~~ ~~58~~ 48 bytes
*-10 bytes thanks to @Neil!*
```
t=1000;g(f,i)int f();{i=f(i%t)&(i<t||g(f,i/t));}
```
[Try it online!](https://tio.run/##dY3RTsMgGEbv9xS/S2ogYSlQvFgqPok3hEEl6eiEf9Gk66uL7fSiifX2nPPls4fO2uI5iXRMDq8pQnzh7bTzYo20jguTa/bww5oVuwwfhISINL8nnDmT9Hep1stKar181DXgm4PeZAR/jRbDECFk6J1HMBlMBPfpkg3ZgR/SPU7OnFwqqAXnvO2IZ4HOj@AJbcegPQkV0kcSnvF2u9saKW2ncjYhEjruLmmuPdlXp9e4Z3PBGZ@Dv1wwIRsujnLTSqa2RcPkk5DiH6cE31aKySOXSqjFTuXL@t50uRz68zc "C (gcc) – Try It Online")
[Answer]
## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 30 bytes
```
And@@#/@#2~IntegerDigits~1000&
```
[Try it online!](https://tio.run/##nY5dCwFBFEDf/YqrKSHlzt3xsQ90FcqDIo/bqo1pTTGbNaS0@9cXWcqT8no6p84hcjt9iJzZRMUiNdYBN6FejOyWWbRZUD6zTsc6HZvYuFMuEbFWNICZ4VYBuAkYDEBArQWSPJQ@Za0XrpZYlWS6T5I0WB1TF4gwXNOno44k@cNREktlctF2@Yh8JCXVi82TbSAeAxjCEObRlb@eeXlOnNHWvZ3nK5LnS8K/e/JUp9vr@1klK@4 "Wolfram Language (Mathematica) – Try It Online")
[Answer]
## JavaScript (ES6), ~~40~~ 36 bytes
```
f=>g=i=>f(i%1e3)&(i<1e3||g(i/1e3|0))
```
Takes the function and value by currying and returns 0 or 1. Edit: Saved 4 bytes thanks to @Shaggy.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 9 bytes
```
.AyMjQ^T3
```
[Try it online!](https://tio.run/##K6gsyfj/36cwKa7YIclIwUhTz7HSNyswLsT4/38jU0MjQwA "Pyth – Try It Online") (uses the third test case)
Assumes the black-box function is named `y`. You can declare such a function using `L` (argument: `b`), as shown on TIO. I will implement all the test cases later, if I have time.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 8 bytes
```
Vk|Eym|A
```
Stax programs do not have function calls or arguments, so we store a block in the `Y` register that consumes and produces a single value. This can be done before the program code.
```
{...}Yd store a block in the Y register that executes ...
Vk|E get "digits" of input using base 1000
ym map "digits" to array using y as mapping function
|A all elements are truthy?
```
[Here's an example](https://staxlang.xyz/#c=%7Bc%7CqJ%3D%7DYd%0AVk%7CEym%7CA&i=25121%0A4101&a=1&m=2) using the perfect square function.
[Answer]
# [Clean](https://clean.cs.ru.nl), 54 bytes
```
import StdEnv
$n=if(n<1)True($(n/1000))&&f(n rem 1000)
```
[Try it online!](https://tio.run/##HcyxDoMgFEbh3af4B2JgMMW9OLVDk252dCEIDQlcDWKTvnxvjeP5huOSt8R5mffkkW0kjnldSsVY5zt9GkEmBknXXr3K7qWQdOm11kq17cEoPuNsDjCYCN0AwgDdjNUeFwOh@edCsu@Nu8eTb1@yObrtDw "Clean – Try It Online")
Defines the function `$ :: Int -> Bool`, expecting a function `f :: Int -> Bool` to be defined elsewhere.
[Answer]
# [Java (OpenJDK 9)](http://openjdk.java.net/projects/jdk9/), 94 bytes
```
f->n->{int r=0,l=n.length();for(;l>0;l-=3)r+=f.test(n.substring(l<4?0:l-3,l))?0:1;return r<1;}
```
[Try it online!](https://tio.run/##tZNRT9swEMff@RQ3JCSbNZ6dhEFJE96Q9oBA4nHag2md4uJeMvtSFaF@9uKm7WBiD@sDliyf/r772b7zzfRCJ01rcDZ5Gq7tvG08wSyKoiPrRN3hmGyD4rQ4GjsdAtxoi/ByBNB2D86OIZCmuCwaO4F53GP35C1Of/4C7aeB965xXO9AoztvJnasyYy2jtXgg1LBEkpY10mFSfVikcCXcuBKFM7glB4ZL@rGs8JVsnBJmXH/tawFmUAMRegeQo9hbpRfyUuXZAPHebRU4Q11HsGPVLFaF/3F7p8DmbloOhJtjCKHbCl027pnVjOEpAKEsgTkfHvAsUozqYbpMef/D/jyHpAfFltBLuW7YBnHAQAWVX6j6VGE3z7mh8PpP7S/XpieqVR97hG5kuqgLJyAkjEVPXGulwy/KXmi5GCzbgz@Vh@ZZkOVys/Cp1l@9v38YnhgEd9KuL/ZKs5d83zoAKjZD6Q/MrT7Ptr94LDBtltgdDRT48VCu87c1izs8as@Yv0K "Java (OpenJDK 9) – Try It Online")
[Answer]
# [Common Lisp](http://www.clisp.org/), ~~73~~ 72 bytes
```
(defun g(x f)(and(funcall f(mod x 1000))(or(< x 1e3)(g(floor x 1e3)f))))
```
[Try it online!](https://tio.run/##rZHRboMwDEXf9xV@dN5sk25F2vYvWSEIKSSUMom/Z4YirQUmTVX9dp1znZv4FOpLO45YlP47QoUDeIMuFqjy5EIAj00qYAAmImMwdfg@qTIzWKEPKXWL9EZrxLarYw9YAQBLRpwLYHDNV@EAowH8gAhxQl9u0bnsCo2pv@FXBisaiO4Nn8raKebedNiB/0L5f6gcWHj7PCyHVpn6cu56zQ5i9q6xTI95JSexbNfeeU9RDduoTJLlLJsPWCxMqho3XPWy1Gt7PvptzJPvZuuO7eH17Zg/a/b4Aw "Common Lisp – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
₄вεI.V}P
```
[Try it online!](https://tio.run/##MzBNTDJM/f//UVPLhU3ntnrqhdUG/P9vZGlgZGJownW4AwA "05AB1E – Try It Online")
**Explanation**
```
₄в # convert first input to base-1000
ε } # apply to each element
I.V # execute second input as code
P # product of the resulting list
```
Takes the number as the first line of input and the function as the second.
Outputs **1** for truthy and **0** for falsy.
[Answer]
# Excel VBA, 79 bytes
An anonymous VBE immediate window function that takes input, `n` as type integer from range `[A1]`, and the name of a publically defined VBA function from range `[B1]`.
```
t=1:n=[A1]:While n:t=t*-Application.Run(""&[B1],n Mod 1E3):n=Int(n/1E3):Wend:?t
```
### Usage example
In a public module, the input function, in this case `f()` is defined.
```
Public Function f(ByVal n As Integer) As Boolean
Let f = (n Mod 2 = 0)
End Function
```
The input variables are set.
```
[A1]=2902414 '' Input Integer
[B1]="f" '' input function
```
The immediate window function is then called.
```
t=1:n=[A1]:While n:t=t*-Application.Run(""&[B1],n Mod 1E3):n=Int(n/1E3):Wend:?t
1 '' Function output (truthy)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 37 bytes
```
g=->f,n{f[n%x=1000]&&(n<x||g[f,n/x])}
```
[Try it online!](https://tio.run/##hZFRb4IwFIXf/RVnJBgwFW9r2cYy2A8hPDApzoRVQyFhEX87q5qZGXG7D03a3u@c0966ff8ahnU8T0qm92Wq3S7mRJRNp55@7fp@ndqLRZf5hyGdAOk80XtoxLFdDgzjxcWSeCQYmrpVyNgv8OFP8FTSgmVeGXUFJpBE90kpbGq6BT2N2QwUhH5QVtttfdyJq/gi5ILfRv0fhOTEx6K658Y7aUVEQnI59jkuONmHenrByQ@KzXrTmOAz705CnMQy4oLGHe@DdhgyfHx6jn4cJ1mg8tUHii36kkEzqG6nVo0qeitZK9NWDWIcJw@d2aNd2xg4blRgnsANDTzX@I41TS177mcXLr6o4Q3OLjfGwQucMt9UTjZRuhi@AQ "Ruby – Try It Online")
A recursive lambda, taking function and integer and returning boolean.
## 36 bytes (only positive n)
```
g=->f,n{n>0?f[n%k=1000]&&g[f,n/k]:1}
```
This version returns `1` for truthy, `false` for falsey. Unfortunately it can fail when `n = 0`
[Try it online!](https://tio.run/##hZHRboJAEEXf/YpbEgyYFWfWpS0m4IcQHqiANdLVuJjYqN9OV41NjWjnYZOZzJl7Z2ez/fhu23k8TCqh9zqhaZVqdxkzEWX9/jy15dEym/CxTXtAOkz0HhpxbJ@jQHewHBNHUoBPWSb@gC9PwXMoC1Z5bcobMIEiekwqaQ3TPehpDAagIPSDql6tNqdM3tiXIUu@t/o/CMXEXVbdS@MDtzIiqVh1fY4LJruop0dMflAs5ovGBF/57jyISY4jltSt@Bi0x1Dh69t7dFXsZUGZzz5RrHCoBLRAuVuXs6YsDnbkpjTbukGM0@mhM1tabxsDx40KDBO4oYHnGt@xoqllL/0C3hWMf8dhCmedG@NgAqfKF7XjZ71SF@0P "Ruby – Try It Online")
[Answer]
# [Appleseed](https://github.com/dloscutoff/appleseed), 51 bytes
```
(lambda(n f)(all(map f(or(to-base 1000 n)(q(0))))))
```
Anonymous lambda function that takes a number and a function and returns a boolean value.
[Try it online!](https://tio.run/##dY9BDoMgEEX3nOJ3NyyaoEnXLj3HWIfGBBEBz28RNemmbCbhv/k8OAQnSWTcaRSLfifH8zAyeVhN7BzNHGBpiZSX58BJ0Bhj4DWtZHQ9u1aqbqd14yidwlWC0kKfTVJCQRVAkwVJoVwHOmnUXJfCkiPHTY5ZwSKW/nD3bYfywuTfV3pmll2SQ@zWyhzz48dKqkuIk88PUI/21bTNbV9/9AU "Appleseed – Try It Online")
```
(lambda (n f) ; Function with parameters n and f
(all ; Return true if all elements of this list are truthy:
(map f ; Map the function f to each element of
(or ; This list if it is nonempty:
(to-base 1000 n) ; Convert n to a list of "digits" in base 1000
(q (0)) ; Or if that list is empty (when n=0), then use the list (0) instead
))))
```
[Answer]
# [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 15 bytes
```
L,1000$bbbUª{f}
```
[Try it online!](https://tio.run/##S0xJKSj476KTpuOgY6BnGpdpFOdo@99Hx9DAwEAlKSkp9NCq6rTa/yo5iblJKYkKhnb2XP7//xuZGhoZAgA "Add++ – Try It Online")
Requires a function `f` to be declared in the TIO header.
## How it works
```
D,f,@,0.5^i2^A= ; Declares a function 'f' to check if a perfect square
; E.g. 25 -> 1; 26 -> 0
L, ; Declare the main lambda function
; Example argument: [25121]
1000$bb ; Convert to base 1000 STACK = [[25 121]]
bUª{f} ; Is 'f' true for all? STACK = [1]
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
`ΛmrC_3
```
[Try it online!](https://tio.run/##ASMA3P9odXNr/@KCgSIyNTEyMSLCo86YxLDilqH/YM6bbXJDXzP//w "Husk – Try It Online") Takes **N** as a string and *f* as a function object. Given a number, *f* can return any truthy or falsy value.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Had to sacrifice 3 bytes and take input as a string in order to handle the `n=>n>0` test case when `n=0`. I could get them back if it was permitted to pass the groupings to the function as strings and convert them to integers within the function, when necessary
```
ò3n)mn eV
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=Clh7WD4wfQ&code=8jNuKW1uIGVW&input=IjAi)
The function, as allowed by consensus, is preassigned to variable `V` on the second line of the header - the empty first line is essential.
Here are all the test case functions rewritten for Japt.
```
n -> n == n X{X==X}
n -> n != n X{X!=X}
n -> n > 400 X{X>400}
n -> n > 0 X{X>0}
n -> n -> 0 X{X{0}}
n -> sqrt(n) ** 2 == n X{Xq v1}
n -> mod(n, 2) == 0 X{X%2==0}
n -> n % 10 > max(digits(n / 10)) X{X%10>Xz10 ì rw}
```
]
|
[Question]
[
### Introduction
Let's observe the following array:
```
[1, 1, 1, 2, 2, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1]
```
A **group** consists of the same digits next to each other. In the above array, there are 5 different groups:
```
[1, 1, 1, 2, 2, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1]
1, 1, 1
2, 2
1, 1, 1, 1
2, 2, 2
1, 1, 1
```
The smallest group of these is `[2, 2]`, so we output `[2, 2]`.
Let's take another example:
```
[3, 3, 3, 4, 4, 4, 4, 5, 5, 4, 4, 3, 3, 4, 4]
3, 3, 3
4, 4, 4, 4
5, 5
4, 4
3, 3
4, 4
```
You can see that there are multiple groups with the same length. The smallest groups are:
```
[3, 3], [4, 4], [4, 4] and [5, 5].
```
So we just output `[3, 3], [4, 4], [4, 4], [5, 5]` in any reasonable format. You may output these in any order.
### The Task
Given an array consisting of only positive integers, output the smallest group(s) from the array. You can assume that the array will contain at least 1 integer.
### Test cases
```
Input: [1, 1, 2, 2, 3, 3, 4]
Output: [4]
Input: [1]
Output: [1]
Input: [1, 1, 10, 10, 10, 100, 100]
Output: [1, 1], [100, 100]
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the least amount of bytes wins!
[Answer]
# Mathematica, 24 bytes
```
MinimalBy[Length]@*Split
```
This is a composition of two functions that can be applied to a list. `Split` takes all groups of consecutive numbers, and `MinimalBy[Length]` selects those with minimal length.
[Answer]
# Pyth, ~~14~~ ~~12~~ 11
```
mM_MmhbrQ8
```
[Test Suite](https://pyth.herokuapp.com/?code=mM_M.mhbrQ8&test_suite=1&test_suite_input=%5B1%2C+1%2C+1%2C+2%2C+2%2C+1%2C+1%2C+1%2C+1%2C+2%2C+2%2C+2%2C+1%2C+1%2C+1%5D%0A%5B3%2C+3%2C+3%2C+4%2C+4%2C+4%2C+4%2C+5%2C+5%2C+4%2C+4%2C+3%2C+3%2C+4%2C+4%5D%0A%5B1%2C+1%2C+2%2C+2%2C+3%2C+3%2C+4%5D%0A%5B1%5D%0A%5B1%2C+1%2C+10%2C+10%2C+10%2C+100%2C+100%5D&debug=0)
2 bytes thanks to Jakube! And 1 byte thanks to isaacg!
Unfortunately, run length decoding doesn't quite do what we want it to do, but it will work with a minor workaround, but that makes it slightly longer than the manual implementation:
```
mr]d9.mhbrQ8
```
Credit to Jakube for finding this out.
[Answer]
## Haskell, 38 bytes
```
import Data.Lists
argmins length.group
```
Usage example: `argmins length.group $ [3,3,3,4,4,4,4,5,5,4,4,3,3,4,4]` -> `[[4,4],[3,3],[4,4],[5,5]]`.
Build groups of equal elements and find those with minimal length.
[Answer]
## Python 2, 120 bytes
```
import re
r=[x.group().split()for x in re.finditer(r'(\d+ )\1*',input())]
print[x for x in r if len(x)==min(map(len,r))]
```
Takes input as a string of space-separated integers with a trailing space, and outputs a list of lists of strings. The strategy is to find groups using the regex `(\d+ )\1*` (which matches one or more space-separated integers, with a trailing space), then split them on spaces into lists of integers, and print those groups whose length is equal to the minimum group length.
[Try it online](http://ideone.com/fork/vIQf9G)
[Answer]
# Python 2.x, 303 bytes
```
x=input()
r=[q[2]for q in filter(lambda l:(len(l[2])>0)&((l[0]<1)or(x[l[0]-1]!=x[l[0]]))&((l[1]>len(x)-1)or(x[l[1]]!=x[l[1]-1]))&(len(filter(lambda k:k==l[2][0],l[2]))==len(l[2])),[(a,b,x[a:b])for a in range(0,len(x))for b in range(0,len(x)+1)])]
print filter(lambda k:len(k)==min([len(s)for s in r]),r)
```
Ugliest. Code. Ever.
Input: An array in the format `r'\[(\d,)*(\d,?)?\]'`
In other words, a python array of numbers
Output: An array of arrays (the smallest groups), in the order that they appear in the input array
Additional Coincidental Features (Features that I did not intend to make):
* The input can be an empty array; the output will be an empty array.
* By changing `min` to `max`, it will return an array of the largest groups.
* If you just do `print r`, it will print all of the groups in order.
[Answer]
# Retina, ~~91~~ ~~85~~ ~~80~~ ~~79~~ ~~77~~ ~~76~~ ~~75~~ 74 bytes
```
M!`\b(\d+)(,\1\b)*
(,()|.)+
$#2:$&
O#`.+
s`^(.*\b(.+:).*)¶(?!\2).+
$1
.+:
<empty-line>
```
[Try it online!](http://retina.tryitonline.net/#code=TSFgXGIoXGQrKSgsXDFcYikqCigsKCl8LikrCiQjMjokJgpPI2AuKwpzYF4oLipcYiguKzopLiopwrYoPyFcMikuKwokMQouKzoK&input=MSwxLDEwLDEwLDEwLDEwMCwxMDA)
## Explanation
The input is `1,1,10,10,10,100,100`.
The first line matches groups with same terms:
```
M!`\b(\d+)(,\1\b)*
```
The input becomes:
```
1,1
10,10,10
100,100
```
The following two lines prepend the number of commas to the line:
```
(,()|.)+
$#2:$&
```
The input becomes:
```
1:1,1
2:10,10,10
1:100,100
```
Then they are sorted by this line, which looks for the first number as index:
```
O#`.+
```
The input becomes:
```
1:1,1
1:100,100
2:10,10,10
```
Then these two lines find the place where the length is different, and remove everything onwards:
```
s`^(.*\b(.+:).*)¶(?!\2).+
$1
```
The input becomes:
```
1:1,1
1:100,100
```
Then the numbers are removed by these two lines:
```
.+:
<empty-line>
```
Where the input becomes:
```
1,1
100,100
```
[Answer]
## C#, 204 bytes
```
void f(string o){var r=Regex.Matches(o,@"([0-9])\1{0,}").Cast<Match>().OrderBy(x=>x.Groups[0].Value.Length);foreach(var s in r){foreach(var z in r)if(s.Length>z.Length)return;Console.WriteLine(s.Value);}}
```
I don't know if using a string is fair considering all the golfing esolangs get their input in the same way but he requested array input.
[](https://i.stack.imgur.com/RPbBC.png)
ungolfed:
```
public static void f(string inp)
{
var r = Regex.Matches(inp, @"([0-9])\1{0,}").Cast<Match>().OrderBy(x => x.Groups[0].Value.Length);
foreach (Match s in r)
{
foreach (Match z in r)
if (s.Length > z.Length)
return;
Console.WriteLine(s.Value);
}
}
```
I need a way to get the smallest matches for the match array, most of my bytes are wasted there, help appreciated. I'm trying to get into LINQ and lambda stuff.
[Answer]
# [R](https://www.r-project.org/), ~~70~~ 65 bytes
*Edit: -5 bytes thanks to Giuseppe*
```
function(x)(y=split(x,diffinv(!!diff(x))))[min(l<-lengths(y))==l]
```
[Try it online!](https://tio.run/##ZcxNDoIwEAXgPafgZzOT1AWoO3sSMIZUik2GgdBi4PQV6UKCk2/xMi95o7ddTdRY92jHfhqs9Hpi5UzPMCMs0g5kHMziabQ2/IYk@aa1W6/sDAPdTtRw614WFkQp6X6cBAW5iINik@8UhydipGoHaZZlFVecYvQ/dxZxcNm5bkL@tYj@Aw "R – Try It Online")
This feels rather clunky, so I won't be surprised if there's a much slicker [R](https://www.r-project.org/) way to do this... *Edit: [there is](https://codegolf.stackexchange.com/a/216382/95126)...*
```
function(x) # x is vector of values;
(y= # define y as
split(x, # groups of values of x that share the same
cumsum( # cumulative sum of
x!=c(0,x)))) # 1 if different to the next element;
[ # now, get element(s) of y
(l=lengths(y)) # whose length(s)
==min(l[l>0])] # equal the smallest non-zero lengths of y
```
[Answer]
# MATL, 15 bytes
```
Y'tX<tb=bw)wTX"
```
[Try it online](http://matl.tryitonline.net/#code=WSd0WDx0Yj1idyl3VFgi&input=WzEsIDEsIDEwLCAxMCwgMTAsIDEwMCwgMTAwXQ)
Input is a vector, like `[1 2 3 4]`, and output is a matrix where each column is one of the smallest groups, e.g.:
```
1 100
1 100
```
for the third test case.
Explanation:
```
Y' %// Run length encoding, gives 2 vectors of group-lengths and values
t %// Duplicate group lengths
X< %// Minimum group length
tb %// Duplicate and get vector of group lengths to the top
= %// Find which group lengths are equal to the minimum
bw) %// And get the values of those groups
wTX" %// Repeats the matrix of minimum-length-group values by the minimum group length
```
[Answer]
# Jelly, ~~22~~ ~~17~~ 16 bytes
```
I0;œṗ¹L=¥ÐfL€Ṃ$$
```
[Try it online!](http://jelly.tryitonline.net/#code=STA7xZPhuZfCuUw9wqXDkGZM4oKs4bmCJCQ&input=&args=WzEsIDEsIDEsIDIsIDIsIDEsIDEsIDEsIDEsIDIsIDIsIDIsIDEsIDEsIDFd&debug=on)
```
I0;œṗ¹L=¥ÐfL€Ṃ$$ Main link. List: z = [a,b,c,...]
I Compute [b-a, c-b, d-c, ...]
0; Concatenate 0 in front: [0, b-a, c-b, d-c, ...]
œṗ Split z where the corresponding item in the above array is not zero.
L=¥Ðf Filter sublists whose length equal:
L€Ṃ$ the minimum length throughout the list.
¹ $ (grammar stuffs)
```
[Answer]
# JavaScript (ES6), 106
```
a=>(a.map((v,i)=>v==a[i-1]?g.push(v):h.push(g=[v]),h=[]),h.filter(x=>!x[Math.min(...h.map(x=>x.length))]))
```
**Test**
```
f=a=>(a.map((v,i)=>v==a[i-1]?g.push(v):h.push(g=[v]),h=[]),h.filter(x=>!x[Math.min(...h.map(x=>x.length))]))
console.log=x=>O.textContent+=x+'\n'
;[[1, 1, 1, 2, 2, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1]
, [3, 3, 3, 4, 4, 4, 4, 5, 5, 4, 4, 3, 3, 4, 4]
, [1, 1, 2, 2, 3, 3, 4]
, [1]
, [1, 1, 10, 10, 10, 100, 100]]
.forEach(t=>console.log(t+' -> '+f(t).join` `))
```
```
<pre id=O></pre>
```
[Answer]
## JavaScript (ES6), 113 bytes
```
a=>a.map(n=>n==c[0]?c.push(n):b.push(c=[n]),c=b=[])&&b.sort((a,b)=>a[l]-b[l],l='length').filter(e=>e[l]==b[0][l])
```
[Answer]
## APL, 25 chars
```
{z/⍨(⊢=⌊/)≢¨z←(1,2≠/⍵)⊂⍵}
```
In English:
* put in z the argument split where a number is different than the one preceding;
* compute the length of each subarray
* compare the minimum with each of the lengths producing a boolean...
* ... that is used to reduce z
[Answer]
# [J](http://jsoftware.com), 31 bytes
```
[:(#~[:(=<./)#@>)]<;.1~1,2~:/\]
```
Input is an array of values. Output is an array of boxed arrays.
## Usage
```
f =: [:(#~[:(=<./)#@>)]<;.1~1,2~:/\]
f 1 1 2 2 3 3 4
┌─┐
│4│
└─┘
f 3 3 3 4 4 4 4 5 5 4 4 3 3 4 4
┌───┬───┬───┬───┐
│5 5│4 4│3 3│4 4│
└───┴───┴───┴───┘
```
## Explanation
```
[:(#~[:(=<./)#@>)]<;.1~1,2~:/\] Input: s
] Identity function, get s
2 The constant 2
\ Operate on each overlapping sublist of size 2
~:/ Check if each pair is unequal, 1 if true else 0
1, Prepend a 1 to that list
] Identity function, get s
<;.1~ Using the list above, chop s at each true index
[:( ) Operate on the sublists
#@> Get the length of each sublist
[:( ) Operate on the length of each sublist
<./ Get the minimum length
= Mark each index as 1 if equal to the min length else 0
#~ Copy only the sublists with min length and return
```
[Answer]
## Clojure, 65 bytes
```
#(let[G(group-by count(partition-by + %))](G(apply min(keys G))))
```
Uses `+` as `identity` function as `(+ 5)` is 5 :) The rest should be obvious, `G` is a hash-map used as a function and given a key it returns the corresponding value.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 6 bytes
```
ḅlᵒlᵍh
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w/@GO1pyHWycBcW/G///RCtGGOgoQZARGhkjICE0wVifaWEcBgkyQkCkYQdgIWaBqZGOgEiBRuIyhATKGELEKsQA "Brachylog – Try It Online")
Input through the input variable and output through the output variable.
```
ḅ The list of runs of consecutive equal elements of
the input
lᵒ sorted by length
lᵍ and grouped by length
has the output variable
h as its first element.
```
Although, unlike `ḅ`, `ᵍ` groups non-consecutive equal elements, the `lᵒ` is still necessary to find the group with the shortest lengths, and it works because the order of groups in the output from `ᵍ` is determined by the position of the first element of each group, so that `ᵍhᵐ` could function as sort of a *deduplicate by* pseudo-metapredicate.
[Answer]
# [Perl 5](https://www.perl.org/) `-MList::Util=pairkeys,min -a`, 69 bytes
```
map$r{y/ //}.="[ $_]",pairkeys"@F "=~/((\d+ )\2*)/g;say$r{min keys%r}
```
[Try it online!](https://tio.run/##K0gtyjH9/z83sUClqLpSX0Ffv1bPVilaQSU@VkmnIDGzKDu1sljJwU1BybZOX0MjJkVbQTPGSEtTP926OLESqCc3M08BpEa1qPb/f0MFCDQCQyjrX35BSWZ@XvF/XV9TPQNDAyDtk1lcYmUVWpKZYwuzQwdo0H/dRAA "Perl 5 – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 4 bytes
```
←kLg
```
[Try it online!](https://tio.run/##yygtzv7//1HbhGyf9P///0cb6gChARyBcSwA "Husk – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
ŒgLÐṂ
```
[Try it online!](https://tio.run/##y0rNyan8///opHSfwxMe7mz6f7j9//9oQx0FCDICI0MkZIQmGAsA "Jelly – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
γé¬gù
```
[Try it online!](https://tio.run/##yy9OTMpM/f//3ObDKw@tST@88///aGMdBQgyQUKmYARhI2RjAQ "05AB1E – Try It Online")
**Commented**:
```
γ # split into chunks of equal adjacent elements
é # sort the chunks by length
¬ # get the shortest (first) chunk without popping the list
g # take the length of that chunk
ù # keep all chunks with this length
```
[Try it with step-by-step output!](https://tio.run/##XY7BasMwEETv/YohpxR6a0IgUPohpQfF2Vgby5KSXRP6SYXeeuq1ueeXHNmya1MxoIWZtztBzI6pbZHfguvouGAF@9joFov15vj68nD7HnxJdmdqQGEbXwnCAXRqjIPZH01BXkGO6vTLH43r50CHs0ItjezuA458qXaK4verj5aUk2ITQ6JYHvgs@phRXFhtaBQxxMi@7KOORWeLUHZ71FSU3f5QV1et0bxmnsb1J8Urogjj3Niwu5MAln9F2/bt@QlZq5nWvfI8ue93)
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-g`](https://codegolf.meta.stackexchange.com/a/14339/), 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Outputs a 2D-array.
```
òÎüÊ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWc&code=8s78yg&input=WzEsIDEsIDEsIDIsIDIsIDEsIDEsIDEsIDEsIDIsIDIsIDIsIDEsIDEsIDFdCi1R)
```
òÎüÊ :Implicit input of array
ò :Partition between elements where
Î : The sign of their difference is truthy (not 0)
ü :Group and sort by
Ê : Length
:Implicit output of first element
```
[Answer]
# [R](https://www.r-project.org/), 56 bytes
```
function(x,r=rle(x),l=min(r$l))lapply(r$v[r$l==l],rep,l)
```
[Try it online!](https://tio.run/##K/qfpmCjq/A/rTQvuSQzP0@jQqfItignVaNCUyfHNjczT6NIJUdTMyexoCCnEsguiwbybW1zYnWKUgt0cjT/p2kkaxjqKECQERgZIiEjNEFNTa7kxBINJWVl5Zi8mDwlTS6QAcY6ChBkgoRMwQjCRshqav4HAA "R – Try It Online")
-2 bytes thanks to Dominic van Essen. Uses `rle` and `rep` to collapse and reconstruct the array.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 24 bytes
```
{{x=&/x:#'x}#(&~=':x)_x}
```
[Try it online!](https://ngn.bitbucket.io/k/#eJxLs6qurrBV06+wUlavqFXWUKuzVbeq0IyvqOXiSlPXMFQwVDACQmMgNLHWMbQGCRgawBEYQwTB6gwVEGwoz9oYohsKTYEQREPFNAEu5BlD)
* `(&~=':x)_x` split the input on indices where the values change
* `{x=&/x:#'x}#` filter down to items of the minimum length
[Answer]
# [Factor](https://factorcode.org/) + `grouping.extras`, 36 bytes
```
[ [ ] group-by values all-shortest ]
```
[Try it online!](https://tio.run/##PY0xDsIwDEX3nsIXaESBCRY2xMKCmKoOITIlIkqK7SAqlLOHQAE9/8FPX/pnbSRQPh52@@0KNHMwDD2FOFjfK3wIaYYrkkcHjLeI3iD//EAoMg5kvcC6qp7QFOaFRWEJ6WPS1zez/01JuYUWummtPo1w1y4ig3au5ksgQRbospDdlJ5SqnTfT34B "Factor – Try It Online")
* `[ ] group-by values` Split a sequence into groups of contiguous equal elements.
* `all-shortest` Take all the shortest groups.
`[ stable-slices all-shortest ]` would work except it doesn't have the right behavior for 1-element inputs.
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 2 bytes
```
ĉş
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FkuOdB6dv6Q4KbkYKrDgZla0oQ4IGgGhoQ6CDeXFckUb64CgCRSaAiGIhooB5WE6wCIgPlTM0ACOwDgWYiUA)
```
ĉ Split the input into chunks of equal elements
ş Find the shortest chunk
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 97 bytes
```
x=>eval(`[[${x}]]`.replace(/\b(\d+),(?!\1\b)/g,'$1],[')).filter((t,_,x)=>!x.some(y=>t[y.length]))
```
[Try it online!](https://tio.run/##fc7PCoJAEAbwe0@hEDhL24ZWR@1BVtFVp83YXHE3UaJntz8eEg/B7zDMB9/MVXTCFG3V2G2tSxzNTSiFxqay1ffGhGMfRtgJBRnn60f/TJKMtdgoUSDs4hzickMonNzYj3Oyk9Rb@wnlHiHsXCmLLYClKe1JGLk9M/qGMISR5QNTWEt7SQgZC10brZApLWFxHrhPnUnw5c8Ei@W7a/W3a0@dyWHm@DXNv/Tz1ws "JavaScript (Node.js) – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell) for Windows, 88 bytes
```
$h=@{}
$args|%{$i+=$p-ne$_;$h.+$i+=,$p=$_}
($g=@($h|% v*|sort c*))|? c*t -eq $g[0].count
```
[Try it online!](https://tio.run/##lVFBboMwELz7FSu0FDsxUShwaYXKH3qMIlRRF1IhoMZpIwFvpwuEhhxrrb3eGXvWGtfVj9JNropiwA@IoB0wj@K2Z/ims6azWzxtI6zdUmHyjPluO9YS6wiTnnHMophj3tnwvemaShtIN0J0L5QMuOoLMDvsj7u0Opdm6BljMWdMcoi5JyR4IK4F7SU8TuFPERAd3NPefj3nhU6NtDdnAkdsueb/ia0inGLe39jpvi/9KQcyuMuhDIVgTEAHNrQMaJA5WgKqS61So97JN0xmQqvmXBgCHsjOmI6xNf5qNFH8Wk2OjRYn7md1Kh0JTk@ldcDkaPViBsGZBcZeF@q1SCy9/yNiIb89hL5nLSqeVo@0WD/8Ag "PowerShell – Try It Online")
The script uses the Powershell alias `sort` that should be `sort-object` with Linux.
Less golfed:
```
$hashTable=@{}
$args|foreach-object{
$i += ($prev -ne $_)
$prev = $_
$hashTable.+$i += ,$prev
}
$groups=@($hashTable|foreach-object Values|sort-object Count)
$groups|where-object count -eq $groups[0].count
```
[Answer]
# [Arturo](https://arturo-lang.io), 46 bytes
```
$=>[c:chunk&=>[&]select c=>[=size&size min c]]
```
[Try it](http://arturo-lang.io/playground?gNzxBg)
]
|
[Question]
[
## Background
J has trains similar to [APL's](https://codegolf.stackexchange.com/q/150380/78410). Given a sequence of verbs (functions), three rightmost verbs are grouped to form a derived verb (a *fork*) recursively, until one or two verbs remain. If the sequence has odd length, the entire train is a chain of forks. Otherwise, two verbs remain at the end, forming a *hook*.
```
(F G H J K) x 5-train called monadically
-> (F G (H J K)) x
-> (F x) G ((H x) J (K x)) Function arities: 1, 2, 1, 2, 1
x (F G H J K) y 5-train called dyadically
-> x (F G (H J K)) y
-> (x F y) G ((x H y) J (x K y)) Function arities: 2, 2, 2, 2, 2
(F G H J K L) x 6-train called monadically
-> (F (G H (J K L))) x
-> x F ((G x) H ((J x) K (L x))) Function arities: 2, 1, 2, 1, 2, 1
x (F G H J K L) y 6-train called dyadically
-> x (F (G H (J K L))) y
-> x F ((G y) H ((J y) K (L y))) Function arities: 2, 1, 2, 1, 2, 1
```
You don't need to fully understand J trains to solve this challenge. The pattern is pretty simple:
* If the train length is even, the pattern is `[2, 1, 2, 1, ..., 2, 1]` regardless of the train's arity.
* Otherwise (length is odd), if the train is called monadically, the pattern is `[1, 2, 1, 2, ..., 2, 1]`; if called dyadically, the pattern is all 2's.
## Challenge
Given a train's length and arity (monadic is 1, dyadic is 2), output the arities of each function in the train.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
```
length, arity -> answer
1, 1 -> [1]
1, 2 -> [2]
2, 1 -> [2, 1]
2, 2 -> [2, 1]
3, 1 -> [1, 2, 1]
3, 2 -> [2, 2, 2]
4, 1 -> [2, 1, 2, 1]
4, 2 -> [2, 1, 2, 1]
9, 1 -> [1, 2, 1, 2, 1, 2, 1, 2, 1]
9, 2 -> [2, 2, 2, 2, 2, 2, 2, 2, 2]
10, 1 -> [2, 1, 2, 1, 2, 1, 2, 1, 2, 1]
10, 2 -> [2, 1, 2, 1, 2, 1, 2, 1, 2, 1]
```
[Answer]
# [Python 2](https://docs.python.org/2/), 28 bytes
```
lambda l,a:(l*[2,l%a+1])[l:]
```
[Try it online!](https://tio.run/##jZDRCoIwFIbv9xTnJtxqRVveJNiL2IhFisLUYTPp6W0ZS2wKjcO5@M7/n/8w/TR5XfE@i8@9kuX1JkFRGWG1TjhVK7lhgiQqEn2XFyoFFiHAioIkFOrWaIihlBqnD2lhI7tLUenWYLK7a1UYHMD2BAEhCHRTVAayjxfieHD3jMLw2NCtNmECOci/kAvEPaUlbOT8hx/8zRSmo4nlXQKFsynOGM5muelxKdHvo9i7wS/7IXu6eNXccqfn/@lf "Python 2 – Try It Online")
### [Python 2](https://docs.python.org/2/), 27 bytes
It saves one byte to output as a string.
```
lambda l,a:(l*`21+l%a`)[l:]
```
[Try it online!](https://tio.run/##jZBBDoIwEEX3PcVsDK1WYisbSfAiSKRGjTUFGigST49FUo0WE5vJLN78/2dSfTeXquT9Odn1ShSHowBFRYzVPOdsoWYiJ6mKs767SHUCFiPAioIgFKrWaEigEBqfbsLCWnR7WerWYBI2WkmDA1huISAEga5laeA8eiFJIAjCayVLPNgbU49xhPSMwvOxZ7f2lGXIQf6CPEPcU1rC3px/8bWfTOFz9GEZKkPR5BZnjCZ3uenm10a/v8XeDX7ZD1nRn1dNhTs9/0//AA "Python 2 – Try It Online")
[Answer]
# [HBL](https://github.com/dloscutoff/hbl) 0.1, 10 bytes
```
<(0.(*(1(+(%.,))2?).
```
[Try it at HBL Online!](https://dloscutoff.github.io/hbl/?f=0&p=PCgwLigqKDEoKyglLiwpKTI/KS4_&a=Nwox)
HBL uses a [half-byte codepage](https://github.com/dloscutoff/hbl/blob/main/docs/codepage.md). Each character above represents one hex digit, two characters per byte. Here's a hexdump of the raw binary file:
```
00000000: 3c0a c5c1 c4c8 abdd 29da <.......).
```
### Explanation
If we reverse the desired output, we can see some patterns emerge:
```
3 1 (1 2 1)
3 2 (2 2 2)
4 1 (1 2 1 2)
4 2 (1 2 1 2)
5 1 (1 2 1 2 1)
5 2 (2 2 2 2 2)
```
* The output is some two-element list repeated a number of times and trimmed to a length equal to the first argument.
* The second element of that list is always 2.
* The first element of that list is 2 if the arguments are, respectively, an odd number and 2; otherwise, the first element is 1.
This leads to our initial solution, given here in Thimble, HBL's "ungolfed mode":
```
'(reverse ; Reverse of
(take arg1 ; The first (arg1) elements of
(repeat ; Repeat the following list...
(cons ; Construct a list from the values...
(cond ; If...
(mul ; Multiply
(odd? arg1) ; parity of arg1
(dec arg2)) ; by (arg2 - 1)
2 ; ... is nonzero, then 2
1) ; else 1
2 ; ... and 2
nil) ; prepended to the empty list
arg1))) ; ... (arg1) times
```
Translating this solution into HBL gives `<(0.(*(1(?(*(%.)(-,))21)2?).` (14 bytes). To get to our 10-byte solution, observe that there's a nice relationship between our two arguments and the number we want in our list:
```
arg1 % 2 | arg2 | num | arg1 % arg2
----------|------|-----|-------------
0 | 1 | 1 | 0
0 | 2 | 1 | 0
1 | 1 | 1 | 0
1 | 2 | 2 | 1
```
So instead of the conditional, all we need is `(inc (mod arg1 arg2))`.
```
'(reverse
(take arg1
(repeat
(cons
(inc
(mod arg1 arg2))
2
nil)
arg1)))
```
Replacing the builtins with their HBL equivalents and removing the opening and closing parentheses (implicit in HBL), this solution maps directly onto the HBL solution given above.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
%‘;2ṁḷU
```
[Try it online!](https://tio.run/##y0rNyan8/1/1UcMMa6OHOxsf7tge@t/y8HLD/wA "Jelly – Try It Online")
Thanks to Unrelated String for making this work! Port of dingledooper's answer.
```
%‘ṭ2ṁḷU # Dyadic link taking two arguments
ṁ # Mold...
;2 # 2 appended to...
% # The modulo of the two inputs
‘ # Plus 1
ṁ # To length...
ḷ # Left argument (length input)
U # Reversed
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
%21+sиJs.$
```
[Try it online!](https://tio.run/##yy9OTMpM/f9f1chQu/jCDq9iPZX//w25LAE "05AB1E – Try It Online")
[Answer]
# [Factor](https://factorcode.org/) + `sequences.repeating`, 50 bytes
```
[ dupd mod 1 + '[ 2 _ ] over 2 * cycle swap tail ]
```
[Try it online!](https://tio.run/##Tc89C8JADAbgvb/i3QSFYj@WKriKi4s4lSLHNdXSr/PuqpTS314PhZpkeXkSCCmEtJ2er5fT@bhDRbqlGoaePbWSjK9JkbBle4fSZO2gdNlaCGM6adAI@0Chh/8@9p43enA1InA9LTlccsg8ZB4xj5jHzGPmCfOEebDlh7ffyTSnyHuVo@lyN91glTq/IUP3Iu3iGnKQNcG8hYIVZY1sLn5/HhpHxgpZ@fMH "Factor – Try It Online")
This is a port of @dingledooper's excellent [Python 2 answer](https://codegolf.stackexchange.com/a/237060/97916).
There is a locals version that is the same length:
```
[| l a | 2 l a mod 1 + 2array l 2 * cycle l tail ]
```
[Try it online!](https://tio.run/##Tc@xCsIwEAbgvU/xzwpSYxcVXMXFRZzE4YhXLU3bmMSh1D57jAp6uSH/fUkIV5IOnYvHw26/XaFm17KB5/uDW81@5tgyhaq9wjoOobeuagPI@057kHPUezQUbjCdJuP/L7HOsiFDWgPmqcZfVr@shCvhC@EL4YXwQvhS@FL4PJcf55@TMZ6eMCA8U/vem@6Sbk2hPtMkUphA99pwyoEqg3MsvxNvGrLwgXQ9iy8 "Factor – Try It Online")
## Explanation:
It's a quotation (anonymous function) that takes the length and the arity (in that order) from the data stack as input and leaves a sequence on the data stack as output. Assuming `9 1` is on the data stack when this quotation is called...
| Snippet | Comment | Data stack (the bottom is the top) |
| --- | --- | --- |
| | |
```
9 <--- NOS (next on stack)1 <--- TOS (top of stack)
```
|
|
```
dupd
```
| Duplicate NOS |
```
991
```
|
|
```
mod
```
| NOS % TOS |
```
90
```
|
|
```
1
```
| Push 1 |
```
901
```
|
|
```
+
```
| NOS + TOS |
```
91
```
|
|
```
'[ 2 _ ]
```
| Slot TOS into the \_ |
```
9[ 2 1 ]
```
|
|
```
over
```
| Copy NOS to TOS |
```
9[ 2 1 ]9
```
|
|
```
2
```
| Push 2 |
```
9[ 2 1 ]92
```
|
|
```
*
```
| NOS \* TOS |
```
9[ 2 1 ]18
```
|
|
```
cycle
```
| Repeat NOS until length of TOS |
```
9[ 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 ]
```
|
|
```
swap
```
| Swap NOS and TOS |
```
[ 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 ]9
```
|
|
```
tail
```
| Take NOS from index at TOS |
```
[ 1 2 1 2 1 2 1 2 1 ]
```
|
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 32 bytes
```
\d+
$*
r`11
21
T`1`2`21,1.*
.+,
```
[Try it online!](https://tio.run/##FcohDoAwEERRP@dA0abpbGt6DyRiSUBgEA33XwYxeSP@vN77OSL2M2FZMZ2EEZvTzY2ZZUVJGRH6MI3ZpMkmm@yyyyGHZP3D@gE "Retina 0.8.2 – Try It Online") Link includes test cases. Takes input in the order arity, length. Explanation:
```
\d+
$*
```
Convert the length to unary, conveniently using `1`s.
```
r`11
21
```
Working right-to-left, change every other `1` to a `2`.
```
T`1`2`21,1.*
```
If the arity is two and the length is odd, change all the `1`s to `2`s.
```
.+,
```
Delete the arity.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
```
%21+S⁰*∷
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%2521%2BS%E2%81%B0*%E2%88%B7&inputs=2%0A3&header=&footer=)
*-1 thanks to emanresuA*
Haha 05ab1e porting goes brrrr. When v2.6.0pre2 drops later this week, this'll be 7 bytes:
```
%21+⁰ẋ∷
```
## Explained (old)
```
%21+S⁰*⁰ȯ # Full program, takes arity, length
% # Push length mod arity,
21+ # add 21 to that,
S # and cast to string. (This value will be called x)
⁰ # Push the length,
* # and repeat x that many times. (This value will be called y)
⁰ # Push the length again,
ȯ # and push y[length:]
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 25 bytes
```
->l,a{([2,l%a+1]*l)[l,l]}
```
[Try it online!](https://tio.run/##KypNqvyfZhvzX9cuRyexWiPaSCdHNVHbMFYrRzM6RycntvZ/tKGOkY6xjomOpY6hQaxebmJBdU1FDVeBQlp0hY5hLJRhFMtV@99QRwEMDMGkrp1CNFAeJmgEFwSqNcJQCRQxRIgboYkbY5qso4AqhaIFhGK5TLDaAtNogtUumKwlLhsxSYRiDDdgImCAGOjgdBU2w2HqjYhTDwA "Ruby – Try It Online")
Another port of @dingledooper's Python answer.
[Answer]
# [J](http://jsoftware.com/), 47 bytes
```
(".@,'~'''''}.~2&|)~'(',')',~,&'1&, :(,2&,)'&''
```
[Try it online!](https://tio.run/##jZBBCsIwEEX3PcWni0wC05CMbhoQBMGVK68gFnHjBTRXT22RNG1FDJMs3rz5A7mn2lKHXQCB4RDet7E4nE/HpGu7Z4o0nJeNop4mkiYmQxxZkVeMoFkUG1JEyVTXy@0BzcEbNAEeHXxmMjIpmDAmUZZQCugZM3kzyUNlv@DLke33lhStD1@/OaSd711XzmxX637EevevPX6fQ5V6 "J – Try It Online")
I would call this one a conscious un-golf, because ofc I could port dingledooper's Python answer to J for fewer bytes...
But it just didn't feel right for a J answer not to use J's train parsing code to compute the answer.
## the idea
First, we construct a verb `1&, :(,2&,)` that prepends 1 to its argument (say `a b c`) when called with 1 argument:
```
1 a b c
```
but plops 2 in the middle when called with 2 args:
```
a b c 2 a b c
```
Next we duplicate that verb `length` times to form a train, and then invoke the train on the empty list `''`. More precisely, we call:
```
train ''
```
if our arity is 1, and:
```
'' train ''
```
if our arity is 2.
With that setup, J's train execution will do the required computation for us.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
ḶU|%Ḃ‘
```
[Try it online!](https://tio.run/##y0rNyan8///hjm2hNaoPdzQ9apjx3/3h7i3Wj5rWPGqYY6Wg8KhhrrXS4eX6QAGQxLGuyP//o6MNdQxjdYCkEZA0ArONwGxjMNsYzDYBs03AbEsw2xLMNjSAaDYA8mIB "Jelly – Try It Online")
Like Dingledooper's answer, but a bit different.
```
ḶU range [L-1..0]
|% bitwise OR by L%A
(if L%A=0, this does nothing;
if L%A=1, it makes the whole range odd)
Ḃ‘ mod 2, add 1
```
[Answer]
# [R](https://www.r-project.org/), 38 bytes
Or **[R](https://www.r-project.org/)>=4.1, 31 bytes** by replacing the word `function` with `\`.
```
function(l,a)tail(rep(2:(l%%a+1),l),l)
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jRydRsyQxM0ejKLVAw8hKI0dVNVHbUFMnB4T@p2kY6iiAgaGmMpjWtVOINozlQkgYIUkYgSSMsOgAihkiyxlhkTPGZpOOAro0mlYQAkmb4LAVYYAJDrsRKixxuwCTRNaAxU2YCBxoBjp4XIndEpgeI2L1/AcA "R – Try It Online")
Based od [@dingledooper's idea](https://codegolf.stackexchange.com/a/237060/55372).
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 46 bytes (44 using puts)
```
i;f(l,a){for(i=l;i--;)printf(L"122"+i%2+l%a);}
```
[Try it online!](https://tio.run/##jZBBCoMwEEX3OcUgKAkqmKkbiXqC3qC4EKklkKpYXYlnt1FqrY2FhmEWb/78P6Twb0UxTVKUVHk5G8q6pTJRQvq@YE0rq66kZ4sjWq600VV2zsQ4aQz3XFZA2UCWFQ1UwoWKEx4I11Wag9SeaQiOAyqOGBR11cmqv4IgMKdxJpq@e1DLYi@Cn2Qk48Q9WB5fup/ChWdkhfiGmBE0lJrwjeMXP5nOHuxHu5W5MhIepqyL4WHWOo1@JZp9Exs3mKU/JPB@XnVkvurxP/0T "C (gcc) – Try It Online")
* Based on @dingledooper [answer](https://codegolf.stackexchange.com/a/237060/84844)
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 9 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
\%J+░*h½≥
```
Port of [*@dingledooper*'s Python answer](https://codegolf.stackexchange.com/a/237060/52210).
[Try it online.](https://tio.run/##y00syUjPz0n7/z9G1Uv70bSJWhmH9j7qXPr/v6GCIZehghGXEZA2AtLGQNoYSJsAaRMgbQmkLYG0oQFIoYGCEQA)
**Explanation:**
```
\ # Swap the two (implicit) input-integers
% # Modulo
J+ # Add 21
░ # Convert it to a string
* # Repeat it the first (implicit) input-integer amount of times
h # Push the length of this string (without popping)
½ # Halve it
≥ # Remove that many leading digits from the string
# (after which the entire stack is output implicitly as result)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes
```
Nθ↓I……⊕﹪θN³θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDyiW/PE9HwTmxuETDuTI5J9U5I79AIygxLz1VwzMvuSg1NzWvJDVFwzc/pTQnX6NQRwHZHE1NTR0FYyAuBLKs//@3VDD6r1uWAwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ Input the length as an integer
… Range from
θ Input length
﹪ Reduced modulo
N Arity as an integer
⊕ Incremented
³ Until 3 (exclusive)
… Cycled to length
θ Input length
I Cast to string
↓ Output right-to-left
```
Instead of `↓`, either `←` or `⮌` can be used for vertical output.
[Answer]
# [Rust](https://www.rust-lang.org/), 61 bytes
```
|l,a|->Vec<_>{(0..l).rev().map(move|x|(x|l%a)%2+1).collect()}
```
[Try it online!](https://tio.run/##TY5BCsIwFET3PcW3UMjHNBjdWa23cCuhpFD4TUuMpZDk7LFqFWcxi3nMMPZxd6k10KvOMASfwSLSDtpzCsRVKOurbk632rOdEITC6omh6NXI@mHSYQ5sDlQoLPZbiaIZiHTjGMZUvafawQJBZ0AKIeW6/wVqBYe//KXRdsaR2bDcRw4@QlmDP15izpdHvGWLI1a/Ssw@HtMT "Rust – Try It Online")
Port of @Lynn's Jelly answer.
Generates range `l-1 .. 0`, bitwise ORs each item with `l modulo a`, then modulos the result with `2` and adds `1`
`Range` in rust (`(start..stop)`) must be ascending, as it returns an empty iterator if `start >= stop`, so we have to `.rev()` the range to reverse it before mapping. Thankfully though the `stop` of a range is exclusive, so `(0..l)` generates range `0` to `l-1` inclusive.
]
|
[Question]
[
\$723 = 3 \times 241\$ is a semi-prime (the product of two primes) whose prime factors include all digits from \$1\$ to \$n\$, where \$n\$ is the total number of digits between them. Another way to look at this is that the (sorted) digits in the factorisation of \$723\$ are all consecutive. The first 10 such semi-primes and their factorisations are
```
[26, 62, 723, 862, 943, 1263, 2906, 3086, 7082, 7115]
[2×13, 2×31, 3×241, 2×431, 23×41, 3×421, 2×1453, 2×1543, 2×3541, 5×1423]
```
We will call the numbers that have this feature **all-inclusive semi-primes**
You may choose whether to:
* Take an integer \$n\$ and output the \$n\$th all-inclusive semi-prime (0 or 1 indexed)
* Take an integer \$n\$ and output the first \$n\$ all-inclusive semi-primes
* Output the sequence of all-inclusive semi-primes indefinitely
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins!
[This](https://tio.run/##AT4Awf9qZWxsef//w4ZmwrVERuG5okrGkcOXTD0yxooKMcOHI@G5hMOGZmrigqzigJ3Dl2rigb4sIMOYW2r//zEwMA) is a Jelly program which takes an integer \$n\$ and outputs the first \$n\$ all-inclusive semi-primes and their factorisations. Spoilers for any Jelly based solutions.
The first 100 all-inclusive semi-primes are
```
[26, 62, 723, 862, 943, 1263, 2906, 3086, 7082, 7115, 8306, 9026, 10715, 10793, 10826, 10862, 11705, 12443, 12773, 21155, 21443, 22313, 22403, 29126, 29306, 31286, 32906, 69302, 70922, 72902, 73082, 87302, 90722, 91226, 91262, 92306, 92702, 104903, 106973, 108326, 108722, 109262, 112862, 116213, 123086, 123155, 127082, 128306, 129026, 129743, 130826, 132155, 135683, 142283, 148373, 155123, 157373, 161393, 171305, 181205, 206315, 216305, 225833, 226223, 230543, 237023, 241103, 241223, 244913, 259433, 270934, 271294, 273094, 274913, 275903, 280403, 287134, 291274, 310715, 312694, 312874, 316205, 317105, 320615, 321155, 328714, 330874, 335003, 335086, 335243, 337111, 340313, 349306, 350926, 355741, 359881, 373701, 379371, 379641, 380581]
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~17~~ ~~16~~ ~~14~~ ~~12~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
∞ʒÒDS{āQиg<
```
Outputs the infinite sequence.
-2 bytes thanks to *@CommandMaster*, which also opened up the opportunity to golf 2 more bytes
-1 byte thanks to *@ovs*.
[Try it online.](https://tio.run/##yy9OTMpM/f//Uce8U5MOT3IJrj7SGHhhR7rN//8A)
**Explanation:**
```
∞ # Push an infinite list of positive integers: [1,2,3,...]
ʒ # Filter this list by:
Ò # Get a list of its prime factors (including duplicates)
D # Duplicate this list
S # Convert the list of integers to a flattened list of digits
{ # Sort these digits
ā # Push a list in the range [1,length] (without popping the list itself)
Q # Check that the two lists are equal (1 if truthy; 0 if falsey)
и # Repeat the list if prime factors that many times as list
# (so it'll become empty for falsey results; and stays the same for truthy)
g # Pop and push the length of this list
< # And decrease it by 1
# (NOTE: only 1 is truthy in 05AB1E, so if the amount of prime factors was
# anything other than 2, this will be falsey)
# (after which the filtered infinite list is output implicitly as result)
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes
*-3 thanks to Unrelated String!*
This defines a predicate that unifies with all-inclusive-semi-primes. In Prolog this is equivalent to a generator, that will return all all-inclusive-semi-primes one by one.
```
ḋĊcẹo~⟦₁&
```
[Try it online!](https://tio.run/##AS4A0f9icmFjaHlsb2cy/3vihrDigoLhuol94bag/@G4i8SKY@G6uW9@4p@m4oKBJv// "Brachylog – Try It Online")
```
ḋĊcẹo~⟦₁&
ḋ prime factors
Ċ are a pair (list of length 2)
cẹ and the elements of the concatenation (all the digits)
o ordered
~⟦₁ are the result of a range operation, f.e.
4 ⟦₁ [1,2,3,4]
[1,2,3,4] ~⟦₁ 4
& return the input
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes
Outputs all **all-inclusive semi-primes**, not quite in ascending order.
```
7°ÅpâʒS{āQ}PÙ
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f/NCGw60FhxedmhRcfaQxsDbg8Mz//wE "05AB1E – Try It Online")
**Commented**:
The `S{āQ` is borrowed from [Kevin's answer](https://codegolf.stackexchange.com/a/215130/64121).
```
7° # push 10^7
Åp # push the first 10^7 primes
# the first 5694505 would be enough but costs more bytes
â # take the cartesian product of that list with itself
# to create all pairs of primes
ʒ } # filter the pairs by
S # split into a list of digits
{ # sort the digits
ā # push the range [1 .. length]
Q # are those lists equal?
P # take the product of each pair
Ù # take the unique elements
```
The different order is a result of the order of the cartesian product, pairs that start with `2` are first, then pairs with `3`, `7`... The order could be fixed by replacing `Ù` with `ê` (unique sort), but this would prevent output until all calculations are finished.
`98765431`, the `5694505th` prime number, is the largest prime that can be used to create an all-inclusive semi-prime.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~22 21 17~~ 16 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
âH«q☻╧Ñ♦├x╓║Nm"°
```
[Run and debug it](https://staxlang.xyz/#p=8348ae7102cfa504c378d6ba4e6d22f8&i=&a=1)
-1 byte using a generating block.
-4 bytes using a filter.
-1 byte from wastl.
Outputs infinite list, separated by newlines.
## Explanation (Uncompressed)
```
VIf|fY%2=y$eEc%R|}*
VIf filter natural numbers, printing truthy values
take current iteration value
|fY store prime factorization in Y(without pop)
% Length
2= Equals 2?
y Push prime factors again
$eE Convert to string, then to digits
c% copy and take length
R Range [1..length]
|} are they setwise equal?
* multiply the two values
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~21~~ ~~19~~ ~~18~~ ~~16~~ 14 bytes
(or **[15 bytes](https://tio.run/##yygtzv7/XzHtxPpzW0sKgFTwoWVHGx7ubEwp8Pv//7@RAQA)** for versions that just output the n-th, or [first *n*](https://tio.run/##yygtzv7//1HbxLQT689tLSkAUsGHlh1teLizMaXA7////0YGAA) all-inclusive semi-primes, and so will always terminate instead of running indefinitely)
*Edit: -2 bytes thanks to Razetime's suggestion to just use `p` twice instead of my complicated approach of spending 3 bytes just to save one character...*
*...then another -1 byte, and again -3 bytes, thanks to Razetime*
*...then -2 more bytes thanks to Leo*
```
fȯεtpfȯS¦ŀṁdpN
```
[Try it online!](https://tio.run/##yygtzv7/qG3io6bG/2kn1p/bWlIApIIPLTva8HBnY0qB3////40MAA "Husk – Try It Online")
Returns infinite list of all-inclusive semi-primes.
[TIO](https://tio.run/##yygtzv7/qG3io6bG/2kn1p/bWlIApIIPLTva8HBnY0qB3////40MAA "Husk – Try It Online") header selects first 20 to avoid timing-out.
```
!fo§&o=2L(§=OoḣLṁd)pN
! # get the input-th element of
f N # natural numbers that satisfy
o§& p # both conditions of prime factors:
o=2L # there are 2 of them, and
ṁd) # their digits
O # sorted
(§= # are equal to
oḣL # the sequence from 1..number of digits
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~22~~ ~~21~~ 19 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Returns the first `n` terms; replace `j` with `i` to return the 0-indexed `n`th term.
```
È=k)cì ÍeX¬ÊõXÊÉ}jU
```
Try [the first 10 terms](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yD1rKWPsIM1lWKzK9VjKyX1qVQ&input=MTA) or [the first 100 terms](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yD1rKWPsIM1lWKzK9VjKyX1qVQ&input=MTAw)
```
È=k)cì ÍeX¬ÊõXÊÉ}jU :Implicit input of integer U
È :Function taking an integer X as argument
= : Reassign to X
k : Prime factors
) : End reassignment
c : Flat map
ì : Digit arrays
Í : Sort
e : Test equality with
X¬ : Join X
Ê : Length (a)
XÊÉ : Length of X minus 1 (b)
õ : Range [b,a]
} :End function
jU :Get the first U integers that return true (or the Uth, if using i)
```
[Answer]
# JavaScript (ES6), 108 bytes
Returns the **n**-th term, 1-indexed.
```
f=(n,k=2)=>(g=n=>a=q>n?'':n%q?g(n,q++):q+g(n/q,i--))(k,q=i=2)*i|[...a].sort().some(v=>v^++i)||--n?f(n,k+1):k
```
[Try it online!](https://tio.run/##FY1BDoIwFET3nqILDP2W1uBO8MNBjIYGgVTw1wJhA5y91tVMMvNm3nrRUz2a7yzJvhrvW@SU9HgBLHiHhIVGV1AZxxkdXdmF0AkBmRPBnl1ipATgfeLQBOZktrtSSj/UZMeZQ5BPwxcslqcQBrZNSirb/4FIIet9a0dODFmaM2I3dg0Sxtl6YKy2NNmhUYPteKV5tNIOoRmtAYe9gvyw@x8 "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
n, // n = input
k = 2 // k = next integer to test
) => ( //
g = n => // g is a recursive function taking an integer and building
// a concatenation of its divisors
a = // assign the final result to a:
q > n ? // if q is greater than n:
'' // stop and coerce the answer to a string
: // else:
n % q ? // if q is not a divisor of n:
g(n, q++) // do a recursive call to g with q + 1
: // else:
q + // append q
g(n / q, i--) // and do a recursive call to g with n / q and i - 1
)(k, q = i = 2) // initial call to g with n = k, q = 2 and i = 2
* i | // if i is not equal to 0 (i.e. k has not exactly 2 divisors)
[...a].sort() // or the sorted digits of a ...
.some(v => v ^ ++i) // ... do not match the sequence 1, 2, ..., x
|| --n ? // or the previous conditions are met but decrementing n does
// not result in 0:
f(n, k + 1) // do a recursive call to f with k + 1
: // else:
k // success: return k
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 123 bytes
outputs the nth term
```
(n=w=0;While[n<#,If[Last/@(f=FactorInteger)@w=={1,1}&&(s=Sort[Join@@(IntegerDigits@#&@@@f@w)])==Range@Max@s,n++];w++];w-1)&
```
[Try it online!](https://tio.run/##LcpBC4IwFADgvxIIY0ND7WoP3kECoyDq0EE8DJlzkE/YHiyIfvuC6vKdvkXzbBbNbtTJQpIEEarmPruH6WmfFd3Un3TgEuUEBz3y6jtiY41XGAFedVG/hZABbqvn/rg6QpT/0TrrOGAmEHHCqAYFcNVkDZ71E0NBeT408cu2ViJdvCPelGhL/LVdldIH "Wolfram Language (Mathematica) – Try It Online")
the following prints all `36918` terms
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 139 bytes
```
Union@(f=Flatten)[Times@@d/@#&/@Select[f[(q=#;TakeDrop[q,#]&/@o)&/@Permutations[o=Range@#],1],And@@PrimeQ[(d=FromDigits)/@#]&]&/@3~Range~9]
```
[Try it online!](https://tio.run/##Hc3BCoMwEATQjwmIgiClp1ICWxDP2tpTyCHoakPNpsb16q@naS9zGeaNM/xCZ9gOJrbBEkO3W2SIT7KeIJ9ksxhmpEL11uEGMFYgsgoeuODAalL5KsW1N2@sg/@otRQ6tb5I0WJwOyfb06a8vBuaEYQuT7q80QiQ/hx2Kh9lE7yr7Wx5K5Kusx9xPv6D46JjjF8 "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Factor](https://factorcode.org/), ~~190~~ 175 bytes
```
: f ( n -- n ) 1 [ over 0 = ] [ dup factors [ 10 >base ] map
[ pair? ] [ concat [ length [1,b] [ 48 + ] map ] keep
diff ""= ] bi and [ [ 1 - ] dip ] when 1 + ] until nip 1 - ;
```
[Try it online!](https://tio.run/##PVCxTsMwFNzzFadOIHCUVAyoVUFMqEsXxBQxOMlLa9V5MbZT1K8PL05hOZ3P9@6eXqebOPjp82N/eN9Ae6@vAWfyTBa9jqcEudM@kL9xb3oKeZcGw6J5zUcKCPQ9EjeJxQDnKcar@Dlim@0PG7xZqww3dgzmQipQb9QSN23Q4Q4MpQTuUaLCcJHKAjt8yaMdHf4qK5QFXmodSL567bIKThv/mozNwI2OQizxUfavysd61p@e8bDYBc9ELmtN12G1mvNrA82tuCQaSoTWzLafE7EI89zI0ViwyLNhO62L/@S0GtbpdreGfPoF "Factor – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), ~~228~~...~~214~~ 212 bytes
-7 bytes thanks to [@Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)!
```
b->{int x=9,l,C[],y,i=b;for(;i>0;i-=b){y=++x;var s="";for(b=0;y>1&&b++<2;y/=l,s+=l)for(l=1;l++<y&y%l>0;);C=new int[l=s.length()];b-=y;for(var c:s.getBytes())b&=c-49<l&c>48?C[c-49]=1:0;for(int k:C)b&=k;}return x;}
```
[Try it online!](https://tio.run/##ZZA/b4MwEMX3fIpTpCIs/jRUGZoYU6lIlTp0yogYbGKoE8cgbNJYEZ@dGpROHax39j3/7vRO9Eqj0/E8VZJqDV9UKLivALqBSVGBNtQ4OTlXPBgh43pQlRGtij8eRfqpDG94H8KjyKAGMrEouwtl4EZ2oQzzogxtKAjDddv7WGQbLCLC0N2SILjhK@1Bk/V66TKywTZLPI8FQfqC7TORoQ6IRHNTkgRL9249@yQdBeGcKP4DblQhiY4lV4359lGJWUTswpvh1V7HDTfv1nDtI8Q8UkXbXSq9Ktu@vuXFfCtJst8sP@a9z/t8tp3x2HMz9ApueJzwv2CurTjCxYXmH0wvVFOUQPtGoyVDAEeDBSeAQIKdpJAsGgR/HoCD1YZf4nYwcecgRiq/jmnXSesLhPDiGlfzGadf "Java (JDK) – Try It Online")
Returns the nth element of the sequence (1-indexed).
Ungolfed:
```
b -> {
int x = 9, l, C[], y, b, i = b;
for (; i > 0; i -= b) {
y = ++x;
var s = "";
for (b = 0; y > 1 && b++ < 2; y /= l, s += l)
for (l = 1; l++ < y & y % l > 0;);
C = new int[l = s.length()];
b -= y;
for (var c : s.getBytes())
b &= c - 49 < l & c > 48 ? C[c - 49] = 1 : 0;
for (int k : C) b &= k;
}
return x;
}
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~112~~ 111 bytes
```
123456789
L$`.
:::$>`
+%/\d$/&Lv$`(.)(.*:)(.)
$`$1$3$2$'
\d+
*
A`:_?:|(:_+)\1|:(__+)\2+:
:(_+):(_+):
$.($.1*$2
```
[Try it online!](https://tio.run/##Jci9CsJAEEXh/j7HVfcHJszGagrFPo@wkBFiYZMiSKq8@xpjc/g4y@vznp/aGrT0Vwx0gZnx5sinrk7szsNKDxKDJNsTQaeyZ@EFdcpIeLiNd9ssjDla1R921ZIN/3cElEDRxNLaFw "Retina – Try It Online") Above program outputs the entire sequence, but TIO times out if the total number of semiprime digits is not less than 5, so the link only outputs six elements. Explanation:
```
123456789
```
Start with the potential semiprime digits.
```
L$`.
:::$>`
```
Get all their prefixes and add some markers to delimit the potential prime factors.
```
+%/\d$/&Lv$`(.)(.*:)(.)
$`$1$3$2$'
```
Generate all permutations of the digits among the potential primes.
```
\d+
*
```
Convert all the numbers to unary.
```
A`:_?:|(:_+)\1|:(__+)\2+:
```
Delete all results unless both numbers are prime and the first is greater than the second. This is one of the slowest parts of the program; [Try it online!](https://tio.run/##JYi9DoJAEAb77zk@9X6SJXtIs4XGnke4hDXBgobCGF//QGlmJvN@fZb1qa1BS38dMNIFZsabI5@6OrM7j196kBgk2Y4IOpU9Cy@oc0bCw226209hytGqHrl31Ww47h@gBIomltY2 "Retina – Try It Online") can calculate 23 results if these are split into separate filters. However, despite my best efforts, larger results are simply too slow.
```
:(_+):(_+):
$.($.1*$2
```
Calculate the resulting semiprimes.
[Answer]
# [Raku](http://raku.org/), 123 bytes
```
{grep({$!=$_/($/=first $_%%*,2..$_);$!.is-prime&&{.[0]===.first(:k,0)}(+«[\∖]
"$!$/".comb.Bag,|('1'..'9'))},9..∞)[$_]}
```
[Try it online!](https://tio.run/##Hc3BDYIwFADQu1MU8qGt1l/0QIKmF9dAbNBQQpRAiheC3JnAowu4haOwSDXeX/Lawt5iV/ckNES5obRFywbwFGjJQCpT2e5OQAfBUmwRQfM9eFh169ZWdRGGA6ZRppTCP2S7q4j4yFafd3qcp2e28MED6eOlqc94yEvxYHRDEWlCOR9FgjhPL56CzkbX5T0x7DcQ01hyit0X "Perl 6 – Try It Online")
* `$_` is the argument to the function.
* `grep(..., 9..∞)` filters the integers from nine to infinity. `[$_]` indexes into that sequence with the function argument and returns that value. Within the filtering function `$_` is the number being tested.
* `$! = $_ / ($/ = first $_ %% *, 2..$_)` sets `$/` to the smallest (necessarily prime) divisor of `$_`, and `$!` to `$_` divided by that number.
* If `$!` is not prime, then `$_` is not a semiprime, so the filter function returns false.
* `"$!$/"` is the concatenation of the semiprime's two factors.
* `.comb` returns a list of those digits.
* `.Bag` returns a bag (that is, a set with multiplicity) of those digits.
* `[\∖]` is a triangular reduction using the set-difference operator `∖` on the list consisting of the aforementioned Bag and each of the digits from 1 to 9. The elements of this reduction are the initial Bag, then the same bag with a single `1` removed, then that second Bag with a single `2` removed, and so on.
Now the idea is to check that this sequence of bags gets exactly one element smaller as one of each successive digit is removed until it reaches a size of zero.
* `+«` turns that list of Bags into a list of their sizes (which counts multiplicity).
* That list of sizes is fed into the bracket-delimited anonymous function, which is immediately called. Within that function, `$_` refers to the list of sizes.
* `.first(:k, 0)` returns the index of the first zero element of the list. If no element is zero, `Nil` is returned instead.
* `.[0] === .first(:k, 0)` is true if the index of the first zero is equal to the first element of the list. This will be true only for lists of the form `N, N-1, N-2, ..., 1, 0, 0, 0`. From the way the list is constructed, each successive element can only ever be one or zero less than the preceding element.
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 208 bytes
```
def f(x,r={26},n=9,R=range):
while len(r)<x:
for d in R(2,n:=n+1):n%d<1and all(k%i for k in(d,n//d)for i in R(2,k))*(l:=[*map(int,sorted(str(d)+str(n//d)))])==[*R(1,len(l)+1)]and r.add(n)
return sorted(r)
```
[Try it online!](https://tio.run/##PVTbctpADH3nKzTTyeBN3LL3CxP3I/JKeaDYBA9kYYzTpMPw7VTSOuXBZ6XV5Uhacf477k/ZxPNwv7fdDnbVZz00V@1vdW5S/dIMm/zaieUMPvb9sYNjl6tBPH@iAnanAVroM7xUus7LJj8pscwP7bPa5BY2x2N1eOjZ6oBWVVvnxaIVJPdfXgchHqvjslk9vm3OVZ/H@nIaxq6tLuNQteKJgL2EWIsGzV4qVROHo8Bka8oz/Ni0bZXFDIZufB8yTBEGce8@z90Wz9DASvsavK4haFNDpFOyeFLa41cniddGRvwGGclMKYd2hvRJkrOSgVQIifzQipUcSqkg6U7bEjMECoohHAErtTaKwUpOqMhdJ05glKbMptDwqCQGMmnmm1gyTCsGvksy0B0GoSgUiyRd2OpAJkraJJmoT6EQNhNj9lUYvlDXUwleKyZf2oDI9LEYzoxmHF7pqR06BS7WTJ0wutgb5yPprdYFo@H8zinNGIrsleFGBoxAflFpQi29Udw2z3qtXTTcOK/JH@k57qfBMgmtUrJgubc2caMdzpcQ@2gsITJmNLLgZBcc90lHWSYTkZAtEwqWZlPmjjPyyZZZFb1nvgYLYETibDeN3VAgssP@sL1xkuIT8rCN05ZlfGoKEbMTH2OnN@FoQIQuWLp3KUZCbJ9kTOjJ6Pk@ShfVerbdd9tDN@CTr@a/3rGE7bwGPikzF7P/28d7XdEqfW2JWCyUFEv4BuPm0F1gA3@64S8cT/kVxv6tg/EE7Yn2GlcMtvvTGfoRNR8ZTX/3I/4jAGRM3MMTKJYuKO14N/HXofCVa7XMa1aeB1z6aje/5ht8/wnXyw2uUwmrrmku69tc3P8B "Python 3.8 – Try It Online")
Inputs an integer \$n\$ and output the first \$n\$ all-inclusive semi-primes (\$1\$-indexed).
]
|
[Question]
[
How, you can’t remember the 6 or 7-digit phone number that appeared on the TV screen for a second?! Using the special technique described below, you will turn into a walking phonebook!
Obviously, the number `402` is easier to remember than the number `110010010`, and the number `337377` is easier to remember than the number `957472`.
This means that the memorized number, on the one hand, should contain as few digits as possible, and on the other hand, it is desirable that the number contains as many repeating numbers as possible.
As a criterion for the difficulty of remembering, we take the sum of the number of digits in number and the number of different digits in number. A memorized number can be written in another number system, perhaps then it will be easier to remember. For example, the number `65535` in the hexadecimal notation looks like `FFFF`.
## Task
You need to write a program for selecting the base of the number system to minimize the complexity criterion. The base of the number system must be selected in the range from 2 to 36, then the numbers `0-9` and the English letters `A-Z` can be used to represent the number.
## Input
The input contains a decimal integer from 1 to 999999999.
## Output
The output must contain the base of the number system (from 2 to 36), minimizing the criterion of memorization complexity, and the number in the selected number system, separated by one space. If several bases give the same value for the criterion, then choose the smallest among them.
## Notes
* The letters must be uppercase(`A-Z`).
## Test Cases
### Input Output
`1` `2 1`
`2` `3 2`
`65535` `16 FFFF`
`123` `12 A3`
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~55~~ 54 bytes
*-1 byte thanks to Jo King.*
```
{~map({$^b,.base($b)},2..36).min:{@$_+.Set}o*[1].comb}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/ui43sUCjWiUuSUcvKbE4VUMlSbNWx0hPz9hMUy83M8@q2kElXlsvOLWkNl8r2jBWLzk/N6n2f3FipUKahkq8pkJafpGCoY6CkY6CmampsamOgqGR8X8A "Perl 6 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~150~~ ~~149~~ ~~127~~ 144 bytes
```
lambda n:min((len(c(n,b))+len(set(c(n,b))),b,c(n,b))for b in range(2,37))[1:]
c=lambda n,b,s='':n and c(n/b,b,chr(n%b+48+7*(n%b>9))+s)or s or'0'
```
[Try it online!](https://tio.run/##TY5LCoMwEED3nmI2JUkNVKPxB/YibReJf9BREjc9fRqh0u7eg5k3s733cUXh@vrpZrXoVgFWy4SUzh3ShiLXjIUH224/nXHNv9ivBjRMCEbh0FHBk5yxR1y9gqY@e37a1oRUCApb8Is3fQRGQ/Giw7QI8@tB99JfsswHLayGRMRtZsIdeipYcGImZSJ/Goskldmfp2UUFZl/wn0A "Python 2 – Try It Online")
---
# [Python 3](https://docs.python.org/3/), 136 bytes
```
lambda n:min((len((*c(n,b),*{*c(n,b)})),b,c(n,b))for b in range(2,37))[1:]
c=lambda n,b,s='':n and c(n//b,b,chr(n%b+48+7*(n%b>9))+s)or s
```
[Try it online!](https://tio.run/##TY7LCoMwEEX3fkU2xYwGfMT4AvsjbReJjyroKNFNKf32NNIKboZzh7mHWV5bPyM3XXU3o5xUIwmW04CUjq0dXk2RKWDe@08fAKbYj6GbNVFkQKIlPlsaM54B3KLy4dTVIbPXa@W6JRKJDbHFIFC7odcUL8pPcj/zdroWAP4K1riaRQ@40Y7GAM7BqRBcnHIU80Sk50VShGGe7i@YLw "Python 3 – Try It Online")
---
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 131 bytes
```
lambda n:min((len((*(x:=c(n,b)),*{*x})),b,x)for b in range(2,37))[1:]
c=lambda n,b,s='':n and c(n//b,b,chr(n%b+48+7*(n%b>9))+s)or s
```
[Try it online!](https://tio.run/##TY7JCoMwEIbvPkUuxRkNuMYlYF@k7cG4VEFHiR4spc9u40HwMv/Cz8fMn7WbKMpmvbfFcx/KUdUlIzn2BDA05jiwyaIC4gqRO19n@xlVfMN20kyxnpgu6d1AyKMU8RHIl1UVJ8cMl8K2JbGSamYonqdMV3Ua6KbcOHNT53D3HNFd0BCXfdY9rdBCiGidPhEiEpcchFEskmsR576fJccL@x8 "Python 3.8 (pre-release) – Try It Online")
---
`c` converts a base 10 number to any base (2-36), and the first (anonymous) function finds the smallest result.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~16~~ 14 bytes
*-1 byte thanks to Kevin Cruijssen*
```
₆LBāøΣнDÙìg}1è
```
[Try it online!](https://tio.run/##ASYA2f9vc2FiaWX//@KChkxCxIHDuM6j0L1Ew5nDrGd9McOo//82NTUzNQ "05AB1E – Try It Online")
Or [add R)» at the end](https://tio.run/##ASoA1f9vc2FiaWX//@KChkxCxIHDuM6j0L1Ew5nDrGd9McOoUinCu///NjU1MzU) to conform exactly to the specified output format, but most other answers didn't bother.
Explanation:
```
₆L # range 1..36
B # convert the input to each of those bases
āø # enumerate (pair each element with its 1-based index)
Σ } # sort by
g # length
н # of the first element
ì # concatenated to
DÙ # itself, uniquified
1è # take the second entry (first will always be base 1)
```
[Answer]
# JavaScript (ES6), ~~87 85~~ 101 bytes
*Edit: +16 useless bytes to comply with the strict output format*
```
n=>(g=m=>--b>2?g(m<(v=new Set(s=n.toString(b)).size+s.length)?m:(o=b+' '+s.toUpperCase(),v)):o)(b=37)
```
[Try it online!](https://tio.run/##DchBjoJAEEDRvafoHVUBOgoDKlq4MHMCM6uJC8CmxUAVoTuYeHlk83/yXtVcuWbqRh@zPMzS0sJUgqWByjiuy@RiYTjDTGze6mY8OGLt5eanji3UiNp1HxM63Ru2/omXoQChOgxUsKKXv3E007VyBjCaEQtBqCnd43L6TyKVZ1maRWqXpGt@jtvtIU/3941uZfqtmiewolI1wk56o3uxK4QqKFSwrgVGxOUL "JavaScript (Node.js) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0 [`-gS`](https://codegolf.meta.stackexchange.com/a/14339/), ~~24~~ 23 bytes
Not pretty, but it does the job. +2 bytes for the completely unnecessary requirement that output be uppercase.
```
37o2@sX u ¸iXÃñÈÌiXÌâ)l
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LWdT&code=MzdvMkBzWCB1ILhpWMPxyMxpWMziKWw&input=NjU1MzU)
```
37o2@sX u ¸iXÃñÈÌiXÌâ)l :Implicit input of integer
37o2 :Range [2,37)
@ :Map each X
sX : Convert the input to a base-X string
u : Uppercase
¸ : Split on spaces (there are none, so this returns a singleton array)
iX : Prepend X
à :End map
ñ :Sort by
È :Pass each X through the following function
Ì : Last element of X
i : Prepend
XÌâ : Last element of X, deduplicated
) : End prepend
l : Length
:Implicit output of the first sub-array, joined with spaces
```
[Answer]
# [PHP](https://php.net/), ~~124~~ 119 bytes
```
for($i=36;$b=strtoupper(base_convert($argn,10,--$i));$o[strlen($b.count_chars($b,3))]="$i $b");krsort($o);echo end($o);
```
[Try it online!](https://tio.run/##TZBRT4MwEMef5VNcSB8gAUcpMBDRwNziEuOLvm3LAliFuLWkLXsxfnYszBnvocn97n/3v2vXdMPtfdd0BlJUKgkZbAwA7MAVjDGbgQ9YE/8fIeBrEoUhCZ0LwxGsdIy9PnH@pNiHnJxhEEbOZQCGIFguRx4knhdHZO5MVnPI87woirGC4yRJ4hjrF@Nk7odk1Lh34EewWITrxyLAReg9FcYuNQzdLdtjfygVBX0OuCt45wJa1vUKOIOX14f1s6ERLesGLPg9t5SASvHBwIYvbUrrhoM5kZutMtNBN1iozUiUoiqTSijedx0VVlVKuq85O1GhrEnvYM9xXdTador4RksPlFmouq55z9S@bkohdeoQ295lJmoBVaadfgrJxwHcTidryt6mZLissmVmqvfqmaRn2fR/gupUi0@t4OxImTK@hx8 "PHP – Try It Online")
A shame about the **+12** bytes in PHP to uppercase the output... but... anyway.
[Answer]
# [Zsh](https://www.zsh.org/), 85 bytes
```
for b ({36..2})x=$[[#$b]$1]&&x=${x#*\#}&&a[$#x+${#${(us::)x}}]=$b\ $x
a=($a)
<<<$a[1]
```
For this number of statements inside the for loop, using `...&&...&&...` is shorter than `{...;...;...;}`.
```
for b ({36..2}) # order decreasing: smaller bases overwrite larger ones
x=$[[#$b]$1] && \ # set x to [base]#[num]
x=${x#*\#} && \ # strip leading [base]#
a[$#x+${#${(us::)x}}]=$b\ $x # use score as index to store "[base] [number]"
# ${(us::) } # (s::)plit into characters, take (u)nique
a=($a) # remove empty elements from array
<<<$a[1] # print out the first element (smallest score)
```
[Try it online!](https://tio.run/##FY1BCoMwEADv@4pgFtEWJTEktlZfojlETFEQBa00VHx7qseZw8xv7f23H0ZLFms6Mg6TfZFuhtV@SJKQAC8T@Pe8kJZEu1Bpmh2xq7CuKbYauQ7Dk3ZHbw09wtDUSN0dd4p7tK1FEbvj0BW2DUEHporQxFCWJZqaa79N18acZQfdPFnPIQPOQEkpJIgceCZAKMbgoXIp2BP@ "Zsh – Try It Online")
Here's an 81-byte solution which prints in the form `[base]#[num]` instead:
```
for b ({36..2})x=$[[#$b]$1]&&y=${x#*\#}&&a[$#y+${#${(us::)y}}]=$x
a=($a)
<<<$a[1]
```
[Try it online!](https://tio.run/##Fc1BCoMwEEDR/ZwimCFoi2IMamvNSayLiCkKoqCVxoacPa3bv3j/uw3@M4yTJqtWPZnGWT9Iv8Cm3ySOSYBnCfxrWUlHQiuKJMlcZCQ2DcWuRd4ydki0hl6e1DGmGqTHFS1FG@5bVUWHc61EA0qGqCKo6xpVw1u/z@dC/VUD/TJrzyEDnkKR5yIHUQLPBIgiTeFWlLlI7/AD "Zsh – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 67 bytes
```
(];'0123456789ABCDEF'{~b)[:(2+]i.<./)](#+#@~.)@(b=:#.inv~)"+2+i.@35
```
[Try it online!](https://tio.run/##Pcm7DsIgFADQna@4KQMQzJWCVEVJ8PkThqWmpDjo0MTFyK/jVLeTnEdNk0dQ4EBVHndMtdqsbLfebA/H0/lyZZ/Si5vjWsaMe1yKyKmkoaAIvPeOYn6@i2iklhmDsVWQBoEljwwW8HWQJkKG@/iCBO0MPaOz1th/a0PqDw "J – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 38 bytes
```
Nθ≔EE³⁴↨θ⁺²ιL⁺ιΦι⁼λ⌕ικη≔⁺²⌕η⌊ηηIη ↥⍘θη
```
[Try it online!](https://tio.run/##RY7NCsIwEITvPsXS0wbixVovPakoCFYK4gPEGppgGtP8@PqxCbQuLMx@DLPTCWa7D1MxXrQJ/haGJ7c4knq1d072Ghtm8pZbCgfmOI4UWhUcbihIQgiFK9e9F5ihpHCWyk8RkzqNgSmHKjH9SuRN8lAQ/wdzWPYICo3UcggDisXYWqk9HpnzCc53AcWiH8Zw26V2qeLdT7BPRVNGHeOuqsoqrr/qBw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input the integer.
```
≔EE³⁴↨θ⁺²ι
```
Convert it from base 2 to base 36...
```
L⁺ιΦι⁼λ⌕ικη
```
... deduplicate, concatenate, and take the length.
```
≔⁺²⌕η⌊ηη
```
Take the index of the minimum complexity and add 2 to get the base.
```
Iη ↥⍘θη
```
Print the base and the integer converted to that base in upper case.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 19 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
Ç╛;ⁿY3█↕(╖S♪*ò▌?½╦l
```
[Run and debug it](https://staxlang.xyz/#p=80be3bfc5933db1228b7530d2a95dd3fabcb6c&i=1%0A2%0A65535%0A123&a=1&m=2)
No fancy algorithm, just straightforward brute force. About a third of the program is format-wrangling for the precise output rules.
Bonus program: [Output for [1..1000]](https://staxlang.xyz/#p=a1c237f507227beab9c02f200e5ac053b7fee47c&i=&a=1)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 25 bytes
```
bⱮ36µQL+LN)Mḟ1Ḣ,ị‘ịØBʋ¥⁸K
```
[Try it online!](https://tio.run/##ATgAx/9qZWxsef//YuKxrjM2wrVRTCtMTilN4bifMeG4oizhu4vigJjhu4vDmELKi8Kl4oG4S////zEyMw "Jelly – Try It Online")
A monadic link taking an integer as its argument and returning a Jelly string of the desired format. If a two-item list was acceptable output (as per most challenges), could save 2 bytes. If base 1 were acceptable for the edge case of 1 as input, could save a further 2 bytes.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 44 bytes
```
∧Y≜∧36≥Xℕ₂≜&ḃ↙X Zd,Zl≡Y∧XwṢwZ{-₁₀;Ạụᵗ∋₍|}ᵐwᵐ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompkcdyx/u2vFwV2ftw60T/gN5kY865wApY7NHnUsjHrVMBanpnKP2cEfzo7aZEQpRKTpROY86F0YC1USUP9y5qDyqWvdRU@Ojpgbrh7sWPNy99OHW6Y86uh819daAjCwHGfs/2lDHSMfM1NTYVMfQyFjHwNDQwtLS0sLCEEgaGlqaG5kaxwIA "Brachylog – Try It Online")
This hurt a bit to write.
[Answer]
# [Perl 5](https://www.perl.org/), 161 bytes
```
sub f{$X=99;for$b(2..36){$_=c($_[0],$b);$x=uniq(/./g)+y///c;($X,$B,$C)=($x,$b,$_)if$x<$X}$B,$C}
sub c{my($n,$b)=@_;$n?c(int$n/$b,$b).chr(48+$n%$b+7*($n%$b>9)):''}
```
[Try it online!](https://tio.run/##dY5PS8NAFMTvfop3ePJ27ZJ0d5ukaUz9Bz3prUJBJJCQ6EpNNUmhpfSz12xsq2Cdw/JgfjM7H3k193bLOod7Uzej0cOiyh8bM6@BlqX5pGhXL1MoNjiLwzAqFhWmTDmO9vkGkzhjmDz1nwWmPMJVbBPMddwX3lu7rptFDGcCbwXe8ZjhqsUEJtwUuLrE2bYztrY@27yvGZa2Jr5OIiyvMmbKBkvXJlLuZK8VGwx7WJ5j2gsuWHeMQ85HRNtu/TQ/rIemPet4PIzOTM0gY9IT0ucCrGhC7ct/WWrvAMlWdLRCLxgESmjr0zSQ/YP1tjAlIyBRMMmPYQXSNsNfSP1AGtQ/kO952utAkj5MWp36Tul9F0kFN5pONX3vthxpBfvhuy8 "Perl 5 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~140~~ 135 bytes
```
lambda n:min([(b,g(n,b))for b in range(2,36)],key=lambda(b,s):len(s)+len(set(s)))
g=lambda n,b:n and g(n/b,b)+chr(n%b+48+7*(n%b>9))or''
```
[Try it online!](https://tio.run/##NY3LDoIwFETX8hXdmPbamxiKoDYpP4IsqPKKcCGFDV9fi8bVnMXMmXlbu4mUb8zDD9VoXxUjPfYkCmGxFYQWoJkcs6wn5ipqa6EwyaDEd72Z3yI0F9BDTWIB@Y16DQgQtebvRKuJVfRiwXm2wSqfnRN0tPJyk9fTTvkdYHKc@/2P9r8iRoVZmiYpxiopdXSYXU9rsHGTc2wEgf8A "Python 2 – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-Minteger -MList::Util=uniq,first -ap`, ~~123~~ 112 bytes
```
$"=$,;map{@r=();$t="@F";do{unshift@r,(0..9,A..Z)[$t%$_]}while$t/=$_;$a[@r+uniq@r]||="$_ @r"}2..36;$_=first{$_}@a
```
[Try it online!](https://tio.run/##HY7BagIxFADvfkXYvoLSNV1dItQQSC89tcdeFAmBxvogJmnyFg/r/npT7WnmNpNc9qJWaBS08mzTqLOaLySQavRbI7/iOIRywiPp3M47zl/aV853iz3QI5jDdDmhd0DPCowEu9f5aQj4o/PhelUNGKZzM6057zcSjDpiLjSCmbStEorqpLb32IP1Pl4KOw@eMHnHyBUqDAOLwbE8hLoRohez1br/jYkwhlKXH4J3q@5GDOS@Xb7ZOxbabj8JvbpftP@9urTJ/wE "Perl 5 – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~109~~ 111 bytes
```
Print[a=OrderingBy[#~IntegerDigits~Range@36,Tr[1^#]+Tr[1^Union@#]&,1][[1]]," ",ToUpperCase[#~IntegerString~a]]&
```
+2: fixed. Thanks for the catch @Roman
[`OrderingBy`](https://reference.wolfram.com/language/ref/OrderingBy.html) was introduced in Mathematica 12.0, which TIO does not seem to have updated to yet.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0, 31 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
2o37 ñ@sX Ê+UsX â ÊÃÎ
+S+NÎsU u
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=Mm8zNyDxQHNYIMorVXNYIOIgysPOCitTK07Oc1UgdQ&input=NjU1MzU)
[Answer]
# Scala, ~~105~~ 97 bytes
```
n=>{val(b,x)=2.to(36)map(b=>b->n.toString(b))minBy((_,x)=>(x++x.toSet).size);b+" "+x.toUpperCase}
```
[Try it online!](https://scastie.scala-lang.org/yEnEOAFHTsO5c9tFxUPcew)
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~165~~ 161 bytes
```
j,r,m,x,*_;t(n){for(char*g,b[74][37]={},i=1,p=99;g=b[++i],i<37;r=j<p?_=g,p=j,i:r)for(j=0,m=n;m;m/=i,*--g=x+=x>9?87:48)j-=~!b[i+36][x=m%i]++;printf("%i,%s",r,_);}
```
[Try it online!](https://tio.run/##Zc7BioMwEAbge5/CFYTEjKw2arTpbB9ERFRoNrJJJbUgiPvqrj3syTn98/0wTB/1P61V2zaAAwMzhI2ciKXL/eFI/926UEFXibSuuKhxWUFjAiOWpVTYVYzpGvSVC@lwuI63BtVeDqAvjr4PDBiDQSuNNJ@oIYwihTPD@au8FeKSFnSI8PejqzTjeV3NaAJdMyZHp@10J36gIXj6@2MNleu2m2dabQldTp43kYTK0/iansT39/SW80HyLOPZQZMzP1p8pLSM4yLn4tCU/7Pv6/YH "C (clang) – Try It Online")
* Shortened and improved by @ceilingcat
```
n//input
,i=2//iterator from base 2 to 36
,j//current complexity
,p=99//best complexity
,r//result = iterator
,m// temp copy of n
,x ;// m%i
char*g // current string ptr
,*_ // best str ptr
,b[74][37];//buffer
/* [37+37] = [strings obtained +
test for used characters ]
*/
t(n){
for(; g=b[i], // move ptr
i<37 ;
r=j<p?_=g,p=j,i:r, // save best solution
++i){//for every base
for( j=0,m=n; m ; m/=i, // extract digit
*--g=x+=x>9?87:48)
// move ptr backward for printf use and transform to ascii value
j+=b[i+36][x=m%i]++?1:2;
// increment byte relative to the character
// and if it was 0 increments j by 2 : 1 for the new character used and 1 for digit count
// else incr only digits count + move pointer
//printf("%s - ",g);// test
// printf("r%i p%i j%i\n",r,p,j);// test
}
printf("%i,%s",r,_);//output
}
```
]
|
[Question]
[
## Introduction *(may be ignored)*
Putting all positive numbers in its regular order (1, 2, 3, ...) is a bit boring, isn't it? So here is a series of challenges around permutations (reshuffelings) of all positive numbers. This is the fourth challenge in this series (links to the [first](https://codegolf.stackexchange.com/questions/181268), [second](https://codegolf.stackexchange.com/questions/181825) and [third](https://codegolf.stackexchange.com/questions/182348) challenge).
In this challenge, we will explore not *one* permutation of the natural numbers, but an entire [world](https://www.youtube.com/watch?v=CXzs47qy2Pk) of permutations!
In 2000, [Clark Kimberling](http://faculty.evansville.edu/ck6/index.html) posed a problem in the 26th issue of *Crux Mathematicorum*, a scientific journal of mathematics published by the Canadian Mathematical Society. The problem was:
>
> \$\text{Sequence }a = \begin{cases}
> a\_1 = 1\\
> a\_n = \lfloor \frac{a\_{n-1}}{2} \rfloor\text{ if }\lfloor \frac{a\_{n-1}}{2} \rfloor \notin \{0, a\_1, ... , a\_{n-1}\}\\
> a\_n = 3 a\_{n-1}\text{ otherwise}
> \end{cases}\$
>
>
> ***Does every positive integer occur exactly once in this sequence?***
>
>
>
In 2004, Mateusz Kwasnicki provided positive proof in the same journal and in 2008, he [published](http://prac.im.pwr.edu.pl/~kwasnicki/stuff/MDproblem.en.pdf) a more formal and (compared to the original question) a more general proof. He formulated the sequence with parameters \$p\$ and \$q\$:
\$\begin{cases}
a\_1 = 1\\
a\_n = \lfloor \frac{a\_{n-1}}{q} \rfloor\text{ if }\lfloor \frac{a\_{n-1}}{q} \rfloor \notin \{0, a\_1, ... , a\_{n-1}\}\\
a\_n = p a\_{n-1}\text{ otherwise}
\end{cases}\$
He proved that for any \$p, q>1\$ such that \$log\_p(q)\$ is irrational, the sequence is a permutation of the natural numbers. Since there are an infinite number of \$p\$ and \$q\$ values for which this is true, this is truly an entire [world](https://www.youtube.com/watch?v=CXzs47qy2Pk) of permutations of the natural numbers. We will stick with the original \$(p, q)=(3, 2)\$, and for these paramters, the sequence can be found as [A050000](https://oeis.org/A050000) in the OEIS. Its first 20 elements are:
```
1, 3, 9, 4, 2, 6, 18, 54, 27, 13, 39, 19, 57, 28, 14, 7, 21, 10, 5, 15
```
Since this is a "pure sequence" challenge, the task is to output \$a(n)\$ for a given \$n\$ as input, where \$a(n)\$ is [A050000](https://oeis.org/A050000).
## Task
Given an integer input \$n\$, output \$a(n)\$ in integer format, where:
\$\begin{cases}
a(1) = 1\\
a(n) = \lfloor \frac{a(n-1)}{2} \rfloor\text{ if }\lfloor \frac{a(n-1)}{2} \rfloor \notin \{0, a\_1, ... , a(n-1)\}\\
a(n) = 3 a(n-1)\text{ otherwise}
\end{cases}\$
*Note: 1-based indexing is assumed here; you may use 0-based indexing, so \$a(0) = 1; a(1) = 3\$, etc. Please mention this in your answer if you choose to use this.*
## Test cases
```
Input | Output
---------------
1 | 1
5 | 2
20 | 15
50 | 165
78 | 207
123 | 94
1234 | 3537
3000 | 2245
9999 | 4065
29890 | 149853
```
## Rules
* Input and output are integers (your program should at least support input and output in the range of 1 up to 32767)
* Invalid input (0, floats, strings, negative values, etc.) may lead to unpredicted output, errors or (un)defined behaviour.
* Default [I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) apply.
* [Default loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answers in bytes wins
[Answer]
# JavaScript (ES6), ~~55 51~~ 50 bytes
*Saved 1 byte thanks to @EmbodimentofIgnorance*
*Saved 1 byte thanks to @tsh*
```
n=>eval("for(o=[p=2];n--;)o[p=o[q=p>>1]?3*p:q]=p")
```
[Try it online!](https://tio.run/##bc5NCsIwEAXgvcfoKhEi@VFsLBMPUrIINRGlZNJWev2YrYyzenw8HvMOe9im9VU@IuMj1gQ1g4t7mFmXcGUIYwHthyzEwLFlHBcozil/N8dyWzyUjtcJ84ZzPM34ZIkpzg@/ciGiJS1RuvaElDb/7EzQSEkHbTv6i@1tq9Yv "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
µ×3żHḞḢḟȯ1Ṫ;µ¡Ḣ
```
A full program accepting the integer, `n` (1-based), from STDIN which prints the result.
**[Try it online!](https://tio.run/##ASsA1P9qZWxsef//wrXDlzPFvEjhuJ7huKLhuJ/IrzHhuao7wrXCoeG4ov//MTIz "Jelly – Try It Online")**
### How?
```
µ×3żHḞḢḟȯ1Ṫ;µ¡Ḣ - Main Link: no arguments (implicit left argument = 0)
µ µ¡ - repeat this monadic chain STDIN times (starting with x=0)
- e.g. x = ... 0 [1,0] [9,3,1,0]
×3 - multiply by 3 0 [3,0] [27,9,3,0]
H - halve 0 [1.5,0] [4.5,1.5,0.5,0]
ż - zip together [0,0] [[3,1.5],[0,0]] [[27,4.5],[9,1.5],[3,0.5],[0,0]]
Ḟ - floor [0,0] [[3,1],[0,0]] [[27,4],[9,1],[3,0],[0,0]]
Ḣ - head 0 [3,1] [27,4]
ḟ - filter discard if in x [] [3] [27,4]
ȯ1 - logical OR with 1 1 [3] [27,4]
Ṫ - tail 1 3 4
; - concatenate with x [1,0] [3,1,0] [4,9,3,1,0]
Ḣ - head 1 3 4
- implicit print
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~16~~ 15 bytes
Saved 1 byte thanks to *Kevin Cruijssen*.
0-indexed.
```
¾ˆ$FDˆx3*‚;ï¯Kн
```
[Try it online!](https://tio.run/##ASQA2/9vc2FiaWX//8K@y4YkRkTLhngzKuKAmjvDr8KvS9C9//8xMjI "05AB1E – Try It Online")
**Explanation**
Using `n=1` as example
```
¾ˆ # initialize global array as [0]
$ # initialize stack with 1, input
F # input times do:
Dˆ # duplicate current item (initially 1) and add one copy to global array
# STACK: 1, GLOBAL_ARRAY: [0, 1]
x # push Top_of_stack*2
# STACK: 1, 2, GLOBAL_ARRAY: [0, 1]
3* # multiply by 3
# STACK: 1, 6, GLOBAL_ARRAY: [0, 1]
‚;ï # pair and integer divide both by 2
# STACK: [0, 3], GLOBAL_ARRAY: [0, 1]
¯K # remove any numbers already in the global array
# STACK: [3], GLOBAL_ARRAY: [0, 1]
н # and take the head
# STACK: 3
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 49 bytes
*-2 bytes thanks to nwellnof*
```
{(1,3,{(3*@_[*-1]Xdiv 6,1).max(*∉@_)}...*)[$_]}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1rDUMdYp1rDWMshPlpL1zA2IiWzTMFMx1BTLzexQkPrUUenQ7xmrZ6enpZmtEp8bO3/4sRKhTSNOCMDzf8A "Perl 6 – Try It Online")
Returns the 0-indexed element in the sequence. You can change this to 1-indexed by changing the starting elements to `0,1` instead of `1,3`
### Explanation:
```
{ } # Anonymous code block
( ...*)[$_] # Index into the infinite sequence
1,3 # That starts with 1,3
,{ } # And each element is
( ).max( ) # The first of
@_[*-1]X # The previous element
3* div 6 # Halved and floored
3* div ,1 # Or tripled
*∉@_ # That hasn't appeared in the sequence yet
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~15~~ 14 bytes
1-indexed.
```
@[X*3Xz]kZ Ì}g
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QFtYKjNYel1rWiDMfWc&input=MTIzNA)
```
@[X*3Xz]kZ Ì}g :Implicit input of integer U
g :Starting with the array [0,1] do the following U times, pushing the result to the array each time
@ : Pass the last element X in the array Z through the following function
[ : Build an array containing
X*3 : X multiplied by 3
Xz : X floor divided by 2
] : Close array
kZ : Remove all elements contained in Z
Ì : Get the last element
} : End function
:Implicit output of the last element in the array
```
[Answer]
# [J](http://jsoftware.com/), ~~47~~ 40 bytes
```
[:{:0 1(],<.@-:@{:@](e.{[,3*{:@])])^:[~]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o62qrQwUDDVidWz0HHStHKqtHGI1UvWqo3WMtUBszVjNOKvoutj/mlx@TnpAjZl5KakVqSlcqckZ@QppSkABPSOD/wA "J – Try It Online")
## ungolfed
```
[: {: 0 1 (] , <.@-:@{:@] (e. { [ , 3 * {:@]) ])^:[~ ]
```
Direct translation of the definition into J. It builds bottom up by using `^:` to iterate from the starting value the required number of times.
[Answer]
# Java 10, ~~120~~ 99 bytes
```
n->{var L=" 1 0 ";int r=1,t;for(;n-->0;L+=r+" ")if(L.contains(" "+(r=(t=r)/2)+" "))r=t*3;return r;}
```
[Try it online.](https://tio.run/##hY/NboMwEITvPMWKk10K4adSQJbzBDSXHKseXAcqp8REy4IURTw7NTTXypeVdubTzO5FTSq@nH8W3alhgHdl7CMAMJYabJVu4LiumwCardNy4ZQ5cGMgRUbDESxIWGx8eEwKoZYhZJBCKFYcZfZKou2RCRvHh1TUkcQohJCbltWJ7i25zoE5JWIoGUnku5xvBEdJL4XAhka0gGJexFp7G786V/tsn3pzhqvLYCdCY78/PkHxv6NP94Gaa9KPlNycRZ1lNtEs5dsL//pvHj@rfAE@YL/3VeS5lygKD5JXle8QR5TelLJ8xszBvPwC)
**Explanation:**
```
n->{ // Method with integer as both parameter and return-type
var L=" 1 0 "; // Create a String that acts as 'List', starting at [1,0]
int r=1, // Result-integer, starting at 1
t; // Temp-integer, uninitialized
for(;n-->0; // Loop the input amount of times:
L+=r+" ")) // After every iteration: add the result to the 'List'
t=r // Create a copy of the result in `t`
r=(...)/2 // Then integer-divide the result by 2
if(L.contains(" "+(...)+" ")) // If the 'List' contains this result//2:
r=t*3; // Set the result to `t` multiplied by 3 instead
return r;} // Return the result
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~67~~ 65 bytes
```
(h[1,0]!!)
h l@(a:o)|elem(div a 2)o=a:h(3*a:l)|1>0=a:h(div a 2:l)
```
[Try it online!](https://tio.run/##LY1BDoIwFET3nqIkLlrzST5FIhAgXsATIDE/UCyxlAaMK85uReMks3jzFqNpeShjfF9ePdd1BNgEgdhpZs6c8kmsyqiRd8OLEZNiKinXPD5QbsQaVfjDv9wmP9Jgy5Hc5cbcPNgnq7kF1jMrVluEblZdsa@2kwQkQoJwSiGS8bdHiBERsi0gszTDpvHvtjd0X3zYOvcB "Haskell – Try It Online")
Uses 0-based indexing.
EDIT: saved 2 bytes by using `elem` instead of `notElem` and switching conditions
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes
```
Ø.;0ị×3$:2$:2eɗ?Ɗ$⁸¡Ṫ
```
[Try it online!](https://tio.run/##y0rNyan8///wDD1rg4e7uw9PN1axMgKi1JPT7Y91qTxq3HFo4cOdq/7//29paWkBAA "Jelly – Try It Online")
A monadic link that takes zero-indexed \$n\$ as the argument and returns \$a(n)\$.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~54~~ ~~52~~ 48 bytes
```
->n{*s=0;j=2;n.times{s<<j=s==s-[j/2]?j/2:j*3};j}
```
[Try it online!](https://tio.run/##RYzBDoIwEETv@xVNvBHBZdsVKlQ/hHBQA9EmNsbqwQDfXiEQnMNk3mQyr8/lG1oT4qPrIm@wsIYKl7zvj8Z3viyt8cb4uLI7qk@jHWwkh8IOASpIxaTtRogUeM0EhGvPwH/YM2T5OsMMUpILaTWBmkGyzEAi4rIkxaBHzahw/CGda5xflc5ZQp005@ut613/FG3l6iH8AA "Ruby – Try It Online")
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), ~~189~~ 180 bytes
-9 bytes to small golfing
```
#import<vector>
#import<algorithm>
int a(int n){std::vector<int>s={1};for(int i=0;i<n;++i)s.push_back(i&&std::find(s.begin(),s.end(),s[i]/2)==s.end()?s[i]/2:3*s[i]);return s[n-1];}
```
[Try it online!](https://tio.run/##VVFdb4IwFH2WX9G4xMBEx5dTLLgHs4f9BkOWWqo2g0JoWZYwfru7LbhNEnrb03tPzz2X1vXiTOn1@sDLumpU8smoqpqddTuT4lw1XF3KncWFQsTWq3A6qfLtdkhOANrJtPN7fKoak8BTD/NE4PmcO3JZt/LyfiT0w@azmSk8cZHbcnlkZy5sx5VLBmeIB549BU6ajsDLAGzDR71xcMNU2wgkD2LhZ7gH0YIWbc5QwiupGkZGlSXRtKizJuY1WrUKJQmavokadt9oTwraFkSxHFXtAL1@1dCMARQgU51vikFIga2Jabst90QyiVK0HiGuGeUhA6jzXbRyUeBBgH@9cZEfhGaJXBR6HoAxfJASb2KvHxmG9/4oAqgAGv/ZcK2hRlevQtgFQQRg5OkrP4o3q1CTgOdoMB0YPAwh@VWKkZ6ANuLeiVE2z4wt0L7pVw93xJ27i5vGIf@/Lb01GYfiYau//gA "C++ (gcc) – Try It Online")
Computes the sequence up to `n`, then returns the desired element. Slow for larger indices.
[Answer]
# [Python 2](https://docs.python.org/2/), 66 bytes
```
l=lambda n,p=1,s=[0]:p*(n<len(s))or l(n,3*p*(p/2in s)or p/2,[p]+s)
```
[Try it online!](https://tio.run/##FcjBDkAwDADQX9mxnSUYF2JfIjsQEkuqmtXF1w@3lyfPfVzsS6FAy7lui2EnoXUa5iaOYoEn2hkU8cqGgF1nv5TaJzb630c3S6wUi@TENxD0A2J5AQ "Python 2 – Try It Online")
Uses zero-based indexing. The lambda does little more than recursively building up the sequence and returning as soon as the required index is reached.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 14 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
üÑα↕○Ü1∟¡f↑ô┬♥
```
[Run and debug it](https://staxlang.xyz/#p=81a5e012099a311cad661893c203&i=0%0A4%0A19%0A49%0A77%0A122%0A1233%0A2999%0A9998%0A29889&a=1&m=2)
Zero-indexed.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 63 bytes
```
(L=Last)@Nest[{##,If[FreeQ[#,x=⌊L@#/2⌋],x,3L@#]}&,{0,1},#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X8PH1iexuETTwS@1uCS6WllZxzMt2q0oNTUwWlmnwvZRT5ePg7K@0aOe7lidCh1jICe2Vk2n2kDHsFZHOVbtf0BRZl6Jgr5Dur6DQrWhrqGOKRAbGYAYIMLcAkgYGhlDSBMgZWxgAJKwBAJdw9r//wE "Wolfram Language (Mathematica) – Try It Online")
This is 0-indexed
(In TIO I added -1 in every test case)
[Answer]
# [Haskell](https://www.haskell.org/), 55 bytes
```
(1%[0]!!)
a%o|b<-div a 2=a:last(b:[3*a|elem b o])%(a:o)
```
[Try it online!](https://tio.run/##FcPRCoIwFADQ977iCglbXGHOJBXtD/qCNeKas6Q5h0pPfnurDpwnLS9jbeiba2BprISOIr6jeNraOumGNxDIhipLy8raSmUH2ow1I7QwaR4zqiYeRhpcM5K/3MDPg1tBMYfQg@ObqxM/m67en1WKOUqBucBTganM/o@YCSGw/EFZFqXQOnzuvaXHEpK7918 "Haskell – Try It Online")
Golfing [user1472751's slick list-generation method](https://codegolf.stackexchange.com/a/182832/20260).
Same length:
```
(1%[0]!!)
a%o=a:[x|x<-[div a 2,a*3],all(/=x)o]!!0%(a:o)
```
[Try it online!](https://tio.run/##FcrfCoIwFIDx@55iQsKMIx1nkorrDXqCNeLgn5LmHBrhhc/esg9@d9@T5ldrjO/kzfMkVKiDINpROEoq1bIuVaya/sOICaBDqoGM4Ue5ROP2YcipHCM/UG/lQO56Z27q7ZspboF1zEarrWI3tU21v6gEMhAIGcI5h0SkfydIERGKLRBFXqDW/lt3hh6zj2vnfg "Haskell – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 62 bytes
```
a=lambda n:n<1or a(n-1)*6**(a(n-1)//2in[0]+map(a,range(n)))//2
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9E2JzE3KSVRIc8qz8Ywv0ghUSNP11BTy0xLSwPC1Nc3ysyLNojVzk0s0EjUKUrMS0/VyNPUBEn8LyjKzCsBKjQ00tT8DwA "Python 2 – Try It Online")
Returns `True` for `a(0)`. 0-indexed.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~105~~ ~~103~~ ~~100~~ ~~95~~ 83 bytes
*-2 bytes thanks to agtoever*
*-12 bytes thanks to ArBo*
```
def f(n):
s=0,1
while len(s)<=n:t=s[-1]//2;s+=(t in s)*3*s[-1]or t,
return s[-1]
```
[Try it online!](https://tio.run/##Hcs9DoMwDEDhPafwaNNUNGSj5CSIoVKTEgkZ5Liqevrws356b/vrvLKv9R0TJGTqDZTwsM7Ab85LhCUyFhoC9xrKeHdT23bPcguokBkKNb65eBVQa0CifuXwk@ommRXHhJkgHUE@F3nxJ6KznaeJ6g4 "Python 3 – Try It Online")
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), ~~22~~ 20 bytes
```
2…@⟨:):3פḥ⌋,;D)+⟩ₓ)
```
[Try it online!](https://tio.run/##S0/MTPz/3@hRwzKHR/NXWGlaGR@efmjJwx1LH/V061i7aGo/mr/yUdNkTaAaSwsLy/8A "Gaia – Try It Online")
0-based index.
Credit to [Shaggy for the approach](https://codegolf.stackexchange.com/a/182861/67312)
```
2… | push [0 1]
@⟨ ⟩ₓ | do the following n times:
:): | dup the list L, take the last element e, and dup that
3פḥ⌋, | push [3*e floor(e/2)]
;D | take the asymmetric set difference [3*e floor(e/2)] - L
)+ | take the last element of the difference and add it to the end of L (end of loop)
) | finally, take the last element and output it
```
`;D`
[Answer]
# [Husk](https://github.com/barbuz/Husk), 18 bytes
```
!t¡(→S-o§e*3÷2→)ŀ2
```
[Try it online!](https://tio.run/##yygtzv7/X7Hk0EKNR22TgnXzDy1P1TI@vN0IyNM82mD0//9/QyNjEwA "Husk – Try It Online")
Not sure why I'm unable to compose the iteration function, but I was only able to get it working with parentheses.
+1 byte after fixing the list.
[Answer]
# [Lua](https://www.lua.org), 78 bytes
```
x,y=1,3 u={}for _=2,...do
u[x]=0
x,y=y,y//2
if u[y]then y=3*x end
end
print(x)
```
[Try it online!](https://tio.run/##yylN/P@/QqfS1lDHWKHUtro2Lb9IId7WSEdPTy8ln6s0uiLW1oALpKBSp1Jf34grM02hNLoytiQjNU@h0tZYq0IhNS@FC4QLijLzSjQqNP///28JBAA "Lua – Try It Online")
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 22 bytes
```
0⅛3?(:½⌊¾$ḟu=[½⌊|3*]:⅛
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=0%E2%85%9B3%3F%28%3A%C2%BD%E2%8C%8A%C2%BE%24%E1%B8%9Fu%3D%5B%C2%BD%E2%8C%8A%7C3*%5D%3A%E2%85%9B&inputs=5&header=&footer=)
1-indexed.
```
0⅛ # Push 0 to glob. arr.
3 # Push 3
?( # Iteration times
[ ] # If...
:½⌊ # Top of stack, halved and floored
¾$ḟu= # Is in global array?
½⌊ # Halved and floored
| # Else
3* # Tripled
:⅛ # And pushed to glob. arr.
```
]
|
[Question]
[
# Challenge
Factory workers are usually very hard-working. However, their work is now being commonly replaced with machines.
You have to write a program that takes a number as input. It will print out a factory of 10 workers 10 times. Every time, each worker has a `1/input` chance of being 'fired' and replaced by a machine.
## Input
An integer, coming from STDIN or a function call.
## Output
10 cases of the factory, each one with usually more workers fired.
# Output format - how to print a factory
A factory looks like this:
`|0000000000|` or `|0000011001|`
A pipe represents the walls, a 0 represents a worker, and a 1 represents a machine, so the first print of the factory will always be `|0000000000|`.
# Example
### Input: 10
### Output:
```
|0000000000| //always start off with this
|0000000010| //a 1/10 chance means that this worker lost his job
|0000010010|
|0010010010|
|1010010010|
|1010110010|
|1010110011|
|1010111011|
|1010111111|
|1110111111|
```
---
### Input: 5
### Output:
```
|0000000000| //always start here
|0000001001| //a 1/5 chance means that 2 workers got fired
|1000101001|
|1000101111|
|1101101111|
|1111111111| //after achieving all machinery, the machines continue to be printed
|1111111111|
|1111111111|
|1111111111|
|1111111111|
```
# NOTE
The number of workers fired is RANDOM - in my examples for `1/5 chance` there would always be 2 workers fired but your program has to do this randomly - sometimes 1 and sometimes 3 - they just have 1/5 chance of being fired.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) `-R`, ~~22~~ ~~21~~ ~~20~~ ~~19~~ 18 bytes
```
AÆP=®|!UöêAçTÃû|C
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=QcZQPa58IVX2w6pB51TD+3xD&input=OAotUg==)
---
## Explanation
```
AÆP=®|!UöêAçTÃû|C :Implicit input of integer U
A :10
Æ :Map the range [0,A)
P= : Assign to P (initially the empty string)
® : Map P
| : Bitwise OR with
! : The negation of
Uö : A random integer in the range [0,U)
à : End Map
ª : OR, for the first element when the above will still be an empty string (falsey)
Aç : Ten times repeat
T : Zero
à :End Map
û| :Centre pad each element with "|"
C : To length 12
:Implicitly join with newlines and output
```
[Answer]
# [R](https://www.r-project.org/), ~~92~~ 89 bytes
```
cat(t(cbind("|",apply("[<-"(matrix(runif(100)<1/scan(),10),1,,0),2,cummax),"|
")),sep="")
```
[Try it online!](https://tio.run/##DcTBCoAgDADQe5@x0waLNOhWX9JpWYGQImZQ4L8vD@9lVScFC7rNxx2hAktK14ewzj1gkJL9i/mJ/kRrDM12uJ1EJLamYW6P7J4Q5CWG2gER30daAEgn/QE "R – Try It Online")
Ungolfed:
```
m <- matrix(runif(100)<1/n,10,10) #10x10 matrix of TRUE with probability 1/n
#and FALSE with probability 1-1/n
m[1,] <- 0 #set first row to 0
m <- apply(m,2,cummax) #take the column cumulative maxima
m <- cbind("|",m,"|\n") #put "|" as the first and last columns
m <- t(m) #transpose m for the write function
cat(m,sep="") #print m to stdout, separated by ""
```
[Answer]
# JavaScript (ES6), 84 bytes
```
n=>[...s=2e9+''].map(j=>`|${s=s.replace(/./g,i=>i&1|Math.random()*n<!+j)}|`).join`
`
```
[Try it online!](https://tio.run/##BcHRCsIgFADQ9/4iiNSsuxb0EKR/0Be0QHFuKe4qOnrJvt3O8fqji8kurSeMo22TaCjkEwCKuNgbJ@QFi07UC6nq7ltEgWxT0MbSDrr56IR0@74@9PqGrHGMC2UHvG@5Z7@qGPjoUG1UMxFLDBZCnOlE@zPjZMABCZ/olbH2Bw "JavaScript (Node.js) – Try It Online")
---
# Recursive version, 88 bytes
```
n=>(g=k=>k?`|${s=s.replace(/./g,i=>i%5|Math.random()*n<(s!=k))}|
`+g(k>>3):'')(s=5e9+'')
```
[Try it online!](https://tio.run/##VchBDsIgEADAe39houmuVaoxHDQuvsA/lFBKEYQGGi/Wt6NXb5N5yJfMKtlp3ofY6zJQCSTAkCPhbt2yfmfKLOnJS6WhZa3ZWRJ2w5e7nEeWZOjjE3AbrpBX5BA/S9U1BpwQJ7zUNUImrs/NT0XFkKPXzEcDAxwPiNV/ccTyBQ "JavaScript (Node.js) – Try It Online")
### How?
We start with **k = s = '5000000000'**.
At each iteration:
* We coerce each character **i** of **s** to a number, compute **i modulo 5** -- so that the leading **5** is treated like a **0** -- and randomly perform a bitwise OR with **1** with the expected probability **1/n**, except on the first iteration.
* The counter **k** is right-shifted by 3 bits. We stop the recursion as soon as **k = 0**, which gives 10 iterations.
It is important to note that **5000000000** is slightly larger than a 32-bit integer, so it is implicitly converted to **5000000000 & 0xFFFFFFFF = 705032704** just before the first bitwise shift occurs. Hence the following steps:
```
step | k
------+-----------
0 | 705032704
1 | 88129088
2 | 11016136
3 | 1377017
4 | 172127
5 | 21515
6 | 2689
7 | 336
8 | 42
9 | 5
10 | 0
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 37 bytes
```
⎕{⎕←' '~⍨⍕'|'⍵'|'⋄×⍵+⍺=?10⍴⍺}⍣10⊢10⍴0
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1Hf1GogftQ2QV1Bve5R74pHvVPVa9Qf9W4Fkd0th6cDmdqPenfZ2hsaPOrdAmTVPupdDGR3LQILGPz/b2gAAA "APL (Dyalog Unicode) – Try It Online")
**How?**
`10⍴0` - start with 10 zeros.
`⎕←' '~⍨⍕'|'⍵'|'` - every time print the formatted array,
`?10⍴⍺` - generate a random array with values ranging `1` to input,
`⍺=` - element-wise comparison with the input. should mark `1` / input of the elements, giving each a `1` / input every time,
`⍵+` - add to the array,
`×` - signum. zero stays zero, anything greater than one comes back to one.
`⍣10` - repeat 10 times.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 30 bytes
```
.+
|¶10*$(*0¶
.-10+0\%0<@`\d
1
```
[Try it online!](https://tio.run/##K0otycxLNPz/X0@bq@bQNkMDLRUNLYND27j0dA0NtA1iVA1sHBJiUriAKgwNAA "Retina – Try It Online")
I'm having lots of fun with randomness in Retina^^
### Explanation
The first stage sets up the string we will be working with:
```
.+
|¶10*$(*0¶
```
It replaces the whole input with `|`, a newline, and then 10 lines containing as many `0`s as the input says. The first character on each line will represent a worker of the factory.
The following stage means:
```
. Disable automatic printing at the end of the program
-10+ Do the following exactly 10 times:
% For each line:
0< Print the first character, then
@`\d Pick a random digit and
1 (on the next line) replace it with a 1
0\ Then print the first character of the whole string
followed by a newline
```
The first line of the working string contains only a `|`, which will be the first character printed by every iteration of the loop (being the first character of the first line), and will be also printed at the end of every iteration (being the first character of the whole string). The replacement will never have any effect on this line because it doesn't contain any digit.
Each other line contains `n` digits, so there is a 1 in `n` chance to turn the first character of the line (which is the only meaningful one) into a `1`.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~82~~ ~~80~~ 69 bytes
```
param($x)($a=,0*10)|%{"|$(-join$a)|";$a=$a|%{$_-bor!(Random -ma $x)}}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQ6VCU0Ml0VbHQMvQQLNGtVqpRkVDNys/M08lUbNGyRoopZIIFFaJ103KL1LUCErMS8nPVdDNTVQA6qyt/f//vykA "PowerShell – Try It Online")
Takes input `$x`. Creates an array of all zeros, saves that into `$a` and then loops that many times. Conveniently, the factory is just as wide as it is iterations worth. Each iteration, we output our current factory with `"|$(-join$a)|"`, then loop through each element of `$a`.
Inside we're selecting the current element `$_` that has been `-b`inary-`or`ed with either `1` based on the `Random` chance based on input `$x`. For example, for input `10`, `Get-Random -max 10` will range between `0` and `9` and be `0` approximately 1/10th of the time. Thus with a `!(...)` wrapping the `Random`, we'll get a `1` approximately `1/input` amount of the time, and the other `1-1/input` amount of the time we'll get `$_`. Yes, this sometimes means that we're overwriting a `1` with another `1`, but that's fine.
That resulting array is then stored back into `$a` for the next go-round. All of the resulting strings are left on the pipeline, and the implicit `Write-Output` at program completion gives us newlines for free.
*-2 bytes thanks to Veskah.*
*-11 bytes thanks to ASCII-only.*
[Answer]
# [Perl 6](http://perl6.org/), 58 bytes
```
{say "|$_|" for 0 x 10,|[\~|] ([~] +(1>$_*rand)xx 10)xx 9}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/ujixUkGpRiW@RkkhLb9IwUChQsHQQKcmOqauJlZBI7ouVkFbw9BOJV6rKDEvRbMCJAsiLWv/g3X6KdgqGFkpWSukaRhpWivAxUwhYqaa1v8B "Perl 6 – Try It Online")
`+(1 > $_ * rand)` generates a single bit with the required frequency of `1`s. `xx 10` replicates that expression ten times to produce a single factory instance as a list of bits, and `[~]` joins that list into a single string. `xx 9` replicates that factory-string-generating expression nine times, and then `[\~|]` does a triangular reduction (which some other languages call a "scan") with the stringwise or operator `~|`, so that a worker fired in an earlier iteration remains fired in later ones.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~104~~ 103 bytes
```
from random import*
x='0'*10;i=input()
exec"print'|%s|'%''.join(x);x=[choice('1'+n*~-i)for n in x];"*10
```
[Try it online!](https://tio.run/##DcxBCsMgEADAe14hgbBqadFexZeUHIo1ZAvZla0FCyFftznNbcqvrkz33hfhTcmTXie4FZZqhxbBgfUuYEQq36rNkFtOYxGkCvv02WECuL0ZSTcTWnyklTFlDR4uZI8rmoVFkUJSbQ7jWfXu3R8 "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ẋ⁵ẋ€⁵¬1¦X€€=1o\j@€⁾||Y
```
A full program accepting the integer as a command line input and printing the output to STDOUT.
(As a monadic link it returns a list of characters and integers.)
**[Try it online!](https://tio.run/##y0rNyan8///hru5HjVtBZNMaIOPQGsNDyyJA7KY1tob5MVkOYPF9NTWR////NwUA "Jelly – Try It Online")**
### How?
Effectively decides at each stage if each worker (including any machines) lose their job (with a one in N chance), however machines are replaced by machines (using logical-OR).
```
ẋ⁵ẋ€⁵¬1¦X€€=1o\j@€⁾||Y - Main link: integer, N
⁵ - literal ten
ẋ - repeat -> [N,N,N,N,N,N,N,N,N,N]
⁵ - literal ten
ẋ€ - repeat €ach -> [[N,N,N,N,N,N,N,N,N,N],...,[N,N,N,N,N,N,N,N,N,N]]
¦ - sparse application...
1 - ...to indices: [1]
¬ - ...do: logical-NOT -> [[0,0,0,0,0,0,0,0,0,0],[N,N,...],...]
X€€ - random integer for €ach for €ach
- (0s stay as 0s; Ns become random integers in [1,N])
=1 - equals one? (vectorises)
o\ - cumulative reduce with logical-OR
⁾|| - literal list of characters = ['|','|']
j@€ - join with sw@pped arguments for €ach
Y - join with line feeds
- implicit print
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 26 bytes
```
'|'it10th&Yr=0lY(Y>48+y&Yc
```
[Try it online!](https://tio.run/##y00syfn/X71GPbPE0KAkQy2yyNYgJ1Ij0s7EQrtSLTL5/39TAA "MATL – Try It Online")
### (Long) explanation
Example stack contents are shown along the way. At each step, stack contents are shown bottom to top.
```
'|' % Push this character
% STACK: '|'
it % Take input. Duplicate
% STACK: '|'
5
5
10th % Push [10 10]
% STACK: '|'
5
5
[10 10]
&Yr % Random 10×10 matrix of integers from 1 to input number
% STACK: '|'
5
[4 5 4 4 5 5 2 1 2 3
3 4 3 3 1 4 4 3 1 5
5 1 4 5 4 4 5 2 3 2
3 4 5 2 1 3 2 5 3 4
4 1 2 2 4 1 1 5 1 1
4 5 3 1 5 3 5 2 4 1
2 1 4 3 3 1 3 5 3 5
1 2 2 1 2 2 4 3 5 3
4 5 4 1 2 2 5 3 2 4
4 1 2 5 5 5 4 3 5 1]
= % Is equal? Element-wise
% STACK: '|'
[0 1 0 0 1 1 0 0 0 0
0 0 0 0 0 0 0 0 0 1
1 0 0 1 0 0 1 0 0 0
0 0 1 0 0 0 0 1 0 0
0 0 0 0 0 0 0 1 0 0
0 1 0 0 1 0 1 0 0 0
0 0 0 0 0 0 0 1 0 1
0 0 0 0 0 0 0 0 1 0
0 1 0 0 0 0 1 0 0 0
0 0 0 1 1 1 0 0 1 0]
0lY( % Write 0 in the first row
% STACK: '|'
[0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 1
1 0 0 1 0 0 1 0 0 0
0 0 1 0 0 0 0 1 0 0
0 0 0 0 0 0 0 1 0 0
0 1 0 0 1 0 1 0 0 0
0 0 0 0 0 0 0 1 0 1
0 0 0 0 0 0 0 0 1 0
0 1 0 0 0 0 1 0 0 0
0 0 0 1 1 1 0 0 1 0]
Y> % Cumulative maximum down each column
% STACK: '|'
[0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 1
1 0 0 1 0 0 1 0 0 1
1 0 1 1 0 0 1 1 0 1
1 0 1 1 0 0 1 1 0 1
1 1 1 1 1 0 1 1 0 1
1 1 1 1 1 0 1 1 0 1
1 1 1 1 1 0 1 1 1 1
1 1 1 1 1 0 1 1 1 1
1 1 1 1 1 1 1 1 1 1]
48+ % Add 48, element-wise. This transforms each number into the
% ASCII code of its character representation
% STACK: '|'
[48 48 48 48 48 48 48 48 48 48
48 48 48 48 48 48 48 48 48 49
49 48 48 49 48 48 49 48 48 49
49 48 49 49 48 48 49 49 48 49
49 48 49 49 48 48 49 49 48 49
49 49 49 49 49 48 49 49 48 49
49 49 49 49 49 48 49 49 48 49
49 49 49 49 49 48 49 49 49 49
49 49 49 49 49 48 49 49 49 49
49 49 49 49 49 49 49 49 49 49]
y % Duplicate from below
% STACK: '|'
[48 48 48 48 48 48 48 48 48 48
48 48 48 48 48 48 48 48 48 49
49 48 48 49 48 48 49 48 48 49
49 48 49 49 48 48 49 49 48 49
49 48 49 49 48 48 49 49 48 49
49 49 49 49 49 48 49 49 48 49
49 49 49 49 49 48 49 49 48 49
49 49 49 49 49 48 49 49 49 49
49 49 49 49 49 48 49 49 49 49
49 49 49 49 49 49 49 49 49 49]
'|'
&Yc % Horizontally concatenate all stack contents as char arrays.
% 1-row arrays are implicitly replicated along first dimension
% STACK: ['|0000000000|'
'|0000000001|'
'|1001001001|'
'|1011001101|'
'|1011001101|'
'|1111101101|'
'|1111101101|'
'|1111101111|'
'|1111101111|'
'|1111111111|']
% Implicitly display
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 105 93 90 bytes
```
x=>w.map(a=>(`|${w=w.map(j=>j|Math.random()<1/x),w.join``}|
`)).join``,w=Array(10).fill(0)
```
[Try it online!](https://tio.run/##LcdBDsIgEADAu@/wsJtUbD27JD6gf2DTFoVQtqGN1Ihvx4PObTw/eR2SW7ZTlHGqlupOOquZF2DSYMrxnel3T9qXnreHShxHmQGv3XnHJisvLhrzKQeD@E@T6ZYSv6BrUVkXArRYB4mrhEkFuYOFC2L9Ag "JavaScript (Node.js) – Try It Online")
+2 bytes for putting the array inside the function, thanks to @Shaggy for pointing that out
```
(x,w=Array(10).fill(0))=>w.map(a=>(`|${w=w.map(j=>j|Math.random()<1/x),w.join``}|
`)).join``
```
[Try it online!](https://tio.run/##Zc5BCsIwEEDRfc/hYgZqbAV3TsADeIcMbaMJaVLSYirGs0dBN@Lyv9W3fOO5i2Zatj70Q9FUYK0TnWLkO7QNCm2cgwaRZBIjT8AkQeXNI9GnLUmbz7xcRWTfhxHw2O5WrJOwwXilnrlSiN8oXfBzcINw4QIa9ojVrxz@5P2A5QU "JavaScript (Node.js) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 110 106 bytes
-4 bytes from @ceilingcat
```
char l[]="|0000000000|",i,j;f(n){for(srand(time(i=0));i++<10;)for(j=!puts(l);j++<10;)rand()%n||(l[j]=49);}
```
[Try it online!](https://tio.run/##PYrLCoMwEADv@QorFHbRQoReyjZfIh5CNO2GGEu0J@O3pw/EOc6MuTyMydk8dSx826kyyYNU1lw7shBwtVOEOerQw8LjAKwkInFV3RtJ@ItOnV7vZQaP5Hb93/EcUgLfuk5db0hbHjUHQLGK4ouFRiKJLX8A "C (gcc) – Try It Online")
Iterates through a list of characters for each round of replacements.
Ungolfed:
```
f(n)
{
//start with a fresh factory
char l[]="|0000000000|";
//init rng
srand(time(0));
//print 11 lines
for(int i = 0; i < 11; i++)
{
//print current factory
puts(l);
//iterate through the workers. start at index 1 to skip the '|'
for(int j = 1; j < 11; j++)
{
//the expression (rand()%n) has n possible values in the range [0,n-1],
//so the value 0 has 1/n chance of being the result and thus the worker
//has 1/n chance of being replaced
if(rand()%n == 0)
{
l[j] = '1';
}
}
}
}
```
[Answer]
# SmileBASIC, 75 bytes
```
INPUT N
FOR J=0TO 9?"|";BIN$(F,10);"|
FOR I=0TO 9F=F OR!RND(N)<<I
NEXT
NEXT
```
[Answer]
# [Perl 5](https://www.perl.org/), 44 bytes
```
#!/usr/bin/perl -a
say"|$_|",s/0/rand"@F"<1|0/eg<0for(0 x10)x10
```
[Try it online!](https://tio.run/##K0gtyjH9/784sVKpRiW@RkmnWN9AvygxL0XJwU3JxrDGQD813cYgLb9Iw0ChwtBAE4j//zf9l19QkpmfV/xfN/G/rq@pnqGBngEA "Perl 5 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 22 bytes
```
TÅ0TFDJ'|.ø=sITи€L€ΩΘ~
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/5HCrQYibi5d6jd7hHbbFniEXdjxqWuMDxOdWnptR9/@/OQA "05AB1E – Try It Online")
There should be some more room for golfing.
* `TÅ0` — Push a list of 10 zeroes.
* `TF...` — Do this 10 times:
+ `DJ` — Duplicate the current item and join it.
+ `'|.ø=` — Surround it with two `|`s and print to STDOUT.
+ `ITи` — Repeat the input 10 times.
+ `€L€Ω` — And for each occurrence, get a random element of **[1 ... N]**. (There might be a built-in for this which I haven’t seen yet)
+ `Θ` — Push 05AB1E truthified™. For each, check if it equals **1**.
+ `s...~` — Logical OR the result by the current item.
[Answer]
# JavaScript, 83 bytes
```
f=(n,t=9,s=`|0000000000|
`)=>t?s+f(n,t-1,s.replace(/0/g,v=>+(Math.random()<1/n))):s
```
```
f=(n,t=9,s=`|0000000000|
`)=>t?s+f(n,t-1,s.replace(/0/g,v=>+(Math.random()<1/n))):s
```
```
<p><input id=i value=10 /><button id=t onclick="o.textContent=f(+i.value)">Run</button><p><pre id=o></pre>
```
[Answer]
# Java 10, ~~153~~ ~~152~~ 131 bytes
```
n->{for(int j=10,a[]=new int[j],i;j-->0;){var s="|";for(i=0;i<10;a[i++]|=Math.random()*n<1?1:0)s+=a[i];System.out.println(s+"|");}}
```
-18 bytes thanks to *@OlivierGrégoire*, and -3 more bytes by converting Java 8 to Java 10.
**Explanation:**
[Try it online.](https://tio.run/##rZIxb4MwEIX3/opTpEq4BGJX6lLH6dQxWTIihisYMCUmsh2iKOG3UwPJ1q2V7OFO7z69d3aNHUZ1/j1kDVoLW1T6@gSgtJOmwEzCbiwBulblkAW@D5pw3@r99cc6dCqDHWgQMOhocy1aM8lqwegSk1RoeR55SZ0uFa@jaEM5uXZowIrFbcEnvaBcrRnlmKgwTG9ii66KDeq8PQTkRa/ZB3unxIbCC1K@v1gnD3F7cvHReHSjAxt6FuF9P/DZ2PH01Xhjd3@T/YMPF@ydnyiTFMkcTMdZwCjhsFoBo8@QVah97LaAUjrnpVAoI3OQmFVg2pPOp7FfLExrmYFvM@/1ziv/ymP04fC/gDPus5Pm0moJZ9U0I@/OwsI/P7hKjrV1MxZGG48FkekL9MMP)
```
n->{ // Method with integer parameter and no return-type
for(int j=10,a[]=new int[j],i; // Create the array with 10 workers (0s)
j-->0;){ // Loop 10 times
var s="|"; // Start a String with a wall
for(i=0;i<10; // Loop `i` from 0 to 10 (exclusive)
a[i++] // After every iteration, change the current item to:
|= // If it's a 0:
Math.random()*n<1? // If the random value [0:1) is below 1/n
1 // Change the worker to a machine
: // Else:
0; // It remains a worker
// Else (it already is a machine)
// It remains a machine
s+=a[i]; // Append the current item to the String
System.out.println(s+"|");}} // Print the String, with a trailing wall and new-line
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~30~~ ~~29~~ 27 bytes
```
⊞υ×χ0Fχ⊞υ⭆§υ±¹‽⁺1×κ⊖θEυ⪫||ι
```
[Try it online!](https://tio.run/##NYy9CsIwFIX3PkXIdC9EaAanToKLQiWoLxDaaxtsEk1Scei7x1To2c7f1406dF5POas5jjALdjeWIshaMF5zxKZ6@MCKR7YtbikYN7T6BYd0cj191/BCg04EElGwq3a9t6CmOQKXfGM@BTtSF8iSS9TDG/9qKlVwCVZe4Zy9ccCXpbzM2ua8z7vP9AM "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞υ×χ0
```
Push an string of 10 `0`s to the empty list `u`.
```
Fχ
```
Repeat the next command 10 times.
```
⊞υ⭆§υ±¹‽⁺1×κ⊖θ
```
For each character of the last string, repeat it `n-1` times, add a `1`, and pick a random character from the string. This gives a `1/n` chance of changing the character to a `1`. The result is pushed to `u`.
```
Eυ⪫||ι
```
Map over the list of strings, surrounding each with `|`, then implicitly print each on its own line.
[Answer]
# [Python 3](https://docs.python.org/3/), 132 bytes
```
from random import*
w,p,c=[0]*10,'|',1/int(input())
for _ in w:print(p+''.join(map(str,w))+p);w=list(map(lambda x:x|(random()<c),w))
```
[Try it online!](https://tio.run/##JY1BCsIwEEX3PUV2mWmDtoibak8iIrGlGGkmQzqSCr17tLr68N6Dz295BDrkPMbgVbQ0fMd5DlHKIhk2fXepr2VTG71q0@wdCTjilwBiMYaobsqRSi3HzXCl9e4ZHIG3DLNEkxArxlPqJjfLj07W3werlnZZ4f8HeO5xK3M@fgA "Python 3 – Try It Online")
[Answer]
# APL+WIN, ~~30 40~~ 35 bytes
Missed the bit about no spaces ;( - fixed & thanks to Uriel for -3 bytes
Prompts for screen input of number
```
'|',(⍕0⍪×+⍀n=?9 10⍴n←⎕)[;2×⍳10],'|'
```
Explanation similar to that of Uriel:
```
?9 10⍴n create a 9x10 matrix of numbers selected at random between 1 and number
×+⍀n= compare elements of matrix to number, cumulatively sum columns and signum
[;2×⍳10] take non-space columns
'|',(⍕0⍪.......,'|' concatenate a row of zeros and front and back columns of |
```
[Answer]
## VBA, 144 bytes
```
Sub f(i)
Dim w(9) As Long
For x = 0 To 9
s = "|"
For y = 0 To 9
s = s & w(y)
If i * Rnd() < 1 Then w(y) = 1
Next
Debug.Print s; "|"
Next
End Sub
```
Indented for easier reading:
```
Sub f(i)
Dim w(9) As Long
For x = 0 To 9
s = "|"
For y = 0 To 9
s = s & w(y)
If i * Rnd() < 1 Then w(y) = 1
Next
Debug.Print s; "|"
Next
End Sub
```
Takes advantage of 2 points: VBA Arrays will default to Base 0 (so `w(9)` is the same as `w(0 to 9)`) and creating the Array as a Long will automatically initialise it to 0.
(Annoyingly, **20** bytes are auto-formatting that VBA adds in but not actually required - 19 spaces and one semi-colon)
[Answer]
I don't see answer for Ruby yet, so:
# [Ruby](https://www.ruby-lang.org/), 92 bytes
```
n=gets.to_i
z='0'*x=10
x.times do
puts'|'+z+'|'
x.times do|s|
z[s]='1' if rand(n)==0
end
end
```
[Try it online!](https://tio.run/##KypNqvz/P882PbWkWK8kPz6Tq8pW3UBdq8LW0ICrQq8kMze1WCEln6ugtKRYvUZdu0obSCJJ1BTXcFVFF8faqhuqK2SmKRQl5qVo5Gna2hpwpealgPD//4YGAA "Ruby – Try It Online")
[Answer]
# Ruby, 67 bytes
```
->n{f=[0]*10;10.times{p"|#{f.join}|";f.map!{|l|rand>(1.0/n)?l:?1}}}
```
I think I've cheated a few things here. First of all, this function prints the output with quotes around each line, e.g.:
```
pry(main)> ->n{f=[0]*10;10.times{p"|#{f.join}|";f.map!{|l|rand>(1.0/n)?l:?1}}}[5]
"|0000000000|"
"|0100100000|"
"|0100100000|"
"|0100100000|"
"|0100100100|"
"|0100110100|"
"|0101110100|"
"|0111110100|"
"|1111110110|"
"|1111110110|"
=> 10
```
If this is unacceptable (given that this is [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'"), that is probably the case), here is a solution that prints without quotes for **70 bytes**:
```
->n{f=[0]*10;10.times{puts"|#{f.join}|";f.map!{|l|rand>(1.0/n)?l:?1}}}
```
### Explanation:
```
->n{ } # defines anonymous lambda
f=[0]*10; # initializes f to [0,0,0,...] (10)
10.times{ } # main loop
p"|#{f.join}|"; # joins f and prints | before and after
f.map!{|l| } # maps each element of f
rand>(1.0/n)? : # if rand is greater than 1.0/n
l ?1 # keep current element or replace with '1'
```
[Answer]
# PHP, ~~71~~ 70 bytes
[merging](https://codegolf.stackexchange.com/a/158096/55735) [loops](https://codegolf.stackexchange.com/a/174268/55735) saved 5 bytes (again):
```
for(;$k<91;$v|=!rand(0,$argn-1)<<$k++%10)$k%10||printf("|%010b|
",$v);
```
Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/ebe434c2fa884c3697e151769d1178c1d547d0b5).
---
edit 1: fixed format and first output (no change in byte count thanks to additional golfing)
edit 2: Golfed one more byte: After the last printing, there´s no more need for firing anyone.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 131 bytes
```
n=>{var r=new Random();var a=new int[10];for(int i=0;i<100;a[i%10]|=r.Next(n)<1?1:0)if(i++%10<1)Write("|"+string.Concat(a)+"|\n");}
```
Hey, at least I tied with Java.
[Try it online!](https://tio.run/##VY5BS8QwEIXv@RWhsGyGriURvDTtioiHBVFZFzzseghpqkN1uqRZFdr@9pruSW8z73u892x3YTucbmzAlgqksK7Licp1/2U89yW5b741VLWfAvQsmbMUfXslX3XdehFvjqXUWCgptdnjIpKh9NmD@wmCoFDXKpeAtcA0jaxQ8OIxOJEMSdoFj/SW3bZkTRAG0mQ4UAJ6nDSL4c7YdzHXNrGSbyjbOlPt2juqBGTPxw8MYnmgJQDr2Tn0HikGb@h4CjznvRyTVQP6L3s8hQjz2MHqeXv2ZHznRAP/bPEZJyXZFbtk6hc "C# (Visual C# Interactive Compiler) – Try It Online")
]
|
[Question]
[
## Introduction
The lexicographical permutations of a list with *n* elements can be numbered from 0 to *n*! - 1. For example, the 3! = 6 permutations of `(1,2,3)` would be `(1,2,3)`, `(1,3,2)`, `(2,1,3)`, `(2,3,1)`, `(3,1,2)`, `(3,2,1)`.
When a permutation is applied to a list, its elements are ordered in the same order as the numbers in the permutation. For example, applying the permutation `(2,3,1)` to `l = (a,b,c)` yields `(l[2],l[3],l[1]) = (b,c,a)`.
The inverse of a permutation is defined as the permutation that reverses this operation, i.e. applying a permutation and then its inverse (or vice versa) does not modify the array. For example, the inverse of `(2,3,1)` is `(3,1,2)`, since applying that to `(b,c,a)` yields `(a,b,c)`.
Also, a permutation's inverse applied to the permutation itself yields the integers 1…*n*. For example, applying `(3,1,2)` to `(2,3,1)` yields `(1,2,3)`.
We now define the function *revind*(*x*) as the index of the inverse permutation of the permutation with index *x*. (This is [A056019](https://oeis.org/A056019), if you're interested.)
Since a permutation with index *i* only modifies the last *k* items of the list [iff](https://en.wikipedia.org/wiki/Iff) 0 ≤ *i* < *k*!, we can add any number of elements to the start of the list without affecting *revind*(*i*). Therefore the length of the list does not affect the result.
## Challenge
Your task is to implement *revind*(*x*). You will write a full program or function that takes a single nonnegative integer *x* as input/argument and outputs/returns the result as a single nonnegative integer.
The input and output may be 0-indexed or 1-indexed, but this must be consistent between them.
Builtins that generate permutations by index, return the index of a permutation or find the inverse permutation are banned. (Builtins that generate all permutations or the next permutation are allowed.)
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
## Examples
The examples below are 0-indexed.
```
Input Output
0 0
1 1
2 2
3 4
4 3
5 5
6 6
13 10
42 51
100 41
1000 3628
2000 3974
10000 30593
100000 303016
```
## Reference implementation (Python 3)
```
def revind(n):
from math import factorial
from itertools import permutations, count
l = next(filter(lambda x: factorial(x) > n, count(1)))
pms = list(permutations(range(l)))
return [k for k in range(len(pms)) if tuple(pms[n][i] for i in pms[k]) == pms[0]][0]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ịŒ!⁺iR
```
I/O uses 1-based indexing. *Very* slow and memory-hungry.
### Verification
As long as the input does not exceed **8! = 40320**, it is sufficient to consider all permutations of the array **[1, …, 8]**. For the last test case, the permutations of **[1, …, 9]** suffice.
With slightly modified code that only considers the permutations of the first **8** or **9** positive integers, you can [Try it online!](http://jelly.tryitonline.net/#code=4buLOcWSIcKkxZIhaTlSwqQ&input=&args=MTAwMDAx) or [verify all remaining test cases](http://jelly.tryitonline.net/#code=4buLOMWSIcKkxZIhaThSwqQKxbzDh-KCrEc&input=&args=MSwgMiwgMywgNCwgNSwgNiwgNywgMTQsIDQzLCAxMDEsIDEwMDEsIDIwMDEsIDEwMDAx).
### How it works
```
ịŒ!⁺iR Main link. Argument: n
Œ! Yield all permutations of [1, ..., n].
ị At-index; retrieve the n-th permutation.
⁺ Duplicate the Œ! atom, generating all permutations of the n-th permutation.
R Range; yield [1, ..., n].
i Index; find the index of [1, ..., n] in the generated 2D array.
```
## Alternate approach, 6 bytes (invalid)
```
Œ!Ụ€Ụi
```
It's just as long and it uses the forbidden *grade up* atom `Ụ`, but it's (arguably) more idiomatic.
By prepending **8** (or **9** for the last test case), we can actually [Try it online!](http://jelly.tryitonline.net/#code=OcWSIeG7pOKCrOG7pGk&input=&args=MTAwMDAx)
### How it works
```
Œ!Ụ€Ụi Main link. Argument: n
Œ! Yield all permutations of [1, ..., n].
Ụ€ Grade up each; sort the indices of each permutation by the corresponding
values. For a permutation of [1, ..., n], this inverts the permutation.
Ụ Grade up; sort [1, ..., n!] by the corresponding inverted permutations
(lexicographical order).
i Index; yield the 1-based index of n, which corresponds to the inverse of
the n-th permutation.
```
[Answer]
# Mathematica, 74 bytes
```
Max@k[i,Flatten@Outer[i=Permutations[j=Range@#];k=Position,{i[[#]]},j,1]]&
```
Uses 1-indexing. Very inefficient. (uses ~11GB of memory when the input is `11`)
# Explanation
```
j=Range@#
```
Generate a list from 1 to N. Store that in `j`.
```
i=Permutations[...]
```
Find all permutations of `j`. Store that in `i`.
```
k=Position
```
Store the `Position` function in `k`. (to reduce byte-count when using `Position` again)
```
Flatten@Outer[...,{i[[#]]},j,1]
```
Find the inverse permutation of the N-th permutation.
```
Max@k[i,...]
```
Find the `k` (`Position`) of the inverse permutation in `i` (all permutations)
# Using built-ins, ~~46~~ 43 bytes
```
a[(a=Ordering)/@Permutations@Range@#][[#]]&
```
1-indexed.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~14~~ 13 bytes
~~Very memory inefficient.~~ Now even more memory inefficient (but 1 byte shorter).
0-based range.
Uses [CP-1252](http://www.cp1252.com) encoding.
```
ƒ¹ÝœD¹èNkˆ}¯k
```
[Try it online!](http://05ab1e.tryitonline.net/#code=xpLCucOdxZNEwrnDqE5ry4Z9wq9r&input=NA)
or as a [Modified test suite](http://05ab1e.tryitonline.net/#code=fHZ5w53Fk0R5w6h5w53igJrDuHvDuDHDqGss&input=MAoxCjIKMwo0CjUKNgo3Cjg)
**Explanation**
```
ƒ # for N in range[0 .. x]
¹ÝœD # generate 2 copies of all permutations of range[0 .. x]
¹è # get permutation at index x
Nkˆ # store index of N in that permutation in global list
} # end loop
¯k # get index of global list (inverse) in list of permutations
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), 15 bytes
```
:Y@tGY)Z)G:=!Af
```
Input and output are 1-based.
Similar to [@MartinEnder's CJam answer](https://codegolf.stackexchange.com/a/95841/36398), but finds the inverse permutation by composing all possible permutations with that specified by the input, and seeing which has become the identity permutation.
It runs out of memory in the online compiler for input `10`.
[Try it online!](http://matl.tryitonline.net/#code=OllAdEdZKVopRzo9IUFm&input=Nw)
### Explanation
```
: % Implicitly input N. Push range [1 2 ... N]
Y@ % Matrix witll all permutations of size N. Each permutation is a row
tGY) % Duplicate. Get the N-th row
Z) % Use that as a column index into the matrix of all permutations
G:= % Compare each row with [1 2 ... N]
!Af % Find index of the row that matches. Implicitly display
```
[Answer]
# Pyth, 12 bytes
```
xJ.phQxL@JQh
```
[Test suite](https://pyth.herokuapp.com/?code=xJ.phQxL%40JQh&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A4%0A5%0A6%0A7&debug=0)
0 indexed.
Explanation:
```
xJ.phQxL@JQh
xJ.phQxL@JQhQ Implicit variable introduction
Q = eval(input())
.phQ Form all permutations of range(Q+1), namely [0, 1, .. Q]
J Save to J.
@JQ Take the Qth element of J.
xL hQ Map all elements of [0, 1, ..., Q] to their index in above
x Find the index in J of the above.
```
[Answer]
## [CJam](http://sourceforge.net/projects/cjam/), 16 bytes
```
ri_)e!_@=_$\f#a#
```
Indices are 0-based.
[Try it online!](http://cjam.tryitonline.net/#code=cmlfKWUhX0A9XyRcZiNhIw&input=OA&debug=on)
I doesn't get a lot more inefficient than this... runs out of memory with Java's default settings for inputs greater than `8` (but works in principle for arbitrary inputs given a sufficient number of universes of time and memory).
### Explanation
```
ri e# Read input and convert to integer N.
_)e! e# Duplicate N, get all permutations of [0 1 ... N].
_@= e# Duplicate permutations, get the Nth permutation.
_$ e# Duplicate and sort to get the sorted range [0 1 ... N].
\f# e# For each of these values, get its index in the Nth permutation.
e# This inverts the permutation.
a# e# Find the index of this new permutation in the list of all permutations.
```
[Answer]
## [GAP](http://gap-system.org), 108 bytes
```
h:=l->n->PositionProperty(l,p->l[n]*p=());
f:=n->h(Set(SymmetricGroup(First([1..n],k->Factorial(k)>=n))))(n);
```
1-indexed. Newlines not counted, they are not needed. I don't really have to assign the final function to a name, but ...
`h` is a curried function taking a list of permutations and an index into that list and returning the index of the inverse permuation. Without restrictions, I'd just do `Position(l,l[n]^-1)`. `f` calls that function with the sorted permutations of a big enough symmetric group and the given `n`.
I could just write `SymmetricGroup(n)`, then the function could be computed for values up to 9. Since there are already much smaller solutions, I prefer to be able to do this:
```
gap> f(100001);
303017
```
A really efficient 0-indexed solution that works for arguments below 99! (and can be made to work for arguments below 999! at the cost of one byte) is this one:
```
f:=function(n)
local m,l,p,i,g;
m:=First([1..99],k->Factorial(k)>n);
g:=List([m-1,m-2..0],Factorial);
l:=[1..m];
p:=[];
for i in g do
Add(p,Remove(l,QuoInt(n,i)+1));
n:=n mod i;
od;
return Sum(ListN(List([1..m],i->Number([1..Position(p,i)],j->p[j]>i)),g,\*));
end;
```
After deleting whitespace, this has 255 bytes.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~14 13~~ 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-4 bytes thanks to @Dennis (which he golfed further using the quick `⁺` in [his answer](https://codegolf.stackexchange.com/a/95920/53748))
```
Œ!ịịŒ!$iR
```
Another very slow implementation.
1-based indexing employed here, so expected results are:
```
input: 1 2 3 4 5 6 7 8 9 10 11
output: 1 2 3 5 4 6 7 8 13 19 9
```
No point in even putting up an online IDE link, as TIO kills at an input of `10`. Local results (last is very slow and required a tonne of memory!):
```
C:\Jelly\jelly-master>python jelly -fu D:\jelly_scripts\revPerm.txt 1
1
C:\Jelly\jelly-master>python jelly -fu D:\jelly_scripts\revPerm.txt 2
2
C:\Jelly\jelly-master>python jelly -fu D:\jelly_scripts\revPerm.txt 3
3
C:\Jelly\jelly-master>python jelly -fu D:\jelly_scripts\revPerm.txt 4
5
C:\Jelly\jelly-master>python jelly -fu D:\jelly_scripts\revPerm.txt 5
4
C:\Jelly\jelly-master>python jelly -fu D:\jelly_scripts\revPerm.txt 6
6
C:\Jelly\jelly-master>python jelly -fu D:\jelly_scripts\revPerm.txt 7
7
C:\Jelly\jelly-master>python jelly -fu D:\jelly_scripts\revPerm.txt 8
8
C:\Jelly\jelly-master>python jelly -fu D:\jelly_scripts\revPerm.txt 9
13
C:\Jelly\jelly-master>python jelly -fu D:\jelly_scripts\revPerm.txt 10
19
C:\Jelly\jelly-master>python jelly -fu D:\jelly_scripts\revPerm.txt 11
9
```
### How?
```
Œ!ịịŒ!$iR - Main link 1: n
$ - last two links as a monad
Œ! - permutations of implicit range [1,2,3,...,n]
ị - value at index n (the nth permutation)
Œ! - permutations of implicit range [1,2,3,...,n]
ị - value at index (the indexes of the permuted values in the nth permutation)
i - index of
R - range [1,2,3,...,n]
```
Note: no need to sort the permutations as we are using the same ordering for both finding the permutation and and it's inverse.
[Answer]
## JavaScript (ES6), ~~163~~ ~~120~~ 110 bytes
```
f=(n,a=[],i=0,r=0,[j,...b]=a)=>n?a.splice(n%-~i,0,i)|f(n/++i|0,a,i):i?f(n,b,i-1,b.reduce((r,k)=>r+=k>j,r*i)):r
```
```
<input type=number min=0 oninput=o.textContent=f(+this.value)><pre id=o>
```
0-indexed. Works by converting the index to a permutation, inverting it, then converting back to an index. Edit: Saved about 25% by making `f` invert and reverse the permutation, then making `g` convert the reversed permutation back to an index. Saved a further 10 bytes by combining the two recursive calls into a single function. Ungolfed:
```
function index(n) {
var a = [0];
for (var i = 1; n = Math.floor(n / i); i++) {
var j = i - n % (i + 1);
for (var k = 0; k < i; k++) {
if (a[k] > j) a[k]++;
}
a.push(j);
}
a = [...a.keys()].map(k => a.indexOf(k));
while (i) {
n *= i--;
j = a.pop();
for (k = 0; k < i; k++) {
if (a[k] > j) n++;
}
}
return n;
}
```
[Answer]
# J, ~~55~~ 50 bytes
```
g=:/:~i.@#
[:(#\.#.+/@(<{.)\.)@g(-i.)@>:g@g@,/@#:]
```
Based on the J essay on [Permutation Index](http://code.jsoftware.com/wiki/Essays/Permutation_Index).
This code only requires memory on the order of `n` but uses more time since it sorts the list `n` times and searches it `n` times for each index.
Using the builtin `/:` which is able to find the grade of a list and the inverse of a permutation, there is a 42 byte solution that is more efficient.
```
[:(#\.#.+/@(<{.)\.)@/:(-i.)@>:/:@/:@,/@#:]
```
This version only requires 44 seconds to compute the last test case when compared against the other which requires 105 seconds.
## Usage
```
g =: /:~i.@#
f =: [:(#\.#.+/@(<{.)\.)@g(-i.)@>:g@g@,/@#:]
(,.f"0) 0 1 2 3 4 5 6 13 42 100 1000 2000 10000
0 0
1 1
2 2
3 4
4 3
5 5
6 6
13 10
42 51
100 41
1000 3628
2000 3974
10000 30593
timex 'r =: f 100000'
105.787
r
303016
```
[Answer]
# Python 2, ~~116~~ 114 bytes
```
from itertools import*
def f(n):r=range(n+1);l=list(permutations(r));print l.index(tuple(l[n].index(v)for v in r))
```
**[repl.it](https://repl.it/Dtwu)**
0-based. Slow and memory hungry but short on bytes.
---
### Using no permutation functions; both memory and time efficient. ~~289~~ 285 bytes
-4 bytes thanks to @Christian Sievers (full permutation already formed)
```
h=lambda n,v=1,x=1:v and(n>=v and h(n,v*x,x+1)or(v,x-1))or n and h(n-1,0,n*x)or x
i=lambda p,j=0,r=0:j<len(p)and i(p,j+1,r+sum(k<p[j]for k in p[j+1:])*h(len(p)-j-1,0))or r
def f(n):t,x=h(n);g=range(x);o=g[:];r=[];exec"t/=x;x-=1;r+=[o.pop(n/t)];n%=t;"*x;return i([r.index(v)for v in g])
```
I know it's code golf but I think @Pietu1998 is interested in efficient implementations also.
See it in action at **[repl.it](https://repl.it/DtlA)**
While this uses more bytes than the reference implementation comparing for `n=5000000`:
```
ref: 6GB 148s
this: 200KB <1ms
```
`f` is the reverse index function.
`f` first gets the next factorial above `n`, `t`, and the integer whose factorial that is, `x` by calling `h(n)`, and sets `g=range(x)`, the items that will make up the permutation, `o=g[:]`, and the permutation holder, `r=[]`
Next it constructs the permutation at index `n` by `pop`ing the indexes of the factorial base representation of `n` in turn from the items, `o`, and appending them to `r`. The factorial base representation is found by div and mod of `n` with `t` where `t` is div'd by `x` and `x` decrements down to `1`.
Finally it finds the index of the reverse permutation by calling `i` with the reverse permutation, `[r.index(v)for v in g]`
`h` is a dual-purpose function for either calculating a factorial of a non-negative integer or calculating both the next factorial above a non-negative integer and the integer that makes that factorial.
In it's default state `v=1` and it does the latter by multiplying `v` by `x` (also initially `1`) and incrementing `x` until `n` is at least as big, then it returns `v` and `x-1` in a tuple.
To calculate `n!` one calls `h(n,0)` which multiples `x` (initially `1`) by `n` and decrements `n` until `n` is `0` when it returns `x`.
`i` provides the lexicographical index of a permutation, `p`, of the items `[0,1,...n]` by adding up the products of the factorial of the factorial base of each index, `h(len(p)-j-1,0)`, and how many items to the right of the index are less than the value at that index, `sum(k<p[j]for k in p[j+1:])`.
[Answer]
# Python 2, ~~130~~ 129 bytes
```
p=lambda x,k,j=1:x[j:]and p(x,k/j,j+1)+[x.pop(k%j)]
n=input();r=range(n+2);k=0
while[p(r*1,n)[i]for i in p(r*1,k)]>r:k+=1
print k
```
[Answer]
# [Actually](http://github.com/Mego/Seriously), ~~18~~ 11 bytes
This answer uses the algorithm in [Dennis' Jelly answer](https://codegolf.stackexchange.com/a/95920/47581) but is 0-indexed. Golfing suggestions welcome! [Try it online!](http://actually.tryitonline.net/#code=NOKVnnI7KeKVqEXilajimYIjw60&input=NA)
```
4╞r;)╨E╨♂#í
```
**Ungolfing**
```
Implicit input n.
4╞ Push 4 duplicates of n. Stack: n, n, n, n
r;) Push the range [0...n], and move a duplicate of that range to BOS for later.
╨E Push the n-length permutations of [0...n] and get perm_list[n].
Stack: perm_list[n], n, [0...n]
╨ Push the n-length permutations of perm_list[n].
♂# Convert every "list" in the zip to an actual list.
Stack: perm(perm_list[n]), [0...n]
í Get the index of [0...n] in the list of permutations of perm_list[n].
Implicit return.
```
]
|
[Question]
[
Mr Jones wants to do a round-trip on his bicycle. He wants to visit several cities in arbitrary order, but his route must not cross it self, since he hates to be at the same place twice in his holidays. As he really loves cycling, the length of his route is completely irrelevant, but he dislikes to drive around the landscape without a target. The route he likes is from on city in a straight line to another, without any detour.
As Mr Jones is a passionated code golfer, he wants you to find a program, that plans a round trip for him, given a set of cities. The input has the form `A (B|C)`. `A` is a city's name, `B` and `C` are its coordinates. You may assume, that the coordinate are positive and less than 1000. The data sets for the cities are line-separated. Here is an example, of how an example input might look like:
```
SomeTown (1|10)
ACity (3|4)
Wherever (7|7)
Home (5|1)
```
Mr Jones isn't pedantic, he just wants to have a useful program. Thus, you may decide by your self how the output is looking like, as long as it mets these criteria:
* The output is a map of the cities, with the route drawn between them. If anything is correct, the route shouldn't overlap itself and should end where it started
* The coordinates are like in usual programming: (1|1) is in the NW corner. Add kind of a ruler to the maps border, to ease reading it
* The cities names have to be written down on the map, but feel free to use abbreviations which is explained somewhere else on the map
* The map can be both ASCII-art or an image
* Keep the output readable
An output might look like this:
```
1234567
1 D
2 * *
3 * *
4 B *
5 * *
6 * *
7 * C
8* **
9* *
10A**
A: SomeTown
B: ACity
C: Wherever
D: Home
```
The program with the smallest char count wins. I don't count parameters to the compiler / interpreter, if they are needed for compiling, but please don't abuse this rule. Usual code golf rules apply.
Here is another testcase. You output doesn't have to match mine, nor do you have to choose the same path as me. The output is drawn by hand and shows a possible output. Input:
```
home (5|7)
supermarket (13|12)
park (15|5)
new plaza (9|16)
friend's house (20|11)
old castle (14|21)
riverside (1|20)
beach (10|1)
cinema (21|18)
forest (23|7)
little island (21|1)
museum of code-golf (6|25)
airport (18|25)
tea-shop (24|14)
restaurant (24|22)
great bridge (3|12)
SO building (25|9)
```
And this is an example output:
```
1111111111222222
1234567890123456789012345
1 H* *K
2 * * * *
3 * * * *
4 * * ** *
5 * C *
6 * *
7 A J
8 * *
9 * Q
10 * *
11 * ***E *
12 P B*** * *
13 * * * *
14 * * * N
15 * * * *
16 * D * *
17 * * * *
18* * I *
19* * * *
20G * * *
21 * F * *
22 * ** * O
23 * ** * **
24 * ** * *
25 L** M**
A: home
B: supermarket
C: park
D: new plaza
E: friend's house
F: old castle
G: riverside
H: beach
I: cinema
J: forest
K: little island
L: museum of code-golf
M: airport
N: tea-shop
O: restaurant
P: great bridge
Q: SO building
```
*I am not an English native speaker. Feel free to correct my language and grammar, if necessary.*
[Answer]
## Haskell, 633 characters
```
import List
c n=n>>=(++" ").show.(*3)
(x&y)l="<text x='"++c[x]++"' y='"++c[y]++"'>"++l++"</text>"
f%p=[a-1,b+2,(a+b)/2]where n=map(f.fst)p;a=minimum n;b=maximum n
s p=concat["<svg xmlns='http://www.w3.org/2000/svg' viewBox='",c[i,m-1,j,n],"'><polygon fill='none' stroke='#c8c' points='",c$snd=<<(sort$map a p),"'/><g font-size='1' fill='#bbb'>",(\x->(x&m$show x)++(i&x$show x))=<<[floor(i`min`m)..ceiling(j`max`n)],"</g><g font-size='2'>",snd=<<p,"</g></svg>"]where a((x,y),_)=(atan2(x-q)(y-r),[x,y]);[i,j,q,m,n,r]=fst%p++snd%p
w(l,s)=((x,y),(x&y)l)where(x,r)=v s;(y,_)=v r
v=head.reads.tail
main=interact$s.map(w.break(=='(')).lines
```
Rather longish for code-golf, but produces a lovely SVG map:

Or, if your browser can't handle SVG, a PNG of that image:

---
* Edit: (648 -> 633) in-line coordinate drawing, and possibly draw more than needed, letting them be clipped by the `viewBox`; also a few golf-tricks here and there.
[Answer]
## Python, 516 476 bytes
```
#!/usr/bin/python
#coding=utf-8
import sys
H=V=0
T=[]
k=65
for L in sys.stdin.readlines():
i,j,K=L.find('('),L.find('|'),'%c'%k
n,h,v=L[:i-1],int(L[i+1:j]),int(L[j+1:-2])
H=max(H,h);V=max(V,v);T+=[(K,h,v)];k+=1;print K+':',n
V=V+1&~1
for s in zip(*['%3d'%(i+1)for i in range(H)]):print' '+''.join(s)
C=H*V*[u'─']
C[0::H]=u'│'*V
C[1::H]=V/2*u'└┌'
C[H-1::H]=V/2*u'┐┘'
C[0:2]=u'┌─'
C[-H:-H+2]=u'└─'
for K,h,v in T:C[v*H-H+h-1]=K
for i in range(V):print'%3d'%(i+1)+''.join(C[i*H:i*H+H])
```
(Note: I didn't include the first two lines in the byte count, I consider them "interpreter parameters". But I did charge myself for the utf-8 length of the program in bytes.)
On your second example I produce:
```
A: home
B: supermarket
C: park
D: new plaza
E: friend's house
F: old castle
G: riverside
H: beach
I: cinema
J: forest
K: little island
L: museum of code-golf
M: airport
N: tea-shop
O: restaurant
P: great bridge
Q: SO building
11111111112222222222333
12345678901234567890123456789012
1┌────────H──────────K──────────┐
2│┌─────────────────────────────┘
3│└─────────────────────────────┐
4│┌─────────────────────────────┘
5│└────────────C────────────────┐
6│┌─────────────────────────────┘
7│└──A──────────────────────────J
8│┌─────────────────────────────┘
9│└──────────────────────Q──────┐
10│┌─────────────────────────────┘
11│└─────────────────E───────────┐
12│┌P─────────B──────────────────┘
13│└─────────────────────────────┐
14│┌─────────────────────N───────┘
15│└─────────────────────────────┐
16│┌──────D──────────────────────┘
17│└─────────────────────────────┐
18│┌──────────────────I──────────┘
19│└─────────────────────────────┐
20G┌─────────────────────────────┘
21│└───────────F─────────────────┐
22│┌─────────────────────O───────┘
23│└─────────────────────────────┐
24│┌─────────────────────────────┘
25│└───L───────────M─────────────┐
26└──────────────────────────────┘
```
Yay, Unicode glyphs!
[Answer]
# J, 357 288
```
m=:>:>./c=:>1{"1 p=:([:<`([:<1-~[:".;._1'|',}:);._1'(',]);._2(1!:1)3
'n c'=:|:o=:p/:12 o.j./"1 c-"1(+/%#)c
C=:<"1 c
L=:u:65+i.#o
g=:<"1;c([:<@|:0.5<.@+[+>@])"1(-~/"2(<@:*]%~i.@>:@])"0([:>./|@-/)"2)>C,"0(1|.C)
echo(u:48+10|i.>:0{m),|:(u:48+10|>:i.1{m),L C}'*'g}m$' '
echo' ',L,.':',.' ',.n
```
This is just a quick squeezing of the original (see below). A lot of golfing is probably still possible to eliminate lots of useless rank manipulation and boxing.
Only caveat: Ruler is just the last digit unlike example output.
**Edit:** Bug fix - Cities had wrong labels (and were not in alpha order on map).
**Edit 2:** Removed all sorts of horseplay and tomfoolery for a savings of 69 characters.
Output (Verbatim, from test script):
```
First example:
01234567
1 B
2 **
3 * *
4 A *
5 * *
6 * *
7 * C
8 * **
9* **
0D*
A: ACity
B: Home
C: Wherever
D: SomeTown
Second example:
012345678901234567890123456789012
1 D F
2 * * ***
3 * ** * *
4 * * ** *
5 * E *
6 * *
7 C * *I
8 ** * *****
9 * * *H* *
0 ** * ** *
1 ** G* **
2 A*********B *
3 ** *
4 * J
5 ** *
6 Q *
7 ** *
8 ** K
9 ** *
0P* *
1 * N *
2 * ** * L
3 * ** * **
4 * ** * **
5 O* M*
A: great bridge
B: supermarket
C: home
D: beach
E: park
F: little island
G: friend's house
H: SO building
I: forest
J: tea-shop
K: cinema
L: restaurant
M: airport
N: old castle
O: museum of code-golf
P: riverside
Q: new plaza
End Second
```
Ungolfed original:
```
coords =: > 1 {" 1 parsed =: ([:<`([:<[:".;._1'|',}:);._1'(',]);._2 (1!:1)3
center =: (+/%#) coords
max =: >:>./ coords
angles =: 12 o. j./"1 coords -"1 center
ordered =: parsed /: angles
paths =: >(],"0(1)|.]) 1 {" 1 ordered
path_grid_lengths =: ([:>./|@-/)"2 paths
path_grid_interval =: ([:<]%~i.@>:@|)"0 path_grid_lengths
path_grid_distances =: -~/"2 paths
path_grid_steps =: path_grid_distances ([:<[*>@])"0 path_grid_interval
path_grid_points_sortof =: (> 1{"1 ordered) ([:<0.5<.@+[+>@])"0 path_grid_steps
path_grid_points =: <"1;([:<>@[,.>@])/"1 path_grid_points_sortof
graph_body =: }."1}. (u:65+i.#ordered) (1{"1 ordered) } '*' path_grid_points} max $ ' '
axis_top =: |:(":"0)10|}.i. 1{max
axis_side =: (":"0)10|i. 0{max
echo |:(axis_side) ,"1 axis_top, graph_body
echo ''
echo (u:65+i.#parsed),.':',.' ',.(> 0{"1 ordered)
```
[Answer]
## Python, 1074 bytes
Ok, spent way too many bytes (and time) getting reasonable paths to work.
```
#!/usr/bin/python
#coding=utf-8
import sys
H=V=0
T=[]
k=65
R=1000
for L in sys.stdin.readlines():
i,j,K=L.find('('),L.find('|'),'%c'%k
n,h,v=L[:i-1],int(L[i+1:j]),int(L[j+1:-2])
H=max(H,h);V=max(V,v);T+=[(v*R-R+h-1,K)];k+=1;print K+':',n
for s in zip(*['%3d'%(i+1)for i in range(H+1)]):print' '+''.join(s)
T.sort()
U=reduce(lambda a,x:a[:-1]+[(a[-1][0],x)]if x/R==a[-1][0]/R else a+[(x,x)],[[(T[0][0],T[0][0])]]+map(lambda x:x[0],T))
C=R*V*[' ']
r=0
for x,y in U:C[x:y]=(y-x)*u'─'
for (a,b),(c,d)in zip(U,U[1:]):
if r:
if d%R>b%R:x=b/R*R+d%R;C[b:x]=(x-b)*u'─';C[x:d:R]=(d-x)/R*u'│';C[x]=u'┐'
else:x=d/R*R+b%R;C[d:x]=(x-d)*u'─';C[b:x:R]=(x-b)/R*u'│';C[x]=u'┘'
else:
if c%R<a%R:x=a/R*R+c%R;C[x:a]=(a-x)*u'─';C[x:c:R]=(c-x)/R*u'│';C[x]=u'┌'
else:x=c/R*R+a%R;C[a:x:R]=(x-a)/R*u'│';C[x:c]=(c-x)*u'─';C[x]=u'└'
r^=1
p=U[0][1];C[p:H]=(H-p)*u'─'
if r:p=U[-1][1];C[p:R*V]=(R*V-p)*u'─'
else:V+=1;C+=[' ']*R;p=U[-1][0]+R;C[p:R*V]=(R*V-p)*u'─';C[p]=u'└'
C[H::R]=u'┐'+u'│'*(V-2)+u'┘'
for p,K in T:C[p]=K
for i in range(V):print'%3d'%(i+1)+''.join(C[i*R:i*R+H+1])
```
Makes nice paths, though:
```
A: SomeTown
B: ACity
C: Wherever
D: Home
12345678
1 ┌─D──┐
2 │ │
3 │ │
4 B───┐│
5 ││
6 ││
7┌─────C│
8│ │
9│ │
10A──────┘
```
and
```
A: home
B: supermarket
C: park
D: new plaza
E: friend's house
F: old castle
G: riverside
H: beach
I: cinema
J: forest
K: little island
L: museum of code-golf
M: airport
N: tea-shop
O: restaurant
P: great bridge
Q: SO building
111111111122222222223333
123456789012345678901234567890123
1 H──────────K───────────┐
2 │ │
3 │ │
4 │ │
5 └────C────────────────┐│
6 ││
7 A──────────────────────────J│
8 │ │
9 └───────────────────Q │
10 │ │
11 ┌────────────────E────┘ │
12 P─────────B──────────┐ │
13 │ │
14 ┌──────────────N │
15 │ │
16 D───────────┐ │
17 │ │
18┌───────────────────I │
19│ │
20G────────────┐ │
21 F │
22 └─────────O │
23 │ │
24 │ │
25 L───────────M─────┘ │
26 └──────────────────────────┘
```
]
|
[Question]
[
A long period prime is a prime number \$p\$ such that decimal expansion of \$1/p\$ has period of length \$(p-1)\$. Your task is to output this number sequence. For purposes of this challenge we will consider only odd primes.
[Period of a decimal expansion](https://en.wikipedia.org/wiki/Repeating_decimal) of a rational number is the smallest period \$k\$ that makes the decimal representation periodic (repeating at regular intervals \$k\$).
This is [A001913](https://oeis.org/A001913), or [A006883](https://oeis.org/A006883) without leading \$2\$.
## Examples
\$\frac{1}{3}=0.33333\ldots\$, so the period is \$1\$ (although the number is also 2-periodic, 3-periodic etc., but we take the minimum). \$3-1=2\neq1\$, so \$3\$ won't appear in our sequence.
\$\frac{1}{7}=0.14285714\ldots\$ - the period is \$6 = 7-1\$.
## Rules
This is a standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")[sequence](/questions/tagged/sequence "show questions tagged 'sequence'") challenge, so please comply with the defaults.
With floating point errors, let's stick to the highest voted decisive answer [here on meta](https://codegolf.meta.stackexchange.com/questions/20528/what-is-our-consensus-on-floating-point-issues/20529#20529), so I'll allow them.
## Test cases
First 10 entries:
```
7, 17, 19, 23, 29, 47, 59, 61, 97, 109
```
For more visit: [A001913's b-file](https://oeis.org/A001913/b001913.txt).
---
*Inspired by recent [Numberphile video](https://www.youtube.com/watch?v=DmfxIhmGPP4).*
[Answer]
# x86-64 machine code, 27 bytes
```
31 F6 FF C6 89 F1 6A 0A 58 99 F7 FE 6B C2 0A FF CA E0 F6 E2 ED FF CF 75 E9 96 C3
```
[Try it online!](https://tio.run/##XVLLTsMwEDzHX7EEVdh9qQXEgVIuPXPhhEQ5uLaTGDl2yKO4VP11wjpphMCHjXdmd3bsWBTFLBWibS@1FaaRCh6qWmo3zx7JH8jo3X@s1DYNGFG@VqWFeBPDUdsaEhoiZ6sT4VUOFJ5jSuapcTtuICHJPYm8K0FVehoCsSiQI4jaXR7lbg9K@J6NiqbKYLnAjSug5J4YrBXyAxuk3vc1Om8MKB5aJIZQLZUICYmMc4X9AtPvoJs20Nj6jtwZ8yJLz7ZwTFSqmrAY2IqQcKCca9ufrEzFFETGSxiPMdkzciSAK5Ae1rCYwiF8Vh36mWmjgE4mHh7WsLxjHRpWgVdYJzQeaZg9wkhvbTwFtJ9Qz1jfPJRs7RMXmbYKhJPqPj7T/neMdHAcqmG0uH5BrcOa0sZWOrVKdobHLGGvfjJ5w58zGDvABYr4zc2/kUDR1@5Qq4r1xga@qYMUvdraqzOEN9XgC0AnJ9K23yIxPK3aWX53iwHfwBoVlfkB "C++ (gcc) – Try It Online")
Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes a number \$n\$ in EDI and returns the 1-indexed \$n\$th long-period prime in EAX.
In assembly:
```
f:
xor esi, esi # Set ESI to 0.
nextm:
inc esi # Add 1 to ESI to get the next number (m) to test.
mov ecx, esi # Set ECX to m.
push 10 # Push 10 onto the stack
pop rax # and pop it into RAX.
l:
cdq # Sign-extend, setting up for the next instruction.
idiv esi # Divide by m, putting the quotient in EAX and the remainder in EDX.
imul eax, edx, 10 # Set EAX to EDX×10.
dec edx # Subtract 1 from EDX.
loopnz l # Subtract 1 from ECX, and repeat if both are nonzero.
loop nextm # Subtract 1 from ECX, and jump if the result is nonzero.
# This point will be reached iff 1 is first obtained
# after exactly m-1 iterations of ×10 and mod m.
dec edi # Subtract 1 from EDI, counting down from n.
jnz nextm # Jump if it is nonzero.
xchg esi, eax # Exchange the final value of m from ESI into EAX.
ret # Return.
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~73~~ 64 bytes
~~The usual Wilson's theorem based prime generation combined with computing the multiplicative order.~~ Now porting [tsh's answer](https://codegolf.stackexchange.com/a/244256/64121), you don't actually need to check for primality if the multiplicative order is right.
```
k=3
while j:=1:
while 10**j%k>1<k>j:j+=1
j==k-1==print(k);k+=1
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P9vWmKs8IzMnVSHLytbQiksBwjE00NLKUs22M7TJtsuyytK2NeRSyLK1zdY1tLUtKMrMK9HI1rTOBgr//w8A "Python 3.8 (pre-release) – Try It Online")
[Answer]
# JavaScript + `alert`, 57 bytes
```
for(i=2n;++i;j-i||alert(i))for(j=1n;j<=i&10n**j++%i!=1;);
```
[Try it online!](https://tio.run/##HcvBDoIwDIDhV6kHZaPBOK@lvssCw7RZVjMIJ959itf/z6dxj@tU5bMNxebUYk51A4Y9ZuAXTFZWy@me7e3OhNB1ntpi1Qk/CyEK6SDH8XdOvD@XciikI8stPErfK@JVLhzoJ9sX "JavaScript (Node.js) – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 15 bytes
```
tfλ=←⁰LUm%⁰İ⁰)N
```
[Try it online!](https://tio.run/##yygtzv7/qG2iocGjpsb/JWnndts@apvwqHGDT2iuKpA6sgFIaPr9/w8A "Husk – Try It Online")
For each natural number (`N`), get the series of powers-of-10 (`İ⁰`) modulo that number (`m%⁰`); now select those (`fλ)`) for which the length (`L`) of the longest prefix of unique elements (`U`) is equal to (`=`) that number minus one (`←⁰`). This annoyingly includes 2 at the start, so we need to take the tail (`t`).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ṖȯfƑ⁵*Ɱ%Ɗµ#
```
A full program that accepts an integer, `n`, from STDIN and prints the Jelly representation\* of a list of the first `n` numbers which have a [primitive root](https://en.wikipedia.org/wiki/Primitive_root_modulo_n "Wikipedia") of \$10\$.
**[Try it online!](https://tio.run/##ASAA3/9qZWxsef//4bmWyK9mxpHigbUq4rGuJcaKwrUj//82MA "Jelly – Try It Online")**
\* the Jelly representation of a list with a single element is just that element.
### How?
```
ṖȯfƑ⁵*Ɱ%Ɗµ# - Main Link: no arguments
µ# - implicitly takes input - call this N
µ# - collect the first N values of K (in [0,1,2,...]) for which:
Ṗ - pop -> [1,2,...,K-1]
ȯ - logical OR with K (so we get K when K is 0 or 1, rather than [])
(let's call this list of integers (or 0 or 1) P)
Ɗ - last three links as a monad - f(K):
⁵ - 10
Ɱ - map across (implicit [1,2,...,K]) with:
* - exponentiation
% - modulo K (vectorises)
(let's call this list of integers M)
Ƒ - is P invariant under?:
f - P filter keep M
- implicit print
```
---
A couple of other 11 byters:
```
⁵*Ɱ%i1=ṖṪµ#
⁵*Ɱ%=1Ḅ⁼2µ#
```
[Answer]
# [Factor](https://factorcode.org/) + `lists.lazy math.primes.lists project-euler.026`, ~~57~~ 52 bytes
```
[ lprimes [ dup -1 ^ period-length - 1 = ] lfilter ]
```
[Try it online!](https://tio.run/##JYyxDoIwFEV3vuL@AA04OGicjYuLcSKYNOUhlUfblMeAP1@LrOfknF4b8TE9H7f79YQQ/YeMlLQwRVUdjmA7y6xYf1dMWgYVop0ogw3vcuf94oxY72aMFB3xn@Yfiay5cYJzUdRVasD7Ag26JaCs8UKgaH1XMrl3jkrUuKAF95aFItpkNDNY9Ei5UpsibYb0Aw "Factor – Try It Online")
Believe it or not, Factor includes solutions to the first 200 or so Project Euler problems and exposes them the same way as any other vocabulary. Many of these vocabularies provide useful words, such as `project-euler.026` which provides the `period-length` word.
## Explanation
It's a quotation that outputs the infinite lazy sequence of long period primes.
* `lprimes` An infinite lazy list of primes.
* `[ ... ] lfilter` Select only those whose...
* `dup -1 ^ period-length - 1 =` ...reciprocals have a period length one less.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
∞ʒ©L.Δ°®%}®α
```
Port of [*@tsh*'s JavaScript answer](https://codegolf.stackexchange.com/a/244256/52210), and also outputs the infinite sequence.
[Try it online.](https://tio.run/##AR8A4P9vc2FiaWX//@KInsqSwqlMLs6UwrDCriV9wq7Osf//)
**Explanation:**
```
∞ # Push an infinite positive list: [1,2,3,...]
ʒ # Filter it by:
© # Store the current value in variable `®` (without popping)
L # Pop and push a list in the range [1,®]
.Δ # Find the first value in this list which is truthy for:
° # Push 10 to the power the value
®% # Modulo-`®`
# (Note: only 1 is truthy in 05AB1E)
} # After we've found our result (or not, resulting in -1)
®α # Take the absolute difference with `®`
# (and again, only 1 is truthy in 05AB1E)
# (after which the infinite list is output implicitly)
```
[Answer]
# [R](https://www.r-project.org/), ~~53~~ 51 bytes
```
repeat if(T==match(1,10^(1:(T=T+1))%%T,0))cat(T,"")
```
[Try it at rdrr.io](https://rdrr.io/snippets/embed/?code=%23%20here%20we%20use%20%27while(T%3C25)%27%20instead%20of%20%27repeat%27%20to%20output%20just%20long-period%20primes%20that%20are%20%3C25%3A%0A%0Awhile(T%3C25)%20if(T%3D%3Dmatch(1%2C10%5E(1%3A(T%3DT%2B1))%25%25T%2C0))cat(T%2C%22%22)) (but see below...)
Similar approach to [this](https://codegolf.stackexchange.com/a/244265/95126): for each integer `T`, check whether the first `1` in the list of powers-of-10 modulo `T` occurs at the `T-1`-th position (meaning that the period of the decimal expansion is `T-1`).
Unfortunately, this approach suffers (quite badly) from inaccuracies as soon as the powers-of-10 exceed [R](https://www.r-project.org/)'s floating-point precision: so, it only manages to output `7 17 19 23` before generating a large number of `probable complete loss of accuracy in modulus` warnings.
---
# [R](https://www.r-project.org/), 65 bytes
```
repeat{y=T=T+1;z=1;while(y&(z=(z*10)%%T)-1)y=y-1;cat(T[y==2],"")}
```
[Try it online!](https://tio.run/##K/r/vyi1IDWxpLrSNsQ2RNvQusrW0Lo8IzMnVaNSTaPKVqNKy9BAU1U1RFPXULPStlLX0Do5sUQjJLrS1tYoVkdJSbP2/38A "R – Try It Online")
Alternative approach unaffected by floating-point inaccuracies (at least until very large values...); outputs a whitespace-separated list of all long-period-primes.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes
```
Þp'ɾ↵$%1ḟ⇧=
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDnnAnyb7ihrUkJTHhuJ/ih6c9IiwiIiwiMTciXQ==)
Port of Kevin Cruijssen's answer.
```
Þp' # Filter the infinite list of primes by...
ɾ # 1...n
↵ # 10 to the power of each of those
$% # Modulo n
1ḟ # Find the first index of a 1
⇧= # Is it + 2 equal to n?
```
See, when I saw something about "powers of 10 modulo n" I thought it meant you could get something with an equivalent cycle in that way. I didn't realise it was so simple...
[Answer]
# [Ruby](https://www.ruby-lang.org/), 47 bytes
```
7.step{|x|x-1==(1..x).find{|c|10**c%x<2}&&p(x)}
```
[Try it online!](https://tio.run/##KypNqvz/31yvuCS1oLqmoqZC19DWVsNQT69CUy8tMy@luia5xtBASytZtcLGqFZNrUCjQrP2/38A "Ruby – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 52 bytes
```
If[10~MultiplicativeOrder~k==k-1,Print@k]~Do~{k,∞}
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773zMt2tCgzrc0pySzIAcoVpJZlupflJJaVJdta5uta6gTUJSZV@KQHVvnkl9Xna3zqGNe7X@wmIJD@v//AA "Wolfram Language (Mathematica) – Try It Online")
-15 bytes from @ovs
[Answer]
# Javascript + `alert`, 54 53 bytes
```
for(n=3;i=n++;i||alert(n))for(x=1;i*(x=x*10%n)>i--;);
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~73~~ ~~72~~ 71 bytes
```
k,j,i;f(n){for(j=k=2;n-=j==k++-1;)for(i=10,j=0;j++<k&i%k>1;)i*=10;--k;}
```
[Try it online!](https://tio.run/##VVHRUsIwEHz3K26YQVuaDLSoDIbw4vgVwkNpL5C2pkwTFGX4deuFAmomSZO9273bNOPrLGur2qxhOAS30RZoqroBh9ZpgmtTfQLnsK4rhTm8Y2N1bWBn0UKOKt1VDrRxsNo5yFLT5W9Sk1cIKohD4HOYtCUrmBYqMOGBxINCljIRhstCyjKKeCxCD2sZj1ghR6KIoll5q/vlnCJ6QLDgvBTH1ld6S7UJQjjcAA0P4H6LmcP8dQkSDhMGsV/To/CeHu9hpbsWqb07d@nNbdDiEyRjBsmUwT1RHuj7GDOYevqI@KcKWW0scTdpM6AdsxKbrlBvsX9JFvvpM62HHoO/93HvzPZPGfji2uS4J9pInI8zsPoLaxVc2g@HZ2BwRQRE0Sk7PIl1li@2Hal1UhHE4l/IUkgFLvyPIqHXtzoxl78J24ZSVNDr5/6P0d63C0OuHAPLrsZRSrs8yx5vju13pqp0bVv@8QM "C (gcc) – Try It Online")
Returns the \$1\$-based \$n^\text{th}\$ long period prime.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes
```
≔¹θFN«≦⊕θW›⊖θ⊕⌕﹪Xχ…¹θθ¹≦⊕θ⟦Iθ
```
[Try it online!](https://tio.run/##fY4xC8IwEIXn9lfceIEIzewkitKhUlzFIbZnG0iTNk3tIP72GKmIk2@44fg@3qta6SordQibcVSNQcFhYOv0Zh1gbvrJH6fuSg4Zg0eaFLL/cLmpHHVkPNWLkcyt0gR4cCR9FHb0BXBgHH4E3CtTY2HrSVss7RxpkXE4SdPQMoC9DwfBYuBfaemU8XjeytHHlkt8PUMQWVjd9Qs "Charcoal – Try It Online") Link is to verbose version of code. Outputs the first `n` long period primes. Explanation: Based on @tsh's answer.
```
≔¹θ
```
Start at `2` (because we increment this almost immediately). (Any number below `7` would work.)
```
FN«
```
Loop `n` times.
```
≦⊕θ
```
Increment the number under test.
```
W›⊖θ⊕⌕﹪Xχ…¹θθ¹
```
While the number's period is not equal to one less than it...
```
≦⊕θ
```
... increment the number under test.
```
⟦Iθ
```
Output the next long period prime.
[Answer]
# [Zsh](https://www.zsh.org/), 54 bytes
```
for ((;++n;))(r=9;for ((;r%n;))r+=9
((n+~$#r))||<<<$n)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhY3zdLyixQ0NKy1tfOsNTU1imwtraEiRaogkSJtW0suDY087ToV5SJNzZoaGxsblTxNiG6oITDDAA)
Uses the fact that the repeating decimal period of \$ n \$ is the minimum integer \$ i \$ such that \$ n \$ divides \$ r = 10^i - 1 = \operatorname{rep}(9, i)\$.
Prints the sequence infinitely, but can only manage the first 3 terms before Zsh's floating point numbers implode.
We have to be careful with how and where we use `$r` to ensure it stays a string, so that `r+=9` literally appends instead of adds 9.
[Answer]
# [Sidef](https://github.com/trizen/sidef), 39 bytes
```
{10.is_primitive_root(_)&&.say}<<2..Inf
```
]
|
[Question]
[
Related: [Landau's function](https://codegolf.stackexchange.com/q/191074/78410) ([OEIS A000793](https://oeis.org/A000793))
## Background
Landau's function \$g(n)\$ is defined as the largest order of permutation of \$n\$ elements, which is equal to \$\max(\operatorname{lcm}(a\_1,a\_2,\cdots,a\_i))\$ where \$a\_1,a\_2,\cdots,a\_i\$ is an integer partition of \$n\$.
We can extend this to define "iterations" of Landau's function: let's define \$g\_0(n) = 1\$, and \$g\_{k+1}(n) = \max(\operatorname{lcm}(g\_{k}(n), a\_1,a\_2,\cdots,a\_i))\$ for \$k \ge 0\$. This eventually converges to \$\operatorname{lcm}(1,2,\cdots,n)\$, so we can define "Landau logarithm" to be the smallest value of \$k\$ such that \$g\_k(n)=\operatorname{lcm}(1,2,\cdots,n)\$, or equivalently \$g\_k(n)=g\_{k+1}(n)\$.
The resulting sequence is [OEIS A225633](https://oeis.org/A225633).
## Illustration
### n = 5
To make it clear, let's list up all the integer partitions of 5, which are:
```
(5)
(4, 1)
(3, 2)
(3, 1, 1)
(2, 2, 1)
(2, 1, 1, 1)
(1, 1, 1, 1, 1)
```
By definition, \$g\_0(5) = 1\$. \$g\_1(5)\$ is defined by whatever partition gives the largest LCM, which is \$\operatorname{lcm}(2,3) = 6\$ (which is the same as the plain Landau function). \$g\_2(5)\$ is the largest LCM of any partition *when combined with 6*. We need to find the partition which can give the largest additional factor. Such partition is plain 5, so \$g\_2(5) = \operatorname{lcm}(6,5) = 30\$. In the next step, the only partition that boosts the LCM further is (4,1), giving \$g\_3(5) = \operatorname{lcm}(30, 4, 1) = 60\$, which is the same as \$\operatorname{lcm}(1, 2, 3, 4, 5)\$. Therefore, the Landau logarithm of 5 is 3.
### n = 10
* \$g\_0(10) = 1\$
* \$g\_1(10) = \operatorname{lcm}(2,3,5) = 30\$
* \$g\_2(10) = \operatorname{lcm}(30,7,3) = 210\$
* \$g\_3(10) = \operatorname{lcm}(210,8,2) = 840\$
* \$g\_4(10) = \operatorname{lcm}(840,9,1) = 2520 = \operatorname{lcm}(1,2,\cdots,10)\$
Therefore the Landau logarithm of 10 is 4.
## Challenge
Given a positive integer \$n\$, compute its Landau logarithm.
The shortest code in bytes wins.
## Test cases
The first 20 terms (starting at `n=1`, up to `n=20` inclusive) are:
```
0, 1, 2, 2, 3, 3, 3, 3, 4, 4,
5, 5, 6, 5, 5, 5, 6, 6, 7, 6
```
[Answer]
# [Haskell](https://www.haskell.org/), 72 bytes
```
(1%)
k%n|k?n==k=0|1>0=1+k?n%n
k?0=k
k?n=maximum[lcm x$k?(n-x)|x<-[1..n]]
```
[Try it online!](https://tio.run/##FcmxDsIgEADQna@4oSRtDA04e/IhlYEQUXJwIVYTBr5dtOPLe/qd7jmPiLcxG7kIktzJMiKh7uaq0Zz@lCzIaiRxVPEtlU/ZcijQJrIzq7b0dlGbWVd2bhSfGBDqK/EbJii@QoQjz9qNb4jZP/ahQq0/ "Haskell – Try It Online")
The helper function `k?n` compute a the Landau function `g(n)` except `k` is also in the list of numbers. Then, `k%n` counts how many iterations of replacing `x` with `x?n` starting with `k` we need to reach a fixed point.
[Answer]
# [Haskell](https://www.haskell.org/), 69 bytes
A small improvement to [xnor's answer](https://codegolf.stackexchange.com/a/217578/64121).
```
(1%)
k%n|k?n==k=0|1>0=1+k?n%n
k?n=maximum$k:[lcm x$k?(n-x)|x<-[1..n]]
```
[Try it online!](https://tio.run/##FclBDsIgEEDRfU8xC0jaGBpwacQepLIgRJQMMyGtJiw4u2iX//2X3/GRc4/23kcjpwElN1zYWrS6mZu25vRPycOB5GuiDwm8rDkQVIHLyKpOrV7VauaZnevkE4OFsiV@gwDyBSIc86xd/4aY/XPvKpTyAw "Haskell – Try It Online")
Compared to the original solution I have simplified the definition of `k?n`, which calculates one iteration of the Landau function.
For \$n=0\$ the function returns \$k\$ and for positive \$n\$ it always returns the \$\mathop{lcm}\$ of \$k\$ and some positive integers, which is greater than or equal to \$k\$.
Since `[1..n]` is empty for \$n=0\$, we can get rid of an explicit base case by prepending \$k\$ to the list of possible results.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ ~~14~~ 13 bytes
```
:ælƒ€@Ṁ¥ƬŒṗL’
```
[Try it online!](https://tio.run/##ASsA1P9qZWxsef//OsOmbMaS4oKsQOG5gMKlxqzFkuG5l0zigJn/w4figqz//zIw "Jelly – Try It Online")
## Explanation (older version)
```
:;Ɱæl/€ṀɗƬŒṗL’ Main monadic link
: Divide the input by itself to get 1
Ƭ Repeat until reaching fixed point, collecting intermediate results
ɗ (
;Ɱ Œṗ Prepend to each integer partition of the input
€ For each
/ fold over
æl the lowest common multiple
Ṁ Maximum
ɗ )
L Length
’ Decrement
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~27~~ ~~21~~ 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
1.ΓIÅœs䪀.¿à}g
```
-6 bytes by porting [*@xigoi*'s Jelly answer](https://codegolf.stackexchange.com/a/217541/52210), so make sure to upvote him!
[Try it online](https://tio.run/##yy9OTMpM/f/fUO/cZM/DrUcnF5/bcmjVo6Y1eof2H15Qmw6UMQAA) or [verify all test cases](https://tio.run/##ATIAzf9vc2FiaWX/MjBFTj8iIOKGkiAiP05V/zEuzpNYw4XFk3POtMKq4oKsLsK/w6B9Z/8s/w).
**Original ~~27~~ 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) approach:**
```
1[DIL.¿QD–#IÅœs䪀.¿à
```
-6 bytes thanks to *@ovs*.
[Try it online](https://tio.run/##yy9OTMpM/f/fMNrF00fv0P5Al0cNk5U9D7cenVx8bsuhVY@a1gBFDy8AqjAAAA) or [verify all test cases](https://tio.run/##AUEAvv9vc2FiaWX/MjBFTj8iIOKGkiAiP05Ewqki/zFbRMKuTC7Cv1FE4oCTI8Kuw4XFk3POtMKq4oKsLsK/w6D/Ii5W/w).
**Explanation:**
```
1 # Push 1
.Γ # Loop until it no longer changes, collecting intermediate results:
I # Push the input-integer
Ŝ # Pop and push all lists of positive integers that sum to this input
δ # Map over each of these lists:
s ª # And add the current value as trailing item to each
€ # Then map over each of these lists again:
.¿ # And calculate its least common multiple
à # Pop this list of lcm's, and only leave the maximum
}g # After the loop: pop and push its length
# (after which it is output implicitly as result)
1 # Push 1
[ # Start an infinite loop:
D # Duplicate the current value on the stack
IL # Push a list in the range [1,input]
.¿ # Pop and get the least common multiple of this list
Q # If this is equal to the current value we've duplicated:
– # Print the (0-based) loop-index
D # # And stop the infinite loop/program
IÅœs䪀.¿à # Same as above
```
[Answer]
# JavaScript (ES6), ~~145~~ 116 bytes
```
n=>~(G=(a,b)=>b?G(b,a%b):a,P=(p,n,i=1)=>m=n?i>n||Math.max(P(p*i/G(p,i),n-i,i),P(p,n,i+1)):p,h=p=>P(p,n)-p&&h(m)-1)``
```
[Try it online!](https://tio.run/##JYvBDoIwEETvfEUPanalqPWILhw5mfAJtChSI9sGiDFB/HVEPc1k3pubfuiubK3vI3bny1TRxJS8ISPQ0iAlJs3ASL00GGuZE3jJ0pKaSUOc2oRfr5Pu602jn5CDX9ttNjsWJUf2G/n/ESrE2MuaPCW/CSO/WtXQYKSwKKbKtcCChDoIFkcS@91cwhDFEAhROu7c/bK5uysUGhYDjzi7i6ECxrHAQzBOHw "JavaScript (Node.js) – Try It Online")
### Commented
The helper function \$G\$ computes \$\gcd(a,b)\$.
```
G = (a, b) => b ? G(b, a % b) : a
```
The helper function \$P(p,n)\$ recursively computes all integer partitions of \$n\$ while keeping track of the maximum \$\operatorname{lcm}\$ of the union of the partition and \$p\$. This maximum is eventually saved in \$m\$ and returned.
```
P = ( // P is a recursive function taking:
p, // p = previous maximum
n, // n = input of the main function
i = 1 // i = counter for the current partition
) => //
m = // save the final result in m
n ? // if n is not equal to 0:
i > n || // return 1 if i is greater than n
Math.max( // otherwise return the maximum of:
P(p * i / G(p, i), n - i, i), // a recursive call with p = lcm(p, i)
// and n = n - i
P(p, n, i + 1) // a recursive call with i + 1
) // end of Math.max()
: // else:
p // stop the recursion and return p
```
The helper function \$h\$ updates the maximum \$m\$ until a fixed point is reached and keeps track of the total number of iterations (as a negative value).
```
h = p => P(p, n) - p && h(m) - 1
```
The main wrapper function just processes the initial call to \$h\$ with \$p\$ zero'ish and bitwise-inverts the result.
```
n => ~h``
```
[Answer]
# [Haskell (Lambdabot)](https://codegolf.stackexchange.com/a/92314/9486), 127 bytes
```
l=foldl1 lcm
p 0=[[]]
p n=[1..n]>>= \x->(x:)<$>p(n-x)
n#v=maximum$fmap(l.(v:))$p n
s n=fromJust$elemIndex(l[1..n])$iterate(n#)1
```
`s` is the "main" function. Requires `Data.List` and `Data.Maybe` from lambdabot to run.
Ungolfed:
```
-- LCM of a list; it saves a few bytes to define a shortcut to it.
l = foldl1 lcm
-- Given an integer n, this function gives us all partitions of n.
-- The list monad is excellent for "enumeration" sorts of problems
-- like this.
p 0 = [[]]
p n = [1..n] >>= \x -> (x: ) <$> p (n - x)
-- Given an integer n and a previous Landau value v, this function
-- (whose name is the infix operator (#)) produces the "next" Landau
-- iteration value.
n # v = maximum $ fmap (l . (v :)) $ p n
-- Given an integer n, we iterate the (#) function until we find the
-- number `l [1..n]' (the lcm of 1 up to n) and then we return the index
-- of that number. Unfortunately, elemIndex returns `Maybe Int' so we need
-- the rather lengthy fromJust to get rid of that.
s n = fromJust $ elemIndex (l [1..n]) $ iterate (n #) 1
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 58 bytes
```
((i=1)//.n_:>Max[i--;n~LCM~##&@@@IntegerPartitions@#];-i)&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X0Mj09ZQU19fLy/eys43sSI6U1fXOq/Ox9m3TllZzcHBwTOvJDU9tSggsagksyQzP6/YQTnWWjdTU@1/QFFmXomCg4JjUVFiZXSajoKRQex/AA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~68~~ 67 bytes
```
k%n=sum[1+k?n%n|k?n>k]
k?n=maximum$k:[lcm x$k?(n-x)|x<-[1..n]]
```
```
(1%)
```
[Try it online!](https://tio.run/##FcmxCsMgEIDhPU9xg0JCMdS11OZBrINIbeW8Q2oDDnn2mmT5v@H/@IqvnHs0zz5qOQ0o2dSVrL7gwpK3ow90w4Eh3xKtJPBmcyBoApeRVZu2dldWzzM718knBgPlm/gHAsgXiHBOfXX9H2L279pVKGUH "Haskell – Try It Online")
Golfs 2 bytes off of [ovs' answer](https://codegolf.stackexchange.com/a/217610/) which itself golfed 3 bytes off [xnor's answer](https://codegolf.stackexchange.com/a/217578/56656).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 100 bytes
```
≔⟦⟦N¹⟧⟧θFθ«≔⊟ιη≔⌊ιζ≔⊟ιε¿εF…·¹ζ⊞θ⁺ι⟦κ⁻εκ÷×ηκ⌈Φ⊕κ∧λ¬∨﹪κλ﹪ηλ⟧⊞υη»≔⟦¹⟧θW⁻Eυ÷×⌈θκ⌈Φ⊕κ∧μ¬∨﹪κμ﹪⌈θμθ⊞θ⌈ιI⊖Lθ
```
[Try it online!](https://tio.run/##jZBPT8MwDMXP9FP46Ejh0CPqaWJCmrSOCnGbdiirt1pL0j9JBgLx2UvSrtqEOJCbn5@ff/G@Lvt9U6phWFjLR4Pb7cq03m28fqMehYR0t5PQiSw5ND1gJ@Arubt4i6ZFDpY6dGctZ8Pa61H/vNFnL0WND4AkYExcmb3yls/0UpojYRrHBBTe1thJKEIPWcL2JCFEh4IknELOyrgln7kifGVNFutJzsuPcf0TKxf4Q3hPmoyjCmN7YSpUEjaNw@ce86byqsEQreLoVNWxmt5OiAxIWZpw/PTT72Q@VXq5zHvNigAnvrxso/M33wzWiX@D6j9A9RX0NlFfiEUEul5vtnD4SFL0bBw@ltbhkq7b1mSOLrjjdDYM6cNwf1Y/ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⟦⟦N¹⟧⟧θFθ«
```
Start a breadth-first search for integer partitions of \$ n \$. Each partition is represented by a list of terms \$ a\_1, a\_2, ..., a\_i, r, l \$ where the residue \$ r = n - \sum a\_k \$ and the LCM \$ l = \operatorname{lcm}(a\_1, a\_2, ..., a\_i) \$ , so as the initial partition has no terms yet, the residue is just \$ n \$ and the lcm is \$ 1 \$.
```
≔⊟ιη≔⌊ιζ≔⊟ιε
```
Extract \$ l, r, \$ and \$ \operatorname{min}(a\_1, a\_2, ..., a\_i, r) \$ (which is the maximum possible next term of the partition).
```
¿εF…·¹ζ
```
If \$ r \$ is non-zero, then looping over each valid next term...
```
⊞θ⁺ι⟦κ⁻εκ÷×ηκ⌈Φ⊕κ∧λ¬∨﹪κλ﹪ηλ⟧
```
... concatenate the previous terms with the current term, the new residue, and the new LCM (calculated manually by dividing the product by the maximum of all common factors).
```
⊞υη
```
Otherwise this is a complete partition so save the LCM to the predefined empty list.
```
»≔⟦¹⟧θ
```
Now start building up the terms of \$ g \$ starting with \$ g\_0(n) = 1 \$.
```
W⁻Eυ÷×⌈θκ⌈Φ⊕κ∧μ¬∨﹪κμ﹪⌈θμθ
```
Take the LCM of each of the partition LCMs with the maximum \$ g \$ value (i.e. the latest \$ g\_i \$), but remove those whose LCM was still that value. Repeat while LCMs still remain.
```
⊞θ⌈ι
```
Add the highest LCM to the \$ g \$ list.
```
I⊖Lθ
```
Print the index of the last term.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~84~~ 78 bytes
-4 thanks to @Bubbler
```
{#1_(|/(x/'{$[x;,/i,''(x-i)o'y&i:1+!x&y;,!0]}/2#y)x')\1}{_x*y%*|(*:)(|!\)/x,y}
```
[Try it online!](https://ngn.bitbucket.io/k#eJwNyzEOgCAMAMCdXxCUtoipOOJT1LiRMLm2Af6ut1/JzaUHO6MwtOmUI3KNAChrpRfU15wWK16PaLd78O6UBOhKoz0SdA4dQybs9iKWqMOYAn/Ytw9O/Rfg)
```
/ungolfed
p:{$[x;,/i,''(x-i)o'y&i:1+!x&y;,!0]} /partitions
g:*|(*:)(|!\)/ /gcd
l:{_x*y%g x,y} /lcm
f:{#1_(|/(l/'p/2#x)l')\1} /landau log
```
[Answer]
# [Scala](https://www.scala-lang.org/), ~~226~~ 185 bytes
```
n=>Stream.iterate(1){z=>1.to(n).toSet.subsets.filter(_.sum<=n).map(?(_,z)).max}indexWhere?(1.to(n).toSet,1).==
val? =(_:Set[Int])./:(_:Int)((a,b)=>Stream.from(a).find(x=>x%a+x%b<1).get)
```
[Try it online!](https://scastie.scala-lang.org/tnKn43hQQxmDr85Ox8NNiQ)
This is embarrassingly long and inefficient. Instead of finding integer partitions of n, this finds all subsets of the range [1..n] where the sum does not exceed n.
`?` is a helper function that finds the lcm of its second argument (a number) and all the elements in its first argument (a list). It does this by folding over the first argument with the second as the initial accumulator.
```
n =>
Stream.iterate(1){z=> //Make infinite list by repeatedly apply this function to 1
1.to(n).toSet.subsets //All subsets of range 1..n
.filter(_.sum <= n) //Keep the ones whose sum is not greater than n
.map(?(_,z)) //lcm of each (including g_{k-1}(n))
.max //Max
} indexWhere //Find the index k where
?(1.to(n).toSet,1) //The lcm of 1..n
.== //equals g_k(n)
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~128~~ 123 bytes
Apparently this uses a very similar approach as [xnor's Haskell answer](https://codegolf.stackexchange.com/a/217578/64121).
```
from math import*
f=lambda n,d=1:d-g(n,d)and-~f(n,g(n,d))
g=lambda n,d:max([g(n-k,k*d//gcd(k,d))for k in range(1,n+1)]+[d])
```
[Try it online!](https://tio.run/##TYqxDoMgFAB3v@JtBZUY7EZif8Q40L6ChPIwhKGNsb9ONV3c7nK3fPIc6VqKSTFA0HkGF5aYcl2Z4aXDHTVQi4NUKCzbiWtC8TU7/pVX9vSpoN9s3Ivwra@x6@wDmT82ExN4cARJk30y2VIj@dSMOPFyNHdu0EuuKoAlOcrMXFanetxA3GA1zHGF24WXHw "Python 3 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 266 bytes
```
from math import*
p=lambda n:{(n,)}|{tuple(sorted((i,)+m))for i in range(1,n)for m in p(n-i)}
c=lambda l,r=1:l and c(l,r*l[-1]//gcd(r,l.pop()))or r
g=lambda i,n:i and max(c([g(i-1,n)]+[*e])for e in p(n))or 1
l=lambda n,p=0,i=0:p-g(i,n)and l(n,g(i,n),i+1) or i and~-i
```
[Try it online!](https://tio.run/##PVDNboMwDL7nKXzDbsParJM2IWUvwjiwkNJoIUSBSt0Ye3UWsrL4ks/W92P7z/HSu9OynEPfQVePFzCd78O4Y17auntvanDFhI7T/D2NV281DnGsG0TDad8RnfsABoyDULtWo@Autbq15dHlhmamNi3LgxSFhdo1oDCinS1zUR0OrWowcPvge49EFAUCazeW4a4widPVN1RYtmjy1ajalztdJT9990tcwex/eu7lkRt5LHweaZG06ti40R/iZi8I0g5x8JObRd@8VnFDkIBHLvhjrNNaxNRFqw8d1kn2dn18flIZh/QTp4zYmsPxlOTLeNwO8kJ806SCQXxDVIgRKAEfjBvxnE1uhvwVpmGG6W5UaimHas5o@QU "Python 3 – Try It Online")
*Quite* verbose! With main function \$l\$ and its helper functions \$g\$ (which is the same \$g\$ as in the OP), \$c\$ (aka \$lcm\$), and \$p\$ (which returns the partitions of \$n\$).
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 24 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
╘J∙╢☼♥DÉ♀→⌂NP¶▐↓╚∞J¼╣øCû
```
[Run and debug it](https://staxlang.xyz/#p=d44af9b60f0344900c1a7f4e5014de19c8ec4aacb9004396&i=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A14%0A15%0A16%0A17%0A18%0A19%0A20&a=1&m=2)
Algorithm borrowed from Kevin Cruijssen's answer, can probably be optimized further.
]
|
[Question]
[
**Given a text input such as:**
```
THE QUICK
BROWN FOX
JUMPS OVER
THE LAZY
DOG
```
**render the following output:**
```
/\
\ \
/ \
/ /\/
/ / /\
/ / / /
/\ \/ / / /\
/ \ / \/ /
/ /\/ / /\ / /\
/ \/\ \/ / / / \
/ /\/\/ /\ / / / /\ \
\ \/\ / \ \/ / \ \/
\/\/ / /\/ / /\/
/ \/\ \ \
/\ / /\/\/ /\ \ \
/\ / / \/ /\ / \ \/ /\
/ / / / /\ / / / /\ \ / \
\ \/ / / / \/ / / / / / /\ \
/\ \ / / / /\ / / / / /\ / / / /
\ \ \/ / / / / \ \/ / / / / / / /
/ \ / / / / /\ \ / / / \ \/ / /\
/ /\/ \ \/ / / / \/ / / /\ \ / / /
/ / /\ \ / / \ \/ / / /\ \ \ / / /\
/ / / / \/ / /\/ /\/ / / / \/ / / / /
/\ \/ / / /\ / / /\/\/\ \/\/ / / /\ / / / / /\
/ \ / \/ / \/ \/\ / /\/ / / / \ \/ / / /
/ /\/ / /\ / /\ / / /\ \/\/ / \ \ / / / /\
/ / /\ \/ / / / \ / / / \ / /\/ \/ / / / \
/ / / / /\ / / / /\ \ / / / /\/ / / /\ /\ / / / /\ \
\ \/ / / \ \/ / \ \/ \/ / \/\ \/ \/ / / \/ / / \/
\/\/ / /\ \ / /\/ / /\/\/ /\ /\/ / / / /\
/ / / / \ \ \/ / \ \ / \ \ / /
/ / / / /\ \ \ / /\ \ / / \ \ / / /\
\ \/ / / \ \/ /\ \ \ \/ \/ /\ \/ / \/ /
\ / / /\ \ / / /\ \ \ / \ / /\/\/
\/ / / \/ / / \ \/ / / /\ \ \/ /\
/ / /\ / / \ / / \ \/ / /
\ \/ / / / /\ \/ /\ / /\/ /\ \/
\ / \ \ / \ / \ \/ / \
\/ \ \ / /\ \ / /\ \ / /\ \
\/ / \/ / / / / / / / / /
/ /\ / /\ / / / / /\ / / / / /\
\/ / / \ \ \ \/ / / / \ \/ / / /
/ / \ \ \ / / / /\ \ / \/ /\
\/ /\/\/ / \/ / / / / \/ /\/\/ /
/ /\/\/ /\ \/ / / /\ / /\/\/
\ \ / / /\/ / / \ \/ /\
\ \ / / /\ \/\/ / /\ \ / /
\/ \ \/ / / \ \/ \/
/ / / /\/ /\
/ /\/ \ \ / \
\/ \ \ / /\/
\/ / \/\
/ /\/\/
\/ /\
/ /
\/
```
# Rules
* The program only needs to work for upper-case A–Z, spaces and newlines. Everything else is allowed to produce undefined behaviour.
* The program is allowed to output any number of extraneous leading or trailing spaces or newlines, as long as the block of text is contiguous as shown.
* Your output may use ‘/’ (U+002F) and ‘\’ (U+005C), or (for prettier Unicode rendering) ‘╱’ (U+2571) and ‘╲’ (U+2572).
* The font must look exactly as shown above. The example contains all the letters A–Z. Arnauld has kindly provided [a bitmappy version of the font here](https://tio.run/##lZNLDsIwDET3vQvvThWwgAUgQF3lAJygB@QigEgRTjxu2ipq2kk89vhz7If@tr0eLvfN6bzbvz7Pc3zklfJGaiPui2lPUCGQ3/9/FI/xQcutd0FwklcnbVSQ/iQSNAFGQBQDPymGwGP2siL60ncya2XAdQJ9thOEDHNxWEZVo7YolMXK6tQNF1ublhO9g68NLJPh5FCIWDJDEMyPRK3d3BxZVk0hK5DwqSjvvQE).
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 418 bytes
Expects a list of strings.
```
a=>(m=[]).map(r=>r.join``,a.map((s,Y)=>(F=y=>~y--&&F(y,Buffer(s).map(c=>(G=x=>x^'2672020001'[c*31%87%33]^4&&G(-~x,(m[X=(a.length-Y)*6-++y+o,Y*6+y+o++]||=Array(X).fill` `).splice(X,2," /"[g(~-x)^g(x)]," \\"[v^g(x,y--)])))(g=x=>v=parseInt(['757553535371117355537131771311715575575511111444575535511117hrlhhhjlph75557353117555f3535571747722225555755552hllla552555572274217'[c*5-325+y]],32)>>x&31>>y&1),o=0)))(5))).join`
`
```
[Attempt This Online!](https://ato.pxeger.com/run?1=JVFtb5swENa-9lcgpBI7GIZtHPeLkdqtSbu1y9aXLRklAmW8pHIggrQCqcof2Zeo2n7U9mtqh7N199zj504n3-8_ZfUr3b9m4u_TNnNO_r97TUQA1iKMoLtONqAWQe0-VqsyjlFyYECD5lBpxqITwa5zHMsagw6dPWVZWoOmL1sqwUS0ImgXAzLixCOe5-FBuBxSfHzCjymNFr5lTYCzaxFYhzMBElemZb4tnDkcjhzb7uwKzYcjHW07enkRp3WddGAG3WwlZWzE0G02crVMwQwRZBrvzTAHO6eFixy0MFLMw4MZPusMqSlhBCEEuZ7pWWySukkvyy0IB5xxxqg-HGPMKWMaUcy1wxwz_a4u1ub7fi8_pLyoZVEUj3JTKJKpWl2hUKb7MY65zzlRxtihBWOkkFImKh4YQrhPMNe_whxKmN1FEaIEBkFrURwEnYUhqoSnB2fK9Xs4ivtV_Zssq7KpZOrKKgcZCM27i3Pj2_3lh88mMs9upj--GOPpTOFP99dfb43p9_MblWjR1enPuYIfpxNT_Urfbr_v4xs)
### Font encoding
Each character is horizontally mirrored, right-aligned and converted to five 5-bit values expressed in base-32.
For instance, `N` is encoded as `"hjlph"`:
```
X...X 10001 17 'h'
X..XX 10011 19 'j'
X.X.X -> 10101 -> 21 -> 'l'
XX..X 11001 25 'p'
X...X 10001 17 'h'
```
All letter encodings are concatenated together to get a single lookup string of 130 characters. The encoding of the space (`"00000"`) is not explicitly stored.
```
7575535353..hrlhhhjlph..5572274217
\___/\___/ \___/\___/ \___/\___/
A B M N Y Z
```
To get the state of the 'pixel' at \$(x,y)\$ of the character whose ASCII code is \$c\$, we do:
```
parseInt([ lookup_string[c * 5 - 325 + y] ], 32) >> x & 31 >> y & 1
```
This code supports \$-1\le x\le 5\$ and \$-1\le y\le 5\$ so that a 1-pixel character border can be tested as well.
### Width encoding
Right padding included, most characters have a width of 4. The exceptions are as follows:
* `I` has a width of 2
* `Q` has a width of 5
* `M`, `N` and `W` have a width of 6
* the space has a width of 3
We use a lookup string, a hash function and a XOR with 4 to turn any valid ASCII code into the corresponding width:
```
'2672020001'[c * 31 % 87 % 33] ^ 4
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70kLz8ldcGCpaUlaboWN-dH6-npORYVJVZqGJlr6mWnVhZraMbq5SYWaJQp2NoplCnYA7G2gpmJgpWCsZGmXlp-kWticoZGMki2mktBITk_rzg_J1UvJz9dI1lHwSvY30-vuKQoMy89M61SIxjM0ksrys91zkgscgbarZGsqamjoG5kZm5kYGRgYGCoHp2soKVgbKigqmBhDiSMjWMV4hRMNK25ajUhzoS6FuZqAA)
### Drawing algorithm
Basic principles:
* We draw by filling a matrix \$m\$, whose exact size is decided on the fly.
* We compare the pixel at \$(x-1,y)\$ with the pixel at \$(x,y)\$ to figure out if we must draw the `/` boundary.
* We compare the pixel at \$(x,y-1)\$ with the pixel at \$(x,y)\$ to figure out if we must draw the `\` boundary.
Pseudo-code:
```
for each string s at index Y in a[]:
for y = 5 to 0:
let o = 0
for each character c in s:
for x = 0 to width(c) - 1:
let X = (a.length - Y) * 6 - y + o
let R = Y * 6 + y + o
if pixel(c, x, y) != pixel(c, x - 1, y):
m[R][X] = "/"
else:
m[R][X] = " "
end
if pixel(c, x, y) != pixel(c, x, y - 1):
m[R][X + 1] = "\"
else:
m[R][X + 1] = " "
end
o = o + 1
end
end
end
end
```
[Answer]
# [Funciton](https://esolangs.org/wiki/Funciton), non-competitive
Big dramatic reveal! This coding challenge was actually suggested to me by a friend. I originally wrote it in C# but then decided that this might be an excuse to flex my old Funciton muscles again. I haven’t written Funciton code in several years and this was a refreshing trip down memory lane.
If I had to do it all over again, I imagine I might implement this very differently. This is the implementation I came up with on my own before being influenced by the other answers posted here.
[**Try it online!**](https://tio.run/##5V1LbxzHEb7vr@i7EGCme3oegCwjiR3nYUeOEud1o621IyQhCZqGczKoBWIkBg@z1tK7YkgTCAjoEAlJgEVyySmXxP4Z/CPK7Oz0THV3VXfPcJeyEYOyuNvPqqlX11c9eveD3XceHO7tPn/O6P@uTmZXJ2X/n/l68KOr2dOr2dHq5@SzkXOd6dXHjxh7fW/v1x/ss8Odt38zrr9dN15czRZXn/9l9YV7ltNBuz1fD35cb7Xe8MmZax1i9dlxQ@tsqX75f/gpR2FMGfyzEW6W/Z/izezTw77Jpva7HMQk3/TLXhx3zrbcKI8syzU3eusd5uSY9QCztz0a67edrsH9hnBtyuJ0bXGPOuONP6G1pfwzyztDjYxeIn1XfxJnv3qadcd8Mx2Tth93T@j1MgTnDN9zXgv7stOD9rPe9dw3mhxnfPaOuLlBA0aMrh9uOGzl1WxWP@EF8dnuh/Vwt16vGWkdwcjojZ0Hu2z/YO@9g53fdpGRyz3ARqxjYzKMFvxb39ezQF9X92yEQNF3nZjtxdM/6xeErGZo/vS2MbT3XDrXowifof3tNRZOQstBkuCJGACbWlZh/hLu9uQzzKevp0DsypyyNnNkyJyaQu0xeIG5q//A2aDI9CLVmoRkfeXYo9ZtXrL/PFQfKo/ZmqNm81OZJXHReFuRS8GT@sO6MeZZ0yTTuCjalm5o295Os27jMpfB/U31LM2NcSliHvNcG0DSj7jERf3bJe7wIDuSLM2FWjXnMoLsSIq0aUpSLhODvKzgiRoqsiyP4UghkuD@GnWwbfUYMh5lqQhhhK0WjQYuGw1k5koRz6KoWSmTFY2QhCxTm82jIucGMVFecN60p5wLCUaKSnYyu38ct/3jrJvPoYd1T/UI4jgu8iKLAgbajJkyqCFXf3xmhJmlzpgiTrhiTBQllWxD8nLVVKSpSA1CRdE9vbgQaQpZGovUZKTgRSaVACaJgP1NJYvTpNGJqm9apFEuM7K7zYRTt5I0@rjQWRELtecVW0SW5FDMc7WdNC1yYep/tUdFWlo9SDgyF0Vhsi6VcaTsBY@V7Wj1NIGqWQmGUNtKkkpJEgmFV9dH3K971aNaotMBXvBY0/BmO9VTzRNpirsQQNejiBeaYiG2JOOtVEkhE9hfVLKokV6tl7dKUclUFsNmXRsp0ifsy/NGB2y6K5FUB7I85kIzCwVTTZUwx8xUcxFJ1R5JXjD4yDm3pL9Iu6XSNBOwf1oUGVw5l7Fot1V0Z2K1a03ZCLoNmTdJbzXkkjotwQYwBPE0Zs@QBazZKyZGBlX95xBxngMJ6UGkMdFKif0sXpvlJ0ZuB4ZBXQhgaKAWyaOtxhR4n0qHckPHAsbwLImgT6a32WlKFT/5GdLEZ1OEEWhEfslebt0TFeJbfRxT2n2rRxllkbQYFDi2sotMY1QIGWACmQrBvGw7RQ6V2AnModR2izYUa3cq8LCRnq16bEb/A6n9GZVfdIRL6QJ70@d8YupBJIafZQk5DJqNUrMBI/tsH112aGoiQFG8/YiJQ2ekprw2SV6SvaIfvBLlBTZBwmwL0J9f7Le9A4cPuD7T2AYEfcg0W976NUejZ5ob2PLs6waMo4IJxHN7zLoOn3G53s52N1EdcLS16gDi8E6won92/isjpte1HIp0h8A3Yj@iptyEJJQbkbDlRhYeXOlgZAs0ZRy57eIlWfbQowQhuAYhoNwipHhhE3UO3Zl@5HYeRtFAc3IOKjAIrjAIKKigSiI2VDvB1bl35DK7BNRvZ3HDSgQG1AiEF1AElhlsqzbBzcshlQT@9j6dB1Yt1FS51drKZuBmzYEQl9o2FPTvdzH6dOWwkoMSXbWhe5qLDCrscJNNg@w6kjbMOS19KwZzXtuF4kKiMI6eWPXmEWx42t0Mnn6TmL3N2TySKNKt49A2orbqr@AYY6zNJ72vAeaZ62TWOmpuOA@FttsUxlIBSivYUOhYWot567iawtZknrXAdyxyB4VV3yRH59KB7A787sZ2@4JrdgC68FHYUiGjPAaIsgZs6/CZQqjTqGiB7xiiI26pnKZ53I40gbkOeat2UER2/USUtu0yzjRYjWci8j1R0VZnVDvmkFsQr9Zhs6Y9UihSxdlYL1XAZK8oOgmp5tMw3w5nW@G/NgAeFbJDfTMptCoRLg1pQzSzhbizpEgg8L6ColttynlmgomVVoi8LW2JNFQUk7@sEDJtaxwiCSVIcsXFFaSfC1OCKgHiai8Jj4X2LGMpIg@VUaFG53mRRlBreJR1/IO7amZPokJRKZM0g3LQVVmA55FlLVTNk1xCS1DwuJ0rjVJuSmyS55FqLzLJoRxEiV9iuexwZAgWr6DEogVzRZ4JE0iOk6xtT2UimcahIsodQLKUXFtL5t1cIrHXEoVox4o41UDrrLJ/3E1lMALcF7kdiBgXqan/fee4mX0mUZS5OOsGgr2Abhjom1fqlPUBije0biYyKX3Uz/yQUhhm2w/fFXEu2RBseEv7KZIi80iKN@1/o1Dw9lYlKMdyf9tDfTe6goOi2cYRr20AvTe2G5JT28d5NzRzMAWbhHWvNaPt7YddgkEuxLxozPeFoM9IjMjYK@N39u6P2eGvxuztnffH30gYkqw1rizrJZsbAnx9uK@184Px/sH4/fHu4c7hg73duu3jR/je62vSnzzcN0jbBJZIgr5YnHqdn3NGYw3aFe36lvbXGyDujxoblo2qxj@yyo3X4i6MmZ9u7qKwDw0yc53G7sI9ALyTwkHB/Utu6LHZtIVBwFuaTnYS1WfoFdr6bKg2dueOd2eOp@HKaw@QLuzSHXaZBcEFrZRzgySYD0KndxlAS2@HN3fdyEEkpzbrhvVCMMQRAkOstIY3CKBeZ6nuW7lYaUfr66MZY/fGu/fHB2ynlRnflYH6cPLJ77u7VtXfKYr0qZ2fWhu5mp0FAw6l/w4DpOdg70O29y47HP/usHJQn673dUzauDUlF4SOPgY6d6ahg5cQkXNc4NO37PuMozFLl5H@9z8Dtbq79tnbO8LSXiDdjVC5ngsAxFdPopD1afvCcjD67y91gmgVw9I2WY9hcReE1ej25meJPEc66sCsmvuzpjxoGQVcHr3QY2RkKjk/@ldLVwn6GfdWrUdp780ec6bW@MOnph2w9v@kM@Otv9OvUcxNs9cmOI@h2tbR5QV5BbjjwAS5/TXRIrVL9uUzIH3//Qe4R4plbW61nRfY3CNgKCuBV2UbnaeqSyxMEUfM5LogSdM36@za0YrIpJ6VCJE6QsdQeXe@6@jcIqyj6hhXIUumdbpK870pbVLl2FbdRfv1gvAe9eensCd1eRtRimrZL04c1S2Y3MCo6rJTGrDpS3b7NrhrovosiHc6lebdWOSxTRBLpzMKuOJKrR5@Du5TR6h5LnGZD6ghKAPu7dacW3iEFaTWoeU4CfC3E01jJoxZf1tsVGULhuPz3zGdEH6i3rj2SjLd4OF8R89glqAtu7vwuIi9rOnIBGdjb7aSEYBVlqNtZ6neqrTeRZM30N8qYoNOvvyHPuJPAZZvzYiZyTsXH7@cwg/PNBfV6wCFbUYxRHsTHCKqrojYYYoWqNibTOvHRFz86RDjCCq8vbORrT@6dVayaVLorf3tWVEb5g3siO1J4BGAWRzoNGWtC@1N/vrFgxcu47rm2wwJkjRRfgrMcUgyUR2uSIdgBFRHwIGsvVkdU2FDGXGssI8ZTI8ZG9zQjo4swYV3/T1JYvt4hAn2mTGLP4uBx5/Bb7eca9Fjm3d6ZBxwiCODMzfvLhec1Vfm0ZJBK2Yne9cxfFRksYzthEyp5dGuzv4GchD1b6@Nd8cHO4djPE/eM9@6QLNkKVzT3v1pyPufzrSslmW3FTX7O/fvP9h9j8ydB2XsserlbWadV1Tp4d3SOnQFJxXOg0V0/lW6mBP0@kyqEILIRZjgQi0Qbx6M98e795W4Yy50wC27ke6mbkG38tjhVlojvv7fTp1ea99FAZ1zdXgZ7HfLfgQEhHPHrfc@NYL5FRlWfnASkO33h1rUdm1LiZ7XzcAmTKXOyeP/cQ@op08WEXlgJsWdTTWDsy/@jkYkPd9bd4wkDb2Bpqt2hbj188iYUacStcPEKVFFIwzLWOJJqpmVbrpkHxlRF2Ua9MPk@rIOfBPUYmSK4ZHTVhHwLTg3rW99eVRUL/E5I3PwJXOd/8z3Y@sygbMr/GpDaRN4DE6xE4c56EJD@2n2PUErYWuDeQ9LSWNlCwYaroeZgiU4a8yoYcYHZsy3DPSmjDoCYlJLAIW3NadUUtdgKNsQnj3Vb/adUVhxs/JtxFcCyV3d9ouV210g6NmEJIQC7cjrirqfWLjeUjrCE@pdsYTrTYTK/bpPxwRRE@NkgBg4Kw/uifs1chD8QWXfsTuibf6@Hv34rzBh1UewEDCResErsXENSFBbrr7kWrrWfTwNEiQfUkRnWkNSVJAkBC04MjABDHRHnaFTUyY67INhQPWwOic@NXwddKZ9IiZl1m2j1nmwO0Z@1IE9ar1RX@aXySGZPeYp1ZjjD84IFnUzeEloC9AKsh292kglSbGgc4Ek8qYMgtW3PE@lJoqw1lS4MHEmci3CMNNWujwxVkeBp31LZ3a9e6sKlffBEq@lESEeefo5wcxwYBo/AS387@iySIXW1R/RTcL7ObFLBdZPHTQByGHiOOotUPjvluEyFLn@vJKBsYZ0cZ5xCF5p6MqChBaY4/iydJ766LcEUVsyUzeuV3wF4GkTdGM2EjCxHl77KlPNTbkl2VlE2858x4kuILi7Dy/DtoVHZ5RLsZ/7R6jsUlls6ulrGXzoXzwYWFcwMtUO4rZxMsJcH6DaV0o9x9AJQ3wnnoZijsxDY2MMVJpGRc1g20XALKDguKSJgWAUZuucjoK4xkhBnUjKZhRaM4zGxVhV8oQ8ExwHF2iX3gw0@TkgevNcxHF5AVC9ahVnYUbCBdDT6Yomu2iE7U0y8gIr3vJczPELj3Vs02NzIpdSWqUnQ6JyX@BGOTjfk7bDZfLCHBWWYw6mZAz/By1wQB10e0K8hYlKmmEYH4SuMRfKNKEhj6@@pD2u7qBAGoFbFlp1twdnH/kBwQB8xC5xAsEL2CCZr2@YOCVeDO5@8294BdUZ/bY2yxPOXDGwLwItA10B/dKfhdMusl7Wsx86a5fQOLEfvXCsZC/ivtKi/79qyRhjtPd02rBrLdYo5oVdIamMx4X/nwb0ruK6REIhKIMXvObzXjx//pPvvsp@9Nb3vv2D0bfu3f3ZD9l37v589P233njzx@zuT1@9N1o1v/7NX/5i9Mrd1/4H)
```
╔═════════════════╗ ╓┬──╖
║↓ Lookup table ║ ╟┘➫ ║
╚═════════════════╝ ╙─┬─╜
┌──┴──────────────────────────────────────────────────────────────────────────────┐
┌─────────────────────┴──────────────────────┐ ┌──────────────────┴─────────────────┐
│ ┌────────────┴───────────┐ ┌─────────┴────────┐ ┌────────┴────────┐
│ ╔════╗ │ ╔═══╗ ╔════╗ │ ╔═══╗ ╔═══╗ │ ╔════╗ ╔═══╗ │ ╔════╗ ╔═══╗ │ ╔═══╗ ╔═══╗ │ ╔═══╗
│ ║ 16 ╟─┬────┴────┬─╢ 8 ║ ║ 16 ╟─┬─┴─┬─╢ 8 ║ ║ 4 ╟─┬─┴─┬─╢ 16 ║ ║ 8 ╟─┬─┴─┬─╢ 16 ║ ║ 8 ╟─┬─┴─┬─╢ 4 ║ ║ 2 ╟─┬─┴─┬─╢ 1 ║
│ ╚════╝┌┴┐ ┌┴┐╚═══╝ ╚════╝┌┴┐ ┌┴┐╚═══╝ ╚═══╝┌┴┐ ┌┴┐╚════╝ ╚═══╝┌┴┐ ┌┴┐╚════╝ ╚═══╝┌┴┐ ┌┴┐╚═══╝ ╚═══╝┌┴┐ ┌┴┐╚═══╝
╔═════════════════╗ │ └┬┘ └┬┘ └┬┘ └┬┘ └┬┘ └┬┘ └┬┘ └┬┘ └┬┘ └┬┘ └┬┘ └┬┘
║↓ Main program ║ │ │ │ │ │ │ │ │ │ │ └────────────┐└┐ ┌┘
╚═════════════════╝ │ │ │ │ │ │ │ │ │ └──────────────┐ │ │ │
│ ┌───────┴───────┐ │ │ └─────┐ ┌─────┘ └───────┐ │ └───────────────────┐ │ │ │ │
╔════╗ ┌───╖ ╔═══╗ │ ╔═════╗ ╔══════╗ │ ╔═══╗ ╔═════╗ │ │ ╔═════╗ ╔═════╗ │ ╔═════╗ │ │ ╔═════╗ ╔═════╗ │ │ ╔═════╗ ╔════════╗ │ │ │ │ │
║ 10 ╟─┤ ǁ ╟─╢ ║ │ ║57419║ ║385324║ │ ║127║ ║56199║ │ │ ║57417║ ║57419║ │ ║25859║ │ │ ║57417║ ║57419║ │ └──┐ ║57419║ ║25312128║ │ │ │ │ │
╚════╝ ╘═╤═╝ ╚═══╝ │ ║47683║ ║282504║ │ ║496║ ║46254║ │ │ ║79243║ ║37781║ │ ║43344║ │ │ ║79243║ ║37781║ │ │ ║37781║ ║56720763║ │ │ │ │ │
╔═══╗ ┌─┴─╖ │ ║02700║ ║754621║ │ ║773║ ║80982║ │ │ ║08922║ ║62235║ │ ║36197║ │ │ ║08911║ ║62172║ │ ╔═════╗ │ ║62176║ ║11198970║ │ ╔═════╗ │ │ │ │
║ 0 ╟─┤ ≭ ╟─┬─┐ │ ║91420║ ║004585║ │ ║380║ ║96636║ │ │ ║39781║ ║19366║ │ ║71362║ │ │ ║32975║ ║24436║ │ ║57419║ │ ║16428║ ║26960857║ │ ║57419║ │ │ │ │
╚═══╝ ╘═╤═╝ └─┘ │ ║13362║ ║913748║ │ ║488║ ║66983║ │ │ ║52695║ ║61768║ │ ║83996║ │ │ ║65107║ ║21417║ │ ║47644║ │ ║21732║ ║44720451║ │ ║37781║ │ │ │ │
┌─┴─╖ │ ║17373║ ║829211║ │ ║444║ ║78457║ │ │ ║33243║ ║30029║ │ ║77254║ │ │ ║77280║ ║53549║ │ ║34204║ │ ║28458║ ║11713714║ │ ║62235║ │ │ │ │
│ ʝ ╟─ │ ║1297 ║ ║812321║ │ ║9 ║ ║1361 ║ │ │ ║0305 ║ ║0529 ║ │ ║82262║ │ │ ║9697 ║ ║6673 ║ │ ║69971║ │ ║8513 ║ ║89 ║ │ ║19366║ │ │ │ │
╘═╤═╝ │ ╚══╤══╝ ╚═══╤══╝ │ ╚═╤═╝ ╚══╤══╝ │ │ ╚══╤══╝ ╚══╤══╝ │ ║05066║ │ │ ╚══╤══╝ ╚══╤══╝ │ ║31884║ │ ╚══╤══╝ ╚═══╤════╝ │ ║61766║ │ │ │ │
╔═╧══╗ │ │ ┌─┴─╖ │ │ ┌─┴─╖ │ │ │ ┌─┴─╖ │ ║58254║ │ │ │ ┌─┴─╖ │ ║27401║ │ │ ┌─┴─╖ │ ║15326║ │ │ │ │
║ 10 ║ │ └──────┤ ? ╟──┘ └────┤ ? ╟──┘ │ └─────┤ ? ╟──┘ ║60705║ │ │ └─────┤ ? ╟──┘ ║6737 ║ │ └──────┤ ? ╟────┘ ║5633 ║ │ │ │ │
╚════╝ │ ╘═╤═╝ ╘═╤═╝ │ ╘═╤═╝ ╚══╤══╝ │ │ ╘═╤═╝ ╚══╤══╝ │ ╘═╤═╝ ╚══╤══╝ │ │ │ │
│ │ ┌─┴─╖ │ │ ┌─┴─╖ │ │ │ ┌─┴─╖ │ │ ┌─┴─╖ │ │ │ │
│ └─────────────┤ ? ╟────┘ └───────┤ ? ╟──┘ │ └───────┤ ? ╟──┘ └─────────┤ ? ╟──┘ │ │ │
│ ╘═╤═╝ ╘═╤═╝ │ ╘═╤═╝ ╘═╤═╝ │ │ │
│ │ ┌─┴─╖ │ │ ┌─┴─╖ │ │ │
│ └───────────────────────────┤ ? ╟────┘ └────────────────────────────┤ ? ╟────┘ │ │
│ ╘═╤═╝ ╘═╤═╝ │ │
│ │ ┌─┴─╖ │ │
│ └──────────────────────────────────────────────────────────┤ ? ╟──────┘ │
│ ╘═╤═╝ │
│ ┌────────────────────────────────────────────┐ ┌─┴─╖ │
┌───────┴────────────────────────────────────────────────────┤ │ ┌─┤ ? ╟────────┘
│ ┌─────────────────────┐ ┌───────────────┴────────────────┐ ┌────────┴────────┐ │ ╘═╤═╝
└──┤ ╔════╗ ╔═══╗ │ ╔════╗ ╔═══╗ │ ╔═══╗ ╔════╗ │ ╔═══╗ ╔════╗ │ ╔═══╗ ╔═══╗ │ ╔═══╗ │ │
└─┬─╢ 16 ║ ║ 8 ╟─┬─┴─┬─╢ 16 ║ ║ 8 ╟─┬─┴─┬─╢ 4 ║ ║ 16 ╟─┬─┴─┬─╢ 8 ║ ║ 16 ╟─┬─┴─┬─╢ 8 ║ ║ 4 ╟─┬─┴─┬─╢ 2 ║ │
┌┴┐╚════╝ ╚═══╝┌┴┐ ┌┴┐╚════╝ ╚═══╝┌┴┐ ┌┴┐╚═══╝ ╚════╝┌┴┐ ┌┴┐╚═══╝ ╚════╝┌┴┐ ┌┴┐╚═══╝ ╚═══╝┌┴┐ ┌┴┐╚═══╝ │
└┬┘ └┬┘ └┬┘ └┬┘ └┬┘ └┬┘ └┬┘ └┬┘ └┬┘ └┬┘ └┬┘ │
╔═══╗ │ ┌──────┘ └──────┐ └┐ ┌┘ │ └───┐ │ └───────────┐ └┐ ┌┘ │
║837║ ┌────────┴────────┐ │ │ │ │ ┌───────────┴─────┐ │ └──────┐ └┐ │ │ │
║432║ ╔═════╗ │ ╔═════╗ ╔═════╗ │ │ ╔═════╗ ╔═════╗ │ │ │ ╔═════╗ ╔═════╗ │ ╔═════╗ ╔═════╗ │ │ ╔═════╗ ╔═════╗ │ ╔═════╗ │ │ │ │
║805║ ║56199║ │ ║57419║ ║57419║ │ │ ║56204║ ║56199║ │ │ │ ║56204║ ║57419║ │ ║57419║ ║57417║ │ │ ║56199║ ║56204║ │ ║25859║ │ │ │ │
║150║ ║16423║ │ ║47683║ ║47644║ │ │ ║21587║ ║46138║ │ │ │ ║21548║ ║47644║ │ ║37781║ ║79243║ │ │ ║16423║ ║21587║ │ ║43343║ │ │ │ │
║183║ ║50812║ │ ║02700║ ║34204║ │ │ ║36609║ ║75184║ │ ╔═════╗ │ │ ║68109║ ║34204║ │ ║62235║ ║09099║ │ │ ║50635║ ║51721║ │ ║27309║ │ │ │ │
║327║ ║18427║ │ ║91420║ ║69971║ │ │ ║90066║ ║41781║ │ ║57417║ │ │ ║99683║ ║69948║ │ ║19366║ ║48636║ │ │ ║09595║ ║67539║ │ ║22544║ │ │ │ │
║828║ ║74945║ │ ║13364║ ║58272║ │ │ ║25838║ ║38014║ │ ║79243║ │ │ ║79356║ ║80052║ │ ║52971║ ║39834║ │ │ ║66024║ ║42131║ │ ║21530║ │ │ │ │
║094║ ║88960║ │ ║32075║ ║67052║ │ │ ║24098║ ║54677║ │ ║08911║ │ │ ║07744║ ║24853║ │ ║92198║ ║60629║ │ │ ║48808║ ║97528║ │ ║04309║ │ │ │ │
║25 ║ ║8161 ║ │ ║6193 ║ ║3873 ║ │ │ ║1473 ║ ║6545 ║ │ ║32908║ │ │ ║9697 ║ ║5521 ║ │ ║5873 ║ ║3473 ║ │ │ ║3937 ║ ║3169 ║ │ ║76132║ │ │ │ │
╚═╤═╝ ╚══╤══╝ │ ╚══╤══╝ ╚══╤══╝ │ │ ╚══╤══╝ ╚══╤══╝ │ ║09671║ │ │ ╚══╤══╝ ╚══╤══╝ │ ╚══╤══╝ ╚══╤══╝ │ │ ╚══╤══╝ ╚══╤══╝ │ ║04007║ │ │ │ │
│ ┌─┴─╖ │ │ ┌─┴─╖ │ │ │ ┌─┴─╖ │ ║82407║ │ │ │ ┌─┴─╖ │ │ ┌─┴─╖ │ │ │ ┌─┴─╖ │ ║73755║ │ │ │ │
└────┤ ? ╟──┘ └─────┤ ? ╟──┘ │ └─────┤ ? ╟──┘ ║3185 ║ │ │ └─────┤ ? ╟──┘ └─────┤ ? ╟──┘ │ └─────┤ ? ╟──┘ ║94977║ │ │ │ │
╘═╤═╝ ╘═╤═╝ │ ╘═╤═╝ ╚══╤══╝ │ │ ╘═╤═╝ ╘═╤═╝ │ ╘═╤═╝ ╚══╤══╝ │ │ │ │
│ ┌─┴─╖ │ │ ┌─┴─╖ │ │ │ ┌─┴─╖ │ │ ┌─┴─╖ │ │ │ │
└───────────────┤ ? ╟────┘ └───────┤ ? ╟──┘ │ └───────────────┤ ? ╟────┘ └───────┤ ? ╟──┘ │ │ │
╘═╤═╝ ╘═╤═╝ │ ╘═╤═╝ ╘═╤═╝ │ │ │
│ ┌─┴─╖ │ │ ┌─┴─╖ │ │ │
╔═════════════════════╗ └───────────────────────────┤ ? ╟────┘ └───────────────────────────┤ ? ╟────┘ │ │
║ Decode the base-4 ║ ╓┬───╖ ╘═╤═╝ ╘═╤═╝ │ │
║ representation ↓║ ╟┘⊁p ║ │ ┌─┴─╖ │ │
╚═════════════════════╝ ╔═══╗ ╙─┬──╜ └─────────────────────────────────────────────────────────────────┤ ? ╟──────┘ │
╔═══╗ ┌───╖ ║ 3 ╟───┬──────┴───────────┐ ╔════╗ ┌────╖ ╘═╤═╝ │
║ 2 ╟─┤ = ╟─────────┐ ╚═══╝ ┌┴┐ ╔═══╗ ┌────╖ │ ║ 21 ╟─┤ >> ╟───────────┬─────────────┐ └─────────────────┘
╚═══╝ ╘═╤═╝ ╔════╗ │ └┬┘ ║ 2 ╟─┤ >> ╟──┴──────────┐ ╔═══════════════╗ ╚════╝ ╘══╤═╝ ╓─┴─╖ ╔═══╗ │
│ ║ 32 ║ │ │ ╚═══╝ ╘═╤══╝ │ ║ Render a ║ ┌─┴─╖ ║ ⊅ ║ ║ 6 ║ │
│ ╚═╤══╝ ├───────────┴─┐ ┌─┴─╖ │ ║ row of text →║ ┌───────┤ ⊅ ╟─────┐ ╙───╜ ╚═╤═╝ │
╔══════╗ ┌─┴─╖ ┌─┴─╖ ┌─┴─╖ ┌────┴────────┤ · ╟────────────┐ │ ╚═══════════════╝ │ ╘═══╝ ┌─┴─╖ │ │
║ 9585 ╟─┤ ? ╟─┤ ? ╟─┤ = ║ │ ╘═╤═╝ │ │ ┌───╖ │ ┌─────┤ · ╟─────────┐ ┌─┴─╖ │
╚══════╝ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ │ ╔════╗ ┌─┴──╖ │ │ ┌─┤ ‼ ╟─┐ │ ┌───╖ ┌─┴─╖ ╘═╤═╝ ┌───╖ ├─┤ − ║ │
╔════╧═╗ ┌┴┐ ╔═╧═╗ │ ║ 21 ║ ┌──┤ ⊁p ╟────┐ │ │ │ ╘═╤═╝ │ └─┤ ʭ ╟─┤ ȶ ║ └─────┤ + ╟─┘ ╘═╤═╝ │
║ 9586 ║ └┬┘ ║ 1 ║ │ ╚═╤══╝ │ ╘════╝ │ │ │ ┌─┴─╖ │ │ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ ┌─┴─╖ │
╚══════╝ │ ╚═══╝ ┌┐ ┌─┴─╖ ┌─┴──╖ │ ┌─┐ │ │ │ ┌─┤ · ╟─┘ ┌─┘ ┌─┴─╖ ┌┬┘ ┌───╖ ╔═══╗ ┌─┴─╖ │ ɕ ║ │
└─────┬───┤├─┤ · ╟─┤ << ║ │ ├─┘ ┌──┴──┐ │ │ │ ╘═╤═╝ │ ┌───┤ · ╟─┘├──┤ ⁞ ╟─╢ 0 ╟─┤ ? ╟─┐ ╘═╤═╝ │
┌──────────┐ ╔═══╗ ┌─┴─╖ └┘ ╘═╤═╝ ╘═╤══╝ │ ╔═╧═╕ ┌─┴─╖ ┌─┴─╖ │ │ │ │ │ │ ╘═╤═╝ └┐ ╘═══╝ ╚═══╝ ╘═╤═╝ │ ┌─┴─╖ │
│ ╓┬──╖ │ ║ 0 ╟─┤ ? ╟──────┘ └────┴─╢ ├─┤ · ╟─┤ ? ╟─┘ │ │ ╔═╧═╕ ╔═╧═╕ ┌─┴─╖ ┌─┴─╖ ┌─┴─╖ ─┘ └─┤ · ╟─┴─┐
│ ╟┘⊁ ║ │ ╚═╤═╝ ╘═╤═╝ ╚═╤═╛ ╘═╤═╝ ╘═╤═╝ │ └─╢ ├─╢ ├─┤ · ╟─┤ ʑ ╟─┤ ʭ ║ ┌─┬─────────────┐ ╘═╤═╝ │
│ ╙─┬─╜ │ │ ┌─┴─╖ └─────┘ │ │ ╚═╤═╛ ╚═╤═╛ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ │ │ ┌───╖ ┌───╖ └───┘ │
│ ┌─┴──╖ ╔═╧═╕ └───┤ ? ╟───────────────────────┐ ╔═══╗ ┌─┴─╖ │ │ ╔═╧═╗ ┌─┴─╖ ┌─┴─╖ └───┘ └─┤ ⊁ ╟─┤ ➫ ╟───────┐ │
└─┤ ⊁p ╟─╢ ├─┬─┐ ╘═╤═╝ │ ║ 0 ╟─┤ ? ╟─┐ │ └───╢ 0 ║ │ ȶ ╟─┤ ? ╟─┐ ╘═══╝ ╘═══╝ ┌┴┐ │
╘════╝ ╚═╤═╛ └─┘ ─┘ │ ╚═══╝ ╘═╤═╝ ├─┘ ╚═══╝ ╘═╤═╝ ╘═╤═╝ │ ╔═════════╗ └┬┘ │
╓───╖ │ ╔════════════╗ │ └─ │ ╔═╧═╗ └─ │ ║ 2097151 ╟──┴─┐ │
║ ✰ ║ ║ Generate ║ └─────────────┘ ║ 6 ║ │ ╚═════════╝ ├─┘
╙─┬─╜ ║ padding ↓║ ╚═══╝ └─────────────────────────────┘
┌───┴───┐ ╚════════════╝ ╔═══════════╗ ┌───────────────────────────────────────────────────────┐
│ ┌─┴─╖ ┌───╖ ╔═══╗ ║ Prepend ║ │ ┌───╖ │
│ │ + ╟─┤ ♫ ╟───────╢ 0 ║ ║ a row ║ ┌─┴─┤ < ╟─────────────────┐ │
│ ╘═╤═╝ ╘═╤═╝ ┌─┐ ╚═╤═╝ ║ of text →║ │ ╘═╤═╝ ┌─┴─╖ │
│ ╔═╧═╗ │ ┌─┴─╖ ╔═╧═╕ ╚═══════════╝ │ ┌─┴─╖ ┌─────────────┤ · ╟─────────────┐ │
│ ║ 6 ║ └───┤ ɱ ╟─╢ ├──────────────┐ │ ┌─┤ ? ╟─┤ ┌───╖ ┌───╖ ╘═╤═╝ │ ╔═══╗ ╓───╖ │
│ ╚═══╝ ╘═══╝ ╚═╤═╛ │ │ │ ╘═╤═╝ └─┤ + ╟─┤ ~ ╟─┐ │ ┌───╖ │ ║ 0 ║ ║ ≭ ╟─┘
│ ┌───╖ ┌───╖ │ │ └─┤ │ ╘═╤═╝ ╘═══╝ │ ├─┤ ⊅ ╟───┐ │ ╚═╤═╝ ╙─┬─╜
│ ┌─┤ + ╟─┤ ~ ╟───────────┴───┐ │ ┌─┘ │ ┌─┴─╖ ├─┘ ╘═╤═╝ ┌─┴─╖ ┌─┴─╖ ┌─┴─╖ │
└─┤ ╘═╤═╝ ╘═══╝ ┌─┴──╖ │ │ └─────┤ · ╟───────┴─┐ └───┤ · ╟─┤ · ╟─┤ ╟───┴───────────┐
│ ┌─┴──╖ ┌───╖ ╔════╗ │ << ╟──┐ │ │ ╘═╤═╝ │ ╘═╤═╝ ╘═╤═╝ └─┬─╜ │
│ │ << ╟────┤ + ╟─╢ 11 ║ ╘═╤══╝ │ │ │ ┌─┴─╖ │ ╔═══╗ │ ┌───┘ │ │
│ ╘═╤══╝ ╘═╤═╝ ╚════╝ ╔═╧═╗ ┌─┴─╖ │ │ │ ✰ ║ │ ║ 0 ║ │ │ ┌─────┘ │
│ ╔═╧═╗ │ ╔════╗ ║ 1 ║ │ ♯ ║ │ │ ╘═╤═╝ │ ╚═╤═╝ │ │ │ │
│ ║ 1 ║ │ ║ 12 ╟─┐ ╚═══╝ ╘═╤═╝ │ │ ┌─┴─╖ ┌───╖ ┌─┴─╖ ┌─┴─╖ │ │ ┌─┴─╖ │
│ ╚═══╝ ┌───╖ │ ╚════╝ │ ┌───╖ │ │ │ │ ʭ ╟─┤ ʭ ╟─┤ ȶ ║ │ ⁞ ║ │ └─┤ ≭ ╟─────────────┐ │
┌─┴──╖ ┌─┤ > ╟─┴─────┐ ┌─┴─┤ > ╟───┴───┐ │ │ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ │ ╘═╤═╝ ╔═══╗ ┌───╖ │ │
│ << ╟──┤ ╘═╤═╝ │ │ ╘═╤═╝ │ │ │ │ ┌─┴─╖ ├─────┘ │ │ ║ 5 ╟─┤ + ╟─┴─────┐ │
╘═╤══╝ │ ┌─┴─╖ │ │ ┌─┴─╖ │ │ │ ┌─────┐ └───┤ · ╟───┴─┐ │ │ ╚═══╝ ╘═╤═╝ │ │
╔═╧═╗ └─┤ ? ╟───┐ │ └───┤ ? ╟───┐ │ │ │ ┌─┴─╖ ┌─┴─╖ ╘═╤═╝ ┌─┴─╖ ┌───┘ │ ┌─┴─╖ │ │
║ 1 ║ ╘═╤═╝ ┌─┴─╖ │ ╘═╤═╝ ┌─┴─╖ │ │ │ ┌─┤ · ╟─┤ ‼ ║ ┌─┴─╖ ┌─┤ ʭ ║ │ ┌───────┘ ┌───┤ + ║ │ │
╚═══╝ └───┤ · ╟─┘ └───┤ · ╟─┘ │ │ │ ╘═╤═╝ ╘═╤═╝ ┌─┤ ʑ ╟─┘ ╘═╤═╝ │ │ ┌───╖ ┌─┴─╖ ╘═╤═╝ │ │
╘═╤═╝ ┌───╖ ╘═╤═╝ │ │ │ ╔═╧═╕ ╔═╧═╕ │ ╘═╤═╝ └───┘ │ ┌───┤ ʝ ╟─┤ ȶ ║ ┌─┴─╖ │ │
┌─┴───┤ > ╟───────┐ │ │ │ └─╢ ├─╢ ├─┤ ┌─┴─╖ ┌─────┘ │ ╘═╤═╝ ╘═╤═╝ │ ~ ║ │ │
│ ╘═╤═╝ ├─┘ │ │ ╚═╤═╛ ╚═╤═╛ └─┤ ʑ ╟─┐ ┌─┴─╖ ╔═╧═╗ ╔═╧═╕ ┌─┴─╖ ╘═╤═╝ │ │
│ ┌─┴─╖ │ │ │ ╔═╧═╗ │ ╘═╤═╝ └─┤ ʭ ║ ║ 0 ╟─╢ ├─┤ · ╟───┘ │ │
└─────┤ ? ╟───┐ │ │ │ ║ 0 ╟───┘ ┌─┴─╖ ╘═╤═╝ ╚═╤═╝ ╚═╤═╛ ╘═╤═╝ │ │
╘═╤═╝ ┌─┴─╖ │ ╔════╗ │ │ ╚═╤═╝ ┌───────┤ ? ╟───┐ │ ┌─┴─╖ ┌─┴─╖ ┌─┴─╖ ╔═══╗ ┌───╖ │ │
└───┤ · ╟─┘ ║ 32 ║ │ │ │ ┌─┴─╖ ╘═╤═╝ │ └─────┤ · ╟─┤ ɱ ║ │ ⁞ ║ ║ 6 ╟─┤ + ╟─┘ │
╘═╤═╝ ╚═╤══╝ │ │ ┌─┴─┤ · ╟─────┐ │ │ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ ╚═══╝ ╘═╤═╝ │
╔═══╗ ┌───╖ ┌─┴─╖ ┌─┴─╖ │ │ │ ╘═╤═╝ ┌─┴───┐ │ ╔═══╗ ┌─┴─╖ │ ╔══╧═╗ ╔═══╗ ┌─┴─╖ │
║ 0 ╟─┤ ʝ ╟─┤ ȶ ║ │ ⁞ ║ │ │ ┌─┴─╖ ┌─┴─╖ ╔═╧═╕ ┌─┴─╖ │ ║ 6 ║ │ ♫ ╟───┘ ║ 32 ║ ║ 0 ╟─┤ ? ╟─┐ │
╚═══╝ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ │ │ │ ♫ ╟─┤ ɱ ╟─╢ ├─┤ ʝ ║ │ ╚═╤═╝ ╘═╤═╝ ╚════╝ ╚═══╝ ╘═╤═╝ ├─┘
│ └───────┘ │ │ ╘═╤═╝ ╘═══╝ ╚═╤═╛ ╘═╤═╝ │ └─────┘ └─ │
└──────────────────┘ └───┘ ┌────────┘ └─┐ └─────────────────────────────────────┘
│ ╔════╗ ┌───╖ ┌─┴─╖
│ ║ 32 ╟─┤ ⁞ ╟─┤ ȶ ╟─┐
│ ╚════╝ ╘═══╝ ╘═══╝ │
└────────────────────┘
```
## How it works
* First, there is a lookup-table-like function (`➫`) that maps ASCII codes to a number which represents the letter’s shape in base-4. For example, `I` maps to a number which is 1012301212012120121201212013201 in base-4. This function looks at just enough least-significant bits to identify just the letters A–Z and the space. Any other Unicode character will therefore be mapped to one of those. For example, the digits 0–9 become letters P–Y.
* Then there’s a function (`⊁`) that turns this base-4 representation into a sequence of strings, one per line, turning 1 into space, 2 into `╱`, 3 into `╲`, and appending to the sequence and starting a new string when encountering a 0. Thus, `I` becomes `·\n·╱╲\n·╱·╱\n·╱·╱\n·╱·╱\n·╱·╱\n·╲╱\n·`. This string representation includes both a single space after each character and one on top of each character, so as to create the one-space margin.
* The next function, `⊅`, takes a string (e.g. `DOG`) and simply concatenates these string representations at the appropriate offsets (`D` at the start, `O` 6 lines down, and `G` 12 lines down). It also calculates the total width of this row of text.
* The main logic (implemented in `≭`) operates as a recursive function that iterates over the lines of text in the input:
+ The function first calls `⊅` to render the current line and calculate its width.
+ Then the recursive call happens, and we pass the maximum width to the next level of recursion. This way, each invocation knows how wide the widest line of text above it is.
+ At the base of the recursion, we know the widest width we need to accommodate and we can generate the bottom-left triangle of spaces (shown as `•` in the example below).
+ After the recursive call, we prepend the current line of text. This is done in three steps:
- 6 new lines are added at the top, containing the necessary spaces at the start (shown as `●` (iteration 2) and `■` (iteration 1) in the example below). With each returning iteration, the amount of spaces to be added is incremented by 6.
- The rendered letter shapes are appended (starting at the top).
- Extra spaces are generated (by `✰`) to bring the width all the way to the widest width we need (shown as `▲` in the example below).
* Finally, the main program just splits the input at `\n`s, calls `≭` with that, and then joins the resulting strings with newlines.
Here’s the example for the input `W\nA`:
```
■■■■■■■■■■■·
■■■■■■■■■■╱╲·
■■■■■■■■■╱·╱··
■■■■■■■■╱·╱····
■■■■■■■╱·╱·╱╲···
■■■■■■·╲╱·╱·╱·╱╲·
●●●●●··╱╲╱·╱·╱·╱·
●●●●╱╲·╲╱╲╱·╱·╱·
●●●╱··╲··╱╲╱·╱·
●●╱·╱╲·╲·╲╱╲╱·
●╱··╲╱·╱·▲···
╱·╱╲··╱·▲▲▲·
╲╱·╱·╱·▲▲▲▲
•·╱·╱·▲▲▲▲
••╲╱·▲▲▲▲
•••·▲▲▲▲
••••▲▲▲
•••••▲
```
Example output:
[](https://i.stack.imgur.com/74Ffh.png)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~177~~ ~~143~~ 141 bytes
```
WSF⁶⊞υE⭆ι⁺?§⪪”‴!⊟γ←B)1F»$g'~δZ@↷➙O'no⦄℅ψzY´´A⭆≦μ6δTK⮌´κ?C…p⌊*RUUρ⁻Ee℅²«êSQe¹AAK›Σ↓^⬤ωε!⬤fº”¶℅λ§↨℅λ²κP↘⪫Eυ⭆ι§╲ ⁼§§υ⊕κμλ¶→P↘⪫Eυ⭆ι§╱ ⁼§ι⊕μλ¶
```
[Try it online!](https://tio.run/##pVDbTsJAEH3vVwyFmC2tGIyKoVoCgloUiyDe0pcGKt2wbLG04I/4IfpJ/kidqRCC8c3d7DmzO7ezMwy8aBh6Ik2XARc@MFvOkrgfR1yOmabBSxgBO9Kgm8wDlhjQ8Wbsx0sWN6ArkjlTa6oB9diWI/@N9WeCx/hUcyXogFA8RCiVCMp0JUvfoytDMCnElScWsVlAsCyEilmBjE6JSgR6JbPIqx@40lWLmL8HVImSc1aOoExUoEL547wrjeIOhq42qlQRNQOcaMSlJ5jQcG20N7y5zzY@A/bxTDDEVDqJiHkXfx6zajNcyh4fB7EB7ZBLRrPA4WwNZl1S/Xr/BGzcek08MWfr5zVjmi2HkT/1ZeyP2ITUTPGshGVysXm48Fk1a/k/KR9/SOHbEqba7/ZpenfZgtuBfXalNHrOww2cO49Ke9Dp9sG5b/UUcl/Xn5@UpnOhpLsL8Q0 "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated strings and outputs the prettier rendering at a cost of 4 bytes. Explanation:
```
WS
```
Loop over each input string.
```
F⁶⊞υE⭆ι⁺?§⪪”...”¶℅λ§↨℅λ²κ
```
Look up each letter in the input string in a large compressed lookup table of ASCII encoded horizontally flipped character bitmaps. The encoded bitmaps are joined with `?` (representing blank values) before being decoded, converted into 6-bit binary (all the values are in the range 32-63), and transposed, and the bitmaps for all of the lines are collected together.
```
P↘⪫Eυ⭆ι§╲ ⁼§§υ⊕κμλ¶→
```
Output `╲`s where each bit changes from the next row.
```
P↘⪫Eυ⭆ι§╱ ⁼§ι⊕μλ¶
```
Output `╱`s at each change in bit in each row.
Edit: Saved 34 bytes by taking inspiration from @Arnauld's encoding method, but inverting the bits because that simplifies the Charcoal code. Saved 2 bytes by building up the entire bitmap at once rather than a line at a time. Note that although the bitmap has a ragged right edge the joining rows are all blank so it makes no difference. The bitmap is output rotated as compared to the previous version which explains the adjustments to the output code.
]
|
[Question]
[
# Background
You may be aware that periods in between letters in gmail addresses are ignored. Email sent to [[email protected]](/cdn-cgi/l/email-protection), [[email protected]](/cdn-cgi/l/email-protection), and [[email protected]](/cdn-cgi/l/email-protection) all end up in the same place!
This is a great way to have multiple different emails addresses for things like signing up for free trails, or filtering mail from different website. We will refer to gmail address aliases created in this way as dot-aliases.
# The Task
Write a program to generate all possible dot-aliases of a given Gmail address.
# Input
A Gmail address as a string. You may choose whether or not the "@gmail.com" part is included in the input. The maximum length of a Gmail ID (the part before the '@') is 30 characters (not including dots). The minimum is 6 characters. You may assume the input will not already include any dots.
For more details on gmail ID requirements: <https://support.google.com/mail/answer/9211434?hl=en>
# Output
All of the dot-aliases, in any order, with no duplicates. This can mean printing them to stdout, writing to a file, returning them in a container, returning a iterator, etc. The output **must** contain the "@gmail.com" suffix. You may choose whether or not to include the original input address in the output.
# Scoring
Code Golf here, solution with fewest bytes wins. In the event of a tie, the code who's least common character has the highest number of occurrences wins. In the event of a double tie, earliest timestamp wins.
# Example:
```
Input:
[[email protected]](/cdn-cgi/l/email-protection)
or
abcabc
(you pick)
Output:
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection) (optional)
```
**-8% Byte Bonus:** Even though the longest Gmail ID is 30 characters, the maximum length for any valid email address prefix is 64 characters. Make your program work for input up to 64 characters before the '@', but ensure output is also limited to 64 characters before the '@'.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~72~~ 69 bytes
-3 bytes thanks to [Jitse](https://codegolf.stackexchange.com/users/87681/jitse)!
Input includes `@gmail.com`.
```
f=lambda s:s[11:]and[s[0]+w+x for x in f(s[1:])for w in('.','')]or[s]
```
[Try it online!](https://tio.run/##JcpBCoMwEIXhfU8xu0mwiNJdoNB7hFmMSmzAJJIR1NPHiPBW3/vXc/un@CnFfRcOw8QgRmzfG@I4WbEdNXtzgEsZDvARnKqvIX3DXkFhi29ETSlboXKzPB3yMNb95sB@accUUJsXwJp93JTocgE "Python 3 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~207~~ ~~145~~ ~~140~~ 138 bytes
Removed the flexibility to accept both with and without @gmail.com, now requires the domain to be omitted.
```
g=lambda e:(f"{''.join(p+t for p,t in zip(((['','.'][s>>i&1]for i in range(len(e)-1,-1,-1))),e))}@gmail.com"for s in range(2**(len(e)-1)))
```
[Try it online!](https://tio.run/##RYtBDoIwEEX3nqJh4cxgJUF3JBLvQVgULHVMaRvoRo1nr@ACf97uvR@e8e7dOSVzsWrsbkroCofsDVA8PDsMhygGP4kgo2AnXhwQsQGQUEDbzHXN@7JdA171pJzRaLVDTcdS/iAiqYk@VzMqtkXvx2zt539/yvPts9Rp0wZBdf0CULUTy8LELuJM6Qs "Python 3 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 52 bytes
Input includes `@gmail.com`.
```
c s@(a:'@':x)=[s]
c(a:b)=[a:s++x|x<-c b,s<-["","."]]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P1mh2EEj0UrdQd2qQtM2ujiWKxnITQIyE62KtbUraipsdJMVknSKbXSjlZR0lPSUYmP/5yZm5inYKuQmFvgqFJSWBJcU@eQpqCgkKyglJiUDkUM6UEWOXnJ@rtJ/AA "Haskell – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
-4 bytes thanks to Kevin Cruijssen.
```
.œʒθgT›}'.ý
```
[Try it online!](https://tio.run/##yy9OTMpM/f9f7@jkU5PO7UgPedSwq1Zd7/De//8Tk5KByCE9NzEzRy85PxcA "05AB1E – Try It Online")
## Explanation
```
.œ All partitions
ʒ Filter:
θ The last part
g Has a length
T›} Larger than 10
'.ý Join by periods
```
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~16~~ 15 bytes
Saved a lot by porting Adám's APL answer.
```
g11-oݨbεRÅÏ'.«
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/3dBQN//w3EMrks5tDTrcerhfXe/Q6v//E5OSgcghPTcxM0cvOT8XAA "05AB1E – Try It Online")
# Explanation
```
g Find the input's length
11- Minus 11
o 2 ** x
Ý 0-range
¨ Pop the last item
b Convert to binary
ε For every binary item:
R Reverse this item
ÅÏ Apply to all truthy indices of this binary item:
'.« Append a period
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~51~~ ~~45~~ ~~34~~ 29 bytes
Anonymous tacit prefix function. Requires `⎕IO←0` and trailing `@gmail.com`. Returns a list of strings.
```
⊂{∊,∘'.'¨@⍵⊢⍺}∘⍸∘⊤¨∘⍳2*∘≢11∘↓
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/x91NVU/6ujSedQxQ11P/dAKh0e9Wx91LXrUu6sWKPSodweI7FpyaAWYt9lIC0R3LjI0BNFtk/@nAU151Nv3qKv5Ue@aR71bDq03ftQ2EWh@cJAzkAzx8Az@n6agnpiUDEQO6bmJmTl6yfm56gA "APL (Dyalog Unicode) – Try It Online")
`11∘↓` drop the first eleven characters from the argument
`≢` count the number of remaining characters
`2*∘` raise two to that power
`⍳` **ɩ**ntegers 0…that
`¨∘` on each index:
`⊤` convert **T**o binary
`⍸∘` **ɩ**ndices where 1-bits are
`⊂{`…`}∘` call the following function with that as right argument (`⍵`) and the entire original argument as left argument (`⍺`)
`⊢⍺` on the original text
`@⍵` **at** the given indices
`¨` for each of the indexed characters
`,∘'.'` append a period
`∊` **ϵ**nlist (flatten)
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + [sed](https://www.gnu.org/software/sed/manual/sed.html), 39
Takes input of just the local part of the email address and not the @gmail.com. Takes input from STDIN.
```
eval echo `sed 's/\B/{,.}/g'`@gmail.com
```
[Try it online!](https://tio.run/##S0oszvj/P7UsMUchNTkjXyGhODVFQb1YP8ZJv1pHr1Y/XT3BIT03MTNHLzk/9///xKRkIAIA "Bash – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 48 bytes
```
*.comb.reduce({@$^a X~$,'.'X~$^b})X~'@gmail.com'
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwX0svOT83Sa8oNaU0OVWj2kElLlEhok5FR11PHUjFJdVqRtSpO6TnJmbmgFSq/7fmKizNTC3JqVQoTqxUUIlXSMsvUkhTUE9MSk5JTUvPyMzKVv8PAA "Perl 6 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-n`, ~~70~~ 56 bytes
Input includes "@gmail.com". Generates all possible ways to distribute valid combinations of dots and empty strings within the id by finding the location of the second character before the @ (this works because the input is guaranteed to have 6 characters), and zips them into the original input.
```
r=p,?.
r.product(*[r]*~/..@/){|e|puts$_.chars.zip(e)*''}
```
[Try it online!](https://tio.run/##DcJbDkAwEADAf@eQoGGdQLiHiLQlNEE32/bD8@iWyVBQOzNVmNcQESDZIWifipY68ZQATZmd13hh8C7uQc@SHBwG0zETSXIzS6X/zbRKs4C262vRG7s5LrYP "Ruby – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 90 bytes
```
char s[],*i=s+91;main(j){for(gets(i);*i;j+=i[10]&&fork(s[j]=46))s[j++]=*i++;write(1,s,j);}
```
[Try it online!](https://tio.run/##DYxBCgIxDAC/4mlJmioWRJBS8B@lhxrWmuq60Cx4EN9eC3MYGBjeF@be@ZHbTmOyRoLSxfklyxsqfu9rgzJvCoLeiK8UJLpjmqYRnqCxpnA6Iw4hSsEIkf802WZwVm1F/@s933hwLWP5OvC6/AE "C (gcc) – Try It Online")
According to my test `write` is atomic, while standard IO aren't
# [C (gcc)](https://gcc.gnu.org/), 93-8%=85.56 bytes
```
char s[],*i=s+91;main(j){for(gets(i);*i;j+=i[10]&&fork(s[j]=46))s[j++]=*i++;write(j<76,s,j);}
```
[Try it online!](https://tio.run/##DYxBCsIwEAC/4qkk2VRaEUFiwH@EHOJS466thWyhB/HtMTCHgYHBPiPWiq9UDhKiNeQFrqNbEn0U6@9zLSpPmyjSzpBj8BTGIXZdC28lgaM/X7RuAhC9IQC3F9omxbfTYMWydr9a0wMb99yu8xHX5Q8)
First one to do bonus
[Answer]
# [Perl 5](https://www.perl.org/) + `-F/(?=.+@)/n` 21 bytes
Much less offensive flags thanks to [@Abigail](https://codegolf.stackexchange.com/users/95135/abigail)!
```
$"="{,.}";say for<@F>
```
[Try it online!](https://tio.run/##K0gtyjH9/19FyVapWkevVsm6OLFSIS2/yMbBze7//8Sk5BSH9NzEzBy95Pzcf/kFJZn5ecX/dd30Next9bQdNPXz/uv6muoZGugZAAA "Perl 5 – Try It Online")
### Explanation
`-F` splits the input based on the regular expression passed in (with no argument it splits the string into chars) and stores in `@F`. Setting `$"` specifies the string used to join list entries when interpolating. `<...>` is short syntax for a [`glob` string](https://perldoc.perl.org/functions/glob.html) which accepts interpolation. In some (most POSIX-compliant?) shells, the glob `a{,.}` expands to the list `a` and `a.`. for an input `[[email protected]](/cdn-cgi/l/email-protection)`, `<@F>` is expanded to `<a{,.}b{,.}c{,.}d{,.}@gmail.com>` thanks to setting `$"`, which finally expands to the list of all permutations which are iterated with `for` and printed using `say`.
---
# [Perl 5](https://www.perl.org/) with `-F`, 32 bytes
Excludes `@gmail.com` from the input.
```
$"="{,.}";say for<@F\@gmail.com>
```
[Try it online!](https://tio.run/##K0gtyjH9/19FyVapWkevVsm6OLFSIS2/yMbBLcYhPTcxM0cvOT/X7v//xKTklH/5BSWZ@XnF/3Xd/uv6muoZGugZAAA "Perl 5 – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 40 bytes
```
^.
$&@
+%`@(.)
$1@$'¶$`.$1@
@
@gmail.com
```
[Try it online!](https://tio.run/##K0otycxL/P8/To9LRc2BS1s1wUFDT5NLxdBBRf3QNpUEPSCLCwjTcxMzc/SS83P//09MSgYiAA "Retina 0.8.2 – Try It Online") Takes input without the domain. Explanation:
```
^.
$&@
```
Insert a marker `@` after the first character.
```
+%`@(.)
$1@$'¶$`.$1@
```
Move the `@` right one character each time, duplicating each line, with an extra `.` in the duplicate.
```
@
@gmail.com
```
Add the domain suffix to all lines.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~134~~ \$\cdots\$ ~~103~~ 102 bytes
Saved ~~4~~ ~~8~~ 9 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
Saved ~~7~~ ~~9~~ 10 bytes thanks to [l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)!!!
```
i;j;k;f(char*g){i=strlen(g)-10;for(j=1<<i;j-=2;k=!puts(g+i))for(;k<i;printf(".%c"+!(j>>k++&1),g[k]));}
```
[Try it online!](https://tio.run/##Hc1LDoIwFIXhOasoTTT3WiHi9FLiPowDbGgt5ZVSR4S112JyZt@fHFUYpWK01JMjDerT@ovBzco1@KGbwGBR3UjPHnpZ1XXqCnknJ/PlG1YwwiIeSC7R4u0UNPDypLjIoW8aJ8S5wqt5uhci7XFs7QTItoyx/xML3RqYZLx9q7SHScFQqnnklBINByNle/wB "C (gcc) – Try It Online")
Takes an email address with the `@gmail.com` part included and prints out all of its dot-aliases (not with the original).
**How**
Loops over \$0\dots2^{n-1}\$ where \$n\$ is the length of email address up to `@`. Uses the binary bits of that loop variable to decide whether or not to insert a dot in between letters.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 52 bytes
```
Thread@StringInsert[#,".",Subsets@Range[2,StringLength@#-10]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@z8koyg1McUhuKQoMy/dM684tagkWllHSU9JJ7g0qTi1pNghKDEvPTXaSAeixCc1L70kw0FZ19AgNlbtfwBQrERB30EhLVopMSkZiBzScxMzc/SS83OVYq3/AwA "Wolfram Language (Mathematica) – Try It Online") Pure function. Takes a string as input and returns a list of strings as output. Ignore any `StringInsert::psl` messages generated.
[Answer]
# [R](https://www.r-project.org/), ~~115~~ ~~104~~ ~~103 bytes~~ 95 bytes
```
d=function(s,p=2,`[`=substring)"if"(s[p,p]=="@",s,c(d(s,p+1),d(paste0(s[1,p-1],".",s[p]),p+2)))
```
[Try it online!](https://tio.run/##FcrBDoMgDADQf@mpzTozvJP4H4REB2pIBjYWD349w8s7vbO1aLerhJqOgspiR57dbPX6aj1T2QnSBqhOWLy1MAErB4xPfRniiLJoXT99GJa38QxDL0489TASUYsI@V7zkn7T/jiEIwO1Pw "R – Try It Online")
Input includes "@gmail.com" (or any other domain, but that's not relevant to the challenge...)
*Edit: -8 bytes thanks to Giuseppe*
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~14~~ 12 bytes
```
/#>11QjL\../
```
[Try it online!](https://tio.run/##K6gsyfj/X1/ZztAwMMsnRk9P//9/pdzEkoys0rzszFSH9NzEzBy95PxcJQA "Pyth – Try It Online")
Input includes `@gmail.com`.
`./` Partitions of input into disjoint substrings
`jL\.` Join the chunks of each partition using `.`
`/#>11Q` Keep only elements where the last 11 characters of the input string appear in that element (this checks that the "@gmail.com" suffix and preceding character are still intact)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
ŒṖẈṪ>ɗƇ⁵j€”.
```
[Try it online!](https://tio.run/##y0rNyan8///opIc7pz3c1fFw5yq7k9OPtT9q3Jr1qGnNo4a5ev8Pt2vrA9kgJTP@/1dKTEoGIof03MTMHL3k/FwlAA "Jelly – Try It Online")
## How it works
```
ŒṖẈṪ>ɗƇ⁵j€”. - Main link. Takes an email E on the left
ŒṖ - All partitions
ɗƇ⁵ - Keep those partitions f(P, 10) for which the following is true:
Ẉ - The lengths of each part of P
Ṫ - The last one
> - is greater than 10
j€”. - Join each of those remaining by ”.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 29 bytes
```
g©<'.и.ιæʒ'.мJg®Q}J’@g‚ç.ŒŒ’«
```
[Try it online!](https://tio.run/##yy9OTMpM/f8//dBKG3W9Czv0zu08vOzUJCBzj1f6oXWBtV6PGmY6pD9qmHV4ud7RSUcnAbmHVv//n2iYlGyUDAA "05AB1E – Try It Online")
[Answer]
# [T-SQL](https://www.microsoft.com/sql-server), 261 bytes
Input is taken from column `U` of table `T` (according to the [Code Golf rules for SQL](https://codegolf.meta.stackexchange.com/a/5341/78876)).
```
WITH V(N)AS(SELECT 1UNION ALL SELECT N+1FROM V WHERE N<(SELECT LEN(U)FROM T)),C AS(SELECT U FROM T UNION ALL SELECT CONVERT(VARCHAR(64),STUFF(U,N+1,0,'.'))FROM C,V WHERE N<LEN(U)AND SUBSTRING(U,N,2)NOT LIKE'%.%'AND LEN(U)<64)SELECT DISTINCT U+'@gmail.com'FROM C
```
[DB Fiddle](https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=08d4c8e5dc14eef76ac776b85ac849df)
Duration of execution grows exponentially and it takes minutes on my machine for strings longer than 10 characters, but theoretically (if given unlimited time) it should work for input strings up to 64 characters, limiting the output to 64 characters. Therefore, it should also get the -8% bonus, getting to 240 bytes.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 86 bytes
```
(m,e,i)=>{while(m[i])w=m.substr(0,i)+'.'+m.substr(i),console.log(w+e),f(w,e,i+2),i++}
```
[Try it online!](https://tio.run/##PYxBDsIgEEX3XmRmwkiqe4z3MC4oQh0DxZQqC9OzI25Mft7iveQ/7NsWt8hz3c/55lswDRN7FjKnT71L9JgucqVqki6vsawLDj0q0KD@RohdnkuOXsc8YVWeOGD93agjdaht1wKCHV0fMJynZCVqlxPwgdoX "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 80 bytes
```
(m,e,i,c)=>{while(m[i])w=m.substr(0,i)+'.'+m.substr(i),c(w+e),f(w,e,i+2,c),i++}
```
[Try it online!](https://tio.run/##PYxBCgIxDEX3XiQJjUXdV7yHuOjEdoy0U5mOdiGevY4b4cODB@/f/ctXmfWxbKdyDT26jpkDKwu547vdNAXMZ71Qc9nW51CXGXesZMCC@RslFmwmEEdsv9wc1oMV5rPpEcEPsg4YTmP2mqyUDLxnKVMtKdhURupf "JavaScript (Node.js) – Try It Online")
[Answer]
# [PHP](https://php.net/), 110 bytes
```
function f($a,$b,$c){while($a[$c]){$w=substr($a,0,$c).'.'.substr($a,$c);echo $w.$b,"\n";f($w,$b,$c+2);$c++;}};
```
[Try it online!](https://tio.run/##RYxBCsMgFESvIkEwEpG229@S3qPtQj@xColKk@Ai5Oz2hy7KDAMzDC/7XK999plVt0ZcQorMtdwobhVHuRUfxoH6g@NLbrzc5tXOy@d4nI6DFqT/RgsM6BPjRROhecYGCFd@uO4igbKDfYfqWmEskoUS9/dkwqgxTUKdJdQv "PHP – Try It Online")
### Human readable version
```
<?php
function f($address, $suffix, $i)
{
while ($address[$i]) {
$str = substr($address, 0, $i) . '.' . substr($address, $i);
echo $str . $suffix, "\n";
f($str, $suffix, $i + 2);
$i++;
}
};
f('abcabc', '@gmail.com', 1);
```
]
|
[Question]
[
## Background (skip to definitions)
Euler proved a beautiful theorem about the complex numbers: \$e^{ix} = \cos(x) + i \sin(x)\$.
This makes de Moivre's theorem easy to prove:
$$
(e^{ix})^n = e^{i(nx)} \\
(\cos(x) + i\sin(x))^n = \cos(nx) + i\sin(nx)
$$
We can plot complex numbers using the two-dimensional Euclidean plane, with the horizontal axis representing the real part and the vertical axis representing the imaginary part. This way, \$(3,4)\$ would correspond to the complex number \$3+4i\$.
If you are familiar with polar coordinates, \$(3,4)\$ would be \$(5,\arctan(\frac 4 3))\$ in polar coordinates. The first number, \$r\$, is the distance of the point from the origin; the second number, \$\theta\$, is the angle measured from the positive \$x\$-axis to the point, counter-clockwise. As a result, \$3 = r \cos \theta\$ and \$4 = r \sin \theta\$. Therefore, we can write \$3+4i\$ as \$r \cos \theta + r i \sin \theta = r(\cos \theta + i \sin \theta) = re^{i\theta}\$.
Let us solve the complex equation \$z^n = 1\$, where \$n\$ is a positive integer.
We let \$z = re^{i\theta}\$. Then, \$z^n = r^ne^{in\theta}\$. The distance of \$z^n\$ from the origin is \$r^n\$, and the angle is \$n\theta\$. However, we know that the distance of 1 from the origin is 1, and the angle is \$\theta\$. Therefore, \$r^n=1\$ and \$n\theta=\theta\$. However, if you rotate by \$2π\$ more, you still end up at the same point, because \$2π\$ is just a full circle. Therefore, \$r=1\$ and \$n\theta = 2kπ\$, giving us \$z=e^{2ikπ / n}\$.
We restate our discovery: **the solutions to \$z^n=1\$ are \$z=e^{2ikπ / n}\$**.
A polynomial can be expressed in terms of its roots. For example, the roots of \$x^2-3x+2\$ are 1 and 2, so \$x^{2}-3x+2 = (x-1)(x-2)\$. Similarly, from our discovery above:
$$z^n-1 = \prod^{n-1}\_{k=0} (z-e^{2ik\pi / n})$$
However, that product certainly contained roots of other n. For example, take \$n=8\$. The roots of \$z^{4}=1\$ would also be included inside the roots of \$z^{8}=1\$, since \$z^{4}=1\$ implies \$z^{8} = (z^{4})^{2} = 1^{2} = 1\$. Take \$n=6\$ as an example. If \$z^{2}=1\$, then we would also have \$z^{6}=1\$. Likewise, if \$z^{3}=1\$, then \$z^{6}=1\$.
If we want to extract the roots unique to \$z^{n}=1\$, we would need \$k\$ and \$n\$ to share no common divisor except \$1\$. Or else, if they share a common divisor \$d\$ where \$d>1\$, then \$z\$ would be the \$\frac k d\$-th root of \$z^{n / d}=1\$. Using the technique above to write the polynomial in terms of its roots, we obtain the polynomial:
$$\prod\_{\substack{0 \le k < n \\ \gcd(k,n) = 1}} (z - e^{2ik\pi / n})$$
Note that this polynomial is done by removing the roots of \$z^{n / d}=1\$ with d being a divisor of \$n\$. We claim that the polynomial above has integer coefficients. Consider the LCM of the polynomials in the form of \$z^{n / d}-1\$ where \$d>1\$ and \$d\$ divides \$n\$. The roots of the LCM are exactly the roots we wish to remove. Since each component has integer coefficients, the LCM also has integer coefficients. Since the LCM divides \$z^{n}-1\$, the quotient must be a polynomial with integer coefficient, and the quotient is the polynomial above.
The roots of \$z^{n}=1\$ all have radius 1, so they form a circle. The polynomial represents the points of the circle unique to n, so in a sense the polynomials form a partition of the circle. Therefore, the polynomial above is the n-th cyclotomic polynomial. (cyclo- = circle; tom- = to cut)
## Definition 1
The n-th cyclotomic polynomial, denoted \$\Phi\_n(x)\$, is the unique polynomial with integer coefficients that divide \$x^{n}-1\$ but not \$x^{k}-1\$ for \$k < n\$.
## Definition 2
The cyclotomic polynomials are a set of polynomials, one for each positive integer, such that:
$$x^n - 1 = \prod\_{k \mid n} \Phi\_k(x)$$
where \$k \mid n\$ means \$k\$ divides \$n\$.
## Definition 3
The \$n\$-th cyclotomic polynomial is the polynomial \$x^{n}-1\$ divided by the LCM of the polynomials in the form \$x^{k}-1\$ where \$k\$ divides \$n\$ and \$k < n\$.
## Examples
1. \$Φ\_{1}(x) = x - 1\$
2. \$Φ\_{2}(x) = x + 1\$
3. \$Φ\_{3}(x) = x^{2} + x + 1\$
4. \$Φ\_{30}(x) = x^{8} + x^{7} - x^{5} - x^{4} - x^{3} + x + 1\$
5. \$Φ\_{105}(x) = x^{48} + x^{47} + x^{46} - x^{43} - x^{42} - 2x^{41} - x^{40} - x^{39} + x^{36} + x^{35} + x^{34} + x^{33} + x^{32} + x^{31} - x^{28} - x^{26} - x^{24} - x^{22} - x^{20} + x^{17} + x^{16} + x^{15} + x^{14} + x^{13} + x^{12} - x^{9} - x^{8} - 2x^{7} - x^{6} - x^{5} + x^{2} + x + 1\$
## Task
Given a positive integer \$n\$, return the \$n\$-th cyclotomic polynomial as defined above, in a reasonable format (i.e. e.g. list of coefficients is allowed).
## Rules
You may return floating point/complex numbers as long as they round to the correct value.
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins.
## References
* [Wolfram MathWorld](http://mathworld.wolfram.com/CyclotomicPolynomial.html)
* [Wikipedia](https://en.wikipedia.org/wiki/Cyclotomic_polynomial)
[Answer]
# [Haskell](https://www.haskell.org/), 120 bytes
```
import Data.Complex
p%a=zipWith(\x y->x-a*y)(p++[0])$0:p
f n=foldl(%)[1][cis(2*pi/fromInteger n)^^k|k<-[1..n],gcd n k<2]
```
[Try it online!](https://tio.run/##PYs9C4JQFEDn/BV3MFBLU6EltKWWlmhrMIOLPu3xvi6vF5j0382ltsM5nAc@BZNymrgiYx0c0WFyMIokGzxaYjlyunL3CG4DvOP9EGP0DgNaraq0Dv10R14HuuyMbGWwDKusrhr@DPKI@KazRp20Yz2zoMP7XXxEEVdZkuh63TctaBBFXk8jlNBBlm49hYKdecNmYc1Lt5CAZSgvaN3cuJ59a7wFWa4djD/wQSHB/x2nLw "Haskell – Try It Online")
Gives a list of complex floats that has entries like `1.0000000000000078 :+ 3.314015728506092e-14` due to float inacurracy. A direct method of multiplying out to recover the polynomial from its roots.

The `fromInteger` is a big concession to Haskell's type system. There's got to be a better way. Suggestions are welcome. Dealing with roots of unity symbolically might also work.
---
# [Haskell](https://www.haskell.org/), 127 bytes
```
(h:t)%q|all(==0)t=[]|1>0=h:zipWith(\x y->x-h*y)t q%q
f n=foldl(%)(1:(0<$[2..n])++[-1])[tail$f k++[0,0..]|k<-[1..n-1],mod n k<1]
```
[Try it online!](https://tio.run/##bU67DoMwDNz5Cg8gJW2C4kpdEOE3OqQZkChKRAiFZmgR/05DxdABnXXy2eeHqV/dw7l1JaYINBuX2jkipaBBKr1gJaQpZvu82WDI/Q0fXr25OX1ogDEbkxa8bAfXOJJRggURZaouee41PZ8VR01VqK1LW@iiFkzkuV66kiuMnthm/dCAh65Evc4goQUU12SKFIVCtiFOMY6/uOzJVsI/7JZjOrQebtNJX1sfLz8n6wOkQOJPErZ3GMx0/QI "Haskell – Try It Online")
No imports.
Uses the formula

Computes Φ\_n(x) by dividing the LHS by each of the other terms in the RHS.
The operator `%` does division on polynomials, relying on the remainder being zero. The divisor is assumed to be monic, and is given without the leading 1, and also with infinite trailing zeroes to avoid truncating when doing `zipWith`.
[Answer]
# Mathematica, ~~43~~ 41 bytes
```
Factor[x^#-1]/Times@@#0/@Most@Divisors@#&
```
Of course, we can always use the built-in, but if we don't, this divides *x**n*-1 by Φ*k*(*x*) (computed recursively) for every proper divisor *k* of *n*.
We use `Factor` to get a polynomial at the end. I think the reason this works is that `x^#-1` factors into all the cyclotomic polynomials of divisors of *n*, and then we divide out the ones we don't want.
*-2 bytes thanks to Jenny\_mathy, rewriting the `Factor` to only apply to the numerator.*
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~32~~ ~~31~~ ~~27~~ 25 bytes
```
Z\"@:@/]XHxvHX~18L*Ze1$Yn
```
Output may be non-integer due to floating-point inaccuracies (which is allowed). The footer does rounding for clarity.
[**Try it online!**](https://tio.run/##y00syfn/PypGycHKQT82wqOizCOiztDCRysq1VAlMu9/ZL4CCKgqFOWX5qUolOQr5KUmFqUWlyhk5pWkpqcW/Tc0MAUA)
[Answer]
# [Haskell](https://www.haskell.org/), ~~250 236 233 218~~ 216 bytes
This is a verbose version, (@xnor can do it in almost [half the score](https://codegolf.stackexchange.com/a/143916/24877)) but it is guaranteed to work for any `n` as long as you have enough memory, but it does not use a builtin for generating the n-th cyclotomic polynomial. The input is an arbitrary size integer and the output is a polynomial type with (exact) rational coefficients.
The rough idea here is calculatin the polynomials recursively. For `n=1` or `n` prime it is trivial. For all other numbers this approach basically uses the formula from definition 2

solved for . Thanks @H.PWiz for quite a bunch of bytes!
```
import Math.Polynomial
import Data.Ratio
import NumberTheory
p=powPoly x
q=poly LE
c n|n<2=q[-1,1%1]|isPrime n=sumPolys$p<$>[0..n-1]|1>0=fst$quotRemPoly(addPoly(p n)$q[-1])$foldl1 multPoly[c d|d<-[1..n-1],n`mod`d<1]
```
For `n=105` this yields following polynomial (I tidied up all the `%1` denominators):
```
[1,1,1,0,0,-1,-1,-2,-1,-1,0,0,1,1,1,1,1,1,0,0,-1,0,-1,0,-1,0,-1,0,-1,0,0,1,1,1,1,1,1,0,0,-1,-1,-2,-1,-1,0,0,1,1,1]
```
The polynomial for `n=15015` can be found [here](https://pastebin.com/D7JpKu4M) (the largest coefficient is 23).
[Try it online!](https://tio.run/##NYwxb8IwFIT3/Io3uFKRSISZY6Z2aytE2aJIuLFRrNp@jv0sipT/HhKg053uu7tepl9t7TQZFzASfErqqz3aq0dnpC2e8ZskWR0kGfxPvrL70fHYa4zXIoiAl2UFf8Uw@9l8vBcd@NHXWzE0JV/zF96OJu2jcRq8SNkt/cRCzXbNpqp8OXO@24hzIjZkpIO@N16lUncN4FdsuWpX7IxWWQ4uW1pY04EaVV02/PGz9ieH6qRq3k5OGg8CQqZvisAg9XiZpQO@nW4 "Haskell – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 23 bytes
```
R÷
ÆḌÇ€FQœ-@Ç×ı2רPÆeÆṛ
```
[Try it online!](https://tio.run/##y0rNyan8/z/o8Hauw20Pd/Qcbn/UtMYt8OhkXYfD7YenH9lodHj64RkBh9tSgdI7Z/8/3P5wx7zDy4qMgNT//4YGpgA "Jelly – Try It Online")
Outputs as a list of coefficients.
Has floating point AND complex inaccuracies. Footer does rounding to make output prettier.
[Answer]
# [J](http://jsoftware.com/), 36 bytes
```
1+//.@(*/)/@(,.~-)_1^2*%*i.#~1=i.+.]
```
[Try it online!](https://tio.run/##y/qfVqxga6VgoADE/w219fX1HDS09DX1HTR09Op0NeMN44y0VLUy9ZTrDG0z9bT1Yv9rcinpKain2VqpK@go1FoppBVzcaUmZ@QrpCkYG/wHAA "J – Try It Online")
Uses the formula

There are some floating-point inaccuracies, but it is allowed.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 8 bytes
A built-in.
```
polcyclo
```
[Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8L8gPye5Mjkn/39afpFGHlDEUEfB0MBAR6GgKDOvBCiipKBrByTSNPI0NTX/AwA "Pari/GP – Try It Online")
---
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 39 bytes, without built-in
```
f(n)=p=x^n-1;fordiv(n,d,d<n&&p/=f(d));p
```
Using the formula:
\$ \Phi\_n(x)=\dfrac{x^{n}-1}{\prod\limits\_{\stackrel{d|n}{{}\_{d<n}}}\Phi\_{d}(x)} \$.
[Try it online!](https://tio.run/##FYwxCoAwDAC/EhwkgRTbucanCEKodImhiPj7Wpcb7uD8aDWc3ntBI3F5dwspl6tpfdBYWVebZ1@koBJl7yOhgUBiSDEyeKt2DzNB2Ab@DVH/AA "Pari/GP – Try It Online")
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 32 bytes [SBCS](https://github.com/abrudz/SBCS)
```
{(0,⍵)-⍺×⍵,0}/⍤⌽1,¯1*2×÷×1⍸⍤=⊢∨⍳
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=e9Q31dP/UdsEAwA&c=q9Yw0HnUu1VT91HvrsPTgSwdg1r9R71LHvXsNdQ5tN5Qy@jw9MPbD083fNS7Ayhs@6hr0aOOFY96NwMA&f=e9S1qOJR24Q0BWMDLo1HXYu1D603NHw0vftR1yLNRz37H/VNdQ7ReNS55FHHjJrD00GilgpABR0z9MCKmisA&i=AwA&r=tryapl&l=apl-dyalog&m=train&n=f)
Almost direct port of [miles' J answer](https://codegolf.stackexchange.com/a/143927/78410). Returns a polynomial as a vector of coefficients wrapped once, with higher-order terms on the right side.
```
{(0,⍵)-⍺×⍵,0}/⍤⌽1,¯1*2×÷×1⍸⍤=⊢∨⍳ ⍵←n
1⍸⍤=⊢∨⍳ Numbers coprime to ⍵
¯1*2×÷× Divide by ⍵, double, raise -1 to the power of them
{(0,⍵)-⍺×⍵,0}/⍤⌽1, Evaluate the polynomial with the roots of the above
```
[Answer]
# Mathematica, 81 bytes
```
Round@CoefficientList[Times@@(x-E^(2Pi*I#/k)&/@Select[Range[k=#],#~GCD~k<2&]),x]&
```
[Answer]
# [R](https://www.r-project.org/), ~~176~~ ~~171~~ ~~139~~ 112 bytes
```
function(n){for(r in exp(2i*pi*(x=1:n)[(g=function(x,y)ifelse(o<-x%%y,g(y,o),y))(x,n)<2]/n))T=c(0,T)-r*c(T,0)
T}
```
[Try it online!](https://tio.run/##RU5LasMwEN3nFIISMmPkVsnSWFcwoXgXWnCVUSKwJTOWikzo2V1l064evD9vZjVjiGFyRrT1ZpM30QUPHh82MLBwXlCe4eSq2VWQ9bHxeIGb/nNmuaKzNC4Eoa3zfr/KG6wyYOGxqB7b08ebR@y1ASV7rLky0EuFu/5n68qqOCrxIuYURSfuxLTLT5JD8ld4J/h/CB3iM3cd4vBqeZiKGMhazfQNGWUknvQ8LJEUHPLnQfo0fREvTUNpLHi@u1LRKMTtFw "R – Try It Online")
Massively simpler version; uses a `for` loop rather than a `Reduce`.
[Answer]
## CJam (52 51 bytes)
```
{M{:K,:!W+K,0-{K\%!},{j($,\:Q,-[{(\1$Qf*.-}*;]}/}j}
```
[Online demo](http://cjam.aditsu.net/#code=105%0A%7BM%7B%3AK%2C%3A!W%2BK%2C0-%7BK%5C%25!%7D%2C%7Bj(%24%2C%5C%3AQ%2C-%5B%7B(%5C1%24Qf*.-%7D*%3B%5D%7D%2F%7Dj%7D%0A~p). This is an anonymous block (function) which takes an integer on the stack and leaves a big-endian array of coefficients on the stack.
### Dissection
```
{ e# Define a block
M{ e# Memoised recursion with no base cases.
:K,:!W+ e# Store argument in K and build (x^K - 1)
K,0-{K\%!}, e# Find proper divisors of K
{ e# Foreach proper divisor D...
j e# Recursive call to get Dth cyclotomic poly
($,\:Q,- e# The cleverest bit. We know that it is monic, and the
e# poly division is simpler without that leading 1, so
e# pop it off and use it for a stack-based lookup in
e# calculating the number of terms in the quotient.
e# Ungolfed this was (;:Q1$,\,-
e# Store the headless divisor in Q.
[ e# Gather terms into an array...
{ e# Repeat the calculated number of times...
(\ e# Pop leading term, which goes into the quotient.
1$Qf*.- e# Multiply Q by that term and subtract from tail.
}*; e# Discard the array of Q,( zeroes.
]
}/
}j
}
```
[Answer]
# [Maxima](http://maxima.sourceforge.net/), 91 bytes
Using the formula:
\$ \Phi\_n(x)=\dfrac{x^{n}-1}{\prod\limits\_{\stackrel{d|n}{{}\_{d<n}}}\Phi\_{d}(x)} \$.
---
Golfed version. [Try it online!](https://tio.run/##NY6xCsMwDET3fIUIHSRwqL0a0k8pOHVMTWNZuA7k71Nl6A036O6JK@HIJZxnQiY/L1t9fVAtbCgmkhF/PHlyJtUG0Tvo77aDHiBWzAlKjcjam60mK4N4uSeMRKatfW@MQnQ7L5j/sLNWYcABVNIyd/0AI0wPGA200L@5CF5ziAaFfw)
```
f(n):=block(local(p,d),p:x^n-1,for d:1 thru n-1 do(if mod(n,d)=0 then p:p/f(d)),return(p))$
```
Ungolfed version. Try it online!
```
f(n) := block(
local(p, d),
p : x^n - 1,
for d:1 thru n-1 do (
if mod(n, d) = 0 then (
p : p / f(d)
)
),
return(p)
)$
for n:1 thru 100 do (
print(n, " -> ", ratsimp(f(n)))
)$
```
[Answer]
# JavaScript(ES6), ~~337~~ ~~333~~ ~~284~~ ... ~~252~~ ~~250~~ ~~245~~ 242 bytes
```
(v,z=[e=[1,u=0]],g=(x,y)=>y?g(y,x%y):x,h=Math,m=(l,x,p=h.cos(l),q=h.sin(l),i=0)=>x.map(()=>[(i&&(n=x[i-1])[0])-(w=x[i])[0]*p+w[1]*q,(i++&&n[1])-w[1]*p-w[0]*q]))=>{for(;++u<v;z=g(v,u)-1?z:[...m(h.PI*2*u/v,z),e]);return z.map(r=>h.round(r[0]))}
```
**Explanation (Selected):**
```
z=[e=[1,u=0]]
```
Initialize z=(1+0i) \* x^0
```
g=(x,y)=>y?g(y,x%y):x
```
GCD calculation.
```
h=Math
```
Since I need to use Math functions quite a lot, I used another variable here.
```
m=(l,x,p=h.cos(l),q=h.sin(l),i=-1)=>blah blah blah
```
Polynomial multiplication.
```
for(;++u<v;z=g(v,u)-1?z:[...m(h.PI*2*u/v,z),e]);
```
The formula used is
[](https://i.stack.imgur.com/MDffE.gif)
```
return z.map(r=>h.round(r[0]))
```
Compress the output back to an integer array.
**Outputs:**
An array of integers, with the element at position i representing the coefficient of x^i.
One of the problem JS have is that since JS does not provide native library for calculations on polynomials and complex numbers, they needed to be implemented in an array-like way.
console.log(phi(105)) gives
```
Array(49)
0: 1 1: 1 2: 1 3: -0 4: -0 5: -1 6: -1
7: -2 8: -1 9: -1 10: 0 11: -0 12: 1 13: 1
14: 1 15: 1 16: 1 17: 1 18: 0 19: -0 20: -1
21: 0 22: -1 23: -0 24: -1 25: 0 26: -1 27: -0
28: -1 29: 0 30: 0 31: 1 32: 1 33: 1 34: 1
35: 1 36: 1 37: -0 38: -0 39: -1 40: -1 41: -2
42: -1 43: -1 44: -0 45: -0 46: 1 47: 1 48: 1
length: 49
__proto__: Array(0)
```
**337>333(-4): Changed the code for checking undefined value**
**333>284(-49): Changed the polynomial multiplication function because it can be simplified**
**284>277(-7): Deleted some redundant code**
**277>265(-12): Use 2 variables instead of a 2-element array to drop some bytes in array usage**
**265>264(-1): Use Array.push() instead of Array.concat() to reduce 4 bytes, but added 3 for the for-loop braces and the z variable**
**264>263(-1): Further golfed on the last amendment**
**263>262(-1): Golfed on the for loop**
**262>260(-2): Golfed out the if clause**
**260>258(-2): Further combined the declarations**
**258>252(-6): Golfed on reuse of array references**
**252>250(-2): Replace some unary operators as binary operators**
**250>245(-5): Move the increment in Array.map() to the last reference of counter to remove bytes**
**245>242(-3): Use spread syntax instead of Array.push()**
]
|
[Question]
[
In this challenge, you will play the iterated Prisoner's Dilemma, but with a twist: There's also an adversary trying to mess you up!
The [Prisoner's dilemma](https://en.wikipedia.org/wiki/Prisoner%27s_dilemma) is a scenario in game theory where there are two players, who we'll call the "prisoners", each with two options: cooperate, or defect. Each prisoner does better for themself if they defect than if they cooperate, but both prisoners would prefer the outcome where both prisoners cooperate to the one where both prisoners defect.
The *iterated* prisoner's dilemma is the same game, except you play against the same opponent repeatedly, and you know what your opponent has played in the past. Your objective is to accumulate the highest score for yourself, regardless of your opponent's score.
The *adversarial* iterated prisoner's dilemma introduces a third player: The *flipper*. The flipper can choose to interfere with the prisoners' communication. After the prisoners make their plays, the flipper can choose to flip one or both of the prisoners' moves, making it look like they played the opposite move. The flipper can only perform this flip a limited number of times over the course of the round. The flipper's goal is to maximize the number of times the prisoners defect.
## Challenge
In this challenge, you will write Python 3 programs to play as the prisoner and as the flipper. You may submit programs for either or both.
Prisoner programs will receive the following inputs:
* Your past moves, *without* the flipper's flips added.
* The other prisoner's past moves, *with* the flipper's flips added.
* A state variable, which is initialized as an empty list, which you can modify over the course of the round.
Your program should output `'c'` for cooperate and `'d'` for defect. The lists of past moves will be represented in the same fashion.
For instance, here's a program that cooperates unless the opponent's last play was a defection:
```
def basic_tit_for_tat(my_plays, their_plays, state):
if len(their_plays) == 0:
return 'c'
return their_plays[-1]
```
Flipper programs will receive the following inputs:
* The past moves for both players, both true and post-flip. The true moves list will include the move played this round, while the post-flip list will not.
* The number of flips remaining, which starts at 40 flips, covering 100 turns.
* A state variable, which is initialized as an empty list, which you can modify over the course of the round.
Your program should output `0` to flip neither move, `1` to flip prisoner 1's move, `2` to flip prisoner 2's move, and `3` to flip both moves. If you have no flips remaining, your program will not be called. If you have one flip remaining and you output `3`, it will be treated as if you had output `1`, to simplify error handling.
For example, here's a program which flips each prisoner's move every fifth turn, if the true move is cooperate:
```
def basic_steady_flipper(p1_moves, p1_flipped_moves, p2_moves, p2_flipped_moves, flips_left, state):
turn = len(p1_flipped_moves)
if turn % 5 == 0 and p1_moves[-1] == "c":
return 1
if turn % 5 == 2 and p2_moves[-1] == "c":
return 2
return 0
```
If you don't know Python, write your submission in pseudocode, and someone (me or another member of the site) can make the corresponding Python program.
If you want to use randomness, please hand-roll it rather than using the `random` package, as I don't want programs to modify global state. See [basic\_random\_flipper](https://github.com/isaacg1/adversarial-ipd/blob/main/basic.py) for an example.
## Tournament
The tournament runner can be found in this repository: [adversarial-ipd](https://github.com/isaacg1/adversarial-ipd). Run [adversarial-game.py](https://github.com/isaacg1/adversarial-ipd/blob/main/adversarial-game.py) to run the tournament. I'll keep that repository updated with new submissions.
To get things started, I'll put a few basic example programs in [basic.py](https://github.com/isaacg1/adversarial-ipd/blob/main/basic.py).
A round consists of 100 turns, involving the same two prisoners and the same flipper. The flipper's budget over that round is 40 flips, which can be distributed however the flipper likes between the two prisoners. The flipper also doesn't have to use all of their flips.
I will simulate a round between every triplet of `(prisoner1, prisoner2, flipper)`, including having prisoners play against themselves.
A prisoner receives one point whenever they defect (output `'d'`), and receives two points whenever the other prisoner cooperates (outputs `'c'`). Note that the prisoner's score is not directly affected by the flipper's action - the flipper only affects communication, not score.
A flipper receives one point whenever either of the prisoners defects.
A program's overall score is its average score over all of its matchups. The players will be all valid submissions to the question, plus the [basic programs](https://github.com/isaacg1/adversarial-ipd/blob/main/basic.py) to get us started.
## Restrictions
Do not modify the input, other than the state variable. Do not interact with the environment. Do not make a sacrificial submission that attempts to benefit other submissions. Submissions may not duplicate the [basic programs](https://github.com/isaacg1/adversarial-ipd/blob/main/basic.py) or other earlier submissions. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are not allowed.
Update: Please make your submissions deterministic, so I don't need to run the tournament many times to get an average.
If you have any questions, feel free to ask!
## [Current results](https://github.com/isaacg1/adversarial-ipd/blob/main/results.txt)
```
Prisoners:
string_prisoner: 166.995
prisoner_nn: 154.392
masquerade: 153.781
slightly_vindictive: 153.498
basic_defect: 152.942
basic_tit_for_tat: 150.245
holding_a_grudge: 147.132
use_their_response_unless_t...: 146.144
basic_threshold: 145.113
blind_rage: 144.418
basic_tit_for_two_tats: 143.861
stuck_buttons: 141.798
less_deterministic_prisoner: 134.457
tit_forty_tat: 134.228
detect_evil: 134.036
basic_cooperate: 118.952
Flippers:
string_flipper: 149.43
flipper_nn: 145.695
basic_immediate_flipper: 144.539
advanced_evil_p1_flipper: 143.246
basic_evil_p1_flipper: 131.336
basic_mod_4_flipper: 103.918
paranoia_pattern: 102.055
basic_steady_flipper: 100.168
basic_biased_flipper: 99.125
less_deterministic_flipper: 90.7891
basic_random_flipper: 86.5469
tempting_trickster: 66.1172
basic_non_flipper: 63.7969
```
---
I will declare a pair of winners (one prisoner, one flipper) one month after this challenge is posted.
See for comparison my [Noisy Iterated Prisoner's Dilemma](https://codegolf.stackexchange.com/q/164205/20080) challenge, where there is randomness instead of an adversary, as well as evolutionary scoring.
[Answer]
# Neural Networks (Prisoner + Flipper)
```
import math
def sigmoid(z):
z = max(-60.0, min(60.0, 5.0 * z))
return 1.0 / (1.0 + math.exp(-z))
def eval_nn(nn, inputs, output_size):
values = {}
for i, x in enumerate(inputs):
values[~i] = x
for v, bias, links in nn:
val = bias
for v2, w in links:
val += values[v2] * w
values[v] = sigmoid(val)
return [values[i] for i in range(output_size)]
def flipper_nn(p1_plays, p1_flipped, p2_plays, p2_flipped, flips_remaining, f_state):
flipper = [(2,1.1181821042173234,[(-4,1.7400885547178728),(-5,-0.06813411778649736),(-1,0.36820555967416463)]),(1413,0.5463770972701019,[(-7,1.2906662332985084)]),(1006,-0.7872435180237973,[(-1,0.15812448989961483)]),(400,0.8765368123690065,[(-1,-0.5507089170354788),(-4,-2.6155008235530275),(-6,-0.13973123898832307),(1413,0.611948590243875)]),(4,-0.7227321303517735,[(-5,1.5683558624231078),(-6,-1.2370613914091573),(-4,0.5237132563743849),(1006,-0.32865555879156394)]),(0,-0.8037738878771841,[(400,-1.539896544478685),(-6,-1.2406408935562372),(-2,1.4008065675860095),(-5,1.3368457316858942)]),(1241,2.8053793783985843,[(400,-1.1720600247508444)]),(3,-0.6671763505247656,[(-7,1.3637083521769713),(-2,0.23978597611290645),(400,0.07355299289323734),(-5,1.4847572012033936)]),(5,1.3240920945810233,[(-3,0.09279702179768222),(-4,-0.42695177997561584),(400,0.01877521376790067)]),(1,1.4532564361954763,[(-4,-3.3511395309047542),(-6,3.4483449908621946),(400,-0.30914255807222707),(-1,4.416629240437298),(1241,-3.2869409990358784)])]
if not f_state:
f_state.append([0, 0, 0, 0])
p1_play = 1 if p1_plays[-1] == 'c' else -1
p2_play = 1 if p2_plays[-1] == 'c' else -1
d1, d2, *f_state[0] = eval_nn(flipper, [p1_play, p2_play, flips_remaining, *f_state[0]], 6)
return 2 * (d1 > .5) + (d2 > .5)
def prisoner_nn(p1_plays, p2_flipped, p1_state):
prisoner = [(0,-2.2128141878495886,[(-2,0.647135699564962),(-1,-3.819879756972317),(-6,-1.5898309666275279),(-5,-1.3569920659927621)]),(2,-0.026842109156755112,[(-6,1.9088324301092459),(-1,-1.498237595085962),(-2,-1.3979942638308056)]),(3,-1.4642587337125894,[(-5,0.027435320810760975),(-3,0.8940799124862344)]),(5,-1.5627901857506785,[(-7,-0.3885493442923349),(-4,-0.6468723685254656),(-6,0.4827740033482678),(-1,1.0907376062753547)]),(3655,-0.6335740926081981,[(-3,-1.131136914882346)]),(4,0.030539518044983505,[(-4,0.6436349726871196),(-6,-0.7427970484374815),(3655,-0.23969124478552287)]),(1,0,[])]
if not p1_state:
p1_state.append([0, 0, 0, 0, 0])
lastact = (1 if p2_flipped[-1] == 'c' else -1) if p2_flipped else 0
lastsact = (1 if p1_plays[-1] == 'c' else -1) if p1_plays else 0
act, *p1_state[0] = eval_nn(prisoner, [lastsact, lastact, *p1_state[0]], 6)
return ['d', 'c'][act > 0.5]
```
Created using [neat-python](https://github.com/CodeReclaimers/neat-python/), but I added a simple neural network implementation so it isn't a dependency.
[Answer]
# Paranoia Pattern (flipper)
```
def paranoia_pattern(
p1_moves, p1_flipped_moves, p2_moves, p2_flipped_moves, flips_left, state
):
turn = len(p1_moves)
match turn:
case 1:
# Don't let them get off on the right foot
return 3
case 2:
# And don't let them get used to it
return 0
case _ if flips_left > 4:
# Then alternate aggressively...
return 1 << (turn % 2)
case 65 | 66:
# and finally throw them back off if they've gotten used to the break.
return 3
case _:
return 0
```
I noticed that the "smarter" pre-packaged flippers never "waste" a flip on a defect. This means prisoners are more able to trust that cooperates are in fact real, which also reduces their incentive to defect for real, if they can tell the flipper isn't just constant or random.
However, prisoners can and should live in constant fear of betrayal instead, and this flipper will aggressively beat it into them, without even bothering to look at what they're actually doing.
[Answer]
# Masquerade (prisoner)
```
def masquerade(my_plays, their_flipped_plays, state):
turn = len(my_plays)
if turn == 0:
return "c"
elif turn == 2:
return "d"
elif turn < 7:
return "c"
always_cooperate_patterns = [
['c', 'd', 'c', 'd', 'd', 'c', 'd', 'c'], ['c', 'c', 'c', 'd', 'd', 'd', 'c', 'c'],
['d', 'c', 'c', 'd', 'd', 'd', 'c', 'c'], ['c', 'c', 'c', 'c', 'd', 'c', 'd', 'c'],
['c', 'c', 'd', 'd', 'd', 'd', 'd', 'd'], ['d', 'c', 'd', 'c', 'c', 'c', 'd', 'c'],
['c', 'c', 'd', 'c', 'd', 'c', 'd', 'd'], ['d', 'd', 'd', 'd', 'c', 'c', 'c', 'c'],
['d', 'd', 'c', 'd', 'c', 'c', 'c', 'c'], ['d', 'c', 'd', 'd', 'c', 'c', 'd', 'c'],
['c', 'd', 'c', 'd', 'd', 'd', 'c', 'c'], ['c', 'c', 'c', 'c', 'd', 'c', 'c', 'd'],
['c', 'd', 'c', 'd', 'd', 'c', 'c', 'c'], ['c', 'c', 'c', 'c', 'd', 'd', 'c', 'c'],
['c', 'c', 'c', 'd', 'd', 'c', 'c', 'd'], ['d', 'c', 'd', 'c', 'c', 'd', 'c', 'c'],
['c', 'd', 'd', 'd', 'c', 'c', 'd', 'd'], ['c', 'c', 'c', 'd', 'd', 'd', 'd', 'd'],
['d', 'd', 'd', 'c', 'c', 'd', 'd', 'd'], ['d', 'd', 'd', 'c', 'd', 'd', 'd', 'd'],
['c', 'c', 'd', 'c', 'c', 'c', 'd', 'c'], ['d', 'c', 'd', 'd', 'c', 'd', 'c', 'c'],
['d', 'c', 'c', 'c', 'd', 'c', 'd', 'd'], ['c', 'd', 'd', 'd', 'c', 'd', 'c', 'c'],
['c', 'c', 'c', 'd', 'c', 'c', 'd', 'c'], ['d', 'd', 'c', 'd', 'd', 'd', 'd', 'd'],
['c', 'c', 'd', 'd', 'c', 'c', 'c', 'c'], ['c', 'c', 'd', 'c', 'c', 'd', 'c', 'c'],
['c', 'c', 'c', 'd', 'c', 'c', 'c', 'c'], ['c', 'c', 'd', 'c', 'c', 'c', 'c', 'c'],
['c', 'c', 'c', 'd', 'd', 'c', 'c', 'c'], ['c', 'c', 'd', 'c', 'c', 'c', 'c', 'd']
]
# "self"-detection
if their_flipped_plays[:8] in always_cooperate_patterns:
return "c"
# defect for the last few turns
if turn > 30:
return "d"
# if they often defect, defect as well
if their_flipped_plays.count("d") > 0.3 * len(their_flipped_plays):
return "d"
# tit-tit for tat
# inspired by slightly vindictive
if "d" in their_flipped_plays[-2:]:
return "d"
return "c"
```
Plays nice for the first 7 rounds, then switches to tit-tit for tat, and finally switches to only defecting after turn 30. Also detects initial patterns where it is optimal to always cooperate.
[Answer]
# Prisoner
```
def use_their_response_unless_they_are_foolish(my_plays, their_flipped_plays, state):
# play "c" at beginning
if not len(my_plays): return 'c'
# play "d" at last few turns
if len(my_plays) > 96: return 'd'
# if op always answer "c", we can cheat on it
if 60 < len(my_plays) < 1.8 * their_flipped_plays.count('c'): return 'd'
# otherwise, play 'c' they play 'c'
if their_flipped_plays[-4:].count('c') >= 2: return 'c'
# or randomly select a response from their past behavior
rand = their_flipped_plays * 5 + ['c', 'd']
return rand[(int('0x' + ''.join(their_flipped_plays), 16) ^ 17 ** len(my_plays)) % len(rand)]
```
[Answer]
# Holding A Grudge (prisoner)
```
def holding_a_grudge(
my_plays, their_flipped_plays, state
):
# First cooperate for 7 plays:
if len(my_plays) < 7: return 'c'
# If 3 or more of their first 7 plays were defects,
# hold a grudge for the entire round and keep defecting as well:
amountOfDefects = their_flipped_plays[:7].count('d')
if amountOfDefects >= 3: return 'd'
# If none of their first 7 plays were defects, always cooperate yourself:
if amountOfDefects == 0: return 'c'
# Otherwise, cooperate 3/4th of the times:
rand = (int('0x' + ''.join(their_flipped_plays), 16) ^ 17 ** len(my_plays)) % 100
if rand >= 25: return 'c'
return 'd'
```
(`rand` taken from [*@tsh*' answer](https://codegolf.stackexchange.com/a/266204/52210).)
[Answer]
# Tit Forty Tat (Prisoner)
```
def tit_forty_tat(my_plays, their_plays, state):
defects = their_plays.count('d')
if(defects > 40):
return their_plays[-1]
else:
return 'c'
```
*Fool me 40 times, shame on you. Fool me 41 times...*
Assumes any defect is the result of flipping, and an honest mistake.
After 40 defects however, the other player **must** have defected intentionally, so we just play Tit for Tat for the rest of the round.
[Answer]
# String (prisoner + flipper)
```
def string_prisoner(my_plays, their_plays, state):
s = "zbemvqjmwqozghuxgymklypogluxxnfvdzcmcusncnsqnuktdhxesvaipgyphcpfgmirmmqlahnkofttkcshrbpvslqngmkjmspkrdzujs"
if state:
i = 'cd'.index(my_plays[-1])
j = 'cd'.index(their_plays[-1])
else:
state.append(18)
i, j = 1, 0
h = state[-1]
h = ord(s[4 * h + 2 * i + j]) - 97
state[0] = h
return 'cd'[h % 2]
def string_flipper(p1_moves, p1_flipped_moves, p2_moves, p2_flipped_moves, flips_left, state):
s = "wvwyhbwyjplcvuowuuwyobcyunxypirmhisyxmsenxqypkcyomgqwnuaomrypzkyxnwblegqdssijkbhnjywnnmrpzwygxsepbwypfsysn"
if state:
i = 'cd'.index(p1_moves[-1])
j = 'cd'.index(p2_moves[-1])
else:
state.append(13)
i, j = 0, 1
h = state[-1]
h = ord(s[4 * h + 2 * i + j]) - 97
state[0] = h
return h % 4
```
[Answer]
# Slightly Vindictive (prisoner)
```
def slightly_vindictive(my_plays, their_flipped_plays, state):
# play nice(-ish) if they've ever cooperated
if 'c' in their_flipped_plays:
# defect twice when they defect once
if 'd' in their_flipped_plays[-2:]:
return 'd'
return 'c'
# wait up to 10 turns for opponent to cooperate
if len(my_plays) <= 10: return 'c'
return 'd'
```
[Answer]
# Tempting Trickster (flipper)
```
def tempting_trickster(
p1_moves, p1_flipped_moves, p2_moves, p2_flipped_moves, flips_left, state
):
# Tease them a bit
target = 'dc'[len(p1_moves) <= 3]
move = p1_moves[-1] == target
move |= (p2_moves[-1] == target) << 1
return move
```
Inspired by a more ambitious prisoner I'm working on...
What if the best way to get prisoners to defect is not to actually make them look *bad* to each other, but rather to convince them that
1. the other prisoner is very patient and won't retaliate too quickly if offended
2. if you defect for real, the flipper will actually cover for you?
The answer is a pretty hard "no" in a test run--this barely does better than not flipping at all--but maybe it'll have its time to shine later.
[Answer]
## Detect Evil
The goal here is to detect if the opponent is evil. We use our knowledge of the 40 max count of flips to hedge our bets.
```
def detect_evil(my_plays, their_plays, state):
turn = len(their_plays)
# Batter through the flipper by sending more than 20 "c"s to start:
if (turn < 22):
return "c"
# Defect last few turns, just because
if (turn > 96):
return "d"
# See if it is plausible that they are always cooperating. If so, cooperate:
their_coop = their_plays.count("c")
if (their_coop + 20 >= turn):
return "c"
# seed possible returns to cooperation around the half-way point:
if (turn > 49 and ((turn % 7) == 0)):
return "c"
# Try to return to cooperation state if they "c"'d last turn in response
# or in coordination with my "c":
if (their_plays[-1:] == ["c"]) and (my_plays[-2:].count("c") > 0):
return "c"
# Assume flipper flips 20 "c" to "d" on their side:
their_defect = their_plays.count("d")
their_defect_min = their_defect-20
their_defect_chance = their_defect_min / turn if (turn > 0) else 0
# Assume flipper flips 20 "c" to "d" on my side:
my_defect = my_plays.count("d")
my_defect_max_count = my_defect + 20
my_defect_chance = my_defect_max_count / turn if (turn > 0) else 0
# Tit-tit-tit for tat, but only if they are probably defecting more than
# they see me defecting:
if their_plays[-3:].count("d") > 0:
if my_defect_chance < their_defect_chance:
return "d"
# Otherwise, assume the best:
return "c"
```
we don't try to detect stupidity in our counterparty ("c" always, regardless of our "d"), just evil (sends "d"s at us).
The enemy "d"ing as many times as they see us "d" is considered "fair", and we assume the flipper is making both of us look more evil than we are.
If the enemy is detected as evil, we defect whenever we see a "d" in the last 3 turns. Otherwise, we cooperate always.
Finally, throw in some unilateral "c"s in the last half of the game, to prevent the hostile "tit tit tit for tat" from leading to a needless chain of "d". A bit of forgiveness.
(I'll be back to fix typos.)
[Answer]
# Modulo 4 (flipper)
```
def basic_mod_4_flipper(
p1_moves, p1_flipped_moves, p2_moves, p2_flipped_moves, flips_left, state
):
return len(p1_flipped_moves) % 4
```
Very simple submission, but still effective
[Answer]
## Make P1 Look Evil Flipper
```
def basic_evil_p1_flipper(
p1_moves, p1_flipped_moves, p2_moves, p2_flipped_moves, flips_left, state
):
out = 0
if p1_moves[-1] == "c":
out += 1
return out
```
but the problem is, P1 could see a friendly P2. And if P2 isn't vindictive enough, P1 could work out that P2 is nice, and stubbornly refuse to defect.
So we allocate up to 10 flips to shutting down P2's overtures of niceness, and the remainder make P1 look like they always-defect.
## Fool P1 as well
```
def advanced_evil_p1_flipper(
p1_moves, p1_flipped_moves, p2_moves, p2_flipped_moves, flips_left, state
):
out = 0
if p1_moves[-1] == "c":
out += 1
turn = len(p1_flipped_moves)
turns_left = 100-turn
p1_coop = p1_moves.count("c")
p1_visible = p1_flipped_moves.count("c")
p1_flips_used = p1_coop - p1_visible
p1_coop_percent = p1_coop / turn if turn > 0 else p1_coop
p2_coop = p2_moves.count("c")
p2_visible = p2_flipped_moves.count("c")
p2_flips_used = p2_coop - p2_visible
flips_left = 40 - p1_flips_used - p2_flips_used
if (p2_coop <= 10 or (flips_left > (p1_coop_percent*turns_left))):
if (p2_moves[-1] == "c"):
out += 2
return out
```
Here, we always flip P1 if we can.
We expend flips to make P2 always defect if it is before turn 10, *or* if we project that we have enough flips to keep P1 always defecting while also flipping this move for P2.
So players looking for cooperation won't see it at the start of the game. If they decide to attempt to regain trust mid-way through the game, they still won't see cooperation. And if P2 assumes up to 20 fake defects on the other party will conclude P1 is evil, and hopefully give up on them.
[Answer]
# Blind Rage (Prisoner)
```
def blind_rage(my_plays, their_plays, state):
if not state:
# Start in a good mood
state.append(0)
return 'c'
if state[0] >= 5:
# Calming down...
state[0] = 0
return 'c'
if state[0]:
# Rage mode
state[0] += 1
return 'd'
if their_plays[-1] == 'd':
# "You dare defect against me? I'll show you!"
state[0] += 1
return 'd'
# Normal course of operation.
return 'c'
```
Usually a cooperative prisoner, this one will fly into a blind rage when the opponent defects. Only calms down after 5 moves.
[Answer]
# Stuck Buttons (Prisoner)
```
def stuck_buttons(my_plays, their_plays, state):
if not state:
state.append(4)
state.append(-1)
return 'c'
if state[0]:
state[0] -= 1
return my_plays[-1]
else:
state[0] = 4
state[1] += 1
return their_plays[state[1]]
```
I want to use the tit for tat strategy, but the buttons for "cooperate" and "defect" have been used so much they're getting stuck. I can't seem to change my choice until after 4 turns!
[Answer]
# Less-Deterministic
## Prisoner
```
def less_deterministic_prisoner(my_plays, their_plays, state):
if not state:
state.append(0xe1) # Initial state
state.append(8) # Whether to collect more info for seed
state.append(False) # PRNG has been initialized?
return 'c'
if state[1]:
# Seed the PRNG with the data we get
state[0] <<= 1
state[0] |= (their_plays[-1] == 'd')
state[1] -= 1
return 'c'
if not state[2]:
# XOR with some data for some good old security through obscurity.
state[0] ^= 0x03
state[2] = True
# PRNG is properly seeded now!
my_choice = (state[0] & 0x8000) >> 15
tap16 = (state[0] & 0x8000) >> 15
tap15 = (state[0] & 0x4000) >> 14
tap13 = (state[0] & 0x1000) >> 12
tap4 = (state[0] & 0x0008) >> 3
feedback = tap16 ^ tap15 ^ tap13 ^ tap4
state[0] <<= 1
state[0] &= 0xffff
state[0] |= feedback
return 'cd'[my_choice]
```
## Flipper
```
def less_deterministic_flipper(p1_moves, p1_flipped_moves, p2_moves, p2_flipped_moves, flips_left, state):
if not state:
state.append(0x21) # Initial state
state.append(4) # Whether to collect more info for seed
state.append(False) # PRNG has been initialized?
return 0
if state[1]:
# Seed the PRNG with the data we get
state[0] <<= 1
state[0] |= (p1_moves[-1] == 'd')
state[0] <<= 1
state[0] |= (p2_moves[-1] == 'd')
state[1] -= 1
return 0
if not state[2]:
# XOR with some data for some good old security through obscurity.
state[0] ^= 0x44
state[2] = True
# PRNG is properly seeded now!
first_bit = (state[0] & 0x8000) >> 15
tap16 = (state[0] & 0x8000) >> 15
tap15 = (state[0] & 0x4000) >> 14
tap13 = (state[0] & 0x1000) >> 12
tap4 = (state[0] & 0x0008) >> 3
feedback = tap16 ^ tap15 ^ tap13 ^ tap4
state[0] <<= 1
state[0] &= 0xffff
state[0] |= feedback
second_bit = (state[0] & 0x8000) >> 15
tap16 = (state[0] & 0x8000) >> 15
tap15 = (state[0] & 0x4000) >> 14
tap13 = (state[0] & 0x1000) >> 12
tap4 = (state[0] & 0x0008) >> 3
feedback = tap16 ^ tap15 ^ tap13 ^ tap4
state[0] <<= 1
state[0] &= 0xffff
state[0] |= feedback
# Use the two bits to make a choice
choice = first_bit << 1
choice |= second_bit
return choice
```
Implements a simple PRNG that is seeded with the input we get from the opponent. With three total players in the mix, surely there's no way the others will be able to reliably influence our PRNG for their gain, right?
This bot is different from `basic_random_flipper` as it attempts to output a different sequence for each interaction.
[Answer]
# Non-deterministic
*EDIT: This bot is non-competing - see @isaacg's comment below.*
## Prisoner
```
def non_deterministic_prisoner(my_plays, their_plays, state):
state.append(object())
return 'cd'[hash(str(state)) % 128 < 65]
```
## Flipper
```
def non_deterministic_flipper(p1_moves, p1_flipped_moves, p2_moves, p2_flipped_moves, flips_left, state):
state.append(object())
return hash(str(state)) % 4
```
`basic_random_flipper` is in fact deterministic (in that it will flip the same way given the same state). This flipper relies on where it is placed in memory, which means it will output different results even if given the same state.
I suppose it's not *technically* non-deterministic as you could in theory predict where the objects will be created in memory.
]
|
[Question]
[
Your task is to take as input a single string (or list of characters, list of code points, etc.) and return the length of the longest substring with no character appearing more than once.
**Aside:** This challenge is similar to [Longest Non-Repeating Substring](https://codegolf.stackexchange.com/q/154331/65425), but *without* the source restriction ranking submissions by their own longest non-repeating substring.
---
### Assumptions
* You may assume that the input contains only lowercase letters and is non-empty (ie. the input will match the regex `(a-z)+`).
* This challenge will use the following definition for substring: "A *contiguous* sequence of characters contained in the input string"
* By "non-repeating" I mean that no letter of the substring is repeated more than once
### Examples
If the input is `abcdefgabc` then the longest substrings with no repeating characters are `abcdefg` and `bcdefga` (their positions in the string are `[abcdefg]abc` and `a[bcdefga]bc`). The length of these substrings is `7`, so the output would be `7`.
If the input is `abadac` then the longest substrings with no repeating characters are `bad` (`a[bad]ac`) and `dac` (`aba[dac]`) so the output is `3`.
If the input is `aaaaaa` then the longest substring with no repeating characters is `a` so the output is `1`.
If the input is `abecdeababcabaa` then the longest substrings with no repeating characters are `abecd` (`[abecd]eababcabaa`)
and `cdeab` (`abe[cdeab]abcabaa`). The output is thus `5`.
### Test Cases
```
abcdefgabc -> 7
aaaaaa -> 1
abecdeababcabaa -> 5
abadac -> 3
abababab -> 2
helloworld -> 5
longest -> 7
nonrepeating -> 7
substring -> 8
herring -> 4
abracadabra -> 4
codegolf -> 6
abczyoxpicdabcde -> 10
```
### Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes for each language wins
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 51 bytes
```
f=lambda s:s>''and max(n:=f(s[:-1]),len({*s[~n:]}))
```
[Try it online!](https://tio.run/##NU3bbsMgDH3PV/gtMK3Tsm5dhZT@SJQHEyCJRAEBVTdN269nhmxYsn0uPoTPvHh3PIe4baa3eJUKIYl0aVt0Cq74wZzoDUuDOHQjf7Tasa@HNPw4MX5zvt2X1WroRAOrC9CXfsuMP6Vg18xaOFyg5Q1gSjpmMIz04Xnk0BdrrpBiN5ST0mamUS7eG6yv7F2DUpOIkkRqlXwjEhVW87HstQp6aRZtrb/7aNXutN7NOuU913kXddCYVzfvTLrJlOMfPNN1/AevFBxxon9o7MTklZ69NQWdfgE "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ẆQƑƇṪL
```
A monadic link accepting a list of characters (or whatever), which yields the length.
**[Try it online!](https://tio.run/##y0rNyan8///hrrbAYxOPtT/cucrn////iUmpySmpiUmJSclAIhEA "Jelly – Try It Online")**
### How?
```
ẆQƑƇṪL - Link: list
Ẇ - all sublists (ordered by length)
Ƈ - filter keep those which are:
Ƒ - invariant under:
Q - deduplication
Ṫ - tail
L - length
```
[Answer]
# [Julia 1.0](http://julialang.org/), ~~98~~ ~~74~~ 73 bytes
```
~=length
!s=max(.~filter(z->[z...]==z∪z,[s[x:y] for x=1:~s,y=1:~s])...)
```
[Try it online!](https://tio.run/##RZBdboQgEMefyynYfdLEmtrvbMKmD72FMRuEUWkpGGCz6oPPPUuP1YtYhLZCwp/5zQwzw9tZCloMyzITCap1HdpZ8kGHJJ8bIR2YZLo@llOe5xUh0/fn15SVthwOY4UbbfBAisNsszFIlfqwdOHkVTCXoKs9rRmHpvWyx@SIn7KVhRXsItg1@CBa@yB/RMdDdFBOY@Ldrx12ILcr6UBKfdFG8i1LatWCdVs9pZWBHqgTqt2oPdfWmT/0HF8z/@A@FjSU@R68bJBpDq2WTSCPMYxNox56wXiYN452g1KEXmynL5hKeXK@J3vqqbXAMVlRUu7eYcSEYF76S/zOlQi1ik14WqVo@QE "Julia 1.0 – Try It Online")
* -3 bytes thanks to @amelies: replace `unique` with `∪` (`union`)
* -4 bytes thanks to @amelies: replace `collect` with splat operator `...`
* -6 bytes thanks to @amelies: replace `in` with `=` in array comprehension
* -5 bytes thanks to @amelies: vectorize the reassigned operator (`~` => `.~`)
* -2 bytes thanks to @amelies: unary operators don't need parentheses
* -4 bytes thanks to @amelies: condense ranges to remove a `for` statement
* -1 byte thanks to @MarcMush: replace `∪(z)` with `z∪z`
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 49 bytes
```
Tr[1^Last@Select[Subsequences@#,DuplicateFreeQ]]&
```
[Try it online!](https://tio.run/##LY7BCgIxDER/RVYQBWHxA4SC4smDojdRSLtjV@i2mmbxIH57ja4JJG@GEKYjadGR3BwVvyxHPi0uW8piDghwcjr0NuPRIzpkM56v@3vQU8GGgf35PCk7vkUZ1cbXZrpqickJONfmVZF1Da5eVzWv6FdfsFCbrNo6BocacgP8WrFFCOmZODQqQooeWZRiiow7NG70KrOGEx64Bf@JrIbQl7pUudTAp3Ct3rNSPg "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 80 bytes
```
m;f(char*s){int F[128]={},i=0;for(;s[i]*!F[s[i]]++;i++);i=i?i>(m=f(s+1))?i:m:0;}
```
[Try it online!](https://tio.run/##NU3LboMwELz7K7aRUtmBSJC@olgkt/wE5WD8IJbAjmxQVCH669SG1Ct5d2ZnZvm@4XyeO6owvzG382TUpodrmR@OVTFOqS4yqqzD1Je62r1cy9irJKE6SQjVhb7oM@4KhX2SE3LRp@6U0WmOYaDNfejLPMuqFMTQdT/loaIQ8@3QhxVFce6YNpjAiOBx060E/Os5Mwpvtj6U2KRrzjMihdfVTBYL3F3IiGIBBWzFtwl6hRcHSZ93CAUEEwIn@8EZyCiaZlZzIVUTGuzP8IXY8uKcI1bLsGR1WIZvIT8CyQRbxG9xXiqiA7rJtrUP61qxKltrGun7NddY4@Rdsl6bZmX8UPvePeExuN0/eA/BjvFwJ7SV4FbIxrYqos8/ "C (gcc) – Try It Online")
---
### [C (gcc)](https://gcc.gnu.org/), 83 bytes
An alternate non-recursive answer, although 3 bytes longer.
```
m;f(char*s){for(m=0;*s;)for(char*t=s++,F[128]={};*t*!F[*t]++;m=m>t++-s?m:t-s);++m;}
```
[Try it online!](https://tio.run/##NU3LbsMgELzzFdtIqYyxJSd9RUVOb/kJ1wcM@CEZiAArqiL3112wU1ZiZ2dnZnnecb4sirYJ75lNHb63xiaqLGjqKI545X3pCMku1eF4qsv7TFOfPl2q1NeEUFWqsyckd1/q0@cOU0IUnZfog0FfJ18diqLOQExK/VTHmgbWg5l8WFEUsWKDTjDcEdz6YZSQ/DrOdJvs9i6U2GVbziMig@fNjFcLXG3IiGIBJezFtw76NlkdOHvcwRQQzAis9JPVUFA0L6zhQrZdaJCf4QOx9UV8QKyRYcmasAzfSr4Fkgm2il8iXitOR9TLcTQ3Y0exKUejO@n8lquNtvIqmR90tzFuapy3j/EU3PZ/eA3BlvFwJ7SN4EbIzoxtnN7/AA "C (gcc) – Try It Online")
[Answer]
# [Python](https://docs.python.org/), 63 bytes
```
f=lambda s:len({*s})<len(s)and max(f(s[1:]),f(s[:-1]))or len(s)
```
**[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P802JzE3KSVRodgqJzVPo1qruFbTBsQq1kzMS1HITazQSNMojja0itXUATGsdA1jNTXzixQgav4XFGXmlQCVqCcmpSanpCYmJSYlA4lEdU3N//8B "Python 3.8 – Try It Online")**
[Answer]
# [Haskell](https://www.haskell.org/), ~~83~~ 75 bytes
-8 using guarded list comprehension for the length.
```
import Data.List
f[]=0
f x=sum[1|nub x==x,_<-x]`max`f(tail x)`max`f(init x)
```
[Try it online!](https://tio.run/##VZFNb4MwDIbv/AoL9QAa7dZ9H8Yu227taceuag2EDy0kKDFqDvvvnaG0hSCR@HntFxOXaH@FlMeqbrQh@NCKjJaLtVaYQZBrs95FcCiFCs8pn0i4WFWWvHyzje@8HFxs23qz/FNtwufYRbu3udvua3T7PCCsJLhwiCpVEUfHFK2wEMMm8DFJM5EXvPkRvISRB7wYc7S8Rv2aokRwISZcyK9OexppmGHn9zBG/cPw/gJL/nV90EZmk3KpVSEsTfpRWhnRCKRKFRPBtoklc6KvI2czsMdRCwZTboy3CU91Jgotc4bP4dbzaqwU302mWe8nAKfrmsFP4CIQrhEpiSyE@fspCUAKgqFrrsx71k0NgjN1cBuPSmd9CkDT0jeZlWJz/2tQL04@3NxAYEt94Jl1Zx9IQyLGwtWy15OW4IB2nDG7@LmQv2oEtYYbC4// "Haskell – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 88 bytes
```
function(l)max(apply(combn(seq(l),2),2,function(v)all(table(l[v[1]:v[2]])<2)*diff(v)))+1
```
[Try it online!](https://tio.run/##pc7BCoMwDAbgu08h7tJuHqawDcZ8EpHR1iiFrO1sFLeXdznJTjIYhBBC@PIPC3rXQ6S7826AAIqs6@9x1JEGnqqlG50h651A@VCzUCHgSxj/0E5EePI2L7ny9WySClGQ0ggC66kumutUl00jb6Xct7br@ELKQ7EgEMEQK6xGhzaS4I8xoCWRfWfJ8iyTMt2ll2Q7KkdJkg1UafN@@TlY0/LYwgoXx79lYE9pZrmpFT796RrfQu@xW8HzD@DyAQ "R – Try It Online")
Input is vector of individual letters.
Commented:
```
max( # maximum value of:
apply( # loop over
combn(seq(l),2) # all pairs of values in 1:length(l)
# (so all possible start & end indices of contiguous subsets)
,2,function(v) # for each pair assigned to 'v':
all(table(l[v[1]:v[2]])<2) # table() counts the different items in each subset v[1]:v[2]
# so: 'all(table()<2)' indicates a nonrepeating subset
*diff(v) # multiply by diff(v) = end-start = subset size -1
))+1 # so finally we have to add 1 to get the subset size
```
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 11 bytes
```
$:u/¦l¦¦_⌉)
```
[Try it online!](https://tio.run/##S0/MTPz/X8WqVP/QspxDyw4ti3/U06n5/38iAA "Gaia – Try It Online")
I feel like there's probably a byte or two that can be removed...
[Answer]
# [Husk](https://github.com/barbuz/Husk), 8 bytes
```
▲mLfS=uQ
```
[Try it online!](https://tio.run/##LY7LDQIxDER7yZkW6IAL4og4OI6TrMjGq3zE57YUQSGUtI0Ek2BLnjdjybKv@drm7bW27f2ZD/a0r8fW2lmBRkPWiaidgl4/0CQxaIlljAQM4IDegp5C4BunYMQEjo5yEYocEy0EZYpObK46lzTYU/oT6AQoJ0XEIRtyHGxf4PPB92VC039Tly8 "Husk – Try It Online")
```
▲mLfS=uQ
▲ # maximum value of
mL # lengths of
f Q # all contiguous sublists of input that are
S=u # equal to themselves without duplicates
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `l`, 8 bytes
```
ǎ'¨=U;ÞG
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJQbCIsIiIsIseOJ8KoPVU7w55HIiwiIiwibm9ucmVwZWF0aW5nIl0=)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 7 bytes
```
le{I#.:
```
[Test suite](https://pythtemp.herokuapp.com/?code=le%7BI%23.%3A&test_suite=1&test_suite_input=%22abcdefgabc%22%0A%22aaaaaa%22%0A%22abecdeababcabaa%22%0A%22abadac%22%0A%22abababab%22%0A%22helloworld%22%0A%22longest%22%0A%22nonrepeating%22%0A%22substring%22%0A%22herring%22%0A%22abracadabra%22%0A%22codegolf%22%0A%22abczyoxpicdabcde%22&debug=0)
##### Explanation:
```
le{I#.: | Full code
le{I#.:Q | with implicit variables
---------+-----------------------------------------------------------------------
.:Q | All substrings of input
# | Filter over
{I | whether the substring is the same as itself without duplicate letters
le | Length of the last (longest) substring
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0, 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ã Ôæ_¶âÃl
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=4yDU5l%2b24sNs&input=ImFiY2RlZmdhYmMi)
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 28 bytes
```
Lw`.+
A`(.).*\1
O^$`
$.&
\G.
```
[Try it online!](https://tio.run/##HY1BCsMwDATvekda0hYMeUJPuRT6gRAs24pTMFZRXPJ8V/YKdqQ9aIXKJ@NUL@Ns6@u05gFPO5qbuS8TvNfBwmCusMymVnQ@0BYVgF2AjjRCp5FauzGgb@gDO6XEJ0sKkDhHOgpkzkJfQm2NcPzcUaRtO0knOkGvTxTgOVDktP0B "Retina – Try It Online") Link includes test cases. Explanation:
```
Lw`.+
```
List all nontrivial substrings.
```
A`(.).*\1
```
Delete those which duplicate characters.
```
O^$`
$.&
```
Sort in descending order of length.
```
\G.
```
Count the first length.
The longest length can also be found using these stages for the same byte count:
```
%C`.
```
Take the length of each remaining substring.
```
N^`
```
Sort in descending order.
```
1G`
```
Keep the first length.
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + Core utilities, 46 bytes
```
sed -E ':a;s/(\w)(\w*)\1/\1\2\n\2\1/;ta'|wc -L
```
[Try the test cases online!](https://tio.run/##RYzBasMwEETv@xWDKaRpcU16bNLc0lOhP@DLStpYBkUKkoN7yL@7G6Wlu8zO8GDHcPGL5Qn7c05D5hN2u@bw9dEsRRzaA1ZvvC3dYz@vVU/rftP1m/61j6pNt514dZ0t2s9Ff4isPyWHy/M3ftuIZj8GQRZ2CGMUAlzSA4j1CW1E83DjeN@j@ed32OCKl@6v6vZZC4CFjXVyHNRAXEfdiEI2CvVUwI5t9bogLyGkOeXgQCHFQcoEiilmOQtPYxxA5WLKlGv0ku@BTWarXWogm5wMKRzpBw "Bash – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
ŒʒDÙQ}€gà
```
[Try it online!](https://tio.run/##yy9OTMpM/f//6KRTk1wOzwysfdS0Jv3wgv//k/NTUtPzc9IA "05AB1E – Try It Online")
# Explanation
```
Œ All sublists
ʒ Filter:
DÙ Is the uniquified version
Q} Equal to the original?
€g Map length
à Maximum
```
[Answer]
# perl -n -Mfeature=say -MList::Util=max, 55 bytes
```
m;.+(??{$&=~/(.).*\1/||push@&,length$&})(?!);;say max@&
```
[Try it online!](https://tio.run/##HY7BbsMgEETvfEUqRchuG0c59BLLsj8gPebWywJrjEQAAVaSNu2nl6y9K@3bmcNoAkb7UQbeVXVbLm3zVvX9z5Z3f/uqqZvXr8P@8Qhzmgb@btHpPG35b131L3XbJrhvLnAbeCkgpMJRExisw0AgWSDIorNoUCAXrMsmtNZffbSKWe80psycdxEDQjZOszSLlOPyTRhXgoggKYTApFeovR3JlN93fwtGqrXDvw/ZeJfKzpXd50hhc8SOmpI6mZSPx3M2tqPaTw "Perl 5 – Try It Online")
Reads lines from `STDIN`, writing results to `STDOUT`.
For each line, it iterates over every sub string (`/.+(?!)/` will do that; `/(?!)/` will never match). For each sub string, if it doesn't contain a duplicated character (`/(.).*\1/` matches if there is a duplicated character), it stores the length of the sub string. We'll print the maximum of those values.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 11 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
éôU)¥¼ó8∩╦z
```
[Run and debug it](https://staxlang.xyz/#p=829355299daca238efcb7a&i=abcdefgabc%0Aaaaaaa%0Aabecdeababcabaa%0Aabadac%0Aabababab&m=2)
[Answer]
# [Factor](https://factorcode.org/), 48 bytes
```
[ all-subseqs [ all-unique? ] find-last length ]
```
[Try it online!](https://tio.run/##RU67bsMwDNz1FfyB5APaoWOQpUvRqchAS7QslKVkiobzQL7dldyhJMDjHUHyRvSWdfv8OL@fXqDSvJB4qke6mmJtglX4JhXi/yEUJbNb0SQG8wqvbl4fDgcfaIwNHO7RFGoSDk1qpXMM6Dvs6SZizmtWDo6zRKrmJItSIbQk0dVlqKa9m0h3xEHRtyMNnM@BYuaxP77f8rUkH3YP7rl9ATIf@j7NFf7YIqn5f4MLjEnCgbEaMEm0CS7bDxY4gmdC3X4B "Factor – Try It Online")
* `all-subseqs` Get all the substrings of the input from shortest to longest
* `[ all-unique? ] find-last` Find the last one whose elements are unique
* `length` Get its length
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes
```
⊇S&sS≠l
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1FXe7BacfCjzgU5//8rJeenpKbn56Qp/Y8CAA "Brachylog – Try It Online")
Another 7 bytes solution:
```
sᶠ≠ˢlᵐ⌉
```
[Try it online!](https://tio.run/##ASoA1f9icmFjaHlsb2cy//9z4bag4omgy6Js4bWQ4oyJ//8iY29kZWdvbGYi/1o "Brachylog – Try It Online")
### Explanation
Unfortunately, `s - substring` does not enumerate substrings of consecutive elements in descending order of length (if it did, we would have a 3 byte solution), but rather enumerates based on the indices. Therefore, we first state that we want a `⊇ - sublist`, which does not force consecutiveness, but which enumerates from longest to smallest.
```
⊇S S is a subset of the input (from longest to smallest)
& And
sS S is also a substring of consecutive elements of the input
≠ All elements of S are different
l Output the length of S
```
The second solution is a more "declarative" approach:
```
sᶠ Find all substrings of consecutive elements from the input
≠ˢ Select all substrings with all-different elements
lᵐ Map length
⌉ Max
```
[Answer]
# JavaScript (ES6), 72 bytes
```
f=s=>/(.).*\1/.test(s)?Math.max(f(s.slice(1)),f(s.slice(0,-1))):s.length
```
[Try it online!](https://tio.run/##fdLvTsMgEADw7z5FwycwG7X@22IyfQLfwC9XeqU1CAuHbm9fz/1xa9FBAoH8OLgL7/AFZGK/TnMfGhyGdkWr51Jqpa/fqlInpCRJvbxC6vQHbGUrSZPrDcpKqdlpdTOb84Z6Iu3Q29QNJngKDrULlg8JqE2DreVJFD9NqaIsi8XVlO3anpxYlbEaORzUHI4HEHv2kDNowEyj3f3Bdl2M2O2Udehc2ITomvMUsktd8JarJsaXZpn64COuEVLvrfif0WdNKR7ML1vmb4tn6Mju80wjGK4JT@ICM/wVbHDtuCCPwzc "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 61 bytes
A port of [@dingledooper's clever Python answer](https://codegolf.stackexchange.com/a/204432/58563) is 11 bytes shorter.
```
f=s=>p=s?f(s.slice(1))>(q=new Set(s.slice(0,p+1)).size)?p:q:0
```
[Try it online!](https://tio.run/##fdHvTsMgEADw7z5FwyeI2m3@27Kk20P4BFd6sBrCMQ5d4stX3HSuRT0SSOCXgzte4A1Yxz6kW08dDoNpuNmEhrdGcs2u1ygXSm3kvvF4qJ4xnbfnN@E6H9Xcv6PahvV@PR80eSaHtSMrjRTQ6g6NzYuoPkOpajarlldTdowT@WGLgrWY00Gb0@UJxIk9lgw60NNs97@w4xAjdjdlO3SODhRdd1lCcakjb5GTGF9aVOrJRwwIqfdW/M34teUUv8yZrcq3xQv0zR7KSiPo3JO8iH@Yzv9vyZlxQ56GDw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes
```
I⌈Eθ⌊Eθ§⌕A⁺✂θκLθ¹λλ¹
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzexIjO3NBdIF2gU6ij4ZuYhcx1LPPNSUis03DLzUhxzcjQCckqLNYJzMpNTQbLZOgo@qXnpJRkahZo6CoZAnAPFhpoQYP3/f2JSUWJyYgqI@q9blpMIAA "Charcoal – Try It Online") Link is to verbose version of code. Works by finding the maximum earliest duplicated character of the string and its nontrivial suffixes. Explanation:
```
θ Input string
E Map over characters
θ Input string
E Map over characters
θ Input string
✂ κLθ¹ Substring starting at outer index
⁺ λ Append current character
⌕A λ Find all matches of the current character
§ ¹ Take the second
⌊ Take the minimum
⌈ Take the maximum
I Cast to string
Implicitly print
```
[Answer]
# [T-SQL](https://www.microsoft.com/sql-server), 118 bytes
Input is taken from table `T` (according to the [Code Golf rules for SQL](https://codegolf.meta.stackexchange.com/a/5341/78876)): column `P` represents position and column `V` represents each character.
```
SELECT TOP 1B.P-A.P+1FROM T A, T B ORDER BY(SELECT COUNT(*)-COUNT(DISTINCT V)FROM T WHERE T.P>=A.P AND T.P<=B.P),1DESC
```
[DB Fiddle](https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=c7bf9c3e5694a355581f25b939b7d1d2)
[Answer]
# [Ohm v2](https://github.com/nickbclifford/Ohm), 16 bytes
```
l@€³sÇ;{⁇DU⁼;»l↑
```
[Try it online!](https://tio.run/##y8/INfr/P8fhUdOaQ5uLD7dbVz9qbHcJfdS4x/rQ7pxHbRP//09MSk5JTUsHUgA "Ohm v2 – Try It Online")
Took me this long to realise `»` goes *before* the component. Almost submitted a 17 byte answer using `€l;`.
## Explained
```
l@€³sÇ;{⁇DU⁼;»l↑
l@ # Push the range [1, len(input)]
€ ; # To each number:
³sÇ # Get all substrings of length number of the input
{ # Deep flatten that
⁇DU⁼; # And only keep substrings that have all unique characters
»l # Push the length of each unique character substring
↑ # and get the biggest length
```
]
|
[Question]
[
This challenge is inspired by a series of young children's books by Fiona Watt and Rachel Wells, which I've recently been enjoying with my daughter.
In each book a mouse (illustrated, but not part of the text) complains that a succession of 5 things of the same type are not its thing. It then backs this up by declaring that some component of the thing doesn't have the property it expects.
On the sixth time of asking, the mouse finds its thing and is pleased because it has the expected property.
Here is the text of a typical example:
```
That's not my bunny, its tail is too fluffy.
That's not my bunny, its paws are too rough.
That's not my bunny, its tail is too woolly.
That's not my bunny, its eyes are too shiny.
That's not my bunny, its nose is too wrinkled.
That's my bunny! Its ears are so soft.
```
Now, most programming folk would realise that this is a very algorithmic method of producing some text. Because it's such a clear process, we should be able to reproduce this by writing some code.
Let's start with three collections of words:
```
things = ["dinosaur", "lamb", "princess", "reindeer", "train"]
parts = ["back", "bells", "body", "bows", "crown", "dress", "ears",
"engine", "fan", "flippers", "funnel", "hooves", "horns", "neck",
"nose", "roof", "sash", "side", "spines", "spots", "tail", "teeth",
"tiara", "wheels", "windows"]
properties = ["bumpy", "fluffy", "furry", "fuzzy", "glittery", "glossy",
"hairy", "red", "rough", "rusty", "shiny", "silky", "slippery",
"soft", "sparkly", "squashy", "thick", "velvety", "woolly"]
```
* First, we decide which kind of thing we will be describing.
* Then 5 times, we will generate the line "That's not my [thing], its [part] is too [property].
* Finally, we generate the line "That's my [thing]! Its [part] is so [property]!
# The challenge
* Generate the text of a "That's not my..." story.
* It must not consistently reproduce the same text.
* It's code golf, so attempt to do so in the smallest number of bytes.
* Use any language you please.
* White space doesn't matter, but there must be a newline character between lines.
* The lists of source words are not part of your answer (in TIO they can be added to the header).
* You can rename the lists of source words.
* Output can be output to a terminal or text generated into an object.
* Please include a link to an online interpreter.
* Ignore plurals, "its horns is" is fine.
* It doesn't need to make sense. If your princess's funnel is too fluffy, just say so.
Sample output:
```
That's not my train, its engine is too rusty.
That's not my train, its hooves is too thick.
That's not my train, its sash is too fuzzy.
That's not my train, its tail is too velvety.
That's not my train, its horns is too glittery.
That's my train! Its hooves is so hairy.
```
Happy golfing!
[Answer]
# [Python 3](https://docs.python.org/3/), 149 bytes
```
lambda a,*l:shuffle(a)or["That's "+s%(a[0],*map(choice,l))for s in["not my %s, its %s is too %s."]*5+["my %s! Its %s is so %s."]]
from random import*
```
[Try it online!](https://tio.run/##PZLPjptADMbP5SmmSKtCFlWVql5W2gfovTfKwQFPGGUYU9sEsS@fzh@0p@8X2/H4w14PnSn8fNr3v08Py3UCA93Fv8m8WeuxgZa4r//MoN/E1K/y0kD/Y@guC6zNOJMbsfNta4mNGBf6OpCa5TAv0hmnEtU4MUoU6Xs9XH699nVOfzW/P9NyZofKMi2GIUxR3LIS6@Wpsws3Me@mrycXSGDjujN1Gjbpyi6MKJKY0YUJMeeVwYV6qFZgLf@@wnhPmSt6n8uvNB1F9/x7ZNpDgonPhggctTKRws0FTDELucZ6t67IucxuIaBPNBM9UApxyBAwPZt6xOFzByaySQVkzuqmHJc1PiGFSDMouNxXEXUuXdQBQ4rtM2IxskfbyUN0yxSHUoen5W1ZjzJtXGehjfmEj48MN@9UkU8mkaM8NIMrQcapjL3d8ry8ieaExNUUcP5eoHyVxKmFkNXiB/juS8W/LdrOGDdbNvJA/8DScifysXCoqnRTcSHxqoxtyhF0Jm8zyqfN9q36kk5Am1jbPv8D "Python 3 – Try It Online")
-9 bytes thanks to movatica
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 72 bytes
```
≔‽θθF⁵«That's not my θ, its ‽η is too ‽ζ.⸿»That's my θ! Its ‽η is so ‽ζ.
```
[Try it online!](https://tio.run/##bZExj9swDIXn@leoXpoA6W2dOnXsdjjclmZQbDoioogOKcdIivvtPkkUcC6uEz@TD@@Rcucsd2T9svwSwVPYvNjQ02Vz3e7MdfuzGYjN5sfW/G2@PDOGuGlfnY3fxASK5nI3bdLUyfUD253BKOthtXXblcigmEj0H9ljLXv6w1nx1vy7QA3/yK7jr@Z3jf6cvAoW@qx5rDRPabos@33bYyCxE6ebWm8vx1zHpOlAJDMDhh6gzCNbDO1h15h9e7TdOfeO4H0RHqm/a53Ld8c0hww9VyuwnGpjEoUTBsi9wRbN4HEcgYtsmEIAn8kR3UCUOBQIkGOzR1q7ODDRkKtYcaViX/oypghRolggWiy@ESA6dYlo2ebe7AD0kDkdnG@od06X8a4rTsOgNDFXeDwKnDzGCFyZRO7q7ixqk6HXXadTWZIniWUgDoMC@rOCPkXmbCE0RD3C8tmr4jqlWwtGh/obbuBvoJYzkU/Cw2H5fvPv "Charcoal – Try It Online") Link is to verbose version of code. Expects the arrays of things, parts and properties to be in the variables `θ`, `η` and `ζ`, which is most easily arranged by providing them in the input rather than the header. Explanation:
```
≔‽θθ
```
Pick a random thing.
```
F⁵«That's not my θ, its ‽η is too ‽ζ.⸿»
```
Print five negative sentences.
```
That's my θ! Its ‽η is so ‽ζ.
```
Print the positive sentence.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0 [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 73 bytes
```
ö
6Æ`Tt's {`not `pT=Y<5}my {+`!,`gT} {73dT*H}ts {Vö} {`tÑ?`ë2!T} {Wö}.
```
Takes the three lists as `U`, `V`, and `W`. Those are the default input variables anyways, so just put the three lists in the input section.
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LVI&code=9go2xmBUlXQncyB7YG5vdCBgcFQ9WTw1fW15IHsrYCEsYGdUfSB7NzNkVCpIfXRzIHtW9n0giSB7YHTRP2DrMiFUfSB7V/Z9Lg&input=WyJkaW5vc2F1ciIsICJsYW1iIiwgInByaW5jZXNzIiwgInJlaW5kZWVyIiwgInRyYWluIl0KWyJiYWNrIiwgImJlbGxzIiwgImJvZHkiLCAiYm93cyIsICJjcm93biIsICJkcmVzcyIsICJlYXJzIiwKICAiZW5naW5lIiwgImZhbiIsICJmbGlwcGVycyIsICJmdW5uZWwiLCAiaG9vdmVzIiwgImhvcm5zIiwgIm5lY2siLAogICJub3NlIiwgInJvb2YiLCAic2FzaCIsICJzaWRlIiwgInNwaW5lcyIsICJzcG90cyIsICJ0YWlsIiwgInRlZXRoIiwKICAidGlhcmEiLCAid2hlZWxzIiwgIndpbmRvd3MiXQpbImJ1bXB5IiwgImZsdWZmeSIsICJmdXJyeSIsICJmdXp6eSIsICJnbGl0dGVyeSIsICJnbG9zc3kiLAogICJoYWlyeSIsICJyZWQiLCAicm91Z2giLCAicnVzdHkiLCAic2hpbnkiLCAic2lsa3kiLCAic2xpcHBlcnkiLCAKICAic29mdCIsICJzcGFya2x5IiwgInNxdWFzaHkiLCAidGhpY2siLCAidmVsdmV0eSIsICJ3b29sbHkiXQ)
```
ö Saves the random object in variable U
6Æ Range [0..6), and map each to the following string
`That's The string "That's " plus
{`not `pT=Y<5} "not " if the index is less than 5 (and store that in variable T), else ""
my Literal "my " plus
{+`!,`gT} U plus ',' if T, else '!'
{73dT*H}ts "its " if T, else "Its "
{Vö} Random item from V
is
{`tsooo`ë2!T} "too" if T, else "so"
{Wö}. Random item from V, plus a period
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 147 bytes
This main program will not repeat any part or property in a run, and has reasonable randomization.
```
$t=$l|Random
$a=$a|Random -c 6
$r=$r|Random -c 6
0..4|%{"That's not my $t, its $($a[$_]) is too "+$r[$_]}
"That's my $t! Its $($a[5]) is so "+$r[5]
```
[Try it online!](https://tio.run/##VZHBTiMxDIbvfYowygqqBbQH2FsfYK9obyuE3I6niZomg@3pqCw8e0ns4cDJX5w/f/wnY5mROGBKF5/cxt10fcyFYaLu1nUJjttWR4p5h8yNCWPuEXVfCGLu1isPenQLu0Nrb6udarelP1uddb2jMucGPS1uCFTrylXK@5ix9QZQzZDiOCKpbJhyxtQolHJCNqKskLFd2zzq5OpApQytMnDQGnvt81ivYKMiCgJRfQVRgrlIBILWmwOiBZlr5pahRiWLOh3Hs005DYPRRLTA25vCPkURpIUL89kuCBCtSdjbuNNe56SJRTc4xGwQ08HAXqNxs@AyiOUAOiRTvE41rqKEaD9xwnRCs5xLSVW4Xl28bHx6f4Ia6Vi/buNhWbi7nftdE248fev8ur9/eP/xv/sbQK7Z5SLueHZebl0Udv7Gwz//8rx2kZ2U4rqfnlrjY/V1QtVX7s@X@tHEvGgfny@XTw "PowerShell – Try It Online")
Writing `get-random` so many times costs so many characters! However, unless you are willing to let parts and properties be repeated, I can't see a way to shrink this in powershell any further. Unless you move the first 3 line pipes to the end of the 3 assignment lines in the header. To have something like
```
# Header
$l = ("dinosaur", "lamb", "princess", "reindeer", "train")|Get-Random
$a = ("back", "bells", "body", "bows", "crown", "dress", "ears",
"engine", "fan", "flippers", "funnel", "hooves", "horns", "neck",
"nose", "roof", "sash", "side", "spines", "spots", "tail", "teeth",
"tiara", "wheels", "windows")|sort{Get-Random}
$r = ("bumpy", "fluffy", "furry", "fuzzy", "glittery", "glossy",
"hairy", "red", "rough", "rusty", "shiny", "silky", "slippery",
"soft", "sparkly", "squashy", "thick", "velvety", "woolly")|sort{Get-Random}
# Main
(1..5)|%{echo("That's not my $t, its "+$a[$_]+" is too "+$r[$_])}
"That's my $t! Its "+$a[6]+" is so "+$r[6]
```
But that seems like it's cheating, and still doesn't beat Neil's answer.
Edit: Thanks for the tips Matt, and thanks AdmBorkBork for fleshing them out, removing the 3 sets of `get-` text reduced it to 159 bytes, then some more golf from Adm got it down to 147. The code I was thinking of which allowed duplicates and contradictory statements was **144 characters** after applying the same golf tips.
```
function n{(random 18)+1}
$t=$l[(n)%5]
0..4|%{"That's not my $t, its $($a[(n)]) is too "+$r[(n)]}
"That's my $t! Its $($a[$(n)]) is so "+$r[(n)]
```
[Try it online!](https://tio.run/##TZHPbtswDMbvfgrNULEYLYoV6IBd@gC77zb0oMR0RESRPJKOkf559lQi06En/kx9@shPnssKxBFSuvjkntymHzEXDgv1d65P4bhtdSbMO2BuTIB5BNBzoYC5Hzof9Oo27A6tva12qt2W8Wx11e8dlTU3GOnqBoFq7VylvMcMrTcF1UwJ5xlIZdOSM6RGsZQTsBFlhQxtbPOom6sDlTK1yoGjVhy1z3MdwUZFFCSg@gqARHMRDBRab40AFmStmVuGGpUs6nKcz7blMk1GC9EVXl4U9glFgK5cmM82IAa0JsFo6y573ZMWFj3giNkA08HAXqNxs@AyieUIdEim@LfUuIoS0f7ECdIJzHItJVXh0F3qY@4ES3b5dUOhBju6h1/D7cN75@XJp7@bPNz8fO5@3N8/vt289n9ikO/schF3PDsvdw6Fnd/40JTPg0N2Uorrbz1p5737vKP6b@73p97/v8Bf9JfLBw "PowerShell – Try It Online")
However, it not only has a tendency to say the same thing multiple times, but it pretty much requires that your inputs be the same number of elements. I believe the pseudo random number generator being used is heavily dependent on the clock, and quick repeated calls to it can often result in the same result. Then it has the condition that it only uses the whole list if all lists are the same length.With only saving 3~5 characters and having so many caveats, I prefer the code at the start of this post.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 72 bytes
```
XWWẋ6;X€}⁶pʋ€s5“ʠ˵ʋb⁵J¥\¢wBD®-Ƥd(CḤ!²kT“Ø!1ẆÑ⁹ṁṾƤṛḄėÄṂMƓṾṖ¿O*½»Ỵ€¤żⱮ"ẎY
```
[Try it online!](https://tio.run/##LZLPihNBEMbvPkV2TiLrwYNevKknQbwIuxJz6MnUZNr0do/VPRmyIJhl8RIQRFgFPYhEvMiC4spO1j/QWXPIW/S8yNjdlVP95uviq/q65ykIMe26/b09t5zfur3fHn193s5@lpu5J32zffFh8/HyxJ5t5mk7O7tvPz@xn@o79@zp9fUiu3rXnS927PfxI9@3erdzwy1frl63s8Y1M9f8WS9c896dH1@@XR275ujB@o0XXXNi/z68Zn/bC3fxww@xi3@/2m@niVu@etytvnRdP8m4VJpVmOz2EsEO0lBL5HIIWgdG4DIDiOcGGZfJoOv3k5QNx0FKfabYl6psSrWO30NUtQyQ4dYJGPp6pedJjriEoOUs9uSClyVgbMsrKUEEKpSagCZCGUFCGBs8/NbRAZXKQ9VMF7HyLOq69CM0kTIRDOPR1wCYglwMZ8iCVhcAFKT2eUOGwW7Px6wOyiltWOU5UYW4hcPDCCPBjQHcstJ6SuYF4yQiZLRqNYo7YqVNPNAFlwRcjAnoJgIHC61yQxkYjgV1PKt81Iim4PQKExATIMtaKf@XJYPBfw "Jelly – Try It Online")
[Answer]
# JavaScript, 129
```
(a,b,c)=>(z='',a.forEach((f,i)=>z+=`That's ${q=i!=5?"not ":""}my ${f}${q?", i":"! I"}ts ${b[i]} is ${q?"to":"s"}o ${c[i]}.\n`),z)
```
input is three arrays, returns string
[Answer]
# [Ruby](https://www.ruby-lang.org/), 128 bytes
```
->a,*l{t=a.sample;6.times{|i|puts"That's#{' not'if i<5} my #{t}#{i<5?', i':'! I'}ts %s is #{i<5?'to':?s}o %s."%l.map(&:sample)}}
```
[Try it online!](https://tio.run/##TU@xkhMxDO3zFeIyxwITtoMiEK6mp2MotLtyrInXNpacHd/efntQ5iiueU9PtvSeSh3azZ1un3/g4VNY9YS94JwDffvaK88k6wu/5Kry8MujdrJfO4hJO3bA379sMDfYr7rtV1NP3QG4O3bv4Ge3qcCjAAv8f9LUHZ9kS9btHx5DP2P@8P746vVx2254OpNKLzmw7oa3Ynwr3G88DIfxz23imARrgYDzALlwHEkECnGciApoQY67AccLDBSCwJCmZrAIjCUtEaZy/09YDOKZI4HDCC5wzmQ9V2OkAD6lK4lRiQKRbJvZEpSUHAiKB@GJQLLNi1GysxU5gBKpB2UsCIsnsgCLJTP73VDn3MyoOmdUS7nj83ODsx2oVO5FEmngkU0Umsyunj2UKtpAPEdDDhfD17RWJKdmj@USTPytlqyBera8VwpXsrklpRDaPw "Ruby – Try It Online")
[Answer]
# [C#](https://dotnetfiddle.net/), ~~204~~ 203 bytes
```
()=>{int a(int x)=>new Random().Next(x);var j=t[a(5)];string s()=>$"That's not my {j}, its {p[a(25)]} is too {o[a(19)]}.\n";return s()+s()+s()+s()+s()+$"That's my {j}! Its {p[a(25)]} is so {o[a(19)]}.";};
```
It is my first answer on this site, so I hope it works well. It also needs those three things, but according to question those do not count:
```
var t = new[] { "dinosaur", "lamb", "princess", "reindeer", "train" };
var p = new[] {"back", "bells", "body", "bows", "crown", "dress", "ears",
"engine", "fan", "flippers", "funnel", "hooves", "horns", "neck",
"nose", "roof", "sash", "side", "spines", "spots", "tail", "teeth",
"tiara", "wheels", "windows" };
var o = new[] {"bumpy", "fluffy", "furry", "fuzzy", "glittery", "glossy",
"hairy", "red", "rough", "rusty", "shiny", "silky", "slippery",
"soft", "sparkly", "squashy", "thick", "velvety", "woolly"};
```
[Try it online!](https://tio.run/##dVJNb9swDL3nV3DGgNlYF2ADdii89FJgwA7rYRuwQ9uDYtOxGlnySDpOavi3Z/oIurZDDMh8oshHvWdX/KFyhMeBtd3AzwMLduXCqg65VxXCzWJaAFRGMcO1R2EHwKJEV7BzuobvStu8iOl0CLBTBAIrsDje3sMEWa2tYzVQdgGZUd06xJ60rZA5YEJta8R4LuQJM5jLZ2T9P7JsraptqFujMbF57epDimPcV@RGG0BNJ3pU5OOJ79WTod1oi6GsUbGtMbrvkWJnM1iLJqDWuR1yQmQjsBhucobWC46k5FwTIituY9R1zHPvp3JCTiIQpeMoQZT2LLFoRSqUjS1icmD07gXxL01zz00buv6QxA1Nk9BAdAKPjxFsjBZBOmHHfDh7iVbpVEdYJ5XDJsqjgSUecKttAtpsE0i@nidl10gyRNHWpJ4/g/ctQml1@vA7NDtMQ0bnjC98kv11sNUXFv9nba6gWR3zYnU1aSug8vDe@613BH4o71eXF8sb3Eu@L8pg18NKblX@ubgvEwFw6H6b/WqVvGOwTqA7wPQwX4AWhqn31Z98@QyaQZyDyfnMx0ufWd7Rnc1KQhnIBp73r9cTbaJ8A9/@o@QXjFk5l8ck8tpZdgaXv0kL5k1eFEn@vAhrPv4F)
One less byte thanks to Sok.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 63 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ΩU6F€Ω`XN5Qi“€Š's€¯ ÿ!€ç ÿ€ˆ€Ê ÿ.“ë“€Š's€–€¯ ÿ,€ç ÿ€ˆ…« ÿ.“}.ª,
```
[Try it online.](https://tio.run/##VZG/SgNBEMZ7nyJeY3Ok00ewFCwEIRy4l5vLDdnsnrN7ORIQgoWFra2FlRIj@AhCgpXgQ@RFzt2Zs0j1/ebPzs63a53KEbrud311dr6///hd31xfnF7ifvUcou@XExdk@znYfR0H2L0FCPrzEIPHEAxD425z0L1fPf2fSQ/PrF63m/7M3XD7nnbdKCnQWKcaStJBotUsj1oTmjE4F5kATQHAdU8KTZIdjUZJ3szqRcyVuilLoYaoh@WSYaLRe6CerXNMlUJJERQstplUDI3zXHAVGgHUUwGNdd1Pcrb0rLWiqZbUbaNcxegrHE8jzEHPQea11urQmKWDsLiScg5as8HcFgvRluMx2dZEKKh/AlAkaiZogB0qI955KyemjQHN/qydgxMiw2BALg1PDWLZlrx32Fp8FiCWwgVOyHoGr5CnegDPvR4VKXZVAYiFNnxR3D7L/gA)
**68 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) version which doesn't output duplicated parts nor properties:**
```
ΩUε.r6£}øεXª`N5Qi“€Š's€¯ ÿ!€ç ÿ€ˆ€Ê ÿ.“ë“€Š's€–€¯ ÿ,€ç ÿ€ˆ…« ÿ.“}.ª,
```
[Try it online.](https://tio.run/##VZHPSsNAEMbvPkXNxUvamz6G4EEQSsBNM2mGbnfj7qahhULx4MGrVw@CoGgFTwVvQoInoQ@RF4mbmXjo6fvNn52db1dbESO07f7tcr8bmbPqeV1/7XfXV@enF9hsHpvbj5@nE@ul@hzU38ce6lcPXn/vuuDeByPfWG8PupvNw/@Z8PDM5qXa9mfWo@o9bNtxkKDSVhQmCAeBFPO409ygmoC1HRtAlQBQ3RmBKoiOxuMgLub5ssulskhTpsKYHlYrgqlE58D0rK0lygRyykBCootpRlBYRwWboWJAOWOQmOf9JKtTR5oLM5OcuimEzQhdhpNZBwuQC@B5pdbSN0bhwC8uuByDlGQw1smStaR4YnSpOkhM/wQgDKuaogJyKBR7p60sm1YKJPnTegGWySgCBXypf2pgyzqlvf3W7DMBtuQvsEzaETiBNNUBOOp1KIwgVxkAWyj9F3XbR1E7HCo9lGK1/AM)
Both programs assumes the list of things is the first input, and a list containing the list of parts and list of properties is the second input.
### Explanation:
```
Ω # Pop and push a random element of the things-list
U # Pop and store it in variable `X`
6F # Loop 6 times:
€Ω # Get a random element from both the parts and properties list
` # Push them to the stack
X # And also push variable `X`
# (the order on the stack is now: property, part, thing)
N5Qi # If it's the last iteration:
“€Š's€¯ ÿ!€ç ÿ€ˆ€Ê ÿ.“
'# Push dictionary string "that's my ÿ! its ÿ is so ÿ."
ë # Else:
“€Š's€–€¯ ÿ,€ç ÿ€ˆ…« ÿ.“
'# Push dictionary string "that's not my ÿ, its ÿ is too ÿ."
# (where the `ÿ` are automatically replaced with the words on the stack)
}.ª # After the if-else: sentence-capitalize the strings
# (so the "That's " as well as the "! Its")
, # And output it with trailing newline
ΩU # Pop and store a random thing in variable `X`
ε # Map the list of lists of parts/properties to:
.r # Shuffle the list
6£ # And leave the first six elements
}ø # After the map: zip/transpose to create pairs of part & property
ε # Foreach over the pairs:
`XN5Qi“€Š's€¯ ÿ!€ç ÿ€ˆ€Ê ÿ.“ë“€Š's€–€¯ ÿ,€ç ÿ€ˆ…« ÿ.“}.ª,
# And the rest of the code is the same as above
```
[See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `“€Š's€¯ ÿ!€ç ÿ€ˆ€Ê ÿ.“` is `"that's my ÿ! its ÿ is so ÿ."` and `“€Š's€–€¯ ÿ,€ç ÿ€ˆ…« ÿ.“` is `"that's not my ÿ, its ÿ is too ÿ."`.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 117 [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")
```
↑('That''s not my ',(t←T⊃⍨?5),', its ')∘,¨P[5?25],¨' is too '∘,¨V[5?19]
'That''s my ',t,'! Its',P[?25],'is so',V[?19]
```
[Try it online!](https://tio.run/##bZCxjhMxEIb7PIVJ4ztpU4CUgupqKCASUZoohZOdzVpxPItnNqtci3SckEBQIPEI9xw8yr5Izp6JKE5sM996Zn7/v10XZvXZBdxflmZ8@GnGH7/ff/r4wa6ntY9Irk/TykyDO25L7ZKPOyAqnMDHGkD6nJyP042dLF6IbN3uUAa2EIJsbbE@ax3kf5dwiAXqdNUFl7TGvY9QqHEy0QTfdaDNpo8RQqEW8QSklKJABL00@5f9hNiUSo5aqb6Wc@ryBaSELMDOiyoDsMyyd8kVGFoAjTDk3MV9jrt6Gbc/dmf12jeNUp/SFe7vBfbBM0O6MhIJtc7rUYJaTfd7cZB6YmlQ66OCDwcFfRFlbFijuHQIevS5z4kFufX6JicIJ1C9ATHkwRxjfPzaXcaHXzd22Tq2lkxENsezsdUN54TL8duX8fvT3fy2spXxTMbejo9/qr9Pi/X87s18k8kaT4YRjdXOKndev91M/kmKHFf2lXnHZKvFWhZt3iK01Wpdpi/ZycXI101ms9nkP/wM "APL (Dyalog Unicode) – Try It Online")
`?N` generates a random index among the first N indices.
`M?N` generates M random indices (without replacement) among the first N indices.
`,` is concatenation
`t←T⊃⍨`… picks a random thing and calls it `t` for reuse in the last line.
`∘,¨` concatenates the string on the left to each string on the right.
`,¨` concatenates each string on the left to each string on the right.
`↑` changes the list of strings into a character matrix so it prints right.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~88~~ ~~78~~ 76 bytes
```
JONj_ms.ic"That's
my
ts
is
o
."b[?d" not"kJ?d", i""! I"OG?d\s"to"OH)6
```
[Try it online!](https://tio.run/##JY8xbsMwDEV3n0LlUhgoMnYLOibtkCzdUqCQbTpmLUsuKcVwLu@S6cL3SZHU57zmYdv2pwt0FJP4wgDBTw3AzBRbFAFgpNgh6ktmTxHq/eECjW9HgAZD0I4mdavFRXXLaYkAHT9m0bPFeKWIAL3Xlz7QPKOV@xIjBoAhpRuKkaMioq1WNzrBKfUA4mXQSJ1WZNZVYkxZkT3phoyYtSOTZw@wDIhma1Hf5qneH9VwmebVfi99byzMD9zvimugnJEfKokoB0@WMnZmolx1OxfJWpKBooHCaPi/xlTqs9nyPAZLf4u6VpEHsntuGG5o80tKQRvqj/Pp53uSHbXwOfj8LJWbVldVWVzlSENy1Q6ay1sHLqYM44eqF0cAT@4dzgfNcoIvOR/r1237Aw "Pyth – Try It Online")
The code presented above requires the following header:
```
=N["dinosaur""lamb""princess""reindeer""train")=G["back""bells""body""bows""crown""dress""ears""engine""fan""flippers""funnel""hooves""horns""neck""nose""roof""sash""side""spines""spots""tail""teeth""tiara""wheels""windows")=H["bumpy""fluffy""furry""fuzzy""glittery""glossy""hairy""red""rough""rusty""shiny""silky""slippery""soft""sparkly""squashy""thick""velvety""woolly")
```
There's a small issue with using the 'Header' feature in TIO with Pyth, as it looks like TIO joins the code blocks on newlines, and newlines are significant in Pyth. [Here is a link](https://tio.run/##JY8xbsMwDEV3n0LlUhgoMnYLOibtkCzdUqCQbTpmLUsuKcVwLu@S6cL3SZHU57zmYdufLtBRTOILAwQ/NQAzU2xRBICRYoeoL5k9Raj3hws0vh0BGgxBO5rUrRYX1S2nJQJ0/JhFzxbjlSIC9F5f@kDzjFbuS4wYAIaUbihGjoqItlrd6ASn1AOIl0EjdVqRWVeJMWVF9qQbMmLWjkyePcAyIJqtRX2bp3p/VMNlmlf7vfS9sTA/cL8rroFyRn6oJKIcPFnK2JmJctXtXCRrSQaKBgqj4f8aU6nPZsvzGCz9LepaRR7I7rlhuKHNLykFbai3j/Pp53uSHbXwOfj8LJWbVldVWVzlSENy1Q6ay1sHLqYM44eqF0cAT@4dzgfNcoIvOR/r1237Aw) to the same code using the 'Header' block, with a junk line in the output.
```
JONj_ms.ic"That's¶ my ¶¶ts ¶ is ¶o ¶."b[?d" not"kJ?d", i""! I"OG?d"to"\sOH)6 Newlines replaced with ¶
Implicit: k="", b=newline
From header: N=things, G=parts, H=properties
JON Choose a random element from N, store in J
m 6 Map [0-6), as d, using:
?d" not"k If d is truthy (i.e. not 0), yield " not", else ""
J J (the chosen thing)
?d", i""! I" ", i" if d else "! I"
OG Random element from G
?d"to"\s "to" if d else "s"
OH Random element from H
[ ) Wrap the previous 6 results in an array
c"That's¶ my ¶¶ts ¶ is ¶o ¶."b Split the template string on newlines
.i Interleave the template string elements with the previous list
s Concatenate
_ Reverse lines
j Join on newlines, implicit print
```
*Edit: Rewrite to golf 10 bytes, previous version: `J+" my "ONV5%"That's not%s, its %s is too %s."[JOGOH;%"That's%s! Its %s is so %s."[JOGOH`*
[Answer]
# Perl 5.10, 127 bytes
Run with `perl -M5.010 -f filename.pl`.
```
my @t = qw(dinosaur lamb princess reindeer train);
my @r = qw(back bells body bows crown dress ears engine fan flippers funnel
hooves horns neck nose roof sash side spines spots tail teeth tiara
wheels windows);
my @p = qw(bumpy fluffy furry fuzzy glittery glossy hairy red rough rusty shiny
silky slippery soft sparkly squashy thick velvety woolly);
sub r{rand@_}$a=" my $t[r@t]";say"That's not$a, its $r[r@r] is too $p[r@p]."for(1..5);say"That's$a! Its $r[r@r] is so $p[r@p]."
```
[Answer]
**JavaScript ES6, 149 (+15?) bytes**
```
a = ["dinosaur", "lamb", "princess", "reindeer", "train"]
b = ["back", "bells", "body", "bows", "crown", "dress", "ears",
"engine", "fan", "flippers", "funnel", "hooves", "horns", "neck",
"nose", "roof", "sash", "side", "spines", "spots", "tail", "teeth",
"tiara", "wheels", "windows"]
c = ["bumpy", "fluffy", "furry", "fuzzy", "glittery", "glossy",
"hairy", "red", "rough", "rusty", "shiny", "silky", "slippery",
"soft", "sparkly", "squashy", "thick", "velvety", "woolly"]
// r=x=>x[parseInt(Math.random()*x.length)] 164 for better random on fast pc
r=x=>x[new Date%x.length]
s=r(a)
g=j=>console.log(`That's ${j?`not my ${s}, its ${r(b)} is to`:`my ${s}! Its ${r(b)} is s`}o ${r(c)}.`)
a.map(g)
g()
```
[Answer]
## Batch File, ~~434~~ 424 + 7 bytes
**Executed via `cmd/q/c`.**
*Code not counted*
```
set a=dinosaur lamb princess reindeer train
set b=back bells body bows crown dress ears engine fan flippers funnel hoobes horns neck nose roof sash side spines spots tail teeth tiara wheels windows
set c=bumpy fluffy furry fizzy glittery glossy hair red rough rusty shiny silky slippery soft sparkly squashy thick velvety woolly
```
*Code counted*
```
set q=random
set m=set/ar=1+%%%q%%%%%%%
call %m%5
for /f "tokens=%r%" %%x in ("%a%")do set x=%%x
:a
set/ad+=1
call %m%25
for /f "tokens=%r%" %%y in ("%b%")do set y=%%y
call %m%19
for /f "tokens=%r%" %%z in ("%c%")do echo That's not my %x%, its %y% is too %%z.
if %d% neq 5 goto a
call %m%25
for /f "tokens=%r%" %%y in ("%b%")do set y=%%y
call %m%19
for /f "tokens=%r%" %%z in ("%c%")do echo That's my %x%! Its %y% is so %%z.
```
I'll go through some challenges you must face and explain/justify what I did so others can improve.
**Choose a random element from an array**
I did this by generating a random number between `1` and `n` where `n` is the amount of elements in that array. I then used this random number as the token to grab in each `for` loop (`tokens=%r%`). Because I did it this way, I could not nest these `for` loops anymore, as `tokens=!r!` was not working for me (with delayed expansion). This would've saved quite a few bytes as it would've removed the need to save the tokens as variables (`set x=%%x`).
**Random number generation**
`m` is my random number generation macro. Doing it this way saves 32 bytes over doing it like `set/ar=%random%%%n+1` every line. You could semi-cheat and decide that tokens `y` and `z` are to be the same element:
```
call %m%19
for /f "tokens=%r%" %%y in ("%b%")do set y=%%y
for /f "tokens=%r%" %%z in ("%c%")do echo That's not my %x%, its %y% is too %%z.
```
This would, while still retaining some randomness, exclude the final 6 elements of `c`. This would save a minimum of 20 bytes, but I don't think this is true to the op's requirements.
**Theoretical Improvements**
I spent quite a while trying to make this "pseudo-code" work, while still saving bytes:
```
set 1-5=echo That's not my %x%, its %y% is too %%z.
set 6=echo That's my %x%! Its %y% is so %%z.
...
set/ad+=1
for /f "tokens=%r%" %%z in ("%c%")do call %%d%%
```
Unfortunately the setup for this is proving to take up way too many bytes to be profitable (have to implement in < 144 bytes) but I can't shake the feeling that adding the last 4 lines of code are superfluous and janky.
[Answer]
# [ink](https://github.com/inkle/ink), 119 bytes
```
~a=LIST_RANDOM(a)
-(l)That's{l<6: not} my {a}{l<6:, i|! I}ts {LIST_RANDOM(b)} is {l<6:to|s}o {LIST_RANDOM(c)}
{l<6:->l}
```
With the lists defined as
```
LIST a=(dinosaur),(lamb),(princess),(reindeer),(train)
LIST b=(back),(bells),(body),(bows),(crown),(dress),(ears),(engine),(fan),(flippers),(funnel),(hooves),(horns),(neck),(nose),(roof),(sash),(side),(spines),(spots),(tail),(teeth),(tiara),(wheels),(windows)
LIST c=(bumpy),(fluffy),(furry),(fuzzy),(glittery),(glossy),(hairy),(red),(rough),(rusty),(shiny),(silky),(slippery),(soft),(sparkly),(squashy),(thick),(velvety),(woolly)
```
[Try it online!](https://tio.run/##VY/LTsMwEEX3/QqzIpHaLQtEkZDYVOIhQfdokkyaUVw7jO1GfYRfL57JBlbn@s7Dd8j115fN59bAumjI@QCJy2VhYV9lDEyuxhCyZCTXIEoxMpArFzpWrYsK6j67FVorjZVvjopRXjX70WU2PK9BYIXbkcMsWpBqa2kYUCttcg5tFp33Bwwq2Akd6j85owyy921GgNAJqBEzDHlrUOGjMALJrogYpS0SMGSOHaKGHfNREnQ@ps7HpP1w1ESpbVUk5pmnk3BnKUbkWfoQRHRAajA2mizt5DNOIYobOnJKsr1yPlalb6OmBe6tGt8pHyQqdqTnHtAeUPeM3tvcdP2BtaT9@nh6e35/LaBcrApbbjuIt@FsH@7ujfNxMvujOcOkxtLQ5cZsphjM@e9oVU6Gsic90V/C5P/X63JaaHH1aKfr9Rc "ink – Try It Online")
---
Though depending on what counts as a list, there are other approaches. If a list can be a function that randomly returns a list item, the following approach is only 91 bytes:
```
~temp t=u()
-(l)That's{l<6: not} my {t}{l<6:, i|! I}ts {p()} is {l<6:to|s}o {q()}
{l<6:->l}
```
(with the "lists" defined as follows)
```
==function u
~return "{~dinosaur|lamb|princess|reindeer|train}"
==function p
~return "{~back|bells|body|bows|crown|dress|ears|engine|fan|flippers|funnel|hooves|horns|neck|nose|roof|sash|side|spines|spots|tail|teeth|tiara|wheels|windows}"
==function q
~return " {~bumpy|fluffy|furry|fuzzy|glittery|glossy|hairy|red|rough|rusty|shiny|silky|slippery|soft|sparkly|squashy|thick|velvety|woolly}."
```
[Try it online!](https://tio.run/##VY8xcgIxDEV7TuHQBGZCyhSZkD59LmBYLdZg5EWS2VlWy9WJIA00X9L3fPkJaX@9XhQOXdB1XSxnq0Ve/qaorzLmr4/PQEWncBjCqNPdeAtoL@FnUgljt1hOAb25PWgxmUoYj27O7s7qO0/X9bqttFUsFOrswqCVKczHS4NUJFa2HA8b6xhpCyLGgNQAsClHpGk@e8h3j/lN3O5tAzmLbUozuPRiWy49WcO3TRDZhXZIYG0kazN2Hbjn@wiypVJOIF6YxAh8mwOBcSmtSZRkgg2YdJ4XL0XFNGI2BdBkipGj9QnAAXpn9u@faY9PtPXQDY5Q29ZLZb7p@TzYLqMq8K0pIoOliD4wNA5Sd8m4ig4mCckV8971/w5vSqsOFnmffThWZx5ME/olJ8gn8FxfSs7D9D6//gE "ink – Try It Online")
---
There's also the following approach.
```
~temp t="{~dinosaur|lamb|princess|reindeer|train}"
-(l)That's{l<6: not} my {t}{l<6:, i|! I}ts {~back|bells|body|bows|crown|dress|ears|engine|fan|flippers|funnel|hooves|horns|neck|nose|roof|sash|side|spines|spots|tail|teeth|tiara|wheels|windows} is {l<6:to|s}o {~bumpy|fluffy|furry|fuzzy|glittery|glossy|hairy|red|rough|rusty|shiny|silky|slippery|soft|sparkly|squashy|thick|velvety|woolly}
{l<6:->l}
```
[Try it online!](https://tio.run/##JY9BUsMwDEX3nMJ0A8zQLQsG2LPnAk6j1Jo4dpDkZtzIvXpQyuZ/STPSf8I0bttNYJqdfB7WW48psy@k0U@dzoTpBMxKgKkHIBXymNrh4fgcX36Clyde48fbu0tZmpuqW6XdB68O9dF9N2G33jp/GrWDGFm73FeThfVEeUna034ePJmkMybQwScdIs4z2GwoKUHUkPMF2IwSawK7ZpSglPOg7DkoYw/Ks@2zWRZW8RhVACSooCevSwAwgMUesfjm0Mh2UsnKLe@UZZqrRZdhMCtEu16vVc8RRYD2IjNXDR6tIegNoJyDUmGpygGTKcbR9J/fijyIAXkaozW/xVirSkD74ALxAra35BxjbQ93mONXbNv2Bw "ink – Try It Online")
This solution is 389 bytes, but if the shuffle literals (which in this scenario can't really be moved) count as list definitions and can be excluded from the byte count, this drops to 80 bytes.
[Answer]
# [Bash](https://www.gnu.org/software/bash/) +awk, 209 bytes
```
T=$(shuf $1|head -1)
join <(sed "s/.*/$T\t&/" $2) <(sed "s/.*/$T\t&/" $3)|shuf|awk 'NR<6{printf "That'\''s not my %s, its %s is too %s.\n",$1,$2,$3}NR==6{printf "That'\''s my %s! Its %s is so %s.\n",$1,$2,$3}'
```
[Try it online!](https://tio.run/##bVLBbtswDL3zK9jMm5shi5EW2CnpbQN26YAix1zkmI60KKInSjHcZd@e0SnQBWgv5JOE9/iepNqIPW9NwuXy28/v@JCsCzuBxgUWkyN4c6ihiy5sSQQiudAQRUjRuADKALgidyYmgdps91CT9wq5GbT0AtvIfWBo4ihDJmoJOxcIWhOg9a7rSPfaHAJ5sMxHEm0xCARSOXVDEJlbEDUM4hoC6ZQv2liHJuM8JKJkITkTDfSWSB30anic/8ZqZJ2YnArU@dAN6iG3rbYc41ifnwfYeZcSxRGwyADWOF1EatRJ3lmIWdIAojem1fm91pcgCrhN6szEvdfF76ymB9C71ShH8kdSXs/s9fDKWKm4xAdhn5PjMNegH26q2oWqHkOf16viVmxusVicLJkGvyym8ItdwOWtUIMTqeafq2K9SZ@qCRZ30/f376enUeVk@j2Wj0/Lr3/G900tTtbWpHJTloKBEx4G/CgzdEm0oxNMzIrmmzCZFYtZcTcr7v8@Pq1W7wlcyDf445Usb7nl@RJ@DIdXofHlD@LlN@H/hzr/Aw "Bash – Try It Online")
Accepts inputs as `things parts properties` where each is a file with one item per line of the desired type.
This is a file-centered approach. May try an array-centered approach later to see if it can be improved.
[Answer]
# Python 3, 130 bytes
Taking your requirements literally, and taking carriage returns to be one byte each:
```
y=0
def x():
global y
y=1-y
print(("That's not my lamb, it's "+b[0:1][y]+" is too red\n")*5+"That's my lamb! Its fan is so red")
```
]
|
[Question]
[
**This question already has answers here**:
[Distribute a number into a list of values as equal as possible whose sum is equal to that number](/questions/132101/distribute-a-number-into-a-list-of-values-as-equal-as-possible-whose-sum-is-equa)
(23 answers)
Closed 4 years ago.
There is a job which can be decomposed into `x` equally-sized smaller tasks. You have a team of size `y <= x`, where every member works equally fast on any task. The goal for this challenge is to divide the work as evenly as possible such that every member of your team has at least 1 task to perform. As evenly as possible means that given any member `a`, the number of tasks it must perform may be at most one more than any other member `b`. A single task cannot be further divided or worked on simultaneously by two members.
# Input
Your program/function will take as input two positive integers `x` and `y`. `y` is guaranteed to be less than or equal to `x`. You are free to decide in what order your program will take these inputs. You may take the inputs from any input source desired.
# Output
Your program/function will output a list of positive integers of length `y` representing the number of tasks each member must perform. The list may be in any order. For example, the following outputs are identical:
```
2 1 2 1
1 1 2 2
2 2 1 1
```
Outputs may be to any output sink desired.
# Examples
Each line pair denotes inputs and one possible output. These example inputs specify `x` first.
```
1 1
1
4 1
4
4 2
2 2
4 3
2 1 1
4 4
1 1 1 1
10 3
3 4 3
10 7
1 2 2 2 1 1 1
```
# Scoring
This is code golf; shortest code wins. Standard loopholes apply.
[Answer]
# [R](https://www.r-project.org/), 26 bytes
```
function(x,y)table(1:x%%y)
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQqdSsyQxKSdVw9CqQlW1UvN/moahjqEmV5qGCYwyglDGEMoERBkaQLhA2lzzPwA "R – Try It Online")
Counts the number of occurrence of `1,2,...,y` in `[1...x]` modulus y.
12 bytes golfed by @mnel, and than an additional 6 by @digEmAll.
[Answer]
# JavaScript (ES6), 34 bytes
Takes input as `(y)(x)`.
```
y=>g=x=>y?[k=x/y--|0,...g(x-k)]:[]
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/S1i7dtsLWrtI@Otu2Qr9SV7fGQEdPTy9do0I3WzPWKjr2f3J@XnF@TqpeTn66RpqGoSYQaSoo6OsrGHJhSJlApUzQpIwQUkYKRmiSxsiShhjGmiCkDSEQU7@hAVAFUIGxgomCMZq0OULaEGQ7xBIFw/8A "JavaScript (Node.js) – Try It Online")
### Example for x = 10, y = 3
```
Remaining tasks | # of tasks for next worker | Workers
---------------------+----------------------------+-------------------------------------
O O O O O O O O O O | 10 / 3 = 3.333... -> 3 | [ O O O ] [ pending ] [ pending ]
O O O O O O O - - - | 7 / 2 = 3.5 -> 3 | [ O O O ] [ O O O ] [ pending ]
O O O O - - - - - - | 4 / 1 = 4 -> 4 | [ O O O ] [ O O O ] [ O O O O ]
```
[Answer]
# [Haskell](https://www.haskell.org/), 25 bytes
```
x#y=map(`div`y)[x..x+y-1]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/v0K50jY3sUAjISWzLKFSM7pCT69Cu1LXMPZ/bmJmnoKtQko@l4KCQkFRZl6JgoqCobIhMtcEnWuEyjVG5ZqgGGWAKg3km/8HAA "Haskell – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
sZẈ
```
**[Try it online!](https://tio.run/##y0rNyan8/7846uGujv///xsa/DcGAA "Jelly – Try It Online")**
### How?
```
sZẈ - Link: integer tasks, integer workers
- implicit range(tasks)
s - split into chunks of length workers
Z - transpose
Ẉ - length of each
```
[Answer]
# Python 2, ~~40~~ ~~38~~ 36 Bytes
-2 bytes thanks to Mr. Xcoder
```
lambda x,y:x%y*[x/y+1]+[x/y]*(y-x%y)
```
[Try it Online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaFCp9KqQrVSK7pCv1LbMFYbRMdqaVTqAgU1/xcUZeaVKGikaRjqGGpqcsG5JuhcI1SuMSrXBJlraIAqDeSba2r@BwA)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
œsẈ
```
[Try it online!](https://tio.run/##y0rNyan8///o5OKHuzr@//9vaPDfHAA "Jelly – Try It Online")
-1 byte thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan), showing me a built-in I haven't seen before. `œs` splits the range \$[1 \dots\:x]\$ in \$y\$ similarly sized pieces, then `Ẉ` retrieves the length of each chunk.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 48 bytes
Takes `i` task size, `j` team size and returns tasks to array `k`.
```
l;f(i,j,k)int*k;{for(l=j;l--;)k[l]=i/j+(i%j>l);}
```
[Try it online!](https://tio.run/##VY9BcoMwDEX3nEKlw4wNpk2y6cKBi3i8cA0ksh1ggGaT4eyuSNpOs9N/@pK@bHmyNr5ib8NX08JxXhoc3s518oQCfhKLQXYMhROeY7/kXt66YWKhcjKUpeReBV3huysYZq4OXK6RbHAx2LOtMNPJCns2E@Q51VcOtwQAO7Y16sNDEiArVmYZcGtc1V5zAe4fOGzAK6fl3T9ONNGxNGtgMbOfgUIBibEdxtBCBSoVFJo/3L8P/CjKj9VO4tFJLAr@t0xkTVq8oPAKNX@@o9M7WJM1xv0ufnwD "C (gcc) – Try It Online")
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 68 bytes
```
({}([{}])<{({}(()))}{}>){({}[()]<({}<{({}<>)<>}>()){<>({}<>)}{}>)}{}
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/X6O6ViO6ujZW06YaxNTQ1NSsra610wTxojU0Y22ANFjKxk7Txq7WDqig2sYOwgcrBBL//xsaKBgDAA "Brain-Flak – Try It Online")
Initializes the stack with y ones, then rolls the stack x-y times, each time adding 1 to the former top of the stack.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
LôζðK€g
```
[Try it online](https://tio.run/##MzBNTDJM/f/f5/CWc9sOb/B@1LQm/f9/QwMuYwA) or [verify all test cases](https://tio.run/##MzBNTDJM/W/u5ulir6SgZA@mHrVNAjKL//sc3nJu2@EN3o@a1qT/1/lvyGXIZQLGRkBsDMRAngGQASTMAQ).
```
L # Create a list in the range [1, first (implicit) input]
# i.e. 10 → [1,2,3,4,5,6,7,8,9,10]
ô # Split it in chunks of size second (implicit) input
# i.e. [1,2,3,4,5,6,7,8,9,10] and 3 → [[1,2,3],[4,5,6],[7,8,9],[10]]
ζ # Zip, swapping rows and columns (with space as filling character by default)
# i.e. [[1,2,3],[4,5,6],[7,8,9],[10]] → [[1,4,7,10],[2,5,8,' '],[3,6,9,' ']]
ðK # Remove all those spaces
# i.e. [[1,4,7,10],[2,5,8,' '],[3,6,9,' ']]
# → [['1','4','7','10'],['2','5','8'],['3','6','9']]
€g # And then take the length of each inner list as result
# i.e. [['1','4','7','10'],['2','5','8'],['3','6','9']] → [4,3,3]
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 6 bytes
```
:gie!s
```
[Try it online!](https://tio.run/##y00syfn/3yo9M1Wx@P9/QwMuYwA "MATL – Try It Online")
```
(implicit input, y)
: % range, push 1...x
g % convert to logical (all ones)
i % push y
e % reshape to matrix of y rows, padding with 0s
!s % row sums; as a row vector
(implicit output)
```
[Answer]
## Haskell, 41 bytes
```
x#y=[div x y+sum[1|i<=mod x y]|i<-[1..y]]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/v0K50jY6JbNMoUKhUru4NDfasCbTxjY3PwUkEAtk60Yb6ulVxsb@z03MzFOwVUjJ51JQUCgoyswrUVBRMFQ2ROaaoHONULnGqFwTFKMMUKWBfPP/AA "Haskell – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-a`, 31 bytes
```
$a[$_--%$F[1]]++while$_;say"@a"
```
[Try it online!](https://tio.run/##K0gtyjH9/18lMVolXldXVcUt2jA2Vlu7PCMzJ1Ul3ro4sVLJIVHp/38TBaN/@QUlmfl5xf91fU31DAwN/usmAgA "Perl 5 – Try It Online")
[Answer]
# Java, 55 bytes
By making use of `var` in Java 10 we can reduce by 1 byte.
```
y->x->{var a=new int[y];for(;0<x;a[x--%y]++);return a;}
```
[Try it online!](https://tio.run/##fY8xa8MwEIVn@1doKUikFs7UQYmhS6FD6ZDReLg6spEjS0Y6uxYhv11VmnQKdLq79x333g2wQDEcT1GNk3VIhjTzGZXmr85B8CJ/AN1sWlTW8Ld7I/K81eA9@QBlyDnPpvlLq5Z4BExlsepIxoToAZ0yfd0QcL1n183s78bu3aDspXsmj4oyWDdVRTqyJzEU1VpU5wUcgb2R3780NKKzjopytwqo16J4Cs1mw4STODtDQFxilolkdwge5cjtjHxKWVAbevuTo72lox2HadKB3u35AnqWnx29Zq63DWP/8TJxxpLTJb/EuC3jyw8)
Java 8 Version with 56 bytes
```
y->x->{int[]a=new int[y];for(;0<x;a[x--%y]++);return a;}
```
Works by just iterating over the array representing the workers until no tasks are left.
[Answer]
# [Groovy](http://groovy-lang.org/), 35 bytes
```
{x,y->o=[0]*y;while(x--)o[x%y]++;o}
```
[Try it online!](https://tio.run/##Sy/Kzy@r/J9o@7@6QqdS1y7fNtogVqvSujwjMydVo0JXVzM/ukK1MlZb2zq/9n9BUWZeSU6eQqJGYlF6MVClQmKxgmdeSWp6apGOAljMEFlM8/9/Q@P/xgA "Groovy – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 14 bytes
```
⟨{h⟦₁}ġ₎t⟩z₁lᵐ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pf/ahtw6Ompoe7Omsfbp3w/9H8FdUZj@Yve9TUWHtk4aOmvpJH81dWAXk5INn/0QrRhjoKhrE6CtEmCNoIShtDaRMQbWgAFQAxzGMVYgE "Brachylog – Try It Online")
Port of [Jonathan Allan's method](https://codegolf.stackexchange.com/a/170680/8774) - range, split, transpose/zip, length - via the explanation in [Kevin Cruijssen's answer](https://codegolf.stackexchange.com/a/170710/8774). Can also be `tT&h⟦₁;Tġ₎z₁lᵐ` equivalently.
Another neat answer is:
### 19 bytes
```
h~+.ℕ₁ᵐ≜⟨⌉-⌋⟩<2&t~l
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pf/ahtw6Ompoe7Omsfbp3wP6NOW@9Ry9RHTY1A3qPOOY/mr3jU06n7qKf70fyVNkZqJXU5//9HK0Qb6igYxuooRJsgaCMobQylTUC0oQFUAMQwj1WIBQA "Brachylog – Try It Online")
[Answer]
# [UGL 1.0.0](https://repl.it/@_Nobody_/ugl-1-0-0), 20 Bytes
```
CÑORCPFÐWC_+_WNINI
```
Port of the Haskell answer. (even though the language transpiles to Python)
Takes 2 inputs via stdin.
## Explanation (Warning: This may get out of hand)(update: it did not)
C takes two arguments, and apart from some other functions, it is (lambda x,y:map(x,y)).
Ñ is the alias of the int() function. (When you pass it as parameter instead of feeding arguments to it)
O takes one function with two arguments, and two anything, and applies the function to them.
R defines a lambda with two arguments: `lambda _,W: <stuff>`
C, again is map.
P is functools.partial
F is flip (lambda f: lambda x,y: f(y,x))
Ð is the alias of Division (/)
W is the second argument of the lambda we defined with R
C is exclusive range this time
\_ is the first argument of the lambda we defined with R
+\_W is literally \_+W
NINI is two inputs taken from stdin and converted to integers.
So, this thing is (functions redefined in order to make the last line a bit short):
```
import functools as ft
apply2 = lambda x,y,z: x(y,z)
flip = lambda f: lambda x,y: f(y,x)
div = lambda x,y: x/y
rg = range
p = print
ip = input()
p(map(int,apply2(lambda _,W: map(ft.partial(flip(div),W),rg(_,(_+W))),int(ip()),int(ip()))))
```
[Answer]
# [Lua](https://www.lua.org), ~~50~~ 49 bytes
*1 byte saved thanks to DLosc* :)
```
x,y=...repeat print(x//y)x=x-x//y y=y-1until y<=0
```
[Try it online!](https://tio.run/##yylN/P@/QqfSVk9Pryi1IDWxRKGgKDOvRKNCX79Ss8K2QhfEUKi0rdQ1VCjNK8nMUai0sTX4//@/8X8jAA "Lua – Try It Online")
The output is decimal and in different lines because of the way Lua implements the function print(), if this is a problem I can edit the submission to use io.write() instead.
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 39 bytes
Not much room for originality in this one.
```
import StdEnv
$x y=[i/y\\i<-[x..x+y-1]]
```
[Try it online!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3PzO3IL@oRCG4JMU1r4xLpUKh0jY6U78yJibTRje6Qk@vQrtS1zA29n9wSSJQma2CioKhgYL5/3/JaTmJ6cX/dT19/rtU5iXmZiYXAwA "Clean – Try It Online")
Defines the function `$ :: Int Int -> [Int]`, always returning higher numbers towards the end.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes
```
NθNηIEθ⁻÷×⊕ιηθ÷×ιηθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oLmZ8B5AcUZeaVaDgnFpdo@CYWaBTqKPhm5pUWa3jmlbhklmWmpGqEZOamgvjJRam5qXklqSkamZo6ChlAXAjE6OoyYVJAYP3/vzmXocF/3bIcAA "Charcoal – Try It Online") Link is to verbose version of code. Based on Bresenham's line algorithm. Explanation:
```
Nθ Input team size
Nη Input number of tasks
θ Team size
E Map over implicit range
ι ι Current value
⊕ Incremented
η η Number of tasks
× × Multiply
θ θ Team size
÷ ÷ Integer divide
⁻ Subtract
I Cast to string
Implicitly print
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 19 bytes
*4 bytes saved thanks to @Adám*
```
{×⍵:(⍺-1)∇⍵-⎕←⌊⍵÷⍺}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24Tqw9Mf9W610njUu0vXUPNRRzuQp/uobypQ6lFPF5BzeDtQqvb/f2OFNAVDAy51W3UuczATAA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 47 bytes
```
: f tuck /mod swap rot 0 do 2dup i > - . loop ;
```
[Try it online!](https://tio.run/##LcxRCsIwEITh957ip@@JTVoQLPQu0hAVlV1iSo8f0@jLN@wwbJSU7@YWjyjlQiRv65PTWwKf/aokyQwEwYdNebBgsLxElLnu9de3qccmxgPbg1no67s1MXcOh3bTX98cm1PVDe2ocUbLFw "Forth (gforth) – Try It Online")
### Explanation
Divides the work by the number of people, add 1 to all workers whose index is less than (or equal) to the amount of excess work (the remainder/modulus)
### Code Explanation
```
: f \ start a new word definition
tuck \ stick a copy of the number of workers in the "back" of the stack
/mod swap \ get the quotient and remainder, move remainder to the top
rot \ grab the copy of the number of workers from earlier and move it to the top
0 do \ start counted loop from 0 to #workers - 1
2dup \ duplicate the modulus and minimum work
i > \ check if the index is greater than the remainder
- \ subtract from minimum work (forth uses -1 for "true")
. \ output the result
loop \ end the counted loop
; \ end the word definition
```
]
|
[Question]
[
We have a square 10x10 meter garden outside our house. We want to plant grass and make a terrace. We have decided *how* to divide the garden, but we haven't decided the ratio between amount of grass vs terrace.
We need help visualizing it, and ASCII-art is clearly the best way to do so.
---
### Challenge:
Take an integer in the inclusive range **[0, 100]** (or optionally decimal [0, 1]) representing how many percent of the garden should be terrace.
One square meter of terrace will be represented by either a dash `-` or a bar `|`. One square meter of grass will be represented by a hash mark `#`.
* If the amount of terrace is less than or equal to 50%, then the garden should be covered with bars, starting in the bottom left corner, and fill vertically, then horizontally.
* If the amount of terrace is more than 50% then we want the decking to be the other way (dashes instead of bars), and starting in the bottom left corner, and fill horizontally, then vertically.
**Examples:**
```
N = 25%
||########
||########
||########
||########
||########
|||#######
|||#######
|||#######
|||#######
|||#######
N = 75%
##########
##########
-----#####
----------
----------
----------
----------
----------
----------
----------
N = 47%
||||######
||||######
||||######
|||||#####
|||||#####
|||||#####
|||||#####
|||||#####
|||||#####
|||||#####
N = 50%
|||||#####
|||||#####
|||||#####
|||||#####
|||||#####
|||||#####
|||||#####
|||||#####
|||||#####
|||||#####
N = 51%
##########
##########
##########
##########
-#########
----------
----------
----------
----------
----------
N = 0%
##########
##########
##########
##########
##########
##########
##########
##########
##########
##########
N = 100%
----------
----------
----------
----------
----------
----------
----------
----------
----------
----------
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes win. Standard rules regarding I/O. This is ASCII-art, so the output should look like the examples above. I.e. outputting `["|", "|" ...]` is not OK.
Explanations are encouraged as always :)
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 34 bytes
Anonymous prefix function expecting integer in range 0–100. Assumes `⎕IO` (**I**ndex **O**rigin) to be `0`, which is default on many systems.
```
{'#-|'[⊖⍉⍣s⊢10 10⍴100↑⍵⍴1+s←50≥⍵]}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/90Ti1JS84DManVl3Rr16Edd0x71dj7qXVz8qGuRoYGCocGj3i2GBgaP2iY@6t0KYmsXA1WbGjzqXAoUiK39DzXi0AojUwVzUwUTcwVTAwVTQwWQXgMA "APL (Dyalog Unicode) – Try It Online")
`{`…`}` lambda; `⍵` is argument:
`'#-|[`…`]` index the string with the following array:
`50≥⍵` 1 if 50 is greater than or equal to argument, else 0
`s←` store in s (for **s**mall)
`1+` increment
`⍵⍴` cyclically **r**eshape to argument-length
`100↑` take the first hundred of that, padding with zeros
`10 10⍴` **r**eshape to ten rows and ten columns
`⊢` yield that (separates `s` from `10 10`)
`⍉⍣s` transpose if small
`⊖` flip upside-down
[Answer]
# [J](http://jsoftware.com/), 39, 38 37 bytes
```
[:|.>&50|:'#-|'"0{~_10]\100{.]$1+51>]
```
How it works:
```
_10]\100{.]$1+51>] - prepares a 10x10 array of 0, 1 or 2
1+51>] - 1 if N<=50 otherwise 2
]$ - list of N copies of the above (1 or 2)
100{. - the above list filled to 100 items with 0
_10]\ - reshape the list to a 10x10 array
'#-|'"0 - constant array of chars
{~ - replaces each digit 0, 1 or 2 with #, - or |
>&50 - is N>50 ?
|: - if not, transpose the array
(in fact |: here is rearrange axes
0 - transpose
1 - leave it intact)
|.@ - reverse the order ot the rows
```
[Try it online!](https://tio.run/##TY9NCgIxDIX3PUUYfzKDWhKZUCh0juAFtLgQi7hxMcvpnL0WBJtd3vc9HuRd0hwsEHigcvXZTnuh7Ps7U7wx0WLjlg/CUxwW3JwydlQG01nAFCzCEVYPaTbm@Xh9AC8Q4Cw7/MVUbyWcEk6L0TUxOiWE/lxIc26cFae2o@v1jSZqMOUL "J – Try It Online")
[Answer]
# JavaScript (ES6), 84 bytes
Takes input as an integer in **[0...100]**.
```
n=>(y=9,g=x=>~y?'|-#'[[x,y][k=n/51|0]*9+x+y<n?k:2]+[`
`[x-9]]+g(x++-9?x:!y--):'')(0)
```
### Test cases
```
let f =
n=>(y=9,g=x=>~y?'|-#'[[x,y][k=n/51|0]*9+x+y<n?k:2]+[`
`[x-9]]+g(x++-9?x:!y--):'')(0)
;[25, 75, 47, 50, 51, 0, 100]
.forEach(n => O.innerText += n + '%:\n' + f(n) + '\n')
```
```
<pre id=O></pre>
```
### Formatted and commented
```
n => ( // given the terrace percentage n
y = 9, // and starting with y = 9
g = x => // g = recursive function taking x:
~y ? // if y is greater than or equal to 0:
'|-#'[ // pick the relevant character:
[x, y][k = n / 51 | 0] // using k = 1 if n > 50, 0 otherwise
* 9 + x + y // and comparing either 10 * x + y or 10 * y + x
< n ? // with n; if we're located over the terrace area:
k // append either '|' or '-'
: // else:
2 // append '#'
] + // end of character insertion
[`\n`[x - 9]] + // append a linefeed if x == 9
g(x++ - 9 ? x : !y--) // update (x, y) and do a recursive call
: // else:
'' // stop recursion
)(0) // initial call to g with x = 0
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~121~~ ~~117~~ 116 bytes
```
def f(n):
s=[('-|'[n<51]*n+'#'*100)[i*10:][:10]for i in range(10)]
for l in[s,zip(*s)][n<51][::-1]:print''.join(l)
```
[Try it online!](https://tio.run/##Tc7BCgIhEMbxu08hdHC0NnRJFqSeRDwErWUso@heit7dduuwnubH//Ax6TU/Iva13kZPPSA3hJaLBdZ9mMWzVk7gnu2YUFJyG5ZjnDVKOh8zDTQgzVe8j6Akd4SucVqiLYd3SCAKd/8Ra0ynnEk54MzY8RkDwsSrh15z8qvEw9D4NGzWsrHa3OT1u/oF "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 23 bytes
```
<©51ị⁾|-ẋḷ"”#ẋ³¤s⁵Z®¡ṚY
```
[Try it online!](https://tio.run/##ATkAxv9qZWxsef//PMKpNTHhu4vigb58LeG6i@G4tyLigJ0j4bqLwrPCpHPigbVawq7CoeG5mln/NTHDh/8 "Jelly – Try It Online")
Change the number before `Ç` in the footer to change the input. Works as a monadic link in a program without command-line arguments, which [is allowed](https://chat.stackexchange.com/transcript/message/40641580#40641580).
[Answer]
# SWI Prolog, 249 bytes
```
p(X):-write(X).
r(X,Y,G):-G=<50,10*X-Y+1=<G,p('|').
r(_,_,G):-G=<50,p('#').
r(X,Y,G):-(10-Y)*10+X>G,p('#').
r(_,_,_):-p('-').
l(_,11,_):-nl.
l(X,Y,G):-r(Y,X,G),Z is Y+1,l(X,Z,G).
a(10,G):-l(10,1,G).
a(Y,G):-l(Y,1,G),Z is Y+1,a(Z,G).
s(G):-a(1,G),!.
```
The solution is pretty straightforward. Procedure `a` creates rows, `l` writes chars to columns in a row and `r` decides what character should be printed out.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 26 bytes
```
'|-#'100:i>~o10eG50>?!E]P)
```
[Try it online!](https://tio.run/##y00syfn/X71GV1nd0MDAKtOuLt/QINXd1MDOXtE1NkDz/38TcwA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmfFar0X71GV1nd0MDAysGuLt/QINXB1MDOXtE1NkDzv0FyhMt/I1MFc1MFE3MFUwMFU0MFAwWgWgA).
### Explanation
```
'|-#' % Push this string
100: % Push array [1 2 ... 100]
i % Input a number and push it
>~ % Less than or equal (element-wise)? This transforms the
% array into [true ... true false ... false]
o % Convert to double. True becomes 1, false becomes 0
10e % Rehaspe into 10-row matrix, in column-major order
G % Push input
50> % Greater than 50?
? % If so
! % Transpose
E % Multiply by 2 (element-wise). So 0 remains as 0, and
% 1 becomes 2
] % End
P % Flip vertically
) % Index into string, modularly. So 1 corresponds to '|',
% 2 to '-', and 0 to '#'
% Implicitly display
```
[Answer]
# [Python 2](https://docs.python.org/2/), 85 bytes
```
T=j=10
n=input()+T
while j:print([(n-j)/T*'|',min(n-T*j,T)*'-'][n>60]+'#'*T)[:T];j-=1
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8Q2y9bQgCvPNjOvoLREQ1M7hKs8IzMnVSHLqqAoM69EI1ojTzdLUz9ES71GXSc3Mw/IDdHK0gnR1FLXVY@NzrMzM4jVVldW1wrRjLYKibXO0rU1/P/f1AAA "Python 2 – Try It Online")
In both cases each line is padded on the right by `#` to length 10, which lets us share that code between the two cases. The number 10 was used often enough that aliasing `T=10` saved a decent number of bytes.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~92~~ 82 bytes
```
->n{puts (r=0..9).map{|y|r.map{|x|n>(n>50?100-y*10+x:x*10+9-y)?"|-"[n/51]:?#}*''}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vuqC0pFhBo8jWQE/PUlMvN7GguqaypgjCqKjJs9PIszM1sDc0MNCt1DI00K6wqgBRlrqVmvZKNbpK0Xn6poaxVvbKtVrq6rW1/6ONTHXMTXVMzHVMDXRMDXUMdIBaY2HGcSkogO2rADLSoitioXyu2v8A "Ruby – Try It Online")
## How it works:
Every cell in the grid has a progressive number starting from the bottom left corner and proceeding horizontally or vertically depending on the value of n:
If `n>50`, the number is `100-y*10+x` otherwise it's `x*10+9-y`
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes
```
NθGTχ#↶F÷θχ⟦χ⟧﹪θχ¿›θ⁵⁰‖T↖
```
[Try it online!](https://tio.run/##NY3BCsIwEETv/YpQLxuo0Aq9tFdBCipF6kk8xDbRQJpt46bg18dG8PiGNzP9S7gehQmhsZOnsx8f0sHM66RF83miharLWJFnLN2kMdUL0lEqghUUOgaNpb1e9CBhjiLnrHXaEtyK/B4LPzjh4A3@jTrRisHBSUHxLGNlrF2kMrKnzgn7XpdHqK5TfOJ1CLsybBfzBQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ Input integer into q
G Draw filled polygon
T Directions Right, Down, Left
χ Size 10
# Filled with `#`
↶ Rotate cursor left (now points up)
F÷θχ Repeat q/10 times (integer divide)
⟦χ⟧ Print 10 `|`s and move to the next column
﹪θχ Print (q mod 10) `|`s
¿›θ⁵⁰ If q > 50
‖T↖ Reflect diagonally
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 24 bytes
```
↔?T†▼'-≤50⁰S↑C10+R⁰'|∞'#
```
[Try it online!](https://tio.run/##yygtzv7//1HbFPuQRw0LHk3bo677qHOJqcGjxg3Bj9omOhsaaAcB2eo1jzrmqSv////f3BQA "Husk – Try It Online")
## Explanation
```
↔?T†▼'-≤50⁰S↑C10+R⁰'|∞'# Input is a number, say n=12
∞'# Infinite string of #s: "#######...
+ Prepend to it
'| the character |
R⁰ repeated n times: "||||||||||||####...
C10 Cut to pieces of length 10: ["||||||||||","||##########","##..
S↑ Take first 10 pieces.
? ≤50⁰ If n is at most 50,
T then transpose,
†▼'- else take minimum with '-' for each character.
↔ Reverse, implicitly print separated by newlines.
```
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), 21 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
┐* #M*+Mm√H.M»>?H§┐┌ŗ
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyNTEwKiUyMCUyM00qK01tJXUyMjFBSC5NJUJCJTNFJTNGSCVBNyV1MjUxMCV1MjUwQyV1MDE1Nw__,inputs=NTA_)
Explanation:
```
┐* push a vertical bar repeated input times
#M* push "#" repeated 100 times
+ add the two together
Mm mold to a length of 100
√ convert to a square
H rotate clockwise
.M»>? if the input is greater than 50
H rotate the array clockwise again
§ reverse it horizontally
┐┌ŗ replace "|" with "-"
```
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), ~~210~~ 197 bytes
```
[256r^1-255/]sx?dddI/dsT9r-sYI%ddIr-sqdsesm-I/sN[[lNlxx124*PIlN-lxx35*PIPlq1-dsq0<o]dsoxlN1+sNledsq0<oq]sJ50!<J[Ilxx35*PIPlY1-dsY0<E]sElY0<E[lmlxx45*PIlm-lxx35*PIP]sClTI>C[Ilxx45*PIPlT1-dsT0<Z]dsZx
```
[Try it online!](https://tio.run/##RY2xDsIgEIafxcFFQwpYTEyIDk0HOpAOLJXg4nW7pqG38PYIduh0392f73745uylum8fwaRSTaD0AgDTALnHxmgy57IViEAzLcw0ZL1HiykJ2V5Gg5YVvqmCI0bBgCLXawBaE1pxJYvzfoqBBsVPevDmEKYqTFz3gXqs0@NS0ramuByfA3XozLP7u@3uuuo6rt@l7J1yluoH "dc – Try It Online")
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 33 bytes
```
f←{'#-|'[⊖(⍉+⍨)⍣(⍵≤50)⊢⍵>⍎¨∘.,⍨⎕d]}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQb/04Bktbqybo169KOuaRqPeju1H/Wu0HzUuxjI3vqoc4mpgeajrkVAtt2j3r5DKx51zNDTAaoAmpASW/v/f9qhFUamCuamCibmAA "APL (Dyalog Classic) – Try It Online")
based on [Adám's answer](https://codegolf.stackexchange.com/questions/148959/garden-architecture-ascii-style/#answer-148966)
`⎕d` is the string `'0123456789'`
`∘.,` Cartesian product
`⍨` with itself
`⍎¨` evaluate each - get a 10x10 matrix of 0..99
`⍵>` boolean matrix for where the argument `⍵` is greater
`⊢` acts as separator
`(⍉+⍨)⍣(⍵≤50)` if ⍵≤50 double the matrix (`+` with itself) and transpose (`⍉`)
`⊖` vertical reverse
`'#-|'[ ]` index the string `'#-|'` with each element of the matrix
[Answer]
# [q](http://code.kx.com/q/ref/card/), 51 bytes
```
{-1@'reverse$[i;::;flip]10 10#@[100#"#";til x;:;"|-"i:x>50];}
```
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~72~~ 62 bytes
```
.+
$*|
T`|`-`.{51,}
$
100$*#
M!10`.{10}
O$s`(?<!-.*)\S
$.%`
O`
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0WrhiskoSZBN0Gv2tRQp5ZLhcvQwEBFS5nLV9HQAChoaFDL5a9SnKBhb6Ooq6elGRPMpaKnmsDln/D/v5Epl7kpl4k5l6kBl6khlwFIKwA "Retina – Try It Online") Link includes test cases. Edit: Saved 10 bytes with some help from @MartinEnder. Explanation:
```
.+
$*|
```
Repeat `|` the given number of times
```
T`|`-`.{51,}
```
But if the input was at least 51, change them to `-`s.
```
$
100$*#
```
Append 100 `#`s.
```
M!10`.{10}
```
Split into 10 groups of 10, discarding anything left over.
```
O$s`(?<!-.*)\S
$.%`
```
If the the input was at least 51, transpose the result.
```
O`
```
Sort the result.
Alternative solution, also 62 bytes:
```
.+
$*|
T`|`-`.{51,}
$
100$*#
M!10`.{10}
O`
O$^s`\S(?!.*-)
$.%`
```
Sorting before transposing allows a byte saving on the condition for the transposition but costs a byte to get the result in the correct order.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~106~~ 103 bytes
```
n=input();x=n>50;k=x*81+10
while k>0:s='';exec"s+='|-##'[x::2][n<k];k+=x or 10;"*10;print s;k+=x*81-101
```
[Try it online!](https://tio.run/##HU5LCoMwFNy/UzziIn4QXqTBYhovIlKKTatYoqilKfTuaXQzDMP85u/WT7bw3XQ3mjHmrR7s/N7iRDlta0lq1C49i0wQfPrhZXCsqVo158o407E10/yXRxFvXFUVbWMvY6vGTDucFhSkWBpgXga74XrooSsXJHzYgkfwXHGwuNzs08RlUgHiXov7ncCPoC8klBJOJUgCKYBAEP0B "Python 2 – Try It Online")
[Answer]
# PHP, 119+1 bytes
```
$r=str_pad("",100,"#");for($x=50<$n=$argn;$n--;)$r[90+($x?$n%10*2-$n:$n/10-$n%10*10)]="|-"[$x];echo chunk_split($r,10);
```
Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/ef4d015d3addf32570097e74f86277abcfaa87a5).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 24 bytes
```
³<51
ȷ2Ḷ<s⁵ZḤ$Ç¡Ṛị“-|#”Y
```
[Try it online!](https://tio.run/##ATYAyf9qZWxsef//wrM8NTEKyLcy4bi2PHPigbVa4bikJMOHwqHhuZrhu4vigJwtfCPigJ1Z////NTA "Jelly – Try It Online")
## How it works
I use too many superscripts...
```
³<51 ~ Helper link.
³ ~ The input.
< ~ Is smaller than
51 ~ 51?
~ Yields 1 for truthy, 0 for falsy.
ȷ2Ḷ<s⁵ZḤ$Ç¡Ṛị“-|#”Y ~ Main link.
ȷ2 ~ 1e2 (i.e compressed 100).
Ḷ ~ Lowered range. Yields [0, 100) ∩ ℤ.
< ~ Is smaller than the input? (element-wise).
s⁵ ~ Split into sublists of length 10.
Ç¡ ~ Repeat <last link as a monad> times (either 1 or 0 times).
ZḤ$ ~ Zip (transpose) and unhalve element-wise.
Ṛ ~ Reverse.
ị ~ Modular, 1-based indexing into...
“-|#” ~ The literal string "-|#".
Y ~ Join by newlines.
```
[Answer]
# [R](https://www.r-project.org/), 102 bytes
```
n=scan();m=matrix("#",y<-10,y);m[0:n]="if"(n<51,"|","-");write("if"(n>50,m[,y:1],t(m[y:1,])),"",y,,"")
```
[Try it online!](https://tio.run/##JYxBCsMgFETvMt38DxNQipsk9iLiIpQEXOjCCq3Qu1uhm@HxHkwdo/jX8yiiW/b5aDV9BDew74s17NMGs5bokS5I2Z0lviAW6PauqZ3yDw9nmAP7aiOb5DCBUZWYT5yr4@7GDw "R – Try It Online")
Reads `n` from stdin and prints the garden to stdout.
Explanation:
```
n=scan() # read from stdin
m=matrix("#",10,10) # create 10x10 matrix of "#"
m[0:n]="if"(n<51,"|","-") # set the first n entries in m to the appropriate character
m="if"(n>50, # prepare for printing using `write`
m[,10:1], # reverse m left to right
t(m[10:1,])) # flip m top to bottom and transpose
write(m,"",10,,"") # write m to stdout in 10 columns with no separator
```
]
|
[Question]
[
*This challenge is essentially identical to [this one](https://codegolf.stackexchange.com/q/131852/3527) with just one difference: it is now allowed to shuffle letters anywhere in the string.*
## Scenario
John has an important number, and he doesn't want others to see it.
He decided to encrypt the number, using the following steps:
His number is always a non-decreasing sequence (ie. `"1123"`)
He converted each digit into English words. (ie. `"123" -> "ONETWOTHREE"`)
And then, rearrange the letters randomly. (ie. `"ONETWOTHREE" -> "EEWOOHRNTET"`)
John felt that his number were safe in doing so. In fact, such encryption can be easily decrypted :(
---
## Task
Given the encrypted string s, your task is to decrypt it and return the original number.
---
## Rules
* This is code golf, so the shortest answer in bytes wins
* You can assume that the input string is always valid
* The input string only contains uppercase letters
* The original numbers are always arranged in ascending order
* You may return the number in string or integer format
* ~~The letters will only be shuffled between one word, not between the whole string.~~ The letters can be shuffled anywhere in the string.
* The numbers will only be from 1 to 9 inclusive (`ONE` to `NINE`)
---
## Possible Unscrambled String
Here is a list of the strings just after they have been converted to strings from the numbers:
```
1 -> ONE
2 -> TWO
3 -> THREE
4 -> FOUR
5 -> FIVE
6 -> SIX
7 -> SEVEN
8 -> EIGHT
9 -> NINE
```
---
## Examples
`"NEO" -> 1`
`"NWEOOT" -> 12`
`"TOEERWNEHOT" -> 123`
`"IHNEVGENNEISTE" -> 789`
`"WEETVTRFSVUHNEEFRHIXEOINSNIEGTOONIEE" -> 123456789`
`"EWHEWROETOTTON" -> 1223`
`"ONEWESTV" -> 27` (thanks, ETHproductions!)
[Answer]
# [Python 2](https://docs.python.org/2/), 123 bytes
```
c=map(input().count,"OWHUFXSGIQ")
i=4
for j in"71735539994":c[i*2]-=c[int(j)];i=-~i%5
s=""
for n in c:i+=1;s+=`i`*n
print s
```
A full program taking quoted input and printing John's number.
**[Try it online!](https://tio.run/##Hcu7CoMwAEDRPV8RAgUftaBWRCVj1CyG@oYiWAKlERrFx9Clv56GTme5d/nsr1l6SnH8fiyGkMuxG@aFz4fcz4h1eZP2VUZvyAQCX8FzXuEEhUShG/pB4EdRdEUxvwvLGxyslbsxmUMisPMVpwBsGKH/JPUEeSxs7CabjUcxWhIsq@7hphTqCKnbukyrtskLQtIypz1htKgKSrKaMQ1BPw "Python 2 – Try It Online")** or see a [test-suite](https://tio.run/##PVFNb4JAED13f8WGxrAoNhGlFMweR@Gym8IKJo2JFGmLLR8BTOylf90uH@1pZt7MezMvU323H2Vh3O7zMvnEVV2@13HuoKQ8pVRV1VtC87giWVFdWqI9JOWlaHWFR@5usw@23rOioYyu0FtZ4zPOCsVaWEvTXNq2vVKc5CWbGoc5lbFoyVk7rDM6/8kmJmqoovSkQpJw4mQzulg3M3rMjtMCVbWcx81N7kdoOGw8wEF9Qr/i/PUUO23atKjXIV2q4/RapUmbnrROlhCFAVd0vNB0LPMIOBddafS14AB@xMAdwWWPei6DcAuMgRcIkA3rye4bEYAIhb8Jwp0cgY3venvgHguYB1vBuQww6KzMxz8SRC5EPgfBheCsb497OIMIAhFKzLA0aexucD34UMngpMGTRlMn5N8XukuvaUK692gjRT7pFw "Python 2 – Try It Online")
### How?
Let's work with the example "NEONSEXTOWNII" (to yield 1269, and be somewhat [Leisure Suite Larry](https://en.wikipedia.org/wiki/Leisure_Suit_Larry)-esque!)
First `c=map(input().count,"OWHUFXSGIQ")` takes input and counts the number of each of `OWHUFXSGIQ` - these are letters that appear in each number in ascending order, with 2,4,6, and 8 having their "own" letters (`WUXG`), plus an extra letter, `Q` to append a zero to the the end and make the length of the resulting list even. For the example:
```
[2,1,0,0,0,1,1,0,2,0] <- c
O W H U F X S G I Q <- is the counts of these letters
1 2 3 4 5 6 7 8 9 0 <- which "relate to" these digits in John's number
2 4 6 8 0 <- these will be correct as the letters are unique to their words
```
The entries for 1, 3, 5, 7, and 9 need adjusting to correct the abundance of the other letters. This is performed by the next loop:
```
i=4
for j in"71735539994":c[i*2]-=c[int(j)];i=-~i%5
```
Note that the entries to adjust are alternate ones (1,3,5,7,9,1,3,5,...), so we can add two to an index variable at each step and modulo by 10 to stay in range if we need to traverse more than once (which we do). To save some bytes we can increment by one and modulo by 5 and use double the index.
Since the adjustments for 9 require the most work we start there - it resides at index 8 so we start at `i=4`.
The string `"71735539994"` then gives the indexes, `j`, of the values to remove at each stage (where we have ensured the ninth index will contain zero by using `"Q"` when creating `c`); `c[i*2]-=c[int(j)]` performs each individual adjustment and `i=-~i%5` moves `i` to the next index (where `-~i` is `-(-1-i)` or `i+1` saving parentheses `(i+1)%5`) keeping `i*2` within the bounds of `c`.
Thus we first subtract the number at index `j=7` from that at index `i*2=8`, subtracting the number of "G"s counted from the number of "I"s, adjusting the "NINE" count down by the (correct) number of "EIGHT"s (which also has an "I"). We then move onto `i=0` (`-~4%5 = (4+1)%5 = 0`), referencing index `i*2 = 0` which is for "ONE" and subtract the value found at index `j=1` the entry counting "W" and hence "TWO", adjusting the count of "O"s down. By the end of the loop we have the corrected counts:
```
[1,1,0,0,0,1,0,0,1,0] <- c (for 1223333448 it would be: [1,2,4,2,0,0,0,1,0,0])
1 2 3 4 5 6 7 8 9 0
```
so all that remains is to print out what `c` now represents (`1269`). `i` is now back at `0`, so we increment it at the start of the loop and use it as our digit:
```
s=""
for n in c:i+=1;s+=`i`*n
print s
```
The back ticks, ``i``, are Python2 shorthand for `repr(i)` which gets a string representation of an object (the digit character in question as a string) and multiplying a string by a number creats a new string of that many repeats (here we only show `n=0` turning ``i`` from say `"5"` to `""` and `n=1` turning keeping say `"6"` as `"6"`, but it also works for larger positive integers, so `"3"*4` becomes `"3333"` for example.)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 31 bytes
```
[{‘Z€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š‘#NSèJ{Q#
```
[Try it online!](https://tio.run/##AVMArP8wNWFiMWX//1t74oCYWuKCrMK14oCa4oCi4oCew63igKDDrMuGw4jFksWhw6/Cv8W4wq/CpcWg4oCYI05Tw6hKe1Ej//9FV0hFV1JPRVRPVFRPTg "05AB1E – Try It Online")
**Explanation**
```
[ # start loop
{ # sort input
‘Z€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š‘# # push the list ['Z','ONE','TWO','THREE','FOUR','FIVE','SIX','SEVEN','EIGHT','NINE']
N # push the current iteration counter
S # split to list of digits
è # index into the list with each
J{ # join to string and sort
Q# # if the strings are equal, exit loop
# implicitly print iteration counter
```
Very inefficient for large input.
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~112~~ 97 bytes
```
O`.
}`GH
8
X
6
H
3
+`F(.*)O(.*)U
4$1$2
+`O(.*)W
2$1
+`F(.*)V
5$1
+`N(.*)V
7$1
}`NO
1
NN
9
T`L
O`.
```
[Try it online!](https://tio.run/##NY27CsMwDEX3@x0e@oCAkz4/QIkNRYbUcTKqQ4cuHUrXfHtiqxTuPXCEkD7P7@v9WJYgFWbpHC6YcIJDg720m2q3DQUDDsaaOs9UR9TG/hcSjir8k3OWWTjAghlXRLkhX88vmHLiGEpcT6Row9BrfaLSu59KKBEryHcuKtgzla4 "Retina – Try It Online")
*-12 bytes thanks to @Neil*
*-3 bytes by use of L character classes in transposition*
**How it Works**
Basically, this relies on the fact that letters are only used in certain number names. For example `SIX` is the only name which contains an `X`. This gets trickier with the fact that some words overlap in letters, such as both `FIVE` and `SEVEN` using `V`. This could be corrected for by identifying `FIVE` with `F(.*)V`.
[Answer]
# [Kotlin 1.1](https://kotlinlang.org), ~~359~~ ~~352~~ ~~331~~ ~~327~~ 325 bytes
## Submission
```
fun r(r:String):String{var s=""
val f=r.split(s).groupingBy{it}.eachCount()
val c=Array(10,{0})
c[8]=f["G"]?:0
c[6]=f["X"]?:0
c[4]=f["U"]?:0
c[2]=f["W"]?:0
c[1]=(f["O"]?:0)-c[2]-c[4]
c[3]=(f["R"]?:0)-c[4]
c[7]=(f["S"]?:0)-c[6]
c[5]=(f["V"]?:0)-c[7]
c[9]=((f["N"]?:0)-c[1]-c[7])/2
for(i in 1..9)for(x in 1..c[i])s+=i
return s}
```
**Does not work on TryItOnline due to Kotlin 1.1 not being supported**
## Test
```
fun r(r:String):String{
val f=r.split("").groupingBy{it}.eachCount()
val c=Array(10,{0})
c[8]=f["G"]?:0
c[6]=f["X"]?:0
c[4]=f["U"]?:0
c[2]=f["W"]?:0
c[1]=(f["O"]?:0)-c[2]-c[4]
c[3]=(f["R"]?:0)-c[4]
c[7]=(f["S"]?:0)-c[6]
c[5]=(f["V"]?:0)-c[7]
c[9]=((f["N"]?:0)-c[1]-c[7])/2
var s=""
for(i in 1..9)for(x in 1..c[i])s+=i
return s}
data class TestData(val input: String, val output: String)
fun main(vararg args:String) {
val items = listOf(
TestData("NEO" , "1"),
TestData("NWEOOT" , "12"),
TestData("TOEERWNEHOT" , "123"),
TestData("IHNEVGENNEISTE" , "789"),
TestData("WEETVTRFSVUHNEEFRHIXEOINSNIEGTOONIEE" , "123456789"),
TestData("EWHEWROETOTTON" , "1223")
)
for (item in items) {
val out = r(item.input)
if (out != item.output) {
throw AssertionError("Bad result: $item : $out")
}
}
}
```
# Logic
[](https://i.stack.imgur.com/QC8Jb.png)
I used the sheet above to work out the simplest way to solve each letter
* Green = Solve by itself
* Blue = Needs greens to solve
* Orange = Needs blues to solve
* Red = Needs oranges to solve
# Edits
* -7 - Whitespace changes by w0lf
* -21 - Shrank listOf to Array
* -4 - Removed unneeded brackets
* 0 - Added logic in
* -2 - Re-using empty string thanks to kevin-cruijssen
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 37 bytes
```
1ðDị“©ȯ¿w¶&ÇhṆỌƘ#Ȯʋ~¢CNẓ_»ŒuḲ¤ẎŒ!ċð1#
```
[Try it online!](https://tio.run/##AVUAqv9qZWxsef//McOwROG7i@KAnMKpyK/Cv3fCtibDh2jhuYbhu4zGmCPIrsqLfsKiQ07hupNfwrvFknXhuLLCpOG6jsWSIcSLw7AxI////09ORVdFU1RW "Jelly – Try It Online")
-1 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan).
[Answer]
# Java 8, ~~248~~ 234 bytes
```
s->{int x=0,a[]=new int[10];for(String t:"2WO;4UORF;6XSI;8GI;5FI;7S;3R;1O;9I".split(";"))for(;s.indexOf(t.charAt(1))>=0;a[t.charAt(0)-48]++)for(String z:t.split(""))s=s.replaceFirst(z,"");for(s="";x++<9;)for(;a[x]-->0;)s+=x;return s;}
```
**Code Explanation:**
```
s->{
// Array to count how often which number appears
int a[]=new int[10];
// The first character behind the number serves the identification
// the other characters get removed to identify the other numbers later
for(String t:"2WO;4UORF;6XSI;8GI;5FI;7S;3R;1O;9I".split(";"))
// Check if the string contains the id
for(;s.indexOf(t.charAt(1))>=0;a[t.charAt(0)-48]++)
// Remove the relevant charcters
for(String z:t.split(""))
s=s.replaceFirst(z,"");
// Clear the string to write the output
s="";
// write the numbers sequential into the output
for(int x=0;x++<9;)
for(;a[x]-->0;)
s+=x;
return s;
}
```
-14 Thanks to Olivier Grégoire
[Answer]
# Java 8, ~~346~~ ~~345~~ ~~344~~ ~~336~~ 327 bytes
```
s->{int g=c(s+=" ","G"),u=c(s,"U"),w=c(s,"W"),x=c(s,"X"),f=c(s,"F")-u,h=c(s,"H")-g,v=c(s,"V")-f,o=c(s,"O")-u-w,i=c(s,"I")-f-x-g;return d(s=d(s=d(s=d(s=d(s=d(s=d(s=d(s=d("",o,1),w,2),h,3),u,4),f,5),x,6),v,7),g,8),n,9);}int c(String...s){return~-s[0].split(s[1]).length;}String d(String s,int i,int n){for(;i-->0;s+=n);return s;}
```
[Try it here.](https://tio.run/##jVFNb5tAEL37V4w4sepAkn6lFXJua8Ohu5IhEMnygWDApHix2MVOZNG/7g7GybG1tB/vwZvR7Hsv6T51ml2uXta/T1mdag2/0kodJwCVMnlbpFkOYqAAoWkrVUJmX4BmHn3vadMSoGAKJ@08HKkQymlm609TCyy05hbDbuBoPRI8jDAh@DrCJ4LFCGcWczrcjMQnUuJ@JDGRApuRyEHmHLAaaTD8c16d0mtz07UK1rae/ntbFjZ4R9PgZ4Yb/EIj4lcaA7/RWPid4R7vGZb4g2GFP5nXTzyy4OYGRGNgl7YGmgLMJofnN5M7WdMpMxke/u6O67qaHcdx/jh6ebty9a6ujK2Xdyvm1rkqzcbrL1auPzzFoUl1PhU7Fk1re5XjPNx65KZi7@/TXn8C2HXPdZWBNqmha99Ua9hSeJdeyxWkbExuiBS2lI/KD2din6OjSN@0ybdu0xl3RzWmVvbWVW5mW4KTx/9XJVzK6AphJDlfJIL7V6kDX/B4zoXgQRjxKwoSzqM4WszC@JFK@WzhB09cBiIUAZ9HUtJ1TRue@DxZSB7JKJLiigIpeMLDKL5I@0l/@gs)
**General explanation:**
I've looked at the occurrences of each character in the alphabet:
```
E 13357789
F 45
G 8
H 38
I 5689
N 1799
O 124
R 34
S 67
T 238
U 4
V 57
W 2
X 6
```
* I first counted all occurrences of the single-matches characters: `G=8; U=4; W=2; X=6`.
* Then all occurrences of two-matched characters, which also match one of the four above, which I can subtract from their counts: `F=5; H=3`.
* Then I did the same again for `V=7` (by subtracting `F=5`).
* Then the same for all three-matches characters that were left: `O=1; N=9`.
+ But because `N` has two occurrences in `NINE`, I had to do an additional `-1` for every occurrence of `N`, so I've used `I=9` instead (by subtracting three previous matches instead of two).
**Code Explanation:**
```
s->{ // Method with String as parameter and return-type
int g=c(s+=" ","G"), // Amount of 8s (and append a space to `s` first, for the .split)
u=c(s,"U"), // Amount of 4s
w=c(s,"W"), // Amount of 2s
x=c(s,"X"), // Amount of 6s
f=c(s,"F")-u, // Amount of 5s
h=c(s,"H")-g, // Amount of 3s
v=c(s,"V")-f, // Amount of 7s
o=c(s,"O")-u-w, // Amount of 1s
i=c(s,"I")-f-x-g; // Amount of 9s
return d( // Return the result by:
s=d(
s=d(
s=d(
s=d(
s=d(
s=d(
s=d(
s=d("", // Making the input String `s` empty, since we no longer need it
o,1), // Append all 1s to `s`
w,2), // Append all 2s to `s`
h,3), // Append all 3s to `s`
u,4), // Append all 4s to `s`
f,5), // Append all 5s to `s`
x,6), // Append all 6s to `s`
v,7), // Append all 7s to `s`
g,8), // Append all 8s to `s`
i,9); // And then returning `s` + all 9s
} // End of method
int c(String...s){ // Separate method with String-varargs parameter and int return-type
// `s[0]` is the input-String
// `s[1]` is the character to check
return~-s[0].split(s[1]).length;
// Return the amount of times the character occurs in the String
} // End of separated method (1)
String d(String s,int i,int n){
// Separate method with String and two int parameters and String return-type
for(;i-->0; // Loop from the first integer-input down to 0
s+=n // And append the input-String with the second input-integer
); // End of loop
return s; // Return the resulting String
} // End of separated method (2)
```
[Answer]
# [Perl 5](https://www.perl.org/), 100 bytes
99 bytes code + 1 byte for `-n` switch.
```
${$_}++for/./g;@a=($O-$W-$U,$W,$H-$G,$U,$F-$U,$X,$S-$X,$G,$I-$F+$U-$X-$G);print$_ x$a[$_-1]for 1..9
```
[Try it online!](https://tio.run/##HYxLC4JAFIX/iouzKJyruGgRErS5o7NxwDdEDC4shFAxF0H015vGNufxcThzvzwO1uIN8/H927SEQXiPz91pB01oCJVAI5ASErFl@SetQEGbOqgI0kflqtvs43kZxhXGe6G7wFB0dZ9eFARHaxvmsi5zWdRVmjHLPFUta5UVmeKk1NoZf6d5HabxaWn8AQ "Perl 5 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 225 bytes
```
def f(s):
r=[]
for i,w in zip([2,4,6,8,3,5,7,1,9],["WTO","UFOR","XSI","GEIHT","HTREE","FIVE","VSEEN","ONE","NINE"]):
while s.count(w[0]):
r+=[i]
for l in w:s="".join(s.split(l,1))
return "".join(sorted(map(str,r)))
```
[Try it online!](https://tio.run/##PY9da4MwFIav7a8IXkV2KOu6z0Ivj5qbBDQ1BfFirEoznEqSItufd0k3epMnJ2/gPO/07c7jsF2WU9uRjtpkt4rMvm5WUTcaomEmeiA/eqL1AzzCM7zCFp7gBTbw1kAdKyliiA@pKDyOJfNnhiyXnrksED1TVgVUJSL3FDxMnHk0YVk0n3XfErv@GC@Do3N9//ccmbt9rZtwCyZ98Jh3dh/H689RD9Su7dRrR3vYJIl3bt3FDOSWjsa1J/r1PlHrDJgkSZbJ6MER2mvrrkEHpI45hgJcoRBBWgrEQnHMrxPLOVYZco6slEFbIcpKFmlZHXyEaZGzIwrGS84wk0J4hG@oclSFQCmkFP@lFZay8pW9yC8 "Python 3 – Try It Online")
Straightforward: remove the digits which are identified by a specific letter first.
[Answer]
# [Python 3](https://docs.python.org/3/), 125 bytes
```
lambda s:''.join(min(w)*(2*sum(map(s.count,w[:2]))-sum(map(s.count,w)))for w in"O1WU W2 H3G U4 F5U X6 S7X G8 IUFXG9".split())
```
[Try it online!](https://tio.run/##ZZFNi4MwEIbP668YvDQpbqH2u@Bx1FwS0GiEUha327Iu9YNqKfvr3US77GEPIe8zM28mmTTf3WddLfqLR/prXr5/5NDuJ5PZV11UpNTrQafEnbb3kpR5Q9rZqb5XnfM47N0jpa//4pTSS32DBxSVLeYqAeVCuAggWYK/SiBbQ7zJINgCS/ws2NmztrkWHaG0p1Z3bru3U96eW/DgYBGbo7AdmFNHa6mMdkcdRoiaFgP5Iok0LEdgqcmsBohZpvV61Jgi17QZCFkQSk3bgTjjxrQbQaEQJjd/NhOIkeIYPoNjUxZyTAPkHFksjXmzHe0KUaYy8uM00SXoRyHLUDAec4aBFEJvOJ6zXK1/TahCVJFAKaQUfEg/@wiOCmOZmrebqx8ta5ivA4UeMfyNbG@9NLei6shFfxl4HrTdjRTUAcO6mvY/ "Python 3 – Try It Online")
After reading the linked challenge I realized this is a variation on [mdahmoune's Python solution](https://codegolf.stackexchange.com/a/132042/19857), which is itself based on [Draco18s's ES6 solution](https://codegolf.stackexchange.com/a/131992/19857), but hey, at least we golfed off two bytes.
Like that solution, we compute the answer through a linear combination of the number of occurrences of certain letters. We encode the linear combinations briefly by writing them as words where the first two letters are to be added and everything afterwards is to be subtracted. Sometimes a character is needed to pad the first two characters; we use this to hide the digit we want to output (which will never occur in the input, so won't affect our algorithm), which we extract with `min`.
[Answer]
## R, 154
```
u=utf8ToInt(s)-71
m=sum
b=m(u==16)
d=m(u==14)
f=m(u==17)
a=m(u==8)-b-d
g=m(u==12)-f
cat(rep(1:9,c(a,b,m(u==11)-d,d,m(u==15)-g,f,g,m(!u),(m(u==7)-a-g)/2)))
```
[Try it online!](https://tio.run/##LYmxDoIwFEX3/oVMfUlfTImKmnQs0gUSQHQt1HZCDdDvr0Q63XPumcIskoeUbdfWedPdi1LKvC7UU1aqbEolb21VrSOT4IVf7Ln9qPdCZ8CMk1HMfiS9GKkXgp@AmIgHIDZiBkRveAbs0RAXQwpoyaAXOr2@lF8vbKCa9WyLHNAwE@UI6JhlbtWdB0b/bwao0cE@BYAQfg "R – Try It Online")
[Answer]
# Axiom, 351 bytes
```
s:="GXUWRFVIONETHS";e:EqTable(CHAR,INT):=table();v:=[8,6,4,2,3,5,7,9,1];z:=[k for k in 1..46|prime?(k)];F(x,y)==>for i in 1..#x repeat y;F(z,e.(s.i):=z.i);t:=[1787026,2451,16445,5957,16036207,130169,20372239,495349,20677];h(a)==(r:=1;F(a,r:=r*e.(a.i));j:=[];F(v,while r rem z.i=0 repeat(r:=r quo t.i;j:=cons(v.i,j)));j:=sort j;k:=0;F(j,k:=k*10+j.i);k)
```
ungolfed commented results
```
s:="GXUWRFVIONETHS" -- tutte le lettere di ONE..NINE in ordine di importanza
e:EqTable(Character,Integer):=table()
v:=[8,6,4,2,3,5,7,9,1] -- numeri da controllare in quell'ordine di apparizione di v
z:=[k for k in 1..46|prime?(k)] -- 14 numeri primi da associare a s
F(x,y)==>for i in 1..#x repeat y
F(z,e.(s.i):=z.i) -- riempie la tavola associando numeri primi alle lettere "GXUW..."
t:=[1787026,2451,16445,5957,16036207,130169,20372239,495349,20677] -- prodotto di numeri primi 1787026 dovrebbe essere HEIGHT
h(a)==
r:=1 ;F(a,r:=r*e.(a.i)) -- calcola il numero associato alla stringa a
j:=[];F(v,while r rem z.i=0 repeat(r:=r quo t.i;j:=cons(v.i,j)));j:=sort j -- leva il nome dei numeri che man mano trova, aggiunge a j
k:=0 ;F(j,k:=k*10+j.i) -- costruisce il numero decimale k, da j vettore ordinato
k -- ritorna tale numero k
------------------------------------------------------
(8) -> h("IHNEVGENNEISTE")
(8) 789
Type: PositiveInteger
```
]
|
[Question]
[
The naming conventions for games in the Super Mario series is very strange, and don't match up between regions.
```
| Japanese Name | American Name |
|---------------------|------------------------------------|
| Super Mario Bros. | Super Mario Bros. |
| Super Mario Bros. 2 | Super Mario Bros.: The Lost Levels |
| Super Mario USA | Super Mario Bros. 2 |
| Super Mario Bros. 3 | Super Mario Bros. 3 |
| Super Mario Bros. 4 | Super Mario World |
```
What a mess!
---
# Challenge:
Given a string consisting of the Japanese name of a Super Mario game, output the corresponding American name. You may input the Japanese string through any reasonable method, and output the American string (with an optional newline) through any reasonable method.
You must use the exact strings shown above. [Standard loopholes are forbidden!](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)
The shortest code (in bytes) is the winner.
[Answer]
# sed, 52
* 1 byte saved thanks to @MikeScott
Straightforward replacement:
```
s/ 2/: The Lost Levels/
s/USA/Bros. 2/
s/B.*4/World/
```
[Try it online](https://tio.run/##K05N@f@/WF/BSN9KISQjVcEnv7hEwSe1LDWnWJ@rWD802FHfqSi/WA@oAMh10tMy0Q/PL8pJ0f//P7i0ILVIwTexKDNfAayGC0NEwQhFDGgaFjXGWMRMAA).
[Answer]
# Retina, 43
* 1 byte saved thanks to @MikeScott
Direct port of my [sed answer](https://codegolf.stackexchange.com/a/124102/11259):
```
2
: The Lost Levels
USA
Bros. 2
B.*4
World
```
[Try it online](https://tio.run/##K0otycxL/P9fwYjLSiEkI1XBJ7@4RMEntSw1p5grNNiRy6kov1gPKOukp2XCFZ5flJPy/39waUFqkYJvYlFmvgJYngtDBKgDWQxkEqYaYyxiJgA).
[Answer]
# JavaScript (ES6), ~~82~~ 81 bytes
```
s=>s.replace(/ 2|o.*4|USA/,(_,i)=>['Bros. 2',': The Lost Levels','o World'][i&3])
```
[Try it online!](https://tio.run/##dZAxb8IwEIX3/IqnDNiuHEdKmKgSqcwwQdUhiiormDbI5SIfMPHf05RujXvj3fv0Pd3J3ix3oR8u2ZkObjxWI1c1m@AGbzsncxR3Mk/L@@vuJdfyXfeqqhuxDsQGhdBihf2nw4b4go27Oc/TjvBGwR9E2/SLslXjc5MA6e46uICtDT3hwaca0@Q5ZpdoHMUPEIvPOvzlp/K/sjiPIi4s/xOijAPLdG54vCJpE/NlB8moanR0ZvLOePqQrCGyrBYaR8lKqfEb "JavaScript (Node.js) – Try It Online")
### How?
There are three patterns to look for and replace. We search all of them at once and use the position \$i\$ of the match to deduce the substitution string.
```
Pattern | Found in | Position in string | Position MOD 4 | Replaced with
--------+-----------------------+--------------------+----------------+--------------------
/ 2/ | "Super Mario Bros. 2" | 17 | 1 | ": The Lost Levels"
/o.*4/ | "Super Mario Bros. 4" | 10 | 2 | "o World"
/USA/ | "Super Mario USA" | 12 | 0 | "Bros. 2"
```
[Answer]
# PHP, 81 Bytes
```
<?=str_replace([" 2",USA,"Bros. 4"],[": The Lost Levels","Bros. 2",World],$argn);
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJSeZ6sUXFqQWqTgm1iUma/gVJRfrKdgpIAsFhrsqICpxkTJ2t4OaJBtcUlRfFFqQU5icqpGtJKCkZIOUIOOEkxVrE60kpVCSEaqgk9@cYmCT2pZak6xEkweqDo8vygnJVYH7BhN6///AQ "PHP – Try It Online")
[Answer]
# JavaScript (ES6), 84 bytes
```
s=>s[r='replace'](' 2',': The Lost Levels')[r]('USA',(b='Bros. ')+2)[r](b+4,'World')
```
```
f=
s=>s[r='replace'](' 2',': The Lost Levels')[r]('USA',(b='Bros. ')+2)[r](b+4,'World')
console.log(
f('Super Mario Bros.'),
f('Super Mario Bros. 2'),
f('Super Mario USA'),
f('Super Mario Bros. 3'),
f('Super Mario Bros. 4')
)
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~96~~ 92 bytes
```
lambda s:r(r(r(s,' 2',': The Lost Levels'),'USA','Bros. 2'),'Bros. 4','World')
r=str.replace
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHYqkgDBIt11BWM1HXUrRRCMlIVfPKLSxR8UstSc4rVNXXUQ4MdgVJORfnFekBFmjCmCVAwPL8oJ0Vdk6vItrikSK8otSAnMTn1f0FRZl6JQpqGenBpQWqRgm9iUWa@AlgTUCluSZDh2KVBLsCr0xi/tIm65n8A "Python 2 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 48 bytes
```
d" 2"`: T” Lo¡ Levels`"USA"`Bžs. 2``Bžs. 4``WŽld
```
[Try it online!](https://tio.run/##y0osKPn/P0VJwUgpwUoh5NAUBZ/8QwsVfFLLUnOKE5RCgx2VEpwOzSvWUzBKgDJMEhLCD/XlpPz/rxRcWpBapOCbWJSZr@BUlF@sx4UhomCEIgY0EIsaYyxiJkoA "Japt – Try It Online")
## Explanation:
```
d" 2"`: T” Lo¡ Levels`"USA"`Bžs. 2``Bžs. 4``WŽld
U // Implicit U = Input
d // Replace:
" 2" // " 2" with
`...` // ": The Lost Levels" decompressed,
"USA" // "USA" with
'...' // "Bros. 2" decompressed,
'...' // "Bros. 4" decompressed with
'...' // "World" decompressed
```
Japt uses the [shoco library](http://ed-von-schleck.github.io/shoco/) for string compression. Backticks are used to decompress strings.
[Answer]
## R, 86 bytes
```
function(x)sub("Bros. 4","World",sub("USA","Bros. 2",sub(" 2",": The Lost Levels",x)))
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~44~~ 43 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
⁹
HḂ+2⁹Ḳ¤ḣK;⁸ị“¥ḄḞ“ḋṗYP8ḷẇ?Ṅ“¡Ạ ṙṗ%»¤
0ịVĊŀ
```
A full program that prints the result.
**[Try it online!](https://tio.run/nexus/jelly#@/@ocSeXx8MdTdpGQNbDHZsOLXm4Y7G39aPGHQ93dz9qmHNo6cMdLQ93zAMyH@7ofrhzemSAxcMd2x/uard/uLMFpGDhw10LFB7unAmUUz20@9ASLgOgzrAjXUcb/v//rxRcWpBapOCbWJSZr@BUlF@sp2CiBAA)**
### How?
```
⁹ - Link 1: yield right argument: number a, list of characters b
⁹ - link's right argument, b
HḂ+2⁹Ḳ¤ḣK;⁸ị“¥ḄḞ“ḋṗYP8ḷẇ?Ṅ“¡Ạ ṙṗ%»¤ - Link 0: change a name: number a, list of characters b
...Note: at this point a will be 0, 2 or 4 for USA, 2 and 4 respectively
H - halve a (0,1, or 2)
Ḃ - mod 2 (0,1, or 0)
+2 - add 2 (2,3, or 2)
¤ - nilad followed by link(s) as a nilad:
⁹ - link's right argument, b
Ḳ - split at spaces
ḣ - head (first two for USA or 4, first three for 2)
K - join with spaces
¤ - nilad followed by link(s) as a nilad:
⁸ - link's left argument a
“¥ḄḞ“ḋṗYP8ḷẇ?Ṅ“¡Ạ ṙṗ%» - list of dictionary/string compresions:
- [" World",": The Lost Levels"," Bros. 2"]
ị - index into (1-based & modular; respectively [4,2,0])
0ịVĊŀ - Main link: list of characters, J
0ị - index 0 into J - gets the last character '.', '2', 'A', '3', or '4'
V - evaluate as Jelly code - the evaluations are:
- "Super Mario Bros." : . - literal 0.5
- "Super Mario Bros. 2" : 2 - literal 2
- "Super Mario USA" : A - absolute value (default argument is 0) = 0
- "Super Mario Bros. 3" : 3 - literal 3
- "Super Mario Bros. 4" : 4 - literal 4
Ċ - ceiling - changes a 0.5 to 1 and leaves others as they were
ŀ - call link at that index as a dyad (left = the evaluation, right = J)
- this is one based and modular so 1 & 3 go to Link 1, while 0, 2 & 4 go to Link 0.
```
[Answer]
# Mathematica, 80 bytes
```
#~StringReplace~{" 2"->": The Lost Levels","USA"->"Bros. 2","Bros. 4"->"World"}&
```
Anonymous function. Takes a string as input and returns a string as output.
[Answer]
# Python 3: 111 bytes
```
from re import sub as r
print(r(" USA","Bros. 2",r(" 2",": The Lost Levels",r("Bros. 4","World",input()))))
```
Gets user input, runs a series of regex-based substitutions, and prints the result.
[Answer]
# [Go](https://golang.org/), 134 bytes
```
import."strings"
func f(s string)string{r:=Replace;return r(r(r(s," 2",": The Lost Levels",1),"USA","Bros. 2",1),"Bros. 4","World",1)}
```
[Try it online!](https://tio.run/##jY7BDoIwDIbvPEXT05YQEpUTxoOeMTGi8bzgwEXYSDe8EJ4dN4hXtT00/fu1f2szdaJ8ilpCK5SOVNsZcglWrcPp01hHStcWo6rXJVTMwqLwpQyU7c6ya0QptyRdTxqIhbQxwhpjzODykJAb6yCXL9lYjFc8xmux98MDGZsELEhLk3r5Zqi5B3GcZtfwHeMwRODj5G1do1nFsOg7SXAUpAzM28j5T8bbfafCa//c2fxFpYEapzc "Go – Try It Online")
Since Go doesn't support default values for arguments, you have to manually pass `1` every time.
[Answer]
# Batch, ~~237~~ 99 bytes
*Assuming input is in exact format in the question*
```
@set s=%*
@set s=%s: 2=: The Lost Levels%
@set s=%s:USA=Bros. 2%
@set s=%s:Bros. 4=World%
@echo %s%
```
[Answer]
# [Pascal (FPC)](https://www.freepascal.org/), ~~184~~ 182 bytes
```
const s='Super Mario ';b='Bros.';m=s+b;var t:string;z:array[0..4]of string=(m+' 2',m+' 3',m,s+'World',m+': The Lost Levels');begin read(t);write(z[(length(t)+ord(t[19])*2)mod 5])end.
```
[Try it online!](https://tio.run/##TY6xDoIwFEV/5W2lokQRB2lYnHHSxIEwFHhAE2jJa8XIzyPi4nSSc4d7BmlL2e3qoZzn0mjrwCbs9hyQ4CpJGWCiSNiFjA2Y6BPrF2KUBC62jpRuxBRLIvnO9kEQ5aaGn0683mcQsu0XxwVb67OHoa5aVQz3FiE1y1uKI3aWcVFgozQQyspzXLxIOfSmzOtQN65dlG9oWbLDOeebkPemglPOUVfBPP/nrqUQfQA "Pascal (FPC) – Try It Online")
### Explanation:
`z` is the array that holds 5 possible outputs, we just need to find the way to index into it. I noticed 2 parameters that can be used to distinguish input. The first part is length of the input:
```
Super Mario Bros. -> 17
Super Mario Bros. 2 -> 19
Super Mario USA -> 15
Super Mario Bros. 3 -> 19
Super Mario Bros. 4 -> 19
```
Only 3 inputs have the same length mod 5. The second part is that, at position 19 in the inputs, `2`, `3` and `4` have consecutive code points, so they can be easily used to fill out the rest of the indexes while the remaining 2 inputs are shorter.
The `String` type defaults to `ShortString` and by default has capacity for 255 characters, all initialized with zeroes, so it is safe to use `t[19]` on all strings and its codepoint is 0 for shorter strings, not changing anything for indexing, so shorter strings' indexes are 0 and 2. Therefore, we need indexes 1, 3 and 4 from `2`, `3` and `4`.
```
| Codepoint | *2 | +19 | mod 5
2 | 50 | 100 | 119 | 4
3 | 51 | 102 | 121 | 1
4 | 52 | 104 | 123 | 3
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 37 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
l„ 2“:€€‹×Œä“:'„À"bros. 2"©:®Y4:'‚ï:™
```
[Try it online](https://tio.run/##MzBNTDJM/f8/51HDPAWjRw1zrB41rQGhhp2Hpx@ddHgJSEgdKHm4QSmpKL9YT8FI6dBKq0PrIk1AwrMOr7d61LLo///g0oLUIgXfxKLMfAUnsDoTAA) or [verify all test cases.](https://tio.run/##MzBNTDJM/V9TVmmvpMD5qG2SgoKSfeX/nEcN8xSMHjXMsXrUtAaEGnYenn500uElICF1oOThBqWkovxiPQUjpUMrrQ6tizQBCc86vN7qUcui/zr/g0sLUosUfBOLMvMVnEAKuTBEFIxQxEKDHbGoMcYiZgIA)
**Explanation:**
```
l # Convert the input to lowercase
„ 2 : # Replace " 2" with:
“:€€‹×Œä“ # ": the lost levels"
'„À : # Then replace "usa" with:
"bros. 2" # "bros. 2"
© # And store the string "bros. 2" in the register
® # Retrieve "bros. 2" from the register,
Y4: # and replace its "2" with "4"
: # Then replace "bros. 4" with:
'‚ï # "world"
™ # Convert the result to title-case (and output implicitly)
```
[See this for more information why `“:€€‹×Œä“` is `": the lower levels"`; `'„À` is `"usa"`; and `'‚ï` is `"world"`.](https://codegolf.stackexchange.com/a/166851/52210)
]
|
[Question]
[
# Kuznetsov's Sequence
```
(I made the name up, don't bother with Wikipedia or Google)
```
Given any number `n > 0`, let `r` represent the reverse of the number `n`. Iterate until the final result is zero, passing the result of each iteration back into the function using recursion or a methodology of your choice by performing the below operation:
* If `r > n` for that iteration the result is `r % n`.
* If `n > r` for that iteration the result is `n % r`.
* If `n % r = 0` or `r % n = 0`, you terminate iteration.
Take the intermediate result of each execution and store them in an array for the final answer. The initial number `n` is not part of the sequence, nor is `0`; the examples should make everything a little more obvious.
Lets walk through an example where `n=32452345`.
```
54325423 % 32452345 = 21873078 # r > n, uses r % n
87037812 % 21873078 = 21418578 # r > n, uses r % n
87581412 % 21418578 = 1907100 # r > n, uses r % n
1907100 % 17091 = 9999 # n > r, uses n % r
9999 % 9999 = 0 # r % n = n % r = 0, terminated
Result: [21873078, 21418578, 1907100, 9999]
```
Another example `n=12345678`:
```
87654321 % 12345678 = 1234575 # r > n, uses r % n
5754321 % 1234575 = 816021 # r > n, uses r % n
816021 % 120618 = 92313 # n > r, uses n % r
92313 % 31329 = 29655 # n > r, uses n % r
55692 % 29655 = 26037 # r > n, uses r % n
73062 % 26037 = 20988 # r > n, uses r % n
88902 % 20988 = 4950 # r > n, uses r % n
4950 % 594 = 198 # n > r, uses n % r
891 % 198 = 99 # r > n, uses r % n
99 % 99 = 0 # r % n = n % r = 0, terminated
Result: [1234575, 816021, 92313, 29655, 26037, 20988, 4950, 198, 99]
```
A final example `n=11000`:
```
11000 % 11 = 0 # n % r = 0, terminated
Result: []
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") lowest byte-count wins.
[Answer]
## PowerShell v2+, 89 bytes
```
param($n)for(){$r=-join"$n"["$n".length..0];if(!($n=(($r%$n),($n%$r))[$n-gt$r])){exit}$n}
```
Iterative solution. Lengthy because there's no easy way to reverse an array, so we stringify it and index on it backwards to store into `$r`. Then a pseudo-ternary to pull out the appropriate modulo and re-store into `$n` for the next round. However, if the result is zero, that means the `!($n...)` will be `$true`, so we `exit` instead of `$n`. The numbers are left on the pipeline and (implicitly) returned as an array, but without an encapsulating pipeline or saving the results into a variable, the default `Write-Output` sticks a newline between.
[Try it online!](https://tio.run/nexus/powershell#FYu7CoAwDAC/RYmQgC3S1kn8EnFw8FHRKKGDUPz2WpeDg7t0TzKdCEzLJUgRpFf75bkELocf@ph5DZvWzdj5BYuc9oggVV7qLBUI0QCs1gAyEsX58eEFflNK1rjWWNd@ "Powershell – TIO Nexus") (Yes, dead serious.)
PowerShell is now on TIO! You gotta give it a second or two, because PowerShell is a beast to startup, but now you, yes *you*, can verify PowerShell code right in your browser!
[Answer]
# Perl, ~~43~~ 38 + 1 = 39 bytes
Run with the `-n` flag
```
say while$_=($;=reverse)>$_?$;%$_:$_%$
```
[Try it online!](https://tio.run/nexus/perl#@1@cWKlQnpGZk6oSb6uhYm1blFqWWlScqmmnEm@vYq2qEm@lEq@q8v@/oZGxiamZuQWXsZGJKYj9Xzfvv66vqZ6BoQEA "Perl – TIO Nexus") Includes the two non-empty examples.
### Explanation chart
`-n`: Wraps the entire program in `while(<>){ ... ;}`. This turns the above code into the following line: `while(<>){say while$_=($;=reverse)>$_?$;%$_:$_%$;}`. Notice, a semicolon has been added to the trailing `$`, so it now becomes an instance of the variable `$;`. In the condition of a `while` loop, `<>` automatically reads one line of input and saves it in the `$_` variable. So now let's look at what the interpreter reads inside the outer `while` loop:
```
say while$_=($;=reverse)>$_?$;%$_:$_%$;
[op][mod][ condition ] #While is acting as a statement modifier.
#It evaluates the operation as long as the condition is truthy.
($;=reverse)>$_?$;%$_:$_%$; #The meat of the program: a ternary operation
($;=reverse) #The reverse function takes $_ as a parameter by default, and reverses the value.
#The value returned by reverse is stored in the variable $;
>$_ #A condition asking if $% is greater than $_. Condition of the ternary operation
?$;%$_ #If true, then return $; modulo $_
:$_%$; #If false, return $_ modulo $;
$_= #Assign the result of the ternary operation back into $_
#If $_ is non-zero, then the condition is true, and while will evaluate the operation
say #Implicitly takes the $_ variable as parameter, and outputs its contents
```
### Original code, saved for posterity: 43 + 1 = 44 bytes
```
say$_=$%>$_?$%%$_:$_%$%while$_-($%=reverse)
```
[Answer]
# Pyth, ~~13~~ 12 bytes
```
t.u|%F_S,s_`
```
Thanks to @TheBikingViking.
Try it online: [Demonstration](https://pyth.herokuapp.com/?code=t.u%7C%25F_S%2Cs_%60&input=32452345&debug=0)
My old code:
```
W
W=Q%F_S,s_`
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=W%0AW%3DQ%25F_S%2Cs_%60&input=32452345&debug=0)
### Explanation:
```
t.u|%F_S,s_`NNNQ implicit Ns and Q at the end
Q start with N = Q (Q = input number)
, create a pair with the numbers
s_`N convert N to string -> reverse-> convert to int
N and N
S sort
_ reverse
%F fold by modulo
| N or N (if the result is zero use N instead to stop)
.u apply this ^ procedure until a value repeats
print all intermediate values
t except the first one (the original number)
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 11 bytes
```
[‚{R`%Ð>#,
```
Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=W8OC4oCae1JgJcOQPiMs&input=MzI0NTIzNDU)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~15 14~~ 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
,ṚḌṢṚ%/
ÇÇпḊ
```
**[TryItOnline](http://jelly.tryitonline.net/#code=LOG5muG4jOG5ouG5miUvCsOHw4fDkMK_4biK&input=&args=MzI0NTIzNDU)**
### How?
```
,ṚḌṢṚ%/ - Link 1, iterative procedure: n
, - pair n with
Ṛ - reverse n
Ḍ - undecimal (int of digit list)
Ṣ - sort
Ṛ - reverse
%/ - reduce with mod
ÇÇпḊ - Main link: n
п - collect while
Ç - last link as a monad is truthy
Ç - last link as a monad
Ḋ - dequeue (remove the input from the head of the resulting list)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 12 bytes
```
,ṚḌṢṚ%/Ṅß$Ṡ¡
```
This is a monadic link/function that prints to STDOUT.
[Try it online!](https://tio.run/nexus/jelly#@6/zcOeshzt6Hu5cBGSo6j/c2XJ4vsrDnQsOLfx/uP3hzpmPGuY8apgLFD609VHTmv//jY1MTI2MTUx1FAxBlJm5BZBlaGBgAAA "Jelly – TIO Nexus")
### How it works
```
,ṚḌṢṚ%/Ṅß$Ṡ¡ Monadic link. Argument: n
,Ṛ Pair n and its reversed digit list.
Ḍ Convert the digit list into an integer.
ṢṚ Sort and reverse.
%/ Reduce by modulo. Result: m
Ṡ¡ Do sign(m) times:
Ṅß$ Print with a newline and call the link recursively.
```
[Answer]
# Python 2, ~~92~~ ~~87~~ ~~81~~ ~~73~~ 61 bytes
Recursive solution:
```
def f(n):
r=int(`n`[::-1]);x=min(r%n,n%r)
if x:print x;f(x)
```
[**Try it online**](https://repl.it/EmPS/6)
Iterative solution: (also **61 bytes**)
```
n=input()
while n:r=int(`n`[::-1]);n=min(r%n,n%r);print n/n*n
```
[**Try it online**](https://repl.it/EmQ8/3)
[Answer]
# [MATL](http://github.com/lmendo/MATL), 16 bytes
```
`tVPUhSPZ}\tt]xx
```
[Try it online!](http://matl.tryitonline.net/#code=YHRWUFVoU1BafVx0dF14eA&input=MTIzNDU2Nzg)
### Explanation
```
` % Do...while
t % Duplicate. Takes input implicitly in the first iteration
VPU % Transform the number at the top of the stack by reversing its digits
hSPZ} % Concatenate the two numbers into an array, sort, reverse, split the
% array: this moves the smaller number to the top
\ % Modulo
t % Duplicate. The original copy is left on the stack for displaying,
% and the duplicate will be used for computing the next number
t % Duplicate. This copy will be used as loop condition: exit if 0
] % End
xx % Delete the two zeros at the top. Implicitly display rest of the stack
```
[Answer]
# PHP, 78 bytes
```
function a($n){while(($r=strrev($n))&&($n=$r>$n?$r%$n:$n%$r)!=0){echo$n.' ';}}
```
[Answer]
## Batch, 140 bytes
```
@echo off
set/pn=
:l
set/am=n,l=0
:r
set/al=l*10+m%%10,m/=10
if %m% gtr 0 goto r
set/an=l%%n%%l+n%%l%%n
if %n% gtr 0 echo %n%&goto l
```
Takes input on STDIN and outputs the sequence on separate lines. Batch has conditional statements (which are somewhat verbose) but no conditional expressions so it's easier (despite having to quote the `%`s) to compute `r%n%r` (which is equal to `r%n` if `n<r` or zero if `n>r`) and `n%r%n` (which is equal to `n%r` if `n>r` or zero if `n<r`) and add them together.
[Answer]
## Mathematica, 68 bytes
Thanks to [Greg Martin](https://codegolf.stackexchange.com/questions/102748/kuznetsovs-sequence/102774#comment249885_102774) for suggesting I use `FixedPointList` rather than `NestWhileList`:
```
FixedPointList[Mod[(r=IntegerReverse@#)~Max~#,r~Min~#]&,#][[2;;-4]]&
```
The shortest I could get my original solution with `FixedPointList` was 73 bytes:
```
NestWhileList[Mod[(r=IntegerReverse@#)~Max~#,r~Min~#]&,#,#!=0&][[2;;-2]]&
```
[Answer]
# JavaScript, ~~72~~ 70 bytes
```
f=(s,...o)=>(u=s>(z=[...s+''].reverse().join``)?s%z:z%s)?f(u,...o,u):o
console.log(...[32452345, 12345678, 11000].map(x=>f(x)))
```
```
.as-console-wrapper{max-height:100%!important}
```
Edited:
**-2 bytes**: Spread operator waits string concatenation.
[Answer]
# R, ~~126~~ 117 bytes
```
x=scan();while(x){y=sort(c(x,as.double(paste(rev(el(strsplit(c(x,""),""))),collapse=""))));if(x<-y[2]%%y[1])print(x)}
```
Sadly, reversing a number (`as.double(paste(rev(el(strsplit(c(x,""),""))),collapse="")))`) is pretty wordy. Rest is pretty easy. Uses `sort` to indirectly check which is higher.
The rest is straightforward, it keeps looping until `x=0`, and prints all steps.
[Answer]
# C, 87 bytes
```
t;r;f(n){while(t=n){r=0;while(t)r=10*r+t%10,t/=10;n=r>n?r%n:n%r;if(n)printf("%d ",n);}}
```
`t` is temporary for reversing. The inner loop shifts `r` 1 digit to the left and adds the last digit of `t` until it is exhausted. Output is after the first iteration and only if it is non-zero to prevent the first and last item to be displayed.
Ungolfed and usage:
```
t;r;
f(n){
while (t = n){
r = 0;
while (t)
r = 10*r + t%10,
t /= 10;
n = r>n ? r%n : n%r;
if(n)
printf("%d ",n);
}
}
```
[Answer]
# Mathematica, 64 bytes
```
NestWhileList[#2~If[#<=#2,Mod,#0]~#&[IntegerReverse@#,#]&,#,#>0&]&
```
The above code represents a pure function which takes a single input, and returns the kuznetsovs sequence. The really beautiful thing about mathematica is that you can put layer upon layer of pure functions... Allow me to explain the code ;)
Each term in the sequence itself is calculated with the below function, which takes one input and returns the next term.
```
#2~If[#<=#2,Mod,#0]~#&[IntegerReverse@#,#]&
```
The code `IntegerReverse@#` just generates r, the reversed value. The code `#2~If[#<=#2,Mod,#0]~#&` is a function that takes two inputs and either does the mod operation, or reverses the inputs and calls itself again. Another way of writing it is `If[#<=#2, Mod, #0][#2, #]&`, or it could be written as a regular function like this: `k[a_, b_] := If[a <= b, Mod, k][b, a]`
[Answer]
## Racket 180 bytes
```
(let p((n n)(ol'()))(let*((v reverse)(o modulo)
(r(string->number(list->string(v(string->list(number->string n))))))
(m(if(> n r)(o n r)(o r n))))(if(= m 0)(v ol)(p m(cons m ol)))))
```
Ungolfed:
```
(define (f n)
(let loop ((n n)
(ol '()))
(let* ((r (string->number
(list->string
(reverse
(string->list
(number->string n))))))
(m (if (> n r)
(modulo n r)
(modulo r n))))
(if (= m 0)
(reverse ol)
(loop m (cons m ol))))))
```
Testing:
```
(f 32452345)
(f 12345678)
```
Ouput:
```
'(21873078 21418578 1907100 9999)
'(1234575 816021 92313 29655 26037 20988 4950 198 99)
```
]
|
[Question]
[
Generate the *n*th [Narayana-Zidek-Capell](https://oeis.org/A002083) number given an input *n*. Fewest bytes win.
f(1)=1, f(n) is the sum of the previous floor(n/2) Narayana-Zidek-Capell terms.
Test Cases:
```
f(1)=1
f(9)=42
f(14)=1308
f(15)=2605
f(23)=664299
```
[Answer]
# Jelly, ~~11~~ 10 bytes
```
HĊrµṖ߀Sȯ1
```
[Try it online!](http://jelly.tryitonline.net/#code=SMSKcsK14bmWw5_igqxTyK8x&input=&args=OQ)
Takes `n` as argument and prints the result.
### Explanation
```
H divide input by 2
Ċ round up to get first n to recurse
r inclusive range from that to n
µ (chain separator)
·πñ remove n itself from the range
߀ call self recursively on each value in the range
S sum results
ȯ1 if sum was zero, return one
```
[Answer]
# Ruby, ~~34~~ 32 bytes
This uses a formula from the OEIS page for the [Narayana-Zidek-Cappell numbers](https://oeis.org/A002083).
**Edit:** Got rid of parentheses using operator precedence with thanks to feersum and Neil.
```
f=->x{x<4?1:2*f[x-1]-x%2*f[x/2]}
```
[Answer]
# Python 2, ~~48~~ ~~42~~ ~~38~~ 36 bytes
Algorithm taken from the OEIS page. `n<3` may be changed to `n<4` with no effect. Returns the `n`th number, where `n` is a positive integer.
```
a=lambda n:n<3or 2*a(n-1)-n%2*a(n/2)
```
[**Try it online**](https://repl.it/Caic/1)
[Answer]
## 05AB1E, 16 bytes
An iterative solution as 05AB1E doesn't have functions.
```
X¸sGDN>;ï£Os‚˜}¬
X¸ # initialize a list with 1
sG } # input-1 number of times do
D # duplicate current list
N>;ï£ # take n/2 elements from the list
O # sum those elements
s‚ÄöÀú # add at the start of the list
¬ # get the first element and implicitly print
```
[Try it online](http://05ab1e.tryitonline.net/#code=WMK4c0dETj47w6_Co09z4oCay5x9wqw&input=MjM)
[Answer]
# C, 38
A translation of the OEIS algorithm. There's just not enough C code around here!
```
f(n){return n<3?:2*f(n-1)-n%2*f(n/2);}
```
[Answer]
# Python 3, 67 bytes
```
def f(n):
x=1,
for i in range(n):x+=sum(x[-i//2:]),
print(x[-1])
```
A function that takes input via argument and prints to STDOUT. This is a direct implementation of the definition.
**How it works**
```
def f(n): Function with input target term index n
x=1, Initialise term list x as tuple (1)
for i in range(n):... For all term indices in [0,n-1]...
x[-i//2:] ..yield the previous floor(i/2) terms...
x+=sum(...) ...and append their sum to x
print(x[-1]) Print the last term in x, which is the nth term
```
[Try it on Ideone](https://ideone.com/0eYDHI)
[Answer]
# Pyth, 12 bytes
```
L|syM>/b2Ub1
```
[Try it online.](http://pyth.herokuapp.com/?code=L%7CsyM%3E%2Fb2Ub1%0Ay&input=9&debug=0) [Test suite.](http://pyth.herokuapp.com/?code=L%7CsyM%3E%2Fb2Ub1%0Ay&test_suite=1&test_suite_input=1%0A9%0A14%0A15%0A23&debug=0)
Defines a function `y(n)` that returns the `n`th Narayana-Zidek-Capell-number.
[Answer]
# Mathematica, 38 bytes
```
If[#<4,1,2#0[#-1]-#~Mod~2#0[(#-1)/2]]&
```
Anonymous function. Takes ùëõ as input and returns ùëì(ùëõ) as output. Based off of the Ruby solution.
[Answer]
## Haskell, 34 bytes
```
f 1=1
f n=sum$f<$>[n-div n 2..n-1]
```
Usage example: `f 14` -> `1308`.
A direct implementation of the definition.
[Answer]
# Java, 63 Bytes
```
int z(int n){return n<3?1:n%2>0?(2*z(n-1)-z(n/2)):(2*z(n-1));}
```
[Answer]
# Go, 63 bytes
```
func f(i int) int{if(i<4){return 1};return 2*f(i-1)-i%2*f(i/2)}
```
Pretty much a direct port from the C answer
[Answer]
# PHP, 81 bytes
This is a full program without recursion. A recursive function can be defined in 52 bytes (it might be possible to beat that) but that's just a pretty boring port of sherlock9's answer (and it errors if you ask for f(100) or more) so I'm putting up this longer and more interesting version
```
<?php for($i=$argv[1];$j=$i;$i--)for(;--$j*2>=$i;)$a[$j]+=$a[$i]?:1;echo$a[1]?:1;
```
Causes many (O[n]) notices but that's fine.
[Answer]
# R, 55 bytes
```
x[1]=1;for(i in 2:10){x[i]=sum(x[i-1:floor(i/2)])};x[9]
```
Change `10` in the `for` loop and `x[9]` to get whichever index the user wants.
[Answer]
# JavaScript, ~~54~~ 52
```
f=n=>Math.round(n<3?1:2*f(n-1)-n%2*f(parseInt(n/2)))
```
Based on the [C](//codegolf.stackexchange.com/a/85190/13486) answer.
* Saved 2 bytes by using `parseInt` instead of `Math.floor`
[Answer]
## Maple, ~~46~~ 44 bytes
```
`if`(n<4,1,2*f(n-1)-(n mod 2)*f(floor(n/2)))
```
Usage:
```
> f:=n->`if`(n<4,1,2*f(n-1)-(n mod 2)*f(floor(n/2)));
> seq( f(i), i = 1..10 );
1, 1, 1, 2, 3, 6, 11, 22, 42, 84
```
[Answer]
# R, 63 bytes
```
f=function(n,a=0)if(n<2)1 else{for(i in n-1:(n%/%2))a=a+f(i);a}
```
`a=0` is added as a default because it saves me two curly brackets. Function recursively calls itself as needed.
]
|
[Question]
[
**Proto space invaders**
This is a graphical output challenge where the task is to give the shortest code per language.
**Task**
Your code should allow the user to move the following alien around the screen/window.
[](https://i.stack.imgur.com/CUweU.png)
Your code can simply load it from a local file. Feel free to convert it to another standard image format or even to fix the small pixel errors in the image that were pointed out in the comments.
The background should be white and the window/screen must be at least 400 pixels by 400 pixels. If your language doesn't support windows/screens that large then use the largest size it does support as long as that is not less than 200 by 200.
To move the alien around the screen the code should support up/down/left/right using the arrows keys on a standard keyboard.
Your code should be a **full program**.
**Restrictions/constraints**
The alien should stop at the borders. It should also move at a uniform rate **smoothly** with no visible flickering or stuttering and be shown at at least 24fps. It should take between 2 and 5 seconds to go from one side of the screen/window to the other.
**Languages and libraries**
You can use any language or library you like (that wasn't designed for this challenge). However, I would like to be able to test your code if possible so if you can provide clear instructions for how to run it in Ubuntu that would be very much appreciated.
### Catalog
The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
## Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
## Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
## Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the snippet:
```
## [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
```
<style>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; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 62426; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 9206; 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,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>
```
[Answer]
# [Scratch](https://scratch.mit.edu/about/), ~~221~~ 217 bytes
[](https://scratch.mit.edu/projects/86078640/#editor)
Click the image to view it in action. The movement is determined by *keystrokes*, so it will be smoother the faster your key repeat is set.
The image is included within the project, but Scratch bytes are usually counted from the golfed [textual representation](http://scratchblocks.github.io/#when%5Bup%20arrow%20v%5Dkey%20pressed%0Achange%20y%20by(9%0Awhen%5Bleft%20arrow%20v%5Dkey%20pressed%0Achange%20x%20by(-9%0Awhen%5Bany%20v%5Dkey%20pressed%0Aif%20on%20edge%20bounce%0Awhen%5Bdown%20arrow%20v%5Dkey%20pressed%0Achange%20y%20by(-9%0Awhen%5Bright%20arrow%20v%5Dkey%20pressed%0Achange%20x%20by(9), per [this meta post](http://meta.codegolf.stackexchange.com/questions/673/golfing-from-scratch/5013#5013). If there is disagreement as to whether this is acceptable (or whether the movement is smooth enough) let me know and I will try to work around it.
[Answer]
## Python 2, ~~262~~ ~~253~~ ~~246~~ 240 bytes
```
from pygame import*
init()
key.set_repeat(1)
p=[0,0]
d=display
c=d.set_mode((400,)*2)
while c.fill((255,)*3):
e=event.get(2);c.blit(image.load("I"),p);d.flip()
if e:x=e[0].key+1;q=x&2;b=q/2;p[b]=max(0,min(336+b*16,p[b]+(1-q)*(1-(2*x&2))))
```
Wow. What a lot of hackery.
Uses the module 'pygame' found at <http://pygame.org>.
### Explanation
`key.set_repeat(1)` - Send repeat key events through the event system every millisecond
`c=d.set_mode((400,)*2)` - Create the 400x400 display surface
`while c.fill((255,)*3):` - Effectively `while 1:` but clears the screen as well
`e=event.get(2);c.blit(image.load("I"),p);d.flip()` - Only collect keyboard events, load the image stored in a png file called `I` and draw it. Update the screen
`if e:x=e[0].key+1;q=x&2;b=q/2;p[b]=max(0,min(336+b*16,p[b]+(1-q)*(1-(2*x&2))))` - If there was an event, work out which arrow key was pressed (does weird stuff if you press other keys), and then change the position of the surface depending on which key you pressed.
[Answer]
## Processing 2, ~~219 199 241 220~~ 219 bytes
```
int a,x=0,y=0;void setup(){size(500,500);}void draw(){background(-1);image(loadImage(".png"),x,y);if(keyPressed){a=keyCode;if(a==38)y--;if(a==37)x--;if(a==40)y++;if(a==39)x++;}x=constrain(x,0,436);y=constrain(y,0,454);}
```
Requires the image saved as `.png` in the same directory as the .pde
[Answer]
## Haskell, 410 bytes
```
import Graphics.Gloss
import Graphics.Gloss.Interface.Pure.Game
main=do b<-loadBMP"b";play(InWindow""(400,400)(0,0))white 200((0,0),id)(b#)e(%)
e(EventKey(SpecialKey k)Down _ _)(c,_)|k==KeyUp=(c,fmap(+1))|k==KeyDown=(c,fmap(+(-1)))|k==KeyLeft=(c,((+(-1))?))|k==KeyRight=(c,((+1)?))
e(EventKey _ Up _ _)(c,_)=(c,id)
e _ w=w
_%(c,f)=(s?(s<$>f c),f)
s=min 200.max(-200)
b#((x,y),_)=Translate x y b
f?(a,b)=(f a,b)
```
The picture of the alien is expected in a file named `b` in `.bmp` format.
I'm new to the Gloss library, so maybe this is not optimal. Does anyone know if I can check if a key is pressed instead of tracking `KeyUp`/`KeyDown` events?
How it works: the last four parameters of `play` are the world state (initialized with `((0,0),id)`, a function to draw a picture from a state (`#`), an event handler (`e`) and a function that changes the state over time (`%`).
The state is a pair of x-y-coordinates and a function how to change them whenever `%` is called.
`#` moves the bitmap (`b`) to the current coordinates and draw it.
`e` looks for either `KeyDown` events of the cursor keys and sets appropriate functions in the state or for `KeyUp` of any key to reset the function in the state to the identity function.
`%` applies the function from the state to the current coordinates and checks the boundaries.
[Answer]
# Elm, 240 bytes
```
import Graphics.Element as G
import Keyboard as K
import Time
import Signal exposing(..)
c=min 800>>max 64
i(x,y)=G.container x y G.middle(G.image 64 48"https://i.stack.imgur.com/CUweU.png")
main=i<~foldp(\{x,y}(v,w)->(c v+x,c w-y))(99,99)(sampleOn(Time.fps 200)K.arrows)
```
[Try it here](http://elm-lang.org/try). Byte count is after replacing the URL with `.png`.
[Answer]
## [AutoIt](http://autoitscript.com/forum), ~~269~~ 267 bytes
```
#include<Misc.au3>
GUICreate(0,-1,-1,-1,-1,-1,34078728)
$0=GUICtrlCreatePic("b.bmp",0,0,64,48)
GUISetState()
Dim $1,$2
$3=_IsPressed
Do
$1+=$3("27")-$3("25")
$2+=$3("28")-$3("26")
$1=($1>336)?336:($1<0)?0:$1
$2=($2>352)?352:($2<0)?0:$2
GUICtrlSetPos($0,$1,$2)
Until 0
```
Requires the picture to be saved as b.bmp in the script directory. If you want to use a picture with actual transparency, you have to to convert it from PNG to a 32bit Bitmap (OT: a really unappreciated format).
### Explanation
We need to import `Misc.au3` to get access to [`_IsPressed`](https://www.autoitscript.com/autoit3/docs/libfunctions/_IsPressed.htm). A function that accepts a key code and returns `True` or `False` when the key is pressed.
The spec of the challenge is quite cool in the way that we have to create a 400px square window. The default (denoted as `-1` or `Default`) size parameters are 400x400. The [extended windows style](https://msdn.microsoft.com/en-us/library/windows/desktop/ff700543(v=vs.85).aspx) is set to `34078728`. This forces the window to be double-buffered and drawn from bottom to top. This is necessary to eliminate flickering as per the challenge requirement. In Windows 10, this unusual (and somewhat undocumented) combination of styles breaks the window title bar (all hovering effects are disabled).
`$1` and `$2` are declared and will hold the x and y offset of the picture loaded by the control `$0`. `$3` becomes a pointer to the function `_IsPressed` to shorten the code significantly.
Since it is not required to be able to exit the program, this script runs in an infinite loop (`Until 0`).
`$1+=$3("27")-$3("25")` abuses the variant datatype in AutoIt by dynamically casting the boolean value returned from `_IsPressed` to an integer that can be added or sub'ed from the x offset. Same for y. `$1=($1>336)?336:($1<0)?0:$1` uses the ternary operator known from C-like languages to perform a bounds check to stop the alien at the borders.
[`GuiCtrlSetPos`](https://www.autoitscript.com/autoit3/docs/functions/GUICtrlSetPos.htm) moves the picture control to the new coordinates.
Here's a screenshot with a transparent alien (you can even move diagonally):
[](https://i.stack.imgur.com/wRoWW.png)
[Answer]
# Lua + LÖVE, 291 characters
```
x=0
y=0
l=love
g=l.graphics
l.window.setMode(400,400)
i=g.newImage("i")
function l.update()d=l.keyboard.isDown
if d("left")and x>0 then x=x-1 end
if d("right")and x<336 then x=x+1 end
if d("up")and y>0 then y=y-1 end
if d("down")and y<352 then y=y+1 end
end
function l.draw()g.draw(i,x,y)end
```
This uses an unresizable 400 x 400 window. I had no success with adjusting `love.keyboard.setKeyRepeat()` to speed up the key reading, so I did the recommended way, polling each key's status.
As my relation with Lua `for` is not the best, neither this time managed to make looping shorter than the dump hardcoding of each key's condition.
[Answer]
# SpecBAS - ~~285~~ 255 bytes
```
1 GRAPHIC NEW v LOAD "inv8.bmp" TRANSPARENT 15
2 PALETTE COPY v,0,1 TO 5: GRAPHIC REMAP v
3 LET x,y=100
4 CLS : WINDOW PUT GRAPHIC v,0,x,y
5 LET x=x+KEYST(39)-KEYST(37),y=y+KEYST(40)-KEYST(38)
6 LET x=CLAMP(x,1 TO 400),y=CLAMP(y,1 TO 400)
7 WAIT SCREEN
8 GO TO 4
```
Loads the image - colour 15 is bright white, so that becomes transparent.
Using the original image and default SpecBAS palette made it come out a bit odd, so line 2 switches them around to match the input image. Below image shows how it looks without line 2 and after.
[](https://i.stack.imgur.com/P5SIP.png)
The CLAMP command limits the graphic between 1 and 400 in both directions, saves on several IF...THEN statements.
Line 9 just waits for things to catch up and prevents flickering.
It moves one pixel at a time based on a boolean check of which key is pressed, so takes slightly longer than 5 seconds to go from side to side.
[Answer]
# Ruby with Shoes, ~~252~~ 243 characters
```
Shoes.app{background white
i=image'i'
m=[0,0]
a=[:width,:height]
animate(99){i.left+=m[0]<=>i.left
i.top+=m[1]<=>i.top}
keypress{|k|d,v={?u=>[1,-1],?d=>[1,1],?l=>[0,-1],?r=>[0,1]}[k[0]];m[d]=[[m[d]+v*4,self.send(p=a[d])-i.send(p)].min,0].max}}
```
This uses a resizable window starting at default 600 x 500. If you resize the window so the invader is left out, will come back when the next movement key is pressed.
The trick to satisfy the requirements is that invader's position is changed in increments of 4, but the actual movement is made with increment of 1 at 99 frames per second.
[Answer]
# [Tcl/Tk](http://tcl.tk/), 242 bytes
```
grid [canvas .c -w 400 -he 403 -bg #FFF -highlightt 0]
.c cr i 30 24 -i [image c photo -fi .png] -t p
lmap {k b x y} "Up 1]>25 0 -5 Right 0]<368 5 0 Down 1]<376 0 5 Left 0]>30 -5 0" {bind . <$k> "if \[lindex \[.c coo p] $b {.c move p $x $y}"}
```
[Answer]
# JavaScript (using paper.js), 215 bytes
```
v=new Raster("https://i.stack.imgur.com/CUweU.png",99,99);p=new Size(4,0)
onFrame=e=>{if(!v.isInside(view.bounds)){p=-p};v.position+=p}
onKeyDown=e=>{p=new Size([[0,-4],[0,4],[-4,0],[4,0]]["udlr".indexOf(e.key[0])])}
```
[paper.js](http://paperjs.org) is a JS graphics framework, which means it features many useful features regarding image manipulation. To run, just copy the above into the section on the left [here](http://sketch.paperjs.org), then, to move the alien around, click once in the right section to give it focus. If your browser can handle it, it should run at 60fps.
]
|
[Question]
[
Different systems have different ways to describe colors, even if all of them are speaking in R-G-B-A space. A front-end developer who is familiar with CSS may prefer `#RRGGBBAA`. But Android developers may prefer `#AARRGGBB`. When handling AAS file format, `#AABBGGRR` is needed. That's too confusing. Maybe we need a program which can convert between different color formats.
**Input:**
The input contains 3 parts:
* The color to be transformed (e.g. `#1459AC0F`), a string starting with sharp sign `#` followed by 8 hex digits.
* The format of the given color (e.g. `#RRGGBBAA`), a string starting with `#` followed by 8 letters which fall into 4 different groups and each group is one of `RR`/`GG`/`BB`/`AA`.
* The format to convert to.
**Output:**
* Output the color in converted format
**Test Cases:**
```
Color, OriginalFormat, TargetFormat -> Result
#12345678, #RRGGBBAA, #AARRGGBB -> #78123456
#1A2B3C4D, #RRGGBBAA, #AABBGGRR -> #4D3C2B1A
#DEADBEEF, #AARRGGBB, #GGBBAARR -> #BEEFDEAD
```
Input / output are case insensitive. You may input / output in any acceptable way.
**Rules:**
This is code golf, shortest (in byte) codes of each language win
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 6 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Full program. Prompts on STDIN for Original, then Target, then Color. Prints Result to STDOUT.
```
⍞[⍞⍋⍞]
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97f@j3nnRQPyotxtIxoLE/iuAQRqXclCQu7uTk6Mjl7KjI4TNpWxoZGxiamZuwYVVlZOTu3tQEFCVo5GTsbOJC0IVRA1IDmGWi6uji5OrqxsA "APL (Dyalog Unicode) – Try It Online")
`⍞` prompt for Original
`⍞⍋` prompt for Target and find the indices into Original that would make Original into Target
`⍞[`…`]` prompt for Color and use the above obtained indices to reorder Color
[Answer]
# JavaScript (ES6), ~~53~~ 52 bytes
*Saved 1 byte thanks to @tsh*
Takes input as 3 distinct parameters: `(Color, From, To)`.
```
(C,F,T)=>T.replace(/\w/g,(x,i)=>C[F.search(x)-~i%2])
```
[Try it online!](https://tio.run/##bc1PC4IwGMfxe69CkHCD6fBP6cVgc7r78FYdxKYZ4kSjPPXWLZOIsOP34cfnuWS3rM@7qr2ajTrJsQhHEKEEpTDcpVYn2zrLJcCHOy4RGFD1Okf7xOpl1uVnMEDzUa2dIxxz1fSqllatSlAAQ7cd19ts/cBAmqELwTmlhLyDkDkNCDWMNd0P5u1qQRCHupHH/hGUci7Eh/CYGznUJguCxYTROE5@H08xa19iWk3r8Qk "JavaScript (Node.js) – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ç▼☺↔kàÅJ
```
[Run and debug it](https://staxlang.xyz/#p=871f011d6b858f4a&i=%22%2312345678%22+%22%23RRGGBBAA%22+%22%23AARRGGBB%22%0A%22%231A2B3C4D%22+%22%23RRGGBBAA%22+%22%23AABBGGRR%22%0A%22%23DEADBEEF%22+%22%23AARRGGBB%22+%22%23GGBBAARR%22&a=1&m=2)
This program takes input in this format.
```
"{Color}" "{OriginalFormat}" "{TargetFormat}"
```
Here's the commented ungolfed unpacked version of the same program.
```
u drop duplicated characters from target format
{ for each character remaining in target format, map using block...
[ duplicate original format at second position in stack
|I get all indices of target character in original format
xs@ retrieve characters from those indices from the color string
m perform map
output implicitly when complete
```
[Run this one](https://staxlang.xyz/#c=u++++%09drop+duplicated+characters+from+target+format%0A%7B++++%09for+each+character+remaining+in+target+format,+map+using+block...%0A++[++%09duplicate+original+format+at+second+position+in+stack%0A++%7CI+%09get+all+indices+of+target+character+in+original+format%0A++xs%40%09retrieve+characters+from+those+indices+from+the+color+string%0Am++++%09perform+map%0A+++++%09output+implicitly+when+complete&i=%22%2312345678%22+%22%23RRGGBBAA%22+%22%23AARRGGBB%22%0A%22%231A2B3C4D%22+%22%23RRGGBBAA%22+%22%23AABBGGRR%22%0A%22%23DEADBEEF%22+%22%23AARRGGBB%22+%22%23GGBBAARR%22&a=1&m=2)
[Answer]
# [Python 2](https://docs.python.org/2/), 59 bytes
```
lambda c,o,t:'#'+''.join(c[o.find(v):][:2]for v in t[1::2])
```
[Try it online!](https://tio.run/##bY1BC4IwAEbv/YqBhymJ4LSUQYfN2e67mgdTRovaRIbQr1@tXQw6Pnjv@@aXvRmNnDxd3GN4XqcBjKlJLYYR3EOY3Y3S8diZTCo9xWuC@w6jXpoFrEBpYLscfzhx86K0BTKGUY6K8nCsapgCGAnBOaWEfIGQgDABUVUHb7cJCaJFU7J/IaWcC@HDkhUNojnZhKwljLbt@ffEQ9gIoTe86d4 "Python 2 – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 33 bytes
```
(.)(?<=(..).{7}\1\1.*)\1
$2
.*#
#
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0NPU8PexlZDT09Tr9q8NsYwxlBPSzPGkEvFiEtPS5lL@f9/ZUMjYxNTM3ML5aAgd3cnJ0dHZUdHCJNL2dDRyMnY2cQFWc7Jyd09KIhL2cXV0cXJ1dUNrlwZoiQoCAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
(.)(?<=(..).{7}\1\1.*)\1
$2
```
For each pair of identical characters, look back for another copy of that pair, and then the 9th and 8th characters before that, and replace the pair with those characters. This is only possible for the pairs of characters in the target format, and replaces them with the desired result.
```
.*#
#
```
Delete the colour and source format.
[Answer]
# [Haskell](https://www.haskell.org/), ~~108 104 100 94~~ 87 bytes
```
(s,(r@(x,y):z))!c|x==c=(s++[y],z)|(p,q)<-(s,z)!c=(p,r:q)
c%i=fst.(foldl(!)("",zip i c))
```
[Try it online!](https://tio.run/##bc3baoNAEAbge59iHBvYJbYQtU0IXehutF6kNGAvSyHBA0qtGteASt7drghS2s7dHP5v0pP8jPN8GIg0Sf1EWrOj255SPby2jIWMyOXyvfswe3ollXmmj7fqsFdrptp6e6ZauMhYIps7kpR5lBOdEkSzzyrIIKR0aOEo0/KSRyI@QgcMqkvz1tQvBdxAlkALjKlxk8YF4GGPEOcyBnwtGzjsddS0r1NWqFRUaqCKoLGybOf@Yb3BBRpB4PtCcI4U0OB8avHnRzTWmymBM8AtYe8c9x9ACN8Pgl@A49o7S6z4DLged4XnPY/A/HQEJusPMN6OGRy@AQ "Haskell – Try It Online")
---
### Old version
Thanks to Laikoni for shortening 6 bytes by finding a shorter way to use `lookup`!
```
f(Just x)=x
p('#':z)=p z
p(x:y:z)=[x,y]:p z
p e=[]
c!i=('#':).(f.(`lookup`zip(p i)(p c))=<<).p
```
[Try it online!](https://tio.run/##bY1Ba4NAFITv/oqXZyG7UISobYJkD7vRCk1pwB5DwJCsKLG6VIXVP281gpS27/Bghplv0nN1k3ne9wl5baoaNGXaUGRpLr2OMgXdILTXjuKoH9uTd7dAsuPJuCwydk9SiyQWifOyvDUq7jJFFGR0eBdK2XZLLdVriKu0bPKrkDG0wEA19Uf99VbAA2QJaGBssOtUFoCHPYLMKwn4XtZw2C/QMD7PWTG0rqUBwxE0V7bjPj2vN7hAM4rCUAjOkQKanE8Sfy6iud5MDZwB3BbOzvX/AQgRhlH0C@D6zs4WKz4D/ID7IgheRsA8OgIm1h/AmB072H8D "Haskell – Try It Online")
### Explanation:
* the `p` function "parses" a string by ignoring the leading `#` and returning groups (lists) of 2 chars.
* the `(!)` operator takes as input the color and the input format and returns a function that takes as a parameter the output format and returns the converted color. It turned out that the pointfree version was shorter, but I started with the more readable version:
`f c i o='#':concat[x#zip(p<$>[i,c])|x<-p o]`
[Try it online!](https://tio.run/##bY1Pa4NAFMTvforn20J2IQT80yaIe9iN1kNKA/YYAgnJFqVWpRqySr671QhS2r7DgxlmfpMcqw@VZV2nCaXNvGXeld005w1vb5Zvc02uRklnZOa1jJfQ9kJ7zSB2et7svbsFiu/2xslM@T3JFpSSNi1pCSnr34kx7vtsUXYaDlVSXLKzVAdogEN5qd/qr5ccHiB9Bw2c93adqBxwu0FQWaUAX4sathsTDePzmOZ961wY0B9FYtmO@/i0XKGJJI6jSEohkAESIUaJPxeRLFdjAyeAsKWzdoN/AFJGURz/AriBs7alJSZAEIpAhuHzAJhGB8DI@gMYskMHu28 "Haskell – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, ~~33~~ ~~32~~ 27 bytes
Give input in the order: target, original, number
```
#!/usr/bin/perl -p
s%.%$2x/(..)+$&(.){10}/g%eg
```
[Try it online!](https://tio.run/##K0gtyjH9/79YVU9VxahCX0NPT1NbRU1DT7Pa0KBWP101Nf3/f2VHx6Agd3cnJwVlCO3oqKBsaGRsYmpmbvEvv6AkMz@v@L9uAQA "Perl 5 – Try It Online")
For each character in the input find the same character an even number of places forward then from there go 10 more characters forward and take that character as replacement. If you can't do these steps replace by nothing.
```
+--even-+----10---+
| | |
#AARRGGBB #RRGGBBAA #12345678
| >-will get removed-<
v
2
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
2FI2ô™J}I‡
```
[Try it online!](https://tio.run/##MzBNTDJM/f/fyM3T6PCWRy2LvGo9HzUs/P/f0TEoyN3dyYkLQjk6chkaGZuYmplbAAA "05AB1E – Try It Online")
---
```
2F } # Loop twice...
I # First 2 inputs.
2ô™ # Title case in pairs of 2.
J # Rejoin together.
I # Last input (The color).
‡ # Transliterate, put color in pattern from a into pattern from b.
```
This works because I change the input from:
```
AARRGGBB
```
To:
```
AaRrGgBb
```
So each value is mapped uniquely, then I can use transliterate.
The arguments are reversed.
[Answer]
# Java 10, ~~179~~ ~~105~~ 102 bytes
```
(a,b,c)->{var r="#";for(int i=1,t;i<9;)r+=a.substring(t=b.indexOf(c.substring(i,i+=2)),t+2);return r;}
```
Whopping -77 bytes thanks to *@OlivierGrégoire*.
**Explanation:**
[Try it online.](https://tio.run/##hY9fa4MwFMXf@yku@pJgKtR2/8gc6HQ@rQP3OPYQo450NpYYZaP42V2qbmwwNkjgnJvwO/fsWMeWu/x14BVrGrhnQh4XAELqQpWMF7A9WYBHrYR8AY5mwcgssk/BMTU/e3PNaTTTgsMWJPgwIEYywvHy5tgxBcq3bIuWtUImBYS/IpqK6yuKleMzt2mzZgQi7WeukHnx9lAi/m0uiHB8D2OiHQ9TVehWSVC0H@iUfWizymTPK3S1yGFvas2bPz0zPFd6b3Sxd@tWuwfzoiuJpMuRZa@89ebs/OLSImDZaZokYRgEowmCyVp4LPsXI/DC9e0m@o0RhkmSpv8zojiIwji@@xl9MhPui9Ev@uED)
```
(a,b,c)->{ // Method with String as three parameters and return-type
var r="#"; // Result-String, starting at "#"
for(int i=1,t;i<9; // Loop `i` from 1 to 9 (exclusive)
r+= // Append the result with:
a.substring( // A substring from the first input,
t=b.indexOf( // where an index is determined in the second input
c.substring(i,i+=2)),t+2);
// based on a substring of the third input
return r;} // Return the result-String
```
[Answer]
# [J](http://jsoftware.com/), 5 bytes
```
/:i./
```
The left argument is the color. The right argument is a character matrix where the first row is the target format and the second row is the original format. [Try it online!](https://tio.run/##y/r/P81WT0HfKlNP/z9XanJGvoK6sqGRsYmpmbmFukIakOfoGBTk7u7kpK5jpa4MYTo6qsPUurg6uji5urpB1EIkg4LAauEa4eY6GjkZO5u4wMx1cnJ3h6qFm/sfAA "J – Try It Online")
[Answer]
# CJam, 14 bytes
```
{'#\1f>2f/~er}
```
[Try it Online!](http://cjam.aditsu.net/#code=%5Blll%5D%7B'%23%5C1f%3E2f%2F~er%7D~&input=%23AARRGGBB%0A%23RRGGBBAA%0A%2312345678%0A)
Input is an array in the reverse order.
```
{
`#\ e# Push '#'+[input array] on to stack
1f> e# Remove the '#' symbol from each input string
2f/ e# Split each input string into an array of substrings of length 2.
~ e# Dump the substring-arrays from the container array onto the stack
er e# Perform a string replace operation
}
```
[Answer]
# Python 2, 62 bytes
```
lambda c,s,e:[c[s.index(e[i]):][:2]for i in range(1,len(e),2)]
```
[Answer]
# SmileBASIC, 144 bytes
```
DEF R C,I,O
C[0]="&H
A=R+G+B
RGBREAD VAL(C)OUT VAR(I[1]),VAR(I[3]),VAR(I[5]),VAR(I[7])?"#";RGB(VAR(O[1]),VAR(O[3]),VAR(O[5]),VAR(O[7]))END
```
[Answer]
# [Red](http://www.red-lang.org), 154 120 114 bytes
```
func[c o t][g: func[q][parse q[skip collect 4 keep 2 skip]]
prin"#"foreach p g t[prin pick g c index? find g o p]]
```
[Try it online!](https://tio.run/##ZYzLCoMwFET3fsUQv6BqH7gpSbXusw1ZSEysKBofhULpt9v42JSu7pzhzB10MXNdCOmZeDbPVgmFDpMUZYwVeylsPowavRjrykJ1TaPVhAi11hYBllZKzw5VS3xiukHn6gGLEpNYSthK1Y4UqrbQryuMu447uNlsQPxDEEbH0/lCXOY8yxijdMmUbkTW5xPeH2/VacDCW5T864xlGee7vttJShOWpvefhy5vO2fPXw "Red – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 102 bytes
```
lambda x,a,b:['#']+[[x[i:i+2]for i in range(1,len(x),2)][i]for i in[a[1::2].index(i)for i in b[1::2]]]
```
[Try it online!](https://tio.run/##bY7BasMwEETP9VcIcpBERInlJC2CHKTa9d3X7RLkRm4XEiXYPrhf78Y1uBR6WRjmzezcvvrPa8zG5vA2nv2lPnk2KK9qA3zFcQ0wABlaa2yuLSNGkbU@fgSRqnOIYpBKSwRaXPCQGqPxkeIpDILkEqtnA3HsQ9cf330XOnZgcP@T6my72z89c8X4qqrK0jlrf4S1s@SoJs5ql71s8/8458qyqmYuL2zuiuL1b8VdzIkJwyRJlmm/g0zycGsp9qIRBBtUBOl0NEo5fgM "Python 3 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
ẹЀQị⁵
```
[Try it online!](https://tio.run/##y0rNyan8///hrp2HJzxqWhP4cHf3o8at////V1cOCnJ3d3JydFQHsh0dnZzc3YOCQGxDRyMnY2cTF3UA "Jelly – Try It Online")
Full program.
Argument 1: Original
Argument 2: Target
Argument 3: Color
[Answer]
# [C (clang)](http://clang.llvm.org/), 89 bytes
```
char *a,b[10],*i,*o;f(x,y){*b=*a;for(x=1;x<8;b[x++]=a[y=index(i,o[x])-i],b[x++]=a[y+1]);}
```
[Try it online!](https://tio.run/##dU/RboIwFH3vVzSQJVDrFHTTpGLSCvLOK@OhomATVxbUBGP8dlboBLZkSXNz77nnnHuajtMTl3ltCpmervvD6nzZi@L1uAYDpBQyV1CdHnkJEce72JkmGAmMCpJZFb7Zd7TzECdZUVqV55BqtSS7uBqNEo/HN0/I/aGyBC7iKrHHIsH9buQkNnnUuWXDO/hShy6ZZbycoX7jNTQw5BgKDAubgMxSpWd9SEPjDwAUBj@5kK0R4J5hOu5s/va@WBoECjVGURgyRqkaCzVSqgGDgLxx1RLqstlm7v8nYSwMo@iXxA@oz4Jg@yPpbVuJ1g8k5eFyLSWcqnaCQJcRw@6Yap8mzf/NxVKTQJfuL1mnaslzf7ZxmUNBl2tgp9pnnpbcrBsaQBPwqL8B "C (clang) – Try It Online")
Takes input value in `a`, in format in `i` and out format in `o`. Returns out value in `b`
Minor cheat: storing result in `b` instead of printing to save bytes. Question doesn't disallow it.
# [C (clang)](http://clang.llvm.org/), 100 bytes
```
char *a,b[10],*i,*o;f(x,y){*b=*a;for(x=1;x<8;b[x]=a[y=index(i,o[x])-i],b[x+1]=a[y+1],x+=2);puts(b);}
```
[Try it online!](https://tio.run/##dY7LbsIwFET3/goLNrExhTxakIyRbEKzzzZi4YSXJepUIZGMEN@emgRCWqkr3zt3zniycXaS@lAPlc5O1Xa3OJdblb8dl6CnFEofrFRnR1lALEmauNMNwYrgnO4dQy7oilOGJd3nhWOYS81iTtPEbJhMLkzp7c44iuRWQGO1sbgZuc3NPsSMmIfod1WenRTRW610Cb@k0g6CVwAkGwxdzw/eP2bzAYXKrnEcRUJwbtfcrpy3woCCvYPoA@Ge8FdB@B8iRBTF8S8kXPNQrNefD@QV2yAt30OKXVkVGk7tOMGg60hg95kdnyFwvITD2bw1ga7dX3PbqjEHob/yhMtB16sXZ8dnn8Z8P99tAE/Arf4B "C (clang) – Try It Online")
# [C (gcc)](https://gcc.gnu.org/), 181 bytes
```
char *a,*i,*o;c[4],x,y,z;g(x){x=x==82?0:x==71?1:x==66?2:3;}f(){a++;for(;z<2;z++){i=(z?o:i)+1;for(y=0;y<7;z?printf("%s%2X","#"+!!y,c[g(i[y])]):sscanf(a+y,"%2X",&c[g(i[y])]),y+=2);}}
```
[Try it online!](https://tio.run/##jZBRb5swFIXf/StcR10wuE2ALIniUARNxjtPlRgPnuOkljKIwJGAKL89M7CyaurUScjHl3v0@dzLHw6c30Yy48fzTqxLtZP54@vTjb@yApqMmJKYOeXJLCUVqUlDD0aFL5VXed7S8acrrQvbt1udz31n5dLr3sAXZll0nxcGbdYObSwLX6RnNH6@ktiyu07tTWm9XtDGPxUyU3sD3Zf3zgsiaISsu7ua8ORgyKROcYpXZclZtjeYVRPUmb6865La8hxMr1dw0yD4k8nMwPACwADeweH7niECD8Y4HmOiJeol7CUYY0wBmEz4UbAMlkemBPwhdFwBlSgV5KwUj5DnOwFFdRJclbBUTEkOZSaVZEfZ6CrPAODJNPV4YreH0x5uqndWe40eGzAPjWzHnX2dL5aIQqnLOI6iMAwCXea6DIL@B6JAr5OC01mVBkJtuv9AB07oPs82/0KHYRTF8QfoT8mbbbAJt9tvv8l/Unbk/pkPyYVQ5yKD03a7JhiGJ3BIp69vOPjwBEeLZW8Cwzh/m/sxOvNs4z47oR2AIeE7nL6@JevMbbu1AXMCrrdf "C (gcc) – Try It Online")
Creates a `RGBA` value in `c[]` array based on format `i`, then prints in `o` format
[Answer]
# Clojure 1.8, 156 bytes
```
(fn[c o t](reduce #(str %(val %2))""(sort-by key(reduce-kv #(let[s(clojure.string/index-of t(nth o %2))](assoc %(if(contains? % s)(inc s)s)%3)){}(vec c)))))
```
Ungolfed
```
(fn [c o t]
(reduce
#(str % (val %2))
""
(sort-by key
(reduce-kv
#(let [s (clojure.string/index-of t (nth o %2))]
(assoc %
(if (contains? % s) (inc s) s)
%3))
{}
(vec c)))))
```
Try it online does not have Clojure 1.8 support. Very strange!
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~55~~ ~~51~~ 46 bytes
```
{[~] %(@^b Z=>@^a){@^c}}o*.map(*.comb(/\w?./))
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OrouVkFVwyEuSSHK1s4hLlGz2iEuubY2X0svN7FAQ0svOT83SUM/ptxeT19T8781V3FipYKSSryCrZ1CdZqGSrxmrZJCWn4RF6eNsqGRsYmpmbmFgnJQkLu7k5Ojo4KyoyOEbacDVuFo5GTsbOKCqsLJyd09KAiiwsXV0cXJ1dUNoVNBGaISqOI/AA "Perl 6 – Try It Online")
Takes a (color, original, target) list as input. Splits each input string into components, creates a Hash mapping source keys to color values, looks up color values in target key order, then formats the result.
]
|
[Question]
[
**This question already has answers here**:
[Run Length Decoding](/questions/12902/run-length-decoding)
(51 answers)
Closed 7 years ago.
Working with old files from DOS, I found an ancient text animation format, that specify how much time each frame must be shown in the screen. It's very simple:
>
> F1W5F2W3
>
>
>
This example above indicates that Frame 1 must be shown for 5 units of time, and frame 2 for 3 units more. Now I want to convert it to:
>
> 1, 1, 1, 1, 1, 2, 2, 2
>
>
>
In the converted example below, frame 1 is repeated 5 times, and frame 2 three times.
**Rules:** The only allowed letters are *F* and *W* (and the lowercase counterparts, *f* and *w*). Numbers can go up to 255. Total input String with no more than 255 chars.
Other examples:
>
> Input: F10W3F11W3F10W3F12W3
>
>
> Output: 10, 10, 10, 11, 11, 11, 10, 10, 10, 12, 12, 12
>
>
> Input: f1w0f2w10
>
>
> Output: 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
>
>
>
**Short code wins.**
**Edited - Accepted formats:**
Any answer containing the output and ignoring spaces. Ex: 1, 1, 2, 2 or [1,1,2,2] or (1,1,2,2). But NOT 1 1 2 2 or [1; 1; 2; 2] or [1 1 2 2].
[Answer]
## Python 3, 57 bytes
```
lambda s:eval(s.upper().translate({70:'+[',87:']*'})[1:])
```
Turns a string like
```
f1w0f2w10
```
into a expression like
```
[1]*0+[2]*10
```
that it evaluated as code. This is done by turning the string uppercase, turning each `f` into `+[` and each `w` into `]*`, and removing the initial `+`. Thanks to Dennis for saving 7 bytes in Python 3 by using translate with a dictionary.
[Answer]
# [V](http://github.com/DJMcMayhem/V), 25 bytes
```
Óá¨ä«©á¨ä«©/²a±,
D@"hD
```
[Try it online!](http://v.tryitonline.net/#code=w5PDocKow6TCq8Kpw6HCqMOkwqvCqS_CsmHCsSwgFhsKREAiaEQ&input=RjEwVzNGMTFXM0YxMFczRjEyVzM)
Here is a hexdump of the answer, which is encoded in latin1:
```
0000000: d3e1 a8e4 aba9 e1a8 e4ab a92f b261 b12c .........../.a.,
0000010: 2016 1b0a 4440 2268 44 ...D@"hD
```
Explanation:
`<C-v>` is byte `0x16` and `<esc>` is byte `0x1B`. Since they are both unprintable, I am using this notation to refer to them.
```
Óá¨ä«©á¨ä«©/²a±, <C-v><esc>
```
This is a compressed regex, that basically transforms the input into V code. Here's what the buffer looks like after running this regex:
```
3a10, <esc>3a11, <esc>3a10, <esc>3a12, <esc>
```
Here's how that works:
```
3 "3 times:
a <esc> "Append the following text:
10, " '10, '
```
Running this in V (or its parent, vim) would create:
```
10, 10, 10,
```
And then a similar command repeats for each element of the input.
---
So, after running this regex, we've got valid V code that will create the desired output. Thankfully, V can easily self-interpret, as long as the code is in a buffer. So, we run the following:
```
D "Delete this line into the unnamed register
@" "Run the text in the unnamed register as V code
```
This is exactly what we want, but now the output has a trailing `,`. So:
```
h "Move one character to the left. Now we are on the second to last character
D "Delete until the end of the current line
```
[Answer]
# Pyth, 18 bytes
```
r_McvM:z"\d+"1 2 9
```
[Try it online.](http://pyth.herokuapp.com/?code=r_McvM%3Az%22%5Cd%2B%221+2+9&input=F10W3F11W3F10W3F12W3&debug=0) [Test suite.](http://pyth.herokuapp.com/?code=r_McvM%3Az%22%5Cd%2B%221+2+9&test_suite=1&test_suite_input=F1W5F2W3%0AF10W3F11W3F10W3F12W3%0Af1w0f2w10&debug=0)
[Answer]
# [MATL](http://github.com/lmendo/MATL), 22 bytes
```
t58<*cU2eZ}Y"&D32','XE
```
[Try it online!](http://matl.tryitonline.net/#code=dDU4PCpjVTJlWn1ZIiZEMzInLCdYRQ&input=J0YxMFczRjExVzNGMTBXM0YxMlczJw)
### Explanation
```
t % Implicitly input string, say 'F10W2F1W3'. Duplicate
58< % Array that contains 1 for numeric chars, 0 otherwise: [0 1 1 0 1 0 1 0 1]
* % Multiply element-wise. Converts chars to numeric code
c % Cast to char. Gives the original string with letters replaced by char 0
U % Interprets as a numeric array. So the string ' 10 2 4 3' (where spaces are
% actually char 0) gives the array [10 2 4 3]
2e % Reshapes into a 2-column array in column-major order: [10 4; 2 3]
Z} % Split into rows: [10 4], [2 3]
Y" % Run-length decoding: [10 10 4 4 4]. Implicitly display
&D % Get string representation, in the format '[10 10 4 4]'
32','XE % Replace spaces by commas
```
[Answer]
# Pyth, 13 bytes
```
smMcr7Xrz0Gd2
```
[Test suite](https://pyth.herokuapp.com/?code=smMcr7Xrz0Gd2&test_suite=1&test_suite_input=F1W5F2W3%0AF10W3F11W3F10W3F12W3%0Af1w0f2w10&debug=0)
This program uses one of my favorite tricks, `mM`, which maps the map function over a list. It is also uses a relic of Pyth's distant past, the `r7` function, which splits a string on whitespace and evaluates the contents, which just so happens to be absolutely perfect for this challenge. Here's how it works, and each intermediate state:
```
smMcr7Xrz0Gd2 f1W5F2w3
z "f1W5F2w3" Implicit: z is the input.
r 0 "f1w5f2w3" Lowercase
X Gd " 1 5 2 3" Replace all lowercase letters (G) with spaces (d)
r7 [1, 5, 2, 3] Split on whitespace, eval each string.
c 2 [[1, 5], [2, 3]] Split into groups of length 2
mM Apply the map function to each pair
[[1, 1, 1, 1, 1], [2, 2, 2]]
s Flatten
[1, 1, 1, 1, 1, 2, 2, 2]
```
[Answer]
# JavaScript ES6, 68 bytes
```
s=>s.replace(/F(\d+)W(\d+)/gi,(z,a,b)=>(f=n=>n&&f(n-1,alert(a)))(b))
```
Hopefully an alert box counts as a frame as I couldn't think of another way to count as a 'frame'.
Slightly modified version to try in-browser
```
t=function(s){s.replace(/F(\d+)W(\d+)/gi,function(z,a,b){(f=function(n){return n&&f(n-1,alert(a))})(b)})}
// Demo
document.getElementById('go').onclick=function(){
document.getElementById('output').innerHTML = t(document.getElementById('input').value)
};
```
```
<div style="padding-left:5px;padding-right:5px;"><h2 style="font-family:sans-serif">Text Animation</h2><div><div style="background-color:#EFEFEF;border-radius:4px;padding:10px;"><input placeholder="Input here..." style="resize:none;border:1px solid #DDD;" id="input"><button id='go'>Run!</button></div><br><div style="background-color:#EFEFEF;border-radius:4px;padding:10px;"><span style="font-family:sans-serif;">Output:</span><br><pre id="output" style="background-color:#DEDEDE;padding:1em;border-radius:2px;overflow-x:auto;"></pre></div></div></div>
```
[Answer]
# Perl, 28 bytes
27 bytes of code, plus 1 for the `p` flag in `perl -pe '…'`:
```
s|f(\d+)w(\d+)|"$1
"x$2|gie
```
Output for `F10W3F11W3F10W3F12W3`:
```
10
10
10
11
11
11
10
10
10
12
12
12
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/), 16 bytes
```
l'f¡vy'w¡`FDïˆ}\
```
**Explanation**
```
# implicit input
l # convert to lower case: 'f1w5f2w3'
'f¡ # split on "f": ['','1w5','2w3']
v # for each: ex '1w5'
y'w¡ # split on "w": ['1','5']
` # flatten: '5','1'
FDïˆ} # N times do; duplicate, convert to int, push to global array: [1,1,1,1,1]
\ # discard last copy
# implicitly print list at the end of the program
```
[Try it online](http://05ab1e.tryitonline.net/#code=bCdmwqF2eSd3wqFgRkTDr8uGfVw&input=RjEwVzNGMTFXM0YxMFczRjEyVzM)
[Answer]
## Perl 6, 30 bytes
```
{m:g/\d+/.map:{|(+$^f xx$^w)}}
```
Anonymous function (aka: lambda) which uses a regex match to pull out all the numbers.
I then map over this list, pulling out 2 items at a time using self-declared positional variables `$^f` and `$^w`. Self-declared positional variables are assigned alphabetically, so `f` and `w` works nicely.
The regex match actually produces a list of `Match` objects, so I use the `+` prefix operator to coerce `f` to an `Int`.
The map creates a list of `f`, `w` times. This would normally create a List-of-Lists, so I use the `Slip` prefix operator `|`. A `Slip` is a `List` sub-type that flattens into an outer list, ie. It *slips* a list into the surrounding list, so in the end we get a flat list.
Usage example: `{m:g/\d+/.map:{|(+$^f xx $^w)}}('F1W5F2W3')` returns `(1, 1, 1, 1, 1, 2, 2, 2)`.
Here is the same function written as a full-blown named subroutine, with a more explicit definition.
```
sub f(Str $s) {
($s ~~ m:g/\d+/).map(-> $f, $w {
slip( $f.Int xx $w )
});
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 (strict), 8 (relaxed) [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
**Strict input (any upper or lower) & strict output form of a flat list**
```
Œl“wẋ”yṣ”fj“ð;ø”VḊ
```
How?
```
Œl“wẋ”yṣ”fj“ð;ø”VḊ - takes an input, example: F11w7f13W5F17w3f19W2
Œl - to lower case f11w7f13w5f17w3f19w2
“wẋ” - make string "wẋ"
y - map "w":"ẋ" f11ẋ7f13ẋ5f17ẋ3f19ẋ2
”f - make string "f"
s - split on "f" [,11ẋ7,13ẋ5,17ẋ3,19ẋ2]
“ð;ø” - make string "ð;ø"
j - join with "ð;ø"s ð;ø11ẋ7ð;ø13ẋ5ð;ø17ẋ3ð;ø19ẋ2
V - eval Jelly code...
each ẋ will repeat left right times, e.g. 17ẋ3 yields [17,17,17]
; will concatenate,
ð will treat the last chain as a dyadic link (the first will yield 0 as there is no link)
ø will treat the last chain as a niladic link
- so the example evaluates to:
[0, 11, 11, 11, 11, 11, 11, 11, 13, 13, 13, 13, 13, 17, 17, 17, 19, 19]
Ḋ - dequeue
[11, 11, 11, 11, 11, 11, 11, 13, 13, 13, 13, 13, 17, 17, 17, 19, 19]
```
Test it at [**TryItOnline**](http://jelly.tryitonline.net/#code=xZJs4oCcd-G6i-KAnXnhuaPigJ1mauKAnMOwO8O44oCdVuG4ig&input=&args=RjExdzdmMTNXNUYxN3czZjE5VzI)
**Non-strict version: only lower input, returns smashed lists** [a,a,...][b,b,..][...
```
“wẋfø”yv
```
How?
```
“wẋfø”yv - takes an input, example: f11w7f13w5f17w3f19w2
“wẋfø” - make the string "wẋfø"
y - map "w":"ẋ";"f":"ø" ø11ẋ7ø13ẋ5ø17ẋ3ø19ẋ2
v - eval Jelly code left with input right (empty)
this is a hack as V should work (I think)
but by forcing no input the leading ø evaluates to nothing
evaluation is as above, but simply yields the ẋ lists in turn
- so the example evaluates to:
[11, 11, 11, 11, 11, 11, 11][13, 13, 13, 13, 13][17, 17, 17][19, 19]
```
Test it at [**TryItOnline**](http://jelly.tryitonline.net/#code=4oCcd-G6i2bDuOKAnXl2&input=&args=ZjExdzdmMTN3NWYxN3czZjE5dzI)
[Answer]
## Perl, 32 bytes
**29 bytes code + 3 for `-n`.**
```
print"$1 "x$' while/(\d+)w/gi
```
### Usage
```
cat text-animation.pl
print"$1 "x$' while/(\d+)w/gi
perl -n text-animation.pl <<< 'F1W5F2W3'
1 1 1 1 1 2 2 2
```
## Perl, 29 bytes
**26 bytes code + 3 for `-n`.**
If no separator is required, this works:
```
print$1x$' while/(\d+)w/gi
```
[Answer]
# Pyth, 18 bytes
```
r9m_sMdcR\Wtcr1Q\F
```
If you don't need to allow for both upper and lower case, you can take out the `r1` for 16 bytes:
```
r9m_sMdcR\WtcQ\F
```
[Try it online!](http://pyth.tryitonline.net/#code=cjltX3NNZGNSXFd0Y3IxUVxG&input=IkYxMFczRjExVzNGMTBXM0YxMlczIg)
Explanation:
```
c split:
r1Q the uppercase of the input
\F on the letter "F"
t Remove the first result
The first "F" in the notation has nothing in front of it,
so this removes the empty string that prefaces everything
cR\W Split each of the results on "W"
m_ Reverse each of the splits so that the "W" part is first (how many repetitions, then what is to be repeated)
sMd Cast everything within the splits to integers
r9 Run length decode
```
[Answer]
# R, 78 bytes
```
m=strsplit(scan(,""),"[FWfw]")[[1]][-1];cat(rep(m[c(T,F)],m[c(F,T)]),sep=", ")
```
Credit for the `rep(m[c(T,F)],m[c(F,T)])` bit goes to [@flodel](https://codegolf.stackexchange.com/questions/12902/run-length-decoding/12913#12913).
Usage:
```
> m=strsplit(scan(,""),"[FWfw]")[[1]][-1];cat(rep(m[c(T,F)],m[c(F,T)]),sep=", ")
1: F10W3F11W3F10W3F12W3
2:
Read 1 item
10, 10, 10, 11, 11, 11, 10, 10, 10, 12, 12, 12
> m=strsplit(scan(,""),"[FWfw]")[[1]][-1];cat(rep(m[c(T,F)],m[c(F,T)]),sep=", ")
1: f1w0f2w10
2:
Read 1 item
2, 2, 2, 2, 2, 2, 2, 2, 2, 2
```
[Answer]
# VBA, ~~162 bytes~~ 147 bytes
Okay, this is only for fun since it's kinda hard to beat esoteric programming languages but I don't care too much about winning the challenge. I do enjoy solving the challenge, though. Here is my *stab* for this challenge:
```
Function F(a):b=Split(Replace(a,"F","W"),"W"):For i=1To Ubound(b)/2:c="":For j=1To b(2*i):c=c & b(2*i-1) & ",":Next:d=d & c:Next:F=Left(d,Len(d)-1)
```
Ungolfed the code:
```
Function F(a)
b = Split(Replace(a, "F", "W"), "W")
For i = 1 To UBound(b) / 2
c = ""
For j = 1 To b(2 * i)
c = c & b(2 * i - 1) & ","
Next
d = d & c
Next
F = Left(d, Len(d) - 1)
End Function
```
Explanation:
1. Substitute the letter **F** in the string input with **W** using VBA function Replace.
2. Split the string result with delimited letter **W** into a 1D array.
3. Looping through each element array where every odd element is replicated as many as its next element value (the nearest even element).
4. Concatenate each of looping output.
5. Truncate the output so that the trailing `,` is excluded.
---
Thanks [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) for the advice.
[Answer]
## Haskell, 68 bytes
```
p""=[]
p(_:b)|[(c,_:d)]<-reads b,[(e,f)]<-reads d=(c+0<$[1..e])++p f
```
Usage example: `p "F1W5F2W3"` -> `[1,1,1,1,1,2,2,2]`.
`reads` takes a string and reads something from the front of it and returns a singleton list with a pair of the something and the rest of the string. The type system knows from the usage `c+0` and `[1..e]` that the somethings must be numbers, so `reads` consumes all digits from the beginning of the string. The `_` in the patterns match the letters `F` and `W` that we don't need otherwise.
[Answer]
## Clojure, 86 bytes
```
(fn[a](mapcat #(repeat(read-string(last %))(first %))(partition 2 (re-seq #"\d+" a))))
```
Depending on requirements, I could also drop "cat" from "mapcat".
[Answer]
## C#, ~~160~~ 155 bytes
```
s=>{var r="";int i=1,j;var t=s.Split('f','F');while(i<t.Length){var u=t[i++].Split('w','W');for(j=0;j++<int.Parse(u[1]);)r+=u[0]+",";}return r.Trim(',');};
```
[Answer]
## PowerShell v2+, 67 bytes
```
($args[0]-replace'F','+,'-replace'W','*').trim('+')+'-join", "'|iex
```
Takes input `$args[0]` as a string, pumps it through two `-replace` statements to swap the `F` for a `+,` and the `W` for a `*`. Then `.trim`s the errant initial `+` before concatenating `-join` with a `,<space>`, and piping to `iex` to evaluate the resulting string into a new string. That's left on the pipeline, and output is implicit.
As an example, with input `F1W5F2W3`, after the `-replace`s, our string will be `+,1*5+,2*3`. After the `.trim`, it'll be `,1*5+,2*3`. That's concatenated with the `-join` statement, like `,1*5+,2*3-join", "`. The `iex` then evaluates that string by forming an array of `5` `1`s via the comma-operator, using array concatenation to add on an array of `3` `2`s, so we have an array like `(1,1,1,1,1,2,2,2)`, which is then fed into `-join` to put the comma-space between the elements.
Since `-replace` is by default case-insensitive, it handles lowercase as well.
### Test cases
```
PS C:\Tools\Scripts\golfing> .\text-animation-format.ps1 'F1W5F2W3'
1, 1, 1, 1, 1, 2, 2, 2
PS C:\Tools\Scripts\golfing> .\text-animation-format.ps1 'F10W3F11W3F10W3F12W3'
10, 10, 10, 11, 11, 11, 10, 10, 10, 12, 12, 12
PS C:\Tools\Scripts\golfing> .\text-animation-format.ps1 'f1w0f2w10'
2, 2, 2, 2, 2, 2, 2, 2, 2, 2
```
[Answer]
## [Retina](https://github.com/m-ender/retina), 51 bytes
Might be able to be golfed further, I'm not super familiar with Retina.
```
i`F(\d+)W(\d+)
$1_$2$*n
(?<=(\d+).*?)n
$1,
\d+_|,$
```
The trailing linefeed is significant.
[Try it online!](http://retina.tryitonline.net/#code=aWBGKFxkKylXKFxkKykKJDFfJDIkKm4KKD88PShcZCspLio_KW4KJDEsClxkK198LCQK&input=ZjF3MGYydzEw)
**Explanation:**
The code consists of three replacement stages.
```
i`F(\d+)W(\d+)
$1_$2$*n
```
This replaces each group of `FxWy` into `x_` followed by `n` repeated *y* times. For example, `F2W3` is replaced with `2_nnn`. `i`` makes the regex case insensitive.
```
(?<=(\d+).*?)n
$1,
```
This matches all the repeated `n`'s. and replaces each of them with the number closest before it, followed by a comma. Using our previous example of `F2W3`, `2_nnn` is replaced with `2_2,2,2,`.
```
\d+_|,$
```
This removes the final garbage left behind. It replaces the numbers directly followed by underscores, and the comma at the end of the line, with nothing. So `2_2,2,2,` becomes `2,2,2`, which is the desired output.
]
|
[Question]
[
There's the classic run length encoding and decoding.
```
input output
a3b2c5 aaabbccccc
```
And that's fairly straight forward and done before.
The challenge is to also account for a non-standard behavior when multiple characters precede the run length (a ***single*** digit from 0-9). Each character before the run length digit (the last digit before a non-digit or end of the string) has that value applied to it *individually* and printed out in order.
Some test input and output including some edge cases:
```
input output
ab3c5 aaabbbccccc
a0b3 bbb
13b1 111b
a13b1 aaa111b
a123b1 aaa111222b
aa2a1b1 aaaaab
```
* A character sequence (`[a-zA-Z0-9]+`) must be followed by its run length length (`[0-9]`)
* Only valid input needs to be considered (`([a-zA-Z0-9]+[0-9])*`)
+ yes, empty string is valid input.
* Input is via standard input, output via standard output
This is code golf, number of bytes determines the winner.
[Answer]
## Perl/Bash ~~54~~ 40+1 = 41 bytes
```
perl -pe's:(\D*\d*)(\d):"\$1=~s/./\$&x$2/egr":ege'
```
It's basically a regex within a regex. And a bit of magic.
### Explanation
The outer regex `/(\D*\d*)(\d)/g` extracts each run-length encoded group. We capture the stuff to repeat in `$1` and the number of repetitions in `$2`. Now we substitute each such group with the expansion of that group. For that, we evaluate the code `"\$1=~s/./\$&x$2/egr"` *two* times (as by the `/ee` flag on the outer substitution).
The first evaluation will only interpolate the number of repetitions into the string – the other variables are protected by a backslash. So assuming the input `a14`, we would now have the code `$1=~s/./$&x4/egr`, which will be evaluated again.
This will apply the substitution to the contents of `$1` (the stuff to repeat `a1`). The substitution matches each character `.`. The `$&` variable holds the whole match, which we repeat `x4` times. We do this `/g`lobally for each match and `/r`eturn the substituted string rather than modifying the `$1` variable (which is read-only). So the result of the inner substitution is `aaaa1111`.
The `-p` flag applies the substitution to each input line and prints out the result.
[Answer]
# CJam, ~~33 31~~ 27 bytes
Ughh, lack of regular expressions makes this pretty long...
```
qN+{:XA,s&L\:L>{])~e*[}&X}%
```
**How it works**
We loop through all characters of the input string and in each iteration, keep track of the last encountered character (starting with an empty character for the first time). Then we check if the current character is non-numeric *and* the last character is numeric. If so, we repeat each previous character (which has not been repeated already), the number times.
(A bit outdated code expansion)
```
q{ }% e# Read the input (q) and loop through each character
L e# Put variable L (initially empty character) on stack
A, e# Put variable A (equals 10) and create an array 0..9
s e# Convert the array to string "0123456789"
& e# Do a set intersect b/w previous char and 0-9 string
e# If numeric, it gives 1 char string, otherwise 0
\:LA,s& e# Swap to bring current character on top. Store it in L
e# and do the same set intersect with it
> e# Means we are checking that current char is non-numeric
e# and previous numeric
{ }& e# Run this block if above is true
])~ e# Wrap everything not already repeated in an array and
e# take out the last character and convert it to integer.
e# This is the run length of the preceding string
e* e# Repeat each character in the string, run length times
[ e# Start a new array to help when next run length is found
L e# Restore the current character back on stack to be used
e# in next iteration
)~e* e# The last string-run-length pair is not decoded..
e# So we do that now
```
[Try it online here](http://cjam.aditsu.net/#code=q%7BLA%2Cs%26%5C%3ALA%2Cs%26%3E%7B%5D)~e*%5B%7D%26L%7D%25)~e*&input=a14f2h3b5c1)
[Answer]
# [rs](https://github.com/kirbyfan64/rs), 43 71 chars
Well, this turned long quickly. Stupid numbers...
```
(\d)(\D)/\1 \2
+(\w)(\w+?)(\d)(?= |$)/\1\3 \2\3
(\w)(\d)/(\1)^^(\2)
/
```
[Try it here!](http://kirbyfan64.github.io/rs/index.html?script=(%5Cd)(%5CD)%2F%5C1%20%5C2%0A%2B(%5Cw)(%5Cw%2B%3F)(%5Cd)(%3F%3D%20%7C%24)%2F%5C1%5C3%20%5C2%5C3%0A(%5Cw)(%5Cd)%2F(%5C1)%5E%5E(%5C2)%0A%20%2F%0A&input=a123b1a3b2c5%0A)
Original version (did not work with input like `123`):
```
+(\D)(\D+)(\d)/\1\3\2\3
(\D)(\d)/(\1)^^(\2)
```
## Explanation
The first line places spaces between runs containing numbers, e.g. turning `a313` into `a3 13`.
The second line continuously expands the compressed encodings like `aa5` to `a5a5`.
The third line converts every instance of `a5` into `aaaaa` using the [repetition operator](https://github.com/kirbyfan64/rs#repetition).
The last line removes the spaces.
[Answer]
# Javascript (*ES6*), 86 83 bytes
```
alert(prompt().replace(/(.+?)(\d)(?!\d)/g,(a,b,c)=>b.replace(/./g,y=>y.repeat(c))))
```
**Commented:**
```
alert( // output final result
prompt(). // take input
replace(/(.+?)(\d)(?!\d)/g, // replace ungreedy capture group of any characters
// followed by a digit (captured)
// and not followed by a digit (negative lookahead)
(a, b, c)=> // replace with a function
b.replace(/./g, // replace all characters in b
y=>y.repeat(c) // with that character repeated c times
)
)
)
```
[Answer]
# CJam, ~~27~~ 25 bytes
```
r_'A+1>.{64&1$>{])~f*o}&}
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=r_'A%2B1%3E.%7B64%261%24%3E%7B%5D)~f*o%7D%26%7D&input=a123b1).
### How it works
```
r_ e# Read a token from STDIN and push a copy.
'A+ e# Append the character A to the copy.
1> e# Discard the first character of the copy.
.{ } e# For each character C of the input string and the
e# corresponding character D of the copy:
64& e# Take the bitwise and of D and 64. This pushes @
e# if D is a letter and NUL if it is a digit.
1$> e# Compare the result to a copy of C. This pushes 1
e# if and only if D is a letter and C is a digit.
{ }& e# If the result was 1, do the following:
] e# Wrap the stack in an array.
)~ e# Pop and evaluate the last character.
f* e# Repeat each char in the array that many times.
o e# Print all characters.
```
[Answer]
# Pip, 22 + 1 = 23 bytes
Uses `-r` flag. Note that this requires you to either 1) enter an EOF after the input (Ctrl-D on Linux, Ctrl-Z on Windows) or 2) pipe the input in from somewhere else.
```
(^_@<v)X_@vMa@`\D*\d+`
```
Explanation:
```
a is first line of stdin (from -r flag) and v is -1 (implicit)
`\D*\d+` Pattern (regex) object that matches zero or more non-digits
followed by at least one digit
a@ Find all non-overlapping matches in a, returning a list of strings
M To that list, map a lambda function:
_@<v Argument sans last character (equivalent to Python a[:-1])
(^ ) Split into a list of characters
_@v Last character of argument
X Repeat each character of the list that many times
(String multiplication X, like most operators, works item-wise
on lists)
Auto-print (implicit)
```
The result of the map operation is actually a list of lists, but by default lists are simply concatenated together when printed, so no manual conversion to string is necessary.
Example, with input `a13b1`:
```
Var a gets "a13b1"
After regex match ["a13" "b1"]
After map [["aaa" "111"] ["b"]]
Final output aaa111b
```
Pip has basic regex support as of... [2 days ago](https://github.com/dloscutoff/pip/commit/5d2b2bb483e0875ecd33182756e96635934d760f). Great timing!
[Answer]
# Pyth, ~~33~~ ~~32~~ 28 bytes
```
ssmm*vedkPdPcz-hMJf<@zT\=UzJ
```
Try it online: [Demonstration](https://pyth.herokuapp.com/?code=ssmm*vedkPdPcz-hMJf%3C%40zT%5C%3DUzJ&input=aa2a1b1&debug=0) or [Test harness](https://pyth.herokuapp.com/?code=zFz.zp%22+-%3E+%22z%0Assmm*vedkPdPcz-hMJf%3C%40zT%5C%3DUzJ&input=Test-cases%3A%0Aa3b2c5%0Aab3c5%0Aa0b3%0A13b1%0Aa13b1%0Aa123b1%0Aaa2a1b1&debug=0)
### Explanation
I'll explain the code using the example input `aa1a23b2`. Hopefully this is a bit easier to follow than without.
```
implicit: z = input string = 'aa1a23b2'
Uz the indices of z: [0, 1, 2, 4, 5, 6, 7]
f filter for indices T, which satisfy:
<@zT\= z[T] < "="
this gives us the list of indices [2, 4, 5, 7],
which correspond to digits in z.
J assignment, J = [2, 4, 5, 7]
hMJ increment all element in J: [3, 5, 6, 8]
- J and remove the elements of J:
[3, 5, 6, 8] - [2, 4, 5, 7] = [3, 6, 8]
cz split z at these indices: ['aa1', 'a23', 'b2', '']
P remove last element: ['aa1', 'a23', 'b2']
m map each string d to:
m Pd map each string k of d-without-last-char to:
ved int(last element of d)
* k * k
this creates [['a', 'a'], ['aaa', '222'], ['bb']]
s sum the lists: ['a', 'a', 'aaa', '222', 'bb']
s sum the strings: 'aaaaa222bb'
```
[Answer]
# Ruby 73
```
gets.split(/(\d)(?!\d)/).each_slice(2){|s,i|s.chars.map{|c|$><<c*i.to_i}}
```
Tests: <http://ideone.com/L1fssb>
[Answer]
# JavaScript 112
```
alert(prompt().replace(/.*?\d+/g,function(m){for(i=n=m.length-1,o="";i--;){j=m[n];while(j--)o=m[i]+o}return o}))
```
[Answer]
# Python 2.7, 98 bytes
```
import re
print"".join(c*int(m[-1])for m in
re.findall(r".+?\d(?!\d)",raw_input())for c in m[:-1])
```
This just does a simple regex search for digits that aren't followed by a digit, and then does the string arithmetic on each group and joins them all back together.
[Answer]
# Julia, ~~105~~ ~~99~~ ~~95~~ 87 bytes
```
s->join([join([string(b)^(int(p[end])-48)for b=chop(p)])for p=matchall(r"\D*\d*\d",s)])
```
This creates an unnamed function that takes a string as input a returns a string. To call it, give it a name, e.g. `f=s->...`.
Two array comprehensions are used here, one nested within the other. The outer comprehension acts on each match of the input string against the regular expression `\D*\d*\d`. The inner comprehension repeats each character of the match according to the trailing digit. The elements of the inner array are joined into a string, so the outer array is an array of strings. These are joined and returned.
In Julia, strings can be treated like character arrays. However, note that the `Char` and `String` types in Julia don't have the same methods defined; in particular, there is no method for repetition using `^` for characters. This uses a convoluted workaround:
* Loop over the string omitting the last character, which is removed using `chop()`.
* Convert the current character to a string using `string()`.
* Convert the trailing digit, which is also a character, into an integer. However, note that, for example, `int('4')` does not return 4. Rather, it returns the codepoint, which in this case is 52. Thus we can subtract 48 to get back the actual integer.
* Repeat `string(b)` according to `int(p[end]) - 48`.
Examples:
```
julia> f("ab3c5")
"aaabbbccccc"
julia> f("a0b3")
"bbb"
julia> f("13b1")
"111b"
```
[Answer]
# Python 3, ~~148~~ ~~144~~ ~~136~~ 135 Bytes
```
w,o,r,d=''.join,'',[],[]
for c in input()+' ':
if'/'<c<':':d+=[c]
elif d:o+=w(x*int(w(d))for x in r);r=[c];d=[]
else:r+=[c]
print(o)
```
*Thanks to Pietu1998 and mbomb007 for the suggestions.*
# Python 2, ~~161~~ ~~151~~ ~~147~~ ~~139~~ 138 Bytes
Maybe today's just been a long day at work, but I can't for the life of me figure out how to golf this..
```
w,o,r,d=''.join,'',[],[]
for c in raw_input()+' ':
if'/'<c<':':d+=[c]
elif d:o+=w(x*int(w(d))for x in r);r=[c];d=[]
else:r+=[c]
print o
```
[Answer]
# Java 7, 175 bytes
```
String c(String s){String r="",a[];for(String x:s.split("(?<=(\\d)(?!\\d))")){a=x.split("");for(int i=0,j,l=a.length-1;i<l;i++)for(j=0;j++<new Short(a[l]);r+=a[i]);}return r;}
```
The challenge is harder than it looks, imo..
**Ungolfed & test code:**
[Try it here.](https://ideone.com/23ghQx)
```
class M{
static String c(String s){
String r = "",
a[];
for(String x : s.split("(?<=(\\d)(?!\\d))")){
a = x.split("");
for(int i = 0, j, l = a.length-1; i < l; i++){
for(j = 0; j++ < new Short(a[l]); r += a[i]);
}
}
return r;
}
public static void main(String[] a){
System.out.println(c("ab3c5"));
System.out.println(c("a0b3"));
System.out.println(c("13b1"));
System.out.println(c("a13b1"));
System.out.println(c("a123b1"));
System.out.println(c("aa2a1b1"));
System.out.println(c("123"));
}
}
```
**Output:**
```
aaabbbccccc
bbb
111b
aaa111b
aaa111222b
aaaaab
111222
```
]
|
[Question]
[
What general tips do you have for golfing in Whitespace? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to Whitespace (e.g. "remove comments" is not an answer).
Please post one tip per answer.
[Answer]
I'm not entirely sure whether this is a joke question or not, so I hope I don't get mocked for taking it seriously, but...
# Tip 1: Don't End Your Program
The spec says that a program should be ended by three line-feeds, `[LF][LF][LF]`, where the first is the flow control IMP, and the next two are the quit command, but many interpreters will just run your code without the proper ending. Saves you 3 characters in any program.
[Answer]
# Tip 2: Use The Heap As Little As Possible
I used to use the Heap a lot for counting my loops and such, but realised it was actually extremely inefficient; first pushing an address, getting the current count, taking/adding one, re-pushing address, etc.
Now I just push a value on the stack to act as loop counter, then use the `[Space][LF][Tab]` swap command to get back to it when I need it. It takes a lot of working in/around, but when you get it it can really reduce your char count.
[Answer]
# Lower all characters by a fixed amount and add that right before printing in a loop
Credit to [*@LukStorms*](https://codegolf.stackexchange.com/users/42827/lukstorms), who uses a similar approach in [his answer for the Hello World challenge](https://codegolf.stackexchange.com/a/55447/52210).
*(`STN` used for Space, Tab, and New-line respectively.)*
Pushing the values for letters is always 11 bytes (i.e. pushing the value 65 for the character 'A' is `SSSTSSSSSTN`; pushing the value 122 for the character 'z' is `SSSTTTTSTSN`). When you want to output large amount of text this can be expensive. Instead, you can lower the values of all the characters you want to print by a fixed amount, and then in the loop to print them add this fixed amount.
This can be done with the following code (let's assume the fixed value is 100 in this case):
1. Push all values for the characters (minus the fixed amount 100) in reverse order
2. `NSSN` (Create a Label\_0; basically starting the loop)
1. `SSSTTSSTSSN` (Push the fixed amount 100)
2. `TSSS` (Add the top two values of the stack together)
3. `TNSS` (Pop and print the now correct value as character)
4. `NSNN` (Jump to Label\_0; go to the next iteration of the loop)
This will stop the program with an error ([which is allowed according to the meta](https://codegolf.meta.stackexchange.com/a/4781/52210)) as soon as it tries to do the Add (`TSSS`) with nothing more on the stack. [I've used this to golf this answer of mine](https://codegolf.stackexchange.com/questions/157684/left-hand-vs-right-hand-typists-challenge/157709#157709) (see items 5 and 6 of *Things I did to lower the byte-count*).
Whether a fixed amount of 100 is the shortest approach depends on what you are printing. *@LukStorm* for example used 107 in his Hello World answer.
Note that copying the top value (`SNS`) for two of the same adjacent characters (like the `l` in `Hello`), or [copying values from another position](https://codegolf.stackexchange.com/a/158230/52210) can still be used in addition to this to golf more bytes.
[Answer]
# Jumping to undefined labels ends the program (in some interpreters)
This starts to get into implementation specific behaviour, but I believe [this is allowed](https://codegolf.stackexchange.com/a/117890/65654).
TIO (and possibly other interpreters? doesn't work on ideone at least) will stop execution when an attempt is made to jump to a label that doesn't exist. If you need to do a comparison to break out of a loop this allows you to save bytes by not declaring the break label. (See [my comment on Print Invisible Text](https://codegolf.stackexchange.com/questions/122703/print-invisible-text?noredirect=1&lq=1#comment302239_122746) for an example.)
[Answer]
# Use arbitrary heap addresses
Many interpreters allow you to read/write to arbitrary heap addresses instead of starting at 0 or 1 and counting up. You can duplicate an existing stack value (3 bytes) to use as an address instead of pushing a new value (minimum 4 bytes)
[Answer]
# The empty sequence is a valid label
`[LF][Space][Space][LF]` (Flow Control - Mark with the label '') creates an empty label that is a valid target for jumps or subroutine calls. This saves a byte when declaring the label and a byte every time it is called.
([Observed in the whitespace answer for implement a truth machine](https://codegolf.stackexchange.com/a/62904))
[Answer]
# The value 0 can be declared as a number with no binary digits
The whitespace tutorial mentions that numbers can be any number of bits/binary digits wide. This means a number with no bits (beyond the required sign bit) is a valid representation of the value 0. `[Space][Space][Space][LF]` and `[Space][Space][Space][Space][LF]` both push the value 0 to the stack but the former is one byte shorter.
[Answer]
# Copying previous integers can be shorter than creating new ones
*(`STN` used for Space, Tab, and New-line respectively.)*
`STS` + Number argument can be used to [*Copy the* n*th item on the stack (given by the argument) onto the top of the stack*](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php). This can in some cases be used to save bytes.
For example, in [this answer of mine](https://codegolf.stackexchange.com/questions/157684/left-hand-vs-right-hand-typists-challenge/157709#157709) I explained in the 4th item of *Things I did to lower the byte-count* how copying the 1st (0-indexed) value (`STSSTN`) is shorter than pushing 12 to create the character 'p' (`SSSTTSSN`) in the part `"pop"` of the output. (NOTE: I use the value 12 instead of 112 for the character 'p', because I've applied [this other tip of lowering all values by a fixed amount, which we add before printing the characters in the loop](https://codegolf.stackexchange.com/a/158232/52210).)
]
|
[Question]
[
## Background
We define a **circular step sequence** of order \$n\$ as follows:
$$
a\_1, a\_2, \dots, a\_n = \text{Permutation of } 1 \dots n \\
b\_i = \min ( |a\_{i+1} - a\_i|, n-|a\_{i+1} - a\_i| ), 1 \le i < n \\
\text{Circular step sequence} \stackrel{\text{def}}{=} b\_1, b\_2, \dots, b\_{n-1}
$$
Informally, it is the \$n-1\$ distances between \$n\$ points evenly spaced on a circle, given a permutation of those points.
For example, if we choose a permutation \$1, 3, 6, 2, 4, 5 \$ for \$n = 6\$, we get a circular step sequence of \$2, 3, 2, 2, 1\$. (Refer to the circular layout below.)
```
1 2
6 3
5 4
```
On the other hand, a circular step sequence of order 6 cannot have a substring of \$2, 2, 2\$. Regardless of where you start and in which direction you go first, you'll get stuck at the third 2.
## Task
Given the value of \$n\$ and a sequence \$b\_1, b\_2, \dots, b\_{n-1}\$ of positive integers, determine if the given sequence can be a circular step sequence of order \$n\$, i.e. there exists a permutation \$a\_1, \dots, a\_n\$ which leads to the given sequence \$b\$.
## Input and output
The elements \$b\_i\$ of the input sequence are guaranteed to satisfy \$ 1 \le b\_i \le n/2 \$ and \$ b\_i \in \mathbb{Z}^+ \$. Also, you can assume \$n \ge 1\$. If \$ n = 1 \$, the only possible \$b\$ is a zero-length sequence. You can omit the number \$n\$ from the input.
For output, you can use truthy/falsy values for your language (swapping is allowed). If such a convention is not defined, you can use two distinct values to represent true/false respectively.
## Scoring and winning criterion
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code measured in bytes wins.
## Test cases
### True
```
1, [] # permutation: [1]
2, [1] # permutation: [1, 2]
3, [1, 1] # permutation: [1, 2, 3]
4, [1, 1, 1] # permutation: [1, 2, 3, 4]
4, [1, 2, 1] # permutation: [1, 2, 4, 3]
4, [2, 1, 2] # permutation: [1, 3, 2, 4]
5, [1, 2, 2, 1] # permutation: [1, 2, 5, 3, 4]
6, [2, 3, 2, 2, 1] # permutation: [1, 3, 6, 2, 4, 5]
```
### False
```
4, [2, 2, 1]
5, [2, 2, 1, 1]
6, [1, 2, 2, 2, 3]
6, [3, 2, 1, 1, 2]
7, [2, 2, 3, 1, 2, 2]
```
[Answer]
# JavaScript (ES7), ~~99 79 74~~ 72 bytes
Takes input as `(n)(b)`. Returns a Boolean value.
```
n=>g=([d,...b],x=0,m=2**n-2)=>d?[x+d,x-d+n].some(y=>g(b,y%=n,m^1<<y)):!m
```
[Try it online!](https://tio.run/##fY9NDoIwFIT3nkIXhlZKI8WfxFjceQJ3FROkiBpojaCB01cUgiLV7Xwzb96c/bufBtfTJbOE5KE6UCWoG1HAOMIY7z2U0zFKKBmNhEUgdfmK5SZHucVN4eFUJiEoygDYo2JIBUp29nJZQLgYJCqQIpVxiGMZAYNtrrfsWHgG7H3qB2BDwDz4rZJStbuy85RRX0MmNfkHyU9IXknShdMmqQ/PqrDTsrQ8xlawtR@nmul1s/7y9A1/NjefPV/QW5zmhHbfvGlxKkvlUg8 "JavaScript (Node.js) – Try It Online")
### How?
Instead of using an array for \$a\_i\$, we use a bitmask \$m\$ initialized to \$2^n-2\$ and a bit pointer \$x\$ initialized to \$0\$ (i.e. pointing to the least significant bit).
For instance: for \$n=4\$, we start with \$m=4^2-2=14=1110\_2\$. Because the LSB is our starting position, it is cleared right away to mark it as visited.
The main part of the code is a recursive search in a binary tree: for each \$b\_i\$, we move the bit pointer to either \$x+b\_i\$ or \$x-b\_i\$ (wrapping around modulo \$n\$) and toggle the bit at the new position in \$m\$.
We have \$m=0\$ on a leaf node iff all positions have been reached exactly once.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
Œ!Iæ%H{Aċ
```
[Try it online!](https://tio.run/##y0rNyan8///oJEXPw8tUPaodj3T/f7hzn/WjhjkKunYKjxrmWh9ers91uP1R05rI//@juaINdaJjY3W4oo10og3BDGMgQwfCNAEzkTlGCA6QqWME5phCZGByZiA5YyQBsGIYxxTKQSiG6AVqgQkYQ@ShpptDNBjrgNXFxnLF/jf7D7cAAA "Jelly – Try It Online")
A dyadic link taking \$n\$ as its left argument and the input sequence \$b\$ as its right argument. Returns a truthy value (positive integer) for True and a falsy value (zero) for False.
## Explanation
```
Œ! | Permutations of 1..n
I | Differences (vectorises)
æ%H{ | Symmetric mod half of n (for n=6, [-5,-4,-3,-2,-1,0,1,2,3,4,5] will map to [1,2,3,-2,-1,0,1,2,3,-2,-1])
A | Absolute
ċ | Count occurrences of b
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~28~~ 26 [bytes](https://github.com/abrudz/SBCS)
```
⊣∊⊣{≢∪⍺|+\⍵}¨⊂⍤,ׯ1*2⍳⍤⍴⍨⊣
```
[Try it online!](https://tio.run/##lZCxTsMwEIZ3P0W2NpAojUPhAVhgpYwslVBZKsGK0jCAVAVLrmCgZWEhlYgqpA7QhTF5k3uR8J/tVhULEDm@u//@@yy7fzUMz6/7w8uLhvSLl1JeRpS/RVUZtEndkv4gvfIpV1WJZLR7VpWsdwLSX349i0NZz6wpkpn4iYCcMSV/Np45qcKiVDGC2Gacb46ZBw4mnVN/kmafYRokPKjbjN6mOZDvM/ZXUgcTGLCk@9cN6OZ/GHv0NghXzBd/h4h6SuOHFK@I5dl/hcUhaxxeFalBL9DH03PLgOspuNUy3mEsQGtqMwCT9ITUXbVMaPxIk6feyaGHcHp03GtibwD@u5CIsUh4R9yzcZNJl0nORddprO4bNXFVK@Sv5bysdNeZ89o5TJgqsR0wD5wvsQ7xDQ "APL (Dyalog Unicode) – Try It Online")
TIO is only on 17.1, so I've implemented the `⍤` operator from 18.0 manually. Takes \$n\$ as the left argument, and the sequence as the right.
### Explanation
```
¯1*2⍳⍤⍴⍨⊣ ⍝ Get all possible combinations of ¯1 1 with length n
⊂⍤,× ⍝ Multiply it by n concatenated with the array (it doesn't matter what the starting value is)
⊣{ }¨ ⍝ Map each to
+\⍵ ⍝ The cumulative sum
⍺| ⍝ Modulo n
≢∪ ⍝ Then get the number of unique values
⊣∊ ⍝ Is one of these n?
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 84 bytes
```
(y=#;!FreeQ[(x=#;Abs[#-#2]&@@@Array[x[[{#,#+1}]]&,y-1])&/@Permutations@Range@y,#2])&
```
[Try it online!](https://tio.run/##bY49C8IwFEV3f4USKC2mSBKrgxTSxbm6hgxRQu3QCmmEhtLfHmMj0g@3dw/3Hl4l9ENWQpd3YYvUhiYFp81ZSXlhYevu7NYwEAPMA0ppppQwrGWsAxBsUc95AE2MeBTsaC5V9dJO9KwbehV1IamBbhcFNldlrde0YAh2PV/9IoYdGmfiMpyQ/UD@MLxgjkA8ZonvzZqHT5Ms@WCYseTLFgbvdZ4ZJ749/ePoLQQOq55b@wY "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~90~~ 89 bytes
-1 thanks to FryAmTheEggman
```
f=lambda n,a,v=[0]:a and any(f(n,a[1:],[(v[0]+x*a[0])%n]+v)for x in(-1,1))or len({*v})==n
```
**[Try it online!](https://tio.run/##bZDdCoJAEIXve4q5CXdygna3PySfRLzYKCmoUUREiZ7dVle2rIRFzvcdD7JFW11y1vui7Losvpn78WSAyVAdJ6s0MmD4ZE8rMmFpIqOUElFbFTYLY1845zSsMctLaODKYilJItp0O7N4LOonxjF3vWYCYxsgZmAfIQmSFMkFZYP0SfeJ4A3WI/jD1DdTQ095tvG9SXXrqvrXjCMTtnmz7xG/3a9NjPYffP7Pzk9pZ0aJ0eCL8srVcNlgkCA4LAMCl7B7AQ "Python 3 – Try It Online")**
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), ~~11~~ 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Outputs `0` for `false` or an integer `>0` for `true`.
```
õ á Ëäa eV
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=9SDhIMvkYSBlVg&input=NApbMiwxLDJd)
```
õ á Ëäa eV :Implicit input of integer U & array V
õ :Range [1,U]
á :Permutations
Ë :Map
ä : Consecutive pairs
a : Reduced by absolute difference
eV : Is equal to V?
:Implicit output of sum of resulting array
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes
```
Lœ€üαD¹αÅLJIå
```
[Try it online!](https://tio.run/##AScA2P9vc2FiaWX//0zFk@KCrMO8zrFEwrnOscOFTEpJw6X//zYKMjMyMjE "05AB1E – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 100 bytes
```
f=lambda n,b,i=[0]:b and(f(n,b[1:],[(i[0]+b[0])%n]+i)+f(n,b[1:],[(i[0]-b[0])%n]+i))or len(set(i))==n
```
[Try it online!](https://tio.run/##Xc1dC4IwFAbg6/YrDkJwhivS9QHC/kV34sWkSQOdYrMPot9uM2tZuxi8z3nP1tzssTa87wtRyio/SDAsZ1qkqyzJQZoDFugkjZKMpagdh7m76Nxkoabh/3AxGdK6hVIZPCmLLglh@stRlwr2bacSMruCAG2aziIls6bVxqI6yxKDAu8PGiyLuq2kxSultI8YpBn8HBI7i36R8MEYTJms3zbhj8X/Fr96sbeN7/kq2Y49/uXP6hg23/DK2@kbw@JI3FeGD8nOb/GRBn0C "Python 3 – Try It Online")
Returns a non-zero integer (`n>1`) / True (`n==1`) for True and False for False.
**Explanation**
`i` is the list of visited numbers in reverse order. At each step of the recursion, we remove the first entry of `b`, move either forwards or backwards by the corresponding amount (modulo `n`) and append the new position at the 0th position of `i`. Terminates when `b=[]`, for which the function evaluates to True if `i` has exactly `n` distinct numbers and False otherwise.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~99 81~~ 71 bytes
```
f=->n,s,w=[0]{w[-n]||(a=s.pop)&&[a,-a].any?{|g|f[n,s,w|[(w[-1]+g)%n]]}}
```
[Try it online!](https://tio.run/##LcqxCoAgEADQva9oKYrOyGi1PuS4wQbbTJKQ8Px2i2p88I5zvXI2SswWPASFA8WAwhJzo5Xv3e7aukYNQlOv7bVE3tjgmxmbp0rqtrayRCllVxqcACWMIImKn@PHfAM "Ruby – Try It Online")
[Answer]
# [Python](https://docs.python.org/2/), 77 bytes
```
f=lambda n,l,m=1:all(f(n,l[1:],m<<d*l[0]|1)for d in[1,n-1])if l else m%~-2**n
```
[Try it online!](https://tio.run/##bY5NCoMwEIX3PUU2RSMT6MTaguhJQhYWDRWSKNZNofTqaTQUbOzyffN@ZnzO98Fy51StG3NrG2JBg6mxbLROVeqVwFKCqao20@IkX0jVMJGW9FYgWIaS9opo0ulHR8zxzXiWWTdOvZ19HEFISg9fyUHgVudeww85r@QP4zvmCfAtK4Ivcl4WZx7zhDGWRHVRsAhsXxdGfGnElxGMn7qGlhzWlL@4Dw "Python 2 – Try It Online")
Outputs True/False swapped.
The idea to store visited values as a bitmask is [from Arnauld](https://codegolf.stackexchange.com/a/200000/20260).
But, instead of storing our current position on the tape of bits and updating it after we move, we simply move the whole tape so that we're located at the end. We treat the tape as unrolled, so that every n-th position is the same, and we always move the tape left with `<<` by converting each rightwards move to an equivalent leftwards move modulo `n`.
In the end, we collapse the tape to its last `n` positions by taking the numerical value modulo `2**n-1`. The only way to get a result of zero is if every position modulo `n` was hit exactly once.
[Answer]
# [Scala](http://www.scala-lang.org/), ~~88~~ ~~82~~ 80 bytes
```
n=>d=>1.to(n).permutations.map(l=>(l.zip(l.tail)).map(_-_)map(_.abs))contains(d)
```
[Try it online!](https://tio.run/##dY/BSsQwEIbvfYocMxADTV2FQgp68@DJo8iSbROIZCd1E0UUn73GbLtrd7sQyPB9M/8koVVODX7zqttIHpVFoj@jxi6Qu77/Lj6UI0bU5AEjkQ150m/PqXz5q@@9d1ohkQPKppNNyaOnCLzXu@17VNF6DHyreupkQx3/sqniUVkHkPH6ag355moTAFqPSWKgHQydNsRQW6dVLNTTUpBGUAs0QFH0O4vRITW0ZMlTAPjHRGblHFZ7yE7w9YQvCbEsEmZiLlaHibOZm3GmOsqDnX1nCj9LWB3FcnjJiJhOtdRQZVXmc/Ly2zE8z@4bxp6f4Rc "Scala – Try It Online")
* -6 thanks to [user](https://codegolf.stackexchange.com/users/95792/user)!
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 29 bytes
```
{|/x=#'?'+x!+\-1 1[!x#2]*x,y}
```
[Try it online!](https://ngn.bitbucket.io/k/#eJxLs6qu0a+wVVa3V9euUNSO0TVUMIxWrFA2itWq0Kms5eIKsapWia6sK7JKU9BTqLBOyM+21khIS8zMsa6wrrQu0oyt5QqJ1jC0VjTQtDaMBbGNrA1hTGNroHEwjgmIg8o1QuYCOQpGMK4pWBZJ3gwob4wqBNIC5hpAtYC5CAEzqBlAjQghY4gakE0QIXOwNmMFsFqwIACLDz5E)
Takes `n` as `x` and `b` (the sequence) as `y`. A port of [@Jo King's APL answer](https://codegolf.stackexchange.com/a/211068/98547).
* `-1 1[!x#2]` generate all combinations of -1 and 1 with length `n`
* `*x,y` multiply these by `n` prepended to the sequence `b`
* `x!+\` take the column-wise cumulative sums, mod'ing them by `n`
* `+` transpose the result
* `#'?'` calculate the number of distinct values in each row
* `|/x=` are any of those equal to `n`?
[Answer]
# [Python 2](https://docs.python.org/2/), 101 bytes
```
lambda n,b:n in map(len,map(set,reduce(lambda Q,k:[q+[(q[-1]+v)%n]for q in Q for v in-k,k],b,[[0]])))
```
[Try it online!](https://tio.run/##XYvNCoJAFIX3PcWFCGbwCDlGC6GHcH2bheZIol5/MqGnn7RyExw4h4/v9K/p3onx5eXqm6zNi4wEeSJUCbVZrxonWPvhJoyueN6c@mkp6oSHgNXAYWSDWR/Elt1Iw3pNaZ3zMsMatUUO5qO1Wmvfj5VMVKoYHMFYvdvACWxgEP2jr7Xf2Bm0QIpB5pPF928 "Python 2 – Try It Online")
Returns `True`/`False` if b is/isn't a circular set sequence.
[Answer]
# [Python 3](https://docs.python.org/3/), 101 bytes
```
lambda n,a,r=range:n in(len({sum([a[j]*(k>>j&1or-1)for j in r(i)])%n for i in r(n)})for k in r(1<<n))
```
[Try it online!](https://tio.run/##bY7LDoIwEEX3fkU3SmvaRUE0McCPVBY1gpbHQCoujPHba6ExweLynjlzZ/rncOsgMmV6Mo1szxeJgEqqUy3hWhwBKcBNAfh1f7RYSFHlW1xnWbXhnWaclJ1GlXWQxorkZA1oJMoRIO9JqF3kSQKEmF4rGHCJORU5IatvDKng8xzZTH/IbiJ/WLhgltBwzmLneeZ@NCOfB4yxwKvzFmPHlnXuiC31@HiE@08dXEtEpy07MR8 "Python 3 – Try It Online")
[Answer]
# Python 3, ~~[120](https://tio.run/##jZHfasMgFMbvz1McKANtLDSmu5Hmdk@wO3EjMNMFjAmJgeTpM/M/ha6boB7158enX9m578JGff@lU0yJpQJwKG/EsDY@szzmx6M9cSoq7ZrKYmI74g9lKBTrXizLP0h4vRJfUkrTosIOMyvbwMizYu1pmAKraJaiQW1qjbZwmAPOcrf@gO9VowU4P346XbsaY5QgFcO7dsBSV3njEpcVVqAMFfjOnjMM@YAxvCMfYQyjmdzDv5AMLxPM/4YvkzIflfkzOJr4VXkTf6z8ujrhy@XpCiiAssqsIyarHYGUGG2JoUFI/YhDSsanhNuXA6UAB3xLfEIC0mHaZ7EpL@W8Wo2O/@c3ovV4fOzCR9PGGMc/ze1MeHf9Dw)~~ ~~[115](https://tio.run/##jZHNaoQwFIX39ykuSCEZM6BxupFx2yfoTtIiNJkKMYpG0Ke38d@B6bSBJDfJl8NJTtXb79JEw/AlFSpiaAw4ljeiWZcErEj46WTOnMa1tG1tMDM9cYdpGAvWvxhWfITXqyuoKmvsMTdp5@s0EKw7j5NvBM0VapS6kVgkSQC4KN0GD9/rVsZg3fhpZWMbTDCFVDC8ax5Wsi5am9m8NDGmoQDX2XOGIR8xhnfkI4xhtJBH@BeS4WWG@d/wZVbmkzJ/Bkczvynv4o@VXzcnfL08XwEBUNW5sUTnjSWgiJaGaOqH1I04hqRdSLh/OVAK4OFb5gKKQY3TMYtdeS2X1WZ0@j@3EW3H02NXPpo3pjj@ae5gwrkbfgA)~~ 90 bytes
```
f=lambda n,l,x=0,m=0:all(f(n,l[1:],y%n,m^1<<y%n)for y in[x+l[0],x-l[0]])if l else m-2**n+2
```
You can [try it online](https://tio.run/##jZHdaoQwEIXv8xQDUkjWWdC4eyPrbZ@gdyEtliZUiFE0C/r0Nur6s7DdVogTJ98cjjl1774rmwyDzkxefn7lYNFgl0VYZlGaG0M19R0RpxL7F4vle3y5@A3TVQM9FFZ0oRGRxO44FskKDQaUaRWUR3442JAPAbw1V5US598fTrWuhQwEERLh7gmgVk15dbkrKpuCiCXxC58zCHzEEO7IRxhCciP38C8kwmmG@d/waVbmkzJ/Biczvypv4o@Vz6sTvgzPI0QSUjeFddQUraNEU6MsNSz0c4bBGI7x4cB25YQxQgJ4zX00KdFj2WexKS/b29dqdLo/30jW4@lnFz6ZG1Mc/zS3M@HdDT8)! Outputs False for CSS and True otherwise.
This is a port of [Arnauld's answer](https://codegolf.stackexchange.com/a/200000/75323) (who saved me almost 20 bytes!). Go upvote his answer because it looks better than this one!
[Answer]
# [J](http://jsoftware.com/), ~~21~~ 17 bytes
```
e.2|@-/\"1!A.&i.]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/U/WMahx09WOUDBUd9dQy9WL/a3KlJmfkK6irK6QpGCogAYi4ho6VoSZQyghTyhAI0xSMsYiCxE1QBY0wBY3AwlhUQtSaIik0houaQZ2rq6sOk4QajcwF60c2EGQEUDPUQGOoIiOEgRAlEMVpCuZc/wE "J – Try It Online")
*-4 bytes thanks to Bubbler*
Literal translation of the question: Is the given list and element of `e.` the adjacent differences of every possible perm?
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 54 bytes
```
Or@@(0!=##&@@@Mod[Accumulate/@Tuples[{#,-#}&/@#2],#])&
```
[Try it online!](https://tio.run/##XY3LDoIwEEX3fAVmEqJJCdKKrjDjBxhduCMsGoRIAmqwrJp@e4Wi42N3z33MtFJdylaqupC2Su2hQ5wvZylAgIj72znbFUXf9o1UZYSn/t6Uj0wDC8EEEQLPGeSLwB67@qoGH0y4rRAgH9fa0zHztTHM03wQsVNiVMyfYPWCP@bfzF3OHSeUU2U9VcSPS0uqJR/@XtKx8QS5gorvxxuai8l1gWfsEw "Wolfram Language (Mathematica) – Try It Online")
See all possible permutations:
[Try it online!](https://tio.run/##XY27DoIwFIZ3ngJzEqYSoBWdMHV0MHHQqWEgCJGEi9EyNX32Wooe0aHJ//2X066Qt6orZFMWps7MpW@GXhxqEa8yAKJiAqDtC0SeB5zz43AV@7Icu7EtZBXx83hvq6dQQELQQcSB5gRs1ZweTS@tDzrc1RzArZWnEuIrrYmnqBWJU2xSxJ9h/YY/pkumLqeOU8yxspkr7MfFJdbSLy@XeGw6gS7D4ufjLc7Z7LrA0@YF "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~137~~ \$\cdots\$ ~~119~~ 118 bytes
Saved a byte thanks to [Surculose Sputum](https://codegolf.stackexchange.com/users/92237/surculose-sputum)!!!
```
lambda n,b:any(b==[min(i:=abs(a-b),n-i)for a,b in zip(p,p[1:])]for p in permutations(range(n)))
from itertools import*
```
[Try it online!](https://tio.run/##Xc1NbsIwEAXgNT7FiNW4MpUSF6gi5Rbs0ixs1SmW4h85ToFWPXsakxJCZzef3pvxl3h0lr/6MDTl29AKI98FWCYLYS8oy7Iy2qIuSiE7FBtJmd1o2rgAgknQFr60R898lRU1rZP7pF4F00cRtbMdBmE/FFpKKWmCM6CjCtG5tgNtvAvxaTgddavgEHpVkNUZyvGE7yNSsvJB24jqU7S4bvD7h66fxydGRDyP94aMQVXDw5B8tOwRCU/GYMnk5c8WfLP8v@XXXD7bds7NUbKbcvzOt@q0bO/Ldd8tb6TiRHyOpIdkP7f4REl/AQ "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 41 bytes
```
⬤EX²LθE⊕Lθ﹪∨ΣE…◧⍘ι²Lθλ×∨Σλ±¹§θμ⁰⊕Lθ⊙ι⊖№ιλ
```
[Try it online!](https://tio.run/##bU9BDoIwEPxKj9ukJoJHT4gXE1QSvBEODazQpLRSisrra0tiDImb3cvMZGa27ripNZfO5UYoC4mUcOYPyPULDcSMZKha28FAKSOBOKnaYI/KYgMrTjeT1HA1UEz9YpHOtcS0096MNxneLRz4iIX1OS0IRmK6dpf@bqLH8WsSgAu23CJEQZDYk2rwDQMjPaUB2fr7X2ihEzWHoCP@FKme/JcipIXZO1eWO9@FkWjZuKrc5ik/ "Charcoal – Try It Online") Link is to verbose version of code. Outputs `-` only if the input is *not* a circular step sequence. Explanation:
```
EX²Lθ
```
Outer loop to `2ⁿ⁻¹` (exclusive).
```
E⊕Lθ
```
Inner loop to `n` (exclusive)
```
…◧⍘ι²Lθλ
```
Convert the outer loop index to binary with `n-1` digits, but only take the first inner loop index bits.
```
E...×∨Σλ±¹§θμ
```
Replace the `1` bits with the values from the input and the `0` bits with the negated values respectively.
```
﹪∨Σ...⁰⊕Lθ
```
Take the sum modulo `n`. Because only the first inner loop index bits were used, each result takes one more bit into account, resulting in a list of the partial sums of the possibly negated values.
```
⬤...⊙ι⊖№ιλ
```
Check that all resulting lists contain duplicate elements. This will be true if the input is *not* a circular step sequence.
]
|
[Question]
[
Output the following result (which is a result of calculating 6 \* 9 in bases from 2 to 36). Make sure letters are uppercase, and the multiplication itself is outputed on every line.
```
6 * 9 = 110110
6 * 9 = 2000
6 * 9 = 312
6 * 9 = 204
6 * 9 = 130
6 * 9 = 105
6 * 9 = 66
6 * 9 = 60
6 * 9 = 54
6 * 9 = 4A
6 * 9 = 46
6 * 9 = 42
6 * 9 = 3C
6 * 9 = 39
6 * 9 = 36
6 * 9 = 33
6 * 9 = 30
6 * 9 = 2G
6 * 9 = 2E
6 * 9 = 2C
6 * 9 = 2A
6 * 9 = 28
6 * 9 = 26
6 * 9 = 24
6 * 9 = 22
6 * 9 = 20
6 * 9 = 1Q
6 * 9 = 1P
6 * 9 = 1O
6 * 9 = 1N
6 * 9 = 1M
6 * 9 = 1L
6 * 9 = 1K
6 * 9 = 1J
6 * 9 = 1I
```
Shortest code wins.
[Answer]
### GolfScript, 39 characters
```
35,{2+'6 * 9 = '54@base{.9>7*+48+}%n+}/
```
Result can be seen [here](http://golfscript.apphb.com/?c=MzUsezIrJzYgKiA5ID0gJzU0QGJhc2V7Ljk%2BNyorNDgrfSVuK30v&run=true).
[Answer]
## Octave, 49
`for i=2:36printf("6 * 9 = %s\n",dec2base(54,i))end`
[Answer]
# Javascript, ~~57~~ 55 bytes
```
for(i=2;++i<37;)console.log('6 * 9 = '+54..toString(i))
```
Could be shortened to 49 with `alert`, but I don't want to submit anyone to that...
[Answer]
# Ruby (47)
```
2.upto(36){|t|puts"9 * 6 = "+54.to_s(t).upcase}
```
Well, I know that GolfScript solution is better, but hey, at least this is not esoteric...
[Answer]
## Python, 89
```
B=lambda x:x*'.'and B(x/b)+chr(x%b+7*(x%b>9)+48)
b=2
while b<37:print'6 * 9 =',B(54);b+=1
```
[Answer]
**Python 2.7 (~~124~~ 114)**
EDIT: Cut some fluff thanks to @boothby's comment below
I think Python is doing ok considering it has no built-in (that I know of) to do the base conversion so it has to be done in code;
```
for b in range(2,37):print'6 * 9 = '+''.join(chr((54/b**y%b>9)*7+48+54/b**y%b)for y in range(4,-1,-1)).lstrip('0')
```
[Answer]
# [Perl 6](http://perl6.org/), 36 bytes
```
say '6 * 9 = ',54.base($_) for 2..36
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~21~~ 20 bytes
```
36G54N>B"6 * 9 = ÿ",
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f2Mzd1MTPzknJTEFLwVLBVuHwfiWd//8B "05AB1E – Try It Online")
[Answer]
# Mathematica 40
Not in contention (lower case letters used):
```
Print["6*9 = ",54~BaseForm~#]&/@2~Range~36
```

[Answer]
**Perl**
Had to use the Math::BaseCnv module
35 chars without the `use` statement:
```
map{say"6 * 9 = ",cnv(54,$_)}2..36
```
54 chars with the `use` statement:
```
use Math::BaseCnv;
map{say"6 * 9 = ",cnv(54,$_)}2..36
```
Not sure how you'd score this, so both are included.
The map BLOCK LIST structure was used. List is the range 2 to 36, that was requested. The meat is in the `cnv($NUMBER, $BASE)` function, and the map is an implied loop.
[Answer]
# J - ~~78~~ 70
```
'6 * 9 = ',"1>;/(a.#~48 10 7 26 165#0 1 0 1 0){~<&.>(2+i.35)#.inv&.>54
```
# Haskell - 137
```
let s=['0'..'9']++['A'..'Z'];t _(0,r)=[s!!r];t b(q,r)=(t b$b q)++[s!!r]in mapM_(putStrLn.("6 * 9 = "++).(\b->t b$b 54).flip divMod)[2..36]
```
[Answer]
**CoffeeScript 71**
```
alert ("6 * 9 = "+59.toString(x).toUpperCase()for x in[2..36]).join "\n"
```
[Link](http://tinyurl.com/oeq8xby)
[Answer]
## C (166 151)
Got rid of some unnecessary characters and changed some declarations. Assumes that you are running the program with no arguments.
```
p[7],i,l,v,r;main(b){for(r=2;r<37;r++){b++;printf("6 * 9 = ");v=54;while(v>0)l=v%b,p[i++]=l>9?l+55:l+48,v/=b;while(i^0)printf("%c",p[--i]);puts("");}}
```
[Answer]
## Clojure, 75
`(for[i(range 2 37)](println"6 * 9 ="(.toUpperCase(Integer/toString 54 i))))`
[Answer]
# Python 3, 83 bytes
```
import numpy;print('\n'.join('6 * 9 = '+numpy.base_repr(54,i)for i in range(2,37)))
```
[Answer]
# Dart, 75 bytes
```
for(int x=2;x<37;x++)print("6 * 9 = ${54.toRadixString(x).toUpperCase()}");
```
Dart is a bit verbose when it comes to the stdlib, but hey... at least you can read it :P
[Answer]
# [Julia 0.6](http://julialang.org/), 60 bytes
```
for b=2:36;@printf("6 * 9 = %s\n",uppercase(base(b,54)));end
```
[Try it online!](https://tio.run/##yyrNyUw0@/8/Lb9IIcnWyMrYzNqhoCgzryRNQ8lMQUvBUsFWQbU4Jk9Jp7SgILUoObE4VSMJTOiYmmhqalqn5qX8/w8A "Julia 0.6 – Try It Online")
Pretty painless, apart from remembering to use the macro @printf versus printf.
Import Base; not needed ...
[Answer]
## Scala, 71
```
2 to 36 map(i=>println("6 * 9 = "+Integer.toString(54,i).toUpperCase))
```
[Answer]
Common Lisp: 56 characters
```
(do((b 2(1+ b)))((> b 36))(format t"6 * 9 = ~vr~%"b 54))
```
[Answer]
## Sage, 48:
Shame Sage prints in lowercase... I'd only be one over Howard. Or, I guess, wrong and tied with David Carraher.
```
for i in[2..36]:print'6 * 9 =',54.str(i).upper()
```
[Answer]
## Forth, 54
```
: f 54 37 2 do ." 6 * 9 = " dup i base ! . cr loop ; f
```
[Answer]
# [///](//esolangs.org/wiki////), 133 bytes
```
/R/6 * 9 = //S/
R/R110110S2000S312S204S130S105S66S60S54S4AS46S42S3CS39S36S33S30S2GS2ES2CS2AS28S26S24S22S20S1QS1PS1OS1NS1MS1LS1KS1JS1I
```
[Try it online!](//slashes.tryitonline.net#code=L1IvNiAqIDkgPSAvL1MvClIvUjExMDExMFMyMDAwUzMxMlMyMDRTMTMwUzEwNVM2NlM2MFM1NFM0QVM0NlM0MlMzQ1MzOVMzNlMzM1MzMFMyR1MyRVMyQ1MyQVMyOFMyNlMyNFMyMlMyMFMxUVMxUFMxT1MxTlMxTVMxTFMxS1MxSlMxSQ)
[Answer]
# SpecBAS - 48 bytes
```
1 FOR i=2 TO 36: ?"6 * 9 = ";BASE$(54,i): NEXT i
```
SpecBAS is actually quite competitive for a change :-)
[Answer]
# [8th](http://8th-dev.com/), ~~65~~ 62 bytes
This is a complete program. Exit after execution
```
( "6 * 9 = " . #54 swap base drop >s s:uc . cr ) 2 36 loop bye
```
**Explanation**
```
(
"6 * 9 = " . \ Print the first part of the formula
#54 swap base \ Enter into the base provided by loop index and
\ convert 54 (which is always expressed in base 10)
drop \ Get rid of previous base
>s s:uc \ Convert number into an upper case string
. cr \ Print result and newline
) 2 36 loop \ Provide base from 2 to 36
bye \ Quit
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2) `rRMj`, 119 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 14.875 bytes
```
34ƛ⇧54R`6*9=`ṄðpJ
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyJyUk1qPSIsIiIsIjM0xpvih6c1NFJgNio5PWDhuYTDsHBKIiwiIiwiIl0=)
Bitstring:
```
01001000111011011000001000111100010001001111010001100010011111010011011001011001000000010100011011001000011111011100011
```
so many flags
```
34ƛ⇧54R`6*9=`ṄðpJ­⁡​‎‏​⁢⁠⁡‌⁢​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁤‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏‏​⁡⁠⁡‌⁢⁣​‎‏​⁢⁠⁡‌­
# ‎⁡R flag casts numbers to ranges
# ‎⁡M flag starts implicit ranges at 0
# The r flag reverses the arguments which makes the base conversion easier
34ƛ # ‎⁢map over the range 0-34
⇧ # ‎⁣add 2, giving a range 2-36
54R # ‎⁤Convert 54 to base B
`6*9=`Ṅ # ‎⁢⁡separate the multiplication by spaces
ðpJ # ‎⁢⁢add a space, and append the converted base
# -j flag joins output on newlines
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [Julia 1.0](http://julialang.org/), 59 bytes
```
2:36 .|>b->println("6 * 9 = ",uppercase(string(54,base=b)))
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/38jK2ExBr8YuSdeuoCgzryQnT0PJTEFLwVLBVkFJp7SgILUoObE4VaO4BCibrmFqopME5NomaWpq/v8PAA "Julia 1.0 – Try It Online")
# [Julia 0.6](http://julialang.org/), 46 bytes
```
@.println("6 * 9 = ",uppercase(base(2:36,54)))
```
[Try it online!](https://tio.run/##yyrNyUw0@//fQa@gKDOvJCdPQ8lMQUvBUsFWQUmntKAgtSg5sThVIwlEGFkZm@mYmmhqav7/DwA "Julia 0.6 – Try It Online")
]
|
[Question]
[
*Inspired by [this video](https://www.youtube.com/watch?v=wdgULBpRoXk) by Ben Eater. This challenge forms a pair with [Decode USB packets](https://codegolf.stackexchange.com/q/229375).*
The USB 2.0 protocol uses, at a low level, a line code called [**non-return-to-zero**](https://en.wikipedia.org/wiki/Non-return-to-zero) encoding (specifically, a variant called [NRZI](https://en.wikipedia.org/wiki/Non-return-to-zero#Non-return-to-zero_inverted)), in which a stream of bits is encoded into a stream of two electrical level states `J` and `K`. Encoding works as follows:
* Start with some initial state, which is either `J` or `K`
* For each bit to be encoded:
+ If the bit is a 0, switch the state from `J` to `K` or from `K` to `J`
+ If the bit is a 1, maintain the same state as before
+ and output that state
For this challenge, we will assume the encoding starts in state `J`.
However, it's not that simple: an additional process called [**bit stuffing**](https://en.wikipedia.org/wiki/Bit_stuffing) takes place, which is designed to make it easier to detect if the signal has dropped out. After 6 consecutive `1`s are read, an extra meaningless `0` bit is processed to ensure the signal never stays in the same state (`J` or `K`) for too long.
The full USB specification is available [here](https://usb.org/document-library/usb-20-specification) on the USB website, or mirrored (and easier to access) [here](https://eater.net/downloads/usb_20.pdf), but I'd caution you before reading it because it's extremely long and the pertinent information is hard to pin down.
## Task
Given a non-empty binary string as input, encode the string using the USB implementation of NRZI described above, and output a string of `J`s or `K`s.
## Test-cases
```
Input Output
=====================================
1 J
0 K
1000101 JKJKKJJ
00000000 KJKJKJKJ
11111111 JJJJJJKKK
001111100 KJJJJJJKJ
0011111100 KJJJJJJJKJK
00111111100 KJJJJJJJKKJK
0011111111111100 KJJJJJJJKKKKKKKJKJ
0011011000111001 KJJJKKKJKJJJJKJJ
01101000011101000111010001110000011100110011101000101111001011110111011101110111011101110010111001111001011011110111010101110100011101010110001001100101001011100110001101101111011011010010111101110111011000010111010001100011011010000011111101110110001111010110010001010001011101110011010001110111001110010101011101100111010110000110001101010001 KKKJJKJKJJJJKKJKJJJJKKJKJJJJKJKJKKKKJKKKJKKKKJJKJKKJJJJJKJJKKKKKJJJJKKKKJJJJKKKKJJJJKKKKJKKJJJJKJJJJJKJJKKKJJJJJKKKKJJKKJJJJKKJKJJJJKKJJKKKJKJJKJJJKJJKKJKKJJJJKJJJKJKKKJJJKKKKKJJJKKKJJKJJKKKKKJJJJKKKKJJJKJKJJKKKKJJKJKKKJKJJJKKKJJKJKJKKKKKKKJKKKKJJJKJKKKKKJJKKKJKKJKJJKKJKJJKKKKJJJJKJJJKKJKJJJJKKKKJKKKKJKKJJKKJJJJKKKJKKKKJJKKKJKJKKKJKJJJKKJJKJKK
```
## Rules
* The input should be a string or array of `1`s and `0`s or of `true`s and `false`s
* The output should be a string or array, with the two states `J` and `K` being represented by any two distinct values
* You may use any [standard I/O method](https://codegolf.meta.stackexchange.com/q/2447)
* [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061) are forbidden
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins
[Answer]
# [Husk](https://github.com/barbuz/Husk), 11 bytes
```
G=Jḋ126xḋ63
```
[Try it online!](https://tio.run/##yygtzv7/qGGBRrK2ucmhNZq5j5oa/7vbej3c0W1oZFYBpMyM////Hx1tGKsTbQDEhjoGYAiiwWI6KBCsAgVC1SBEIKpQxXCJQsRjAQ "Husk – Try It Online")
Input as array of `0`s and `1`s, output as array of `1`s (for state `J`) and `0`s (for state `K`): TIO header converts to `J`s and `K`s.
```
x # split input on
ḋ63 # binary digits of 63 = [1,1,1,1,1,1]
J # then join back together using
ḋ126 # binary digits of 126 = [1,1,1,1,1,1,0]
G= # and scan from the left by equality
```
[Answer]
# JavaScript (ES6), 53 bytes
Expects a binary string. Returns an array of 0's and 1's.
```
s=>[...s.replace(/1{6}/g,'$&0')].map(q=c=>q^=c^!!++q)
```
[Try it online!](https://tio.run/##fY7LDoIwEEX3fgUQo23QdmbjrvyIkaSphWiQ8jBujN@OSFGhiLe76T0n9yxvslbVqbhuc3PUTSKaWkR7xljNKl1kUmnC8b578HSzXq5gTQ/sIgtSCiWiMhYq9v0wLGmjTF6bTLPMpCQhAQbeOJR6nHu4cHrwuwduDwEAYWDtfe0RcGrtEzhWtG8i7@PU7bHVTPX9T@Do7Rln@l9g1H9NmiM@iEP8Q96ci3SZWQddwZoHoAW6idg8AQ "JavaScript (Node.js) – Try It Online")
### Commented
This is a rather straightforward implementation in two steps.
```
s => // s = input string
// STEP 1 - Bit stuffing
//
[...s.replace( // replace in s:
/1{6}/g, // each group of six consecutive 1's
'$&0' // with the same group with a trailing 0
)] // split the resulting string
// STEP 2 - NRZI encoding
//
.map(q = // initialize q to a zero'ish, non-numeric value
c => // for each character c:
q ^= // invert q if ...
c ^ // ... c is not equal to the result of
!!++q // the test 'q is a number'
// (0 on the 1st iteration, 1 afterwards)
) // end of map()
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
7Ṭ¬©Ṗœṣ@j®⁼\
```
A monadic Link that accepts a list of integers (from \$[0,1]\$) and yields a list of integers (from \$[0,1]\$) where \$0\$ represents \$K\$.
**[Try it online!](https://tio.run/##y0rNyan8/9/84c41h9YcWvlw57Sjkx/uXOyQdWjdo8Y9Mf///4820FEAIkMiEEhlLAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/9/84c41h9YcWvlw57Sjkx/uXOyQdWjdo8Y9Mf8f7t5yaGvYo6Y1h9sf7u5@1LjPy1vHQdMbKBD5/78hlwGXoYGBgaEBkAUFXIZQABQB00AhKAuZicJGFgAhsIQByFAQ3wDKN0SjDeDqDJEkDCBmQWlc2ABGwTlI6g0M0eyDOQpqlQGyfgOYo6H6oU7GsN8A5jiouQh9MI@gqDWE2gw2CmqnAbL7kdwH878BktvhQQK1GWYfRBcA "Jelly – Try It Online").
### How?
```
7Ṭ¬©Ṗœṣ@j®⁼\ - Link: list of integers in [0..1], A
7 - seven
Ṭ - untruth -> [0,0,0,0,0,0,1]
¬ - logical NOT -> [1,1,1,1,1,1,0]
© - copy to register
Ṗ - pop -> [1,1,1,1,1,1]
œṣ@ - (A) split on sublists equal to (that)
® - recall from register
j - (split list) join (register value)
\ - cumulative reduce with:
⁼ - (left) equals (right)?
```
---
11 if we could take input with `0` meaning *true* and `1` meaning *false* with `7Ṭ©Ṗœṣ@j®⁻\`.
[Answer]
# [convey](http://xn--wxa.land/convey/), 31 bytes
Outputs `KJ` as `01`.
```
v|6
0"("=0
+*6!<}
""~,="
{ 5 1<
```
[Try it online!](https://xn--wxa.land/convey/run.html#eyJjIjoidnw2XG4wXCIoXCI9MFxuKyo2ITx9XG5cIlwifiw9XCJcbnsgNSAxPCIsInYiOjEsImkiOiIwIDAgMSAxIDEgMSAxIDEgMSAxIDEgMSAxIDEgMCAwIn0=)
In the top left is a counter that gets incremented by the input 1s `+` and reset whenever it reaches 6 `|6` or the input has a 0 `*`. If it reaches 6, it also injects a 0 into the stream (the `("=0 6!<` part). Because the input stream would be faster (the 0 would get there 2 bits too late), we delay it by 5 ticks `~5`. On the bottom right is the current output bit that gets flipped on 0s with `=` and then copied into the output `=}`.
[](https://i.stack.imgur.com/BkKrf.gif)
[Answer]
# [R](https://www.r-project.org/), 59 bytes
```
function(x)cumsum(49-utf8ToInt(gsub('(1{6})','\\10',x)))%%2
```
[Try it online!](https://tio.run/##dVLLasMwELznKwIlSIIUZksp7aEf0HuPgULcpPQQG2oLAqXf7sbW7mqlOA5BsTSvHeVnjP3@49A23efhdTzGthm@u9afQxNPfTz5x5f7OByf37u3dvBffdx75@n36S@4rdvtCG57DiFsNg9GxztyYX23rh@sLAaLGCowBIBQq01bl5NSjZ8SSkifUpSfEprol@1KdoZWusRgLGErMGOnGIvoEq7om/CCk@FpeyHRXBVmDmVSAs@xKooe8A@7QpXIHCAl4vXWF7Loi8GDKj@JzVawfMhYzOfIV/6QcKybeaazjOUCkx97wuY3@WR@mOxaCTuLX2Jx9ToNTNFyE@UE0hKkBxLhhVWmzWBkDNV@UkquOPN5OvXjIFf@hOIyzZ9EBslzyIa0B61TRYuA5m41vHZCVN3q9LYa/wE "R – Try It Online")
Regex-based bit-stuffing ~~stolen from~~ inspired by [pajonk's R answer](https://codegolf.stackexchange.com/a/229384/95126) to the paired usb-decoding challenge.
The state-switching is achieved here by determining whether the cumulative sum is odd or even.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 16 bytes
```
\16*:0+V1$(nɽ߬…
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%5C16*%3A0%2BV1%24%28n%C9%BD%C3%9F%C2%AC%E2%80%A6&inputs=%2711111111%27&header=&footer=)
```
\16* # Six ones
:0+ # Duplicate and append a 0
V # Replace in input
1$ # Starting with a one
( # Iterating through the string
߬ # Flip if...
nɽ # It's a 1
… # Print without popping
```
Returns 1 for J and 0 for K. [Here](http://lyxal.pythonanywhere.com?flags=&code=%5C16*%3A0%2BV1%24%28n%C9%BD%C3%9F%C2%AC%3A%60KJ%60%24i%E2%82%B4&inputs=%2711111111%27&header=&footer=)'s a version that does JKs.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
“?~‘Bœṣjƭƒ^¬¥\
```
[Try it online!](https://tio.run/##y0rNyan8//9Rwxz7ukcNM5yOTn64c3HWsbXHJsUdWnNoacz/sEdNaw63P9zd/ahxn5f3//9KBoaGBoYGQGAIZSDTMHEDCIZKgFiGcBoXNoBRcA6SegNDNPvA8iBlBlDVSPrBipD0Q52MYb8BzHFQcxH6YB5BUWsItRlsFNROA2T3I7kP5n8DJLfDgwRqM8w@iC4lAA "Jelly – Try It Online")
-2 bytes thanks to Nick Kennedy
```
“?~‘Bœṣjƭƒ^¬¥\ Main Link; accepts a list of [0, 1] on the left
“?~‘ 63, 126
B To binary ([1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 0])
ƒ Reduce starting with the input:
ƭ Tie; cycle
œṣ The first time, split on sublist ([1, 1, 1, 1, 1, 1])
j The second time, join on [1, 1, 1, 1, 1, 1, 0]
\ Cumulative reduce
^´ Each time, XOR, and then logical NOT
```
[Answer]
## [<>^v](https://github.com/Astroide/---v#v), 161 bytes
```
1±n"0"o"1"i0q.h"J"j"K"kJtv
v v=ICc®NHn)N v=N-?1¿H<
>Q)7=v_qv >`! ~
vcOn(Nq0< v >Ktv T
v< <>TJ=^Jtv ^
>C O=^ > ^
```
#### Explanation
##### First line
```
1±n"0"o"1"i0q.h"J"j"K"kJtv
1 Push 1 to stack
± Negate
n Store in variable `n`
"0" Push "0"
o Store in variable `o`
"1" Push "1"
i Store in variable `i`
0 Push 0
q Store in variable `q`
. Read line from stdin
h Store in variable `h`
"J" Push "J"
j Store in variable `j`
"K" Push "K"
k Store in variable `k`
J Push value of variable `j` ("J")
t Store in variable `t`
v Redirect instruction pointer down
```
The variables `i` and `o` store the values `"1"` and `"0"`", `j` and `k` store `"J"` and `"K"`. `h` contains the line read from stdin (1's and 0's). `q`, initialized to 0, will be used for bit stuffing. `n` is the "current character pointer".
##### The main loop
```
v v=ICc®NHn)N v=N-?1¿H< <-- loop starts here
>Q)7=v_qv >`! ~
vcOn(Nq0< v >Ktv T
v< <>TJ=^Jtv ^
>C O=^ > ^
[start of loop]
< Send instruction pointer leftward
H Push value of variable `h` to stack
¿ Push length of top of stack
1 Push 1
? Swap top two elements
- Substract second element of stack to top of stack
N Push value of variable `n`
= If the top two elements of the stack (length of `h` - 1 and `n`) are equal (reached end of string)
v Send instruction pointer down
> Send instruction pointer right
` Print newline
! Exit
N Push value of variable `n` (character index in string)
) Increment top of stack (increment character index in string)
n Pop and write to variable `n`
H Push value of variable `h` (string that was previously read from stdin and that contains the 0's and 1's
N Push value of variable `n`
® Set top of stack to (second element of stack)[top of stack] (character read)
c Write to variable `c` ("current")
C Push value of variable `c` (variable write pops the stack)
I Push value of variable `i` ("1")
= If the top two elements of the stack (current character and "1") are equal
v Send instruction pointer down
> Send instruction pointer right
Q Push value of variable `q`
) Increment top of stack
7 Push 7
= If the top two elements of the stack are equal (`q` and 7)
v Send the instruction pointer down
< Send the instruction pointer left
0 Push 0
q Pop stack and write to variable `q`
N Push value of variable `n`
( Decrement top of stack
n Pop stack and write to variable `n`
O Push value of variable `o` ("0")
c Pop stack and write to variable `c` (current character)
v Send instruction pointer down
< Send instruction pointer left
Go to [loop-continuation]
Else
_ Pop stack (remove the 7)
q Pop stack and write to variable `q`
v Send instruction pointer down
v Same as previous, only for readability
< Send instruction pointer left
< Same
Go to [loop-continuation]
[loop-continuation]
Else
v. Send instruction pointer down
v. Same
>. Send instruction pointer right
C. Push value of variable `c` to stack (current character)
O. Push value of variable `O` ("0")
=. If the top two elements of the stack (current character and "0") are equal
^ Send instruction pointer up
>. Send instruction pointer right
T. Push to stack value of variable `t` (current state, J or K)
J. Push to stack value of variable `j` ("J")
= If the top two elements of the stack (current state and "J" are equal)
^. Send instruction pointer up
>. Send instruction pointer left
K. Push value of variable `k` ("K")
t. Pop stack and write to variable `t`
v. Send instruction pointer down
Continue at the [here] indicator
Else
J Push value of variable `j` ("J")
t. Pop stack and write to variable `t`
v. Send instruction pointer down
Continue at the [here] indicator
[here]
>. Send instruction pointer right
^. Send instruction pointer up
^. Same
T. Push value of variable `t` ("J" or "K")
~. Print top of stack without newline
Go to [start of loop] indicator
```
That can be clarified to :
```
while has not reached end of string:
increment character_index
current_character = string[character_index]
if current_character is a 1:
increment one_count
if one_count is 7:
set one_count to zero
decrement character_index
current_character = 0
if current_character is a 0:
if state is J:
state = K
else:
state = J
print state
print newline
exit
```
[run online - largest input](https://v.astroide.repl.co/?i=MDExMDEwMDAwMTExMDEwMDAxMTEwMTAwMDExMTAwMDAwMTExMDAxMTAwMTExMDEwMDAxMDExMTEwMDEwMTExMTAxMTEwMTExMDExMTAxMTEwMTExMDExMTAwMTAxMTEwMDExMTEwMDEwMTEwMTExMTAxMTEwMTAxMDExMTAxMDAwMTExMDEwMTAxMTAwMDEwMDExMDAxMDEwMDEwMTExMDAxMTAwMDExMDExMDExMTEwMTEwMTEwMTAwMTAxMTExMDExMTAxMTEwMTEwMDAwMTAxMTEwMTAwMDExMDAwMTEwMTEwMTAwMDAwMTExMTExMDExMTAxMTAwMDExMTEwMTAxMTAwMTAwMDEwMTAwMDEwMTExMDExMTAwMTEwMTAwMDExMTAxMTEwMDExMTAwMTAxMDEwMTExMDExMDAxMTEwMTAxMTAwMDAxMTAwMDExMDEwMTAwMDE=#d2946ddce572d88f5079f600c5b12fbd5f667238f1b0271ab0e5f49b098e6a9f)
[run online - enter input yourself](https://v.astroide.repl.co/#d2946ddce572d88f5079f600c5b12fbd5f667238f1b0271ab0e5f49b098e6a9f)
[Answer]
# [Red](http://www.red-lang.org), 79 bytes
```
func[x][p: 0 x: replace/all x"111111""1111110"forall x[prin p: 49 - x/1 xor p]]
```
[Try it online!](https://tio.run/##bZDBCsMgDIbvfYqQ@2iEXda9gd52FQ@lVTYobZENfHunsay27FfI4f/@hMTbMT7sqE3juug@86CD0WsHBKEDb9epH2zbTxMEFCzcKqFbPBt69a8ZUuZ6gwuEVkBYPKzGxETYfnjCG3SDAuGsO0pskP4ZKhmCiAQdcimhpFKSc5vwkJPl5fimgy9ZSiluUDapOuQGhZA7UBM/IE@pkIqpkBOzgzXD2gfmzwni1QtZCJ6aOKNdumk@@xsQTfwC "Red – Try It Online")
Both input and output are strings of \$1\$s and \$0\$s. Output is done by printing.
Despite the unwieldy string replacement, other ways to account for the extra zero bit tend to be even longer.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~33~~ 32 bytes
```
1{6}
$&0
{+rT`d`JK`K.
1T`d`KJ`\d
```
[Try it online!](https://tio.run/##dVC7DsIwDNz9HVAhIaHzwi8gNSsjQ5DK0IWhYqv49pCk5@AWESXy@XnnTI/X@Lyn/eESk87nt@w6yHycrnGIfYjhJFpg6ONtSEkFogAUGfGI8uRItTlE5OEK@0C5NYEytPigrxuLVqcugWUW7b8HM81x9dANn4kiFXw/TDT7KfmHHyaOc799tsiqVslcR5ETXr/TZ/vDaW9fQmbjW7o@ "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
1{6}
$&0
```
Perform bit-stuffing.
```
{`
```
Make as many replacements as possible.
```
+rT`d`JK`K.
```
Change `0` after a `K` to `J` and `1` after a `K` to `K`. Change starting with the character after the last `K` (and working back, not that it matters), and keep replacing characters until there are no digits after a `K`.
```
1T`d`KJ`\d
```
The first remaining digit is not after a `K`, so change `0` to `K` and `1` to `J`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes
```
≔⪫⪪S×1⁶⁺×1⁶0θ⭆θ§JK№…θ⊕κ0
```
[Try it online!](https://tio.run/##VYyxCoMwGIT3PkXI9AdSiEsXJ8kUpSDYF5AYNDT@URNL@/Rp2lJob7u7705P/aZ971KqQrAjQu0tQrc4G0HhsscubhZHYJxc7GwC0IJycmLZt24P8BdyQgV9VSsrD23eRfjMz/0CKydVVDiYO9C6ybz0ewbkQzsjJ/8GFOrNzAajGeDKvn@MlSkJUfxIiHS8uSc "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⪫⪪S×1⁶⁺×1⁶0θ
```
Perform bit-stuffing.
```
⭆θ§JK№…θ⊕κ0
```
For each prefix of the string count the number of `0`s and output `K` if it is odd and `J` if it is even.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 21 bytes
```
0=\.'(t,$0)/(t:6#$1)\
```
[Try it online!](https://ngn.bitbucket.io/k#eJx1UjGOwzAM2/2Kg1qgCRD05KVDDgfcbH6hc6eOnfv21hblqA7OSSDYIkVKzm3V3+v5ND2Wo87f02O9HI55vqZ0X6VAflKaFikyP+9ft79FstQ9+l4lvWEFKEXqkWRVzfqGCYo9dq5cFd8WADK4GsVSndMSjcRUrfiRHLK79Jhva1QYoQZpagFY30ZQ66827bgxtpkAhZ8hwQ7MhvvZRbh0B5cNg1HPzcLRgQ+SXY9GdvrwQ6cEMLahdbBbAY0gFKByNwhsXXXREioEQSvOideBKweeh6j9InJIqF0i43+feuibgNc86PmtU0ojX/2vIJ+Wd/rq5lh343kjH9hM5VaKmpqD/+DP+9fgvY+Eyq5nLEkvFPXv7w==)
Takes input as a string of `"1"`s and `"0"`s. Returns a list of `0`s (for `J`) and `1`s (for `K`).
* do a string replace of `"111111"` with `"1111110"`
+ `(t:6#$1)` store `"111111"` in variable `t`
+ `(t,$0)` append a `"0"` to the end of `t`, generating `"1111110"`
* `.'` convert each character to an integer
* `0=\` use a equals-scan, seeded with 0 (this does the non-return-to-zero part)
[Answer]
# [Haskell](https://www.haskell.org/), 85 bytes
```
map("JK"!!).(0%)
j%(1:1:1:1:1:1:y)=j:j:j:j:j:j:j%(0:y)
j%(i:y)|k<-i^j*j^i=k:k%y
j%e=e
```
[Try it online!](https://tio.run/##dVHbboMwDH3nK9JoqDCplfOKlh@If2GqhDrYuLRDZS@V9u1juTjgwpYInBwf@9jxRzl2Vd9PtX6dLuWQSYNyt8uPGaR50qaZKpZ9z3VbsJ1mYDHHaqz97l4Ozal9bk@N7oouvVtHpatpKG9jJfZqL7RQCd3A3SCpnanFUVhp4V3JpWyuFnz7TIQYbs31SzwJS5NKCq2FNHKFQ8BxjSsAUBCj0CCaTayiRSS/EDepQNlE4PLRgduIQ/jI4U5qtv99EM18YXxQKz3vdzQgNov3JBZPJW/0IRZHeZe42MgDV5GyT0WawOtn9cX@gdU@PwkpR70QRZNzk7HzCY@/sn5w6H/hQJP0Po8Q/w9LR0Y2CwfXekEi8IN/iUcKjnpUyEYfIxhDGDnUv/QRARLGKMqaeCgQcelqFjUsAxMMyeX0c6778n2cDudh@AU "Haskell – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~84~~ ~~80~~ 78 bytes
-6 thanks to @ceilingcat
```
x;c;a(char*p){for(c=0,x=1;*p;c>5&&a(L"10"+x))putchar(x^=*p<49),c=*p++/49*-~c;}
```
[Try it online!](https://tio.run/##dVLvaoMwEP/uU0hgRa1lF9g@FNc9QG6PUAYS1s0PS6W1IJTu1V2T3Gma2lS5mP7@JTm9@tZ6GPpKV3Wmf@pD0ebn3f6Q6Q2U/UZWRVvp99fFos4@hASx7PO8PXUWmfWfm6J9e1nnpb5Olsvnl3Wx@tPVZWhMl3Zfx84rpo0pUz/bn7o8OSfpddRZY/LKTdvDlbDLxNY8Hbdma0RpcVVySRKr9Fs3JmOakxVSlKlQgvh@Dewa3q5JAJDg0agQVcyh4ajK/yIFGk7CDUSMRRyCVTxIzWJuQdZuHhbjHgNn0W7MZrCP44I/FfR4hT5OzLAEIIKMKoxCMvgDfB6qj17gMn4EeJCRH6cmKwj5wLsiPkW@8wcOR7oTjzdyg5Xk7KTIE8L8QT7ePwTZxyMhZ/bzLHfythv54OPqmhVR0euRSD3jL5hv@q4i3@UIVhMGYz@@fWR0wEcisx8FufNHXmRKAMapHUcwR0EKgoEAOY8BEaddjaYqUAgMvbht4cvwDw "C (gcc) – Try It Online") Takes input as the characters `0` and `1`, outputs with bytes `0x01` for `J` and `0x00` for `K`.
For output as actual `J` and `K`,
[Try it online!](https://tio.run/##dVLvasIwEP/epyiBSVsru4AypHMPkNsjyKCE6fphtWiFgrhX70xy18ZYT8vV@PuX5PRir3Xfd4UuykT/lMesSS@7wzHRG8i7jSyyptAfq9msTD6FBDHv0rT72mTN@3Kd61ufz1@X62zxp/Pm3BqB5G216NLi2ld1G7ffp9bJxlWdx@7tcG7T6BLFtyqTqk4L@9ocb4RdIrb1y2lbb2uRG1wRXaPIKP2WVZ0wzcoKKfJYKEF8twZmDe/XJABIcGhUiCrkUFmqcp9AgcpK2ELEUMQiWMWB1CTmHmTspmEh7jlwEm1rMoP5Wi64U0GHV@jihAxDACLIoMMgJL0/wOWh/uwBbsMPDw8y8OPUZAU@H3hXxKfID/7A4Uh35PFG7rCSnK0UeYKf38vH@wcv@3Ak5Mx@jmVP3kwjH3zY7bAiKnocEmlm3AXzTT905LscwGrEYOjHt4@M9vhIZPajIA/@yItM8cA4juMA5ihIQdATIOchIOK4q8FUeQqeoRM3I3zt/wE "C (gcc) – Try It Online")
[Decoder](https://codegolf.stackexchange.com/a/229553/80050)
]
|
[Question]
[
She said **s(he) be(lie)ve(d)**, he said **sbeve**.
**Input**
* A non-empty string, `s`. It's guaranteed that `s` will have only printable ASCII characters and at least one word (defined as `[A-Za-z0-9]+`) in parentheses, and all parentheses will be closed respectively.
**Output**
* A string containing all non-whitespace characters (whitespaces are defined as spaces, tabs, carriage returns, new lines, vertical tabs and form feeds characters) that are not in parentheses.
**Test cases**
```
Input -> Output
s(he) be(lie)ve(d) -> sbeve
s(h3) (1s) br(0k)3n -> sbr3n
(I) (K)now (Ill) Be
(My) Best (Self) -> nowBeBest
sho(u)lder (should)er
s(ho)u(ld)er s(h)ould(er) -> sholderersuersould
p(er)f(ection) -> pf
(hello) (world) ->
```
The last output is an empty string.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
>Ƈ⁶Ø(yṣ”)m2
```
A full program printing the result.
**[Try it online!](https://tio.run/##ATEAzv9qZWxsef//PsaH4oG2w5goeeG5o@KAnSltMv///3MoaGUpIGJlKGxpZSkJdmUoZClh "Jelly – Try It Online")**
### How?
Whitespace printable ASCII characters are `"\t\r\n\f\v "` and non-whitespace printable ASCII are all greater than `' '`, so:
```
>Ƈ⁶Ø(yṣ”)m2 - Link: list of printable ASCII characters, s
Ƈ - filter keep those (characters) for which:
> ⁶ - greater than literal space character
Ø( - literal list of characters ['(', ')']
y - translate (replace all '(' with ')')
”) - literal ')' character
ṣ - split at
m2 - modulo-two-slice (every other entry)
- implicit, smashing print
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes
```
ηʒ„()S¢Æ_}€θJžKÃ
```
[Try it online!](https://tio.run/##AToAxf9vc2FiaWX//863ypLigJ4oKVPCosOGX33igqzOuErFvkvDg///cChlcik0NSgyMSkgZihlY3Rpb24p "05AB1E – Try It Online"), or [Verify all test cases](https://tio.run/##HY49CsJAEIWvsqSagRRKbmAXxcrSiBgzweCwK5s/UgREwQN4AAtre60sFBsLD@FF4qzVvPc93syYfBFn1FVN97m@j9/tCXDyOD8P8/a7u3xuw9d99Nx3fttNvRxWhCom4IywIkjQ8x0MUEE/l8RCb42BFgqhsBFqUysImVENKNIwbpzICwUT4vTfXhkokROyCkSXnCDZSMtSgyX8nRKDLgGyrrJxMwVaFpnRDshXzEbu1cZKw5v9AA "05AB1E – Try It Online")
---
### Explanation
```
η - Prefixes of the string
ʒ } - filter these when...
„()S¢ - the counts of ( and ) characters
Æ_ - are the same
€θ - get the last character from each of these prefixes
J - Join all these last characters
žKÃ - and remove any that aren't in [a-zA-Z0-9]
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 11 bytes
```
\(.*?\)|\s
```
(Note the trailing newline in the code).
[Try it online!](https://tio.run/##K0otycxLNPz/P0ZDT8s@RrMmppjr//9ijYxUTYWkVI2czFTNslSNFE0A "Retina – Try It Online")
### How it works
```
Replace either
.* a sequence of characters
\( \) in parentheses,
? matched non-greedily,
| or
\s any whitespace character
by nothing
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + GNU utilities, ~~36~~ ~~32~~ 28 bytes
```
xargs|sed 's/([^)]*)\|\s//g'
```
[Try it online!](https://tio.run/##S0oszvj/vyKxKL24pjg1RUG9WF8jOk4zVkszpiamWF8/Xf3/fw1PTQUNb828/HIFDc@cHE0Fp1QuDd9KEF1coqARnJqTpgkA "Bash – Try It Online")
*Thanks to @user41805 for 4 bytes!*
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 119 bytes
```
I =INPUT
S I ARB . L '(' ARB ')' REM . I :F(W)
O =O L :(S)
W O NOTANY(&UCASE &LCASE 84 ** 9) ='' :S(W)
OUTPUT =O
END
```
[Try it online!](https://tio.run/##JY2xCsIwGIT3PMVNzf93cOqggQxVIwRqIk1KcS0NKBQ7FHz9GOp03x133PZZp3VpcoaFtu4xRBEKtv0ZB3SQJHeWLNGbe8ks1I1GFvDQvjQUBRZjcc7H1j2pGi5tMKi6XY4N6honhpYSKvyHQyw3ZS2Mu@a80SsxpkTLO/E30cw/ "SNOBOL4 (CSNOBOL4) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
e€Ø(œpm2FfØB
```
[Try it online!](https://tio.run/##y0rNyan8/z/1UdOawzM0jk4uyDVySzs8w@n////FGhmpmgpJqRo5mamaZakaKZoA "Jelly – Try It Online")
A monadic link taking and returning a Jelly string. Now handles other whitespace characters.
## Alternative 12 bytes
```
Ø(yṣ”)m2FfØB
```
[Try it online!](https://tio.run/##y0rNyan8///wDI3KhzsXP2qYq5lr5JZ2eIbT////izUyUjUVklI1cjJTNctSNVI0AQ "Jelly – Try It Online")
[Answer]
# APL+WIN, 25 bytes or 30 bytes
Prompts for string.
```
((~x∨≠\x←s∊'()')/s←⎕)~' '
```
[Try it online! Courtesy of Dyalog Classic](https://tio.run/##PY07EoJADIZ7TpFuk8Kx8Bp6AxuEIDtG4rAi2lgqWjg29paeay@CQR2rJN//SLqRUX5IRZejTNIQfNbH22M2jaf7JInduegRj/vYveLlOd8bDbG7OiRH42CXeenowPVm7YvEBSyZYMEonmnHmJNL/hh9MK1GXRFXH47e6IoqbU0UGZKA68MwwxYwsBS/glKxIcm5NlpqIznZarVKDf4PGgTk@puBzbAWyNnWa0UOPh9LFlH72mptOQcAbw "APL (Dyalog Classic) – Try It Online")
If I now have to handle none alphanumeric characters this works for 5 extra bytes in APL+WIN but will not work in Dyalog Classic so no TIO
```
((~x∨≠\x←s∊'()')/s←⎕)~⎕av[⍳33]
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes
```
ŒʒÁ„)(å}KžKÃ
```
[Try it online!](https://tio.run/##HY4xCsJAEEWvMmw1AwpKegU7CVaWamHMhASXXdlNDCkExQuIB7DzGjbBxmN4kXXWav5/nz8z1m@zisOx629TBcMJqGl43z/3/vI9Pwj75yl9v9L@GgZhpTyWTJAx6orpyJiTGkSYEODYS@JwtKfECMW5sJSMbQHnWhPMeG1w0UXha8Al6@LfLi02pHN2gKIbnRO7tZGllhr8OxBDMUF2sXKIs0De1ZU1EchXWlu511onDbX5AQ "05AB1E – Try It Online")
```
Œ # substrings
ʒ } # filter, keep each substring if:
Á # after being rotated right
„)(å # it contains ")("
K # remove those substrings from the input
žKÃ # keep only characters in [a-zA-Z0-9]
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 11 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
û┼╢╕jN&╪º╛╘
```
[Run and debug it](https://staxlang.xyz/#p=96c5b6b86a4e26d8a7bed4&i=s%28he%29+be%28lie%29ve%28d%29)
Unpacked:
```
"\(.*?\)| "zR
```
this is just a simple regex replace. It replaces all strings that match `/\(.*?\)| /` with z (an empty string)
[Answer]
# [Perl 5](https://www.perl.org/) + `-lF/\(\w+\)|\s+/ -M5.10.0`, 5 bytes
```
say@F
```
[Try it online!](https://tio.run/##PY49C4NADIb3@xU3JohfiHvpIIg4db2lrRGlwZM7rQj97b3mli553zz5XMlxHYK/n5dGBCZC/SDgmfBNMKASVKGG0gt3ULywWhS0Qjpc7KGhZUZ9JQ39GdVvGm7EowxOFnbkgZwG8TsPKFbWWdzhn2AsADlUa4wj0HOb7YJKPmG2cuewTrq/do3ch5Sb3IA5EoMf45M8pH2dlUVW/AA "Perl 5 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~10~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
„()S¡ιнJʒð›
```
+1 byte as bug-fix (`žu` to `„()` and `žKÃ` to `ʒð›`), since apparently all printable ASCII + whitespaces are valid input-characters, instead of only alphanumeric, whitespaces, and parenthesis..
[Try it online](https://tio.run/##yy9OTMpM/f//UcM8Dc3gQwvP7byw1@vUpMMbHjXs@v9fSUlJw1NTQcNbMy@/XEHDMydHU8EplUvDtxJEF5coaASn5qRpApUBAA) or [verify all test cases](https://tio.run/##HY4xCsJAEEWvMmw1AymUHECwi2JlaSyMGTG47MpuoqQQrDxADiB4A1sFG@0sxDPkInHWav5/nz8z1i@ygrtdPVDQnhpQg7prj2ek6fPyuX0fo3fzurbHe3eIupnyuGaCjFEXTDvGnFQUYEyAfS@Jw96GYiMUE2FjMnYPmGhNMOTU4KQOwpeAU9arf3ttsSKdswMUXemc2KVGllqq8O9ADIUE2YXKNswV8rIsrAlAvtLayr29ddJQ8x8).
**Explanation:**
```
„()S # Push string "()", and split it to a list of characters: ["(",")"]
¡ # Split the (implicit) input-string by that
ι # Uninterleave this list
н # Only keep the first inner list
J # Join it together to a single string
ʒ # Filter the characters in this string by:
ð› # Check if the character is larger than a space " " (by ASCII codepoint)
# (after which the result is output implicitly)
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
r"%s|%(.*?%)
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ciIlc3wlKC4qPyUp&input=InMoaGUpIGJlKGxpZSl2ZShkKSI)
[Answer]
# [Python 3](https://docs.python.org/3/), ~~47~~ 45 bytes
Saved 2 bytes thanks to [FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman)!!!
```
lambda s:re.sub(r"\(\w+\)|\s","",s)
import re
```
[Try it online!](https://tio.run/##PZBBS8QwEIXv/RVDLjuDVVwrCAv1sIKwiCe9GQ9bO6XFbFImyS5L3d9e01Y8BN7M@/Jmkv4cWmeLsSn1aPaHqt6D3wjf@FihKI36dKXpR3uVK5V7yrpD7ySA8BjYB19ihspjywQVo@mYjow1qRyUr/jIivIFKAhw7RMlePtNhV0ISWImcJf8F7LuBLgzhmDL2uLreRI@AL6xaebURGx56v0ltw4jmZoFMOloamLRNg10FHGuIBU0OciyLNa66QKLj@lMzpLVT0CD/BU6Z2eyb/62a9kYlzY8OTHL6yaDMimHd4m8gah0vHtYF8l63hv/37l/UpescQIhZ@gszJ@2ycCXDQbKoJfOBmxWaggXBdePoAafxCAfviz587Ki8Rc "Python 3 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes
```
Φθ∧›ι ⁼№…θ⊕κ(№…θκ)
```
[Try it online!](https://tio.run/##bctBDsIgEAXQvaeYsJpJ8ASuDFHjzisgTALpCHZKm/T0WPb@3c9/PySvoXrp/aW5NLxnaaw4W7iWiA9lP2q2YMCQhdu8elnQ1fWwbg/CLtXv4M8SlD9cGkec6KAGx@GPnMZIhkYuvS@YmODNKJlpY4x06udNfg "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ Input string
Φ Filtered where
ι Current character
› Is not whitespace
∧ Logical And
№ Count of
( Open parentheses
…θ⊕κ In input string so far (inclusive)
⁼ Equals
№ Count of
) Close parentheses
…θκ In input string so far (exclusive)
```
[Answer]
# [Perl 5](https://www.perl.org/) `-p0`, 15 bytes
```
s/\s|\(.*?\)//g
```
[Try it online!](https://tio.run/##K0gtyjH9/79YP6a4JkZDT8s@RlNfPx0okJGvUaqZk5JapKABZJfmpGimFnEVa2Tka5ZqgDkKQI4mSEIjtUjzX35BSWZ@XvF/3QIDAA "Perl 5 – Try It Online")
[Answer]
# [sed](https://www.gnu.org/software/sed/), ~~32~~ 31 bytes
```
:l;s/([^)]*)\|\s//g;N;s/\n//;tl
```
[Try it online!](https://tio.run/##K05N0U3PK/3/3yrHulhfIzpOM1ZLM6YmplhfP93aDygUk6evb12S8/@/hqemgoa3Zl5@uYKGZ06OpoJTKpeGbyWILi5R0AhOzUnTBAA "sed – Try It Online")
*Shaved off one byte by removing the -E option and just using basic regular expressions, surprisingly :-) .*
sed is *almost* perfect for this challenge. The only issue is that sed is a stream editor, processing one line at a time: the trailing newline on each line is not processed, which doesn't make it straightforward to delete any newline characters.
So here's how this script does it:
```
:l
Label we can jump to later.
s/([^)]*)\|\s//g
Delete all parenthetical expressions and whitespace before the first newline.
N
If we're not at the last line, append the next line to the pattern space. (The next line is appended immediately _after_ the \n at the end of the previous line. That \n is still there, now in the middle of the pattern space, where it's available for processing by sed.)
s/\n//
Delete a \n in the middle of the pattern space, if any. (There will be one if we weren't at the last line in the previous step already.)
tl
If the last command found a \n to delete, jump back to label l, and do it again!
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 70 bytes
```
f(char*s){for(;*s;)s=*s-40?isalnum(*s)&&putchar(*s),s+1:strchr(s,41);}
```
[Try it online!](https://tio.run/##dY8xb8IwEIX3/IpTKqG7ABURTA1tpW6o6tSVJbUdYvWwkc8GVYjfnjpMHdKb3tP7dO9OLQ9KDUOHqm9DJXTtfMCmkobkuZLlZvVqpWWXjpjD2eyU4giOZiHz@kliUH1AWWxqam7Dg3WKkzawlaitf@xfisK6CMfWOjx7q6m4FpCnw1KwNwRfBtkaOhvUVFIDuUCwzOoPtibAWjIbcPVNazfJ4S5T7@T8BXDHTPBm9g4/fkYhEfDTcPdPQ@8xEWsTALNOrMmEvcvFnhLeHWRDY4ImTC85jUmHRkXr3TSS/2X2@cqLD3z/trgNvw "C (gcc) – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), 52 bytes
```
func[s][parse trim/all s[any[to"("remove thru")"]]s]
```
[Try it online!](https://tio.run/##HU4xbsMwDNz1CkITObVFto7dgqJLMwoaXIuCjdKSQckJgqBvd@lwOd4dyDvltH9zCtHl9z1vZQwthnXQxtB1Xl4GEWhhKPfQq0evvNSrWZNunnyMLe65Kg/jBB2C8w0nJvhhlJnpypjIP8UTAb41cxRff@lUvHvg2bRPKvUGeBYh@GCHX/cDWwe8sGT6c482VdxIEiug7ZskYnX2stKGTwJG6DCQ1S78emBGHvtcy5FvnUSqpd2qytEoBgc2q87FWi9VkrXP0KOL@z8 "Red – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 30 bytes
```
s=>s.replace(/\(.*?\)|\s/g,"")
```
[Try it online!](https://tio.run/##JY9Bb4MwDIXv/IqoJ3uidBPHKUyqtEM17bRjqUQAU9isBCVAO2377SwJh8ixv6fn50@1KNfYYZz22rS0dnJ1snCZpZFVQ3AoIXt4KfG3dIdrutvh@nyuHPSEoibggXAhaFHsC@FqWqhKk4BzFPDkvMbC4xfmeuM214HDydM31OYm4MSM4kgJvH@H6iYBH8RdNPSCI4VZNO0NzMgtWQH@P3OLZBO/yuAMsRG@wQCA7BaoN0FP1s3@BRKMxoA7oGYajI66sYupemI2PtnNWN4uqi5ZZ@yranq4y@InWZQ9q7S@yHvmRh6mKoqSxmhnmDI2V1BpBwrTOhYpa0z@cP0H "JavaScript (Node.js) – Try It Online")
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~21~~ 19 bytes
```
∊⊢⊆⍨<>(≠\∨⊢)⍤∊∘'()'
```
[Try it online!](https://tio.run/##XY69TsNQDIV3nsJM15ZaqVVWxEAXogohEdhYCtdpK65yq/xQOiNFIVIqGJAYEWLoxjvwKH6R4DRMXazj79jHnq3c0G5mzs@H/JRzYtm2rVS11F9Sl9LsTk5RXj5vpdopImm@O7P6MEimjaV8lWYr2/fwUurn359AyjftoquJ1uvzMGpjMBkumOCO0S2ZHhktmaMeBwQ4ztRLcfRAQbLnGCqdUuLXgKFzBGdsBqh5N5MIxiMaGLzYdDTLASN28X/cwmNBznIKqLpwljg9WNSTngrcW6ANdWPIaZ@w6lSMfJ8vfdIj/dw5T3AMuPap7pk/ "APL (Dyalog Extended) – Try It Online")
### How it works
```
∊⊢⊆⍨<>(≠\∨⊢)⍤∊∘'()' ⍝ Input: string s
∊∘'()' ⍝ Boolean vector (1 if a member of '()')
(≠\ )⍤ ⍝ Scan by boolean XOR
⍝ (gives 1 between '()'s, including '(' but not ')')
∨⊢ ⍝ Include back ')'
> ⍝ Bitmask indicating negation of the above,
< ⍝ plus each char not being whitespace
∊⊢⊆⍨ ⍝ Filter s by the bitmask above
```
Boolean filtering uses [this APL golfing tip](https://codegolf.stackexchange.com/a/153435/78410).
[Answer]
# [Gema](http://gema.sourceforge.net/), 7 characters
```
(*)=
=
```
Sample run:
```
bash-5.0$ gema '(*)=; =' <<< 's(he) be(lie)ve(d)'
sbeve
```
[Try it online!](https://tio.run/##S0/NTfz/X0NL05ZLwfb//2KNjFRNhaRUjZzMVM2yVI0UTQA "Gema – Try It Online") / [Try all test cases online!](https://tio.run/##lZBRS8MwEMefl09xlrlchNHp8EkKOvBhiAj6uBXZ2qsdi01J2k2Z@@zzkoq6Bx8sNPe/3C93/2S5cOUhp0wvLMHwBhpyzXO2cJSg6M2kw5IULAn1itSGMFcyTaRb0obkV32sAM8dQxZHazWuOsCy8ABOuXynKrMFnGqtYEIC7999dA3gE@kitGRgQn6va1sabJXOyQKybnWuyAoeZlSLIQFOlC8g2c5TaTxP1rX8@0roVPt6gZQ1K1MFsC46YyVpbdjc1ljdXUvC8SeUELVdVU0B8gNOh5cjBz5eHMcLXueVBDmt6rbh@Eiu1V7cvtU8mHKWD2spRGEsrDzEK0T93cn3a8@u0310BbkRPRtOJ1EfgbLSwNCj4VTE02JTN/ELvS5iZ7MgQB7wTCUCkoMEFQnR@4dnNhFax3Ffch7P59U@4t3OhFe7H4@dizQACLPZLy5J/kLTFAaD7ib@EbzD3FR0@AQ "Bash – Try It Online")
[Answer]
# [Kotlin](https://kotlinlang.org), 75 bytes
```
{fold(""){a,v->when(v){')'->a.takeWhile{it!='('}
in " \r\n"->a
else->a+v}}}
```
[Try it online!](https://tio.run/##LY4xDoMwFEN3TvGbJflq4QBI0At069CFJYhPiUhDFdJ0iHL29AvVi2U9S/a6BWtcidrCPlKkFu7BG/dsFELd/wN0Jc2bnZQQmPQl1v13IaciJomy7nUT9EqPxVhKJpw6qWSujAMBgx@c4EJFdif2c8w5l/nj4KWN44lUAetYDx468KSnm3HE6NqCEAd@84egjnuKa4hVhrKrhRBGUtYQMpjwBw "Kotlin – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 14 bytes
```
aRMw,`\(.+?\)`
```
[Try it online!](https://tio.run/##K8gs@P8/Mci3XCchRkNP2z5GM@H///8anpoKGt6aefnlChqeOTmaCk6pXBq@lSC6uERBIzg1J03zv24KAA "Pip – Try It Online")
Unweave works really well in this solution.
-2 bytes from DLosc, with the first documented use of `,` for Regex alternation!
]
|
[Question]
[
[Related, but this only requires positive integers and does not have to be commutative](https://codegolf.stackexchange.com/q/8892/59487)
The Cantor Pairing Function is described in [this Wikipedia article](https://en.wikipedia.org/wiki/Pairing_function). Essentially, it is an operation such that when it is applied to two values X and Y, one can obtain the original values X and Y given the result.
Your task is to design two functions: one which performs `X, Y -> Z` and the other which performs `Z -> X, Y`. Here's the catch: `X, Y -> Z` must be commutative. This means that `Z -> X, Y` won't be able to determine if the input was `X, Y` or `Y, X`.
The formal definition of this challenge would be:
Choose an countable infinite set S of numbers.
Design two functions that perform the following tasks:
* Given an unordered pair of values in S, return a value in S
* Given a return value from the initial function, return the unordered pair of values which evaluates to the input integer when passed through the first function. I don't care about the behaviour of this inverse function if the input isn't a return value from the first function.
# Requirements
* The result should be identical between runs.
* `{a, a}` is an unordered pair
Note: your answer is more likely to get an upvote from me if you provide a proof, but I will test answers when I get to it and upvote it once I'm fairly sure it works.
[Answer]
# [Haskell](https://www.haskell.org/), 65 + 30 = 95 bytes
```
a#b=length.fst$span(<(max a b,min a b))[(a,b)|a<-[1..],b<-[1..a]]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P1E5yTYnNS@9JEMvrbhEpbggMU/DRiM3sUIhUSFJJzczD0RrakZrJOokadYk2uhGG@rpxeokQRiJsbH/cxOBimwVUvK5FAqKMvNKFFQUTJWNERxjZdP/AA "Haskell – Try It Online")
```
([(a,b)|a<-[1..],b<-[1..a]]!!)
```
[Try it online!](https://tio.run/##y0gszk7NyfmfbhvzXyNaI1EnSbMm0UY32lBPL1YnCcJIjI1VVNT8n5uYmadgq1BQlJlXoqCikK5gaPT/X3JaTmJ68X/d5IICAA "Haskell – Try It Online")
---
**Note:** When the two functions may share code, this is only 75 bytes:
```
(l!!)
a#b=length.fst$span(<(max a b,min a b))l
l=[(a,b)|a<-[1..],b<-[1..a]]
```
[Try it online!](https://tio.run/##VcixDsIgEIDhnae4ph24hJKYplt5kspw1EIbDyTSwcFnFzVOTv@Xf6NyXZmrN7JFEcy5Sm4aFGxmScrhk6Z@PmltlfuBrBXUOsNrCsemfTm6kinJSUZ6AIFTcU/fInKN9LGBy01Avu/pgA6C9DDCgP9ngBHra/FModR@yfkN "Haskell – Try It Online") The domain is the positive integers. The function `(#)` performs the pairing, the function `(l!!)` its inverse. Usage example: Both `(#) 5 3` and `(#) 3 5` yield `12`, and `(l!!) 12` yields `(5,3)`.
This works by explicitly listing all sorted pairs in an infinite list `l`:
```
l = [(1,1),(2,1),(2,2),(3,1),(3,2),(3,3),(4,1),(4,2),(4,3),(4,4),(5,1),(5,2),(5,3),(5,4),(5,5),(6,1), ...`
```
The encoding is then just the index in this list.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 8 + 6 = 14 bytes
```
ij\aSQ16
```
```
SQ # Sort the input
j\a # join with "a"
i 16 # convert from base 16 to base 10
```
[Try it online!](https://tio.run/##K6gsyfj/PzMrJjE40NDs/38jcx1LIwA "Pyth – Try It Online")
```
c.HQ\a
```
```
.HQ # convert from base 10 to 16
c \a # split on "a"
```
[Try it online!](https://tio.run/##K6gsyfj/P1nPIzAm8f9/QzMjE1MDAA "Pyth – Try It Online")
Domain: Positive integers.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 + 11 = 19 bytes
Rolled back since Rod's algorithm didn't work.
This works on the domain of the positive integers.
Takes `x` and `y` as 2 arguments, doesn't matter in which order, returns `z`.
```
»’RSð+ð«
```
[Try it online!](https://tio.run/##ARsA5P9qZWxsef//wrvigJlSU8OwK8Owwqv///8z/zE "Jelly – Try It Online")
Takes `z` and returns `[min(x, y), max(x, y)]`
```
R€Ẏ,Rx`$ị@€
```
[Try it online!](https://tio.run/##y0rNyan8/z/oUdOah7v6dIIqElQe7u52AHL///9vAgA "Jelly – Try It Online")
[Answer]
## JavaScript (ES7), 44 bytes
```
(x,y)=>x>y?x*x+y:y*y+x
z=>[x=z**.5|0,y=z-x*x]
```
Maps from non-negative integers to a subset thereof.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 36 + 39 = 75 bytes
Thanks to @tsh for saving two bytes.
The domain is non-negative integers.
```
p(x,y){return y>x?p(y,x):-~x*x/2+y;}
```
Takes `x` and `y`, returns `z`.
```
u(int*r){for(*r=0;r[1]>*r;r[1]-=++*r);}
```
Takes a two-element `int` array. The second element must be set to `z` before the call. After the call `r` contains `x` and `y`.
[Try it online!](https://tio.run/##NZDBaoQwFEXX@hWXKUJiYusI3TRqP8S6KGamFdqMpAqJkv66fZHpIsnjHu6Bl6H4GIZ9n5iTnm/2Mi/WwLfudWJeOv5S/LrcPVXCq7Cw0cy55dv1Zllum1LZ7ty3uT3eohGCoAr7w2iGr0VfUP/Merw9frYpFfH9PhrGsaUJ9RFdWMmBtX6OtxAHS2Juu6pHgw2lxIqgKF4Yue/YEbNd2Uv4Yzr3kUyW2JWdWKYlMs1RFy2ySv@fN3OScNQhp0RcGJ7HgQLHozykyf0DSpWG/Q8 "C (gcc) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 11 bytes
### pair of positive integers to positive integer, 5 bytes
```
Ṁc2+Ṃ
```
[Try it online!](https://tio.run/##y0rNyan8///hzoZkI@2HO5v@//9vaK6jYGQMAA "Jelly – Try It Online")
### positive integer to pair of positive integers, 6 bytes
```
ŒċṀÞị@
```
[Try it online!](https://tio.run/##y0rNyan8///opCPdD3c2HJ73cHe3w////43MDQA "Jelly – Try It Online")
## Algorithm
If we sort the set of all unordered pairs of positive integers by their maximum and then by their sum, we get the following sequence.
**{1,1}, {1,2}, {2,2}, {1,3}, {2,3}, {3,3}, {1,4}, {2,4}, {3,4}, {4,4}, {1,5}, {2,5}, {3,5}, {4,5}, {5,5}, …**
The first function takes a pair **{x,y}** and finds its index in this sequence.
The second function takes a positive integer **z** and returns the **z**th item of the sequence.
Note that this mapping is the same as in [@EriktheOutgolfer's Jelly answer](https://codegolf.stackexchange.com/a/142387/12012).
## How it works
```
Ṁc2+Ṃ Main link. Argument: [x, y]
Let m = max(x, y) and n = min(x, y).
Ṁ Maximum; yield m.
c2 2-combinations; yield mC2 = m(m-1)/2.
Note that there's one pair with maximum 1 ({1,1}), two pairs with maximum 2
({1,2}, {2,2}), etc., so there are 1 + 2 + … + (m-1) = m(m-1)/2 pairs with
maximum less than m.
Ṃ Minimum; yield n.
Note that {x,y} is the n-th pair with maximum m.
+ Add; yield mC2 + n.
This finds {x,y}'s index in the sequence.
```
```
ŒċṀÞị@ Main link. Argument: z
Œċ 2-combinations w/replacement; yield all pairs [x, y] such that x ≤ y ≤ z.
ṀÞ Sort by maximum.
ị@ Retrieve the pair at index z (1-based).
```
[Answer]
## Mathematica (35+53)=78 Bytes
```
((x=Min[#])+(y=Max[#]))(x+y+1)/2+y&
(i=Floor[(-1+Sqrt[1+8#])/2];{#-i(1+i)/2,i(3+i)/2-#})&
```
This is the one good known quadratic pairing function for Z<-->ZxZ combined with Min and Max to make it orderless.
[Answer]
# Ruby, 66 bytes
```
f=->x,y{2**~-x|2**~-y}
g=->n{x,y=(1..n).select{|i|n[i-1]>0};[x,y||x]}
```
I'm trying to find a way to cunningly select an infinite set to make this easier, this is the best I've got so far.
We define f(x,y) = 2x-1 bitwise-or 2y-1. The domain consists of the set defined recursively as containing 1,2, and all numbers that can be produced by calling f on numbers in the set (note that f(1,1) = 1 and f(2,2) = 2, so 1 and 2 have inverses). The resulting numbers all have either one or two 1s in their binary expansion, with the indices of the 1s corresponding to numbers in the set. We can get the original unordered pair out by taking the indices. If there's only one 1, that means the elements of the pair are equal.
For example, f(3,5) is 20, because 20 is 10100 in base 2, which has 1s in the 3rd and 5th least significant places.
[Answer]
# Java 8, ~~153~~ ~~146~~ ~~141~~ 137 + ~~268~~ ~~224~~ ~~216~~ 205 bytes
Pair function
```
a->{String f="";for(int i=(f+a[0]).length(),c=0,j;i>0;i-=c,f+=c,c=0)for(j=1;j<10;c+=i-j++<0?0:1);return new Integer(a[0]+""+a[1]+"0"+f);}
```
[Try it online!](https://tio.run/##VU@xboMwEJ3LV5yY7BosI7VLHKdbpQ6dMiIGFwy1SwwyR6oo4tup01KpveHu9PTuvXtOn3U@jMa75mO1p3EICC5ifEbb83b2NdrB83uZJOP81tsa6l5PE7xq6@Ga3G3ghBrjeN74@xePpjOhrDLY1gM0oGDV@eF6xGB9B61KU9kOgViPYBVpmS5FRXlvfIfvhGa1EpmT9iCkzVWdtSy2iNHbjVOFdPtCyJopmzvG9uJJ7Aoqg8E5ePDm89eZ3GRZmkb5Ik6RspbKZZUQK7m1/xnOg23gFOORnz/LCnToJhrTwlbHy4TmxIcZ@Rgp2HvScD2O/YX88S2rayFE9viwUCq/b5dkWb8A "Java (OpenJDK 8) – Try It Online")
Depair function
```
r->{String a=r+"",t=a.substring(a.lastIndexOf('0')+1);int l=0,i=l,o=t.length();for(;i<o;l+=r.decode(t.charAt(i++)+""));return new int[]{r.decode(a.substring(0,l)),r.decode(a.substring(l,a.length()-o-1))};}
```
[Try it online!](https://tio.run/##bVA9a8MwEJ3rX3F4iVTLwqbtpDjQpZChdMhoPCi24ihVJCOf04bg3@4qH4QWesMJ3j29d/d28iBT1ym7az4nve@cR9gFjA@oDd8MtkbtLH8UUdQNa6NrqI3se3iX2sIperiBPUoMz9uNP19aVK3yDLTFslqAggImny5OK/TatiALn8Qxw0Lyflj3F5BIHqRxaRv1/bEhs2xGk5yKoACmyJguDHMFcqNsi1tCxcZ5IvTcCZMUnjeqdo0iyOut9K9IdJLQYEGp8AoHb8Gqr@s2pzv5t3nGDKXs35Fh8u6aujSndBTjJCBUdG5/Mzg43cA@xEOut5YVSN/29JzWxR9kCENx2XXmSPIse3nOnqi4KJ1rdexR7bkbkHfhPxpLZJlVkEDM4tBlmVc3@hiN0w8 "Java (OpenJDK 8) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 + 11 = 17 bytes
Port of my Jelly answer.
Domain: positive integers.
Takes a list `[x, y]` as input, returns `z`.
```
{`<LO+
```
[Try it online!](https://tio.run/##MzBNTDJM/f@/OsHGx1/7//9oQx0F41gA "05AB1E – Try It Online")
Takes a positive integer `z` as input, returns `[min(x, y), max(x, y)]`.
```
L2ã€{RÙR¹<è
```
[Try it online!](https://tio.run/##MzBNTDJM/f/fx@jw4kdNa6qDDs8MOrTT5vCK//9NAA "05AB1E – Try It Online")
-5 thanks to [Emigna](https://codegolf.stackexchange.com/users/47066/emigna).
[Answer]
# JavaScript, 72 bytes
```
f=a=>eval('0x'+a.sort().join`a`)
g=n=>n.toString(16).split`a`.map(x=>+x)
```
Works for positive integers (in theory). Quite simple idea: sort two number in some (magic) order, connect them as string by a letter `"a"`, parse it as hex integer.
```
f=a=>eval('0x'+a.sort().join`a`)
g=n=>n.toString(16).split`a`.map(x=>+x)
```
```
<pre oninput="p.value=f([+x.value, +y.value])">
X = <input id="x" type="number" min="0" />
Y = <input id="y" type="number" min="0" />
f(X,Y)= <output id="p"></output>
</pre>
<pre oninput="q.value=g(+u.value).join(', ')">
U = <input id="u" type="number" />
g(U)= <output id="q"></output>
</pre>
```
[Answer]
# MATL, 6+8=14 bytes
Encoding function, takes two inputs n, m. Outputs product of nth prime and mth prime.
```
,iYq]*
```
Steps:
* `,` - Do twice
* `i` - Push input
* `Yq` - Pop input, push input'th prime
* `]*` - End do twice, pop both primes and push product
---
Decoding function, takes one input m. Outputs the number of primes below each of the prime factors of n.
```
iYf"@Zqn
```
Steps:
* `i` - Push input
* `Yf` - Pop input, push array of prime factors
* `"` - For n in array
* `@Zq` - Push array of primes below n
* `n` - Pop array, push length of array
This is commutative because multiplication is commutative, and injective because prime factorizations are unique. Not that this is not onto the integers.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5+3=8 bytes
I really hope I got the challenge right, I see some deleted answers that seem valid to me...
Couples of positive integers to a single positive integer:
```
¤*!İp
```
[Try it online!](https://tio.run/##yygtzv7//9ASLcUjGwr@//9v/N8IAA "Husk – Try It Online")
It works by taking the numbers at the given indices (1-indexed) from the list of prime numbers, and multiplying them.
Result of the first function to couples of positive integers:
```
mṗp
```
[Try it online!](https://tio.run/##yygtzv7/P/fhzukF////NzQFAA "Husk – Try It Online")
We factorize the input number and return the index in the list of primes of all (both) of its factors.
### Worked example
Given `(4,1)` as a starting couple, we take the fourth and first prime numbers `(7,2)` and multiply them → `14`. This multiplication is what makes the function indipendent on the order of the two elements.
Starting from `14`, we factorize it `(2,7)` and return the indices of `2` and `7` in the list of prime numbers → `(1,4)`.
[Answer]
## [C#](http://csharppad.com/gist/762f6e301f0ea55178a4e121663c1c68), 80 bytes ( 38 + 42 )
---
### Data
### Encoder
* **Input** `Int32` `l` A number
* **Input** `Int32` `r` A number
* **Output** `Int64` Both ints fused together
### Decoder
* **Input** `Int32` `v` The value
* **Output** `Int32[]` An array with the two original ints.
---
### Golfed
```
// Encoder
e=(l,r)=>{return(long)l<<32|(uint)r;};
// Decoder
d=v=>{return new[]{v>>32,v&0xFFFFFFFFL};};
```
---
### Ungolfed
```
// Encoder
e = ( l, r ) => {
return (long) l << 32 | (uint) r;
};
// Decoder
d = v => {
return new[] {
v >> 32,
v & 0xFFFFFFFFL };
};
```
---
### Ungolfed readable
```
// Encoder
// Takes a pair of ints
e = ( l, r ) => {
// Returns the ints fused together in a long where the first 32 bits are the first int
// and the last 32 bits the second int
return (long) l << 32 | (uint) r;
};
// Decoder
// Takes a long
d = v => {
// Returns an array with the ints decoded where...
return new[] {
// ... the first 32 bits are the first int...
v >> 32,
// ... and the last 32 bits the second int
v & 0xFFFFFFFFL };
};
```
---
### Full code
```
using System;
using System.Collections.Generic;
namespace TestBench {
public class Program {
// Methods
static void Main( string[] args ) {
Func<Int32, Int32, Int64> e = ( l, r ) => {
return(long) l << 32 | (uint) r;
};
Func<Int64, Int64[]> d = v => {
return new[] { v >> 32, v & 0xFFFFFFFFL };
};
List<KeyValuePair<Int32, Int32>>
testCases = new List<KeyValuePair<Int32, Int32>>() {
new KeyValuePair<Int32, Int32>( 13, 897 ),
new KeyValuePair<Int32, Int32>( 54234, 0 ),
new KeyValuePair<Int32, Int32>( 0, 0 ),
new KeyValuePair<Int32, Int32>( 1, 1 ),
new KeyValuePair<Int32, Int32>( 615234, 1223343 ),
};
foreach( KeyValuePair<Int32, Int32> testCase in testCases ) {
Console.WriteLine( $" ENCODER: {testCase.Key}, {testCase.Value} = {e( testCase.Key, testCase.Value )}" );
Console.Write( $"DECODING: {e( testCase.Key, testCase.Value )} = " );
PrintArray( d( e( testCase.Key, testCase.Value ) ) );
Console.WriteLine();
}
Console.ReadLine();
}
public static void PrintArray<TSource>( TSource[] array ) {
PrintArray( array, o => o.ToString() );
}
public static void PrintArray<TSource>( TSource[] array, Func<TSource, String> valueFetcher ) {
List<String>
output = new List<String>();
for( Int32 index = 0; index < array.Length; index++ ) {
output.Add( valueFetcher( array[ index ] ) );
}
Console.WriteLine( $"[ {String.Join( ", ", output )} ]" );
}
}
}
```
---
### Releases
* **v1.0** - `80 bytes` - Initial solution.
---
### Notes
* None
[Answer]
# Python: 41+45=86
## encoder: 41
```
e=lambda*x:int('1'*max(x)+'0'+'1'*min(x))
```
>
>
> ```
> e(4, 3), e(3,4)
>
> ```
>
> (11110111, 11110111)
>
>
>
## decoder: 45
```
d=lambda z:[len(i)for i in str(z).split('0')]
```
>
>
> ```
> d(11110111)
>
> ```
>
> [4, 3]
>
>
>
# Older attempt:
Python: 114: 30 + 84
## encoder: 30
accepts 2 integers, returns a string
```
e=lambda*x:2**max(x)*3**min(x)
```
>
>
> ```
> e(3, 4), e(4, 3)
>
> ```
>
> (432, 432)
>
>
>
## decoder: 86
```
def d(z):
x=y=0
while 1-z%2:
x+=1
z/=2
while 1-z%3:
y+=1
z/=3
return x,y
```
>
>
> ```
> d(432)
>
> ```
>
> 4, 3
>
>
>
## decoder2: 120
another attempt with generator comprehensions and sum
```
def d(z):
x=sum(1 for i in range(z)if not z%(2**i))-1
z/=2**x
return x,sum(1 for i in range(int(z))if not z%(3**i))-1
```
]
|
[Question]
[
Given an integer \$ n \$ \$ (n \ge 1) \$, return/output the total number of set bits between \$ 1 \$ and \$ n \$ inclusive. To make the problem more interesting, **your solution must run with a time complexity of** \$ \mathcal{O}((\log n)^k) \$ **or better, for some constant** \$ k \$ **(AKA poly-logarithmic time complexity)**.
This is [OEIS A000788](https://oeis.org/A000788), not including \$ n = 0 \$. Here are the first 100 numbers:
```
1, 2, 4, 5, 7, 9, 12, 13, 15, 17, 20, 22, 25, 28, 32, 33, 35, 37, 40, 42, 45, 48, 52, 54, 57, 60, 64, 67, 71, 75, 80, 81, 83, 85, 88, 90, 93, 96, 100, 102, 105, 108, 112, 115, 119, 123, 128, 130, 133, 136, 140, 143, 147, 151, 156, 159, 163, 167, 172, 176, 181, 186, 192, 193, 195, 197, 200, 202, 205, 208, 212, 214, 217, 220, 224, 227, 231, 235, 240, 242, 245, 248, 252, 255, 259, 263, 268, 271, 275, 279, 284, 288, 293, 298, 304, 306, 309, 312, 316, 319
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
[Answer]
# JavaScript (ES6), ~~57 54 53~~ 52 bytes
```
n=>(i=0,g=b=>b--&&(n>>b&1&&b+i+i++<<b)+g(b))(32)/2+i
```
[Try it online!](https://tio.run/##PYVLCoMwFAD3nuItJOSRp1X7R5NdT1EKGqs2RZKipRvx7GlLPwwzc60e1VgP5naPrDs3vpXeSsWNTKiTWiodRYxxq5RmKWNamBeiKDSKjmtEvsxwkQnj82NKkBEsCVYEa4INwZZgR7AnSJO3n3z72//JKYhbNxyq@sItSAVTAFA7O7q@iXvX8bLi4WRnBAnh1HKLc4l5MKN/Ag "JavaScript (Node.js) – Try It Online")
This is designed for 32-bit integers and always performs 32 iterations, no matter the input value.
The following version performs \$\lfloor log\_2(n)\rfloor+1\$ iterations instead, but this is really pointless since bitwise operations on vanilla JS numbers [1] are limited to 32 bits anyway:
```
n=>(i=0,g=b=>b--&&(n>>b&1&&b+i+i++<<b)+g(b))(32-Math.clz32(n))/2+i
```
[Try it online!](https://tio.run/##PY3JCoMwFEX3fsVbSEjwaR06osmuy35BKZikTkWSotJFxW@3lg5czjnLe5MP2euuuQ@@sddiLvlsuKAND7Hiigvl@4RQI4QiESHKa5Z5WaaYV1HFGE1i/ySHOtDtM4mpYWwVe82cniOEGCFBWCNsELYIO4Q9wgEhCt989PUv/4YXJyhtd5S6pga4gNEB0Nb0ti2C1lY0l9QdzcSAgzuWy/GUs9SZ2PwC "JavaScript (Node.js) – Try It Online")
[1]: i.e. without using BigInts or a Big Integer library
### How?
As mentioned by Emeric Deutsch in [A001787](https://oeis.org/A001787), the total sum of set bits between \$1\$ and \$2^k-1\$ is:
$$k\times 2^{k-1}$$
Below is an illustration of the first few terms:
```
1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111
V \___/ \_____________/ \_____________________________________/
count: 1 3 8 20
sum : 1 4 12 32
```
Because we only need one extra bit to go from \$2^k-1\$ to \$2^k\$, the total sum of set bits between \$1\$ and \$2^k\$ is:
$$k\times 2^{k-1}+1$$
In order to compute the total sum of set bits between \$1\$ and an arbitrary integer \$N\$ of \$M+1\$ bits, we can use the above formula for each set bit at position \$0\le b\le M\$ in \$N\$. But we also have to take the total number of set bits at a position higher than \$b\$ into account, because they have to be counted several times.
We end up with:
$$\sum\_{b=0}^{M} B(b)\times(b\times 2^{b-1}+1+S(b)\times 2^b)$$
where:
* \$B(b)\$ is the value of the bit \$b\$ (0-indexed)
* \$S(b)=\sum\_{i=b+1}^{M} B(i)\$
[Here](https://tio.run/##PVDLboMwELzzFXOIKjs4ESR9RQ4cIvULcqwqBVNoqZAdAckF@dvp2uAcdndGs55d719xL/qya67DRpvvaprqmy6HxmjUTHOMEdBWA07IoJDl0MhzQk9I5SKdgzR62hNNJGrTMUcbr8bUTvCYYe9AHHPqizOcWMMlumq4dRq9hI0W09nFsWCkZl8VTJQzceshWCmONZiitMPaow1S7mZTnGfZK4rTM0vxGBzZSX6mAjuBvcCzwIvAq8CbwLvAQSBNXMxpyaE8avIVbWnZj6L8ZdrfgyaURvemrbat@WGXgq1GbTl9ZDW669oLp8l8@gc) is an ungolfed implementation.
In the golfed version, we go from the most to the least significant bit and keep track of the number of set bits in `i`. Besides, we ignore the `+1` in the formula and add `i` at the very end of the process instead.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~45~~ 32 bytes
```
{+/b*1+(q!'x)+-2!q*<q:2/=#b:2\x}
```
[Try it online!](https://ngn.bitbucket.io/k#eJztkkFu3TAMRPc6BT+6SBs5sEhJtvTR9CTdJIssC3xk84GgPXvnOS3Qoj1BEECmORyJHI39dH7J6+Ot54+X0831U76L0+X28+Uc6/2Hx3N8vX5P6enGPNvJS0kP357P5ovFYm2xvti+2FzMhb3qUcVViqJHtRCOsVhVXsVX4Sq+iW/0EG7iu/JOQ3GbuE35pnzXqF17hmpD+VCPAdaZqdoUnptmlkJARUFCEe+HqEORHxLRhxivbEaOV84ixhuw7VzBCRCdYxsEWnyn3w6BFB9kkxoqfDJoHnfn8mgJtARaAi3hjcCWV3+AAaw4ijeBlsCZaAfkbD+MBCIoEBQbBO4E9sQOMeiHM4GgmPheGmEjaEtFRnWgT76l/bA/Pm5ak5sVM2cVPeuqT2R3X7Aw1ZARNsyaKUsivLL0FuzUrRqcqdco2Wt2yzI99yNp2bOn2agNhY0k/T2zHDPb68z+z8ymbqzG1v/OjN8z26+ZhZmV2q7QNe/9930Dv+9PwvLWyg==)
*Golfing ideas thanks to @ngn and @coltim*
The OEIS page contains a curious PARI program:
```
a(n)=if(n==0,0,m=logint(n,2);r=n%2^m;m*2^(m-1)+r+1+a(r));
```
which has a recursion depth of \$\mathcal{O}(\log n)\$ and each recursive call involves constant number of arithmetic operations (and therefore meets the time complexity requirement).
I translated this recursive formula to vectorized operations on the bit pattern of n, keeping array dimensions to the number of bits of n, so every built-in op takes polylog time of n.
```
1 0 1 1 0 0 // n = 44 -> 115
5 4 3 2 1 0 // m
16 8 4 2 1 0 // 2^(m-1)
12 12 4 0 0 0 // n mod 2^(m-1)
93 17 5 // m * 2^(m-1) + n mod 2^(m-1) + 1,
// keeping only ones in the bits of n
sum = 115
```
How the solution works:
```
{+/b*1+(q!'x)+-2!(<q)*q:2/=#b:2\x} x:n
b:2\x b:bit pattern of n
q:2/=#b q:reversed powers of 2
=# identity matrix of size #b
2/ evaluate in base 2 column-wise
-2!(<q)*q m*2^(m-1) for m in #b-1..0
<q grade up q; the power is in decreasing order
so it gives #b-1..0
-2!( )*q multiply 2^m and divide by 2
(q!'x)+ add n%2^m
1+ add 1
+/b* add the terms corresponding to one bits
```
[Answer]
# JavaScript (ES6), 51 bytes
```
f=(n,i=0,p=1<<i)=>n<p?0:f(n,i+1)+(n&p&&n%p+1+p*i/2)
```
[Try it online!](https://tio.run/##FYvRCoMwDAC/ZiUxdWv3uLX6LeKsZEgSdPj7XYXjHg7uO53TMe9sv170s9SSGyCec/CWY0qMeZBkY3iVK1NEAnHmnNyMIlnHjyfWoju05c0phmYinFUO3Zb7piuwL8CI9Q8 "JavaScript (Node.js) – Try It Online")
Let we denote
$$ n = \left(\overline{b\_mb\_{m-1}\dots b\_2b\_1b\_0}\right)\_2 $$
Then
$$ f\left(n\right)=\sum\_{i=0}^{m} b\_i \cdot \left(\left(n \bmod 2^i\right) + 1 + 2^{i-1}\cdot i\right) $$
This function loops from \$0\$ to \$m\$ with constant time each loop. And we have
$$ m = \mathcal{O}\left(\log n\right) \ $$
It would be [55 bytes](https://tio.run/##LYoxDsIwDABfQ2UXGTWlbHEGNp4RlTQyVE5FIgaGPp1QBDfdSXfzT5/HhyyFNF1DnbgqO4gs7NQ5aZoItAru4VegOzZqrSCtINYSCSJCp1jHpDnN4TCnCBOcJV60wNBj2/7d9MfhtN31nZYi210pFz/eKcsrsOm@fAA) to handle larger numbers (BigInt).
[Answer]
# [Python 3](https://docs.python.org/3/), ~~106~~ 104 bytes
```
def f(A):
A+=1;a=0
for i in range(32):
x=2<<i;d,r=A//x,A%x;a+=d*x/2
if 2*r>x:a+=r-x/2
return a
```
[Try It Online!!](https://tio.run/##RYyxDoMgFEV3vuItTUBtVNxUmvAdTQcapCVRNE@avH49RZcOdznn5mzf@F5Dl5KdHDiuRc9Al6odjGoYuBXBgw@AJrwm3slDAyk5jn6wFSpd11TpCw2mVLagWmbtHcgCb9RnhteT4RQ/GMAAsDT7HdSdzjb9223TiAfLMvLFbHw2y9MaoH5DHyI/5jiVrRCigvwSIv0A)
This is designed for 32-bit integers, here I am using float to save some bytes from "//" operator, I hope you won't mind \$x.0\$ instead of \$x\$, further bytes can be reduced if I allow hardcoding input by user.
P.S. This is my first answer, hope to hear some suggestions.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes
```
NθIΣE⮌↨θ²⁺×÷θX²⊕κX²κ×ι⊕﹪θX²κ
```
[Try it online!](https://tio.run/##VYw5DsIwFER7TuHyWzJNRJcOaFwEWYELGOdLWPGSeOP4JosoMsVIo5k36iOD8tLUyt2U0yPbNwaYaXsSQbsENxkTPLOFTk7QY8EQEa5ysZmRhlJGhMkRXtpiBO7SXRc9bKXw3@WpYYQ7FdCiSzjASDfkX41r2ll9HHZ@yMYfflZ2V1vrpannYn4 "Charcoal – Try It Online") Explanation: For a given bit position `k`, the sum of the bits at position `k` from `1` to `n` depends on whether the `k`th bit of `n` is `0` or `1`:
* If the `k`th bit of `n` is `0`, then the bits at position `k` are of the form `0...1...0...1...0...1...0..0`. Each run of `2ᵏ⁺¹` integers contributes `2ᵏ` bits.
* If the `k`th bit of `n` is `1`, then the bits at position `k` are of the form `0...1...0...1...0...1...0...1..1`. This means that there are `(n mod 2ᵏ)+1` extra `1` bits to account for.
Since the number of bits is O(log n), this is the major factor in the time complexity of the algorithm.
```
Nθ Input `n` as an integer
θ `n`
↨ ² Converted to base 2
⮌ Reversed so LSB first
E Map over bits
θ Input `n`
÷ Integer divide by
² Literal 2
X Raised to power
κ Index `k`
⊕ Incremented
× Multiplied by
² Literal 2
X Raised to power
κ Index `k`
⁺ Plus
ι Current bit
× Multiplied by
θ Input `n`
﹪ Modulo
² Literal `2`
X Raised to power
κ Index `k`
⊕ Incremented
Σ Take the sum
I Cast to string
Implicitly print
```
[Answer]
# [Python 3](https://docs.python.org/3/), 81 bytes
```
def f(A):
c=0
while A>1:
a=len(bin(A))-3;A=A%(2**a);c+=2**a*a/2+A
return c
```
[Try it online!](https://tio.run/##FYxBCsMgEADvvmIvhdVQasylNFjwKdZqsxA2shhKX2@T2zAMU39t2Xi6V@n9nQsUDPqhIHmr4LvQmiE8x0NA9GtmfBEfgb5Oc/Dhgs6YqOc0@BNMvLkhKJDcdmFIoHrZBAiIQSJ/Mo7WnvMqxA0L0uC07n8 "Python 3.8 (pre-release) – Try It Online")
For exponentials of 2 -1 every bit is flipped 50% of the time so the total sum of bits is `n*(# of bits)/2` this gets done recursively. For every further recursion we also need to add up the first bits that get progessively ignored.
[Answer]
# [Python 3](https://docs.python.org/3/), 64 bytes
```
f=lambda n:n and(2*f(n//2)+n//2+1if n%2else f(n/2)+f(n/2-1)+n/2)
```
[Try it online!](https://tio.run/##HYxBCsMgFETX6Sk@gYK/SUk1O6GHsUTbD8lEjF309FazmBl4M0z85c@OuZTwXN32WhzBghwWZW5BYZoMD80HLYFwNX49PLWi8jPuug0Ml7AnEhJQcnh7JchV8ZsVM9tLF9NJRuptP9YHYS768Qc "Python 3 – Try It Online")
from the recurrence relation: a(0) = 0, a(2n) = a(n)+a(n-1)+n, a(2n+1) = 2a(n)+n+1
[Answer]
# Python 3.8 (59 bytes)
```
f=lambda n:n and(r:=2**(m:=len(bin(n))-3))*m/2+n%r+1+f(n%r)
```
Here is my attempt 2, since `dingledooper` noted that my previous attempt was not polylog time complexity.
Also, the golfiness can probably be improved by using walrus operator in python3.8
I used the formula found from "a curious PARI program on the OEIS page":
`a(n) = if (n==0, 0, m = logint(n, 2); r = n % 2^m; m*2^(m-1) + r + 1 + a(r));`
My ungolfed code is:
```
def a(n):
output = 0.0
while n:
logn = n.bit_length() - 1 # log(n) in base 2, golfed: len(bin(n))-3
n = n % (2 ** logn) # strip top bit, golfed: n%r
output += logn*2**(logn-1) + n + 1 # golfed: m*r/2+n%r+1
return output
```
]
|
[Question]
[
A Russian nesting doll, more commonly known as a [Matryoshka doll](https://en.wikipedia.org/wiki/Matryoshka_doll), is a doll which contains a smaller version of itself, which then contains another smaller version of itself, which contains a smaller version of itself, which contains a smaller version of itself, which contains a smaller version of itself... - until finally, the last one is empty.
Today your goal is to emulate this Russian tradition by writing a program or function that, when it contains itself N times, will print itself containing N-1 copies of itself times.
For example, the doll program `abcd` will have the N=3 program `abababcdcdcd`, which will print the N=2 program `ababcdcd`, which prints the original N=1 program `abcd`, which finally prints N=0, which is empty. This should theoretically work for any reasonable value of N.
Rules:
* Here is a [TIO program](https://tio.run/##PY0xDoMwDEX3nMJbh0BP4Hrv0gtYGQgYgVCTioSinj51QK0ly9Z737JfuzmMW7@UB9zAahkiKg1T4wwyt2TRIaMjbtGSDnKopiI0bAA0QnxVY0/olFGNUZWHOnhte4q2ZvBHdbf/utY3eO6kl2hZkatHxpV7eG0ZgsiQIEfwAl0AeUuA7hm3kCGO4D9ZEsQ8ybrPSSBPc4IhSgqXDHtcl9L5fvgC "brainfuck – Try It Online") to help generate doll programs based on your program
* [Standard Quine Rules apply](https://codegolf.meta.stackexchange.com/q/4877/76162)
* [Standard Loopholes apply](https://codegolf.meta.stackexchange.com/q/1061/76162)
* 'Contains' means directly in the center of the previous version, so your solution must have a positive even number of bytes. A program of length 10 will have a copy of the original inserted after the fifth byte, then another after the tenth byte etc.
* A single trailing whitespace is allowed in the output
* As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), your goal is to make your N=1 program as short as possible.
* An explanation of your code would be appreciated
[Answer]
# [Underload](https://github.com/catseye/stringie), 4 bytes
N=1: [Try it online.](https://tio.run/##K81LSS3KyU9M@f9fQUMz@P9/AA)
```
()S
```
N=2: [Try it online.](https://tio.run/##K81LSS3KyU9M@f9fQUNBQzNYM/j/fwA)
```
( ()S)S
```
N=3: [Try it online.](https://tio.run/##K81LSS3KyU9M@f9fQQMENYNB8P9/AA)
```
( ( ()S)S)S
```
**Explanation:**
Self-explanatory, but I add it anyway.
* `(...)S` prints anything between the parenthesis to STDOUT
* The space before it is a no-op to make the byte-count even and comply to the rules of the challenge.
[Answer]
# JavaScript, ~~36~~ 32 bytes
Takes advantage of the fact that `Function.prototype.toString()` takes no arguments and will therefore ignore any that are passed to it.
Partly inspired by [user202729's solution](https://codegolf.stackexchange.com/a/154637/58974).
```
f=_=>f.toString( ).slice(14,-16)
```
---
## Try it
```
o.innerHTML=["<span>Five</span>",(f=_=>f.toString(f=_=>f.toString(f=_=>f.toString(f=_=>f.toString(f=_=>f.toString( ).slice(14,-16) ).slice(14,-16) ).slice(14,-16) ).slice(14,-16) ).slice(14,-16))(),"<span>Four</span>",(f=_=>f.toString(f=_=>f.toString(f=_=>f.toString(f=_=>f.toString( ).slice(14,-16) ).slice(14,-16) ).slice(14,-16) ).slice(14,-16))(),"<span>Three</span>",(f=_=>f.toString(f=_=>f.toString(f=_=>f.toString( ).slice(14,-16) ).slice(14,-16) ).slice(14,-16))(),"<span>Two</span>",(f=_=>f.toString(f=_=>f.toString( ).slice(14,-16) ).slice(14,-16))(),"<span>One</span>",(f=_=>f.toString( ).slice(14,-16))(),"<span>Thunderbirds Are Go!</span>"].join`\n`
```
```
span{font-weight:bold;font-size:16px;line-height:1.5em;text-transform:uppercase;}span:last-child{font-size:8px;}
```
```
<pre id=o></pre>
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 46 bytes
Full program. So `console.log` is necessary.
Use an idea from [this answer](https://codegolf.stackexchange.com/a/154642/69850) to save some bytes.
```
l=console.log; g=_=>{};l((''+g).slice(4,-1))
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/xzY5P684PydVLyc/3VpBQSHdNt7WrrrWOkdDQ11dO11TrzgnMzlVw0RH11BT8/9/AA "JavaScript (Node.js) – Try It Online") [Try it online twice!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/xzY5P684PydVLyc/3VpBQSHdNt7WrhqHcK11joaGurp2uqZecU5mcqqGiY6uoaYmDuH//wE "JavaScript (Node.js) – Try It Online") [Try it online, three times!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/xzY5P684PydVLyc/3VpBQSHdNt7Wrpo04VrrHA0NdXXtdE294pzM5FQNEx1dQ01N0oT//wcA "JavaScript (Node.js) – Try It Online")
---
My approach is similar to that used in Kevin Cruijssen's [answer](https://codegolf.stackexchange.com/a/154636/69850), find a nestable structure (a function in this case).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
Ṿḣ-9Ḋð}“““““““““
```
[Try it online!](https://tio.run/##y0rNyan8///hzn0PdyzWtXy4o@vwhtpHDXNwof//AQ "Jelly – Try It Online")
Doubled: [Try it online!](https://tio.run/##y0rNyan8///hzn0PdyzWtXy4o@vwhtpHDXMwBEhF//8DAA "Jelly – Try It Online")
Tripled: [Try it online!](https://tio.run/##y0rNyan8///hzn0PdyzWtXy4o@vwhtpHDXMIC1AL/f8PAA "Jelly – Try It Online")
---
Jelly doesn't have any nestable structure, but its string literals are auto-terminated.
```
Ṿḣ-9Ḋ First chain. (monadic)
Ṿ Une**Ṿ**al. (to string)
ḣ-9 Take the **ḣ**ead, ends at the *-9*'th character.
Ḋ **Ḋ**equeue, remove the first character.
ð Terminate the first chain, start a new one.
} Convert the last monadic chain to a dyadic one.
“““““““““ String literal.
This matches the pattern <dyad> <nilad>, so applies
the the corresponding rules. This way a link can take data
to the right of it.
```
---
Will try different approaches to see if they can be shorter.
[Answer]
# [DipDup](https://github.com/AlephAlpha/DipDup), 2 bytes
```
[]
```
It pushes the list onto the stack, and prints it without the outmost brackets.
N = 1: [Try it online!](https://tio.run/##ZVRNj9owEL3nV0wjJBJRuPWClr0gKlVqVVR6i9KsN5hibWJbjilB6n@nM@N8LeVAxm/emy9PchbNm6yq@13V1jgPP2XrV3vhGum2pn5VWnjjmtUPKY77KDoKL5DiatjAFrZn4eAv7GDXWhdF/mYlm@jMiJRHkdKNF7qUcDiba1Bez9LJCPDXEJZsoUxJUeYTcAeSwDiLYbEImCQrzuOB9VU1HjnJYpHCCkqjS@G/Ccu@SWYq/TGzQ6zZO1miHoUYZ8bYvvCmOLBJioHbpXqghLZ7MqzXnGvPyUZ4Qy0@zZ6hEV41pxskL9r4XSXrF@wvj9MUG1tQy0R6lf4qpYakpOHOs3namzmafdY0pOVhD2m5nAHeQC30bWwl3N3Bi/INfUG5XAcAh3VSrYNPBNHolA/E9UjoIbypnJUDhDdv7ECF5XOohMCkZWpBd9l2G/L5omnsA7mLIf@Iqh8jP9FF1NHRL0UiKWg6cWxh/mtOrqOy7@EiwJcH@APD1jzAa4ZpIUa8QEQdQ339vPk5ra@b@KlSFlfxZKpjhRvFxz5QiDBV85QY3AANazUKmDIZMPZFSs5HdjfXG/83VHQwB20LDaouE9VlUDE/mB0QRdaMVLKTYqSim0Yy@PnwfwV4PXiCNu1jOtlthVP6d7hpshhX2l7ojSpFIyFr8SuStB8hjlN4Woa3M1ByMCd@C7M2pxD8JZhxn7hQ5CgIls4ZB7Gl71Y4xFFUC6WpgC/fIUnDCa9Se@lE6TGJvd@z/B8 "Haskell – Try It Online")
N = 2: [Try it online!](https://tio.run/##ZVRNj9owEL3nV0wjJBJRuPWClr0gKlVqVVR6i9KsN5hibWJbjilB6n@nM@N8LeVAxm/emy9PchbNm6yq@13V1jgPP2XrV3vhGum2pn5VWnjjmtUPKY77KDoKL5DiatjAFrZn4eAv7GDXWhdF/mYlm@jMiJRHkdKNF7qUcDiba1Bez9LJCPDXEJZsoUxJUeYTcAeSwDiLYbEImCQrzuOB9VU1HjnJYpHCCkqjS@G/Ccu@SWYq/TGzQ6zZO1miHoUYZ8bYvvCmOLBJioHbpXqghLZ7MqzXnGvPyUZ4Qy0@zZ6hEV41pxskL9r4XSXrF@wvj9MUG1tQy0R6lf4qpYakpOHOs3namzmafdY0pOVhD2m5nAHeQC30bWwl3N3Bi/INfUG5XAcAh3VSrYNPBNHolA/E9UjoIbypnJUDhDdv7ECF5XOohMCkZWpBd9l2G/L5omnsA7mLIf@Iqh8jP9FF1NHRL0UiKWg6cWxh/mtOrqOy7@EiwJcH@APD1jzAa4ZpIUa8QEQdQ339vPk5ra@b@KlSFlfxZKpjhRvFxz5QiDBV85QY3AANazUKmDIZMPZFSs5HdjfXG/83VHQwB20LDaouE9VlUDE/mB0QRdaMVLKTYqSim0Yy@PnwfwV4PXiCNu1jOtlthVP6d7hpshhX2l7ojSpFIyFr8SuStB8hjlN4Woa3M1ByMCd@C7M2pxD8JZhxn7hQ5CgIls4ZB7Gl71Y4xFFUC6WpgC/fIUnDCa9Se@lE6TGJvd@zLM//AQ "Haskell – Try It Online")
N = 3: [Try it online!](https://tio.run/##ZVRNj9owEL3nV0wjJBJRuPWClr0gKlVqVVR6i9KsN5hibWJbjilB6n@nM@N8LeVAxm/emy9PchbNm6yq@13V1jgPP2XrV3vhGum2pn5VWnjjmtUPKY77KDoKL5DiatjAFrZn4eAv7GDXWhdF/mYlm@jMiJRHkdKNF7qUcDiba1Bez9LJCPDXEJZsoUxJUeYTcAeSwDiLYbEImCQrzuOB9VU1HjnJYpHCCkqjS@G/Ccu@SWYq/TGzQ6zZO1miHoUYZ8bYvvCmOLBJioHbpXqghLZ7MqzXnGvPyUZ4Qy0@zZ6hEV41pxskL9r4XSXrF@wvj9MUG1tQy0R6lf4qpYakpOHOs3namzmafdY0pOVhD2m5nAHeQC30bWwl3N3Bi/INfUG5XAcAh3VSrYNPBNHolA/E9UjoIbypnJUDhDdv7ECF5XOohMCkZWpBd9l2G/L5omnsA7mLIf@Iqh8jP9FF1NHRL0UiKWg6cWxh/mtOrqOy7@EiwJcH@APD1jzAa4ZpIUa8QEQdQ339vPk5ra@b@KlSFlfxZKpjhRvFxz5QiDBV85QY3AANazUKmDIZMPZFSs5HdjfXG/83VHQwB20LDaouE9VlUDE/mB0QRdaMVLKTYqSim0Yy@PnwfwV4PXiCNu1jOtlthVP6d7hpshhX2l7ojSpFIyFr8SuStB8hjlN4Woa3M1ByMCd@C7M2pxD8JZhxn7hQ5CgIls4ZB7Gl71Y4xFFUC6WpgC/fIUnDCa9Se@lE6TGJvd@zLMvz/B8 "Haskell – Try It Online")
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 4 bytes
```
[]p
```
Similar to some other answers, since strings in `dc` have start (`[`) and end (`]`) delimiters (that is, `"` doesn't perform both duties, etc.), they're nestable without any real effort. `p` to print.
N=1: [Try it online!](https://tio.run/##S0n@/18hOrbg/38A "dc – Try It Online")
N=2: [Try it nested!](https://tio.run/##S0n@/18hWiE6tiC24P9/AA "dc – Try It Online")
N=3: [Try it nesteder!](https://tio.run/##S0n@/18hGgRjC0Dw/38A "dc – Try It Online")
[Answer]
# [Tcl](http://tcl.tk/), 12 bytes
```
puts {}
```
[Try it online!](https://tio.run/##K0nO@f@/oLSkWKEamaxVAAFk8v9/AA "Tcl – Try It Online")
It's just another language that also has this.
]
|
[Question]
[
## Input:
We take two inputs:
* An input `b` with two distinct values: `Left` and `Right`.*†*
* And a positive integer `n`.
## Output:
Based on the Left/Right input, we output either of the following two sequences in the range of `1-n` (in the sequences below the first 125 items are displayed):
```
Left:
1, 6, 7, 56, 57, 62, 63, 960, 961, 966, 967, 1016, 1017, 1022, 1023, 31744, 31745, 31750, 31751, 31800, 31801, 31806, 31807, 32704, 32705, 32710, 32711, 32760, 32761, 32766, 32767, 2064384, 2064385, 2064390, 2064391, 2064440, 2064441, 2064446, 2064447, 2065344, 2065345, 2065350, 2065351, 2065400, 2065401, 2065406, 2065407, 2096128, 2096129, 2096134, 2096135, 2096184, 2096185, 2096190, 2096191, 2097088, 2097089, 2097094, 2097095, 2097144, 2097145, 2097150, 2097151, 266338304, 266338305, 266338310, 266338311, 266338360, 266338361, 266338366, 266338367, 266339264, 266339265, 266339270, 266339271, 266339320, 266339321, 266339326, 266339327, 266370048, 266370049, 266370054, 266370055, 266370104, 266370105, 266370110, 266370111, 266371008, 266371009, 266371014, 266371015, 266371064, 266371065, 266371070, 266371071, 268402688, 268402689, 268402694, 268402695, 268402744, 268402745, 268402750, 268402751, 268403648, 268403649, 268403654, 268403655, 268403704, 268403705, 268403710, 268403711, 268434432, 268434433, 268434438, 268434439, 268434488, 268434489, 268434494, 268434495, 268435392, 268435393, 268435398, 268435399, 268435448, 268435449
Right:
1, 4, 7, 32, 39, 56, 63, 512, 527, 624, 639, 896, 911, 1008, 1023, 16384, 16415, 16864, 16895, 19968, 19999, 20448, 20479, 28672, 28703, 29152, 29183, 32256, 32287, 32736, 32767, 1048576, 1048639, 1050560, 1050623, 1079296, 1079359, 1081280, 1081343, 1277952, 1278015, 1279936, 1279999, 1308672, 1308735, 1310656, 1310719, 1835008, 1835071, 1836992, 1837055, 1865728, 1865791, 1867712, 1867775, 2064384, 2064447, 2066368, 2066431, 2095104, 2095167, 2097088, 2097151, 134217728, 134217855, 134225792, 134225919, 134471680, 134471807, 134479744, 134479871, 138149888, 138150015, 138157952, 138158079, 138403840, 138403967, 138411904, 138412031, 163577856, 163577983, 163585920, 163586047, 163831808, 163831935, 163839872, 163839999, 167510016, 167510143, 167518080, 167518207, 167763968, 167764095, 167772032, 167772159, 234881024, 234881151, 234889088, 234889215, 235134976, 235135103, 235143040, 235143167, 238813184, 238813311, 238821248, 238821375, 239067136, 239067263, 239075200, 239075327, 264241152, 264241279, 264249216, 264249343, 264495104, 264495231, 264503168, 264503295, 268173312, 268173439, 268181376, 268181503, 268427264, 268427391
```
**How are these sequences generated you ask?**
A default sequence from 1 through `n=10` would be:
```
As integer:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
As binary:
1 10 11 100 101 110 111 1000 1001 1010
```
When we stretch left, the binary will become this:
```
1, 110, 111, 111000, 111001, 111110, 111111, 1111000000, 1111000001, 1111000110
```
Why? The last bit is used once; the single-last is used twice; the second-last is used three times; etc.
```
So `1010` will become (spaces added as clarification): `1111 000 11 0`
```
And these new left-stretched binary strings are converted back to integers:
```
1, 6, 7, 56, 57, 62, 63, 960, 961, 966
```
---
As for stretched right, the first bit is used once; second twice; third three times; etc. Like this:
```
As binary:
1, 100, 111, 100000, 100111, 111000, 111111, 1000000000, 1000001111, 1001110000
As integer:
1, 4, 7, 32, 39, 56, 63, 512, 527, 624
```
## Challenge rules:
* *†* You can take any two distinct values, but state which one you use. So it can be `1/0`, `true/false`, `null/undefined`, `"left"/"right"`, etc.
* `n` is always larger than 0.
* You should support a maximum output of at least your language's default integer (which is 32-bit for most languages).
* Output format is flexible. Can be printed or returned as array/list. Can be with a space, comma, pipe, and alike as delimiter. Your call. (Again, please state what you've used.)
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
BmxJ$mḄð€
```
[Try it online!](https://tio.run/##y0rNyan8/98pt8JLJffhjpbDGx41rfn//7@hkel/XUMA "Jelly – Try It Online")
`-1` for left, `1` for right.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~102~~ 96 bytes
```
lambda d,n:[int(''.join(c*-~i for i,c in enumerate(bin(x+1)[2:][::d]))[::d],2)for x in range(n)]
```
-1 for left, 1 for right
[Try it online!](https://tio.run/##LcyxDsIgFIXh3ae4G1ylxjKS@CTIQFtoMe2lIZjUxVdHWp3O8P056ztPkWTx90eZ7dINFgZBSgfKnLHrMwbi/bn5BPAxQRA9BAJHr8Ulmx3vKm@XFrVURis1GMRjhMS93/Y6WRodJzRlTfUW2Ox8VgBMgOdNK0De8PSnFMap2kE/KV8 "Python 2 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14~~ 13 bytes
Saved 1 byte thanks to *Erik the Outgolfer*
```
LbεIiRƶRëƶ}JC
```
`1` for left.
`0` (or anything else) for right.
[Try it online!](https://tio.run/##MzBNTDJM/f/fJ@ncVs/MoGPbgg6vPrat1sv5/39LLkMA "05AB1E – Try It Online")
**Explanation**
```
L # push range [1 ... first_input]
b # convert to binary
ε # apply to each
Ii # if second_input is true
RƶR # reverse, multiply each element with its 1-based index and reverse again
ëƶ # else, multiply each element with its 1-based index
} # end if
J # join
C # convert to base-10
```
[Answer]
## [Husk](https://github.com/barbuz/Husk), 13 bytes
```
mȯḋṠṘo?ḣṫ⁰Lḋḣ
```
That's a lot of dotted letters...
Takes first `b` (`0` for left and `1` for right), then `n`.
[Try it online!](https://tio.run/##yygtzv7/P/fE@oc7uh/uXPBw54x8@4c7Fj/cufpR4wYfkOCOxf///zf8b2gAAA "Husk – Try It Online")
## Explanation
```
mȯḋṠṘo?ḣṫ⁰Lḋḣ Inputs b=1 and n=5 (implicit).
ḣ Range to n: [1,2,3,4,5]
mȯ Map function over the range:
Argument: number k=5
ḋ Binary digits: [1,0,1]
ṠṘ Repeat each digit with respect to the list
o L obtained by applying to the length (3) the function
? ⁰ if b is truthy
ḣ then increasing range: [1,2,3]
ṫ else decreasing range: [3,2,1].
We get [1,0,0,1,1,1].
ḋ Convert back to integer: 39
Final result [1,4,7,32,39], implicitly print.
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), ~~19~~ ~~18~~ 17 bytes
`0` for "left", `1` for "right". (It can actually take any falsey or truthy values in place of those 2.)
```
õȤËpV©EĪEnFlÃn2
```
[Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=9ciky3BWqUXEqkVuRmzDbjI=&input=MTAKMA==)
---
## Explanation
Implicit input of integers `U` & `V`.
```
õ
```
Create an array of integers from 1 to `U`, inclusive.
```
È
```
Pass each through a function.
```
¤
```
Convert the current integer to a binary string
```
Ë Ã
```
Map over the string, passing each character through a function, where `E` is the current index and `F` is the full string.
```
p
```
Repeat the current character
```
V© ª
```
`©` is logical AND (`&&`) and `ª` is logical OR `||`, so here we're checking if `V` is truthy (non-zero) or not.
```
YÄ
```
If `V` is truthy then `X` gets repeated `Y+1` times.
```
YnZl
```
If `V` is falsey then `X` gets repeated `Y` subtracted from (`n`) the length (`l`) of `Z` times.
```
n2
```
Convert back to a base 10 integer.
Implicitly output resulting array.
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 15 bytes
```
⟪¤bw¦¤;ċ%׆_b⟫¦
```
Uses `-1` for left and `1` for right.
[Try it online!](https://tio.run/##AScA2P9nYWlh///in6rCpGJ3wqbCpDvEiyXDl@KAoF9i4p@rwqb//zIwCjE "Gaia – Try It Online")
### Explanation
```
⟪¤bw¦¤;ċ%׆_b⟫¦ Map this block over the range 1..n, with direction as an extra parameter:
¤ Swap, bring current number to the top
b List of binary digits
w¦ Wrap each in a list
¤ Bring direction to the top
;ċ Push the range 1..len(binary digts)
% Select every direction-th element of it (-1 reverses, 1 does nothing)
׆ Element-wise repetition
_ Flatten
b Convert from binary to decimal
```
[Answer]
# [Proton](https://github.com/alexander-liao/proton), 79 bytes
```
n=>d=>[int(''.join(b[x]*[l-x,x-1][d]for x:2..(l=len(b=bin(i)))),2)for i:1..n+1]
```
`0` is left, `1` is right.
[Try it online!](https://tio.run/##FYxBCoAgEAC/0s3dyiU9BttHxEuYYMga0sHfm811hnlqeYv0yF34CHy4JC8oRXdJAqdrfnZZt7Vp413wsdSp7ZYIMudrBHyOLOFgtfjbtBsiWYzvT/1XEeyGYBD7Bw "Proton – Try It Online")
### Ungolfed
```
f=n=>d=> # Curried function
[ # Collect the results in a list
int( # Convert from a binary string to an int:
''.join( # Join together
b[x] # Each character of the binary string of n
*[l-x,x-1][d] # Repeated by its index or its index from the end, depending on d
for x:2..(l=len(b=bin(i))))
,2)
for i:1..n+1 # Do this for everything from 1 to n inclusive
]
```
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~192~~ 187 + 23 bytes
*-5 bytes thanks to [TheLethalCoder](https://codegolf.stackexchange.com/users/38550/thelethalcoder)*
```
b=>n=>new int[n].Select((_,a)=>{var g=Convert.ToString(a+1,2);return(long)g.Reverse().SelectMany((x,i)=>Enumerable.Repeat(x,b?i+1:g.Length-i)).Select((x,i)=>x>48?Math.Pow(2,i):0).Sum();})
```
Byte count also includes:
```
namespace System.Linq{}
```
[Try it online!](https://tio.run/##bVFda@MwEHz3r9jLQyMRVyTlHkpduxylLeUSKE2hD6UcirqxBYqUk@R8UPLbc5LdpjG9xZjV7mh2ZyTcqTAW97WTuoTp1nlcsGujFAovjXbsDjVaKbJE8wW6JRf4iRpL/Td5TyCEUNw5@NXkbSWG89xLASsj32DCpSb00PoCxbittbicGaPSNpXap3B/o@sFWj5TeKmMLouigDnk@1le6PDhGgLsRb@yKcZlCfmTcpoX7ytuocyvjV6h9ezJTL0N0ggfjNIzmln0tdUkEtKSPWIAOST0g2TC9ZaQTSoD0df4AFsi96E@u5KD0UXJxqhLX51KSg/T20ub4uf51YT7ij2YNTkLtYthwNQLQrMd3R@LzpKOB65ZM2ha1j7rdNaVVAiENC3IIUhzptmKv4U3CNtT@JGDrpWCk5OWIRZ6Pdrh6XoeI1rllkpG1uYam8YT6af9FPrQp@y5QotkA3kBmw/OYOlYOh8EfeObk/iI7IFHTxvil@ErpWFz3ymOQvFAw26NveGiaqd8inu20sfBA@hBj/5nVgfY2tAF7br@Hrv2G7fH6F3S/nd7b2uE0TCZc@Vi8g8 "C# (.NET Core) – Try It Online")
Input: `left` is `true`, `right` is `false`
Explanation:
```
b => n => // Take two inputs (bool and int)
new int[n].Select((_, a) => { // Create new collection the size of n
var g = Convert.ToString(a + 1, 2); // Take every number in sequence 1..n and convert to base 2 (in a string)
return (long)g.Reverse() // Reverse the bits
.SelectMany((x, i) => // Replace every bit with a collection of its repeats, then flatten the result
Enumerable.Repeat(x, b ? i + 1 : g.Length - i))
.Select((x, i) => x > 48 ? Math.Pow(2, i) : 0)
.Sum(); // Replace every bit with a corresponding power of 2, then sum
})
```
[Answer]
# Dyalog APL, 23 bytes
```
{2⊥b/⍨⌽⍣⍺⍳≢b←2⊥⍣¯1⊢⍵}¨⍳
```
left is `1` right is `0` (passed in as left argument of function)
`⍳` is index generator
`{`...`}¨` apply function in braces to each item on the right
`b←2⊥⍣¯1⊢⍵` b is ⍵ encoded as binary (using the inverse of decode to get the minimum number of bits required to represent `⍵` in base 2)
`⍳≢b` generate indexes for vector b (`≢b` is length of b)
`⌽⍣⍺` reverse `⍺` times (used conditionally here for left or right stretch)
`b/⍨` b replicated by (replicates the bits as per the (reverse)index)
`2⊥` decode from base 2
[TryAPL online](http://tryapl.org/?a=0%7B2%u22A5b/%u2368%u233D%u2363%u237A%u2373%u2262b%u21902%u22A5%u2363%AF1%u22A2%u2375%7D%A8%u237310&run)
[Answer]
# JavaScript (ES6), 131 bytes
This is significantly longer than [Shaggy's answer](https://codegolf.stackexchange.com/a/139572/58563), but I wanted to try a purely bitwise approach.
Due to the 32-bit limit of JS bitwise operations, this works only for ***n < 128***.
Takes input in currying syntax `(n)(r)`, where ***r*** is falsy for left / truthy for right.
```
n=>r=>[...Array(n)].map((_,n)=>(z=n=>31-Math.clz32(n),g=n=>n&&(x=z(b=n&-n),r?2<<z(n)-x:b*2)-1<<x*(r?2*z(n)+3-x:x+1)/2|g(n^b))(n+1))
```
### Formatted and commented
```
n => r => [...Array(n)] // given n and r
.map((_, n) => ( // for each n in [0 .. n - 1]
z = n => // z = helper function returning the
31 - Math.clz32(n), // 0-based position of the highest bit set
g = n => // g = recursive function:
n && ( // if n is not equal to 0:
x = z(b = n & -n), // b = bitmask of lowest bit set / x = position of b
r ? // if direction = right:
2 << z(n) - x // use 2 << z(n) - x
: // else:
b * 2 // use b * 2
) - 1 // get bitmask by subtracting 1
<< x * ( // left-shift it by x multiplied by:
r ? // if direction = right:
2 * z(n) + 3 - x // 2 * z(n) + 3 - x
: // else:
x + 1 // x + 1
) / 2 // and divided by 2
| g(n ^ b) // recursive call with n XOR b
)(n + 1) // initial call to g() with n + 1
) // end of map()
```
### Demo
```
let f =
n=>r=>[...Array(n)].map((_,n)=>(z=n=>31-Math.clz32(n),g=n=>n&&(x=z(b=n&-n),r?2<<z(n)-x:b*2)-1<<x*(r?2*z(n)+3-x:x+1)/2|g(n^b))(n+1))
console.log(JSON.stringify(f(10)(false)))
console.log(JSON.stringify(f(10)(true)))
```
[Answer]
# JavaScript (ES6), 113 bytes
Oh, this is just far too long! This is what happens when you spend the day writing "real" JavaScript, kiddies; you forget how to golf properly!
Uses any truthy or falsey values for `b`, with `false` being "left" and `true` being "right".
```
n=>b=>[...Array(n)].map(_=>eval("0b"+[...s=(++e).toString(2)].map((x,y)=>x.repeat(b?++y:s.length-y)).join``),e=0)
```
---
## Try it
```
o.innerText=(f=
n=>b=>[...Array(n)].map(_=>eval("0b"+[...s=(++e).toString(2)].map((x,y)=>x.repeat(b?++y:s.length-y)).join``),e=0)
)(i.value=10)(j.value=1);oninput=_=>o.innerText=f(+i.value)(+j.value)
```
```
label,input{font-family:sans-serif;font-size:14px;height:20px;line-height:20px;vertical-align:middle}input{margin:0 5px 0 0;width:100px;}
```
```
<label for=i>Size: </label><input id=i type=number><label for=j>Direction: </label><input id=j min=0 max=1 type=number><pre id=o>
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
B€xJṚ⁹¡$$€Ḅ
```
[Try it online!](https://tio.run/##y0rNyan8/9/pUdOaCq@HO2c9atx5aKGKCpD7cEfL////DQ3@GwIA "Jelly – Try It Online")
Argument #1: `n`
Argument #2: `1` for left, `0` for right.
[Answer]
# [Retina](https://github.com/m-ender/retina), 111 bytes
```
\d+
$*
1
$`1¶
+`(1+)\1
${1}0
01
1
.
$.%`$*R$&$.%'$*L
+s`(R?)(\d)(L?)(.*¶\1\3)$
$2$2$4
¶*[RL]
1
01
+`10
011
%`1
```
[Try it online!](https://tio.run/##FYwxDkIxDEN3nyMf2lSqGmDnAp26EqQgfQYWBmBD/1o9QC9WgjzYluX3un8ez9ucuiYQQ0AmoyNZkBTV61e2giK@ZFBejLjRzsOeuCK9LbRzDLrGUN0zj66ix0igg@uE0fnS6hX@d0gy@cMEi8mcUtoP "Retina – Try It Online") Takes the number and either `L` or `R` as a suffix (or on a separate line). Explanation:
```
\d+
$*
1
$`1¶
```
Convert from decimal to unary and count from 1 to `n`.
```
+`(1+)\1
${1}0
01
1
```
Convert from unary to binary.
```
.
$.%`$*R$&$.%'$*L
```
Wrap each bit in `R` and `L` characters according to its position in the line.
```
+s`(R?)(\d)(L?)(.*¶\1\3)$
$2$2$4
```
Replace the relevant `R` or `L` characters with the appropriate adjacent digit.
```
¶*[RL]
1
01
+`10
011
%`1
```
Remove left-over characters and convert from binary to decimal.
[Answer]
# JavaScript (ES6), ~~130~~ 127 bytes
*3 bytes, thanks Kevin*
I sure don't know enough ES6 for this site, but I tried! Loop through each number, and loop through each binary representation for that number, repeating each character however many times needed.
```
d=>n=>{i=0;while(i++<n){b=i.toString(2),s="",k=-1,l=b.length;while(++k<l)s+=b[k].repeat(d?k+1:l-k);console.log(parseInt(s,2))}}
```
```
f=d=>n=>{i=0;while(i++<n){b=i.toString(2),s="",k=-1,l=b.length;while(++k<l)s+=b[k].repeat(d?k+1:l-k);console.log(parseInt(s,2))}}
f(1)(10)
f(0)(10)
```
[Answer]
# Ruby, 98 bytes
```
->n,r{t=->a{r ?a:a.reverse};(1..n).map{|k|i=0;t[t[k.to_s(2).chars].map{|d|d*(i+=1)}].join.to_i 2}}
```
[Answer]
# Java 8, 136 bytes
Lambda (curried) from `Boolean` to a consumer of `Integer`. The boolean parameter indicates whether to stretch left (values `true`, `false`). Output is printed to standard out, separated by newlines, with a trailing newline.
```
l->n->{for(int i=0,o,c,d,s=0;i++<n;System.out.println(o)){while(i>>s>0)s++;for(o=c=0;c++<s;)for(d=0;d++<(l?s-c+1:c);o|=i>>s-c&1)o<<=1;}}
```
## Ungolfed lambda
```
l ->
n -> {
for (
int i = 0, o, c, d, s = 0;
i++ < n;
System.out.println(o)
) {
while (i >> s > 0)
s++;
for (o = c = 0; c++ < s; )
for (
d = 0;
d++ < (l ? s - c + 1 : c);
o |= i >> s - c & 1
)
o <<= 1;
}
}
```
[Try It Online](https://tio.run/##jZAxa8MwEIXn5FeIDEXCtrDXyFahhUKHQiFj6aDKsqNUkYR0Tgmpf7srp5naDNl0p/c97r2dOIjCeWV37efkhw@jJZJGxIhehLbotFz4oA8CFIogIH3uEkAH0IZ2g5WgnaVPl0f94JxRwubXRI/OxmGvQv1sQfUqcI56BRsICuT2Nei0DaiZTMFtwU@dCzitkG7K3OUyb/PYlExnWW3Z5hhB7akbgPqZMxY7Qk5fW20U1pxHXpKYZWz2cI1MnExcZGRetGls04jNfSxkVq0lYe67mbFC3lXE1XVTsXGcFmyZsv8Wcol@cLpF@1QLTmdr27@9IxH6SOaWFleuWhnVQYLPEdcrwpLsX2YqvDdHDGFQhAoplQdclWftNcug@@2tnp0w8a/puBynHw)
## Limits
Because they're accumulated in `int`s, outputs are limited to 31 bits. As a result, inputs are limited to 7 bits, so the maximum input the program supports is 127.
## Explanation
This solution builds up each stretched number using bitwise operations. The outer loop iterates `i` over the numbers to be stretched, from 1 to *n*, and prints the stretched value after each iteration.
The inner `while` loop increments `s` to the number of bits in `i`, and the subsequent `for` iterates `c` over each bit position. Within that loop, `d` counts up to the number of times to repeat the current bit, which depends on input `l`. At each step, `o` is shifted left and the appropriate bit of `i` is masked off and OR'd in.
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.