text
stringlengths 180
608k
|
---|
[Question]
[
I like to save time quite literally, by wearing three watches on my wrist... Problem is they each give a different time. One watch is x minutes behind the actual time. One watch is x minutes ahead of the actual time. The last watch shows the actual time.
Problem is, I can't tell which watch has the correct time...
From the time displayed on each watch, determine the actual time. If it is not possible to determine the time, print "Look at the sun".
**Input:**
Three readings, separated by single space characters: `H1:M1 H2:M2 H3:M3`
In each reading H1,H2,H3 represent the hours displayed (0 < H1,H2,H3 < 13), and
M1,M2,M3 represent the minutes displayed (0 <= M1,M2,M3 < 60). If the number of
minutes is less than 10, a leading 0 is prepended in the input. Similarly, is the number of hours is less than 10, a leading 0 is prepended in the input.
**Output:** `The correct time is HH:MM` where HH:MM is the correct time. If no correct time can be determined, it displays `Look at the sun`.
**Input 1:** `05:00 12:00 10:00`
**Output 1:** `The correct time is 05:00`
**Input 2:** `11:59 12:30 01:01`
**Output 2:** `The correct time is 12:30`
**Input 3:** `12:00 04:00 08:00`
**Output 3:** `Look at the sun`
Shortest code wins... No special penalties apply. Also, bear in mind that we're dealing with a 12-hour clock... I don't care about AM or PM... Imagine we're dealing with analogue watches...
[Answer]
# CJam, ~~86~~ ~~83~~ ~~77~~ ~~75~~ 71 bytes
```
"The correct time is "ea{aea+':f/60fb(f-:+720%!},{];"Look at the sun"}*
```
*Thanks to @jimmy23013 for golfing off 6 bytes from my code.*
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=lS%25%3AE%3B%7B%7D%3AA%3B%20e%23%20Emulate%20command-line%20arguments%20as%20EA.%0A%0A%22The%20correct%20time%20is%20%22EA%7BaEA%2B'%3Af%2F60fb(f-%3A%2B720%25!%7D%2C%7B%5D%3B%22Look%20at%20the%20sun%22%7D*&input=05%3A00%2012%3A00%2010%3A00).
### Test cases
```
$ cjam time.cjam 05:00 12:00 10:00; echo
The correct time is 05:00
$ cjam time.cjam 11:59 12:30 01:01; echo
The correct time is 12:30
$ cjam time.cjam 12:00 04:00 08:00; echo
Look at the sun
```
### How it works
```
"The correct time is "
e# Push that string.
ea e# Push the array of command-line arguments.
{ e# Filter; for each time T:
a e# Wrap T in an array.
ea+ e# Concatenate with the array of all times.
':f/ e# Split each time at the colon.
60fb e# Consider it a base 60 integer.
(f- e# Shift out the converted T and subtract it from the remaining times.
:+ e# Add them.
720%! e# Push 1 is the sum is 0 modulo 720 and 0 if not.
}, e# Keep the time iff a 1 has been pushed.
e# The array on the stack now contains one or three times.
{ e# Reduce; for each time but the first:
]; e# Discard the entire stack.
"Look at the sun"
e# Push that string.
}* e#
```
[Answer]
# JavaScript (*ES6*), 164 ~~168 172~~
For each reading, calc the distance from the other two. The one that have the same distance is what you need. If there is more than one, then you can't tell.
```
F=s=>(s=s.split(' '))
.map(x=>([h,m]=x.split(':'),+m+(h%12)*60))
.map((v,i,z)=>(v+v-z[++i%3]-z[++i%3])%720||'The correct time is '+s[k+=i],k=-2)
[k]||'Look at the sun'
// TEST
out=x=>O.innerHTML += x+'\n';
['12:30 01:01 11:59', '11:50 11:55 12:00', '05:00 12:00 10:00', '12:10 04:10 08:10', '07:00 06:00 08:00']
.forEach(x => out(x + ' -> ' + F(x)))
go=_=>out(I.value + ' -> ' + F(I.value))
```
```
<pre id=O></pre>
<input id=I><button onclick="go()">Test</button>
```
[Answer]
# Python 3, ~~166~~ 163 bytes
```
L=input().split()
f=lambda x:int(x[:2])*60+int(x[3:])
s=""
for a in L:s=[s,s and"Look at the sun"or"The correct time is "+a][(sum(map(f,L))-3*f(a))%720<1]
print(s)
```
Uses
```
a-b == b-c
<==> a+c-2*b == 0
<==> (a+b+c)-3*b == 0
```
with arithmetic being minutes modulo 720.
[Answer]
# Python 2, ~~254~~ ... ~~199~~ ~~207~~ ~~203~~ ~~194~~ 200 Bytes
Probably a few ways to shorten this, give me some time..
```
t=[x.split(':')for x in raw_input().split()]
a,b,c=[int(x[0])*60+int(x[1])for x in t]
print["The correct time is "+':'.join(t[[(c+a)%720%(b/2)<1,2][(a+b)%720%(c/2)<1]]),"Look at the sun"][(a-b)%240<1]
```
Thanks to Sp3000 helping me fix this.
] |
[Question]
[
## Introduction
Some of you may have heard of [Hilbert's Grand Hotel](https://en.wikipedia.org/wiki/Hilbert's_paradox_of_the_Grand_Hotel). The manager there has lost his list of where the guests are staying but he still has the order in which they checked in. Each guest can not stay in a room with a room number less than their value and if a guest is added to a lower room, all guests in higher rooms with no empty space between them and the new guest are shifted up one room. Can you help him find where each of the guests are staying?
## Requirements
Write a program which receives an ordered list of natural numbers as input and places them at their index. If there is already a value in that index, it is shifted up to the next entry in the list. This process repeats until the first empty (0 or undefined) space is found. Any undefined spaces between the current highest index and any new input will be filled by adding 0s. As this is Hilbert's Grand Hotel, rooms higher than the current highest occupied index do not exist.
## Input and Output
Input will be an ordered list of natural numbers (allowed to be read through any accepted form of input)
Each number in the input is considered one guest arriving at the hotel and is in order of arrival
Output will be the final arrangement of guests (numbers)
## Examples
>
> **Input:** 1 3 1
>
> **Output:** 1 1 3
>
> **Step by step:**
>
> 1
>
> Create room at index 1 and place 1 in it
>
> 1 0 3
>
> Create rooms up to index 3 and place 3 in room 3
>
> 1 1 3
>
> Shift the contents of room 1 up one room and place 1 in room 1
>
>
> **Input:** 1 4 3 1 2 1
>
> **Output**: 1 1 2 1 3 4
>
> **Step by step:**
>
> 1
>
> Create room at index 1 and place 1 in it
>
> 1 0 0 4
>
> Create rooms up to index 4 and place 4 in room 4
>
> 1 0 3 4
>
> Place 3 in room 3
>
> 1 1 3 4
>
> Shift contents of room 1 up one room and place 1 in room 1
>
> 1 2 1 3 4
>
> Shift contents of rooms 2 to 4 up one room and place 2 in room 2
>
> 1 1 2 1 3 4
>
> Shift contents of rooms 1 to 5 up one room and place 1 in room 1
>
>
> **Input:** 10
>
> **Output:** 0 0 0 0 0 0 0 0 0 0 10
>
> **Step by step:**
>
> 0 0 0 0 0 0 0 0 0 10
>
> Create rooms up to room 10 and place 10 in room 10
>
>
> Notes:
>
> Working with 0 indexed is fine and you may insert a 0 at the front of the output in that case
>
>
>
[Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden, shortest code in bytes wins
[Answer]
# PHP 93 bytes
```
for(;$r=$g?$r+1:$g=$argv[++$i];[$g,$h[$r]]=[$h[$r],$g])$h=array_pad($h?:[],$g,0);print_r($h);
```
0 indexed. Uses a 2 in 1 loop that looks up the next guest after it gets a 0 (or a null form going beyond the current final room). Use like:
```
php -r "for(;$r=$g?$r+1:$g=$argv[++$i];[$g,$h[$r]]=[$h[$r],$g])$h=array_pad($h?:[],$g,0);print_r($h);" 1 4 3 1 2 1
```
Ungolfed:
```
for( $hotel = []; $room = $guest = $argv[ ++$i ]; )
{
for( $hotel = array_pad( $hotel, $guest, 0 ); $guest; $room++ )
{
$last = $hotel[ $room ];
$hotel[ $room ] = $guest;
$guest = $last;
}
}
print_r( $hotel );
```
[Answer]
# [Haskell](https://www.haskell.org/), 107 bytes
```
h=foldl(\h n->let{(b,a)=splitAt n h;(c,d)=span(>0)a;e=0:e;f=take n$b++e;g(0:m)=m;g m=m}in f++[n]++c++g d)[]
```
[Try it online!](https://tio.run/nexus/haskell#FcixDsIgEADQX7mhA@TOhKpTyTXxOyoDbWkhwtkom/HbMb7xtcjbM69Z3SPIacyhftRMXvP7yKneKghEqxZa/@NFjUZ7G9gMwW5c/SOAdDNisLsyQ9Fc7A6FyzcJbIiTOMQFcYdVT64Vn4SPV5LaxamnK12opzP1rv0A "Haskell – TIO Nexus")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~24~~ 22 bytes
```
aŻƤSƇḢßoɓ@ooƑ?
Ṭ×)ç@ƒ0
```
[Try it online!](https://tio.run/##y0rNyan8/z/x6O5jS4KPtT/csejw/PyTkx3y849NtOd6uHPN4emah5c7HJtk8P9wu7dm5P//0YY6xjqGsTpA2gTE0jGC8AxiAQ "Jelly – Try It Online")
I still have the strangest feeling that something closer to Dennis's answer should beat this, but I haven't had any luck with that so far. I have twisted the first line into something that sounds like some kind of exploding can (from [my original recursive solution](https://tio.run/##y0rNyan8/z//8PzEo7uPLQk@1v5wx6JT3SenO@TnH5toz/Vw55rD0zUPLz82yeD/4XZvzcj//6MNdYx1DGN1gLQJiKVjBOEZxAIA); I thought it saved a byte but I didn't look at the output too carefully so it actually ties but it does look funnier).
```
aŻƤSƇḢßoɓ@ooƑ? Helper link: add a pre-positioned guest to the hotel
ɓ With reversed arguments (hotel left, guest right):
oƑ? Unless both arrays have a nonzero at the same location,
o return with the guest placed in its empty room;
ɓ if they do:
@ (guest left, hotel right)
a Overlay the guest's zeroes on the hotel.
ŻƤ Prepend another zero to each prefix,
SƇḢ and take the first with a nonzero sum.
ß Call this link again with that as the new guest
o and with the hotel having the previous guest replace the new one.
Ṭ×)ç@ƒ0 Main link
) For each guest value,
Ṭ obtain a list of all zeroes then a one at that index,
× and multiply that by the same guest value.
ƒ0 Starting with 0, reduce that by
ç@ the helper with reversed arguments.
```
Essentially just boots occupants out of their rooms in sequence until there's no collision, considering a new guest as equivalent to someone evicted from the last room they can't start in.
Dennis's answer with some simple golfs for fair comparison, and an explanation for those still wondering:
# [Jelly](https://github.com/DennisMitchell/jelly), 26 bytes
```
’⁹ḣ;⁸;ṫ@œṡ0Fɗð0ẋ;@
ç@ƒ0œr0
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw8xHjTsf7lhs/ahxh/XDnasdjk5@uHOhgdvJ6Yc3GDzc1W3twHV4ucOxSQZHJxcZ/D/c7q0Z@f9/tKGOgrGOgmGsjgKIaQLh6SgYwcQMYgE "Jelly – Try It Online")
```
’⁹ḣ;⁸;ṫ@œṡ0Fɗð0ẋ;@ Helper link: add a guest on the left to the hotel on the right
ð Let the right argument to the rest of the link be
0ẋ zero repeated by the value of the guest
;@ concatenated to the end of the hotel.
⁹ḣ Take elements from that right argument numbering
’ one less than the guest,
;⁸ concatenate the guest,
; ɗ and concatenate:
ṫ@ remove elements from that right argument numbering the guest value,
œṡ0 split those remaining around the first zero,
F and flatten them back together.
ç@ƒ0œr0 Main link
ç@ƒ0 With the hotel starting as 0, add each guest to the hotel in sequence.
œr0 Trim trailing zeroes.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 28 bytes
```
ṫœṡ0F
’⁹ḣ;⁸;ç@ð0ẋ;@
0;ç@/œr0
```
[Try it online!](https://tio.run/nexus/jelly#@/9w5@qjkx/uXGjgxvWoYeajxp0Pdyy2ftS4w/rwcofDGwwe7uq2duAyAPH0j04uMvh/uP1R0xr3//@jDXUUjHUUDGN1FEBMEwhPR8EIJmYQCwA "Jelly – TIO Nexus")
[Answer]
# JavaScript (ES6), ~~144~~ 120 bytes
*Saved 20B thanks to Arnauld and 11B thanks to Neil*
```
a=>a.map((d,c)=>b[d]?(b.splice(d,0,d),b.splice([...b,0].findIndex((e,g)=>g&&!e),1)):b[d]=d,b=[])&&[...b].map(c=>c|0)
```
## Usage
You can assign the function to the variable `f` and the list should be given as an array. Example:
```
f=a=>a.map((d,c)=>b[d]?(b.splice(d,0,d),b.splice([...b,0].findIndex((e,g)=>g&&!e),1)):b[d]=d,b=[])&&[...b].map(c=>c|0)
f([1,4,3,1,2,1])
```
## Output
The output is in an array as well. Since Javascript works zero-indexed, there is an extra 0 up front.
```
[0, 1, 1, 2, 1, 3, 4]
```
[Answer]
## JavaScript (ES6), 86 bytes
```
f=([n,...a],r=[],p=n,m=r[p],_=r[p]=n)=>n?m?f([m,...a],r,p+1):f(a,r):[...r].map(n=>n|0)
```
Leading zero in the result because JavaScript is 0-indexed.
[Answer]
# Mathematica, 98 bytes
```
Fold[If[Length@#<#2,PadRight@##~Append~#2,Join[Take@##,{#2},Drop@##/.{a___,0,b__}->{a,b}]]&,{0},#]&
```
Unnamed function taking a list of positive integers and returning a 0-indexed list of integers. The whole `If` function takes a partially completed list and the next integer to insert as arguments. If the next integer exceeds the length of the partial list, `PadRight@##~Append~#2` increases the partial list accordingly; otherwise, `Join[Take@##,{#2},Drop@##/.{a___,0,b__}->{a,b}]]` inserts the next integer into its position, then throws away the first `0` found after it. `Fold[...,{0},#]` applies this function repeatedly to the original list, starting with the empty hotel `{0}`, and outputs the final hotel list.
[Answer]
# JavaScript (ES6), 81
Using 0 indexing
```
l=>l.map(v=>(s=(p,v,w=r[p])=>(w&&s(p+1,w),r[p]=v))(v,v),r=[])&&[...r].map(x=>~~x)
```
*Less golfed*
```
l => {
s = ( // recursively insert a value, shifting present values up until it finds an empty spot
p, // insert position
v, // value to insert
w = r[p] // value a current position
) => (
w && s(p+1,w), // if there is a value, put it in the next position
r[p] = v // now the current place is empty
);
r = []; // initialize the result array
l.map( // execute the following for each value in input
v => s(v,v) // insert value
);
return [...r].map(x=>~~x) // fill the missing places with 0
}
```
**Test**
```
F=
l=>l.map(v=>(s=(p,v,w=r[p])=>(w&&s(p+1,w),r[p]=v))(v,v),r=[])&&[...r].map(x=>~~x)
out=x=>O.textContent+=x+'\n'
out([1,3,1]+' -> '+F([1,3,1]))
out([10]+' -> '+F([10]))
function go() {
var v = I.value.match(/\d+/g).map(x=>+x)
out(v +' -> ' + F(v))
}
go()
```
```
<input id=I value='1 4 3 1 2 1'><button onclick='go()'>go</button>
<pre id=O></pre>
```
[Answer]
# R, 133 bytes
```
a=scan()
z=rep(0,max(a))
for(i in a){b=match(0,z[-1:-i])+i
if(z[i])z[i:b]=c(i,z[i:(b-1)])else(z[i]=i)
z=c(z,0)}
z[1:max(which(z!=0))]
```
To avoid problems with bad indexing, I pad with some zeros, and then strip them at the end. This is maybe not the best solution, but it works.
[Answer]
## Python, ~~134~~ ~~125~~ 116 bytes
```
def a(b):
r=[]
i=0
for n in b:
d=n
while n:
if i<d:r.extend([0]*(d-i));i=d
n,r[d-1]=r[d-1],n;d+=1
return r
```
Valid for both Python 2.7.13 and 3.6.0. This code functions by means of a swapping the held value with the value contained at each index until the held value is 0. If it reaches an index not yet in the array, it adds zeros to the end of the array until the array contains that index. Thanks to Wheat Wizard and xnor for golfing off 9 bytes each
] |
[Question]
[
Write a program that takes as its input a string consisting of printable characters (ASCII 20-7E) and an integer `n` in [2,16] and performs the following modification to the string.
* Each character in the string is converted to its ASCII code (the examples given are in hexadecimal, though base 10 is also acceptable).
* The ASCII codes are converted to base `n` and are concatenated together.
* The new string is split every other character. If there are an odd number of characters, then the last character is removed entirely.
* Printing ASCII codes (in base 16) are converted back into their characters, whereas non-printing ASCII codes are removed.
* The resulting string is printed.
**Test case**
*Input*
```
Hello, World!
6
```
*Steps*
```
Hello, World!
48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21
2002453003003031125222330331030024453
20 02 45 30 03 00 30 31 12 52 22 33 03 31 03 00 24 45
```
The output of this program is `E001R"31$E`.
---
This is code golf, so standard rules apply. Shortest code in bytes wins.
[Answer]
# Pyth - 22 bytes
Hope to golf a lot more, pretty straightforward.
```
sfq3l`TmCid16csjRQCMz2
```
[Try it online here](http://pyth.herokuapp.com/?code=sfq3l%60TmCid16csjRQCMz2&input=Hello%2C+World%21%0A6&debug=0).
[Answer]
# CJam, 33 bytes
```
q~:i\fb:~0+2/W<Gfb:c' ,-'ÿ),127>-
```
Takes input in the form `6 "Hello, World!"`. [Test it here.](http://cjam.aditsu.net/#code=q~%3Ai%5Cfb%3A~0%2B2%2FW%3CGfb%3Ac'%20%2C-'%C3%BF)%2C127%3E-&input=6%20%22Hello%2C%20World!%22)
[See Dennis's answer](https://codegolf.stackexchange.com/a/62979/8478) for a similar but better solution with a nice explanation.
[Answer]
# Bash + common linux utils, 118
```
printf %s "$1"|xxd -p|sed -r "s/../\U& /g;y/ /n/;s/^/dc -e$2o16i/e;s/../& /g;s/ .$//;"|xxd -rp|sed 's/[^[:print:]]//g'
```
[Answer]
# CJam, 24 bytes
```
l:irifbe_2/{Gbc',32>&}/
```
Note that there is a DEL character (0x7F) between `'` and `,`. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=l%3Airifbe_2%2F%7BGbc'%7F%2C32%3E%26%7D%2F&input=Hello%2C%20World!%0A6).
### How it works
```
l:i Read a line from STDIN and cast each char to integer.
ri Read another integer (base) from STDIN.
fb Convert each integer from line 1 to that base.
e_2/ Flatten and split into chunks of length 2.
If the last chunk has only one element, it will get
converted into a control character, which will be
removed later.
{ }/ For each digit pair:
Gb Convert the pair from base 16 to integer.
c Cast to character.
', Push the string of ASCII characters up to '~'.
32> Remove the first 32 (control characters).
& Intersect.
```
[Answer]
# JavaScript (ES6), 137 ~~147~~
Using the most verbose functions available in JavaScript
```
f=(s,b)=>alert(s.replace(/./g,x=>x.charCodeAt().toString(b)).match(/../g).map(x=>(x=String.fromCharCode('0x'+x))<='~'&x>' '?x:'').join``)
// Just for test purpose, redefine alert()
alert=x=>document.write('<pre>'+x+'</pre>')
f('Hello, World!',6)
f('PORK',3)
```
[Answer]
# Julia, 118 bytes
```
f(s,n)=join(map(i->(c=string(Char(parse(Int,i,16))))^isprint(c),matchall(r"..",join(map(i->base(n,Int(i)),[s...])))))
```
Ungolfed:
```
function f(s::AbstractString, n::Integer)
# Construct an array of ASCII codes in base n
v = map(i -> base(n, Int(i)), [s...])
# Join into a string and get all pairs, truncating
# to an even length
m = matchall(r"..", join(v))
# Parse each pair as an integer in base 16, get the
# character associated with that code point, convert
# to a string, and include if it's printable
x = map(i -> (c = string(Char(parse(Int, i, 16)))^isprint(c), m)
# Join as a string and return
return join(x)
end
```
[Answer]
# Mathematica, 134 bytes
```
Print@FromCharacterCode@Select[#~FromDigits~16&/@StringPartition[""<>ToCharacterCode@InputString[]~IntegerString~Input[],2],31<#<127&]
```
If a function is allowed:
### Mathematica, 112 bytes
```
FromCharacterCode@Select[#~FromDigits~16&/@StringPartition[""<>ToCharacterCode@#~IntegerString~#2,2],31<#<127&]&
```
[Answer]
# TeaScript, 23 bytes
TeaScript is JavaScript for golfing
```
£lc¡T(y©K(2)ßC(P(l,16±µ
```
Relatively straight-forward but delightfully short. I can probably golf down a few more characters with some more operators. A few other new features might also be able to be used to cut down some bytes.
# Ungolfed && Explanation
```
x.l(#
l.c().T(y)
).K(2)
.m(#
C(
P(l,16)
)
).j``
```
[Answer]
# Ruby 92
```
->s,n{o=''
s.chars.map{|x|x.ord.to_s n}.join.scan(/../).map{|x|x>?2&&x<?8&&o<<x.to_i(16)}
o}
```
Online test [here](http://ideone.com/QBaJje).
[Answer]
# Python 2, 174 bytes
```
def J(a,b,i=0):
h=r=''
B=lambda n,b:n*'x'and B(n/b,b)+chr(48+n%b+7*(n%b>9))
for c in a:h+=B(ord(c),b)
while i<len(h):v=int(h[i:i+2],16);r+=chr(v)*(31<v<127);i+=2
print r
```
[Try it here](http://ideone.com/pXV5cH)
Not really the best tool for the job. Since Python has no convert-to-arbitrary-base function, I had to implement my own. That was fun, at least--particularly finding a [marginally] shorter expression for the digits than `"0123456789ABCDEF"[n%b]`. For iterating over two characters at a time, I found a `while` loop was slightly shorter than a functional approach.
181 bytes as a full program:
```
B=lambda n,b:n*'x'and B(n/b,b)+chr(48+n%b+7*(n%b>9))
a=raw_input()
b=input()
h=r=''
for c in a:h+=B(ord(c),b)
i=0
while i<len(h):v=int(h[i:i+2],16);r+=chr(v)*(31<v<127);i+=2
print r
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 13 bytes
```
C$vτHfṅǒHCkQ↔
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwiQyR2z4RIZuG5hceSSENrUeKGlCIsIiIsIkhlbGxvLCBXb3JsZCFcbjYiXQ==)
[Answer]
## MATLAB, 103 bytes
```
function k(s,n),b=dec2base(s,n)';b(~cumsum(b-'0',1))='';c=base2dec(textscan(b,'%2c'),16)';char(c(c>31))
```
I've written a function *k* that takes a string *s* and an integer *n* as input. e.g.:
```
k('Hello, World!',6)
```
gives
```
E001R"31$E
```
Most annoying thing I had to work around is leading zeros showing up when converting to base *n*. Getting these out of the array that was to be split after every 2nd character cost quite a lot of bytes. Not sure if it is possible to save any more bytes using this approach.
[Answer]
## PHP - 286 bytes
Put the string in `$s` and the integer in `$b`.
```
<?php $s=$_GET["s"];$b;$m="array_map";echo implode($m(function($v){return ctype_print($v)?$v:"";},$m("chr",$m("hexdec",str_split(strlen(implode($a=$m(function($v){global$b;return base_convert($v,16,$b);},$m("dechex",$m("ord",str_split($s))))))%2==1?substr(implode($a),0,-1):$a,2)))));?>
```
Pass the value to `GET["s"]`.
[Answer]
# [Ly](https://github.com/LyricLy/Ly), 26 bytes
```
ir[sp>lS<]>ry[puu' oy1G*]p
```
[Try it online!](https://tio.run/##y6n8/z@zKLq4wC4n2CbWrqgyuqC0VF0hv9LQXSu24P9/j9ScnHwdhfD8opwURQA "Ly – Try It Online")
This code uses the `S` instruction to convert the codepoints to digits one input character at a time. Then it just prints pairs of digits delimited with spaces from the accumulation stack.
```
ir
i - read input as codepoints
r - reverse stack
[ ] - for each input char/codepoint...
sp - stash codepoint and delete
>l - switch to accum stack, load codepoint
S - convert codepoint to digits
< - switch back to input stack
>r - switch to accum stack, reverse digits
y[ ] - loop until stack size is <2
p - delete loop iterator artifact
uu - print two digits
' o - print a space
y1G - is the stack size >1?
* - multiple to combine top two of stack
p - print iterator artifact
```
] |
[Question]
[
The Animal-Alphabetical Sequence is an infinite string of letters built accordingly to the following procedure:
1. Start with the letter `A`;
2. Replace each letter with the name of the animal starting with such letter in the table below;
3. Go back to step 2.
For instance, the first four steps of the procedure give:
* `A`
* `ADDAX`
* `ADDAXDINGODINGOADDAXXERUS`
* `ADDAXDINGODINGOADDAXXERUSDINGOINDRINYALAGECKOOTTERDINGOINDRINYALAGECKOOTTERADDAXDINGODINGOADDAXXERUSXERUSEAGLEROBINURIALSQUID`
Note that the string obtained at each step is a prefix of the string obtained at the next step. Hence, the procedure does indeed converge to a well-defined infinite string:
`ADDAXDINGODINGOADDAXXERUSDINGOIND...`
# The Challenge
Write a function that takes as input an integer `n` in the range `[0, 2^31 - 1]` and returns as output the `n`-th letter of the Animal-Alphabetical Sequence.
# Notes
* The first letter is the `0`-th.
* Letters can be uppercase or lowercase.
* It must be possible to run the program in the [Try It Online](https://tio.run) interpreter and get the result in at most 5 minutes.
# Test Cases
```
1511763812 -> M
1603218999 -> I
2049234744 -> X
2060411875 -> K
2147483647 -> D
```
# Table of Animal Names
```
ADDAX
BISON
CAMEL
DINGO
EAGLE
FOSSA
GECKO
HORSE
INDRI
JAMBU
KOALA
LEMUR
MOUSE
NYALA
OTTER
PRAWN
QUAIL
ROBIN
SQUID
TIGER
URIAL
VIXEN
WHALE
XERUS
YAPOK
ZEBRA
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 83 bytes
```
≔AηF↨N⁵≔§⁺η§⪪”$⌊∧X;F‖ρ=JD θ⊘⊙~'ΣV⦄K◨|]≕‖◨⟧TJρ¿¿C´!⁸⁶S/U¶V×W⧴a“,=6;‴*Þ↓h!�{≦”⁴⌕αηιηη
```
[Try it online!](https://tio.run/##NY/LTsMwFET3fIWVlS0FCRUjhFjdEBOu6tjBrkW7TNtALAW3ygPx98aIspszmsWZQ9@Oh1M7xAjT5D8CzSDLSc8er95PI6FFO3UUw3mZ1fK570bKcnLHGLmMYcZw7L5pMywT7XPyz/Y8@JlmZQlbtFpBLSSqSkMlhbYWxNNaa2OFKg1CXTgNEkTtjHZW7FLebIQx8KYcoNQFqleHJVapQ5C4FeoFpBDGWWj0OtnyJPXsw5G2v@YskWd/H5rRh5mmFOPqhj@sbvk95/H6a/gB "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔Aη
```
Start with `A` at the `0`th index.
```
F↨N⁵
```
Input `n`, convert it to base 5 and loop over the digits.
```
≔§⁺η§⪪”...”⁴⌕αηιη
```
Get the current animal from the compressed string of all animal suffixes (excluding `EBRA`) and lookup the appropriate letter from the current digit.
```
η
```
Output the final letter.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 168 bytes
```
n=>[...n.toString(5)].reduce((c,k)=>'DIAIA-EON-OEOYTRUOQIR-HEADSMNG-CRD-AMUATAABUGI-ARPAOEGL-KSR-LUSLEWIIIEA-LUOXNLOE-OEI-AREARNLNDRL-ESK'[Buffer(c)[0]-90+k*25]||c,'A')
```
[Try it online!](https://tio.run/##ZcxPb4IwAAXw@z6FN@hmK@U/B0zqaFhDoVuRzIVwMAjGaWBB9OR3Zyzc2O0lv/fe9/6@v5bd6aeHTXuohtofGn@dI4Qa1Ldp352ao2qBAnXV4VZWqlouz8BfKwEjjEAqEiio@NrKTHwwCd8oCdI4CeGrDCCJM7IlZJOFDBL5TgQNOYxSCXmWcvrJGKNkzGKXcEHHm78WJTLhSSA5pGmk5JtbXVedWoJcK6CnvZyfdat4PMqlQhQwlG1zbS8VurRHtVaxhbFjGy7WAVisVov4aea2ZujY9TxvcjZzXTM93TAd05x8989tzcTYdazJo7njcesatulMHgy/ "JavaScript (Node.js) – Try It Online")
### How?
The lookup string (let's call it `S`) is built as 4 sub-strings of 25 characters as follows:
```
ABCDEFGHIJKLMNOPQRSTUVWXY
-------------------------
DIAIA-EON-OEOYTRUOQIR-HEA --> 2nd letter of each word
DSMNG-CRD-AMUATAABUGI-ARP --> 3rd letter of each word
AOEGL-KSR-LUSLEWIIIEA-LUO --> 4th letter of each word
XNLOE-OEI-AREARNLNDRL-ESK --> 5th letter of each word
```
Therefore:
```
S[Buffer(c)[0] - 90 + k * 25] // equivalent to S[Buffer(c)[0] - 65 + (k - 1) * 25]
```
is undefined if `k = 0`, in which case we leave `c` unchanged as expected (the first letter of the word that starts with `c` is `c`).
[Answer]
# [Haskell](https://www.haskell.org/), ~~[170](https://codegolf.stackexchange.com/revisions/216562/2)~~ 162 bytes
*Thanks to AZTECCO for helping me index the lookup shorter*
```
f 0='A'
f n|x<-f$div n 5=(x:drop(4*length['B'..x])"DDAXISONAMELINGOAGLEOSSAECKOORSENDRIAMBUOALAEMUROUSEYALATTERRAWNUAILOBINQUIDIGERRIALIXENHALEERUSAPOK")!!mod n 5
```
[Try it online!](https://tio.run/##FY5RC8FQGEDf/YrRaihriheZ@mZf8@XuftzrhuRBzZAZMdqD/z5znk7n6ZwPr@sxy6oqtTzfAaeRWvm3HPdSO7l8rNwa@u1ylDzvj/agmx3zU3HeOYHjuuW@0wpD2JBmCTEKkhFDJJC1BpzOmZVGGSqCODAMAjA2io3Gbe2rFSoFa2mABAckl4ZCiupGIGiDcgYCURkNC563Os3m7Z78T6rb4ZL7j3ehi6edju3JznPd/tCr2Vc/ "Haskell – Try It Online")
This exceeds TIO's output capacity nearly instantly, so I think this is safe on timing. My quick analysis tells me the algorithm should be \$O(n)\$. That is if you input a number of length \$n\$ bits it should take about the \$n\$ time to find the answer.
I'm not the best at golfing data encoding so I think that is where I am losing the most bytes.
This gets a lot easier to read if we just say we have a function `u` which gives the word for a letter. Then it is:
```
f 0='A'
f n=u(f$div n 5)!!mod n 5
```
[Answer]
# [Python ~~3~~ 2](https://docs.python.org/2/), ~~160 159~~ 158 bytes
```
s="ABCDEGHIKLMNOPQRSTUWXYDIAIAEONOEOYTRUOQIRHEADSMNGCRDAMUATAABUGIARPAOEGLKSRLUSLEWIIIEALUOXNLOEOEIAREARNLNDRLESK"
f=lambda n:s[n and s.find(f(n/5))::22][n%5]
```
[Try it online!](https://tio.run/##DctBC4IwFADge79ChGBeCoQIhA7P9rDh3HJzVIgHQ0ZCvSTt0K837983/KbHm@J5Hg8hpEeO2UnkslD6XBpbucv1xgUIQK006ltlnC6FOSFwW6jsaDgUDiqA1GUCzBk0ZjK3Rjor8SKEQJBOX5VcMi4AwSipuJFo83DlD8/2de/agJKxpqClLhg3vqeOeUbbXRQlSRw3Na13zTx8epoCz3oavhOLonn/Bw "Python 2 – Try It Online")
*-1 thanks to @ovs*
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~78~~ 77 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
'aI5вvA…fjvмSD.•13ôºå}Æ ë¾‚pu®×ÌмĀαù·o×#·Îg4™Ā8%+ÚONp:rƒÜ∊₁Œ¿ÝøuÏādûá•4ôøJ‡yè
```
-1 byte thanks to *@Arnauld*.
Output in lowercase.
[Try it online](https://tio.run/##AZMAbP9vc2FiaWX//ydhSTXQsnZB4oCmZmp20LxTRC7igKIxM8O0wrrDpX3DhiDDq8K@4oCacHXCrsOXw4zQvMSAzrHDucK3b8OXI8K3w45nNOKEosSAOCUrw5pPTnA6csaSw5ziiIrigoHFksK/w53DuHXDj8SBZMO7w6HigKI0w7TDuErigKF5w6j//zE1MTE3NjM4MTI) or [verify all test cases](https://tio.run/##AdcAKP9vc2FiaWX/dnk/IiDihpIgIj//J2F5NdCydkHigKZmanbQvFNELuKAojEzw7TCusOlfcOGIMOrwr7igJpwdcKuw5fDjNC8xIDOscO5wrdvw5cjwrfDjmc04oSixIA4JSvDmk9OcDpyxpLDnOKIiuKCgcWSwr/DncO4dcOPxIFkw7vDoeKAojTDtMO4SuKAoXnDqP99LP9bMCwxLDMsMTAsMTUxMTc2MzgxMiwxNjAzMjE4OTk5LDIwNDkyMzQ3NDQsMjA2MDQxMTg3NSwyMTQ3NDgzNjQ3XQ).
**Explanation:**
```
'a '# Push string "a"
I # Push the input-integer
5в # Convert it to base-5 as list
v # Loop `y` over each digit in this list:
A # Push the lowercase alphabet
…fjvм # Remove the letters 'f', 'j', and 'v'
S # Convert it to a list of characters
D # Duplicate this list
.•13ôºå}Æ ë¾‚pu®×ÌмĀαù·o×#·Îg4™Ā8%+ÚONp:rƒÜ∊₁Œ¿ÝøuÏādûá•
# Push compressed string "ddaxisonamelingoagleeckoorsendrioalaemurouseyalatterrawnuailobinquidigerrialhaleerusapok"
4ô # Split the string into parts of 4 characters
ø # Create pairs with the alphabet-list (the trailing 'z' is ignored)
J # Join each pair together to a single 5-char string
‡ # Transliterate the current character to the animal name
# (again ignoring the trailing 'z')
yè # And index digit `y` into this string for the next iteration
# (after the loop, the resulting character is output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•13ôºå}Æ ë¾‚pu®×ÌмĀαù·o×#·Îg4™Ā8%+ÚONp:rƒÜ∊₁Œ¿ÝøuÏādûá•` is `"ddaxisonamelingoagleeckoorsendrioalaemurouseyalatterrawnuailobinquidigerrialhaleerusapok"`.
[Answer]
# [Perl 5](https://www.perl.org/), 175 bytes
```
sub f{my$n=pop;$_=substr$n?f(1,$n/5):ADDAX,$n%5,1;@_?$_.[DDAXISONAMELINGOAGLE_ECKOORSENDRI_OALAEMUROUSEYALATTERRAWNUAILOBINQUIDIGERRIAL_HALEERUSAPOK=~/_|.{4}/g]->[-65+ord]:$_}
```
[Try it online!](https://tio.run/##Tc/basIwHMfxe5@iSIaW1UN6PlA1W4ML1mZrLXOIBIZVhNmWtsLEucs9wB5xL9LVTrbl6s/387tJGmUvSlnm@2dufdwdQGynSWoBZlclLzIQD9dtKIC4p/Amchw0r@4rRYDWiA0B6y7OiQTUQ1PsEm9M0djFDN9OKPUD7Dk@YRS5CE9Dn4YBfqru2Qz7Pnr0QkRcekO8h5A4ZFw1glx2h1yM/TBA93Riv/fYW/con3qbZWew6KjKdZKtliZgp3KfR9wsygvTnCZZZDXWSdZucNVbQAVCTZV0KHL2gGtNW0vhAmpfEqFuGEYN5BfEvmyIkqzJcg3zf6D2ZQh1Talh8gewWuuSKms1OGfgj7XtDm2wjVMBRK8pb48Asy4ZbJLCXtfI/7Rt3j7Heio0L8R9fXxy59ysVqfGKokjVlQf3cYbq/wG "Perl 5 – Try It Online")
Somewhat ungolfed. Added whitespace and moved dictionary string into variable $animals:
```
sub f {
$animals='DDAXISONAMELINGOAGLE_ECKOORSENDRI_OALAEMUROUSE'
.'YALATTERRAWNUAILOBINQUIDIGERRIAL_HALEERUSAPOK';
my $n=pop; #arg
$_=substr #put letter into $_
$n ? f(1,$n/5) : ADDAX, #next word is word at n/5 or first word
$n%5,1; #get letter at pos n%5 of word
@_ #if recursed ...
?$_.[$animals=~/_|.{4}/g]->[-65+ord]#then return letter + its 4 letters in dict
:$_ #else return just letter
}
```
About runtime: on my "vintage" laptop the five test cases spends about 0.025 sec in total. If I change `$n/5` into `int$n/5` this is reduced to 0.0016 sec (because then it doesn't need to keep dividing by 5 until the decimals disappears, thus far fewer recursions)
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~254~~ ~~234~~ ~~230~~ ~~229~~ ~~228~~ ~~209~~ ~~199~~ 198 bytes
```
string f(int v,int p=-1){var h=v>-p?f(v/5,v%5):"ADDAX";return p<0?h[..1]:h[p]+"DDAXISONAMELINGOAGLEOSSAECKOORSENDRIAMBUOALAEMUROUSEYALATTERRAWNUAILOBINQUIDIGERRIALIXENHALEERUSAPOK"[(h[p]*4-260)..];}
```
[Try it online!](https://tio.run/##dc1Na4NAEAbge3@FCAVtEnV1/Uqahklc7JLVbTWSFMmhBFOFYkSNl9LfbiN4TC/D8M7DO6dmdmqKvm/auii/hLNUlK3QTYdZLWdI/uk@ayFfdpPqRVudpU41p92jKc9F8Dw4iIs6a691KVTP2ipPFQUd53laHSficKUxDyEgjIY@B58RHsdANlvOo5iEXkQhWCccGJAgiXgSk4/bvtuRKIJ9mABlfE3D94R61L9lFBg9kPAVGCFREsMb34qpNDx7wjPd0mRFOS5@@82lbC7fmbKvizZjRZlJZwmZCNmW4SBdlheCqgrBw11maYaOHNd1R0bvMl3Drm5gG@ORHf5hloYRcmxzZNv7DN2aHMPC9si8/g8 "C# (Visual C# Interactive Compiler) – Try It Online")
**How?**
```
char f(int v, int p = -1)
{
var h = v > -p ? f(v / 5, v % 5) : "ADDAX";
return p < 0 ? h[..1] : h[p] + "DDAXISONAMELINGOAGLEOSSAECKOORSENDRIAMBUOALAEMUROUSEYALATTERRAWNUAILOBINQUIDIGERRIALIXENHALEERUSAPOK"[(h[p] * 4 - 260)..];
}
```
This version is a complete rewrite of my original solution. Inspired from other submissions, I decided to use a recursive function. The gist is still converting `v` to base 5 and use the digits to point to the correct words. When `v` and `p` are both equal to 0, the conversion is complete, so we take `ADDAX` and stop the recursion.
`Zebra` was removed from the list because it is not reachable.
Updates:
* Saved 20 bytes removing the first letter from each word in the string literal.
* Replacing `do/while` with a `for` loop reduced the size by 4 bytes
* -1 byte using a tuple to assign `b` and `g`
* -1 byte replacing 'A' with 65
* -1 byte replacing `[((h[b] - 65) * 4)..]` with `[(h[b]*4 - 260)..]`
* -10 bytes using a recursive function
* -1 byte replacing `v+p>0` with `v>-p` (thanks to @ceilingcat)
[Answer]
# [Julia 1.0](http://julialang.org/), 153 bytes
```
f(n)=*('A':'Y'...,"DIAIAOEONAOEOYTRUOQIRIHEADSMNGSCRDMAMUATAABUGIXARPAOEGLSKSRBLUSLEWIIIEAELUOXNLOEAOEIUAREARNLNDRLNESK")[n<1||f(n÷5)-'@':25:end][1+n%5]
```
[Try it online!](https://tio.run/##LU3dSsMwGL3PU5SBpNVamjb9xYrfbKhhaarJghujF4IbTEYQV8GLvZcP4IPVDr05nD/Oefs87F/I1zjuXOtVly4GXOI1DoLAn9UcOHSsk2dYL5XpnrjiDwxq3cpG36u6hdbAEmBuGr4C9TgVG6EXWs2F0YI9c84ZMGG6lRQdm1JuQDFQUshaCcn0YuZt7A05nab7n@/Eu8Z3uIyScmtf@w25shdJPw7b43B0KmeDSEJIlsY5iXxE0jCOSF4UhY@ikBZRTDNKzzwNKSF5lkycTF4epzTzUY/Q@8feDgcbuH@LQXXr7P6F542/ "Julia 1.0 – Try It Online")
[Answer]
# PowerShell, 185 182 179 177 174 173 Bytes
-1 byte thanks to mazzy!
```
for($f=[char]65;!($x=$f[$args])){$f=$f|%{,$_+"DDAXISONAMELINGOAGLEOSSAECKOORSENDRIAMBUOALAEMUROUSEYALATTERRAWNUAILOBINQUIDIGERRIALIXENHALEERUSAPOK"[($i=$_%65*4)..($i+3)]}}$x
```
Could probably be shortened, but I got stumped. If 0 can be ignored as an input, you can drop the [char] in [char]65 to save 4 bytes.
] |
[Question]
[
Note: this problem was inspired by the [Unsolved Mathematical Problems for K-12](https://www.youtube.com/watch?v=JPhqhZvXlhQ) youtube video, which also features other interesting puzzles.
*From the [wikipedia article](https://en.wikipedia.org/wiki/No-three-in-line_problem):*
>
> The **no-three-in-line** problem asks for the maximum number of points that can be placed in the *n × n* grid so that no three points are [collinear](https://en.wikipedia.org/wiki/Collinearity) ..... Although the problem can be solved with *2n* points for every *n* up to 46, it is conjectured that fewer than *2n* points are possible for sufficiently large values of *n*.
>
>
>
You must write a program or function which takes in an input \$ n \$ where \$ 2 \leq n \leq 46 \$, and returns/outputs an \$ n \times n \$ grid containing \$ 2n \$ points, such that no three points are collinear (lie on a single line, including diagonals). Here is a [checker](https://tio.run/##bVHBaoNAFLzvVwyRkLW1Iemx4Cm00EsLIQchSJC4JrvKKquhpj9v365JY20EffNmxnlvtTo3x1I/d50HqatTg@YoUMtvgTJz@GBkilI7nElTNyikFoHte1KjpXto06JtiLK@mjGNkKIbbpKvnRvBfZ85e4jtgERWGkiywiT6ILj2Y8Yia4rZP@mFObsacZCZ22Qr462KEYaYeTPLI5onVSV0yrkMoGgDJuvdvizskomhKRtzEuM5hdA88u8Mk4/LADfVyflNViMZsg0gzzSYqqKaU83PNDWymy7ioAdLB9SVUVcmvzK5ZVxgBk4BT5Tm4wFctYRl69sjc2UF2Qu5FVTbr4HRmd@SohZOqAz9IkzeP1af6/XraoOkAZ@mAaapH9xBE0zB75@KPu0l7ZI16brlgs3p8jz7JOiqZ6FDFrOesT27kNQN4cDw57Vb2O@IHw) for your program.
## Clarifications
* Each *point* is represented as a square in the grid
* Each square must have two states, representing whether a square contains a point or not.
* You may return a 2D array of chars, a 1D array of strings, or a string with an arbitrary separator.
* It is not expected for your solution to run in time for a \$ 46 \times 46 \$ grid, but it should for at least \$ n \leq 5 \$
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins!
## Examples
### Input
```
2
3
4
5
10
```
### Output
*'#' represents an occupied point, '.' represents an empty square*
```
##
##
.##
#.#
##.
.##.
#..#
#..#
.##.
..#.#
.##..
...##
#..#.
##...
....##....
..#....#..
.#......#.
...#..#...
#........#
#........#
...#..#...
.#......#.
..#....#..
....##....
```
[Answer]
# JavaScript (ES6), ~~208 ... 197~~ 196 bytes
Returns a binary matrix.
```
f=(n,m=[...Array(n)].map(_=>Array(n).fill(0)),g=(C,z)=>m.some((r,y)=>r.some((v,x)=>v^z&&C(x,V=y,r))))=>!n|g((x,y,r)=>g((X,Y)=>g(H=>(V-=Y)|(H-=X)&&V*(X-x)==H*(Y-y)))?0:r[x]=+!!f(n-++r[x]/2,m),1)&&m
```
[Try it online!](https://tio.run/##NY/BasMwEER/Rb44q2ilpoFe2qxCycVfYGzStJjUMg6WFORi7JB/d@XQ7mXmDczCXKqh6s@hvf5I57/reTYEDi0dlVLvIVQTOH5StrrCF@n/QJm262DDOTYEB7xx0lb13tYAAadI4Y8GHCMNn7c0PcCIOU0YeDzSibs3EKMlIB1tgeXDZKQhl1TyO2SSCp6m@RoKGf9QtoZSTrG@37yG43gikSQGnBRioactWo7PsWBn4wM4Rmz7xhzbEXuJKgRnZ@9639Wq8w2YZcjFtw5WH27FmWAPnX8B "JavaScript (Node.js) – Try It Online")
### Output
Only \$N=2\$ to \$N=5\$ can be processed on TIO. The output for \$N=6\$ was computed locally.
\$N=2\$:
$$\begin{pmatrix}
1&1\\
1&1
\end{pmatrix}$$
\$N=3\$:
$$\begin{pmatrix}
1&1&0\\
1&0&1\\
0&1&1
\end{pmatrix}$$
\$N=4\$:
$$\begin{pmatrix}
1&1&0&0\\
0&0&1&1\\
1&1&0&0\\
0&0&1&1
\end{pmatrix}$$
\$N=5\$ ([check it](https://tio.run/##bVFRa4MwGHzPrzgaSuPmZBvsZeBT2WAvG5Q@CEWKzNgmSpRomd2fd19iS4vrg@Zyd9x9nzbHbl@b52HgUKY5dOj2Eq36lagLj3dW5aiNx4WybYdKGRm6@0ga9PRc24zsO6Kcr2XMIKboTtjsZ@srRBAwb4@xuSJR1BaKrLCZ2UlhgpSxxJlS9k96Zd6uJxxU4SfZqHSjU8QxFnzheCRR1jTS5EKoEJomYKrdfteVGzKz1LK2BzntqaQRSXCjTN0/hbioXi4vsp7IUH0IdaRiOjWdJZ3lkVoTN@ljGo7gyQN9ZvSZKc9M6RgfWEBQwAOlBbiD0D1h1QduZaGdoEahdILuxzEw2fk9q1rphcbSL8Ls43P5tVq9LdfIOoh5HmKeB@ENNMMc4vZW9GlPaaes2TC8MM6jKGL04hEjxDmLHMUcwf8A)):
$$\begin{pmatrix}
1&1&0&0&0\\
1&0&0&1&0\\
0&0&0&1&1\\
0&1&1&0&0\\
0&0&1&0&1
\end{pmatrix}$$
\$N=6\$ ([check it](https://tio.run/##bVHBaoNAFLzvVwxZQtbWSttDDwVPoYVeWgg5CEGC1DXZVVZZDTX9eft2TUiwEdf3nBlm3tPm2O1r8zwMHMo0hw7dXqJVvxJ14fudVTlq4/tC2bZDpYwM3fsIGvR0rmVG9h1BTtcyZhCTdSds9rP1ESIImJfH2FyBKGoLRVLYzOykMEHKWOJEKftHvTIv1xMMqvCTbFS60SniGAu@cDiSKGsaaXIhVAhNEzDVbr/ryg2ZWUpZ24Oc5lTSiCS4Eabun0JcWE@XF1pPaKg@hDpSMFVNtaRaHik1cZM@puHYPPlGnxF9RsozUjrEGxYQZPBAbgHuIHRPveoDt7LQjlAjUTpC9@MYmOz8nlWt9ERj6Rdh9vG5/Fqt3pZrZB3EPA8xz4PwRjfDHOL2VvRpT24nr9kwvDDOI7oYHR5xRg@6GXfVgxEnMHKiPw)):
$$\begin{pmatrix}
1&1&0&0&0&0\\
0&0&0&1&0&1\\
0&1&0&0&1&0\\
1&0&1&0&0&0\\
0&0&0&0&1&1\\
0&0&1&1&0&0
\end{pmatrix}$$
### Commented
```
f = ( // f is a recursive function
n, // n = input
m = [...Array(n)].map( // m[] = n x n output matrix,
_ => Array(n).fill(0) // initially filled with 0's
), //
g = (C, z) => // g is a helper function taking a callback C and a flag z:
m.some((r, y) => // for each row r[] at position y in m[]:
r.some((v, x) => // for each value v at position x in r[]:
v ^ z && // if v is not equal to z:
C(x, V = y, r) // invoke C(x, y, r) and copy y to V
) // end of inner some()
) // end of outer some()
) => //
!n | // force success if n = 0
g((x, y, r) => // for each 0-cell at (x, y) on row r[]:
g((X, Y) => // for each 1-cell at (X, Y):
g(H => // for each 1-cell at (H, V):
(V -= Y) | // update V to V - Y
(H -= X) // update H to H - X
&& // test if either V - Y or H - X is not equal to 0
V * (X - x) == // and (V - Y) * (X - x) is equal to
H * (Y - y) // (H - X) * (Y - y), i.e (x, y), (X, Y) and (H, V)
// are collinear
) // end of 3rd iteration
) // end of 2nd iteration
? // if there's a pair of points collinear to (x, y):
0 // do nothing
: // else:
r[x] = +!!f( // do a recursive call:
n - ++r[x] / 2, m // set (x, y) and subtract 1/2 from n
), // if falsy, unset (x, y) afterwards
1 // use z = 1 for the 1st iteration
) && m // end of 1st iteration; return m[]
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 185 bytes
```
(d=1~(r=RandomInteger)~{#,#};While[(M=Max)[{M[(z=#;M[Tr/@(Diagonal[z,#]&/@Range[-2,2])])&/@{d,Reverse@d}],M[Tr/@d],M[Tr/@Transpose@d]}]>2||Tr[Join@@d]!=2#,d=1~r~{#,#}];ToString/@#&/@d)&
```
[Try it online!](https://tio.run/##NY5BC8IgGIb/SiWEgjEadFqGhy4FQqxBB/EgKU5oGiYRre2vmyO6ve/z8b08nYyt7mS0V5kMSVCR9QgDqaVTvju4qI0OaOwBBkN1ae1Nc8gIky/Ee8bhm4CK8SYUFO6tNN7JG39jIJYFzQtG81WJS4EEyqBXuNZPHR6aqkHg35v6hyZI97j76SgGsSs/nybwo7eOZjAnJcCTWfiZiKrx5xisMwUFeVqhZTrlGrPHYrHdTWxm@EaglL4 "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~62~~ ~~53~~ 43 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
L3‹œêIи[D.rI£DεƶN>δ‚}€`ʒßĀ}3.Æʒ{ü-`R*Ë}g_#\
```
Random brute-force approach, so obviously pretty slow (`n=5` finishes between 15-45 seconds on average).
Output as a list of lines, with `10` instead of `#.` respectively.
-10 bytes thanks to *@Grimmy*.
[Try it online](https://tio.run/##AU4Asf9vc2FiaWX//0wz4oC5xZPDqknQuFtELnJJwqNEzrXGtk4@zrTigJp94oKsYMqSw5/EgH0zLsOGypJ7w7wtYFIqw4t9Z18jXP9dSsK7/zU).
**Explanation:**
```
L # Push a list in the range [1, (implicit) input-integer]
3‹ # Check for each whether it's smaller than 3
# (so we'll have a list with 2 zeroes and input-2 amount of 1s)
œ # Take the powerset of this list
ê # Sort and uniquify the list of lists
Iи # Repeat each sublist in the list the input amount of times
[ # Then start an infinite loop:
D # Duplicate the list of potential rows
.r # Randomly shuffle it
I£ # And then leave just the first input amount of rows
D # Duplicate it
ε # Map each row to:
ƶ # Multiply each by their 1-based index
δ # For each inner value:
‚ # Pair it with
N> # the 1-based map-index
}€` # After the map: flatten one level
ʒ } # Filter each coordinate to:
ß # Get the minimum
Ā # And check that it's NOT 0
# (we now have a list of all coordinates for the 1-bits)
3.Æ # Get all possible triplets of the coordinates
ʒ # Filter the list of triplets by:
{ # Sort the coordinates from lowest to highest
ü # For each overlapping pair of coordinates:
# [[ax,ay],[bx,by],[cx,cy]] → [[[ax,ay],[bx,by]],[[bx,by],[cx,cy]]]
- # Subtract them from one another
# → [[ax-bx,ay-by],[bx-cx,by-cy]]
` # Push them separated to the stack
R # Reverse the second
* # Multiply them
# → [(ax-bx)*(by-cy),(ay-by)*(bx-cx)]
Ë # And check if they are equal
}g # After the filter: get the amount of remaining triplets
_ # If this is 0 (thus none are remaining anymore):
# # Stop the infinite loop
# (after which the duplicated list of binary rows is output implicitly)
\ # (Else:) discard it before trying again in the next iteration
```
[Answer]
# [R](https://www.r-project.org/), 192 bytes
Outputs a binary matrix. Random brute, found the answer for N=5 in <60s only once.
```
function(N){m=2*N;c=combn(1:m,3);repeat{p=t(replicate(m,sample(1:N,2,T)));o=matrix(0,N,N);o[p]=1;sum(o)==m&&1>sum(sapply(1:ncol(c),function(x)qr(cbind(p[c[,x],],1:3*0+1))$rank<3))&&return(o)}}
```
[Try it online!](https://tio.run/##PY/NToQwFIX3PgVWQ3rHqxkGV8PceYSu3CGLTi0JsX@WkmAIz44lGnffl9x7ck7clrui6C/PWz85lQbvuIDF0ukgGkXK25vj1dliDU3UQcu0BEo8oxmUTJpbHKUNRucjgSd8A4DGk5UpDjM/okCRvQ0dVc04We6ByJZldd1llCGY7/zplDdcAf5XmOErcnUb3AcPrWpx7rDD6lwfjk8VwGOU7vNSA5Rl1GmKLseu61YUgl7zGE993rBD66/HjtgD@5X7HbO/7J7bc4Hs3TH4syDHPMgDjjoQY9gPxlAOWrcf "R – Try It Online")
Just started learning R, any help appreciated.
```
function (N) {
m = 2 * N
c = combn(1:m, 3) # all 3-point combinations
repeat { # indefinitely
p = t(replicate(m, sample(1:N, 2, T))) # 2N random points
o = matrix(0, N, N)
o[p] = 1 # output matrix
sum(o) == m # is each point different?
&& 1 > sum( # is it a vector of FALSEs?
sapply(1:ncol(c), # for each combination
function(x)
qr(
cbind(
p[c[,x],] # point coordinates
,1:3*0+1) # add (1,1,1) column
)$rank < 3) # is the matrix rank 2 or less
)
&& return(o)}}
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 83 bytes
```
NθW‹№ω#⊗θ¿⁼Lω×θθ≔⁺…ω⊟⌕Aω#¦.ω«≔⁻÷⌕Aω#θ÷Lωθη≔⁻﹪⌕Aω#θ﹪Lωθζ≔⁺ω§#.⊙η⊙…ηλ⁼×κ§ζν×μ§ζλω»⪪ωθ
```
[Try it online!](https://tio.run/##bZHLbsMgEEXX9VcgsgGJZNdVVlbSSpaSylL7A45NA@oYbANxk6rf7o4frZOobEYw9555kKusyW0GXZeYKviXUB5kw2q@jlqlQRK2k86xjQ3Gs1YQuqBckK0NB5AFyjgn@p2wpzpk4FBrjl6xFiVvupSO1YIMmtg5fTQshYCscw5yo2zV81IMz9oUMcAvnqObrvoyLXYhwUnyFT1MhL02iEiM3@qTLuS9ty8nyJy@aqjuuQqJt6i9LQLY/zlT7h5yuYIME6Ep9okp5CejixXFmzkzNYZ5WnwAdE@rGvfzMTsvghj@t7jyJgF8PONKvqO00fgdrxXo4VOwq3XXPXbLE/wA "Charcoal – Try It Online") Link is to verbose version of code. Brute force so too inefficient for `n>5`. Explanation:
```
Nθ
```
Input `n`.
```
W‹№ω#⊗θ
```
Repeat until a solution was found.
```
¿⁼Lω×θθ
```
Have we reached the end of the grid?
```
≔⁺…ω⊟⌕Aω#¦.ω«
```
In that case, one of our `#`s must have been placed incorrectly. Backtrack to the last one and replace it with a `.`, otherwise:
```
≔⁻÷⌕Aω#θ÷Lωθη
```
Get the list of indices of the `#`s so far, convert to rows, and subtract the current row from each, giving the relative rows.
```
≔⁻﹪⌕Aω#θ﹪Lωθζ
```
And again for the columns.
```
≔⁺ω§#.⊙η⊙…ηλ⁼×κ§ζν×μ§ζλω
```
Check whether any of the pairs of relative offsets are collinear and if so append a `.` otherwise append a `#`.
```
»⪪ωθ
```
Print the solution once it has been found.
Tweaking the test for an invalid solution allows `n=7` to be calculated on TIO at a cost of 3 bytes:
```
NθW‹№ω#⊗θ¿‹№ω#⊗÷Lωθ≔⁺…ω⊟⌕Aω#¦.ω«≔⁻÷⌕Aω#θ÷Lωθη≔⁻﹪⌕Aω#θ﹪Lωθζ≔⁺ω§#.⊙η⊙…ηλ⁼×κ§ζν×μ§ζλω»⪪ωθ
```
[Try it online!](https://tio.run/##fZFNTsMwEIXX5BSWu7Elt1sWXUUtSJFoFQkukCamtpjYaWw3tIizm0lSFFoB3ozsN@@bH5eqaEtbQIyZaYLfhnonW3bgy6RTGiRhT9I5trLBeNYJQmeUC7K2YQeywjTOiX79Pykzfq2PupKYZfZesQ7FwZk6p/eG5RDQfCpBrpRtekCO4VGbKgX45nE00UXP7bA3CU6Sj@TuQthog4ip0I23LyfIX30IopB4jdrYKoD9nXPRbiHnH5BhIjSlPjOVfGd0tqB4MyemxjBNiw@A7odDKMCxF11Lx94m51kQ09NHob4SgI9nXMlnkrca9//cgB5@Abtaxngf50f4Ag "Charcoal – Try It Online") Link is to verbose version of code.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~41~~ ~~39~~ ~~37~~ ~~36~~ ~~34~~ 33 bytes
```
`G:t!J*+tt1eGEZrt&-X/GEXy+Sd~z]m&
```
The output is a binary matrix.
Running time is random. Input `4` typically takes between 3 and 20 seconds on my computer.
[**Try it online!**](https://tio.run/##y00syfn/P8HdqkTRS0u7pMQw1d01qqhETTdC3901olI7OKWuKjZX7f9/YwA)
### Explanation
```
` % Do...while
G:t!J*+ % Generate n x n matrix representing a grid of complex numbers a+j*b,
% with a, b = 1, 2, ..., n (*)
t % Duplicate
t1e % Duplicate again and reshape as a row vector
GEZr % Randomly choose 2*n entries, without replacement (**)
t % Duplicate
&- % 2*n x 2*n matrix of pairwise differences between the chosen numbers
X/ % 2*n x 2*n matrix with the angle of each of those (complex)
% differences, in radians (***)
GEXy+ % Add identity matrix of size 2*n x 2*n
S % Sort each column
d % Consecutive differences along each column
~z % Number of zeros
] % End. A new iteration is run if the top of the stack is nonzero; that
% is, if the matrix (***) has been found to have two equal elements in
% the same column. That indicates that two points are aligned. This is
% because three complex numbers A, B, C are aligned if and only if
% there is one of them, say C, such that A-C and B-C have the same
% angle. The identity matrix has been added to avoid zeros in the
% diagonal, which would lead to incorrectly detecting alignment when
% there are just two points at the same vertical position (their
% complex difference has angle 0). Adding the identity matrix sets
% those diagonal entries to 1 radian, that is, 1/2/pi of a whole turn.
% Since the coordinates of the points are integer and pi is
% irrational, an angle difference of 1 radian will never occur for any
% pair of points (at least theoretically; in practice there may be
% numerical precision issues for huge grids).
m % For each point in the copy of the n x n complex grid (*), determine
% if it is present in the vector of chosen points (**). Gives an n x n
% matrix containing true or false, which will be displayed as 1 or 0
& % Configures the implicit display function so that it will only show
% the top of the stack
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 325 bytes
```
n->{int g[]=new int[n],i,r,a,b,d,e,j,x,y,c;for(java.util.Arrays.fill(g,3);;){for(i=-1,r=1;++i<n&r>0;r=g[i]>1<<n?g[i]=3:0)for(;n.bitCount(++g[i])!=2;);for(r=i=0;i<n*n;)for(a=i/n,b=i%n,j=++i;(g[a]&1<<b)>0&j<n*n;r|=c>1?1:0)for(x=j/n-a,y=j++%n-b,c=0,d=a+x,e=b+y;d>=0&d<n&e>=0&e<n;d+=x,e+=y)c+=(g[d]&1<<e)>0?1:0;if(r<1)return g;}}
```
[Try it online!](https://tio.run/##fVLBjpswEL3nK9xISezaYWFX6mHNsGorVeqhpz1GHAwYZEoGZMw2KM23p4awPbSrPaAZ8968Z95Qqxe1r4ufV3PsWutI7c/B4EwTfLZWjb1c/QeUA@bOtBh8Wxq5WnVD1pic5I3qe/JDGSTnFSHL294p58tLawpy9Bh9dtZgdUiJslXPZiohr2rxd3S60lYQg@6QJqQkQK64T87@TPwUoP41Y5gKI6xQIhOF0KIWJzGKXJatpf9@RlCapqGVeGBSsvPEMLCPhIVIcm5i3NoklBaqg0mTKI7xaerg4TFkE1dikBn3tR3QUc4niH2Ae8lmKwsGQuk1PqKc2QrMHYoMzAZFDV5e0uqg0q3XzVgSbuuZan9DnkRP0WJxgvoO90qMUHO@wX0mcghFAYqfhIaMj7JIINwW/qp6anSMsuDgQQ4jyzl4j2L20N5jkpWmpDaOmNVusEgqeblc5Zy09yN0CtP4ZO@lLzGQT75y/roMcgufWN0PjfO0MlBd14zUMLkQnsfe6WPQDi7o/Dpdg3TJ2rW3BdPbNPs7MufufZE8LspsQd6Uu6kEfuqoHF1v1tzwdb8Wyw/ifb4YVHZc3JCxwOquUbmmO7ITu3DH3rvtgl1W03O5/gE "Java (JDK) – Try It Online")
Works in time on TIO for up to `n = 6`.
## Explanation
(partial explanation)
This answer returns an int-array. Each int has exactly two bits set. The position of those bits represent the dots for that row.
The algorithm first makes sure that exactly two bits are set in each row. If that's the case, we go to the next part. If that's not the case, numbers are increased/reset until exactly two bits are set in each row.
We now have a grid with exactly 2 positions set each row.
For each of those positions, the algorithm checks each possible next position (on the right first, then each position downwards) and traces a line from the base position until the border, through each next positions. If the line goes through 0 or 1 set values, it goes to the next position.
If more than 1 positions are found, the algorithm will check the next grid.
## Credits
* -8 bytes and a pretty printer thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen).
* -1 byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)
] |
[Question]
[
Having spend some time on this site I have come to enjoy things being as short as possible. That may be the reason why I'm recently kind of offended by strings containing the same characters more than once. Your job is to write a function or program which *condenses* a given string according to the following rules:
* Start with a *0-condensation*, that is look for the first (leftmost) pair of the same characters with 0 other characters between them. If such a pair is found, remove one of the two characters and restart the algorithm by performing another *0-condensation*. If no such pair is found, proceed with the next step. Examples:
`programming` -C0-> `programing`
`aabbcc` -C0-> `abbcc`
`test` -C0-> `test`
* Then perform a *1-condensation*, that is look for the first pair of same characters with 1 other character between them. If such a pair is found remove one of them **and all characters between them** and restart with a *0-condensation*. If no such pair is found, proceed with the next step. Examples:
`abacac` -C1-> `acac`
`java` -C1-> `ja`
* Continue with a *2-condensation* and so on up to a *n-condensation* with *n* being the length of the original string, each time restarting after a condensation removed some letters. Examples:
`programing` -C2-> `praming`
`abcdafg` -C3-> `afg`
The resulting string is called *condensed* and contains each character at most once.
---
**Input:**
A lower case string of printable ascii-characters.
**Output:**
The *condensed* string according to the rules above.
**Examples:**
```
examples -> es
programming -> praming
puzzles -> puzles
codegolf -> colf
andromeda -> a
abcbaccbabcb -> acb
if(x==1):x++ -> if(x+
fnabnfun -> fun
abcdefae -> abcde
```
Detailed examples to clarify how the algorithm works:
```
fnabnfun -C0-> fnabnfun -C1-> fnabnfun -C2-> fnfun -C0-> fnfun -C1-> fun -C0-> fun
-C1-> fun -C2-> ... -C8-> fun
abcbaccbabcb -C0-> abcbacbabcb -C0-> abcbacbabcb -C1-> abacbabcb -C0-> abacbabcb
-C1-> acbabcb -C0-> acbabcb -C1-> acbcb -C0-> acbcb -C1-> acb -C0-> acb
-C1-> ... -C12-> acb
```
Your approach doesn't have to implement the algorithm from above as long as your solution and the algorithm return the same output for all allowed inputs.
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge.
---
Thanks to [@Linus](http://meta.codegolf.stackexchange.com/users/46756/linus) for helpful sandbox comments!
[Answer]
## JavaScript (ES6), 74 bytes
```
f=
(s,n=0,m=s.match(`(.).{${n}}\\1`))=>s[n]?m?f(s.replace(...m)):f(s,n+1):s
;
```
```
<input oninput=o.textContent=f(this.value)><pre id=o>
```
[Answer]
# Perl, ~~38~~ ~~31~~ ~~30~~ 29 bytes
This should should leave the non-golfing languages far behind...
-1 for `$-[0]` thanks to [Riley](https://codegolf.stackexchange.com/users/57100/riley)
-1 for `@{-}` thanks to [Dada](https://codegolf.stackexchange.com/users/55508/dada)
Includes +1 for `-p`
Give input on STDIN
`condense.pl`:
```
#!/usr/bin/perl -p
s/(.)\K.{@{-}}\1// while/./g
```
This 27 byte version should work but it doesn't because perl doesn't interpolate `@-` in a regex (see <https://stackoverflow.com/questions/39521060/why-are-etc-not-interpolated-in-strings>)
```
#!/usr/bin/perl -p
s/(.)\K.{@-}\1// while/./g
```
[Answer]
# [CJam](http://sourceforge.net/projects/cjam/), 35 bytes
```
rL{_,{{(_@_@#I={I)>]sj}*}h]s}fI}j
```
[Try it online!](http://cjam.tryitonline.net/#code=ckx7Xyx7eyhfQF9AI0k9e0kpPl1zan0qfWhdc31mSX1qCgo&input=Zm5hYm5mdW4)
---
```
rL{ }j | run recursion on input
_,{ }fI | for I from 0 to length(input)
{ }h]s | one pass & clean up
(_@ | slice and store leading element A
_@#I={ }* | if next A is I steps away
I)> | slice off I+1 element
]sj | clean up & recursion
```
You can see the individual condensations by [inserting `ed`](http://cjam.tryitonline.net/#code=ckx7ZWRfLHt7KF9AX0AjST17SSk-XXNqfSp9aF1zfWZJfWoKCg&input=Zm5hYm5mdW4)
[Answer]
# Python 2, ~~117~~ ~~104~~ 101 bytes
Recursively do the necessary replacements. I build the regex dynamically.
```
import re
def f(s,i=0):t=re.sub(r"(.)%s\1"%("."*i),r"\1",s);e=s==t;return i>len(t)and t or f(t,i*e+e)
```
[**Try it online**](https://repl.it/DiEM/2)
[Answer]
# Perl 53 52
Includes +1 for -p
```
for($i=0;$i<length;){$i=(s/(.).{$i}\1/\1/)?0:$i+1;}
```
Try it on [ideone](http://ideone.com/WyyE3d).
[Answer]
# Mathematica, 101 bytes
```
NestWhile[i=0;StringReplace[#,a_~~_~RepeatedNull~i++~~a_:>a,1]&,#,SameQ,2,ByteCount@#]&~FixedPoint~#&
```
There should be a way to make this shorter...
[Answer]
# PHP, 90 Bytes
```
for($s=$argv[$c=1];$s[$i=++$i*!$c];)$s=preg_replace("#(.).{{$i}}\\1#","$1",$s,1,$c);echo$s;
```
or 92 Bytes
```
for($s=$argv[1];$s[$i];$i=++$i*!$c)$s=preg_replace("#(.).{".+$i."}\\1#","$1",$s,1,$c);echo$s;
```
[Answer]
# Ruby, ~~75~~ ~~64~~ 57 bytes
(56 bytes of code + `p` command line option.)
Using string interpolation inside a regex to control the length of the matches that are replaced.
```
i=0
~/(.).{#{i}}\1/?sub($&,$1)&&i=0: i+=1while i<$_.size
```
Test:
```
$ ruby -p condense.rb <<< fnabnfun
fun
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~97~~ 88 bytes
```
(0?)
(a:s)!(b:t)|a==b=a:t|1<3=a:s!t
s!_=s
m?s|length s<m=s|a<-s!drop m s=sum[m+1|a==s]?a
```
[Try it online!](https://tio.run/##bc7NaoQwEADgc32KcelBEaHSmxh8gd56bEuZxMSV5g8ngiw@e23M3twewsxkvszkivQjtd4VsM@9eOnLrMCWyrzgbSg3ZIwzbMPWdK8xUh4yyr8ZZaanTUs7hitQZxht2NWUD7PzYIAYLebDVM3xnr563A1OFhgMLgO/hPcwv1l4BgUXuaLxWtLlqa5B0rntZzfOaMxkxyR8LGL@wJbbLQ1JZjnyMxFukKPTKo0RMTkDtPH3Rg6YBD60ueAo4onxLgQ/m0kVK2NN2a5VlcxxUZ2VssitWmwSMf6zaZAK5X3LUey/Qmkcaa@F938 "Haskell – Try It Online")
---
### Old 97 byte bersion:
```
(a:s)!(b:t)|a==b=a:t|1<3=a:s!t
s!_=s
m?s|length s==m=s|a<-s!drop m s=(last$0:[m+1|a==s])?a
c=(0?)
```
[Try it on ideone](https://ideone.com/NkXY2C).
**Explanation:**
```
(a:s)!(b:t)|a==b = a:t --perform condensation
|1<3 = a:s!t --recursively compare further
s ! _ = s --no condensation performed
```
The `(!)` function performs one n-condensation when given a string once whole and once with the first n characters removed, e.g. `abcdbe` and `cdbe` for a 2-condensation, by recursively comparing the two leading characters.
```
m?s|length s==m = s --stop before performing length-s-condensation
|a <- s!drop m s --a is the m-condensation of s
= (last$0:[m+1|a==s])?a --disguised conditional:
-- if a==s if the m-condensation did not change s
-- then (m+1)?a then perform m+1-condensation
-- else 0?a else restart with a 0-condensation
c=(0?) -- main function, initialise m with 0
```
] |
[Question]
[
## Background
I have a row of powerful magnets and a bunch of metal objects between them.
Where will the magnets pull them?
## Input
Your input is an array of non-negative integers, which will contain at least one `1`.
You can use any reasonable format.
The `0`s of the array represent empty space, and the `1`s represent fixed magnets.
All other numbers are metal objects, which are pulled by the magnets.
Every object gets pulled towards the nearest magnet (if there's a tie, the object is pulled to the right), and it travels in that direction until it hits the magnet or another object.
In the end, all the objects have clustered around the magnets.
The order of the objects is preserved.
## Output
Your output is the array where every object has been pulled as close to the nearest magnet as possible.
It should have the same format as the input.
## Example
Consider the array
```
[0,0,2,0,1,1,0,2,0,3,0,5,0,1,0]
```
The leftmost `2` gets pulled towards the first pair of magnets, as does the second `2`.
The `3` has a magnet four steps away in both directions, so it gets pulled to the right.
The `5` also gets pulled to the right, and it goes between the `3` and the magnet.
The correct output is
```
[0,0,0,2,1,1,2,0,0,0,0,3,5,1,0]
```
## Rules and scoring
You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
## Test cases
```
[0,1,0] -> [0,1,0]
[1,0,2,0,0,1,0] -> [1,2,0,0,0,1,0]
[7,0,5,0,0,1,0] -> [0,0,0,7,5,1,0]
[1,0,3,0,1,0,3,0,1] -> [1,0,0,3,1,0,0,3,1]
[1,0,0,0,0,0,0,7,3] -> [1,7,3,0,0,0,0,0,0]
[1,2,3,4,5,6,7,8,9,10,11,0,0,0,1] -> [1,2,3,4,5,6,7,0,0,0,8,9,10,11,1]
[12,3,0,0,1,0,1,3,0,0,6,12,0,0,0,1] -> [0,0,12,3,1,0,1,3,6,0,0,0,0,0,12,1]
```
[Answer]
# Pyth, ~~28~~ 20
```
[[email protected]](/cdn-cgi/l/email-protection)?bhaDk_x1QkQ~hZQ
```
Thanks @ThomasKwa for golfing 6 bytes!
This abuses stable sorting by assigning to all the values 1 or greater in the list the index of the nearest 1 (ties broken to the rightmost 1) and then sorting the list by these values. Zeroes are given their own index as their sort value.
[Test Suite](http://pyth.herokuapp.com/?code=o%40.e%3FbhaDk_x1QkQ~hZQ&input=%5B1%2C0%2C3%2C0%2C1%2C0%2C3%2C0%2C1%5D&test_suite=1&test_suite_input=%5B0%2C+1%2C+0%5D%0A%5B1%2C+0%2C+2%2C+0%2C+0%2C+1%2C+0%5D%0A%5B7%2C+0%2C+5%2C+0%2C+0%2C+1%2C+0%5D%0A%5B1%2C+0%2C+3%2C+0%2C+1%2C+0%2C+3%2C+0%2C+1%5D%0A%5B1%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+7%2C+3%5D%0A%5B1%2C+2%2C+3%2C+4%2C+5%2C+6%2C+7%2C+8%2C+9%2C+10%2C+11%2C+0%2C+0%2C+0%2C+1%5D%0A%5B12%2C+3%2C+0%2C+0%2C+1%2C+0%2C+1%2C+3%2C+0%2C+0%2C+6%2C+12%2C+0%2C+0%2C+0%2C+1%5D&debug=0)
[Verification Suite](http://pyth.herokuapp.com/?code=qo%40.e%3FbhaDk_x1QkQ~hZQE&input=%5B0%2C1%2C0%5D+-%3E+%5B0%2C1%2C0%5D%0A%5B1%2C0%2C2%2C0%2C0%2C1%2C0%5D+-%3E+%5B1%2C2%2C0%2C0%2C0%2C1%2C0%5D%0A%5B7%2C0%2C5%2C0%2C0%2C1%2C0%5D+-%3E+%5B0%2C0%2C0%2C7%2C5%2C1%2C0%5D%0A%5B1%2C0%2C3%2C0%2C1%2C0%2C3%2C0%2C1%5D+-%3E+%5B1%2C0%2C0%2C3%2C1%2C0%2C0%2C3%2C1%5D%0A%5B1%2C0%2C0%2C0%2C0%2C0%2C0%2C7%2C3%5D+-%3E+%5B1%2C7%2C3%2C0%2C0%2C0%2C0%2C0%2C0%5D%0A%5B1%2C2%2C3%2C4%2C5%2C6%2C7%2C8%2C9%2C10%2C11%2C0%2C0%2C0%2C1%5D+-%3E+%5B1%2C2%2C3%2C4%2C5%2C6%2C7%2C0%2C0%2C0%2C8%2C9%2C10%2C11%2C1%5D%0A%5B12%2C3%2C0%2C0%2C1%2C0%2C1%2C3%2C0%2C0%2C6%2C12%2C0%2C0%2C0%2C1%5D+-%3E+%5B0%2C0%2C12%2C3%2C1%2C0%2C1%2C3%2C6%2C0%2C0%2C0%2C0%2C0%2C12%2C1%5D&test_suite=1&test_suite_input=%5B0%2C+1%2C+0%5D%0A%5B0%2C+1%2C+0%5D%0A%5B1%2C+0%2C+2%2C+0%2C+0%2C+1%2C+0%5D%0A%5B1%2C+2%2C+0%2C+0%2C+0%2C+1%2C+0%5D%0A%5B7%2C+0%2C+5%2C+0%2C+0%2C+1%2C+0%5D%0A%5B0%2C+0%2C+0%2C+7%2C+5%2C+1%2C+0%5D%0A%5B1%2C+0%2C+3%2C+0%2C+1%2C+0%2C+3%2C+0%2C+1%5D%0A%5B1%2C+0%2C+0%2C+3%2C+1%2C+0%2C+0%2C+3%2C+1%5D%0A%5B1%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+7%2C+3%5D%0A%5B1%2C+7%2C+3%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%5D%0A%5B1%2C+2%2C+3%2C+4%2C+5%2C+6%2C+7%2C+8%2C+9%2C+10%2C+11%2C+0%2C+0%2C+0%2C+1%5D%0A%5B1%2C+2%2C+3%2C+4%2C+5%2C+6%2C+7%2C+0%2C+0%2C+0%2C+8%2C+9%2C+10%2C+11%2C+1%5D%0A%5B12%2C+3%2C+0%2C+0%2C+1%2C+0%2C+1%2C+3%2C+0%2C+0%2C+6%2C+12%2C+0%2C+0%2C+0%2C+1%5D%0A%5B0%2C+0%2C+12%2C+3%2C+1%2C+0%2C+1%2C+3%2C+6%2C+0%2C+0%2C+0%2C+0%2C+0%2C+12%2C+1%5D&debug=0&input_size=2)
### Explanation:
```
[[email protected]](/cdn-cgi/l/email-protection)?bhaDk_x1QkQ~hZQ ## implicit: Q = eval(input())
o Q ## Sort Q using the values of the lambda below
@ ~hZ ## select the value from the matching index of the enumerate
.e Q ## enumerate with b = value, k = index
?b ## ternary on b
haDk_x1Q ## if true, this thing
k ## otherwise use the index as the sort weight
_x1Q ## the indices of 1 in Q, given in reverse order
## (the reverse makes it sort to the right because of stable sorts)
aDk ## sort those indices by |index - k|
h ## take the first value
```
### Example:
Take the test case `[1,0,3,0,1,0,3,0,1]`, for example. When we apply the enumeration, the zeros will all get their own index as a sort value, so I'll skip those, and do a one and a three.
For the first one, we get the indices of ones: `[0, 4, 8]`. Then reverse it, and sort by the absolute value of the indices minus the index of the one, which happens to be zero here. So we get `[0, 4, 8]` back again. The first value is `0` so we use that.
For the three, we get the reversed indices and do the same sorting but using two as the index of the three, so both the `0` and the `4` give the same value for the absolute difference, so we get: `[4, 0, 8]` and we take the `4`.
Then the final "sorting values" array will be `[0, 1, 4, 3, 4, 5, 8, 7, 8]`. Thanks to the stable sort, the ties are broken by the order that the values originally appeared, so we get the final array we want.
[Answer]
## [Retina](https://github.com/mbuettner/retina/), ~~97~~ 72 bytes
```
+`(?<=\b1(,1*)*?)(\B,(11+)|,(11+))\b(?!(?<-1>,1*)*,1\b)|(11+),\B
$3,$4$5
```
Input is expected to be a comma-separated list of [unary integers](http://meta.codegolf.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary) (leading and trailing delimiters like `[...]` work just fine).
[Run all test cases here.](http://retina.tryitonline.net/#code=XGQrCiQwJCoxCitgKD88PVxiMSgsMSopKj8pKFxCLCgxMSspfCwoMTErKSlcYig_ISg_PC0xPiwxKikqLDFcYil8KDExKyksXEIKJDMsJDQkNQooMSkqKFtdLF0pCiQjMSQy&input=WzAsMSwwXQpbMSwwLDIsMCwwLDEsMF0KWzcsMCw1LDAsMCwxLDBdClsxLDAsMywwLDEsMCwzLDAsMV0KWzEsMCwwLDAsMCwwLDAsNywzXQpbMSwyLDMsNCw1LDYsNyw4LDksMTAsMTEsMCwwLDAsMV0KWzEyLDMsMCwwLDEsMCwxLDMsMCwwLDYsMTIsMCwwLDAsMV0) (For convenience, this takes care of the conversion from and to decimal automatically.)
Here is a completely different idea that avoids the expensive balancing groups by using multiple stage. It's currently 6 bytes longer, but might be more golfable:
```
,1\b
>1
\b1,
1<
(T`,`<`<1*,
)T`,`>`,1*>
+`(1+>)>
>$1
+`<(<1+\b)(?!>)
$1<
<|>
,
```
[Answer]
# JavaScript (ES6), 108 bytes
```
a=>a.map(_=>a.map((x,i)=>x>1?a[j=(n=a.indexOf(1,i))<0|n-i>i-p?i-1:i+1]?0:a[a[i]=0,j]=x:x<1?0:p=i,p=-1/0))&&a
```
## Explanation
Iterates over each cell and if it contains metal, checks if the next cell in the direction of the closest magnet is empty, and if it is, moves it there. This process is repeated many times until all metal has moved as far as it can go.
```
var solution =
a=>
a.map(_=> // loop a.length times to ensure completeness
a.map((x,i)=> // for each cell item x at index i
x>1? // if the cell contains metal
a[j= // j = index of cell to move to
(n=a.indexOf(1,i)) // n = index of next magnet
<0|n-i>i-p?i-1:i+1 // set j to previous or next cell based on closest magnet
]?0: // if cell j is empty
a[a[i]=0,j]=x // set it to x and set cell i to 0
:x<1?0: // else if the cell contains a magnet
p=i, // set p to the index of this magnet
p=-1/0 // p = index of previous magnet, initialise to -Infinity
)
)
&&a // return a
```
```
<input type="text" id="input" value="1,2,3,4,5,6,7,8,9,10,11,0,0,0,1" />
<button onclick="result.textContent=solution(input.value.split(',').map(n=>+n))">Go</button>
<pre id="result"></pre>
```
[Answer]
# PHP, 337 chars
```
<?$i=explode(",",$argv[1]);$m=$n=[];foreach($i as$k=>$v)if($v>0)eval("array_push(\$".($v<2?"m":"n").",$k);");for($p=0;$p<count($i);$p++)foreach($i as$k=>$v)if($v>1){$i[$k]=0;$r=-1;foreach($m as$_)if($r<0||abs($k-$r)>abs($_-$k))$r=$_;while($i[$r]>0)$r+=($r<$k?1:-1);$i[$r]=$v;}$s="";foreach($i as$v)$s.=$v.",";echo substr($s,0,-1)."\n";?>
```
Yes this is very long, because PHP is not really a language for golfing, but it works and I had FUN making it so it's fine to me. Of course I'm open to possible shortings.
Also there is a little bug feature which thinks, so for example here:
```
root@raspberrypi:~/stack# php magnet.php 12,3,0,0,1,0,1,3,0,0,6,12,0,0,0,1
0,0,3,12,1,0,1,3,6,0,0,0,0,0,12,1
```
it looks like the 12 magicly got in front of the 3, but that's not true!
The 3 respects the bigger number and lets it go closer to the maget!
[Answer]
# [Haskell](https://www.haskell.org/), 127 bytes
```
(a:b)!(c:d)=c/=1&&a==1||b!d
_!_=1<0
infix 4#
x@(a:b)#0:i@(c:d)|i!x=a:0:b#i|x!i=c:x#0:d
x#a:b=a:x#b
x#[]=x
l=([]#)
l.l.l.reverse
```
[Try it online!](https://tio.run/##TYvRCsIgGIXvfQrFGBuM0upK@mHvMcbQaUuyFVuEF7676aiIAz//Oec7F7lcjXMxllKoipSD0BUMO@BFIQF4CIpo1JMe@IkhO52tx0eKfLPilAnbrJNgiQcpmFDUBk8sDMKnViNPE5gaT1X62w48clC2Ha3QCG6bNZuXmRcTb9JOoO8I48dspyfe4BG3@5rVvM4365DEkuM/z1efmW/G/tjDZ8G7@AY "Haskell – Try It Online")
Instead of moving the objects towards the magnets we move the empty space away from the magnets.
A big frustration for me was that the default was to the right. Defaulting to the left could have saved me 10 bytes. To default to the left we do `l.l` to default to the right we need `l.l.l.reverse`.
When we run `l` it naturally reverses the list, however this is actually pretty convenient since we need to run it on the list going both ways, so the output is ready to go for the second run. Unfortunately though since to default to the right this means we need to reverse it manually first, then run it twice, we end up needing an additional `l` to get it back to the correct order.
] |
[Question]
[
Your task is to sum up and output one player's score in a game of 10-pin bowling after *up to* 21 **rolls**.
The rolls are represented as a sequence of integers in your [preferred method of input](https://codegolf.meta.stackexchange.com/q/2447/4372).
Each integer corresponds to the number of pins that were knocked down in that roll.
## Scoring
After each **round** the number of pins knocked down in that round is counted into the final score.
If a player knocks down all ten pins in the first roll of a round, this is a **strike**, and the round is over.
Otherwise, the round lasts for one more roll. If the second roll of a round knocks down all the remaining pins, this is a **spare**.
For each strike there is a **bonus** equal to the sum of pins knocked down in the two next rolls.
For each spare there is a bonus equal to the number of pins knocked down in the next roll.
The 10th and final round, the player may be granted extra rolls:
In case of a strike, the player gets two more rolls to make up his strike bonus.
In case of a spare, the player gets one more roll.
## Examples
```
Input: 4 3 8 2 7 1 10 7 3 0 10 2 2 10 10 5 4
Output: 131
Input: 10 10 9 1 7 3 2 7 10 1 9 10 7 1 10 10 10
Output: 183
```
## Rules
* You may assumed that the input is valid.
* As per Mego's comment I have loosened the requirements for the input/output methods to meet our [current standard](https://codegolf.meta.stackexchange.com/q/2447/4372).
* Answers in **languages that are newer than the challenge are allowed**
* Shortest code wins!
[Answer]
### GolfScript, 50 41 characters
```
~0]-1%~0{\.9>{+1$3$}{@+.9>3$*}if++}10*p];
```
Another attempt in GolfScript ([run it online](http://golfscript.apphb.com/?c=Oyc0IDMgOCAyIDcgMSAxMCA3IDMgMCAxMCAyIDIgMTAgMTAgNSA0JwoKfjBdLTElfjB7XC45PnsrMSQzJH17QCsuOT4zJCp9aWYrK30xMCpwXTsKCjsnMTAgMTAgOSAxIDcgMyAyIDcgMTAgMSA5IDEwIDcgMSAxMCAxMCAxMCcKCn4wXS0xJX4we1wuOT57KzEkMyR9e0ArLjk%2BMyQqfWlmKyt9MTAqcF07)).
An explanation of the code follows. The solution utilises the stack nature of the problem (consume rolls one after another) but therefore the input has to be reversed.
```
~0 # Take the input and evaluate to single numbers on the stack. Add zero.
]-1%~ # Reverse the stack (make array, reverse array, dump array)
0 # Start with a sum of zero
{ # Perform this block 10 times (once for each round)
\ # Take the next roll
.9>{ # If it is a strike
+ # Add the value of the roll to the sum
1$3$ # and duplicate top two members of the stack (i.e. next two rolls).
}{ # ... else ...
@+ # Take the next roll and add with first roll in round.
.9> # Does this sum show a spare?
3$* # Get next roll (potential bonus) and multiply with yes/no.
# Since we pushed an additional 0 in the beginning
# there is a spare roll even for the last round.
}if # endif
++ # Add top three stack entries together
# (i.e. sum+2 bonus rolls for strike, sum+rolls+bonus else)
}10* # Loop ten times
p]; # Sum is top of stack. Print sum and discard any leftover rolls.
```
Previous version:
```
~].1>.1>]zip{((.10<{@(0=@+@1>1$9><}*@}10*;]{+}.@**
```
[Answer]
## Python, 116 110 105 103 100 99 characters
```
z=map(int,raw_input().split())
s=0
exec('s+=sum(z[:2+(z[0]+z[1]>9)]);z=z[2-(z[0]>9):];'*10)
```
Spending 30 characters on input is irksome. Suggestions welcome.
Much thanks to Howard for improvements.
[Answer]
# R, 101 bytes
I am not sure why this challenge was bumped, but I like it, so I'll late answer anyways.
```
f=function(x,s=0,c=10)`if`(c&length(x),f(x[-(0:(x[1]!=10)+1)],sum(x[1:(2+(sum(x[1:2])>9))])+s,c-1),s)
```
[Try it online!](https://tio.run/##PYvvCgIhEMS/9xT2JXZxD9QuqgN7kRAOJOugDPIOfHtT7w/ssMPMb34pOe0mb8fh6yFS0IKslgL7wfVgD@@Hf44viEgO4r0B0eUnzb4gXKKhMH1K0oHisHpl8FYANMgD2UYiBUwOLEhBrOiaH7EzsSMxVU1t5kLMwZJVIe7KvK2Dy7bZ4JwurKq3Lk/EWsT0Bw "R – Try It Online")
Ungolfed:
```
f <- function(throws, score = 0, count = 10){
if(count != 0 & length(throws) != 0){
IsStrike <- throws[1] == 10
IsStrikeOrSpare <- sum(throws[1:2]) >= 10
f(throws[-c(1, 2 * !IsStrike)],
score + sum(throws[c(1:(2 + IsStrikeOrSpare))]),
count - 1)
} else {
return(score)
}
}
```
Recursive function. Takes `x` as input, which holds the scores. Initialises the `s`cores and `c`ounts the amount of rounds thrown.
The if statement checks if 10 rounds are thrown, or if `x` is empty. If that is the case, the score is returned. Else the function will call itself as follows:
It removes the throws from `x`, by checking if it is a strike or not. If so, the first entry is removed, else the first two. `(S=x[1]!=10)` checks for strikes. We remove (`-`) index `0:S`, where `S` is 1 if it is a strike, and 0 if not. And then we add one: `-(0:(x[1]!=10)+1)`. We pass the shortened `x` to the next call.
As for the score, this is found by taking `x[1:2]` if it is a regular turn, and `x[1:3]` if it is a strike or a spare. We check if `sum(x[1:2])` is bigger or equal than 10. If it is a strike, obviously this is the case. If it is a spare, then this works as well. So if this is TRUE, we add `x[3]` to the sum. This is then added to `s`.
[Answer]
## CoffeeScript (234 215 170)
```
z=(a)->b=(Number i for i in a.split(' ').reverse());t=0;(r=b.pop();l=b.length;if(9<r)then(t+=r;t+=b[l-1]+b[l-2];)else(f=r+b.pop();t+=f;(t+=b[l-2])if 9<f))for i in[0..9];t
```
**EDIT**: A hefty re-write, shamelessly plagiarising Howard's great stack-based approach. I'm confident more can be stripped out for accessing the last element of an array without destroying it...
[Answer]
# Ruby, 252 bytes
Accepts input into an array add all elements first, then searches for spare and strike bonus
```
s,p,t,r=0,0,1,1
o=ARGV
o.each_with_index do |m,n|
y=m.to_i
s+=y
if r<10
p+=y
if p==10&&t==1
r,p=(r+1),0
s+=o[n+1].to_i+o[n+2].to_i
elsif p<10&&t==1
t=2
elsif p<10&&t==2
t,p,r=1,0,(r+1)
elsif p==10&&t==2
t,p,r=1,0,(r+1)
s+=o[n+1].to_i
end end end
puts s
```
[Answer]
# PHP, 82 bytes
```
for($a=$argv;$r++<10;$i+=$p<10)$s+=(9<$q=$a[++$i+1]+$p=$a[$i])*$a[$i+2]+$q;echo$s;
```
takes input from command line arguments; run with `-nr` or [test it online](http://sandbox.onlinephpfunctions.com/code/5bc3e94901bd2af400521cbb42c90cfca4355121).
**breakdown**
```
for($a=$argv; # import arguments
$r++<10; # loop through rounds
$i+=$p<10) # 6. if no strike, increment throw count again
$s+=(9<
$q=$a[++$i+1]+ # 1. increment throw count 2. $q=second throw plus
$p=$a[$i] # 3. $p=first throw
)*$a[$i+2] # 4. if $q>9 (strike or spare), add third throw to sum
+$q; # 5. add first and second throw to sum
echo$s; # print sum
```
[Answer]
# [Perl 5](https://www.perl.org/), 65 + 2 = 67 bytes
Requires `-ap` flags
```
$\+=(($"=shift@F)<10?$"+=shift@F:10+$F[1])+$F[0]*(9<$")for 0..9}{
```
[Try it online!](https://tio.run/##K0gtyjH9/18lRttWQ0NFybY4IzOtxMFN08bQwF5FSRvGtzI00FZxizaM1QRRBrFaGpY2KkqaaflFCgZ6epa11f//GxooAJGlgqGCuYKxghGQBImABAxAbAWIvKHBv/yCksz8vOL/ur6megaGBv91EwsA "Perl 5 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~36~~ 35 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
+\µi©⁵+Ị$ḂḤị;®×Ị¤¡-
;0Ç3ƤFṣ-m€2Fḣ⁵S
```
A monadic link accepting a list of integers and returning an integer.
**[Try it online!](https://tio.run/##y0rNyan8/1875tDWzEMrHzVu1X64u0vl4Y6mhzuWPNzdbX1o3eHpQJFDSw4t1OWyNjjcbnxsidvDnYt1cx81rTFye7hjMVBP8P///6NNdBSMdRQsdBSMdBTMdRQMgcgAzAKKGkA4RmBkCOWZ6iiYxAIA "Jelly – Try It Online")**
### How?
Calculates the score of each overlapping run of three bowls as if it were one that started at the beginning of a frame and optionally appends a strike identifier (`-1`), flattens this resulting list, splits it at the strike identifiers, then discards every second result from each chunk (removing the scores of those runs that did not really start with the start of a frame).
To cater for the final frame a zero is first appended to the input (to allow the 3-wise slicing to allow a frame to start on what was the penultimate bowl) and the resulting scores are truncated to the first ten (to remove the now possible bogus 11th frame) prior to summing them up.
```
+\µi©⁵+Ị$ḂḤị;®×Ị¤¡- - Link 1, threeBowlEvaluate: list, bowlScores
- e.g. [0,4,6] [9,1,10] [0,4,4] [10,7,9]
\ - cumulative reduce with:
+ - addition [0,4,10] [9,10,20] [0,4,8] [10,17,26]
µ - monadic chain separation, call that "left"
⁵ - literal ten 10 10 10 10
i - first index in left 3 2 (spare) 0 1 (strike)
© - (copy to register for later reuse)
$ - last two links as a monad (f(x)):
Ị - abs(x) <= 1 0 0 1 1
+ - add x 3 2 1 2
Ḃ - modulo by 2 1 0 1 0
Ḥ - double 2 0 2 0
ị - index into left (both 1-indexed and modular)
- ... 4 20 4 26
- - literal -1 -1 -1 -1 -1
¡ - repeat:
; - ...action: concatenate
¤ - ...number of times: nilad followed by link(s) as a nilad:
® - z from register 3 2 0 1
Ị - abs(z) <= 1 0 0 1 1
× - multiply 0 0 0 1 (strike)
- ...yielding: 4 20 4 [26,-1]
;0Ç3ƤFṣ-m€2Fḣ⁵S - Main link: list bowlValues
- e.g. [4,3,8,2,7,1,10,7,3,0,10,2,2,10,10,5,4]
0 - literal zero 0
; - concatenate [4,3,8,2,7,1,10,7,3,0,10,2,2,10,10,5,4,0]
3Ƥ - for infixes of length 3:
Ç - last link (1) as a monad
- [7,11,17,9,8,11,[20,-1],10,3,12,[14,-1],4,12,[25,-1],[19,-1],9]
F - flatten [7,11,17,9,8,11,20,-1,10,3,12,14,-1,4,12,25,-1,19,-1,9]
- - literal -1 -1
ṣ - split at [[7,11,17,9,8,11,20],[10,3,12,14],[4,12,25],[19],[9]]
2 - literal two 2
m€ - modulo slice for €ach [[7,17,8,20],[10,12],[4,25],[19],[9]]
F - flatten [7,17,8,20,10,12,4,25,19,9]
⁵ - literal ten 10
ḣ - head to index [7,17,8,20,10,12,4,25,19,9] (no effect this time)
S - sum 131
```
[Answer]
# JavaScript (ES6), ~~79 78 72 69~~ 68 bytes
```
f=([x,y,...r],n=9)=>x+y+~~r[!n|x+y>9?0:f]+(n&&f(x>9?[y,...r]:r,n-1))
```
[Try it online!](https://tio.run/##XYxRC4IwFIXf@xX2Mja8zs0ZuUD7IcMHMZVCtpgRCuFfX5vVS/deOIfDud@teTZTa6/3R6LNpXOuL7GaYQFKqa1Bl5KU1RwvMd7rl9dKIrSuVrGaxFgj1OO5kmf17Z8s6IQT4lqjJzN2dDQD7rHKQUABGRyBA2deBLBgMr98cwfIa0IiP2kaccF3f4RPS/r/8LyRfBIC9qNuFyCBUAj3Bg "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
[x, // x = result of the current roll
y, // y = result of the next roll
...r], // r[] = remaining results
n = 9 // n = remaining number of rounds
) => //
x + y + // add x + y to the score
~~r[ //
!n | // if this is the last round
x + y > 9 ? // or this is either a spare or a strike:
0 // add the result of the next roll to the score
: // else:
f // use a dummy index so that nothing is added
] + ( //
n && // if n is not equal to 0:
f( // add the result of a recursive call:
x > 9 ? // if this is a strike:
[y, ...r] // re-insert y into r[]
: // else:
r, // pass r[] unchanged
n - 1 // decrement n
) // end of recursive call
) //
```
[Answer]
## Perl, 140?
First attempt:
```
#!/usr/bin/perl
# usage: ./bowling.pl [list of scores]
@A=@ARGV;{last if(9<$n++);$a=shift@A;$S+=$a;($S+=$A[0]+$A[1])&redo if($a==10);$b=shift@A;$S+=$b;($S+=$A[0])&redo if(10==$a+$b);redo}print$S
```
Sadly, there are certain cases where it fails. I will come and redo it later.
] |
[Question]
[
Your task is to create the shortest program (A) that outputs another program (B) with the most unique bytes, which in turn outputs the original program (A). Essentially, you are golfing one half of a pair of [ouroboros programs](https://en.wikipedia.org/wiki/Quine_(computing)#Ouroboros_programs) (a.k.a. periodic iterating quine) and bowling the other half. A and B may be in different languages.
## Rules and Scoring
Your final score is `<number of unique bytes in B> / <number of bytes in A>`. Highest score wins. It should be noted that the theoretical maximum score is 256.
* Program A must be at least one byte long
* Program B cannot consist entirely of no-ops, i.e. at least one character must affect the output in some way.
* [Standard rules of quines apply](https://codegolf.meta.stackexchange.com/questions/4877/what-counts-as-a-proper-quine) to both programs. Notably, error quines are not allowed in either case.
For the sake of answer format consistency, begin your answer with something like this:
```
# <Language for A> & <Language for B>, Score: <B score> / <A score> = <combined score>
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) & [Japt](https://github.com/ETHproductions/japt), Score: 255 / 38 = [6.71](https://ethproductions.github.io/japt/?v=1.4.6&code=MjU1LzM4&input=)
[Program A](https://ethproductions.github.io/japt/?v=1.4.6&code=ImlRILKvMjQKR7L1QGknIytYZCJpUSCyrzI0Ckey9UBpJyMrWGQ=&input=):
```
"iQ ²¯24
G²õ@i'#+Xd"iQ ²¯24
G²õ@i'#+Xd
```
[Program B](https://ethproductions.github.io/japt/?v=1.4.6&code=IwEiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIwIiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIwMiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIwQiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIwUiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIwYiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIwciaVEgsq8yNApHsvVAaScjK1hkImlRILIsIwgiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIwkiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIwoiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIwsiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIwwiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIwoiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIw4iaVEgsq8yNApHsvVAaScjK1hkImlRILIsIw8iaVEgsq8yNApHsvVAaScjK1hkImlRILIsIxAiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIxEiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIxIiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIxMiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIxQiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIxUiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIxYiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIxciaVEgsq8yNApHsvVAaScjK1hkImlRILIsIxgiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIxkiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIxoiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIxsiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIxwiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIx0iaVEgsq8yNApHsvVAaScjK1hkImlRILIsIx4iaVEgsq8yNApHsvVAaScjK1hkImlRILIsIx8iaVEgsq8yNApHsvVAaScjK1hkImlRILIsIyAiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIyEiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIyIiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIyMiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIyQiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIyUiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIyYiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIyciaVEgsq8yNApHsvVAaScjK1hkImlRILIsIygiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIykiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIyoiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIysiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIywiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIy0iaVEgsq8yNApHsvVAaScjK1hkImlRILIsIy4iaVEgsq8yNApHsvVAaScjK1hkImlRILIsIy8iaVEgsq8yNApHsvVAaScjK1hkImlRILIsIzAiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIzEiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIzIiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIzMiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIzQiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIzUiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIzYiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIzciaVEgsq8yNApHsvVAaScjK1hkImlRILIsIzgiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIzkiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIzoiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIzsiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIzwiaVEgsq8yNApHsvVAaScjK1hkImlRILIsIz0iaVEgsq8yNApHsvVAaScjK1hkImlRILIsIz4iaVEgsq8yNApHsvVAaScjK1hkImlRILIsIz8iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI0AiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI0EiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI0IiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI0MiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI0QiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI0UiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI0YiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI0ciaVEgsq8yNApHsvVAaScjK1hkImlRILIsI0giaVEgsq8yNApHsvVAaScjK1hkImlRILIsI0kiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI0oiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI0siaVEgsq8yNApHsvVAaScjK1hkImlRILIsI0wiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI00iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI04iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI08iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI1AiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI1EiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI1IiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI1MiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI1QiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI1UiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI1YiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI1ciaVEgsq8yNApHsvVAaScjK1hkImlRILIsI1giaVEgsq8yNApHsvVAaScjK1hkImlRILIsI1kiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI1oiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI1siaVEgsq8yNApHsvVAaScjK1hkImlRILIsI1wiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI10iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI14iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI18iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI2AiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI2EiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI2IiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI2MiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI2QiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI2UiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI2YiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI2ciaVEgsq8yNApHsvVAaScjK1hkImlRILIsI2giaVEgsq8yNApHsvVAaScjK1hkImlRILIsI2kiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI2oiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI2siaVEgsq8yNApHsvVAaScjK1hkImlRILIsI2wiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI20iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI24iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI28iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI3AiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI3EiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI3IiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI3MiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI3QiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI3UiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI3YiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI3ciaVEgsq8yNApHsvVAaScjK1hkImlRILIsI3giaVEgsq8yNApHsvVAaScjK1hkImlRILIsI3kiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI3oiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI3siaVEgsq8yNApHsvVAaScjK1hkImlRILIsI3wiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI30iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI34iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI38iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI4AiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI4EiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI4IiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI4MiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI4QiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI4UiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI4YiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI4ciaVEgsq8yNApHsvVAaScjK1hkImlRILIsI4giaVEgsq8yNApHsvVAaScjK1hkImlRILIsI4kiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI4oiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI4siaVEgsq8yNApHsvVAaScjK1hkImlRILIsI4wiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI40iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI44iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI48iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI5AiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI5EiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI5IiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI5MiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI5QiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI5UiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI5YiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI5ciaVEgsq8yNApHsvVAaScjK1hkImlRILIsI5giaVEgsq8yNApHsvVAaScjK1hkImlRILIsI5kiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI5oiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI5siaVEgsq8yNApHsvVAaScjK1hkImlRILIsI5wiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI50iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI54iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI58iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI6AiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI6EiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI6IiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI6MiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI6QiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI6UiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI6YiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI6ciaVEgsq8yNApHsvVAaScjK1hkImlRILIsI6giaVEgsq8yNApHsvVAaScjK1hkImlRILIsI6kiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI6oiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI6siaVEgsq8yNApHsvVAaScjK1hkImlRILIsI6wiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI60iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI64iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI68iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI7AiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI7EiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI7IiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI7MiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI7QiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI7UiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI7YiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI7ciaVEgsq8yNApHsvVAaScjK1hkImlRILIsI7giaVEgsq8yNApHsvVAaScjK1hkImlRILIsI7kiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI7oiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI7siaVEgsq8yNApHsvVAaScjK1hkImlRILIsI7wiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI70iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI74iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI78iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI8AiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI8EiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI8IiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI8MiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI8QiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI8UiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI8YiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI8ciaVEgsq8yNApHsvVAaScjK1hkImlRILIsI8giaVEgsq8yNApHsvVAaScjK1hkImlRILIsI8kiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI8oiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI8siaVEgsq8yNApHsvVAaScjK1hkImlRILIsI8wiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI80iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI84iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI88iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI9AiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI9EiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI9IiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI9MiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI9QiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI9UiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI9YiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI9ciaVEgsq8yNApHsvVAaScjK1hkImlRILIsI9giaVEgsq8yNApHsvVAaScjK1hkImlRILIsI9kiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI9oiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI9siaVEgsq8yNApHsvVAaScjK1hkImlRILIsI9wiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI90iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI94iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI98iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI+AiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI+EiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI+IiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI+MiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI+QiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI+UiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI+YiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI+ciaVEgsq8yNApHsvVAaScjK1hkImlRILIsI+giaVEgsq8yNApHsvVAaScjK1hkImlRILIsI+kiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI+oiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI+siaVEgsq8yNApHsvVAaScjK1hkImlRILIsI+wiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI+0iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI+4iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI+8iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI/AiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI/EiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI/IiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI/MiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI/QiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI/UiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI/YiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI/ciaVEgsq8yNApHsvVAaScjK1hkImlRILIsI/giaVEgsq8yNApHsvVAaScjK1hkImlRILIsI/kiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI/oiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI/siaVEgsq8yNApHsvVAaScjK1hkImlRILIsI/wiaVEgsq8yNApHsvVAaScjK1hkImlRILIsI/0iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI/4iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI/8iaVEgsq8yNApHsvVAaScjK1hkImlRILIsI1x1MDEwMCJpUSCyrzI0Ckey9UBpJyMrWGQiaVEgsg==&input=) is over 8kB long, so long that the link breaks, so I won't paste the whole thing. Here's a sample:
```
#þ"iQ ²¯24
G²õ@i'#+Xd"iQ ²,#ÿ"iQ ²¯24
G²õ@i'#+Xd"iQ ²,#Ā"iQ ²¯24
G²õ@i'#+Xd"iQ ²
```
I couldn't find a way to get a `NUL` byte to work, which is why program B only has 255 unique characters. Program B essentially consists of 255 copies of a single program, where a single irrelevant byte is changed each time, and the first 254 executions are ignored.
For the explanation, I'll start with [this](https://ethproductions.github.io/japt/?v=1.4.6&code=ImlRILKvMjMKM/VAaScjK1hkImlRILKvMjMKM/VAaScjK1hk&input=) simplified version of A so that the resulting B is easier to discuss.
```
"iQ ²¯23
3õ@i'#+Xd"iQ ²¯23
3õ@i'#+Xd
```
This program is based on the [basic payload-capable Japt quine](https://codegolf.stackexchange.com/a/71932/71434). The string at the start contains a duplicate of the rest of the program, `iQ ²` inserts a quote and duplicates to create a string representation of the entire program, and then `¯23` trims off itself and everything after it. The resulting string is [a program that outputs Program A](https://ethproductions.github.io/japt/?v=1.4.6&code=ImlRILKvMjMKM/VAaScjK1hkImlRILI=&input=):
```
"iQ ²¯23
3õ@i'#+Xd"iQ ²
```
I will refer to this string as `U`.
The last line of A duplicates `U` a bunch of times with a small change each time. Specifically, for each number `X` in the range `[1...3]` it outputs `"#c" + U` where `c` is the character with charcode `X`. The default behavior of Japt is to output those strings with no quotation marks and separated by commas, so this is the output of our Simplified A (note that there's an unprintable byte between each `#` and `"iQ`:
```
#"iQ ²¯23
3õ@i'#+Xd"iQ ²,#"iQ ²¯23
3õ@i'#+Xd"iQ ²,#"iQ ²¯23
3õ@i'#+Xd"iQ ²
```
We'll call this [Simplified B](https://ethproductions.github.io/japt/?v=1.4.6&code=IwEiaVEgsq8yMwoz9UBpJyMrWGQiaVEgsiwjAiJpUSCyrzIzCjP1QGknIytYZCJpUSCyLCMDImlRILKvMjMKM/VAaScjK1hkImlRILI=&input=).
Simplified B has a simple structure, alternating between `#c` and `U`. Fortunately for this answer, each `#c` and `U` is treated as separated by a comma, and in this situation the behavior of that is everything except the very last `U` has no effect on the output. The only portion of Simplified B which affects the output is this:
```
"iQ ²¯23
3õ@i'#+Xd"iQ ²
```
Which is identical to `U` that we already know outputs Simplified A.
The only difference between Simplified A and Program A is that instead of generating copies for the range `[1...3]` the real program generates copies for the range `[1...256]`. That results in 256 versions of `#c` each of which has a different character, though the last version "Ā" is a multi-byte character so it doesn't add any unique bytes, but everything except the last `U` is still ignored.
[Answer]
# Program A, [Gol><>](https://github.com/Sp3000/Golfish), 256/20 bytes = 12.8
```
"44XFL|r2ssl3%Q4s]|H
```
[Try it online!](https://tio.run/##S8/PScsszvj/X8nEJMLNp6bIqLg4x1g10KQ4tsbj/38A "Gol><> – Try It Online")
# Program B, [Gol><>](https://github.com/Sp3000/Golfish)
```
"44XFL|r2ssl3%Q4s]|H
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ
```
[Try it online!](https://tio.run/##BcEHV5IBAAXQrMy0jmWZTc0oK02zkNSWacOsbJALV5qWE@fXDk0F3FscDAHBDQ4QB7jOee@H0b3ldfKySqHC6xVJJLLUdEWjWBDkcRFSiVCoSDvgc/DQYd8jfkf9A44dDwg8cTLo1OngMyFnz52/cPFSaNjl8Cuiq9cirt@4GRl1Kzrmduydu@I4yb34hMT7Dx4@epz0JDnl6bPnL1Jfpr16/Sb97bv3H6QfMzKzsnNkuXn5BYWfioo/l5R@@VpWXlFZVS2vqa2rb2gUvn3/8fPX7z9/FU3N/9CCVrRBCRXUaEcHOtGFbvSgF33oxwAGMYRhjECDUYxhHBPQQgc9DJiEESaYMQULrJjGDGYxh3ksYBE22LGEZaxgFQ44sQYX1rGBTWzBDQ@2sYNd7GGfLWxlG5VUUc12drCTXexmD3vZx34OcJBDHOYINRzlGMc5QS111NPASRppoplTtNDKac5wlnOc5wIXaaOdS1zmClfpoJNrdHGdG9zkFt30cJs73OUe973e/w "Gol><> – Try It Online")
The program alternates between outputting itself followed by every byte and just outputting itself.
### Explanation:
```
" Wrapping string literal pushes the first line to the stack backwards
44X Push 256
FL| Push the range from 0 to 255
r Reverse the stack
2ss Push a quote
l3% If the stack length is divisible by 3
Q4s]| Only take the top 20 characters
H And output the stack
```
[Answer]
# Program A: [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score: ~~256/41~~ 256/31 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) = 8.258...
```
0"D34çý₅Ýç'q†22ǝ"D34çý₅Ýç'q†22ǝ
```
[Try it online.](https://tio.run/##yy9OTMpM/f/fQMnF2OTw8sN7HzW1Hp57eLl64aOGBUZGx@fiEv//HwA)
# Program B: [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands)
```
0"D34çý₅Ýç'q†22ǝ"D34çýq
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnoprstuvwxyz{|}~ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿÝç'q†22ǝ
```
[Try it online.](https://tio.run/##VdHpOxMAAMfxBxWpp1BKRY5EUWGUo3JXKtGFyk2qdQ0jOs3YHHPf1xgbO8wx18w2nuf3e@H/8I@MN1709vvy8xWJS8uEFQ5HZFB6dAy1tO9JZVRSG1q1J1EJBLvKw17l5Oxy5OgxV7fj7idOup867eHpdeas97nzPhcuXvL1u@wfEBh0JfhqSOi162HhN27eioiMEkTH3L4TGxefcPfe/cSk5JTUtPQHDx9lPH7yNPNZVvbzFy9fvc7JzXvz9l1@QWFRcUlpWfn7ig8fPwk/f/n67buoslpcU/ujrv7nr99//v5rgASNkKIJzZBBjha0og3tUKADnehCN3rQiz70YwCDGMIwRjCKMYxjAkpMYgoqTGMGamgwizlooYMeBszDiAUsYgnLMGEFq1jDOjZgxiYs2IIVNtixjR1K2Egpm9hMGeVsYSvb2E4FO9jJLnazh73sYz8HOMghDnOEoxzjOCcONCc5RRWnOUM1NZzl3AGojnoaOE8jF7jIJS7TxBWuco3r3KCZm7Rwi1baaOc2d/574nDsAw)
**Explanation:**
The shortest [quine](/questions/tagged/quine "show questions tagged 'quine'") for 05AB1E is this one: `0"D34çý"D34çý` (**14 bytes**) [provided by *@OliverNi*](https://codegolf.stackexchange.com/a/97899/52210). My answer uses a modified version of that quine by adding `₅Ýç'q†vy27ǝD}J`.
```
0 # Push a 0 to the stack
# STACK: [0]
"D34çý₅Ýç'q†vDy27ǝ}J"
# Push the string "D34çý₅Ýç'q†vDy27ǝ}J" to the stack
# STACK: [0,"D34çý₅Ýç'q†vDy27ǝ}J"]
D # Duplicate the string
# STACK: [0,"D34çý₅Ýç'q†vDy27ǝ}J","D34çý₅Ýç'q†vDy27ǝ}J"]
34çý # Join the stack by '"'
# STACK: ['0"D34çý₅Ýç'q†vDy27ǝ}J"D34çý₅Ýç'q†vy27ǝD}J']
₅Ý # Push a list in the range [0,255]
ç # Convert each integer to an ASCII character
'q† '# Filter the "q" to the front
22ǝ # Insert it at index 22 in the string (replacing the second '₅')
# (and output the result implicitly)
```
Program B will terminate as soon as it reaches the `q`, so the actual program B is:
```
0"D34çý₅Ýç'q†22ǝ"D34çýq
```
Everything after that is ignored, and the top of the stack (`0"D34çý₅Ýç'q†22ǝ"D34çý₅Ýç'q†22ǝ`) is output implicitly.
] |
[Question]
[
Your goal is to write a program that will solve any Mastermind puzzle in 6 or less moves.
### Background
Mastermind is a board game. The goal of the game is to exactly guess the combination (colours and order) of 4 coloured pegs hidden by the other player. When a guess is made, the other player responds with between 0 and 4 white and or red pegs. A red peg is where the colour and location are correct. A white peg is where the colour is represented in the remaining pieces, but is in the incorrect location. If there are duplicate colours in the guess, there will only be one peg awarded per corresponding colour in the secret. (So - if the secret contained 1 Blue, and the guess had 2 blues with one in the correct location, there would be one red peg given). There are 6 different colors, and duplicates may be used.
So for instance, a game might go as follows:
(Assuming the solution is Red Green Green Blue)
```
1: Blue Purple Black Green - 2 white pegs
2: Green Red Black Blue - 2 white pegs, 1 red peg
3: Green Green Green Blue - 3 red pegs
4: Red Green Green Blue - 4 red pegs
```
The rules are expanded on [Wikipedia](http://en.wikipedia.org/wiki/Mastermind_%28board_game%29#cite_note-1)
### Requirements
* The program must read from stdin, and write to stdout
* I will be using numbers for simplicity instead of colors. The combination to guess will be 4 numbers between 1 and 6
* They must output their guesses as a series of 4 space separated numbers from 1 to 6 concluding with a newline. For instance:
1 5 2 2 \n
* The program will subsequently receive as input after its guess 2 integers between 0 and 4 separated by a space and concluding with a newline. The first will be the amount of white pegs, the second the amount of red pegs.
* On an input of "0 4" (4 red pegs), the program must terminate
* The program must be able to solve any puzzle in less then 6 turns (your program giving output, followed by the response input is 1 turn). There is no bonus (due to complexity of proof) for being able to solve it in less.
* The solution must be completely internal and included in the source. Standard Libraries only are permitted. The solution may therefore not rely on any other files (such as dictionaries), or the internet.
### Example Input/Output
```
> is your programs output
< is the responding input
Solution is 1 5 6 6
> 1 2 3 4
< 0 1
> 4 1 6 6
< 1 2
> 1 6 5 6
< 2 2
> 1 5 6 6
< 0 4
```
### Scoring
* This is pure and simple **Code Golf**. The shortest solution **in bytes** wins.
This is my first Code Golf question. My apologies if I have done something wrong, but I've attempted as well as possible to ensure that there is absolutely no ambiguity, and prevent as much rules lawyering as possible. If I have been ambiguous or unclear, please feel free to ask questions.
[Answer]
# Python 2 Python 3, 359 365 338 chars
```
from itertools import*
from collections import*
m=h=set(product(*['123456']*4))
def f(g,k):b=sum(x==y for x,y in zip(g,k));return'%s %s'%(sum(min(g.count(c),k.count(c))for c in set(g))-b,b)
while len(m)>1:g=min(h,key=lambda g:max(Counter(f(g,k)for k in m).values()));print(*g);s=input();m=set(x for x in m if s==f(g,x))
print(*(m.pop()))
```
Funny, it took me many edits to realize I had a five character variable name.
I do not like the long imports. It feels like I should be able to implement a replacement for `collections.Counter` that would save the import.
I also do not like the `print(*(m.pop()))` at the end. It feels like it should disappear into the while loop, but I can't find a way to do it without making it longer.
[Answer]
## Haskell, 317 304
```
q[0,4]_=error""
q[n,m]l=(\s->all(==4-m)[g s,n+g(u(foldr((u((.drop 1).(++)).).break.(==)))$unzip s)]).c(u(/=)).zip l
u=uncurry;m=map;g=length;c=filter
f a=[head.c(($(zipWith q(take n a)$f a)).all.flip($)).sequence$replicate 4[1..6]|n<-[0..]]
main=interact$unlines.m(unwords.m show).f.m(m read.words).lines
```
I love writing purely functional interactive programs! But of course this style has certain limitations: it terminates now with an error, but you didn't specify that this is not ok. I'd need to refactor the whole thing into the `IO` monad to get a non-error exit.
[Answer]
## Python, 385 357 chars, Solves in 5 moves
The more I change it, it grows more and more like Steven Rumbalski's... The main difference is that he works with strings rather than integers.
Implemented Knuth's algorithm (correctly now, I hope).
Borrowed the scoring function from Steven Rumbalski.
It takes a long time to generate the first guess, gets better later.
Hard-coding it (`g=len(A)==1296 and [1,1,2,2] or ...`) makes life easier if you want to test it.
I don't count 4 newlines+tab pairs, which can be replaced by semicolons.
```
from collections import*
from itertools import*
a=B=A=list(product(*[range(1,7)]*4))
r=lambda g,k:(sum(x==y for x,y in zip(g,k)),sum(min(g.count(c),k.count(c))for c in set(g)))
while a!=4:
g=A[1:]and min(B,key=lambda x:max(Counter(r(x,i)for i in A).values()))or A[0]
print"%d "*4%tuple(g)
b,a=map(int,raw_input().split())
A=[x for x in A if r(g,x)==(a,a+b)]
```
] |
[Question]
[
# Introduction
This site is rapidly building up a huge dataset of code snippets, so let's do something with it!
[Here's a data file](https://drive.google.com/file/d/0B3uyVnkMpqbVMGVtMndpbEdlVEE). It contains 9,066 unique language+snippet pairs for 113 languages, all taken from this site. The format is tab-separated (language-TAB-snippet), with all newlines in the snippets replaced with `<LF>`, and all tabs replaced with 4 spaces. There are at least 5 snippets for each language.
[update: I've made a minor change to the data file to merge some Python & RegExp versions I missed before - the link above has been updated]
# Challenge
Write a program or function which takes a code snippet and outputs the language it is written in (see below for details). The total size of your source + any data you require must be 300 bytes or less, and your program **must** output the correct language when given its own source code. Highest accuracy (most correct answers on the dataset above) wins.
# Rules
* The total size of your source code, resources, and any required compilation / runtime flags must not exceed 300 bytes.
* Your answer will be tested against the dataset above; it will be given one of the "Snippet" values as input and its output will be compared against the "correct" output according to the dataset. This will be repeated for all entries in the dataset and the final number of correct answers is your score.
* You can choose the input encoding - I'll assume UTF-8, so if you need another encoding specify it in your answer.
* You don't need to use the `<LF>` replacement for newlines; if your entry expects to receive newlines as literal newlines (char 10), specify it in your answer.
* Your entry must output the language it thinks the input snippet is written in. To avoid the need to compress lots of language strings, I'll allow mappings (If you want to output 3 for "Java", that's fine); just note the mappings in your answer.
* You can only have 1 output mapping for each language (i.e. if 3 means "Java", you can't also have 4 meaning "Java").
* When given its own source code, your program **must** produce the correct answer (must output the language it is written in).
* You don't need to support all languages in the dataset, and you can support extra languages if you want to (e.g. if your entry isn't in one of the languages in the dataset).
* Your program must be deterministic (providing the same input twice must produce the same output).
# Tie-Breaking
* Ties will be decided by reducing the dataset until one entry wins. The dataset will be reduced by removing all snippets for the most popular language (i.e. ties are broken by accuracy on rarer languages). *For example, if A and B score 70% on the full dataset, all Python snippets will be removed. If A and B now both score 60%, CJam will be removed. If A now scores 50% but B scores 55%, B is the winner.*
* If 100% accuracy is achieved, ties will be decided using a second (blind) dataset containing more samples for the same languages.
# Example 1
The Python script:
```
print("python")
```
This script successfully produces "python" when given its own source code, so it is valid. On the dataset, it scores 1008/9066 = 11.1%
# Example 2
The JavaScript function:
```
function f(s){return /function/.test(s)?1:2}
```
With the mappings 1 → javascript, 2 → python. Again it successfully produces 1 ("javascript") for its own source, and on the dataset it scores 1092/9066 = 12.0%
---
Where did the data come from?
I created an [SEDE query](http://data.stackexchange.com/codegolf/query/509563/top-code-golf-answers) to pull samples from [code-golf] challenges on this site. From the resulting 10,000 answers, I used a hacked-together python script to find the code & language name for each, then filtered out any language with less than 5 examples. The data isn't 100% clean (I know there are some non-code snippets it pulled), but should be good enough.
---
Inspired by this challenge from earlier in the year: [Who said that? 2016 Presidential election](https://codegolf.stackexchange.com/q/74585/8927)
Also partly related to [What's the Language?](https://codegolf.stackexchange.com/q/69920/8927)
[Answer]
# C, 297 bytes, 43.194351% matched (v2)
This is the first non-golf challenge I've competed in. Surprisingly, golfing languages are actually rather easy to separate, with about 60% matching accuracy per language.
The code requires input as UTF-8 string, results based on version 2 of the supplied dataset. This code does not require `<LF>` to be replaced with actual newlines.
```
#define S(x)!!strstr(p,#x)
f(char*p){return S(#d)?:S(voi)?0:S(mai)|S(utc)?:S(mbd)|S(impor)|S(input)|S(def)|S(rang)?2:S(log)|S(fun)|S(=>)|S(lert)?3:S(<?)?4:S(echo)|S(sed)?5:S(+++)?6:S(<-)?7:S($_)|S(say)?8:S(\342)|S(\303)?9:S(->)|S(map)?10:S(@#)|S(]])|S([#)?11:S(V)|S(Q)?12:S(Z)|S(Y)?13:S(.)?14:15;}
```
Mapping table:
```
0. java
1. c
2. python
3. javascript
4. php
5. bash
6. brainf*
7. haskell
8. perl
9. apl
10. ruby
11. wolfram
12. pyth
13. matl
14. golfscript
15. cjam
```
The percentage is based on my hits/total calculation: 3916 hits/9066 total.
[Answer]
# Python 3, 271 278 bytes, 25.049636% matched (v2, unverified)
```
def f(c):
try:compile(c,'','exec');return 5
except:
for j in range(9):
if any(l in c for l in [['echo'],['require'],['Main','string'],['document','alert','var ','function'],['String'],['def ','lambda','print '],['main','int','char'],['+++','<<<'],[]][j]):break
return j
```
map:
```
0 = bash
1 = ruby
2 = c#
3 = javascript
4 = java
5 = python
6 = c
7 = brainf*
8 = cjam
```
much better golfed (probably still not great), finally broke the 25% barrier! Inputs have `<LF>` replaced with newline (`\n`)
] |
[Question]
[
## The challenge
Write a function or a program that takes a string composed of one or more **subjective personal pronouns**, separated by **+** signs, as an argument. The output must be a single pronoun, that is the result of the relation defined in the next paragraph.
Of course, feel free to edit as you wish to correct those grammatical errors that are surely present ;)
This is a code-golf challenge, so the shortest code wins.
## The relation
The goal of this task is to translate in "math-speak" something that we use daily. How do we think of "You and I" ? Well, "We", don't we?
So, if the input is `You+I` the output should be the string `We`.
With more than two pronouns, it should look like:
`You+He+They` -> `You`
The relation is defined as this table:
```
I You He We You They
I I We We We We We
You You You We You You
He He We You They
We We We We
You You You
They They
```
## The 'You' Problem
Well, as you can see I'm not a native English speaker. In my language (Italian) there's a difference between the plural *you* (*voi*, in italian) and the singular *you* (*tu*). When I thought this challenge I didn't think in English, so there's the problem that it is impossible to recognize if I'm using plural or singular form. Fortunately (or obviously?), the input/output doesn't change in both forms, so you can use one of them and you will cover both cases!
## About the input
The input will be always in the form "Pronoun+Pronoun+Pronoun" ... The pronouns will have the first letter in uppercase and the rest in lowercase. Pluses will be not be surrounded by spaces, only by pronouns. Empty input is possible and the result must be empty output.
## Bonus
A little bonus of 15% if the program will manage two new pronouns: **She** and **It**. They are the same as He, obviously. Remember that this relation is reflexive, so She -> She and It -> It. Therefore, any combination that includes only She, He or It should output They.
## Examples
```
You+I -> We
You+He+They -> You
I+You+He+They -> We
They -> They
They+You -> You
You+You+I+You -> We
For Bonus
She -> She
She+He -> They
I+It+He -> We
It+You -> You
```
[Answer]
# Retina, ~~62 61 56 53~~ 52 bytes
```
(.+)\+(?=\1)
.*(W|.I|I.).*
We
.*Y.*
You
.{4,}
They
```
Further golfing and explanation comes later.
The 4 substitution steps do the following:
* anything multiple times is itself
* if there is any We or I + anyhing the result is We
* for anything else containing You the result is You
* if we still have multiple parts or a sole They it's They as only He's and They's can be left
[Try it online here.](http://retina.tryitonline.net/)
*3 bytes saved thanks to Martin Büttner.*
[Answer]
# JavaScript (ES6), 130 bytes
```
s=>(a=",I,You,He,We,They".split`,`,m="012345014444042242042345044444042545",r=0,s.split`+`.map(p=>r=m[+m[a.indexOf(p)]+r*6]),a[r])
```
## Explanation
```
s=>(
// a = array of each pronoun (including an empty string at index 0)
a=",I,You,He,We,They".split`,`,
// m = 6 x 6 map of pronoun indices for each combination of pronouns
m="012345014444042242042345044444042545",
r=0, // r = index of result pronoun
s.split`+`.map(p=> // for each pronoun in the input string
r=m[+m[a.indexOf(p)]+r*6] // combine each pronoun with the previous one
),
a[r] // return the resulting pronoun
)
```
## Test
```
var solution = s=>(a=",I,You,He,We,They".split`,`,m="012345014444042242042345044444042545",r=0,s.split`+`.map(p=>r=m[+m[a.indexOf(p)]+r*6]),a[r])
```
```
<input type="text" id="input" value="You+You+I+You" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
[Answer]
# Python ~~159~~ 153 bytes
**EDIT**: Thanks @Pietu1998
This is a direct translation of the Javascript ES6 answer:
```
a=",I,You,He,We,They".split(',')
m="012345014444042242042345044444042545"
r=0
for p in raw_input().split('+'):r=int(m[int(m[a.index(p)])+r*6])
print a[r]
```
[Try it here](http://ideone.com/65tgUh)
[Answer]
## Perl 5, 67 bytes
79 bytes really, but there's a 15% bonus.
```
$a{$_}=""for split/[+\s]/,<>;@_=%a;say@_<3?@_:I~~@_||We~~@_?We:You~~@_?You:They
```
[Answer]
# Ruby, ~~150~~ ~~136~~ ~~131~~ ~~119~~ 111 bytes
```
ARGV.each{|a|puts %w[We You I He They][a.bytes.inject(0){|m,c|m|({87=>15,73=>7,89=>11,84=>9,72=>8}[c]||0)}%5]}
```
Bonus feature: handles multiple expressions on the same command line.
] |
[Question]
[
A Quat is a combination of a [quine](/questions/tagged/quine "show questions tagged 'quine'") and the popular esolang [cat](http://esolangs.org/wiki/Cat_program) program.
# Challenge
The challenge is to write a standard cat program. Whatever the user inputs, the program will echo the input to stdout.
However, when the length of the input is greater than 0 **and** a multiple of 4, the program should output its own source code. *Quat* comes from the Portuguese [quatro](https://translate.google.com/#pt/en/quatro), which translates to 'four'.
# Rules
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply
* You may not read the source code from a file
* An empty input should produce an empty output
# Bonus
If your input length is a multiple of 4 you can earn a 25% bonus by printing the quine `length/4` times. Another 5% bonus if you seperate the output by spaces (no trailing space allowed).
# Test cases
The following test cases apply for the program `in%4=0?cat:self` (not a real language).
`<empty input> -> <empty output>`
`input -> input`
`1234 -> in%4=0?cat:self`
`12345678 -> in%4=0?cat:self` **0%** bonus
`12345678 -> in%4=0?cat:selfin%4=0?cat:self` **25%** bonus
`12345678 -> in%4=0?cat:self in%4=0?cat:self` **30%** bonus
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest code in bytes wins.
[Answer]
## CJam, 23 \* 0.75 = 17.25 bytes
Standard generalised quine...
```
{`"_~"+q:Q,4md@@*Q\?}_~
```
or
```
{`"_~"+q_,4md@@]:\*?}_~
```
[Test it here.](http://cjam.aditsu.net/#code=%7B%60%22_~%22%2Bq%3AQ%2C4md%40%40*Q%5C%3F%7D_~&input=12345678)
### Explanation
```
{`"_~"+ e# Generalised quine framework. Leaves the source code on the stack.
q:Q e# Read input and store it in Q.
, e# Get its length.
4md e# Divmod 4.
@ e# Pull up the source code.
@ e# Pull up the div.
* e# Repeat the source code that many times.
Q\ e# Push the input and swap it below the repeated source.
? e# Pick the right output based on the modulo.
}_~
```
The other version avoids the use of a variable by using the stack-rotation trick `]:\`.
[Answer]
# Pyth, 33 \* .75 = 24.75
```
?%lz4z*/lz4jN*2]"?%lz4z*/lz4jN*2]
```
[Test Suite](http://pyth.herokuapp.com/?code=%3F%25lz4z%2A%2Flz4jN%2A2%5D%22%3F%25lz4z%2A%2Flz4jN%2A2%5D&input=asdf&test_suite=1&test_suite_input=%0A1%0A12%0A123%0A1234%0A12345%0A12345678%0A123456781234&debug=0)
Standard Pyth quine using join. This is only a true quine on the online interpreter, which doesn't add a final trailing newline.
Getting the final bonus reults in a score of 39 \* .7 = 27.3:
```
?%lz4zjd*/lz4]jN*2]"?%lz4zjd*/lz4]jN*2]
```
[Answer]
# [Vitsy](https://github.com/VTCAKAVSMoACE/Vitsy), ~~18~~ 17 bytes
~~*So close*.~~ Yus. I am now winning amongst non-built in quiners! *glares at Seriously*
```
zl4M([&'rd3*8\}]Z
z Grab ALL THE INPUT! :D
l4M([ ] If the input is a multiple of four, do the stuff in brackets.
& Generate a new stack and move to it.
'rd3* Standard quine.
8\} Push the bottom 8 items of the stack to the top.
Z Output the current stack.
```
There's no reason for me to go after the bonuses - they'd chuck on a lot more bytes.
## Cheating quine version, 12 bytes:
```
zl4M([&iG`]Z
zl4M([& ]Z Same as above.
i Push -1.
G Get the name of the file with this index of use (-1 is self)
` Read the file with the given name and push its contents to the stack.
```
[Answer]
# Emacs Lisp (323 \* 0.75 = 242.25)
```
((lambda (s) (let* ((a (read-string "")) (l (string-bytes a))) (if (> (% l 4) 0) (message a) (dotimes (v (/ l 4)) (prin1 (list s (list (quote quote) s))))))) (quote (lambda (s) (let* ((a (read-string "")) (l (string-bytes a))) (if (> (% l 4) 0) (message a) (dotimes (v (/ l 4)) (prin1 (list s (list (quote quote) s)))))))))
```
This uses Lisp's quoting mechanic to give the source code as input to itself.
**Old cheating version**
```
:; exec emacs -Q -script $0
(find-file(nth 2 command-line-args))(set'b(buffer-string))(set's(read-string""))(set'l(string-bytes s))(if(>(% l 4)0)(message s)(dotimes(v(/ l 4))(message"%s"b)))
```
Ungolfed:
```
:; exec emacs -Q -script $0
(find-file(nth 2 command-line-args)) ; open self
(set'b(buffer-string)) ; read own code to string
(set's(read-string"")) ; read input
(set'l(string-bytes s)) ; length of input
(if(>(% l 4)0) ; l % 4 > 0 ?
(message s) ; output input
(dotimes(v(/ l 4)) ; (implicit else) repeat l/4 times
(message"%s"b))) ; output own code
```
[Answer]
## Seriously, ~~8~~ 9 bytes
```
Q,ó;l4@%I
```
[Try it Online](http://seriouslylang.herokuapp.com/link/code=512ca23b6c34402549&input=hello,%20y%60all)
(Hit enter once in the input box to test empty input.)
The first bonus can be done in 12 bytes (16\*.75):
```
Q,ó;l;4@\(*)4@%I
```
Explanation:
```
Q Push program source to stack
,ó Push input string, and terminate if it's empty
;l Push length of input
4@% Take the length mod 4.
I Pick the next stack element (input) if nonzero,
else the next next (program source)
```
Since some people don't like the use of Seriously's quining built-in, I provide this 22 byte version that doesn't use `Q` for reference:
```
`è";ƒ"(+,ó;l4@%I`;ƒ
```
If you are one of those people, consider this the definitive version (for now) and then go start a meta thread about the use of built-ins in quines.
[Answer]
# JavaScript, ~~57~~ ~~56~~ 72 bytes \* 0.75 = 54
Thanks to @Neil for a one byte savings!
```
(f=_=>alert(!(p=prompt())||(l=p.length)%4?p:`(f=${f})()`.repeat(l/4)))()
```
The shortest solution I could find was pretty straight-forward.
So, here's a couple bonus (more interesting) solutions:
### JavaScript, ~~82~~ 81 bytes \* 0.75 = 60.75
```
f=_=>{try{p=prompt();a=`f=${f};f()`.repeat(p.length/4)}catch(e){a=p}alert(a)};f()
```
This one abuses `repeat`'s functionality of throwing an exception if passed a non-integer.
### JavaScript, 83 bytes \* 0.70 = 58.1
```
(f=_=>alert((a=(p=prompt()).split(/.{4}/)).pop()?p:a.fill(`(f=${f})()`).join` `))()
```
This last one is definitely my favorite, splitting the input on every four characters using the regex `/.{4}/`. If there are any characters left at the end of the string when we `pop`, it isn't divisible by 4, so alert the input. Otherwise, the `pop` reduced the array's length by one, so at this point the array's length is equal to the input length / 4. In this case, just `fill` it with the quine and `join` with spaces.
[Answer]
# Perl, ~~68~~ 65 \* 0.75 = 48.75 bytes
```
perl -e'$_=q{print+($l=($~=<>)=~y///c)%4?$~:"\$_=q{$_};eval"x($l/4)};eval'
```
See the online test suite [here.](http://ideone.com/lgZwPo)
## Broken down
```
perl -e'
$_=q{ # store source code in $_
print+(
$l=($~=<>)=~ y///c # read STDIN into $~, assign length to $l
)%4 ? # if length is a multiple of 4
$~ : # print $~
"\$_=q{$_};eval" # otherwise, print source code
x($l/4) # length/4 times
};
eval' # eval $_ to execute its contents
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 71 bytes -30% = 49.7
```
exec(a:="s=len(t:=input());print(*s%4and[t]or s//4*['exec(a:=%r)'%a])")
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P7UiNVkj0cpWqdg2JzVPo8TKNjOvoLREQ1PTuqAoM69EQ6tY1SQxLyW6JDa/SKFYX99EK1odpkm1SFNdNTFWU0nz/39DI2MTUzNzCwA "Python 3.8 (pre-release) – Try It Online")
[Answer]
## Mathematica, 229 bytes
```
($RecursionLimit = Infinity; WriteString[$Output, If[Mod[StringLength[a = (If[(a = InputString[]) === EndOfFile, "", StringJoin["\n", a, #0[]]] & )[]], 4] == 1, ToString[#0, InputForm][], If[a == "", "", StringDrop[a, 1]]]]) & []
```
All of the whitespace is for the `InputForm` of the program to match its actual code.
[Answer]
# Javascript ES6, 45 bytes
```
$=(_=prompt())=>_.length%4?_:`$=${$};$()`;$()
```
Extension of my 21-byte Bling Quine. Hope that mixing `prompt` and function output is allowed.
[Answer]
# JavaScript, 33 bytes
```
f=(i,l=i.length)=>l%4?i:("f="+f).repeat(l/4)
```
* **+44** bytes
* **-25%** bonus
Other solutions:
## ~~44~~ 36 bytes
```
f=(i,l=i.length)=>l%4?i:("f="+f).repeat(!!l)
```
```
f=(i,l=i.length)=>l%4?i:l?("f="+f):i
```
## 38.5 bytes
```
f=(i,l=i.length)=>l%4?i:Array(l/4).fill("f="+f).join` `
```
* **+55** bytes
* **-25%** bonus
* **-5%** bonus
[Answer]
# [Zsh](https://www.zsh.org/), 78 bytes
```
s='s=\47%s\47
0()printf $s $s
$[$#1&3]||<<<$1'
0()printf $s $s
$[$#1&3]||<<<$1
```
[Try it online!](https://tio.run/##qyrO@F@cWqJgaGRsYmpmbvG/2Fa92DbGxFy1GEhwGWhoFhRl5pWkKagUAxGXSrSKsqGacWxNjY2NjYqhOiEF//8DAA "Zsh – Try It Online")
Uses `&3` instead of `%4` so the `%` doesn't get interpreted by `printf`.
The bonus could be added with `repeat $[$#1/4]` before the `printf` in both places, but unfortunately it gives a higher score (\$ 75\% \times 110 = 82.5 \$).
[Answer]
# Excel, 204 bytes - 30% = 142.8 score
```
=LET(a,LEN(A1),c,CHAR(34),q,"=LET(a,LEN(A1),c,CHAR(34),q,#,IF(MOD(a,4)=0,TRIM(REPT(SUBSTITUTE(q,CHAR(35),c&q&c),a/4)),LEFT(A1,1))) ",IF(MOD(a,4)=0,TRIM(REPT(SUBSTITUTE(q,CHAR(35),c&q&c),a/4)),LEFT(A1,1)))
```
[Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnDMfSU9R0-k5t3LF?e=fJmfE8)
## 2nd Place, 191 bytes - 25% = 143.25 score
```
=LET(a,LEN(A1),c,CHAR(34),q,"=LET(a,LEN(A1),c,CHAR(34),q,#,IF(MOD(a,4)=0,REPT(SUBSTITUTE(q,CHAR(35),c&q&c),a/4),LEFT(A1,1)))",IF(MOD(a,4)=0,REPT(SUBSTITUTE(q,CHAR(35),c&q&c),a/4),LEFT(A1,1)))
```
## 3rd Place, 179 bytes
```
=LET(a,LEN(A1),c,CHAR(34),q,"=LET(a,LEN(A1),c,CHAR(34),q,#,IF(a*(MOD(a,4)=0),SUBSTITUTE(q,CHAR(35),c&q&c),left(A1,1)))",IF(a*(MOD(a,4)=0),SUBSTITUTE(q,CHAR(35),c&q&c),LEFT(A1,1)))
```
## Best Cheesy Answer, 59 byte - 25% = 44.25 score
```
=LET(a,LEN(A1),IF(MOD(a,4)=0,REPT(FORMULATEXT(B8),a/4),A1))
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 38 - 25% = 28.5 bytes
```
`?DL4%[|[$:q$+$L4/*`?DL4%[|[$:q$+$L4/*
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%60%3FDL4%25%5B%7C%5B%24%3Aq%24%2B%24L4%2F*%60%3FDL4%25%5B%7C%5B%24%3Aq%24%2B%24L4%2F*&inputs=12345678&header=&footer=)
```
`...` # Source code in string
? # Grab input
D # Triple
L4% # If length is (not) divisible by 4
[| # Do nothing, otherwise
L0>[ # If length is positive
$ # Swap (to get source-code string)
:q$+ # Standard quine - duplicate, uneval, swap, concatenate
$ # Swap to get original input
L4/ # Length / 4
* # (Source code) that many times
```
Trying to get the bonus is sadly longer.
] |
[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/10760/edit)
[](https://xkcd.com/292/)
Your task is to build the largest program you can that uses exactly one GOTO, without which the entire program (or at least a huge chunk of it) must be completely restructured. The score is counted as the number of statements in your code that *change places* or *are newly introduced* (removing statements doesn't add to your score) when the code is restructured without the GOTO (others are allowed to challenge your restructuring by presenting a more elegant one). As this is code bowling, highest score wins.
Note: I do not claim any liability for velociraptor attacks by attempting this challenge.
[Answer]
## C fizzbuzz
This solution runs around the idea of interrupts and label variables (gcc only, sorry). The program sets up a timer which periodically calls main, where we goto whichever place the last execution of our interrupt handler (main) told us we should.
I've never used timers or label variables before, so I think there is much to bowl here.
```
#include <sys/time.h>
#include <signal.h>
#include <stdio.h>
int main(int argc)
{
static int run = 1;
static int* gotoloc = &&init;
static int num = 0;
static int limit = 50;
goto *gotoloc;
init:
signal(SIGVTALRM, (void (*)(int)) main);
gotoloc = &&loop;
struct itimerval it_val;
it_val.it_value.tv_sec = 0;
it_val.it_value.tv_usec = 100000;
it_val.it_interval.tv_sec = 0;
it_val.it_interval.tv_usec = 100000;
setitimer(ITIMER_VIRTUAL, &it_val, NULL);
while(run);
loop:
num = num + 1;
run = num < limit;
gotoloc = &¬fizz + (&&fizz - &¬fizz) * !(num % 3);
return 1;
fizz:
printf("fizz");
gotoloc = &¬buzz + (&&buzz - &¬buzz) * !(num % 5);
return 1;
notfizz:
gotoloc = &¬fizzbuzz + (&&buzz - &¬fizzbuzz) * !(num % 5);
return 1;
buzz:
printf("buzz\n");
gotoloc = &&loop;
return 1;
notbuzz:
printf("\n");
gotoloc = &&loop;
return 1;
notfizzbuzz:
printf("%d\n", num);
gotoloc = &&loop;
return 1;
}
```
[Answer]
## Perl
I'm not very good at bowling, but I suspect this may interest the OP. This is a Sieve of Eratosthenes using a variable goto. Were this to be 'refactored', I doubt any of it would be reusable, other than perhaps the first few lines. When the sieve ends, all remaining `1`s in the `@primes` array correspond to prime values.
For added fun, no ands, ors, ternaries, conditionals or comparison operators of any kind are used.
```
@primes[2..1e4]=(1)x9999;
$a=2;
Y:
$b=$a*~-$a;
X:
$primes[$b+=$a+=$c=$a/100%2+$b/1e4%2]=0;
goto"$c"^h;
Z:
```
[Answer]
## C
My usage of macros perhaps doesn't make it "one GOTO".
And it's quite short, so "completely restructured" isn't much.
But here's my attempt anyway.
Reads a number from standard input, prints it modulu 3.
```
int main() {
char s[100], *p, r=0;
void *pl[] = { &&a, &&b, &&c, &&d, &&e, &&f, &&g, &&h, &&i, &&j, &&a, &&b, &&x, &&y, &&z }, *p1;
p = gets(s);
#define N(n) (pl+n)[!*p*60+*p-48];p++;goto *p1
a: p1=N(0);
b: p1=N(1);
c: p1=N(2);
d: p1=N(0);
e: p1=N(1);
f: p1=N(2);
g: p1=N(0);
h: p1=N(1);
i: p1=N(2);
j: p1=N(0);
z: r++;
y: r++;
x: printf("%d\n", r);
return 0;
}
```
] |
[Question]
[
A **monotonic subsequence** is a sequence of numbers \$a\_1, a\_2, ..., a\_n\$ such that
$$a\_1 \le a\_2 \le ... \le a\_n \\
\text{or} \\
a\_1 \ge a\_2 \ge ... \ge a\_n$$
`[1, 3, 3, 7, 9, 13, 13, 100]` is a monotonic (non-decreasing) subsequence, as well as `[9, 4, 4, 3, 0, -10, -12]` (this one is non-increasing), but `[1, 3, 6, 9, 8]` is not. Given a list of integers (in any reasonable format), output the smallest number `N` such that the sequence of these integers can be split into `N` monotonic sequences.
# Examples
```
[1, 3, 7, 5, 4, 2] -> [[1, 3, 7], [5, 4, 2]] -> 2
[1, 2, 3, 4, 5, 6] -> [1, 2, 3, 4, 5, 6] -> 1
[3, 1, 5, 5, 6] -> [[3, 1], [5, 5, 6]] -> 2
[4, 6, 8, 9, 1, 6] -> [[4, 6, 8, 9], [1, 6]] -> 2
[3, 3, 3, 3] -> [[3, 3, 3, 3]] -> 1
[7] -> [[7]] -> 1
[] -> [] -> anything (you don't actually have to handle an empty list case)
[1, 3, 2, -1, 6, 9, 10, 2, 1, -12] -> [[1, 3], [2, -1], [6, 9, 10], [2, 1, -12]] -> 4
```
[Answer]
# [Brachylog](http://github.com/JCumin/Brachylog), 12 bytes
```
~c:{<=|>=}al
```
[Try it online!](http://brachylog.tryitonline.net/#code=fmM6ezw9fD49fWFs&input=WzE6MzoyOl8xOjY6OToxMDoyOjE6XzEyXQ&args=Wg)
This returns `false.` for the empty list `[]`.
### Explanation
```
(?)~c Take a list of sublists which when concatenated result in the Input
:{<=|>=}a Each sublist must be either increasing or decreasing
l(.) Output is the length of that list
```
This will return the smallest one because `~c` will generate choice points from the smallest number of sublists to the biggest.
[Answer]
## Perl, 65 bytes
62 bytes of code + 3 bytes for `-n` flag.
monot\_seq.pl :
```
#!perl -n
s/\S+ /($_<=>$&)*($&<=>$')-$g>=0?$g=1:$.++;$g--;$_=$&/ge,$_=$.
```
Give the input without final newline, with the numbers separated by spaces :
```
$ echo -n "1 3 2 -1 6 9 10 2 1 -12" | perl -M5.010 monot_seq.pl
4
```
*-5 bytes thanks to @Gabriel Benamy.*
[Answer]
# Mathematica, 111 bytes
```
d=#[[2]]-#[[1]]&;r=Rest;f@{n_}:=1;f@k__:=If[d@k==0,f@r@k,g[k Sign@d@k]];g@{n_}:=1;g@k__:=If[d@k>0,g@r@k,1+f@r@k]
```
Named function `f` taking a nonempty list of numbers (integers or even reals). Works from front to back, discarding the first element repeatedly and keeping track of how many subsequences are needed. More verbose:
```
d = #[[2]] - #[[1]] &; function: difference of the first two elements
r = Rest; function: a list with its first element dropped
f@{n_} := 1; f of a length-1 list equals 1
f@k__ := If[d@k == 0, f@r@k, if the first two elements are equal, drop one
element and call f again ...
g[k Sign@d@k]]; ... otherwise call the helper function g on the
list, multiplying by -1 if necessary to ensure
that the list starts with an increase
g@{n_} := 1; g of a length-1 list equals 1
g@k__ := If[d@k > 0, g@r@k, if the list starts with an increase, drop one
element and call g again ...
1 + f@r@k]; ... otherwise drop one element, call f on the
resulting list, and add 1
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
IṠḟ0E
ŒṖÇ€€0e$Ðḟḅ1Ṃ
```
**[TryItOnline!](http://jelly.tryitonline.net/#code=SeG5oOG4nzBRTOG7igrFkuG5lsOH4oKs4oKsMGUkw5DhuJ_huIUx4bmC&input=&args=WzQsIDYsIDgsIDksIDEsIDZd)** or [run all tests](http://jelly.tryitonline.net/#code=SeG5oOG4nzBFCsWS4bmWw4figqzigqwwZSTDkOG4n-G4hTHhuYIK4bmEw4fhuYTCteKCrMK14oG2&input=&args=W1sxLCAzLCA3LCA1LCA0LCAyXSwgWzEsIDIsIDMsIDQsIDUsIDZdLCBbMywgMSwgNSwgNSwgNl0sIFs0LCA2LCA4LCA5LCAxLCA2XSwgWzMsIDMsIDMsIDNdLCBbN10sIFtdLCBbMSwgMywgMiwgLTEsIDYsIDksIDEwLCAyLCAxLCAtMTJdXQ) (empty list results in `1`)
### How?
```
IṠḟ0E - Link 1, test for monotonicity: a sublist
I - incremental differences
Ṡ - sign {fall:-1; same:0; rise:1}
ḟ0 - filter out the zeros
E - all equal?
ŒṖÇ€€0e$Ðḟḅ1Ṃ - Main link
ŒṖ - all partitions of the input list
Ç€€ - call last link (1) as a monad for €ach for €ach
Ðḟ - filter out results:
$ - last two links as a monad
0e - contains zero?
ḅ1 - convert from unary (vectorises)
Ṃ - minimum
```
(I'm not convinced that this is the most suitable method to minimise byte count though)
[Answer]
# Perl, ~~98~~ ~~97~~ ~~96~~ 79 bytes
```
($a,$b)=($a<=>$b)*($b<=>$c)<0?($c,shift,$d++):($b,$c)while$c=shift;say$d+1 if$a
```
Input is provided as a list of numbers, separated by spaces, provided at runtime, e.g.
```
perl -M5.010 monotonic.pl 1 3 2 -1 6 9 10 2 1 -12
4
```
(the 4 is the output)
Readable:
```
($a,$b)=($a<=>$b)*($b<=>$c)<0
?($c,shift,$d++)
:($b,$c)
while$c=shift;
say$d+1
if$a
```
The 'spaceship operator' `<=>` returns -1 if LHS < RHS, 0 if LHS = RHS, and +1 if LHS > RHS. When comparing three sequential elements `$a,$b,$c` to determine if they're monotonic, it's only necessary to determine that it's not the case that exactly one of `$a<=>$b`,`$b<=>$c` is 1 and the other is -1 -- which only happens when their product is -1. If either `$a==$b` or `$b==$c`, then the sequence is monotonic, and the product is 0. If `$a < $b < $c`, then both result in -1, and -1 \* -1 = 1. If `$a > $b > $c`, then they both result in 1, and 1 \* 1 = 1. In either case, the sequence is monotonic, and we wish to continue.
If the product is less than 0, we know that the sequence is not monotonic, and we discard the values of `$a,$b` we're currently holding, and increment our subsequence counter. Otherwise, we move forward one number.
Returns nothing if the input is empty, otherwise returns the smallest number of contiguous monotonic subsequences
[Answer]
## C#6, ~~297~~ 209 bytes
```
using System.Linq;int G(int[] a)=>a.Any()?a.SkipWhile((x,i)=>i<1||x>=a[i-1]).Count()<a.SkipWhile((x,i)=>i<1||x<=a[i-1]).Count()?G(a.Select(x=>-x).ToArray()):G(a.SkipWhile((x,i)=>i<1||x<=a[i-1]).ToArray())+1:0;
```
Ungolfed with explanations
```
int G(int[] a)=>
a.Any()
?a.SkipWhile((x,i)=>i<1||x>=a[i-1]).Count()<a.SkipWhile((x,i)=>i<1||x<=a[i-1]).Count() // If a begins by decreasing (including whole a decreasing)...
?G(a.Select(x=>-x).ToArray()) // ... Then flip sign to make a begins by increasing
:G(a.SkipWhile((x,i)=>i<1||x<=a[i-1]).ToArray())+1 // ... Else skip the increasing part, recursively find the remaining part number, then add 1
:0; // Return 0 if a is empty
```
[Answer]
## JavaScript (ES6), 69 bytes
```
f=(d,c,b,...a)=>1/b?(d>c)*(b>c)+(d<c)*(b<c)?1+f(b,...a):f(d,b,...a):1
```
Takes input as multiple parameters. Works by recursively comparing the first three elements to see whether they are monotonic, if so, removes the middle element as it is useless, if not, removes the first two elements and starts a new sequence.
[Answer]
## Clojure, 97 bytes
```
#((reduce(fn[[C i]s](let[S(conj C s)](if(or(apply <= S)(apply >= S))[S i][[s](inc i)])))[[]1]%)1)
```
`reduce` keeps track of the current subsequence and calculates how many times `<=` and `>=` conditions fail. Last `1` takes 2nd element from the result (being the counter `i`).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
ŒṖỤ€IṠƑƊƇẈṂ
```
[Try it online!](https://tio.run/##y0rNyan8///opIc7pz3cveRR0xrPhzsXHJt4rOtY@8NdHQ93Nv0/3A4U/f8/2lBHwVhHwVxHwVRHwURHwShWRwEkZgQWNgELm4HEgDxDMA8mAJQz01Gw0FGwBMvAFEERiGcOIqDmGYON1DUEawLpMAALGILEjGIB "Jelly – Try It Online")
Empty list yields `1`
## How it works
```
ŒṖỤ€IṠƑƊƇẈṂ - Main link. Takes an array A on the left
ŒṖ - Yield all partitions of A
ƊƇ - Keep those partitions for which the following is true:
€ - Over each sublist in the partition:
Ụ - Grade up; Sort its indices by its values
I - Increments
Ƒ - Is this invariant under:
Ṡ - Convert to sign
This (ṠƑ) is a trick that returns 1 if the list contains only
-1, 1 and 0s. As we're working with the indices, not the values,
we will never have duplicate elements, and so no 0. The increments
will either be all 1 or -1 iff the ordered indices are in directly
ascending or descending order, i.e. the values are sorted in
either ascending or descending order
Ẉ - Get the lengths of each kept partition
Ṃ - Get the minimum
```
] |
[Question]
[
My electric garage door works like this:
* There is just one push button to control the door
* If the door is fully closed and I hit the button, the door starts to open. It takes 10 seconds to open fully
* If the door is fully open and I hit the button, the door starts to close. It takes 10 seconds to close fully
* If the door is part way through opening or closing and I hit the button, then the door stops and is left partially open.
* Whenever the door stops moving, either from automatic completion of an open or close action, or from manual interruption by pushing the button partway through an action, then the mechanism will reverse and remember its direction for the next action.
* If the button is pushed when the door is stopped but partially open, then the amount of time for it to complete its action will be a fraction of 10 seconds in proportion to the amount it needs to move to complete the action.
Assume the door is fully closed at the start.
An input list of integers will be given. These integers are the number of seconds I wait between successive pushes of the control button.
Output two things:
* a percentage indicating the state of the door once all button pushes are completed and the door has reached a steady state. Output of `%` symbol is optional.
* an unambiguous indication of what direction the door will travel on the next button push. This may be `up`/`down`, `U`/`D`, `+`/`-`, `1`/`0` or whatever you choose.
You may assume the door takes infinitesimally less than 10 seconds to complete an open or close action.
### Example inputs:
```
<empty list> # button was pushed just once
20 # button was pushed twice with 20 seconds between
10
5
20 20
10 10
5 5
1 2 3
8 9 10 11
11 10 9 8 7
```
### Expected outputs corresponding to above inputs
```
100% D
0% U
0% U
50% D
100% D
100% D
0% U
100% D
0% U
20% U
```
### Worked example of the last test
* Door starts off closed. Button is pushed
* Wait 11 seconds. Door ends up fully opened. Button is pushed.
* Wait 10 seconds. Door ends up fully closed. Button is pushed.
* Wait 9 seconds. Button is pushed. Door stops at 90% open.
* Wait 8 seconds. Button is pushed. Door starts to close.
* Wait 7 seconds. Button is pushed. Door stops at 20% open. Next direction will be up.
[Answer]
# Lua, ~~258~~ ~~248~~ 242 bytes
```
u,s,p=1>0,0>1,0;io.read():gsub("%d+",function(a)if(not s)then p=u and p+a or p-a;if(p>=10 or p<=0)then s,p=1>0,p>0 and 10 or 0;end;u,s=not u,not s else s=0>1;end end)if(not s)then p=u and 10 or 0;u=not u;end;print(10*p.."% "..(u and"U"or"D"))
```
### Ungolfed
```
u,s,p=true,false,0; -- Up direction, Stopped, Position
io.read():gsub("%d+",function(t) -- For each number in input
if(not s)then -- If door wasn't stopped
p=u and p+t or p-t; -- Position = Moving up ? +t : -t
if(p>=10 or p<=0)then -- If door fully opened or closed
s,p=true,p>0 and 10 or 0; -- Then door stopped at 0 or 10
end
u,s=not u,not s; -- Toggle direction and toggle stopped
else
s=false; -- If stopped, nothing happened, un-stop.
end
end)
-------------------- Done pressing the button --------------------
if(not s)then -- If left off moving
p=u and 10 or 0; -- Finish movement
u=not u; -- Toggle direction
end
print(10*p.."% "..(u and"U"or"D")) -- Output answer
```
~~I don't see how your test cases can be right...~~
```
20 20 -- Initial push, after 20, garage is at 100, push to start it down, after 20, garage is at 0, push to start it up, garage finishes up.
10 10 -- Same as above
1 2 3 -- 0 U Moving, wait 1, 1 D Stopped, wait 2, 0 U stopped, wait 3, 100 D stopped
```
OP Fixed
[Answer]
# Pyth, ~~50~~ ~~45~~ 39 bytes
6 bytes thanks to Sp3000.
```
J1,*Tu@S[0T+?|!%GTZ+=Z0*H~_J~Z1G)1+QT0J
```
[Test suite.](http://pyth.herokuapp.com/?code=J1%2C*Tu%40S%5B0T%2B%3F%7C!%25GTZ%2B%3DZ0*H%7E_J%7EZ1G%291%2BQT0J&test_suite=1&test_suite_input=%5B%5D%0A%5B20%5D%0A%5B10%5D%0A%5B5%5D%0A%5B20%2C20%5D%0A%5B10%2C10%5D%0A%5B5%2C5%5D%0A%5B1%2C2%2C3%5D%0A%5B8%2C9%2C10%2C11%5D%0A%5B11%2C10%2C9%2C8%2C7%5D&debug=0)
[Answer]
## JavaScript (ES6), ~~109~~ 106 bytes
```
a=>a.map(e=>(s^=1)?(r-=e*(d=-d))>9?(s=0,r=10):r<1?(r=s=0):r:r,r=s=0,d=1)&&(s?r:5*++d)*10+(d-s?"% D":"% U")
```
[Answer]
# Ruby, 152 bytes
```
->v{u,s,a=!!1,!0,0;v.map{|w|!s ?(a=u ? a+w : a-w;a>=10 ?(s,a=!!1,10):a<=0 ?(s,a=!!1,0):0;u,s=!u,!s):s=!0};!s ?(a=(u=!u)?0:10):0;p"#{10*a}% #{u ??U:?D}"}
```
**Test cases:**
```
f=->v{u,s,a=!!1,!0,0;v.map{|w|!s ?(a=u ? a+w : a-w;a>=10 ?(s,a=!!1,10):a<=0 ?(s,a=!!1,0):0;u,s=!u,!s):s=!0};!s ?(a=(u=!u)?0:10):0;p"#{10*a}% #{u ??U:?D}"}
f[[]] # => "100% D"
f[[20]] # => "0% U"
f[[10]] # => "0% U"
f[[5]] # => "50% D"
f[[20,20]] # => "100% D"
f[[10,10]] # => "100% D"
f[[5,5]] # => "0% U"
f[[1,2,3]] # => "100% D"
f[[8,9,10,11]] # => "0% U"
f[[11,10,9,8,7]] # => "20% U"
```
[Answer]
# Python 3.5, ~~193~~ ~~187~~ ~~185~~ ~~181~~ ~~175~~ ~~173~~ 172 bytes:
```
def G(*p):
O=100;y=0;l=10;z,v='UG'
for g in[*p,O]:
if v=='G':Q=O*g//10;y=min(max(0,[Q,y-Q][z=='D']),O);l=min(10,g);z='UD'[z=='U']
v='GS'[(O>y>0)*(v!='S')]
print(y,z)
```
Takes input in the form of comma separated numbers, for instance `1,2,3,4,5` or even `1.2,3.4,7.8,9.2`. Outputs whether the door in the next step is going up or down with `U` or `D`, respectively. Will golf more over time.
[Try It Online! (Ideone)](http://ideone.com/erHCRB) (Here the input is taken in the form of a list consisting of comma separated numbers, e.g. `[1,2,3,4,5]`.)
[Answer]
# PHP, ~~128~~ 120 bytes
```
$d=$argv[]=10;
foreach($argv as$a)
if($r){$p=min(max($p+$a*$d,0),100);$r=$p<1||99<$p;$d=-$d;}else$r=1;
echo"$p% ".DU[$d>0];
```
The code is wrapped here to fit in the code box. Put everything on a single line, put the PHP open marker in front of it and save it into a file. Or run it from the command line using `php -d error_reporting=0 -r '...the code...' [arguments]`.
The ungolfed source code, the test suite and examples of usage can be found on [github](https://github.com/axiac/code-golf/blob/master/is-the-electric-garage-door-open.php).
] |
[Question]
[
Given a non-flat list of integers, output a list of lists containing the integers in each nesting level, starting with the least-nested level, with the values in their original order in the input list when read left-to-right. If two or more lists are at the same nesting level in the input list, they should be combined into a single list in the output. The output should not contain any empty lists - nesting levels that contain only lists should be skipped entirely.
You may assume that the integers are all in the (inclusive) range `[-100, 100]`. There is no maximum length or nesting depth for the lists. There will be no empty lists in the input - every nesting level will contain at least one integer or list.
The input and output must be in your language's native list/array/enumerable/iterable/etc. format, or in any reasonable, unambiguous format if your language lacks a sequence type.
## Examples
```
[1, 2, [3, [4, 5], 6, [7, [8], 9]]] => [[1, 2], [3, 6], [4, 5, 7, 9], [8]]
[3, 1, [12, [14, [18], 2], 1], [[4]], 5] => [[3, 1, 5], [12, 1], [14, 2, 4], [18]]
[2, 1, [[5]], 6] => [[2, 1, 6], [5]]
[[54, [43, 76, [[[-19]]]], 20], 12] => [[12], [54, 20], [43, 76], [-19]]
[[[50]], [[50]]] => [[50, 50]]
```
[Answer]
# Pyth, 17
```
us-GeaYsI#GQ)S#Y
```
The leading space is important. This filters the list on whether the values are invariant on the `s` function, then removes these values from the list and flatten it one level. The values are also stored in `Y` and when we print we remove the empty values by filtering if the sorted value of the list is truthy.
[Test Suite](https://pyth.herokuapp.com/?code=+us-GeaYsI%23GQ%29S%23Y&input=%5B1%2C+2%2C+%5B3%2C+%5B4%2C+5%5D%2C+6%2C+%5B7%2C+%5B8%5D%2C+9%5D%5D%5D&test_suite=1&test_suite_input=%5B1%2C+2%2C+%5B3%2C+%5B4%2C+5%5D%2C+6%2C+%5B7%2C+%5B8%5D%2C+9%5D%5D%5D%0A%5B3%2C+1%2C+%5B12%2C+%5B14%2C+%5B18%5D%2C+2%5D%2C+1%5D%2C+%5B%5B4%5D%5D%2C+5%5D%0A%5B2%2C+1%2C+%5B%5B5%5D%5D%2C+6%5D%0A%5B%5B54%2C+%5B43%2C+76%2C+%5B%5B%5B-19%5D%5D%5D%5D%2C+20%5D%2C+12%5D%0A%5B%5B%5B50%5D%5D%2C+%5B%5B50%5D%5D%5D&debug=0)
Alternatively, a 15 byte answer with a dubious output format:
```
us-GpWJsI#GJQ)
```
[Test Suite](https://pyth.herokuapp.com/?code=%20us-GpWJsI%23GJQ%29&input=%5B1%2C%202%2C%20%5B3%2C%20%5B4%2C%205%5D%2C%206%2C%20%5B7%2C%20%5B8%5D%2C%209%5D%5D%5D&test_suite=1&test_suite_input=%5B1%2C%202%2C%20%5B3%2C%20%5B4%2C%205%5D%2C%206%2C%20%5B7%2C%20%5B8%5D%2C%209%5D%5D%5D%0A%5B3%2C%201%2C%20%5B12%2C%20%5B14%2C%20%5B18%5D%2C%202%5D%2C%201%5D%2C%20%5B%5B4%5D%5D%2C%205%5D%0A%5B2%2C%201%2C%20%5B%5B5%5D%5D%2C%206%5D%0A%5B%5B54%2C%20%5B43%2C%2076%2C%20%5B%5B%5B-19%5D%5D%5D%5D%2C%2020%5D%2C%2012%5D%0A%5B%5B%5B50%5D%5D%2C%20%5B%5B50%5D%5D%5D&debug=0)
### Expansion:
```
us-GeaYsI#GQ)S#Y ## Q = eval(input)
u Q) ## reduce to fixed point, starting with G = Q
sI#G ## get the values that are not lists from G
## this works because s<int> = <int> but s<list> = flatter list
aY ## append the list of these values to Y
e ## flatten the list
-G ## remove the values in the list from G
S#Y ## remove empty lists from Y
```
[Answer]
# Mathematica, ~~56~~ ~~54~~ 52 bytes
*-2 bytes due to [Alephalpha](https://codegolf.stackexchange.com/users/9288).*
*-2 bytes due to [CatsAreFluffy](https://codegolf.stackexchange.com/users/51443).*
```
Cases[#,_?AtomQ,{i}]~Table~{i,Depth@#}/.{}->Nothing&
```
Actually deletes empty levels.
[Answer]
# Python 2, 78 bytes
```
f=lambda l:l and zip(*[[x]for x in l if[]>x])+f(sum([x for x in l if[]<x],[]))
```
[Answer]
# [Retina](http://github.com/mbuettner/retina), 79
I *know* the Retina experts will golf this more, but here's a start:
```
{([^{}]+)}(,?)([^{}]*)
$3$2<$1>
)`[>}],?[<{]
,
(\d),+[<{]+
$1},{
<+
{
,*[>}]+
}
```
[Try it online.](http://retina.tryitonline.net/#code=K2B7LD99CgooYHsoW157fV0rKX0oLD8pKFtee31dKikKJDMkMjwkMT4KKWBbPn1dLD9bPHtdCiwKKFxkKSwrWzx7XSsKJDF9LHsKPCsKewosKls-fV0rCn0&input=e3s1NCx7NDMsNzYse3t7LTE5LHt7fSx7e319fX19fX0sMjB9LDEyLHt7fX19)
[Answer]
# Mathematica ~~55 64~~ 62 bytes
```
#~Select~AtomQ/.{}->Nothing&/@Table[Level[#,{k}],{k,Depth@#}]&
```
---
```
%&[{1, 2, {3, {4, 5}, 6, {7, {8}, 9}}}]
```
>
> {{1, 2}, {3, 6}, {4, 5, 7, 9}, {8}}
>
>
>
[Answer]
# JavaScript, ~~112~~ 80 bytes
```
F=(a,b=[],c=0)=>a.map(d=>d!==+d?F(d,b,c+1):b[c]=[...b[c]||[],d])&&b.filter(d=>d)
```
Thanks Neil for helping shave off 32 bytes.
[Answer]
# Jelly, 24 bytes
```
fFW®;©ṛ¹ḟF;/µŒḊ’$¡W®Tị¤;
```
[Try it online!](http://jelly.tryitonline.net/#code=ZkZXwq47wqnhuZvCueG4n0Y7L8K1xZLhuIrigJkkwqFXwq5U4buLwqQ7&input=&args=W1s1NCwgWzQzLCA3NiwgW1tbLTE5XV1dXSwgMjBdLCAxMl0)
If newline-separated lists were allowed, this could be golfed down to **14 bytes**.
```
fFṄ¹¹?ḟ@¹;/µ¹¿
```
[Try it online!](http://jelly.tryitonline.net/#code=ZkbhuYTCucK5P-G4n0DCuTsvwrXCucK_&input=&args=W1s1NCwgWzQzLCA3NiwgW1tbLTE5XV1dXSwgMjBdLCAxMl0)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
ŒJẈĠịF
```
[Try it online!](https://tio.run/##y0rNyan8///oJK@HuzqOLHi4u9vt/@H2R01rjk56uHMGkI78/z/aUEfBSEch2hiITXQUTGN1FMyATHMgtgCyLWNjYyGyQHXRhiCVhiYgAiRpBMSGIOloE5AqkN5oI4jKaFOQiBlY0hSkwQRohDnI5OhoXUOQqSD9BiADjMCKok0NYiGqgXQsAA "Jelly – Try It Online")
Jelly has [substantially improved](https://codegolf.stackexchange.com/a/73659/66833) in the past 5 years
## How it works
```
ŒJẈĠịF - Main link. Takes a list L on the left
ŒJ - Multi-dimensional indices
Ẉ - Get the length of each element
This yields the depth (starting at 1 for flat elements) of each element
Ġ - Group the indices of this list by the values
F - Flatten L
ị - Index into
```
Huh? The way that `ŒJẈĠ` works is kinda confusing without an example. Let's take `L = [3, 1, [12, [14, [18], 2], 1], [[4]], 5]` and work through it
`ŒJ` is one of a series of multi-dimensional commands that reflect the behaviour of their one-dimensional versions. Specifically, this is the "multi-dimensional indices" command, a multi-dimensional version of `J`, the "indices" command.
Picture `L` arranged like this:
```
3 1 12 14 18 2 1 4 5
12 14 18 2 1 4
14 18 2 4
18
```
That is, each element is repeated down a number of times equal to it's depth. `ŒJ` doesn't quite leave the elements like this (it changes the specific values, not the shape), but it's enough. `Ẉ` then calculates the length of each i.e. how many rows each element goes down:
```
1 1 2 3 4 3 2 3 1
```
`Ġ` the takes this list as it's argument. First, it's generates this list's indices: `[1, 2, 3, 4, 5, 6, 7, 8, 9]`. We then group these indices by the values of the argument. So because the values at indices `3` and `7` are equal (they're both `2`), `[3, 7]` is grouped. The final result of this is `[[1, 2, 9], [3, 7], [4, 6, 8], [5]]` as the groups are sorted by the values they're grouped by.
Finally, we index into the flattened `L` using this list of groups, which yields the intended output
[Answer]
# Python, ~~108~~ 99 bytes
This seems a bit long to me, but I couldn't make a one-liner shorter, and if I try using `or` instead of `if`, I get empty lists in the results.
```
def f(L):
o=[];i=[];j=[]
for x in L:[i,j][[]<x]+=[x]
if i:o+=[i]
if j:o+=f(sum(j,[]))
return o
```
[**Try it online**](http://ideone.com/FhIvyM)
Edit: [Saved 9 bytes thanks to Stack Overflow](https://stackoverflow.com/a/12135169/2415524)
[Answer]
## Python 3, 109 bytes
As ever, stupid Python 2 features like comparing `int`s and `list`s mean that Python 3 comes out behind. Oh well...
```
def d(s):
o=[]
while s:
l,*n=[],
for i in s:
try:n+=i
except:l+=[i]
if l:o+=[l]
s=n
return o
```
[Answer]
# Perl, 63 bytes
```
{$o[$x++]=[@t]if@t=grep{!ref}@i;(@i=map{@$_}grep{ref}@i)&&redo}
```
Input is expected in `@i`, output produced in `@o`. (I hope this is acceptable).
Example:
```
@i=[[54, [43, 76, [[[-19]]]], 20], 12]; # input
{$o[$x++]=[@t]if@t=grep{!ref}@i;(@i=map{@$_}grep{ref}@i)&&redo} # the snippet
use Data::Dumper; # print output
$Data::Dumper::Indent=0; # keep everything on one line
$Data::Dumper::Terse=1; # don't print $VAR =
print Dumper(\@o);
```
Output:
```
[[12],[54,20],[43,76],[-19]]
```
[Answer]
## Clojure, 119 bytes
**(116 with seq? and input as lists, a trivial modification)**
```
(defn f([v](vals(apply merge-with concat(sorted-map)(flatten(f 0 v)))))([l v](map #(if(number? %){l[%]}(f(inc l)%))v)))
```
Better intended:
```
(defn f([v] (vals(apply merge-with concat(sorted-map)(flatten(f 0 v)))))
([l v](map #(if(number? %){l[%]}(f(inc l)%))v)))
```
When called with two arguments (the current level and a collection) it either creates an one-element unordered-map like `{level: value}`, or calls `f` recursively if a non-number (presumambly a collection) is seen.
These mini-maps are then merged into a single `sorted-map` and key collisions are handled by `concat` function. `vals` returns map's values from first level to the last.
If a number is the only one at its level then it remains a `vec`, others are converted to lists by `concat`.
```
(f [[54, [43, 76, [[[-19]]]], 20], 12])
([12] (54 20) (43 76) [-19])
```
If input was a `list` instead of `vec` then `number?` could be replaced by `seq?`, oddly vector isn't `seq?` but it is `sequential?`. But I'm too lazy to implement that version, re-do examples etc.
[Answer]
## Racket 259 bytes
```
(let((ol'())(m 0))(let p((l l)(n 0))(cond[(empty? l)][(list?(car l))(set! m(+ 1 n))
(p(car l)(+ 1 n))(p(cdr l)n)][(set! ol(cons(list n(car l))ol))(p(cdr l)n )]))
(for/list((i(+ 1 m)))(flatten(map(λ(x)(cdr x))(filter(λ(x)(= i(list-ref x 0)))(reverse ol))))))
```
Ungolfed:
```
(define (f l)
(define ol '())
(define maxn 0)
(let loop ((l l) ; in this loop each item is added with its level
(n 0))
(cond
[(empty? l)]
[(list? (first l))
(set! maxn (add1 n))
(loop (first l) (add1 n))
(loop (rest l) n)]
[else
(set! ol (cons (list n (first l)) ol))
(loop (rest l) n )]))
; now ol is '((0 1) (0 2) (1 3) (2 4) (2 5) (1 6) (2 7) (3 8) (2 9))
(for/list ((i (add1 maxn))) ; here similar levels are combined
(flatten
(map (λ (x) (rest x)) ; level numbers are removed
(filter (λ (x) (= i(list-ref x 0)))
(reverse ol))))))
```
Testing:
```
(f '[1 2 [3 [4 5] 6 [7 [8] 9]]])
```
Output:
```
'((1 2) (3 6) (4 5 7 9) (8))
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 37 bytes
```
j']['!=dYsXKu"GK@=)'[\[\],]'32YXUn?1M
```
[**Try it online!**](http://matl.tryitonline.net/#code=aiddWychPWRZc1hLdSJHS0A9KSdbXFtcXSxdJzMyWVhVbj8xTQ&input=W1s1NCwgWzQzLCA3NiwgW1tbLTE5XV1dXSwgMjBdLCAxMl0)
Works with [current release (13.0.0)](https://github.com/lmendo/MATL/releases/tag/13.0.0) of the language/compiler.
This produces the output as lines of space-separated values, where each line corresponds to the same nesting level, and different nesting levels are separated by newlines.
```
j % read input as string (row array of chars)
']['! % 2x1 array containing ']' and '['
= % test for equality, all combinations
d % row array obtained as first row minus second row
Ys % cumulative sum. Each number is a nesting level
XK % copy to clibdoard K
u % unique values: all existing nesting levels
" % for each nesting level
G % push input
K % push array that indicates nesting level of each input character
@ % push level corresponding to this iteration
= % true for characters corresponding to that nesting level
) % pick those characters
'[\[\],]' % characters to be replaced
32 % space
YX % regexp replacement
U % only numbers and spaces remain: convert string to array of numbers
n? % if non-empty
1M % push that array of numbers again
% end if implicitly
% end for each implicitly
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 18 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
é╔óó)₧ú↔u.≤∟╦Ç╟·○`
```
[Run and debug it](https://staxlang.xyz/#p=82c9a2a2299ea31d752ef31ccb80c7fa0960&i=%5B1,+2,+%5B3,+%5B4,+5%5D,+6,+%5B7,+%5B8%5D,+9%5D%5D%5D%0A%5B3,+1,+%5B12,+%5B14,+%5B18%5D,+2%5D,+1%5D,+%5B%5B4%5D%5D,+5%5D%0A%5B2,+1,+%5B%5B5%5D%5D,+6%5D%0A%5B%5B54,+%5B43,+76,+%5B%5B%5B-19%5D%5D%5D%5D,+20%5D,+12%5D%0A%5B%5B%5B50%5D%5D,+%5B%5B50%5D%5D%5D&m=2)
I rhought I'd be able to beat pyth, but ¯\\_(○-○)\_/¯
] |
[Question]
[
You may have seen [Jacob's Ladder](https://en.wikipedia.org/wiki/Spark_gap#Visual_entertainment) in children's science museums. If you're not familiar with what they look like, there are several images and video examples on the [Wikimedia Commons](https://commons.wikimedia.org/wiki/Category:Jacob%27s_ladder_(electrical)). The challenge today is to create an animated ASCII version of the electrical gadget. In the end, it should look something like this:

---
**Ladder Construction**
Here is the basic shape of a ladder with a height (***H***) of 6:
```
6 \ /
5 \ /
4 \ /
3 \ /
2 \ /
1 \ /
0 ¯¯
```
The numbers on the left simply indicate row number for this example and should not be included in the output. We'll refer to a given row by it's number (***R***). Row 0 is the bottom `¯¯`. Each row 1 through ***H*** is comprised of four parts:
* A space (U+0020) repeated (***H*** - ***R***) times
* A back slash `\` (U+005C)
* A space (U+0020) repeated (2 \* ***R***) times
* A forward slash `/` (U+002F)
Row 0 is identical except both the slashes are replaced with a macron `¯` (U+00AF). Trailing whitespace at the end of each line or below the ladder is OK. Leading whitespace is not.
---
**Arc Construction**
Once the ladder is constructed, you can create arcs between the left and right side. One arc is entirely within a row and replaces the spaces between the leading `\` and trailing `/`. Therefore, row 2 will have 4 characters in its arc, row 3 will have 6, and so forth. Each arc is composed using the following rules:
* The only allowable characters are `_/¯\` (U+005F, U+002F, U+00AF, U+005C)
* In order to ensure a smooth appearance, any `¯` or `/` must be followed by a `¯` or `\`
* In order to ensure a smooth appearance, any `_` or `\` must be followed by a `_` or `/`
* The two rules above apply to the edges of the ladder as well
* The three rules above effectively mean that the first character in the arc must be `_` or `/` and the last character must be `_` or `\` (`\¯\_//` is invalid on both ends but `\_/¯\/` is OK)
* There must be a non-zero chance for each allowable character to occur at a given point
* Each arc is independent from every other arc
---
**Animation**
The life of a single arc is created by starting it at row 1 and "moving" it up one row at a time until it reaches the top. I.E., first generate an arc at row 1, then set it back to spaces and generate an arc at row 2, and so forth. Given a number of arcs to show (***N***), show the complete life of that many arcs one at a time using the following guidelines:
* Only one arc should be "alive" at any one time. The next arc cannot start until the current one reaches the top and then extinguishes.
* Each row of the arc's life should be shown for exactly one frame
* There should one frame of just the basic ladder (with no arcs) before a new arc starts (optional before the first arc)
* The animation should show the full life of ***N*** arcs. If ***N***=0, it should animate random arcs forever until stopped.
* If ***N***>0, you may still loop the animation forever but it must be a loop of the same arcs over and over. (The example GIF at the top of this post has ***H***=6 and ***N***=3 but it loops forever.)
* The animation should occur in-place. That is, each frame should completely overwrite the next frame and be in the same location.
* The length of each frame can be whatever you want but make it watchable by a human (I.E., use your common sense: 0.01s/frame and 30s/frame are both unacceptable.)
---
**Input / Output**
* Input and Output can be in any [standard format](https://codegolf.meta.stackexchange.com/q/2447/38183)
* You can export a GIF, write text to the screen, output a single file for each frame, or any other reasonable means
* [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/38183) are forbidden
* The height of the ladder ***H*** will be a positive integer
* The number of arcs to show ***N*** will be a non-negative integer
* Both ***H*** and ***N*** are taken as inputs in any order you choose (Please include the order in your answer)
---
**Winning Condition**
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code wins.
[Sandbox](https://codegolf.meta.stackexchange.com/a/16352/38183)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~287~~ ~~271~~ ~~270~~ ~~276~~ 275 bytes
```
import time,random
r,n=input()
c=n*-~r or-r
while c:
c-=1;L=[list(' '*i+'\\'+' '*(r-i)+'/')for i in range(r)];x=c%-~r;time.sleep(1);y=x+1;exec"L[x][y]=random.choice('\xaf/\_'[L[x][y-1]in'\_'::2][y==2*r-x:]);y+=1;"*2*(r-x)
for l in['']*99+L+[' '*r+'\xaf'*2]:print''.join(l)
```
[Try it online!](https://tio.run/##Jc5LasMwEIDhvU8hAmX0sBLsRSA2uoFvIIsSVKWeYktGUam86dVdudnNMPDPt25pCr7dd1zWEBNJuLg63v1HWKpYe4V@/U6UVVZ5Ln8jCVHG6mfC2RHbVcRK1fSD0jM@EwUCHAWMIwggZaZRIhNwAfYIkSBBT0r509HITJ@VfSvB/nh4fs7OrbRh/aayaHqXnT0NOhu9GfXCnO0U0DoKY74/LuM76NddNgY9lL3r2rIq1fIoc2dKShTaibcHI7OKHIa5GDSA4bebGIQ@wFH8J4G3plsj@gRw/gro6cz2/Vo3fw "Python 2 – Try It Online")
Does not clear the screen on tio, but works in a console.
Gif of it running:
[](https://i.stack.imgur.com/Vw7w4.gif)
[Answer]
## JavaScript (ES6), 245 bytes
```
f=(o,h,n,i=0)=>(o.innerText=[...Array(h+1)].map((_,j)=>` `.repeat(j)+(j<h?`\\${[...Array(w--*2)].map((_,k)=>h+~j-i?` `:k>w*2|Math.random()<.5?s[s=t,1]:s[s=`¯\\`,0],s=t=`/_`).join``}/`:`¯¯`),w=h).join`
`,(++i<h||--n)&&setTimeout(f,250,o,h,n,i%h))
```
```
Height: <input type=number min=1 value=6 id=h><br>Arcs: <input type=number min=0 value=3 id=n><br><input type=button value=Go! onclick=f(o,+h.value,+n.value)><pre id=o></pre>
```
Byte count assumes ISO-8859-1 encoding.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 406 bytes
```
#define p(X) printf(X),usleep(999)
#define x(X) do{s[X]=0;p(s);s[X]=' ';}while(0)
char c[2][2]={95,47,92,'¯'};R;i;j;k;a(){char s[2]={92,0};for(j=0;j<2*R-1;++j,p(s))*s=c[*s<50][rand()%2];*s=c[*s<50][0];p(s);}f(H,N){char s[99];for(i=0;i<99;++i)s[i]=' ';p("\e[s");for(i=0;;++i){i%=(N?N:i+1);srand(i^H^N);for(k=1;k<H;++k){for(R=H;--R;){x(H-R+1);p("\\");if(R==k)a();else x(2*R);p("/\n");}x(H);p(" ¯¯\n\e[u");}}}
```
[Try it online!](https://tio.run/##TZFLboMwEIb3nMJKFcUmRgXatHInqFtWWbCqBI6ECCQOKUE4aSMhzpQ75GJ0MGpay4t5fPPPjJ052yzr@4dNXqgqJzX9YKRuVHUq0OJnfcjzmgohmPWLXAZkc2x1/CEDF2qqGRh7RmbQfe/UIacus7Jd2pAs9iXeoBUL/vzKhc9nt@usgwgU7KGElLLWgHqkfO52UBwbukfl/dK3I8eD@XzPhy7M1kEW23q5cGXcpNWGsqkv4X/UleM8XUFDvrprCyGNqkJVtRQCJRXTsRpnrukkyWM9YXfG5Fs1DejqffWm5h5uaBqqdbhejVwZeFAuQ0RL1g6BKAjBcSJg7YWGTjQUDcoJ6qoCs0HJcF3ID3p4Q1zN5B@TCoEOS4xLbtfbNalwnvMQ7roev4J8pqqig5E224wTs5WN9lcsGWktgqeg6emoqAl6kvE/z5eMgWGa/HRuKuKC1fX9S//0Aw "C (gcc) Try It Online")
Description:
```
#define p(X) printf(X),usleep(999) // Define p to printf(p) + delay
#define x(X) do{s[X]=0;p(s);s[X]=' ';}while(0) // Define x(X) to print X spaces
// This uses a string s full of
// spaces and adds the null
// terminator where approrpiate
char c[2][2]={95,47,92,'¯'}; // 2d array of 'next arc' options
R;i;j;k; // Variables
a(){ // a() -> print arc for row R
char s[2]={92,0}; // s is a string of next char
// initialize to backslash
for(j=0;j<2*R-1;++j // loop over each character
,p(s)) // printing s each time
*s=c[*s<50][rand()%2]; // set s to the next arc char
*s=c[*s<50][0]; // set s to the 'first' arc char
// note that in definition of c
// first means appropriate as
// final character before /
p(s);} // print the last character
f(H,N){ // f(H,N) -> print jacob ladder
char s[99];for(i=0;i<99;++i)s[i]=' '; // this is the space string for x
p("\e[s"); // ANSI terminal save position
for(i=0;;++i){i%=(N?N:i+1); // loop i->N (or i->INT_MAX if N=0)
srand(i^H^N); // seed random with i XOR H XOR N
for(k=1;k<H;++k){ // for each row (bottom to top)
for(R=H;--R;){ // for each row (top to bottom)
x(H-R+1);p("\\"); // print left " \"
if(R==k) // if on the arc row
a(); // print the arc
else x(2*R); // otherwise print spaces
p("/\n");} // finish off the row
x(H);p(" ¯¯\n\e[u");}}} // print bottom line and move back
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~347~~ 319 bytes
```
filter c{Param($h,$n)if($n-eq0){$n=-1}for($x=0;$x++-ne$n;){($h..1)|%{$l=(($h..1)|%{"$(" "*($h-$_))\$(" "*$_*2)/"})+"$(" "*$h)¯¯"
$r="Get-Random"
$i=0
$z=-join((0..(($h-$_)*2))|%{$i=switch($i%3){0{&$r 0,1}default{&$r 2,3}}"_/¯\"[$i]})+"_\\_"[$i]
$l[$_-1]=($l[$_-1]).Substring(0,$_)+"$z/"
cls
$l
Sleep -m 250}}}
```
[Try it online!](https://tio.run/##RY5BboMwEEX3nMJyJ5WdYDCJ2k3kdbdVswwRosQUV8akhihRqM@UO3Ax6pJU3c2b@fpvDs1J2raSWo9jqXQnLSr619zmNYEqBENVScAw@cVpD0awxJWNJXAWfA3nxYIZCWZNex@OooR@z3rQgvwTBoIRnvsFg4zS9IaQzZc0xo4u7neo6HAdrjgAK/CL7NhbbvZN7VkJHsBFsM9GGUJ4FJF7l2@YdEq0J9UVFQE1W9Ge949gEQ8Tt5dlftTdxMtw5RzO4uGa4i2o3a85S9NsggD0FjKW7AT5m2i0Ob63nVXmg/DQ2/yjlxgHD4VufTzYaCkPiNVo@cSdc0GBntFqHH8A "PowerShell – Try It Online") Couldn't get `$args` to play nice, so the link calls the function without clearing the console.
## Ungolfed
```
filter c{
Param($h,$n)
if($n -eq 0){$n=-1} # inelegant swap to allow for an infinite loop.
# Curse you zero-indexing!
for($x=0;$x++-ne$n;)
{
($h..1) | % {
$l=(($h..1)|%{ # (( double paren is needed to induce each line
# as a new array element
"$(" "*($h-$_))\$(" "*$_*2)/" # offset by total height.
# N spaces + rung + N*2 spaces + rung
})+"$(" "*$h)¯¯" # last line is the floor of the ladder
$r="Get-Random" # shorter to declare once and execute with & operator
$i=0 # initialize $i so we choose only _ or / for the first char
$z=-join( # build an electric ZAP!
(0..(($h-$_)*2))|%{
$i = switch($i%3) { # choose next char based on previous selection
0{&$r 0,1}
default{&$r 2,3}
}
"_/¯\"[$i]
}
)+"_\\_"[$i] # final char is \ or _ to rejoin the ladder
$l[$_-1]=($l[$_-1]).Substring(0,$_)+"$z/" # select one rung of the ladder
# append an electric ZAP!
cls # clear the console
$l # display the ladder
Sleep -m 250
}
}
}
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 293 bytes
```
m={}
" __/\\_/¯¯\\/¯\\".chars.each_slice(3){|e|u,*v=e;m[u]=v}
a=->l,c{l<1?"/":(d=m[c].sample;c+a[l-1,d])}
n=gets.to_i
h=gets.to_i
o=0
while o<n||n<1
h.times{|i|puts (0...h).map{|j|" "*j+"\\"+a[2*(h-j),i==h-j-1?["_","/"].sample: " "]}*"\n";puts" "*h+"¯¯";sleep(0.3);puts"\n"*99}
o+=1
end
```
[Try it online!](https://tio.run/##TY9faoQwEIffc4owT/6Na4XCrqZ7EJVgNWwiicpGtxTjmfYOezEbKYW@zAzMbz6@uS@f3/uu6bohwBgzllQVS17P17OqkqMAaUVzN4Q3rWBGyZZ7mb9abpcoeFCe63Kp6WNDDY0/VNSuqkivkMDF66gu25qYRk@K523YlCpOo672NzTQG58NmUcmkfg3j/SEvoRUHI/FYO1QpEiQWWpuVivttMwGeydCiPCJbqbV9hYwBH0ITtPx3wJPxL0fSUpdj9NrCQwiJ/NnccEuX28BVAPkB@44FyEc70JuFOeT42f@786FgvN5Q2NIU8SHbt8z9P4D "Ruby – Try It Online")
I'm on windows so it just prints many "\n" to clear the console. Takes 2 arguments `n` and `h` as two lines on stdin.
] |
[Question]
[
# String Stairs
**Disclaimer:** This is the first challenge I propose. Any and all feedback is welcome. If this is a duplicate, please point it out.
[Here](https://codegolf.meta.stackexchange.com/a/13976/74163)'s a link to the sandbox post.
# Goal
The goal of this challenge is to, given a string and an integer, print the string into blocks of that integer's size. If a word has more characters than the size of a block, print it into a descending "stair" pattern.
# Rules
* The "stair pattern" mentioned above means that, for every block of a same word, that block must begin exactly where the block above it ends. Check the test cases (or ask) if you have any questions.
* If a word is broken in multiple blocks, the following word must be printed with an adequate number of spaces, that is, it must be separated from the preceding word's lowermost block by exactly one whitespace. Check the test cases (or ask) for clarification.
* You can assume the input string will consist only of printable ASCII characters. Also, it will not have multiple whitespaces in a row.
* You can also assume that the integer will always be in the range [1, +∞).
* Trailing whitespace or newlines are allowed.
* You can use [any reasonable method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) for I/O.
* [Standard Loopholes](https://codegolf.meta.stackexchange.com/q/1061/73111) apply.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code (in bytes, per language) wins. After a week (or so), I'll accept the overall shortest answer.
# Test Cases
```
(String, Integer) => (Output)
"This is a large string", 3 => Thi is a lar str
s ge ing
"This is an even larger string!", 2 => Th is an ev la st
is en rg ri
er ng
!
"Ooooh dear, what a big string you have!", 3
=> Ooo dea wha a big str you hav
oh r, t ing e!
"Staphylococcus saprophyticus", 4 => Stap sapr
hylo ophy
cocc ticu
us s
"I hope you find this challenge interesting", 2
=> I ho yo fi th ch in
pe u nd is al te
le re
ng st
e in
g
"Well, this test case looks kinda pointless now doesn't it?", 15
=> Well, this test case looks kinda pointless now doesn't it?
"This one looks a lot more interesting!", 1 => T o l a l m i
h n o o o n
i e o t r t
s k e e
s r
e
s
t
i
n
g
!
"Keep in mind, people: 'Punctuation! Does! Matter!'", 2
=> Ke in mi pe 'P Do Ma
ep nd op un es tt
, le ct ! er
: ua !'
ti
on
!
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes
```
F⪪θ «↑⸿⸿FLι«M¬﹪κIη↙§ικ
```
[Try it online!](https://tio.run/##LY2xDoIwFEVn@IoXptcEFkecjC4kYEyMGwuBQhuaPiwP1Bi@vYK6npxzb60qV1NlvG/JAV4HoxnvMUQQCQHvMLg4bRnT27Cy0pUuEvsw@Lq5tB0r1D8vKGiWeCbGgprJEPYxHKuRUQkhYkhP9LC5bHnL/6MHzmwjn6jjXmx4CRfvM1A0SHjRBK22DbDSI9SqMma9k7B20smRte3CnU9mn4zmAw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ First input
⪪ Split on spaces
F « Loop over each word
↑⸿⸿ Move the cursor to the top row and two columns right*
ι Current word
L Length
F « Loop over implicit range
κ Current index
η Second input
I Cast to integer
﹪ Modulo
¬ Logical not
M ↙ Move that many characters down and left
ι Current word
κ Current index
§ Index into word and implicitly print
```
\*More precisely, "move to the start of the next line twice, but as if the canvas was rotated." Edit: In between this challenge being set and this answer being accepted, Charcoal actually acquired a means of splitting a string into pairs of characters, reducing the code 16 bytes:
`F⪪θ «↑⸿⸿F⪪ιIη«κ↙` [Try it online!](https://tio.run/##TcuxCsIwFEDROfmKR6YE6uJYR10EBUHcuoT42gRDXkxiRaTfHlt0cL2ca6xOhrSvtacE8hy9K/LegAChFLw5OyUXimwvcW5d6pJQG87@rGtgq3ORVn39b7gtjB1pRNnu6BkO2JclTXyqdQ@WIsKLHtC7cIViXQZjtfcYBoT5x4S5uDDwdV2N/gM "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ First input
⪪ Split on spaces
F « Loop over each word
↑⸿⸿ Move the cursor to the top row and two columns right
ι Current wordIη
η Second input
I Cast to integer
⪪ Split into substrings of that length
F « Loop over each substring
κ Print the substring
↙ Move the cursor down and left
```
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), ~~28~~ ~~27~~ 26 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
ā,θ{0Eā;{ēb÷eb‰⁴bH*+I;Iž}┼
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUwMTAxJTJDJXUwM0I4JTdCMEUldTAxMDElM0IlN0IldTAxMTNiJUY3ZWIldTIwMzAldTIwNzRiSCorSSUzQkkldTAxN0UlN0QldTI1M0M_,inputs=SSUyMGhvcGUlMjB5b3UlMjBmaW5kJTIwdGhpcyUyMGNoYWxsZW5nZSUyMGludGVyZXN0aW5nJTBBMg__)
I did implement [`‰`](https://github.com/dzaima/SOGL/blob/811fe102f36968272be17f8fe3d6baaf7e4d527e/P5ParserV0_12/data/charDefs.txt#L489-L493) while making this, but the documentation for it existed before.
Explanation:
```
ā push an empty array - the main canvas
, push the first input
θ{ for each word (pushing the word each time)
0E set the variable E to 0
ā; below the current word place an empty array - current word canvas
{ } for each character of the word
ēb÷ push (E++ // B) - note that E is incremented after being used
eb‰ push E positive modulo B - like regular modulo but in the 0 output case it gives B
⁴ duplicate the item below ToS
bH push B-1
* multiply [(E++ // B) and B-1]
+ add [that multiplication to E‰B] - current letters X position
I increase the X position to have one leading space row
; swap top 2 items - current X position and (E++ // B)
I increase to create current letters Y position
ž in those positions insert the current letter in the current words canvas
┼ append to main canvas current word canvas horizontally
```
[Answer]
# Javascript ES6 , 187 183 174 166 163 148 145 143 141 140 138 bytes
* for readability added some bytes in the code and removed them in the bytes count
* instead of s="",j=0 i did j=s=""
* instead of for(i in s) - regular for loop - removed 1 byte
* using already generated values in the indexers of the arrays - removed 8 bytes
* using already with value i= s.length (from the first loop) in the eval - instead of the real array length - causes trailing space which are allowed
* using map of S instead of eval - reduces by 3 bytes
* using fill instead on initializing empty array- so there is not need for the loop in the map result
* could replace || with | - reduced by 2 bytes
* thanks to @Justin Mariner - replace occurrences ==" " with <"!" reduces 2 bytes
* moved the conditions from the a[I] to the other statement to reduces one " u<"!" " - reduces 2 bytes
* instead of (I+=2,j=0) - j=!(I+=2) - reduced 1 byte
* "for of" instead of for
```
F=(s,n)=>{R=[I=j=i=0]
for(u of s)
a=R[z=u<"!"?j=!(I+=2):(j%n&&I++,j++/n|0)]=R[z]||[...s].fill` `,a[I]=u
return R.map(x=>x.join``).join`
`}
console.log(F("This is a large string", 3));
console.log(F("This is an even larger string!", 2));
console.log(F("Ooooh dear, what a big string you have!", 3));
console.log(F("Staphylococcus saprophyticus", 4));
console.log(F("I hope you find this challenge interesting", 2));
console.log(F("Well, this test case looks kinda pointless now doesn't it?", 15));
console.log(F("This one looks a lot more interesting!", 1))
console.log(F("Keep in mind, people: 'Punctuation! Does! Matter!'", 2));
```
[Answer]
## C#, 200 bytes
```
int x=-2,y=0;Regex.Split(i,@"\s+").ToList().ForEach(w =>{y=0;Regex.Matches(w,".{0,"+s+"}").Cast<Match>().ToList().ForEach(c=>{x+=(y==0?2:s-1);Console.SetCursorPosition(x,y);Console.Write(c);y++;});});
```
Where the string is specified by **i** and the size is specified by **s**.
E.g.
```
string i = "Staphylococcus saprophyticus";
int s = 2;
int x=-2,y=0;Regex.Split(i,@"\s+").ToList().ForEach(w =>{y=0;Regex.Matches(w,".{0,"+s+"}").Cast<Match>().ToList().ForEach(c=>{x+=(y==0?2:s-1);Console.SetCursorPosition(x,y);Console.Write(c);y++;});});
```
Basically, the first part **Regex.Split** uses white spaces to split the sentence into words, and the **Regex.Matches** splits each word into chunks specified by **s**. The chunk is written to Cursor position (x,y) where Y is set to 0 for every new word, and x is incremented by 2 for the first chunk of a word and subsequently (s-1) for each chunk.
x starts off it's life at -2 to ensure it's first use is set to 0.
I'm not knowledgable enough in C# trivia to be able to to make it smaller, but suspect it probably can be.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~203~~ 199 bytes
```
s,l=input()
S=s.split()
x=[]
for w in S:L=len(w);W=[i/l*~-l*' '+w[i:i+l]for i in range(0,L,l)];x+=[[c.ljust(L/l*~-l+L%l)for c in W+['']*len(s)]]
for l in zip(*x):
L=' '.join(l)
if L.strip():print L
```
[Try it online!](https://tio.run/##JY2xasMwFEV3f8VzoEiyVSe0m4O2blWhkCGD8GBcpX3hVRKSjN0O/XU3ItuFe8694Sd/efe0bUmSQhfmzEV1UqlLgbDkVZmhuvgIC6CDU68VWccXcTwrg3tq/h6pYcDaxWCPLQ0FxYLG0X1afpBakhiOa6uMmTq6zilzffda/UCi8FPhz61hbGjKehLD/ZNK8YuBN6voK9Dq9tRdPTpOogK8gO5Sjrde9CGiy6C3bfdqbSjeN7oPCcH6QLYH9j67Kc9jRu9qePE21fA25mxjzXYSnv8B "Python 2 – Try It Online")
[Answer]
## Perl 5, 59 bytes
**55 bytes code + 4 for `-ai`.**
```
$-=s/.{$^I}\K(?=.)/\x1b[1B\x1b[1D/g,print$_,"\x1b[1A"x$-,$"for@F
```
**Note: the `\x1b`s are literal `ESC` chars, but escaped here for easy copy and paste.**
This script utilises ANSI escape sequences and requires input via the `-i` flag which is non-standard. If either of these are not acceptable, please let me know and I'll updated.
### Example runs
```
perl -ai3 string-stairs.pl <<< 'This is a large string' 2>/dev/null
Thi is a lar str
s ge ing
perl -ai2 string-stairs.pl <<< 'This is an even larger string!' 2>/dev/null
Th is an ev la st
is en rg ri
er ng
!
perl -ai3 string-stairs.pl <<< 'Ooooh dear, what a big string you have!' 2>/dev/null
Ooo dea wha a big str you hav
oh r, t ing e!
perl -ai4 string-stairs.pl <<< 'Staphylococcus saprophyticus' 2>/dev/null
Stap sapr
hylo ophy
cocc ticu
us s
perl -ai2 string-stairs.pl <<< 'I hope you find this challenge interesting' 2>/dev/null
I ho yo fi th ch in
pe u nd is al te
le re
ng st
e in
g
perl -ai15 string-stairs.pl <<< "Well, this test case looks kinda pointless now doesn't it?" 2>/dev/null
Well, this test case looks kinda pointless now doesn't it?
perl -ai1 string-stairs.pl <<< 'This one looks a lot more interesting!' 2>/dev/null
T o l a l m i
h n o o o n
i e o t r t
s k e e
s r
e
s
t
i
n
g
!
perl -ai2 string-stairs.pl <<< "Keep in mind, people: 'Punctuation! Does! Matter!'" 2>/dev/null
Ke in mi pe 'P Do Ma
ep nd op un es tt
, le ct ! er
: ua !'
ti
on
!
```
] |
[Question]
[
## Background
I play D&D on a regular basis with some friends. While talking about the complexity of some systems/versions when it comes to rolling dice and applying bonuses and penalties, we jokingly came up with some additional complexity for dice rolling expressions. Some of them were too outrageous (like extending simple dice expressions like `2d6` to matrix arguments1), but the rest make for an interesting system.
## The Challenge
Given a complex dice expression, evaluate it according to the following rules and output the result.
## Basic Evaluation Rules
* Whenever an operator expects an integer but receives a list for an operand, the sum of that list is used
* Whenever an operator expects a list but receives an integer for an operand, the integer is treated as a one-element list containing that integer
## Operators
All operators are binary infix operators. For the purpose of explanation, `a` will be the left operand, and `b` will be the right operand. List notation will be used for examples where operators can take lists as operands, but actual expressions consist only of positive integers and operators.
* `d`: output `a` independent uniform random integers in the range `[1, b]`
+ Precedence: 3
+ Both operands are integers
+ Examples: `3d4 => [1, 4, 3]`, `[1, 2]d6 => [3, 2, 6]`
* `t`: take the `b` lowest values from `a`
+ Precedence: 2
+ `a` is a list, `b` is an integer
+ If `b > len(a)`, all values are returned
+ Examples: `[1, 5, 7]t1 => [1]`, `[5, 18, 3, 9]t2 => [3, 5]`, `3t5 => [3]`
* `T`: take the `b` highest values from `a`
+ Precedence: 2
+ `a` is a list, `b` is an integer
+ If `b > len(a)`, all values are returned
+ Examples: `[1, 5, 7]T1 => [7]`, `[5, 18, 3, 9]T2 => [18, 9]`, `3T5 => [3]`
* `r`: if any elements in `b` are in `a`, reroll those elements, using whatever `d` statement generated them
+ Precedence: 2
+ Both operands are lists
+ Rerolling is done only once, so it is possible to still have elements of `b` in the result
+ Examples: `3d6r1 => [1, 3, 4] => [6, 3, 4]`, `2d4r2 => [2, 2] => [3, 2]`, `3d8r[1,8] => [1, 8, 4] => [2, 2, 4]`
* `R`: if any elements in `b` are in `a`, reroll those elements repeatedly until no elements of `b` are present, using whatever `d` statement generated them
+ Precedence: 2
+ Both operands are lists
+ Examples: `3d6R1 => [1, 3, 4] => [6, 3, 4]`, `2d4R2 => [2, 2] => [3, 2] => [3, 1]`, `3d8R[1,8] => [1, 8, 4] => [2, 2, 4]`
* `+`: add `a` and `b` together
+ Precedence: 1
+ Both operands are integers
+ Examples: `2+2 => 4`, `[2]+[2] => 4`, `[3, 1]+2 => 6`
* `-`: subtract `b` from `a`
+ Precedence: 1
+ Both operands are integers
+ `b` will always be less than `a`
+ Examples: `2-1 => 1`, `5-[2] => 3`, `[8, 3]-1 => 10`
* `.`: concatenate `a` and `b` together
+ Precedence: 1
+ Both operands are lists
+ Examples: `2.2 => [2, 2]`, `[1].[2] => [1, 2]`, `3.[4] => [3, 4]`
* `_`: output `a` with all elements of `b` removed
+ Precedence: 1
+ Both operands are lists
+ Examples: `[3, 4]_[3] => [4]`, `[2, 3, 3]_3 => [2]`, `1_2 => [1]`
## Additional Rules
* If the final value of an expression is a list, it is summed before output
* Evaluation of terms will only result in positive integers or lists of positive integers - any expression that results in a non-positive integer or a list containing at least one non-positive integer will have those values replaced by `1`s
* Parentheses can be used to group terms and specify order of evaluation
* Operators are evaluated in order of highest precedence to lowest precedence, with evaluation proceeding from left to right in the case of tied precedence (so `1d4d4` would be evaluated as `(1d4)d4`)
* The order of elements in lists does not matter - it is perfectly acceptable for an operator that modifies a list to return it with its elements in a different relative order
* Terms that cannot be evaluated or would result in an infinite loop (like `1d1R1` or `3d6R[1, 2, 3, 4, 5, 6]`) are not valid
## Test Cases
Format: `input => possible output`
```
1d20 => 13
2d6 => 8
4d6T3 => 11
2d20t1 => 13
5d8r1 => 34
5d6R1 => 20
2d6d6 => 23
3d2R1d2 => 3
(3d2R1)d2 => 11
1d8+3 => 10
1d8-3 => 4
1d6-1d2 => 2
2d6.2d6 => 12
3d6_1 => 8
1d((8d20t4T2)d(6d6R1r6)-2d4+1d2).(1d(4d6_3d3)) => 61
```
All but the last test case were generated with the reference implementation.
## Worked Example
Expression: `1d((8d20t4T2)d(6d6R1r6)-2d4+1d2).(1d(4d6_3d3))`
1. `8d20t4T2 => [19, 5, 11, 6, 19, 15, 4, 20]t4T2 => [4, 5, 6, 11]T2 => [11, 6]` (full: `1d(([11, 6])d(6d6R1r6)-2d4+1d2).(1d(4d6_3d3))`)
2. `6d6R1r6 => [2, 5, 1, 5, 2, 3]r1R6 => [2, 5, 3, 5, 2, 3]R6 => [2, 5, 3, 5, 2, 3]` (`1d([11, 6]d[2, 5, 3, 5, 2, 3]-2d4+1d2).(1d(4d6_3d3))`)
3. `[11, 6]d[2, 5, 3, 5, 2, 3] => 17d20 => [1, 6, 11, 7, 2, 8, 15, 3, 4, 18, 11, 11, 1, 10, 8, 6, 11]` (`1d([1, 6, 11, 7, 2, 8, 15, 3, 4, 18, 11, 11, 1, 10, 8, 6, 11]-2d4+1d2).(1d(4d6_3d3))`)
4. `2d4 => 7` (`1d([1, 6, 11, 7, 2, 8, 15, 3, 4, 18, 11, 11, 1, 10, 8, 6, 11]-7+1d2).(1d(4d6_3d3))`)
5. `1d2 => 2` (`1d([1, 6, 11, 7, 2, 8, 15, 3, 4, 18, 11, 11, 1, 10, 8, 6, 11]-7+2).(1d(4d6_3d3))`)
6. `[1, 6, 11, 7, 2, 8, 15, 3, 4, 18, 11, 11, 1, 10, 8, 6, 11]-7+2 => 133-7+2 => 128` (`1d128).(1d(4d6_3d3))`)
7. `4d6_3d3 => [1, 3, 3, 6]_[3, 2, 2] => [1, 3, 3, 6, 3, 2, 2]` (`1d128).(1d[1, 3, 3, 6, 3, 2, 2])`)
8. `1d[1, 3, 3, 6, 3, 2, 2] => 1d20 => 6` (`1d128).(6)`)
9. `1d128 => 55` (`55.6`)
10. `55.6 => [55, 6]` (`[55, 6]`)
11. `[55, 6] => 61` (done)
## Reference Implementation
This reference implementation uses the same constant seed (`0`) for evaluating each expression for testable, consistent outputs. It expects input on STDIN, with newlines separating each expression.
```
#!/usr/bin/env python3
import re
from random import randint, seed
from collections import Iterable
from functools import total_ordering
def as_list(x):
if isinstance(x, Iterable):
return list(x)
else:
return [x]
def roll(num_sides):
return Die(randint(1, num_sides), num_sides)
def roll_many(num_dice, num_sides):
num_dice = sum(as_list(num_dice))
num_sides = sum(as_list(num_sides))
return [roll(num_sides) for _ in range(num_dice)]
def reroll(dice, values):
dice, values = as_list(dice), as_list(values)
return [die.reroll() if die in values else die for die in dice]
def reroll_all(dice, values):
dice, values = as_list(dice), as_list(values)
while any(die in values for die in dice):
dice = [die.reroll() if die in values else die for die in dice]
return dice
def take_low(dice, num_values):
dice = as_list(dice)
num_values = sum(as_list(num_values))
return sorted(dice)[:num_values]
def take_high(dice, num_values):
dice = as_list(dice)
num_values = sum(as_list(num_values))
return sorted(dice, reverse=True)[:num_values]
def add(a, b):
a = sum(as_list(a))
b = sum(as_list(b))
return a+b
def sub(a, b):
a = sum(as_list(a))
b = sum(as_list(b))
return max(a-b, 1)
def concat(a, b):
return as_list(a)+as_list(b)
def list_diff(a, b):
return [x for x in as_list(a) if x not in as_list(b)]
@total_ordering
class Die:
def __init__(self, value, sides):
self.value = value
self.sides = sides
def reroll(self):
self.value = roll(self.sides).value
return self
def __int__(self):
return self.value
__index__ = __int__
def __lt__(self, other):
return int(self) < int(other)
def __eq__(self, other):
return int(self) == int(other)
def __add__(self, other):
return int(self) + int(other)
def __sub__(self, other):
return int(self) - int(other)
__radd__ = __add__
__rsub__ = __sub__
def __str__(self):
return str(int(self))
def __repr__(self):
return "{} ({})".format(self.value, self.sides)
class Operator:
def __init__(self, str, precedence, func):
self.str = str
self.precedence = precedence
self.func = func
def __call__(self, *args):
return self.func(*args)
def __str__(self):
return self.str
__repr__ = __str__
ops = {
'd': Operator('d', 3, roll_many),
'r': Operator('r', 2, reroll),
'R': Operator('R', 2, reroll_all),
't': Operator('t', 2, take_low),
'T': Operator('T', 2, take_high),
'+': Operator('+', 1, add),
'-': Operator('-', 1, sub),
'.': Operator('.', 1, concat),
'_': Operator('_', 1, list_diff),
}
def evaluate_dice(expr):
return max(sum(as_list(evaluate_rpn(shunting_yard(tokenize(expr))))), 1)
def evaluate_rpn(expr):
stack = []
while expr:
tok = expr.pop()
if isinstance(tok, Operator):
a, b = stack.pop(), stack.pop()
stack.append(tok(b, a))
else:
stack.append(tok)
return stack[0]
def shunting_yard(tokens):
outqueue = []
opstack = []
for tok in tokens:
if isinstance(tok, int):
outqueue = [tok] + outqueue
elif tok == '(':
opstack.append(tok)
elif tok == ')':
while opstack[-1] != '(':
outqueue = [opstack.pop()] + outqueue
opstack.pop()
else:
while opstack and opstack[-1] != '(' and opstack[-1].precedence > tok.precedence:
outqueue = [opstack.pop()] + outqueue
opstack.append(tok)
while opstack:
outqueue = [opstack.pop()] + outqueue
return outqueue
def tokenize(expr):
while expr:
tok, expr = expr[0], expr[1:]
if tok in "0123456789":
while expr and expr[0] in "0123456789":
tok, expr = tok + expr[0], expr[1:]
tok = int(tok)
else:
tok = ops[tok] if tok in ops else tok
yield tok
if __name__ == '__main__':
import sys
while True:
try:
dice_str = input()
seed(0)
print("{} => {}".format(dice_str, evaluate_dice(dice_str)))
except EOFError:
exit()
```
---
[1]: Our definition of `adb` for matrix arguments was to roll `AdX` for each `X` in `a * b`, where `A = det(a * b)`. Clearly that's too absurd for this challenge.
[Answer]
# Python 3, ~~803 788 753 749 744 748 745 740 700 695 682~~ 680 bytes
```
exec(r'''from random import*
import re
class k(int):
p=0;j=l([d(randint(1,int(b)),b)range(a)]);__mul__=l(sorted()[:b]);__matmul__=l(sorted()[-b:]);__truediv__=l([d(randint(1,int(_.i)),_.i)if _==b else _ ]);__sub__=k(max(1,int.__sub__(a,b)))
def __mod__(a,b):
x=[]
while x!=:x=;a=a/b
l(x)
def :
if b.p:p=b.p;del b.p;l(+b.l)if~-p else l([_ if~-(_ in b.l)])
k(int.)
def __neg__(a):a.p+=1;a
def l(x):a=k(sum(x)or 1);=x;a
def d(v,i):d=k(v);d.i=i;d
w=lambda a:eval(re.sub("(\d+)","(k(\\1))",a).translate({100:".j",116:"*",84:"@",114:"/",82:"%",46:"+--",95:"+-"}))'''.translate({2:" for _ in ",3:"a.l",4:"lambda a,b:",5:"return ",6:"__add__(a,b)"}))
```
[Try it online!](https://tio.run/##bVLbjtowEJVI2Yd8hWupYrwYLwGKto4s9RuqvgGynLXZzeJA5ARIVW1/nY65rFZqXzz2nHNmztiuf7Uvu@30dHKde4IwGAzWYVeRYLYWQ1nVu9Dep5dIgkufvGkasoFy2zKZklqN81f1ycPCQtRgGjIe14IxXrAeJp8dGLZiudbV3msd2Q1WcxYStpDFBTHtf8BRIc9oG/bOlocL/E8nLUrsFddyTbRSBXG@cUSTXnJWN/siKjdQme4iEdckGLTIWEqsQ6Wudvaaw8lIpxYrDMeX0jvSfVaJ7FSSG2UeCkz3PXRX4V1kY@tC1LJWuObW@XjKkZQMC@HR2J9RfbGFA@heQmIGNCm3JOIrFkueb1XcvfvZuufoh0kj6qHK8r5JIxA7S6M20Owr3O4CyVieqO6GWzjwkkmLjAPLrShVmfdtelTeVIU1xEh3MB6CE3gJQGFph4xyChtYLjOGW8NEi1fceNM6@J2Nx5KKV8qzbC7pPeWPM0m/xyPGBzxOJP1C@QzB4WhE@bevcUPfGMPP9LEQ8sga3Z6npnwqqREehZLejPFCUo7y4Np9iBysqbWxt2eJRU91iI9@BJpZgEc7GbeznxNmYW7nP7IwZ6OJnQ0zO2ECkDGzcz21UxwLpX8B "Python 3 – Try It Online")
Contains a lot of unprintables, see the TIO link for the full code
-5 bytes thanks to Mr.Xcoder
-5 more bytes thanks to NGN
-about 40 bytes thanks to Jonathan French
Yuck, what a kludge!
This works by using a regular expression to wrap all numbers in my `k` class, and converting all of the operators into operators python understands, then using the magic methods of the `k` class to handle the math. The `+-` and `+--` at the end for `.` and `_` are a hack to keep the precedence correct. Likewise, I can't use the `**` operator for d because doing so would make `1d4d4` be parsed as `1d(4d4)`. Instead, I wrap all numbers in an extra set of parens and do d as `.j`, since method calls have higher precedence that operators. The last line evaluates as an anonymous function that evaluates the expression.
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 367 bytes
```
d←{(⊢⍪⍨1+?)⍉⍪⊃⍴/⊃¨+/¨⍺⍵}⋄r←{z←⊣⌿⍺⋄((m×?n)+z×~m←z∊⊣⌿⍵)⍪n←⊢⌿⍺}⋄R←{⍬≡⊃∩/⊣⌿¨⍺⍵:⍺⋄⍵∇⍨⍺r⍵}
u←{⍺[;((⊃+/⍵)⌊≢⍉⍺)↑⍺⍺⊣⌿⍺]}⋄t←⍋u⋄T←⍒u⋄A←+/,⋄S←+/,∘-⋄C←,⋄D←{⍺/⍨~⊃∊/⊣⌿¨⍺⍵}
h←v←⍬⋄o←'drRtT+-._'⋄f←{8<i←o⍳⊃⍵:0⋄v⊢←(¯2↓v),(⍎i⊃'drRtTASCD')/¯2↑v}
{⊃⍵∊⎕d:v,←⊂⍪2↑⍎⍵⋄'('=⍵:h,←⍵⋄')'=⍵:h↑⍨←i-1⊣f¨⌽h↓⍨i←+/∨\⌽h='('⋄h,←⍵⊣h↓⍨←-i⊣f¨⌽h↑⍨-i←+/∧\⌽≤/(1 4 4 1/⌽⍳4)[o⍳↑⍵,¨h]}¨'\d+' '.'⎕s'&'⊢⍞
f¨⌽h⋄1⌈+/⊣⌿⊃v
```
[Try it online!](https://tio.run/##XVLfS9tQFH7PX@HT7r2kaZoYinQTEcU/oPZNRYoX10C1o62BVerDLF2a9BadiHsarA6WibAH15fCGMT/5Pwj3Tk3qYwRSM6P7/vOdw6pv2ta8n292XprHTXrnY5/tIDJrd@C4VXJgPDjzkJieM4hmoJ6AJU45oYANaIkugT1y8ZPmph2moCag5r1IR60idLDF0T3MP5DjXjA@cnz3capMHvPdxcn2OxBGC0BM9R8ONWMacYgnSrpgHqE0VcaFv6wM/xyViVTxgidojdM22TBOMuI873XHJ1fmraeMI5gNNXe5wKG11pj/mLxgCZ2yYKKzzCs6fAThZsYmnYBo908Cj9bmG1hRtXtfByOSS600@g/p32jgZhASz4ig@7LZLvarZlW8ZBh5Zg01t74@GmBetLHnVVK2AnoJsMrnv50YXgTiAIHNfERkAls7m5tM2Hr7nXQN84zKh13cisrQUFf9QPe19VLT6gZDxhn6zShoftZSeQljUuw7lsO7nGMW4x/Y/UGq76@AITJPtXWUQaZLyLRfQ7D3PL/5ZKitSR/JzKMvtncWfHwcWzK1ZMn9vTyhJ4V0qRx0E8Tti9NtsKKDPfpsFdM/4pfjKVyPHBgHJr5wXH5YIF/g7GzcCTna9Itdb2aKyQvy3LVaZeF5UrPdKQrihwRniwfrspVIf4C "APL (Dyalog Classic) – Try It Online")
This is the shunting yard algorithm from the reference implementation merged with `evaluate_dice()`, without the cruft and object-oriented nonsense. Only two stacks are used: `h` for the operators and `v` for the values. Parsing and evaluation are interleaved.
Intermediate results are represented as 2×N matrices where the first row are the random values and the second row are the number of sides on the dice that produced them. When a result is not produced by the dice-throwing "d" operator, the second row contains arbitrary numbers. A single random value is a 2×1 matrix and thus indistinguishable from a 1-element list.
[Answer]
## Python 3: 723 722 714 711 707 675 653 665 bytes
```
import re
from random import*
S=re.subn
e=eval
r=randint
s=lambda a:sum(g(e(a)))or 1
g=lambda a:next(zip(*a))
def o(m):a,o,b=m.groups();A=sorted(e(a));t=g(e(b));return str(o in"rR"and([([v,(r(1,d)*(o>"R")or choice([n+1for n in range(d)if~-(n+1in t)]))][v in t],d)for(v,d)in A])or{"t":A[:s(b)],"T":A[-s(b):],"+":[(s(a)+s(b),0)],"-":[(s(a)-s(b),0)],".":e(a)+e(b),"_":[t for t in e(a)if~-(t[0]in g(e(b)))]}[o])
def d(m):a,b=map(s,m.groups());return str([(r(1,b),b)for _ in" "*a])
p=r"(\[[^]]+\])"
def E(D):
D,n=S(r"(\d+)",r"[(\1,0)]",D)
while n:
n=0
for e in[("\(("+p+")\)",r"\1"),(p+"d"+p,d),(p+"([tTrR])"+p,o),(p+"(.)"+p,o)]:
if n<1:D,n=S(*e,D)
return s(D)
```
The entry point is `E`. This applies regular expressions iteratively. First it replaces all integers `x` with a singleton list tuple `[(x,0)]`. Then the first regular expression performs the `d` operation, by replacing all `[(x,0)]d[(b,0)]` with the string representation of an array of tuples like `[(1,b),(2,b),(3,b)]`. The second element of each tuple is the second operand to `d`. Then, subsequent regular expressions perform each of the other operators. There is a special regex to remove parens from fully calculated expressions.
[Answer]
Python 3, 695 bytes
```
import random,tatsu
A=lambda x:sum(x)or 1
H=lambda x:[[d,D(d.s)][d in x[2]]for d in x[0]]
R=lambda x:R([H(x)]+x[1:])if{*x[0]}&{*x[2]}else x[0]
class D(int):
def __new__(cls,s):o=super().__new__(cls,random.randint(1,s));o.s = s;return o
class S:
o=lambda s,x:{'+':[A(x[0])+A(x[2])],'-':[A(x[0])-A(x[2])],'.':x[0]+x[2],'_':[d for d in x[0]if d not in x[2]]}[x[1]]
f=lambda s,x:{'r':H(x),'R':R(x),'t':sorted(x[0])[:A(x[2])],'T':sorted(x[0])[-A(x[2]):]}[x[1]]
d=lambda s,x:[D(A(x[2]))for _ in' '*A(x[0])]
n=lambda s,x:[int(x)]
l=lambda s,x:sum(x,[])
lambda i:tatsu.parse("s=e$;e=o|t;o=e/[-+._]/t;t=f|r;f=t/[rRtT]/r;r=d|a;d=r/d/a;a=n|l|p;n=/\d+/;l='['@:','.{n}']';p='('@:e')';",i,semantics=S())
```
An interpreter built using `tatsu`, a PEG parser library. The first argument to `tatsu.parser()` is the PEG grammar.
`class D` (for Die) subclasses the built in `int` type. It's value is the result of a roll. The attribute `.s` is the number of sides on the die.
`class S` has the semantic actions for the parser, and implements the interpreter.
[Answer]
## Clojure, ~~731~~ 720 bytes
(when newlines are removed)
Update: a shorter implementation of `F`.
```
(defn N[i](if(seq? i)(apply + i)i))
(defn g[i](let[L(fn[i](let[v(g i)](if(seq? v)v(list v))))R remove T take](if(seq? i)(let[[o a b :as A]i](if(some symbol? A)(case o d(repeatedly(N(g a))(fn[](inc(rand-int(N(g b))))))t(T(N(g b))(sort(g a)))T(T(N(g b))(sort-by -(g a)))r(for[i(L a)](if((set(L b))i)(nth(L a)0)i))R(T(count(L a))(R(set(L b))(for[_(range)i(L a)]i)))+(+(N(g a))(N(g b)))-(-(N(g a))(N(g b))).(into(L a)(L b))_(R(set(L b))(g a)))A))i)))
(defn F[T](if(seq? T)(if(next T)(loop[[s & S]'[_ . - + R r T t d]](let[R reverse[b a](map R(split-with(comp not #{s})(R T)))a(butlast a)](if a(cons s(map F[a b]))(recur S))))(F(first T)))T))
(defn f[i](N(g(F(read-string(clojure.string/replace(str"("i")")#"[^0-9]"" $0 "))))))
```
This consists of four main parts:
* `N`: coerces a list into a number
* `g`: evaluates an abstract syntax tree (S-expressions with 3 items)
* `F`: converts an infix AST to prefix notation (S-expressions), also applies operand order precedence
* `f`: uses `read-string` to convert a string into a nested sequence of numbers and symbols (infix AST), pipes them through F -> g -> N, returning the result number.
I'm not sure how to thoroughly test this, maybe via statistical tests against a reference implementation? At least the AST and its evaluation is relatively easy to follow.
Example S-expression from `1d((8d20t4T2)d(6d6R1r6)-2d4+1d2).(1d(4d6_3d3))`:
```
(. (d 1 (- (d (T (t (d 8 20) 4) 2)
(R (d 6 6) (r 1 6)))
(+ (d 2 4)
(d 1 2))))
(d 1 (_ (d 4 6) (d 3 3))))
```
Less golfed with internediate results and tests:
```
(def f #(read-string(clojure.string/replace(str"("%")")#"[^0-9]"" $0 ")))
(defn F [T]
(println {:T T})
(cond
(not(seq? T))T
(symbol?(first T))T
(=(count T)1)(F(first T))
1(loop [[s & S] '[_ . - + R r T t d]]
(let[[b a](map reverse(split-with(comp not #{s})(reverse T)))
_ (println [s a b])
a(butlast a)]
(cond
a(do(println {:s s :a a :b b})(cons s(map F[a b])))
S(recur S))))))
(->> "3d6" f F)
(->> "3d6t2" f F)
(->> "3d2R1" f F)
(->> "1d4d4" f F)
(->> "2d6.2d6" f F)
(->> "(3d2R1)d2" f F)
(->> "1d((8d20t4T2)d(6d6R1r6)-2d4+1d2).(1d(4d6_3d3))" f F)
(defn N[i](if(seq? i)(apply + i)i))
(defn g[i]
(let[L(fn[i](let[v(g i)](if(seq? v)v(list v))))]
(if(seq? i)
(let[[o a b :as A] i]
(println {:o o :a a :b b :all A})
(if(every? number? A)(do(println{:A A})A)
(case o
d (repeatedly(N (g a))(fn[](inc(rand-int(N (g b))))))
t (take(N (g b))(sort(g a)))
T (take(N (g b))(sort-by -(g a)))
r (for[i(L a)](if((set(L b))i)(nth(L a)0)i))
R (take(count(g a))(remove(set(L b))(for[_(range)i(g a)]i)))
+ (+(N (g a))(N (g b)))
- (-(N (g a))(N (g b)))
. (into(L a)(L b))
_ (remove(set(L b))(g a)))))
(do(println {:i i})i))))
(g '(. (d 3 5) (d 4 3)))
(g '(. 1 (2 3)))
(g '(+ 1 (2 3)))
(g '(R (d 10 5) (d 1 3)))
(g '(T (d 5 20) 3))
(g '(t (d 5 20) 3))
(g '(d (d 3 4) 10))
(g '(d 4 3))
(g '(_ (d 4 6) (d 3 3)))
(->> "1d(4d6_3d3)" f F g)
(->> "1r6" f F g)
(->> "(8d20t4T2)d(6d6R1r6)" f F g)
(->> "(8d20t4T2)d(6d6R1r6)-2d4+1d2).(1d(4d6_3d3)" f F g)
(->> "1d((8d20t4T2)d(6d6R1r6)-2d4+1d2).(1d(4d6_3d3))" f F g))
```
] |
[Question]
[
Stolen from @Downgoat with permission
The point of this challenge is to (not) settle the debate on the pronunciation of "gif".
[](https://i.stack.imgur.com/j8SIr.gif)"
---
The pronunciation of *gif* is debated and while it's supposed to be (and should be) pronounced *jif*, it's still commonly disputed.
In this challenge you will be given a set of words that have a *g* or *j*, representing the sound that the word is pronounced with. You'll also get some text in which you have to fix the incorrect spellings of *gif*.
Because this is the internet and everyone always wrong. It's (not) common courtesy to correct them.
An example of a wrong pronunciation would be:
```
There was a **gif** of a mouse eating a burrito
```
The wrong spelling of *gif*? Unacceptable! This must be corrected immediately:
```
There was a **jif (as in jar)** of a mouse eating a burrito
```
---
Are we done? Nope, you're *still* wrong.
You're *always* wrong
This must work the other way:
```
In the **jif** the cat wore a hat of a cat
```
This obvious misspelling must be fixed, we shall correct this to:
```
In the **gif (as in graphic)** the cat wore a hat of a cat
```
---
### Rules
* Input is a string (the sentence) and an array of strings (or any reasonable alternative, such as a comma separated string) in any order
* You may take the `g` and `j` words in any order. They may be taken separately.
* Every instance of `gif` (any case) in the sentence must be replaced with `jif (as in ___)` where `___` is a uniformly random selected word beginning with `j` from the array of strings, and vice versa for `jif` with words beginning with `g`.
* ONLY the words `gif` and `jif` should be replaced (i.e "jiffy" should not be changed). Those words have done no wrong.
* You are guaranteed that at least one word in the array begins with `g` and at least one begins with `j`.
* Case must be preserved (e.g. `GiF` -> `JiF`).
* You may write a program or a function
* Standard loopholes apply
* We need to (not) settle the debate quickly; shortest code in bytes wins
---
### Examples
Input and output separated by a single line:
```
graphic, jar, jam, gram
I saw a jif of how to pronounce gif that showed gif is pronounced jif
I saw a gif (as in graphic) of how to pronounce jif (as in jar) that showed jif (as in jam) is pronounced gif (as in gram)
gravy, jeff
G is for gIf, h is for JiF, i is for gIF, j is for JIf
G is for jIf (as in jeff), h is for GiF (as in gravy), i is for jIF (as in jeff), j is for JIf (as in gravy)
joke, june, gorilla, great
Jiffy should not be treated as a GIF or JIF, like gifted.
Jiffy should not be treated as a JIF (as in june) or GIF (as in great), like gifted.
```
[Answer]
## Mathematica, 164 165 bytes
This is an abomination, but I want someone to share my pain.
```
StringReplace[f[f@"g"="j"]="g";f[f@"G"="J"]="G";z=IgnoreCase->1>0;#,x:"g"|"j"~~y:"if ":>{f@x,y,"(as in ",RandomChoice@StringCases[#2,f@x~~Except[","]..,z]}<>") ",z]&
```
`Function` which expects the first argument `#` to be the sentence to be (in)corrected and the second argument `#2` to a be comma separated string of words.
`f[f@"g"="j"]="g";f[f@"G"="J"]="G"` defines a function `f` which takes the letters `g`, `G`, `j`, and `J` to their appropriate replacements. This is ever so slightly shorter than `f@"g"="j";f@"j"="g";f@"G"="J";f@"J"="G"`.
I also set `z` equal to `IgnoreCase->True` since I'll be using it twice.
`x:"g"|"j"~~y:"if "` is a `StringExpression` which matches `"gif "` or `"jif "`, naming the first letter `x` and the last three characters `y`. Since the option `z` (also known as `IgnoreCase->True`) is passed to `StringReplace`, these letters can be in any combination of upper and lower case.
I then replace every such match with
```
{f@x,y,"(as in ",RandomChoice@StringCases[#2,f@x~~Except[","]..,z]}<>") "
```
`RandomChoice@StringCases[#2,f@x~~Except[","]..,z]` randomly selects a word out of the second argument `#2` which begins with `f[x]`, again ignoring case because the option `z` is given.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~88~~ ~~87~~ 91 bytes
-1 byte from ETHproductions. +4 bytes because words containing "gif" or "jif" shouldn't be replaced. -2 bytes because replacement word lists can be taken separately now.
```
->s,g,j{s.gsub(/\b(g|j)if\b/i){$&.tr("GgJj","JjGg")+" (as in #{($1[/g/i]?j:g).sample})"}}
```
[Try it online!](https://tio.run/##TY7LasMwEEX3@YrBDcWmiky3hbbQRU38C3EWsiuNR5EfWBLBuPnsrt0xpbSbM/feeTBTrOfVPFfr4cULFHbxEn2s07yqU/y0GZmqzilb9vcyTGlSYGkTkZS2wCR7SCBVHqiHuyXdP55yzOn8ap8wk151o9O3LLnd1jEGD@aEOngBG6UfHYX/@rwWQDw0TIBHI6D9dSW9C6C/HjsLZH56RyPhTcOVQgvzELdHFFgyZpY7nNTYUgNcO4ZWAXDoNaDqNnhAMhxFcmFmTz0nurkMO6smsLxjVXPhY86xqsHyrmduastjz1AfGqy@avfVD4dGNa3@Bg "Ruby – Try It Online")
[Answer]
# [CJam](https://sourceforge.net/p/cjam/wiki/), 78 bytes
```
l',%:A;lS%{_ela"gifjif"3/&{_V=_el:B'g=1W?Z*+V\t" (as in "A{V=elB=!},mR')}O?S}%
```
[Try it online!](http://cjam.aditsu.net/#code=l'%2C%25%3AA%3BlS%25%7B_ela%22gifjif%223%2F%26%7B_V%3D_el%3AB'g%3D1W%3FZ*%2BV%5Ct%22%20%28as%20in%20%22A%7BV%3DelB%3D!%7D%2CmR'%29%7DO%3FS%7D%25&input=graphic%2Cjar%2CJaM%2Cgram%0AI%20saw%20a%20JiF%20of%20how%20to%20pronounce%20gif%20that%20showed%20giF%20is%20pronounced%20jIf)
Requires the list of replacement characters to be separated by nothing but commas.
---
Explanation:
```
l',% e# read line of input and split at commas
:A; e# store in var A and pop off the stack
lS%{...}% e# for each word in the next line of input so:
_ela"gifjif"3/& e# intersection of ["gif" "jif"] and [lowercase(word)]
{...}O? e# if set it non-empty, run block below, otherwise do nothing (push empty string)
S e# push space
_V= e# extract first char
_el:B e# duplicate to lowercase and store in var B
'g=1W?Z*+ e# convert g/G <=> j/J
V\t e# store back to word
" (as in " e# push string
A{V=elB=!}, e# filter replacements by words starting with the same char (case insensitive)
mR e# select random element
') e# push ')' char
```
[Answer]
# [Python 3](https://docs.python.org/3/), 237 bytes
```
lambda s,g,j:' '.join([(w if False in(w[0]in q,w[1:2]in['i','I'],w[2:3]in['f','F'],w[3:]in",;!?.")else q[w[0]]+w[1:3]+" (as in "+choice(g if w[0]in 'jJ'else j)+')'+w[3:])for w in s.split()])
from random import*
q=dict(zip("gGjJ","jJgG"))
```
[Try it online!](https://tio.run/##LY3LboMwEEX3@YrJbGwXC7VhRxR1Bwq/4LKgEJuxEsyrQvTn6YC6mpkzuuf269yGLtns7Wt7Vq/vpoJJO@1TASL2gTpp5AJkIaue0wP4Xsx7SR0MejEf6YVXI0hocRclk0uaHMQyyQ6SpAxQX8@fMarH7hjMriijPZ@UEYKsJhYDRnUbqH5It/f91whfiCPlVSSUiA6hsmGEZc9M8dQ/aZaqVCc7hheMVdfwoFcfxvntNNwaqmf5S71El/sCNfrC5ajU1o/UzdIypwwKbszJZuDvNlvBgQZHVoMne0YNBt1Y9S3VnHdtmGYstUF@2pW/6H92ws4/ "Python 3 – Try It Online")
This is the best I can do -- might be some way to do it quicker (probably with regexes) but my brain hurts now.
Explanation:
`q` is a simple dictionary mapping, I hope that's clear.
`s,g,j` are the input string, the list of g-words, and the list of j-words.
`' '.join` joins together the list comprehension done across `for w in s.split()` is therefore for the list of words in s.
The middle bit is black magic, which I'll break down piecewise. First, the condition: `False in(w[0]in q,w[1:2]in['i','I'],w[2:3]in['f','F'],w[3:]in",;!.")`.
`w[0]in q` checks the first character is in the keys of `q` which are `'g','G','j','J'`. The reason for separating out `q` as a variable is we also use it as a dict/map later.
`w[1:2]in ['i','I']` checks that the second character is either i or I. The :2 is necessary because just putting `w[1]` would result in a crash on 1-letter words, but slices don't do that for some reason (I thought they did, whatever!)
`w[2:3]in ['f','F']` is analogous. I briefly had this as just 2: before I realized I needed to account for gif, or jif, followed by punctuation!
`w[3:]in",;!?."` checks that the subsequent character(s) are punctuation. I admit my code doesn't work if someone puts 'gif?!' but I can't be perfect. Someone else can take up the challenge of opening quotes before gif or jif, too.
`False in(,,,)` is basically a big NAND. It's actually the same bytecount as separating four items with `and` and swapping the arguments, but this looks cooler and works better if you have to extend it to a fifth `and`ed thing.
`w if` means that if False is in the conditional-list, we just return the word unchanged -- it doesn't meet our criteria. `else`, we change it to:
`q[w[0]]+w[1:3]+" (as in "+choice(g if w[0]in 'jJ'else j)+')'+w[3:]`
OK. `q[w[0]]` substitutes the first letter correctly. `w[1:3]` tacks on the i or I and f or F, `w[3:]` tacks on any trailing punctuation. That leaves the as in clause.
`" (as in "+choice(g if w[0]in 'jJ'else j)+')'` puts in the obvious string literal at the start and the trailing parenthesis, the interesting bit here is `choice(g if w[0]in 'jJ'else j)` which randomly chooses from `g` or `j`, depending on if `w[0]` is in `'jJ'`. and I just realized I had this bit backwards so fixing that throughout, done.
It's been a long day. `choice` is in the `random` module hence the import. I think that's everything.
[Answer]
## JavaScript (ES6), 142 bytes
```
(s,g,j,r=l=>l[Math.random()*l.length|0])=>s.replace(/\b[gj]if\b/gi,w=>`GJgj`[l=`JGjg`.search(w[0])]+w.slice(1)+` (as in ${r([g,j,g,j][l])})`)
```
Takes separate `g` and `j` word lists.
[Answer]
# Javascript(ES6), 151 bytes
```
f=(s,g,j)=>s.replace(/\b(g|j)(if)\b/ig,(m,p,c)=>`${a=g,p=="j"?"g":p=="J"?"G":(a=j,p=="g"?"j":"J")}${c}(as in ${a[Math.floor(Math.random()*a.length)]})`)
```
I probably can golf down the ternary part more, but I can't think of how right now. Also, it takes the g and j words separately.
] |
[Question]
[
For those of you who are unfamiliar, [Kirkman's Schoolgirl Problem](http://mathworld.wolfram.com/KirkmansSchoolgirlProblem.html) goes as follows:
>
> Fifteen young ladies in a school walk out three abreast for seven days in succession: it is required to arrange them daily so that no two shall walk twice abreast.
>
>
>
We could look at this like a nested *3* by *5* list (or matrix):
```
[[a,b,c]
[d,e,f]
[g,h,i]
[j,k,l]
[m,n,o]]
```
Essentially, the goal of the original problem is to figure out 7 different ways to arrange the above matrix so that two letters *never share a row more than once*. From MathWorld (linked above), we find this solution:
```
[[a,b,c] [[a,d,h] [[a,e,m] [[a,f,i] [[a,g,l] [[a,j,n] [[a,k,o]
[d,e,f] [b,e,k] [b,h,n] [b,l,o] [b,d,j] [b,i,m] [b,f,g]
[g,h,i] [c,i,o] [c,g,k] [c,h,j] [c,f,m] [c,e,l] [c,d,n]
[j,k,l] [f,l,n] [d,i,l] [d,k,m] [e,h,o] [d,o,g] [e,i,j]
[m,n,o]] [g,j,m]] [f,j,o]] [e,g,n]] [i,k,n]] [f,h,k]] [h,l,m]]
```
Now, what if there were a different number of schoolgirls? Could there be an eighth day?† This is our challenge.
†In this case no††, but not necessarily for other array dimensions
††We can easily show this, since `a` appears in a row with every other letter.
---
## The Challenge:
Given an input of dimensions (rows, than columns) of an array of schoolgirls (i.e. `3 x 5`, `4 x 4`, or `[7,6]`, `[10,10]`, etc.), output the largest possible set of 'days' that fit the requirements specified above.
**Input:**
The dimensions for the schoolgirl array (any reasonable input form you wish).
**Output:**
The largest possible series of arrays fitting the above requirements (any reasonable form).
**Test Cases:**
```
Input: [1,1]
Output: [[a]]
Input: [1,2]
Output: [[a,b]]
Input:* [2,1]
Output: [[a]
[b]]
Input: [2,2]
Output: [[a,b] [[a,c] [[a,d]
[c,d]] [b,d]] [b,c]]
Input: [3,3]
Output: [[a,b,c] [[a,d,g] [[a,e,i] [[a,f,h]
[d,e,f] [b,e,h] [b,f,g] [b,d,i]
[g,h,i]] [c,f,i]] [c,d,h]] [c,e,g]]
Input: [5,3]
Output: [[a,b,c] [[a,d,h] [[a,e,m] [[a,f,i] [[a,g,l] [[a,j,n] [[a,k,o]
[d,e,f] [b,e,k] [b,h,n] [b,l,o] [b,d,j] [b,i,m] [b,f,g]
[g,h,i] [c,i,o] [c,g,k] [c,h,j] [c,f,m] [c,e,l] [c,d,n]
[j,k,l] [f,l,n] [d,i,l] [d,k,m] [e,h,o] [d,o,g] [e,i,j]
[m,n,o]] [g,j,m]] [f,j,o]] [e,g,n]] [i,k,n]] [f,h,k]] [h,l,m]]
There may be more than one correct answer.
```
\*Thanks to [@Frozenfrank](https://codegolf.stackexchange.com/users/68782/frozenfrank) for correcting test case **3**: if there is only one column, there can only be one day, since row order does not matter.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") competition - shortest answer wins.
[Answer]
# Mathematica, 935 bytes
```
Inp={5,4};L=Length;T=Table;ST[t_,k_,n_]:=Binomial[n-1,t-1]/Binomial[k-1,t-1];H=ToExpression@Alphabet[];Lo=Inp[[1]]*Inp[[2]];H=H[[;;Lo]];Final={};ST[2,3,12]=4;ST[2,4,20]=5;If[Inp[[2]]==1,Column[Partition[H,{1}]],CA=Lo*Floor@ST[2,Inp[[2]],Lo];While[L@Flatten@Final!=CA,Final={};uu=0;S=Normal[Association[T[ToRules[H[[Z]]==Prime[Z]],{Z,L@H}]]];PA=Union[Sort/@Permutations[H,{Inp[[2]]}]];PT=Partition[H,Inp[[2]]];While[L@PA!=0,AppendTo[Final,PT];Test=Flatten@T[Times@@@Subsets[PT[[X]],{2}]/.S,{X, L@PT}];POK=T[Times@@@Subsets[PA[[Y]],{2}]/.S,{Y,L@PA}];Fin=Select[POK,L@Intersection[Test,#]==0&];Facfin=T[FactorInteger[Fin[[V]]],{V,L@Fin}];end=T[Union@Flatten@T[First/@#[[W]],{W,L@#}]&[Facfin[[F]]],{F,L@Facfin}]/.Map[Reverse,S];PA=end;PT=DeleteDuplicates[RandomSample@end,Intersection@##=!={}&];If[L@Flatten@PT<L@H,While[uu<1000,PT=DeleteDuplicates[RandomSample@end,Intersection@##=!={}&];If[L@Flatten@PT==L@H,Break[],uu++]]]]];Grid@Final]
```
this is for ***26 ladies max***
**EDIT**
I made some changes and I think it works!
The code right now is set to solve [5,4] (which is the "social golfers problem") and gets the result in a few seconds.
However [5,3] problem is tougher and you will have to **wait** 10-20 minutes but you **will get** a right combination for all days.
For easier cases it is very quick.
anyway you can try it and see the results
[**Try it online here**](https://sandbox.open.wolframcloud.com/app/objects/)
copy and paste using ctrl-v
press shift+enter to run the code
you can change the input at the begining of the code -> Inp={5,4}
run the code multiple times to get different permutations
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes
```
׌!s€ɗœcⱮ×ẎẎṢ€QƑƊƇṪ
```
[Try it online!](https://tio.run/##y0rNyan8///w9KOTFIsfNa05Of3o5ORHG9cdnv5wVx8I7VwEFA08NvFY17H2hztX/T@8PMobKAJEWSCqYY4CEDxqmBvJdXi5Pli0cd@hbYe2/f8fHW2oo2AYq6MAoo2gtDGUNgHRRlB5I6i8MZRvAqJjAQ "Jelly – Try It Online")
The Footer simply formats the input and output and demonstrates for various inputs. Assumes that it's ok to return any valid configuration, rather than the one stated in the question.
This is a brute force approach and isn't efficient by any meaning of the word. If we call the dimensions \$n\$ and \$m\$ (\$n\$ being height), this generates
$$f(n, m) = \sum^{nm}\_{i=1} \binom {(nm)!} {i}$$
lists to check. For example, for \$n = 3, m = 5\$, we generate
$$42755752626996476442177192901690329126386272975917980316235035492211700060653916251199050827754168292191219682093923414635027126605138973495697914193291687743693535776000$$
lists to check. Unsurprisingly, this times out on TIO for basically all inputs. Those for which it doesn't time out are shown in the TIO link.
## How it works
```
׌!s€ɗœcⱮ×ẎẎṢ€QƑƊƇṪ - Main link. Takes n on the left and m on the right
ɗ - Group the previous 3 links into a dyad f(n, m):
× - Yield n×m
Œ! - Promote n×m into a range [1, 2, ..., n×m] and yield
all permutations of that range
€ - Over each permutation:
s - Split it into an n×m matrix
× - Yield n×m
Ɱ - For each integer 1 ≤ i ≤ n×m:
œc - Yield all combinations (without replacement) of the
permutations of length i
Ẏ - Tighten these into a single list of lists of matrices
ƊƇ - Keep those for which the following is true:
QƑ - The matrix has no duplicates when:
Ẏ - Tightened into a list of lists
Ṣ€ - And each list is sorted
Ṫ - Get the last (i.e. the longest) such list
```
] |
[Question]
[
This is a potato:
```
@@
@@@@
@@@@@@
@@@@@@
@@@@
@@
```
More generally, a size N potato is defined as the following shape:
If N is even, it is 2 centered `@` symbols, followed by 4 centered `@` symbols, followed by 6 centered `@` symbols, all the way up to N centered `@` symbols; then, N centered `@` symbols, followed by N-2 centered `@` symbols, all the way down to 2.
If N is odd, a size N potato is generated in the same way as described above, but we begin with 1 `@` symbol, rather than 2.
A potato is peeled by starting in the top right corner, and removing one `@` sign each step, going in a counterclockwise fashion. For instance, peeling a size-3 potato looks like this:
```
@
@@@
@@@
@
```
---
```
@@@
@@@
@
```
---
```
@@
@@@
@
```
---
```
@@
@@
@
```
---
```
@@
@@
```
---
```
@@
@
```
---
```
@
@
```
---
```
@
```
# Challenge
Write a program, that, given an integer input, displays all of the steps of peeling a potato of that size.
Trailing whitespace/newlines are allowed.
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); the shortest code in bytes wins.
## Sample Test Cases
***N=2***
```
@@
@@
@
@@
@@
@
```
***N=7***
```
@
@@@
@@@@@
@@@@@@@
@@@@@@@
@@@@@
@@@
@
@@@
@@@@@
@@@@@@@
@@@@@@@
@@@@@
@@@
@
@@
@@@@@
@@@@@@@
@@@@@@@
@@@@@
@@@
@
@@
@@@@
@@@@@@@
@@@@@@@
@@@@@
@@@
@
@@
@@@@
@@@@@@
@@@@@@@
@@@@@
@@@
@
@@
@@@@
@@@@@@
@@@@@@
@@@@@
@@@
@
@@
@@@@
@@@@@@
@@@@@@
@@@@
@@@
@
@@
@@@@
@@@@@@
@@@@@@
@@@@
@@
@
@@
@@@@
@@@@@@
@@@@@@
@@@@
@@
@@
@@@@
@@@@@@
@@@@@@
@@@@
@
@@
@@@@
@@@@@@
@@@@@@
@@@
@
@@
@@@@
@@@@@@
@@@@@
@@@
@
@@
@@@@
@@@@@
@@@@@
@@@
@
@@
@@@
@@@@@
@@@@@
@@@
@
@
@@@
@@@@@
@@@@@
@@@
@
@@@
@@@@@
@@@@@
@@@
@
@@
@@@@@
@@@@@
@@@
@
@@
@@@@
@@@@@
@@@
@
@@
@@@@
@@@@
@@@
@
@@
@@@@
@@@@
@@
@
@@
@@@@
@@@@
@@
@@
@@@@
@@@@
@
@@
@@@@
@@@
@
@@
@@@
@@@
@
@
@@@
@@@
@
@@@
@@@
@
@@
@@@
@
@@
@@
@
@@
@@
@@
@
@
@
@
```
## Catalog
Based on [Is this number a prime?](https://codegolf.stackexchange.com/questions/57617/)
```
<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 = 101224; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 12012; 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.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>
```
[Answer]
## Perl, 129 bytes
128 bytes of code + `-n` flag.
```
$p=($r=$"x$n++."@"x$_.$/).$p.$r,$_-=2while$_>0;say$_=$p;say y/A/ /r while s/(^| )A(.*
? *)@/$1 $2A/m||s/@( *
?.*)A/A$1 /||s/@/A/
```
You'll need `-nE` flags to run it :
```
perl -nE '$p=($r=$"x$n++."@"x$_.$/).$p.$r,$_-=2while$_>0;say$_=$p;say y/A/ /r while s/(^| )A(.*
? *)@/$1 $2A/m||s/@( *
?.*)A/A$1 /||s/@/A/' <<< 7
```
**Explanations:** (I'll detail them more when I have a moment)
The first part, `$p=($r=$"x$n++."@"x$_.$/).$p.$r,$_-=2while$_>0;`, generates the initial potato: it starts from the middle line of the potato, and adds two lines at each iteration: one before the previous string, one after. Note that `$"` is a space, and since `$n` isn't initialized, it starts at 0, and `$/` is a newline.
Note much to say about the `say$_=$p;` that prints the initial potato while storing it in `$_` (which will later be easier to manipulate).
Finally, `say y/A/ /r while s/(^| )A(.*\n? *)@/$1 $2A/m||s/@( *\n?.*)A/A$1 /||s/@/A/` peels the potato. The last position where a `@` was removed contains a `A` (it's arbitrary, it could have be any symbol). So each iteration consist in finding the `A`, replacing it with a space, and in the meantime replacing the next `@` with a `A`. That's done thanks to two regex: `s/(^| )A(.*\n? *)@/$1 $2A/m` when the `A` is on the left side of the potato (`A(.*\n? *)@` allows to go on the right or down), and `s/@( *\n?.*)A/A$1 /` when the `A` is on the right side (`@( *\n?.*)A` allows to go up or on the left). `s/@/A/` replaces the first `@` with a `A` (that's the initialization). Since we always have a `A` in the string, we need to replace it with a space when printing it, that's what `y/A/ /r` does.
---
**Just for the eyes**, the animated version looks fairly nice: (to run in a terminal, it's roughly the same code but with `clear` and `sleep`)
```
perl -nE 'system(clear);$p=($r=$"x$n++."@"x$_.$/).$p.$r,$_-=2while$_>0;say$_=$p;select($,,$,,$,,0.1),system(clear),say y/A/ /r while(s/(^| )A(.*\n? *)@/$1 $2A/m||s/@( *\n?.*)A/A$1 /||s/@/A/)&&/@/' <<< 10
```
[Answer]
## Befunge, ~~319~~ 254 bytes
```
&:00p1+:40p2/10p>:40g%20p:40g/30p\:10g30g`:!00g:2%!-30g-*\30g*+:20g1+v
+10g-::40g\-*2*30g+\-1+00g2%!+\00g2/1++20g-:::40g\-*2*+30g-\4*00g2*-v>
v+1\,-**2+92!-g02g00**84+1`\+*`g02g01\*!`g02g01+**!-g02\`g03:/2g00-4<
>:40g00g:2%+*`!#v_$1+:55+,00g::*1-2/+`#@_0
```
The motivation for this algorithm was to try and avoid branching as much as possible, since a single path of execution is generally easier to golf. The code is thus comprised of just two loops: the outer loop iterating over the frames of the peeling process, and the inner loop rendering the potato for each frame.
The rendering loop is essentially just outputting a sequence of characters, the character for each iteration being determined by a rather complicated formula that takes the frame number of the peeling process and the index of the output sequence and returns either an `@`, a space, or a newline, as required.
[Try it online!](http://befunge.tryitonline.net/#code=JjowMHAxKzo0MHAyLzEwcD46NDBnJTIwcDo0MGcvMzBwXDoxMGczMGdgOiEwMGc6MiUhLTMwZy0qXDMwZyorOjIwZzErdgorMTBnLTo6NDBnXC0qMiozMGcrXC0xKzAwZzIlIStcMDBnMi8xKysyMGctOjo6NDBnXC0qMiorMzBnLVw0KjAwZzIqLXY-CnYrMVwsLSoqMis5MiEtZzAyZzAwKio4NCsxYFwrKmBnMDJnMDFcKiFgZzAyZzAxKyoqIS1nMDJcYGcwMzovMmcwMC00PAo-OjQwZzAwZzoyJSsqYCEjdl8kMSs6NTUrLDAwZzo6KjEtMi8rYCNAXzA&input=Mw)
[Answer]
# Python 3.5.1, 520 bytes
```
n=int(input())L=lenR=rangeP=printdefg(a,b):f=list(a)ifb:foriinR(L(f)):iff[i]=="@":f[i]=""breakelse:foriinR(L(f)-1,-1,-1):iff[i]=="@":f[i]=""breakreturn"".join(f)l=[]s=(2-n%2n)*(((n-2n%2)/2)1)i=2-n%2whilei<=n:l.append("@"*i)i=2j=L(l)-1whilej>=0:l.append(l[j])j-=1y=[rforrinR(int((L(l)/2)-1),-1,-1)]forhinR(L(y)-1,-1,-1):y.append(y[h])defH(q):foreinR(L(l)):P((""*y[e])q[e])P("")H(l)k=0m=0whilek<s:fortinR(L(l)):if'@'inl[t]andm%2==0:l[t]=g(l[t],True)k=1H(l)if'@'inl[t]andm%2==1:l[t]=g(l[t],False)k=1p=l[:]p.reverse()H(p)m=1
```
# Explanation
Basic idea: Alternate between iterating down each line and removing leftmost character and iterating up each line removing rightmost character while there are still `@`s left.
```
n=int(input())
L=len
R=range
P=print
# g() returns a line in the potato with leftmost or rightmoxt '@' removed
def g(a,b):
f=list(a)
if b:
for i in R(L(f)):
if f[i]=="@":
f[i]=" "
break
else:
for i in R(L(f)-1,-1,-1):
if f[i]=="@":
f[i]=" "
break
return "".join(f)
l=[]
# s is the total number of '@'s for size n
s=(2-n%2+n)*(((n-2+n%2)/2)+1)
i=2-n%2
# store each line of potato in l
while i<=n:
l.append("@"*i)
i+=2
j=L(l)-1
while j>=0:
l.append(l[j])
j-=1
# this is used for spacing
y=[r for r in R(int((L(l)/2)-1),-1,-1)]
for h in R(L(y)-1,-1,-1):
y.append(y[h])
# print the potato
def H(q):
for e in R(L(l)):
P((" "*y[e])+q[e])
P("\n")
H(l)
k=0
m=0
# while there are still '@'s either
# go down the potato removing leftmost '@'
# go up the potato removing rightmost '@'
while k<s:
for t in R(L(l)):
if '@' in l[t] and m%2==0:
l[t]=g(l[t],True)
k+=1
H(l)
if '@' in l[t] and m%2==1:
l[t]=g(l[t],False)
k+=1
p=l[:]
p.reverse()
H(p)
m+=1
```
Overall a sad attempt at a straightforward procedure.
] |
[Question]
[
**Can't see emoji? Click [here](https://geokavel.github.io/emojis/emoji.html).**
You will simulate a vending machine. The items are 56 different emojis, which can be represented as two surrogate UTF-8 characters, from: üçÖ(U+D83C U+DF45) to üçº
(U+D83C U+DF7C). In HTML these emojis can be represented in UTF-16 form as **🍅** through **🍼**. In base 10 the first UTF-8 character has value **55356**. The value of the second character ranges from **57157** to **57212**. [Here](http://cjam.aditsu.net/#code=56%7B%5B57157%2B%2055356%5C%5D%3Ac%7D%2F) is a CJam program that generates all the relevant emojis. To avoid confusion, this challenge will be scored in **characters, not bytes**. Some emojis are 2 characters, some are 3. <http://www.lettercount.com> will give you an accurate count for this challenge.
## Pricing üíµüíµüíµ
There are 8 different price categories:
* $1.00 : üçÖüçÜüçáüçàüçâüçäüçã
* $1.50 : üçåüççüçéüçèüçêüçëüçí
* $2.00 : üçìüçîüçïüçñüçóüçòüçô
* $2.50 : üçöüçõüçúüçùüçûüçüüç†
* $3.00 : üç°üç¢üç£üç§üç•üç¶üçß
* $3.50 : üç®üç©üç™üç´üç¨üç≠üçÆ
* $4.00 : üçØüç∞üç±üç≤üç≥üç¥üçµ
* $4.50 : üç∂üç∑üç∏üçπüç∫üçªüçº
## Displaying the Vending Machine
This is what the user sees when the program starts and after making a purchase. You can use regular numbers instead of emoji numbers, but emoji numbers have the benefit of being the same width as other emojis. If you use emoji numbers you can subtract **14 characters** from your score, because emoji numbers are 3 characters each.
```
1️⃣2️⃣3️⃣4️⃣5️⃣6️⃣7️⃣
A üçÖüçÜüçáüçàüçâüçäüçã
B üçåüççüçéüçèüçêüçëüçí
C üçìüçîüçïüçñüçóüçòüçô
D üçöüçõüçúüçùüçûüçüüç†
E üç°üç¢üç£üç§üç•üç¶üçß
F üç®üç©üç™üç´üç¨üç≠üçÆ
G üçØüç∞üç±üç≤üç≥üç¥üçµ
H üç∂üç∑üç∏üçπüç∫üçªüçº
```
If the user enters `G5` that selects üç≥. Entering `E6` selects üç¶.
## Adding Cash üí∏üí∏üí∏
To add money, the user should input `/` and then the code for a coin or bill. The coins are (N)ickel ($0.05), (D)ime ($0.10), and (Q)uarter ($0.25). The bills are (O)ne ($1.00), (F)ive ($5.00), (T)en ($10.00). Every time the user adds a bill or coin, the program should output `Balance: [New Balance]`. Only one bill or coin can be added each time.Here is an example containing three lines of input:
```
/D
Balance: $0.10
/Q
Balance: $0.35
/F
Balance: $5.35
```
## Selecting Items
The user selects an item by entering the item code, like `B2` or `C3`. If the user has not added any money, the program should output `Item Cost: [Cost of Item]`. If the user has added money, but it is not enough to buy the item, the output should be `Insufficient Funds. Item Cost: [Cost of Item]`. If the user did add enough money, the program should output: `Item at [Item Location] Purchased. Remaining Balance: [Balance - Cost of Item]`. Then on its own line, print out the emoji of the purchased item. Then print out the entire vending machine (See "Displaying the Vending Machine") with the purchased item replaced with üö´(U+D83D U+DEAB) Base 10: (55357 57003).
## Ending the Program
If the user buys an item which brings his/her balance down to $0.00, the program should automatically terminate. Alternatively, if the user enters "Done" at any time, the program must give the user his/her remaining balance in change. Change must be in only Nickels, Dimes, and Quarters, and must be the smallest amount of coins possible. For example if the remaining balance is $1.45, the output should be `QQQQQDD`.
## Sample Run
(Input starts with "-")
```
1️⃣2️⃣3️⃣4️⃣5️⃣6️⃣7️⃣
A üçÖüçÜüçáüçàüçâüçäüçã
B üçåüççüçéüçèüçêüçëüçí
C üçìüçîüçïüçñüçóüçòüçô
D üçöüçõüçúüçùüçûüçüüç†
E üç°üç¢üç£üç§üç•üç¶üçß
F üç®üç©üç™üç´üç¨üç≠üçÆ
G üçØüç∞üç±üç≤üç≥üç¥üçµ
H üç∂üç∑üç∏üçπüç∫üçªüçº
-E1
Item Cost: $3.00
-/F
Balance: $5.00
-E1
Item at E1 Purchased. Remaining Balance: $2.00
üç°
1️⃣2️⃣3️⃣4️⃣5️⃣6️⃣7️⃣
A üçÖüçÜüçáüçàüçâüçäüçã
B üçåüççüçéüçèüçêüçëüçí
C üçìüçîüçïüçñüçóüçòüçô
D üçöüçõüçúüçùüçûüçüüç†
E üö´üç¢üç£üç§üç•üç¶üçß
F üç®üç©üç™üç´üç¨üç≠üçÆ
G üçØüç∞üç±üç≤üç≥üç¥üçµ
H üç∂üç∑üç∏üçπüç∫üçªüçº
-Done
QQQQQQQQ
```
## Invalid Codes
* If the input starts with `/` but is not a valid money input, output
`Money not Accepted`.
* If the input is an item that has already been purchased, output `Item out of stock`
* If the input is a digit-letter combination that is not in range (like `A0` or `J2`, output "Invalid code"
* For all other invalid input, output "Error"
## Bonus (-15%) : Jam
When vending an item, there is a 10% chance the machine will jam, and the item gets stuck. Output `JAM!!!` one time. In this case the user must input "punch" or "kick". Each time the user does so, there is a 20% chance that the item will break free, and vend as normal. Until the jam clears, the only inputs recognized are "punch" and "kick". All other inputs do nothing.
Here is a sample:
```
-A4
Item at A4 purchased. Remaining Balance: $1.00
JAM!!!
-punch
-kick
-kick
-punch
-punch
üçö
```
(The jam has been cleared. Resume as normal.)
## Bonus (-10%) : ID
If the user tries to buy an alcoholic beverage (any item on the last row except the baby bottle), you must demand proof of age. To do so, you ask the user to multiply two random numbers between 13 and 19 (inclusive). Output `ID required: [13-19]x[13-19] = ?`. If the user answers correctly, the purchase can go through. If not, print üîû(U+D83D U+DD1E) base 10: (55357 56606)
## Alternative Challenge : Minecraft
This challenge seems like something possible in Minecraft. To successfully create a Minecraft version of this program, the player must
* Have an 8x7 grid to select from 56 unique items
* Be able to add money to the balance (Maybe use different types of stones for the different denominations described above.)
* Give the user the item he/she selects if they have put in enough "money"
* Return the user the appropriate amount of change at the end.
## Compatibility Mode
* ### I can only take input at the beginning of the program
+ Not to worry, you can make a program that takes all input up front. If your program has not terminated after evaluating all input, assume that "Done" is called at the end. If you do this method, you will not be eligible for any bonuses.
* ### I can't view/output emojis
+ You can copy and paste your input and output into this Stack Snippet (or [here](https://geokavel.github.io/emojis/evaluate.html)). It can understand both unicode emojis and HTML codes for emojis. If your output looks correct on this page, your program passes. Try pasting in some of the sample input/output to see how it looks.
```
function parse() {
var o = document.getElementById("output");
var text = document.getElementById("in").value;
o.innerHTML = text.replace(/\n/g,"<br/>").replace(/ /g," ");
twemoji.parse(o);
}
```
```
<head>
<script src="//twemoji.maxcdn.com/twemoji.min.js"></script>
</head>
<body>
<h1>Emoji to Image</h1>
<textarea id="in" rows="10" cols="50"></textarea>
<input type="submit" onclick="parse()">
<div id="output"></div>
</body>
```
Here is an abbreviated compatibility-mode version of the vending machine display that you can test in the Stack Snippet:
```
1⃣2⃣3⃣4⃣5⃣...
A🍅🍆🍇🍈🍉...
B
...
```
* ### I can output emojis, but not to STDOUT.
+ Seemingly, the Mac OS X Terminal is the only one known to be able to output emojis. If you are not able to output emojis in your terminal, your other options are
- Send all output to a file.
- Display all output in a window.
- Use the technique described in "I can't view/output emojis".
[Answer]
# PHP, (1295 - 14) - 25% = 960.75 characters
## Old scores ~~1315~~ ~~1351~~ ~~1361~~ ~~1295~~ ~~989~~ ~~977~~
That was fun, and it's the first answer – yeah.
```
$i=[A=>[üçÖ,üçÜ,üçá,üçà,üçâ,üçä,üçã],B=>[üçå,üçç,üçé,üçè,üçê,üçë,üçí],C=>[üçì,üçî,üçï,üçñ,üçó,üçò,üçô],D=>[üçö,üçõ,üçú,üçù,üçû,üçü,üç†],E=>[üç°,üç¢,üç£,üç§,üç•,üç¶,üçß],F=>[üç®,üç©,üç™,üç´,üç¨,üç≠,üçÆ],G=>[üçØ,üç∞,üç±,üç≤,üç≥,üç¥,üçµ],H=>[üç∂,üç∑,üç∏,üçπ,üç∫,üçª,üçº]];$p=[A=>1,B=>1.5,C=>2,D=>2.5,E=>3,F=>3.5,G=>4,H=>4.5];$v=[N=>.05,D=>0.1,Q=>.25,O=>1,F=>5,T=>10];a:$m='';$w=$x=0;$q=$c[0];$r=$c[1];$f=fgets;$n=rand;$u=number_format;if('Done'==$c&&$e=1)foreach([Q,D,N]as$_)while($b&&round($b-$v[$_],2)>=0&&$m.=$_)$b-=$v[$_];elseif('/'==$q){$v[$r]?$b+=$v[$r]:$m="Money not accepted
";$m.="Balance: $".$u($b,2);}elseif(in_array($q,range(A,Z))){if(0<$r&&8>$r--&&($_=$p[$q])){$b&&$b<$_?$m="Insufficient funds. ":0;if($b<$_)$m.="Item cost: $".$u($_,2);elseif(üëæ==$i[$q][$r])$m="Item out of stock.";else{$t=0;if(H==$q&&$r<6){$t=$n(13,19);$s=$n(13,19);echo"ID required: {$t}x$s = ?
";if($f(STDIN)!=$t*$s)$m=üîû;else$t=0;}if(!$t){$b-=$_;if(1>$n(0,9)){$w=1;}$x=$i[$q][$r];$m="Item at $c purchased. Remaining balance: $".$u($b,2).($w?"":"
$x");$i[$q][$r]=üëæ;if(!$b)$e=1;}}}else$m="Invalid code";}if($c&&!$m&&!$e)$m=Error;system(clear);echo" 1Ô∏è‚É£ 2Ô∏è‚É£ 3Ô∏è‚É£ 4Ô∏è‚É£ 5Ô∏è‚É£ 6Ô∏è‚É£ 7Ô∏è‚É£";foreach($i as$k=>$_){echo"
$k ";foreach($_ as$_)echo"$_ ";}echo"
$m
";if($w){echo"JAM!!!
";for(;$c!=kick&&$c!=punch||7>$n(0,9);$c=trim($f(STDIN)));echo"$x
";}$e?exit:$c=trim($f(STDIN));goto a;
```
As vending machines remind me of the 90s I used `goto` and for purchased items the *Space Invader* `üëæ` is shown. The machine is redrawn after every command.
**Ungolfed (somehow)**
```
$i=[A=>[üçÖ,üçÜ,üçá,üçà,üçâ,üçä,üçã],B=>[üçå,üçç,üçé,üçè,üçê,üçë,üçí],C=>[üçì,üçî,üçï,üçñ,üçó,üçò,üçô],D=>[üçö,üçõ,üçú,üçù,üçû,üçü,üç†],E=>[üç°,üç¢,üç£,üç§,üç•,üç¶,üçß],F=>[üç®,üç©,üç™,üç´,üç¨,üç≠,üçÆ],G=>[üçØ,üç∞,üç±,üç≤,üç≥,üç¥,üçµ],H=>[üç∂,üç∑,üç∏,üçπ,üç∫,üçª,üçº]];
$p=[A=>1,B=>1.5,C=>2,D=>2.5,E=>3,F=>3.5,G=>4,H=>4.5];
$v=[N=>.05,D=>0.1,Q=>.25,O=>1,F=>5,T=>10];
a:
$m='';
$w=$x=0;
$q=$c[0];
$r=$c[1];
$f=fgets;
$n=rand;
$u=number_format;
if('Done'==$c&&$e=1)
foreach([Q,D,N]as$_)
while($b&&round($b-$v[$_],2)>=0&&$m.=$_)
$b-=$v[$_];
elseif('/'==$q){
$v[$r]?$b+=$v[$r]:$m="Money not accepted
";
$m.="Balance: $".$u($b,2);
}elseif(in_array($q,range(A,Z))){
if(0<$r&&8>$r--&&($_=$p[$q])){
$b&&$b<$_?$m="Insufficient funds. ":0;
if($b<$_)$m.="Item cost: $".$u($_,2);
elseif(üëæ==$i[$q][$r])
$m="Item out of stock.";
else{
$t=0;
if(H==$q&&$r<6){
$t=$n(13,19);
$s=$n(13,19);
echo"ID required: {$t}x$s = ?
";
if($f(STDIN)!=$t*$s)
$m=üîû;
else
$t=0;
}
if(!$t){
$b-=$_;
if(1>$n(0,9)){
$w=1;
}
$x=$i[$q][$r];
$m="Item at $c purchased. Remaining balance: $".$u($b,2).($w?"":"
$x");
$i[$q][$r]=üëæ;
if(!$b)$e=1;
}
}
}else
$m="Invalid code";
}
if($c&&!$m&&!$e)$m=Error;
system(clear);
echo" 1️⃣ 2️⃣ 3️⃣ 4️⃣ 5️⃣ 6️⃣ 7️⃣";
foreach($i as$k=>$_){
echo"
$k ";
foreach($_ as$_)
echo"$_ ";
}
echo"
$m
";
if($w){
echo"JAM!!!
";
for(;$c!=kick&&$c!=punch||7>$n(0,9);$c=trim($f(STDIN)));
echo"$x
";
}
$e?exit:$c=trim($f(STDIN));
goto a;
```
üëæ Tested on OS X with PHP 5.5 and 5.6 üëæ
---
**Edits**
* *Added* **12 bytes**. Fixed exit on `Done` and golfed some strings.
* *Added* **306 bytes**. Fixed one or two bugs and added support for the bonuses. With the bonuses it's now nearly **15 bytes** shorter.
* *Added* **66 bytes**. Had to format the money differently, also had to accept more values (`[A-Z][0-9]`) for `Invalid code`.
* *Saved* **10 bytes**. Found one whitespace and turned some `.=` into `=` were applicable.
* *Saved* **36 bytes** due to some refactoring.
* *Saved* **20 bytes** by refactoring some loops and assignments.
[Answer]
# C# 6 (.Net Framework 4.6), ~~1356~~ ~~1324~~ ~~1304~~ ~~1311~~ ~~1307~~ ~~1238~~ ~~1235~~ ~~1231~~ 1220 Letters - 14 Letters (Emoji Numbers) - (15% Jam Bonus + 10% ID Bonus) = ~~1017~~ ~~993~~ ~~978~~ ~~972.75~~ ~~969.75~~ ~~918~~ ~~915.75~~ 904.5 Letters
```
using h=System.Console;class c{static void Main(){double b=0,z,p,x=0,i=57157,j,n,r,c,m;var a=1==0;var d=new System.Collections.Hashtable();for(;i<57213;)d.Add(x++,""+(char)55356+(char)i++);for(var e=new System.Random();;){for(w(" 1Ô∏è‚É£ 2Ô∏è‚É£ 3Ô∏è‚É£ 4Ô∏è‚É£ 5Ô∏è‚É£ 6Ô∏è‚É£ 7Ô∏è‚É£"),x=0;x<8;x++,w(""))for(h.Write((char)('A'+x)),i=0;i<7;)h.Write(" "+d[x*7+i++]);for(;;){var k=h.ReadLine();if(k[0]==47){var l=k[1];z=b;b+=l=='N'?.05:l=='D'?.1:l=='Q'?.25:l=='O'?1:l=='F'?5:l=='T'?10:0;a=a|z!=b;w(z!=b?$"Balance {b:0.00}":"Money not Accepted");}else{if(k=="Done"){for(;b/.25>=1;b-=.25)h.Write("Q");for(;b/.1>=1;b-=.1)h.Write("D");for(;b/.05>=1;b-=.05)h.Write("N");return;}r=k[0]-65;c=k[1]-49;if(r<0|r>7|c<0|c>6)w("Invalid code");else{p=1+r/2;if(!a|p>b)w($"{(a&p>b?"Insufficient Funds. ":"")}Item Cost: ${p:0.00}");else{m=r*7+c;if(d[m]=="üö´")w("Item out of stock");else{if(r>6&c<6){j=e.Next(13,20);n=e.Next(13,20);w($"ID required: {j}x{n} = ?");if(int.Parse(h.ReadLine())!=j*n){w("üîû");break;}}b-=p;w($"Item at {k} Purchased. Remaining Balance: ${b:0.00}");if(e.Next(10)==1)for(w("Jam!!!");;){var f=h.ReadLine();if((f=="punch"|f=="kick")&e.Next(10)<2)break;}w(""+d[m]);d[m]="üö´";if(b==0)return;break;}}}}}}}static void w(string s)=>h.WriteLine(s);}
```
slightly more ungolfed for use in LinqPad 5 (C# 6). Use h=System.Console in F4.
```
void Main()
{
double b=0,z,p,x=0,i=57157,j,n,r,c,m;
var a = 1==0;
var d = new Hashtable();
for (; i < 57213;) d.Add(x++, ""+(char)55356 + (char)i++);
for (var e = new Random(); ;)
{
for (w(" 1️⃣ 2️⃣ 3️⃣ 4️⃣ 5️⃣ 6️⃣ 7️⃣"), x = 0; x < 8; x++, w(""))
for (h.Write((char)('A' + x)), i = 0; i < 7;)
h.Write(" " + d[x * 7 + i++]);
for (; ;)
{
var k = h.ReadLine();
if (k[0] == 47)
{
var l = k[1];
z = b;
b += l == 'N' ? .05 : l == 'D' ? .1 : l == 'Q' ? .25 : l == 'O' ? 1 : l == 'F' ? 5 : l == 'T' ? 10 : 0;
a = a|z!=b;
w(z != b ? $"Balance {b:0.00}" : "Money not Accepted");
}
else
{
if (k == "Done")
{
for (; b / .25 >= 1; b -= .25) h.Write("Q");
for (; b / .1 >= 1; b -= .1) h.Write("D");
for (; b / .05 >= 1; b -= .05) h.Write("N");
return;
}
r = k[0] - 65;
c = k[1] - 49;
if(r<0|r>7|c<0|c>6)w("Invalid code");
else
{
p = 1 + r / 2;
if (!a | p > b) w($"{(a&p>b?"Insufficient Funds. ":"")}Item Cost: ${p:0.00}");
else
{
m = r * 7 + c;
if (d[m] == "üö´")
w("Item out of stock");
else
{
if (r > 6 & c < 6)
{
j = e.Next(13, 20);
n = e.Next(13, 20);
w($"ID required: {j}x{n} = ?");
if (int.Parse(h.ReadLine()) != j * n)
{
w("üîû");
break;
}
}
b -= p;
w($"Item at {k} Purchased. Remaining Balance: ${b:0.00}");
if (e.Next(10) == 1)
for (w("Jam!!!"); ;)
{
var f = h.ReadLine();
if ((f == "punch" | f == "kick") & e.Next(10) < 2)
break;
}
w(""+d[m]);
d[m] = "üö´";
if (b == 0) return;
break;
}
}
}
}
}
}
}
void w(string s)=>h.WriteLine(s);
```
edit: thanks for the for(;;) hint ;)
edit: Strike !! Better than PHP ;-)
edit: Removed 24 Letters. Still something left for php.
edit: Removed 20 Letters by switching from decimal to double.
edit: Removed 7 Letters by switching to Emoji Numbers
edit: Removed 4 Letters by switching everything to double instead of a mix of double and ints.
edit: Removed 69 Letters - found dead code o\_O Best Entry C# :D
edit: Removed 3 Letters - switched last if-else statement
edit: Removed 4 Letters - switched from short-circuit operators (&& and ||) to normal & and |
edit: Removed 11 Letters - switched from h.WriteLine to w() with conditional verbatim string.
] |
[Question]
[
One of my kid's favorite toys is [a set like this](http://rads.stackoverflow.com/amzn/click/B000CBSNRY). Actually its one of my favorite toys - I've been playing with it and its been giving me some PPCG challenge ideas. Here's one:
Write a program or function that takes an ASCII line drawing as input and decides whether or not it folds into a cube.
### Input
Input will consist of exactly one hexomino built from squares like this:
```
+-+
| |
+-+
```
For example a valid input heximino is:
```
+-+
| |
+-+-+-+-+
| | | | |
+-+-+-+-+
| |
+-+
```
### Output
* A truthy value if the hexomino can be folded into a cube, or
* A falsey value otherwise.
To save us a bit of work, wikipedia has nice graphics of:
* All 35 hexominoes:

* All 11 hexominoes that fold into cubes:

### Notes
* Input hexominoes may have any rotation or reflection, not just those shown in the images above
* Input hexominoes may have leading spaces, but will be correctly aligned with respect to themselves
* Input hexominoes may have trailing space at the end of lines and trailing newlines at the end of input
[Answer]
# [PMA/Snails](https://codegolf.stackexchange.com/a/47495/30688), 130
```
.!(z\ |o{c..!(z\ }3){w=(..!(z\ )|b..!(z\ )o{..!(z\ }2|c{..!(z\ }1,2w..!(z\ )|w{..!(z\ }1,2c..!(z\ }4o..!(z\ )(..!(z\ )|n..!(z\ )`2
```
or more "readably",
```
?
.!(z\ | o{c..!(z\ }3 )
{w =( ..!(z\ ) | b ..!(z\ ) o {..!(z\ }2 | c {..!(z\ }1,2w..!(z\ ) | w {..!(z\ }1,2c..!(z\ }4
o ..!(z\ ) ( ..!(z\ ) | n ..!(z\ ) `2
```
Unusually, a problem came along that can be handled by the limited amount of features implemented so far. The `!(z\ )` pattern determines that the current position is at the space in the middle of a square using a negative assertion that there is a space in some "octilinear" direction. The general idea is to check for a pattern that places a square at each of the 5 necessary locations relative to the square that the match starts on. Also, it needs to check that it is not in a 2x2 block of squares. Before the program would work, I had to fix a bug with the parsing of parentheses.
If the hexomino does not map a cube, `0` is printed. If it does, some positive integer is printed (number of matches).
I adapted [this polyomino generator](https://codegolf.stackexchange.com/a/2237/30688) to create all possible test cases:
```
n=input()
r=range
T=lambda P:set(p-min(p.real for p in P)-min(p.imag for p in P)*1j for p in P)
A=[]
for i in r(1<<18):
P=[k%3+k/3*1j for k in r(18)if i>>k&1]
C=set(P[:1])
for x in P:[any(p+1j**k in C for k in r(4))and C.add(p)for p in P]
P=T(P)
if not(C^P or P in A or len(P)-n):
#for y in r(4):print''.join(' *'[y+x*1j in P] for x in r(6))
o = [ [' ']*13 for _ in r(9)]
for y in r(4):
for x in r(6):
if y+x*1j in P: X=2*x;Y=2*y; o[Y][X]=o[Y+2][X]=o[Y][X+2]=o[Y+2][X+2]='+'; o[Y][X+1]=o[Y+2][X+1]='-';o[Y+1][X+2]=o[Y+1][X]='|'
print '\n'.join(map(''.join,o))
A+=[T([p*1j**k for p in P])for k in r(4)]
```
[Answer]
# Ruby, ~~173 148 145~~ 143 bytes
```
h=->b,c{[c.count(c.max),c.count(c.min),3].max*2<b.max-b.min}
->s{x=[];y=[];i=j=0
s.bytes{|e|e==43&&x<<i|y<<j;i=e<32?0*j+=1:i+1}
h[x,y]||h[y,x]}
```
Latest change: `/2` on right side of `<` replaced by `*2`on left side. Allows elimination of one set of`()`
**Explanation**
The code is in two parts: a main unnamed function that does the parsing, and an auxiliary unnamed function assigned to the variable `h` that does the checking.
The main function scans bytewise through the string, adding the x and y coordinates `i,j` of all `+` symbols found to `x[]` and `y[]`. It then calls `h` twice. The first time it assumes the hexomino is horizontal (`x[]` contains the lengths and `y[]` the widths) and the second time it assumes it is vertical.
**The function `h` takes the lengthwise coordinates in array `b` then the widthwise coordinates in array `c`.** It calculates the length (in squares) by the expression `(b.max.b.min)/2`. If this is less than or equal to 3, the hexomino should be evaluated in the other direction so `h` returns `false`.
Inspection of the hexominos will show that if the length is 4, **those hexominos that will fold into a cube have no more than 2 squares (3 `+` symbols) in the first and last row**. Most of the squares are concentrated on the middle row, which will become the equator of the cube. This condition turns out to be necessary and sufficient for a hexomino of length 4 that will fold into a cube.
There is only one hexomino of length 5 that will fold into a cube. It has 3 squares (4 `+` symbols) in its first and last rows. All other hexominos of length 5 have 5 or more `+` symbols in either the first or last row.
There is only one hexomino of length 6. It has 7 `+` symbols on each row.
**Putting all this together, it is sufficient to check that the length of the hexomino is greater than 3, and the number of `+` symbols on the first and last rows (whichever is higher) is less than the length.**
**Ungolfed in test program**
```
#checking function as explained in text
h=->b,c{[c.count(c.max),c.count(c.min),3].max<(b.max-b.min)/2}
#main function for parsing
f=->s{
x=[] #separate assignments required,
y=[] #otherwise we get 2 pointers to the same array
i=j=0 #start coordinates 0,0
s.bytes{|e| #scan string bytewise
e==43&&x<<i|y<<j #if byte is a + symbol (ascii 43) add the coordinates to arrays x and y
i=e<32?0*j+=1:i+1 #if byte is before ascii 32 assume newline, increment j and zero i. Otherwise increment i
}
h[x,y]||h[y,x] #call h twice, with x and y in each possible order
}
#VALID INPUTS
puts f["
+-+
| |
+-+-+-+-+
| | | | |
+-+-+-+-+
| |
+-+"]
puts f["
+-+
| |
+-+-+-+-+
| | | | |
+-+-+-+-+
| |
+-+"]
puts f["
+-+
| |
+-+-+-+-+
| | | | |
+-+-+-+-+
| |
+-+"]
puts f["
+-+
| |
+-+-+-+
| | | |
+-+-+-+-+
| | |
+-+-+"]
puts f["
+-+
| |
+-+-+-+-+
| | | | |
+-+-+-+-+
| |
+-+"]
puts f["
+-+
| |
+-+-+-+-+
| | | | |
+-+-+-+-+
| |
+-+"]
puts f["
+-+
| |
+-+-+-+
| | | |
+-+-+-+-+
| | |
+-+-+"]
puts f["
+-+
| |
+-+-+-+-+
| | | | |
+-+-+-+-+
| |
+-+"]
puts f["
+-+
| |
+-+-+-+
| | | |
+-+-+-+-+
| | |
+-+-+"]
puts f["
+-+-+
| | |
+-+-+-+
| | |
+-+-+-+
| | |
+-+-+"]
puts f["
+-+-+-+
| | | |
+-+-+-+-+-+
| | | |
+-+-+-+
"]
#INVALID INPUTS
puts f["
+-+-+-+
| | | |
+-+-+-+
| | | |
+-+-+-+
"]
puts f["
+-+-+-+-+-+-+
| | | | | | |
+-+-+-+-+-+-+
"]
puts f["
+-+-+
| | |
+-+-+
| |
+-+
| |
+-+
| |
+-+
| |
+-+
"]
puts f["
+-+-+-+-+-+
| | | | | |
+-+-+-+-+-+
| |
+-+
"]
puts f["
+-+
| |
+-+-+-+-+-+
| | | | | |
+-+-+-+-+-+
"]
puts f["
+-+-+-+-+
| | | | |
+-+-+-+-+-+
| | |
+-+-+"]
puts f["
+-+-+-+-+
| | | | |
+-+-+-+-+
| | |
+-+-+
"]
puts f["
+-+-+-+-+
| | | | |
+-+-+-+-+
| | | |
+-+ +-+
"]
puts f["
+-+ +-+
| | | |
+-+-+-+-+
| | | | |
+-+-+-+-+
"]
puts f["
+-+-+
| | |
+-+-+-+-+
| | | | |
+-+-+-+-+
"]
puts f["
+-+
| |
+-+
| |
+-+-+-+-+
| | | | |
+-+-+-+-+
"]
puts f["
+-+
| |
+-+-+-+
| | | |
+-+-+-+
| |
+-+
| |
+-+
"]
puts f["
+-+
| |
+-+-+-+
| | | |
+-+-+-+
| |
+-+
| |
+-+"]
puts f["
+-+-+
| | |
+-+-+
| |
+-+-+
| | |
+-+-+
| |
+-+
"]
puts f["
+-+-+-+
| | | |
+-+-+-+-+
| | | |
+-+-+-+
"]
puts f["
+-+-+-+
| | | |
+-+-+-+
| |
+-+-+
| | |
+-+-+
"]
puts f["
+-+-+-+
| | | |
+-+-+-+-+
| | |
+-+-+
| |
+-+
"]
```
[Answer]
# JavaScript (ES6), 443 ~~431~~
*Edit* bug fix, problem during input parse, removing blank columns
```
F=t=>(a=b=c=d=e=f=g=h=0,M=Math.min,
t=t.split('\n').filter(r=>r.trim()>''),
t=t.map(r=>r.slice(M(...t.map(r=>r.search(/\S/))))),
t.map((r,i)=>i&1&&[...r].map((_,j)=>j&1&&r[j-1]==r[j+1]&t[i-1][j]==t[i+1][j]&r[j-1]=='|'
&&(y=i>>1,x=j>>1,z=y*5,w=x*5,a|=1<<(z+x),e|=1<<(w+y),b|=1<<(4+z-x),f|=1<<(4+w-y),c|=1<<(20-z+x),g|=1<<(20-w+y),d|=1<<(24-z-x),h|=1<<(24-w-y)
))),~[1505,2530,3024,4578,252,6552,2529,4577,2499,4547,7056].indexOf(M(a,b,c,d,e,f,g,h)))
```
That's very long, and even longer as parsing input is a big part of the task.
What I do is verifyng if the given input is one of the 11 foldable hexominoes.
Each foldable hexomino can be mapped to some 5x5 bitmap (up to 8 different, with simmetry and rotations). Taken the bitmaps as 25bit number, I have found the min values for the 11 noted hexominoes, using the following code (with very simple input format)
```
h=[ // Foldable hexominoes
'o\noooo\no', ' o\noooo\n o', // pink
'o\noooo\n o', ' o\noooo\n o', 'ooo\n ooo', 'oo\n oo\n oo', //blue
'o\noooo\n o', 'o\noooo\n o', 'oo\n ooo\n o', 'oo\n ooo\n o', 'o\nooo\n oo' // gray
]
n=[]
h.forEach(t=>(
a=[],
t.split('\n')
.map((r,y)=>[...r]
.map((s,x)=>s>' '&&(
a[0]|=1<<(y*5+x),a[1]|=1<<(x*5+y),
a[2]|=1<<(y*5+4-x),a[3]|=1<<(x*5+4-y),
a[4]|=1<<(20-y*5+x),a[5]|=1<<(20-x*5+y),
a[6]|=1<<(24-y*5-x),a[7]|=1<<(24-x*5-y))
)
),
n.push(Math.min(...a))
))
```
That gives `[1505,2530,3024,4578,252,6552,2529,4577,2499,4547,7056]`
So, given the input string, I have to do the same to find the min bitmap, then return true if this number is present in my precalc list.
```
// Not so golfed
F=t=>(
a=b=c=d=e=f=g=h=0,M=Math.min,
t=t.split('\n').filter(r=>r.trim()>''), // remove blank lines
t=t.map(r=>r.slice(M(...t.map(r=>r.search(/\S/))))), // remove blank colums to the left
t.map((r,i)=>i&1&&[...r] // only odd rows
.map((_,j)=>j&1&& // only odd columns
r[j-1]==r[j+1]&t[i-1][j]==t[i+1][j]&r[j-1]=='|' // found a cell
&&(y=i>>1,x=j>>1,z=y*5,w=x*5, // find bitmaps for 8 rotations/simmetries
a|=1<<(z+x),e|=1<<(w+y),
b|=1<<(4+z-x),f|=1<<(4+w-y),
c|=1<<(20-z+x),g|=1<<(20-w+y),
d|=1<<(24-z-x),h|=1<<(24-w-y)
))),
~[1505,2530,3024,4578,252,6552,2529,4577,2499,4547,7056].indexOf(Math.min(a,b,c,d,e,f,g,h)) // look for min
)
```
Run snippet to test in Firefox
```
F=t=>(a=b=c=d=e=f=g=h=0,M=Math.min,
t=t.split('\n').filter(r=>r.trim()>''),
t=t.map(r=>r.slice(M(...t.map(r=>r.search(/\S/))))),
t.map((r,i)=>i&1&&[...r]
.map((_,j)=>j&1&&r[j-1]==r[j+1]&t[i-1][j]==t[i+1][j]&r[j-1]=='|'
&&(y=i>>1,x=j>>1,z=y*5,w=x*5,
a|=1<<(z+x),e|=1<<(w+y),b|=1<<(4+z-x),f|=1<<(4+w-y),c|=1<<(20-z+x),g|=1<<(20-w+y),d|=1<<(24-z-x),h|=1<<(24-w-y)
))),~[1505,2530,3024,4578,252,6552,2529,4577,2499,4547,7056].indexOf(M(a,b,c,d,e,f,g,h)))
s=[...' \n \n \n 2 \n \n '],o=7,l=5,k={},t=0
out=[[],[]]
Test=s=>k[s]?0 // filter duplicates, but allow same shape in different position
:k[s]=(
p=Array(13).fill(0).map(x=>Array(13).fill(' ')), // build string to test in long format
s.map((v,i)=>(x=2*(i%7),y=2*(i/7|0),-v&&(
p[y][x]=p[y][x+2]=p[y+2][x]=p[y+2][x+2]='+',
p[y][x+1]=p[y+2][x+1]='-',
p[y+1][x]=p[y+1][x+2]='|'
))),
s=p.map(r=>r.join('')).join('\n'),
ok=F(s), // test
out[!ok|0].push('\n'+s+-ok),
1
)
Fill=(z,p)=>(
s[p]=2,
z>l?Test(s):s.forEach((v,i)=>v==' '&(s[i+o]==2|s[i-o]==2|s[i-1]==2|s[i+1]==2)?Fill(z+1,i):0),
s[p]=' '
)
Fill(1,s.indexOf('2'))
OV.innerHTML=out[0].join('\n')
OI.innerHTML=out[1].join('\n')
```
```
pre {
overflow: auto;
font-size: 9px;
height: 500px;
display: block;
border: 1px solid #888;
padding: 6px 20px;
line-height: 6px;
}
```
```
Verify all hexominoes possible in a 6x6 grid (Better full page) <br>
<table><tr>
<th>VALID</th><th>INVALID</th>
</tr><tr>
<td><pre id=OV></pre></td>
<td><pre id=OI></pre></td>
</tr></table>
```
] |
[Question]
[
From <http://en.wikipedia.org/wiki/Triangle>:

---
Write a program that takes three 2d coordinate tuples (Cartesian), and classifies what shape these three points describe.
In almost all cases these points will describe a triangle of varying types. In some degenerate cases, the points will either describe a singular point or a straight line. The program will determine which of the following tags apply to the described shape:
* Point (3 points are co-incident)
* Line (3 points lie on a straight line - no more than 2 points may be co-incident)
* Equilateral (3 sides equal, 3 angles equal)
* Isosceles (2 sides equal, 2 angles equal)
* Scalene (0 sides equal, 0 angles equal)
* Right (1 angle exactly π/2 (or 90°))
* Oblique (0 angles exactly π/2 (or 90°))
* Obtuse (1 angle > π/2 (or 90°))
* Acute (3 angles < π/2 (or 90°))
Note that for some described shapes, more than one of the above tags will apply. For example, any right-angled will also either be isosceles or scalene.
### Input
* The program may read the 3 input coordinates from STDIN, command-line, environment variables or whatever method is convenient for your language of choice.
* The input co-ordinates my be formatted however is convenient for your language of choice. It can be assumed that all input numbers are well-formed with respect to the datatypes you end up using.
* Nothing can be assumed about the ordering of the input coordinates.
### Output
* The program will output to STDOUT, dialog box or whatever display method is convenient for your language of choice.
* The output will display all the tags applicable to the shape described by the input coordinates.
* Tags may be output in any order.
### Other Rules
* Your language's trigonometric libraries/APIs are allowed, but any APIs that specifically calculate triangle types are banned.
* When determining equality of angles or lengths of sides, you will likely end up comparing floating-point values. Two such values are to be considered "equal" if one is within 1% of the other.
* [Standard “loopholes” which are no longer funny](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny)
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
### Examples
```
Input Output
(1,2) (1,2) (1,2) Point
(1,2) (3,4) (5,6) Line
(0,0) (1,1) (2,0) Isosceles Right
(0,0) (2,1) (10,1) Scalene Oblique Obtuse
```
[Answer]
# C (451 bytes)
Uses only squared lengths and slopes.
```
p[2],q[2],r[2];z(c){char*y[]={"Line","Point","Isosceles ","Equilateral ","Scalene ","Right","Oblique ","Acute","Obtuse"};printf(y[c]);}d(int*a,int*b){int c=*a++-*b++,e=*a-*b;return c*c+e*e;}main(){scanf("%d%d%d%d%d%d",p,p+1,q,q+1,r,r+1);int a=d(p,q),b=d(q,r),c=d(r,p),e=!a+!b+!c,f=(a==b)+(b==c)+(c==a),g=a>b&&b>c?a:b>c?b:c,h=g^a?g^b?a+b:c+a:b+c;e?z(e/2):(1[q]-1[p])*(*r-*q)^(1[r]-1[q])*(*q-*p)?f?z(2+f/2),f-1&&z(2):z(4),h^g?z(6),z(7+(h<g)):z(5):z(0);}
```
Ungolfed (and ternary operator replaced with if/else):
```
int p[2],q[2],r[2];
void print(c){
char *y[]={"Line","Point","Isosceles ","Equilateral ","Scalene ","Right","Oblique ","Acute","Obtuse"};
printf(y[c]);
}
squared_distance(int *a,int *b){
int c = *a++ - *b++, e = *a - *b;
return c*c+e*e;
}
main(){
scanf("%d%d%d%d%d%d",p,p+1,q,q+1,r,r+1); // read in coordinates
int a = squared_distance(p,q),b = squared_distance(q,r),c = squared_distance(r,p),
e=!a+!b+!c, // number of sides of length 0
f=(a==b)+(b==c)+(c==a), // number of equal-length pairs
g = a > b && b > c ? a : (b > c ? b : c), // longest side
h = g != a ? g != b ? a + b : c + a : b + c; // sum of squares of length of other two sides
if(e)
print(e/2); // 1 side of len 0: line, 3 sides: point
// comparing slopes PQ and QR
else if((q[1]-p[1])*(*r-*q) != (r[1]-q[1])*(*q-*p)){ // not line
if(f){
print(2+f/2); // 1 pair of equal length sides: isosceles, 3: equilateral
if(f-1) print(2); // equilateral therefore also isosceles
}else print(4); // 0: scalene
if(h!=g){ // a^2+b^2!=c^2: not right
print(6); // oblique
print(7+(h<g)); // a^2+b^2<c^2:obtuse, acute otherwise
}else print(5); // right
}else
print(0); // line
}
```
Input (through stdin) Format: x y x y x y
ex. 0 0 1 1 2 0 for Isosceles Right
[Answer]
# C,333
```
z,c,r,b,s,i,t[14],g[14];
main(){
for(;i<14;i++){
g[i]=r=t[(i+2)%6]-t[i%6];r*=r;t[i|1]+=r;
i<6&&scanf("%d",t+i);
i>7&&(b<t[i]&&(b=t[i]),s+=t[i],z+=!t[i],c+=t[i]==t[i-2]);
}
if(g[6]*g[9]==g[8]*g[7])puts(z==6?"point":"line");else
printf(b*2==s?"right ":"oblique %s",b*2>s?"obtuse ":"acute "),puts(c>3?c>5?"equilateral":"isosceles":"scalene");
}
```
I left the whitespace in for the moment. This works but could probably do with some tidying up and golfing. Similar math to `@es1024`'s answer, but uses a loop and arrays. Input format `x y x y x y`
Variables
`t[]` stores both the input and the squares of the lengths. By the end of the program it looks like the table below (increasing the number of iterations of the loop would lead to indefinite repitition of the squared lengths.) At the start of the loop squares of lengths (garbage as not all the data is available) are needlessly stored in cells 1,3 and 5, but are promptly overwritten by `scanf.` Useful data is written to `z,b,c` ahd `s` when `i`=9,11,13 (`t[i]` and `t[i-2]` are accessed.)
```
01 23 45 67 89 1011 1213
aa bb cc a b c a
xy xy xy L L L L
```
`g[]` was added late on to hold the dx and dy values needed for slope calculation. The only cells used are 6 through 9 (0 through 5 are unreliable as not all the data is available when they are written.) If `g[6]/g[7]==g[8]/g[9]` the slopes of 2 lines are equal and the triangle is just a line (or a point.) The equation is rearranged in the program to avoid division.
`r`is an intermediate value used for squaring
`z`counts the number of sides of length zero. It has an offset of +3 because the loop reads 3 blank cells in `t[]`.
`c`counts the number of sides that are of identical length. It also has an offset of +3. Note that side `a` is written to `t[]` twice in order to be able to check a=b,b=c,c=a.
`b`is the biggest length of a side, squared.
`s`is the sum of the squares of all sides.
Note that comparing side lengths A^2+B^2+C^2 with 2\*B^2 is the same as comparing A^2+C^2 with B^2 (just subtract B^2 from both sides.) Thus if B^2=A^2+C^2 it is a right triangle. if B^2 is greater it is obtuse, if smaller it is acute.
[Answer]
# Golfscript (175 bytes)
```
~..|,({.)2$([\;\]@(;]{{~}/@- 2?@@- 2?+}%$.{2-1??100*}/-+abs 1<{;"Line"}{.[]|,((["Isosceles ""Scalene "]=\~-+.!["Oblique ""Right "]=\.!\0>-)["Acute ""Obtuse "]=}if}{;"Point "}if
```
You can test it [here](http://golfscript.apphb.com/?c=e117cHJpbnR9L24gcHJpbnR9OnE7Cjt7fi4ufCwoey4pMiQoW1w7XF1AKDtde3t%2BfS9ALSAyP0BALSAyPyt9JSQuezItMT8%2FMTAwKn0vLSthYnMgMTx7OyJMaW5lIn17Li58LCgoWyJJc29zY2VsZXMgIiJTY2FsZW5lICJdPVx%2BLSsuIVsiT2JsaXF1ZSAiIlJpZ2h0ICJdPVwuIVwwPi0pWyJBY3V0ZSAiIk9idHVzZSAiXT19aWZ9ezsiUG9pbnQgIn1pZn06ZjsKCiJbWzEgMV1bMyAyXVs3IDRdXSIgZiBxICMgTGluZQoiW1swIDddWzAgN11bOCAxXV0iIGYgcSAjIExpbmUKIltbMCA3XVswIDddWzAgN11dIiBmIHEgIyBQb2ludAoiW1sxIDRdWzkgN11bNCAwXV0iIGYgcSAjIFNjYWxlbmUgT2JsaXF1ZSBBY3V0ZQoiW1swIDBdWzQgMF1bMCAzXV0iIGYgcSAjIFNjYWxlbmUgUmlnaHQgCiJbWzEgNF1bOSAxXVs0IDBdXSIgZiBxICMgU2NhbGVuZSBPYmxpcXVlIE9idHVzZQoiW1swIDBdWzQgMF1bMiAzXV0iIGYgcSAjIElzb3NjZWxlcyBPYmxpcXVlIEFjdXRlCiJbWzAgMF1bNCAwXVsyIDJdXSIgZiBxICMgSXNvc2NlbGVzIFJpZ2h0CiJbWzAgMF1bNCAwXVsyIDFdXSIgZiBxICMgSXNvc2NlbGVzIE9ibGlxdWUgT2J0dXNlIAoK) (test set included).
**Input format:**
```
"[x y][x y][x y]"
```
**Commented version:**
```
~ # evaluates input string
..|,( # pushes the number of unique coords - 1
{
.)2$([\;\]@(;] # makes all 3 possible pairings of coords
{{~}/@- 2?@@- 2?+}%$ # gets all squares of side lengths
.{2-1??100*}/-+abs 1< # 0 if triangle, 1 if line
{;"Line"}
{
.[]|,((["Isosceles ""Scalene "]=\ # removes duplicate side-squares,
# and use the count to determine
# if isosceles or scalene (no
# equilaterals will exist)
~-+.!["Oblique ""Right "]=\ # compute a^2 + b^2 - c^2. Use to
# determine if oblique or right.
# c = max side length
.!\0>-)["Acute ""Obtuse "]= # use same value to determine if
# acute, obtuse, or right
}
if
}
{;"Point "}
if
```
**NOTE:**
The reason my code contains no "equilateral" output is because:
* OP said "all input numbers are well-formed with respect to the datatypes you end up using"
* Golfscript does not have floating point numbers - not inherently anyway
* It's impossible (in a 2-dimensional grid) to have an equilateral triangle with integer coordinates, as proven [here](https://math.stackexchange.com/questions/105330/equilateral-triangle-with-integer-coordinates).
[Answer]
# Mathematica (~~313~~ 307 characters)
Golfed:
```
f@p_:=(P=Print;R=RotateLeft;L=Length;U=Union;If[L@U@p==1,P@"Point",If[Det[Join[#,{1}]&/@p]==0,P@"Line",v=p-R@p;a=MapThread[VectorAngle[#,#2]&,{-v,R@v}];u=L@U[Norm/@v];If[u==1,P@"Equilateral",If[u==2,P@"Isosceles",P@"Scalene"]];If[MemberQ[a,Pi/2],P@"Right",P@"Oblique";If[Max@a>Pi/2,P@"Obtuse",P@"Acute"]]]])
```
Ungolfed:
```
f@p_ := (
P = Print; (* make aliases for functions used more than once *)
R = RotateLeft;
L = Length;
U = Union;
If[L@U@p == 1, (* if all points identical *)
P@"Point",
If[Det[Join[#, {1}] & /@ p] == 0, (* if area is zero *)
P@"Line",
v = p - R@p; (* cyclic vectors *)
a = MapThread[VectorAngle[#, #2] &, {-v, R@v}]; (* interior angles *)
u = L@U[Norm /@ v]; (* number of unique side lengths *)
If[u == 1,
P@"Equilateral",
If[u == 2,
P@"Isosceles",
P@"Scalene"
]
];
If[MemberQ[a, Pi/2],
P@"Right",
P@"Oblique";
If[Max@a > Pi/2,
P@"Obtuse",
P@"Acute"
]
]
]
]
)
```
The input format is a list of points, upon which the function is called:
```
points = {{x1,y1},{x2,y2},{x3,y3}};
f@points
```
] |
[Question]
[
# Introduction
Write a solver for the [Hitori](https://en.wikipedia.org/wiki/Hitori) puzzles using least bytes.
# Challenge
Your task is write a solver for the Hitori (ひとり, the word for "alone" in Japanese; the meaning of the game name is "Leave me alone") logical puzzles. The rules are as follows:
* You are presented with a n-by-n grid of cells, each cell contains an integer between 1 and n (inclusive).
* Your goal is to make sure that no number appear more than once in each row and each column of the grid, by removing numbers from the given grid, subject to the restriction indicated in the next two rules,
* You cannot remove two numbers from two adjacent (horizontally or vertically) cells.
* The remaining numbered cells must be all connected to each other. It means that any two remaining numbered cells can be connected with a curve that is composed solely of segments connecting adjacent remaining numbers (horizonally or vertically). (Thanks to @user202729 for pointing out that this is missing)
I hope the rules are clear by now. If there is anything unclear about the rules, check the [Wikipedia page](https://en.wikipedia.org/wiki/Hitori).
# Test Cases
The cells from which the numbers are removed are represented with 0s.
```
Input -> Output
4
2 2 2 4 0 2 0 4
1 4 2 3 -> 1 4 2 3
2 3 2 1 2 3 0 1
3 4 1 2 3 0 1 2
4
4 2 4 3 0 2 4 3
4 1 1 2 -> 4 1 0 2
3 1 2 1 3 0 2 1
4 3 1 3 0 3 1 0
5
1 5 3 1 2 1 5 3 0 2
5 4 1 3 4 5 0 1 3 4
3 4 3 1 5 -> 3 4 0 1 5
4 4 2 3 3 4 0 2 0 3
2 1 5 4 4 2 1 5 4 0
8
4 8 1 6 3 2 5 7 0 8 0 6 3 2 0 7
3 6 7 2 1 6 5 4 3 6 7 2 1 0 5 4
2 3 4 8 2 8 6 1 0 3 4 0 2 8 6 1
4 1 6 5 7 7 3 5 -> 4 1 0 5 7 0 3 0
7 2 3 1 8 5 1 2 7 0 3 0 8 5 1 2
3 5 6 7 3 1 8 4 0 5 6 7 0 1 8 0
6 4 2 3 5 4 7 8 6 0 2 3 5 4 7 8
8 7 1 4 2 3 5 6 8 7 1 4 0 3 0 6
9
8 6 5 6 8 1 2 2 9 8 0 5 6 0 1 2 0 9
5 6 2 4 1 7 9 8 3 5 6 2 4 1 7 9 8 3
5 8 2 5 9 9 8 2 6 0 8 0 5 0 9 0 2 0
9 5 6 6 4 3 8 4 1 9 5 6 0 4 3 8 0 1
1 1 6 3 9 9 5 6 2 -> 0 1 0 3 9 0 5 6 2
1 1 4 7 3 8 3 8 6 1 0 4 7 0 8 3 0 6
3 7 4 1 2 6 4 5 5 3 7 0 1 2 6 4 5 0
3 3 1 9 8 7 7 4 5 0 3 1 9 8 0 7 4 5
2 9 7 5 3 5 9 1 3 2 9 7 0 3 5 0 1 0
```
These test cases are taken from [Concept Is Puzzles](http://www.conceptispuzzles.com/index.aspx?uri=puzzle/euid/010000009ca896ef2fb6a5a4b63d1dd96e51c0295f72a24561f98409baf064ecfb79f6bba827f62665d86d96d267ca4f6bc6bf07/play), [PuzzleBooks](http://www.puzzlebooks.net/images/puzzles/solutions/070871f80140c9de6463dcb95c66c8a4.png), [Concept Is Puzzles](http://www.conceptispuzzles.com/index.aspx?uri=puzzle/hitori/rules), [Wikipedia](https://en.wikipedia.org/wiki/Hitori), and [Youtube](https://www.youtube.com/watch?v=iaAdKqT2TVo), respectively.
# Specs
* No need to worry about exception handling.
* You **can** assume that the input is always a valid puzzle with a **unique** solution and you can take advantage of this in writing your code.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the lowest number of bytes wins.
* 4 <= n <= 9 (16 originally, changed to 9 following Stewie Griffin's suggestion, also save some trouble in IO)
* You can take input and provide output through [any standard form](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), and you are free to choose the format.
* Some suggestions for the output format are (but you are not restricted to these)
+ Outputting the final grid
+ Outputting the grid containing all removed numbers
+ Output a list of coordinates of one of the above
* As usual, [default loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply here.
---
Related(inspired by this challenge): [Check if All Elements In a Matrix Are Connected](https://codegolf.stackexchange.com/questions/154363/check-if-all-elements-in-a-matrix-are-connected)
My last challenge: [Extension of the Game of Sevens](https://codegolf.stackexchange.com/questions/154147/extension-of-the-game-of-sevens)
[Answer]
# [Haskell](https://www.haskell.org/), 374 bytes
```
import Data.Array;import Data.List;r=range;p=partition
c(e,f)=p(\(b,p)->any(==1)[(b-d)^2+(p-q)^2|(d,q)<-e])f
n#g=[s|(o,(e:f))<-[p((==0).(g!))$indices g],
null.fst$c(o,o),null.snd$until(null.fst)c([e],f),
s<-case[((l,c),d)|((l,c),h)<-assocs g,h>0,
d<-[filter((==h).(g!))$r((l,c+1),(l,n))++r((l+1,c),(n,c))],d/=[]]
of[]->[g];((c,d):_)->n#(g//[(c,0)])++n#(g//[(c,0)|c<-d])]
```
[Try it online!](https://tio.run/##bVHbbtswDH33V3hIHkiETmLn4jiJAwzYy4D9gaYVrm8R6squ5DwUyL9nlJIWBTYQpMTDc0haPhf2pe662029Dr0Zwx/FWMy/G1O8H74iv5QdDyY3hW7rw5APhRnVqHodlFBTg/kAv@GZBoxOhX6HPI9RwHNU4Z9kBkP0xucVKnrDY1RLbAI9aXNhr9AT1PsGGRYDsGyJc2i/IU6VrlRZ27CVFIT60nXzxo7TkgU9ks@trqYXPaoOPspYgqglb8MSe4zKwtYCoKMSqcLr43bmWYW1fcm96XxaMrfi6Y3qxtq4Fc4fKxivmMVIfGrE2cwhs9h1Ac0RJVWLXEgZhH0jZHQSrTwAlDxt/8QvoSfQLhaCgSVKln/Nr@UxqiTKWxSFMMH9/qceo5N/dwC@EzuiB8V/UBm8Fkrng1F6nGql66DpLyZfTzr@Tw9@TG71Na0RRULO1hSzJ7R6eMzRYYkMXI88@1eeUcbyHW1pw75zZLbMZ/eGKWc7brThmHDMfJ5w/c7aMmvFiOM623KWfXaI/UqpZzh31fS@lFdu2FZsse@a@trGb5D6ipvHnyFvfwE "Haskell – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 133 bytes[SBCS](https://github.com/abrudz/SBCS)
```
{q←{⊢/4 2⍴⍵}⌺3 3⋄g←⍵=⊂∪,⍵⋄⍵×~1⊃{((⌈/q b)⌈b<{2<≢∪0,,(⍵×⊢⌈⌈/∘q)⍣≡⍵×(⍴⍵)⍴1+⍳≢,⍵}¨~b∘⌈¨⊂⍤2∘.≡⍨⍳⍴b)(+/↑w<g×⌈.⌈⍨w×g)⌈w b←⍵}⍣≡×\(⌈/=∘⌽⍨q⍵)0}
```
[Try it online!](https://tio.run/##RVDNbhMxEL7zFHvbDQ3JeOyxvSh9Ey6JaKKKKCFRpQhF2wOgKg3ZCg4oHCHlEHElXJC4NG/iFwmfvZUq7/pn5vuz@2/HL16/64@no1O4@3o5DTef6TTEvJzFKax3XZNxqA@h/lOFzV@d6fDp4wg9FM7D@n1Y/WpjiyLm4/ZahfWHZVGEzao7ywYtrIPeknvhdgcktdtFgkEXnQgKq2@zVqjvw@2P1CkaL5QO6izUv0GM@tXD/noALCgP@2hb/2QcO4m2j7j6MGgVZ91w82XRG8Fhs@pEi3q/OG5HMcciGzSxq8buuH2VYp4n2X9AzqIxVafTVbz7BFNHnqPeEejhAuma/ewiyjxGWO84m2STFPoOyRLkAuA5QMOs/zIf9i/HOUjZvED9@7wFQD59k1fPrnJmNsqwxlDaKCamxzMpfJwDY9igpVgrVkajnM4ECCvSiiJGCbpioIGhxEACiljRIBZKDUIBBqmRWMYrq1mcto6VFZCMZ2@VwcE5LQ6eXuAs1mFnLBBinPcuZhRLnsCnhk8QhUfDJ3GkKf6RT@CTApie@GjZmMFbsV4xl2LxFK70WjxLWXq2KFmjPe6OmGUEKGWc9tpb7fBY1ohorUrvnBEunWgplfZww8vRkyBiCpWUSgRBUhi6pChIxhEQEKQkSBQFqREkjZej/D8 "APL (Dyalog Unicode) – Try It Online")
My implementation of rule #4 (cells must form a single connected component) is rather wasteful, but still this passes all tests in about 10 seconds on TIO.
---
The overall algorithm: Store two boolean matrices `b` and `w` for cells that are certain to be black and white respectively. Initialise `b` as all-zero. Initialise `w` as 1 only for those cells that have opposite matching neighbours.
Repeat until `b` and `w` settle down:
* add to `b` cells that are on the same line (horizontal or vertical) and of the same value as a cell in `w`
* add to `w` the immediate neighbours of all cells in `b`
* add to `w` all cutpoints - cells whose removal would split the graph of non-black cells into multiple connected components
Finally, output `not(b)` multiplied by the original matrix.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 62 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Uses [user202729's isConnected monadic link](https://codegolf.stackexchange.com/a/154447/53748) from another question.
---
```
FJṁa@µ«Ḋoµ€ZUµ4¡ÐLFQL<3
ḟ0ĠḊ€
¬T€œ&2\;Ç€FȦ
ZÇȯÇ_1Ŀ
2ḶṗLṗLa⁸ÇÞḢ
```
A full program printing a representation of a list of lists.
Works by brute force and is stupidly inefficient.
**[Try it online!](https://tio.run/##y0rNyan8/9/N6@HOxkSHQ1sPrX64oyv/0NZHTWuiQg9tNTm08PAEH7dAHxtjroc75hscWQCUBspxHVoTAqSOTlYzirE@3A5kup1YxhV1uP3E@sPt8YZH9nMZPdyx7eHO6T4gnPioccfh9sPzHu5Y9P///@hoQx0FIyCK1VGINgIzjUFMYx0FkERsLAA "Jelly – Try It Online")** - a 3 by 3, since it is too inefficient to run even a size 4 within the 60 second TIO limit!
### How?
```
FJṁa@µ«Ḋoµ€ZUµ4¡ÐLFQL<3 - Link 1 isConnected? List of lists
... - 1 if connected 0 if not -- see linked answer in the header
ḟ0ĠḊ€ - Link 2, helperFor-AnyRepeatedValues: list
ḟ0 - filter out zeros
Ġ - group indices by value (i.e. [[indices of min],...,[indices of max]]
Ḋ€ - dequeue €ach -- leaving a list of empty lists iff no repeated values
- any remaining values are non-zero (1-based indexing in Jelly)
¬T€œ&2\;Ç€FȦ - Link 3, columnwiseAnyAdjacentZerosOrRowwiseAnyRepeatedValues: list of lists
¬ - logical not (convert all zeros to ones and all others to zeros)
T€ - for €ach row get a list of truthy indexes (i.e. indexes of original zeros)
2\ - pairwise reduction (i.e. for neighbouring rows) with:
œ& - intersection (empty if no columnwise adjacent original zeros
- any remaining values are non-zero due to 1-based indexing)
Ç€ - call last link (1) as a monad for €ach row
; - concatenate
F - flatten into a single list (empty iff no columnwise adjacent original zeros
- AND no rowwise repeated values)
Ȧ - any and all (0 if empty [or contains any zero -- never] else 1)
ZÇȯÇ_1Ŀ - Link 4, validity check? list of lists
Z - transpose
Ç - call last link (2) as a monad rowwiseAnyAdjacentZerosOrColumnwiseAnyRepeatedValues?
Ç - call last link (2) as a monad columnwiseAnyAdjacentZerosOrRowwiseAnyRepeatedValues?
ȯ - logical OR
1Ŀ - call link 1 as a monad (isConnected?)
_ - subtract
- this yields -1 for valid, while it yields 0 or 1 if not.
2ḶṗLṗLa⁸ÇÞḢ - Main link: list of lists
2Ḷ - lowered range of 2 -> [0,1]
L - length (number of rows in the input)
ṗ - Cartesian power (all lists of zeros and ones of length L)
L - length (number of rows in the input again)
ṗ - Cartesian power (all grids of zeros and ones of same shape as the input)
⁸ - the input
a - logical AND -- effectively uses each of the formed grids as a mask
Þ - sort by:
Ç - last link (3) as a monad
Ḣ - head
- implicit print
```
[Answer]
# Python3, 567 bytes:
```
E=enumerate
M=[(0,1),(0,-1),(1,0),(-1,0)]
V=lambda b:[(x,r,y,v)for x,r in E(b)for y,v in E(r)]
J=list.count
def C(b,x,y,s):
b=eval(str(b));b[x][y]=0
if b in s:return
t=[(x,y)for x,_,y,v in V(b)if v]
q=[t.pop()]
while q:
x,y=q.pop(0)
for X,Y in M:
if(N:=(x+X,y+Y))in t:q+=[N];t.remove(N)
if[]==t:return b
def f(b):
q,s=[b],[]
while q:
b=q.pop(0)
F=1
for x,r,y,v in V(b):
if v and(J(r,v)>1 or J([*[*zip(*b)][y]],v)>1):
F=0
if all(b[x+X][y+Y]for X,Y in M if 0<=x+X<len(b)and 0<=y+Y<len(r))and(B:=C(b,x,y,s)):q+=[B];s+=[B]
if F:return b
```
[Try it online!](https://tio.run/##bVHBbuIwED3XXzE3bHBRQkBahbqHrtoDUjlWIG9UxcVRI4UkOIYl@/PsjMmyu1IVyeN589688aTt/WdTJ99ad7k8K1sf99bl3rJXpXkkYyHxvKcQywjPewoZe1NVvje7HEyq@Vk62cuTKBoHeIeyhmduQorwNXUoWqmq7Pz0oznWnu1sAd@5kWeUdiJlYJQ95RXvvEOtWBp9znSfqYhBWYChLl3qrD@6moFX5NoPju9ysHlDJZJPGYOD0n7aNi1HX/j5WVYWDmiC7F4dQiESmFKDjdyS@JXK6MXXqeLnyUb2k60QWPDpYaL0Olv6qbP75mT5WtBQOlPKDyOBCQ8qcABsc5Cd0iaT@n9vc3O@w@xFxcMAw/7@vGCYA06Q1zu@4g5X@xgDEldcj/X4V9nysRG0nSyUrgpsGIWI0ryqOC5wskHSZJv9@0oqRw8Kaw@VrdEOTQhAXgCcIIQ/perv3xFhA0/ZsguBBY@X29MvXQwKRqMRmwF9cxbDHGOCeYIxZgnmMcwYcbrZQCbKHElUomJCJ5IRw1tyJScDOYZFgGdsEXphx9CVsAVKgl9wJCbmQU7/xDfvpsndjmPETd0NU2s93uctL2svoZx2bVV6LkRYVUmLKsrKW8fXTW0loHSgjH7UI6Qx1jqU8oLf2nexEOILePY1nCB8@Q0)
] |
[Question]
[
In this challenge, you'll calculate how great your land is.
---
Write a program or function that calculates the size of your land, given a wall you have built. You're given a non-empty input string containing a set of 4 distinct characters of your choice that represent the four directions "up", "down", "left" and "right" (I'll use `^ v < >` in this challenge). It's not possible to take 180 degree turns (`<>` or `^v`), but you may cross your wall.
The way you "capture" land is by encircling it with your wall. The wall itself is also considered part of your land. A few examples will make it more clear. I'll use `o` for land that has been encircled by the wall, `x` for the wall itself, and `S` for the starting point of the wall, just to illustrate how the wall is built. The output should be the total size of your land (the number of `o`, `x` and `S` in the test cases below).
```
Input: >>>>
Land: Sxxxx
Output: 5
Input: <<<^^^>>>vv
Land:
xxxx
xoox
xoox
xxxS
Output: 16
Input: <<<^^^>>>v
Land:
xxxx
x x
x
xxxS
Output: 11
Input: <
Land: xS
Output: 2
Input: >>>>>>vvvvvvvvv<<<<<^^^^>>>>>>>>vvvvvvvvvv<<<<<<<<<<<<<<<^^^^^^^^^>>>vvvvvv<<<<<
Land:
Sxxxxxx
x
x
x
x
xxxxxxxxx
xxxx xoooox x
xoox xoooox x
xoox xoooox x
xoox xxxxxx x
xoox x
xoox x
xxxxxx x
x x
x x
xxxxxxxxxxxxxxxx
Output: 101
Input: >>vvvv>>^^<<<<^
Land:
Sxx
xox
xxxxx
xox
xxx
Output: 17
Input: <<^^^>>>vv
Land:
xxxx
x x
x x
xxS
Output: 11 <- Note, diagonal edges do not close the "loop"
```
**Clarifications:**
* You do not need to draw the wall, the output should only be an integer
* The input format is optional. You may take a string with `<>^v`, a list of digits, `(1, -1, i, -i)`, a list of characters `ABCD` etc.
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code *in each language* wins. Remember, explanations are important, even in "regular" languages!
[Answer]
# [Python 2](https://docs.python.org/2/), ~~385~~ ~~345~~ 332 bytes
```
A,I,R=max,min,range
a=b=0
p=[[a,b]]
for i in input():a+=i%2*(2-i);b+=(1-i%2)*(1-i);p+=[a,b],
k,l=zip(*p)
x=A(k)-I(k)+3
y=A(l)-I(l)+3
o=[[1]*y for _ in' '*x]
def g(m,n):
if 0<o[m][n]and[m+I(k)-1,n+I(l)-1]not in p:o[m][n]=0;[g(i,j)for i in R(A(0,m-1),I(x,m+2))for j in R(A(0,n-1),I(y,n+2))if(i,j)!=(m,n)]
g(0,0)
print sum(map(sum,o))
```
[Try it online!](https://tio.run/nexus/python2#lY8xa8MwEIV3/Qp1KNFZZ5DszamGjF6zClEUEhslkSxSB5L@@VRyS9sUHCh86Hjc6b272wpbXCtvL@hdwJMN/Y5YtVGCRKW1xY0xpBtO1FEXEvE8MmgsV@65KlhVOlhuuGKyTBqKXGEZuZo@IjngUb27yIoI5KJW7ABlmx5ek2tSx6yOWQ0pSpriSnPSa4pZ0EVxMWS762jPPAZoCHUdFS@D9kYHY8NWe569SomBZ5tSmjCMecvYfE0psdQ9c7iH7wvWbMUE@lICtizdzCuYmvufZvhsXpNvarpuMnhS0xqG9GlCAIknF0b6dvbM28hSxQHgdtMC6R/kPNU99S/EDPI/ho@p53kQd2diPgA "Python 2 – TIO Nexus") or [Try all test cases](https://tio.run/nexus/python2#XU9BTsMwELznFeaAbCcbFBcBUhtH6rFXrpaD3KYphtqJQlu1fL6sHWiBPXi1M@PZ2XOzbknLXvk0IXNYwLN05gjOehiM36wTYuRSFgnppVIGllonpO0GYon15HVqMmlvJymb5JbPlplkIseZp6HzWZ/J@AcS8g5b@Wl7lvY8IUc5Z@88X@CT3SfkhOM2jNs4drhJ6PQU97zgHkpoesS9IemGOfAhK7EtKcpOOa28Nr5RLgt@uQCfBadcaN/tQsp@@q2SxUxtmIU3frngmc1ZAS4XHBYMz84mPJJvV9KP5Al9kbRtNLiRMQeG2qCkwJuG9W4/ePKxd8yZnmGHjvNz3ARDsLO@3@9YyN4P1mM0aKN0a9yyMWQ1pdWhrOmd9c36yFYcLOdSDmelaIVF4UGDomVZ1nWN8@FAQTz@hRAREaEwCb2KdfipshyldVX9Y0bqWvVPXUQRRv9CjMYBq6q6jmrEn8Ykv7IJrb8A "Python 2 – TIO Nexus")
Input is numerical, 0~3, the 0-index of the symbols here: `>v<^`
```
#starting position
a,b=0
#new list to hold the wall coordinates
p=[[a,b]]
#iterate over the input calculating
#the next coordinate and storing on p
for i in input():
a=a+i%2*(2-i)
b=b+(1-i%2)*(1-i)
p+=[[a,b]]
#i%2*(2-i) and (1-i%2)*(1-i) generate the increment
#of each symbol from last position
# >/0 : (0,1)
# v/1 : (1,0)
# </2 : (0,-1)
# ^/3 : (-1,0)
#transpose the coordinate list
k,l=zip(*p)
#calculate the difference between the max and min values
#to generate the total land size
#adding a border to avoid dead-ends
x=max(k)-min(k)+3
y=max(l)-min(l)+3
#create a matrix of 1's with the total land size
o=[([1]*y) for _ in ' '*x]
#recursive function that sets a cell to 0
#and call itself again on all surrounding cells
def g(m,n):
#correct the indexes (like negative ones)
a,b=m+min(k)-1,n+min(l)-1
#if this cell contains 1 and don't belong to the wall
if o[m][n]>0 and (a,b) not in p:
#sets to 0
o[m][n]=0
#call again on surrounding cells
for i in range(max(0,m-1),min(x,m+2)):
for j in range(max(0,n-1), min(y,n+2)):
if (i,j)!=(m,n):g(i,j)
#call the recursive function o origin
g(0,0)
#print the sum of the cells
print sum(map(sum,o))
```
This is the resulting matrix:
```
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, **1**, **1**, **1**, **1**, **1**, **1**, **1**, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, **1**, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, **1**, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, **1**, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, **1**, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, **1**, **1**, **1**, **1**, **1**, **1**, **1**, **1**, **1**, 0]
[0, 0, 0, **1**, **1**, **1**, **1**, 0, 0, 0, **1**, **1**, **1**, **1**, **1**, **1**, 0, 0, **1**, 0]
[0, 0, 0, **1**, **1**, **1**, **1**, 0, 0, 0, **1**, **1**, **1**, **1**, **1**, **1**, 0, 0, **1**, 0]
[0, 0, 0, **1**, **1**, **1**, **1**, 0, 0, 0, **1**, **1**, **1**, **1**, **1**, **1**, 0, 0, **1**, 0]
[0, 0, 0, **1**, **1**, **1**, **1**, 0, 0, 0, **1**, **1**, **1**, **1**, **1**, **1**, 0, 0, **1**, 0]
[0, 0, 0, **1**, **1**, **1**, **1**, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, **1**, 0]
[0, 0, 0, **1**, **1**, **1**, **1**, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, **1**, 0]
[0, **1**, **1**, **1**, **1**, **1**, **1**, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, **1**, 0]
[0, 0, 0, **1**, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, **1**, 0]
[0, 0, 0, **1**, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, **1**, 0]
[0, 0, 0, **1**, **1**, **1**, **1**, **1**, **1**, **1**, **1**, **1**, **1**, **1**, **1**, **1**, **1**, **1**, **1**, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
```
[Answer]
# Octave, ~~83~~ ~~85~~ ~~83~~ 79 bytes
```
@(p)nnz(bwfill(accumarray([real(c=cumsum([0;p])) imag(c)]+nnz(p)+1,1),"holes"))
```
[Try it on Octave Online!](http://octave-online.net/#cmd=p%3D%5Bi%3Bi%3Bi%3Bi%3Bi%3Bi%3B1%3B1%3B1%3B1%3B1%3B1%3B1%3B1%3B1%3B-i%3B-i%3B-i%3B-i%3B-i%3B-1%3B-1%3B-1%3B-1%3Bi%3Bi%3Bi%3Bi%3Bi%3Bi%3Bi%3Bi%3B1%3B1%3B1%3B1%3B1%3B1%3B1%3B1%3B1%3B1%3B-i%3B-i%3B-i%3B-i%3B-i%3B-i%3B-i%3B-i%3B-i%3B-i%3B-i%3B-i%3B-i%3B-i%3B-i%3B-1%3B-1%3B-1%3B-1%3B-1%3B-1%3B-1%3B-1%3B-1%3Bi%3Bi%3Bi%3B1%3B1%3B1%3B1%3B1%3B1%3B-i%3B-i%3B-i%3B-i%3B-i%5D%3Bbin%20%3D%7E%7Eaccumarray(%5Breal(c%3Dcumsum(%5B0%3Bp%5D))%20imag(c)%5D%2Bnnz(p)%2B1%2C1)%3B%27%20*%27(bin%2B1)%2Cfilled%20%3D%20bwfill(bin%20%2C%20%22holes%22)%3B%27%20*%27(filled%2B1)%2Cresult%20%3D%20nnz(filled))
A function that takes as input a column vector containing `(1, -1, i, -i)`
Using approach of @lanlock4 's Mathematica answer adding length of the input to coordinates to avoid non positive coordinates, instead of subtracting min of coordinates from them. Saved 4 bytes.
Previous answer:
```
@(p)nnz(bwfill(accumarray((k=[real(c=cumsum([0;p])) imag(c)])-min(k)+1,1),"holes"))
```
[Try it on Octave Online!](http://octave-online.net/#cmd=p%3D%5Bi%3Bi%3Bi%3Bi%3Bi%3Bi%3B1%3B1%3B1%3B1%3B1%3B1%3B1%3B1%3B1%3B-i%3B-i%3B-i%3B-i%3B-i%3B-1%3B-1%3B-1%3B-1%3Bi%3Bi%3Bi%3Bi%3Bi%3Bi%3Bi%3Bi%3B1%3B1%3B1%3B1%3B1%3B1%3B1%3B1%3B1%3B1%3B-i%3B-i%3B-i%3B-i%3B-i%3B-i%3B-i%3B-i%3B-i%3B-i%3B-i%3B-i%3B-i%3B-i%3B-i%3B-1%3B-1%3B-1%3B-1%3B-1%3B-1%3B-1%3B-1%3B-1%3Bi%3Bi%3Bi%3B1%3B1%3B1%3B1%3B1%3B1%3B-i%3B-i%3B-i%3B-i%3B-i%5D%3Bbin%20%3D%7E%7Eaccumarray((k%3D%5Breal(c%3Dcumsum(%5B0%3Bp%5D))%20imag(c)%5D)-min(k)%2B1%2C1)%3B%27%20*%27(bin%2B1)%2Cfilled%20%3D%20bwfill(bin%20%2C%20%22holes%22)%3B%27%20*%27(filled%2B1)%2Cresult%20%3D%20nnz(filled))
Changed for better visualization.
Explanation:
```
%compute position of walls
c= cumsum([0;p]) % p should be top padded with a 0
row = real(c);
col = imag(c);
k = [row col];
%offset positions so all positions become positive
pos = k - min(k) +1;
%create a binary array that is 1 for walls and 0 elsewhere
bin = ~~accumarray(pos,1);
*******
*
*
*
*
*********
**** * * *
* * * * *
* * * * *
* * ****** *
* * *
* * *
****** *
* *
* *
****************
%use flood fill to fill holes
filled = bwfill(bin, 'holes');
*******
*
*
*
*
*********
**** ****** *
**** ****** *
**** ****** *
**** ****** *
**** *
**** *
****** *
* *
* *
****************
%count number of ones in the filled image
result = nnz(filled)
```
[Answer]
# Haskell, ~~579~~ 530 bytes
```
y=length
i=filter
u i e l=take i l++[e]++drop(i+1)l
k v(r,c)g=u r(u c v(g!!r))g
b(r,c)g=g!!r!!c
w(r,c)s g=case s of{""->j;'<':t->w(r,c-1)t j;'>':t->w(r,c+1)t j;'v':t->w(r+1,c)t j;'^':t->w(r-1,c)t j}where j=k 2(r,c)g
e[]v g=g;e(x:d)v g|elem x v||b x g/=1=e d v g|b x g==1=e(d++(i(\x->notElem x v)$i(\(r,c)->r>=0&&c>=0&&r<y g&&c<y(g!!0))$a x))(x:v)(k 0 x g)
a(r,c)=[(r+1,c+1),(r+1,c),(r+1,c-1),(r,c+1),(r,c-1),(r-1,c+1),(r-1,c),(r-1,c-1)]
m s=(y.i(/=0).concat.e[(0,0)][])(w(l+1,l+1)s(map(\_->map(\_->1)q)q))where l=y s;q=[0..2*l+2]
```
`m` is the main function, which takes a string over `v^<>`, and returns the appropriate integer.
### Ungolfed:
```
import Data.Set hiding (map, filter)
-- Generate a grid full of ones, of width and height 2x+1. We pass the length of
-- the input, and get back a grid that we could never go out of bounds from,
-- even when the input is a straight wall in any direction.
genGrid :: Int -> [[Int]]
genGrid x = map (\_->map(\_->1) [0..2*x+2]) [0..2*x+2]
-- Update the value of a list l, such that index i now contains the value e
update :: Int -> a -> [a] -> [a]
update i e l = take i l ++ [e] ++ drop (i+1) l
-- scale update to two dimensions
set :: a -> (Int, Int) -> [[a]] -> [[a]]
set val (r,c) g = update r (update c val (g !! r)) g
-- index into a 2D array
at :: (Int, Int) -> [[a]] -> a
at (r,c) g = g !! r !! c
-- Walk the wall path. Replace any 1 we step on with a 2. Start walking from
-- given coordinates, recursively updating the spot we step on as we process
-- the input string.
walk :: (Int, Int) -> String -> [[Int]] -> [[Int]]
walk (r,c) s g = case s of
"" -> set 2 (r,c) g
'<':t -> walk (r,c-1) t (set 2 (r,c) g)
'>':t -> walk (r,c+1) t (set 2 (r,c) g)
'v':t -> walk (r+1,c) t (set 2 (r,c) g)
'^':t -> walk (r-1,c) t (set 2 (r,c) g)
-- Given an input string, generate a grid of appropriate size and walk out the
-- wall path starting at the center.
sketch :: String -> [[Int]]
sketch s = let l = length s in walk (l+1,l+1) s (genGrid l)
-- Breadth-first exploration of the 2D grid, but do not pass through walls.
-- Will touch everything that's not part of the land, and mark it as not part
-- of the land. We use a set (a list in the golfed version) to keep track
-- of which coordinates we've already explored.
explore :: [(Int, Int)] -> Set (Int, Int) -> [[Int]] -> [[Int]]
explore [] v g = g
explore (x:cs) v g
| member x v = explore cs v g
| at x g == 2 = explore cs v g
| at x g == 0 = explore cs v g
| at x g == 1 =
explore (cs ++ (filter (\x-> notMember x v) $ filtBound g $ adj x))
(insert x v) (set 0 x g)
-- Count everything marked as land to get the final total
countLand :: [[Int]] -> Int
countLand = length . filter (/=0) . concat
-- for a given list of coordinates and a 2D grid, filter those coordinates that
-- are within the grid's bounds
filtBound :: [[Int]] -> [(Int, Int)] -> [(Int, Int)]
filtBound g = filter (\(r,c) -> r >= 0 && c >= 0 && r < length g && c < length (g !! 0))
-- Given a coordinate, get all the adjacent coordinates, including diagonally
-- adjacent coordinates.
adj :: (Int, Int) -> [(Int, Int)]
adj (r,c) = [(r+1,c+1),(r+1,c),(r+1,c-1),(r,c+1),(r,c-1),(r-1,c+1),(r-1,c),(r-1,c-1)]
-- The main function
runMain :: String -> Int
runMain = countLand . explore [(0,0)] empty . sketch
-- Print a grid (for debugging & REPL convenience)
printG :: [[Int]] -> String
printG = concat . map ('\n':) . map show
```
[Answer]
## Mathematica, 124 bytes
You probably won't be surprised to learn that Mathematica has a built-in function for measuring the area encircled by a wall. Unfortunately, it's quite bytey: `ComponentMeasurements[..., "FilledCount", CornerNeighbors -> False]`.
With that in mind, here's my full answer. It's a function that takes a list of 1, i, -1 or -i:
```
1/.ComponentMeasurements[SparseArray[{Re@#,Im@#}&/@FoldList[#+#2&,2(1+I)Length@#,#]->1],"FilledCount",CornerNeighbors->1<0]&
```
Explanation:
* `FoldList[#+#2&,2(1+I)Length@#,#]` builds the wall by starting at coordinate 2(1+i)(length of wall) and successively adding the elements of the input list. (We have to start at the ridiculously large coordinate 2(1+i)(length of wall) to ensure that the wall coordinates stay positive, otherwise things break.)
* `SparseArray[{Re@#,Im@#}&/@...->1]` turns these coordinates from complex numbers to pairs of integers, and makes an array with 1s where the wall is and 0s elsewhere.
* `1/.ComponentMeasurements[...,"FilledCount",CornerNeighbors->1<0]&` uses built-in Mathematica magic to measure the area enclosed by the wall.
[Answer]
# PHP>=5.6.2, 888 Bytes
[Online Version](http://sandbox.onlinephpfunctions.com/code/ac3cae51bccd98a1f2511ce613d3bb40362335ad)
```
<?$h=$v=0;
s($v,$h,S);
for($z=0;$z<strlen($i=$_GET[0]);){
2<($b=$i[$z++])?$h--:($b>1?$v++:($b?$h++:$v--));
$e=max($h,$e);
$w=min($h,$w);
$n=min($v,$n);
$s=max($v,$s);
s($v,$h,X);}
$f=($e-$w+1)*($s-$n+1);
ksort($a);
function i($v,$h){global$a;return isset($a[$v][$h])&&$a[$v][$h]==" ";}
function s($v,$h,$l=" "){global$a;$a[$v][$h]=$l;}
function c($v,$h,$n=1){global$a;
foreach($r=range(-1,$n)as$i)
foreach($r as$j)
if(($i+$j)&&i($v+$i,$h+$j)){if($n)s($v,$h);return 1;}return;}
foreach($a as$v=>$z){
foreach(range($w,$e)as$h){
if(!isset($a[$v][$h])){
if(($v==$s)||($v==$n)||($h==$e)||($h==$w)||c($v,$h,0))s($v,$h);
else$c[]=[$v,$h];}
}ksort($a[$v]);}
while($z){$z=0;
foreach($c as$b=>$w){if(c(...$w)){$z++;unset($c[$b]);}}};
foreach($c as$b=>$w)$a[$w[0]][$w{1}]=O;
foreach($a as $k=>$v){ksort($a[$k]);$g.=join($a[$k])."\n";}echo $g;
echo $f-substr_count($g," ");
```
] |
[Question]
[
As part of its compression algorithm, the JPEG standard unrolls a matrix into a vector along antidiagonals of alternating direction:
[](https://i.stack.imgur.com/KU5Iu.png)
Your task is to take the unrolled vector along with the matrix dimensions and reconstruct the corresponding matrix. As an example:
```
[1, 2, 5, 9, 6, 3, 4, 7, 1, 2, 8, 3], 4, 3
```
should yield
```
[1 2 3 4
5 6 7 8
9 1 2 3]
```
whereas dimensions `6, 2` would give
```
[1 2 6 3 1 2
5 9 4 7 8 3]
```
## Rules
You may choose to take only one of the dimensions as input. The individual inputs can be taken in any order. You may assume that the width and height are positive and valid for the given vector length.
You may assume that the vector elements are positive integers less than `10`.
You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.
The input vector may be given in any convenient, unambiguous, flat list or string format.
The output matrix may be in any convenient, unambiguous, nested list or string format, or as a flat list along with both matrix dimensions. (Or, of course, as a matrix type if your language has those.)
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
## Test Cases
Each test case is of the form `vector width height => matrix`.
```
[1] 1 1 => [[1]]
[1 2 3 1] 2 2 => [[1 2] [3 1]]
[1 2 3 1] 4 1 => [[1 2 3 1]]
[1 2 5 9 6 3 4 7 1 2 8 3] 3 4 => [[1 2 3] [5 6 4] [9 7 8] [1 2 3]]
[1 2 5 9 6 3 4 7 1 2 8 3] 4 3 => [[1 2 3 4] [5 6 7 8] [9 1 2 3]]
[1 2 5 9 6 3 4 7 1 2 8 3] 6 2 => [[1 2 6 3 1 2] [5 9 4 7 8 3]]
[1 2 5 9 6 3 4 7 1 2 8 3] 12 1 => [[1 2 5 9 6 3 4 7 1 2 8 3]]
[1 2 5 9 6 3 4 7 1 2 8 3] 1 12 => [[1] [2] [5] [9] [6] [3] [4] [7] [1] [2] [8] [3]]
```
## Related Challenges
* [Zigzagify a Matrix](https://codegolf.stackexchange.com/q/75587/8478) (the somewhat simpler inverse transformation)
* [Rotate the anti-diagonals](https://codegolf.stackexchange.com/q/63755/8478)
[Answer]
# Jelly, ~~18~~ 13 bytes
```
pS€żị"¥pỤỤị⁵s
```
Takes number of rows, number of columns and a flat list as separate command-line arguments.
My code is almost identical to [the one in the twin challenge](https://codegolf.stackexchange.com/a/75590). The only differences are an additional `Ụ` (which inverts the permutation of the indices) and an `s` (to split the output into a 2D array).
[Try it online!](http://jelly.tryitonline.net/#code=cFPigqzFvOG7iyLCpXDhu6Thu6Thu4vigbVz&input=&args=NA+Mw+WzEsIDIsIDUsIDksIDYsIDMsIDQsIDcsIDEsIDIsIDgsIDNd)
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 29 bytes
```
:!i:+-1y^8MtsQ/*-X:4#S2$S1GZC
```
Input is `height`, `width`, `vector` separated by newlines.
This reuses part of the code in [my answer to the related challenge](https://codegolf.stackexchange.com/a/75595/36398).
[**Try it online!**](http://matl.tryitonline.net/#code=OiFpOistMXleOE10c1EvKi1YOjQjUzIkUzFHWkM&input=Mwo0ClsxIDIgNSA5IDYgMyA0IDcgMSAyIDggM10)
### Explanation
```
:! % take number of rows, r, as input. Generate column vector [1;2;...;r]
i: % take number of columns, c, as input. Generate row vector [1,2,...,c]
+ % add with broadcast. Gives 2D array
-1 % push -1
y^ % duplicate previous 2D array. Compute -1 raised to that
8M % push [1;2;...;r] again
tsQ/ % divide by its sum plus 1
* % multiply
- % subtract
X: % linearize 2D array into column array
4#S % sort and push the indices of the sorting. Gives a column vector
2$S % take vector as input. Sort it according to previous column vector
1G % push r
ZC % reshape into columns of r elements
```
[Answer]
# J, 24 bytes
```
]$({~[:/:@;[:<@|.`</.i.)
```
Also uses the oblique adverb `/.` to perform zigzagify as in the J [answer](https://codegolf.stackexchange.com/a/75594/6710) from that [challenge](https://codegolf.stackexchange.com/questions/75587/zigzagify-a-matrix).
## Usage
Input is with the array on the LHS and the dimensions `[height, width]` on the RHS.
```
f =: ]$({~[:/:@;[:<@|.`</.i.)
1 f 1 1
1
1 2 3 1 f 2 2
1 2
3 1
1 2 5 9 6 3 4 7 1 2 8 3 f 4 3
1 2 3
5 6 4
9 7 8
1 2 3
1 2 5 9 6 3 4 7 1 2 8 3 f 3 4
1 2 3 4
5 6 7 8
9 1 2 3
1 2 5 9 6 3 4 7 1 2 8 3 f 2 6
1 2 6 3 1 2
5 9 4 7 8 3
1 2 5 9 6 3 4 7 1 2 8 3 f 1 12
1 2 5 9 6 3 4 7 1 2 8 3
1 2 5 9 6 3 4 7 1 2 8 3 f 12 1
1
2
5
9
6
3
4
7
1
2
8
3
```
## Explanation
```
]$({~[:/:@;[:<@|.`</.i.) Input: list A (LHS), dimensions D (RHS)
i. Range shaped to D
[:<@|.`</. Zigzagify that matrix
[: ; Raze the boxes to get a zigzagify permutation
/:@ Invert that permutation to get an unzigzagify permutation
{~ Apply that permutation to A
] Get D
$ Shape that permutation to D and return
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 36 bytes
```
{y#x@<,/((#c)#(|:;::))@'c:.=+/!y:|y}
```
[Try it online!](https://ngn.codeberg.page/k#eJyFj1EKgzAQRP/3FFv8MKGhsjFa3bTgT2/gDQTPUNH27N0VCwrVfu68TGam53FIns3NZcYknU3MxJHZ2ibt+HI/Z6eBp+EF0LIxjiIhWUA0hB5zpOjRb+6w4gXWWIoa8Ip6V5hHuQ55wPyQl6u8X5z8nwIywFsL8GDjHMH8UFqpyS0jYJkTC3GHWIu7irNiv0hkhQpq3CDN0y81W3OrGbmdOkLSHaQd332TpS18APpFSKA=)
Basically the same as [Zagify a matrix](https://codegolf.stackexchange.com/a/254384/111844) but with a grade.
] |
[Question]
[
The goal of this challenge is to write [a program or function](https://codegolf.meta.stackexchange.com/a/2422/30072) that returns the least amount of strikes needed to complete a given course.
### Input
* The layout of the course can be passed in any suitable way and format you prefer.
(read from the console, passed as an input parameter, read from a file or any other, multiline-string, string array, two-dimensional character/byte array).
* The start position of the ball and the hole can be passed as input too, it doesn't have to be parsed from the input. In the test-cases they are included in the course to make sure there is no confusion about the actual position.
* You can remap the input characters to something else, as long as they are still recognisable as distinct characters (e.g. printable ASCII characters).
### Output
* The program must return the lowest possible score (least amount of strikes needed to reach the hole) for any course passed as input in a sensible format (string, integer, float or a haiku describing the result)
* If the course is impossible to beat, return `-1` (or any other **falsy** value of your choice that wouldn't be returned for a beatable course).
### Example:
In this example positions are notated 0-based, X/Y, left-to-right, top-down - but you can use any format you like since the result is completely format-independent anyways.
Input:
```
###########
# ....#
# ...#
# ~ . #
# ~~~ . #
# ~~~~ #
# ~~~~ #
# ~~~~ o #
# ~~~~ #
#@~~~~ #
###########
Ball (Start-Position): 1/9
Hole (End-Position): 8/7
```
Output:
```
8
```
[](https://i.stack.imgur.com/CRZcI.png)
## Rules and fields
The course can consist of the following fields:
* `'@'` **Ball** - The start of the course
* `'o'` **Hole** - The goal of the course
* `'#'` **Wall** - Ball will stop when it hits a wall
* `'~'` **Water** - Must be avoided
* `'.'` **Sand** - Ball will stop on sand immediately
* `' '` **Ice** - Ball will continue to slide until it hits something
The basic rules and restrictions of the game:
* The ball can't move diagonally, only left, right, up and down.
* The ball will not stop in front of water, only in front of walls, on sand and in the hole.
+ Shots into the water are invalid/impossible
+ The ball will stay in the hole, not skip over it like it would on ice
* The course is always rectangular.
* The course is always bordered by water or walls (no boundary checks required).
* There is always exactly one ball and one hole.
* Not all courses are possible to beat.
* There might be multiple paths that result in the same (lowest) score.
## Loopholes and Winning Condition
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden
* [Programs must terminate](https://codegolf.meta.stackexchange.com/a/4785/30072)
* You can't make up additional rules (hitting the ball so hard it skips over water, rebounds off a wall, jumps over sand fields, curves around corners, etc.)
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the solution with the least amount of characters wins.
* Solutions must be able to handle all provided test-cases, if this is impossible due to restrictions of the used language please specify that in your answer.
## Test cases
Course #1 (2 strikes)
```
####
# @#
#o~#
####
```
Course #2 (not possible)
```
#####
#@ #
# o #
# #
#####
```
Course #3 (3 strikes)
```
~~~
~@~
~.~
~ ~
~ ~
~ ~
~ ~
~.~
~o~
~~~
```
Course #4 (2 strikes)
```
#########
#~~~~~~~#
#~~~@~~~#
## . ##
#~ ~ ~ ~#
#~. o .~#
#~~~ ~~~#
#~~~~~~~#
#########
```
Course #5 (not possible)
```
~~~~~~~
~... ~
~.@.~.~
~... ~
~ ~ ~.~
~ . .o~
~~~~~~~
```
### More Test cases:
<https://pastebin.com/Azdyym00>
[Answer]
# JavaScript (ES6), 174 bytes
Takes input in ~~curling~~ currying syntax `([x, y])(a)`, where **x** and **y** are the 0-indexed coordinates of the starting position and **a[ ]** is a matrix of integers, with `0` = ice, `1` = wall, `2` = sand, `3` = hole and `4` = water
Returns `0` if there's no solution.
```
p=>a=>(r=F=([x,y],n,R=a[y],c=R[x])=>R[c&(R[x]=4)|n>=r||[-1,0,1,2].map(d=>(g=_=>(k=a[v=Y,Y+=d%2][h=X,X+=~-d%2])||g())(X=x,Y=y)>3?0:k>2?r=-~n:F(k>1?[X,Y]:[h,v],-~n)),x]=c)(p)|r
```
[Try it online!](https://tio.run/##zVdbixoxFH73VxwIrRM2BnW3NyHjQKGvhX1ShqEMo3vpbh0Zt4uC5K/bzNWZ5CTOlj40giYn5/qdk5P4M36Nd0n2uH0ZbdLV@nQnTlvhx8L3MvFNeOGeHSK2YbciDtUkEbfhPqLCvw2T914@Fzf0uPFFdjyGowkbswmbRvxXvPVWSsW9@KG@n5Tsq1iy5ZVYvZtG4YNYsMWVkKN8RY/He49SbyH2bCkO1L@ej2dP/nSeiZHczL55T/5kHi7YMpqFD@w1YopKKVOGE@pt6TE7vax3LyAgBuGDN4B8AnHhgpcxWNKcnpXrhMGiWCcgBAyDIczB2yv@BYOD@lkyGFOYwRAIT@WQP25W6/33Oy@hyqRSfZfjAYeIejEd0MEgSTe79HnNn9N7b/g1/Z3t1kAmQwa5T16oJELO@ZCoMYxYs4Sgs0xlZ1kwDyJq0z9F9XdUBABdg6m21vYv2rw2bEopWxpk0Fnxzgr@ctXVknZWuXWHvzc4RjpOshw6LdBpCjCuIOvyQfHp0rhCmhv6ALFh2D3754jrA5YHqeVCfYGGZMA1NE2ePBgtbxy4jrq8hPxHO/JEr0GFqhomFUyqLMhaFefQotSCuz817cMboFTSL2@fHKjoxWLYUJni@YbppEkseHVxnpcgFqNEQuSpJUJngJ9daccGGjW0f6qBQ6GOZK0JqqkFn5YqjupsQMs/5WGVNusVkiUnr7UWHxzeklPadZaYl84RmYI99kt4OrLzpV87VBYD5IgY7Quj8SIKjvDBRRovokcQRGu@l2w/u/@RzxKxIfvb7eVzb1reEgH@zZU1GfdpDR3zvBz4MQD3sSfaWdd3CbhkK/lc2LJbnGpi7p6bi81u1REIrrl4drh25QW73BFvJWiL17VL3LupZZc0SGM@N02ekB5tzl1ek7fePIYvRkmR@iLSgzpXR3tWhtl9b5/D78xMVlI@Lts1CVVWMdZaY31TFgUpDdZ6s6ydisNxnpriDqpLq5TRwOJV3IhWol@V5Fx4BasdAd5BE5y4kvbF3wxbts4BNxOCa20OGZwfDihrFT3yTnnbdX2hqKe9itp8ONs7EJA6d1i6wMAK6aqkDaT@d7KrAFNOWsceda3xDXWtnqSWhh@AS9rmGnE@N7uiBI2b9JGu5JFact0ZbtQ00OAt5WAtyNMf "JavaScript (Node.js) – Try It Online")
### Commented
```
p => a => ( // given the starting position p[] and the matrix a[]
r = // r = best result, initialized to a non-numeric value
F = ( // F = recursive function taking:
[x, y], // (x, y) = current position
n, // n = number of shots, initially undefined
R = a[y], // R = current row in the matrix
c = R[x] // c = value of the current cell
) => //
R[ // this will update R[x] once the inner code is executed
c & (R[x] = 4) | // set the current cell to 4 (water); abort if it was
n >= r || // already set to 4 or n is greater than or equal to r
[-1, 0, 1, 2].map(d => // otherwise, for each direction d:
(g = _ => ( // g = recursive function performing the shot by
k = a[ // saving a backup (h, v) of (X, Y)
v = Y, Y += d % 2][ // and updating (X, Y) until we reach a cell
h = X, X += ~-d % 2]) // whose value k is not 0 (ice)
|| g() //
)(X = x, Y = y) // initial call to g() with (X, Y) = (x, y)
> 3 ? // if k = 4 (water -> fail):
0 // abort immediately
: // else:
k > 2 ? // if k = 3 (hole -> success):
r = -~n // set r to n + 1
: // else:
F( // do a recursive call to F():
k > 1 ? // if k = 2 (sand):
[X, Y] // start the next shots from the last cell
: // else (wall):
[h, v], // start from the last ice cell
-~n // increment the number of shots
) // end of recursive call
), x // end of map(); x = actual index used to access R[]
] = c // restore the value of the current cell to c
)(p) | r // initial call to F() at the starting position; return r
```
[Answer]
# [Python 3](https://docs.python.org/3/), 273 bytes
```
def p(g,c,d,k=0):
while 1>k:c+=d;k=g.get(c,9)
return-(k==2)or c-d*(k==3)
def f(g):
c={q for q in g if g.get(q,9)>4};I=0;s=[c]
while all(g.get(q,9)-4for q in c):
c={k for k in{p(g,k,1j**q)for k in c for q in range(4)}if-~k}
if c in s:return-1
s+=[c];I+=1
return I
```
[Try it online!](https://tio.run/##rVdLb@M4DD7Hv4KoLnabCnXaeSXwwMCeet9b0UPGcVJPsrZru9gGRfXXu3qLspV0F1hn4OrxkfxI0RSnPQ5PTX378bEpt9DGu3kx38z32U2yjGZ/P1WHEtKf@2VxlW1W@2xHd@UQF/MfSTTryuGlq6/jfZYtkqaD4npzKSa3SSRUbeOdUFFkb8@w5dvPUNWwg2oLSskzV/Lz7n11n92s@uyheDTm1odD7CDXd1a4EPqEwr1UuOdrb4Lwfp7@vrx8TswiFM5gt653ZXyXvFfba7Z/5/KcQCF2@qV2IOWL/ZVgsLq/ylLjGNx/KD5/di8lN1zV7csQJyvQg2i266oNZPBgmWvkbOiO4s@s57saTfuhq1ohJRnwnQwuLpbwqyvXe7EolNF125b1Jj5U/RD/tW7jC6CMNPkF3Vb1Zg59kggF5WtRtoO0oMVFUCUZwcYqbbuqHuJt/PYKV3CES0h/LyXu4fXx4fgog/TqgnQo61jsJoncOU53uFySvCfJxx/NS9eXQFKIF9A/NUOfRBHhD0QEcvFumHjzJ4oMeAFx3QzQNn1f/TqUWkLAcgAp2ag/auYL30J8ay0xxiBiuXhR8YLAS2404sWYU3M3JmwoMPXoYa6HnAvlbOQqyJ8cUs6UGiw4MaPBPM7ul4nvGi6YUm5DDnKqaNsVYVF5SIFqZ5jn0FeIv08dIjqOnD5/7ATshMmZCrdggSdy79Skme7keEICzn@D@GuAow6fkeQuUzG3@u1Y7mgMFQFHHJijQBufgSPwHeL0JhSl0OPRwn8Aplw53Mrp4cgB91CswXnFfyqJ2MiEcVUCqNEhf77/EsAmGlRQlGHCGph4cf5x4fsRDp/Kqtzlh/kS0JBKBtStwmhIJT3nED7/ACCk4f80wZwYO6UhYOLEUHwuAJ8WBx7cOF2cy0@hjKrHO0EI5h4ZJZxeJBBAarSA@osytYhddNk70qmTkHjisoQGFllYJ53y1LARz8AiCS42/iKx3iPr9ssm5PQXgU4p/S9VxJiYHBExRUUzc/HHI81V3ImOujeyCKJuKe9odWwRwsibSMsDZgZh1tQx6Y1pptnUyHXdUVDlLdUeBHQQXdKIO1qJmPhCvShAKB4E11wXbT@miLoZEE@HTUhwpRojtB@B8v@vaidOG972pF/Opo29nicfmIqczVOAEZZ4Hw5YPNIAo2ggDQR9AtiaXcPWzKDxa0wOAezIGgldoT6QYL7kDFaj3SEFilLQt9ESnI76@ePkjSivBCeOU/ay8oam7p52U9V9qTKu3yMEYIQTMWMfQbWYbheAmgYBISjWYf/5CMcDYUYI2kxDg6LC@@r02@e10XalfkPk15jRF@7nm00Pim8MV/eIK5Wi4ADBXRFOVeJmtrj5lyq6HgmMaYgAoaIYYohs6fsf1TvD0PHKAes@K3XOli1kDF2OZku36aEtgu8HRIOCFyhV3MdSJlB4i2EpXjfYhKG5lbDUab9sjUZvCGYU/bRKo8zl/zNbfNZ75a6c@dkKXr9iTsZ1K36Goisc1Sn5ozj1cGfjIamXiWc6P9UBjdLZBRxnEMXWwc/8UT0lOKO9lgbfYUrb@ARQ/xmR0RVx6qz@AQ "Python 3 – Try It Online")
-41 bytes thanks to ovs
-1 byte thanks to Jonathan Frech
[Answer]
# C#, ~~461~~ 418 bytes
This is just a non-competitive reference implementation to (hopefully) revive this challenge:
**Golfed by Kevin Cruijssen**
```
int P(string[]C){int w=C[0].Length,i=0,l=c.Length;var c=string.Join("",C);var h=new int[l];for(var n=new List<int>();i<l;n.Add(i++))h[i]=c[i]!='@'?int.MaxValue:0;for(i=1;;i++){var t=n;n=new List<int>();foreach(int x in t){foreach(int d in new[]{-1,1,-w,w}){for(int j=x+d;c[j]==' ';j+=d);if(c[j]=='#'&h[j-d]>s){h[j-d]=s;n.Add(j-d);}if(c[j]=='.'&h[j]>s){h[j]=s;n.Add(j);}if(c[j]=='o')return s;}}if(n.Count<1)return -1;}}
```
**Ungolfed**
```
int IceGolf(string[] course)
{
// Width of the course
int w = course[0].Length;
// Course as single string
var c = string.Join("", course);
// Array of hits per field
var hits = new int[c.Length];
// Fields to continue from
var nextRound = new List<int>();
// Initialize hits
for (int i = 0; i < hits.Length; i++)
{
if (c[i] != '@')
// All fields start with a high value
hits[i] = Int32.MaxValue;
else
{
// Puck field starts with 0
hits[i] = 0;
nextRound.Add(i);
}
}
for (int s = 1; ; s++)
{
// clear the fields that will be used in the next iteration
var thisRound = nextRound;
nextRound = new List<int>();
foreach (int i in thisRound)
{
// test all 4 directions
foreach (int d in new[] { -1, 1, -w, w })
{
int j = i+d;
// ICE - slide along
while (c[j] == ' ')
j += d;
// WALL - stop on previous field
if (c[j] == '#' && hits[j-d] > s)
{
hits[j-d] = s;
nextRound.Add(j-d);
}
// SAND - stop
if (c[j] == '.' && hits[j] > s)
{
hits[j] = s;
nextRound.Add(j);
}
// HOLE return strikes
if (c[j] == 'o')
return s;
}
}
// No possible path found
if (nextRound.Count == 0)
return -1;
}
}
```
[Try it online](https://tio.run/##3V1dc1vHkX0Of8VZdVVMlqWOnM0bo5Rd3sTxlvJRSdX6QaUHBLyU4NCACgAtZ1XKX3cuQBCY6T6nL5y3XdoWLQD3A9N3erpPnz4z3zybr9bDjz/ebxbLN/jrPzbb4bvri/Zv/uXq7m6Ybxer5ca/GpbDejG/vpjfzTYb/Hm9erOefYcPFxeb7Wy7mOP71eIGf5gtlpeb7Xo8yavXmK3fbK7Gj/zsy/EMq7vBv1kvtsPLxXK4/Ho@fLW6u71cDu/x@PkPT2z8efL0ieHz/a/VP/e/di9@vLq6/mnn2R/6OfBwwtXh9@Hv/@45/z/8PHl6sR8YOHbD8fCft39//LHmv@M73r7LfuN4xvaV5kzen9n6d/urdee2w6dO9/zwZXY/OPyJw//j@Dc7voPwOeve71@PR7avWPMK0j/ttfPZjB738Pf9lzl@w@abNqNzfNXj@@ET7ft@HE1vL3sYRWKPwye8@1uywdGW3r5@@P3wZdKYIow6yBhDWJTZLI@ihU9ZODfSHYE8B9a982iZ01NNxr4ZyfxnPMacP/XG5oRbsjuZSd3VQe7j8H/dnKnnDcJYgFqTP/Xxua@efFC78iek/@doGTXO3XgcRrJ7rtV8Y3bsLWPBYhbsl71oa2XzaJvTnOlHPj7r7Lk2OQP4fIlHcL8XZ5Ily0a/d7Jnb5nHZzjbB83TammELawn@f/yzLFgod3MjHYJHqy1S5hz/Zyx4BmyBZQ1QOcMqK3jDASdPexu@PV7K50sg/z8O8TzirRmtKvLaZWhz3rySI/@L/lIb8/DZ1Azd7yfM@pJzt7HirnAV@wcCWRrZYshzRx2R9ZZhvh0Dx4sefXHlT2tQA46M/o1u40B4xoiPOkxFjRn18Tpy4Q5YMKj55FmTz5biZg1IGeTyWtaiiROR56@DDx7i2yThyeZrTOH5/bxVbfGTn00bcx2x4iLzTATa1NjGW8tY3I1mZo1PGZg8YHJtYbNCUtRIIsL22s0j1n2/DEycHTrShgjN/HEG50V5qDzpJ0hKm7o18Lje/2Xod4F1ItYsg2fa2xt4tmSkZFnMQWIDa1bZ9o4Ns@XPlvUUVxak@Wom4y6@nyln1X8teMaFCIAo7GsiRg4@hg95kb9khUxMqTn4qtZl8@0MdQpN/Sjf3HL4@zRPtGeXXTlIDHDcU2THtKoT40RY7vOsLhsagaoaEGNXrax9oWW3kGJMliIAJos0fuMkWUd@5F0kGius6KfPFLjuxwQa7jCXhoLG0EBkGKznMmwHAXF0w@ZRRqNA6avkhEJkBjE@uTsiKRArPugHq6bRc5WAWMoT5mBQs4VstZ4d0QTAZiInyBfyasQj5eNZImgHpHFCKDRXESQwjrjpye6eSLdYp7oGmWzLldFsiqfCypP5bNWHHu0jBEUBpMojFEkJuehbHbkGagiCo3n5E9HRDPPmzaKOs4Nb1d6EzhNinxzNOYRibHWvt11Tz6SIaMWEE2jcRDI2q@QYhP@zASWAIrAgM5bo3hovw6lTFOs5nHeWI@/t2t5/4x7G003VvBTXtTEH67jiXTdxo4xajaRZegsn63VKiaDiMbz@gGR/xj1av1nW8uQfJ4i9TkbJdmjR@9lAnsOr3qHPx/jcASMIUUjXWwGiuQqNNEkxsUrBZBrCJuRHLVUeKvROVNjjSLLoGiaJd@V8UhWB4JAH5BnU4/TOEIEwFdwiNqJic@pLJBFACarNP0aXyFElhFNDxhuzjrduL9zRAzGUUZzRqO4NqOKuFh8LiRq3UUAoAgLhL8yGgWYRN0Ufm8Ct0EZ72WvZ31s5jyqZXgI83yivum93VWcDFmZY17y8W7bKKGPmjGBxZhcjbnFIBFKNlNsEknQkYj1KUAeb9cV/uN4OKvXW7E2gaNzTtYfz3kQ/yRCpsnzeF65Up6qqsJAViRZhYxX1yAyXUtVAJYhKtZEFSPk2IpjZBTjjzFxXu/I2tP4wQ4D4PUoFO@rSo3JygrLE3kNAmGt4REhBKKJgEqix/WDn7KAdVlCaBiyH2cJQyxT3doxOe/adUYhuKzOApmZ1NmH5nSYiLlQxM5G7ucYmzWoYsN7Cc/rI1qmOUkJcXTGuugyfEesqXrH9ugrPM6RNnOETJOPu/JVPOtTFbAK8bKiameyupPnVMcD8OglWgu0lTXK9tJPtKdoS6Bynb2cVYvolR2UB8CxMIZRKV9jcmWpEWQrcygrooEYNbOcIq0RJ6/k6OoDYJwaB@XE8Hwx114wUcmjmGdXOePML4ZDm6yvKTQnf2a6KgZZ/8QEE5DZRjPPON8sx7hszYgYC2hGn/OZvPaHvLWbM4pXqZkXlfdh7Bmjc4ofq6rcEAyn3pslz0LqxQYExgBlcDo43kay@zaPlXVOWh094eEcneFZpolaiX66Ve1NrUdqTVdVT6O@tpszvWdvMfkcwQaGTYcRp8hNeLQUC0NY2iiDMN3RMTYziROycWHImsICICLeKkqo1i3I@Rlqml3NWTAjHMLzcFxAzyDi9Tx7tg7/iRF7k/GCcjQ1yl7X9flKpY9WHs0kO4MzEk5/Bo4mxxedZxA0x2GdA84yJlUj5Ty1robTZkjOcTOTnFVVA9a1Tp7BaG6HZjNV2VN8djivmfGMWbWxqjfmrL2qHlcoWuBo6gicMDQg2Ps1EwAlNxCCC6NsY6WlTfi6/Zfx8Ox78EKu6sPMJ6WR8@iDjCB0zDasmtBWXdMcC10anFWhoi3I@rwVSBwEt08zYxXTM66ALdbMMkDk3CPOLWexbuQD9FECyVScYDXOq2zRktYxNHgvEQr0ErJGDIrfVz00VrKc6sy1f0JaRNOoFShG6RwD5tlhrH4lrMarCLnmd4B0aeAMjhEKVlG9gp@DJFjpH3X3k1GGBs8ykEbdBCcGMn@pepVAImhVN5UogVs3Z2yycqk45FP4marcqI4pVRVDiX52lvGEy3hgVKBixVrPwSTjH23MuP88lgBl2zAcNfLNquqWrvKqGqR@ulVmqXvPjCIE/d3E@kzAvJzERrJrLMwbj5WENrrgCD@Lu5CRO0fKrZBYTTwaQxFTa1zMiloPhL@D5NVgossJlHFuJGeX/t0hI2KTKI@qIrO6HEUPXGCe3kcANhHrQvSVWYEta3zMzhxvSK5b9GsZ0STrtWeGuVE@mnnso@VrTbRsQBv8xHBC6uwpencDr7nqHLYJltM51RsTfQCK2a66ZXgHTdsNSPrtA1ZDcheP2Q@rk02wLorZIlUCvO0iaKvNui4M2U8L2QmtebJWspnrnjQrmOeW@jQpSuz5CeXstIrxF0Y9oQjHWeETnHbayw4yZ6rKI@QajIJVMdUhYCJaR8mx5tz0Zs445ZARz97VpHO3n0P0nuXupSbSED0Efbav8aKmrkm8GeQar7oDdfcM56lZofhgsu@tYntazwPo6i4KwU@xkex8ZR3IvEvNJng1Cv2PKGrmm1nB5sLZ@WTN4dB4s@o@twJbyNwZExoVSPawEBXwCn94xWPPS69m0vdlqqgt1bxlBFDx@upeQciVBgWDHIUajarb6AyLoTNw1sfPlXysy00yw6nlTmirW8lu5xgD6YJyyEzTRE5oIrqtjsKEVpAJfQbNDTXZq5EZGpbYgBMolqdZQHFgogYgvV/2ki03hPUQTikCKZbztP6LCf2emmNmZRaq@9@N5jOi1uKKd0eYHE5q9apK4JFX0HEM2szJdd8ZqwLoWqOuz6u6vBU9TipGs8JWqrbDuLVHy7jqa@KZhshQHIIrINYhZ8zcWMNW@WWqa5L@mSom4ppkWv0MlGOgO2JMYDuaS90ewbgzOR7qUQDjmloujonZYZgp4HpbjmLFi52LmdUEyb6H5CJpzTkUNR8IqzB2iMYQ8hGJoSEqjgFb8agBl@aGm1dIMhJDCqlHB6JqwPjUUd3EpHqJ7imuOmkrVSDGGKw7cM7RWYmMc8pNJnVlUsd3GS143x2eVgyi0mCOSZzGRE1TYzC1oth0PFZp2PD8BpLXpPsHjEUAlH/UexjNk2T@iWkzsapX7H5i@RLr7OjsGiIAK3SA6uffJlgzKHqZeCaq7abO0s0Z59ghCu0mpW8CYVlW6WF6ZYyZoFg2maFhwpuY0MZSY6jrA7UNrdSXmdY2CbozYVXp4lmHJ6axZ55lUoOjzBsI3b@MWpOcxxMHzXvdGZPqcRDxEWTfOEddVN5pUs@mUtBS3QFcE1D1UkD384k8U6iXSd2nBg91pkXIVLlAdDStyK8VfmVC3RKiU7mKfiGZulaqoOWuc/qtHVzzhcTHSGsCZ9lC8s5j9z9npFlQ@WixuKpP0wovZ0UXLQSjabqzrNJN4RidEQ2NnPHRPN5V72U/MyqtHxS5atIQyuqyrHvEIRjnCn3X1UrFwNAMAqUgaFIPRSEB8QqZB8AqWYl955VuqQmWNIIOVmabG@G5s2hDeNrAOLeie9WKfkwUXEFQvNpkL5TR1QRFdTTpm6W6sgkmGOVGCNxE9jp7HW9Zof4cehbbJyZxZ7T6i0l9LK52pdQXVJeB7pBC2aVoqbOpyRWddUdqZd4420zocLJu8qAgnNYrOJhfpHqOPaKpdF7sJ/Azzu1pPqdyPaUynLMf4s1SBKU1zIL@X60646DMgA6ZyYxlLzp54hqVqs0QvFkI9TEIdpiKxpQmOkoe5jkzqPdmoGixEY4f8/tZHabTBqBVfho5O6vS9Up4PGrLXecmrVDrataacJAYadWZAcGBM9FBE7sBFbrPOi609rXmExbKi1Lxj/M/uyq2I/QC8FhJVS3NINVodAegUgesempMYgcRhYgMjcAbS/oykKwmUslkuvSiVpPwUGc@jOgHetZrtoJbrjNCTPQkK/YNCo3facUHxZyxgDU3q7Oriq9VnGYH7cA13jntiGNLq95FXtpfn6qb1PgLCh3FGknQOsxqZvAjpxgabNcMolzJ412HGDUUeT8de4eI6kxgo@zLWKGoiLJ/xiSOY7Lzs1Y4P3/9ipFc1gQUOLHM@lHqMTE2uWANRMTMKT46qTynFKy1BjDKfhabqLNMdQMqLRqNTwTdGY9zwmg/TV8lU3p0WumhZBiyKrfLvbeSF2Tq85jsfFEKZnrXB5zFmLKJmEBpBSjuTL07Q1DVFDp1XQTsfC@sKauQtcVRVVs9Zpomdf2sVG6A7H5ing9SLbjWLuHIKDJ3xpkSQNSOlxrx/b6CDslfa5WbLFU2QfpjjPZ/Zj9oUnnO6PqiGWiQOY7qb7LCyym2Z91vlro0vN6nzErlRcY6AqmlTev79iiDBV6AyP@dKQLhDMS@4r1aqeNkJcsDZ80brbmVappKlZd1msf6iOypzPFCVs7iNWcoxJ9pSFGlhkqNv96JxKjak2I2V/00qoJgEpXjUbNFlZmkyqe6/7gGmRE9BpNMkFqBQLKd3ZL6fM0phsgTUdSNdYw2vUvDOXmTVjfRe8CaQIe7LNXrKKzf/YH0kHmai5yd6yLP6XgAtTWmNa0gsHororqq@79CTJnNY88Zq@rHVYBFBWBqDEX@IfvJHExbW@NzLaJEeps1uwh2jtq5lb0AVvBxbSJag@Sah/6ZtOue0fHp5olC1VxFt0rXR8SGZ@xKAKqkDaliaiLaMoOsSqs1W7P4auVG3ZdjqT7DGJiMc1Z1tJhgaeR6aGBGE4aSTUaGlO2cdqCrVBhVhFTlInbGeqJ3vNMdVCwKbOeMSeSD97RM8Z@MKtlY0buktM2F5mr0v0XPWV1D1mhYpYqt9wiyglWguc397zhnTOT7GqNkuznxfsCjr3NWo2O6N5mlSftBne3aqDJ2m8j@65iJeyIT6wjvGayel7D/TOZkiOhHqwPqfWutYDKZmFvge9wg1jVDHZvsDnyON8GZ1Tamd8EjXkjNExWXKfV5K/aHa6otrN/cdae@0sjoMlGvu2T4vrTU0p730qhU3zR6A9O7@1X8dc1vqyPrCp0htiG9/ZBKixZ6jZBwFl0dUFwQhtGF3VOoVpOqKGo00gpkxkokQDEB672ZTOAxIMpz5@xM0nQSO2dVkF3jTjlkwb05o4tA7hjZ2ZgwNHCGailK5XJI7dhK1anq0dS73ypFoKwIqypqcXUHwWBYpdQcqSapMZgqmohXZwwNWK3Zr7ToNdemivlUXVsxaqvZ1ivPRUay7m3q9wgsdGpJbZjvZpP2LUs7SdP43Ln2LEwrwENw0HXup3Hr8/S5eYaKgt1hpNocFf3AkMnu6S/6ZQXDObLU6I5oThiZziL0btamnU7reAgS9dWdmmpHZh61QdhvqtLGK2fWdTWdOEYnrpGsGTjXb2RxVNYN4h1ocb@urCvQIGciNqv6KlU3h2a1Km1Zm9CC1go0VjI0DLzfy0j/EkKlBq56azDZ/2qxKu1prhYVgeBDqYqW3jWu3nkGE/WDCjNQXf@Y0KHlXRqm@sgcEoEGYdVC8M1BtMqr2g7rZcqsK75jg1qdIXuVOZpvBd/8XC0uFN3m1V6bvWWqmIjpZoYOZFca2igwM83uVHvZ8HlnFANQ6uVKN1MropjMCZWCjNZBq/Uem2qz45SPe9jXZXq3Bqid5aF6/Y91tkotSFV1ENfAwNGE6IqsFMisXHdwlsZAZQMre@G5x8tK2ky5ut@prFIiF2ocbqTvQuoupx3MOna7J9VPt9QNiIIjBpvaHQYTOjUqqqr4OVZ4TrZqNRFAwmM444vv02tyL0d2TrVi8VgkWoqudA7SQVuv6lMdg5jse7IyWkDRKwjpPaP2bFJjpLpxJvMU3htef95KzYBK1dFIjyjLZ0x2xlpRq/kpu6JzHh8magi6Ooq@CiCrwc0uwC3L2I/W6@vNrmyY8DfnykNp9Xem/sD4iX195jx2q@L76V2DdB@70oXSXRmYUKflu2nxHKTra0KhmkF55YHn76lTitRe@hoaXdloB63WVdDjjQJNRlFN4NGVVgnQ9Rs2Z5jiK@@soPPBWScFr2CfZkbh51zv1cw6pFhvM4r6peoVNKlnqjkuJvqnIfNQTPb19Hs2naM2Kms0HvdiILUbp324njQIJEsmqt8SVfrE0KhqjVV32ZR6M0SmVPfSVLFg9nuRo9mgJHnEAs6IVOPq@vUchDtjpY4sqCI9uzZR/l4x9fn/uz9PPl5dXV98vLjYbGfbxRyL5RZfz4evVne3l5vterF88@o15qv79Wa4uvhwsRuKX/wC3yxutm@xusX27XB4d//W7uj3eHF46dXz1/5yWL7Zvr2@eDzyy/07mG2wGc99N@DhIvu3v5@tMR@PfnjJ/3u1WF4@efL08fKnk3yxXs/@sbv828V2g3fDGreL4e7meJL9yy@wHN7v7ujV/HAXr09n@N3u8xtsV@PJl9vF8n7A7Xr13fEMy@GH7V9W98ubw2leLjbbX4/n@s1lcxtfLxfbxexu8b/D/or7l29Xa1zuhmExHvn8evz16/2bjwOBxaefXu0/@TCY@1G7xeX81eI1/uMFPvn8k6uLNl3bfd27u4cvOA7adrYeh3gxjv5sPO@bt@Pd3t0P3RG7y@3O9mK8we1//tL/MPvhf3Yfuj5@arjbnA75EC/35/v53x@u93C5zcP1nouLPL/u3jiOnH9xc3O5uDq9@/Hi4c9@nHaG@uwa19jkgRlvZn43jObYPWaHEdi@ne0GYBySvw243ww3o4n37@8ujMV2WI/P8Wp5PMf3@8MXm5M1D/d3urFpYx/ueJjN3z5ad3/Vw2mv9GBuh80Ws/Fuf4WbxXqY7@5t032oO@/@24z3ME66D3j22VOM/z57/3ScVB/7x6K/0OPc@3b8BotPb5q7bm7l6y9/i2fY3C1uxvl3tzpMuvbn/dvFOCPHZ/Hb0bDjs4jwLD7@fItPX0Bc5ZsvXr7cXWa7eofVEu/Ww/eL1f2mmaHdTd82l7NP8POfPzxZ3z67eY3fYJOv/4He0emg0X1c04/0D@b42av8uY/0K/31iz/@1@Er1V/Amy/wb9z@@Td/9q3//k8vf4v1sL1fL/du9e/Dpv4KK2Hyx3P0F/54QS4/XvaPK7xbbTaLv42P07vZ6Dxud/feObzTNxqXhPHRHS/@vL/04ZLPPrs@OI7xnx9//Bc)
] |
[Question]
[
A simple graph is toroidal if it can be drawn on the surface of a torus without any edges intersecting. Your task is to take a simple undirected graph via any reasonable method (adjacency matrix, edge vertex sets, etc.) and decide whether or not it is a toroidal graph. You should output one of two distinct values for each of the two decisions. You may choose what these values are.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with less bytes being better.
## Test Cases
Here Kn is the [complete graph](https://en.wikipedia.org/wiki/Complete_graph) with n vertices and Kn,m is the [complete bipartite graph](https://en.wikipedia.org/wiki/Complete_bipartite_graph).
### Toroidal
* K3
* K7
* K3,3
* [The Peterson graph](https://en.wikipedia.org/wiki/Petersen_graph)
* [The Möbius Cantor graph](https://en.wikipedia.org/wiki/M%C3%B6bius%E2%80%93Kantor_graph)
### Not Toroidal
* K8
[Answer]
# Rust, ~~1210~~ 1200 bytes
```
use std::collections::HashMap as H;type I=i64;type E=Vec<(I,I)>;fn d(g:&E)->bool{let mut s:Vec<(E,Vec<I>)>=vec![];for e in g{let(v,w)=e;let f=(*v,*w);let z=|x|s.iter().position(|p|p.1.contains(x));match(z(v),z(w)){(Some(i),Some(j))=>{if i!=j{let mut p=s.remove(i);let q=s.remove(j-(i<j)as usize);p.0.extend(q.0);p.1.extend(q.1);s.push(p)}else{s[i].0.push(f)}}(Some(i),_)=>{s[i].0.push(f);s[i].1.push(*w)}(_,Some(j))=>{s[j].0.push(f);s[j].1.push(*v)}_=>{s.push((vec![f], vec![*v, *w]))}}}s.iter().map(|h|{let mut p=H::new();let mut r=H::new();let mut i=0;for e in&h.0{let(v,w)=e;i+=2;p.insert(i-1,i);p.insert(i,i-1);r.entry(v).or_insert(vec![]).push(i-1);r.entry(w).or_insert(vec![]).push(i)}let mut r:Vec<Vec<I>>=r.values().cloned().collect();r.sort();let mut x=0;let m=r.iter().flat_map(|v|1..v.len()).fold(1,|p,n|p*n);for mut w in 0..m{let mut t=H::new();for u in&r{let mut v=u.clone();let s=v.pop().unwrap();let mut f=s;while v.len()>0{let o=v.remove(w%v.len());w/=v.len()+1;t.insert(f,o);f=o}t.insert(f,s);}let mut f=vec![];let mut n=0;for s in p.keys(){if!f.contains(s){n+=1;let mut c=s;loop{f.push(*c);c=&t[&p[c]];if c==s{break}}}}x=x.max(n)}1-(r.len()as I-g.len()as I+x as I)/2}).sum::<I>()<2}
```
A toroidal example:
[Try it online!](https://tio.run/##dVTBcpswEL3nK5TO1KNNsGpct2kg8i0z8aGXdqYXj8dDsIjlYokiAU6Ab08lIJjQKRf2rd6it08r0kzp19dMMaT0zvNCGccs1FwK5XkPgdp/DxIUKPTg6@eEoRXlXxdteE9/sfAOr5wVLP1IoB1@8ib3MF0@ShmXMdPomGmkvIZ179jXaglLmrPwcr3xI5kihrhAT5aLc6cAynxbFlF8lTtXBTTohVanShGuWYqBJFJxKw5XSZUQl4RS6IALhU8A/jHQ4R6/4BycF1wAlPinPDLMwWneBwC6LHmE@CU99AITqkjKjjK3xGbHP@fMYYr53QFM/5niLwz8hMwIO2kmdvgPmVnsnrELviJJpvY4gZrFipVqzTemoslFUNe9oK2V8n7Vb6DbQtN9jbdD3Wp9eE8@nMk51FtLaSFuHI42DmoC4yW6KjZgtq97H49Bgqt9NXDhwfMEK3BrgU2l/6Y4nfXnNtmT2fDk@DWdGzvMWbBUYz51HQ4D7JgM@ClhQqfP5oSITLfdWjsQ0Ip/Ryv@T4O619lMWDteS5qSPIgzpkyPYSwF29mgnWlsP6xkqgcdnUxHTWwKO2uiONDbxp@8cgnJScwEBpOX8Q67TpU4okquBDRO2G8UdopnhBx7N/XZOkvKrF1pv5rTrNXW6VA0N3OdmK0zUaRm47O8iCq/2POYoU7GsvEcSVPSjWjx8U2hX3yiXXzt@vrN@siRRgaV9SCjwK/Pe3Q38i0hulNWtq@E/GbPxk1zby6j83VTUIpr6vY1oREaS5mUUTeSIfghnej1JFmHm41vbl1IqSofUxb8NoNYn@jJDOEJC6jdKU5b2eaeraZP5/j6ZH89K/g0r4Go7Oh55owx3M3rV/PDORolGFB5gcxjhTwZ8/aItmPfZO2DZw5ywXmHP4/wYojnI/58xDf4yxAvRvzFiL8Y8b846OsIfxthdzZM3IwKbkYFN@OC21HB7ajgdlCw8Xv/UqayWBsDd3jSeAntWpJyoWNxiT/8aBgeKusPTkc3nPri9S8 "Rust – Try It Online")
That's this toroidal graph: [](https://i.stack.imgur.com/XvH6k.png)
A non-toroidal example: [Try it online!](https://tio.run/##dVTBcqM4EL3PVyhTtS51gjXGk5lsIPItVfFhL7tVc3G5XAwWsTxY0iABToBvz0pAMGFrudCv9Rq9fmqR5dq8veWaIW32QRDLNGWx4VLoIHiK9OGvSKFIo6fQvCiG1pR/v@3CR/qDxQ947a1hFSYC7fFzMHuE@eqnlGmVMoNOuUE6aFmPnnutV7CiBYuvNtswkRliiAv07Li48EqgLHRlCcXXhXddQoteaX2uNeGGZRiIkpo7cbhWtSI@iaUwERcanwHCU2TiA37FBXivuASo8D/yxDAHr30fAeiq4gniV/Q4CFRUk4ydZOGI7Y6/L5njHPOHI9j@c81fGYSKLAg7Gyb2@DdZOOxfsA@hJirXB6ygYalmld7wra1ocwk0zSBo56R8XA1b6HfQdt/g3Vi33hw/ko8XcgHNzlE6iFuHk62H2sB6ia7LLdjtm8HHU6RwfahHLjwFgWAl7ixwqey/KU4Xw7nNDmQxPjl@Q5fWDnsWLDOYz32Pwwh7NgNhRpgw2Ys9ISKzXb/WDQR04j/Qyv@nQTPobCesG68VzUgRpTnTtsc4lYLtXdDNNHYf1jIzo47OtqM2toW9NUkamV3rT1H7hBQkZQKDzct0j32vVp6o1bWA1gn3jdJN8YKQ0@CmuVjnSLmzKxtWC5p32nodmhZ2rpXdOhdlZje@yEuoDssDTxnqZaxaz5G0Jf2Iln@8KwzLL7SPb/zQvFufeNLKoLIZZTSEzWWP/ka@J0R/ytr1pcgv9mLdtPfmKrlcNw2VuKH@UBNboamUqkr6kYwhjOnMbGZqE2@3ob11MaW6@pmx6JcdxOZMz3YIz1hA489x1sm292w9f77EN2f361nDl2UDROenILBnjOFh2bzZH87JKsGAqk/IPk7IszXvgGg39m3WPXjhIR@8D/jrBH8b4@WEv5zwlxP@7YR/O@HfTvjfPPR9gv@cYH8xTtxNCu4mBXfTgvtJwf2k4H5UsA0H/zKm89RYA/d41noJ3ZrKuDCpuMKf/24ZAaqaz15Pt5zm09u/ "Rust – Try It Online")
That's this non-toroidal graph: [](https://i.stack.imgur.com/ggGVV.png)
The original code I wrote, before golfing, was the following. It has printouts so you can see what's happening:
```
use std::collections::HashMap;
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
struct Vertex(u64);
type Edge = (Vertex, Vertex);
type Graph = Vec<Edge>;
fn full_genus(graph: &Graph) -> usize {
componets(graph).iter().map(|g| genus(g)).sum()
}
fn genus(graph: &Graph) -> usize {
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug, PartialOrd, Ord)]
struct HalfEdge(usize);
let mut edge_pairing: HashMap<HalfEdge, HalfEdge> = HashMap::new();
let mut vertex_groups: HashMap<&Vertex, Vec<HalfEdge>> = HashMap::new();
let mut i = 0;
for edge in graph {
let (vert1, vert2) = edge;
let half1 = HalfEdge(i);
i += 1;
let half2 = HalfEdge(i);
i += 1;
edge_pairing.insert(half1, half2);
edge_pairing.insert(half2, half1);
vertex_groups.entry(vert1).or_insert(vec![]).push(half1);
vertex_groups.entry(vert2).or_insert(vec![]).push(half2);
}
let mut vertex_groups: Vec<Vec<HalfEdge>> = vertex_groups.values().cloned().collect();
vertex_groups.sort();
println!("{:?}", edge_pairing);
println!("{:?}", vertex_groups);
let mut max_faces = 0;
let num_rotations = vertex_groups
.iter()
.map(|v| v.len() - 1)
.map(|n| {
let mut prod = 1;
for i in 0..n {
prod *= i + 1;
}
prod
})
.fold(1, |p, n| p * n);
println!("\nNum rotations: {}\n", num_rotations);
for rotation_index in 0..num_rotations {
let mut working_index = rotation_index;
let mut rotation: HashMap<HalfEdge, HalfEdge> = HashMap::new();
let mut pretty_rotation: Vec<Vec<HalfEdge>> = vec![];
for group in &vertex_groups {
let mut removal_group = group.clone();
let start = removal_group.pop().unwrap();
let mut from = start;
let mut pretty_group = vec![from];
while !removal_group.is_empty() {
let index = working_index % removal_group.len();
working_index /= removal_group.len();
let to = removal_group.swap_remove(index);
rotation.insert(from, to);
pretty_group.push(to);
from = to;
}
rotation.insert(from, start);
pretty_rotation.push(pretty_group);
}
let mut seen_on_face: Vec<HalfEdge> = Vec::new();
let mut num_faces = 0;
for start_halfedge in edge_pairing.keys() {
if !seen_on_face.contains(start_halfedge) {
num_faces += 1;
let mut current_halfedge = start_halfedge;
loop {
seen_on_face.push(*current_halfedge);
let pair_halfedge = &edge_pairing[current_halfedge];
current_halfedge = &rotation[pair_halfedge];
if current_halfedge == start_halfedge {
break;
}
}
}
}
if num_faces > max_faces {
max_faces = num_faces;
let euler_characteristic: isize =
vertex_groups.len() as isize - graph.len() as isize + max_faces as isize;
let genus_num: isize = 1 - euler_characteristic / 2;
println!(
"Faces: {}, Genus <= {} on rotation {}",
max_faces, genus_num, rotation_index
);
println!("{:?}\n", pretty_rotation);
}
if rotation_index % 1e7 as usize == 0 {
println!("Faces: {} <= {} on rotation {}", num_faces, max_faces, rotation_index);
}
}
let euler_characteristic: isize =
vertex_groups.len() as isize - graph.len() as isize + max_faces as isize;
let genus_num: isize = 1 - euler_characteristic / 2;
assert!(genus_num >= 0);
genus_num as usize
}
fn componets(graph: &Graph) -> Vec<Graph> {
let mut graphs: Vec<(Graph, Vec<Vertex>)> = vec![];
for edge in graph {
let (vert1, vert2) = edge;
let g_index1 = graphs.iter().position(|(_g, h)| h.contains(&vert1));
let g_index2 = graphs.iter().position(|(_g, h)| h.contains(&vert2));
match (g_index1, g_index2) {
(Some(i1), Some(i2)) => {
if i1 != i2 {
let (mut graph1, mut vs1) = graphs.remove(i1);
let new_i2 = if i1 < i2 { i2 - 1 } else { i2 };
let (graph2, vs2) = graphs.remove(new_i2);
graph1.extend(graph2);
vs1.extend(vs2);
graphs.push((graph1, vs1));
} else {
graphs[i1].0.push(edge.clone());
}
}
(Some(i1), None) => {
graphs[i1].0.push(edge.clone());
graphs[i1].1.push(vert2.clone());
}
(None, Some(i2)) => {
graphs[i2].0.push(edge.clone());
graphs[i2].1.push(vert1.clone());
}
(None, None) => {
let edges = vec![edge.clone()];
let vs = vec!(vert1.clone(), vert2.clone());
graphs.push((edges, vs));
}
}
}
graphs.into_iter().map(|(g, _h)| g).collect()
}
fn main() {
let graph = vec![
(Vertex(0), Vertex(1)),
(Vertex(0), Vertex(2)),
(Vertex(0), Vertex(3)),
(Vertex(0), Vertex(4)),
(Vertex(0), Vertex(5)),
(Vertex(1), Vertex(2)),
(Vertex(1), Vertex(3)),
(Vertex(1), Vertex(4)),
(Vertex(1), Vertex(5)),
(Vertex(2), Vertex(3)),
(Vertex(2), Vertex(4)),
(Vertex(2), Vertex(5)),
(Vertex(3), Vertex(4)),
(Vertex(3), Vertex(5)),
];
let result = full_genus(&graph);
println!("Result: {}", result);
}
```
This program finds the minimum genus surface that the given graph can be embedded in. A graph is toroidal if that genus is at most 1, the genus of the torus.
The code works by separating the graph into its connected components, finding their genii separately, and adding up the results.
To find the genus of a connected graph, I brute force search over all possible [rotation systems](https://en.wikipedia.org/wiki/Rotation_system) of the graph, and figure out which one has the most faces. A rotation system is simply an ordering on the edges emerging from each vertex, saying what order those edges are in going around the vertex. Each rotation system has a straightforward minimum genus it can be embedded in, and having more faces directly corresponds to having lower genus. Since every possible embedding corresponds to some rotation system, if there is a toroidal embedding, my program will find the corresponding rotation system and declare that the graph is toroidal, and vice versa.
This program is very slow, because it searches through a number of rotation systems equal to the product over all degrees `d` of the vertices of `(d-1)!`. However, it can search through a little over 10 million such rotation systems per minute, so it can verify the toroidality or non-toroidality of simple graphs like the ones shown above.
] |
[Question]
[
## Introduction
There is a small village with nothing but a few houses and empty fields.
The local bureaucrats want to divide the village into lots so that each lot contains exactly one house, and the borders of the lots form a nice straight-line grid.
Your task is to determine whether this is possible.
## The task
Your input is a rectangular 2D array of bits; 1 represents a house and 0 an empty field.
Its size will be at least **1×1**, and it will contain at least one 1.
You can take the input in any reasonable format (nested list of integers, list of strings, multiline string etc).
Your program shall determine whether the array can be divided into grid cells using straight horizontal and vertical lines so that each grid cell contains exactly one 1.
The grid cells may have different sizes and shapes, although they will always be rectangular.
The lines must run from one edge of the array to the opposite edge.
For example, the following is a valid division of an array:
```
00|0010|01|1
01|0000|00|0
--+----+--+-
00|0000|00|1
01|0010|01|0
--+----+--+-
01|1000|10|1
```
whereas the following division is not valid, since there are grid cells with no 1s or more than one 1:
```
00|0010|01|1
--+----+--+-
01|0000|00|0
00|0000|00|1
01|0010|01|0
--+----+--+-
00|1000|10|1
```
If a valid division exists, you shall output a truthy value, and otherwise a falsy value.
## Rules and scoring
You can write a full program or a function.
The lowest byte count wins.
## Test cases
```
[[1]] -> True
[[0,1],[1,0]] -> True
[[1,1],[1,0]] -> False
[[1,0,1],[0,1,0]] -> True
[[1,0],[0,1],[0,1]] -> True
[[1,0,0],[0,0,1],[0,1,1]] -> True
[[1,1,1],[1,1,1],[1,1,1]] -> True
[[1,0,1],[0,1,0],[1,0,0]] -> True
[[1,0,0],[1,0,0],[0,1,1]] -> False
[[0,0,0,0,1],[1,0,0,1,0],[0,0,0,1,0]] -> False
[[0,0,1,0,1],[0,0,0,1,0],[0,0,0,0,0]] -> True
[[1,1,0,0,0],[0,0,0,0,0],[1,0,1,0,0]] -> True
[[1,1,0,1,1],[0,1,0,1,1],[1,0,0,0,0]] -> True
[[0,0,0,0,0,0,0],[0,1,1,1,0,1,0],[0,1,0,0,1,0,0],[0,0,0,0,0,0,1],[0,0,1,0,0,0,1],[1,1,0,1,1,0,0]] -> False
[[1,1,0,0,0,0,0],[1,0,1,1,0,1,0],[0,0,0,0,1,0,0],[0,1,0,1,1,0,0],[1,0,0,0,1,1,0],[0,0,0,0,0,1,0]] -> False
[[0,1,0,1,1,1,0],[0,0,0,0,1,0,0],[0,0,0,0,0,0,0],[1,0,0,1,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,1]] -> True
[[0,1,0,0,1,0,1],[1,0,0,0,1,0,1],[0,0,1,0,1,0,1],[1,0,0,0,1,1,0],[0,0,0,1,1,1,0],[0,1,0,0,1,0,1]] -> True
[[0,1,0,0,1,0,0,1,0],[0,0,0,0,1,1,0,1,0],[1,1,0,0,1,0,0,0,0],[0,0,1,0,1,0,1,0,0],[0,0,1,0,1,0,1,0,0],[0,1,0,0,0,1,0,0,1],[0,1,0,0,0,0,1,0,0]] -> False
[[1,0,1,0,0,1,1,0,1],[0,1,1,0,0,1,1,0,1],[1,0,0,0,0,1,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,1,0,0,0,0,1,1],[0,1,1,0,1,0,1,0,1],[1,0,1,0,0,1,1,0,1]] -> True
```
[Answer]
# Pyth, ~~30~~ ~~29~~ ~~26~~ ~~24~~ 23 bytes
```
sm.Asmmq1ssbCkds./MC./M
```
[Try it online.](https://pyth.herokuapp.com/?code=sm.Asmmq1ssCbCkds.%2FMC.%2FM&input=%5B%5B1%2C0%2C0%5D%2C%5B0%2C0%2C1%5D%2C%5B0%2C1%2C1%5D%5D&debug=0)
I'm sure this will get shorter. This is **O(2*mn*)**, where *m* and *n* are the width and height of the array, but completes the last two test cases in 45 seconds on my laptop on battery (i5-5200U with limited performance).
Outputs the number of solutions.
### Explanation
Five-dimensional arrays are really fun to work with.</sarcasm> You are not supposed to understand how this works even with the explanation.
```
./M Find all partitions of each row. Now we have a list of rows,
each containing the ways to split the row, each containing
the parts of the split (3D).
C Transpose. Now we have a list of ways to split the columns,
each containing the rows, each containing the parts of the
row (3D).
./M Find all partitions of each row list. Now we have a list of
ways to split the columns, each containing the ways to split
the rows, each containing the bunch of rows, each containing
the rows in the bunch, each containing the parts of the row
(6D).
s Combine the ways to split rows & columns into one array (5D).
m d Do the following for each way to split rows & columns (4D):
m k Do the following for each bunch of rows (3D):
C Transpose the array. We now have a list of column
groups, each containing the row parts (3D).
m b Do the following for each column group (2D):
s Combine the row parts in the column group. We now
have the list of cells in this row/column group
(1D).
s Sum the cells.
q1 Check if the sum is one.
We now have the list of booleans that tell if each
row/column group is valid (1D).
We now have the 2D list of booleans that tell if each
row/column group in each bunch of rows is valid. (2D)
s Combine the 2D list of booleans to 1D.
.A Check if all values are truthy; if the split is valid.
We now have the validity of each split.
s Sum the list to get the number of valid solutions.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 22 bytes
```
ŒṖḅ1S€€=1Ȧ€
SŒṖ⁸ṁþÇ€FS
```
[Try it online!](https://tio.run/nexus/jelly#dVExDsMgDJybtzBwD@jaPoAR8ZhUqrp36BM69QHJ0iWq1G8kH6EkGGwClRDG9vl8Nv5zn8fHPFxhlssrnCO@z2A6syWWfpjHfnpPtxA7Gb/Zs/e2O1gL59RqtYJTFkqTj8qPiHDLWIzQzcgY5wrOJV5pyzqu59zKlfgQX7mHVEQe9d3jtJyOfJmL3Khw4Mmz7pIvc0jthNe5NnGrAp@0opiRerU0F1pRzSj3xxysGfudFPtLNf84daVBt3bZnFP24H@C6CF3UefLP0djt6FH534 "Jelly – TIO Nexus")
[Answer]
# [Haskell](https://www.haskell.org/), 116 bytes
```
import Data.List
m(a:b)=[a:e|e<-m b]++[zipWith(+)a d:e|d:e<-m b];m e=[e]
d=(any$any$all$all(==1)).map(m.transpose).m
```
[Try it online!](https://tio.run/nexus/haskell#dVM9b8QgDN3zKxg6JDoa4fVaOnXs3gExcEqkIh25KGFp1f@eki@wSToQwDbv@dnOZF3/GDx7N97UH3b0hSvN9VZJZa7tb/v67NhNXy7qx/af1n@Vl8qwJnjCWn0vjrVStbpoZGm676dl3e/zKqWEqqqd6UtX@8F0Y/8Y22CYnLGd7Afb@TmONUop0JorJTiEDbhYbmEPJx6sqz18OWwe2CLxviLMUXv8dotnEZFhu2HPwrx6UBREbhHZMFb0ZEyQ4yMOccZ/cgfEkHQBYth1wqkfZ4QzxHh7pSG9SdXObMCJumP@uGMoFuPlmVIOrdlbwVgYo3UsTgcilRa3XZAkqXRBogR@vyeUFebYCiprH7tYJjpYZKDgMIZYQUL4r3VUAx6gHDUxAYmjbYFM49EGpM1AbPEX0cX0Bw "Haskell – TIO Nexus")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes
```
ŒṖS€€ỊȦ$ÐfZ€µ⁺€Ȧ€€FS
```
This is still a brute-force solution, but it's quite a bit faster than my other answer – which cannot cope with the last two test cases on TIO – and handles all test cases in ~4 seconds.
[Try it online!](https://tio.run/nexus/jelly#dVO7DcIwEK3JHJQufEvAAOmI3LIHNEhUiIIRUtFSAB0RUtYgixhH/tw725GSOPd79@7Ztt/r73lrp@PdPb/3eezXw2W/c8bnMR1ebh17H9y0dji5dWtt16y6joxR86oVGdWR0sGmwvYZ7os@7wlfzvR@ruBYxMVV1nE9x2asiEf@L/VARsEKffM8jdMFG2Mem4o84skTb4mXMJB7yNepNmIrkR@5kpgx9KpxFlypmBH1YwzmTLkmQr9Ys4SpCw66pmV1TuzB@0TQA7Uo43LPqaJtrUepD2tGIg/OLbzLPmQOt0NoBrcHu6czIn1ZdalpxidNBHi5drKHacwf "Jelly – TIO Nexus")
### How it works
```
ŒṖS€€ỊȦ$ÐfZ€µ⁺€Ȧ€€FS Main link. Argument: M (matrix, array of rows)
ŒṖ Compute all partitions, i.e., all groupings of M's rows.
S€€ Map sum over all individual groupings, collapsing the grouped
rows into a single row.
Ðf Filter; keep only those partially collapsed matrices for
which the link to the left returns a truthy value.
$ Group the two links to the left into a monadic chain.
Ị Insignificant; map 0 and 1 to 1, greater integers to 0.
Ȧ All; return 1 iff the matrix contains no zeroes.
Z€ Zip/transpose all kept matrices,
µ Combine all links to the left into a monadic chain.
⁺€ Duplicate the chain and map it over the individual results
from the first call. We now have all possible combinations
of row and column groupings (represented by the corresponding
matrices of collapsed rows and columns) that do not have a
2 anywhere. However, they still may contain zeroes.
Ȧ€€ Map the all atom over the matrices, returning 1 only for
matrices that consist entirely of ones.
FS Flatten and sum, counting the number of valid divisions.
```
] |
[Question]
[
## Introduction
[Kerning](https://en.wikipedia.org/wiki/Kerning) means adjusting the spacing between the letters of a text.
As an example, consider the word `Top` written with the following three glyphs:
```
##### ..... .....
..#.. ..... .....
..#.. ..##. .###.
..#.. .#..# .#..#
..#.. .#..# .#..#
..#.. ..##. .###.
..... ..... .#...
..... ..... .#...
```
We could just fill the gaps between the glyphs with dots and be done with it, but the gaps somehow look too wide.
Instead, we slide the glyphs to the left so that they almost touch:
```
#####........
..#..........
..#..##..###.
..#.#..#.#..#
..#.#..#.#..#
..#..##..###.
.........#...
.........#...
```
This looks much better!
Note how the bar of `T` is on top of the left border of `o`.
In this challenge, your task is to implement a simple kerning program for such rectangular glyphs.
## The kerning process
Consider two rectangular 2D character arrays of `.` and `#` of the same shape.
In our simple kerning process, we first place the arrays side by side, with one column of `.`s in between.
Then, we move each `#` in the right array one step to the left, until some `#`s of the left and right array are orthogonally or diagonally adjacent.
The outcome of the kerning is the step *before* we introduce adjacent `#`s.
Your task is to implement this process.
Let's take an example:
```
Inputs:
..###
#....
#....
..##.
...#.
...##
..###
....#
Process:
..###....#.
#........##
#.......###
..##......#
..###...#.
#.......##
#......###
..##.....#
..###..#.
#......##
#.....###
..##....#
..###.#.
#.....##
#....###
..##...#
..####.
#....##
#...###
..##..#
```
In the last array, we have new adjacent pairs of `#`s, so the second-to-last array is the result of the kerning process.
## Input and output
For simplicity, you only need to handle kerning of **two** glyphs.
Your inputs are two rectangular 2D arrays, in one of the following formats:
* 2D arrays of integers, with 0 standing for `.` and 1 for `#`.
* Multiline strings over `.#`.
* Arrays of strings over `.#`.
* 2D arrays of the characters `.#`.
If the inputs are taken as a single string, you can use any reasonable delimiter.
However, the delimiter should go between the two arrays, meaning that you are not allowed to take the two inputs already paired row-by-row.
Your output is the result of the kerning process applied to these two arrays, which is a rectangular 2D array in the same format as the inputs.
You are allowed to add or remove any number of leading or trailing columns of `.`s, but the output **must** be rectangular and have the same height as the inputs.
It is guaranteed that the kerning process ends before the left edge of the second input slides over the left edge of the first input.
## Rules and scoring
The lowest byte count in each programming language wins.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
## Test cases
To help with copy-pasting, these test cases are given as lists of strings.
```
["#"] ["#"] -> ["#.#"]
["#.","..",".#"] ["##","..","##"] -> ["#..##",".....",".#.##"]
["..#","#..","#.."] ["...","..#","###"] -> ["..#..","#...#","#.###"]
["###.","##..","#...","...."] ["....","...#","..#.",".#.."] -> ["###..","##..#","#..#.","..#.."]
["..##...","#......","#......"] [".....##",".....##",".#...#."] -> ["..##..##","#.....##","#.#...#."]
["...#.",".....",".....",".....","....#"] [".....","....#","#....",".....","....."] -> ["...#..",".....#",".#....","......","....#."]
["..#..",".....",".....",".....","....#"] [".....","....#","#....",".....","....."] -> ["..#..","....#","#....",".....","....#"]
["######","#.....","#.....","#.....","######"] ["......",".....#",".#...#",".....#","......"] -> ["######..","#......#","#..#...#","#......#","######.."]
["######","#.....","#.....","#.....","######"] ["......","......",".#....","......","......"] -> ["######","#.....","#.#...","#.....","######"]
["#...#","#..#.","#.#..","##...","#.#..","#..#.","#...#"] ["...#.","..#..",".#...",".#...",".#...","..#..","...#."] -> ["#...#..#","#..#..#.","#.#..#..","##...#..","#.#..#..","#..#..#.","#...#..#"]
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~40~~ 39 bytes
-1 thanks to Erik the Outgolfer
```
{⌈⌿↑⍺(⍉(1-⌈/+⌿+∘×⍨2⌈/0,+/⌈\↑(⌽⍺)⍵)↑⍉⍵)}
```
[Try it online!](https://tio.run/##tVM9T8MwEN37Kyrd4Fht3dKdgQGxMHUFhihNP6RIrdpUokJdAEVtaRAdEPwExN4FCTHwT/xHwiV2zk4/xAKLfX73/O5dfHGHQa09dYNBt@YF7njc9xL5@NwfyOipkXRwvZGruVx9yWgt4w9HxgvnqIZQvYJgRc5fv19k/NZMkUa1Usf9EqmOXH0inct4w7ObizSaJUmYKo5wkcu7Tp0BO25m@Y18uMe6mGCMQoQdJoBdjK74rMTO/U54FkyHvXKr3@3p8PR66Huh327540kQlk@8cOIG6sBKIfp9xyLc7NG6Kpe3DFCWp/lojTErM5EtmsIAcggIEkKjQnPTc66ByZSsruDKNaqksxwp4Tnn6VtgKWGs6hJHFzWaGlFuQJsRZF3fBPKkG8w4xq@WBpF3lEemjtWxijLLhgH5RwHDASJRqdyA6WV7B7soYVp35w43ugSSPUJIp9C1@B8r8Cu38MJgfbX9geJYVnY7hQJi@1G37UelSbAM0lwq7h/ZEwcfYsteURgOVKB/tDjNIMyUF86UL7yk9Qdod/t284o042qWrc9nqlsGQGyjNlcr8NIP "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 154 bytes
```
lambda a,b,p=".":[c.rstrip(p)+d.lstrip(p).rjust(max(len((d+c).strip(p))for(c,d)in zip((a*3)[1:],b[:-1]+b+b[1:]))+1-len(c.rstrip(p)),p)for(c,d)in zip(a,b)]
```
[Try it online!](https://tio.run/##tVJNb4MwDL33V0TkEo/UEuoNqb@EckiAaqyURsCkbX@ehXxC6XHLIbGf7fecOOp7en/0p/lGzpe5E3dZCyK45OqcYJIXFQ7jNLSKKUhr7LyNw8fnOLG7@GJd0zNWpxWgD8L1MbCK19D25EcjTLydoMjykssiP2ZlKlO5uABpdlzKVyLA1XO57gbKuW6upBJjo10iIT8QvXQi6YhOuzmUqKHtJ9aBCVsHDgdTVyQ0KTkxBwQIE56g2XyUeoSuExEXnNqA3k0u2kob2qRrz1L4Apu4KnSAVbNtGN61oqtbjq0VSNC1G6wlg25pHHvU3J10RRggp7Yr2XSI/0RNzQo3fm3YnMgfiOJLbJC/FfEje0J2IvHG9ku4R4vDDX@EeuWo50ZHo9qrM87BjH7@BQ "Python 3 – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina), 223 bytes
```
+`(.+)¶(¶(.+¶)*)(\W+(¶|$))
$2$1i$4
T`.`i`\.*i\.*
+`(¶(.)*#.*i.*¶(?<-2>.)*)i
$1@
+`(¶(.)*)i(.*¶(?<-2>.)*(?(2)(?!))#.*i)
$1@$3
T`i@`.`i*[#@]+i
mT`.`i`\.+i+$
msT`i`.`.*^\W+$.*
+`(\b(i+)\W+\2i*)i
$1.
+s`\bi((i+).+\b\2\b)
.$1
i
```
[Try it online!](https://tio.run/##rVFLTsMwEN3PKUpsJE9cRmpgiWgPUYlFXTCRuvCiLChLzpUD5GJhnPGH0i4bJWP7@X3szNfhO3x@TPdm65e7Zu/H4R0WMA7jMFlvyOI4GH7JjgO2aNyr5eWPRgTd6VXQT7D15IN31Ab@gEWRjq1igFqer58fuhcGMIBebSoBgznbN2vToVnfIUYpRrJ@ZPewiQHtTm32NsAxx9lgNRxPvM8AtW98Mi35rjfBIq9dFySVwJ6864OJG2Rd7zrXI5BeQYBp2jWq2S/mClypWTY0lwSrDChhEEVECcQ1kkgUspN4PIoqM4VSFWkt/pI7@0lGEsThfJbVlE5WZpGgsj4Z1piLUVWngqSUC0U6E93aU81Pudz1iXCKcXGolz5DbuSe@/EP@eNebyeNTv@ndq50XuXIEpS6o2rMtbH@8djXXw "Retina – Try It Online") Link includes test cases plus header script to reformat them to its preferred input format of two newline-delimited strings. This seems overly long yet there's probably an edge case that I've overlooked, but it does at least pass all of the test cases now. Explanation:
```
+`(.+)¶(¶(.+¶)*)(\W+(¶|$))
$2$1i$4
```
Join the two input arrays together using a letter `i` as a separator. (This allows use of `\W` and `\b` later on.)
```
T`.`i`\.*i\.*
```
Change all the `.`s to `i`s at the join.
```
+`(¶(.)*#.*i.*¶(?<-2>.)*)i
$1@
```
Change all `i`s below `#`s to `@`s.
```
+`(¶(.)*)i(.*¶(?<-2>.)*(?(2)(?!))#.*i)
$1@$3
```
Change all `i`s above `#`s to `@`s.
```
T`i@`.`i*[#@]+i
```
Change all the `@`s to `.`s, plus all the `i`s adjacent to `@`s or `#`s.
```
mT`.`i`\.+i+$
```
If there is no `#` after an `i`, then change the adjacent `.` back to an `i` again.
```
msT`i`.`.*^\W+$.*
```
If there is a line with no `i`s, change all the `i`s to `.`s, as there is nothing to do here.
```
+`(\b(i+)\W+\2i*)i
$1.
```
Calculate the minimum number of `i`s on any line.
```
+s`\bi((i+).+\b\2\b)
.$1
```
Propagate to the other lines.
```
i
```
Delete the `i`s, thus performing the required kerning.
] |
[Question]
[
Programming Puzzles & Code Golf has opened a [taco truck](https://en.wikipedia.org/wiki/Food_truck)! The word is out and now users from all over the Stack Exchange network are coming to try our tasty, authentic ASCII [tacos](https://en.wikipedia.org/wiki/Taco). We need your help to ensure that everyone gets their orders in a timely manner. There isn't a whole lot of room inside food trucks, so you'll need your code to be as short as possible.
Now for some on-the-job training.
## Your job
Write a full program that reads an order from STDIN or a function that gets a single string order as input. Tacos are printed to STDOUT, made to order.
## Taking orders
Customers will give you their orders via STDIN or function argument. Orders will be in the form of a comma-delimited list of desired toppings. The order in which the toppings are given dictates the order in which they appear in the taco, with the first listed topping on the bottom and the last on the top. Here's what we keep in stock:
* Beans
* Rice
* Veggies
* Lettuce
* Guacamole
* Sour cream
* Salsa
Customers may order as few as 1 topping but no more than 5 toppings. Toppings need not be distinct.
You may assume that the customers are familiar with the menu before ordering and thus all orders will only contain ingredients that we stock. That is, the input will always be valid.
## Serving tacos
Customers demand their tacos be printed to STDOUT. They're fine with some leading or trailing whitespace in their food.
Market research shows that everyone wants to eat tacos as words, and words in all caps are much more flavorful. Thus we will list toppings in ALL CAPS with no spaces.
In the interest of artsy presentation, we can't just plop stuff in a tortilla and call it good, we have to gently lay toppings left to right, wrapping and repeating as needed. Each topping gets a minimum of 2 lines to itself. This will all become clearer once we inspect the sample platter.
## Sample platter
Let's take a look at some sample orders.
The customer orders: `Beans,Veggies,Rice,Lettuce,Sour Cream`
We deliver:
```
SOUR
CREAMS
T LETTUC L
O ELETTU I
R RICERI T
T CERICE R
I VEGGIE O
L SVEGGI T
L BEANSB A
A EANS L
TORTIL
```
Looks pretty tasty, right? The toppings wrap after 6 characters to a new line and are repeated to fill 2 lines each, truncated to 12 characters. The first ingredient gets 6 characters on its top line but only 4 on its second line. This ensures that it fits in the fold of the tortilla. Similarly, the last ingredient always gets 4 characters on its top line and 6 on its second.
What happens if a customer orders two of the same topping in a row? Keep wrapping that ingredient for all consecutive lines of that ingredient.
The customer orders: `Lettuce,Lettuce,Lettuce,Salsa`
We deliver:
```
T SALS L
O ASALSA I
R LETTUC T
T ELETTU R
I CELETT O
L UCELET T
L TUCELE A
A TTUC L
TORTIL
```
The customer orders: `Guacamole`
```
T L
O I
R T
T R
I O
L GUAC T
L AMOLEG A
A UACA L
TORTIL
```
Only one ingredient? Give 4 extra characters' worth on the top.
## Employees of the month
```
var QUESTION_ID=65888,OVERRIDE_USER=20469;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
---
Happy cooking!
[Answer]
## Python 3, 475 bytes
```
n=range
s=input().upper().replace(" ","").split(",")[::-1]
s=sum(zip(s,s),tuple())
t=""
p=0
l=len(s)
if l==2:q=s[0];s=[q,q,q];l=3
r=[]
e=" "
f=e*4
d=[f," AL ","L A","L T","I O","T R","R T","O I","T L",f,f]
for i in n(l):
h=s[i]
c=6
a=""
if i==0 or i==l-1:c=4
if t!=h:
p=0
t=h
for x in n(0,c):
a+=h[p]
p+=1
if p==len(h):
p=0
if c==4:a=e+a+e
r+=[a]
r=["TORTIL"]+r[::-1]
for i in n(0,11):
y=10-i
x=d[y]
m=e*6
if y<=l:m=r[y]
print(x[:2]+m+x[2:])
```
It's probably way too long, but I may as well post something!
[Answer]
# JavaScript (ES6), ~~269~~ 263 bytes
```
x=>eval('x=x.split`,`;p=o="";for(i=10;i--;){t=x[1]?x[i/2|0]:x[i>2|0];t!=p?r=(n=0,t?t.replace(s=" ",""):s).toUpperCase().repeat(99):0;m=r.slice(n,n+=p&&i?6:4);p&&i?0:m=s+m+s;p=t;o+=(i>7?t?s+s+m:"":i?"TORTILL"[7-i]+s+m+s+"LITROTA"[7-i]:` A${m}L`)+`\n`}')+" TORTIL"
```
## Explanation
```
x=>
eval(' // use eval to save writin return and {}
x=x.split`,`; // convert ingredients to an array
p= // p = previous ingredient
o=""; // o = output text
for(i=10;i--;){ // loop from top to bottom of taco
t=x[1]?x[i/2|0] // t = ingredient text
:x[i>2|0]; // start a line early if 1 ingredient
t!=p?r= // r = repeated ingredient text
(n=0, // n = current index in repeated text
t?t.replace(s=" ",""):s) // get the ingredient (or space)
.toUpperCase().repeat(99):0; // upper-case and repeat the ingredient
m=r.slice(n,n+=p&&i?6:4);p&&i?0:m=s+m+s; // m = text in the middle of the taco
p=t; // set p to current ingredient
// Add the appropriate output
o+=(i>7?t?s+s+m:"":i?"TORTILL"[7-i]+s+m+s+"LITROTA"[7-i]:` A${m}L`)+`\n`
} // implicit: eval returns o
')+" TORTIL" // return the output text
```
## Test
```
var solution = x=>eval('x=x.split`,`;p=o="";for(i=10;i--;){t=x[1]?x[i/2|0]:x[i>2|0];t!=p?r=(n=0,t?t.replace(s=" ",""):s).toUpperCase().repeat(99):0;m=r.slice(n,n+=p&&i?6:4);p&&i?0:m=s+m+s;p=t;o+=(i>7?t?s+s+m:"":i?"TORTILL"[7-i]+s+m+s+"LITROTA"[7-i]:` A${m}L`)+`\n`}')+" TORTIL"
```
```
<input type="text" id="input" value="Beans,Veggies,Rice,Lettuce,Sour Cream" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
[Answer]
## Ruby, ~~376~~ ~~375~~ ~~368~~ ~~363~~ 362 bytes
```
->a{p='ALLITROT'.chars
s='LATORTIL'.chars
t=[' TORTIL']
c=[*a.split(?,).chunk(&:upcase)]
c.map.with_index{|x,i|n=x[1].size*2
w=x[0].tr(' ','')*9*n
[n+=i==0?1:0,w.sub!(/..../,' \0 ')]if i==c.size-1
w.chars.each_slice(6).take(n).reverse.map{|l|t=["#{p.shift||' '} #{l*''} #{s.shift||' '}"]+t}}
p.map{|x|t=[x+' '*8+s.shift]+t}
t[-2].sub! /(.{6})../,' \1'
t.join$/}
```
Still a work in progress.
(Bonus: Works with as many toppings as you want, not just 5. Mostly because I didn't see that rule at first >\_<)
Ungolfed version:
```
#!/usr/bin/env ruby
def make_taco ingredients
# These three variables make up the tortilla.
prefixes = 'ALLITROT'.chars
suffixes = 'LATORTIL'.chars
taco = [' TORTIL']
# .chunk is a Ruby builtin that's *incredibly* useful for this challenge.
chunks = ingredients.split(',').chunk{|x| x}.to_a
# Loop through every chunk of equal ingredients.
chunks.each_with_index do |ingredient, idx|
# Get the number of lines the group of ingredients should take up.
count = ingredient[1].length * 2
# *9 because that's guaranteed to be enough ingredient.
wrapped = ingredient[0].upcase.sub(' ','') * 9 * count
# If this is the last element...
if idx == chunks.length - 1
# Add spaces strategically to position the top "layer."
wrapped.sub! /..../, ' \0 '
# If this is also the first element...
if idx == 0
# We need to make one more row.
count += 1
end
end
# Arrange the ingredient like so, and then for each "layer"...
wrapped.chars.each_slice(6).take(count).reverse.each do |line|
# Add it to the taco, along with prefixes/suffixes if they exist.
taco.push "#{prefixes.shift || ' '} #{line * ''} " +
"#{suffixes.shift || ' '}"
end
end
# Fill in the rest of the prefixes and suffixes we didn't use.
prefixes.each do |prefix|
taco.push prefix + ' ' * 8 + suffixes.shift
end
# Fix the "offset" on the second-to-last line.
taco[1].sub! /(.{6})../, ' \1'
# Since we've been building the taco bottom-up, reverse, join, and return.
taco.reverse.join("\n")
end
puts make_taco 'Beans,Veggies,Rice,Lettuce,Sour Cream'
puts
puts make_taco 'Lettuce,Lettuce,Lettuce,Salsa'
puts
puts make_taco 'Guacamole'
```
] |
[Question]
[
**Monday Mini-Golf:** A series of short [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") questions, posted (hopefully!) every Monday.
Sometimes folks get tired of life's rules: "don't do this", "you can't do that", "we won't let you do this". It can seem really restricting at times! But every now and then, it's good to have a little fun, so let's write some code to modify these rules. And while we're at it, might as well modify other negativity as well. (Of course, these modifications ~~won't~~ WILL be only temporary, so we'll leave the original wording too.)
# Challenge
Your challenge is to write a program or function that puts HTML `<s>`~~strikethroughs~~`</s>` around restrictive words—that is, words ending in `n't` or followed by `not`—and after each of these, inserts its positive equivalent in ALL CAPS. At the end, after a space, the number of replacements made should be included. For example:
```
Please don't jump into the pool.
```
becomes
```
Please <s>don't</s> DO jump into the pool. 1
```
For words ending in `n't` or followed by `not` (as well as `cannot`), the positive equivalent is everything up to the aforementioned `not` (excluding spaces). Here's what I mean:
* `do not speak` becomes `<s>do not</s> DO speak`
* `it doesn't work` becomes `it <s>doesn't</s> DOES work`
* `we cannot` becomes `we <s>cannot</s> CAN`
However, there are a few exceptions. Make sure these are handled properly.
```
can't -> <s>can't</s> CAN
won't -> <s>won't</s> WILL
ain't -> <s>ain't</s> AM
shan't -> <s>shan't</s> SHALL
I'm not -> <s>I'm not</s> I AM
you're not -> <s>you're not</s> YOU ARE
```
## Details
* The input will never contain any whitespace except normal spaces (no tabs, newlines, etc.).
* The input will never contain any double negatives (e.g. `we can't not do this`).
* If a `not` appears immediately after a punctuation mark, or as part of another word, leave it be.
* Be sure to preserve the original text, including upper/lowercase, between the `<s></s>` tags.
* If you wish, you may use `<strike></strike>` in place of `<s></s>`.
# Test-cases
**Inputs:**
```
I'm sorry, but you can't do that.
Driving on the beach isn't allowed.
Driving on the beach is not allowed.
Please don't jump in; I cannot imagine what might come of that.
Don't worry; we won't get into trouble.
I'm not perfect, but you're not either.
You shan't do it 'cause I ain't doin' it!
Can't we capitalize special cases?
I don't like the words can't, shan't, won't, don't, ain't, or ppcgn't.
Oh, this? It's nothing.
Tie a slipknot in the rope.
Would you like Pinot Noir?
This sentence contains none of the replacement words. Not even knot or ca't.
This sentence doesn't contain one of the replacement words.
```
**Outputs:**
```
I'm sorry, but you <s>can't</s> CAN do that. 1
Driving on the beach <s>isn't</s> IS allowed. 1
Driving on the beach <s>is not</s> IS allowed. 1
Please <s>don't</s> DO jump in; I <s>cannot</s> CAN imagine what might come of that. 2
<s>Don't</s> DO worry; we <s>won't</s> WILL get into trouble. 2
<s>I'm not</s> I AM perfect, but <s>you're not</s> YOU ARE either. 2
You <s>shan't</s> SHALL do it 'cause I <s>ain't</s> AM doin' it! 2
<s>Can't</s> CAN we capitalize special cases? 1
I <s>don't</s> DO like the words <s>can't</s> CAN, <s>shan't</s> SHALL, <s>won't</s> WILL, <s>don't</s> DO, <s>ain't</s> AM, or <s>ppcgn't</s> PPCG. 7
Oh, this? It's nothing. 0
Tie a slipknot in the rope. 0
Would you like Pinot Noir? 0
This sentence contains none of the replacement words. Not even knot or ca't. 0
This sentence <s>doesn't</s> DOES contain one of the replacement words. 1
```
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest valid code in bytes wins. Tiebreaker goes to submission that reached its final byte count first. The winner ~~will not~~ WILL be chosen next Monday, Oct 26. Good luck!
[Answer]
# [Pip](http://github.com/dloscutoff/pip), ~~138~~ 140 bytes
Yeesh, that `cannot`/`knot` distinction is tricky.
```
x:"ca wo ai sha i'm you're"^sY"CAN0WILL0AM0SHALL0I AM0YOU ARE"^0OqR-`([\w']+)( no|n'|(?<=can)no)t\b`{++i"<s>".a."</s>".s.((yx@?LCb)|UCb)}s.i
```
Reads a line from stdin, outputs to stdout. The regex:
```
`([\w']+)( no|n'|(?<=can)no)t\b`
```
matches a word (including apostrophes) followed by one of three things:
* `not`
* `n't`
* `not` without a space, provided the first half of the word was `can`
The `-` operator on a regex makes it case-insensitive.
Matches are replaced with the result of the following function. (Note: within the function, `a` is the whole match and `b` is capture group 1.)
```
{++i"<s>".a."</s>".s.((yx@?LCb)|UCb)}
++i Increment counter
"<s>".a."</s>" Return entire match wrapped in HTML tags...
.s.( ) plus space, plus the following:
LCb Lowercase first capture group
x@? Find its index in list x of special cases (nil if
not in list)
(y ) Use that as index into list y of replacements
|UCb If it wasn't a special case, this is nil, and we
instead use uppercase(b)
```
Once the modified string is done, we also output a space and the number of replacements `i`.
[Answer]
# GNU Sed, 321 bytes
(including +1 for `-r`)
```
:
s!(can('|no)t)([^<])!<s>\1</s> CAN\3!i
s!(won't)([^<])!<s>\1</s> WILL\2!i
s!(ain't)([^<])!<s>\1</s> AM\2!i
s!(shan't)([^<])!<s>\1</s> SHALL\2!i
s!(I'm not)([^<])!<s>\1</s> I AM\2!i
s!(you're not)([^<])!<s>\1</s> YOU ARE\2!i
t
s!(([^ .!?]+)(n't| not))([^<])!<s>\1</s> \U\2\4!i
t
h
s/1//g
s/<s>/1/g
s/[^1]//g
x
G
s/\n/ /
```
"String replacement - a job for sed!" I thought. But this was surprisingly hard, and I kept inflooping with the substitution of the original text. And the counting! At least there's no prohibition on unary in the question...
[Answer]
## Perl, 153 bytes
**150 script + 3 for `-p`**
```
$c=0|s!\b((ca)nnot|([\w']+)(?: not|n't))\b!"<s>$&</s> ".uc({ai,AM,ca,CAN,wo,WILL,sha,SHALL,"i'm","I AM","you're","YOU ARE"}->{lc$+}||$+)!egi;s/
/ $c
/
```
So whilst I match all the test cases now but that regex has cost me dearly... I'll think on it!
### Example output:
```
$perl -p can.pl <<< "I'm sorry, but you can't do that.
Driving on the beach isn't allowed.
Driving on the beach is not allowed.
Please don't jump in; I cannot imagine what might come of that.
Don't worry; we won't get into trouble.
I'm not perfect, but you're not either.
You shan't do it 'cause I ain't doin' it!
Can't we capitalize special cases?
I don't like the words can't, shan't, won't, don't, ain't, or ppcgn't.
Oh, this? It's nothing.
This sentence contains none of the replacement words. Not even knot or ca't.
This sentence doesn't contain one of the replacement words.
Tie a slipknot in the rope.
Would you like Pinot Noir?
You cannot be serious\!"
```
```
I'm sorry, but you <s>can't</s> CAN do that. 1
Driving on the beach <s>isn't</s> IS allowed. 1
Driving on the beach <s>is not</s> IS allowed. 1
Please <s>don't</s> DO jump in; I <s>cannot</s> CAN imagine what might come of that. 2
<s>Don't</s> DO worry; we <s>won't</s> WILL get into trouble. 2
<s>I'm not</s> I AM perfect, but <s>you're not</s> YOU ARE either. 2
You <s>shan't</s> SHALL do it 'cause I <s>ain't</s> AM doin' it! 2
<s>Can't</s> CAN we capitalize special cases? 1
I <s>don't</s> DO like the words <s>can't</s> CAN, <s>shan't</s> SHALL, <s>won't</s> WILL, <s>don't</s> DO, <s>ain't</s> AM, or <s>ppcgn't</s> PPCG. 7
Oh, this? It's nothing. 0
This sentence contains none of the replacement words. Not even knot or ca't. 0
This sentence <s>doesn't</s> DOES contain one of the replacement words. 1
Tie a slipknot in the rope. 0
Would you like Pinot Noir? 0
You <s>cannot</s> CAN be serious\! 1
```
] |
[Question]
[
[This question is a follow up to [Compute the runs of a string](https://codegolf.stackexchange.com/questions/84410/compute-the-runs-of-a-string) ]
>
> A period `p` of a string `w` is any positive integer `p` such that `w[i]=w[i+p]`
> whenever both sides of this equation are defined. Let `per(w)` denote
> the size of the smallest period of `w` . We say that a string `w` is
> periodic iff `per(w) <= |w|/2`.
>
>
>
So informally a periodic string is just a string that is made up from another string repeated at least once. The only complication is that at the end of the string we don't require a full copy of the repeated string as long as it is repeated in its entirety at least once.
For, example consider the string `x = abcab`. `per(abcab) = 3` as `x[1] = x[1+3] = a`, `x[2]=x[2+3] = b` and there is no smaller period. The string `abcab` is therefore not periodic. However, the string `ababa` is periodic as `per(ababa) = 2`.
As more examples, `abcabca`, `ababababa` and `abcabcabc` are also periodic.
For those who like regexes, this one detects if a string is periodic or not:
```
\b(\w*)(\w+\1)\2+\b
```
The task is to find all **maximal** periodic substrings in a longer string. These are sometimes called **runs** in the literature.
>
> A substring `w` is a maximal periodic substring (run) if it is periodic and neither `w[i-1] = w[i-1+p]` nor `w[j+1] = w[j+1-p]`. Informally, the "run" cannot be contained in a larger "run"
> with the same period.
>
>
>
Because two runs can represent the same string of characters occurring in different places in the overall string, we will represent runs by intervals. Here is the above definition repeated in terms of intervals.
>
> A run (or maximal periodic substring) in a string `T` is an interval
> `[i...j]` with `j>=i`, such that
>
>
> * `T[i...j]` is a periodic word with the period `p = per(T[i...j])`
> * It is maximal. Formally, neither `T[i-1] = T[i-1+p]` nor `T[j+1] = T[j+1-p]`. Informally, the run cannot be contained in a larger run
> with the same period.
>
>
>
Denote by `RUNS(T)` the set of runs in string `T`.
**Examples of runs**
* The four maximal periodic substrings (runs) in string `T = atattatt` are `T[4,5] = tt`, `T[7,8] = tt`, `T[1,4] = atat`, `T[2,8] = tattatt`.
* The string `T = aabaabaaaacaacac` contains the following 7 maximal periodic substrings (runs):
`T[1,2] = aa`, `T[4,5] = aa`, `T[7,10] = aaaa`, `T[12,13] = aa`, `T[13,16] = acac`, `T[1,8] = aabaabaa`, `T[9,15] = aacaaca`.
* The string `T = atatbatatb` contains the following three runs. They are:
`T[1, 4] = atat`, `T[6, 9] = atat` and `T[1, 10] = atatbatatb`.
Here I am using 1-indexing.
**The task**
Write code so that for each integer n starting at 2, you output the largest numbers of runs contained in any binary string of length `n`.
**Score**
Your score is the highest `n` you reach in 120 seconds such that for all `k <= n`, no one else has posted a higher correct answer than you. Clearly if you have all optimum answers then you will get the score for the highest `n` you post. However, even if your answer is not the optimum, you can still get the score if no one else can beat it.
**Languages and libraries**
You can use any available language and libraries you like. Where feasible, it would be good to be able to run your code so please include a full explanation for how to run/compile your code in Linux if at all possible.
**Example optima**
In the following: `n, optimum number of runs, example string`.
```
2 1 00
3 1 000
4 2 0011
5 2 00011
6 3 001001
7 4 0010011
8 5 00110011
9 5 000110011
10 6 0010011001
11 7 00100110011
12 8 001001100100
13 8 0001001100100
14 10 00100110010011
15 10 000100110010011
16 11 0010011001001100
17 12 00100101101001011
18 13 001001100100110011
19 14 0010011001001100100
20 15 00101001011010010100
21 15 000101001011010010100
22 16 0010010100101101001011
```
**What exactly should my code output?**
For each `n` your code should output a single string and the number of runs it contains.
**My Machine** The timings will be run on my machine. This is a standard ubuntu install on an AMD FX-8350 Eight-Core Processor. This also means I need to be able to run your code.
**Leading answers**
* **49** by Anders Kaseorg in **C**. Single threaded and run with L = 12 (2GB of RAM).
* **27** by cdlane in **C**.
[Answer]
# C
This does a recursive search for optimal solutions, heavily pruned using an upper bound on the number of runs that could be finished by the unknown remainder of the string. The upper bound computation uses a gigantic lookup table whose size is controlled by the constant `L` (`L=11`: 0.5 GiB, `L=12`: 2 GiB, `L=13`: 8 GiB).
On my laptop, this goes up through *n* = 50 in 100 seconds; the next line comes at 142 seconds.
```
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#define N (8*sizeof(unsigned long long))
#define L 13
static bool a[N], best_a[N];
static int start[N/2 + 1], best_runs;
static uint8_t end_runs[2 << 2*L][2], small[N + 1][2 << 2*L];
static inline unsigned next_state(unsigned state, int b)
{
state *= 2;
state += b;
if (state >= 2 << 2*L) {
state &= ~(2 << 2*L);
state |= 1 << 2*L;
}
return state;
}
static void search(int n, int i, int runs, unsigned state)
{
if (i == n) {
int r = runs;
unsigned long long m = 0;
for (int p = n / 2; p > 0; p--) {
if (i - start[p] >= 2*p && !(m & 1ULL << start[p])) {
m |= 1ULL << start[p];
r++;
}
}
if (r > best_runs) {
best_runs = r;
memcpy(best_a, a, n*sizeof(a[0]));
}
} else {
a[i] = false;
do {
int r = runs, bound = 0, saved = 0, save_p[N/2], save_start[N/2], p, s = next_state(state, a[i]);
unsigned long long m = 0;
for (p = n/2; p > i; p--)
if (p > L)
bound += (n - p + 1)/(p + 1);
for (; p > 0; p--) {
if (a[i] != a[i - p]) {
if (i - start[p] >= 2*p && !(m & 1ULL << start[p])) {
m |= 1ULL << start[p];
r++;
}
save_p[saved] = p;
save_start[saved] = start[p];
saved++;
start[p] = i + 1 - p;
if (p > L)
bound += (n - i)/(p + 1);
} else {
if (p > L)
bound += (n - (start[p] + p - 1 > i - p ? start[p] + p - 1 : i - p))/(p + 1);
}
}
bound += small[n - i - 1][s];
if (r + bound > best_runs)
search(n, i + 1, r, s);
while (saved--)
start[save_p[saved]] = save_start[saved];
} while ((a[i] = !a[i]));
}
}
int main()
{
for (int n = 0; n <= N; n++) {
if (n <= 2*L) {
for (unsigned state = 1U << n; state < 2U << n; state++) {
for (int b = 0; b < 2; b++) {
int r = 0;
unsigned long long m = 0;
for (int p = n / 2; p > 0; p--) {
if ((b ^ state >> (p - 1)) & 1) {
unsigned k = state ^ state >> p;
k &= -k;
k <<= p;
if (!(k & ~(~0U << n)))
k = 1U << n;
if (!((m | ~(~0U << 2*p)) & k)) {
m |= k;
r++;
}
}
}
end_runs[state][b] = r;
}
small[0][state] = end_runs[state][0] + end_runs[state][1];
}
}
for (int l = 2*L < n - 1 ? 2*L : n - 1; l >= 0; l--) {
for (unsigned state = 1U << l; state < 2U << l; state++) {
int r0 = small[n - l - 1][next_state(state, 0)] + end_runs[state][0],
r1 = small[n - l - 1][next_state(state, 1)] + end_runs[state][1];
small[n - l][state] = r0 > r1 ? r0 : r1;
}
}
if (n >= 2) {
search(n, 1, 0, 2U);
printf("%d %d ", n, best_runs);
for (int i = 0; i < n; i++)
printf("%d", best_a[i]);
printf("\n");
fflush(stdout);
best_runs--;
}
}
return 0;
}
```
Output:
```
$ gcc -mcmodel=medium -O2 runs.c -o runs
$ ./runs
2 1 00
3 1 000
4 2 0011
5 2 00011
6 3 001001
7 4 0010011
8 5 00110011
9 5 000110011
10 6 0010011001
11 7 00100110011
12 8 001001100100
13 8 0001001100100
14 10 00100110010011
15 10 000100110010011
16 11 0010011001001100
17 12 00100101101001011
18 13 001001100100110011
19 14 0010011001001100100
20 15 00101001011010010100
21 15 000101001011010010100
22 16 0010010100101101001011
23 17 00100101001011010010100
24 18 001001100100110110011011
25 19 0010011001000100110010011
26 20 00101001011010010100101101
27 21 001001010010110100101001011
28 22 0010100101101001010010110100
29 23 00101001011010010100101101011
30 24 001011010010110101101001011010
31 25 0010100101101001010010110100101
32 26 00101001011010010100101101001011
33 27 001010010110100101001011010010100
34 27 0001010010110100101001011010010100
35 28 00100101001011010010100101101001011
36 29 001001010010110100101001011010010100
37 30 0010011001001100100010011001001100100
38 30 00010011001001100100010011001001100100
39 31 001001010010110100101001011010010100100
40 32 0010010100101101001010010110100101001011
41 33 00100110010001001100100110010001001100100
42 35 001010010110100101001011010110100101101011
43 35 0001010010110100101001011010110100101101011
44 36 00101001011001010010110100101001011010010100
45 37 001001010010110100101001011010110100101101011
46 38 0010100101101001010010110100101001011010010100
47 39 00101101001010010110100101101001010010110100101
48 40 001010010110100101001011010010110101101001011010
49 41 0010100101101001010010110100101101001010010110100
50 42 00101001011010010100101101001011010110100101101011
51 43 001010010110100101001011010110100101001011010010100
```
Here are [*all* optimal sequences for *n* ≤ 64](https://glot.io/snippets/egszelg3ry/raw/runs.txt) (not just the lexicographically first), generated by a modified version of this program and many hours of computation.
# A remarkable nearly-optimal sequence
The prefixes of the infinite fractal sequence
```
1010010110100101001011010010110100101001011010010100101…
```
that is invariant under the transformation 101 ↦ 10100, 00 ↦ 101:
```
101 00 101 101 00 101 00 101 101 00 101 101 00 …
= 10100 101 10100 10100 101 10100 101 10100 10100 101 10100 10100 101 …
```
seem to have very nearly optimal numbers of runs—always within 2 of optimal for *n* ≤ 64. The number of runs in the first *n* characters divided by *n* approaches (13 − 5√5)/2 ≈ 0.90983. But it turns out this is not the optimal ratio—see comments.
[Answer]
Since it's not a race if there's only one horse, I'm submitting my solution though it's only a fraction the speed of Anders Kaseorg's and a only a third as cryptic. Compile with:
>
> gcc -O2 run-count.c -o run-count
>
>
>
The heart of my algorithm is a simple shift and XOR scheme:
[](https://i.stack.imgur.com/tTbK0.jpg)
A run of zeros in the XOR result that's greater than or equal to the current period/shift indicates a run in the original string for this period. From this you can tell how long the run was and where it starts and ends. The rest of the code is overhead, setting up the situation and decoding the results.
I'm hoping it will make at least 28 after two minutes on Lembik's machine. (I wrote a pthread version, but only managed to make it run even slower.)
```
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
enum { START = 0, WIDTH } ;
// Compare and shuffle just one thing while storing two
typedef union {
uint16_t token;
uint8_t data[sizeof(uint16_t)];
} overlay_t;
#define SENTINAL (0) // marks the end of an array of overlay_t
#define NUMBER_OF_BITS (8 * sizeof(uint64_t))
void period_runs(uint64_t xor_bits, uint8_t nbits, uint8_t period, overlay_t *results) {
overlay_t *results_ptr = results;
uint8_t count = 0;
for (uint8_t position = 0; position < nbits; position++) {
if (xor_bits & 1ULL) {
if ((nbits - position) < period) {
break; // no room left to succeed further
}
if (count >= period) { // we found a run
results_ptr->data[START] = position - (count - 1);
results_ptr->data[WIDTH] = period + count;
results_ptr++;
}
count = 0;
} else {
count++;
}
xor_bits >>= 1;
}
if (count >= period) { // process the final run, if any
results_ptr->data[START] = 0;
results_ptr->data[WIDTH] = period + count;
results_ptr++;
}
results_ptr->token = SENTINAL;
}
void number_runs(uint64_t number, uint8_t bit_length, overlay_t *results) {
overlay_t sub_results[bit_length];
uint8_t limit = bit_length / 2 + 1;
uint64_t mask = (1ULL << (bit_length - 1)) - 1;
overlay_t *results_ptr = results;
results_ptr->token = SENTINAL;
for (uint8_t period = 1; period < limit; period++) {
uint64_t xor_bits = mask & (number ^ (number >> period)); // heart of the code
period_runs(xor_bits, bit_length - period, period, sub_results);
for (size_t i = 0; sub_results[i].token != SENTINAL; i++) {
bool stop = false; // combine previous and current results
for (size_t j = 0; !stop && results[j].token != SENTINAL; j++) {
// lower period result disqualifies higher period result over the same span
stop = (sub_results[i].token == results[j].token);
}
if (!stop) {
(results_ptr++)->token = sub_results[i].token;
results_ptr->token = SENTINAL;
}
}
mask >>= 1;
}
}
int main() {
overlay_t results[NUMBER_OF_BITS];
for (uint8_t bit_length = 2; bit_length < 25; bit_length++) {
int best_results = -1;
uint64_t best_number = 0;
for (uint64_t number = 1ULL << (bit_length - 1); number < (1ULL << bit_length); number++) {
// from the discussion comments, I should be able to solve this
// with just bit strings that begin "11...", so toss the rest
if ((number & (1ULL << (bit_length - 2))) == 0ULL) {
continue;
}
uint64_t reversed = 0;
for (uint8_t i = 0; i < bit_length; i++) {
if (number & (1ULL << i)) {
reversed |= (1ULL << ((bit_length - 1) - i));
}
}
if (reversed > number) {
continue; // ~ 1/4 of bit_strings are simply reversals, toss 'em
}
number_runs(number, bit_length, results);
overlay_t *results_ptr = results;
int count = 0;
while ((results_ptr++)->token != SENTINAL) {
count++;
}
if (count > best_results) {
best_results = count;
best_number = number;
}
}
char *best_string = malloc(bit_length + 1);
uint64_t number = best_number;
char *string_ptr = best_string;
for (int i = bit_length - 1; i >= 0; i--) {
*(string_ptr++) = (number & (1ULL << i)) ? '1' : '0';
}
*string_ptr = '\0';
printf("%u %d %s\n", bit_length, best_results, best_string);
free(best_string);
}
return 0;
}
```
Output:
```
> gcc -O2 run-count.c -o run-count
> ./run-count
2 1 11
3 1 110
4 2 1100
5 2 11000
6 3 110011
7 4 1100100
8 5 11001100
9 5 110010011
10 6 1100110011
11 7 11001100100
12 8 110110011011
13 8 1100100010011
14 10 11001001100100
15 10 110010011001000
16 11 1100100110010011
17 12 11001100100110011
18 13 110011001001100100
19 14 1101001011010010100
20 15 11010110100101101011
21 15 110010011001001100100
22 16 1100101001011010010100
23 17 11010010110100101001011
24 18 110100101001011010010100
25 19 1100100110010001001100100
26 20 11010010100101101001010010
27 21 110010011001000100110010011
28 22 1101001010010110100101001011
```
] |
[Question]
[
In APL, you can write tacit functions, called *trains*. How they work is irrelevant for this challenge. Here are the different ways they can be grouped, using `⍴` as the function:
```
⍴ -> ⍴
⍴⍴ -> ⍴⍴
⍴⍴⍴ -> ⍴⍴⍴
⍴⍴⍴⍴ -> ⍴(⍴⍴⍴)
⍴⍴⍴⍴⍴ -> ⍴⍴(⍴⍴⍴)
⍴⍴⍴⍴⍴⍴ -> ⍴(⍴⍴(⍴⍴⍴))
...
```
The order remains the same. The procedure is that as long as there are strictly more than 3 functions, the last 3 functions are grouped into one function. If we meet a nested train, we parenthesize that first, before continuing. Here is the procedure applied to `⍴⍴⍴⍴⍴⍴`:
```
Step 0: ⍴⍴⍴⍴⍴⍴
There are strictly more than 3 functions, repeat.
Step 1: ⍴⍴⍴(⍴⍴⍴)
There are strictly more than 3 functions, repeat.
Step 2: ⍴(⍴⍴(⍴⍴⍴))
There are 3 or less functions, we're done.
```
Here is the same procedure applied to `⍴⍴⍴(⍴⍴)⍴(⍴⍴⍴⍴(⍴⍴⍴))⍴⍴`:
```
Step 0: ⍴⍴⍴(⍴⍴)⍴(⍴⍴⍴⍴(⍴⍴⍴))⍴⍴
There are strictly more than 3 functions, repeat.
We have met a nested train, applying procedure to that first:
Step 0: ⍴⍴⍴⍴(⍴⍴⍴)
There are strictly more than 3 functions, repeat.
We have met a nested train, applying procedure to that first:
Step 0: ⍴⍴⍴
There are 3 or less functions, we're done.
Step 1: ⍴⍴(⍴⍴(⍴⍴⍴))
There are 3 or less functions, we're done.
Step 1: ⍴⍴⍴(⍴⍴)⍴((⍴⍴(⍴⍴(⍴⍴⍴)))⍴⍴)
There are strictly more than 3 functions, repeat.
We have met a nested train, applying procedure to that first:
Step 0: ⍴⍴
There are 3 or less functions, we're done.
Step 2: ⍴⍴⍴((⍴⍴)⍴((⍴⍴(⍴⍴(⍴⍴⍴)))⍴⍴))
There are strictly more than 3 functions, repeat.
Step 3: ⍴(⍴⍴((⍴⍴)⍴((⍴⍴(⍴⍴(⍴⍴⍴)))⍴⍴)))
There are 3 functions or less, we're done.
```
# Input
For this challenge, input will be simplified. This means that you can choose 2 different chars for opening and closing parentheses and 1 char for functions, different from the ones chosen for parentheses. The chars you choose must be consistent. The input will not be empty, and will not contain parentheses with no content (i.e. `()`).
# Output
Again, you may choose 3 different chars, 2 for parentheses and 1 for functions. Note that they need not be the same as the ones chosen for input, but they must be consistent.
# Rules
* If there are parentheses which only enclose one function within them in the input, you must remove them in the output. Your output may not contain unneeded parentheses (i.e. enclosing only one function, or enclosing the whole output).
* You don't need to implement the algorithm used here, as long as your solution is valid for this challenge.
* Input and output are strings in the format explained in the Input and Output sections. The input will have at least one character.
* Using the [standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/41024) is strictly forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins. However, there won't be an accepted answer, since this is a per-language competition, and to encourage answering in languages in which this task would result in longer code compared to code written in other languages.
# Test cases
The chars used here are `()⍴`, you should replace them with your chosen chars.
```
⍴ -> ⍴
⍴ -> ⍴
⍴⍴ -> ⍴⍴
⍴⍴⍴ -> ⍴⍴⍴
⍴⍴⍴⍴ -> ⍴(⍴⍴⍴)
⍴⍴⍴⍴⍴⍴⍴⍴⍴⍴⍴⍴⍴⍴⍴ -> ⍴⍴(⍴⍴(⍴⍴(⍴⍴(⍴⍴(⍴⍴(⍴⍴⍴))))))
⍴⍴⍴⍴⍴(⍴⍴⍴)⍴⍴(⍴(⍴⍴⍴)⍴⍴⍴)⍴⍴⍴ -> ⍴(⍴⍴(⍴⍴((⍴⍴⍴)⍴(⍴(⍴(⍴⍴⍴)(⍴⍴⍴))(⍴⍴⍴)))))
(⍴⍴⍴)(⍴⍴⍴)(⍴⍴⍴) -> (⍴⍴⍴)(⍴⍴⍴)(⍴⍴⍴)
(⍴⍴⍴)(⍴⍴⍴)⍴⍴⍴ -> (⍴⍴⍴)(⍴⍴⍴)(⍴⍴⍴)
⍴⍴(⍴)⍴⍴ -> ⍴⍴(⍴⍴⍴)
((⍴⍴)) -> ⍴⍴
⍴⍴((⍴⍴))⍴⍴ -> ⍴⍴((⍴⍴)⍴⍴)
```
This challenge has been posted in the Sandbox. If you have the required privilege, you can view the sandbox post [here](https://codegolf.meta.stackexchange.com/a/14312/41024).
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~71~~ ~~68~~ ~~65~~ 63 bytes
```
0{⍵≡⍕⍵:⍵⋄⍬≡⍵:'⍬'⋄1=≢⍵:⍺∇⊃⍵⋄3≥≢⍵:⍺⌽')(',⍣⍺∊1∇¨⍵⋄⍺∇¯3(↓,∘⊂1∇↑)⍵}⍎
```
[Try it online!](https://tio.run/##jZHBSsNAEIbveQpvswsptBQ8BHwTL6ElpRiMpAER6UUlNtEtihS8WhF6ELyYi@AljzIvEmd3DdkkTdtlyUxmv5n5Z9e98HvjK9cPJr2R785m01GBy9U0wPipX3jye40iw@QNxYocR/483KH4VKHMAXKBIoMTTNYa@MHFPaa3mhxi8mGcPP4CZ2CjeFdcOiA235RFZWb@NWQYv9i4eMX0Rp5j/MyJmKNYFoWXb@zTYxTfqrHlSaM304ZXbi0uj7i2Mo2VOAfLimhOPeY6JNcjJQ5chsH5BKQokYUkD4IzmFuq7VHXirSqf1GwEzPJHXBkIAbenaESjKEbWXs3bGnODjbqSuVqtzWIKtAK1jwwhylNPYW1C5lSGrJI1XbQvLDaBezHu0p2PNRhJauRefdrN55Hpf4B "APL (Dyalog Classic) – Try It Online")
The characters I chose for I/O are `'('`, `')'`, and `'⍬'`.
This solution is itself an APL train.
`⍎` parses the input as if it's a nested array - a tree with empty numeric vectors (`⍬`) as leaves.
The dfn (i.e. lambda - `{ }`) traverses the tree recursively and converts it to a properly parenthesised string. The left argument `⍺` controls whether parentheses should be added to the current level if necessary.
The dfn handles the following cases based on the right argument:
* if it's already a string (`⍵≡⍕⍵`), return it
* if it's `⍬`, return the char `'⍬'`
* if it's a singleton, just dig deeper (`∇` is the symbol for a recursive call)
* if its length is ≤3, recurse for each of the items and surround with `()` if necessary
* otherwise, recurse for the 3-tail, prepend all but the 3-tail, and recurse again
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 56 bytes
Beats APL!
```
lW%~]]]{{_,{K_,({~}|}&}%{_,3>}{3/(aa\+:~}w}:K~~`1>W<W%S/
```
[Try it online!](https://tio.run/##S85KzP3/PydctS42Nra6Ol6n2jteR6O6rramVq1WFcg3tqutNtbXSEyM0baqqy2vtfKuq0swtAu3CVcN1v//HwA "CJam – Try It Online")
This works (I think) and I have no idea why...
Input characters are `][T` for `()⍴`, and output characters are `][0` for `()⍴` (yes, this means they are reversed from what you would expect; for example, you might pass in `TTT]TT[T]TTTT]TTT[[TT`).
## High-Level Overview
The program works with the input backwards, because it's more convenient. To parse the input, we leverage CJam's parser — reversing and executing the input provides the (backwards) parsed form of the input.
We then define a procedure `K`. `K` does most of the work for our submission, and it works as follows:
* The input array will be a mix of zeroes and nonempty sub-arrays. Identify the sub-arrays and recursively apply `K` to them. The result should be another array, and if this array consists of just a single element, unpack it (this gets rid of redundant parentheses).
* As long as the result has more than three elements, group its first three (not its last three; recall that the input is being processed backwards) into a single list.
* Return the result.
By applying `K` to the input, we get the properly parenthesized form of the input (the only thing to note is that we actually wrap the input in a singleton list and unwrap it afterwards; the reason for this is that we want the snippet that unpacks singletons to apply to the top-level program, and not just its sub-arrays). Afterwards, we just apply some minimal formatting to get our result.
# Some explanation for golfed bits
The golf I'm most proud of is using `,` to perform the check between integers and arrays.
* If the top-of-stack is an integer *n*, `,` generates the range *[0..n)*. Since the only integer we will encounter is `0`, this always gives us the empty list `[]`, which is falsey.
* If the top-of-stack is an array, `,` takes its length. Since all arrays we encounter will be non-empty, this always gives us a positive integer, which is truthy.
Another golf that might be of interest is the method I use to group the first three elements of the array; it's somewhat similar to [my "Turing complete language interpreter code golf" submission](https://codegolf.stackexchange.com/a/120967/61384). CJam doesn't have a short way to break an array into two pieces (you can try to slice off the first part and then the other part while keeping the original array and index on the stack, but that doesn't work very well), so what I do instead is use `3/`, which groups an array into blocks of 3. I can then pop off the first element `(`, wrap in array twice `aa`, and then append back on to the start of the list `\+`. The reason we wrap in array twice is that we have to take off a layer with `:~`, since we just grouped the rest of the array into sections as well.
[Answer]
## JavaScript (ES6), ~~149~~ 146 bytes
```
i='a';f=s=>s==(s=s[R='replace'](/\((\w+)\)/,(q,t)=>(f[q=i+=0]=f(t),q)))&&s==(s=s[R](/(?!^)((a0+|p){3})$/,"($1)"))?s[R](/a0+/g,t=>`(${f[t]})`):f(s)
```
```
<textarea cols=80 id=I>ppp(pp)p(pppp(ppp))pp</textarea><br>
<button onclick=O.innerText=f(I.value)>Run</button><br>
<pre id=O></pre>
```
Uses `()p`, although you to use a different letter you can just change the `p` toward the end.
] |
[Question]
[
This challenge is inspired by [this fantastic animated diagram](http://www.datapointed.net/visualizations/math/factorization/animated-diagrams/) (thanks to flawr for posting it in chat).
Given an input `n`, draw all of its prime factors as nested polygons of dots, as specified.
For example, given the number `357 = 17x7x3`, you arrange 3 dots in a triangle, 7 versions of those triangles in a heptagon, and 17 versions of those heptagons in a 17-gon. In short, nested polygons going from the largest prime factor on the outside to the smallest on the inside. For `357`, your answer should look a little like this (with or without color):
[](https://i.stack.imgur.com/mznik.png)
Every polygon of every prime `>= 3` should not be rotated around the diagram.
The only exception is the prime `2`, specifically for odd powers of `2`. As you can see in the example for `376 = 47x2x2x2` below, the `8`s rotate and are not single lines of `2`s, but are vertical stacks for `4`s in a square. Even powers of `2`, arranged in squares, do not need to be rotated in this way.
[](https://i.stack.imgur.com/5jzcF.png)
In fact, `448 = 7x2x2x2x2x2x2` has a diagram that looks like a heptagon of `64`s, and `64` is arranged into a square of squares of squares, but without rotation.
[](https://i.stack.imgur.com/ZtW2H.png)
Two more examples are `440 = 11x5x2x2x2` and `432 = 3x3x3x2x2x2x2`. We see that `440` with an odd power of 2, has rotated `8`s, but `432` with an even power of `2` does not rotate its `16`s.
[](https://i.stack.imgur.com/U2laG.png) [](https://i.stack.imgur.com/KZOhp.png)
And finally, here is a minimal example, `10 = 5x2`, without color that I mocked up with Python and its `turtle` module.
[](https://i.stack.imgur.com/oax3w.png)
**The challenge**
* Given an input `n` where `1 <= n <= 10000`, output an image of its nested factor polygons.
* Rules are:
+ The image is made up of nested polygons of dots, from a polygon with (the largest prime factor) sides on the outside to the smallest prime factor on the inside.
+ For the factor 2, the powers of 2 should stack as a line, then a squares, then a line of squares, and so on. Even powers of 2 should not be rotated. Odd powers of 2 should be rotated around their respective polygons, and they should be stacked vertically before rotation.
* You may orient the image however you like (though I prefer up), but every nested polygon should be facing the same direction as any other polygon with the sole exception of odd powers of 2.
* You have two options for image size and dot size:
+ The image size is static and the dot size decreases as `n` increases (as in the animation).
+ The dot size is static and the image size grows as `n` increases.
* The first **three** layers of polygons should be distinguishable from neighboring polygons (i.e. not touching), but considering the size of the images at and around `n=10000`, it's okay if the layers after start to touch. I'd prefer it if they didn't, but it may be unavoidable to fit on an image that is uploadable to Stack Exchange.
* Color is optional.
* The shape of the dots is up to you. If squares are better for your language, use those.
* No bonuses, but I would like to see someone animate and color the diagrams like in the original post.
Thanks to Conor O'Brien, EasterlyIrk, Martin Ender, Kritixi Lithos, Mego, DJ McMayhem, and El'endia Starman for their help in writing this question.
This code golf, so shortest code wins. Good luck and good golfing!
[Answer]
# Python 3.5, ~~331~~ ~~309~~ ~~308~~ ~~306~~ 304 bytes
It took quite a bit of messing with the spacing of the polygons (and the specification, too, to be honest) to get this answer to work, but I finally did it and hopefully other answers can start coming in.
**Edit:** -2 bytes thanks to FlipTack. -8 bytes from removing a section of code that I forgot to remove earlier. -12 bytes from golfing the last function. -1 byte from changing the circumference of the drawings from `size=2500` to `size=2e3`, which also allows the drawings to better fit on screens (`diameter ~= 795.77` down to `diameter ~= 636.62`). -2 bytes from fixing a bug. -2 bytes from restructuring how I build `a`.
Golfing suggestions welcome. Trinket for testing and images to follow shortly.
```
from math import*
from turtle import*
ht();pu()
def g(n):
i=1;a=[]
while n%4<1:a+=4,;n//=4
while n>1:
i+=1
while n%i<1:a+=i,;n//=i
return f(a,2e3)
def f(a,s,x=0,y=0,t=0):
if a:
*c,b=a;s/=b
for i in range(b):u=2*pi*i/b+t*(b<3)+pi/4*(b==4);f(c,s,x+s*sin(u),y+s*cos(u),u)
else:goto(x,y);dot(4)
```
Here's `g(448)`, which now fits on my 1366x768 screen.
[](https://i.stack.imgur.com/UTFOI.png)
**Ungolfing**
```
import math
import turtle
turtle.hideturtle() # don't display the turtle itself)
turtle.penup() # don't draw lines, just dots later on
def g(n):
i = 1
a = []
while n % 4 == 0: # get 4's into the list first,
a = a + [4] # so that the fractal will be easier to structure
n = n // 4
while n > 1: # now get all of the other factors (including any stray 2's)
i += 1
while n % i == 0:
a = a + [i]
n = n // i
return f(a, 2000) # 2000 is the circumference of the circle
# on which we draw the polygons
def f(a, s, x=0, y=0, t=0):
if a:
c = a[-1] # the size of the current outermost polygon
b = a[:-1] # the rest of the factors for recursion
s = s/b # the current circumference / the number of polygons at this layer
for i in range(b):
u = 2*math.pi*i/b # angle around the circle
if b == 2: # if b == 2, add the previous angle to rotate the structure
u += t
if b == 4: # if b == 4, add 45 degrees to keep the squares upright
u += math.pi/4
dx = s * math.sin(u) # our coordinate changes for this polygon
dy = s * math.cos(u)
f(c, s, x+dx, y+dy, u) # call the function again
# on a new circle with new starting coordinates
else: # when we run out of factors,
turtle.goto(x,y) # go to each coordinate
turtle.dot(4) # and draw a dot
```
] |
[Question]
[
In this game two players compete to eat the most points worth of tokens, but there's a twist! Eating multiple tokens in a row of the same color gives an ever-growing bonus, but watch out, or your opponent will thwart your plans by eating the tokens you want before you can!
**Rules:**
* 1 versus 1
* n by n board (random size between 5x5 and 15x15)
* You and your opponent will spawn in the same random cell
* Throughout the board will be randomly generated numbers in some cells ranging in value from 1-3
* 2 \* (the width of the board) tokens will be generated, but there can be overrides, so there may be fewer by chance.
* Each number will be one of 3 colors: Red, Green, or Blue, in hex RGB format
* Each round, player 1 moves and the board is updated, then player 2 moves, and the board is updated. So each player can effectively tell what move the previous player made based on the change in the board state. This continues until the game ends, as described later.
* You have 6 possible actions for a turn: UP, RIGHT, DOWN, LEFT, EAT, and PASS
* The 4 move commands are self-explanatory, and you CAN pass your turn. If you return a nonsensical move, we will assume you meant pass. If you try to move off the edge of the board, you will not move. The edges don't wrap.
* EAT consumes the number you are currently in the same space as
* You gain as many points as the number you consume
* If you eat 2 numbers in a row of the same color, you get +1
* If you eat 3 numbers in a row of the same color, you get +2
* If you eat m numbers in a row of the same color, you get +(m-1)
* These bonuses are added cumulatively, so getting m numbers in a row leads to m\*(m-1)/2 in total bonus by the time you eat a different color.
* Game end conditions:
+ All numbers are consumed
+ 4 \* (the width of the board) turns have gone by with no effective eating (just saying “EAT” with no token where you are doesn't count) occurring by either player (any token is reachable in 2 \* (the width) moves, so this bound will only be surpassed if both players have no single target token in mind)
* Your AI should take less than a second to make a move, else PASS will be assumed as your choice.
The tournament will be round robin with a large number of rounds, say 100 or 1000. A random board is generated, and each ordered pair of different players is run on that board. After the tournament completes we will rank people by their total score. So even if you are player 2 for a game, your goal is still to get as many points as possible.
**AI Submission:** The language my controller supports is Javascript. Multiple submissions are allowed. Everyone submits a constructor for an object like this:
```
function (player1) {
this.yourMove = function (b) {
return "MOVE";
}
}
```
The input `player1` is a boolean saying whether you are player 1 or not.
Your constructor must have the `yourMove` function, but it can have
any number of additional functions or values as well. Don't define any
global variables, just put them as variables on your object. A new version
of your object will be created at the beginning of each match, and
`yourMove` will be called on it, with the current board as input, on each of your turns, and should return a valid move.
`b`, the input to `yourMove`, is a **copy** of the current board, here are the
constructors, with input examples, though you can't call them yourself:
```
function token(color, points) {
this.color = color; //"#FF0000"
this.points = points; //5
}
function player(pos, score, colorBonus, lastColor) {
this.pos = pos; //[5, 5]
this.score = score; //9
this.colorBonus = colorBonus; //i.e. 2 if you just ate 3 blue tokens in a row
//0 if you just ate two different colors.
this.lastColor = lastColor; //"#00FF00", is "#000000" at start
}
function board(player1, player2, tokens) {
this.player1 = player1; //new player([5, 5], 9, 2, "#00FF00")
this.player2 = player2; //new player([5, 5], 9, 2, "#00FF00")
this.tokens = tokens; //[[new token("#0000FF", 5), false],
// [new token("#0000FF", 5), false]]
}
```
The token array has "false" for any empty squares, and tokens[a][b] is
the token at x = a, y = b, numbered starting from the upper-left corner.
**Controller:**
[Here's](https://github.com/allenkev/annieflow/blob/master/aicomp.html) a link to the controller in GitHub. It's an html file that you can run to see how the game and the round-robin works, and it comes with two AIs, a random one that moves in a random direction each turn but eats tokens at its position, and a naive algorithm that goes for the nearest token that gives the most points. I will add in each AI as it is submitted.
Below is a snippet that allows you to run the controller on the default AI.
Current AIs:
* KindaRandomAI
* NaiveAI
* MirrorBot
* HungryBot
```
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="700" height="600" style="border:1px solid #c3c3c3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
// AI Array, put in at least two constructor functions as described in the
// data file, and it will do round robin on them.
// Also, you can adjust some variables for testing purposes only.
var interval = 1; // in milliseconds per turn
var matches = 10; // number of matches for each pairing
var aiArray = [];
myAI = function(player1) {
this.player1 = player1;
this.yourMove = function(b) {
var me;
if (this.player1) {
me = b.player1;
} else {
me = b.player2;
}
var d = 0;
var tokenP;
while (tokenP == undefined) {
var arr = this.findTokensAtDistance(me.pos, d)
tokenP = this.findBestToken(arr, b.tokens, me);
d += 1;
}
return this.startAndGoalToCommand(me.pos, tokenP);
}
this.findTokensAtDistance = function(p, d) {
if (d == 0) {
return [
[p[0], p[1]]
];
}
var myArr = [];
for (i = 0; i <= d; i++) {
myArr[i] = [i, d - i];
}
var mySecArr = [];
for (i = 0; i <= d; i++) {
mySecArr[i] = [myArr[i][0] + p[0], myArr[i][1] + p[1]];
}
mySecArr[mySecArr.length] = [myArr[0][0] + p[0], -myArr[0][1] + p[1]];
for (i = 1; i < myArr.length - 1; i++) {
mySecArr[mySecArr.length] = [-myArr[i][0] + p[0], myArr[i][1] + p[1]]
mySecArr[mySecArr.length] = [myArr[i][0] + p[0], -myArr[i][1] + p[1]]
mySecArr[mySecArr.length] = [-myArr[i][0] + p[0], -myArr[i][1] + p[1]]
}
mySecArr[mySecArr.length] = [-myArr[myArr.length - 1][0] + p[0], myArr[myArr.length - 1][1] + p[1]];
return mySecArr;
}
this.findBestToken = function(arr, t, player) {
var tokenPos;
for (i = 0; i < arr.length; i++) {
if (arr[i][0] >= 0 && arr[i][0] < t.length && arr[i][1] >= 0 && arr[i][1] < t.length) {
if (t[arr[i][0]][arr[i][1]] != false && ((tokenPos == undefined) || (this.tokenScore(player, t[arr[i][0]][arr[i][1]]) > this.tokenScore(player, t[tokenPos[0]][tokenPos[1]])))) {
tokenPos = [arr[i][0],
[arr[i][1]]
];
}
}
}
return tokenPos;
}
this.tokenScore = function(player, token) {
if (player.lastColor == token.color) {
return player.colorBonus + 1 + token.points;
} else {
return token.points;
}
}
this.startAndGoalToCommand = function(start, goal) {
var diff = [goal[0] - start[0], goal[1] - start[1]];
if (diff[0] > 0) {
return "RIGHT";
} else if (diff[1] > 0) {
return "DOWN";
} else if (diff[1] < 0) {
return "UP";
} else if (diff[0] < 0) {
return "LEFT";
} else {
return "EAT";
}
}
}
aiArray[0] = myAI;
// This is a really stupid AI, used to test that the round-robin selected
// it is the worst by far
myStupidAI = function(player1) {
this.player1 = player1;
this.yourMove = function(b) {
var me;
if (this.player1) {
me = b.player1;
} else {
me = b.player2;
}
if (b.tokens[me.pos[0]][me.pos[1]] != false) {
return "EAT";
} else {
var dirs = this.getViableDirections(b, me.pos);
var rand = Math.floor(Math.random() * dirs.length);
return dirs[rand];
}
}
this.getViableDirections = function(b, p) {
var dirs = [];
if (p[0] > 0) {
dirs.push("LEFT");
}
if (p[1] > 0) {
dirs.push("UP");
}
if (p[1] < b.tokens.length - 1) {
dirs.push("DOWN");
}
if (p[0] < b.tokens.length - 1) {
dirs.push("RIGHT");
}
return dirs;
}
}
aiArray[1] = myStupidAI;
mirrorBot = function(player1){
this.hasStarted=0;
this.player1 = player1;
this.yourMove = function(b){
this.op = this.player1 ? b.player2 : b.player1;
var out = "EAT";
if(this.hasStarted){
if(this.opl.pos[0] < this.op.pos[0]) out = "LEFT";
if(this.opl.pos[0] > this.op.pos[0]) out = "RIGHT";
if(this.opl.pos[1] < this.op.pos[1]) out = "UP";
if(this.opl.pos[1] > this.op.pos[1]) out = "DOWN";
}
this.opl = this.op;
this.hasStarted = 1;
return out;
}
}
aiArray[2] = mirrorBot;
hungryBot = function(first) {
// Set up "self"
var self = this;
// Determine player order
this.player = -(first - 2);
this.enemy = first + 1;
// Action associative array
this.actions = ['EAT', 'LEFT', 'RIGHT', 'UP', 'DOWN'];
//Logic handler
this.yourMove = function(board) {
// Determine player object
var player = board['player' + self.player];
var enemy = board['player' + self.enemy];
// Point value action grid
var actions = [0, 0, 0, 0, 0]; // Associative with "this.actions"
// Board dimensions
var size = board.tokens.length;
var maxDist = size * 2;
// Colors remaining
var colors = {
'#FF0000': 0,
'#00FF00': 0,
'#0000FF': 0
};
// Averaged value weight
var average = [0, 0];
// Total points
var points = 0;
// Token holder
var tokens = [];
// Token parser
for (var i = 0, x = 0, y = 0; i < size * size; i += 1, x = i % size, y = i / size | 0) {
if (!board.tokens[x][y]) {
continue;
} else {
var token = {};
token.points = board.tokens[x][y].points;
token.color = board.tokens[x][y].color;
token.x = x - player.pos[0];
token.y = y - player.pos[1];
token.distX = Math.abs(token.x);
token.distY = Math.abs(token.y);
token.dist = token.distX + token.distY;
token.distE = Math.abs(x - enemy.pos[0]) + Math.abs(y - enemy.pos[1]);
token.value = -token.points - (player.colorBonus + 1) * (token.color == player.lastColor) * ((token.dist == 0) + 1) * 1.618 - (enemy.colorBonus + 1) * (token.color == enemy.lastColor);
tokens.push(token);
colors[token.color] += 1;
points += token.points;
average[0] += x * token.points;
average[1] += y * token.points;
}
}
// Determine actual average
average[0] = average[0] / points | 0;
average[1] = average[1] / points | 0;
// Pick best token
var best = 0;
// Calculate point values of tokens
for (i = 0; i < tokens.length; i++) {
var token = tokens[i];
// Add remaining numbers of tokens of color as factor
token.value -= (colors[token.color] / tokens.length) * 1.618;
// Subtract distance as a factor
token.value += token.dist;
// Add distance to average to value
token.value += (Math.abs(average[0] - (token.x + player.pos[0])) + Math.abs(average[1] - (token.y + player.pos[1]))) / Math.sqrt(2);
// Consider them higher value if we are closer, and lower if they are
token.value += ((token.dist - token.distE) / (token.dist + token.distE + 0.001)) * token.dist;
// Don't go for it if enemy is already there
token.value += (token.distE == 0 && token.dist > 0) * 100;
if (tokens[best].value > tokens[i].value || (tokens[best].value === tokens[i].value && Math.round(Math.random()))) {
best = i;
}
}
// Set token to best token
var token = tokens[best];
// What to respond with
var response = 'PASS';
// Find best action to get token
if (token.dist == 0) {
response = 'EAT'; // We're on the token
} else if (token.distX >= token.distY) { // Token is more horizontal
if (token.x < 0) { // Token is left
response = 'LEFT';
} else if (token.x > 0) { // Token is right
response = 'RIGHT';
}
} else if (token.distX < token.distY) { // Token is more vertical
if (token.y < 0) { // Token is above
response = 'UP';
} else if (token.y > 0) { // Token is below
response = 'DOWN';
}
}
// Return response
return response;
}
};
aiArray[3]=hungryBot;
for (i = 0; i < aiArray.length; i += 1) {
Object.freeze(aiArray[i]);
}
// This is the actual code to run the program. You shouldn't mess with it,
// or your AI might not work during the actual competition.
// Also note that you can't access this code at all in your AI.
// Feel free to make suggestions and we'll try to incorporate them,
// and let us know if something isn't working correctly.
Object.freeze(aiArray);
setInterval((function() {
function token(color, points) {
this.color = color;
this.points = points;
}
function player(pos, score, colorBonus, lastColor) {
this.pos = pos;
this.score = score;
this.colorBonus = colorBonus;
this.lastColor = lastColor;
}
function board(player1, player2, tokens) {
this.player1 = player1;
this.player2 = player2;
this.tokens = tokens;
}
function copyBoard(b) {
return new board(copyPlayer(b.player1), copyPlayer(b.player2), copyTokens(b.tokens));
}
function copyTokens(t) {
var tokens = [];
for (i = 0; i < t.length; i++) {
tokens[i] = [];
for (j = 0; j < t[i].length; j++) {
tokens[i][j] = t[i][j];
}
}
return tokens;
}
function copyPlayer(p) {
return new player([p.pos[0], p.pos[1]], p.score, p.colorBonus, p.lastColor);
}
function endGame(b) {
if (b.player1.score > b.player2.score) {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = 20 + "px Arial";
ctx.textAlign = "left";
ctx.fillStyle = "#000000";
ctx.fillText("Player 1", 601, 160);
ctx.fillText("wins!", 601, 180);
} else if (b.player1.score < b.player2.score) {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = 20 + "px Arial";
ctx.textAlign = "left";
ctx.fillStyle = "#000000";
ctx.fillText("Player 2", 601, 160);
ctx.fillText("wins!", 601, 180);
} else {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = 20 + "px Arial";
ctx.textAlign = "left";
ctx.fillStyle = "#000000";
ctx.fillText("It's a", 601, 160);
ctx.fillText("draw!", 601, 180);
}
}
function genTokenArray(size) {
var temp = [];
for (i = 0; i < size; i++) {
temp[i] = [];
for (j = 0; j < size; j++) {
temp[i][j] = false;
}
}
return temp;
}
function genRandomTokenArray(size) {
var temp = genTokenArray(size);
for (i = 0; i < size * 2; i++) {
var rand = Math.floor(Math.random() * temp.length);
var points = Math.floor(Math.random() * 3 + 1);
var rand2 = Math.floor(Math.random() * 3);
var color;
var rand3 = Math.floor(Math.random() * temp[rand].length);
if (rand2 == 0) {
color = "#FF0000"
} else if (rand2 == 1) {
color = "#00FF00"
} else {
color = "#0000FF"
}
temp[rand][rand3] = new token(color, points);
}
return temp;
}
function countTokens(tokenArr) {
var x = 0;
for (i = 0; i < tokenArr.length; i++) {
for (j = 0; j < tokenArr[i].length; j++) {
if (tokenArr[i][j] != false) {
x += 1
}
}
}
return x;
}
function actPlayer(b, p, s) {
if (s == "UP" && p.pos[1] > 0) {
p.pos[1] -= 1;
} else if (s == "RIGHT" && p.pos[0] < b.tokens.length - 1) {
p.pos[0] += 1;
} else if (s == "DOWN" && p.pos[1] < b.tokens.length - 1) {
p.pos[1] += 1;
} else if (s == "LEFT" && p.pos[0] > 0) {
p.pos[0] -= 1;
} else if (s == "EAT" && b.tokens[p.pos[0]][p.pos[1]] != false) {
if (p.lastColor == b.tokens[p.pos[0]][p.pos[1]].color) {
p.colorBonus += 1;
p.score += p.colorBonus;
} else {
p.lastColor = b.tokens[p.pos[0]][p.pos[1]].color;
p.colorBonus = 0;
}
p.score += b.tokens[p.pos[0]][p.pos[1]].points;
b.tokens[p.pos[0]][p.pos[1]] = false;
}
}
function drawEmptyRect() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.clearRect(0, 0, 700, 600);
}
function drawToken(t, x, y, g) {
drawEntity(x, y, t.points, t.color, "#000000", 300 / g, g);
}
function drawLittleEntity(x, y, label, fillColor, labelColor, size, cX, cY, g) {
var delta = 600 / g;
var x1 = x * delta + cX * delta / 4;
var y1 = y * delta + cY * delta / 4;
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(x1, y1, size / 2, 0, 2 * Math.PI);
ctx.stroke();
ctx.fillStyle = fillColor;
ctx.fill();
ctx.font = delta / 2 + "px Arial";
ctx.textAlign = "center";
ctx.fillStyle = labelColor;
ctx.fillText(label, x1, y1 + delta * 3 / 16);
}
function drawEntity(x, y, label, fillColor, labelColor, size, g) {
var delta = 600 / g;
var x1 = x * delta + delta / 2;
var y1 = y * delta + delta / 2;
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(x1, y1, size, 0, 2 * Math.PI);
ctx.stroke();
ctx.fillStyle = fillColor;
ctx.fill();
ctx.font = delta + "px Arial";
ctx.textAlign = "center";
ctx.fillStyle = labelColor;
ctx.fillText(label, x1, y1 + delta * 3 / 8);
}
function drawAllTokens(arrToken) {
for (i = 0; i < arrToken.length; i++) {
for (j = 0; j < arrToken[i].length; j++) {
if (arrToken[i][j] != false) {
drawToken(arrToken[i][j], i, j, arrToken.length);
}
}
}
}
function drawGrid(g) {
var delta = 600 / g;
for (i = 0; i <= g; i++) {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(i * delta, 0);
ctx.lineTo(i * delta, 600);
ctx.stroke();
}
for (j = 0; j <= g; j++) {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(0, j * delta);
ctx.lineTo(600, j * delta);
ctx.stroke();
}
}
function drawPlayer1(b, g) {
drawLittleEntity(b.player1.pos[0], b.player1.pos[1], "F", "#000000", "#FFFFFF", 300 / g, 1, 1, g);
}
function drawPlayer2(b, g) {
drawLittleEntity(b.player2.pos[0], b.player2.pos[1], "S", "#000000", "#FFFFFF", 300 / g, 3, 3, g);
}
function drawScore(b) {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.font = "20px Arial";
ctx.fillStyle = "#000000";
ctx.textAlign = "left";
ctx.fillText("P" + indices[0] + " Score:", 601, 50);
ctx.fillText(b.player1.score, 601, 70);
ctx.fillText("P" + indices[1] + " Score:", 601, 100);
ctx.fillText(b.player2.score, 601, 120);
}
function drawScoreNum(s, i) {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.font = "20px Arial";
ctx.fillStyle = "#000000";
ctx.textAlign = "left";
ctx.fillText("P" + i + " Score:", 601, i * 50 + 50);
ctx.fillText(s, 601, i * 50 + 70);
}
function redraw(b, g) {
drawEmptyRect();
drawGrid(g);
drawScore(b);
drawAllTokens(b.tokens);
drawPlayer1(b, g);
drawPlayer2(b, g);
drawScoreNum()
}
function nextPair(pair, total) {
var pairRes = [pair[0], (pair[1] + 1) % total];
if (pairRes[1] == 0) {
pairRes[0] = pairRes[0] + 1;
}
return pairRes;
}
function nextGameUnfair() {
scores[indices[0]] = scores[indices[0]] + currBoard.player1.score;
scores[indices[1]] = scores[indices[1]] + currBoard.player2.score;
if (matchCount >= matches) {
matchCount = 0;
indices = nextPair(indices, aiArray.length);
if (indices[0] == indices[1]) {
indices = nextPair(indices, aiArray.length);
}
if (indices[0] >= aiArray.length) {
return false;
}
player1Turn = true;
timeWithoutEating = 0;
firstAI = new aiArray[indices[0]](true);
secondAI = new aiArray[indices[1]](false);
currBoard = genBoard();
} else {
matchCount++;
player1Turn = true;
timeWithoutEating = 0;
firstAI = new aiArray[indices[0]](true);
secondAI = new aiArray[indices[1]](false);
currBoard = genBoard();
}
return true;
}
function nextGameFair() {
scores[indices[0]] = scores[indices[0]] + currBoard.player1.score;
scores[indices[1]] = scores[indices[1]] + currBoard.player2.score;
indices = nextPair(indices, aiArray.length);
if (indices[0] == indices[1]) {
indices = nextPair(indices, aiArray.length);
}
if (indices[0] >= aiArray.length) {
indices = [0, 1];
matchCount++;
if (matchCount >= matches) {
return false;
}
player1Turn = true;
timeWithoutEating = 0;
currBoard = genBoard();
} else {
player1Turn = true;
timeWithoutEating = 0;
currBoard = savedBoard;
}
firstAI = new aiArray[indices[0]](true);
secondAI = new aiArray[indices[1]](false);
savedBoard = copyBoard(currBoard);
return true;
}
function genBoard() {
var rand = Math.floor(Math.random() * 11 + 5);
var randX = Math.floor(Math.random() * rand);
var randY = Math.floor(Math.random() * rand);
return new board(new player([randX, randY], 0, 0, "#000000"),
new player([randX, randY], 0, 0, "#000000"),
genRandomTokenArray(rand));
}
var running = true;
var indices = [0, 1];
var scores = []
for (i = 0; i < aiArray.length; i++) {
scores.push(0);
}
var matchCount = 0;
var firstAI = new aiArray[0](true);
var secondAI = new aiArray[1](false);
var player1Turn = true;
var currBoard = genBoard();
var savedBoard = copyBoard(currBoard);
var timeWithoutEating = 0;
return function() {
if (running) {
var numTokens = countTokens(currBoard.tokens);
if (numTokens <= 0) {} else if (player1Turn) {
actPlayer(currBoard, currBoard.player1, firstAI.yourMove(copyBoard(currBoard)));
} else {
actPlayer(currBoard, currBoard.player2, secondAI.yourMove(copyBoard(currBoard)));
}
player1Turn = !player1Turn;
redraw(currBoard, currBoard.tokens.length);
if (numTokens > countTokens(currBoard.tokens)) {
timeWithoutEating = 0;
} else {
timeWithoutEating += 1;
}
if (numTokens <= 0 || timeWithoutEating > 4 * currBoard.tokens.length) {
running = nextGameFair();
}
} else {
drawEmptyRect();
for (i = 0; i < scores.length; i++) {
drawScoreNum(scores[i], i);
}
}
}
})(), interval);
</script>
</body>
</html>
```
[Answer]
# HungryBot
Uses a point system to add weight to the value of pursuing each token. Uses a variety of different factors in its consideration, and reevaluates them each turn to ensure its following the best strategy.
```
function hungryBot(first) {
// Set up "self"
var self = this;
// Determine player order
this.player = -(first - 2);
this.enemy = first + 1;
// Action associative array
this.actions = ['EAT', 'LEFT', 'RIGHT', 'UP', 'DOWN'];
//Logic handler
this.yourMove = function(board) {
// Determine player object
var player = board['player' + self.player];
var enemy = board['player' + self.enemy];
// Point value action grid
var actions = [0, 0, 0, 0, 0]; // Associative with "this.actions"
// Board dimensions
var size = board.tokens.length;
var maxDist = size * 2;
// Colors remaining
var colors = {
'#FF0000': 0,
'#00FF00': 0,
'#0000FF': 0
};
// Averaged value weight
var average = [0, 0];
// Total points
var points = 0;
// Token holder
var tokens = [];
// Token parser
for (var i = 0, x = 0, y = 0; i < size * size; i += 1, x = i % size, y = i / size | 0) {
if (!board.tokens[x][y]) {
continue;
} else {
var token = {};
token.points = board.tokens[x][y].points;
token.color = board.tokens[x][y].color;
token.x = x - player.pos[0];
token.y = y - player.pos[1];
token.distX = Math.abs(token.x);
token.distY = Math.abs(token.y);
token.dist = token.distX + token.distY;
token.distE = Math.abs(x - enemy.pos[0]) + Math.abs(y - enemy.pos[1]);
token.value = -token.points - (player.colorBonus + 1) * (token.color == player.lastColor) * ((token.dist == 0) + 1) * 1.618 - (enemy.colorBonus + 1) * (token.color == enemy.lastColor);
tokens.push(token);
colors[token.color] += 1;
points += token.points;
average[0] += x * token.points;
average[1] += y * token.points;
}
}
// Determine actual average
average[0] = average[0] / points | 0;
average[1] = average[1] / points | 0;
// Pick best token
var best = 0;
// Calculate point values of tokens
for (i = 0; i < tokens.length; i++) {
var token = tokens[i];
// Add remaining numbers of tokens of color as factor
token.value -= (colors[token.color] / tokens.length) * 1.618;
// Subtract distance as a factor
token.value += token.dist;
// Add distance to average to value
token.value += (Math.abs(average[0] - (token.x + player.pos[0])) + Math.abs(average[1] - (token.y + player.pos[1]))) / Math.sqrt(2);
// Consider them higher value if we are closer, and lower if they are
token.value += ((token.dist - token.distE) / (token.dist + token.distE + 0.001)) * token.dist;
// Don't go for it if enemy is already there
token.value += (token.distE == 0 && token.dist > 0) * 100;
if (tokens[best].value > tokens[i].value || (tokens[best].value === tokens[i].value && Math.round(Math.random()))) {
best = i;
}
}
// Set token to best token
var token = tokens[best];
// What to respond with
var response = 'PASS';
// Find best action to get token
if (token.dist == 0) {
response = 'EAT'; // We're on the token
} else if (token.distX >= token.distY) { // Token is more horizontal
if (token.x < 0) { // Token is left
response = 'LEFT';
} else if (token.x > 0) { // Token is right
response = 'RIGHT';
}
} else if (token.distX < token.distY) { // Token is more vertical
if (token.y < 0) { // Token is above
response = 'UP';
} else if (token.y > 0) { // Token is below
response = 'DOWN';
}
}
// Return response
return response;
}
};
```
[Answer]
# PATH bot
Acronym stands for Pathfinding And Tree Heuristics Bot
**EDIT:** As of now, here are the rankings for the AIs, with the points
1. HungryBot (6422)
2. PATH bot (4591)
3. NaiveAI (3811)
4. KindaRandomAI (618)
5. MirrorBot (193)
6. LazyBot (25)
Link to complete controller [on github](https://github.com/jediguy13/annieflow/blob/master/aicomp_full.html)
Description: Like NaiveAI, this bot finds the nearest token that will give it the most points. However, it also simulates the outcomes of each of its moves, up to 6 times.
Rationale: Because NaiveAI is already pretty good, I though I would make it better. Without looking at the code first (big mistake).
Beats: All except HungryBot
Looses to: None except HungryBot
Problems:
* Cannot simulate increased streak
* Hangs while calculating best token
* ~~Can teleport~~
I still don't know why it was teleporting, but I fixed it. Old video here: <https://youtu.be/BIhSKycF9iA>
Full code:
```
pathBot = function (player1)
{
this.pathNode = function(pos,ppt,parents,par)
{
this.pos = pos;this.ppt = ppt;this.parents = parents;this.par=par;
this.childs=[];
}
this.addChildren = function (pn,children)
{
pn.childs=[];
for(var i=0; i<children.length; i=i+1)
{
if(pn.parents.indexOf(children[i].pos)==-1&&pn.pos!=children[i].pos)
pn.childs.push(
new this.pathNode(
children[i].pos,
children[i].ppt*pn.ppt,
pn.parents.concat([pn.pos]),
pn
)
);
}
}
this.orderTokensByPPT = function(b,pos){
var tokens = [];
for(var y=0; y<b.tokens.length; y=y+1)
{
for(var x=0; x<b.tokens[y].length; x=x+1)
{
var tok = b.tokens[y][x];
if(tok)
{
tokens.push(
new this.pathNode(
[y,x],
(tok.points+(tok.color==this.color ? this.streak : 0)) / this.lenOfMovesTo(pos,[y,x]),
[],
undefined
)
);
}
}
}
tokens.sort(function(a,b){
return b.ppt - a.ppt;
});
return tokens;
}
this.lenOfMovesTo = function(cur,pos)
{
return Math.abs(cur[0]-pos[0])+Math.abs(cur[1]-pos[1])+1;
}
this.startAndGoalToCommand = function (start, goal) {
var diff = [goal[0] - start[0], goal[1] - start[1]];
if (diff[0] > 0) { return "RIGHT"; }
else if (diff[1] > 0) { return "DOWN"; }
else if (diff[1] < 0) { return "UP"; }
else if (diff[0] < 0) { return "LEFT"; }
else { return "EAT"; }
}
this.color = 0;
this.streak = 0;
this.eatTok = function(b)
{
if(b.tokens[this.me.pos[0]][this.me.pos[1]].color==this.color)
{
this.streak++;
}
else{
this.streak = 0;
this.color = b.tokens[this.me.pos[0]][this.me.pos[1]].color;
}
this.bestToken = false;
return "EAT";
}
this.recurLen = 6;
this.include = 4;
this.recurDown = function(b,pn,level)
{
if(level==0) return pn;
this.addChildren(pn,this.orderTokensByPPT(b,pn.pos));
var newChilds = [];
for(var i=0; i<pn.childs.length&&i<this.include; i=i+1)
{
newChilds.push(this.recurDown(b,pn.childs[i],level-1));
}
pn.childs = newChilds;
return pn;
}
this.findMax = function(pn)
{
if(pn.childs)
{
var maxList = [];
for(var i=0; i<pn.childs.length; i=i+1)
maxList.push(this.findMax(pn.childs[i]));
maxList.sort(
function(a,b)
{
return b.ppt-a.ppt;
}
);
return maxList[0];
}
return pn;
}
this.findMaxList = function(pnList)
{
for(var i=0; i<pnList.lenght; i=i+1)
{
pnList[i] = this.findMax(pnList[i]);
}
pnList.sort(function(a,b){return b.ppt-a.ppt;});
return pnList[0];
}
this.bestToken=false;
this.yourMove = function(b){
this.op = player1 ? b.player2 : b.player1;
this.me = player1 ? b.player1 : b.player2;
if(this.bestToken)
{
if(b.tokens[this.bestToken.pos[0]][this.bestToken.pos[1]]==undefined)
this.bestToken = false;
}
if(!this.bestToken)
{
var paths = this.orderTokensByPPT(b,this.me.pos);
for(var i=0; i<paths.length; i++)
{
paths[i] = this.recurDown(b,paths[i],this.recurLen);
}
var max = this.findMaxList(paths);
while(max.par)
{
max = max.par;
}
this.bestToken = max;
}
var move = this.startAndGoalToCommand(this.me.pos,this.bestToken.pos);
if(move=="EAT") return this.eatTok(b);
else return move;
}
}
```
[Answer]
# NaiveAI
Starting with `r=0`, look at all tokens with taxicab distance `r` away from your position. If there are any, pick one that would give you the highest score if you got it right now. Otherwise, increase `r` by 1 and try again.
```
naiveAI = function(player1) {
this.player1 = player1;
this.yourMove = function(b) {
var me;
if (this.player1) {
me = b.player1;
} else {
me = b.player2;
}
var d = 0;
var tokenP;
while (tokenP == undefined) {
var arr = this.findTokensAtDistance(me.pos, d)
tokenP = this.findBestToken(arr, b.tokens, me);
d += 1;
}
return this.startAndGoalToCommand(me.pos, tokenP);
}
this.findTokensAtDistance = function(p, d) {
if (d == 0) {
return [
[p[0], p[1]]
];
}
var myArr = [];
for (i = 0; i <= d; i++) {
myArr[i] = [i, d - i];
}
var mySecArr = [];
for (i = 0; i <= d; i++) {
mySecArr[i] = [myArr[i][0] + p[0], myArr[i][1] + p[1]];
}
mySecArr[mySecArr.length] = [myArr[0][0] + p[0], -myArr[0][1] + p[1]];
for (i = 1; i < myArr.length - 1; i++) {
mySecArr[mySecArr.length] = [-myArr[i][0] + p[0], myArr[i][1] + p[1]]
mySecArr[mySecArr.length] = [myArr[i][0] + p[0], -myArr[i][1] + p[1]]
mySecArr[mySecArr.length] = [-myArr[i][0] + p[0], -myArr[i][1] + p[1]]
}
mySecArr[mySecArr.length] = [-myArr[myArr.length - 1][0] + p[0], myArr[myArr.length - 1][1] + p[1]];
return mySecArr;
}
this.findBestToken = function(arr, t, player) {
var tokenPos;
for (i = 0; i < arr.length; i++) {
if (arr[i][0] >= 0 && arr[i][0] < t.length && arr[i][1] >= 0 && arr[i][1] < t.length) {
if (t[arr[i][0]][arr[i][1]] != false && ((tokenPos == undefined) || (this.tokenScore(player, t[arr[i][0]][arr[i][1]]) > this.tokenScore(player, t[tokenPos[0]][tokenPos[1]])))) {
tokenPos = [arr[i][0],
[arr[i][1]]
];
}
}
}
return tokenPos;
}
this.tokenScore = function(player, token) {
if (player.lastColor == token.color) {
return player.colorBonus + 1 + token.points;
} else {
return token.points;
}
}
this.startAndGoalToCommand = function(start, goal) {
var diff = [goal[0] - start[0], goal[1] - start[1]];
if (diff[0] > 0) {
return "RIGHT";
} else if (diff[1] > 0) {
return "DOWN";
} else if (diff[1] < 0) {
return "UP";
} else if (diff[0] < 0) {
return "LEFT";
} else {
return "EAT";
}
}
}
```
[Answer]
# KindaRandomAI
Every turn, do the following:
If there is a token at your position, "EAT".
Otherwise, move in a random viable direction, i.e. if you're at the left edge don't say "LEFT".
```
kindaRandomAI = function(player1) {
this.player1 = player1;
this.yourMove = function(b) {
var me;
if (this.player1) {
me = b.player1;
} else {
me = b.player2;
}
if (b.tokens[me.pos[0]][me.pos[1]] != false) {
return "EAT";
} else {
var dirs = this.getViableDirections(b, me.pos);
var rand = Math.floor(Math.random() * dirs.length);
return dirs[rand];
}
}
this.getViableDirections = function(b, p) {
var dirs = [];
if (p[0] > 0) {
dirs.push("LEFT");
}
if (p[1] > 0) {
dirs.push("UP");
}
if (p[1] < b.tokens.length - 1) {
dirs.push("DOWN");
}
if (p[0] < b.tokens.length - 1) {
dirs.push("RIGHT");
}
return dirs;
}
}
```
[Answer]
# LazyBot
Only eats something if he spawns on it.
This has no chance to win, but the challenge didn't have one of these, so why not.
```
lazyBot = function (player1) {
this.yourMove = function(b) {
return "EAT";
}
}
```
[Answer]
# MirrorBot
Should be called "cannon fodder"
Description: Moves the exact opposite of what the other player did
Rationale: I wanted to get comfortable programming in JS again. This should not win
Will beat: No one
Will lose to: Everyone
```
function mirror(player1) {
this.hasStarted=false;
this.player1 = player1;
this.opl=[0,0];
this.yourMove = function(b){
this.op = this.player1 ? b.player2.pos : b.player1.pos;
out = "EAT";
console.log(this.op);
console.log(this.opl);
if(this.hasStarted){
if(this.opl[0] < this.op[0]) out = "RIGHT";
if(this.opl[0] > this.op[0]) out = "LEFT";
if(this.opl[1] < this.op[1]) out = "UP";
if(this.opl[1] > this.op[1]) out = "DOWN";
}
this.opl = [this.op[0],this.op[1]];
this.hasStarted = true;
return out;
}
}
```
[Answer]
# OneTarget
Finds the token that will give the most points in the least time and will go for that one. Ranks same color tokens a little higher because of the cumulative effect.
```
function (player1) {
this.yourMove = function (b) {
var me = player1? b.player1: b.player2;
var him= player1? b.player2: b.player1;
var x = me.pos[0];
var y = me.pos[1];
var maxVal = -1;
var maxX = 0;
var maxY = 0;
for(var i = 0;i < b.tokens.length;i++){
for(var j = 0;j < b.tokens.length;j++){
if(b.tokens[i][j]){
var dist = Math.abs(x-i) + Math.abs(y-j);
var val = this.valueOf(b.tokens[i][j]);
val /= (dist + 1);
if(val > maxVal){
maxVal = val;
maxX = i;
maxY = j;
}
}
}
}
if(maxY < y)
return "UP";
if(maxX < x)
return "LEFT";
if(maxY > y)
return "DOWN";
if(maxX > x)
return "RIGHT";
return "EAT";
}
this.valueOf = function(t){
//how many points would it give you?
return t.points + (this.lastColor == t.color? 2 * this.colorBonus + 1 : 0);
}
}
```
[Answer]
## QuantityPlayer
All QuantityPlayer cares about is the amout of dots he eats, not the value or color of the dots. He know that even though all dots are different, they should be treated the same.
```
QuantityBot = function(playernum) {
this.dist = function(token) {
return (Math.abs(token[0])+Math.abs(token[1]))
}
this.yourMove = function(game_board) {
board_size = game_board.tokens.length
board_area = board_size * board_size
fete = board_size = size * 2
token_list = []
count = curr_x = curr_y = 0
while(count < board_area) {
if(game_board.tokens[x][y]) {
token_list.push([x-player.pos[0],y-player.pos[1]])
}
count++; x = count % board_size; y = Math.floor(count / size)
}
closest_token = token_list[0]
count = 1
while(count < token_list.length) {
curr_token = token_list[count]
if(dist(curr_token) < dist(closest_token)){closest_token = curr_token}
count++
}
if(dist(closest_token)==0){return 'EAT'}
else{
if(closest_token[0] >= closest_token[1]) {if(closest_token[0]<0) {return 'LEFT'} {return 'RIGHT'}}
else{if(closest_token[1]<0) {return 'UP'} {return 'DOWN'}}
}
}
}
```
] |
[Question]
[
# Problem
Say you have N [stacks](https://en.wikipedia.org/wiki/Stack_(abstract_data_type)) named S1 through SN, where each Sk (k = 1 to N) contains N copies of the number k.
For example, when N = 3 the stacks looks like this:
```
1 2 3 <- top of stack
1 2 3
1 2 3 <- bottom of stack
=======
1 2 3 <- stack index
```
Here there are 3 stacks indexed as 1, 2, and 3, and each one contains N instances of its own index.
The goal is to rearrange the N stacks such that each of them identically contains the numbers 1 through N in order from top to bottom.
e.g. for N = 3 the goal is to rearrange the stacks into:
```
1 1 1
2 2 2
3 3 3
=======
1 2 3
```
The only action you can perform with the stacks is **taking the top number from one of the stacks (popping) then immediately placing it on top of a different stack (pushing)**. This is subject to these stipulations:
* **A number can only be pushed onto a stack if it is less than or equal to the top number on that stack.**
+ e.g. a `1` can be pushed onto a stack with a `1`, `2`, or `3` at the top, but a `2` can only be pushed onto a stack with a `2` or `3` (or higher) at the top.
+ This has the effect that stacks are always [monotonically increasing](https://en.wikipedia.org/wiki/Monotonic_function) from top to bottom.
* Any nonempty stack may be popped from, and, assuming the previous bullet is satisfied, any stack may be pushed to.
* Any number may be pushed onto an empty stack.
* Stacks have no maximum height limit.
* Stacks cannot be created or destroyed, there are always N of them.
This challenge is about deciding which pops and pushes to do in order to complete the stack exchange, not necessarily in the fewest moves, but in a surefire way.
(Practicing with a deck of cards is a good way to get a feel for the problem.)
# Challenge
Write a program or function that takes in a positive integer N, guaranteed to be 3 or above. Print or return a string that denotes all the pop-push actions required to rearrange the stacks from the initial state:
```
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
=============
1 2 3 4 5
```
(N = 5 case)
To the final state:
```
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5
=============
1 2 3 4 5
```
Every line in your output must contain two numbers separated by a space. The first number is the index of the stack to pop from and the second number is the index of the stack to push to. Performing the actions of all the lines in order should arrange the stacks correctly without breaking any rules.
For example, here is a potential valid output for the N = 3 case:
```
1 2 [move the top number on stack 1 to the top of stack 2]
1 2 [repeat]
1 2 [repeat]
3 1 [move the top number on stack 3 to the top of stack 1]
2 3 [etc.]
2 3
2 3
2 1
2 1
2 1
3 1
3 1
3 1
3 2
1 2
1 2
1 2
1 3
2 3
2 3
2 3
1 2
3 2
3 1
```
### Notes
* **Your output does *not* need to be optimal**, only correct. i.e. you do not need to minimize the number of pops and pushes.
+ So it would be alright if, say, some move were repeatedly made and immediately reversed.
+ Popping and pushing to the same stack in one move, e.g. `2 2`, is allowed as well (though of course pointless).
* Your output *does* need to be deterministic and finite.
* Remember that stacks have 1-based indexing. 0-based indexing is not allowed.
* N greater than 9 should of course work just as well as single digit N.
* If desired you may use any two distinct, non-digit [printable ASCII](https://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) characters in place of spaces and newlines. A trailing newline (or newline substitute) in the output is fine.
# Scoring
The shortest code in bytes wins. Tiebreaker is higher voted answer.
Valueless brownie points if you can show your algorithm is optimal.
[Answer]
# Pyth ~~96~~ 94 bytes
```
Mt*Q+++bGdHM|%+y_GHQQg1 2++Qd1g2 3g2 1g3 1++Qd2Vr3QgNtN++QdN;g1QVStQVStQI<NHgnNHnNtH)++nN0dnNH
```
[Try it here](http://pyth.herokuapp.com/?code=Mt%2aQ%2B%2B%2BbGdHM%7C%25%2By_GHQQg1+2%2B%2BQd1g2+3g2+1g3+1%2B%2BQd2Vr3QgNtN%2B%2BQdN%3Bg1QVStQVStQI%3CNHgnNHnNtH%29%2B%2BnN0dnNH&input=5&debug=0)
## How does it work?
This explanation will be using N=5.
### Part 1: Create the bottom layer on every stack
The reason why this is needs a separate piece of code is because every stack needs to be used: the first 4 need a 5 to be put beneath them, and the last stack must provide the 5s. This means that we can't just move all the 4s somewhere, put a 5 there, and move the 4s back.
Visualization: (parentheses mean what will be moved)
```
_
11111 |
22222 |_ Can't move 4s here, not monotonically increasing
33333_|
(44444)------------??? Where to put the 4s?
55555 <- Must supply the 5 that will be moved
```
Instead, to do this first exchange, we will first move all the 1s over to to the second stack, move a 5 to the first stack (which is now empty), move the 1s to the third stack, move the 2s to the first stack, move the 1s back to the first stack, and finally move a 5 to the second stack.
```
(11111)-----.
2222211111<-'
===============================
5<---------.
2222211111 : (from stack 5)
===============================
5
22222(11111)-.
3333311111<--'
===============================
522222<-.
(22222)-'
3333311111
===============================
52222211111<-.
|
33333(11111)-'
===============================
52222211111
5<-----.
33333 |
44444 |
555(5)-'
```
Now that we have a free space to move stacks into (stack 2, which only contains a 5 that is placed in the right spot), we can move all the 3s to stack 2 and place a 5 in stack 3. We can then repeat the same thing for stack 4, and now we get all the 5s in the right place! And just one more thing: we will move all the 1s to stack 5 so that we get a nice setup for the next stack exchange.
```
522222(11111)-.
533333 |
544444 |
5 |
511111<-------'
```
## Part 2: Do everything else :)
This is much easier now, because now we will always have a free stack to move other numbers we need to juggle around into. So, first we figure out where the 4 is. A bit of examination will show that it will always be 1 up from where it started, or 2 above the last stack. Now, we just keep going down the stacks, placing a 4 in the stack if it's free, or moving the other numbers up 1 stack if it's not. Now we have all the 4s in place.
```
522222<------.
533333<----. |
544444-.-.-'-'
5<-----' |
511111<--'
===============================
5433333
54
54
5411111
5422222
```
Now, we realize that the 3s are 2 stacks above where the 4s where. This means that we can do the exact same thing we did with the 4s! And as it turns out, we can keep doing this as long as we wrap the stack index around to the other side.
```
5433333-'wrap around 543
54 543
54 54311111
5411111 .----------->54322222
5422222 |2 stacks up 543
```
And so, we can keep doing this until we have exchanged all the stacks.
## Code explanation:
### First of all: The (important) predefined variables.
```
Q: Evaluated input.
b: The newline character, '\n'
d: A space, ' '
```
### There are 2 lambda definitions.
```
M | g(G)(H), used for moving Q numbers at a time.
| We will call these Q numbers a "(number) block"
t | Tail, used to remove beginning newline
*Q | Repeat the following Q times
+++bGdH | '\n' + G + ' ' + H. Just a whole bunch of concatenating.
|
M | n(G)(H), used for figuring out which stacks to move from
| Q | If the following code is 0 (false), then use Q instead
% Q | Mod Q
+ H | Add H
y | Multiply by 2
_G | Negate (remember in the explanation part 2? Always 2 stacks above?)
```
### The stack exchanging: part 1
```
g1 2 | Move the 1 block to stack 2
++Qd1 | Move a Q to stack 1
g2 3 | Move the 1 block to stack 3
g2 1 | Move the 2 block to stack 1
g3 1 | Move the 1 block back to stack 1
++Qd2 | Move a Q to stack 2
v---Code-continuation---' |I don't have enough room!!!
Vr3Q | For N in range(3, Q)
gNtN | Move the number block in stack N up 1
++QdN | Move a Q to stack N
;g1Q | End for loop; move the 1 block to the last stack
```
### The stack exchanging: part 2
```
VStQ | For N in [1, 2, ..., Q - 1]
VStQ | For H in [1, 2, ..., Q - 1]
I<NH | If N < H
g | Number block move
nNH | (find number block)
nNtH | (find the previous stack)
) | End "For H"
++nN0dnNH | Find start, move number to next location down
```
I already know I'm not getting brownie points, cuz I can see many more efficient and more complicated methods :(
] |
[Question]
[
Fed up with [experimenting on tiny domestic animals](https://en.wikipedia.org/wiki/Schr%C3%B6dinger%27s_cat), Nobel prize-winning Erwin Schrödinger has decided to find the nearest laser and shoot it at things instead. Because... science!
# Description
You will be given two points that the laser passes through and the size of a laser beam, and you must determine where the laser beam *must* have gone, *could* have gone, and *could not* have gone.
The laser beam can be horizontal, vertical, or diagonal. For a size 1 laser beam, they look like this respectively:
```
# #
# #
##### # #
# #
# #
```
The diagonal laser beam can also be flipped. Size 2 laser beams look like this:
```
### ##
##### ### ###
##### ### ###
##### ### ###
### ##
```
In general, to get a laser beam of size (n), simply take the laser beam of size (n-1) and add a laser beam of size (1) on both sides. As a final example, here are all possible laser beams of size 3, shown on the same "board":
```
###.....#####.....##
####....#####....###
#####...#####...####
.#####..#####..#####
..#####.#####.#####.
...###############..
....#############...
.....###########....
####################
####################
####################
####################
####################
.....###########....
....#############...
...###############..
..#####.#####.#####.
.#####..#####..#####
#####...#####...####
####....#####....###
```
This "board" will always have dimensions of 20x20 (in characters).
# Input
Your program will be given five integers as input. They are, in order, x1, y1, x2, y2, and the size of the laser beam. They must be taken exactly in that order. If you wish, you may take the ordered (x, y) pairs as an array, tuple, list, or other built-in data type that stores two values.
Both of the two points given as input will be within the board, and they are guaranteed to be distinct (i.e. the two points will never be the same). The size of the laser beam is bound to `1 ≤ size < 20`. There will always be at least one possible laser beam that passes through both of the points.
# Output
Your program must output a 20x20 grid of the following characters:
* `#` if every possible laser beam that passes through the two points also passes through this point.
* `.` if there is no laser beam that passes through the two points and this point.
* `?` if some, but not all, of the possible laser beams pass through this point.
* `X` if this is one of the two original input points (this overrides the `#`).
# Test cases
7, 7, 11, 3, 1
```
..............#.....
.............#......
............#.......
...........X........
..........#.........
.........#..........
........#...........
.......X............
......#.............
.....#..............
....#...............
...#................
..#.................
.#..................
#...................
....................
....................
....................
....................
....................
```
18, 18, 1, 1, 2
```
#??.................
?X??................
??#??...............
.??#??..............
..??#??.............
...??#??............
....??#??...........
.....??#??..........
......??#??.........
.......??#??........
........??#??.......
.........??#??......
..........??#??.....
...........??#??....
............??#??...
.............??#??..
..............??#??.
...............??#??
................??X?
.................??#
```
10, 10, 11, 10, 3
```
?????..????????..???
??????.????????.????
????????????????????
????????????????????
.???????????????????
..??????????????????
????????????????????
????????????????????
????????????????????
????????????????????
??????????XX????????
????????????????????
????????????????????
????????????????????
????????????????????
..??????????????????
.???????????????????
????????????????????
????????????????????
??????.????????.????
```
3, 3, 8, 10, 4
```
??????????..........
??????????..........
??????????..........
???X??????..........
???##?????..........
???###????..........
????###????.........
.????###????........
..????###????.......
..?????##?????......
..??????X??????.....
..??????????????....
..???????????????...
..????????????????..
..?????????????????.
..??????????????????
..??????????????????
..????????.?????????
..????????..????????
..????????...???????
```
The test cases were generated with the following Ruby script, located inside a Stack Snippet to conserve vertical space.
```
/*
#!/usr/bin/ruby
$w = $h = 20
class Point
attr_reader :x, :y
def initialize x, y
@x = x
@y = y
end
def inspect
"(#{@x}, #{@y})"
end
def == p
@x == p.x && @y == p.y
end
alias eql? ==
def hash
@x * $h + @y
end
def valid?
@x >= 0 && @y >= 0 && @x < $w && @y < $h
end
end
module Angle
HORIZONTAL = Point.new(1, 0)
VERTICAL = Point.new(0, 1)
DIAG1 = Point.new(1, 1)
DIAG2 = Point.new(1, -1)
end
def line_points point, angle, size
points = [point]
while points[-1].valid?
points.push Point.new(points[-1].x + angle.x, points[-1].y + angle.y)
end
points.pop
while points[0].valid?
points.unshift Point.new(points[0].x - angle.x, points[0].y - angle.y)
end
points.shift
if size == 1
points
elsif size > 1
a2 = case angle
when Angle::HORIZONTAL then Angle::VERTICAL
when Angle::VERTICAL then Angle::HORIZONTAL
else Angle::VERTICAL # HORIZONTAL also works
end
(size-1).times do |n|
np1 = Point.new(point.x + a2.x*(n+1), point.y + a2.y*(n+1))
np2 = Point.new(point.x - a2.x*(n+1), point.y - a2.y*(n+1))
points.concat line_points np1, angle, 1 if np1.valid?
points.concat line_points np2, angle, 1 if np2.valid?
end
points
else
throw 'something is very wrong'
end
end
def generate_grid x1, y1, x2, y2, size
p1 = Point.new(x1, y1)
p2 = Point.new(x2, y2)
lasers = []
points = [Point.new((p1.x + p2.x) / 2, (p1.y + p2.y) / 2)] # midpoint
while points.length > 0
point = points.pop
new_lasers = Angle.constants
.map{|angle| line_points point, Angle.const_get(angle), size }
.select {|laser| laser.include?(p1) && laser.include?(p2) } -
lasers
if new_lasers.length > 0
lasers.concat new_lasers
points.push Point.new(point.x+1, point.y) if point.x+1 < $w
points.push Point.new(point.x, point.y+1) if point.y+1 < $h
points.push Point.new(point.x-1, point.y) if point.x-1 > 0
points.push Point.new(point.x, point.y-1) if point.y-1 > 0
end
end
grid = Array.new($h) { ?. * $w }
lasers.each do |laser|
laser.each do |point|
grid[point.y][point.x] = ??
end
end
lasers.reduce(:&).each do |point|
grid[point.y][point.x] = ?#
end
grid[p1.y][p1.x] = 'X'
grid[p2.y][p2.x] = 'X'
grid
end
testcases = [
[7, 7, 11, 3, 1],
[18, 18, 1, 1, 2],
[10, 10, 11, 10, 3],
[3, 3, 8, 10, 4]
]
testcases.each do |test|
puts test * ', '
puts
puts generate_grid(*test).map{|line| ' ' + line }
puts
end
*/
```
# Rules
* Your program must be able to solve each of the test cases in under 30 seconds (on a reasonable machine). This is more of a sanity check, as my test Ruby program solved all of the test cases near-instantaneously.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution wins.
[Answer]
# C, ~~291~~ ~~280~~ ~~277~~ 265 bytes
```
x,y,A,C,B,D,a,c,b,d,w,s,t;T(i){return abs(i)<2*w-1;}U(j,k){s+=T(j-k)*T(j)*T(k);t*=T(j-k)*j*k<1;}main(){for(scanf("%i%i%i%i%i",&a,&b,&c,&d,&w);y<20;y+=!x)s=0,t=1,U(A=a-x,C=c-x),U(B=b-y,D=d-y),U(A-B,C-D),U(A+B,C+D),putchar((x=++x%21)?".?#x"[!!s+t+(!A*!B+!C*!D)]:10);}
```
Can be compiled/run using:
*gcc laser.c -o laser && echo "10 10 11 10 3" | ./laser*
Below, the same code with whitespace and explanatory comments:
```
// Integers...
x,y,A,C,B,D,a,c,b,d,w,s,t;
// Is true if i is in range (of something)
T(i){return abs(i)<2*w-1;}
// Tests if lasers (horizontal, vertical, diagonal, etc) can/must exist at this point
// T(j-k) == 0 iff the laser of this direction can exist
// s += 1 iff this laser direction can pass through this point
// t *= 1 iff this laser direction must pass through this point
U(j,k){
s+=T(j-k)*T(j)*T(k);
t*=T(j-k)*j*k<1;
}
main(){
// Read input; p0=(a,b), p1=(c,d)
for(scanf("%i%i%i%i%i",&a,&b,&c,&d,&w); y<20; y+=!x)
// A, B, C and D represent delta-x and delta-y for each points
// e.g.: if we're processing (2,3), and p0=(4,5), A=4-2, B=5-3
// s != 0 iff (x,y) can have some laser through it
// t == 1 iff all lasers pass through (x,y)
// (!A*!B+!C*!D) == 1 iff (x,y) is either p0 or p1
s=0,t=1,U(A=a-x,C=c-x),U(B=b-y,D=d-y),U(A-B,C-D),U(A+B,C+D),
putchar((x=++x%21)?".?#x"[!!s+t+(!A*!B+!C*!D)]:10);
}
```
[Answer]
# C, 302 bytes
```
b[400],x,y,s,t,w,d,e,g,k;f(u,v){d=u*x+v*y;e=u*s+v*t;if(e<d)k=e,e=d,d=k;for(k=0;k<400&d+w>e;++k)g=k%20*u+k/20*v,b[k]|=g>e-w&g<d+w|(g<d|g>e)*2;}main(){scanf("%d%d%d%d%d",&x,&y,&s,&t,&w);w=2*w-1;f(1,0);f(0,1);f(1,1);f(1,-1);b[y*20+x]=4;b[t*20+s]=4;for(k=0;k<400;)putchar(".#.?X"[b[k]]),++k%20?0:puts("");}
```
Input is taken from stdin, reading the 5 numbers in the defined order.
Before final size reduction step:
```
#include <stdio.h>
#include <stdlib.h>
int b[400], x, y, s, t, w, d, e, g, k;
void f(int u, int v) {
d = u * x + v * y;
e = u * s + v * t;
if (e < d) k = e, e = d, d = k;
if (d + w > e) {
for (k = 0; k < 400; ++k) {
g = u * (k % 20) + v * (k / 20);
if (g > e - w && g < d + w) b[k] |= 1;
if (g < d || g > e) b[k] |= 2;
}
}
}
int main() {
scanf("%d%d%d%d%d", &x, &y, &s, &t, &w);
w = 2 * w - 1;
f(1, 0); f(0, 1); f(1, 1); f(1, -1);
b[y * 20 + x] = 4;
b[t * 20 + s] = 4;
for (k = 0; k < 400; ) {
putchar(".#.?X"[b[k]]);
++k % 20 ? 0 : puts("");
}
}
```
Some explanation of key steps:
* Array `b` holds the state/result. Bit 0 will be set for all pixels that can be reached by a beam. Bit 1 will be set for all pixels that are **not** covered by all beams.
* Function `f` is called for all 4 directions (vertical, horizontal, both diagonals). Its arguments specify the normal vector of the direction.
* In function `f`:
+ The distance of both input points relative to the direction is calculated (`d` and `e`) as the dot product of the point with the normal vector passed in.
+ The distances are swapped if necessary so that `d` is always less than or equal to `e`.
+ If the difference between `d` and `e` is larger than the width of the beam, no beams are possible in this direction.
+ Otherwise, loop over all pixels. Set bit 0 if the pixel is reachable by any beam, and bit 1 if it is not covered by all beams.
* Mark the two input points with value 4. Since we used bits 0 and 1 to track the state, which results in values 0 to 3, this is the smallest unused value.
* Loop over the pixels in `b`, and convert the values in the range 0 to 4 to their corresponding character while printing them out.
] |
[Question]
[
Everyone knows that C is a lovely, safe, high level programming language. However you, as a coder are set the following task.
>
> Write a program to add two numbers.
>
>
>
* Input: Two space separated integers.
* Output: The sum of the two numbers in the input.
The twist is that your code must be 100% safe. In other words, it must behave properly no matter what the input is. If the input is indeed two space separated integers, both of which are less than 100 digits long, it must output the sum. Otherwise, it must output an error message and quit safely.
How hard can it be after all?
General kudos will be given to pathological input cases which break other people's answers :)
The code must compile without warnings using gcc -Wall -Wextra on ubuntu.
---
**Clarification.**
* Input is from stdin.
* Horizontal whitespace is only a single space character. There should be nothing before the first number and the input should be terminated with either newline+EOF or just EOF.
* the only valid input, specified in [Augmented Backus-Naur Form](http://en.wikipedia.org/wiki/Augmented_Backus%E2%80%93Naur_Form), is:
```
NONZERODIGIT = "1" / "2" / "3" / "4" / "5" / "6" / "7" / "8" / "9"
POSITIVENUMBER = NONZERODIGIT *98DIGIT
NEGATIVENUMBER = "-" POSITIVENUMBER
NUMBER = NEGATIVENUMBER / POSITIVENUMBER / "0"
VALIDINPUT = NUMBER SP NUMBER *1LF EOF
```
* The error message is the single letter 'E', followed by a new line.
* The code must terminate cleanly in less than 0.5s no matter what the input is.
[Answer]
### 6610 bytes (unminified)
"Good boy" C program that meets all challenge criteria. Uses 10s complement for negative numbers. Also included, a test harness and test cases.
```
/*
Read input from STDIN. The input must conform to VALIDINPUT:
NONZERODIGIT = "1" / "2" / "3" / "4" / "5" / "6" / "7" / "8" / "9"
POSITIVENUMBER = NONZERODIGIT *98DIGIT
NEGATIVENUMBER = "-" POSITIVENUMBER
NUMBER = NEGATIVENUMBER / POSITIVENUMBER / "0"
VALIDINPUT = NUMBER SP NUMBER *1LF EOF
Check syntax of input. If input is correct, add the two numbers and print
to STDOUT.
LSB => least significant byte
MSB => most significant byte
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
#include <assert.h>
#define NUL ('\0')
/*
maximum characters in VALIDINPUT:
'-' 1
POSITIVENUMBER MAXDIGITS
' ' 1
'-' 1
POSITIVENUMBER MAXDIGITS
LF 1
*/
#define MAXDIGITS (99)
#define MAXVALIDINPUT (2*MAXDIGITS+4)
void die() { printf("E\n"); exit(1); }
/*
Add two NUMBERs and print the result to STDOUT. The NUMBERS have
been separated into POSITIVENUMBERS and sign information.
Arguments:
first - pointer to LSB of 1st POSITIVENUMBER
firstSize - size of 1st POSITIVENUMBER
firstNegative - is 1st # negative?
second - pointer to LSB of 2nd POSITIVENUMBER
secondSize - size of 2nd POSITIVENUMBER
secondNegative - is 2nd # negative?
carry - carry from previous place?
Returns:
sum[] - sum
addNUMBERs() - carry to next place?
- Don't use complementDigit(popDigit(p,s),n). Side-effects generate two pops.
*/
#define popDigit(p,s) ((s)--,(*(p++)-'0'))
#define complementDigit(c,n) ((n) ? 9-(c) : (c))
#define pushSum(c) (*(--sumPointer)=(c))
#define openSum() (pushSum(NUL))
#define closeSum() ;
char sum[MAXVALIDINPUT];
char *sumPointer = sum+sizeof(sum);
int addNUMBERs(char *first, int firstSize, bool firstNegative,
char *second, int secondSize, bool secondNegative,
int previousCarry) {
int firstDigit, secondDigit;
int mySum;
int myCarry;
/*
1st half of the problem.
Build a stack of digits for "first" and "second"
numbers. Each recursion of addNUMBERs() contains one digit
of each number for that place. I.e., the 1st call holds
the MSBs, the last call holds the LSBs.
If negative, convert to 10s complement.
*/
assert((firstSize > 0) && (secondSize > 0));
if (firstSize > secondSize) {
firstDigit = popDigit(first, firstSize);
firstDigit = complementDigit(firstDigit, firstNegative);
secondDigit = 0;
} else if (secondSize > firstSize) {
firstDigit = 0;
secondDigit = popDigit(second, secondSize);
secondDigit = complementDigit(secondDigit, secondNegative);
} else {
// same size
firstDigit = popDigit(first, firstSize);
firstDigit = complementDigit(firstDigit, firstNegative);
secondDigit = popDigit(second, secondSize);
secondDigit = complementDigit(secondDigit, secondNegative);
}
// recursion ends at LSB
if ((firstSize == 0) && (secondSize == 0)) {
// if negative, add 1 to complemented LSB
if (firstNegative) {
firstDigit++;
}
if (secondNegative) {
secondDigit++;
}
myCarry = previousCarry;
} else {
myCarry = addNUMBERs(first, firstSize, firstNegative,
second, secondSize, secondNegative,
previousCarry);
}
/*
2nd half of the problem.
Sum the digits and save them in first[].
*/
mySum = firstDigit + secondDigit + ((myCarry) ? 1 : 0);
if ((myCarry = (mySum > 9))) {
mySum -= 10;
}
pushSum(mySum + '0');
return(myCarry);
}
// Handle the printing logic.
void addAndPrint(char *first, int firstSize, bool firstNegative,
char *second, int secondSize, bool secondNegative,
int previousCarry) {
openSum();
addNUMBERs(first, firstSize, firstNegative,
second, secondSize, secondNegative,
previousCarry)
closeSum();
if (*sumPointer<'5') {
// it's positive
for (; *sumPointer=='0'; sumPointer++) {} // discard leading 0s
// if all zeros (sumPointer @ NUL), back up one
sumPointer -= (*sumPointer == NUL) ? 1 : 0;
printf("%s\n", sumPointer);
} else {
// it's negative
char *p;
// discard leading 0s (9s in 10s complement)
for (; *sumPointer=='9' && *sumPointer; sumPointer++) {}
// if -1 (sumPointer @ EOS), back up one
sumPointer -= (*sumPointer == NUL) ? 1 : 0;
for (p=sumPointer; *p; p++) {
*p = '0' + ('9' - *p); // uncomplement
// special handling, +1 for last digit
*p += (*(p+1)) ? 0 : 1;
}
printf("-%s\n", sumPointer);
}
return;
}
/*
Lex a number from STDIN.
Arguments:
bufferPointer - pointer to a pointer to a buffer, use as
**buffer = c; // put "c" in the buffer
*buffer += 1; // increment the buffer pointer
(*buffer)++; // also increments the buffer pointer
All sorts of side-effects:
- getc(stdin)
- ungetc(...,stdin)
- modifies value of **bufferPointer
- modifies value of *bufferPointer
Returns:
lexNUMBER() - number of bytes added to *bufferPointer,
*1 if POSITIVENUMBER,
*-1 if NEGATIVENUMBER
*bufferPointer - points to the LSB of the number parsed + 1
*/
#define pushc(c) (*((*bufferPointer)++)=c)
bool lexNUMBER(char **bufferPointer) {
char c;
int size = 0;
bool sign = false;
/* lex a NUMBER */
if ((c=getchar()) == '0') {
pushc(c);
c = getchar();
size++;
} else {
if (c == '-') {
sign = true;
c = getchar();
// "-" isn't a digit, don't add to size
}
if (c == '0') {
die();
}
for (size=0; isdigit(c); size++) {
if (size >= MAXDIGITS) {
die();
}
pushc(c);
c = getchar();
}
}
if (size < 1) {
die();
}
ungetc(c,stdin); // give back unmatched character
return (sign);
}
int main() {
int c;
char buffer[MAXVALIDINPUT];
char *bufferPointer;
char *first, *second;
int firstSize, secondSize;
bool firstNegative, secondNegative;
bufferPointer = buffer + 1; // hack, space for leading digit
// parse 1st number
first = bufferPointer;
firstNegative = lexNUMBER(&bufferPointer);
firstSize = bufferPointer - first;
*(bufferPointer++) = NUL; // hack, space for EOS
bufferPointer++; // hack, space for leading digit
// parse separating blank
if ((c=getchar()) != ' ') {
die();
}
// parse 2nd number
second = bufferPointer;
secondNegative = lexNUMBER(&bufferPointer);
secondSize = bufferPointer - second;
*(bufferPointer++) = NUL; // hack, space for EOS
// parse end of input
c = getchar();
if (! ((c == EOF) || ((c == '\n') && ((c=getchar()) == EOF))) ) {
die();
}
// Some very implementation-specific massaging.
*(--first) = '0'; // prefix with leading 0
*(first+(++firstSize)) = NUL; // add EOS
*(--second) = '0'; // prefix with leading 0
*(second+(++secondSize)) = NUL; // add EOS
// add and print two arbitrary precision numbers
addAndPrint(first, firstSize, firstNegative,
second, secondSize, secondNegative, false);
return(0);
}
```
Here's a little test harness and a few test cases to get you started. Feel free to tear out the excessive use of perl. The system it was developed on didn't have a modern bash.
```
#!/bin/bash
#
# testharness.sh
#
# Use as: bash testharness.sh program_to_be_tested < test_data
#
# Each line in the test data file should be formatted as:
#
# INPUT = bash printf string, must not contain '"'
# OUTPUT = perl string, must not contain '"'
# (inserted into the regex below, use wisely)
# TESTNAME = string, must not contain '"'
# GARBAGE = comments or whatever you like
# INPUTQUOTED = DQUOTE INPUT DQUOTE
# OUTPUTQUOTED = DQUOTE OUTPUT DQUOTE
# TESTQUOTED = DQUOTE TESTNAME DQUOTE
# TESTLINE = INPUTQUOTED *WSP OUTPUTQUOTED *WSP TESTQUOTED GARBAGE
TESTPROGRAM=$1
TMPFILE=testharness.$$
trap "rm $TMPFILE" EXIT
N=0 # line number in the test file
while read -r line; do
N=$((N+1))
fields=$(perl -e 'split("\"",$ARGV[0]);print "$#_";' "$line")
if [[ $fields -lt 5 ]]; then
echo "skipped@$N"
continue
fi
INPUT=$(perl -e 'split("\"",$ARGV[0]);print "$_[1]";' "$line")
OUTPUT=$(perl -e 'split("\"",$ARGV[0]);print "$_[3]";' "$line")
TESTNAME=$(perl -e 'split("\"",$ARGV[0]);print "$_[5]";' "$line")
printf -- "$INPUT" | $TESTPROGRAM > $TMPFILE
perl -e "\$t='^\\\s*$OUTPUT\\\s*\$'; exit (<> =~ \$t);" < $TMPFILE
if [[ $? -ne 0 ]]; then # perl -e "exit(0==0)" => 1
echo "ok $TESTNAME"
else
echo -n "failed@$N $TESTNAME," \
"given: \"$INPUT\" expected: \"$OUTPUT\" received: "
cat $TMPFILE
echo
fi
done
```
A small set of test cases:
```
"0 0" "0" "simple, 0+0=0"
"1 1" "2" "simple, 1+1=2"
"" "E" "error, no numbers"
"0" "E" "error, one number"
"0 0" "E" "error, two/too much white space"
"0 0 " "E" "error, trailing characters"
"01 0" "E" "error, leading zeros not allowed"
"-0 0" "E" "error, negative zero not allowed
"0 -0" "E" "error, negative zero not allowed here either
"1 1\n" "2" "LF only allowed trailing character
"\0001 1\n" "E" "error, try to confuse C string routines #1"
"1\00 1\n" "E" "error, try to confuse C string routines #2"
"1 \0001\n" "E" "error, try to confuse C string routines #3"
"1 1\000\n" "E" "error, try to confuse C string routines #4"
"1 1\n\000" "E" "error, try to confuse C string routines #5"
"-1 -1" "-2" "add all combinations of -1..1 #1"
"-1 0" "-1" "add all combinations of -1..1 #2"
"-1 1" "0" "add all combinations of -1..1 #3"
"0 -1" "-1" "add all combinations of -1..1 #4"
"0 0" "0" "add all combinations of -1..1 #5"
"0 1" "1" "add all combinations of -1..1 #6"
"1 -1" "0" "add all combinations of -1..1 #7"
"1 0" "1" "add all combinations of -1..1 #8"
"1 1" "2" "add all combinations of -1..1 #9"
"0 123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789" "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789" "0+99 digits should work"
"100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" "200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" "99 digits+99 digits should work"
"500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" "1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" "test for accumulator overflow"
"-123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789 0" "-123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789" "0+negative 99 digits work"
"-100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 -100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" "-200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" "99 digits+99 digits (both negative) should work"
"-500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 -500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" "-1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" "test for negative accumulator overflow"
"1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 0" "E" "error, 100 digits"
```
[Answer]
## 289
**EDIT** : This code works only for positive integers. The rules has changed since I post this answer.
```
#include <stdio.h>
#include <stdlib.h>
int r[101],s;void x(int i){r[i]|=32;if(r[i]>41)r[i+1]++,r[i]-=10,x(i+1);}void f(int b){int c=getchar();if(c!=b){if(s>99||c<48||c>57)exit(puts("E"));f(b);r[s]+=c-48;x(s++);}}int main(){f(32);s=0;f(10);for(s=100;s--;)if(r[s])putchar(r[s]+16);return 0;}
```
Ungolfed and commented version :
```
#include <stdio.h>
#include <stdlib.h>
//global variables are automatically init to zero
int result[101]; //101 because 2 numbers of 100 digits can give a 101-digits result
int currentNumber;
void reportAddition(int i) {
result[i]|=0x20; //flag "active" value, 6th bit
if(result[i]>9+0x20) {
result[i+1]++;
result[i]-=10;
reportAddition(i+1);
}
}
void addNumber(int endingChar) {
int c=getchar();
if(c!=endingChar) {
if(currentNumber>99||c<'0'||c>'9') //error
exit(puts("Error"));
addNumber(endingChar);
result[currentNumber]+=c-'0';
reportAddition(currentNumber); //handle case when addition give a value greater than 9
currentNumber++;
}
}
int main() {
addNumber(' '); //add first number
currentNumber=0;
addNumber('\n'); //add second
for(currentNumber=100;currentNumber--;)
if(result[currentNumber])
putchar(result[currentNumber]+'0'-0x20); //display char
return 0;
}
```
[Answer]
## 442
It is quite long, so I may golf it down further during the weekend. Assumes input is from stdin, EOF-terminated (without newline), separator is only one character of ASCII value 32 (that is, `' '` character).
```
#include<stdio.h>
char a[102],b[102],c[102],*p=a,d;int i,j=101,l,L,k,F=1;int main(){while(~(k=getchar())){if(47<k&&k<58){p[i++]=k;if(i==101)goto f;}else if(k==32&&F)p=b,l=i,F=0,i=0;else goto f;}L=i;for(i=(l<L?l:L)-1;i+1;i--){c[j]=(L<l?b[i]-48+a[i+l-L]:a[i]-48+b[i+L-l]);if(c[j--]>57)c[j]++,c[j+1]-=10;}for(i=(L<l?l-L-1:L-l-1);i+1;i--)c[j--]=(L<l?a[i]:b[i]);for(i=0;i<102;i++)if(c[i]&&(c[i]-48||d))d=putchar(c[i]);return 0;f:return puts("E");}
```
The error message will be a single character 'E', followed by a new line.
With newlines and a little bit of indentation added: (a readable version follows, so feel free to skip over here)
```
#include<stdio.h>
char a[102],b[102],c[102],*p=a,d;
int i,j=101,l,L,k,F=1;
int main(){
while(~(k=getchar())){
if(47<k&&k<58){
p[i++]=k;
if(i==101)goto f;
}else if(k==32&&F)p=b,l=i,F=0,i=0;
else goto f;
}
L=i;
for(i=(l<L?l:L)-1;i+1;i--){
c[j]=(L<l?b[i]-48+a[i+l-L]:a[i]-48+b[i+L-l]);
if(c[j--]>57)c[j]++,c[j+1]-=10;
}
for(i=(L<l?l-L-1:L-l-1);i+1;i--)c[j--]=(L<l?a[i]:b[i]);
for(i=0;i<102;i++)if(c[i]&&(c[i]-48||d))d=putchar(c[i]);
return 0;
f:return puts("E");
}
```
The readable version (some statements are slightly altered to make it more readable, but what they do should be the same):
```
#include <stdio.h>
char num1[102],num2[102],sum[102]; //globals initialised to 0
char *p=num1;
int outputZero=0, noExtraSpace=1;
int i=0, j=101, len1, len2, ch;
#define min(x,y) (x<y?x:y)
int main(){
while((ch=getchar())!=-1) { //assumes EOF is -1
if('0'<=ch && ch<='9') {
p[i]=ch;
i++;
if(i==101) goto fail; //if input too long
} else if(ch==' ' && noExtraSpace) {
p=num2;
len1=i;
noExtraSpace=0;
i=0;
} else goto fail; //invalid character
}
len2=i;
for(i=min(len1, len2)-1; i>=0; i--) {
//add each digit when both numbers have that digit
sum[j]=(len2<len1?num2[i]-'0'+num1[i+len1-len2]:num1[i]-'0'+num2[i+len2-len1]);
if(sum[j]>'9') { //deal with carries
sum[j-1]++;
sum[j]-=10;
}
j--;
}
for(i=(len2<len1?len1-len2-1:len2-len1-1); i>=0; i--) {
//copy extra digits when one number is longer than the other
sum[j]=(len2<len1?num1[i]:num2[i]);
j--;
}
for(i=0; i<102; i++) {
if(sum[i] && (sum[i]-'0' || outputZero)) {
putchar(sum[i]);
outputZero=1;
//if a digit has been output, the remaining zeroes must not be leading
}
}
return 0;
fail:
puts("Error");
return 0;
}
```
The `goto fail;` thing is here to mock Apple.
The version of gcc I used is `gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3`, and there are no warnings.
[Answer]
### 633 bytes
"Bad boy" C program that meets half the challenge. Abuses C, throws lots of warnings, but works ... sort of. Arbitrary precision arithmetic is actually done by `bc`.
```
#include<stdio.h>
#include<string.h>
#include<ctype.h>
#define g() getc(stdin)
#define z(c) b[i++]=c,b[i]='\0'
x(){puts("E\n");exit(1);}main(){int c,y=0,i=0;char b[232]="",*h="echo ",*t=" | bc -q | tr -d '\\\\\\012'";strcat(b,h);i=strlen(h);if((c=g())=='0'){z(c);y=1;c=g();}else{if(c=='-'){z(c);c=g();}c!='0'||x();ungetc(c,stdin);for(y=0;isdigit(c=g());y++){z(c);y<99||x();}}y>0||x();c==' '||x();z('+');y=0;if((c=g())=='0'){z(c);y=1;c=g();}else{if(c=='-'){z(c);c=g();}c!='0'||x();do{if(!isdigit(c))break;z(c);y++;y<=99||x();}while(c=g());}y>0||x();strcat(b+i,t);i+=strlen(t);if(!((c==-1)||((c=='\n')&&((c=g())==-1))))x();system(b);}
```
Unminified version
```
/*
Read input from STDIN. The input must conform to VALIDINPUT:
NONZERODIGIT = "1" / "2" / "3" / "4" / "5" / "6" / "7" / "8" / "9"
POSITIVENUMBER = NONZERODIGIT *98DIGIT
NEGATIVENUMBER = "-" POSITIVENUMBER
NUMBER = NEGATIVENUMBER / POSITIVENUMBER / "0"
VALIDINPUT = NUMBER SP NUMBER *1LF EOF
Check syntax of input. If input is correct, use the shell command
"echo NUMBER+NUMBER | bc -q" to do the arbitrary precision integer arithmetic.
NB, this solution requires that the "normal" bc be 1st in the PATH.
Fun C language features used:
- ignore arguments to main()
- preprocessor macros
- pointer arithmetic
- , operator
- ?: operator
- do-while loop
- for loop test does input
- implicit return/exit
- short is still a type!
- ungetc()
- use int as bool and 0 & 1 as magic numbers
- implicit type coersion
5/5/14, Stop fighting the syntax graph. Get rid of "positive" flag.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAXDIGITS (99)
#define pushc(c) (buffer[index++]=c,buffer[index]='\0')
#define pushs(s) (strcat(buffer+index,s),index+=strlen(s))
int die() { printf("E\n"); exit(1); }
int main () {
int c;
/*
buffer budget:
5 "echo "
1+MAXDIGITS (include "-") NUMBER
1 "+"
1+MAXDIGITS (include "-") NUMBER
25 " | bc -q | tr -d '\\\012'"
1 NUL
*/
char buffer[5+1+MAXDIGITS+1+1+MAXDIGITS+25+1] = "";
short index = 0;
short digits;
pushs("echo ");
// parse 1st number
digits = 0;
if ((c=getchar()) == '0') {
pushc(c);
digits = 1;
c = getchar();
} else {
if (c == '-') {
// "-" doesn't count against digits total
pushc(c);
c = getchar();
}
(c != '0') || die();
ungetc(c,stdin);
for (digits=0; isdigit(c=getchar()); digits++) {
pushc(c);
(digits<MAXDIGITS) || die();
}
}
(digits>=1) || die();
// parse separating blank
(c == ' ') || die();
pushc('+');
// parse 2nd number
digits = 0;
if ((c=getchar()) == '0') {
pushc(c);
digits = 1;
c = getchar();
} else {
if (c == '-') {
// "-" doesn't count against digits total
pushc(c);
c = getchar();
}
(c != '0') || die();
do {
if (!isdigit(c)) {
break;
}
pushc(c);
digits++;
(digits<=MAXDIGITS) || die();
} while(c=getchar());
}
(digits>=1) || die();
pushs(" | bc -q | tr -d '\\\\\\012'");
// parse end of input
if (! ((c == EOF) || ((c == '\n') && ((c=getchar()) == EOF))) ) {
die();
}
// add two arbitrary precision numbers and print the result to STDOUT
system(buffer);
}
```
] |
[Question]
[
# How long's left?
Recently, I was making pizza using a 5-minute timer on my phone. When someone walked in and asked me how long was left, I was confused for a moment at first as to how to answer the question. You see, if the timer at the current moment was at 3:47, by the time I had read out 'Three minutes and forty seven seconds' aloud, the time would have changed. Therefore, I need to find a time that the timer would reach *just* as I finish reading it out.
This is your challenge: to automate this process. Given a time in any appropriate format (":" delimited, or as a minute and second argument), output the earliest time from that current moment which would take an equal amount of time to read out as it would take for the timer to get to. We're assuming that each syllable takes 1 second to read out.
## Further rules
* You must count 'minutes' and 'seconds' as two of the syllables each, as well as an 'and' between them.
* The pizza will never take more than 59:59 to cook.
* '11 minutes and 0 seconds' is not 10 syllables: you must simplify to '11 minutes' (i.e 5 syllables). Same goes with minutes: '0 minutes and 7 seconds' is also only counted as 4 syllables.
* Your program can give the output in any format: an array of `[minutes, seconds]`, or even as `<minutes> minutes and <seconds> seconds` (normal text written out).
* Standard loopholes apply.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
# Test cases
All inputs as `(minutes, seconds)`
```
(4, 47) = (4, 38) (Four MiNutes And ThirTy Eight SeConds - 9 syllables/seconds)
(1, 1) = (0, 56) (FifTy-Six SeConds - 5 syllables/seconds)
(59, 57) = (59, 46) (FifTy Nine Minutes And Forty Six SeConds - 11 syllables/seconds)
(0, 10) = null/error/0 (no positive answer)
```
# Syllable count reference
For reference, here are the number of syllables in each number up to 59.
```
0,0 (does not need to be counted)
1,1
2,1
3,1
4,1
5,1
6,1
7,2
8,1
9,1
10,1
11,3
12,1
13,2
14,2
15,2
16,2
17,3
18,2
19,2
20,2
21,3
22,3
23,3
24,3
25,3
26,3
27,4
28,3
29,3
30,2
31,3
32,3
33,3
34,3
35,3
36,3
37,4
38,3
39,3
40,2
41,3
42,3
43,3
44,3
45,3
46,3
47,4
48,3
49,3
50,2
51,3
52,3
53,3
54,3
55,3
56,3
57,4
58,3
59,3
```
[Answer]
# JavaScript (ES6), ~~112 106~~ 105 bytes
*A shorter version based on a suggestion by @EmbodimentofIgnorance
6 more bytes saved by @DaniilTutubalin*
Takes input as `(minutes)(seconds)`. Returns `[minutes, seconds]` or \$0\$ if there's no solution.
```
m=>d=F=s=>m|s?(g=n=>n&&(n%10!=7)-7+(n-11?n<13?2:n<21|n%10<1:0))(m)+g(s)^~d?F(s?s-1:m--&&59,d=-~d):[m,s]:0
```
[Try it online!](https://tio.run/##bcpLDoIwFIXhubtwYHNvoKZFCKHh0hmbMJoQCkRDW2ONI8LWEYc@kjP6zn9tnk1o75fbgztvuqWnxVJlqKZAlZ2ChoEcVY4xcDsptpQjzyNwXErtSnnQiXJlIqf3WUolEMFiNEDA82x0DUEHLpXlnLGsiA3x2aA62jiclFha74Ifu/3oB@ghRUhzxM2nSlz3jVmBkP22Ym3FX/2Ha7m8AA "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), ~~126~~ 119 bytes
Takes input as `(minutes)(seconds)`. Returns `[minutes, seconds]` or \$0\$ if there's no solution.
```
m=>d=F=s=>m|s?(g=n=>n&&2+(30774612>>2*n%(n>12?20:26)&3)+(n>12)+(n>19))(m)+g(s)+!!(m*s)^d?F(s?s-1:m--&&59,d=-~d):[m,s]:0
```
[Try it online!](https://tio.run/##bcrPCoJAEMfxe2/hoWVG3VjXfyjsevMlokBclcJdo4lO0aub1KkSBn7Mh@@5uTfUXk@XG3eT6eZezVZpo2pFStsHVTAop7RjTAYQizxPskhqLX23BacjWUlRygxZjMH7/0yBCBaDAQgDzwPrEx5NVQNVxKPScs5YWoRG8afBcm9DOpRibidH09jtxmmAHhKEJEfcfGuEy/1iWiCk/61YWrGqa7iU8ws "JavaScript (Node.js) – Try It Online")
### Commented
```
m => // m = minutes
d = // d = delta in seconds between the initial time and the current time,
// initialized to a non-numeric value (zero-ish)
F = s => // F is a recursive function taking s = seconds
m | s ? ( // if either m or s is not 0:
g = n => // g is a helper function taking an integer n in [0..59]
n && // return 0 if n = 0
2 + ( // otherwise, start with 2 for either 'mi-nutes' or 'se-conds'
30774612 >> // add the base number of syllables (0 to 3) corresponding to n
2 * n % // using a bitmask of 13 entries x 2-bit:
// 12 11 10 9 8 7 6 5 4 3 2 1 0
// 01 11 01 01 01 10 01 01 01 01 01 01 00
(n > 12 ? 20 // using n MOD 10 if n is greater than 12
: 26) // or just n otherwise
& 3 // isolate the two least significant bits
) + //
(n > 12) + // add 1 syllable for '-teen' or '-ty' if n is greater than 12
(n > 19) // add 1 more syllable for 'x-ty' if n is greater than 19
)(m) + // invoke g for the minutes
g(s) + // invoke g for the seconds
!!(m * s) // add 1 syllable for 'and' if both m and s are non-zero
^ d ? // if the result is not equal to the delta:
F( // otherwise, do a recursive call:
s ? s - 1 // decrement s if it's not 0,
: m-- && 59, // or decrement m and restart with s = 59
d = -~d // increment the delta
) // end of recursive call
: // else:
[m, s] // success: return [m, s]
: // else:
0 // failure: return 0
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~287~~ 285 bytes
```
m=int(input())
s=int(input())
y=lambda w:3+(w[-1]=='7')-(w[-1]=='0')-(w[0]in'01')*(1+(w[0]=='0'))+(w=='11')-(w=='12')
z=lambda m,s:(2+y(f'{m:02d}'))*(m!=0)+(2+y(f'{s:02d}'))*(s!=0)+(m!=0!=s)
q=lambda t: (m-(t+60-s-1)//60,(s-t)%60)
print([q(t) for t in range(s+60*m) if z(*q(t))==t][0])
```
[Try it online!](https://tio.run/##VY/BqsIwEEX3/Yq4kMy0BpOKFQP5EumiD60GTKzNiFTx22tqn4q7OZx7L0zT0eHkF33vjPUE1jcXAsQk/GJnjpX721bsqhcZXDdClcbwFUfxATmCLK3nUnFMQWUvHh1GiJdSr9hw5RyT23vXzYKGPOug5nenZb59xEoKbmJkbP6L8BVhFIOfmIDJ@T1EmoETQFkhRRAK5/NCziAIwmkhMWna4a/NGQhZfWoZMetZW/n9DkKspA6ZrdkN0iGBxlAZP8C@X671cvUE "Python 3 – Try It Online")
It's not a very clever solution - it's mostly striaghtforward. Takes ~~'m:s'~~ **m and s as separate inputs** ~~(doesn't need to be padded),~~ and outputs (m,s). Throws an error if there's no valid output.
The program relies heavily on implicitly casting booleans to 0 and 1. The first line takes input. The second line defines a lambda function y which gives the syllables in a number - it assumes a base of 3 syllables, then adds 1 if it ends in 7, subtracts 1 if it ends in 0, and subtracts 1 if it's in the 10's and 2 if it's in the single digits. Twelve and eleven are manually adjusted at the end. The third line is a lambda for the syllables in the whole expression. Finally, fourth line gives the time after t seconds. Fifth line is the output - it builds an array of all the times that satisfy the problem, and outputs the first one.
**EDIT 1:** Thanks to Matthew Anderson in the comments, 2 bytes were shaved off by taking the inputs separately.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 141 bytes
```
a=>b=>((a=Enumerable.Range(1,b+=a*60).Last(i=>new[]{i/60,i%60}.Sum(x=>x<1?0:(x%10==7?4:3)+(x==11?3:x<13?1:x<21|x%10<1?2:3))-1==b-i))/60,a%60)
```
[Try it online!](https://tio.run/##XY5NawIxEIbPm18RBCFT4zbxk6qzeyj2JBS2hx7Ew@wSa6CmsBtbi/W3bxOlLfSQzMs7Dw9TNf2qse3DwVUL67z8DSJ@4UGWbbElzErMhCBcusPe1FS@mrQg92KElmUP6WaiIF1R44XFzJmP9eZkbydK2u5EndOnw14cMTsudK5m4tjVCnGaj2ZD6IUetc6Hs7Ac5jqMgf6KRGAHAYC@Riz7FiDqKOignbN4Had4Hy9hveHeNP6eGtNw5CeWiJHkoynIkLTk@hLGd5KPr50KnfpJY2DnOdu@1YaqnXin@iLj1v1JgSW@/ozi5Lm23qysM2Ir4j4luM4SYM6SM0sq8tXuH9tZFsVj0bkQ7Tc "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 46 bytes
```
ḅḶbɗ60Ṛµ“÷ṢḣxE⁻Ṇ⁹ƬƝwɼỤṡl’ḃ4+2;0⁸ịS+ṬS$’)=JTị⁸Ḣ
```
[Try it online!](https://tio.run/##y0rNyan8///hjtaHO7YlnZxuZvBw56xDWx81zDm8/eHORQ93LK5wfdS4@@HOtkeNO4@tOTa3/OSeh7uXPNy5MOdRw8yHO5pNtI2sDR417ni4uztY@@HONcEqQHFNW68QoABIeMei/zqH249OerhzxqOmNVlAgxV07RQeNczlOtwOFIhEs/rINNvD7bWHluofawdqfbhz1f9ormgTHRPzWB2uaEMdQxBlaqljCuYb6BgagGgTHeNYrlgA "Jelly – Try It Online")
A monadic link taking as its argument the time as `[minutes, seconds]` and returning the appropriate time to say as `[minutes, seconds]` or `[seconds]` if less than a minute.
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 102 bytes
```
60:X;q~\X*+:W_{;(__X%\X/{_196656821516111872\_A%K+e<_{(2*m>3&3.5+}{\;}?@}2*+i+\X*+_W=!2$0<-}g;_X%\X/S@
```
[Try it online!](https://tio.run/##S85KzP3/38zAKsK6sC4mQkvbKjy@2lojPj5CNSZCvzre0NLMzNTMwsjQ1NDM0NDQwtwoJt5R1Vs71Sa@WsNIK9fOWM1Yz1S7tjrGutbeodZISztTG2RMfLitopGKgY1ubbo1xKxgh///TS0VTC0B "CJam – Try It Online")
Just a boring old magic-number binary look-up-table, nothing to see here.
] |
[Question]
[
# The task
Write a program or function that takes a traffic intersection structure and outputs the sequence, in which vehicles will pass.
The output should contain at most four lines with the following format `#. x->y\n`, where `#` is a sequence number number, followed by the dot `.`, `x` and `y` are characters `["N", "E", "S", "W"]`. They should be separated by characters `->`. If you do not return an array of strings, each line must end with a `\n` (new line character) or equivalent to your system.
The input should take the following form:
* Part 1: four characters, each having the destination road for the source roads in order N, E, S, W (clockwise). The allowed characters are `N`, `S`, `W`, `E` or . Space means that there is no vehicle on particular road. For example string `S WE` means, that N vehicle wishes to go South, space means that there is no E vehicle, `W` means that S wishes to go West, `E` means West wishes to go East.
* Part 2 - a space or a single letter meaning which one is of the emergency vehicle.
* Part 3 - two characters determining which two roads have priority (eg. `NE` means that North and East both have higher priorities than both South and West). If it is easier for you, you may take lower priority roads (in that case `SW`).
In an unsolvable situation you are allowed to return a one-line string which is clear to the user, like `unsolvable`, `no solution` and similar. JavaScript users may take built-in `undefined` constant.
This is a code-golf, so the shortest answer in bytes wins.
# The rules of traffic
*Please note that some of the rules may not follow your country traffic rules. Some of them have been simplified to make the challenge easier. Do not use this question as a guide for real life traffic system.*
1. For the challenge you are allowed to use only right-side traffic.
2. The traffic intersection consists of exactly four roads which meet in one point. They are marked `N` (as for "North"), `S`, `W`, `E`. These letters should be used instead of `x` and `y` in the output example above.
[](https://i.stack.imgur.com/NPKYN.png)
3. On each road there is at most one vehicle. It is not guaranteed that there is a vehicle on each road. Each vehicle can drive in any of four directions, ie. turn left, turn right, go straight or make a [U-turn](https://en.wikipedia.org/wiki/U-turn).
[](https://i.stack.imgur.com/WCFrb.png)
4. If paths of two vehicles do not intersect (they do not collide), they can go at the very same moment. Paths do not collide, if two vehicles (the list might not be complete, but this is intentional, just to give you a clue):
* come from opposite directions and both go straight, or at least one of them turns right,
* come from opposite directions and both turn left,
* come from opposite directions and one of them turns in any direction or makes the U-turn, while the other makes the U-turn,
* come from orthogonal directions, the one to the left is turning right and the other does not make the U-turn
>
> Some examples of not colliding paths below. Please note that on the third drawing any path of N would collide with the path of E, even if N makes a U-turn.
>
>
>
[](https://i.stack.imgur.com/gYH7G.png) [](https://i.stack.imgur.com/nnqIO.png)
[](https://i.stack.imgur.com/vRa0w.png) [](https://i.stack.imgur.com/u21hh.png)
5. If two paths collide, it is necessary to use other rules. If two vehicles are on the same priority road (see below), the [right of way](https://en.wikipedia.org/wiki/Traffic#Priority_.28right_of_way.29) is given to the vehicle that:
* is comes from the road on the right side, if they come from orthogonal directions
* turns right if the other turns left
* goes straight or turns right if the other makes a U-turn.
>
> In both examples below the E vehicle has right of way over the vehicle S.
>
>
>
[](https://i.stack.imgur.com/ItdqM.png) [](https://i.stack.imgur.com/GyKur.png)
>
> In the example below first goes W, then N, then E and last goes S.
>
>
>
[](https://i.stack.imgur.com/4p080.png)
>
> For this particular case the output of your program should be:
>
>
>
```
1. W->S
2. N->S
3. E->S
4. S->S
```
6. All drivers use [turn signals](https://en.wikipedia.org/wiki/Automotive_lighting#Turn_signals) and know where all others want to go to (for simplicity we assume that it is possible to distinguish between the left turn and the U-turn).
7. Sometimes roads are given priority signs, which are more important that the rules above. A road with higher priority has a priority sign ([priority sign image](https://en.wikipedia.org/wiki/File:Zeichen_306_-_Vorfahrtstra%C3%9Fe,_StVO_1970.svg)). If the priority road does not go straight, also additional signs are used, like [this one](https://en.wikipedia.org/wiki/File:CZ-E02b_Tvar_k%C5%99i%C5%BEovatky.svg). The roads with lower priority have a [yield sign](https://en.wikipedia.org/wiki/Yield_sign) or a [stop sign](https://en.wikipedia.org/wiki/Stop_sign) (they are equivalent). None or exactly two different roads will have higher priority. The user of your program should be able to enter which roads have higher (or lower) priorities.
8. A vehicle that comes from the road with higher priority has the right of way over a vehicle coming from lower priority road, even if it is on its left side.
9. If paths of two vehicles coming from the roads with the same priority collide, above right-side rules are active.
>
> On the example below roads S and W have priority signs, which means that vehicles on N and E should give them the way. The S vehicle has the priority over the W vehicle, because it is on its right side, so goes first. Then goes W, because it is on the road of higher priority than E. The vehicle N has right of way from E, because it is on its right side. As the last goes E.
>
>
>
[](https://i.stack.imgur.com/UXZ7y.png)
>
> For this particular case the output of your program should be:
>
>
>
```
1. S->W
2. W->N
3. N->S
4. E->W
```
10. It is possible that one (and no more) vehicle is an [emergency vehicle](https://en.wikipedia.org/wiki/Emergency_vehicle), which has the priority regardless to which direction it comes from or goes to, and what sign it has (it always goes first). The program should allow the user to enter, which vehicle is an emergency vehicle. Considering that on the last example N is an emergency vehicle, N goes first, then S, W and as the last E.
>
> For this particular case with an emergency vehicle at N the output of your program should be:
>
>
>
```
1. N->S
2. S->W
3. W->N
4. E->W
```
11. If two vehicles are allowed to go at the very same moment (their paths do not collide and they do not have to give way to other vehicles), your program should find this out and return them as having the same sequence number
>
> On the example below paths of N and E as well as E and S or W and E do not collide. Because S has to give way to N and W give way to S, S cannot go simultaneously with E, etc. The N and E can. So at first N and E go together, than goes S, and W as the last.
>
>
>
[](https://i.stack.imgur.com/HZeDw.png)
>
> The proper output of your program should be:
>
>
>
```
1. N->W
1. E->E
2. S->W
3. W->N
```
>
> You are free to choose the order of lines `1` (`N->W / E->E` is equivalent to `E->E / N->W`)
>
>
>
12. Sometimes the traffic may lead to unsolvable situation, that does not allow any vehicle to go. In real life it is solved when one of the drivers voluntarily resigns from his right of way. Here, your program should output `unsolvable` etc., as mentioned in the first part of the question.
>
> Below is an example of unsolvable situation. E should give way to W, W should give way to S, and S should give way to E.
>
>
>
[](https://i.stack.imgur.com/u1EHD.png)
[Answer]
## Q, 645 Bytes
```
r:{(1_x),*x} /rot
R:{x 3,!3} /-rot
A:4 4#/:@[16#0;;:;]'[(&0100011001111100b;&0001111101100010b;&0010001111000100b;0);(&0 6 2;&0 1 7;&0 3 3;0)]
K:,/{,'/A x}'3 R\3 0 2 1 /Konflick matrix
G:3 R\|E:"NESW" /E:NESW G:WSEN NWSE ENWS SENW
m:{x-y*_x%y} /mod
t:{1=+/m'[_x%4;2]} /orthogonal
w:{-1($x),". ",y[0],"->",y 1;} /write
b:{_x%4} /n-> base dir.
g:m[;4] /n-> turn
e:(!4)in /exists
d:{s:r a:e b x;R s&~a} /right free
I:{(G[a]?x 1)+4*a:E?*x} /"dd"->n
O:{E[a],G[a:b x]g x} /n-> "dd"
P:{N::(y=4)&z~4 4;a@&0<a:(@[4#0;b x;:;4-g x])+(5*d x)+(24*e z)+99*e y} /priority
H:{a::K ./:/:x,/:\:x; if[N&2 in *a;:,0N]; x@&{~|/x[;z]'y}[a]'[!:'u+1;u:!#x]} /each set of concurrent movements
f:{i:I'(E,'a)@&~^a:4#x; i:i@p:>P[i;E?x 4;E?x 5 6]; {0<#x 1}{a:H x 1;$[a~,0N;-1"unsolvable";w[*x]'O'a];$[a~,0N;(0;());(1+*x;x[1]@&~x[1] in a)]}/(1;i);}
```
**COMMENTS**
Definitively, it's not short (nor simple) code. It can be (severely) compacted, but it's left as excercise to the reader (I've dedicated too much time to this problem).
I've included multiline commented solution, but assume newlines as 1 Byte and discard comments (from / to end of line) to count size
The main difficulty is to fully understand all rules. Early optimization of code length is incompatible with developing a solution for a complex problem. Nor bottom-up or top-down approach copes well with unreadable code.
Finally, I developed a decission table (conflict matrix) with 16 rows and 16 columns (for each direction combined with each possible turn). The values of the items are 0 (compatibility), 1 (preference for row), or 2 (preference for column). It satisfies all test, by I'm not sure that all possible situations are well covered
Source file must have k extension. Start interactive interpreter (free for non-commertial use, kx.com) and evaluate at prompt (as shown in 'test' paragraph)
**TEST**
```
q)f " WN "
1. E->W
2. S->N
q)f " SW "
1. E->S
2. S->W
q)f "SSSS "
1. W->S
2. N->S
3. E->S
4. S->S
q)f "SWWN WS"
1. S->W
2. W->N
3. N->S
4. E->W
q)f "SWWNNWS"
1. N->S
2. S->W
3. W->N
4. E->W
q)f "WEWN "
1. N->W
1. E->E
2. S->W
3. W->N
q)f " SWE "
unsolvable
```
**EXPLANATION**
The base structure is the 'precedence matrix'
```
N E S W
W S E N N W S E E N W S S E N W
NW 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1
S 0 0 0 0 0 1 1 0 0 0 1 1 2 2 2 2
E 0 0 0 0 0 1 1 1 2 2 0 0 0 2 2 0
N 0 0 0 0 2 2 0 0 0 2 0 0 0 0 2 0
EN 0 0 0 1 0 0 0 0 0 1 0 0 0 0 1 0
W 2 2 2 2 0 0 0 0 0 1 1 0 0 0 1 1
S 0 2 2 0 0 0 0 0 0 1 1 1 2 2 0 0
E 0 0 2 0 0 0 0 0 2 2 0 0 0 2 0 0
SE 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0
N 0 0 1 1 2 2 2 2 0 0 0 0 0 1 1 0
W 2 2 0 0 0 2 2 0 0 0 0 0 0 1 1 1
S 0 2 0 0 0 0 2 0 0 0 0 0 2 2 0 0
WS 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0
E 0 1 1 0 0 0 1 1 2 2 2 2 0 0 0 0
N 0 1 1 1 2 2 0 0 0 2 2 0 0 0 0 0
W 2 2 0 0 0 2 0 0 0 0 2 0 0 0 0 0
```
Meaning (by example)
* `m[NW][SE]` has 0 value (both movements are compatible -concurrent-)
* `m[EW][SN]` has 1 value (EW has priority over SN) NOTE.- other priority factors may alter this sentence (emergency vehicles, priority road, ..)
* `m[NE][SE]` has 2 value (SE has priority over NE) NOTE.- other priority factors may alter this sentence (emergency vehicles, priority road, ..)
The matrix can be constructed using four submatrix (4x4) types
```
NESW A B C D
N DACB 0100 0001 0010 0000
E BDAC 0110 2222 0011 0000
S CBDA 0111 0220 2200 0000
W ACBD 2200 0020 0200 0000
```
The matrix is complemented with a function that assigns a priority to each movement. That function takes account of emergency vehicles, priority roads, orthogonal directions, type of turn and vehicles 'comming from right'
We sort movements by priority and applies matrix values. The resulting submatrix includes conflicts and priority of each movement.
* we analyze unsolvable cases (mutual conflicts)
* if not, we select most priority item and all movements compatible with it and not incompatible with previous incompatible movements, and create a set of movements allowed to go simultaneously
* Write that set of movements and iterate over the rest of candidates
] |
[Question]
[
I was just playing the board game *[Sorry!](https://en.wikipedia.org/wiki/Sorry!_(game))* with some people, and I realized that I could base a few interesting challenges off of it. This one is pretty simple.
You task is simply to output an [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") version of a sorry board, placing pieces where I tell you to.
# Specs
First, here is an image of an actual *Sorry!* board for reference:

The empty board looks like:
```
# > - - o # # # # > - - - o # #
# # S v
o # H # # # # # |
| # |
| # S o
| # #
^ H #
# #
# #
# H v
# # |
o S # |
| # |
| # # # # # H # o
^ S # #
# # o - - - < # # # # o - - < #
```
Notice a few features.
* The `#`'s are empty squares.
* The `S`'s and `H`'s are Start's and Home's respectively.
* The `>v<^`'s are the start of the slides, depending on which direction they face.
* The `|`'s and `-`'s are the middles of slides, depending on if they're horizontal or vertical.
* The `o`'s are the end's of slides.
* Each column is separated by a column of spaces to make it look more square-like.
Now here is what *you* have to do:
* Your input is a list of coordinates of various pieces that have been placed on the board.
* The coordinates start at `0` at the square outside the Start of the bottom color (yellow in the picture), and increase by one per square clockwise.
* After these 60 squares, the safe zones have the next and last 20 coordinates, starting from the one on the bottom (which gets 60-64), then going clockwise.
* You will have to place star's(`*`'s) on the correct coordinate, replacing the character underneath for all players.
* Additionally, if any of the players are on the start square of a slider, move them to the end of the slider before placing them.
* You can assume that there will be no collisions, before or after resolving sliders.
* You con't need to worry about the Home's or Start's.
* You can be 1-indexed if you want, but the test cases are 0-indexed.
# Test Cases
```
[0, 20] ->
# > - - o # # # # > - - - o # #
# # S v
* # H # # # # # |
| # |
| # S o
| # #
^ H #
# #
# #
# H v
# # |
o S # |
| # |
| # # # # # H # o
^ S # #
# # o - - - < # # # # * - - < #
[2, 7, 66] ->
# > - - o # # # # > - - - o # #
# # S v
o # H # # # # # |
| # |
| # S o
| # #
^ H #
# #
# #
# H v
# # |
o S # |
| # |
| # * # # # H # o
^ S # #
# # o - * - < # # * # o - - < #
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 204 [bytes](https://github.com/abrudz/SBCS)
```
(~2|⍳31)\'H'@(g⊂2 9)⊢'S'@(g⊂4 14)⊢('*'@({(60>⍵)⊃⍵,60|⍵+4 3+.×5 12=15|⍵}¨⎕)⊢'o####<---o##^||o####^|||o##>--o####>---o##v||o####v|||o##<--',20⍴'#')@((4⌽g 15,⍨¨⍳15),(g←(15∘-,⊢)(|15 0-⌽)¨,⊢)2,¨14-⍳5)⊢16 16⍴''
```
[Try it online!](https://tio.run/##pVPNSsNAED67TzGQw25sVrJpEpHWUhAhHmoP9SiFgrSXQgShIK4eFGopRnoRPXvKvfbopb7Jvkid3aS10L@Ds4SZ@b7M7yat6y6/um11485MDZ5P6rXa6fkFsaACHE8MVn4yP0eQB9BPA9ZJj8Q5/yfRIpMFksgVflm28w2Id8RbpGkqbuY3x/6Xj8z8W3oz88UbNjfn5Y54ubTNaIWPzfzrNpfxun8LbzK70fIiUzz3CX4KRL2@ndVVf@Rqr126KXVm7MGTKhkXhX1JI1plHTV89ODIVsNP2sh9H4SvAUb3EbljoVtRyQSRJ1RO6GKCScGHYuHg5z0A4R2LQEP30xQLmkyxhVLmnKPRlNK4qLVRMaDR2ujlbC9jMYY6nquSL2pRu8qYr16@OyACRyUp5k/GIrAd7LI/YiJQgw/uYD2bSRGAy/Fde5oaxHOmqfA5BgS6IxGCCHVWqv@R2V6buOC5BHsgaHtwCGH4Cw "APL (Dyalog Unicode) – Try It Online")
It is very likely possible to compress the hardcoded length-60 string, but I'm too lazy :P
A full program that takes a vector of numbers from stdin and prints the board to stdout. Uses lots of `@` to place various things at various places, starting from an empty board. This is an interesting use case for an otherwise seldom used built-in `@`.
### Ungolfed with comments
```
⍝ Hardcoded string of the 80 positions that can be occupied by players
s←'o####<---o##^||o####^|||o##>--o####>---o##v||o####v|||o##<--',20⍴'#'
⍝ Place '*' for actual players' positions
s←'*'@({(60>⍵)⊃⍵,60|⍵+4 3+.×5 12=15|⍵}¨⎕)⊢s
({ }¨⎕) ⍝ Take input and slide the positions
⍵+4.3+.×5 12=15|⍵ ⍝ If n%15=5, add 4; if n%15=12, add 3
60| ⍝ Wrap 60 to 0
(60>⍵)⊃⍵, ⍝ Discard change if n is 60 or higher
'*'@ ... ⊢s ⍝ Overwrite '*' at players' positions on s
⍝ Helper function to generate positions on 2D board
g←(15∘-,⊢)(|15 0-⌽)¨,⊢ ⍝ Take a vector of coordinates on the right side
,⊢ ⍝ Prepend to self...
(|15 0-⌽)¨ ⍝ abs((15-y,x)); 90 degrees counterclockwise
(15∘-,⊢) ⍝ Take the above and prepend 180 degrees rotation
⍝ Main result
(~2|⍳31)\'H'@(g⊂2 9)⊢'S'@(g⊂4 14)⊢s@((4⌽g 15,⍨¨⍳15),g 2,¨14-⍳5)⊢16 16⍴''
16 16⍴'' ⍝ Empty 16×16 board
s@((4⌽g 15,⍨¨⍳15),g 2,¨14-⍳5) ⍝ Place the 80 chars around the board
(4⌽g 15,⍨¨⍳15) ⍝ First 60 positions on the boundaries
,g 2,¨14-⍳5 ⍝ and the other 20 positions inside
'S'@(g⊂4 14) ⍝ Place S's
'H'@(g⊂2 9) ⍝ Place H's
(~2|⍳31)\ ⍝ Insert blank columns
```
[Answer]
## Python 2, 476 bytes
Short 3-line solution ([Try it online](https://tio.run/nexus/python2#RVFRa4MwEH7fr5DmIUk9hxdN3Lp10JaB7z6KhZatkNEmol3ZQPzr3cVuTMjdl3yXz@9y13552rXiaPszcH7/4a0T@8geIgqOs@3l@SUZfFWO/P3Yv/OIz607iz2gkQffTVXRjL0kiWf0UQ5gZMiwWl1Gj8yUgWDDOCDbTHFd@WnDxi2WFNnr79qUeKHIcBh9tQ5pmDbDpFAahn7crirSpmLm6V/PgfAhz@R93x7tWfCRS3kXvNngzbr28yzk4gu@l@K4O@3fdpFbiBoxcYC6maOK6xSUSRzhPK5dogykhE1cowaX5Hgjir8bhDEjQlOVpvM0nGcTVlDoIKSDjtGgCMpazd2CVqwaKf495PTIwV9NZSlkGkgvvHGU/RGoQBWQK9DFjUmlsDK28qmvv5v6q1nyOZ9a7UKr/aLtaDg0o9sYO3m9UmsICjLIQQPpkXFdgH4A/QgmBYNALosUisfmBw))
```
s=map(list,''.join(b if b in'#^v<>-|oSH~'else' '*int(b,16)for b in "#>--o####>---o##~#1#1SAv~o1#6H#####|~|1#C|~|1#BSo~|1#C#~^1HC#~#E#~#E#~#CH1v~#C#1|~oSB#1|~|C#1|~|#####H6#1o~^AS1#1#~##o---<####o--<#").split('~'))
for i in input():x,y=(lambda n:([11-n,15]*12+[0,26-n]*14+[n-26,0]*16+[15,n-41]*14+[71-n,15]*4+[13,n-50]*5+[70-n,13]*5+[2,75-n]*5+[n-65,2]*5)[2*n:2*n+2])((lambda n:4if n in[5,20,35,50]else 3if n in[12,27,42,57]else 0)(i)+i);s[y][x]='*'
for r in s:print' '.join(r)
```
One-liner in 534 ([Try it online](https://tio.run/nexus/python2#VVFNa/MwDP4rZj44bpQRObGzlTFYxwvZOUeTQspScGntkmY9hfz1vnK6Hmaw9FiPPq3bPgxsYM4nx@60@@7YBr7W1loHh9Z5durOD8KvE4uYeUDdrlClNgdlMk@4TK3PlIGcsEktavBZiXeiekQQxoIITV46BpgSsFiwgkrHRHezBkVQWrXya7qpauFPFz4t3Z55atmSaw6FBsrZHy8982nxoFCBqqBUoKtfDr6k7Py3WAmaeMfi3A525Mt6/3Pqh27sk0620X6A7q99I1uZLF24ywhCPB8C/RgF71nMIPj2@vaeTaGpZxGrCSZWzo/JDtDI/VLP@Sf@nmWB0yEdwcyRY/NxnQNyU0eCT/OE/HORmyYsDz5vsSbJ//3ezxqvJDlOc2g2UU3LY1oy1IZjmLcfDeUmZx6o1lskQtRP8vlyProxEbOQEpw//4yJlOvzQO1S1/fBBnm70XoRFBRQggb6TVqerkC/gH4Fk4NBoE1VOVSv7X8)):
```
for r in(lambda B,I:[[[i,j]in map(lambda n:([11-n,15]*12+[0,26-n]*14+[n-26,0]*16+[15,n-41]*14+[71-n,15]*4+[13,n-50]*5+[n-64,13]*5+[2,75-n]*5+[n-65,2]*5)[2*n:2*n+2],map(lambda n:n+4if n in[5,20,35,50]else n+3if n in[12,27,42,57]else n,I))and'*'or b for i,b in enumerate(a)]for j,a in enumerate(B)])(map(list,''.join(b if b in'#^v<>-|oSH~'else' '*int(b,16)for b in"#>--o####>---o##~#1#1SAv~o1#6H#####|~|1#C|~|1#BSo~|1#C#~^1HC#~#E#~#E#~#CH1v~#C#1|~oSB#1|~|C#1|~|#####H6#1o~^AS1#1#~##o---<####o--<#").split('~')),input()):print' '.join(r)
```
I assume indices of safe zone this way:
```
# > - - o # # # # > - - - o # #
# 74 S v
o 73 H 75 76 77 78 79 |
| 72 |
| 71 S o
| 70 #
^ H #
# #
# #
# H v
# 60 |
o S 61 |
| 62 |
| 69 68 67 66 65 H 63 o
^ S 64 #
# # o - - - < # # # # o - - < #
```
Explanation (lines are separated a bit for better understanding):
```
# Hardcode board. Spaces are changed to their number in hex (as there are up to 14 spaces in row)
# Unfortunatly v^<> characters made board non-symmetrical and replacing chars costs too much in python, so I had to hardcode it all
B="#>--o####>---o##~#1#1SAv~o1#6H#####|~|1#C|~|1#BSo~|1#C#~^1HC#~#E#~#E#~#CH1v~#C#1|~oSB#1|~|C#1|~|#####H6#1o~^AS1#1#~##o---<####o--<#"
# Encode board to list of lists of characters
s=map(list,''.join(b if b in'#^v<>-|oSH~'else' '*int(b,16)for b in B).split('~'))
# Map coordinates, based on n (awfully long)
# Creates long list (lenght of 80) with values based on n and only one valid, which occures under index n
l=lambda n:([11-n,15]*12+[0,26-n]*14+[n-26,0]*16+[15,n-41]*14+[71-n,15]*4+[13,n-50]*5+[70-n,13]*5+[2,75-n]*5+[n-65,2]*5)[2*n:2*n+2]
# Returns additional move of n if it appers to be on slide start
j=lambda n:4if n in[5,20,35,50]else 3if n in[12,27,42,57]else 0
# Here takes input as list of numbers, get coordinates for them and update board with *
for i in input():x,y=l(j(i)+i);s[y][x]='*'
# Print board, spacing characters with one whitespace
for r in s:print' '.join(r)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 169 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
11Ý₅+R14L17*R15ݤDL17*+¤3Lα4Ý©17*DƵ—αs19+®Ƶ_+s®48α)˜•1ŠΓ;Ü|má•Ƶªв•5–à†@1δ!•Ƶ§в‡Iè'*•3‡Ù¬¨èˆ‚1æ°þBÚ•" #
0o1HS"ÅвJ.BD€SøíJ‚øJ»∊2ä`¶¡í»«8Å120Å0«">>v^v^<<"„-|S5×Jº«S.;rǝS¶¡»
```
[Try it online](https://tio.run/##JYtNSwJRGIX3/YqaFpFzk7nz4QeKhLiowZWzjOwDWrQIIcGVi4swEW0NItFwRGpqVBppQhpo8b40LYTB33D/yHSl3XPOc06jeXZ@eZEklOKAd2y5RvUqzaZq1MABjCtrlmGsVWNfF8WriJUo4Ow@9ps0L8MsCk7kJsz0XOzvLvucjejPMO4WsN@@QkfEKIC31VyAwVkXh5wN92n8sfVvXtbGOUR3JyUKTTA@wgRcdJc3nPUoPsM7fpexJ6y0ub2hNOiBJaG9mpvpcoV3JhYucGqKKS5MCPntnYrjU/gEB6cQgpdDm6oK2gp4UqnUqrfqxaLE2dNe2zLwwYQv8Kx04fp3YK0/ECbJkUqyRFWIqhPNIFqGZDIkmz/@Aw) or [verify all test cases](https://tio.run/##NYtLSwJhFIb3/oppWkTOl8w3Fy8pGuKiBiFwlqJdoEWLMvICgotBMKKtQSQaGlKWF1JSJKHFOWQLYfA3fH9k@kTaPc/7nJPJnpyenzkF8eDyKp/bFcRIkbjEw3xubcShFBusXJESVItTnztBdWxAO7ZiCdpq3B5qfHjjGpuPmXVvD7M0IMFgPj6SsjDQ/PZwe1Fn1jP9adrVINZLF9jiOh/D@3LEQWdWFZvMau5R@3NjXV5XpVXEzpabDypnfIQedLCzuGFWjeILfOB3FGu8isKmS87QfVPEynJkeKIxVu6ZOMW@wU9xasCM3d4p2D6GCbSwDzPo@rFCFRkrMnTFcLiQLqRDIZFZTzslU8cHA76ga3qC178Nc/UDM4fAJOIkkykiJGUiKPIKFOIjXu8/KTJRNKLqRPXylfgCqdQf).
**Explanation:**
We start by creating a list of all possible coordinates of the `*` on the finished board.
The list we want to create for the 0-based indices is:
```
[266,265,264,263,262,257,260,259,258,257,256,255,187,221,204,187,170,153,136,119,34,85,68,51,34,17,0,4,2,3,4,5,6,7,8,13,10,11,12,13,14,15,83,49,66,83,100,117,236,151,168,185,202,219,236,253,270,266,268,267,251,234,217,200,183,222,223,224,225,226,19,36,53,70,87,48,47,46,45,44]
```
The duplicated coordinates are for the positions that are on the start of a slider, which end up at the end of the slider.
Using a straight-forward compressed list would be 86 bytes:
```
•€l:å–£²voùäÉÿ¢º(ºT≠εÁ~нΣûÑ‚Ćδ·нäVø<:‘.IWÚC¯ht;t∍W₂zþ#6÷(›ǝé$)‚ιô.!=É/g=Ë₁Ìjh:½~₃Y•Ƶ«в
```
But instead, we create the list manually in 79 bytes:
```
11Ý # Push a list in the range [0,11]
₅+ # Add 255 to each
R # And reverse it
14L # Push a list in the range [1,14]
17* # Multiply each by 17
R # And reverse it
15Ý # Push a list in the range [0,15]
¤ # Push its last value (15) (without popping the list itself)
D # Duplicate it
L # Create a list in the range [1,15]
17* # Multiply each by 17
+ # And add the 15 to each
¤ # Push its last value (270) without popping the list itself)
3L # Push a list in the range [1,3]
α # Take the absolute difference of each value with 270
4Ý # Push a list in the range [0,4]
© # Store it in variable `®` (without popping)
17* # Multiply each by 17
D # Duplicate this list
Ƶ— # Push compressed integer 251
α # And take the absolute difference of each value with this 251
s # Swap so the duplicated list of [0,4] * 17 is at the top again
19+ # Add 19 to each
® # Push the list in the range [0,4] again from variable `®`
Ƶ_ # Push compressed integer 222
+ # Add it to each
s # Swap the two lists at the top of the stack
® # Push the list in the range [0,4] once again from variable `®`
48α # Take the absolute difference of each value with 48
) # Now wrap all lists on the stack into a list
˜ # And flatten it to a single list
# And finally adjust this list with the slider positions:
•1ŠΓ;Ü|má• # Push compressed integer 108136777658162939
Ƶª # Push compressed integer 270
в # Convert the larger integer to base-270 as list:
# [1,9,32,102,134,238,261,269]
•5–à†@1δ!• # Push compressed integer 391758411553146080
Ƶ§ # Push compressed integer 267
в # Convert the larger integer to base-267 as list
# [4,13,83,34,236,187,257,266]
‡ # Transliterate; replace all values of the first list with the values of
# the second list in the big list we created earlier
```
Now that we have this list of coordinates for the `*`, we use the input to get the positions:
```
I # Push the input-list
è # Index it into the list we created
'* '# Push a "*" (which we will use later on)
```
Now we are going to create the empty board (without the space columns for now). We do this as follows:
```
•3‡Ù¬¨èˆ‚1æ°þBÚ•
# Push compressed integer 68098022849564198525854900638097
" #\n0o1HS" # Push this string
Åв # Convert the large integer to base-" #\n0o1HS", which means it's converted
# to base-length, and then indexed into the string
J # And join the entire list of characters to a string
```
We now have a quarter of the board as template (without trailing spaces):
```
#100o###
# # S
o #
0 #
0 #
0 #
1 H
#
```
Which we'll use to create the entire board:
```
.B # Box it. This will split on newlines, but also make all lines of equal
# length by adding trailing spaces
D # Duplicate this list of lines
€S # Convert each line to a list of characters
ø # Zip/transpose; swapping rows/columns
í # Reverse each row
# (`øí` basically rotates a character-matrix once clockwise)
J # Join each inner list together to a string
‚ # Pair it with the list of strings we duplicated
ø # Zip/transpose; swapping rows/columns
J # Join the pair of lines together
» # And join the lines by newlines
```
We now have halve the board:
```
#100o####1000o##
# # S 1
o # H#####0
0 # 0
0 # So
0 # #
1 H #
# #
```
And we'll continue:
```
∊ # Mirror vertically
2ä # Split it into two halves
` # Pop and push both halves separated to the stack
¶¡ # Split the top list on newlines again
í # Reverse each row
» # Join it by newlines
« # And then merge it back to the first halve
# And now we'll fix the arrows and lines:
8Å1 # Push a list of 8 1s
20Å0 # Push a list of 20 0s
« # Merge those two together
">>v^v^<<" # Push this string
„-| # Push string "-|"
S # Convert it to a pair of characters: ["-","|"]
5× # Repeat each 5 times: ["-----","|||||"]
J # Join it together to a string "-----|||||"
º # Mirror it horizontally: "-----||||||||||-----"
« # Append it to the arrows-string
S # Convert it to a list of characters
.; # Replace each of the 1s/0s one-by-one with these characters in the board
```
So we end up with our completed empty board (without space columns):
```
#>--o####>---o##
# # S v
o # H#####|
| # |
| # So
| # #
^ H #
# #
# #
# H v
# # |
oS # |
| # |
|#####H # o
^ S # #
##o---<####o--<#
```
Then we'll place the `"*"` we pushed earlier at the positions we calculated earlier:
```
r # Reverse the values on the stack
ǝ # Insert the "*" at the position of the list in the board-string
```
And finally we fix the space-columns, and output the result:
```
S # Convert the entire board to a list of characters
¶¡ # Split it on newlines
» # Join each inner list by spaces, and then each line by newlines
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand how the compression works.
[I've used this 05AB1E tip to generate the quarter board.](https://codegolf.stackexchange.com/a/120966/52210)
] |
[Question]
[
There is a network of up to 26 nodes (named `A` to `Z` or `a` to `z` as per your wish). Every pair of nodes may be connected or disconnected. A node may be connected to at most 4 other nodes. Your task is to draw the network in a 2D diagram. Input will be given such that this task is possible (see more constraints in output section).
---
**Format**
**Input**
* Pairs of letters (`A` to `Z` or `a` to `z` as per your wish). They are not sorted in any order.
* Optional - number of pairs
**Output**
* An ASCII drawing that shows the actual links between the nodes. Nodes are given by `a` to `z` or `A` to `Z`. Use `-` for horizontal links and `|` for vertical links. Links may be of any (non-zero) length but they should be straight horizontal/vertical lines *that do not bend*. Spaces can be added provided they don't disfigure the picture.
You may not use built-ins that help in layout of the graph. Other graph-related built-ins may be allowed (though solutions without built-ins would be more appreciated). Shortest code wins.
---
**Sample data**
**Input**
```
A B
B F
B L
F K
L K
K R
K S
R P
S J
S P
J A
T V
V N
```
**Output**
```
A - B - F T - V
| | | |
| L - K - R N
| | |
J ----- S - P
```
**Input**
```
H C
G H
A B
B F
B C
F G
C D
D A
```
**Output**
```
A - B ----- F
| | |
D - C - H - G
```
[Answer]
# CJam, 142
You didn't ask for an optimal, deterministic or fast solution, so here you go:
```
qN%Sf%::c_s_&:Aff#:E;{A{;[DmrDmr]2f*}%:C;E{Cf=~.-:*}%0m1{E{Cf=$~1$.-_:g:T\:+,1>\ff*\f.+T0="-|"=f+~}%CA.++:L2f<__&=!}?}gS25*a25*L{~2$4$=\tt}/N*
```
[Try it online](http://cjam.aditsu.net/#code=qN%25Sf%25%3A%3Ac_s_%26%3AAff%23%3AE%3B%7BA%7B%3B%5BDmrDmr%5D2f*%7D%25%3AC%3BE%7BCf%3D%7E.-%3A*%7D%250m1%7BE%7BCf%3D%24%7E1%24.-_%3Ag%3AT%5C%3A%2B%2C1%3E%5Cff*%5Cf.%2BT0%3D%22-%7C%22%3Df%2B%7E%7D%25CA.%2B%2B%3AL2f%3C__%26%3D!%7D%3F%7DgS25*a25*L%7B%7E2%244%24%3D%5Ctt%7D%2FN*&input=A%20X%0AX%20Y%0AT%20X)
This generates random coordinates for each letter and tests if the layout is acceptable (edge letters lining up and no intersections), until it is. It gets mind-numbingly slow as you add more edges.
The two `D` letters in the code specify the maximum x and y coordinates; I picked `D` (=13) because I think it should be sufficient for all cases, feel free to prove me wrong. But you can change them to other values to speed up the program, e.g. the 2nd example should finish within a minute or two if you use 3 and 4 instead.
[Answer]
# C, 813 bytes
```
#include<map>
#include<set>
#include<cstdlib>
typedef int I;typedef char*C;I a,t,s,h;struct p{I x,y;}j,k;std::map<I,std::set<I>>l;std::map<I,p>g;C m,M=" |-";I L(I n,C q,C Q){j=g[n],h=1;for(I o:l[n])if(g.find(o)!=g.end())if(!(a=(k=g[o]).y==j.y)&&k.x^j.x)h=0;else for(I x=j.x,y=j.y,e=k.y*s+k.x,b,d=(k.x<j.x||k.y<j.y)?-1:1;a?x+=d:y+=d,(b=y*s+x)^e;m[b]=q[a])if(m[b]^Q[a]){h=0;break;}}I N(){for(auto i:g)for(I n:l[i.first])if(g.find(n)==g.end())return n;for(auto i:l)if(g.find(a=i.first)==g.end())return a;exit(puts(m));}I f(){for(I n=N(),x,y=0,b;y<s;y+=2)for(x=0;x<s;x+=2)m[b=y*s+x]==*M?g[n]={x,y},m[b]=n,L(n,M+2,M),h&&f(),L(n,M,M+2),m[b]=*M,g.erase(n):0;}I main(I c,C*v){for(;--c;l[a].insert(s),l[s].insert(a))a=v[c][0],s=v[c][1];t=l.size(),s=t|1;memset(m=(C)calloc(s,s),*M,s*s-1);for(a=1;a<s;++a)m[a*s-1]=10;f();}
```
Takes input as commandline arguments, e.g.:
```
./network AB BF BL FK LK KR KS RP SJ SP JA TV VN
```
Nowhere near competitive with aditsu's answer by size, but much more efficient!
This will brute-force all possible solutions, but will quickly recognise failure as it goes. For the two test cases, it finishes almost immediately, and it seems to only take a few seconds on more awkward inputs. It also has no limitation to the accepted node names (though you can't name one space, `|` or `-`) and has no limit on the number of nodes (as long as all names fit in a byte, so the practical limit is 252 nodes, and it will get slow long before reaching that many).
There's plenty of scope for speeding this up; a lot of short-circuit exiting was lost to the golfing, and there's parts which could be moved out of hot-loops. Also some observations of symmetry can dramatically reduce the positioning of the first 2 nodes, among other things.
---
Breakdown:
```
#include<map>
#include<set>
#include<cstdlib>
typedef int I;
typedef char*C;
I a,t,s,h; // Variables shared between functions
struct p{I x,y;} // Coord datatype
j,k; // Temporary coord references
std::map<I,std::set<I>>l; // Bidirectional multimap of node links
std::map<I,p>g; // Map of nodes to positions
C m, // Rendered grid
M=" |-"; // Lookup table for output characters
// Line rendering function
// Sets h to 1 if all lines are drawn successfully, or 0 if there is a blocker
I L(I n,C q,C Q){
j=g[n],h=1;
for(I o:l[n]) // For each connection to the current node
if(g.find(o)!=g.end()) // If the target node has been positioned
if(!(a=(k=g[o]).y==j.y)&&k.x^j.x)h=0; // Fail if the nodes are not aligned
else
for(I x=j.x,y=j.y, // Loop from node to target
e=k.y*s+k.x,
b,d=(k.x<j.x||k.y<j.y)?-1:1;
a?x+=d:y+=d,(b=y*s+x)^e;
m[b]=q[a]) // Render character (| or -)
if(m[b]^Q[a]){h=0;break;} // Abort if cell is not blank
}
// Next node selection: finds the next connected node to try,
// or the next unconnected node if the current connected set is complete.
// Displays the result and exits if the entire graph has been rendered.
I N(){
for(auto i:g)for(I n:l[i.first]) // Search for a connected node...
if(g.find(n)==g.end())return n; // ...and return the first available
for(auto i:l) // Else search for an unconnected node...
if(g.find(a=i.first)==g.end())
return a; // ...and return the first available
exit(puts(m)); // Else draw the grid to screen and stop
}
// Recursive brute-force implementation
I f(){
for(I n=N(),x,y=0,b;y<s;y+=2) // Loop through all grid positions
for(x=0;x<s;x+=2)
m[b=y*s+x]==*M // If the current position is available
?g[n]={x,y}, // Record the location for this node
m[b]=n, // Render the node
L(n,M+2,M), // Render lines to connected nodes
h&&f(), // If line rendering succeeded, recurse
L(n,M,M+2), // Un-render lines
m[b]=*M,g.erase(n) // Un-render node
:0;
}
// Input parsing and grid setup
I main(I c,C*v){
// Parse all inputs into a bidirectional multi-map
for(;--c;l[a].insert(s),l[s].insert(a))a=v[c][0],s=v[c][1];
t=l.size(),s=t|1; // Calculate a grid size
// Allocate memory for the grid and render newlines
memset(m=(C)calloc(s,s),*M,s*s-1);
for(a=1;a<s;++a)m[a*s-1]=10;
f(); // Begin recursive solving
}
```
] |
[Question]
[
The `puppy` utility takes a filename as input, and does exactly what you would expect a puppy to do: it shreds it!
[](https://i.stack.imgur.com/Vkfvz.jpg)
## How to shred
1. ~~Rip out the pages with your teeth~~ Split the input file on newlines.
2. ~~Tear up each page with your paws~~ For each line (not including the linefeed), pick a random integer `n` such that `2 <= n <= # of characters in the line`. Split the line into `n` non-empty non-overlapping substrings of random length.
3. ~~Scatter the shreds all over the floor~~ Output each substring of each line to a unique random filename (`[a-zA-Z0-9]` only, any consistent extension including none, length `1 <= n <= 12`) in the current directory. Overwriting pre-existing files within the current directory (including the input file, if it is in the current directory) is acceptable, as long as it does not interfere with your submission running.
## Clarifications
* There will never be an input where it is possible to use up all of the possible filenames.
* Files will consist of only printable ASCII (ordinals 32-127) and linefeeds, and will use UNIX/Linux-style line endings (LF, not the Windows-style CRLF).
* A single trailing newline in output files is acceptable as long as every output file has a trailing newline, but is not required. You may choose whether or not the input file contains a trailing newline.
* Each line in the input will contain at least 2 characters.
* The random values chosen must be chosen from a uniform random distribution on the given set of possible values.
If your language is unable to perform file I/O, you may instead take the input file's contents as input, and output pairs of strings representing the output filename and the text for that file. However, your submission will not be eligible for winning.
## Example
Reference implementation:
```
#!/usr/bin/env python3
import random
import string
import sys
fname = sys.argv[1]
with open(fname) as f:
txt = f.read().rstrip().split('\n')
for line in txt:
n = random.randint(2, len(line))-1
idxs = [0]+random.sample(range(1, len(line)), n)+[len(line)]
idxs.sort()
splits = []
for i in range(0, len(idxs)-1):
splits.append(line[idxs[i]:idxs[i+1]])
ofnames = []
for s in splits:
flen = random.randint(1, 10)
ofname = ''
while ofname == '' or ofname in ofnames:
ofname = ''
for i in range(flen):
ofname += random.choice(string.ascii_letters+string.digits)
ofnames.append(ofname)
with open(ofname, 'w') as f:
f.write(s)
```
Example run:
```
$ cat bestsong.txt
Never gonna give you up
Never gonna let you down
Never gonna run around
And desert you!
$ puppy bestsong.txt
$ ls
8675309
a
bestsong.txt
cSdhg
Dq762
jq7t
ret865
rick4life
weu767g
xyzzy
$ cat 8675309
esert you!
$ cat a
Never gonna let you down
$ cat cSdhg
ive y
$ cat Dq762
And d
$ cat jq7t
Never gonna g
$ cat ret865
run arou
$ cat rick4life
Never gonna
$ cat weu767g
nd
$ cat xyzzy
ou up
```
[Answer]
## PowerShell v2+, ~~215~~ 211 bytes
```
nal d Get-Random;gc $args[0]|%{$b=d(0..($l=($t=$_).length)) -C(d(2..$l));$b=$b+0+$l|select -u|sort;0..($b.count-2)|%{-join($t[$b[$_]..($b[$_+1]-1)])}}|%{$_>(-join[char[]](d(48..57+65..90+97..122) -c(d(1..12))))}
```
Requires v2 or newer since v1 didn't have [`Get-Random`](https://technet.microsoft.com/en-us/library/hh849905.aspx) available.
Edit -- saved 4 bytes by using char-array casting instead of individually casting each letter
**Somewhat Ungolfed**
```
Get-Content $args[0]|ForEach-Object{
$t=$_
$l=$t.length
$b=Get-Random(0..$l) -Count(Get-Random(2..$l))
$b=$b+0+$l|Select-Object -unique|Sort-Object
0..($b.count-2)|ForEach-Object{
-join($t[$b[$_]..($b[$_+1]-1)])
}
}|ForEach-Object{
$_>(-join[char[]](Get-Random(48..57+65..90+97..122) -count(Get-Random(1..12))))
}
```
### Explanation
Starts with setting `d` as a `New-Alias` for `Get-Random`, so we don't have to type out `Get-Random` each time we're using it (a lot). We then `Get-Content` of our input `$args` and pipe those through a loop with `|%{...}`. Note that `Get-Content` will by default split on newlines (either CRLF or just LF), so we don't need to do anything additional there.
Each iteration of the loop, we start with formulating the slices this line is going to be [Ginsu'd](https://en.wikipedia.org/wiki/Ginsu) into. Set `$t` equal to the line we're working with, and `$l` equal to its length, then construct a collection from `(0..$l)`. This represents all possible character indices in our current line. We then `Get-Random` from between `(2..$l)` to determine how many to select, and then get a random number of indices equal to that `-c`ount. Store those indices in `$b`.
We then also add on `0` and `$l` to `$b`, so we have the beginning and end of our line guaranteed to be in the collection of indices. Pipe that through to `Select-Object` with the `-u`nique flag, then pipe to `Sort-Object`, so our indices are now guaranteed to start with the first character and end with the last character, and some random number in between.
Next, we're looping over all the indices in `$b` with `0..($b.count-2)|%{...}`. Each of those loop iterations, we're slicing `$t` (our current line of text) and then `-join`ing them together into a string (rather than a char-array). Those get bundled up and left on the pipeline, and we close the outer loop.
So now we have an in-order collection of random slices of each of the lines of text. (Meaning, at this point, if we simply `-join`ed them back together, we'll get the original text minus newlines.) We then pipe that collection through another loop `|%{...}` and each iteration we're outputting that slice to a file with `$_>...`. The file is created by taking from 1 to 12 random integers that correspond with ASCII codes for `[0-9A-Za-z]`. No file will have an extension, and the `>` command will output a trailing newline by default on every file.
### Example
[](https://i.stack.imgur.com/4LeZI.png)
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~85 80 67~~ 62 bytes
```
{⍵⎕NPUT(⎕A,⎕D,¯1⎕C⎕A)[?62/⍨?12]1}¨⊃,/{⍵⊆⍨(⍋⊃¨⊂)?⍴⍨≢⍵}¨⊃⎕NGET⍞1
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97X/1o96tj/qm@gWEhmgAaUcdIOGic2i9IZB2BgloRtubGek/6l1hb2gUa1h7aMWjrmYdfbC2rjagsMaj3m6gEEi8SdP@Ue8WoNijzkVAeYhakOHuriGPeucZgmz8z5nGpZ6RmpOTr1dSUaIOAA "APL (Dyalog Unicode) – Try It Online")
This was a fun one.
Full program which takes a string as input, and outputs files to wherever the `]cd` command points to in the Dyalog workspace.
Done with some advice from dzaima.
-13 bytes from Bubbler, by removing ⎕UCS 10.
-5 more bytes from Bubbler after some more smaller golfs and change to the sorting idiom.
## Output
Input file is a list of numbers from 1-99 from my "Size Up a Number" challenge.
[](https://i.stack.imgur.com/twyDH.gif)
## Explanation
`⊃⎕NGET⍞1` read file from location as APL array, take first element, split on newlines. (mode 1)
(last two elements are file attributes)
`{⍵⊆⍨(⊂∘⍋⌷⊢)?(/⍨≢⍵)}¨` *for each line, execute the following:*
`(/⍨≢⍵)` create a list of the length repeated length times
`?` generate random numbers within those ranges
`(⊂∘⍋⌷⊢)` sort in ascending order
`⍵⊆⍨` partition the line according to the sorted array
`⊃,/` join into a single vector and remove nesting
`{⍵⎕NPUT(⎕A,(¯1∘⎕C⎕A),⎕D)[?(?12)/62]1}` for each partition, do the following:
`(⎕A, )` create a list with the uppercase alphabet,
`( (¯1∘⎕C⎕A) )` the lowercase alphabet,
`( ,⎕D)` and numbers from 0-9.
`[ (?12) ]` generate a random number in range 1-12
`[ /62]` replicate 62 that many times
`[? ]` create that many random numbers in range 1-62, and index into the list.
`⍵⎕NPUT 1` write the partition into the random filename, creating it if necessary.
] |
[Question]
[
The goal of this challenge is to find the direction and area enclosed by a loop.
# Input:
A rectangular grid consisting entirely of these characters: `^v<>`
(Optionally, you may also be given the dimensions of the grid before the grid itself in decimal with a prefix, suffix, and separator character of your choice.)
A **loop** in the grid is a set of the aforementioned characters such that one points to the next, pointing to the next, eventually pointing back at the first character. For example:
```
<>>v> >>v
^^<>v ^ >v
>^<<< ^<<<
>^<v>
```
The left grid is the sample input; the right grid is the loop isolated.
The input grid will contain either no loops at all or one loop; you do not have to worry about any cases in which the grid contains more than one loop.
# Output:
If the grid contains no loop, output `X`.
If the grid contains two arrows pointing at each other, output `0`.
If the grid contains a counterclockwise loop, count the characters enclosed by the loop, including the border. Output that number.
If the grid contains a clockwise loop, follow the same process for the counterclockwise loop, but output the negative of that number. For instance, the above input grid would have an output of `-11`: 10 come from the loop itself, and 1 from the character enclosed by the loop.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest code wins.
# Test cases:
```
<<^
^>v
^v<
```
Output `X`.
```
<<<<
><<<
>>^>
```
Output `0`.
```
<>^^<
>>>v>
<^^>v
<^>>v
>^<<<
```
Output `-15`.
```
v<<<<
>v>>^
v<^<<
>>>>^
```
Output `20`.
[Answer]
# C#, 604 bytes
Complete program, accepts input (line-delimitated layout, no dimensions) from STDIN, outputs to STDOUT.
```
using C=System.Console;class P{static void Main(){int w=0,W,i,j,t,k,l,c;string D="",L;for(;(L=C.ReadLine())!=null;D+=L)w=L.Length;var R=new[]{-1,0,1,w,-w};L="X";for(W=i=D.Length;i-->0;){var M=new int[W];for(k=j=i;i>0;){M[j]=++k;t=j+R[c=D[j]%5];if(t<0|t>=W|c<3&t/w!=j/w|c>2&t%w!=j%w)break;j=t;if((l=M[j])>0){var J=new int[W+1];System.Func<int,int>B=null,A=s=>J[s]<0?0:J[k=B(s)]=k==W?k:i;B=x=>J[x]==x?x:B(J[x]);for(i=J[W]=W;i>0;)J[--i]=M[i]<l?i%w<1|i%w>w-2|i<w|i>W-w?W:i:-1;for(;i<W;)if(J[++i]<0)l=D[i]%5/2-1;else{A(i-1);if(i>w)A(i-w);}for(c=W;i-->0;L=""+(c>2?c:0)*l)c-=J[i]<0?0:B(i)/W;}}}C.WriteLine(L);}}
```
The program works by first reading in the layout, needless to say, and then iterating over every cell. We then run a 'snake' from each cell, which follows the arrows until it runs off the edge, or runs into itself. If it runs into itself, then we know we have found a loop (or one of those "><" things), and it also knows how much of the snake is in the loop.
Once we know we have a loop, we know which cells are on the loop, and we create a map from each cell (+1, for reasons) to either itself, `-1` (means it's on the loop), or `W` (the whole width) if it's on the edge (or the +1 (which is at index `W`) to simplify things further one).
While we do this, we also find the direction that the 'last' element of the loop has (that is, the last element of the loop on the last row that has elements from the loop on it). This element must be a "<" or an "^", and this tells us the clockness (CW/CCW) of the loop (translated to -1/+1).
We then perform a disjoin set pass, which assigns all the elements that are outside the loop to the `W` set. We then subtract how many of these there are from `W` to get the number contained on and in the loop. If this number is less than 3, we replace it with 0. We multiply this by the clockness, set it as the result, and somehow escape from the for loops, where the result is output.
If, however, most of the above never happens (because no snake ever finds itself), then the result remains as "X", and that is outputted.
```
using C=System.Console;
class P
{
static void Main()
{
int w=0, // width
W, // full length
i, // used for iterating over all the cells
j, // keeps track of where the snake as got to
t, // t is next j
k, // how far along the snake we are, kind of
// later on, k is used as temp for A
l, // stores a threshold for how far along the snake the loop starts
// later on, l stores the last seen pointer - this tells us the clockness
c; // the translated direction
// later on, c is a backwards-count
string D="", // D is the map
L; // used for reading lines, and then storing the result
// might not be the best yay of doing this
for(;(L=C.ReadLine())!=null; // read a line, while we can
D+=L) // add the line to the map
w=L.Length; // record the width
var R=new[]{-1,0,1,w,-w}; // direction table (char%5) - might be able to replace this array with some bit bashing/ternary
L="X"; // can't seem to fit this in anywhere... (don't strictly need to re-use L)
for(W=i=D.Length;i-->0;) // for each cell, we send a 'snake' to try to find the loop from that cell
{
var M=new int[W]; // stores how far along the snake this point is
for(k=j=i; // k's value doesn't really matter, as long as it's not stupidly big
i>0;) // the i>0 check is just for when we return (see comment at the end of the code)
{
M[j]=++k; // store snake point and advance distance
t=j+R[c=D[j]%5]; // t is position after move (translate <>v^ to 0234 (c is direction))
//c=D[j]%5; // translate <>v^ to 0234 (c is direction)
//t=j+R[c]; // t is position after move
if(t<0|t>=W|c<3&t/w!=j/w|c>2&t%w!=j%w)
break; // hit an edge - will always happen if we don't find a loop - give up on this snake
j=t; // move to new position
if((l=M[j])>0) // we've been here before...
{
// disjoint sets (assign all the edges to one set, assign all the ones on the line to another set, do adjacent disjoint, return size-outteredge (minus if necessary)
var J=new int[W+1]; // looks like we can reuse M for this
System.Func<int,int>B=null,
// whatever s points at should point to i, unless s points to W, in which case it should keep point to W
A=s=>J[s]<0?0:J[k=B(s)]=k==W?k:i;
// read the value this points to
B=x=>J[x]==x?x:B(J[x]);
for(i=J[W]=W;i>0;)
J[--i]=M[i]<l? // if we are not part of the loop
i%w<1|i%w>w-2|i<w|i>W-w? // if we are on the edge
W: // on the edge
i: // not on the edge
-1; // this is on the loop
// now fill in
// we don't have to worry about wrapping, the important bit being an un-wrapping closed loop
// i = 0
for(;i<W;)
if(J[++i]<0) // we are on the loop
l=D[i]%5/2-1; // last one must be ^(4) or <(0)
else{ // can probably crush this into an l returning l assigning term (with if above)
A(i-1);
if(i>w)
A(i-w);
}
// now count the number of non-edges
for(c=W; // assume everything is a non-edge
i-->0;
L=""+(c>2?c:0)*l) // set output to be number of non-edges * clockness (or 0 if too few)
c-=J[i]<0?0:B(i)/W; // subtract 1 if an edge (B(i) is W), othewise 0
// at this point, i is 0, so we will fall out of all the loops
}
}
}
C.WriteLine(L); // output result
}
}
```
] |
[Question]
[
Domain name trading is big business. One of the most useful tools for domain name trading is an automatic appraisal tool, so that you can easily estimate how much a given domain is worth. Unfortunately, many automatic appraisal services require a membership/subscription to use. In this challenge, you will write a simple appraisal tool that can roughly estimate the values of .com domains.
## Input / Output
As input, your program should take a list of domain names, one per line. Each domain name will match the regex `^[a-z0-9][a-z0-9-]*[a-z0-9]$`, meaning that it is composed of lowercase letters, digits, and hyphens. Each domain is at least two characters long and neither begins nor ends with a hyphen. The `.com` is omitted from each domain, since it is implied.
As an alternative form of input, you can choose to accept a domain name as an array of integers, instead of a string of characters, as long as you specify your desired character-to-integer conversion.
Your program should output a list of integers, one per line, which gives the appraised prices of the corresponding domains.
## Internet and Additional Files
Your program may have access to additional files, as long as you provide these files as part of your answer. Your program is also allowed to access a dictionary file (a list of valid words, which you don't have to provide).
(Edit) I have decided to expand this challenge to allow your program to access the internet. There are a couple restrictions, being that your program cannot look up the prices (or price histories) of any domains, and that it only uses pre-existing services (the latter to cover up some loopholes).
The only limit on total size is the answer size limit imposed by SE.
### Example input
These are some recently-sold domains. Disclaimer: Although none of these sites seem malicious, I do not know who controls them and thus advise against visiting them.
```
6d3
buyspydrones
arcader
counselar
ubme
7483688
buy-bikes
learningmusicproduction
```
### Example Output
These numbers are real.
```
635
31
2000
1
2001
5
160
1
```
## Scoring
Scoring will be based on "difference of logarithms." For example, if a domain sold for $300 and your program appraised it at $500, your score for that domain is abs(ln(500)-ln(300)) = 0.5108. No domain will have a price less than $1. Your overall score is your average score for the set of domains, with lower scores better.
To get an idea what scores you should expect, simply guessing a constant `36` for the training data below results in a score of about `1.6883`. A successful algorithm has a score less than this.
I chose to use logarithms because the values span several orders of magnitude, and the data will be filled with outliers. The use of absolute difference instead of difference squared will help reduce the effect of outliers in scoring. (Also, note that I am using the natural logarithm, not base 2 or base 10.)
## Data Source
I have skimmed a list of over 1,400 recently sold .com domains from [Flippa](https://flippa.com/domains/just-sold?tld=com), a domain auction website. This data will make up the training data set. After the submission period is over, I will wait an additional month to create a test data set, with which the submissions will be scored. I might also choose to collect data from other sources to increase the size of the training/test sets.
The training data is available at the following gist. (Disclaimer: Although I have used some simple filtering to remove some blatantly NSFW domains, several might still be contained in this list. Also, **I advise against visiting any domain you don't recognize**.) The numbers on the right-hand side are the true prices. <https://gist.github.com/PhiNotPi/46ca47247fe85f82767c82c820d730b5>
Here is a graph of the price distribution of the training data set. The x-axis the the natural log of price, with y-axis being count. Each bar has a width of 0.5. The spikes on the left correspond to $1 and $6 since the source website requires bids to increment at least $5. The test data may have a slightly different distribution.
[](https://i.stack.imgur.com/zXmnJ.png)
[Here is a link](https://i.stack.imgur.com/fHP9w.png) to the same graph with a bar width of 0.2. In that graph you can see spikes at $11 and $16.
[Answer]
# Perl, 1.38605
I figured I should go ahead and post my own submission, in the hope that it spurs competition. Its score of `1.38605` means that it is typically off by a factor of `3.999` (that was my stopping point). I didn't use any machine learning libraries, just straight up Perl. It does require access to a dictionary; I used the one from [here](https://github.com/dwyl/english-words/blob/master/words2.txt).
Please feel free to use some of the numbers/statistics from my program in your own.
```
use strict;
my %dict;
my $dictname = "dict.txt";
open(my $dfh, '<', $dictname);
while (my $row = <$dfh>) {
chomp $row;
$dict{lc $row} = 1;
}
my $domain = <>;
chomp($domain);
my $guess = 1;
if($domain =~ /^[a-z]*$/){
my @bylength = (200000,20001,401,45,45,41,26,26,26,26,26,24);
if(length($domain) < ~~@bylength+2){
$guess *= $bylength[length($domain)-2];
} else {
$guess *= 18;
}
} elsif ($domain =~ /^[0-9]*$/){
my @bylength = (300000,30001,6000,605,50);
if(length($domain) < ~~@bylength+2){
$guess *= $bylength[length($domain)-2];
} else {
$guess *= 7;
}
} elsif ($domain =~ /^[a-z0-9]*$/){
my @bylength = (52300,523,28);
if(length($domain) < ~~@bylength+2){
$guess *= $bylength[length($domain)-2];
} else {
$guess *= 23;
}
} else {
my @bylength = (50000,500,42,32,32,31);
if(length($domain) < ~~@bylength+2){
$guess *= $bylength[length($domain)-2];
} else {
$guess *= 12;
}
}
my $wordfact = 1;
my $leftword = 0;
for(my $i = 1; $i <= length($domain); $i++){
my $word = substr $domain, 0, $i;
if(exists($dict{$word})){
$leftword = $i;
}
}
$wordfact *= ($leftword/length($domain))**2 * 0.8 + ($leftword/length($domain)) * -0.1 + 0.9;
if($leftword/length($domain) >= 0.8){
$wordfact *= 2.4;
}
my $rightword = 0;
for(my $i = 1; $i <= length($domain); $i++){
my $word = substr $domain, length($domain)-$i, $i;
if(exists($dict{$word})){
$rightword = $i;
}
}
$wordfact *= ($rightword/length($domain))**2 * 0.9 + ($rightword/length($domain)) * -0.2 + 1;
$guess *= $wordfact;
my $charfact = 1;
my %charfacts = (
i => 1.12, #500
l => 0.84,
s => 1.09,
a => 0.94,
r => 1.03,
o => 0.97,
c => 1.22, #400
d => 0.88,
u => 1.07,
t => 0.95,
e => 1.08,
m => 0.91, #300
p => 1.08,
y => 0.92,
g => 0.97,
ne => 0.56, #100
n => 1.13,
z => 0.67,
re => 1.30,
es => 0.75,
);
while(my ($key,$value) = each %charfacts){
if($domain =~ /$key/){
$charfact *= $value;
}
}
$guess *= $charfact;
$guess = int($guess + 0.5);
if($guess <= 0){
$guess = 1;
}
print $guess;
```
Here's a graph made by my scoring program, showing a scatter plot of appraisal over actual price and a histogram of the errors. In the scatter plot `.:oO@` mean `10, 20, 30, 40, 50` domains at that point, respectively. In the histogram each `O` represents 16 domains.
The scale is set at `1 character width = e^(1/3)`.
[](https://i.stack.imgur.com/6ske8.png)
There are three main steps to this program. The results from each step are multiplied together.
1. Categorization by character class and length. It determines if the domain is all letters, all numbers, letters and numbers, or if it contains a hyphen. It then gives a numerical value determined by the domain's length. I found that there is a strange dip in value around length 5. I suspect this is due to sampling: shorter domains are valuable due to their length (even if the letters are nonsense), while most longer domains tend to be words/phrases. I order to prevent overfitting, I put a restriction in that domains cannot be penalized for being shorter (so length 5 is at least as good as length 6).
2. Evaluation of word content. I use the dictionary to determine the lengths of the left-hand and right-hand words in a domain name. For example, `myawesomesite -> my & site -> 2 & 4`. Then, I try to do some fitting based on what proportion of the domain name is made up by those words. Low values typically indicate that the domain does not contain a word, contains a pluralized/modified word not in the dictionary, contains a word surrounded by other characters (internal words are not detected, although I tried that with no improvement), or contains a several-word phrase. High values indicate that it is a single word or a likely a two word phrase.
3. Evaluation of character content. I looked for substrings that were contained in lot of domains and which appeared to affect the values of the domain. I believe this is caused by certain types of words being more popular/more attractive, for various reasons. For example, the letter `i` appeared in about half of the domains (741 of them), and bumps up domain value by about 12% on average. That's not overfitting; there's something real there, that I don't fully understand. The letter `l` appears in 514 domains and has a factor of 0.84. Some of the less common letters/digraphs, like `ne` which appeared 125 times and has a really low factor of 0.56, might be overfitting.
In order to improve upon this program, I would probably need to use machine learning of some kind. Also, I could look for relationships between length, word content, and character content to find better ways of combining those separate results into the overall appraisal value.
] |
[Question]
[
Every programmer knows that rectangles `□` are really fun. To exacerbate this fun, these cute and fuzzy diagrams can be transformed into groups of interwoven brackets.
This challenge is the inverse [of my previous](https://codegolf.stackexchange.com/questions/68864/make-bracket-squares).
Let's say you have a group of interlocking rectangles like so:
```
+------------+
| |
+--+-+ +----+-+
| | | | | |
| | | +---+--+ | |
| | | | | | | |
+--+-+ | +-+--+-+-+-+
| | | | | | | |
| | | | | | | |
| | | | | | | | +-+
| +-+-+--+ | | | | |
| | | | | | +-+-+-+
+-----+-+----+ | | | | | |
| | | | | +-+ |
| +------+ | | |
| | | |
+----------+ +-----+
```
Additional Notes:
* No two `+`s will ever be adjacent
* No two rectangles will ever share an edge or corner
* **There will only ever be at most one vertical edge in each column**
The first step is to look at the left-most edge of any rectangle. Assign it one of four bracket types `({[<`. I choose `[`.
```
+------------+
| |
[--+-] +----+-+
[ | ] | | |
[ | ] +---+--+ | |
[ | ] | | | | |
[--+-] | +-+--+-+-+-+
| | | | | | | |
| | | | | | | |
| | | | | | | | +-+
| +-+-+--+ | | | | |
| | | | | | +-+-+-+
+-----+-+----+ | | | | | |
| | | | | +-+ |
| +------+ | | |
| | | |
+----------+ +-----+
```
Now look at the second left-most rectangle. Since it overlaps a `[` rectangle, it must be of a different type. I choose `(`.
```
(------------)
( )
[--(-] +----)-+
[ ( ] | ) |
[ ( ] +---+--+ ) |
[ ( ] | | | ) |
[--(-] | +-+--+-)-+-+
( | | | | ) | |
( | | | | ) | |
( | | | | ) | | +-+
( +-+-+--+ ) | | | |
( | | ) | | +-+-+-+
(-----+-+----) | | | | | |
| | | | | +-+ |
| +------+ | | |
| | | |
+----------+ +-----+
```
The next left-most rectangle does not intersect with any previous rectangle, but does nest within the previous. I choose to assign it `(` again. It is normally a good guess to assign a rectangle the same type as what it is nesting inside if possible, but sometimes backtracking is needed.
```
(------------)
( )
[--(-] +----)-+
[ ( ] | ) |
[ ( ] (---+--) ) |
[ ( ] ( | ) ) |
[--(-] ( +-+--)-)-+-+
( ( | | ) ) | |
( ( | | ) ) | |
( ( | | ) ) | | +-+
( (-+-+--) ) | | | |
( | | ) | | +-+-+-+
(-----+-+----) | | | | | |
| | | | | +-+ |
| +------+ | | |
| | | |
+----------+ +-----+
```
This next rectangle can be assigned `[` again.
```
(------------)
( )
[--(-] +----)-+
[ ( ] | ) |
[ ( ] (---+--) ) |
[ ( ] ( | ) ) |
[--(-] ( [-+--)-)-+-]
( ( [ | ) ) | ]
( ( [ | ) ) | ]
( ( [ | ) ) | ] +-+
( (-[-+--) ) | ] | |
( [ | ) | ] +-+-+-+
(-----[-+----) | ] | | | |
[ | | ] | +-+ |
[ +------+ ] | |
[ ] | |
[----------] +-----+
```
This next rectangle is kinda fun. It intersects both a `(` and a `[` rectangle, so I could call it a `{` rectangle (or `<` but nobody likes those).
```
(------------)
( )
[--(-] {----)-}
[ ( ] { ) }
[ ( ] (---{--) ) }
[ ( ] ( { ) ) }
[--(-] ( [-{--)-)-}-]
( ( [ { ) ) } ]
( ( [ { ) ) } ]
( ( [ { ) ) } ] +-+
( (-[-{--) ) } ] | |
( [ { ) } ] +-+-+-+
(-----[-{----) } ] | | | |
[ { } ] | +-+ |
[ {------} ] | |
[ ] | |
[----------] +-----+
```
The last two rectangles aren't that bad. They can be of any two different types.
```
(------------)
( )
[--(-] {----)-}
[ ( ] { ) }
[ ( ] (---{--) ) }
[ ( ] ( { ) ) }
[--(-] ( [-{--)-)-}-]
( ( [ { ) ) } ]
( ( [ { ) ) } ]
( ( [ { ) ) } ] {-}
( (-[-{--) ) } ] { }
( [ { ) } ] <-{-}->
(-----[-{----) } ] < { } >
[ { } ] < {-} >
[ {------} ] < >
[ ] < >
[----------] <----->
```
**Reading off the rectangles, I get `[(]([{))}]<{}>`.** This would be one possible output for the above input. Here's a list of many possible options, not exhaustive:
```
[(]([{))}]<{}>
<(>(<{))}>{()}
{<}[{(]>)}[<>]
any of the 4! permutations of ([{<, you get the idea...
```
## Input
ASCII-art rectangles, on the assumptions that they are unambiguous (see notes above) and can be properly converted into a string of brackets. You may assume either no trailing spaces or padded to a rectangle, with optional trailing newline. There will be no leading whitespace.
## Output
Any one of the valid bracket strings that obeys the intersection restrictions of the rectangles. Other than an optional trailing newline, there should be no other characters than brackets. The main rule is, if two squares intersect, then they should be assigned different bracket types.
## Goal
This is code-golf, (lack of) quantity over quality.
[Answer]
# Python 3, 519 bytes
```
def c(i):
a,b,c,d={},0,[],{}
for e in map("".join,zip(*i.split("\n"))):
if"+"in e:
f=e.index("+"),e.rindex("+")
if f in a:j=a.pop(f);d[j]=f+(d[j],len(c));c.append(j)
else:a[f]=b;d[b]=len(c);c.append(b);b+=1
g,h={},0
while d:
i={list(d)[0]};
for j,(k,l,m,n)in d.items():
for(o,p,q,r)in(d[v]for v in i):
if not(m>r or n<q or k>p or l<o or(q<m<n<r and o<k>l<p)):break
else:i.add(j)
for j in i:del d[j];g[j]=h
h+=1
s,u=set(),""
for t in c:u+="[{(<]})>"[g[t]+4*(t in s)];s.add(t)
return u
```
Here's a first attempt at a solution. The algorithm used purely looks at the corners in the diagram, abusing the fact only one vertical line can occur in a column, and therefore the first and last + in a column must be the corners of a rectangle. It then collects all rectangles and performs a naive (and somewhat nondeterministic) search for collisionless groups. I am not sure if this will always find the most optimal solution, but it worked for all examples I tried so far. Alternatively it could be replaced by a brute-force search for the least amount of groups.
Input: a string containing the ascii art. No trailing newline, and all lines must be padded to the same length using spaces. It is also completely fine with you not putting any of the |'s or -'s in there as it just looks at the corners.
As the golfing is quite simple (just whitespace minimalization and variable renaming mostly) it could probably be shorter, but as there are no other answers on this yet I'll leave it like this for now.
] |
[Question]
[
When a number is shown on a calculator, it's possible to consider what various transformations of that number would look like. For example, on a seven-segment display, 2 is shown like this:

And when flipped horizontally it looks like this:

As such, the mirror image of 2 is 5.
The task in this challenge is to take a single-digit number, and return the number that's its mirror image (if possible). If its mirror image does not look like a number, return the number rotated 180 degrees (if possible). If neither of these are the case, return -1.
Here's the full list of inputs and outputs your program needs to handle:
```
Input Output
0 0
1 -1
2 5
3 -1
4 -1
5 2
6 9
7 -1
8 8
9 6
```
As a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, the shortest code wins!
[Answer]
## Haskell - ~~43~~ 31
43 characters without anything fancy.
```
f 0=0
f 8=8
f 2=5
f 5=2
f 6=9
f 9=6
f _= -1
```
Got it down to 31 characters by making it a partial function.
```
f=([0,-1,5,-1,-1,2,9,-1,8,6]!!)
```
[Answer]
# GolfScript, 15 14
I read the spec again and found that the input must be a string.
```
"0.5..29.86"\?
```
To run:
```
echo -n 2 | ruby golfscript.rb a.gs
```
Old version(which has integer input):
```
[0.5..2 9.8 6]?
```
The newer one(14 byte) is somewhat inspired by the [CJam answer by aditsu](https://codegolf.stackexchange.com/a/31987/).
[Answer]
## PowerShell - 27
```
'0 5 29 86'.indexof($args)
```
[Answer]
# Python 2.x - 28
```
'015..29.86'.find(`input()`)
```
[Answer]
# JavaScript ~~37~~ 36
```
alert("0_5__29_86".search(prompt()))
```
[Answer]
**BEFUNGE 93 - ~~18~~ ~~14~~ 20 Bytes**
I guess the commentators are right, though Befunge being a 2d language lines are kinda different. Still, in this instant, the commentators are right.
```
&1g01g-.
! & #* )'
```
Steps:
```
&
```
Reads input as a numerical value x, and pushes it on the stack.
```
1g
```
Gets the character value c (so, like '!' = 33, or '\*' = 42. An empty cell = 32) at position x, 1.
```
01g-.
```
Reads the character value of cell 0,1 (33), subtracts it from c, and outputs it as a numerical value.
[Answer]
# CJam, 20 bytes
```
q25691347`"5296W"er~
```
[Try it online.](http://cjam.aditsu.net/)
### Output
```
$ for i in {0..9}; { cjam <(echo 'q25691347`"5296W"er~') <<< $i; echo; }
0
-1
5
-1
-1
2
9
-1
8
6
```
### How it works
```
q " Read from STDIN. The leaves a string on the stack. ";
25691347` " Push the string '25691347'. ";
"5296W" " Push the string '5296W'. ";
er " Perform character transliteration. ";
~ " Evaluate the result. Examples: '2' returns 2, 'W' returns -1. ";
```
[Answer]
# Java - 49
```
long f(int a){return(0x790a300601L>>(a*4)&15)-1;}
```
Here, `0x790a300601` is a value stuffed with the desired outputs, with one added to make them positive. The values are stored in nibbles within the value, so a bit of shifting and masking is required to pop them out.
# Java - 100 (fun option)
```
int f(int a){Random r=new Random(0x2000A2F47D6Fl);int b=0;for(;a>=0;a--)b=r.nextInt(11)-1;
return b;}
```
Not the smallest option, but a bit of fun. I found a random seed that produces the correct values when called *X* times (where 0 >= *X* <= 9).
[Answer]
# JavaScript (ECMAScript 6) 25
```
x=>'1060039097'[x]-(x!=6)
```
# JavaScript (ECMAScript 5) 43
```
function f(x){return'1060039097'[x]-(x!=6)}
```
UPDATE: edc65 has suggested a much better technique. toothbrush has suggested a much better language. At this point, my primary contributions are debugging and gumption.
[Answer]
# bash 29
```
tr 1-9 x5xx29x86|sed s/x/-1/g
```
e.g.
```
$ echo 0 1 2 3 4 5 6 7 8 9 | tr 1-9 x5xx29x86|sed s/x/-1/g
0 -1 5 -1 -1 2 9 -1 8 6
```
[Answer]
# [Kona](https://github.com/kevinlawler/kona) - 29
This function returns the element `x` from the array `0 -1 5...`
```
f:{0 -1 5 -1 -1 2 9 -1 8 6@x}
```
Examples:
```
> f 2
5
> f 5
2
> f 8
8
```
[Answer]
# JavaScript 36 ~~37~~ ~~41~~
```
alert('0x'+'65b558f5ec'[prompt()]-6)
```
as ES6 function - 27:
```
f=v=>'0x'+'65b558f5ec'[v]-6
```
[Answer]
# Sclipting, 11 characters
```
걄럣뉥밈결⓷方分결剩貶
```
Finally I have found a Windows computer with Visual Studio installed to build its interpreter. And it has defeated my GolfScript code easily.
It reads `18453063256\11\?/11%(` in GolfScript.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 22 bytes
```
⊢⌷{1-⍨⎕A⍳'BAGAADKAJH'}
```
Explanation:
```
⊢⌷{1-⍨⎕A⍳'BAGAADKAJH'}
⎕A⍳'BAGAADKAJH' ⍝ numeric vector 2 1 7 1 1 4 11 1 10 8
1-⍨ ⍝ decrement: 1 0 6 0 0 3 10 0 9 7
⊢⌷ ⍝ value at index ⍵ in the lut
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/9OApMajrkWPerZXG@o@6l0BlHJ81LtZ3cnR3dHRxdvRy0O9VhOkAagw7dAKAwVDBSMF4/8A "APL (Dyalog Extended) – Try It Online")
[Answer]
# J - ~~28~~ 27 bytes
You know what I like? Simplicity (28 bytes). Note that in J, `_1` is negative one (-1).
```
f=:{&0 _1 5 _1 _1 2 9 _1 8 6
```
Add a little complexity and you have 27 bytes.
```
f=:-{&0 2 _3 4 5 3 _3 8 0 3
```
Example:
```
f 2
5
f 6
9
f 5
2
...
```
[Answer]
# CJam - 14
Input/output version:
```
"0 5 29 86"q#
```
Stack version (assumes the number is on the stack):
```
[0W5WWY9W8 6]=
```
Try them at <http://cjam.aditsu.net/>
[Answer]
# Perl, 27 26
Count includes the `p` flag
```
y/2569/5296/,s/[1347]/-1/
```
Usage:
```
$ echo 7 | perl -pe y/2569/5296/,s/[1347]/-1/
-1
```
***Wait, did Perl just beat J? :)***
[Answer]
## ECMAScript 6, 24
```
f=x=>~-++'0n5nn29n86'[x]
```
Using normal JavaScript it would be 33:
```
alert(~-++'0n5nn29n86'[prompt()])
```
[Answer]
# [Marbelous](https://github.com/marbelous-lang) 34 bytes
```
}0
=6=9=2=5=0=8?0
+3-3+3-3....--
```
It's not the shortest solution, but it's not the longest either.
**How it works**
`}0` spawns a marble representing the first command line input. This marble drops down the next tick, onto the `=6` cell. `=6` is a comparison cell, it pushes any marble with value 6 down and all others to the right. This line-up of comparison cells pushes marbles right until they equal a desired value. 0 and 8 just fall through and get printed when tehy fall off the bottom of the board, 6 and 2, and 9 and 5 first get 3 added to them, subtracted from them respectively. If a marble doesn't equal any of the desired values, it lands on the `?0` cell, which turn any marble into a 0 marble1. This marble then gets decremented and falls off the board.
1 A `?n` marble technically turns any marble into a marble between 0 and n. This has the nice side effect that `?0` turns anything into 0.
[Answer]
# MATLAB - 35
I would wrap this in a function with `n` as the only parameter.
```
f=[0,-1,5,-1,-1,2,9,-1,8,6];
f(n+1)
```
35 characters.
[Answer]
# TI-BASIC, ~~24~~ 22
```
-1+int(11fPart(11^Ans.0954191904
```
This encodes the possible outputs in a lookup table stored as a base-11 floating point number; the (N+1)th base-11 digit after the decimal point is extracted from the table to get the value of the inverted digit. In base 11 the number is `.106003A097`, and the digits of this less one are exactly `0,-1,5,-1,-1,2,9,-1,8,6`.
edc65's trick of subtracting one in the case of 6 leads to this 24-byte solution, where `⑩^(` is a single one-byte token:
```
-(Ans≠6)+int(10fPart(.1060039097⑩^(Ans
```
The string approach is 29 bytes:
```
-(Ans≠6)+expr(inString("1060039097",Ans+1,1
```
The array approach (which Ypnpyn also took) is 30 bytes, assuming the number is stored in X:
```
{1,0,6,0,0,3,10,0,9,7}-1:Ans(X+1
```
24 -> 22: Removed two extra digits of precision in the magic constant.
[Answer]
# C - 47 bytes [was 48 Bytes]
```
f(i){return(int[]){1,0,6,0,0,3,10,0,9,7}[i]-1;}
```
To add I/O (which other answers didn't always) for 86 bytes:
```
main(i){i=(int[]){1,0,6,0,0,3,10,0,9,7}[getchar()-48]-1;i<0?puts("-1"):putchar(i+48);}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes
```
0®5®®Y9®8 6¹@
```
[Try it online!](https://tio.run/nexus/05ab1e#@29waJ3poXWH1kVaHlpnoWB2aKfD//@WX/PydZMTkzNSAQ "05AB1E – TIO Nexus")
-3 thanks to [Emigna](/users/47066).
Explanation:
```
0®5®®Y9®8 6¹@ Takes an integer from STDIN.
0®5®®Y9®8 6 Push 0, r=-1, 5, r=-1, r=-1, Y=2, 9, r=-1, 8, 6.
¹ Push first input item.
@ Pop and push the 0-indexed stack item at the respective index.
```
[Answer]
# Python - 34
```
f=lambda n:ord("A@F@@CJ@IG"[n])-65
```
[Answer]
## Java, 58 ~~59~~
```
int f(int i){int[]a={1,0,6,0,0,3,10,0,9,7};return a[i]-1;}
```
OR
```
int f(int i){return new int[]{1,0,6,0,0,3,10,0,9,7}[i]-1;}
```
[Answer]
## JavaScript 42 37
Run it on the console of your browser
```
alert(~-[1,,6,,,3,10,,9,7][prompt()])
```
[Answer]
# C - 117 108 106 77 76 bytes
```
a[]={1,0,6,0,0,3,10,0,9,7};main(int c,char**b){printf("%d",a[*b[1]-48]-1);}
```
Not the best language for golfing, but oh well...
Compile with `gcc progname.c -o progname`. (Ignore the warnings, or add `-include stdio.h` to the compile command.)
>
> Usage: ./progname <number>
>
>
>
**EDIT**
As per @bebe's suggestion, here is an example that takes the input from STDIN instead:
# C - 68 51 bytes
```
main(){printf("%d","106003:097"[getchar()-48]-49);}
```
[Answer]
# J (24, function)
(the input panel isn't playing nice. Paste the following in a python interpreter and my answer shall be revealed:)
```
print "f=:{&(_3+3 u:'^C^B^B^E^L^B^K\t')"
```
[Answer]
# Clojure - 36
```
#(case % 2 5 5 2 6 9 9 6 0 0 8 8 -1)
```
[Answer]
# Perl, 22B
`perl -pe "y/25690/52960/or$_=-1"`
Based off <https://codegolf.stackexchange.com/a/32012/19039>, but shorter. 1B penalty for -p.
] |
[Question]
[
# Challenge
Write a program or function that given a string, returns a valid Brainfuck program that when compiled and executed as Brainfuck, returns that string..
1. Assume all inputs are encoded as ASCII.
2. Assume the outputted BF program will execute in an environment with an infinite tape.
3. Assume the pointer starts at cell 0 with every cell initialized to a value of zero.
4. Each example below represent one possible correct output for the given input. In particular, the examples include extra newlines and spaces to help human readability. Solutions are free to format the outputted BF code in any way.
5. The tape is doubly infinite.
6. All cells provided by the interpreter are exactly 8-bit cells. Overflow and underflow wrap around in a predictable and sane matter.
## Examples
### Space string
Given the input ` ` , your program/function could return:
```
+++++ +++++
+++++ +++++
+++++ +++++
++ .
```
### Exclamation point
Given the input `!` , your program/function could return:
```
+++++ +++++
+++++ +++++
+++++ +++++
+++
.
```
### Two letters
Given the input `hi` , your program/function could return:
```
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
++++
.
+
.
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the smallest number of bytes wins. Good luck.
[Answer]
## Brainfuck, ~~55~~ 51 bytes
```
,[>+++[>+++++++<-]>[<++>>+++<-]<+<[>.<-]>+++.>>-.,]
```
[Try it online!](http://brainfuck.tryitonline.net/#code=LFs-KysrWz4rKysrKysrPC1dPls8Kys-PisrKzwtXTwrPFs-LjwtXT4rKysuPj4tLixd&input=aGVsbG8)
Example output for `hi` (without the linefeeds):
```
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>
```
### Explanation
This moves across the tape while writing the program. The surrounding `,[...,]` is a standard input loop. For each character, we use four cells:
```
[... x a b c ...]
```
where `x` is the cell we write the input to.
```
>+++[>+++++++<-]
```
This part uses cell `a` to write a `21` into cell `b` via a standard multiplication of `3` and `7`.
```
>[<++>>+++<-]
```
Now we use that `21` to write `42` into `a` and `63` into `c` by multiplying by `2` and `3` respectively. Then `<+<` moves back to cell `x` while turning the `42` into a `43` (the code point of `+`). Recap:
```
[... x 43 21 63 ...]
```
Now the main output loop:
```
[>.<-]
```
That is, while decrementing `x` we print one `+` each time.
```
>+++.
```
After we're done we reuse the `+` cell, by adding `3` to give `.`.
```
>>-.
```
Finally, we move to the `63`, decrement it to `62` (`>`) and output that as well. The next iteration will use this cell as `x`.
[Answer]
# Brainfuck, ~~39~~ ~~33~~ ~~32~~ 31 bytes
```
-[-[>]<--<--],[[>.<+]>+.--.+<,]
```
The algorithm that places **45** on the tape is taken from [Esolang's Brainfuck constants](https://esolangs.org/wiki/Brainfuck_constants#45 "Brainfuck constants - Esolang # 45").
This answer assumes that the output program's interpreter has wrapping, bounded cells; and that `,` zeroes the current cell (implying that the output program is run without input). [Try it online!](http://brainfuck.tryitonline.net/#code=LVstWz5dPC0tPC0tXSxbWz4uPCtdPisuLS0uKzwsXQ&input=Q29kZSBHb2xm)
For a (longer) solution that works unconditionally, see [my other answer](https://codegolf.stackexchange.com/a/83912).
### Test run
For input `Code Golf`, the following output is generated.
```
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.,-------------------------------------------------------------------------------------------------------------------------------------------------.,------------------------------------------------------------------------------------------------------------------------------------------------------------.,-----------------------------------------------------------------------------------------------------------------------------------------------------------.,--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.,-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.,-------------------------------------------------------------------------------------------------------------------------------------------------.,----------------------------------------------------------------------------------------------------------------------------------------------------.,----------------------------------------------------------------------------------------------------------------------------------------------------------.,
```
[Try it online!](http://brainfuck.tryitonline.net/#code=LS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLiwtLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLiwtLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0uLC0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLiwtLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS4sLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0uLC0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0uLC0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0uLC0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0uLA&input=)
### How it works
We begin by putting the integer **45** (character code of `-`) into a cell of the tape. The following code achieves this.
```
- Decrement cell 0, setting it to 255.
[ While the cell under the head in non-zero:
[>] Advance to the next zero cell.
<-- Decrement the cell to its left.
<-- Decrement the next cell to the left.
]
```
Before we enter the loop, the tape looks like this.
```
v
000 000 255
```
These three cells – **-2**, **-1**, and **0** – are the only ones we'll use in this program.
In the first each iteration of the loop, the rightmost cell is, then that cell and middle cell are decremented twice, leaving the following state.
```
v
000 254 252
```
In the next 126 iterations, the initial `-` decrements the middle cell, `[>]<` jumps to the rightmost cell, and `--<--` decrements the middle and the right cell. As a result, **3** is subtracted from the middle cell (modulo **256**) and **2** is subtracted from the rightmost cell.
Since **254 √∑ 3 (mod 256) = (254 + 256) √∑ 3 = 510 √∑ 3 = 170** and **252 √∑ 3 = 84**, the rightmost cell is zeroed out before the middle one, leaving the following state.
```
v
000 132 000
```
Similarly to the first iteration of the loop, the next iteration now subtracts **3** from the middle cell and **2** from the leftmost cell, placing the head on the leftmost cell.
```
v
254 129 000
```
Subsequent iterations, as in the 126 iteration before them, subtract **3** from the leftmost cell and **2** from the rightmost cell.
Since **254 √∑ 3 (mod 256) = 170** and **129 √∑ 2 (mod 256)** is undefined, this is done 170 times, leaving the following state.
```
v
000 045 000
```
The cell under the head is zero; the loop ends.
Now we're ready to generate output.
```
, Read a character from STDIN and put it the leftmost cell.
[ While the leftmost cell is non-zero:
[ While the leftmost cell is non-zero:
>. Print the content of the middle cell ('-').
<- Increment the leftmost cell.
] If the leftmost cell held n, the above will print 256 - n minus signs
which, when executed, will put n in cell 0 of the output program.
> Increment the middle cell, setting it to 46 ('.').
. Print its content ('.').
-- Decrement the middle cell twice, setting it to 44 (',').
. Print its content (',').
When executed, since the output program receives no input, the above
will zero cell 0 of the output program.
+ Increment the second cell, setting it back to 45 ('-').
<, Go back to the leftmost cell and read another character from STDIN.
] Once EOF is reached, this will put 0 in the leftmost cell, ending the loop.
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
O”+ẋp“.>
```
[Try it online!](http://jelly.tryitonline.net/#code=T-KAnSvhuotw4oCcLj4&input=&args=J2hpJw)
### Sample run
For input `hi`, this program prints
```
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++>++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++>
```
(without the linefeeds) which, in turn, [prints `hi`](http://brainfuck.tryitonline.net/#code=KysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysuKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKys-KysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrLisrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKz4&input=).
### How it works
```
O”+ẋp“.> Main link. Argument: s (string)
O Ordinal; convert each character in s into its code point.
”+ Yield the character '+'.
ẋ Repeat '+' k times, for each k in the code points.
“.> Yield the string ".>".
p Take the Cartesian product of both results.
```
[Answer]
# Brainfuck, ~~3513~~ 43 bytes
```
++[>+<------],[[>.>+<<-]>+++.->[<.>-]<--<,]
```
This answer makes *no assumptions* about the interpreter of the output program. [Try it online!](http://brainfuck.tryitonline.net/#code=KytbPis8LS0tLS0tXSxbWz4uPis8PC1dPisrKy4tPls8Lj4tXTwtLTwsXQ&input=Q29kZSBHb2xmIQ)
For a shorter solution (which works only with some interpreters), see [my other answer](https://codegolf.stackexchange.com/a/83862).
### Test run
For input `Code Golf`, the following output is generated.
```
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.-------------------------------------------------------------------+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.---------------------------------------------------------------------------------------------------------------++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.----------------------------------------------------------------------------------------------------+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.-----------------------------------------------------------------------------------------------------++++++++++++++++++++++++++++++++.--------------------------------+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.-----------------------------------------------------------------------+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.---------------------------------------------------------------------------------------------------------------++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.------------------------------------------------------------------------------------------------------------++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.------------------------------------------------------------------------------------------------------+++++++++++++++++++++++++++++++++.---------------------------------
```
[Try it online!](http://brainfuck.tryitonline.net/#code=KysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKy4tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrLi0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLSsrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysuLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLSsrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrLi0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysuLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0rKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKy4tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLSsrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKy4tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0rKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysuLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrLi0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLSsrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKy4tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0&input=)
### How it works
We begin by putting the integer **43** (character code of `+`) in the second cell of the tape. The following code achieves this.
```
++ Increment the first cell twice, setting it to 2.
[ While the first cell in non-zero:
>+ Increment the second cell.
<------ Decrement the first cell six times.
]
```
This essentially performs the modular division **2 √∑ 6 (mod 256)**. Since **(2 + 256) √∑ 6 = 258 √∑ 6 = 43**, the result is **43**, as intended.
Now we're ready to generate output.
```
, Read a character from STDIN and put it the first cell.
[ While the first cell is non-zero:
[ While the first cell is non-zero:
>. Print the content of the second cell ('+').
>+ Increment the third cell.
<<- Decrement the first cell.
] If the first cell held n, the above prints n plus signs
and puts n in the third cell.
>+++ Add three to the second cell, setting it to 46 ('.').
. Print its content ('.').
- Decrement, setting it to 45 ('-').
> Advance to the third cell.
[ While the third cell is non-zero:
<. Print the content of the second cell ('-').
>- Decrement the third cell.
] If the first cell held n, the above prints n minus signs,
thus negating the plus signs and zeroing the cell of the output program.
<-- Subtract 2 from the second cell, setting it back to 43.
<, Go back to the first cell and read another character from STDIN.
] Once EOF is reached, ',' will put 0 in the first cell, ending the loop.
```
[Answer]
# Pyth - 11 bytes
```
sm+*\+Cd".>
```
[Try it online here](http://pyth.herokuapp.com/?code=sm%2B%2a%5C%2BCd%22.%3E&input=%22helloworld%21%22&debug=0).
[Answer]
## 05AB1E, ~~12~~ 11 bytes
```
vyÇ`'+ׄ.>J
```
**Explained**
```
v # for each char in input string
yÇ` # convert to its ascii value
'+√ó # push the char '+' that many times
„.>J # push string ".>" and join with the plus signs
# implicitly print combined string
```
[Try it online](http://05ab1e.tryitonline.net/#code=dnnDh2AnK8OX4oCeLj5K&input=aGk)
Saved 1 byte thanks to @Adnan
[Answer]
# Java, 98 bytes
```
class a{String A(char[]b){String z="";for(char B:b){for(int c=B;c-->0;)z+="+";z+=".>";}return z;}}
```
`String`s are nothing more than immutable `char[]`s with a bunch of utility methods, so let's use the array!
Ungolfed:
```
class a {
void A(char[] b) {
for (char B : b) {
for (int c = B; c-- > 0;)
System.out.print('+');
System.out.print(".>");
}
}
}
```
Equivalent standalone program that is 138 bytes long:
```
interface a{static void main(String[]A){for(char b:A[0].toCharArray()){for(int B=b;B-->0;)System.out.print('+');System.out.print(".>");}}}
```
**Bonus:**
```
interface a{static void main(String[]A){for(char b:new java.util.Scanner(new java.io.File(A[0])).useDelimiter("\\Z").next().toCharArray()){for(int B=b;B>0;B--)System.out.print('+');System.out.print(".>");}}}
```
This 207-byte app actually encodes a file as a BF program, just as said in the title.
[Answer]
# [Brainfuck](https://github.com/TryItOnline/brainfuck), 29 bytes
```
,[[+>+[---------.]<]--[--.],]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fJzpa2047WhcG9GJtYnV1o0EMndj//zMyAQ "brainfuck – Try It Online")
**Explanation**:
```
,[ loop over all characters on input
[+ output number of minuses based on input
>+[---------.]< print characters including -
]
--[--.] print all even characters in reverse equal to .,
,]
```
This solution expects classic 8-bit wrapping interpreter and uses the fact that other characters than `+-,.<>[]` are ignored by brainfuck interpreter. It also expects that generated program will be run with no input and thus receives null bytes as input - reading of input is used to clear the cell.
Statement generating `-` actually generates following string: `øïæÝÔ˹°§zqh_VMD;2) üóêáØÏƽ´«¢~ulcZQH?6-$` , where the only interpretable character is `-`.
Statement generating `.,` actually generates `üúøöôòðîìêèæäâàÞÜÚØÖÔÒÐÎÌÊÈÆÄÂÀ¾¼º¸¶´²°®¬ª¨¦¤¢ ~|zxvtrpnljhfdb`^\ZXVTRPNLJHFDB@><:86420.,*(&$" ` where following characters are interpreted `><.,`. The `><` moves pointer right and then left, so it actually doesn't do anything.
[Answer]
# Vitsy, ~~19~~ 17 bytes
```
I\[&'>.+'i1-\Du]Z
I Get the length of the input stack.
\[ ] Pop n, repeat this block of code n times.
& Push a new stack and move to it.
'>.+' Push the string '+.>' to the stack.
i Pop an item from the input stack and push it to the current
program stack.
1- Subtract one from the top program stack item.
\D Duplicate the '+' in the stack that many times.
u Merge the current program stack with the previous.
Z Output the entire current stack as a string.
```
Note that this answer is one of the few times that I've ever used `I` and `u`. :D
[Try it online!](http://vitsy.tryitonline.net/#code=SVxbJmlcWycrJ10nLj4ncnVdWg&input=&args=VGhlIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu)
[Answer]
# [O](http://jadonfowler.xyz/o/), 13 bytes
```
i{'+n#*".>"}d
```
Explanation:
```
i Read standard input into a string and push it onto the stack.
{ }d For each character in the string...
'+ Push "+".
n# Convert the character (n) to its ASCII code.
* Multiply the "+" by the character code to get the number of +'s needed.
".>" Push the string ".>".
In O, the stack is printed after execution, so this prints out the result.
```
[Answer]
# K6, 16 bytes
```
,/{|">.",x#"+"}'
```
## Usage
```
,/{|">.",x#"+"}'"some string"
```
## Explanation
```
{ }' For each character in the string...
x#"+" Repeat "+" as many times as the character's ASCII code.
, Combine that with...
">." The code to print it and move on.
| But we put the string together backwards...so now it gets reversed.
,/ Combine all the substrings into one BIG string.
```
[Answer]
# Python 3, 43 bytes
```
lambda s:''.join('+'*ord(c)+'.>'for c in s)
```
The Python puts a number of pluses equivalent to the ASCII code of each character, followed by `.>` to print and move to the next cell.
The brainfuck increments up to the correct value, prints, and moves on to the next cell.
Output for `hi` (with newlines for clarity):
```
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>
```
That program's output:
```
hi
```
[Answer]
## Perl, 25 bytes
```
s/./"+"x ord($&).".>"/eg
```
## Usage
```
echo -n hi | perl -pe 's/./"+"x ord($&).".>"/eg'
```
## Explanation
Uses a regular expression replace operation to replace every character in every line given on standard input with a number of `+` calculated from the ordinal value of that character, then outputs `.>` to print and advance to the next character.
Uses the perl `-p` flag to automatically read the input and print the result, adding 1 extra to the bytecount.
[Answer]
# Java, 91 bytes
```
String b(char[] f){String k="";for(char b:f){for(int u=b;u>0;u--)k+="+";k+=".>";}return k;}
```
Props to [dorukayhan](https://codegolf.stackexchange.com/a/83857/45348) for beating me to it :)
[Answer]
# C, ~~72~~ ~~64~~ 60 bytes
```
main(c){for(;c=~getchar();)for(;printf(~c++?"+":".>")^2;);}
```
Ungolfed version:
```
main( c )
{
for ( ; c = ~getchar( ); )
for ( ; printf( ~c++ ? "+" : ".>" ) ^ 2; );
}
```
Compile and test with:
`gcc -o bfcat bfcatgolf.c && cat 1.txt | ./bfcat > o.txt && beef o.txt`
### Results
* `hi` - <http://paste.ubuntu.com/17995958/>
* `quick brown fox jumps over the lazy dog` - <http://paste.ubuntu.com/17996059/>
* source code - <http://paste.ubuntu.com/18000808/>
[Answer]
# CJam, 12 bytes
Converts each character to its ASCII value, and increments the current cell by that number of times before printing it. Since we have infinite tape we can just move to the right after processing each character.
```
q{i'+*'.'>}%
```
[Try it online!](http://cjam.tryitonline.net/#code=cXtpJysqJy4nPn0l&input=aGk)
[Answer]
## Lua, ~~67~~ ~~66~~ 61 Bytes
Simply iterate over each characters in the argument, and print a line for each one with `n` `+`s followed by `.>` where `n` is the value of this character in the ASCII Table.
**Uses gmatch as @LeakyNun advised in the comment for saving 1 Bytes over the the gsub solution**
```
for c in(...):gmatch"."do print(("+"):rep(c:byte())..".>")end
```
**Old solution using gsub**
```
(...):gsub(".",function(c)print(c.rep("+",c:byte())..".>")end)
```
**Old 67**
```
(...):gsub(".",function(c)print(string.rep("+",c:byte())..".>")end)
```
To run it, just save it as a file (`golf.lua` for instance) and run it with `lua golf.lua "hi"`. For `hi`, it should output
```
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>
```
[Answer]
# Sesos, 12 bytes
Hexdump:
```
0000000: 28cbf6 02e83d 655bae 243901 (....=e[.$9.
Size : 12 byte(s)
```
[Try it online!](http://sesos.tryitonline.net/#code=YWRkIDQzLGZ3ZCAxLGdldApqbXAKICBqbXAsc3ViIDEscndkIDEscHV0LGZ3ZCAxLGpuegogIGFkZCA0NixwdXQsYWRkIDE2LHB1dAogIGdldA&input=aGk&debug=on)
## Assembler
```
add 43,fwd 1,get
jmp
jmp,sub 1,rwd 1,put,fwd 1,jnz
add 46,put,add 16,put
get
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 27 bytes
```
,[[>+[++++.+++]<-]--[.--],]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fJzraTjtaGwj0gDjWRjdWVzdaT1c3Vif2///EJAA "brainfuck – Try It Online") [Try result](https://tio.run/##7drfKx5QHMfxtmZpiWXSEmtbkjZtS0vIlpa2xdKSaZOWeZaNrSeEtIQwmRAmEzITMvmVCT2z5@Lz@cMe50/YpYv33alz@r7ep87laep41xJt7op8SiSSUq5l3cq/X/SooqrmTeOHaFevhjSmac3rpza0o0P99aC/eco/vOx1b/uPYxeS0zJzcu8WlpQ/q37VEGlt7@nXiCY0q0Wt6rf2day4v3rc373gX970no/8DwwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDOy8YY771DGfhPWhD7zv3TBuK@xueM2rXgnAUjg/7znPeiaQk2HCmEc94uEQMaC4ThXTiY5C1kFQdrWtLW2G0LXgrmhZS1oI6XOhZEZTmtR4uMxoaBvWoAb6er/0dHd2tEU/t35sft/U@Lah/nVdbc3L6heVz59WPCl/XFZaXPSw8MG9gjv5ebm3b97IzrqemZF@NTXlSvLlSxd5BWBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGB8PP2vj6eJxBk)
Optimized from [Jiří's solution](https://codegolf.stackexchange.com/a/247269)
# [JavaScript (V8)](https://v8.dev/), 49 bytes
```
x=>[...x].map(c=>'+'.repeat(c.charCodeAt())+.1)+0
```
[Try it online!](https://tio.run/##BcFbCoAgEADA47iLtNRfEAoRdInoY9ukB5ZiEt3eZk5@@ZF0xFy9bRlN@YydiOib6eIIYqzSipKLjjMIyc5pCKvrMyBqalDXpZNwP8E78mGDERQvohDLDw "JavaScript (V8) – Try It Online")
[Answer]
# J, 28 bytes
```
[:;[:('.>',~'+'#~])"0[:]3&u:
```
Simple enough. `3&u:` converts chars to char codes. The rest is just repeat `'+'` that number of times, then concatenating with `.>` at the end of each line, and `;` flattens the result.
## Some results
```
bf =: [:;[:('>.',~'+'#~])"0[:]3&u:
bf 'hi'
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>.
bf ' !'
++++++++++++++++++++++++++++++++>. +++++++++++++++++++++++++++++++++>.
bf ' ~'
++++++++++++++++++++++++++++++++>.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>.
```
[Answer]
## Pyke, 11 bytes
```
F.o\+*".>"+
```
[Try it here!](http://pyke.catbus.co.uk/?code=F.o%5C%2B%2a%22.%3E%22%2B&input=hi)
[Answer]
## Actually, 13 bytes
```
O`'+*".>"@`MΣ
```
[Try it online!](http://actually.tryitonline.net/#code=T2AnKyoiLj4iQGBNzqM&input=ImFiYyI)
The strategy used here is the same as in many of the other solutions - for each character, output enough `+`s to increment a zero-initialized cell to the proper ASCII ordinal, output it with `.`, and move to the next cell with `>`.
Explanation:
```
O`'+*".>"@`MΣ
O list of ordinals (technically this is Unicode code points, but code points 0-127 are the same for Unicode and ASCII)
`'+*".>"@`M for each ordinal:
'+* push a string containing that many +s
".>"@ push ".>" and swap (putting it before the +s)
Σ concatenate all the strings (if "[", "]", and "," weren't meaningful characters in BF, this technically wouldn't be necessary)
```
[Answer]
# Mouse-2002, 27 bytes
```
(?'l:l.^(l.^"+"l.1-l:)".>")
```
This works in theory and according to the language's documentation, but the reference implementation of Mouse's interpreter seems to have a bug where string input appends a `'`, so for `a` this outputs
```
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++.>
```
Which in turn outputs `a'`. That may or may not be okay, so here's a **39 byte** long one which doesn't output `'` ever and thus is likely *more* invalid.
```
(?'l:l.39=l.0=+0=^(l.0>^"+"l.1-l:)".>")
```
Which gives right output in the reference impl. as long as there are no `'`s :)
Explained:
```
( ~ while (true) {
?' l: ~ l = getchar()
l. ^ ~ if (! (l) ) { break }
( ~ while (true) {
l. ^ ~ if (! (l) ) { break }
"+" ~ puts("+")
l. 1 - l: ~ l-- // l = l - 1
) ~ }
".>" ~ puts(".>")
) ~ }
```
[Answer]
# Factor, 58 bytes
```
[ [ [ 43 ] ""replicate-as ".>"append ] { } map-as ""join ]
```
Works like:
```
[
[
[ 43 ] "" replicate-as ! ``+'' * code point, clone-like a string ""
".>" append ! append ".>"
]
{ } map-as ! for each char in string and clone-like an array { }
"" join ! join array of str into str by ""
]
```
Since Factor comes with a Brainfuck interpreter, it's simple to test.
**bfcat.factor**
```
USING: sequences ;
IN: bfcat
: string>brainfuck ( s -- bf )
[ [ 43 ] "" replicate-as ".>" append ]
{ } map-as "" join ;
```
**bfcat-tests.factor**
```
USING: tools.test bfcat brainfuck ;
IN: bfcat.tests
{ "a" } [ "a" string>brainfuck get-brainfuck ] unit-test
{ "ab" } [ "ab" string>brainfuck get-brainfuck ] unit-test
{ "+++++++++++++" } [ "+++++++++++++" string>brainfuck get-brainfuck ] unit-test
{ "Code Golf" } [ "Code Golf" string>brainfuck get-brainfuck ] unit-test
```
**output**
```
Unit Test: { { "a" } [ "a" string>brainfuck get-brainfuck ] }
Unit Test: { { "ab" } [ "ab" string>brainfuck get-brainfuck ] }
Unit Test: {
{ "+++++++++++++" }
[ "+++++++++++++" string>brainfuck get-brainfuck ]
}
Unit Test: {
{ "Code Golf" }
[ "Code Golf" string>brainfuck get-brainfuck ]
}
```
Yay! they all pass.
[Answer]
# Ruby, ~~40~~ 38 bytes
```
gets.chop.each_byte{|o|puts"+"*o+".>"}
```
[Answer]
# [Sidef](https://github.com/trizen/sidef), 38 bytes
Hey, the same length as Ruby! just that Sidef isn't Ruby :D
```
read().bytes.each{|c|say"+"*c;say".>"}
```
Read some chars, then for each byte do that thing.
[Answer]
# GNU Bash, ~~100~~ 85 bytes
```
while IFS= read -rn1 c;do printf '+%.0s' $(seq 1 $(printf %d \'$c));echo '.>';done<$1
```
Thanks [@cat](https://codegolf.stackexchange.com/users/46231/cat) for saving me 15 bytes!
### Postramble
1. Assumes input string is represented as-is in a file passed as first argument.
2. Usage: `bash bfcat.sh <path to file containing string>`
3. Usage (with named pipe): `bash bfcat.sh <(echo -n '<string>')`
### Ungolfed
```
while IFS= read -r -n1 c # Read file byte by byte [1]
do
n=$(printf "%d" \'"$c") # `ord` of a char in bash [2]
printf '+%.0s' $(seq 1 $n) # emit character $n times [3]
echo '.>' # Emit output and shift command for bf. I love infinite memory.
done <"$1"
```
### References in Ungolfed version
1. [Read file byte by byte](https://stackoverflow.com/questions/13889659)
2. [`ord` of a char in bash](https://stackoverflow.com/questions/890262/)
3. [emit character $n times](https://stackoverflow.com/questions/5349718)
[Answer]
# ES6, ~~119~~ 115 bytes
`f=s=>{a='';for(i in[...s]){b=s[c='charCodeAt'](i)-(s[c](i-1)|0);a+=(b>0?'+'.repeat(b):'-'.repeat(-b))+'.'}return a}`
Saved 4 bytes, thanks to @Leibrug
[Answer]
# Haskell 50 Bytes
```
f[]=[]
f(x:y)=replicate(fromEnum x)'+'++".>"++f y
```
[Answer]
# ><>, ~~39~~ 41 bytes
```
0i:@:0(?;\~~o!
v?:+"Ā"-$/'.'~
/.13-1o'+'
```
## Explanation
Add 256 to each char code, then print that many `+`, then `.`
] |
[Question]
[
This is a problem from [NCPC 2005](https://ncpc.idi.ntnu.no/ncpc2005/). Roy has
an apartment with only one single electrical outlet, but he has a bunch of power strips.
Compute the maximum number of outlets he can have using the power strips he
has. The number of outlets per power strip is given as input.
It turns out that if the number of outlets of the strips respectively are
$$p\_1, p\_2, \dots, p\_n$$
then the number of outlets is
$$1 - n + \sum\_i p\_i$$ ,
or
$$1 + p\_1-1 + p\_2-1 + \dots + p\_n-1$$.
**The input to the *program or function* is a non-empty series of positive integers.**
## Examples
```
2 3 4
> 7
2 4 6
> 10
1 1 1 1 1 1 1 1
> 1
100 1000 10000
> 11098
```
[Answer]
## [Retina](https://github.com/mbuettner/retina/), 3 bytes
```
1
```
The trailing linefeed is significant.
Input is a space-separated list of [unary numbers](http://meta.codegolf.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary).
[Try it online!](http://retina.tryitonline.net/#code=IDEK&input=MTEgMTExMSAxMTExMTE)
### Explanation
The code simply removes all spaces as well as the `1` after them from the string. Here is why that works:
Addition in unary is simple: just concatenate the numbers which is the same as removing the delimiters. Decrementing by 1 is also simple: just remove a `1` from each number. We want 1 more than the sum of the decremented inputs though, so we simply only remove the `1`s we find after spaces, thereby decrementing all but the first input.
[Answer]
# Jelly, 3 bytes
```
’S‘
```
Decrement (all), sum, increment. [Try it here.](http://jelly.tryitonline.net/#code=4oCZU-KAmA&input=&args=Miw0LDY)
[Answer]
## [Hexagony](https://github.com/mbuettner/hexagony), ~~18~~ 14 bytes
```
.?<_(@'")>{+.!
```
Unfolded:
```
. ? <
_ ( @ '
" ) > { +
. ! . .
. . .
```
[Try it online!](http://hexagony.tryitonline.net/#code=ICAuID8gPAogXyAoIEAgJwoiICkgPiB7ICsKIC4gISAuIC4KICAuIC4gLg&input=MiA0IDY)
I don't think side-length 2 is possible, but there ~~must~~ might be a more efficient side-length 3 solution that this.
This is the usual "decrement all, sum, increment" approach, but I'll have to add diagrams later to show how exactly it works in Hexagony.
[Answer]
## Python, 24 bytes
```
lambda*n:1-len(n)+sum(n)
```
[Try it online](http://ideone.com/fork/DTMBwR)
[Answer]
# Mathematica, 9 bytes
```
Tr[#-1]+1&
```
[Answer]
## Haskell, ~~17~~ 15 bytes
```
foldl1$(+).pred
```
Usage example: `( foldl1$(+).pred ) [2,4,6]` -> `10`.
Old version, different approach, 17 bytes: `succ.sum.map pred`.
[Answer]
# J, 6 bytes
```
+/+1-#
```
Sum plus one minus length. Parenthesize and apply it, like so:
```
(+/+1-#) 2 3 4
7
```
[Answer]
## [Labyrinth](http://github.com/mbuettner/labyrinth), 9 bytes
```
"?;)!@
+(
```
[Try it online!](http://labyrinth.tryitonline.net/#code=Ij87KSFACiso&input=MiA0IDY)
The usual primer:
* Labyrinth is 2D and stack-based. Stacks have an infinite number of zeroes on the bottom.
* When the instruction pointer reaches a junction, it checks the top of the stack to determine where to turn next. Negative is left, zero is forward and positive is right.
Here we start at the top left `"`, a no-op, heading rightward. Next is `?`, which reads an int from STDIN (throwing away chars it can't parse as an integer, e.g. spaces). Now we have two cases:
If the input is positive, we turn right, performing:
```
( decrement top of stack
+ add top two stack elements
[continue loop]
```
If the input is zero (which occurs at EOF), we go straight ahead, performing:
```
; pop zero from EOF
) increment top of stack
! output top of stack as number
@ halt program
```
[Answer]
# Pyth, 5 bytes
```
hstMQ
```
increment(sum(map(decrement, input)))
[Answer]
## ES6, 25 bytes
```
a=>a.map(n=>r+=n-1,r=1)|r
```
[Answer]
# MATL, 3 bytes
```
qsQ
```
[Try it online.](http://matl.tryitonline.net/#code=cXNR&input=WzIsMyw0XQ)
## Explanation
```
qsQ
q thread decrement over the input array
s sum
Q increment
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
Code:
```
E<O>
```
Explanation:
```
E # Evaluates input
< # Decrement on list
O # Compute the total sum
> # Increment on the sum
# Implicit: output top of the stack
```
Takes input like an array (e.g. `[3, 4, 5]`).
[Answer]
## [Starry](https://esolangs.org/wiki/Starry), ~~26~~ 24 bytes
```
, + '` + ** `, +'*.
```
Expects newline-separated integers. [Try it online!](http://starry.tryitonline.net/#code=LCArICdgICAgICAgKyAqKiBgLCArJyou&input=MTAwCjEwMDAKMTAwMDA)
Thanks to @MartinBüttner for -2 bytes.
```
, Read line as integer
+ ' Dupe and jump to label 1 if nonzero
` Set label 0
+ Push 1
* Sub
* Add
` Set label 1
, Read line as integer
+ ' Dupe and jump to label 0 if nonzero
* Add
. Output as integer
```
The loop is unrolled so that the first number is not decremented, negating the need to increment. Pushing numbers is expensive in Starry...
[Answer]
# Bash + GNU utilities, 16
If there are `N` power strips, then there should be `N-1` separators in the comma-separated input list. All we need to do is replace the separators with `- 1 +` and arithmetically evaluate:
```
sed s/,/-1+/g|bc
```
Or using the same trick:
# Pure Bash (no external utilities), 19
```
echo $[${1//,/-1+}]
```
[Answer]
# APL (NARS 2000), ~~13~~ 10 bytes
`{1+(+/⍵)-⍴∊⍵}`
Edit: Down to 10 with Lynn's (better) approach.
`{1++/1-⍨⍵}`
[Answer]
# gs2, 5 bytes
(CP437-encoded.)
```
W&Φd'
```
That’s `read-nums dec m1 sum inc`.
[Answer]
## CJam, 7 bytes
```
q~:(:+)
```
[Test it here.](http://cjam.aditsu.net/#code=q~%3A(%3A%2B)&input=%5B2%204%206%5D)
Same approach as Lynn's (decrement all, sum, increment). This also works for 8 bytes (and is maybe a bit more interesting):
```
q~{(+}*
```
This folds "decrement, add" over the list. By doing that, the decrement is only applied to all elements except the first, such that we don't need to take care of the increment separately.
[Answer]
# C, ~~60~~ ~~59~~ 55 bytes
```
x;main(s){while(~scanf("%i",&x))s+=x-1;printf("%i",s);}
```
[Answer]
# Perl 6, 14 bytes
```
{1+[+] --¬´@_}
```
**usage**
```
my &f = {1+[+] --¬´@_}
say f([2,3,4]) # 7
say f([2,4,6]) # 10
say f([1,1,1,1,1,1,1,1]) # 1
say f([100,1000,10000]) # 11098
```
[Answer]
## Seriously, 7 bytes
```
,;l@Σ-u
```
[Try it online!](http://seriously.tryitonline.net/#code=LDtsQM6jLXU&input=MiwzLDQ)
Explanation:
```
,;l@Σ-u
, push input
; dupe
l@ push length (n), swap
Σ-u push sum, subtract n, add one
```
[Answer]
# [Mornington Crescent](https://github.com/padarom/esoterpret), ~~1909 1873~~ 1839 bytes
```
Take Northern Line to Stockwell
Take Victoria Line to Seven Sisters
Take Victoria Line to Victoria
Take Circle Line to Victoria
Take Circle Line to Bank
Take Circle Line to Hammersmith
Take Circle Line to Cannon Street
Take Circle Line to Hammersmith
Take Circle Line to Cannon Street
Take Circle Line to Bank
Take Circle Line to Hammersmith
Take District Line to Upminster
Take District Line to Hammersmith
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Turnham Green
Take District Line to Hammersmith
Take District Line to Turnham Green
Take District Line to Notting Hill Gate
Take Circle Line to Notting Hill Gate
Take Circle Line to Bank
Take Circle Line to Embankment
Take Northern Line to Stockwell
Take Northern Line to Embankment
Take Circle Line to Temple
Take Circle Line to Hammersmith
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Blackfriars
Take Circle Line to Embankment
Take District Line to Parsons Green
Take District Line to Bank
Take Circle Line to Hammersmith
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Parsons Green
Take District Line to Embankment
Take Circle Line to Blackfriars
Take Circle Line to Bank
Take Northern Line to Angel
Take Northern Line to Bank
Take Circle Line to Bank
Take District Line to Upminster
Take District Line to Bank
Take Circle Line to Bank
Take Northern Line to Mornington Crescent
```
[Try it online!](https://tio.run/##zVXBTsMwDL3vK8IdPoIVtB5gmrQC5xDMGjWxJ9fA5w8PtFZaWxpAlXrNc16c5/eSSIwed0J45RhqByiHQ2ErMGtiKYHR3HkEI2S2Qq76gBAWX/ijd0LsbYvDO6DZ@lqA64Ga08I3nHl2AdLApcWqF8htjHpg9FL24plFJO1LGEAmYkhv7kblYb1nU/Gwjx6Pkg3g/2dYgiM89j7T/cUbY2mjWWkJ/lmFFJY1iajZTe5DMCsr0DuztKrBkd/GZ4WiBmmRlKMOfk5wxl9A3AeYyG1z98oyWFe96htxemFGxO8QbHQnYf2jTSZM89z1TZFnxJ9jI2rV7Tj/GncwlIrBobTA79UY5@z0cd98mCZrPsxc00yX5ok4vFx8Ag "Mornington Crescent – Try It Online")
[Answer]
# [Perl 6](http://perl6.org), 20 bytes
```
put 1+sum --¬´@*ARGS
```
( You can use `<<` instead of `¬´` )
### Usage:
```
$ perl6 -e 'put 1+sum --¬´@*ARGS' 100 1000 10000
11098
```
[Answer]
# Perl 5 23+2=25 or 19+2=21
Requires `-ap` flags:
```
map{$.+=($_-1)}@F;$_=$.
```
Saved in a file and run as
```
perl -ap file.pl
```
EDIT: Another answer, smaller (19+2) but basically copied from dev-null answer:
```
$.+=$_-1for@F;$_=$.
```
[Answer]
## F#, 25 bytes
```
Seq.fold(fun s n->s+n-1)1
```
This is a function that takes in an array/list/sequence of integers and returns the required result.
### How it works:
`Seq.fold` allows you to apply a function to every element of a sequence while carrying some state around while it does so. The result of the function as applied to the first element will give the state that will be put into the function for the second element, and so forth. For example, to sum up the list `[1; 3; 4; 10]`, you'd write it like this:
```
Seq.fold (fun sum element -> sum + element) 0 [1; 3; 4; 10]
( function to apply ) ^ (sequence to process)
( initial state )
```
Which would be applied like so:
```
// First, initial state + first element
0 + 1 = 1
// Then, previous state + next element until the end of the sequence
1 + 3 = 4
4 + 4 = 8
8 + 10 = 18
```
With the last state being the return value of `Seq.fold`.
[Answer]
# ùîºùïäùïÑùïöùïü, 5 chars / 7 bytes
```
ï⒭+‡_
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter3.html?eval=true&input=%5B2%2C3%2C4%5D&code=%C3%AF%E2%92%AD%2B%E2%80%A1_)`
Uses a custom encoding with 10-bit chars (thx @Dennis!). Run `encode('ï⒭+‡_')` in the JS console to get encoded form, and `decode(/*ENCODED TEXT HERE*/)` to decode encoded form.
# Explanation
Translates to Javascript ES6 as:
```
i=>i.reduce(($,_)=>$+--_)
```
[Answer]
## Python 3, 79 bytes
```
import sys
print(sum(map(lambda x: int(x)-1, sys.stdin.readline().split()))+1)
```
[Answer]
## Ruby, 30 bytes
```
$*.inject(1){|s,v|s+=v.to_i-1}
```
Simple enough - starting from 1, add up the supplied numbers, each -1 (command line args are in `$*`). Shame `inject` is such a long word.
[Answer]
## PowerShell, 19 bytes
```
$args-join'-1+'|iex
```
Note that `1 + p1-1 + p2-1 + ... + pn-1` is equivalent to `p1-1 + p2-1 + ... + pn`.
Takes input as separate command-line arguments with `$args`. We `-join` those together with a `-1+` delimiter to create a string, such as `2-1+3-1+4`. The string is then piped to `Invoke-Expression` (similar to `eval`), and outputs the result.
[Answer]
## Perl, 21 + 2 = 23 bytes
```
$a+=$_-1for@F;say++$a
```
Requires `-a` and `-E`:
```
$ perl -aE'$a+=$_-1for@F;say++$a'<<<'2 3 4'
7
```
[Answer]
## Brainfuck, 15 bytes
Assumption: The , operator returns 0 once all input has been exhausted, and there are no extension cords with 0 plugs. Also, the IO needs to be in byte values instead of ASCII character codes.
```
+>,[-[-<+>],]<.
```
Explanation:
This uses 2 registers. A "Value" accumulator register, representing the number of devices that can be plugged in, and a "current cord" register that keeps track of the value of the current cord. It starts off by incrementing the value by 1, for the existing outlet. Then, for each extension cord, it subtracts one from the value since a plug is being taken up, then increments the value by the number of plugs.
Most online interpreters don't operate in raw byte input mode. To test it online, use this code:
```
+>,[->-[>+<-----]>---[-<+>]<[-<->]<[-<+>],]<.
```
] |
[Question]
[
## Context
So the Dutch "Ministerie van Binnenlandse Zaken en Koninkrijksrelaties" (NL) - "Ministry of the Interior and Kingdom Relations" (EN) recently released the source code of their digid-app.
They have some goofy code in there, which led to [mockery and memes on reddit](https://www.reddit.com/r/ProgrammerHumor/comments/10dh6x1/very_efficient_code/)
Source code of the offending method can be found [here](https://github.com/MinBZK/woo-besluit-broncode-digid-app/blob/ad2737c4a039d5ca76633b81e9d4f3f9370549e4/Source/DigiD.iOS/Services/NFCService.cs#L182). Here's a copy:
```
private static string GetPercentageRounds(double percentage)
{
if (percentage == 0)
return "‚ö™‚ö™‚ö™‚ö™‚ö™‚ö™‚ö™‚ö™‚ö™‚ö™";
if (percentage > 0.0 && percentage <= 0.1)
return "üö™‚ö™‚ö™‚ö™‚ö™‚ö™‚ö™‚ö™‚ö™";
if (percentage > 0.1 && percentage <= 0.2)
return "üîµüö™‚ö™‚ö™‚ö™‚ö™‚ö™‚ö™‚ö™";
if (percentage > 0.2 && percentage <= 0.3)
return "üîµüîµüö™‚ö™‚ö™‚ö™‚ö™‚ö™‚ö™";
if (percentage > 0.3 && percentage <= 0.4)
return "üîµüîµüîµüö™‚ö™‚ö™‚ö™‚ö™‚ö™";
if (percentage > 0.4 && percentage <= 0.5)
return "üîµüîµüîµüîµüö™‚ö™‚ö™‚ö™‚ö™";
if (percentage > 0.5 && percentage <= 0.6)
return "üîµüîµüîµüîµüîµüö™‚ö™‚ö™‚ö™";
if (percentage > 0.6 && percentage <= 0.7)
return "üîµüîµüîµüîµüîµüîµüö™‚ö™‚ö™";
if (percentage > 0.7 && percentage <= 0.8)
return "üîµüîµüîµüîµüîµüîµüîµüö™‚ö™";
if (percentage > 0.8 && percentage <= 0.9)
return "üîµüîµüîµüîµüîµüîµüîµüîµüö™";
return "üîµüîµüîµüîµüîµüîµüîµüîµüîµüîµ";
}
```
## Try it online:
<https://dotnetfiddle.net/aMEUAM>
## Challenge
Write code in any language as short as possible to replicate the above function
## Rule clarification
* You must exactly match the input and output of the original function. Substituting the ball characters with something else is not allowed.
* You must stick to the functions original boundaries. Meaning if the input is something unexpected like -1 or 42 you must still return the same result as the original function.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 53 bytes
```
f=(n,i=10)=>i?f(n,--i)+(n>=0&n<=i/10?"‚ö™":"üîµ"):''
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9mC0QaeTqZtoYGmrZ2mfZpQI6ubqamtkaena2BWp6Nbaa@oYG90qNZq5SslD7Mn7JVSdNKXf1/cn5ecX5Oql5OfrpGmoaukaYmF6qQgZ4JFjEzCyyClpYYgn6JfkCx/wA "JavaScript (Node.js) – Try It Online")
Need `n>=0` to handle NaN
[Answer]
# Scratch, ~~172 166~~ 142 bytes
This program [outputs to a global variable `o` which is automatically displayed](https://codegolf.meta.stackexchange.com/a/25520/108687) and assumes that [the `i` variable is initialized at 0](https://codegolf.meta.stackexchange.com/a/20836/108687) and that [the procedure will only be run once](https://codegolf.meta.stackexchange.com/a/20839/108687)1.

```
define(n
set[o v]to(
set[a v]to[üîµ
repeat(10
change[i v]by(1
if<<(i)>((n)*(10))>and<(-.01)<(n)>>then
set[a v]to[‚ö™
end
set[o v]to(join(o)(a
```
[Try it on Scratch!](https://scratch.mit.edu/projects/790853978/)
## Scratch, 116 bytes
This solution is technically invalid because it replaces the emojis with the characters "x" and "\_". Unfortunately, this method cannot use emojis due to the way strings seem to work in Scratch, as getting the character at a certain index of a string doesn't work for unicode chars. I just wanted to add this since I think it's really cool.
```
define(n
set[o v]to(
repeat(10
change[i v]by(1
set[o v]to(join(o)(letter((1)+<<(i)>((n)*(10))>and<(-.01)<(n)>>)of[x_
```
[](https://i.stack.imgur.com/f9rVT.png)
[Try it on Scratch!](https://scratch.mit.edu/projects/824072957)
1For testing purposes, the procedure is run many times in the scratch link, so `o` is pushed to an array of test results at the end of each call.
[Answer]
# [Type System](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-9.html) (TypeScript 4.9.4) - ~~243~~ 188 Bytes
Now they can validate their function with type safety!
* 56 Bytes thanks to **@ASCII-only**
* 8 Bytes thanks to **@ASCII-only**
* 114 Bytes only by **@ASCII-only** (without rounding)
```
type H<N,C=[],E={length:N},I='üîµ',L=C['length'],D=(`${N}`extends`${}e-${}`?'0.0':`${N}.0`)extends`0.${L}.0`|`0.${E['length']}${string}`?'‚ö™':I>=`${D}${L extends 9?'':H<N,[...C,0],C,D>}`
```
**Example usage**:
```
type ProgressBarZero = H<0>
type ProgressBarHalf = H<0.5>
type ProgressBarFull = H<1>
```
**(Original) Un-golfed Version**:
```
type LoadingBar<
// N is a given number
N extends number,
// AddOne is used to add 1 to a number since we can't use addition [0]=1, [1]=2, [9]=10 etc.
AddOne extends number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
// Progress is calculated by checking if N is 0 if so return 0, otherwise cast to string and extract first digit after 0.(M)(R...)
// and cast to a number along with anything else after R. If R is an empty string '' then we can just return M since this means
// it must be .(1)(0), .(2)(0), .(3)(0), etc. otherwise we use M to index V to add one.
Progress = N extends 0 ? 0 : `${N}` extends `0.${infer M extends number}${infer R}` ? R extends '' ? M : AddOne[M] : 10,
// ArrayCounter is an empty tuple which is used to count the iterations by tracking the length and appending
// elements recursively.
ArrayCounter extends any[] = [],
// IsLoading is a cached flag to help denote when to display ‚ö™ or üîµ since we can only check for equality and not less than
// or greater than we need to be able to keep track of when we are finished showing the percent loaded.
IsLoading extends number = 1,
// OutputString is our output string which we return at the end.
OutputString extends string = '',
// Length tracks the length of A each pass.
Length extends number = ArrayCounter['length'],
// Check if we have loaded all the üîµ elements by checking if our Length is equal to our Progress
CheckIsLoaded extends number = (Progress extends Length ? 0 : 1) & IsLoading,
// Symbol is which string to display and in order to check for "never" we need to compare [never] inside a tuple
// otherwise it becomes distributive, also [never] = [0]
Symbol extends string = [CheckIsLoaded] extends [0] ? '‚ö™' : 'üîµ'
> =
// Here is the logic portion: if our Length is 10 we are finished and return the OutputString
Length extends 10 ? OutputString :
// Otherwise call recursively adding a new element to ArrayCounter each time to keep of the iterations
// using EndLoading as the new IsLoading and concatinating Symbol to OutputString. Unfortunately,
// we can only keep track of the tuple ArrayCounter'ss length and not strings.
LoadingBar<N, AddOne, Progress, [...ArrayCounter, Symbol], CheckIsLoaded, `${OutputString}${Symbol}`>
```
[Try it on the TypeScript playground!](https://www.typescriptlang.org/play?#code/C4TwDgpgBAEgPAOQDQGEC8BtAukgomgbwBsIA7Ac2AAsAuBAXyQEk0ByQXg3BWXdaQBk0UGViQrVWOACJoAFAAMAJAQayIAD2BkAJgGcFBehAC0i+rID8rAAwA6S6xp6Gt2QEo1G0jtk3Fves4Afb2tFXCERSipxekVtYAAnAEsKUwtAKrJ7JgA+ND0JGIJeKHctbSgATgt7eGQMa3qUJEscRoks0wAoDtBIKA04ywBGKDRYOBtLSampgCZBrI6AekWoVYA9M27waH7gSxmRsZsAFiGF5dWoDa3e3csAZkP4GxnzlfXNnp2IAeOn8es9zel2uXz6Pz2AFZ-idgR8bt8BgA2GHWSFwq6fbbggYAdlRuIxoOxdwAHKjSUSsbcIZZyqjylSETjgINLP9BrYmWDdoNhqNnlylu9MczeQcBXBDJzLNySRDBo9JWzJnKaXFBn9JZZVIMZkDhSDqYjWdDlWqTYMUcqIPdVYb4TyFfibeU3UygA)
[Answer]
## Excel formula, 58 ~~82~~ ~~104~~ bytes
>
> -22 bytes thanks to @DominicvanEssen massive optimizations !
>
>
> -24 bytes thanks to @TaylorAlexRaine even more massive optimization !
>
>
>
```
=LEFT(REPT("üîµ",-INT(-10*A1^(A1>=0)))&REPT("‚ö™",10),10)
```
Put the formula in any cell, and the parameter in the "A1" cell
---
Alternative solution : Creating a number of exactly 10 digits composed exclusively of 9's mapped as üîµ, and 8's mapped as ‚ö™ (**82 bytes**) :
```
=SUBSTITUTE(SUBSTITUTE(10^10-1-INT(10^INT(10*(1-A1^(A1>=0)))/9),9,"üîµ"),8,"‚ö™")
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 70 bytes
```
p->{var s="";for(int i=0;i<=9;)s+=p<0|p>i++*.1?"üîµ":"‚ö™";return s;}
```
[Try it online!](https://tio.run/##tdI9TsMwFAfwPad48pQQJU0GhtZNuUCZGBGDSZzKJXUs24lAJbdgYmFn50KcgBsER6QgVUlaUrDsxR8///X01qQk3jq5q0Vxm7EY4owoBZeEcdhaFgDjmsqUxBSWZgPMuNKS8RWkdpKbJxSEg81@1VxWmmhjLCGDqBbeYlsSCSpCCKe5tA0FLAowm0dT7Cg3EvPgUSyY65754QX6eHl6QzP0/vyKsKS6kBwUruoGb7O1fJmzBDYmof0V5foGiFwpp433oDTd@HmhfWFOdcbtzE9tLwz8wHGwuTGZAL0XNNY0gRk03x6zBnFjh/@Ff@fex02lBuYBsj/vaDPsjnmauUO76zoOPe8Pur9@5U6Pdzv@OWAPF@KUBgv7GuxP8J/2HY1XVlV/Ag "Java (JDK) – Try It Online")
Don't hesitate to correct me, or ask me if this needs explanations!
I've really tried to do this challenge using alternative approaches, but it could never beat the good ol' for :(
---
*Here are my other attempts so far :*
Using the repeat available in Java 11+ (**78 bytes**) :
```
p->{int n=(int)(p<0|p>1?0:10-p*10);return"üîµ".repeat(10-n)+"‚ö™".repeat(n);}
```
Using a single inline Stream (**85 bytes**) :
```
p->"0123456789".chars().mapToObj(e->p<0|p*10>e-48?"üîµ":"‚ö™").reduce("",(a,b)->a+b)
```
Creating a 11-bits binary (the "1" to the left end is to protect the "ten zeroes" case) and mapping 1's as üîµ, and 0's as ‚ö™ (**109 bytes**) :
```
p->Integer.toString(2048-(1<<(int)(p<0|p>1?0:10-p*10)),2).substring(1).replace("0","‚ö™").replace("1","üîµ")
```
Creating a number of exactly 10 digits composed exclusively of 9's mapped as üîµ, and 8's mapped as ‚ö™ (**110 bytes**) :
```
p->(""+(long)(Math.pow(10,10)-Math.pow(10,(int)(p<0|p>1?0:10-p*10))/9)).replace("8","‚ö™").replace("9","üîµ")
```
Dirty recursion with optional parameter to match original function call signature (**113 bytes**) (fails if called without parameter) :
```
String f(Double... p){return p.length<2?f(p[0],10d):p[1]>0?f(p[0],--p[1])+(p[0]<0|p[0]>p[1]*.1?"üîµ":"‚ö™"):"";}
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 34 [bytes](https://en.wikipedia.org/wiki/UTF-8)
```
*A c mA : multiply input by 10, round up to nearest whole n, max of this and 10. Store this result in U
<0?A:U : If U is negative, 10, else U. Store in V
"üîµ"pV +"‚ö™"pVnA : Blue dot repeated V times, white dot repeated 10-V times
: Implicit output
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=KkEgYyBtQQo8MD9BOlUKIlx1ZDgzZFx1ZGQzNSJwViArIlx1MjZhYSJwVm5B&input=LTAuMQ)
## [Japt](https://github.com/ETHproductions/japt) [`-E"üîµüîµüîµüîµüîµüîµüîµüîµüîµüîµ"`](https://codegolf.meta.stackexchange.com/a/14339/), 24 [bytes](https://en.wikipedia.org/wiki/UTF-8) + 13 = 37
`-E"s"` implicitly outputs "s" if an error is thrown, but is considered a cheating flag.
```
*A c : Multiply input by 10, round up to whole number. Store in U
"üîµ"pU +"‚ö™"pUnA : Blue dot repeated U times, white dot repeated 10-V times
: Implicit: Output that, or 10 dots if (0 < input < 1) is false
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LUUiXHVkODNkXHVkZDM1XHVkODNkXHVkZDM1XHVkODNkXHVkZDM1XHVkODNkXHVkZDM1XHVkODNkXHVkZDM1XHVkODNkXHVkZDM1XHVkODNkXHVkZDM1XHVkODNkXHVkZDM1XHVkODNkXHVkZDM1XHVkODNkXHVkZDM1Ig&code=KkEgYwoiXHVkODNkXHVkZDM1InBVICsiXHUyNmFhInBVbkE&input=LTAuMQ)
[Answer]
# C([gcc](https://gcc.gnu.org/)/[clang](https://clang.llvm.org/)) 86 characters (126 bytes)
returns a constant string of 30 bytes, same as the original and not a null terminated string as is common in C.
```
const char*p(double f){return"●●●●●●●●●●○○○○○○○○○○"+3*(int)(10.5-10*(f>1?1:f<0?1:f));}
```
```
const char*p(double f){
return "●●●●●●●●●●○○○○○○○○○○" //the constant string we index into
+3* //each character is three bytes
(int)( //pointers must be integers
10.5 //constant offset handling centering and rounding
-10*( //multiply up from the range 0->1 to
f>1?1:f<0?1:f //correctly enforce the bounds
)
);
}
```
[Answer]
# [R](https://www.r-project.org/), 48 bytes
```
function(i)intToUtf8(9898+118411*(0:9<10*i|i<0))
```
[Try it online!](https://tio.run/##TctBCoAgEEDRvSdxjGImWoxht6gTJMZsFMJ23d0Wgrl7fPh38XKJ30p44pklRS0gMe/pyIG1ZcsDES9ERuNqHaGRVxwC1E@PBKoKGyb849Szs@3YcsMMqnw "R – Try It Online")
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 59 bytes
```
param($a)-join(0..9|%{("‚ö™","üîµ")[$a-lt0-or$_-lt$a*10]})
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNydFNzi9K/a@SZlv9vyCxKDFXQyVRUzcrPzNPw0BPz7JGtVpD6dGsVUo6Sh/mT9mqpBmtkqibU2Kgm1@kEg9kqCRqGRrE1mr@r@XiUlNJU9A10DMEMwwgpJ6BKZRhCKNhAkYwGiZgDKNhAiYwGiYAp2EMMxgNEzCH0TABCxgNE7CE0RABw/8A "PowerShell Core – Try It Online")
Fixed the behaviour for negative values, thanks Ad√°m!
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `U`, 24 bytes
```
01?ŀ¬∨:⌐"₀*⌈`ǐẏḭ≈≠ṙ₅`½*∑
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBVSIsIiIsIjAxP8WAwqziiKg64oyQXCLigoAq4oyIYMeQ4bqP4bit4omI4omg4bmZ4oKFYMK9KuKIkSIsIiIsIjBcbjAuMVxuMC4yXG4wLjNcbjAuNFxuMC41XG4wLjZcbjAuN1xuMC44XG4wLjlcbjFcbi0xXG4wLjMxIl0=)
Utf-8 emojis amiright
## [Vyxal](https://github.com/Vyxal/Vyxal), 16 bytes
```
01?ŀ[₀*⌊×*₀↲|×₀*
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiMDE/xYBb4oKAKuKMisOXKuKCgOKGsnzDl+KCgCoiLCIiLCIwXG4wLjFcbjAuMlxuMC4zXG4wLjRcbjAuNVxuMC42XG4wLjdcbjAuOFxuMC45XG4xXG4tMSJd)
Uses `*` for üîµ and for ‚ö™, otherwise I'd have to score this in utf 8.
[Answer]
# [C# (.NET 7)](https://dotnet.microsoft.com/en-us/), 72 bytes
```
string a(double b,double c=0)=>c<.9?(b<0|b>c?"üîµ":"‚ö™")+a(b,c+.1):"";
```
[Try it here!](https://dotnetfiddle.net/CfVWS0)
```
string a(double b,double c=0) => //return
c<.9 //if counter is less than .9
? //then
( //this "X"
b<0|b>c //if the percentage is less less than 0 or greater than the counter
? //then
"üîµ" //blue ball
: //otherwise
"‚ö™" //white ball
) //end "X"
+ //plus
a(b,c+.1) //the result of calling the same function again with the counter increased by .1
: //otherwise (counter is greater than or equal to 1)
""; //return an empty string
```
[Answer]
# [Python](https://www.python.org), 55 bytes
-4 bytes thanks to `l4m2` and -15 bytes thanks to `Dominic van Essen`.
```
lambda n:(10-(b:=int(10-10*n)*(0<=n<1)))*'üîµ'+b*'‚ö™'
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3zXMSc5NSEhXyrDQMDXQ1kqxsM_NKQExDA608TS0NAxvbPBtDTU1NLfUP86dsVddO0lJ_NGuVOlR7QVp-kUKBQmaegkaFvqGBgQKIXwHiFyXmpadqGOgoGBoYAglNTSsuBYWCIpDpaerVBbUKCtVpGgWateqaXFxwQ6J1DfWAWkyMYq24OLEqhti7YAGEBgA)
[Answer]
# JavaScript 62 60 57 bytes
## Update. 57 bytes
Slitly shorter version using `[...1e9+'']` to generate an array of 10 elements instead of [...Array(10)]
```
i=>[...1e9+''].map((_,b)=>i<0|b<i*10?'üîµ':'‚ö™').join``
```
```
f=i=>[...1e9+''].map((_,b)=>i<0|b<i*10?'üîµ':'‚ö™').join``
const testCases = [-2, 0, 0.01, 0.20, .666, 0.9, 0.99, 1, 10, NaN];
testCases.forEach(i => console.log(f(i), i))
```
```
.as-console {
background-color: grey !important;
}
```
## Older version
Thank to @RydwolfPrograms for the `join` tip.
Non recursive solution.
```
i=>[...Array(10)].map((_,b)=>i<0|b<i*10?'üîµ':'‚ö™').join``
```
This solution does not handle a NaN parameter.
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 37 bytes [SBCS](https://github.com/abrudz/SBCS)
Tacit function.
```
⎕UCS 128309 9898/⍨10(⊢,-)∘⌈10×1⌊|+0∘>
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=e9Q3NdQ5WMHQyMLYwFLB0sLSQv9R7wpDA41HXYt0dDUfdcx41NNhaHB4uuGjnq4abQOggB0A&f=S1M4tN5Az5ArTcEAhCEsPUMIZQkhQRww1jMEAA&i=S1PQMzQFAA&r=tryapl&l=apl-dyalog&m=train&n=f)
`0‚àò>`‚ÄÉis argument negative? (0 or 1)
`|+`‚ÄÉadd that to the absolute value of the argument
`10√ó`‚ÄÉmultiply 10 by that
`10(`…`)∘⌈` round up and then, with 10 as left argument, apply the following function:
‚ÄÉ`-`‚ÄÉdifference between the arguments
 `⊢,` prepend the left argument
`128309 9898/‚ç®`‚ÄÉuse those counts to replicate the code points
`‚éïUCS` ‚ÄÉconvert to characters
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~33~~ 30 bytes
```
Y!@a?-:-a///tt'üîµXy.'‚ö™Xt-y
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhb7IhUdEu11rXQT9fX1S0rUP8yfsjWiUk_90axVESW6lRBFULUro5V0DfQMDJVioQIA)
### Explanation
I've replaced üîµ and ‚ö™ with `@` and `o` below so the columns will line up.
```
Y!@a?-:-a///tt'@Xy.'oXt-y
a ; Command-line argument
@ ; Get the first character
! ; Negate (truthy for 0, falsey for anything else)
? ; If that is truthy (which means 0.0 <= a < 1.0):
-a ; Negate a
// ; Int-divide (rounding down) by
/t ; 1/10
; (i.e. multiply by 10 and round down)
-: ; Negate the result
; Else:
t ; 10
Y ; Yank that value into y
'@Xy ; String of y copies of @ character
'oXt-y ; String of 10-y copies of o character
. ; Concatenate the two strings
```
[Answer]
# [Factor](https://factorcode.org/), 56 bytes
```
[| x | 10 iota [ x 10 * < x 0 < or 128309 9898 ? ] map ]
```
[Try it online!](https://tio.run/##NVDBToQwEL3zFS8kezGhaQsVqkaPxosX4wn3QLC4ZFmK0E00rt@OryRO5r15M5m20@maNvh5fX15en68wTS7EL6nuR8DFvd5dmPrFpyacMDRzaMb0PmZaejHDwy@bYYFt0nyg8wUQuYGmRQkoaKQCiT8C7sRjTEWlIy2qY0Kq0tDoSOiyHOI3EIUdANhiGuiLCEqlqMbKL6geJ8RJbTUWnCI32StL/jCBUqi96FBzYz6CncUkuxnKF3lHMpWtsID9vzlhP1a4/3MGDcx@cXxZJoO/dEh3dkzkN0Du@VtTLEtqWNn609bp2vaw/oH "Factor – Try It Online")
```
[| x | ! a quotation taking an argument x
10 iota ! the range [0..9]
[ ! start map quotation
x 10 * < ! is the range number less than x times ten?
x 0 < or ! or is x less than zero?
128309 9898 ? ! 128309 if so; 9898 if not
] map ! map each number in the range to something
] ! end quotation
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
•
#*Γ•6ôç9ÝT/I@Id*è
```
Output as a list of characters, since [strings are basically sequences of characters](https://codegolf.meta.stackexchange.com/questions/2214/whats-a-string). But since the challenge does ask to mimic the output *exactly*, a trailing `J`oin could be added for +1 byte.
[Try it online](https://tio.run/##yy9OTMpM/f//UcMiLmWtc5OBtNnhLYeXWx6eG6Lv6eCZonV4xX@v/wZ6xoYA) or [verify all test cases](https://tio.run/##Pc4hDsIwFMZxDacgxS2v8F63dasaGo0jCAgI1AQJSR2KA4DGYOAA3KCeQ@wipV8F4v/aXyr6@tN2dzzEs@/UZLjeRqqLw@U5nhbfezpt@ISXC4/V3C/8vgjvuKS41sLMpCtDWkjzzGHkGwspzYqY8j0NR3hK5QEZBBmoRFAJVeivGkE1ZBFkoQZBDdQiqIVykHMkJOl/YUrbYu3NDw).
**Explanation:**
```
•\n#*Γ• # Push compressed integer 1283099898
6ô # Split it into parts of size 6: [128309,9898]
√ß # Convert both to a character with this codepoint: ["üîµ","‚ö™"]
9√ù # Push list [0,1,2,3,4,5,6,7,8,9]
T/ # Divide each by 10: [0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]
I@ # Check for each value in the list whether it's >= the input
I # Push the input-decimal again
d # Check that it's non-negative (1 if >=0; 0 if <0)
* # Multiply that to each check, so negative inputs will become a list of 0s
è # 0-based index each 0 or 1 into the pair of unicode characters
# (after which the list of characters is output implicitly as result)
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•\n#*Γ•` is `1283099898`.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 69 bytes
```
void a(double b){for(int c=0;c<10;)Write(b<0|b*10>c++?"üîµ":"‚ö™");}
```
[Try it online!](https://tio.run/##Sy7WTS7O/P@/LD8zRSFRIyW/NCknVSFJszotv0gjM69EIdnWwDrZxtDAWjO8KLMkVSPJxqAmScvQwC5ZW9te6cP8KVuVrJQezVqlpGld@z9Rw0DPQNOaC6zUJzMvVQPIAQsaGBhiEzc0NjbHJm5kZolN2NjYGFNYF2jyfwA "C# (Visual C# Interactive Compiler) – Try It Online")
**Iterative Solution**
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 71 bytes
```
string a(double b,int c=0)=>c<10?(b<0|b*10>c?"üîµ":"‚ö™")+a(b,++c):"";
```
[Try it online!](https://tio.run/##Sy7WTS7O/P@/uKQoMy9dIVEjJb80KSdVIUknM69EIdnWQNPWLtnG0MBeI8nGoCZJy9DALtle6cP8KVuVrJQezVqlpKmdqJGko62drGmlpGT9P7wosyTVJzMvVSNRw0DPQFPTmgtNyMDAEFPU0NjYHFPUyMwSU9DY2BhdUBdk4n8A "C# (Visual C# Interactive Compiler) – Try It Online")
**Recursive Solution**
[Answer]
# [Swift](https://developer.apple.com/swift/), 70 84 bytes
-2 bytes thanks to @hatcyl suggestion
```
var f={i in(0...9).map{i<0||i>Float($0)/10 ?"üîµ":"‚ö™Ô∏è"}.joined()}
```
[Try it online!](https://tio.run/##Ky7PTCsx@f@/LLFIIc22OlMhM0/DQE9Pz1JTLzexoDrTxqCmJtPOLSc/sURDxUBT39BAwV7pw/wpW5WslB7NWvV@R79SrV5WfmZeaoqGZu3/gqLMvBKNNA1dI01NLhjHQM8EhWdmgcK1tETiGuoZGBoZAwX@AwA "Swift – Try It Online")
[Answer]
# [Perl](https://www.perl.org/), ~~52~~ 54 bytes
**Edit** : Change condition with >=&<= to handle NaN + add note
```
sub k($c){join'',map$c>=0&$c<=$_/10?"‚ö™":"üîµ",0..9}
```
[Try it online!](https://tio.run/##K0gtyjH9X1qcqpCWmlhSWpSqoF6cWKlu/b@4NEkhW0MlWbM6Kz8zT11dJzexQCXZztZATSXZxlYlXt/QwF7p0axVSlZKH@ZP2aqkY6CnZ1n7H6hZI1tD10hT05oLwjbQM0HmmFkg8ywtETy/RD8Q5/@//IKSzPy84v@6vjA3FWem54FZxQA "Perl 5 – Try It Online")
#### Note
It is possible to remove the join part, because Perl default behavior when you print an array is to join it, but it feel cheaty. What you guys think ?
##### Perl Cheaty version - 47 Bytes
```
sub k($c){map$c>=0&$c<=$_/10?"‚ö™":"üîµ",0..9}
```
[Try it online!](https://tio.run/##K0gtyjH9X1qcqpCWmlhSWpSqoF6cWKlu/b@4NEkhW0MlWbM6N7FAJdnO1kBNJdnGViVe39DAXunRrFVKVkof5k/ZqqRjoKdnWfsfqEsjW0PXSFPTmgvCNtAzQeaYWSDzLC0RPL9EPxDn/7/8gpLM/Lzi/7q@MMcUZ6bngVnFAA "Perl 5 – Try It Online")
It uses "signatures 15 years beta" feature (activable via commande line -Mfeature=signature) or via import. The old school perl take 2 bytes more :
```
sub j{join'',map@_[0]<0|@_[0]>$_/10?"üîµ":"‚ö™",0..9}
```
#### Explaination :
```
sub j{
join ('', # Join each element of a list with the string ''.
map( # Return a list of what the block return for each element of the list passed in second argument
{@_[0]<0|@_[0]>$_/10?"üîµ":"‚ö™"} , #@_[0] is the function first parameter, $_ the current iterated element
(0..9)) # Simple list
}
```
### Other interesting solution :
### The substr 61|59(signatures) Bytes,
probably fastest and lightest solution, (OK NaN)
```
sub b{substr'üîµ'x(10).'‚ö™'x(10-(@_[0]<0?10:@_[0]*10)),-10}
sub p($c){substr'üîµ'x(10).'‚ö™'x(10-($c<0?10:$c*10)),-10}
```
### The for loop 55|57 Bytes
Work only once, dunno if it can be improve without too many bytes (KO NaN):
```
sub l($c){$a.=($c<0|$c>$_/10?"üîµ":"‚ö™")for 0..9;$a}
```
### Recursive 81|62 Bytes
Not very interesting at first, juste a copy cat of JS. But i run into a small bug on the "old perl" version (KO NaN):
```
sub a{(@_[1]//=10)?a(@_[0],@_[1]-1).(@_[0]<0|@_[0]>(@_[1]-1)/10?"üîµ":"‚ö™"):''}
sub t($n,$i=10){$i?t($n,--$i).($n<0|$n>$i/10?"üîµ":"‚ö™"):''}
```
I expected this to work :
```
sub z{(@_[1]//=10)?z(@_[0],--@_[1]).(@_[0]<0|@_[0]>(@_[1])/10?"üîµ":"‚ö™"):''}
```
But it does not. --@\_[1](https://www.perl.org/) do not work and i dont understand why.
[Answer]
# [Julia 0.6](http://julialang.org/), 49 bytes
```
~x=rpad("üîµ"^ceil(Int,10(0<=x<1?x:1)),20,"‚ö™")
```
[Try it online!](https://tio.run/##yyrNyUw0@/@/rsK2qCAxRUPpw/wpW5XiklMzczQ880p0DA00DGxsK2wM7SusDDU1dYwMdJQezVqlpPmfS1nBrTQnR6EoMS89lSs3sUAjU9euoCgzryQnT6MuU1NH10DP0AqEDfUMNa25uGBymlxArc4ZqcnZCkX5pXkpmXnpCmn5RQqpKempCsmJxanF2EyLNtAz0FEAEkBgCGZYWlqCaMNYTev/AA "Julia 0.6 – Try It Online")
If the input `x` falls outside the range [0,1), it's replaced with `1`. The value ‚åà10x‚åâ determines the number of `"üîµ"`, and the output is padded to length with `"‚ö™"`.
Using the [ternary operator](https://docs.julialang.org/en/v1/manual/control-flow/) without spaces is deprecated in Julia 0.7 and disabled in Julia 1.0. The padding length passed to `rpad` has to be adjusted for Julia 0.6, probably because `textwidth` was added in Julia 0.7.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
>⁵Ḷ÷¤»⁻A$ị“¢€:“&Ɠ’Ọ
```
A monadic Link that accepts a double precision floating point number and yields a list of characters.
**[Try it online!](https://tio.run/##ATgAx/9qZWxsef//PuKBteG4tsO3wqTCu@KBu0Ek4buL4oCcwqLigqw64oCcJsaT4oCZ4buM////MC40MQ "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/9/uUePWhzu2Hd5@aMmh3Y8adzuqPNzd/ahhzqFFj5rWWAEZascmP2qY@XB3z/@jexwOtwNFvYE48v//aN3MvDQdBV0jAwMdIAHEQI4hEBvomYJYqbrGRsY6CgY6CnCmnoEpiDQEEWCWBZgwQAFGIDFLMAEkgWoN9QyAJFAYaIkCyDYFsMV5iXmxAA "Jelly – Try It Online").
### How?
```
>⁵Ḷ÷¤»⁻A$ị“¢€:“&Ɠ’Ọ - Link: double D
¤ - nilad followed by link(s) as a nilad:
⁵ - ten
·∏∂ - lowered range -> [0, 1, 2, ..., 9]
√∑ - divided by (ten) -> [0, 0,1, 0.2, ..., 0.9]
> - (D) greater than (that) (vectorised) -> G
$ - last two links as a monad - f(D):
A - absolute value (D)
⁻ - (D) not equal to (that)? -> K (K = (x<0 or x is nan)?)
» - (G) maximum (K) (vectorised)
-> L = list with 1 at blue and 0 at white
“¢€:“&Ɠ’ - list of base 250 compressed numbers = [128309, 9898]
ị - (L) index into (that) (vectorised)
Ọ - cast to characters
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 67 bytes
```
^[^0]|^0.9.
10$*@
T`_d`d`....
\d(..)?
$1$*@10$*‚ö™
1M!`.{10}
@
üîµ
```
[Try it online!](https://tio.run/##JY4tDgIxEIX9uwXJkiwkO5nhfxXrUDgcUErSFRgEwQG3QGHweC7ECbhB6StNvtcvM@LNqT0fjvvYLRc@urXT7dWp1ALTot9g5XfBBy/pYRNKkd4chaUN15/HC7bseLmY3tDg@7y/Y6xMzMBkKBOV5plKjjRT/D/JMAaEMiSUEaGMCWVCKFNCmRFKTQypELmU9TzkBw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
^[^0]|^0.9.
10$*@
```
Unless the input is from `0` to `0.9` inclusive, put 10 `@`s at the start. (I use `@` as it's a single UTF-16 character and `üîµ` isn't.)
```
T`_d`d`....
```
Increment the digits if there are at least three (not including the decimal point) i.e. leave `0`, `0.1` ... `0.9`.
```
\d(..)?.*
$1$*@10$*‚ö™
```
Convert the number of tenths (if any) into `@`s and also add 10 `‚ö™`s.
```
1M!`.{10}
```
Keep just the first 10 characters. This removes any surplus `‚ö™`s and also spurious `@`s or `‚ö™` arising from later digits.
```
@
üîµ
```
Turn `@`s into `üîµ`s.
[Answer]
# [Arturo](https://arturo-lang.io), 54 bytes
```
$[x][join map 0..9'n[(or? n<x*10x<0)?->"üîµ"->"‚ö™"]]
```
[Try it](http://arturo-lang.io/playground?QrcLJW)
```
$[x][ ; a function taking an argument x
join ; join a block of strings into a string
map 0..9'n[ ; map over 0..9 and assign current element to n
(or? n<x*10x<0)? ; is n<x*10 or x<0?
->"üîµ" ; blue orb if so
->"‚ö™" ; white orb if not
] ; end map
] ; end function
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/) with `-lm`, ~~86~~ 85 Unicode characters (~~91~~ 90 bytes)
* -1 thanks to ceilingcat
Converts the value to an integer to avoid floating-point rounding issues. Although `float` would be sufficient for this task, the original specified a `double`, so I used that type instead.
```
b,c;f(double a){for(b=c=fmin(a<0?:a,1)*10;b--;)printf("üîµ");for(;c++<10;)printf("‚ö™");}
```
[Try it online!](https://tio.run/##PYw7DsIwEET7nGJlCcnGceQg0eAYzrJ2cBQpP@VDE@UWVDT09FyIE3ACjFNAMzujtzNWFNZ6b2KrHM3byVRnQDa7tqdGW@3qsqGYydMB45RtU6mMEIp1fdmMjpL3/fokTK3fynKeBf5nr9sjoMWHBDWGmUtb5gzmCMBVLY6AKlp96KIWqQLMdsl6uJaJ3MfQTeNACWGhA7/RDXegj0BiZAocXXWJFv@xrsJi8KKqvw "C (gcc) – Try It Online")
[Answer]
# JavaScript, 68 bytes
Without recursion:
```
(p,i=0)=>'‚ö™'.repeat(10).replace(/‚ö™/g,e=>p>=0&i++>=p*10?e:'üîµ')
```
Try it:
```
f=(p,i=0)=>'‚ö™'.repeat(10).replace(/‚ö™/g,e=>p>=0&i++>=p*10?e:'üîµ')
console.log(f(-2));
console.log(f(0));
console.log(f(1));
console.log(f(2));
console.log(f(0.1));
console.log(f(0.4));
console.log(f(0.68));
console.log(f(0.9));
console.log(f(0.99));
console.log(f(NaN));
```
```
.as-console {
background-color: grey !important;
}
```
## UPD 96 -> 86
Thanks to [mousetail](https://codegolf.stackexchange.com/users/91213/mousetail) for the [tip](https://codegolf.stackexchange.com/questions/256890/shortest-digid-app-getpercentagerounds-function/257060?noredirect=1#comment568580_257060) to reduce bytes count
## UPD 86 -> 70
Thanks to [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen) for the [tip](https://codegolf.stackexchange.com/questions/256890/shortest-digid-app-getpercentagerounds-function/257060?noredirect=1#comment568583_257060) to reduce bytes count
## UPD 70 -> 68
Thanks to [Rydwolf Programs](https://codegolf.stackexchange.com/users/79857/rydwolf-programs) for the [tip](https://codegolf.stackexchange.com/questions/256890/shortest-digid-app-getpercentagerounds-function/257060?noredirect=1#comment568588_257060) to reduce bytes count
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-P`](https://codegolf.meta.stackexchange.com/a/14339/), 22 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
AǨA*U©ÎÌ?9898d:# 309d
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVA&code=QceoQSpVqc7MPzk4OThkOiOAMzA5ZA&input=LTAuMQ)
```
AǨA*U©ÎÌ?9898d:# 309d :Implicit input of float U
A :10
Ç :Map the range [0,A)
¨A*U : Is greater than or equal to A*U
© : Logical AND with
Î : Sign of U
Ì : Sign of difference with -1
? : If true
9898d : Character at codepoint 9898
: : Else
# 309d : Character at codepoint 128309
:Implicitly join and output
```
[Answer]
# [Scala](https://www.scala-lang.org/), ~~81~~ 78 bytes
saved 3 bytes thanks to comment.
[Try it online!](https://tio.run/##K05OzEn8n5@UlZpcouCbmJmnUP0/JTVNIU2jwMolvzQpJ1XTKrikKDMv3VbDQKEkX8FSUy83sUAj09YuE6jGxqCmwC5TS89QU@nD/ClblVJzilOVHs1apQRUlQ3R919BAWRgLtBsjcSi9GIrBceiosTKaIhsrKaVQmheZomCrUI1lwIQFABFS3LyNNI0dA0N9Aw0NYFi@voKqRUFQBempihYKYAsIgajGwc0zZB6xsHchm4c0PN4EKYhON1EiimGWJ1CsilQY7CHD9HGmOJ0DDomZJIl0SZhMRnTNLzeIzH6DXFEP7nGwZMT2cbVctX@BwA)
```
def f(p:Double):String=(0 to 9).map(i=>if(p<0|p>i*.1)"üîµ"else"‚ö™").mkString
```
Ungolfed version
```
object Main {
def f(p: Double): String =
(0 to 9).map(i => if (p < 0 || p > i * 0.1) "üîµ" else "‚ö™").mkString
def main(args: Array[String]): Unit = {
println(f(-10.0)) // expected : üîµüîµüîµüîµüîµüîµüîµüîµüîµüîµ
println(f(-0.01)) // expected : üîµüîµüîµüîµüîµüîµüîµüîµüîµüîµ
println(f(0.0)) // expected : ‚ö™‚ö™‚ö™‚ö™‚ö™‚ö™‚ö™‚ö™‚ö™‚ö™
println(f(0.001)) // expected : üö™‚ö™‚ö™‚ö™‚ö™‚ö™‚ö™‚ö™‚ö™
println(f(0.1)) // expected : üö™‚ö™‚ö™‚ö™‚ö™‚ö™‚ö™‚ö™‚ö™
println(f(0.11)) // expected : üîµüö™‚ö™‚ö™‚ö™‚ö™‚ö™‚ö™‚ö™
println(f(0.5)) // expected : üîµüîµüîµüîµüö™‚ö™‚ö™‚ö™‚ö™
println(f(0.9)) // expected : üîµüîµüîµüîµüîµüîµüîµüîµüö™
println(f(0.91)) // expected : üîµüîµüîµüîµüîµüîµüîµüîµüîµüîµ
println(f(1.0)) // expected : üîµüîµüîµüîµüîµüîµüîµüîµüîµüîµ
println(f(10.0)) // expected : üîµüîµüîµüîµüîµüîµüîµüîµüîµüîµ
}
}
```
[Answer]
# [jq](https://stedolan.github.io/jq/), 32 bytes
```
.*10|["üîµ"*.,"‚ö™"*(10-.)]|add
```
[Try it online!](https://tio.run/##yyr8/19Py9CgJlrpw/wpW5W09HSUHs1apaSlYWigq6cZW5OYkvL/v4Ge@X9d3aLEct380pKC0hIA "jq – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes
```
Ժƌ∏‚≠Üœá¬ß‚ö™üÄπŒπ√óœá‚ஂÄπŒ∏‚Å∞Œ∏
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0QjuARIpfsmFmgYGugoOJZ45qWkVmgoPZq16sP8KVuVdBR8UouLNTJ1FEIyc1OLwYr8izTAgoU6CgaaOgqFmmBg/f@/gZ6Z5X/dshwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ First input as a number
χ Predefined variable 10
⭆ Map over implicit range and join
‚ö™üîµ Literal string `‚ö™üîµ`
§ Indexed by
ι Current value
‹ Is less than
χ Predefined variable 10
√ó Multiplied by
θ Input number
‹ Is less than
⁰ Literal integer `0`
‚à® Logical Or
θ Input number
Implicitly print
```
Although `‚ö™` and `üîµ` are not in Charcoal's code page it can still represent them using special byte sequences which take 3 and 4 bytes respectively as you can see in its `xxd`-style dump: [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0QjuARIpfsmFmgYGugoOJZ45qWkVmgoPZq16sP8KVuVdBR8UouLNTJ1FEIyc1OLwYr8izTAgoU6CgaaOgqFmmBg/f//f92ynAoA "Charcoal ‚Äì Try It Online")
] |
[Question]
[
All the [quine](/questions/tagged/quine "show questions tagged 'quine'") challenges on this site are focused on byte count, or the characters themselves. This one is different. Your challenge is to write a program that produces output which has a code point sum identical to the source's code point sum.
To produce a code point sum:
1. Find the values of the characters in the program's character set.
For example - `FOO` in ASCII: `F` = 70, `O` = 79, `O` = 79
2. Add them all together.
Code point sum of `FOO` in ASCII: `F`+`O`+`O` = 70+79+79 = 228.
An example of an ASCII sum quine would be if the source code was `ABC` and the output was `!!!!!!`. This is because the sum of the the ASCII values of the source (`A` = 65, `B` = 66, `C` = 67, sum = 198) is the same as the sum of the ASCII values in the output (`!` = 33, 33\*6 = 198). `BBB` would also be valid output, as would `cc`.
# Rules
* Your program must not be a reverse, shuffled, error, or any other type of "true" quine. To elaborate: If the output contains all the same characters as the source, it is invalid.
* Your program cannot use any errors/warnings from the compiler/interpreter as the output.
* Your program's source must use the same codepage as the output.
* Your program may use any codepage that was created before this challenge was.
* Your program's output must not contain any unprintable characters (e.g. ASCII 0 through 31, or above 127) aside from linefeeds and tabs.
* Standard loopholes apply.
* If the source and/or output has a trailing linefeed, it must be included in the code point sum.
* Compiler flags need to be included in the final byte count (score), but not the source's code point sum.
* The output/source may not be empty.
# Scoring
Shortest answer in byte count (not code point sum) wins. Please use this header format answers:
```
# Jelly, 12 bytes, sum 56 (SBCS)
```
You can use [this tool](https://tio.run/##fVA9b8IwEN3zK45ISAkBqbQbUQbKhNShEmNbgeVcgqXERraTDlV/u3uHgYqh9WDfx3v3fE8uWilDUNpDL5TOOBC2lXOQR2FhNqNkzJOvBOioBjJuwqSCpxxikc/JEq/J0tcOhUNKzahqBP9pQJq@F7qGTmnkyUOP2jtojIX1brPdght6Bp2EVc7oSZqXt7EW/WA1LJax9J2cH@GkUvtRdAPuf4n8sfFt@XGh/wd6ZBANG42q/wLG7Z23192vK@48Be0KDlN3eNfpnCHlHeIFdeuPK5jWl36HOmMY4aKN5DEJRhYbkVEGFTyUZ8US6CqK/GYDd4sq9pI7qeigNDWeRItsZZRlYWLxmiGE9fMmSPkD) to calculate ASCII sums.
# Reference
Here are some useful codepage references.
* [ASCII table](http://asciitable.com)
* [UTF-8 table](http://www.utf8-chartable.de/)
* [UTF-16 table](http://www.fileformat.info/info/charset/UTF-16/list.htm)
* [EBCDIC table](http://www.astrodigital.org/digital/ebcdic.html)
* [Jelly SBCS table](https://github.com/DennisMitchell/jelly/wiki/Code-page)
* [CP-1252 table](https://en.wikipedia.org/wiki/Windows-1252#Character_set)
* [ISO-8859-1 table](https://en.wikipedia.org/wiki/ISO/IEC_8859-1#Codepage_layout)
```
/* Configuration */
var QUESTION_ID = 135571; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 8478; // This should be the user ID of the challenge author.
/* App */
var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;
function answersUrl(index) {
return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}
function commentUrl(index, answers) {
return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}
function getAnswers() {
jQuery.ajax({
url: answersUrl(answer_page++),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
answers.push.apply(answers, data.items);
answers_hash = [];
answer_ids = [];
data.items.forEach(function(a) {
a.comments = [];
var id = +a.share_link.match(/\d+/);
answer_ids.push(id);
answers_hash[id] = a;
});
if (!data.has_more) more_answers = false;
comment_page = 1;
getComments();
}
});
}
function getComments() {
jQuery.ajax({
url: commentUrl(comment_page++, answer_ids),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(c) {
if (c.owner.user_id === OVERRIDE_USER)
answers_hash[c.post_id].comments.push(c);
});
if (data.has_more) getComments();
else if (more_answers) getAnswers();
else process();
}
});
}
getAnswers();
var SCORE_REG = (function(){
var headerTag = String.raw `h\d`
var score = String.raw `\-?\d+\.?\d*` // with negative/floating-point support
var normalText = String.raw `[^\n<>]*` // no HTML tag, no newline
var strikethrough = String.raw `<s>${normalText}</s>|<strike>${normalText}</strike>|<del>${normalText}</del>`
var noDigitText = String.raw `[^\n\d<>]*`
var htmlTag = String.raw `<[^\n<>]+>`
return new RegExp(
String.raw `<${headerTag}>`+
String.raw `\s*([^\n,]*[^\s,]),.*?`+
String.raw `(${score})`+
String.raw `(?=`+
String.raw `${noDigitText}`+
String.raw `(?:(?:${strikethrough}|${htmlTag})${noDigitText})*`+
String.raw `</${headerTag}>`+
String.raw `)`
);
})();
var OVERRIDE_REG = /^Override\s*header:\s*/i;
function getAuthorName(a) {
return a.owner.display_name;
}
function process() {
var valid = [];
answers.forEach(function(a) {
var body = a.body;
a.comments.forEach(function(c) {
if(OVERRIDE_REG.test(c.body))
body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
});
var match = body.match(SCORE_REG);
if (match)
valid.push({
user: getAuthorName(a),
size: +match[2],
language: match[1],
link: a.share_link,
});
});
valid.sort(function (a, b) {
var aB = a.size,
bB = b.size;
return aB - bB
});
var languages = {};
var place = 1;
var lastSize = null;
var lastPlace = 1;
valid.forEach(function (a) {
if (a.size != lastSize)
lastPlace = place;
lastSize = a.size;
++place;
var answer = jQuery("#answer-template").html();
answer = answer.replace("{{PLACE}}", lastPlace + ".")
.replace("{{NAME}}", a.user)
.replace("{{LANGUAGE}}", a.language)
.replace("{{SIZE}}", a.size)
.replace("{{LINK}}", a.link);
answer = jQuery(answer);
jQuery("#answers").append(answer);
var lang = a.language;
lang = jQuery('<i>' + a.language + '</i>').text().toLowerCase();
languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link, uniq: lang};
});
var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);
langs.sort(function (a, b) {
if (a.uniq > b.uniq) return 1;
if (a.uniq < b.uniq) return -1;
return 0;
});
for (var i = 0; i < langs.length; ++i)
{
var language = jQuery("#language-template").html();
var lang = langs[i];
language = language.replace("{{LANGUAGE}}", lang.lang)
.replace("{{NAME}}", lang.user)
.replace("{{SIZE}}", lang.size)
.replace("{{LINK}}", lang.link);
language = jQuery(language);
jQuery("#languages").append(language);
}
}
```
```
body { text-align: left !important}
#answer-list {
padding: 10px;
float: left;
}
#language-list {
padding: 10px;
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="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654">
<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>
<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><a href="{{LINK}}">{{SIZE}}</a></td></tr>
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
<tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr>
</tbody>
</table>
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 1 byte, sum = 58 (ASCII)
```
:
```
This counts the matches of `:` in the input (**0**), so it prints
```
0
```
The code points of `:`, `0`, and LF (linefeed) are **58**, **48**, and **10** (respectively), and **58 = 48 + 10**.
[Try it online!](https://tio.run/##K0otycxL/P/f6v9/AA "Retina – Try It Online")
[Answer]
# ArnoldC, 316 bytes, sum 20992 (ASCII)
Fun enough.
```
IT'S SHOWTIME
HEY CHRISTMAS TREE s
YOU SET US UP 1
HEY CHRISTMAS TREE iaV
YOU SET US UP 0
STICK AROUND s
GET TO THE CHOPPER iaV
HERE IS MY INVITATION iaV
GET UP 8
ENOUGH TALK
TALK TO THE HAND "H"
GET TO THE CHOPPER s
HERE IS MY INVITATION 2048
LET OFF SOME STEAM BENNET iaV
ENOUGH TALK
CHILL
YOU HAVE BEEN TERMINATED
```
I used [this](https://tio.run/##dZBRa8IwEMefl09x9GWWwXBjDyJ0kOlpgk0izdXhY6fdcGhXbDYE8bN3Z2EwhnvJkdzv/ztyzarYFu3Hy3u5CmCKTQXlIZTVugFZ10dxtS5fgZFVLwx92G@qt3ioq5Ac269iD83nLumLcLsr6t4heeTrTXKIBdf2JETNeNhWvS4eRZGmaw9euWfSBoXCJYxUpj0Z6YEyRGjE0uXgkSD3kM/h7hK0KRZ/sL7wpEczkJnL7ZgtU26RA1LIYTefY9alFGYI2oNZgrYLTZK0s13nHGDRQKB1@VQByXQmzsePRkkWRyq6pG7@Ed/3HwYiZd5NJuCdQfCE0sATWsuv57m/x42UTtPuZ0oukCm0QJgZbSXhmNcXx@LUfgM) and [this](https://tio.run/##K05OzEn8n5@UlZpcouCbmJmnkFpRkpqXUqzgWFBQzcWZkpqmAFSSrFFiFVxSlJmXrmnlmVdiW/2/LLFIobg019aAq0QvN7FAo8LWDsjVtq3Q5ALS/2u5uAqAykty8jTA2pWUlDy4RuFIhsAkoKnJVfsfAA) to do my calculations. Took me an hour and a half. But fun.
[Try It Online!](https://tio.run/##dY8xa8NADIX3@xWPLF3T0iHr1VEiEd/JnHQuHkO7FEIKzf/HPRsKpaSLBr3vfULnr@vn5f1tnsUfDMb66pIoME3ouIh5igYvRLiFSSuMHNVQBzzegz7O4x9sG8ylOyEWrXnfLMcWucKZWlmHgcraYioEMaQJkkfx6KJ5TZZCE@0CZa1Hhsf@FJbxo@HYxBve3FPf/hE/bZ93oW@8Hg4wTQRzigkvlHPbLnd/n@tY@n79jONIjaIMp5IkR6f9PH8D)
**How it works**
`STICK AROUND` is a loop, that loops `2048` times on the index `iaV`, but this index steps by `8`. So there is `256` loops, printing `H` and a linefeed (72+10 = 82, 82\*256 = 20992).
This is still *HIGHLY* golfable (by finding other calcs) but it is long and boring to measure your byte sum every time you do a modification.
Please tell me if I'm mistaken anywhere.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 1 byte, sum = 180 ([Charcoal SBCS](https://github.com/somebody1234/Charcoal/wiki/Code-page))
```
⁴
```
[Try it online!](https://tio.run/##S85ILErOT8z5//9R45b//wE "Charcoal – Try It Online") In Charcoal's code page, `⁴` has a code of `0xB4 = 180`, while the output is 4 `-`s which is `4 * 45 = 180`.
[Answer]
# Python 2, 11 bytes, sum 838 (ASCII)
```
print 76**8
```
prints
```
1113034787454976
```
Not very clever but it works
[Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EwdxMS8vi/38A "Python 2 – Try It Online")
[Answer]
# Jelly, 12 bytes, sum 948 (SBCS)
You said:
>
> Jelly, 12 bytes
>
>
>
then it's Jelly, 12 bytes.
```
\
³³³,:D+++
```
Was fun, since I don't know Jelly at all.
**How it works**
I don't have any idea.
But `³` does put 100 in the stack, `,` puts the stack in an array or something, `:` might concatenate the thing while `D` lists every letter of the last numeral (which does not exist), and +++ are for fun. The first and last line does not affect the output :)
[Try it Online!](https://tio.run/##y0rNyan8/z@G69BmENSxctHW1ub6/x8A)
Used [this](https://tio.run/##K05OzEn8n5@UlZpcouCbmJmnkFpRkpqXUqzgWFBQzcWZkpqmAFSSrFFiFVxSlJmXrmnlmVdiW/2/LLFIobg019aAq0QvN7FAo8LWDsjVtq3Q5ALS/2u5uAqAykty8jTA2pWUlGK4Dm0GQR0rF21tbS6giKYmhqJoEwMDHYXMvDQdBWMDg1iIotr/AA) to count.
[Answer]
# CJam/Japt/bc, 2 bytes, sum 97 (ASCII)
`A`
[Try it Online](http://cjam.aditsu.net/#code=A%20) (CJam), [Try it Online](http://ethproductions.github.io/japt/?v=1.4.5&code=QSA=&input=) (Japt) (thanks @shaggy),
The bc version works on command line, but not TIO.
Outputs `10`
Source: `A` + `Space` = 65 + 32 = 97
Output: `1` + `0` = 49 + 48 = 97
[Answer]
# [Haskell](https://www.haskell.org/), 9 bytes, byte sum 743 (ASCII)
Code:
```
show$29^9
```
Output:
```
14507145975869
```
[Try it online!](https://tio.run/##y0gszk7NyflfaBvzvzgjv1zFyDLO8n9uYmaegq1CQWlJcEmRQuH/f8lpOYnpxf91I5wDAgA "Haskell – Try It Online")
[Answer]
# [Cubically](https://git.io/cubically), 4 bytes, sum 141 (ASCII)
```
%44E
```
Outputs `3636`. [Try it online!](https://tio.run/##Sy5NykxOzMmp/P9f1cTE9f9/AA) And here's the [ASCII sum checker](https://tio.run/##fVA9a8MwEN39Ky4Ggx0n0DQhQ4yHUjoEOhQytiURsuwIbMlIsjuU/nb1LkpSMqQapPt4757u8XnDufdSOeiYVCkFzDR8BvzIDEynmIxZ9B0BHllDSk2YlLDMIBTp9AZ5dRq/tYJZgakeZSXAfWnguuuYqqCVStDkoRPKWai1gafd83YLdugI1DMjrVaTOCuuY41wg1EwX4TST3R6mOVS7kfWDmL/R6SPje@LzzP9P9AjgXDYqGV1Dxi2t85cdr@suHMYNBs4JPbwoeIZQYobxKtQjTtuIKnO/VaolGCICzaixygYWGREihmU8FCcFAvAK8@zqw3UzcvQi26kgoNcV6JnjSArgywJI4vW9N4nq9WLX66X618) I used.
Explanation:
* `%` means 'print face sum as integer'.
* `4` prints the sum of all values on the BACK face (36) twice.
* `E` is a no-op, just used to get the required sum.
[Answer]
*Some of these answers contain characters that will likely be invisible to you (particularly ASCII 17), click the TIO links to see their placement.*
# [Klein](https://github.com/Wheatwizard/Klein) 100/110, 4 bytes, sum 147
```
1
@
```
[Try it online!](https://tio.run/##y85Jzcz7/9@Qy0HwP5AyMAAA "Klein – Try It Online")
Output:
```
1 1
```
# [Klein](https://github.com/Wheatwizard/Klein) 201, 4 bytes, sum 147
```
1
@
```
[Try it online!](https://tio.run/##y85Jzcz7/1/QkMvh////RgaGAA "Klein – Try It Online")
Output:
```
1 1
```
# [Klein](https://github.com/Wheatwizard/Klein) (any topology), 5 bytes, sum 221 (ASCII)
```
111@
```
[Try it online!](https://tio.run/##y85Jzcz7/9/Q0NCB6////wYGBgA "Klein – Try It Online")
This prints
```
1 1 1
```
[Answer]
# Java 7, ~~88~~ 85 bytes, sum ~~7808~~ ~~7617~~ 7507 (ASCII)
```
class
w{public
static
void
main(String[]H){for(int
B=0;B<77;)System.out.print(B++);}}
```
Almost certainly golfable. It's pretty easy to tweak since we have some spare variables like the name of the class and the name of the program arguments parameter that we can change freely.
[Test it online!](https://tio.run/##fVJNT@MwEL3nVwyVkBIKyN9OyPaw3csi7WGlHlkEXscNlvJRxU7RqupvD3YDrDiAD7HH82bevBfrq1rrabKdh1bZLo0HNdT6EvSTGuDiIgT7LDkkEJbdQhqTcLYCmsF8GdduCHXbdPG7McqZEPZ7Wxnwzz3ovm1VV0FjOxM7j63pvINtP8D3zY/bW3BjG0E7NVjXd2eLrHxvOxg/Dh1c4fnqmJw25bS1D3vVjObhf2EcbH@H71/LvwKRCArN9r2tPgPO6p0f3rS/Sdz4cKhv4PHcPf7pFpcRUn5A/DJd7Z9u4Lx6zTemSyMs4GYbg8eBcK6KRqQhghWg8sRYQvgsl9m7DTG7XM255APV7KDuK7NTtYlWzrSROFRFmdM06UY5lzwfduPfxurEeeXDFtUnp38@S7q7/5kdwjTxCSTrFSrX36Qss80/50173Y/@@sSarsNo5fE4IUwo40LmBUYYY4IpZphjgSXOcUEQwYQQShjhRBBJclJQRDEllFJGORVU0pwWDDHMCKOMMc4EkyxnBUccc8IpZ5xzwSXPeSGQwIIIKpjgQggpclFIJLEkkkomuRQv "C (gcc) – Try It Online")
[Try it online!](https://tio.run/##Dcq7DkAwFADQvV/SRojNUJZOdqMYLkWuR9voRaTx7WU6y1nggtS60Sx6jXHYwHt2B3f2Gw7ME9DPZVGzHdDwhg40c9vVIkz24GiIqSqXqiwKKZrH07hn9qTM/Y24ShIh3zfGDw "Java (OpenJDK 8) – Try It Online")
---
# Java 8, 84 bytes, sum 7434
Credit goes to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen).
```
interface A{static void main(String[]G){for(int A=59;A-->0;)System.out.print("~");}}
```
[Test it online!](https://tio.run/##nVFNa8JAEL3nV0wDQqJGtKWHGlIIPRShh4JHK7psJnEh2ZXdTUoR/evpfqjFQ3voHJKdnTfz9r2hSUVp3zOuoSGMR/ZAZEXHQHdEwnBoki4ODgGYYCVEtgh3GTzE4C9t7KXpK6PwvUai0KSiYwWC/hRARdMQXkDNONrJbYNcKyiFhHz5sliAahsL2hPJlOB3YZxex0rUreSQzPzVMXA/oihjm47ULW5@Gu3DutVsfW7/C3RvQWZYJ1jxG9CrV1petF8kLrU5VHPYDtT2g4djC0lvEG/IK72bw6A412vkkYUZnLfReGwIfZc1IjIZZDBNHWMK5jMaxVcbbHWU@VpwQ@UdpKLAPanQWulpLbHpsjJ7t1yUJaEI@UFpohkFJ90t3OtZrV/jg3mK23@ePT6leZI8T9N4@aU0NhPR6okjjcKT2dDx2J/@H98 "C (gcc) – Try It Online")
[Try it online!](https://tio.run/##y0osS9TNL0jNy0rJ/v8/M68ktSgtMTlVwbG6uCSxJDNZoSw/M0UhNzEzTyO4pCgzLz061l2zOi2/SAOoVsHR1tTS2lFX187AWjO4srgkNVcvv7RErwCosERDqU5J07q29v9/AA "Java (OpenJDK 8) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 11 bytes, byte sum 854 (ASCII)
Code (with trailing newline):
```
print'z'*7
```
Output (with trailing newline):
```
zzzzzzz
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EvUpdy5zr/38A "Python 2 – Try It Online")
[Answer]
# [brainfuck](https://github.com/TryItOnline/tio-transpilers), 3 bytes - byte sum 255 (ISO-8859-1)
```
-.¤
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fV@/Qkv//AQ "brainfuck – Try It Online")
Requires 8-bit cells. Prints the character `ÿ`, which is value 255. `¤` is a no-op to fill the sum.
[Answer]
# [V](https://github.com/DJMcMayhem/V), 2 bytes, Sum 255 (Latin1)
```
á
```
[Try it online!](https://tio.run/##K/v/X@7wwv//AQ "V – Try It Online")
Hexdump:
```
00000000: 1ee1 ..
```
The first character is `ctrl-^`, or LATIN1/ASCII code-point `0x1E`. The second character is `alt-a`, or the LATIN1 character `0xE1`. This program outputs `ÿ`, which is `0xFF` in LATIN1.
How does it work?
The first character is a no-op. It has no effect on the program at all. The second character is the *append single character* command. But we don't specify what character to append. So, due to [implicit endings](https://codegolf.stackexchange.com/a/124600/31716), it appends the character that V uses to signal the program is over, which just so happens to be `0xFF`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes, sum 256 (05AB1E Base-255 Translation)
```
ΔTnon
```
[Try it online!](https://tio.run/##MzBNTDJM/a/0/9yUkLz8vP9Kh7Z5H1qpF6Z0eL@Si865rUampoe31bro@OscWofK/w8A "05AB1E – Try It Online")
---
This outputs:
`1606938044258990275541962092341162602522202993782792835301376`
Which, using 05AB1E's code-page results in:
`[1, 6, 0, 6, 9, 3, 8, 0, 4, 4, 2, 5, 8, 9, 9, 0, 2, 7, 5, 5, 4, 1, 9, 6, 2, 0, 9, 2, 3, 4, 1, 1, 6, 2, 6, 0, 2, 5, 2, 2, 2, 0, 2, 9, 9, 3, 7, 8, 2, 7, 9, 2, 8, 3, 5, 3, 0, 1, 3, 7, 6]`
Which is:
`256`
---
Where the code is:
`ΔTnon`
With code-points:
`[79, 29, 49, 50, 49]`
Which is:
`256`
[Answer]
# [Taxi](https://bigzaphod.github.io/Taxi/), 543 bytes, sum 47124 (ASCII)
```
374 is waiting at Starchild Numerology.Go to Starchild Numerology:w 1 l 2 r 1 l 1 l 2 l.Pickup a passenger going to The Underground.'~' is waiting at Writer's Depot.Go to Writer's Depot:w 1 r 1 l 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:n.[a]Pickup a passenger going to Cyclone.Pickup a passenger going to Post Office.Go to Zoom Zoom:n.Go to Post Office:w 3 l 2 r 1 l.Go to The Underground:n 1 r 1 l.Switch to plan "R" if no one is waiting.Pickup a passenger going to The Underground.Go to Cyclone:n 3 l 2 l.Switch to plan "a".[R]
```
[Try it online!](https://tio.run/##lZBfS8MwFMW/yqEvfQvoBKGvCr7p2BTBsYeQpullWW5JUupe/Oq161KcVYa@5M@9N@d3cqJ8p75f3N6AAjpJkZyBjFhH6VVNtsRju9eeLZuDeGBE/rVVdLiCxTX8uJ/OVixJ7doGEo0MQTujPQwfCYPMc63x4krtjefWlSL/yGceXj1F7fOAe91wTPTvxZE7Mf1F3t1BWXY6yaRb4cRGbv/y7NLMkkPEU1WRmuTfmPfjMgBOlbOZwfTiK6zUn8VRuOljYt1RVPVxprHSIVtloAqOMdg6S@xfYc9CSH5@smQmNqtt338C) ([Score verification](https://tio.run/##7VNRa9swEH7Pr7gaSpymNUszGDjkoXQwCmMLTctgWWiFLNuiss5IskMp61/3JMtum2wL7dNedg@S7u67@@4@Y3qSUdo0XBooCJehexCV0WOgOVFwdGSdejR4GIA1nkLoknAwh@kIfNBZqWxdGgYLwYhm1sWaJwzMBoFiURCZgOCSuc5VwaTRkKKCs@X5xQXoqnCgkiiuUR4Eo9lTW8VMpSScTHzo56C9iKac39REVOzmudANVq8m6658H@jUgWyzGnnyN6DfXhvV796vuDT2kcVwe6hvf8jg2EFmW4jPTGYmj@Ew6fKCydDBLM7LaDW2hL7KCRFaD@bwbtYyzsAe4/HoSQaXHc99brBF5RWkmLCSZMxJ6Wkdsa1yazZNM/3wHriGDeHGjg7EwNIQRXMuEvhiv4dCgdl99AnB4B9T8QYmIOAUVHv7t4gWnN5VJRAoidZ2aaYgQ8dg21zlDK5lwlSmsJJJNHwc7szwTXHD1FDDR1ai6di3gy1vz6n28p3fU4GSdW06L5bRiqxfU7YPs0Bt4Guactq3/45YtIcl8JEXGDv09FmsLr8jRyz7xaLlhhuaO0wpiITgMnC/mUSwY71Q7E1i74jQzfM7Fwmi1eW6efxv/8B@AQ))
The output is 374 tildes `~`.
[Answer]
# Mathematica, 2 bytes, sum=101 (ASCII)
E + Space returns e
```
E
```
# Mathematica, 2 bytes, sum=105 (ASCII)
it works for I, too
I + Space returns i
```
I
```
[Answer]
# [Factor](https://factorcode.org/), 7 bytes, sum 250
```
7/2 .
```
[Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQnVqUl5qjUFCUWlJSWVCUmVeiUJxaWJqal5xarGD931zfSEGPi@u/EpgRkxeTp6RQXJoLFFMy1jbUN4Lz/wMA "Factor – Try It Online")
Outputs `3+1/2` and a newline.
Factor has a rational number type. When an improper fraction (numerator > denominator) is printed, it is converted to a mixed fraction form (integer part + proper fraction part).
Since the easiest way to adjust the byte value sum is to add spaces or newlines (which are the only token separators in Factor), I tried various fractions until the code's sum is higher than the output's sum by a multiple of 10, and added a couple newlines at the end.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes, sum = 152 (ASCII)
```
58+
```
[Try it online!](https://tio.run/##y0rNyan8/9/UQvv/fwA "Jelly – Try It Online")
[Answer]
# [Brain-Flak (Rain-Flak)](https://github.com/DJMcMayhem/Brain-Flak), 79 bytes
```
(((((((((((((((((((((((((((((((((()()()()){}){})))))))))))))))))))))))))))))))
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/X4Mg0IRAzepaEMIPuP7/BwA "Brain-Flak – Try It Online")
This prints `16` and a newline 31 times.
# [Brain-Flak (BrainHack)](https://github.com/Flakheads/BrainHack), 55 bytes
```
(((((((((((((((((((((()()()()){}){})))))))))))))))))))#
```
[Try it online!](https://tio.run/##SypKzMzLSEzO/v9fAyvQhEDN6loQwgTK//8DAA "Brain-Flak (BrainHack) – Try It Online")
This prints `16` and a space 18 times.
# Also 55 bytes
```
((((((((((((((((((((((()()()){}){}))))))))))))))))))))
```
[Try it online!](https://tio.run/##SypKzMzLSEzO/v9fAzvQBEHN6loQwgIY//8HAA "Brain-Flak (BrainHack) – Try It Online")
This prints `12` followed by a space 19 times.
[Answer]
# [Vim](http://www.vim.org/), 3 bytes, sum 234 (ASCII)
```
3iN
```
Output:
```
NNN
```
[Try it online!](https://tio.run/##K/v/3zjT7/9/AA "V – Try It Online")
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), 20 bytes, code point sum 1505
```
OuOOQ++OOOOU@>!OOO<
```
Contains the unprintable character `DEL` (ascii 127).
`Q` pushes `"` (the largest constant available in cubix), then repeatedly prints out (`O`) `68` or `102` enough times to get it to `68686868686868102102102102102` which is 1505; through some trial and error I realized that I needed 81 more points than `.` (a Cubix no-op and ASCII `46`) which resulted in needing `DEL`, which is still a no-op in Cubix.
[Try it online!](https://tio.run/##Sy5Nyqz4/9@/1N8/UFvbHwhCHewUgVS9zf//AA "Cubix – Try It Online")
On a cube:
```
O u
O O
Q + + O O O O U
@ > ! O O O <
. .
. .
```
[Answer]
# dc, 7 bytes, sum 720 (ASCII)
```
[my]fff
```
(91+109+121+93+(102\*3)=720)
Outputs:
```
my
my
my
```
((109+121+10)\*3=720)
[Answer]
# [Carrot](https://github.com/kritixilithos/Carrot/), 4 bytes, sum = 279 (ASCII)
```
]^*2
```
[Try it online!](http://kritixilithos.github.io/Carrot/)
Prints `]]]`.
[Answer]
# [Cubically](https://github.com/aaronryank/cubically), 3 bytes, sum = 105 (ASCII)
```
%4
```
The third byte is **DLE**, which has code point **16**, so the code point sum of the source code is
**37 + 52 + 16 = 105**.
The program prints
```
36
```
whose code point sum is **51 + 54 = 105**.
[Try it online!](https://tio.run/##Sy5NykxOzMmp/P9f1UTg/38A "Cubically – Try It Online")
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), 11 bytes, byte sum 954 (ASCII)
Code:
```
vOw~N(!@O^|
```
Output:
```
998877665544332211
```
[Verified here!](https://tio.run/##fVDJbsIwEL3nKwYkpISA1LBDFKlVT0hVqcSxC1iOEywlNrKdcOjy68GDgYpD64M9y3vzPI/2c0qbhgsDJeHCx4ConPaA7oiCbtcmdeB9emAPz8DHJrQSGAbginj2yvIyv/1SMKKZTWXNUwbmIIHKsiQihYILhpOrkgmjIZMKHtaPyyXoqkTQniiupWi1g/g6VjFTKQH9yJW@vdNDNOV8U5OiYptfIn6sfo3ez/T/QAME2WG15OlfQLe9Nuqy@2XFtbFBvoBtR2/fRLuHkPgG8cREbnYL6KTnfsGEjzCLczZaj62gY6ERvs0ggbv4pBiDvcIwuNqA3TBxPe9GyjlIZcr2JGdopZNFYcvCNZummc9ns@l0MhmPR6PhcDCIoqZeHX6e/db96uPrCA "C (gcc) – Try It Online")
[Try it online!](https://tio.run/##Sy5Nyqz4/7/Mv7zOT0PRwT@u5v9/AA "Cubix – Try It Online")
Cubified:
```
v O
w ~
N ( ! @ O ^ | .
. . . . . . . .
. .
. .
```
* `N` initializes the stack with 10
* `(!` decrement and test for truthy
+ `@` on zero halt
* `O^O` output current number redirect to top face and output again
* `vw` redirect back to the `(` decrement to begin the loop again
[Watch it run](https://ethproductions.github.io/cubix/?code=ICAgIHYgTwogICAgdyB+Ck4gKCAhIEAgTyBeIHwgLgouIC4gLiAuIC4gLiAuIC4KICAgIC4gLgogICAgLiAuCg==&input=&speed=20)
[Answer]
# [INTERCAL](http://www.catb.org/~esr/intercal/), ~~47~~ ~~46~~ 45 bytes, sum = 2945 (ASCII...?)
```
PLEASE,8<-#38DO,8SUB#8<-#6DOREADOUT,8DOGIVEUP
```
[Try it online!](https://tio.run/##y8wrSS1KTsz5/z/Ax9Ux2FXHwkZX2djCxV/HIjjUSRnEM3PxD3J1dPEPDdEBirt7hrmGBvz/DwA "INTERCAL – Try It Online")
Prints seven null bytes followed by thirty-one underscores. One of six possibilities generated by a somewhat revised [awful hacky Python script](https://tio.run/##fZBNa4NAEIbP8VcMeNgdo6BpU4rEQ4pSCoWEpvYiHrRqXdisy2okRfLbrYZIUwgd5rDM8@47H/K7KStx1/d6U7IahjTKSimW8tzQsryAgjNJj@hqsxQ8SJmgi@WDdcRo4caR61pOPJK5B8QmBn20eC5oiqjNVN4clIC8TTgldkrmKWpaUSngwASoRHzl1LHtwRmGGEH7C4YeFzDB5OqX6dhXdFLUoyIixCRA4r94krB/TaaQw6IF2b4G613Q1SezS04rS@/4yd@M7134pHfsXGqH0luw9jfh@0j8zfPLRxBuyU1bVgDlFmWWg2icz9oieB7Uhz3dJ5JWKjMlIiQig/GKEmHlwf3y9pDnQRUTDZXmRW7CZ6noxRmx738A).
[Answer]
# [Labyrinth](https://github.com/m-ender/labyrinth), 6 bytes, sum 271 (ASCII)
```
92
9!@
```
[Try it online!](https://tio.run/##y0lMqizKzCvJ@P/f0ojLUtHh//9/@QUlmfl5xf91UwA "Labyrinth – Try It Online")
Outputs `92299` (the number 92, then the number 299, without separators).
I experimented with small layouts that print some digits in the code twice until I got
```
99
9!@
```
whose output's ASCII sum is 7 higher than code's. Decreasing a digit on the top row by one decreases two digits in the output, which leads to the solution above.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 4 bytes, sum 334 ([Husk SBCS](https://github.com/barbuz/Husk/wiki/Codepage))
```
up63
```
Output:
```
[3,7]
```
The value of a digit is given by `0x3?` (where `?` stands for that digit) and `u`,`p`,`[`,`]`,`,` have values `0x75`,`0x70`,`0x5b`,`0x5d`,`0x2c` - thus the sums are:
```
0x75 + 0x70 + 0x36 + 0x33 = 0x14e
0x5b + 0x33 + 0x2c + 0x37 + 0x5d = 0x14e
```
[Try it online!](https://tio.run/##yygtzv7/v7TAzPj/fwA "Husk – Try It Online")
[Answer]
## JavaScript (ES6), 6 bytes, sum = 385 (ASCII)
```
Y=>1E7
```
Outputs `10000000`. There are other 6 byte answers such as `h=>1e8`. Try this code point counter:
```
<input oninput=o.textContent=[...this.value].reduce(function(s,c){return(s+c.charCodeAt())},0)><pre id=o>0
```
[Answer]
# [cQuents](https://github.com/stestoltz/cQuents), 5 bytes, sum 238 (ASCII)
```
#3::$
```
Outputs `1,2,3`, or in cQuents terms, prints the first three terms of the sequence `1,2,3,4,5,6...`.
Now listen. This was, literally, the first program I tried. The reason I tried it was because this was the program I used for [Output with the same length as code](https://codegolf.stackexchange.com/a/131540/65836). And it freaking worked.
[Try it online!](https://tio.run/##Sy4sTc0rKf7/X9nYykrl/38A "cQuents – Try It Online")
] |
[Question]
[
Your task is simple, just remove the odd indices and double the even indices
## Example
the input is `Hello, World!` and we get indices
```
H e l l o , _ W o r l d !
1 2 3 4 5 6 7 8 9 10 11 12 13
```
and remove the odd indices
```
el,Wrd
```
Double!
```
eell,,WWrrdd
```
and you are done
1-Indexing
## Test cases
```
abcdef => bbddff
umbrella => mmrrllaa
looooooooong text => ooooooooooggttxx
abc => bb
xkcd => kkdd
Hello, World! => eell,,WWrrdd
D => <empty>
KK => KK
Hi => ii
odd_length! => dd__eegghh
<empty> => <empty>
```
The input can be list if you want.
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 8 bytes
```
,,[..,,]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fRydaT09HJ/b///yUlPic1Lz0kgxFAA "brainfuck – Try It Online")
[Answer]
# [convey](http://xn--wxa.land/convey/), 8 bytes
*-1 thanks to Wheat Wizard!*
```
v2{
0"!}
```
[Try it online!](https://xn--wxa.land/convey/run.html#eyJjIjoidjJ7XG4wXCIhfSIsInYiOjEsImkiOiInSGVsbG8sIFdvcmxkIScifQ==)
[](https://i.stack.imgur.com/px7Oo.gif)
The 0 and 2 loop around, applying themselves to the input via `!` (take), thus duping the element 0 or 2 times.
[Answer]
# [J](http://jsoftware.com/), 8 bytes
```
#~0 2$~#
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/lesMFIxU6pT/a3KlJmfkK6QpqHuk5uTk6yiE5xflpCiqw4UrspNT1P8DAA "J – Try It Online")
* `0 2$~#` Repeat the pattern `0 2` for the length of the string:
```
Hello, World
020202020202
```
* `#~` Use that mask to "copy" the characters: zeros get deleted, twos get doubled:
```
eell,,WWrrdd
```
[Answer]
# [R](https://www.r-project.org/), ~~35~~ ~~34~~ 32 bytes
*Edit: -1 byte thanks to Giuseppe*
```
function(x)rep(x,`[<-`(x,0:1*2))
```
[Try it online!](https://tio.run/##jc@9TsMwFAXgPU9hymJXqQRMCLWdGKiyFmVgSJPca8eKfyrrBpmnD2YAV0z2YulY35FPWAPazgN0MJgOP91hlYsbSXvHowh45bG@fOx3l3Q/vDxun4RYtaOzfyf5zP9ZvqTw7E@O@KYfRkC5EUKwe3Y4smEAkLIqsosdAhrTZ21tCCnoy7zxv8cpRhgpF/29eKWIYqxKx9wuKUNxHiGreQYoc29puq9Z64OBu1yAKa7rtg2htOg14z3aK30dy1zTZNg0hZ/W2WhdZn5ig07RdDMzZR2iUtNUrd8 "R – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 3 bytes
```
y2•
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJ5MuKAoiIsIiIsInVtYnJlbGxhIl0=)
Vyxal has a better built-in for this than Jelly.
```
y2• Full Program
y Uninterleave; push a[::2] and a[1::2]
2• Repeat each character twice
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 4 bytes
```
Ḋm2Ḥ
```
[Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCLhuIptMuG4pCIsIiIsIiIsWyJ1bWJyZWxsYSJdXQ==)
```
Ḋm2Ḥ Main Link
Ḋ Remove the first character
m2 Return every other character
Ḥ Double. This turns ["a", "b"] into ["aa", "bb"], which
is not the correct format for a Jelly string, but displays
correctly when printed.
```
[Answer]
# [Python](https://www.python.org), 37 bytes
```
lambda a:"".join(x*2for x in a[1::2])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3VXMSc5NSEhUSrZSU9LLyM_M0KrSM0vKLFCoUMvMUEqMNrayMYjWhinUKijLzSjTSNJRKc5OKUnNyEpU0NbnggvkpKfE5qXnpJRmKQHGIngULIDQA)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 bytes
```
Ṙ2Ċ2t
```
[Try it online!](https://tio.run/##yygtzv7//@HOGUZHuoxK/v//75Gak5OvoxCeX5SToggA "Husk – Try It Online")
### Explanation
```
Ṙ2Ċ2t
t drop first char
Ċ2 take every 2-nd char
Ṙ2 repeat each char 2 times
```
[Answer]
# [ayr](https://github.com/ZippyMagician/ayr), ~~9~~ 8 bytes
Using Jonah's J method gets me -1 byte
```
]#0 2$`#
```
I have the advantage of `#`'s args being swapped compared to J, but unfortunately monadic 2-trains are not hooks like in J.
Old answer:
```
:,_2]/,@:
```
[Try it!](https://zippymagician.github.io/ayr#Zjo@/XSMwIDIkYCM@/PWYiICdIZWxsbywgV29ybGQhJyAnYWJjZGVmJyAndW1icmVsbGEn//)
# Explained
`:` is partial application (K-style train)
```
,@: Zip-self with concatenation
_2]/ Split into groups of two, take right element
, Flatten
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 29 bytes
```
x=>x.replace(/.(.?)/g,'$1$1')
```
[Try it online!](https://tio.run/##PYzNTsQgFEb3PEVNJikY7Ni1tm6MmaRLF102FC4US6FSxjAxPnuF8YfN/e75uOeNfbCNe72GO@sE7LLZY9PGysNqGAd8rHD1RI6Klof6UJdkf0Ae3s/aAy7lVpL0kYkXbeD1Yjm@p6VhQdv6WvwacHVLiqYt8kwiPFBGR9K0n9zZzRmojFM4ISoxI@SL7GzkAmQ@GUchpETnZfRgDMtoWbxPkSHj/p5VRYAYcvvPnFIhxIiS60eE4sxFjvMsBDolnaNF77wRN5lCApT2vfepfc7kEZY1XFrUdXnrOnTSOWiNnBCDAavCdD1N2wCg1DR9Aw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Factor](https://factorcode.org/) + `sequences.repeating`, 19 bytes
```
[ <odds> 2 repeat ]
```
Get the odd-indexed elements then repeat them twice.
[](https://i.stack.imgur.com/jVlhQ.gif)
[Answer]
# Excel, 46 bytes
```
=CONCAT(REPT(MID(A1,SEQUENCE(2^15,,2,2),1),2))
```
Input is in cell `A1`. Output is wherever the formula is.
Working from the inside out:
* `SEQUENCE(2^15,,2,2)` creates an array of even numbers from 2 to 32,768. This is the [limit](https://support.microsoft.com/en-us/office/excel-specifications-and-limits-1672b34d-7043-467e-8e27-269d656771c3) for how many characters can be in a cell so it's the limit of the input.
* `MID(A1,SEQUENCE(~),1)` pulls out all the even-index characters one at a time.
* `REPT(MID(~),2)` doubles all those characters.
* `CONCAT(REPT(~))` combines them all into a single string.
[](https://i.stack.imgur.com/oWHG9.png)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ιθºS
```
I/O as a list of characters.
[Try it online](https://tio.run/##yy9OTMpM/f//3M5zOw7tCv7/P1rJQ0lHKRWIc6A4H4hBUAGIw6H8IqhcChArKsUCAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn1l8P9zO8/tOLQr@L@Xzv/EpOSU1DSu0tykotScnESunHwYyEtXKEmtKOECquCqyE5O4fIAKsjXUQjPL8pJUeRy4fL25vLI5MpPSYnPSc1LL8lQBAA).
**Explanation:**
```
ι # Uninterleave the (implicit) input-list into two parts
# e.g. ["a","b","c","d","e","f"] → [["a","c","e"],["b","d","f"]]
θ # Only leave the last/second part
# → ["b","d","f"]
º # Mirror/double each character
# → ["bb","dd","ff"]
S # Convert the list of strings to a flattened list of characters
# → ["b","b","d","d","f","f"]
# (after which it is output implicitly as result)
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 10 bytes
```
.(.?)
$1$1
```
[Try it online!](https://tio.run/##K0otycxL/P9fT0PPXpNLxVDF8P//xKTklNQ0rtLcpKLUnJxErpx8GMhLVyhJrSjhAqrgqshOTuHyACrI11EIzy/KSVHkcuHy9ubyyOTKT0mJz0nNSy/JUAQA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Port of @l4m2's JavaScript answer. In Retina 1 you can write `2*$1` for the same byte count.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 8 bytes
```
⭆S×ι⊗﹪κ²
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaHjmFZSWQLgamjoKIZm5qcUamToKLvmlSTmpKRq@@SmlOfka2ToKRpogYP3/v0dqTk6@jkJ4flFOiiLXf92yHAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
S Input as a string
⭆ Map over characters and join
ι Current character
× Repeated by
κ Current index
﹪ Modulo
² Literal integer `2`
⊗ Doubled
```
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 9 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
```
⊢/˜≠⥊0‿2˙
```
[Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oqiL8uc4omg4qWKMOKAvzLLmQoKUyDihpAgKCjiiqIty5wrYMOXwqwp4oiYPeKKlOKKoikKPijiiqLii4jCt0Ygwq8x4oaTwrfiipEnPSfiirhTKcKoKEArMTApIFMgImFiY2RlZiA9PiBiYmRkZmYKdW1icmVsbGEgPT4gbW1ycmxsYWEKbG9vb29vb29vb25nIHRleHQgPT4gb29vb29vb29vb2dndHR4eAphYmMgPT4gYmIKeGtjZCA9PiBra2RkCkhlbGxvLCBXb3JsZCEgPT4gZWVsbCwsV1dycmRkCkQgPT4gPGVtcHR5PgpLSyA9PiBLSwpIaSA9PiBpaQpvZGRfbGVuZ3RoISA9PiBkZF9fZWVnZ2hoCiA9PiA8ZW1wdHk+Ig==)
Uses Jonah's J idea.
# [BQN](https://mlochbaum.github.io/BQN/), 10 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
```
2/1⊑˘⌊‿2⊸⥊
```
[Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgMi8x4oqRy5jijIrigL8y4oq44qWKCgpTIOKGkCAoKOKKoi3LnCtgw5fCrCniiJg94oqU4oqiKQo+KOKKouKLiMK3RiDCrzHihpPCt+KKkSc9J+KKuFMpwqgoQCsxMCkgUyAiYWJjZGVmID0+IGJiZGRmZgp1bWJyZWxsYSA9PiBtbXJybGxhYQpsb29vb29vb29vbmcgdGV4dCA9PiBvb29vb29vb29vZ2d0dHh4CmFiYyA9PiBiYgp4a2NkID0+IGtrZGQKSGVsbG8sIFdvcmxkISA9PiBlZWxsLCxXV3JyZGQKRCA9PiA8ZW1wdHk+CktLID0+IEtLCkhpID0+IGlpCm9kZF9sZW5ndGghID0+IGRkX19lZWdnaGgKID0+IDxlbXB0eT4i)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 28 bytes
```
f=([,y,...z])=>y?y+y+f(z):''
```
[Try it online!](https://tio.run/##PYxNbsMgEIX3nGK6MiiUAzQi3aRSJB/AiyRKsPkxNTYWppGdqmd3IVU6QsOb7828T3ETUxPsGF8HL9WqeXr4SBfKGLufCd8t78tm2Wh8J29FsUbgcEWibqTSwHdQ11Jqjb76OijnREZ9H0KSAjn/rMFAVHPM7j/zxsQ4zznrLwjNXSOz7Dop0SHFeQqVD06@ZKoSoLSqQkjuPhNUlvkrS3SwWViLvJQXpwYT28dNmi5KGdO26MpisD0mbBqdjbg4DQVhvRixy4vuifNQELJFkWkfPkTTYny0FNSZZOsbATR@mLxTzHmDFXAOGltCHz3d/ZDt@gs "JavaScript (Node.js) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) -p, 14 bytes
```
s/.(.?)/$1$1/g
```
[Try it online!](https://tio.run/##K0gtyjH9/79YX09Dz15TX8VQxVA//f//xKTklNQ0rtLcpKLUnJxErpx8GMhLVyhJrSjhAqrgqshOTuHyACrI11EIzy/KSVHkcuHy9ubyyOTKT0mJz0nNSy/JUPyXX1CSmZ9X/F@3AAA "Perl 5 – Try It Online")
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 10 bytes
```
(2*2!!#:)#
```
[Try it online!](https://ngn.codeberg.page/k#eJxlkFFPgzAUhd/vr2DMB2dgRGI0Ad3THpbwA/awLBu0l9JQ6Czd0sXob7e1Q6fyQO45597T5Kuz2/QunUym2WwKoLO3m835Q2V1EAQm38s2v93XJRe5yc+5mm3fQW/CsiIU6zAPq4rSug63zjx2lUIhSmt3nVJ2Kn0g5Pj1LNBotN34tiRjWhvjN23vV6lXpiXUyral1BsrWy+jYC2VoBOboNVRtF4rddmIwqW1/XJR2NH+/CW3gnMvJKU7gT3TjSuxYofIWNP41Bck0Gh9GLIkIZIik6KeD7okLRrSlD3DOZFd8nrEQXPZD0n6cJ8+PiUKO3nC2D4Q855ygkNc9jSm8lgJjHWDMZ6wHzMAzzF4WQQeJIwMnTVChH/8XPoXoOvyReC4udGBg1/MnHsNDZbOecbuoM8LKAqnigJW3A2cwxUp5/yggsvN1fknfze9SQ==)
* `(...)#` set up a filter/replicate, where the code in `(...)` is run on the (implicit) input and returns a list of numbers. for each such number, that many copies of the corresponding input item will be returned.
* `(2*2!!#:)` return a sequence like `0 2 0 2 ... 0 2` that matches the length of the input. this removes items at even indices (0-based), and doubles those at odd indices
[Answer]
# [Uiua](https://www.uiua.org/), 7 bytes
```
▽↯△,0_2
```
[Try it online!](https://www.uiua.org/pad?src=ZiDihpAg4pa94oav4pazLDBfMgoKZiAiSGVsbG8sIFdvcmxkISI=)
```
▽↯△,0_2 input: a string
↯△,0_2 [0, 2] cycled to the length of the input:
0_2 [0, 2]
△, shape of the input ([length])
↯ reshape [0, 2] to the shape [length]
▽ keep; delete chars at 0s and duplicate at 2s
```
[Answer]
# [Haskell](https://www.haskell.org/), 23 bytes
```
f(a:b:c)=b:b:f c
f _=[]
```
[Try it online!](https://tio.run/##y0gszk7Nyfmfm5iZp2CrkJlXklqUmFyikPY/TSPRKskqWdM2CUilKSRzpSnE20bH/v/vAVSfr6MQnl@Uk6IIAA "Haskell – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), 53 bytes
```
func[s][foreach c extract/index s 2 2[prin c prin c]]
```
[Try it online!](https://tio.run/##K0pN@R@UmhIdy5Vm9T@tNC85ujg2Oi2/KDUxOUMhWSG1oqQoMblEPzMvJbVCoVjBSMEouqAoMw8oBaFiY/@nKSh5pObk5OsohOcX5aQoKv0HAA "Red – Try It Online")
`extract/index s 2 2` says "get every other element of `s` starting at index 2" (keeping in mind Red is 1-indexed). Then print each of those elements twice.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 35 bytes
```
f(char*c){for(;*c++;c++)c[-1]=*c;}
```
[Try it online!](https://tio.run/##S9ZNT07@r5yZl5xTmpJqU1ySkpmvl2H3P00jOSOxSCtZszotv0jDWitZW9saiDWTo3UNY221kq1ruf7nJmbmaWhWgxQqJEfH2ip5pObk5OsohOcX5aQoKlkDzdC0LijKzCsBs2r/AwA "C (gcc) – Try It Online")
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 4 bytes
```
i#o:
```
[Try it online!](https://tio.run/##S8sszvj/P1M53@r///yUlPic1Lz0kgxFAA "><> – Try It Online")
Terminates with an error.
[This again?](https://codegolf.stackexchange.com/questions/237085/swap-every-two-elements-in-a-list/237115#237115)
## How?
```
i Take an input (instruction pointer (IP) going right)
# IP bounces off # and starts going left
i Take another input
: Duplicate it
o Output it
# IP bounces off # and starts going right
o Output again
: Duplicate (Useless)
And now, we're back to where we started, at the first character facing right.
The code will continue executing until it terminates with an error when running out of input.
```
[Answer]
# [GNU AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 35 bytes
```
BEGIN{RS=".|"}{printf NR%2?e:RT RT}
```
or
```
BEGIN{RS=".|";ORS=e}$0=NR%2?e:RT RT
```
[Try it online!](https://tio.run/##SyzP/v/fydXd0686KNhWSa9Gqba6oCgzryRNwS9I1cg@1SooRCEopJZLGUWRtT@QkVqrYmCLrIpLubggJ7NEQ8VAJ1EnVbM6Lb9II1MhM08hURNqZiZYcWJ0ZiwI1/7/75Gak5OvoxCeX5SToggA "AWK – Try It Online")
This is possible thanks to the `RT` variable, only available in GNU AWK. The characters are stored one at a time in `RT`, and the ternary conditional operator is used to skip the odds and double the even characters.
# AWK, 47 bytes
```
split($0,a,e){for(i in a)printf i%2?e:a[i]a[i]}
```
[Try it online!](https://tio.run/##SyzP/v9f2cnV3dOvOijYVkmvRqm2uqAoM68kTcEvSNXIPtUqKEQhKKSWC1WRtT@QkVqrYmCLrIqruCAns0RDxUAnUSdVszotv0gjUyEzTyFRE2pkJlhtYnRmLAjX/v/vkZqTk6@jEJ5flJOiCAA "AWK – Try It Online")
Splits the input character by characters into the array `a`, and does the skip-and-double magic through the ternary operator `?:`.
[Answer]
## **[MATLAB](https://www.mathworks.com/products/matlab.html), 25 bytes**
```
@(x)repelem(x(2:2:end),2)
```
[Answer]
# [Lua](https://www.lua.org/),77 83 bytes
Edited to comply with code golf rules. Assumes at least a space in input because I'm not entirely sure how to make it work with nil input without throwing an error.
```
p,t=io.read(),{} for i=0,#p,2 do t[i],t[i+1]=string.sub(p,i,i),string.sub(p,i,i)end
```
[Try it online!](https://tio.run/##yylN/P@/QKfENjNfryg1MUVDU6e6ViEtv0gh09ZAR7lAx0ghJV@hJDozVgdIaBvG2haXFGXmpesVlyZpFOhk6mRq6mCIpOal/P//HwA "Lua – Try It Online")
[Answer]
# [Fig](https://github.com/Seggan/Fig), \$4\log\_{256}(96)\approx\$ 3.292 bytes
```
eh]y
```
[Try it online!](https://fig.fly.dev/#WyJlaF15IiwiYWJjZGVmIl0=)
## Explanation
```
eh]y
y Uninterleave the input - return a list like [a[::2], a[1::2]]
] Get the last element (which is a[1::2])
e Over each character...
h Double it
```
[Answer]
# [4](https://github.com/urielieli/py-four), 25 bytes
```
3.72372382352352372372394
```
[Try it online!](https://tio.run/##M/n/31jP3MgYiCyMjE3BCMK1NMEjBQA "4 – Try It Online")
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 4 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
zt2Ḅ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faMGCpaUlaboWy6pKjB7uaFlSnJRcDBVasNYjNScnX0chPL8oJ0URIggA)
#### Explanation
```
zt2Ḅ # Implicit input
z # Uninterleave
t # Leave only the tail
2Ḅ # Double each character
# Implicit output
```
] |
[Question]
[
Inspired by [this code review](https://codereview.stackexchange.com/questions/242563/check-if-array-has-the-same-number-of-even-and-odd-values-in-python) question, I am curious to see what happens if we turn that into a code-golf challenge!
The description is easy, the input is an array or any similar data structure with only unsigned integers, the output is a boolean if the number of odd numbers is equal to the number of even numbers inside (true or false doesn't matter, as long as the opposite is used in case the number doesn't match)
Here are some examples with true as output for matching (thanks to the original OP)
```
[5, 1, 0, 2] -> true
[5, 1, 0, 2, 11] -> false
[] -> true
```
Usual code-golf rules, shortest code wins.
[Answer]
# [Haskell](https://www.haskell.org/), 20 bytes
```
(==0).sum.map((-1)^)
```
[Try it online!](https://tio.run/##TYk9CoAgGIav8g4NChYaNHoSM5DIilQk6/p92db2/GyuHEsI5PVITGvJu3LHLrrMWKv4xCm6PUEjn3u60KAeeBgzCCgBKdBbgZ9VUF@xlp7ZB7cWauecXw "Haskell – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 33 bytes
```
lambda l:sum(n%-2|1for n in l)==0
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHHqrg0VyNPVdeoxjAtv0ghTyEzTyFH09bW4H95RmZOqoKhVUFRZl6JQppGZl5BaYmGpub/aFMdBUMdBQMdBaNYLiQOkGEIFIgFAA "Python 2 – Try It Online")
`n%-2|1` is a shorter way to do`(-1)**n`. It works like this:
```
n n%-2 n%-2|1
------------------
even 0 1
odd -1 -1
```
**36 bytes**
```
lambda l:sum(map((-1).__pow__,l))==0
```
[Try it online!](https://tio.run/##TchBCoAgEEDRfaeY5QxYpNAm8CQVYpQkqA1lRKe3lu3@@/zkbU@qOD2WYOO8WAj9eUWMlhFrSY0xvN/GiECkdVvuzYcVZM@HTxkc@sRXRqIydAKkgFaAmqofvpDfmF4 "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Thanks to [Nick Kennedy](https://codegolf.stackexchange.com/users/42248/nick-kennedy) for fixing a bug after three years!
```
Ḃo-S
```
A monadic Link that accepts a list of integers and yields zero (falsey) if the odd and even counts are equal or a non-zero number (truthy) otherwise.
**[Try it online!](https://tio.run/##y0rNyan8///hjqZ83eD/Ryc93DnD@lHDHAVbO4VHDXNBzNK81MLSxBwgD8iBMQ@322tG/v8fHW2qo2Coo2Cgo2AEZBjG6nApgITMwQygkBGYYQiRhrGNdRRMYQpMdBTMwGxkhaj6jCGqYJoQNgK5sQA "Jelly – Try It Online")**
### How?
```
Ḃo-S - Link: list of integers e.g. [ 1, 2, 3, 4, 6]
Ḃ - least-significant bit (vectorises) [ 1, 0, 1, 0, 0]
- - -1
o - logical OR [ 1,-1, 1,-1,-1]
S - sum -1
```
Alternatively, `ịØ+S`, [does the same thing](https://tio.run/##y0rNyan8///h7u7DM7SD/x@d9HDnDOtHDXMUbO0UHjXMBTFL81ILSxNzgDwgB8Y83G6vGfn/f3S0qY6CoY6CgY6CEZBhGKvDpQASMgczgEJGYIYhRBrGNtZRMIUpMNFRMAOzkRWi6jOGqIJpQtgI5MYCAA "Jelly – Try It Online") using modular indexing.
[Answer]
-2 bytes, BIG Thanks to Arnauld
# [JavaScript (V8)](https://v8.dev/), 31 bytes
```
s=>s.map(e=>d+=e&1||-1,d=0)&&!d
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifZvu/2NauWC83sUAj1dYuRds2Vc2wpkbXUCfF1kBTTU0x5X9yfl5xfk6qXk5@ukaaRrSpjoKhjoKBjoJRrKaOuoKunYJCSVFpqoK6pjUXTqVAhiFceVpiTnEqIeVGBJWjWA@U/w8A "JavaScript (V8) – Try It Online")
[Answer]
# perl -alp, 20 19 bytes
```
$_=@F-2*grep$_%2,@F
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3tbBTddIK70otUAlXtVIx8Ht/39TBUMFAwUjLiitYGjIxWWoAIJGIIjMVjD6l19QkpmfV/xfNzGnAAA "Perl 5 – Try It Online")
Just checks whether the size of the input is twice the number of odd integers. Accepts a list of space separated integers on STDIN. Prints 0 if the number of even and odd numbers are equal, something else otherwise.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 14 bytes
```
Tr[(-1)^#]==0&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277P6QoWkPXUDNOOdbW1kDtf0BRZl6JQ7qDQnUtF4JtqmOoY6BjhEVIx9Cw9v9/AA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), 4 bytes
Port of @xnor's Haskell answer. In MathGolf, summing an empty list yields `0`.
```
b▬Σ┌
```
[Try it online!](https://tio.run/##y00syUjPz0n7/z/p0bQ15xY/mtLz/3@0qYKhgoGCUSwA "MathGolf – Try It Online")
## Explanation
```
b Constant -1
▬ -1 ** input list (vectorizes)
Σ Sum the resulting list
┌ Convert to inverted boolean
```
[Answer]
# [Python 3](https://docs.python.org/3/), 30 bytes
```
lambda x:sum(i%2-.5for i in x)
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHCqrg0VyNT1UhXzzQtv0ghUyEzT6FC839BUWZeiUaaRrSxjrGOqY6hjoGOUaymJhdcHCH2HwA "Python 3 – Try It Online")
[Answer]
# x86 32-bit machine code, 13 bytes
Input: `uint32_t *esi, size_t ecx`
returns: EDX = `len - 2*even` = 0 for balanced, non-zero for unbalanced.
This conveniently works even for len=0 = balanced. As part of this asm custom calling convention / ABI, my boolean data type is 0 / non-zero, rather than the 0 / 1 that C ABIs use.
This avoids needing to actually compare, just decrement twice *inside* the loop, starting with the list length.
```
1 boe:
2 00000000 89CA mov edx, ecx ; balance = len
3 00000002 E309 jecxz .end
4 .loop: ; do {
5 00000004 AD lodsd ; eax = *p++
6 00000005 A801 test al, 1
7 00000007 7502 jnz .odd
8 00000009 4A dec edx
9 0000000A 4A dec edx ; more compact than sub edx,2 in 32-bit code
10 .odd:
11 0000000B E2F7 loop .loop ; }while(--ecx);
12 .end:
13 ; xchg eax, edx ; custom calling convention: return in EDX instead of spending a byte on xchg
14 0000000D C3 ret
```
[Try it online!](https://tio.run/##pVPBbtswDL3rK3hsFidIsrUobPS2/cOAYShoi7U1yJIhKYnTYd@ekbaHukVSDJthQCJFkY9PfBgjtaU9rRzG9nwuPeUK@Gv9QRbSfQZU9YPvB2@eAdbktFpb77scrnwFaA8/h0vW66ivhhH28AAfuuVyCE4UEy9oM9iOJR0XhLXXejA1VROqN@aF1K0PBJVvO6wSpAYdxH05NLQD4@DjblWaxAGalOTPJ7S@k4LT@irhr2NjLN2sVkzDolBCQ64KOeurphYcKGTNwRRQ7WPyLVRorXE1l3MHcsl4l0OgtA9OsHz5/HWozh6lFFpTO9jeqdr6Ei08xoQhqXGZvw5pkwGGsJ374gVfxbhu/0AqwHcCgBGdoMMYASE2PiQKYMnVqcnA89a7mj3JMyrU8EzBRwkXLgm49/VQQRoDnho1WMVUsBQisJ9jKEdu5i6ha8RpnDz7pr/fzGejN@lGct9IP5mAW8CCCYpUSQOwDl5jQiXHMopawy1nzGCTwY43Y27JxSdsvVxM1CfFmR8Pu/zC6KBNcKAQOfaVGPB/xTDNd3lKBN/4@b4zypew/v4OTARrUrK04sQGXcF0s49/od3643jZP/GrHRtvSbh7TyrYvzHh77WCopXrYokVvidtbZYPn/5NVZMYzuff "Assembly (nasm, x64, Linux) – Try It Online") (with a `_start` test case that exits with the return value as exit status)
An alternate version that calculates in EAX to return in the standard calling convention's register is 14 bytes. It uses `test byte [edi], 1` (1 byte longer than `test al,1`) and increments the pointer with `scasd` (without caring about the FLAGS result of the `eax - [edi]` it also does). See the TIO link.
Uncommenting the `xchg eax, edx` at the bottom of the 13-byte version would do the same thing, and that version's loop is more efficient.
---
For 8-bit integer input, use `lodsb` instead. Unfortunately, we can't use `and al, 1` / `add dl, al` or similar (without branching). That would only work for array sizes up to 255. `and eax,1` is 3 bytes.
Also, masking and adding only does one increment. `lea edx, [edx + eax*2]` could work but that's also 3 bytes. Branching on the low bit with test/jnz seems to be best for size, although it sucks for performance with branch mispredicts.
Of course if we wanted to go fast, we'd load 16 bytes at once with `movdqa`, isolate the low bits with `pand`, and sum with `paddd`. Then hsum at the end. Or hsum with `psadbw` against a zeroed register, then `paddq`. SIMD is of course especially good for 8-bit elements, 16 per vector instead of 4, with an outer loop to avoid overflowing 8-bit counters. e.g. [this AVX2 SO answer](https://stackoverflow.com/questions/54541129/how-to-count-character-occurrences-using-simd).
Something like this could maybe be smallish code-size if we limited it to a fixed-size 16-byte input array, or maybe 8-byte in MMX registers. Unfortunately we rarely get to play with SIMD in code golf because the instructions are larger and inputs can be odd lengths requiring cleanup loops.
[Answer]
Here is my version (Thanks to @ElPedro and to everyone in the comments for the corrections):
# [Python 3](https://docs.python.org/3/), 37 bytes
```
lambda x:sum(i%2for i in x)==len(x)/2
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHCqrg0VyNT1Sgtv0ghUyEzT6FC09Y2JzVPo0JT3@h/QVFmXolGmka0qY6hjoGOUaym5n84GwA "Python 3 – Try It Online")
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), ~~25~~ ~~24~~ 23 bytes
```
?0[r_1r^+z1<F]sFz1<Fd/p
```
[Try it online!](https://tio.run/##S0n@/9/eILoo3rAoTrvK0MYtttgNRKXoF/z/b6pgqGCgYKRgaAgA "dc – Try It Online")
Or verify the [test examples](https://tio.run/##RY1BCsIwFET3/xRDcCfFfsFdrCuz9QBFJSbRFNqkpAVBvHtsteBmHrxhmJsefDZ6RNWn@Ei6g5TieFIiH8o6XTld1i@W6jyoGXbT56kkevqmdUhOW7RNcATYOAXgjI8oAsRq9thXEH//kwJvWIPijuXyuw4u78AosaWFYCb6AA).
---
Input on stdin: a line of space-separated integers.
Output on stdout: `0` for truthy, and `1` for falsey (dc doesn't have standard truthy/falsey values).
[Answer]
# [Ruby](https://www.ruby-lang.org/), 23 bytes
```
->x{x.sum{|n|~0**n}==0}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf166iukKvuDS3uiavps5ASyuv1tbWoPZ/gUJadLSpjqGOgY5RbCwXlKtgqKNgoKNgBGQYwkRjY/8DAA "Ruby – Try It Online")
Special thanks to [Manatwork](https://codegolf.stackexchange.com/users/4198/manatwork), [Dingus](https://codegolf.stackexchange.com/users/92901/dingus) and to [histocrat](https://codegolf.stackexchange.com/users/6828/histocrat) for finding the shortest solution, all credit to them.
[Answer]
# [K (Kona)](https://github.com/kevinlawler/kona), ~~7~~ 6 bytes
-1 byte thanks to coltim
```
~+/-1^
```
[Try it online!](https://tio.run/##y9bNzs9L/P8/zapOW1/XMO5/mrqGqYKhgoGCkbUClKFgaGitYKBsoPkfAA "K (Kona) – Try It Online")
# [J](http://jsoftware.com/), 9 bytes
```
0=1#._1^]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DWwNlfXiDeNi/2tyKXClJmfkK2hYp2mq6dkpmCoYAhUaWcMYCoaG1goGKgYKCgr/AQ "J – Try It Online")
Ports of [xnor's Haskell solution](https://codegolf.stackexchange.com/a/205112/75681) - please upvote him!
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 7 bytes
Port of xnor's Haskell solution. Prompts for the input; -2 thanks to @Graham.
-1 byte thanks to @Adám by switching the language.
```
=+/¯1*⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKM97b@ttv6h9YZaj/qmgvj/07hMFQwVDBSMuOAsBUNDZI4BkPOodw0A "APL (Dyalog Extended) – Try It Online")
[Answer]
# [Excel], 28 bytes
Paste this into a cell outside of column A, the array goes in column A.
```
=0=SUM(IF((A:A<>""),-1^A:A))
```
An example:
[](https://i.stack.imgur.com/dphbb.png)
[Answer]
# [Java (JDK)](http://jdk.java.net/), 28 bytes
```
a->a.map(n->-n%2|1).sum()==0
```
[Try it online!](https://tio.run/##bU/BSsNAEL33K8ZAYKPN0oi9pCbgwYMHUag38TCmu2VrdhN2JoGi/fZ1E@pB9PB4zLx5M28OOGJ@2H0EY/vOMxxiLQc2rbzcLP709OAaNp37VyT2Cu0kNS0SwSMaB58LgH54b00DxMiRxs7swEZNbNkbt399A/R7yuZRgGevdqZBVrcPjrfzyhp0FTCvUVrshcvr3KXXX0UmabAiq6pV2MxW3XkxogdWxOWvpQBTH6GCO@/xSOesYpqU1LeGRQJXSZZJbVpWXhDkNVyQNHRvez6KqMTbL13MJCLUXvmyHLEd1JPONucb2yOxsrIbWPbxM9YiSamElFKXLOdUS9ByYoHZ2XVaTDiFsIYCVnD9w1AUIRSR13DzDQ "Java (JDK) – Try It Online")
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), ~~17~~ 14 bytes
```
ps{2.%}pt)L[sm
```
[Try it online!](https://tio.run/##SyotykktLixN/f@/oLjaSE@1tqBE0ye6OPf/f1MFQwUDBSMA "Burlesque – Try It Online")
Saved 3 bytes using shorthand map
Explanation:
```
ps # Parse input as a block
{2.%}pt # Partition block based on modulo 2
)L[ # Map blocks to their length
sm # Check lengths are the same
```
[Answer]
# [Befunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), ~~13~~ 12 bytes
*-1 byte thanks to @Jo King!*
```
#.&2%2*1-+#@
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//9X1lMzUjXSMtTVVnb4/z/aVEfBUEfBQEfBKBYA)
This uses the same logic (`&2%2*1-+`) as @Abigail's answer, but has a different control flow structure. Befunge-98 adds extra "error handling" functionality to the `&` and `~` input instructions: when EOF is reached, they reflect the instruction pointer. When this happens, the program can execute a different section of code without the need for an explicit conditional.
```
#.&2%2*1-+#@
(Implicit: the counter, the top of the (empty) stack, starts at 0)
(Implicit in program structure: begin loop)
# Skip the next instruction
. (skipped)
& Get integer from STDIN
2% Take the integer modulo 2
2* Multiply that by 2 (results in 2 if the number was odd and 0 if even)
1- Subtract 1 (results in 1 if the number was odd and -1 if even)
+ Add that to the counter
# Skip the next instruction
@ (skipped)
Repeat
When the input runs out:
& Catch the EOF and reverse direction
. Output the counter (0 if odds and evens are matched, nonzero otherwise) as an integer
# Skip the next instruction (a space)
@ End the program
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~6~~ 5 bytes
-1 bytes thanks to @LuisMendo
```
oEqs~
```
[Try it online!](https://tio.run/##y00syfn/P9@1sLju//9oUwVDBYNYAA "MATL – Try It Online")
## Explanation
```
oEqs~
o % Replace each elements with its parity (i.e. mod 2)
E % Multiply all element by 2
q % Decrement all elements by 1
s % Sum the array
~ % Boolean not the sum
```
[Answer]
# sed `-E`, ~~78~~ 80 bytes
*+7 to account for 0's and empty lists, -5 from golfing*
Tried to have some fun:) Input is spaced separated unary numbers.
Ex: `echo "!!! !! !!!!" | sed -Ef main.sed` (if the code is saved to main.sed)
```
s/_/@/g
s/(!!)+/@/g
s/@*!/!/g
s/ //g
:l
s/(!@|@!)//g
tl
s/!+/true/g
s/^$/false/g
```
[Try it online!](https://tio.run/##TYq9CoAwEIP3PkUDDmqR2526@BqK4A@CtOLVzWf3bIuDIZB8JDxPzeouEaaBLK2KqQQq83Vbg5Cbphjtnnd7W1SJQ2IYCuc151df0DLuHEEESRp60ID6QzSUevwRNu9Ymu4F "sed – Try It Online")
[Answer]
# [Uiua](https://uiua.org), 8 [bytes](https://uiua.org/pad?src=U0JDUyDihpAgK0BcMOKKlwpEZWNvZGUg4oaQIOKHjOKKjy0x4pa9wrEu4o2Y4ouv4oav4oqCwq8x4qe74ouv4qe7LOKHjOKItSjihpjCrzHii68rMjU2KSAtQFwwKzEKJnAg4oqCIjggYml0IGVuY29kaW5nOlx0IiBTQkNTICLih4ziio8tMeKWvcKxLuKNmOKLr-KGr-KKgsKvMeKnu-KLr-Knuyzih4ziiLUo4oaYwq8x4ouvKzI1NikiIOKKgitAXDDih6ExMjkiLiziiLY74oiYwqzCscKv4oy14oia4peL4oyK4oyI4oGFPeKJoDziiaQ-4omlKy3Dl8O34pe_4oG_4oKZ4oan4oal4oig4qe74paz4oeh4oqi4oeM4pmt4ouv4o2J4o2P4o2W4oqa4oqb4oqd4pah4oqU4omF4oqf4oqC4oqP4oqh4oav4oaZ4oaY4oa74per4pa94oyV4oiK4oqXL-KIp1xc4oi14omh4oi64oqe4oqg4o2l4oqV4oqc4oip4oqT4oqD4oqZ4ouF4o2Y4o2c4o2a4qyaJz_ijaPijaQh4o6L4oas4pqCzrfPgM-E4oiefl9bXXt9KCnCr0AkXCLihpB8IyIKJnAg4oqCImRlY29kZWQ6XHQiIERlY29kZSAiwqPCsS0xwrjChy7DjMKlwrPCsMKIMcKfwqXCnyzCo8K_KMK1wogxwqUrMjU2KSIg4oqCK0BcMOKHoTEyOSIuLOKItjviiJjCrMKxwq_ijLXiiJril4vijIrijIjigYU94omgPOKJpD7iiaUrLcOXw7fil7_igb_igpnihqfihqXiiKDip7vilrPih6HiiqLih4zima3ii6_ijYnijY_ijZbiipriipviip3ilqHiipTiiYXiip_iioLiio_iiqHihq_ihpnihpjihrvil6vilr3ijJXiiIriipcv4oinXFziiLXiiaHiiLriip7iiqDijaXiipXiipziiKniipPiioPiipnii4XijZjijZzijZrirJonP-KNo-KNpCHijovihqzimoLOt8-Az4TiiJ5-X1tde30oKcKvQCRcIuKGkHwjIg==)
```
=0/+ⁿ∶¯1
```
[Try it!](https://uiua.org/pad?src=ZiDihpAgPTAvK-KBv-KItsKvMQoKZiBbNSAxIDAgMl0KZiBbNSAxIDAgMiAxMV0KZiBbXQpmIFsxIDNdCmYgWzEgMl0KZiBbMiAyIDIgMiAxXQ==)
```
=0/+ⁿ∶¯1
ⁿ∶¯1 # raise -1 to input
/+ # sum
=0 # is it equal to zero?
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~6~~ 9 bytes
+3 bytes from fixing code per @Dominic van Essen's comment
```
~+/1 1'2!
```
[Try it online!](https://ngn.codeberg.page/k#eJxVi8FugzAQRO/+io1Uqa3KxjYpFyz1RxBSXLMOCLAb20Sgqvn2kjYS7Zxm3szY8vrCJcjHfMdYKj8fquUaSguzOvpePR2t7gY1q0WF5/prXVQFSBCQK1lvAaRU4pZ34j9/vWHGWZvSRyw5N76hkx/sPiZteppNq92J9saP/DxRTJ13keeikOLATUumx86idqhD0Av6gHSeuoseyCVsdcTUEkY9ErppfKeA3qJvmvXRIF3I3XFkrCoykBmIDPIafoRvAClMBH+71cj6t7N6iMSq+3rT9mPsG0vSWQM=)
* `2!` mod the (implicit) input by two
* `1 1'` convert `0`'s to `-1`'s, leave `1`s unchanged
* `~+/` not the sum of the above
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~6~~ 4 bytes
```
ÉD¢Ë
```
[Try it online!](https://tio.run/##yy9OTMpM/f//cKfLoUWHu///jzbVUTDUUTDQUTACMgxjAQ "05AB1E – Try It Online")
## Explanation
```
É Is the number odd?
D Duplicate
¢ Count the occurances of the bits in the original copy
Ë Are all items in the list equal?
```
[Answer]
# [Factor](https://factorcode.org/), 52 bytes
```
: f ( s -- ? ) [ odd? ] partition [ length ] bi@ = ;
```
[Try it online!](https://tio.run/##TU6xCsIwFNz9iht1iFjBpUXqJl26FKfSIbWvGmxfYpIKUvrtMYiD3HJ3HHfXy6vXNlyqojyneJBlGjBKf4ej50R8JQdjyfu3sYo9slVRpqjkSIKnsSUrdC901wnJnaAX8c92IUWPNRyEQI4NasRUjgZGWq@80hytgfgWpxq06oQjsjBjxgEJdthj@eNJ8pVLRB17m3jRYBs@ "Factor – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 6 bytes
```
!sm^_1
```
[Try it online!](https://tio.run/##K6gsyfj/X7E4Ny7e8P//aFMdBUMdBQMdBaNYAA "Pyth – Try It Online")
## Explanation
```
!sm^_1
m : map
^_1 : -1 power value
: over implicit input
s : sum it
! : logical negate the sum (i.e. 0 -> True, -1 -> False, 10 -> False)
```
[Answer]
# [R](https://www.r-project.org/), ~~18~~ 17 bytes
```
!sum((-1)^scan())
```
[Try it online!](https://tio.run/##K/r/X7G4NFdDQ9dQM644OTFPQ1PzvyGXEZcxlwnXfwA "R – Try It Online")
*Edit: -1 byte thanks to Bart-Jan van Rossum*
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~45~~ ~~44~~ 43 bytes
Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
Saved a byte thanks to [Olivier Grégoire](https://codegolf.stackexchange.com/users/16236/olivier-gr%c3%a9goire)!!!
```
b;f(int*a){for(b=0;~*a;b+=-*a++%2|1);b=!b;}
```
[Try it online!](https://tio.run/##vZBbS4RAFMff@xQnQfAywszYPrSTQURfoNfVB68l7NqiLhpmX92Ozrop7UO20ICI5/wv4y@0XsKw6wKRaGlWGr7eJG@5FjhUfBq@CEzHMnzTVPkH00XgXAei7XZ@mmk6NFeAB02QHXYF23jgQLMiwAhQApyAxVox0/CfGsbO6Gypm823cVbI8Q0BTKCTXVzv47CMI7mX2aM3fPVzA3K5Utz6ibv17SM@K4XA9NtW0DFY9jmGJprykOf@@xo2ii6jEAz0kCDFLCrwdSevRT0BppmOSIZrJSi9p/opDMuOMdMKNcKFxJd6x307u4TnZqOxr66wOtEGx3E6Cp/j4rAt16BGoBZoIlAR/O/KcU54qNd3zFzW@SNL/0aDXU6D/4LGNwm@nAT7FxL8chL2IhL2chJ8INF2Xw "C (gcc) – Try It Online")
**Input**:
\$-1\$ terminated `int` array.
**Output**
C boolean values: \$1\$ if number of odd are equal to the number of even numbers, \$0\$ otherwise.
**How**
Initialise a counter `b` to \$0\$. Then go through the elements in the array adding \$1\$ to `b` for every odd number and \$-1\$ to `b` for every even number. Return the boolean result of testing `b` equal to \$0\$.
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 34 bytes
```
+>+>>,[[-[->]<]<<+[>]>,]<<[-<->]<.
```
[Try it online!](https://fatiherikli.github.io/brainfuck-visualizer/#Kz4rPj4KLFtbLVstPl08XTw8K1s+XT4sXQo8PFstPC0+XTwuCgppbnB1dDogNDgsIDQ5LCA0OCwgNDkKITAxMDE=) (Check the `!` box to enter input automatically.)
Takes input as code points. Prints a null byte if there are equal number of odds and evens. Otherwise, prints a non-null byte.
**Memory layout**:
```
a b 0 n 0
```
where `a` is the current number of odds, `b` is the current number of evens, and `n` is the current element in the array.
**Explanation**:
```
+>+>> set a and b to 1, and pointer to n
,[ for each element n in the array
[-[->]<] if n is even, pointer stops at n, else, pointer stops at left of n
in both case, n is set to 0
this requires the cells left and right of n to be 0
<<+ increment a or b appropriately
[>]>, pointer back to n, read new n
] stop if n = 0 (end of array)
<<[-<->]<. find b - a, and print that value
```
[Answer]
# [Brainetry](https://github.com/rojergs/brainetry), 342 bytes
Golfed version:
```
a b c d
a b
a b c d
a bb
a b
a b c d e f
a b c d e f g h
a b c d e f g h
a b c d e
a b c d e f g h
a b c d e
a b
a b c d e f g h i
a b c
a b c d e f g h i
a b c
a b c
a b c d
a b c d e f g h
a b
a b c d e f g h i
a b
a b c d e f
a b c d e f g h i
a b c
a b c
a b c d e f g h
a b c d e
a b c
a b c d e
a b
a b c d e f g h i
a b c
a b c d e f g
```
To make our lives easier we use the `--numeric-io` flag, so that we can take input and give output as integers, but we don't really need to and the answer works without it. Read the program below for due credit.
The golfed version was adapted from the program found below. To try this online you can
* head over to this [replit](https://repl.it/github/rojergs/brainetry) link, copy&paste the code into the `btry/replit.btry` file and hit the green "Run" button (takes input as ASCII characters (converts them to codepoints) and outputs ASCII characters, use CTRL-D in a newline to terminate input, doesn't really work well for this challenge.);
* clone the [github repo](https://github.com/rojergs/brainetry) and from your terminal run `./brainetry btry/ppcg/evens_and_odds.btry --numeric-io` (give one integer per line, use CTRL-Z or CTRL-D in an empty line to stop giving input).
```
"Check if an array
(or equivalent)
has the same number
of odd
and even
numbers - Code Golf Edition !"
That is the title of the codegolf.stackexchange.com challenge
that this brainetry program solves. Once more, with
no shame at all ,
I am piggy backing on someone else's answer.
This time, Surculose Sputum's answer.
Oh boy!
You can check the original answer over here: https://codegolf.stackexchange.com/a/205621/75323
Go upvote that!
This is a very literal port of that answer.
I am pretty
sure I could
have used brainetry's builtins
to make this easier, like » or ≥,
except that
would mean I would have to think... ugh... nope!
For now
I will stick to the low
hanging fruit just to show that brainetry is out.
If this is
the first time
you find a brainetry program, welcome! By now
you probably understood you are
allowed to write
pretty much anything as source.
(source code)
You only have to write lines of correct size
and with the
correct line modifiers. (That's a recent addition.)
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 6 bytes
```
%₂ᵍlᵐ=
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/X/VRU9PDrb05D7dOsP3/P9pUR8FQR8FAR8EIyDCM/R8FAA "Brachylog – Try It Online")
### How it works
```
%₂ᵍlᵐ=
ᵍ group input based on result of …
%₂ mod 2
lᵐ map length over all groups
= are the lengths equal?
```
] |
[Question]
[
Given two arrays of non-negative integers \$A = [A\_1,A\_2,\ldots,A\_n]\$ and \$R = [R\_1,R\_2,\ldots,R\_n]\$ which are equal in length, return an array which has the element \$A\_1\$ repeated \$R\_1\$ times, then element \$A\_2\$ repeated \$R\_2\$ times, all the way up to \$A\_n\$.
[Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest program wins.
### Test Cases
| \$A\$ | \$R\$ | Output |
| --- | --- | --- |
| `[1,2,3]` | `[1,2,3]` | `[1,2,2,3,3,3]` |
| `[6,0,0,6]` | `[5,1,1,0]` | `[6,6,6,6,6,0,0]` |
| `[100,100]` | `[0,0]` | `[]` |
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 1 byte
```
x
```
[Try it online!](https://tio.run/##y0rNyan8/7/i/@Hl@o@a1hyd9HDnDCAd@f9/dHS0oY6RjnGsDpQGMqLNdAyA0AzINNUxBEIDsKihgYEOEAOZBiCRWAA "Jelly – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 27 bytes
```
(concat.).zipWith replicate
```
[Try it online!](https://tio.run/##LY0xDsIwDEV3TuGBASS3SkB0okdgZggZ3CilEWmwmkyIsxNMhb6s//QG/4nyw8dYx/5Wd@6ZHJV2374CX0OZYPEcgyhfi88lQw/GGI0HPFr8t4DpUEk6wRNqiVqtVgrlBNXP2M1MIcmLmfgCvIRUYAtmBILhbQYke27WFQv148ZI91wbx/wF "Haskell – Try It Online")
These built-ins have long names, but I haven't found anything shorter.
[Answer]
# [J](http://jsoftware.com/), 1 byte
```
#
```
[Try it online!](https://tio.run/##y/qvpKegnqZga6WgrqCjYKBgBcS6egrOQT5u/5X/a3KlJmfkKxgqGCkYKwBBmgKEDRE2BXIMgepBwmZA2kDBDCIBYirA1BsYgDBEwlLBQsEc2aD/AA "J – Try It Online")
Simple built-in solution: The [copy](https://www.jsoftware.com/help/dictionary/d400.htm) verb.
[Answer]
# [R](https://www.r-project.org/), 3 bytes
```
rep
```
[Try it online!](https://tio.run/##K/qfZvu/KLXgf5qGoZWxDhBrcqVpJGuY6RgAoZmmTrKGqY4hEBpoQiQMDQx0gBgkYQAS/A8A "R – Try It Online")
In [R](https://www.r-project.org/) many functions are vectorized and so is `rep` - it happens to work correctly for this challenge.
[Answer]
# [Raku](https://raku.org/), 12 bytes
```
(*Zxx*).flat
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfQyuqokJLUy8tJ7Hkv7VCcWKlQppGjUq8pkJafpGCho2hgpGCsZ2OApShqQMUM1MwAEIzkKipgiEQGkDEDQ0MFIAYJG4AEvsPAA "Perl 6 – Try It Online")
* `xx` is Raku's replication operator. It produces a list of a number of copies of its left argument given by its right argument. (Very conveniently, though irrelevant for this problem, the left-hand side is re-evaluated the requested number of times, so for example `rand xx 10` will produce a list of ten different random numbers.)
* `Z` is the zip "meta-operator." It can be prepended to any other operator to produce a new operator that zips two lists together using the original operator.
* The asterisks make this a "WhateverCode" expression, a short way of defining anonymous functions. The first and second argument to the function will take the place of the first and second asterisk, respectively.
* `.flat` flattens the list of replicated lists.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~44~~ 43 bytes
−1 thanks to Arnauld.
```
A=>R=>A.flatMap((a,i)=>Array(R[i]).fill(a))
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@9/R1i7I1s5RLy0nscQ3sUBDI1EnUxMoUFSUWKkRFJ0Zq6mXlpmTo5Goqfk/OT@vOD8nVS8nP10jTSPaUMdIxzhWE87Q5EJTYKZjAIRmICWmOoZAaIBFkaGBgQ4QgxQZgBX8BwA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~42~~ ~~41~~ 40 bytes
```
lambda*a:sum(map(lambda x,*y:x*y,*a),())
```
[Try it online!](https://tio.run/##LcxBCsMgFATQvadwqTILbWgWQk5iXfxSpIFqJE1BT29/SRmGgbeY2o/nVqaRltt4Ub4/yJB/f7LKVNUJssF030yHIQ2l9aAlhOBwwRTx3wgRwgzLmRmvcBx7srMWXGb7oyhE2nZ@7XItknzd13KopDoaf38B "Python 3 – Try It Online")
-1 thanks to Jonathan Allan!
-1 thanks to loopy walt!
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 1 byte
```
/
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///X/9/2qO2CY96@x51NT/qXfOod8uh9caP2iY@6psaHOQMJEM8PIP/GyoYKRgrpCmAaS5TIG2oYADkmwFJAwUzLgMwz9DAAIQB "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 3 bytes
```
r9C
```
[Test suite](https://pythtemp.herokuapp.com/?code=r9C&test_suite=1&test_suite_input=%5B1%2C2%2C3%5D%2C%5B1%2C2%2C3%5D%0A%5B5%2C1%2C1%2C0%5D%2C%5B6%2C0%2C0%2C6%5D%0A%5B0%2C0%5D%2C%5B100%2C100%5D&debug=0)
Takes input as `R,A`.
[Answer]
# [Factor](https://factorcode.org/), ~~27~~ 25 bytes
```
[ [ <array> ] 2map-flat ]
```
[Try it online!](https://tio.run/##PY29CsIwFIX3PsV5AUsa0UFF3MTFRZxKh0tIIZi24eY6lNJnjzGCw/nh48DpycjE6fm43a8HEDPNES/Lo/Uw0xCct1y/xXknzkYEtiJzYDcKjlW1oIHGFiuAf890l3sDlfmCfU6V/ctVYfitlSpaU4sWp3J9Rgc9UNj0ngRd0sLugjrCeEucPg "Factor – Try It Online")
Takes input as `R A`.
[Answer]
# [Python](https://www.python.org) NumPy, 39 bytes
```
lambda a,b:[0,*b]*1**b[:1]@[(),*zip(a)]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=Lc5RCsIwDAbg952ib7YlQqs4ZDDwHrUPKVIc2K6UDpzgSXwZiN7J25ixEcIPXwLJ65vGcu3j9Pbt-TMUvz3-NjcM7oIMwTVGgXRWaimdabQ9GS5APrrEUdh1_YmtMUbDDvYW1rRQGVODoqoJD6Cp1MJaKaAmVjPZyuc-sDiENLIupD4XhjnjWPk-szsQRhaQLs4IKJqUu1i45zQTYnlimpb8Aw)
Of course, there is also the `repeat` builtin.
### How?
Beside the usual bending over backwards to avoid the explicit numpy import this uses the fact that if we write \$c\_i = [b\_i]\$ then, formally, \$c\_1 a\_1 + c\_2 a\_2 + ... + c\_n a\_n\$ is a dot product. It is mildly tricky to set up an array of equal length sequences because numpy will just create an additional dimension and create an array of scalars. Here we prepend a different length sequence, forcing a ragged array (after using zip to create a list of singleton tuples). To match we must also prepend one value to the length array. The 1\*\*b[:1] factor, mathematically a nop, is there to trigger a coercion cascade to numpy arrays-
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes
```
¨£ẋf
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBUCIsIiIsIsKowqPhuotmIiwiIiwiWzEsMiwzXSxbMSwyLDNdXG5bNiwwLDAsNl0sWzUsMSwxLDBdXG5bMTAwLDEwMF0sWzAsMF0iXQ==)
This two-byte solution should work, but it seems to bork when the length is an array only of zeros: [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBUCIsIiIsIsO44biKIiwiIiwiWzEsMiwzXSxbMSwyLDNdXG5bNSwxLDEsMF0sWzYsMCwwLDZdXG5bMCwwXSxbMTAwLDEwMF0iXQ==)
[Answer]
# [MATL](https://github.com/lmendo/MATL), 2 bytes
```
Y"
```
[Try it online!](https://tio.run/##y00syfn/P1Lp//9oMx0DIDSL5Yo21TEEQoNYAA) Or [verify all test cases](https://tio.run/##y00syfmf8D9S6b@6rq56hEvI/2hDHSMd41guOG2mYwCEZkCWqY4hEBqA5AwMdIAYyALKxQIA).
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 7 bytes
```
repelem
```
It seem's that TIO's version of Octave doesn't have this built-in.
[Answer]
# [Goruby](https://codegolf.stackexchange.com/questions/363/tips-for-golfing-in-ruby/9289?r=SearchResults&s=1%7C19.2033#9289), ~~25~~ 22 bytes
-3 bytes thanks to [G B](https://codegolf.stackexchange.com/users/18535/g-b)
```
->a,b{a.fl{[_1]*b.sh}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=pVbdbts2FL73U5w6aSy5imKvazEE9dIfpNtuVqAFdjHDEyiJttlSlEBSaWxJfZHd9GJ7hb3L9jQ7JCX5p2nRYTFi0uef53znkL__Ict48_GfQXkCP-RmD4WkvEwpnMMg4UQpeBW_pYkeADx9usr5MloTtYYZVM0AaTdUxrmiAZz-cv36-as318jptgEIxlEmpUvIqF7naZQxpZhYQRbAmARwFiMbQKPSnvE5zJGvKF-GNoIFLKCuZ5ARnaxRO3LGlJf588nCWmBLNHJ2Bs4eQBQpKtIo8rRx5ENVj4lcqbplA8RhzESKxkJ6Q7g3LGSeVLUNwbpJiSY1nH7AyA6J0Az9MCGce6cffOP39MOeUcuwrvyW2tiVckVbgoaro_BMHny4BFUWVDpxkQ66773EtskedDk9zodCmdEogAxXEwmJOe2YLh6JnIvfTioV6jxS4UqVsXcRXvjV0AvHV_4QHsBruqK3RUhVQgrqnZ75TXNhdbNwJWnhST9UudQRQiXNoWZdTpkzaYMyQqiuS0kNpfDOLhXbUh-ePAF2dML2MK7cuVC6B0nyGXAkwVdgIwnAWiNCqx4mGohIQVIMTDh2tKLa021yCFMUfiYZvZYylwEMS8EE04xwDD7t7cFJlTTDwKaYSm_qH51kjemhaJrEsaQ3jGiWi6-ojZFwdbE_81JGCcGAZuBdPQvDq199mM1QZA_zWYggpreeU9tkHeimYVnoHMk261W9rdEyFlTYYmOaM0S_i2vrmwJVtZZ4zF1_CHqroRSc4gDwDvxbQYzB_OqD7PUsF8bmrD2tzbdjsTtwazmYGlMnexJjWnUN9EkHualyB4aO8-rS2mPFWHXDDFuwFUHAF5LdEN0rYSPu1FvjrUjnZ-0RU80fsZyx2bzHTWI290auAkWpFQxPKtJQzvMAARM3ueSpBc5hzEvPIGI6mTjNtnIZFk3UxszoJdtun5fb7WA0ZzMxHn97_3z6KGAPpg8XdS2anTVEKVGgyMa67-ynefR-zbjL3QTsHjaM8qPcoVwpdJvZCdj9gZyVdXl8JiXZ9B5znka2aC10HdVS3uZM7Cu-JFjFF2b7WW0TS98Dw-Gnzn8SGieU7A1QkqxBs4waFSYSe3ldizKj0mBhX_UNAk2ses0LUAVnerDzShxiDNUbjfb62rNHxm4zAyDZYeUc7iDdZ3NjS24Q8kSoAkc2LDnRmopuvYfDJCsIIrFd7wEGmCc4g8yy8ENzrKo2Rl1TmmsKhnZrgj2pDKtxd425QHievOva36CzP43pP1VyM0ZJ-EU1nO6cJNQjoalbR8WGdQZ2TdTV3_21BbHDwUliG2OHtVp4unfeKBmPzBXX0iwunDb29R0e2vrpXO5NESvibhMboBkVFAV3luiRdMexg8KuJoPNPiYOPN0Nyf9U_Pllm8YFjpb5pTHxP6tpKvmlwvWn2o8fIyvMoGvXntfRuzMetMcmi_PuwbZ7yRx6Mw8le_FLmtzUPXKSm7B_1JiJa941d0W638_L2Z-lXp5_99f59ySIKxIueTWPpotxHKp10zjm39cFLOfzafBN8HARQLtZDCz1cTDBz2NDfxRM8TPpODhQA_w3nImhOmMfP7r1Xw)
# [Ruby](https://www.ruby-lang.org/), ~~33~~ 31 bytes
-2 bytes thanks to G B
```
->a,b{a.flat_map{[_1]*b.shift}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGiNNulpSVpuhb7de0SdZKqE_XSchJL4nMTC6qj4w1jtZL0ijMy00pqayGqbroWKKRFRxvqGOkYx-ooQBmxXGBRMx0DIDQDiZvqGAKhAUzG0MBAB4hBMgYgUYhhCxZAaAA)
[Answer]
# [Desmos](https://desmos.com/calculator), 72 bytes
```
f(A,R)=[A[i<=∑_{n=1}^{[1...R.length]}R[n]][1]fori=[0...R.total][2...]]
```
Might post an explanation if I feel like it.
[Try It On Desmos!](https://www.desmos.com/calculator/xnfpltkd6z)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/fnvee6gmm9)
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 4 bytes
```
,/#'
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs9LRV1bn4krT1zBVMARCA2szBQMgNNMEAEY4BM4=)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Takes `R` as the first input.
A byte or 2 could be saved if output could be a 2D-array but I'm guessing a flat array is one of the points of the challenge.
```
cÈÇYgV
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Y8jHWWdW&input=WzUsMSwxLDBdCls2LDAsMCw2XQotUQ)
```
cÈÇYgV :Implicit input of arrays U=R & V=A
c :Flat map U
È :Pass each X at index Y through the following function
Ç : Map the range [0,X)
YgV : Index into V
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes
```
z⟨kj₎t⟩ˢc
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v@rR/BXZWY@a@koezV95elHy///R0WY6BkBoFqsTbapjCIQGsbH/owA "Brachylog – Try It Online")
*-2 bytes thanks to @DLosc*.
*-1 byte thanks to @Kroppeb*
### Explanation
Given inputs `[a1, …, an]` and `[r1, …, rn]`:
```
z Zip: [[a1,r1], ..., [an, rn]]
⟨ ⟩ˢ For each sublist [ai, ri]
k Take [ai]
t Take ri
j₎ Juxtapose the list [ai] ri times to itself
c Concatenate into one list
```
[Answer]
# [Julia 1.0](http://julialang.org/), 23 bytes
```
a^b=vcat(fill.(a,b)...)
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/PzEuybYsObFEIy0zJ0dPI1EnSVNPT0/zf7ShjpGOcWwclFaosVMoKMrMK8nJ44o20zEAQjOgpKmOIRAaoEobGhjoADFQ2gBV6v9/AA "Julia 1.0 – Try It Online")
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~59~~ 55 bytes
* -2 bytes thanks to [@jdt](https://codegolf.stackexchange.com/users/41374/jdt).
```
f(*a,*b,n){for(;n;)~--*b?printf("%d ",*a):a++-b++-n--;}
```
[Try it online!](https://tio.run/##bVDLbsMgEDybr1i5agQ2pKSPHErSfojFAduhXSvFUWz30Mj9dXexq/YSaRdmhhnQUqnq6MLbNHmeOZmVMoiLb8/cBCO@lcrK19MZQ@95eltDKjMnnl2eq5I6KGXG6QZDdRzqA@y6vsZ2/f7CGAXYh8PAP1usBbuwhBRACY1ZoCss7IH0ZCPhXsKDJLiVoOfaRrbRhGhZs2T8TZXXUk/kmktHFi/4D4QlQEZ4pAREnYYDjiQ31NoAwg46/Dq0HgLc/cFCW0OWfE8Q89yK@V1/GvqOpwX9BNC47dALE2W@ckVjJazKeaOInQ8Wu00jGdk4/QA "C (clang) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 9 bytes
```
IΣEθE§ηκι
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FjcNAooy80o0nBOLSzSCS3M1fBMLNAp1FECUY4lnXkpqhUaGjkK2po5CpiYIWC8pTkouhupeHq2kW5ajFLsxOtpQx0jHOFYHSsdC5AE) Link is to verbose version of code. Explanation:
```
θ Array of values
E Map over values
η Array of counts
§ Indexed by
κ Current index
E Map over implicit range
ι Current value
Σ Concatenate arrays
I Cast to string
Implicitly print
```
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 30 bytes
```
param($a,$r)$r|%{,$a[$i++]*$_}
```
[Try it online!](https://tio.run/##hY/RS8MwEMafm7/iGFEal0CrrG9CpeCDL4rzbYwRY8aUdqlJq0Lbv71e2q6PGx@By3c/7r4rza@27qDzXChjdU/3cA9NX0ori5BKTi2jtr1qOJUb@rlcbm/orus7QtKQBDwN0zDmt/yO8bmAscLai7EJS3iESjy44jEqGtCEn4TtGY6jiOPzcDSB2GPQwiOGlOognt@/tKqgIQGGBGrx6b8SLf2BB9Ad@la7Oq/wd41HUYkQmq5WSjuHbngCWsjM8Ufb6s2IJ2eOIDJTlNh0DIT@RnCefAYlweZlndWuMsWYbQsppgsW63Hjwseatnv7YTDkmZGeeh0oe4kaDhnRSzeRoCMd6f8B "PowerShell Core – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes
```
ÅΓ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//cOu5yf//R5vqGAKhQSxXtJmOARCaxQIA "05AB1E – Try It Online")
[Answer]
# Excel (ms365), 60 bytes
```
=IFERROR(TEXTSPLIT(CONCAT(REPT(A1:C1&"|",A2:C2)),"|",,1),"")
```
[](https://i.stack.imgur.com/Jc6ha.png)
---
Or, if you don't mind whole rows as input arrays, for 56 bytes:
```
=IFERROR(TEXTSPLIT(CONCAT(REPT(1:1&"|",2:2)),"|",,1),"")
```
[](https://i.stack.imgur.com/M2Pam.png)
[Answer]
# [simply](https://github.com/ismael-miguel/simply), 87 bytes
The code defines an anonymous function that returns the expected result.
Nothing special here...
```
fn($A$R){$X=[]each$R as$k=>$v;if$v$X=&array_concat($X&array_fill($A[$k]$v))send$X;}
```
## Usage
Just use it normally...
Example using the 2nd test case.
```
$fn = fn($A$R){$X=[]each$R as$k=>$v;if$v$X=&array_concat($X&array_fill($A[$k]$v))send$X;}
// should output: 6,6,6,6,6,0,0
echo &join(call $fn([6,0,0,6], [5,1,1,0]), ',');
```
Since it is an anonymous function, using `call` is required.
## Ungolfed
This code does exactly the same as the golfed version.
This is pretty close to pseudo-code.
```
Set $fn to an anonymous function($A, $R)
Begin.
Define the variable $result = [].
Loop through $R as value $value key $key.
Begin.
If $value then.
Begin.
Set $result to the result of calling &array_concat(
$result,
&array_fill($A[$key], $value)
).
End.
End.
Return the $result.
End.
```
A little further from pseudo-code...
```
$fn = fn($A, $R) => {
$result = [];
foreach $R as $key => $value {
if $value {
$result = &array_concat(
$result,
&array_fill($A[$key], $value)
);
}
}
return $result;
};
```
[Answer]
# [I](https://github.com/mlochbaum/ILanguage), 1 byte
```
\
```
[Try it online!](https://tio.run/##y/z/Xz1NXcFKIea/obWRjrGCggKID2ZzmVkb6BjomIFFTK0NdQx1DLgMDQysgRgsZmBt8B8A "I – Try It Online")
Body must be at least 30 characters; you entered 27.
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-p`, 16 bytes
```
{FA({aRLb}MZab)}
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCJZIiwie0ZBKHthUkxifU1aYWIpfSIsIlAoeVsxIDIgM11bMSAyIDNdKVxuUCh5WzYgMCAwIDZdWzUgMSAxIDBdKVxuKHlbMTAwLDEwMF1bMCwwXSkiLCIiLCItcCJd)
```
{FA({aRLb}MZab)} ; First argument = A = a
; Second argument = B = b
{ } ; Create a function that...
MZab ; maps a and b (as zipped pairs of elements) to...
{aRLb} ; a block that repeats the (first argument) by (second argument)...
FA( ) ; and flattens the resulting list
; (after which the list is implicitly printed out)
```
[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Åaam*─
```
[Try it online.](https://tio.run/##y00syUjPz0n7/z/3cGtiYq7WoykN//9HG@oY6RjHKkBprmgzHQMgNAOKmOoYAqEBUMzQwEAHiIFiQLlYAA)
Or alternatively, with the input-lists swapped:
```
^mæ~Ä_;
```
[Try it online.](https://tio.run/##y00syUjPz0n7/z8u9/CyusMt8db//0cb6hjpGMcqQGmuaFMdQyA0AIqY6RgAoRlQzADMNzQw0AHiWAA)
**Explanation:**
```
m # Map over the first (implicit) input-list,
Å # using two characters as inner code-block:
a # Wrap it into a list
a # Wrap that into a list
# (e.g. [6,0,0,6] → [[[6]],[[0]],[[0]],[[6]]])
m* # Repeat each the second (implicit) input amount of times
# (e.g. [5,1,1,0] and [[[6]],[[0]],[[0]],[[6]]] →
# [[[6,6,6,6,6]],[[0]],[[0]],[[]]])
─ # Flatten it to a single list
# (e.g. [[[6,6,6,6,6]],[[0]],[[0]],[[]]] → [6,6,6,6,6,0,0])
# (after which the entire stack is output implicitly as result)
```
Unfortunately, using `m*` on lists `[6,0,0,6]` and `[5,1,1,0]` results in `[30,0,0,0]` and lists `[[6],[0],[0],[6]]` and `[5,1,1,0]` results in `[[30],[0],[0],[0]]` (apparently..). Hence the need for two wraps before we can use `m*`.
```
^ # Zip the two (implicit) input-lists together
# (e.g. [5,1,1,0] and [6,0,0,6] → [[6,5],[0,1],[0,1],[6,0]]
m # Map over each inner pair,
æ # using 4 characters as inner code-block:
~ # Pop and push the contents of the pair separately to the stack
Ä # Pop the top, and loop that many times:
_ # Duplicate
; # After the inner loop, discard the top item
# (after which the entire stack is output implicitly as result)
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 1 byte
```
Ṙ
```
[Try it online!](https://tio.run/##yygtzv7//@HOGf///4820THVMYv9H22oY6RjHAsA "Husk – Try It Online")
Built-in solution. Input is arg1=R, arg2=A
---
# [Husk](https://github.com/barbuz/Husk), 5 bytes
```
Σz(↑∞
```
[Try it online!](https://tio.run/##yygtzv7//9ziKo1HbRMfdcz7//9/tKGOkY5x7P9oEx1THbNYAA "Husk – Try It Online")
Roll-your-own solution avoiding `Ṙ` built-in.
```
Σz(↑∞
z # zip the two inputs together with
( # combination of functions:
∞ # make an infinite list of copies of arg1
↑ # and then take arg2 elements from it;
Σ # finally, flatten the output
```
] |
[Question]
[
You are given an integer `n` as input, and, regardless of the current date, must return the calendar year (Gregorian calendar, other calendars not allowed) taking place `n` seconds from now.
## Rules
* You may **not** assume that the current year is 2021. In other words, imagine a user testing your solution in five years.
* Standard loopholes forbidden.
* Shortest answer in **bytes** wins.
* Built-in date functions are allowed.
* You must also support negative numbers.
* **On the topic of the year zero: Your answer must follow the ISO specifications, meaning there *is* a year zero.**
* You may assume that the input is always an integer **within bounds of your language number system**.
* If your language's date functions take leap seconds into account, then follow your language, otherwise do not take leap seconds into account.
## Examples (in this case, measured at the time of writing, which is February 15, 2021)
```
100000000000 -> 5190
1000 -> 2021
54398643 -> 2022
54398643234 -> 3744
-100000000000 -> -1148
```
[Answer]
# [Ohm v2](https://github.com/nickbclifford/Ohm), 5 bytes
```
υ!+υy
```
[Try it online!](https://tio.run/##y8/INfr//3yrovb51sr//3UNDRDgv24KAA "Ohm v2 – Try It Online")
**Explanation**:
```
υ!+υy
υ! get the current timestamp in seconds
+ sum with the implicit input
υy get the year from the resulting timestamp
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 16 bytes
```
date -d$1sec +%Y
```
[Try it online!](https://tio.run/##S0oszvifqKGpUP0/JbEkVUE3RcWwODVZQVs18n8tF1eigqEBAkC5QMrUxNjSwszEGIlpZGwC5Okiq/8PAA "Bash – Try It Online")
### Credits
* Saved 12 bytes thanks to @manatwork
[Answer]
# [PHP](https://php.net/), 27 bytes
```
<?=date(Y,time()+$argv[1]);
```
[Try it online!](https://tio.run/##K8go@P/fxt42JbEkVSNSpyQzN1VDU1slsSi9LNowVtP6////hgYIoAAA "PHP – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 116 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
"`т‰0Kθ4ÖUD2Qi\28X+ë<7%É31α}"Vžežfžg)IŽª+·÷ÄF©IdiY.V‹i®¬>0ë®1¾ǝDÅsD12‹i>1ë\1Dǝ¤>2}}ǝëć©ić©i<D_-12š31šë®<šDY.Všë®<š]θ
```
Here we go again..
[Try it online](https://tio.run/##yy9OTMpM/f9fKeFi06OGDQbe53aYHJ4W6mIUmBljZBGhfXi1jbnq4U5jw3Mba5XCju5LPbov7ei@dE3Po3sPrdI@tP3w9sMtbodWeqZkRuqFPWrYmXlo3aE1dgaHVx9aZ3ho3/G5Lodbi10MjUAydoaHV8cYuhyfe2iJnVFt7fG5h1cfaT@0MhNM2LjE6xoaHV1obHh0IUizzdGFLkAT4ZzYczv@/9c1NTG2tDAzMQYA) or [try it only with custom specified starting date](https://tio.run/##PYy/S8NAHMX3/hVfAlJLidwlRauETkEo0kGwRSGisXfaA/OD3GXoECiiiP@AW4eCS40UnVoHHe4M2Qr@C/1HYtrBNzx4vM97AXevGC20LqfgQj/mIvCACzcSzL8B4goKIoAwooL6BJgAxiGKfQh8EANXlMTwADSnop0MKDA/jDcEW7cUroPIK5kqIdDpwLBUFbZ56PapTugt85igpLaZV7AJGAFCyCi0y9@71egdHS0XDfXctY1j5hjN07pKrb0t9WTi5Uei9Wrt7Eu@1uVczdX9oZy2CTvb6a1Gn0zO5FsLqVTOsPzOx7Z64DY21k0Lq9TBdj6WLy0jSfKxSn8e5ZRtzLIvdGxkExNnk/XYyiZ2@fgfzpeLotAxapj7zd2G@Qc). (Pretty slow for large inputs, so won't be able to output the larger test cases with the current date.)
**Explanation:**
Since 05AB1E doesn't have any date builtins (except for the current day/time), I've calculated things manually before. I've used the code of going to the next day from [this answer of mine](https://codegolf.stackexchange.com/a/173126/52210), which in turns also uses the leap year calculation of [this answer of mine](https://codegolf.stackexchange.com/a/177019/52210).
Since this challenge also asks to go back in time, I've modified the program accordingly to support that as well.
Step 1: Create a function to calculate the amount of days in a month for a given year/month:
```
"`т‰0Kθ4ÖUD2Qi\28X+ë<7%É31α}" # Push this string
V # Pop and store it in variable `Y`
` # Pop the list and push all values separated to the stack
# (the year will be at the top; month below it)
т‰ # Take the divmod-100 of the year
0K # Remove the 0s
θ # Pop and push its last item
4Ö # Check if it's divisible by 4
U # Pop and store this in variable `X`
# (X=1 for leap years; X=0 for non-leap years)
D # Duplicate the current month
2Qi # If it's equal to 2 (thus February):
\ # Discard the duplicated month
28X+ # Push 28 + isLeapYear from variable `X`
ë # Else:
< # Decrease the month by 1
7% # Modulo-7
É # Modulo-2
31α # Absolute difference with 31
} # Close the if-else statement
```
Step 2: Now we determine the current date, and loop an amount of times depending on the input:
```
že # Push the current day
žf # Push the current month
žg # Push the current year
) # Wrap all three into a list
I # Push the input-integer
Žª+ # Push compressed integer 42300
· # Double it to 84600 (60*60*24)
÷ # Integer-divide the input by 84600
Ä # Take its absolute value
F # And loop that many times:
```
Step 3: If the input was positive, calculate the next date:
```
© # Store the current date in variable `®` (without popping)
Idi # If the input is non-negative:
Y.V # Execute string `Y` as 05AB1E code to get the amount
# of days for the current month/year
‹i # If this is smaller than the current days:
® # Push the current date again
¬ # Get its first item (the days)
> # Increase the day by 1
0 # Push index 0
ë # Else:
® # Push the current date again
1 # Push day=1
¾ # Push index 0
ǝ # Insert days=1 at index 0 into the date
D # Duplicate it
Ås # Pop and push its middle item (the month)
D # Duplicate that month
12‹i # If it's smaller than 12:
> # Increase the month by 1
1 # Push index 1
ë # Else:
\ # Discard the duplicated month
1 # Push month=1
D # Push index 1
ǝ # Insert month=1 at index 1 into the date
¤ # Push its last item (the year)
> # Increase the year by 1
2 # Push index 2
} # Close the if-else statement
} # Close the if-else statement
ǝ # Insert the value at the given index into the date
```
Step 4: If the input was negative instead, calculate the previous date:
```
ë # Else (the input is negative):
ć # Extract head; push [month,year] and day separated
© # Store the day in variable `®` (without popping)
i # If day == 1:
ć # Extract head; push [year] and month separated
© # Store the month in variable `®` (without popping)
i # If month == 1:
< # Decrease the [year] by 1
D # Duplicate it
_ # Check if it's equal to 0 (1 if 0; 0 otherwise)
- # Subtract that (so we go from year 1 to -1)
12š31š # Prepend 12 and 31: [31,12,year-1-(year-1==0)]
ë # Else:
®<š # Prepend month-1 to the [year] list
D # Duplicate it
Y.V # Execute string `Y` as 05AB1E code to get the amount
# of days for this month/year
š # Prepend this to the [month-1,year] list
ë # Else:
®<š # Prepend day-1 to the [month,year] list
```
Step 5: After the loop, extract the year to output:
```
] # Close both the if-else and loop
θ # Pop the date, and only leave its last item (the year)
# (after which it is output implicitly as result)
```
[See this 05AB1E tips of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Žª+` is `42300`.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 21 bytes
```
->n{[*Time.now+n][5]}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOlorJDM3VS8vv1w7LzbaNLb2f4mCrUI0l4KCoQEC6ChABcAMUxNjSwszE2MUjpGxCVcsV4leamJyhkK1Qk1ejUKBQlp0XqxCLaaoLkj4PwA "Ruby – Try It Online")
Shorter by a byte than the more obvious `->n{(Time.now+n).year}`.
[Answer]
# [Octave](https://www.gnu.org/software/octave/) / MATLAB, 27 bytes
```
@(x)datestr(x/86400+now,10)
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0IzJbEktbikSKNC38LMxMBAOy@/XMfQQPN/moahAQJockH4INrUxNgSqNYYmW1kbALi6qLo@Q8A "Octave – Try It Online")
### How it works
```
@(x) % Define anonymous function with input x
x/86400 % Divide input by 86400, to convert to days
now % Current time in days since "January 0, 0000"
+ % Add
datestr( ,10) % Convert to string with format 10, which is year
```
[Answer]
# JavaScript (ES6), 42 bytes
```
n=>new Date(+new Date+n*1e3).getFullYear()
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1i4vtVzBJbEkVUMbxtLO0zJMNdbUS08tcSvNyYlMTSzS0PyfnJ9XnJ@TqpeTn66RpmFogACamgr6@gqmhpYGXJiKgJIwAFRkZGBkiKbI1MTY0sLMxBiqEKLICIciI2MTkDqgImNzE5P/AA "JavaScript (Node.js) – Try It Online")
[Answer]
# [jq](https://stedolan.github.io/jq/), ~~20~~ 15 characters
```
now+.|gmtime[0]
```
Sample run:
```
bash-5.0$ jq 'now+.|gmtime[0]' <<< 100000000000
5190
```
[Try it online!](https://tio.run/##yyr8/z8vv1xbryY9tyQzNzXaIPb/f0MDBOACcbhMTYwtLcxMjOEMI2MTLl1kdQA "jq – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~32~~ ~~26~~ 23 bytes
```
date|% *dds* @args|% y*
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/PyWxJLVGVUErJaVYS8EhsSi9GMir1Pr//7@hAQIAAA "PowerShell – Try It Online")
-3 bytes thanks to mazzy and ZaelinGoodman
[Answer]
# [Python 3](https://docs.python.org/3/), ~~74~~ ~~72~~ 65 bytes
```
lambda x:(date.today()+timedelta(0,x)).year
from datetime import*
```
[Try it online!](https://tio.run/##FcrBCoQgEADQe1/hcaYNibSlXehPukyoJGSKzCG/fqLze6XxkS8jYd3kpLQ7UvcfHLHXnB01wA/H5J0/mWAcbkTdPNUu1JzU215VMZVcuZdS48UQYLbmt3ytmYxFFHkA "Python 3 – Try It Online")
-7 bytes thanks to @Eric
[Answer]
# [Japt](https://petershaggynoble.github.io/Japt-Interpreter), ~~12~~ 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ÐKj +Ue3)i
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=0EtqICtVZTMpaQ&input=MTAwMDAwMDAwMDAw)
-2 bytes from AZTECCO.
This transpiles to the following JS:
```
new Date(K.j() + U * 1e3).i()
```
where `K.j()` is the current time converted to milliseconds, `U` is the input, and `.i()` gets the year from the date constructor.
[Answer]
# R, 12 bytes
```
Sys.time()+n
```
This returns a full date, the year is at the beginning of the string. This is according to the rules, which didn't say to print *just* the year; and this is not in the [list of "standard loopholes"](https://codegolf.meta.stackexchange.com/q/1061) by the time of this answer.
To print *just* a year, R would need 25 bytes:
```
format(Sys.time()+n,"%Y")
```
[Answer]
# IBM/Lotus Notes Formula Language, ~~34~~ 32 Bytes
```
@Year(@Adjust(@Now;0;0;0;0;0;i))
```
Takes input from a field named `i`. Unfortunately, Formula only supports 32 bit signed integers so it is restricted to a maximum input of +/- 2,147,483,647.
There is no TIO for Formula so here are a couple of screenshots:
[](https://i.stack.imgur.com/wx7iU.png)
[](https://i.stack.imgur.com/PKFax.png)
[](https://i.stack.imgur.com/7XJaw.png)
[](https://i.stack.imgur.com/OQ4Be.png)
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 11 bytes
```
12L/Z'+10XO
```
Try it out at [MATL Online](https://matl.io/?code=12L%2FZ%27%2B10XO&inputs=54398643&version=22.4.0)
**Explanation**
```
% Implicitly grab input as an integer (seconds)
12L % Push the literal 86400 to the stack (seconds in a day)
/ % Divide the input (in seconds) by the seconds in a day to convert to days
Z' % Get the current time in days as a float
+ % Add the current time and the seconds in the future together
10XQ % Determine the year of this date
% Implicitly display the result
```
[Answer]
# [Julia](http://julialang.org/), 38 bytes
```
using Dates
f(x)=Year(now()+Second(x))
```
[Try it online!](https://tio.run/##Xc3BCoMwDAbge54ix5YhmLZuenCnvcFOQzzIrKND4rDKfPvOytjY/kvI90Nyn3vX0BLC7B3f8NRM1kMnFllebDMKHp5C7s72OnC7ogxrPXkssQJKv8HyiBkV6YZxUakiyIwu8r3Rb1AfUNpE0wdjIPm/kxCZHGqAbhgxvkPH2/SAax6j46lnEUX@SLdZRbWUYLkNLw "Julia 1.0 – Try It Online")
[Answer]
# [Raku](http://raku.org/), 28 bytes
```
{DateTime.new($_+time).year}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/2iWxJDUkMzdVLy@1XEMlXrsEyNbUq0xNLKr9X5xYqaCkEq/waN5Cheo0BZX4WiWFtPwiBRtDAwRQAHEUTE2MLS3MTIzhDCNjEwVdZHV2/wE "Perl 6 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 51 bytes
```
lambda x:gmtime(time()+x).tm_year
from time import*
```
[Try it online!](https://tio.run/##TYpBCsIwFAX3PcWjq0RTsSaKLdSLqEjERgP@JIQs0tNH7abOYngML0zp5Z0sBgMu5a3p/tDI/ZOSpZHN4uvMN4lu06hjZaIn/DIsBR/TqhgfkWEdzu12QaCdvVeyOx6UXNZOKoHm/3vtK3wJ0brEskDdnGoBwzLn5QM "Python 3 – Try It Online")
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 30
```
$1=strftime("%Y",$1+systime())
```
[Try it online!](https://tio.run/##SyzP/v9fxdC2uKQorSQzN1VDSTVSSUfFULu4shjM19T8/9/QAAG4QBwuUxNjSwszE2M4w8jYhEsXRR0A "AWK – Try It Online")
* 5 bytes saved thanks to @manatwork.
[Answer]
# GNU coreutils (16 bytes)
```
date +%Y -d$1sec
```
Saved 4 bytes, thanks to @ovs.
[Answer]
# MySQL, 35 bytes
`select year(now()+interval [input] second)`
[Answer]
# [Java (JDK)](http://jdk.java.net/), 57 bytes
```
n->java.time.LocalDateTime.now().plusSeconds(n).getYear()
```
[Try it online!](https://tio.run/##lY9BS8QwEIXv/RVzTIQG11ZRFhcEEYR66l5EPIxpWlLTSWimK4vsb6@xCF481LkMj3nvfUyPB8z75n22Q/AjQ5@0mtg61U6k2XpSZ9ss0w5jhCe0BJ8ZQJjenNUQGTmtg7cNDOkmah4tdS@vgGMX5WIFqDx1e/9I/PDTCO3tTPluQbEdjKq8RnePbPbfivyHkCq4KdZGe2qiIKk6w88GRyHn7VJaHyObQfmJVUhMdiRahSG4411MKLE5/51KyvWh1ebLsri5viqLfwcuinJ1Jv/jj1N2mr8A "Java (JDK) – Try It Online")
Beats the `Date` API (71 bytes):
```
n->new java.util.Date(System.currentTimeMillis()+n*1000).getYear()+1900
```
[Try it online!](https://tio.run/##lY/BSgMxEIbv@xRzTCobUncVS1EQRBDaU3sR8RC32SVrdhKSSaVIn32NpYIHD@tchpn5v/lnerVXZb97H83gXSDocy0SGSvahA0Zh2K2LIrGqhhhrQzCZwHg05s1DURSlNPemR0MecY2FAx2L6@gQhf5SQqwctht3RPS43kjtLcjlneoP37ZPSjSbHOIpAfRpBA00tYMem2sNZHxC5zNpZRcdJqetQq5M19IOS5PFmfOJRI@X0AWWSuU9/ZwH7Mx@0Z/YsX5dGiy@KquFjfXdfVv4LKqJzPlH38ci@P4BQ "Java (JDK) – Try It Online")
Note that this one returns the year in absolute form (no negative year).
And I don't even speak about the Calendar API.
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 98 bytes
```
public class E{public static void m(double x){Console.WriteLine(DateTime.Now.AddSeconds(x).Year);}
```
[Try it online!](https://tio.run/##bYyxCgIxEER/JWVSGLS@Ss7r1OYEscwliywkWcnm9CTct8cUgo3TDG94jOWNpQR1Zox3Mb45Q@jqY548WmG9YRZD@SJnk1s9CZ0I0lFbQSyq9BSZPOhrwgxHjCAPJsMFA@gzvfTeuREsRcdyUfoGJqlurX8@TwajVGXQQe62vzR7rR8 "C# (.NET Core) – Try It Online")
Didn't count the `using System;` and calling function in `Main()`, if they needed to be added, please inform me!
[Answer]
# [Visual Basic .NET (VBC)](http://www.mono-project.com/docs/about-mono/releases/5.12.0/#vbnet-compiler), 89 bytes
```
public class E
Shared sub m(x)
Console.WriteLine(DateTime.Now.AddSeconds(x).Year)
end Sub
```
[Try it online!](https://tio.run/##Tc69CsIwFAXgPU@RMR0a9BGkdhC0SwRxzM8FL@Sn5CZVnz5WHfQsZ/k4nAWpat8bTWj7CKVfjG2HMKdciKsnFQhtrsaj5dZrIj4yddMZHKdqeBCPjg0pUvIgLxkLHDGC2OsCZwwgp3SXO@cU2BQdrVheQeeOQXRcVdP@pk4ao@jYKIPYbn752hV8enhfaC8 "Visual Basic .NET (VBC) – Try It Online")
[Answer]
# VBScript, 52 bytes
```
MsgBox Year(DateAdd("s",Wscript.Arguments(0),Now())
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 34 bytes
```
x=>DateTime.Now.AddSeconds(x).Year
```
[Try it online!](https://tio.run/##Sy7WTS7O/O9Wmpdsk5JfmpSTqpOZV2KXZvu/wtbOJbEkNSQzN1XPL79czzElJTg1OT8vpVijQlMvMjWx6L81V1p@UWpicoZGWWKRQrJCZp5CXmp5dKxCtaEBAugoGIJJUxNjSwszE2MEy8jYpFaTK7wosyTVJzMvVUNFqTq5VkHXTqE6TSNZs1ZJ0/o/AA "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [AppleScript](https://developer.apple.com/library/archive/documentation/AppleScript/Conceptual/AppleScriptLangGuide/introduction/ASLR_intro.html) function, 46
```
to y(s)
(current date+s/60*minutes)'s year
end
```
### Test driver:
```
repeat with sec in {100000000000, 1000, 54398643, 54398643234, -100000000000}
log y(sec)
end repeat
```
Save the function and the test driver as text to `nseconds.applescript`, then run in the terminal:
```
osascript nseconds.applescript
```
Or run in the AppleScript Editor app.
[Answer]
# T-SQL, 42 bytes
```
select year(dateadd(s,a,getdate()))from t;
```
Uses the standard input method for T-SQL of taking input from a table. You can create a suitable table like this:
```
create table t (a int not null);
insert into t values (1000000000), (1000), (54398643), (-1000000000);
```
Note that T-SQL is limited to 32-bit integers for the number of seconds. To avoid that and allow the resulting year to vary between 0 and 9999 costs 6 bytes:
```
select year(dateadd(d,a/86400,getdate()))from t;
```
Don't forget to declare `a` as `bigint` if you do this. (Note that hours is represented by `hh` so it's no shorter, and minutes won't let you reach 9999.)
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 20 [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, prompting for `n` from stdin.
```
⊃⊃20 ¯1⎕DT⎕+20⎕DT'J'
```
`20⎕DT'J'` get current local\* (**J**uliett) **D**ate**T**ime as UNIX time (code 20; seconds from beginning of 1970)
`⎕+` prompt for `n` and use that to increment the UNIX time.
`20 ¯1` interpret as UNIX times (code 20) and convert to an array of time stamps (code -1)
`⊃` extract the first (and only) time stamp
`⊃` extract the first element (the year)
[Try APL!](https://tryapl.org/?clear&q=%7B%E2%8A%83%E2%8A%8320%20%C2%AF1%E2%8E%95DT%E2%8D%B5%2B20%E2%8E%95DT%27J%27%7D%C2%A810000000000%201000%2054398643%2054398643234%20%C2%AF1000000000&run "TryAPL") (first and last case scaled down by a factor of 10 to avoid hitting date-time limits, 1 January 0001 though 28 February 4000; turned into function for ease of use)
\* could also have `'Z'` (**Z**ulu) to use the current UTC time instead of local time.
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 23 bytes
```
$_=gmtime$^T+$_;s/.* //
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3jY9tyQzN1UlLkRbJd66WF9PS0Ff//9/QwMEUNC1UzA1tDTgMoRyjAyMDLlMTYwtLcxMjKECRnABI2MTkJixuYkJly66ObqGhiYW//ILSjLz84r/6xbkAAA "Perl 5 – Try It Online")
[Answer]
# Mathematica, 43 bytes
```
IntegerPart@DatePlus[#/86400]["YearExact"]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78H1iamVoSHVCUmVei76Dx3zOvJDU9tSggsajEwSWxJDUgp7Q4WlnfwszEwCA2WikyNbHItSIxuUQpVu2/vkO1oQEC6IA4OqYmxpZA1cZwhpGxiY4usrpazdj/AA "Wolfram Language (Mathematica) – Try It Online")
Thanks to [@LegionMammal978](https://codegolf.stackexchange.com/users/33208/legionmammal978) for hinting that `DatePlus[#/86400][[1,1]]&` fails for negative years
] |
[Question]
[
Given a non-negative integer, print out an `X` that is that big. `X` is the output for input `0`, and you will add slashes equal to the input in each direction to extend the `X` for larger inputs.
# Test Cases
0
```
X
```
1
```
\ /
X
/ \
```
2
```
\ /
\ /
X
/ \
/ \
```
...
10
```
\ /
\ /
\ /
\ /
\ /
\ /
\ /
\ /
\ /
\ /
X
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
```
# Rules
You may either print the output, or return a string or list of string from a function. A trailing newline, as well as extra interior whitespace that does not affect appear, is allowed.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins!
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 6 bytes
```
PX⁺¹NX
```
Your nonsense ain't stopping me ;)
[Try it online!](https://tio.run/##S85ILErOT8z5///9ng0Rjxp3Hdr5fs@6iP//DQE "Charcoal – Try It Online")
[Answer]
## JavaScript (ES6), 79 bytes
Uses a recursive function **g** that walks through a grid and builds the output character by character.
```
n=>(g=x=>`/\\ X
`[~x?x-y?x+y-w&&2:x-n?1:3:4]+(~y?g(~x--?x:y--&&w):''))(y=w=n*2)
```
### How?
Both variables **x** and **y** iterate from **2n** to **-1**, where **n** is the input.
For each position **(x, y)** in the grid, we pick one of these characters:
* 0: `/`
* 1: `\`
* 2: space
* 3: `X`
* 4: newline
using the following tests:
* `~x`: Falsy if **x == -1**: we've reached an end of line.
* `x-y`: Falsy if **x == y**: we're located on the anti-diagonal.
* `x+y-w`: Falsy if **x + y == w**: we're located on the diagonal.
* `x-n`: Falsy if **x == n**: because this test is only performed when **x == y**, this means that we're located in the exact center of the grid.
and the following decision tree:
[](https://i.stack.imgur.com/GOOvy.png)
### Demo
```
let f =
n=>(g=x=>`/\\ X
`[~x?x-y?x+y-w&&2:x-n?1:3:4]+(~y?g(~x--?x:y--&&w):''))(y=w=n*2)
console.log(f(0))
console.log(f(1))
console.log(f(4))
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 16 bytes
```
'\/X 'iEQXytEP+)
```
[Try it online!](https://tio.run/##y00syfn/Xz1GP0JBPdM1MKKyxDVAW/P/fyMA "MATL – Try It Online")
Consider input `2` as an example. The stack is shown here upside down, i.e. lower elements are the ones most recently pushed.
```
'\/X ' % Push this string
% STACK: '\/X '
iEQ % Input a number, n. Multiply by 2, add 1: gives 2*n+1
% STACK: '\/X '
5
Xy % Identity matrix of that size
% STACK: '\/X '
[1 0 0 0 0;
0 1 0 0 0;
0 0 1 0 0;
0 0 0 1 0;
0 0 0 0 1]
tEP % Duplicate, multiply each entry by 2, flip vertically
% STACK: '\/X '
[1 0 0 0 0;
0 1 0 0 0;
0 0 1 0 0;
0 0 0 1 0;
0 0 0 0 1]
[0 0 0 0 2;
0 0 0 2 0;
0 0 2 0 0;
0 2 0 0 0;
2 0 0 0 0]
+ % Add the two matrices
% STACK: '\/X '
[1 0 0 0 2;
0 1 0 2 0;
0 0 3 0 0;
0 2 0 1 0;
2 0 0 0 1]
) % Index into the string. Indexing is 1-based and modular, so 1 picks
% the first character ('\'), ..., 0 picks the last (space)
% STACK: ['\ /';
' \ / ';
' X ';
' / \ ';
'/ \']
% Implicit display
```
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 3 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
╵\┼
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXUyNTc1JXVGRjNDJXUyNTND,i=Mw__,v=2)
half of the size of the Charcoal answer :D
```
╵ increment the input
\ create a diagonal that long
┼ and quad-palindromize, mirroring what's required, with 1 overlap;
This overlaps the `/` and `\`, resulting in `X`
```
[Answer]
# C, ~~108~~ ~~106~~ 104 bytes
```
a;g(n){for(int b=2*n,i=1,c=47;a+=i;!b?i=-i,c=92:puts(""),b-=2*i)printf("%*c%*c",a,b?c^115:88,b,b?c:10);}
```
[Try it online!](https://tio.run/##FY3BCsIwEER/RQPCbt2AqRbbhNA/EZKFhj0YS21PxW@PKcxlHm8Y1om5lOASZNynzwKS11P0bZNJvCH2j6cLVy/uHEfxWioZWjtv6xeUQoq6qoLzUmcTqEvDNYoCxZFfxnS27ykexZobul95B8mAe4IO6@X9QH8 "C (gcc) – Try It Online")
(−2 golfing thanks to MD XF)
(−1 golfing thanks to ceilingcat)
It prints two characters (at first, `c = 47`, which is a slash, and `c + 45`, which is a backslash; then they are swapped) with a dynamic field width.
The field widths start at `1` and `2n`, and at each iteration, the first width is incremented by 1, and the second one is decremented by 2.
When the second field width becomes 0, it outputs `'X'` and a newline instead of the regular characters, and reverses the direction of increments (`i`). A newline is printed for all other lines separately (`puts("")`).
[Answer]
# [shortC](https://github.com/aaronryank/shortC), 111 bytes
```
s(x){Wx--)R" ")}j;f(x){O;j<x;j++)s(j),P92),s((x-j)*2-1),R"/\n");s(x);R"X\n");Wj--)s(j),P47),s((x-j)*2-1),R"\\\n
```
Based on [my C answer](https://codegolf.stackexchange.com/a/125419/61563). Conversions:
* `R` -> `printf(`
* `P` -> `putchar(`
* `W` -> `while(`
* `O` -> `for(`
* Auto-inserted closing `");}`
This also uses ASCII codes for `\` and `/`.
[Try it online!](https://tio.run/##K87ILypJ/p@bmJmnoVnNlaZhaKBpzVX7v1ijQrM6vEJXVzNISUFJszbLOg0k4m@dZVNhnaWtrVmskaWpE2BppKlTrKFRoZulqWWka6ipE6SkH5OnpGkN0m8dpBQB5oRnAc2BaDAxx9AQExOT9/8/AA "shortC – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 81 bytes
```
r=range(2*input()+1)
for i in r:print''.join(' \/X'[i==j::2][r[~i]==j]for j in r)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v8i2KDEvPVXDSCszr6C0RENT21CTKy2/SCFTITNPociqoCgzr0RdXS8rPzNPQ10hRj9CPTrT1jbLysooNrooui4zFsiJBWnIAmvQ/P/fCAA "Python 2 – Try It Online")
[Answer]
# C, ~~168~~ ~~155~~ 150 bytes
-5 thanks to Computronium
```
#define p printf(
s(x){while(x--)p" ");}j;f(x){for(;j<x;j++)s(j),p"\\"),s((x-j)*2-1),p"/\n");s(x);p"X\n");while(j--)s(j),p"/"),s((x-j)*2-1),p"\\\n");}
```
Can certainly be golfed; I'm doing so. [Try it online!](https://tio.run/##bYxBDsIgEEX3nILUzYwtqXU7PYgLNgZBIYqkmEjScHakGHcu/8x7T4mrUqXsLtpYr3ngYbH@ZViEhOv7Zu8akhAYoOMdUnZktod5LkBuTuT6HiM4HCogZYdDhMo73B/F1I6j9NXbalTXqa1v1tXsTx3/mFI2OJfH2XrAlRmYDkgslw8)
Ungolfed:
```
int space(int x)
{
while (x--)
putchar(' ');
}
int f(int x)
{
for (int j = 0; j < x; j++) {
space(j);
printf("\\");
space((x-j)*2-1);
printf("/\n");
}
space(x);
puts("X");
while (j--) {
space(j);
putchar('/');
space((x-j)*2-1);
printf("\\\n");
}
}
```
[Answer]
# [V](https://github.com/DJMcMayhem/V), 21 bytes
```
éXÀñ>HÄÒ r\Á/YGpr/$r\
```
[Try it online!](https://tio.run/##K/v///DKiMMNhzfaeRxuOTxJoSjmcKN@pHtBkb5KUcz///9NAQ "V – Try It Online")
Hexdump:
```
00000000: e958 c0f1 3e48 c4d2 2072 5cc1 2f59 4770 .X..>H.. r\./YGp
00000010: 722f 2472 5c r/$r\
```
Explanation:
```
éX " Insert an 'X'
Àñ " Arg1 times:
>H " Add a space to every line.
" Conveniently, this also puts us on the first line
Ä " Duplicate this line
Ò " And replace the whole line with spaces
r\ " Replace the first char with '\'
Á/ " Append a '/' char
Y " Yank this line
G " Move to the last line
p " And paste the line we yanked
r/ " Replace the first character with a '/'
$ " Move to the end of the line
r\ " And replace the last character with a '\'
```
Essentially, we have *Insert an X, n times extend the slashes*.
But it's not quite that simple because we also have to add the slashes the first time. If the slashes were already there, we could write *extend the slashes* as:
```
>HÄX2pGÙX2p
```
Which would save us 6 bytes.
[Answer]
# C#, 157 122 120 bytes
```
_=d=>"".PadLeft(d)
a=>{var s=_(a)+"X\n";for(int i=0;++i<=a;)s=$@"{_(a-i)}\{_(i*2-1)}/
{s+_(a-i)}/{_(i*2-1)}\
";return s;}
```
Ungolfed version:
```
Func<int, string> _ = (d) =>"".PadLeft(d);
Func<int, string> func = a => {
var s = _(a) + "X\n";
for (int i = 0; ++i <= a;) {
s = $@"{_(a - i)}\{_(i * 2 - 1)}/
{s + _(a - i)}/{_(i * 2 - 1)}\
";
}
return s;
};
```
[Answer]
## Mathematica, 71 bytes
*(Partially inspired by Jenny\_mathy's 104-byte solution)*
```
""<>#&/@(#"\\"+Reverse@#"/"&@IdentityMatrix[2#+1]/.{0->" ",a_+_->"X"})&
```
Returns a list of strings.
Explanation: `IdentityMatrix[2#+1]` makes a matrix of the right size with 1s along the diagonal and 0s elsewhere. Next, we multiply it by `"\\"` (an escaped backslash), which makes it a matrix with backslashes along the diagonal and 0s elsewhere, since of course 1 times backslash is backslash and 0 times backslash is 0. We add this to `"/"` times its reverse to make the X shape. We're nearly done, except there are still 0s everywhere, and the middle is `"\\" + "/"`. We fix these two things by substituting `" "` for `0` and `"X"` for `a_+_`, which matches any sum of two things (like `_+_` should, except Mathematica is too clever for its own good and interprets that as 2 times `_`). Finally, `""<>#&/@` turns this into a list of strings.
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 135 bytes
```
i->{int k=0,j,l=2*i+1;String[]s=new String[l];for(;k<l;k++)for(s[k]="",j=0;j<l;j++)s[k]+=j==k?j==i?"X":"\\":j==l-1-k?"/":" ";return s;}
```
Lambda expression that takes and integer and returns an array of Strings
[Try it online!](https://tio.run/##NY89b4MwEIZn8itOnqCAm7QbjsNWqUOnLJUSBpcY5I8YhE2qKOK300MNy3089753Oi1uIu966fTFzP34Y1UNtRXew5dQ7rGJnswHETDdOnWBK07iYxiUa08ViKH1CQojjavoGJSlzejqoDpHP57F/tMF2cohg9V2gAY4zCo/PJQLYPg205nlby8q3bFV5LmTv6vFVqzphpiZvWUmTZOl8SdTcUIyzbdMI9fIF5ZyzbkpMaiSfJOCnM@kwM7mu9yU5BUJEDbIMA4OPJvmKGL4wbLy/xp4KKChou/tPX5PEjjefZBX2o2B9igI1sU@Qc@0meY/ "Java (OpenJDK 8) – Try It Online")
Ungolfed:
```
i->{
int k=0,j,l=2*i+1; // Some variables to be used
String[]s=new String[l]; // Return array (size 2*i+1)
for(;k<l;k++) // For each array entry
for(s[k]="",j=0;j<l;j++) // Set each character to
s[k]+=j==k?j==i?"X":"\\" // \ or X if it's the jth character of the jth row
:j==l-1-k?"/" // / if it's the opposite char
:" "; // else blank
return s;
}
```
[Answer]
# T-SQL, 201 bytes
```
DECLARE @ INT SELECT @=a FROM t DECLARE @i INT=@
WHILE @>0BEGIN PRINT SPACE(@i-@)+'\'+SPACE(2*@-1)+'/'SET @-=1 END
PRINT SPACE(@i)+'X'WHILE @<@i BEGIN SET @+=1 PRINT SPACE(@i-@)+'/'+SPACE(2*@-1)+'\'END
```
Formatted:
```
DECLARE @ INT
SELECT @=a FROM t
DECLARE @i INT=@
WHILE @>0
BEGIN
PRINT SPACE(@i-@)+'\'+SPACE(2*@-1)+'/'
SET @-=1
END
PRINT SPACE(@i)+'X'
WHILE @<@i
BEGIN
SET @+=1
PRINT SPACE(@i-@)+'/'+SPACE(2*@-1)+'\'
END
```
Input is via column **a** in named table **t**, [per our guidelines](https://codegolf.meta.stackexchange.com/a/5341/70172).
[Answer]
# [Ruby](https://www.ruby-lang.org/), 66 bytes
Recursive function.
```
f=->x{?X[x]||"\\#{s=' '*(2*x-1)}/
#{f[x-1].gsub /^/,' '}
/#{s}\\"}
```
[Try it online!](https://tio.run/##KypNqvz/P81W166i2j4iuiK2pkYpJka5uthWXUFdS8NIq0LXULNWn0u5Oi0ayIzVSy8uTVLQj9PXAcrXcukDVdbGxCjV/i8oLSlWSItOTy0p1ivJj8@M/W9oAAA "Ruby – Try It Online")
### Explanation
```
f=->x{ # Start of recursive function named `f`
?X[x]|| # Return 'X' if x==0, otherwise the following:
"\\#{s=' '*(2x-1)}/ # Top edge of the cross. Save no. of spaces needed
#{f[x-1] # Get result of f[x-1]
.gsub /^/,' '} # Regex sub to left-pad every line w/ a space
/#{s}\\" # Bottom edge of cross (insert saved no. of spaces)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~24~~ 17 bytes
```
Ḥ‘=þ`µḤ+Uị“/\x ”Y
```
[Try it online!](https://tio.run/##y0rNyan8///hjiWPGmbYHt6XcGgrkK0d@nB396OGOfoxFQqPGuZG/v//3xQA "Jelly – Try It Online")
**How it Works**
```
Ḥ‘=þ`µḤ+Uị“/\x ”Y main link, input a
Ḥ‘ input doubled and incremented
þ Make a table: Apply
= "equals"/ to
` each element in range(2a+1) cartesian multiplied with itself.
eg. For input 1: [1=1,1=2,1=3],[2=1,2=2,2=3],[3=1,3=2,3=3]
µ on this array:
+ add:
Ḥ double of it to
U its reverse (changes south-east to north-west)
ị“/\x ” index into the string "/\x " to get the right characters
Y join by newlines for the final output.
```
*-6 bytes thanks to @LeakyNun* and *-1 byte with an additional improvement*
[Answer]
# [///](https://esolangs.org/wiki////), 223 bytes
```
/|/\\\\//i///& / &// &///> /^b|b^v|v^^$|+^
f|fvv&i|||^$|-^^$|-^$|+^^<|$^<-|$>|->vv&i||||
^^<-|$^<|$^^f|f| ^ f|f^^>|->| ^ >|->^^f|fv|v^||||^^>|->v|v^|||^^^v|v ^ b|b^>//^/\///b\/>/b\/\/$|+\/\/\/<|$\/\///>$+//>i$+
iX/<$//
<$
```
[Try it online!](https://tio.run/##LU5BCsMwDLvnFT6YXErRB0LesUMQrLDSwG6FnPz3zM4asIQiGfn@vu/rc88JQ/MHdABZIJKBGFQBDzs4bJBqG9Np5xi5m5nrnQvCYDFl2U2r7fVJWOL6Wh5904TiREYoRPByoiA2/tajyCgWz8UNFSD8SBwNNaDBi4MavKAtr@rm0HVL/YWiQCo65w8 "/// – Try It Online")
Seems like a fitting language for the challenge. (suck it, sed)
Input is given in unary spaces, after `/i/`:
```
/|/\\\\//i/<spaces here>//& / &// &///...
```
Explanation:
don't ask me, I only programmed it ;)
[sorta commented version, lightly ungolfed version](https://tio.run/##VVTbbtswDH3PVxBp0IsbR@9DYPRl@4ENRYFpBmSLroXYkiHJdrOf70gp6do8KBTvPDp0GFToMby/iz@b3yIdRhT5JwQcSzB2miOdMFvlz7Ca2IMKEb0Jp0B6EpUG10GYVIsBgoOzm6FVFlQbZzUMZwiIEHscIVe4LajELaXX8zSYVkXMVbKVLQLC3ERPCcBZinXwivESDc/PMCpqaFI@8iX2hspGugXqDCrufQ8eJ1TR2Ndsp@tA/Y1oI/RuxQU9ZbFniGbEFJdaOMCvHr84U2zrNPevIkzeWKpCs0A7e892NbqZ/ggA7WLYs82CiTDOkQYLLA7mhKmLbwDww/gQ4T4h/ABlBT@xdVZDcZ8UGNsDfFdtT1EW9ymTWzDXZBU4bt2xTVGYxgG5jMr4Q@fdmHxHo/WAB6CBaATVddgyPsMAjsz@gg9qmm4ySI3Tw3GcxbcMepqV7AxubzoWv5b@4h1X05Ke28/PVBUC6kbKpl6kXGqod1I@1raSslqWWyPTrwbSltlYZg@oj1Lu6mNJJzmXn7yltMD2MjnwATXnk7KoCxbyvfxQlKSB7JOauKa5@n1S1qTja0GRqWuoeAyehCh2IQRRQXlPz5zXIOTlIXBpHRiOMyj/wR69pzewZjR/mYQYWjWRcICgRszxFld@UcLeWdqSznkYnDuFDGAtZBas2GTii2tHjPyqzukFtumdKPMWVud5JRMZoueq26ebLfxnv8518e0A2xDnruPNSvFw87S9cHdLYnp08m17imlUe2JHTnbIdLKIOrCuV9NEMRfudInbn7dHOwz2jr8fHWERkcakEae8Zo2LkdhKq8PBL1yUBXzjvWeYEimZsqy@S43e8abHlDxc0c485jZX5XW4Pxmr1UMGr5Gi4gOkYHpJkUQmj7zgW5nN7nFjXjbHHX0GF7kIIkBDaPPJV1iWtK3/AA)
I didn't save the pregolfed code, and I don't understand it enough anymore to take it apart again (or maybe just laziness, who knows)
[Answer]
## Batch, 201 bytes
```
@echo off
set s= /
for /l %%i in (2,1,%1)do call set s= %%s%%
set s=\%s%
for /l %%i in (-%1,1,%1)do call:c
exit/b
:c
echo %s%
set s=%s:\ = \%
set s=%s:X =/\%
set s=%s:\/=X %
set s=%s: /=/ %
```
Starts by building up the top line, then after printing each line, moves the `\` right one space and the `/` left once space, making sure that they make an `X` in the middle.
[Answer]
# [PHP](https://php.net/), 115 bytes
```
for(;$i<$c=1+2*$argn;$b?:$t[$i-1]="\\".!$t[$c-$i]="/",$o.="$t\n")$t=str_pad(" X"[$b=$argn==+$i++],$c," ",2);echo$o;
```
[Try it online!](https://tio.run/##JcxLDoIwFEbhuavAm38AtsXA0HLDNkwoMVCRdkIb7NYd19fwy0lOdDF3fXTxgGlfN6aWdH6EvdTwHSw3oj39isbcX5AGeNWMTMZQffzSKviPzyQRaiYks1GFxM@03@J0L6m40oCZ/3sW8EKMElZSQbKt9GJdQNA5v7ag7GTd8gY "PHP – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina), 74 bytes
```
.+
$* X
+`^ ( *).( *)
$1\ $2/¶$&
+`¶ ( *).( *).?$
$&¶$1/ $2\
m` (\W)$
$1
```
[Try it online!](https://tio.run/##K0otycxL/P9fT5tLRUshgks7IU5BQ0FLUw9EcKkYxigoqBjpH9qmogaUOrQNIadnr8KlogaUMNQHKYnhyk1Q0IgJ1wSKGv7/b2gAAA "Retina – Try It Online") Explanation:
```
.+
$* X
```
Place the `X`.
```
+`^ ( *).( *)
$1\ $2/¶$&
```
Starting at the `X`, working upwards, place a `\` diagonally to the left each time. Also place a `/` two more spaces after the `/` than last time.
```
+`¶ ( *).( *).?$
$&¶$1/ $2\
```
Starting at the `X`, working downwards, place a `/` diagonally to the left each time. Also place a `\` two more spaces after the `/` than last time.
```
m` (\W)$
$1
```
The number of spaces between the two diagonals needs to be odd, so the last space on each line (except the original `X` line) is deleted.
[Answer]
# Mathematica, 131 bytes
```
(F[x_,y_]:=Table[x<>StringJoin@Table[" ",i]<>y,{i,1,#*2,2}];Column[Join[Reverse@F["\\","/"],{"X"},F["/","\\"]],Alignment->Center])&
```
# Mathematica, 104 bytes
here is another approach using Grid
```
(S=DiagonalMatrix[Table["\\",r=2#+1]];Table[S[[r+1-i,0+i]]="/",{i,r}];S[[#+1,#+1]]="X";Grid@S/. 0->" ")&
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 138 bytes
```
for i in `seq $1;seq $[$1-1] -1 1`
{ $[a++]
printf "%*c%*s\n" `echo ' '$i $[a>$1?1:2] $[($1-i)*2]' '$[a<$1?1:2]`
}|sed 's/22/X/'|tr 12 /\\
```
[Try it online!](https://tio.run/##LYxBDoIwFET3nGJCSqoQUn@XavQaJrRJK5bQTVHKTjx7LcbVvMmbzN3GMaVhmuHhA0x0LzA6/aJj1JJGSyBTvHO3TaOL5@zDMqCs6r6qowoljOvHCRyc@W10YXSlo9SZd/nB72upN9nZ89@Y4rNG9wCPQkpxE3xdZpCEUCqlRIcv "Bash – Try It Online")
Really long, bash heates '\ and /'
Less golfed
```
for i in {1..10} {9..1};{
$[a++]; #argument as padding, prints 1 for \ and 2 for /
printf "%*c%*s\n" `echo ' '$i $[a>$1?1:2] $[($1-i)*2]' '$[a<$1?1:2]`;
}|sed 's/22/X/g' | tr 12 /\\
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~95~~ 84 bytes
*-10 bytes thanks to @FelipeNardiBatista*
```
f=lambda s,i='\n':i+(s and'\\'+' '*~-s+' /'+f(s-1,i+' ')+i+'/'+' '*~-s+' \\'or'X')
```
[Try it online!](https://tio.run/##VYqxCoAgAAV/xe1pKlJtgf/R4GKIJJSKurT06@badHdw@WlnikvvXl/2PpwlVQQNE7EFTiux0cEYcBCC6ZV1iAL3tMpZhBFgfED9hvGngh2s5xJio56ujPUP "Python 2 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 21 bytes
```
F'\Nú}'X¹ú).B€.∞ø€.∞»
```
[Try it online!](https://tio.run/##MzBNTDJM/f/fTT3G7/CuWvWIQzsP79LUc3rUtEbvUce8wzugjEO7//83NAAA "05AB1E – Try It Online")
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 25 bytes
Requires `⎕IO←0` which is default on many systems.
```
' \/X'[(⊢+2×⌽)∘.=⍨⍳1+2×⎕]
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXI862iP@qyvE6EeoR2s86lqkbXR4@qOevZqPOmbo2T7qXfGod7MhWKxvaux/oOL/EVwGXBFchkBsBKINAA "APL (Dyalog Unicode) – Try It Online")
`' \/X'[`…`]` index the string with
`⎕` get input
`2×` multiply by two
`1+` add one
`⍳` that many integers
`∘.=⍨` equality table (i.e. identity matrix; NW-SE diagonal)
`(`…`)` apply the following tacit function on that
`⊢` the argument
`+` plus
`2×` two times
`⌽` the horizontally mirrored argument (i.e. NE-SW diagonal)
[Answer]
# Perl 5, 110 + 1 = 111 bytes
Uses `-n` flag.
```
$x=$_;$,="\n";push@x,$"x($x-$_)."\\".$"x(2*--$_+1)."/"while$_>0;say@x,$"x$x."x";for(reverse@x){y!\\/!/\\!;say}
```
[Answer]
# [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 90 bytes
```
~b=0|?@X`\[0,:-1|X=space$(a)┘Z=Z+X+@\`+space$((b-a)*2-1)+@/`+X+@┘`]Z=Z+space$(b)+A+_fZ
```
How this monstrosity works, is left as an excercise for the reader...
Sample output:
```
Command line: 3
\ /
\ /
\ /
X
/ \
/ \
/ \
```
[Answer]
## [Visual Basic.Net](https://msdn.microsoft.com/en-us/library/aa903378(v=vs.71).aspx), ~~454~~ 450 Bytes
```
Option Strict Off
module m
sub main(a As String())
dim v=Convert.toInt32(a(0))
for i as Integer=v to 1 step -1
for j as Object=1 to v-i
w(" ")
next
w("\")
for j as Object=1 to i*2-1
w(" ")
next
console.writeline("/")
next
console.writeline(new String(" ",v)&"X")
for i as Object=1 to v
for j as Object=1 to v-i
w(" ")
next
w("/")
for j as Object=1 to i*2-1
w(" ")
next
console.writeline("\")
next
end sub
sub w(s)
console.write(s)
end Sub
end module
```
not sure whether making a func for `writeline` will save some bytes
thanks to Stephen S for pointing at `as ...` removal
also changed `integer` into `object`
last edit changed the first one back
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 22 bytes
```
F'\IN-úR.∞})Âí'Xs)˜.c»
```
[Try it online!](https://tio.run/##ASgA1/8wNWFiMWX//0YnXElOLcO6Ui7iiJ59KcOCw60nWHMpy5wuY8K7//8z "05AB1E – Try It Online")
**Explanation**
```
F # for N in [0...input-1] do
'\ # push a backslash
IN-ú # prepend input-N spaces
R # reverse
.∞ # mirror
} # end loop
) # wrap stack in a list
 # bifurcate
í # reverse each item
'Xs # push an "X" between the 2 lists on the stack
)˜ # wrap in flattened list
.c # pad lines to equal length
» # join on newlines
```
Alternative 22 byte solution
```
F'\N·>ú'/ì})Âí'X¸«ì.c»
```
[Answer]
## Pyke, 14 bytes
```
\XQV.X \ /\/
```
[Try it here!](http://pyke.catbus.co.uk/?code=%5CXQV.X+%5C+++%2F%5C%2F&input=3)
```
\X - "X"
QV - repeat input times:
.X \ /\/ - surround(^, all=" ",
tl="\",
left=" ",
right=" ",
lower=" ",
tr="/",
br="\",
bl="/")
```
[Answer]
# tcl, 134
```
proc P {x s b} {time {puts [format %[incr ::i $x]s%[expr ($::n-$::i)*2+2]s $s $b]} $::n}
P 1 \\ /
puts [format %[incr i]s X]
P -1 / \\
```
## [demo](http://rextester.com/NKOT69701)
Set `n` on the first line.
May be I can golf it more using a recursive approach
] |
[Question]
[
# Introduction
In chess, Knights can move two squares in one direction, and then one square in an orthogonal direction. On an x/y plane, these can be thought of as being a relative change of coordinates, such as (+1, -2).
# Challenge
Your task is to output all 8 possible moves as pairs of relative x/y coordinates, in any order.
You may output in any reasonable format. To decrease reliance on printing random separators, using the same separators for everything is fine, and no separators are also fine. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
**Example Outputs:**
```
1,2 1,-2 -1,-2 -1,2 2,1 2,-1 -2,-1 -2,1
2-112-2-1-211-2-1-2-1221
1;2
-1;2
2;1
2;-1
-2;-1
1;-2
-1;-2
-2;1
```
This is code golf, so fewest bytes wins.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 25 bytes
```
Solve[x^2y^2==4,Integers]
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7Pzg/pyw1uiLOqDLOyNbWRMczryQ1PbWoOPZ/QFFmXolD2n8A "Wolfram Language (Mathematica) – Try It Online")
Outputs a list of `{x -> *x*, y -> *y*}`s.
[Answer]
# [Python](https://www.python.org), 30 bytes
```
print((2*"2212-1-21-2-1")[2:])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhb7Cooy80o0NIy0lIyMDI10DXWNgEjXUEkz2sgqVhOiCKoWpgcA)
A mashup of my previous and the [trivial](https://codegolf.stackexchange.com/a/247684/107561) solutions.
# [Python](https://www.python.org), 41 bytes
```
a=1
for b in b"41030143":print(a,a:=b-50)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3NRNtDbnS8osUkhQy8xSSlEwMDYwNDE2MlawKijLzSjQSdRKtbJN0TQ00IRqg-mD6AQ)
Abuses the dual stringy/inty nature of `bytes` objects. Arranges items such that a sliding 2-window finds all required pairs.
[Answer]
# [J](http://jsoftware.com/), 18 bytes
```
(,+)@(1j2*0j1^i.4)
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NXS0NR00DLOMtAyyDOMy9Uw0/2typSZn5CukKair/wcA "J – Try It Online")
A function taking any input and returning the list we want as complex numbers.
* `0j1^i.4` \$i\$ raised to 0, 1, 2, 3 -- gives the 4 compass directions in the complex plane: `1 0j1 _1 0j_1`.
* `1j2*` Multiply \$(1 + 2i)\$ times each of those, and we get \$(1 + 2i)\$ rotated 0, 90, 180, and 270 degrees: `1j2 _2j1 _1j_2 2j_1`.
* `(,+)` Take the complex conjugates of each of those, and append them: `1j2 _2j1 _1j_2 2j_1 1j_2 _2j_1 _1j2 2j1`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ø+pḤUƬ
```
A niladic Link that yields this pair of lists of pairs of integers:
```
[[[1, 2], [1, -2], [-1, 2], [-1, -2]], [[2, 1], [-2, 1], [2, -1], [-2, -1]]]
```
**[Try it online!](https://tio.run/##y0rNyan8///wDO2ChzuWhB5b8/8/AA)**
### How?
```
Ø+pḤUƬ - Link: no arguments
Ø+ - literal [1,-1] - set as the left argument
Ḥ - double -> [2,-2]
p - ([1,-1]) Cartesian product ([2,-2]) -> [[1,2],[1,-2],[-1,2],[-1,-2]]
Ƭ - collect up inputs while distinct, applying:
U - reverse each
```
---
Original seven byter (not abusing the very lose IO):
```
Ø+pḤ;U$ - Link: no arguments
Ø+ - literal [1,-1] - set as the left argument
Ḥ - double -> [2,-2]
p - ([1,-1]) Cartesian product ([2,-2]) -> [[1,2],[1,-2],[-1,2],[-1,-2]]
$ - last two links as a monad - f(X=that):
U - reverse each of (X)
; - (X) concatenate (that)
```
[Try it online!](https://tio.run/##y0rNyan8///wDO2ChzuWWIeq/P8PAA "Jelly – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 bytes
```
Ø+pר½UƬ
```
[Try it online!](https://tio.run/##y0rNyan8///wDO2Cw9MPzzi0N/TYmv//AQ "Jelly – Try It Online")
*-1 by stretching the output format a bit*
```
Ø+p Cartesian product of [1, -1] with itself.
ר½ Multiply each pair with [1, 2],
UƬ and pair with the reversed pairs.
```
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
ı*Ɱ4×2ıṠƬ
```
[Try it online!](https://tio.run/##ARoA5f9qZWxsef//xLEq4rGuNMOXMsSx4bmgxqz//w "Jelly – Try It Online")
Port of [Jonah's J solution](https://codegolf.stackexchange.com/a/247680/85334).
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
“ç©Ḅ’b5_2ṡ2
```
[Try it online!](https://tio.run/##AR4A4f9qZWxsef//4oCcw6fCqeG4hOKAmWI1XzLhuaEy//8 "Jelly – Try It Online")
Port of [loopy walt's Python solution](https://codegolf.stackexchange.com/a/247681/85334).
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
“œƇØj_’ṃ“21-
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw5yjk4@1H56RFf@oYebDnc1AASND3f//AQ "Jelly – Try It Online")
A fully hardcoded, no separator solution for comparison.
[Answer]
# [Factor](https://factorcode.org/) + `math.combinatorics math.unicode`, 47 bytes
```
{ 1 -1 2 -2 } 2 selections [ Σ odd? ] filter .
```
[Try it online!](https://tio.run/##JcgxDoJAEEbhq/wXgARKLSiNjY2xMhbr7BAngR3cGQpiOI338Uor0erlfX0g11wu5@PpsMMY/FGTjndJYWMh@9OchDTyb2D8nDkRG6bM7suUJTn25YUGVYMWVYt1i/HA5KLJcMXnDY2xww29DM4ZdSlf "Factor – Try It Online")
## How?
Generate all 2-selections of `{ 1 -1 2 -2 }`:
```
{ 1 1 }
{ 1 -1 }
{ 1 2 }
{ 1 -2 }
{ -1 1 }
{ -1 -1 }
{ -1 2 }
{ -1 -2 }
{ 2 1 }
{ 2 -1 }
{ 2 2 }
{ 2 -2 }
{ -2 1 }
{ -2 -1 }
{ -2 2 }
{ -2 -2 }
```
and keep only those with odd sums:
```
{ 1 2 }
{ 1 -2 }
{ -1 2 }
{ -1 -2 }
{ 2 1 }
{ 2 -1 }
{ -2 1 }
{ -2 -1 }
```
[Answer]
# [R](https://www.r-project.org/), ~~42~~ ~~35~~ ~~34~~ 33 bytes
```
round(2*exp((1:2+0:7%/%2*pi)/2i))
```
[Try it online!](https://tio.run/##K/r/vyi/NC9Fw0grtaJAQ8PQykjbwMpcVV/VSKsgU1PfKFNT8/9/AA "R – Try It Online")
Outputs as complex numbers.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes
```
12ẹ{ṅ|}ᵐp
```
[Try it online!](https://tio.run/##ASkA1v9icmFjaHlsb2cy/@KGsOKCgeG6ieKKpf8xMuG6uXvhuYV8feG1kHD//w "Brachylog – Try It Online")
[Generates](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/10753#10753) each move.
```
{ }ᵐ For each element of
ẹ the digits of
12 12,
| maybe
ṅ negate it.
p Output a permutation of the result.
```
Although `ᵐ` maps over digits if given a raw integer, it also smashes the results back into an integer, which doesn't play nice with signs.
[Answer]
# [R](https://www.r-project.org/), ~~37~~ ~~29~~ ~~26~~ 25 / 23\* bytes
*Edit: -1 byte thanks to pajonk*
\**Edit 2: Or -2 more bytes [with output as elements of a 2x4 matrix](https://tio.run/##K/r/X8NQW8/UStdQyyRTUzVf1TAzTsPQykTz/38A), thanks to Giuseppe*
```
(1+.5:-1*4i)*1i^(2:9%/%2)
```
[Try it online!](https://tio.run/##K/r/X8NQW8/UStdQyyRTU8swM07DyMpSVV/VSPP/fwA "R – Try It Online")
Change of approach to try to compete with [pajonk](https://codegolf.stackexchange.com/a/247685/95126); now outputs as complex numbers.
~~Still frustratingly 3 bytes longer than~~ ~~Now the same length as~~ Satisfyingly now shorter than a [hard-coded string](https://codegolf.stackexchange.com/a/247684/95126)...
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 9 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
2╤ç■gɱ~¡
```
[Try it online.](https://tio.run/##AR0A4v9tYXRoZ29sZv//MuKVpMOn4pagZ8OJwrF@wqH//w)
**Explanation:**
```
2╤ # Push a list in the range [-2,2]: [-2,-1,0,1,2]
ç # Remove the 0 with a falsey filter
■ # Cartesian product with itself
g # Filter these pairs by,
É # using three characters as inner code-block:
± # Take the absolute values of the pair
~ # Pop and push the values separated to the stack
¡ # Check that they are NOT equal
# (after which the entire stack is output implicitly as result)
```
[Answer]
# x86-64 machine code, 15 bytes
```
B8 01 02 FF FE AB 0F C8 AB C1 C8 18 73 F7 C3
```
[Try it online!](https://tio.run/##bVG7TsMwFJ3tr7gEVXL6khsqVDWEBdGNhQmpZHAdOzFK7ChOHxLi1wnXhTIgBvta53HPkSxnpZTDIHwD7DlidF7Wbidq0FSvSeMOoMRpCvy0edxseMIXtFsT3ztfULLzR9EGnl6QznXf@mRJyZuV0CGmehpHcUrpwZkCNJOV6ICNfbxN8gBfGyvrfaHgzveFcfPqnhrbQyOMZTF9p@Rs8NtVjoaUEs18HAZmsSA0kAFPcVxlsMI5mcSUkLZDTrNolBjA82qjKe4w@ZbnP49FSP/VvdonIStjFUhXqHUoTKSzvoe99aa0qoBzj3GLcexfJtbpH0jiksLBJQNGPHnBHjIbt9gyhWNlaoXbQnV@erjB0I9h@JS6FqUfZs3tEi/8mgz9qv4C "C (gcc) – Try It Online")
Writes a size-8 array of size-2 arrays of 8-bit integers to an address given in RDI.
In assembly:
```
f: mov eax, 0xFEFF0201 # Set EAX to this value; -2, -1, 2, 1 from top to bottom.
r: stosd # Write EAX to the output address, advancing the pointer.
bswap eax # Reverse the order of the bytes of EAX, getting 1, 2, -1, -2.
stosd # Write EAX to the output address, advancing the pointer.
ror eax, 24 # Rotate right by 24 bits, getting 2, -1, -2, 1.
jnc r # Jump back if CF (set from the last bit rotated: the high bit) is 0.
# This is true the first time.
# After the jump, the value is added to the output again,
# then reversing gives 1, -2, -1, 2, which is also added to the output,
# and then rotating gives -2, -1, 2, 1, and CF is 1, ending the loop.
ret # Return.
```
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 3 bytes
```
į→ŋ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHHBgqWlJWm6FsuPrH_UNulo95LipORiqBhMDgA)
```
į→ŋ
į [0,1] or [1,0]
→ Increment
ŋ Optionally negate each element
```
---
## [Nekomata](https://github.com/AlephAlpha/Nekomata) before v0.3.5.0, 6 bytes
```
2R↕ᵐᶜ_
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHHBgqWlJWm6FmuMgh61TX24dcLDbXPilxQnJRdDJWAKAA)
A port of [@Unrelated String's](https://codegolf.stackexchange.com/users/85334/unrelated-string) [Brachylog](https://github.com/JCumin/Brachylog) [answer](https://codegolf.stackexchange.com/a/247700/9288).
```
2R Range from 1 to 2
↕ Permutation
ᵐᶜ_ Optionally negate each element
```
[Answer]
# [Regenerate](https://github.com/dloscutoff/Esolangs/tree/master/Regenerate) `a`, 13 bytes
```
-?1-?2|-?2-?1
```
Not sure if this is golfable unless more features are added to the language lol... but please prove me wrong!
Prints like this:
```
12
1-2
-12
-1-2
21
2-1
-21
-2-1
```
Breakdown:
```
-?1-?2|-?2-?1
Print every string that is
-?1 -1 or 1
-?2 followed by -2 or 2
| or
-?2 -2 or 2
-?1 followed by -1 or 1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72qKDU9NS-1KLEkdVm0km6iUuyCpaUlaboWa3XtDXXtjWqAGMiCiEGlFkBpAA)
[Answer]
# [Python](https://www.python.org), 67 bytes
```
lambda:[z for i in range(99)if{*map(abs,z:=(i%5-2,i//5-2))}=={1,2}]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3nXMSc5NSEq2iqxTS8osUMhUy8xSKEvPSUzUsLTUz06q1chMLNBKTinWqrGw1MlVNdY10MvX1gZSmZq2tbbWhjlFtLMSo1QVFmXklGlppGpqaEJEFCyA0AA)
Shorter than using `itertools.product`
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~16~~ 13 bytes
```
»1rKȮ8»`-12`τ
```
[Try it online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCuzFyS8iuOMK7YC0xMmDPhCIsIiIsIiJd)
-3 thanks to [Steffan](https://codegolf.stackexchange.com/users/92689/steffan)
**7 bytes**
(`o`, Port of [this](https://codegolf.stackexchange.com/a/247705/107262), also thanks to Steffan)
```
k-:dẊ…R
```
[Try it online!](https://vyxal.pythonanywhere.com/#WyJvIiwiIiwiay06ZOG6iuKAplIiLCIiLCIiXQ==)
### 16 bytes (old)
```
»-∞ðO∩ß¹¶"⊍»0\-¢
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCuy3iiJ7DsE/iiKnDn8K5wrZcIuKKjcK7MFxcLcKiIiwiIiwiIl0=)
```
»-∞ðO∩ß¹¶"⊍» # Compressed integer 201120201021102010201221
0\-¢ # Replace 0 with -
```
Spent forever trying to find a cool answer but this is all my half asleep brain could come up with at the moment
There is a 0% chance this is optimal :P
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 68 bytes
```
-[----->>+<+<]>-.>--..----.<.>.<.-..+..->.<.>.<.+.>.<.->.<.>.<.+>.<.
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fN1oXBOzstG20bWLtdPXsdHX19EBCejZ6dkAM5GkDBeygXG2IIJwLIv7/BwA "brainfuck – Try It Online")
Start is Similar to Pyautogui's answer, with a loop running `255/5=51` times to set a starting cell to `51`. But I set two cells to `51`, and use one for the characters `12` and the other one (hunt and peck style) for the character `-`.
The output `211-2-21122-1-12-2-1-1-2` consists of alternating pairs of `2`s and `1`s with interspersed `-` where necessary. The first two `1`'s are read from the cell which generates the `-` as the value descends from `51` through `49` to `45`. The rest of the `1`s are from the same cell as the `2`.
# [brainfuck](https://github.com/TryItOnline/brainfuck), 29 bytes
```
+.+..-..>--..+..-..<.+.>+..<.
```
[Try it online!](https://tio.run/##SypKzMxLK03O/q@NBKJ17UAUmLCxibX7r62nraenq6dnpwskIEwbIG2nDaL//wcA "brainfuck – Try It Online")
A different interpretation of the rules outputting binary values `-2, -1, 1, 2` when run on a blank Brainfuck tape. For convenient verification the header initializes the two cells used on the tape to `48 = ASCII '0'` so that the outputs for `-2, -1, 1, 2` are `. / 1 2` respectively.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/language/), ~~41~~ 36 bytes
-5 bytes, thanks @att.
Selects the elements with odd element sum from the group of all length 2 tuples with elements from the set {1,-2,2,-2}:
```
{1,-1,2,-2}~Tuples~2~Select~OddQ@*Tr
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~74~~ 70 bytes
*-4 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)*
```
i;main(){for(;i<32;++i)putchar(i&1?(i/2^i/8)%2+49:i&4+6*(i&2)?45:43);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z/TOjcxM09Dszotv0jDOtPG2MhaWztTs6C0JDkjsUgjU83QXiNT3yguU99CU9VI28TSKlPNRNtMCyhjpGlvYmplYqxpXfv/PwA "C (gcc) – Try It Online")
Edit: it's obviosly longer than necessary, but it's the shortest way I found without printing directly the result.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 68 bytes
```
y;main(x){for(y=3;x--<-3?x=--y+6:x*x+y*y-5||printf("%d,%d;",x,y););}
```
[Try it online!](https://tio.run/##BcHhCkAwEADgd1Fqs92vxQ9HnmVNk2KEcpd5def7AkwhiDCufk6K9BO3Q3HvkAA6cAP1AGyalioyXDHUOe/HnK6oinK05YiFJcsaNb4iX4iLn06B@wc "C (gcc) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes
```
IΦEφ⁻↨ι⁵⁰χ⁼⁵ΣXι²
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwy0zpyS1SMM3sUDD0MDAQEfBNzOvtFjDKbE4VSNTR8HUQFNHwRBEuBaWJuYUa5jqKASX5moE5JcDdQEVGGmCgfX///91y3IA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
φ Predefined variable `1000`
E Map over implicit range
ι Current value
↨ Convert to base (i.e. divmod)
⁵⁰ Literal integer `50`
⁻ Vectorised subtract
χ Predefined variable `10`
Φ Filtered where
ι Current pair
X Vectorised raised to power
² Literal integer `2`
Σ Take the sum
⁼ Is equal to
⁵ Literal integer `5`
I Cast to string
Implicitly print
```
Using base conversion results in the invalid "pairs" `[]`, `[-9]`, `[-8]`, ... `[39]` but none of them have a Euclidean distance of `√5`. Boring string compression version for 11 bytes:
```
”{“↥?UV&✳¿>
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvREPJSNfQ0EgXSOoaGRpCaF1DIyNDJU3r////65blAAA "Charcoal – Try It Online") Link is to verbose version of code.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 33 bytes
```
x,y=1,2
4.times{p x,t=y,y=-x,x=t}
```
[Try it online!](https://tio.run/##KypNqvz/v0Kn0tZQx4jLRK8kMze1uLpAoUKnxLYSKKpboVNhW1L7/z8A "Ruby – Try It Online")
A straightforward rotation based on a concept of `y,x=-x,y` with some extra code to print in reverse as well.
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 18 bytes
```
{1-1}{2-2}cpJ)<-_+
```
[Try it online!](https://tio.run/##SyotykktLixN/f@/2lDXsLbaSNeoNrnAS9NGN177f@B/AA "Burlesque – Try It Online")
```
{1-1} # {1 -1}
{2-2} # {2 -2}
cp # Cart product
J # Duplicate
)<- # Reverse each in dup
_+ # Concat
```
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 19 bytes
```
(2|+´)¨⊸/⥊⋈⌜˜-⊸∾1‿2
```
[Try it at BQN online](https://mlochbaum.github.io/BQN/try.html#code=KDJ8K8K0KcKo4oq4L+KliuKLiOKMnMucLeKKuOKIvjHigL8y)
### Explanation
```
(2|+´)¨⊸/⥊⋈⌜˜-⊸∾1‿2
1‿2 List containing 1 and 2
∾ Prepend
-⊸ its negation
⋈⌜˜ Table of each item of that list paired with each item of that list
⥊ Deshape into a list of two-element lists
( )¨ For each of those:
+´ Get its sum
2| Mod 2
⊸/ Select the elements for which that result is 1
```
[Answer]
# Excel, ~~49~~ 40 bytes
Saved 9 bytes thanks to [JvdV](https://codegolf.stackexchange.com/questions/247676/generate-all-8-knights-moves/247724?noredirect=1#comment560567_247724)
```
=CONCAT({1,-1}&2*{1;-1},2*{1,-1}&{1;-1})
```
Outputs pairs without delimeters.
[](https://i.stack.imgur.com/yeiQk.png)
---
# Excel, 27 bytes
```
="12-121-2-1-221-212-1-2-1"
```
... but that's too boring.
[Answer]
A reference for all the trivial approaches.
# [Python](https://www.python.org), 33 bytes
```
print('2-112-2-1-211-2-1-2-1221')
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3FQuKMvNKNNSNdA0NjXSBpK6RoSGE1jU0MjJU14QohKqH6QMA)
# [R](https://www.r-project.org/), 26 bytes
```
'2-112-2-1-211-2-1-2-1221'
```
[Try it online!](https://tio.run/##K/r/X91I19DQSBdI6hoZGkJoXUMjI0P1//8B "R – Try It Online")
# [Wolfram Language (Mathematica)](https://www.wolfram.com/language/), 26 bytes
Assumes a notebook environment. If this is false `Echo@` can be added in front at the cost of 5 bytes.
```
"2-112-2-1-211-2-1-2-1221"
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/981OSPfQclI19DQSBdI6hoZGkJoXUMjI0Ol//8B "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [A0A0](https://esolangs.org/wiki/A0A0), 39 bytes
```
O-1212212
O-1
O-2
O-11
O-2
O-1
O-2
O-21
```
Prints `-1212212-1-2-11-2-1-2-21`. This simply prints many negative numbers, of which the negative numbers form non-separated pairs of relative positions. Since there are eight negative numbers, we use eight different output instructions.
[Answer]
# JavaScript, 58 bytes
```
_=>[...'01234567'].map(i=>[((i&4)-2)/(m=i%2+1),(i&2)*m-m])
```
[Try it online!](https://tio.run/##DchbDkAwEADA02AXXdTrqy4iIo1XKq2KiutX53NO@Um3POp@2WXXze/Cz2IYiSgpK143bdcnExl5gwoNoOIGGccCjFARzyrMQ3FMDTMT@sVezuqNtD1gB0T/Aw "JavaScript (Node.js) – Try It Online")
I know it's shorter to hardcode, but that feels cheaty...
[Answer]
# [(8-bit, wrapping) Brainfuck](https://github.com/TryItOnline/brainfuck), 80 bytes
```
-[>+<-----]>-.[->+>+<<]>>-----.<-..+.>.<.>.<-.>.<+.-..>.<+.>.<-.>.<+.>.<-.+..-.>
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70yqSgxMy-tNDl7wYKlpSVpuhY3A3Sj7bRtdEEg1k5XL1rXThvIt4m1swOL6dno6ulp69np2YCwLojQ1gMKgWmECJilrQeUsYOYCzUeZg0A)
Outputs in the example format: "2-112-2-1-211-2-1-2-1221".
Originally, this was in severe need of a golf, having been made by an [automated tool](https://copy.sh/brainfuck/text.html). I have now optimized it a little. It now uses a similar technique to [Level River St's answer](https://codegolf.stackexchange.com/a/247722/104836), though I arrived at it independently, and it differs in the details; instead of 51, the starting value is 50.
[Answer]
# [Headascii](https://esolangs.org/wiki/Headass#Headascii), 71 bytes
```
++++[]+^^^D^^^D^P]PD^P]+PD^P]+PD^P]PD^P]P+PPD^P]PPD^P]+PD^P]+P-PP+PP-P!
```
Outputs `-1-2-2-1-122-11-2-211221`
Try it [Here](https://replit.com/@thejonymyster/HA23) by executing
```
erun("++++[]+^^^D^^^D^P]PD^P]+PD^P]+PD^P]PD^P]P+PPD^P]PPD^P]+PD^P]+P-PP+PP-P!")
```
I'm ashamed at how long this is. I have to make a golfier language.............................
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
X®‚xâ˜Â«
```
[Try it online!](https://tio.run/##ARkA5v9vc2FiaWX//1jCruKAmnjDosucw4LCq/// "05AB1E – Try It Online")
```
X push an integer variable, which is initialized to 1 (using 1 makes it a string, which makes the output look weird)
® push the register, which is initialized to -1
‚ pair, to get [1, -1]
x push tos and itself doubled, to get [1, -1], [2, -2]
â Cartesian product, all pairs
˜ Flatten, to get a list of coordinates instead of a list of pairs
 Push tos and itself reversed
« Concatenate
```
] |
[Question]
[
You have a 3x3 grid. Each cell can be colored black or white. Display all 512 of these colorings. Fewest bytes wins.
You can display the grids in any formation as long as they are visually separated and the spacing looks regular. You may use ASCII art or images. Any two distinct visible symbols or colors can be used for black and white. Any whitespace is fine as long as the result is visually correct.
**Example output:**
```
...
...
...
...
...
..X
...
...
.X.
...
...
.XX
...
...
X..
...
...
X.X
...
...
XX.
...
...
XXX
...
..X
...
...
..X
..X
...
..X
.X.
...
..X
.XX
...
..X
X..
...
..X
X.X
...
..X
XX.
...
..X
XXX
...
.X.
...
...
.X.
..X
...
.X.
.X.
...
.X.
.XX
...
.X.
X..
...
.X.
X.X
...
.X.
XX.
...
.X.
XXX
...
.XX
...
...
.XX
..X
...
.XX
.X.
...
.XX
.XX
...
.XX
X..
...
.XX
X.X
...
.XX
XX.
...
.XX
XXX
...
X..
...
...
X..
..X
...
X..
.X.
...
X..
.XX
...
X..
X..
...
X..
X.X
...
X..
XX.
...
X..
XXX
...
X.X
...
...
X.X
..X
...
X.X
.X.
...
X.X
.XX
...
X.X
X..
...
X.X
X.X
...
X.X
XX.
...
X.X
XXX
...
XX.
...
...
XX.
..X
...
XX.
.X.
...
XX.
.XX
...
XX.
X..
...
XX.
X.X
...
XX.
XX.
...
XX.
XXX
...
XXX
...
...
XXX
..X
...
XXX
.X.
...
XXX
.XX
...
XXX
X..
...
XXX
X.X
...
XXX
XX.
...
XXX
XXX
..X
...
...
..X
...
..X
..X
...
.X.
..X
...
.XX
..X
...
X..
..X
...
X.X
..X
...
XX.
..X
...
XXX
..X
..X
...
..X
..X
..X
..X
..X
.X.
..X
..X
.XX
..X
..X
X..
..X
..X
X.X
..X
..X
XX.
..X
..X
XXX
..X
.X.
...
..X
.X.
..X
..X
.X.
.X.
..X
.X.
.XX
..X
.X.
X..
..X
.X.
X.X
..X
.X.
XX.
..X
.X.
XXX
..X
.XX
...
..X
.XX
..X
..X
.XX
.X.
..X
.XX
.XX
..X
.XX
X..
..X
.XX
X.X
..X
.XX
XX.
..X
.XX
XXX
..X
X..
...
..X
X..
..X
..X
X..
.X.
..X
X..
.XX
..X
X..
X..
..X
X..
X.X
..X
X..
XX.
..X
X..
XXX
..X
X.X
...
..X
X.X
..X
..X
X.X
.X.
..X
X.X
.XX
..X
X.X
X..
..X
X.X
X.X
..X
X.X
XX.
..X
X.X
XXX
..X
XX.
...
..X
XX.
..X
..X
XX.
.X.
..X
XX.
.XX
..X
XX.
X..
..X
XX.
X.X
..X
XX.
XX.
..X
XX.
XXX
..X
XXX
...
..X
XXX
..X
..X
XXX
.X.
..X
XXX
.XX
..X
XXX
X..
..X
XXX
X.X
..X
XXX
XX.
..X
XXX
XXX
.X.
...
...
.X.
...
..X
.X.
...
.X.
.X.
...
.XX
.X.
...
X..
.X.
...
X.X
.X.
...
XX.
.X.
...
XXX
.X.
..X
...
.X.
..X
..X
.X.
..X
.X.
.X.
..X
.XX
.X.
..X
X..
.X.
..X
X.X
.X.
..X
XX.
.X.
..X
XXX
.X.
.X.
...
.X.
.X.
..X
.X.
.X.
.X.
.X.
.X.
.XX
.X.
.X.
X..
.X.
.X.
X.X
.X.
.X.
XX.
.X.
.X.
XXX
.X.
.XX
...
.X.
.XX
..X
.X.
.XX
.X.
.X.
.XX
.XX
.X.
.XX
X..
.X.
.XX
X.X
.X.
.XX
XX.
.X.
.XX
XXX
.X.
X..
...
.X.
X..
..X
.X.
X..
.X.
.X.
X..
.XX
.X.
X..
X..
.X.
X..
X.X
.X.
X..
XX.
.X.
X..
XXX
.X.
X.X
...
.X.
X.X
..X
.X.
X.X
.X.
.X.
X.X
.XX
.X.
X.X
X..
.X.
X.X
X.X
.X.
X.X
XX.
.X.
X.X
XXX
.X.
XX.
...
.X.
XX.
..X
.X.
XX.
.X.
.X.
XX.
.XX
.X.
XX.
X..
.X.
XX.
X.X
.X.
XX.
XX.
.X.
XX.
XXX
.X.
XXX
...
.X.
XXX
..X
.X.
XXX
.X.
.X.
XXX
.XX
.X.
XXX
X..
.X.
XXX
X.X
.X.
XXX
XX.
.X.
XXX
XXX
.XX
...
...
.XX
...
..X
.XX
...
.X.
.XX
...
.XX
.XX
...
X..
.XX
...
X.X
.XX
...
XX.
.XX
...
XXX
.XX
..X
...
.XX
..X
..X
.XX
..X
.X.
.XX
..X
.XX
.XX
..X
X..
.XX
..X
X.X
.XX
..X
XX.
.XX
..X
XXX
.XX
.X.
...
.XX
.X.
..X
.XX
.X.
.X.
.XX
.X.
.XX
.XX
.X.
X..
.XX
.X.
X.X
.XX
.X.
XX.
.XX
.X.
XXX
.XX
.XX
...
.XX
.XX
..X
.XX
.XX
.X.
.XX
.XX
.XX
.XX
.XX
X..
.XX
.XX
X.X
.XX
.XX
XX.
.XX
.XX
XXX
.XX
X..
...
.XX
X..
..X
.XX
X..
.X.
.XX
X..
.XX
.XX
X..
X..
.XX
X..
X.X
.XX
X..
XX.
.XX
X..
XXX
.XX
X.X
...
.XX
X.X
..X
.XX
X.X
.X.
.XX
X.X
.XX
.XX
X.X
X..
.XX
X.X
X.X
.XX
X.X
XX.
.XX
X.X
XXX
.XX
XX.
...
.XX
XX.
..X
.XX
XX.
.X.
.XX
XX.
.XX
.XX
XX.
X..
.XX
XX.
X.X
.XX
XX.
XX.
.XX
XX.
XXX
.XX
XXX
...
.XX
XXX
..X
.XX
XXX
.X.
.XX
XXX
.XX
.XX
XXX
X..
.XX
XXX
X.X
.XX
XXX
XX.
.XX
XXX
XXX
X..
...
...
X..
...
..X
X..
...
.X.
X..
...
.XX
X..
...
X..
X..
...
X.X
X..
...
XX.
X..
...
XXX
X..
..X
...
X..
..X
..X
X..
..X
.X.
X..
..X
.XX
X..
..X
X..
X..
..X
X.X
X..
..X
XX.
X..
..X
XXX
X..
.X.
...
X..
.X.
..X
X..
.X.
.X.
X..
.X.
.XX
X..
.X.
X..
X..
.X.
X.X
X..
.X.
XX.
X..
.X.
XXX
X..
.XX
...
X..
.XX
..X
X..
.XX
.X.
X..
.XX
.XX
X..
.XX
X..
X..
.XX
X.X
X..
.XX
XX.
X..
.XX
XXX
X..
X..
...
X..
X..
..X
X..
X..
.X.
X..
X..
.XX
X..
X..
X..
X..
X..
X.X
X..
X..
XX.
X..
X..
XXX
X..
X.X
...
X..
X.X
..X
X..
X.X
.X.
X..
X.X
.XX
X..
X.X
X..
X..
X.X
X.X
X..
X.X
XX.
X..
X.X
XXX
X..
XX.
...
X..
XX.
..X
X..
XX.
.X.
X..
XX.
.XX
X..
XX.
X..
X..
XX.
X.X
X..
XX.
XX.
X..
XX.
XXX
X..
XXX
...
X..
XXX
..X
X..
XXX
.X.
X..
XXX
.XX
X..
XXX
X..
X..
XXX
X.X
X..
XXX
XX.
X..
XXX
XXX
X.X
...
...
X.X
...
..X
X.X
...
.X.
X.X
...
.XX
X.X
...
X..
X.X
...
X.X
X.X
...
XX.
X.X
...
XXX
X.X
..X
...
X.X
..X
..X
X.X
..X
.X.
X.X
..X
.XX
X.X
..X
X..
X.X
..X
X.X
X.X
..X
XX.
X.X
..X
XXX
X.X
.X.
...
X.X
.X.
..X
X.X
.X.
.X.
X.X
.X.
.XX
X.X
.X.
X..
X.X
.X.
X.X
X.X
.X.
XX.
X.X
.X.
XXX
X.X
.XX
...
X.X
.XX
..X
X.X
.XX
.X.
X.X
.XX
.XX
X.X
.XX
X..
X.X
.XX
X.X
X.X
.XX
XX.
X.X
.XX
XXX
X.X
X..
...
X.X
X..
..X
X.X
X..
.X.
X.X
X..
.XX
X.X
X..
X..
X.X
X..
X.X
X.X
X..
XX.
X.X
X..
XXX
X.X
X.X
...
X.X
X.X
..X
X.X
X.X
.X.
X.X
X.X
.XX
X.X
X.X
X..
X.X
X.X
X.X
X.X
X.X
XX.
X.X
X.X
XXX
X.X
XX.
...
X.X
XX.
..X
X.X
XX.
.X.
X.X
XX.
.XX
X.X
XX.
X..
X.X
XX.
X.X
X.X
XX.
XX.
X.X
XX.
XXX
X.X
XXX
...
X.X
XXX
..X
X.X
XXX
.X.
X.X
XXX
.XX
X.X
XXX
X..
X.X
XXX
X.X
X.X
XXX
XX.
X.X
XXX
XXX
XX.
...
...
XX.
...
..X
XX.
...
.X.
XX.
...
.XX
XX.
...
X..
XX.
...
X.X
XX.
...
XX.
XX.
...
XXX
XX.
..X
...
XX.
..X
..X
XX.
..X
.X.
XX.
..X
.XX
XX.
..X
X..
XX.
..X
X.X
XX.
..X
XX.
XX.
..X
XXX
XX.
.X.
...
XX.
.X.
..X
XX.
.X.
.X.
XX.
.X.
.XX
XX.
.X.
X..
XX.
.X.
X.X
XX.
.X.
XX.
XX.
.X.
XXX
XX.
.XX
...
XX.
.XX
..X
XX.
.XX
.X.
XX.
.XX
.XX
XX.
.XX
X..
XX.
.XX
X.X
XX.
.XX
XX.
XX.
.XX
XXX
XX.
X..
...
XX.
X..
..X
XX.
X..
.X.
XX.
X..
.XX
XX.
X..
X..
XX.
X..
X.X
XX.
X..
XX.
XX.
X..
XXX
XX.
X.X
...
XX.
X.X
..X
XX.
X.X
.X.
XX.
X.X
.XX
XX.
X.X
X..
XX.
X.X
X.X
XX.
X.X
XX.
XX.
X.X
XXX
XX.
XX.
...
XX.
XX.
..X
XX.
XX.
.X.
XX.
XX.
.XX
XX.
XX.
X..
XX.
XX.
X.X
XX.
XX.
XX.
XX.
XX.
XXX
XX.
XXX
...
XX.
XXX
..X
XX.
XXX
.X.
XX.
XXX
.XX
XX.
XXX
X..
XX.
XXX
X.X
XX.
XXX
XX.
XX.
XXX
XXX
XXX
...
...
XXX
...
..X
XXX
...
.X.
XXX
...
.XX
XXX
...
X..
XXX
...
X.X
XXX
...
XX.
XXX
...
XXX
XXX
..X
...
XXX
..X
..X
XXX
..X
.X.
XXX
..X
.XX
XXX
..X
X..
XXX
..X
X.X
XXX
..X
XX.
XXX
..X
XXX
XXX
.X.
...
XXX
.X.
..X
XXX
.X.
.X.
XXX
.X.
.XX
XXX
.X.
X..
XXX
.X.
X.X
XXX
.X.
XX.
XXX
.X.
XXX
XXX
.XX
...
XXX
.XX
..X
XXX
.XX
.X.
XXX
.XX
.XX
XXX
.XX
X..
XXX
.XX
X.X
XXX
.XX
XX.
XXX
.XX
XXX
XXX
X..
...
XXX
X..
..X
XXX
X..
.X.
XXX
X..
.XX
XXX
X..
X..
XXX
X..
X.X
XXX
X..
XX.
XXX
X..
XXX
XXX
X.X
...
XXX
X.X
..X
XXX
X.X
.X.
XXX
X.X
.XX
XXX
X.X
X..
XXX
X.X
X.X
XXX
X.X
XX.
XXX
X.X
XXX
XXX
XX.
...
XXX
XX.
..X
XXX
XX.
.X.
XXX
XX.
.XX
XXX
XX.
X..
XXX
XX.
X.X
XXX
XX.
XX.
XXX
XX.
XXX
XXX
XXX
...
XXX
XXX
..X
XXX
XXX
.X.
XXX
XXX
.XX
XXX
XXX
X..
XXX
XXX
X.X
XXX
XXX
XX.
XXX
XXX
XXX
```
[Answer]
# Mathematica, 25 bytes
```
Image/@{0,1}~Tuples~{3,3}
```
Gives an array with all the grids as images, which is also directly displayed on screen:

(Cropped so as not to blow up the post unnecessarily.)
[Answer]
# K, 11 bytes
```
(3 3#)'!9#2
```
Output example:
```
((0 0 0
0 0 0
0 0 0)
(0 0 0
0 0 0
0 0 1)
(0 0 0
0 0 0
0 1 0)
(0 0 0
0 0 0
0 1 1)
…
```
This is K's native prettyprinted representation of a list of matrices, which I think is sufficient for the problem spec. Each matrix is delimited by an enclosing set of parentheses.
And a quick sanity check to demonstrate that 512 matrices are constructed:
```
#(3 3#)'!9#2
512
```
Very straightforward. Most of the work is in the `!`. First we generate a 9-long vector of 2s using "take" (`9#2`). Then, we make use of the "odometer" monadic form of `!`- a few examples illustrate its behavior:
```
!2 2
(0 0
0 1
1 0
1 1)
!2 3
(0 0
0 1
0 2
1 0
1 1
1 2)
!2 2 2
(0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1)
```
Then simply do a 3x3 reshape (`(3 3#)`) of each (`'`) of the 9-length 0/1 vectors.
[Answer]
# JavaScript, 77 ~~80~~
Revised after the revision of the OP. Now we have a question, so here is an answer.
Run the snippet in any browser to test.
```
// Test: redefine console to have output inside the snippet
console = { log: function(x) { O.textContent+=x+'\n\n';} }
// Solution: 77 chars (note, distinct outputs to console are automatically separed)
for(i=511;++i<1024;)console.log(i.toString(2).slice(1).match(/.../g).join`
`)
```
```
<pre id=O></pre>
```
Old post: graphic display in a browser, with javascript and canvas. ~300 byte of code (can be made shorter).
Run the snippet below.
```
d=8, // Min block size
C.width=d*64,C.height=d*128,
T=C.getContext('2d')
for(i=0;i<512;i++)
{
bx=4*(i/32|0)
by=4*(i%32)
for(b=1,j=0;j<9;j++,b+=b)
{
if(b&i)
x=j/3|0, y=j%3, T.fillRect((bx+x)*d,(by+y)*d,d,d);
}
T.strokeRect(bx*d,by*d,d*3,d*3);
}
```
```
<canvas id=C></canvas>
```
[Answer]
# Matlab, 33
```
reshape(dec2bin(0:511,9)',3,3,[])
```
Was kind of fiddly to get the dimensions correct, but I am very happy with the result!
[Answer]
## POWERSHELL - 65
```
0..511|%{[convert]::ToString($_,2).padleft(9,'0')-split"(.{3})"}
```
result
```
000
000
000
000
000
001
000
000
010
000
000
011
```
confirmation
```
(0..511|%{[convert]::ToString($_,2).padleft(9,'0')-split"(.{3})"} | measure -Line).lines/3
512
```
edit inspired by the mathematica answer's display of results-617
```
Add-Type -AssemblyName System.Drawing
$a=new-object System.Drawing.Bitmap 992,496
$g=[Drawing.Graphics]::FromImage($a)
$b=@{};$y=@{};$i=$c=$d=$z=$k=$l=$m=0;
0..511|%{$y[$d++]=[convert]::ToString($_,2).padleft(9,'0')}
while($m-lt480){while($l-lt496){for($z=($m+0);$z-lt($m+32);$z++){
$y[$z].tochararray()|%{if($_-eq"0"){$b[$i++]=[Drawing.Brushes]::Black}
else{$b[$i++]=[Drawing.Brushes]::White}
}
for($j=($l+0);$j-lt($l+30);$j+=10){
($k+0),($k+10),($k+20)|%{$g.FillRectangle($b[$c++],$_,$j,10,10)}
}$k+=31
}$k=0;$l+=31;$m+=32
}
}$a.save("$HOME/3X3_Grid.png")
```
[](https://i.stack.imgur.com/95M6A.png)
[Answer]
## Python 2, 49 bytes
```
i=2048;exec"print bin(i/4)[i%4*3+3:][:3];i+=1;"*i
```
Split the binary expansion of `i`. The length-10 binary values 512 through 1023 are used, cutting off the initial 1 (and prefix `0b`). These are split into chunks of 3 as windows `[3:6]`, `[6:9]`, `[9:12]`, and `[12:15]`, with the last one blank to make a blank line. Iterating over the four slices is collapsed with the outer loop of counting through 512 numbers with the divmod trick.
[Answer]
# CJam, 12 bytes
```
2,9m*3f/N*N*
```
[Test it here.](http://cjam.aditsu.net/#code=2%2C9m*3f%2FN*N*)
Uses `0` and `1` as the distinct characters.
## Explanation
```
2, e# Push [0 1].
9m* e# Generate all 9-tuples of 0s and 1s.
3f/ e# Split each 9-tuple into 3 subarrays of length 3.
N* e# Join all those grids with newlines.
N* e# Put newlines between all the length-3 arrays.
```
An alternative (still 12 byte) solution is
```
2,3m*3m*N*N*
```
[Answer]
## Ruby, 86 bytes
```
0.upto(511).map{|i|i.to_s(2).rjust(9,'0')}.each{|j|p j[0..2];p j[3..5];p j[6..8];puts}
```
Mine prints with quotes because `p` is shorter than `puts`, but it does still fit the rules.
[Answer]
# Haskell, ~~57~~ 54 bytes
```
r x=sequence[x,x,x]
u=unlines
f=putStr$u$map u$r$r".X"
```
`f` gives the same output as in the challenge description, i.e. it starts with
```
...
...
...
...
...
..X
...
...
.X.
```
Edit: @Mauris found 3 bytes to save. Thanks!
[Answer]
# C# - 111
```
for(int i=0;i<512;i++)Console.WriteLine(Regex.Replace(Convert.ToString(i,2).PadLeft(9,'0'),"(.{3})","$1\r\n"));
```
Converts every int to its binary representation and splits every 3 chars.
[Answer]
# Python 2, 95 Bytes
Distinct characters are `0` and `1`, each block is separated by `\n\n`.
```
n='\n';print(n+n).join(y[:3]+n+y[3:6]+n+y[-3:]for y in[bin(x)[2:].zfill(9)for x in range(512)])
```
[Answer]
# Python 2, 81
```
import re
for i in range(512):print re.sub('(.{3})','\\1\n',bin(i)[2:].zfill(9))
```
[Answer]
## Ruby, 92 bytes
```
0.upto(511){|i|("%09d"%i.to_s(2)).scan(/.{3}/).map{|j|j.scan(/./)}.map{|j|puts j.join};puts}
```
Counts in `0`s and `1`s, and each block is separated by an empty line (`\n\n`)
[Answer]
# Ruby, 68 bytes
Prints the exact same output as the example given in the question
```
puts (0..511).map{|i|("%09b"%i).tr("01",".X").gsub(/.../){$&+$/}}*$/
```
[Answer]
# Python 3, 80 bytes
```
for i in range(512):print("\n".join(format(i,'09b')[j:j+3]for j in(0,3,6)),"\n")
```
I managed to outgolf someone :)
[Answer]
# PHP, 55 bytes
```
for(;$c<512;)echo chunk_split(sprintf("%09b ",$c++),3);
```
uses `0` and `1`. Run with `-r`.
[Answer]
# Pyth, 11 bytes
```
V^`T9jbc3Nk
```
[**Try it here!**](https://pyth.herokuapp.com/?code=V%5E%60T9jbc3Nk&debug=0)
Thanks @Jakube :)
[Answer]
# [Python 2](https://docs.python.org/2/), 56 bytes
```
from itertools import*
print set(combinations('X.'*9,9))
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P60oP1chsyS1qCQ/P6dYITO3IL@oRIuroCgzr0ShOLVEIzk/NykzL7EkMz@vWEM9Qk9dy1LHUlPz/38A "Python 2 – Try It Online")
Returns the 512 configurations as a set object in python. Refer to ungolfed version to make output more readable.
Ungolfed Version to make output more readable:
# [Python 2](https://docs.python.org/2/), 121 bytes
```
from itertools import*
for i in set(combinations('X.'*9,9)):
for j in range(3):print''.join(list(i))[j*3:(j*3)+3]
print
```
[Try it online!](https://tio.run/##HcqxDsIgEADQuXwFGweaDjKVLzExDtVQPVLuyHGLX4/W5U2vffTNdBljE64WNYsy791ibSwazMZi0SLZnhWeXB9IqyJTB3edXVjOi/fJTEcrR5OVXhmiT02Q1Lm5MBLs2BXQ@1sJMcEPf4p3M/3PGF8 "Python 2 – Try It Online")
[Answer]
# C - 97 bytes
```
i;main(j){for(;i++<512;)for(j=0;j++<13;)putchar(j%4&&j<13?i%(1<<j-j/4)>(1<<j-j/4-1)-1?88:46:10);}
```
Basically prints the example output from the original question.
[Answer]
## Swift 2, 92 bytes
Int to binary string in Swift takes up too many chars so I just use two nested loops...
```
var s="";for x in 0..<512{(0..<9).map{s+=($0%3==0 ?"\n":"")+"\(x>>$0&1)"};s+="\n-"};print(s)
```
[Answer]
# Prolog (SWI), 98 bytes
Output is a list of 3x3 matrices containing the elements 0 and 1.
```
r([]).
r([H|T]):-between(0,1,H),r(T).
p(Y):-Z=[[_,_,_],[_,_,_],[_,_,_]],findall(Z,maplist(r,Z),Y).
```
[Online interpreter](http://swish.swi-prolog.org/p/DEEQVgbL.pl)
I feel like the matrix generation could be shorter.
It should be possible to fit the between in a forall or something similar, but I can't figure out how.
Golfing tips appreciated.
[Answer]
# Perl, ~~56~~ 55 bytes
```
print$_/9&1<<$_%9?1:0,$/x(!(++$_%3)+!($_%9))for+0..4607
```
Output:
```
000
000
000
100
000
000
...
```
[Answer]
# Python 3, 123 121 109 103 bytes
Here is my old one:
```
import itertools
[print(a+b+c,d+e+f,g+h+i,'\n',sep='\n') for a,b,c,d,e,f,g,h,i in itertools.product(['X','.'],repeat=9)]
```
And here is my new one:
```
import itertools as i
[print(a[:3],a[3:6],a[6:],'\n',sep='\n') for a in i.product(['X','.'],repeat=9)]
```
This prints extra characters but the OP said ASCII art is allowed which implies multiple characters are fine.
[Answer]
# **Python 3, 74 bytes**
```
i=512;b="\n"
while i:i-=1;a=format(i,'09b');print(a[:3]+b+a[3:6]+b+a[6:],b)
```
Just a little shorter than Destructible Lemon's answer
[Answer]
## [Perl 5](https://www.perl.org/), 32 bytes
```
$_=("{.,#}"x3 .$/)x3;say<"$_\n">
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3lZDqVpPR7lWqcJYQU9FX7PC2Lo4sdJGSSU@Jk/J7v//f/kFJZn5ecX/dX1N9QwMDQA "Perl 5 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
T3ã¶«3ãJ»
```
Uses the digits `[1,0]`. The `T` could be replaced with `₂`, `₃`, or `₆` to use the digits `[2,6]`, `[9,5]`, or `[3,6]` respectively.
[Try it online.](https://tio.run/##yy9OTMpM/f8/xPjw4kPbDq0GUl6Hdv//DwA)
Outputting as an unformatted list could have been **5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)**: [`T3ã3ã`](https://tio.run/##yy9OTMpM/f8/xPjwYiD6/x8A).
**Explanation:**
```
T # Push 10
3ã # Take the cartesian power of 3 with its digits:
# ["111","110","101",...,"000"]
¶« # Append a newline to each triplet
# ["111\n","110\n","101\n",...,"000\n"]
3ã # Take the cartesian power of 3 with this list of strings:
# [["111\n","111\n","111\n"],["111\n","111\n","110\n"],...,["000\n","000\n","000\n"]]
J # Join each inner list together
# ["111\n111\n111\n","111\n111\n110\n",...,"000\n000\n000\n"]
» # And join that list by newlines
# "111\n111\n111\n\n111\n111\n110\n\n...\n000\n000\n000\n"
# (after which it is output implicitly as result)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 15 bytes
```
žAFNžA+b¦3ô»,¶?
```
[Try it online!](https://tio.run/nexus/05ab1e#@390n6ObH5DQTjq0zPjwlkO7dQ5ts///HwA "05AB1E – TIO Nexus")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
512+ḶBḊ€s€3Y€j“¶¶
```
[Try it online!](https://tio.run/nexus/jelly#@29qaKT9cMc2p4c7uh41rSkGYuNIIJH1qGHOoW2Htv3/DwA "Jelly – TIO Nexus")
Uses `01`. Because of a bug in `⁾`, I had to use `“¶¶` instead of `⁾¶¶`, because otherwise, instead of two newlines, two pilcrows would have showed up in the output. As you can see, though, that didn't cost me any bytes at all.
K beats this, so this must be further golfed down.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 42 bytes
```
512.times{puts ("%09b"%_1).scan(/.../),$/}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGCpaUlaboWN7VMDY30SjJzU4urC0pLihU0lFQNLJOUVOMNNfWKkxPzNPT19PT0NXVU9GshOqAaYQYAAA)
[Answer]
# [Uiua](https://www.uiua.org), 12 bytes
```
≡(↯3_3)⋯⇡512
```
Outputs an array of 512 3x3 bit matrices. Makes clever use of the `bits ⋯` primitive, which converts all numbers in an array to lists of bits.
With `&gifs`, you can make a very tiny GIF cycling every grid.
[Pad, GIF version](https://uiua.org/pad?src=0_8_0__4omhKOKGrzNfMynii6_ih6E1MTIgIyBNYWluIGNvZGUKJmdpZnMgMTIK)
] |
[Question]
[
Create a program, that converts input string to a palindrome starting with the input string. The program itself must be a palindrome.
For example input: `neverod`, print `neveroddoreven`. You should handle multi-word, multi-line inputs as well.
[Answer]
# Dyalog APL, 6 4
```
⌽,,⌽
```
[Try it here.](http://tryapl.org/?a=f%u2190%20%u233D%2C%2C%u233D%20%u22C4%20f%20%27abcde%27&run)
Other solutions:
```
⌽,⊢⊢,⌽
⌽⊢⊢,⊢⊢⌽
```
### Explanation
They are just:
```
{⌽((,⍵),(⌽⍵))}
{⌽((,⍵)⊢((⊢⍵),(⌽⍵)))}
{(⌽⍵)⊢((⊢⍵),((⊢⍵)⊢(⌽⍵)))}
```
Monadic `,` and `⊢` does nothing on strings. Dyadic `,` is concatenation. Dyadic `⊢` returns its right operand. And `⌽` is obviously reversion.
[Answer]
# piet 19x2 = 38

Accepts input until it encounters 0x00. Doesn't terminate, but output will be correct.
[Answer]
## APL, 9
```
⍞←Z,⌽,Z←⍞
```
Explanation:
```
Z←⍞ ⍝ read a line from the keyboard, and store it in Z
, ⍝ flatten into one-dimensional array (this has no effect here)
⌽ ⍝ reverse
Z, ⍝ concatenate Z to its reverse
⍞← ⍝ explicit output (not necessary, but it makes it a palindrome)
```
[Answer]
# CJam, 13 bytes
```
qL;_-1%1-_;Lq
qL; "Read the input, Put an empty array on stack and pop that array";
_-1% "Now the string is on top, make a copy and reverse the copy";
1- "Remove occurrences of integer 1 from the reverse string. [no-op]";
_; "Copy the reversed string and pop it";
Lq "Put an empty array on stack and read the remaining input. Remaining";
"input will be empty as we already read whole of the input";
```
[Try it online here](http://cjam.aditsu.net/#code=qL%3B_-1%251-_%3BLq&input=asdf123)
---
or..
# GolfScript, 9 bytes
```
.-1%}%1-.
. "Input is already on stack. Make a copy";
-1% "Reverse the copy";
} "This marks the beginning of a super comment. Anything after this in the";
"code is a comment";
%1-. "no-op comment";
```
[Try it here](http://golfscript.apphb.com/?c=OyJhc2RmZzEyMyIKCgouLTElfSUxLS4%3D)
[Answer]
# Haskell, 102+22=124 bytes
```
a b fa=fa<|>b
fa=reverse>>=a
main=interact fa
niam=main
af tcaretni=niam
a=>>esrever=af
b>|<af=af b a
```
This must be run with the `Control.Applicative` module in scope, which can be set via the ghci init file `.ghci`: `:m Control.Applicative` (-> +22 bytes).
No comment trick, just 7 functions where 4 of them are never called.
If functions (instead of programs) are allowed:
# Haskell, 55+22=77 bytes
```
a b fa=fa<|>b
f=reverse>>=a
a=>>esrever=f
b>|<af=af b a
```
Usage `f "qwer"`-> `"qwerrewq"`
Edit: the previous version was just wrong.
[Answer]
## C++, 162 bytes
```
#include<cstdio>//
main(){int c=getchar();if(c>0)putchar(c),main(),putchar(c);}//};)c(rahctup,)(niam,)c(rahctup)0>c(fi;)(rahcteg=c tni{)(niam
//>oidtsc<edulcni#
```
## C, 117 bytes
```
main(c){c=getchar();if(c>0)putchar(c),main(),putchar(c);}//};)c(rahctup,)(niam,)c(rahctup)0>c(fi;)(rahcteg=c{)c(niam
```
[Answer]
# Pyth, 11 bytes
```
+z_z " z_z+
```
In Pyth, anything preceding with a space is not printed. So we simply add the negative of the string to itself, put a space, start a string and mirror the left side of the quote"
[Try it online here](http://pyth.herokuapp.com/?code=%2Bz_z%20%22%20z_z%2B&input=asdfgh)
[Answer]
# Ruby, 44
```
s=gets p
s+=s.reverse||esrever.s=+s
p steg=s
```
Takes a multiline string as input from stdin, outputs a Ruby representation of that string concatenated to its reverse. Could trim a character by replacing `||` with `#` to comment out the dead code on the second line.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 4 bytes
```
êêêê
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=6urq6g==&input=Im5ldmVyb2Qi)
### How it works
```
U.ê("ê".ê("ê")) Transpiled to JS
.ê("ê") String.ê(string): true if `this` is palindrome
"ê".ê("ê") true (treated same as 1)
U.ê( ) String.ê(number): palindromify
"abc"->"abccba" if `number` is odd, "abcba" otherwise
`true` is odd number, so we achieve the desired function
```
# Alternative 4 bytes
```
pwwp
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=cHd3cA==&input=Im5ldmVyb2Qi)
### How it works
```
U.p("w".w("p")) Transpiled to JS
"w".w( ) Reverse of "w" ("p" is ignored)
U.p("w") Append U.w(), which is reverse of U, to the right of U
```
[Answer]
## PowerShell, 67
```
$args|%{$_+-join$_[$_.Length..0]}#}]0..htgneL._$[_$nioj-+_${%|sgra$
```
[Try it online](https://tio.run/##BcFRCoAgDADQw7S@xOFBvIHICBpqxAyV@ijPvt676sOtZz5PVdha6t/6Ahl71CJAAQg9SxoZ0cW5zOgQ80jCHgkCgZR6WEPwrl9PbQNVFb651f0H)
As suggested by @mazzy the code can be shortened by 12 bytes when using a static range. This, however, limits the input length to 9KBytes. Theoratically 9MBytes would be possible but it would slow down the code significantly.
```
$args|%{$_+-join$_[9kb..0]}#}]0..bk9[_$nioj-+_${%|sgra$
```
[Answer]
# Jolf, 9 bytes
[Try Here](http://conorobrien-foxx.github.io/Jolf/#code=Yc63K2lfaSvOt2E)
```
aη+i_i+ηa
```
Explanation: I only just started Jolf and I don't think I'm explaining this properly.
```
aη alert function, arity of the function can't be reduced by 1 so it stays at 1
+i_i concatenate the input with the reversed input
+η arity of the add reduced by 1, it just takes the following character (a)
a returns the input
```
[Answer]
## [<>^v](https://github.com/Astroide/---v), 55 bytes
```
.~""?§0 26 0«0 72!=0_~?(___|___(?~_0=!27 0«0 62 0§?""~.
```
##### Explanation
```
.~""?§0 26 0«0 72!=0_~?(___|___(?~_0=!27 0«0 62 0§?""~.
. Input string, push to stack
~ Print top of stack without newline
"" Push empty string to stack
? Swap top two elements
§ Split top of stack (now the user input) with second element of stack (`""`)
0 Push 0
26 Push 26
0 Push 0
« Goto ; redirects program to the `|`
| Reverses instruction pointer direction, now going left
_ Pop stack
_ Pop stack (again)
_ For the third time, pop the stack
) Decrement top of stack
? Swap top two elements
~ Print top of stack without newline
_ Pop stack
0 Push 0
= Execute next instruction only if top two elements of the stack are equal
! Exit, executed only if the top two elements of the stack are equal
72 Push 27 (pointer is going left, so literal 72 -> value 27
0 Push 0
« Goto _
_ (Loop goes on, go back to the first "Pop stack")
___(?~_0=!27 0«0 62 0§?""~. This part is useless and never executed, only for the palindrom requirement
```
What it does is first print the first part of the palindrom, the string itself. Then it stores every letter of the string and the string's length on the stack in reverse order, and print them.
[run online](https://v.astroide.repl.co/#e86c1b42879e59e7696711550bfd6586b97297c9e600e5471d2b5a51644f70fa) (`>` is the prompt, it is not an output of the program)
---
Or, with the string reverse operator :
```
.~—;!;—~.
```
Inputs a string, prints it, reverses it, and prints it.
[run online](https://v.astroide.repl.co/#6c4bd368594074d83cb8b30581d910e40a56301f858a04c84c9f7b1e377a5cb7)
[Answer]
# Fuzzy Octo Guacamole, 17 bytes
```
^dz''sjX@Xjs''zd^
```
Alt solution in 19 bytes:
```
^Czs''.jX@Xj.''szC^
```
They both take input, duplicate and reverse, and join the stack.
Explanation:
```
^dz''sj@js''zd^
^ # Get input
d # Duplicate ToS (input)
z # Reverse ToS
'' # Push empty string (for joining separator)
s # Move the empty string to the inactive stack
j # Join the active stack with the top of the inactive stack as the delimiter and push the result.
X # Print the ToS
@ # End the program
Xjs''zd^ # Backwards version of the beginning.
```
[Answer]
# [tinyBF](http://esolangs.org/wiki/TinyBF), 40
```
|=||==>|=|=|=+|=>==||==>=|+=|=|=|>==||=|
```
My first thought was Brainfuck, but it's impossible to match the braces... fortunately tinyBF has simpler flow control.
No comments, it takes a null terminated string as input and returns the result in a null terminated string. You can test it [here](http://bataais.com/tinyBF.html), just be forewarned that it doesn't halt (although Firefox at least prompts to stop the unresponsive script).
**Commented:**
```
|=| Retrieve a byte of input.
| Positive (opening) bracket.
== Output the byte.
> Move the pointer in positive direction.
|=| Retrieve a byte of input.
= Switch direction to negative.
| Negative (closing) bracket.
= Switch direction.
+ Increment byte to execute return loop.
| Opening bracket.
=> Move the pointer in negative direction.
== Output the byte.
| Closing bracket.
|=| Output the null terminator.
|==>|=|=|=+|=>==| ...and keep null terminating it just to be sure.
```
Note that if you encode it into 2 bit instructions, it cuts the size to 10 bytes (wouldn't be a palindrome).
[Answer]
## Python 3, 59 bytes
```
a=input()#
print(a+a[::-1])#([1-::]a+a)tnirp
#()tupni=a
```
I tried my best to find a solution that only used one line but I had no luck.
## Python 3, 79 bytes
```
a=input()#()tupni=a#
print(a+a[::-1])#([1-::]a+a)tnirp
#a=input()#()tupni=a
```
My original attempt in which every line is a palindrome. I don't think that it is necessary for this challenge, but I included it just in case.
[Answer]
# Vitsy, 9 bytes
```
z:Zr?rZ:z
z Grab all string input from the command line arguments.
: Duplicate this stack.
Z Print all elements in this stack as a string.
r Reverse (reverses an empty stack).
? Go right a stack.
r Reverse (reverses the input).
Z Print all elements in this stack as a string.
: Duplicate the stack (duplicates an empty stack).
z Grab all input from the command line (the command line arguments stack is already empty).
```
[Try it online!](http://vitsy.tryitonline.net/#code=ejpacj9yWjp6&input=&args=VGhpcyBpcyBhIHN0cmluZy4)
[Answer]
# [Befunge](http://github.com/catseye/Befunge-93), 37 bytes
```
~:0`!#v_:,
>:#,_@_,#:>
,:_v#!`0:~
```
[Try it online!](http://befunge.tryitonline.net/#code=fjowYCEjdl86LAogID46IyxfQF8sIzo-ICAKLDpfdiMhYDA6fg&input=bmV2ZXJvZA)
The top line pushes and prints every character of input. The second line (before the `@`) prints the stack in reverse, but we enter at the contional `_` to consume the -1 generated when finish reading input. The other half of the code (including those ugly trailing newlines) makes the source a palindrome, but nevers runs.
[Answer]
# C# (~~33~~ 32 + 1) \* 2 = ~~68~~ 66 bytes
saved 2 bytes to the use of .Aggregate()
```
s=>s+s.Aggregate("",(a,b)=>b+a);//;)a+b>=)b,a(,""(etagerggA.s+s>=s
```
Oh the good old lambda, you can catch it with
```
Func<string, string> f=<lambda here>
```
and then call it with
```
f("neverod")
```
[Answer]
## Perl, 45 bytes
```
;print$_=<>,~~reverse;m;esrever~~,><=_$tnirp;
```
Pretty straightforward, `print`s the input (`$_=<>`) followed by the `reverse` of it. `reverse` returns `$_` because we're using it in scalar context by prefixing with `~~`. Then we match (`m//` using `;` as delimiter), in void context, against the reverse of the script.
If we can guarrantee we won't have to create a palindrome of `esrever,><=_$tnirp` we can shorten the code to **43 bytes**:
```
g.print$_=<>,reverse.m.esrever,><=_$tnirp.g
```
### Usage
```
echo -n 'neverod' | perl -e 'g.print$_=<>,reverse.m.esrever,><=_$tnirp.g'
neveroddoreven
```
---
## Perl, 26 bytes
**Includes 25 bytes code + 1 for `-p`.**
```
$_.=reverse;m;esrever=._$
```
I don't think this is valid since it requires the `-p` flag which I don't think can be easily combined into the script contents to make a true palindrome. Pretty much the same calls as above, except it relies on the fact that `-p` also adds a `;` behind the scenes (on newer Perls...) to close the `m//`.
### Usage
```
echo -n 'neverod' | perl -pe ';$_.=reverse;m;esrever=._$;'
neveroddoreven
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 1 byte
```
m
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJtIiwiIiwiYmFnIl0=)
A simple 1-byter - `m` mirrors input by appending its reverse.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~5~~ 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
R«R
```
-2 bytes thanks to *@ovs*.
[Try it online.](https://tio.run/##yy9OTMpM/f8/6NDqoP//lZSUSjIyi7mAKJGrJLW4BCgAAA)
**Explanation:**
```
R # Reverse the (implicit) input
# i.e. "neverod" → "doreven"
« # Append it to the (implicit) input
# → "neveroddoreven"
R # Reverse it (no-op, since it's a palindrome)
# (after which the result is output implicitly)
```
If we are allowed to output `neverodoreven` for the input `neverod`, which is still a palindrome, it can be done in **1 byte** instead with the palindromize builtin:
```
û
```
[Try it online.](https://tio.run/##yy9OTMpM/f//8O7//5WUlEoyMou5gCiRqyS1uAQoAAA)
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), ~~5~~ 3 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
x+x
```
[Try it online.](https://tio.run/##y00syUjPz0n7/79Cu@L/f6W81LLUovwUJS6lpJxEIGloZGxiamZuYakEAA)
Or 1 byte if overlapping the last character would be allowed, with the palindromize builtin:
```
ñ
```
[Try it online.](https://tio.run/##y00syUjPz0n7///wxv//lfJSy1KL8lOUuJSSchKBpKGRsYmpmbmFpRIA)
**Explanation:**
```
x # Reverse the (implicit) input
+ # Append it to the (implicit) input
x # Reverse it (no-op, since it's a palindrome)
# (after which the entire stack is output implicitly)
```
[Answer]
# Pyth, 15
```
k k+ z_z +k k
```
Notice the space at the beginning and at the end.
Quite annoying task in Pyth. `z_z` prints the desired palindrome, but it prints `z` (the input string) and `_z` the inverse on two different lines. `+` combines the two words, but `+` at the end requires two new statements at the end (and at the beginning). I choose `k` and `k`, which are just empty strings. Then a lot of white space, which suppresses printing (and printing empty spaces, which generate of course line breaks).
Since the white space suppresses every output except the `+z_z`, you can replace the `k`s and literal with arity 0. E.g. `1 2+ z_z +2 1` or `T Z+ z_z +Z T`.
Try it [online](https://pyth.herokuapp.com/?code=%20k%20k%2B%20z_z%20%2Bk%20k%20&input=neverod&debug=0).
[Answer]
# JavaScript, 58 bytes
```
p=>p+[...p].reverse().join``//``nioj.)(esrever.]p...[+p>=p
```
[Answer]
# PHP, 28+1+28=57 bytes
```
<?=($x=$argv[1]).strrev($x);#;)x$(verrts.)]1[vgra$=x$(=?<
```
takes input from command line argument. quote for multi-word, escape newlines for multi-line.
[Answer]
# Python 2, 51 bytes
```
s=input();print s+s[::-1]#]1-::[s+s tnirp;)(tupni=s
```
I'm surprised no-one thought of this! Needs quoted input (`'` or `"`). If functions were allowed, I could have done this for 37 bytes instead:
```
lambda x:x+x[::-1]#]1-::[x+x:x adbmal
```
[Answer]
# C++14, ~~152~~ 116 bytes
As unnamed lambda, assumes `s` to be `string`
```
[](auto s){decltype(s)r;for(auto c:s){r=c+r;}return s+r;}//};r+s nruter};r+c=r{)s:c otua(rof;r)s(epytlced{)s otua(][
```
Old solution:
```
[](auto s){auto r=s;for(auto p=s.rbegin()-1;++p!=s.rend();r+=*p);return r;}//};r nruter;)p*=+r;)(dner.s=!p++;1-)(nigebr.s=p otua(rof;s=r otua{)s otua(][
```
Usage:
```
auto f=[](auto s){decltype(s)r;for(auto c:s){r=c+r;}return s+r;};
main(){
string a="123456789";
cout << f(a) << endl;
}
```
[Answer]
# x86-64 Assembly (Microsoft x64 calling convention), 89 bytes:
```
80 39 00 48 8B D1 4C 8B C1 74 0B 48 FF C2 49 FF C0 80 3A 00 75 F5 48 FF CA 8A 02 41 88 00 48 8B C2 48 FF CA 49 FF C0 48 3B C1 77 ED C3 ED 77 C1 3B 48 C0 FF 49 CA FF 48 C2 8B 48 00 88 41 02 8A CA FF 48 F5 75 00 3A 80 C0 FF 49 C2 FF 48 0B 74 C1 8B 4C D1 8B 48 00 39 80
```
Disassembled:
```
0000000000000000: 80 39 00 cmp byte ptr [rcx],0
0000000000000003: 48 8B D1 mov rdx,rcx
0000000000000006: 4C 8B C1 mov r8,rcx
0000000000000009: 74 0B je 0000000000000016
000000000000000B: 48 FF C2 inc rdx
000000000000000E: 49 FF C0 inc r8
0000000000000011: 80 3A 00 cmp byte ptr [rdx],0
0000000000000014: 75 F5 jne 000000000000000B
0000000000000016: 48 FF CA dec rdx
0000000000000019: 8A 02 mov al,byte ptr [rdx]
000000000000001B: 41 88 00 mov byte ptr [r8],al
000000000000001E: 48 8B C2 mov rax,rdx
0000000000000021: 48 FF CA dec rdx
0000000000000024: 49 FF C0 inc r8
0000000000000027: 48 3B C1 cmp rax,rcx
000000000000002A: 77 ED ja 0000000000000019
000000000000002C: C3 ret
000000000000002D: ED in eax,dx
000000000000002E: 77 C1 ja FFFFFFFFFFFFFFF1
0000000000000030: 3B 48 C0 cmp ecx,dword ptr [rax-40h]
0000000000000033: FF 49 CA dec dword ptr [rcx-36h]
0000000000000036: FF 48 C2 dec dword ptr [rax-3Eh]
0000000000000039: 8B 48 00 mov ecx,dword ptr [rax]
000000000000003C: 88 41 02 mov byte ptr [rcx+2],al
000000000000003F: 8A CA mov cl,dl
0000000000000041: FF 48 F5 dec dword ptr [rax-0Bh]
0000000000000044: 75 00 jne 0000000000000046
0000000000000046: 3A 80 C0 FF 49 C2 cmp al,byte ptr [rax+FFFFFFFFC249FFC0h]
000000000000004C: FF 48 0B dec dword ptr [rax+0Bh]
000000000000004F: 74 C1 je 0000000000000012
0000000000000051: 8B 4C D1 8B mov ecx,dword ptr [rcx+rdx*8-75h]
0000000000000055: 48 00 39 add byte ptr [rcx],dil
0000000000000058: 80
```
Note that the code after the `ret` instruction at `2C` is unreachable so it doesn't matter that it's nonsense
[Answer]
# [Backhand](https://github.com/GuyJoKing/Backhand), ~~33~~ 27 bytes
```
iH~0}|{<:: oi]io ::<{|}0~Hi
```
[Try it online!](https://tio.run/##S0pMzs5IzEv5/z/To86gtqbaxspKIT8zNjNfwcrKprqm1qDOI/P//8SkZAA "Backhand – Try It Online")
Unlike a lot of the solutions here, this one actually *does* use the palindromised code!
### Explanation:
```
i 0 |{ Get the first character and enter the loop
: o Output the character while preserving it
i : Get input and duplicate it
<{ Turn around
] Increment the copy to check if EOF
}| < Loop again if not EOF
~ If EOF, pop the extra copy of EOF
H Terminate, printing the contents of the stack.
```
Altogether, the unexecuted instructions are:
```
: i o : |}0~Hi
```
[Answer]
# [Python 3](https://docs.python.org/3/), 53 bytes
```
t=input();print(t+t[::-1])#)]1-::[t+t(tnirp;)(tupni=t
```
[Try it online!](https://tio.run/##DcgxDoAgDAXQw7i0MQzErYSTEHa7fBvyGTx99Y0vXt4Prkx2R2yKtlgOCk8Os1KnHjprMRv/COErmgp3wDszPw "Python 3 – Try It Online")
] |
[Question]
[
A palindromic number, as a refresher, is any number which reads the same forward as backwards. However, what about palindromes in other bases?
## Input
Any integer `b` where `b > 1`.
## Output
All integer base 10 numbers from 0 to 1000 inclusive that are palindromes in base b. The output can either be a list of integers, or integers separated by a delimiter such as a comma or a newline.
## Test cases
`Input->Output`
`10->{0,1,2,3,4,5,6,7,8,9,11,22,33,44,55,66,77,88,99,101,111,121,131,141,151,161,171,181,191,202,212,222,232,242,252,262,272,282,292,303,313,323,333,343,353,363,373,383,393,404,414,424,434,444,454,464,474,484,494,505,515,525,535,545,555,565,575,585,595,606,616,626,636,646,656,666,676,686,696,707,717,727,737,747,757,767,777,787,797,808,818,828,838,848,858,868,878,888,898,909,919,929,939,949,959,969,979,989,999}`
`2->{0,1,3,5,7,9,15,17,21,27,31,33,45,51,63,65,73,85,93,99,107,119,127,129,153,165,189,195,219,231,255,257,273,297,313,325,341,365,381,387,403,427,443,455,471,495,511,513,561,585,633,645,693,717,765,771,819,843,891,903,951,975}`
`9->{0,1,2,3,4,5,6,7,8,10,20,30,40,50,60,70,80,82,91,100,109,118,127,136,145,154,164,173,182,191,200,209,218,227,236,246,255,264,273,282,291,300,309,318,328,337,346,355,364,373,382,391,400,410,419,428,437,446,455,464,473,482,492,501,510,519,528,537,546,555,564,574,583,592,601,610,619,628,637,646,656,665,674,683,692,701,710,719,728,730,820,910,1000}`
[Answer]
# [Python 3](https://docs.python.org/3/), 78 bytes
Outputs the numbers in decreasing order `1000 -> 0`, and short-circuits with a `ZeroDivisionError`
```
def f(b,n=1000):
r=0;m=n
while m:r=r*b+m%b;m//=b
n==r==print(n);f(b,n-n//n)
```
[Try it online!](https://tio.run/##HcvLDgIhDEDRPV/RjQn4AnXlkP4MCpkm0zIpGDNfj4@bnOVdtz5XuQ3itWqHtjXzdW65a368tFGVhZi6vf9y45kLFJuOgpcQgpsMKIbIKAbeMy0ZeFLUfTrwLkX2HpMBQVTEVUm6FRf/@0m8FzeKvbrxAQ "Python 3 – Try It Online")
The `f(b,n-n//n) -> f(b,n-1)` recurses until `0`, and errors because dividing by zero is undefined.
### [Python 3](https://docs.python.org/3/), 76 bytes
We can shorten the answer by 2 bytes if a floating-point output is allowed.
```
def f(b,n=1e3):
r=0;m=n
while m:r=r*b+m%b;m//=b
n==r==print(n);f(b,n-n/n)
```
[Try it online!](https://tio.run/##HcvLDgIhDEDRPV/RjQn4Qp2VQ/ozKGSaTAspGDNfj4@bnOWtW1@KTIO4Fu3Qtma@zi11TY@XNiqyElO3919uPFOGbONR8JomNxtQvARGMfBeaE3As6Lu44F3MbD3GA0IoiJWJelWXPjfJ/HiRrY3Nz4 "Python 3 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/) forwards, ~~118~~ ~~117~~ 115 bytes
```
b[11],*p,*x,i,m;f(n){for(i=-1;i++<1e3;){for(p=x=b,m=i;m;*p++=m%n,m/=n);while(p>x)m|=*--p-*x++;m||printf("%d,",i);}}
```
[Try it online!](https://tio.run/##ZcvNCoJAFIbhvVcxGML8lmOrOI03Ui3KnzzgTEMZCeq1m1gtpLN6@XhOpq5ZNo6Xg9Ynyb3krURpoaSOdeXtTtEoDSjEXhdb@EzetOYirUGwwL0QxkZO2o1xDF4V1gX1actsb7hSXvFWCLB97@/ompKGUS5DiQyGYVyhy@pnXpD9o8nxtq7SIJgQsWd0lAVdQKb7/emYmJSEDOa1pDr@5g8cXbIUyR/YLcFuqmHu8Q0 "C (gcc) – Try It Online")
# [C (gcc)](https://gcc.gnu.org/), backwards, ~~115~~ 113 bytes
```
b[11],*p,*x,i,m;f(n){for(i=1001;i--;){for(p=x=b,m=i;m;*p++=m%n,m/=n);while(p>x)m|=*--p-*x++;m||printf("%d,",i);}}
```
[Try it online!](https://tio.run/##ZcvLDoIwEIXhPU/RYEx6VcrOjOVF1IUUkElsbbzEJsKzI1FZEGf15@Qbq07WDkO50/ogeZA8SpQOGurZq7lcKRqdZRpQKfgOwURTSmcQHPAghHFLL93aeAbPFs81DUVkrjNcqaB4FAJc14Ur@ntD02UlU4kM@n5YoLfnR1WT7e1e4WXVFkkyIuKO6ClLXgkZb/rTGTEFSRl81obq7JcT2Pt8LvI/sJmDzVj9p4c3 "C (gcc) – Try it online")
## Explanation
C signature:
```
// Technically implicit int with a void return
void f(int base);
```
Loops through all numbers from 0 to 1000, converts them to base `base` by hand, then checks if it is a palindrome.
The backwards version does the same thing, but backwards.
Prints matching numbers, comma separated, to stdout.
Ungolfed version
```
#include <stdio.h>
// A buffer to hold our converted integer.
// It is large enough for 1000 in binary.
int buffer[11];
// Start and end pointers for buffer
int *start, *end;
// Loop counter
int i;
// Temporary
int tmp;
void f(int base)
{
// Loop for 0 to 1000
#ifdef BACKWARDS
// Loop backwards
for (i = 1001; i-- != 0;) {
#else
// Loop forwards
// for (i = 0; i <= 1000; i++)
for (i = -1; i++ < 1e3; ) {
#endif
// Convert to base in buffer, tracking the length in end.
for(start = end = buffer, tmp = i; tmp != 0;) {
*end++ = tmp % base;
tmp /= base;
}
// Check if it is a palindrome.
// Loop while our starting pointer is less than our ending pointer.
// tmp will zero at the start thanks to the loop condition.
while (end > start)
// Assembly style comparison using subtraction.
// If *end == *start, tmp will still be zero.
// If not, it will be permanently set to non-zero with a binary or.
tmp |= *--end - *start++;
// If tmp is still zero (meaning it is a palindrome), print.
tmp || printf("%d,", i);
}
}
```
Thanks to Arnauld for the -1 bytes!
Thanks to Toby Speight for the -2 bytes!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes
```
₄ÝʒIвÂQ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//UVPL4bmnJnle2HS4KfD/f0MDAwMA "05AB1E – Try It Online")
## Explained
```
₄Ý "Push the range [0, 1000]"\
ʒ "and keep the items where:"\
Iв "After being converted to base (input)"\
ÂQ "have its reverse equal to itself"\
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
ȷŻbŒḂ¥Ƈ
```
[Try it online!](https://tio.run/##ASIA3f9qZWxsef//yLfFu2LFkuG4gsKlxof/w4figqz//zEwLCAy "Jelly – Try It Online")
## How it works
```
ȷŻbŒḂ¥Ƈ - Main link. Takes a base b on the left
ȷ - 1000
Ż - [0, 1, 2, ..., 1000]
¥ - Group the previous 2 links into a dyad f(k, b):
b - Convert k to base b
ŒḂ - Is this a palindrome?
Ƈ - Filter [0, 1, 2, ..., 1000], keeping those k that are true under f(k, b)
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
A³ô fÈìU êê
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QbP0IGbI7FUg6uo&input=Mg)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 44 bytes
```
Pick[r=0~Range~1000,r-r~IntegerReverse~#,0]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277PyAzOTu6yNagLigxLz21ztDAwECnSLeozjOvJDU9tSgotSy1qDi1TlnHIFbtf0BRZl6JgkN6tKFBLBeEE62kBGMCxY2wC1vG/v8PAA "Wolfram Language (Mathematica) – Try It Online")
-13 bytes from @att
[Answer]
# JavaScript (ES6), ~~87~~ 86 bytes
Returns a comma-separated string.
```
n=>(g=k=>--k&&g(k)+((h=k=>a=k?[k%n,...h(k/n|0)]:[])(k)+''==a.reverse()?[,k]:''))(1001)
```
[Try it online!](https://tio.run/##ZcqxDsIgEADQ3f@w3MWC1M0m134IYSCVUr0GDJhO/jva0bi@vIfbXJny/fmSMd18nalGGiAQ0yAlN00AxhPAsoMjHg0fY6uUWoDP8a3R9sbifoQgcir7zefiAUfTsu2FQIRO6w7rlGJJq1drCjB/DfHwS5c/uSLWDw "JavaScript (Node.js) – Try It Online")
### How?
```
n => ( // n = input base
g = k => // g is a recursive function taking a counter k
--k && // decrement k; abort if it's equal to 0
g(k) + ( // otherwise do a recursive call and append the ...
( h = k => // ... result of the recursive function h
a = k ? // which builds an array a[]
[ k % n, // consisting of each digit of k in base n,
...h(k / n | 0) ] // dividing k by n and taking the integer part
: // for the next iteration until k = 0
[] //
)(k) + '' // invoke h with k and coerce the result to a string
== a.reverse() ? // if this is palindromic:
[, k] // append a comma followed by k to the output
: // else:
'' // just append an empty string
) //
)(1001) // initial call to g with k = 1001
```
[Answer]
# [Scala](http://www.scala-lang.org/), ~~62~~ 87 bytes
* Fixed after Siu Ching Pong -Asuka Kenji- pointed out `BigInt`'s `toString` only works for bases up to 36.
* Saved 1 byte thanks to [@cubic lettuce](https://codegolf.stackexchange.com/users/74778/cubic-lettuce).
```
b=>0 to 1000 filter{x=>val y=Seq.unfold(x){q=>Option.when(q>0)(q%b,q/b)};y==y.reverse}
```
[Try it online!](https://scastie.scala-lang.org/zTFJgi3VQ3e8ZrLa3yrPLQ)
This is pretty straightforward. It makes a range from 0 to 1000, then filters by checking if they equal their reverse in base `b`. To convert to base `b` (as a string), `BigInt`'s `toString` method ~~is~~was used, but now `Seq.unfold` is used to create a `Seq` of digits.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~12~~ 11 bytes
*Edit: -1 byte thanks to LegionMammal978*
```
foS=↔B⁰ŀdḋ9
```
[Try it online!](https://tio.run/##yygtzv7/Py0/2PZR2xSnR40bjjakPNzRbfn//38jAA "Husk – Try It Online")
The actual 'based palindrome' code is 7 bytes (`foS=↔B⁰`), but specifying 0...1000 costs ~~5~~ 4 (thanks to LegionMammal978) more bytes.
We could save a byte if it's Ok to output a few more based palindromes with values up to decimal 1024 (`foS=↔B⁰ŀ□32`).
```
f # output the truthy values of
ŀdḋ9 # series from zero up to one less than 1001
# (decimal interpretation of binary digits of '9')
o # based on combination of 2 functions:
S=↔ # 1. is it equal to reverse of itself?
B⁰ # 2. digits in base given by argument
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes
```
NθIΦ⊕φ⁼↨ιθ⮌↨ιθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDObG4RMMtM6cEKOqZl1yUmpuaV5KaopGmqaPgWliamFOs4ZRYnKqRqaNQCBQKSi1LLQJyEWJgYP3/v@V/3bIcAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ Input the base `b`
φ Predefined variable 1000
⊕ Incremented
Φ Filter on implicit range
ι Current value
↨ θ Converted to base `b`
⁼ Equals
ι Current value
↨ θ Converted to base `b`
⮌ Reversed
I Cast to string
Implicitly print
```
[Answer]
# [Haskell](https://www.haskell.org/), 63 bytes
```
f b|let 0%m=m;n%m=div n b%(m*b+mod n b)=[n|n<-[0..1000],n==n%0]
```
[Try it online!](https://tio.run/##XYgxDsIwDAB3XuElUgO0ctkQ@CVVh6RpICJ2I1ox9e2YMsINJ93d3fwYc1aN4Nc8LoCGiS@yOaQXCHhT8d4feArfsNTJKte6w6ZpEbE/CpEY7JVdEiAI0w42yjPJAlWEFu3vOP312ep7iNndZq2HUj4 "Haskell – Try It Online")
Based on a nice idea from [dingledooper's Python answer](https://codegolf.stackexchange.com/a/216981/20260): to check that `n` is a base-`b` palindrome, don't generate the list of base-`b` digits, but reverse `n` as a base-`b` number by running a base-conversion reading digits from the end, and check that the result still equals `n`.
The code `|let 0%m=m;n%m=div n b%(m*b+mod n b)` recursively defines an infix function `%` that reverses base `n` (given `0` as an initial second argument). Defining it inside of a `let` guard lets us access the argument `b` to the main function, whereas a standalone function would need to keep passing it with each recursive call.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~17~~ 15 bytes
Thanks to [Razetime](https://codegolf.stackexchange.com/users/80214/razetime) for -2 bytes!
A bug fixed thanks to [Siu Ching Pong](https://codegolf.stackexchange.com/users/74641/siu-ching-pong-asuka-kenji)!
Requires index origin `0`.
```
⍸⎕(⊤≡∘⌽⊤)¨⍳1001
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKM97f@j3h2P@qZqPOpa8qhz4aOOGY969gLZmodWPOrdbGhgYAhS9R@owtP/UdsEAy4ukJiCAoZ6S0tLLi51BSMrda40LiMurke9a7jUDQ3AXEMDKN8SzLWEyxoYQuUNDAE "APL (Dyalog Extended) – Try It Online")
```
⍝ tradfn taking the base as input
⍳1001 ⍝ the indices up to 1000
⍵( )¨ ⍝ apply a function to each index as a right argument and the input base as a left argument:
⌽⊤ ⍝ the reverse of the index converted to the input base
≡ ⍝ does it match
⊤ ⍝ the index converted to the input base
⍸ ⍝ all truthy indices
```
[Answer]
# C - [76 bytes](https://tio.run/##TU/basQgEH3PVwxZFtQYkvStiP0XtSY7sDWLMS24m2@3mtCSgWFmzgXOmHYyJiWUQ98PXPEoRqLpc5w9Edi2uePr9fDowkjq6yfUHCktrJLIo@yFEqqTmkYZmW7UVYstZTF8KXSkLMpPhoO5KQ@M5eObVs8Kcv3c8G6BsKbZUTjQUsWmQYIKM5LDI/7JvyyXC@Q48iMnAn3iS/yTeg0LqesTcnwqoGPg7WIDLOimu23XxcK4OhNwdsC6Xb9V2z5TGvr0lt5/AQ "C (gcc) – Try It Online")
```
i=1001,a,z;f(b){for(;i--;i-z||printf("%d ",i))for(a=i,z=0;a;a/=b)z=z*b+a%b;}
```
# Explanation
Sufficiently different from [my earlier answer](/a/216970/39490) to warrant posting separately. This time, we completely reverse the number, then compare to the original. So we don't need to eliminate trailing zeros, or special-case `0`.
```
void fun(int b)
{
for (int i = 1001; i--;) {
int z = 0;
for (int a = i; a != 0; a /= b) {
z = z*b + a%b;
}
if (i==z) {
printf("%d ",i);
}
}
}
```
This method works reliably for `i` up to `INT_MAX/b` and `b` up to `INT_MAX`, or the appropriate equivalents if we change the integer type used. For unsigned types (or with `gcc -fwrapv`), it should work for the full range of `i`.
[Answer]
# C, 100 bytes
```
i=1001,a,z;f(b){for(;--i;)for(a=i,z=0;i%b*a;a/=b)if(a==z||a==(z=z*b+a%b))printf("%d ",i);puts("0");}
```
[Try it online](https://tio.run/##TU9db4QgEHz3V2y8mABi1L41hP4XoOBtcsWLYptw52@noOnHPuzOzuxksqabjEkJ5TgMI1c8Ckc0fbh5IaLrUNCClEQe5SCw0UwJ1UtN0WVWxuczdxJlZLpVjab0vqAPjtTNO9QcqbhvYSX1UFOxp6zAh0JPClDLZDiYq1qAsbx80upRQa6vK94sENa2BwsnW6rYNEhQYUZyesSv@BN8uUDOlm85HvQ/vbz1t53/CugZLHa1AVb0081222rBbd4EnD2w/rjfq/2YKY1Dekmv3w "C (gcc) – Try It Online")
## Ungolfed code
```
void fun(int b)
{
for (int i = 1001; --i;) {
if (i%b) { /* no leading/trailing zeros */
for (int a = i, z = 0; a != 0; a /= b) {
if (a==z) {
printf("%d ",i);
}
z = z*b + a%b;
if (a==z) {
printf("%d ",i);
}
}
}
}
puts("0");
}
```
## Explanation
This outputs the numbers highest first, since no particular order was specified. For each candidate number, we reduce it (as `a`) by successively dividing by the base, using the remainder to build up the reverse number (in `z`). If `a` becomes equal to `z`, then we have a palindrome. Ordinarily, we'd stop there (`a >= z` in the loop condition), but for golfing, we continue all the way to `a==0`.
We need to test the equality both before and after transferring the remainder to `z`, to accept both odd and even length palindromes.
Finally, we print `0`, which is always a palindrome, and is easier to special-case than include in the loop.
The method works for integers up to `INT_MAX` if we ungolf the condition `i%b*a` back to `i%b&&a`, and would also work for other integer types.
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), 18 bytes
```
{&{x~|x}'x\'!1001}
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NqlqtuqKupqJWvSJGXdHQwMCw9n@auqGBgpGC5X8A "K (ngn/k) – Try It Online")
* `x\'!1001` convert each of 0..1000 to base-x representation
* `{x~|x}'` check if each representation is a palindrome
* `&` get indices of trues
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~92~~ 85 bytes
```
lambda b:[i for i in range(1001)if(f:=lambda n:n*[0]and[n%b]+f(n//b))(i)==f(i)[::-1]]
```
[Try it online!](https://tio.run/##TYxBCsIwEEX3niIbYUYpTXSjAzlJmkVCnTig0xC68fSxiwpuPu/B49fP@lz0equtFz/1V3rnOZlMQQwvzYgRNS1peYCz1qEwMPm9UtJTsDHpHPSY45lBxzEjgqD3vG0gGlyMvTbRFcp2gXj4yeWP74j9Cw "Python 3.8 (pre-release) – Try It Online")
Thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper) for saving 7 bytes!
[Answer]
# Haskell, 67 bytes
```
b&n=take n$mod n b:b&div n b
f b=[n|n<-[0..1000],reverse(b&n)==b&n]
```
`f` is the function of interest. [Try it online!](https://tio.run/##y0gszk7Nyfn/P0ktz7YkMTtVIU8lNz9FIU8hySpJLSWzDMTiSlNIso3Oq8mz0Y020NMzNDAwiNUpSi1LLSpO1QBq1LS1BZKx/3MTM/MUbBVS8rkUgKCgKDOvREEjTcHQQBNVwAiNb6n5HwA "Haskell – Try It Online")
Perhaps the only clever bit here is the use of `take n` to make a base case for the digit-expansion function. When `n=0`, `take n` ignores its argument and so the recursion stops via laziness; when `n>0`, there certainly won't be more than `n` digits so it's safe to keep only the first `n`. The following definition is equivalent (and equally long):
```
b&0=[]
b&n=mod n b:b&div n b
```
...but the `take n` version is more fun because it's more confusing. ^\_^
[Answer]
# [J](http://jsoftware.com/), 27 bytes
```
((-:|.)@(#.inv)"0#])i.@1001
```
## how
* `(...) i.@1001` - The whole thing is a J hook, meaning that the argument will be the left arg to everything in the parens, and the right arg will be the integers from 0 to 1000: `i.@1001`
* `...#]` The phrase inside the parens uses copy `#` to filter the right arg `]` by the boolean mask resulting from the phrase on the left of `#`:
* `(-:|.)@(#.inv)"0` - The rank 0 `"0` ensures the phrase applies to each individual number of the right arg. The phrase itself first converts each of those numbers to a list of digits in the base given by the left arg `(#.inv)`, and then checks if that list equals its reverse `(-:|.)@`. The entire phrase will thus return 1 when this is true and 0 otherwise, and this boolean mask will filter the right arg as desired.
[Try it online!](https://tio.run/##ZZJBbxQxDIXv8ytCi7S7kncUx3EcrwSqQOKEOPTeE6Jqe4AbF@hvX77ZhRMjfcrIk7Hfe8nLOd@cLMpD6eVtqSW3Z1lu1t1jeXcquyIUT3Bcy8f7z5/O@/3x9Hs93O1v1@fvPw839fbh8Lzeaa16PizLt69PP8pjadeX3e5fQev/lVqX5cuHtbTj@19VVExcQlLURUOaSgsxyibdxVWGyWCHyXRJk2RnDVFlZae27U8TZY9O3tPpkdJo0Zx3pyc/t9y6mlhzsU579ttknSG9MotevW8zXXqo9NyGK6BvsDJ9oGkgaiAj0BqbLvZO5k3@namS9EpUZ/jr1afWv0YbVjtmB3bnZphSu/ikSpk6H@bVofIZiENxoihWuipKlImKcmVaqw23QKNm0MFhQMCEZAiqru6BiYZaIzUjXCMdm4CrXrt0hQYGSOsOAwImJHLrlg6QphtsR4UHJxEPv6TlJDjqkKHQwKCDA2ZHwITEOCd6SZRTCIMOviUMpBKcUnCCs07ShgYGHRwGBBDfTCKsKcmpJLcjDTo4DAjgpnDjX89/AA "J – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~82~~ 81 bytes
(or [79 bytes](https://tio.run/##Zc1BCsIwEAXQq9RF4H8QrLiykKsoGZvoQMxIUnXTu6cH6LvAq11Ci/P9E7KWudo7Nt/TtzwWtQJhsgodtAzjdI4XasJB1zXkDASv7uTkhnHK9oQehXRO6H2NPwSS7WV/KPcFruwb) using the rather-complicated delimiter of "`\n[1]` ")
*Edit: -1 byte thanks to caird coinheringaahing*
```
function(b)for(i in 0:1e3)if(!i||all((a=i%/%b^(0:log(i,b))%%b)==rev(a)))cat(i,'')
```
[Try it online!](https://tio.run/##Zc1BCsIwEAXQq9RF6P8gWHFlIVdRZtpEBmIiaXXVu6fdu32bV5vKEubnR5LluZZ3WHyL3zytVjKUsVRYZ7kbxmu40SJOtm2SEiDe3MXpA8OYygt2VtI5pfc1/CAkJ1kP7nv@J7iz7Q "R – Try It Online")
Manually calculates digits in new base representation, and checks whether they are the same as themselves reversed.
```
function(b)
for(i in 0:1000) # loop i through zero to 1000
if(!i # if i is zero (always a palindrome),
|| # or
all( # if all the digits of
(a=i%/%b^(0:log(i,b))%%b) # a = the representation of i in base b
==rev(a)) # are the same as themselves reversed
)cat(i,'') # output this i
```
[Answer]
# [Ruby 2.7](https://www.ruby-lang.org/), 74 bytes
```
->b{(0..1e3).select{(a=(g=->k,r=[]{k>0?g[k/b,r<<k%b]:r})[_1])==a.reverse}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6pWsNAT88w1VhTrzg1JzW5pLomr0Yj0VYj3VbXLlunyDY6tjrbzsA@PTpbP0mnyMYmWzUp1qqoVjM6L1bT1jZRryi1LLWoOLW29n@BQlq0oUEsF4g2glCWUMoy9j8A "Ruby – Try It Online")
TIO uses an older version of Ruby, whereas in Ruby 2.7, we've numbered parameters, which saves two bytes.
---
# [Ruby](https://www.ruby-lang.org/), 48 bytes
```
->b{(0..1e3).select{|k|(k=k.to_s b)==k.reverse}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6pWsNAT88w1VhTrzg1JzW5pLomu0Yj2zZbryQ/vlghSdMWyCxKLUstKk6trf1foJAWbWgQywWijSCUZex/AA "Ruby – Try It Online")
Doesn't works for bases over 64, due to the limitation in `.to_s` method.
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~77~~ 89 bytes
Fixed for bases greater than 36.
```
b=>{for(i=-1;i<1e3;){j=[],k=++i;while(k|=0)j.push(k%b),k/=b;''+j==j.reverse()&&print(i)}}
```
[Try it online!](https://tio.run/##FcRBDsIgEADAu/@w3Q1tLXqxoetHjIdiIF0wSqDiofbtGOcwbspTukcOS5vPxVLRdFntKwJTKxWP0pwUro6ut8aTEKw@Mz8M@C/16LrwTjP4vcbGH0iruhaOyHXRZBOTAayqEPm5AOO2FQuyx52F478Byw8 "JavaScript (V8) – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 102 100 98 95 87 75 bytes
-14 bytes thanks to mazzy!
```
param($u)0..1e3|?{for($b=@();$_=($_-($b+=$_%$u)[-1])/$u){}"$b"-eq$b[11..0]}
```
[Try it online!](https://tio.run/##hZDBToQwEIbvPMWEzJo2CFI9qWkkevHEycQDIQTMbCRhAduSPbB9dizguptsjHPpPzP/fDNp3@1J6U9qmgm3Q/th6q6VHrgYp75U5Y7hwOMoEnR3eBq3nWJYyYTxRywkwyJ0aSCx2DhXFoqc3zgxWh8rP6QvrDIhoijO7TQTrYeGtHkpNWmQkLBlTzIuzxx12w9mFnPzni91e/2X4fY/g4h/HB4/33yADYxLng67ipQUdgXgOi0Bi2iRa1WRHpq5fPX7Q5Cc@u@qNhS@dtqAn705Kpyx8@zZ7QRkRyTPfbiMMO1S2jd1SxfIh@MB/nrNiR0Enp2@AQ "PowerShell – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `M`, 7 bytes
```
k1'⁰τḂ⁼
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJNIiwiIiwiazEn4oGwz4ThuILigbwiLCIiLCIyIl0=)
[Answer]
# [jq](https://stedolan.github.io/jq/), 66 bytes
```
. as$a|range(1001)|select([while(.>0;./$a|floor)|.%$a]|reverse==.)
```
[Try it online!](https://tio.run/##yyr8/19PIbFYJbGmKDEvPVXD0MDAULOmODUnNblEI7o8IzMnVUPPzsBaTx@oJC0nP79Is0ZPVSUxtqYotSy1qDjV1lZP8/9/SwA "jq – Try It Online")
## Explanation
```
. as $a | # Assign the input to $a.
range(1001) | # For every item in [0..1000]:
select ( # Filter out all items where:
[ while(. > 0; # The list of quotients from repeatedly
. / $a | floor) # short-dividing by $a
|. % $a] # And then modulo-ing by $a
| reverse == .) # is equal to its reverse
```
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 11 bytes
```
f_IjTQUh^T3
```
[Try it online!](https://tio.run/##K6gsyfj/Py3eMyskMDQjLsT4/38jAA "Pyth – Try It Online")
---
```
f_IjTQUh^T3 | Explanation
------------+---------------------------------------
f | filter
Uh^T3 | the range [0, 1001)
jTQ | on whether each number in base <input>
_I | equals itself reversed
```
[Answer]
# Java 10, 118 bytes
```
b->{for(int i=-1;i++<1e3;){var s=b.toString(i,b);if(s.contains(new StringBuffer(s).reverse()))System.out.println(i);}}
```
[Try it online.](https://tio.run/##jVA9T8MwEN37K06dbCWxCEw0hAGmDpShY9XBcS@VS@pE9iUIRf7twfkoE0gsJ927d@@9u4vsZHI5fQyqks7Bm9SmXwFoQ2hLqRB2YwvQ1foEim0DfkYLBc8C7FehOJKkFezAQD4UyXNf1paFfdB5kmY6ip5SfMh430kLLi8E1Xuy2pyZjoOKLpkTqjYUjB0z@Anz9KUtS7TMcWGxQ@uQcc73X47wKuqWRBNIVBmmeeb9kI1BmraoQpAlzxT4GlTZLHg4guTzLbeAhI5epUPYwGgcoMOxT@/i@/jRL1SAXzzXW9O0tIF1dFOYvvEX@72lmf7DMkKx/6wuMz@92g/f)
**Explanation:**
```
b->{ // Method with Integer parameter and no return-type
for(int i=-1;i++<1e3;){ // Loop `i` in the range [0,1000]:
var s=b.toString(i,b); // Convert `i` to base-`b` as String
if(s.contains(new StringBuffer(s).reverse()))
// If this String is a palindrome:
System.out.println(i);}} // Print `i` with trailing newline
```
[Answer]
# [Factor](https://factorcode.org/), ~~53~~ 52 bytes
```
[ 1e3 [0,b] swap '[ _ >base dup reverse = ] filter ]
```
[Try it online!](https://tio.run/##XY4xC8IwFIR3f8VtLhJanVQUN3FxEadSJI0vNdgm8SVV@uvrAzdv/O6OO6tNDjxdL6fzcYNe54di7VtKeBJ76mB5/OGoOREj0WsgbyQQmXIeIzuf4XVPKeo/rEzw1rVwAdvZrCywxHqqUNIKVbFoaqSPjphXuGHf6ES4DxFMb5Il7FDDui7LZi0lpRR8J8yEPgbxy0Ik17h1Xl5lZHaH6Qs "Factor – Try It Online")
] |
[Question]
[
Given a positive integer number \$n\$ output its perfect radical.
# Definition
A perfect radical \$r\$ of a positive integer \$n\$ is the lowest integer root of \$n\$ of any index \$i\$:
$$r = \sqrt[i]{n}$$
where \$r\$ is an integer.
In other words \$i\$ is the maximum exponent such that \$r\$ raised to \$i\$ is \$n\$:
$$n = r^i$$
This is OEIS [A052410](http://oeis.org/A052410).
# Special cases
For \$n = 1\$ we don't really care about the degree \$i\$ as we are asked to return \$r\$ in this challenge.
* Just take \$r=1\$ for \$n=1\$.
* Since there is an OEIS for this and it starts from 1 you don't have to handle \$n=0\$.
# Note
A positive integer \$n\$ is expressed in the form \$100...000\$ if we convert it to base \$r\$
For example the perfect radical of \$128\$ is \$2\$ which is \$1000000\$ in base \$2\$, a \$1\$ followed by \$i -1\$ \$0\$s.
**Input:** a positive integer. You don't not have to handle inputs not supported by your language (obviously, abusing this is a [standard loophole](https://codegolf.meta.stackexchange.com/a/8245/66833).)
**Output:** the perfect radical of that number.
You may instead choose to take a positive integer \$n\$ and output the radicals of the first \$n\$ positive integers, or to output the infinite list of radicals.
# Test cases
This is a list of all numbers \$n \le 10000\$ where \$n \ne r\$ (expect for \$n = 1\$, included as an edge case, included also some cases where r==n for completeness sake ) :
```
[n, r]
[1, 1],
[2,2],
[3,3],
[4, 2],
[5,5],
[6,6],
[7,7],
[8, 2],
[9, 3],
[10,10],
[16, 2],
[25, 5],
[27, 3],
[32, 2],
[36, 6],
[49, 7],
[64, 2],
[81, 3],
[100, 10],
[121, 11],
[125, 5],
[128, 2],
[144, 12],
[169, 13],
[196, 14],
[216, 6],
[225, 15],
[243, 3],
[256, 2],
[289, 17],
[324, 18],
[343, 7],
[361, 19],
[400, 20],
[441, 21],
[484, 22],
[512, 2],
[529, 23],
[576, 24],
[625, 5],
[676, 26],
[729, 3],
[784, 28],
[841, 29],
[900, 30],
[961, 31],
[1000, 10],
[1024, 2],
[1089, 33],
[1156, 34],
[1225, 35],
[1296, 6],
[1331, 11],
[1369, 37],
[1444, 38],
[1521, 39],
[1600, 40],
[1681, 41],
[1728, 12],
[1764, 42],
[1849, 43],
[1936, 44],
[2025, 45],
[2048, 2],
[2116, 46],
[2187, 3],
[2197, 13],
[2209, 47],
[2304, 48],
[2401, 7],
[2500, 50],
[2601, 51],
[2704, 52],
[2744, 14],
[2809, 53],
[2916, 54],
[3025, 55],
[3125, 5],
[3136, 56],
[3249, 57],
[3364, 58],
[3375, 15],
[3481, 59],
[3600, 60],
[3721, 61],
[3844, 62],
[3969, 63],
[4096, 2],
[4225, 65],
[4356, 66],
[4489, 67],
[4624, 68],
[4761, 69],
[4900, 70],
[4913, 17],
[5041, 71],
[5184, 72],
[5329, 73],
[5476, 74],
[5625, 75],
[5776, 76],
[5832, 18],
[5929, 77],
[6084, 78],
[6241, 79],
[6400, 80],
[6561, 3],
[6724, 82],
[6859, 19],
[6889, 83],
[7056, 84],
[7225, 85],
[7396, 86],
[7569, 87],
[7744, 88],
[7776, 6],
[7921, 89],
[8000, 20],
[8100, 90],
[8192, 2],
[8281, 91],
[8464, 92],
[8649, 93],
[8836, 94],
[9025, 95],
[9216, 96],
[9261, 21],
[9409, 97],
[9604, 98],
[9801, 99],
[10000, 10]
```
# Rules
* Input/output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963).
* You can print it to STDOUT, return it as a function result or error message/s.
* Either a full program or a function are acceptable.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins.
[Sandbox](https://codegolf.meta.stackexchange.com/a/20521/84844)
[Answer]
# [J](http://jsoftware.com/), 14 bytes
```
(%+./)&.(_&q:)
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NVS19fQ11fQ04tUKrTT/a3JxpSZn5CtoWKdpKhibcSmAAFQoTcFEU8FWwQjOtUDlWoK4xnCuoRmqtJEpiG@K4Jujqjc2QlVvDNZvhrAcbL45nG@G7hpDNPsNDEAChgZc/wE "J – Try It Online")
```
(%+./)&.(_&q:)
&.(_&q:) number to prime exponents
(%+./) divide them by their GCD
&.(_&q:) prime exponents to number
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
ÆEgƒ0:@ƊÆẸ
```
[Try it online!](https://tio.run/##RZRNilVBDIW38hbwwErlXxCcuAhpHIogvQGnDlpw2BNdhAtQp40NLqPdyPOepOr16Ia6t5IvOSf34/vb20@Xy8Pdmw@P9@Pl68evD3dPv39eHr68@nP/9Ov7328v/n3@8fZyuaHzid6dTzdyPk08Yz3zfGI8ydbB1PNJK/D1iud6xcc3VkmOW47Arulo5xnjqDQqnChKHe6sNHdlkuMydWhHQur7eRQhKQDa9SauU1MJr0pTr8iB696sSBoV4ss@NIBkkQNvFp7IcTp7KIE@KpfS7lbnkXVWKXWUKii7dmJ1WHw@9xi9MlX9qPxVNVGVq2qChWmN6nlWY@5R0kA73NMgNMnSk0NpXlPMPRtifh4zY5Dsa7xHRi4UUkjB2bNGVemqBt2k7zqUWXo4hJWOA2rLEgcWkFZnAEdalCFb1UlQTVo2iu2hSelb4jkHMhbl5IFK0dIOWopNBaQW5DQcK7Un8bl2JS8DNUwgpXb6BIHWORekFiQ/m5AJfagtx@BqG4XRt7Z92K@mY8GcNNtMQLNCY8dcrdA4gGO9KAkdjNtxuX0qpaBVSmEoa71OAsWtEMRgBCsEcZjF2rjlIW/nJvE2vA7YzKm9C/d5u5fhSW/7CqzqNREtA7u2reu8GDSw5r05mnW3N3xUzmjvV63szQdPFI@p7fU3B34UgoXm3jsLtBi9IwOth/TmACcKxxmTit4oxQSjELyEjujYt/E9Mfyo9DGe9zrqF5Qrzr3OMaFhUq8mdM4@N@ifRRYBX6T0zoIsiyzrV5TWsV3/GymwXXovNqyZRZkBy2buLe81/w8 "Jelly – Try It Online")
`ÆE:g/$ÆẸ` errors given 1.
```
ÆE Take the exponents of the input's prime factorization.
:@Ɗ Divide each exponent by
gƒ0 the exponents' GCD (or 0 in the case that there are none).
ÆẸ Let the result be the exponents of the output's prime factorization.
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 6 bytes
```
1|~^hℕ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFSu9qhtw6Ompoe7Omsfbp3w37CmLi7jUcvU//@jDXUUTHQULHQULHUUDM10FIxMgdhcR8HYCIiBfBOguJlJLAA "Brachylog – Try It Online")
```
1|~^hℕ with the implicit input n
1 input and output is 1
| or
~^ find two numbers [r, i] so that r^i = n
h return r
ℕ to limit the search space: r must be positive
```
Search tries lowest `i` first, so we get the maximum `r` for free.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~55~~ \$\cdots\$ ~~59~~ 57 bytes
Added 7 bytes to fix an error kindly pointed by [user](https://codegolf.stackexchange.com/users/95792/user).
Saved 3 bytes thanks to [user](https://codegolf.stackexchange.com/users/95792/user)!!!
```
lambda n:{r**i:r for i in range(n)for r in range(n+1)}[n]
```
[Try it online!](https://tio.run/##TVHLcoMwDLznK3QDUncmEsZAZuiPkBzSFBqmrZMx9NBh@HZq@UHri@S1tbuSHj/T7a7ztW9O6@fl6/XtAvo4m/1@OBro7wYGGDSYi37vUp0xYP4BT5gtrT6vUzdOIzSQtijwLKAlAcQxF5BzlOFeCCg4KgGKYymg5FiF9zr8x4MAPLhMhSeKtVSGT/mmEulkHfhUFKxwY/yjJAsi@jSyIkUPKG0x@lRZQvT1tRVB6Qxg1CMuR@9Kxl6p2CxXXF56r0xauZR/elCxkdo5Z3vk7ElpUXL2ZMV9@Mlh7LYgy0pOqihZyplSWyfKgX685Aaa7a637vrRGV5RcvqmUl4TEOBSzJNsx4udRMerdbs87sAeXmmfTpm7PMygp7RP5mmB5xeYxwXmQNuOTdOdlyRbfwE "Python 3 – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 8 bytes
```
VȯεΣ`B¹ḣ
```
[Try it online!](https://tio.run/##ASIA3f9odXNr/23igoHigKYwIDEwMP9WyK/Otc6jYELCueG4o/// "Husk – Try It Online")
```
V # index of first truthy element of
ȯ # applying 3 functions to
ḣ # 1...input
`B¹ # convert input to this base
Σ # sum of digits
ε # is at most 1
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ ~~6~~ 5 bytes
```
bR§i1
```
[Try it online!](https://tio.run/##AS4A0f9qZWxsef//YlLCp2kx/8OH4oKsxZLhuZj//zEsIDQ5LCA2NCwgMjE2LCA5MjYx "Jelly – Try It Online")
Uses the fact that `n` in base `r` has the format `100...000`, meaning that the sum of the digits only equals 1 in base `r`
-1 byte (indirectly) thanks to [Dominic van Essen's answer](https://codegolf.stackexchange.com/a/215878/66833), make sure to give them an upvote
## How it works
```
bR§i1 - Main link. Takes n on the left
R - [1, 2, 3, ..., n]
b - Convert n to each base 1, 2, 3, ..., n
§ - Sum of the digits of each
i1 - First index of 1
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~~~8~~~~ ~~11~~ 8 bytes
-3 thanks to @ovs!
```
L¦BíCXkÌ
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f59Ayp8NrnSOyD/f8/29mZAoA)
I am trying to somehow implement a log function to check whether a number matches the regex `10*`, but that is too mathematical for me...
# Wait, how?
```
L # Push all numbers natural numbers up to input [1, 2, 3 ... I]
¦ # What is that 1 doing there? Remove it! [2, 3, 4 ... I]
B # Convert the input to each of the bases e.g input: 9 [1001, 100, 21...]
í # Reverse each string [1001, 001, 12...]
C # Convert each from binary to decimal [9, 1, 4...] (How though! Can someone explain?)
Xk # Get first index of 1 1
Ì # Add 2 3
```
[Answer]
# [k4](https://code.kx.com/q/ref/), ~~26~~ ~~24~~ ~~21~~ 18 bytes
-2 bytes by ignoring `n=0` case
-3 bytes by applying [@caird coinheringaahing's logic](https://codegolf.stackexchange.com/a/215859/98547)
-3 bytes by simplifying/combining operations
```
{(x{+/y\:x}'!x)?1}
```
Benefits from `list ? value` returning the count of the list if the value isn't present in it, and from convenient weirdness with the `n=0` and `n=1` edge cases.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 60 bytes
```
.+
$*
(?<=(?=((?=((1*)(?=\5\3+$)1)(\2*$))\4)*1$)^(..+)).*
1
```
[Try it online!](https://tio.run/##Hco9CsMwFAPgXedwwc8BE8lxfqAhYy9hSjt06NKh9P7Oo4MQSN/39Xt/nv0Sb4@eB4SEeFz3eOzxHybzbrWVIRgtNqVg1iZLDHaPOQ9mOQHsfQQhFEyomLFgxQaNkK@CCjRBFZqhBVqhDfSb/tMBXdAJ3dARXdEZtZ0 "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
.+
$*
```
Convert to unary.
```
(?<=(?=...$)^(..+)).*
```
Delete the earliest suffix leaving behind the smallest prefix \$r\$ (captured into `\5`) such that the \$n\$ matches the following:
```
((?=((1*)(?=\5\3+$)1)(\2*$))\4)*1
```
Find \$k\$ `\3` such that \$n-r\$ is divisible by \$k\$, but also \$n\$ is divisible by \$k+1\$ `\2`. Apparently this can only be satisfied by \$n=r(k+1)\$, but I can't find the answer where this is proved. \$(r-1)(k+1)\$ is then subtracted from \$n\$, resulting in \$k+1\$. This is then repeated until \$n\$ is reduced to \$1\$, which is matched at the end.
```
1
```
Convert to decimal.
[Answer]
# [R](https://www.r-project.org/), 47 bytes
```
n=scan();match(n,sapply(0:n,"^",1:n))%/%n-(n<2)
```
[Try it online!](https://tio.run/##jc3BCsIwDADQe78iVAYJVOwGXjr3JyKE2LKhZsPUg19fL3r3/A7v2ZpOJqxI44OrzKjBeNvub4xJg7/40Ccl6g6d7lFPA7Xh6JxwRX9WT24H11wWzcAGDOWlUpdVoa4gc5Yb1GwVhC1bcmX6OSr9t7kv96mPMRRqHw "R – Try It Online")
Struggled for ages trying to beat [Giuseppe's answer](https://codegolf.stackexchange.com/a/215862/95126), only to be totally outgolfed (seconds before posting) by Robin Ryder's comment (now an [answer](https://codegolf.stackexchange.com/a/215904/95126))...
[Answer]
# [R](https://www.r-project.org/), ~~37~~ 33 bytes
-4 bytes thanks to Dominic van Essen
```
match(T,!log(n<-scan(),1:n)%%1,1)
```
[Try it online!](https://tio.run/##Vc2xCsJADIDhPU8RK4UETmg2OfQtHF2OeGeLNS29OPj05yTo/MP3b609k@tIl7CblzvZ6VA1GXGQaNz3EoTbUQA0OXVX6xj2eMtlsoypYnmZ@rQY@oI6Zn2g5@qoqeYaoZy/nYz/Nz88QE3rOr9JogxDKNw@ "R – Try It Online")
A different (and shorter) approach than the one used in [Giuseppe's](https://codegolf.stackexchange.com/a/215862/86301) and [Dominic van Essen's](https://codegolf.stackexchange.com/a/215881/86301) R answers.
Finds the first integer `k` such that `log(n,k)` is an integer, or returns `1` if there is no such `k` (which corresponds to the special case `n=1`).
[Answer]
# JavaScript (ES7), 36 bytes
Recursively looks for the highest \$i\le n\$ such that \$k=n^{1/i}\$ is an integer. Then returns this \$k\$.
```
f=(n,i=n)=>(k=n**(1/i))%1?f(n,i-1):k
```
[Try it online!](https://tio.run/##FYxBDoIwEEX3nGIWmMyAIN2Ko1ehAWoqZMYAYdP07LWu/kvey//Y0@7j5r9HIzrNKTlGuXoW4icuLFWF5uaJLubl/qIxdF@S0w0FGEwPAo@8XZeprglCATCq7LrO7apvHCyWQSLluAz5geJAfRHTDw "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES7), 37 bytes
A slightly longer version that performs more recursive calls but is not subject to rounding errors.
```
n=>(g=k=>k**i-n?g(k-1||i--|n):k)(i=n)
```
[Try it online!](https://tio.run/##DcqxDoMgEIDh3ae4weFOQxNNutSefRWJCqGYo9GmC/DslOn/hv@tf/paT/f5KgnbXgwX4Rkte5591zklL4teDSk5pZLQwxM6FiomnCjAMEwg8Kwd71V9TxAbgDXIFY79dgSLi8Y2SqY6t9GgUF5oanL5Aw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), ~~53~~ 51 bytes (thanks [@user](https://codegolf.stackexchange.com/users/95792/user) for pointing out extra spaces)
```
def r(n):
i=n
while(a:=n**(1/i))%1:i-=1
return a
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/PyU1TaFII0/Tiksh0zaPS6E8IzMnVSPRyjZPS0vDUD9TU1PV0CpT19aQS6EotaS0KE8h8X9BUWZeiUaRhqGmJheMbYLEtkBiWyKxDc2QOEamyDxzI6DC/wA)
[Answer]
# [R](https://www.r-project.org/), ~~49~~ 44 bytes
```
n=scan();which(outer(1:n,n:1,"^")==n,T)[1,1]
```
[Try it online!](https://tio.run/##K/r/P8@2ODkxT0PTujwjMzlDI7@0JLVIw9AqTyfPylBHKU5J09Y2TydEM9pQxzD2v6GJyX8A "R – Try It Online")
Thanks to Dominic van Essen for pointing out a bug.
```
n <- scan() # read input
arr <- outer(0:n,1:n,"^") # create the array of powers (0^(1:n), 1^(1:n), ... n^(1:n))
arr <- t(arr) # transpose, so the array is ((0:n)^1, (0:n)^2, ... (0:n)^n)
ind <- which(arr==n,T) # get 1-based array indices where arr == n. So they are a matirx of rows of [i+1,r+1] pairs, sorted in increasing order of r
ind[1,2]-1 # extract the appropriate r.
```
[Answer]
# [Factor](https://factorcode.org/), 49 bytes
```
[ dup [1,b] 2dup '[ _ swap _ n^v member? ] find ]
```
[Try it online!](https://tio.run/##LYy9DoJAEAb7e4rPysaYgEZFC0tDQ2OsCJrzXJToHefegjHGZ8ffaqaYTKmN1Nxt1mm2mqPkO87Eji6wWk5D1u5I4ectfcoAzyRy91w5QaBrQ85QUAuVZnMEw1rMSakehIKgcr6RoB6IEGOEMRJEE8RTzCIkCZ5djkPjkUeDfYH4o/0cO4Sb9m@4bQtLdk@8RIGycgcU3f9cN/Jd23c5VOZCmrsX "Factor – Try It Online")
Slow for larger inputs because it tries to evaluate a large power.
```
[
dup [1,b] 2dup ! ( n 1..n n 1..n )
'[ ! Put stack items in the `_`s in the quotation
_(n) swap _(1..n) ! ( elt -- n elt 1..n )
n^v member? ! Test if n appears in elt^(1..n)
] find ! Find the first number in 1..n that satisfies the above
]
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
Inspired by [SunnyMoon's answer](https://codegolf.stackexchange.com/a/215863/64121).
```
LÀ.ΔBR
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f53CD3rkpTkH//xsCAA "05AB1E – Try It Online")
```
L # push the range [1, 2, ..., n]
À # rotate the 1 to the back: [2, 3, ..., n, 1]
.Δ # find the first integer where ...
B # the input converted to that base
R # reversed
# implicit: is equal to 1 as a number
```
---
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
LÀ.Δ.n.ï
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f53CD3rkpenkuh9cH/v9vaGkGAA "05AB1E – Try It Online") There was [a bug with `.ï`](https://github.com/Adriandmen/05AB1E/issues/160), which has recently been fixed, but the interpreter on TIO is not up to date.
```
L # push the range [1, 2, ..., n]
À # rotate the 1 to the back: [2, 3, ..., n, 1]
.Δ # find the first integer where ...
.n # the logarithm of the input in that base
.ï # is an integer
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-g`](https://codegolf.meta.stackexchange.com/a/14339/), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
I feel like I'm missing a trick here.
```
õ ï æ@¥Xrp
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWc&code=9SDvIOZApVhycA&input=NA)
```
õ ï æ@¥Xrp :Implicit input of integer U
õ :Range [1,U]
ï :Cartesian product with itself
æ :Get first pair that returns true
@ :When passed through the following function as X
¥ : Test U for equality with
Xr : X reduced by
p : Exponentiation
:Implicit output of first element of that pair
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
┌Pèó~JRå▲ï
```
[Run and debug it](https://staxlang.xyz/#p=da508aa27e4a52861e8b&i=4%0A49%0A125&m=2)
## Explanation
```
R{xs|E|+1=}j
R range 1..n
{ }j get first number i where:
xs|E input(x) in base i digits
|+ summed
1= equals 1
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 (10) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÓDā<Ør0š¿÷mP
```
Port of [*@UnrelatedString*'s Jelly answer](https://codegolf.stackexchange.com/a/215860/52210).
The `0š` shouldn't be necessary, but unfortunately [there is a bug in 05AB1E for `¿` with empty lists](https://github.com/Adriandmen/05AB1E/issues/178).
[Try it online](https://tio.run/##AR8A4P9vc2FiaWX//8OTRMSBPMOYcjDFocK/w7dtUP//MzI0) or [verify all test cases](https://tio.run/##PVQ7blRBELzKYyMsbTA9PdPTLSFtYBOQ8LHILAfYcuAAWTIIyQEBCQeAhJSYA0CCkFhIEWfgIstUzexGb7b3dVdNVfW7efXi4vpq9@bu7/eTzWr59/7Dstrsth9Pfr17sP10m35//vlj@/Xl093J5u7Pt2fXq@X@5c3t7dXl66PV9kv/9ejx8ZPT04fHz@8drd6ud2dnsl7kfH1W1kvuDx@PWC/aH2LjZ67rpeLZRl3zqGv/39Dc32/9afspMvtT6tMTThk4wtMcJnmCSeltwpP1QcLO6KOlAFMmSEajkEbRMT/XPUFHYyM1DHOc8BZLBuwAT/DJ4FNKr2Ve3EEaQ6rMa9Xcp2UA1AYA0LA9bWMJhFqeMjWOAKZzLKACUAqoALzKkOOgR8pTK0ngrry04D5aKA7wdOgUUwFRPaiokErbkK@PUsBLhcwalBJYhVgGPwrbGkQfWje4VXh0GFiG7vC0UPgECoWCpzK9ygI7Cv0Qn3HIEm36lnPCKPDKmgDgNCzJ8CJX0KqglQ3FKswVXq0EaEwDCThmVY4NwFZUlbQqaOkhSyqgXW0EAF00XnHFyjBo26dHC@SowWSAjYGNNkhnYKMOCsaAB2Q2ZXZihq3QG8OsonDMuAMFPhpwi8FcA25pcN8YPkaiMX0hOvNaEyLThPlDjhoTqMhWYwQLAtdw9coQtspgsgrg6lhHRr4G27iKicOc0SVEcEHBwcHBqs0ttQa6DlzzGnNXzHEfZ74TbumFmQcFB4WmEMS5CRUyOXAb/XPnsc3gtoC4jrGeDjvo/DzEOMbcPc9wJ4TLBPuCVYOpATLusDoKdwxkAmSCn4kwHm2/21GQoGjcQkQswCscwYuYGzlW8vw/).
**Explanation:**
```
Ó # Get the prime exponents of the (implicit) input-integer
D # Duplicate this list of exponents
ā # Push a list in the range [1, length] (without popping the list itself)
< # Decrease each by one to make the range [0, length)
Ø # Get the n'th prime for each of these indices
r # Reverse the three lists on the stack
0š # Prepend a 0 (work-around for `¿` bug with empty lists)
¿ # Pop and get the greatest common divisor (gcd) of this list
÷ # Integer-divide all values in the list by this gcd
# (we use integer-division due to another bug that isn't on TIO yet,
# as well as to get an integer output, instead of float)
m # Take the primes we created earlier to the power of these values
P # And take the product of that
# (after which it is output implicitly)
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~65~~ ~~60~~ 58 bytes
Saved 5 bytes thanks to [Sisyphus](https://codegolf.stackexchange.com/users/48931/sisyphus)!!!
```
p;i;r;f(n){for(r=0;r++<n;)for(p=i=1;i++<n;p*=r)n=p-n?n:r;}
```
[Try it online!](https://tio.run/##XZTrbhs3EIX/5ykIAwEke43yfulG7Y@iT1EbhSGvUiHpRpAM1KjhV68633AtJBZAijucGZ45Z8jt7eft9nw@jPvxOO5W8/pl9@24Om7seLy5@TSPaz4Pm/3GjXs1HK43x/W8OdzOv84/H8fX898P@3m1Ni8fjPz285N5mk5Ppz/nP@7Nxry4wfjBhMHEwaTB5MGUwdTBtME4K0MMXuxerAFH@Y6yl8W9Onxw8qxwc15CXYwEkqERrjk0SQxk47M28olfwBayJIikipFVBYyT45IXv1QkIpMgsyrYCi4V50ZYyx0LYCxpneUE5zjM@Q4NMC4EPIOiiwo0KfqssVlrKlpFoUZXo9ZB3d5qETZWitKqXC3Mjdlb8fTBRgq18JrI6bOui9oLJ/qqno0MQXMG12dOEVbgJnB6CAV7BFVQhKGANlTyhEYV0VJX1BpjoN4YqT1meIhFqVWSYnPCdbKwlpxyHJTfCK1JGU5F1xWtU2M3WzwlmUN18uREzlzIn2vCp3JisUnlIU8JoCoJhEWrLpq5NPBXVaq6Pjc5q3pqrFH7KsNArbDRlJ@mPdQ857YIey3DZ6t20d2@jpf@np4P0/ZpenzX4P67Bu8WGrxb@/b7Ped009M8NA0to17uEuIKPaJxDlHJyIledz1O/WL53EPoHfRFS3eBELgESNoRcnDgxlVURmMZrsOIDO4r6nZ0secGYCxcH8WTLDJzhzruhPj8JwWEVgm32utRHVEXbSFj4QRE3L@CzDJU6F54cciN2DKQGOHzQgj7/COlVXzVd5Iqa3ROaC2DF6dq4XXhsHVaGnrzH9BdBr2QO8XcucZDpS/VIv/2r4fjtczT9st07Ppf3T3/7u@e228y0tVgvv8OV0ucPKJmRe/s58fpWcLsuCw/mdP@3@nbbrW8muuflu/rN8Nobm7U9@2NfevDWfK8vbXqcD/@sH@SfV70H62TWC8d/D7scBSX3erq46O5/cXI/PF0N0tR82BOw6XuabM53S9pXz@8nv/b7r4@fD6db//5Hw "C (gcc) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 27 bytes
```
Most@*Internal`PerfectPower
```
[Try it online!](https://tio.run/##LZJBixRBDIX/Sp@lYSuVVCV1EObqQRjPIjgs7TrgzsLY4kH87W19GQ9dpKtfXt576dfL/n17vezX58vx8v74@PZzP737cNu3@@3y4@t5u3/bnvfz2@/tfnz6dd32z@f79bYvT6eXp9MfWRdbl1iXsS7S16W2@fi6aJ3PfLd530FMoJQyj0oFTOpsEzMa6R60J0eSmMLGawz4Jk65085MqMyoYn5oMse1OnHNZ0eHoFM5dw4kAA/aRn9oQUyBVgoTRBgm9SENMaIKUlOdpdCW6nv29vTk6cLxKGHpA9@1pIligal0JeGcg7OWiaxaDKNFcApn7Vl73jsTayRywKDJqfI4mTJTIRtluqpzb6jSVKiOWg14dODCCr4sPZri1wzv1snBPKPNkGzIzLoVUmuSGWvma8TaMuHmWQe7boOvvYCcZMLW4ekNzu7w92hggoleWq4HHldUeUOhp2tPZh/oj9xUyOMcc1ZUPIblf9VJIII0RuYz8h8albnDSG908hxR/u@9/P1yHP8A "Wolfram Language (Mathematica) – Try It Online")
-20 bytes from att
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 33 bytes
```
@(n)[~,j]=find((t=1:n)'.^t'==n,1)
```
[**Try it online!**](https://tio.run/##y08uSSxL/Z9mq6en999BI08zuk4nK9Y2LTMvRUOjxNbQKk9TXS@uRN3WNk/HUPN/moahJleahgWIMLEEkYZGlmYg2tLIDCgPAA "Octave – Try It Online")
### How it works
```
@(n) % anonymous function with input n
(t=1:n) % let t = [1, 2, ..., n] (row vector)
.^ % element-wise power with broadcast...
' % of t transposed...
t % raised to t. Gives n×n matrix of powers
'==n % test each entry for equality with n
[~,j]=find( ,1) % col index of the first true entry (in linear order)
```
[Answer]
# Scala, 50 bytes
Back to 50 bytes because n=0 doesn't have to be handled anymore!
```
n=>1.to(n)find(r=>1.to(n)exists(n==math.pow(r,_)))
```
[Try it online!](https://scastie.scala-lang.org/xDx1z2cBTnKTqoN8mIu68w)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~19~~ 16 bytes
```
NθI⊕⌕Eθ⎇ιΣ↨θ⊕ιθ¹
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDObG4RMMzL7koNTc1ryQ1RcMtMy9FwzexQKNQRyEktSgvsahSI1NHIbg0V8MpsTgVJIysPFNTU1NHoRBEGAKZmtb//xsamf7XLcsBAA "Charcoal – Try It Online") Link is to verbose version of code. Edit: Now back to a reformulation of my original answer. Works by converting `n` to each base `1..n` and finding the first 1-indexed value with a digit sum of `1`. Conveniently this automatically works for an input of `0` (the resulting list is empty, so the 1-indexed position is `0`), so the only edge case is base `1` as Charcoal cannot convert to unary, but the digit sum is always `n` in base `1` anyway. Explanation:
```
Nθ Input `n` as a number
θ `n`
E Map over implicit range
ι Current value
⎇ θ If zero then `n` else
↨θ `n` converted to base
⊕ι Incremented value
Σ Sum of digits
⌕ ¹ Find first occurrence of literal `1`
⊕ Increment (convert to 1-indexing)
I Cast to string
Implicitly print
```
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 34 bytes
```
++$\until grep"@F"==$\**$_,1..$_}{
```
[Try it online!](https://tio.run/##K0gtyjH9/19bWyWmNK8kM0chvSi1QMnBTcnWViVGS0slXsdQT08lvrb6/3/Df/kFJZn5ecX/dQsSAQ "Perl 5 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 55 bytes
```
f=lambda n,r=1,i=1:r*(r**i==n)or f(n,r+(i>n),i>n or-~i)
```
[Try it online!](https://tio.run/##NZBNbsMgEIX3OcV0Z7vTlAGME0v0IlYWdhsrSDFE2F1kk6u7A3aRePw83jcjHs/lFrxa3fQIcYH5OR94HufrEq/fv3F2wd/d5JaCBI9yHe29n4afHjxGS@gstbEqYlU5a30ZIowFO@@F@/IlskCIHy/HObZ6HMB56DpCoAt2EiWrQsWqEdKhxprVoGFtsGE9bcYZIT0jgSTSarZrWSOkhGw2X8ntXrGfGJpziWJ2/on@OYJ7yCSZuqG822Ek96KkOUZ5ZxhEOXlmNOlUk/YiMgUpt6FV4l/aA7iRv6Iv3@zQ0qdY/wA "Python 3 – Try It Online")
My first golf in over a year! It's a bit longer than [this answer](https://codegolf.stackexchange.com/a/215919/82577), but doesn't use that nasty floating point. As many good code golf answers do, this hits the recursion limit pretty soon.
[Answer]
# [Python 3](https://docs.python.org/3/), 74 bytes
```
lambda n,r=round:r(n**[1/i for i in range(1,n+1)if r(n**(1/i))**i==n][-1])
```
[Try it online!](https://tio.run/##RVHLcoMwDLznK3QDU2caGWMgM/RHCIc0gYRp62QMOXQy@XZq@UF90cPS7kq6/87Xm86XoTks38efz/MRNDeNuT30eW9SnWUtvo8w3AyMMGowR33pU@T6Ddk4gKtIbQVjWTY2je7aLXZsmftpnqCBtEWOHYdWcBBkcw45WRnigkNBVnFQZEsOJdkq/NehHncccOc8Fb5E7BVlKMpXlggn64CnImGFK@I/pLBJRO9GVBRRA0rbjN5VFhB9f21JUDoBGPkEtaNXJeOsolglV9Reeq0EWjmXKn1SkZDaKSd5wsmT0maFkycrmsNvDuO0hbCowlEVJVE5UWqdRLmkX69wC2Wb07U/ffWGTpQcHqKUpwQ4OBfzhG3o4DPv6eTulvsN2EcnHdKZueBuRj2nQ/KcX7D9gOf0gmeAbaem6btXwpY/ "Python 3 – Try It Online")
This solution is longer but faster than this [answer](https://codegolf.stackexchange.com/a/215867/99104)
] |
[Question]
[
Your program should take as input a number `n` that is greater than 0 and output a bar composed of `n // 8` ▉ characters (U+2588), as well as a final character which should be one of ▉ ▊ ▋ ▌ ▍ ▎▏(U+2589 to U+258F) representing `n % 8`. If `n % 8` is 0, your program should not output any additional characters. This is difficult to explain well in text, so here are some examples:
```
Input: 8
Output: ‚ñà
Input: 32
Output: ████
Input: 33
Output: ████▏
Input: 35
Output: ████▍
Input: 246
Output: ██████████████████████████████▊
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins.
[Answer]
# Excel (ms365), 56 bytes
* -2 Bytes thanks to @[EngineerToast](https://codegolf.stackexchange.com/users/38183/engineer-toast)
[](https://i.stack.imgur.com/UH5yu.png)
Formula in `B1`:
```
=REPT("‚ñà",A1/8)&IF(MOD(A1,8),UNICHAR(9616-MOD(A1,8)),)
```
[Answer]
# [Julia 0.7](http://julialang.org/), ~~35~~ ~~32~~ 27 bytes
```
!n='▐'.-diff((0:8:n)∪n)
```
[Try it online!](https://tio.run/##yyrNyUw0//9fMc9W/dG0Cep6uimZaWkaGgZWFlZ5mo86VuVp/i8oyswrycnT08jKzwSSeooahlbGZpqamv8B "Julia 0.7 – Try It Online")
Generates a range from 0 to n with step 8, and n itself force-included. Then taking the `diff` produces our codepoint offsets, e.g. `35` gives `8 8 8 8 3`, etc. Returns character arrays.
Analogous solution in R:
# [R](https://www.r-project.org), ~~45~~ ~~44~~ 43 bytes
```
\(n)intToUtf8(9616-diff(c(0:(n/8-.1)*8,n)))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3tWM08jQz80pC8kNL0iw0LM0MzXRTMtPSNJI1DKw08vQtdPUMNbUsdPI0NTUhWtYVJxYU5FRqGFoZm-mkQQUXLIDQAA)
Thanks to amelies and MarcMush for -3 and -5 on Julia and pajonk for -1 on R.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
s8Ẉ⁽"s_Ọ
```
A monadic Link that accepts a non-negative integer and yields a list of characters.
**[Try it online!](https://tio.run/##y0rNyan8/7/Y4uGujkeNe5WK4x/u7vn//7@RiRkA "Jelly – Try It Online")**
### How?
```
s8Ẉ⁽"s_Ọ - Link: integer, n e.g. 17
8 - eight
s - split (implicit [1..n]) into chucks of length (8)
[[1..8],[9..16],[17]]
Ẉ - length of each [8,8,1]
‚ÅΩ"s - 9616
_ - subtract (vectorises) [9608,9608,9615]
Ọ - cast to characters ['█','█','▏']
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~43 41~~ 36 bytes
```
lambda n:~-n//8*'‚ñâ'+chr(9608-n%-8)
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPqk43T1/fQkv90bROde3kjCINSzMDC908VV0Lzf9p@UUKmQqZeQpFiXnpqRqGOgqGBgaaVlwKBUWZeSUaxSVFGpmaelVpmTk5GkaaOgrqunbqOgppQEHN/wA "Python 3 – Try It Online") (Fails for n=0)
* -2 thanks to 97.100.97.109
* -5 thanks to loopy walt
(Note: 9608 is the decimal value of 0x2588)
[Answer]
# x86-64 machine code, ~~18~~ 16 bytes
```
AB B8 88 25 00 00 83 EE 08 77 F5 29 F0 48 AB C3
```
[Try it online!](https://tio.run/##VVLRjtowEHyOv2KbCsk5AoJwUARHq@qke6IvbU@qBAgZxwFXxm5tcwQhfr3p2iDRPsRZz87Mji3zzpbzpnkvNVeHUsCT86U03d1HcoeU4UyJ/7Ej3zEbIMLcHih8TSnpbpXZMAUVsZPEeeNKUk2SvXkDweocenUxHI9J4g4bEE7mgPVPBvaGBArCJCp/k8QKT7IUsil5M7KEisaRa/8ALgepPehsCrFlKZIICdieSU0zckYX4a@56fx5/Xk@zyEVev36rfv6/aUzTlGR3AzBCndQfjHsFytEK2OBBi8JM@hP8fc0g6KHRbudkQStMSHzkscQovZ8sULmeVDkMBjgN8yheBxd0CqJMbEZPfoj@ITV5KqRnf6HMC6p6HV@Hg6E@@Mvi7KKztOWXPqWckudYi@/xQycC/mHtdRfGN9JLYCbUkziycLcGuf2cjjhtjRwvgug1St@oOVpRulBO7nVooRwFQ@ZzRZ1u73Kphc47qQSQE/wDm3q50G8sLsHbUnYnLxwWYxXY/vSNH94pdjWNZ396BEXfBozFAj1Fw "C (gcc) – Try It Online")
Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes in RDI an address at which to place the result, as a null-terminated UTF-32 string, and takes the number `n` in ESI. The starting point is after the first byte.
In assembly:
```
r: stosd # Write EAX to the string, advancing the pointer.
f: mov eax, 0x2588 # (Start here) Set EAX to 0x2588.
sub esi, 8 # Subtract 8 from the input number in ESI.
ja r # Jump back if the number was greater than 8.
sub eax, esi # Subtract ESI from EAX, increasing it by 0 to 7.
stosq # Write RAX (the 64-bit register containing EAX) to the string,
# advancing the pointer. Because it's little-endian,
# the first 32 bits are the value of EAX, and the next 32 bits are 0
# (as the high bits are zeroed when operating on only EAX)
# to add the null terminator.
ret # Return.
```
[Answer]
# [Factor](https://factorcode.org), 66 65 64 46 bytes
```
[ [1,b] 8 group [ length ] map 9616 v-n vabs ]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70sLTG5JL9owU2H0GBPP3crhdzEkgy9osS89NRihfSi_NKCzLx0heLUwtLUvGSgUGY-REVZKkhbsYI1l6mBQrShTlLs0tKSNF2Lm3rREK6CBUS7QrRCTmpeekmGQixQZ4GCpZmhmUKZbp5CWWJSsQJU1yaQTLRCQVFmXglQXWpicgZEYsECCA0A)
* -1 byte from Mama Fun Roll
* -1 more by taking an entirely different approach
* -18(!) by porting Jonathan Allan's amazing [Jelly answer](https://codegolf.stackexchange.com/a/254276/97916).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes
```
⭆⪪×ψN⁸℅⁻⁹⁶¹⁶Lι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaAQX5GSWaIRk5qYWa1TqKHjmFZSW@JXmJqUWaWhq6ihYALEzUHNicglQxDczr7RYw9LM0ExHwSc1L70kQyNTEwSs//83MjH7r1uWAwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
ψ Predefined variable null byte
√ó Repeated by
N Input integer
‚™™ Split into substrings of maximum length
⁸ Literal integer `8`
⭆ Map over substrings and join
ι Current substring
L Length
⁻ Subtract from
⁹⁶¹⁶ Literal integer `0x2590`
‚ÑÖ Convert to Unicode
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 50 bytes
*-2 thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil)*
```
f=n=>n?Buffer([226,150,144-(q=n>7?8:n)])+f(n-q):''
```
[Try it online!](https://tio.run/##DcxBDoIwEADAr@yN3RQawAoGLSQmvsCj8UCgJRiyhVL9fuU2p/n0v34f/LyGjN1oYrSadcvd/Wut8fgqyyotznlaKJXhprmtu0vD9CZhkbONmiSJ1nlk0JBfgeGmoVIHhCAYHO9uMXJxE7IM7hn8zBOSXPvxwSOeCAQcD1H8Aw "JavaScript (Node.js) – Try It Online")
### How?
We use `Buffer()` to build the characters from their UTF-8 encodings.
For instance, the character with code point `9608` (0x2588) is generated with:
```
Buffer([226,150,136]) // 0xE2, 0x96, 0x88
```
That's a bit lengthy, but still shorter than the infamous `String.fromCharCode(9608)`.
[Answer]
# [R](https://www.r-project.org), ~~51~~ ~~49~~ 46 bytes
```
\(n)intToUtf8(9616-c(rep(8,n/8),if(b<-n%%8)b))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGSpMQi26WlJWm6Fjf1YjTyNDPzSkLyQ0vSLDQszQzNdJM1ilILNCx08vQtNHUy0zSSbHTzVFUtNJM0NSG6NhQnFhTkVGoYWhmb6QANgwovWAChAQ)
Still not as golfy as [Kirill L's approach](https://codegolf.stackexchange.com/questions/254265/fractional-unicode-bars#comment564396_254275), unfortunately...
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 12 bytes
```
ɾ8ẇvL9616εCṅ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLJvjjhuod2TDk2MTbOtUPhuYUiLCIiLCIxNyJd)
Yet another port of Jonathan Allan's Jelly answer.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~46~~ 36 bytes
```
->n{?‚ñà*(n/8)<<(n%8>0?9616-n%8:"")}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGiNNulpSVpuhY3VXTt8qrtH03r0NLI07fQtLHRyFO1sDOwtzQzNNMFMq2UlDRroWrNCkpLihXSoi1iuaAsYyME0xjBNIUzjUzMYiG6FyyA0AA)
A whopping 10 bytes saved by G B.
[Answer]
# [sclin](https://github.com/molarmanful/sclin), 25 bytes
```
O>a8/`"len"map9616- _ c>S
```
[Try it here!](https://replit.com/@molarmanful/try-sclin) Port of @Jonathan Allan's clever Jelly answer!
For testing purposes:
```
[8 32 33 35 246] ( ; n>o ) map
O>a8/`"len"map9616- _ c>S
```
## Explanation
Prettified code:
```
O>a 8/` \len map 9616- _ c>S
```
Assuming input *n*.
* `O>a` range [0, *n*)
* `8/`` chunk into lengths of max 8
* `\len map` get lengths of each chunk
* `9616- _` subtract from 9616
* `c>S` convert to fractional block char
---
# [sclin](https://github.com/molarmanful/sclin), 38 bytes
```
8/%"‚ñà"rot ** >o""Q"9616- _ c>S >o"&#
```
[Try it here!](https://replit.com/@molarmanful/try-sclin) Outputs the bars.
For testing purposes:
```
[8 32 33 35 246] ( ; ""n>o ) map
8/%"‚ñà"rot ** >o""Q"9616- _ c>S >o"&#
```
## Explanation
Prettified code:
```
8/% "‚ñà" rot ** >o dup ( 9616- _ c>S >o ) &#
```
* `8/%` divmod by 8
* `"‚ñà" rot **` repeat `‚ñà` <div part> times
* `>o` output
* `dup (...) &#` execute if <mod part> is truthy (i.e. greater than 0)...
+ `9616- _ c>S` convert to fractional block char
+ `>o` output
[Answer]
# Mathematica, 59 bytes
```
FromCharacterCode[9616-Tr[1^#]&/@Range@#~Partition~UpTo@8]&
```
[View it on Wolfram Cloud!](https://www.wolframcloud.com/obj/f1ee3d30-f224-4566-9de9-237aa5b00f9d)
[Answer]
# [///](https://esolangs.org/wiki////), 73 bytes
```
/d/iii//ddii/‚ñà//ddi/‚ñâ//dd/‚ñä//dii/‚ñã//di/‚ñå//d/‚ñç//ii/‚ñé//i/‚ñè/
```
[Try it online!](https://tio.run/##K85JLM5ILf6vz6Wv/18/RT8zM1NfPyUFSD6a1gFmARmdIAaQ7gLSYJluEANI9wBpINWrrw8W7gPSQKpf/38mkeA/AA "/// – Try It Online")
Input is a unary.
[Answer]
# [Rust](https://www.rust-lang.org), 61 bytes
```
|n,r|{*r=[9608].repeat((!-n/8)as _);r.push((9615-!-n%8)as _)}
```
A `fn(i32,&mut Vec<u32>)`, where the first argument is `n`, and `r` is a mutable reference to a vector where the output will be stored.
[Attempt This Online!](https://ato.pxeger.com/run?1=rZJBa8IwGIZhR3_FpzBJRq1rO7sarf9hl11EpOsSFGzsknQM1PsYyG677OLB_Sh33C9Zqpna9roQKLzP-37fG-jnVmRSbXZtxiGJphxhWNRmVAEjwDjiZOq5lqCSNJNMwT2N-5nnDnD4lSnWCnbhkltiubgS4bDrXwcjW9CURgqheou3AxxJGOOesNNMThDq-k6npcGlAavDkO-Lu16tBvrkexWVCkLQc4G-pDRW9JFAUyqx1MXAnNyY93nImPY-07g-HPWOlCEdbhqOT3okJRVqTJ_qSIPTfDueREIibCdRivTzCGFinmA7ns9m2kBIP3_3eDBA2IIG1xsXq4YF3IxemfZ5c-Rox8_He8OwvebttXVBC_baa0HrHrRy3PH_9KLduT3q5Yh7c4aKKbdzjipV3SItZj2vRCvxTsWwLhXzK47_vW_5PvNnbTaH7y8)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 30 bytes
```
.+
$*
1{1,8}
$.&
T`8-1`‚ñâ-‚ñè
```
[Try it online!](https://tio.run/##K0otycxL/P9fT5tLRYvLsNpQx6KWS0VPjSskwULXMOHRtE7dR9P6//@34DI24jI25jI25TIyMQMA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
.+
$*
```
Convert to unary.
```
1{1,8}
$.&
```
Convert groups of up to 8 to decimal.
```
T`8-1`‚ñâ-‚ñè
```
Map digits to the appropriate Unicode character.
[Answer]
# [Sequences](https://github.com/nayakrujul/sequences), 30 bytes
```
iH8/nx$\‚ñâ$""Jfh8%H?9616h-VF:
```
Sequences was definitely not made for this!
**Explained:**
```
iH8/nx$\‚ñâ$""Jfh8%H?9616h-VF:
iH // Get an integer input and store in `h`
8/ // Divide by 8
n // Convert to integer (floor)
x$ $ // This many times:
\‚ñâ // Push the string "‚ñâ"
// Implicitly put into a list
""J // Join by empty strings
f // Output with no newline
h // Push `h`
8%H // Mod by 8 and store in `h`
? // If this is truthy (h != 0)
h // Push `h`
9616 - // Subtract from 9616
V // Get chr of the result
F // Output with a newline
: // Else: (do nothing)
```
In Sequences there is no way of multiplying an integer with a string, so we have to settle for making a list of that string, repeated, and then join it by an empty string.
Also, Sequences uses the 96 printable ASCII characters as its codepage, but because we have `‚ñâ` in our code, we have to use UTF-8.
[Answer]
# [Haskell](https://www.haskell.org), ~~[44](https://codegolf.meta.stackexchange.com/questions/13376/is-a-crossed-out-4-still-a-4)~~ 40 bytes
```
f n|n<9=[toEnum$9616-n]
f n='‚ñà':f(n-8)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GCpaUlaboWNzXSFPJq8mwsbaNL8l3zSnNVLM0MzXTzYrmA4rbqj6Z1qFulaeTpWmhC1WvmJmbmKdgq5CYW-CpoFJSWBJcU-eQp6CmkAbFGnJGmpkK0oZ6ekUEsRAPMIgA)
-4 bytes by ignoring `n=0`
[Answer]
# [Go](https://go.dev), ~~91~~ ~~81~~ 73 bytes
```
func f(n int)(s string){
for;n>8;n-=8{s+="‚ñâ"}
s+=string(9616-n)
return}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=Lc4xCsIwFAbgPacInRJMBVst0VJ3N8FRREJpStG-liSdQg_gBVxciuAhPIqrJzGxnd4bfr7_fzzLZni3Ir-IssC1qABVddsoMw9kbYJXZ2TIPzvZQY4lAVyBoURjbVQFJbVINiqFLU8hzLjVsyz43m9Bj9w3Rsg6WSQhUKQK0ynoJ_DwB30dcQhovMnw8eRwy1kcsThm8YpFy6T3BfjMwAeUALfRhS3aO9tcgQDzqyhFPZroYRjvDw)
* -10 bytes by @jdt
* -8 bytes by @Neil
[Answer]
# Java 11, ~~58~~ ~~48~~ 39 bytes
```
n->"‚ñà".repeat(--n/8)+(char)(9615-n%8)
```
-9 bytes thanks to *@Neil*.
Doesn't support `n=0`.
[Try it online.](https://tio.run/##LY9BbsIwEEX3nGIUqZKtjINCSEhBcAPYdElZuMa0pmESOQNVhbLvCXrAXiR1gM1IM6P/3/9HfdHquP/sTaXbFtba0XUE4IitP2hjYTOsAC/sHb2DEeEDJBfh2I3CaFmzM7ABgmVPahX9/f5EibeN1SyUonEpY2E@tJfiuUhzRU@l7BeDsjm/VUH5MLjUbg@nQBd30nan5Z18qP0N6uZkv4Zg2901xQlmOMUcC5xhiekMs3DJMMtxMi06eVOG1N8t21NSnzlpgitXJFwczeGVo5iSUEY@mnT9Pw)
**Explanation:**
```
n-> // Method with integer parameter and String return-type
"‚ñà".repeat( // Repeat this character
--n/8) // `n-1` integer-divided by 8 times
// (by first decreasing `n` by 1 with `--n`)
+(char) // Append an integer casted to a character:
(9615-n%8) // 9615 minus (`n-1` modulo 8)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14~~ ~~11~~ 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
L8ô€gŽb¶αç
```
[Try it online!](https://tio.run/##AR4A4f9vc2FiaWX//0w4w7Tigqxnxb1iwrbOscOn/0r/MTc "05AB1E – Try It Online") (I've put `J` for join in the footer, but apparently outputting a list of characters is ok)
* -3 thanks to S ®…†…†an
* -1 thanks to Kevin Cruijssen
### Explained
```
L8ô€gŽb¶αç # Implicit integer input 17
L # Inclusive range [1, 2, ..., 17]
8ô # Split into groups of 8 [1, ..., 8], [9, ..., 16], [17]
€g # Length of each [8, 8, 1]
Žb¶ # 9616
α # Absolute difference from 9616 [9608, 9608, 9615]
ç # chr of each ["█", "█", "▏"]
# Implicit output
```
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~54~~ 50 bytes
-4 bytes thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil)!
```
f(*o,n){for(;n>8;n-=8)*o++=9608;*o++=9616-n;*o=0;}
```
[Try it online!](https://tio.run/##LY3NCsIwEITvPsUSKCT9gVSwRGN8EfUQY1MCMZW24qH01Y3bn7nsMHyzYwrjdWhitDRt88BG23ZUhouQoVCCpW2WqWPFhdxcWRUBveJyii4M8NIuUAbjDlB9PfjWaF/TKgdCmFzSGXt87FXw@xrgBNA5daCglHjOCg4cTZaxhVjfLSzFag5u@zXr3WHXUpLw/RNOkPj@Fggi@byycdNuij9jvW76WHz/ "C (clang) – Try It Online")
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 43 bytes
```
:8,:1%-v
v1-"‚ñà"$>:?!
>~{8%:"‚ñà"+$?!~}>o<
```
[Try it online!](https://tio.run/##S8sszvj/38pCx8pQVbeMq8xQV@nRtA4lFTsre0Uuu7pqC1UrsIC2ir1iXa1dvs3///91y4xNAQ "><> – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 45 bytes
```
f=n=>n>8?'‚ñà'+f(n-8):Buffer([226,150,144-n])
```
[Try it online!](https://tio.run/##VY07DoJAFAB7T/E6dsNHQUSioomJJ7AkFAi7iCFvDawab@Dfbg@4F0ESbexmisns0mPaZHW5lzaKnLUtjzCa4zxcGFpdDJMTtEM6WR44ZzWJPS@w3NHAcn3fxoS2/T78gvF/EHf21uql1VOrh1Z3rW5aXY0YbTdJLBh5sDlL1sCplFtxkPA99LioCUIE7hQQZhEEfgemSSET2IiKOZUoCDpSrGVdYkGos0/zFeZkSMGEbk5p@wE "JavaScript (Node.js) – Try It Online")
52 bytes without `Buffer`:
```
f=n=>n>7?'█'+f(n-8):['▏▎▍▌▋▊▉'[n-1]]
```
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~46~~ 44 bytes
```
f(*o,n){for(;*o=n>0;*o++=9608-(n<0)*n)n-=8;}
```
[Try it online!](https://tio.run/##LY1BCoMwFET3nuITEBJjIBQqtmov0nZhUyOB9KeopQvx6k0TdTYDw5sZJZRtsfde08zlyGbtBlplrsGLDMZ5cypkKSjWkmXIUDRltXiDE7xag5TBnEDQ2E3WqdZ2tMiBEFatacQeH30t5X0LwjjQmBpoQFbBajhG55ytwLa2ojQ0czD7VNR7CFVNSSoPTzhDascbkoDk8WTnlmTxP6Vt249efP8 "C (clang) – Try It Online")
From jdt's solution, support 0
[Answer]
# [jq](https://stedolan.github.io/jq/), 43 bytes
```
[9616-((range(1;./8)|8),(.-1)%8+1)]|implode
```
[Try it online!](https://tio.run/##DchBDsIgFAXA/buHCUSpPmgR4lGMCxMb06aFii45u78ks5r5I3KPnt4oVZ7pPSreunPQNeiT6gz1IRypH3VatyW/RhHCwqHHAI8rAiJ4AQm2bhzcANv7f95@U05fMWUH "jq – Try It Online")
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 23 bytes
```
@+9608+{ùï©>7?0‚àæùïäùï©-8;7-ùï©}
```
[Try it at BQN REPL](https://mlochbaum.github.io/BQN/try.html#code=RWlnaHRzIOKGkCBAKzk2MDgre/Cdlak+Nz8w4oi+8J2VivCdlaktODs3LfCdlal9CkVpZ2h0c8KoICjihpUzMCk=)
```
@+9608+{ùï©>7?0‚àæùïäùï©-8;7-ùï©}
{ } # recursive function ùïä with argument ùï©
ùï©>7? # if x is greater than 7
0‚àæ # prepend zero onto
ùïäùï©-8 # result of recursive call with agument ùï©-8
; # otherwise
7-ùï© # 7-ùï©
+ # now, add the result of this to
@ # the null character
+9608 # +9608
```
We could use the literal character '‚ñâ' instead of `@+9608`, but this would prevent the code from being encoded with the [BQN](https://mlochbaum.github.io/BQN/) [single byte character system](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn), so the UTF8-encoded code would end-up [longer](https://mothereff.in/byte-counter#%27%E2%96%88%27%2B%7B%F0%9D%95%A9%3E7%3F0%E2%88%BE%F0%9D%95%8A%F0%9D%95%A9-8%3B7-%F0%9D%95%A9%7D).
[Answer]
# [Thunno](https://github.com/Thunno/Thunno) `J`, \$ 12 \log\_{256}(96) \approx \$ 9.88 bytes
```
R8Ap.L9616_C
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhZrgiwcC_R8LM0MzeKdIUJQmaXRSl5KsYuMLCFcAA)
Yet another port of Jonathan Allan's Jelly answer.
] |
[Question]
[
**This question already has answers here**:
[Diamond Puzzles!](/questions/67952/diamond-puzzles)
(21 answers)
Closed 2 years ago.
When learning to factorise quadratics in the form \$x^2 + ax + b\$, a common technique is to find two numbers, \$p, q\$ such that
$$pq = b \\
p + q = a$$
as, for such numbers, \$x^2 + ax + b = (x + p)(x + q)\$
You are to take two integers \$a, b \in (-\infty, +\infty)\$ and output the two integers \$p, q\$ such that
$$pq = b \\
p + q = a$$
You may take input in any [convenient method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) and you may assume that a solution always exists.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins
## Test cases
```
2, -15 -> 5, -3
-22, 85 -> -5, -17
6, -16 -> -2, 8
-8, -240 -> -20, 12
-1, -272 -> 16, -17
17, 16 -> 1, 16
-4, 0 -> 0, -4
3, -54 -> 9, -6
13, 40 -> 8, 5
-29, 198 -> -11, -18
11, -12 -> -1, 12
4, -320 -> 20, -16
4, 4 -> 2, 2
```
[Answer]
# [Scala 3](http://dotty.epfl.ch/), ~~49~~ 44 bytes
```
a=>b=>(-b*b to b*b)map(p=>a-p->p)find(_*_==b)
```
[Try it onlne!](https://scastie.scala-lang.org/o1O8XHFOTMKTbrrpKrS9DQ)
Takes `(a)(b)` and returns an `Option[(Int, Int)]`. It's now a little more inefficient since it goes from \$-b^2\$ to \$b^2\$ instead of \$-|b|\$ to \$|b|\$, including values that \$p\$ and \$q\$ could never be, but it saves 4 bytes.
```
a => b =>
(-b*b to b*b) //Make a range of all possible q's and then some
map(q => (a - q, q)) //Make a tuple of (p, q)
find(_ * _ == b) //Find a pair such that p * q = b
```
[Answer]
# JavaScript (ES7), ~~37 36 34~~ 31 bytes
*Saved 3 bytes thanks to @tsh*
Expects `(a)(b)`.
```
a=>b=>[b=a/2+(a*a/4-b)**.5,a-b]
```
[Try it online!](https://tio.run/##bZDNDoIwEITvPsUeKXbFXVooB3wR46H4F40Ro8bXx66Ug9b7l5lv5uxf/rG9n25PvPa7/XBoB9@uuna17lpf8DzzuS8MdirPF1Z77DbDtr8@@st@cemP2SEDYJUBklUKigKsBixn3wiyIOAigsJQPfvNqT45VYRYg/tF0KkQZpYTstRAnEAkUM0jRNXfMqrFaCqjkFMlOUYQiGWhCk2iXIqyNSPSBCRJIUFgUnYabHJOEwhqXBxFJMLJdKLPOzxR/5ZDMMaSY5e8g@ksGGdF5/AyD28 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~23~~ ~~21~~ 18 bytes
```
Solve[x x+#2==x#]&
```
[Try it online!](https://tio.run/##LYtBCoMwEEX3nqIQ6KYTMJOocZHiEQoupYsgSoVqoYQSCPHqaTp19@a9@at1j2m1bhltmk3qX8/PNPiTvzA0xrP7Od3ey@YGxq9z1@V770e77aEICFxUEYrAEUET1VnVpDRwVCWhyNjgD0UDR1ZATQKvFBUJxze2IFpNLg8F7RRwieWfVCxi@gI "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
1ṭÆrN
```
[Try it online!](https://tio.run/##y0rNyan8/9/w4c61h9uK/P6HHm73VnnUtCby//9oIx1dQ9NYnWhdIyMdCxDDDChgBhKw0NE1MjEAsQyBLHMjIMvQXAciZ6IDkjDW0TU1AQkb60AUGlnqGFpagESAWgxBOkx0dI2NDMAMk1gA "Jelly – Try It Online")
Input as a list `[b, a]`.
```
1ṭ Append 1 to the input, (resulting in [b, a, 1])
Ær find roots of polynomial from little-endian coefficient list,
N negate each root.
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 94 bytes
```
\d+
$*
^(-?)(1*)(,(-)(?<2>\2(1(1)*))|(?<5>(?<6>1)*),)(?<-6>\2)*$(?(6)1)
$1$.2,$4$1$.5
--
-0
0
```
[Try it online!](https://tio.run/##FYqxDsIwDER3f0eQ7GCj2E3SVELtyE9UCCQYWBgQI/8enOWe3t19nt/X@94PeLn1/XGEEOGKshFqJGQUwu1s626oqBSJfu5l9ajrcB67VD9QDLhhJSUIGk7GIQ8WEAGQBKl3Y1F3M24FqksFaSyWE4g6ZwOdebSZE0wsJYNOPGZbWJcG6jc1yCyTJUf@Aw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: \$|p|\$ is captured in `$2` and \$|q|\$ is captured in `$5`, with `$6` being a helper balancing group used to verify the multiplication.
```
\d+
$*
```
Convert to unary.
```
^(-?)(1*)
```
Start by matching the sign of \$a\$, then initially assume \$|p|\$ is no greater than \$|a|\$.
```
(,(-)(?<2>\2(1(1)*))
```
If \$b\$ is negative, then we actually end up matching \$|a|\$, and choose \$|q|\$ and overwrite `$2` with \$|p|=|a|+|q|\$, so \$|a|=|p|+|q|\operatorname{sgn}(b)\$.
```
|(?<5>(?<6>1)*),)
```
Otherwise \$b\$ is positive, so overwrite `$5` with \$|q|\$ such that \$|a|=|p|+|q|\operatorname{sgn}(b)\$.
```
(?<-6>\2)*$(?(6)1)
```
Ensure \$|b|=|pq|\$.
```
$1$.2,$4$1$.5
```
Output \$p = |p|\operatorname{sgn}(a)\$ and \$q = |q|\operatorname{sgn}(ab)\$. We then have \$p+q=|p|\operatorname{sgn}(a)+|q|\operatorname{sgn}(ab)=(|p|+|q|\operatorname{sgn}(b))\operatorname{sgn}(a)=|a|\operatorname{sgn}(a)=a\$ while \$pq=|p|\operatorname{sgn}(a)|q|\operatorname{sgn}(ab)=|pq|\operatorname{sgn}(b)=|b|\operatorname{sgn}(b)=b\$ as desired (where \$\operatorname{sgn}(0)=1\$).
```
--
-0
0
```
Fix up extraneous `-`s.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes
```
NθNηI⊟ΦE…·±↔η↔η⟦ι⁻θι⟧⁼ηΠι
```
[Try it online!](https://tio.run/##VckxD8IgEAXg3V/BeCR00MmmkzGadGjTuBqHKxK5BKEFrn8fiZO@6X3vaYtRB3Sl9H7hPPJ7NhFW2e1@baunSD7DGVOGKSxwJZfrM@ACvdeOE23mhv5lYDQvzAZOcwqOa7FSKvGvOykxkOcEqxIkH3W6rIwugVViiuHJOgPJb7pSmkMr9u2xNJv7AA "Charcoal – Try It Online") Link is to verbose version of code. Same idea as @user's Scala solution. Explanation:
```
NθNη
```
Input \$a\$ and \$b\$.
```
E…·±↔η↔η
```
Loop \$p\$ over \$[-|b|,|b|]\$.
```
⟦ι⁻θι⟧
```
For each \$p\$ create a list \$(p,q)\$ where \$q=a-p\$.
```
I⊟Φ...⁼ηΠι
```
Output the one with the highest \$p\$ where \$pq=b\$.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 17 bytes
```
@(x)-roots([1 x])
```
[Try it online!](https://tio.run/##PYzBCoAgEETvfYVHBYV209JD0H@Uh4i6ChXR39tKi7d5zJtJ270@ez7GJU/yVeZM6b7kDOKNKh9yRi0MuKgaygaJPENfip4LT4C2ZYJCA/4EgxbVs1qw1JHjLCsEdYyB/OC5KVfATzQ2HbYVaJ0/ "Octave – Try It Online")
You simply need to solve \$x^2 + ax + b = (x + p)(x + q) = 0\$, and \$x\_1=-p\$, \$x\_2=-q\$.
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), ~~42~~ ~~39~~ 37 bytes
Saved 2 bytes thanks to [Danis](https://codegolf.stackexchange.com/users/99104/danis)!!!
```
lambda a,b:[c:=a/2+(a*a/4-b)**.5,a-c]
```
[Try it online!](https://tio.run/##PZDdboMwDIXveQrfkbBkbcJvkdiLtL0INKhoGyDIpG1Vn505BsbVx7GPfZzxx92HPi7GaWmry/JhPuubASPq8tyUlTnoF2Yic0hkzaPoNRVGNtfF2dnNUAFjWoBUKRfApEYuCDMvZiQWiDo5EivPufascgFbRyKAyjFW04SKiJtFn7DvVJDq7YrcaJGxxg4e2O/RNs7eKEzqdfJ5Uvk6AlOtcMRZ6/bsv6z2HFiUtB03SlIw@nrYurnYb1hn@Gl0JA@au23e7eQjhJcvnSdNKIBIxSEP2mECJyx0Pfx2I6O3E7AH52UA@PnXbFnkOP2NU9c71oYP9wT5Bo/5CY9ty3keJrSxmVfVhpZfnyFf/gA "Python 3.8 (pre-release) – Try It Online")
Port of [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s [JavaScript answer](https://codegolf.stackexchange.com/a/216270/9481).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~17~~ 16 bytes
```
(Dn4I*-t‚DOsÆ);(
```
[Try it online!](https://tio.run/##yy9OTMpM/f9fwyXPxFNLt@RRwywX/@LDbZrWGv//6xoZcVmYAgA "05AB1E – Try It Online")
Why oh why aren't there any built-ins for this? This solves the quadratic equation to get the two roots. *-1 thanks to @ovs*
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes
```
~+ʰ⟨≜×⟩Ċ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wv0771IZH81c86pxzePqj@SuPdP3/Hx1tpBNvaBqrEx1vZKRjAWKYAQXMQAIWOvFGJgYgliGQZW4EZBma60DkTHRAEsY68aYmIGFjHYhCI0sdQ0sLkAhQiyFIh4lOvLGRAZhhEhsLAA "Brachylog – Try It Online")
Takes input as a list `[a,b]`.
```
ʰ For the first element of the input,
~+ get a list of integers which sum to it
≜ (in order of least absolute value of the first element).
⟨ ×⟩ Its product is the second element,
Ċ its length is 2,
and it's the output.
```
I'm not entirely sure why this needs `≜`, but it comes at no cost because the "sandwich" construct `⟨~+×⟩` won't parse without braces around `~+` anyhow (and both `⟨{~+}×⟩Ċ` and `~+ʰ⟨≡×⟩Ċ` would still come out to 8).
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~28 bytes~~ 24 bytes
thanks to att
```
#&@@Solve[#-b==a==#2/b]&
```
[Try it online!](https://tio.run/##Vc1LCoMwEAbgfU8RCLhKqBmjRmQgRyh0KS5iESrUFkqox4@TRWGy/fgfe4jPdQ9xe4R0YJKV9/fP67dOUi@IAVHCdZmrdPtu7@iPCZTQpp3Hyx80EDkuXY50POJIwNacTKYeGJleibJmleCdhiqt5Q2SchUG2hgcz@Qjw39oVTdQl0Kz6QQ "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 24 bytes
Input is a line of two numbers from STDIN. Output is to STDOUT.
```
?rdsad*r4*-vla+2/dlar-rf
```
[Try it online!](https://tio.run/##S0n@/9@@KKU4MUWryERLtywnUdtIPyUnsUi3KO3/fyOFeENTAA "dc – Try It Online")
## Explanation
```
? # Read a line of input
r # Swap the two numbers
dsa # Store to `a` w/o popping
d* # Square the 1st input
r # Swap up the second input
4* # Multiply by four
- # Second-to-top - TOS
v # Square root
la+ # Add by `a`
2/ # Halve
d # Duplicate
lar- # Push `a` - TOS
r # Swap the top 2 items
f # Print entire stack
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 37 bytes
```
lambda a,b:[p:=a/2+(a*a/4-b)**.5,a-p]
```
[Try it online!](https://tio.run/##PZDRboMwDEXf@Qq/kbBkbQIUWon9SNuHQIOKtrURZNI2xLczx8B4Olz72tdxP/7@fKSl6@e2uswf5rO@GTCiPp3dqTI7/cJMYnaZrHmSvObCSHedvR38ABUwpgVIlXMBTGrkkvAQxAOJJaLO9sQqcKEDq0LA2pEJoHKK1TyjIuJq0UfsO5akBrsiN1pkqrGDR/bb2cbbG4XJg06@QKpYRmCqBfY4a9l@@C@rLQcWJW3HjZIUjL4ctmwutxuWGWEaHcmj5m6bd9uHCPHlSxdZEwsgUmnMo/bZgxcWugf8do7R2wnYgvNTBPiF12xZ4jn9ub57eNbGo59AvsE4TDCuW87Ds0cbG3hVrWj5dYr5/Ac "Python 3.8 (pre-release) – Try It Online")
**[Python 2](https://docs.python.org/2/), 42 bytes**
```
def f(a,b):p=a/2+(a*a/4-b)**.5;print p,a-p
```
[Try it online!](https://tio.run/##PZDdbsMgDIXv8xS@C2SwFkJ@2qlvshuSghptSlBKpW4vnxnTjKtPPj72MeEn3pZZb9vVefDMioGfw8Ue9BuzlT0YOfCqem8@wjrNEYKwMmzR3eMdLsCYFiBVwwUwqZF7wjYVWyr2iNociVXiTidWnYBXhxFAco1qY0hEfFn0CftOPVWTXZEbLbLW2MEL9wxujO5KYZpUJ18i1eURmCrDEWfl7e2/rPYcKErajhslVTB6Pixv7vcb8ow0jY7kxXhz45dbU4Ty86E7M5YCiFRd8sIvK9C3CgfTDL9TYPR/Avbw/FwAPs/892Ijszg/08D59gc "Python 2 – Try It Online")
Takes input as float, and prints the output.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 12 bytes
```
ḟo=¹ΠmSe`-²ṡ
```
[Try it online!](https://tio.run/##ASEA3v9odXNr///huJ9vPcK5zqBtU2VgLcKy4bmh////Nv8tMTY "Husk – Try It Online")
Port of [user](https://codegolf.stackexchange.com/users/95792/user)'s [Scala answer](https://codegolf.stackexchange.com/a/216271/95126).
```
ṡ # range of integers from -arg1 to +arg1
m # map over each of them
S # combining itself
e # into a 2-element list with
`-² # arg2 minus this;
ḟ # now find the first element that satisfies
o # combine 2 functions:
Π # product
=¹ # equals arg1
```
[Answer]
# [R](https://www.r-project.org/), ~~36~~ 35 bytes
```
function(b,c)b/2+-.5:1*(b^2-4*c)^.5
```
[Try it online!](https://tio.run/##dZHNDoIwEITvPEUTL4AtsmvLj4k@CgaqJFwgErj48riNlNP21s1@O5OZzlvf2mWah@/7@Vnb19wug71v/TraZZjGuJM26S54Vpm5QRp3DSqd2qTJDHcYoxQKTCJOQj2EoeEacZhCAivPKQdCyZKFWxUedFe8YEUc6vwAcykAeRQcWuKOQhE2h5JUvDm4N6@opfDO5Ks0S11pY/SO1TTwYkDckYNSmUCBpAB15fOCCwV8N/8dHmiwGe3@C723q1AFEhPpk9CXYLT9AA "R – Try It Online")
Uses the [Quadratic formula](https://en.wikipedia.org/wiki/Quadratic_formula) with `a=1`.
[Answer]
# [C (gcc)](https://gcc.gnu.org/) `-lm`, 45 bytes
```
f(int*a){*a-=a[1]=(*a+sqrt(*a**a-4*a[1]))/2;}
```
[Try it online!](https://tio.run/##bY9Ra8MgFIWf66@QwkDNlUZj25Qs@yNZHsTNIrTpluRpkr8@d@PyMhgIfp5zz8Xj5NW5lDwLwywsj8LK1naqb5mwxfQ5zngLFI1YVc4PulnS3YaB8UgwQ2fX9Z3u20iiBqmOC5AotYY60wmlU5ZqkNqUGRXiWa@ozrDZBrJXgTya7FSwTesLqEudNQyqnDMgK13@klnI0hD/GOnagYa2bMLzFL7eH57Njh82FMhNKApOI9l9jDjq2f7pjeKRL3QP2CP0XdlvgF0bsls34GvFP5HX4f8AfiV9O3@z1ynJ2/0H "C (gcc) – Try It Online")
Modifies an input array of 2 `int`s.
---
### [C (gcc)](https://gcc.gnu.org/), 53 bytes
```
i;f(int*a){for(i=*a/2;(*a-i)*i-a[1];i--);*a-=a[1]=i;}
```
[Try it online!](https://tio.run/##bY/BasMwDIbP9VOYwsBOJRo7aZvieS@S@WDSZeiwdHQ5zeTZM9nLZTDQ4dP/6xfSgO/DsK7kRkXTXEWdxvtDka/i0TpVRSRdEcbeBEeI2rHic@fJLetHpEnpJDgp56EPvQ0@iWQBzWkBkdBa6AqdWToXqQO0bV3QMF5sRnOBzW6heA3gqS1OA9u0vYK5dkXjoCm5FrCx9S@1i1ic4Otl/kSSrx09f9H3231U86CPG1bMjg4HLZPYfT54dFT7p5vkwhe5B/6DQl@HDUzQTuzyBu4y/om8Tv8H@JT1Bw "C (gcc) – Try It Online")
Doesn't use `sqrt`.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~28~~ 26 bytes
-2 thanks to Razetime.
```
{⍺-⎕←(⍺÷2)+.5*⍨⍵-⍨⍺×⍺÷4}
```
[Try it online!](https://tio.run/##LYwxDsIwDEX3nOKPUBTUuEmbHqcSEkslGIsQK1sQC@IKbJ0QUsf2JrlIcJIu38/2s7tzLw@Xrj8dQxj8/Xn1bpL@8WLcMC4/2u72pvDu491XpjIt77TRtxAAwoB5VEbMI0WGNQKo87QWnDYx6TI2KjcNCagm6tnREcEGqiQYzfuI4DP2W0bVWh7mB4rvoRNWVK7M@Qc "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 19 bytes
-2 thanks to @Bubbler
```
÷∘2⍛{⍺(+,-)√⍵-⍨⍺*2}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v@JR24TD2x91zDB61Du7@lHvLg1tHV3NRx2zHvVu1X3UuwIoomVU@/@/goKRQoXCofWGplyH1huB2AoWplwKCmYQUTMuIGkBZhuZGIA4hhCOuRGXgqE5SDlEjQmIqQBUoWAMVmBqApQHMRWA2oDqLYFMQ0sLoCDEAEOgfgUTMNPYyADKBpIA "APL (Dyalog Extended) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~[46](https://codegolf.stackexchange.com/revisions/216319/1)~~ 39 bytes
```
a!b=[(k,b-k)|k<-[-a*a..],k*b-k*k==a]!!0
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P1ExyTZaI1snSTdbsybbRjdaN1ErUU8vVidbCyiklW1rmxirqGjwPzcxM8@2oCgzr0RFQ9dCU9HoPwA "Haskell – Try It Online")
Kind of boring, but short.
[Answer]
# [convey](http://xn--wxa.land/convey/), 113 bytes
```
v<1
>>>v 0
{?>*"-"v
4* "vvv
v >*vv
v#<<<<vv
-< vv
*%2 v>v
.1 v}>v
v v%2v}%2
">>>>>-^>+>^
>>>>>>>>^
```
[Try it online!](https://xn--wxa.land/convey/run.html#eyJjIjoidjwxXG4+Pj52IDBcbns/PipcIi1cInZcbjQqICBcInZ2dlxuIHYgID4qdnZcbnYjPDw8PHZ2XG4tPCAgICB2dlxuKiUyICAgdj52XG4uMSAgICB2fT52XG52ICAgICB2JTJ2fSUyXG5cIj4+Pj4+LV4+Kz5eXG4+Pj4+Pj4+Pl4iLCJ2IjoxLCJpIjoiMiAtMTUifQ==)
Ungolfed, mostly. Uses quadratic formula.
[](https://i.stack.imgur.com/oL5X9.gif)
[Answer]
# [Julia 1.0](http://julialang.org/), 34 bytes
```
(a,b)->(d=(a*a-4b)^.5;[a+d,a-d]/2)
```
[Try it online!](https://tio.run/##PZDBTsMwEETv@Yo92mBDvLWTVCiI/7CC5BJHBKG2IkZU/HzY3Yb69DSz4x374/tzTu6yTv2qkjlo@6zGXqW7ZP1Bvz6Ep5juR5PsODyiXkteygI9KIUGrAvagLJI3Ak2LDYidoToa2HH3CKzaw1sE96A2DtygxeTcIvgnub2nagcd5KmiN0hTegqX875reSRy8TA@mAgWibXMkoBBsdVsRZsbjajY6hJ8gy00TZbMshl183d7RKZx1oeOVCH6fQFqpisYT7C73xW8j0G/rvpCujwf02qREqXiMNVfFneTz9s9ZCrfBzXPw "Julia 1.0 – Try It Online")
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 13 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
_½\²¼k-√+`-αÞ
```
I/O as floats.
Port of [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/216270/52210).
[Try it online.](https://tio.run/##y00syUjPz0n7/z/@0N6YQ5sO7cnWfdQxSztB99zGw/P@/zfSM1DQNTTVM@DSNQKxLUBMM7CgGUjQAsQ0MjEAsQ3BbHOgMi5DcyAbosIEyAJJG4NkTU1AkiAmRIuRJUidpQVIFKzdEKQbpEXX2MgAygRiAA)
I have the feeling this can be a byte shorter with some smart stack manipulations, but I've been unable to find anything yet. An equal-bytes alternative could be [`²¼k-√`;½+`-αÞ`](https://tio.run/##y00syUjPz0n7///QpkN7snUfdcxKsD60VztB99zGw/P@/zfSM1DQNTTVM@DSNQKxLUBMM7CgGUjQAsQ0MjEAsQ3BbHOgMi5DcyAbosIEyAJJG4NkTU1AkiAmRIuRJUidpQVIFKzdEKQbpEXX2MgAygRiAA).
**Explanation:**
```
_ # Duplicate the first (implicit) input-float
½ # Halve it
\ # Swap so the first input is at the top of the stack again
² # Square it
¼ # Divide it by 4
k- # Subtract the second input-float
√ # Take the square-root of that
+ # Add it to the halved first input that's still on the stack
` # Duplicate the top two values (since the stack only contains a single
# item, this will first add the first input-float implicitly as leading
# item, and then duplicate both items)
- # Subtract the top two items from one another
α # Pair the top two items
Þ # Only leave the top item of the stack, and discard everything else
# (after which the entire stack is output implicitly as result)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~41~~ ~~37~~ 35 bytes
*A port of [Arnauld's answer](https://codegolf.stackexchange.com/a/216270/83605) in Ruby!*
```
->a,b{[b=a/2r+(a*a/4r-b)**0.5,a-b]}
```
[Try it online!](https://tio.run/##VZCxEoMgEET7fAVlYiByJygW5EccCyisMyYWmUy@nRyCYrrbebc7ezcv/h0mG8Tdcf8ZvHU1ztezq1ytZuEvVSVvmjvhx294LK8nmwbkTIAembVs0DQ34ykTgcRMRiIy6HbYRtkmZmjGYlulkolBzEdZKETdYabtfyp0nG2pkUHxKc5ypCSP2kFDSqtEeprbEkZoq0Gd9OEwWoTe5MsgVgJTfKvGQ/9SQ8UPYQ5FmZ4Qfg "Ruby – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 9 bytes
```
D(Ÿʒ-y*¹Q
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fRePojlOTdCu1Du0M/P9f19SEyxgA "05AB1E – Try It Online")
Takes input as
```
b
a
```
In case \$p=q\$ it returns only a single value. In case that's not allowed, it's +5 bytes for appending `}Ðgi«`
Explanation:
```
D duplicate
) negate
Ÿ range, so [-b,.. , b]
ʒ filter
- minus the implicit a
y the current number
* multiply
¹ the first item from the input history - b
Q is equals
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 3 bytes
```
∆QN
```
[Try it Online!](http://lyxal.pythonanywhere.com?s=?flags=&code=%E2%88%86QN&inputs=2%0A-15&header=&footer=)
Solve for the roots and then negate
[Answer]
# [Whispers v2](https://github.com/cairdcoinheringaahing/Whispers), ~~110~~ 92 bytes
*Edit: -18 bytes (within less than 2 minutes of submission!) thanks to caird coinheringaahing and the `±` operator*
```
> Input
> Input
> 2
> 4
>> 1*3
>> 2⋅4
>> 5-6
>> √7
>> 8÷3
>> 1÷3
>> 10±9
>> Output 11
```
[Try it online!](https://tio.run/##K8/ILC5ILSo2@v/fTsEzr6C0hAtBGwGxCZednYKhljGIMnrU3Qrmm@qagahHHbPMQbTF4e1geUMYbXBooyWI4V9aAjRJwdDw/38jLl1DUwA "Whispers v2 – Try It Online")
My first **Whispers** program.
Uses the [Quadratic formula](https://en.wikipedia.org/wiki/Quadratic_formula) with `a=1`.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 33 bytes
```
f(a,b)=round(polroots(x^2+a*x+b))
```
[Try it online!](https://tio.run/##LctNCoMwEAXgqwyukpqAifFv0V5ELMQWixBMiBbs6dPJ4O6b9@YFG1f5CSktzIqZ36P/bm8WvIveHzs7n7q0t7OcOU82BPdjFuQDQly3A1nko4CXdY4tAiznAsZRC5CqmZBSo3tim8OWwh6pTUVW2Z3OVp2A68MIoLrGtjFUIq@JHvBv6CnNc0VrnMhaVxfNNPH0Bw "Pari/GP – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 39 bytes
```
f a b=let c=a/2+(a*a/4-b)**0.5in[c,a-c]
```
[Try it online!](https://tio.run/##XcwxDsIgGMXxvad4gwOgUIo0MU04gJMHMA5fsY1ERKO9P1I3Gd/vn7wbfe5TjDnPIIwuTgu8o9ZsGQlqrRy5EFr1IZ39jqS/5AeFhGHA8QTGm99yuD4b4PUOacEGM4zSYLLrleZ/zqQpieNQShXs6rribl@ObK12RaXzFw "Haskell – Try It Online")
] |
[Question]
[
## Getting the average of a list (e.g `[2,6,7]`)
* Get the length of the list: `[2,6,7] -> 3`
* Sum the numbers in the list: `2 + 6 + 7 = 15`.
* Divide the sum by their count: `15 / 3 = 5`.
You should compare the averages of two lists of *positive* integers **N** and **M**, by returning a value if **N** has a higher average, another value if **M** has a higher average, and another one in case of a tie.
---
# I/O rules
All the [standard Input and Output methods](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) are allowed.
### Input
You may take input as two separate lists, a nested list, or anything else you consider suitable for the task. Please specify the format.
### Output
The values provided have to be distinct and must consist of at least one non-whitespace character. Also, they *must* be consistent between runs (a single value for **N**, a single value for **M**, a single value for **Tie**). Please specify those in your answer. The values can be non-empty Strings, Bool values, Integers, or anything you consider suitable.
---
# Specs
* The lists will not necessarily have equal length.
* You are guaranteed that the lists are non-empty.
---
# Test Cases
I chose the values `N wins`, `M wins` and `Tie`, which are pretty much self-evident.
```
N, M -> Output (Averages)
[7], [6] -> N wins (N has 7, M has 6 )
[4,5], [4,4] -> N wins (N has 4.5, M has 4)
[2,3,4], [4,5,6] -> M wins (N has 3, M has 5)
[4,1,3], [7,3,2,1,1,2] -> Tie (both have 2.666...)
[100,390,1], [89,82,89] -> N wins (N has 163.666..., M has 86.666...)
[92,892], [892,92] -> Tie (lists are basically identical)
[10,182], [12,78,203,91] -> Tie (both have 96)
```
---
[Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. Explanations are encouraged! This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins!
[Answer]
## Mathematica, 15 bytes
```
Order@@Mean/@#&
```
[Try it online!](https://tio.run/##RY5BCoMwEEX3nmKgUNrywWSiNUGEXKC0V5BWqYu60OxCzp4mIrh7894MzK933@m9xjh2z@UzLNY@hn4u7encFm5Y3Uod@YK8bwL8PQRkrlCnqUK1zwyVOJsax46ESq5JjRNL8F6kEFBGQKaqDTRDmz2ZzLx5hjkOIHW2ktFosFAwMoQitPHyWqbZkb3ReKXS0vZy/AM "Mathics – Try It Online")
`Function` which expects a list of two lists. `Mean/@#` takes the arithmetic mean of each list in the input, then those means are passed into `Order`, which returns `-1` if the first list wins, `0` if there is a tie, and `1` if the second list wins.
[Answer]
# JavaScript (ES6), ~~52~~ 50 bytes
*(Saved 2 bytes thanks to @Shaggy.)*
Here are two 50-byte solutions:
```
f=(N,M,a=eval(N.join`+`)/N.length)=>M?(a-f(M))/0:a
(N,M,A=a=>eval(a.join`+`)/a.length)=>(A(N)-A(M))/0
```
Returns **Infinity** for N, **-Infinity** for M, and **NaN** for a tie.
The first solution may require a bit of explanation due to the recursion:
On the first call to the function, `a` is initialized as the average of the `N` array:
```
a=eval(N.join`+`)/N.length
```
`M` has a value at this point, so the first part of the conditional expression is called:
`M ? (a-f(M))/0 : **a**
----------`
The function is called within this expression, this time substituting `M` for `N`.
On this second call to the function, `a` is initialized as the average of `N` –– which was `M` in the previous call.
Since there is no second parameter during this call to the function, the second part of the conditional expression is triggered, which returns the average:
`M ? (a-f(M))/0 : **a**
--`
We can now understand the expression better:
```
(a - f(M)) / 0
```
It's:
```
(the average of N minus the average of M) divided by 0
```
The difference between the averages will be a positive number, a negative number, or 0.
Dividing the difference by 0 results in **Infinity**, **-Infinity**, or **NaN** – providing the three distinct values as required.
**Test Cases:**
```
f=(N,M,a=eval(N.join`+`)/N.length)=>M?(a-f(M))/0:a
console.log(f([7], [6] )) // N wins (N has 7, M has 6 )
console.log(f([4,5], [4,4] )) // N wins (N has 4.5, M has 4)
console.log(f([2,3,4], [4,5,6] )) // M wins (N has 3, M has 5)
console.log(f([4,1,3], [7,3,2,1,1,2] )) // Tie (both have 2.666...)
console.log(f([100,390,1], [89,82,89] )) // N wins (N has 163.666..., M has 86.666...)
console.log(f([92,892], [892,92] )) // Tie (lists are basically identical)
console.log(f([10,182], [12,78,203,91] )) // Tie (both have 96)
```
[Answer]
# Mathematica, 21 bytes
```
Sign[Mean@#-Mean@#2]&
```
1 for `#` wins, -1 for `#2` wins, 0 for tie.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 8 bytes
Soooo many modifiers (`Y` and `Z`). I can't find a way to make it shorter. `sum / number_of_elements` is three bytes. It might be a better way to do `-ZS`, but I can't find one.
```
YmiYm-ZS
```
[Try it online!](https://tio.run/##y00syfn/PzI3MzJXNyr4//9oEx1DHeNYrmhzHWMdIyDbUMcoFgA "MATL – Try It Online")
```
% Take first input implicitly
Ym % Mean of that input
i % Grab second input
Ym % Mean of that input
- % Subtract
ZS % Sign
```
Returns `1` if the first input is larger, `0` if they tie, and `-1` if the second input is larger.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
**1** if `M` wins, **-1** if `N` wins and **0** for a tie.
```
vyOyg/}.S
```
[Try it online!](https://tio.run/##MzBNTDJM/f@/rNK/Ml2/Vi/4///oaBMd01gdBSBlEhsLAA "05AB1E – Try It Online")
**Explanation**
```
v # for each y in list of lists
yO # sum y
yg # get length of y
/ # divide
} # end loop
.S # compare
```
[Answer]
# [Julia](https://julialang.org/), 27 bytes
```
(x,y)->cmp(mean(x),mean(y))
```
[Try it online!](https://tio.run/##ZYxBCsIwEEX3nsJlAl/ITBKTLPQipYsiFiptKVKhPX1M4kbS1TDvvZnXZxw6G/tbFBt2ebk/pkVMz24Wm0SZu5RxeQ/zOs6iF41rcW6urZSnP2hgMzYwlWDoxIqyOF4RdJYuVZwWAlcJKQUdFChnPsAzfKiakBn/AkY4vgD5oonhPFhpBEpR/AI)
Returns `1` if the first average is larger, `-1` if second is, and `0` if they tie.
[Answer]
# [Actually](https://github.com/Mego/Seriously), 5 bytes
```
♂æi-s
```
[Try it online!](https://tio.run/##S0wuKU3Myan8///RzKbDyzJ1i///j442NDDQUTC2BBKGsToK0RaWOgoWRkBsGRsLAA "Actually – Try It Online")
`1` for `N > M`, `0` for `N = M`, `-1` for `N < M`.
Explanation:
```
♂æi-s Takes input in format [N, M]
♂æ Map average
i Dump to stack in reverse
- Subtract
s Get sign
```
[Answer]
# [Python 2](https://docs.python.org/2/), 43 bytes
```
lambda p:cmp(*[sum(l)*1./len(l)for l in p])
```
[Try it online!](https://tio.run/##JYpBDoIwFET3nqJLSn60/xekJfEktQtUiCSlNAgxnr62sJqZ9yb81vfsKQ63e3Td9Hh1LLTPKRSl@WxT4XiJ54vrfWrDvDDHRs@C5fH7Hl3PsA3L6Fc2FKMP21pwHk1jgZmrPZkK6lwrqNIgkCn3WcNhEWQGTTKUBgIljEKA1AIwK6VBESiduM5JByTQxxVQ7QgJGgUkJGi0fw "Python 2 – Try It Online")
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 27 bytes
```
@(x,y)sign(mean(x)-mean(y))
```
[Try it online!](https://tio.run/##JYo7DoMwEET7nILSKw0WuzafFEi5B3KBECAKoAiK4PRmcaqZ92b24eh/Y5xaa238mBMXfZd5M@vYb@akPOVFFCfTeZQBmYYP9FIWOK3JlKhClqQHwz2y1lUUGPK/cwFu5JlYUDeQwuHNgeIN "Octave – Try It Online")
Takes two vectors `x.y` as input, takes the `mean` of both vectors, and subtract one from the other. Get the sign of this, to get `1`, `0` and `-1` for the three different alternatives.
[Answer]
# Python 2, 49 bytes
```
lambda N,M:cmp(1.*sum(N)/len(N),1.*sum(M)/len(M))
```
[**Try it online**](https://tio.run/##LYpBDoIwEEXXcgqWhfxoZwBpSTwCXABZoEIggUoUYjw9Furqz3tvpu/cPQ2v7eW6DvV4e9R@gTy7j5OgY/heRlEEp6ExdvAXuRN5EKyfrh8anzLvML16M4tWhL2ZllkENpZpBb88V14ZI9nOGLEFRmR3xwSuEqJNpLawBQJbTVIi0hK0JaWhGEpbr7dlJxnavYLUroiRKrCMoKn6AQ)
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 11 bytes
Prompts for a list of two lists. Prints `1` if the left has higher average, 0 if they have the same average, and `¯1` if the right has higher average.
```
×-/(+/÷≢)¨⎕
```
[Try it online!](https://tio.run/##fc0xCsJAEAXQ3lP8MouKO5NodmMlnkRQoxBJ0CB4ArXQTqxsrOxsBHtzk71I3BVExOBUw8ybP4MsaQ5XgySNS7NZ99NZ1lvGi7I4NltevVXczfYsHhezP7h1aXYnUJSMxnkXMsqnoy4eV4rm03iS1/Cqd0TNa4QCXqMj8FU/LEDbOja7WyD@QoYPS9wBPqkVeQTfstBytj2BRQUjKeFrCbJUaSiG0uKXaTfnl2G4pvop2SDlGDFCBZY@NIkn "APL (Dyalog Unicode) – Try It Online")
`⎕` prompt
`(`…`)¨` apply the following tacit function to each:
`+/` the sum
`÷` divided by
`≢` the tally
`-/` insert (and evaluate) a minus between them
`×` signum
[Answer]
# Javascript, ~~81~~ ~~66~~ ~~58~~ 56 bytes
*saved 15 bytes thanks to Luke*
*saved 2 bytes thanks to Justin Mariner*
```
n=>m=>Math.sign((a=b=>eval(b.join`+`)/b.length)(m)-a(n))
```
Tie is 0, M is 1 and N is -1. Called using currying syntax, eg. `f([7])([6])`
[Answer]
# [PHP](https://php.net/), 68 bytes
```
<?foreach($_GET as$v)$r[]=array_sum($v)/count($v);echo$r[0]<=>$r[1];
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwKUS7@4aYqsQHW1ooGNoYRSroxBtaKRjbqFjZGCsY2kYG2v9Py2/KDUxOUMDrFQhsVilTFOlKDrWNrGoKLEyvrg0VwMoop@cX5pXAmJZpyZn5AMVGMTa2NoBaUOgEf8B "PHP – Try It Online")
# [PHP](https://php.net/), 69 bytes
```
<?=($s=array_sum)($a=$_GET[0])/count($a)<=>$s($b=$_GET[1])/count($b);
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwKUS7@4aYqsQHW1ooGNoYRSroxBtaKRjbqFjZGCsY2kYG2vNZW8HVGuroVJsm1hUlFgZX1yaq6mhkmgL1hptEKupn5xfmlcCFNK0sbVTKdZQSYLKGSLkkjSt//8HAA "PHP – Try It Online")
[spaceship operator](http://php.net/manual/en/language.operators.comparison.php)
-1 less then , 0 tie , 1 greater then
[Answer]
# Haskell, ~~65~~ 43 Bytes
*Saved 22 bytes thanks to nimi!*
```
a x=sum x/sum[1|_<-x]
x#y=compare(a x)$a y
```
~~There has to be a much better way... But type conversions screwed me.~~
**Usage**
```
(#) [7] [6]
```
Returns `GT` if the first argument wins, `LT` if the second argument wins, and `EQ` if they tie.
[Try it online!](https://tio.run/##hdHLasMwEAXQfb7iQrKwYeJasi1bUH9CsuouiKIkhoj6ESK3taH/7spu00eSUi2GWUiHe9FB26eiLIdBo8vtc4Xuzs0Ne3u8X3YKs27e57umOupT4bkr/kKjHyptauTYNzPgeDJ1iwW8uY9NqrARCpdnucQar6a2gLfGQVukhNW0CPiXSEyJGmes/kHiIDkz8ZXCKRqFUaMfkZyy@q1EZyO5kYRR5IzUWdztjLj6MB5MMXHetmkP7vVLAR4IIYIguFJYGFIkQ2JOyiRlnDKpbvVhIvo0zpEy8RcqR4VPIifJ1Xe9r2ilsa2F@zhstTU7XZY9zL6o23H3cR2TWDaKjFOaEQ8jki7y7bJS@MM7)
[Answer]
# J, 10 bytes
```
*@-&(+/%#)
```
One list given on the left, one on the right. Will return \_1 if the left average is smaller, 1 if it's bigger, and 0 if they're equal
* `(+/%#)` is a standard J fork for calculating the average of a list
* `&` provides a variation on the dyadic fork. it applies the right side (the average verb, in this case) to both arguments, and then passes them along to the verb on the left side, which in this case is...
* `*@-` subtract followed by "sign of": so the right avg is subtracted from the left, and we are given the sign of the result -- \_1, 1, or 0
[Answer]
# **Pyth, ~~10~~ ~~8~~ ~~7~~ 6 bytes**
Thanks @isaacg for saving a byte
```
._-F.O
```
Input is taken as a nested list, `[N, M]`. Outputs `-1` if `N < M`, `1` if `N > M` and `0` if they are equal.
[Try It Online](http://pyth.herokuapp.com/?code=._-F.O&test_suite=1&test_suite_input=%5B%5B7%5D%2C+%5B6%5D%5D%0A%5B%5B4%2C5%5D%2C+%5B4%2C4%5D%5D%0A%5B%5B2%2C3%2C4%5D%2C+%5B4%2C5%2C6%5D%5D%0A%5B%5B4%2C1%2C3%5D%2C+%5B7%2C3%2C2%2C1%2C1%2C2%5D%5D%0A%5B%5B100%2C390%2C1%5D%2C+%5B89%2C82%2C89%5D%5D%0A%5B%5B92%2C892%5D%2C+%5B892%2C92%5D%5D%0A%5B%5B10%2C182%5D%2C+%5B12%2C78%2C203%2C91%5D%5D&debug=0)
[Answer]
## TI-Basic, ~~25~~ ~~21~~ ~~13~~ ~~12~~ 10 bytes
-2 bytes thanks to lirtosiast
```
:tanh(ᴇ9mean(L₁-mean(L₂
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
S÷Lµ€IṠ
```
A monadic link accepting a list of the two lists, `N,M` which returns:
`[-1]` for `N`;
`[1]` for `M`; and
`[0]` for a tie.
As a full program it prints the result (single item lists print their content only, so `-1`, `1`, or `0`).
**[Try it online!](https://tio.run/##y0rNyan8/z/48HafQ1sfNa3xfLhzwf///6MNDXQMLYxidRSiDY10zC10jAyMdSwNYwE "Jelly – Try It Online")**
### How?
```
S÷Lµ€IṠ - Link: list of lists, [N,M]
µ€ - perform the chain to the left for €ach (of N, M)
S - sum
L - length
÷ - divide (yields the average)
I - incremental differences (yields [avg(M) - avg(N)])
Ṡ - sign (yields: [1] if avg(M)>avg(N); [-1] if avg(N)>avg(M); or [0] if equal)
```
[Answer]
# [Perl 6](http://perl6.org/), 25 bytes
```
{sign [-] .map:{.sum/$_}}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/ujgzPU8hWjdWQS83scCqWq@4NFdfJb629r@1QnFipUKahoaNoYKRgrGdjoINkFIwsdPU/A8A "Perl 6 – Try It Online")
Takes a single argument, a two-element list of lists of numbers. Returns `1` if the first list has a greater average, `-1` if the second list does, and `0` if the averages are equal.
[Answer]
# JavaScript (ES6), 60 bytes
```
a=>(b=(c=a.map(d=>eval(d.join`+`)/d.length))[0])-c[1])?b>0:0
```
Outputs `0` for `Tie`, `true` for `N` and `false` for `M`.
[Answer]
# JavaScript (ES6), ~~60~~ 54 bytes
*-6 bytes thanks to @Luke and @Neil*
```
(i,[x,y]=i.map(v=>eval(v.join`+`)/v.length))=>y-x&&x>y
```
Takes input as a 2-element array `[N, M]`. Outputs `true`, `0`, or `false` for `N`, `Tie`, or `M`, respectively.
## Explanation
```
(i, // input array: [N, M]
[x,y] = // destructure assignment: set x and y to...
i.map(v=> // the input values mapped as...
eval(v.join`+`) // the sum, by joining the array with +
/ v.length // divided by the length
)
) => y-x && x>y // return 0 for tie, or the result of avg(N) > avg(M)
```
## Test Snippet
Input numbers separated by spaces/commas.
```
f=
(i,[x,y]=i.map(v=>eval(v.join`+`)/v.length))=>y-x&&x>y
```
```
<div oninput="O.value=f([N.value,M.value].map(x=>x.split(/[ ,]+/)))">N <input id=N> M <input id=M></div>
Out: <input id=O disabled>
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 13 bytes
```
{$CM$+*a/#*a}
```
This is a function that takes a list of lists. Returns `1` if the first average is bigger, `-1` if the second is bigger, `0` if tied. [Run all test cases here.](https://tio.run/##RYoxDsIwEAT7vGKluApC@M4Ovqup8wLLRUoalB7x9uMcS9DNzuzxPMze4bGFy7Lf5mX/2FYn1Foa6r21jhmrj4w8JiM5drHi9yAkV8UTOxN4BIpIGkHeRCEM0RG0I5@aof83SZfEKAKOCUqemtn19QU "Pip – Try It Online")
### Background
This solution makes heavy use of two of Pip's metaoperators:
* `$`, fold. Take a binary operator and apply it between the elements of a list. For instance, `+` is addition, but `$+` sums a list. Note that `$` makes a binary operator into a unary operator.
* `*`, map. Take a unary operator and apply it to each element of a list. For instance, `#` gives the length of a list, but `#*` gives (a list of) the lengths of the list's items.
* These two metaoperators can be combined: `$+*` maps fold/plus over a list, summing each of the list's elements.
The other thing to know about Pip is that a lot of operators work item-wise on lists by default. For instance, `[1 2 3] * 5` gives `[5 10 15]`; `[1 2 3] * [2 3 4]` gives `[2 6 12]`; and `[[1 2] [3 4]] * [5 6]` gives `[[5 10] [18 24]]`.
### Explanation
We'll use an example input of `[[2 3 4] [2 3 4 6]]`:
* `{...}`
Defines a function. The (first) argument is bound to the local variable `a`.
* `#*a`
Map `#` to the function's argument, getting the lengths of the sublists. Result: `[3 4]`
* `a/#*a`
Divide (the elements of) the sublists of `a` by their respective lengths. Result: `[[0.667 1 1.333] [0.5 0.75 1 1.5]]`
* `$+*a/#*a`
Map `$+` (fold on addition) to that result, summing the sublists. Result: `[3 3.75]`
* `$CM$+*a/#*a`
Fold on `CM`, which gives `-1`, `0`, or `1` depending on the comparison of its two operands (like Python's `cmp`). Result: `-1` (because `3` is smaller than `3.75`).
---
You can also define functions in Pip by writing expressions containing the identity function `_`. For example, `_*_` is a function that squares its argument--syntactic sugar for `{a*a}`, and fewer bytes. However, there's a bug in the current version of the interpreter that prevents `_` from working with the `*` metaoperator. Once that's fixed, this solution can be **11 bytes**: `$CM$+*_/#*_`.
[Answer]
# C (gcc), 91 ~~98~~ bytes
```
u,v,j;f(x,y,a,b)int*a,*b;{for(u=v=0;x--;u+=a[x])for(j=0;j<y;)v+=b[j++];j=u*y-v;x=j>0?2:!j;}
```
Wrong place for C and probably the only answer that doesn't need division. At least the code is displayed without a slider.
Return 0,1,2 for `M>N`, `M=N`, `M<N` respectively. Takes input as `length of M`, `length of N`, `M`, `N`.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes
```
⟨+/l⟩ᵐ-ṡ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//9H8Fdr6OY/mr3y4dYLuw50L//@PjjbRMY3VAZImsbH/owA "Brachylog – Try It Online")
Outputs `1` if the first list has a bigger average, `-1` is the second list has a bigger average, and `0` if they are tied.
### Explanation
```
ᵐ Map:
⟨ ⟩ Fork:
+ Sum…
/ …divided by…
l …length
- Subtract
ṡ Sign
```
[Answer]
# Java, 105 bytes
```
s->s.stream().map(l->l.stream().reduce((i,j)->i+j).get()/l.size()).reduce((i,j)->Math.signum(i-j)).get();
```
Lambda that takes a nested list, as per allowable inputs.
Streams the list of lists, converts both to their averages, then returns the sign of the difference. `1` if the first list is larger, `-1` if the second list is larger, `0` for a tie.
[Answer]
# R 38 34 bytes
```
function(a,b)sign(mean(a)-mean(b))
```
Function that takes as input two numeric vectors. Returns 1 if first list average is higher, 0 if they are the same and -1 if second list average is higher.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 6 bytes
Don't be so mean!\*
```
!-ssZS
```
Input stack order:
```
M
N
```
Output:
```
1 = N wins
-1 = M wins
0 = tie
```
[Try it online!](https://tio.run/##y00syfn/X1G3uDgq@P//aBMdUx0zMDaJ5Yo20jEG0gA "MATL – Try It Online")
```
!-ssZS
========
! % transpose M
- % N - M^T using elementwise subtraction and implicit expansion
s % sum columns of the result
s % sum the resulting row vector
ZS % sign of the sum
```
\*This answer was golfed without being mean to any poor, defenseless numbers.
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~76~~ 62 bytes
```
a->b->Math.signum(a.average().orElse(0)-b.average().orElse(0))
```
[Try it online!](https://tio.run/##bZJRb4IwEMff/RQXE5N2wQacmzA3kyXbkj345N6MD0WLq4OWtMXELHx2dxbcFoUCLf/73b/NcTu@50NdCrXbfB1lUWrjYIcaq5zM2c20d6VllVo7qVVn0DojeHEKlVWayzWsc24tzLlU8N0DaFXruMNpr@UGCoyRhTNSbZcr4GZrqUcB3tqdHt@VW3jj4EO/aLQQ16HZDDJ4OvLhLB3O5tx9Miu3qioIZ3wvDN8KQpk2r7kVJKTDtEulR/DX1G8vlVuuTgOcsM7CU3ssgG8cE6gDnO6hxsU/fRzAXRPC1fgyOgrg1sstcBd0OkSINczEJ4y8hPfoEo7CEIkEX1GTECcBxMjHySWaeHV0xvAr6bBDo7hlIkQmMW4a4hGS6I@tmwJl2pC2SL5ED02h6G@dfn8OcKzeszH8YNsWISd0Ga7o9IpNu9noj10crBMF05VjJfaNy0h/YOEBBizMBqofnNM3QpQfuuktb0IDyBgvy/xAOG0Wz7bpKJLS1r/unZ76@AM "Java (OpenJDK 8) – Try It Online")
Since the input can be anything, I decided to take `IntStream`s as input. You can get such an input from a standard `int[]` with `Arrays.stream(array)`.
The output is `1` for "N wins", `-1` for "M wins", and `0` for tie.
### Saves
* -14 bytes from insights of both @Zircon and @Xanderhall!
[Answer]
# Dyalog APL, 14 bytes
```
×(-/(+/÷≢)¨∘⊢)
```
`1` if the left is greater, `¯1` if the right is and `0` on tie.
**How?**
`¨∘⊢` for each list
`+/÷≢` calculate average (`+/` sum `÷` divide by `≢` length)
`-/` subtract the averages
`×` sign of the result
[Answer]
# [Common Lisp](http://www.clisp.org/), ~~74~~ 71 bytes
```
(defun g(x)(/(apply'+ x)(length x)))(defun f(x y)(signum(-(g x)(g y))))
```
[Try it online!](https://tio.run/##lczBCsIwEATQe79ibp1Fimhb/0e0WQNpCDaF5uvjCp7EHty97AyPvQW/pFp5n9waodyER15TCqU9wEKYouaHXSIf47ihCBevcZ3ZUd9MrbKpTE8fMx1ofzNOOKPHgEG@ilFg2@zw8T9@@c3rCw "Common Lisp – Try It Online")
] |
[Question]
[
A [*proper divisor*](http://mathworld.wolfram.com/ProperDivisor.html) is a [divisor](https://en.wikipedia.org/wiki/Divisor) of a number *n*, which is not *n* itself. For example, the proper divisors of 12 are 1, 2, 3, 4 and 6.
You will be given **an integer** *x*, *x* ≥ 2, *x ≤ 1000*. Your task is to sum all the ***highest* proper divisors** of the integers from *2* to *x* (inclusive) (OEIS [A280050](http://oeis.org/A280050)).
### Example (with `x = 6`):
* Find all the integers between 2 and 6 (inclusive): 2,3,4,5,6.
* Get the proper divisors of all of them, and pick the highest ones from each number:
+ 2 -> **1**
+ 3 -> **1**
+ 4 -> 1, **2**
+ 5 -> **1**
+ 6 -> 1, 2, **3**.
* Sum the highest proper divisors: `1 + 1 + 2 + 1 + 3 = 8`.
* The final result is 8.
# Test Cases
```
Input | Output
-------+---------
|
2 | 1
4 | 4
6 | 8
8 | 13
15 | 41
37 | 229
100 | 1690
1000 | 165279
```
# Rules
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
* You can take input and provide output by [any standard method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods).
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest valid submission in each language wins! Have Fun!
[Answer]
# [Oasis](https://github.com/Adriandmen/Oasis), 4 bytes
### Code:
```
nj+U
```
[Try it online!](https://tio.run/##y08sziz@/z8vSzv0////FgA "Oasis – Try It Online")
### Explanation:
Extended version:
```
nj+00
0 = a(0)
0 = a(1)
a(n) =
n # Push n
j # Get the largest divisor under n
+ # Add to a(n - 1)
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes
```
⟦bb{fkt}ᵐ+
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//9H8ZUlJ1WnZJbUPt07Q/v/f0MDA4H8UAA "Brachylog – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~13~~ ~~9~~ 8 bytes
1 byte thanks to jacoblaw.
```
tsm*FtPh
```
[Test suite](http://pyth.herokuapp.com/?code=tsm%2aFtPh&test_suite=1&test_suite_input=2%0A4%0A6%0A8%0A15%0A37%0A100%0A1000&debug=0).
## How it works
The largest proper divisor is the product of the prime factors except the smallest one.
[Answer]
## [Husk](https://github.com/barbuz/Husk), 7 bytes
```
ṁȯΠtptḣ
```
[Try it online!](https://tio.run/##yygtzv7//@HOxhPrzy0oKSh5uGPx////jc0B "Husk – Try It Online")
## Explanation
Husk has no built-in for computing the divisors directly (yet), so I'm using prime factorization instead.
The largest proper divisor of a number is the product of its prime factors except the smallest one.
I map this function over the range from 2 to the input, and sum the results.
```
ṁȯΠtptḣ Define a function:
ḣ Range from 1 to input.
t Remove the first element (range from 2).
ṁ Map over the list and take sum:
ȯ The composition of
p prime factorization,
t tail (remove smallest prime) and
Π product.
```
[Answer]
# [Python 2](https://docs.python.org/2/), 50 bytes
```
f=lambda n,k=2:n/k and(f(n,k+1),n/k+f(n-1))[n%k<1]
```
This is *slow* and can't even cope with input **15** on TIO.
[Try it online!](https://tio.run/##DYxBCoMwFETX9RSzCSYY2yZIKVJ7kdKFrUqD@iNJXHj69A/M4j2Y2Y7082SzWzcfEuIRC@45jimM3z1E52lxq0vSXDkqT93Sr5@hB@m5sy1dZvQ0yEkyV0ZpFhVDbZR6kZgf5p0nH0BwBKvRaNw07m1x2oKjJEthdtRPCLuXEOAX8Foplf8 "Python 2 – Try It Online")
However, memoization (*thanks @musicman523*) can be used to verify all test cases.
[Try it online!](https://tio.run/##VU5Ra8IwGHw2v@Jeis2MrK3ODamDMRiUbT5svgwRcTbBUJuUNH1wY7@9pikie8mXu/vu7qtO9qBV0gqjSxhe68bsOWRZaWNxQzxdn@orQ2puzVGW0oYfb9l7ttp@rp6eXxk83GbLl2yZrb4Y/kFKvY/vG1NLrXp/jDTFJKKtWBx35Xe@g2LFIpmr2wI7lYcidHgUU@aIkQPjmNK1Coo03rQ5Fyh5qeUPDwWdk0EHsMDvHxl02oEfK25cAArHJt3GQAp4gkJpC6l8QCd487rXNm5d9F@nGG4b0y9edHIh@wpChHNcT3FYG6guPmGYMswYHhjiO4bJvZtR5J/I9VZGKhsOg2mD8SOCWTNE4C90/ZTS9gw "Python 2 – Try It Online")
### Alternate version, 52 bytes
At the cost of 2 bytes, we can choose whether to compute `f(n,k+1)` or `n/k+f(n-1)`.
```
f=lambda n,k=2:n>1and(n%k and f(n,k+1)or n/k+f(n-1))
```
With some trickery, this works for all test cases, even on TIO.
[Try it online!](https://tio.run/##VYxNi8IwGITP9lfMpdhoxMb6haggCwth1YP24kmqthhq35QkPfjr3dg9LF5meB6YqZ/uril5FUZXMLnVjbnmUFWtjUMvaLV92n8T2NyZh6qUiw5buZPp@Zhuvn44WjzL/bfcy/TE8YGMtbv82hirNP3tBZZLJDF7FatHVl1uGYiXq9GC1iKjW0RhCd8oIq/7gmkDGpZ9jwPB/OjNUIQRx5hjyjHnEBOOZOY7jtuIF0GnNopc1A3HDQZrhNOmixD@833M/NEv "Python 3 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
ÆḌ€Ṫ€S
```
[Try it online!](https://tio.run/##y0rNyan8//9w28MdPY@a1jzcuQpIBv///9/QwMAAAA "Jelly – Try It Online")
## How it works
```
ÆḌ€Ṫ€S
ÆḌ€ map proper divisor (1 would become empty array)
implicitly turns argument into 1-indexed range
Ṫ€ map last element
S sum
```
[Answer]
## JavaScript (ES6), 40 bytes
```
f=(n,i=2)=>n<2?0:n%i?f(n,i+1):n/i+f(n-1)
```
```
<input type=number oninput=o.textContent=f(this.value)><pre id=o>
```
A number equals the product of its highest proper divisor and its smallest prime factor.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 8 bytes
-1 Byte thanks to [Leaky Nun](https://codegolf.stackexchange.com/users/48934/leaky-nun)'s prime factor trick in his Pyth answer
```
L¦vyÒ¦PO
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f59CyssrDkw4tC/D//9/QwMAAAA "05AB1E – Try It Online")
### Explanation
```
L¦vyÒ¦PO
L¦ # Range [2 .. input]
vy # For each...
Ò¦ # All prime factors except the first one
P # Product
O # Sum with previous results
# Implicit print
```
Alternative 8 Byte solution (That doesnt work on TIO)
```
L¦vyѨθO
```
and ofc alternative 9 Byte solution (That works on TIO)
```
L¦vyѨ®èO
```
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~31~~ 24 bytes
7 bytes thanks to Martin Ender.
```
.+
$*
M!&`(1+)(?=\1+$)
1
```
[Try it online!](https://tio.run/##K0otycxL/P9fT5tLRYvLV1EtQcNQW1PD3jbGUFtFk8vw/39DAwMDAA "Retina – Try It Online")
## How it works
The regex `/^(1+)\1+$/` captures the largest proper divisor of a certain number represented in unary. In the code, the `\1+` is turned to a lookahead syntax.
[Answer]
# Mathematica, 30 bytes
```
Divisors[i][[-2]]~Sum~{i,2,#}&
```
[Answer]
# [Python 2 (PyPy)](http://pypy.org/), ~~73~~ ~~71~~ 70 bytes
```
n=input();r=[0]*n;d=1
while n:n-=1;r[d+d::d]=n/d*[d];d+=1
print sum(r)
```
Not the shortest Python answer, but this just breezes through the test cases. TIO handles inputs up to **30,000,000** without breaking a sweat; my desktop computer handles **300,000,000** in a minute.
At the cost of **2 bytes**, the condition `n>d` could be used for a ~10% speed-up.
*Thanks to @xnor for the `r=[0]*n` idea, which saved 3 bytes!*
[Try it online!](https://tio.run/##JcpBCoAgEADAe6/wqEWkdVP2JeJtA4XaFlPC11vQnIdbiRetMzduvRMk4lqkchm8DiM5BDM8MR27IEszGJc9TmgtBqAFR4/B4fQdzomKuOsps@p9078X "Python 2 (PyPy) – Try It Online")
[Answer]
## Haskell, ~~48~~ ~~46~~ 43 bytes
```
f 2=1
f n=until((<1).mod n)pred(n-1)+f(n-1)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P03ByNaQK00hz7Y0ryQzR0PDxlBTLzc/RSFPs6AoNUUjT9dQUzsNTP3PTczMU7BVKCjKzCtRUFHITSxQSFOINtIx0THTsdAxNNUxNtcxNDAAYYPY/wA "Haskell – Try It Online")
Edit: @rogaos saved two bytes. Thanks!
Edit II: ... and @xnor another 3 bytes.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~8+2=10~~ ~~8~~ 6 bytes
```
òâ1 xo
```
[Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=8uIxIHhv&input=MTAw)
* 1 byte saved thanks to ETHproductions.
---
## Explanation
```
:Implicit input of integer U.
ò :Generate an array of integers from 1 to U, inclusive
â :Get the divisors of each number,
1 : excluding itself.
x :Sum the main array
o :by popping the last element from each sub-array.
:Implicit output of result
```
[Answer]
# MATL, 12 bytes
```
q:Q"@Z\l_)vs
```
Try it at [MATL Online](https://matl.io/?code=q%3AQ%22%40Z%5Cl_%29vs&inputs=37&version=20.1.1)
**Explanation**
```
% Implicitly grab input (N)
q % Subtract one
: % Create an array [1...(N-1)]
Q % Add one to create [2...N]
" % For each element
@Z\ % Compute the divisors of this element (including itself)
l_) % Grab the next to last element (the largest that isn't itself)
v % Vertically concatenate the entire stack so far
s % Sum the result
```
[Answer]
# [PHP](https://php.net/), 56 bytes
```
for($i=1;$v||$argn>=$v=++$i;)$i%--$v?:$v=!$s+=$v;echo$s;
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwJVaVJRfFF@UWpBfVJKZl65R5xrv5x/i6eyqac2lkliUnmerZGhgYKBk/T8tv0hDJdPW0FqlrKYGLGVnq1Jmq62tkmmtqZKpqqurUmZvBRRRVCnWBspYpyZn5KsUW///DwA "PHP – Try It Online")
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), 72 bytes
```
f(A,B):-A=2,B=1;C is A-1,f(C,D),between(2,A,E),divmod(A,E,S,0),B is D+S.
```
[Try it online!](https://tio.run/##FcyxDkAwGEXhVzH2j1tpjcTQap/AYhatNEFFhccv9vOd44xrXHh6Qs6eKWhquOpq6E62fRFSobiEZz0MYXLX49zOaihYwhzuLc6fsRggCPrPTTlU/0kKITBS9QI "Prolog (SWI) – Try It Online")
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), 27 ~~39~~ bytes
```
?%\(W!:.U0IU(;u;p+qu.@Op\;;
```
[Try it online!](https://tio.run/##Sy5Nyqz4/99eNUYjXNFKL9TAM1TDutS6QLuwVM/BvyDG2vr/f0MDAwMA "Cubix – Try It Online")
Cubified
```
? % \
( W !
: . U
0 I U ( ; u ; p + q u .
@ O p \ ; ; . . . . . .
. . . . . . . . . . . .
. . .
. . .
. . .
```
[Watch It Run](https://ethproductions.github.io/cubix/?code=ICAgICAgPyAlIFwKICAgICAgKCBXICEKICAgICAgOiAuIFUKMCBJIFUgKCA7IHUgOyBwICsgcSB1IC4KQCBPIHAgXCA7IDsgLiAuIC4gLiAuIC4KLiAuIC4gLiAuIC4gLiAuIC4gLiAuIC4KICAgICAgLiAuIC4KICAgICAgLiAuIC4KICAgICAgLiAuIC4K&input=OAo=&speed=20)
* `0IU` Set up the stack with an accumulator, and the starting integer. U-turn into the outer loop
* `:(?` duplicate the current top of stack, decrement and test
* `\pO@` if zero loop around the cube to a mirror, grab the bottom of stack, output and halt
* `%\!` if positive, mod, relect and test.
+ `u;.W` if truthy, u-turn, remove mod result and lane change back into inner loop
+ `U;p+qu;;\(` if falsey, u-turn, remove mod result, bring accumulator to top, add current integer (top) divisor push to bottom and u-turn. Clean up the stack to have just accumulator and current integer, decrement the integer and enter the outer loop again.
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 74 72 bytes
```
n=>{int r=0,j;for(;n>1;n--)for(j=n;--j>0;)if(n%j<1){r+=j;j=0;}return r;}
```
[Try it online!](https://tio.run/##lY8/a8MwEMV3f4pbChKNEtn5jyIvhU4tFDp0NopcJJITSEqhGH921w52vXRQ33Do7vTjvVOBKed1B73UpQoB3rz79NU1GybNvQ4KsYpGwZczZ3itDBL6u5o/DXr/DlFfl883VCeDcQF9KaEGmXUoy6bvwEu@sKJ2nggsc4GM0aGxEgVjtuSCmprggz3ltPGP0goruWi9jjeP4EXbiewvyyeHwV308sObqF8MalKTglIBqxXkqcBmBDapwG4EDqnAYYq0TiXy7RQq@Yz1fkSK4phsw/kUbXfk/6BmbFvsZ7v2/mq7Hw "C# (.NET Core) – Try It Online")
* 2 bytes shaved thanks to Kevin Cruijssen.
[Answer]
# [Actually](https://github.com/Mego/Seriously), 12 bytes
```
u2x⌠÷R1@E⌡MΣ
```
[Try it online!](https://tio.run/##S0wuKU3Myan8/7/UqOJRz4LD24MMHVwf9Sz0Pbf4/39DAwMDAA "Actually – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~78 75 73~~ 71 bytes
Not even close to Leaky nun's python answer in byte count.
```
f=lambda z:sum(max(i for i in range(1,y)if 1>y%i)for y in range(2,z+1))
```
[Try it online!](https://tio.run/##RclLCoAgEADQq8wmmCEXWrug7mKUNZAfzCC9vNWq5eOFnHbv@lrNeGg7LxrKcF4Wrb6RwfgIDOwgaretqEQmNqCm3DB9l//rRGkVUQ2RXUKDSkr58gE "Python 3 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~69~~ ~~63~~ 59 bytes
4 bytes thanks to Dennis.
```
f=lambda n:n-1and max(j for j in range(1,n)if n%j<1)+f(n-1)
```
[Try it online!](https://tio.run/##Tc5bCoMwEAXQf1cxUAoJfZDEd2kXk1bTRswoMYW6ehulxg7Mz@HeYfrRvTqMJ236zjoYxiHyex5qZ@vH2w66w1Yb7YhgjNFJ3Vpp7pUEvOCJS6zAyA9pQHUWGtAIVuKzJvyIVCvAfXPl9KCIz9KptxodUURQCn52wKOVkpWSQNlKRaAiFONgPF3QN7drcf4zIcot6N@nSzkr2b/OPGsq8nL6Ag "Python 3 – Try It Online")
I set the recursion limit to 2000 for this to work for 1000.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 37 bytes
```
A⁰βF…·²N«A⟦⟧δF⮌…¹ι«¿¬﹪ικ⊞δκ»A⁺β⌈δβ»Iβ
```
[Try it online!](https://tio.run/##Nc69CoMwFAXg3afIeC9E0K5O0slBEdfSITFRgzEp@ZFC8dlTWtv1cL7DGRfmRst0SrX3ajZQUMKxyibrCDRm1NGrXQ7MzBIulDTmEUMXNy4dICJ5ZT92u1Mi/m6Qu3RewslKqr5VNRHobIDWiqgtKLp@4j76BQQlK1bHf6wWAjglLXuqLW4gEM9TR9Y7ZQJcmQ/AEauUyqJI@Z5yr98 "Charcoal – Try It Online")
Link is to the verbose version. It took me almost all day to figure out how could I solve a non-ASCII-art-related question in Charcoal, but finally I got it and I am very proud of me. :-D
Yes, I am sure this can be golfed a lot. I just translated my C# answer and I am sure things can be done differently in Charcoal. At least it solves the `1000` case in a couple of seconds...
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), ~~36~~ 30 bytes
```
n->sum(i=2,n,i/divisors(i)[2])
```
[Try it online!](https://tio.run/##HYxBCoMwEEWv8nGVwARjWqubeBHpQiiWgXYcEi309DHt5r/3Nl@XxO6pZUUs4qZ8vA3HQELcPvjDeUvZsJ3D3ZZF9fU1AjdBE8tetflFg9WItYQ5EK6EG2EkdD3hMlR6/x9fH04 "Pari/GP – Try It Online")
[Answer]
# [Python 2 (PyPy)](http://pypy.org/), 145 bytes
Because turning code-golf competitions into fastest-code competitions is fun, here is an O(*n*) algorithm that, on TIO, solves *n* = **5,000,000,000** in 30 seconds. ([Dennis’s sieve](https://codegolf.stackexchange.com/a/128176/39242) is O(*n* log *n*).)
```
import sympy
n=input()
def g(i,p,k,s):
while p*max(p,k)<=n:l=k*p;i+=1;p=sympy.sieve[i];s-=g(i,p,l,n/l*(n/l*k+k-2)/2)
return s
print~g(1,2,1,-n)
```
[Try it online!](https://tio.run/##NYy9DsIgFEZ3noIRWrCWxMXKkxgHE7G9gd7eAFVZfHX8i99whpOcj0qeFjSaCpVaYaYlZp7KTIWhBaQ1C8ku7spHAYqUV0nuGb9PEBynZj4/xFvKg8V9sL6hAVrbD2S/D5sE7uaOcBqStr8@KOxCIz7wrddGdkYyHl1eI/LEKALm5yh6ZVSvNMpad9v/Xg "Python 2 (PyPy) – Try It Online")
### How it works
We count the size of the set
*S* = {(*a*, *b*) | 2 ≤ *a* ≤ *n*, 2 ≤ *b* ≤ largest-proper-divisor(*a*)},
by rewriting it as the union, over all primes p ≤ √n, of
*S**p* = {(*p*⋅*d*, *b*) | 2 ≤ *d* ≤ *n*/*p*, 2 ≤ *b* ≤ *d*},
and using the [inclusion–exclusion principle](https://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle):
|*S*| = ∑ (−1)*m* − 1 |*S**p*1 ∩ ⋯ ∩ *S**p**m*| over *m* ≥ 1 and primes *p*1 < ⋯ < *p**m* ≤ √n,
where
*S**p*1 ∩ ⋯ ∩ *S**p**m* = {(*p*1⋯*p**m*⋅*e*, *b*) | 1 ≤ *e* ≤ *n*/(*p*1⋯*p**m*), 2 ≤ *b* ≤ *p*1⋯*p**m* − 1*e*},
|*S**p*1 ∩ ⋯ ∩ *S**p**m*| = ⌊*n*/(*p*1⋯*p**m*)⌋⋅(*p*1⋯*p**m* − 1⋅(⌊*n*/(*p*1⋯*p**m*)⌋ + 1) − 2)/2.
The sum has *C*⋅*n* nonzero terms, where *C* converges to some constant that’s probably 6⋅(1 − ln 2)/π2 ≈ 0.186544. The final result is then |*S*| + *n* − 1.
[Answer]
# [NewStack](https://github.com/LyamBoylan/NewStack/), 5 bytes
Luckily, there's actually a built in.
```
Nᵢ;qΣ
```
## The breakdown:
```
Nᵢ Add the first (user's input) natural numbers to the stack.
; Perform the highest factor operator on whole stack.
q Pop bottom of stack.
Σ Sum stack.
```
**In actual English:**
Let's run an example for an input of 8.
`Nᵢ`: Make list of natural numbers from 1 though 8: `1, 2, 3, 4, 5, 6, 7, 8`
`;`: Compute the greatest factors: `1, 1, 1, 2, 1, 3, 1, 4`
`q`. Remove the first element: `1, 1, 2, 1, 3, 1, 4`
`Σ` And take the sum: `1+1+2+1+3+1+4` = `13`
[Answer]
# Java 8, ~~78~~ ~~74~~ 72 bytes
```
n->{int r=0,j;for(;n>1;n--)for(j=n;j-->1;)if(n%j<1){r+=j;j=0;}return r;}
```
[Port of *@CarlosAlejo*'s C# answer.](https://codegolf.stackexchange.com/a/128169/52210)
[Try it here.](https://tio.run/##hY7BasMwEETv@Yq9FCRaGTtN2sBG@YPkkmPpQVXkItVZG1kOBKNvd@Qk1yJYLey8YTROXZRoO0Pu9DfpRvU97JWlcQFgKRhfK23gMJ93ATSbN3FMSkwvTR9UsBoOQCBhIrEbZ4uX5ZvDuvUMaVchCcHnw0lCJ0RSuK0ZvbhtxUf/Kh06WWL0JgyewGOc8JHeDT9NSn9@cmntCc6pIDsGb@n36xsUf7Q7XvtgzkU7hKJLKDTEqNBsye9d/@WrDP/I8E2GV@uM4f0zl1CWecfTEhdxugE)
**Old answer (78 bytes):**
```
n->{int r=0,i=1,j,k;for(;++i<=n;r+=k)for(j=1,k=1;++j<i;k=i%j<1?j:k);return r;}
```
[Try it here.](https://tio.run/##hY7NasMwEITveYq9FCTsGLs/Sams9gmaS46lB0VRwkrO2shyoAQ/uysnuQbBakHzDTtj1Vkt286Q3btJN6rv4VshXRYASMH4g9IGNvP3KoBm8yYuojLGF6cPKqCGDRBImGj5eZktXpY5yiq3uROH1jORZVhLEj6Tjs@CjdDJKuq2RuEkPtm6@rIfjgtvwuAJvBgnccvohl0TM@5R5xb3cIo12TZ4pOPPLyh@67j964M5Fe0Qii6i0BCjQrNnfm38kL8m@CrB3xO8eksYXtapC2WZdtwt42Kc/gE)
**Explanation (of old answer):**
```
n->{ // Method with integer parameter and integer return-type
int r=0, // Result-integers
i=1,j,k; // Some temp integers
for(;++i<=n; // Loop (1) from 2 to `n` (inclusive)
r+=k) // And add `k` to the result after every iteration
for(j=1,k=1;++j<i; // Inner loop (2) from `2` to `i` (exclusive)
k=i%j<1?j:k // If `i` is dividable by `j`, replace `k` with `j`
); // End of inner loop (2)
// End of loop (2) (implicit / single-line body)
return r; // Return result-integer
} // End of method
```
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2) `-S`, 5 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
ı⁺FṫG
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDNCVCMSVFMiU4MSVCQUYlRTElQjklQUJHJmZvb3Rlcj0maW5wdXQ9NiZmbGFncz0tU2U=)
#### Explanation
```
ı⁺FṫG # Implicit input
# Decrement the input
ı # Map over [1..input-1]:
⁺ # Increment the number
Fṫ # Push the proper divisors
G # Maximum of this list
# Sum the list
# Implicit output
```
[Answer]
# [Arturo](https://arturo-lang.io), 32 bytes
```
$=>[∑map..2&=>[x:do factors&]]
```
[Try it!](http://arturo-lang.io/playground?B7ePFw)
[Answer]
# [Lua](https://www.lua.org), 74 bytes
```
c=0 for i=2,...do for j=1,i-1 do t=i%j<1 and j or t end c=c+t end print(c)
```
[Try it online!](https://tio.run/##JcnRCoAgDEDRX9lLUGSy9dw@RmbBJDTEvn9Jvt3Dvd9gJoxwlQrKu/Pex/IrMTndCDob65QOgpAjJOivwdlTWNZRT9XcZlnMjBDxAw "Lua – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 18 bytes
```
[:+/1}.&.q:@+}.@i.
```
[Try it online!](https://tio.run/##y/r/P83WKtpKW9@wVk9Nr9DKQbtWzyFT739qcka@QpqCoYGBwX8A "J – Try It Online")
] |
[Question]
[
>
> This is the cops' thread to a [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge. Click the link to find the [robbers' thread](https://codegolf.stackexchange.com/questions/242076/output-two-numbers-robbers-thread).
>
>
>
The challenge here is very simple. Create two programs of the same size, in the same language, which output (using 1 standard output method) two different natural numbers, \$x\$ and \$y\$. Submit both programs, both numbers and the language used in an answer on this thread.
Robbers will then attempt to find a program in the same language which outputs a number in between \$x\$ and \$y\$, and is the same length as or shorter than your programs. If they do, they will post it to the [robbers' thread](https://codegolf.stackexchange.com/questions/242076/output-two-numbers-robbers-thread), and it is "cracked".
For example If I post:
>
> # Haskell, \$9-7 = 2\$, 12 bytes
>
>
>
> ```
> main=print 7
>
> ```
>
>
> ```
> main=print 9
>
> ```
>
>
Then robbers must find a program that prints `8` in 12 bytes or fewer.
Unlike many challenges in cop's do not need to have an answer in mind when posting. It is perfectly valid to post an answer which *cannot* be cracked at all. In fact that is incentivized. However the scoring means that the better you score the harder it will be to prevent a crack.
## Scoring
Your score will be the difference between \$x\$ and \$y\$. So in the example answer it was \$2\$. Higher score is better. If your answer is cracked it's score is automatically set to 0.
Since there is no hidden information that needs to be revealed, answers will not be marked as safe. You get your score as soon as you post the answer and it will remain your score until someone cracks it.
[Answer]
# [Zsh](https://www.zsh.org/), 1 byte, score 124, provably uncrackable
Programs output via exit code.
```
/
```
Outputs 126 ("permission denied"). [Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhYL9SE0lAsTBgA)
```
[
```
Outputs 2 ("invalid argument"). [Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhYLoyE0lAsTBgA)
Here is a script which tests all 256 possible 1-byte programs, which you can use to verify that this is uncrackable (and unbeatable for 1-byters):
```
{ for c ({0..255}) ( zsh -c ${(#)c} &>/dev/null; echo $? ) } | sort -n
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhY33aoV0vKLFJIVNKoN9PSMTE1rNRU0FIAqFHSTFVSqNZQ1k2sV1Oz0U1LL9PNKc3KsFVKTM_IVVOwVNBVqFWoUivOLShR08yCmQQ2FGQ4A)
The empty program exits with 0.
[Answer]
# Malbolge, 7 bytes. Score: 3 - 1 = 2. [Cracked](https://codegolf.stackexchange.com/a/242197/61379).
```
D'<;_L"
```
Outputs 3.
```
(&a%M"o
```
Outputs 1.
[Answer]
# [R](https://www.r-project.org/), 5 bytes, score: 10^307
```
1e308
```
[Try it online!](https://tio.run/##K/r/3zDV2MDi/38A "R – Try It Online")
```
9e307
```
[Try it online!](https://tio.run/##K/r/3zLV2MD8/38A "R – Try It Online")
`2e308` overflows [R](https://www.r-project.org/)'s numeric type, and outputs `Inf`, so I suppose that `1e308` is the highest number that we can output using 5 bytes.
---
# [R](https://www.r-project.org/), 4 bytes, score: 9 x 10^98, [cracked, almost instantly](https://codegolf.stackexchange.com/a/242084/95126)
```
1e99
```
[Try it online!](https://tio.run/##K/r/3zDV0vL/fwA "R – Try It Online")
```
1e98
```
[Try it online!](https://tio.run/##K/r/3zDV0uL/fwA "R – Try It Online")
Note after crack: Well, that was pretty stupid of me.
[Answer]
# C, 24 bytes, score 33482810471
Output format is *decimal*.
```
main(){printf("%o",~9);}
```
Outputs 37777777766. [Try it online!](https://tio.run/##S9ZNT07@/z83MTNPQ7O6oCgzryRNQ0k1X0mnzlLTuvb/fwA "C (gcc) – Try It Online")
```
main(){printf("%u",-1);}
```
Outputs 4294967295. [Try it online!](https://tio.run/##S9ZNT07@/z83MTNPQ7O6oCgzryRNQ0m1VElH11DTuvb/fwA "C (gcc) – Try It Online")
Uncrackable?
[Answer]
# Excel, 10 bytes, score (145!)-(144!) 0 [Cracked!](https://codegolf.stackexchange.com/a/242152/103471)
I'm interested to see how this can be cracked.
```
=FACT(145)
```
Outputs 8.04792605747199E+251 (actually prints every digit when in "Number" format and a very wide column/merged columns, the most I could get it to print before they became ##### or #NUM!
```
=FACT(144)
```
Outputs 5.55029383273931E+249 (again, actually prints every digit [although it does turn most to 0's])
But... if you think it's okay if I can use un-printable numbers (likely not)
# Excel, 10 bytes, score (999999999!)-(999999998!)
```
=FACT(999999999)
```
Output is approximately 1e8448735636
```
=FACT(999999998)
```
Output is approximately (1e8448735636)/999999999
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 2 bytes, score: 1000 - 99 = 901
```
Iφ
```
Outputs 1000. [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEw9DAwEBT0/r///@6ZTkA "Charcoal – Try It Online") Link is to verbose version of code.
```
99
```
Outputs 99. [Try it online!](https://tio.run/##S85ILErOT8z5/9/S8v9/AA "Charcoal – Try It Online")
[Answer]
# Jelly, \$1000 - 256 = 744\$, 1 byte
This is provably uncrackable. Our programs are
```
ȷ
```
[Try it online!](https://tio.run/##y0rNyan8///E9v//AQ "Jelly – Try It Online")
and
```
⁹
```
[Try it online!](https://tio.run/##y0rNyan8//9R487//wE "Jelly – Try It Online")
These are the following one byte programs in Jelly that output a number:
```
¤¥¬®µ½×ðȷ !$&*+-.0123456789<=>ACEHLNOPSX^_aceghinoquvw|~°¹²³⁴⁵⁹⁻⁼ẠḄḌẸḤỊṂṆẒȦḂĊḞḢṀṠṪạḅḍịḳḷṇṛ§ẉỵẓȧċḋėġṅȯẇẏ«»‘’
```
[Try it online!](https://tio.run/##AdoAJf9qZWxsef//VuKCrP///yLCpMKlwqzCrsK1wr3Dl8OwyLcgISQmKistLjAxMjM0NTY3ODk8PT5BQ0VITE5PUFNYXl9hY2VnaGlub3F1dnd8fsKwwrnCsuKBtOKBteKBueKBu@KBvOG6oOG4hOG4jOG6uOG4pOG7iuG5guG5huG6ksim4biCxIrhuJ7huKLhuYDhuaDhuarhuqHhuIXhuI3hu4vhuLPhuLfhuYfhuZvCp@G6ieG7teG6k8inxIvhuIvEl8Sh4bmFyK/huofhuo/Cq8K74oCY4oCZIg "Jelly – Try It Online")
The two largest outputs are \$1000\$ with `ȷ`, then \$256\$ with `⁹`. Nothing else outputs something in between, and the empty program outputs `0`.
[Answer]
# [Vyxal 2.8.1, online edition](https://github.com/Vyxal/Vyxal), Score: \$no\$, 102 bytes - [cracked](https://codegolf.stackexchange.com/a/242091/103772)
Our two programs are:
```
kḭkḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(↵
```
which is equivalent to:
```
stack.append(4294967296)
for i in range(4294967296):
for j in range(4294967296):
for l in range(4294967296):
...
stack.append(10 ** stack.pop())
```
and
```
k×k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(↵
```
```
stack.append(2147483648)
for i in range(2147483648):
for j in range(2147483648):
for l in range(2147483648):
...
stack.append(10 ** stack.pop())
```
These both output really big numbers, which I need to calculate. Online edition here means that it should be able to work on the online version of the interpreter if given enough resources and time.
[Answer]
## Seed 4791 bytes, 9^9^9^9^9^9^9^9^9^9^9 - 9^999
9^999:
```
36 94981479280208146944953816764699944095961978453221682715159791056688140996853888504437229889191975183564015323273899198344481103250895668467924054339223701930305051118652741561583994582158440585564368286547479926974178096702473601294217332487135194413906552257837173590043556058790275467394479137424662603752651645938216669070115921033298764330851330467996807939281657656425699237251690473743679487474871854542411596819130830481224340562767172942708101325192086341055751991333028615416686839981817142945819118242545846019740984523396598771709676467792891959285529685021033906795910583508008242630927336057598688291102981549916746769870319488733952651891371543582899041173842586806720961829689851873808965388202504531747804845840143327859796447099370149069303515672221742322125494895020945918848068614407697751238250677431155329740069260038983064746127731524766636439066019193467422893766041808161143968190057861269526918372578995949004970306694838999565427329694454909226376047136625534400886807619996259128667499478409012349612038652572951348047086088817551011308002652053644287503036935028935844715426527836055671911027719964392826069078969082698559771882396772799751373195780148811909716528980696256380945795001274573193459618177342958415946401666965464920052072906030975414694315792619540688825293711591412127002343225335880571865520167604325308977304908296745198902342257861540933487039862994356564924690417285711172056255742252487361407255067571158083586073346420212617420441279183030666063290178409730490381049078147916881460523911120507498436875929418470544681759185903900133455626013012351989728905311148323498044351461599265083429729804099930581137436822766380518345367947616841345549577232164529955502684122270790499052240935152809235771171370434070236688989688479953925955276348719434668321141480227864703028324596206817015011573827251621510788266231733052888294086085254666969188534237535939663347385652634046245668458458194635071661213214973469115822380087405654270393830651870914063112038485264582625501640551679797243637993058707669484199371425261416836151503596151478053438581656553121438841132537636618059562148278640553730409617733965555456279846109188629372980642417837804453861796471345795684171211276475918979481722058104857844758843603165344900677433585454487342231624372104550191735735796454388857238022368193594741972999621272782164771208619698294562775042889372442244124800173695001811951104483064798795939319310120564380578007164764614616015236574253569882284714066981102630472310220979239145467130016229967089894017391315803929147667149546926923076190028432304251122963960242247834461462078725734648747107996037476017483441942628448413731020112504750795380529669192191584807395775799602140589910229189049503739591898879818034929487479963008540786045617483659914745637538236332799035903698998398005069763801222822678189343269224348393728495631906613048781189537304930344768279627715649280517720235827779507044205103495831324708746293837927334289124220386247007983741488271118125085904363197981352562772119852399632426650691964453022658894369910133959424146640109164371294689079802777902307296880648093189854866622499839863241317182736088299334215289137396403643588453171937501380801955934324623689028726948232299713278675563351730787914169555473591390989160245212337001718142110638979369841824007070047204941161283902352728852331043554053279968108315668988738506810443190205259224591564532510273789237748335782790807545071073495745130501275790665780813262239133252704358246589268608658852890888957950256512957031746836236764704856568474359369600518287601870385217873471559723711460790851490641852774919778389159824024349093647531524452566965015853360104186115940302479291089022327363165427092882556283691659718308627299377279772911302647604701234001616842762253575818861145567617316017544857744939000573784180397907315361706557618352235994622697878150716754864959319585660748889125094235883962411794008488384621978956654775262754623280713877112553348864910614097062301093879722439179562871939066598227413212667524976059454125001698534620701802564422768614905506319489756942407153064671390062115508534001167416000467035978170537796335329422124742348973353594178675864912238921028339003101191208960656005489477745423235808264714405884454620918978113027106595440238470298437388674769792190539877475662105937286759309442118449241650440411271188409657695505912558859008915175033843314270463991607598704331221534023888995395090620691204768
```
This generates the following befunge programs:
```
"cb 0=HTGNEL_ENIL_CB|'999^9' ohce"=@
```
Thanks to [@null](https://codegolf.stackexchange.com/users/87986/null) for reminding me I know how to program Seed.
The second program becomes:
```
53 309587622060800553797768779768494911841628261184767731489332912878541825672886566188681588715091427880831872903145865614752063676670384244697938284581157766493625127486069966517483807267622940281840537784840565165614923074081025668091978619573378790644656852906050466371773524417205893183522285682501264293869247195711547240624794051171506566110127196684091043263704047601080904572252690239932534180485242573593166277713560062201443018547580753558753076249237708886730792578837512812594738578149293808173180907025198002544953022811343070481719591552371661589667292782400655709462087966594005437890287977681252692413309430402819975448488893242566687723971049600796250960915479240241523929324115544908597729425622791811471173026530746268048270787941195246863033941763322474063945991208609412842541131320624405655371178829432647519162966803019160693234110850310536828203057708491223327429158504206916042083919635627816797751112595799425150793221319690691484648035817244488524453691950153293122568235889159354407000681042368350613187209832365401659548342971503410960096851577419002008732886164772578445903853439006453593714967313295474365940623318333595448104799161502690614815839414921869269173019141656145770493252423864457874164529445010976172453560422794168628767033007798464857807868972770119452458362389906963282436285266581231736927418149622919396524509045600877152139736196549699718010709692427212834211798096407951361607408561365539352799316609116886495092220026475056054004109655559238156190632938794875725763241934373532462961173950124119350519950416535961630182879968505149425984423718446515752555953370146281257558975704887791656829772389610358616172108023688683194195646087461491617635517077426354405251289450350884001525808934031920441467238068082960111819700136750591936811451950869796830795917902563838207457238199783664676631034747422610392737824936385217739329722785171995265543924626358418544733893242621181268907981435590946535967453087735571432009511302485790035630081692234070829135516653019636470143030262426164209059107313322273527988454852167740639604116654661106183147469766915633812512660623654733210776980513357988371975078629660700128024350111565369418799322994425194707442766131638194451296869655903560930552909726193906116203105280133098173487874636694252312563326834465786203019871459621428412218125660006856353034700431931551987177749720765277804188429325209144778878250052168648774014287051224303669581052487796035601212899803091980714662821531796312403019296375399485542097354585848372838776512451340890861805997089465652085241774190551963641174852103085029950949878525880282522636862689978529309241328139079974474498840789713396190657697469158669210302848644464901861283874879947038142675120700972350655160123482902871840054575564022314230414143498863246180321421107093159843511652846289238887904021891711361912352395752690348787554827002831376719081050720410310253594459120692911078678989959842508193061754966247315287630553272097166145570047781427011192833631466194493500860462029105164607250519256275264184570393514673731241768380866974597977047998254748735616785609554132052392767706860844358763762550597658505611387104158401413665230304581335849536972107107380977005367190725149287488469722296267278310609063864272116083546208401737358229303260037829564529791746229429584305623876048177048606434240808955564817647762135226292996457376569825840317487337230342808888439404782377044367241171285682843079144996791352785027653912966489528982369346460394462814510925432325649339476445012957862795528485420766725202232921562144249478994398630291247115812027459339439917745701011664764129641934911394405527525162982448137755434800132266423495736646406665020110921399145992639873000772187319349501446035997970338236156282496731462537470287250998341901639931110985832053143995593295587994998629729807528492791923904555457866017778430904246471024077597359827409642434169201834219584106992783524218181235229797375275600542981388826320938305229269139948945723602080721878638825973118853705899013952011812734028557886010265443351247058659869796789367980202658727913440606028570394873456111539589719778807886159735916680268655045949064003143304502567591948483646514438384066523522818325855415617165015245093826574834982063177898711249371505888565014662311628585433493237461213627490980308832056414074306954654643982609793175536357731519819711214704220198179035754939835716988611721494310455897591499137450735143359976295914194929864424760941191508944873123510109598842071064171881097121958831073339652141908077795821260390971306588642697066016462777462135092080108211612548519054989094919411477432604519350786361891036501628076178403464320215611778222267688190891672404404679274514697484921192422288645990934995323948756777118204678605373179302677235930726235223857
```
The first one can be padded with spaces to it's length. It expands to the following:
```
"cb 0=HTGNEL_ENIL_CB|'9^9^9^9^9^9^9^9^9^9^9' ohce"=@
```
The score:
\$10^{10^{10^{10^{10^{10^{10^{10^{10^{8.567841344463465}}}}}}}}}\$
[Answer]
# Brainf\*ck, 25 bytes. Score = 7 - 4 = 3, [cracked by Fmbalbuena](https://codegolf.stackexchange.com/a/242093/96037)
```
>>+++++[<+++++++++++>-]<.
```
[^ Outputs 7](https://tio.run/##SypKzMxLK03O/v/fzk4bBKJttBHATjfWRu//fwA)
```
>++++[<+++++++++++++>-]<.
```
[^ Outputs 4](https://tio.run/##SypKzMxLK03O/v/fThsIom20kYGdbqyN3v//AA)
I just learned Brainf\*\*\*, I think it's going to be an easy crack.
[Answer]
# [Zsh](https://www.zsh.org/), 13 bytes, score \$ \approx 10^{(21 \times 10^6)} \$
```
tr<=go -c 9 9
```
Outputs 13061918 `9`s. [Try it online!](https://tio.run/##qyrO@P@/pMjGNj1fQTdZwVLB8v9/AA "Zsh – Try It Online")
```
tr<=z3 -c 1 1
```
Outputs 21366224 `1`s. [Try it online!](https://tio.run/##qyrO@P@/pMjGtspYQTdZwVDB8P9/AA "Zsh – Try It Online")
Exact score:
$$ \frac{10^{21366225} - 1}9 - 10^{13061919} + 1 $$
---
## Explanation
* `<=go`: load the program `go`, as a file
* `tr -c 9 9`: replace all characters except `9`, with `9`s
The other program is similar.
[`z3`](https://github.com/Z3Prover/z3) and [`go`](https://go.dev) are the largest 2-character programs available on TIO, at about 22MB and 14MB respectively. We can use them as an easy source of very long "strings", and by converting all the bytes to digits, very large numbers.
I used TIO instead of ATO because it has much bigger binaries available, and also because ATO is too frequently updated, changing the binaries, so the score would change over time.
I'm not intending for this to be cracked, but I haven't tried very hard to ensure there aren't any cracks.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes, score = 61803398875 - 14159265359 = 47644133516
```
φṫb₂ị
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//3zbw52rkx41NT3c3f3///8oAA "Brachylog – Try It Online")
```
πṫb₂ị
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//3zDw52rkx41NT3c3f3///8oAA "Brachylog – Try It Online")
### Explanation
Not sure this is crackable:
```
φ Take Phi = 1.61803398875
π Or Pi = 3.14159265359
ṫ Convert to string
b₂ Remove the first digit and the decimal separator
ị Convert back to integer
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 1 [byte](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py), score 100000000-10000000=90000000
100,000,000: `↕`
10,000,000: `◄`
[Try it online.](https://tio.run/##y00syUjPz0n7//9R21SFR9Nb/v8HAA)
I would be surprised if this is crackable..
[Answer]
# [Python 3](https://docs.python.org/3/), 63 bytes, score \$2\rightarrow12\rightarrow(9^{99}-1)-2\rightarrow11\rightarrow(9^{99}-1)\$
Program 1:
```
A=lambda m,n:m and A(m-1,n<1or A(m,n-1))or-~n
print(A(9**99,8))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/39E2JzE3KSVRIVcnzypXITEvRcFRI1fXUCfPxjC/CMTWydM11NTML9Kty@MqKMrMK9Fw1LDU0rK01LHQ1Pz/HwA "Python 3 – Try It Online")
Program 2:
```
A=lambda m,n:m and A(m-1,n<1or A(m,n-1))or-~n
print(A(9**99,9))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/39E2JzE3KSVRIVcnzypXITEvRcFRI1fXUCfPxjC/CMTWydM11NTML9Kty@MqKMrMK9Fw1LDU0rK01LHU1Pz/HwA "Python 3 – Try It Online")
This just calculates the difference between two nearby invocations of the Ackermann function.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 22 bytes, Score=\$\frac 19\times 10^{10000000}-\frac 19\$, [cracked](https://codegolf.stackexchange.com/a/242097/)
```
x=>'8'.repeat(9999999)
x=>'9'.repeat(9999999)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f@/wtZO3UJdryi1IDWxRMMSAjT///@vW5YDAA "JavaScript (Node.js) – Try It Online")
# [brainfuck](https://github.com/TryItOnline/brainfuck), 19 bytes, Score=\$3\times 10^{254}\$, unlikely crackable
```
+[+++++>+<]+[>.<+]
+[+++++>+<]++[>.<+]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fO1obBOy0bWK1o@30bLRj////r1uWAwA "brainfuck – Try It Online")
[Answer]
# [Lexurgy](https://www.lexurgy.com/sc), score \$11111111111111111\$, 121 bytes
Both programs use the following method:
1. Output a string of 26 digits
2. Make 16 copies of those digits and append them to the end.
### Program 1:
Outputs `9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999988888888888888888` (425 `9`s then 17 `8`s).
```
a:
*=>\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\8
b:
[]$1=>$1 $1 $1 $1 $1 $1 $1 $1 $1 $1 $1 $1 $1 $1 $1 $1 $1
```
### Program 2:
Outputs
`9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999` (442 `9`s).
```
a:
*=>\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9
b:
[]$1=>$1 $1 $1 $1 $1 $1 $1 $1 $1 $1 $1 $1 $1 $1 $1 $1 $1
```
## Minimal answer: score \$9-8=1\$, 8 bytes
```
# program 1
a:
*=>\8
# program 2
a:
*=>\9
```
[Answer]
# [!@#$%^&\*()\_+](https://github.com/ConorOBrien-Foxx/ecndpcaalrlp), 6 bytes, score: 1001001, [Cracked](https://codegolf.stackexchange.com/a/242232/106959) by emanresu
```
(#)
```
The first three bytes are char code 127.
[Try it online!](https://tio.run/##S03OSylITkzMKcop@P@/vr5eQ1nz/38A "!@#$%^&*()_+ – Try It Online")
```
~~~(#)
```
[Try it online!](https://tio.run/##S03OSylITkzMKcop@P@/rq5OQ1nz/38A "!@#$%^&*()_+ – Try It Online")
>
> You can't see the solution, But this is easy
>
>
>
[Answer]
# [MATLAB](https://www.gnu.org/software/octave/), 1.797693e+308 - 1.797047e+308 = 6.463132e+304, 7 bytes
```
realmax
```
outputs 1.797693e308
```
5175^83
```
outputs 1.797047e+308
[Try it online!](https://tio.run/##y08uSSxL/f@/KDUxJzexgovL1NDcNM7C@P9/AA "Octave – Try It Online")
[Answer]
# Python3, 41 bytes, score=\$2.82×10^{456573}-2.82×10^{446573}\$, [Cracked](https://codegolf.stackexchange.com/questions/242076/output-two-numbers-robbers-thread/242222#242222)
```
import math
print(math.factorial(100000))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PzO3IL@oRCE3sSSDq6AoM69EA8TUS0tMLskvykzM0TA0AAFNzf//AQ)
```
import math
print(math.factorial(99999))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PzO3IL@oRCE3sSSDq6AoM69EA8TUS0tMLskvykzM0bAEAU3N//8B)
This is embarrassing i forgot that you can just do 3\*10\*\*456573
[Answer]
## PHP4, score ≈ 0.011 × 10^1000
**Program 1** (23 chars) output `999` times `9` :
```
echo str_repeat(9,999);
```
**Program 2** (23 chars) output `999` times `8` :
```
echo str_repeat(8,999);
```
Output of both PHP4 scripts is a 999 digits integer in decimal form.
```
var_dump(chop($out_1, '0..9') === ''); // bool(true)
var_dump(chop($out_2, '0..9') === ''); // bool(true)
```
*[BC Math](https://www.php.net/manual/en/bc.installation.php) is only available if PHP was configured with `--enable-bcmath`, by default there is not.*
] |
[Question]
[
Recently, someone proposed more stringent limits for Python's default line length:
>
> Clearly, no program should ever use more than 80 characters per line, for a whole host of reasons. First and foremost, for readability and maintainability, it is important to have a solid standard, so we can adjust the width of our text editors appropriately. As a secondary benefit, code can easily be transferred onto media that may have restrictions, and where adding line-breaks can be distracting, like print pages for review in a meeting, or punch cards.
>
>
> But is 80 characters too high? Some suggest 79, or even as low as 75, to allow for an 80 character wide terminal to fit the code with a few columns devoted to line numbers. Clearly, ultimately, lower is better, as lower limits allow for the code to be used in more situations without reformatting.
>
>
> **[Introducing the max6 standard](https://github.com/petersn/six-char-max)**
>
>
>
Your goal is to find and demonstrate the minimum line length required by Your Favorite Language by writing a FizzBuzz variant with the fewest number of characters in any line.
# Input
An integer, *n*, via any desired method.
# Output
Print the numbers from 1 to *n*, (*n* ≥ 1, *n* ∈ ℤ) separated by line breaks, except:
* for multiples of 3 print "Apple"
* for multiples of 5 print "Pie"
* for multiples of both 3 and 5 print "ApplePie"
# Scoring
The maximum line length in bytes, not including the line break (Cr, CrLf, Lf, or other system standard break, specify, as desired), and the total code length in bytes as a tiebreaker.
# Rules
All line breaks must be meaningful. Line breaks that can be removed and adjacent lines directly concatenated without an impact on the output, *must* be removed.
[Answer]
## [><>](https://esolangs.org/wiki/Fish), 1 byte per line, ~~243~~ ~~161~~ 135 bytes
*-26 bytes thanks to Jo King!*
2D languages FTW! Although writing loops and branches using goto instructions instead of the 2D structure is not fun.
```
v
l
:
:
3
%
:
&
0
4
7
*
&
?
.
~
~
"
e
l
p
p
A
"
o
o
o
o
o
$
5
%
:
&
0
a
5
*
&
?
.
~
~
"
e
i
P
"
o
o
o
*
0
@
?
n
?
~
l
{
:
}
=
?
;
a
o
1
```
[Try it online!](https://tio.run/##S8sszvj/v4wrh8sKCI25VIGkGpcBlwmXOZcWkGXPpcdVB4RKXKlANQVA6Ahk58OhCpcpXE8ikI2uJ5MrAK5eC6jGASibB8R1QNOqgfpquWyBPGug3nwuw////@uWGRsAAA "><> – Try It Online"), or watch it at the [fish playground](https://fishlanguage.com/playground)!
The fish swims downward along the code, using conditional gotos to skip things depending on what divides the accumulator.
I believe this meets the spec: whatever newlines are removed, the fish always hits the initial `v` (the only direction-changing instruction present), so the fish always swims downwards in the first column. Thus deleting a newline has the effect of simply removing the next character from the fish's path, and I don't think you can remove any of the characters without changing the output.
[Answer]
# [Haskell](https://www.haskell.org/), 3 bytes/line, ~~494 471 470 463 453 450~~ 461 bytes
EDIT:
* -26 bytes: Removed some redundant linebreaks and their associated comment markers, and changed `-1+x` into `x-1`.
* +3 bytes: Oops, needed extra `--` line after `x-`.
* -1 byte: In `f` use `c 47:[]` instead of `[c 47&0]`.
* -7 bytes: Move newline handling to `w`.
* -10 bytes: Inline `a="Apple"` and `p="Pie"` in `#` and use a dummy recursion for the 15 case.
* -3 bytes: Inline `w` in `f`. Remove redundant `--` between `x` and `15`.
* +11 bytes: Oops again! My string gap theory had a hole. Fixed by introducing `%` function. Finally made some automated testing to make sure there were no more surprises.
`f` takes an `Int` and returns a `String`.
```
{;f
n=
--
[--
1..
--
n--
]--
>>=
\
--
x->
--
gcd
x
15#
--
x++
--
c
47:
--
[--
]--
;1#
--
x=
--
n!!
--
(x-
--
1--
)--
;3#
--
_=
--
"A\
\p\
\p\
\l\
\e\
\"&
--
0--
;5#
--
_=
--
"P\
\i\
\e\
\"&
--
0--
;--
15#
--
_=
--
3#
--
0++
--
5#
--
0--
;n=
--
d++
--
[--
s++
--
t|
--
s<-
--
n--
,--
t<-
--
[c
9]:
--
d--
]--
;d=
--
(:
--
[--
]--
)--
<$>
--
[c
8..
--
c
0--
]--
;c
x=
--
[--
"9\
\"%
--
0--
,--
"8\
\"%
--
0..
--
]!!
--
x--
;--
[--
a]%
--
_=
--
a--
;x&
--
y=
--
x}
```
[Try it online!](https://tio.run/##ZVDRTsMwDHzPV7CyoaGRqhGb2NhaiT/gfa1QlGZbRYlQW4kg4NtLzm61IR4uTuw7x@eTbl9tXfdvunJp5TrbaNNND3FjdXn1cbKN7b@2B@FSIaXYB6g4xtUFFAFZloocCS8zhKMphRdqdU25xQLBiOXD46iHaKu4TE3dZIIw9xJBBdyCck@UF6JET7nI3wfUATYgukEpAXd1yX0Oteo/B70vedw/4Qm5QDx2WnIeA7d87b5xtjs5ur9Dkp97IzYFOSxHhyW1mf@xDV@7aTYo1rxIQ9@SxgwbAT/aYPzZOBY@i9bnFGsLXp0f/EGni9nZo0bB0w4@KeF/@l4lyS8 "Haskell – Try It Online")
[Test source restrictions!](https://tio.run/##ZVRtT9swEP7uX3EYmBIlqdptaBBopW7qEFILaLDxIY2qkLiNheNUsbMGDX4780vS8hLpaufuucfPnS/NE/FAGHt5@Rfsw3R8ef57fD6BWc0kvUseL5awHzwjWqzLSsLNo5Ck6F1XZUqEQKhIKIchZCUC9aynlBMBZwEwuzkYwYrIHyWXhEthMbW8kdWUwwHgWdLAhmYyDwGD54HIyw04RdLQoi4UoEjWwAhfybyldg1FqU@QREglY9VGTEDhZwtw5g73C4uHYNSJM4CrN6nFLvW9tEuy0TXA/k4Y1zu63ML18wS8ZqwlUu/qOAx5IuCeEA6kSVmdkQyymoAsgfIlK8t1D7/jULKGQ1WWfQwHFfBrMrv6M/4@nXzAlzIn1YYK8gbPSwkVKcq/yT0j2xwXerovzlI3My15mkhXt5ZUK6V40LUPtY4whAsuNWekekH5KjZ7Rzn9qHPFbtzhOTgsLMLKHYLqeuQwzyvcsHpSYiaMFA7zC1eVPVVli9heX7jV42hjoeu66tYtn8O9gX5TjG53xgIqNWNRjFDHNIwcHATYx5nnYSUGba9U7KZxU1FJflJGAN/2coFV1TW3g2nv3Fn40l@4eiQqkmTtUN9RmU8aqqY2I9u@41WeYohwQLAP2A4KODJ5IDDo9xXzEj73XR27xTFg2/yKyLriIJH6tE6XiA9REKBI2aDX01uuLFY2Gg3RXDuaYKSXVZqhBg2O9o3P8/SSoq/fwi5fJ50ObNiQ8r09vThNoJeBMldDvhjIwkDweI7m69aYMqIMf9KhvsYevcZeqxj9iNHcr3GWv28V2oDB2Uoz69eChd3KJ/0rzoKuel877WuUopPYVJh1FWaGxnlTtq5L/a20Gce2kak51uSkbUc0Hp9o@YedLH0YPt65bG5sW9e09em8JD7c1ZjoQGN68GgczfN/ "Haskell – Try It Online") (Line 70 is excluded from the testing because removing its newline causes an infinite loop without output.)
Version with the most important squeezing tricks removed:
```
{;f n=[1..n]>>= \x->gcd x 15#x++c 47:[]
;1#x=n!!(x-1)
;3#_="Apple"
;5#_="Pie"
;15#_=3#0++5#0
;n=d++[s++t|s<-n,t<-[c 9]:d]
;d=(:[])<$>[c 8..c 0]
;c x=["9"%0,"8"%0..]!!x
;[a]%_=a
;x&y=x}
```
# How it works
* This code is written in the more rarely used indentation insensitive mode of Haskell, triggered e.g. by surrounding an entire program with `{}`. Since I'm actually defining a function rather than a whole program, I'm not quite sure how to count bytes; I've chosen to defensively count *both* the `{}`s and an extra `;` declaration separator (the latter usually being a newline in normal Haskell mode.)
* The main trick for making newlines "meaningful" is `--` line comments, which make the next newline non-removable, and also a *previous* newline in the case when the previous line ends in an operator character (which is not itself part of a line comment).
* The second trick is "string gaps", a sequence of whitespace between `\` backslashes in string literals, indented for line continuations with possible indentation. A string gap with delimiters is removed from the parsed string.
+ If the newline of a string gap is removed, it becomes an added backslash in the string. For `"Apple"` and `"Pie"` this shows up directly in the output. For `"8"` and `"9"` a pattern match is used to give an error if the string has more than one character.
* The third trick is the `&` and `%` operators, which allow forcing a line to end in an operator character for the first trick. We need this to end string literals, because `\"` is too wide to append `--`.
+ `&` is the general one, defined such that `x&y=x`.
+ `%` is defined such that `[a]%y=a`, allowing it to replace `!!0` and simultaneously enforce that its string argument must have length 1.
* The newline character poses a special problem, as `\n` seems impossible to fit in a string literal with only 3 bytes on the line.
+ Therefore, the more easily defined `c x=["9"%0,"8"%0..]!!x` is used to convert from an `Int` to a character, counting from the digit `'9'` downwards.
* Because `show` is four characters, number output must be implemented by hand.
+ `d` is a list of the digit strings `"1".."9"`.
+ `n` is an infinite list of number representations `["1","2","3",...]` defined recursively using `d`.
* `#` converts an `Int` `x` to its ApplePie form given an extra first argument that is the `gcd` of `x` with 15.
[Answer]
# [Haskell](https://www.haskell.org/), 7 bytes/line, 339 bytes
The requirement for line breaks to be meaningful makes this a nontrivial challenge in Haskell. There are almost no ways to insert line breaks that cannot be removed, so everything has to be done with legitimately tiny statements.
```
c=cycle
h=head
i=tail
k=[1..]
s=do
let
_=0
_=0
putStr
t=take
p=print
u=fst
v=snd
z=zip
n=s"\n"
o 5=do
s"Pie"
n
o _=n
5%x=o 5
_%x=p x
3!x=do
s"App"
s"le"
o$u x
_!x=do
let
y=u x
z=v x
y%z
q x=do
let
y=u x
z=v x
y!z
g[]=s""
g x=do
q$h x
g$i x
a=t 3 k
b=t 5 k
l=z$c a
m=z$c b
f n=do
let
x=t n
y=x k
z=m y
g$l z
```
[Try it online!](https://tio.run/##fY7BboMwDIbvfgo3oteKquLow95g0o5thVIIEBFC2oQK8vLMYUzaaRd/kv9Pv91J3ytj1rWiaqmMgo46JWvQFKQ20NP1fDrdwVM9AhoVALGk/He6KXyFFwSWewWO3EvbABM1PsCbvK0hUtQOLHlxswJGLLYiLz61EoCWNyVZKI4zcQYl0@EMl8O8ex/OiUST9DGbOCz38OebhdIOMdI7cTlGeOJ/wiFCe73zQwLaXXxmXYraTDMkBbxgDw9mwTQUswolDBsf0KD90z6zZbcrM7vpyoBLqjIY10FqSw2e83z9Bg "Haskell – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~3~~ 2 bytes/line, ~~106~~ ~~80~~ 56 bytes
```
“3
,e
5P
ḍ,
T‚Åæ
ịi
‚Åæe
AF
ps
,5
⁾¤
pȯ
lµ
,€
‚ÅæY
”Ỵ
¢Z
¢F
¢v
```
Rows and columns of the string literal get transposed, so removing newlines messes up their order.
The remaining lines are separate links/functions and contain function calls (`¢`), so they can only be concatenated if the function calls are eliminated as well.
[Try it online!](https://tio.run/##y0rNyan8//9RwxxjLp1ULtMAroc7enW4Qh417uN6uLs7kwvISOVydOMqKObSMQXxDi3hKjixnivn0FYunUdNa0BCkVyPGuY@3L2F69CiKCB2A@Ky////GxoYAAA "Jelly – Try It Online")
[Answer]
# TI-BASIC, 4 bytes per line
Since the goal is only to minimize the maximum line length, some of the lines are longer than they need to be, but the smallest I could make the longest line was 4 bytes. Therefore I felt it'd make the code easier to read if I merged the lines that could be combined without exceeding 4 bytes.
```
"APP
Ans‚ÜíStr1
"LE
Str1+Ans
Ans‚ÜíStr1
"PIE
Ans‚ÜíStr2
Input N
1‚ÜíI
While I‚â§N
fPart(I/3
not(Ans‚ÜíA
fPart(I/5
not(Ans‚ÜíB
If A and B
Then
Str1
Ans+Str2
Disp Ans
Else
If A
Then
Disp Str1
Else
If B
Then
Disp Str2
Else
Disp I
End
End
End
I+1
Ans‚ÜíI
End
```
## Ungolfed
```
"APPLE"‚ÜíStr1
"PIE"‚ÜíStr2
Input "N:",N
For(I,1,N)
remainder(I,3)=0‚ÜíA
remainder(I,5)=0‚ÜíB
If A and B:Then
Disp Str1+Str2
Else
If A:Then
Disp Str1
Else
If B:Then
Disp Str2
Else
Disp I
End
End
End
End
```
## About the Language and Limitations
TI-BASIC is a tokenized language, and, in this case, each of the tokens are 1 byte with the exception of the `StrN` variables, which are 2 bytes. Also, you can leave off closing parentheses most of the time. The `remainder(` function is 2 bytes, so using it would require at least 5 bytes (one for the function, two for the arguments, and one for the comma in `remainder(I,3`). Instead, I used the `fPart(` and `not(` functions to make it shorter, which are both 1 byte tokens. Also, you can see I used the built-in variable `Ans` quite a lot, since any expression that gets evaluated on a line by itself gets automatically stored to it. So, I can save a few bytes by splitting up the expressions and assignments.
Another strategy was to obviously minimize the string assignments. My method for doing so depended on the maximum line length in the rest of the code. Once I determined it to be 4 bytes, I was able to cram as much of each string on the same line as possible to minimize the amount of assignments I needed. I did this for the sake of readability.
The limiting factors in this code are the assignments to string variables and concatenation with string variables. The lines `Ans‚ÜíStr1` and `Str1+Ans` both are 4 bytes in total. I would have to find a way to eliminate string variables completely in order to further minimize the maximum line length in my code. Everything else can be shortened to a maximum of 3 bytes or less per line.
The problem there lies in assignments to numeric variables, such as `1‚ÜíI`. You can't golf that any further without somehow coming up with a solution without variables that doesn't exceed 2 bytes in line length. That happens to be impossible for this challenge.
Binary operators like `+` require the operator symbol and the left and right arguments. So without this, you would not be able to concatenate strings. Without string concatenation, there would be no way to display the strings required for this program to complete the challenge without exceeding 2 bytes in line length. Therefore the theoretical limit for this challenge in this language would be 3 bytes per line, which I was not able to attain.
[Answer]
# [Aceto](https://github.com/aceto/aceto), 1 byte per line, 230 bytes
Well, that wasn't fun to write. As a fungoid, Aceto's control structures heavily rely on its 2D nature, but we can work around that with lots, lots of conditional escapes (```). The only problem with those is that they affect the next command, regardless of its presence (all Aceto programs are squares, internally), which is why we need to align the program at some places by inserting empty lines at some points.
String literals can't really be used, but char literals can (in some places; again, we need to align them).
```
&
p
$
L
Q
`
L
p
`
L
d
`
L
Q
`
L
Q
`
L
x
`
L
M
!
%
5
d
$
L
Q
`
L
Q
`
L
p
`
L
d
`
L
Q
`
L
x
`
L
M
!
%
3
d
$
L
p
`
L
d
`
L
x
`
L
M
!
%
*
5
3
d
[
X
`
n
=
0
l
)
@
(
z
i
r
{
J
s
]
d
s
}
d
[
~
£
A
'
d
p
'
l
'
e
'
{
~
£
P
'
i
'
e
'
```
Called with `20`, this prints:
```
1
2
Apple
4
Pie
Apple
7
8
Apple
Pie
11
Apple
13
14
ApplePie
16
17
Apple
19
Pie
```
>
> All line breaks must be meaningful. Line breaks that can be removed and adjacent lines concatenated without an impact on the output, must be removed.
>
>
>
This is never the case here because it runs from the bottom to the top.
There's at least one place where we can save 2 bytes (by replacing the ``X` with a `|` or `#`), but I kept it as it is because of the runtime cost associated with running through a relatively big Hilbert curve.
I also ignored the implicit requirement for using `\r` or `\r\n` newlines because I think it's an unintentional mistake by the OP. If there's an edit or a comment reinforcing this requirement, I can change it without much trouble to use CR newlines instead.
The bytecount is based on Aceto's codegolfing encoding; Latin-7, in which `£` is a single byte.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 2 bytes per line, ~~374~~ ~~368~~ ~~320~~ ~~310~~ 262 bytes
I assume it can be golfed a bit more. Backslashes escaping newlines makes it sort of trivial.
```
i\
;\
f\
(\
n\
)\
{\
f\
o\
r\
(\
i\
=\
0\
;\
i\
+\
+\
<\
n\
;\
p\
r\
i\
n\
t\
f\
(\
i\
%\
3\
&\
&\
i\
%\
5\
?\
"\
%\
d\
\\
n\
"\
:\
i\
%\
3\
?\
"\
P\
i\
e\
\\
n\
"\
:\
i\
%\
5\
?\
"\
A\
p\
p\
l\
e\
\\
n\
"\
:\
"\
A\
p\
p\
l\
e\
P\
i\
e\
\\
n\
"\
,\
i\
)\
)\
;\
}
```
[Try it online!](https://tio.run/##bY9BCgIxFEPX5hQiKC0qVMSNo4g38ADZSHWkoFVkdoNnr58MijBCFj/576c0zi8xlpKIiqgJR2TCE63snXgqNGBLBGE2T6WNYEsewpJs8@kxOyaWxETq7IrYESPNJ4I6Mbv@4TvgoOT8j/mW7PW06doj@9t@4UyJl@wXr5JyM7wdU3YeLQa1W4TgK8vf "C (gcc) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 4 bytes/line, 113 bytes
```
e=\
exec
def\
f(n\
):i\
=0;\
e('\
pri\
nt(\
i%3\
//2\
*"A\
ppl\
e"+\
i%5\
//4\
*"P\
ie"\
or-\
~i)\
;i+\
=1;\
'*n)
```
[Try it online!](https://tio.run/##FcxBCsIwFITh/RwjIE0q0tTajSULb@ABZqcvGJA0lC5049Xjy/LnG6Z899eap1olEPKRB54SiWgz4a6JCH5RsB1RNs28WyIdJmIYzkRvbgrlrRNzbDA3uDS4a4oh1u1E/JIjlqSTMOpf12dXox29d/UP "Python 3 – Try It Online")
[Answer]
# PHP 7, 2 bytes per line
```
(#
c#
.#
r#
.#
e#
.#
a#
.#
t#
.#
e#
.#
_#
.#
f#
.#
u#
.#
n#
.#
c#
.#
t#
.#
i#
.#
o#
.#
n#
)#
(#
'#
'#
,#
g#
.#
l#
.#
o#
.#
b#
.#
a#
.#
l#
.#
(#
c#
.#
h#
.#
r#
)#
(#
6#
*#
6#
)#
.#
a#
.#
r#
.#
g#
.#
n#
.#
(#
c#
.#
h#
.#
r#
)#
(#
7#
*#
8#
+#
3#
)#
.#
w#
.#
h#
.#
i#
.#
l#
.#
e#
.#
(#
c#
.#
h#
.#
r#
)#
(#
5#
*#
8#
)#
.#
(#
c#
.#
h#
.#
r#
)#
(#
6#
*#
6#
)#
.#
i#
.#
(#
c#
.#
h#
.#
r#
)#
(#
6#
*#
7#
+#
1#
)#
.#
(#
c#
.#
h#
.#
r#
)#
(#
6#
*#
7#
+#
1#
)#
.#
(#
c#
.#
h#
.#
r#
)#
(#
7#
*#
8#
+#
4#
)#
.#
(#
c#
.#
h#
.#
r#
)#
(#
6#
*#
6#
)#
.#
a#
.#
r#
.#
g#
.#
n#
.#
(#
c#
.#
h#
.#
r#
)#
(#
5#
*#
8#
+#
1#
)#
.#
e#
.#
c#
.#
h#
.#
o#
.#
(#
c#
.#
h#
.#
r#
)#
(#
6#
*#
6#
)#
.#
i#
.#
(#
c#
.#
h#
.#
r#
)#
(#
6#
*#
6#
+#
1#
)#
.#
3#
.#
(#
c#
.#
h#
.#
r#
)#
(#
7#
*#
9#
)#
.#
(#
c#
.#
h#
.#
r#
)#
(#
5#
*#
8#
)#
.#
(#
c#
.#
h#
.#
r#
)#
(#
6#
*#
6#
)#
.#
i#
.#
(#
c#
.#
h#
.#
r#
)#
(#
6#
*#
6#
+#
1#
)#
.#
5#
.#
(#
c#
.#
h#
.#
r#
)#
(#
7#
*#
9#
)#
.#
(#
c#
.#
h#
.#
r#
)#
(#
6#
*#
6#
)#
.#
i#
.#
(#
c#
.#
h#
.#
r#
)#
(#
7#
*#
8#
+#
2#
)#
.#
P#
.#
i#
.#
e#
.#
(#
c#
.#
h#
.#
r#
)#
(#
5#
*#
8#
+#
1#
)#
.#
(#
c#
.#
h#
.#
r#
)#
(#
7#
*#
8#
+#
2#
)#
.#
(#
c#
.#
h#
.#
r#
)#
(#
5#
*#
8#
)#
.#
(#
c#
.#
h#
.#
r#
)#
(#
6#
*#
6#
)#
.#
i#
.#
(#
c#
.#
h#
.#
r#
)#
(#
6#
*#
6#
+#
1#
)#
.#
5#
.#
(#
c#
.#
h#
.#
r#
)#
(#
7#
*#
9#
)#
.#
A#
.#
p#
.#
p#
.#
l#
.#
e#
.#
(#
c#
.#
h#
.#
r#
)#
(#
7#
*#
8#
+#
2#
)#
.#
A#
.#
p#
.#
p#
.#
l#
.#
e#
.#
P#
.#
i#
.#
e#
.#
(#
c#
.#
h#
.#
r#
)#
(#
5#
*#
8#
+#
1#
)#
.#
(#
c#
.#
h#
.#
r#
)#
(#
6#
*#
7#
+#
2#
)#
.#
(#
c#
.#
h#
.#
r#
)#
(#
4#
*#
8#
+#
2#
)#
.#
(#
c#
.#
h#
.#
r#
)#
(#
2#
*#
5#
)#
.#
(#
c#
.#
h#
.#
r#
)#
(#
4#
*#
8#
+#
2#
)#
.#
(#
c#
.#
h#
.#
r#
)#
(#
7#
*#
8#
+#
3#
)#
)#
(#
)#
;#
```
[Answer]
## [Perl 5](https://www.perl.org/), 2 bytes per line, 182 bytes
```
&
#
{'
Er
0h
|R
hR
o
'#
^#
'I
O
Ro
3f
+~
'#
.#
(#
p#
|#
Y#
)#
}#
(#
'z
;d
y"
"z
7#
vU
aW
zZ
7#
vU
gW
..
~.
4e
r;
|6
'#
^#
('
xR
~R
KR
fR
QR
/R
$R
cR
QR
/R
vR
UR
%R
xR
$R
'#
.#
4#
))
```
[Try it online!](https://tio.run/##NY7NCoJgFET35ynCW31FYEX2A65bRIvogkgtgijLRaC4iDLz1b@0bHc4DDOTRtltam0X4WVYZoxiCiVWEoxwEMyK1gZNmFwYlLV0hZ6QCoWwE/rC@2tMjn/m6eDkzIV7wDEk3zd8DXFdShcvIvMpZk1/z/BQSmWtXJStMlTayunPdyVQOlrHKv874FW7fWvHiw8 "Perl 5 – Try It Online")
Perl's syntax is very forgiving, so a lot of gaps can be added to the code and comments added, which makes the core idea fairly straightforward. The main aim with this code is to build a string containing the code we want to run, and `eval` it. In Perl, it's possible to call a function using a string or variable with the `&{...}` notation, unfortunately however, `eval` isn't callable in this form, but `evalbytes` is, as long as you call it via the `CORE::` namespace. Building that string was fairly straightforward and the program is passed directly to this call. The strings are built utilising the newlines as part of the XOR, to build these [I used this script](https://tio.run/##NYxBCsIwFET3OUUWX9ISTRDpKlbwBtKtNKGFKoHQ/NaiC@vVjZ@qq3k8Zga7MRQpdfcm8OGRQaNK0AZaCmeJ@GIWXOTPVP9KZfIzeClXu/oSR6301TBw5TA8GRPQCCugFYy9FF1baHOTEo6@n2R2RAwdjR1NVXbyXy7qeQa3Bk1vfKvU/vCOOPnY39IGPw "Perl 5 – Try It Online"). To keep this valid, a few places have had to have comments placed, so that removing the newlines would result in non-functioning code.
The FizzBuzz routine was taken from [primo's excellent answer](https://codegolf.stackexchange.com/a/58675/9365).
---
## [Perl 5](https://www.perl.org/), 1 byte per line, 172 bytes
So, I (now) know *this is invalid*, because a bunch of the newlines can be removed, but since this was my original approach to the problem I'm adding it. It was fun see how far you can push Perl's syntax! I enjoyed this problem on its own merit, even though it's invalid.
```
&
{
(
I
.
'
X
0
o
k
h
~
'
.
(
p
|
Y
)
)
^
'
E
O
0
|
f
s
o
'
}
(
'
x
d
!
K
z
o
Q
U
9
$
Z
o
Q
U
?
v
.
&
%
e
*
$
6
'
^
'
c
~
"
z
f
#
.
/
W
"
c
#
.
/
W
v
U
.
l
x
;
$
4
'
^
p
)
```
[Try it online!](https://tio.run/##PY27CsJAFET78xcazRqLVSGKYmFlIRZiIT4KmzwQDGRRCKLRX19HEbnNzHBmrssuxdD7kAcdFlgMO/qUnDnxkrPKHTV7It1RyZyViJqcqzjDU4ThRkqDJXdlazZMaHH46RmVdkLaZHSVj8R/lkj0oqlKTiCgx1Yu@etKVUuh6alK8bfkiLwfjN8 "Perl 5 – Try It Online")
[Answer]
# SmileBASIC, ~~9~~ 7 bytes per line, ~~159~~ ~~155~~ ~~154~~ 152 bytes
This was a really fun challenge.
Unfortunately, the rule against unnecessary line breaks causes a few problems, (though luckily it doesn't affect the maximum line length here.)
I had to add comments between lines like `A%=I/3` and `A=A%*3`, since `A%=I/3A=A%*3` is parsed correctly in SB. I was able to use a trick to leave out some comments, since replacing `A` with `E` makes that line invalid (It has something to do with numbers written using `E` notation, I think. `3E` is considered an invalid number rather than a number and a variable name.)
```
A$="App
B$="le
P$="Pie
INPUT N
R=N
WHILE R
INC I
R=I<N
A%=I/3'
A=A%*3'
A=A==I
B%=I/5
E=B%*5
E=E==I'
?A$*A;
?B$*E;
?P$*E;
C=A+E
WHILE!C
C=1?I;
WEND?
WEND
```
The biggest limitation here is getting input. `INPUT x` is the simplest way allowed, the alternative being to define a function with an input value like `DEF F x` but that is still 7 characters. Making a conditional statement is also hard; I can't think of anything shorter than `WHILE x`.
[Answer]
# JavaScript (ES6), 3 bytes per line
Uses the global variable `top` to access the `window` object, from which we `eval` the following code:
```
n=prompt('')
i=0
for(;++i<=n;console.log(i%5?f||i:f+'Pie'))f=i%3?'':'Apple'
```
You'll have to run it in the console as `top` is inaccessible from a sandboxed Stack Snippet.
---
```
t//
=//
top
t//
[`\
ev\
al\
`//
]//
(`\
n=\
pr\
om\
pt\
('\
')
i=0
fo\
r(\
;+\
+i\
<=\
n;\
co\
ns\
ol\
e.\
lo\
g(\
i%\
5?\
f|\
|i\
:f\
+'\
Pi\
e'\
))\
f=\
i%\
3?\
''\
:'\
Ap\
pl\
e'\
`)
```
[Answer]
## C#, 9 bytes per line, ~~248 242~~ 230 bytes
Since C# doesn't care about linebreaks, it needs a oneline comment at the end of almost (thanks √òrjan Johansen) every line to comply with the rules. This program expects *n* as a command line argument. Here's with as many non-deletable newlines as possible:
```
class
A//
{//
static
void
Main//
(//
string//
[//
]//
a//
)//
{//
for//
(//
var
i//
=//
0//
;//
i++//
<//
int//
.Parse//
(//
a//
[//
0//
]//
)//
;//
)//
{//
var
s//
=//
""//
;//
if//
(//
i//
%//
3//
==//
0//
)//
s//
+=//
"A"+//
"p"+//
"p"+//
"l"+//
"e"//
;//
if//
(//
i//
%//
5//
==//
0//
)//
s//
+=//
"P"+//
"i"+//
"e"//
;//
if//
(//
s//
==//
""//
)//
s//
=//
$"{i}"//
;//
System//
.//
Console//
.//
Write//
(//
s//
+//
@"
"//
)//
;//
}//
}//
}
```
But since the longest line is 9 bytes, other lines can get that long too, shaving off some bytes:
```
class
A{static
void
Main(//
string[//
]a){//
for(var
i=0;i++//
<int.//
Parse(a//
[0]);){//
var
s="";if//
(i%3==0//
)s+=//
"Apple"//
;if(i%5//
==0)s+=//
"Pie";//
if(s==//
"")s=//
$"{i}";//
System.//
Console//
.Write(//
s+@"
");}}}
```
[Answer]
# Python 2, 5 bytes/line, 93 bytes
The max6 standard is already obsolete.
```
def\
f(n):
i=0
\
exec\
'pri\
nt i\
%3/2\
*"Ap\
ple"\
+i%5\
/4*"\
Pie"\
or-~\
i;i+\
=1;'\
*n
```
[Try it online!](https://tio.run/##K6gsycjPM/r/PyU1LYYrTSNP04pLIdPWgEshhiu1IjU5hku9oCgzhiuvRAFIqhrrG8VwaSk5FsRwFeSkKsVwaWeqmsZw6ZtoAdkBmSCR/CLduhiuTOtM7RguW0NrdaD6vP9pGoYGBpr/AQ "Python 2 – Try It Online")
# Python 2 and 3, 5 bytes/line, 100 bytes
```
def\
f(n):
i=0
\
exec\
('pr\
int(\
i%3/\
/2*"\
Appl\
e"+i\
%5//\
4*"P\
ie"o\
r-~i\
);i+\
=1;'\
*n)
```
[Try it online!](https://tio.run/##DcqxCoMwGEXh/T6FBMQkUhKrXSoOfYM@wN3ahAZKDOLQLr56/JczfJzy3z9rHmt9h0hEnc0dTVo8GiL8wovQXdmIlHctbUdHuKtVxKOUrzyqT0R7c@KTVU95glqJ7XKImzn1xDLMHWGzqVEP3pt6Ag)
[Answer]
# JavaScript, max of 6 bytes/line, 528 bytes
Idea ripped from [here](https://github.com/petersn/six-char-max/blob/master/max6.py).
Code ripped from [here](https://codegolf.stackexchange.com/questions/58615/1-2-fizz-4-buzz/62697#62697).
Thanks to Anders Kaseorg for `g=eval`, saving a byte per line.
```
a="n"
a+="="
a+="p"
a+="r"
a+="o"
a+="m"
a+="p"
a+="t"
a+="("
a+="'"
a+="'"
a+=")"
a+=";"
a+="f"
a+="o"
a+="r"
a+="("
a+="i"
a+="="
a+="0"
a+=";"
a+="+"
a+="+"
a+="i"
a+="<"
a+="="
a+="n"
a+=";"
a+="c"
a+="o"
a+="n"
a+="s"
a+="o"
a+="l"
a+="e"
a+="."
a+="l"
a+="o"
a+="g"
a+="("
a+="i"
a+="%"
a+="5"
a+="?"
a+="f"
a+="|"
a+="|"
a+="i"
a+=":"
a+="f"
a+="+"
a+="'"
a+="P"
a+="i"
a+="e"
a+="'"
a+=")"
a+=")"
a+="f"
a+="="
a+="i"
a+="%"
a+="3"
a+="?"
a+="'"
a+="'"
a+=":"
a+="'"
a+="A"
a+="p"
a+="p"
a+="l"
a+="e"
a+="'"
g=eval
g(a)
```
Unseperated:
```
n=prompt('');for(i=0;++i<=n;console.log(i%5?f||i:f+'Pie'))f=i%3?'':'Apple'
```
[Answer]
# PHP, 4 Bytes/line
```
for#
(#
$z=#
${#
ar.#
gn#
};#
$k#
++<#
$z#
;){#
(#
pr.#
in.#
t_.#
r)#
([#
A.#
p.p#
.le#
][#
$k#
%3#
].[#
Pie#
][#
$k#
%5#
]?:#
$k)#
;(#
pr.#
in.#
t_.#
r)#
("
");}
```
[Try it online!](https://tio.run/##dYxBC4JAFITv8zN8Bi3CEkiXVpH@QXeR8FAqxfpYOiX@9nW2Ll26fMzMm3k6aqwaHRV5HwZflwcX73MQ7AX5uyYWQR@sYPCC1TF4CIqiSmeBM8unqqkxeeJ1JYJh2grO1GpVYJ83Qdd@17uS2tJcpt/0SN2ckuHa/XmaITNujXED "PHP – Try It Online")
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 5 bytes per line
```
‚àáf
A‚Üê'A'
p‚Üê'p'
p,‚Üêp
e‚Üê'e'
A,‚Üêp
l‚Üê'l'
A,‚Üêl
A,‚Üêe
P‚Üê'P'
i‚Üê'i'
P,‚Üêi
P,‚Üêe
{O‚Üê''
M‚Üê3|‚çµ
M‚Üê0=M
O‚ÜêM/A
M‚Üê5|‚çµ
M‚Üê0=M
M‚ÜêM/P
O,‚ÜêM
M←⍴O
M‚Üê0=M
M‚ÜêM/‚çµ
O,‚ÜêM
⎕←O⍝
}¨⍳⎕
‚àá
```
[Try it online!](https://tio.run/##XY8xDgIhEEX7fxEajRhjacEBCFxhE1lDQiKtUVu1YWNjaW@vXsCjzEWQgW20evP@nyGhi2G63nVhu8mZLuceik5XoQQiMxZOyhDhWJ2AahpYw6ihwcFyagU80wtYjn2Dw95wLKALFgdK7zrJlQYXeqaqL38aXRsLw080pfQyfz1fjBs03AoNpTuOnwelZwlQPpZzj7mUXw "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina), 4 bytes/line
```
.+
$* Convert the input number to unary.
1
$`1¶ Count from 1 to the input number.
111
A Divide by 3.
+`A1
1111 If there was a remainder, restore the original number.
A{5}
AP If the number is divisible by 3, try to divide by 5.
.*A The result ends in `AP` if the number is divisible by 15,
Appl or in `A` if it is only divisible by 3. Replace everything
l up to the `A` with `Apple`; multiples of 15 become `AppleP`.
le
1{5} If the number did not divide by 3, try dividing it by 5 anyway.
P
+`P1 If there was a remainder, restore the original number.
6$*1 Otherwise replace the result with `Pie`,
P+ which also fixes multiples of 15.
Pie If the number was divisible by neither 3 nor 5,
1+ convert it back to decimal.
$.&
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0WLy5BLJcHw0DYuQ0NDLkcu7QRHQxATyK42reVyDODS03LkciwoyOECwlQuQ5BoAFBZgCGXmYqWIVeANldAJlAcaJae2v//hgYGAA "Retina – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 10 bytes per line, 800 bytes
The "meaningful linebreaks" rule made this challenging. Currently this just spells out fizzbuzz code into a string and then executes it.
```
a="x"
a[2]="="
a[3]="y"
a[4]="="
a[5]="1"
a[6]=":"
a[7]="s"
a[8]="c"
a[9]="a"
a[10]="n"
a[11]="("
a[12]=")"
a[13]=";"
a[14]="y"
a[15]="["
a[16]="3"
a[17]="*"
a[18]="x"
a[19]="]"
a[20]="="
a[21]="'"
a[22]="A"
a[23]="p"
a[24]="p"
a[25]="l"
a[26]="e"
a[27]="'"
a[28]=";"
a[29]="y"
a[30]="["
a[31]="5"
a[32]="*"
a[33]="x"
a[34]="]"
a[35]="="
a[36]="'"
a[37]="P"
a[38]="i"
a[39]="e"
a[40]="'"
a[41]=";"
a[42]="y"
a[43]="["
a[44]="1"
a[45]="5"
a[46]="*"
a[47]="x"
a[48]="]"
a[49]="="
a[50]="'"
a[51]="A"
a[52]="p"
a[53]="p"
a[54]="l"
a[55]="e"
a[56]="P"
a[57]="i"
a[58]="e"
a[59]="'"
a[60]=";"
a[61]="w"
a[62]="r"
a[63]="i"
a[64]="t"
a[65]="e"
a[66]="("
a[67]="y"
a[68]="["
a[69]="x"
a[70]="]"
a[71]=","
a[72]="'"
a[73]="'"
a[74]=")"
t=toString
g=gsub
o=", "
l=""
f=t(a)
r=g(o,l,f)
P=parse
p=P(t=r)
eval(p)
```
[Try it online!](https://tio.run/##PZLLboMwEEX3/oqKTaFi4cfYhlZe9A8idRllQasERUIBEfr6euqZ6np3lOA5xwPrvg@p@qnUcLSnVCUGl@GXgfCLz2AYQoZnhpjhztBl@GDoMwwMRme6CZlMtRAPb4R4@osQwWN4/lGIBU6IDU9CrJBCw46TtGqkWXY8CrHjVYgdixAVYsckxI6zUCxnO1TZHlVOo8qxwwtZVDmHKkeocr6sMGCyY8dBiB1XoR4FpPEcGRSQLft3KCDCGyCPFgpooYgW6tBCfXl5xeENNuQt9uLLrjxhQ96jzwfU@4h635V/e0wOGvWBHd9C7FiFHM4GdmxCxRECvpIQcfPQ4eahx92ixt0iO1ohi4LoCtH/t7albX7b1uttVGMa75/vas6nHio1papSl7TVQ6PWNNZzO7WXRh3SMqz3s1rSod7S2qjz1zDVS7Mbrfc/ "R – Try It Online")
Here is the concatenated ApplePie code (adapted from [MickyT's](https://codegolf.stackexchange.com/users/31347/mickyt) golf [here](https://codegolf.stackexchange.com/questions/58615/1-2-fizz-4-buzz/58637#58637)).
```
x=y=1:scan()
y[3*x]='Apple'
y[5*x]='Pie'
y[15*x]='ApplePie'
write(y[x],'')
```
And the ungolfed version of the parsing code:
```
eval(t=parse(gsub(", ", "", toString(a))))
```
Here I use `toString` to concatenate the list of symbols `a` into a single string. However, the default behavior is to separate each symbol with `,`, so we call `gsub` to replace them with nulls. Then we pass it to `parse` and `eval` to do the dirty work.
It's possible that there's an approach that doesn't use this string parsing method and just straight up implements fizzbuzz, but it seems to me that using `for` or `while` or defining a `function` needs longer lines than the current approach.
[Answer]
# Ruby, ~~10~~ 5 bytes/line, ~~354~~ 214 bytes
-140 bytes from the raw score from @NieDzejkob.
```
eval\
"pu"\
"ts"\
" ("\
"1."\
".g"\
"et"\
"s."\
"to"\
"_i"\
")."\
"ma"\
"p{"\
"|i"\
"|i"\
"%1"\
"5<"\
"1?"\
":A"\
"pp"\
"le"\
"Pi"\
"e:"\
"i%"\
"5<"\
"1?"\
":P"\
"ie"\
":i"\
"%3"\
"<1"\
"?:"\
"Ap"\
"pl"\
"e:"\
"i}"
```
### How it works
Ruby will automatically concatenate sequences of string literals (except for single-character literals such as `?a`) in the same statement. That means that `x = "a" 'b' "c" %q{d}` is equivalent to `x = "abcd"`. We use this to split the FizzBuzz-like code into much smaller strings for calling `eval` with, since `+` will invalidate the program due to the removing-newlines rule, but the `\` will cause syntax errors if the newlines are taken out!
[Answer]
# [Julia 0.6](http://julialang.org/), 5 bytes per line, 168 bytes total
```
f=#
n->#
((i,#
a=#
"A"*#
"p"*#
"p"*#
"l"*#
"e",#
p=#
"P"*#
"i"*#
"e"#
)->#
["$i
","$a
","$p
",a*#
p*"
"][#
1+(i#
%3<1#
)+2(#
i%5<#
1)]#
|>[#
print
sin#
][1]#
).(#
1:n)
```
[Try it online!](https://tio.run/##TY7LCsIwEEX38xUy08JMG4UY6kJrwT9wX7rIQiFSQ/Cx89/jNLhwc@Bezh3m9p6D3@V8PRLE9UDAHAyB14gnbJTpj3PhBdVIi3EuOfxaAlkujFgFQIOVL0xKr0JqEHAaCWzLgaB2vdVBu2WCUHe99jIRfAY10iPEFzxDJJhGq61s1LL7KJDvPrE@yleOcijiHFnErNgaZzrjnEj@Ag "Julia 0.6 – Try It Online")
The `print` brings this unavoidably (afaict) into the 5 bytes per line territory.
Ungolfed:
```
function f_ungolfed(n)
inner = (i,
a="Apple",
p="Pie") -> ["$i\n",
"$a\n",
"$p\n",
a*p*"\n"][
1 + (i%3 < 1) + 2(i%5 < 1)
] |> [print; sin][1]
inner.(1:n)
end
```
`*` is the string concatenation operator, so `a*p*"\n"` forms "ApplePie\n". `|>` is the function chaining (/piping) operator, so the chosen string gets sent as the argument to `print`. The `sin` is not used, it's just there because `print` needs to be in an array to have significant whitespace after it (using the `#` trick after it will bring the per line max byte count to 6).
---
If simply returning the output as an array is allowed, it can be done with 4 bytes max per line:
## [Julia 0.6](http://julialang.org/), 4 bytes per line, 152 bytes total
```
f=#
n->#
((i#
,a=#
"A"#
*#
"p"#
*#
"p"#
*#
"l"#
*#
"e"#
,p=#
"P"#
*#
"i"#
*#
"e"#
)->#
[i,#
a,p#
,a*#
p][#
1+(#
i%3#
<1#
)+#
2(i#
%5<#
1)]#
).(#
1:n#
)
```
[Try it online!](https://tio.run/##yyrNyUw0@/8/zVaZK0/XTplLQyNTmUsnEchVclRS5tIC0gVodA6UTgXSOgUglQFQkUwkGU2QadGZOspciToFICOBEgWx0cpchtoaylyZqsbKXDaGQGXaylxGIDtVTW2AcpqxQCE9oAJDqzwgi@t/bmKBRkFRZl5JTt6jjhlpOgoahjrGOqY6Rqaamv8B "Julia 0.6 – Try It Online")
A function that takes n and returns an array containing the expected output.
Max line length here is constrained by `n->` - Julia needs that in a single line to parse it properly as the start of a lambda.
[Answer]
# [Pascal (FPC)](https://www.freepascal.org/) `-Sew`, 6 bytes per line, ~~348~~ 320 bytes
```
var
n,i://
word//
;begin
read//
(n);//
for
i:=1to
n do
if 0=i
mod
15then
write{
$}(//
'A',//
'p',//
'p',//
'l',//
'e',//
'P',//
'i',//
'e',//
#10)//
else
if 0=i
mod
3then
write{
$}(//
'A',//
'p',//
'p',//
'l',//
'e',//
#10)//
else
if 0=i
mod
5then
write{
$}(//
'P',//
'i',//
'e',//
#10)//
else
write{
$}(i//
,#10//
)end.
```
[Try it online!](https://tio.run/##nc5LCsIwEAbg/ZyioNAWUvsQNy1deAPBE8RmUgdiUtJiF@LVjSldWEERXH3Mg5m/433DVSK7xrkrt6AZlWkKo7HCU52wJQ0W@VRFOq480ligss4HAzoQBkgGWU1wMQLy3XBGDaOlAW@wvkd@PdyHbKJ7Q83gzGGGls1VnsUeVD0uX2z/@vDl2Ke4v7K8tsm3mB95YtRi41xRPBqpeNu75IjjEw "Pascal (FPC) – Try It Online")
Utilises FPC to get 6 bytes per line; without it, the result would be much worse. This is the smallest possible line width since after `write` must be either `;` or `(` (or unnecessary whitespace), so a special comment is inserted to avoid this. The features from FPC which influenced this answer are:
1. `//` - starting one-line comments.
2. Block comments in form `{$<something>...}` are compiler directives. If the directive does not exist, FPC will issue a warning (and on `{$ ...}` as well). In this program, `{` and `$` are separated with a newline which will issue the warning when deleted.
3. `-Sew` - Compiler also halts after warnings so that `{` and `$` joined stop the compilation.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 3 bytes per line
Nearly managed to get it down to two bytes per line, but the return from map breaks if it's followed by a newline.
The FizzBuzz implementation itself is from [the canonical FizzBuzz thread](https://codegolf.stackexchange.com/a/62944/16484).
```
`A
p
p
l
e
`y
Vx
`P
i
e
`y
Xx
ò1\
Ë\
;W\
pD\
v3\
)+\
Yp\
Dv\
5)\
ªD\
÷
```
[Try it online!](https://tio.run/##y0osKPn/nyvBkasACHO4UrkSKrnCKrgSArgyIZyICq7DmwxjuBQOd8dwWYfHcBW4xHCVGcdwaWrHcEUWxHC5lMVwmWrGcB1aBZQ43Hxo@///hgYGAA "Japt – Try It Online")
[Answer]
# [LOLCODE](http://lolcode.org/), ~~18~~ 8 bytes per line, 303 bytes total
```
HAI 1.2
I HAS A…
B ITZ 0
IM IN…
YR L
B R SUM…
OF B AN…
1
MOD OF…
B AN 15
WTF?
OMG 0
VISIBLE…
"Apple"…
"Pie"
OMGWTF
MOD OF…
B AN 5
WTF?
OMG 0
VISIBLE…
"Pie"
OMGWTF
MOD OF…
B AN 3
WTF?
OMG 0
VISIBLE…
"Apple"
OMGWTF
VISIBLE…
B
OIC
OIC
OIC
BOTH…
SAEM B…
AN 100
O RLY?
YA RLY
GTFO
OIC
IM…
OUTTA…
YR L
KTHXBYE
```
[Try it online!](https://tio.run/##fZBNDoIwEIX3c4oJBzCgcU2mSmEipYbWH9wqCxMSOIKn8WBepFKIxJjIoun0vfd1MtO0zbW91c5lxBgtlsCYkUF6PZ4gkO0FQ2CFXHihKjHv1RLNQfm3liiQBisCpbeo5chRgdEaTlbGoFXaf3FkwyJPvBtQ1zV1MJT7ex34RJ/85f/iM8xqvuWH@nIEaN5MR2ibedVQolD4yg8ShqCxzKsYKvI3pFbqIc/jFg7W0rSenc3OokqcewM)
*-10 bytes per line using the line-continuation character `…`, thanks to Ørjan Johansen!*
[Answer]
# [Python 2](https://docs.python.org/2/), 5 bytes/line
```
exec\
'f\
o\
r\
\
x\
\
i\
n\
\
x\
r\
a\
n\
g\
e\
(\
1\
,\
i\
n\
p\
u\
t\
(\
)\
+\
1\
)\
:\
\n\
\
i\
f\
\
x\
%\
1\
5\
=\
=\
0\
:\
s\
="\
A\
p\
p\
l\
e\
P\
i\
e"\
\n\
\
e\
l\
i\
f\
\
x\
%\
5\
=\
=\
0\
:\
s\
="\
P\
i\
e"\
\n\
\
e\
l\
i\
f\
\
x\
%\
3\
=\
=\
0\
:\
s\
="\
A\
p\
p\
l\
e"\
\n\
\
e\
l\
s\
e\
:\
s\
=\
x\
\n\
\
p\
r\
i\
n\
t\
(\
s\
)'
```
[Try it online!](https://tio.run/##jZDBCsIwEETv8xVSkFr0kCpehB78Az9gLiKpCtIWWyF@fQxTkkNEEJawu7PzNuzwnm59t/XeOnshypboiSexIJzeO9HFMvTPKq@EJVZETWzizEC8iEn9ilhLDcmBYBdZbWQtJe@JRmE0NyoviKNwIR7adJLXFolkpWS8X7D/3Ltvd/6RnDAqSatckgfdaj7LfJAwUZXe18Z8AA "Python 2 – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 3 bytes per line, 72 bytes total
```
V@Y
YUW
Y"L
a
P
S
T
[
`
A
p
p
l
e
`
`
P
i
e
`
]
X
!
*
+
+
i
%
^
3
5
|
i"
```
[Try it online!](https://tio.run/##K8gs@P8/zCGSKzI0nCtSyYcrkSuAK5grhCuaK4HLkasACHO4UoHsBKB4JpgVyxXBpcilxaUNhJlcqlxxXMZcplw1XJlK////NzIAAA "Pip – Try It Online")
Pip is exceedingly flexible about whitespace, so the only strategy that seems feasible is to create a string, modify it in a way that requires the newlines not to be disturbed, and eval it.
We create a string where every other character is a newline, and take every other character of it using `UW` (unweave) and unary `@` (get first element):
```
UW"abcdef" => ["ace" "bdf"]
@UW"abcdef" => "ace"
```
The result of `@UW` should be our ApplePie code, adapted from the FizzBuzz solution [here](https://codegolf.stackexchange.com/a/58758/16766). If any newlines in the string are deleted, this will not result in the full code, giving either a syntax error or incorrect output.
There are still two newlines outside the string. We made these mandatory by using the `Y` (yank) operator--which here acts as a no-op--together with the way Pip parses runs of uppercase letters:
```
YUW => Y UW
YUW Y => Y UW Y
YUWY => YU WY
```
So if these newlines are deleted, the program parses differently and doesn't do what it's supposed to.
[Answer]
# Java 8, 7 bytes per line, 171 bytes
A void lambda taking an `int`. I suspect this obeys the requirement regarding newlines, but I can't prove it, and verifying it by brute force would take about a month on my computer. So it goes.
```
a->{//
System
s=//
null;//
for(int
i=0;i//
<a;)s//
.out.//
print//
((++i//
%3*(i//
%5)<1//
?(i%3//
<1?//
"App"//
+"le"//
:"")+//
(i%5<//
1?//
"Pie"//
:"")://
i)+//
"\n");}
```
[Try It Online](https://tio.run/##XdBBa8MgFAfwc/wUIgR0obal66UmLWOnHQaDHrcdXGrCy4yRqIVR@tmzl27ssIs/9b0/6Ov0WS8Gb1x3@px8@rBQ09rqEOizBkcvJPu9DFFHpAGnLe0wJVMEK5vk6giDk4@DC6k3Y/nkomnNuKcNrSa92F@WS3L8CtH0JFS4d8lahTbDyMFFAtVKAZ5LrURA5ZCiRP2IVZTzopjr@eaO39yKco0eOOSbObc@4MoevGdowayZ3TEmijkN@bZEf5pe4K@4Q@HWwt4cE@o6ZYr8/@15gBPtcRD8GPE57es71WMbxDyXrJG6ro2P/H4lFMmu5Eqmbw)
Pretty boring due to the line comments. The only interesting thing here is the use of a null `System` reference, which seems to be necessary in order to print to standard out in under 8 bytes per line. Note also that the `print` method call is the bottleneck.
## Ungolfed with no comments:
```
a -> {
System s = null;
for (int i = 0; i < a; )
s.out.print(
(++i % 3 * (i % 5) < 1 ?
(i % 3 < 1 ? "App"+"le" : "")
+ (i % 5 < 1 ? "Pie" : "")
: i
) + "\n"
);
}
```
[Answer]
# JavaScript (ECMAScript6), 2 bytes per line
```
'\
'[
'\
b\
i\
g'
][
'\
c\
o\
n\
s\
t\
r\
u\
c\
t\
o\
r'
][
'\
c\
a\
l\
l'
](
0,
`\
n\
=\
p\
r\
o\
m\
p\
t\
(\
'\
'\
)\
;\
i\
=\
0\
;\
f\
o\
r\
(\
;\
+\
+\
i\
<\
=\
n\
;\
c\
o\
n\
s\
o\
l\
e\
.\
l\
o\
g\
(\
i\
%\
5\
?\
f\
|\
|\
i\
:\
f\
+\
'\
P\
i\
e\
'\
)\
)\
f\
=\
i\
%\
3\
?\
'\
'\
:\
'\
A\
p\
p\
l\
e\
'\
`)
()
```
---
## TLDR - Short*er* explanation
I'm accessing the [new Function(code)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) constructor to parse the string instead of [eval(code)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval). This constructor is available at every native function by doing anyFunction.[constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor/), like `alert.constructor===Function`. I'm using a function/method inside the [String.prototype.big](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/big) `String.prototype.big.constructor.call(null, /*string*/)`
But accessing it directly from a string literal `"".big` and turned it to [bracket notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors). `""['big']['constructor']['call'](0, CODE)` to be able to break it using the `\`.
## Long explanation
The way we can make lines shorter is transforming code into a string and escaping the line ends, this will impose a limit of 2bytes per line.
So `alert(1)` becomes
```
"\
a\
l\
e\
r\
(\
1\
)"
```
But now your code is a string so we need to execute the string as code. I know at least 4 ways you can execute string as code:
1. [eval(code)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval). Which takes at least 5 bytes to call `eval(`
2. [setTimeout(code, timeout)](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout). Runs function asyncronously, but optionally if you pass a string it will invoke eval internally.
3. You can take advantage of the DOM and put your code inside a `onclick=""` attribute, but I could not manage to make the element creation part short.
4. Invoking the [Function constructor new Function()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) will parse your code into a anonymous function which you can call later (I used this).
All the native functions lives inside the [window](https://developer.mozilla.org/en-US/docs/Web/API/Window) object and in javascript you can access object properties using the [dot notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors) so `eval()` becomes `window.eval()`, or you can access properties using the [bracket notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors) `window['eval']()`. You can take advantage of this to break the `eval` in multiple lines using the method described before. But you still have to type the [window](https://developer.mozilla.org/en-US/docs/Web/API/Window), one trick is that if you're not inside a frame, the [top](https://developer.mozilla.org/en-US/docs/Web/API/Window/top) variable is also window, so window.eval becomes top.eval (3 bytes less).
```
w=top
w['eval']
You can shorten the assignment using parenthesis
w=(
top
)
w[
'e\
av\
al'
](
/*string*/
)
```
So this will make the code minimum of 3 bytes. To make the code 2 bytes I used the `new Function(/*string*/);` constructor, but I had to be creative to access it without having to type it.
First, the [Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) constructor allows you to call it as a function omitting the new keyword, this reduce 4 bytes but it is also important for another reason. Calling the constructor as a function still returns a instance this allows us to turn `new Function(code)` to `Function(code)`. Another importante thing is that the Function constructor have a `call` method that allows you to call any function but overriding the this reference, and the Function constructor itself being a function you can call a method on it self like `Function.call(null, code)`.
All native functions are instances of the Function constructor, and all objects in javascript have a [constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor) property. So you can have access Function constructor on any native function like `alert.constructor`, and using the [call](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) method we can execute the constructor as a function. Now we have alert.constructor.call(null, code) returns a function.
combining the previous thechiniques we can turn it into `alert['constructor']['call'](null, code)`
Now we just need to find a short named function or method, so I choose the [big()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/big) method inside the String constructor. So I can access it directly from a empty string `"".big`
```
"".big.constructor.call(null, "code")();
''['big']['constructor']['call'](0,'/* code */')()
```
Then I just broke every thing in 2 bytes
] |
[Question]
[
The challenge is to list all ordered partitions (composition (combinatorics)) of a given positive integer `n`. These are the lists of numbers from `1` to `n` whose sum is `n`. For example, given input `n = 4`, the result should be:
>
> 4
>
> 1, 3
>
> 3, 1
>
> 2, 2
>
> 2, 1, 1
>
> 1, 2, 1
>
> 1, 1, 2
>
> 1, 1, 1, 1
>
>
>
The result can be in any order, but must contain each ordered partition once. This means that for `n = 4`, `[1, 1, 2]`, `[1, 2, 1]` and `[2, 1, 1]` must all be part of the result.
Here's my own JavaScript code which achieves this:
```
function range(n) {
for (var range = [], i = 0; i < n; range.push(++i));
return range;
}
function composition(n) {
return n < 1 ? [[]] : range(n).map(function(i) {
return composition(n - i).map(function(j) {
return [i].concat(j);
});
}).reduce(function(a, b) {
return a.concat(b);
});
}
```
Golfed, ES6 (**~~169~~ ~~167~~ ~~119~~ ~~109~~ ~~105~~ ~~89~~ 85 bytes**):
```
n=>n?[].concat(...[...Array(n)].map((x,i)=>i+1).map(b=>m(n-b).map(a=>[b,...a]))):[[]]
```
[Answer]
# Haskell, 37 bytes
```
f 0=[[]]
f n=[a:x|a<-[1..n],x<-f$n-a]
```
xnor saved two bytes.
[Answer]
## Python, 56 bytes
```
f=lambda n:[x+[n-i]for i in range(n)for x in f(i)]or[[]]
```
A recursive solution: The ordered partitions of `n` are a partition of some smaller `i` with `0<=i<n`, followed by the remainder `n-i` as the last element. For a base case, `n=0` only has the empty partition.
[Answer]
## Python 2, 61 bytes
```
f=lambda n,s='1,':1/n*[eval(s)]or f(n-1,'1+'+s)+f(n-1,'1,'+s)
```
This isn't the shortest, but I really like the method because it's so weird.
Recursively generates and evaluates `2**(n-1)` strings, like
```
1+1+1+1,
1,1+1+1,
1+1,1+1,
1,1,1+1,
1+1+1,1,
1,1+1,1,
1+1,1,1,
1,1,1,1,
```
for `n=4`. These strings evaluate to tuples representing all the partitions. Between any two 1's is either a `+`, joining them into a single number, or a `,`, splitting adjacent sections.
[Answer]
## JavaScript (Firefox 30-57), 63 bytes
```
f=n=>n?[for(i of Array(n).keys())for(a of f(i))[n-i,...a]]:[[]]
```
[Answer]
# Pyth, ~~7~~ 6 bytes
7 byte solution:
Pyth has an integer partition builtin `./`, so 5 of the 7 bytes is getting the orderings.
```
{s.pM./
```
[Try it online!](https://pyth.herokuapp.com/?code=%7Bs.pM.%2F&input=4&debug=0)
Explanation:
```
./ Integer partition (sorted by default)
.pM get all the orderings of each of the partitions as a nested list of lists of orderings
s Flatten by one layer
{ Remove duplicates
```
6 byte solution:
If you have a list, `./` will compute with orderings; all that remains is to make the lists numbers again.
```
lMM./m
```
[Try it online!](http://pyth.herokuapp.com/?code=lMM.%2Fm&input=4&debug=0)
Explanation:
```
m Get lists by gathering a list of [0, 1,...input] (I could use U as well)
./ Partition with orderings
MM Map an operation across each of the orderings lists of elements
l where that operation is the length of the sublists
```
[Answer]
## Mathematica, 40 bytes
```
Join@@Permutations/@IntegerPartitions@#&
```
Mathematica's built-in for integer partitions doesn't give all *ordered* partitions, so we have to generate all possible permutations of each of them, and then flatten the result.
[Answer]
# [CJam](http://sourceforge.net/projects/cjam/), ~~17~~ 14 bytes
```
ri"X)"m*{~]p}/
```
[Try it online!](http://cjam.tryitonline.net/#code=cmkiWCkibSp7fl1wfS8&input=NA)
### Explanation
[I know I said](https://codegolf.stackexchange.com/a/94162/8478) that using the Cartesian product is longer, but I ended up finding a way to use it more efficiently. I think that both approaches are interesting in their own right, so I'm putting them in separate posts.
This is still based on the idea that, we can choose `n` times between appending a `1` to the current partition or to increment the last element of the current partition. In this solution, we do this by generating 2n-1 different programs which correspond to these different choices.
```
ri e# Read input and convert to integer N.
e# Decrement.
"X)"m* e# Get all strings of length N which consist of 'X' and ')'. If
e# we treat these strings as CJam code then 'X' pushes a 1 and ')'
e# increments the top of the stack.
e# Note that some of these strings will begin with an increment that
e# doesn't have anything on the stack to work with. This will result in
e# an error and terminate the program. Luckily, the programs are ordered
e# such that all programs starting with 'X' are first in the list, so
e# we get to print all the 2^(N-1) permutations before erroring out.
{ e# For each of these programs (well for the first half of them)...
~ e# Evaluate the string as CJam code. This leaves the partition as
e# individual integers on the stack.
]p e# Wrap the stack in a list and pretty-print it.
}/
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 byte thanks to @Dennis (convert from unary `ḅ1`, rather than sum for each for each `S€€`)
```
1ẋŒṖḅ1
```
**[TryItOnline](http://jelly.tryitonline.net/#code=MeG6i8WS4bmW4biFMQ&input=&args=NA)**
How?
```
1ẋŒṖḅ1 - Main link: n e.g. 4
1ẋ - repeat 1 n times [1,1,1,1]
ŒṖ - partitions of a list [[[1],[1],[1],[1]], [[1],[1],[1,1]], [[1],[1,1],[1]],
[[1],[1,1,1]], [[1,1],[1],[1]], [[1,1],[1,1]],
[[1,1,1],[1]], [[1,1,1,1]]]
ḅ1 - from base 1 (vectorises) [[1,1,1,1], [1,1,2], [1,2,1],
[1,3], [2,1,1], [2,2],
[3,1], [4]]
```
[Answer]
# Pure Bash, 51
This is a port of [@xnor's brilliant answer](https://codegolf.stackexchange.com/a/94165/11259), using multiple levels of bash expansions to achieve the desired result:
```
a=$[10**($1-1)]
eval echo \$[${a//0/{+,']\ $[}1'}],
```
[Ideone.](https://ideone.com/vEF9fV)
* The first line is simply an arithmetic expansion to create a variable `$a` containing `1` followed by `n-1` zeros.
* The first expansion `${a//0/{+,']\ $[}1'}` replaces each `0` in `$a` with copies of the string `{+,']\ $[}1'`. Thus n=4 we get the string `1{+,']\ $[}1'{+,']\ $[}1'{+,']\ $[}1'`
* This is prefixed with `$[` and postfixed with `],` to give `$[1{+,']\ $[}1'{+,']\ $[}1'{+,']\ $[}1]`
* This is a brace expansion that expands to `$[1+1+1+1], $[1+1+1] 1, $[1+1] $[1+1], $[1+1] 1 1,...`
* This is finally arithmetically expanded to give the required result.
Careful use of quotes, backslash escaping and `eval` ensures that the expansions occur in the correct order.
[Answer]
## Ruby, 61 bytes
```
f=->n{n<1?[[]]:(1..n).map{|i|f[n-i].map{|x|x<<i}}.flatten(1)}
```
### ungolfed
```
f=->n{
n < 1 ?
[[]]
:
(1..n).map { |i|
f[n-i].map { |x|
x << i
}
}.flatten(1)
}
```
### usage
```
p f[4]
# => [[1, 1, 1, 1], [1, 1, 2], [1, 2, 1], [1, 3], [2, 1, 1], [2, 2], [3, 1], [4]]
```
[Answer]
# [Brachylog](http://github.com/JCumin/Brachylog), 20 bytes
```
~lL#++?,L:=f:{:0x}ad
```
[Try it online!](http://brachylog.tryitonline.net/#code=fmxMIysrPyxMOj1mOns6MHh9YWQ&input=NA&args=Wg)
### Explanation
This is a situation where you would think declarative languages would do well, but because of the overloading of `+` and the difficutly in writing a summing predicate which propagates constraints properly, they do not.
```
~lL L is a list of length Input
L#+ L is a list of non-negative integers
L +?, The sum of the elements of L results in the Input
L:=f Find all values for the elements of L which satisfy those constraints
:{:0x}a Remove all 0s from each sublist of the result of Findall
d Remove all duplicate sublists
```
[Answer]
## [CJam](http://sourceforge.net/projects/cjam/), 19 bytes
```
Lari{_1af.+1@f+|}*p
```
[Try it online!](http://cjam.tryitonline.net/#code=TGFyaXtfMWFmLisxQGYrfH0qcA&input=NA)
### Explanation
CJam doesn't have a useful combinatorics built-in for integer partitions. So we'll do this manually. To find all the *ordered* partitions of an integer `n`, we can look at a list of `n` ones and consider every possible way to insert separators. Then we'll sum the `1`s in each section. Example for `n = 3`:
```
1 1 1 => 3
1 1|1 => 2|1
1|1 1 => 1|2
1|1|1 => 1|1|1
```
I tried using a Cartesian product to generate all of these separators, but that ended up at 21 bytes. Instead I went back to [this old technique for generating power sets](https://codegolf.stackexchange.com/a/42325/8478) (this is based on an old answer of Dennis's but I can't find it right now). The idea is this: to generate all partitions we can start from an empty list. Then `n` times we can make a binary decision: either we append a `1` (corresponds to a separator in the above example) or we increment the last value of the list (corresponds to not having a separator). To generate all partitions, we simply perform both operations at each step and keep all possible outputs for the next step. It turns out that in CJam, prepending and incrementing the first element is shorter, but the principle remains the same:
```
La e# Push [[]] onto the stack. The outer list will be the list of
e# all possible partitions at the current iteration, and we initialise
e# it to one empty partition (basically all partitions of 0).
ri e# Read input and convert to integer N.
{ e# Repeat this N times...
_ e# Duplicate the list of partitions of i-1.
1af.+ e# Increment the first element in each of these. This is done
e# by performing a pairwise addition between the partition and [1].
e# There is the catch that in the first iteration this will turn
e# the empty array into [1], so it's equivalent to the next step.
1@f+ e# Pull up the other copy of the list of partitions of i-1 and
e# prepend a 1 to each of them.
| e# Set union. This gets rid of the duplicate result from the first
e# iteration (in all other iterations this is equivalent to concatenating
e# the two lists).
e# Voilà, a list of all partitions of i.
}*
p e# Pretty-print the result.
```
[Answer]
# T-SQL, 203 bytes
**Golfed:**
```
USE master
DECLARE @ INT=12
;WITH z as( SELECT top(@)cast(number+1as varchar(max))a FROM spt_values WHERE'P'=type),c as(SELECT a*1a,a b FROM z UNION ALL SELECT c.a+z.a,b+','+z.a FROM c,z WHERE c.a+z.a*1<=@)SELECT b FROM c WHERE a=@
```
**Ungolfed:**
```
USE master --needed to make sure it is executed from the correct database
DECLARE @ INT=12
;WITH z as
(
SELECT top(@)cast(number+1as varchar(max))a
FROM spt_values
WHERE'P'=type
),c as
(
SELECT a*1a,a b
FROM z
UNION ALL
SELECT c.a+z.a,b+','+z.a
FROM c,z
WHERE c.a+z.a*1<=@
)
SELECT b
FROM c
WHERE a=@
```
**[Fiddle](https://data.stackexchange.com/stackoverflow/query/542961/list-all-ordered-partitions-of-n)**
[Answer]
# Mathematica 10.0, 44 bytes
An attempt without using partition-related builtins. From each ordered partition of size *k*, two successor partitions of *k + 1* are generated: one by prepending 1, and the other by incrementing the first value.
```
Nest[##&[{1,##},{#+1,##2}]&@@@#&,{{1}},#-1]&
```
A funnier, but sadly 2 bytes longer way of implementing the same idea:
```
#@{1}&/@Tuples[Prepend[1]@*MapAt[#+1&,1],#-1]&
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~14~~ 12 bytes
Saved 2 bytes thanks to [Adnan](https://codegolf.stackexchange.com/users/34388/adnan)
```
>G¹LNãvyO¹Q—
```
**Explanation**
```
>G # for N in range(1..input)
¹L # range(1, input)
Nã # cartesian product with N (all combinations of length N)
v # for each resulting list
yO¹Q— # if it's sum equals the input print it
```
[Try it online!](http://05ab1e.tryitonline.net/#code=PkfCuUxOw6N2eU_CuVHigJQ&input=NA)
The corresponding solution is 2 bytes shorter in **2sable**.
# [2sable](http://github.com/Adriandmen/2sable), 10 bytes
```
>GLNãvyOQ—
```
[Try it online!](http://2sable.tryitonline.net/#code=PkdMTsOjdnlPUeKAlA&input=NA)
[Answer]
## Haskell, 41 bytes
```
f 1=[[1]]
f n=do a:b<-f$n-1;[1:a:b,a+1:b]
```
Not the shortest Haskell solution, but I like that it doesn't use `[..]` ranges. Instead, it recursively computes the partitions of `n` as the partitions of `n-1` with either a new 1 at the start or the first value one higher. This makes explicit why there's `2^(n-1)` of them.
[Answer]
# Mathematica, 53 bytes
Doesn't beat Martin Ender's answer, which uses the built-in `IntegerPartitions` function (and built-ins are totally fine by me). (Nor does it beat feersum's answer, which I didn't see until too late.) But I wanted to practice a golfed recursive function.
```
If[#<1,{{}},Join@@Table[#~Append~j&/@#0[#-j],{j,#}]]&
```
Recursively generates all compositions, by generating all possible final numbers `j` and then calling itself on `#-j` where `#` is the input.
[Answer]
## [Retina](http://github.com/mbuettner/retina), 32 bytes
Byte count assumes ISO 8859-1 encoding.
```
.+
$*
+%1`1
!$'¶$`,!
!+
$.&
A`^,
```
[Try it online!](http://retina.tryitonline.net/#code=LisKJCoKKyUxYDEKISQnwrYkYCwhCiErCiQuJgpBYF4s&input=NQ)
### Explanation
This works similar to my [CJam answer](https://codegolf.stackexchange.com/a/94171/8478). We go through a list `N` ones and at each position we take both branches of the binary decision a) increment the last value or b) start a new value at 1.
**Stage 1**
```
.+
$*
```
Convert the input to unary.
**Stage 2**
```
+%1`1
!$'¶$`,!
```
The `+` tells Retina to execute this stage in a loop until the output stops changing. The `%` tells it to split the input into lines before applying the stage and join them back together afterwards. By putting the `%` after the `+`, Retina splits and rejoins after each iteration. One iteration of the stage makes one of those decisions I mentioned and thereby bifurcates the current set of partitions.
How it actually works is that it matches a `1` (but only the first one as indicated by the `1` in front of the backtick), and replaces it with `!` (which we'll use as the unary digit of our output), followed by the remaining `1`s on this row (this increments the last value). Then on another line (`¶`) it prints the prefix of the current line, followed by `,!`, which inserts a separator and then starts the next value at `1`.
**Stage 3**
```
!+
$.&
```
This converts the runs of `!` to decimal integers by replacing them with their length.
**Stage 4**
```
A`^,
```
And finally, we notice that we've generated twice as many lines as we wanted, and half of them start with a `,` (those where we initially made the decision of splitting, even though there wasn't anything to split after yet). Therefore, we discard all lines that start with a `,`.
[Answer]
# Perl, 44 bytes
Includes +3 for `-n` (code uses `$'` and `$0` so it can't be run as a `-e` commandline)
Give number to partition on STDIN:
```
partitions.pl <<< 4
```
`partitions.pl`
```
#!/usr/bin/perl -n
$_=$&-$_.",$_$'",do$0for/\d+/..$&-1;print
```
If you don't mind extra spaces at the end of a line and an extra newline this 42 byte solution works too (run as `perl -M5.010 partitions.pl`):
```
#!/usr/bin/perl -n
$_=$`-$_." $_ $'",do$0for/\s/..$_-1;say
```
[Answer]
## Julia, 113 Bytes
```
f(N)=unique(reduce(vcat,(map(x->[permutations(x)...],[vcat([1 for _=i+1:N],sum([1 for _=N-i:N-1])) for i=1:N]))))
```
Non-recursive solution
**Explained:**
1. `[vcat([1 for _=i+1:N],sum([1 for _=N-i:N-1])) for i=1:N]` build a set of lists that sum to N, whose permutations will resemble the solution (e.g. for N=4: [[1,1,1,1],[1,1,2],[1,3],[4]])
2. `map(x->[permutations(x)...],)` Calculate all permutations
3. `reduce(vcat,)` combine them into a list of lists
4. `unique()` filter duplicates
[Answer]
# [MATL](http://github.com/lmendo/MATL), 15 bytes
```
:"G:@Z^t!XsG=Y)
```
[Try it online!](http://matl.tryitonline.net/#code=OiJHOkBaXnQhWHNHPVkp&input=NA)
### Explanation
Given input `n`, this computes the Cartesian power with increasing exponents `k` from `1` to `n`; and for each exponent `k` selects the tuples that have a sum equal to the input.
```
: % Take input n implicitly and push range [1 2 ... n]
" % For each k in that range
G: % Push [1 2 ... n] again
@ % Push k
Z^ % Cartesian power. Gives 2D array, say A, with each k-tuple in a row.
t % Duplicate
! % Transpose
Xs % Sum of each column. Gives a row vector
G= % True for entries that equal the input
Y) % Use as logical vector into the rows of array A
% End implicitly
% Display stack implicitly
```
[Answer]
# Lua 214 203 182 bytes
```
function g(m, l, n,c)for i=1,m do if i+n < m then l[#l+1]=i;g(m,l,n+i,c+1)elseif i+n == m then l[#l+1]=i;print(unpack(l))end end for k=c,#l do l[k]=nil end end g(io.read()*1,{},0,0)
```
Ungolved version.
```
function g(m, l, n,c)
for i=1,m do
if i+n < m then
l[#l+1]=i
g(m,l,n+i,c+1)
elseif i+n == m then
l[#l+1]=i
print(unpack(l))
end
end
for k=c,#l do
l[k]=nil
end
end
g(io.read()*1,{},0,0)
```
Found a stray whitespace and removed an unnecessary variable to safe 11 bytes.
as it turns out, table.insert() is byte inefficient
[Answer]
# PHP, 125 Bytes
```
for($i=$n=$argv[1];$i<=str_repeat(1,$n);$i++)if(array_sum($a=str_split($i))==$n&!strpos($i,"0"))$r[]=$a;echo json_encode($r);
```
-4 Bytes for `print_r($r);` instead of `echo json_encode($r);` for the output
a recursive solution with 250 Bytes
```
function f($n){global$a;foreach($a as$x)foreach(range(1,$n)as$y)$a[]=array_merge((array)$x,[$y]);if(--$n)f($n);}$a=range(1,$w=$argv[1]);f($w-1);foreach($a as$z)if(array_sum((array)$z)==$w)$c[join("-",(array)$z)]=$z;echo json_encode(array_values($c));
```
[Answer]
## Prolog, 81 bytes + 6 bytes to call
```
L*L.
[H|T]*L:-H>1,M is H-1,[M,1|T]*L.
[H,K|T]*L:-H>1,M is H-1,N is K+1,[M,N|T]*L.
```
[Try it online!](http://swish.swi-prolog.org/p/PCG%3A%20partitions.pl)
Call with `[4]*L.`, repeat with `;` until all solutions have been presented.
Alternatively, if repeatedly pressing `;` is not okay (or should be added to the byte count), call with `bagof(L,[4]*L,M).` which adds 17 bytes for the call.
[Answer]
# [J](http://jsoftware.com/), ~~30~~ 26 bytes
```
#&1<@(+/;.1)~2#:@(+i.)@^<:
```
Works by splitting the list of unary *n* by using the binary values of 2*n*.
[Try it online!](https://tio.run/nexus/j#@5@mYGuloKxmaOOgoa1vrWeoWWekbAVkZ@ppOsTZWHFxpSZn5CukKRjCGEYwhjGMYfL/PwA "J – TIO Nexus")
## Explanation
```
#&1<@(+/;.1)~2#:@(+i.)@^<: Input: n
<: Decrement n
2 ^ Compute 2^(n-1)
( )@ Operate on that
i. Make the range [0, 1, ..., 2^(n-1)-1]
+ Add 2^(n-1) to each in that range
#:@ Convert each in that range to binary
#&1 Make n copies of 1 (n in unary)
( )~ Operate over each row on RHS and unary n on LHS
;.1 Chop unary n starting at each 1
+/ Reduce by addition on each chop
<@ Box the sums of each chop
```
[Answer]
# Actually, ~~17~~ 16 bytes
This answer is partially based on [Luis Mendo's MATL answer](https://codegolf.stackexchange.com/a/94152/47581). Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=O-KVl1Jg4pWcUuKImWlgTWDOo-KVnD1g4paR&input=NA)
```
;╗R`╜R∙i`M`Σ╜=`░
```
**Ungolfing**
```
Implicit input n.
;╗ Duplicate n and save a copy of n to register 0.
R Take the range of [1..n].
`...`M Map the following function over the range. Variable k.
╛R Push n from register 0 and take the range [1..n] again.
∙ Take the k-th Cartesian power of the range.
i Flatten that product.
`...`░ Push values of the previous map where the following function returns a truthy value.
Variable L.
Σ Push sum(L).
╜ Push n from register 0.
= Check if sum(L) == n.
Implicit return.
```
[Answer]
# Actually, ~~17~~ ~~16~~ 15 bytes
This is an interesting fork of [Martin Ender's CJam answer](https://codegolf.stackexchange.com/a/94171/47581) (the one with the Cartesian product), with a difference in implementation that I thought was interesting. When one of Martin's strings start with an increment, the errors prevent that string from being evaluated. In Actually, the error is suppressed and the string is evaluated anyway. This ends up giving the compositions of every `k` in the range `[1..n]`.
Rather than try to remove the extra compositions, I took the `n-1`th Cartesian power of `"1u"` appended a `"1"` to the beginning of each string. This trick gives only the compositions of `n`. It is, unfortunately, longer than Martin's answer.
Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=RCIxdSLiiJlgMUDOo8KjxpJrYE0&input=NA)
```
D"1u"∙`1@Σ£ƒk`M
```
**Ungolfing**
```
Implicit input n.
D Decrement n.
"1u"∙ Take the (n-1)th Cartesian power of the string "1u".
In Actually, 1 pushes 1 to the stack and u is increment.
`...`M Map the following function over the Cartesian power. Variable s.
1@ Push a 1 to be used later.
Σ Summing a list of chars joins the chars into one string.
£ƒ Turn s into a function and call it immediately on the 1 in the stack.
k Take the whole stack and wrap in a list. This is a composition of n.
Implicit return.
```
] |
[Question]
[
### Your task
Given two positive integers \$x\$ and \$d\$ (such that \$d<x\$), output the 5th term of the \$d\$th difference of the sequence \$n^x\$
### Example
Let's say we are given the inputs \$x=4\$ and \$d=2\$.
First, we get the series \$n^4\$:
* \$0^4 = 0\$
* \$1^4 = 1\$
* \$2^4 = 16\$
* \$3^4 = 81\$
* ...
These are the first 10 elements:
```
0 1 16 81 256 625 1296 2401 4096 6561
```
Now we work out the differences:
```
0 1 16 81 256 625 1296 2401 // Original series
1 15 65 175 369 671 1105 // 1st difference
14 50 110 194 302 434 // 2nd difference
```
Finally, we get the 5th term (1-indexed) and output:
```
302
```
Note: this is [sequence](/questions/tagged/sequence "show questions tagged 'sequence'"), so as long as the 5th term is somewhere in your output, it's fine.
### Test cases
```
x d OUTPUT
4 2 302
2 1 9
3 2 30
5 3 1830
```
[This Python program](https://tio.run/##Vcs7DoMwEEXRnlVMh40cKQSlQcoqUiIK80nigsEy5pfNOzOWUET73j12958RizDAAwx6YdDOXkgZNA0VQpbBAK/RAdINTuO7F/lV1ol1nKfP3pl@KlMFWiZJw2iHC2zRbAp2Zl9jhaaiysv6T/PJs2vItexWckt0i4L1cA0VZ3fDjl1LrmM3k/PReQXz4Voqzq5w0XUyhPsP) can be used to get the first three differences of any power series.
### Rules
* **This is [sequence](/questions/tagged/sequence "show questions tagged 'sequence'"), so the input/output can be in any form.**
* **This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins!**
[Answer]
# [R](https://www.r-project.org), ~~26~~ 24 bytes
```
\(x,d)diff((0:5^d)^x,,d)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMH6gvzy1KL44tTC-JTMtDTbpaUlaboWO2I0KnRSNEEiGhoGVqZxKZpxFTpAEYj0zXhUXRoVtiY6KbZGmlwY4kZAcUMs4sY41JsCxY2h1ixYAKEB)
Returns the first `5^d-d+1` elements (which is always ≥5) of `d`-th differences.
Obviously, for `d`>1 this includes a lot of unneccessary differences, but simply returning the first 5 elements is ~~2~~ 1 byte\* longer: `\(x,d)diff((-d:4+d)^x,,d)` ([Attempt it here](https://ato.pxeger.com/run?1=m72waMH6gvzy1KL44tTC-JTMtDTbpaUlaboWO2M0KnRSNEEiGhq6KVYm2imacRU6QCGI_M14VG0aFbYmOim2RppcGOJGQHFDLOLGONSbAsWNodYsWAChAQ)).
\*Thanks to pajonk
[Answer]
# [Python](https://www.python.org), 53 bytes
```
f=lambda x,d,b=4:d and f(x,d-1,b+1)-f(x,d-1,b)or b**x
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PYxNCoMwEEb3OcW3KSQ2Fn_BCvYuCWmoEJOgKdizdOOmvZO3aVDpZob3mHnvr3-Fh7PL8nkGnTZrrTsjBqkEZq647KpWQVgFTSOnOZfnnKV_YG6ETJL5eL7pyAa9hfN3SzPWki3j0GEQnvY2cHOZvOkDZYzAj9HQrca4Y3tlWU8VUABlVpC4cuBKysOQOs7omjLbr38)
Straight-forward recursion.
# [Python](https://www.python.org) + NumPy, 50 bytes using builtin `diff`
```
lambda x,d:diff(r_[4:5+d]**x,d)
from numpy import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LYxLCsIwAET3OcVshKRGqa2FWqgXUZFKDQbyI6Zgz-KmIHqn3saUdjMDj5n3_rk-PKwZPqI-f7sgNuWYqUbf2gYv3latFIL662lfFev2kiSRMSK81TCddj2kdtaHZHkehfVQkAbW3Q1NWUUmC7eooRtHpQlcbZ9OyUAZI3A-EiroZOWWzZZhXO2BDMjTjMTaAQeSL4QUMSMr83Re_wE)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~7~~ 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
∞ImIF¥
```
-1 byte thanks to *@TheThonnu*
Outputs the infinite sequence minus the first item. Inputs in the order \$x,d\$.
[Try it online.](https://tio.run/##yy9OTMpM/f//Ucc8z1xPt0NL//834TICAA)
**Explanation:**
```
∞ # Push the infinite sequence of positive integers: [1,2,3,...]
Im # Takes each to the power of the first input
IF # Loop the second input amount of times:
¥ # Get the deltas/forward-differences of the infinite list
# (after which the infinite list is output implicitly)
```
Outputting the \$5^{th}\$ term would be 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) instead by adding a trailing `}3è` (close the loop and get the 0-based 3rd item).
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 112 bytes
```
j;i;*v;f(x,d){v=calloc(d+9,8);for(i=0;i<d+5;)v[i++]=pow(i,x);for(;d--;)for(j=0;j++<i;)v[j-1]-=v[j];x=abs(v[4]);}
```
[Try it online!](https://tio.run/##bZFhb4IwEIa/@ysuJCZF2gxFE01lX5b9CiULa4srQzCUYTPDXx87BIwua9Kjfd/n2t4h2EGItk255rOaJ8RS6V7qUMRZVggivQ1duzwpSqJDn@ut9FbcrXfa86LwVJyJpra3uWSMu90qRTD1vK3uwJTNIxbiN@I2jN8NqXfLyOVNq/MKjrHOiQuXCeDohEqZ6s3uIgjhsqSwoBBQWDX8EZA9gO68Z@4AZU9KVGpAAh/tDRI@suvAH0BR5KYC8RGXM4xKfKqy5529fV3s7eYF58qhcL8PnCEbawTS3aVzqSym@XxYbsHob1UkZHyFC0@jNLtpHDzvyo@Vj2/vzho6cPUj/mDL0Zb/2gbt/vc96gr1W1f@Jp5KRBLiTCWFqQT23MWp2edYvKWAqqG3FpkwVNHd6UmpFKkHobnGUlVfZY4dmTTtj0iy@GBadm5ZdvwF "C (gcc) – Try It Online")
*This works on my machine with gcc version 13.0.0 but the return fails on TIO.*
# [C (gcc)](https://gcc.gnu.org/), ~~66~~ 60 bytes
```
q;f(x,d){q=x;g(d,4);}g(d,b){d=d--?g(d,b+1)-g(d,b):pow(b,q);}
```
[Try it online!](https://tio.run/##bZHtaoMwFIb/9yoOQiG2CbO1hXWZ24@xq5hl2CQ6WavWOBom3vrcUaO0Y4GcJO/7nHycCJYI0bZnHhNDpVufA8MTIunG5U03HtxaBpKx536xXLlsUB@K/EIO9IxYm2YVnKI0Iy7UM8DWCZXS1bt520MA9YbCmoJPYdvwW0AOALqrgbkClCmUqJRFfA/tHRIesve@Z0GRZ7oC8RGVC4xKfKpy4J3QvK5Ds3vBvnUoXK99x2bHeQmkOyvNpDKY5nE7fQSdfqs8JuMtXLgbpcWkcVgue358@Xj3bi9bgd7f8xtbjrb819ZoD/9xqyvUp6r8TSxKRGLizCWFuQT21MW5DjN8vKGAqqZTiXQQqL3dveljqaqvMsMCzJr2R8THKNEtu7TsePoF "C (gcc) – Try It Online")
*Port of [loopy walt](https://codegolf.stackexchange.com/users/107561/loopy-walt)'s [Python answer](https://codegolf.stackexchange.com/a/253999/9481)*
*Saved 6 bytes thanks to the man himself [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!!*
Inputs \$x\$ and \$d\$.
Returns the \$5^\text{th}\$ term of the power sequence difference.
[Answer]
# Java, ~~127~~ 90 bytes
```
x->d->g(x,d,4)double g(int x,int d,int k){return d>0?g(x,--d,k+1)-g(x,d,k):Math.pow(k,x);}
```
-37 bytes porting [*@loopyWalt*'s Python answer](https://codegolf.stackexchange.com/a/253999/52210)
Outputs the \$5^{th}\$ term like the test cases, except as double instead of int.
[Try it online.](https://tio.run/##jVA9b4MwEN3zK05MtrCt5qNLaOhSVeqQKWPVwcWGGohBcCSOIn47NRSpdOvy/J7f3T2fc3mRPFfFkJSybeEojb2vAHJ/LTo0pUg7m6CprHidydObRZ3phv2v6KXqPksdx5DCYXA8VjzOiGOK7WikJg8yYiyCYyOqCQt6bzR2jQUVPzyP9ZwrVoRryn@aC7o/SvwSdXUlBXM06geA2k8zCbQo0R@Xyig4@33ICRtjs/cPScfVAFC3SHZsQ6NfuWHrpdz@dR/ZdpL9ysNy/uQuXj8nnG4t6rOoOhS1z8bSksAdgtCFAQPliQqDPQSh1dfpywkVqZB1Xd6IozNRdI7sh28)
**Explanation:**
```
x->d-> // Method with two integer parameters and double return-type
g(x,d,4) // Call the recursive method below with k=4
double g(int x,int d,int k){
// Recursive method with three integer parameters and double return
return d>0? // If `d` is not 0:
g(x,--d,k+1) // Do a recursive call with x, d-1, k+1
-g(x,d,k) // Subtract a recursive call with x, d-1, k
: // Else:
Math.pow(k,x);} // Calculate `k` to the power `x`
// (which results in a double, hence the double return-type)
```
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 43 bytes
```
f(n,d)=polylog(-n,x)*(1-x)^d%x^(d+=5)\x^d--
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWN7XTNPJ0UjRtC_JzKnPy0zV083QqNLU0DHUrNONSVCviNFK0bU01YyriUnR1oVo8EgsKcio1EhV07RQKijLzSoBMJRBHSSE5MSdHI01HIVFTU0chOtpER8EoFsgw0lEwBNHGUL6pjoJxbKwmxDyYUwA)
Using the polylogarithm \$\operatorname{Li}\_{s}(x) = \sum\_{k=1}^\infty\frac{x^k}{k^s}\$. When \$s=-n\$, this is the generating function of the sequence \$1^n, 2^n, 3^n, \dots\$. Taking the \$d\$th difference is just multiplying the generating function by \$(1-x)^d\$.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes
```
Þ∞$e$(¯
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyLigKYiLCIiLCLDnuKIniRlJCjCryIsIiIsIjRcbjIiXQ==)
"Make infinite lists of numbers a digraph" they said. "It doesn't need to be 1 byte" they said. Well look where that got us :p. Could be 6 bytes in 2.4.1 but I don't know if it actually prints.
## Explained
```
Þ∞$e$(¯
Þ∞$e # [1 ** x, 2 ** x, 3 ** x, ...]
$( # d times:
¯ # deltas
```
[Answer]
# Excel (ms365), 143 bytes
```
=INDEX(REDUCE((ROW(1:1048576)-1)^A2,SEQUENCE(B2),LAMBDA(a,b,HSTACK(a,LET(c,TAKE(a,,-1),d,FILTER(c,ISNUMBER(c)),DROP(d,1)-DROP(d,-1))))),5,B2+1)
```
[](https://i.stack.imgur.com/FilTp.png)
* `ROW(1:1048576)-1)^A2` - 1st Parameter in `REDUCE()` to have our 'n' thus 'infinite' (as many rows as possible in Excel) to the power of x;
* `SEQUENCE(B2)` - The 2nd parameter of `REDUCE()` will tell the function to loop d-times;
* `LAMBDA(a,b,HSTACK(a,LET(c,TAKE(a,,-1),d,FILTER(c,ISNUMBER(c)),DROP(d,1)-DROP(d,-1))))` - The lambda helper function will keep pushing new columns with the difference between each value and it's predecessor;
* The above is wrapped into `INDEX()` to grab the 5th element from the latest column.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 9 bytes
```
.+F^Rvz+5
```
[Try it online!](https://tio.run/##K6gsyfj/X0/bLS6orErb9P9/Yy5TAA "Pyth – Try It Online") or [Test suite.](https://pythtemp.herokuapp.com/?code=.%2BF%5ERvz%2B5&test_suite=1&test_suite_input=2%0A4%0A%0A1%0A2%0A%0A2%0A3%0A%0A3%0A5%0A&debug=0&input_size=3 "Pyth – Try It Online")
Input is in the form \$d\$ then \$x\$. Returns the first \$5\$ terms of the sequence.
**Explanation:**
```
.+F^Rvz+5QQ # Whole program. Implicit input Q (as d) added
R # right map with lambda taking one argument:
^ # using exponentiation
z # the second input (x)
v # evaluated
+5Q # into implicit range(5 + d)
F # repeat the function
.+ # deltas
Q # d times
```
[Answer]
# JavaScript (ES7), 38 bytes
Expects `(x)(d)`. Same recursion as [loopy walt in Python](https://codegolf.stackexchange.com/a/253999/58563).
```
x=>g=(d,k=4)=>d--?g(d,k+1)-g(d,k):k**x
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/C1i7dViNFJ9vWRNPWLkVX1z4dxNM21NQFMzStsrW0Kv4n5@cV5@ek6uXkp2ukaZhoahhpairo6ysYGxhxocoZaWoYQuQs0WSMkXShSZlqAmXBUoYWxgb/AQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~28~~ 27 bytes
```
NθNη≔E⁺⁵ηXιθζFηUMζ⁻κ§ζ⊖λI⊟ζ
```
[Try it online!](https://tio.run/##TYuxDoIwFEV3vuKNr0ldjE5MBBcGSH@hQpXG9hXaooafr4/Nu52bc8ZZxzFoV0pHy5aHzd9NxFXU1T/PzE1K9knY6wWV2xJeJcxCggofFqyEVTDtLD5CBC6AzTZ4r2nCXUJviaOXhCZ3NJnv8d3MGI03lM2ETvDqSkVLGVudMqqw4H6cpVyqczm93Q8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
NθNη
```
Input `x` and `d`.
```
≔E⁺⁵ηXιθζ
```
Generate `d+5` `x`th powers.
```
FηUMζ⁻κ§ζ⊖λ
```
Generate differences `d` times.
```
I⊟ζ
```
Output the last difference (which is now the fifth).
[Answer]
# [sclin](https://github.com/molarmanful/sclin), 29 bytes
```
$W rev ^"."itr
2%`",_ - _"map
```
[Try it here!](https://replit.com/@molarmanful/try-sclin) Takes input *n* and returns an infinite list of infinite lists starting from *d* = 0.
For testing purposes:
```
5 ; >kv ( ,_ 10tk >A swap >o ": ">o f>o ) map 10tk >A
$W rev ^"."itr
2%`",_ - _"map
```
## Explanation
Prettified code:
```
$W rev ^ \; itr
2%` ( ,_ - _ ) map
```
Assuming input *d* and *n*.
* `$W` infinite range [0, ∞)
* `rev ^` i.e. `range ^ n`
* `\; itr` successively apply next line to create infinite list
+ `2%`` sliding pairs
+ `( ,_ - _ ) map` difference of each pair
[Answer]
# [Desmos](https://www.desmos.com/), ~~44~~ 43 bytes
-1 byte thanks to Aiden Chow
```
f(n,d)=∑_{k=0}^d(-1)^{d-k}nCr(d,k)(k+4)^n
```
[View it on Desmos.](https://www.desmos.com/calculator/higqk4tdcd)
Takes `n` and `d` as the inputs to a function `f`.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 70 bytes
```
->x,d{s=(0..5**d+x).map{_1**x}
d.times{s=s.each_cons(2).map{_2-_1}}
s}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY33XTtKnRSqottNQz09Ey1tFK0KzT1chMLquMNtbQqarlS9Eoyc1OLgQqK9VITkzPik_PzijWMoGqMdOMNa2u5imuhpikXKLhFm-gYxXKBGEY6hhCGMUzEVMc4FqJ0wQIIDQA)
[Answer]
# [Clojure](https://clojure.org/), 69 bytes
```
#(nth(iterate(fn[x](map -(rest x)x))(for[i(range)](Math/pow i %)))%2)
```
[Try it online!](https://tio.run/##HYzNCsIwEAbveYoPpLB7ELHVx/AJlj0Eu7H1J6lpxLx9LF6Gucxcn@n@ydZotIDQdhTLRHOx7ItRiFKVXn7BnrKtBZUrM4WUZabs481Y6eLLdFjSFzM6Zu56buxoTKu9RSpGhTg5oVcnPY4bh7@fMahTdbTkCCr@YTiDArZiu3D7AQ "Clojure – Try It Online")
Returns the entire (lazy) sequence.
# [Clojure](https://clojure.org/), ~~82~~ 75 bytes
```
#(nth(nth(iterate(fn[x](map -(rest x)x))(for[i(range)](Math/pow i %)))%2)4)
```
[Try it online!](https://tio.run/##HYtBCsIwEEX3OcWAFGYWIqb1GJ5gmEUwExvRpKYp5vaxdPEfb/H@451fW9GOXgOEfsJU52OxanFVMSRugh@3wBmLrhUaNSIMuXDE4tJTSfDu6nxZ8g8iDEQ0WJqok0GfV/0yN/ACbHgCK4YtXHeOh99gFCNicCkJMMBe7v/@Bw "Clojure – Try It Online")
Returns specifically the 5th term of the sequence.
[Answer]
# [J](https://www.jsoftware.com), ~~19~~ 16 bytes
```
2&(-~/\)i.@+&5^]
```
Takes inspiration from [Jelly](https://codegolf.stackexchange.com/a/254014/110888). Accepts `d` as the left arg and `x` as the right arg.
-3 bytes thanks to [Jonah](https://codegolf.stackexchange.com/users/15469/jonah)
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxwUhNQ7dOP0YzU89BW800LhYifNNOkys1OSNfQT1FoUJdx8dNR11XV1cdIqahZKWjrqBrp6Cuo2TlkKavqWanYKRgYm2oYGRtpGBsbaxgCjFlwQIIDQA)
```
2&(-~/\)i.@+&5^]
i.@+&5^] NB. dyadic fork
] NB. returns right arg
i.@+&5 NB. atop, +&5 adds five to left arg, i. creates a range 0..n-1
^ NB. raises each item of the range to y
2&(-~/\) ... NB. dyadic hook
2&(-~/\) NB. 2 -~/\ y computes the delta of adjacent elements
NB. ~ is necessary to flip the args since, for example, 1-16=_15
NB. x(n&u)y is a special form of ^:, it is equivalent to
NB. n&u^:x y, which applies n&u to y x times
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 27 bytes
```
\!\(\_{i,#2}i^#\)/.i->4&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P0YxRuP9pCUx8dWZOspGtZlxyjGa@nqZunYmav8DijLzSqKVde3SHByUY9XqgpMT8@qquUwUahSMdLiMgJShDpcxhGcKpIy5av8DAA "Wolfram Language (Mathematica) – Try It Online")
The private-use character `` is [`\[DifferenceDelta]`](https://reference.wolfram.com/language/ref/DifferenceDelta.html).
This character has code point `U+F4A4`, which is different from what the documentation (as of current writing) claims it to be. `U+2206`, the code point in documentation, corresponds to the similar-looking `\[Laplacian]`/`∆` (undocumented).
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~9~~ 7 bytes
*Edit: saved 2 bytes by outputting an infinite list of infinite lists, instead of just the `d+1`-th infinite list*
```
¡Ẋ-m^⁰N
```
[Try it online!](https://tio.run/##yygtzv6v@Kip8dCmR22THjVu@H9o4cNdXbq5cUC23////03@GwEA "Husk – Try It Online")
Returns an infinite list of infinite lists of differences of `x`-th powers.
The header in the TIO link extracts the `d+1`-th element of this, which is the infinite list of `d`-th differences.
```
m # map over
N # all integers 1..infinity
^⁰ # getting their x-th powers;
¡ # now, make an infinite list of infinite lists by repeatedly
Ẋ- # taking pairwise differences;
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 6 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
úr▬kÄ│
```
Inputs in the order \$d,x\$. Outputs a list of the first \$10^{d}-d\$ amount of values, which gives a minimum of 9 terms (for \$d=1\$), including the \$5^{th}\$ term.
[Try it online.](https://tio.run/##y00syUjPz0n7///wrqJH09ZkH255NKXpf8F/IwUTLkMFIy4jBWMuYwVTAA)
**Explanation:**
```
ú # Push 10 to the power the first (implicit) input-integer `d`
r # Pop and push a list in the range [0,10ᵈ)
▬ # Take each value to the power of the second (implicit) input `x`
k # Push the first input `d` again
Ä # Loop that many times, using 1 character as inner code-block:
│ # Get the forward-differences of the list
# (after which the entire stack is output implicitly as result)
```
A trailing `4§` (get 0-based 4th item) can be added to only output the \$5^{th}\$ term: [try it online](https://tio.run/##y00syUjPz0n7///wrqJH09ZkH255NKXJ5NDy//@NFEy4DBWMuIwUjLmMFUwB).
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 13 bytes
```
:e…⟪¤*⟫¦@'ọ&e
```
[Try it online!](https://tio.run/##ASIA3f9nYWlh//86ZeKApuKfqsKkKuKfq8KmQCfhu40mZf//NAoy "Gaia – Try It Online")
I finally figured out how to do for loops in Gaia! Outputs approximately (10\*\*x)-d terms (I think)
## Explained
```
:e…⟪¤*⟫¦@'ọ&e
:e… # Push range(0, x ** 10) to the stack
⟪¤*⟫¦ # and raise each item in that range to the power of x
@'ọ& # Repeat the string "ọ" d times (ọ is the deltas/forward differences command)
e # and execute that as Gaia code
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
+5Ḷ*I⁸¡
```
A dyadic Link that accepts \$d\$ on the left and \$x\$ on the right and yields a list of the first five terms.
**[Try it online!](https://tio.run/##y0rNyan8/1/b9OGObVqejxp3HFr4//9/o/8mAA "Jelly – Try It Online")**
### How?
```
+5Ḷ*I⁸¡ - Link: integer, d; integer, x
+5 - (d) add five -> d+5
Ḷ - lowered range -> [0,1,2,...,d+4]
* - exponentiate (x) -> [0^x,1^x,2^x,...,(d+4)^x]
¡ - repeat...
⁸ - ...times: chain's left argument -> d
I - ...action: deltas
```
[Answer]
# [Perl 5](https://www.perl.org/), 65 bytes
```
sub f{my($x,$d,$p)=(@_,4);$d?f($x,--$d,$p+1)- f($x,$d,$p):$p**$x}
```
[Try it online!](https://tio.run/##RY1BC4JAEIXv/oohJnRthUqNSpa6B3npViGUuxKVLmqwIf52Gy3o9N73vYHRsnyEXVe9LqCa59tBwzHlqJlwtgkPWITpRvXW8wY/mTEP1P9sjdp10bSdKkrHAjgGHOYc/On8zHukPuOw@oL/274UUqV1OTBrSP3/Sya2mESDw0z8HrJe6PKW12o09hYVABiBhiIVmFJIo@W1lkSSKCtqgdkpH3FAKajCBuzibsMa7H18gHhnR1bbfQA "Perl 5 – Try It Online")
[Answer]
# [Factor](https://factorcode.org/), 54 49 47 bytes
```
[ dup 5 + iota rot v^n [ differences ] repeat ]
```
Returns the first 5 elements of the sequence.
[Try it online!](https://tio.run/##Pc/LCsIwEAXQfb/iuhaKtgo@wK24cSOupEKoUw1tk5hMC1r67TV94OzmcAfuZCJlbbvr5XQ@7iCc06lDKfgFR@@KVEoOOVlFxaBhTX1@jISOBUvH0p88SZEVhfx60crBWGL@GCsVYx8ETQA/DVaI0GKGeBFNEmE5yHba439igrWnHpYbT213w6MyHueQmgWsZtR3Bc8yy8iOjRNYMiQYSZeNTx1KYeD7pnnY/QA "Factor – Try It Online")
```
! 4 2
dup ! 4 2 2
5 ! 4 2 2 5
+ ! 4 2 7
iota ! 4 2 { 0 1 2 3 4 5 6 }
rot ! 2 { 0 1 2 3 4 5 6 } 4
v^n ! 2 { 0 1 16 81 256 625 1296 }
[ differences ] repeat ! { 14 50 110 194 302 }
```
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), ~~8~~ 7 bytes (14 nibbles)
```
`..,~^$@!>>$@-
```
Function that returns an infinite list of infinite lists of all differences of the `x`-th powers of all integers:
```
=@`..,~^$@!>>$@-
,~ # make a list 1..infinity
. # and map over each number
^$ # raising it to
@ # the arg1-th power;
`. # now iteratively apply this function:
! # zip together
>>$ # this list without the first element
@ # with itself
- # by subtraction (so: get differences)
```
To only output the `d`-th differences (as shown in the screenshot below) costs 1 byte (2 nibbles) more:
```
= # get the list at index
@ # arg2
```
[](https://i.stack.imgur.com/AkEkI.png)
[Answer]
# [MATLAB](https://www.gnu.org/software/octave/), 45 bytes
```
function f(x,d)
y=diff((0:5*d).^x,d);y(5)
end
```
Uses built-in diff function with the dth difference argument, outputs the fifth index of the resulting array.
[Try it online!](https://tio.run/##y08uSSxL/f8/rTQvuSQzP08hTaNCJ0WTq9I2JTMtTUPDwMpUK0VTLw4kaF2pYarJlZqX8v8/AA "Octave – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 50 bytes
can someone get rid of `iterate`?
```
x!d=iterate(zipWith(-)=<<tail)[n^x|n<-[0..]]!!d!!4
```
[Try it online!](https://tio.run/##LYxBCsIwFET3nmKyS@C31LaCQuMNXLuoVQINNJiGErMo4t3jx7qbN2@Yybye1vucVzFql2w0ycq3W64uTbJQuuuScV714b5@Qlf0VVkOgxCjEG2ejQvQmM1yeUDe5EojWYXiDG8TIis@BW@W6ELCz0fiXsMqtUMP2RJqQlPVjATJeU84bdD83UYHjmyPPx7yFw "Haskell – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 47 bytes
```
r x 0 i=i^x
r x d i=(r x(d-1)(i+1))-(r x(d-1)i)
```
[Try it online!](https://tio.run/##VYu7CoAwEAR7v2LLHCKYGEGL/IoQiOBhfKAW/n08LYR0szPs5M95jDGlAzdqsOPhLl4OwkpAhUqT4lITVf9mSovnFQ5hQwFgP3i9lHQLA0vONbWhvBjor/SU6eY/5L6V8nrdSUkP "Haskell – Try It Online")
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 89 bytes
Prints **d\*2** junk number in the beginning and another **2** junk numbers at the end.
```
:&5*>:0(?v:1-$:{:}\nao92*0.
:2(?v1-}$ :@*{ >
v~@~\02. >&:1-&1(?vl
>:2( ?^1-@$:@$-}$
```
[Try it online](https://tio.run/##S8sszvj/30rNVMvOykDDvszKUFfFqtqqNiYvMd/SSMtAj8vKCChsqFuromDloFWtAAR2XGV1DnUxBkZ6CnZqQA1qhkAVOVx2QJUgafs4Q10HFSsHFaCe////65aZArExAA)
# [><>](https://esolangs.org/wiki/Fish), 94 bytes
Only prints numbers in the sequence.
```
:&5*>:0(?v:1-$:{:}c2.
~@~/01. >~{~v
:2(?^1-}$:@*{
vlv?(1&-1:&<~~<
2:<$ }-$@:$@-1^?(
oan<
```
[Try it online](https://tio.run/##DcMxCsMwDADAXa/QYIwJKI1MswgT@yWBECgtlHYoaDHW15Ue3OP1e7pLXKdNllRVmIJ0GWeeAa3ZbeEZN@umIDnVnWkEaVMHRH1rTRyJJRazAllKQMRBoUloxHtNgN/jU9yddP2/Xw)
[Answer]
# [Scala](https://www.scala-lang.org/), 198 bytes
Golfed version. [Try it online!](https://tio.run/##bY9BS8NAEIXv@RVz3KXJYlp7aRtBkYJgLxZPpZRtsklGNrtxd1orIb89bnpQUC/DzPfeG3g@l1oO2LTWEfjxELnVWuWE1ojmRPKolXhGTw@nslQuiuzxLaiwkWigGwpVwppdFk@G4mKcPOvOUoPPfjK7R3sKX/aML0vrGK6SGyDLNpJq0doPNo8LPrlwQXbMd36SfUsYX3h/TR1WSRpSUASDQFNgrrwonG1fsKqJpVwEl5J53WF25xnyLIxJypNx75deONXYs2JeaGUqqpP0Sslu1Xs/RABjkyaUYtJVfgH3zsnP3ZYcmmrPF/BqkCCDLjgB2kBJG7ZmtzFMOf8FpzGkf@DsP@c8htkV9lE/fAE)
```
def F(x:Int,d:Int)={val s=ListBuffer[Double]();for(i<-0 to(Math.pow(5,d)+x).toInt){s+=Math.pow(i,x)};for(_<-1 to d){s.indices.dropRight(1).foreach{i=>s(i)=s(i+1)-s(i)};s.remove(s.length-1)};s.toSeq}
```
Ungolfed version. [Try it online!](https://tio.run/##bZBRS8MwFIXf@yvOY8K6YDd9GU5QZCC4F8WnMSRr0zbSJiXJ5mTst9fbUrcxfAr33O@ee3N8KivZtrpurAvwXSVSW1UqDdoaUW@D3FRKvGofnrZ5rlwU2c0XdbGU2uAQAZnKsWD7GV5MiJH1L5@hG1k92y2NrzHvSWAnK3iqzn5/COM9kFsHpnE/xg2CBVvKUIrGfrM7suYYYc9FsN2GwRHkN5rjxOmYkL5zPBt@doZJZ5hdzAltMp0qLzJnmzddlIElXNCAkmmJAzTmDwNLNNOcDqeHjkg4xr0ytI8nS6dqu1PMi0qZIpSEJZfXeDq@@3vUCUN2NQXJpCv8DI/OyZ/Ve3DaFGvK8MPocMquITVUhi3YbYwJ51fiJKZV1@L0P5KinPbiMTpGbfsL)
```
import scala.collection.mutable.ListBuffer
object Main {
def F(x: Int, d: Int): List[Double] = {
val s = ListBuffer[Double]()
for (i <- 0 to (Math.pow(5, d) + x).toInt) {
s += Math.pow(i, x)
}
for (_ <- 1 to d) {
s.indices.dropRight(1).foreach { i =>
s(i) = s(i + 1) - s(i)
}
s.remove(s.length - 1)
}
s.toList
}
def main(args: Array[String]): Unit = {
println(F(4, 2))
println(F(2, 1))
println(F(3, 2))
println(F(5, 3))
}
}
```
] |
[Question]
[
Sometimes, while golfing, one needs to represent large number(s) in their code. Writing them as is can significantly increase the byte-count.
What *general*1 tips do you have for representing long numbers concisely in code?
Please post one tip per answer.
---
1With *general*, I mean tips that can be applied to more than a single language. For language-specific tips, post in their respective thread.
[Answer]
# Look out for special numbers
Some languages have built-in functions for squares, exponentiation with base 2, *n*-th prime, factorial, or other procedures that can generate large numbers. Check if you number *happens to fall* into any of those categories.
And if it doesn't, it may happen that a *larger* number that does will fit for your purposes and can be used instead.
[Answer]
# Use bitwise boolean operators
Some languages have bitwise AND, OR, XOR, and sometimes NOT.
Expressing a specific large number as a bitwise combination of a result of an exponentiation or left shift and another number can get you to precisely the number you need. This is usually only worth it if the numbers get quite big.
For example, `2147483722` is 10 bytes, but `2<<30^74` (2^31 bitwise-XORed with 74) is only 8.
[Answer]
## Use Strings for repetitive numbers
For numbers that are very repetitive in nature, you can use Strings and cast them to Integer. For Example, in JavaScript
```
+"1".repeat(100) // returns 100 1s (saves 84 bytes!)
```
[Answer]
## Use Scientific Notation
Scientific notation can save bytes in case of long numbers. For Example:
```
3564e-8 // returns 0.00003564 (saves 3 bytes!)
```
[Answer]
# Look for another number to use instead
This may sound like a non-answer, but it is not always obvious that a larger number can be calculated by shorter code. An example I remember is [Output a googol copies of a string](https://codegolf.stackexchange.com/questions/97975/output-a-googol-copies-of-a-string), where the obvious answers require computing 10100. As it turns out, computing any multiple of 10100 leads to an equally correct, but in some languages, shorter answer. Dennis's answer there uses 100100, my own uses 250255.
[Answer]
## Base Compression
Base decompression code can be fairly complex, but if you have a truly enormous number sometimes it can help to compress it in some base higher than 10.
It also helps that in some languages, the base compression code is very simple. For example, PHP has `base64_decode(_)`, Python has `int(_,36)`, JavaScript has `parseInt(_,36)`, and many golfing languages have base decompression builtins.
For example, in CJam:
```
"+ÜTbô±"256b
```
This contains an unprintable. [Try it online!](https://tio.run/nexus/cjam#@6@kfXhOSNKhiYe3HNqoZGRqlvT/PwA)
This yields:
```
12345678987654321
```
[Answer]
## Use exponential fractions for large repetitive numbers
Say you wanted to generate the number made of 100 1's. You could use `int("1"*100)`, `+"1".repeat(100)`, etc. but you can also take advantage of the fact that it's very close to
```
1e100/9
```
This works best for very repetitive numbers, such as those made of a single digit. A couple repeated digits also works fairly well:
```
12e100/99 // Generates 121212121212... (100 digits)
```
Occasionally you'll find some other weird pattern which also can be represented fairly tersely in this method. If you happened to need `int("123456790"*11)`, for example:
```
1e100/81
```
Be careful, though: numbers such as `int("1234567890"*10)` don't have such an easy representation.
[Answer]
## Use Bitwise Left Shift for 2's exponentiation
Although, there are many languages that support operator for exponentiation, some do not. And those which don't, usually require calling functions (or Class/Object methods), which can cost a few bytes.
But you can save some bytes when you need to raise 2 to the power *n* by using the Bitwise Left Shift operator `<<` as `1<<n`. Note that this will only save you bytes if *n* is greater than or equal to 17. However, this will *always* save you bytes if *n* is dynamic. Few Examples:
```
1<<2 // returns 4 (3 bytes more :( )
1<<3 // returns 8 (3 bytes more :( )
1<<6 // returns 64 (2 bytes more :( )
1<<14 // returns 16384 (no bytes saved)
1<<17 // returns 131072 (saves 1 byte!)
1<<18 // returns 262114 (saves 1 byte!)
```
[Answer]
# Chinese Remainder Theorem
If arbitrary big integers frequently appear, or big integer representation in target programming language costs too many bytes, you can consider using Chinese Remainder Theorem.
Choose some pairwise relatively prime integers mi >=2, and you can express a big number from 0 to lcm(m1, m2, ... , mi) -1
For example, I choose 2, 3, 5, 11, 79, 83, 89, 97, then I can express number less than 18680171730 uniquely. 10000000000 (1e10) can be expressed as 0,1,0,1,38,59,50,49 (1e10 mod 2, 3 ... , 97) which need not be expressed as special Big Integer class/struct which might save some bytes in some programming language.
Addition and substraction can be done directly using this representation.
Example:
```
(0,1,0,1,38,59,50,49)+(0,2,0,6,23,20,16,53) = 1e10 + 5000
= (0+0 mod 2, 1+2 mod 3, 0+0 mod 5, 1+6 mod 11, 38+23 mod 79, 59+20 mod 83, 50+16 mod 89, 49+53 mod 97)
```
[Answer]
# Use String Padding (where possible)
If a large number includes a repeating digit at the beginning or end, you may be able to save bytes by using your one of your language's padding methods to construct a string of the number you're looking for, which you can then convert to an integer.
---
# Example
To generate the number `1111111111111111111111112` (25 bytes) in JavaScript (ES8):
```
+"2".padStart(25,1) // 19 bytes
```
[Answer]
# Use Exponents
If your language has an exponent operator you might be able to use it to generate, if not the number you want, at least a number you can perform a simple calculation or 2 on to arrive at your number. Even without an operator, you may still be able to save bytes with a built-in function or method.
## Example
The [maximum safe integer in JavaScript](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER) is `9007199254740991`, which is 16 digits long. In ES7, this can be calculated with the following 7 bytes:
```
2**53-1
```
The equivalent in ES6 and earlier, while the same length as the integer itself in this instance, demonstrates that using a more verbose method might not necessarily cost you any bytes.
```
Math.pow(2,53)-1
```
The above, though, may work out *shorter* if, for example, you already have `Math` aliased to a single character elsewhere in your code.
[Answer]
# Use fractions in the place of float
Example: `1./3` in place of `0.333333333`
] |
[Question]
[
Given a nonnegative integer \$n\$, determine whether \$n\$ can be expressed as the sum of two square numbers, that is \$\exists a,b\in\mathbb Z\$ such that \$n=a^2+b^2\$.
```
0 -> truthy
1 -> truthy
2 -> truthy
3 -> falsy
4 -> truthy
5 -> truthy
6 -> falsy
7 -> falsy
11 -> falsy
9997 -> truthy
9999 -> falsy
```
Relevant OEIS sequences:
* [A001481](https://oeis.org/A001481 "Truthy") - should return truthy
* [A022544](https://oeis.org/A022544 "Falsy") - should return falsy
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer as measured in bytes wins.
[Answer]
# [Python 3](https://docs.python.org/3/), 49 bytes
```
def f(n):[*{(n-2*x*x)**-2for x in range(n+1)}][n]
```
[Try it online!](https://tio.run/##VY/BroJADEX3fEXjamYEI7iDzPZ9wdsRFoMUJcHOpNQEY/x2HuMzGren97an4SZnT4dl6bCHXpEua3NXlBVmNrM2Jit6zzDDQMCOTqhom@tHU1OzjP5k6yYZLsGzwCDI4v04JbFAn0K@3@syAQDhWxl4IFGUInV2AxtdxZPVP/1x44S6WtfuXAhr4kViF@cjBnnVf/n6nXuCGHPTtFrAOqqzvLFWPT3uzrhta1qIZi5tI3vr7gL77noU9XkvZQzoxBb6oZc/ "Python 3 – Try It Online")
Numerics on this and the previous one may be fragile. I don't know whether `n**-2` is guaranteed to give the same value as `(-n)**-2`.
If necessary this can be fixed at the cost of 1 byte.
#### Old [Python 3](https://docs.python.org/3/), 50 bytes
```
def f(n):[*{(n-2*x*x)**-2 for x in range(n+1)}][n]
```
[Try it online!](https://tio.run/##VY9BjoMwDEX3nMLqKkmhKswOlO2cYHaIRSimg0SdyLgSVdWzU0KrqWb7/J/9HW7y6@lrWTrsoVeky9rcFWWFmc2sjckK6D3DDAMBOzqjon2uH01NzTL6s62bZLgEzwKDIIv345REgT5CfjzqMgEA4VsZeCBRlCJ1dgc7XcWb1Yt@u3FCXa1rDy6ENfEm0cX5hEHe@g9f/@c2EGNumtYWsI7qLG@sVVuPuzNu35p2e8WlbWR/dQ@BfXc9ifq8lzIGdGIL/dDLEw "Python 3 – Try It Online")
### [Python 3](https://docs.python.org/3/), 53 bytes
```
def f(n):[*{(n-2*x*x)**2 for x in range(n+1)}-{0}][n]
```
[Try it online!](https://tio.run/##RYxBCoMwFAX3PcXHVX5aIdqd4rYn6E5cSP1phfIMaQoR8ewpoYVuZ4Zxa3gsOKc0iSWrwE2vN4Wy1lFH1romu3iKNIP8iLsoHCvey83sQ48hZYm/rIzh5kBEwa@N8zOCwkkwdQUV3OZ9@6WX8fkSzqXEm7jwi6/@LZw@ "Python 3 – Try It Online")
#### Old [Python 3](https://docs.python.org/3/), 58 bytes
```
def f(n):[*{sorted({x*x,n-x*x})[1]for x in range(n+1)}][n]
```
[Try it online!](https://tio.run/##RY2xCsIwFEV3v@LRKa9WaHBLce0XuIUMxbxoQV5CGiGl9NujQcHlDuccuGFND8/nUiw5cIJR6XZbfExkxZbb3PHpsztqaZyPkGFmiBPfSfBR4m40m1IF/4Xse1QHAEhxVSHOnAR3xPbSQIND/Ri@dJyeC2EtKd8opF98jS/C8gY "Python 3 – Try It Online")
## How
Signals by exit code: Errors out for True and returns without error for False. The error is triggered by trying to access list positions which are out of bounds if `n` is the sum of two squares. In the last two versions the special case a=b triggers a zero division error.
All versions avoid double loops. The first version does it rather clumsily by computing x^2 and n-x^2, taking the maximum and checking for collisions (by counting uniques). The convoluted way of taking the max catches the special case a=b.
The second version implements the same logic a bit smarter: instead of taking the maximum of two values it makes use of he observation that
```
`n = a^2 + b^2`
```
can be rewritten
```
`abs(n-2a^2) = abs(n-2b^2)`
```
instead of the absolute value we can also take squares. AS before we can check for collisions as long as we do not forget the special case a=b.
The last version takes the reciprocal such that the a=b case triggers a zero division error.
[Answer]
# [R](https://www.r-project.org/), 33 bytes
```
function(n)all((n-(1:n)^2)^.5%%1)
```
[Try it online!](https://tio.run/##bYyxCsIwFEX3fsUDKU3gKSZaSwoOHXSSOuhcKKXBQH2pTTL49bGCIIjLHQ7n3CmS9S7crZbuEdqpd/uoA3XeWGLE22FgjJZMlMQbyZtVnqaCR9eO4/BkHVujQIkb3GKOOyxQCFRKFe9RHH@veZIswAY/Bg/GlZAdq9PlkIHRQDMAf@thDsBqkPBpEOwEWV19rfp8/WvGFw "R – Try It Online")
Outputs `NA` if `n` is not the sum of 2 squares, `FALSE` if `n` is the sum of 2 squares.
If we are restricted to `TRUE`/`FALSE` output, then add +4 bytes for [37 bytes](https://tio.run/##K/pfXJqbn2ZUXFiaWJRabPs/rTQvuSQzP08jT1MxMSdHQyNPV8PQKi9Oz1QzzkgTSKmqGmr@L04sKMip1EjWMNAx1DHSMdYx0THVMdMx1zE01LG0tDQHEZaaOihma/4HAA), or +3 bytes for [36 bytes](https://tio.run/##XYzLCsIwFET3/YoLUprAVUy0lhRcuNCVKGjdFkppMFCTmgfi18cIrtzMMHDO2KiNd@FhJHfP0NnBbaMMuvfKaKJpN46E6DlhtW4XJW05TZXnjEbXTdP4Jj1ZIkOOK1xjiRuskDEUQlTfEBT/32mWzcAEPwUPytVQNJfbvgAlQacNp3MD/j5AcsBI4PDTEIyF4rA7XhNsEmFfyg3xAw) if we can reverse the output.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~88~~ ~~74~~ ~~67~~ ~~66~~ ~~64~~ 53 bytes
```
a,b;f(n){for(a=n;~a*n;b=b?--b:--a)n*=a*a+b*b!=n;a=n;}
```
-14 bytes - thanks to Kevin Cruijssen
-7 bytes - by omitting return (using global variable)
-1 byte - by using `-` instead of `!=`
-2 bytes - thanks to AZTECCO
-11 bytes - thanks to AZTECCO x2
[Try it online!](https://tio.run/##RcrBEoIgFEDRdXxF0gYo2rSTyG95D0WZQWwEpnEc@/TIVm3PvUb2xpSTC8bntjvekxu76/Agf4mp9Q53K3BBZVngq51mBjqoN4igUGMjJdZSAg9Cg4AzCqz2/Fu2MoILjK@EHJ45RVZZduMNTXNOw0JrasHHhXJFtvIx1kMfi3x9AQ "C (gcc) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 15 bytes
```
2~SquaresR~#>0&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@9@oLriwNLEotTioTtnOQO1/QFFmXkm0soKunUJatHJsrIKagr6DQrWBjoKhjoKRjoKxjoKJjoKpjoKZjoI5UBAoamlpaQ4mLWv/AwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 14 bytes [SBCS](https://github.com/abrudz/SBCS)
```
{⍵∊∘.+⍨×⍨0,⍳⍵}
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q37Uu/VRR9ejjhl62o96VxyeDiQMdB71bgaK1wIA&f=S1Mw4EpTMARiIyA2BmITIDYFYjMgNgfJGQIA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f)
[Answer]
# [R](https://www.r-project.org/), ~~41~~ 39 bytes
Or **[R](https://www.r-project.org/)>=4.1, 32 bytes** by replacing the word `function` with a `\`.
*Edit: -2 bytes thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe).*
```
function(n)n%in%outer(k<-(0:n)^2,k,`+`)
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jTzNPNTNPNb@0JLVII9tGV8PAKk8zzkgnWydBO0Hzf5qGgSZXTmJBQU6lhqGVuU6aJleahqEhiLS0tDSH0paa/wE "R – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `RM`, 5 bytes
```
Ẋ²Ṡ=a
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJSTSIsIiIsIuG6isKy4bmgPWEiLCIiLCIwIl0=)
```
Ẋ # Cartesian product of (implicit range) self with (implicit range) self
² # Square each
Ṡ # Sums of each
a # Do any...
= # Equal the input?
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes
```
~+Ċ~^₂ᵐ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v077SFdd3KOmpodbJ/z/b2lpaf4fAA "Brachylog – Try It Online")
If you put a variable name such as `Z` as argument, you’ll get the actual couple of values whose squared sum is the input.
### Explanation
It’s a direct description of the problem:
```
~+Ċ Get a couple of two values Ċ whose sum is the input
Ċ~^₂ᵐ Both elements of Ċ must be squares of some numbers
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 33 bytes
Returns a positive integer for Truthy, and `0` for Falsey.
```
f=(n,x=1)=>x>n?!n:!(n%x)-f(n,x+2)
```
[Try it online!](https://tio.run/##FYrRCkBAFAXffcXxoPa2COUFy7cIK9K9WtL@/eJpmmn28RmvyW3nnbHMSwjWKE69Kcn0vuch5iZWnHjK7N91RcGKg2IYFC0YHeqfWlMEbBbq@4gwCV9yLPkh6@dteAE "JavaScript (Node.js) – Try It Online")
This is a trivial modification of [@MitchSchwartz's brilliant answer](https://codegolf.stackexchange.com/a/66181/88546) to *[Count sums of two squares](https://codegolf.stackexchange.com/questions/64812/count-sums-of-two-squares)*.
### Explanation
It can be proven that if \$ n \$ has more \$ 4k + 1 \$ divisors than \$ 4k + 3 \$ divisors, that it can be written as the sum of two squares. One way to achieve this would be to add `1` if `n%(4*k+1)==0`, and `-1` if `n%(4*k+3)==0`. Writing this down, we can see that the task comes down to computing the following alternating sum:
```
!(n%1) - !(n%3) + !(n%5) - !(n%7) + ...
```
which can then be written as:
```
!(n%1) - (!(n%3) - (!(n%5) - (!(n%7) - ... )))`
```
The base case of `!n` handles the special case where `n=0`, by returning `1` instead.
[Answer]
# [R](https://www.r-project.org/), 37 bytes
```
function(n,k=2^(0:n)^2)2^n%in%(k%o%k)
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jTyfb1ihOw8AqTzPOSNMoLk81M09VI1s1XzVb83@ahoEmV05iQUFOpYahlblOmiZXmoahoSbXfwA "R – Try It Online")
This checks whether \$2^n\$ can be written as \$2^{a^2}\times 2^{b^2}\$. This will rapidly run into numerical issues, but is shorter than [pajonk's similar answer](https://codegolf.stackexchange.com/a/242465/86301) because we can then use `%o%` instead of `outer`. Note that [Dominic's R answer](https://codegolf.stackexchange.com/a/242475/86301) remains 4 bytes shorter.
[Answer]
# Regex (ECMAScript or better), 37 bytes
```
^((x(x*))(?=.*(?=\2*$)(\3+$))\4|){2}$
```
[Try it online!](https://tio.run/##TY@9bsIwFEZfhUYI7k0ak1DEgGuYOrAwtGNpJQsujlvjWLaBlJ9nT8NQqcu3nE86Ol/yKMPGaxfz4PSW/L623/TTemHp1Hsl9dI4gLOYj9L2E6CBJkWEhWBpN@tx2kdYP2V9xPXkipfxrd@mozOyWL9Fr60CZMHoDcH0MZ8g8iAKfqq0IQAjPMmt0ZYA8UHYgzF4UcKw4IyOMMyHyPUOwArFDFkVK5yPr1cdVnIFWjjpAy1tBPVefCD@AfoP7LxclLM7xlj5@pQs7VEave15aRXNeklm@K72wPWzIK6zDDth0iTMkyMZQSPby7ipwCNewmDguqQI94qSu0MM0XcXfru1RV5Oi18 "JavaScript (SpiderMonkey) – Try It Online") - ECMAScript
[Try it online!](https://tio.run/##RU7LTsMwEPyVVbVqvHmQB48DjttUKldO3EixCmokS6YNdpCCjPn14IZKXEY7s7M70x@Mvp3evwANB6dPb3sNmPNARb3dPG1WHrqTYWhFwesVJweqC4xcb9RxgEV7XHAPjRa212pgURal9vPVDuFEplmZlnT4OJvW/2oRdLpHSfz8y4bEvWl0XZFr9HO5EwGLHb/kqgtFVYt5HaYkIac6YCwaIxghmIhA/ECOJieHdrmcy83dQvGS/3VFxb33Uj48bqWcXhgb2RgTsbW4igO0VYzE2usEidqbb3KVx2kqsvKu@AU "Perl 5 – Try It Online") - Perl
[Try it online!](https://tio.run/##bVJdb9MwFH3vr7hEQ7XT1ksH4gEvmgCBhMQArY9tkdzEab05TrCdNV3pby/XafiY1DzEvvcen@tzfO/Fo5jc5w9HVdaV9XCPMVMVizn8n2m80mdzVq5li5VB3ay0yiDTwjm4FcrAHvqc88Lj8lipHEqskJm3yqxB2LWbLyn4ja22Dj62may9qvDkAOCT0hKK1MhttyURy6pcMqxHlL9vikJamd9JkUsLqw72PEn@nOzDglLe93Vjz7ebwE@IS1eoQeRflJGE0hepabSmqiCOyZ@N0I5El3EcR5Tun0NPDIT4swR7ZPB/GZDgEhlWiHvgbpQOF2YYVs8Pp9zhu/BeWgM27XeotqxDA0c5urGqKi2Fgae0QEbJYZYJY1C6MnXjIYWgts@R2c55WTJlKIdeZwdjG@G@ytbjNTuLAXpDNN4dOU4gg4heYl@fL0FjOaCYq7XyJJrgIyDeg0mw8tl4HAPLamGdxIDoebKkYzDTs0WmpVn7zfUV3EBAwltcpktkzDbCzpdtr6eLzHTJ4Z21YudYobQm7XjYDjtTAIrKBm14jdQkHMx1aqa4jEYo8Fb4bIMOlchmWXmKSDe5Bgf8A5KfJoZtrahJ3yKr6t234k6YtcROydhQGpQWQEpsb3L0LrztE@1NrtCxrVVekvColD@l3jbhff6Va/TQFyR66SK0hPJD@AZhqo4/CGlJG1NKblIW429xFV9Qsng1uqB08foX3V8dLo5hfI7JZPom@Q0 "Java (JDK) – Try It Online") - Java
[Try it online!](https://tio.run/##NY7RboMwDEXf@Qor4sGmEBE67QEW7UOASdVG20xpgpxUpdr27Yx02otl@foc3fkez97tV3OZPUcI91DyVH4G7zpgzUKI9Q1xwaUgwlcti20MTZETDvtdTjQ8fdNX85Ov22ev2kqNHRhdZ0fPYMG4ZJQhfhjXZmC1lWG2JqKoBGVgjmAnh5ZemhZsr0Zt@3rMIMEuwXxwpwmNi5gCKv82NdJO0eZLAp7k5RDfz8gliEUU7hGkxLQwcyLocdCq@y/jr1He2MQJQ2R0RGtdqef6Fw "Python 3 – Try It Online") - Python
[Try it online!](https://tio.run/##PY7fS8MwEMff/SvOUliu2tBW8WExSHFFfJkwfWtnUJZ1gZCVNGMVf/zrXTJ1D3dw3/t@vnd29/4xWuCwkK0cOmrkHmblS0mtfFtd/orT6ePD/GlR3ZfPFQPFMwb7jdISNG@l688A1Bp0neZLzqPGRMwvdJ1RmhZLBtKsvMMrtO@0cmSSTvAPoVqa1m0I3haeqT3vsROy3lowoAwEkbqtUCTPkNJgPI3ed8wi0RAlBoH/gGVBUOfhz27n@mNe@Dv3s1XGgfk/EXooIar5TIjxlZCBDAkiueM08a0pkhhJc3URIzbXX/hZfMfjmKX5TXYA "Ruby – Try It Online") - Ruby
Takes its input in unary, as a string of `x` characters whose length represents the number. Uses a variant of the multiplication/squaring algorithm [explained in this post](https://codegolf.stackexchange.com/questions/125237/its-hip-to-be-square/223201#223201).
Commented and indented:
```
^ # tail = N = input number
( # subtract a perfect square from tail
# subtract a nonzero perfect square from tail
(x(x*)) # \2 = any positive integer; \3 = \2-1; tail -= \2
(?=
.* # find the smallest value of tail that satisfies the following
(?=\2*$) # assert \2 divides tail
(\3+$) # assert \3 divides tail at least once; \4 = \2*\2 - \2
)
\4 # along with "tail -= \2" above, acts as "tail -= \2*\2"
|
# or just subtract 0 from tail
){2} # do this twice
$ # assert that tail == 0
```
This can be generalized to sums of any number of squares by changing the `2` in `{2}` to the desired count.
# Regex (Perl / Java / PCRE2 v10.34 or later / .NET), ~~21~~ 20 bytes
```
^(\1?(\2xx|^x)*){2}$
```
[Try it online!](https://tio.run/##RY5fa8IwFMW/ykWCzZ0tTQrbg2m0gnvd095WDU4sBDLtkg4ysuyrd7ETfLncc@6f8@tP1jyOH99ArIBgLseDAVKKJGW93bxuVhG6i6XESSbqlcAAuksKQ2/1eYBZe56JCI2Rrjd6oFmR5e7r3Q3pROUFzzmePq9L67vLko9LolBcf7mUeLCNqSsMjXnjO5kq24lbrr5Joms5jVO3WGDQHVCa@Qw8pCVEkL9QEltiIG4@n@AmtgTOxT8r0SLGqNTzy1apcU9bvqZt5f3P3uMDhiqScWQFf2J/ "Perl 5 – Try It Online") / [Attempt This Online!](https://ato.pxeger.com/run?1=RU5BTsMwEPzKqrIab5socQ4I4bhNpXLlxI20VosayZJpg51KQcZ8hEsP8AM-wzd4AW5SxGV3Z2Z3Z94_mp3Rp--fpxcghoPTh8eNBpLyAEWxXNwvZh7qg6HEiowXM44OVB0QusaofQujaj_iHkotbKNVS6Mkiu1xa9twIuOExQx3z-el-T-bBR5viER-_mWD48aUusjRlfqBrUSo2YpffNUFElWIXg7TdIpO1UBp1EXQQVhCBPEGKTEpOmLH4z5cny0EZ3zIShT33kt5e7eU8vPY1sn115pWbE6rvOte1x1O0OWeDNLpr2UJu8oG8As) - Perl
[Try it online!](https://tio.run/##bVJNb9swDL3nV3DGhkhpqiY57DDVKLZhAwas29Ae0xRQbDlRK9OeJDdOsvz2jHK8jwL1hSb59Kj3xAf1pM4f8sejKevKBXigXJhKjCT8X2mCsS/WnF7pljqDullak0FmlfdwrQzCHvqaDypQeKpMDiV12G1wBleg3MrPFxzC2lUbD5/aTNfBVHRyAPDZWA1FinrT/bJEZFWuBfUTLj80RaGdzm@0yrWDZQd7XmR/TvZpwbns5/pxkJt15GfMp0vSoPKvBjXj/FWKjbXcFMwL/bNR1rPkYjQaJZzvn0NPDIyFFwn2xBD@MhDBBTEsCfco/Vk6vMNhjEEeTrXDDxWCdggu7f9IbVnHAZ5LcmNZVVYrhF1aEKOWcJspRJJusG4CpBDV9jV2u/VBl8Igl9Dr7GBirfw33Qa6ZmcxQG@IpbsTxwmEhOgl9v35Aiy1I0r42prAknN6BMIHwAl1vmCgNXCiVs5rSpidTxZ8DDh9sSmsxlVYX87gCiIS3lGYLogxWys3X7S9ni7D6ULCe@fU1ovCWMva8bAddqYAFJWL2ugaKU4k4GWKUwpnZyTwWoVsTQ6VxOZEecpYt7lIC/6RyE8bIzZO1awfkVX19ntxo3CladJkjJxHpQWwksZjTt7Ft93x3uSKHNs4EzSLj8rlLg2uie/zr12Th6FgyRufkCVcHuI3iFt1vGd30yt2N2vbX/ctH/H97PD6GLflODmfvp38Bg "Java (JDK) – Try It Online") / [Attempt This Online!](https://ato.pxeger.com/run?1=bVLNbhMxED5wy1MMESh2mmySHhDCXVUFgYREKWq5JankbLyJwetd7Nlm05An4dJD-wY8DU_DeHf5qZS9jGfm22_8fZ4f91_kjbz79QR1VuQOIaSRzqO-gP8rJWpzsObUSlXU6RTlwugEEiO9h3OpLeygrXmUSOEm10vIqMOu0Gm7AulWfjrngGuXbzy8rRJVoM7pzw7AO20UpLFVm_rIuqOzzxejJF-qLhevyzRVTi0vlVwqB4sa9rjI_vzZpinnop3rByg268DPmI8XpEEuP2irGOdPY1saw3XKfKS-ldJ4Gtzv97uc7x5DGwbG8CDBjhjwLwMRjIhhQbivwh_FvZnthYhi39T2nySichZc3J6iJM-KMMBzQW4s8twoaeE2TolRCbhKpLUkXduiRIghqG1r7GrrUWWRtlxAq7OGRWvpP6oK6Zq1xQCtIYbuThwNyBKildj2p3Mw1A6oyBdGI-sO6REIj2DH1HlvkdbARYV0XlHCzHQ85wOwk4PNyCi7wvXJMZxCQMIrCpM5MSZr6abzqtVTZ3YyF3DmnNz6KNXGsGrQq3q1KQBp7oI2ukZsxwLsSWwnFI6OSOC5xGRNDmXE5qKsyVi9uZYW_A2RNxsTbZwsWDsiyYvtRXop7UrRpPHAch6UpsAyGm-X5F1421vempyTYxunUbHwqFzcxujK8D7_2gV5iCnrPvddsoSLffg6YaseSkyHL39es9nklM2Oq-r7dcX7fHe8f9a07sPmNMe7h_Fw8mLcJL8B) - Java
[Try it on regex101](https://regex101.com/r/lzh7Fq/2) / [Attempt This Online!](https://ato.pxeger.com/run?1=XVDNSsNAEMZrn2JZFrJjkzYJtVq2oRcVCuJBvTXtksZNG0w3YbOFQO0b-AZeCuIb-DQ-jZNWLx52dv6-75uZ949qXR2-z97GE3QIMyQitE9Jj1RGraRRVZGkijv93vlEynVSWJmWmyovlIl5DCJ-6NeOSxx8GSblSrUN2iptay7l7fTuRkpwSQBIicSik-tc1spyWqVG9ZZJ-mINGlnkm9xSl9BBOBqMhpfh6IKC6GSl4SyPfMGKKEP2mj8-XU_vQcCO5Blnxay2plAaPfCCeRTRWFPA5nq7xAqmXd_1AmjxqqmK8llx6lEX2wXi03KrbYsdhwiaIQFafy46hByV9W_M9Dg61tHrdgGlCT9eaJPYdM2ZcVGsPZdKLHcax2UaAMiuHTEHla7Ldi5BcJVAkDYmTIs9yuz_nZWD-NzazLv6WvA4mPA4bJrXRQPnsAv37FQ6_H2-Fwz9U_AD) - PCRE2
[Try it online!](https://tio.run/##RY/BaoQwFEV/ReSBydgM6qKLCaEDXfcLHAeCfVMD6YvEDIax@XarLaXLc7kc7h3djH4a0NoVvGo9fmDsTifCmZ2L9cou9Qu7NDF@XSM/8KVJsBbnp/zVfY7G4nvOJTxUJW/Oo@4HBjYzlIGh8R74AlqBFdNoTchFLs2NgT727k5B2JA1e6FUoNuqS5uAAanWUOh@EgkkLP5xvXNZ8mV3@OObDv2AEyticQDiv/GDL7M3AcXgppC2WbX850yQ205ZQ5gBpZTWStTP1Tc "PowerShell – Try It Online") - .NET
```
^ # tail = N = input number
( # The following will be captured in \1
\1? # Optionally subtract the previous perfect square from tail
(\2xx|^x)* # If on the first iteration, subtract a perfect square from tail;
# if on the second iteration and "\1?" was evaluated once,
# combines with it to subtract a perfect square from tail that
# is greater than or equal to the previous one; if "\1?" was
# evaluated zero times, this adjusts the first perfect square
# subtracted, optionally increasing it to a larger one, which
# effectively makes the "other" perfect square zero.
){2} # Iterate this twice
$ # Assert that tail == 0
```
[Answer]
# [Python 3](https://docs.python.org/3/), 59 bytes
```
lambda n:n in(n and(i//n)**2+(i%n)**2for i in range(n*n+1))
```
[Try it online!](https://tio.run/##RYpBCoAgFAWv8jfB1wK1dkI3aWOU9aFeIW06vVmbdsPMnPe1Huhy7Ie8hX2cAsGDBAwKmFiMgdK6rVmqD@KRSEqnFLDMDI3aKZVfjV87a5U/k@BiNJFRjgc "Python 3 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
Żpݲ§i
```
[Try it online!](https://tio.run/##y0rNyan8///o7oKjuw9tOrQ8E8g8tPVw@7F2ncPthyc83DHf/f9/IwMA "Jelly – Try It Online")
Outputs `0` for falsy, and a non-zero positive integer for truthy. The Footer in the TIO link simply splits the range \$[0, n]\$ into truthy (top line) and falsey (bottom line)
## How it works
```
Żpݲ§i - Main link. Takes n on the left
Ż - Zero range; [0, 1, ..., n]
Ż - Zero range; [0, 1, ..., n]
p - Cartesian product
² - Square everything
§ - Sums of each pair
i - Index of n, or 0
```
[Answer]
# [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 125 bytes
```
(load library
(d V repeat-val
(d R(q((N)(map* *(0to N)(0to N
(q((N)(any(map* contains?(V(map* s(V N(a N 1))(R N))(a N 1))(R N
```
[Try it online!](https://tio.run/##TYy7DsIgGIV3n@KMP01MitfRN2BoE/Zf24EEAYGY8PQI1sHp5Du3bFyxJoVayXpeYM09ciw7WqAR17By3r/Zdp7oRaQEPTkMGGjMHo2@0uP5F7MrW@XhXWbj0o30ZiTSUMRQkELQ1Nbin2pvYUb7GSFxwBEnnHHBFVKifgA "tinylisp – Try It Online")
[Answer]
# [Excel](https://support.microsoft.com/en-us/excel), 64 bytes
```
=LET(x,SEQUENCE(SQRT(A1)+1,,1)^2,1-AND(ISERROR(XMATCH(A1-x,x))))
```
[Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnhqES3qUXNTMPOcY?e=acImqD)
List all \$k^2\$ in \$[0..n]\$. Match all \$n - k^2\$ to list. If all matches are errors, then false, otherwise true.
[Answer]
# [Desmos](https://desmos.com/calculator), 52 bytes
```
a=.5
f(n)=min(ceil(mod((n-[0...floor(n^a)]^2)^a,1)))
```
[Try It On Desmos!](https://www.desmos.com/calculator/a7t3uxhoc4)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/a5k9tooxd3)
### 47 bytes (doesn't work past 100 because of Desmos 10000 element restriction)
```
l=[0...n]
f(n)=min(sign([aa+bb-nfora=l,b=l])^2)
```
[Try It On Desmos!](https://www.desmos.com/calculator/ueloh5qkkp)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/mfqgggvtvi)
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~9~~ 8 bytes
```
0y&:U&+m
```
[Try it online!](https://tio.run/##y00syfn/36BSzSpUTTv3/39LAwA "MATL – Try It Online")
([Or this version for larger inputs](https://tio.run/##y00syfn/36AyIk7NKlRNO/f/f0tLS3MA "MATL – Try It Online"))
1 for truthy, 0 for falsy. (Thanks to @Giuseppe for -1 byte and this neater output.)
Square every number from 0 upto the input, add all the combinations of them, and check if the input is in there. (The "larger inputs" version does the sensible - but non-golfy - thing of limiting the check upto the square root of the given number; same logic, two extra bytes, a lot less resource hunger.)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~8~~ 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÝãnOIå
```
Bugfixed and -2 bytes thanks to *@Mr.Xcoder*, making it now similar as *@emanresuA*'s Vyxal answer and [*@cairdCoinheringaahing*'s Jelly answer](https://codegolf.stackexchange.com/a/242501/52210).
[Try it online](https://tio.run/##yy9OTMpM/f//8NzDi/P8PQ8v/f/f0AwA) or [verify the smaller test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w3MPL87zrzy89L/O/2gDHUMdIx1jHRMdUx0zHXMdCx1LHUOgoGEsAA).
**Explanation:**
```
Ý # Push a list in the range [0, (implicit) input]
ã # Create all possible pairs with the cartesian product
n # Square each integer
O # Sum each inner pair
Iå # Check if this list contains the input
# (after which the result is output implicitly)
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 25 bytes
Returns 0 for truthy and 1 for falsy. Quite short considering it's a conventional language.
```
@(n)0||(k=0:n).^2+k.^2'-n
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BI0/ToKZGI9vWwCpPUy/OSDsbSKjr5v1PtI2OteZKyy9SyFSwVTCwMjTgAgolWmfqpGlkagKlUvNSuBL/AwA "Octave – Try It Online")
[Answer]
# [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), ~~125~~ ~~117~~ 109 bytes
```
(d X(q((N I)(i(l N 1)N(X(s N I)(a I 2
(d S(q((I N)(i(a(X I 1)(X(s N I)1))(i(l N I)0(S(a I 1)N))1
(q((N)(S 0 N
```
The last line is an anonymous function that takes a number and returns 1 if it is the sum of two squares, 0 otherwise. [Try it online!](https://tio.run/##PY0xDsMgAAP3vMKjvUGkfiESCwsLK1UWJNqkSZa8ngJSu57u7Cu/75LPvVauiPyQHk7MLPCw8ow8MVCCwzw1K3TLwXcrMTZs9desfrGTYRhVm5FsT5dxIAYY@MqypRUlP4903Jr4SjsW0Fwb5odUvw "tinylisp – Try It Online")
### Ungolfed/explanation
*Look, ma, no library!*
First, we define a helper function `X` that takes a number `N` and determines if it is (not) a square. A perfect square is the sum of consecutive odd numbers; therefore, subtracting the sum of the first several odd numbers from `N` (for an appropriate value of "several") will result in 0 if `N` is square. Thus, we recurse over increasingly large odd numbers (which we track as `I`) and subtract each one from `N` until `N` equals 0 (in which case `N` is square) or `N` is less than 0 (in which case `N` is not square):
```
(def not-square? ; Define not-square?
(lambda (N I) ; as a function of two arguments:
(if (less? N 1) ; If N is less than 1,
N ; return N (0 if square, negative if not square)
(not-square? ; Else, recurse with these arguments:
(sub2 N I) ; New N is previous N minus current odd number
(add2 I 2))))) ; New I is the next odd number
```
Next, we'll define a function `S` that determines whether a number `N` is the sum of two squares. Our algorithm here is to recurse over integers `I` starting at 0: if `I` is not square, or `N` minus `I` is not square, try the next `I` until `N` is less than `I`, at which point `N` cannot be the sum of two squares. On the other hand, if `I` and `N` minus `I` are both square, then `N` is the sum of two squares.
```
(def sum-squares? ; Define sum-squares?
(lambda (I N) ; as a function of two arguments:
(if ; If
(add2 ; the sum of
(not-square? ; 0 if
(sub2 N I) ; N minus I
1) ; is square, < 0 otherwise
; and
(not-square? I 1)) ; 0 if I is square, < 0 otherwise
; is truthy (nonzero), then:
(if (less? N I) ; If N is less than I
0 ; then return 0
(sum-squares? ; Else, recurse with these arguments:
(add2 I 1) ; New I is the next integer
N)) ; Same N
1 ; Else (I and N minus I are both square), return 1
```
Finally, our submission is an anonymous function that takes `N` only and passes it to `sum-squares?` with a starting `I` of 0:
```
(lambda (N)
(sum-squares? 0 N))
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~31~~ 26 bytes
```
.+
$*
^((^1|11\2)*\1?){2}$
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0WLK05DI86wxtAwxkhTK8bQXrPaqFbl/38DLkMuIy5jLhMuUy4zLnMuQ0MuS0tLcxBhCQA "Retina 0.8.2 – Try It Online") Link includes test cases. Edit: Saved 5 bytes thanks to @Deadcode. Explanation: `^((^1|11\2)*)` matches a square number at the beginning of the string. Repeating the expression with `{2}` does not in itself change this, but it allows the use of `\1?` to add a square number matched on the first iteration. (The first stage simply converts the decimal input to unary.)
[Answer]
# [Julia](https://julialang.org/), ~~49~~ 35 bytes
```
~n=1 in[i^2+j^2==n for i=0:n,j=0:n]
```
[Try it online!](https://tio.run/##bZPNbtswEITveQodbVQFNPwTWcB9kSABfAlqw1UD1wHcS17dnW977YEENDNL7g5H54/L6aj74/G5HTSdtufTa/pyfk2Hwza9/bpOp8PybZvP7C@P2/Xj9uPP4XmZJ81TmqcyT3We@jwNI6DZq3mtXoaTsWRFMpasya7JLsr@ztYU88VHFWuK@ervak31OdX1zVyzvplv/l7NreZWY93abr4b63Th@mFs@NzR6YeGFrEVNvpaaDS6jDajz4QkJbbKRm2OYZDQpgoH0KQKWEFCv6JRVSRteXl6ejteftsfg5aBxtGIkXm5huu4LVmVjCfruJMrs7lsPFubwawv@GyMHri94Ju5am3lAaytxumiWt98TnNNowvjzXgzvhpfXbNav9Ke8RVPzXVrO54a78Y7T2rt8DnD3DA3XDfMj3hrhloYfmGshVkXXIkUxNgxdwwekytYagmFmF6ML7KhFA8BiwUiJ8IIkRZhh3K8CxJSI2KjEt6iwxURH@GLCJFquE4t/ohACYdErNQiq7C4pBaPiASTRNJEzIRfWiPUSLBLZE6YJlwTtqlH5jmAJIooCg@FiRrx@rBjOCjv19N2u2y7n8f33f3r98/dfT9P/36v/f7/bGTL5OMv)
Thanks to MarcMush we can save a lot more! We can also replace `f(n)` with the slightly shorter version `~n`!
[Answer]
# [Julia 1.0](http://julialang.org/), ~~28~~ 23 bytes
```
~n=n∈(N=(0:n).^2).+N'
```
[Try it online!](https://tio.run/##bZNNbtRAFIT3OYV32MJErv5zN9JwhFwAgTQbRNAwisJEGjZZ55xcZKjvsWXRLbmqXvd71eUfL6fHo6632@v5cP7z9jY/HObt43m5/5qW@/cP726X55fL99@Hz9s6aZ3SOpV1quvU12kYAc1ezWv3MpyMJSuSsWRNdk12UfZ3tqaYLz6qWFPMV39Xa6rPqa5v5pr1zXzz925uN7cb69Z2891YpwvXD2PD545OPzS0ia2w0ddGo9FltBl9JiQpsVU2anMMg4Q2VTiAJlXAChL6FY2qImnbl7u7b8fTL/tj0DLQOBoxMi/XcB23JauS8WQdd3JlNpeNZ2szmPUFn43RA7cXfDNXra08gLXVOF1U65vPaa5pdGG8GW/Gd@O7a3brd9ozvuOpuW5tx1Pj3XjnSa0dPmeYG@aG64b5EW/NUBvDb4y1MeuGK5GCGDvmjsFjcgVLLaEQ04vxRTaU4iFgsUDkRBgh0iLsUI53QUJqRGxUwlt0uCLiI3wRIVIN16nFHxEo4ZCIlVpkFRaX1OIRkWCSSJqImfBLe4QaCXaJzAnThGvCNvXIPAeQRBFF4aEwUSNeH3YMB@Xp@fF8OZ3nn8en@frh0@t8Xdbp3@@1LP9nI1smb38B "Julia 1.0 – Try It Online")
Based on [David Scholz](https://codegolf.stackexchange.com/a/242869/101725)’s solution.
Thanks to dingledooper for shaving 5 bytes
[Answer]
# [Ruby](https://www.ruby-lang.org/), 44 bytes
```
->n{(k=0..n).any?{|a|k.any?{|b|a*a+b*b==n}}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWiPb1kBPL09TLzGv0r66JrEmG8pKqknUStRO0kqytc2rra39X6CgAVRoaKipl5tYoKGWpvkfAA "Ruby – Try It Online")
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 63 bytes
```
lambda n:(r:=range(n+1))and n in(i*i+j*j for i in r for j in r)
```
[Try it online!](https://tio.run/##JcwxCoAwDEDRq2RMWgfFRQrexCVSqykaS3Dx9FV0e/zhl/vaTu2HYjWNU935mCODBrQwGuu6oPqOiDWCgiiKE59dhnQayBvAPuaPVIuJXugOLpga@Add2xJRfQA "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes
```
Nθ≔X…·⁰θ²η⊙η⊙η⁼θ⁺ιλ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05rLsbg4Mz1PIyC/HCjgmZecU1qcWZYalJiXnqphoKNQqKmjYATEGUClAUWZeSUajnmVGhk6ClDKtbA0MadYo1BHIQCoUyNTRyFHEwSs//@3tLQ0/69blgMA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input `n`.
```
≔X…·⁰θ²η
```
Generate a list of squares from `0` to `n²` inclusive (in case `n<2`).
```
⊙η⊙η⁼θ⁺ιλ
```
Check whether any pair sums to `n`.
[Answer]
# [Haskell](https://www.haskell.org/), ~~41~~ 38 bytes
```
f n=or[n==x*x+y*y|x<-[0..n],y<-[0..x]]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzza/KDrP1rZCq0K7UquypsJGN9pATy8vVqcSwqqIjf2fm5iZp2CrkJtY4BuvUFBaElxS5JOnEK1RnJFfrpCnqa2tpKCkrQ3hqigADdWsyYPoNjQwAOoHAA "Haskell – Try It Online")
* Thanks to @ovs for saving 3 Bytes.
[Answer]
# [MATLAB](https://www.gnu.org/software/octave/), 43 bytes
```
o=@(x)any(~mod(sqrt(x-(0:(x/2)^.5).^2),1));
```
taking advantage of vectorized code to search from 0 to sqrt(x/2), checking sqrt(x - i^2) is an integer with mod([],1)
[Try it online!](https://tio.run/##y08uSSxL/f8/39ZBo0IzMa9Soy43P0WjuLCoRKNCV8PASqNC30gzTs9UUy/OSFPHUFPT@v9/AA "Octave – Try It Online")
[Answer]
# k (ngn/k), 37 bytes
```
c:{0<#&x{x=+/y}/:+{(%x)=_%x}#'!2#1+x}
```
try it in the [ngn/k repl](https://ngn.bitbucket.io/k/#r)
[Answer]
# [Desmos](https://desmos.com/calculator), 47 bytes
```
f(n)=\prod_{a=0}^n\prod_{b=0}^n\{aa+bb=n:0,1\}
```
The leading newline is necessary for the piecewise to paste properly.
Outputs 0 for truthy and 1 for falsey.
[Try it on Desmos!](https://www.desmos.com/calculator/fggeb7ut8d)
The [`∏` trick](https://codegolf.stackexchange.com/a/236800/68261) didn't work, maybe due to the `\{aa+bb=n:0,1\}` piecewise. Avoiding it with `sign(aa+bb-n)^2` or `0^{(aa+bb-n)^2}` ended up longer.
] |
[Question]
[
[Quote notation](https://en.wikipedia.org/wiki/Quote_notation) is a way of expressing rational numbers based on the concept of [\$p\$-adic numbers](https://en.wikipedia.org/wiki/P-adic_number), written in the form \$x'y\$.
The quote indicates that the number to it's left (\$x\$) is "repeated" infinitely to the left, then prefixed to the number on the right (\$y\$). For example \$3' = \: ...3333\$ and \$764'31 = \: ...76476431\$. We can then consider the geometric series:
$$\cdots + 10^{3k} + 10^{2k} + 10^{k} + 10^{0} = \frac 1 {1 - 10^k}$$
By setting \$k\$ to be equal to the number of digits of \$x\$, we can transform this "infinite" number into a value which converges:
$$\begin{align}
3' & = \: ...333
& 764'31 & = \: ...76476431 \\
&
& & = 31 + 764'00 \\
& = \cdots + 3\cdot10^3 + 3\cdot10^2 + 3\cdot10^1 + 3\cdot10^0
& & = 31 + 100 \times 764'\\
& = 3(\cdots + 10^3 + 10^2 + 10^1 + 10^0)
& & = 31 + 100 \times 764(\cdots + 10^9 + 10^6 + 10^3 + 10^0)\\
& = 3\left( \frac 1 {1 - 10} \right)
& & = 31 + 76400\left( \frac 1 {1 - 10^3} \right) \\
& = \frac {3} {-9}
& & = 31 - \frac {76400} {999}\\
& = - \frac 1 3
& & = - \frac {45431} {999}
\end{align}$$
Note that \$9'0 \ne 9'\$ as the first equals \$-10\$ and the second \$-1\$. Additionally, note that leading zeros on \$y\$ do affect the output: \$81'09 = -\frac {801} {11} \ne \frac {9} {11} = 81'9\$ Therefore, a value after the \$'\$ (\$y\$) may be omitted in the input.
You are to take, in any reasonable format, up to 2 non-negative integers \$x\$ and \$y\$, and output the fraction \$\frac a b\$ represented by \$x'y\$. Reasonable formats include:
* A string, delimited by a non-digit character, such as `'`, e.g. `9'` or `9'0`. The string will always begin with a digit; if there is no \$x\$ value, it will be a \$0\$ (e.g. `0'3`)
* A list of either 1 or 2 non-negative integers, represented as strings or lists of digits. If there is only 1, it represents \$x'\$. 2 integers represent \$x'y\$.
* A list of 2 elements. The last element may be either a non-negative integer (as a string or digit list), or a consistent value that is not a non-negative integer (e.g. `null` or `None` or `-1` etc.) that indicates that there is no \$y\$ value. The first value will always be a non-negative integer.
This is not an exhaustive list, if you have another method, feel free to ask.
You may output the two integers \$a\$ and \$b\$ instead of the fraction \$\frac a b\$. The fraction must be exact, and fully simplified (i.e. \$a\$ and \$b\$ are coprime). If \$b\$ is 1, outputting just \$a\$ is acceptable. For negative outputs, if outputting \$a\$ and \$b\$ separately, either may have the negative sign, but not both.
You may input and output in any [convenient method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins.
---
Modified from the linked Wikipedia page:
>
> Let \$x\$ and \$y\$ be sequences of digits, as in \$x'y\$
>
>
> Let \$z\$ be the digit \$1\$ followed by a sequence of zeros of the same length as \$y\$.
>
>
> Let \$w\$ be a sequence of \$9\$s of the same length as \$x\$.
>
>
> Then the number represented by \$x'y\$ is given by \$y-\frac{xz}w\$
>
>
>
## Test cases
```
x'y = a / b
31'491 = 17609 / 99
844'80 = -4480 / 999
4'128 = -2848 / 9
247'0 = -2470 / 999
0'716 = 716 / 1
592' = -16 / 27
3'45 = 35 / 3
9'7 = -3 / 1
9' = -1 / 1
3'0 = -10 / 3
764'31 = -45431 / 999
81'09 = -801 / 11
81'9 = 9 / 11
123456' = -41152 / 333333
```
[Answer]
# [J](http://jsoftware.com/), 25 bytes
```
(%-.)~/@(10^#&>)#.10#.&>]
```
[Try it online!](https://tio.run/##y/qvpKegnqZga6WgrqNgoGAFxLp6Cs5BPm7/NVR19TTr9B00DA3ilNXsNJX1DA2U9dTsYv9r/k9TsKhQMKxQsFYwqFCwrOBC8MEcS7CMigGIbQxRBWSZVyiYVSiYgPjGINUA "J – Try It Online")
Takes a boxed 2-item vector containing the digit vectors of \$x\$ and \$y\$, and returns a rational number. The digits must be given in extended precision. \$y\$ may be an empty vector. I guess it's pretty well golfed when Jelly is at 20 bytes :)
### How it works
Uses the formula at the end of the challenge. If we define \$\#x\$ as the number of digits of \$x\$,
$$
z = 10^{\#y}, \quad w=10^{\#x}-1, \quad x'y = -\frac{z}{w}x+y,
$$
and observe that the result is the same as the 2-vector \$[x,y]\$ evaluated in base \$-\frac{z}{w}\$.
```
(%-.)~/@(10^#&>)#.10#.&>] NB. Monadic train; input = (digits of x;digits of y)
10#.&>] NB. Evaluate each in base 10 to get [x,y]
#. NB. Evaluate in base...
(10^#&>) NB. 10 raised to the power of length of each; [10^#x, 10^#y]
(%-.)~/@ NB. (10^#y) / (1 - 10^#x) = -z/w
```
---
# [J](http://jsoftware.com/), 23 bytes
```
(%-.)~&(10x^#)#.,&{.&".
```
[Try it online!](https://tio.run/##bY7NCoJAEIDvPsWg5CjoMqOj7gqegk6deoA8hBJdAk9B0Ktvu2tJhxYGdr5v/m42VjjD0ANCAQS9i1LB/nQ82GxXqvyVZkyPc5InqkifKo2VzaNoulzvgDUjzIBiGFfCXUtmMQYG@GNHEU3Oeo1aJGhNX1tJt1n3D3aT7KkJ7IM6bj2jwFyyLWFuqqUOzxdwVUvT/naOmnjhMFGvN5JB@wY "J – Try It Online")
Modification of [Jonah's solution](https://codegolf.stackexchange.com/a/222886/78410) to use the same base trick. This one is a dyadic function accepting plain strings as its two args. One caveat is that eval(`".`) of an empty string is an empty vector, so we need to make it a 0 explicitly using `{.`.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~37~~ 33 bytes
```
d[#/d[0#-9]]~d~#2&
d=Fold[9#+##&]
```
[Try it online!](https://tio.run/##TY47C4MwFIV3f0XggktvqSa@MlicOrd0DA5ilArVQrFTSP66zcPB7ZyPc889c7e@hrlbp77bxnqTAi5SJHDmbWukARpHsr593lJwOAHE7fb4TcPa3L/Tsgo4X8emgTY2z75bjIqUYkhSjSpDwp3SaFmFxPpMI3EyCdDbFAlFUgVCfax0fM8kTpe2B0kRSO57qeMBMCftWR4s9xcHfUjtpbav2New48TUZ2x/IGEa85ty99@XRXr7Aw "Wolfram Language (Mathematica) – Try It Online")
Input two lists of digits.
`Fold[9#+##&]` is longer than `FromDigits`, but has more flexibility with its input.
[Answer]
# [Vyxal v2.6.0pre1](https://github.com/Vyxal/Vyxal/releases/tag/v2.6.0pre1), ~~15~~ 11 bytes
```
vL↵‡⌐/R?⌊$β
```
Haha rationals go brrr. Obligatory port of Jelly, M and Bubbler.
## Explained
```
vL↵‡⌐/R?⌊$β # Full program, takes ["x", "y"]
vL # vectorise length over each
↵ # and raise 10 to the power of each
‡⌐/ # lambda x, y: x / 1 - y
R # reduce the above list by that
?‚åä # cast each string in input to it
$β # and convert to the result of reducing the lambda
```
## History
I spent roughly an hour on this, trying to arrange it to work properly. Took me a few re-reads of the specs, but I got there in the end.
Input taken as:
```
y
x
```
where `y` and `x` are strings (done by surrounding them with `""`s), and if `y` isn't provided, `[]` is used.
## Explained
```
L↵⁰I*⁰L↵‹/¹I$-ƒ
L↵ # 10 ** length(y)
⁰I # int(x)
* # ↑ * ↑↑ (we'll call this W)
⁰L↵ # 10 ** length(x)
‹ # ↑ - 1
/ # W / ‚Üë
¬πI # int(y) # on an empty list, this will return 0
$- # ↑↑ - ↑
ƒ # fractionify(↑) # this built-in has been around for a long time before this challenge --> it turns a decimal into the most simple fraction
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 61 bytes
```
x=>y=>(G=(a,b)=>b?G(b,a%b):[x/a,z/a])(z=-1+x-~x,x-=y+x-(x+y))
```
[Try it online!](https://tio.run/##VY/JTsMwEIbvfgoLCY2tZnPsLKZyOKE@AMdSqU4XSJUmURqhtAhePdgOPeDDLJ/@f2Z80p/6suurbvCbdn@YjmoaVXFVBVkpor2SqqJ8XpHS048lfVqPofZuod5QclM@W4z@z@iNvrqaioyLK6XTgBXeIs5ASGZKlqWRxCGWEuVCQB4Z5gthsmUSCWBxji2Mc5FbiGKRQTQjkd11EWQstdCmEDOUyBiwUzkQZ4iDSBzhiQEcScjwrODOIa1@drie2y1zHzlDlgrgzB2YCM7@NucMzA8szSNnZBZJ55Rzz2IukhSck7EkttPcQ9tg6KszocGlq6uBwFsDNDjrjtRYFbi@YwV0HW3@ax/ggdIlGoJj27/o3cds@UIY79rm0taHoG7fSR2c2qpx4qDT@9dB9wNhEfUwqAI8fCS1mUxNZBs6a8GcB3b0N11Ovw "JavaScript (Node.js) – Try It Online")
Take input as two strings, output an array with two numbers.
JavaScript use `+` for both number plus and string concatenation. When any operand is string, it works as string concatenation.
[Answer]
# [R](https://www.r-project.org/), ~~118~~ ~~116~~ ~~108~~ ~~103~~ ~~98~~ 92 bytes
```
function(x,y,`+`=nchar,B=10^+x-1,A=el(max(y,0):0)*B-x*10^+y,q=1:x)c(A,B)/max(q[!A%%q&!B%%q])
```
[Try it online!](https://tio.run/##Jc1RC4IwEMDxdz@FGqtNJ92VpCfswX2NKCZSFJShFMxPvzZ9OY7f/eEmZ9iOGeXuv6H/Pj8Dt3KWJjdq6B/dJLVCuOa2QNmq24u/O8tnCaIBkenCZuE4y1FhY0XPW6nFPiTjOWkZG7eJ9vMi3BH9k7QkTOMNViegeB8TRYeyCg5eC7/DohTVSw0UuAb0ihhRsDRCxHVZo9DQErg/ "R – Try It Online")
Takes first input as integer and second as string (empty if no \$y\$).
GCD implementation borrowed from here: <https://codegolf.stackexchange.com/a/48845/55372>
*-8 bytes thanks to [@Kirill](https://codegolf.stackexchange.com/users/78274/kirill-l) & [@Dominic](https://codegolf.stackexchange.com/users/95126/dominic-van-essen);
-5 and another -6 bytes thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe)*
[Answer]
# [R](https://www.r-project.org/), ~~114~~ ~~110~~ ~~109~~ ~~107~~ 104 bytes
*Edit: -4 and then -2 more bytes thanks to Giuseppe's comments on pajonk's answer, and then -3 bytes after copying a trick from Robin Ryder's answer [here](https://codegolf.stackexchange.com/a/223168/95126)*
```
function(s,z=10^nchar(s)-1:0,n=scan(t=pmax(s,0)),a=c(diff(n*z[2:1]),z[1]),c=1:z)a/max(c[!a%%c&!a[2]%%c])
```
[Try it online!](https://tio.run/##fdJha4QgGAfw9/sUHuOWjo7zUUsN/CTRhniLHWzeVh2MvnzTGK0Nu16IwY9//3zsps/rZXg5PXd2OF@8fTNTe/Uu7nGfjwbok3evtsM9OUBFc296Zz0ezMe7/QqCEpJb4/Dp3LbYP441q6Ah@VjH1RmoRmKPkbp6Z/d797CzNWvCpiH/v4wdzjhkeSY0ZIgQdI8MAllSjY5I67sEV0IEr@jCD0IoOvOkjxqYytDimRIq@pRmQgZP11rIG@k0aAnlrw8vQUPKFpoFHeiSPVsmU5jHQylWmBfB8hTVsUOUSy7fqqB/Cqwq3KL0TyrQLcvTNtlWlnEiHFbzKwSH7SNW8X5QvRqJonPrZBVgXBRl/M0lHqBgsc38TN8 "R – Try It Online")
Input is a vector of two strings representing `x` and `y`.
I tried to answer this without peeking at the other [R](https://www.r-project.org/) answers, but now I realise that [pajonk's answer](https://codegolf.stackexchange.com/a/222898/95126) is ~~probably~~ golfier... Bah!
[Answer]
# [J](http://jsoftware.com/), 39 32 30 27 bytes
```
{.@".@]-".@[*(%<:)~&(10x^#)
```
[Try it online!](https://tio.run/##bY7BCsIwDEDv@4qgaDZxJdm6rR0OhoIn8eBVdAdxiBdhJ0Hw12vb6VAwkNC8l7S9mpHAFqoSEOZAUNqMBax2m7V5iHok6kNsy34WThZl9JyGTPfjODJRsF0K@JkIgvPpcgNMGaEFlJqxJ1zkpDutoYI/tpFSkbVOo5LSa0Ufm8hisPbs7SDZUe3ZGxWcO0ae2WZ4hDlLutSHG@AklVn@vdko4o79jar/I2k0Lw "J – Try It Online")
-5 thanks to Bubbler. Also go upvote [his j answer](https://codegolf.stackexchange.com/a/222891/15469), which is more creative and has delightful application of base `#.`
The wikipedia formula translated into J. The only part that might be of some interest is the calculation of `z/w`:
* `(%&x:<:)~&(10^#)`
+ `&(1>.10^#)` Convert each string input by raising 10 to the power of its length `10^#` (which will be 1 when length is 0).
+ `(%&x:<:)~` Next swap the argument order `~` and subtract 1 `<:` from the new right arg, to get a number whose digits are all nines. Divide the left argument by that `%`.
[Answer]
# [Haskell](https://www.haskell.org/), 58 bytes
```
x#y=f y-f x*0!y/1!x
c!s=10^length s-c
f x=read$'0':x++"%1"
```
[Try it online!](https://tio.run/##NY9Pc8IgEMXvfAqMdtBqDATyh4701ltPvVo7EkXNFImTMNPk06dAWi47@9v3dh832X0rrcfxNOsEwV9amau9wS4@gQvsRavkeYEweunX6@iJRKCfD@ICh9gNn/FsSMisH@@yNlDAcwMg3JuN3FSHXfzTtOdue6m1Ve3yaBr7ptX9GIkkWu0Wr1dl32ujnEEru@w3w0p0D2mWiUCfCK3MNNhLt6s6CNt8SFs3RuqtD@T8e3/EiR5tbexCyqSqhOjnVtYaDo77SCMliHHikpEixxwmkHNQMoZK7FjMmKueccAQSUvoYVqy0kOQsgLhCbHiX4dRQXIPfUkgARlPEQyqANICUMSyQGjmAAUcFXBS0ODgXj85Qk/9lanHwVDkDFESAmaMkr/LJUHuB56WOBgJICllWY6CkpAs9e7wfgE "Haskell – Try It Online")
The relevant function is `(#)`, which takes `x` and `y` as strings, with `y` possibly empty. Returns a `Rational`.
**DISCLAIMER:** the compiler is unable to correctly deduce the type of `(#)`, unless it is specified by some other part of the program, either explicitly (i.e. `::Rational`) or implicitly (i.e. by using the return value as if it were a `Rational`). Based on [this Meta answer](https://codegolf.meta.stackexchange.com/a/12747/82619) I believe this should be allowed, but since I'm quite inexperienced I'm not sure. If that's not the case, then the best I can do is:
## [Haskell](https://www.haskell.org/), 63 bytes
```
x#y=f y-f x*0!y/1!x
c!s=10^length s-c
f x=toRational.read$'0':x
```
[Try it online!](https://tio.run/##XY/LbsMgEEX3fAV5SJNUcQwGP6hCd9111W2aKjghiVUHRzZS7a93AbebshnNmXvnDjfVfem6Hsd@McgLHqIL7p/IbIjprEenWScp@ay1udob7qITclNpm3dlq8aoettqdV4Cged@vKvKYInPDcJ4bzZqUx520XfTnrvtpaqtbldH09jXWt@PcxnP17vly1Xbt8poZ6i1XfWbYS27hzKrWMIHwNpMg71yu8rD/1jn3/sQJ3q0lbFLpeKylLJfWFXVeHDcnzQyClxQdxnNMyJwjIVABedQEMcizl31TCAONCmwh0nBCw9RwnMgE@L5n45ATjMPfYkxRalIAAdVAEmOGPA0EJY6wJCAHE8KFhzC6ydH6JlPmXoSDHnGgdFwYMoZ/U0uKLgfeFqQYKSIJoynGQQlpWni3eH9AA "Haskell – Try It Online")
[Answer]
# JavaScript (ES7), ~~ 80 ~~ 76 bytes
Expects `(x)(y)` as strings (`y` may be an empty string) and returns `[numerator, denominator]`.
```
x=>y=>(G=(a,b)=>b?G(b,a%b):[p/a,q/a])(q=1-10**x.length,p=y*q+x*10**y.length)
```
[Try it online!](https://tio.run/##NY/LboMwEEX3fMUoUmWbEMDYvFqZrtp@QJZJVDkJJFSUdytQ1W@nxlAvxqOjc8fjD/ktu0ub1/2urK7plIlpEMkoEvwmsLTORCTn5zd8tuTDmTweakdajSNPBDeC7qhrmoNdpOWtv1u1GM1mO5gzHFdIpjZtvvI2xSjrELHbVF5f8yLdj@UFu8Tuq33f5uUNE7uri7zH6FgqLavaF3m54w5EAj8GQJH2cIB3CwYLRjiBgM7@lL1SHHy8bglS1SQOeVLupSq7qkjtorrhAbawQRtVx7k79iLZWJDhgeCRKPuXTIwiHlNQI2kYuDE4EMdGxDmK3BnuOFfNDGODI@pFoKkX8WimhsdD5K6Mh/@mi0IaaDrfDlDDjz0Ei6eJFxoMcX9BzFeEGTEKYXWYDsU6soQ0YPqtBbg6EwYcMbps6nNG1wUiitRfNI5cnaUG9Rj3A6RVSn1vzuvzBw "JavaScript (Node.js) – Try It Online")
### Commented
```
x => // outer function taking x
y => // inner function taking y
( G = (a, b) => // G is a helper function which takes 2 integers,
b ? G(b, a % b) // computes their GCD a
: [ p / a, q / a ] // and eventually returns [ p / a, q / a ]
)( // we invoke G with (q, p) defined as follows:
q = // q =
1 - // 1 - 10 ** len(x)
10 ** x.length, //
p = // p =
y * q + // y * q + x * 10 ** len(y)
x * 10 ** y.length //
) //
```
[Answer]
# [R](https://www.r-project.org/) `+ MASS`, ~~99~~ 91 bytes
```
function(x,y,`[`=gsub)MASS::fractions(eval(parse(t=paste0(y,"-",x,"."[0,y],"/","."[9,x]))))
```
[Try it online!](https://tio.run/##TdBNboMwEAXgfU9huRsjmWbGP9iOyqIH6CrLKFJoBVWlKo2AVHB66jExrVfwPs1jTL907LlkS3e7vI@f3xcxyVmej@f6Y7i9Fa8vh8N@3/VNskG0P82XuDb90IqxvjbD2IKYJS@5nCR/4keQ80nyHU8vQU6nIp6lE1xjzExAXjyymqGrILAdC@EhmjcmoofVSmM8JEtIhMqTESpvPCGRMi4ibGTcvzmI5LC6Y3yKhAQ2qEgpp6kEypFoWtFm0TaCpjxQ1RrThM5NYetZm3Kut63WHHKRq@g2GvNFrdH4t7GnXwQhX8dDKkyNqLSx1f1zNIloFbWms/wC "R – Try It Online")
Takes input as two strings (`y` possibly empty), outputs a rational fraction or an integer.
[Answer]
# [Jelly (fork)](https://github.com/https://github.com/cairdcoinheringaahing/jellylanguage), 11 bytes
```
ḌḅẈ⁵*C÷@¥/Ʋ
```
[Try it online!](https://tio.run/##ASsA1P9qZWxsef//4biM4biF4bqI4oG1KkPDt0DCpS/Gsv///1s4LDFdLFswLDld "Jelly – Try It Online"), or rather, don't
As of last week, my fork now includes symbolic math support! Unfortunately, [M](https://codegolf.stackexchange.com/a/222926/66833) (Jelly's version with symbolic math) only implements this in the `İ` atom, not in the `÷` division atom. My fork does both.
Again, implements [Bubbler's strategy](https://codegolf.stackexchange.com/a/222891/66833) to evaluate \$[x, y]\$ in base \$-\frac z w\$.
## How it works
```
ḌḅẈ⁵*C÷@¥/Ʋ - Main link. Takes [x, y] as lists of digits on the left
Ḍ - Convert [x, y] to integers
∆≤ - Do the following to [x, y]:
Ẉ - Lengths of each
⁵* - Raise 10 to the power of each length
¥/ - Reduce by the following:
C - Complement; 1 - a
√∑@ - Divide b by that; b / (1 - a)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes
```
9ṁḌ+Ø.µ×³ḌU¤_/,Ḣ:g/$
```
[Try it online!](https://tio.run/##y0rNyan8/9/y4c7Ghzt6tA/P0Du09fD0Q5uBnNBDS@L1dR7uWGSVrq/y////aGMdw1idaBMdSyANAA "Jelly – Try It Online")
Seems very bad ¯\\_(ツ)\_/¯
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~96~~ 92 bytes
```
(.+)'(.*)
$($($.1*9)*$2*)-$($1$.2*0)*_/$($.1*9)*
+`_-_
-
-/
/
(_+)(\1)*/(\1)*$
$.(_$#2*)/$#3
```
[Try it online!](https://tio.run/##PYtLDsIwEEP3vkYHzafKZ9JCmxNwCaSUBQs2LBD3DxELZNl6luX34/N83b2f5Hp0ibOyRFOQDEW3qkbFNIzmFItltZb@E@ajhYaAkJAgbVa5uVr6JYGiNJrGPdG09L6ylx1l3Tgj8@YXnGthLLyeUXkbHpyxO@f6BQ "Retina – Try It Online") Link includes faster test cases. Explanation:
```
(.+)'(.*)
$($($.1*9)*$2*)-$($1$.2*0)*_/$($.1*9)*
```
Write out `yw-xz/w`. (Edit: I don't actually multiply `x` by `z`, I just suffix the appropriate number of `0`s to it, which saves on a `1` amongst other things.)
```
+`_-_
-
-/
/
```
Perform the subtraction, slowly.
```
(_+)(\1)*/(\1)*$
$.(_$#2*)/$#3
```
Slowly divide by the GCD and convert to decimal.
Just for completeness, optimising for speed results in code that readily dispatches all of the test cases. [Try it online!](https://tio.run/##PYs7csMwDET7vYaRgKCGIkFCH1YqcwmNpRQp3KTw5Gw@gC@m0Co8GOws9i3uP3@33289PtzXfri@E3a9F5Br06uv4il7Ce1S6rNP4rf4Rrjvqwa3eYmIuLqtk7AqAq5hAfHzQZ/o9jOPq/pXEZQjKeJyhsvz4cIiblXp4qmN06VEuthxFGWritmM5wRjzTOyTZyQeNIRQ82Mwjag8tS2@YRpNC7tSTlVaC42jPwP "Retina – Try It Online")
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 70 bytes
Not great, but I felt like submitting it anyway
```
{⍺←⍬⋄{⍵÷⊃⌽⊃∩⍥(⍸0=⊢|⍨⍳)/|⍵}((W×⍎'0',⍺)-(⍎⍵)×⍎'1','0'\⍨⍴,⍺),W←⍎'9'\⍨⍴,⍵}
```
Not sure why, but my code to handle single arguments works in TryAPL.org but not in tio.run
Also, because of how APL handles default arguments, I had to swap the order on input...like I said, not the best solution :|
```
⍺←⍬⋄ ⍝ assign Empty Set to the default value for the left argument (Y from the problem statement)
⍵÷⊃⌽ ⍝ divide the 2-tuple (a and b from the problem statement) by their gcd
⊃ ⍝ pick (removes one layer of nesting)
‚à© ‚çù intersection
‚ç• ‚çù function composition operator (Over)
(⍸0=⊢|⍨⍳)/ ⍝ fold/reduce by finding divisors
|‚çµ ‚çù absolute value of 2-tuple (a and b from the problem statement)
W√ó‚çé'0',‚ç∫ ‚çù W (from problem statement) times the integer representation of the left argument (Y from the problem statement) or zero if alpha is the empty set
-(⍎⍵) ⍝ subtract the integer representation of the right argument (X from the problem statement)
√ó‚çé ‚çù decode then multiply
'1', ‚çù concatenate the character 1
'0'\⍨⍴ ⍝ expand the character 0 by the number of characters in Y
,‚ç∫ ‚çù ravel Y (effectively making single characters into singleton arrays)
, ‚çù concatenate
W←⍎'9'\⍨⍴ ⍝ assign the integer representation of the expansion of the character 9 by the number of characters in X
,‚çµ ‚çù ravel X
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/P@1R24TqR727gNSj3jWPuluAnK2Htz/qan7UsxdEdqx81LtU41HvDgPbR12Lah71rnjUu1lTH8jYWquhEX54@qPePnUDdR2gGZq6QHV9QAlNiKihug5QJgasZQtYgU442J4@dUsk4a21//@rm1gaqiukKagbG6pzqVsYgNkWJiZAjqGRBZgHYkPEjUzMgWxzQzMwzwDINjGFaAYJg1mWcMUgMWOI2eZmYDMsIYaDLEIwgZSppRGYtgSThkbGJqZm6gA "APL (Dyalog Extended) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 55 bytes
```
F⪪S'«≔ζη≔ιζ»≔I⭆η⁹δ≔⁻×IζδI⁺η⭆ζ⁰ε⊞υε⊞υδW﹪εδ«≔δε≔ιδ»⪫÷υ↔δ/
```
[Try it online!](https://tio.run/##VY/NqsIwEIXX@hShGycQ0btTXMl1o1Ao6Av0mmgGcpPSJAoVnz1OWvFnl5M555szR123R1eblE6uZbBvDAbY2iaGfWjRnoELVkwKzm7j0dp7PFvoBNN89ZIoWEfyPn7q39oHGMJl3YAWbMkJIsnzdJRoo4cD/is/uLt@LlgvKkNDSr0RtHDOeYYoglTRa4jf7wy/ajSKQelkNA5U/vxsLYfER2vZt65oS4CdQ0tnhw1eUKqMXP95Z2JQIPPiYlZwvkpp8TOZL9P0Yh4 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F⪪S'«≔ζη≔ιζ»
```
Split the input string on `'` and save the parts into separate variables.
```
≔I⭆η⁹δ
```
Change the digits of the first part to `9`s and save the result as an integer.
```
≔⁻×IζδI⁺η⭆ζ⁰ε
```
Multiply that by the second part as an integer, then change the digits of the second part to `0`s, append that to the first part, and subtract the integer value.
```
⊞υε⊞υδ
```
Save the fraction to the predefined empty list.
```
W﹪εδ«≔δε≔ιδ»
```
Find the GCD.
```
⪫÷υ↔δ/
```
Reduce the fraction to its lowest terms and output it with a `/` separator.
[Answer]
# [Clojure](https://clojure.org/), 92 bytes
```
#(let[b biginteger p(fn[x](.pow(b 10)(count x)))](-(b(or %2 0))(/(*(b %)(p %2))(dec(p %)))))
```
[Try it online!](https://tio.run/##PZFNboMwEIX3PsWIKPK4UhL/AXarngSxgZiICgEFR01Pn9qY1Kvx5/fGTzPtMH3dF/fEq@ugex5wcL5qoOlv/ejdzS0wYzdWjxrP8/SDDQjOsJ3uo4cHY6zGEzY4LXCUwBnDC74FzZHhHEi4X10bSxbPkxG8Tqv7hsq71UNFMiWotiL7gE8QZcEtXMBakhmtqeEbPmlt@IYD11RIE3Dk0mgTOcmkLil/UV3@qzktRZF4KAIVJMutpBFF7cZkGVJQne9Q5YEpkllabiTqVLLaZEzWhFT6NyGenGWhqRJ79lwr8YpjBOV2j2n41iG0EFLpvKC7XohcxjbbITW8x21UD/itAdu0qfPql368XdZ56D1sgzxkNGN1TXAOL34YATsInjjyPw "Clojure – Try It Online")
Relies on the formula from Wikipedia. Takes input as two strings (`nil` when there is no `y`), outputs a rational fraction, or a bigint when denominator is 1.
[Answer]
# [M](https://github.com/DennisMitchell/m), 13 bytes
```
Cİ×
L€⁵*ç/ḅ@Ḍ
```
[Try it online!](https://tio.run/##ASkA1v9t//9DxLDDlwpM4oKs4oG1KsOnL@G4hUDhuIz///9bOCwxXSxbMCw5XQ "M – Try It Online")
Implements [Bubbler's method](https://codegolf.stackexchange.com/a/222891/66833)
## How it works
```
Cİ× - Helper link. Takes a on the left and b on the right
C - Yield 1-a
İ - Inverse; Yield 1 / (1-a)
√ó - Times; Yield b / (1-a)
L€⁵*ç/ḅ@Ḍ - Main link. Takes [x, y] as lists of digits
L€ - Length of each
⁵* - Raise 10 to the power of the lengths
ç/ - Run the helper link with the powers of 10 as a and b
Ḍ - Convert [x, y] into integers
·∏Ö@ - Evaluate [x, y] as base b / (1-a)
```
[Answer]
# [Perl 5](https://www.perl.org/) `-apl`, 99 bytes
```
($w,$z)=map s/./9/gr,@F;@e=($F[1]*$w-$F[0]*($z+1),$w);$w--while grep$_%$w,@e;$_=join"/",map$_/$w,@e
```
Takes two space separated strings from `stdin`, outputs a fraction.
[Try it online!](https://tio.run/##HczdCsIgGIDhW5HxBbo0k/4IETzaTcSQHXwsw6a4QNjFZ9LZy3PwJszhUiuFwmFj5j0lssqDvMs5cztoi4bC8FBjD0W0OI49hW2vGIfCdDNRnj4gmTMmcLt2sajBmVf0Syc73n7g5J9rvV3P5KS@MX18XNYqphR@ "Perl 5 – Try It Online")
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÂI‚JÆ-нID®ì+н>‚D¿÷
```
Despite 05AB1E's name (when `05AB1E` converted to hexadecimal is interpret as base64 it spells `Base`), it can't do base conversion from decimal values, so [*@Bubbler*'s approach](https://codegolf.stackexchange.com/a/222891/52210) won't work for it.
Instead, this is a port of [*@tsh*'s JavaScript answer](https://codegolf.stackexchange.com/a/222951/52210), so make sure to upvote that answer as well!
This uses the legacy version of 05AB1E, because the GCD builtin `¿` will always result in a positive integer in the new version of 05AB1E (the `D¿÷` should be `Ð.±s¿*ß÷` as workaround in that case).
[Try it online](https://tio.run/##MzBNTDJM/f//cJPno4ZZXofbdC/s9XQ5tO7wGu0Le@2AQi6H9h/e/v9/tLGhjomlYSwA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfeXhCaH/DzdFPGqY5XW4TffC3giXQ@sOr9G@sNcOKORyaP/h7f91/kdHGxvqmFgaxupEW5iY6FgYABkmOoZGFkDayMRcB8Q30DE3NAPSppZGOkpKQIaxjokpkLLUMQeTUDGQUnMzEx1jsGGGOkoGlkoQliWQMjQyNjE1A6mNBQA).
**Explanation:**
Uses the formula:
$$(x,y) = [x-(y\mathbin\Vert x-x\mathbin\Vert y), \text{-1}\mathbin\Vert x + x + 1]$$
integer-divided by their \$\gcd\$ afterwards; where \$\mathbin\Vert\$ is concatenation, taking precedence over the other operators.
```
 # Reverse the (implicit) input-pair (without popping)
I‚Äö # Pair it with the input-pair
J # Join both inner pairs together
Æ # Reduce this pair by subtracting
- # Subtract this integer from both values of the input-pair
–Ω # Pop and only keep the first one
ID # Push the input-pair twice again
®ì # Prepend both integers in the top pair with "-1"
+ # Add both to the input-pair at the same positions
–Ω # Pop and only keep the first one
> # Increase it by 1
‚Äö # Pair the two values together
D # Duplicate this pair
¬ø # Get the GCD (Greatest Common Divisor)
√∑ # Integer-divide the values in the pair by this GCD
# (after which the pair is output implicitly as result)
```
] |
[Question]
[
### Background
The [systematic chemical symbol](https://en.wikipedia.org/wiki/Systematic_element_name) is defined as such for \$ 118 < n < 1000 \$:
* The first letter corresponds to the first digit, capitalized.
* The second letter corresponds to the second digit.
* The third letter corresponds to the third digit.
This can be generalized for all \$ n > 0\$:
* For each digit, get the corresponding letter.
* Capitalize the first character.
### Task
Write a function or full program that takes an integer or a list of digits \$n > 0\$ and returns or prints the corresponding systematic chemical symbol.
```
Digit | Letter
--------------
0 | n
1 | u
2 | b
3 | t
4 | q
5 | p
6 | h
7 | s
8 | o
9 | e
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so ***shortest code wins.***
### Test Cases
```
In - Out
----------
119 - Uue
120 - Ubn
123 - Ubt
999 - Eee
6859 - Hope
1 - U
92 - Eb
987654321 - Eoshpqtbu
1010101 - Unununu
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes
Input is a list of digits.
```
.•*Š"—Êo•sèJ™
```
[Try it online!](https://tio.run/##yy9OTMpM/f9f71HDIq2jC5QeNUw53JUP5BQfXuH1qGXR///RhjoKQGQZCwA) or [Try all cases!](https://tio.run/##yy9OTMpM/V9Waa@koGunoGRf@V/vUcMiraMLlB41TDnclQ/kFB9e4fWoZdF/nf/R0YY6hjqWsTpA2kjHAEobA2lLHUuwuJmOhY4pRAVY1AhMWuiY65gBxU10jIHqDcH6DHTgODYWAA "05AB1E – Try It Online")
**Commented:**
```
.•*Š"—Êo• # compressed alphabet string "nubtqphsoe"
s # swap to implicit input
è # index each digit into the string
J # join into a single string
™ # apply title case
```
See the step-by-step output [here](https://tio.run/##Zcw9CsJAEAXg3lMMKSXY@IMKYu8VxGKyWZIJ6@6SWVG7FFbWHkBSeY/gRXKRdVFiQF/34HvPMCYkvR@1VT183qO2ujVXEwpEwuxtKZllCqhsjol0wK4knS0hGk@K9WrA0CXiI1pwBmhvFQlyQNoe3Fc2j56STuUJJIocUsreNAxdLn/vN/2mMKQ/DoGDUX@4vdQ9R2vVGRy54ASy7JT321kM8ximMSx2Lw).
---
[Lyxal](https://codegolf.stackexchange.com/users/78850/lyxal) has suggested another 13-byter with a nicer input format:
```
.•*Š"—Êo•ÅвJ™
```
[Try it online!](https://tio.run/##yy9OTMpM/f9f71HDIq2jC5QeNUw53JUP5BxuvbDJ61HLov//zSxMLQE "05AB1E – Try It Online")
This uses `Åв`, which converts the input integer into the custom base defined by the string.
[Answer]
# [Haskell](https://www.haskell.org/), 43 bytes
```
f(h:t)="NUBTQPHSOE"!!h:map("nubtqphsoe"!!)t
```
[Try it online!](https://tio.run/##TU7LasMwELzrKxTTQwIbkOzYsQK5FAw59EmaUzDFNnJV6shKJf1@1ZVaSllWMzszi1Z19kNOUwjjUu3cap89nG5fnp8Ox8cmWyzU7tKZZaZ9765G2VmitnLBSeteh85KS/f0fObAQbSAmAP7xQKRAUtzBTWUPwlsAXl6a9hChfoGCszztMfgr9uWXLp3jR/gCffUeHd0n3ea3sSZjoj/rgicC7qmJy8Jz1lkvUZWJOaIENFtpCRVXUZ6mA0mo0tEHq2eiHpblZsij2ozW2WurveEs1QxqX0s8jWMU/dmw3ow5hs "Haskell – Try It Online")
Input is a list of digits. Yes, the code really just writes out the string once in uppercase and a second time in lowercase. This kludge seems shorter than other things I tried. Haskell without imports doesn't have built-ins to capitalize and is really clumsy in working with characters.
**43 bytes**
```
zipWith(!!)$"NUBTQPHSOE":repeat"nubtqphsoe"
```
[Try it online!](https://tio.run/##TU5Na8MwDL37V7ihhw1UsJ0mjQe9DAI97JO27NCG4gRnCUsdt7Yv@/Hz7GyMIaT3pPeE1AnzIYfBt@uj/@z1W2@7m9nsdp487e93ry@b7XOZ3F2llsImytX2ojszysRbaeypEUYavMaHAwUKvIKADMgvpgEJkKnPoYDsxxGSA5tqASvIw3wJafDTaY/AX1YVOotehQNnoR@xdnZrrw8Kz2OP24D/vvCUcrzAeycRZSSyWgWWTswizqNaSonyIot0M@rgjCriLEo14sUqz5Ypi9NyNJ2@2NohSqaITuVioK@mHcS78YtG628 "Haskell – Try It Online")
Taking [Lynn's solution](https://codegolf.stackexchange.com/a/214057/20260) and making it more boring. We can also write:
**43 bytes**
```
zipWith(!!)$"NUBTQPHSOE":l
l="nubtqphsoe":l
```
[Try it online!](https://tio.run/##TU7LasMwELzrKxSTQwMbkOTYsQq@FAw59BXS0ENqim3k2lSRlUq@9OOrSmopZdmd2ZkR2qEx70JK15cv7nPUz6MdrhaL1TK5P9487R93h4cquZZIlomaW3vRg5mEF5wVxr52jREGl/h0okCB1@CRAfnF1CMBEvccCsh@Er45sDgL2ELu9Q2kPk/jOwJ/Xdfo3IzKf3Bu9B3Wsz3Yj1uFl2HHvcd/VzhKOV7j4ywQZSSwVnmWRmYR58GthEB5kQW6m7RPBhdxFqwW8WKbZ5uUBbWazKAvtp0RJbFCUs2h0FfXy@bNuHWn9Tc "Haskell – Try It Online")
**47 bytes**
```
(%0)
(h:t)%i=["NUBTQPHSOE"!!h..]!!i:t%32
_%_=""
```
[Try it online!](https://tio.run/##TU7baoNAEH3fr1ilQgKTsJdo3IAvBSEPvZLmyYqorFVqzLa7/n7t7raUMsycM3POMNPX@l2O49Jlr8sqImu06g9mHQ1ZET6cb1@en46nxzwMgn67LYNgOJiIM1RFVRaGi5HaVG2tpcYZLgoKFEQJFhmQX@QWCRDfJ5BC/OOwKYD5msIeEjvfAbd@6vcI/GVZoks9TPbApVb3WM3mZD7vJnzjetxZ/PfFQqnAG3yeJaKMONZMlnHPDBLCqbmUKEljR49XZZ1ORYI5qUEi3SfxjjM3za@6Vx@mmRElPpxzml2gr7Yb6ze9bFqlvgE "Haskell – Try It Online")
Based off [Lynn's solution](https://codegolf.stackexchange.com/a/214057/20260). Handles the capitalization by passing in an offset `i` of 0 initially, then updating it to 32 in each recursive function call.
It doesn't seem like Haskell has a nice function to title-case a string even with imports, which are probably too lengthy anyway to be competitive. The below with `Data.Text` doesn't work because it operates on `Text` not `[Char]`. `Data.Char` only has `toUpper` to capitalize a single character.
*44 bytes (non-working)*
```
import Data.Text
toTitle.map("NUBTQPHSOE"!!)
```
[Try it online!](https://tio.run/##TU5Na8MwDL37V7hlhw3UYjtNGh96KQv0sE@ankoYTnDXsHx4tQL79fNsr4whpPek94R0VvZDd51zbW/GC9J7hWpZ6i8kOJYtdnrZK3M7fzpsy9eX3f65mM9mdw61xbdGWW3phh6PHDjICjwKYFdMPDJgsc8gh/TX4VOCiDWHNWR@voLE@3ncY/CXVUV61Q7@gP/gkZoJ93h5GOhN6OnJ478vHOeSLuhh0oQLFlg9eJZEhkTKoBZakyxPA92NxjuDSqQIUk1kvs7SVSLCtBjt2XxiPRHOYgTnMIUg382pU@/WLRpjfgA "Haskell – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
ị“ubtqphsoen”Œt
```
[Try it online!](https://tio.run/##y0rNyan8///h7u5HDXNKk0oKCzKK81PzHjXMPTqp5L/L4fZHTWsi//@3tDA3MzUxNjLUUTA0tAQSRgYgwhgA "Jelly – Try It Online")
Inputs as a list of digits, which the Footer does for you.
As it appears the string can't be compressed, this is likely to be the shortest approach in Jelly
## How it works
```
ị“ubtqphsoen”Œt - Main link. Takes a list l on the left
“ubtqphsoen” - Yield the string “ubtqphsoen”
ị - For each digit in l, index into the string (1-indexing)
Œt - Title case (capitalise the first character)
```
[Answer]
# [R](https://www.r-project.org/), ~~80~~ ~~72~~ 56 bytes
-8 bytes thanks to Kirill L.
-16 bytes thanks to Giuseppe.
```
sub("(.)","\\U\\1",chartr("0-9","nubtqphsoe",scan()),,T)
```
[Try it online!](https://tio.run/##K/r/v7g0SUNJQ09TSUcpJiY0JsZQSSc5I7GopEhDyUDXEiiaV5pUUliQUZyfqqRTnJyYp6GpqaMTovnf0sLczNTE2MjwPwA "R – Try It Online")
First we translate the digits to the relevant letters thanks to `chartr`, then `sub` switches the first letter to upper case. This last part is possible thanks to the option `perl = T`, a nice trick found by Giuseppe.
Also, note that all the functions are vectorized the way we need them to be, so we can handle several inputs at a time, which is rather unusual in R golf with `scan()`.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~17~~ 16 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Input as a digit array, output as a character array.
```
mg`eo¢pqt¿n`w)vu
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=bWdgZW%2bicHF0v25gdyl2dQ&input=WzEsMSw5XQ)
```
mg`...`w)vu :Implicit input of digit array
m :Map
g : Index (0-based) into
`...` : Compressed string "eoshpqtbun"
w : Reversed
) :End map
v :Modify first element
u : Uppercase
```
[Answer]
# [Haskell](https://www.haskell.org/), 48 bytes
```
zipWith(\i d->["NUBTQPHSOE"!!d..]!!i)$0:k
k=32:k
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzvyqzIDyzJEMjJlMhRdcuWskv1CkkMMAj2N9VSVExRU8vVlExU1PFwCqbK9vW2Mgq@39uYmaebUFRZl6JRppCtKGOkY6xjomOaazm/3/JaTmJ6cX/dZMLCgA "Haskell – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~20~~ 17 bytes
```
§:oa←tm!¨Ḃ+q²"ṗen
```
[Try it online!](https://tio.run/##ASoA1f9odXNr///CpzpvYeKGkHRtIcKo4biCK3HCsiLhuZdlbv///1sxLDEsOV0 "Husk – Try It Online")
input as a list of digits.
There's probably a better way to do the titlecasing part.
-3 bytes from Dominic van Essen.
## Explanation (old)
```
§:oa←tmo!¨nḂ+q²"ṗe¨→
→ increment input to accomodate 0-indexing
mo map each digit to
!¨nḂ+q²"ṗe¨ it's index value in the compressed string
§: join the
oa← first letter uppercased
t with it's tail
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~20~~ 18 bytes
```
⭆⍘Nnubtqphsoe⎇κι↥ι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaDglFqdCeBqeeQWlJX6luUmpRRqaOgpKeaVJJYUFGcX5qUpAbkhqUV5iUaVGto5Cpo5CaEFBalEyUK9GpiYQWP//b2ZhavlftywHAA "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 2 bytes thanks to @Lyxal's comment on @ovs's answer. Explanation:
```
N Input number
⍘ Custom base conversion using
nubtqphsoe Literal string
⭆ Map over characters
κ Current index
⎇ If not first character then
ι Current character
↥ι Else uppercased character
Implicitly print
```
[Answer]
# [Python 3](https://docs.python.org/3/), 51 bytes
```
lambda a:"".join("nubtqphsoe"[x]for x in a).title()
```
[Try it online!](https://tio.run/##BcFbCoAgEADAq4hfCktQ9oZOUn0oJRm1mm1Qp7eZ8NHmUSU7TOnQp1k00z3n2e4dCo6PoStst1/5@M7WR/Yyh0zLjBwdq5ApRIckrBg7aKGBGiooQUEB@Sxl@gE "Python 3 – Try It Online")
---
# [Proton](https://github.com/alexander-liao/proton), 42 bytes
```
a=>"".join("nubtqphsoe"[x]for x:a).title()
```
[Try it online!](https://tio.run/##BcFbCoAgEADAq4RfCovQ@wF2EfHDQMkI12wDb28zKSNhrF5Vq3bG5IUhcha/g550vuiYLsZjbspmhaRAt@Oiphwicc/1CgvMMMEIA/TQQWuEqD8 "Proton – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~51~~ 49 bytes
Apparently I can get rid of the customary "assign to first parameter" because I only care about a false/non-false answer from this function. Interesting to know!
```
f(n){n&&putchar("nubtqphsoe"[n%10]^32*!f(n/10));}
```
[Try it online!](https://tio.run/##HY7bCoJAEIbvfYpJKHY90O6apiw@iRhsWx6gVvNQF@Krt40xzMD3Mfz8Oqy1trYihi7mcOjnSTdqIK6Zr9Orb8bu7hZmz1l5iYS3w7cjZ5TK1bZmgqdqDXl37Y3C4gBsSg1DUeYL51kAXLDtRAFkGWKSxptEErjpOYlPkUDk7D8BsDUAT@UYIR2Mq7qBSBQSsNVIXJdSqIinfJ9KZ7VfXT1UPdrw8wM "C (gcc) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-nl`, 37 bytes
```
p$_.tr("0-9","nubtqphsoe").capitalize
```
[Try it online!](https://tio.run/##HchNCoAgEEDh/RxDWhSUOPY7pwmLICHU0hZ1@KaIx7d5xzldzCEbZTpyoSoSpXDnlPawRr@IQs4m2GQ2ey/MiASo1acGIoJuaL8BpIGGvmubWiOg@nt8SNa7yJXbXg "Ruby – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 27 bytes
```
y/0-9/nubtqphsoe/;$_="\u$_"
```
[Try it online!](https://tio.run/##K0gtyjH9/79S30DXUj@vNKmksCCjOD9V31ol3lYpplQlXun/f0NDSy5DIwMgNuaytLTkMrMwBQpwWRpxWVqYm5maGBsZchkagOG//IKSzPy84v@6BQA "Perl 5 – Try It Online")
[Answer]
# JavaScript (ES6), 54 bytes
Expects an array of digits.
```
a=>a.map((c,i)=>"nNuUbBtTqQpPhHsSoOeE"[c*2+!i]).join``
```
[Try it online!](https://tio.run/##bdBND4IgGMDxe5@iOmk9mdmrBz20tXXqZeWptQVEZTOgkL4@YZutiTBuv/H84Y7eSJJXKvIe42eqL5FGUYy8BxKOQyB1o7jNVirB83z/3IrNbSl3fE0X7QPpBN1WenS9O0/Z6aQJZ5Jn1Mv41bk4hwEMIDy6bvN/9fvNRNGGRQPw6yhmdXRYS/MqDSGsDVhQK2ACMxhXsaFLLuzY6pVlgT0/sKmBK2zLGUxhYhJGMDQP/I4oSrm8iWeOlf0LPvxOOaRoYKrY@gM "JavaScript (Node.js) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), ~~11~~ 10 bytes
```
«/
∨+Ċ≤«βǐ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C2%AB%2F%0A%E2%88%A8%2B%C4%8A%E2%89%A4%C2%AB%CE%B2%C7%90&inputs=999&header=&footer=)
I finally turned my suggested 13 byte 05AB1E answer into a Vyxal answer.
## Explained
```
«...«βǐ
«...« # the string "nubtqphsoe"
β # convert the input to bijective-base 10 using the above string as the alphabet
ǐ # titlecase that result
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 26 bytes
```
T`d`nubtq\p\hs\oe
T`l`L`^.
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyQhJSGvNKmkMKYgJqM4Jj@VKyQhJ8EnIU7v/39DQ0suQyMDIDbmsrS05DKzMAUKcFkacVlamJuZmhgbGXIZGoAhAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
T`d`nubtq\p\hs\oe
```
Translate each digit to the appropriate letter. The letters `h`, `o` and `p` have special meaning, so they need to be quoted.
```
T`l`L`^.
```
Translate the first letter to upper case.
[Answer]
# APL+WIN, 39 bytes
Prompts for a character vector of digits with index origin = 0
```
⎕av[(↑n),32+1↓n←⎕av⍳'NUBTQPHSOE'[⍎¨⍕⎕]]
```
Explanation:
```
[⍎¨⍕⎕]] Convert input to individual digits
⎕av⍳'NUBTQPHSOE' Find index positions of all upper case characters in atomic vector
and use result above to select those according to input
(↑n),32+1↓n Concatenate first index to remaining indices + 32 to apply appropriate case
⎕av[...] Use the above indices to select required characters from atomic vector
```
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), ~~31~~ ~~29~~ 28 bytes
```
~{"nubtqphsoe"1/=}%()[32-]|\
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/v65aKa80qaSwIKM4P1XJUN@2VlVDM9rYSDe2Jub//2gzBQsFUwXLWAA "GolfScript – Try It Online")
Input as a digit array.
```
~ # Parse the input to an array [6 8 5 9]
{ }% # For each digit
"nubtqphsoe"1/ # Split each letter of this string 6 ["n" "u" ... "e"]
= # Get the corresponding letter "h"
( # Get the first letter ["o" "p" "e"] "h"
) # Get the ascii value ["o" "p" "e"] "" 104
32- # Subtract 32 ["o" "p" "e"] "" 72
[ ] # Put it in an array ["o" "p" "e"] "" [72]
| # Convert to ascii ["o" "p" "e"] "H"
\ # Swap the two elements in the stack "H" ["o" "p" "e"]
# Only the strings are outputted "Hope"
```
[Answer]
# [Scala](http://www.scala-lang.org/), ~~47~~ 40 bytes
```
_+""map(d=>"nubtqphsoe"(d-48))capitalize
```
[Try it online!](https://tio.run/##Vc1NC4JAEIDhu79i8KSE@G1aKHgQ6tCxc@zqioaNa67RB/12ow7bytzmZZ4ZS9KRuadnVgo4kBaB3QXDaoSc85d2Ix3UG9ijgDSDHB@QzqeVrl8IN6o003GiYuDN2DPdqKwgNs2S8FaQrn2yeavxa4uiQ6M2XDcxTbBtsOA4MTV4jgwUF8H/B6GEJJFUwVQqikNZdj1ffJGUCnnSoeo6Xkdh4HvypujHhg@CTiro/EayOH1He88f "Scala – Try It Online")
* -7 Thanks to [user](https://codegolf.stackexchange.com/users/95792/user)!
[Answer]
# x86 machine code (MS-DOS .COM format), ~~35~~ 33 bytes
The program will terminate at the end of input from the command line.
For fun, I decided to use `XLAT` to index each digit's representation as the translation array easily fits into an 8-bit index and everything is 1:1.
Byte representation:
```
0000 B4 20 BB 19 01 BE 82 00 AC 2C 0D 74 09 D7 32 C4
0010 CD 29 32 E4 EB F0 C3 6E 75 62 74 71 70 68 73 6F
0020 65
```
Assembly code (TASM):
```
IDEAL
MODEL TINY
CODESEG
ORG 100H
SYMS_M EQU OFFSET SYMS-23H
MAIN:
MOV AH,20H
MOV BX,SYMS_M
MOV SI,82H
VAL:
LODSB
SUB AL,0DH
JZ QUIT
XLATB
XOR AL,AH
INT 29H
XOR AH,AH
JMP VAL
QUIT:
RET
SYMS DB "nubtqphsoe"
END MAIN
ENDS
```
[Answer]
# [Befunge-93](https://github.com/catseye/Befunge-93), 105 bytes
Terrible implementation, it works at least, input is each digit of the number then any other character to terminate. Feel free to suggest any optimisations.
```
~::68*`vnubtqphsoe
v+4*96_@
`
@_68*8--0 v
v <
v:~<,-*84g<
>:68*` v
v+4*96_@
`
@_68*8--0 g,^
```
[Try it online!](https://tio.run/##S0pNK81LT/3/v87KysxCK6EsrzSppLAgozg/lUuhTNtEy9Is3oFLIYHLIR4obaGra6BQxqWgoFCmAAU2XGVWdTY6uloWJuk2XHZgQ0BKsOtN14n7/9/MwtQyBQA "Befunge-93 – Try It Online")
[Answer]
# [Zsh](https://www.zsh.org/), 29 bytes
```
<<<${(C)$(tr 0-9 nubtqphsoe)}
```
[Try it online!](https://tio.run/##qyrO@P/fxsZGpVrDWVNFo6RIwUDXUiGvNKmksCCjOD9Vs/b/fzMLU0sA "Zsh – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~63~~ 60 bytes
Saved 3 bytes thanks to [AZTECCO](https://codegolf.stackexchange.com/users/84844/aztecco)!!!
```
f(a,l)int*a;{l--&&f(a,l)+putchar("nubtqphsoe"[a[l]]-!l*32);}
```
[Try it online!](https://tio.run/##ZZPfboIwFIfveYquiYZiyRQUIWy7W7IX8MqRhT91kjBAgcTM8Oyu0FLgDKPAx3d6fi01Nr/j@PE46SHNSJrXRujfM9NcLgVZlU0dn8OrjvMmqi/luSoYPobHLAjMp8ywLeK3D16GfsI014l21xA/OlCzqv4KN8cAvaL7hm6o11IJrQFadK2gPUJbwa2AHvUm5TsBHerS3QQ7cgAF9kOxpZA7IJfuqcPLt9TmDccab0ixpurb@sOkDGkJSc5QzUrNRKVXiVVGlU0lUp3HNoJkokuV/rLipMtm5FneGwOgaGZY0LCgYUPDhsYWGlto7KCxg4YDDQcae2jsoeFCw4WGBw2PyGXsNq2B2K1kcc0SsZT40DBMET5EuTjV3emd9fCjKMXDnkX9b1Gdy0sdNT3Pm@6D5fin4qp3ryrNE3bjg699efkyTwgDEh@tVr1JkPizzPYWH0lusd4J/KmCMpYPQvZPUImSIU/SpeE1fctk1rA7yivXTzpeJFhswiOXAjKO2GpQReYbwhNDzJLyHhOoZH1Rkc9uqdVrEJml22rt4w8 "C (gcc) – Try It Online")
Inputs a pointer to an array of digits and its length (since there's no way to know how long an array passed into a function as a pointer is in C) and prints the corresponding systematic chemical symbol.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 41 bytes
```
V.T,.T]."buÞ“;UØ".T]."09I–Ò"=:zeNhN;rz3
```
[Try it online!](https://tio.run/##K6gsyfj/P0wvREcvJFZPKamU4/C8Q5OtQw/PUAILGFh6HprGdHiSkq1VVapfhp91UZXx//9mFqaWAA "Pyth – Try It Online")
## Explanation
The main part of the program is `.T,.T]."buÞ“;UØ".T]."09I–Ò"`, which returns the list `[['u', '1'], ['b', '2'], ['t', '3'], ..., ['n', '0']]`. `."buÞ“;UØ"` is the packed string `ubtqphsoen`, and `."09I–Ò"` is the packed string `1234567890`. `.T]` splits them into characters, and `.T,` zips them together.
# Pyth, 24 bytes
```
Vz=+k@."bu\nL‘"vN;rk3
```
[Try it online!](https://tio.run/##K6gsyfj/P6zKVjvbQU8pqZSNIybP59BEcaUyP@uibOP//80sTC0B "Pyth – Try It Online")
This one is a port of [HyperNeutrino's Python 3 answer](https://codegolf.stackexchange.com/a/214049/91569).
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 24 bytes
```
q~{"nubtqphsoe"1/=}%(eu\
```
[Try it online!](https://tio.run/##S85KzP3/v7CuWimvNKmksCCjOD9VyVDftlZVI7U05v//aAMFCwUzIDZVsFQwVzAGsiwUjIAsEM8cyDaIBQA "CJam – Try It Online")
Input in the form of a digit array string.
[Answer]
# [Raku](http://raku.org/), 29 bytes
```
*.trans(^10=>'nubtqphsoe').tc
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfS6@kKDGvWCPO0MDWTj2vNKmksCCjOD9VXVOvJPm/tUJxYqWCkkq8gq2dQnWagkp8rZJCWn6Rgo2hoaWCoZEBEBsrWFpa2v0HAA "Perl 6 – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~142~~ ~~100~~ 94 bytes
```
$k=[string]$args;0..9|%{$k=$k.replace([string]$_,'nubtqphsoe'[$_])};get-culture|% t*o|% *se $k
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/XyXbNrq4pCgzLz1WJbEovdjaQE/Pska1Giiukq1XlFqQk5icqgFXEq@jnleaVFJYkFGcn6oerRIfq1lrnZ5aoptcmlNSWpRao6pQopUPJLWKUxVUsv///29oaAkA "PowerShell – Try It Online")
[Answer]
# JavaScript, ~~264~~ ~~157~~ ~~150~~ 100 bytes
-107 bytes by replacing `if` statements with a JavaScript object to match each number with a corresponding string.
-7 bytes by using ES6 `for` loop through a string, and shorter arrow functions.
-50 bytes by replacing JavaScript Object with ES6 string indexing.
```
a='';o='nubtqphsoe';x=c=>a+=o[c];for(let e of prompt())x(e);alert(a[0].toUpperCase()+a.substring(1))
```
[Answer]
# [Lexurgy](https://www.lexurgy.com/sc), 101 bytes
Map a digit to its respective letter.
```
Class D {\0,\1,\2,\3,\4,\5,\6,\7,\8,\9}
a:
@D=>{N,U,B,T,Q,P,H,S,O,E}/$ _
@D=>{n,u,b,t,q,p,h,s,o,e}
```
[Answer]
## bash + coreutils, ~~40~~ 37 bytes
```
c=`tr 0-9 nubtqphsoe<<<$1`
echo ${c^}
```
] |
[Question]
[
Whenever I search for the running length of a movie in IMDb, it is displayed in minutes. Immediately I would try to convert it into hour(s) and minute(s). It would be better if we could automate this.
Input:
```
150 min
```
Output:
```
2 hours 30 minutes
```
Input:
```
90 min
```
Output:
```
1 hour 30 minutes
```
Input:
```
61 min
```
Output:
```
1 hour 1 minute
```
Input:
```
60 min
```
Output:
```
1 hour 0 minute or 1 hour 0 minutes
```
**Following are the conditions:**
1. Input and Output should be in this exact format.
2. Input minutes will between 0 and 240.
3. Your answer can accept command line arguments or read input from the
user or a function.
4. Output should not be enclosed within quotes.
5. Output must be printed, not returned.
**Leaderboard:**
```
var QUESTION_ID=65106,OVERRIDE_USER=16196;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/65106/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}#answer-list{padding-right: 100px}
```
```
<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>
```
# Result:
Its a tie between CJam and Pyth. Accepting CJam's answer as it was submitted before Pyth's 35 bytes code. However, please continue encouraging new submissions.
[Answer]
# Python 3, ~~50~~ ~~67~~ ~~119~~ ~~116~~ ~~112~~ ~~111~~ ~~104~~ 94 bytes
~~I'm not fond of going back to `%`-style string formatting, but it saves 6 bytes on `.format`.~~
**Edit:** Forgot to parse input.
**Edit:** Forgot to handle plurals.
~~**Edit:** Yay lambdas!~~
**Edit:** Added ungolfing
**Edit:** Darn it. Lambdas didn't help.
**Edit:** Since the minutes have maximum three digits, and `int()` doesn't mind spaces in the string, I can save a few bytes by using `input()[:3]`.
```
i,j=divmod(int(input()[:3]),60);print(str(i),"hour"+("s"[:i!=1]),str(j),"minute"+("s"[:i!=1]))
```
Ungolfed:
```
string = input()[:3]
hours, minutes = divmod(int(string), 60)
a = string(div)
b = "hour" + ("s" if hours == 1 else "")
c = string(mod)
d = "minute" + ("s" if minutes == 1 else "")
print(a, b, c, d)
```
[Answer]
# CJam, ~~39~~ 35 bytes
```
ri60md]"hour minute"S/.{1$1>'s*+}S*
```
[Try it online](http://cjam.aditsu.net/#code=ri60md%5D%22hour%20minute%22S%2F.%7B1%241%3E's*%2B%7DS*&input=90%20min)
Latest version includes improvements suggested by @MartinBüttner, particularly using the element-wise vector operator instead of transposing the two lists.
Explanation:
```
ri Get input and convert to integer.
60md Split into hours and minutes by calculating moddiv of input.
] Wrap hours and minutes in a list.
"hour minute"
String with units.
S/ Split it at spaces, giving ["hour" "minute"]
.{ Apply block element-wise to pair of vectors.
1$ Copy number to top.
1> Check for greater than 1.
's Push 's.
* Multiply with comparison result, giving 's if greater 1, nothing otherwise.
+ Concatenate optional 's with rest of string.
} End block applied to both parts.
S* Join with spaces.
```
[Answer]
# JavaScript, 78 bytes
```
n=>(h=(n=parseInt(n))/60|0)+` hour${h-1?"s":""} ${m=n%60} minute`+(m-1?"s":"")
```
```
<!-- Try the test suite below! --><strong id="bytecount" style="display:inline; font-size:32px; font-family:Helvetica"></strong><strong id="bytediff" style="display:inline; margin-left:10px; font-size:32px; font-family:Helvetica; color:lightgray"></strong><br><br><pre style="margin:0">Code:</pre><textarea id="textbox" style="margin-top:5px; margin-bottom:5px"></textarea><br><pre style="margin:0">Input:</pre><textarea id="inputbox" style="margin-top:5px; margin-bottom:5px"></textarea><br><button id="testbtn">Test!</button><button id="resetbtn">Reset</button><br><p><strong id="origheader" style="font-family:Helvetica; display:none">Original Code Output:</strong><p><div id="origoutput" style="margin-left:15px"></div><p><strong id="newheader" style="font-family:Helvetica; display:none">New Code Output:</strong><p><div id="newoutput" style="margin-left:15px"></div><script type="text/javascript" id="golfsnippet">var bytecount=document.getElementById("bytecount");var bytediff=document.getElementById("bytediff");var textbox=document.getElementById("textbox");var inputbox=document.getElementById("inputbox");var testbtn=document.getElementById("testbtn");var resetbtn=document.getElementById("resetbtn");var origheader=document.getElementById("origheader");var newheader=document.getElementById("newheader");var origoutput=document.getElementById("origoutput");var newoutput=document.getElementById("newoutput");textbox.style.width=inputbox.style.width=window.innerWidth-50+"px";var _originalCode=null;function getOriginalCode(){if(_originalCode!=null)return _originalCode;var allScripts=document.getElementsByTagName("script");for(var i=0;i<allScripts.length;i++){var script=allScripts[i];if(script.id!="golfsnippet"){originalCode=script.textContent.trim();return originalCode}}}function getNewCode(){return textbox.value.trim()}function getInput(){try{var inputText=inputbox.value.trim();var input=eval("["+inputText+"]");return input}catch(e){return null}}function setTextbox(s){textbox.value=s;onTextboxChange()}function setOutput(output,s){output.innerHTML=s}function addOutput(output,data){output.innerHTML+='<pre style="background-color:'+(data.type=="err"?"lightcoral":"lightgray")+'">'+escape(data.content)+"</pre>"}function getByteCount(s){return(new Blob([s],{encoding:"UTF-8",type:"text/plain;charset=UTF-8"})).size}function onTextboxChange(){var newLength=getByteCount(getNewCode());var oldLength=getByteCount(getOriginalCode());bytecount.innerHTML=newLength+" bytes";var diff=newLength-oldLength;if(diff>0){bytediff.innerHTML="(+"+diff+")";bytediff.style.color="lightcoral"}else if(diff<0){bytediff.innerHTML="("+diff+")";bytediff.style.color="lightgreen"}else{bytediff.innerHTML="("+diff+")";bytediff.style.color="lightgray"}}function onTestBtn(evt){origheader.style.display="inline";newheader.style.display="inline";setOutput(newoutput,"");setOutput(origoutput,"");var input=getInput();if(input===null){addOutput(origoutput,{type:"err",content:"Input is malformed. Using no input."});addOutput(newoutput,{type:"err",content:"Input is malformed. Using no input."});input=[]}doInterpret(getNewCode(),input,function(data){addOutput(newoutput,data)});doInterpret(getOriginalCode(),input,function(data){addOutput(origoutput,data)});evt.stopPropagation();return false}function onResetBtn(evt){setTextbox(getOriginalCode());origheader.style.display="none";newheader.style.display="none";setOutput(origoutput,"");setOutput(newoutput,"")}function escape(s){return s.toString().replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}window.alert=function(){};window.prompt=function(){};function doInterpret(code,input,cb){var workerCode=interpret.toString()+";function stdout(s){ self.postMessage( {'type': 'out', 'content': s} ); }"+" function stderr(s){ self.postMessage( {'type': 'err', 'content': s} ); }"+" function kill(){ self.close(); }"+" self.addEventListener('message', function(msg){ interpret(msg.data.code, msg.data.input); });";var interpreter=new Worker(URL.createObjectURL(new Blob([workerCode])));interpreter.addEventListener("message",function(msg){cb(msg.data)});interpreter.postMessage({"code":code,"input":input});setTimeout(function(){interpreter.terminate()},1E4)}setTimeout(function(){getOriginalCode();textbox.addEventListener("input",onTextboxChange);testbtn.addEventListener("click",onTestBtn);resetbtn.addEventListener("click",onResetBtn);setTextbox(getOriginalCode())},100);function interpret(code,input){window={};alert=function(s){stdout(s)};window.alert=alert;console.log=alert;prompt=function(s){if(input.length<1)stderr("not enough input");else{var nextInput=input[0];input=input.slice(1);return nextInput.toString()}};window.prompt=prompt;(function(){try{var evalResult=eval(code);if(typeof evalResult=="function"){var callResult=evalResult.apply(this,input);if(typeof callResult!="undefined")stdout(callResult)}}catch(e){stderr(e.message)}})()};</script>
```
For the test suite, enter input like `"61 min"` into the input box.
### Explanation
```
n=> //Define anonymous function w/ parameter n
(h= //start building the string to return with h, the # of hours
(n=parseInt(n)) //parse input for n
/60|0)+ //set h to floor(n / 60)
` hour //add ' hour' to the string to return
${h-1?"s":""} //add 's' to the string to return if h != 1, else add ''
//<--(a single space) add ' ' to the string to return
${m=n%60} //set m, the # of miuntes, to n % 60, and add it to the string to return
minute`+ //add ' minute' to the string to return
(m-1?"s":"") //add 's' to the string to return if m != 1, else add ''
//implicitly return
```
[Answer]
# Pyth, 39 38 bytes
```
jd.iJ.Dv-zG60+Vc"hour minute")m*\s>d1J
```
[Answer]
# [Vitsy](https://github.com/VTCAKAVSMoACE/Vitsy), ~~57~~ ~~54~~ 52 bytes
Oh, wow, I don't even have integers in my language. o-o
```
VVa6*Dv/D1M-D1m'ruoh 'Z' 'OVvM1m'etunim 'Z
N1-(['s']
```
```
VV Capture the input as a final global
variable, and push it again.
a6*Dv/1M- Get floor(input/60), capturing 60 as a
temp variable in the process.
DN Duplicate and output it as a number.
1-(['s'] If it is only one, push 's'.
'ruoh ' Push ' hour'
Z Output everything.
' 'O Output a space.
V Push the input.
v Get the temp variable (60).
M Modulo.
N Output as a number.
1-(['s'] If it is only one, push 's'.
'ruoh ' Push ' hour'
Z Output everything.
```
[Try it online!](http://vitsy.tryitonline.net/#code=VlZhNipEdi9EMU0tMW0ncnVvaCAnWicgJ09Wdk0xbSdldHVuaW0gJ1oKRE4xLShbJ3MnXQ&input=&args=MjQx&debug=on)
[Answer]
# K5, ~~55~~ 51 bytes
```
" "/(" hour";" minute"){y,x,("s";"")1=.y}'$25 60\.*" "\
```
This is more general than it strictly has to be; might still golf it down further.
In action:
```
f: " "/(" hour";" minute"){y,x,("s";"")1=.y}'$25 60\.*" "\;
f'("61 min";"120 min";"150 min")
("1 hour 1 minute"
"2 hours 0 minutes"
"2 hours 30 minutes")
```
## Edit:
This program went through several very different iterations in the course of development, and I thought that it might be more illuminating to show some of the intermediate steps.
Here was my first stab at the problem, before the pluralization requirement was introduced. There is clear repetition here:
```
{($_x%60)," hours ",($_60!x)," minutes"}@.*" "\
```
I realized that the general way to handle casting out of places was K5's "decode" form. To slot values into place in the string I used the "dot-apply" primitive, which applies an argument list to a function and unpacks the list into individual parameters:
```
{x," hours ",y," minutes"}.$25 60\.*" "\
```
Not much redundancy left here. When pluralization was added, I decomposed that leading anonymous function into a transformation I could apply to each number, like this:
```
{x,y,("s";"")1=.x}
```
Join `x`, `y`, and either `s` or nothing, depending on whether `x` is equal to "1". Ultimately it worked better to reverse the order of the arguments to this function.
## Edit 2:
```
" "/(" hour";" minute"){y,x,("s";"")1=.y}'$25 60\.*" "\
" "/(" hour";" minute"){y,x,(~1=.y)#"s"}'$5 60\.-4_
```
Several small improvements here. A better way of selecting an "s" or an empty string, a shorter constant for "decode" which reflects the limited range of input, and a simpler way of discarding "min".
[Answer]
## Pyth, 46 bytes
```
jKdm++J.v+++hd:z03K60K+td*\s>J1c"/hour %minute
```
Takes input as `x min` and outputs `x hours y minutes`
Try it [Here](https://pyth.herokuapp.com/?code=jKdm%2B%2BJ.v%2B%2B%2Bhd%3Az03K60K%2Btd*%5Cs%3EJ1c%22%2Fhour+%25minute&input=162+min&debug=1)
Explanation:
```
m~~~~~~~~~~~~~~~~~~~~~~~~~~~c"/hour %minute - map(func, "/hour %minute".split(" "))
hd - Get the first character of the string (/ or %)
:z03 - Get the first 3 characters of input
+++ K60 - Join them together and add a space and 60 to the end
J.v - Evaluate it and set result to J
td - Get all the characters of the string but the first (hour, minute)
+ *\s>J1 - If the result of the evaluated expression is less than 1, add an 's' character to the string
++ K - Join the results seperated with a space
jKd - Join the 2 halves together with a space
```
[Answer]
## [Perl 6](http://perl6.org), ~~80~~ 73 bytes
80 byte original
```
{my$h=$_ div 60;my$m=$_%60;"$h hour{'s'x?($h-1)}"~" $m minute{'s'x?($m-1)}"x?$m}
```
Usage:
```
.say for (150,90,61,60).map:
{my$h=$_ div 60;my$m=$_%60;"$h hour{'s'x?($h-1)}"~" $m minute{'s'x?($m-1)}"x?$m}
```
```
2 hours 30 minutes
1 hour 30 minutes
1 hour 1 minute
1 hour
```
Due to a change in the question I can remove `x?$m` from the end of the function, which allows me to reduce it by 3 more bytes.
```
{my$h=$_ div 60;my$m=$_%60;"$h hour{'s'x?($h-1)} $m minute{'s'x?($m-1)}"}
```
```
2 hours 30 minutes
1 hour 30 minutes
1 hour 1 minute
1 hour 0 minutes
```
[Answer]
# JavaScript (ES6), ~~100~~ ~~94~~ ~~89~~ 81 bytes
```
t=>(h=0|(t=parseInt(t))/60)+' hour'+(h>1?'s ':' ')+t%60+' minute'+(t%60>1?'s':'')
```
De-golfed demo (converted to ES5, as not all the browsers support ES6 yet)
```
function s(t) {
return (h = 0 | (t = parseInt(t)) / 60) + ' hour' + (h > 1 ? 's ' : ' ') + t % 60 + ' minute' + (t % 60 > 1 ? 's' : '');
}
alert(s(prompt()))
```
[Answer]
# C#, 127 bytes
```
var i=int.Parse(Console.ReadLine().Split(' ')[0]);Console.Write(i/60+" hour"+(i/60>1?"s ":" ")+i%60+" minute"+(i%60>1?"s":""));
```
This can be put in a file and run via the [C# interactive shell](http://www.mono-project.com/docs/tools+libraries/tools/repl/) that comes with Mono, using the default configuration.
[This is my first attempt at code golf. I hope that my contribution is not violating any rules.]
[Answer]
# C, 89 bytes
```
main(n){scanf("%d",&n);printf("%d hour%s %d minute%s",n/60,"s"+119/n,n%60,"s"+(n%60<2));}
```
[Answer]
# Ruby, 75 bytes
```
a,b=gets.to_i.divmod 60;$><<"#{a} hour#{a>1??s:''} #{b} minute#{b>1??s:''}"
```
[Answer]
# MATLAB, ~~111 108~~ 106 bytes
```
i=sscanf(input(''),'%d');h=fix(i/60);m=i-h*60;fprintf('%d hour%c %d minute%c\n',h,'s'*(h~=1),m,'s'*(m~=1))
```
This also works with **Octave**, and can be tried [here](http://octave-online.net/?s=QHPazBNGkfyhbhbdFrYAnJeGZmDvKMKYapOgHyikJRbmUTQP). The link is to a workspace already containing the code in a file named `runningLength.m`. So to test it out simply enter `runningLength` at the prompt, then enter the input string, e.g. `'123 mins'` and it will display the output.
Takes the input as a string, e.g. `'123 mins'`, converts it to a number (which implicitly ignores the `mins` bit).
```
i=sscanf(input(''),'%d');
```
Minutes and hours are then calculated
```
h=fix(i/60);m=i-h*60;
```
Then displays the output string
```
fprintf('%d hour%c %d minute%c',h,'s'*(h~=1),m,'s'*(m~=1));
```
The 's' bit of the output is calculated and handled correctly - an 's' is added whenever the number is not 1.
[Answer]
# Haskell, ~~117~~ 109 bytes
```
f x|(d,m)<-divMod(read$take 3 x)60=putStr$u[d#"hour",m#"minute"];u=unwords;1#q=u["1",q];p#q=u[show p,q++"s"]
```
Less golfed version:
```
f :: String -> IO ()
f x = putStr (unwords [(n`div`60)#"hour",(n`mod`60)#"minute"])
where
n :: Int
n = take 3 (read x)
(#) :: Int -> String -> String
1#q = unwords ["1",q]
p#q = unwords [show p,q++"s"]
```
`f` is a function which takes the first 3 characters of its input and converts them to an integer.
`p#q` is a function which pluralises `q` if `p` is not equal to 1. In order to return the result without surrounding quotes, I used `putStr` to print the result to STDOUT.
Thanks to nimi for the help!
[Answer]
# Python 2, ~~79~~ 77 bytes
```
m=int(raw_input()[:3])
print m/60,"hours"[:4+m/120],m%60,"minutes"[:6+m/2%30]
```
The first 3 characters of the input are simply parsed as an integer. This only works because the third character in a 2 digit input is a space, which `int` will ignore during conversion.
[Answer]
# LabVIEW, 50 Bytes
This is counted according to [my suggestion on Meta](http://meta.codegolf.stackexchange.com/a/7589/39490).
The code is pretty straight forward, take number from input Modulo by 60 and add an s for minutes != 1. Other side of case just puts the string through.
[](https://i.stack.imgur.com/rNrO3.jpg)
[Answer]
# Scala, 135 bytes
```
var a=(i:String)=>{var (v,b)=(i.split(" ")(0).toInt,(i:Int)=>if(i<2)""else"s");printf(v/60+" hour"+b(v/60)+" "+v%60+" minute"+b(v%60))}
```
**Usage:**
```
a("120 min")
2 hours 0 minute
```
[Answer]
# Haskell, ~~107~~ 101 bytes
```
g=putStr.f.read.take 3;s!1='1':s;s!n=show n++s++"s";f x|(a,b)<-divMod x 60=" hour"!a++' ':" minute"!b
```
Ungolfed:
```
g :: String -> String
g = putStr . f . read . take 3
where
(!) :: String -> Int -> String
s!1 = '1':s
s!n = show n++s++"s"
f :: Int -> String;
f x
| (a,b) <- divMod x 60 = " hour"!a ++ ' ':(" minute"!b)
```
`s!n` prepends `n` to `s`, adding a `'s'` to the end if `n /= 1`.
`f x` does the formatting after using `divMod`.
Since we can assume a max input of `240`, `take 3` is sufficient to take only the number.
(Had to try really hard to beat @Craig Roy's score...)
[Answer]
# R, 112 bytes
**Edit**: Fixed a scoping error and then addressed the quotation output issue.
```
g=function(x){h=floor(x/60);m=x%%60;cat(paste(h,ifelse(h==1,"hour","hours"),m,ifelse(m==1,"minute","minutes")))}
```
### Test cases
```
> g(150)
2 hours 30 minutes
> g(90)
1 hour 30 minutes
> g(61)
1 hour 1 minute
> g(60)
1 hour 0 minutes
```
I tried to save space by trying to find a way to just add or subtract "s" as necessary but I had to mess with the `sep =` argument in the `paste()` function and it didn't really seem like it was going to save me very much space. Any suggestions?
### Ungolfed
```
g=function(x){
h=floor(x/60);
m=x%%60;
cat(paste(h,
ifelse(h==1,"hour","hours"),
m,
ifelse(m==1,"minute","minutes")))
}
```
Rounding down with input/60 or input%%60 (mod) gives the hours and minutes respectively. Chain them together with an `ifelse()` statement that specifies whether or not the units are hour(s) or minute(s).
[Answer]
# Ruby, ~~97~~ ~~100~~ ~~99~~ 88 bytes
**Edit:** Fixing output.
**Edit:** Removing braces from `divmod`.
**Edit:** Yay string interpolation! Thanks to [Vasu Adari](https://codegolf.stackexchange.com/users/16196/vasu-adari). Also, better ungolfing.
```
i,j=gets.split[0].to_i.divmod 60;puts"#{i} hour#{i==1?"":"s"} #{j} minute#{j==1?"":"s"}"
```
Ungolfed:
```
input = gets Input
number = input.split[0].to_i Get number, convert to int
hours, minutes = number.divmod 60 hours == s / 60, minutes == s % 60
result = hours.to_s+" hour" Start with the hours
result += {hours == 1 ? "" : "s"} Put in the first "s" if plural
result += minutes.to_s+" minute" Add the minutes
result += {minutes == 1 ? "" : "s"} Put in the second "s" if plural
puts result Output
```
[Answer]
# Go, 177 Bytes
(It includes only the function and the import statements)
```
import("fmt";c"strconv";t"strings")
func f(s string){p,_:=c.Atoi(t.Split(s," ")[0]);t:=fmt.Printf;h:=p/60;m:=p%60;t("%d Hour",h);if h>1{t("s")};t(" %d Minute",m);if m>1{t("s")}}
```
Pretty solution -
```
func f(s string) {
p, _ := c.Atoi(t.Split(s, " ")[0])
t := fmt.Printf
h := p / 60;m := p % 60
t("%d Hour", h)
if h > 1 {
t("s")
}
t(" %d Minute", m)
if m > 1 {
t("s")
}
}
```
Testing it -
```
func main() {
ip_list := []string{
"120 min",
"150 min",
"60 min",
}
for _, ip_val := range ip_list {
f(ip_val)
fmt.Println("")
}
}
/* OUTPUT
2 Hours 0 Minute
2 Hours 30 Minutes
1 Hour 0 Minute
*/
```
[Answer]
# Mathematica, 61 bytes
```
Print@ToString[Quantity@#~UnitConvert~MixedRadix["h","min"]]&
```
[Answer]
## Python 2, 96 bytes
```
i=int(raw_input().split()[0])
print"%d hour%s %d minute%s"%(i/60,"s"*(i>120),i%60,"s"*(i%60!=1))
```
[Answer]
## [AutoHotkey](http://www.autohotkey.com), ~~174~~ ~~170~~ 160 bytes
```
x::Send,% !i?"x" i:=SubStr(clipboard,1,(Clipboard~="\s")):"{Backspace "StrLen(i)"}" i//60 " Hour"(i//60!=1?"s ":" ")Mod(i,60)" Minute"(Mod(i,60)!=1?"s":"")i:=""
```
Notes:
1. Input from Clipboard
2. Output prints to any form by pressing `x`
3. Correctly handles plurals
4. Could be smaller but I wanted a provide a One Liner.
[Answer]
# PHP, ~~77~~ 76 bytes
```
$m=($i=$argv[1])%60;echo$h=$i/60|0," hour","s"[$h<2]," $m minute","s"[$m<2];
```
horible, horible, horible!
PHP only issues a couple of `Notice`s for `"s"[$h<2]`
To run: `php -r 'CODE' '150 minutes'`
and of course turn error reporting off/away from stdout!
Edit: -1byte assign in assign (credit: insertusernamehere)
It's so ugly I must give a run helper for linux users:
```
php -c /usr/share/php5/php.ini-production.cli -r 'CODE' '61 min'
```
[Answer]
# [Arcyóu](https://github.com/nazek42/arcyou) (non-competitive), 93 bytes
*This submission uses a version of the language that was created after this challenge.*
```
(: x(#((v(l))0)))(: h(#/ x 60))(: m(% x 60))(% "%d hour%s %d minute%s"(' h(* s([ h))m(* s([ m
```
Yeesh! This language needs better string manipulation.
Explanation:
```
(: x ; Set x
(# ; Cast to int
((v (l)) 0))) ; First element of input split on spaces
(: h (#/ x 60)) ; Set h to the hours
(: m (% x 60)) ; Set m to the minutes
(% ; String format
"%d hour%s %d minute%s"
(' ; List
h ; Hours
(* s([ h)) ; Evaluates to 's' if h is not 1
m ; Minutes
(* s([ m ; Evaluates to 's' is m is not 1
```
[Answer]
# Ruby, ~~74~~ ~~73~~ 71 bytes
```
->i{puts"#{i=i.to_i;h=i/60} hour#{h>1??s:''} #{m=i%60} minute#{m>1??s:''}"}
```
**73 bytes**
```
->i{puts"#{h,m=i.to_i.divmod 60;h} hour#{h>1??s:''} #{m} minute#{m>1??s:''}"}
```
**74 bytes:**
```
->i{h,m=i.to_i.divmod 60;puts "#{h} hour#{h>1??s:''} #{m} minute#{m>1??s:''}"}
```
**Usage:**
```
->i{puts"#{i=i.to_i;h=i/60} hour#{h>1??s:''} #{m=i%60} minute#{m>1??s:''}"}[61]
1 hour 1 minute
```
[Answer]
## Kotlin, 132 bytes
```
val m={s:String->val j=s.split(" ")[0].toInt();print("${j/60} hour${if(j/60==1)"" else "s"} ${j%60} minute"+if(j%60==1)"" else "s")}
```
Ungolfed Version:
```
val m = { s: String ->
val j = s.split(" ")[0].toInt();
print("${j / 60} hour${if(j / 60 == 1) "" else "s"} ${j % 60} minute" + if(j % 60 == 1) "" else "s")
}
```
Test it with:
```
fun main(args: Array<String>) {
for(i in arrayOf(150, 90, 61, 60)) {
m("$i min")
println()
}
}
```
Example outputs:
```
2 hours 30 minutes
1 hour 30 minutes
1 hour 1 minute
1 hour 0 minutes
```
[Answer]
## [Seriously](https://github.com/Mego/Seriously), 77 bytes
```
ε" min",Æ≈;:60:@\@:60:@%'sε(;)1≥I"%d hour"+(#@%'sε(;)1≥I"%d minute"+(#@%@k' j
```
Seriously is *seriously* not good at string manipulation. [Try it online with full explanation](http://seriouslylang.herokuapp.com/link/code=ee22206d696e222c92f73b3a36303a405c403a36303a40252773ee283b2931f24922256420686f7572222b282340252773ee283b2931f249222564206d696e757465222b28234025406b27206a) (you will need to manually enter the input like `"210 mins"` because permalinks don't like quotes).
Quick and dirty explanation:
```
ε" min",Æ≈ get input, replace " min" with the empty string, convert to int
;:60:@\@:60:@% calculate divmod
'sε(;)1≥I"%d hour"+ push "%d hour" or "%d hours", depending on whether pluralization is needed
(#@% format "%d hour(s)" with the # of hours calculated earlier
'sε(;)1≥I"%d minute"+ same as above, but with minutes
(#@% same as above, but with minutes
@k' j swap the order and join with a space to get "X hour(s) X minute(s)"
```
[Answer]
## Java 8, 148 Bytes
```
interface S{static void main(String[]b){int a=new Integer(b[0]),h=a/60,m=a%60;System.out.printf(h+" hour%s "+m+" minute%s",h>1?"s":"",m>1?"s":"");}}
```
I chose to post an alternative to @TheAustralianBirdEatingLouse as this is not only shorter by a good deal (~10%) but also more correct in printing hour(s) and minutes(s) instead of abbreviated hrs and mins. Method implementations in Interfaces are new to Java 8 - so this would be needed to compile/run
] |
[Question]
[
Given a string, capitalize it. By capitalization I mean `conTeNT-lENgth` changes to `Content-Length`. In the example I showed the string with 2 words with `-` as the word boundary. However I expect you to write the code for the string containing any number of words separated by a **single** character as the boundary. This boundary may change across the string.
**Conditions**
1. using `regular expressions` is **not allowed**.
2. there could be any number of words in a sentence(string).
3. each word will consist of `English` letters`[a-zA-Z]` of any case.
4. different words in the sentence will be separated by a single character. This character will **only** be any one of `-`, `.`, ` `, `/`, `&`, `#`. You can safely assume that sentence will **not** contain any other character except the mentioned ones.
5. word boundaries should be preserved in the output.
6. shortest code wins.
For example your program should output `Begin/With.Type&Content` for `BeGin/wITH.tyPE&conTeNt`.
```
Some test cases:
"aGeNT ACcEpT/LEngTh-tYPe USeR raNgE.TyPe"
"type&AgeNt/CC/COnteNt lEnGth#acCePT/AgeNt.RAnGe-Cc/contEnt/cODe"
"cc/rEspoNCe.lEngtH#tYpE-witH&UsEr/bEgIN&uSer.AGEnT&begIn/aCCEPt/Cc"
"lENgTH#USeR.tYpE/BeGiN&LENGth tYpe/ACCEpt#rANge/codE&AnD-ACCepT/ConTenT"
"contENT/ACcEpT"
"BeGin/wITH.tyPE&conTeNt"
"Code.cc#User.lenGTh-USer-AND&tyPE TypE&leNgtH.tYPe usER.UseR&with"
"RaNgE&COnTeNT WITh CoNTENT-TypE tyPe"
"BEgin COdE#uSeR#aGeNt.USeR"
"TypE LENGth"
```
[Answer]
**Python 3,22**
```
print(input().title())
```
This code will take a string as input from stdin and gives a capitalized output to stdout.
for example:
input:
```
BEGIN/wITH.tyPe&cOnTENt
```
ouput:
```
Begin/With.Type&Content
```
The following code is for multi-line inputs (if necessary)
**Python 3, 46**
```
import sys
for i in sys.stdin:print(i.title())
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 1 byte
Code:
```
‚Ñ¢
```
Explanation:
```
‚Ñ¢ # Implicit input which is converted to title case.
```
[Try it online!](http://05ab1e.tryitonline.net/#code=4oSi&input=Y2MvckVzcG9OQ2UubEVuZ3RII3RZcEUtd2l0SCZVc0VyL2JFZ0lOJnVTZXIuQUdFblQmYmVnSW4vYUNDRVB0L0Nj)
[Answer]
### GolfScript, 36 27 19 characters
```
0\{95&+.47>32*\}%\;
```
A quite basic GolfScript approach which works for all input according to the specification. The examples can be tested [online](http://golfscript.apphb.com/?c=ezBcezk1JisuNDc%2BMzIqXH0lXDtwdXRzfTpmOwoKImFHZU5UIEFDY0VwVC9MRW5nVGgtdFlQZSBVU2VSIHJhTmdFLlR5UGUiIGYKInR5cGUmQWdlTnQvQ0MvQ09udGVOdCBsRW5HdGgjYWNDZVBUL0FnZU50LlJBbkdlLUNjL2NvbnRFbnQvY09EZSIgZgoiY2MvckVzcG9OQ2UubEVuZ3RII3RZcEUtd2l0SCZVc0VyL2JFZ0lOJnVTZXIuQUdFblQmYmVnSW4vYUNDRVB0L0NjIiBmCiJsRU5nVEgjVVNlUi50WXBFL0JlR2lOJkxFTkd0aCB0WXBlL0FDQ0VwdCNyQU5nZS9jb2RFJkFuRC1BQ0NlcFQvQ29uVGVuVCIgZgoiY29udEVOVC9BQ2NFcFQiIGYKIkJlR2luL3dJVEgudHlQRSZjb25UZU50IiBmCiJDb2RlLmNjI1VzZXIubGVuR1RoLVVTZXItQU5EJnR5UEUgVHlwRSZsZU5ndEgudFlQZSB1c0VSLlVzZVImd2l0aCIgZgoiUmFOZ0UmQ09uVGVOVCBXSVRoIENvTlRFTlQtVHlwRSB0eVBlIiBmCiJCRWdpbiBDT2RFI3VTZVIjYUdlTnQuVVNlUiIgZgoiVHlwRSBMRU5HdGgiIGY%3D&run=true).
[Answer]
## JavaScript (94)
```
prompt().split(l='').map(function(a){return l='A'>l?a.toUpperCase():a.toLowerCase()}).join('')
```
[Answer]
# Mathematica 62
**Data**
```
tests={"aGeNT ACcEpT/LEngTh-tYPe USeR raNgE.TyPe","type&AgeNt/CC/COnteNt lEnGth#acCePT/AgeNt.RAnGe-Cc/contEnt/cODe","cc/rEspoNCe.lEngtH#tYpEwitH&UsEr/bEgIN&uSer.AGEnT&begIn/aCCEPt/Cc","lENgTH#USeR.tYpE/BeGiN&LENGth tYpe/ACCEpt#rANge/codE&AnD-ACCepT/ConTenT","contENT/ACcEpT","BeGin/wITH.tyPE&conTeNt","Code.cc#User.lenGTh-USer-AND&tyPE TypE&leNgtH.tYPe usER.UseR&with","RaNgE&COnTeNT WITh CoNTENT-TypE tyPe","BEgin COdE#uSeR#aGeNt.USeR","TypE LENGth"}
```
---
**Code**
```
StringReplace[ToLowerCase@#,WordBoundary~~x_:>ToUpperCase@x]&
```
---
**Usage**
```
f["aGeNT ACcEpT/LEngTh-tYPe USeR raNgE.TyPe"]
```
>
> "Agent Accept/Length-Type User Range.Type"
>
>
>
```
f /@ tests
```
>
> {"Agent Accept/Length-Type User Range.Type",
>
> "Type&Agent/Cc/Content Length#Accept/Agent.Range-Cc/Content/Code",
> "Cc/Responce.Length#Type-With&User/Begin&User.Agent&Begin/Accept/Cc",
> "Length#User.Type/Begin&Length Type/Accept#Range/Code&And-Accept/Content", "Content/Accept",
>
> "Begin/With.Type&Content",
>
> "Code.Cc#User.Length-User-And&Type Type&Length.Type User.User&With",
>
> "Range&Content With Content-Type Type",
>
> "Begin Code#User#Agent.User",
>
> "Type Length"}
>
>
>
[Answer]
**PHP : 78 73 65 64 characters**
```
$b=ucfirst;foreach(str_split($s)as$c)echo$b($c),!$b[0]=$c<A?u:l;
```
Input is passed in `$s`. It operates on the string as an array of characters.
It is a simple 2 state machine. It relies on lexical ordering of strings, and that the parser automatically assumes you meant to type a string in some cases.
The state is being stored in `$b` and is being represented as the name of the function that needs to be called on the next character. `ucfirst` and `lcfirst` are shorter to type and have identical behaviour to `strtolower`/`strtoupper` on single character strings. Also, since they only differ by one letter, we can use them efficiently to store the state. The original version needed to store the state explicitly in a boolean.
Since echo doesn't print anything for boolean false, I used a comma and the `!` operator to "hide" the assignment(which in this case is truthy) in the echo statement. This allowed me to save a character by removing the `{}`.
[Answer]
## C, 83
```
n;main(c){c=getchar();putchar(c>96?n?c:(n=c-32):c&64?n?c+32:(n=c):(n=0,c));main();}
```
Takes lines on `stdin`, translates them to `stdout`. (Prefers `SIGINT` to `EOF`.)
[Answer]
# Powershell: 37 - 43
Depending on how you want to take the input...
**Prompt the user for input: 43**
```
(Culture).TextInfo.ToTitleCase((read-host))
```
**Take input from pipeline: 38**
```
(Culture).TextInfo.ToTitleCase($input)
```
**Provide input as an argument when running the script: 37**
```
(Culture).TextInfo.ToTitleCase($args)
```
---
**NOTE:** The above scripts will ignore all-caps words, leaving them as-is. If this needs to be accounted for, the input should be forced to lower-case before the Title Case conversion. This adds 10 characters to the first method, and 12 to the other two.
```
(Culture).TextInfo.ToTitleCase((read-host).ToLower())
(Culture).TextInfo.ToTitleCase("$input".ToLower())
(Culture).TextInfo.ToTitleCase("$args".ToLower())
```
[Answer]
## Java - 209 characters
```
class C{
public static void main(String[]a){
for(String b:a){
char[]k=b.toLowerCase().toCharArray();
for(int i=-1;i<k.length;i++){if(i<0||"-. /&#".indexOf(k[i])>=0)k[++i]=(char)(k[i]-32);}
System.out.println(k);}}}
```
I added newlines only for readability.
[Answer]
### R, ~~143~~ 116
A solution a bit long maybe but here we go:
```
f=function(x){a=sapply(1:nchar(x),function(y)substr(tolower(x),y,y));d=c(1,which(!a%in%letters)+1);a[d]=toupper(a[d]);cat(a,sep="")}
```
Slightly ungolfed and explained:
```
f <- function(x){
#Split the string in characters and "lower-case" everything
a <- sapply(1:nchar(x),function(y)substr(tolower(x),y,y))
#Select the first character and each character following a
#character that doesn't belong to lower case alphabet
d <- c(1,which(!a%in%letters)+1)
#Make those ones uppercase.
a[d] <- toupper(a[d])
#Output (stdout) while pasting them back together.
cat(a,sep="")
}
```
**Edit**: 116 characters
The main challenge here is to vectorize `substr`. Here's another less verbose way.
```
f=function(x){n=1:nchar(x);a=mapply(substr,tolower(x),n,n);d=c(T,!a%in%letters);a[d]=toupper(a[d]);cat(a[n],sep="")}
```
Indented:
```
f <- function(x){
n <- 1:nchar(x)
a <- mapply(substr,tolower(x),n,n)
d <- c(T,!a%in%letters) #This has been simplified as well
a[d] <- toupper(a[d])
cat(a[n],sep="") #Because a is now 1 char longer than x, need to subset a
}
```
Usage:
```
> f("aGeNT ACcEpT/LEngTh-tYPe USeR raNgE.TyPe")
Agent Accept/Length-Type User Range.Type
```
[Answer]
# Befunge 98 - ~~24~~ 45
```
~\j:'``!3*j' -;:'``b*j:'/`!3*j' +#;:,'/`!jc#@
```
Writing this hurt my brain.
This takes input through `~` and if the previous character was one of the separators (or if there was no previous character), it executes
```
:'``!3*j' -;
```
This snippet takes the character, and if its ascii value is greater than or equal to `a`, it subtracts 32 from it, thus changing it to upper case. If it is less than `a`, `3*j` skips the adjustment. Afterwards, it skips the next part. This part handles changing from upper case to lower case (I'm sure it can be merged with the next part; I'm just not sure how):
```
:'``b*j:'/`!3*j' +#;
```
The character is printed (`,`), then this checks if the character is one of the boundaries:
```
'/`!
```
It basically compares the character to the ascii value of `/`. If the character is not a boundary, the code pushes `12` so that it will skip the capitalization adjustment the next time around. `#` skips over the end program: `@`, and if the end of the input is reached, `~` sends the code execution back to the `@`, ending the program.
[Answer]
# Ruby: ~~60~~ ~~51~~ ~~50~~ 47 characters
```
$_.downcase.chars{|c|$><<$/=$/<?0?c.upcase: c}
```
Sample run:
```
bash-4.1$ for line in "${test[@]}"; do printf '%-75s | %s\n' "$line" "$( ruby -ne '$_.downcase.chars{|c|$><<$/=$/<?0?c.upcase: c}' <<< "$line" )"; done
aGeNT ACcEpT/LEngTh-tYPe USeR raNgE.TyPe | Agent Accept/Length-Type User Range.Type
type&AgeNt/CC/COnteNt lEnGth#acCePT/AgeNt.RAnGe-Cc/contEnt/cODe | Type&Agent/Cc/Content Length#Accept/Agent.Range-Cc/Content/Code
cc/rEspoNCe.lEngtH#tYpE-witH&UsEr/bEgIN&uSer.AGEnT&begIn/aCCEPt/Cc | Cc/Responce.Length#Type-With&User/Begin&User.Agent&Begin/Accept/Cc
lENgTH#USeR.tYpE/BeGiN&LENGth tYpe/ACCEpt#rANge/codE&AnD-ACCepT/ConTenT | Length#User.Type/Begin&Length Type/Accept#Range/Code&And-Accept/Content
contENT/ACcEpT | Content/Accept
BeGin/wITH.tyPE&conTeNt | Begin/With.Type&Content
Code.cc#User.lenGTh-USer-AND&tyPE TypE&leNgtH.tYPe usER.UseR&with | Code.Cc#User.Length-User-And&Type Type&Length.Type User.User&With
RaNgE&COnTeNT WITh CoNTENT-TypE tyPe | Range&Content With Content-Type Type
BEgin COdE#uSeR#aGeNt.USeR | Begin Code#User#Agent.User
TypE LENGth | Type Length
```
[Answer]
# JavaScript (string->string), 67 bytes
```
s=>[...s].map(a=>l=a[`to${'A'>l?'Upp':'Low'}erCase`](),l='').join``
```
Try it:
```
f=s=>[...s].map(a=>l=a[`to${'A'>l?'Upp':'Low'}erCase`](),l='').join``
console.log(f('aGeNT aCcEpT/LEngTh-tYPe USeR raNgE.TyPe'));
console.log(f('type&AgeNt/CC/COnteNt lEnGth#acCePT/AgeNt.RAnGe-Cc/contEnt/cODe'));
console.log(f('cc/rEspoNCe.lEngtH#tYpE-witH&UsEr/bEgIN&uSer.AGEnT&begIn/aCCEPt/Cc'));
console.log(f('lENgTH#USeR.tYpE/BeGiN&LENGth tYpe/ACCEpt#rANge/codE&AnD-ACCepT/ConTenT'));
console.log(f('contENT/ACcEpT'));
console.log(f('BeGin/wITH.tyPE&conTeNt'));
console.log(f('Code.cc#User.lenGTh-USer-AND&tyPE TypE&leNgtH.tYPe usER.UseR&with'));
console.log(f('RaNgE&COnTeNT WITh CoNTENT-TypE tyPe'));
console.log(f('BEgin COdE#uSeR#aGeNt.USeR'));
console.log(f('TypE LENGth'));
```
# [Jacob](https://codegolf.stackexchange.com/users/108687/jacob)'s variant - JavaScript (char[]->char[]), 55 bytes
```
s=>s.map(a=>l=a[`to${'A'>l?'Upp':'Low'}erCase`](),l='')
```
Try it:
```
f=s=>s.map(a=>l=a[`to${'A'>l?'Upp':'Low'}erCase`](),l='')
g = s => f([...s]).join``
console.log(g('aGeNT aCcEpT/LEngTh-tYPe USeR raNgE.TyPe'));
console.log(g('type&AgeNt/CC/COnteNt lEnGth#acCePT/AgeNt.RAnGe-Cc/contEnt/cODe'));
console.log(g('cc/rEspoNCe.lEngtH#tYpE-witH&UsEr/bEgIN&uSer.AGEnT&begIn/aCCEPt/Cc'));
console.log(g('lENgTH#USeR.tYpE/BeGiN&LENGth tYpe/ACCEpt#rANge/codE&AnD-ACCepT/ConTenT'));
console.log(g('contENT/ACcEpT'));
console.log(g('BeGin/wITH.tyPE&conTeNt'));
console.log(g('Code.cc#User.lenGTh-USer-AND&tyPE TypE&leNgtH.tYPe usER.UseR&with'));
console.log(g('RaNgE&COnTeNT WITh CoNTENT-TypE tyPe'));
console.log(g('BEgin COdE#uSeR#aGeNt.USeR'));
console.log(g('TypE LENGth'));
```
[Answer]
## C# – 110
A simple finite-state-machine-based processing:
```
x.Aggregate(new{b=1>0,r=""},(s,c)=>new{b="-. /&#".Contains(c),r=s.r+(s.b?Char.ToUpper(c):Char.ToLower(c))}).r
```
(where `x` is the `string` to capitalize)
and of course, if you want to be boring (after the specification was updated), you can use
```
new CultureInfo(9).TextInfo.ToTitleCase(x)
```
or, with all the boring boilerplate:
```
class C{static void Main(string[]a){System.Console.WriteLine(new System.Globalization.CultureInfo(9).TextInfo.ToTitleCase(a[0]));}}
```
[Answer]
## Javascript 102
```
prompt().split(o=q='').map(function(c){o+=(q)?c.toLowerCase():c.toUpperCase(),q=('A'>c)?0:1})
alert(o)
```
[Answer]
## Forth, 135
```
: s swap ;
: c 1 begin key dup 96 > if s if 32 - then 0 s
else dup 64 > if s 0= if 32 + then 0 s then else 1 s then then emit again ; c
```
Translated output is written to `stdout` as it reads from `stdin`.
[Answer]
## Befunge-98 (29), C (65)
Since the method/algorithm is pretty much the same, I include both versions in the same post. Both rely on keeping track of whether the last character was a symbol or letter, in order to know whether to lowercase a letter or not.
**Befunge-98 (29)**
```
#@~:'0` #v_,0>
',++@'% '< ^
```
**C (65)**
```
c,d;main(){for(;~(c=getchar());d=c>48)putchar(c<48?c:c&95|32*d);}
```
[Answer]
# [Python 3](https://docs.python.org/3/), 122 bytes
```
lambda s:''.join(chr(ord(c)+[[0,0],[0,32],[-32,0]][('@'<c<'[')-('`'<c<'{')]['@'<p<'['or'`'<p<'{'])for c,p in zip(s,'-'+s))
```
[Try it online!](https://tio.run/##XVFRa9swGHzfrxA1yDaNpdK8jQ7mKsIJFMW4CqN4gTmyYntkspBVSrofn33KoOC@2NLpu@O@O3v2/WiWl@O3n5dT8@fQNmj6Gsfk9ziYRPUuGV2bqPS2ru8Wd/sFfJf38MuW93Dd10n8PX5QD3Edp1kS/7qe/8bpvg64DfjoAmwDvE@Po0NqYdFg0Ptgk2kRZ/HtlKYX6wbjk2Ny0xRaSJQzxa2kT9x0ss/8S6nR7llXyDWi40SeS32Tpl8@SP5sNc47LTxljLKt8XBEJ24K30eNYrqU9PpMqtwUOmOKqtF4bjxV29VcSynq@GRHwTQBhc6vI/9iefY2@DXeTdzRA@82Ar8@a0fyghuJD7rbGNowxkswoGZyJy46uY6CexJ06KMuBoGfuABvCBBNcyBaH7lcdBp8tRznZpUBqiECNhqpjZxbDN4FrHRNafYU1A1928g18eeSYxXows9m2NhqolS0m2CDkzYFRAz@XJaLFQ4sJM@W45MWsDy5hv868YrAfIUhhn6mVoVKMGQuQ3E/NrJHbBQS/GVBBvnPZT3yDupn25ZHkGEVhcY9CQHNxq7k/zEBfvkH "Python 3 – Try It Online")
Not a great score, but I wanted to try it without builtin string operations for case changing.
[Answer]
## [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), ~~113~~ ~~103~~ 98 bytes
```
{OFS=""
for(n=split($0,a,"");i<=n;s=a[++i]){$i=(L?tolower(s):toupper(s))
L=!(index("-. /&#",s))}}1
```
[Try it online!](https://tio.run/##JZFRa9swFIXf9StUuwiHxlL7us4MV9GcQFCMozDK2IOr3DlmRja2QhZKf3t65b6Jq3N1zndUX/7dbu@7n/ssisjffkxcNg1d65P7x2W9jKLFc/s9c89TVv9@eGj/LN7v2yzZ/vB9119gTKbFN9@fh2E@Lsg2u0tad4T/SZRyKlgcLXH88fF0u9UFaENzadVgxFa5xpxS/1oCPeyhomOtG8XNtQTirwOwvAHthZRC7pzHI@2UK/wprq2E0oj5mle5KyCVVtjeeeW8sLsVEGvFqKah1xI4bjV@HfvXQaWX1q/ZYVKjeFPNRrPzHkaeF8oZ9gbNxolaSlWiqSWd0o1ZxyEZD7viBYpWs63SmIHiBESO4sHHY64bQP@jYrlbpTgFxJO9M@AMmXNpjDtTk/CKE5eNWXN/LRWzQaY9kf0RuLXxYcJEHbgCq0HvMc31igUlNddBsQ40wvC5tPOkKo76iiHWiVShPoZdmVDyr405Udlrg95pWKU@FPuimtZRuTuqGNmrOPyI5wGSzKIvvE8)
This works fine for single line content, but for multi-line input a few more inits need to be added
## [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 104 bytes
```
{OFS=i=s=L=""
for(n=split($0,a,"");i<=n;s=a[++i]){$i=(L?tolower(s):toupper(s))
L=!(index("-. /&#",s))}}1
```
[Try it online!](https://tio.run/##JZFRa9swFIXf9Ss0uwiHxtL2us4MV9GcgFGMozDK2IOr3DlmRja2QhZKf3t65b2Jq3N1znfUXP/e72/7H4esy@aszKKI/BmmxGXz2Hc@efi8btZRtHrqvmXuac6aX4@P3e/V20OXJeV3P/TDFaZkXn31w2Ucl@OKlNmnpHMn@JdEKaeCxdEax@/vX@73pgBtaC6tGo0olWvNOfUvFdDjAWo6NbpV3NwqIP42Astb0F5IKeTeeTzSXrnCn@PGSqiMWK55nbsCUmmFHZxXzgu73wCxVkxqHgctgeNW67exfxlVeu38lh1nNYlX1e40uxxg4nmhnGGv0O6caKRUFZpa0ivdmm0ckvGwK56h6DQrlcYMFCcgchSPPp5y3QL6nxTL3SbFKSCeHJwBZ8iSS2PchZqEV5y47syW@1ulmA0y7YkcTsCtjY8zJurBFVgNek9prjcsKKm5jYr1oBGGL6VdZlVz1NcMsc6kDvUx7MqEkn/uzJnKQRv0TsMq9aHYZ9V2jsr9ScXIXsfhRzwPkGQR/cf7AA "AWK – Try It Online")
It would have been nice to take advantage of AWK's automatic splitting of a record into fields and modifying said fields, but that throws away the field separators. :(
This update throws away the idea of tacking characters onto a string and then printing the string. Instead, each character becomes its own field. Without the `OFS=""` bit, each character/field would be separated by a space when printed, which isn't what was requested.
Realizing that "" is essentially the same thing as 0 in AWK shortens the byte-count for the multi-line version a little bit. (I know it's different... I said 'essentially' :p )
[Answer]
# QBasic, 74 bytes
```
1c$=LCASE$(INPUT$(1))
IF f=0THEN c$=UCASE$(c$)
f=c$>"@
?c$;
IF""<c$GOTO 1
```
Bytes are counted in [CP-437](https://en.wikipedia.org/wiki/Code_page_437); is a single byte (character code 20).
The input method here is a bit strange: characters are typed one at a time, and their capitalization is converted before they are displayed. So when you type in `aGeNT`, it appears on screen as `Agent`. Hitting `Enter` ends the program.
[Answer]
# [Python 3](https://docs.python.org/3/), 9 bytes
```
str.title
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v7ikSK8ksyQn9f9/AA "Python 3 – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) + `-pF`, 42 bytes
```
$\.=~$=?uc:lc,$==index'?/.- &#',$_ for@F}{
```
[Try it online!](https://tio.run/##K0gtyjH9/18lRs@2TsXWvjTZKidZR8XWNjMvJbVC3V5fT1dBTVldRyVeIS2/yMGttvr//0T3VL8QBUfnZNeCEH0f17z0kAzdksiAVIXQ4NQghaJEv3RXvZDKgNR/@QUlmfl5xf91C9wA "Perl 5 – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~20~~ 15 bytes
```
f: ă†‚Ä¢∆õ·∏£v‚á©$‚áßp;f‚àë
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJmOsqAxKDigKLGm+G4o3bih6kk4oencDtm4oiRIiwiIiwiWW91cmUgYS1uRXJkIl0=)
Or, if that's too long:
## 1 byte
```
«ê
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLHkCIsIiIsIllvdXJlIGEtbkVyZCJd)
## Explained
```
f: ă†‚Ä¢∆õ·∏£v‚á©$‚áßp;f‚àë
f: # Push two copies of the letters of the input
Ä # is each letter in the first copy in the alphabet?
Ġ # group that on consecutive elements - this has the effect of grouping words.
• # reshape the other copy of the letters to have the same shape as that
∆õ # to each sublist L:
·∏£v‚á© # push L[0] and [lower(x) for x in L[1:]] - on single length strings this just leaves L[0] on the stack.
$‚áßp # uppercase L[0] and prepend it to the other list
; # close map
f‚àë # deep flatten and summate to get a single string - the `d` flag would save 3 bytes here by removing this pair and allowing structure autocompletion to save a byte.
```
[Answer]
# Excel VBA, 13 characters
In the Immediate window
```
?[Proper(A1)]
```
Function takes input from cell `A1`
## VBScript
```
Set xlapp = CreateObject("excel.application")
wscript.echo xlapp.Evaluate("Proper(""BeGin/wITH.tyPE&conTeNt"")"
```
[Answer]
# [Go](https://go.dev), 153 bytes
```
import."strings"
func f(s string)(o string){c:=0<1
for i:=range s{x:=s[i:i+1]
if c{o+=ToUpper(x);c=!c}else{o+=ToLower(x)}
c=Contains("-. /&#",x)}
return}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jZJBitswFIahS59CtcE4TC11diVtFq4inMCgGI9CGUoXHkVWTB3JyAqZELLtHUo3odBD9CjtaSo5nUUns-jK4n9Pv7_3P337LvXpZ1fxz5UUYFM1Kmg2nTYWhvXGhj-2tk7f_Pr6qPXWNEr2YVBvFQd10oOzMkr04-nAx5PX766DWhvQjCemUs64PzyMJ_3HZtxcXX8Kmhrwg76aML3sOmGSh9FbPnnJj6LtxVm_0btBPwZ8grWyjqtPwhQCFEfhK68bYbdGHc-Av198GYA8fzICh6BwKLZVSZ2A8L3IG4V2czaDdl-QmGvFBLUhGI3-6atyQRnIMCcdQzdESbZO7V0hwPJWlMBUVBLI9oUIwdObdt-JOJPOFGGM8EJZdwQtUbldRxXHomBoKMMyU7lIMUcOwhJlEV9MnzHkHBnSd5piAZ2NtLPI3nUk3TV2Fi97YtA9kXMab2-FgVlOFIvvhZwrVGFMCkfBLz1bQiWbRX4Y6M2Qz4XGN4Q6SuAUgTJ3u7ORyagUjnBF4kxNU6cKlwj2sSn2DKwfhboJh-Qu6_-bP9YrATmPlr0bqhUqd_k7WpNmdBr7m4DtOxK3gro84LCZbU9K6PrL2CWzvvx16ZcWu4Uwv9oPc7YGWFPmaFPvBeywzqe8RDYK4MWKRC7fMvLvwkKf20XrYHJOcKj9fY6n0_n7Bw)
[Answer]
# [Julia 1.0](http://julialang.org/), 9 bytes
```
titlecase
```
[Try it online!](https://tio.run/##fVHRitswEHy/rxAxiDuoJfoDB66yOIFDMT6Fchx98CmL7OIqxt5wDfTf010H@tg3MTujnZn9eRmH7uvv240GGjF2C95@ddPjUD7/Ax6Hpy/vD2oTzzmgD@UIPlG/YeQb1kO2n/uwM3RtQN8ZJKOuZqqqXIQp2BfIKfQlvTWojq/YqrnzCUy4NrhRTKbrhLpKLLXOWXfIxE81Qq6pL7rosAl2HZu2yjWWLlpeRZDJxsP2/keMdoZlOnuHhpWJdgW9TVB@DrTTxwVm@wFp7/XlFWdT1ZCD/sC0z7ZzDhpeHNdvJFzYFeLSiN5KRq9fwLMXxQjaigUTFXPlE7KPE@gqb0tGkaM6qSCHuyXx6Nn62sIK/acxdz6hibE4LmxwxFxzY2xjLiu/1UJW4TqBHpHbZ7V0eVmgNcxvNafs1wWtNKu5QjmV@r4PvXJnH9hGKXJF0rkYgTRk5Q4nKLiRtpB7kZHYMl2p98ybhx9Pyvx5VtM8ZBrz7S8 "Julia 1.0 – Try It Online")
[Answer]
# [Thunno](https://github.com/Thunno/Thunno), \$2\log\_{256}(96)\approx\$ 1.65 bytes
```
zV
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhaLqsIgDCh_wXanVPfMPP1yzxAPvZLKAFe15Py8kFS_Eog0AA)
Just a built-in solution.
[Answer]
# JavaScript (Node.js), ~~54~~ 53 bytes
Exact same score as [the RegEx approach](https://tio.run/##NZHhauswDIV/3z1FaMC0sNhP0EHmirRQ3JC5XMY2WOpqbkZmm8S7XZ@@V07ZPyMdSd85/mz/taMZuhAL5494/Vhex@XDyKPf@jMOsh1xvuADhr41OBevBy7s/c/y4YcU@xB@FYur8W70PfLe2/nL3Z9ZW6HSWSkNBC224Kw@FfG5xmz/hE02tMoC15caZ/ckjpeArLSoopBSyJ2L9Mx6cFU85a2RWGsxtXlTugoLaQTdi@CiMLvVbYcxYoAxeCUJgu7FdR6fAxTnLq7ZfoRBHMBuFPt@woGXFTjNDmg3TrRSQk2HzbSmB2X1Ok@UPM2LR6w6xbagiCWjCoqSBkLMh1JZJI4jsNKtCqoiWZXeaXT6hpQYFaFPKUyltM2J80avebzUwEySqzj1JH0ANybfj0TYo6soMuIYilKtWFJn@hKA9ajIHJ/C/B6h4aRvGNk8TVuaFC2jDHX6gL8bfcqkV5o4ijSexd/QH8F2LpO7I@SUSZOnH4s8GZ/ak/hme3b3xr/aMP9Y8E/fufdX9764/gc) would have been!
```
s=>Buffer(s.toLowerCase()).map(x=c=>x=x>64?c:c^32)+``
```
[Try it online!](https://tio.run/##NZHditswEIWvu09hYhAxXUuwLb0oOIujCCcQFONVKEt/iFeZOF68krGVJnn6dKTQOzE6M/OdM@/133rUQ9u71Ng93A7Zbcxm89PhAMN0pM6u7RkGXo8wTRL6UffTS6az2SW7zL59fdbf9Z8vT8nn3e6mrRltB7SzzfTnw6dJXYBUUc616BVbC9OoY@peS4i2L1BFQy0bQdW1hMkjit21B5I3IB3jnPGNcfiMOmEKd4xrzaFULHzTKjcFpFwz3OeEcUxvFvcZWrNBjL2VHCFwn1vG7rUX6bl1S7IdxcDeRLOS5PQCA80LYRR5g2ZlWM25KHGxDmM6IRu1jD0l9f1sDkUryVpIZImwAizHht7FQy4bQI69ILlZpFgFtMqtUWDUHckzSkQPKYSSn2bYeaWW1F1LQbSXSxf@OB6Aah1vRyTswBQYGXIMaS4XxKsjde0F6UCiORrCPI2ioqivCNo8himVj5Zghsof4MdKHSNupUKO1LdH7n/oc9G0JuKbvYgxkyr2F3PUGw/fQXy3PXn4HU5/SOi7bc3ul9klt38) (includes all test cases)
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 36 bytes
```
{,/{`c$x-32*~!#x}'_(&1,~~"a{"'_x)_x}
```
[Try it online!](https://ngn.codeberg.page/k#eJytU1FP2zAQfu+v8BpkYCK22DShtU9ZsNpKKFTBCCGEILhuEtE5WWJEuor+9t05ho0HJKTxFOfu/H3f3X1ejjYHfHOrdrrw65fP209B97R7s0cPD7bbYbYZ7t50+zfd02BgR5udq/W2GS0JId34trof790us3I17sbrcbN//TSwV8NsohNJoliJWvITYXJZhPZyrsn5mU5JkyW5YHI918PxMMq1sSRSSteWn2iT2yKU6xpKW92QNDO5Zvg/vEZgCycKVxLL45jHp8bCkayEmdgiyFSs55K7NEsjM9FhrLiqjBXGcnV6jHzSI0AEkjEkkb8nDrwMl2aOO/xbBN+Fl6EUb0RbV0msGZDndhrYy1qEj6Wd0vNWNPxO5LOEPpzphkUTYSS90/nM8CyOxRyZQQkgpxpAjNLM86O48KK0BcXu+Q+dl8YdmZNEXYB7lQDixKxEkstpgKNlqAKuTcqEnogEhkIgonkEtLUNmijJNQxkIWhkjkOIatgPtCe1kaDIq3CEKMUL6MPERXruwM3GDQSQFuGzon5QfkY49wTW4VyA/fox9sV9EUo1/HEmp8yu54Iq1JJYqO5bxVk4KfQVNhIzpXqlK20m4C/ovwmj5JgiEIoVdKUTWA1zzntoRcqgPqWwpMLJAYzYY3jj4TmEhqhzoOPtM+zFkojRUNTVS0nRzBScKNHyFzNZkLhKJHSONhbE9jZ3A3tuguB14n/CFy4/EgGNk/h0IQKwTxrgW7IMt/s8FYLSne6gdyoe+8uOst+897q3NqQHfFBYW7cjjhbQebVastZm6l53qnDvTFU/+a8H3dqyMi0//Pb96IirrC5ttip/67C1TWnyAXn/8yZQ/L9PFjE+4L0hzEe9FCfptb0x9JaZIfX/hkWCd3kNhbxtIcj+65HBH29m7oE=)
* `_(&1,~~"a{"'_x)_x` split input after each non-letter and lowecase it, e.g. `"Begin/With.Type&Content"` to `("begin/";"with.";"type&";"content")`
* `{`c$x-32*~!#x}'` subtract 32 from the first character in each word and 0 from the rest (in effect capitalizing the first letter and leaving the others unchanged)
* `,/` flatten back into a single string and (implicitly) return
[Answer]
## T-SQL, 179
```
DECLARE @T VARCHAR(MAX)='foo',@X VARCHAR(2),@ INT=0WHILE @<LEN(@T)SELECT @X=SUBSTRING(@T,@,2),@+=1,@T=STUFF(@T,@,1,IIF(@X LIKE'[a-Z]_',LOWER(RIGHT(@X,1)),UPPER(RIGHT(@X,1))))PRINT @T
```
Try the SELECT version in SQL Server 2012 [here](http://sqlfiddle.com/#!6/d41d8/21970).
Replace "foo" with the input string. The char count is for a zero-length string. This code traverses the string using an index, uppercasing or lowercasing the character at that position based on the previous character.
] |
[Question]
[
My [boss](https://codegolf.stackexchange.com/questions/137209/efficient-robot-movement) now wants me to implement a mechanism that lets him search for an item in an array, and gives him the index/indices where that value occurs.
## Your Task:
Write a program or function that receives an array and a value (String, Integer, Float, or Boolean), and returns the indices of the array at which the value occurs (either 0 or 1 indexed, whichever you prefer). If the value is not in the array return an empty array.
## Input:
An array A and a value V, that may or may not be present in A.
## Output:
An array containing the indice(s) at which the V occurs in A, or, if V does not occur in A, an empty array.
## Test Cases:
Please note that the test cases are 0 based.
```
12, [12,14,14,2,"Hello World!",3,12,12] -> [0,6,7]
"Hello World", ["Hi", "Hi World!", 12,2,3,True] -> []
"a", ["A",True,False,"aa","a"] -> [4]
12, [12,"12",12] -> [0,2]
```
## Scoring:
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the lowest score in bytes wins.
[Answer]
# [Pyth](http://pyth.readthedocs.io), 2 bytes
0-indexed.
```
xE
```
**[Try it online!](http://pyth.herokuapp.com/?code=xE&input=%22a%22%0A%5B%22A%22%2CTrue%2CFalse%2C%22aa%22%2C%22a%22%5D&test_suite=1&test_suite_input=%5B12%2C14%2C14%2C2%2C%22Hello+World%21%22%2C3%2C12%2C12%5D%0A12&debug=0&input_size=2)** or **[Check all the Test Cases](http://pyth.herokuapp.com/?code=xE&input=%22a%22%0A%5B%22A%22%2CTrue%2CFalse%2C%22aa%22%2C%22a%22%5D&test_suite=1&test_suite_input=%5B12%2C14%2C14%2C2%2C%22Hello+World%21%22%2C3%2C12%2C12%5D%0A12%0A%0A%5B%22Hi%22%2C+%22Hi+World%21%22%2C+12%2C2%2C3%2CTrue%5D%0A%22Hello+World%22%0A%0A%5B%22A%22%2CTrue%2CFalse%2C%22aa%22%2C%22a%22%5D%0A%22a%22%0A&debug=0&input_size=3)**
---
# Explanation
```
xEQ - Full Program. Takes Input from standard input. Q means evaluated input and is implicit at the end of the program.
x - Get all the indexes of x in y
E - Evaluated Input #2 - The value
Q - The list - Evaluated Input #1
```
[Answer]
# JavaScript, 39 bytes
```
e=>a=>[...a.keys()].filter(i=>a[i]===e)
```
```
f=
e=>a=>[...a.keys()].filter(i=>a[i]===e)
console.log(f(12)([12,14,14,2,"Hello World!",3,12,12]));
console.log(f("Hello World")(["Hi", "Hi World!", 12,2,3,true]));
console.log(f("a")(["A",true,false,"aa","a"]));
console.log(f(12)([12,14,14,2,"Hello World!",3,12,'12']));
```
The above snippet might not work on all browsers, so here's a [TIO link](https://tio.run/##FcnBCsIwDADQX9GdUqiBVm@Snf0DD6WHsqVSDYu0Q9jXdw7e7b3TL7Wplu96WXTmnqkzjYnGgIgJP7w1MBFzkZUrlH@FEomITZ90aSqMoi/I4LyB4Lx1t4O3w4NF9PTUKvN5sFd7nI/G3PsO).
[Answer]
# [MATL](https://github.com/lmendo/MATL), 2 bytes
```
mf
```
The `m` consumes two arguments, and checks each element in the array whether is equal to the other argument, `f` returns the indices of the truthy entries of an array.
[Try it online!](https://matl.suever.net/?code=mf&inputs=%7B%27Hi%27%2C+%27Hi+World%21%27%2C+12%2C+2%2C+3%2C+%27Hi+World%21%27%7D%0A%27Hi+World%21%27&version=20.2.2 "MATL – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 45 bytes
*-3 bytes thanks to @EriktheOutgolfer and @Chris\_Rands*
```
lambda y,x:[i for i,j in enumerate(x)if j==y]
```
**[Test Suite.](https://tio.run/##VYtBCoMwEEX3PcU0qwRmY@yqkEU3xQMIXVgXKSY0EhNJFfT06Si0tDD8gf/@G9fpGUOZrbpnr4dHp2HF5dw4sDGBwx5cABPmwSQ9Gb4IZ6FXam3zmFyYuOWFRGgoitN2ElllvI9wi8l3R4Ylbky2Qhw@xu@CkcwqR4/yKwE5ktQ6zebP1Pv@wnaCV@1fBpmmlkgLIER@Aw "Python 3 – Try It Online")**
Today I learned `enumerate(x) == zip(range(len(x)),x)`.
---
# [Python 3](https://docs.python.org/3/), 47 bytes
```
lambda n,l:[x for x in range(len(l))if l[x]==n]
```
**[Try it online!](https://tio.run/##FcmxCoAgEIDhV7maFG7JmgL33qDBHIy0hOsMabCnt4Kfb/mv5z4S9zXopZI7180BI42mQEgZCkSG7Hj3gjwLkjIGIFOs1mzrlSPfIohOIZiPbvhT2E6eKMGcMm1Niz3@T1kp6ws "Python 3 – Try It Online")** or **[Check all the Test Cases](https://tio.run/##VYtBCsIwEEX3nmLMKoHZNHUldOFGeoCCi5pFpIkGxqTECvX0cVpQFIY/8N9/42u6pVgX35wL2ftlsBCR9v0MPmWYIUTINl6dJBclKRU8UD@bpommjDnESXpZaYSeo9otp1G0jijBKWUatgJrXJg2Sm0@xu9CsCzawI/zKwE7mtUuP92fadf9QawEj5YeDoXllokBUKq8AQ)**
[Answer]
# R (+pryr), 20 bytes
```
pryr::f(which(a==b))
```
Which evaluates to the function
```
function (a, b)
which(a == b)
```
Where either `a` can be the value to look for and `b` the vector, or the other way around. When presented with two vectors of unequal lengths (a single value counts as a length-1 vector in R), R will wrap the shorter one to match the length of the longer one. Then the equality is checked. This generates a logical vector. `which` provides the indices where this vector is true.
[Try it online!](https://tio.run/##TYu7CsMwDEX3fIWqyQItcbt6yJCSIVMfdHbdmhhMDCGhn@9KLZSCuOI@zlKjq3Gbw5rKDMYz3Ama15TCZDw4J7ZG01qGoNoe9Czj8My5wK0s@bFD3rN2lgigiea/RAVxSPJFfwDI3gp2OV17ImX8d9nhJ@NjN557Ri@xVET1DQ "R – Try It Online")
[Answer]
# JavaScript (ES6), ~~44~~ 43 bytes
*Crossed out 44 is still regular 44 ;(*
```
v=>a=>a.map((x,i)=>x===v&&++i).filter(x=>x)
```
*Saved 1 bytes thanks to* [@Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)
```
let f=
v=>a=>a.map((x,i)=>x===v&&++i).filter(x=>x)
;
console.log(f(12)([12,14,14,2,"Hello World!",3,12,12])); // => [1,7,8]
console.log(f("Hello World")(["Hi", "Hi World!", 12,2,3,true])); // => []
console.log(f("a")(["A",true,false,"aa","a"])); // => [5]
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
QāsÏ
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/8Ehj8eH@//@jDY10FAxNIBjIVPJIzcnJVwjPL8pJUVTSUTAGyoBUGMVyGRoBAA "05AB1E – Try It Online")
1-indexed.
[Answer]
# C#, ~~88~~ 72 bytes
```
using System.Linq;a=>o=>a.Select((i,n)=>o.Equals(i)?n:-1).Where(n=>n>=0)
```
*Saved 16 bytes thanks to @LiefdeWen.*
[Try it online!](https://tio.run/##rZBNT8MwDIbv/RUmp0TqIlo4sbUITeNLIKHtsAPikHUeBKUOa1IQmvbbS9oKNgQ3sJTEid/keZ3CDUpLtiFVontRBcLs3Xks5Y2mdbSJIERhlHNw1@X9SRvOK68LeLV6CbdKExdfpZ2ojfOaipFdPGPh7x/i/W0MY2tMSLQlJy@QsNKFvJpQXWKlFgZHmnye57CCrFFZbrNcyRm2NzjXMYlwJCfrWhnHtTilk0Ei5PwJK@SU5ZRnh6IZRt/MjAPJGpTzSnsMPSJ3vtL0KK9taIEBi2HFCd/g0/AGkjSG5LgfIWWXaIyFua3M8iDIj@JekW4FT1IhxPBvQNgEhGYtSO8oLSLtYL6qEQJr3wf7H@wZ658PtfClYWFKtUYU64DqJ@ZX5hTVskPuibdRP2@bDw "C# (Mono) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
⁼€T
```
[Try it online!](https://tio.run/##y0rNyan8//9R455HTWtC/v//H21opKNgaALBQKaSB1BFvkJ4flFOiqKSjoIxUAakwij2v6ERAA "Jelly – Try It Online")
-1 thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder). (dyadic chains)
[Answer]
# [Haskell](https://www.haskell.org/), ~~41~~ 39 bytes
```
v!l=fst<$>(filter((==v).snd)$zip[1..]l)
```
[Try it online!](https://tio.run/##Xc7BaoQwEAbgc32K3@AhARHW9tgUKlTq2dIeFg8DyW5DU7ONqYfiu9uoFcpeZmDmn495p@FDWzvPY2rlaQj32QM/GRu051zKURRDr0T2Yy7HQ1F0VsyKAuFVtmiDN/15atD0YapRW0dhqlA5Z6G0N2Pc8qcvkXyS6SGhXHJziScBGXiDQynS49LyWO72UuZowZ7jRw5vzlvFcjS4zfdg2f1DrpLRWyaGbYbZxukqxGus@oKhwov/1lcU/QGPbA8svSY76BUk2mBiXQLMvw "Haskell – Try It Online")
*Saved two bytes thanks to @flawr*
Haskell is statically typed, so I had to use a little workaround to run the test cases.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 bytes
```
`fNm=
```
[Try it online!](https://tio.run/##yygtzv7/PyHNL9f2////xv@jTXWMdYyA2FjHMBYA "Husk – Try It Online") 1-indexed.
### Explanation
```
-- implicitly input a value v and a list L
m= -- map "equals v" over the list L, resulting in a list of truthy and falsy values
`fN -- filter the natural numbers N by discarding the numbers at falsy positions
and keeping the ones at truthy positions
```
[Answer]
# Ruby, ~~46 40~~ 39 bytes
```
->e,a{i=-1;a.map{|x|i+=1;x==e&&i}-[!1]}
```
Saved 7 bytes!!! thanks to Eric Duminil.
[Try it online.](https://tio.run/##KypNqvyfZvtf1y5VJ7E601bX0DpRLzexoLqmoiZT29bQusLWNlVNLbNWN1pRsSC29n@BQlq0oZGOAogwNAEhIx0lj9ScnHyF8PyinBRFJR1jHZCcUWzsfwA)
[Answer]
# Ruby, 38 bytes
```
->e,a{a.each_index.select{|x|a[x]==e}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf165YJ7E6US81MTkjPjMvJbVCrzg1JzW5pLqmoiYxuiLW1ra4tvZ/gUJatKGRjgKIMDQBISMdJY/UnJx8hfD8opwURSUdYx2QnFFs7H8A "Ruby – Try It Online")
[Answer]
# Google Sheets, 101 bytes
```
=IfError(Join(",",Filter(Column(Offset(A1,0,0,1,Counta(Split(B1,",")))),Exact(Split(B1,","),A1))),"")
```
Value `V` in `A1` and array `A` in `B1` with each entry separated by a comma. Null entires are not allowed (row 5 below shows what happens).
[](https://i.stack.imgur.com/fuURg.png)
Explanation:
`Offset(A1,0,0,1,Counta(Split(B1,",")))` returns a range that is one row tall and as many columns wide as there are entries in `A1`.
`=IfError(Join(",",Filter(Column(~),Exact(Split(B1,","),A1))),"")` filters the column numbers of that range based on whether or not the value in `A1` is exactly each of the values in `B1` and concatenates them all in a comma-delineated list.
[Answer]
# [Clojure](https://clojure.org/), 40 bytes
First attempt at code golf.
`keep-indexed` maps a function over a collection here, passing the current index into the callback and yielding any non-nil return values.
```
(fn[a b](keep-indexed #(if(= %2 a)%1)b))
```
[Try it online!](https://tio.run/##FYvBCoMwEAV/5VURdiEesu219/5BDyEHbVZIuyQSLPTvrcLAHIZ5WX1/m@5kuiEcXkqYMEf6qK5jLkl/mtBTXuiOQTDx4Hlm3iNobblsVkAKLwhenL@diOsealbxrM3SpXNXdzaJfHx/ "Clojure – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 2 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Takes item to look for as left argument (must be scalar to find an *item* of the lookup array rather than a subarray) and the lookup array (which may have up to 15 dimensions) as right argument. Returns list of indices, each of which may has as many elements as the number of dimensions in the lookup array.
```
⍸⍷
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGCo965yqk5RcpGOgmJRanpiiUpBaXFP/PzANKPurd8ah3@///hkYKmXkKQC1ewf5@CurRhkY6hiYgZKSj5JGak5OvEJ5flJOiqKRjrAOSM4pV59J41NWkjiSprolqhpJHppKOApCE61UAajUCmlBSVJoKNUBHPRFDn6MSWIVOWmJOcaqOUmKiEpBQAmrA4kolQyMlsHMA "APL (Dyalog Unicode) – Try It Online")
`⍸` **ɩ**ndices where
`⍷` found
[Answer]
## Batch, 86 bytes
```
@set i=0
:g
@if "%~2"=="" exit/b
@if %1==%2 echo %i%
@set/ai+=1
@shift/2
@goto g
```
Takes input as command line parameters (value then the array elements as separate parameters). Note: String quoting is considered part of the match e.g. `"1"` won't equal `1` (would cost 6 bytes).
[Answer]
# [Python 2](https://docs.python.org/2/), 49 bytes
```
lambda l,v:filter(lambda i:l[i]==v,range(len(l)))
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFHp8wqLTOnJLVIAyqSaZUTnRlra1umU5SYl56qkZOap5Gjqan5v6AoM69EIU0j2lBHwUhHwVhHwRCMjGKBlOZ/AA "Python 2 – Try It Online")
Not short enough, but I thought it was cool. ¯\\_(ツ)\_/¯
[Answer]
# [Perl 5](https://www.perl.org/), 28 bytes
```
sub{grep$_[$_]eq$_[0],1..@_}
```
[Try it online!](https://tio.run/##XYxRC4IwFIXf/RW3JViwJC0pkKJewh8Q9BAiE@8qWMw29yDRb1/TIEo4nAvn3PPVqERifQ4bsNqUz4vC2i/OfpHjw915TqMw3BUvm3pGI3BkjVEIgWZtkHrOgUsFPp9tJ1FMOy07xZRkKISEk1SiGhG66Lt4msIY9FUaUUGJEMEK1v@U3x2hQLLbx78kcKDY8Y7K4ACH97ppBzjWzfekf6cHJjRSwlzoisE6sW8 "Perl 5 – Try It Online")
The output is 1-indexed.
An anonymous function is quite unusual for Perl, but it happens to be the shortest I could think of. `grep ..., 1 .. @_` iterates over the indexes of the input array (actually it goes one cell beyond the last, but it doesn't matter), keeping only the index that satisfy `$_[$_]eq$_[0]`, ie. the ones where the value of the element (`$_[$_]`) is the same as the value we need to keep (`$_[0]`).
---
Slightly longer (31 bytes (30 + `-l` flag)), but as a full program:
```
$@=<>;$@eq$_&&print$.-1while<>
```
[Try it online!](https://tio.run/##K0gtyjH9r6xYAKQVdHP@qzjY2thZqzikFqrEq6kVFGXmlajo6RqWZ2TmpNrY/f9vaMQFQiYgZMSl5JGak5OvEJ5flJOiqMRlzAWRBgA "Perl 5 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~37~~ 33 bytes
```
import Data.List
findIndices.(==)
```
Thanks @Laikoni for -4 bytes!
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRzyezuIQrzTYtMy/FMy8lMzm1WE/D1lbzf25iZp6CrUJBUWZeiYKKQpqCkUK0kY6xjpGOCRCb6hjFcnH@BwA "Haskell – Try It Online")
[Answer]
# Java 8, ~~146~~ ~~113~~ ~~112~~ ~~111~~ ~~110~~ 108 bytes
```
import java.util.*;l->o->{List r=new Stack();for(int i;(i=l.indexOf(o))>-1;l.set(i,null))r.add(i);return r;}
```
-2 bytes thanks to *@TAsk* by using `Vector` instead of `ArrayList`.
-1 byte by using `Stack` instead of `Vector`.
0-indexed
**Explanation:**
[Try it here.](https://tio.run/##xVA9T8MwFNz7Kx6ebJS4SmFzG6kLYgAVqQMDYnATB5y6dmS/FKKqvz04UKBSGSsh@eN0d/K7cy23MnWNsnW57vWmcR6hjhxvURt@KQBgPIYHGWlXAb4qWHWo0sK1Fkcn/qq1BWpn@c0BiFFhZAhwL7XdjQACStQFfMvTufeyu9MBp4tVrQrMk1/ti0ngWM5zKGAGvUlzl@a7QQI/s@oNliiLNWWicp5qi6AF1TPDtS3V@6KijrE8zYThQSHViW2NYcxzWZZUM@EVtt6CF/texJRxNe3KxKCHvFunS9jEDnSJXtuXp2eQbOgDyy6g2nDXIm@igsbSgsumMR0dUp30o59M4DIMLM0mCWTXXztCcquMcfDovCkvSAJXURkcE8bY4dUBi3@Z/GMxJTlPBjKPk9C3KoFKmhAvIiUZTnI0VpLzNSbZhPz9n/vRvv8A)
```
import java.util.*; // Required import for Vector and Vector
l->o->{ // Method with List and Object parameters
List r=new Stack(); // Result-list
for(int i;(i=l.indexOf(o))>=-1;
// Loop as long as we can find the object in the list
l.set(i,null)) // After every iteration, remove the found item from the list
r.add(i); // Add the index to the result-list
// End of loop (implicit / single-line body)
return r; // Return the result-List
} // End of method
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
Qƶ0K
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/8Ng2A@///6MNdYx0jHVMdEyB2BjIhvNjuYwB "05AB1E – Try It Online")
**It is 1-indexed, as shown below:**
```
IN A-#------------------------> [2,3,3,3,4]
IN B-#------------------------> 3
-----#------------------------+-----------------
Q # Vectorized equivalence | [0,1,1,1,0]
ƶ # Lift by index | [0,2,3,4,0]
0K # Remove zeros | [2,3,4]
```
[Answer]
# Mathematica, 12 bytes
```
Position@##&
```
1-Indexed
**input** [Array,Value]
>
> [{12, 14, 14, 2, "Hello World!", 3, 12, 12}, 12]
>
>
>
**output**
>
> {{1}, {7}, {8}}
>
>
>
[Answer]
## Haskell, 29 bytes
```
e#l=[i|(i,h)<-zip[0..]l,h==e]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P1U5xzY6s0YjUydD00a3KrMg2kBPLzZHJ8PWNjX2f25iZp6CrUJBUWZeiYKKgqGRgrJCtIGOoY6hkY6xjgmIMtMxB1GWsf8B "Haskell – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 9 bytes
```
mȶV©YÄÃf
```
1-indexed.
Japt input doesn't support booleans, so they have been replaced with `0` and `1` in the test cases.
[Try it online!](https://codepen.io/justinm53/full/NvKjZr?code=bci2VqlZxMNm&inputs=WzEyLDE0LDE0LDIsIkhlbGxvIFdvcmxkISIsMywxMiwxMl0KMTI=,WyJIaSIsIkhpIFdvcmxkISIsMTIsMiwzLHRydWVdCiJIZWxsbyBXb3JsZCI=,WyJBIiwgMSwgMCwgImFhIiwgImEiXQoiYSI=,WzEyLCIxMiIsMTJdCjEy&flags=LVE=) with the `-Q` flag to format the array output.
## 0-indexed Solution, 11 bytes
```
l o f@gX ¶V
```
[Try it online!](https://codepen.io/justinm53/full/NvKjZr?code=bCBvIGZAZ1ggtlY=&inputs=WzEyLDE0LDE0LDIsIkhlbGxvIFdvcmxkISIsMywxMiwxMl0KMTI=,WyJIaSIsIkhpIFdvcmxkISIsMTIsMiwzLHRydWVdCiJIZWxsbyBXb3JsZCI=,WyJBIiwgMSwgMCwgImFhIiwgImEiXQoiYSI=,WzEyLCIxMiIsMTJdCjEy&flags=LVE=)
[Answer]
# [Perl 6](http://perl6.org/), 21 bytes
```
{grep :k,*===$^v,@^z}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Or0otUDBKltHy9bWViWuTMchrqr2v7VCcWKlQpqGoZGOAphQMjRS0lEwNNLUtP4PAA "Perl 6 – Try It Online")
The `:k` adverb to `grep` tells it to return the matching keys (indices) of the input sequence that match the predicate `* === $^v`.
If strings and numbers were considered equivalent, one could use a grep predicate of just `$^v` instead of `* === $^v`.
[Answer]
# Common Lisp, 66 bytes
```
(lambda(x s)(loop as i in s as j from 0 when(equal i x)collect j))
```
[Try it online!](https://tio.run/##TU/RagIxEHyuXzEulO6CQi/1udA3/8CHUiG9O2lk76KXE4XS/LpuTloaNmwmM5PN1BrS4coa4wG7OIAvSILQ44m5cii7WpVyoHWrGrGJgzZzwgsK50T4P0EwGMjE4U9pOmfyUWT2YIvJF9UbYUQfFOQN250IfkdS5Wh6uzjQRLD9rfOjOSinBd7zd055u8g/H1i@TtDfYX4kWASwZfLdZ@OnQPd8PiGUaKmc9tgNscMzzl9tz@3x5NXYi9RRta1H7EWuxWrtBg)
[Answer]
## [TXR Lisp](http://nongnu.org/txr), 26 bytes
```
(op where(op equal @@1)@2)
```
In other words, "Where is argument 2 equal to argument 1?"
Run:
```
1> (op where(op equal @@1) @2)
#<interpreted fun: lambda (#:arg-01-0166 #:arg-02-0167 . #:rest-0165)>
2> [*1 12 #(12 14 14 2 "Hello world!" 3 12 12)]
(0 6 7)
3> [*1 "Hello World" #("Hi" "Hi world!" 12 2 3 t)]
nil
```
[Answer]
## Clojure, ~~39~~ 38 bytes
```
#(filter(comp #{%2}%)(range(count %)))
```
A bit obscure :) The first input argument is a `vec` of values and the second one is the searched value. `%` maps indexes to values, and the set `#{%2}` returns truthy (the input argument `%2`) or falsy `nil` for that value. [comp](https://clojuredocs.org/clojure.core/comp) composes these together.
[Answer]
## C ~~340~~ ~~362~~ ~~166~~ 115 Bytes
Hello all. My first time here. I figured since I enjoy (attempting) to write optimized code I may as well give this a try.
@Rodney - ~39 bytes from the includes
@Zacharý - 7 bytes with implicit typing
**0-indexed**.
**How to Run:**
As per @Arnolds suggestion, the program takes arguments in a much more C friendly manner. This let me reduce the size of the file by a little more than half.
The arguments should be passed in the following order `value [element1 ...]`
where braces indicate optional arguments
You may or may not have to add escaped quotes to any strings that are provided in order to satisfy the condition of `12 != "12"`. On my system the this can be done in the following manner
```
prog-name.exe 12 3 "Hello" 12 4 "12"
Returns [2,4] < This is incorrect
prog-name.exe 12 3 "\"Hello\"" 12 4 "\"12\""
Returns [2] < Correct
```
---
golfed
```
#define P printf(
b=0;main(int c,char**v){P"[");for(--c;c-1;c--)b|=strcmp(v[1],v[c])?0:P b?",%i":"%i",c-2);P"]");}
```
ungolfed
```
#define P printf(
//Implicit only works in global(I totally knew this after almost 4 years of C :P)
b = 0;
main(int c,char**v)
{
P"[");
//match loop
//b is used to determine if this is the first iteration. it can be assumed that printf will always return >0
//subract two from c to get correct index number of match
for(--c; c-1; c--)
b |= strcmp(v[1], v[c]) ? 0 : P b ? ",%i" : "%i", c-2);
P"]");
return 0;
}
```
] |
[Question]
[
For a given positive integer, try to find out the smallest possible rotation resulted by rotating it 0 or more bits.
For example, when the given number is 177, whose binary representation is \$10110001\_{(2)}\$:
* \$ 10110001\_{(2)}=177 \$
* \$ 01100011\_{(2)}=99 \$
* \$ 11000110\_{(2)}=198 \$
* \$ 10001101\_{(2)}=141 \$
* \$ 00011011\_{(2)}=27 \$
* \$ 00110110\_{(2)}=54 \$
* \$ 01101100\_{(2)}=108 \$
* \$ 11011000\_{(2)}=216 \$
27 is the smallest rotating result. So we output 27 for 177.
## Input / Output
You may choose one of the following behaviors:
* Input a positive integer \$n\$. Output its smallest bit rotation as defined above.
* Input a positive integer \$n\$. Output smallest bit rotation for numbers \$1\dots n\$.
* Input nothing, output this infinity sequence.
Due to definition of this sequence. You are not allowed to consider it as 0-indexed, and output smallest bit rotate for \$n-1\$, \$n+1\$ if you choose the first option. However, if you choose the second or the third option, you may optionally include 0 to this sequence, and smallest bit rotation for \$0\$ is defined as \$0\$. In all other cases, handling \$0\$ as an input is not a required behavior.
## Test cases
So, here are smallest bit rotate for numbers \$1\dots 100\$:
```
1 1 3 1 3 3 7 1 3 5
7 3 7 7 15 1 3 5 7 5
11 11 15 3 7 11 15 7 15 15
31 1 3 5 7 9 11 13 15 5
13 21 23 11 27 23 31 3 7 11
15 13 23 27 31 7 15 23 31 15
31 31 63 1 3 5 7 9 11 13
15 9 19 21 23 19 27 29 31 5
13 21 29 21 43 43 47 11 27 43
55 23 55 47 63 3 7 11 15 19
```
## Notes
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") as usual.
* This is [A163381](https://oeis.org/A163381).
* The largest bit rotation is [A163380](https://oeis.org/A163380). [A233569](https://oeis.org/A233569) is similar but different. (The first different item is the 37th).
[Answer]
# x86-64 machine code, ~~18~~ 16 bytes
```
0F BD D7 0F 43 C7 0F B3 D7 D1 D7 39 F8 75 F4 C3
```
[Try it online!](https://tio.run/##XVCxTsMwEJ3trziCKtlNWrUUMbRNF2YWJiRgcBwnMXKcykmLo6q/Tji3BRWWO917z/feWU5KKYfhVltpdrmCddvluplWG/oHMjr7jzlty4BRbTsoWKiCr6hoa2DwHDE6LU2TCQMFLZYkax2o3CdYNHVLIutmbyUocYFI1gWBDpOnxElznuYUpdsr3YdV4FCgOsojQMOTfy20PUdwpUxAVsLBeIzDntMDJYHxkMIsgT60FSWflTYKWBx7WKewmHNKyBZv6goWjTRMNjDSbzZKAI0L5jk6/fJv9knISmMS2eRqGQXOX/bmDRx@dDCa3b3gij5lbGdbXVqVn7KNecFffRy/89URLkl6uMEN/nFx7QQMs2R9p1p@DhNIvH3nbHA70mH4koURZTtM6od7LPj/Kb5V5hs "C (gcc) – Try It Online")
Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes \$n\$ in EDI and returns its smallest bit rotation in EAX.
In assembly:
```
f: bsr edx, edi # Set EDX to the highest position of a 1 bit in n.
r: cmovnc eax, edi # (EAX will hold the lowest rotation found so far.)
# Set EAX to EDI if CF=0. The first iteration, CF=0 always:
# the value of CF after BSR is officially undefined, but it is
# consistently 0 (as this code needs) on at least some CPUs.
# (To not rely on this, add CLC before this for +1 byte.)
# On later iterations, CF=1 if EDI ≤ EAX (from the cmp).
btr edi, edx # Set the bit at position EDX in EDI to 0.
# Set CF to the previous value of that bit.
rcl edi, 1 # Rotate EDI and CF together left by 1,
# putting the removed bit back in at the end.
cmp eax, edi # Compare EAX and EDI.
jne r # Jump back if they are not equal.
# (Once a value repeats, all possible values have been seen.)
ret # Return.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
bā._Cß
```
Input \$n\$; outputs the smallest bit rotation.
[Try it online](https://tio.run/##yy9OTMpM/f8/6UijXrzz4fn//xuamwMA) or [verify all test cases](https://tio.run/##yy9OTMpM/X@xydXPXknhUdskBSV7v/9JRxr14p0Pz/@v89/Q3BwA).
Both the \$[1,n]\$ list with an input \$n\$ and infinite list would be 2 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) longer with a leading `Lε` or `∞ε` respectively.
[Try the infinite version online.](https://tio.run/##yy9OTMpM/f//Uce8c1uTjjTqxTsfnv//PwA)
**Explanation:**
```
b # Convert the (implicit) input-integer to a binary-string
ā # Push a list in the range [1,length] (without popping the string)
._ # Map each integer v in the list to a v-times (left-)rotated version of the
# binary-string
C # Convert each binary-string in the list back to an integer
ß # Pop and leave the minimum
# (which is output implicitly as result)
```
[Answer]
# Excel, ~~81~~ ~~80~~ ~~71~~ 68 bytes
`=LET(a,DEC2BIN(n),b,LEN(a),c,SEQUENCE(b),MIN(BIN2DEC(MID(a&a,c,b))))`
Input ***n***
*With many thanks to @KevinCruijssen for the great suggestions and 11-byte improvement!*
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 73 bytes
It's not pretty, and it doesn't work on TIO. But it works in the program itself.
```
x=de2bi(k=input(''));for i=1:k,[ans,bi2de(circshift(x',i)')];end,min(ans)
```
[Try it online!](https://tio.run/##Dco7DoAgDADQq7jRJiwySjiJceAbGyIYQMPtq29@1Q/7RuZpQlSOIBsq9zNACESdalvIrFuWuy1dOlIhgqfm@0lpwBSSUOChYwnyogJ/QuYP "Octave – Try It Online")
```
x=de2bi(k=input(''));for i=1:k,[ans,bi2de(circshift(x',i)')];end,min(ans)
k=input('') % Take input, k = 177
x=de2bi(k=input('')); % Convert input to binary, k = [1 0 0 0 1 1 0 1],
% x = 177
for i=1:k,[...];end % Do k times (177 times)
% Shortest way to make something happen enough times
circshift(x',i)') % Transpose x to make a vertical vector
% Shift it i times, and transpose it back
% Must be transposed for circshift to work
bi2de(circshift(x',i)') % Convert to decimal
[ans,bi2de(...)] % Concatenate into a long vector 'ans'
min(ans) % The minimum of this vector
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page)
```
BṙRḄṂ
```
[Try it online!](https://tio.run/##y0rNyan8/9/p4c6ZQQ93tDzc2fT//39Dc3MA "Jelly – Try It Online")
#### Explanation
```
BṙRḄṂ # Implicit input (n)
B # Convert n into binary
ṙ # Rotate this string this many times:
R # Each of the numbers in [1..n]
# (this will generate some duplicates, but that's fine)
Ḅ # Convert each one back from binary
Ṃ # Get the minimum of this list
# Implicit output
```
[Answer]
# [Python](https://www.python.org), 61 bytes
*-5 bytes thanks to `Shaggy` and -5 bytes thanks to `M Virts`.*
Takes a positive integer `n` as input. Outputs its smallest bit rotation in integer form.
```
lambda n:min(int((a:=f'{n:b}')[i:]+a[:i],2)for i in range(n))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3bXMSc5NSEhXyrHIz8zQy80o0NBKtbNPUq_OskmrVNaMzrWK1E6OtMmN1jDTT8osUMhUy8xSKEvPSUzXyNDUhhqwtKAJpTNMwNDeHiS1YAKEB)
[Answer]
# [J](http://jsoftware.com/), 16 bytes
```
[:<./2#.i.|."{#:
```
[Try it online!](https://tio.run/##y/r/P03B1koh2spGT99IWS9Tr0ZPqVrZ6n9qcka@gqEBCKkopCkZKNhZKWTqAbkGCv8B "J – Try It Online")
* `#:`: Convert \$n\$ to binary.
* `i.` `|.` `"` `{`: `i.` makes a list of the integers from 0 (inclusive) to \$n\$ (exclusive), then `|.` uses that to rotate the binary expansion of \$n\$, with its ranks being set (`"`) to the ranks of `{` so that it takes each integer as a separate rotation.
* `2` `#.`: Convert back from binary expansions to numbers.
* `[:` `<.` `/`: Take the minimum, using a 'cap' to do so monadically.
[Answer]
# [><> (Fish)](https://esolangs.org/wiki/Fish), 91 bytes
```
i0$1>:@$:@)?!v\
;n\^@+1$*2@ <r
$@:\?=@:$@:r-1/&~$?)@:&:
2+*2~v?:}:{%2:/.2b-%1:,
1$*2$/.38-
```
[Try it](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiaTAkMT46QCQ6QCk/IXZcXFxuIDtuXFxeQCsxJCoyQCA8clxuJEA6XFw/PUA6JEA6ci0xLyZ+JD8pQDomOlxuMisqMn52Pzp9OnslMjovLjJiLSUxOixcbjEkKjIkLy4zOC0iLCJpbnB1dCI6IjEwMCIsInN0YWNrIjoiIiwic3RhY2tfZm9ybWF0IjoibnVtYmVycyIsImlucHV0X2Zvcm1hdCI6Im51bWJlcnMifQ==)
Instead of counting how many iterations happened, which would be expensive, this exits if the current value equals the minimum value.
[](https://i.stack.imgur.com/WYrgF.png)
[Answer]
# [R](https://www.r-project.org), ~~62~~ 59 bytes
*Edit: -3 bytes thanks to pajonk*
```
\(n,j=2^(0:(i=log2(n))))min(j%*%array(n%/%j%%2,2:3+i)[-1,])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMG24tzEnJzU4pL4pMyS-KL8ksSSzPw826WlJWm6FjetYzTydLJsjeI0DKw0Mm1z8tONNPI0gSA3M08jS1VLNbGoKLFSI09VXzVLVdVIx8jKWDtTM1rXUCdWE2qEcnFiQUFOpYahlaGBgQ5W26BKFyyA0AA)
Instead of iteratively rotating bits, we use them to fill a 2D array with one-too-many rows, with recycling, so that each column ends-up with the bits rotated (plus an extra useless row).
We can then use matrix multiplication (`%*%` in R) with a vector of powers-of-2 to easily calculate the values encoded by each column, and output the minimum one.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 63 bytes
```
x=>'0b'+[...y=x.toString(2)].map(t=>y=y.slice(1)+t).sort()[0]-0
```
[Try it online!](https://tio.run/##DclBDsIgEADAux8pG9INNtEL0k/02PSACM0aZBsgprweneu87dcWl@moY@KX78H008yDeg5yRcRmTqy81ExpFxNs@LGHqGZupmGJ5Ly4gqyAhXMVsKptVF1fAmdBZJQmeky3u5aSCBynwtFj5F2EfwP0Hw "JavaScript (Node.js) – Try It Online")
`t` keeps being the needed digit
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 9 bytes
Anonymous tacit prefix function.
```
⌊/⍳⊥⍤⌽¨⊤¨
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1FPl/6j3s2PupY@6l3yqGfvoRWPupYcWvE/7VHbhEe9fY@6mh/1rnnUu@XQeuNHbRMf9U0NDnIGkiEensH/0w6tMDRQMDQASgONMDQwAAA "APL (Dyalog Extended) – Try It Online")
`⌊/` the smallest (lit. minimum-reduction) of
`⍳`…`¨⊤¨` for each integer in the range 1 through \$n\$, combined with the binary representation of \$n\$:
…`⍤⌽` rotate that representation that integer steps left, and then:
`⊥` convert back to a regular number
[Answer]
# [R](https://www.r-project.org), ~~80~~ ~~78~~ ~~75~~ 71 bytes
```
f=\(n,b=2^(0:log2(n)),x=n%/%b%%2)if(n)min(x%*%b,f(n-1,b,c(x[-1],x[1])))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGCpaUlaboWN93TbGM08nSSbI3iNAyscvLTjTTyNDV1KmzzVPVVk1RVjTQz04AiuZl5GhWqWqpJOkCerqFOkk6yRkW0rmGsTkW0YaympibUOP00DUNNLiBhDCbNzTW5chNLijIrNIoTCwpyKjUMrQwNDHTSNHUMDXR0QqDaYK4BAA)
Recursive function that in every iteration rotates the binary representation by one place and keeps track of the minimum value.
[Answer]
# [Fig](https://github.com/Seggan/Fig), \$18\log\_{256}(96)\approx\$ 14.816 bytes
```
[KeBtLbxGWbxO'J]xq
```
[Try it online!](https://fig.fly.dev/#WyJbS2VCdExieEdXYnhPJ0pdeHEiLCIxNzciXQ==)
Fig is missing a few important builtins, so this is longer than expected.
```
[KeBtLbxGWbxO'J]xq
bx # Get the binary form of this number
GW # Generate an infinite list from the binary
O' # Using the function...
J]xq # Rotate by prepending the last element to the tailless list
Lbx # Length of the binary representation
t # Take that many items from the infinite list
eB # Convert each from binary
K # Sort ascending
[ # Take the first element (i.e. the minimum one)
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~73~~ 61 bytes
```
s;l;r;f(n){for(l=r=log2(s=n);r--;s=s<n?s:n)n=n%2<<l|n/2;r=s;}
```
[Try it online!](https://tio.run/##jVJdb4MgFH3vr7hp0gRbTafMNg7ZHpb9irUPDcXOzGIDLjPr/OtzgGht1oeRHOCee@4H4bLgwFjbKlIQSTIkvHNWSlRQSYvyECFFhUdkEBBFVSqe1IPwBBWzKE2Lb7GMiKSKNG0uKjjucoE8OE9AL0Pw@sRZxfevW6BwDn0AAzw6DdYjO/at2dMaYXzttrw@w9AhvugH28UZ4PBGfOK02Onj7h5pLsKdL1p3dxz@zW@1uNNYv6vX6/u6Biv8j/rGTkb1E1c/cfnH/TndPXZYX/o1duz6MKfxrfCN/pOG2E9ipVAVsLednOuds3cuu7@abuqXaFMnzxrx1IexjacuWo8JIPPPudjzWofdEXdNQeVfvMxQPwEeLHtqPnAEFgur72emn5tK5@oSLSAkVy6lXRmqvGuWa3YYNhu5vQhOUksyNJ3tIXgEvc/URug3VT4of3i2opRvXdrG7pJXH1LoR02a9odlxe6g2uCzDYrjLw "C (gcc) – Try It Online")
*Saved a whopping 12 bytes thanks to [c--](https://codegolf.stackexchange.com/users/112488/c)!!!*
[Answer]
# [Python](https://www.python.org), 57 bytes
```
lambda n:int(min(h:=f"{n:b}",*[h:=h[1:]+k for k in h]),2)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3LXMSc5NSEhXyrDLzSjRyM_M0Mqxs05Sq86ySapV0tKKBvIxoQ6tY7WyFtPwihWyFzDyFjFhNHSNNqAEGIOFMkHBRYl56qoahjqGBgaZVQRHIvEydNI1MTZ3UvBRbJQUFXV0FBSWovgULIDQA)
### Old [Python](https://www.python.org), 58 bytes
```
lambda n:int(min([h:=f"{n:b}"]+[h:=h[1:]+k for k in h]),2)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3rXISc5NSEhXyrDLzSjRyM_M0ojOsbNOUqvOskmqVYrVBvIxoQ6tY7WyFtPwihWyFzDyFjFhNHSNNqAkGIOFMkHBRYl56qoahjqGBgaZVQRHIwEydNI1MTZ3UvBRbJQUFXV0FBSWovgULIDQA)
[Answer]
# [C (gcc)](https://gcc.gnu.org/) with `-lgmp`, ~~233~~ ~~231~~ 227 bytes
* -6 thanks to ceilingcat
As it uses the GMP library, the maximum integer that this function handles is quite large. Takes a number as a string to avoid overflowing native types.
```
#import<gmp.h>
f(s,v,w,x,y)char*s,*v;{mpz_t c,l;mpz_init_set_str(c,s,10);mpz_init(l);for(y=x=strlen(v=mpz_get_str(0,2,c));y--;mpz_cmp(c,l)>0?mpz_set(c,l):0)w=v[x-1],bcopy(v,v+1,x-1),*v=w,mpz_set_str(l,v,2);gmp_printf("%Zd",c);}
```
[Try it online!](https://tio.run/##ZU9bbsIwEPznFFYqJBs2VZwHJDWm9yhCiBoSLCUkilNDirh603WK@KlkW7ue2dkZ5RdKDcOLrpq67VZF1bye1pOcGrBwgSv0TJ327czAzIpb1XzvOqKgFK7SZ93tzBFv11IFBnjAngAtmcjrlvbyKhEvj2dqpQOLx0AAISjGRO/745CqGhQp2Tp4dy3qju1bwC7Sbq4@38KnqpueWrBzDvjB0JO8wIM9ipboOmQCU@yaVp@7nHrTj4OHi8R9wJ5Ue41Gan1g5DYhxGUjMyO9iMc8ycJFEiVptsyiMErjRbiIoyiNwmWWBGGaxh4Qu@HBVuCkE9NigpVLqWUgiF7xgAvSfHWGeh7720CIeTixQLwpeiF6PmdihJ4eDZFr4uTxMEGQPDLuTv8fyYwMfCf34Ufl5b4wg19i5l8 "C (gcc) – Try It Online")
Ungolfed:
```
#import<gmp.h>
f(s, // input value
v, // bit representation of value
w, // rotated bit
x,y // bit string length and loop counter
)char*s,*v; {
mpz_t c,l; // current lowest value, test value
mpz_init_set_str(c,s,10); // initialize variables
mpz_init(l);
for(
y=x=strlen(v=mpz_get_str(0,2,c)); // initialize bit string
y--;
mpz_cmp(c,l)>0?mpz_set(c,l):0) { // adjust lowest value
w=v[x-1]; // get rotated bit
bcopy(v,v+1,x-1); // rotate
*v=w; // put rotated bit at top
mpz_set_str(l,v,2); // get test value
}
gmp_printf("%Zd",c);
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), 76 bytes
```
i,o=bin(input())[2:],[]
for x in i:i=i[-1]+i[:-1];o+=[int(i,2)]
print min(o)
```
[Try it online!](https://tio.run/##DcwxDoAgEAXRnlNQQsACGhIMJ9nQWBh/4S4hmOjpkWpeNe0bl3CcE17KATbg9gxjLcVcPVV1StevBmtkFNAWqgPllV1cIfAw8NFW1fqyvtdB7JwhpR8 "Python 2 – Try It Online")
Python2 because it accepts integers directly as input (no int() required) and it saves a space on the print statement by not needing brackets.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 55 bytes
```
.+
$*
+r`\1(1+)
0$1
10
1
.
$&$'$`¶
1
10
+`01
110
O`
\G1
```
[Try it online!](https://tio.run/##K0otycxL/P9fT5tLRYtLuyghxlDDUFuTy0DFkMvQgMuQS49LRU1FXSXh0DYusIh2ggGQBjL8E7hi3A3//zc0NwcA "Retina 0.8.2 – Try It Online") Explanation:
```
.+
$*
```
Convert to unary.
```
+r`\1(1+)
0$1
10
1
```
Convert to mirrored binary i.e. LSB first, MSB last.
```
.
$&$'$`¶
```
Generate all of the rotations.
```
1
10
+`01
110
```
Convert each rotation back to unary.
```
O`
```
Sort.
```
\G1
```
Convert the shortest to decimal.
[Answer]
# [Factor](https://factorcode.org/), 43 bytes
```
[ >bin all-rotations [ bin> ] map infimum ]
```
[Try it online!](https://tio.run/##RYyxCsJADEB3vyIfYEu7KnQVFxdxKh3SktbAXe5MUtCvPysdHN978GacPGl53K@3ywki@rPOqEYKRq@VZCKr6e2KtkdFWcj@EbKS@ycri8Oiac0sC5wPh7ZpoG@P41B66EYWwBAqTY7OSQx62FwHw3bNwDJzXCMM5Udts4/AOOZAleMYqC5f "Factor – Try It Online")
```
>bin ! convert input from decimal to a binary string
all-rotations ! get every rotation as a sequence of strings
[ bin> ] map ! convert each to decimal from binary
infimum ! get the smallest one
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 16 bytes
```
&/2/'{1_x,*x}\2\
```
[Try it online!](https://ngn.codeberg.page/k#eJx9UX9rwjAQ/T+fIoMxdf6IlxhDm4+iMmvXarEa12ZQEffZl1xbmTACR7i89+5e2pfHb4yzwQ0+msl7c1/zNSE2vr2urj9VnFNKG701Rz3c5klR6kZfdTXa3Amp4iFQ6kr0pyvV95JQvLWYoiAfDCKeB8CSnarrUQueF/A8E6FEoArnBeVAufAwV74R8NjleYkS4UnP4OZW1e93tRT/urTz/hb1LhG6RLjrjz/yC4Glurcs/LxEN3c6eCmevhKikfvLgxWMX2A+1xNWbQhh5GDtpY4ZS81ntjdlPqttkh6zJj0k5302S82JfX1ntS3MuWZcKqE4q09JWTpsuivstDI28SwhNBxOMJpwMOFYwqGEIwkHEo4jHEYwil/tkZRF)
* `2\` convert (implicit) input to its binary representation
* `{1_x,*x}\` build a list of all rotations of the bits
* `2/'` convert each back to its decimal representation
* `&/` calculate, and (implicitly) return the minimum
[Answer]
# [Python 2.7](https://www.python.org/download/releases/2.7/), 73 bytes
```
x=bin(input())[2:]
print min([int(x[i:]+x[:i],2)for i in range(len(x))])
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `g`, ~~7~~ 6 bytes
```
ƛ?b$ǓB
```
[Try it online!](https://vyxal.pythonanywhere.com/#WyJnIiwiIiwixps/YiTHk0IiLCIiLCIxNzciXQ==)
* -1 thanks to a suggestion from Shaggy
#### Explanation
```
ƛ?b$ǓB # Implicit input
ƛ # Map over the range:
?b # Get the input in binary
$Ǔ # Rotate ^ ^^ times
B # Convert it back from binary
# g flag gets the minimum of this list
# Implicit output
```
Previous 7-byter:
```
b:ż¨VǓB # Implicit input
b # Convert the input to binary
:ż # Duplicate and push range(len(^))
¨V # Map over each element in ^:
Ǔ # Rotate ^^^ ^ places to the left
B # Convert each back from binary
# g flag gets the minimum of this list
# Implicit output
```
[Answer]
# JavaScript (ES6), 57 bytes
*-2 bytes thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)*
```
n=>(m=g=q=>x--?g(q%2<<Math.log2(n,m=m<q?m:q)|q/2):m)(x=n)
```
[Try it online!](https://tio.run/##NYzNbsJADITvfQpfKmyFLJDeyBqegBPHisMqJCEou5tNFoT46asHp1UP1oztb@ZsrmYo@qaLqfPHcqx4dLxByzUH3tzSdFtj@My0/tmZeFJFe//K0M0tWx22dh3oGRYZrS3hjR2Nle@xLSM4YFjmIhpWy1@TsDiCxwfABBgBvg@5bP8RK5dVLqInUkyS/OEARnWX4YQVSg1YUtHvY9@4Gkl15riPpo@YEU1tL5nCu8G3pWp9jUadfeNwBrPp/xrf "JavaScript (Node.js) – Try It Online")
### Commented
```
n => ( // n = input
m = // m = minimum value, initially non-numeric
g = // g is a recursive function taking
q => // the current rotation q
x-- ? // if x is not equal to 0 (decrement it afterwards):
g( // do a recursive call:
q % 2 << // using the number of bits in the original
Math.log2( // input, left-shift the LSB so that it takes
n, // the place of the MSB
m = m < q ? // update m to min(m, q)
m // (this always updates m to q if m is
: // still non-numeric)
q //
) | q / 2 // right-shift all other bits by 1 position
) // end of recursive call
: // else:
m // stop and return m
)(x = n) // initial call to g with q = x = n
```
[Answer]
# MATL, ~~13~~ 12 bytes
```
:"GB@YSXBvX<
```
*1 byte saved thanks to @lmendo*
Try it at [MATL Online](https://matl.io/?code=%3A%22GB%40YSXBvX%3C&inputs=177&version=22.7.4)!
**Explanation**
```
% Implicitly grab the input (N)
: % Create an array from [1...N]
" % For each value in the array
G % Grab the input as a number
B % Convert to an array of booleans representing the binary equivalent
@YS % Circularly shift by the loop index
XB % Convert the result from binary to decimal
v % Vertically concatenate the entire stack
X< % Compute the minimum value so far
% Implicitly display the result
```
[Answer]
# [Julia 1.0](http://julialang.org/), ~~84~~ 78 bytes
```
!x=(c=string(x,base=2);r=keys(c);min((r.|>i->parse(Int,"0b"*(c^2)[i.+r]))...))
```
[Try it online!](https://tio.run/##dZDRToQwEEXf@YqBmNiuSBhql8CmG33wwW9Y16TLNooCEooRE/8d2wIaHkxuJjd3bs40ff2oSonDOPqDIIXQfVc2z2QIT1IrkdBdJ97UlyYF3dVlQ0gXfe/L630rO63IQ9OHQXwKNqR4SuihjK66I6VRFFE6tobTk@B@kHVbqRwC6t3ql/dP8FP0vFZqrc4goJYt8UPMMY7pJQgBBwQwYss0ShfPrZ2CFJD/xTbhgOjE587sXdOI4bqfuQJzHW5NgpAwGyapNQxXHFtgdmVzx5w6E9loy/7nG58t/MzxM8f5veu2N8wpnd9gPHdXzDThlq3fkx29@Y8fm7uqgl7pXsP0sTlcTCag4w8 "Julia 1.0 – Try It Online")
* `c` is the bitstring of input `x`. Another method would be `lstrip(bitstring(x),'0')`.
* `r` contains the indices in `c` and is iterated over the repeated bitstring `c^2` to get each rotation.
* `min` treats a vector `V` as a single value, so the splat operator is used: `min(V...)`. Another method would be `minimum(V)`.
-6 bytes thanks to MarcMush:
* Replace range `1:length(c)` with iterator `keys(c)`
* [Use broadcasting](https://codegolf.stackexchange.com/a/219504/114865)
[Answer]
# Java 10, 118 bytes
```
n->{var b=n.toString(n,2);for(int l=b.length(),i=l,t;i-->0;n=t<n?t:n)t=n.parseInt((b+b).substring(i,i+l),2);return n;}
```
Input \$n\$; outputs the smallest bit rotation.
[Try it online.](https://tio.run/##bZA9b8MgEIb3/IqTJ5A/ZHeJFEI6d2iWjG0H7BD3UnK24GypivLbXRynnbogeE88PC9nM5r8fPyaGmdCgFeDdF0BILH1J9NY2M/HewCNeIlxaz2QVDG9reIS2DA2sAcCPVG@u47GQ62p4O7AHqkVlD1Jdeq8mBlO14Wz1PKnkBlql7HCPN@VijRv6Zk3JDle7o0PNr4mRJ3WsghDHRYYZpg6ORO95cETkLpNahbph9pFkYfP2OERLrGNWCzePoxcmhy@A9tL0Q1c9HHCjkRSrdebd05SKhoR9/JeD@BXGnWlcKurslSYpvI@@xeEafLHQfn4pNv0Aw)
**Explanation:**
```
n->{ // Method with Integer as both parameter and return-type
var b=n.toString(n,2); // Convert the input-integer to a binary-String
for(int l=b.length(), // Set `l` to the length of this binary-String
i=l,t;i-->0 // Loop `i` in the range (l,0]:
; // After every iteration:
n=t<n? // If `t` is smaller than `n`:
t:n) // Set `n` to this new minimum `t`
t= // Set `t` to:
n.parseInt( // The following binary converted to a base-10 integer:
(b+b) // Append the binary-String to itself
.substring(i,i+l) // And then get its substring in the range [i,i+l)
,2);
return n;} // Return the modified `n` holding the smallest result
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes
```
≔⍘N²θI⍘⌊Eθ⭆θ§θ⁺κμ²
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DKbE4NbikKDMvXcMzr6C0xK80Nym1SENTR8EIiAs1rbkCgJIlGs6JxSXIin0z8zJzS3M1fBMLNAp1FCCiUI5jiWdeSmoFiBmQU1qska2jkKsJAiBDNTWt//83NDf/r1uWAwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⍘N²θ
```
Convert the input to binary.
```
I⍘⌊Eθ⭆θ§θ⁺κμ²
```
Generate all of the rotations, take the minimum, and convert back to decimal.
[Answer]
# [Zsh](https://www.zsh.org/), 70 bytes
```
b=$[[##2]$1];for i ({1..$#b})m+=($[2#${b:$i}${b:0:$i}]);printf ${(n)m}
```
[Try it online!](https://tio.run/##FcbBCsAQHIDx@55C@R9oJVzU5EnkYk0csGynybNbLt/v@544A6F9egPWYiwdCKdDbSgh0gVjgP2geTcErMTQ/QFpLPgaR/XdUnkDgk4KzWNeZ6xj2wISSq1yPn8 "Zsh – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
ḋ▼U¡ṙ1ḋ
```
[Try it online!](https://tio.run/##yygtzv6f@6ip8eGOxYYGBv8f7uh@NG1P6KGFD3fONARy/v8HAA "Husk – Try It Online")
```
ḋ # convert to bits,
¡ # make infinite list by repeatedly
ṙ1 # rotating by one position,
U # get the longest unique prefix,
▼ # get the minimum of this,
ḋ # and get the value from the bits.
```
[Answer]
# [Desmos](https://desmos.com/calculator), 95 bytes
```
L=[floor(log_2N)...0]
B=mod(floor(N/2^L),2)
f(N)=[total(join(B[i+1...],B[1...i])2^L)fori=L].min
```
Even worse than the fish answer... at least it beats Java :P
[Try It On Desmos!](https://www.desmos.com/calculator/nswp1oanee)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/zapwwl0vnl)
] |
[Question]
[
Write the shortest code to reverse the bit order of a 32-bit integer.
**Rules:**
1. Input is assumed to be a valid integer or string equivalent if your language doesn't support numerical values (e.g. Windows Batch).
2. Output must be a valid integer or string equivalent if your language doesn't support numerical values (e.g. Windows Batch).
3. Standard library only.
4. It may be a function or a complete program.
5. Input may be either from `stdin` or as a function argument.
6. Output must be either `stdout` or as a returned value.
7. If your language has a built-in or standard library function that does this in one step (e.g. `rbit` in ARM assembly), that cannot be used.
**Examples:**
Key:
1. decimal
* binary
* (reverse)
* reversed binary
* decimal output
Examples:
1. `-90` (8-bit example for demonstration)
* `10100110b`
* (reverse)
* `01100101b`
* `101`
2. `486`
* `00000000000000000000000111100110b`
* (reverse)
* `01100111100000000000000000000000b`
* `1736441856`
3. `-984802906`
* `11000101010011010001100110100110b`
* (reverse)
* `01100101100110001011001010100011b`
* `1704506019`
Note: Omissions are free game. If I didn't say it, and it's not one of the [standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/14668), then it's completely allowed.
[Answer]
## MMIX assembly (28 Bytes)
### 64 bit numbers
```
rbit:
SETH $1,#0102 # load matrix in 16-byte steps
ORMH $1,#0408
ORML $1,#1020
ORL $1,#4080
MOR $0,$1,$0 # multiplication 1
MOR $0,$0,$1 # multiplication 2
POP 1,0 # return
```
This assembles to:
```
rbit:
E0010102 # SETH $1,#0102
E9010408 # ORMH $1,#0408
EA011020 # ORML $1,#1020
EB014080 # ORL $1,#4080
DC000100 # MOR $0,$1,$0
DC000001 # MOR $0,$0,$1
F8010000 # POP 1,0
```
### How does it work?
The `MOR` instruction performs a matrix multiplication on two 64-bit quantities used as two 8x8 matrices of booleans. A boolean number with digits *abcdefghklmnopqr2* is used as a matrix like this:
```
/ abcd \
| efgh |
| klmn |
\ opqr /
```
The `MOR` instruction multiplies the matrices represented by their arguments where multiplication is `and` and addition is `or`. It is:
```
/ 0001 \ / abcd \ / opqr \
| 0010 | \/ | efgh | -- | klmn |
| 0100 | /\ | klmn | -- | efgh |
\ 1000 / \ opqr / \ abcd /
```
and furthermore:
```
/ opqr \ / 0001 \ / rqpo \
| klmn | \/ | 0010 | -- | nmlk |
| efgh | /\ | 0100 | -- | hgfe |
\ abcd / \ 1000 / \ dcba /
```
which is the reverse order of bits of the original number.
### 32 bit numbers
If you just want the reverse of a 32 bit number instead of a 64 bit number, you can use this modified method:
```
rbit:
SETL $1,#0408 # load first matrix in two steps
ORML $1,#0102
MOR $1,$1,$0 # apply first matrix
SLU $2,$1,32 # compile second matrix
16ADDU $1,$2,$1
MOR $1,$0,$1 # apply second matrix
POP 1,0 # return
```
assembled:
```
rbit:
E3010408 # SETL $1,#0408
EA010102 # ORML $1,#0102
DC010001 # MOR $1,$1,$0
3B020120 # SLU $2,$1,32
2E010201 # 16ADDU $1,$2,$1
DC010001 # MOR $1,$0,$1
F8010000 # POP 1,0
```
The first matrix multiplication basically works like this:
```
/ 0000 \ / 0000 \ / 0000 \
| 0000 | \/ | 0000 | -- | 0000 |
| 0001 | /\ | abcd | -- | efgh |
\ 0010 / \ efgh / \ abcd /
```
the corresponding octabyte is `#0000000001020408` which we load in the first two instructions. The second multiplication looks like this:
```
/ 0000 \ / 0001 \ / 0000 \
| 0000 | \/ | 0010 | -- | 0000 |
| efgh | /\ | 0100 | -- | hgfe |
\ abcd / \ 1000 / \ dcba /
```
The corresponding octabyte is `#0102040810204080` which we create from the first matrix like this:
```
SLU $2,$1,#32 # $2 = #0102040800000000
16ADDU $1,$2,$1 # $2 = $2 + $1 << 4
= $2 + #0000000010204080
# = #0102040810204080
```
The second multiplication is business as usual, the resulting code has the same length (28 bytes).
[Answer]
## 80386 assembly (~~13~~ 12 bytes)
As a function in AT&T syntax using the cdecl calling convention.
```
# reverse bits of a 32 bit word
.text
.globl rbit
.type rbit,@function
rbit:
push $32 # prepare loop counter
pop %ecx
0: shrl 4(%esp) # shift lsb of argument into carry flag
adc %eax,%eax # shift carry flag into lsb
loop 0b # decrement %ecx and jump until ecx = 0
ret # return
```
This function assembles to the following byte sequence:
```
6a 20 59 d1 6c 24 04 11 c0 e2 f8 c3
```
Broken down into instructions:
```
6a 20 push $32
59 pop %ecx
d1 6c 24 04 shrl 0x4(%esp)
11 c0 adc %eax,%eax
e2 f8 loop .-6
c3 ret
```
It works like this: In each of the 32 iterations of the loop, the argument, which is located at `4(%esp)`, is right shifted by one position. The last bit is implicitly shifted into the carry flag. The `adc` instruction adds two values and adds the value of the carry flag to the result. If you add a value to itself, i.e. `%eax`, you effectively left-shift it by one position. This makes `adc %eax,%eax` a convenient way to left shift `%eax` by one position while shifting the content of the carry flag into the low-order bit.
I repeat this process 32 times so that the entire content of `4(%esp)` is dumped into `%eax`. I never explicitly initialize `%eax` as its previous contents are shifted out during the loop.
[Answer]
## C, ~~63~~ ~~52~~ 48
**Original version:**
```
int r(int n){int r=0,i=32;for(;i--;r=r<<1|n&1,n>>=1);return r;}
```
---
**Updated version** (with changes suggeted by *Allbeert*, *es1024*, and *Dennis*):
```
r(n){int r,i=32;for(;i--;r=r*2|n&1,n>>=1);return r;}
```
Note: Since the second version omits setting `r=0`, the code is assuming that an `int` is 32 bits. If this assumption is false, the function will most likely produce an incorrect result, depending on the initial state of `r` on entry to the function.
---
**Final version** (with further changes suggested by *Dennis* and *Alchymist*):
```
r(n,r,i){for(;32-i++;r=r*2|n&1,n>>=1);return r;}
```
Note: This puts the declaration of the work variables `r` and `i` into the parameter list. Parameters are as follows: `n` is the number to be bit-reversed. `r` and `i` are work variables that must be passed as 0.
[Answer]
## x86 assemply, 10 Bytes
```
f9 stc
d1 d8 1: rcr %eax
74 05 je 2f
d1 d2 rcl %edx
f8 clc
eb f7 jmp 1b
2:
```
This assume input in eax, output in edx. (Also, on output eax is zero and CF and ZF are set, if anyone cares).
Instead of a counter, an additional 1 is pushed in in the beginning as end-of data marker
[Answer]
## Julia 0.2, 33 bytes
```
f(n)=parseint(reverse(bits(n)),2)
```
Does what it looks like.
`bits` gives you the bit representation (respecting two's complement). `parseint` doesn't care about two's complement, but returns a 32 bit integer, so the two's complement is simply handled by overflow.
According to the changelogs, overflow detection was added to `parseint` in Julia 0.3, so this might not work any more.
[Answer]
# Python 2, 50
```
print int("{:032b}".format(input()%2**32)[::-1],2)
```
Broadly the same as my Pyth solution. Take the input mod 2\*\*32, convert to 32-bit padded binary, reverse, convert binary sting back to decimal and print.
[Answer]
# CJam, 15 bytes
```
li4H#+2bW%32<2b
```
[Try it online.](http://cjam.aditsu.net/ "CJam interprter")
"Free game" joker used: The output will always be an *unsigned* integer.
### Test cases
```
$ cjam reverse32.cjam <<< 486; echo
1736441856
$ cjam reverse32.cjam <<< -984802906; echo
1704506019
```
### How it works
```
li " Read from STDIN and cast to integer. ";
4H#+ " Add 4 ** 17 to avoid special cases. ";
2b " Convert into array of digits in base 2. ";
W% " Reverse the order. ";
32< " Discard the 33th and all following digits. ";
2b " Convert the array of digits into an integer. ";
```
[Answer]
# JavaScript (E6) 37 ~~39 40 50~~
Function, number input and returning reversed number. ~~Most basic algorithm, probably can be golfed more with some smart trick.~~
**Edit** Recursion instead of loop
**Edit 2** Following @bebe suggestion `k*2` instead of `k<<1`
**Edit 3** Something I had missed at all: it's a full 32 bit loop, no need to initialize k. Thanks @FUZxxl
```
R=(v,b=32,k)=>b?R(v>>1,b-1,k*2|v&1):k
```
*It was*
```
R=v=>{for(k=b=0;b++<32;)k+=k+(v&1),v>>=1;return k}
```
**Test** In FireFox console, test using numbers in OP and some more random 16 and 32 bit numbers
```
Bin=x=>('0'.repeat(32)+(x<0?-x-1:x).toString(2)).slice(-32).replace(/./g,d=>x>0?d:1-d),
Dec=x=>(' '.repeat(11)+x).slice(-11),
R16=_=>Math.random()*65536|0,
R32=_=>(Math.random()*65536<<16)|R16(),
[-90,486,-984802906,R16(),R16(),R16(),R32(),R32(),R32(),R32()]
.forEach(n=> console.log(Dec(n)+' '+Bin(n)+' '+Dec(R(n))+' '+Bin(R(n))))
```
**Example of test output**
```
-90 11111111111111111111111110100110 1711276031 01100101111111111111111111111111
486 00000000000000000000000111100110 1736441856 01100111100000000000000000000000
-984802906 11000101010011010001100110100110 1704506019 01100101100110001011001010100011
45877 00000000000000001011001100110101 -1395851264 10101100110011010000000000000000
39710 00000000000000001001101100011110 2027487232 01111000110110010000000000000000
56875 00000000000000001101111000101011 -730136576 11010100011110110000000000000000
-1617287331 10011111100110100010011101011101 -1159439879 10111010111001000101100111111001
-1046352169 11000001101000011110111011010111 -344488573 11101011011101111000010110000011
1405005770 01010011101111101010111111001010 1408597450 01010011111101010111110111001010
-35860252 11111101110111001101000011100100 655047615 00100111000010110011101110111111
```
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 10 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
```
2⊥⌽⎕⊤⍨32/2
```
`2⊥` from-base-2 of
`⌽` the reversed
`⎕` numeric input
`⊤⍨` in the number system consisting of
`32/2` 32 bits
[TryAPL online!](http://tryapl.org/?a=%u2206%u2190486%20%u22C4%202%u22A5%u233D%u2206%u22A4%u236832/2%20%u22C4%20%u2206%u2190-984802906%20%u22C4%202%u22A5%u233D%u2206%u22A4%u236832/2&run)
[Answer]
# J (~~17~~ ~~15~~ 13 bytes)
```
_32#.@|.@{.#:
```
Here is an explicit definition to explain what it does:
```
3 : '#. |. _32 {. #: y'
```
1. `#: y` represents `y` as a base 2 number using as many places as necessary.
2. `x {. y` takes `|x` (magnitude of `x`) items from `y`, from the front if `x` is positive, from the back if `x` is negative. If we take more items than present, the result is padded with zeroes. `_32 {. #: y` effectively pads `#: y` to 32 bits.
3. `|. y` flips `y`, i. reverses the order of items in `y`.
4. `#. y` interprets `y` as a base-2 number.
[Answer]
## Python - 89
```
def r(n):
if n<0:n=~n^0xFFFFFFFF
print int(['','-'][n%2]+'{:032b}'.format(n)[::-1],2)
```
Python represents negative binary numbers as simply `-0b{positive_number}`. So to deal with this, complement negative numbers and then XOR with all 1's.
After that, create the string representation of the integer based on the format `{:032b}` which provides the 32bit representation of the number. Finally, reverse the string and turn it back into an integer.
**EDIT**
Thanks to [@Martin Büttner](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner) for pointing out a two's complement issue. If `n` ends in a 1 then by two's complement the reversed version would be negative.
Luckily, as explained above, Python likes negative binary numbers in a pretty simple way. Also luckily, Python's `int` function [allows optional sign characters](https://docs.python.org/2/library/functions.html#int) in its first argument.
So now, add a minus sign if `n` is odd to satisfy two's complement.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 33 32 22
```
v_%"%032db0"vsc%Q^2 32
```
Explanation:
```
Q Evaluated input.
%Q^2 32 Q mod 2^32. Same 32 bit binary representation as Q.
vsc%Q^2 32 Convert to binary string, then that to decimal int.
%"%032db0"vsc%Q^2 32 Pad above number to 32 bits, and append b0.
_%"%032db0"vsc%Q^2 32 Reverse it.
v_%"%032db0"vsc%Q^2 32 Eval and print. Due to leading "0b", eval as binary.
```
Golfs:
33 -> 32: Moved add to before reversing to save an end-quote.
32 -> 22: Used Q mod 2^32 instead of complicated machinery. Combined both strings into one.
Test cases:
```
$ cat rev_bits
v_%"%032db0"vsc%Q^2 32
$ ./pyth.py rev_bits <<< -984802906
1704506019
$ ./pyth.py rev_bits <<< 486
1736441856
$ ./pyth.py rev_bits <<< 0
0
```
[Answer]
# GNU dc, 27 bytes
```
0?[2~rssr2*+dlsz34>m]dsmx+p
```
### Output:
```
$ dc revbits.dc <<< 15
4026531840
$ dc revbits.dc <<< 255
4278190080
$ dc revbits.dc <<< 65535
4294901760
$ dc revbits.dc <<< 4294901760
65535
$ dc revbits.dc <<< 4278190080
255
$ dc revbits.dc <<< 4026531840
15
$
```
---
# Bash+coreutils, 45 bytes
```
n=`dc -e2do32^n$1p`
dc -e2i`rev<<<${n: -32}`p
```
### Output:
```
$ ./revbits.sh 15
4026531840
$ ./revbits.sh 255
4278190080
$ ./revbits.sh 65535
4294901760
$ ./revbits.sh 4294901760
65535
$ ./revbits.sh 4278190080
255
$ ./revbits.sh 4026531840
15
$
```
---
# C function, 89 bytes
Same idea as <https://codegolf.stackexchange.com/a/36289/11259> - using the [Stanford bit twiddling hacks](https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel). Not going to win the golfing, but interesting nonetheless:
```
// 89 byte function:
i;r(v){for(i=1;i<32;i*=2)v=v>>i&(1L<<32)/((1<<i)+1)|(v&(1L<<32)/((1<<i)+1))<<i;return v;}
// Test program:
#include <stdio.h>
int main (int argc, char **argv)
{
printf("r(0x0000000f) = 0x%08x\n", r(0x0000000f));
printf("r(0x000000ff) = 0x%08x\n", r(0x000000ff));
printf("r(0x0000ffff) = 0x%08x\n", r(0x0000ffff));
printf("r(0xffffffff) = 0x%08x\n", r(0xffffffff));
printf("r(0x0f0f0f0f) = 0x%08x\n", r(0x0f0f0f0f));
printf("r(0xf0f0f0f0) = 0x%08x\n", r(0xf0f0f0f0));
}
```
### Output:
```
$ ./revbits
r(0x0000000f) = 0xf0000000
r(0x000000ff) = 0xff000000
r(0x0000ffff) = 0xffff0000
r(0xffffffff) = 0xffffffff
r(0x0f0f0f0f) = 0xf0f0f0f0
r(0xf0f0f0f0) = 0x0f0f0f0f
$
```
[Answer]
## Java function, 64 chars.
```
int r(int n){int r=0,i=32;for(;i-->0;n>>=1)r=r<<1|n&1;return r;}
```
Should also work in C.
[Answer]
# PHP, 46 Bytes
[Online Versions](http://sandbox.onlinephpfunctions.com/code/889f775cac73041fdfb5967887e45659f3b384c7)
```
for(;$i<32;)$t.=$argn>>$i++&1;echo bindec($t);
```
or
```
<?=bindec(strrev(sprintf("%064b",$argn<<32)));
```
[Answer]
x86 assembly, 9 bytes
```
xor eax, eax
inc eax
myloop:
shr ecx, 1
adc eax, eax
jnc short myloop
```
In byte form: `33 C0 40 D1 E9 13 C0 73 FA`, 9 bytes.
[Answer]
# JS 115
Well that doesn't look good at all :D
```
n=+prompt();alert(eval('0b'+(Array(33).join(0)+(n<0?n>>>0:n).toString(2)).slice(-32).split('').reverse().join('')))
```
@Florian F's method in JS is 53 bytes long:
```
for(n=+prompt(r=0),i=32;i--;n>>=1)r=r<<1|n&1;alert(r)
```
[Answer]
# C# ~~81~~ 74
```
int R(int V){int l,r=l=0,i=1;for(;i>0;i*=2)r|=i*(1&V>>(31-l++));return r;}
```
Bit operations which most likely can be done shorter in all programming languages.
Basically, loop through all powers of 2 up to integer maximum+1(Which turns into a power of two) and since (2,147,483,647+1)=0 I can loop to 0. Bit shift Left to right to move the bit into the first position. Last bit at place 32 goes 31 steps to the right, second last goes 30 etc. So by using AND operator with 1 i will know if it is 1 or 0. If it is 1 I will add the current i value to the result and return it.
```
int R(int V)
{
int l,r=l=0,i=1;
for(;i>0;i*=2)
r|=i*(1&(V>>(31-l++)));
return r;
}
```
[Answer]
## C# 142
```
using System;using System.Linq;int f(int n){return Convert.ToInt32(new string(Convert.ToString(n,2).PadLeft(32,'0').Reverse().ToArray()),2);}
```
Expanded
```
int f(int n)
{
return Convert.ToInt32(
new string(
Convert.ToString(n, 2)
.PadLeft(32, '0')
.Reverse()
.ToArray()), 2);
}
```
[Answer]
# Python - 37
Similar to @isaacg's solution.
```
f=lambda n:int(bin(n%2**32)[:1:-1],2)
```
[Answer]
# C++, 160
This isn't the shortest one, however it uses only 24 operations.
Taken from Hacker's Delight book.
Golfed:
```
typedef unsigned U;U R(U&x){U a=-1u/3,b=-1u/5,c=-1u/17,d=65280;x=(x&a)*2|(x/2)&a;x=(x&b)*4|(x/4)&b;x=(x&c)<<4|(x>>4)&c;x=(x<<24)|((x&d)<<8)|((x>>8)&d)|(x>>24);}
```
Ungolfed:
```
unsigned R(unsigned x) {
x = (x & 0x55555555) << 1 | (x >> 1) & 0x55555555;
x = (x & 0x33333333) << 2 | (x >> 2) & 0x33333333;
x = (x & 0x0F0F0F0F) << 4 | (x >> 4) & 0x0F0F0F0F;
x = (x << 24) | ((x & 0xFF00) << 8) | ((x >> 8) & 0xFF00) | (x >> 24);
return x;
}
```
[Answer]
# Haskell, 145 - no bitwise operations
Bit-twiddling strikes me as the antithesis of Haskell, so I've avoided any use of bitwise operators. The resulting program is certainly not the shortest contestant, but I thought the use of math instead of bit-twiddling was interesting at least.
```
import Data.Tuple
import Data.List
f m=foldl1((+).(*2))$take 32$(unfoldr(\n->if n==0 then Nothing else Just$swap$divMod n 2)$mod m$2^32)++[0,0..]
```
### Explanation
```
f m=foldl1((+).(*2))$take 32$(unfoldr(\n->if n==0 then Nothing else Just$swap$divMod n 2)$mod m$2^32)++[0,0..]
|------5-------|---4----|--------------------------2---------------------------------|----1-----|---3----|
```
1. uses modulo to bring the result into 32-bit range
2. constructs a list of `0`s and `1`s, least significant bit first by repeatedly dividing by 2 and taking the remainder
3. concatenates an infinite list of `0`s to the end of this list
4. grabs the first 32 elements of the list (These last two were needed to ensure the list is actually 32 bits long.)
5. converts a list of `0` and `1` into an integer assuming the *most* significant bit is first (repeated double and add).
I'm not quite sure what constitutes "the standard library" in Haskell so I assumed Data.Tuple and Data.List were OK (they are pretty standard).
Also, the output is an *unsigned* 32-bit integer since changing that would cost me bytes: I'm arguing this under "omissions are free game".
[Answer]
# PHP, ~~46~~ 41 bytes
[try them online](http://sandbox.onlinephpfunctions.com/code/d9ddf7272f067307ec3303d5c7d6378265a5c311)
```
while($i<32)$r=$r*2|$argn>>$i++&1;echo$r;
```
bitwise ... more or less. Run as pipe with `php -nR '<code>'`.
**PHP, 46 bytes**
```
while($i<32)$r|=($argn>>$i&1)<<31-$i++;echo$r;
```
a pure bitwise solution; run as pipe with `-nR`.
**PHP, ~~47~~ 59 bytes**
```
<?=bindec(str_pad(strrev(substr(decbin($argn),-32)),32,0));
```
another built-in approach; save to file and run as pipe with `-F`.
[Answer]
# ARM Thumb machine code, 10 bytes
```
00000000: 01 20 49 08 40 41 fc d3 70 47 . [[email protected]](/cdn-cgi/l/email-protection)
```
As per request, this does not use the `rbit` instruction.
```
.syntax unified
.arch armv7-a
.thumb
.globl rbit
.thumb_func
// input: r1
// output: r0
rbit:
// sentinel bit
movs r0, #1
.Lloop:
// shift the lowest bit into the carry flag
lsrs r1, #1
// shift in with adc, put highest bit in carry flag
adcs r0, r0
// when the carry is set we flipped all 32 bits
bcc .Lloop
// return
bx lr
```
---
# ARM Thumb machine code (with builtins), 6 bytes
```
00000000: 90 fa a0 f0 70 47 ....pG
```
This is literally the `rbit` instruction that was explicitly disallowed but I am providing for reference
```
.syntax unified
.arch armv7-a
.thumb
.globl rbit_cheater
.thumb_func
// input: r0
// output: r0
rbit_cheater:
// Trivialize the challenge.
rbit r0, r0
// Return
bx lr
```
[Answer]
## Perl - 60
```
$_=unpack"N",pack"B*",scalar reverse unpack"B32",pack"N",$_
```
+1 for the p flag (let me know if I'm counting this wrong).
Run with:
```
echo 486 | perl -pe'$_=unpack"N",pack"B32",scalar reverse unpack"B32",pack"N",$_'
```
[Answer]
## C++ 69
```
int r(int n){int e=0,i=0;for(;i<32;i++)e|=((n>>i)&1)<<31-i;return e;}
```
[Answer]
## R, 45
```
f=function(x)packBits(intToBits(x)[32:1],"i")
```
Examples:
```
f(486)
# [1] 1736441856
f(-984802906)
# [1] 1704506019
```
Always just shy of the Python answers. That damn function keyword.
[Answer]
# Ruby, ~~43~~ 41 bytes
`def r(n)(0..31).inject(0){|a,b|a*2+n[b]}end`
In Ruby, using the bracket index notation (foo[i]) returns the bit at the nth place.
### --Edit--
Refactoring the `inject` functionality shaves a couple bytes
`def r(n)z=0;32.times{|i|z=z*2+n[i]};z;end`
[Answer]
# Perl5: 46
```
sub r{for(0..31){$a=$a*2|$_[0]&1;$_[0]>>=1}$a}
```
Nothing fancy. It shifts output left, copy lsb before shifting source right.
[Answer]
## Clojure, ~~202~~ ~~156~~ 142
```
#(read-string (let [s (clojure.pprint/cl-format nil "~2r" %)](apply str (reverse (apply str (concat (repeat (- 32 (count s)) "0") s "r2"))))))
```
] |
[Question]
[
[A recent SO question](https://stackoverflow.com/q/61348795/5306507) asks for *a convenient one-liner to generate a list of numbers and their negative counterparts in Python*.
Given two integers \$1≤a≤b\$, generate all the integers \$x\$ such that \$a≤|x|≤b\$. The result may be printed or returned in any order or structure, as putting the result into a list and sorting it, yields `[-b,1-b,2-b,…,-a,a,a+1,a+2,…,b]`
### Examples
\$a=6,b=9\$ gives `[6,-6,7,-7,8,-8,9,-9]` or `[6,7,8,9,-9,-8,-7,-6]` or `[-8,7,-9,-7,9,8,-6,6]` or `[[6,-6],[7,-7],[8,-8],[9,-9]]` or `[[6,7,8,9],[-6,-7,-8,-9]]` etc.
\$a=6,b=6\$ gives `[6,-6]` or `[-6,6]` or `[[6,-6]]` or `[[6],[-6]]` etc.
[Answer]
# [Python 2](https://docs.python.org/2/), 33 bytes
```
def f(a,b):print-a,a;a<b<f(a+1,b)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFNI1EnSdOqoCgzr0Q3USfROtEmyQYoqG0IFP6fpmGmY6n5HwA "Python 2 – Try It Online")
A recursive function that prints in a two-column format. Based on [ideas from Surculose Sputum](https://codegolf.stackexchange.com/a/203803/20260).
In Python 3, we'd need 2 more bytes for `print()` needing parens.
---
# [Python 2](https://docs.python.org/2/), 37 bytes
```
lambda a,b:range(a,b+1)+range(-b,1-a)
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFRJ8mqKDEvPVUDyNI21NSGcHSTdAx1EzX/FxRl5pUopGmY6VhqciE4Zpr/AQ "Python 2 – Try It Online")
Unfortunately for this challenge, Python's ranges are exclusive, so we have to add 1 to both upper endpoints.
[Answer]
# [Haskell](https://www.haskell.org/), 21 bytes
```
a%b=[a..b]++[-b.. -a]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P1E1yTY6UU8vKVZbO1o3SU9PQTcx9n9uYmaegq1CQVFmXomCioKZgqqC5f9/yWk5ienF/3WTCwoA "Haskell – Try It Online")
Looks like this boring solution is shortest. The space in before `-a` is needed to avoid a misparse with `..-`.
**22 bytes**
```
a%b=[id,(0-)]<*>[a..b]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P1E1yTY6M0VHw0BXM9ZGyy46UU8vKfZ/bmJmnoKtQkFRZl6JgoqCmYKqguX/f8lpOYnpxf91kwsKAA "Haskell – Try It Online")
**22 bytes**
```
a%b=[[x,-x]|x<-[a..b]]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P1E1yTY6ukJHtyK2psJGNzpRTy8pNvZ/bmJmnoKtQkFRZl6JgoqCmYKqguX/f8lpOYnpxf91kwsKAA "Haskell – Try It Online")
**23 bytes**
```
a%b=do x<-[a..b];[x,-x]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P1E1yTYlX6HCRjc6UU8vKdY6ukJHtyL2f25iZp6CrUJBUWZeiYKKgpmCqoLl/3/JaTmJ6cX/dZMLCgA "Haskell – Try It Online")
**23 bytes**
```
a%b=(,)<*>(0-)<$>[a..b]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P1E1yVZDR9NGy07DQFfTRsUuOlFPLyn2f25iZp6CrUJBUWZeiYKKgpmCqoLl/3/JaTmJ6cX/dZMLCgA "Haskell – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
ŸD(«
```
[Try it online!](https://tio.run/##yy9OTMpM/f//6A4XjUOr//8347IEAA "05AB1E – Try It Online")
# Explanation
```
Takes two input integers
Ÿ Inclusive range.
D Duplicate the stack.
( Negate all items of the duplicated item.
« Concatenate both lists.
Implicit output
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 5 bytes
```
_BM}F
```
[Try it online!](https://tio.run/##K6gsyfj/P97Jt9bt//9oUx1Dg1gA "Pyth – Try It Online")
`}F` forms an inclusive range, then `_B` pairs a number with its negation, and `M` maps that over the list.
[Answer]
# [PowerShell](https://github.com/PowerShell/PowerShell), 28 bytes
```
$args[0]..$args[1]|%{$_,-$_}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/XyWxKL042iBWTw/CMoytUa1WidfRVYmv/f//v9l/SwA)
`$args[0]..$args[1]` generates integer array range from `$args[0]` to `$args[1]`. It's piped and then each item in that array is mapped to itself and its negative counterpart.
[Answer]
## [Dyalog APL](https://www.dyalog.com), **19 bytes**
```
{(⊢,-)⍺,⍺(⊣+∘⍳-⍨)⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1Hf1EdtE8wUqjUedS3S0dV81LtLB4iBvMXajzpmPOrdrPuodwVQeGutguX//wA)
[Answer]
# [Python 3](https://docs.python.org/3/), ~~40~~ 39 bytes
*-1 byte thanks to @xnor!*
```
f=lambda a,b:b//a*[0]and[a,-a]+f(a+1,b)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRIVEnySpJXz9RK9ogNjEvJTpRRzcxVjtNI1HbUCdJ839BUWZeiUaahpmOpaYmF4Jnpqn5HwA "Python 3 – Try It Online")
This would be 38 bytes in Python2, by replacing `//` operator with just `/`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
rNƬ
```
A dyadic Link accepting two integers (either way around) which yields a list of two lists.
**[Try it online!](https://tio.run/##y0rNyan8/7/I79ia////m/23BAA "Jelly – Try It Online")**
### How?
```
rNƬ - Link: integer, a; integer b e.g. 7; 4
r - inclusive range [a..b] [7,6,5,4]
Ƭ - collect up while unique, applying:
N - negate (vectorises) 0-applications: [[7,6,5,4]]
1-application: [[7,6,5,4],[-7,-6,-5,-4]]
2-applications: [[7,6,5,4],[-7,-6,-5,-4],[7,6,5,4]]
- no longer distinct
-> [[7,6,5,4],[-7,-6,-5,-4]]
```
---
There are many, many ways to achieve this task in four bytes in Jelly.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 22 bytes
```
->a,b{[*-b..-a,*a..b]}
```
[Try it online!](https://tio.run/##KypNqvyfZhvzX9cuUSepOlpLN0lPTzdRRytRTy8ptvZ/gUJatJmOZex/AA "Ruby – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 26 25 bytes
-1 bytes thanks to Giuseppe
```
function(a,b)c(a:b,-b:-a))
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jUSdJM1kj0SpJR1cjySpRU/N/moaZjpkmF4iy1PwPAA "R – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~44~~ ~~43~~ 42 bytes
Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
Saved a byte thanks to [S.S. Anne](https://codegolf.stackexchange.com/users/89298/s-s-anne)!!!
```
f(a,b){for(;b/a;)printf("-%d %1$d ",a++);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NI1EnSbM6Lb9IwzpJP9Fas6AoM68kTUNJVzVFQdVQJUVBSSdRW1vTuvZ/bmJmnoZmNVeahpmOpaY1F0xlTJ4SkAcSNQPStf8B "C (gcc) – Try It Online")
[Answer]
# Java 10, ~~76~~ ~~56~~ ~~52~~ 50 bytes
```
b->a->{for(;a<=b;)System.out.println(a+","+-a++);}
```
-22 bytes thanks to *@OlivierGrégoire*.
Takes the inputs in reverse order. Prints pairs of positive and negative integers `"a,-a"` newline separated.
[Try it online.](https://tio.run/##dY8xa8MwEIV3/4rDk4xtjYHWiZdCIUPIkLF0ODlykCPLwjoFQvBvdxVXpR3c5bjHvXf3XYc3LLvzdW40OgcHVOaRADhCUg10Yco9Kc1bbxpSg@HvsdnuDcmLHIs109tgnO/l@GOqa2hhN4uyxrJ@tMPIKtzuRJWd7o5kzwdP3I7KkDYM87RI8xLzPKumuUoCjfVCB5oIdRvUGfoAyk4UMpePT8DsCQ1A0hHbFC9Z9VduFjklv38tK5ZpuAlYPKuIO1aQ0r2xnl4hzcUCFxCDiEfW/EdP34HoaTlaq@9MZBybRlpi@H860k7zFw)
**Explanation:**
```
b->a->{ // Method with two integer parameters and no return-type
for(;a<=b;) // Loop in the range [a,b]:
System.out.println( // Print with trailing newline:
a // `a`
+" " // appended with a space
+-a // appended with `-a`
++);} // And then increase `a` by 1 with `a++`
```
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg), `-pn` , 5 bytes
```
ɧ⑷④±.
```
It prints all the numbers separated by newlines.
## Explained
```
ɧ⑷④±.
ɧ # Generate a range between the two implicit inputs
⑷④±. # For each number in that range, print it raw without popping, negate it, and print it raw
```
[Try it online!](https://tio.run/##ARkA5v9rZWf//8mn4pG34pGjwrEu//82Cjn/LXBu "Keg – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~33~~ 31 bytes
-2 bytes thanks to [@mypronounismonicareinstate](https://codegolf.stackexchange.com/users/36445/my-pronoun-is-monicareinstate).
```
b=>f=a=>a>b?[]:[a,-a,...f(a+1)]
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9u@z/J1i7NNtHWLtEuyT461io6UUc3UUdPTy9NI1HbUDP2f3J@XnF@TqpeTn66RrqGpaaGmabmfwA "JavaScript (Node.js) – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~47~~ 46 bytes
Much shorter than the beautiful LINQ solutions with `SelectMany` :(
I also cannot remember when I last wrote a `for` loop while code-golfing, so I likely missed trivial golfs.
```
a=>b=>{for(int i=a;i<=b;Print(-i++))Print(i);}
```
[Try it online!](https://tio.run/##Sy7WTS7O/O9Wmpdsk5lXoqPgmFySmZ8HYtvZKbgp2P5PtLVLsrWrTssv0gAKKmTaJlpn2tgmWQcUAbkaupna2pqaEHampnXtf2suNw0zTQ1LTev/AA "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# Google Sheets, 66 bytes
```
=ArrayFormula({Row(Indirect(A1&":"&A2));-Row(Indirect(A1&":"&A2))}
```
Sheets will automatically add the last closing parentheses when you exit the cell. (A 1.5% byte reduction!)
Input is in cells A1 and A2. The order doesn't actually matter.
`Indirect(A1&":"&A2)` creates a range that contains all the rows between those numbers, inclusive.
`Row(Indirect(~))` returns the row numbers of everything in that range.
[](https://i.stack.imgur.com/ioHOB.png)
[Answer]
# [PHP](https://php.net/), ~~51~~ ~~46~~ 40 bytes
```
fn($a,$b)=>[range($a,$b),range(-$b,-$a)]
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwKWSZvs/LU9DJVFHJUnT1i66KDEvPRXK1YFwdFWSdHRVEjVj/1tzlSUWxaeU5hZoqKRpmOlYamqiC5kBhf4DAA "PHP – Try It Online")
simply using php7 lambda functions short notation and built-in array functions..
EDIT: hum I see that from PHP7.4 we have now a spread operator! -5 bytes
EDIT2: thanks to DomHastings for saving another 6 bytes!
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + Core utilties, 21 bytes
```
seq $1 $2;seq -$2 -$1
```
[Try it online!](https://tio.run/##S0oszvj/vzi1UEHFUEHFyBrE0lUxAmLD////m/23BAA "Bash – Try It Online")
[Answer]
# LaTeX, ~~61~~ 56 bytes
```
\input tikz.tex\def\f#1#2{\foreach~in{#1,...,#2}{~;-~;}}
```
Defines a macro `f` that takes input as two arguments and outputs the numbers as tokens to latex (so they are printed in the pdf), semicolon-seperated.
## Explanation
```
\input tikz.tex % load the tikz package for the foreach command
\def\f#1#2{ % define a macro f that takes two arguments
\foreach ~ % loop with the loop variable called ~
% (to save a space between the name and "in")
in {#1,...,#2} { % where ~ ranges from the first to the second
% argument, inclusive
~;-~; % the macro f expands to
% ~
% a semicolon and a minus sign
% ~
% another semicolon
}
}
```
## Example
```
\documentclass{article}
\input tikz.tex
\def\f#1#2{\foreach~in{#1,...,#2}{~;-~;}}
\begin{document}
\f6 9
\f6 6
\end{document}
```
Output:
[](https://i.stack.imgur.com/lIckw.png)
[Answer]
# [Kotlin](https://kotlinlang.org) , 22 bytes
```
{a,b->(a..b)+(-b..-a)}
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `W`, 3 bytes
```
ṡ:N
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=W&code=%E1%B9%A1%3AN&inputs=6%0A9&header=&footer=)
```
ṡ:N
ṡ Inclusive range of inputs
: Duplicate
N Negate the duplicate
W flag: Wrap both ranges into one list, which is implicitly output
```
[Answer]
# [Erlang (escript)](http://erlang.org/doc/man/escript.html), 36 bytes
```
g(A,B)->[[X,-X]||X<-lists:seq(A,B)].
```
[Try it online!](https://tio.run/##Sy3KScxL100tTi7KLCj5z/U/XcNRx0lT1y46OkJHNyK2pibCRjcns7ik2Ko4tRAsF6v3PzcxM08jOlZTQdeOSwEIMvOtyosyS1I10jXMdMw0NXWAAnk5Gpo6mLKWCFm9/wA "Erlang (escript) – Try It Online")
# [Erlang (escript)](http://erlang.org/doc/man/escript.html), 40 bytes
Port of Surculose Sputum's answer.
```
g(A,A)->[A,-A];g(A,B)->[A,-A]++g(A+1,B).
```
[Try it online!](https://tio.run/##Sy3KScxL100tTi7KLCj5z/U/XcNRx1FT1y7aUUfXMdYaxHWCc7W1gXxtQ6CI3v/cxMw8jehYTQVdOy4FIMjMtyovyixJ1UjXMNMx09TUAQrk5Who6mDKWiJk9f4DAA "Erlang (escript) – Try It Online")
[Answer]
# [Befunge-98 (FBBI)](https://github.com/catseye/FBBI), 24 bytes
```
&00p&v
0g-k@>::.'-,.1+:0
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tPj/X83AoECtjMsgXTfbwc7KSk9dV0fPUNvK4P9/QyMFMwA "Befunge-98 (FBBI) – Try It Online")
### Explanation
`&00p&` is the input part. `&00p` takes \$b\$ as input and stores it in the top left corner. `&` takes input \$a\$ and pushes it to the stack.
`0g-k@>::.'-,.1+:0` is the main loop and, as the instruction pointer wraps around, equivalent to:
```
::.'-,.1+:00g-k@
:: duplicate a twice
. print a
'-, print '-'
. print a
1+ increase a
: duplicate the new value of a
00g get b from the top-left corner
- calculate a-b, as Befunge has no negative values,
this is 0 for b>=a
k@ execute *quit* (b-a)-times
```
[Answer]
# [J](http://jsoftware.com/), 10 bytes
```
]-.&i:<:@[
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/Y3X11DKtbKwcov9rcilwpSZn5CuYKaQpWHL9BwA "J – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk/wiki/Commands), 5 [bytes](https://github.com/barbuz/Husk/wiki/Codepage)
```
mSe_…
```
[Try it online.](https://tio.run/##yygtzv7/Pzc4Nf5Rw7L///@b/bcEAA)
Or alternatively:
```
Svm_…
```
[Try it online.](https://tio.run/##yygtzv7/P7gsN/5Rw7L///@b/bcEAA)
**Explanation:**
```
… # Create a an inclusive range using the two (implicit) input-arguments
m # Map over this list
Se # and pair each element with:
_ # Its negative
# (after which the result is output implicitly)
… # Create a an inclusive range using the two (implicit) input-arguments
v # Concatenate it with:
S m # The same list with each value mapped to:
_ # Its negative
# (after which the result is output implicitly)
```
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 11 bytes
```
ps^pr@Jng.+
```
[Try it online!](https://tio.run/##SyotykktLixN/f@/oDiuoMjBKy9dT/v/f2MFSwA "Burlesque – Try It Online")
I feel like there's probably a better way to parse the input, but I'm not getting it. Explanation:
```
ps^p # Parse input as block and split block to stack
r@ # Generate range between two inputs
Jng # Duplicate and negate
.+ # Concatenate and implicitly output
```
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 15 bytes
```
{1 -1*/:y,y^!x}
```
[Try it online!](https://tio.run/##y9bNz/7/P82q2lBB11BL36pSpzJOsaL2f1q0mbVl7H8A "K (oK) – Try It Online")
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 36 bytes
```
,[->+>->-<<<],+[->>+<<]>>[-<.+>>.-<]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fJ1rXTttO107XxsYmVkcbyLPTBrLs7KJ1bfS07ez0dG1i//9n4wQA "brainfuck – Try It Online")
## Clarification
Input and output are treated as bytes (as permitted in [Can numeric input/output be in the form of byte values?](https://codegolf.meta.stackexchange.com/questions/4708/can-numeric-input-output-be-in-the-form-of-byte-values/4719#4719))
Since negative bytes don't really make sense, a negative answer wraps around and starts at the largest value of the cell. For example, given a cell size of 128, the output for the input in bytes `[6, 9]` will be (in bytes) `[6,(128-6),7,(128-7),8,(128-8),9,(128-9)]`
Hopefully that's a fair enough interpretation of the rules!
[Answer]
# [Perl 5](https://www.perl.org/), 20 bytes
```
say"$_
-$_"for<>..<>
```
[Try it online!](https://tio.run/##K0gtyjH9/784sVJJJZ5LVyVeKS2/yMZOT8/G7v9/My7Lf/kFJZn5ecX/dX1N9QwMDQA "Perl 5 – Try It Online")
[Answer]
# [Zsh](https://www.zsh.org/), 17 bytes
```
echo {,-}{$1..$2}
```
[Try it online!](https://tio.run/##qyrO@J@moanxPzU5I1@hWke3tlrFUE9Pxaj2vyYXV5qCoYIJkDRTsASTZv8B "Zsh – Try It Online")
] |
[Question]
[
Your challenge: Write a function that takes a string `s`, a character `c`, and finds the length of the longest run of `c` in `s`. The length of the run will be `l`.
**Rules**:
* If `s` is of length 0 or `c` is empty, `l` should be 0.
* If there are no instances of `c` in `s`, `l` should be 0.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/61563) and [Standard I/O Rules](https://codegolf.meta.stackexchange.com/q/2447/61563) apply.
* No matter where in `s` the run of `c`s is located, `l` should be the same.
* Any printable ASCII characters can appear in `s` and `c`.
**Test cases**:
```
s,c --> l
"Hello, World!",'l' --> 2
"Foobar",'o' --> 2
"abcdef",'e' --> 1
"three spaces",' ' --> 3
"xxx xxxx xx",'x' --> 4
"xxxx xx xxx",'x' --> 4
"",'a' --> 0
"anything",'' --> 0
```
**Winner**:
As with [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") the shortest answer in each language wins.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
### Code:
```
SQγOM
```
Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f8/OPDcZn/f//89UnNy8nUUwvOLclIUuXIA "05AB1E – Try It Online")
### Explanation:
```
SQ # Check for each character if it is equal to the second input
γ # Split the list of zeros and ones into groups
O # Sum each array in the arrays
M # Get the maximum
```
[Answer]
# Mathematica, 35 bytes
```
Max[Tr/@Split@Boole@Thread[#==#2]]&
```
Pure function taking a list of characters and another character as input and returning a nonnegative integer. Improved upon my first effort using [Adnan's observation](https://codegolf.stackexchange.com/a/125385/56178) (go upvote!) that one should test for equaling the special character before splitting the array.
`Thread[#==#2]` checks whether each input character in the first argument equals the character given as the second argument. `Boole` converts the resulting `True`s and `False`s to `1`s and `0`s. `Split` splits the list into runs of consecutive elements; `Tr/@` sums each sublist, and `Max` finds the winner. (Because of how `Max` works, if the first argument is the empty list, then this function returns `-∞`. So, you know, don't do that.)
## first submission (51 bytes)
```
Max[Split@#/.a:{c_String..}:>Boole[c==#2]Length@a]&
```
`Split@#` splits the input into runs of consecutive characters, such as `{{"t"}, {"h"}, {"r"}, {"e", "e"}, {" ", " ", " "}, {"s"}, {"p"}, {"a"}, {"c"}, {"e"}, {"s"}}` for the fourth test case. `/.a:{c_String..}:>` replaces each subexpression `a` that is a list of a repeated character `c` by `Length@a` multiplied by `Boole[c==#2]`, which is `1` if `c` equals the input character and `0` otherwise. Then `Max` extracts the answer.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 20 18 15 bytes
```
fV+Vî+)ª0)n o l
```
[Try it online!](https://tio.run/##y0osKPn/Py1MO@zwOm3NQ6sMNPMU8hVy/v9XKskoSk1VUFAoLkhMTi1W0lFXUAcA "Japt – Try It Online")
Saved 5 bytes thanks to obarakon and ETHproductions
[Answer]
# [Python](https://docs.python.org/2/), 38 bytes
```
f=lambda s,c:+(c in s)and-~f(s,c+c[0])
```
[Try it online!](https://tio.run/##LcyxCsIwEIDhuX2Ks0sbGkEdC13FN3AQhzS50kBMQhIxLr56vFqXO/6P4/w7Lc6eSplHIx6TEhC5HPpOgrYQmbBq/5k7sl7eDndWXos2CMehrshGbf0zdayufNA2we@QcXoBsjQXNMZxuLpg1K7hrWnr5uzcJAKFoxCTVDhTIEVaAiIARC8kRkIgzDlD3gZJ3mStVf9CS7Rf "Python 2 – Try It Online")
Dennis saved 3 bytes by updating `c` to a string of duplicated characters rather than recursively updating a number to multiply `c` by.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~11~~ 6 bytes
-5 bytes thanks to [carusocomputing](https://codegolf.stackexchange.com/users/59376/carusocomputing)
```
γvy²¢M
```
[Try it online!](https://tio.run/##MzBNTDJM/f//3OayykNrDm0KzEyvNfD9/78koyg1VUFBobggMTm1mEsBAA "05AB1E – Try It Online")
```
γ # split into chunks of consecutive equal elements
vy # For each chunk...
²¢ # Count the number of input characters in this chunk
M # Push the largest count so far
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes
```
=ĠṠG
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCI9xKDhuaBHIiwiIiwiW1wieFwiLFwieFwiLFwieFwiLFwiIFwiLFwieFwiLFwieFwiLFwiIFwiLFwieFwiLFwieFwiLFwieFwiXVxueCJd)
```
= # Is each character of the string equal to the character?
# Produces a list of 1s and 0s
Ġ # Group consecutive items
Ṡ # Sum each - groups of 1s become their length, groups of 0 become 0
G # Find the maximum
```
[Answer]
## Haskell, ~~43~~ 39 bytes
```
f c=maximum.scanl(\n k->sum[n+1|c==k])0
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00h2TY3sSIztzRXrzg5MS9HIyZPIVvXrrg0NzpP27Am2dY2O1bT4H9uYmaegq1CSj6XgkJBUWZeiYKKQpqCerK6glJycrJCMoRQwpTFIpSYlJySmqb0HwA "Haskell – Try It Online")
Run through the string and replace the current char with a counter that is increased whenever it equals `c` or reset to `0` if not. Take the maximum of the list.
Thanks to @xnor for 4 bytes.
[Answer]
# C# ~~116~~ 115 bytes
My first code golf
Edited because initial submission was a snippet and was missing required namespace for regex
Edit#2 complete rewrite to support characters with special regex meanings
~~using System.Linq;s=>c=>System.Text.RegularExpressions.Regex.Replace(s,"[^"+c+"]",++c+"").Split(c).Max(x=>x.Length);~~
```
using System.Linq;s=>c=>{var r=(char)(c-1);return string.Join("",s.Select(x=>x==c?c:r)).Split(r).Max(x=>x.Length)};
```
[Answer]
# JavaScript (ES6), ~~54~~ ~~53~~ 51 bytes
*-2 bytes thanks to @Neil*
*-1 byte thanks to @apsillers*
```
s=>c=>[...s].map(x=>j=(i=x==c&&i+1)>j?i:j,i=j=0)&&j
```
Takes input in currying syntax: `f("foobar")("o")`.
## Test Snippet
```
f=
s=>c=>[...s].map(x=>j=(i=x==c&&i+1)>j?i:j,i=j=0)&&j
```
```
String: <input id=I> Letter: <input id=J maxlength=1 size=1> <button onclick='O.innerHTML+=`f("${I.value}")("${J.value}") = ${f(I.value)(J.value)}\n`'>Run</button><pre id="O"></pre>
```
### Another option using `eval` and `for` (54 bytes)
```
s=>c=>eval("i=j=0;for(x of s)i=x==c&&i+1,i>j?j=i:0;j")
```
### Old Answer using Regex (85 bytes)
```
s=>c=>c?Math.max(...s.match(eval(`/${/\w/.test(c)?c:"\\"+c}*/g`)).map(x=>x.length)):0
```
[Answer]
## JavaScript (Firefox 30-57), ~~75~~ 72 bytes
```
(s,c)=>Math.max(0,...(for(s of s.split(/((.)\2*)/))if(s[0]==c)s.length))
```
ES6 compatible snippet:
```
f=
(s,c)=>Math.max(0,...s.split(/((.)\2*)/).filter(s=>s[0]==c).map(s=>s.length))
```
```
<div oninput=o.textContent=f(s.value,c.value)><input id=s><input id=c maxlength=1 size=1><pre id=o>0
```
`split` returns a bunch of empty strings and single characters as well as the runs but this doesn't affect the result.
[Answer]
# [Micro](http://esolangs.org/wiki/Micro), 112 bytes
```
{T l m 1+:Q # T Q T l~:r}:Z{T[0]+}:X
{i s m:n
n p = if(Z,X)
i L=if(,a)}:a
0\\:C:s:i"":p"":n[0]:T
s l:L
a
T l m:\
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 63 bytes
```
i;m;f(s,c)char*s;{for(i=m=0;*s;s++)*s^c?m=m>i?m:i,i=0:i++;s=m;}
```
[Try it online!](https://tio.run/##ZY7BisIwEIbvPsVspLSxKXg2RE@77H2FvZSFOKY60DSSeAiIz16netniHAb@7xtmBpsT4jiS9rqrkkKJZxtXSd@6ECsy3qw1p1TXcpX@cOeN39LOb0iRWW@ornUyXt/H5dF1NDjYf/7sn2vgEmm4dpVoRZFaoaAssISm2QIU1A4MkgJU8DoqF97SUMnbArieS8S36/ug4DfE/vghVNmXUv/TXyEcbGQe5twekH9h7ub8eo7OcUoXiy6xh7nPOUN@NZb5TU5iGniXTOxE7uMD "C (gcc) – Try It Online")
[Answer]
# [Perl 6](https://perl6.org), ~~45 43~~ 42 bytes
```
->$_,$c {$c&&$_??.comb(/$c+/)».chars.max!!0}
```
[Test it](https://tio.run/##ZY9da8IwFIbv8yuOpdgWk7ovvFhRt4uOwTa92NgYFCRNj1OoTWnqqDh/2e72x7pTde4rgZC8z3vOe5JjkfbqpUF47fkqYIsVtJVOEPq1GNgTbitY26rdtifDoa/0Ina7tup0vY93X81kYfyFrFqto01NhRclmhL6kM4zNK5HKD@HNQNo2t@NRzfhs7gPQzEai/Dx8jYg8tZcXN8sY1O6jhADh9P2PA72hG1YU/hATQOWpzKDzjYhYFNd7MPEANzI8EjxCKscVYkJjxI0ytsGzw00n3ENV9Ty4IDGwTa1dY1pqjk86SJNWhZ3UgeAhgA4YdaV1rEsSNQk7tcXk7FKcEoM/7BjZpWzApHeJpcKDXnA2bFTZlVVBdXuIFA5h7qzLWv0hv9jJMjvpB95RzRLtipn8@yFPM5v9gk "Perl 6 – Try It Online")
```
->$_,$c {$c&&$_??.comb(/$c+/).max.chars!!0}
```
[Test it](https://tio.run/##ZY9da8IwFIbv8yuOpdgW0@o@8GJF3S46Btv0YmNjUJA2PU6hNqWpI6L@9u5EnftKICTv857znpRY5f1mpRA@@oEI2XINbSEzhEHjD@0ptwVsbNFu29PRKBBymbpdW3S6XrBMdCDmSaVard6uobLrGlUNA8gXBSrXGMor2DAA0/xxMr6P3vynKPLHEz96uXkIiWzNxQ3UKlW16/j@0OG0PY@DPWU7ZgqfqWnIyjwpoLNPCNlMVscwfwhurHgseIy6RFFjxuMMlfD2wQsF5iuu4oJanhxgHGzXWHeY55LDq6zyrGVxJ3cAaAiAc2bdSpkmFYmSxOP6YkkqMpwRwz/sjFn1vEKktyoTgYo84BzYBbO01qAPBwHtnOou98zohv9jJCTfST/yejRLsa7ni@KdPM5v9gk "Perl 6 – Try It Online")
```
->$_,$c {$c&$_??.comb(/$c+/).max.chars!!0}
```
[Test it](https://tio.run/##ZY9da8IwFIbv8yuOpZgW0@o@8GJF3S46Btv0YmNjUJA2PU6hNqWpo6L@9u5EnftKICTv857znhRYZv1mpRE@@r4M2HINbalShEHjDe2psCVsbNm2p6ORL9Uycbq27HRdfxnXvpzHpW61eruGqq4r1BUMIFvkqB1jKK5gwwBM78fJ@D58857C0BtPvPDl5iEgsjUXx9erRFcO97whF7RdV4A9ZTtmCp@pacCKLM6hs08I2EyVxzBvCE6kRSRFhHWBssJURClq6e6DFxrMTxwtJLU8OcA42K6x7jDLlIBXVWZpyxI84wA0BMA5s26VSuKSREXicX2xOJEpzojhH3bGrGpeItJbF7FETR7gB3bBrLquoT4cBGp@qrvcM6Mb/o@REH8n/cjr0Sz5upov8nfy8N/sEw "Perl 6 – Try It Online")
## Expanded:
```
-> $_, $c { # pointy block lambda
$c & $_ # AND junction of $c and $_
# empty $c would run forever
# empty $_ would return 4 ( "-Inf".chars )
?? # if True (neither are empty)
.comb(/$c+/) # find all the substrings
.max # find the max
.chars # get the length
!! # if False (either is empty)
0 # return 0
}
```
[Answer]
# JavaScript, ES6, 52
Recursive solution that treats the string input as an array (note: the initial input is still a string) and consumes left-to-right in character `C`:
```
f=([C,...s],c,t=0,T=0)=>C?f(s,c,C==c&&++t,t>T?t:T):T
```
Tracks current run in `t` and global best in `T`.
Explanation:
```
f= // function is stored in `f` (for recursion)
([C,...s], // turn input string in first-char `C` and the rest in `s`
c, // argument `c` to search for
t=0,T=0) // current total `t`, best total `T`
=>
C? // if there is still any char left in the string
f(s,c, // recursively call `f`
C==c&&++t, // increment `t` if char is match, or set `t` to `false`
t>T?t:T) // set global `T` to max of `t` and `T`
:T // when string is depleted, return `T`
```
Setting `t` to `false` on non-matches works because whenever `t` is incremented, `false` is treated as `0` (i.e., `false + 1` is `1`), and `false` will never compare grater than any value in global-max `T`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
=ŒgṀS
```
This is a dyadic link/function that takes a string and a character. Note that it cannot work as a full program, as input from command-line arguments uses Python syntax, and Python – unlike Jelly – does not distinguish singleton strings from characters.
[Try it online!](https://tio.run/##Tc2xCsIwEAbg3af43YM@gau4FxTHa3u1lWBKWiXdio/grLOLo6DiKD5I@yKxqQEd7nJ8P5dbs5SVtZP3YdU86sA2zyvm7f6C13nsniXQ3G9tfUSQy6wElZDZhhPmuBDgHUkwRWmPAprjbcS9CBSck6aSEVa/nZG13Wez7qoSWCgt42Fbn0RXctAFU6V0SNqTckRhFHPihZ2UqWYGUOQUceETuMQYA/Ntno1nRy76Zz/TBw "Jelly – Try It Online")
### How it works
```
=ŒgṀS Main link. Left argument: s (string). Right argument: c (character)
= Compare all characters in s with c, yielding 1 for c and 0 otherwise.
Œg Group adjacent, equal Booleans in the resulting array.
Ṁ Take the maximum. Note that any array of 1's will be greater than any array
of 0's, while two arrays of the same Booleans are compared by length.
S Take the sum, yielding the length for an array of 1's and 0 otherwise.
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 25 bytes
```
(.).*?(\1*)(?!.+\2).*
$.2
```
[Try it online!](https://tio.run/##K0otycxL/P9fQ09TT8teI8ZQS1PDXlFPO8YIyOdS0TP6/z/fLT8/KbEIAA "Retina – Try It Online")
The first character is the character to be checked.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~18~~ 11 bytes
Requires swapping `⊂` with `⊆` in Version 16.0 or having `⎕ML←3` (default on many systems).
```
⌈/0,≢¨⊂⍨⎕=⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qr8@jtgnGXI862n3y84AiPR36BjqPOhcdWvGoq@lR7wqgElsg/g9U8F8BDEDquNQ9UnNy8nUUwvOLclIU1bnUc9S5kKXd8vOTEouA4vmo4olJySmpaUDxVFTxkoyi1FQgr7ggMTm1GCivgCpfUVGhUAEhgJIVGJIgCZACTEmgSCKaG/IqSzIy89KBMuoA "APL (Dyalog Unicode) – Try It Online")
`⎕=⎕` Boolean for equality between two inputs
`⊂⍨` self-partition (begin partitions where a non-zero element is greater than its predecessor)
`≢¨` tally each
`0,` prepend a zero (for the empty-input cases)
`⌈/` max of those
---
Old solution
Prompts first for *s*, then for *c*
```
⌈/0,(⎕,¨'+')⎕S 1⊢⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKPdJz8PSPd06BvoaDzqm6pzaIW6tromkBWsYPioaxGQAVL1XwEMQIq51D1Sc3LydRTC84tyUhTVudRz1LmQpd3y85MSi4Di@ajiiUnJKalpQPFUVPGSjKLUVCCvuCAxObUYKK@AKl9RUaFQASGAkhUYkiAJkAJMSaBIIpob8ipLMjLz0oEy6gA "APL (Dyalog Unicode) – Try It Online")
`⎕` prompt for s
`⊢` for that
`(`…`)⎕S 1` PCRE **S**earch for the lengths of occurrences of
`'+'` a plus symbol (meaning one or more)
`,¨` appended to each of the elements of
`⎕` the prompted-for *c*
`0,` prepend a zero (for the empty-input cases)
`⌈/` max of those
*c* must be given as a 1-element vector of an enclosed string if it needs escaping.
[Answer]
# PHP, ~~70~~ 67 bytes
three versions:
```
while(~$c=$argv[1][$i++])$x=max($x,$n=($c==$argv[2])*++$n);echo+$x;
while(~$c=$argv[1][$i++])$x=max($x,$n=$c==$argv[2]?++$n:0);echo+$x;
for(;++$n&&~$c=$argv[1][$i++];)$x=max($x,$n*=$c==$argv[2]);echo+$x;
```
takes input from command line arguments; run with `-r` or [test them online](http://sandbox.onlinephpfunctions.com/code/6e28c32804921c118e088c07cc97afb6c03f9dde).
[Answer]
# [PHP](https://php.net/), 70 bytes
```
for(;~$c=$argv[1][$i++];)$r[]=$argv[2]==$c?++$n:$n=0;echo$r?max($r):0;
```
[Try it online!](https://tio.run/##LcqxCsMgEADQvZ8hB0kwgbRjrqcfIg4i0etQlRtCp/51ZgOl6@M1bv1pG7cbBMkHObWoWaWUsxhjMrOahzB47KnKiF@I9Hvu7h28tPY4gTj/x4cngmi1hrJBoRX3yBXEvsNnBJm2FXs/S11iiLxf "PHP – Try It Online")
# [PHP](https://php.net/), 75 bytes
```
for(;~$s=substr($argv[1],$i++);)$r[]=strspn($s,$argv[2]);echo max($r?:[0]);
```
[Try it online!](https://tio.run/##JYqxCsIwEEB3v6KEgyY0BXU0hn5IyBBDNQ42x53KTf61cyx2ecN7Dwu284QFd5Do9vZBjcoqEelkg7K99NG1ayXtPsCeXxd@kv7v4RAt3IfBOAMUol8D46KB7ZaP0bg5l9o9kmig6RT2q2ntu9Qxp1zmHw "PHP – Try It Online")
# [PHP](https://php.net/), 83 bytes
```
<?=@preg_match_all("<".preg_quote($argv[2])."+>",$argv[1],$t)?strlen(max($t[0])):0;
```
[Try it online!](https://tio.run/##JYzLDoMgFAX3foW5kggpPuqyIvY/KDHEEFmgUkub@@NdW2PPbiaZE1zYRR9cSIjZpk@noAAOiJhmWVWhPIb4EAJTROC5zHWb9PJIunvY7DTMJo5uMN5TEFCe6vleo6XnnWo0K@Eigf/xqjmJrH/FzduFzgYpiarWjN3qdt@/y1qMZnT2Bw "PHP – Try It Online")
+8 Bytes to avoid `@`
```
<?=($a=$argv[2])&&preg_match_all("<".preg_quote($a)."+>",$argv[1],$t)?strlen(max($t[0])):0;
```
[Answer]
# JavaScript (ES6), ~~47~~ ~~40~~ 38 bytes
(Saved 7 bytes thanks to @Neil, and 2 bytes thanks to @HermanLauenstein.)
```
s=>g=c=>c&&s.includes(c)?1+g(c+c[0]):0
```
**Explanation:**
Recursively searches for a longer run until none is found.
**Snippet:**
```
let f=
s=>g=c=>c&&s.includes(c)?1+g(c+c[0]):0
console.log(f('Hello, World!')('l' )); //2
console.log(f('Foobar')('o' )); //2
console.log(f('abcdef')('e' )); //1
console.log(f('three spaces')(' ' )); //3
console.log(f('xxx xxxx xx')('x' )); //4
console.log(f('xxxx xx xxx')('x' )); //4
console.log(f('')('a' )); //0
console.log(f('anything')('' )); //0
```
[Answer]
# Jelly, ~~10~~ 9 bytes
```
f⁴L
ŒgÇ€Ṁ
```
Explanation:
```
f⁴L
f⁴ -Filter by the character argument.
L -Return Length of filtered String.
ŒgÇ€»/
Œg -Group string by runs of characters.
Ç€ -Run above function on each group.
Ṁ -Return the largest in the list.
```
[Try it online!](https://tio.run/##y0rNyan8/z/tUeMWH66jk9IPtz9qWvNwZ8P///8zgFL5CuX5RTkpiv9zAA "Jelly – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 71 bytes
```
f=lambda s,c,m=0,k=0:s and f(s[1:],c,-~m*(s[0]==c),max(m,k))or max(m,k)
```
[Try it online!](https://tio.run/##NY6xDoIwFEV3v@LJ0pY8DepG0t0/cGg6FChCaIG0HTAEf71WjC93uOcs982v0E3jLcaWG2WrRoHHGi0vcOBF6UGNDbTUi0spkz@9bZ6gkJzXDK1aqMWBscnBv8c2QdA@QD@CEOSujZkQHpMzzZEgMUQiCKKqutFt4ufO2ZIO9iwZkuUnQ@e0BgA/q1r75IFIWR5gdv0YaLaW19sG65ad06ZVgfrg6HeaYXo53xtj8QM "Python 3 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 66 bytes
```
import Data.List
((maximum.(0:).map length).).(.group).filter.elem
```
[Try it online!](https://tio.run/##FcKxCgIxDADQ3a8It1w7GJyF2xz1I8KRXoNNG9oc@OPOFR8v03hzKXOKWusOD3LCpwy/pC0EpY/oqRhu94hKBoXr4TlixIBHb6dFTFKcO3JhnUpSYQPrUh1CgnWssLxkjH8zWeL81nbdac/8Aw "Haskell – Try It Online")
A slightly easier to read version - not pointfree:
```
f c s = maximum (0:(map length (filter (elem c) (group s))))
```
Groups the string by letter, then filters by those groups that contain the right character, then finds the lengths, appends 0 to the list of lengths in case it doesn't appear, and finally finds the maximum value.
[Answer]
# Mathematica, 109 bytes
```
(s=Differences[First/@StringPosition[#,#2]];k=t=0;Table[If[s[[i]]==1,t++;If[k<t,k=t],t=0],{i,Length@s}];k+1)&
```
**input**
>
> ["xxx xxxx xx","x"]
>
>
>
[Answer]
# [Python 2](https://docs.python.org/2/), 69 bytes
```
lambda s,c:c and max(map(len,re.findall(c+'+',s))or[0])or 0
import re
```
[Try it online!](https://tio.run/##XZDBbsMgDEDvfIV3IlHRlPVYqdepf9BDhiYHTItEAAEH9vUZbJOy1gfLfs@SZcevcg/@uJnzx@ZwXTRCFuqkAL2GFeuwYhwceZHo1Viv0blBHfiBizyOIc2TbBkmZtcYUoFEW6FcPhVmynCGmUGLmV/IuSDgGpLTL1wAd1yKP/cewoKpw7BDXJQm0yHtsNwTUatyREW5S9hlrRXqb@qmPphOu30yvcV/S337hvW3jrlkkjHTjrNgPexXnX6GY7K@gBls@4AAO7/JcfsG "Python 2 – Try It Online")
[Answer]
# [CJam](https://sourceforge.net/p/cjam), ~~20~~ ~~19~~ ~~18~~ 16 bytes
```
0q~e`f{~@=*}$+W=
```
[Try it online!](https://tio.run/##S85KzP3/36CwLjUhrbrOwVarVkU73Pb/f/UcBSWP1JycfB2F8PyinBRFJQA "CJam – Try It Online")
### Explanation
```
0 e# Push 0. We'll need it later.
q~ e# Read and eval input. Pushes c and s to the stack.
e` e# Run-length encode s: turns it into an array of [length, char] pairs.
f{ e# Map over these pairs using c an extra parameter:
~ e# Dump the pair to the stack.
@= e# Bring c to the top, check equality with the char, pushing 0 or 1.
* e# Multiply the length by the result.
} e# (end map)
$ e# Sort the resulting list in ascending order.
+ e# Prepend the 0 from before, in case it's empty.
W= e# Get the last element.
```
[Answer]
# Excel, 56 bytes
```
{=MAX(IFERROR(FIND(REPT(A2,ROW(A:A)),A1)^0*ROW(A:A),0))}
```
`s` should be input to `A1`.
`c` should be input to `A2`.
Formula must be an array formula (`Ctrl`+`Shift`+`Enter`) which adds curly brackets `{ }`.
Technically, this can only handle where the longest run is less than 1,048,576 (which is 2^20) because that's how rows the current Excel will let you have in a worksheet. Since it loads the million+ values into memory whenever it recalculates, this is not a *fast* formula.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 15 bytes
```
0i0v=dfd1L)0hX>
```
[Try it online!](https://tio.run/##y00syfn/3yDToMw2JS3F0EfTICPC7v9/dY/UnJx8hfD8opwUdS71HHUA "MATL – Try It Online")
The basic algorithm is very simple (no use of split!), but I had to throw in `0i0v` and `0h` to allow for the edge cases. Still, I thought the approach was nice, and perhaps I can still find another technique to handle the edge cases: the algorithm finds the longest run in the middle of a string just fine, but not for single characters or empty strings; I'm still testing if I can 'pad' the variables at better places for better results.
```
0i0v % Prepends and appends a zero to the (implicit) input.
= % Element-wise equality with the desired char (implicit input)
d % Pairwise difference. Results in a 1 at the start of a run, and -1 at the end.
f % Get indices of 1's and -1's.
d % Difference to get length of the runs (as well as length of non-runs)
1L) % Only select runs, throw out non-runs. We now have an array of all run lengths.
0h % 'Find' (`f`) returns empty if no run is found, so append a zero to the previous array.
X> % Maximum value.
```
Does not work on empty `c`. Then again, I suppose each string contains an infinite run of empty strings between each character :)
[Answer]
# [R](https://www.r-project.org/), ~~66~~ 58 bytes
*-8 bytes thanks to BLT and MickyT*
```
function(s,c)max((r=rle(el(strsplit(s,''))))$l*(r$v==c),0)
```
returns an anonymous function. TIO has a 1-byte difference because `el` doesn't work there for inexplicable reasons.
[Try it online!](https://tio.run/##DchBCoAgEADAe6@oJWg3PNQDvPeDDuEhTEHYMlaLfm/ehpHidfHPZXOIFyZl6dw/RNHCDlOWdHPI9YeBtm02hqjnEaV/tbakJioeYXHMUbVrFD46UMBATe2qHaj8 "R – Try It Online")
[Answer]
# Java 8, ~~67~~ 65 bytes
```
s->c->{int t=0,m=0;for(char x:s)m=m>(t=x==c?t+1:0)?m:t;return m;}
```
-2 bytes thanks to *@OlivierGrégoire*
Takes input `s` as a `char[]`, and `c` as a `char`
**Explanation:**
[Try it here.](https://tio.run/##pdI9a8MwEAbgPb/imiU2dYS7xrVDKYR26JShQ5pBkeVEqT6MdA4yIb/dlalLJ1NDQQhxd3p4ETrTC12amutz@dkJVRuLcA410qCQpGo0Q2E02QyHbMYkdQ7eqNDXGYBDioLBT/uRnajd7ZPfwnMoUIbcJvCqkR@5LQqoIIfOLQu2LK5CI2CeJipPs8rYqBfAr1ysclVEmPs8Z2u8f1il8VqtMLMcG6tBZbcuCwHCqpuDDBmGKBcjSlAhXrRFK/Rxtwca91EBtq1DrohpkNShhVJHFaF1Ldto/sKlNAm8GyvLuzlB0wd/spa2URwPQwu5iOPsT2pjzIHaMcNMMuiBlbwaM/gkA0@W8zDjasq4G7NgkuW9B/@9jUF@KtQjPfY/aOw2nfa@usVT@B1jykc6MLfZrfsC)
```
s->c->{ // Method with char[] and char parameters and int return-type
int t=0, // Temp counter-integer
m=0; // Max integer
for(char a:s) // Loop over the characters of the input
m=m>(
t=x==c? // If the current character equals the input-character:
t+1 // Raise `t` by 1
: // Else:
0) // Reset `t` to 0
?m:t; // If `t` is now larger than `m`, put `t` as new max into `m`
// End of loop (implicit / single-line body)
return m; // Return the resulting max
} // End of method
```
] |
[Question]
[
# "Fit Numbers"
Sam has a "brilliant" idea for compression! Can you help?
---
Here is a rundown of Sam's compression scheme. First take in a base 10 representation of any natural number strictly smaller than 2^16, and write it as a binary string without any leading zeros.
```
1 -> 1
9 -> 1001
15 ->1111
13 ->1101
16 -> 10000
17 -> 10001
65535 -> 111111111111111
```
Now replace any group of one or more zeros with a single zero. This is because the number has gotten leaner. Your binary string now will look like this.
```
1 -> 1 -> 1
9 -> 1001 -> 101
15 ->1111 -> 1111
13 ->1101 -> 1101
16 -> 10000 -> 10
17 -> 10001 -> 101
65535 -> 111111111111111 -> 111111111111111
```
Now you convert the binary string back to a base 10 representation, and output it in any acceptable format. Here are your test cases. The first integer represents an input, and the last integer represents an output. Note that some numbers do not change, and thus can be called "fit"
```
1 -> 1 -> 1 -> 1
9 -> 1001 -> 101 -> 5
15 ->1111 -> 1111 -> 15
13 ->1101 -> 1101 -> 13
16 -> 10000 -> 10 -> 2
17 -> 10001 -> 101 -> 5
65535 -> 1111111111111111 -> 1111111111111111 -> 65535
65000 -> 1111110111101000 -> 11111101111010 -> 16250
```
---
You may use any language, but please note that Sam hates standard loopholes. This is code golf so the code can be as short as possible to make room for the "compressed" numbers".
---
Note:This is NOT an acceptable compression scheme. Using this will promptly get you fired.
---
Citation-Needed: I do not take credit for this concept. This comes from @Conor O' Brien's blog [here](http://cergos.blogspot.com/2016/02/fitbits.html) see this OEIS of fit numbers. <https://oeis.org/A090078>
[Answer]
# Bash + GNU utilities, 27
```
dc -e2o?p|tr -s 0|dc -e2i?p
```
Input read from STDIN.
[Answer]
## [05AB1E](https://github.com/Adriandmen/05AB1E), ~~8~~ 6 bytes
```
b00¬:C
```
**Explanation**
```
b # convert input to binary
00¬: # replace 00 with 0 while possible
C # convert to int
```
[Try it online](http://05ab1e.tryitonline.net/#code=YjAwwqw6Qw&input=NjUwMDA)
Saved 2 bytes thanks to [Adnan](https://codegolf.stackexchange.com/users/34388/adnan)
[Answer]
## JavaScript (ES6), 41 bytes
```
n=>+`0b${n.toString(2).replace(/0+/g,0)}`
```
[Answer]
## [Jellyfish](https://github.com/iatorm/jellyfish), 20 bytes
```
p
d
# S
,1
*
\dbi
2
```
[Try it online!](http://jellyfish.tryitonline.net/#code=cApkCiMgUwosMQoqClxkYmkKIDI&input=MTc)
## Explanation
* `i` is input.
* `b` converts it to binary (list of digits)
* `\d` with arguments `2` and the digit list applies `d` (binary digits to number) to every length-2 substring of the digit list.
* `*` takes signum of the results: 00 goes to 0, everything else to 1.
* `,1` tacks a 1 to the end, so the last digit is not lost.
* `# S` selects from `bi` those digits which have a 1 on the list computed above: those that are not the left halves of 00.
* `d` converts back to number, and `p` prints the result.
[Answer]
## Python 2, 36 bytes
```
f=lambda n:n and f(n/2)<<(n%4>0)|n%2
```
A direct recursive implementation with no base conversion built-ins or string operations. Less golfed:
```
f=lambda n:n and[f(n/2),n%2+2*f(n/2)][n%4>0]
```
When `n` is a multiple of 4, it ends in two 0's in binary, so we cut one by floor-dividing by 2. Otherwise, we split `n` into `(n%2) + 2*(n/2)`, leave the last binary digit `n%2` alone, and recurse on the other digits `n/2`.
[Answer]
# Bash (sed + bc), ~~60~~ ~~55~~ 43 bytes
```
echo $[2#`bc<<<obase=2\;$1|sed s/00\*/0/g`]
```
edit:
1. changed `sed -E 's/0+` to `sed 's/00*` and changed echo and pipe used to pass the value to bc with `<<<`.
2. Brilliant suggestion by @Digital Trauma!
example:
```
$ bash script.sh 65000
16250
$ bash script.sh 15
15
$ bash script.sh 9
5
```
[Answer]
# [Perl 6](http://perl6.org), ~~31~~ 27 bytes
```
~~{:2(.base(2).subst(:g,/0+/,0))}~~
{:2(.base(2)~~{S:g/0+/0/})}
```
## Explanation:
```
-> $_ {
# convert from base 2
:2(
# convert to base 2
$_.base(2)
# substitute
.subst(
:global,
/ 0+ /, # all substrings made of 0s
'0' # with one 0
)
)
}
```
## Example:
```
my &fit-compress = {:2(.base(2)~~{S:g/0+/0/})}
say fit-compress 1; # 1
say fit-compress 9; # 5
say fit-compress 15; # 15
say fit-compress 13; # 13
say fit-compress 16; # 2
say fit-compress 17; # 5
say fit-compress 65535; # 65535
say fit-compress 65000; # 16250
# number created with 「:2( [~] <0 1>.roll: 256 )」
say fit-compress 80794946326210692074631955353531749442835289622757526957697718534769445507500
# 4240335298301026395935723255481812004519990428936918
```
[Answer]
# MATL, ~~11~~ ~~9~~ 8 bytes
```
BFFOZtXB
```
This version works only in MATLAB since `strrep` in MATLAB can handle logical inputs. Here is a version that will work in Octave (9 bytes) (and thus the online interpreter) which explicitly casts the logical inputs to type `double`.
[**Try it online**](http://matl.tryitonline.net/#code=Qm9GRk9adFhC&input=OQ)
**Explanation**
```
% Implicitly grab input
B % Convert decimal to binary
FF % Create the array [0 0]
O % Number literal
Zt % Replaces all [0 0] with [0] (will replace any number of 0's with 0)
XB % Convert binary to decimal
% Implicitly display
```
[Answer]
# Python 3, ~~55~~, 50 bytes.
Saved 4 bytes thanks to Sp3000.
Pretty straightforward solution.
```
import re
f=lambda x:eval(re.sub('0+','0',bin(x)))
```
[Answer]
# Ruby, ~~35~~ 31 bytes
-2 bytes thanks to @Doorknob
```
->n{eval ("0b%b"%n).squeeze ?0}
```
See it on repl.it: <https://repl.it/CnnQ/2>
[Answer]
## Javascript (ES6), 40 bytes
```
n=>'0b'+n.toString(2).replace(/0+/g,0)-0
```
[Answer]
## Actually, 14 bytes
```
├`'0;;+(Æ`Y2@¿
```
[Try it online!](http://actually.tryitonline.net/#code=4pScYCcwOzsrKMOGYFkyQMK_&input=NjUwMDA)
Explanation:
```
├`'0;;+(Æ`Y2@¿
├ bin(input) (automatically discards leading zeroes)
`'0;;+(Æ`Y call this function until the output stops changing:
'0;;+ push "0", "00"
(Æ replace "00" with "0" in binary string
2@¿ convert from binary to decimal
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 7 bytes
**6 bytes thanks to Zgarb for [his algorithm](https://codegolf.stackexchange.com/a/90083/48934).**
```
~~BŒgµL\*x@Ḣµ€FḄ~~
BŒgḄBFḄ
```
[Try it online!](http://jelly.tryitonline.net/#code=QsWSZ-G4hEJG4biE&input=&args=NjUwMDA)
[Answer]
## PHP, 53 51 Bytes
```
<?=bindec(preg_replace("/0+/",0,decbin($argv[1])));
```
Takes an argument from the console.
## Thanks to:
@manatwork replace "0" with 0
[Answer]
## Perl, 38 + 1 (`-p`) = 39 bytes
```
$_=oct"0b".sprintf("%b",$_)=~s/0+/0/gr
```
Needs `-p` flag to run (I added `-l` flag to make it more readable, but it's not needed otherwise) :
```
perl -plE '$_=oct"0b".sprintf("%b",$_)=~s/0+/0/gr' <<< "1
9
15
13
16
17
65535
65000"
```
Note much to say about the code : it converts the number into binary (`sprintf"%b"`), then replaces blocs of zeros by just one zero, and converts the result into decimal (`oct"0b".`).
[Answer]
## C#, ~~112~~ 91 bytes
```
int x(int x)=>Convert.ToInt32(Regex.Replace(Convert.ToString(x,2),"0+","0"),2);
```
-8 bytes thanks to TuukkaX
[Answer]
# Java, 75
```
int f(Integer x){return x.valueOf(x.toString(x,2).replaceAll("0+","0"),2);}
```
Test program:
```
public class Fit {
int f(Integer x){return x.valueOf(x.toString(x,2).replaceAll("0+","0"),2);}
public static void main(final String... args) {
final Fit x = new Fit();
System.out.println(x.f(65000));
}
}
```
[Answer]
# [PARI/GP](http://pari.math.u-bordeaux.fr/), ~~54~~ 43 bytes
```
n->fold((a,b)->a+if(b,a+1,a%2,a),binary(n))
```
[Answer]
# C, 37 bytes
```
f(x){return x?f(x/2)<<!!(x%4)|x&1:0;}
```
[Answer]
## PowerShell v2+, 69 bytes
```
[convert]::ToInt32(([convert]::ToString($args[0],2)-replace'0+',0),2)
```
(*[feature-request](/questions/tagged/feature-request "show questions tagged 'feature-request'")A shorter way to convert to/from binary in PowerShell*)
Takes input `$args[0]`, uses the .NET built-in `[convert]::ToString(int,base)` to convert the input integer into a binary base string. That's filtered through the `-replace` to strip out any runs of one-or-more-zeros to just `0`. That resultant string is sent back through the other direction via `[convert]::ToInt32(string,base)` to turn the binary back into an integer. That integer is left on the pipeline and output is implicit.
### Test Cases
```
PS C:\Tools\Scripts\golfing> 1,9,15,13,16,17,65535,65000|%{"$_ -> " +(.\output-fit-number.ps1 $_)}
1 -> 1
9 -> 5
15 -> 15
13 -> 13
16 -> 2
17 -> 5
65535 -> 65535
65000 -> 16250
```
[Answer]
# Reference Implementation in [S.I.L.O.S](https://esolangs.org/wiki/S.I.L.O.S) "only" 417 bytes
Golfed
```
readIO :
i + 1
I = i
z = 1
n = 32
b = n
z = 1
n = b
lbla
n - 1
GOSUB p
j = i
j - p
if j b
if z c
z = 1
GOTO e
lblc
b - 1
if n a
GOTO f
lblb
z = 0
A = a
A + 1000
set A 1
i - p
lble
a + 1
if n a
lblf
q = 1000
e = q
e + b
i = 0
lbl>
d = q
d - e
if d ?
n = b
n - i
GOSUB p
g = get q
g * p
o + g
i + 1
q + 1
GOTO >
lbl?
o / 2
printInt o
GOTO z
funcp
p = 1
Z = n
lblQ
if Z C
GOTO D
lblC
Z - 1
p * 2
GOTO Q
lblD
return
lblz
```
Here is the reference implementation fully ungolfed. As a bonus feature it outputs the steps needed to come to an answer.
```
/**
*Reference Implementation in the high quality S.I.L.O.S language.
*/
readIO Enter a number to "compress"
//some declarations
i + 1
I = i
z = 1
//the above is a flag which shows whether or not a zero was last outputted
n = 32
b = n
//maximum number of input bits
printLine Original Binary
lblbinLoop
n - 1
GOSUB pow
j = I
j - p
if j printOne
if z ENDLOOP
print 0
GOTO ENDLOOP
lblprintOne
z = 0
print 1
I - p
lblENDLOOP
if n binLoop
printLine
printLine Binary "Compressed"
z = 1
n = b
lbltopA
n - 1
GOSUB pow
j = i
j - p
if j printAOne
if z DontPrint
z = 1
print 0
GOTO ENDLOOPA
lblDontPrint
b - 1
if n topA
GOTO endOfBin
lblprintAOne
z = 0
print 1
A = a
A + 1000
set A 1
i - p
lblENDLOOPA
a + 1
if n topA
lblendOfBin
printLine
printLine -----------
printLine Base 10 Output
print Out Bits:
printInt b
q = 1000
e = q
e + b
i = 0
lblOutputDec
d = q
d - e
if d DONE
n = b
n - i
GOSUB pow
g = get q
g * p
o + g
i + 1
q + 1
GOTO OutputDec
lblDONE
printLine
printLine ---------
o / 2
printInt o
GOTO funcs
//function declarations must be wrapped in gotoes to avoid the interpreter from complaining (breaking)
/**
*This will store the nth power of two in the "p" variable
*/
funcpow
p = 1
Z = n
lbltop
if Z continue
GOTO end
lblcontinue
Z - 1
p * 2
GOTO top
lblend
return
lblfuncs
```
By request the transpilation has been deleted. Feel free to view the edit history to recover it, otherwise go to [this repo](https://github.com/rjhunjhunwala/S.I.L.O.S) for an interpreter.
Sample output for 65000
```
Enter a number to "compress"
65000
Original Binary
1111110111101000
Binary "Compressed"
11111101111010
-----------
Base 10 Output
Out Bits:14
---------
16250
```
[Answer]
# Pyth, 12
```
i:.BQ"0+"\02
```
[Online.](https://pyth.herokuapp.com/?code=i%3A.BQ%220%2B%22%5C02&input=65000&test_suite=1&test_suite_input=1%0A9%0A15%0A13%0A16%0A17%0A65535%0A65000&debug=0)
```
.BQ # Convert input from base 10 to base 2
: "0+"\0 # Replace multiple zeroes with single zero
i 2 # Convert back from base 2 to base 10
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 30 bytes
```
.+
$*1;
+`(1+)\1
$1;
1;
1
;+
0
```
[Try it online!](http://retina.tryitonline.net/#code=LisKJCoxOworYCgxKylcMQokMTsKMTsKMQo7Kwow&input=NjUwMDA)
And here I thought Retina would be amongst the first answers...
[Answer]
# Java, ~~152~~ ~~143~~ 138 bytes
```
interface C{static void main(String[]b){Integer i=0;System.out.print(i.parseInt(i.toString(i.parseInt(b[0]),2).replaceAll("0+","0"),2));}}
```
* 9 bytes less thanks to @RohanJhunjhunwala. I prefer to keep it as a fully functioning program with main and the like. However, of course it can be golfed more otherwise.
* 5 bytes less thanks to @LeakyNun's suggestions.
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 19 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
```
{2⊥⍵/⍨~0 0⍷⍵}2∘⊥⍣¯1
```
[TryAPL online!](http://tryapl.org/?a=f%u2190%7B2%u22A5%u2375/%u2368%7E0%200%u2377%u2375%7D2%u2218%u22A5%u2363%AF1%20%u22C4%20f%A81%209%2015%2013%2016%2017%2065535%2065000&run)
**This function is really an "atop" of two functions, the first function is:**
`2∘⊥⍣¯1` the *inverse* of binary-*to*-decimal conversion, i.e. binary-*from*-decimal conversion
*two* `2` *is bound* `∘` to *-to-decimal* `⊥`
*repeat* the operation `⍣` *negative one* time `¯1` (i.e. once, but inverted)
**In the second function, the above's binary result is represented by** `⍵`**:**
`{2⊥⍵/⍨~0 0⍷⍵}`
`0 0⍷⍵` Boolean for where {0, 0} begins in ⍵
`~` Boolean negation, so now we have ᴛʀᴜᴇ everywhere but at non-first zeros in zero-runs
`⍵/⍨` use that to filter ⍵, so this removes our unwanted zeros
`2⊥` convert binary-to-decimal
[Answer]
# TSQL, 143 bytes
Not using build ins to convert from and to binary.
Golfed:
```
DECLARE @i INT=65000
,@ CHAR(99)=''WHILE @i>0SELECT @=REPLACE(LEFT(@i%2,1)+@,'00',0),@i/=2WHILE @>''SELECT @i+=LEFT(@,1)*POWER(2,LEN(@)-1),@=STUFF(@,1,1,'')PRINT @i
```
Ungolfed:
```
DECLARE @i INT=65000
,@ CHAR(99)=''
WHILE @i>0
SELECT @=REPLACE(LEFT(@i%2,1)+@,'00',0),@i/=2
WHILE @>''
SELECT @i+=LEFT(@,1)*POWER(2,LEN(@)-1),@=STUFF(@,1,1,'')
PRINT @i
```
**[Fiddle](https://data.stackexchange.com/stackoverflow/query/525494/output-fit-numbers)**
[Answer]
# CJam, 16
```
q~2b1+0a%0a*);2b
```
[Try it online](http://cjam.aditsu.net/#code=q~2b1%2B0a%250a*)%3B2b&input=65000)
It's quite long due to lack of regex.
**Explanation:**
```
q~ read and evaluate the input number
2b convert to base 2 (array of 1s and 0s)
1+ append a 1 to deal with trailing zeros
0a% split by [0], dropping empty pieces; only chunks of 1s are left
0a* join by [0]
); discard the 1 we appended before
2b convert back from base 2
```
[Answer]
# Java, 64 bytes
```
i->{return i.parseInt(i.toString(i,2).replaceAll("0+","0"),2);};
```
# Test Program
```
public static void main(String[] args) {
Function<Integer, Integer> function = i -> {
return i.parseInt(i.toString(i, 2).replaceAll("0+", "0"), 2);
};
System.out.println(function.apply(1)); // 1
System.out.println(function.apply(9)); // 5
System.out.println(function.apply(15)); // 15
System.out.println(function.apply(13)); // 13
System.out.println(function.apply(16)); // 2
System.out.println(function.apply(17)); // 5
System.out.println(function.apply(65535)); // 65535
}
```
[Answer]
# [CJam](https://sourceforge.net/projects/cjam/), 23 bytes
```
ri2be`{_:g:>{:g}&}%e~2b
```
[**Try it online!**](http://cjam.tryitonline.net/#code=cmkyYmVge186Zzo-ezpnfSZ9JWV-MmI&input=MTc)
### Explanation
```
ri e# Read input as an integer
2b e# Convert to binary
e` e# Run-length encoding. Gives a nested (2D) array with run-lengths
e# and binary digits
{ e# This block is mapped over the outer array, i.e. is applied to
e# each inner array
_ e# Duplicate the inner array
:g e# Signum of each element of inner array
:> e# This gives true if second element (digit) is false and first
e# element (run-length) is not zero. If so, we need to set that
e# run-length to 1
{:g}& e# If that's the case, apply signum to original copy of inner
e# array, to make run-length 1
}% e# End block which is mapped over the outer array
e~ e# Run-length decoding
2b e# Convert from binary. Implicitly display
```
[Answer]
### Ruby, 37 35 bytes
Saved two bytes thanks to manatwork.
```
->a{a.to_s(2).gsub(/0+/,?0).to_i 2}
```
The naive approach. (:
] |
[Question]
[
Given an input `n`, write a program or function that outputs/returns the sum of the digital sums of `n` for all the bases 1 to `n`.
$$n + \sum\_{b=2}^n \sum\_{i=0}^\infty \left\lfloor \frac{n}{b^i} \right\rfloor \bmod b$$
### Example:
`n = 5`
---
Create the range `[1...n]`: `[1,2,3,4,5]`
---
For each element `x`, get an array of the base-`x` digits of `n`: `[[1,1,1,1,1],[1,0,1],[1,2],[1,1],[1,0]]`
bijective base-`1` of `5` is `[1,1,1,1,1]`
base-`2` (binary) of `5` is `[1,0,1]`
base-`3` of `5` is `[1,2]`
base-`4` of `5` is `[1,1]`
base-`5` of `5` is `[1,0]`
---
Sum the digits: `13`
---
### Test cases:
```
1 1
2 3
3 6
4 8
5 13
6 16
7 23
8 25
9 30
10 35
36 297
37 334
64 883
65 932
```
The sequence can be found on OEIS: [A131383](https://oeis.org/A131383)
### Scoring:
[code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): The submission with the lowest score wins.
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 3 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
┬]∑
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXUyNTJDJXVGRjNEJXUyMjEx,i=NjU_,v=8)
Canvas beating Jelly?
```
{ ] map over 1..input (implicit "{")
┬ decode input from that base
∑ sum the resulting (nested) array
```
[Answer]
# [Haskell](https://www.haskell.org/), 46 bytes
```
f n=sum$do a<-[1..n];mapM(pure[0..a])[1..n]!!n
```
[Try it online!](https://tio.run/##JY69DoMwDIR3nuJaMYCAiJ8WhhKWru3UEUVVJEKpCgGRIHh7GmDx2Z9PZzdc/UTbrmsNSdXU2VUPngdlRIhkt44PT2eYRlGGhHDmHvh0kmvHvxIUzuZ4Y5g0tFBaoShckH0mGAWvQPMcH6HvvdRCamUBcyNGsVsWk2D0pceHhA3V9LNhnoczgsIU0@3MqbG4lnVcoNi@iEK2rcsk9ZPMTy9@emVrHGd/ "Haskell – Try It Online")
## Explanation
The function `\b n -> mapM(pure[0..b])[1..n]`, generates all strings \$[0 \dotsc b]^n\$ in lexicographic order. For example:
```
mapM(pure[0..2])[0..1] == [[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2]]
```
By indexing into it with `(!!n)` this can be used to convert `n` to base `b+1`, however this won't work for unary (base-\$1\$), but we're summing the results.. We can even save some bytes with `a <- [1..n]` and using base-\$(n+1)\$ rather than a work-around for base-\$1\$ since we're missing \$[\underset{n\text{ times}}{\underbrace{1,\dotsc,1}}]\$ which is the same as \$[n]\$ when summing.
Using `do`-notation just concatenates all the lists instead of nesting them:
```
λ [ mapM (pure [0..a]) [1..5] !! n | a <- [1..5] ]
[[0,0,1,0,1],[0,0,0,1,2],[0,0,0,1,1],[0,0,0,1,0],[0,0,0,0,5]]
λ do a <- [1..5]; mapM (pure [0..a]) [1..5] !! n
[0,0,1,0,1,0,0,0,1,2,0,0,0,1,1,0,0,0,1,0,0,0,0,0,5]
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~39~~ 37
```
->n{(2..n).sum{|b|n.digits(b).sum}+n}
```
The only golfing here is removing some whitespace. [Try it online](https://tio.run/##KypNqvyfpmCrEPNf104jT7Naw0hPL09Tr7g0t7omqSZPLyUzPbOkWCMJLFSrnVf7v0AhTS85MSdHw8jIXPM/AA)
[Answer]
# [Python 2](https://docs.python.org/2/), 57 bytes
```
lambda n:sum(n/(k/n+2)**(k%n)%(k/n+2)for k in range(n*n))
```
This uses the formula $$a(n)=\sum\_{b=2}^{n+1}\sum\_{i=0}^{n-1}\left\lfloor\frac{n}{b^i}\right\rfloor\bmod b,$$ which works since \$\left\lfloor\frac{n}{(n+1)^0}\right\rfloor\bmod(n+1)=n\$.
[Try it online!](https://tio.run/##RYyxCsIwGAZnfYpvCf2TRkpSrVDQF1GHiMaW2L8lNoNPHy0IDjfcDTe9525kmz0OOOenG643B25faSCuKFRcWqkUBcFS/NSPEQE9Izp@3IkVS5mXyP9oNIyRKHGqG416r9Fsv@wu7Xo1xZ5nFMImbI4QdSogQKzhaTl9AA "Python 2 – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 14 [bytes](https://github.com/abrudz/SBCS)
```
+/∘∊⊢,⊢(⍴⊤⊣)¨⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///X1v/UceMRx1dj7oW6QCxxqPeLY@6ljzqWqx5aMWj3s3/0x61TXjU22f0qKv5Ud/U4CBnIBni4RnMBaSBUmkKhnCWEZxlDGeZwFmmcJYZnGUOZ1nAWZYIkw0QBiL0GCM0mSFMN0MYb2SEUGFobGH8HwA "APL (Dyalog Unicode) – Try It Online")
### Explanation
Some parentheses are implied and can be added (lighter than the "official" parenthesizing):
```
+/∘∊(⊢,(⊢(⍴⊤⊣)¨⍳))
```
This is a monadic atop. Given an argument `Y`, this function behaves like:
```
+/∘∊(⊢,(⊢(⍴⊤⊣)¨⍳))Y
```
The two functions are applied in order. We'll start from the right one:
```
⊢,(⊢(⍴⊤⊣)¨⍳)
```
The are three functions in this train, so this is a fork. Given an argument `Y`, it acts as:
```
(⊢Y),((⊢Y)(⍴⊤⊣)¨⍳Y)
```
We can easily reduce to this (monadic `⊢` returns its argument, hence called *identity*):
```
Y,Y(⍴⊤⊣)¨⍳Y
```
Now, we know that `Y` is an integer (simple scalar, i.e. number or character), since we're given one. Therefore `⍳Y`, with `⎕IO=1`, returns `1 2 ... Y`. `⍳Y` actually returns an array with shape `Y` (`Y` must be a vector), where every scalar is the index of itself in the array (that's why monadic `⍳` is called the *index generator*). These indices are vectors, except for the case where `1≡⍴Y`, where they are scalars (this is our case).
Let's parse the middle function, `(⍴⊤⊣)¨`, next. `⍴⊤⊣` is the operand of `¨` (*each*), and the function is dyadic, so the `¨` operator will first reshape each length-1 argument to the shape of the other (that is, take the element and use it to replace every scalar in the other argument), and then apply the function to each pair of the two arguments. In this case, `⍳Y` is a vector and `Y` is a scalar, so, if `n≡⍴⍳Y`, then `Y` will be converted to `n⍴Y` (`⍴` represents the *shape* (monadic) and *reshape* (dyadic) functions). That is, in simpler terms, `Y` will be converted to an array containing `Y` times `Y`.
Now, for each pair, let's call the left argument `X` and the right `Z` (so that we don't conflict with the input `Y`). `⍴⊤⊣` is a dyadic fork, so it will expand to:
```
(X⍴Z)⊤X⊣Z
```
Let's make the easy first step of reducing `X⊣Z` to `X` (dyadic `⊣` is the *left* function):
```
(X⍴Z)⊤X
```
The `⍴` in `X⍴Z` is, again, the *reshape* function, so `X⍴Z`, in our case, is simply `X` times `Z`. `⊤` is the *encode* function. Given two arrays of numbers, where the left array is the base of each digit in the result (doesn't need to be integer or positive), i.e. the encoding, and the right is an array of numbers, returns the transposed array of those numbers in the specified encoding (transposition is the reversal of an array's dimensions relative to its elements). The representation of a digit is based on the quotient of the division of the number and the product of the less significant bases. If any base is `0`, it acts as base +∞. The arguments' scalars are all simple. Since `X` is a positive integer, and `X⍴Z` is a vector of equal elements, this is really just a case of converting `X` to base `Z` and reshaping to `X` digits. For \$X,Z\in\mathbb N\$, \$X\_Z\$ (\$X\$ in base \$Z\$) can't have more than \$X\$ digits, since \$X\_1\$ has \$X\$ digits. Therefore, `X⍴Z` is enough for our purposes.
The result of `Y(⍴⊤⊣)¨⍳Y` is, therefore, `Y` converted to each base from 1 to `Y`, possibly with leading zeroes. However, there is one issue: in APL, base 1 isn't special-cased, while this challenge does special-case it, so we have to include the sum of the base-1 digits of `Y` ourselves. Fortunately, this sum is just `Y`, since \$Y\_1=\underbrace{[1,1,...,1]}\_Y\$, so the sum is simply \$Y\times1=Y\$. It follows that we have to add `Y` somewhere into the array. This is how we do it:
```
Y,Y(⍴⊤⊣)¨⍳Y
```
I have already included this part here. Dyadic `,` is the *catenate* function, it concatenates its arguments on their last axes, and errors if that's not possible. Here, we simply concatenate the scalar `Y` to the vector `Y(⍴⊤⊣)¨⍳Y`, so that we increment the sum we're going to calculate by `Y`, as explained above.
The final part is the left function of our atop, `+/∘∊`:
```
+/∘∊Y,Y(⍴⊤⊣)¨⍳Y
```
`∘` is the *compose* operator. `f∘g Y` is the same as `f g Y`. However, we're using it here so that our train doesn't fork on the `∊`. So, we can reduce:
```
+/∊Y,Y(⍴⊤⊣)¨⍳Y
```
Now, it's time for the sum, but wait... there's a problem. The array isn't flat, so we can't just sum its elements before flattening it first. The *enlist* function `∊` flattens an array. Now that the array has been flattened, we finally use `+/` to sum it. `/` is the *reduce* operator, it applies a dyadic function between an array's elements on its second-to-last axis, with right-to-left priority. If the rank (number of dimensions, i.e. length of shape) of the array doesn't decrease, the array is then enclosed, although this is not the case here. The function that's applied here is `+`, which is the *plus* function that adds the pairs on the last axes of two arrays (and errors if the arrays can't be added like that). Here, it simply adds two numbers a number of times so that the reduce is completed.
Lo and behold, our train:
```
+/∘∊⊢,⊢(⍴⊤⊣)¨⍳
```
[Answer]
# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 153 bytes
```
[S S S N
_Push_0][S N
S _Duplicate_0][T N
T T _Read_STDIN_as_integer][T T T _Retrieve_input][S N
S _Duplicate_input][N
S S N
_Create_Label_OUTER_LOOP][S N
S _Duplicate_top][S S S T N
_Push_1][T S S T _Subtract][N
T S S N
_If_0_Jump_to_Label_PRINT][S S S N
_Push_0][S N
S _Duplicate_0][T T T _Retrieve_input][N
S S T N
_Create_Label_INNER_LOOP][S N
S _Duplicate][N
T S S S N
_If_0_Jump_to_Label_AFTER_INNER_LOOP][S N
T _Swap_top_two][S T S S T N
_Copy_1st_item_to_top][S T S S T T N
_Copy_3rd_item_to_top][T S T T _Modulo][T S S S _Add][S N
T _Swap_top_two][S T S S T S N
_Copy_2nd_item_to_top][T S T S _Integer_divide][N
S N
T N
_Jump_to_Label_INNER_LOOP][N
S S S S N
_Create_Label_AFTER_INNER_LOOP][S N
N
_Discard_top][S T S S T S N
_Copy_2nd_item_to_top][T S S S _Add][S N
T _Swap_top_two][S S S T N
_Push_1][T S S T _Subtract][N
S N
N
_Jump_to_Label_OUTER_LOOP][N
S S S N
_Create_Label_PRINT][S N
N
_Discard_top][T N
S T _Print_as_integer]
```
Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.
[**Try it online**](https://tio.run/##PY1RCoAwDEO/k1P0DPvxPCID/RMUPH7XtHMbZF3ySL/zevtz70d3NzPGBaGTc4nJm8KfAihLH5QHSyhVrEqUlF@vMGZlTFxBYWtPRHMP1efe2jYA) (with raw spaces, tabs and new-lines only).
Port of [my Java 8 answer](https://codegolf.stackexchange.com/a/176982/52210), because Whitespace has no Base conversion builtins at all.
**Example run: [`input = 3`](https://tio.run/##PY1RCsAgDEO/k1P0DjvRGIL7Exzs@F3TOhViTR7p2@@nzXFezd3MGBeETs4lJm8JfwqgLH1QHiyhVLEqUVJ@vcKYlTFxB4XtPRGtPVSf@/EB)**
```
Command Explanation Stack Heap STDIN STDOUT STDERR
SSSN Push 0 [0]
SNS Duplicate 0 [0,0]
TNTT Read STDIN as integer [0] {0:3} 3
TTT Retrieve input from heap 0 [3] {0:3}
SNS Duplicate 3 [3,3] {0:3}
NSSN Create Label_OUTER_LOOP [3,3] {0:3}
SNS Duplicate 3 [3,3,3] {0:3}
SSSTN Push 1 [3,3,3,1] {0:3}
TSST Subtract (3-1) [3,3,2] {0:3}
NTSSN If 0: Jump to Label_PRINT [3,3] {0:3}
SSSN Push 0 [3,3,0] {0:3}
SNS Duplicate 0 [3,3,0,0] {0:3}
TTT Retrieve input from heap 0 [3,3,0,3] {0:3}
NSSTN Create Label_INNER_LOOP [3,3,0,3] {0:3}
SNS Duplicate 3 [3,3,0,3,3] {0:3}
NTSSSN If 0: Jump to Label_AFTER_IL [3,3,0,3] {0:3}
SNT Swap top two [3,3,3,0] {0:3}
STSSTN Copy (0-indexed) 1st [3,3,3,0,3] {0:3}
STSSTTN Copy (0-indexed) 3rd [3,3,3,0,3,3] {0:3}
TSTT Modulo (3%3) [3,3,3,0,0] {0:3}
TSSS Add (0+0) [3,3,3,0] {0:3}
SNT Swap top two [3,3,0,3] {0:3}
STSSTSN Copy (0-indexed) 2nd [3,3,0,3,3] {0:3}
TSTS Integer divide (3/3) [3,3,0,1] {0:3}
NSNTN Jump to LABEL_INNER_LOOP [3,3,0,1] {0:3}
SNS Duplicate 1 [3,3,0,1,1] {0:3}
NTSSSN If 0: Jump to Label_AFTER_IL [3,3,0,1] {0:3}
SNT Swap top two [3,3,1,0] {0:3}
STSSTN Copy (0-indexed) 1st [3,3,1,0,1] {0:3}
STSSTTN Copy (0-indexed) 3rd [3,3,1,0,1,3] {0:3}
TSTT Modulo (1%3) [3,3,1,0,1] {0:3}
TSSS Add (0+1) [3,3,1,1] {0:3}
SNT Swap top two [3,3,1,1] {0:3}
STSSTSN Copy (0-indexed) 2nd [3,3,1,1,3] {0:3}
TSTS Integer divide (1/3) [3,3,1,0] {0:3}
NSNTN Jump to LABEL_INNER_LOOP [3,3,1,0] {0:3}
SNS Duplicate 0 [3,3,1,0,0] {0:3}
NTSSSN If 0: Jump to Label_AFTER_IL [3,3,1,0] {0:3}
NSSSSN Create Label_AFTER_IL [3,3,1,0] {0:3}
SNN Discard top [3,3,1] {0:3}
STSSTSN Copy (0-indexed) 2nd [3,3,1,3] {0:3}
TSSS Add (1+3) [3,3,4] {0:3}
SNT Swap top two [3,4,3] {0:3}
SSSTN Push 1 [3,4,3,1] {0:3}
TSST Subtract (3-1) [3,4,2] {0:3}
NSNN Jump to LABEL_OUTER_LOOP [3,4,2] {0:3}
SNS Duplicate 2 [3,4,2,2] {0:3}
SSSTN Push 1 [3,4,2,2,1] {0:3}
TSST Subtract (2-1) [3,4,2,1] {0:3}
NTSSN If 0: Jump to Label_PRINT [3,4,2] {0:3}
SSSN Push 0 [3,4,2,0] {0:3}
SNS Duplicate 0 [3,4,2,0,0] {0:3}
TTT Retrieve input from heap 0 [3,4,2,0,3] {0:3}
NSSTN Create Label_INNER_LOOP [3,4,2,0,3] {0:3}
SNS Duplicate 3 [3,4,2,0,3,3] {0:3}
NTSSSN If 0: Jump to Label_AFTER_IL [3,4,2,0,3] {0:3}
SNT Swap top two [3,4,2,3,0] {0:3}
STSSTN Copy (0-indexed) 1st [3,4,2,3,0,3] {0:3}
STSSTTN Copy (0-indexed) 3rd [3,4,2,3,0,3,2] {0:3}
TSTT Modulo (3%2) [3,4,2,3,0,1] {0:3}
TSSS Add (0+1) [3,4,2,3,1] {0:3}
SNT Swap top two [3,4,2,1,3] {0:3}
STSSTSN Copy (0-indexed) 2nd [3,4,2,1,3,2] {0:3}
TSTS Integer divide (3/2) [3,4,2,1,1] {0:3}
NSNTN Jump to LABEL_INNER_LOOP [3,4,2,1,1] {0:3}
SNS Duplicate 1 [3,4,2,1,1,1] {0:3}
NTSSSN If 0: Jump to Label_AFTER_IL [3,4,2,1,1] {0:3}
SNT Swap top two [3,4,2,1,1] {0:3}
STSSTN Copy (0-indexed) 1st [3,4,2,1,1,1] {0:3}
STSSTTN Copy (0-indexed) 3rd [3,4,2,1,1,1,2] {0:3}
TSTT Modulo (1%2) [3,4,2,1,1,1] {0:3}
TSSS Add (1+1) [3,4,2,1,2] {0:3}
SNT Swap top two [3,4,2,2,1] {0:3}
STSSTSN Copy (0-indexed) 2nd [3,4,2,2,1,2] {0:3}
TSTS Integer divide (1/2) [3,4,2,2,0] {0:3}
NSNTN Jump to LABEL_INNER_LOOP [3,4,2,2,0] {0:3}
SNS Duplicate 0 [3,4,2,2,0,0] {0:3}
NTSSSN If 0: Jump to Label_AFTER_IL [3,4,2,2,0] {0:3}
NSSSSN Create Label_AFTER_IL [3,4,2,2,0] {0:3}
SNN Discard top [3,4,2,2] {0:3}
STSSTSN Copy (0-indexed) 2nd [3,4,2,2,4] {0:3}
TSSS Add (2+4) [3,4,2,6] {0:3}
SNT Swap top two [3,4,6,2] {0:3}
SSSTN Push 1 [3,4,6,2,1] {0:3}
TSST Subtract (2-1) [3,4,6,1] {0:3}
NSNN Jump to LABEL_OUTER_LOOP [3,4,6,1] {0:3}
SNS Duplicate 1 [3,4,6,1,1] {0:3}
SSSTN Push 1 [3,4,6,1,1,1] {0:3}
TSST Subtract (1-1) [3,4,6,1,0] {0:3}
NTSSN If 0: Jump to Label_PRINT [3,4,6,1] {0:3}
NSSSSN Create Label_PRINT [3,4,6,1] {0:3}
SNN Discard top [3,4,6] {0:3}
TNST Print top (6) to STDOUT as int [3,4] {0:3} 6
error
```
Program stops with an error: No exit found. (Although I could add three trailing newlines `NNN` to get rid of that error.)
[Answer]
# Java 8, ~~76~~ 65 bytes
```
n->{int r=n,b=n,N;for(;b>1;b--)for(N=n;N>0;N/=b)r+=N%b;return r;}
```
-11 bytes thanks to *@OlivierGrégoire*.
[Try it online.](https://tio.run/##fZG9boMwFIX3PMUVUiUsFxpCQqq6Zu9QLxnbDjYhkVNyiYyJVEU8O7VpBEvF4J9z/Pnca/kkrzI67b/7opJNA@9S420BoNGW5iCLEoSXgwFF@ObsY2kACXNut3BTY6XVBQhA4NBjlN88ajg@KjcEO9QmZCpPmIoi4oXgyES@ZOKJK2IoFw@KmdK2BsGwrmc@9NKqyoXes6@13sPZdRburNF4/PgCSf7a8oG@nuYJA/3Kk6VbKCXDIcDup7HlOa5bG1/cTVthqGnw8mkDinERajK8418uSLORS7NZcDuB2zkwW49gtp4FNxO4mQNXq6m228@hSfqcjqwX5P6HXf8L)
**Explanation:**
```
n->{ // Method with integer as both parameter and return-type
int r=n, // Result-sum, starting at the input to account for Base-1
b=n, // Base, starting at the input
N; // Temp integer
for(;b>1 // Loop the Base `b` in the range [n, 1):
;b--) // After every iteration: Go to the next Base (downwards)
for(N=n; // Set `N` to the input `n`
N>0; // Loop as long as `N` isn't 0 yet:
N/=b) // After every iteration: Divide `N` by the Base `b`
r+=N%b; // Increase the result `r` by `N` modulo the Base `b`
return r;} // Return the result-sum `r`
```
[Answer]
**SAS, ~~81~~ 74 bytes**
```
data;input n;s=n;do b=2to n;do i=0to n;s+mod(int(n/b**i),b);end;end;cards;
```
Input is entered after the `cards;` statement, on newlines, like so:
```
data;input n;s=n;do b=2to n;do i=0to n;s+mod(int(n/b**i),b);end;end;cards;
1
2
3
4
5
6
7
8
9
10
36
37
64
65
```
Outputs a dataset containing the answer `s` (along with helper variables), with a row for each input value
[](https://i.stack.imgur.com/ouycx.png)
Ungolfed:
```
data; /* Implicit dataset creation */
input n; /* Read a line of input */
s=n; /* Sum = n to start with (the sum of base 1 digits of n is equal to n) */
do b=2to n; /* For base = 2 to n */
do i=0to n; /* For each place in the output base (output base must always have less than or equal to n digits) */
/* Decimal value of current place in the output base = b^i */
/* Remainder = int(b / decimal_value) */
/* Current place digit = mod(remainder, base) */
s+mod(int(n/b**i),b);
end;
end;
cards;
1
2
3
```
[Answer]
# Japt `-x`, 6 bytes
```
ÆìXÄ x
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=xuxYxCB4&input=OAoteA==)
```
õ!ìU c
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=9SHsVSBj&input=OAoteA==)
[Answer]
# [J](http://jsoftware.com/), ~~24~~ 23 bytes
```
+1#.1#.]#.inv"0~2+i.@<:
```
[Try it online!](https://tio.run/##RY7LCsIwEEX3/YpLuyhSDXm0eWFBEFy5cu9KLNaF7lz66zFkcAKZwDncYe4ztaJfMEf02EIi5tkJHC/nUxpUJ/K7dmJ9fVr51cMqDvuYNs399nhDYcaSf4DYFNbMtrBh9oVHZkULUxW0YVloSrgqpiJ8vSmLCFVQQkleCY56WI6YkYzjZp4O2fFvgtFkcrsm/QA "J – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 6 bytes
I really wish that there was something like `M` for `cmap` :(
```
Σ§ṁ`Bḣ
```
[Try it online](https://tio.run/##yygtzv7//9ziQ8sf7mxMcHq4Y/H///9NAQ "Husk – Try It Online") or [test all!](https://tio.run/##AUoAtf9odXNr/21TbytgKyIgLT4gIsivc@KCgXLCtv/Oo8Kn4bmBYELhuKP///8xCjIKMwo0CjUKNgo3CjgKOQoxMAozNgozNwo2NAo2NQ "Husk – Try It Online")
### Explanation
```
Σ§ṁ`Bḣ -- example input: 5
§ -- fork the argument..
ḣ -- | range: [1,2,3,4,5]
`B -- | convert argument to base: (`asBase` 5)
ṁ -- | and concatMap: cmap (`asBase` 5) [1,2,3,4,5]
-- : [1,1,1,1,1,1,0,1,1,2,1,1,1,0]
Σ -- sum: 13
```
## Alternatively, 6 bytes
```
ΣΣṠMBḣ
```
[Try it online](https://tio.run/##ARYA6f9odXNr///Oo86j4bmgTULhuKP///81 "Husk – Try It Online") or [test all!](https://tio.run/##AUoAtf9odXNr/21TbytgKyIgLT4gIsivc@KCgXLCtv/Oo86j4bmgTULhuKP///8xCjIKMwo0CjUKNgo3CjgKOQoxMAozNgozNwo2NAo2NQ "Husk – Try It Online")
### Explanation
```
ΣΣṠMBḣ -- example input: 5
Ṡ -- apply ..
ḣ -- | range: [1,2,3,4,5]
.. to function applied to itself
MB -- | map over left argument of base
-- : [[1,1,1,1,1],[1,0,1],[1,2],[1,1],[1,0]]
Σ -- flatten: [1,1,1,1,1,1,0,1,1,2,1,1,1,0]
Σ -- sum: 13
```
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 5 bytes
```
LвOO+
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f58Imf3/t//@NzQA "05AB1E (legacy) – Try It Online")
Explanation:
```
LвOO+ //Full program
L //push [1 .. input]
в //for each element b, push digits of input converted to base b
O //sum each element
O //sum each sum
+ //add input
```
In 05AB1E (legacy), base 1 of 5 is [0,0,0,0,0], not [1,1,1,1,1]. Therefore after summing the range, add the input to account for the missing base 1.
I am using 05AB1E (legacy) because in current 05AB1E, base 1 of 5 is [1]. In order to account for this, I would either need to decrement the result by 1 or remove the first element of the range, both of which would cost 1 byte.
[Answer]
# Desmos, 127 bytes
$$f\left(n\right)=\sum\_{b=2}^{n+1}\sum\_{i=0}^{n-1}\operatorname{mod}\left(\operatorname{floor}\left(\frac{n}{b^i}\right),b\right)$$
```
f\left(n\right)=\sum_{b=2}^{n+1}\sum_{i=0}^{n-1}\operatorname{mod}\left(\operatorname{floor}\left(\frac{n}{b^i}\right),b\right)
```
[Try it here!](https://www.desmos.com/calculator/nwyhin9y2j) Defines a function \$f\$, called as \$f\left(n\right)\$. Uses the formula given in [Dennis's answer](https://codegolf.stackexchange.com/a/176951/31957).
Here is the resulting graph (point at \$(65, 932)\$):
[](https://i.stack.imgur.com/vmxaL.png?s=256)
## Desmos, 56 bytes
This might not work on all browsers, but it works on mine. Just copy and paste the formula. This is \$f\_2(n)\$ in the above link.
```
f(n)=\sum_{b=2}^{n+1}\sum_{i=0}^{n-1}mod(floor(n/b^i),b)
```
[Answer]
# [Perl 6](http://perl6.org/), ~~45~~ 41 bytes
```
{$^a+sum map {|polymod $a: $_ xx*},2..$a}
```
*-4 bytes thanks to Jo King*
[Try it online!](https://tio.run/##DclLCoAgFAXQrVxCGlRIX4M@LqV4UI4SpQgSc@3W9By7n4eI2iFVmKNnC@XXraHJwr/WHE6bDYwGsBXPk4Wi5pxRiBc5JL/NEl79GRIoc2KafMV5VQY0Ak0P0UJ0Uo7xAw "Perl 6 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 60 bytes
```
function(n){if(n-1)for(i in 2:n)F=F+sum(n%/%i^(0:n)%%i)
n+F}
```
[Try it online!](https://tio.run/##Pci9CoAwDATgvU/RpZAgYqqdRNc@RhchkMEI/kzis9fg4HD3HbdX9lNb@dLllE1B8RYGbSPytoN4Ud@PinnOzXGtoKELUoDsCkHQaZOfCpFo7Imw/MvFlIrFHMzBMVjjR8L6Ag "R – Try It Online")
Fails for `n>143` since `144^144` is larger than a `double` can get. Thanks to [Josh Eller](https://codegolf.stackexchange.com/users/84282/josh-eller) for suggesting replacing `log(n,i)` with simply `n`.
The below will work for `n>143`; not sure at what point it will stop working.
# [R](https://www.r-project.org/), 67 bytes
```
function(n){if(n-1)for(i in 2:n)F=F+sum(n%/%i^(0:log(n,i))%%i)
n+F}
```
[Try it online!](https://tio.run/##BcE7CoAwEAXA3lOkCewSRWMZtM0xBBFWFvQl@ClEPHucOYqYoSlyY7k0gcCvCqHxLOkgNQrTB3AcozvvnWBbqxN1YUsroVZma5UruPiVc855e8gH39XC5Qc "R – Try It Online")
Uses the classic `n%/%i^(0:log(n,i))%%i` method to extract the base-`i` digits for `n` for each base `b>1`, then sums them and accumulates the sum in `F`, which is initialized to `0`, then adding `n` (the base `1` representation of `n`) to `F` and returning the result. For `n=1`, it skips the bases and simply adds `n` to `F`.
[Answer]
# [Python 2](https://docs.python.org/2/), 61 bytes
```
f=lambda n,b=2.:n and n%b+f(n//b,b)+(n//b>1/n==0and f(n,b+1))
```
[Try it online!](https://tio.run/##HcxBCsIwFIThtZ5iNqENeTYm1QqF9CLiIqFGC/paQl14@pi6GBj44Vu@63Nmm3N0L/8OowdTcLbpGZ5HsAgq1qx1oCDV/wxGs3PHrZZCQRkpc5wTGBMjeX7ca0MwRkLh2naE9kLoTmXnW7/fLWniFZWwHxwGiMbGCgJF2rhC/QA "Python 2 – Try It Online")
Though this is longer the [Dennis's solution](https://codegolf.stackexchange.com/a/176951/20260) off which it's based, I find the method too amusing to not share.
The goal is to recurse both on lopping off the last digit `n->n/b` and incrementing the base `b->b+1`, but we want to prevent the base from being increased after one or more digits have been lopped off. This is achieved by make the base `b` a float, so that after the update `n->n//b`, the float `b` infects `n` with its floatness. In this way, whether `n` is a float or not is a bit-flag for whether we've removed any digits from `n`.
We require that the condition `1/n==0` is met to recurse into incrementing `b`, which integers `n` satisfy because floor division is done, but floats fails. (`n=1` also fails but we don't want to recurse on it anyway.) Otherwise, floats work just like integers in the function because we're careful to do floor division `n//b`, and the output is a whole-number float.
[Answer]
# JavaScript (without recursion), 77 bytes
Returns correct value for "any" number. [Try it online](https://tio.run/##HY1BDsIgEEX3PcW4MBlCq@3CFU7vApVqTTsYQF1Az47Et/lv8ZP31B8dJr@8YsfuZkuZCbk1bRA0pu9jWS1ioJAzRjLEQoyDSFGSOQZlCDdCcw65FyJnVvXYHbbd2/j2DFHtRdPQ/1HN7DwyEGgFDNe68lJNSgGpAZgcB7fa0@rutQ8z1pRq9vID)
```
f=(n,b,s)=>{while((s=s||(t=b=n))>1){t+=b%s;b=(m=(b/s|0))||n;s=s-!m}return t;}
```
# JavaScript (with recursion), 54 bytes
Returns correct value for maximum number 3867 ("Maximum call stack size exceeded" is thrown for larger input). [Try it online](https://tio.run/##DYxBCsIwEADvfcV6ELIk0agIYlx9S1IbsbQb6YoX49tjTjMwMGP4BOmX5@ttOd@HWhMpNtEI0lUJSSkqEiPa3S2uRacW1UxxK8VhKWzErmY8xxrocDo636W8KAaC4IHh0qj3rqnWCN8OoM8seRo2U360E7Qdou9@9Q8)
```
f=(n,b,s)=>(s=s||(b=n))-1?b%s+f(n,(m=b/s|0)||n,s-!m):b
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
bRFS
```
[Try it online!](https://tio.run/##y0rNyan8/z8pyC34v6GBQpCCtYKxmY6xuY6ZiY6ZqcKhrQpH9ygcbn/UtEbB/T8A "Jelly – Try It Online")
### How it works
```
bRFS Main link. Argument: n
R Range; yield [1, ..., n].
b Convert n to back k, for each k to the right.
F Flatten the resulting 2D array of digits.
S Take the sum.
```
[Answer]
# JavaScript (ES6), 42 bytes
This version is almost identical to my main answer but relies on arithmetic underflow to stop the recursion. The highest supported value depends on the size of the call stack.
```
f=(n,b=1,x)=>b>n?n:~~x%b+f(n,b+!x,x?x/b:n)
```
[Try it online!](https://tio.run/##FcvRCoJAEEbhe5/i7yJw2K0w6EYbfRbX3ChkRjRiIPLVt@3ucOB79u9@HZbH/DqI3saUIpfiA1feiNvQSif1ttk@uPj/bmfeOjuFWihFXUoBo2oguDLOlxzOET4FMKisOo3HSe8ZImuipvimHw "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), ~~51 48~~ 44 bytes
```
f=(n,b=2,x=n)=>b>n?n:x%b+f(n,b+!x,x?x/b|0:n)
```
[Try it online!](https://tio.run/##ZY9BDoIwFET3ngIXJjSgQAuUkhTOQhGIhvwaMaYL715j/F343b6Xmcxch@ewjffL7XEEe568n3UMqdE8dRqY7kwHPbTuYJL5w5O9S13vMvPKW2B@tLDZdTqtdonnuIgYi7IsKna/nCMXhAvkNeEl8obwKvTTojoI2iRRcJpogqiIUGFrTkSRo6AJUWOVktRIjIiSDi7xYfN3pfoaJbh/Aw "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f = recursive function taking:
n, // - n = input
b = 2, // - b = current base, initialized to 2
x = n // - x = current value being converted in base b
) => //
b > n ? // if b is greater than n:
n // stop recursion and return n, which is the sum of the digits of n
// once converted to unary
: // else:
x % b + // add x modulo b to the final result
f( // and add the result of a recursive call:
n, // pass n unchanged
b + !x, // increment b if x = 0
x ? // if x is not equal to 0:
x / b | 0 // update x to floor(x / b)
: // else:
n // reset x to n
) // end of recursive call
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 22 bytes
```
{1⊥⍵,∊(1+⍳⍵-1)⊥⍣¯1¨⊂⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v9rwUdfSR71bdR51dGkYaj/q3Qzk6BpqgkUXH1pveGjFo64moFjt/7RHbRMe9fY96pvq6f@oq/nQeuNHbROBvOAgZyAZ4uEZ/P9R76q0Qys0gKYYGmjqGJspGJsrmJkomJkCAA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 30 bytes
```
n->n+sum(b=2,n,sumdigits(n,b))
```
[Try it online!](https://tio.run/##DYrBCoAgEAV/Zem00grlXf8lCWUPvUTt@20vwzBMu7r62lahuOAT9vE9nGMQiNmtVedgSHZulbczKNIpFA6h1hXTwkY@GQrD2fQD "Pari/GP – Try It Online")
[Answer]
# C (gcc), ~~67~~ 56 bytes
```
b,a,s;e(n){for(b=a=n;a>1;a--)for(s=n;s;s/=a)b+=s%a;n=b;}
```
Port of [my Java 8 answer](https://codegolf.stackexchange.com/a/176982/52210).
-11 bytes thanks to *@OlivierGrégoire*'s golf on my Java answer.
[Try it online.](https://tio.run/##NY3NDoIwEITvfYrGhKQNJVpQNK7rk3DZ8mN6sBLKjfDstVU4zbczk522eLVtCEaR8tALJ5fhMwmDhA7oqYGKQibHx9uDPyJJk6PPCBwaWMObrBNyYZynlnUzt6iB2wfqU5Q8lzHifBRWAkta1TtcN6jPO1w2KMs909WtirgyNv6f/6bGKfIgDll3b@asa9xBWdXHiVQNXw)
**Explanation:**
```
b, // Result integer
a, // Base integer
s; // Temp integer
e(n){ // Method with integer as parameter
for(b=a=n; // Set the result `b` to input `n` to account for Base-1
// And set Base `a` to input `n` as well
a>1 // Loop the Base `a` in the range [input, 1):
;a--) // After every iteration: Go to the next Base (downwards)
for(s=n; // Set `s` to input `n`
s; // Inner loop as long as `s` is not 0 yet:
s/=a) // After every iteration: Divide `s` by Base `a`
b+=s%a; // Add `s` modulo Base `a` to the result `b`
n=b;} // Set input `n` to result `b` to 'return it'
```
[Answer]
# [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 71 bytes
```
(load library
(d S(q((N)(sum(map sum(map* to-base(1to N)(repeat-val N N
```
[Try it online!](https://tio.run/##LctBDsIgEIXhfU8xy1eTJmIV9RJseoJpyoKECgKa9PRIBjffLN78xb0O73KsFT7wRt6tidMxYKMFb8CMyJ8dO0f63xOVMK2cLVQJ1PZko@UyfdmTIVOxkBqH5kWcxat4E7V4Fx/iU1TnHvR97g@6l7ql9Qc "tinylisp – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 7 bytes
```
+ssjLQS
```
[Test suite](http://pythtemp.herokuapp.com/?code=%2BssjLQS&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A36%0A37%0A64%0A65&debug=0)
##### Explanation:
```
+ssjLQS | Full program
+ssjLQSQQ | with implicit variables filled
----------+--------------------------------------------------
L SQ | Map over each d in [1..input]:
j Q | input to base d as a list (unary is a list of 0)
ss | Sum of sums
+ Q | Add input (to account for unary)
```
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/Attache), 25 bytes
```
{Sum!`'^^ToBase[_,2:_]'_}
```
[Try it online!](https://tio.run/##SywpSUzOSP2fpmBl@786uDRXMUE9Li4k3ymxODU6XsfIKj5WPb72v19qakpxtEpBQXJ6LFdAUWZeSUhqcYkzUFFxdJqOgqGVoYG6sZm6sbm6mYm6mWnsfwA "Attache – Try It Online")
## Explanation
```
{Sum!`'^^ToBase[_,2:_]'_}
{ } anonymous lambda, input: _
example: 5
ToBase[_, ] convert `_`
2:_ ...to each base from 2 to `_`
example: [[1, 0, 1], [1, 2], [1, 1], [1, 0]]
'_ append `_`
example: [[1, 0, 1], [1, 2], [1, 1], [1, 0], 5]
^^ fold...
`' the append operator over the list
example: [1, 0, 1, 1, 2, 1, 1, 1, 0, 5]
Sum! take the sum
example: 13
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes
```
IΣEIθΣ↨Iθ⁺²ι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI7g0V8M3sQDCKdTUUQAJOCUWpyJEAnJKizWMdBQyNcHA@v9/0/@6ZTkA "Charcoal – Try It Online") Link is to verbose version of code. Charcoal can't convert to base 1, but fortunately the digit sum is the same as the conversion to base \$n + 1\$. Explanation:
```
θ First input
I Cast to integer
E Map over implicit range
θ First input
I Cast to integer
↨ Converted to base
ι Current index
⁺ Plus
² Literal 2
Σ Sum
Σ Grand total
I Cast to string
Implicitly print
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 49 bytes
```
.+
$*
1
11$`;$_¶
+`\b(1+);(\1)+
$1;$#2$*1,
1+;
1
```
[Try it online!](https://tio.run/##DcmxDYMwFEXR/q6Rj2QwivIwmEQegCWQ4iBRpKFAzMYALObktGdfj@/2KZWbcrl7rEFIlpO9rxOf58XJ18nNqv@rZLfOGrXIJ1ApoiPQMxAZefJCD0IkjMSeOPwA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
.+
$*
```
Convert to unary.
```
1
11$`;$_¶
```
List all the numbers from 2 to \$n + 1\$ (since that's easier than base 1 conversion).
```
+`\b(1+);(\1)+
$1;$#2$*1,
```
Use repeated divmod to convert the original number to each base.
```
1+;
```
Delete the list of bases, leaving just the base conversion digits.
```
1
```
Take the sum and convert to decimal.
[Answer]
# Desmos, 51 bytes
Inspired by [Conor O'Brien's answer](https://codegolf.stackexchange.com/a/176976/16293) and looking at the OEIS-entry I came up with my own Desmos-solution:
```
h(n)=n^2-\sum_{p=2}^n(p-1)\sum_{k=1}^n floor(n/p^k)
```
[Try it online!](https://www.desmos.com/calculator/zyakvkc5d7)
[Answer]
# APL(NARS), 29 chars, 58 bytes
```
{+/+/¨⍵{(⍺⍴⍨⌊1+⍺⍟⍵)⊤⍵}⍨¨1+⍳⍵}
```
little test on how to use:
```
h←{+/+/¨⍵{(⍺⍴⍨⌊1+⍺⍟⍵)⊤⍵}⍨¨1+⍳⍵}
h¨1 2 4 10 36 37 64 65
1 3 8 35 297 334 883 932
```
] |
[Question]
[
Given a positive integer \$n\$ output an ASCII hexagon with diagonal side length \$n\$, as pictured (note there are \$2n\$ `_` characters on the top edge)
### Examples:
\$n = 1\$
```
__
/ \
\__/
```
\$n = 2\$
```
____
/ \
/ \
\ /
\____/
```
\$n = 5\$
```
__________
/ \
/ \
/ \
/ \
/ \
\ /
\ /
\ /
\ /
\__________/
```
etc.
Shortest code in bytes wins.
[Usual input/output methods](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) apply.
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), ~~15~~ 9 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
_;1*⁸/∔╬
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JTIwXyV1RkYxQiV1RkYxMSV1RkYwQSV1MjA3OCV1RkYwRiV1MjIxNCV1MjU2Qw__,i=NQ__,v=8), [another 9 bytes](https://dzaima.github.io/Canvas/?u=XyVENyUyMCV1MjA3OCV1RkYzQyV1MjIxNCV1RkYwQiV1MjE5NCV1MjU2Qw__,i=NQ__,v=8)
-6 bytes after fixing the program.
Draws a quarter of the hexagon, and quad palindromizes.
[Answer]
# [Python 2](https://docs.python.org/2/), 92 bytes
```
k=n=input()
while 1:a=k^k>>n;print" "*a+"\/_"[k/n-2]+"_ "[-n<k<n]*2*(2*n+~a)+"\_/"[k/n];k-=1
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9s2zzYzr6C0REOTqzwjMydVwdAq0TY7LtvOLs@6oCgzr0RJQUkrUVspRj9eKTpbP0/XKFZbKV5BKVo3zybbJi9Wy0hLw0grT7suUROoKF4frCjWOlvX1vD/f1MA "Python 2 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~119~~ 109 bytes
```
a,i,j;f(n){for(i=a+=a=j=n*2;~j;)putchar(!i--?i=a,j--,13:i%(n*3)<n|j%(n*2)?(i-~j-n)%a?(i-j+n)%a?32:92:47:95);}
```
[Try it online!](https://tio.run/##JczRCoIwGIbhc69iEcJ@3QKnEW4ur2WszH/UDNMj01tfmkfPCx98lj@sDcEwZE411MPUdD1FbVJttNM@EWpxCt7jYFvT0wNyXq8rc5yzLJcYU5/kUPmv20pATZEvjnuIzZYu/VcuZClkcZHlGdQcjujtc7zdSfUZbtid2muEfiAvg54CmSLS0AzUhtjJd4qd9SOaww8 "C (gcc) – Try It Online")
* saved 2 thanks to @ceilingcat
The table below is not updated so values can differ, but the concept is:
* we have 2 pairs of parallel lines
```
. .
_______.______.________
| / \ | .
. | / \ | .
.| / \ |.
|/ \|
|\ /|.
.| \ / | .
. | \ / |
__|___\________/___|___
| . .
```
we iterate x,y from size to 0 and we sum them to check if a / should be printed, we subtract to check for \ , we use modulo to check both parallels.
```
i 65432109876543210. j
i+j-n ________ 8
13+7-4=> / \ 7
14+6-4 / \ 6
15+5-4 / \ 5
/ \ 4
\ 1+3-4=> / 3
\ 2+2-4 / 2
\ 3+1-4 / 1
\________/ 0
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes
```
←×_θ↖θ→↗θ×_θ‖M
```
[Try it online!](https://tio.run/##S85ILErOT8z5//9R24TD0@PP7XjUNg1ETHrUNv3cDohIw7T3e9b@/x9taBD7XzcRAA "Charcoal – Try It Online")
+1 byte fix from ASCII-Only.
Draws half of the hexagon, and mirrors it.
[Answer]
# [Haskell](https://www.haskell.org/), 100 bytes
```
f n=unlines[q<$>[1..3*n]++[1-n..0]|y<-[-n..n],let q x|abs y==n,x>n='_'|x==y='\\'|x+y==1='/'|1>0=' ']
```
[Try it online!](https://tio.run/##FY1BCsMgEAC/sofCQk1spNBT1h/01KORYMHSULMk1UAC/t3a28DAzNvFjw@hlBcwbRwm9tGs/UkbJeX1zFYIo1qWsrP56FvzR7ZN8AlW2LN7RjiIuNk1E46Yd6KDcBgqiSoU4QWz0h0hoC2zm5hmt9xHWLb0SF8w9Zu5huvuZm35AQ "Haskell – Try It Online")
Golfing [AZTECCO's answer](https://codegolf.stackexchange.com/a/217486/20260) plus some new techniques.
The main idea is that the hexagon is simpler if we transplant the first `n` columns to the end.
```
|-|
______
/ \
/ \
/ \
\ /
\ /
\______/
|-|
______
\ /
\ /
\/
/\
/ \
______/ \
```
Now all the `/` and `\` are in a single line, and the `_` are all to the left of those. This makes it much easier to do AZTECCO's strategy of determining the character from the coordinate. To implement these relabeled coordinates, we replace the `x`-coordinates `[1..4*n]` with a cycled and shifted version `[1..3*n]++[1-n..0]`.
[Answer]
# [Perl 5](https://www.perl.org/) (`-p`), 102 bytes
```
s/_+/__$&/g,s/^|$/ /gm,s/^ *\S /$& /gm,s-( +)\\
-$&/ $1 \\
\\ $1 /
- for($\=' __
/ \
\__/')x--$_}{
```
[Try it online!](https://tio.run/##JYy9CsJAEIT7e4ohLPkxrmuEVJJHsLJdXCxMCKgJOQsl5tU9T@y@mW@Y8TJd69C3OWkx@/OLdE/aJMkSvFgpZpRKt/ZyepNAutsPsdIjhFL8C85RFqpwHLegCqouxgjiGO0wxe8mgxmcANGZSVY8mcmWOYTK7Vz9GcZHP9x94DHwod5sqy8 "Perl 5 – Try It Online")
`-p` and `}{` at the end is a trick to only print the output record separator `$\` at the end. It only works for one input record; the header is used to print all in one tio link.
```
$\=' __
/ \
\__/' # output record separator initialized with hexagon (size 1)
s/_+/__$&/g,s/^|$/ /gm,s/^ *\S /$& /gm,s-( +)\\
-$&/ $1 \\
\\ $1 /
- # regexes to increase the hexagon by 1
for .. --$_ # to repeat n-1 times where n is the input
```
[Answer]
# [Haskell](https://www.haskell.org/), 150 bytes
```
r=reverse
m(o:c:k)=o:c:c:c:k++" "
f 1=[["\\ /","__ "],["/__\\"]]
f n|[w:i,j]<-map m<$>f(n-1),_:_:k<-r$m w=[r k:w:i,k:j]
h[i,j]=unlines$r<$>r i++j
h.f
```
[Try it online!](https://tio.run/##FYuxDoMgFEV3vuKFMNiANSadiPQnOgIhpkFFhBrUuvTfqeQMdzj3TP3m7bLknESyX5s2i0L14W/ub6JMwVOKAaMBWiElVgqgwQwbA1gziRtjlMJaXz7@5Mkdm3VXh36F0JHnUMW6vTHDDfddnUiAU8gEnpej57NGkyyFOOLiot1IuqIEjtIZjWK6Dzn0Lor12F97IiM88h8 "Haskell – Try It Online")
A more recursive version of this answer. The arbitrariness of this challenge makes this pretty frustrating.
## Explanation
This answer is a bit hard to explain. The challenge is, as I already said, arbitrary in a few ways, so the code is sort of just a nest of symbols.
### Idea
The idea of the program here is to build up the two halves. That is when calculating the nth hexagon we get the two halves for the n-1th hexagon and use that to make the next biggest one.
There are some caveats though. We build the top half up-side-down and we build both halves mirrored left to right. We do this because it is convenient to do it this way. No deep reason it just makes things shorter even if it does make things a little incomprehensible.
### Details
The first line is pretty straight forward `r` is an alias for `reverse`. The second line is not so straight forward. `m` is a nonsense function, it exists because it or a similar operation needs to be done in a few places. It doesn't really have a semantic meaning. The best explanation of what it does here is the code.
```
m(o:c:k)=o:c:c:c:k++" "
```
From here we start getting to `f` which handles basically all of the logic. The first case for `f` is the base case, it is pretty standard
```
f 1=[["\\ /","__ "],["/__\\"]]
```
Note that we return a list of two items instead of a tuple. In any sane program we would be using a tuple since it is fixed at 2 elements. However later we will map over both arguments of this with the same function. It is hard to do that with a tuple but easy with a list, and the list doesn't pose any drawbacks so we use it.
Then we have the inductive case. First we fetch the previous case, and double map our `m` over it. This makes the hexagon 1 unit wider (2 characters) and moves it half a unit (1 character) to the right (although since this whole thing is backwards the space characters are added on the *right*). We pattern match this to `[w:i,j]` because we want to use `w` to make new rows later. Speaking of which next we make the rows. We do this with a pattern match:
```
_:_:k<-r$m w
```
This is sort of nonsense code. It just slaps together things we already had to produce the correct output. `k` and its reverse form the new rows so we add them in. and return that.
After `f` we have `h` which turns the output of `f` into a string. It undoes all the wacky transforms we used during the construction and packages it up to be used.
With all that we just compose `f` and `h` for the final function.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 94 bytes
```
.+
$* ¶$&$*
\G
¶$%'/$`$%_$%_$`\
r` \G
$%`\$'$%_$%_$%'/¶
^¶( *)
$1 $.&$*_$.&$*_$&
T` `\_` +/$
```
[Try it online!](https://tio.run/##LYw9CoAwFIP3nOINqb@gKHiGXsDxYZ@Dg4uDeLYeoBerFYSQfISQ@3jOa8@u8ZaHHuwkRVYloF5Q2NUjjS58MsVtoh50pqz/tixSxJZiI10LTsKhHITfK6wmpsGkH5nzhBnLCw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
.+
$* ¶$&$*
```
Insert two rows of `n` spaces.
```
\G
¶$%'/$`$%_$%_$`\
```
Convert the first row into the top sides of the hexagon.
```
r` \G
$%`\$'$%_$%_$%'/¶
```
Convert the second row into the bottom sides of the hexagon.
```
^¶( *)
$1 $.&$*_$.&$*_$&
```
Insert the top line.
```
T` `\_` +/$
```
Replace the bottom line.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~119~~ 114 bytes
```
i=n=input()
d=0
exec"k=i/n|d;print' '*i+'\_/'[~k]+'_ '[i-d<n]*2*(2*n+~i)+'\_/'[k]\nif i==d:d=i=-1\ni-=d|1;"*(n-~n)
```
[Try it online!](https://tio.run/##LcpLCsIwEADQfU8Rupl8CDVZWuckbejCqTgExiARFEquHl24fPDKp94fEntnFGQpr6rNQHga9vd@HTPyJAfN5clSQYFlB@s2wdJycrApWNjTRZKNVkcrrrH5h5xW4ZtiRDoTMvrws0c6wjxaLb6J6T18AQ "Python 2 – Try It Online")
[Answer]
# JavaScript (ES6), ~~109~~ 107 bytes
```
w=>(x=0,W=w*4,i=g=y=>~y?`
/\\_`[x++-W?y*!i|w/x|x>w*3?(x+~y+w)%W?(x+y)%W-w?1:3:2:4:x=i=0&y--]+g(y):'')(w*2)
```
[Try it online!](https://tio.run/##Zci9DoIwFEDhnafQQeltqciPS5NLH4NBjBAEgiHUiLFtQnj1qqNhOiffvXpXU/3sHy8@qlvjWnQaM2LwGOSoaRr02KHFbLGy9DZhUVzLs2GM59LSbT/r0Mwm0zSRxLDFMg27/Lf2W65lJBIRi1QY7PG4t5xfWEcsCN8HomkMrlbjpIbmMKiOtCQC8P4lXkmykhOA@wA "JavaScript (Node.js) – Try It Online")
### Commented
```
w => ( // w = input
x = 0, // initialize x to 0
W = w * 4, // W = total width
i = // initialize i to a non-zero value
g = y => // g is a recursive function taking y
~y ? // if y is not equal to -1:
`\n /\\_`[ // list of characters
x++ - W ? // if this is not the end of the row:
y * !i | // if this is neither the first nor the last row
w / x | // or x is less than or equal to w
x > w * 3 ? // or x is greater than w * 3:
(x + ~y + w) % W ? // if (x - y - 1 + w) mod W is not equal to 0:
(x + y) % W - w ? // if (x + y) mod W is not equal to w:
1 // draw a space
: // else:
3 // draw a '\'
: // else:
2 // draw a '/'
: // else:
4 // draw a '_'
: // else:
x = i = 0 & y-- // decrement y, set x and i to 0 and draw a linefeed
] + g(y) // append the result of a recursive call
: // else:
'' // stop the recursion
)(w * 2) // initial call to g with y = w * 2
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~194~~ \$\cdots\$ ~~149~~ 144 bytes
Saved ~~13~~ ~~14~~ 19 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
```
p(n,c){for(;n--;)printf(L"/\\ _\n"+c);}i;t;f(n){p(n,2);for(i=t=p(2*n,3);i>=p(1,4);t=i/n?--i,1:t)i+=!p(!p(n+i<<!p(!p(n+~i,2),t),t&!i|2),!t)-2*t;}
```
[Try it online!](https://tio.run/##NY5BCsJADEX3PUXahUw6M5RW3ZiOXsAjFEQGKlkYS5ldrVevacXwIT/hkZ/oHzEuy2DERZz612hIvCccRpbUm2tRdR3cOilsRJqZEvVGcFr5BmnlOaQwmKYUt0fis/raHZBS4Eou3rOrTwnZhnwwKrHctn/7YT3ikmqX81ttntA3ZaJ50XR43lkMZlMGWhoFZt0KBKhJWxvgSGCtIPyQDdPvaJvmbF6@ "C (gcc) – Try It Online")
### Explanation (before some golfs)
```
p(n,c){for(;n--;) // Helper function to print
putchar("/\\ _\n"[c]);} // one of '/', '\', ' ', '_' , or
// newline n times, this function
// also returns 0
i;t;f(n){ // Main function prints an n hexagon
p(n,2); // Print n leading spaces for the 1st
// line
for( // Main loop
i=t=p(2*n,3); // Set i and t to 0,
// and print 2*n '_'s for the 1st line
i>=p(1,4); // Loop until i goes below 0, and
// print a newline
// At the end of each loop:
i+=1-2*t, // increment i for the 1st half
// and then decrement i in the 2nd
t=i/n?--i,1:t) // keep t as t unless i equals n,
// then make t 1 and decrement i
// In the main loop:
p(n+~i,2), // print n-i-1 leading spaces
p(1,t), // print a '/' in the 1st half and a
// '\' in the 2nd
p(n+i<<1,t&!i|2), // print the 2*(n+i) middle spaces
// unless at the bottom print '_'s
p(1,!t); // print a '\' in the 1st half and a
// '/' in the 2nd
}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~33~~ ~~29~~ 25 bytes
-4 ([7](https://codegolf.stackexchange.com/questions/217366/draw-an-ascii-hexagon-of-side-length-n/217393?noredirect=1#comment507103_217393)) bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)!
```
L+<'/úíºI·'_ך»∊¶¡`ðs‡).c
```
[Try it online!](https://tio.run/##ATIAzf9vc2FiaWX//0wrPCcvw7rDrcK6ScK3J1/Dl8WhwrviiIrCtsKhYMOwc@KAoSkuY///NQ "05AB1E – Try It Online")
*05AB1E* has a canvas builtin which might be useful, but is quite tricky to get working, this is just the mirror builtins `º` and `∊` and the centralize builtin `.c`.
[Answer]
# [J](http://jsoftware.com/), 50 47 bytes
*-3 thanks to Jonah!*
```
' \/_'{~]|."1((0,]+2*|.)@=@i.,.3,3,~0$~<:,])@+:
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/1RVi9OPVq@tia/SUDDU0DHRitY20avQ0HWwdMvV09Ix1jHXqDFTqbKx0YjUdtK3@a3KlJmfkK6QpGEIY6uowASN0AdP/AA "J – Try It Online")
```
((0,]+2*|.)@=@i. ,. 3,3,~0$~<:,])@+:
0 0 0 0 3 3 3 3
1 0 0 2 0 0 0 0
0 1 2 0 0 0 0 0
0 2 1 0 0 0 0 0
2 0 0 1 3 3 3 3
]|."1
0 0 3 3 3 3 0 0
0 2 0 0 0 0 1 0
2 0 0 0 0 0 0 1
1 0 0 0 0 0 0 2
0 1 3 3 3 3 2 0
' \/_'{~
____
/ \
/ \
\ /
\____/
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 174 bytes
```
n=int(input())
b,a,s="\/ "
z,f=range(n),lambda c,d,t:((n-1-i)*s+c+2*(n+i)*s+d for i in t)
print(f"{'_'*2*n:^{4*n}}",*f(a,b,z),*f(b,a,z[:0:-1]),f"{b:>{n}}{'_'*2*n}/",sep="\n")
```
[Try it online!](https://tio.run/##NY5LDoIwFEXnrKLphLY8gqAmpgluxF9aoNpEH02pAyGsvYKJszM49@M@4dHj9uB8jFhbDMyiewfGeaJBwVDTc0FoMoKpvcJ7x5DDU710q0gDLQTJGOZlbrkYsiarBMPsxy0xvSeWWCSBJ86vzYZO6S0VlUB5nXYC55mCMEyBhpGvtC6OJ7mReXnhsOhaHqdF@8fmgsLQueUTUh7j/gs "Python 3.8 (pre-release) – Try It Online")
-1 byte thanks to @Duncan
-8 bytes thanks to @Danis
[Answer]
# [Haskell](https://www.haskell.org/), ~~129~~ 120 bytes
```
g=mod
f n|a<-n*4=[c|y<-[-n..n],x<-[0..a],let c|x<1='\n'|g x(n*3+1)>n,abs y==n='_'|g(x+y)a==1='/'|g(x-y)a<1='\\'|1>0=' ']
```
[Try it online!](https://tio.run/##HY7NDoIwEITvPsXeyl8rjcYTyxt48ggNWRHRCCsRTErSd6@V23yZmcw8aH51w@B9j@P7trsDOyokJ0esWrcWspKsFJvMBpkrRSYbugVaZwuNombherARJ4dUxyVndJ1hRWQUTXAim64xIYbkfkMZcOvVwukyRwHC@JGejCNN5wam73JZPlD9X3AY1EqdjPE/ "Haskell – Try It Online")
* saved 9 thanks to @Wheat Wizard and @xnor.
* Check @xnor answer and its big improvement on the approach to the problem (avoiding modulo and parallel lines) !
* Equivalent of my C answer
We make cartesian coordinates using list comprehension |y<-[0..n\*2],x<-[0..a]
[c| ... ,let c| ... | ... | ... ] and we yeld the character needed based on x-y or x+y to draw lines..
We use modulo to draw multiple lines(2)
Special case is for `_` which doesn't need a x/y ratio but a range, we used modulo to do just one comparison `>` instead of an a>x>b like
[Answer]
# [SlimSharp](https://github.com/jcoehoorn/SlimSharp/), 150 bytes
```
I n=RI(),m=n;S b=new S('-',n*2).Pad(n*-3),l="/",r="\\";Action<I> x=a=>P(l.Pad(-a).Pad(4*n-a)+r);P(b);for(;m>0;)x(m--);l=r;r="/";for(;m<n;)x(++m);P(b);
```
>
> <https://dotnetfiddle.net/iXLzcO>
>
>
>
The fiddle differs slightly from the post because .Net Fiddle can't use the RI() function to read from the console.
This is still the naiive version, without any recursive or coordinate mapping tricks. I'm unlikely to get shorter, because SlimSharp hasn't defined shortcuts for some of the relevant array and string functions yet.
---
# C#, 227 bytes
The full C# looks like this, and that's still assuming all the necessary `using` directives and that we get to abstract to a method.
```
void H(int n){int m=n;string b=new string('-',n*2).PadLeft(n*3),l="/",r="\\";Action<int> x=a=>Console.WriteLine(l.PadLeft(a).PadRight(4*n-a)+r);Console.WriteLine(b);for(;m>0;)x(m--);l=r;r="/";for(;m<n;)x(++m);Console.Write(b);}
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 141 bytes
```
->(n,g=->c,d{(1..n).map{|i|" "*(n-i)+d+" "*2*(n+i-1)+c}},l=g[?/,e=?\\].reverse){[" "*n+?_*n*2,g[e,?/],l[0..-2],l[-1].sub(/ +(?=\/)/,?_*n*2)]}
```
[Try it online!](https://tio.run/##PcrRCoMgFIDh@z1FdKV5PE5hl@aDmIxVFkGTsDUY1bO7xcbuvh/@uNSv1OnESxKg17xsoF2JRAwU77dp3YYtz/KCBD5Q1rLD6lNs4JKyZt9h1L01Arw2VeUw@qePs6erPc7AzLUIhYLeejDCwWjPiFwd4NLhvNREZIwYXQkq4DtTt6dpecxZZ6U7/aT@urj0Bg "Ruby – Try It Online")
If an upper underscore is allowed, then it would take a bit lesser bytes, while the hexagon is as pretty as it was earlier ;-)
# [Ruby](https://www.ruby-lang.org/), 114 bytes
```
->n{[" "*n+?_*2*n,(g=->c,d{(1..n).map{|i|" "*(n-i)+c+" "*2*(n+i-1)+d}})[?/,e=?\\],g[e,?/].reverse," "*n+?‾*n*2]}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOlpJQUkrT9s@XstIK09HI91W1y5ZJ6Vaw1BPL09TLzexoLomswakRiNPN1NTO1kbxDYC8rQzdQ01tVNqazWj7fV1Um3tY2JiddKjU3Xs9WP1ilLLUouKU3Wghj9q2KeVp2UUW/u/oLSkWCEt2jCWC8oygrNMY/8DAA "Ruby – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 70 bytes
```
ðש'_¹·×«©¶«©¹'/1Λ¹·Ì'.2Λ¹'\3.Λ«©„./`.;©¶¡Â‚€»`s'.ð:,¹3*>(£„._`:„/\‡,
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8IbD0w@tVI8/tPPQdiBr9aGVh7aByZ3q@obnZoOFe9T1jEBM9RhjPSANlH3UME9PP0HPGqx64eGmRw2zHjWtObQ7oVhd7/AGK51DO4217DQOLQapi0@wAlL6MSBVC3X@/zcFAA "05AB1E – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 143 bytes
```
sub f{$n=pop;@b=map{join'',$"x($n-$_),'/',' 'x($n+$_-1),'\\',$/}1..$n;join('',$"x$n,$u=__ x$n,$/,@b,map y|/\\|\\/|r,reverse@b)=~s| +/$|$u/|sr}
```
[Try it online!](https://tio.run/##bZBNasMwEIX3OsUQBmQTJcIt2cRR8QW66y4qoga5pDSykeKSEKdXd/UT2jqtNpr53nuSRp2276uxdxqetDus14@t1XDwpRMP9yXZn6AKncjItmCbDaXPjIBShANIIpXihGzvvgWveA28GOS4RV8qOAEZDCGz@slAiqUV@2swhad9IhMQ0Q35df0Uyr8wPOsfdgsDmrJI0khp@cECyUvStDaLH5efI9qfMtyZjqE@drmoUJVXDPjaHkQT1TzBncsCjF42C8SIIEsT8My7LqPra2jOaETXdmVVi/1Ld35rd4ZShrNjhmaBKmeUU0YBaABzVIvCIym9hV@K5RJNGSJZyqBh2AulIFacVTXzh8Jp4FIOUvLBMqs/tHW6qnPx6QaYcxyw54Ozl3EsvgA "Perl 5 – Try It Online")
```
sub f{
$n=pop; #n = input
@b=map{ #set array @b to line 2 - n+1
join'', #join parts into a line string
$" x ($n-$_), #space times n-1
'/', #char /
' ' x ($n+$_-1), #space times n+iterator minus 1
'\\', #char \
$/ #char newline
} 1..$n; #n lines
join('', #return string of these joined:
$" x $n, #n spaces
$u = __ x$n, #n*2 underscores
$/, #char newline
@b, #lines 2 to n+1 constructed above
map y|/\\|\\/|r, #and bottom part which is the same
reverse@b #as top part reversed and /\ rotated
)=~s| +/$|$u/|sr #and change last spaces of last line to _'s
}
```
[Answer]
# [Haskell](https://www.haskell.org/), 186 168 bytes
-18 bytes with xnor's fixes and removing unneeded spaces on the last line
```
s=' '
(!)=replicate
e=reverse
h n=unlines$(\m->(n!s++(2*n)!'_'++n!s):e(e<$>m)++init m++[(n-1)!s++'\\':(2*n)!'_'++"/"])$(\i->i!s++'\\':(4*n-2*i-2)!s++'/':i!s)<$>[0..n-1]
```
[Try it online!](https://tio.run/##TY7RCoJAEEXf9yvGCHbXZU2lXiT9EY1YbMAhdwjXor@3tYJ6O8O99zCDC1ccx2UJtQQpVKLrCW8j9W5GgZEfOAUUA3B955EYw1Z13jaKk2CMKlPWiTxLY@KtK1R43DZeG0NMM3hjWsW20GtXdp2s/gab3eako4xsQ798n7ItU7LlZ7OTVQx1lLZ5lkXVaRnwCTUMwjviCMQzTq6fQX3/gwy8u8Fa@9CE7hLxHeqlEKU4iCJ/AQ "Haskell – Try It Online")
Ungolfed:
```
hex :: Int -> String
hex n = unlines $ first: middle ++ (init $ reverse (map reverse middle)) ++ [last]
where
first = replicate n ' ' ++ replicate (2*n) '_' ++ replicate n ' '
f i = replicate i ' ' ++ "/" ++ replicate (n-i + 2*n + n-i -2) ' ' ++ "\\" ++ replicate i ' '
middle = map f [n-1,n-2..0]
last = replicate (n-1) ' ' ++ "\\" ++ replicate (2*n) '_' ++ "/" ++ replicate (n-2) ' '
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 60 bytes
```
ð*\_?*d+,(n-‹ð*\/n?+ð*d++\\+,)(nð*\\?d‹n-n›?=[\_|ð]*d++\/+,)
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C3%B0*%5C_%3F*d%2B%2C%28n-%E2%80%B9%C3%B0*%5C%2Fn%3F%2B%C3%B0*d%2B%2B%5C%5C%2B%2C%29%28n%C3%B0*%5C%5C%3Fd%E2%80%B9n-n%E2%80%BA%3F%3D%5B%5C_%7C%C3%B0%5D*d%2B%2B%5C%2F%2B%2C%29&inputs=3&header=&footer=)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 177 bytes
```
n=>[...Array((N=2*n)+1)].map((_,i,a,g=i>n,s=g?i-n-1:n-i,j=i&&N-i,r='_'.repeat(N),S=Z=>' '.repeat(Z))=>i?S(s)+'/\\'[+g]+(j?'':r)+S(g?j&&6*n-2*i:N+2*--i)+'\\/'[+g]:S(n)+r).join`
`
```
[Try it online!](https://tio.run/##PY67asNAEAB7f4Ur3a7uYSRwCsFK5AfUqLNl7MORjz2cPXEygXy9LFKkG4YpJvofv9wzzy8r6WtaH7QKtWfn3GfO/hegp7oU1BVe3LefAa6GjTeBuBWzUOjYiq0asWwicVH0G2RSV@XyNE/@BT2agU7Uqv2/OiFSy90AC2p1GEd11uGiIXZKNRn1AKGLRfFRiq1Lbnpdl9bylo7j4S9tBtiOMrqYWG6723pPsqTn5J4pwAOqI@L6Bg "JavaScript (Node.js) – Try It Online")
Not the shortest but uses a different approach. Second in my series of text-writing programs which aren't the shortest, but help assemble a repertoire of array solutions.
] |
[Question]
[
*Inspired by [this](https://codegolf.stackexchange.com/questions/265087/dp-approach-gives-tle) (off topic) post*
Given an array of numbers, find the largest sum over a subarray not containing two adjacent elements
```
[1,2,3,4] -> 6 // [_,2,_,4]
[1,2,3,4,5] -> 9 // [1,_,3,_,5]
[2,2,1,1,2,1,1,2] -> 7 // [2,_,1,_,2,_,_,2]
[3,1,4,1,5,9,2] -> 16 // [3,_,4,_,_,9,_]
[9,8,7,9,9,8] -> 26 // [9,_,_,9,_,8]
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1] -> 21
```
## Rules
* You can assume that all number in the array are positive integers
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") the shortest solution wins
*Optional additional requirement:*
* Your solution has to run in **polynomial time** (\$O(n^k)\$ for some integer k)
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~46~~ 38 bytes
```
->l{a=b=0;l.map{a,b=b,[a+_1,b].max};b}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGiNNulpSVpuhY31XTtcqoTbZNsDaxz9HITC6oTdZJsk3SiE7XjDXWSYoFCFbXWSbVQ1XEFCmnR0YY6RjrGOiaxsVzIXB1TmIARUMBQxxBGwoSNgRwTIDbVsUQIWupY6JgDBYB0bCzElgULIDQA)
Runs in O(n).
### How?
We need 2 accumulators. The first 2 steps will initialize them with the first 2 elements of the list. Then at every step: add the current element to the accumulator that was not increased in the previous step, and discard the smallest.
### Example:
```
[3,1,4,1,5,9,2]
Start -> a=0, b=0
3 -> a=0, b=3
1 -> a=3, b=1
4 -> a=3, b=[3+_+4]
1 -> a=[3+_+4], b=[3+_+_+1]
5 -> a=[3+_+4], b=[3+_+4+_+5]
9 -> a=[3+_+4+_+5], b=[3+_+4+_+_+9]
2 -> a=[3+_+4+_+_+9], b=[3+_+4+_+5+_+2]
```
Thnks @tsh for -6 bytes
[Answer]
# [Haskell](https://www.haskell.org), ~~38~~ 35 bytes
```
g(x:y:r)=max(g$y:r)$x+g r
g x=sum x
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TZBLCsIwEIYRXPUUA3bR4tSSPqwR6g08QSmlC43FRkpViGdx40Y8k57GiWnUwDyS__uHMNfHrj7uN217u93Pp22weE6Ep5aXZe_nslaecHXrqqmA3hGg8uNZgjLoazR2ZN0cIAdZd2vwur45nGbCh8KBgmGEMSYlgj1BAMEK5tSFIRQV6RXpPxTTL2xQPqCMwJgi1XBEMENmM1kMnA2wnqoNulLWlpgeEooU-cdg57O5sejZyQfnWGkDxwVmdKFaln8figYDtzDpjlmG3d8b)
`g x=sum x` is a handy way to combine the two base cases `g[x]=x` and `g[]=0`.
---
# [Haskell](https://www.haskell.org), \$O(n)\$, ~~42~~ 38 bytes
```
fst.foldr(\a(b,c)->(max(a+c)b,b))(0,0)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TZBdisIwEIDZFx96inmSBCdq-qdB9AaeoJaSqtViq6IVhGVP4ktBxDPtnmYnpnU3MDNJ5vuGkNtzq8-7dVHU98_N9HGpMjH-7mbnqp8ditWJLTRLccnFjJX6ynRvyVNMOWdDHHJL_3x0Jk6p8z1ModTHObDjKd9X_Q2HyIFIoose-jFCu4QAMYOQdoMBRAn1E-r_oRi8YYuqBpUEehSBgV2CJco2k2LhUQObqUYwlbJRPLrwKQJUL6GdL0OrmNn-C1eYGEHhGEd0oBrH_x7kNoJqYeo7X_Y76trWXw)
Based on [G B's Ruby answer](https://codegolf.stackexchange.com/a/265384/56433). -4 bytes thanks to [regr4444](https://codegolf.stackexchange.com/users/95913/regr4444)!
[Answer]
# [R](https://www.r-project.org), ~~80~~ ~~46~~ 43 bytes
*Edit: hugely golfed with inspiration from [G B's answer](https://codegolf.stackexchange.com/a/265384/95126): upvote that!*
```
\(x)max(Reduce(\(a,i)c(max(a),a[1]+i),x,0))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TY9LDsIgEED3noLEDZNOU2nph4Uewm3bNKTapAs3xia9i5tq4qG8hwdw6ICRZBgY3hvg_rguz2H_mm5DXL2jRs5wsbM8nk9Tf5aNtDhCL13JAtpatdEIOOMOwCufQfZSYYoZagARxlbEByEKWiWJqDs671C3mz8Y8x_OsPGwIjSjyBlPCVeowkwS46XHXWenuEwzSxmVNEWOZlXCHapgyfXXq2CwY8VghSVtKfuHsZJ6xQQcq5b_viycvw)
Runs in polynomial time.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~11~~ 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÎĆvMsy+s
```
-3 bytes and \$O(n)\$ complexity by porting [*@G B*'s Ruby answer](https://codegolf.stackexchange.com/a/265384/52210), so make sure to upvote that answer as well!
[Try it online](https://tio.run/##yy9OTMpM/f//cN@RtjLf4krt4v//ow11jHSMdUx0TGMB) or [verify all test cases](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpdfnJiUmapgY6Pg6u/GZa@k8KhtkoKS/f/DfUfaynyLK7WL/9fqcIHkuMozMnNSFYpSE1MUMvO4UvK5FBT08wtK9CFGQCk0U20UVMBq81L/RxvqGOkY65jEcsFYOqZAthGQbahjCCOBIsZA2gSITXUswXxLHQsdcyAbSMdyAQA).
**Explanation:**
```
Î # Push 0 and the input-list
Ć # Enclose; append the first item at the end of the input-list
# (this is to have an extra iteration, the value that's appended is irrelevant)
v # Pop and loop over each item `y` of this modified input-list:
M # Push a copy of the stack's maximum
s # Swap so the previous value (or 0 in the first iteration) is at the top again
y+ # Add the current loop-integer `y` to it
s # Swap back to the pushed maximum for the next iteration
# (after the loop, the maximum of the extra iteration is output implicitly)
```
[Answer]
# [Befunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), 35 ~~52~~ ~~60~~ ~~67~~ bytes
```
1pp>1g00g`g3j>;#&00g+01p00p'#j<;.@
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//83LCiwM0w3MEhPSDfOsrNWVgMytQ0MCwwMCtSllLNsrPUc/v@3VLBQMFewVADRAA "Befunge-98 (PyFunge) – Try It Online")
Takes input as a series of space separated integers. The last integer must have a trailing space.
Uses the dynamic programming approach, and so runs in O(n).
### Alternate version with only printable characters, 36 bytes
```
1pp>1g00g`g3j>;#&00g+01p00p93*#j<;.@
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//83LCiwM0w3MEhPSDfOsrNWVgMytQ0MCwwMCiyNtZSzbKz1HP7/t1SwUDBXsFQA0QA "Befunge-98 (PyFunge) – Try It Online")
Same as above but replaces the unprintable character with 9\*3=27, costing an extra byte (which is why it is not 26)
## Explanation
Here the unprintable character has been replaced by `O`. Note that the unprintable character has ASCII value of 26
```
1pp>1g00g`g3j>;#&00g+01p00p'O#j<;.@ Full program
1p 0 is always on the stack, so 1p stores 0
at (0,1)
p stores 0 at (0,0)
> >;#& 'O#j<;.@ Loop until EOF received
1g00g Get (0,1) and put on stack, then get
(0,0) and put on stack
` Pop b, then a, push 1 if a>b, otherwise
push 0
g Stack now either contains 1 or 0, which
corresponds to one of the stored values,
get that value
3j>;#& ;.@ Jump to &, which gets one integer input.
If EOF, print top of the stack, then end
Otherwise if continuing loop:
00g+ Get (0,0) then add top two values of
the stack
01p00p Pop the top of the stack and store at
(0,1), then get the top of the stack
again and store at (0,0)
'O#j< Jump 26 characters back to the start of
the loop
```
[Answer]
# JavaScript (ES6), 43 bytes
Port of [GB's answer](https://codegolf.stackexchange.com/a/265384/58563), running in \$O(n)\$.
```
a=>[...a,b=0].map(v=>[b,a]=[a>b?a:b,b+v])|b
```
[Try it online!](https://tio.run/##bc7dCsIgFAfw@57Cy41OLveZgetBRIauLYo1R4td9e52rEbBEs454N8fx4ue9FjfzsN909tj41rhtCglpVSDEVtFr3oIJrwxoJWQujQHvTdg1pMKH8bVth9t19DOnoI2kAxiSCBV5HPCkEQRyQmRFSYVJqv/AjL1KzgKhu8TrGxhYjQM2NzV2xRo/A7v/MS@kAmmKVYGHNN5G8uJ9JvSl@JQLRyHHRSY4FTfX8bo@GwwcU8 "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 44 bytes
This one runs in \$O(2^n)\$.
```
f=([v,...a],p)=>x=v?p|(v+=f(a,1))<f(a)?x:v:0
```
[Try it online!](https://tio.run/##bc7NCsIwDAfwu0/RY4uxs/u0w7oHGWWM6UQZ63BSdvDda6oOhVlIcvj3R3KtbT02t8tw3/TmeHKuVbS0wDmvNQxMHSZli@FB7Vq1tAbB2B4nK6bc5lvXmH403Yl35kxbWgoIIYJYk89jjAQBSQkpK0wqTFb/BST6V0gUAv9HWMnChGgEiLnrt8nQ@B3e@Yl9ISNMY6wEJKbzNpGS0m@KX0pCtXASdpBhglN/rwzRydlg4p4 "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
[v, // v = next value from the input array
...a], // a[] = remaining values
p // p = flag set if the previous value was used
) => //
x = // save the result in x
v ? // if v is defined:
p | ( // if p is set
v += // or the updated value of v obtained by adding
f(a, 1) // the result of a recursive call with p set
) < f(a) ? // is less than f(a):
x // use x (the result of f(a))
: // else:
v // use v
: // else:
0 // stop
```
[Answer]
# [Uiua](https://www.uiua.org/), 8 bytes
```
↥∧⊃⋅+↥.0
```
[Try it online!](https://www.uiua.org/pad?src=ZiDihpAg4oal4oin4oqD4ouFK-KGpS4wCgpmIDFfMl8zXzQKZiAxXzJfM180XzUKZiAyXzJfMV8xXzJfMV8xXzIKZiAzXzFfNF8xXzVfOV8yCmYgOV84XzdfOV85Xzg=)
```
↥∧⊃⋅+↥.0 input: a vector V of numbers
.0 set up two accumulators:
maximum containing the last element (Mc),
maximum not containing the last element (Mn)
‚àß fold over V: for each item Vi,
⊃⋅+↥ replace [Mc Mn Vi] with [Mn+Vi max(Mc,Mn)]:
‚ãÖ+ discard Mc and add Mn and Vi (arity 3)
‚Ü• max of Mc and Mn (arity 2)
⊃ fork: take 3 values and pass enough amount of args to each function
‚Ü• max of final Mc and Mn
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `G`, 59 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 7.375 bytes
```
ẏṗ'¯‹g;İṠ
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJHfj0iLCIiLCLhuo/huZcnwq/igLlnO8Sw4bmgIiwiIiwiWzEsMiwzLDRdICAgICAgICAgLT4gNlxuWzEsMiwzLDQsNV0gICAgICAgLT4gOVxuWzIsMiwxLDEsMiwxLDEsMl0gLT4gN1xuWzMsMSw0LDEsNSw5LDJdICAgLT4gMTZcbls5LDgsNyw5LDksOF0gICAgIC0+IDI2Il0=)
Probably doesn't meet the criteria of running in polynomial time.
## Explained
```
ẏṗ'¯‹g;İṠ­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌⁢​‎⁠⁠‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁤​‎‏​⁢⁠⁡‌⁢⁡​‎‏​⁢⁠⁡‌⁢⁢​‎‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁢⁤​‎‏​⁢⁠⁡‌­
ẏṗ' ; # ‎⁡Keep items of the powerser of range(0, len(input)) where:
g # ‎⁢ The minimum
¯‹ # ‎⁣ Of deltas - 1 isn't 0
# ‎⁤Essentially, this finds all sets without consecutive items, as consecutive items will have a forwards difference of 1, which is 0 when decremented.
# ‎⁢⁡This works regardless of input because it's operating on the list of indices, not actual values
İ # ‎⁢⁢Index into the input list
Ṡ # ‎⁢⁣And sum each
# ‎⁢⁤The G flag outputs the biggest sum
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes
```
F²⊞υ⁰FA≔⟦⁺ι§υ¹⌈υ⟧υI⌈υ
```
[Try it online!](https://tio.run/##RYu9CoMwFEb3PsUd74VbqLYdipM4ORSyhwzB/hiIsSS54ttH26XDt5xzvmG0cZitL@U1R8CaQEkaURhO1Bx@rA8fyUgEbUruHVArLwkdQ5v78Hiu37giYrjb1U0yoZBhkP2uogsZO5sy/h1RU4rWZ674su/KN66NKcfFbw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @GB's Ruby answer.
```
F²⊞υ⁰
```
Start with an accumulator of two zeros.
```
FA
```
Loop over the input.
```
≔⟦⁺ι§υ¹⌈υ⟧υ
```
Update the accumulators.
```
I⌈υ
```
Output the best sum.
[Answer]
# [Scala 3](https://www.scala-lang.org/), 69 bytes
```
l=>{val(a,b)=l.foldLeft((0,0)){case((a,b),c)=>(a max b,a+c)};a max b}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=hc_BSsNAEAZgvPoQMscdnErTtNhGNuDBg1BPxVPpYbJNSspmK8lWlJAn8RIP-k76NE6b9hoPMz-z-zEwH9-VYcth-3txtUu2qfHwxLmD-hJgnWZQyKC43FQR3Jclvy8XvszdZoURPLvcgz5KgBd59dapgt8W-0LN88qrgEYU0hgR_yM06UMjQQEF595HQwFjqQnN-uGMpnQrSLJjjdQrW-hQBAe1fHR-pWPpcufX3meD6c-D1XEtUDElqO1NtrPreZp5pYY0RKwNV6k6fpJBHSs-bISE-Npgc3eamm7Z5ynbtss_)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 39 bytes
```
a=>a.map(v=>q=(v+=p)>(p=q)?v:p,p=q=0)|q
```
[Try it online!](https://tio.run/##rY/NDoIwDIDvPsWOW6zgxp8zGT4IWciCYDQIQ8xOvjsWhWiCR7e0XfL1S9eLcaYvbmd73zTtsRwqNRiVGu9qLHUq7RR1a2VZSq3q2MHtLeBDbdmjG4q26du69Or2RCuacRAQQKjJdBgjvk9iQrIcSY5k9duASH8bEg2O/QFGtHAEOhz4nPXbSdAZZ4zeWDEvzABpiBGBRDpP4zHJxknhy5KQLzwJO0iQYNWfXwr05OwgWe725zttKvjwBA "JavaScript (Node.js) – Try It Online")
Use two variables `p`, and `q` to track:
* `p`: Largest sum we got for `a[0..i-1]`
* `q`: Largest sum we got for `a[0..i]`
So, for each iteration,
* `i' = i + 1`
* `p' = q`
* `q' = max(q, p + a[i'])`
[Answer]
# Java, ~~64~~ 57 bytes
```
a->{int t=0,r=0;for(int k:a)r=(k+=t)>(t=r)?k:t;return r;}
```
Another port of [*@G B*'s Ruby answer](https://codegolf.stackexchange.com/a/265384/52210).
Also runs in \$O(n)\$ complexity.
[Try it online.](https://tio.run/##rVHLasNADLznK0ROu3hj4jxoY@OU0nNzydH4oDqb4kfWYVd2Ccbf7spOQn@gLCuNBmkYoQJbXBSncsgqdA4@MTfdDCA3pO0ZMw2HsZwIyATHJAWUEXP9jIMjpDyDAxiIB1zsu7GP4qWy8TI613acgDJEaWNRejHJvaDYyrcypMhqaqwBG/VDNGpdm6@KtR6SbZ2f4MJ2xJFsbr6TFOXdyijbogXSjj7Q6dDoH5icJWnXBWql1mrTqydSW8YrxoEKnpGZNecN/63aTfVOvaoXxpyn2X9@fS8n8wDHmyN98euG/CsvRpURBR/Bbyiv/Hdr8eZ8qu9Li@eO0puHMPeMn/1Rjyv0wy8)
**Explanation:**
```
a->{ // Method with integer-array parameter and integer return-type
int t=0, // Temp-integer, starting at 0
r=0; // Result-integer, starting at 0 as well
for(int k:a) // Loop over the integers `k` of the input-array:
r=(k+=t)>(t=r)?k:t;
// (k+=t) // First increase the current `k` by value `t`
// (t=r) // Then replace `t` with value `r`
//r= k > t ?k:t; // And then set `r` to the maximum of these new `k` and `t` as
// preparation for the next iteration
return r;} // After the loop, return the final 'prepared' maximum `r`
```
[Answer]
# [Python](https://www.python.org), 48 bytes
```
lambda a,b=0,c=0:max(b:=max(d+c,c:=b)for d in a)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=rdDdboIwFAfw7FKeopftPCrlQy1J9yKONAUkNkEgih97lt2YLNs7bU-zU2zjC0jT_iHn15OWz5_-Y9h17e2rlu_fp6GerX_DRu-LShMNhQyhlGG211daZNJGNS2hzGTB6u5AKmJaopnbJy4702wJz4KJAQUdvCpp2v40UDY_9o3BDCb9wbQDNVDT7Vk31DAGnWtw-3uZbjhEEEOSE__M3sgSY7EgG4U1hbXAK0jzhxJOcTQxzhRdhI4D92tu3co528tam7iijvE7wZmCsHbsypd3bTsmoxSg0ApYwwrfMXN_gshZ4R3W7FmfPMZbRPz-0_4B)
\$O(n)\$ complexity.
Loops over the list. On each prefix, `b` and `c` are the largest such sums of the two previous prefixes.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 41 bytes
```
.+
$*
+`^((.+).*)¶\2(.*)¶
$1$3¶$1
O^`
\G1
```
[Try it online!](https://tio.run/##K0otycxL/K@qEZyg819Pm0tFi0s7IU5DQ09bU09L89C2GCMNMM2lYqhifGibiiGXf1wCV4y74f//hjpGOsY6JlxQWseUywjIMtQxhJFcxkDSBIhNdSyBPEsdCx1zIAtIAwA "Retina 0.8.2 – Try It Online") Takes input on separate lines but link is to test suite that splits on commas for convenience. Explanation: Another port of @GB's Ruby answer.
```
.+
$*
```
Convert to unary.
```
+`^((.+).*)¶\2(.*)¶
$1$3¶$1
```
Add the first element to the third and keep the larger of the first and second elements.
```
O^`
```
Sort descending.
```
\G1
```
Convert the larger of the remaining two numbers to decimal.
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 9.5 bytes (19 nibbles)
```
`//$`,1:`/@]+/@$$]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWmxL09VUSdAytEvQdYrX1HVRUYiESUPnN0UrRxjqGOiZAbKpjqWMUqxQLlQIA)
Runs in polynomial time.
Direct port of [my R answer](https://codegolf.stackexchange.com/a/265383/95126), which is itself inspired by [G B's answer](https://codegolf.stackexchange.com/a/265384/95126).
```
/ # fold from right
$ # over the input,
`,1 # starting with a list of only [0]:
: # join
/@] # maximum in the result-list-so-far
# to
/@$ # first entry of the result-list-so-far
+ $ # plus the current element
`/ ] # and output get the maximum in the final result-list
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 47 bytes
```
x=>x.map(e=(t,i)=>e=x[i]=(t+=~~x[i-2])<e?e:t)|e
```
[Try it online!](https://tio.run/##bc7fCoIwFAbw@55il46OyvyTLZo9iAwRW2GYSkp4Eb66fVZSYIOds/Htx9klu2dtfiuazq7qoxlPauxV3DvXrLGMsjoquIqN6pNC47ZWw4Cj7Wm@Nwez6/jDjHldtXVpnLI@WycrEeSRT4Fmn8U5c122YSxJkaRIVv8FhfpXSAiB9z52uDAejCAxV/02Ecw0Y3JTR11IH2mAHZJEOk8TG5ZMk4KXkpQunKQtRUjQ9feXHpycDZLxCQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python](https://www.python.org), 55 bytes
```
f=lambda a,b,c,*d:d and f(max(a,b),a+c,*d)or max(a+c,b)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PYxJDoMwDEX3nCJLB1ypTGKQOEMPgLIIDRGRIEQodDhLN2zaO3GbppR2Yfu_J30_XuZuu1Evy3O28pCvmax6PjSCE44NntEXpSBcCyJh4DdwkiIPPp6OE9mUo4bu9eDaqb4loMpKaTNboLT0CDGT0hYk-O2F96BofWR0ryzrqa5DjDDGhDHvnzHdKHIUYvjbm4tdStykWOymwBwzR-4y9v37Bg)
Adapted from [G B's answer](https://codegolf.stackexchange.com/a/265384/113573). It only works if the array is at least three elements long.
[Answer]
# [C (clang)](http://clang.llvm.org/), \$\mathcal{O}(N)\$, 53 bytes
takes in a zero-terminated array of positive integers and returns via out parameter.
```
n,t;f(*a,*r){for(*r=n=0;*a;(n=*r)<t?*r=t:0)t=n+*a++;}
```
[Try it online!](https://tio.run/##rVLLTsMwELz7K0ZBBcdxUfpAQN20HxJysJKWWipu5Lhconx72DhQDrQ3FMn27Mx6J7sup@VR2/e@t9KrPRdaChe3@5PjwmU2S5XQituMgmu/pZBfpbHPbCJ0kqiuvzO2PJ6rHdaNr8zp8bBh7PNkKuZ3jefGegjtXMxaBgzISLidV4xgffblQTv@kD/EijDVBDfIkCpQTm4KhSQxMVEkdpS959GkmVSRhMEWtEVYIaJ9lI@3cAIS91Ql4J/EAtMNJtWbjYID4jrGiGIf2lg@WP41KQbzTV6QlzZUH34kL@IWM4m5xEJiKZGik7fZp2uCeRDM5LfycvirXARqGVa66vWGjOIvEs9BMJ6vufrv71IjpbWTEKIOEw0TrKlroX8KFEadJOMEw4MQ9dD4/gs "C (clang) – Try It Online")
---
# [C (gcc)](https://gcc.gnu.org/), \$\mathcal{O}(N)\$, 46 bytes
This one returns the result in the first element of the array, has UB in the form of unsequenced modification and access to `a[2]` and requires the last two elements of the array to be \$0\$.
```
f(int*a){*a=*a?f(a+1)<a[2]+*a?a[2]+*a:a[1]:0;}
```
[Try it online!](https://tio.run/##rZLPboMwDMbveYpPTFVDSCdoO60t/fMgjEMUShupowjoLohXH3NC113GrQLFNv7F/oijZyet@z7npmiE8luhdkIdcq6CyN@qZJ4GFN7tRiVRugnjrn8xhb7csiO2dZOZ6@t5z9jX1WSsOdaNLQWhqspnLQNsZGJGXnlr9FlVfJpM/Zji/FqBG@wQxiA8MWmMIDA@pQiuaGPOvUk9yTwJgwPIeNjAIzvgQxVuW1nvd0uK2R6T7KO4g6EFO8Yoyz6VKbiV@idOWNF1kpKQ1rW2P5CkfotIYi6xkFhKhPSik@PA2wgzd0wk7/DD@RdeuOzSrVRwPU5SaiXx7pjBH1H47CeUjy4hrZ2EEKWbr5tnScfoDjQGfUYZBMM83c0QpZ1E/63zizrV/Yxuz06v1j8 "C (gcc) – Try It Online")
[Answer]
# [Erlang](https://www.erlang.org), 77 bytes
```
f(L)->f(L,{0,0}).
f([],{A,B})->max(A,B);
f([H|T],{A,B})->f(T,{max(A,B),A+H}).
```
[Attempt This Online!](https://ato.pxeger.com/run?1=hY_PCoJAEMbvPYV4iF36ttw00oLATh7q1k0khNwIUkMMAtMX6eKl3qljb9JIWUcH5g_z_WaGuT2i7Bgm-_rZF3G6Ox8jFoeHhA97Irqc0ixnvhpJaE1zJAM-vJ9zJeznWrEVFwuKKAwYJQ0o5gcoXCxLEuLwwqjk86btXTd_RbENilaGO_DK39JXc4VtuSYWPY3skM5UmsVhzvTqVCU6NJ-2SYxhwgp4wNGNYdIFjgmUkG3swk2CLPIJnG7YgY0pgZQb9PtoXX_yGw)
[Answer]
# [Elixir](https://elixir-lang.org), 80 bytes
```
def f(l)do
{a,b}=Enum.reduce(l,{0,0},fn x,{a,b}->{max(a,b),a+x}end)
max(a,b)
end
```
[Attempt This Online!](https://ato.pxeger.com/run?1=fZC9CsIwFIX3PMUdE7wW7Q_WQTcHB9FdHGqTQKBNRS0USp_EpYvuPo6rT2KSKi7VcEnOzfm44eRyE5mq1LG9cyHzgpeZgFWiNPDiWp7lMH5sjAGSZowXpE5w38wWusy9o-BlKmiG9QhHDUoNFTp7OK_zpKJGMkwGVSM0Z-RzQ0z3nvsEsJPz7jECZi3XntKng0jPVNLtGMFHCBDCHWN_fYSoH_EdMnb1Ff1s4MzQ7RHC9CdonBhh4hCrO8oEs-EIsb_n2VSUdUnbtjtf)
[Answer]
# [Racket](https://racket-lang.org/), 99 bytes
Golfed version. [Try it online!](https://tio.run/##dY7fCoJQDIfvfYofdNGkm/xHedWDiBdTj3FoHsUM6ultJ4kIdLCN7ftgG7m@mWneCbsrxmWgxrTWGVALCUnMBOn7gQqBlAXjWBaVlpBsC3IPkYvXOn6CUanv3boZ/5YHbVSzX37id6Nj68IAoMbeB@GXOH93TxFiJEjV3YbI1nGsOEL0retSoijVzJBvKTnOOCnW7p8OguXb@Q0)
```
(define (f l)(let loop([l l][a 0][b 0])(if (null? l)(max a b)(loop(cdr l)(max a b)(+ a (car l))))))
```
Ungolfed version. [Try it online!](https://tio.run/##hY/dCsIwDIXv9xQHvLDijftDd@WDDJFu66QYu7Ef0KevaeeY3sxAE3L6JZx0sryrwdoNSXND57sgEJWqtVEQD/m89uMD1A@7ABCkBlDTtBA5S06@IJc4cC44O4YpXUOYkeg8z03htkGi@FKmXWXVeXIhIPZcRSmnDx8/trTxfirdtyRfZBarWxEiQozEjfxBkK5BEUMhwjmvoTEDCb8U2TqY4YQjQ1w/N/lbrH0D)
```
#lang racket
(define (max_sum lst)
(let loop ([lst lst] [a 0] [b 0])
(if (null? lst)
(max a b)
(loop (cdr lst) (max a b) (+ a (car lst))))))
(define (main)
(displayln (max_sum '(1 2 3 4)))
(displayln (max_sum '(1 2 3 4 5)))
(displayln (max_sum '(2 2 1 1 2 1 1 2)))
(displayln (max_sum '(3 1 4 1 5 9 2)))
(displayln (max_sum '(9 8 7 9 9 8))))
(main)
```
[Answer]
# [Rust](https://www.rust-lang.org/), 90 bytes
Golfed version. [Try it online!](https://tio.run/##hc9LCoMwEAbgfU8RXU3oVHxi7cNjdFNKCTZCQGPRtFitZ7dTwXUCk3@GfAykfXVmLjWrhdLA2bhhdJ6t0qbSDrjj5CLr4C0L5xpgiBHGN86PdoWJxYXkAgzW26IjMjFVgpnVZrjHlBzlIqf//zoQh4ssTioKc77LKcZKGujxw8/CozXNXRnZAvfKpnoA@Ohz/C7vOFB6teiB@n470M51nOb5Bw)
```
fn s(a:Vec<i32>)->i32{let(x,y)=a.into_iter().fold((0,0),|(x,y),z|(x.max(y),x+z));x.max(y)}
```
Ungolfed version. [Try it online!](https://tio.run/##jdBfC4IwEADwdz/F6dNGV/iXapUfo5cIsTlBUIs5I1A/ux2abz04uO3gfsdt021jxjGvoUqLmnHoLKD10kVtytpmTjc4SLVP0rQVeytp3zz0McDwzvlprcVolfZJe@gt@6qegGRIEeFxZccRD7gnTefkB8uanj@TVGsBVyXPReDHHLYxUPL7lVIZYCnCg8MFCO5oyDMpjNKM7/JnmTHmIrgcoZ8ZguyBNSYTQlYvIWjIUkhhA3K57h9hDeP4BQ)
```
fn main() {
println!("{}", max_sum(vec![1,2,3,4]));
println!("{}", max_sum(vec![1,2,3,4,5]));
println!("{}", max_sum(vec![2,2,1,1,2,1,1,2]));
println!("{}", max_sum(vec![3,1,4,1,5,9,2]));
println!("{}", max_sum(vec![9,8,7,9,9,8]));
}
fn max_sum(arr: Vec<i32>) -> i32 {
let (a, b) = arr.into_iter().fold((0, 0), |(a, b), c| (std::cmp::max(a, b), a + c));
std::cmp::max(a, b)
}
```
[Answer]
# [OCaml](http://www.ocaml.org/), 104 bytes
Golfed version. [Try it online!](https://tio.run/##lY1NCsIwEIX3nuItE2yl1RZ/QnsCbyAS0jbVQJJKGzEL715jENwqDMObj/cxQyuMnmctHUbZwkBXRrj2Co2HcleczmmdPf3h4Ke0Di0ikoZWRzW5VT/ojmvZO9LfbeQ@rYkRHgJNIpaeUpIlGdVQFh8cHxGKagHcRmUdl7bTykqQyYX7woeeBwxicMoZ1gwbhuJMKfvPYCh/ldZRyuN8w6/2JtaLuEuG/R9q6O4YtlF657c3vwA)
```
let rec m l=match l with []->0|x::xs->let(a,b)=List.fold_left(fun(a,b)x->(max a b,a+x))(0,0)l in max a b
```
Ungolfed version. [Try it online!](https://tio.run/##nY7NCoMwEITvPsUcDbXgL20N9kVERG2sgRhFI/TQd7dJ0PZsISy7s/vNZGiqXqyrYAoTa9BXr3JeeohZIXOAXe@YGNkEt/JQE2RoF9koPkh9AryRFzjfDYwK9aZ1aaqMuqPb1tPlhI5A6Tsuv2vfg09MruOYUJfY/HHiUpVMPgSXDO6s9Pwsh7bUsrW0v80DipAioogLQug/HEVyDA0tGtj3a455RBaKbU0obocNNHGluFjU9IZe1w8)
```
let rec max_sum lst =
let rec helper (a, b) = function
| [] -> max a b
| h::t -> helper (max a b, a + h) t
in helper (0, 0) lst
let () =
print_endline (string_of_int (max_sum [1; 2; 3; 4]));
print_endline (string_of_int (max_sum [1; 2; 3; 4; 5]));
print_endline (string_of_int (max_sum [2; 2; 1; 1; 2; 1; 1; 2]));
print_endline (string_of_int (max_sum [3; 1; 4; 1; 5; 9; 2]));
print_endline (string_of_int (max_sum [9; 8; 7; 9; 9; 8]));
```
] |
[Question]
[
[Pascal's triangle](https://en.wikipedia.org/wiki/Pascal%27s_triangle) is a triangular diagram where the values of two numbers added together produce the one below them.
This is the start of it:
```
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
```
You can see that the outside is all 1s, and each number is the sum of the two above it. This continues forever.
Your challenge is to check whether a non-empty array of positive integers is a row of Pascal's triangle, somewhere down the line.
You should output two distinct values for truthy and falsy.
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins.
## Testcases
Truthy:
```
[1]
[1,2,1]
[1,3,3,1]
[1,5,10,10,5,1]
[1,6,15,20,15,6,1]
[1,7,21,35,35,21,7,1]
```
Falsy:
```
[2]
[1,2]
[1,1,2]
[2,2,2,2]
[1,2,10,2,1]
[1,2,3,4,5,6]
[1,3,5,10,5,3,1]
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~36~~ ~~31~~ 26 bytes
```
f[1]=1
f(1:b)=f$scanr1(-)b
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/Py3aMNbWkCtNw9AqSdM2TaU4OTGvyFBDVzPpf25iZp5tSj6XgkJBUWZeiQpQqY6JjhkQG8b@BwA "Haskell – Try It Online")
This version errors as a false indicator and returns `1` as the true indicator. It's short but I generally find these sorts of answers a little cheaty so below I have a version with a more traditional output method:
# ~~42~~ ~~37~~ 32 bytes
```
f[1]=1
f(1:b)=f$scanr1(-)b
f _=0
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/Py3aMNbWkCtNw9AqSdM2TaU4OTGvyFBDVzOJK00h3tbgf25iZp5tSj6XgkJBUWZeiQpQg46JjhkQG8b@BwA "Haskell – Try It Online")
Outputs `1` for yes and `0` for no.
This is I believe the only answer here using this method. We use `scanr1(-)` to calculate what the layer above would have to be in order to produce the input, and check if that new smaller layer holds. If we encounter `[1]` we halt with yes, because that is the first layer of Pascal's triangle. And if we encounter something starting with something other than `1` we halt with no.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
L’cŻ$⁼
```
[Try it online!](https://tio.run/##y0rNyan8/9/nUcPM5KO7VR417vl/uP3opIc7Z2hG/v8fzRVtGKsDJHSMdKAMYyCEMk11DA1AyBQmYKZjaKpjZAAizWBi5jpGQE2mIGQE4oGFjSByQGNBDAMdEyA0gFtkgLDNCGibCdACM5jlphALQW7gigUA "Jelly – Try It Online")
As each row of Pascal's triangle has a unique length \$n\$, all we have to do is reconstruct the row, given its length, and check if it equals the original input. As each row is given by \$\binom{n-1}{i}, 0 \le i < n\$, we just calculate that (as Jelly has a 1 byte for binomial coefficient)
In fact, if we can take the length of the input as a second input, we can get [5 bytes](https://tio.run/##y0rNyan8//9Rw8zko7tVHjXu@a/jc3i5g77m///RXNGGsTpAQsdIB8owBkIo01TH0ACETGECZjqGpjpGBiDSDCZmrmME1GQKQkYgHljYCCIHNBbEMNAxAUIDuEUGCNuMgLaZAC0wg1luCrEQ5AauWAA)
## How it works
```
L’cŻ$⁼ - Main link. Takes a list L on the left
L - Length of L
’ - Decrement
$ - Last 2 links as a monad f(len-1):
Ż - Range from 0 to len-1
c - Binomial coefficient of len-1 and each element in the range
⁼ - Does that equal the input?
```
[Answer]
# [R](https://www.r-project.org/), 43 bytes
Or **[R](https://www.r-project.org/)>=4.1, 36 bytes** by replacing the word `function` by `\`.
```
function(r)any(r-choose(x<-sum(r|1)-1,0:x))
```
[Try it online!](https://tio.run/##VY7RCsIwDEXf/ZIEUkjjWkH0Y6Ss6IMtdA4m7N9rO5mt5JLcJISclP01@zm41yMGSHgLb0jK3WOcRlguapqfkFaNShOfF8TswYFGPGyVhJo/lmidIc1VpptZ0oaEa7bd@ERSrk2V1G7fSHvzc80zDSW4R@E/Hik8Q/lvO0LzRdpA8wc "R – Try It Online")
Taking also length of input as second argument, we can shave 6 bytes off: [Try it online!](https://tio.run/##TU7RCgMhDHvfl1jogdVTx2AfM2SywaHgtod9vWv1ZEdDSRoxqS1dW/rk@H6WrCpucMtfVZf4KOV1V9tCSBfeAC2pqAiQ4NQZGqZop7I8rNepHZIWOLn6efVIDo2W7cUI0who@A8nMKLYOw/PHCOBsfOu9niNK48@xBvJ7g3d/2T5EQcf@tjR043yAdoP "R – Try It Online").
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~11~~ 9 bytes
Saved 2 bytes thanks to Bubbler
```
⊢≡⍳∘≢!≢-≡
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/9OA5KOuRY86Fz7q3fyoY8ajzkWKQKwLFPj/Xz2kqLQko1KdK03B8FHvFkMQrWCkAKGNgRDCMlEwA2II21TB0ACETKF8MwVDUwUjAxBpBhUyVzAC6jYFISMQz5BL3S0xpxhujRFYFdAiIG0ANNhEwQBmsQHcdiOg7SZAW8ygbjGFWAp0EgA "APL (Dyalog Unicode) – Try It Online")
Requires 0-indexing.
```
⊢≡⍳∘≢!≢-≡
⊢ ⍝ Does the input
≡ ⍝ equal
⍳∘≢!≢-≡ ⍝ the row of Pascal's triangle with the same length?
≢-≡ ⍝ The number r of the real row that has the same length
≢ ⍝ The length of the input
-≡ ⍝ Decremented/Minus the depth (which is always one)
⍳∘≢ ⍝ The column numbers for that row (a range [0..r])
! ‚çù Get the number at row r and column c for each element in the previous range
```
[Answer]
# [C (clang)](http://clang.llvm.org/), 66 bytes
```
i,c,t;f(*p,n){for(t=c=i=1;i<=n;c=c*(n-i)/i++)t=t&&p[i-1]==c;*p=t;}
```
[Try it online!](https://tio.run/##bVFtb4IwEP7ur7iQaABLBjhcTO2@LPsV6gdTQZu5ztCauSz@9bG7VlRU0h7c89w93ItM5Hap102jmGSWV2G8Yzr6rb7q0AoplMi4mgrNpZBxqBMVPanhMLLCDga7mUqyhRCSxzth@bFR2sLnUukw6v32AIB8WxprZgsQ4CB8MgZZmrKLl7N7bOTOHVwQ4G/xgB4jgHie@vf4QcgL0qRf@Jt7qBuWk8RNhV3gDsM/PruTPsilcn2Td9TIJfla89sJFOdOR7fZSUYfR05WbpZ1jLaUH2XtRw3B/PCezw@TN7xFwDr@KDgl0n4MhqfOw5VDSJBy0GlzagGvzqW1n3eoKggvPEwm0YloA7x67ERQzsXCEAy/8JVTYPi7BEzEO4lQl2a/pcyYgnivy2oGtt7bzU8rTWUIQTu80tnVGFuFwSy4Vndtakw0HPRUocHGLvRVHvRXODmvrxfRA2WgYfdX0DdzjaG@aHZeRduEOFXb0aDBKxxJ1mLHXmvq0u5rTWs5Nn@y2i7Xpkm@/wE "C (clang) – Try It Online")
# [C (clang)](http://clang.llvm.org/), 55 bytes
```
i,c;f(*p,n){for(c=i=1;i<=n;c=c*(n-i)/i++)c/=p[i-1]==c;}
```
Inspired by Wheat Wizards' post. Triggers a floating point exception for falsey.
[Try it online!](https://tio.run/##bVNNj5swEL3zK0ZUkYBAF0jZKiLeS7WteqvUYxJVrIHELesgPrZbrfLXl45tTCDEwsZ@M2/m2WNTjxYJP3Qdc2mcW07pcvstP1UWJYwEMdsQHlNCHYt7zL5jy6VN70i5ZV6wJ4TG5@4D47Ro0ww2NTvwpPh4fDBGWJOy0wwq2NMVljW/n0uBGfj/9dTmkPGX2DBeTiyFY8LTIqssxhvAJDa8GYANp8WJH5BgobMLgR0bZ8MQXk1WN3nLqaA4ULogQD4iolDr5/dvX388ujo8soWR5WChg1KkAwMhOEo7tipr2oqDrwi5hfF5z@5NwaDkOWHcsg2ZWCurt3sgvRaAABP4vntZhe4cW8lvBkcCUD26Yb5HAPHQV//7Gy6f0SziR6qHCpq6hSLElcIpMMMw4yf5@Te4Qq7a5My0kiSlNbw@gWjY6eqa7QVicpZFoMekcnDM6J@sUkcN5u71Mdy9rr9gj0x3sl6ZPVHeL3RXhcVHAPLKMQn1lWN7eJBL8RSGGopLc7HDeq3vinboo3MXmqptjv8w5OAv7pbfXybZygp9c8vcmvYIlXo4EusY@IbhgAou5hEPFiluUcXne/tGZBCnIqJP5DmSo6XBEjNN5VdZ3RbaQb4vMcHXBR7U4zzzjIsUFvWOoy4VxB0KpIOS/mgmgkU5GCoJNHY29HB5hefuneZFcqg77@9/ "C (clang) – Try It Online")
[Answer]
# [Lean](https://leanprover.github.io/), ~~187~~ ~~176~~ ~~143~~ 131 bytes
```
def q:list ℕ→bool:=λx,by{induction x,exact[],apply(::)1,induction x_ih with h t i,exact[],cases t,exact[h],exact(h+t_hd)::i}=x
```
[Try it online!](https://tio.run/##y0lNzPv/PyU1TaHQKiezuEThUcvUR22TkvLzc6xsz@2u0EmqrM7MSylNLsnMz1Oo0EmtSEwuiY7VSSwoyKnUsLLSNNRBko7PzFAozyzJUMhQKFHIhCtOTixOLVYogfIzYiEMjQztkviMFE0rq8xa24r/yqlliTkKGoXRhrGaXAiODhrXCF3AGAjRhEx0zIAYQxBNyAih7j8A "Lean – Try It Online")
A simpler version of this can be found below:
# [Lean](https://leanprover.github.io/), ~~190~~ ~~185~~ 169 bytes
```
def f:ℕ→list ℕ:=λn,by{induction n,exact[],apply(::)1,induction n_ih with h t i,exact[],cases t,exact[h],exact(h+t_hd)::i}
def g:list ℕ→bool:=λx,f(x.length)=x
```
[Try it online!](https://tio.run/##y0lNzPv/PyU1TSHN6lHL1Edtk3Iyi0sUgEwr23O783SSKqsz81JKk0sy8/MU8nRSKxKTS6JjdRILCnIqNaysNA11kKTjMzMUyjNLMhQyFEoUMuGKkxOLU4sVSqD8jFgIQyNDuyQ@I0XTyiqzlgvkgHQrmNVAVyTl5@eAXFChk6ZRoZeTmpdekqFpW/FfObUsMUdBIz3aMFaTC8HRQeMaoQsYAyGakImOGRBjCKIJGSHU/QcA "Lean – Try It Online")
This version defines a helper function `f` which gives the \$n\$th row of pascal's triangle. From here we check if the input is equal to the \$m\$th row where \$m\$ is the length of the input.
This is the straightforward way to do things.
The shorter version rolls these two into one. Instead of doing induction on the length of the list, it just does induction on the list itself. This turns the already hairy induction into a real mess.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `r`, 6 bytes
```
₌ẏL‹ƈ⁼
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=r&code=%E2%82%8C%E1%BA%8FL%E2%80%B9%C6%88%E2%81%BC&inputs=%5B1%2C2%2C1%5D&header=&footer=)
vyxal (and lyxal) is the best?
```
₌ẏL‹ƈ⁼
(implicit input)
‚Çå parallel stuffs, do the next two command both on the stack top
ẏ range of len(top)
L len(top) currently stack [range(0,len),len]
‹ -1 len-1
ƈ do combination caculation C(i,len-1) i= range(0,len)
⁼ check equal stack are not enough so input is used
```
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 15 13 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
-2 bytes thanks to Marshall Lochbaum
```
-˜`⍟≠≡1‿¯1⥊˜≠
```
[Try it here](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgLcucYOKNn+KJoOKJoTHigL/CrzHipYrLnOKJoAoKRsKo4p+oMeKfqeKAv+KfqDEsMiwx4p+p4oC/4p+oMSwzLDMsMeKfqeKAv+KfqDEsNSwxMCwxMCw1LDHin6nigL/in6gxLDYsMTUsMjAsMTUsNiwx4p+p4oC/4p+oMSw3LDIxLDM1LDM1LDIxLDcsMeKfqeKAv+KfqDLin6nigL/in6gxLDLin6nigL/in6gxLDEsMuKfqeKAv+KfqDAsNCw0LDDin6nigL/in6gxLDIsMTAsMiwx4p+p4oC/4p+oMSwyLDMsNCw1LDbin6nigL/in6gxLDMsNSwxMCw1LDMsMeKfqQo=).
Unlike many array languages, BQN doesn't have a binomial primitive, so a more creative solution is required.
```
-˜`⍟≠≡1‿¯1⥊˜≠ #
-Àú` # swapped minus scan
⍟≠ # repeated input length number of times
≡ # matches
1‿¯1⥊˜≠ # alternating 1,-1 .. extended to the input length
```
[Answer]
# [Julia](https://julialang.org/), ~~47~~ ~~38~~ 34 bytes
```
!l=binomial.((n=[l;0][2];),0:n)==l
```
[Try it online!](https://tio.run/##VY7BCsMgEETv/kVuEaToJhpo8EtCDulhIcXaUlLo39td7SGLovNm0Zn7J@2b@5bSpXjb8/Oxb@nS9zkuabbrAuusjb1mHWMqGDt12Li4VR2OLsMCWECVA8uBFsPI4I2zvH21PFvBOG/A8hmqG9idDNBTzxuYaKCQMmBV2BJI1P@bpN/B1EXg/xVs64Gh8WBGCg5kTK2Yb1VqP/V67/lIucf@sFqf0UkEiYPEUaKXGE54HqDMQJmBMgNlBsoMDBInrcsP)
## Explanation
We just generate the n-th row of the Pascal triangle and test equality.
Thanks to amelies, we can get it down to 38 bytes!
Thanks to MarkMush, we can get it further down to 34 bytes!
[Answer]
# [Python 3](https://docs.python.org/3/), 66 bytes
```
f=lambda a,*r:r<a[1:]and f(a,*map(sum,zip(r,(1,*r))),1)or(1,*r)==a
```
[Try it online!](https://tio.run/##RY/BDoMgDIbvPgVHXHoAFJeY@STEQxdHZqJImB62l2cl4JY25e@fwlf8e39uronRDguu9wkZwiX04YZG9iO6iVlOzoqev44VPrPnAbikmbquQdZbyM0wYLRbYMhmx0xl5AhUQEERDUWRGqRIqU@jA6lBiVS707uCoks6pUpdsiujyqv5KEJASyF@QPGnKqK2BOrOJXQG513Gnvkwu51bvh9@eXCkP8Uv "Python 3 – Try It Online")
Constructs the rows of Pascal's triangle recursively until a match is found or the generated row is larger than the input.
[Answer]
# JavaScript (ES6), 46 bytes
Returns a Boolean value.
```
a=>!a.some(v=>v-n|(n*=a.length/q++-1)-n,q=n=1)
```
[Try it online!](https://tio.run/##dZBBDoIwEEX33sIVVAq2leKqLD2BO2TRYAFNbYUiiYl3xyIbjW1mMsn8@cnkvysfuan6y32IlT6LqWYTZ/maJ0bfRDiyfIzVK1QbxhMpVDO02y6KYgxiBTumGAZTpZXRUiRSN2FQHPvH0D7LAKy@9ToscAn@NUigW9/Zcl8oxGhu6rlnEFNI0Dwzj2UPif1A5ybz9nH92IKTKg5cGlcQ4g7iVN06gqkt5AOCvFSIpZLa5JmHGV3ALOimNw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Factor](https://factorcode.org/) + `math.combinatorics`, 47 bytes
```
[ dup length 1 - dup [0,b] [ nCk ] with map = ]
```
[Try it online!](https://tio.run/##TU/BTsMwDL3vK94HQJWEZUggThwQFy6IU9VDVkyJlrkhyYQG4ttLkm4F2Xp6fpb97DfTpzFML8@PTw832FFgcoj0cSDuKWIgpmCc/TLJjhyxN@m9QhMMDzQLTT/ut5ZNXmT7CB8opaMPlhNuV6tvSPxUVAu7ynHmGlKU1IuygdRQouBmEa@h8pwuqUo16@rUlScmsM4h/gzFP1eVXdcoS89X6Nm4HjO1eD14OOIh/yhxWctWXGw7tOD7HTp82vq@xx26SSqw8d4d0UT0jkyYfgE "Factor – Try It Online")
## Explanation:
It's a quotation (anonymous function) that takes a sequence of numbers from the data stack as input and leaves a boolean on the data stack as output. Assuming `{ 1 3 3 1 }` is on the data stack when this quotation is called...
* `dup` Duplicate the top object on the data stack.
**Stack:** `{ 1 3 3 1 } { 1 3 3 1 }`
* `length` Get the length of a sequence.
**Stack:** `{ 1 3 3 1 } 4`
* `1 -` Subtract one.
**Stack:** `{ 1 3 3 1 } 3`
* `dup` Duplicate the top object on the data stack.
**Stack:** `{ 1 3 3 1 } 3 3`
* `[0,b]` Create a range from 0 to whatever is on top of the data stack, inclusive.
**Stack:** `{ 1 3 3 1 } 3 T{ range f 0 4 1 }`
* `[ nCk ] with map` Take \$\binom{3}{0}\$, \$\binom{3}{1}\$, ... \$\binom{3}{3}\$
**Stack:** `{ 1 3 3 1 } { 1 3 3 1 }`
* `=` Are the top two objects on the data stack equal?
**Stack:** `t`
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 38 bytes
```
Factor@Fold[x#-#+#2&,#]===x^--Tr[1^#]&
```
[Try it online!](https://tio.run/##RY7BCoMwDIbvvkbBy1JoM@tOHZ48b2w3USjOMWEqSAeC6Kt3KdaNhOTPD8mXzthX0xnb1sY9tctNbYcxy4f3o5gYZweGMbBSaz1VnN/HQlasjN310zY2u4xtbwvGz8@MzPVWm36do1kuQAUQgjhSBKlACp9qN1KQClD4mu7eCZCWlE/0k7ejGcPVrQUhIKEQP6D4U5GoCYHS/Qm1gf0v0eK@ "Wolfram Language (Mathematica) – Try It Online")
Checks that the polynomial in \$(x-1)\$ with these coefficients is a power of \$x\$.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 69 bytes
```
lambda l:[math.comb(~-len(l),x)for x in range(len(l))]==l
import math
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPqfYxttqGOqY2gAQkA6livNNuZ/TmJuUkqiQo5VdG5iSYZecn5ukkadbk5qnkaOpk6FZlp@kUKFQmaeQlFiXnqqBkRcM9bWNocrM7cgv6hEAaTtf0FRZl6JRhpI7j8A "Python 3.8 (pre-release) – Try It Online")
Luckily python 3.8 has a built-in for n choose k
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
g<D√ùcQ
```
Port of [*@cairdCoinheringaahing*'s Jelly answer](https://codegolf.stackexchange.com/a/235367/52210).
[Try it online](https://tio.run/##yy9OTMpM/f8/3cbl8NzkwP//ow11zHWMDHWMTUHICMQzjAUA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/3Qbl8NzkwP/6/yPjjaM1Yk21DHSgdDGQAhhmeoYGoCQKZRvpmNoqmNkACLNoELmOkZAHaYgZATigUSNIMaBSQhtpAOGMGsM4HYZAe0yAZpvBrXZFGIdyAGxAA).
**Explanation:**
```
g # Get the length of the (implicit) input-list
< # Decrease it by 1
D # Duplicate it
√ù # Pop the copy, and push a list in the range [0,length-1]
c # Get the binomial coefficient of length-1 with each integer in this list
Q # Check if this list is now equal to the (implicit) input-list
# (after which the result is output implicitly)
```
[Answer]
# [Pascal (FPC)](https://www.freepascal.org/), 165 bytes
```
function f(a:Array of Integer):integer;var i,n,c:Integer;begin
i:=1;c:=1;f:=1;n:=High(a)+1;for i:=1 to n do begin
if a[i-1]<>c then f:=0;c:=Trunc(c*(n-i)/i);end;end;
```
[Try it online!](https://tio.run/##TU67DsIwDNz5Co8JtIUiYEgoEhvsbBVDCEmxhBwUAhVfXxxgYLiTddY9buZuzbX0NzsM/kE2YSDwwqhtjOYFwcOekutclAq/h36aCFhQYdXvpU@uQxqhamptM/lMpJoddhdh5ISVwB5WIQUgOAf4WTyYFsv6uN5YSBfH1aqZ5ZBD5DHCjgWVKKcotaPzB0Ouj6FXYPLCtq6q5fFvJzQg6mJRrBhzqUffIgDoIyYnvGCvZJ2zquEN "Pascal (FPC) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), ~~45~~ 44 bytes
```
sub{$n=$q=1;!grep$_-$n|($n*=@_/$q++-1)*0,@_}
```
[Try it online!](https://tio.run/##ZY/dCoMwDIXvfQonYfgTt7azDiYF30Q20O1CRK0OZNuzd@28sR05hJyEhC99PbZcQSOUnG8v6AQMgha7@1j3UKXQvUPoYlFWRxiSJKVRTLCsPqrwZln7T36gpPDkdfGDaZynx3IJVruHJqTRpkaGtj/psDscKTHiTj9HypERk3NndEamL3EjZpyZrjjNtZUWDbMWNc/GE8x0EJeX/EEzDZ1pwNx5ha/cv4/UFw "Perl 5 – Try It Online")
A translation of the JavaScript answer from @Arnauld.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 20 bytes
```
a->a==binomial(#a-1)
```
When `binomial` takes only one argument, it returns the `n`'th row of the Pascal's triangle.
[Try it online!](https://tio.run/##PY7BCsMgDIZfRbqLQgTNpjvZF5Ee0kOL0HVSdunTO1PdSMifP5B8yXQkveayiFBIjxTCnPb3K9Emb6StKpTzdkoSehT5SPuntgObQSySlIIY7QTRAkLTe43WObCG03XvwTpAw9X30ROwbjhOZMdTbOeu2hThih/G/FlYWY9633eyazh@YFLlCw "Pari/GP – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 51 bytes
```
->l{l.all?{r=0;*l,r=l.map{|x|r=x-r};r==(l[0]?0:1)}}
```
[Try it online!](https://tio.run/##ZYxBCoMwEEX3PUVXJUoMpqkuKqkHCVmoGAiM0aYKFs3Z04CbSBkG/vs8vl3ar1fcZy/YgDQA9WZ5XqWALQcyNNO2r7vla2ZdZTlHIHJZ50@aOOenqxKCSnk5Ao7iPQYWLsIHLsOfZBaKIhrCx1hgJFJKSCnTIiHdOLTaNLMeDQr46aHvZnRTCVmMfscyO8vsT/Y/ "Ruby – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-x`, ~~20~~ 14 bytes
```
L#al+:lPE!ll=a
```
[Try it here!](https://replit.com/@dloscutoff/pip) TIO doesn't support the `-x` flag, but you can simulate it using the header: [Try it online!](https://tio.run/##K8gs@B9mlfjfRzkxR9sqJ8BVMSfHNvH////RhgrGQGgYCwA "Pip – Try It Online")
### Explanation
We generate the nth row of Pascal's triangle, where n is the length of the input list; then we output truthy if the row and the input are equal, falsey otherwise. Heavily based on [my answer to Generate Pascal's triangle](https://codegolf.stackexchange.com/a/211994/16766), which I recommend you read for a better explanation of the core algorithm.
```
a is 1st cmdline arg, evaluated (-x flag); l is empty list
L Loop
#a len(a) times:
!l 1 if l is empty, 0 otherwise
lPE l with that value prepended
l+: Add to l itemwise and assign back to l
l=a 1 if l equals a, 0 otherwise
```
[Answer]
# [Python 3.8 (pre-release)](https://www.python.org), 71 68 bytes
```
lambda l:[*map(math.comb,(a:=len(l))*[a-1],range(a))]==l
import math
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/PycxNyklUSHHKlorN7FAIzexJEMvOT83SUcj0co2JzVPI0dTUys6UdcwVqcoMS89VSNRUzPW1jaHKzO3IL@oRAGk4f9/AA "Python 3.8 (pre-release) – Try It Online")
Using some list expansion shenanigans, it can be slightly shorter.
Old answer:
```
lambda l:list(map(math.comb,(a:=len(l))*[a-1],range(a)))==l
import math
```
[Try it online!](https://tio.run/##BcExDoAgDADA3VcwtgQH40bCS4xDVRSSFgh28fV41z5NtaxjMMlxkWHP@VUQanBWORyQDxwLMKLdaF5216k8EQgRQ@Dp7lWMkCaTpdWudowf "Python 3 – Try It Online")
Happily, Python has a built-in combination function. This just uses a simple mapping of that to build the row of Pascal's triangle corresponding to the length of the input list and compares that to the input.
[Answer]
# [Desmos](https://desmos.com/calculator), ~~62~~ 48 bytes
*Thanks Bubbler for -14 bytes.*
The function \$f(l)\$ takes in a list of numbers, and returns `0` for falsey, `1` for truthy.
```
a=length(l)-1
f(l)=\min(\{l=\nCr(a,[0...a]),0\})
```
[Try It On Desmos!](https://www.desmos.com/calculator/liygyhonhy)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/yovievs2dn)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes
```
⬤θ⎇κ⁼×⁻Lθκ§θ⊖κ×κι⁼¹ι
```
[Try it online!](https://tio.run/##LYw9C8JAEET/ypW7cBYBsbEKaCEoWKQLKY7LYo7brNxHRH/9eYkWM/AY3tjJRPs0XMo9OsnQMkPQqqMoJn7Aa3UOi@EEnZspwc3JkuBK8sgTBNTK17T5IiO9V@9ENtJMkmkEj1jHn1d/3Er/s2ZDxGMpfV9hr9Vh62YYyu7FXw "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` if it's a row, nothing if not. Explanation: The first element must always be `1`. Subsequent elements obey the recurrence relation that the previous element multiplied by the inclusive number of elements remaining equals the current element multiplied by its index.
```
θ Input array
⬤ Do all elements satisfy
⎇κ If not first element then
§θ⊖κ Previous element
√ó Multiplied by
⁻Lθκ Number of elements remaining
⁼ Equals
×κι Current element multiplied by its index
⁼¹ι If first element then it is `1`
Implicitly print
```
] |
[Question]
[
**Input:**
a positive number \$n\$, smaller than \$80\$, from stdin or as a command-line argument.
**Output:** A square chessboard pattern, the size of the input number. The dark fields are represented by the letter `X`, the white fields by a space. The top-left field should be `X`.
A complete program is required. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins
---
**Examples:**
**Input**: 1
**Output**:
```
X
```
**Input**: 8
**Output**:
```
X X X X
X X X X
X X X X
X X X X
X X X X
X X X X
X X X X
X X X X
```
[Answer]
## Golfscript - 17 chars
```
~:N,{"X "N*>N<n}%
```
Analysis
`~` convert input to an int
`:N` store in the variable N
`,{...}` for each value of [0...N-1]
`"X "N*` repeat "X " to give a string of N\*2 characters
`>` take the substring starting from the loop index...
`N<` ...ending N characters later
`n` put a newline a the end of each string
[Answer]
# Pyth, 13 chars
Note: Pyth is much too new to be eligible to win. However, it was a fun golf and I thought I'd share it.
```
VQ<*QX*d2N\XQ
```
[Try it here.](https://pyth.herokuapp.com/)
How it works:
```
Q = eval(input())
VQ for N in range(Q):
< Q [:Q]
*Q (Q* )
X*d2N\X assign_at(" "*2, N, "X")
```
Basically, this uses `X` to generate `"X "` or `" X"` alternately, then repeats that string `Q` times, and takes its first `Q` characters. This is repeated `Q` times.
How does the `X` (assign at) function work? It takes the original string, `" "` in this case, an assignment location, `N` in this case, and a replacement character, `"X"` in this case. Since Pyth's assignments are modular, this replaces the space at location `N%2` with an `X`, and returns the resultant string, which is therefore `"X "` on the first, third, etc. lines, and `" X"` on the others.
[Answer]
## Perl, ~~41~~ 40
```
for$i(1..$_){say substr" X"x$_,$i%2,$_}
```
Perl 5.10 or later, run with `perl -nE 'code'` (`n` counted in code size)
Sample output:
```
$ perl -nE'for$i(1..$_){say substr" X"x 40,$i%2,$_}' <<<5
X X X
X X
X X X
X X
X X X
$ perl -nE'for$i(1..$_){say substr" X"x 40,$i%2,$_}' <<<8
X X X X
X X X X
X X X X
X X X X
X X X X
X X X X
X X X X
X X X X
```
[Answer]
### Python, 48 Characters
```
x,i=input(),0
exec'print(x*"X ")[i:i+x];i^=1;'*x
```
[Answer]
## Python, 76 characters
```
n=input()
p='X '*n
print n/2*(p[:n]+'\n'+p[1:n+1]+'\n'),
if n&1:print p[:n]
```
[Answer]
## Scala - 141 95 characters
```
var a=args(0).toInt
for(y<-1 to a;x<-1 to a)print((if((x+y)%2<1)"X"else" ")+("\n"*(x/a)take 1))
```
Usage: `scala filename N` where n is your input to the program.
[Answer]
## APL (16)
Assuming `⎕IO=0` (i.e. zero-indexed arrays, it is a setting)
```
' X'[=/¨2⊤¨⍳2⍴⎕]
```
Explanation:
* `⍳2⍴⎕`: read a number N, and create a N×N matrix containing (0,0) to (N-1,N-1).
* `2⊤¨`: get the least significant bit of each number in the matrix. (So now we have (0,0), (0,1), (0,0)... (1,0), (1,1), (1,0)...)
* `=/¨`: for each pair, see if the two numbers are equal. (Now we have 1 0 1 0 1 0 ...)
* `' X'[`...`]`: put a space for each 0 and an X for each 1.
[Answer]
## Ruby ~~45~~ 42
```
(x=gets.to_i).times{|i|puts ("X "*x)[i,x]}
```
Demo: <http://ideone.com/Mw25e>
[Answer]
# Brainfuck, 140 bytes
```
-[+[+<]>>+]>++++[<++++++++>-]<<<<<<,[->+>+>+<<<]>>[->[->.<[->>.>]<<<]<[<<<]>>>>>[-<+>]>[-<+>]<<[->>+<<]<<[-<+>]<[->+>>+<<<]++++++++++.[-]>>]
```
[Answer]
## C++ - 253 obfuscated characters
```
#include <iostream.h>
int main(int i,char*c[]=0)
{
char a=i,b=i>>8;i&32512?((i>>16&255)<a)?(cout<<b)?main((i^30720)+65536):0:(cout<<endl)?(((b=(i>>24)+1)<a)?main((i&2130706559)+((b&1)?16785408:16799744)):0):0:main((i>=2?atoi(1[c]):8)|22528);
}
```
[Answer]
# JavaScript, 169
```
function b(w){var i=w,j=w,r='';while(i--){while(j--){if((i+j)%2)r+=' ';else r+='X'}j=w;r+="\n"}return r}do{n=parseInt(prompt('Number'))}while(isNaN(n)||n<1);alert(b(n));
```
[Answer]
# k (26 chars)
26 For bare function:
```
{-1',/x#',x#'("X ";" X");}
```
Or a further 7 to take input from stdin
```
{-1',/x#',x#'("X ";" X");}"I"$0:0
```
[Answer]
# Bash: 60 characters
```
yes X|fmt -w80|paste -d '' <(yes '
') -|head -$1|cut -c1-$1
```
The table size is passed as command-line parameter, for example `bash chesstable.sh 8`.
[Answer]
# Java 10, lambda function, ~~92~~ ~~87~~ 84 bytes
```
n->{for(int i=0;i<n*n;)System.out.print(((i%n+i/n)%2<1?"X":" ")+(++i%n<1?"\n":""));}
```
Try it online [here](https://tio.run/##lY9BawIxEIXP2V8xBITExa1bEKSr7cGzJy9C20PMRju6TpYkCkX2t2@z2x5swYKnYd6b983MXp3VyNaG9uWhrU@bCjXoSnkPS4UEl4QhBeO2ShtYfBh9MG5jlSs7h50tltC3Ik4BySJhTcJ@MD6oEEs/dIwwsQoOaff6DsrtvOwJv5D6uplDS6Pny9a6no3zcYEzGlIhV58@mGNmTyGrIzAIIXBAKT6QHDzO8he@5k8cuExFmkajU94oSlzKomkZi0ey61XZ9wd5dz37C69IyBuB6b2BfPJfokma9gs).
Thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) for golfing 4 bytes and to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) for golfing 3 more.
Ungolfed version:
```
n -> { // void lambda taking an int as argument
for(int i = 0; i < n*n; ) // loop over the entire square
System.out.print(((i%n + i/n) % 2 < 1 ? "X" : " ") // print an 'X' or a space depending on which line&column we're on
+ (++i % n < 1 ? "\n" : "")); // print a newline at the end of a line
}
```
# Java 8, full program, ~~155~~ 139 bytes
```
interface M{static void main(String[]a){int i=0,n=new Byte(a[0]);for(;i<n*n;)System.out.print(((i%n+i/n)%2<1?"X":" ")+(++i%n<1?"\n":""));}}
```
Try it online [here](https://tio.run/##FYtPC4IwFMC/yhgIWyuzTtGUoHsnL4F5GDrlGb6JvgwRP/ta19@fzszm4AaLXf32HpDs2JjKssc6kSGo2OygZr0BFDmNgG1RGrmGjkGW7DFD@2X3hawwRVJK3bhRaEhxh1rmy0S2j92H4iGcJISACBUcUUbn9HTjT37ljEsllAriT14YEJdSb5v3/vID).
Ungolfed version:
```
interface M {
static void main(String[] a) {
int i = 0, // iterator variable for the loop
n = new Byte(a[0]); // take the argument and convert it to an int
for(; i < n*n; ) // loop over the entire square
System.out.print( ((i%n + i/n) % 2 < 1 ? "X" : " ") // print an 'X' or a space depending on which line&column we're on
+(++i % n < 1 ? "\n" : "") ); // print a newline at the end of a line
}
}
}
```
[Answer]
# Japt, ~~8~~ 7 bytes
```
ÆîSi'XY
```
[Run it online](https://ethproductions.github.io/japt/?v=1.4.6&code=xu5TaSdYWQ==&input=OAoKLVI=)
**~~7~~ 6 bytes** if we can replace `X` with `x`:
```
ÆîSixY
```
[Run it online](https://ethproductions.github.io/japt/?v=1.4.6&code=xu5TaXhZ&input=OAoKLVI=)
---
Alternative **8 byte** solution:
```
Æî"X "éY
```
[Run it online](https://ethproductions.github.io/japt/?v=1.4.6&code=xu4iWCAi6Vk=&input=OAoKLVI=)
[Answer]
# [Python 2](https://docs.python.org/2/), 47 bytes
```
n=input()
s='X '*n
exec"print s[:n];s=s[1:];"*n
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P882M6@gtERDk6vYVj1CQV0rjyu1IjVZqaAoM69EoTjaKi/Wuti2ONrQKtZaSSvv/39TAA "Python 2 – Try It Online")
---
**[Python 2](https://docs.python.org/2/), 47 bytes**
```
n=input()
i=0
exec"i^=1;print'X'*i+n/2*' X';"*n
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P882M6@gtERDkyvT1oArtSI1WSkzztbQuqAoM69EPUJdK1M7T99IS10hQt1aSSvv/39TAA "Python 2 – Try It Online")
Trims trailing space.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 12 [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. Requires `⎕IO←0` (zero-based indexing).
```
'X '⊇⍨2|⍳+⍀⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/9UjFNQfdbU/6l1hVPOod7P2o94GIPU/DSj5qLcPoq6r@dB640dtE4G84CBnIBni4Rn8P03BkEtXV5crTcEUSlsAAA "APL (Dyalog Extended) – Try It Online")
`⍳` **ɩ**ndices 0…n–1
`+⍀` plus table with that horizontally and vertically:
`⍳` **ɩ**ndices 0…n–1
`2|` division remainder when divided by two
`'X '⊇⍨` use that matrix to index into the string
[Answer]
# Scala, 68 bytes
```
def^(n:Int)=for(a<-1 to n)println(("x_"*n).substring(n%2+1,n+n%2+1))
```
or
```
def^(n:Int)=for(a<-1 to n)println(("x_"*n).substring(a%2+1).take(n))
```
[Try it online!](https://tio.run/##NcrBCoJAEADQe18xCMJMobgdIw8d@wlj1FEqmV3cCQTx2zcvXh8vdjxx8u1HOgMPsphoH@ERAqypl6FBvT3VqB78jHwvHJgHpTC/1SZFzJZXdlYq46@NtuOInF8vjkrjr6ASpaM26Cqi05b@ "Scala – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 9 bytes
```
:&+o~88*c
```
[Try it online!](https://tio.run/##y00syfn/30pNO7/OwkIr@f9/CwA "MATL – Try It Online")
ASCII `c` 88 multiplied `*` by not `~` the parity `o` of the broadcast self-addition `&+` of the range `:` from 1 to the input.
[Answer]
## Javascript, 67 bytes
```
for(j=n=readline()|0;j--;)console.log(' X'.repeat(n).substr(j%2,n))
```
[Try it online](https://tio.run/##y0osSyxOLsosKNEts/j/Py2/SCPLNs@2KDUxJSczL1VDs8bAOktX11ozOT@vOD8nVS8nP11DXSFCXa8otSA1sUQjT1OvuDSpuASoT9VIJ09T8/9/QzMuAA)
## C, 83 bytes
```
i,j;main(n){for(scanf("%d",&n);i++<n;puts(""))for(j=0;j<n;)putchar(i+j++&1?88:32);}
```
[Try it online](https://tio.run/##S9ZNT07@/z9TJ8s6NzEzTyNPszotv0ijODkxL01DSTVFSUctT9M6U1vbJs@6oLSkWENJSVMTpCLL1sA6CyioCRRNzkgs0lBSiFCKztTO0tZWM4zVtK79/98CAA)
## Basic C64, 89 bytes
```
1 INPUTN:FORI=1TON;FORJ=1TON:IFI+JAND1THENPRINT" ";:GOTO3
2 PRINT"X";
3 NEXT:PRINT"":NEXT
```
[](https://i.stack.imgur.com/5eaOo.png)
[Answer]
# Scala, 40 and 54
The number of characters is 40 for a function, 54 for a complete program.
**The solution giving only a function body is:**
`("X "*n)sliding n take n foreach println`
[Try it online](https://tio.run/##PccxCgIxEAXQfk7x2Sqx02oRLCytbWzHZEajcTZsUgji2aMLYvV4NXDmPp1vEhqO/ChZIM8mFiv2peBFFEWhzrY4WPPYobvhhGFlvuYUk11gaHyXLzrNwuGKMidr2bq6tadfiNRt/sPS0dO7fwA)
**The solution giving a complete program is:**
`val n=readInt;("X "*n)sliding n take n foreach println`
You can run it using the following command line.
`scala -e 'val n=readInt;("X "*n)sliding n take n foreach println' <<< 8`
where 8 is the input.
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 249 bytes
```
>-[-[-<]>>+<]>->+++>-[<+>---]+>>>>>>+[[-]>,[>++++++[<-------->-]<<<[->>++++++++++<<]>+>[-<<+>>]]<]<[<+<+>>-]<<[->[->+<<<+<[<<<.>>>->-<]>[<<<.>>+>-]>>]++++++++++.[-]>[<+>>+<-]>>++<[>->+<[>]>[<+>-]<<[<]>-]>[-]>-[<<<<<<<[>+<[-]]+>[<->-]>>>>>>[-]]<<<<<]
```
[Try it online!](https://tio.run/##RY9BCsMwDAQfpCjnHIQ@InRoA4VS6KHQ97uzjqHrWNiSPNrcP7fn@/E9X2OkFys60wieZkYqCO5tOWVV3rmViqjCl9I7IspzVaQAYwkSRnZHBzSd1UsrHz2kirhDh8KTdWMuVvqP2zVafnilEgNKNolXfmJlnSvbBZJKPd78A34nVVJmlnuM4wc "brainfuck – Try It Online")
Could definitely be golfed more.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~90~~ ~~88~~ ~~83~~ 82 bytes
-2 thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)
And -5 more by [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat). Iterate backwards for extra confusion!
Another -1 by [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat). Iterate using negative integers for extra confusion!
```
m;main(n,v)int**v;{for(n*=m=~(n=atoi(v[1]));n++;)putchar(n%m?n%m-n/m&1?88:32:10);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z/XOjcxM08jT6dMMzOvREurzLo6Lb9II0/LNte2TiPPNrEkP1OjLNowVlPTOk9b21qzoLQkOSMRqEI11x6IdfP0c9UM7S0srIyNrAwNNK1r////bwEA "C (gcc) – Try It Online")
**Ungolfed**
```
m;
main(n, v) int**v;
{
for (n *= m = ~(n = atoi(v[1])); n++;)
putchar(n % m ? n % m - n / m & 1 ? 88 : 32 : 10);
}
```
[Answer]
## Python - 127 characters
```
from sys import*
r=stdout.write
s=int(raw_input())
[[r((x+y+1)%2 and"x"or" ")for x in range(s)]and r("\n")for y in range(s)]
```
[Answer]
## C - 92 86
```
i,j;main(n){for(scanf("%d",&n);i<n;puts(""),i++)for(j=0;j<n;j++)putchar("X "[i+j&1]);}
```
[Answer]
## Python
**48 Chars**
**EDIT:** Kinda Wrong...There's an extra space at the end...but thats not visible. If you change the space to "O" (or any nonwhitespace char) then modify `[i%2:n]` to `[i%2:n+i%2]`. for the correct version.
```
n=input()
i=0;
while i<n:print('X '*n)[i%2:n];i+=1
```
[Answer]
# Q, 33
```
{$[1=x mod 2;x;x-1]cut(x*x)#"X "}
```
[Answer]
## Ruby 58
```
i=ARGV[0].to_i
1.upto(i*i){|n|print n%i==0?"\n":' x'[n%2]}
```
[Answer]
## PHP - 136 chars (without whitespace)
Allows for x and y function input.
*Also supports odd inputs now.*
If you style the output to have 0.65 em line-height and change this ▒█ and █░ to □■ and ■□ then it comes out looking like a real (square) chessboard.
## Code:
```
function gen_cb($x,$y)
{
$c=0;
$y*=2;
for($i=0;$i<$y;$i++){
for($j=0;$j<$x;$j++){
echo $c%2==0 ? "░█" : "█░";
}
echo "<br/>";
$c++;
}
}
gen_cb(7,7);
```
## Output:
```
░█░█░█░█░█░█░█
█░█░█░█░█░█░█░
░█░█░█░█░█░█░█
█░█░█░█░█░█░█░
░█░█░█░█░█░█░█
█░█░█░█░█░█░█░
░█░█░█░█░█░█░█
```
[Answer]
## PHP, 87
```
for($x=0;$x<$m=$argv[1];$x++){echo"\n";for($y=0;$y<$m;$y++)echo($y^($x%2))%2?' ':'X';}
```
] |
[Question]
[
# Context
Consider the following sequence of integers:
$$2, 10, 12, 16, 17, 18, 19, ...$$
Can you guess the next term? Well, it is \$200\$. What about the next? It is \$201\$... In case it hasn't become obvious to you, this is the sequence of positive integers whose name starts with a letter `D` in Portuguese.
# Task
Given a positive integer \$n\$, decide if it belongs in the sequence or not. An algorithm to do so is given next to the Output section.
# Input
A positive integer \$n\$, no greater than \$999999999\$.
# Output
A truthy/falsey value, representing whether or not the input belongs in the sequence. Truthy if it does, falsey if it doesn't. Truthy/falsey can't be switched for this challenge.
For \$0 < n < 10^9\$, here's how to determine if \$n\$ is part of the sequence. If \$9 < n\$, say \$ab\$ are its two leading digits, so that if \$n = 583\$, \$a = 5\$ and \$b = 8\$. If \$n < 10\$ then \$a = n\$. Let \$k\$ be the number of digits of \$n\$, so that if \$n = 583\$, \$k = 3\$. \$n\$ is in the sequence if any of these hold:
* \$a = 2\$ and \$k = 1, 3, 4, 6, 7, 9\$;
* \$ab = 10, 12, 16, 17, 18, 19\$ and \$k = 2, 5, 8\$
Please notice that standard loopholes are forbidden by default, in particular trivialising the challenge by using a language with a trivial numeric type.
(The rules above generalise trivially for \$n\$ arbitrarily big but I capped the input for simplicity)
# Test cases
## Truthy
```
2
10
12
16
17
18
19
200
201
223
256
10000
10100
10456
10999
12000
12180
12220
16550
17990
18760
19000
200000
212231
256909
299999
10000000
10999999
12000000
12999999
16000000
16562345
16999999
17000000
17999999
18000000
18999999
19000000
19999999
200000000
200145235
200999999
201000000
245345153
299999999
```
## Falsy
```
1
3
4
5
6
7
8
9
11
13
14
15
20
100
1000
1200
1600
1738
1854
1953
20000
21352
120000
160000
170000
180000
190000
20000000
100000000
120000000
160000000
170000000
180000000
190000000
999999999
```
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest submission in bytes, wins! If you liked this challenge, consider upvoting it! If you dislike this challenge, please give me your feedback. Happy golfing!
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 42 bytes
Of course there is a built-in for this...
And as @Charlie mentioned we can golf `"Portuguese"` to `"Spanish"` and save 3 bytes
```
#~IntegerName~"Spanish"~StringTake~1=="d"&
```
[Try all test cases](https://tio.run/##dVGxasMwEN3zFcWFTheikyxZNxgyFbqUlmQLGURrbNM6lEQZSql/3T3LkjJV4MfxTnp373lwvmsG5/s3N7X1dD8@nXzTNudnNzRjsftyp/7SFePOn/tTu3cfzYh1XbwXD9MLM/5QrNfr/fnqu28uiuPq9do3/hB6d5ttu9n@SEAByGgAK0ALSCCF4A9BSgVSc0PwYcSAZWCIiJ8FXqKdUUpGozVjRcRoK8NIIqgFCcm3FM6aJHgMUVARy1lEs@4inRiTGKONVKXmIrWq1KoSYxNjE0OJocjECctqWGqp9FzlLqZuqXkaagWruAvR73F1S/fRfV7@DRdBQQkaDFRggfdAQAVYAs7TYMkz@AzWggnFv8BqvkI8VMbYlJYxlRhFtB29RoPZVc5U5CxFzlDkyESOSuSIBNDN5zT9AQ "Wolfram Language (Mathematica) – Try It Online")
-13 bytes from @att
[Answer]
# perl -plF, 55 41 bytes
Using ideas from @Dom Hastings, and eliminating common expressions:
```
$x=@F=~/[258]/;$_=/^2/&!$x|/^1[026-9]/&$x
```
[Try it online!](https://tio.run/##PVBBagMxDLzrF4Ult2BJtmyLstBTPhGSnnoohGZpe9hDydOzlb22DR7skT0azfLxfZNtm9b57TQ/3JklX9zr9D67K7vDy7T@uSudkeNRL@4wrdvGQAhkGIESUAZSYETbBMweWKyAtgypYqiMqtq3yjPlgsyGUcQwqRrmFA0Vq1qVYHvlqWgqWhvVqoL72kWH7i7dmdiZKJF9EDv0Uuql1JncmdwZ7Yw2pnXYrVEQ9lJOo0q9GsS6kfjmtqqBhwACERJksDsBeaAAVDRgT6m6r4arNW/BZrEnWqRaGF64zdoGbMO0CZrt4XUkhSMhHMngCAJHADgGR@ju9Xlffj/vXz/bcbmd/gE "Perl 5 – Try It Online")
## How does it work?
Due to the `-F` option, the input is split on characters which are put in the array `@F`. So, if we use `@F` in scalar context, we have the length of the number.
First, we set `$x` to true if the number contains 2, 5, or 8 digits (it's given the number is at most 9 digits).
The rest is straightforward. We check whether the number starts with `2`, and does not contain 2, 5, or 8 digits, or whether it starts with `10`, `12`, `16`, `17`, `18`, or `19`, and contains 2, 5 or 8 digits.
[Answer]
# [Python 2](https://docs.python.org/2/), 48 bytes
```
lambda n:988164-2**200>>n/1000**(len(`n/3`)/3)&1
```
[Try it online!](https://tio.run/##PVBda8MwDHzXr@jTSAIjkvypwvpL9tCWtbSQOmV0jP36THFsG3w4J@V0uuff6zYnXq4fn8t0epy/Tru0lxjJ23ceBkY8HNJIiDgM3XRJ3TGN5tiPpn@j5fd2ny472j@/7@m1O8/z1F27e3r@vLq@7xcGQiBFDxSAIpCACuolYDbATguqrE1IGW1mRER/yzxTXJFZ0TunGEQUY/CKglktS7B2GVo1BXWMSFbB7WyiTXeTroyvjHeejXX6qKVQS6EysTKxMlIZKUyZsFkj69i49dWqVKvW6TRyprjNamDAggMPASLoNwEZIAu0asCWUnafDWdrRoONTltklSphGMdl17JgWaZsUGw3ry0pbAlhSwZbENgCwLY4gjT7/w "Python 2 – Try It Online")
**[Python 2](https://docs.python.org/2/), 50 bytes**
```
f=lambda n:f(n/1000)if n>299else 988164>>n&1|n/200
```
[Try it online!](https://tio.run/##PVDLboQwDLz7KzhVcFrbeRCvVP5lVwUtEg2rLVVVqf9OTUiCxCgZO@PxPH@3xxp536f35fZ5/7g18Tq18UKI2M1TEwcWGZevsZEQyNthiG/0Fy@MuP885mVs6Pp8zXFr7uu6tFM7x@f31nZdtzMQAil6oB4oAAnoM/0JmA2w04KO0SakhDYxIqLPEs8UDmRW9M4p9iKKofeKgkktSbB2GTo0BXWMSFLB8ztFq@4pXRhfGO88G@v0UEp9KfWFCYUJhZHCSGbyhNMaWcfGHadapVK1TqeRM9ltUgMDFhx46CGA3gnIAFmgQwPOlJL7ZDhZMxpscNoih1QOwzjOu@YF8zJ5g2y7eq1JYU0IazJYg8AaANbFEaTa/wc "Python 2 – Try It Online")
An arithmetic solution. Chomps down `n` to a three-digit number by repeatedly removing the last 3 digits. Then, checks that the remaining three-digit number is one of `[2,10,12,16,17,18,19]`, or is between 200 and 299.
The `[2,10,12,16,17,18,19]` is checked against the set bits of a binary number, `988164`.
The `200≤n<300` check is simplified by making the `≥300` case never happen. We keep chomping groups of 3 digits if the number is at least 300 (rather than at least 1000), making the 300-999 case go to 0. This leaves us with a `200≤n` check that we do simply as `n/200`.
You might wonder why the `if/else` isn't shortened to `and/or` as usual, but the output potentially being truthy or falsey doesn't play nicely here.
**53 bytes**
```
import re
re.compile("(2|1[026-9]|2..)(...)*$").match
```
[Try it online!](https://tio.run/##PVDLasQwDLzrK8LSg1NokOTYsQr9ktJDu@yygc2DNKUU9t9TxbFtyOCM5NFo5r/1No28bf0wT8taLRe4vi2X5jwNc3@/mJPhB70j@xf5eHDT1KZReH461c3wuZ5v2@9N2yp6nZd@XKuvabqbq/leF9OP889qaj0bAyGQogfqgAKQACPqR8BsgZ0WUI8iRWwjIyL6LPJMYUdmRe@cYieiGDqvKBjVogRrl6VdU1DHiEQVPM4hWnQP6cz4zHjn2bZOL7nU5VKXmZCZkBnJjCQmTTisUevYuv1WqpSrrdNp5GxyG9XAQgsOPHQQQP8JyAK1QLsGHClF99FwtGY12OC0RXapFIZ1nHZNC6Zl0gbJdvFaksKSEJZksASBJQAsiyNIsf8P "Python 2 – Try It Online")
Porting [Neil's Retina solution](https://codegolf.stackexchange.com/a/213695/20260). Takes input as a string. Thanks to n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ for saving a byte and Sisyphus for saving two.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~25~~ ~~21~~ ~~20~~ ~~19~~ 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
2Ž Ć.¥T+ªƵžIgåèÅ?à
```
-1 byte thanks to *@ovs* and -1 byte after being inspired by *@ovs* in the comments
[Try it online](https://tio.run/##yy9OTMpM/f/f6OhehSNteoeWhmgfWnVs69F9numHlx5ecbjV/vCC//8NLS0NgcAIAA) or [verify all test cases](https://tio.run/##PVA7TkQxDLzK07ZYyHbiJK7eJegQBUgIUVEgIb0DsAfgBNushOgpodjHchAu8nC@kTJKxsl4PE/Pt3eP99vLMu@mv/3btJuXjc9f08/@8nS8ujh9/H6ev5eH9bi@r6/zethgu2YgBDIMQBEoASkwom0CZgcsVkBbhlTQF0ZV7VvhmVJGZsMgYhhVDVMMhopFrUiwvXKUNRWtjWpRwbqq6NCt0p0JnQkS2HmxQy/FXoqdSZ1JndHOaGNah2qNvLCTfBpV6lUv1o3ENbdFDRx4EAgQIYHdCcgBeaCsATWl4r4YLtacBZvEnmiWamE44TZrG7AN0yZotofXkRSOhHAkgyMIHAHgGByhu9ebfw).
**Explanation:**
```
2 # Push a 2
Ž Ć # Push compressed integer 24111
.¥ # Push the cumulative sum of its digits with 0 prepended:
# [0,2,6,7,8,9]
T+ # Add 10 to each: [10,12,16,17,18,19]
ª # Append it to the 2: [2,[10,12,16,17,18,19]]
Ƶž # Push compressed integer 258
Ig # Push the input, and pop and push its length
å # Check that this length is in 258 (1 if truthy; 0 if falsey)
è # Use that to 0-based index into the list [2,[10,12,16,17,18,19]]
# ([10,12,16,17,18,19] if truthy; 2 if falsey)
Å? # Check whether the (implicit) input starts with any of these
# values (or the 2)
à # And pop and push the maximum of the top item,
# which is either already 1 or 0 if it was 2,
# or the maximum of the list of truthy/falsey values if not
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (sections *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ž Ć` is `24111` and `Ƶž` is `258`.
[Answer]
# [R](https://www.r-project.org/), ~~57~~ 56 bytes
```
substr(n<-scan(),1,2^!nchar(n)%%3<2)%in%c(2,10,12,16:19)
```
[Try it online!](https://tio.run/##K/r/v7g0qbikSCPPRrc4OTFPQ1PHUMcoTjEvOSMRKKipqmpsY6SpmpmnmqxhpGNooGMIJM2sDC01/xsaGRib/P8PAA "R – Try It Online")
Note that `2^!nchar(n)%%3<2` is equal to `2` when `nchar(n)%%3==2`, and equal to `1` otherwise.
Extract either the first, or the first 2, digits of `n` (depending on the value of `nchar(n)%%3`), and check whether the result is in `c(2,10,12,16,17,18,19)`.
Works for arbitrarily large input.
[Answer]
# JavaScript (ES6), ~~51 47~~ 46 bytes
```
n=>(730>>n.length^n[0])&/^2|^1[^1345]/.test(n)
```
[Try it online!](https://tio.run/##fVJNa4NAEL3nV2wvVenU7Oy66ga0p@bSQyHkFhIIqUlaREu0gUD/ezquu9uPQwd8Lm/WN/Mevm3P2253en3v75v2pbrui2tTlGEmeVk2cV01h/64aVZ8Hd1ON@Jzg6sNykStp3FfdX3YRNclK9hKAHJAwhQwA8wBNQjO6UEQQoJQ1OBUhGgwMYzWmj4zvMB8QCEIU6UIM60J8ywl1NyoGQlBtyQOmprTGK2NCh9rFPW6o7RjUsekKhVkgw6ulblW5pjcMbljtGO0ZeyEcTVMlJBqOPkuum6iaBoqabelWk/mQ3AIEhJQkEIGOdAMBJSACeCgBGNWxoNZ2ywoKd5c0RU9CNpIpBLWsbVpLVkfdnm/sc@L@5y4z4f7OLiPgXv7HPS3icmubbq2ruK6PYTB8vTRHy9s@DXYbttV3SwAtoyrc3W6hA0rSran1x0LgihiDyx4fgrYjAWPi8XzIoh@a823dfdXav5T6uY/resX "JavaScript (Node.js) – Try It Online")
### How?
\$730\$ is the bit-mask of valid lengths when the first digit of \$n\$ is \$2\$:
```
730 = 1011011010
^ ^^ ^^ ^
9876543210
```
Once it's been right-shifted by the number of digits, we XOR it with the first digit of \$n\$. Therefore, the least significant bit is left unchanged if the first digit is \$2\$ and inverted if the first digit is \$1\$. For other leading digits, we don't care about the result because the regex will not match anything anyway.
We either keep the least significant bit or discard it according to the result of the following regex:
```
/^2|^1[^1345]/
^2 // either a leading "2"
| // or
^1 // a leading "1" followed by ...
[^1345] // ... anything but 1, 3, 4 or 5
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 24 bytes
```
^(2|1[026-9]|2..)(...)*$
```
[Try it online!](https://tio.run/##PVBNTkYhDNzPOTR5mvjSFgr0BB7CaHThwo0L4/K7@/vKTyFhAlOYTufv@//n9@t6PF4/r49DbvxGUl7s/Sbn@XScDs8P1yVgAjsWcAU3sEGIfDNEEkS9QL4ceWAejJn5t8ELt44ijkXVsZo5tlocjYbakBB/lbhrGnkbs6FCc03RrTulgynBFC2SsvohSjVKNZgWTAvGgrHFrA7TGmeVpP20qxzVrN6NNS23Qw0JGYqCiga/MziBM7hrYKY03A/Dw1ryYJv6E@tSK4yksmZdA65h1gTL9va6k6KdEO1kaAdBOwDagxPCvd0B "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: The rules simplify to: Take the first base 1000 digit, which should be either 2, 10, 12, 16-9, or 200-299.
[Answer]
# [Haskell](https://www.haskell.org/), 52 bytes
```
(%)=div
f n|n>299=f$n%1000|r<-2^n=odd$n%200+988164%r
```
[Try it online!](https://tio.run/##PVDtasMwDPyvp/CPBVq2giR/xIJmT7BnGATSsrDOHdnYr757pji2DT6ck3I63cf483m53db10B2Haf6Dq0mP9Moiw/UpdYSIj@V84vc03KdJGUZ8lhgpuG5Zv8Y5mcFMdzDJnE9muYzTWwLzvczp1xzSi1G5I5itb2UgBFIMQD1QBBJQNb0EzBbYa0HnaRNSRpcZEdHfMs8UN2RWDN4r9iKKsQ@KglktS7B2Wdo0BXWMSFbB/eyiTXeXrkyoTPCBrfP6qKW@lvrKxMrEykhlpDBlwm6NnGfrt1erUq06r9PI2@I2q4EFBx4C9BBBvwnIAjmgTQP2lLL7bDhbsxps9Noim1QJw3ouu5YFyzJlg2K7eW1JYUsIWzLYgsAWALbFEap7@Qc "Haskell – Try It Online")
This is a translation of xnor's Python solution. They contributed a byte-save with `r<-2^n`, too!
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes
```
¬⎇﹪⊕Lθ³⌕θ2⬤026789⌕θ⁺1ι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMvv0QjJLUoL7GoUsM3P6U0J1/DMy@5KDU3Na8kNUXDJzUvvSRDo1BTU0fBGIjdMvNSNAp1FJSMlIA8x5wcDSUDIzNzC0slhFxATmmxhpIhUCRTEwys//83NDI2Mf2vW5YDAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Works by testing whether the string begins with either 2 or one of 10, 12, 16, 17, 18, or 19, depending on the number of digits in the string; Find() will return 0 if it does, which we then invert to provide the desired truthy answer. (And because we're working in negative logic, we actually use All() to see if any of the strings is found at position 0.)
```
θ Input as a string
L Length
⊕ Incremented
﹪ ³ Modulo literal `3`
⎇ If nonzero then
⌕ Index of
2 Literal string `2`
θ In input
⬤ Else map over characters
026789 Literal string
⌕ Index of
1 Literal string `1`
⁺ Concatenated with
ι Current character
θ In input
¬ (Any) zero
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-2 thanks to [Sisyphus](https://codegolf.stackexchange.com/users/48931)!
```
bȷḢbȷ2Ḣe“,-n’DĤ
```
**[Try it online!](https://tio.run/##y0rNyan8/z/pxPaHOxYBSSMglfqoYY6Obt6jhpkuh1sOLfn//7@RsYmpmbkFAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##PVAxTgQxDPzQINlOnMQ9v1hdg3QNOl1Pd0JIvAGJClHSQ801fIP9SM6bTWLtzkbj7Hg8j8fT6anWh7/v/58PR/HPcb284@68Xt7ury@/n/X6uj5/@VPrsgiYwI4JnMEFbBAifxkiAaLeIC9HbhgbY2b@W@OFy4YijknVMZs5lpwcjZpakxC/FXjTNPIxZk2F9tpFp@4uPZg0mKRJQlQ/jFYerTyYMpgyGBuMdaZP2K1xVAm6nWaXRzeqT2MN3a3XAQsjIEKRkFHg@gwO4AjeVLDn1Pw3y81c8GiL@hXbxHocQaVv21fs6/QduvHpdmZFMyOa2dCMgmYENFcn2FzgcAM "Jelly – Try It Online").
### How?
```
bȷḢbȷ2Ḣe“,-n’DĤ - Link: n
ȷ - 1000
b - (n) base (1000)
Ḣ - head -> x
ȷ2 - 100
b - (x) base (100)
Ḣ - head
¤ - nilad followed by link(s) as a nilad:
“,-n’ - 2824111
D - digits
Ä - cumulative sums -> [2,10,12,16,17,18,19]
e - exists in?
```
[Answer]
# [Zsh](https://www.zsh.org/), 37 bytes
```
>$#1$1
: (12|[34679]2|[258]1[^1345])*
```
[Try it online!](https://tio.run/##PVExbsMwDNz9igPqwc5EUqIkFkH7kDQdg2YoCiRb0b@7tCxJgA/0UT4ez7/Pr@22rMuyvc0vPPP0ioXl7xJiynb1QrRc@fLJIep1PW3rdD6fZ/7A/D49vnGa1un288Adi4AJ7JjAGVzABiHyhyESIOoN8uPIFWNlzMw/q7xw2VHEMak6ZjPHkpOjUVWrEuK3Au@aRj7GrKrQcQ7RoXtIdyZ1JmkSX8qL3sq9lTtTOlM6Y52xxrQJhzWOKkH3anS5d6P6NNbQ3FY1BEQoEjIK/J3BARzBuwaOlKr7arhaCx5sUb9iu1QLI6i0XduCbZm2QbM9vI6kaCREIxkaQdAIgMbihO7e/M9jvm// "Zsh – Try It Online")
Outputs via status code (`0` = is in sequence, `1` = is not in sequence).
Explanation:
* `>` - create the file
+ `$#1` - the length of the input
+ `$1` - followed by the input itself
* `(12|[34679]2|[258]1[^1345])*` - try to find a file matching this pattern:
+ `(||)` - one of:
- `12` (the literal input `2` which is of length `1`)
- `[34679]2` - any character from the set `34679`, then a `2`
- `[258]1[^1345]` - any character from the set `258`, then a `1`, then any character except one from `1345` (shorter than `026789`)
+ `*` - followed by any string
+ this will produce an error if there is no file
* `:` - and then do nothing with that file (this is required because otherwise `()` would be treated as a sub-shell)
[Answer]
# [Ruby](https://www.ruby-lang.org/) + `i18n` + `numbers_and_words`, ~~96 93~~ 91 bytes
```
require'i18n'
require'numbers_and_words'
I18n.with_locale(:pt){p gets.to_i.to_words[0]==?d}
```
[Try it on repl.it!](https://repl.it/join/wdtvwtgv-razetime)
It's probably longer than a simple pattern matching solution, but I wanted to try it anyway.
-3 bytes from ovs.
-2 bytes from Dingus.
[Answer]
# [Scala](http://www.scala-lang.org/), ~~98~~ 79 bytes
```
n=>{val m=n+"";if(m.size%3>1)Set(0,2,6,7,8,9)(m.take(2).toInt-10)else m(0)==50}
```
[Try it online!](https://tio.run/##dVTBbtswDL3nK4RgBSzUDSjZsq0VDtDddtipX@CmCurNsdNYHdYW/fbMTUhLLFpd@IhHihQf7XHTdM1xuPvtNl78atpeuH/e9fejuNnvXxdiOn@bTmy/i5@9F/Va/BiGzjW9qI99vX5953Z1f7lcXrfbZLca2xd3ka2VvHU@gVSnRVqmVWrlxPnmj0u0XPlhuupKgXTd6MQuAVnXBt6OVMsfnvzDs6jFrXtMdHrqQQFa8gu0JdoKrT1bDUBAIdAZAkO5ABSlQAWYhwBrLdUNsVpVM9SaYGEMwdJaglVZELQQegqV9XRHpubOLNADrA3FASDu1cacZpxmXMG4whQ6yw15LLJkkSXjKsZVjLOMszGHjUWPVrnRmZldHqxYcG6mTpXJ4mFM5@TJRVjLphtpU3CImJKfDVZDQXFZcFfoDZioMFNhqpo7nVUIcoThh1HT8DLaxcrQVXZ@Sax8ZnQsYixaLEssQzx2Pma@KsC3A/hCAFcduNDAtUXXfqbB@VNdbYeDazYPSfv@g9gf2t53fTIu8UP@1oorsRSXYpu0UspT4km4r/LOqn5MW7wd/wM "Scala – Try It Online")
* Thanks to [user](https://codegolf.stackexchange.com/users/95792/user) for -19!!!!
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~41 33~~ 42 bytes
```
§|§&ȯ€B19 26441084r↑2o₁L§&o='2←ȯ¬₁Ls
€d258
```
[Try it online!](https://tio.run/##yygtzv7//9DymkPL1U6sf9S0xsnQUsHIzMTE0MDCpOhR20Sj/EdNjT5A2XxbdaNHbRNOrD@0BiRSzAVUnGJkavH//39DIwA "Husk – Try It Online")
-8 bytes from Dominic Van Essen.
+9 bytes after corrections.
[Answer]
# [R](https://www.r-project.org/), ~~87~~ ~~82~~ 79 bytes
(or [82 bytes](https://tio.run/##Tc1BCoMwEEDR0wzMYEpnlAoVsvMcrRK0CSljiErp6aObQnd/8eDnkpa87a9pnZ69LfOubguLoppo1fkxo9JFaAjzgE0LgLG6kVG4gvAjWlv/GuPJICg4FDZSG2k7uROVjw/O4zqm9P6idA0zm7/nKcoB) as a function)
```
`if`(36%%((k=nchar(n<-scan())-1)+5),n%/%10^k==2,n%/%10^(k-1)%in%c(10,12,16:19))
```
[Try it online!](https://tio.run/##NcnBCoAgDADQrxlspLQZCUX@SihCJMIO9v@sLt0evGGW25VxiQCIPWm9y0A9/FOLIpEXmlZyCjMInz2l8Bv7d9AUKgo7CU7iLhuRBWazFw "R – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~28~~ ~~26~~ ~~25~~ ~~23~~ ~~21~~ 20 bytes
or **[19 bytes](https://tio.run/##ASkA1v9odXNr///igqziiKtkMjgyNDExMWnihpHCueKGkj0yJTNM////IjE5Ig)** by accepting input as a string
*Edit: -2 bytes thanks to LegionMammal978, then -1 more byte thanks to Zgarb*
```
€∫d2824111d↑d¹→=2%3L
```
[Try it online!](https://tio.run/##AS8A0P9odXNr/1figoHhuKM1MDD/4oKs4oirZDI4MjQxMTFk4oaRZMK54oaSPTIlM0z//w "Husk – Try It Online") (header in TIO link loops over integers from 1 to 500, and outputs those beginning with 'D' in Portugese)
Port of [Robin Ryder's R answer](https://codegolf.stackexchange.com/a/213684/95126). Outputs zero (falsy) for numbers not beginning with 'D' in Portugese, or a positive integer (truthy) for numbers beginning with 'D'.
**How?**
```
€∫d2824111d`↑d¹→=2%3Ld
€ # does the argument belong to this list:
∫ # cumulative sum of
d2824111 # base-10 digits of 2824111
# (2,10,12,16,17,18 and 19)
d # argument is the base-10 number formed from
`↑d¹ # the first x digits of the input
# where x is calculated as:
→=2%3Ld
→ # 1 plus
Ld # the number of input digits
%3 # mod 3
=2 # equals 2?
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~48~~ ~~47~~ 34 bytes
```
->s{s=~/^(2|1[026-9]|2..)(...)*$/}
```
[Try it online!](https://tio.run/##dVJda4MwFH2/vyK4PWyD2tzEqHnoYP9g790H7WpXwekwyiht99e7a0xCLSzgQc6J59x7sO3X@/N28XKePZqDWfzO3@7EEZdcpDP9ehRxfH8XEzzczk/nru273f697r/WRWvYgkUCkAMSpoAZYA6oQXBOD4IQEoQigdMhRIuJZbTW9JnlBeYDCkGYKkWYaU2YZymh5tbNWgi6JXHw1JxitLYufDyjafAdrT2TeiZVqZCJohcvZV7KPJN7JveM9ox2jEsYR8NECamGt6CiVxNFaaikm5ZOBLBdVSa0uIgQJCSgIIUMcqA4BJSACeBgCmNtdh27gZ1VUtO5oit68HbtSCXc8m5jt51bye0Rhg/V8VAZD1Xx0AwPjfDQBAd9sc/0t4iL1cfuvSrrgm0adpyIR2CsXZWmYNFz26yr4ov9lN2ObdjNYXLxFLG@rgpj2HY5EWLTteX3KxT15qrIq9xL7b/YuqlnQ/TlXUout5R6yU1Cv/vOsOipqthn02wiOP8B "Ruby – Try It Online")
Takes input is a string.
Based on ~~[Abigail's Perl solution](https://codegolf.stackexchange.com/a/213667/65905)~~.
Based on [Neil's impressive regex.](https://codegolf.stackexchange.com/a/213695/65905)
] |
[Question]
[
This is the robbers' thread of [this](https://codegolf.stackexchange.com/questions/99155/polyglot-anagrams-cops-thread) challenge
The cops will choose an [OEIS](https://oeis.org) sequence and write two *full programs* in two different languages that produces that nth item in the sequence when given an n via STDIN. The two programs must be anagrams of each other, meaning each can be rearranged from the other's letters.
They will present the OEIS number, the source code for and the name of *one* language it is in.
You must find an anagram of the original cop's submission that runs in a language other than the one used by the cop. To crack an answer you must only find ***any*** language and program which produces the sequence and is an anagram of the original, not necessarily the answer the cop was thinking about.
You may output by character code or include STDERR in your solution, but only if the cop has indicated their hidden solution does so. Decimal output to STDOUT is always a valid crack.
Thus cops are incentivized to make it as hard as possible to find any language that does the task using their list of symbols.
## Scoring
The person with the most cracks will be the winner of this section. Only the first crack for each solution will count towards one's score.
## Leader Board
Big thanks to every one that took place in this challenge.
Here is the leader board as it stands
```
Place User Score
-----------------------------
1 Adnan 3
1 Kritixi Lithos 3
1 Emigna 3
1 milk 3
5 Steven H. 2
5 Wheat Wizard 2
5 jimmy23013 2
8 ETH Productions 1
8 Dennis 1
8 alleks 1
8 Martin Ender 1
8 Oliver 1
8 Conor O'Brien 1
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 38 bytes, [Loovjo](https://codegolf.stackexchange.com/a/99160/47066), [A000290](http://oeis.org/A000290)
```
nXtdief e():return X*X
pr e(input())##
```
[Try it online!](http://05ab1e.tryitonline.net/#code=blh0ZGllZiBlKCk6cmV0dXJuIFgqWApwciBlKGlucHV0KCkpIyM&input=NQ)
Very likely not the intended solution, but it works.
**Explanation**
```
n # square input
X # push 1
t # push sqrt(1)
d # push is_number(1.0)
i # if true do the rest of the code (1.0 is not a number so it will never execute)
```
[Answer]
# Jolf, 15 bytes, [Adnan](https://codegolf.stackexchange.com/a/99177/31957), [A000290](http://oeis.org/A000290)
```
*&"?!#$|<=@\^{}
```
[Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=KiYiPyEjJHw8PUBcXnt9) Definitely not the intended solution, but hey, it works.
## Explanation
```
*&"?!#$|<=@\^{}
* multiply
& the two inputs to this func, x, y: x && y
returns y if x and y, or the falsey argument.
"?!#$|<=@\^{} this string is always truthy, so the second arg is used.
two implicit inputs are taken, both equal to the first arg
so, this corresponds to *xx, which is x^2.
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 49 bytes, [Wheat Wizard](https://codegolf.stackexchange.com/a/99164/34388), [A000290](http://oeis.org/A000290)
Actually the same approach as Emigna's crack :p.
```
n4i<({({)({[()]){))()()()turpetne/"*"*splint>}}}}
```
Explanation:
```
n # Square the input
4i # If 4 == 1, do the following...
<({...
```
[Try it online!](http://05ab1e.tryitonline.net/#code=bjRpPCh7KHspKHtbKCldKXspKSgpKCkoKXR1cnBldG5lLyIqIipzcGxpbnQ-fX19fQ&input=Nw)
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 35 bytes, [Oliver](https://codegolf.stackexchange.com/a/99171/47066), [A000290](http://oeis.org/A000290)
Cops should stop posting `n^2` challenges in python...
```
n0iprt(input()**(1+1))
"'1°3¢','m'"
```
[Try it online!](http://05ab1e.tryitonline.net/#code=bjBpcHJ0KGlucHV0KCkqKigxKzEpKQoiJzHCsDPCoicsJ20nIg&input=NQ)
**Explanation**
```
n # square input
0i # if 0 == 1 do the rest of the code
```
[Answer]
# [2sable](http://github.com/Adriandmen/2sable), 7 bytes, [Kritixi Lithos](https://codegolf.stackexchange.com/a/99178/34388), [A005843](http://oeis.org/A005843)
Code:
```
r^#ei2*
```
Explanation:
```
r # Reverse the stack, which is a no-op
^ # XOR the input with itself, always leading to 0
# # If 1, break (which stops the program)
e # Compute input nPr input, which always leads to 1
i # If equal to one, do the following..
2* # Multiply the input by 2.
```
[Try it online!](http://2sable.tryitonline.net/#code=cl4jZWkyKg&input=MjEK)
[Answer]
# [Hexagony](https://github.com/m-ender/hexagony), 13 bytes, [Adnan](https://codegolf.stackexchange.com/a/99276/8478), [A002378](https://oeis.org/A002378)
```
?"&\>=})\*!@<
```
[Try it online!](http://hexagony.tryitonline.net/#code=PyImXD49fSlcKiFAPA&input=Ng)
Unfolded:
```
? " &
\ > = }
) \ * ! @
< . . .
. . .
```
Not 100% whether this is the original, because the top left `\` is unused.
The `<\>` are just mirrors, so the program is actually entirely linear:
```
?"&)}=*!@
? Read input.
" Move back and left.
& Copy input.
) Increment copy.
}= Move forward and right and turn around (to face the n and n+1 edges).
* Multiply.
! Print.
@ Terminate.
```
[Answer]
# [V](https://github.com/DJMcMayhem/V), 13 bytes, [DJMcMayhem](https://codegolf.stackexchange.com/a/99181/56656), [A002275](http://oeis.org/A002275)
```
v!:x]''"
@ai1
```
[Try it online!](http://v.tryitonline.net/#code=diE6eF0nJyIKQGFpMQ&input=&args=MjI)
This might be the first solution in the language the author intended.
---
## Explanation
```
v!:x]''" Does nothing
@ai1 inserts 1 a times
```
[Answer]
# 2sable, [Conor O'Brien](https://codegolf.stackexchange.com/a/99377/55696), [A000290](http://oeis.org/A000290)
```
~*
```
[Try it online!](http://2sable.tryitonline.net/#code=fio&input=NQ)
I don't know how it works, there's really only one program that meets the requirements and I just brute-forced to find the language it worked in.
After looking through the docs, I am able to come up with an explanation:
```
~ Push Input OR Input (always pushes the input)
* Multiply that by Input
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 26 bytes, [Steven H.](https://codegolf.stackexchange.com/a/99381), [A023443](https://oeis.org/A023443)
Code:
```
tQ.qly 7:esau0euii s uxC !
```
[Try online](https://pyth.herokuapp.com/?code=tQ.qly+7%3Aesau0euii+s+uxC+%21&input=0&debug=0).
Fairly simple:
```
Q Reads input
t Substracts 1 from it
.q Quits program (implicit print)
ly 7:esau0euii s uxC ! None of this ever plays a part...
I just thought it'd be fun to scramble it.
```
[Answer]
# Python 3, 118 bytes, [ETHproductions, A042545](https://codegolf.stackexchange.com/a/99174/12012)
```
s,a=801**.5-28,[0,0==0]
for i in range(int(input())):a+=[a[i]+a[-1]*int(1/s)];s=1/s-1//s
(print(a[-2]),) #.0fhlmop|
```
Test it on [Ideone](http://ideone.com/Wxs3T8).
### Cop submission
```
i=input();s=1/(801**.5-28);a=[0,1]
for p in range(i):a+=[a[-2]+a[-1]*int(s)];s=1/(s-int(s))
print a[i]#,,,.//000fhlmo|
```
### What's different
The cop submission doesn't work in Python 3 for two reasons.
* Python 2's *input* function automatically evals one line of input, while Python 3's counterpart just returns the line as a string. We can simply call *int* to fix this.
* `print` was a statement in Python 2, but it is a function in Python 3. In particular, that means that we have to surround its argument with parentheses.
That means we need `int()` and `()`, but those characters aren't all part of the comment. That means we must make some changes.
Instead of the fraction **s**, we keep track of **1/s**.
The initialization of **s** – `s=1/(801**.5-28)` – becomes `s=801**.5-28`, saving the characters `1/()`.
The factor of **a[-1]** in the update of **a** – `int(s)` – becomes `int(1/s)`, costing the characters `1/`.
The update of **s** – `s=1/(s-int(s))` – becomes `s=1/s-1//s`, costing the characters `1//`, but saving the characters `(int())`.
The saved characters in `()(int())` cover those we needed to port the code to Python 3, but obtaining them cost us `1//`. We can take `//` from the comment, but we'll have to save `1` elsewhere.
One way (the only one?) of saving the needed `1` is to replace the `1` in the initialization of **a** with `0==0`. This costs those four characters, but we can take `00` from the comment.
So far, we have the following code.
```
i=int(input());s=801**.5-28;a=[0,0==0]
for p in range(i):a+=[a[-2]+a[-1]*int(1/s)];s=1/s-1//s
print(a[i]) #,,,.()0fhlmo|
```
To recover one of the `=` we now "owe", we can rewrite the initialization of **s** and **a** with a single assignment: `s,a=801**.5-28,[0,0==0]` Additionally, this saves a `;` and costs a `,`, which can be be added to and removed from the comment.
The second `=` can be saved by not storing the input in a variable, i.e., writing `range(int(input()))` instead, saving the characters in `i=`. We use **i** after the loop as well, but the **i**th element of **a** is just the second one from the right, so we can replace `i` with `-2`. For the same reason, `a[-2]` in the loop body can be replaced with `i`.
We now have a permutation into working Python 3 code:
```
s,a=801**.5-28,[0,0==0]
for i in range(int(input())):a+=[a[i]+a[-1]*int(1/s)];s=1/s-1//s
print(a[-2]) #,.()0fhlmop|
```
However, this code also works in Python 2! One way of fixing this is to replace `print(a[-2])` with `(print(a[-2]),)`; we have the characters we need in the comment. As mentioned before, *print* is a function in Python 3, so this constructs the tuple **(*None*,)**. However, Python 2's *print **statement*** is a *SyntaxError* inside a tuple literal.
[Answer]
# CJam, 39 bytes, [milk](https://codegolf.stackexchange.com/a/99202/25180), [A000007](https://oeis.org/A000007)
```
l~0{"e.bockj(>=@$t0)@$t0+(<7)??0t:"};1?
```
[Try it here.](http://cjam.aditsu.net/#code=l%7E0%7B%22e.bockj(%3E%3D%40%24t0)%40%24t0%2B(%3C7)%3F%3F0t%3A%22%7D%3B1%3F&input=0)
[Answer]
# Pyth, 7 bytes, [Luis Mendo](https://codegolf.stackexchange.com/questions/99155/polyglot-anagrams-cops-thread/99199#99199), [A000217](https://oeis.org/A000217)
```
x:{ps}1
```
As requested, the program exits with error after `p`rinting the correct answer.
Try it online [here](http://pyth.herokuapp.com/?code=x%3A%7Bps%7D1&input=3&debug=0)!
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 12 bytes, [tuskiomi](https://codegolf.stackexchange.com/a/99203/47066), [A000012](http://oeis.org/A000012)
```
1,(FI1=1=1,)
```
[Try it online!](http://05ab1e.tryitonline.net/#code=MSwoRkkxPTE9MSwp&input=NQ)
**Explanation**
```
1, # print 1
( # negate input
F # that many times do (i.e. no times)
I1=1=1,) # the rest of the code
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 38 bytes, [Conor O'Brien](https://codegolf.stackexchange.com/a/99236/56656), [A000290](https://oeis.org/A000290)
```
n2iJ=>eval(Array(J).fill(J).jo`+`)|-2;
```
[Try it Online!](http://05ab1e.tryitonline.net/#code=bjJpSj0-ZXZhbChBcnJheShKKS5maWxsKEopLmpvYCtgKXwtMjsK&input=NQ)
---
## Explanation
This is based on [Emigna's crack here](https://codegolf.stackexchange.com/a/99172/56656).
```
n #Squares the number
2i #Runs the rest of the code if 2==1
```
[Answer]
# 05AB1E, 27 bytes, [boboquack](https://codegolf.stackexchange.com/a/99358/58106), [A000012](https://oeis.org/A000012)
```
1 1pif:
if :
rint( '1' )
```
[Try it online](http://05ab1e.tryitonline.net/#code=MSAxcGlmOgoJaWYgOgoJCXJpbnQoICcxJyAp&input=NTA)
How it works:
```
1 # push 1
1 # push 1
p # pop (1), push is_prime(1)
i # pop (is_prime(1), false), if is false so don't execute rest
```
[Answer]
# CJam, 70 bytes, [Shebang](https://codegolf.stackexchange.com/a/99193/25180), [A000217](https://oeis.org/A000217)
```
ri),:+
e#| d00->1@@@++-^,[o=input(v=0i=1whil o v=i i+=1pnt v
```
[Try it here.](http://cjam.aditsu.net/#code=ri%29%2C%3A%2B%0A%0A%0A%0A%0A%0A%0A%0A%0Ae%23%7C%20%20d00-%3E1%40%40%40%2B%2B-%5E%2C%5Bo%3Dinput%28v%3D0i%3D1whil%20o%20v%3Di%20i%2B%3D1pnt%20v%0A&input=5)
[Answer]
# Convex, 75 bytes, [boboquack](https://codegolf.stackexchange.com/a/99251/58106), [A004526](https://oeis.org/A004526)
```
2/Q2 2/2/2/2/2/2/2/2/2/2/2/2/2/2/2/2/2/2*2*2*; 2*; 2; 2; 2;
```
[Try it online](http://convex.tryitonline.net/#code=Mi9RMiAyLzIvMi8yLzIvMi8yLzIvMi8yLzIvMi8yLzIvMi8yLzIvMioyKjIqOyAyKjsgICAgICAgICAgICAgICAgIDI7IDI7IDI7&input=Nw)
How it works:
```
2 e# push 2
/ e# pop first 2, divide, push result
e# push a bunch of garbage but discard it all with semi-colons (;)
Q2 2/2/2/2/2/2/2/2/2/2/2/2/2/2/2/2/2/2*2*2*; 2*; 2; 2; 2;
```
[Answer]
# [Dip](https://github.com/mcparadip/Dip), 9 bytes, [Kritixi Lithos](https://codegolf.stackexchange.com/a/99299/12537)
Definitely not the intended answer.
```
1^,-$)×1*
```
Explanation:
```
1$^,-)× # Basically does nothing
1* # Repeat "1" n times
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 6 bytes, [DLosc](https://codegolf.stackexchange.com/a/99405/42545), [A000012](https://oeis.org/A000012)
```
.()49o
```
I figured I'd try the OP's esolang first ;-)
[Try it online.](http://pip.tryitonline.net/#code=LigpNDlv&input=NA&debug=on)
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 25 bytes, [Mego](https://codegolf.stackexchange.com/a/99275/34388), [A000583](https://oeis.org/A000583)
Code:
```
nnYi=put("");prit`Y**4`,X
```
Explanation:
```
n # Square the input
n # Square the squared input
Y # Constant that pushes 2
i # If equal to 1, do the following:
=put...
```
[Try it online!](http://05ab1e.tryitonline.net/#code=bm5ZaT1wdXQoIiIpO3ByaXRgWSoqNGAsWA&input=NA)
[Answer]
# [Dip](https://github.com/mcparadip/Dip), 8 bytes, [Oliver](https://codegolf.stackexchange.com/a/99345/41805), [A000042](http://oeis.org/A000042)
```
(1J&F},1
```
### Explanation
```
#Implicit Input
( #Start range loop
1 #Push 1 to the stack
J #Join all the elements in the stack
& #End program
F},1 #These are ignored
```
The funny thing is that this was the intended language! Dip is an esolang created by Oliver.
### Test Cases and Running Dip from Command-Line
```
$python3 dip.py
Dip v1.0.0 by Oliver Ni.
>>> (1J&F},1
> 4
1111
>>> (1J&F},1
> 7
1111111
```
[Answer]
# 2sable, 14 bytes, [Dopapp](https://codegolf.stackexchange.com/a/99384/58106), [A121377](https://oeis.org/A121377)
```
Q@5 2*%6 8*+.&
```
[Try it online.](http://2sable.tryitonline.net/#code=UUA1IDIqJTYgOCorLiY&input=OQ)
How it works (more or less):
```
Q@
5 # Push 5
2 # Push 2
* # Pop (2), pop (5), push 5*2=10
% # Pop (10), pop (input), push input%10
6 # Push 6
8 # Push 8
* # Pop (8), pop (6), push 8*6=48
+ # Pop (48), pop (input), push input+48
.&
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes, [Oliver](https://codegolf.stackexchange.com/a/99389/41805), [A000012](https://oeis.org/A000012)
```
p¥_1
```
[Try it online!](http://05ab1e.tryitonline.net/#code=cMKlXzE&input=ODY)
This is a sequence of `1`s.
```
# Implicit input
p¥_ # Does nothing
1 # Pushes 1 to the stack
# Implicit output
```
This outputs `1` no matter what the input is.
[Answer]
# [Dip](https://github.com/mcparadip/Dip), 5 bytes, [Oliver](https://codegolf.stackexchange.com/a/99456/41805), [A000012](https://oeis.org/A000012)
```
`¸WW/
```
The sequence just prints a `1` no matter what the input is. Oliver's answer prints
a `1.0`. This program also prints a `1.0`. This apparently is the intended solution.
### Explanation
```
`¸ # push character `¸`
W # pushes 1000000
W # pushes 1000000 also
/ # divides the last two items in stack resulting in 1.0
# implicit output (1.0)
```
### Alternative solution (courtesy of @milk)
# [Convex](https://github.com/GamrCorps/Convex), 5 bytes
```
WW¸`/
```
[Try it online!](http://convex.tryitonline.net/#code=V1fCuGAv&input=Ng)
### Explanation
```
// implicit input
W // pushes -1
W // pushes -1 also
¸ // calculates the LCM of the two numbers (which evaluates to 1)
` // finds its string representation
/ // slices the string (so that it would evaluate to "1")
// implicit output
```
] |
[Question]
[
The [cross product](https://en.wikipedia.org/wiki/Cross_product) of two three-dimensional vectors \$\vec a\$ and \$\vec b\$ is the unique vector \$\vec c\$ such that:
* \$\vec c\$ is orthogonal to both \$\vec a\$ and \$\vec b\$
* The magnitude of \$\vec c\$ is equal to the area of the parallelogram formed by \$\vec a\$ and \$\vec b\$
* The directions of \$\vec a\$, \$\vec b\$, and \$\vec c\$, in that order, follow the [right-hand rule](https://en.wikipedia.org/wiki/Right-hand_rule).
There are a few equivalent formulas for cross product, but one is as follows:
$$\vec a\times\vec b=\det\begin{bmatrix}\vec i&\vec j&\vec k\\a\_1&a\_2&a\_3\\b\_1&b\_2&b\_3\end{bmatrix}$$
where \$\vec i\$, \$\vec j\$, and \$\vec k\$ are the unit vectors in the first, second, and third dimensions.
### Challenge
Given two 3D vectors, write a full program or function to find their cross product. Builtins that specifically calculate the cross product are disallowed.
### Input
Two arrays of three real numbers each. If your language doesn't have arrays, the numbers still must be grouped into threes. Both vectors will have magnitude \$<2^{16}\$. Note that the cross product is noncommutative (\$\vec a\times\vec b=-\bigl(\vec b\times\vec a\bigr)\$), so you should have a way to specify order.
### Output
Their cross product, in a reasonable format, with each component accurate to four significant figures or \$10^{-4}\$, whichever is looser. Scientific notation is optional.
### Test cases
```
[3, 1, 4], [1, 5, 9]
[-11, -23, 14]
[5, 0, -3], [-3, -2, -8]
[-6, 49, -10]
[0.95972, 0.25833, 0.22140],[0.93507, -0.80917, -0.99177]
[-0.077054, 1.158846, -1.018133]
[1024.28, -2316.39, 2567.14], [-2290.77, 1941.87, 712.09]
[-6.6345e+06, -6.6101e+06, -3.3173e+06]
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution in bytes wins.
Maltysen posted a [similar challenge](https://codegolf.stackexchange.com/q/70269/39328), but the response was poor and the question wasn't edited.
[Answer]
# Jelly, ~~14~~ ~~13~~ 12 bytes
```
;"s€2U×¥/ḅ-U
```
[Try it online!](http://jelly.tryitonline.net/#code=OyJz4oKsMlXDl8KlL-G4hS1V&input=&args=WzMsIDEsIDRdLCBbMSwgNSwgOV0)
### How it works
```
;"s€2U×¥/ḅ-U Main link. Input: [a1, a2, a3], [b1, b2, b3]
;" Concatenate each [x1, x2, x3] with itself.
Yields [a1, a2, a3, a1, a2, a3], [b1, b2, b3, b1, b2, b3].
s€2 Split each array into pairs.
Yields [[a1, a2], [a3, a1], [a2, a3]], [[b1, b2], [b3, b1], [b2, b3]].
¥ Define a dyadic chain:
U Reverse the order of all arrays in the left argument.
× Multiply both arguments, element by element.
/ Reduce the 2D array of pairs by this chain.
Reversing yields [a2, a1], [a1, a3], [a3, a2].
Reducing yields [a2b1, a1b2], [a1b3, a3b1], [a3b2, a2b3].
ḅ- Convert each pair from base -1 to integer.
This yields [a1b2 - a2b1, a3b1 - a1b3, a2b3 - a3b2]
U Reverse the array.
This yields [a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1] (cross product).
```
## Non-competing version (10 bytes)
OK, this is embarrassing, but the array manipulation language Jelly did not have a built-in for array rotation until just now. With this new built-in, we can save two additional bytes.
```
ṙ-×
ç_ç@ṙ-
```
This uses the approach from [@AlexA.'s J answer](https://codegolf.stackexchange.com/a/70517). [Try it online!](http://jelly.tryitonline.net/#code=4bmZLcOXCsOnX8OnQOG5mS0&input=&args=WzMsIDEsIDRd+WzEsIDUsIDld)
### How it works
```
ṙ-× Helper link. Left input: x = [x1, x2, x3]. Right input: y = [y1, y2, y3].
ṙ- Rotate x 1 unit to the right (actually, -1 units to the left).
This yields [x3, x1, x2].
× Multiply the result with y.
This yields [x3y1, x1y2, x2y3].
ç_ç@ṙ- Main link. Left input: a = [a1, a2, a3]. Right input: b = [b1, b2, b3].
ç Call the helper link with arguments a and b.
This yields [a3b1, a1b2, a2b3].
ç@ Call the helper link with arguments b and a.
This yields [b3a1, b1a2, b2a3].
_ Subtract the result to the right from the result to the left.
This yields [a3b1 - a1b3, a1b2 - a2b1, a2b3 - a3b2].
ṙ- Rotate the result 1 unit to the right.
This yields [a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1] (cross product).
```
[Answer]
## **LISP, 128 122 bytes**
Hi! This is my code:
```
(defmacro D(x y)`(list(*(cadr,x)(caddr,y))(*(caddr,x)(car,y))(*(car,x)(cadr,y))))(defun c(a b)(mapcar #'- (D a b)(D b a)))
```
I know that it isn't the shortest solution, but nobody has provided one in Lisp, until now :)
Copy and paste the following code [here](http://www.tutorialspoint.com/lisp/try_lisp.php) to try it!
```
(defmacro D(x y)`(list(*(cadr,x)(caddr,y))(*(caddr,x)(car,y))(*(car,x)(cadr,y))))(defun c(a b)(mapcar #'- (D a b)(D b a)))
(format T "Inputs: (3 1 4), (1 5 9)~%")
(format T "Result ~S~%~%" (c '(3 1 4) '(1 5 9)))
(format T "Inputs: (5 0 -3), (-3 -2 -8)~%")
(format T "Result ~S~%~%" (c '(5 0 -3) '(-3 -2 -8)))
(format T "Inputs: (0.95972 0.25833 0.22140), (0.93507 -0.80917 -0.99177)~%")
(format T "Result ~S~%" (c '(0.95972 0.25833 0.22140) '(0.93507 -0.80917 -0.99177)))
(format T "Inputs: (1024.28 -2316.39 2567.14), (-2290.77 1941.87 712.09)~%")
(format T "Result ~S~%" (c '(1024.28 -2316.39 2567.14) '(-2290.77 1941.87 712.09)))
```
[Answer]
# J, ~~27~~ 14 bytes
```
2|.v~-v=.*2&|.
```
This is a dyadic verb that accepts arrays on the left and right and returns their cross product.
Explanation:
```
*2&|. NB. Dyadic verb: Left input * twice-rotated right input
v=. NB. Locally assign to v
v~- NB. Commute arguments, negate left
2|. NB. Left rotate twice
```
Example:
```
f =: 2|.v~-v=.*2&|.
3 1 4 f 1 5 9
_11 _23 14
```
[Try it here](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=f%20%3D%3A%202%7C.v~-v%3D.*2%26%7C.)
Saved 13 bytes thanks to randomra!
[Answer]
# Dyalog APL, 12 bytes
```
2⌽p⍨-p←⊣×2⌽⊢
```
Based on [@AlexA.'s J answer](https://codegolf.stackexchange.com/a/70517) and (coincidentally) equivalent to @randomra's improvement in that answer's comment section.
Try it online on [TryAPL](http://tryapl.org/?a=3%201%204%20%28%202%u233Dp%u2368-p%u2190%u22A3%D72%u233D%u22A2%20%29%201%205%209&run).
### How it works
```
2⌽p⍨-p←⊣×2⌽⊢ Dyadic function.
Left argument: a = [a1, a2, a3]. Right argument: b = [b1, b2, b3].
2⌽⊢ Rotate b 2 units to the left. Yields [b3, b1, b2].
⊣× Multiply the result by a. Yields [a1b3, a2b1, a3b2].
p← Save the tacit function to the right (NOT the result) in p.
p⍨ Apply p to b and a (reversed). Yields [b1a3, b2a1, b3a2].
- Subtract the right result (p) from the left one (p⍨).
This yields [a3b1 - a1b3, a1b2 - a2b1, a2b3 - a3b2].
2⌽ Rotate the result 2 units to the left.
This yields [a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1].
```
[Answer]
# C, 156 154 150 148 144 bytes
```
#include <stdio.h>
main(){float v[6];int i=7,j,k;for(;--i;)scanf("%f",v+6-i);for(i=1;i<4;)j=i%3,k=++i%3,printf("%f ",v[j]*v[k+3]-v[k]*v[j+3]);}
```
Not going to be winning any prizes for length, but thought I'd have a go anyway.
* Input is a newline- or space-delimited list of components (i.e. a1 a2 a3 b1 b2 b3), output is space-delimited (i.e. c1 c2 c3).
* Cyclically permutes the indices of the two input vectors to calculate the product - takes fewer characters than writing out the determinants!
[Demo](http://cpp.sh/5acf)
Ungolfed:
```
#include <cstdio>
int main()
{
float v[6];
int i = 7, j, k;
for (; --i; ) scanf("%f", v + 6 - 1);
for (i = 1; i < 4; )
j = i % 3,
k = ++i % 3,
printf("%f ", v[j] * v[k + 3] - v[k] * v[j + 3]);
}
```
[Answer]
## Haskell, 41 bytes
```
x(a,b,c)(d,e,f)=(b*f-c*e,c*d-a*f,a*e-b*d)
```
A straightforward solution.
[Answer]
# Bash + coreutils, 51
```
eval set {$1}*{$2}
bc<<<"scale=4;$6-$8;$7-$3;$2-$4"
```
* Line 1 constructs a brace expansion that gives the cartesian product of the two vectors and sets them into the positional parameters.
* Line 2 subtracts the appropriate terms; `bc` does the arithmetic evaluation to the required precision.
Input is as two comma-separated lists on the command-line. Output as newline-separated lines:
```
$ ./crossprod.sh 0.95972,0.25833,0.22140 0.93507,-0.80917,-0.99177
-.07705
1.15884
-1.01812
$
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 17 bytes
```
!*[6,7,2;8,3,4])d
```
First input is **a**, second is **b**.
[**Try it online!**](http://matl.tryitonline.net/#code=ISpbNiw3LDI7OCwzLDRdKWQ&input=WzAuOTU5NzIsIDAuMjU4MzMsIDAuMjIxNDBdClswLjkzNTA3LCAtMC44MDkxNywgLTAuOTkxNzddCg)
### Explanation
```
! % input b as a row array and transpose into a column array
* % input a as a row array. Compute 3x3 matrix of pairwise products
[6,7,2;8,3,4] % 2x3 matrix that picks elements from the former in column-major order
) % apply index
d % difference within each column
```
[Answer]
# Pyth, 16 bytes
```
-VF*VM.<VLQ_BMS2
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=-VF*VM.%3CVLQ_BMS2&input=[3%2C+1%2C+4]%2C+[1%2C+5%2C+9]&debug=0)
### Explanation:
```
-VF*VM.<VLQ_BMS2 Q = input, pair of vectors [u, v]
S2 creates the list [1, 2]
_BM transforms it to [[1, -1], [2, -2]]
.<VLQ rotate of the input vectors accordingly to the left:
[[u by 1, v by -1], [u by 2, v by -2]]
*VM vectorized multiplication for each of the vector-pairs
-VF vectorized subtraction of the resulting two vectors
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
Takes input in the form \$[[x\_1,x\_2],[y\_1,y\_2],[z\_1,z\_2]]\$. If you want them to be two lists of x-y-z coordinates, just prepend `Z` to the beginning of the program.
```
ṁ4ÆḊƝ
```
[Try it online!](https://tio.run/##y0rNyan8///hzkaTw20Pd3Qdm/v/cPujpjXu//9HR0frGuooGMbqKEQDaSMQrWuso6BrGQtigsRMQAwjqBqglGlsbCwA "Jelly – Try It Online")
Here is a PDF [explanation](https://mr-xcoder.github.io/data/Cross_Product_Calculation.pdf) in case SE markdown can't handle it.
---
### The cross-product in analytic form
Let \$(x\_1,y\_1,z\_1)\$ be the coordinates of \$\vec{v\_1}\$ and \$(x\_2,y\_2,z\_2)\$ be the coordinates of \$\vec{v\_2}\$. Their analytic expressions are as follows:
$$\boldsymbol{\vec{v\_1}}=x\_1\cdot \boldsymbol{\vec{i}}+y\_1\cdot \boldsymbol{\vec{j}}+z\_1\cdot\boldsymbol{\vec{k}}$$
$$\boldsymbol{\vec{v\_2}}=x\_2\cdot \boldsymbol{\vec{i}}+y\_2\cdot \boldsymbol{\vec{j}}+z\_2\cdot\boldsymbol{\vec{k}}$$
The only thing left to do now is to also write their cross-product in terms of its coordinates in the \$Oxyz\$ space.
$$\boldsymbol{\vec{v\_1}}\times \boldsymbol{\vec{v\_2}}=\left(x\_1\cdot \boldsymbol{\vec{i}}+y\_1\cdot \boldsymbol{\vec{j}}+z\_1\cdot\boldsymbol{\vec{k}}\right)\times\left(x\_2\cdot \boldsymbol{\vec{i}}+y\_2\cdot \boldsymbol{\vec{j}}+z\_2\cdot\boldsymbol{\vec{k}}\right)$$
Keeping in mind that: $$\boldsymbol{\vec{i}}\times \boldsymbol{\vec{j}}=\boldsymbol{\vec{k}}, \:\: \boldsymbol{\vec{i}}\times \boldsymbol{\vec{k}}=-\boldsymbol{\vec{j}}, \:\: \boldsymbol{\vec{j}}\times \boldsymbol{\vec{i}}=-\boldsymbol{\vec{k}}, \:\: \boldsymbol{\vec{j}}\times \boldsymbol{\vec{k}}=\boldsymbol{\vec{i}}, \:\: \boldsymbol{\vec{k}}\times \boldsymbol{\vec{i}}=\boldsymbol{\vec{j}}, \:\: \boldsymbol{\vec{k}}\times \boldsymbol{\vec{j}}=-\boldsymbol{\vec{i}}$$
After the necessary rearrangements and calculations:
$$\boldsymbol{\vec{v\_1}}\times \boldsymbol{\vec{v\_2}}=(y\_1z\_2-z\_1y\_2)\cdot \boldsymbol{\vec{i}}+(z\_1x\_2-x\_1z\_2)\cdot \boldsymbol{\vec{j}}+(x\_1y\_2-y\_1x\_2)\cdot \boldsymbol{\vec{k}}$$
### The close relationship with matrix determinants
There's an interesting thing to note here:
$$x\_1y\_2-y\_1x\_2=\left|\begin{matrix}x\_1 & y\_1 \\\ x\_2 & y\_2\end{matrix}\right|$$
$$z\_1x\_2-x\_1z\_2=\left|\begin{matrix}z\_1 & x\_1 \\\ z\_2 & x\_2\end{matrix}\right|$$
$$y\_1z\_2-z\_1y\_2=\left|\begin{matrix}y\_1 & z\_1 \\\ y\_2 & z\_2\end{matrix}\right|$$
Where we use the notation \$\left|\cdot\right|\$ for matrix determinant. Notice the *beautiful* rotational symmetry?
### Jelly code explanation
Well... not much to explain here. It just generates the matrix:
$$\left(\begin{matrix}x\_1 & y\_1 & z\_1 & x\_1 \\\ x\_2 & y\_2 & z\_2 & x\_2\end{matrix}\right)$$
And for each pair of neighbouring matrices, it computes the determinant of the matrix formed by joining the two.
```
ṁ4ÆḊƝ – Monadic Link. Takes input as [[x1,x2],[y1,y2],[z1,z2]].
ṁ4 – Mold 4. Cycle the list up to length 4, reusing the elements if necessary.
Generates [[x1,x2],[y1,y2],[z1,z2],[x1,x2]].
Ɲ – For each pair of neighbours: [[x1,x2],[y1,y2]], [[y1,y2],[z1,z2]], [[z1,z2],[x1,x2]].
ÆḊ – Compute the determinant of those 2 paired together into a single matrix.
```
[Answer]
# K5, ~~44~~ ~~40~~ ~~37~~ 32 bytes
Wrote this one quite a while ago and [dusted it off again recently](https://github.com/JohnEarnest/ok/blob/gh-pages/ike/examples/vector.k#L16).
```
{{x[y]-x[|y]}[*/x@']'3 3\'5 6 1}
```
In action:
```
cross: {{x[y]-x[|y]}[*/x@']'3 3\'5 6 1};
cross (3 1 4;1 5 9)
-11 -23 14
cross (0.95972 0.25833 0.22140;0.93507 -0.80917 -0.99177)
-7.705371e-2 1.158846 -1.018133
```
## Edit 1:
Saved 4 bytes by taking input as a list of lists instead of two separate arguments:
```
old: {m:{*/x@'y}(x;y);{m[x]-m[|x]}'(1 2;2 0;0 1)}
new: {m:{*/x@'y}x ;{m[x]-m[|x]}'(1 2;2 0;0 1)}
```
## Edit 2:
Saved 3 bytes by computing a lookup table with base-decode:
```
old: {m:{*/x@'y}x;{m[x]-m[|x]}'(1 2;2 0;0 1)}
new: {m:{*/x@'y}x;{m[x]-m[|x]}'3 3\'5 6 1}
```
## Edit 3:
Save 5 bytes by rearranging application to permit using a tacit definition instead of a local lambda. Unfortunately, this solution no longer works in oK, and requires the official k5 interpreter. Gonna have to take my word for this one until I fix the bug in oK:
```
old: {m:{*/x@'y}x;{m[x]-m[|x]}'3 3\'5 6 1}
new: {{x[y]-x[|y]}[*/x@'] '3 3\'5 6 1}
```
[Answer]
# Python, ~~73~~ 48 bytes
Thanks @FryAmTheEggman
```
lambda (a,b,c),(d,e,f):[b*f-c*e,c*d-a*f,a*e-b*d]
```
This is based on the component definition of the vector cross product.
[Try it here](http://ideone.com/Pt0NpE)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 49 bytes
```
->u,v{(0..2).map{|a|u[a-2]*v[a-1]-u[a-1]*v[a-2]}}
```
[Try it online!](https://tio.run/##PU4xCsMwDNzzCo9tsYUk27U9tB8xHtIhWyEUHChJ3u4qLmQQd6fTifvU17dNj2aeVS/rBQH4Cu9xXrdxq3k0XG6LABVTO3TFZd/brKacrVaklStaZUGvVSplGLolArUy9vCM3BmWiaeNkHwKskNgH63thMlh0YdnPQa5R4iY6M@SkHDmCdkBx@OvpTvYpBX7ewDqZQxzQggSpOQIopBADCj12g8 "Ruby – Try It Online")
Returning after 2 years, I shaved off 12 bytes by using how Ruby treats negative array indices. `-1` is the last element of the array, `-2` the second last etc.
# Ruby, 57
```
->u,v{(0..2).map{|a|u[b=(a+1)%3]*v[c=(a+2)%3]-u[c]*v[b]}}
```
**In test program**
```
f=->u,v{(0..2).map{|a|u[b=(a+1)%3]*v[c=(a+2)%3]-u[c]*v[b]}}
p f[[3, 1, 4], [1, 5, 9]]
p f[[5, 0, -3], [-3, -2, -8]]
p f[[0.95972, 0.25833, 0.22140],[0.93507, -0.80917, -0.99177]]
p f[[1024.28, -2316.39, 2567.14], [-2290.77, 1941.87, 712.09]]
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~38 33 25~~ 24 bytes
-1 byte thanks to [@att](https://codegolf.stackexchange.com/users/81203/att).
```
Det@{a={i,j,},##}~D~{a}&
```
[Try it online!](https://tio.run/##JY6xisMwDIZfRRDoJAtJjmt76JGhD9C9dDCl5XLQG45swn31nNIMQp/@XxL/qy3fj1db5ntbn3CC9fxYJmsnm/EHOw5Df5/f1vphvfzNv8vVXIHwBc/rMNxucIBpmsDMIoIgjB3BvCeE2jc2J0YIcRuCLwX1KrvHVFPNLjBpKjF@QGXkjpsXE2dfZipcZafqkPdjYR1Jy/YxypFiRdB0zCSfDEG1MmW/kjoKFYcsSuyp@voP "Wolfram Language (Mathematica) – Try It Online")
[Answer]
## ES6, 40 bytes
```
(a,b,c,d,e,f)=>[b*f-c*e,c*d-a*f,a*e-b*d]
```
44 bytes if the input needs to be two arrays:
```
([a,b,c],[d,e,f])=>[b*f-c*e,c*d-a*f,a*e-b*d]
```
52 bytes for a more interesting version:
```
(a,b)=>a.map((_,i)=>a[x=++i%3]*b[y=++i%3]-a[y]*b[x])
```
[Answer]
# [Julia 0.7](http://julialang.org/), ~~45~~ 39 bytes
```
f(a,b)=1:3 .|>i->det([eye(3)[i,:] a b])
```
[Try it online!](https://tio.run/##XY5NagMxDIX3OYWWNshCP@PYDjQXGbyY0AlMCCGEdFHo3aeadFOyEPrQe5Le5eu6TGVdz2HCU/yQgwH9HJd0/JyfYZy/52BxXPDQYYJTj@v9sdye11s4h9EQBGHoCKP3jNB6jLt/Bh8xQrLNkdyd1Ku@mZhabsUVJs3V7AUqA3fcNMtcfIupcpM/ag7l7YqwDqR1@2GyJ2sImveF5BUvqTam4uvSBqHqUESJt8DrLw "Julia 0.7 – Try It Online")
Uses the determinant-based formula given in the task description.
Thanks to H.PWiz for -6 bytes.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 41 bytes
```
(a,b)->Vec(matdet(Mat([[x^2,x,1],a,b]~)))
```
[Try it online!](https://tio.run/##JY5BagMxDEWvIrKyQTaSPI7tRXODbrsxU3DTpASmxYRZpJtefSpnFkJP@v8L9Xa/ua@@XeEFNtPww7rT2@Vsvtv6eVnNa1tNrY93wQfyjKrPf9barfW@/JoG7gT9fvtZFQ9jOMC5LYu5IjRrsdYaEBhhmhGq9ohQ5sFViRBcGINTkxOtvGvkSyxJF@Ql5hCeIDzRUFUMkZK6yWcqvFNRSHuaSSYveZwMfPShIEg8Js/PJ5xIIZ80xWVinxUSiyd9a7bbPw "Pari/GP – Try It Online")
[Answer]
# [CSASM v2.5.0.2](https://github.com/absoluteAquarian/CSASM/releases/tag/v2.5.0.2), 306 bytes
```
func a:
dup
dup
ldelem 0
pop $3
ldelem 1
pop $4
ldelem 2
pop $5
dup
dup
ldelem 0
pop $a
ldelem 1
pop $1
ldelem 2
pop $2
push $1
push $5
mul
push $2
push $4
mul
sub
push $2
push $3
mul
push $a
push $5
mul
sub
push $a
push $4
mul
push $1
push $3
mul
sub
push 3
newarr f32
pop $a
push $a
swap
stelem 2
push $a
swap
stelem 1
push $a
swap
stelem 0
push $a
ret
end
```
The function `a` expects two `~arr:f32` arrays representing the two 3D vectors on the stack before calling it.
\$\vec a\$ should be pushed to the stack first, then \$\vec b\$ should be pushed.
This function leaves an `~arr:f32` array on the stack which corresponds to \$\vec c\$.
**Explanation:**
```
; Input: two ~arr:f32 representing the two vectors
func a:
; stack: [ a, b, c ], [ d, e, f ]
; These numbers represent the coordinates of the two vectors for an easier explanation
; Duplicate the second vector twice
dup
dup
; stack: [ a, b, c ], [ d, e, f ], [ d, e, f ], [ d, e, f ]
; Store the elements in the array to the pre-defined registers $3, $4 and $5
ldelem 0
pop $3
ldelem 1
pop $4
ldelem 2
pop $5
; Duplicate the first vector twice
dup
dup
; stack: [ a, b, c ], [ a, b, c ], [ a, b, c ]
; Store the elements in the array to the pre-defined registers $a, $1 and $2
ldelem 0
pop $a
ldelem 1
pop $1
ldelem 2
pop $2
; Perform the algorithm: [ bf - ce, cd - af, ae - bd ]
; $a = a, $1 = b, $2 = c
; $3 = d, $4 = e, $5 = f
; bf - ce
push $1
push $5
mul
push $2
push $4
mul
sub
; cd - af
push $2
push $3
mul
push $a
push $5
mul
sub
; ae - bd
push $a
push $4
mul
push $1
push $3
mul
sub
; Create the result array and store it in $a
push 3
newarr f32
pop $a
; Store the resulting values from earlier into this new array
; "swap" swaps the top two values on the stack
push $a
swap
stelem 2
push $a
swap
stelem 1
push $a
swap
stelem 0
push $a
ret
end
```
[Answer]
## TI-BASIC, ~~75~~ ~~73~~ ~~71~~ 62 bytes
-4 bytes thanks to [@MarcMush](https://codegolf.stackexchange.com/users/98541/marcmush)
-9 bytes using `Ans` instead of `Prompt` and `Disp`
Not 62 characters -- TI-BASIC is tokenized.
```
:Prompt A
:{Ans(2)ʟA(3)-Ans(3)ʟA(2),Ans(3)ʟA(1)-Ans(1)ʟA(3),Ans(1)ʟA(2)-Ans(2)ʟA(1
```
Usage example, computing \$\langle 1,2,3\rangle\times\langle 0,1,0\rangle\$:
```
{1,2,3}:pgrmXPROD
A=?{0,1,0}
{⁻3 0 1}
```
[Answer]
# MATLAB/Octave, 61 bytes.
[Try it online!](https://tio.run/##XY/NasMwEITvfQodbVgv@yNFEiKQ9zA@SE0CPbWQ0Nd3VwoB04NgdjTzSfv9@ay/t32/ny9ThTav19tzWhkIqNTSthmGQcD/DbNexlb2yu7sVgXH4PxWXBuzDQFctvn69fiZ7lM1p/E8l48qPWC3BG7R3hjGYohF7KRDyeYmo6Q9Q5hDjmYSSkiqQwh76pR3QgNFwxAmyvxS2UQ8YK3YdGD9@CyJR0n9feUTagYn4RSRxz4jsohkwmg4zp4xmYgsSMcNvVG9Ufc/)
```
f=@(a,b)[det([1,0,0;a;b]),det([0,1,0;a;b]),det([0,0,1;a;b])];
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~24~~ 21 bytes
```
D/@HodgeDual[1##]&
```
[Try it online!](https://tio.run/##JY4/zsIwDMWvYqkSU2JspyHJAOrAwMheMVT8@5A@QEJlinIGDsAhOUJx6WD55/ds6127/u947frLvhtOsIRhPW8298P5uH52/y1/Xu@q2s2G7eNy69tcVQXsCk6tijuYQdM0kHN2BthAXQxk7d5AKiNnJTJg3ThYXbKiFSePMPkUVCAUH537gXBNxYye8xR0mTBS4omSQpiOmaRGieNHxwt0yYD4RUD@ZbAiiTDoFaeaMSoEFiRNVYYv "Wolfram Language (Mathematica) – Try It Online")
`` is `\[TensorWedge]` (U+F3DB).
[Answer]
# APL(NARS), 23 chars, 46 bytes
```
{((1⌽⍺)×5⌽⍵)-(5⌽⍺)×1⌽⍵}
```
test:
```
f←{((1⌽⍺)×5⌽⍵)-(5⌽⍺)×1⌽⍵}
(3 1 4) f (1 5 9)
¯11 ¯23 14
(5 0 ¯3) f (¯3 ¯2 ¯8)
¯6 49 ¯10
(0.95972 0.25833 0.22140) f (0.93507 ¯0.80917 ¯0.99177)
¯0.0770537061 1.158846002 ¯1.018133265
(1024.28 ¯2316.39 2567.14) f (¯2290.77 1941.87 712.09)
¯6634530.307 ¯6610106.843 ¯3317298.117
```
] |
[Question]
[
Given two lists of numbers, a *source* and a *pattern*, reorder the source to match the relative ordering of the pattern. Any two entries of the reordered source should compare the same way as the entries at those same positions of the pattern.
For example, the input
```
s = [-5, 9, 4, 13, 11, -6, 0]
p = [7, -4, 1, -8, 4, -3, 12]
```
should produce the result
```
[11, -5, 4, -6, 9, 0, 13]
```
Comparing the first and last positions, the result has `11<13`, which matches `7<12` in the pattern.
**Input:** Two equal-length non-empty lists of integers. Each list will have no repeats. It's up to you whether the source or pattern is given first.
**Output:** A list that rearranges the source numbers to have the same relative ordering as the pattern numbers.
**Leaderboard:**
```
var QUESTION_ID=62587,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/62587/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
## CJam, 12 10 bytes
```
{_$f#\$f=}
```
This is an anonymous function, which takes `s p` on the stack and leaves the result on the stack. [Online demo](http://cjam.aditsu.net/#code=%5B-5%209%204%2013%2011%20-6%200%5D%5B7%20-4%201%20-8%204%20-3%2012%5D%0A%0A%7B_%24f%23%5C%24f%3D%7D%0A%0A~%60)
With thanks to [Martin Büttner](https://codegolf.stackexchange.com/users/8478/martin-b%c3%bcttner) for 2 bytes.
### Dissection
```
{ e# Define an anonymous function
_$f# e# Use a copy of the pattern to map each element to its sort index
\$ e# Sort the source
f= e# Map each sort index to the corresponding source element
}
```
[Answer]
# J, 9 bytes
```
/:^:2~/:~
```
This is a dyadic verb that takes **p** and **s** as left and right arguments. Try it online with [J.js](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=7%20_4%201%20_8%204%20_3%2012%20(%2F%3A%5E%3A2~%2F%3A~)%20_5%209%204%2013%2011%20_6%200).
### Test run
```
7 _4 1 _8 4 _3 12 (/:^:2~/:~) _5 9 4 13 11 _6 0
11 _5 4 _6 9 0 13
```
### How this works
Say we defined assigned the left and right input from the example via
```
p =: 7 _4 1 _8 4 _3 12
s =: _5 9 4 13 11 _6 0
```
Then:
* The train `/:^:2~/:~` is a hook of the verbs `/:^:2~` and `/:~`, so calling
```
p (/:^:2~/:~) s
```
executes
```
p /:^:2~ /:~ s
```
* The adverb `~` in `/:~` is *reflexive*, since `/:` is used monadically. Thus, calling
```
/:~ s
```
executes
```
s /: s
```
* The adverb `~` in `/:^:2~` is *passive*, since the verb `/:^:2` is used dyadically. Thus, calling
```
p /:^:2~ y
```
executes
```
y /:^:2 p
```
* The adverb `^:` is *power*. Thus, calling
```
y /:^:2 p
```
executes
```
y /: y /: p
```
Putting it all together, calling
```
p (/:^:2~/:~) s
```
executes
```
(s /: s) /: (s /: s) /: p
```
### How *that* works
Dyadic `/:` is *grade up using*, i.e., `x /:y` returns the elements of **x**, sorted according to the corresponding values of `y`.
* `s /: s` simply sorts the elements of **s**.
* `(s /: s) /: p` sorts the (sorted) elements of **s** according to the corresponding values of **p**.
* Grading up twice essentially computes the ordinals of its right argument.
Thus, `(s /: s) /: (s /: s) /: p` sorts the (sorted) elements of **s**, imitating the order of the elements of **p**.
[Answer]
# Mathematica, ~~32~~ 27 bytes
```
Sort@#~Permute~Ordering@#2&
```
Example usage:
```
Sort@#~Permute~Ordering@#2 &[{-5, 9, 4, 13, 11, -6, 0}, {7, -4, 1, -8, 4, -3, 12}]
(* {11, -5, 4, -6, 9, 0, 13} *)
```
Previous attempt:
```
Sort[#][[Ordering@Ordering@#2]]&
```
[Answer]
## J, 17 bytes
```
(A.^:_1/:~)~A.@/:
```
This evaluates to a dyadic (meaning binary) verb. It can be evoked as follows:
```
_5 9 4 13 11 _6 0 ((A.^:_1/:~)~A.@/:) 7 _4 1 _8 4 _3 12
11 _5 4 _6 9 0 13
```
## Explanation
This may not be the shortest possible J solution, but it's a novel approach.
```
Left input is x, right input is y.
A.@/: The index of the permutation P that sorts y. /: gives the
permutation itself, and A. gives its index in the sorted
list of all its permutations.
/:~ x sorted in ascending order. We are applying the x-sorting
permutation to x itself.
(A.^:_1 )~ The inverse of the permutation P applied to the sorted
version of x. Since P maps y to its sorted version, its
inverse maps the sorted version to y, and thus sorted x to
the correct output.
```
[Answer]
# Pyth, 10 bytes
```
@LSvzxLSQQ
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=%40LSvzxLSQQ&input=%5B-5%2C%209%2C%204%2C%2013%2C%2011%2C%20-6%2C%200%5D%0A%5B7%2C%20-4%2C%201%2C%20-8%2C%204%2C%20-3%2C%2012%5D)
### Explanation
```
@LSvzxLSQQ implicit: z = first input line as string
Q = second input line evaluated
SQ sorted(Q)
xLSQQ find the index for each element of Q in sorted(Q)
Svz sorted(evaluated z)
@LSvz take the element in ^ for each index
```
[Answer]
# Pyth, 7 bytes
```
XQSQSvz
```
This is a full program that expects string representations of **s** and **p** on two lines. [Try it online.](http://pyth.herokuapp.com/?code=XQSQSvz&input=%5B-5%2C+9%2C+4%2C+13%2C+11%2C+-6%2C+0%5D%0A%5B7%2C+-4%2C+1%2C+-8%2C+4%2C+-3%2C+12%5D)
### How it works
```
Store the first line of input (rep. of s) in z.
Evaluate the second line of input and store the result (p) in Q.
SQ Sort the elements of p.
Svz Evaluate the repr. of s and sort its elements.
XQ Perform transliteration on p.
This replaces the lowest element of p with the lowest element of s, etc.
```
[Answer]
# Python 2, 51
```
lambda s,p,a=sorted:[a(s)[a(p).index(x)]for x in p]
```
[Answer]
# Mathematica ~~56 43 30~~ 29 bytes
```
o=Ordering;Sort[#][[o@o@#2]]&
```
`Ordering@#2` returns the order of numbers in the pattern.
`Ordering@Ordering@#2` gives the positions that the sorted elements in the source should occupy.
`Sort[#][[o@o@#2]]&` returns the source in the required positions, namely, those that have the same relative ordering as the pattern list.
**Testing**
```
o=Ordering;Sort[#][[o@o@#2]]&[{-5, 9, 4, 13, 11, -6, 0}, {7, -4, 1, -8, 4, -3, 12}]
```
>
> {11, -5, 4, -6, 9, 0, 13}
>
>
>
[Answer]
# CJam, 8 bytes
```
{_$@$er}
```
This is an anonymous functions that expects **s** and **p** (topmost) on the stack and pushes the reordered **s** in return. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q~%0A%20%20%7B_%24%40%24er%7D%0A~p&input=%5B-5%209%204%2013%2011%20-6%200%5D%0A%5B7%20-4%201%20-8%204%20-3%2012%5D).
### How it works
```
_ e# Push a copy of p.
$ e# Sort it.
@ e# Rotate s on top of p and the sorted p.
$ e# Sort s.
er e# Perform transliteration.
e# This replaces the lowest element of p with the lowest element of s, etc.
```
[Answer]
## J, 13 bytes
```
/:@/:@[{/:~@]
```
I'm still having trouble wrapping my head around J's verb composition, so I feel like some of those `@` and `[]` might be unnecessary. If some more experienced J user could let me know if this can be compressed, that would be great. :)
The verb can be used as follows:
```
7 _4 1 _8 4 _3 12 (/:@/:@[{/:~@]) _5 9 4 13 11 _6 0
11 _5 4 _6 9 0 13
```
### Explanation
```
/:@/:@[{/:~@] NB. Left input is the pattern, right input is the source.
/:~@] NB. Sort the source.
/:@/:@[ NB. Compute the ordering of the ordering of the pattern.
{ NB. Use those as indices into the sorted source.
```
[Answer]
## Python 2, 48
```
lambda*l:map(dict(zip(*map(sorted,l))).get,l[0])
```
A big glob of functions. This uses the element translation approach of many other answers using a dictionary.
The starred input `*l` expects the patterns and source in that order, and turns them into a list `l`.
Mapping `sorted` sorts both lists, and `dict(zip(_))` turns a pair of lists into a dictionary with keys from the first list matched with values in the second, in ascending order. So, the result is that that `i`-th largest element of the pattern is matched with the `i`-th largest element of the source.
Finally, we transform the pattern (`l[0]`) via this dictionary by mapping its `.get` method.
[Answer]
# Bash + coreutils, 55
```
nl $2|sort -nk2|paste <(sort -n $1) -|sort -nk2|cut -f1
```
Input is taken as two filenames, for the source and pattern respectively:
```
$ ./imitord.sh source.txt pattern.txt
11
-5
4
-6
9
0
13
$
```
[Answer]
## R, 38 bytes
```
function(s,p)sort(s)[match(p,sort(p))]
```
[Answer]
# Ruby, 51 bytes
```
->s,p{s.map{|x|s.sort[p.sort.index(p[s.index x])]}}
```
[Answer]
## APL, ~~17~~ 12 bytes
```
{⍺[⍋⍺][⍋⍋⍵]}
```
Thanks to @Dennis, this is now very elegant.
Here's a nice 14-byte solution that doesn't use double indexing:
```
{⍺[(⍋⍋⍺)⍳⍋⍋⍵]}
```
Unfortunately, we can't index arrays from within trains in APL.
[Answer]
## Haskell, 65 bytes
```
import Data.List
s#p=[sort s!!i|b<-p,(i,e)<-zip[0..]$sort p,b==e]
```
Usage example: `[-5,9,4,13,11,-6,0] # [7,-4,1,-8,4,-3,12]` -> `[11,-5,4,-6,9,0,13]`.
How it works:
```
b<-p -- for every b in p
,(i,e)<-zip[0..]$sort p -- walk through the sorted list of p
-- paired with it's index ->
-- (index,element) or (i,e)
,b==e -- for those cases where b equals e
sort s!!i -- take the i-th element from the
-- sorted list s
```
[Answer]
## R, 37 bytes
```
function(s,p,o=order)s[o(s)][o(o(p))]
```
[Answer]
# TeaScript, 15 bytes
```
ys¡m™x[yi(l)])
```
This takes input as an array. The interpreter is currently down because I'm putting up the fancy new interpreter
### Explanation
```
y // Second input
s¡ // Sort it = s()
m™ // Map over it = m(#
x[ // Num in first input at index...
yi(l) // Current char's index in y
]
)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes, language postdates challenge
```
Œ¿œ?Ṣ}
```
[Try it online!](https://tio.run/nexus/jelly#@3900qH9RyfbP9y5qPb////R5joKuiY6CoZAykJHAcjSNQbyjGL/R@ua6ihYgoUMQUIgFWY6CgaxAA "Jelly – TIO Nexus")
This takes the pattern, followed by the source, as two separate arguments.
## Explanation
```
Œ¿œ?Ṣ}
Œ¿ Generate an integer that describes the order of {the first input}
œ? Use that integer to reorder
Ṣ} the sorted version of the second {input}
```
[Answer]
## Haskell, 56 bytes
```
import Data.List
p%s=[sort s!!(length$filter(<x)p)|x<-p]
```
Defines a binary function `%`. Each entry in `p` is transformed to the entry of `s` with the same order statistic, i.e. relative rank in its list. The order statistic of `x` in `p` is found by counting the elements smaller than it (`sort p!!x` produces an annoying `Maybe`). The result is indexed into `sort s`.
A `zip/lookup` solution is the same length, except it gives `Just` numbers.
```
import Data.List
p%s=[lookup x$zip(sort p)(sort s)|x<-p]
```
] |
[Question]
[
Your challenge is to sort a string, but rather than by the normal alphabetical order (abc..xyz), you will be sorting strings by a specified alphabet.
You must write a program or function that takes two inputs: An alphabet **A** and an string **S**. Both will only contain lowercase English letters, and both will contain at least one character.
You must move letters in **S** so that the letter that appears first in **A** appears first, then whichever letter appears second in **A**, etc. There may be some letters in **S** that do not appear in **A**, these should be left at the end and not moved around relative to each other.
Test cases:
```
A S Result
axd haxuizzxaxduxha aaaxxxxdhuizzuh
a xyz xyz
abc dcba abcd
il nmiuplliu iillnmupu
asdf qwerty qwerty
```
Fewest bytes wins!
[Answer]
# [Python 3](https://docs.python.org/3/), ~~50 47 46~~ 44 bytes
*-3 bytes thanks to ngn!*
*-1 byte thanks to mypetlion*
```
lambda a,s:s.sort(key=lambda c:a.find(c)%27)
```
[Try it online!](https://tio.run/##LYnLDsIgEEX3/Qo2BkhIF7owadIv0S7GUtKJlFYeceDnkaire885R47r7i7VjPdqYXtoYKDCEPqw@yieSx7/dh6gN@i0mOXpfJXV7J6RygwduwkOpLniK1DCUqhRohW4VK00T7l8P9oGbsN0WIvpl4M2Tb7ei4@Zy2noWBkthiiy7JgRpErbw6OLosj6AQ "Python 3 – Try It Online")
Takes in a string as the alphabet and a list of chars as the string and sorts the list in place.
The `%27` ensures that if the character is not in the alphabet, the index returned puts it after the rest of the alphabet.
[Answer]
## Haskell, 42 bytes
```
a#s=[c|c<-a,d<-s,c==d]++[c|c<-s,all(/=c)a]
```
[Try it online!](https://tio.run/##VcpBCsIwEIXhvacYpi6UpniBzkmkiyERMjiNxRiYBu8eW1x1@d73R87Ph2pr3GW6@68fB3ZhHLLzRGHq@/@XHatebuSvPLWZJQFBeJ0AlrekD5wBkC0gdICRrUittu1ikfEQiSLsUZqlLKpSjsyb7mxrxfYD "Haskell – Try It Online")
```
a#s= -- take alphabet a and string s
c<-a -- for all c in a
d<-s -- for all d in s
[c| c==d] keep c if c equals d
++ -- append
[c|c<-s ] -- all c of s
,all(/=c)a -- that are not in a
```
[Answer]
# [Perl 6](https://perl6.org), ~~55~~ 43 bytes
```
->\A,\S{[~] S.comb.sort:{%(A.comb.antipairs){$_}//∞}}
```
[Try it](https://tio.run/##VU7LTsMwELz7K/YQUCNa99ZDo1bkzolwo6ja2q5i4SQmtqnbKJz5Cj6OHwnOQ6IdydLO7Mx4tajVqnNGwOeKsoSQ4gz3rOICNt1iu0vnu6x5/XqDjLKqOFBT1Xbd3M3SkWJppUZZm7iJ9u1y@fv907ZdqHi0wljYgJKlMNS8S00L1GtogJ6qmhv6JI2dQ7SHlpD@95fgT4hWWMLDEA6nHKt6KlpsYTaL0hDIwhNeC2YFj8PMhWExNARAGujv7m1RFl/ZJldC2i6FERnc4lkYpyxBzweao3fycvGBO58jIKIP4HmvupzgFPPny01N4AQPbJg5O@D1LuicSDWSspBOKyXdtJRSqbJw2hE0/NgrHydR2/N/fOR/ "Perl 6 – Try It Online")
```
->\A,\S{[~] S.comb.sort:{A.index($_)//∞}}
```
[Try it](https://tio.run/##VU7LboMwELz7K/aAKlAT55ZDUKJy76n01lSRsR1h1YCL7caA6Llf0Y/rj1DzkJKMtNLO7MzuKl7L7WA1h68tpjFCRQMPtGIc9sP6cExWx7R7@36HFNOqyLCuarPrEixKxl0YnKLN5u/nt@8HH3syXBvYgxQl11h/CIULonbQAb5UNdP4WWizguAEPULjxVfvj5GSpITHKezPn6t6WbQ@QBgGiQ@kvrhTnBrOIt8zrmkEHQIQGsZfR1uQRje2xRWjfkhgRgr3eOHaSoOIYxPNibOibZ3n1uUECCHOg@WjanNElphr2rs1niOS0alnNCO3M68zJORMykJYJaWwy1AIKcvCKouIZudR@bzw2jTX@Mz/AQ "Perl 6 – Try It Online")
## Expanded:
```
-> \A, \S {
[~] # reduce using &infix:«~» (shorter than `.join`)
S.comb.sort: # split into character list and sort by:
{ # bare block lambda with implicit parameter $_
A.index( $_ ) # get the position
// # if it is undefined (not in `A`)
∞ # return Inf instead (so it comes at end of result)
}
}
```
[Answer]
# [Haskell](https://www.haskell.org/), 40 34 bytes
**-6** bytes huge thanks to [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni).
```
foldr(\c->r(==c)<>r(/=c))
r=filter
```
[Try it online!](https://tio.run/##ZYsxD4IwFIR3fsVL4wADGBMHB3DRRBcTRweX2lJ58dFiKbHw463VUW65y313De8fNVHAtjPWwZ47XpyMNighTcttlkGeg9E0gjIWDscdlJtiXaySREEF16AMSZteRb61aVWJrIy@jJ4ltlJIrrah5ajjVpoEojqL2sECFLCG@wGnyXMvB99wBiwm9r/y4/Qls16K2@9yEzOkWxw6IhwiR5rh56u2bvx@e6lYeAtF/N6H/LI7nz8 "Haskell – Try It Online")
The first line is an expression that takes two arguments: **S** and **A**.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 6 bytes
```
{xrINo
```
[Run and debug it](https://staxlang.xyz/#c=%7BxrINo&i=%22axd%22+++++%22haxuizzxaxduxha%22&a=1)
This sorts by a block that does this.
* Reverse the alphabet.
* Get the index of each character in the reversed alphabet. Missing yields -1.
* Negate the index.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
Rvy†
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/qKzyUcOC//8TK1K4MhIrSjOrqiqA7NKKjEQA "05AB1E – Try It Online")
**Explanation**
```
R # Reverse the alphabet
vy # For each letter ...
† # Push S with the current letter filtered to the front
```
[Answer]
# [Python 2](https://docs.python.org/2/), 38 bytes
```
def f(a,s):s.sort(None,a[::-1].find,1)
```
**a** must be a string, **s** a list of strings of length 1. **f** sorts **s** in place.
[Try it online!](https://tio.run/##NY6xCoMwFEVn/Yq3SAxEwUIpCB27Oth2Kh1iYzBgE@tLaPTnrYF0e@eey@VNix2MPmyb6CXInDOkNZZoZps3RveMP@q6qJ6lVFqwim7SzLC3ACkoDTnhXhAGZODeqXX1Ozo/cEJZcMH4ZY3UvQKLVxe1GgPrt3LTOCoXWyhkiD/ffrYLoXWaIJxhVGhzpGkyzUpbIFlxQsiK6ogEsvhQmsj/EVvt5XZvm@u@hzHbfg "Python 2 – Try It Online")
### Alternate version, string I/O, 48 bytes
```
lambda a,s:`sorted(s,None,a[::-1].find,1)`[2::5]
```
[Try it online!](https://tio.run/##LY5NCoMwGETX7Sm@jcRALChIIdAr9AJWMBqDAU1sfmj08qlBNwNv3ixm3dykVRUFvOATZ7b0nAEjlnZWGzfy3JK3ViNhDaVF2T6EVJyUuGsqSus2Cm0gZwQsBqkgRyxwRABNLHi57@FAHyaGMEkumbDtF/VDYj70l5ZzYrVIv86z9NfKcpHq7280bkOY3m@rkcoByoqnhawo6yMtguy8QUCcd3D8Aw "Python 2 – Try It Online")
### How it works
`s.sort(None,a[::-1],1)` is shorthand for `s.sort(cmp=None,key=a[::-1],reverse=1)`.
From [the docs](https://docs.python.org/2/library/functions.html#sorted):
>
> *reverse* is a boolean value. If set to `True`, then the list elements are sorted as if each comparison were reversed.
>
>
>
[Answer]
# [J](http://jsoftware.com/), 5 bytes
```
]/:i.
```
Dyadic verb, taking the alphabet on its left and the string to be sorted on the right.
`i.` finds the indeces of string's characters in the alphabet, the alphabet length if not found.
```
'axd' i. 'haxuizzxaxduxha'
3 0 1 3 3 3 3 1 0 1 2 3 1 3 0
```
`/:` sorts its left agrument according to the order specified in the right one.
`]` the rigth argument (the string)
```
'haxuizzxaxduxha' /: 3 0 1 3 3 3 3 1 0 1 2 3 1 3 0
aaaxxxxdhuizzuh
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/Y/WtMvX@a3IpcKUmZ@QrqCdWpKgrpCmoZyRWlGZWVVUA@aUVGYnqMGmwZEVlFVwgKRkslJKcBFeUmQMWysvNLC3IyckshastTkkDyxSWpxaVVKr/BwA "J – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 5 [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, taking `[string,ordering]` as argument.
```
⍋⍨/⌷⊃
```
[Try it online!](https://tio.run/##ZYy9DsFQFMd3T3G3sxCDJxALk6T1AoerepOLojduu0oMtA2D0W4zmiwe5bxInbYkPv7DSc7/44eBbsgI9XyS55TuKb00KbnRbpN7tD1QmlF26vX5f1xbtD3y5zodvoNuz@XBWQjRFpVc8SdnvDI6rHmCkjuglcAe@GiNimPLv7E@gigwiGhZ0i8i41eT@uMCWG5sFMMXudiw@UYPR2VNjoYIvzUO5aundJnCbKpMoLUy8NFTSuvZ1ATmDV1Jj3NYrMfLMIJvaGU@AQ "APL (Dyalog Unicode) – Try It Online")
…`/` Reduce by the following function:
…`⍨` namely the reversed-arguments version of the following function:
`⍋` grade the right string according to the left ordering (missing letters go at the end)
`⌷` use that to index into…
`⊃` the first element of the argument (i.e. the string)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~35~~ 50 bytes
```
lambda a,s:sorted(s,key=lambda c:-a[::-1].find(c))
```
[Try it online!](https://tio.run/##LY1NCsMgGETX7SncqWAK7VJIL5Jm8UUjkRqT@EM1l7cR3M2bNzB7DstmX0X1n2JgnSQgYJ77zYVZEs@@c@5bL3gHA@fdc3wobSURlBa1ubpH2qKBYEgSM4QXSFGfZ7owpgUwZehy1aR8NppEZSmmprWpbFcdd2N0bCsvVa2P3@xCxnTk99vutA31k@H@jZkiV6TlDw "Python 2 – Try It Online")
Takes `a` and `s` as strings; returns a list of singelton strings.
Note: Ouch! Gained 15 bytes to fix...
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), 9 bytes
```
{y@>-x?y}
```
[Try it online!](https://tio.run/##NYxBDoIwEEX3noI0LiARD0AT9RDsSBMGam1DKYg2TiF49doGnM3M///96XLzMN6LYnG3S45Xt/qyWI6V@06FSM4J0nroaFoLUJoidXTK2Hooq5QAckKJBLRqnjEoixJIRgkAYBguY2AlYRE/EQg0ujkScbHtSdMGm7fN1mxavgdKB9/0yo5aKxtDpbQ2vR3tv/riIjDPz316uwjsF/M/ "K (ngn/k) – Try It Online")
`{`...`}` is a function with arguments `x` and `y`
`x?y` finds for each element in `y` the index of its first occurrence in `x`; if an element is not found in `x`, its index is considered `0N` (-263)
`-` negates all indices except that it keeps the `0N`-s intact, because 263≡-263 (mod 264)
`>` returns a sort-descending permutation
`y@` indexes `y` with that
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes
```
Fθ×ι№ηιΦη¬№θι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBo1BTIaAoM69EIyQzN7VYI1NHwTm/FMjN0FHI1NTUtOaCyLpl5pSkFoFE/fJLNCBKCiFKNK3//0@sSOHKSKwozayqqgCySysyEv/rluUAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ First input
F Loop over characters
η Second input
ι Current character
№ Count matches
ι Current character
× Repeat
Implicitly print
η Second input
Φ Filter
θ First input
ι Current character
№ Count matches
¬ Logical not
Implicitly print non-matching characters
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
fⱮ;ḟ
```
A dyadic link accepting the string on the left and the alphabet on the right (as lists of characters) and returning the result (also as a list of characters).
**[Try it online!](https://tio.run/##y0rNyan8/z/t0cZ11g93zP///39GYkVpZlVVRWJFSmlFRuJ/IA0A "Jelly – Try It Online")**
### How?
```
fⱮ;ḟ - Link: string; alphabet e.g. smallnotxl; xl
Ɱ - map (for each character in the alphabet): 1=x; 2=l
f - filter keep (keep occurrences of this character from string) x lll -> xlll
ḟ - filter discard (discard all alphabet characters from string) smanot
; - concatenate xlllsmanot
```
[Answer]
# JavaScript (SpiderMonkey), 50 bytes
Takes input in currying syntax `(a)(s)`, where **a** is a string and **s** is an array of characters. Returns an array of characters.
```
a=>s=>s.sort((b,c)=>(g=c=>-1/a.search(c))(b)-g(c))
```
[Try it online!](https://tio.run/##fU7NcoQgDL73KZhcFmYqTh9AX6TTQwQUtggWpEVf3uLs1oPbNpNDku8n3xU/MYpgprmKk5EqjN69q2Xrmw2bNpbm0YeZ0u5ZsKalQyOatnqpkUeFQWgqGKMdq4Z92IR30VvFrR9oTwGzBMLoK@ccNOZk1jWXW8oa4Y3xqzeOXi6MkbomiJhLSb2zkn46WwEhP1Z5WfftqLNVwR/knTiSSNEh/CMvXHnWGwvHezeaNFlrEvyuN8ZaN6YpPYSIsoe7yceXCvMCf4a44ds3 "JavaScript (SpiderMonkey) – Try It Online")
### How?
We define the helper function **g()** as:
```
c => -1 / a.search(c)
```
which returns:
* **1** if **c** does not belong to the alphabet
* a float value in **[-Inf, 0)** based on the position of **c** in the alphabet otherwise (-Inf, -1, -1/2, -1/3, etc.)
We sort **s[ ]** by computing **g(b) - g(c)** for each pair of characters **(b, c)** passed to the callback of **sort()**.
Because the implementation of **sort()** in SpiderMonkey is stable, all characters of **s[ ]** that do not belong to the alphabet are simply moved at the end in order of appearance and are let unchanged when they are compared with each other.
---
# JavaScript (ES6), 61 bytes
Takes input in currying syntax `(a)(s)`, where both **a** and **s** are arrays of characters. Returns a string.
```
a=>s=>a.map(C=>s=s.filter(c=>c!=C||!(o+=c)),o='')&&o+s.join``
```
[Try it online!](https://tio.run/##bU7LjsIwDLzvVwQfIBEQviC98BkrJEzSUqM06TbNbqj499KKl2A7J8/YM@MT/mLQDdXt2nmT94XqUWVBZSgrrPl2nIMsyLZ5w7XK9ExtL5cZ90ulhVh5tViI@dwvgzx5cvt9r70L3ubS@iMv@LeUEjAZYDtxIyWmSF2XBjGmEmEnBNtsGCKmAaYcl7H8mooBxp4x6dyN9Il7zCBPWg/69YHRB4T/1uHGTHnJwqvWVRRraynCm5fIWlfFOk6WB1PAI@DnL2/aM3yW3@T@Cg "JavaScript (Node.js) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~69 62~~ 58 bytes
```
function(a,s)c(rep(a,rowSums(outer(a,s,"=="))),s[!s%in%a])
```
[Try it online!](https://tio.run/##XYvBbsMgEETv@Yp2o0gg8Qt8RY5VDxjseCWMKcsq2D/vLI5UVd3L7MybKcdkj4mTr7gm5Qxpr8qY5Svr884LqZXrWDoxYC1orQ19fdIN08196@Nhf8fNbNq7qibFKSJVRbVQjliFnGpB5uY/3P5AbeAChsbc3eWhwLUABmbXGPe9ieM2O9DXD@dckwtzBzyfXWm2be9U5EwGL1nww3sy@NBTjBKmBTnHiNwJYoxp4czniMIkhZ/nWOrW6fs7Xg "R – Try It Online")
Input and output are vectors of individual characters.
Explanation:
```
function(a,s)c( , ) #combine:
a, #[each char in a
rep( #each repeated
rowSums( ) #the number of
outer(a,s,"==") #occurrence in s]
s #with s
[ s%in%a] #all chars in a
! #omitted
```
[Answer]
# [Brain-Flak (BrainHack)](https://github.com/Flakheads/BrainHack), 118 bytes
```
{({}(<>))<>}{}<>{<>([[]()]<{<>(({})<({}<>[({}<>)]){(<()>)}{}{}>)<>}<>({}<{({}<>)<>}<>>)>[]){({}()<(({}))>)}{}{}<>{}}<>
```
[Try it online!](https://tio.run/##NY0xCkJBDETvslWmEDxACHiOZYuoxX4EC@HD8kPOHpMvNkOGNzO5f3R7T328IozMiQVgcXMWY6HeB2FwnUnBVKCfigEjJggybS5Vy1gi@/HTC6RXMKezXRv/Qj7wlIi43KLpera4Rpu69u04Vvp9TW1f "Brain-Flak (BrainHack) – Try It Online")
Input is the first string, followed by a null, followed by the second string. A version that uses a newline as the separator instead adds 24 bytes:
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 142 bytes
```
(()){{}(({}(<>))[(()()()()()){}]<>)}{}<>{<>([[]()]<{<>(({})<({}<>[({}<>)]){(<()>)}{}{}>)<>}<>({}<{({}<>)<>}<>>)>[]){({}()<(({}))>)}{}{}<>{}}<>
```
[Try it online!](https://tio.run/##NU1BCsNACLz3Jc4hPxA/suzBtpSElB4KgSXi261uCaKMM6Nz/@r2WV5v3SOIADMnymYBWhJXwbwn5@YsxkKtdULngmkHUwltTnQYMWG6zQUsyZZkf33uAmllzKy8rh/XQQZ4jggdz9uq49jOcyQ@xqqxPH4 "Brain-Flak – Try It Online")
### Explanation
```
# Move A to other stack reversed
# Zeroes are pushed under each character for later.
# (This is the only part that needs to change in order to use newline as separator.)
{({}(<>))<>}{}<>
# For each character in A, starting at the end:
{
# Track current length of S.
<>([[]()]<
# For each character in S:
{
# While keeping character from A
<>(({})<
# Move character from S to second stack and push difference
({}<>[({}<>)])
# Delete character if equal
{(<()>)}{}{}
>)
<>}
# Move S back to first stack while maintaining character from A
<>({}<{({}<>)<>}<>>)
# Push difference between old and new lengths of S
>[])
# Insert character from A at beginning of S that many times
{({}()<(({}))>)}{}{}
<>{}}<>
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 97 bytes
```
f(D,d,S,s,i,o)char*D,*S;{
while(d--){
for(i=o=s;i--;)S[i]-D[d]?S[--o]=S[i]:0;
while(o--)S[o]=D[d];
}
}
```
All whitespaces (spaces and newlines) in the code above are only for readability and should be removed.
The dictionary is passed in `D` and have length `d`, the string is passed in `S` and have length `s`. `i` and `o` should be omitted.
[Try it online!](https://tio.run/##PU3LboMwELzzFStXFXZkV@21Du2FP@DocrBsqFdKcIRBtUB8O12SqnNY7c5jx6lv5/a957X0spFJoozCBTueanlq9PoT8NJxr5RY@zhyrGKVNCqlRWOwVbXx7WdjlIptdRDvr/qRiJRoDLGHQ2/b/oSDu8y@g3OaPMaX8FEcNWBNCxWspS0llPkYvtz0Q0t3jQWbZ1yWbLOfc7BMFzhMcLU4cAFrAYSeWwkJly7SJmj9v5IABW9C3223eUrE/B0jvek5e/ZfAyP/NLrrjVOSWWszwYejdg5MUGLbfwE "C (gcc) – Try It Online")
[Answer]
# [Pyth](https://pyth.readthedocs.io), ~~9~~ 5 bytes
```
ox+vz
```
[Try it here!](https://pyth.herokuapp.com/?code=%2Bs%40RQKE-K&input=%22axd%22%0A%22haxuizzxaxduxha%22&debug=0)
```
ox+vz Full program. Input format: "S" \n "A".
o Sort the characters of S by (variable: N)...
x ... N's index in...
+vz ... A + N
```
[Answer]
# Java 8, 98 bytes
```
a->s->{for(int i=a.length;i-->0;s=s.replaceAll("[^"+a[i]+"]","")+s.replaceAll(a[i],""));return s;}
```
[Try it online.](https://tio.run/##jY/NasMwEITveYpFJ5vEonc3hl566ynHkMLGP8kmG1m1Vqmd4Gd3ZZocCoYaBBL7aWZnTnjF5FSch5zROfhAMvcFgBMUyuEUqPZCrCtvcqHa6PfH43UjDZnDdrea8WsFv3eWQQXrAZPMJdm9qpuIjACtUXNpDnJMKUmyl9StnW5Ky5iXb8yR2n6qJW5pt1Q7tVIqXv7BIxmncdqU4hsDLu2HNJQIx/o9hx6POteaCriEitEzPGA81gXYdE7Ki669aBuQsIkqjdZyFylsC6WdZZJoXPMcH7H1dLu1Afv2iGOA/62mjNruNk@8z6fkRb6ft5x4Sm4u5C0z@XkZXFFNuXx9l410D4t@0Q8/)
**Explanation:**
```
a->s->{ // Method with String-array and String parameters, and String return-type
for(int i=a.length;i-->0;
// Loop backwards over the alphabet
s= // Replace the current `s` with:
s.replaceAll("[^"+a[i]+"]","")
// All the current characters of `a` in `s`
+s.replaceAll(a[i],""));
// Concatted with everything else
return s;} // Return the modified `s`
```
[Answer]
## [Perl 5](https://www.perl.org/) with `-pF`, 43 bytes
```
$_=<>;print$F[0]x s/@{[shift@F]}//g while@F
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3tbGzrqgKDOvRMUt2iC2QqFY36E6ujgjM63EwS22Vl8/XaE8IzMn1cHt///EihSujMSK0syqqgogu7QiI/FffkFJZn5e8X/dAjcA "Perl 5 – Try It Online")
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), 136 bytes
```
X/_/[X|_].
X/Y/[Z|R]:-Y\=Z,X/Y/R.
i(_,X,[],[X]).
i(A,X,[Y|R],[X,Y|R]):-X/Y/A.
i(A,X,[Y|R],[Y|S]):-i(A,X,R,S).
A*S*T:-foldl(i(A),S,[],T).
```
[Try it online!](https://tio.run/##XYzBCoMwEETvfkUvgsok3oUe/AXjIZoGEaQ1kKq0hIr473a33rp72H07M7u8Zj8/xPvjjkPnXW703lkZ6bzJTbtXthDN7dqCuZKRSzpoGAujbcpYMjbkowt4poVgb/knNrti6bxVUBQuM5XVhbjPfvAJCSkUf65TeRyx6bFisJkZwVuAw0a9/mggXkGKzZS8xH3fr1TDGNy2hTEyDp6SE56UCljgqWk73c55Pz3DEr4 "Prolog (SWI) – Try It Online") Example usage:
```
[i,l]*[n,m,i,u,p,l,l,i,u]*S.
S = [i, i, l, l, n, m, u, p, u]
```
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 61 bytes
```
import StdEnv
$a s=[c\\c<-a,k<-s|k==c]++[c\\c<-s|all((<>)c)a]
```
[Try it online!](https://tio.run/##RYzLDoIwFET3fEUTSYAgf0Bd6cLEHUtgcb28GvogtDWV8O1WgkaXc87MIG9BeqEay1sigEnPxKRmQwrTXOQjCIFoWmJVYZ7BccwzvY6UYp2mX6hX4DyO81OCCdS@MDCb4ECATwPcW0MoKSNwTVRvUJuZyX5HAzjLlsVtyroBdt1ZiYYpuRXCgP7j7@uz9y/sOPTaZ9ebPz8lCIb6DQ "Clean – Try It Online")
Defines the function `$ :: [Char] [Char] -> [Char]`.
Unsurprisingly, this is literally [nimi's Haskell answer](https://codegolf.stackexchange.com/a/165488/18730) but longer.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
i@oİ$¥Þ
```
[Try it online!](https://tio.run/##y0rNyan8/z/TIf/IBpVDSw/P@///f2JSctX/xOQkAA "Jelly – Try It Online")
[Answer]
# APL+WIN, 12 bytes
Prompts for screen input of S then A:
```
s[(,⎕)⍋s←,⎕]
```
[Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/4XR2voAIU0H/V2FwNFQezY/0CZ/2lc6hmJFaWZVVUViRUppRUZiepc6kCWOgA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [PynTree](https://github.com/alexander-liao/pyn-tree), 13 bytes
```
§yz:ṡzCæf+yxx
```
[Try it online!](https://tio.run/##K6jM0y0pSk39H@CV/P/Q8soqq4c7F1Y5H16Wpl1ZUfE/mkspsSJFiUspI7GiNLOqqgLIK63ISFTiiv0PAA "PynTree – Try It Online")
Port of Jo King's Python answer.
# Explanation
```
§yz:ṡzCæf+yxx Anonymous lambda
§ lambda ,
y y
z z
: :
ṡ sorted( ,lambda x:
z z
C ( )( )
æf ( ).find
+ +
y y
x x
x x
```
] |
[Question]
[
# Introduction
Classically, booleans are one bit; `true` or `false`, `1` or `0`. Leading zeros would just be redundant. For example, `001` means the same as `00001` or just `1`.
# The 32-bit boolean
Given a truthy/falsey value, output the equivalent 32-bit boolean as a string.
(Or as a number if for *some reason* your language supports leading zeros.)
**Your program doesn't have to work for every truthy/falsy type, only what your programming language work best for.**
# Example i/o
```
Input >> Output
truthy >> 00000000000000000000000000000001
falsey >> 00000000000000000000000000000000
```
## This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest bytes wins!
[Answer]
# [Python 3](https://docs.python.org/3/), ~~33~~ ~~25~~ ~~18~~ 15 bytes
Thanks @jurjen-bos for the `__mod__` tip.
```
'%.32d'.__mod__
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzX11Vz9goRV0vPj43PyU@/n9BUWZeiUaahqGmJheMbYDEDikqTUXiuiXmFAP5/wE "Python 3 – Try It Online")
[Answer]
# x86-16 Machine Code (DOS), 16 bytes
```
B4 02 mov ah, 2
B2 30 mov dl, '0'
B9 1F 00 mov cx, 31
PrintZeros:
CD 21 int 0x21
E2 FC loop PrintZeros
00 CA add dl, bl
CD 21 int 0x21
C3 ret
```
The above function receives a boolean value (0 == falsey, 1 == truthy) in the `BL` register (low byte of `BX`), and prints a "redundant boolean" string to the standard output.
It works by invoking an interrupt (0x21) to make a DOS function call (selected by setting `AH` to 2) that prints a single character (in `DL`) to the standard output.
First, the ASCII character '0' is loaded into `DL`, the counter (`CX`) is set to 31, and it loops to print the "redundant" bytes. Then, the input boolean value is added to `DL` (if `BL` is falsey, adding 0 will leave `DL` unchanged as ASCII '0'; if `BL` is truthy, `DL` will be incremented by one to ASCII '1'), and the final byte is printed.
The function does not return a value.
Pretty decent for a language that doesn't really do strings.
---
### Full Program, 21 bytes
If you want to make it into a full program, only 5 more bytes are required. Instead of passing the input in a register, this reads the input from the arguments passed on the command line when invoking the application. An argument of 0 is interpreted as falsey, as is the complete lack of arguments; an argument greater than 0 is interpreted as truthy.
Simply assemble the following code as a COM program, and then execute it on the command line.
```
B4 02 mov ah, 2
B2 30 mov dl, '0'
B9 1F 00 mov cx, 31
PrintZeros:
CD 21 int 0x21
E2 FC loop PrintZeros
3A 16 82 00 cmp dl, BYTE PTR [0x82] ; compare to 2nd arg, at offset 0x82 in PSP
D6 salc ; equivalent to sbb al, al
28 C2 sub dl, al
CD 21 int 0x21
C3 ret ; you can simply 'ret' to end a COM program
```
Sample Output:
```
C:\>bool.com
00000000000000000000000000000000
C:\>bool.com 0
00000000000000000000000000000000
C:\>bool.com 1
00000000000000000000000000000001
C:\>bool.com 2
00000000000000000000000000000001
C:\>bool.com 7
00000000000000000000000000000001
```
How does it work? Well, it's basically the same thing, until you get down to the `CMP` instruction. This compares the command-line argument with the value of the `DL` register (which, you recall, contains an ASCII '0'). In a COM program, the bytes of code are loaded at offset 0x100. Preceding that is the [program segment prefix (PSP)](https://en.wikipedia.org/wiki/Program_Segment_Prefix), which contains information about the state of a DOS program. Specifically, at offset 0x82, you find the first (actually the second, since the first is a space) argument that was specified on the command line when the program was invoked. So, we are just comparing this byte against an ASCII '0'.
The comparison sets the flags, and then the `SALC` instruction (an undocumented opcode prior to the Pentium, equivalent to `sbb al, al`, but only 1 byte instead of 2) sets `AL` to 0 if the two values were equal, or -1 if they were different. It is then obvious that when we subtract `AL` from `DL`, this results in either ASCII '0' or '1', as appropriate.
(Note that, somewhat ironically, you will break it if you pass an argument with a leading 0 on the command line, since it looks only at the first character. So `01` will be treated as falsey. :-)
[Answer]
# [Python 3](https://docs.python.org/3/), 23 bytes
```
lambda n:'0'*31+'01'[n]
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPSt1AXcvYUFvdwFA9Oi/2f0FRZl6JRpqGW2JOcaqmJheMH1JUCuT@BwA "Python 3 – Try It Online")
[Answer]
# Javascript, 23 bytes
```
a=>'0'.repeat(31)+ +!!a
```
`!!a` coerces a into a boolean, which the unary plus turns into an int.
[Answer]
# [V](https://github.com/DJMcMayhem/V), 8 bytes
```
32é0Àñl
```
[Try it online!](https://tio.run/##K/v/39jo8EqDww2HNzLm/P//3wAA "V – Try It Online")
Explanation:
```
32é0 " Insert 32 '0's
Àñ " Arg1 times...
<C-a> " Increment the number under the cursor
l " Move one char to the right. This will break the loop since there is
" no more room on this line
```
[Answer]
# [Neim](https://github.com/okx-code/Neim), 6 5 bytes
```
ᛝΨβ_I
```
[Try it online!](https://tio.run/##y0vNzP3//@HsuedWnNsU7/n/vyEA)
Explanation:
```
·õù # Constant 31
Ψ # Apply next token to all in list
β # Constant 0
_ # Push each element to stack
I # Take Line of input.
```
Saved a byte thanks to *Okx*
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 17 bytes
```
@(n)dec2bin(n,32)
```
Anonymous function. Works in MATLAB too.
[Try it online!](https://tio.run/##y08uSSxL/Z@mYKugp6f330EjTzMlNdkoKTNPI0/H2Ejzf5pGSVFpqiZXmkZaYk5xquZ/AA "Octave – Try It Online")
[Answer]
# [ArnoldC](https://lhartikk.github.io/ArnoldC/), 369 bytes
```
IT'S SHOWTIME
HEY CHRISTMAS TREE A
YOU SET US UP 0
GET YOUR ASS TO MARS A
DO IT NOW
I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY
BECAUSE I'M GOING TO SAY PLEASE A
TALK TO THE HAND "00000000000000000000000000000001"
BULLSHIT
TALK TO THE HAND "00000000000000000000000000000000"
YOU HAVE NO RESPECT FOR LOGIC
YOU HAVE BEEN TERMINATED
```
[Try it online!](https://tio.run/##lVC7bsMwDNz1FQcvWd1PoGXGIqKHK1I1PBbNWLRA/x9w5SzZCpQTcS8c@f7z9f15/zgOsYtCQ9lMErvAO3yoopZIYZUZ5PbSoGxoirZidEvfO1ZB2jUFiap22Vwghlw2J9go20mR3k4pCFPLPqBc8dpYTUruljzjKQ30xrDAqeO6ceVOpsSzkHHc3cSemjLkkrAUycvpUdqxRiY9axrF2wn2jB7Ws4fx73kZ3NRi1CD2f/M4PP7yaJ0LKuvK3nAtFbEs4p/sxJxhXJPkfsp8HOMv "ArnoldC – Try It Online")
[Answer]
# [Brainfuck](https://en.wikipedia.org/wiki/Brainfuck), ~~61~~ ~~60~~ 36 bytes
```
++++[>++++<-]>[>++>+++<<-]>-[>.<-]>>,.
```
~~I'm sure there is a clever way of not moving around so much with the pointers.~~
I was right. There were. Thanks to @Graviton for giving me the idea!
Next step: Get the values 32 and 48 quicker!
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fGwii7UCkjW6sHYgF4tiAOLrRdnpAWkfv/38DAA "brainfuck – Try It Online")
```
++++ - Increment 1st slot by 4
[ - Loop until 4 becomes 0
>++++ - Add 4 to 2nd slot
<- - Decrement loop
] - At this point, we point to slot 1 and slot 2 contains 16, which is the Greatest Common Divisor of 48 (value 0 in ASCII) and 32 (final length of answer)
> - Point to value 16 (slot 2)
[ - Start loop to get our target values 32 and 48
>++ - Point to slot 3 and multiply 16 by 2 = 32
>+++ - Point to slot 4 and multiply 16 by 3 = 48
<<- - Decrement the loop so that slot 2 becomes 0
] - We now point slot 2
>- - Move to slot 3 and remove one so we can spam (output) 31 zeroes
[ - Start outputting until slot 3 is empty
>. - Move to slot 4 where our ASCII value for 0 is
<- - Decrement the loop so that slot 3 becomes 0
] - We are now at slot 3 and it is empty.
,. - We can now gather input from the user and output it.
```
Was fun for a first Golf!
~~It has gotten way too late now.~~ What am I even doing
[Answer]
# Scala, 32 bytes
Sorry but I was forced to do it in 32 bytes >\_<
```
var s=t
for(u<-0 to 30)s="0"+s
s
```
It's enclosed by a function taking `t` as parameter (as a `string` that can be "0" or "1" for resp. falsy or truthy), and `s` is returned.
[Try It Online!](https://tio.run/##K05OzEn8n5@UlZpcouCbmJmnkFpRkpqXUqzgWFBQzcWZkpqmUJJvbJSkUWIVXFKUmZeuCaVtq/@XJRYpFNuWcKXlF2mU2ugaAFUqGBtoFtsqGShpF3MV/6/l4ioAqi3JydNQMlTQtVNQ0oYYpmSopKmJkDNAkTMAydX@BwA)
# Valid response : Scala, 46 bytes
Same as my java response, I was supposed to take a boolean for the parameter. So :
```
var s=if(t)"1"else"0"
for(u<-0 to 30)s="0"+s
s
```
[Try It Online!](https://tio.run/##TYxBCsIwEADP5hVLTgmlkNpbsYLePfmCtN1IJSQluxWh9O0xB0GvM8zQaL3NcXjiyHCzcwB8M4aJ4LIsmzhM6IBjexwUd9cYPdqguzunOTz6Lb9sAupnp1jLRqInlEYKF5NaT7UpIbRGU19gRYLyLsRSSvZByQbqM8jq@04rav2T5l86W77F7vkD)
[Answer]
# [Braingolf](https://github.com/gunnerwolf/braingolf), ~~10~~ 8 bytes
```
#‚êü>[0_]N
```
[Try it online!](https://tio.run/##SypKzMxLz89J@/9fWd4u2iA@1u/////mAA "Braingolf – Try It Online")
`‚êü` is a Unit Separator, ASCII `0x1F`, or 31. Can't find the actually character to paste into TIO, so TIO instead uses `# 1-`, which pushes space (32) and decrements to 31.
## Explanation
```
#‚êü>[0_]N Implicit input from commandline args
#‚êü Push unit separator (31)
> Move top item to bottom of stack
[..] Loop, runs 31 times
0_ Print 0
N Boolean conversion, truthy values become 1, falsey values become 0
Implicit output of top of stack
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 23 bytes
```
@(x)[48+[!(1:31),x],'']
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0IzOiU12SgpM0/DQMfYUFOnQtvEIvZ/mkZJUWmqJleaRlpiTnGq5n8A "Octave – Try It Online")
This is shorter than all the approaches I tried with `printf`. I might have missed something though, since I did this on my phone.
Only one byte longer
```
@(x)[dec2bin(0,31),x+48]
```
This could be 18 bytes if I could take 1/0 as strings.
```
@(x)[48+!(1:31),x]
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0Iz2sRCW1HD0MrYUFOnIvZ/moa6obomF5AyUNf8DwA "Octave – Try It Online")
[Answer]
# Java 8, ~~31~~ 27 bytes
```
b->"".format("%032d",b?1:0)
```
-4 bytes thanks to *@OlivierGrégoire*.
[Try it here.](https://tio.run/##dY5BCsIwEEX3PcUQEFKwoepOUU9gNy7FxSRNJTVNSjMtiPTsNdpuhZnF8P/jTY0DZr7Vri6fk7IYAlzQuHcCYBzprkKlofieAFfqjHuA4tJ7q9GBTA8xGOPGCYRkFBTg4AiTzE6Micp3DRJnq3y3Ldlanjf7PJ0OM9D20kZg4QZvSmiims@a2x0wXbyvQLoRvifRxois404oTl2v098HfysV2rB0xmScPg)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
¾31׫
```
[Try it online!](https://tio.run/##MzBNTDJM/f//0D5jw8PTD63@/98QAA "05AB1E – Try It Online")
[Answer]
# Ruby, 21 bytes
Yeah, that space needs to be there.. :/
```
->x{"%032b"%(x ?1:0)}
```
In Ruby *everything* except `false` and `nil` is truthy;
[Try it online!](https://tio.run/##DcTdCkAwGAbgW3lbKeqj4UzhElyAHJi2EBKbn3Dts4Pn2Yy4rcptWFwP83iaCOb5F8o448FnV6N31MswEVQ77ZKgN@PmhJiQEBhz@sFdiVF2Olrk2URzu@LBe7xQ9dHgsz8 "Ruby – Try It Online")
[Answer]
# Mathematica, 36 bytes
```
""<>ToString/@PadLeft[{Boole@#},31]&
```
# Mathematica, 26 bytes
```
Row@PadLeft[{Boole@#},31]&
```
[Try it online!](https://tio.run/##y00sychMLv6fZvs/KL/cISAxxSc1rSS62ik/PyfVQblWx9gwVu1/QFFmXomCQ5qCQ0hRaSoXguuWmFOMzNcwtDPQROHbGGj@BwA "Mathics – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 5 bytes
```
×0³¹S
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCMkMze1WEPdQF3H2FBT01oBIuqZV1BaElwCZKdrAEX//zf8r1v2X7c4BwA "Charcoal – Try It Online") (Link to the verbose version.)
As Charcoal understand `0` and `1` as `True` or `False`, this just prints 31 `0`s and the input (`0` or `1`) as string.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~26~~ 25 bytes
Thanks to *Erik the Outgolfer* for saving a byte!
Goes for the full program approach:
```
print+bool(input(31*'0'))
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EOyk/P0cjM6@gtETD2FBL3UBdU/P/fxMA "Python 2 – Try It Online")
[Answer]
# [Unwanted, Unnecessary, Opportunistic](https://github.com/faso/Unwanted-Unnecessary-Opportunistic), 7 bytes
```
P0M31P*
```
Pass either 1 or 0 into the register.
[Answer]
# C, 26 bytes
Pretty much the same idea as [1bluestone's solution](https://codegolf.stackexchange.com/a/133327/63856), but in C it's shorter, and it does work correctly for any integer input:
```
f(a){printf("%032i",!!a);}
```
Of course, this includes some implicitly typed variables/functions as all good C-golf answers do... The `!!` operator is the shortest way to convert any truthy value to `1` in C (via double negation, `!` is defined to return either `1` or `0`).
Test with:
```
#include <stdio.h>
f(a){printf("%032i",!!a);}
int main() {
f(0), printf("\n");
f(1), printf("\n");
f(2), printf("\n");
f(-1), printf("\n");
}
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~37~~ 32 bytes
```
(('0'<$[1..31])++).show.fromEnum
```
[Try it online!](https://tio.run/##y0gszk7Nyflfraus4OPo5x7q6O6q4BwQoKCsW8uVZhvzX0ND3UDdRiXaUE/P2DBWU1tbU684I79cL60oP9c1rzT3f25iZp6CrUJuYoFvvIJGQWlJcEmRT55emqZCtFtiTnGqTkhRaWrsfwA "Haskell – Try It Online")
Thanks @nimi for `-5` bytes!
[Answer]
# PHP, 28 bytes
```
<?=str_pad($argv[1],32,0,0);
```
Save as bool.php and run:
```
$ php bool.php 0
00000000000000000000000000000000
$ php bool.php 1
00000000000000000000000000000001
```
[Answer]
# [Ly](http://esolangs.org/wiki/Ly), ~~20~~ ~~15~~ 13 bytes
```
65*1+[0u1-]nu
```
EDIT: Saved 5 bytes thanks to ovs.
EDIT: Saved another 2 bytes by printing 0 as a number rather than a character.
[Answer]
# Octave,~~16~~ 11 bytes
```
@(x)x(1:32)
```
[Try it online!](https://tio.run/##y08uSSxL/f/fQaNCs0LD0MrYSPN/mm1iXrE1V5qGkgF@YKikSYQqgxgDoLr/AA "Octave – Try It Online")
A function handle that takes `"00000000000000000000000000000001"` as truthy and
`"00000000000000000000000000000000\0"` as falsey.
Explanation:
In Octave an array is considered as falsey if at least one of its elements is zero. The 33th element of the second string is a character with the ASCII value of 0 so it can be considered as falsey.
[Answer]
# Java, 40 chars, 40 bytes
This takes string as parameter, which is not correct (falsy/truthy java value is forced by OP to be represented by a boolean).
```
c->{for(int i=0;++i<32;c=0+c);return c;}
```
[Try It Online!](https://tio.run/##dY2xCsMgFEV3v@KRSQkNaTvadM/QqWPpYI0JpokGfQZK8NutlKzdLhzOPaNYxcEuyozdO8lJeA83oc1GtEHleiEVtBu5o9NmAKT7kIxHAkA8CtQSWgjQQJKH69ZbR7MKuql5WerL@cRlU5dZcAqDMyB5TJyQJbymbO4Hq9UdzLm7Bx5PEG7wLJc/HtVc2YDVkglOhoYKaVEXjPG/9PijkcT0BQ)
# Valid response : Java, 60 chars, 60 bytes
```
c->{String k="";for(k+=c?1:0;k.length()<32;k=0+k);return k;}
```
[Try It Online!](https://tio.run/##dY6xDsIgFAB3vuLFCWJsqm5ide7g5GgcnkgrgtDAw8Q0/fbaqKvzXS53xycuQqf9/WpH5TAlOKDxPTOedGxQaah7dqRofAvELyE4jR6UkANjiZCMghoyVDCqxa7/ibaazWQTIrfzSu2Xm1Lawmnf0o2L7XolbVXOrZBRU44erBxGyViXL26q/aLPYK7wmFb4t3k6A8Y2iWnmlUg/ipCp6CZCzvNcEG/QJS2E/Mcp5g8e2DC@AQ)
I know there is already a Java answer which is shorter than this one, but still :)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~13~~ 11 bytes
```
?1:0 ¤i31ç0
```
## Explanation:
```
?1:0 ¤i31ç0
? // If the input is a truthy, return:
1 // 1
:0 // Else, 0
¤ // Convert to a base-2 string
i // Insert at index 0:
31ç0 // A string filled with 0s, length 31
```
Saved a byte using a base-2 conversion built-in!
To insert the string of 0s in front of the `1`/`0`, I need to cast the `1` and `0` into a string. The typical way of doing that would be `1s ` (3 bytes). But because we're only converting 1s and 0s, I can use the base-2 built-in `1¤` (2 bytes).
---
Input can be in the form of an integer or string.
`0` and `""` are falsy in Japt.
[Try it online!](https://tio.run/##y0osKPn/397QykDh0JJMY8PDyw3@/zcEAA)
[Test suite](https://tio.run/##y0osKPn//9DiCHtDKwOFQ0syjQ0PLzf4/z9aSUlHKS0/X0nHQMcwVkE3CAA)
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 29 bytes
```
a=>new string('0',31)+(a?1:0)
```
OP said 1/0 can be used for truthy/falsey, so can make `a` an int and it becomes
```
a=>new string('0',31)+a
```
C# doesn't really have truthy/falsey though so I will not use this answer.
[Try it online!](https://tio.run/##dY6xCsIwFEX3fMXbTLBKi5u1dRCcFAQHB3F4xrQE0gTyUkWk317T1tU73nMuXEkL6bzqW9K2hvObgmpyxqRBIjh5V3ts2IdBDAUMWsLT6QccUVtOwcfR9QboaxKjM5lD9q2Vm7tzJoHJK6GKFRTAgPVYlFa9foTP0lmyysSc4zZbp6KPB3bOkjNqefE6qIO2ig9rHnyrhMj/4QoNjTwe6FjH@i8)
[Answer]
# [MY](https://bitbucket.org/zacharyjtaylor/my-language/src/728aa9b047892569a2bd5a15d54c68dd3bae0bb2?at=master), ~~10~~ 9 bytes
```
ùï´B·πÑi‚ÑëpŒ≠‚Üê‚Üê
```
[Try it online!](https://tio.run/##y638///D3KmrnR7ubMl81DKx4NzaR20TgOj/f8P/AA)
Explanation (codepage [with reasoning behind the character]/hex code):
```
ùï´: 1A - Push an integer from STDIN (lowercase integers)
B: 0B - Push 11 (B is 11 in hex)
Ṅ: 36 - Pop n; push the nth prime, 11th prime is 31 (Ṅ-th)
i: 49 - Pop n; push [1,...,n] (index/iota)
‚Ñë: 34 - Pop n; push imag(n) (‚Ñëmaginary part, applied to each element, which gives 0 for real numbers)
p: 60 - Pop n; push stringified n (0=>"0" ... 35=>"Z", the b in base upside down)
έ: 56 - Pop n; push n joined by "" (έmpty string)
‚Üê: 26 - Pop n; output n with no newline (out‚Üêin)
‚Üê: 26 - Pop n; output n with no newline (out‚Üêin)
```
I can't believe that this is possible without any two-argument commands whatsoever!
Edit: Saved 1 byte by using primes instead of arithmetic to get 31.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 5 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
⌡Ö├⌡→
```
[Run and debug it](https://staxlang.xyz/#p=f599c3f51a&i=1%0A0)
Numeric 0 and empty lists are considered falsy. All other values are truthy.
[Answer]
# Julia 0.6, 12 bytes
```
~x=bin(x,32)
```
Nothing clever here, there is basically a built in for it.
] |
[Question]
[
Today your goal is to find integers *a* and *b* given non-negative integer *n* such that:

You should write a program or a function that takes parameter *n* and outputs *a* and *b* in a format of your choice.
Standard loopholes apply. Additionally, it's intended that you implement the above problem using basic arithmetic yourself. So you may not use built-in exact algebra functionality, rationals, or functions implementing non-trivial mathematical constructs (for example the [Lucas sequence](https://en.wikipedia.org/wiki/Lucas_sequence)).
**Shortest code in bytes wins.**
---
Example input/output:
>
> 0 → 1, 0
>
> 1 → 3, 1
>
> 2 → 14, 6
>
> 3 → 72, 32
>
> 4 → 376, 168
>
> 5 → 1968, 880
>
> 6 → 10304, 4608
>
> 7 → 53952, 24128
>
> 8 → 282496, 126336
>
> 9 → 1479168, 661504
>
>
>
[Answer]
# Octave, 26 bytes
```
[3 5;1 3]**input('')*[1;0]
```
Because (**a**+*b*\*sqrt(5)) \* (3+sqrt(5)) = (**3a+5b**) + (*a+3b*) \* sqrt(5),
multiplying input vector
```
| 1 | /* a = 1 */
| 0 | /* b = 0 */
```
which stands for 1 = (3+sqrt(5))^0
by matrix
```
| 3 5 |
| 1 3 |
```
seems natural. Instead of looping `n` times, we rather raise the matrix to the power of `n` and then multiply it by input vector.
[Answer]
# Python 2, 50
```
a=1;b=0
exec"a,b=3*a+5*b,3*b+a;"*input()
print a,b
```
Multiplies by `3+sqrt(5)` repeatedly by its action on the pair `(a,b)` representing `a+b*sqrt(5)`. Equivalent to starting with the column vector `[1,0]` and left-multiplying `n` times by the matrix `[[3,5],[1,3]]`.
[Answer]
# Julia, ~~22~~ 20 bytes
```
n->[3 5;1 3]^n*[1;0]
```
This creates a lambda function which takes a single integer as input and returns a 2-element vector of integers corresponding to the solution [a, b]. To call it, give it a name, e.g. `f=n->...`.
Start by multiplying

We can then translate the right hand side of this equation into a 2-column matrix, where the first corresponds to the coefficient of *a* and the second to the coefficient of *b*:

Multiply this matrix by itself *n* times, then right multiply by the column vector (1, 0), and POOF! Out pops the solution vector.
Examples:
```
julia> println(f(0))
[1,0]
julia> println(f(5))
[1968,880]
```
[Answer]
# J, 20 bytes
```
+/@:*(3 5,.1 3&)&1 0
```
Multiplicate the vector `[1 0]` with the matrix `[[3 5] [1 3]]` `n` times.
2 bytes saved thanks to @algorithmshark.
Usage and test:
```
(+/@:*(3 5,.1 3&)&1 0) 5
1968 880
(+/@:*(3 5,.1 3&)&1 0) every i.6
1 0
3 1
14 6
72 32
376 168
1968 880
```
[Answer]
# Pyth, 20 bytes
```
u,+*3sGyeG+sGyeGQ,1Z
```
`u` which is reduce in general, is used here as an apply repeatedly loop. The updating function is `G` -> `,+*3sGyeG+sGyeG`, where `G` is a 2 tuple.
That function translates to `3*sum(G) + 2*G[1], sum(G) + 2*G[1]`. `s` is `sum`, `y` is `*2`.
[Answer]
# APL (22)
```
{⍵+.×⍨2 2⍴3 5 1}⍣⎕⍨2↑1
```
Explanation:
* `{`...`}⍣⎕⍨2↑1`: read a number, and run the following function that many times, using `[1,0]` as the initial input.
+ `2 2⍴3 5 1`: the matrix `[[3,5],[1,3]]`
+ `⍵+.×⍨`: multiply the first number in ⍵ by 3, the second by 5, and sum them, this is the new first number; then multiply the first number in ⍵ by 1, the second by 3, and sum those, that is the new second number.
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/blob/master/docs/code-page.md)
```
5W×U++Ḥ
2Bdz¡
```
[Try it online!](http://jelly.tryitonline.net/#code=NVfDl1UrK-G4pAoyQsOHwrPCoQ&input=&args=OQ)
### How it works
```
5W×U++Ḥ Helper link. Argument: [a, b]
5W Yield [5].
×U Multiply it by the reverse of [a, b]. This yields [5b, a].
+ Hook; add the argument to the result. This yields [a + 5b, a + b].
+Ḥ Fork; add the doubled argument ([2a, 2b]) to the result.
This yields [3a + 5b, a + 3b].
2Bdz¡ Main link. Argument: n
2B Convert 2 to binary, yielding [1, 0].
¡ Repeat:
Ç Apply the helper link...
³ n times.
```
[Answer]
## Dyalog APL, 18 bytes
```
((3∘×+5 1×⌽)⍣⎕)1 0
```
This is a program that takes input through `⎕`.
```
( ) Monadic train:
3∘× 3 times argument
+ Plus
5 1×⌽ (5 1) times the reverse
( ⍣⎕) Apply that function (input) times
1 0 starting with (1 0)
```
The features used here were implemented well before April 2015, making this answer valid.
Try it [here](http://tryapl.org/?a=%28%283%u2218%D7+5%201%D7%u233D%29%u23635%291%200&run). Note that tryapl.org is a limited subset of Dyalog and does not support `⎕`.
[Answer]
# Mathematica, 31
```
Nest[{{3,5},{1,3}}.#&,{1,0},#]&
```
[Answer]
# CJam, 21 bytes
```
0X{_2$3*+@5*@3*+}li*p
```
[Try it online.](http://cjam.aditsu.net/#code=0X%7B_2%243*%2B%405*%403*%2B%7Dli*p "CJam interpreter")
### How it works
```
0X " Stack: [ 0 1 ] ";
li{ " Do int(input()) times: ";
_2$ " Stack: [ a b ] -> [ a b b a ] ";
3*+ " Stack: [ a b b a ] -> [ a b (b+3a) ] ";
@5*@3* " Stack: [ a b (b+3a) ] -> [ (b+3a) 5a 3b ] ";
+ " Stack: [ (b+3a) 5a 3b ] -> [ (b+3a) (5a+3b) ] ";
}* " ";
p " Print topmost stack item plus linefeed. ";
" Print remaining stack item (implicit). ";
```
[Answer]
# Javascript, ~~63~~ 61 bytes
I am using a recursive evaluation of the binomial: (x+y)^n = (x+y)(x+y)^{n-1}
New(thanks to @edc65)
```
F=n=>{for(i=y=0,x=1;i++<n;)[x,y]=[3*x+5*y,x+3*y];return[x,y]}
```
Old
```
F=n=>{for(i=y=0,x=1;i<n;i++)[x,y]=[3*x+5*y,x+3*y];return [x,y]}
```
[Answer]
# C, 114 bytes
```
g(n){int i,a[2]={1,0},b[2];for(i=0;i<n;i++)*b=*a*3+5*a[1],b[1]=*a+3*b[1],*a=*b,a[1]=b[1];printf("%d,%d",*a,a[1]);}
```
This implements matrix multiplication the boring way. For a more fun (quote: "awesomely horrific") 238 byte solution, look no further!
```
f(n){int p[2][n+3],i,j,k=0,a[2]={0};for(j=0;j<n+3;j++)p[0][j]=0;*p[1]=0;(*p)[1]=1;for(j=0;j<n;j++,k=!k)for(i=1;i<n+3;i++)p[!k][i]=p[k][i-1]+p[k][i];for(i=1;i<n+2;i++)a[!(i%2)]+=p[k][i]*pow(3,n+1-i)*pow(5,(i-1)/2);printf("%d,%d",*a,a[1]);}
```
Unraveled:
```
g(n){
int i,a[2]={1,0},b[2];
for(i=0;i<n;i++)
*b=3**a+5*a[1],b[1]=*a+3*b[1],*a=*b,a[1]=b[1];
printf("%d,%d",*a,a[1]);
}
```
This could probably be shortened a bit.
Try a test program [online](http://ideone.com/Zjzt1z)!
[Answer]
# k2 - 22 char
Function taking one argument.
```
_mul[(3 5;1 3)]/[;1 0]
```
`_mul` is matrix multiplication so we curry it with the matrix `(3 5;1 3)` and then hit it with the functional power adverb: `f/[n;x]` applies `f` to `x`, `n` times. Again we curry it, this time with the starting vector `1 0`.
```
_mul[2 2#3 5 1]/[;1 0] 5
1968 880
f:_mul[2 2#3 5 1]/[;1 0]
f'!8 /each result from 0 to 7 inclusive
(1 0
3 1
14 6
72 32
376 168
1968 880
10304 4608
53952 24128)
```
This will not work in Kona, because for some reason `f/[n;x]` isn't implemented correctly. Only the `n f/x` syntax works, so the shortest fix is `{x _mul[(3 5;1 3)]/1 0}` at 23 char.
[Answer]
# ised, 25 bytes (20 characters)
```
({:{2,4}·x±Σx:}$1)∘1
```
I hoped for better, but there are just too many braces needed in ised to make it competent, the operator precedence is not optimal for golfing.
It expects the input to be in $1 memory slot, so this works:
```
ised '@1{9};' '({:{2,4}·x±Σx:}$1)∘1'
```
For n=0, the zero is skipped (outputs 1, instead of 1 0). If that's an issue, replace the final `1` with `~[2]`.
[Answer]
## Seriously, 32 bytes, non-competing
```
,╗43/12`╜";)@4*≈(6*-"£n.X4ì±0`n
```
Hex Dump:
```
2cbb34332f313260bd223b2940342af728362a2d229c6e2e58348df130606e7f
```
[Try It Onlline](http://seriously.tryitonline.net/#code=LOKVlzQzLzEyYOKVnCI7KUA0KuKJiCg2Ki0iwqNuLlg0w6zCsTBgbn8&input=OQ)
Obviously not a contender for shortest, but at least the method is original. (Noting that such a problem necessarily indicates a Lucas sequence, as mentioned in the description, this program generates successive terms of the sequences using the recurrence relation
a\_n = 6\*a\_{n-1} - 4\*a\_{n-2}.)
[Answer]
# Haskell, 41 bytes
```
(iterate(\(a,b)->(3*a+5*b,a+3*b))(1,0)!!)
```
Usage example: `(iterate(\(a,b)->(3*a+5*b,a+3*b))(1,0)!!) 8` -> `(282496,126336)`.
[Answer]
**C/C++ 89 bytes**
```
void g(int n,long&a,long&b){if(n){long j,k;g(n-1,j,k);a=3*j+5*k;b=j+3*k;}else{a=1;b=0;}}
```
Formatted:
```
void g(int n, long&a, long&b) {
if (n) {
long j, k;
g(n - 1, j, k);
a = 3 * j + 5 * k;
b = j + 3 * k;
} else {
a = 1;
b = 0;
}}
```
Same concept:
```
void get(int n, long &a, long& b) {
if (n == 0) {
a = 1;
b = 0;
return;
}
long j, k;
get(n - 1, j, k);
a = 3 * j + 5 * k;
b = j + 3 * k;
}
```
The test bench:
```
#include <iostream>
using namespace std;
int main() {
long a, b;
for (int i = 0; i < 55; i++) {
g(i, a, b);
cout << i << "-> " << a << ' ' << b << endl;
}
return 0;
}
```
The output:
```
0-> 1 0
1-> 3 1
2-> 14 6
3-> 72 32
4-> 376 168
5-> 1968 880
6-> 10304 4608
7-> 53952 24128
8-> 282496 126336
9-> 1479168 661504
10-> 7745024 3463680
11-> 40553472 18136064
12-> 212340736 94961664
13-> 1111830528 497225728
14-> 5821620224 2603507712
15-> 30482399232 13632143360
16-> 159607914496 71378829312
17-> 835717890048 373744402432
18-> 4375875682304 1956951097344
19-> 22912382533632 10246728974336
20-> 119970792472576 53652569456640
21-> 628175224700928 280928500842496
22-> 3289168178315264 1470960727228416
23-> 17222308171087872 7702050360000512
24-> 90177176313266176 40328459251089408
25-> 472173825195245568 211162554066534400
26-> 2472334245918408704 1105661487394848768
```
[Answer]
# Jelly, 10 bytes
```
31,53Dæ*³Ḣ
```
[Try it online!](http://jelly.tryitonline.net/#code=MzEsNTNEw6YqwrPhuKI&input=&args=OQ)
Uses matrix. Computes ([[3,1],[5,3]]\*\*input())[0].
[Answer]
# K, 37 bytes
```
f:{:[x;*(1;0)*_mul/x#,2 2#3 1 5;1 0]}
```
or
```
f:{:[x;*(1;0)*_mul/x#,(3 1;5 3);1 0]}
```
They're both the same thing.
[Answer]
# Python 3, 49 bytes
```
w=5**0.5;a=(3+w)**int(input())//2+1;print(a,a//w)
```
although on my machine, this only gives the correct answer for inputs in the range `0 <= n <= 18`.
This implements the closed form formula
```
w = 5 ** 0.5
u = 3 + w
v = 3 - w
a = (u ** n + v ** n) / 2
b = (u ** n - v ** n) / (2 * w)
```
and takes advantage of the fact that the `v ** n` part is small, and can be computed by rounding rather than direct calculation.
[Answer]
# Scheme, 97 bytes
```
(define(r n)(let s([n n][a 1][b 0])(if(= 0 n)(cons a b)(s(- n 1)(+(* a 3)(* b 5))(+ a(* b 3))))))
```
[Answer]
**C 71 bytes (60 with pre-initialised variables)**
Scope for golfing yet but just to prove that C does not have to be "awesomely horrific".
```
f(int n,int*a){for(*a=1,a[1]=0;n--;a[1]=*a+3*a[1],*a=(5*a[1]+4**a)/3);}
```
If the values in a are initialised to {1,0}, we do better.
```
f(int n,int*a){for(;n--;a[1]=*a+3*a[1],*a=(5*a[1]+4**a)/3);}
```
This is iteratively using the mappings a->3a+5b, b->a+3b but avoiding a temporary variable by calculating a from the new value of b instead.
] |
[Question]
[
Take the string `abcdfghjk`. To overwrite it, starting from `f`, with the string `wxyz`, you would continue along the original, replacing each character with the one from the replacement string. The result would be `abcdwxyzk`.
Now, consider a string which would be too long to fit, like `lmnopqrs`. Starting at `f` you would get `abcdlmnop`, then hit the end of the string. In order to continue, you wrap back to the beginning, resulting in `qrsdefghi`. With a long enough string, you could even wrap around multiple times.
**Task:**
You should take three inputs: the original string, the replacement string, and an index to start replacing at. This can be zero or one indexed.
**Test Cases:**
```
"This is a string" "That" 0 -> "That is a string"
"This is a string" "That" 5 -> "This That string"
"This is a string" "That" 14 -> "atis is a striTh"
"hi" "Hello there!" 0 -> "e!"
"hi" "Hello there!" 1 -> "!e"
"over" "write multiple times" 0 -> "imes"
"over" "write multiple times" 3 -> "mesi"
```
**Other:**
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer per language in bytes wins!
[Answer]
# [Python 3](https://docs.python.org/3/), 39 bytes
```
def f(x,y,z):
for x[z%len(x)]in y:z+=1
```
[Try it online!](https://tio.run/##jc1BasMwEAXQdX2KqaGgoSLUpNkYvM8BugtZuHhsTy1LRp62ki/vyKWLEAoNCAb@f3xNUXpn9@vaUAutCjrqBcvsoXUewml5MmRVwDNbiOXyXBVrBxWYenxvaggaooalBPUbDGWaGDQYnkVFTB1C2snz3YdjqwZE9VMFxCybPFtRncrfep4hvRpmSVmXa0hZLem@JHiPO9zpitdr2PNWHckYB9KTp8fbL/8UxbVwX@Q38@1ZCMZPIzwZAuGR5tu1f@wecb0A "Python 3 – Try It Online")
-5 bytes thanks to ovs for spotting the trick with cleverly using python's for loop specifics
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
Ż¡sL}o@ƒ
```
[Try it online!](https://tio.run/##y0rNyan8///o7kMLi31q8x2OTfr//79SSEZiiRKIyixWAKJEheKSosy8dKX/hiYA "Jelly – Try It Online")
## How it works
Take some of the examples (the two `"over", "write multiple times"` and `"This is a string" "That", 14`), and "layer" them, as though overwriting. At the end, the lowest letter in each column is taken:
```
over over This is a string
writ w Th
e mu rite at
ltip mul
le t tipl
imes e ti
mes
imes mesi atis is a striTh
```
We reshape the inputs into a matrix like this, then take the final character in each column. In order to offset the "overwriting" string, and to make the final replacement easier, we don't prepend spaces, instead `0`s
```
Ż¡sL}o@ƒ - Main link. Takes R on the left and O on the right, i third
¡ - Do the following i times to R:
Ż - Prepend 0 to R
} - To O:
L - Length of O, L
s - Slice into rows of length L
ƒ - Reduce columnwise by the following, starting with O:
o@ - Reversed logical OR, taking the final element,
or the first, if all zero
```
[Answer]
# Scratch 3.0, 37 blocks / 262 bytes
[](https://i.stack.imgur.com/xmNNu.png)
As ScratchBlocks syntax:
```
define(L)(y)(x)
set[a v]to(1
set[l v]to(length of(L
repeat(l
add(letter(a)of(L))to[T v
change[a v]by(1
end
set[a v]to((y)mod(l
set[! v]to(1
repeat(length of(x
replace item((a)+(1))of[T v]with(letter(!)of(x
change[! v]by(1
set[a v]to(((a)+(1))mod(length
end
say(T
```
I am very glad Scratch has a modulo block built-in, otherwise this would have been pain.
[Try it on Scratch!](https://scratch.mit.edu/projects/512090649/)
[Answer]
# vim, ~~33~~ 30 bytes
Thanks for the sweet golf @kops
Pure vim answer, the TIO link is to V, which is a superset of vim. Takes input in 3 lines: index, original string, replacement string. Final buffer is "replaced string" output. 1-indexed.
```
D3gJhmd@"|qqmm`dlD`mR"|@qq@q
```
```
D3gJhmd@"|qqmm`dlD`mR<C-r>"<esc>|mm@qq@q # with unprintables shown
```
[Try it online!](https://tio.run/##K/v/38U43SsjN8VBqaawMDc3ISXHJSE3SEhJusahsNCh8P9/E678stQirvKizJJUhdzSnJLMgpxUhZLM3NRiAA "V (vim) – Try It Online")
[Bonus 14 byte V answer, but vim is cooler](https://tio.run/##K/v/P93LJbficEPN4U2HJyRU5LjU/P8fkpFZrABEiQrFJUWZeelcIRmJJf8NTQE "V (vim) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 31 30 bytes
```
1 :'-@u|.[[`((|i.)~&#)`]}u|.]'
```
[Try it online!](https://tio.run/##fY7NCoJAFEb3PcVnQeNASlJthCAIokWraBdCEtdmwjJ0rE316jY12h/i4i7m3HMusy/aLosw9sHQQx@@HsfFdLmYFR585kzyq7teb2z7Kl1@73b4JrhpFLCCt2grErCVCBVkhhCZSuVxx@D4hjLYfUT8@dD7b@Wdavjqa9JRYxqqb74SP6k3bGzJMvac4jiBEpQ@SflXISvNolrN@9PkgTIjXlKpCIc8VvIUE5TZlHeTM6VVorlsTAafpHgA "J – Try It Online")
Surprisingly hard to find a decent golf in J, given how simple the problem is.
This is a J adverb, modifying the index, and taking the main string as the right arg and the replacement string as the left arg. Eg:
```
'That' (5 f) 'This is a string'
```
This would have been the perfect place to use the semidual version of under `u&.(a:`v)`, but it cost more bytes than explicitly doing the rotation and its reverse.
## how
```
u|.] NB. Rotate by index
}~ NB. Replace:
`] NB. String with
[` NB. Replacement chars
((|i.)~&#) NB. At indexes 0...<str len>
NB. Each modded by <replacement len>
-@u|. NB. Unrotate by index
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 36 bytes
```
(a,b,i)=>b.map(c=>a[i++%a.length]=c)
```
[Try it online!](https://tio.run/##nZGxTsMwEIb3PMXVEopNUpcKmKpkQ0IMMNCtDaqTuslVThwlpgzAs4draEVpWYply7779f3ns9dqo9qswdoNK7vU3SrquArTEEUUp7JUNc@iWM0wCC6UNLrKXZFEmegcRLDw2LTAFmgqaF2DVc4AKKcc7cfjitYw3um/mLNsbn9sCOi9/mMzvtnZKHfITAuyKfAEYPfaGAuu0I0esD@aouxZ4HgPDjSBdqObI5S9Neg0lK/GYW00OCx1yw4q9vFZ6PUepRCZt5DUcMmFbGuDjvvzyhf9jxuIYjB0dFnBR2z2wpJL9jFfBqNciInn5Mo2d4o0PlMhpCFgCDoRW@rdA3rJCGZSyofnp0dZq6bVXIlkQkp6qqTfCpJykEWxTa74zr6PMlu11mhpbM6pxImTFgkE4PshKLm2WHHf3972U0y6Lw "JavaScript (Node.js) – Try It Online")
Input two strings as array of characters. Input the integer as 0-indexed. Modify the first string in-place.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 79 bytes
```
param($x,$y,$i)$y|% t*y|%{$x=$x.remove(($n=$i++%$x.length),1).insert($n,$_)};$x
```
[Try it online!](https://tio.run/##DYlBCoMwEAC/EmSFpAZB6K34C@8lh8UsxCibpY1U374NDHOYOfYvcomYkuoROGwWqofTAzk4r97Io/kHdYY6Mm77B62FPAMNQ99SwrxKdH5yI@WCLG16eLv7BVVVuyVSMY1gijDltdMlBtHp@Qc "PowerShell – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 50 bytes
```
f(x,y,z)char*x,*y;{for(;*y;z++)x[z*=x[z]>0]=*y++;}
```
[Try it online!](https://tio.run/##dY9NTsMwEIXX8SmGIFB@BtQCZROVNQfoLgQpOE5tyUkq26WOq3D1YBc2RVSyZkbfvPds07stpfPcJhZHdCnltcosZmNxbAeVFH5weZ7a0mVrX6qXRbXOxjwvpvla9FTuGwaxNo0Y7nlMzpAUH4ER0RvoatEnKRxJFC4AWz6sniuE8dQLCBJXkOjAhWSQfGla920S35TvWOFvbd76GMF6E8KtS09hUXh2AC717minfFDw6R9tgBOZ5g0XGvypQRsv2eKG1wYX5H@@usCXT4QLfGVSDmA4U@zKR/wlSzJ8MoUHJQyDbi@N2PkfGdEx7dWXd4/kGw "C (gcc) – Try It Online")
-45 bytes thanks to dingledooper with a lot of golfing from someone who actually knows C :P (also inlining `++`, which i forgot about because python doesn't have that)
-1 byte thanks to tsh with a clever trick to set `z` to 0 if `x[z]` is 0, which happens with the null byte after the end of the string
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 19 [bytes](https://github.com/abrudz/SBCS)
Assumes `⎕IO←0`.
```
{⍺@((⍴⍵)|⍺⍺+⍳⍴⍺)⊢⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR7y4HDY1HvVse9W7VrAHygEj7Ue9msMguzUddi4AStf/THrVNeNTb96ir@VHvGqDcofXGj9omPuqbGhzkDCRDPDyD/wNpT3@gOgMu9ZCMxBJ1BQ0DhTRNBSAns1gBiBIVikuKMvPS1eHypgTkDU1wKfBIzcnJVyjJSC1KVYRblJGJKWOIkCkvyixJVcgtzSnJLMhJVSjJzE0thuvNL0stwq3GGKEGAA "APL (Dyalog Unicode) – Try It Online")
A dop which takes the index as the left operator operand `⍺⍺`, the original string as right input `⍵` and the replacement string as a left input `⍺`.
`⍳⍴⍺` generate the indices of the replacement string.
`⍺⍺+` add the index offset to each index.
`(⍴⍵)|` each index modulo the length of the original string.
`⍺@(...)⊢⍵` place the replacement string at those indices in the original string.
[Answer]
# [R](https://www.r-project.org/), 81 bytes
```
function(o,r,i,`?`=utf8ToInt,`!`=nchar){p=?o;p[1+(i-1+1:!r)%%!o]=?r;intToUtf8(p)}
```
[Try it online!](https://tio.run/##pdDBSsQwEAbgu08xGVlo2SwYVBCX2Kve60mEliVrBrpJmU71ID57jUWwrXipIZBhJv9HCA/x1fEbkzg7HPtwEIohi5o16aqobC/HmzI@BNGVqmw4@Jrz99YWcd8@mW1GO7M1t4rzzUbFZ1vwnoKU8TGlsjb/@MEzLD11kHYNnTCFF9QAqVkLwmKlwUU6cjiH3d33pVnybC17PWdTbLT/y5qrCVvLNFn6GesJf6Xx3jVNBPGOncK/PiGNVkNmCik3g75KXELjDE59I9Q2DoROrsPli8bmaupySqUe4fAJ "R – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~103~~ 78 bytes
```
^.+
$*
(1)*(¶(?<-1>.)*)(.*)¶
$2$3$2
+`¶.(.*)¶(.)
1¶$1$2¶
+`1¶(.*)(.)
¶$2$1
G`.
```
[Try it online!](https://tio.run/##JcoxDsIwDEbh/T9FBg92Iiw5MCI6cgEkNpQMFURIHdqcLQfIxUIr1u@9da5lyWO8NIA82MRzbzxdT3ZT8cLqpTdQpDNFhNSb/olVYL2RUdx7SHbQ8Qt2jWS4Jx3DLnh@cnVlc9ltdS3fecLy1scP "Retina 0.8.2 – Try It Online") Takes the 0-indexed index on the first line. Explanation:
```
^.+
$*
```
Convert the index to unary.
```
(1)*(¶(?<-1>.)*)(.*)¶
$2$3$2
```
Prefix the replacement string with the original string up to the index. This was inspired by @Wezl's sed answer. (Previously I was rotating the original string to bring the index to the beginning.)
```
+`¶.(.*)¶(.)
1¶$1$2¶
```
Rotate the original string, replacing it with characters from the replacement string, keeping track of the number of characters rotated.
```
+`1¶(.*)(.)
¶$2$1
```
Rotate the original string back to its initial position.
```
G`.
```
Remove the now empty working lines.
[Answer]
# GNU sed [<4.3](https://codegolf.stackexchange.com/questions/51323/tips-for-golfing-in-sed#comment268984_51352) `-E`, ~~125 124~~ 117 bytes
Takes `offset-0-based-unary-~tildes@replacement#textontape` like `~~~~~~~~~~@banana made of mush#This is a tape made of text`. The input tape and replacement cannot contain tilde `~`, at `@`, or hash `#` characters.
```
s/(.*)@/@\1/
:
s/^(.*)@~(.*#\1(.))/\1\3@\2/
t
s/.*@#//
te
s/^(.*)@(.)(.*#\1)./\1\2@\3\2/
s/^(.*)@(.+#)\1$/@\2\1/
t
:e
```
## explanation
`~~~~~~~~~~@banana made of mush#This is a tape made of text`
```
s/(.*)@/@\1/
```
`@~~~~~~~~~~banana made of mush#This is a tape made of text`
`@` is the cursor, which marks the current character
```
:
```
start loop
```
s/^(.*)@~(.*#\1(.))/\1\3@\2/
```
When the cursor is before a tilde `~`, replace the `~` with the corresponding letter from the tape.
```
t
```
If a `~` was replaced, loop again. This works like so:
`@~~~~~~~~~~banana made of mush#This is a tape made of text`
`T@~~~~~~~~~banana made of mush#This is a tape made of text`
`Th@~~~~~~~~banana made of mush#This is a tape made of text`
...
`This is a @banana made of mush#This is a tape made of text`
```
s/.*@#//
te
```
If the cursor has reached the end of the replacement, finish by branching to `e`
```
s/^(.*)@([^~])(.*#\1)./\1\2@\3\2/
```
If the cursor is followed by a not `~` character, advance it and place that character on the tape. It finds its place in the tape with a backreference. Like so:
`This is a @banana made of mush#This is a tape made of text`
`This is a b@anana made of mush#This is a bape made of text`
`This is a ba@nana made of mush#This is a bape made of text`
...
`This is a banana made of mu@sh#This is a banana made of mu`
```
s/^(.*)@([^~]+)#\1$/@\2#\1/
```
If the cursor is at the end of the tape but not the end of the replacement text, remove the replacement text before the cursor so it is now at the start of the line. Like so:
`This is a banana made of mu@sh#This is a banana made of mu`
->
`@sh#This is a banana made of mu`
```
t
```
If either of these above two replacements worked, the work is not finished, loop again.
```
:e
```
The end label
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
║H┤1╫╢╘i
```
[Run and debug it](https://staxlang.xyz/#p=ba48b431d7b6d469&i=0+%22This+is+a+string%22+%22That%22%0A5+%22This+is+a+string%22+%22That%22%0A14+%22This+is+a+string%22+%22That%22%0A0+%22hi%22+%22Hello+there%21%22%0A1+%22hi%22+%22Hello+there%21%22%0A0+%22over%22+%22write+multiple+times%22%0A3+%22over%22+%22write+multiple+times%22&m=2)
input taken as `index, original, replacement`.
## Explanation
```
Fdix+n%%_&
F for each char in replacement:
d delete current iteration
ix+ add iteration index and input index
n% get original's length
% modulo by that
(this is needed because & extends the string when out of bounds)
_ push current iteration value
& replace at that index
```
[Answer]
# [Red](http://www.red-lang.org), 54 bytes
```
func[s r i][forall r[s/:i: r/1 i:(i % length? s)+ 1]s]
```
[Try it online!](https://tio.run/##ldE9C8IwEAbg2f6K14CgONSiLl1cncUtZCjt1RykH1xS/fm1VkWwU49Md/eQS06o6C9UaBOVKfqyq3PtIWCjy0Yy5yDaxymnkDgBp2vGCo7qW7An@M0WifGmH1opyy2@NMIQ6mrZYzgZfBCub2rMZUFhEjvMJsf5JDm8ieVJUZ3JuQbBktBSTQebQZIPae4kf0g9hAOh6lzg1hECV@TV75YZZB8Z3Q7vDSgx/jpeu1j0Tw "Red – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes
```
PSMN→FS«F¬KKMⅈ←ι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@3NKcks6AoM69EwzOvoLQkuATITtfQ1LTm8s0vS4UI@pXmJqUWaWjqKFgFZaZnlAAl0/KLFNB0KFRzcYKF/fJLNAJSU7OBYpoKYFMiwHp9UtNAWjkDwNZlApm1//@HZySWKGQWKyQqFAMNyk615zI04cpL1wv5r1uWAwA "Charcoal – Try It Online") Link is to verbose version of code. Takes the index as the middle input. Explanation:
```
PS
```
Print the original string without moving the cursor.
```
MN→
```
Move to the desired index.
```
FS«
```
Loop over the characters of the replacement string.
```
F¬KK
```
If we reached the end of the original string...
```
Mⅈ←
```
... then move the cursor back to the beginning.
```
ι
```
Overwrite the original string with the current character of the replacement string.
[Answer]
# [Haskell](https://www.haskell.org/), 67 bytes
```
(s!l@(h:t))i|(a,b:c)<-splitAt i s=(a++h:c)!t$i+1|0<1=s!l$0
(s!_)_=s
```
[Try it online!](https://tio.run/##nZFBT4MwFIDv@xWl4UAzSCjoBWHRg4kHb@5mzFbdc32xwEKfetl/x8eyhW16maSE9IPvaxus8R/gXN9HPnC3kS1IKdxGJn4t3lSZ@I1DuiOBwleRmU4t04BCnOptWuqKnTCdsLpQi8r3tcGmWrUTIVxaJu/oCLpo2bR076BeymQmVRnO1kCP2MDwFXBZF8UTddisb54j1LHT6qXqwKw8RwaUxS4bkR5QHrt8RBmjNl6MIOf0hosUcjDATGFeVcOuhv31cm7RCx5G@N26Ughmhvh5fqV8J7P9@xNncknmesywsGv9J6Ov9hlDx87ccsbiL0E@8I9tBVnoIJB/HIrpRaI@iAGw2H5Bd6bK7w4JRP3pCDcOBGENXh6tuJtfpOYHlacofwA "Haskell – Try It Online")
The relevant function is `(!)`, which takes as input the original string `s`, the replacement string `l` and the index `i` (0-indexed).
## How?
Haskell is definitely the wrong tool for the job, since there is no easy way to replace a character at a given index in a string. As far as I can tell, the best way is to split the string `s` at index `i` in two parts, replace the first character of the second part, and then join them back.
To make up for the immutability of values in Haskell, we define the overwrite function recursively.
$$
\text{overwrite}(s,l,i)=
\begin{cases}
s&\text{if $l=\epsilon$},\\
\text{overwrite}(s,l,0)&\text{if $i\ge\text{length}(s)$},\\
\text{overwrite}(s',l[1:],i+1)&\text{where $s'=s$ except for $s'[i]=l[0]$}.
\end{cases}
$$
[Answer]
# Java, 41 bytes
```
(o,r,i)->{for(var c:r)o[i++%o.length]=c;}
```
Takes two char arrays and the index as input.
[Try it online!](https://tio.run/##jVLBSsNAED3brxgLQkLTYFEvhgoiiBdP9VZ6GNNJsnWzG2anqaX02@OmCdZCoQ4bkt158@blza6wxvFq@dVU60@tUkg1OgfvqAzsBuBDGSHOMCV4hR3UVi3BWV1TkBbI8wVYVrkyqCPoD5gq7eElGYnaav8s6TtMYH/gq1jVKAROUHy/rK311Nm0CWzEkQrHT7vMclAjQ/rIoZ2r0ejGxppMLsVimib7JumYOsU90UFZ6XUHM2Flcq8EOXdh/xttCDkJhh@FcuAX@soWOIzAn6H4922YDK4uoh7@hZrcH2GFahNvpLUFKYjp@rTZ2fzkmLc1cYvYsPLOlWstqtIEokpyp0wXkHdhZ93ZURwcPNB0DoKNoP/ifpLh0cx@2ghTsLHYF799ZsZt0LdoI4u7q4IR8CnG8/3BzbZOqIztWmKvyYg2gaFN3zzA8Ff1vvkB)
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~42~~ 39 bytes
```
->a,b,n{b.map{|c|a[n%a.size]=c;n+=1};a}
```
[Try it online!](https://tio.run/##hY3RCoIwFIbve4olhFBLkupK7LoH6E52cSZHN5hTtlmU@uxLwcCLQDjww/99/Me0/O3L1B9vQDnVHY8qaLo@7yHTO4is/CBL80Qf0nhIYPBF@jPLDKJcgLGUz6nZPgyHzaYhRRY8hLRkPCDWGanLgJKxAzfmia0q13UlvsyOkFN7R6Vq4gQa3C5@/IXxDOsnmgm/jHRIqlY52SgkTlZoFxsr2pn5Lw "Ruby – Try It Online")
Taking 2 char arrays in input.
[Answer]
# VBA, 105 bytes
```
Function f(x,y,z)
For i=1 To Len(x)
Mid(x,(z Mod Len(x))+1,1)=Mid(y,i,1)
z=z+1
Next
MsgBox x
End Function
```
Chosen VBA instead of VBScript, because VBA has `Mid()` instruction, but VBScript lacks that.
-5 bytes thanks to @BrianJ
[Answer]
# [Icon](https://github.com/gtownsend/icon), 55 bytes
```
procedure f(s,r,i)
!r:=:s[i%*s+1]&i+:=1&\z
return s
end
```
[Try it online!](https://tio.run/##ndHBCoJAEAbgu08xLSRu7sGlugjee4Bu1UF0zAFdZXYt6OXNOqlFYMucZubjZ1jKGtP3LTcZ5h0jFIFVrEh6K46T2J5ovbGhvvgUxon2zw@P0XVswHpo8pGrUzKB9O5MDoMiEMeSLAyVgnVM5ioUwNBMnYDpUxDJ3@4rGxzspYT/pN6NM0sS8w1xwKpqwJXIuBIjGU0yl0g9kc0NWczkewh1VzlqKwRHNVrxkblEboczX//0BA "Icon – Try It Online")
`procedure`, `return` and `end` add a lot to the bytecount :)
[Answer]
# [Perl 5](https://www.perl.org/) `-lF`, 38 bytes
```
$i=<>;$F[$i++%@F]=$_ for<>=~/./g;say@F
```
[Try it online!](https://tio.run/##K0gtyjH9/18l09bGzlrFLVolU1tb1cEt1lYlXiEtv8jGzrZOX08/3bo4sdLB7f///LLUIi5jrvKizJJUhdzSnJLMgpxUhZLM3NTif/kFJZn5ecX/dX1N9QwMDf7r5rgBAA "Perl 5 – Try It Online")
Input is on three lines:
```
original string
offset
replacement string
```
[Answer]
# [Rust](https://www.rust-lang.org/), 129 bytes
This is about as close as I could get while maintaining safety
```
|mut x:Vec<u8>,y:Vec<u8>,z:usize|->String{let l=x.len();(z..y.len()+z).for_each(|i|x[i%l]=y[i-z]);String::from_utf8(x).unwrap()};
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 50 bytes
```
o(v,e,r)char*v,*e;{for(;*e;r*=!!v[++r])v[r]=*e++;}
```
[Try it online!](https://tio.run/##jZA/T8MwEMX3fIpLGWInBlGgC1HFVImpSzOgphmCuTSW8k@OE4SqfPZwjjzAApUs@/nd791ZlrdnKee5ZaNAobkscx2OIsT4UrSaxSR0uPX9MY0infEx1dk2xCiKp7k3uVESbALehyLdrB@y2Lv5wEI1CAk7CDgK2AvYcbjAyYPeaNl9MWIFsAPnsTVbdz9y2vbO7AZj2zKbqDtH7DiHFwjeAniG4C4gcvI81Rioc9UwmuHR0FVSqh5o5Xacas4rAeTlhs57J3@V@X@pzSKptkSvTa2fSNP//KgnpYuVyoKvWFUtmBI1@u5xJP4g1mT56Ih2RG2ZT60MQj1URnUVglE19q7bIq@iH6lEShE9zd8 "C (gcc) – Try It Online")
[Answer]
# [Julia 1.0](http://julialang.org/), ~~39~~ 32 bytes
```
a*b*c=b.|>i->a[mod1(c+=1,end)]=i
```
[Try it online!](https://tio.run/##nZLPTsQgEMbvPMUsp3ZdG@uuFxI2Hn2AvTUcKJ1YNvRPKKtr4rvXKdpEq5dKCDDzzfcjhDlfnNX5dRz1ttwaWWbvR3t71EXTVXlibmS@w7ZKlbRjwCEMIKFg/FTbAWhqGIK37TMHoJwOtC/H3bRE8YdhFePhi0HVEfQfRn6YGDp8N5xqYtT2VzV/Quc6CDV63PDlWyi1ypVHcYPk6l7QL3z81duA0FxcsL1DCLbBgc93xWCVbx9FOlvOFGOaPsx0zqEJWRJ/sBC7XKWs/Eu4J8GQMMd7xR4ziJ3BPOXPnW2zRKeMVXbonX5LCqFBlCBaEHjtCYYViGRytCkI03lPOfbZOh58JuXMPiiVjh8 "Julia 1.0 – Try It Online")
`a` and `b` are expected to be lists of characters, and the function mutates `a`
[Answer]
# TI-Basic, 51 bytes
```
Prompt Str1,Str2,I
Output(8,1,Str1
For(J,1,length(Str2
Output(8,remainder(I,length(Str1)),sub(Str2,J,1
End
```
Output is displayed. Uses 1-based indexing. Only works if the original string is 16 (or 26 on color calculators) or less characters long because of the limited screen width. Replace `remainder(I,length(Str1))` with `length(Str1)fPart(I/length(Str1))` (adds 4 bytes) if run on a calculator before the TI-84+/SE with the 2.53 MP OS.
---
Without using `Output(` (not limited by the screen size):
### 102 bytes
```
Prompt Str1,Str2,I
" "+Str1+" →Str3
For(J,1,length(Str2
1+remainder(I+J-2,length(Str1
sub(Str3,1,Ans)+sub(Str2,J,1)+sub(Str3,Ans+2,length(Str3)-Ans-1→Str3
End
sub(Str3,2,length(Str1
```
Output is stored in `Ans` and displayed. Uses 1-based indexing. Replace `remainder(I+J-2,length(Str1` with `length(Str1)fPart((I+J-2)/length(Str1` (adds 6 bytes) if run on a calculator before the TI-84+/SE with the 2.53 MP OS.
] |
[Question]
[
# Let me introduce you to GAU numbers
```
GAU(1) = 1
GAU(2) = 1122
GAU(3) = 1122122333
GAU(4) = 11221223331223334444
GAU(6) = 11221223331223334444122333444455555122333444455555666666
...
GAU(10) = 11221223331223334444122333444455555122333444455555666666122333444455555666666777777712233344445555566666677777778888888812233344445555566666677777778888888899999999912233344445555566666677777778888888899999999910101010101010101010
```
# **This challenge is pretty simple!**
Given an integer n>0, find the number of digits of GAU(n)
# Example
Let's make **GAU(4)**
we take the following steps (until we get to 4) and concatenate them
```
[1][122][122333][1223334444]
```
you must write every number as many times as its value, but you have to count every time from 1
Let's try to make **GAU(5)**
we will have to count from 1 to 1
```
[1]
```
then from 1 to 2 (but **repeating every number as many times as its value**)
```
[122]
```
then from 1 to 3
```
[122333]
```
then from 1 to 4
```
[1223334444]
```
and finally from 1 to 5 (this is the **last step** because we want to find GAU(**5**))
```
[122333444455555]
```
Now we take all these steps and concatenate them
the result is GAU(5)
```
11221223331223334444122333444455555
```
**We are interested in the number of digits of these GAU numbers.**
# Test cases
***Input⟼Output***
```
n ⟼ Length(GAU(n))
1 ⟼ 1
2 ⟼ 4
3 ⟼ 10
10 ⟼ 230
50 ⟼ 42190
100 ⟼ 339240
150 ⟼ 1295790
```
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge.
Shortest code in bytes will win.
If you still have any questions please let me know.
I really want everyone here to understand this magic-hidden-complex pattern
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), ~~11~~ ~~10~~ ~~8~~ ~~7~~ 5 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
∫∫l*+
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyMjJCJXUyMjJCbCorRiUwQTEwJXUyMDFEckY_) - this expects to be called as a function with the input on the stack and the input box empty.
7 byte alternative taking the input from the input box:
```
0.∫∫l*+
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=MC4ldTIyMkIldTIyMkJsKis_,inputs=MTA_)
```
0 push 0
. push the input
∫ iterate over a range 1..POP (input) inclusive, pusing the current number
∫ iterate over 1..POP (above loops number) inclusive, pusing the current number
l push that numbers length without popping the number
* multiply the length by the number
+ add to the zero, or whatever it is now
```
[Answer]
# [Haskell](https://www.haskell.org/), 45 bytes
```
f n=sum[j*length(show j)|i<-[1..n],j<-[1..i]]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hz7a4NDc6SysnNS@9JEOjOCO/XCFLsybTRjfaUE8vL1YnC8LKjI39n5uYmadgq5CSr8DFmZtY4KugUVCUmVeil6apAFJiaBCLKW5qoGNoAMSmBrH/AQ "Haskell – Try It Online")
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 166 bytes
```
<>(((()()())({}){})())<>{({}[()]<({}({}<<>({}[()])((){[()](<()>)}{}){{}((((({})({})){}{}){}))<>(({}<({}())>){()<({}[({})])>}{})(<>)}{}<>>({}({})())))>)}{}({}<{}{}{}>)
```
[Try it online!](https://tio.run/##JY2xCoAwDER/JzcIOriF/Ih0qIMgioNr6LfXO5smJG3vXva3ns903PXq3cMY0IFlA5OTR/KyGYqzM5268QCqU4O5IdDkoUQhL4uMAYLg9AoBatPgP4V/BSGV@Y/wiLFHyzGwcoqULdD7ss4f "Brain-Flak – Try It Online")
### Explanation
```
<>(((()()())({}){})())<> # Initialize second stack with 9 and 10
{({}[()]< # Do main loop n times:
({}
({}
<
<>({}[()]) # Subtract 1 from counter to next power of 10
((){[()](<()>)}{}){ # If reached a power of 10 (say, 10^k):
{}((((({})({})){}{}){})) # Multiply existing (10^k*0.9) by 10 and push twice
<> # On first stack
(
({}<({}())>) # Increment length of numbers
{()<({}[({})])>}{} # Divide length of new set of numbers by this length
) # Add together to get new set of numbers length
(<>)}
{}<>>
({}({})()) # Add number length to number set length
) # Add number set length to new segment length
) # Add new segment length to total length
>)} # End main loop
{}({}<{}{}{}>) # Put result on stack by itself
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 bytes
```
ṁLΣQḣ
```
[Try it online!](https://tio.run/##yygtzv7//@HORp9ziwMf7lj8//9/QwMA "Husk – Try It Online")
**Explanation**
```
ṁ map over
L length
Σ sum list
Q all sublists
ḣ range 1 .. N
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
Rx`ƤDFL
```
[Try it online!](https://tio.run/##y0rNyan8/z@oIuHYEhc3n////xsaAAA "Jelly – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
LŒJJg
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f5@gkL6/0//8NDQA "05AB1E – Try It Online")
**Explanation**
```
L # push [1 .. a]
Œ # all substrings (a)
J # numbers to strings (inner)
J # numbers to strings (outer)
g # length
```
[Answer]
# [Python 2](https://docs.python.org/2/), 53 bytes
```
lambda x:sum(len(`i`)*i*(x-i+1)for i in range(1,x+1))
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHCqrg0VyMnNU8jITNBUytTS6NCN1PbUDMtv0ghUyEzT6EoMS89VcNQpwIoqPkfLhxtqGOkY6xjaKBjagAkgdjUINaKi7OgKDOvRCNNIxOoGAA)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
Σ∫mS*Lḣ
```
[Try it online!](https://tio.run/##yygtzv7//9ziRx2rc4O1fB7uWPz//39DAwMA "Husk – Try It Online")
### Ungolfed/Explanation
```
-- implicit input N | 10
m ḣ -- map the following function over [1..N] | [1,2,3,4]
S*L -- multiply length of number by itself | [1,2,3,4] (only important for numbers ≥ 10)
∫ -- prefix sums | [0,1,3,6,10]
Σ -- sum | 20
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
ṁLṁṘNḣḣ
```
[Try it online!](https://tio.run/##yygtzv7//@HORh8gfrhzht/DHYuB6P///4amBgA "Husk – Try It Online")
### Explanation
```
Implicit input, e.g 4
ḣ Range from 1 to n [1,2,3,4]
ḣ Prefixes [[],[1],[1,2],[1,2,3],[1,2,3,4]]
ṁ Map and then concatenate
ṘN Repeat each number in each list by its index [[],[1],[1,2,2],[1,2,2,3,3,3],[1,2,2,3,3,3,4,4,4,4]]
[1,1,2,2,1,2,2,3,3,3,1,2,2,3,3,3,4,4,4,4]
ṁ Map and then sum
L Length (of number: 10 -> 2) 26
```
[Answer]
# JavaScript (ES6), ~~57~~ 55 bytes
```
n=>[...Array(n)].reduce(x=>x+(++y+"").length*y*n--,y=0)
```
[Try it online!](https://tio.run/##BcFLCoAgEADQu7SayRxatlHoHNFCbOiDjKEVenp773Kfyz6d96Mlbtx8lBwDU4g7QBNjFyKaU3IVBFdKvL2eoRhbFChVVdchBZb9Ofrai9ZDNSM2hAmx/Q)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~59~~ 58 bytes
*Another one bytes the dust thanks to Jonathan Frech.*
```
f=lambda n:n and sum(i*len(`i`)for i in range(n+1))+f(n-1)
```
[Try it online!](https://tio.run/##PYnBCoMwEAXvfsUed2sKieJF8EtKwRRNXdCnxPTg18ecOjBzmeNKy44m5zCsfvtMntCDPCY6fxvrY53Bo44S9khKCooe35lRO5E6MJ5O8v@9nGlMa5w1nS0tdvbdV1Q4oiJxYBXJNw "Python 2 – Try It Online")
Not short but eh... what the heck.
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 20 bytes
```
q~),(\{),{_s,*+}*+}%
```
[Try it online!](https://tio.run/##S85KzP3/v7BOU0cjplpTpzq@WEdLuxaIVP//BwA "CJam – Try It Online")
The number is passed in the "input" field.
Ungolfed explanation: (example input = 2)
```
q~),(\{),{_s,*+}*+}% | Stack:
q read input as string | "2"
~ eval input (add it to stack as integer) | 2
) add 1 | 3
, range (convert to array with values 0...N) | [0, 1, 2]
( pop first item of array | [1, 2] 0
\ swap top two values of stack | 0 [1, 2]
{ } for each item in array... | 0 1
) add 1 | 0 2
, range (convert to array with values 0...N) | 0 [0, 1]
{ } for every element in the array... | 0 0
_ duplicate | 0 0 0
s convert to string | 0 0 "0"
, get length of string | 0 0 1
* multiply | 0 0
+ add | 0 1
* fold | 0 1
+ add | 1
% repeat | 4
```
It seems hard when explained lol.
[Answer]
# JavaScript (ES6), ~~50~~ 42 bytes
*Updated: now basically a port of what other answers are doing.*
```
f=(n,i=1)=>n&&`${n}`.length*n*i+f(n-1,i+1)
```
### Test cases
```
f=(n,i=1)=>n&&`${n}`.length*n*i+f(n-1,i+1)
console.log(f(1)) // 1
console.log(f(2)) // 4
console.log(f(3)) // 10
console.log(f(10)) // 230
console.log(f(50)) // 42190
console.log(f(100)) // 339240
console.log(f(150)) // 1295790
```
[Answer]
# J, 24 bytes
```
[:+/[:+/\[:(*#@":"0)1+i.
```
Similar high-level approach to dzaima's APL answer, translated into J, except we calculate the number's length by turning it into a string first instead of taking logs, and we get to use J's hook to multiply that length by the number itself: `(*#@":"0)`. After that it's just the sum of the scan sum.
[Try it online!](https://tio.run/##y/r/P91WTyHaSlsfhGOirTS0lB2UrJQMNA21M/W4UpMz8hXSFQxhDCMYwxguZYBgGfz/DwA "J – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 39 bytes
```
function(n)sum(nchar(rep(1:n,n:1*1:n)))
```
[Verify all test cases!](https://tio.run/##DYhBCoAwDMC@00oPG7LLwMeM4lDQWjp38PW1hyQQ8755n8Lv@QgIjnmD8NEMbFfIVUhqXqKI6KOpXh9w/JVyopLCQUlIHf0H)
Simple algorithm; I observed, as most did, that for `i` in `1:n`, `i` is repeated `i*(n-i+1)` times. So I create that vector, count the number of characters in each, and sum them.
[Answer]
# [Perl 6](https://perl6.org), 36 bytes
```
{[+] 1..*Z*($_...1).map:{.chars*$_}}
```
[Test it](https://tio.run/##ZY5NTsMwEIX3PsUsIpSfMq2dpChERWzZs@JHUXCmIlJ@rDhFoJKzcBBYcRQuEuzUrNjY7z1/88aKhmY7HzTByxZlzto3OJN9RbCbj/fRI3DE8C70vQIReYBtqS6PKJ/LQYdeMU2z4a9H0iPsoKk70r5jGMA7yr598tcPVbQOvj/xphtX4BVsYnbdrRnKmWrKDqKlIWf7fnBl51fge3WnDnaCXhXJkSojK9IyAFtea7DfdFTwH2PTzAHg5@MLzM2E04nR8V@@McYe1ojYCGCps4ng2el5s/g4zkSyBOkp4CJLLyzyCw "Perl 6 – Try It Online")
## Expanded:
```
{ # bare block lambda with implicit parameter 「$_」
[+] # reduce the following using &infix:«+»
1 .. * # Range from 1 to infinity
Z* # zip using &infix:«*»
( $_ ... 1 ) # sequence from the input down to 1
.map: # for each one
{ .chars * $_ } # multiply the number of digits with itself
}
```
[Answer]
# [Röda](https://github.com/fergusq/roda), 31 bytes
```
{f={seq 1,_}f|f|[#`$_`*_1]|sum}
```
[Try it online!](https://tio.run/##K8pPSfzv9r86zba6OLVQwVAnvjatJq0mWjlBJT5BK94wtqa4NLf2f25iZp5CNZcCEBQUZeaVKBSUFmdoGJoaaCrUKLhpaHLV/gcA "Röda – Try It Online")
[Answer]
# Python 2, 51 50 bytes
```
lambda n:sum(~k*(k-n)*len(`k+1`)for k in range(n))
```
[Answer]
# Mathematica, 66 bytes
```
Tr[1^(f=Flatten)[IntegerDigits/@f@(a=Array)[a[#~Table~#&,#]&,#]]]&
```
[Answer]
# [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 21 bytes
```
[:|[a|[c|A=A+!c$}?_lA
```
[Answer]
# [Actually](https://github.com/Mego/Seriously), 13 bytes
```
R♂R♂i⌠;n⌡Mεjl
```
[Try it online!](https://tio.run/##S0wuKU3Myan8/z/o0cwmEM581LPAOu9Rz0Lfc1uzcv7/NzQAAA "Actually – Try It Online")
Explanation:
```
R♂R♂i⌠;n⌡Mεjl
R range(1, n+1)
♂R range(1, x+1) for x in previous
♂i flatten into 1D list
⌠;n⌡M for x in list:
;n repeat x x times
εj concatenate to string
l length
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), ~~12~~ ~~11~~ ~~10~~ 9 bytes
```
õõÈ*sÊÃxx
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=9fXIKnPKw3h4&input=OA==) or [test all numbers from 1 to 150](https://ethproductions.github.io/japt/?v=1.4.5&code=9V/19cgqc8rDeHg=&input=MTUw).
---
## Explanation
Implicit input of integer `U`.
```
õõ
```
Generate an array of integers from 1 to `U` and then generate sub-arrays from 1 to each integer.
```
È Ã
```
Pass the elements of each sub-array through a function.
```
*sÊ
```
Convert the current element to a string (`s`), get it's length (`Ê`) and multiply it by the element.
```
xx
```
Reduce the main array by addition after first doing the same to each sub-array.
[Answer]
# [Jq 1.5](https://stedolan.github.io/jq/), ~~82~~ ~~49~~ 43 bytes
```
[range(.)+1|range(.)+1|"\(.)"*.|length]|add
```
Expanded
```
[ range(.)+1 # for i=1 to N
| range(.)+1 # for j=1 to i
| "\(.)"*. # "j" copied j times
| length # convert to length
] | add # add lengths
```
Sample Run
```
$ jq -Mr '[range(.)+1|range(.)+1|"\(.)"*.|length]|add' <<< "150"
1295790
```
[Try it online!](https://tio.run/##yyr8b1rzP7ooMS89VUNPU9uwBompFAOklbT0anJS89JLMmJrElNS/v//l19QkpmfV/xfVzevNCdHNzOvoLQEyClKLNfNLy0BcgA "jq – Try It Online") also [jqplay.org](https://jqplay.org/s/eo2lWPgLj0)
[Answer]
# [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 28 bytes
```
[~>[~>[:rep]"!]"!flat''#`#']
```
[Try it online!](https://tio.run/##Ky5JTM5OTfn/P7rODoSsilILYpUUgSgtJ7FEXV05QVk99r@DVRoXl6GBQp2dgoapgYKhARCbGmgq6ChEWymkASl1BV07IJGVn5mnkF9aEquQm1jwHwA "Stacked – Try It Online")
Some might ask, "At which point are aliases unreadable?" If this isn't close, you have a very liberal definition of "readability".
## Explanation
```
[~>[~>[:rep]"!]"!flat''#`#'] input: N
~>[ ]"! for each number K from 1 to N
~>[ ]"! for each number J from 1 to K
:rep repeat J J times
flat flatten the resultant array
''#` join by the empty string
#' get the length of said string
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~41~~ 40 bytes
```
->n{(1..n).map{|x|[x]*x*=-x-~n}*''=~/$/}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWsNQTy9PUy83saC6pqImuiJWq0LLVrdCty6vVktd3bZOX0W/9j9IkaEBVFVRTYFCdJFOWnRRbGztfwA "Ruby – Try It Online")
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 94 80 74 bytes
```
n=>{int b=0,a=0,i;while(a++<n)for(i=0;i++<a;)b+=(i+"").Length*i;return b;}
```
[Try it online!](https://tio.run/##fY6xasMwEEDn6CuOTFKcGich00VZAp1SKDSQWVbU5MA9EUluKcbf7opCoUPs4Q4ej8edjU/WBze0kfgKb98xuQ8U/6k8Et9R2MbECK@diMkksvDcst0RpyXktYcTaBhY77tMUOtqafIQft2ocdIUxY7Vuw@SdIWUyaCqCy2pmM9VeXR8TbcFYXCpDQw19gOKv0Ofni7wYoilEp2YHTxH37jyHCi5/JqTJ7lSCh@b9ajZjJpVNaq21UQ1lU12v7IX/fAD "C# (.NET Core) – Try It Online")
I was hoping to find a direct solution like what [@kamoroso94's answer](https://codegolf.stackexchange.com/a/143614/73579) started, but gave up as I was spending too much time on it. There probably is a way of doing it, but the formula needs to adjust for every magnitude step.
### Acknowledgements
14 bytes saved thanks to @someone
6 bytes saved thanks to @Kevin Cruijssen
[Answer]
# [MATL](https://github.com/lmendo/MATL), 15 bytes
```
:ttP*Y"10&YlQks
```
[Try it online!](https://tio.run/##y00syfn/36qkJEArUsnQQC0yJzC7@P9/Q1MDAA "MATL – Try It Online")
Explanation:
```
: range 1:input (implicit input)
tt duplicate twice
P reverse
* multiply elementwise
Y" runlength decoding
10&Yl log10
Qk increment and floor
s sum (implicit output)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~18~~ 14 bytes
```
IΣE⊕NΣE⊕ι×λLIλ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI7g0V8M3sUDDMy@5KDU3Na8kNQXILigt8SvNTUot0tDU1FHApiYTKB6SmZtarJGjo@CTmpdekgExMEcTBqz//zc0@K9b9l@3OAcA "Charcoal – Try It Online") Link is to verbose version of code. Edit: Using `Sum` saved me 4 bytes. Explanation:
```
E⊕N Map from 0 to the input (loop variable i)
E⊕ι Map from 0 to i (loop variable l)
Iλ Cast l to string
L Take the length
×λ Multiply by l
Σ Sum the results
Σ Sum the results
I Cast to string
Implicitly print
```
[Answer]
# [Ohm v2](https://github.com/MiningPotatoes/Ohm), 7 bytes
```
@@D×JJl
```
[Try it online!](https://tio.run/##y8/INfr/38HB5fB0L6@c//8NDQz@AwA "Ohm v2 – Try It Online")
[Answer]
# [Dyalog APL], ~~22~~ 20 bytes
```
{+/≢¨⍕¨↑,/(/⍨¨⍳¨⍳⍵)}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P03hUdsEhWpt/Uediw6teNQ7FUi0TdTR19B/1LsCJLAZTDzq3apZ@/9R31Sw8rRDKxSAgqZccAEFQwMkjqnBfwA "APL (Dyalog Unicode) – Try It Online")
Explanation:
```
{+/≢¨⍕¨↑,/(/⍨¨⍳¨⍳⍵)}
{ } anonymous function with right argument named ⍵
⍳⍵ range 1 to right arg
⍳¨ for each, range 1 to it
¨ for each
/⍨ for each item, repeat right arg left arg times
( ) take that and
,/ join the sub-arrays together
↑ convert from a nested array to a simple array (or something like that, I don't quite understand it :p)
⍕¨ convert each number to a char-array (aka string version)
≢¨ get length of each
+/ sum that together
```
] |
[Question]
[
The [Bernoulli numbers](https://en.wikipedia.org/wiki/Bernoulli_number) (specifically, the second Bernoulli numbers) are defined by the following recursive definition:
[](https://i.stack.imgur.com/tNGGY.png)
Where [](https://i.stack.imgur.com/x3UZs.png) denotes a [combination](https://en.wikipedia.org/wiki/Combination).
Given a nonnegative integer `m` as input, output the decimal representation OR a reduced fraction for the `m`th second Bernoulli number. If you output a decimal representation, you must have at least 6 decimal places (digits after the decimal point) of precision, and it must be accurate when rounded to 6 decimal places. For example, for `m = 2`, `0.166666523` is acceptable because it rounds to `0.166667`. `0.166666389` is not acceptable, because it rounds to `0.166666`. Trailing zeroes may be omitted. Scientific notation may be used for decimal representations.
Here is the input and expected output for `m` up to and including 60, in scientific notation rounded to 6 decimal places, and as reduced fractions:
```
0 -> 1.000000e+00 (1/1)
1 -> 5.000000e-01 (1/2)
2 -> 1.666667e-01 (1/6)
3 -> 0.000000e+00 (0/1)
4 -> -3.333333e-02 (-1/30)
5 -> 0.000000e+00 (0/1)
6 -> 2.380952e-02 (1/42)
7 -> 0.000000e+00 (0/1)
8 -> -3.333333e-02 (-1/30)
9 -> 0.000000e+00 (0/1)
10 -> 7.575758e-02 (5/66)
11 -> 0.000000e+00 (0/1)
12 -> -2.531136e-01 (-691/2730)
13 -> 0.000000e+00 (0/1)
14 -> 1.166667e+00 (7/6)
15 -> 0.000000e+00 (0/1)
16 -> -7.092157e+00 (-3617/510)
17 -> 0.000000e+00 (0/1)
18 -> 5.497118e+01 (43867/798)
19 -> 0.000000e+00 (0/1)
20 -> -5.291242e+02 (-174611/330)
21 -> 0.000000e+00 (0/1)
22 -> 6.192123e+03 (854513/138)
23 -> 0.000000e+00 (0/1)
24 -> -8.658025e+04 (-236364091/2730)
25 -> 0.000000e+00 (0/1)
26 -> 1.425517e+06 (8553103/6)
27 -> 0.000000e+00 (0/1)
28 -> -2.729823e+07 (-23749461029/870)
29 -> 0.000000e+00 (0/1)
30 -> 6.015809e+08 (8615841276005/14322)
31 -> 0.000000e+00 (0/1)
32 -> -1.511632e+10 (-7709321041217/510)
33 -> 0.000000e+00 (0/1)
34 -> 4.296146e+11 (2577687858367/6)
35 -> 0.000000e+00 (0/1)
36 -> -1.371166e+13 (-26315271553053477373/1919190)
37 -> 0.000000e+00 (0/1)
38 -> 4.883323e+14 (2929993913841559/6)
39 -> 0.000000e+00 (0/1)
40 -> -1.929658e+16 (-261082718496449122051/13530)
41 -> 0.000000e+00 (0/1)
42 -> 8.416930e+17 (1520097643918070802691/1806)
43 -> 0.000000e+00 (0/1)
44 -> -4.033807e+19 (-27833269579301024235023/690)
45 -> 0.000000e+00 (0/1)
46 -> 2.115075e+21 (596451111593912163277961/282)
47 -> 0.000000e+00 (0/1)
48 -> -1.208663e+23 (-5609403368997817686249127547/46410)
49 -> 0.000000e+00 (0/1)
50 -> 7.500867e+24 (495057205241079648212477525/66)
51 -> 0.000000e+00 (0/1)
52 -> -5.038778e+26 (-801165718135489957347924991853/1590)
53 -> 0.000000e+00 (0/1)
54 -> 3.652878e+28 (29149963634884862421418123812691/798)
55 -> 0.000000e+00 (0/1)
56 -> -2.849877e+30 (-2479392929313226753685415739663229/870)
57 -> 0.000000e+00 (0/1)
58 -> 2.386543e+32 (84483613348880041862046775994036021/354)
59 -> 0.000000e+00 (0/1)
60 -> -2.139995e+34 (-1215233140483755572040304994079820246041491/56786730)
```
Reference implementation (in Python 3):
```
def factorial(n):
if n < 1:
return 1
else:
return n * factorial(n - 1)
def combination(m,k):
if k <= m:
return factorial(m)/(factorial(k) * factorial(m - k))
else:
return 0
def Bernoulli(m):
if m == 0:
return 1
else:
t = 0
for k in range(0, m):
t += combination(m, k) * Bernoulli(k) / (m - k + 1)
return 1 - t
```
### Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins
* You may not use any functions, either built-in or included in an external library, that compute either type of Bernoulli numbers or Bernoulli polynomials.
* Your answer must give correct output for all inputs up to and including 60.
# Leaderboard
The Stack Snippet at the bottom of this post generates the leaderboard 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 = 65382; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 45941; 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.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>
```
[Answer]
# Mathematica, ~~40~~ ~~28~~ ~~23~~ 22 bytes
Using the famous formula *n*\**ζ*(1−*n*)=−*B**n*, where *ζ* is the [Riemann Zeta function](https://en.wikipedia.org/wiki/Riemann_zeta_function).
```
If[#>0,-Zeta[1-#]#,1]&
```
The same length:
```
B@0=1;B@n_=-Zeta[1-n]n
```
---
Original solution, 40 bytes, using [the generating function of Bernoulli numbers](https://en.wikipedia.org/wiki/Bernoulli_number#Generating_function).
```
#!SeriesCoefficient[t/(1-E^-t),{t,0,#}]&
```
[Answer]
# Julia, 58 bytes
```
B(m)=m<1?1:1-sum(k->big(binomial(m,k))*B(k)/(m-k+1),0:m-1)
```
This creates a recursive function `B` that accepts an integer and returns a `BigFloat` (i.e. high precision floating point).
Ungolfed:
```
function B(m::Integer)
m == 0 && return 1
return 1 - sum(k -> big(binomial(m, k)) * B(k) / (m-k+1), 0:m-1)
end
```
[Answer]
## [Minkolang 0.14](http://github.com/elendiastarman/Minkolang), 97 bytes
I actually tried doing it recursively first, but my interpreter, as currently designed, actually can't do it. If you try to recurse from within a for loop, it starts a new recursion. So I went for the tabulating approach...which had precision problems. So I did the whole thing with fractions. With no built-in support for fractions. [*sigh*]
```
n1+[xxi$z0z2%1+F0c0=$1&$d4Mdm:1R:r$dz1Az0A]$:N.
11z[i0azi6M*i1azi-1+*d0c*1c2c*-1c3c*4$X]f
z1=d1+f
```
[Try it here.](http://play.starmaninnovations.com/minkolang/?code=n1%2B%5Bxxi%24z0z2%251%2BF0c0%3D%241%26%24d4Mdm%3A1R%3Ar%24dz1Az0A%5D%24%3AN%2E%0A11z%5Bi0azi6M*i1azi-1%2B*d0c*1c2c*-1c3c*4%24X%5Df%0Az1%3Dd1%2Bf&input=60) Bonus: the array has all fractions for every previous Bernoulli number!
### Explanation (in a bit)
```
n1+ Take number from input (N) and add 1
[ Open for loop that runs N+1 times (starts at zero)
xx Dump the top two values of the stack
i$z Store the loop counter in the register (m)
0 Push 0
z2%1+ Push 1 if N is even, 2 if odd
F Gosub; pops y,x then goes to codebox(x,y), to be returned to
0c Copy the first item on the stack
, 1 if equal to 0, 0 otherwise
$1& Jump 11 spaces if top of stack is not 0
(If top of stack is not 0, then...)
$d Duplicate whole stack
4M Pop b,a and push GCD(a,b)
dm Duplicate and merge (a,b,c,c -> a,c,b,c)
: Divide
1R Rotate 1 item to the right (0G works too)
: Divide
r Reverse stack
(In both cases...)
$d Duplicate whole stack
z1A Store denominator of B_m in array
z0A Store numerator of B_m in array
] Close for loop
$: Divide (float division)
N. Output as number and stop.
11 Push two 1s (a, b)
z[ Open a for loop that repeats m times
i0a Retrieve numerator of B_k (p)
zi Push m, k
6M Pop k,m and push mCk (binomial) (x)
* p*x (c)
i1a Retrieve denominator of B_k (q)
zi-1+ m-k+1 (y)
* q*y (d)
d Duplicate top of stack
0c* a*d
1c2c* b*c
- a*d-b*c
1c3c* b*d
4$X Dump the bottom four items of stack
]f Jump back to F
z m
1= 0 (if m is 1) or 1 (otherwise)
d1+ Duplicate and add 1 (1 or 2)
f Jump back to F
```
The third line is responsible for `1/2` if `m` is 1 and `0/1` if `m` is an odd number greater than 1. The second line calculates `B_m` with the summation formula given in the question, and does so entirely with numerators and denominators. Otherwise it'd be a lot shorter. The first half of the first line does some bookkeeping and chooses whether to execute the second or third line, and the second half divides the numerator and denominator by their GCD (if applicable) and stores those values. And outputs the answer at the end.
[Answer]
# Julia, ~~23~~ 20 bytes
Saved 3 bytes thanks to Alex A.
It uses the same formula as [my Mathematica solution](https://codegolf.stackexchange.com/a/65408/9288) and [PARI/GP solution](https://codegolf.stackexchange.com/a/65412/9288).
```
n->n>0?-zeta(1-n)n:1
```
[Answer]
# Python 2, 118 bytes
*Saved 6 bytes due to [xsot](https://codegolf.stackexchange.com/posts/comments/158355?noredirect=1).*
*Saved ~~6~~ 10 more due to [Peter Taylor](https://codegolf.stackexchange.com/posts/comments/158810?noredirect=1).*
```
n=input()
a=[n%4-1,n<2]*n;exec"a=[(a[j-1]+a[j+1])*j/2for j in range(len(a)-2)];"*~-n
print+(n<1)or-n/(2.**n-4**n)*a[1]
```
Uses the following identity:

where *An* is the *nth* [Alternating Number](http://en.wikipedia.org/wiki/Alternating_permutation#Related_integer_sequences), which can be formally defined as the number of alternating permutations on a set of size *n*, halved (see also: [A000111](http://oeis.org/A000111)).
The algorithm used was originally given by [Knuth and Buckholtz (1967)](http://www.ams.org/journals/mcom/1967-21-100/S0025-5718-1967-0221735-9/):
>
> *Let T1,k = 1 for all k = 1..n*
>
>
> *Subsequent values of T are given by the recurrence relation:*
>
>
> *Tn+1,k = 1/2* [ *(k - 1) Tn,k-1 + (k + 1) Tn,k+1* ]
>
>
> *An is then given by Tn,1*
>
>
> (see also: [A185414](http://oeis.org/A185414))
>
>
>
---
## Python 2, 152 bytes
```
from fractions import*
n=input()
a=[n%4-1,n<2]*n
for k in range(n-1):a=[(a[j-1]+a[j+1])*j/2for j in range(n-k)]
print+(n<1)or Fraction(n*a[1],4**n-2**n)
```
Prints the exact fractional representation, necessary for values greater than 200 or so.
[Answer]
# PARI/GP, ~~52~~ 23 bytes
Using the famous formula *n*\**ζ*(1−*n*)=−*B**n*, where *ζ* is the [Riemann Zeta function](https://en.wikipedia.org/wiki/Riemann_zeta_function).
```
n->if(n,-n*zeta(1-n),1)
```
---
Original solution, 52 bytes, using [the generating function of Bernoulli numbers](https://en.wikipedia.org/wiki/Bernoulli_number#Generating_function).
```
n->n!*polcoeff(-x/sum(i=1,n+1,(-x)^i/i!)+O(x^n*x),n)
```
[Answer]
## CJam, ~~69 49 34~~ 33 bytes
```
{_),:):R_:*_@f/@{_(;.-R.*}*0=\d/}
```
[Online demo](http://cjam.aditsu.net/#code=%7B_)%2C%3A)%3AR_%3A*_%40f%2F%40%7B_(%3B.-R.*%7D*0%3D%5Cd%2F%7D%0A%0A61%25N*)
Thanks to [Cabbie407](https://codegolf.stackexchange.com/users/44613/cabbie407), whose answer made me aware of the Akiyama–Tanigawa algorithm.
### Dissection
```
{ e# Function: takes n on the stack
_),:) e# Stack: n [1 2 3 ... n+1]
:R e# Store that array in R
_:* e# Stack: n [1 2 3 ... n+1] (n+1)!
_@f/ e# Stack: n (n+1)! [(n+1)!/1 (n+1)!/2 (n+1)!/3 ... (n+1)!/(n+1)]
e# representing [1/1 1/2 ... 1/(n+1)] but avoiding floating point
@{ e# Repeat n times:
_(;.- e# Take pairwise differences
R.* e# Pointwise multiply by 1-based indices
}* e# Note that the tail of the array accumulates junk, but we don't care
0=\d/ e# Take the first element and divide by (n+1)!
}
```
[Answer]
# Python 3, 112 bytes
**Edit:** I cleaned up this answer. If you want to see all the other ways I thought of to answer this question in Python 2 and 3, look in the revisions.
If I don't use the lookup table (and I use memoization instead), I manage to get the recursive definition to 112 bytes! WOO! Note that `b(m)` returns a `Fraction`. As usual, [the byte count](https://mothereff.in/byte-counter#from%20fractions%20import%2A%0Adef%20e%28m%29%3A%0A%20if%20m%3C1%3Areturn%201%0A%20s%3Dk%3D0%3Bp%3D1%0A%20while%20k%3Cm%3Aa%3Dm-k%3Bs%2B%3DFraction%28p%2Ae%28k%29%29%2F-%7Ea%3Bp%3Dp%2Aa%2F%2F-%7Ek%3Bk%2B%3D1%0A%20return%201-s) and [a link for testing](http://ideone.com/ZG7m33).
```
from fractions import*
def b(m):
s=k=0;p=1
while k<m:a=m-k;s+=Fraction(p*b(k))/-~a;p=p*a//-~k;k+=1
return 1-s
```
And a function that does use a lookup table, and returns the whole table of fractions from `b(0)` to `b(m)`, inclusive.
```
from fractions import*
def b(m,r=[]):
s=k=0;p=1
while k<m:
if k>=len(r):r=b(k,r)
a=m-k;s+=Fraction(p*r[k])/-~a;p=p*a//-~k;k+=1
return r+[1-s]
```
[Answer]
# PARI/GP, 45 bytes
```
n->if(n,2*n/(2^n-4^n)*real(polylog(1-n,I)),1)
```
Using the same formula as my [Python answer](https://codegolf.stackexchange.com/a/65410/4098), with *An* generated via polylog.
---
**Test Script**
Run `gp`, at the prompt paste the following:
```
n->if(n,2*n/(2^n-4^n)*real(polylog(1-n,I)),1)
for(i=0, 60, print(i, ": ", %(i)))
```
[Answer]
## Mathematica, ~~52~~ ~~48~~ 42 bytes
```
1-Sum[#~Binomial~k#0@k/(#-k+1),{k,0,#-1}]&
```
Unnamed function that uses the literal definition.
[Answer]
# Python 2, ~~132~~ 130 bytes
```
import math,fractions
f=math.factorial
B=lambda m:~-m*m%2or 1+sum(B(k)*f(m)/f(k)/f(m-k)/fractions.Fraction(k+~m)for k in range(m))
```
This is just a golfed version of the reference implementation.
This is a little slow in practice, but can be sped up significantly with memoization:
```
import math,fractions
f=math.factorial
def memoize(f):
memo = {}
def helper(x):
if x not in memo:
memo[x] = f(x)
return memo[x]
return helper
@memoize
def B(m):
return~-m*m%2or 1+sum(B(k)*f(m)/f(k)/f(m-k)/fractions.Fraction(k+~m)for k in range(m))
for m in range(61):
print(B(m))
```
You can try this version online on [Ideone](http://ideone.com/oc6yHW).
[Answer]
# gawk4, 79 bytes
77 bytes code + 2 bytes for `-M` flag
```
PREC^=2{for(n=$0;m++<=n;)for($(j=m)=1/m;j>1;)$j=(-$j+$--j)*j;printf"%.6f",$1}
```
It's an implementation of the Akiyama–Tanigawa algorithm from the Wikipedia page.
Had some trouble with the "6-decimal-digits-rule", because this prints the whole number and then 6 digits, but there is no list here to compare the results.
A flaw is that this prints a minus sign in front of the `0.000000` al lot of times, but I don't think that's wrong.
## Usage example
```
echo 58 | awk -M 'PREC^=2{for(n=$0;m++<=n;)for($(j=m)=1/m;j>1;)$j=(-$j+$--j)*j;printf"%.6f",$1}'
```
## Output from 0 to 60
```
0 -> 1.000000
1 -> 0.500000
2 -> 0.166667
3 -> -0.000000
4 -> -0.033333
5 -> 0.000000
6 -> 0.023810
7 -> 0.000000
8 -> -0.033333
9 -> 0.000000
10 -> 0.075758
11 -> -0.000000
12 -> -0.253114
13 -> -0.000000
14 -> 1.166667
15 -> -0.000000
16 -> -7.092157
17 -> -0.000000
18 -> 54.971178
19 -> -0.000000
20 -> -529.124242
21 -> -0.000000
22 -> 6192.123188
23 -> 0.000000
24 -> -86580.253114
25 -> 0.000000
26 -> 1425517.166667
27 -> 0.000000
28 -> -27298231.067816
29 -> 0.000000
30 -> 601580873.900642
31 -> 0.000000
32 -> -15116315767.092157
33 -> 0.000000
34 -> 429614643061.166667
35 -> 0.000000
36 -> -13711655205088.332772
37 -> 0.000000
38 -> 488332318973593.166667
39 -> -0.000000
40 -> -19296579341940068.148633
41 -> -0.000000
42 -> 841693047573682615.000554
43 -> -0.000000
44 -> -40338071854059455413.076812
45 -> -0.000000
46 -> 2115074863808199160560.145390
47 -> -0.000000
48 -> -120866265222965259346027.311937
49 -> -0.000000
50 -> 7500866746076964366855720.075758
51 -> -0.000000
52 -> -503877810148106891413789303.052201
53 -> -0.000000
54 -> 36528776484818123335110430842.971178
55 -> -0.000000
56 -> -2849876930245088222626914643291.067816
57 -> -0.000000
58 -> 238654274996836276446459819192192.149718
59 -> -0.000000
60 -> -21399949257225333665810744765191097.392674
```
[Answer]
# R, 93 bytes
```
function(m){if(m==0){1}else{v=c();for(k in 0:(m-1))v=c(v,choose(m,k)*f(k)/(m-k+1));1-sum(v)}}
```
Not really original as a solution. If any comment, please feel free !
**Ungolfed :**
```
function(m)
if(m==0){1}
else
v=c()
for(k in 0:(m-1))
v=c(v,choose(m,k)*f(k)/(m-k+1))
1-sum(v)
```
[Answer]
# GolfScript, 63 bytes
```
~:i.!+.[3i&(2i>]*i(,{i\-,{1$1$(=2$2$)=+*2/}%\;}/~\2i?.(*\--1?**
```
[Online Demo](http://golfscript.apphb.com/?c=IjYwIgp%2BOmkuISsuWzNpJigyaT5dKmkoLHtpXC0sezEkMSQoPTIkMiQpPSsqMi99JVw7fS9%2BXDJpPy4oKlwtLTE%2FKio%3D).
Using the same formula as my [Python answer](https://codegolf.stackexchange.com/a/65410/4098).
---
**Test Script**
```
61,{[.`
~:i.!+.[3i&(2i>]*i(,{i\-,{1$1$(=2$2$)=+*2/}%\;}/~\2i?.(*\--1?**
]p}/
```
The apphb link will time out on this. If you don't have GolfScript installed locally, I recommend using the [anarchy golf interpreter](http://golf.shinh.org/check.rb) (use form, select GolfScript, paste, submit).
[Answer]
# Perl, 101 bytes
```
#!perl -p
@a=($_%4-1,$_<2)x$_;
@a=map$_*($a[$_-1]+$a[$_+1])/2,0..@a-3for 2..$_;
$_=!$_||$_/(4**$_-2**$_)*$a[1]
```
Counting the shebang as three, input is taken from stdin.
Using the same formula as my [Python answer](https://codegolf.stackexchange.com/a/65410/4098).
---
**Sample Usage**
```
$ echo 60 | perl bernoulli.pl
-2.13999492572253e+034
```
[Online Demo](http://codepad.org/ht3M6XJw).
[Answer]
# Ruby, ~~66~~ 61 bytes
This is a Ruby version of my Python answer.
```
b=->m{s,p=0r,1;m.times{|k|a=m-k;s+=p*b[k]/-~a;p=p*a/-~k};1-s}
```
Since this uses `Rational` in its answers, I'm fairly sure this works up to 60, but I had trouble running even `b[24]`, so I implemented the lookup table again for ~~86~~ ~~81~~ 80 bytes.
```
t=->m{s,p,r=0r,1,m>0?t[m-1]:[];m.times{|k|a=m-k;s+=p*r[k]/-~a;p=p*a/-~k};r<<1-s}
```
[Answer]
# J, 10 bytes
```
(%1-^@-)t:
```
Computes the *nth* Bernoulli number by finding the *nth* coefficient of the exponential generating function of *x*/(1 - *e-x*).
## Usage
If the input is given integer or floats as an argument, it will output a float. If given an extended integer, marked with a suffix `x`, it will output either an extended integer or a rational, two extended integers separated by `r`.
```
f =: (%1-^@-)t:
f 1
0.5
f 1x
1r2
(,.f"0) i. 10x
0 1
1 1r2
2 1r6
3 0
4 _1r30
5 0
6 1r42
7 0
8 _1r30
9 0
```
## Explanation
```
(%1-^@-)t: Input: n
( )t: Takes a monad and creates a new monad that
computes the coefficients of its egf
( ) A monad that operates on x
- Negate x
^@ Computes its exponential, e^-x
1- Subtract it from 1
% Divide x by it, x/(1 - e^-x)
```
[Answer]
# Axiom, ~~134~~ 147 bytes
```
b(n:NNI):FRAC INT==(v:=[1/1];k:=1;repeat(k>n=>break;r:=1-reduce(+,[binomial(k,j)*v.(j+1)/(k-j+1)for j in 0..k-1]);v:=append(v,[r]);k:=k+1);v.(n+1))
```
ungolf and test
```
(23) -> b
(23)
b n ==
1
v := [-]
1
k := 1
repeat
if n < k
then break
else
binomial(k,j)v(j + 1)
r := 1 - reduce(+,[[--------------------- for j in 0..(k - 1)]])
k - j + 1
v := append(v,[r])
k := k + 1
v(n + 1)
Type: FunctionCalled b
(50) -> [[i,b(i)] for i in [0,1,2,3,4,5,6,7,8,9,10]]
(50)
1 1 1 1 1 5
[[0,1],[1,-],[2,-],[3,0],[4,- --],[5,0],[6,--],[7,0],[8,- --],[9,0],[10,--]]
2 6 30 42 30 66
Type: List List Fraction Integer
(51) -> b 1000
(51)
-
18243104738661887254572640256857788879338336867042906052197158157641126_
2572624911158657472577321069709615489924627495522908087488299539455188_
7918567582241551668492697244184914012242579830955617098629924652251740_
9791915637226361428342780548971002281045465308441161372350696920220116_
2441791760680262602019620260255790058416539271332852806000966628467639_
0683434226380702951226108116666172815817157023611889303668166839919156_
3797683877845690114843122753427426880591799883780255338278664578660218_
5045895962670442011443630321460259486764674312436994856054301765557425_
1371150213401051058408679874766352952749178734973676859834707623881634_
6251471489942512878190574323531299070406930309477389251738705417680653_
1183648189451892725726445949589759600705334767585389769924857630972963_
9976364832442643512622073858780110731539833099817555775136008111170797_
6250597322951308884900670113339167641953793994512377610306198429310933_
1214632141683542607746641232089854815064629129596536997380608256428801_
9784909897301658268809203555030692846151917069465607257641149187197651_
0905515966840312411845543650593021402849221691341852819791233589301994_
1012291773441794027493574651881059432274494354092231954894280742068472_
7146192942133436054611475404867886313250114399681532753236429290625909_
3411000391368336312138915621701535954814084208794241665492294270773347_
6055878415765927582014214726584822236443691314366097570085473354584000_
9985915190584047337934331297339403392719579093995842312746836871169674_
9786460913411872527166990047126222109345933847358924230951718379883743_
2563465487604170316077418754242710065269818190591271690695446633836120_
3745255515267088218383996330164203403732365333352120338272021319718003_
5994220458994876460018350270385634117807768745161622933834063145505621_
9106004731529642292049578901
/
342999030
Type: Fraction Integer
(52) -> b 60
1215233140483755572040304994079820246041491
(52) - -------------------------------------------
56786730
Type: Fraction Integer
```
[Answer]
# APL(NARS), 83 chars, 166 bytes
```
r←B w;i
r←,1⋄i←0x⋄w+←1
→3×⍳w≤i+←1⋄r←r,1-+/{(1+i-⍵)÷⍨(⍵!i)×r[⍵+1]}¨0..i-1⋄→2
r←r[i]
```
Input as integer output as big rational
```
B 0
1
B 1
1r2
B 2
1r6
B 3
0
B 4
¯1r30
B 10
5r66
B 100
¯94598037819122125295227433069493721872702841533066936133385696204311395415197247711r33330
B 1000
¯1824310473866188725457264025685778887933833686704290605219715815764112625726249111586574725773210697096154899246
27495522908087488299539455188791856758224155166849269724418491401224257983095561709862992465225174097919156
37226361428342780548971002281045465308441161372350696920220116244179176068026260201962026025579005841653927
13328528060009666284676390683434226380702951226108116666172815817157023611889303668166839919156379768387784
56901148431227534274268805917998837802553382786645786602185045895962670442011443630321460259486764674312436
99485605430176555742513711502134010510584086798747663529527491787349736768598347076238816346251471489942512
87819057432353129907040693030947738925173870541768065311836481894518927257264459495897596007053347675853897
69924857630972963997636483244264351262207385878011073153983309981755577513600811117079762505973229513088849
00670113339167641953793994512377610306198429310933121463214168354260774664123208985481506462912959653699738
06082564288019784909897301658268809203555030692846151917069465607257641149187197651090551596684031241184554
36505930214028492216913418528197912335893019941012291773441794027493574651881059432274494354092231954894280
74206847271461929421334360546114754048678863132501143996815327532364292906259093411000391368336312138915621
70153595481408420879424166549229427077334760558784157659275820142147265848222364436913143660975700854733545
84000998591519058404733793433129733940339271957909399584231274683687116967497864609134118725271669900471262
22109345933847358924230951718379883743256346548760417031607741875424271006526981819059127169069544663383612
03745255515267088218383996330164203403732365333352120338272021319718003599422045899487646001835027038563411
78077687451616229338340631455056219106004731529642292049578901r342999030
```
[Answer]
# [Actually](https://github.com/Mego/Seriously), ~~46~~ 45 bytes
I've been meaning to do a Seriously/Actually answer for months and now I can. Golfing suggestions welcome. [Try it online!](https://tio.run/nexus/actually#@2/9aOq00qJHPQuAjLkQhrVB3aPG/RqPps5@NK1D69HUORqlQL7Wo56FvucWA0VLs0HMR1PWZDpYn2@w1nw0syFGyyH70bQ9//@bGQAA "Actually – TIO Nexus")
**Edit:** In February of 2017, there was an update to Actually that changed which function literals are which. Enjoy.
This uses the explicit definition of the Bernoulli numbers on Wikipedia.
```
;╖ur⌠;╝ur⌠;;0~ⁿ(╛█*╜(uⁿ*⌡MΣ╛uk⌡M┬i@;π;)♀\*@k▼
```
**Ungolfing**
```
;╖ Duplicate and save m in register 0.
ur Range [0..m]
⌠ Start first for loop
;╝ Duplicate and save k in register 1.
ur Range [0..k]
⌠ Start second for loop (as string).
;; Duplicate v twice.
0~ⁿ Push -1, and pow() to get (-1)**v.
(╛█ Rotate a duplicate v to TOS, push k, and binom(k, v).
* Multiply (-1)**v by binom(k, v).
╜(uⁿ Push m, rotate last duplicate v to TOS, increment, and pow() to get (v+1)**m.
* (-1)**v * binom(k, v) * (v+1)**m
⌡ End second for loop (string turned to function).
MΣ Map over range [0..v] and sum
╛u Push k and increment (the denominator)
(Note: second for loop does numerators only as denominator only depends on k)
k Push fraction in list form [numerator, denominator]
⌡ End first for loop
M Map over range [0..k]
┬i@ Transpose all of the fractions, flatten and swap.
Stack: [denominators] [numerators]
;π Duplicate and take product of denominators.
;) Duplicate product and move to bottom of stack.
Stack: product [denominators] [numerators] product
♀\ For all items in denominators, integer divide product by item.
Return a list of these scaled-up denominators.
* Dot product of numerators and the scaled-up denominators as new numerator.
(In effect, getting the fractions to the same denominator and summing them)
@k Swap new numerator and product (new denominator) and turn into a list (fraction).
▼ Divide fraction by gcd(numerator, denominator) (Simplify fraction).
```
[Answer]
# Haskell, 95 bytes
```
import Data.Ratio
p=product
b m=sum[p[k-v+1..k]*(v+1)^m%(p[-v..0-1]*(k+1))|k<-[0..m],v<-[0..k]]
```
This implements the explicit definition of Bernoulli numbers outlined on the [Wikipedia page](http://en.wikipedia.org/wiki/Bernoulli_numbers).
[Answer]
## Perl 6, 83 bytes
```
my &B={$^m??1-[+] (^$m).map: {combinations($m,$_)*B($_)/($m+1-$_)}!!1};say B slurp;
```
A faster, 114-byte solution:
```
my @b=1;for 1..+slurp() {@b.push: 1-[+] (^$^m).map: {([*] $m+1-$_..$m)*@b[$_]/($m+1-$_)/([*] 1..$_)}};say @b[*-1];
```
[Answer]
## Javascript, 168 bytes
```
function h(b,a){return a?h(a,b%a):b}for(var c=[],a=[],e=0,b,d,f,g;e<=k;)for(c[b=d=e]=1,a[e]=++e;d;)f=c[--d]*a[b]-(c[b]*=g=a[d]),r=h(f*=b,g=a[b]*=g),c[d]=f/r,a[--b]=g/r;
```
Set the 'k' variable to the Bernoulli number you want, and the result is c[0] over a[0]. (numerator & denominator)
## Sample Usage
```
k = 2;
console.log(c[0] + "/" + a[0]);
```
Not as small as the others, but the only one I've written that comes close. See <https://marquisdegeek.com/code_ada99> for my other (non-golf) attempts.
[Answer]
# Axiom, 57 bytes
```
g(n)==factorial(n)*coefficient(taylor(t*%e^t/(%e^t-1)),n)
```
code for test and results
```
(18) -> [[i, g(i)] for i in 0..29]
(18)
1 1 1 1 1
[[0,1], [1,-], [2,-], [3,0], [4,- --], [5,0], [6,--], [7,0], [8,- --],
2 6 30 42 30
5 691 7 3617
[9,0], [10,--], [11,0], [12,- ----], [13,0], [14,-], [15,0], [16,- ----],
66 2730 6 510
43867 174611 854513
[17,0], [18,-----], [19,0], [20,- ------], [21,0], [22,------], [23,0],
798 330 138
236364091 8553103 23749461029
[24,- ---------], [25,0], [26,-------], [27,0], [28,- -----------], [29,0]]
2730 6 870
Type: List List Expression Integer
(19) -> g 60
1215233140483755572040304994079820246041491
(19) - -------------------------------------------
56786730
Type: Expression Integer
```
one has to note that the function is not the one someone wrote above
but `t*%e^t/(%e^t-1))` with %e Euler costant
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 22 bytes
```
L?b-1sm*.cbdcyd-btdUb1
```
[Try it online!](https://tio.run/##K6gsyfj/38c@SdewOFdLLzkpJbkyRTepJCU0yfB/ZeB/MwMA "Pyth – Try It Online")
Defines a function that is called as `y<number>`, e.g. `yQ`.
```
L # y=lambda b:
?b 1 # ... if b else 1
-1 # 1 -
s # sum(
m Ub # map(lambda d: ... , range(b))
*.cbd # combinations(b, d) *
cyd # y(d) / (float division)
-btd # b - (d - 1)
```
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.