text
stringlengths 180
608k
|
---|
[Question]
[
## Background
[Fractran](http://en.wikipedia.org/wiki/FRACTRAN) is an esoteric Turing-complete programming language invented by John Conway. A Fractran program consists of an ordered list of fractions. The program starts by taking a single integer as input. Each iteration of the program, it searches the list for the first fraction such that multiplying the number by that fraction produces another integer. It then repeats this process with the new number, starting back at the beginning of the list. When there is no fraction on the list that can be multiplied with the number, the program terminates and gives the number as the output.
The reason that Fractran is Turing-complete is because it simulates a register machine. The number's prime factorization stores the contents of the registers, while the division and multiplication is a way to conditionally add and subtract from the registers. I would recommend reading the Wikipedia article (linked to above).
## The Challenge
Your task is to write the shortest program possible that can take a valid Fractran program from STDIN as its only input and generates a valid BF program to STDOUT that simulates the Fractran program. There are two ways that you could simulate a Fractran program with BF.
*NOTE: Your answer is not a BF program. Your answer is the code that generates the BF program from any given Fractran program. The goal is to get the BF program to be the equivalent of the Fractran program. (technically you could do the competition in BF, but it would be hard)*
**Option 1**
Your program should output a BF program that does the following:
* Takes exactly 1 number from STDIN in the form of the corresponding ASCII character (due to the way that BF input works), which is the input to the Fractran program.
* Prints exactly 1 number to STDOUT in the form of the corresponding ASCII character, which is the output to from the Fractran program.
This option is meant to represent the exact input and output from a Fractran virtual machine.
**Option 2**
The BF code that your program produces should do the following:
* Take input by having the prime factorization of the number already encoded in memory (prior to running the program). If the input is 28 (2\*2\*7), then there will be a value of 2 in the second cell and a value of 1 in the seventh cell (the pointer starts on cell 0). All other cells will be zero.
* Give output by having the prime factorization of the output encoded in memory when the program terminates. If the output is 10, then there must be a value of 1 in each of cells 2 and 5. All other prime-numbered cells must have a value of zero. The content of other cells do not matter.
This option represents the computing model behind the Fractran language.
## Rules and Requirements
1. Input (top your program) will be a list of fractions on STDIN. There will be one fraction per line with a comma between the numerator and denominator. An empty line represents the end of input. The fractions will always be reduced to lowest terms.
2. Your program's output should be a single-line, valid BF program to STDOUT. This program should be able to simulate that particular Fractran program according to one of the two options. For any input, the BF program generated should be able to produce the same output as the Fractran program.
3. You must state which option you chose.
4. You can choose the bounds on the BF memory and tape, and whether they are wrapping
5. CODE GOLF. Also, the size of the outputted BF programs does not matter, only the size of the program that is doing the converting.
6. Programs should only consist of printable ASCII
If I am ambiguous anywhere, do not hesitate to ask. This is a very complicated challenge to describe.
In addition, please post your program's generated BF code for the following input, as to provide an easy way to check if your program is working:
```
33,20
5,11
13,10
1,5
2,3
10,7
7,2
```
This program calculates the number of 1s in the binary expansion of a number. However, the input and output are formatted strangely (as with all Fractran programs). Input is of the form 2^A, while output is of the form 13^B.
[Answer]
## Python, 182 chars
Option 1, standard byte cells. There are only 255 possible inputs (0 as an input doesn't really make sense), so I just run a Fractran interpreter 255 times in Python and generate a simple table lookup Brainfuck program encoding the results.
```
import sys
I=map(eval,sys.stdin)
P='+>,'
Q=''
for i in range(1,256):
while i:j=i;i=([i*x/y for x,y in I if i%y==0]+[0])[0]
r=j&255;P+='-[';Q=']<[-'+'+'*r+'.'+'-'*r+']>'+Q
print P+Q
```
Output for the example input (`___` = 246 more nested conditions, I can't paste the whole result as it is too large):
```
+>,-[-[-[-[-[-[-[-[___]<[-+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.-------------------------------------------------------------------------------------------------------------------------------------------------------------------------]>]<[-+++++++++++++.-------------]>]<[-+++++++++++++.-------------]>]<[-+.-]>]<[-+++++++++++++.-------------]>]<[-+++++++++++++.-------------]>]<[-+++++++++++++.-------------]>]<[-+.-]>
```
[Answer]
**Python, 420 chars**
This uses a sort of blend of options 1 and 2: It assumes that brainfuck is implemented with big integers (I use a Sage implementation). Input a fractran program, for example, `33/20,5/11,13/10,1/5,2/3,10/7,7/2`. Then, pre-load a number, for example, `2^5`, at the cursor. Then, run the output of this python script. Wait 44 seconds. The result, `13^2` sits where the cursor started. I didn't wait for the answer for `2^7`.
```
s="[->>>+<<<]+["
for l in raw_input().split(','):
a,b=map(int,l.split('/'))
s+="[->+>+<<]>[-<+>]>[->[->+>>+<<<]>[-<+>]>>["+"[->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]<"*(b-1)+"[->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<<->>>]<<<++>>>]<]<<[->+>+<<]>>[-<<+>>]<[[-]<->]<[<[-]>[-<+>]<"+"[->+>+<<]>[-<+>]<"*a+"[-]>>[-<<+>>]<<<<<->>>>]<<]<<"
print s+">+<[->-<]>[-<+>]<]>>>[-<<<+>>>]"
```
This is my first brainfuck script. It can certainly be golfed further, but I've got other things to do until later tonight.
edit: rather than golf this further, I'm working on a solution for option 2. also, here's the output for the requested program:
```
[->>>+<<<]+[[->+>+<<]>[-<+>]>[->[->+>>+<<<]>[-<+>]>>[ [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<<->>>]<<<++>>>]<]<<[->+>+<<]>>[-<<+>>]<[[-]<->]<[<[-]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]<[-]>>[-<<+>>]<<<<<->>>>]<<]<<[->+>+<<]>[-<+>]>[->[->+>>+<<<]>[-<+>]>>[ [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<<->>>]<<<++>>>]<]<<[->+>+<<]>>[-<<+>>]<[[-]<->]<[<[-]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]<[-]>>[-<<+>>]<<<<<->>>>]<<]<<[->+>+<<]>[-<+>]>[->[->+>>+<<<]>[-<+>]>>[ [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<<->>>]<<<++>>>]<]<<[->+>+<<]>>[-<<+>>]<[[-]<->]<[<[-]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]<[-]>>[-<<+>>]<<<<<->>>>]<<]<<[->+>+<<]>[-<+>]>[->[->+>>+<<<]>[-<+>]>>[ [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<<->>>]<<<++>>>]<]<<[->+>+<<]>>[-<<+>>]<[[-]<->]<[<[-]>[-<+>]< [->+>+<<]>[-<+>]<[-]>>[-<<+>>]<<<<<->>>>]<<]<<[->+>+<<]>[-<+>]>[->[->+>>+<<<]>[-<+>]>>[ [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<<->>>]<<<++>>>]<]<<[->+>+<<]>>[-<<+>>]<[[-]<->]<[<[-]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]<[-]>>[-<<+>>]<<<<<->>>>]<<]<<[->+>+<<]>[-<+>]>[->[->+>>+<<<]>[-<+>]>>[ [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<<->>>]<<<++>>>]<]<<[->+>+<<]>>[-<<+>>]<[[-]<->]<[<[-]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]<[-]>>[-<<+>>]<<<<<->>>>]<<]<<[->+>+<<]>[-<+>]>[->[->+>>+<<<]>[-<+>]>>[ [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<->>]<<+[<[-]>-]>>]< [->+>+<<]>>[-<<+>>]<[[-]<-[->+>+<<]>>[-<<+>>]<<>[[-]<<<->>>]<<<++>>>]<]<<[->+>+<<]>>[-<<+>>]<[[-]<->]<[<[-]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]< [->+>+<<]>[-<+>]<[-]>>[-<<+>>]<<<<<->>>>]<<]<<>+<[->-<]>[-<+>]<]>>>[-<<<+>>>]
```
[Answer]
## Perl, 326 characters
I am going to answer my own question hopefully to stimulate more answers. I am of course not eligible to win. This is option 2 with unbounded memory and cells, although it works on wrapping cells. Each fraction is converted into a single block of code. The newlines are for readability.
```
L:{$A=<>;
if($/eq$A){last L}
($B,$C)=eval$A;
$D=$E=$F=$G=$H=2;
while($C>1){
if($C%$H==0){
$C/=$H;
$R=">"x$H;
$L="<"x$H;
$D.=$R.'[-'.$L;
$E.=$R.'-'.$L;
if($H>2){$R.="+[->+<]]>[-<+>]<"}
else{$R.="+[-<+>]]<[->+<]>"}
$G=$R.$L.$G;
$H--}$H++}
$H=2;while($B>1){
if($B%$H==0){
$B/=$H;
$F.=">"x$H.'+'.'<'x$H;
$H--}$H++}
$I="+[-$I$D$E+$F$G]";
redo L}print$I
```
Here is the example output. This takes advantage of the fact that other characters are ignored as comments. This also appears to be a very short output compared to the other entries, although output size doesn't technically matter.
```
+[-+[-+[-+[-+[-+[-+[-2>>[-<<>>[-<<>>>>>[-<<<<<2>>-<<>>-<<>>>>>-<<<<<+2>>>+<<<>>>>>>>>>>>+<<<<<<<<<<<>>>>>+[->+<]]>[-<+>]<<<<<<>>+[-<+>]]<[->+<]><<>>+[-<+>]]<[->+<]><<2]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]
**Sage, 431 chars**
This is a completely new solution. I figured out some better ways of doing things in brainfuck, and this properly implements Option 2. Newlines added for clarity. This can probably be golfed further, but it involves rewriting the BF to have a lower loop depth.
```
exec"f=factor;
J=''.join;
Q=L(a,b):Lz:a*z+b*-z;M=Q('<>');
C=Lj,k:(Ll:'[-%s+%s+%s]%s[-%s+%s]%s'%tuple(map(M,[-j,-k,l,-l,l,-l,k])))(j+k);
print '>+[>>>+'+J(map(L(n,m):reduce(Lr,(p,e):'[-%s%s%s[[-]<<+>>]%s<<%s]'%(M(4-p),C(6-p,2),'[-'*(e-1),']'*(e-1),r),f(m),'[-<<<->>>%s]'%J(map(L(p,e):M(4-p)+Q('+-')(e)+M(p-4),f(n/m))))+'<<<'+C(3,2),[map(QQ,x.split('/'))for x in raw_input().split(',')]))+'<<<<+>[-<->]<[->+<]>]'".replace('L','lambda ')
```
Sample output:
Given the input `33/20,5/11,13/10,1/5,2/3,10/7,7/2`
```
>+[>>>+[->[->+>>+<<<]>>>[-<<<+>>>]<<[[-]<<+>>]<<[-<<[->>>>+>>+<<<<<<]>>>>>>[-<<<<<<+>>>>>>]<<[-[[-]<<+>>]]<<[-<<<->>><<-->><+>>-<>>>>>>>+<<<<<<<]]]<<<[->>>+>>+<<<<<]>>>>>[-<<<<<+>>>>>]<<[->>>>>>>[-<<<<<+>>+>>>]<<<[->>>+<<<]<<[[-]<<+>>]<<[-<<<->>>>+<>>>>>>>-<<<<<<<]]<<<[->>>+>>+<<<<<]>>>>>[-<<<<<+>>>>>]<<[->[->+>>+<<<]>>>[-<<<+>>>]<<[[-]<<+>>]<<[-<<[->>>>+>>+<<<<<<]>>>>>>[-<<<<<<+>>>>>>]<<[[-]<<+>>]<<[-<<<->>><<->>>-<>>>>>>>>>+<<<<<<<<<]]]<<<[->>>+>>+<<<<<]>>>>>[-<<<<<+>>>>>]<<[->[->+>>+<<<]>>>[-<<<+>>>]<<[[-]<<+>>]<<[-<<<->>>>-<]]<<<[->>>+>>+<<<<<]>>>>>[-<<<<<+>>>>>]<<[-<[->>>+>>+<<<<<]>>>>>[-<<<<<+>>>>>]<<[[-]<<+>>]<<[-<<<->>><<+>><->]]<<<[->>>+>>+<<<<<]>>>>>[-<<<<<+>>>>>]<<[->>>[-<+>>+<]>[-<+>]<<[[-]<<+>>]<<[-<<<->>><<+>>>+<>>>-<<<]]<<<[->>>+>>+<<<<<]>>>>>[-<<<<<+>>>>>]<<[-<<[->>>>+>>+<<<<<<]>>>>>>[-<<<<<<+>>>>>>]<<[[-]<<+>>]<<[-<<<->>><<->>>>>+<<<]]<<<[->>>+>>+<<<<<]>>>>>[-<<<<<+>>>>>]<<<<<<+>[-<->]<[->+<]>]
```
] |
[Question]
[
[Brainfuck](https://esolangs.org/wiki/brainfuck) is an esoteric programming language that is Turing Complete, meaning you can't tell whether a given program will halt without running it. It's cell-based and has an infinite tape of cells, values containing an unsigned integer from 0 to 255, but if you give it arbitrary-size cells, just three is enough to make it Turing Complete.
But one cell isn't in either case.
The bit of brainfuck that we'll be using contains these four operations:
* `+`: Increment the current cell
* `-`: Decrement the current cell
* `[`: Loop while the current cell is nonzero
* `]`: End a loop
You should use a single unsigned integer from 0 to 255 as the cell, wrapping round when you decrement zero or increment 255.
You may return any two distinct, consistent values to say whether it halts or not. The program will be a valid brainfuck program (balanced brackets) and only contain these four characters. You may *not* output by halting/not halting.
## Testcases
If you want to look at these in more depth, [here](https://fatiherikli.github.io/brainfuck-visualizer/)'s a good visualizer.
### Falsy (doesn't halt)
```
+[]
+[++]
+[++[+]--]
+[----]
+[-]-[+[-]-]
+[[-]-[+[-]-+[++]-[+]]-[++][-]]
++[-]+[--]-
```
### Truthy (halts)
```
[+]
+
+[+]
++[+++]
+++--[++-][+][+]
+[+]-[+++]-
```
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 36 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
0ì„+-„><‡'[„₄ƒ:']"D₁Ö#N₄Qi0q}}":1«.V
```
Outputs `1` if it halts; `0` if it doesn't halt.
[Try it online](https://tio.run/##yy9OTMpM/f/f4PCaRw3ztHWBhJ3No4aF6tFA1qOmlmOTrNRjlVweNTUenqbsBxQIzDQorK1VsjI8tFov7P9/7eho3VjdaG0QqR2trQ1ix4II7VigUCwA) or [verify all test cases](https://tio.run/##XU47CsJAEO33FEMULMbx00owjVoqNjbLFolZSECMP7ASVMQDWFgK1noKAx5kLxJ3NoJg8@bNm3lvJgrXSTENN9CFaRbrRrYOo1SD70N/NBCBB@Z8AS8oWvnT7G9IFrq@2d9r0jJzPL0vnZryeuZ4yK@VoRXGaau@3O28Tvv1aEyKuuAcsU3SmYaVDmNI5yLOBEAzW2ya5blv@fvAh6rbnesCpRIoEUuUqIiYEn2rIumQm1/nHJYrBlRWsnOesFORkJzHiU5GF49IvEzKqrK859wWxQc).
**Explanation:**
```
0ì # Prepend a "0" in front of the (implicit) input-string
„+-„><‡ # Replace all "+" with ">" and all "-" with "<"
'[„₄ƒ: '# Replace all "[" with "₄ƒ"
']"D₁Ö#N₄Qi0q}}": '# Replace all "]" with "D₁Ö#N₄Qi0q}}"
1« # Append a trailing "1" at the end
.V # Execute it as 05AB1E code
# (after which the result is output implicitly)
```
[Verify all test cases without `.V` to see what 05AB1E programs the inputs are transformed into.](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3lf4PDax41zNPWBRJ2No8aFqpHA1mPmlqOTbJSj1VyedTUeHiash9QIDDToLC2VsnK8NDq/zr/taNjubSjtbUhZLR2rK4uiKmrC6VjdaPBJIiD4IF1ANmxIEI7FigElAfJgHTG6nJFg8wDmQgW1gYbr62tC1KsGwsUjYbYB9YNJAE)
```
0ì # We start the cell at 0
„+-„><‡ # `>` increases the top of the stack by 1
# `<` decreases the top of the stack by 1
'[„₄ƒ: '# `₄ƒ` loop `N` in the range [0,1000]
']"D₁Ö#N₄Qi0q}}": '#
D # Duplicate the top
₁Ö # Pop and check if it's divisible by 256
# # If this is truthy: stop the loop
N # Else: push the loop index `N`
₄Qi # If it's equal to 1000:
0 # Push a 0
q # And stop the entire program
# (after which this 0 is output implicitly as result)
} # Close the if-statement
} # Close the loop
1« # Push a 1
# (which is output implicitly as result if we didn't halt)
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 116 bytes
```
s=>eval(`try{${s.replace(/./g,(c,i)=>(c=='['?'for(;v;){':c>{}?'}':`v=v${c}1&255`)+`;s[t++>>9].x;`)}}catch{1}`,v=t=0)
```
[Try it online!](https://tio.run/##dVBNawMhEL33V/QQojLrpink0Ijmh4igWDdJWWJYRVLE377d3RZ62HgZhnnzeB9fJplgh@s90pv/dGP3ysfAhUumxzoO33mTQzu4e2@sw7t2d26wba6EC2w5RxKdUOcHzBIjGR2tyOWECjrqxNMm27Lfvh8OmoBmQUYAIT5U@2CalGJNtJe8L7pJPPI3Mlp/C753be/PuMMIpEKEsJfVGaAKSFCUVlBK65CicpkV/P9hUZ92NQ9Q0@k5ZX6eJRVdwWg2gtYcWYlVyVrThVo9AHT2TNXEldUKl1zwxPZfw7/E8Qc "JavaScript (Node.js) – Try It Online")
---
# [JavaScript (Node.js)](https://nodejs.org), 135 bytes
```
s=>(e=(p,v,b=0)=>(s[p]=='['?b|!v?++b:b:s[p]>'['?b|v?--b:b:b)?e(b>0?p+1:p-1,v,b):s[p]?e[m=[p,v]]||e(p+(e[m]=1),v+(s[p]+1|0)&255):0)(0,0)
```
[Try it online!](https://tio.run/##dU@9bsMgEN7zFM0SOJ2vwpWyuMI8CLohOLhK5MSojpj87g44lTo4LCf4/u676ymepu73Eh50H89@6T/0MulWei1DFSunFaTfZANrLawwbt5Hg@ga12SwfWHREGXIgfHStcoErJtAdU6AVWi8vWmbIpnn2cuAMgGsa6girvFYzwoOX8cjNAqkqhQs3XifxsF/DuOP7KVAywLge7eBEYuERSYqsERlismus8D/C9bt6c15ICdoaxF5k9jm2ELvwjHvxblAiULKpYiT98@@PAE "JavaScript (Node.js) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 117 bytes
```
ToExpression[a=b=0;StringReplace[#,{"["->"Do[If[c∣a,Break[]];","]"->"i<c||(b=1),{i,c=256}];",c_:>"a"<>c<>"=1;"}]]b&
```
[Try it online!](https://tio.run/##RU3BSsQwEL33K8IUFiUJuoIebBNE9OBNXG/DIGlINbi7Ld0ehN29@x/@mT9SM6mwlzcz7817b@PGj7BxY/RuaoWZXrvHr34Iu13stuhMYy6r1TjE7ftL6NfOByzVHhC0hYcOn1r0v98/Tt0PwX0iUQUKiMVY@8PhrDHLc7WPypur65sjq/7t1oKD2vragllWcCRqFtNzahixFNqKFksisRAXd2IuXvXrOGIBEqmQKOWMKElrXrX@n6QxIx@nKzvSTgySEpV0VthJukDO48RMyxwvpeZnTYnFuS@7EwJNfw "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 245 bytes
```
p=input()
m={}
s=[]
for i,c in enumerate(p):
if"["==c:s+=[i]
if"]"==c:m[s[-1]]=i;m[i]=s.pop()
a=n=0
while a<len(p):
if(a,n)in s:print();break
s+=[(a,n)];q=p[a]
if"["==q and n<1or"]"==q and n:a=m[a]
if"+"==q:n+=1
if"-"==q:n-=1
a+=1;n%=256
```
[Try it online!](https://tio.run/##PY7BagMxDETP8VeYQGAXx6Hb0h680ZcIHdzUIaax1rE3lFLy7RvbbXoRmjdiRvF7Pk38siwRPMfr3PUiwM9NZEASxylJvz1Iz9LxNbhkZ9fF3oiVP65xDXAwWQF6aoAaCJhRD0Tgx1AcyLs4xZJqgeFJfJ382Um7Pzt@BHV2y31pyCYmz@WB8T05@ylWNbqZNF4goqX/2ou0/CF5P0yptf5pYyE8zlTFhhUMTepfqau0BY68gefXt2VRiJo0qjoVKlV3qkNRQXQH "Python 3 – Try It Online")
so idrk how the fancy string substitution solutions are working so here's my terrible attempt to just run the code instead
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~90~~ 88 bytes
```
≔⁰η≔⁰ζ≔⟦⟧εW∧‹ηLθ¬№υ⟦ηζ⟧«⊞υ⟦ηζ⟧≡§θη[¿ζ⊞εηW›№…θ⊕η[⁺№…θ⊕η]Lε≦⊕η]≔⊖⊟εη≔﹪⁺I⁺§θη1ζ²⁵⁶ζ≦⊕η»⁼ηLθ
```
[Try it online!](https://tio.run/##jZFBa8MgFMfP5lNITkoT2AbboTmVbIxCO3IPOYh5rQGnTdR1y@hnz0wiS7fDmPDEp3//7/eUC9ZxzeQwbIxpjorcJFjQLFqyfsnKKsHg07NoJGCyUTXZgTFEJHgH6mgFaSlN8Iu2JNdOWeISXPrDvqJ@4M8IFc6Iq90sQubcWC68md2qGt5JO9aftJwZwHEZryOEmgMmPcXTdZgJEQLpBYHluQNmoQt18w8uIRf6NNptFe/gFZSFmoiRz3v6uZDO/E9ejfLQIEyd7NkpPMmVOmDN2FW8xkHyCIth4WvAaDpJazgwJ@23cq9rJzWZyZix8@rHy3ic23g06H3c3T/Q@YPQJUJ/QF2iomt8o0@tY/LXf9FsGFarMq18pFU6pG/yCw "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` if the program halts, nothing if not. Explanation:
```
≔⁰η
```
Start at the beginning of the code.
```
≔⁰ζ
```
Start with zero in the cell.
```
≔⟦⟧ε
```
Start with no unmatched `[`s.
```
W∧‹ηLθ¬№υ⟦ηζ⟧«
```
Repeat until either the end of the program is reached or the current state has been seen previously (i.e. an infinite loop has been detected).
```
⊞υ⟦ηζ⟧
```
Record the current state.
```
≡§θη
```
Switch on the next program character.
```
[¿ζ
```
For `[`, if the cell is non-zero, then...
```
⊞εη
```
... save the current position, so it can be quickly restored when the matching `]` is reached, otherwise...
```
W›№…θ⊕η[⁺№…θ⊕η]Lε≦⊕η
```
... advance the current position to the matching `]`.
```
]≔⊖⊟εη
```
For `]`, jump back to the matching `[`, which will then test the cell value.
```
≔﹪⁺I⁺§θη1ζ²⁵⁶ζ
```
Otherwise, adjust the cell value modulo 256 as necessary.
```
≦⊕η
```
Advance to the next character of the program. (In the case of `[` jumping forward to its matching `]`, this skips past the `]`. In the case of `]` jumping back to its matching `[`, this increment has been adjusted for, so that the `[` becomes the next code to execute.)
```
»⁼ηLθ
```
Output whether the end of the program was reached.
] |
[Question]
[
Related: [Music: what's in this chord?](https://codegolf.stackexchange.com/q/24816), [Notes to Tablature](https://codegolf.stackexchange.com/q/39778), [Generating guitar tabs?](https://codegolf.stackexchange.com/q/2975), [Translate number pairs to guitar notes](https://codegolf.stackexchange.com/q/94629)
Given a guitar fingering, output the chord it represents. You can use standard input and output, or write a function that returns a string.
The input fingerings will be classifiable as one of the following chords, to be expressed as follows (if the root note were C):
* major triad: `C`
* minor triad: `Cm`
* (dominant) seventh: `C7`
* minor seventh: `Cm7`
The chord might be inverted, so you can't rely on the lowest note being the root. Nor can you rely on this being an easy or common fingering in the real world. More generally, your program's output must ignore the octaves of the pitches, and treat all pitches that correspond to the same musical note (i.e., `A`) as equal.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
# Input format
The input is a series of 6 values that indicate, for each string of a 6-string guitar in [standard tuning](https://en.wikipedia.org/wiki/Standard_tuning) (E A D G B E), which fret that string will be played at. It could also indicate that the string is not played at all. The "zeroth" fret is also known as the open position, and fret numbers count up from there. Assume the guitar has 21 fret positions, such that the highest fret position is number 20.
For example, the input `X 3 2 0 1 0` means placing ones fingers at the following positions at the top of the guitar's neck:
```
(6th) |---|---|---|---|---
|-X-|---|---|---|---
|---|---|---|---|---
|---|-X-|---|---|---
|---|---|-X-|---|---
(1st) |---|---|---|---|---
```
and strumming the 2nd through the 6th strings. It corresponds to this [ASCII tab](https://en.wikipedia.org/wiki/ASCII_tab):
```
e |-0-|
B |-1-|
G |-0-|
D |-2-|
A |-3-|
E |---|
```
You have some flexibility in choosing the kind of input you want: each fret position can be expressed as a string, or a number. Guitar strings that are not played are commonly indicated with an `X`, but you can choose a different sentinel value if that makes it easier for you (such as `-1` if you're using numbers). The series of 6 fret positions can be input as any list, array, or sequence type, a single space-separated string, or as standard input—once again, your choice.
You can rely on the input corresponding to one of the 4 chord types mentioned above.
Please explain in your post what form of input your solution takes.
# Output format
You must either return or print to standard output a string describing the chord the fingering is for. This string is composed of two parts concatenated together. Capitalization matters. Trailing whitespace is allowed.
The first part indicates the [root note](https://en.wikipedia.org/wiki/Root_(chord)), one of `A`, `A#`/`Bb`, `B`, `C`, `C#`/`Db`, `D`, `D#`/`Eb`, `E`, `F`, `F#`/`Gb`, `G`, or `G#`/`Ab`. (I'm using `#` instead of `♯`, and `b` instead of `♭`, to avoid requiring Unicode.) Root notes that can be expressed without a sharp or flat must be expressed without them (never output `B#`, `Fb`, or `Dbb`); those that cannot must be expressed with a single sharp or flat symbol (i.e. either `C#` or `Db`, but never `B##`). In other words, you must minimize the number of accidentals (sharps or flats) in the note's name.
The second part indicates the type of chord, either empty for a major triad, `m` for a minor triad, `7` for the dominant seventh, or `m7` for the minor seventh. So a G major is output simply as `G`, while a D♯ minor seventh could be output as either `D#m7` or `Ebm7`. More examples can be found in the test cases at the end.
# Theory & hints
## Musical notes
The chromatic scale has 12 pitches per octave. When tuned to equal temperament, each of these pitches is equally distant from its neighbors1. Pitches that are 12 [semitones](https://en.wikipedia.org/wiki/Semitone) apart (an octave) are considered to be the same musical note. This means we can treat notes like integers modulo 12, from 0 to 11. Seven of these are given letter names2 from A to G. This isn't enough to name all 12 pitches, but adding accidentals fixes that: adding a ♯ (sharp) to a note makes it one semitone higher, and adding a ♭ (flat) makes it one semitone lower.
## Chords
A chord is 2 or more notes played together. The type of chord depends on the relationships between the notes, which can be determined by the distances between them. A chord has a root note, as mentioned earlier. We'll treat the root note as 0 in these examples, but this is arbitrary, and all that matters in this challenge is the distance between notes in modulo arithmetic. There will always be one unique chord type for the answer, either a triad or a [seventh chord](https://en.wikipedia.org/wiki/Seventh_chord). The root note will not always be the lowest-frequency pitch; choose the root note such that you can describe the chord as one of the four following chord types:
* A **major triad** is a chord with the notes `0 4 7`.
* A **minor triad** is a chord with the notes `0 3 7`.
* A **dominant (or major/minor) seventh** chord has the notes `0 4 7 10`.
* A **minor (or minor/minor) seventh** chord has the notes `0 3 7 10`.3
## Guitar tuning
Standard tuning on a 6-string guitar starts with E on the lowest string, and then hits notes at intervals of 5, 5, 5, 4, then 5 semitones going up the strings. Taking the lowest E as 0, this means strumming all the strings of the guitar gives you pitches numbered `0 5 10 15 19 24`, which modulo 12 is equivalent to `0 5 10 3 7 0`, or the notes `E A D G B E`.
# Worked examples
If your input is `0 2 2 0 0 0`, this corresponds to the notes `E B E G B E`, so just E, B, and G. These form the chord `Em`, which can be seen by numbering them with the root as E, giving us `0 3 7`. (The result would be the same for `X 2 X 0 X 0`, or `12 14 14 12 12 12`.)
If your input is `4 4 6 4 6 4`, numbering these with a root of C♯ gives `7 0 7 10 4 7`, or `0 4 7 10`, so the answer is `C#7` (or `Db7`). If it was instead `4 4 6 4 5 4`, the numbering would give `7 0 7 10 3 7`, or `0 3 7 10`, which is `C#m7` (or `Dbm7`).
# Test cases
```
X 3 2 0 1 0 ---> C
0 2 2 0 0 0 ---> Em
X 2 X 0 X 0 ---> Em
4 4 6 4 6 4 ---> C#7 (or Db7)
4 4 6 4 5 4 ---> C#m7 (or Dbm7)
0 2 2 1 0 0 ---> E
0 0 2 2 2 0 ---> A
X X 4 3 2 2 ---> F# (or Gb)
3 2 0 0 0 1 ---> G7
X X 0 2 1 1 ---> Dm7
3 3 5 5 5 3 ---> C
4 6 6 5 4 4 ---> G# (or Ab)
2 2 4 4 4 5 ---> B7
0 7 5 5 5 5 ---> Am7
7 6 4 4 X X ---> B
8 6 1 X 1 3 ---> Cm
8 8 10 10 9 8 --> Fm
0 19 5 16 8 7 --> Em
6 20 0 3 11 6 --> A# (or Bb)
X 14 9 1 16 X --> G#m (or Abm)
12 14 14 12 12 12 --> Em
15 14 12 12 12 15 --> G
20 X 20 20 20 20 --> Cm7
X 13 18 10 11 10 --> A#7 (or Bb7)
```
---
1by the logarithms of their frequencies
2or, in [solfège](https://en.wikipedia.org/wiki/Solf%C3%A8ge), names like *do, re, mi*. In this challenge, use the letter names.
3This could also be called a major sixth chord, with a different choice of root note. In this challenge, call it by its minor seventh name.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~115~~ 114 bytes
```
[OAXICO]+tZN~)Y@!"@t1)XH- 12\XzXJK7hm?O.]JI7hm?'m'.]J[KCX]m?'7'.]J[ICX]m?'m7'.]]'FF#GG#AA#BCC#DD#E'l2741B~QY{HX)wh
```
Input format is `[N 3 2 0 1 0]`, where `N` indicates unused string.
The output string always uses `#`, not `b`.
[Try it online!](https://tio.run/nexus/matl#@x/t7xjh6ewfq10S5VenGemgqORQYqgZ4aGrYGgUE1EV4eVtnpFr768X6@UJYqjnqgOZ0d7OEbFAjjmY4wnh5IJ4sepubsru7sqOjspOzs7KLi7Kruo5RuYmhk51gZHVHhGa5Rn//0f7KRgrGCkYKBgqGMQCAA "MATL – TIO Nexus") Or verify all test cases, in two parts to avoid the online compiler timing out:
* [Test cases 1‒12](https://tio.run/nexus/matl#TY1LC8IwEITv/orVHEoRJUlre7Qv@xJSBA@pMeCxB3srCAr963WTVpBlYT52Z@YxqSaWVdro7XATo9tG6000MFeWO2D8Lt@yPoddf2z2uq6McHoHpTqnUiOEFqoZekPayXNSFCSOSZKmJMvIyXny0GfJeGk/pXRf3ZRdJyXAAw4UGFC9UhS1IWpJoBaohSUffAjm/aODpdnHFp/x8znJpgj8My0cyfvlA1tu1DqZvXmYZ8azDQEO5mPDFw);
* [Test cases 13‒24](https://tio.run/nexus/matl#TY5PC8IwDMXvfopoD2OI0tRtnSedm382YUPwUJ0Fjx7cTRAU/OozaREk75Dfa/LSa982mSnzxo4f5/oTnpbD0fKBodlNANXFvEy117du0UxtVXITdAG17T43lkA7KD10TDbYbMR2K7JMrPJcFIVYB3elI1x9Dqf3zoTPW18c@1aBgshVbAetBA2xLyINiXupoSZKiZB6hJmjFFCy5pC6TZzTGibka@IElAQJM0CEhJj2IhpFnuA0VGywlBd78b8ByH@glJqjfvJRFOvPU560Xw).
### Explanation
```
[OAXICO] % Push [0 5 10 3 7 0]. This represents the pitch of each open
% string relative to the lowest string, modulo 12
+ % Add to implicit input. May contain NaN's, for unused strings
tZN~) % Remove NaN's
Y@! % Matrix of all permutations, each in a column
" % For each column
@ % Push current column
t1) % Duplicate and get first entry
XH % Copy into clipboard H
- 12\ % Subtract. This amounts to considering that the first note
% of the current permutation is the root, and computing
% all intervals with respect to that
12\ % Modulo 12
Xz % Remove zeros
XJ % Copy into clipboard J
K7hm? % Are all intervals 4 or 7? If so: it's a major chord
O % Push 0 (will become space when converted to char)
. % Break for loop
] % End if
J % Push array of nonzero intervals again
I7hm? % Are all intervals 3 or 7? If so: it's a minor chord
'm' % Push this string
. % Break for loop
] % End if
J % Push array of nonzero intervals again
[KCX]m? % Are all intervals 4, 7 or 10? If so: it's a dominant-7th
% chord
'7' % Push this string
. % Break for loop
] % End if
J % Push array of nonzero intervals again
[ICX]m? % Are all intervals 3, 7 or 10? If so: it's a minor 7th chord
'm7' % Push this string
. % Break for loop
] % End if
] % End for. The loop is always exited via one of the 'break'
% statements. When that happens, the stack contains 0, 'm',
% '7' or 'm7', indicating the type of chord; and clipboard H
% contains a number that tells the root note using the lowest
% string as base (1 is F, 2 is F# etc)
'FF#GG#AA#BCC#DD#E' % Push this string. Will be split into strings of length 1 or 2
l % Push 1
2741B~Q % Push [1 2 1 2 1 2 1 1 2 1 2 1] (obtained as 2741 in binary,
% negated, plus 1)
Y{ % Split string using those lengths. Gives a cell array of
% strings: {'F', 'F#', ..., 'E'}
H % Push the identified root note
X) % Index into cell array of strings
wh % Swap and concatenate. Implicitly display
```
[Answer]
**MS-DOS .COM file (179 bytes)**
The file (here displayed as HEX):
```
fc be 81 00 bf 72 01 31 db b9 06 00 51 e8 73 00
59 e2 f9 b9 0c 00 be 48 01 ad 39 c3 74 0d 40 75
f8 d1 fb 73 03 80 c7 08 e2 ec c3 31 db 88 cb 8a
87 59 01 e8 42 00 8a 87 65 01 e8 3b 00 81 c6 08
00 ac e8 33 00 ac eb 30 91 00 89 00 91 04 89 04
ff ff 00 00 6d 00 37 00 6d 37 42 41 41 47 47 46
46 45 44 44 43 43 00 23 00 23 00 23 00 00 23 00
23 00 04 09 02 07 0b 04 84 c0 74 06 b4 02 88 c2
cd 21 c3 8a 0d 47 ac 3c 20 76 fb 30 ed 3c 41 73
22 2c 30 72 0b 86 c5 b4 0a f6 e4 00 c5 ac eb ed
88 e8 00 c8 30 e4 b1 0c f6 f1 88 e1 b8 01 00 d3
e0 09 c3
```
The input is given via command line. Invalid input will lead to invalid program behaviour!
The assembler code looks like this:
```
.text
.code16
ComFileStart:
cld
mov $0x81, %si
mov $(TuneTable-ComFileStart+0x100), %di
xor %bx, %bx
# 6 strings: Build the mask of played tones
mov $6, %cx
NextStringRead:
push %cx
call InsertIntoMask
pop %cx
loop NextStringRead
# Check all base tones...
mov $12, %cx
TestNextTone:
mov $0x100+ChordTable-ComFileStart, %si
TestNextChord:
lodsw
# Is it the chord we are searching for?
cmp %ax, %bx
je FoundChord
# Is it the end of the table?
inc %ax
jnz TestNextChord
# Transpose the chord we really play
# and go to the next tone
# This code rotates the low 12 bits of
# BX one bit right
sar $1, %bx
jnc NoToneRotated
add $8, %bh
NoToneRotated:
loop TestNextTone
EndOfProgram:
ret
FoundChord:
# Get and print the tone name
xor %bx, %bx
mov %cl, %bl
mov (ToneNamesTable+0x100-1-ComFileStart)(%bx),%al
call printChar
mov (ToneNamesTable+0x100+12-1-ComFileStart)(%bx),%al
call printChar
# Get the chord name suffix and print it
add $(ChordNamesTable-ChordTable-2),%si
lodsb
call printChar
lodsb
# Note: Under MS-DOS 0x0000 is the first word on
# the stack so the "RET" of printChar will jump
# to address 0x0000 which contains an "INT $0x21"
# (end of program) instruction
jmp printChar
ChordTable:
# Major, Minor, Major-7, Minor-7
.word 0x91, 0x89, 0x491, 0x489, 0xFFFF
ChordNamesTable:
.byte 0,0,'m',0,'7',0,'m','7'
ToneNamesTable:
.ascii "BAAGGFFEDDCC"
.byte 0,'#',0,'#',0,'#',0,0,'#',0,'#',0
TuneTable:
.byte 4,9,2,7,11,4
#
# Subfunction: Print character AL;
# Do nothing if AL=0
#
printChar:
test %al, %al
jz noPrint
mov $2, %ah
mov %al, %dl
int $0x21
noPrint:
ret
#
# Subfunction: Get one finger position
# and insert it into a bit mask
# of tones being played
#
# Input:
#
# [DS:DI] =
# Tuning of current string (0=C, 1=C#, ..., 11=B)
# Actually only 2=D, 4=E, 7=G, 9=A and 11=B are used
#
# DS:SI = Next character to read
#
# DF = Clear
#
# Input and Output:
#
# BX = Bit mask
# DI = Will be incremented
#
# Destroys nearly all registers but SI and BX
#
InsertIntoMask:
mov (%di), %cl
inc %di
SkipSpaces:
lodsb
cmp $' ', %al
jbe SkipSpaces
# Now evaluate each digit
xor %ch, %ch
GetNextDigit:
# Number = 10*Number+Digit
cmp $'A', %al
jae DigitIsX
sub $'0', %al
jb DigitsDone
xchg %al, %ch
mov $10, %ah
mul %ah
add %al, %ch
lodsb
jmp GetNextDigit
DigitsDone:
# Add the tune of the string
# and perform modulus 12
mov %ch, %al
add %cl, %al
xor %ah, %ah
mov $12, %cl
div %cl
mov %ah, %cl
mov $1, %ax
shl %cl, %ax
or %ax, %bx
DigitIsX:
ret
```
>
> Test cases:
>
>
>
> ```
> 6 20 0 3 11 6 --> A# (or Bb)
>
> ```
>
>
I already saw two piano players playing together "four handed" on a piano.
This test case is the first time I read about guitar players doing this!
Even with right-hand tapping you cannot play a cord like this!
[Answer]
# Ruby, 129 bytes
As previous version but uses a single loop, with ternary operator to sequence between the parsing step and output step. Some other minor modifications were required to make this work.
```
->a{r=0
18.times{|j|j<6?a[j]&&r|=8194<<(6--~j%5+a[j]*7)%12:(r/=2)&11==3&&puts("CGDAEBF"[j%7]+?#*(j/13)+['',?m,?7,'m7'][r>>9&3])}}
```
# Ruby, 136 bytes
Llamda function accepts an array of 6 numbers as an argument and outputs to stdout. Unused string is represented by a falsy value (the only falsy values in ruby are `nil` and `false`.)
```
->a{r=0
6.times{|j|a[j]&&r|=4097<<(6--~j%5+a[j]*7)%12}
12.times{|j|r&11==3&&puts("FCGDAEB"[j%7]+?#*(j/7)+['',?m,?7,'m7'][r>>9&3]);r/=2}}
```
**Explanation**
I use a representation of the 12 pitches based on the [circle of fifths](https://en.wikipedia.org/wiki/Circle_of_fifths) .
This means each pitch is followed by the pitch 7 semitones higher (or 5 semitones lower) giving the sequence `F C G D A E B F# C# G# D# A#`. There are 2 advantages to this. One is that all the sharps appear together. The other is that the open-string notes of the 5 string bass appear together: GDAEB (the guitar is related but slightly more complex, see below).
The first loop runs 6 times. The expression `6--~j%5`(equivalently `6-(j+1)%5`) gives the note values for the open strings: `E=5 A=4 D=3 G=2 B=6 E=5`. To this we add the fret number multiplied by 7 (as can be seen above, adding one semitone moves us 7 places forward in the sequence.) Then we take the whole thing modulo 12 and make a bitmap of the notes that are present (we use `4097<<note value` to give 2 consecutive octaves.)
Having composed the bitmap, we are ready to search the chord and output it.
We are interested in the following notes:
```
Note position in position in Note position in
semitone domain circle of fifths circle of fifths
Root 0 0 Root 0
Minor 3rd 3 9 Fifth 1
Major 3rd 4 4 Sixth 3
Fifth 7 1 Major 3rd 4
Sixth 9 3 Minor 3rd 9
Minor 7th 10 10 Minor 7th 10
```
Starting by checking for chord F, we test to see if the root and fifth are present: bits 0 and 1 (counting from least significant: the 1's and 2's bits.) In order to reject sixth chords we also need to check that the sixth is absent: bit 3 (8's bit.) so we check that `r&&11==3` and if so we print the chord.
We ignore the major third, and rely entirely on bit 9 (minor third) and bit 10 (minor 7th) to work out the chord type. The expression `r>>9&3` is used to pick the correct chord type from an array.
At the end of the loop, we shift the bitmap right one bit `r/=2` to test the possible chord roots in sequence: `F C G D A E B F# C# G# D# A#`.
**Ungolfed in test program**
```
f=->a{ #Accept array of 6 numbers as argument.
r=0 #Setup an empty bitmap.
6.times{|j| #For each string
a[j]&& #if the fret value is truthy (not nil or false)
r|=4097<<(6--~j%5+a[j]*7)%12 #calculate the note value in the circle of fifths and add to the bitmap.
}
12.times{|j| #For each possible root note
r&11==3&& #if root and fifth are present (bits 0 and 1) and sixth is absent (bit 3)
puts("FCGDAEB"[j%7]+?#*(j/7)+ #output the note name and a sharp symbol if necessary, followed by
['',?m,?7,'m7'][r>>9&3]) #m and/or 7 as indicate by bits 9 and 10.
r/=2
}
}
print 1;f[[nil,3,2,0,1,0]] # C
print 2;f[[0,2,2,0,0,0]] # Em
print 3;f[[nil,2,nil,0,nil,0]] # Em
print 4;f[[4,4,6,4,6,4]] # C#7
print 5;f[[4,4,6,4,5,4]] # C#m7
print 6;f[[0,2,2,1,0,0]] # E
print 7;f[[0,0,2,2,2,0]] # A
print 8;f[[nil,nil,4,3,2,2]] # F#
print 9;f[[3,2,0,0,0,1]] # G7
print 10;f[[nil,nil,0,2,1,1]] # Dm7
print 11;f[[3,3,5,5,5,3]] # C
print 12;f[[4,6,6,5,4,4]] # G#
print 13;f[[2,2,4,4,4,5]] # B7
print 14;f[[0,7,5,5,5,5]] # Am7
print 15;f[[7,6,4,4,nil,nil]] # B
print 16;f[[8,6,1,nil,1,3]] # Cm
print 17;f[[8,8,10,10,9,8]] # Fm
print 18;f[[0,19,5,16,8,7]] # Em
print 19;f[[6,20,0,3,11,6]] # A#
print 20;f[[nil,14,9,1,16,nil]] # G#m
print 21;f[[12,14,14,12,12,12]] # Em
print 22;f[[15,14,12,12,12,15]] # G
print 23;f[[20,nil,20,20,20,20]] # Cm7
print 24;f[[nil,13,18,10,11,10]] # A#7
```
[Answer]
# Javascript (ES6), ~~335~~ 333 bytes
Love this challenge and PPCG SE! This is my first golf - suggestions welcome as I'm sure it could be improved a lot.
(knocked off 2 bytes as I had included f= in the count)
Function `f` takes an array of strings, representing numbers and 'X', like `f(['X','3','2','0','1','0'])` and returns a chord (natural or sharp) like `E#m7`. Newlines added for clarity (not included in byte count)
```
f=c=>[s=new Map([[435,''],[345,'m'],[4332,7],[3432,'m7']]),
n=[...new Set(c.map((e,i)=>e?(+e+[0,5,10,3,7,0][i])%12:-1)
.filter(e=>++e).sort((a,b)=>a>b))],d=[...n,n[0]+12].reduce(
(a,c,i)=>i?[...a,(c-n[i-1]+12)%12]:[],0).join``.repeat(2),
m=+d.match(/(34|43)(5|32)/g)[0],'E0F0F#0G0G#0A0A#0B0C0C#0D0D#'
.split(0)[n[d.indexOf(m)]]+s.get(m)][4]
```
Usage example:
```
console.log(f(['0','2','2','0','0','0'])); // Em
```
To run test cases:
```
tests=`X 3 2 0 1 0 ---> C
0 2 2 0 0 0 ---> Em
X 2 X 0 X 0 ---> Em
4 4 6 4 6 4 ---> C#7 (or Db7)
4 4 6 4 5 4 ---> C#m7 (or Dbm7)`; // and so on...
tests.split`\n`.forEach(e=>{
console.log(`Test: ${e}
Result: ${f(e.split(' ').slice(0,6))}`)
})
```
Ungolfed version with explanation:
```
f = (c) => {
s = new Map([
[435,''], [345,'m'], [4332,7], [3432,'m7']
]) /* Each key in s describes the intervals (semitones)
between consecutive notes in a chord, when it is
reduced to a single octave, including the interval
from highest back to lowest. The values describe
the corresponding chord suffix. E.g. C-E-G has
intervals C-4-E-3-G-5-C. 435=major=no suffix. */
n = [ ...new Set(
c.map(
(e,i) => e ? ( +e + [0,5,10,3,7,0][i] )%12 : -1
).filter( (e) => ++e ).sort( (a,b) => a>b )
) ] /* take the input array, c, and transform each fret
position into a note. remove non-notes (-1), sort
in tone order, remove duplicates. An input of
positions X 13 18 10 11 10 becomes notes
(-1) 6 4 1 6 10 then 1 4 6 10. */
d = [ ...n, n[0] + 12 ].reduce(
(a,c,i) => i ? [ ...a, (c - n[i-1] + 12)%12 ] : [], 0
).join``.repeat(2)
/* convert the note array, n, into an interval string, d,
including the lowest note repeated above it to capture
all intervals. Repeat it twice so that, regardless of the
inversion played, the intervals will appear in root order
somewhere. E.g. notes 1-4-6-10 and 13 (1+12)
become intervals 3 2 4 3, and string for searching
32433243 */
m = +d.match( /(34|43)(5|32)/g )[0];
/* m is the matched chord pattern. In this case, 4332. */
return 'E0F0F#0G0G#0A0A#0B0C0C#0D0D#'.split(0)[
n[ d.indexOf(m) ]
/* get the position in the interval string where the root
interval first occurs. this corresponds to the position
of the chord root note in the note array, n. convert this
number 0-12 to a note name E - D# */
] + s.get(m)
/* add the suffix corresponding to the matched
chord interval pattern */
}
```
] |
[Question]
[
For your hard thing to do, you must make a thing for a computer to do that finds out if some words are explained in a simple way. Something is explained in a simple way if it only uses the ten hundred most used words. If not, it is explained in a hard way. This can be a full computer thing or part of a computer thing. (full program or function)
There is a thing for a computer to read that has all of the ten hundred words in it with a space between each word. The name of the thing for the computer to read is called 'most used.txt'. You can take this thing from [this computer place](https://drive.google.com/file/d/0B2sM8IORrbL3RVpJWTZNUy1rOFU/view?usp=sharing).
The person who uses the computer thing will enter some words. (This can be from STDIN, function arguments or command line arguments) The computer must say something like a true if the words are simple and something like a not true if it is hard. ([truthy-falsy](http://meta.codegolf.stackexchange.com/questions/2190/interpretation-of-truthy-falsey)) The person who makes the shortest thing for the computer to do is the best. The things that every person knows are bad are bad. ([standard loopholes apply](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default))
---
More stuff to know about how the computer thing works:
* It doesn't matter if the words are BIG or little.
* The pictures that make what the word meaning easier to know (punctuation) don't matter. So if the person who uses the computer thing says "dont" it isn't a different word than the word "don't". Numbers and other pictures also don't matter. So if the person says "HE$$ll9o" the computer should read it like "hello"
* The little lines between words (dashes) work the same way as spaces. So the word "up-goer-five" is the same as the words "up goer five".
---
More stuff to know about making words like this:
<https://xkcd.com/1133/>
<http://splasho.com/upgoer5/#>
[Answer]
# R, 106 bytes
Is not sure if is understand challenge because is has hard time reading.
```
function(s){u=toupper;all(strsplit(gsub("[^A-Z -']","",u(s)),"[ -]")[[1]]%in%u(scan("most used.txt","")))}
```
This creates an unnamed part of a computer thing that accepts a string and returns something like a true or like a not true.
Ungolfed + explanation:
```
partOfAComputerThing <- function(s) {
# Remove everything but letters, spaces, dashes, and single quotes
s <- gsub("[^A-Z -']", "", toupper(s))
# Split s into a vector on spaces/dashes
v <- strsplit(s, "[ -]")[[1]]
# Read the file of words (assumed to reside in the current directory)
m <- scan("most used.txt", "")
# Determine if all words in the input are in the file
all(v %in% toupper(m))
}
```
Thanks to Dennis for inspiration thing.
[Answer]
# CJam, 41 bytes
```
q"file:///most used.txt"g]{el_euS--S%}/-!
```
This makes the rather unclean assumption that `most used.txt` is in the root directory, since CJam cannot handle relative paths.
Alternatively, we have the following web-based solutions (78 and 29 bytes):
```
q"https://docs.google.com/uc?id=0B2sM8IORrbL3RVpJWTZNUy1rOFU"g]{el_euS--S%}/-!
```
```
q"j.mp/-o_O"g]{el_euS--S%}/-!
```
The "proper" way of doing this in CJam would be reading both inputs from STDIN (input on the first line, dictionary on the second), which is possible in 18 bytes:
```
qN%{el_euS--S%}/-!
```
You can try the last version in the [CJam interpreter](http://cjam.aditsu.net/#code=qN%25%7Bel_euS--S%25%7D%2F-!&input=ten%20hundred%0Athe%20I%20to%20and%20a%20of%20was%20he%20you%20it%20in%20her%20she%20that%20my%20his%20me%20on%20with%20at%20as%20had%20for%20but%20him%20said%20be%20up%20out%20look%20so%20have%20what%20not%20just%20like%20go%20they%20is%20this%20from%20all%20we%20were%20back%20do%20one%20about%20know%20if%20when%20get%20then%20into%20would%20no%20there%20I'm%20could%20don't%20ask%20down%20time%20didn't%20want%20eye%20them%20over%20your%20are%20or%20been%20now%20an%20by%20think%20see%20hand%20it's%20say%20how%20around%20head%20did%20well%20before%20off%20who%20more%20even%20turn%20come%20smile%20way%20really%20can%20face%20other%20some%20right%20their%20only%20walk%20make%20got%20try%20something%20room%20again%20thing%20after%20still%20thought%20door%20here%20too%20little%20because%20why%20away%20let%20take%20two%20start%20good%20where%20never%20through%20day%20much%20tell%20wasn't%20girl%20feel%20oh%20you're%20call%20talk%20will%20long%20than%20us%20made%20friend%20knew%20open%20need%20first%20which%20people%20that's%20went%20sure%20seem%20stop%20voice%20very%20felt%20took%20our%20pull%20laugh%20man%20okay%20close%20any%20came%20told%20love%20watch%20arm%20anything%20I'll%20though%20put%20left%20work%20guy%20hair%20next%20couldn't%20yeah%20while%20mean%20home%20few%20saw%20place%20school%20help%20wait%20late%20year%20can't%20house%20happen%20last%20always%20move%20old%20night%20nod%20life%20give%20sit%20stare%20sat%20should%20moment%20another%20behind%20side%20sound%20once%20find%20toward%20boy%20ever%20nothing%20front%20mother%20name%20am%20since%20reply%20he's%20myself%20leave%20bed%20new%20car%20use%20mind%20maybe%20has%20heard%20answer%20minute%20yes%20until%20both%20found%20end%20small%20I'd%20word%20someone%20same%20enough%20began%20run%20bit%20sigh%20each%20those%20almost%20against%20everything%20most%20thank%20wouldn't%20mom%20better%20play%20I've%20own%20every%20hard%20remember%20three%20stood%20live%20stand%20second%20sorry%20keep%20finally%20point%20gave%20already%20actually%20probably%20himself%20big%20everyone%20guess%20lot%20step%20hey%20hear%20light%20quickly%20dad%20kiss%20black%20pick%20else%20soon%20shoulder%20table%20best%20without%20notice%20stay%20care%20phone%20reach%20realize%20follow%20decide%20kind%20she's%20grab%20he'd%20show%20inside%20suddenly%20father%20rest%20herself%20grin%20hour%20hope%20also%20body%20might%20hadn't%20floor%20its%20continue%20ran%20across%20hold%20cry%20half%20pretty%20great%20course%20mouth%20class%20kid%20miss%20wonder%20morning%20least%20nice%20dark%20slowly%20done%20change%20doesn't%20together%20yet%20question%20anyway%20bad%20blue%20believe%20week%20God%20lip%20Mr.%20sleep%20fine%20what's%20family%20many%20worry%20roll%20parents%20under%20surprise%20water%20onto%20we're%20glance%20wall%20between%20seen%20read%20window%20idea%20white%20push%20feet%20must%20such%20seat%20set%20please%20red%20brother%20these%20whole%20lean%20part%20person%20slightly%20pass%20shook%20fact%20wrong%20gone%20far%20hit%20finger%20quite%20hate%20meet%20finish%20heart%20book%20past%20kill%20reason%20anyone%20figure%20top%20along%20world%20she'd%20high%20shirt%20does%20today%20young%20held%20outside%20listen%20whisper%20won't%20happy%20ground%20deep%20drop%20shrug%20dress%20fell%20there's%20yell%20breath%20air%20tear%20sister%20chair%20kitchen%20matter%20hurt%20fall%20wear%20isn't%20woman%20eat%20lie%20hell%20suppose%20cover%20couple%20large%20either%20five%20leg%20jump%20die%20return%20able%20bag%20alone%20shut%20stuff%20short%20ready%20understand%20kept%20plan%20raise%20street%20different%20problem%20break%20line%20early%20cut%20cold%20paper%20scream%20instead%20stupid%20silence%20tree%20caught%20ear%20food%20full%20four%20cause%20fuck%20explain%20expect%20fight%20exactly%20sort%20completely%20men%20dance%20met%20story%20whatever%20build%20speak%20glass%20pain%20check%20glare%20corner%20Mrs.%20chest%20hot%20rather%20month%20real%20touch%20park%20bring%20they're%20drink%20ago%20force%20you've%20fast%20lost%20attention%20wish%20mark%20wave%20shout%20fill%20begin%20baby%20interest%20money%20fun%20green%20however%20cheek%20mine%20clear%20brown%20forward%20near%20picture%20may%20cool%20drive%20hug%20shake%20sense%20alright%20you'll%20dream%20hang%20clothes%20act%20become%20manage%20meant%20game%20ignore%20stair%20taken%20party%20add%20sometimes%20job%20ten%20shot%20date%20quiet%20gaze%20group%20loud%20straight%20dead%20neck%20beside%20pause%20number%20conversation%20chance%20we'll%20rose%20quietly%20town%20blood%20color%20desk%20dinner%20hall%20horse%20music%20brought%20piece%20anymore%20beautiful%20order%20fire%20office%20true%20although%20warm%20easy%20enter%20perfect%20mutter%20softly%20cross%20shock%20smirk%20damn%20soft%20stomach%20snap%20spoke%20tire%20box%20catch%20skin%20teacher%20middle%20note%20yourself%20haven't%20lunch%20tomorrow%20breathe%20clean%20except%20appear%20lock%20knock%20bathroom%20movie%20agree%20offer%20kick%20form%20confuse%20lay%20less%20calm%20slip%20weren't%20sign%20dog%20lift%20immediately%20arrive%20deal%20tonight%20usually%20case%20frown%20shop%20scare%20promise%20mum%20couch%20pay%20state%20shit%20wrap%20pocket%20hello%20free%20huge%20ride%20bother%20land%20known%20especially%20expression%20carry%20ring%20spot%20allow%20several%20aren't%20during%20empty%20lady%20eyebrow%20strange%20coffee%20road%20threw%20wide%20bus%20forget%20gotten%20smell%20fear%20press%20boyfriend%20blonde%20throw%20round%20sun%20tall%20glad%20age%20write%20upon%20hide%20became%20crowd%20rain%20save%20trouble%20annoy%20nose%20weird%20death%20beat%20tone%20trip%20six%20control%20nearly%20consider%20gonna%20join%20learn%20above%20hi%20obviously%20entire%20direction%20foot%20angry%20power%20strong%20quick%20doctor%20edge%20song%20asleep%20twenty%20barely%20remain%20child%20enjoy%20gun%20slow%20city%20broke%20key%20lead%20throat%20normal%20you'd%20somewhere%20wake%20pair%20sky%20funny%20business%20student%20giggle%20bright%20admit%20jeans%20given%20children%20store%20sweet%20low%20climb%20rub%20apartment%20knee%20shoe%20attack%20bedroom%20joke%20spent%20situation%20stuck%20gently%20possible%20cell%20mention%20silent%20definitely%20rush%20hung%20brush%20perhaps%20groan%20ass%20rock%20card%20lose%20blush%20besides%20crazy%20type%20bore%20afraid%20chase%20respond%20marry%20remind%20pack%20daughter%20serious%20girlfriend%20mad%20somehow%20buy%20sent%20tight%20simply%20trust%20imagine%20wind%20chuckle%20bar%20pink%20shove%20ball%20sight%20drag%20they'd%20human%20truth%20share%20area%20concern%20shouldn't%20team%20escape%20mumble%20often%20search%20apparently%20attempt%20son%20within%20band%20cute%20led%20memory%20anger%20fly%20paint%20bottle%20busy%20comment%20exclaim%20avoid%20grow%20grey%20mirror%20gasp%20hallway%20dear%20star%20sick%20cat%20counter%20interrupt%20none%20blink%20spend%20usual%20worse%20locker%20important%20favorite%20grip%20TV%20ice%20pretend%20settle%20amaze%20pop%20disappear%20carefully%20train%20stick%20guard%20teeth%20flash%20uncle%20send%20doubt%20visit%20nervous%20excite%20approach%20excuse%20fit%20noise%20study%20letter%20police%20eventually%20burn%20field%20hospital%20tie%20summer%20huh%20shift%20self%20hurry%20greet%20wife%20position%20we've%20wipe%20heavy%20slam%20broken%20complete%20space%20brain%20tiny%20pants%20ah%20punch%20shower%20tongue%20afternoon%20seriously%20cup%20further%20race%20recognize%20computer%20rang%20safe%20jacket%20bottom%20hundred%20relax%20sudden%20wow%20college%20flip%20mood%20track%20crack%20block%20handle%20themselves%20drove%20seven%20struggle%20whether%20ahead%20sad%20dry%20women%20focus%20repeat%20thick%20relationship%20jerk%20present%20suck%20bell%20surround%20evening%20bite%20single%20fault%20shadow%20wood%20easily%20woke%20smoke%20draw%20suggest%20wet%20accept%20third%20totally%20wore%20breakfast%20trail%20animal%20warn%20aunt%20sir%20piss%20burst%20match%20fix%20practically). (permalink tested in Chrome)
### Examples
```
$ cjam <(echo 'q"file:///most used.txt"g]{el_euS--S%}/-!') <<< 'ten hundred'; echo
1
$ cjam <(echo 'q"file:///most used.txt"g]{el_euS--S%}/-!') <<< 'thousand'; echo
0
```
[Answer]
# Python 3, 148 bytes
```
import re
print(all(i in open("most used.txt").read().lower().split(' ')for i in re.sub("[^a-z ']+","",input().replace("-"," ").lower()).split(" ")))
```
Outputs `True` and `False`
## Examples
```
Input: Don't
Output: True
Input: The poison air he's breathing has a dirty smell of dying
Output: False
Input: Who let the dogs out?
Output: False
```
[Answer]
# Pyth, 35 bytes
```
!-Fm@LGcrXd\-bZ),zs'"most used.txt
```
Tests, where the above is the file `common.pyth`
```
$ pyth common.pyth <<< 'I can write this way too-hell99#0O.'
True
$ pyth common.pyth <<< 'But I get confused easily.'
False
```
Explanation:
```
!-Fm@LGcrXd\-bZ),zs'"most used.txt
m ,zs'"most used.txt Map over input and input file:
Xd\-b Replace hyphens with newlines.
r Z Cast to lower case.
c ) Split on whitespace.
@LG Remove non-alphabetic characters.
-F Setwise difference - remove anything in
the text file from the input.
! Logical negation.
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 69 bytes
Assumes that the file is in the current directory.
```
s←819⌶' '(1↓¨,⊂⍨⊣=,)'[- ]' '\W'⎕R' ' ''
∧/(s⍞)∊s⊃⎕NGET'most used.txt'
```
[Try it online!](https://tio.run/nexus/apl-dyalog#fZixrjU3FYX7PIW7k0ghKB0UlBClCEIoQAEUnhnPjP8zYw@2585/UoIUooggJERLQ0GegAfgUe6LhG9tnwTRUPz3v3fOHHt777XXWtu3PdfmzhqmD9rbdnv9899@@rNffPr61de3tgb3sWvZ@TQ57/LsLl8dDx/5dLG5mPijuMqTtvrm9odbY3V7cDm5K7bV8VDf8JObc3HD2Xhhd9XHyQ3BnYfLPNpyvruaee0luEsLpdzcm5OotngPbsksHx6OpZvWn0vend82d/F6KMENfry7KbNrcH7QkveULxeJdw3JLaFpgUS8nOXK5zaxgx7x3Y9vt92N9mzK6XZTwFrsSq5FTjLFyZ5ePjUXHjpp2F1@4dxkoTjPGjpaYH1t6pMbHoozcaYQOBS5i@12qxyb/OiVkk8eroG0sDxn4CxDIEMsNSvo7Hb9EV5YtJ0lESCh1D1unJhVSuD4Dzey2exHvtWsDnqpxGW148ZCPnjp8tvd7d7yyAflYe8pwMWVrEwunkL2B35uWqhFImprPrXWlDmf5arlTEVaI4ohjB7IEOvDeYW0KcnapV2ZBXxp7JcnVYBvpqCEtbVoSTfx/n6Oq2s6OZiyDC@xbG4OYXN5VW5vN744qs5NR7gU05YJEqwl8MqhpgAYYiCZ9xQulw8VIQTQFgvoudbIJkfIx9YRqipcgULWk7UpD1hs@XAvOZJFQnwQwNZ00LtTdY9Tm3oFvbNpvhP5uGUO7pPyvyspQGfLgq5vbOfLrg97PkHXd5lkMQAdZuLK5e6WEzR4qpTC29YRaGl4BL8qckLeA3uuqurM6aq/3LGp3HVcc96oyXawKY24@Rb0xSJIaBE2rMLeoYxsnlz4jSqRMwWqiJPhJFGhLc5gI/K8spRKx280YV2tK3b2J2M@dZANgYNNvEruq@E4J0Ka9bDlyxc6Oz@c1VtfURZoWFbY@wJJSfMkPup7JRxgdA2qzP6oYZtJkXhgoIqq6cihdJZdG@z@MehYIiHt5FOFAPTZaQmo7kxglwjgntmiEzjqLhRRi0mpn6wBxBVVoYRkxRnCQrLLSfsqC2THBS@IrlbtzUjSWoX/dbpnhe25EHnvzGLpJ2cs2NRLVOyhrZV2OMW@yQmIooQ97ENvC4gCIFoxVIcm0qhhzPovF75xD@FQkq3vjwyTuUVp8htcMNGDYzv7ZyUPflBO427pHOLSd9WJlzPUClpVZxYUqyqTbCs0/O6M452vThDTPfLisIlZD566sFUVHGLvuFDc7KNCqdOiMG7ErU7iAOoOgHSs2rZYKsVa8TOwkrcNGpzCKBDdDU4dAUvxg4FBT8TgqePsnKYgLpu9QahoS36x8y1FMqRmXel/EoKSDJmU7HYmtMdKMm@isdgqrQZG0klUFNyPJXPQVS0xWmVY8ijU7sHKwVtnFuGP4630vuftO6S9Kz8XBRL@cknCAsglsKQMTJ4WrxxT6VQKRiCy8DyHznYtI0s6zCMo8ZwokluIQ2Q6UIBhO5XcLQZRSwh395Hh43CflA9Y@gmIrphK3uzRh4d46iGYc5hCot1BGVJTZyhUiO8osRpZBSmEFDEY1S6bV0de3tSoXVK0qh9CGBVOkyoyBS92ot2Os67ia@Auqa4i9KqMVR4dyoUKz0FKb3x@mGBkQLOJ2Q6JxEEZBSpDoPCrBFN8CBhpA1lFlL8ohTNAZWedemE90NpEBk1EGexxJCLhuYEAFjhUjrt0gyPUnl5bKC6nydkBXLQ86dqeIESX1ft1jaVZtXhNeoUg8SKUO8mzGCy3SBMlZaNyCoHBqBfSFXaMfSZVaSpsVNdyLvyq/puDiQLCqLo9TP6FNcQDPWhqyKq1i1DDk3tEWNhp90Yp60loczdAvBo7oK4shVL@gYwC3SjJcYi9RrMrAFk6uPkCDkO0msyimy0suK2dQKMqZoajt7ZfLEF04HqKMk7cCbVh@846hqnOVvdwqOriUC981VZUlCnOcxAAjZg2BFcnvRMjqxK9XMypJiOvh1ca68gLu1q/CXdsekTpzRaETq0Ks5gx0eFnkeYslZ5FAd2UzKcI6y3RQA38H0ahw77yFkxtskBFm@4kBA9C05DdyeCPNRIV0z3qK5Ox4YxCx6G4FyOAQwtTktEeyKbAALz5Sakf6LnoCY4tna52uqyzH1hSlxwih6FE8zLhYd03FTlGj9fFB46hG6AXgV422MSH4idjiUs437XIJQ2oRr1ztL5diAwBeMjsBiNKtofmZ5QNQgviysuORZyQyq5CjJtySaOiUGxvKp70COpvapVdfC7PQZjsuALlusrt1ZBMHrvttKA3vaUSivHkltT4EiiZRpkZcOqX7m6kYjyJS5LfBUnCP@t2ckDWpq7WsuLVvcmDU8dVJXdS48MBQWugKuq4g0ydwgwYNOsqBCWVCZVSyx6Gj3Sa7iIE5AGro5yKn8V@wQ5Q1Da2OOBoSsuwCWngFBWZgkaEmFTyVX1IS0gizhpHZdHQecQwmk00Kz8Ef7YIUBkWJmu8bvajYfpUCp8u8ZKBhK7wUMkMRCizALyf1vw1z4qpyxaJ4GzMBUBh8nuyTwXfXXpbk4d3jixTru2G/JYGkUetdzl@ibK5p2mi2ZFuQ11XVc1iRivbmeSCMqcAHk@e6ohRb41qe9lMmQgFw@SldHt5fVwQfhNS8UKejhtEZnwOyDR1pVnl2Gx84DiY/V1KcNhYZ9tjxOjMvMilMnDue5iit5b1xaA49bbqdvas53MwEgsYnEkRSehehLkxWp1s4rNGfAh0TT0UpTUk7CD@0IxA6UXFDdo1V03BfCVH2Izwkvk5aGGMtilEI3Y3MHmTXzU4@Zf5luGpajui9c@zTae9EfYDpG/iU@ZLNaEBWG5hVMrYOwNjucSL1lcYDD9kUHMtM511xC6@n61lTWLw4M/JCODC0jZ7Xa6rUoULmnALeWGi2egq0tLzIPbVdgg224CyaxKhs4OYpvF9CYNPCY@f1CQXg6Z0Tuo1SH2a9KIViljjWzNb2BBjExUmm6MrEvTkaWhWFvdIcDSZrNHl4SUyvWyGf8F24sdoPQrZaxBZiizwZYOquQPzraBkhLddmBYZVQ2z3SQ1TXzyVEWwwXV38hanh/SGcyxnMqvmxqj3ihrmHoTJnvZsNxKFIaITXKekPtheIsFDtFXvRrKYL8oDqao92zlJ@pa4LJLTTpJ@2sHaG/qn2tj1DKaojM1o8JJyWkBb3AeGkoEWgw9tEGPSNcoPEgRv1DZZq71R3MBR421kGrCUEYJEioc2NwBP1W8UWvanmpi0iitloKy1ipzdKr8z2K9QEK5G9jzLMnOyoiYfJRM2DONV6/rkWNq4@M9gzcehhuE8fi668IFhzRHSETbKWYsEm@sOu8AxVVdVQxEC7ELgCeLd96RrKBgYnKsibpbOGneNkJBoFUH4xTyxVh1Xzm42RkKm@5hVGBuE/Nr1ofhvJRjfd8pAsU6T/RNh8M8LsmMo34493btL3QKkchiZKKPwrtllX3QFcHTTLZaiPelvAdKGJFNnxaaBdcMdMwPKbHiztLMZYA13MI1ds5xVTbNb5WFbHM3u/EsmnYv6GV7VoAM101K@HiZHmiAmM5HNnKSVygYZExQzBuU8BOqk2llqDqXZ@FNuWKwsHuTt/cArSaln9jWaWNTcn/7SSbs0KtmIHSxev0uKjywvWZ@yIO6VQ1ONjEmaIlpOoaeBdIYITNWKmURUVFndxJ1Dcy9RFxKI7IvQwOm1OYuCQpLM3@b19ErujvOc7B7KVDNvCk83aM/BeJCtnaMMPCP9EZt0I2q4JLsy1Wb6JZ@mf6fguZiHvXRBQu/Ebr6C@bIrHnLZ/gUwbn7vtJG@85QkVDc1g52YcVN11RTmdQ0kRdV8q6EIopL6694t2XTdwW@@mAEPq28Tr7e7kjEvSRO0djmbPZfEeOJ74022hBu4gOadNHtBef7tc36mrpcMDHaftElld1kaiiKA2M/BJFxXllu/6CQXL3Q0BCOfafeRcO5pdAYBWmzeLjKrLjPlmnVdBFNTHF3umCKsKrhCUQJJ8gH74VikVP0yzljMBpbSFUo7SRsHlRw21X6zPzfdSnnNoZdCxyVp4r2M@Hb9pKFRT@KzSwny4UdzKIQgtOVmULjMkWkOMXctWKLKKYrhLxOj00hUtCEtPXWZuJtzmtG0g1yBYS11e@f1iz/O39TXz//ygw9/@Pqnf93c7d0PXz//67@/fv/1y9@/fvX165f/@NH7791@/T33Wz77za90v/5zfnM3ffef33@3vn719/dev/iyvn75B929f/TjT2//eyP/DXt8M78jgnnW9R3@0hUfheLXn@TnXbRdK/VrKcb6Kf@/z963S3yb3O1y2D8/1D29/y/A7N1@u68rvmoX9nHud826TKt2A/4ctkAccPedk@2q@oP/AA "APL (Dyalog Unicode) – TIO Nexus")
The first line defines a normalising and splitting-into-list-of-strings helper function, *s*:
`s←` *s* is
`819⌶` the lowercased
`' '(` result of the following function, with a space as left argument…
`1↓¨` drop one from each of
`,` the concatenation of the arguments
`⊂⍨` cut before each element where
`⊣` the left argument
`=` is equal to
`,` the concatenation of the arguments
`)` applied to
`'[- ]' '\W'⎕R' ' ''` the PCRE replacements dash/space→space, non-word-char→nothing
`∧/(`…`)` is it all-true that
`s` the normalised and split
`⍞` text input
`∊` are members of
`s` the normalised and split
`⊃` first element of
`⎕NGET'most used.txt'` the (content, encoding, newline-style) of the file
[Answer]
# PHP, 101 bytes
```
foreach(preg_split("#[^\w']+#",$argn)as$w)preg_match("#\b$w\b#i",end(file("most used.txt")))?:die(1);
```
takes input from STDIN, assumes single line dictionary
exits with `1` (error) for falsy, `0` (ok) for truthy. Run with `-R`.
Split input by non-word characters, loop through resulting array (words):
If word is in the dictionary, continue; else `exit(1)`.
implicit `exit(0)`.
or, simply put:
one word after another: If word is in the most used words, continue; else return 1.
return 0.
and: I could save two points if the most used words had a space each in front and at the end.
[Answer]
# JavaScript (ES7), 161 bytes
```
s=>fetch("most used.txt").then(t=>t.text()).then(d=>alert(s.split(/[ -]/g).every(l=>d.split` `.map(w=>w.replace(/[\.']/,"")).includes(l.replace(/[^a-z]/g,"")))))
```
Anyone got a copy of the file online that I can use to create a working Snippet?
[Answer]
# Java, 248 bytes
With the Phrase passed as an argument.
```
void g(String s) throws Exception{String c=new java.util.Scanner(new java.io.File("most used.txt")).useDelimiter("\\Z").next(),x="false";for(String l:s.split(" "))if(c.contains(l.toLowerCase().replaceAll("![a-z]","")))x="true";System.out.print(x);}
```
input/output:
```
g("was he") --> "true"
g("was h!e") --> "true"
g("delicious cake") --> "false"
```
Spaced and tabbed out:
```
void g(String s) throws Exception{
String c=new java.util.Scanner(new java.io.File("most used.txt")).useDelimiter("\\Z").next()
,x="false";
for(String l:s.split(" "))
if(c.contains(l.toLowerCase().replaceAll("![a-z]","")))
x="true";
System.out.print(x);
}
```
] |
[Question]
[
Your task is to compile regexes... by specifying a substitution for each character in a regex.
## Regexes
The regexes support these
```
REGEX = (LITERAL REGEX / GROUP REGEX / STAR REGEX / ALTERNATIVE)
LITERAL = 1 / 0
GROUP = '(' REGEX ')'
STAR = (LITERAL / GROUP) '*'
ALTERNATIVE = '('REGEX ('|' REGEX)*')'
```
Why only 1 or 0? It is for simplification. The regex thus has only the following characters:
```
*()|10
```
It is interpreted as follows:
1. `*` is Kleene star (repeat left group or literal 0 or more times).
2. `|` is alternation (match if either the regex to the left or the regex to the right matches).
3. `()` is grouping.
4. `1` matches character 1.
5. `0` matches character 0.
## How to compile?
You specify six code snippets: one to replace each regex character. For example, if your answer is:
>
> `*` : `FSAGFSDVADFS`
>
> `|` : `GSDGSAG`
>
> `(` : `GSDG`
>
> `)` : `GDSIH`
>
> `1` : `RGIHAIGH`
>
> `0` : `GIHEBN`
>
>
>
Then you replace each regex with its respective code snippet, so:
```
(0|11)*
```
is turned into:
```
GSDGGIHEBNGSDGSAGRGIHAIGHRGIHAIGHGDSIHFSAGFSDVADFS
```
## What is the resulting program supposed to do?
Your program will:
1. Take the input.
2. Output a truthy value if the regex matches whole input.
3. Else output a falsy value.
Input outside `01` is consindered undefined behavior. Input can be empty.
## Additional rules
1. For a given regex character, the resulting snippet must always be the same.
2. There is no prefix or suffix character added afterwards.
3. The regex is guaranteed to be nonempty.
## Scoring
The least combined snippet is the winner. So the score for the example case would be calculated as follows:
`FSAGFSDVADFS` + `GSDGSAG` + `GSDG` + `GDSIH` + `RGIHAIGH` + `GIHEBN`
12 + 7 + 4 + 5 + 8 + 6 = 42
[Answer]
# [Snails](https://github.com/feresum/PMA), 48 bytes
`0` -> `)0(\0!(l.)(~`
`1` -> `)0(\1!(l.)(~`
`(` -> `)0({{(`
`)` -> `)0}}(~`
`|` -> `)0}|{(`
`*` -> `)0),(~`
If we had to search for partial matches rather than matching only the full input, then it would be very easy. `0` would become `\0`, `1` would become `\1`, `*` would become `,`, and the others would map to themselves. Instead there are a lot of shenanigans to prevent matches from starting somewhere other than the beginning or ending somewhere other than the end. `!(l.)` is an assertion that will fail if the beginning of the match is not at the beginning of the input. `~` matches a cell outside of the input, so it is added to all the characters that are allowed to be at the end of the regex. If there is another regex character following, it is canceled out by a numerical quantifier `0` which requires it to be matched 0 times, essentially commenting it out. To allow `*` (`,`) to work correctly despite the dummy out-of-bounds test being in the way, the language's bracket matching rules are heavily used. From the documentation:
>
> Matching pairs of parentheses `()` or curly braces `{}` will behave as expected (like parentheses in regex), but it is also possible to leave out one half of a pair and have it inferred, according to the following rules. `)` or `}` groups everything to the left until the nearest unclosed group opening instruction of the same type(`(` or `{` respectively), or the beginning of the pattern if none exists. It closes any unclosed opening instructions of the opposite type in the middle of this range. An otherwise unmatched `(` or `{` is closed by the end of the pattern.
>
>
>
Clear as mud, right?
[Answer]
# CJam, 151 bytes
```
{]Na/Saf+{:m*:sSf-~}%}:J{+:MU{]W=~Jea&,}|}:TM0sa`T
{]Na/Saf+{:m*:sSf-~}%}:J{+:MU{]W=~Jea&,}|}:TM1sa`T
M{{+:M];eas!}:T}|U):UM'[T
MN`T
U(:UM'JT
M\"S+ea`,m*\"T
```
The lines correspond to the characters `01(|)*` (in that order). [Try it online!](http://cjam.tryitonline.net/#code=bCIwMSh8KSoiIgoKe11OYS9TYWYrezptKjpzU2Ytfn0lfTpKeys6TVV7XVc9fkplYSYsfXx9OlRNMHNhYFQKe11OYS9TYWYrezptKjpzU2Ytfn0lfTpKeys6TVV7XVc9fkplYSYsfXx9OlRNMXNhYFQKTXt7KzpNXTtlYXMhfTpUfXxVKTpVTSdbVApNTmBUClUoOlVNJ0pUCk1cIlMrZWFzLCltKjpzU2YtTHxcIlQKCiJOJWVyc34&input=KDB8MTEpKg&args=MDExMDExMDAw&debug=on)
This uses no built-in regular expression or other types of pattern matching. In fact, CJam has neither of these features. Instead, it starts from the regular expression it represents and builds all possible strings it *could* match, to finally check if the user input is one of them.
### Test runs
The following uses a program that reads a regular expression from STDIN, replaces each of its characters by the proper snippet, and finally evaluates the generated code to see if it matches the input specified in the command line argument.
```
$ cat regex.cjam
l"01(|)*""
{]Na/Saf+{:m*:sSf-~}%}:J{+:MU{]W=~Jea&,}|}:TM0sa`T
{]Na/Saf+{:m*:sSf-~}%}:J{+:MU{]W=~Jea&,}|}:TM1sa`T
M{{+:M];eas!}:T}|U):UM'[T
MN`T
U(:UM'JT
M\"S+ea`,m*\"T
"N%ers~
$ cjam regex.cjam '' <<< '(|)'
1
$ cjam regex.cjam '0' <<< '(|)'
0
$ cjam regex.cjam '' <<< '0(|)'
0
$ cjam regex.cjam '0' <<< '0(|)'
1
$ cjam regex.cjam '' <<< '(0|11)*'
1
$ cjam regex.cjam '0' <<< '(0|11)*'
1
$ cjam regex.cjam '11' <<< '(0|11)*'
1
$ cjam regex.cjam '011011000' <<< '(0|11)*'
1
$ cjam regex.cjam '1010' <<< '(0|11)*'
0
```
Unfortunately, this isn't particularly fast. It will choke rather quickly if there are more than 9 characters in the input or more than a single Kleene star in the regex.
At the cost of 5 extra bytes – for a total of **156 bytes** – we can generate shorter strings to match the potential input against and deduplicate them. This doesn't change how the code works; it just makes it more efficient.
```
$ cat regex-fast.cjam
l"01(|)*""
{]Na/Saf+{:m*:sSf-~}%}:J{+:MU{]W=~Jea&,}|}:TM0sa`T
{]Na/Saf+{:m*:sSf-~}%}:J{+:MU{]W=~Jea&,}|}:TM1sa`T
M{{+:M];eas!}:T}|U):UM'[T
MN`T
U(:UM'JT
M\"S+eas,)m*:sSf-L|\"T
"N%ers~
$ cjam regex-fast.cjam '0101001010' <<< '(01|10)*'
0
$ cjam regex-fast.cjam '011001101001' <<< '(01|10)*'
1
$ cjam regex-fast.cjam '0' <<< '(0*1)*'
0
$ time cjam regex-fast.cjam '101001' <<< '(0*1)*'
1
```
] |
[Question]
[
# Definition
There is infinite row of concatenated natural numbers (positive integers, starting with 1):
`1234567891011121314151617181920212223...`
# Challenge
* Write program in any language, that accepts position number as an input, and outputs digit from that position in the row defined above.
* Position number is arbitrary size positive integer. That is first position is 1, yielding output digit '1'
* Input is either in decimal (eg. 13498573249827349823740000191), or e-notation (eg. 1.2e789) corresponding to positive integer.
* Program has to end in reasonable time (10 seconds on modern PC/Mac), given very large index as an input (eg. 1e123456 - that is 1 with 123456 zeroes). So, **simple iteration loop is not acceptable.**
* Program has to terminate with an error in 1 s, if given any invalid input. Eg. 1.23e (invalid), or 1.23e1 (equals to 12.3 - not an integer)
* It's ok to use public BigNum library to parse/store numbers and do simple mathematical operations on them (+-\*/ exp). No byte-penalty applied.
* Shortest code wins.
# TL;DR
* Input: bignum integer
* Output: digit at that position in infinite row `123456789101112131415...`
# Some acceptance test cases
in notation "Input: Output". All of them should pass.
* 1: 1
* 999: 9
* 10000000: 7
* 1e7: 7 (same as row above)
* 13498573249827349823740000191: 6
* 1.1e10001: 5
* 1e23456: 5
* 1.23456e123456: 4
* 1e1000000: 0
* 1.23e: error (invalid syntax)
* 0: error (out of bounds)
* 1.23e1: error (not an integer)
# Bonus!
Output digit position number inside the number, and output number itself.
For example:
* `13498573249827349823740000191: 6 24 504062383738461516105596714`
+ That's digit '6' at position 24 of number '50406238373846151610559**6**714'
* `1e1000000: 0 61111 1000006111141666819445...933335777790000`
+ Digit '0' at position 61111 of 999995-digit long number I'm not going to include here.
If you fulfill the bonus task, multiply size of your code by 0.75
# Credit
This task was given at one of devclub.eu gatherings in year 2012, without large number requirement. Hence, most answers submitted were trivial loops.
# Have fun!
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 78 bytes
```
r_A,s-" e . .e"S/\a#[SSS"'./~'e/~i1$,-'e\]s"0]=~~_i:Q\Q=Qg&/
s,:L{;QAL(:L#9L*(*)9/-_1<}g(L)md_)p\AL#+_ps=
```
The program is 104 bytes long and qualifies for the bonus.
The newline is purely cosmetic. The first line parses the input, the second generates the output.
[Try it online!](https://tio.run/##FcfBCoMgAIDhVwkby1pmZsPp1sG7F/E4Q2KTaBDEPI756q79l4//8ZrWlN5O1gGBzGdN1nhgsJ3yuzEGFA2OhcdxIYcaFd6OAbTjEKNbhLZ60PMRh1qoz1VLBYXKuapgVXKMHLl9Z6jK9enKzUqVn9wWhpQI7fnlzGi307H/dJT17R7h5Ac "CJam – Try It Online")
### Idea
For any positive integer **k**, there are **9×10k-1** positive integers of exactly **k** digits (not counting leading zeroes). Thus, if we concatenate all of them, we obtain an integer of **9×n×10k-1**.
Now, concatenating all integers of **n** or less digits yields an integer of

digits.
For a given input **q**, we try determine the highest **n** such that the above expression is smaller than **q**. We set **n := ⌈log10q⌉-1**, then **n := ⌈log10q⌉-2**, etc. until the desired expression becomes smaller than **q**, subtract the resulting expression from **q** (yielding **r**) and save the last value of **n** in **l**.
**r** now specifies the index in the concatenation of all positive integers of **l+1** digits, which means that the desired output is the **r%(l+1)**th digit of the **r/(l+1)**th integer of **l+1** digits.
### Code (input parsing)
```
r_ e# Read from STDIN and duplicate.
A,s- e# Remove all digits.
" e . .e"S/ e# Push ["" "e" "." ".e"].
\a# e# Compute the index of the non-digit part in this array.
[SSS"'./~'e/~i1$,-'e\]s"0]
e# Each element corresponds to a form of input parsing:
e# 0 (only digits): noop
e# 1 (digits and one 'e'): noop
e# 2 (digits and one '.'): noop
e# 3 (digits, one '.' then one 'e'):
e# './~ Split at dots and dump the chunks on the stack.
e# 'e/~ Split the and chunks at e's and dump.
e# i Cast the last chunk (exponent) to integer.
e# 1$ Copy the chunk between '.' and 'e' (fractional part).
e# ,- Subtract its length from the exponent.
e# 'e\ Place an 'e' between fractional part and exponent.
e# ]s Collect everything in a string.
e# -1 (none of the above): push 0
~ e# For s string, this evaluates. For 0, it pushes -1.
~ e# For s string, this evaluates. For -1, it pushes 0.
e# Causes a runtime exception for some sorts of invalid input.
_i:Q e# Push a copy, cast to Long and save in Q.
\Q= e# Check if Q is numerically equal to the original.
Qg e# Compute the sign of Q.
& e# Logical AND. Pushes 1 for valid input, 0 otherwise.
/ e# Divide by Q the resulting Boolean.
e# Causes an arithmetic exception for invalid input.
```
### Code (output generation)
```
s,:L e# Compute the number of digits of Q and save in L.
{ e# Do:
; e# Discard the integer on the stack.
Q e# Push Q.
AL(:L# e# Push 10^(L=-1).
9L*( e# Push 9L-1.
*) e# Multiply and increment.
9/ e# Divide by 9.
- e# Subtract from Q.
_1< e# Check if the difference is non-positive.
}g e# If so, repeat the loop.
( e# Subtract 1 to account for 1-based indexing.
L)md e# Push quotient and residue of the division by L+1.
_)p e# Copy, increment (for 1-based indexing) and print.
\AL#+ e# Add 10^L to the quotient.
_p e# Print a copy.
s e# Convert to string.
2$= e# Retrieve the character that corresponds to the residue.
```
[Answer]
# CJam, 75 \* 0.75 = 56.25
This is quite fast, one iteration per digit of the number that contains the desired position. I'm sure it can be golfed a lot more, it's quite crude as it is.
```
q~_i_@<{0/}&:V9{VT>}{T:U;_X*T+:T;A*X):X;}w;U-(_X(:X/\X%10X(#@+s_2$\=S+@)S+@
```
Give the position as input, the output is:
```
<digit> <position> <full number>
```
[Try it online](http://cjam.aditsu.net/#code=q~_i_%40%3C%7B0%2F%7D%26%3AV9%7BVT%3E%7D%7BT%3AU%3B_X*T%2B%3AT%3BA*X)%3AX%3B%7Dw%3BU-(_X(%3AX%2F%5CX%2510X(%23%40%2Bs_2%24%5C%3DS%2B%40)S%2B%40&input=13498573249827349823740000191).
] |
[Question]
[
A new code-golfer, Joe, just registered to the site. He has 1 reputation but determined to reach all his lucky numbers in reputation exactly. Joe believes in higher powers which will help him to achieve his goal with minimal amount of (his or others) actions. As a new user he also believes that negative reputation is possible.
You should write a program or function which helps Joe to compute how many action should he expect.
## Details
* The actions can change the reputation by the following amounts (all actions are available at every step regardless of stackexchange rules):
```
answer accepted: +15
answer voted up: +10
question voted up: +5
accepts answer: +2
votes down an answer: −1
question voted down: −2
```
* Other special reputation changes are disregarded.
* Lucky numbers can be negative and can be reached in any order.
* **Your solution has to solve any example test case under a minute** on my computer (I will only test close cases. I have a below-average PC.).
## Input
* Joe's lucky numbers as a list of integers in a common form of your language.
## Output
* The number of minimum actions needed as a single integer.
* Output could be printed to stdout or returned as an integer.
## Examples
Input => Output (Example reputation states)
```
1 => 0 (1)
3 2 1 => 2 (1 -> 3 -> 2)
2 10 50 => 7 (1 -> 3 -> 2 -> 12 -> 10 -> 25 -> 40 -> 50)
10 11 15 => 3 (1 -> 11 -> 10 -> 15)
42 -5 => 7 (1 -> -1 -> -3 -> -5 -> 10 -> 25 -> 40 -> 42)
-10 => 6 (1 -> -1 -> -3 -> -5 -> -7 -> -9 -> -10)
15 -65 => 39
7 2015 25 99 => 142
-99 576 42 1111 12345 => 885
```
This is code-golf so the shortest entry wins.
[Answer]
# Rust, ~~929~~ 923 characters
```
use std::io;use std::str::FromStr;static C:&'static [i32]=&[-2,-1,2,5,10,15];fn main(){let mut z=String::new();io::stdin().read_line(&mut z).unwrap();let n=(&z.trim()[..]).split(' ').map(|e|i32::from_str(e).unwrap()).collect::<Vec<i32>>();let l=*n.iter().min().unwrap();let x=n.iter().max().unwrap()-if l>1{1}else{l};let s=g(x as usize);println!("{}",p(1,n,&s));}fn g(x:usize)->Vec<i32>{let mut s=vec![std::i32::MAX-9;x];for c in C{if *c>0&&(*c as usize)<=x{s[(*c-1)as usize]=1;}}let mut i=1us;while i<x{let mut k=i+1;for c in C{if(i as i32)+*c<0{continue;}let j=((i as i32)+*c)as usize;if j<x&&s[j]>s[i]+1{s[j]=s[i]+1;if k>j{k=j;}}}i=k;}s}fn p(r:i32,n:Vec<i32>,s:&Vec<i32>)->i32{if n.len()==1{h(r,n[0],&s)}else{(0..n.len()).map(|i|{let mut m=n.clone();let q=m.remove(i);p(q,m,&s)+h(r,q,&s)}).min().unwrap()}}fn h(a:i32,b:i32,s:&Vec<i32>)->i32{if a==b{0}else if a>b{((a-b)as f32/2f32).ceil()as i32}else{s[(b-a-1)as usize]}}
```
This was fun!
---
## Commentary on the implementation
So I'm obviously not too happy with the size. But Rust is absolutely terrible at golfing anyway. The performance, however, is wonderful.
The code solves each of the test cases correctly in a near-instantaneous amount of time, so performance is obviously not an issue. For fun, here's a much more difficult test case:
```
1234567 123456 12345 1234 123 777777 77777 7777 777
```
for which the answer is `82317`, which my program was able to solve on my (medium-performance) laptop in **1.66 seconds** (!), even with the recursive brute-force Hamiltonian path algorithm.
## Observations
* First we should build a modified weighted graph, with the nodes being each "lucky" number and the weights being how many changes it takes to get from one reputation level to another. Each pair of nodes must be connected by *two* edges, since going up is not the same as going down in reputation value (you can get +10, for example, but not -10).
* Now we need to figure out how to find the minimum amount of changes from one rep value to another.
+ For getting from a higher value to a lower value, it's simple: just take `ceil((a - b) / 2)` where `a` is the higher value and `b` is the lower value. Our only logical option is to use the -2 as much as possible, and then the -1 once if necessary.
+ A low to high value is a bit more complicated, since using the greatest possible value is not always optimal (ex. for 0 to 9, the optimal solution is +10 -1). However, this is a textbook dynamic programming problem, and simple DP is enough to solve it.
* Once we have calculated the minimum changes from each number to every other number, we are essentially left with a slight variant of TSP (travelling salesman problem). Luckily, there are a small enough number of nodes (a maximum of 5 in the hardest test case) that brute force is sufficient for this step.
## Ungolfed code (heavily commented)
```
use std::io;
use std::str::FromStr;
// all possible rep changes
static CHANGES: &'static [i32] = &[-2, -1, 2, 5, 10, 15];
fn main() {
// read line of input, convert to i32 vec
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
let nums = (&input.trim()[..]).split(' ').map(|x| i32::from_str(x).unwrap())
.collect::<Vec<i32>>();
// we only need to generate as many additive solutions as max(nums) - min(nums)
// but if one of our targets isn't 1, this will return a too-low value.
// fortunately, this is easy to fix as a little hack
let min = *nums.iter().min().unwrap();
let count = nums.iter().max().unwrap() - if min > 1 { 1 } else { min };
let solutions = generate_solutions(count as usize);
// bruteforce!
println!("{}", shortest_path(1, nums, &solutions));
}
fn generate_solutions(count: usize) -> Vec<i32> {
let mut solutions = vec![std::i32::MAX - 9; count];
// base cases
for c in CHANGES {
if *c > 0 && (*c as usize) <= count {
solutions[(*c-1) as usize] = 1;
}
}
// dynamic programming! \o/
// ok so here's how the algorithm works.
// we go through the array from start to finish, and update the array
// elements at i-2, i-1, i+2, i+5, ... if solutions[i]+1 is less than
// (the corresponding index to update)'s current value
// however, note that we might also have to update a value at a lower index
// than i (-2 and -1)
// in that case, we will have to go back that many spaces so we can be sure
// to update *everything*.
// so for simplicity, we just set the new index to be the lowest changed
// value (and increment it if there were none changed).
let mut i = 1us; // (the minimum positive value in CHANGES) - 1 (ugly hardcoding)
while i < count {
let mut i2 = i+1;
// update all rep-values reachable in 1 "change" from this rep-value,
// by setting them to (this value + 1), IF AND ONLY IF the current
// value is less optimal than the new value
for c in CHANGES {
if (i as i32) + *c < 0 { continue; } // negative index = bad
let idx = ((i as i32) + *c) as usize; // the index to update
if idx < count && solutions[idx] > solutions[i]+1 {
// it's a better solution! :D
solutions[idx] = solutions[i]+1;
// if the index from which we'll start updating next is too low,
// we need to make sure the thing we just updated is going to,
// in turn, update other things from itself (tl;dr: DP)
if i2 > idx { i2 = idx; }
}
}
i = i2; // update index (note that i2 is i+1 by default)
}
solutions
}
fn shortest_path(rep: i32, nums: Vec<i32>, solutions: &Vec<i32>) -> i32 {
// mercifully, all the test cases are small enough so as to not require
// a full-blown optimized traveling salesman implementation
// recursive brute force ftw! \o/
if nums.len() == 1 { count_changes(rep, nums[0], &solutions) } // base case
else {
// try going from 'rep' to each item in 'nums'
(0..nums.len()).map(|i| {
// grab the new rep value out of the vec...
let mut nums2 = nums.clone();
let new_rep = nums2.remove(i);
// and map it to the shortest path if we use that value as our next target
shortest_path(new_rep, nums2, &solutions) + count_changes(rep, new_rep, &solutions)
}).min().unwrap() // return the minimum-length path
}
}
fn count_changes(start: i32, finish: i32, solutions: &Vec<i32>) -> i32 {
// count the number of changes required to get from 'start' rep to 'finish' rep
// obvious:
if start == finish { 0 }
// fairly intuitive (2f32 is just 2.0):
else if start > finish { ((start - finish) as f32 / 2f32).ceil() as i32 }
// use the pregenerated lookup table for these:
else /* if finish > start */ { solutions[(finish - start - 1) as usize] }
}
```
[Answer]
## C# - 501 Bytes
*Update* 551 -> 501 Bytes
```
namespace System.Linq{class A {static void Main(){var i = c(new int[]{10,11,15});Console.WriteLine(i);Console.ReadLine();}private static int c(int[] a){var o=a.OrderBy(x => x).ToArray();int d=1,count=0;for(var i=0;i<a.Length;i++){if(o[i]==d)i++;int c=o[i],b=o.Length>=i+2?o[i+1]-o[i]:3;if(b<=2){i++;c=o[i];}while(d!=c){if(d>c){var e=d-c;if(e>1)d-=2;else d-=1;}else if(c>d){var e=c-d+2;if(e>14)d+=15;else if(e>9)d+=10;else if(e>4)d+=5;else if(e>2)d+=2;}count++;}if(b<=2){d-=b;count++;}}return count;}}}
```
## Ungolfed code
```
namespace System.Linq {
class Program {
static void Main(){
var i = CalculateNumbers(new int[]{10,11,15});
Console.WriteLine(i);
Console.ReadLine();
}
private static int CalculateNumbers(int[] numbers){
var ordered = numbers.OrderBy(x => x).ToArray();
int cur = 1, count = 0;
for (var i = 0; i < numbers.Length; i++){
if (ordered[i] == cur) i++;
int val = ordered[i], next = ordered.Length >= i+2 ? ordered[i + 1] - ordered[i] : 3;
if (next <= 2){
i++;
val = ordered[i];
}
while (cur != val){
if (cur > val){
var dif = cur - val;
if (dif > 1)
cur -= 2;
else
cur -= 1;
} else if (val > cur){
var dif = val - cur + 2;
if (dif > 14)
cur += 15;
else if (dif > 9)
cur += 10;
else if (dif > 4)
cur += 5;
else if (dif > 2)
cur += 2;
}
count++;
}
if (next <= 2){
cur -= next;
count++;
}
}
return count;
}
}
}
```
[Answer]
# C++ - 863 bytes, ungolfed
This runs fairly fast, in the same ballpark as the solution written in Rust (about 6 times as fast when compiling with optimisation turned on). I will golf this later this evening (evening in Sweden, that is).
```
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
const int lookup[] = {0, 2, 1, 2, 2, 1, 3, 2, 2, 2, 1, 3, 2, 2, 2};
int distance(int start, int end) {
return start > end
? (start - end + 1) / 2
: (end - start) / 15 + lookup[(end - start) % 15];
}
int walk(int current, std::vector<int> points) {
int min = 0;
if (points.size() == 0) return 0;
for (int i = 0; i < points.size(); i++) {
std::vector<int> new_points = points;
new_points.erase(new_points.begin() + i);
int d = distance(current, points[i]) + walk(points[i], new_points);
min = min && min < d ? min : d;
}
return min;
}
int main() {
std::vector<int> points;
std::string line;
std::getline(std::cin, line);
std::stringstream ss(line);
int i;
while (ss >> i)
points.push_back(i);
std::cout << walk(1, points) << std::endl;
return 0;
}
```
] |
[Question]
[
Note: *Minor* spoilers for *The Martian* are in this challenge. Read ahead with caution
---
[The Martian](https://en.wikipedia.org/wiki/The_Martian_(Weir_novel)) is a Science Fiction novel about astronaut and botanist extraordinaire, *Mark Watney*, who has been accidentally stranded on Mars. At one point in the book, Mark tries communicating with NASA, but the only means of communication they have is a camera. Mark sends messages by writing on index cards, and, since NASA can rotate the camera 360 degrees, NASA sends replies back by pointing the camera at cards labeled "Yes" or "No".
Since the only data NASA can send is the direction the camera is facing, Mark comes up with a system where they can point at cards with alphabet characters on them to type messages. But using the letters 'a-z' would be impractical. To quote the book (from [this answer](https://scifi.stackexchange.com/a/107677/50357), over on scifi.se):
>
> We’ll need to talk faster than yes/no questions every half hour. The camera can rotate 360 degrees, and I have plenty of antenna parts. Time to make an alphabet. But I can’t just use the letters A through Z. Twenty-six letters plus my question card would be twenty-seven cards around the lander. Each one would only get 13 degrees of arc. Even if JPL points the camera perfectly, there’s a good chance I won’t know which letter they meant.
>
>
> So I’ll have to use ASCII. That’s how computers manage characters. Each character has a numerical code between 0 and 255. Values between 0 and 255 can be expressed as 2 hexadecimal digits. By giving me pairs of hex digits, they can send any character they like, including numbers, punctuation, etc.
>
>
> ...
>
>
> So I’ll make cards for 0 through 9, and A through F. That makes 16 cards to place around the camera, plus the question card. Seventeen cards means over 21 degrees each. Much easier to deal with.
>
>
>
Your goal today, as one of the top software engineers at NASA, is to write a program to encode the various angles of the camera. The seventeen cards Mark has for you to point at are (in order):
```
?0123456789ABCDEF
```
and each of these cards is 21 degrees apart, so to rotate the camera from `?` to `0`, you should rotate the camera 21 degrees, and `2` to `1` is -21 degrees. (It's not *exactly* 21, but we'll round to keep it simpler) This wraps, so to go from `F` to `3` is 105 degrees (5 turns, 5 \* 21 = 105). This is more efficient than going -252, since the camera won't have to move as far.
Here's what your program or function must do.
1. Take a string as input. We'll call this string *s*. To keep it simple, we'll say that the input will only ever be printable ASCII. For our example, let's say that the input was `STATUS`
2. Convert each character to its hexadecimal representation. This would convert `STATUS` to `53 54 41 54 55 53`.
3. Print out or return the consecutive degree turns the camera will need to make in order to point at each card and return to the "Question Card". For our example, this would be:
```
6 * 21 = 126 (?-5)
-2 * 21 = -42 (5-3)
2 * 21 = 42 (3-5)
-1 * 21 = -21 (5-4)
0 * 21 = 0 (4-4)
-3 * 21 = -63 (4-1)
4 * 21 = 84 (1-5)
-1 * 21 = -21 (5-4)
1 * 21 = 21 (4-4)
0 * 21 = 0 (5-5)
0 * 21 = 0 (5-5)
-2 * 21 = -42 (5-3)
-4 * 21 = -84 (3-?)
```
Or, in array format:
```
[126, -42, 42, -21, 0, -63, 84, -21, 21, 0, 0, -42, -84]
```
Note that you must always take the smallest of the possible rotations. So if the input was `NO`, which is `4E 4F`, you should output:
```
5 * 21 = 105
-7 * 21 = -147
7 * 21 = 147
-6 * 21 = -126
1 * 21 = 21
```
Rather than:
```
5 * 21 = 105
10 * 21 = 210
-10 * 21 = -210
11 * 21 = 231
-16 * 21 = -336
```
Here are some more worked examples:
```
Input: CROPS?
ASCII: 43 52 4F 50 53 3F
Worked Example:
5 * 21 = 105
-1 * 21 = -21
2 * 21 = 42
-3 * 21 = -63
2 * 21 = 42
-6 * 21 = -126
7 * 21 = 147
-5 * 21 = -105
5 * 21 = 105
-2 * 21 = -42
0 * 21 = 0
-5 * 21 = -105
1 * 21 = 21
Result: [105 -21 42 -63 42 -126 147 -105 105 -42 0 -105 21]
Input: DDD
ASCII: 44 44 44
Worked Example:
5 * 21 = 105
0 * 21 = 0
0 * 21 = 0
0 * 21 = 0
0 * 21 = 0
0 * 21 = 0
-5 * 21 = -105
Result: [105, 0, 0, 0, 0, 0, -105]
Input: Hello world!
ASCII: 48 65 6c 6c 6f 20 77 6f 72 6c 64 21
Worked example:
5 * 21 = 105
4 * 21 = 84
-2 * 21 = -42
-1 * 21 = -21
1 * 21 = 21
6 * 21 = 126
-6 * 21 = -126
6 * 21 = 126
-6 * 21 = -126
-8 * 21 = -168
4 * 21 = 84
-2 * 21 = -42
7 * 21 = 147
0 * 21 = 0
-1 * 21 = -21
-8 * 21 = -168
-8 * 21 = -168
-5 * 21 = -105
4 * 21 = 84
6 * 21 = 126
-6 * 21 = -126
-2 * 21 = -42
-2 * 21 = -42
-1 * 21 = -21
-2 * 21 = -42
Result: [105 84 -42 -21 21 126 -126 126 -126 -168 84 -42 147 0 -21 -168 -168 -105 84 126 -126 -42 -42 -21 -42]
```
Since NASA prides itself on efficiency, your goal is to write the shortest code possible. Standard loopholes apply. Now bring him home!
[Answer]
# JavaScript (ES6), ~~103~~ 99 bytes
```
s=>[...s.replace(/./g,c=>c.charCodeAt().toString(16)),10].map(n=>((24-p-~(p='0x'+n))%17-8)*21,p=-1)
```
### Test cases
```
let f =
s=>[...s.replace(/./g,c=>c.charCodeAt().toString(16)),10].map(n=>((24-p-~(p='0x'+n))%17-8)*21,p=-1)
let g = s => console.log(`f('${s}'): [${f(s)}]`)
g('STATUS')
g('NO')
g('CROPS?')
g('DDD')
g('Hello world!')
```
[Answer]
# C, ~~212~~ ~~202~~ ~~199~~ 187 bytes
*3 bytes saved thanks to @KritixiLithos!*
```
i;f(a,b){i=abs(a-b);i=8>i?i:17-i;i=a<b&a>b-8?i:a<b&a<b-8?-i:b<a&b>a-8?-i:i;i*=21;}v;g(char*s){for(v=0;*s;s+=v++%2)printf("%d ",v?v%2?f(*s%16,s[1]?s[1]/16:-1):f(*s/16,*s%16):f(-1,*s/16));}
```
[Try it online!](https://tio.run/nexus/c-gcc#JY1BDoIwEEWvYkggbWmjZYGEUohnAFfGxRQDzkI01HRDODu2uJn8999MZkM1EOCGLqjBWALCUIW6qLHBUp4FeoDKJFAbUfhqz1XIAktTQWJq@IPfZDqTanVqJP0TZmbpMrxn4vRJMatsql2axhn9zDh9BxLFj0PEXePirBkIs7HMub3JexPGUealkLQMwme@64BC8r2hVK3bC3AiPXd0f8ecWkbi/HVwW9tdumv7Aw "C (gcc) – TIO Nexus")
[Answer]
# Python, ~~187~~ 178 bytes
```
def g(x):w,z=map('?0123456789abcdef'.index,x);d=w-z;return min(d,d+17*(d<=0 or -1),key=abs)*21
def f(s):s=''.join(map('{:2x}'.format,s.encode()));return[*map(g,zip(s+'?','?'+s))]
```
### Test cases
```
for k in ['STATUS', 'NO', 'CROPS?', 'DDD', 'Hello world!']:
print('Input: {}\nOutput: {}'.format(k, f(k)))
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~135~~ 112 bytes
```
h=reduce(lambda l,r:l+(r/16,r%16),map(ord,input()),())
print[(((r-l+8)%17)-8)*21for l,r in zip((-1,)+h,h+(-1,))]
```
**[Try it online!](https://tio.run/nexus/python2#HcxNCsIwEEDhvaeIi9IZM0Hiohahe@8gLqKJJDBNwtAi9PLxZ/HgW70WJwl@fQZgNz@8U0xyYQ1ytANJZwek2VUo4inlui6ASN92VVJebgAghvWInT2jGfFwsq8iv4dKWW2pAhhLqCNF/RfeW@uvgbmodxH2@/4D)**
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~21~~ 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ob⁴F-;;-I+8%17_8×21
```
**[Try it online!](https://tio.run/nexus/jelly#@@@f9Khxi5uutbWup7aFqqF5vMXh6UaG////90jNyclXKM8vyklRBAA)**
### How?
```
Ob⁴F-;;-I+8%17_8×21 - Main link: string s e.g. 'e.g.'
O - cast to ordinals [101, 46, 103, 46]
b - convert to base
⁴ - 16 [[6, 5], [2, 14], [6, 7], [2, 14]]
F - flatten [6, 5, 2, 14, 6, 7, 2, 14]
-; - -1 concatenate [-1, 6, 5, 2, 14, 6, 7, 2, 14]
;- - concatenate -1 [-1, 6, 5, 2, 14, 6, 7, 2, 14, -1]
I - increments [ 7, -1, -3, 12, -8, 1, -5, 12, -15]
+8 - add 8 [ 15, 7, 5, 20, 0, 9, 3, 20, -7]
%17 - mod 17 [ 15, 7, 5, 3, 0, 9, 3, 3, 10]
_8 - subtract 8 [ 7, -1, -3, -5, -8, 1, -5, -5, 2]
×21 - multiply by 21 [147, -21, -63,-105,-168, 21,-105,-105, 42]
```
[Answer]
# [Ohm](https://github.com/MiningPotatoes/Ohm), ~~20~~ 19 bytes (CP437)
**EDIT**: Saved 1 byte by changing a map block to repeated single-component maps.
Would probably be quite a bit shorter if I had implicit vectorization.
```
`»x»}{»úΓXΓHδ▓_~21*
```
Explanation:
```
`»x»}{»úΓXΓHδ▓_~21* Main wire, arguments: s
`»x Convert char codes of s to hex
»} Split digit pairs
{ Flatten
»ú Convert digits back to base 10
ΓXΓH Append and prepend with -1
δ Get deltas between each element of array
▓ Map array over...
_~21* Negate, multiply by 21
```
[Answer]
# PHP, ~~125~~ 116 bytes:
```
function m($i){static$a;$a+=$d=($i-$a+10)%17-9;echo$d*21,"
";}for(;$c=ord($argv[1][$i++]);m($c%16))m($c/16|0);m(-1);
```
**breakdown**
```
function m($i) // function to turn camera:
{
static$a; // remember angle
$a+= // add delta to angle
$d=($i-$a+10)%17-9; // delta: target=nibble value+1-current angle
// add 9, modulo 17, -9 -> shortest movement
echo$d*21,"\n"; // print delta * 21 and a linebreak
}
for(;$c=ord($argv[1][$i++]);// loop through input characters
m($c%16)) // 2. move to low nibble value
m($c/16|0) // 1. move to high nibble value
;
m(-1); // move back to "?"
```
---
Of course, `21` is pretty inaccurate and may fail for strings longer than 14 characters; but then ... `360/17` would be four bytes longer.
>
> An alternative solution would have been to attach a laser pointer to the camera;
>
> we could use all printable ascii chars and a "question" card at 3.75 degrees each with that.
>
>
> Another alternative: Use 16 cards (at 22.5 degrees) with 6 characters each:
>
> implement some sort of T9 and we can omit the high nibble. ;)
>
>
>
] |
[Question]
[
Given the name of a Stack Exchange site which doesn't have their own design yet, decide how many ASCII characters (non-ASCII ones are counted separately) are there on their icons. Your code should distinguish these 4 cases:
1 character:
```
Astronomy
Beer
Freelancing
Health
History
Law
Music: Practice & Theory
Parenting
The Great Outdoors
Writers
```
2 characters:
```
3D Printing
Amateur Radio
Biblical Hermeneutics
Bitcoin
Board & Card Games
Buddhism
Chinese Language
Coffee
Community Building
Computational Science
Computer Graphics
Data Science
Earth Science
Ebooks
Economics
Emacs
Engineering
Expatriates
French Language
Gardening & Landscaping
Genealogy & Family History
German Language
Hardware Recommendations
Hinduism
Homebrewing
Islam
Italian Language
Japanese Language
Joomla
Lifehacks
Martial Arts
Mathematics Educators
Motor Vehicle Maintenance & Repair
Music Fans
Mythology
Open Data
Personal Productivity
Pets
Philosophy
Physical Fitness
Politics
Portuguese Language
Project Management
Puzzling
Quantitative Finance
Reverse Engineering
Robotics
Russian Language
Software Quality Assurance & Testing
Software Recommendations
Sound Design
Space Exploration
Spanish Language
Sports
Startups
Sustainable Living
Tridion
Vi and Vim
Video Production
Windows Phone
Woodworking
Worldbuilding
```
3 characters:
```
Cognitive Sciences
elementary OS
Ethereum
History of Science and Mathematics
Linguistics
Open Source
Programming Puzzles & Code Golf
Signal Processing
Tor
```
Non-ASCII:
```
Anime & Manga
Arduino
Aviation
Chess
CiviCRM
Poker
```
Excluded in this challenge for having non-ASCII characters in their names:
```
LEGO® Answers
Русский язык
```
Your code should output a consistent distinct value for each of the 4 sets. Each output (or its string representation for non-string values returned from a function) should be no more than 10 bytes, not counting the optional trailing newline.
You can create multiple pieces of code in the same language. The output of your submission is considered to be the output of each piece of code concatenated in a fixed order (so you can use Regex).
Shortest code wins.
[Answer]
## CJam, ~~50~~ ~~48~~ 45 bytes
```
l22b391"þÁ "+{i%}/"Yª>Þÿ9cîÂcVáòe~"322b4b=
```
There's unprintable characters in the strings above, which can be obtained by the snippets
```
[254 193 160]:c
[89 170 62 222 30 255 20 57 99 238 194 99 86 225 242 101 126 20]:c
```
This also shows that the code points are all below 256. Output is `0` for 1 letter, `1` for 2 letters, `2` for 3 letters and `3` for non-ASCII.
The program simply converts the input string to a base 22 number, performs a series of modulos to reduce the number down, before performing a lookup from a base-4 encoded table.
[Try it online](http://cjam.aditsu.net/#code=l22b391%22%C3%BE%C3%81%C2%A0%22%2B%7Bi%25%7D%2F%22Y%C2%AA%3E%C3%9E%1E%C3%BF%149c%C3%AE%C3%82cV%C3%A1%C3%B2e~%14%22322b4b%3D&input=Anime%20%26%20Manga) | [Test suite](http://cjam.aditsu.net/#code=87%7B%0A%0Al22b391%22%C3%BE%C3%81%C2%A0%22%2B%7Bi%25%7D%2F%22Y%C2%AA%3E%C3%9E%1E%C3%BF%149c%C3%AE%C3%82cV%C3%A1%C3%B2e~%14%22322b4b%3D%0A%0A%7D*%5DN*&input=Astronomy%0ABeer%0AFreelancing%0AHealth%0AHistory%0ALaw%0AMusic%3A%20Practice%20%26%20Theory%0AParenting%0AThe%20Great%20Outdoors%0AWriters%0A3D%20Printing%0AAmateur%20Radio%0ABiblical%20Hermeneutics%0ABitcoin%0ABoard%20%26%20Card%20Games%0ABuddhism%0AChinese%20Language%0ACoffee%0ACommunity%20Building%0AComputational%20Science%0AComputer%20Graphics%0AData%20Science%0AEarth%20Science%0AEbooks%0AEconomics%0AEmacs%0AEngineering%0AExpatriates%0AFrench%20Language%0AGardening%20%26%20Landscaping%0AGenealogy%20%26%20Family%20History%0AGerman%20Language%0AHardware%20Recommendations%0AHinduism%0AHomebrewing%0AIslam%0AItalian%20Language%0AJapanese%20Language%0AJoomla%0ALifehacks%0AMartial%20Arts%0AMathematics%20Educators%0AMotor%20Vehicle%20Maintenance%20%26%20Repair%0AMusic%20Fans%0AMythology%0AOpen%20Data%0APersonal%20Productivity%0APets%0APhilosophy%0APhysical%20Fitness%0APolitics%0APortuguese%20Language%0AProject%20Management%0APuzzling%0AQuantitative%20Finance%0AReverse%20Engineering%0ARobotics%0ARussian%20Language%0ASoftware%20Quality%20Assurance%20%26%20Testing%0ASoftware%20Recommendations%0ASound%20Design%0ASpace%20Exploration%0ASpanish%20Language%0ASports%0AStartups%0ASustainable%20Living%0ATridion%0AVi%20and%20Vim%0AVideo%20Production%0AWindows%20Phone%0AWoodworking%0AWorldbuilding%0ACognitive%20Sciences%0Aelementary%20OS%0AEthereum%0AHistory%20of%20Science%20and%20Mathematics%0ALinguistics%0AOpen%20Source%0AProgramming%20Puzzles%20%26%20Code%20Golf%0ASignal%20Processing%0ATor%0AAnime%20%26%20Manga%0AArduino%0AAviation%0AChess%0ACiviCRM%0APoker)
[Answer]
# Retina, ~~146~~ ~~136~~ ~~134~~ ~~130~~ ~~124~~ ~~107~~ 102 bytes
```
A\w*i|Che|CR|ke
4
my|Be|lan|^H.*y$|lt|aw|:|Pa|Ou|Wr
1
gn.|^e|Et|^H.*S|gui|rc|lf|To
2
.*(\d).*
$1
..+
3
```
Thanks @Sp3000 for golfing off 4 bytes!
Thanks @Mwr247 for golfing off 17 bytes by letting me use regexes from [his answer](https://codegolf.stackexchange.com/a/74706/48836)!
Thanks @jimmy23013 for golfing off 5 bytes by reminding me that I can change output values!
The output is 1, 3, 2, and 4 for 1-char, 2-char, 3-char, and non-ASCII, respectively.
Version with all testcases has edits in few places to make it work with multiple lines.
[Try it online!](http://retina.tryitonline.net/#code=QVx3Kml8Q2hlfENSfGtlCjQKbXl8QmV8bGFufF5ILip5JHxsdHxhd3w6fFBhfE91fFdyCjEKZ24ufF5lfEV0fF5ILipTfGd1aXxyY3xsZnxUbwoyCi4qKFxkKS4qCiQxCi4uKwoz&input=ZWxlbWVudGFyeSBPUw)
[Try it online with all testcases!](http://retina.tryitonline.net/#code=bWBBXHcqaXxDaGV8Q1J8a2UKNAptYG15fEJlfGxhbnxeSC4qeSR8bHR8YXd8OnxQYXxPdXxXcgoxCm1gZ24ufF5lfEV0fF5ILipTfGd1aXxyY3xsZnxUbwoyCi4qKFxkKS4qCiQxCi4uKwoz&input=QXN0cm9ub215CkJlZXIKRnJlZWxhbmNpbmcKSGVhbHRoCkhpc3RvcnkKTGF3Ck11c2ljOiBQcmFjdGljZSAmIFRoZW9yeQpQYXJlbnRpbmcKVGhlIEdyZWF0IE91dGRvb3JzCldyaXRlcnMKM0QgUHJpbnRpbmcKQW1hdGV1ciBSYWRpbwpCaWJsaWNhbCBIZXJtZW5ldXRpY3MKQml0Y29pbgpCb2FyZCAmIENhcmQgR2FtZXMKQnVkZGhpc20KQ2hpbmVzZSBMYW5ndWFnZQpDb2ZmZWUKQ29tbXVuaXR5IEJ1aWxkaW5nCkNvbXB1dGF0aW9uYWwgU2NpZW5jZQpDb21wdXRlciBHcmFwaGljcwpEYXRhIFNjaWVuY2UKRWFydGggU2NpZW5jZQpFYm9va3MKRWNvbm9taWNzCkVtYWNzCkVuZ2luZWVyaW5nCkV4cGF0cmlhdGVzCkZyZW5jaCBMYW5ndWFnZQpHYXJkZW5pbmcgJiBMYW5kc2NhcGluZwpHZW5lYWxvZ3kgJiBGYW1pbHkgSGlzdG9yeQpHZXJtYW4gTGFuZ3VhZ2UKSGFyZHdhcmUgUmVjb21tZW5kYXRpb25zCkhpbmR1aXNtCkhvbWVicmV3aW5nCklzbGFtCkl0YWxpYW4gTGFuZ3VhZ2UKSmFwYW5lc2UgTGFuZ3VhZ2UKSm9vbWxhCkxpZmVoYWNrcwpNYXJ0aWFsIEFydHMKTWF0aGVtYXRpY3MgRWR1Y2F0b3JzCk1vdG9yIFZlaGljbGUgTWFpbnRlbmFuY2UgJiBSZXBhaXIKTXVzaWMgRmFucwpNeXRob2xvZ3kKT3BlbiBEYXRhClBlcnNvbmFsIFByb2R1Y3Rpdml0eQpQZXRzClBoaWxvc29waHkKUGh5c2ljYWwgRml0bmVzcwpQb2xpdGljcwpQb3J0dWd1ZXNlIExhbmd1YWdlClByb2plY3QgTWFuYWdlbWVudApQdXp6bGluZwpRdWFudGl0YXRpdmUgRmluYW5jZQpSZXZlcnNlIEVuZ2luZWVyaW5nClJvYm90aWNzClJ1c3NpYW4gTGFuZ3VhZ2UKU29mdHdhcmUgUXVhbGl0eSBBc3N1cmFuY2UgJiBUZXN0aW5nClNvZnR3YXJlIFJlY29tbWVuZGF0aW9ucwpTb3VuZCBEZXNpZ24KU3BhY2UgRXhwbG9yYXRpb24KU3BhbmlzaCBMYW5ndWFnZQpTcG9ydHMKU3RhcnR1cHMKU3VzdGFpbmFibGUgTGl2aW5nClRyaWRpb24KVmkgYW5kIFZpbQpWaWRlbyBQcm9kdWN0aW9uCldpbmRvd3MgUGhvbmUKV29vZHdvcmtpbmcKV29ybGRidWlsZGluZwpDb2duaXRpdmUgU2NpZW5jZXMKZWxlbWVudGFyeSBPUwpFdGhlcmV1bQpIaXN0b3J5IG9mIFNjaWVuY2UgYW5kIE1hdGhlbWF0aWNzCkxpbmd1aXN0aWNzCk9wZW4gU291cmNlClByb2dyYW1taW5nIFB1enpsZXMgJiBDb2RlIEdvbGYKU2lnbmFsIFByb2Nlc3NpbmcKVG9yCkFuaW1lICYgTWFuZ2EKQXJkdWlubwpBdmlhdGlvbgpDaGVzcwpDaXZpQ1JNClBva2Vy)
[Answer]
# Javscript ES6, ~~342~~ ~~339~~ ~~330~~ 327 bytes
```
a=>{for(c of "9As4BebFr6He7Hi3LaoMu9PaiTh7Wrzb3DdAmlBi7BiiBo8BugCh6CoiColCohCocDadEa6Eb9Ec5EmbEnbExfFrnGaqGefGeoHa8HibHo5IsgIthJa6Jo9LicMalMayMoaMu9My9OplPe4PeaPhgPh8PojPoiPr8PukQujRe8RogRu10SooSocSohSpgSp6Sp8StiSu7TraVigVidWibWodWoziCodel8EtyHibLibOpvPrhSi3To".split`z`)if(~c.indexOf(a.length.toString(36)+a[0]+a[1]))return c}
```
Returns a long string starting with `9` for one character, a different long string starting with `b` for two, a third string starting with`i` for three, and simply `undefined` for non-ascii.
[Answer]
## PowerShell, ~~212~~ 181 bytes
```
$a=-join$args[0][0,2,-1];$b="Aty,Ber,Feg,Hah,Hsy,Lww,Msy,Prg,Tes,Wis,Cgs,eeS,Ehm,Hss,Lns,Oee,Pof,Sgg,Trr,Aia,Ado,Ain,Ces,CvM,Pkr".IndexOf($a);(((1,3)[$b-ge40],4)[$b-ge76],2)[$b-lt0]
```
I found that if you take the first, third, and last characters of each of the possible entries (`[0,2,-1]` when zero-indexed), we obtain a unique three-letter string for each entry. We then are simply using a string-based lookup to determine which one we have.
Takes input `$args[0]`, and applies the above unique-ness function, saves as `$a`.
This is then sent through our lookup list via `.IndexOf($a)` and the result stored in `$b`. Then, we go through a pseudo-ternary that indexes based on the value of `$b` to output the appropriate value.
Outputs `1`, `2`, `3`, and `4` for one-character, two-character, three-character, non-ASCII, respectively.
Edit - discovered that `[0,2,-1]` creates a unique three-character string for each entry, saving 31 bytes
[Answer]
# JavaScript (ES6), 108 bytes
```
a=>[/A\w*i|Che|CR|ke/,/my|Be|lan|^H.*y$|lt|aw|:|Pa|Ou|Wr/,/gn.|^e|Et|^H.*S|gui|rc|lf|To/].map(b=>+b.test(a))
```
Creates an array composed of regex matches unique to each of the three smallest groups (1 character, 3 character, and non-ascii), then maps a test on the data for each array. When the output is stringified, it evaluates to `1,0,0` for non-ascii, `0,1,0` for 3 characters, `0,0,1` for 1 character, and `0,0,0` for 2 characters.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 41 bytes
```
ȷ;€ȷḥ€ɠḋ“¥ẏ⁻ỵŻŀ]Ḥ6Iɠçịƥṃƈ=ẈQk®bȷƥ!?’b5¤%5
```
[Try it online!](https://tio.run/##AWIAnf9qZWxsef//yLc74oKsyLfhuKXigqzJoOG4i@KAnMKl4bqP4oG74bu1xbvFgF3huKQ2Scmgw6fhu4vGpeG5g8aIPeG6iFFrwq5iyLfGpSE/4oCZYjXCpCU1//9QdXp6bGluZw "Jelly – Try It Online")
Full program: input from standard input, output to standard output. Output is 1/2/3/0 for 1 character / 2 characters / 3 characters / non-ASCII.
## Discussion
Hey, I found another question where my algorithm for automatically generating answers to "map this input to that output" questions beats all the existing answers. So here we go.
I used [this generator](https://tio.run/##xVZNbxRHEL3vr2itBNoVi2ODOASLw2LsNRYbHBvZSoBEvTO9M23PdI/6w@vlRCJFOXDjxCGRckhuUaSIgEGRcjBCIj/D/iObV92z6zVE5Bit5emPquqqV6@qe08UxXgyOX38w81CW6tLNpSFE4YJlehUmIVGo2syXwrl7PXG8XN2gxXSOqaHTKrKO8taXI2ZG1ei3WmcfvPHnECijRG20iqVKmPau3@RfwF55csBToRGBRfkoBBnwqWHrYFglZGlaLPLLPVVIRPuhGXcCJzhlRMp0yoRHcZVysbas5KPGU9TJg6d4TNjUtGmgU6qS46Zy7kLVpQ4gAPewpAcBgsjaXPy7yX82yCM4IHODC@jUkQHLqjaOow7TVN8RQZjwbxghqtMsMWFha8o1pbxCkoOLpSVRJwOUXWY1fAAZysdYs10MRRpgOfoP4//6HlTp2ofW3QAXACIhlISzXTYAHsheG5ZxU1IHhkbSsWL6cltUOEeFkt@KEtfzmWtJoK0yHwpKRs4dWlxcZGc0gYsooWS74tgtXZmGhCHlnNFDFtCtrVHOU/yEAkpWJGAQ1OnXG6EYO@OLBmFMjcUfu3NQBR6RBszdWmnjk8TBdjYNs/EOUg7bJQLReB0iGtgO6Q@RP5MDAxxOTIG/tTlMVM8gy4TShhOiJyvLnj0mXbievCP5ZwOsyUviuB3IihWZBI0xflDLgtkq4OsiRizxdQjcGDqjDwExqw1EAlHDmufMbJsILPLAsUHAgy4pVpRoLmVWtn21Bj5WggeKjSVmUTuI5GgfAYq7XKwqvEFSiOBvSFODWHCN09lGNy2cEh5hDHukE8hj1SGHPQeRZp8Ms0@l4EVTSOMLopmDVoA5/Txjw20mo3l029/fXd08uoXfI9fswtgdAONqkRN9EPgrd5aC8KMqI6NdofR7Pj5m@@h8fbpyetnYZk9@Kg8ivz4xcHp779R99r98kzv@KW5YZ1pgfEt6mmtst1eQEMJ6fg60WI4lIlE6lvthUIO8bm0BKXAgpYRFTQXgh7UMC14IlpN1uw0m212iTVPXn3XxNfQeHDl2uLJn0/ePNt44K8sLqXhf7IcP@@O5pH4@6eTV0@i1PLynPSntfRgZvT45wtz0dYqtBtXj05e/xWCxWbwttlc2NNSEUTLywRAG6O3T3cCGBhOJpP7zS4Q0UqXY8RxUwiDzxoKskD@gQpm64IXLqcBQteG5O7wEf73vZXJdbZpeOIkOH6RoSqjwCaasHJRn0q1ZwS63F3vUq2NxeKuQV@hUaPRvHoLNuRUvIsaEGjqW@CwJp9wf@B@KNi6MChL4XGWDesuQXA00tykOH2FPj1eirDt0xS1WGK4kkslUC530EE8@gQt6eFQxEFZeiXdmN30skijC1gEpblDYeHcbaJEImbrKKCe4VUe3bjFHZ8TWUW3zefnA633SW41IZCjzmrJ41dl8EyYeOrqYUWkppsw5kAl@bzPPYQnFFXuRVpObcKrqNkDLLzQ2Rg7a7yU6BdnueoBNhT4nKF1GBrRLbmFPlwC0zSEakOKVeojauu6FAMjRvGI27bgtHrb8UKeN7fBK/4@vhsanY4TU@RQ5DwJEPSBjQSgXePiFC0CyQYmbDX1eAJEavQ1BmxHAGBcIn1OF6IKTfQiPKY@M@Uegg1e98cu1xQ/xncrtHNKCrEQDAsp3DQaBzh5gESH9eDAZi7RxHWVh7V8bAPN1qRDNGFf4yKLGdvUxvnMvxclzO6JxMFHhQW6M2jRP3pURNA@9xysJiIdCNgNQWB5ix4nsHQ@/Vt6oOvTtjxeTedB3tZDF3IGmwXRtWutNzUq94Sti2cm9mFqt/GwStktYWVGRbNdoXsxcK7QJsjENYVn0rlzKx2zte2QPV@FIa4BZIXTu@4OMI1VbmQarezI8GzbkWWYpELP8A/7u@CYHlm2mWtFR@xqnY602Y92drUp0sGsFtEeVnSGAiUI67IiH0QR8OZmzO5uU/GAS0b48qxN0ZVbKwR/5ugWeIkQIRhngTQAyCR1Wul9UFKphWziHkR3wcuK9fCkIQSAYaQVvLE1ANoEd7sKT0DIgxQZkbBrUFGKOln3QE6RXskjxVYA38pWPzBsH7334eT@UufDX4Nd6fx/vwa72nn/12CLndnv4eTapNnE3z8 "Jelly – Try It Online") (which I wrote myself) in order to automatically generate this output. For information on the underlying algorithm and how it works, see [this answer](https://codegolf.stackexchange.com/a/214222) and [this answer](https://codegolf.stackexchange.com/a/220588).
This question isn't an ideal fit for the algorithm in question, incidentally. There are two issues which mean that it could well be beatable.
The first issue is that 4 (the number of possible outputs) is not a prime number. The algorithm *itself* doesn't technically require the number of outputs to be prime, just a prime power (because we need a finite field of the appropriate size). 4 is a prime power (2²), so it would be an ideal fit for the question. However, Jelly doesn't have any builtins for operating on **GF**(4), so we're using **GF**(5) instead, which multiplies the size of our long constant by a factor of log(5)/log(4), an increase of about 16%.
The second issue is that 2 is an overwhelmingly common output, with most of the inputs mapping to it. The algorithm doesn't care about this at all, and works equally well with any distribution of outputs. However, an output that *did* care about this fact could probably take advantage of it in order to use a shorter constant string. Although it's easy to imagine what such an algorithm could look like (and it could use almost the same program shell), I can't think of any efficient way to calculate the string constant that most of the program is built around.
Of course, there's also the fact that the total amount of data required is so small that the overhead of the decompressor is rather notable, and a less efficient algorithm could beat it simply by needing a smaller amount of boilerplate!
So I imagine there's scope for improvement here, although I can't immediately see how. It's still interesting to see a machine-generated solution beating all the human-written solutions, though.
## Explanation
```
ȷ;€ȷḥ€ɠḋ“…’b5¤%5
ȷ;€ȷ Generate 1000 different (arbitrary) hash configurations
ḥ Hash
ɠ standard input
€ using each of the hash configurations
ḋ Take the dot product of the resulting vector of 1000 hashes
¤ with
“…’b5 a particular list of numbers in the range 0…4 inclusive
%5 {The output is} that dot product, modulo 5
```
The long list of numbers is chosen to give the correct output for every input (by asking a computer, specifically my generator written in a mix of Jelly and Sage, to find a short list that happens to give the correct input/output mapping).
] |
[Question]
[
Time for another Pyth practice. I present here 8 problem statements with a Pyth solution each. These solutions are written by a Pyth beginner. He is quite happy about these solutions, since they are a lot shorter than his Python answers. Your task however is to show him better. Create equivalent but shorter programs.
This is a challenge about the the tricks and optimizations that can be used when golfing in Pyth. Pyth golfers may recognize many of the tricks involved, that lead to shorter solutions. However some problems will require some unusual approaches that are rarely used. Some of the tricks I've actually never seen in the wild. But no solution requires any bugs or strange behavior, that was not intentional by the designer(s) of Pyth. All answers must be valid for the most recent Pyth commit ([2b1562b](https://github.com/isaacg1/pyth/commit/2b1562bbe275d2bec3bb4e9432b89771338f221a)) as of this question's posting. You can use the [Pyth interpreter](http://pyth.herokuapp.com) for testing. It is up-to-date right now and I don't expect any big changes in Pyth, that will invalidate optimal solutions or make shorter solutions possible. The online interpreter also features the new Character Reference. Since it is pretty new, you can (should) also use [the old docs](https://github.com/isaacg1/pyth/blob/5a30b8e87ac1c3f72845f5f10536ac370c2a7919/doc.txt), in case something is incorrect or missing.
**Goal:** The reference solutions total 81 bytes. Your goal is to beat that by as much as possible. The submission that solves all 8 problems with the smallest total number of bytes wins. Tiebreaker is the submission date.
Of course only submissions are valid, which contain solutions for all 8 problems. You can use the reference implementation, if you can't improve the score of one (or more) particular problem.
Your solutions must print the exact same output as the reference solutions. Except for an optional trailing newline.
Since this is a Pyth practice, only programs written in the language Pyth are allowed.
**Answering:** Please spoiler your entire answer, except for your total score. It is intended that you do not look at other people's answers before submitting your own. You can create spoilers by putting >! in front of every line, like:
```
>! Problem 1: V9m?>dNd0S9 (11 bytes)
>! Problem 2: VTN)VGN (7 bytes)
>! ...
```
I hope I haven't chosen too difficult or too trivial problems. Hoping for a lots of participators and for everyone to gain a few new insights into Pyth. **Happy golfing!**
### Problem 1:
Create the following 9x9 matrix and print it:
```
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 0, 3, 4, 5, 6, 7, 8, 9]
[0, 0, 0, 4, 5, 6, 7, 8, 9]
[0, 0, 0, 0, 5, 6, 7, 8, 9]
[0, 0, 0, 0, 0, 6, 7, 8, 9]
[0, 0, 0, 0, 0, 0, 7, 8, 9]
[0, 0, 0, 0, 0, 0, 0, 8, 9]
[0, 0, 0, 0, 0, 0, 0, 0, 9]
```
Reference solution ([Link](http://pyth.herokuapp.com/?code=V9m%3F%3EdNd0S9&debug=0)):
```
V9m?>dNd0S9 (11 bytes)
```
### Problem 2:
Print all digits and all letters on separate lines:
```
0
...
9
a
...
z
```
Reference solution ([Link](http://pyth.herokuapp.com/?code=VTN%29VGN&debug=0)):
```
VTN)VGN (7 bytes)
```
### Problem 3:
Find the lexicographically smallest palindrome, that is lexicographically bigger or equal than an input string containing lowercase letters and is of the same than the input string.
```
a -> a
abc -> aca
adcb -> adda
```
Reference solution ([Link](http://pyth.herokuapp.com/?code=hf%26gTzqT_T%5EGlz&input=abc&test_suite=1&test_suite_input=a%0Aabc%0Aadcb&debug=0)):
```
hf&gTzqT_T^Glz (14 bytes)
```
### Problem 4:
Check, if a number is in the range [0, input number). This should also work for floats.
```
4, 6 -> True
5.5, 6 -> True
6, 6 -> False
6, 6.1 -> True
```
Reference solution ([Link](http://pyth.herokuapp.com/?code=%26gQ0%3CQE&input=4%0A6&test_suite=1&test_suite_input=-0.1%0A3%0A4%0A6%0A5.5%0A6%0A6%0A6%0A7.1%0A6%0A6%0A6.1&debug=0&input_size=2)):
```
&gQ0<QE (7 bytes)
```
The reference format is `to be tested value<newline>end value`. You can choose a different input format however. Important is only, that you accomplish the problem statement and produce the correct results.
### Problem 5:
Parse an input string of the format "\d+[a-zA-Z]+". Notice that the number really has to be a number, not a string containing digits.
```
'123Test' -> [123, 'Test']
```
Reference solution ([Link](http://pyth.herokuapp.com/?code=A.ggk%5CAz%2CsGH&input=123Hallo&test_suite=1&test_suite_input=123Hallo%0A0a%0A101Test&debug=0)):
```
A.ggk\Az,sGH (12 bytes)
```
### Problem 6:
Compute the sum of numbers, that are separated by one or multiple commas. You can assume that there is at least one number in the string.
```
11,2,,,3,5,,8 -> 29
```
Reference solution ([Link](http://pyth.herokuapp.com/?code=svM%3Az%22%2C%2B%223&input=11%2C2%2C%2C%2C3%2C5%2C%2C8&test_suite=1&test_suite_input=11%2C2%2C%2C%2C3%2C5%2C%2C8%0A5%2C1%2C2%0A4%2C%2C%2C%2C%2C%2C2&debug=0)):
```
svM:z",+"3 (10 bytes)
```
### Problem 7:
Read positive integers from the input until you get the number 0. Print the sum of all numbers.
Reference solution ([Link](http://pyth.herokuapp.com/?code=WJE%3D%2BZJ%29Z&input=1%0A2%0A3%0A0%0A5&debug=0)):
```
WJE=+ZJ)Z (9 bytes)
```
### Problem 8:
Sum up all elements of a square matrix, except the ones of the main diagonal (left upper corner to right bottom corner).
Reference solution ([Link](http://pyth.herokuapp.com/?code=-ssQs.e%40bkQ&input=[[1%2C%202%2C%203]%2C%20[2%2C%203%2C%204]%2C%20[3%2C%204%2C%205]]&debug=0)):
```
-ssQs.e@bkQ (11 bytes)
```
[Answer]
# ~~59~~ ~~58~~ 56 bytes
Problem 1:
>
> `j.tmLdS9Z` (9 bytes)
>
>
>
Problem 2:
>
> `MTjG` (5 bytes) (The first character is a newline)
>
>
>
Problem 3:
>
> `h.f_IZ1z` (8 bytes)
>
>
>
Problem 4:
>
> `%IQE` (4 bytes)
>
>
>
Problem 5:
>
> `,J.vz-zJ` (8 bytes)
>
>
>
Problem 6:
>
> `srXz\,d7` (8 bytes)
>
>
>
Problem 7:
>
> `u+GE0` (5 bytes)
>
>
>
Problem 8:
>
> `ss.DR~hZQ` (9 bytes)
>
>
>
[Answer]
# 66 bytes
>
> 1. 10 bytes: `V9+mZN}hN9`
>
> 2. 6 bytes: `jUT)jG`
>
> 3. 8 bytes: `h.f_IZ1z`
>
> 4. (reference implementation) 7 bytes: `&gQ0<QE`
>
> 5. 11 bytes: `,sK-rzZG-zK`
>
> 6. 7 bytes: `ssMcz\,`
>
> 7. 8 bytes: `s<.Qx.QZ`
>
> 8. 9 bytes: `ss.eXbkZQ`
>
>
>
[Answer]
## ~~68~~ ~~67~~ ~~66~~ 65 bytes
Task 1
>
> 10 bytes: `V9m*d>dNS9`
>
>
>
Task 2
>
> 5 bytes: `\nMTjG`, where `\n` is a newline
>
>
>
Task 3
>
> 9 bytes: `h.fqZ_Z1z`
>
>
>
Task 4
>
> 5 bytes: `qQ%QE`
>
>
>
Task 5
>
> Reference solution, 12 bytes: `A.ggk\Az,sGH`
>
>
>
Task 6
>
> 7 bytes: `ssMcz\,`
>
>
>
Task 7
>
> 8 bytes: `s<.Qx.Q0`
>
>
>
Task 8
>
> 9 bytes: `ss.DVQUlQ`
>
>
>
[Answer]
# 54 bytes
Here are the intended solutions. Except for task 8 all solutions were found.
>
> 1. j.tmLdS9Z (9 bytes) using map for left-map, transpose and fill with zeros
>
> 2. \nMTjG (5 bytes) use newlines for map
>
> 3. h.f\_IZ1z (8 bytes) generate the possible strings with .f
>
> 4. %IQE (4 bytes) found a usecase, where the invariant operator needs 2 parameters
>
> 5. ,J.vz-zJ (8 bytes) .v evaluates only the first statement of a string and ignores the rest
>
> 6. ssMcz\, (7 bytes) s"" = 0
>
> 7. u+GE0 (5 bytes) reduce until it reaches a know number
>
> 8. ss.DVQUQ (8 bytes) delete the diagonal using vectorization
>
>
>
[Answer]
# ~~60 59~~ 57 bytes
>
> 1. **[9 bytes](https://pyth.herokuapp.com/?code=j.tmRdS9Z&debug=0)**: `j.tmRdS9Z`
>
>
>
---
>
> 2. **[6 bytes](https://pyth.herokuapp.com/?code=jbUTjG&debug=0)**: `jbUTjG`
>
>
>
---
>
> 3. **[8 bytes](https://pyth.herokuapp.com/?code=h.f_IZ1z&input=adcb&debug=0)**: `h.f_IZ1z`
>
>
>
---
>
> 4. **[4 bytes](https://pyth.herokuapp.com/?code=%7DsEU&input=6%0A5.5&test_suite=1&test_suite_input=6%0A4%0A%0A6%0A5.5%0A%0A6%0A6%0A%0A6.1%0A6%0A&debug=0&input_size=3)**: `}sEU`
>
>
>
---
>
> 5. **[8 bytes](https://pyth.herokuapp.com/?code=%2CK.vz-zK&input=123Test&debug=0&input_size=3)**: `,K.vz-zK`
>
>
>
---
>
> 6. **[7 bytes](https://pyth.herokuapp.com/?code=ssMcz%5C%2C&input=11%2C2%2C%2C%2C3%2C5%2C%2C8&debug=0&input_size=3)**: `ssMcz\,`
>
>
>
---
>
> 7. **[8 bytes](https://pyth.herokuapp.com/?code=s%3CFxB.Q0&input=1%0A2%0A3%0A0%0A5&debug=0&input_size=3)**: `s<FxB.Q0`
>
>
>
---
>
> 8. **[~~11 10~~ 7 bytes](https://pyth.herokuapp.com/?code=ssm.DFdCUB&input=%5B%5B1%2C+2%2C+3%5D%2C+%5B2%2C+3%2C+4%5D%2C+%5B3%2C+4%2C+5%5D%5D&debug=0&input_size=3)**: `ss.DVQU`
> Previous version: `ss.e+<bk>bh`
>
>
>
Note that I developed this solutions **completely** independently of other answers, although I am quite late to the party.
] |
[Question]
[
## Some background
In math, a [**group**](https://en.wikipedia.org/wiki/Group_(mathematics)) is a tuple \$(G, \*)\$ where \$G\$ is a set and \$\*\$ is an operation on \$G\$ such that for any two elements \$x, y \in G, x \* y \in G\$.
For some \$x,y,z\in G\$, basic group axioms are as follows:
* \$G\$ is **closed** under \$\*\$, i.e. \$x \* y \in G\$
* The operation \$\*\$ is **associative**, i.e. \$x \* (y \* z) = (x \* y) \* z\$
* \$G\$ has an **identity** element, i.e. there exists \$e \in G\$ such that \$x \* e = x\$ for all *x*
* The operation \$\*\$ is **invertible**, i.e. there exist \$a, b \in G\$ such that \$a \* x = y\$ and \$y \* b = x\$
Okay, so those are groups. Now we define an [**Abelian group**](https://en.wikipedia.org/wiki/Abelian_group) as a group \$(G, \*)\$ such that \$\*\$ is a **commutative** operation. That is, \$x \* y = y \* x\$.
Last definition. The [**order**](https://en.wikipedia.org/wiki/Order_(group_theory)) of a group \$(G, \*)\$, denoted \$|G|\$, is the number of elements in the set \$G\$.
## Task
The Abelian orders are the integers \$n\$ such that every group of order \$n\$ is Abelian. The sequence of Abelian orders is [A051532](https://oeis.org/A051532) in OEIS. Your job is to produce the \$n\$th term of this sequence (1-indexed) given an integer \$n\$. You must support input up to the largest integer such that nothing will overflow.
Input can come from function arguments, command line arguments, STDIN, or whatever is convenient.
Output can be returned from a function, printed to STDOUT, or whatever is convenient. Nothing should be written to STDERR.
Score is number of bytes, shortest wins.
## Examples
Here are the first 25 terms of the sequence:
```
1, 2, 3, 4, 5, 7, 9, 11, 13, 15, 17, 19, 23, 25, 29, 31, 33, 35, 37, 41, 43, 45, 47, 49, 51
```
[Answer]
## CJam (35 32 bytes)
```
0q~{{)_mF_z~2f>@::#@m*::%+1&}g}*
```
[Online demo](http://cjam.aditsu.net/#code=0q~%7B%7B)_mF_z~2f%3E%40%3A%3A%23%40m*%3A%3A%25%2B1%26%7Dg%7D*&input=25)
### Dissection
To rephrase some of the information in OEIS, the Abelian orders are the cube-free [nilpotent orders](https://oeis.org/A056867); and the nilpotent orders are the numbers `n` for which no prime power divisor `p^k | n` is congruent to `1` modulo another prime divisor.
If we pass the cube-free test, the nilpotency test reduces to
* No prime factor is equal to `1` modulo another prime factor
* If the multiplicity of prime `p` is `k`, `p^k` must not equal `1` modulo another prime factor.
But then the second condition implies the first, so we can reduce it to
* If the multiplicity of prime `p` is `k`, `p^k` must not equal `1` modulo another prime factor.
Note that the word "another" is unnecessary, because `p^a == 0 (mod p)` for `a > 0`.
```
0q~{ e# Loop n times starting from a value less than the first Abelian order
{ e# Find a number which doesn't satisfy the condition
)_ e# Increment and duplicate to test the condition on the copy
mF e# Find prime factors with multiplicity
_z~ e# Duplicate and split into the primes and the multiplicities
2f> e# Map the multiplicities to whether or not they're too high
@::# e# Bring factors with multiplicities to top and expand to array of
e# maximal prime powers
@m*::% e# Cartesian product with the primes and map modulo, so for each
e# prime power p^k and prime q we have p^k % q.
+ e# Combine the "multiplicity too high" and the (p^k % q) values
1& e# Check whether either contains a 1
}g
}*
```
[Answer]
## CJam, ~~46~~ 45 bytes
```
0{{)_mf_e`_:e>3a>\{~\,:)f#}%@fff%e_1e=|}g}ri*
```
[Test it here.](https://tio.run/##S85KzP3/36C6WjM@Ny0@NSHeKtXOONEuprouRsdKM025VtUhLS1NNTXeMNW2pja9tihT6/9/I1MA "CJam – Try It Online")
I'm using the condition given on the OEIS page:
>
> Let the prime factorization of \$n\$ be \$p\_1^{e\_1}\cdots p\_r^{e\_r}\$. Then \$n\$ is in this sequence if \$e\_i < 3\$ for all \$i\$ and \$p\_i^k \ne 1 \text{ (mod }p\_j\text)\$ for all \$i, j\$ and \$1 \le k \le e\_i\$ --- [T. D. Noe](https://oeis.org/wiki/User:T._D._Noe), Mar 25 2007
>
>
>
I'm fairly certain this can be golfed, especially the check of the last condition.
[Answer]
# Pyth, 37 bytes
```
e.f!&tZ|f>hT2JrPZ8}1%M*eMJs.b*LYSNJ)Q
```
[Test suite](https://pyth.herokuapp.com/?code=e.f%21%26tZ%7Cf%3EhT2JrPZ8%7D1%25M%2aeMJs.b%2aLYSNJ%29Q&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A14%0A15%0A16%0A17%0A18%0A19%0A20&debug=0)
Uses the formula from OEIS, cubefree and no prime-power factors that are 1 mod a prime factor, other than 1.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 23 bytes
```
ÆF*/€%þÆfn1ṭÆE<3ƊȦ
1Ç#Ṫ
```
[Try it online!](https://tio.run/##AS8A0P9qZWxsef//w4ZGKi/igqwlw77DhmZuMeG5rcOGRTwzxorIpgoxw4cj4bmq//8yNQ "Jelly – Try It Online")
Takes input via STDIN
## How it works
This uses the same condition as the other answers, given on the OEIS page:
>
> Let the prime factorization of \$n\$ be \$p\_1^{e\_1}\cdots p\_r^{e\_r}\$. Then \$n\$ is in this sequence if \$e\_i < 3\$ for all \$i\$ and \$p\_i^k \ne 1 \text{ (mod }p\_j\text)\$ for all \$i, j\$ and \$1 \le k \le e\_i\$
>
>
>
```
1Ç#Ṫ - Main link. Takes no arguments
1 # - Read an integer n from STDIN. Count up k = 1, 2, 3, ... until n such k
return true under:
Ç - The helper link
Ṫ - Return the last k
ÆF*/€%þÆfn1ṭÆE<3ƊȦ - Helper link. Takes an integer k on the left
ÆF - Yield the prime factorisation of k in [base, exponent] pairs
/ - Reduce
€ - Each
* - By exponentiation
Æf - Yield the list of primes whose product is k
%þ - Yield a modulo table of these two lists. This takes all pairs
from the two lists and reduces each by modulo, yielding a
table of all possible modulo pairings. k can only return true
iff 1 is not in this table
n1 - Map 1 -> 0 and everything else to 1
Ɗ - Group the previous three links into a monad f(k):
ÆE - Exponents of k's prime factorisation
<3 - Less then 3? (vectorises)
This yields a binary list of all 1s if k is true else at least 1 0
ṭ - Tack. Append the modulo table to the binary list. Call this T
Ȧ - Any and all. Does T contain all 1s when flattened and T is non-empty?
```
] |
[Question]
[
Well, the librarian caught you cheating at your job by using your [sorting algorithm](https://codegolf.stackexchange.com/q/58086/42963), so now you're being punished. You've been ordered to create some code so the librarian can impress the object of their unrequited affection, the math teacher. So *that's* what "Other duties as assigned" means ...
Everyone is familiar with the natural number sequence in base 10, called \$\mathbb N\$:
>
> 0, 1, 2, 3, 4, 5, 6, ...
>
>
>
From that, we can generate the prime number sequence, let's call it \$\mathbb P\$, such that every element in \$\mathbb P\$ has exactly two divisors in \$\mathbb N\$, namely `1` and itself. This sequence is:
>
> 2, 3, 5, 7, 11, 13, ...
>
>
>
OK, pretty routine so far.
The librarian thought of a nifty function \$F(x, y)\$ that takes a number \$x\$ from \$\mathbb N\$, with the condition \$0 \le x \le 9\$, and a number \$y\$ from \$\mathbb N\$, and inserts \$x\$ into \$y\$'s decimal expansion in every position (i.e., prepending, inserting, or appending \$x\$ into \$y\$), then returns the sorted set of new numbers.
For example, \$F(6, 127)\$ would result in
>
> 1267, 1276, 1627, 6127
>
>
>
That's still kinda boring, though. The librarian wants to spice things up a bit *more* by instead specifying a new function \$z \to \{p : p \in \mathbb P , F(z,p) \subset \mathbb P\}\$, sorted ascending.
For example, \$z(7)\$ would be
>
> 3, 19, 97, 433, 487, 541, ...
>
>
>
because \$37\$ and \$73\$ are both prime, \$719\$, \$179\$ and \$197\$ are all prime, etc.
Note that \$z(2)\$ is empty, because no prime that has a \$2\$ appended will ever still be prime. Similarly for \$\{0,4,5,6,8\}\$.
Your task is to write code that will generate and output the first 100 numbers in sequence \$z(x)\$ for a given \$x\$.
## Input
A single integer \$x\$ such that \$0 \le x \le 9\$. Input can be via function argument, STDIN, or equivalent.
## Output
A sequence of the first 100 numbers, delimited by your choosing, to STDOUT or equivalent, such that the sequence satisfies \$z(x)\$ as described above. If \$z(x)\$ is empty, as is the case for \$\{0,2,4,5,6,8\}\$, the words `Empty Set` should be output instead.
## Restrictions
* This is code-golf, since you'll need to transcribe this to an index card so the librarian can show the math teacher, and your hand cramps easily.
* Standard loophole restrictions apply. The librarian doesn't tolerate cheaters.
### Reference sequences
x=1 : [A069246](https://oeis.org/A069246)
x=3 : [A215419](https://oeis.org/A215419)
x=7 : [A215420](https://oeis.org/A215420)
x=9 : [A215421](https://oeis.org/A215421)
Related:
[Find the largest fragile prime](https://codegolf.stackexchange.com/questions/41648/find-the-largest-fragile-prime) /
[Find the smallest prime from a substring](https://codegolf.stackexchange.com/questions/22951/find-the-smallest-prime-from-a-substring) / [Find largest prime which is still a prime after digit deletion](https://codegolf.stackexchange.com/questions/10739/find-largest-prime-which-is-still-a-prime-after-digit-deletion)
[Answer]
# Pyth, 49 bytes
Like the Python3 and other Pyth answer, the runtime for finding 100 numbers is prohibitive. (test suite gives 10)
```
?}z"1379".f&!tPZ!|FmtPvjzc`Z]dhl`Z*TT3"Empty Set"
```
[Try it online](http://pyth.herokuapp.com/?test_suite=1&code=%3F%7Dz%221379%22.f%26%21tPZ%21%7CFmtPvjzc%60Z%5Ddhl%60Z%2A1T3%22Empty%20Set%22&test_suite_input=0%0A1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9&input=1)
[Answer]
# Python 3, 188 bytes
```
x=input()
k=1
i=100
if x in"024568":i=print("Empty Set")
while i:k+=1;s=str(k);i-=all(sum(p%d<1for d in range(2,p))<4for p in[k*int(s[:j]+x+s[j:])for j in range(len(s)+1)])and not print(k)
```
Badly golfed, but here's something for now. Instead of checking `p in P and F(z,p) subset of P`, we check that `p*f` is a semiprime for each `f in F(z,p)`. Combine that with trial division for primality testing, and you get an `O(scary)` algorithm.
[Answer]
# Perl, 124 bytes
```
$p=prime_iterator;y/1379//or$i=+~print'Empty Set'}while($i<100){$_=&$p;is_prime"$`@F$'"or redo while//g;$i++
```
Requires the following command line option: `-palMntheory=:all`, counted as 16. Input taken from stdin.
Uses [@DanaJ](https://codegolf.stackexchange.com/users/30069/danaj)'s `Math::Prime::Util` module for perl (loaded with the pragma `ntheory`). Get it with:
```
cpan install Math::Prime::Util
cpan install Math::Prime::Util::GMP
```
[`is_prime`](http://search.cpan.org/~danaj/Math-Prime-Util-0.53/lib/Math/Prime/Util.pm#is_prime) is deterministic for all values less than *264*, which is sufficient for our purposes.
---
**Sample Usage**
```
$ echo 2|perl -palMntheory=:all oscary.pl
Empty Set
$ echo 7|perl -palMntheory=:all oscary.pl
3
19
97
433
487
541
691
757
853
1471
.
.
.
718705783
720574573
737773357
745157779
747215167
767717017
768743377
770294977
771778477
774577777
```
---
**Expected Runtimes**
*x = 1* : 1m 09.2s
*x = 3* : 0m 04.2s
*x = 7* : 2m 52.5s
*x = 9* : 0m 11.5s
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 37 bytes
```
D-ṭJœṖ€$j€Ṗ€ḌẒȦ
1Ẓ×çɗȷ2#µ“¬ḟ¦⁻v»ẇ?⁽¢°
```
[Try it online!](https://tio.run/##y0rNyan8/99F9@HOtV5HJz/cOe1R0xqVLCABYT7c0fNw16QTy7gMgdTh6YeXn5xuaKB8aOujhjmHgJLzDy171Li77NDuh7va7R817j206NCG/5ZHdysc2qpwuP3opIc7Z6gAGQpI0gqaCpH/AQ "Jelly – Try It Online") (takes the first 10 instead of 100)
## How it works
```
D-ṭJœṖ€$j€Ṗ€ḌẒȦ - Helper link. Takes n on the left and d on the right
D - Digits of n
-ṭ - Append -1; Call this D
$ - To the digits:
J - Indices; Yield [1, 2, ..., len(D)]
€ - Over each index i:
œṖ - Partition D at the index i
j€ - Join each with d
Ṗ€ - Remove the -1s
Ḍ - Convert back to integers
Ẓ - Is prime?
Ȧ - True for all?
1Ẓ×çɗȷ2#µ“¬ḟ¦⁻v»ẇ?⁽¢° - Main link. Takes a digit d on the left
? - If statement:
ẇ ⁽¢° - Condition: d is one of 1,3,7,9?
µ - Then:
ɗ - Define a dyad f(n, d):
Ẓ - n is prime?
× - and
ç - the helper link is true
1 ȷ2# - Count up k = 1, 2, ... and return the first 100 k for
which f(k, d) is true
“¬ḟ¦⁻v» - Else: Return "Empty Set"
```
[Answer]
# Pyth, 58
```
L}bPb|*"Empty Set"}Qj204568T.f&yZ.Amyi++<JjZTdQ>JdThl`Z100
```
This [test suite](http://pyth.herokuapp.com/?code=L%7DbPb%7C%2a%22Empty+Set%22%7DQj204568T.f%26yZ.Amyi%2B%2B%3CJjZTdQ%3EJdThl%60Z10&input=9&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9&debug=0) only calculates the first 10 numbers because it takes far too long to generate the rest. Brute forces both primality and the inserting of the digits. Demonstrates such bad performance that I haven't been able to run it up to 100, so please tell me if there are problems.
] |
[Question]
[
In this challenge you will receive a list of non-negative integers. Each one represents a mushroom with a cap of that radius centered at that location. So a `0` means that it occupies no space at all, a `1` means that its cap only occupies space above it, a `2` means it occupies space above it and one unit to the left and right etc. More generally for size \$n\$ a total of \$2n-1\$ spaces are occupied, with the exception of 0 which occupies 0 spaces (i.e. there's no mushroom at all).
Mushroom caps can't occupy the same space as each other but mushrooms can have different heights to avoid collisions.
So for example here we have two mushrooms. They can't be in the same row since they would occupy the same space but if they are given different heights there is no issue:
```
=-=-=
|
=-=-=-=-= |
| |
[ 0,0,3,0,0,2,0 ]
```
(Stems are drawn with `|` for clarity, but can't collide)
Your task is to take as input a list of mushrooms and output a list of heights, one for each input mushroom, such that there is no collisions between mushrooms and they occupy the fewest total rows.
For example here we have a worked case:
```
=-=-= =-=-=-=-=-=-= =
| | |
| =-=-= | =-=-=
| | | | |
=-=-= =-=-=-=-=
| | | | | | |
[ 2,2,2,0,0,4,0,3,2,1 ] <- Widths
[ 2,0,1,0,0,2,0,0,1,2 ] -> Heights
```
(Stems are drawn with `|`, and extra spacer rows are added between layers for clarity)
For any input there are a wide variety of valid answers, you are allowed to output any 1 of them or all of them. You may also consistently use 1-indexed heights instead of 0-indexed heights if you wish.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal will be to minimize the size of your source code as measured in bytes.
## Selected examples
Here are some selected examples with possible solutions:
This one defeats a certain greedy algorithm:
```
=-=-= =
| |
=-=-= =-=-=-=-=
| | | |
[ 2,2,0,1,3 ] <- Width
[ 0,1,0,1,0 ] -> Height
```
This one requires everything to be on its own row:
```
=-=-=-=-=-=-=
|
=-=-=-=-=-=-=
| |
=-=-= |
| | |
= | | |
| | | |
=-=-= | | |
| | | | |
[ 2,1,2,4,4 ] <- Width
[ 0,1,2,3,4 ] -> Height
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 23 bytes
```
Ḥ’R_"+"JJṗL;Ɱ"ẎQƑɗƇƲṀÞḢ
```
A monadic Link that accepts a list of non-negative integers and yields a list of positive integers specifying the levels (i.e. 1-indexed heights).
**[Try it online!](https://tio.run/##AT8AwP9qZWxsef//4bik4oCZUl8iKyJKSuG5l0w74rGuIuG6jlHGkcmXxofGsuG5gMOe4bii////WzIsMiwwLDEsM10 "Jelly – Try It Online")**
### How?
Inefficient brute-force...
```
Ḥ’R_"+"JJṗL;Ɱ"ẎQƑɗƇƲṀÞḢ - Link: cap sizes
Ḥ - double (the cap sizes)
’ - decrement (these)
R - range (those) - i.e. [[1..2*n-1] for each cap size, n]
" - zip (those) and (cap sizes) applying:
_ - subtraction - i.e. make these offsets like [...,-1,0,1,...]
J - range of length (cap sizes) -> [1..length(cap sizes)]
" - zip (the offsets) with (the range) applying:
+ - addition -> covered indices of each mushroom, "covers"
Ʋ - last four links as a monad - f(covers):
J - range of length -> same as [1..length(cap sizes)]
L - length -> same as length(cap sizes)
ṗ - (range) Cartesian power (length)
-> all lists of the same length as cap sizes
using alphabet [1..length(cap sixes)]
Ƈ - filter keep those (arrangements) for which:
ɗ - last three links as a dyad - f(arrangement, covers):
" - zip with:
Ɱ - map with:
; - concatenate -> coordinates
Ẏ - tighten
Ƒ - is invariant under?:
Q - deduplicate
Þ - sort by:
Ṁ - maximum value
Ḣ - head
```
[Answer]
# JavaScript (ES7), ~~146 131~~ 129 bytes
*Saved 15 bytes thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil)!*
Returns a single solution as a space-separated string.
```
f=(a,...B)=>(F=(x,b,o,w=a[x])=>1/w&&b.every((v,i,[...c])=>v&(c[i]|=m=4**w/2-1<<x>>w,m)||F(x+1,c,O=[o]+i+' ')))(0,B)?f(a,...B,0):O
```
[Try it online!](https://tio.run/##bY1BCsIwFET3nsJV/b/9pkntSkwFF249QMiixlYqakQlidC7xxRcyjAwzBuYS@val3kOj/fybk9djL2ElhhjO5QN7CUEOpIlL1sVdKpE6bPsyDrXPT8AjgZSaWwm5DIwatCjvMk6z31ZLcVmE5rG0w3HcQ@hEGToIJXVxVAs5gtEBE473Pa/S@K4PkRj7y977djVnqEHVdEknlQnr1IWGnH2Z8VJ0OovE4nWVCcWvw "JavaScript (Node.js) – Try It Online")
### How?
We generate one bitmask per mushroom cap and attempt to dispatch them among \$N\$ rows without any collision, trying all possible distributions. We start with \$N=0\$ (which is obviously unlikely to work) and increment \$N\$ until a solution is found.
The pattern for a mushroom cap of width \$w\$ and position \$x\$ is computed with:
$$\left\lceil\frac{4^w}{2}-1\right\rceil$$
which generates \$max(0,2w-1)\$ consecutive \$1\$'s.
The final bitmask is obtained by shifting this pattern by \$x\$ positions to the left and \$w\$ positions to the right.
[Answer]
# Python3, 248 bytes:
```
from itertools import*
E=enumerate
C=lambda x,c,I:[i for i,a in E(x)if a*((a-1+i>=I-c+1 and i<I)or(i-a+1<=I+c-1 and i>I))]
f=lambda x:min([i for i in product(*[range(j+1)for j in x])if all(all(i[t]!=m for t in C(x,x[n],n))for n,m in E(i))],key=max)
```
[Try it online!](https://tio.run/##bY7PboMwDMbvPIV3S8BIBHqYqqaXqgeeAXHIIKzuSIKyVEqfnjXs32GTZR@@n/19Xu7h4mzzvPh1nbwzQEH74Nz8DmQW50OenaW2N6O9Cjo7yVmZl1FBxAHbfUcwOQ@ECsjCmUVOE6icMVWKgo6yLYdCgLIj0KHlzjMqVSEOsi2G8ks/tpz32fTjuzdk2bdvcl28G29DYHnnlX3V7FoInuA1wdhvifPMUlMX@idpttuQ8IlFjJ3t0fLtxqL5fJQeofim79KoyNfFkw1sYh1UWGGDadZYQc959stqTJXYbtuqUfyzUaHA5o8uHmSHu6SvHw)
Heights are 0-indexed.
A longer, no-import solution:
```
E=enumerate
def F(x):r={j:a for a,b in min(f(x),key=len).items()for j in b};return[r[i]*(a>0)for i,a in E(x)]
C=lambda x,c,I:{*[i for i,a in E(x)if a*((a-1+i>=I-c+1 and i<I)or(i-a+1<=I+c-1 and i>I))]+[I]}
def f(x,c=0,d={0:[]}):
if len(x)==c:yield d;return
for i in d:
if not C(x,x[c],c)&set(d[i]):yield from f(x,c+1,{**d,i:d[i]+[c]})
yield from f(x,c+1,{**d,max(d)+1:[c]})
```
[Try it online!](https://tio.run/##dY/PisIwEIfvfYo5LUkzXRr1sGSNF1HoM5QeYpOycW0qsUKl9Nm7iQoL@4dADvN9M7@Z863/6Nzy7ezneSeNu7bGq94k2jSwJwMVXo5HoaDpPCg8gHXQWkeagPDT3OTJOPpqe9NeCI3OMRqH6d2b/upd6UtbpURt8ju0qCLeheYq2cqTag9awYA1FmJMSws/JNuASglRGWd2I4usZhyU02DXBe08sZlifC0LVmfP@qagtGJlUU33A8KWWMsctRxzUVYTFQmEmWHnMFzKWtysOWnQz22TR35M18GMqut62IYpQ1lXWNOXi@mJDjfRZ2vju/YRwziOaarRishZ8CeawH9WqwaiKePi7s1nb11P9qSEHHNcYvwXmENFafLNFhhfZKu7tUD@h5Ejx@WvOg9khatYn78A)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~115~~ ~~112~~ 102 bytes
```
≔⟦⟦⟦⟧⟦⟧⟧⟧ηFEθ÷×÷⊖X⁴ι²X²κX²ι«≔⟦⟧ζFη«≔§κ¹εFΦLε¬&§ελι⊞ζ⟦⁺§κ⁰⟦λ⟧Eε⎇⁼νλ⁺μιμ⟧⊞§κ⁰Lε⊞ει⊞ζκ»≔ζη»≔EηL⊟ιζI§η⌕ζ⌊ζ
```
[Try it online!](https://tio.run/##XVBBbsIwEDzDK3xcS64EKTdOtBQJqVQ5cLN8iMiWWDgO2A60qXh7uk5KQJVlK5OdndnZXZG5XZWZtl14r/cWpJRKMKkUvQWfjz8rx2CTHeEk2NqGpT7rHGGrS/Rwx0vcOSzRBswhrS7oYCaY5lywhG7/JxHswB8R1TlnP@PRzZosG7IcdZ5FV7rVFmFtc/yCg2BT0sBI63krbQLpvaPdhwKQih9VgBcdLtrjwuZDKwpm@M01rX0BDQVNTe0f1SdEkUbRG0NTzxadzdw3vJ3qzHiwvUrXVkY1wUrOVTdPJ/pPa5jrzsDYNqAmroXQddhD02/@Ov7DcZBiUEqrI8QM/a5Sp22A18yHwZioK025SWajrS7rEpqYmc/bVspExDOhM6P7TN9Tpdqns/kF "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⟦⟦⟦⟧⟦⟧⟧⟧η
```
Start with no mushrooms placed.
```
FEθ÷×÷⊖X⁴ι²X²κX²ι«
```
For each mushroom, calculate a bitmask corresponding to the space that it occupies. Edit: Saved 3 bytes by using my golf to @Arnauld's formula.
```
≔⟦⟧ζ
```
Start collecting placements that include this mushroom.
```
Fη«
```
Loop over the existing placements.
```
≔§κ¹ε
```
Get the bitmasks for the heights as this gets used a lot.
```
FΦLε¬&§ελι
```
Find whether this mushroom can be placed at any existing height.
```
⊞ζ⟦⁺§κ⁰⟦λ⟧Eε⎇⁼νλ⁺μιμ⟧
```
Generate a placement for putting this mushroom at that height.
```
⊞§κ⁰Lε⊞ει⊞ζκ
```
Generate a placement for putting this mushroom at a new height.
```
»≔ζη
```
Save the new placements as the current placements.
```
≔EηL⊟ιζ
```
Get the heights of all of the placements.
```
I§η⌕ζ⌊ζ
```
Output one of the placements with minimal height.
Previous less inefficient 112-byte version:
```
≔⟦⟦⟦⟧⟦⟧⟧⟧ηFEθ÷×÷⊖X⁴ι²X²κX²ι¿ι«≔⟦⟧ζFη«≔§κ¹εFΦLε¬&§ελι⊞ζ⟦⁺§κ⁰⟦λ⟧Eε⎇⁼νλ⁺μιμ⟧⊞§κ⁰Lε⊞ει⊞ζκ»≔ζη»Fη⊞§κ⁰¦⁰≔EηL⊟ιζI§η⌕ζ⌊ζ
```
[Try it online!](https://tio.run/##bVHBbsIwDD3DV@ToSJkEHTdObAwJaUw9cItyqKihEWkKTQpbJ769c9q1oGmKEsXx83v2yy5Lyl2RmKZZOKcPFqSUSjCpFJ0Zn4/3Rclgk5zgLNja@qW@6BRhq3N0cI@XuCsxR@sxhbi4YgkzwTTngkW0u5dIsCN/jCjPOdN7Bpqz7/Go74CUa1IetdJZm@pzC7@2KX7CUbApUWGAdbiVNp5o39EefAZIyY/Cw4v2V@1wYdOhFAUzvBePK5dBTfPGpnKP7BOCSKPoDLNTzRZLm5Rf8HauEuPAdixtWR7YBMs5V20/LekfrqGvOwJD2RDVwR2KboMPdfcBtzEah6w34z/yCcF@i0K32SAXFycIg3aGxqW2Hl4T5wcCgq40mUNaG211XuVQB2P4vGmkjERYE1oz2s90nyrVPF3MDw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Always places zero-width mushrooms at zero height instead of at all possible heights.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~45~~ 43 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
εD(Ÿ¦¨N+}[DN.Œ.Δε˜DÙQ}P}Zd#\}ε€ÅsIgݨåN*}øO
```
Brute-force approach.
[Try it online](https://tio.run/##yy9OTMpM/f//3FYXjaM7Di07tMJPuzbaxU/v6CS9c1PObT09x@XwzMDagNqoFOWY2nNbHzWtOdxa7Jl@eO6hFYeX@mnVHt7h//9/tJEOCBoAoQkQGwPZhrEA) or [verify both test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf/PbXXROLrj0LJDK/y0a6Nd/PSOTtI7N@Xc1tNzXA7PDKwNqI1KUY6pPbf1UdOaw63Fh9alH557aMXhpX5atYd3@P/X@R8dbaBjoGOsAyKNdAxidaKNdEAQxDcByxjpGMbGAgA).
**Explanation:**
Step 1: Change each value in the input to a list of indices it can reach:
```
ε # Map over each value of the (implicit) input-list:
D( # Create a negative copy
Ÿ # Pop both, and push a list in the range [n,-n]
¦¨ # Remove the first and last to make the range (n,-n)
# (or empty the list if n=0)
N+ # Add the current map-index as offset
} # Close the map
```
[Try just this first step.](https://tio.run/##yy9OTMpM/f//3FYXjaM7Di07tMJPu/b//2gjHRA0AEITIDYGsg1jAQ)
Step 2: Indefinitely loop up from \$N=0\$ and get all \$N\$-element combinations of the list of lists. Stop as soon as we've found a partition for which all inner indices are unique.
```
[ # Start an infinite loop:
D # Duplicate the list we've created in step 1
N # Push the loop-index `N`
.Œ # Pop both, and get all N-sized partitions of the list
.Δ # Find the first partition that's truthy for:
# (or -1 if none are truthy)
ε # Map over each part:
˜ # Flatten the list of lists of indices
DÙQ # Check whether all indices are unique:
D # Duplicate it
Ù # Uniquify this copy
Q # Check if both lists are still the same
}P # After the map: check if all parts were truthy
}Z # After the find_first: push the maximum (without popping)
# (which results in "-" for -1)
d # If this is a non-negative integer (0 for "-", 1 otherwise)
# # Stop the infinite loop, since we have a hit
\ # (else:) discard the -1 that's still on the stack
} # Close the infinite loop
```
[Try just the first two steps.](https://tio.run/##yy9OTMpM/f//3FYXjaM7Di07tMJPuzbaxU/v6CS9c1PObT09x@XwzMDagNqoFOWY2v//o410QNAACE2A2BjINowFAA)
Step 3: Convert this found result of parts of index-ranges to a list of heights to output:
```
ε # Map over each part in this partition:
€ # Inner map over each inner index-range (-n,n):
Ås # Pop and leave just the middle value
# (this is the offset we've added in step 1,
# or [] if the list was empty for n=0)
Igݨ # Push a list in the range [0, input-length):
I # Push the input-list
g # Pop and push its length
Ý # Pop and push a list in the range [0,length]
¨ # Remove the last item to make the range [0,length)
å # Check for each if it's in the earlier list
N* # Multiply each by the 0-based map-index,
# which are the heights
}ø # After the map: zip/transpose; swapping rows/columns
O # Sum each inner list (mapping each to its max, since each inner
# list will only contain (at most) one non-0 height)
# (after which this list of heights is output implicitly)
```
*Note: It outputs the first result it can find, so for the second example test case, it outputs this list of mushroom-heights:*
```
=-=-= =-=-=
| |
=-=-= =-=-=-=-=
| | | |
=-=-= =-=-=-=-=-=-= =
[ 2,2,2,0,0,4,0,3,2,1 ] <- Widths
[ 0,1,2,0,0,0,0,1,2,0 ] -> Heights
```
[Answer]
# [Python](https://www.python.org), ~~293~~ ~~264~~ ~~263~~ 262 bytes
*-1 bytes thanks to [@Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)*
```
j=lambda h:min((((n:=h.copy()).__setitem__(a+b,n.pop(a)|n.pop(b)))or j(n)for a in h for b in h if not h[a]&h[b]),default=h,key=len)
def f(w):
r=[0]*len(w);i=0
for K in j({(i,):set(range(-x-~i,x+i))for i,x in enumerate(w)}):
for k in K:r[k]=i
i+=1
return r
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NZBLTsQwDIbFBml6iqwgpumoAyxQUU4wR6iqKmVSkj7cKqSiFY-LsJkN3AlOgzPVxIry5bf12_LXz7h4M-Dx-D35Onn4u7hsZKf66qCYyXqLnA5m0myfhnHhANuyfNHeet2XJVdxJXA7DiNX8L5CBQCDYw1HqOlVzCIzLGC1oq0ZDp6ZXBVXJq8KEAddq6nz0ohWL7LTCBFJrOavkEUbJ_O0uCGVvo9WptEmmO2DWcPfuBWQ0UDcKXzWPJmTTyvm2MKpO2Go0zj12imvyeIjeJ4s2pDaZy5vC2lJs7HcUTvtJ4fMrev4vZ6ZpElyditCpBT3dO-Id6yAaHQWPZ9hLT9v8R8)
Note: it's extremely inefficient.
A slightly more efficient (and longer) variant:
```
from itertools import*
j=lambda h:min((((n:=h.copy()).__setitem__(a+b,n.pop(a)|n.pop(b)))or j(n) for a,b in combinations(h,2)if not h[a]&h[b]),default=h,key=len)
def f(w):
r=[0]*len(w);i=0
for K in j({(i,):set(range(-x+1+i,x+i))for i,x in enumerate(w) if x}):
for k in K:r[k]=i
i+=1
return r
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NVBBTsMwEBTH5hV7Am_jVm3hgIL8gj4hiiKndbDbeB25jkgFvIRLL_AneA0bKryyNDs7Ho_246s_JxvocvkcUrt4_LmZtzF4cMnEFEJ3Auf7ENM8O6hO-2avwRbekeBDhbLLXejPAnFZ1yeT-JWva6HzRtKyD73Q-HYFDSKGCAdBCC0DLRtwBLvgG0c6uUAnYeUGXQsUEthSV7e2bCqUe9PqoUvKyqM5q84QZkxBK16wyGZRlatqziy3T06tstnkvp28D-JVOIkF5xJR07MRizFf506OuUOcZAwnoaHBm6iTYQ_gAOP75PxndJzm2yKWx0o55lyu1vypSUMkiNeVfd-NoDhPCRs51Yrrge894zVUmPXRURIjXuX_m_4F)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~143~~ 142 bytes
```
f=(a,i=x=[])=>(g=y=>1/a[y.length]?x.some(i=>g(O=[...y,i])):!a.some((P,p)=>a.some((Q,q)=>y[p]==y[q]&p<q&P+Q>q-p+1&&P*Q)))([])?O:f(a,x.push(+i))
```
[Try it online!](https://tio.run/##bY3LDoIwEEX3/oUbMpVaqbIiDn6CsG66aJRHDdIiaujX4xjjjtxMMjdnJudm3ma8PKx/bnt3rea5RjDc4oRKM8yhwYC53BkVRFf1zbPVp0mM7l6BxbyBMyohROBWM5atzY9AwT39/lvJB2pBeY0Y1KAjfxyiIi7zYetjGUXFpmSMAflO56wm@yT8a2whtozNF9ePrqtE5xqoQe35NwklpTnQLsm8WrhKuOSHRSaJpjwlNn8A "JavaScript (Node.js) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 28 bytes
```
d‹ɾ-:ż+:£₌żLÞẊ'¥¨£v"ÞfÞu;⁽G∵
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJUIiwiIiwiZOKAucm+LTrFvCs6wqPigozFvEzDnuG6iifCpcKowqN2XCLDnmbDnnU74oG9R+KItSIsIiIsIlsyLDIsMCwxLDNdIl0=)
Port of Jelly. Outputs a list of 1-indexed heights.
[Answer]
## Clojure, ~~214~~ 227 bytes
```
(defn f([W](:H(nth(flatten(for[m(range)](f m 0 W[][1])))0)))([m i W H O](if-let[w(nth W i nil)](for[h(range(if(= w 0)1 m))O[(into O(for[d(range(+(- w)1)w)][(+ i d)h]))]:when(apply distinct? O)](f m(inc i)W(conj H h)O)){:H H})))
```
[TIO](https://tio.run/##PY/BasQgEIbveYo5zrBZMN2eAqXX3DzmMHgIiVYXY0LWImXZZ08n3bYOA6Kf3/yOcbl@bnbfcbIugUPuDbYdpuzRxSFnm9AtG8@4DenDkkEHMyjo2XBjiEhJI88QoIcOtMHgztFmLodCzgKkEI9nIvFPiSD4BgUUNTATacaQ8gL6h5l@mROeoVBDhQzjSTQTeZln2uIl0rCu8QumcMshjfkd9DOYiEYI1OO4pKvE8aSJ7m0H3UNiVhWum4yKCVhofqmPUlKv0hfZy48q@F9/jKqb@mJI7vb9Gw).
Buggy code:
```
(defn f([W](:H(nth(flatten(f 0 W[][1]))0)))([i W H O](if-let[w(nth W i nil)](for[m(range)h(range(if(= w 0)1 m))O[(into O(for[d(range(+(- w)1)w)][(+ i d)h]))]:when(apply distinct? O)](f(inc i)W(conj H h)O)){:H H})))
```
I thought I could move the `for[m(range)...` from the initial function call inside the recursion, but apparently it leads to a wrong output in come cases.
Less golfed:
```
(defn f
([widths] (first (flatten (for [max-height (range)] (f max-height 0 widths [] [])))))
([max-height ix widths heights occupied]
(if (-> widths count (= ix))
{:heights heights :occupied occupied}
(for [w [(widths ix)]
h (range (if (= w 0) 1 max-height))
:let [new-occupied (for [dx (range (-> w - inc) w)] [(+ ix dx) h])
occupied (into occupied new-occupied)]
:when (apply distinct? nil occupied)] ; Cannot call `distinct?` without any arguments, thus the `nil` is there.
(f max-height (inc ix) widths
(conj heights h)
occupied)))))
```
] |
[Question]
[
You probably know what a Turing Machine is but do you know what is a Turning Machine (lathe)?
Ok you already know.. and what about a Golf Turning Machine ??
Ok I tell you..
A Golf Turning Machine is a full program or function taking a list/array (or any convenient method) representing the Profile (P) of a turned piece and producing an ascii turned shape.
An ascii turned shape has square rotated by 45° cutting section instead of a circle so that we only need '/' and '\' characters to draw it.
And it has '\_' characters for the profiles: upper, lower and median.(like the one of this challenge : [ASCII TURNED SHAPE](https://codegolf.stackexchange.com/questions/194279/ascii-turned-shape?r=SearchResults) ) for simple and nice drawing purpose.
```
_________
/\ \
/ \________\
\ / /
\/________/
```
A Profile P is a container of positive integers values in the range 0 <= value < 26(minimum)
- Every value represents the radius of a 1 long character section, so the length of the container is the length of the piece obtained.
- Alphabet are also valid [a to z] or [A to Z] they must correspond to a [0 to 25] value.
* 0 values at the beginning and at the end of the profile input can not be considered.
Test cases:
```
[2,2,2,2,2,4,4,4,4,4,6,6,6,6,6,4,4,4,4,4,2,2,2,2,2] or
"CCCCCEEEEEGGGGGEEEEECCCCC" or
['c','c','c','c','e',.....]
_____
/\ \
___/_ \ \__
/\ \ \ \ \
___/_ \ \ \ \ \__
/\ \ \ \ \ \ \ \
/ \____\ \____\ \____\_\_\
\ / / / / / / / /
\/____/ / / / / /_/
\ / / / / /
\/____/ / /_/
\ / /
\/____/
```
.
```
[1,0,0,0,0,0,0,3,3,0,0,1] or
[0,0,0,0,0,1,0,0,0,0,0,0,3,3,1,1,1,0,0,0]
__
/\ \
_ / \ \_
/\\ / \_\\
\// \ / //
\ / /
\/_/
```
.
```
[2,1,1,1,1,10,10,8,8,8,8,8,8,10,10,1,1,1,1,2]
__ __
/\ \ /\ \
/ \ \__/_ \ \
/ \ \ \ \ \
/ \ \ \ \ \
/ \ \ \ \ \
/ \ \ \ \ \
/ \ \ \ \ \
/ _ \ \ \ \ \
/ /\\___ \ \ \ \ \
/ / \\__\ \_\___\ \_\
\ \ //__/ / / / / /
\ \// / / / / /
\ / / / / /
\ / / / / /
\ / / / / /
\ / / / / /
\ / / / / /
\ / /___/ / /
\ / / \ / /
\/_/ \/_/
```
Rules :
- Margins are not specified.
- Standard loopholes are forbidden.
- Standard input/output methods.
- Shortest answer in bytes wins.
Sandbox <https://codegolf.meta.stackexchange.com/a/18150/84844>
[Answer]
# JavaScript (ES6), ~~259 249~~ 246 bytes
Takes input as an array of integers. Returns a matrix of characters.
```
a=>{for(m=[],i=a.length,X=i+25;i--;r[X]>' '|!w?0:r[X]='_',X--)for(y=w=a[i];y>=-w;y--)for(r=m[Y=y+25]=m[Y]||Array(X).fill` `,W=w+(y>0?1-y:y),k=2;k--;)for(x=-W;x<W;x++)r[X+x+k]='/\\ _'[w^a[i+k]|w^a[i+k-1]?(x+W&&2-!(~x+W))^y>0:y&&y-w?2:4];return m}
```
[Try it online!](https://tio.run/##TZDfboMgGMXv@xTsRiGCU9ctiwzNLvYMdbG0JZ22tv5pqJuSub26w9Z2zQ/Cxzl8nMBOfInjWmaHmpTVR9KnrBcs@E4rCQsWc5wxYedJuam3OGKZ5T3SjBAq44gHJjC7uyZ0/GHHzKWJI0LQ0KlYw0SccaoCRhqqRlmyIn5nSl/Ch4p33auUQsEI2WmW5yuwwjPWWFAFTugS5SuE98yjex146m8ZmdH2RU/LQjrUaq29Dr6fzwFYmnGz0Jla6caCuDyErTUzDI/cwV9dIbTQd/vKMBRpQs@fciqT@lOWoPjpaTwBIPbwhemVpyv/2vUcx0Obi50bHjTD6p5ND7sXnGE833BWLr7HJ3xi67e@ifUWFoAFYF2VxypP7LzawBQWyC7EAcrBkfauykpomuj0f3UiRx2NxrzUFqL9Hw "JavaScript (Node.js) – Try It Online") (with leading and trailing empty lines removed for readability)
## Commented
We are 'drawing' in a matrix \$m[\:]\$, from right to left. The code essentially consists of 4 nested *for* loops, followed by the matrix update.
### First loop: input values
```
for( // initialization:
m = [], // m[] = output matrix
i = a.length, // i = length of input
X = i + 25; // X = center x-coordinate
// condition:
i--; // stop when i = 0; decrement i
// final expression:
r[X] > ' ' | !w ? 0 // unless w = 0 or there's already a character other
: r[X] = '_', // than a space here, append the top '_'
X-- // decrement X
) //
```
### Second loop: rows
```
for( // initialization:
y = w = a[i]; // y = w = next width, taken from the input list,
// read in reverse order
// condition:
y >= -w; // stop when y = -w-1
// final expression:
y-- // decrement y
) //
```
### Third loop: slices
```
for( // initialization:
r = m[Y = y + 25] = // r[] = row to update
m[Y] || Array(X).fill` `, // if undefined, initialize it with X leading spaces
W = w + (y > 0 ? 1 - y : y), // W = width of the pattern at this row
k = 2; // k = counter to draw two consecutive slices
// condition:
k--; // stop when k = 0; decrement k
) //
```
### Fourth loop: columns
```
for( // initialization:
x = -W; // start with x = -W
// condition:
x < W; // stop when x = W
// final expression:
x++ // increment x
) //
```
### Matrix update
```
r[X + x + k] = // set the character at the current position:
'/\\ _'[ // 0 = '/', 1 = '\', 2 or 3 = space, 4 = '_'
w ^ a[i + k] | // if a[i] is different from a[i + k]
w ^ a[i + k - 1] ? // or different from a[i + k - 1]:
( x + W && // append a '/' if x = -W
2 - !(~x + W) // append a '\' if x = W - 1, or a space otherwise
) ^ y > 0 // invert '/' and '\' if we're below the middle row
: // else:
y && y - w ? 2 : 4 // append a '_' if y = 0 or y = w,
]; // or a space otherwise
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 68 bytes
```
FLθ«≔⌕α§⮌θιηFη«J±⁺ιη⁰G↘η↗⊕η↖η ↘η←↙η↑↖η→↗η↘§_/⁼/KK≔⎇⁼ηζ◧_ηηδ↘δ←↙δ»≔ηζ
```
[Try it online!](https://tio.run/##jZFdS8MwFIav218RcnUKFb3urjqmUJlSxnYtoTlrg13SpWl1yn57TdI6VkXwQEI@nvO@5yRFxXShWD0Me6UJrFGWpoJjFJHPMEjbVpQSHoTkwGKSmkxyfIcN9qhbtFRMRGSnKlqEgc@vfF7w2B2arYJnLJlByOuuBeEwy945NshVfSqVhGSl3uRGlJWx1zFJds20yWSh8YDSILei/maN@5GihI4iWkgzl/DnT6pHSBz@E5skrqhdc81cTK4ILz2HZm6/q/h@J/pyS2Nyf@xY3QJ16xzxFSIbLnF63S1qyfQJJs7292H7zRl3pVgN6ozGwf8w5P9q21Pny696o0V4HoZl6mNlI02X2XDT118 "Charcoal – Try It Online") Link is to verbose version of code. Takes a string of uppercase letters as input. Explanation:
```
FLθ«
```
Loop once for each input letter.
```
≔⌕α§⮌θιη
```
Calculate the previous letter's value, since the drawing is done from end to start.
```
Fη«
```
Loop that many times; this is slightly golfier than an `if` since it doesn't need an `else`.
```
J±⁺ιη⁰G↘η↗⊕η↖η ↘η←↙η↑↖η→↗η
```
Erase and draw the main diamond of the section.
```
↘§_/⁼/KK
```
Draw the `_` profile at the top if there isn't already a `/` there.
```
≔⎇⁼ηζ◧_ηηδ↘δ←↙δ
```
Draw the right side of the back of the section if this is a new section, otherwise erase the right side of the front diamond we drew last time (the left side was already erased earlier) leaving just two `_`s for the profiles.
```
»≔ηζ
```
Save the size of the section for the next loop.
] |
[Question]
[
Inspired by the upcoming winter bash event
### Objective
Add a hat `^`,`´` or ``` to a single vowel in each word of the input.
### Rules
* The `hat` and the `vowel` must be chosen at random. Each hat has to appear with the same probability (33%) and the vowels must have the same probability within the valid vowels in the word (if the word have 2 valid vowels each must be 50% likely to be chosen) - or the closest that your language has.
* Only `AEIOUaeiou`are considered vowels (sorry `y`)
* Vowels with hats in the input DO NOT interfere with the rules (you can consider it as a consonant)
* If the input has no vowel it won't be modified
* Capitalization must be preserved.
### Examples
`winter` > `wintér`
`bash` > `bâsh`
`rhythm` > `rhythm`
`rng ftw` > `rng ftw`
`cat in the hat` > `cât ìn thê hát`
`dès` > `dès`
`tschüss` > `tschüss`
`principî` > `prìncipî`
`PROGRAMMING PUZZLES & code golf` > `PROGRÂMMING PÚZZLES & codé gòlf`
### Winning
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code wins
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `S`, 17 bytes
```
⌈ƛAa[AT›℅3℅767+CṀ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJTIiwiIiwi4oyIxptBYVtBVOKAuuKEhTPihIU3NjcrQ+G5gCIsIiIsImhlbGxvLCB3b3JsZCEgcG90YXRvZXMgYXJlIGdyZWVuIFBQUFAiXQ==)
Some tricks stolen from [Seggan's answer](https://codegolf.stackexchange.com/a/248413/100664).
```
⌈ƛ # Over each word
Aa[ # If it has a vowel...
A # Is each a vowel?
T # Indices of vowels
℅› # Choose a random one and increment it
3℅ # Random choice from [1, 2, 3]
767+ # Add 767
C # Make it a char
Ṁ # Insert that at the specified index.
# (S flag) turn the word list into a sentence
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `S`, 27 bytes
```
⌈:ƛAT:[℅|u];Zƛ÷›[nt3℅767+CṀ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJTIiwiIiwi4oyIOsabQVQ6W+KEhXx1XTtaxpvDt+KAultudDPihIU3NjcrQ+G5gCIsIiIsIlBST0dSQU1NSU5HIFBVWlpMRVMgJiBjb2RlIGdvbGYiXQ==)
The result of my older answer mixed with [emanresu A's answer](https://codegolf.stackexchange.com/a/248465/107299).
# [Vyxal](https://github.com/Vyxal/Vyxal) `S`, ~~37~~ ~~35~~ 33 bytes
```
⌈:ƛ≬k∨$cḟ:[℅|u];Zƛ÷›:[768:⇧ṡC℅Ṁ|_
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJTIiwiIiwi4oyIOsab4omsa+KIqCRj4bifOlvihIV8dV07Wsabw7figLo6Wzc2ODrih6fhuaFD4oSF4bmAfF8iLCIiLCJQUk9HUkFNTUlORyBQVVpaTEVTICYgY29kZSBnb2xmIl0=)
-2 bytes thanks to @Steffan
-2 bytes by inlining the register
I manually generated the diacritics list so this wouldn't have to be scored in UTF-8.
```
⌈:ƛ≬k∨$cḟ:[℅|u];Zƛ÷›:[768:⇧ṡC℅Ṁ|_ # 'S' flag joins the output on spaces
⌈ # Split the input on spaces
: # Duplicate
ƛ ; # Map the duplicate to...
≬ ḟ # Find the indexes in the word that satisfy the following condition:
$c # Is the character contained in...
k∨ # "aeiouAEIOU"?
:[ ] # If the list is not empty (i.e. the word has vowels)
℅ # Choose a random index from the list
| # Otherwise...
u # Push -1
Z # Zip the mapped list and the word list together
ƛ # Map the new list of pairs of words and indexes
÷ # Push the word, then the index
› # Increment the index (0 becomes 1, -1 becomes 0)
:[ # If the index is not 0 (i.e. if there is a vowel)
768 # Push the charcode of the first diacritic
: # Duplicate
⇧ # Add 2
ṡ # Inclusive range from 768 - 770
C # Unicode value -> character for each number
℅ # Choose a random diacritic
Ṁ # And insert it before the vowel
| # Otherwise...
_ # Pop the duplicated index, leaving the word on the stack
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 118 bytes
Spec doesn't state what [Unicode normalisation](https://en.wikipedia.org/wiki/Unicode_equivalence#Normal_forms) is allowed. Examples use NFC, but NFD is cheaper.
```
s=>s.replace(/\S+/g,w=>w.replace(x=/[aeiou]/gi,c=>v--?c:c+'̀́̂'[3*r()|0],v=(r=Math.random)()*w.match(x)?.length|0))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZVLPb9MwGJU4-q_widhrm4RfAq0k1YTKNImu06Zd1lZa6jpxIE0i22k7tkljJw6cuAGXUoG0oYnDbkjcfO0_AH8NdtMWJE7vvU_f8_s-25--pNmATmeh97WQYe3Jr5HwfGFzmicBocjpHlScqDr2_PG6NvGcTkDjrOg5UVwlnj-q1Rpkk1Ss-cX8zfzS6jzY4Aifub3qyEPcawWS2TxIB9kQI7wxtoeBJAxNcMNOaBpJduZiXKb_vlPUATgGW9CH6gI0DbwFOwbegbaB9-DQwAcQGJgCauAKxAZuQGbgFhQGfoBxnErKNTdEXXPQDwTTsq9mggHOTiQbalkSwNMIhnJsCiUDA3UltDQApCBM_RRGryjIeZySOFffdTHn6qYUgAQSximUjEKmqQ-Jmkk9nSmpb5CpzxLs7be397darZ3dbbh3eHT0onkA70KinwJGWRJq06JDXS5b1Md_etQ1jNRtEoJjW_J4iLAt8iSWyOqmFrbDjDcDfb-SCgk9H54CqE2pFp2qnisvZBXSSU6J7EEPmq7lgzjIrmCdbMDB9bWNU1EkUujm03NT1QEQJVQvqUtuXcNTeM91DavoA5btnRAtwrCdZnwYJPFriqzd588svIjlBf2bkAfCHL9yltP971sZsoTaSRahha0BrW5x_7H7yIKbJX1IrPWiVs3Xot1_aQ58RU8EWoboO8u4RFjveY7r5e-bTkv8Aw) Note: My test does 1000 trials and checks to see if it got the example output. Occasionally it misses for the long ones.
This is basically the same as the old solution, just swapped out the vowel replacement function.
# Old solution (NFC), 159 bytes
```
s=>s.replace(/\S+/g,w=>w.replace(x=/[aeiou]/gi,c=>v--?c:Buffer(c+c).map((n,j)=>j?n+68-4*!(n&12)-!(n&16)+3*r()|0:195),v=(r=Math.random)()*w.match(x)?.length|0))
```
[Attempt This Online 2!](https://ato.pxeger.com/run?1=TZJNTxNBGMcTj_MpxgudabvbFgGxdbeBpCEk1hIaLrQkbIfZF9zubmZmaQmQGE8ePHlTD9ZGEzDEAzcTb_Mp9NP4TLegp9__efb_vMzMfvqapCd8Nvedb7nyrc3fn6XjSlvwLPYYJ7Vhv1ILqhPHnTzkpk5t4PEozY9qQVRljntmWW3W3M59nwvCKozaYy8jJKmeUsc9bSeVjU1rrfyYJCuNVWotuEErT8qC0Mt6s_FsnVbPHCKcrqdCW3jJSTqmhJYn0EaxkExp2455Eqjwsk5pseafR_0WQsdoC7tYv0Ydg7do1-Ad6hm8RwcGH5BnMEPc4BpFBrcoNbhDucFPNIkSxQVoI_SNQCNPhhCO9FyGSITnKhxDWAgkkgD7amIShUIn-lpCaICUZKH-JU18L1EmooRFmf4ByUzo2yJAzFM4SrAKOQ5BupjpuYLtTEp_x6H-otDefm9nf6vb3X25g_cODg9fdPp4BTN4MxyksQ9FC4d-s7Toj_959A0O9F3so2NbiWhMqC2zOFKkNExK1PZT0fHgfhWXCjsuvkAYihIIBlXYK8tVFfNpxpk6wg42ruWD1IhdoTDZoEZbD2WCyzxWEswXVyYLAzCJORwSUvUW4Dlu1OtGVaDB0j7wyWIYXUwROf_XMPOk6XZvXC5z_z2NuR2nAVm42rg0zFef1tdLuFnINVZ6OEbJciHojU6h3n7FzyVZ9oQbSYUiFE5xRVvFvzWbFfwL)
## Ungolfed and somewhat explained
In UTF-8, all the accented character are 2 bytes, the first of which is always 195. The second can be calculated from the base letter.
```
char: A E I O U a e i o u
code: 65 69 73 79 85 97 101 105 111 117
&12: 0 4 8 12 4 0 4 8 12 4
&16: 0 0 0 0 16 0 0 0 0 16
with \: 128 136 140 146 153 160 168 172 178 185
with /: 129 137 141 147 154 161 169 173 179 186
with ^: 130 138 142 148 155 162 170 174 180 187
code to \: 63 67 67 67 68 63 67 67 67 68
code to /: 64 68 68 68 69 64 68 68 68 69
code to ^: 65 69 69 69 70 65 69 69 69 70
|---same---| |---same---|
```
For most letters, we just increase character code by 67 (for `Aa`, increase by 63, for `Uu` increase by 68), then offset by 0, 1, or 2 to add the hat.
```
s => s.replace( // replace each word
/\S+/g,
w => w.replace( // replace each vowel
x = /[aeiou]/gi,
c => v-- ? // if this is not the vowel to replace
c : // don't replace
Buffer(c + c).map( // otherwise create a Buffer of 2 bytes
(n, j) => j ? // map (replace) each byte; if it's the 2nd byte
n // start at n
+ 68 // add 68
- 4 * !(n & 12) // subtract 4 if it's 'A' or 'a'
- !(n & 16) // subtract 1 if it's not 'U' or 'u'
+ 3 * r() | 0 : // add randomly 0, 1, or 2 (and floor it)
195 // set the first byte to 195
),
v = (r = Math.random)() * w.match(x)?.length | 0 // choose vowel
)
)
```
[Answer]
# [Perl 6](https://perl6.org), 101 bytes
```
~*.words.map: {(my$p=m:ex:i/<[aeiou]>/».to.pick)~~Mu:D??~S/.**{$p}<(/{("\x300".."\x302").pick}/!!$_}
```
[Try it](https://tio.run/nexus/perl6#NZDLToNQEIb3PMWUkHKJHhqNLqC0mmgaE6tNGzf1FuRSThTOCRxKCYHnceUL6EoeDIGDq/n@f/7JTCZNPNifI8cUhDCHsUNcD6ym0lBGYjdBoU0NKJQwl6gVGt7BwPr00fYwSZ9n@u83YgRR7LyrVbVMjav5vNroSNMKiZZTRS8U8elwOpmICPVwIqp9utRHI@m1bPjOCxzRlIEFigAgZzhiXiwfdfxmJwGnOMhZEA4c7cBnGReOzQBHwAIPAptxz60/E04scYL6JxkUjXHkYFp/cbla3y/Wl8vlzd0CVg/b7e31BsbQP2BHPvw2pLYH@iT@v/B4BhKnop3vahdWuKdCl3w5M4eWLJtC2fwB "Perl 6 – TIO Nexus")
## Expanded:
```
~ # stringify (join with spaces)
*\ # Whatever lambda (input parameter)
.words # split into words
.map: # for each word
{ # bare block lambda with implicit parameter 「$_」
(
my $p =
m
:exhaustive # all possible matches
:ignorecase
/<[aeiou]>/\ # match a vowel
».to.pick # pick one of the positions
) ~~ Mu:D # is it defined ( shorter than 「.defined」 )
?? # if 「$p」 is defined
~ # stringify
S/
. ** {$p} # match 「$p」 positions
<( # ignore them
/{
("\x300".."\x302").pick # pick one of the "hats" to add
}/
!! # if 「$p」 is not defined
$_ # return the word unchanged
}
```
[Answer]
## C#, ~~273~~ 267 bytes
```
using System.Linq;A=s=>{var r=new System.Random();var a=s.Split(' ');return string.Join(" ",a.Select(w=>w.Select((c,i)=>"AEIOUaeiou".Any(d=>c==d)?i:-1).Where(x=>x>=0).ToList()).Select((l,i)=>l.Any()?a[i].Insert(l[r.Next(l.Count)]+1,""+(char)r.Next(768,771)):a[i]));};
```
[repl.it demo](https://repl.it/EsX5/1)
I really feels like I'm cheating, since I still add hats to already accented vowels created by [combining characters](https://en.wikipedia.org/wiki/Combining_character). If that is not acceptable, let me know so I can ~~add boilerplate codes~~ declare this answer non-competing.
This thing adds a random character among [U+0300](http://www.fileformat.info/info/unicode/char/0300/index.htm) or [U+0301](http://www.fileformat.info/info/unicode/char/0301/index.htm) or [U+0302](http://www.fileformat.info/info/unicode/char/0302/index.htm), after a random vowel of each input word (if any).
Ungolfed (lambda body only)
```
var r=new System.Random();
// Split sentence to array of words
var a=s.Split(' ');
// Join the (hat-ed) words back to sentence
return string.Join(
" ",
// Select an IEnum of list of integers indicating the positions of vowels
a.Select(w=>
w.Select((c,i)=>
// If it's vowel, return position (>=0), else return -1
"AEIOUaeiou".Any(d=>c==d)?i:-1
// Filter vowels only
).Where(x=>x>=0)
.ToList()
// Convert each list of integers to hat-ed words
).Select((l,i)=>
l.Any()
// Insert "something" into the word...
?a[i].Insert(
// ...at the position after a random vowel in that word...
l[r.Next(l.Count)]+1,
// "something" is a random integer in [0x0300, 0x0303), then casted to UTF16 i.e. [U+0300, U+0302]
""+(char)r.Next(768,771))
// List is empty => just return original word
:a[i]));
```
[Answer]
# Mathematica, 226 bytes
```
Join@@((p=Position[w=#,Alternatives@@(v=Characters@"aeiouAEIOU")];If[p!={},i=#&@@RandomChoice@p;w[[i]]=FromCharacterCode[ToCharacterCode["àèìòùÀÈÌÒÙ"][[#&@@Position[v,w[[i]]]]]+RandomInteger@2]];w)&/@Split[#,{##}~FreeQ~" "&])&
```
Unnamed function taking a list of characters as input and returning a list of characters. Easier-to-read version, slightly ungolfed as well:
```
1 v = Characters["aeiouAEIOU"];
2 a = ToCharacterCode["àèìòùÀÈÌÒÙ"];
3 Join @@ (
4 (p = Position[w = #, Alternatives @@ v];
5 If[p != {},
6 i = First[RandomChoice[p]];
7 w[[i]] =
8 FromCharacterCode[
9 a[[ First[ Position[ v, w[[i]] ] ] ]] + RandomInteger[2]
10 ]
11 ]; w
12 ) &
13 ) /@ Split[#1, FreeQ[{##1}, " "] &] &
```
Line 13 splits the input into words (sublists of characters) at all the spaces; each word is operated on by the function defined by lines 4-12, and the results joined back together again in a single list by line 3.
Line 4 sets `p` to the list of indices indicating which characters of the word `w` are vowels. If there are any vowels (line 5), we make a random choice of one such index `i` (line 6) and then reset that single character of the word to a new character (lines 7-10). Finally we output the (possibly modified) word `w`.
To select the new character, we find where the vowel to be replaced sits in the string `v` and choose the corresponding character code from `a`. But to randomly select the three hats, we take that code and add a random integer between 0 and 2 (line 9) before converting back to a character. (Fortunately the behatted vowels all come in consecutive trios of UTF-8 character codes.)
[Answer]
# Python 3, 170 bytes
```
from random import *
c=choice
print(' '.join([w,w[:i]+c('̀́̂')+w[i:]][i>0]for w in input().split()for i in[c([j+1 for j,x in enumerate(w)if x in 'aeiouAEIOU']or[0])]))
```
Ungolfed:
```
from random import choice
print(' '.join([
w, # Don't modify the word if no vowels were found
w[:i] + choice('̀́̂') + w[i:]
][i > 0]
for w in input().split()
for i in [choice([j + 1 for j, x in enumerate(w) if x in 'aeiouAEIOU']
or [0]) # choice requires a non-empty sequence
]))
```
[Answer]
# [Python 3](https://docs.python.org/3/), 162 bytes
```
from random import*
print(*(w.insert(*choice([(n+1,q)for n,c in enumerate(w)if c in'AEIOUaeiou'for q in'̀́̂']or[(0,'')]))or''.join(w)for*w,in input().split()))
```
[Try it online!](https://tio.run/##TVG7TgMxEOz9FasU@ByiCESHBBJFQEhAEI@GKEIXxxcb7uxjz9FBB3wGHVSAEAU1ndv8U1hfeFU7M54Z2evyxmtn1@bSjdVGq9WaZ@gKwNSOaZiidOjbrERjfdJO6q6xlUKCUjsjVTJI7PJq50pkDsF2JBgLyk4LhalXSS1MBlHjW73d/mmqjJvy6LyK2ux2dje750OHg2Slw7kYCuGQ8@6FM5ayZGzXHSo0tpz6RHSrMjc0hZjTNRlDlebnzRlsLDyM1drkCk5wqtYZgMebOAB@XHlajMbpOvxFf2s5bAIXg5VhE1DXSiZxI4JFIlXpodff7iE6XFSOqONyXtNaFFI0gvCCbJRWmugoPFWaoabdFkQXgKGdQObrKCwQk6mPK/NagSa4CTI8eQhvUQqvoMOjZ@PwXNFJHMxXUofPKvIf2PyNNGV4J7FEyjaEHR71d4629vd3D3bg8PTsbK93DEsQ3wQTl2dkbhzh/tsSHv55wgtMwkeefQE "Python 3 – Try It Online")
] |
[Question]
[
I recently ordered some new and colorful tiles to replace my boring old white tiling for my kitchen. However, when the tiles arrived, they were all in a weird shape! Therefore, I need a program to figure out how to arrange the tiles so that I need to use as few of my old boring white tiling as possible.
Even though the tiles are weird, I'm not a fan of abstract design stuff, so the tiling should be regular. To be precise, it should be a **lattice**: there should no rotation or reflection of the tiles, and there should be two translations `S` and `T` which are combined to place the tiles with relative offsets of `aS + bT` for all `a` and `b`. Of course, the tiles shouldn't overlap when placed in this lattice arrangement.
I'll give you the tile in string format, and I need you to output the tiling. You may need to cut some of the tiles where they extend beyond the edges of my kitchen. For example:
```
abc abcdefabcdef
def -> cdefabcdefab
efabcdefabcd
```
can be broken down as
```
+-----+ +-+-----+ +-+
|a b c|d e f|a b c|d e f|
+-+ +-+---+-+ +-+---+
c|d e f|a b c|d e f|a b
+-+---+-+ +-+---+-+
e f|a b c|d e f|a b c|d
----+-+ +-----+-+ +-
```
where the translations are `(+6, 0)` and `(+4, +1)`. All but three of the tiles have been cut in this example.
You will be given a string to tile either via function parameter or STDIN. Spaces in the tile are considered "empty" and can be filled with other tiles.
My kitchen is 30x30 squares big, so all you need to do is make the number of empty squares is as small as possible in that area. You only need to print out 1 valid 30x30 square, which means that there may not be any lattice arrangement which has a 30x30 square with fewer empty squares.
Examples (I'm not going to give the full 30x30 square for brevity):
```
Input:
ab
a
Output:
abaaba
baabaa
aabaab
Input:
xxx
x x y
xxx
Output:
xxxxxxxxxxx
xyxxyxxyxxy
xxxxxxxxxxx
xxxxxxxxxxx
xyxxyxxyxxy
xxxxxxxxxxx
Input:
012
3 4
56
Output:
0123 456
23 45601
4560123
5601234
Input:
rrr
R r
Output:
rrrR r
R rrrr
rrrR r
Input:
defg
c
ab
Output:
cabdefg cab
defg cabdef
g cabdefg c
abdefg cabd
efg cabdefg
cabdefg ca
bdefg cabde
fg cabdefg
```
Your program should run in a reasonable amount of time, and this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program wins!
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 193 [bytes](https://github.com/abrudz/SBCS)
```
{G←{⍵⊃⍨⊃⍋(+/' '=,)¨⍵}
G{s←,30-⍳,⍨61
G,⊢∘⊂⌺30 30⊢((≢a)/⍪' '~⍨,x)@(B∘.+a)⊢''⍴⍨(⍴b)+⊃⌈/a←(⊢-⌊/)(⊃+/)¨s×⊂⍵}¨o/⍨(⍱/X∊⍨+/,-/)¨o←,∘.,⍨⊂¨∪{⍵/⍨0<2⊥¨×⍵}(,B∘.-⍸b<(1∊⊢)⌺3 3⊢b)~X←,B∘.-B←⍸b←(⍉0,⌽)⍣4⊢' '≠x←⍵}
```
[Try it online!](https://tio.run/##JY@xSgNBEIb7e4rtdpfbcy@eWCWgaQ4LsbAw7Z3x0gQipImEpEggXNZb0UK0lIhwpAsaEMEmvsm8yPnvpZmdnfnmn3@S237QvUv6g15FD89nF7R4DKsMcRy7QHZLZk62rOO98DVnvKXkrkRn4sXjISgVhQHZTwXsuOHFisyK8lcyMyp@opBFIQpC0HKVSE12DYUpUDWSJ6IN8MBPJAjOyX6hLvCk0ncLi1wn0BfoBlQYLZHNfY3tw78Xpw8Pu3Kg91Mb3aHcIPe1Chw0cN7cAlUfMIPpfO1OcgNh85DMx66EEFSEqp3gjO@0KRpOx6yk888iZKmcdpzYHmojdWBtzS5DRcWvJPt@5K5gnJZvo5rYTqoKpfqzeOLdm6yHNmPXiEnKPc69jI2q89PO1WWrEf8D "APL (Dyalog Unicode) – Try It Online")
A monadic dfn that takes a matrix of characters and returns the 30-by-30 matrix of a possible tiling with minimal blanks. Runs in 5 seconds for the smallest test case and in under a minute for the last one.
### The idea
The task looks pretty straightforward at first glance, but it was surprisingly hard to derive a valid solution, and even harder to get one that "runs in a reasonable amount of time" (which somewhat explains why it was unanswered so far).
The first obstacle was that there are infinitely many possible tiling vectors. I solved this by limiting the vectors to the ones where the original tile and the moved tile share at least a point. If `ab` is the given tile, this means the following movements are considered as tiling vector candidates:
```
AB AB AB AB AB
ABab ab ab ab ab ab abAB ab ab ab ab ab
AB AB AB AB AB
```
Then I filter out redundant ones (keeping only one of \$v\$ or \$w\$ when \$v = -w\$), generate all possible pairs of these candidate tiling vectors, and only keep the ones \$v, w\$ where neither \$v+w\$ nor \$v-w\$ movement overlaps with the original tile.
Reasoning: We know that the pairs of tiles at offsets \$(0, v)\$ and \$(0, w)\$ do not overlap, and therefore \$(v, v+w)\$ and \$(w, v+w)\$. Once it is known that \$(0, v+w)\$ and \$(v, w)\$ (alternatively \$(0, v-w)\$) pairs are safe, we know that \$(0, v, w, v+w)\$ are mutually safe, and by translation in four directions \$v, w, -v, -w\$, the entire infinite tiling is safe.
Given a full list of candidate vector pairs, I chose a naive way: for each vector pair, generate a large enough board of actual tiling, extract all 30-by-30 regions, and choose the one with the smallest number of blanks. For that, I used \$-30 \le a,b \le 30\$ for the formula \$av + bw\$. In order to prevent the memory (and execution time) blowing up, I apply this filtering twice, first within each vector pair, and then across all minimally chosen boards.
### Ungolfed
The code changed a lot while golfing, but the core idea remains the same.
```
f←{
⍝ A boolean matrix where 1 means non-blanks, padded once to all directions
bool←(⍉0,,∘0)⍣2⊢' '≠x←⍵
⍝ Spread 1s to adjacent cells (8 directions)
padded←({1∊⍵}⌺3 3>⊢)bool
⍝ Extract the coordinates of ones
cbool←⍸bool
cpadded←⍸padded
⍝ badoffs: All offsets that move a cell to already occupied cell
⍝ offs: All offsets that move a cell to a cell adjacent to the tile,
⍝ badoffs removed and (negative, any) and (zero, negative) removed
offs←∪{⍵/⍨0<2⊥¨×⍵}(,cbool∘.-cpadded)~badoffs←,cbool∘.-cbool
⍝ Pairs of valid offsets
offpairs←,∘.,⍨⊂¨offs
⍝ Remove offset pairs (v,w) if v+w or v-w is bad
filter←{⍱/(⍺+⍵)(⍺-⍵)∊badoffs}/¨offpairs
pairs←filter/offpairs
⍝ Aux. function: Select the matrix with smallest number of blanks
MinBlanks←{⍵⊃⍨⊃⍋(+/' '=,)¨⍵}
⍝ Aux. function: Given an offset pair, tile the floor using them and
⍝ extract the 30x30 region with minimum blanks
GetResults←{
somepair←⍵
⍝ -30 to 30, inclusive (the values of a and b)
steps←30-⍳61
⍝ All values of av + bw, offset to the minimum coordinates of (0,0)
alloffs←⊃{,(steps×⊂⍺)∘.+steps×⊂⍵}/somepair
alloffs-←⌊/alloffs
⍝ Initialize a big enough blank grid
dims←(⍴bool)+⊃⌈/alloffs
grid←dims⍴''
⍝ Fill the grid with the tiles' cells moved accordingly
filled←((≢alloffs)/⍪' '~⍨,x)@(cbool∘.+alloffs)⊢grid
⍝ Extract all 30x30 regions and return the one with minimum blanks
results←,{⊂⍵}⌺30 30⊢filled
MinBlanks results
}
⍝ Map the above function over each of the pairs, and extract min blanks
results←GetResults¨pairs
MinBlanks results
}
```
] |
[Question]
[
This challenge is based on actual collision detection I had to write for a simple game recently.
Write a program or function which, given two objects, returns a [truthy or falsy value](http://meta.codegolf.stackexchange.com/a/2194/8478) depending on whether the two objects are in collision (i.e. intersect) or not.
You need to support three types of objects:
* **Line segments**: represented by 4 floats, indicating the two endpoints, i.e. *(x1,y1)* and *(x2,y2)*. You may assume that the endpoints are not identical (so the line segment is not degenerate).
* **Discs**: i.e. filled circles, represented by 3 floats, two for the centre *(x,y)* and one (positive) for the radius *r*.
* **Cavities**: these are a disc's complement. That is, a cavity fills all of 2D space, *except* a circular region, specified by a centre and radius.
Your program or function will receive two such objects in the form of an identifying integer (of your choice) and their 3 or 4 floats. You can take input via STDIN, ARGV or function argument. You may represent the input in any convenient form that is not preprocessed, e.g. 8 to 10 individual numbers, two comma-separated list of values or two lists. The result can be returned or written to STDOUT.
You may assume that the objects are either at least 10-10 length units apart or intersect by that much, so you don't need to worry about the limitations of floating point types.
This is code golf, so the shortest answer (in bytes) wins.
## Test Cases
Representing line segments with `0`, discs with `1` and cavities with `2`, using a list-based input format, the following should all produce a truthy output:
```
[0,[0,0],[2,2]], [0,[1,0],[2,4]] # Crossing line segments
[0,[0.5,0],[-0.5,0]], [1,[0,0],1] # Line contained in a disc
[0,[0.5,0],[1.5,0]], [1,[0,0],1] # Line partially within disc
[0,[-1.5,0.5],[1.5,0.5]], [1,[0,0],1] # Line cutting through disc
[0,[0.5,2],[-0.5,2]], [2,[0,0],1] # Line outside cavity
[0,[0.5,0],[1.5,0]], [2,[0,0],1] # Line partially outside cavity
[0,[-1.5,0.5],[1.5,0.5]], [2,[0,0],1] # Line cutting through cavity
[1,[0,0],1], [1,[0,0],2] # Disc contained within another
[1,[0,0],1.1], [1,[2,0],1.1] # Intersecting discs
[1,[3,0],1], [2,[0,0],1] # Disc outside cavity
[1,[1,0],0.1], [2,[0,0],1] # Disc partially outside cavity
[1,[0,0],2], [2,[0,0],1] # Disc encircling cavity
[2,[0,0],1], [2,[0,0],1] # Any two cavities intersect
[2,[-1,0],1], [2,[1,0],1] # Any two cavities intersect
```
while the following should all result in a falsy output
```
[0,[0,0],[1,0]], [0,[0,1],[1,1]] # Parallel lines
[0,[-2,0],[-1,0]], [0,[1,0],[2,0]] # Collinear non-overlapping lines
[0,[0,0],[2,0]], [0,[1,1],[1,2]] # Intersection outside one segment
[0,[0,0],[1,0]], [0,[2,1],[2,3]] # Intersection outside both segments
[0,[-1,2],[1,2]], [1,[0,0],1] # Line passes outside disc
[0,[2,0],[3,0]], [1,[0,0],1] # Circle lies outside segment
[0,[-0.5,0.5],[0.5,-0.5]], [2,[0,0],1] # Line inside cavity
[1,[-1,0],1], [1,[1,1],0.5] # Non-intersecting circles
[1,[0.5,0],0.1], [2,[0,0],1] # Circle contained within cavity
```
[Answer]
## APL, ~~279~~ ~~208~~ ~~206~~ 203
```
s←1 ¯1
f←{x←⊣/¨z←⍺⍵[⍋⊣/¨⍺⍵]
2 2≡x:∧/0∧.=⌊(2⊃-⌿↑z)⌹⍣(≠.×∘⌽/x)⍉↑x←s×-/2⊢/↑z
2≡2⌷x:∨/((2⊃z)∇2,x[1]×(2⌷⊃z)+,∘-⍨⊂y÷.5*⍨+.×⍨y←⌽s×⊃-/y),x[1]=(×⍨3⊃⊃z)>+.×⍨¨y←(s↓⌽↑z)-2⌷⊃z
~x∨.∧x[1]≠(.5*⍨+.×⍨2⊃-⌿↑z)<-/⊢/¨z×s*1⌷x}
```
Line breaks in the function `f` are for clarity. They should be replaced with the statement separator `⋄`
It has been so long since I last made such a complex APL program. I think the last time was [this](https://codegolf.stackexchange.com/a/13010/6972) but I am not even sure that was as complex.
**Input format**
Basically same as the OP, except using `0` for cavity, `1` for disc and `2` for line segment.
**Major update**
I managed to golf a lot of chars using a different algorithm. No more `g` bulls\*\*t!!
The main function `f` is divided into cases:
---
**`2 2≡x`: Segment-segment**
In this case, calculate the vector from the end points of each line and solve a system of linear equations to check if the intersection is contained within the vectors.
Caveats:
* The end point of a vector is not considered as a part of the vector (while its origin is). However, if only the tip of a vector is on the other one, the input is invalid according to spec.
* Non-degenerate parallel segments always returns false, regardless of collinearity.
* If one of the segments is degenerate, always return false. If both segments are degenerate, always return true.
Examples: (Note caveat 1 in action in the figure on the right)


---
**`2≡2⌷x`: Segment-other**
In this case, the other object is a circular one. Check if the end points of the segment is within the circle using distance check.
In the disc case, also construct a line segment of the diameter perpendicular to the given segment. Check if the segments collide by recursion.
In the cavity case, sneak in a "times 0" in the construction of the said segment to make it degenerate. (See why I use `0` for cavity and `1` for disc now?) As the given segment is not degenerate, the segment-segment collision detection always return false.
Finally combine the results of the distance checks and the collision detection. For the cavity case, negate the results of the distance checks first. Then (in both cases) OR the 3 results together.
Regarding the segment-segment caveats, numbers 3 is addressed (and exploited). Number 2 is not a problems as we are intersecting perpendicular segments here, which are never parallel if they are not degenerate. Number 1 takes effect only in the disc case, when one of the given end points is on the constructed diameter. If the end point is well inside the circle, the distance checks would have taken care of it. If the end point is on the circle, since the constructed diameter is parallel to the given segment, the latter must be tangent to the circle with only one point touching the disc, which is not valid input.
Examples:


---
**Default case: Other-other**
Calculate the distance between the centers. Disc-disc collision occurs if and only if the distance is smaller than the sum of radii. Disc-cavity collision occurs if and only if the distance is greater than the difference in radii.
To take care of the cavity-cavity case, negate the result of the distance check, AND with each of the identifying integers and then OR them together. Using some logic, one can show that this process returns true if and only if both identifying integers are falsy (Cavity-cavity case), or if the distance check returned true
[Answer]
# Javascript - 393 bytes
Minified:
```
F=(s,a,t,b,e,x)=>(x=e||F(t,b,s,a,1),[A,B]=a,[C,D]=b,r=(p,l)=>([g,h]=l,[f,i]=y(h,g),[j,k]=y(p,g),m=Math.sqrt(f*f+i*i),[(f*j+i*k)/m,(f*k-i*j)/m]),u=(p,c)=>([f,g]=c,[i,j]=y(p,f),i*i+j*j<g*g),y=(p,c)=>[p[0]-c[0],p[1]-c[1]],[n,o]=r(C,a),[q,v]=r(D,a),w=(v*n-o*q)/(v-o),z=r(B,a)[0],Y=u(A,b),Z=u(B,b),[v*o<0&&w*(w-z)<0,Y||Z||o<D&&o>-D&&n*(n-z)<0,!Y||!Z,x,u(A,[C,D+B]),B>D||!u(A,[C,D-B]),x,x,1][s*3+t])
```
Expanded:
```
F = (s,a,t,b,e,x) => (
x = e || F(t,b,s,a,1),
[A,B] = a,
[C,D] = b,
r = (p,l) => (
[g,h] = l,
[f,i] = y(h,g),
[j,k] = y(p,g),
m = Math.sqrt( f*f + i*i ),
[(f*j + i*k)/m, (f*k - i*j)/m] ),
u = (p,c) => (
[f,g] = c,
[i,j] = y(p,f),
i*i + j*j < g*g ),
y = (p,c) => [p[0] - c[0], p[1] - c[1]],
[n,o] = r(C,a),
[q,v] = r(D,a),
w = (v*n - o*q)/(v - o),
z = r(B,a)[0],
Y = u(A,b), Z = u(B,b),
[ v*o < 0 && w*(w-z) < 0,
Y || Z || o < D && o > -D && n*(n-z) < 0,
!Y || !Z,
x,
u(A,[C,D+B]),
B > D || !u(A,[C,D-B]),
x,
x,
1
][s*3+t]);
```
Notes:
* defines function `F` that accepts the required arguments and returns the required value
* input format is identical to format in the OP, with the exception that the integer type code for each primitive is separate from the tuple. For example, `F( 0,[[0,0],[2,2]], 0,[[1,0],[2,4]] )` or `F( 1,[[3,0],1], 2,[[0,0],1] )`.
* code validated on all test cases supplied in the OP
* should handle all edge and corner cases, including zero-length line segments and zero-radius circles
[Answer]
# Python, 284
I'm using a pretty garbage algorithm compared to all these geometric tricks, but it gets the right answers even though it takes a over a minute to get through the test cases. The big advantage is that I only have to write the three scoring functions, and the hillclimbing takes care of all the edge cases.
Golfed:
```
import math,random as r
n=lambda(a,c),(b,d):math.sqrt((a-b)**2+(c-d)**2)
x=lambda(t,a,b),p:max(eval(["n(b,p)-n(a,b)+","-b+","b-"][t]+'n(a,p)'),0)
def F(t,j):
q=0,0;w=1e9
for i in q*9000:
y=x(t,q)+x(j,q)
if y<w:p,w=q,y
q=(r.random()-.5)*w+p[0],(r.random()-.5)*w+p[1]
return w<.0001
```
Ungolfed:
```
import math
import random as r
def norm(a, b):
return math.sqrt((a[0] - b[0])**2 + (a[1] - b[1])**2)
def lineWeight(a, b, p):
l1 = norm(a, p)
l2 = norm(b, p)
return min(l1, l2, l1 + l2 - norm(a, b))
def circleWeight(a, r, p):
return max(0, norm(a, p) - r)
def voidWeight(a, r, p):
return max(0, r - norm(a, p))
def weight(f1, f2, s1, s2, p):
return f1(s1[1], s1[2], p) + f2(s2[1], s2[2], p)
def checkCollision(s1, s2):
a = [lineWeight, circleWeight, voidWeight]
f1 = a[s1[0]]
f2 = a[s2[0]]
p = (0.0, 0.0)
w = 0
for i in a*1000:
w = weight(f1, f2, s1, s2, p)
p2 = ((r.random()-.5)*w + p[0], (r.random()-.5)*w + p[1])
if(weight(f1, f2, s1, s2, p2) < w):
p = p2
if w < .0001:
return True
return False
```
And finally, a test script in case anyone else wants to try this in python:
```
import collisiongolfedbak
reload(collisiongolfedbak)
tests = [
[0,[0,0],[2,2]], [0,[1,0],[2,4]], # Crossing line segments
[0,[0.5,0],[-0.5,0]], [1,[0,0],1], # Line contained in a disc
[0,[0.5,0],[1.5,0]], [1,[0,0],1], # Line partially within disc
[0,[-1.5,0.5],[1.5,0.5]], [1,[0,0],1], # Line cutting through disc
[0,[0.5,2],[-0.5,2]], [2,[0,0],1], # Line outside cavity
[0,[0.5,0],[1.5,0]], [2,[0,0],1], # Line partially outside cavity
[0,[-1.5,0.5],[1.5,0.5]], [2,[0,0],1], # Line cutting through cavity
[1,[0,0],1], [1,[0,0],2], # Disc contained within another
[1,[0,0],1.1], [1,[2,0],1.1], # Intersecting discs
[1,[3,0],1], [2,[0,0],1], # Disc outside cavity
[1,[1,0],0.1], [2,[0,0],1], # Disc partially outside cavity
[1,[0,0],2], [2,[0,0],1], # Disc encircling cavity
[2,[0,0],1], [2,[0,0],1] , # Any two cavities intersect
[2,[-1,0],1], [2,[1,0],1] , # Any two cavities intersect
[0,[0,0],[1,0]], [0,[0,1],[1,1]] , # Parallel lines
[0,[-2,0],[-1,0]], [0,[1,0],[2,0]], # Collinear non-overlapping lines
[0,[0,0],[2,0]], [0,[1,1],[1,2]], # Intersection outside one segment
[0,[0,0],[1,0]], [0,[2,1],[2,3]], # Intersection outside both segments
[0,[-1,2],[1,2]], [1,[0,0],1], # Line passes outside disc
[0,[2,0],[3,0]], [1,[0,0],1], # Circle lies outside segment
[0,[-0.5,0.5],[0.5,-0.5]], [2,[0,0],1], # Line inside cavity
[1,[-1,0],1], [1,[1,1],0.5], # Non-intersecting circles
[1,[0.5,0],0.1], [2,[0,0],1] # Circle contained within cavity
]
for a, b in zip(tests[0::2], tests[1::2]):
print collisiongolfedbak.F(a,b)
```
] |
[Question]
[
A Young diagram is a rectangular binary mask whose every row and every column are sorted in descending order.
It is easy to check that every rectangular binary mask can be formed by xor-ing together a finite number of Young diagrams.
This decomposition is by no means unique, but there will be a minimum number of Young diagrams required. Your task in this code golf challenge is given a number \$k\$ and an \$m\$-by-\$n\$ binary mask \$b\$ determine whether \$b\$ can be represented as xor of \$k\$ \$m\$-by-\$n\$ Young diagrams.
Example xor decompositions: These are minimal and can be used as test cases: Just take the leftmost pattern. The minimum number of Young diagrams is written just below it. If you take the pattern together with a smaller number you get a falsy test case and a truthy one otherwise. Your code needn't output the decomposition. It is typically not unique anyway.
```
1001 1000 1110 1111 1111 1111
0010 <- 0000 1100 1110 1111 1111
1001 0000 0000 1000 1110 1111
5
0010 1100 1110
0110 <- 1000 1110
1100 0000 1100
2
1001 1000 1100 1100 1110 1111
0100 <- 0000 1000 1100 1110 1110
1010 0000 0000 1000 1100 1110
5
1010 1000 1100 1110 1111 1111
1011 <- 0000 0000 1000 1100 1111
0010 0000 0000 0000 1100 1110
5
00111110 11000000 11110000 11110000 11111110 11111111 11111111
11101001 <- 00000000 11100000 11110000 11111000 11111110 11111111
00110111 00000000 00000000 11000000 11110000 11111000 11111111
6
10111010 10000000 11000000 11100000 11100000 11111000 11111100 11111110 11111111 11111111
10010111 <- 00000000 00000000 10000000 11100000 11110000 11111000 11111110 11111110 11111111
11100101 00000000 00000000 00000000 00000000 11100000 11111000 11111100 11111110 11111111
9
11100110 11100000 11110000 11110000 11111000 11111110 11111111 11111111
00110110 <- 00000000 11000000 11110000 11111000 11111110 11111111 11111111
00100001 00000000 00000000 00000000 11000000 11100000 11111110 11111111
7
10110011 10000000 11000000 11110000 11111000 11111000 11111100 11111111 11111111 11111111
00111100 <- 00000000 00000000 00000000 11000000 11111000 11111000 11111100 11111111 11111111
01110101 00000000 00000000 00000000 10000000 11110000 11111000 11111100 11111110 11111111
9
10110 10000 11000 11110 11111 11111
01111 00000 10000 11110 11110 11111
11101 <- 00000 00000 11100 11110 11111
10000 00000 00000 10000 11110 11110
00110 00000 00000 00000 11000 11110
5
00101 11000 11100 11110 11111 11111 11111
10010 00000 10000 11100 11110 11111 11111
10010 <- 00000 10000 11100 11110 11111 11111
10101 00000 10000 11000 11100 11110 11111
11011 00000 00000 00000 11000 11100 11111
6
0111101 1000000 1110000 1110000 1111100 1111110 1111111 1111111 1111111
1101000 0000000 1100000 1110000 1111000 1111100 1111100 1111111 1111111
1001100 <- 0000000 0000000 0000000 1000000 1110000 1111100 1111111 1111111
0000001 0000000 0000000 0000000 0000000 1110000 1110000 1111110 1111111
0110010 0000000 0000000 0000000 0000000 1000000 1110000 1111100 1111110
8
0001010 1000000 1000000 1110000 1111000 1111100 1111110 1111111 1111111
1000011 0000000 1000000 1100000 1100000 1111000 1111000 1111100 1111111
0100011 <- 0000000 0000000 1000000 1100000 1111000 1111000 1111100 1111111
1011010 0000000 0000000 0000000 1000000 1100000 1111000 1111100 1111110
1111110 0000000 0000000 0000000 0000000 0000000 0000000 0000000 1111110
8
011000101 100000000 111000000 111111000 111111100 111111110 111111110 111111110 111111111
000100001 000000000 000000000 111000000 111100000 111111110 111111110 111111110 111111111
111100111 <- 000000000 000000000 000000000 111100000 111111000 111111110 111111110 111111111
111100001 000000000 000000000 000000000 000000000 000000000 111100000 111111110 111111111
110000000 000000000 000000000 000000000 000000000 000000000 000000000 000000000 110000000
8
001100011 110000000 111100000 111110000 111110000 111111100 111111110 111111110 111111111 111111111 111111111
000110101 110000000 110000000 111000000 111110000 111111000 111111100 111111110 111111111 111111111 111111111
011011100 <- 100000000 110000000 110000000 111000000 111100000 111111000 111111000 111111100 111111111 111111111
100000001 000000000 100000000 110000000 110000000 111100000 111100000 111111000 111111000 111111110 111111111
110101001 000000000 000000000 000000000 110000000 111000000 111100000 111110000 111111000 111111110 111111111
10
```
Standard rules apply.
[Answer]
# [Python](https://www.python.org) with [numpy](https://numpy.org/), ~~94~~ 93 bytes
```
from numpy import*
S=cumsum
f=lambda k,m:f(k-1,flip(S(S(flip(m),0),1)>0)^m)if k else any(m)<1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PVFNT-MwENUe61_hW22UIs9ltUKUG1w5wA0VKRSHWo0dy0kE_S176WX5T_BrmA9nE8WZefPmvZnk72c-TYchnc__5qnb_PnadWWIOs0xn3SIeSjThXrY7uc4zlF1276NL6-tPjbxqjPHDTRdH7J5wJuDaBtnG7A3zj5HGzp91L4fvW7TCWvXUE2-9rHXW_20U1M5XanV-yH0Xj-W2WOy6kPyWA0pz5OxCKAOYVRbYedlm7NPr6YP42Rim01IU0MEa4lNhkzthoL-IenSpjdv4LdleJULNpiD_zBH-7SBnUZ9XKZBaSvjrjfrRqPFdr0mxdphq79M7j_2Pk_69v7utpShoHRux1EWPH__-gTnQOHjFEcSOqAcASWooxCoIicetYlOuohOJRGjOjAXYJFmiHIKVY3IS-gcOMczcF4tmKeq0FLjXNRAcZfIyPggfv9PRnhk6aupc0JhfSfWYsw6bplcJgF5s71sC2IIIFxpYRWoyy2RYOJRP1lVleWrsay68OqQ8lfkf_0A)
Takes a sequence of sequences of `int`s.
---
This uses a greedy algorithm.
Let A be the smallest Young diagram that contains the input (that is, has 1s where the input has 1s). I claim that A is part of an optimal solution.
Observe that the AND of two Young diagrams is a Young diagram, and the OR of two Young diagrams is a Young diagram.
Firstly, any solution can be converted to a solution that lies within A by ANDing each diagram with A.
Next, if the solution is X,Y,Z, we can replace X and Y with X|Y and X&Y without changing the overall XOR. Apply the same process to X|Y and Z next, to obtain a solution that includes X|Y|Z; this necessarily contains A, and thus is equal to A. (A similar repeating process works on solutions of any size.)
---
After `flip` reverses the input, `cumsum` in each direction spreads positiveness forwards, then `>0` reduces the entries back to Booleans. `flip` again to return to the original orientation, then apply the XOR.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes
```
NθWS⊞υI⪪⮌ι¹FθUMυEκ⁻⌈E✂υλLυ¹⌈…ξ⊕νμ⌈⌈υ
```
[Try it online!](https://tio.run/##TU5BbgMhDLzzCh@NRCU497inSE0VdV9AiZtFBXbDQpq@nmL2UiN5YMYzxi02u9WG1k5pq@W9xk/KeJev4mfxgQAHPZfs0w2lhEvdF6wKJrsXnLfgC37Qg/JO6KUCI2W3fq0Zegac7TatMdp0ZUt/4XcHn@qOZ/v0sUZkcg7eEU8EBW@UbqVvGFnsOcamXxdoWtYNnwpOyWWKlApdMUkuBXEsvvRvln/ZB1bWWjNaaG2M5iZG1/2IgUwLlriMOCS@tZdH@AM "Charcoal – Try It Online") Link is to verbose version of code. Takes input as `k` and then the binary mask represented as a list of newline-terminated strings, and outputs `-` if `k` was too small, nothing if `k` was sufficient. Explanation: Uses a greedy algorithm.
```
Nθ
```
Input `k`.
```
WS⊞υI⪪⮌ι¹
```
Convert the newline-terminated list of strings into a binary matrix, although flip it horizontally because that saves a byte.
```
Fθ
```
Loop `k` times.
```
UMυEκ⁻⌈E✂υλLυ¹⌈…ξ⊕νμ
```
Flip only those bits in the array that have a `1` bit in the rectangle whose original corners are the bit and the bottom right corner of the array. The array of the bits that were flipped is itself a Young diagram and the result of the flip is the same as the XOR of that diagram with the array.
```
⌈⌈υ
```
If `k` was sufficient, then the array will be all `0`s, so its double maximum will also be `0`, but if it was insufficient, then the maximum row will contain a `1`, so the double maximum will also be `1`. This is then output in unary as a count of `-`s.
Example:
```
0010
0110
1100
```
All the `1`s get flipped because obviously any rectangle containing them contains a `1`, but the `0`s above and left also get flipped because there is a `1` in the rectangle from them to the bottom right corner. The Young matrix of bits that get flipped is therefore as follows:
```
1110
1110
1100
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 55 bytes
**-27 bytes thanks to @att.**
```
r/@r@#-#&~Nest~##==0#&
r=#@*FoldList[BitOr]@*#&@Reverse
```
[Try it online!](https://tio.run/##tZFBC4IwFMfvfooHDzyIkQuMOhijQ6eo6CoepCYJWTBHF5lffbnS3NRr4zHeeO/3f/9tRSpurEhFfklVBpHic8opztCtD6wUNWIUBeg6PELq7Z736z4vRbzNxZEn1EOXntmL8ZKpE88fIq4QJcw2kMWISQIuUEodqJpFfAg@QaQPVZs2uz4ZteYYSt8BzdhN39RAWkojiw4ZTemaflNIi4Q2QoZNQ5uTxswwbPWSEzcmJqxllyMnloT9QBY8GNjXtez6P7IrQ3bQYvzU@Kp2JTCidSvVGw "Wolfram Language (Mathematica) – Try It Online")
---
## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 82 bytes
```
If[#==0#,0,1+#0[#~BitXor~Map[Reverse@FoldList[BitOr,Reverse@#]&,#,{0,1}]]]&@#<=#2&
```
[Try it online!](https://tio.run/##bZBNC8IwDIbv@xWBwC5WaAcKgpPiQRAUxZNQehg6ceAXs3gZ3V@frW7abiuhpE2eN297TdQ5vSYqOyTVCeJqeRIYxxQJJWyAVGA5z9T@npfr5CF26SvNnylf3C/HVfZUwtQ2OWmuUYYESWFILaUMOU5jjMJqm2c3JQpEDcMZGH2UEkLgnAdQmMUI0E8wTaCoU7Pbk1Mzx5EmAVjGb/qmDlJTFokapDOlafpNYTUy8hHWbmrb7DXmhmPrL9nzYubCVnbcceJJ@B/kwa2B/7qVnTiyrRbnS7ue/Ap1opbV1Rs "Wolfram Language (Mathematica) – Try It Online")
Or shorter if I can just take the matrix and output the minimum number \$k\$.
```
If[#==0#,0,1+#0[#~BitXor~Map[Reverse@FoldList[BitOr,Reverse@#]&,#,{0,1}]]]&
```
[Try it online!](https://tio.run/##bVDdCsIgFL7fUxwQdpORPsBidBEERdFVIF5IbTRoLZx0I@7VzWpr6oKDHP1@zuephboWtVDVWdgSMrspGcoygjDBdIYIQ92qUqdGdjvxYMfiWci2yNfN7bKtWsUctpd4eEY8xQhrpzSc89QeZHVXDMF8Cc6Vc0hhkSegtaYYyKeowaD71p3vm4cZnICjh/i39di9YGBPvAf8500nbBrjca44iV9ejtHtz@@oL57MD9ThHgJdNGvEPccI9TY3TRIixCvnaOwL "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 39 bytes
```
Lm|MCd._CbWss=QmxMCdC,Q__Myy__MQ=hZ;>EZ
```
[Try it online!](https://tio.run/##K6gsyfj/3ye3xtc5RS/eOSm8uNg2MLcCyHPWCYyP962sBBKBthlR1nauUf//R0cb6igYgJFhrI5CNJQJJEE8JLlYLlMA "Pyth – Try It Online")
A port of @m90's answer, be sure to upvote them.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 25 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ZLr0œċL⁸ḣ"ⱮFE$ƇḢ!^µÐ¡§§0e
```
A full program that accepts a rectangular list of lists of ones and zeros and a non-negative integer and prints `1` if possible or `0` if not.
**[Try it online!](https://tio.run/##y0rNyan8/z/Kp8jg6OQj3T6PGnc83LFY6dHGdW6uKsfaH@5YpBh3aOvhCYcWHlp@aLlB6v///6OjDXUMgNAwlksnGszQMQAx4aKx/00B "Jelly – Try It Online")**
This [test-suite](https://tio.run/##PVExjsJADOz3FxxIae0f0ECFdD1CdGlOVHSUoaG45iReABRpEBLohIKQKDbAP3Y/shd7vBcJM7bHM3byVS4Wq5SmkyW9ts/vSaya0Bw@4vk0Hg3em9Dse3PXbmJ1a3/8zte@pjK9tuF2iNXDX/013H8/Q7Omth5yf/C@xPUxpaIoZo6J2HU/AgIklrwrOOsLZOkgdsGGJMojdGlBTPqsXOYsrSXJBTpD4gW6AiLdQXOzUJ4zodzTHGrsdAoyWJ/h9x@1oitjzlIiUFSfYA1j1aG8OTZh/Ks9rmUYMoOLEVVhOy4j1OBhr8xUcbwZ49TMsyVFqPtQfw "Jelly – Try It Online") alters the code so it is callable as a dyadic Link (by replacing the `µ` with a newline and `Ç⁹`) and calls the link starting with `0` until a truthy result is found for each of the grids and returns the values reached. Note that going any higher is guaranteed to give a truthy result due to the implementation (repeatedly applying an operation and collecting up).
### How?
Greedily inverts the Young "cut-out" that contains all of the same elements with the maximal row-length array. Performs this \$N\$ times and then checks for the existence of an array with no ones.
```
ZLr0œċL⁸ḣ"ⱮFE$ƇḢ!^µÐ¡§§0e - Main Link: grid of 1s and 0s, G (n rows, m columns)
С - repeat and collect (starting with G)...
- ...times: (implicit) second program argument, N
µ - ...action: the monadic chain to the left - f(Current):
Z - transpose (Current)
L - length
r0 - inclusive range to 0 -> [m,...,2,1,0]
L - length (Current) -> n
œċ - combinations with replacement
-> [[m,m,m],...,[m,m,1],[m,m,0],[m,m-1,m-1],...,[0,0,0]]
⁸ - chain's left argument -> Current
Ɱ - map with:
" - zip with:
ḣ - head to
-> Young-style "cut-outs" reverse sorted by row-lengths
Ƈ - keep those for which:
$ - last two links as a monad:
F - flatten
E - all equal?
Ḣ - head
! - factorial (vectorises) -> converts all 0s to 1s
^ - XOR (Current)
§ - sums
§ - sums
0 - zero
e - exists in?
```
[Answer]
# [Python](https://www.python.org) + NumPy, 82 bytes
```
from numpy import*
f=lambda k,m:~k<0<all(~m)|f(k-1,triu([[email protected]](/cdn-cgi/l/email-protection)<2)@m@tril(m[0]<2)^m)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RVHBTuMwEBXH-Ct8q41S5OGAEGqlXtjrSituVRcFcGgUO7FcR0slxI9w6WX5p91_2H_YGY8DkeK8mXnz3kz8_hGOaT8Op9PvKbXL6z8_2jh6OUw-HGXnwxjTuWjXrvEPT43sa3_z1q_MqnFOvXn92qp-CXWK3aT8xl_crS71xm8wdspvzQ7Dn14X5X-P3sm13O5EiscbUf3ad87KuzhZDCrXDRar3RCmpDQmulZSjmoVdl40IdjhSbnukJRvguqGVBNBa2Jbd_ikoszDOLp7hZhqVTtG2aO0jM3wbBVc6UytQkQRtbcvqtfbJewkeuJGNfVJUpSL5aKWaLteLLISd-gvI9zGvjzakOTt92-3MY4RpUNzOPDSp79nH2AMCHyNyIihAYoxIThrCAJV-MSjNNFJD9GpxGJUh8wFmKVzimKCoiDyYnoGxuQZclwsMk8UobmWY1YDkbtYhscH9vs8cyaPzH0lNIYpWd-wNRtnHTNPzpMAf7M9bwtsCMBcbskqUJabEefYo_yyosrLF2NedeaVIflW-L7-Aw)
As @m90 doesn't seem to want my golfs and I don't want to let them go to waste I post them here.
This takes the input mask as a boolean array.
#### How?
It uses that a cumsum can be written as multiplication with a triangular matrix. By choosing upper or lower triangles we can choose whether to sum from left to right or from right to left.
Also, note that matrix multiplication preserves the type, bool in this case, so we needn't restore any larger values to 1.
Also worthwhile noting that NumPy bools behave differently to Python bools w.r.t. to `~`.
] |
[Question]
[
>
> Weather forecasting: Wrong too often to rely on, right too often to ignore.
>
>
>
Given a high and low temperature and one of four weather conditions per day, output an ASCII-art graphical five day weather forecast. The structure of the four graphical indicators are shown below.
```
\ /
-O- Sunny
/ \
\ /
-O(==) Partly Cloudy
(====)
(==) Cloudy
(====)
(==)
(====) Rainy
/////
```
The forecasting chart is as follows: each graphical indicator is centered in its own 9x5 box, with 5 boxes across the chart. Each box is separated by `|` characters. Below the graphical indicator is a three-letter abbreviation for the day of the week (`MON, TUE, WED, THU, FRI, SAT, SUN`) centered in its own 9x1 box. The temperatures are below the day of the week centered in their own 9x2 box. An example is shown below.
```
---------------------------------------------------
| | | | | |
| (==) | (==) | \ / | \ / | \ / |
| (====) | (====) | -O(==) | -O- | -O- |
| | ///// | (====) | / \ | / \ |
| | | | | |
---------------------------------------------------
| MON | TUE | WED | THU | FRI |
---------------------------------------------------
| H 75 | H 69 | H 77 | H 80 | H 85 |
| L 57 | L 53 | L 61 | L 63 | L 66 |
---------------------------------------------------
```
Note that "centered" can be taken loosely -- see in the example how the graphical alignment and the temperature horizontal alignment are somewhat flexible.
Additionally, since I'm from the US and therefore use Fahrenheit, you can safely assume that the temperatures are all double-digit, so `9 < t < 100`.
### I/O and Rules
*The I/O examples here are demonstrative of the above example chart.*
* Input can be taken in any reasonable format and [by any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). For example,
1) you could use numbers for the days of the week, the high and low temperatures, and the four conditions, and take input as five tuples, like `[0, 75, 57, 2], [1, 69, 53, 3], ...`
2) you could take input as five tuples using words, like `['MON', 75, 57, 'CLOUDY'], ['TUE', 69, 53, 'RAINY'] ...`
3) you could take input as just the first day, and a list of high temperatures, a list of low temperatures, and a list of conditions, like `1, [75, 69, ...], [57, 53, ...], [2, 3, ...]`
4) etc.
* Leading/trailing newlines or other whitespace are optional, provided that the characters line up appropriately.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* Output can be to the console, returned as a list of strings, returned as a single string, etc.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins.
[Answer]
# [Emojicode](http://www.emojicode.org/), ~~1202~~ 974 bytes
```
üçáaüç®üêöüç®üêöüöÇüçÆfüî∑üç®üêöüç®üêöüî°üê∏üç¶Düç®üî§ MON üî§üî§ TUE üî§üî§ WED üî§üî§ THU üî§üî§ FRI üî§üî§ SAT üî§üî§ SUN üî§üçÜüçÆfüç®üç®üî§ / \ üî§üî§ \ / üî§üî§ -O- üî§üçÜüç®üî§(====)üî§üî§\ / üî§üî§-O(==)üî§üçÜüç®üî§ üî§üî§ (==)üî§üî§(====)üî§üçÜüç®üî§///// üî§üî§ (==)üî§üî§(====)üî§üçÜüçÜüç¶lüî§ ---------------------------------------------------üî§üç¶uüî§ üî§üç¶süî§ | üî§üç¶Süî§ | üî§üç¶wüç®üî§üî§üî§üî§üî§H üî§üî§L üî§üçÜüòÄlüç¶Lüç™s u s u s u s u s u süç™üòÄLüçÆoüî§üî§üîÇi‚è©-2 4üçáüçÆo süçä‚óÄÔ∏è1iüçáüçÆoüç™süî§ üî§üç™üçâüîÇj‚è©0 5üçáüçä‚ñ∂Ô∏è1iüçáüçÆoüç™oüç∫üêΩüç∫üêΩfüç∫üêΩüç∫üêΩa j 0i süç™üçâüçã‚óÄÔ∏è1iüçáüçÆoüç™oüç∫üêΩw iüî°üç∫üêΩüç∫üêΩa j i 10Süç™üçâüçìüçáüçÆoüç™oüç∫üêΩDüç∫üêΩüç∫üêΩa j 1 süç™üçâüçâüòÄoüçäüéâüòõ0iüòõ1iüçáüçäüòõ0iüçáüòÄLüçâüòÄlüçâüçâüòÄlüçâ
```
Takes input as a list of lists of integers in the format of `condition day high low` where condition is an integer between 0 and 4. [Try it online!](https://tio.run/##lVMxT8JAGN39Fd@IQ0MLtMXBwQQMJiiJQFxYCEJSgjIQwsKADJjWVEwkanBoTEiDJjIqMfHP8AfsP8D7ru31Shn0krvre/e9dy/Xu/pFu6nV2uf1tWONr8CxzOsdwMludC9ra8RVMswd624azNMh@V40HGvyGV2cvJB5iRYZl5zM4Lhwgq6TGUWlcpZDZ9kMv5Yrc@jw9IhDxYMSj8rM0xx5eXA7b8s4VLjiCsEBEgpCSEoVsX3Sdv0aKmAKoRBja4ECaGOuEOP0vFugiGP7qwK73XID/795RnZ3M6lpdyjVD4iiW9Pnanp@5M2eY/Hz3BE@DVqoypPhrQNdiHRcwDKsWLQ5w6G2Gr8KCUjhXaOLtNhYPQ5@lmNJYzS1pkG9bYmfqaNDkziIIHuVxurhI6rE4YtczG9/bmwSVWiCqPlJ0dm82RqCWfVAc6971EgDSSxyTvfbHTLbtFIog46nhgLDsW4RPIsajiyU4XOI3APW/R@ih8Cavux3wKeNX3N3SIAIqgyyinDkckmSQtkDOclxEqlUVVAkjhNJZVoEJRniUpCWQVEYN9qh2/8C "Emojicode – Try It Online")
[Answer]
# JavaScript (ES8), ~~304~~ ~~263~~ 222 bytes
Takes input as an array of 5 `[w,d,h,l]` entries, where **d** is the day as a string and **w**, **h**, **l** are integers representing the weather (0-indexed, with 0 = sunny), high temperature and low temperature respectively. Returns an array of strings.
```
a=>',0,04,05,06,0,,01,,0H 2,0L 3,'.split`,`.map(s=>(s=a.map(p=>s.replace(/\d/g,n=>+n?p[n]||' (==),(====),/////,\\ /,-O(==), \\ /, -O-, / \\,'.split`,`['765143810210'[p[0]*3-n+6]]:'| ').padEnd(10,' -'[+!s])).join``)+s[0])
```
### Demo
```
let f =
a=>',0,04,05,06,0,,01,,0H 2,0L 3,'.split`,`.map(s=>(s=a.map(p=>s.replace(/\d/g,n=>+n?p[n]||' (==),(====),/////,\\ /,-O(==), \\ /, -O-, / \\,'.split`,`['765143810210'[p[0]*3-n+6]]:'| ').padEnd(10,' -'[+!s])).join``)+s[0])
O.innerText =
f([
[2,'MON',75,57],
[3,'TUE',69,53],
[1,'WED',77,61],
[0,'THU',80,63],
[0,'FRI',85,66]
]).join('\n');
```
```
<pre id=O></pre>
```
### How?
We define:
* `L = ',0,04,05,06,0,,01,,0H 2,0L 3,'.split(',')`
An array of strings describing each line of the board, in which:
+ 0 = prefix string: `"| "`
+ 1 = day of week
+ 2 = high temperature
+ 3 = low temperature
+ 4 = top pattern of the graphical indicator
+ 5 = middle pattern of the graphical indicator
+ 6 = bottom pattern of the graphical indicator
* `W = ' (==),(====),/////,\\ /,-O(==), \\ /, -O-, / \\,'.split(',')`
An array of strings describing the patterns of the graphical indicators.
* `P = '765143810210'`
A string describing the indices of the patterns in **W** for each graphical indicator, grouped by 3 and stored in reverse order.
The main function now reads as:
```
a => L.map(s => // for each substring s in L
(s = a.map(p => // for each array of parameters p in a:
s.replace( // replace in s
/\d/g, n => // each digit n with:
+n ? // if n is non-zero:
p[n] || // the n-th parameter in p, if defined
W[P[p[0] * 3 - n + 6]] // or a graphical indicator pattern
: // else:
'| ' // the prefix string '| '
) // end of replace()
.padEnd(10, ' -'[+!s]) // pad the result with either spaces or '-'
).join``) // end of inner map(); join the results and save in s
+ s[0] // append the first character
) // end of outer map()
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~110~~ 94 bytes
```
↑χF⁵«Nθ↘→↘P⎇θ⁺⁺⎇⊖θ ¦\ /¶-o“⎇)D№⸿≡⬤»”×/×⁵⁼賓2⸿φ*EC+@OΠ≦”M¹¦⁵PS¶¶EHL⁺⁺κ SM⁶±¹↑χ»F6231«P←⁵¹MIι↓
```
[Try it online!](https://tio.run/##XVFNb4JAED3rr3jZ05JAFAmLtfFUbTRRayymFy7UrkqKC8Ji0zT97XSA1K89vJ2ZnX3v7exmH2abJIzLcplFSvPBOjVhd43H9jbJwF0DP@3WVKWFXhSHd5nxIx215slJ8sEo@VKraLfXl9JdettRxDpKaxVfZirMvvnRxDIucl7Df3EkN5k8SKXlB6mZYAAjDAJ0AmUlzADjw6ERKMJ6p4ofHWTOWYcam9A1MT4WYZxXGo5Bi3gaCliJRdihlBlnr7YJ985l/exXTfGO143NiFigKs1zPg9TziYzdv2Wz8o2I/O3HBc5YWIhd6Em4Svqy/R/m/kz0XNsVn/ClbHBTG41@bXPdE9hrnlEevXIq/tl2cP8ZQHPhevBgb8eQzzAdWDjbTyC50HY6MKfrNHvQjgUP6@m6LsQorRO8R8 "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 16 bytes by avoiding repeating the cloud. Explanation:
```
↑χ
```
Print the left-hand column of `|`s.
```
F⁵«
```
Loop over the 5 days.
```
Nθ
```
Input the weather condition, numbered 0 to 3 using the same order as the question.
```
↘→↘P⎇θ
```
If the weather condition is not sunny:
```
⁺⁺⎇⊖θ ¦\ /¶-o
```
If the weather condition is partly cloudy then print a partial sun.
```
“⎇)D№⸿≡⬤»”
```
Print a cloud.
```
×/×⁵⁼θ³
```
If the weather is rain then print it.
```
“2⸿φ*EC+@OΠ≦”
```
Otherwise print the sun.
```
M¹¦⁵PS
```
Read and print the day.
```
¶¶EHL⁺⁺κ S
```
Loop over and input and print the temperatures.
```
M⁶±¹↑χ»
```
Print the next column of `|`s.
```
F6231«
```
Loop over the characters `6`, `2`, `3` and `1`.
```
P←⁵¹
```
Print a row of `-`s.
```
MIι↓
```
Cast the character to integer and move ready to print the next row.
[Answer]
# Python 3, ~~636~~ ~~610~~ ~~534~~ ~~464~~ 379 bytes
```
def w(s,l,h,a):
g='|';A=' ';p,q,r=[A+'\ /'+A,' \ / '+A,A+' (==) ',A+' (==) '],[A+'-O-'+A,' -O(==) ',' (====) ',' (====) '],[A+'/ \\'+A,' (====) ',A*3,' ///// '];n='-'*51;R=n,;w=x=y=z=''
for e in s:x+=g+p[e];y+=g+q[e];z+=g+r[e];w+=g+A*3
R+=x+g,y+g,z+g,w+g;x=u=v=''
for i in range(5):x+=g+a[i];v+='| H '+h[i]+A;u+='| L '+l[i]+A
print('\n'.join(R+(x+g,n,u+g,v+g,n)))
```
**Input Format:-**
The first list takes the weather conditions day wise -
**0 - Sunny
1 - Partly cloudy
2 - Cloudy
3 - Rainy.**
Second and third list take the highest and lowest temperatures respectively(as strings). Don't do anything with the fourth list - its mainly to store the days of the week.
[Try It Online](https://tio.run/##ZZFPa4NAEMXvfoq5rWbXJqmYtFnmIDQlhbYBaelBPQRqjCVsjPmjhn53O5MEW6iwj9@@fY7ytmj2q43x2vYzXUJl79RardTCmViQofgWOkABAEIXaqtKjAIpYugLGSiyiYCRTLARHRB/MFEcdufuNezOrxFion98yfchjq8vdKGg5/G@zw/9SqINClf0/KEO0ShdYY0NnlAIC5abElLIDewmtcRMFlGa6IZpy3RiKpkqJhpsQSixlplqaJ1oVTLTNR7w2M3LeV65MFlq@85l7CLKE32UVBDAjCpY0V4G@nBxnslZnx0LijI3e1vERtx8bXJjh9Lmrxl1ID0yOY7TVnZ0qzw1VAM1oB7E2KdqRvck4zHJ3YDF54qEz4bv8fmQ5Uyj8xHd08v8lW@L64K392nHH9OHX3/23vFj@MScOO0P)
Note:- A very special thanks to Mr.XCoder, ovs and pizzapants184 for helping reduce a lot of bytes.
[Answer]
# [Clean](https://clean.cs.ru.nl), 328 bytes
```
import StdEnv,Text
s="----------"
u=" (====)"
v="(==)"
j=['-|||||-|-||-']
$[[d,h,l,w]:t]=[[z:cjustify 10(fromString x)]%(0,9)<+y\\x<-[s,"":[["\\ /","-O-","/ \\"],["\\ / "," -O"+v,u]:map((++)[" "+v,u])[[""],["/////"]]]!!w]++["",s,"MONTUEWEDTHUFRI"%(d*3,d*3+2),s,"H "<+h,"L "<+l,s]&y<-if(t>[])($t)(map((<+)"")j)&z<-j]
```
#
```
join"\n"o$
```
[Try it online!](https://tio.run/##PY5dT8IwFIbv9yvqEbW1p2EwGUo2r8RAomIE40XXiwlMtuyDbAWB8NudZSa@Tdunz@nXPF2GeZ0Vi026JFkY53WcrYtSk6leDPMtzpY7bVU@iP@AtfGBUN@EgbX1gTaQ@PJKHE8Rph3FlbJaUi5whSl@q4FWvpSHwTzZVDqO9qRj06gssqku4/yL7Ji6oDbeMY/vg2DnCVkhwEBKCALSBgQxEWZskyAAhX@WEGOImADf4kYNsnBNKedMAjGVxjFzvtnePgWUUmdn34pzY9Hc/zx5mb0PP4YPs9H749sYLuji2kHTeZed6iMCHl8hPJ3mFCt1ufdEHFF9LxWjLc1o86bHGQBL2OXBE4mqpzostXVOIuKTpIhzCHIoWpZvhJQ29nvY62PX/KqD7h32HHQMd7HfR7eDHcMO3troOmgbvsHbHrquYVX/zKM0/Kpq8VmL8VP9sM/DLJ5XzeI1DXVUlNkv "Clean – Try It Online")
As a partial function literal, taking `[[Int]]` and returning `String`.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 206 bytes
```
→a\-51*D:,\|w6ẋfð9*j:,`\ / *\ / * * (==)
-O- *-O(==)* (==)*(====)
/ \\ *(====)*(====)*///// `↵ƛ×/;ƛ£←aƛ¥ni;` | `j`| `p` |`+,;_,,?ƛð3*pð3*+;\|j\|p\|+,,`| H % `5*?%\|+,`| L % `5*?%\|+,,
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%86%92a%5C-51*D%3A%2C%5C%7Cw6%E1%BA%8Bf%C3%B09*j%3A%2C%60%5C%20%2F%20%20%20*%5C%20%2F%20%20%20*%20%20%20%20%20%20*%20%20%28%3D%3D%29%0A-O-%20%20%20*-O%28%3D%3D%29*%20%20%28%3D%3D%29*%28%3D%3D%3D%3D%29%0A%2F%20%5C%5C%20%20%20*%28%3D%3D%3D%3D%29*%28%3D%3D%3D%3D%29*%2F%2F%2F%2F%2F%20%60%E2%86%B5%C6%9B%C3%97%2F%3B%C6%9B%C2%A3%E2%86%90a%C6%9B%C2%A5ni%3B%60%20%7C%20%20%60j%60%7C%20%20%60p%60%20%7C%60%2B%2C%3B_%2C%2C%3F%C6%9B%C3%B03*p%C3%B03*%2B%3B%5C%7Cj%5C%7Cp%5C%7C%2B%2C%2C%60%7C%20%20H%20%25%20%20%20%605*%3F%25%5C%7C%2B%2C%60%7C%20%20L%20%25%20%20%20%605*%3F%25%5C%7C%2B%2C%2C&inputs=%5B0%2C3%2C1%2C2%2C3%5D%0A%5B%27MON%27%2C%27TUE%27%2C%27WED%27%2C%27THU%27%2C%27FRI%27%5D%0A%5B98%2C76%2C45%2C32%2C67%5D%0A%5B15%2C35%2C56%2C32%2C43%5D%0A%0A&header=&footer=)
A giant mess. Please don't ask.
] |
[Question]
[
You have probably seen these signs on the doors of various shops:
>
> ### OPENING HOURS
>
>
> mon-fri 0900-1800
>
> sat-sun 1100-1530
>
>
>
The task here is to generate a sign like that, grouping consecutive days with the same opening hours, from a list of opening hours for the whole week. Note that the week "wraps around" for what is considered consecutive.
## Input:
* 7 elements, representing the opening hours for each day in a week, starting with Monday.
* Each element is a string, on the form XXXX-XXXX
* Example input:
```
0900-1800 0900-1800 0930-1730 0930-1730 0900-1500 1100-1500 1100-1500
```
* It's ok to send the input as an array (for instance as input to a function if you don't read from stdin)
## Output:
* A list of opening hours, where consecutive days with the same opening hours are shown as a range. Note that sunday (the last day) and monday (the first day) also are consecutive days.
* A day where the day doesn't have similar opening hours to the days before or after is printed by itself
* Days are specified as three lowercase letters: *mon tue wed thu fri sat sun*
* Remember that first element in the input corresponds to mon, next to tue etc.
* Opening hours are shown as in the input
* Two examples
```
mon-fri 0900-1800, sat-sun 1100-1500
mon-wed 1030-1530, thu 100-1800, fri-sun 1200-1630
```
* **The output should be sorted, so ranges appear in the order the days do in the week.** Monday is preferred to be first, but it may happen it is not first in a group because the week wraps. So in this case tue is the first range.
```
tue-fri 0900-1800, sat-mon 1100-1500
```
* Don't group unless consecutive, here wednesday and friday have same opening hours but are separated by a Thursday with different opening hours so they are listed by themselves.
```
mon-tue 1000-1200, wed 0900-1500, thu 1000-1800, fri 0900-1500, sat-sun 1000-1500
```
* The output can be either comma-separated as the examples here, or separated by a newline as in the example on top.
## Test cases
First line is input, second line is expected output
```
0900-1800 0900-1800 0900-1800 0900-1800 0900-1800 1100-1500 1100-1500
mon-fri 0900-1800, sat-sun 1100-1500
0900-1800 0900-1800 0900-1800 0930-1700 0900-1800 1100-1500 1100-1500
mon-wed 0900-1800, thu 0930-1700, fri 0900-1800, sat-sun 1100-1500
1100-1500 0900-1800 0900-1800 0900-1800 0900-1800 1100-1500 1100-1500
tue-fri 0900-1800, sat-mon 1100-1500
1100-1500 1100-1500 0900-1800 0900-1800 0900-1800 0900-1800 1100-1500
wed-sat 0900-1800, sun-tue 1100-1500
1200-1500 1100-1500 0900-1800 0900-1800 0900-1800 0900-1800 1100-1500
mon 1200-1500, tue 1100-1500, wed-sat 0900-1800, sun 1100-1500
```
### Rules
This is code-golf, so the shortest answer in bytes wins.
[Answer]
## JavaScript (ES6), ~~182~~ ~~173~~ ~~170~~ ~~163~~ 157 bytes
*Saved 6 bytes with the help of edc65*
Takes input as an array of strings and directly prints the result to the console:
```
h=>{for(D="montuewedthufrisatsun".match(/.../g),d=c=i=j=0;j<8;y=d)h[i]==h[6]?i++:(v=h[d=(i+j++)%7])!=c&&(j>1&&console.log(D[x]+(x-y?'-'+D[y]:''),c),x=d,c=v)}
```
### Formatted and commented
```
h => { // input = list h of opening hours
for( //
D = "montuewedthufrisatsun" // D = list of abbreviated names of days
.match(/.../g), //
d = // d = current day of week
c = // c = current opening hours
i = // i = first day of week to process
j = 0; // j = day counter
j < 8; // stop when 7 days have been processed
y = d // update y = last day of current day range
) //
h[i] == h[6] ? // while the opening hours of day #i equal the opening
i++ // hours of sunday: increment i
: (v = h[d = (i + j++) % 7]) != c // else, if the new opening hours (v) of the current
&& ( // day (d) doesn't match the current opening hours (c):
j > 1 && // if this is not the first iteration:
console.log( // print:
D[x] + // - the first day of the current day range (x)
(x - y ? // - followed by either an empty string
'-' + D[y] // or a '-' and the last day of the range
: ''), // (if they differ)
c // - the corresponding opening hours
), // (endif)
x = d, // update x = first day of current day range
c = v // update c = current opening hours
) // (endif)
} // (end)
```
### Test cases
```
let f =
h=>{for(D="montuewedthufrisatsun".match(/.../g),d=c=i=j=0;j<8;y=d)h[i]==h[6]?i++:(v=h[d=(i+j++)%7])!=c&&(j>1&&console.log(D[x]+(x-y?'-'+D[y]:''),c),x=d,c=v)}
f(["0900-1800", "0900-1800", "0900-1800", "0900-1800", "0900-1800", "1100-1500", "1100-1500"]);
console.log('-');
f(["0900-1800", "0900-1800", "0900-1800", "0930-1700", "0900-1800", "1100-1500", "1100-1500"]);
console.log('-');
f(["1100-1500", "0900-1800", "0900-1800", "0900-1800", "0900-1800", "1100-1500", "1100-1500"]);
console.log('-');
f(["1100-1500", "1100-1500", "0900-1800", "0900-1800", "0900-1800", "0900-1800", "1100-1500"]);
console.log('-');
f(["1200-1500", "1100-1500", "0900-1800", "0900-1800", "0900-1800", "0900-1800", "1100-1500"]);
```
[Answer]
## Batch, 334 bytes
```
@echo off
set/af=l=w=0
set h=%7
call:l mon %1
call:l tue %2
call:l wed %3
call:l thu %4
call:l fri %5
call:l sat %6
call:l sun %7
if not %w%==0 set l=%w%
if %f%==0 set f=mon
call:l 0 0
exit/b
:l
if not %h%==%2 (
if %f%==0 (set w=%l%)else if %f%==%l% (echo %f% %h%)else echo %f%-%l% %h%
set f=%1
set h=%2
)
set l=%1
```
Takes input as command-line parameters, outputs each group on a separate line. Works by comparing each day's hours to the previous day, tracking `f` as the first day in the group, `h` as the hours for that group, `l` as the last day in the group and `w` for when the last group wraps back to the start of the week. When a mismatch is found the previous group is printed unless week wrapping is in effect. Finally when all the days are processed the last group is adjusted for any week wrapping and whether all the hours turned out to be the same before being output. `0` is used as a placeholder because empty strings cost more bytes to compare in Batch.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~87 84 80~~ 75 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
* 4bytes with the kind help of @Dennis (fixed a hack I used with the `'` quick, "flat")
Pretty sure there is a better way but for now:
```
Ṫ2ị$€;@µ+\µżṙ1’$Ṗị“ḅạṄMḤ9\E¥LḃɓṅÐĿ;$»s3¤Q€j€”-
ṙ7Ḷ¤Œr'€Ėµ2ịLµÐṂḢ
ÇṪḢ€ż@ÇÑ$G
```
**[TryiItOnline](http://jelly.tryitonline.net/#code=4bmqMuG7iyTigqw7QMK1K1zCtcW84bmZMeKAmSThuZbhu4vigJzhuIXhuqHhuYRN4bikOVxFwqVM4biDyZPhuYXDkMS_OyTCu3MzwqRR4oKsauKCrOKAnS0K4bmZN-G4tsKkxZJyJ-KCrMSWwrUy4buLTMK1w5DhuYLhuKIKw4fhuarhuKLigqzFvEDDh8ORJEc&input=&args=WyIxMTAwLTE1MDAiLCIxMTAwLTE1MDAiLCIwOTAwLTE4MDAiLCIwOTAwLTE4MDAiLCIwOTAwLTE4MDAiLCIwOTAwLTE4MDAiLCIxMTAwLTE1MDAiXQ)**
### How?
```
“ḅạṄMḤ9\E¥LḃɓṅÐĿ;$» - compressed string "montuewedthufrisatsun"
v v
Ṫ2ị$€;@µ+\µżṙ1’$Ṗị -- s3¤Q€j€”- - Link 1, getDayStrings: [offset, groupedList]
Ṫ - Tail: get groupedList
2ị$€ - second index of each: get group sizes, e.g. mon-thu is 4
;@ - concatenate (reversed arguments): prepend with offset
µ - monadic chain separation
+\ - cumulative reduce with addition: start indexes
µ - monadic chain separation
ż - zip with
$ - last two links as a monad
ṙ1 - rotated left by one
’ - decrement: end indexes
Ṗ - pop: remove last one, it's circular
ị - index into
¤ - last two links as a nilad
-- - compressed string of weekdays (as shown at the top)
s3 - split into 3s
Q€ - unique items for each: [tue,tue] -> [tue]
j€ - join each with
”- - literal string "-"
ṙ7Ḷ¤Œr'€Ėµ2ịLµÐṂḢ - Link 2: CalculateGroupingData: list of time strings
¤ - last two links as a nilad
ṙ - rotate time strings list left by
7Ḷ - range 7: [0,1,2,3,4,5,6]
€ - for each
Œr - run length encode
' - flat - i.e. don't vectorise
Ė - enumerate [[1,[groupsFromMon]],[2,[groupsFromTue], ...]
µ - monadic chain separation
ÐṂ - filter for minimum of
L - length of
2ị - item at index 2: The number of groupings
Ḣ - head: get the first occurring minimal (i.e Mon, or Tue, ...)
ÇṪḢ€ż@ÇÑ$G - Main link: list of time strings
Ç - call last link (1) as a monad: get the offset and grouping
Ṫ - tail: get the grouping
Ḣ€ - head each: get the time information
$ - last two links as a monad
Ç - call last link (1) as a monad: get the offset and grouping
Ñ - call the next link as a monad: get the day strings
ż@ - zip (with reversed arguments)
G - arrange as a group (performs a tabulation to nicely align the result)
```
[Answer]
## JavaScript (ES6), ~~171~~ 169 bytes
```
a=>a.map((e,d)=>(d='montuewedthufrisatsun'.substr(d*3,3),e!=h&&(f?o(f):w=l,f=d,h=e),l=d),f='',l=w='sun',h=a[6],o=f=>console.log((f==l?l:f+'-'+l)+' '+h))&&o(f||'mon',l=w)
```
Takes input as an array and outputs to the console on separate lines. This is almost exactly a port of my Batch answer; `f` now defaults to an empty string of course, while I can also default `l` and `w` to `'sun'` (using a sentinel value saved me 3 bytes in Batch because I was able to merge the initialisation into the `set/a`).
[Answer]
# **[BaCon](http://www.basic-converter.org), ~~514~~ ~~496~~ 455 bytes**
The BASIC program below is shown with its indentation. But without the indentation it consists of 455 bytes.
The idea is to use the time schedules as indexes to an associative array. Then, each day represents a bit: Monday = bit 0, Tuesday = bit 1, Wednesday = bit 2 and so on. The actual values for the members of the associative array are calculated by the respective bits of the days using a binary OR.
After that, it is a matter of checking how many consecutive bits are present in the associative array members, starting with bit 0.
In case bit 0 and also bit 6 are set, there is a week wrap. In that case, start looking for the start of the next sequence of bits, memorizing this start position. Print the rest of the sequences, and as soon bit 6 is reached, the day range should be ended with the memorized position earlier.
```
LOCAL n$[]={"mon","tue","wed","thu","fri","sat","sun"}
GLOBAL p ASSOC int
SUB s(VAR t$ SIZE a)
FOR i = 0 TO a-1
p(t$[i])=p(t$[i])|BIT(i)
NEXT
LOOKUP p TO c$ SIZE o
b=e=0
REPEAT
FOR i=0 TO o-1
IF p(c$[i])&BIT(b) THEN
IF b=0 AND p(c$[i])&65=65 THEN
WHILE p(c$[i])&BIT(b)
INCR b
WEND
e=b
BREAK
FI
?n$[b];
r=b
REPEAT
INCR b
UNTIL NOT(p(c$[i])&BIT(b))
IF e AND b>6 THEN
?"-",n$[e-1];
ELIF b-r>1 THEN
?"-",n$[b-1];
FI
?" ",c$[i]
FI
NEXT
UNTIL b>6
FREE p
ENDSUB
```
Using the following calls to invoke the SUB:
```
s("0900-1800", "0900-1800", "0900-1800", "0900-1800", "0900-1800", "1100-1500", "1100-1500")
PRINT "======"
s("0900-1800", "0900-1800", "0900-1800", "0930-1700", "0900-1800", "1100-1500", "1100-1500")
PRINT "======"
s("1100-1500", "0900-1800", "0900-1800", "0900-1800", "0900-1800", "1100-1500", "1100-1500")
PRINT "======"
s("1100-1500", "1100-1500", "0900-1800", "0900-1800", "0900-1800", "0900-1800", "1100-1500")
PRINT "======"
s("1200-1500", "1100-1500", "0900-1800", "0900-1800", "0900-1800", "0900-1800", "1100-1500")
```
**Output**:
```
mon-fri 0900-1800
sat-sun 1100-1500
======
mon-wed 0900-1800
thu 0930-1700
fri 0900-1800
sat-sun 1100-1500
======
tue-fri 0900-1800
sat-mon 1100-1500
======
wed-sat 0900-1800
sun-tue 1100-1500
======
mon 1200-1500
tue 1100-1500
wed-sat 0900-1800
sun 1100-1500
```
] |
[Question]
[
## Introduction
Almost everyone is familiar with the [Travelling Salesman Problem](https://en.wikipedia.org/wiki/Travelling_salesman_problem) (TSP). The task is to, given a list of `N` cities, find the minimum [Hamiltonian cycle](https://en.wikipedia.org/wiki/Hamiltonian_path) which is to say the shortest path that visits each city and comes full-circle back to the start. That is not what this challenge is about. This challenge is to implement Chuck Norris' [solution](https://github.com/pyjokes/pyjokes/blob/master/pyjokes/jokes_en.py) to the TSP:
>
> Chuck Norris solved the Travelling Salesman problem in `O(1)` time: break salesman into N pieces; kick each piece to a different city.
>
>
>
## Challenge
In order to solve the TSP in this way, we need a sufficiently durable Salesman that won't shy away from frivolities like dismemberment; a number of cities to visit; a set of products to sell; a concrete method for dismemberment; and a calculation for scoring.
## Specification
* **Cities**
+ `N` is the number of cites our Salesman will visit
* **Salesman**
+ The main program or function
+ Written in language `X`
+ With length mod `N` equal to `0`
* **Products**
+ The full names of the [elements](http://www.ptable.com) on the Periodic Table
+ This includes the [newly](https://iupac.org/iupac-announces-the-names-of-the-elements-113-115-117-and-118/) accepted names of elements
* **Dismemberment**
+ Slicing the Salesman into `N` continuous pieces of equal length
+ Each piece is should be a valid function or program in language `X`
* **Output**
+ When executed the Salesman should output `Chuck Norris` and the sliced pieces should each output a distinct product
+ Only extra trailing white space is acceptable
* **Scoring**
+ The length, `L`, of the Salesman in bytes divided by the number of cities, `N`, squared.
+ `Score = L/(N*N)`
+ Smallest score wins
+ Please include 3 significant figures when posting your decimal score
## Examples
1. This Salesman visits 3 cities so `N=3` and and it has a length of 9 so `L=9`. Thus the score for this answer would be `S = 9 / (3 * 3) = 9/9 = 1`.
* Note that the Salesman and each sliced piece (of which there are 3), should all be valid programs or functions in the same language.
```
Program -> Output
------- ------
aaaBBBccc -> Chuck Norris
aaa -> Helium
BBB -> Iridium
ccc -> Tennessine
```
2. `N=4` and `L=20` so `S=20/16=1.25`
```
Program -> Output
------- ------
aaaaaBBBBBcccccDDDDD -> Chuck Norris
aaaaa -> Hydrogen
BBBBB -> Cadmium
ccccc -> Mercury
DDDDD -> Iron
```
[Answer]
## CJam, L = 1482, N = 114, score 0.114
```
'C:L"arbon" L'h+:L;"Gold"L'u+:L;"Iron"L'c+:L;"Lead"L'k+:L;"Neon"LS+:L;"Argon"L'N+:L"ickel"L'o+:L;"Zinc""Coppe"L'r+:L"Silve"L'r+:LL'i+:L;"Tin" "Boron" "Radon" "Barium" "Cerium" "Cesium" "Cobalt" "Curium" "Erbium" "Helium" "Indium" "Iodine" "Osmium" "Oxygen" "Radium" "Sodium" "Sulfur" "Arsenic" "Bismuth" "Bohrium" "Bromine" "Cadmium" "Calcium" "Dubnium" "Fermium" "Gallium" "Hafnium" "Hassium" "Holmium" "Iridium" "Krypton" "Lithium" "Mercury" "Niobium" "Rhenium" "Rhodium" "Silicon" "Terbium" "Thorium" "Thulium" "Uranium" "Yttrium" "Actinium" "Aluminum" "Antimony" "Astatine" "Chlorine" "Chromium" "Europium" "Fluorine" "Francium" "Hydrogen" "Lutetium" "Nihonium" "Nitrogen" "Nobelium" "Platinum" "Polonium" "Rubidium" "Samarium" "Scandium" "Selenium" "Tantalum" "Thallium" "Titanium" "Tungsten" "Vanadium" "Americium" "Berkelium" "Beryllium" "Flerovium" "Germanium" "Lanthanum" "Magnesium" "Manganese" "Moscovium" "Neodymium" "Neptunium" "Oganesson" "Palladium" "Plutonium" "Potassium" "Ruthenium" "Strontium" "Tellurium" "Ytterbium" "Zirconium" "Dysprosium" "Gadolinium" "Lawrencium" "Meitnerium" "Molybdenum" "Phosphorus" "Promethium" "Seaborgium" "Technetium" "Tennessine" "Californium""Copernicium""Einsteinium""Livermorium""Mendelevium""Roentgenium"]L's+"Xenon"?
```
[Try it online!](http://cjam.tryitonline.net/#code=J0M6TCJhcmJvbiIgIEwnaCs6TDsiR29sZCJMJ3UrOkw7Iklyb24iTCdjKzpMOyJMZWFkIkwnays6TDsiTmVvbiJMUys6TDsiQXJnb24iTCdOKzpMImlja2VsIkwnbys6TDsiWmluYyIiQ29wcGUiTCdyKzpMIlNpbHZlIkwncis6TEwnaSs6TDsiVGluIiAiQm9yb24iICAgICAgIlJhZG9uIiAgICAgICJCYXJpdW0iICAgICAiQ2VyaXVtIiAgICAgIkNlc2l1bSIgICAgICJDb2JhbHQiICAgICAiQ3VyaXVtIiAgICAgIkVyYml1bSIgICAgICJIZWxpdW0iICAgICAiSW5kaXVtIiAgICAgIklvZGluZSIgICAgICJPc21pdW0iICAgICAiT3h5Z2VuIiAgICAgIlJhZGl1bSIgICAgICJTb2RpdW0iICAgICAiU3VsZnVyIiAgICAgIkFyc2VuaWMiICAgICJCaXNtdXRoIiAgICAiQm9ocml1bSIgICAgIkJyb21pbmUiICAgICJDYWRtaXVtIiAgICAiQ2FsY2l1bSIgICAgIkR1Ym5pdW0iICAgICJGZXJtaXVtIiAgICAiR2FsbGl1bSIgICAgIkhhZm5pdW0iICAgICJIYXNzaXVtIiAgICAiSG9sbWl1bSIgICAgIklyaWRpdW0iICAgICJLcnlwdG9uIiAgICAiTGl0aGl1bSIgICAgIk1lcmN1cnkiICAgICJOaW9iaXVtIiAgICAiUmhlbml1bSIgICAgIlJob2RpdW0iICAgICJTaWxpY29uIiAgICAiVGVyYml1bSIgICAgIlRob3JpdW0iICAgICJUaHVsaXVtIiAgICAiVXJhbml1bSIgICAgIll0dHJpdW0iICAgICJBY3Rpbml1bSIgICAiQWx1bWludW0iICAgIkFudGltb255IiAgICJBc3RhdGluZSIgICAiQ2hsb3JpbmUiICAgIkNocm9taXVtIiAgICJFdXJvcGl1bSIgICAiRmx1b3JpbmUiICAgIkZyYW5jaXVtIiAgICJIeWRyb2dlbiIgICAiTHV0ZXRpdW0iICAgIk5paG9uaXVtIiAgICJOaXRyb2dlbiIgICAiTm9iZWxpdW0iICAgIlBsYXRpbnVtIiAgICJQb2xvbml1bSIgICAiUnViaWRpdW0iICAgIlNhbWFyaXVtIiAgICJTY2FuZGl1bSIgICAiU2VsZW5pdW0iICAgIlRhbnRhbHVtIiAgICJUaGFsbGl1bSIgICAiVGl0YW5pdW0iICAgIlR1bmdzdGVuIiAgICJWYW5hZGl1bSIgICAiQW1lcmljaXVtIiAgIkJlcmtlbGl1bSIgICJCZXJ5bGxpdW0iICAiRmxlcm92aXVtIiAgIkdlcm1hbml1bSIgICJMYW50aGFudW0iICAiTWFnbmVzaXVtIiAgIk1hbmdhbmVzZSIgICJNb3Njb3ZpdW0iICAiTmVvZHltaXVtIiAgIk5lcHR1bml1bSIgICJPZ2FuZXNzb24iICAiUGFsbGFkaXVtIiAgIlBsdXRvbml1bSIgICJQb3Rhc3NpdW0iICAiUnV0aGVuaXVtIiAgIlN0cm9udGl1bSIgICJUZWxsdXJpdW0iICAiWXR0ZXJiaXVtIiAgIlppcmNvbml1bSIgICJEeXNwcm9zaXVtIiAiR2Fkb2xpbml1bSIgIkxhd3JlbmNpdW0iICJNZWl0bmVyaXVtIiAiTW9seWJkZW51bSIgIlBob3NwaG9ydXMiICJQcm9tZXRoaXVtIiAiU2VhYm9yZ2l1bSIgIlRlY2huZXRpdW0iICJUZW5uZXNzaW5lIiAiQ2FsaWZvcm5pdW0iIkNvcGVybmljaXVtIiJFaW5zdGVpbml1bSIiTGl2ZXJtb3JpdW0iIk1lbmRlbGV2aXVtIiJSb2VudGdlbml1bSJdTCdzKyJYZW5vbiI_&input=)
Each program is 13 bytes long. Here they are split up into individual lines:
```
'C:L"arbon"
L'h+:L;"Gold"
L'u+:L;"Iron"
L'c+:L;"Lead"
L'k+:L;"Neon"
LS+:L;"Argon"
L'N+:L"ickel"
L'o+:L;"Zinc"
"Coppe"L'r+:L
"Silve"L'r+:L
L'i+:L;"Tin"
"Boron"
"Radon"
"Barium"
"Cerium"
"Cesium"
"Cobalt"
"Curium"
"Erbium"
"Helium"
"Indium"
"Iodine"
"Osmium"
"Oxygen"
"Radium"
"Sodium"
"Sulfur"
"Arsenic"
"Bismuth"
"Bohrium"
"Bromine"
"Cadmium"
"Calcium"
"Dubnium"
"Fermium"
"Gallium"
"Hafnium"
"Hassium"
"Holmium"
"Iridium"
"Krypton"
"Lithium"
"Mercury"
"Niobium"
"Rhenium"
"Rhodium"
"Silicon"
"Terbium"
"Thorium"
"Thulium"
"Uranium"
"Yttrium"
"Actinium"
"Aluminum"
"Antimony"
"Astatine"
"Chlorine"
"Chromium"
"Europium"
"Fluorine"
"Francium"
"Hydrogen"
"Lutetium"
"Nihonium"
"Nitrogen"
"Nobelium"
"Platinum"
"Polonium"
"Rubidium"
"Samarium"
"Scandium"
"Selenium"
"Tantalum"
"Thallium"
"Titanium"
"Tungsten"
"Vanadium"
"Americium"
"Berkelium"
"Beryllium"
"Flerovium"
"Germanium"
"Lanthanum"
"Magnesium"
"Manganese"
"Moscovium"
"Neodymium"
"Neptunium"
"Oganesson"
"Palladium"
"Plutonium"
"Potassium"
"Ruthenium"
"Strontium"
"Tellurium"
"Ytterbium"
"Zirconium"
"Dysprosium"
"Gadolinium"
"Lawrencium"
"Meitnerium"
"Molybdenum"
"Phosphorus"
"Promethium"
"Seaborgium"
"Technetium"
"Tennessine"
"Californium"
"Copernicium"
"Einsteinium"
"Livermorium"
"Mendelevium"
"Roentgenium"
]L's+"Xenon"?
```
The missing elements are Darmstadtium, Praseodymium, Protactinium and Rutherfordium which are 12 or 13 characters long which means I can't print them in 13 characters each.
The idea is that the first few programs, which prints the elements with short names use their extraneous characters to build the string `Chuck Norri` in the variable `L`, which does not affect the output when used on their own. The final program then checks if anything is already on the stack, and uses it to choose between `L` (plus `s`) and `Xenon`.
A few additional bytes are saved by using the character we just added to `L` as part of the element name, specifically for `C`arbon, `N`ickel, Coppe`r` and Silve`r`.
[Answer]
# Python, L = 2596, N = 118, Score = 0.186
The length of each slice is **22** so that makes this pretty lengthy.
```
lambda:"Gold"; print"""";print "Carbon "print "Thorium "print "Curium "print "Calcium "print "Nickel "print "Zinc "print "Neon "print "Boron "print "Iron "print "Cerium "print "Barium "print "Caesium """[9::22];lambda:"Tin"[0];lambda:"Lead "#print"Argon "print"Radon "print"Xenon "print"Erbium "print"Cobalt "print"Copper "print"Helium "print"Indium "print"Iodine "print"Osmium "print"Oxygen "print"Radium "print"Silver "print"Sodium "print"Sulfur "print"Arsenic "print"Bismuth "print"Bohrium "print"Bromine "print"Cadmium "print"Dubnium "print"Fermium "print"Gallium "print"Hafnium "print"Hassium "print"Holmium "print"Iridium "print"Krypton "print"Lithium "print"Mercury "print"Niobium "print"Rhenium "print"Rhodium "print"Silicon "print"Terbium "print"Thulium "print"Uranium "print"Yttrium "print"Actinium "print"Antimony "print"Astatine "print"Chlorine "print"Chromium "print"Europium "print"Fluorine "print"Francium "print"Hydrogen "print"Lutetium "print"Nitrogen "print"Nobelium "print"Platinum "print"Polonium "print"Rubidium "print"Samarium "print"Scandium "print"Selenium "print"Tantalum "print"Thallium "print"Titanium "print"Tungsten "print"Vanadium "print"Nihonium "print"Aluminium "print"Americium "print"Berkelium "print"Beryllium "print"Flerovium "print"Germanium "print"Lanthanum "print"Magnesium "print"Manganese "print"Neodymium "print"Neptunium "print"Palladium "print"Plutonium "print"Potassium "print"Ruthenium "print"Strontium "print"Tellurium "print"Ytterbium "print"Zirconium "print"Moscovium "print"Oganesson "print"Dysprosium "print"Gadolinium "print"Lawrencium "print"Meitnerium "print"Molybdenum "print"Phosphorus "print"Promethium "print"Seaborgium "print"Technetium "print"Tennessine "print"Californium "print"Copernicium "print"Einsteinium "print"Livermorium "print"Mendelevium "print"Roentgenium "print"Darmstadtium "print"Praseodymium "print"Protactinium "print"Rutherfordium "
```
Here is the Salesman after the slicing and dicing:
```
lambda:"Gold"; print"" # <-- This is a function
"";print "Carbon "
print "Thorium "
print "Curium "
print "Calcium "
print "Nickel "
print "Zinc "
print "Neon "
print "Boron "
print "Iron "
print "Cerium "
print "Barium "
print "Caesium "
""[9::22];lambda:"Tin" # <-- This is a function and the choke point
[0];lambda:"Lead "# # <-- This is a function
print"Argon "
print"Radon "
print"Xenon "
print"Erbium "
print"Cobalt "
print"Copper "
print"Helium "
print"Indium "
print"Iodine "
print"Osmium "
print"Oxygen "
print"Radium "
print"Silver "
print"Sodium "
print"Sulfur "
print"Arsenic "
print"Bismuth "
print"Bohrium "
print"Bromine "
print"Cadmium "
print"Dubnium "
print"Fermium "
print"Gallium "
print"Hafnium "
print"Hassium "
print"Holmium "
print"Iridium "
print"Krypton "
print"Lithium "
print"Mercury "
print"Niobium "
print"Rhenium "
print"Rhodium "
print"Silicon "
print"Terbium "
print"Thulium "
print"Uranium "
print"Yttrium "
print"Actinium "
print"Antimony "
print"Astatine "
print"Chlorine "
print"Chromium "
print"Europium "
print"Fluorine "
print"Francium "
print"Hydrogen "
print"Lutetium "
print"Nitrogen "
print"Nobelium "
print"Platinum "
print"Polonium "
print"Rubidium "
print"Samarium "
print"Scandium "
print"Selenium "
print"Tantalum "
print"Thallium "
print"Titanium "
print"Tungsten "
print"Vanadium "
print"Nihonium "
print"Aluminium "
print"Americium "
print"Berkelium "
print"Beryllium "
print"Flerovium "
print"Germanium "
print"Lanthanum "
print"Magnesium "
print"Manganese "
print"Neodymium "
print"Neptunium "
print"Palladium "
print"Plutonium "
print"Potassium "
print"Ruthenium "
print"Strontium "
print"Tellurium "
print"Ytterbium "
print"Zirconium "
print"Moscovium "
print"Oganesson "
print"Dysprosium "
print"Gadolinium "
print"Lawrencium "
print"Meitnerium "
print"Molybdenum "
print"Phosphorus "
print"Promethium "
print"Seaborgium "
print"Technetium "
print"Tennessine "
print"Californium "
print"Copernicium "
print"Einsteinium "
print"Livermorium "
print"Mendelevium "
print"Roentgenium "
print"Darmstadtium "
print"Praseodymium "
print"Protactinium "
print"Rutherfordium "
```
---
[](https://i.stack.imgur.com/E73ik.gif)
---
**Update**
* [16-09-08] Sublime added an extra space when joining to a line that ends in a comment character
* [16-09-08] Made each slice **22** characters long and added gif
] |
[Question]
[
Write a program to play the game of [Connect 4](http://en.wikipedia.org/wiki/Connect_Four). You are given the state of the board as input and you must decide which column to place your piece in to either get 4 in a row (horizontally, vertically, or diagonally) or block your opponent from doing the same.
The board is a 6x7 array, where each cell may be empty (' '), contain your piece ('X') or your opponent's piece ('O'). An example board:
```
O
XX X
XOX OO
XOO OXO
OXXOXXO
XOXOXOX
```
You would want to play in column 3 (columns are 0-6, numbered from the left) for the diagonal win. So you output:
```
3
```
Your code must output a column number, and it must satisfy the following criteria:
1. You cannot play in a column that already has 6 pieces in it.
2. If there is at least one winning move, you must play one of them.
3. If you can prevent your opponent from winning on his next move, you must do so.
Note that optimal play is not necessary, only that you take an immediate win or prevent your opponent's immediate win. If your opponent has more than one way to win, you need not block any of them.
You are given the board on standard input and must print a column number in which you want to play on standard output. The board is guaranteed to be well-formed (no holes, at least one possible move) and to not already have a win for either player.
Shortest code wins.
## Example 1
```
X
O
X
O
OOO X
XXX O
```
You must play either column 0 or 4 for the win.
## Example 2
```
X
X X
O O
XOX XO
XXO XOX
XXO XXO
```
You must play column 3 to block your opponent's immediate win.
## Example 3
```
X
XO
OX O
XO XX
XXO OOO
OOO XXO
```
You cannot win or stop your opponent from winning, so you may play any column 1-6 (0 is full).
## Example 4
```
X
O
X
OOO
XOX
OXOX
```
You cannot play in column 3, as it lets your opponent win immediately. You may play in columns 1-2 or 4-6.
[Answer]
## C, 234 286 256 chars
Fixed to correctly solve the problem, by checking for opponent winning moves following every move attempted.
This code is very sensitive to the input file format - each line must conatain 7 chars + newline.
The board is treated as an 8x8 matrix, rather than 7x6. The 8th column contains the newlines, and the 2 extra rows contain zeros, so they don't interfere with the solution. They actually help - When moving right from the rightmost column, you hit to newline column, which serves as a boundary check.
`w` checks one position for an opportunity to win or block. `q` should be the cell to check around. It uses reursion to loop through 4 directions (starts with 9,8,7, then several times 1).
`C` checks for a sequence of identical characters starting at `q` in direction `d`, both back and forth. It returns the sum of both sequences (not counting the starting position), so if it returns 3, there's a row of 4.
```
char B[99],q;
C(i,d){
return B[d*i+++q]-B[q]?d>0?C(1,-d):0:1+C(i,d);
}
w(x){
return x&&C(1,x>6?x:1)>2|w(x-1);
}
t(l,c,r,v){
for(;c--;)B[q=c]&32&B[c+8]-32?r=w(9,B[c]=l)?v=c:v||r*t(79,l,0,1)?r:c,B[c]=32:0;
return r;
}
main(){
putchar(48+t(88,16+read(0,B+16,48),0,0)%8);
}
```
[Answer]
# Python 2.x - 594 591 576 557 523 459 458 433 bytes
This is the best I've achieved so far. I guess it's hard to beat C. Awesome challenge, I have to say.
```
r=range
f=[]
exec'f+=list(raw_input());'*6
def n(p):
o,b,a,k=[],1,'O',lambda q:any([o[i:i+4]==list(q)*4for o in(f[x-x%7:],f[x%7::7])for i in r(3)]+[all(q==f[7*(y+u*i)+z+i]for i in r(4))for u,z,v,c in((1,0,3,4),(-1,3,6,3))for y in r(z,v)for z in r(c)])
for x in r(42):
if x>34<a>f[x]or x<35and f[x+7]>'0'>f[x]:f[x]=p;z=k(p)*b;o=z*[x]+o+[x]*(a==p or n(a)[1]);b-=z;f[x]=' '
return o[0]%7,b
a,b,c,d=n('X')+n('O')
print(a,(c,a)[d])[b]
```
The if-line (line 7) has indentation of one tab. SE doesn't like tabs.
] |
[Question]
[
A `TicTacToe` game can be represented by a string denoting the sequence of positions as the players make their move.
```
0 1 2
3 4 5
6 7 8
```
Assume `X` always plays first.
So a string of "012345678" denotes the game
```
X O X
O X O
X O X
```
Notice, the game is already won when Player `X` marks `6`, at that point the game ends, granting a win to `X`. (ie, ignore the remaining moves once a player wins)
Your challenge (code) is to print all the games (sorted order) and its results.
The Format
```
<movesequence>:<result>\n
```
eg:
```
012345678:X
012345687:X
012345768:X
...
```
Denote `X` for the 1st player winning, `O` for the second player, and `D` for Draws.
There will be `9!` (362880) games.
Here is some data to verify your results.
```
'X' Wins: 212256
'O' Wins: 104544
Draws : 46080
```
This is a codegolf, and runtime should be within a minute. Have Fun!
**EDIT:** Removed excess details, and just print it on `stdout`. No need to create a file.
[Answer]
## J, 124 chars
```
((],~':',~1":[){&'DOX'@(</+2*>/)@:(<./"1)@:(((2{m/.@|.),(2{m/.),m"1,>./)"2)@(<:@(>:%2|]),:(%(2|>:)))@(3 3$]))"1((i.!9)A.i.9)
```
X win, O win and Draw counts check out.
Was a bit painful to debug though. :)
[Answer]
## Ruby 1.9, 201 characters
```
r=*[*l=0..8,0,3,6,1,4,7,2,5,8,0,4,8,2,4,6].each_slice(3)
w=->a{r.any?{|b|b&a==b}}
[*l].permutation(9){|a|u=[[],[]];i=-1
u[i%2]<<a[i+=1]while !((x=w[u[1]])||o=w[u[0]])&&i<8
puts a*""+":#{x ??X:o ??O:?D}"}
```
Slightly golfed so far. Takes about 45 seconds to complete here.
* Edit: (268 -> 249) Write to stdout instead of a file
* Edit: (249 -> 222) Don't pre-fill the array with each player's moves.
* Edit: (222 -> 208) Shorter way to find out if a player won
* Edit: (208 -> 213) Back to 213, the previous solution was too slow.
* Edit: (213 -> 201) Some rearrangements, removed whitespace
[Answer]
## Haskell, 224 222 characters
```
import Data.List
p=sort.permutations
a(e:_:z)=e:a z;a z=z
[c,d]%(e:z)|any((`elem`words"012 345 678 036 147 258 048 246").take 3).p.a.reverse$e=c|1<3=[d,c]%z;_%[]='D'
main=putStr$p['0'..'8']>>=(\s->s++':':"OX"%inits s:"\n")
```
Alas, the `permutations` function from `Data.List` doesn't produce permutations in lexographic order. So I had to expend 6 characters on the sort.
[Answer]
## APL (139)
This can probably be shortened more, but it was hard enough as it is. Believe it or not, it runs in about 45 seconds on my computer (excluding the time it takes to output everything, when output to the screen).
```
↑{⊃,/(,/⍕¨⍵-1),':',{1∊T←↑{∨/↑{⍵∘{⍵≡⍵∧⍺}¨↓⍉(9⍴2)⊤⎕UCS'㗀㐇㔤㑉㔑㑔'}¨↓(M∘.≥M)∧[2]M∊⍵}¨↓⍉5 2⍴0,⍨⍵:'XO'[1+</+/T]⋄'D'}⍵}¨↓{1≥⍴⍵:↑,↓⍵⋄↑⍪/⍵,∘∇¨⍵∘~¨⍵}M←⍳9
```
Explanation:
* `M←⍳9`: Store in M the numbers from 1 to 9. Internally, this program uses 1..9 instead of 0..8.
* `{`...`}`: a function to get all permutations:
+ `1≥⍴⍵:↑,↓⍵`: if the length is smaller or equal to 1, return the argument as a matrix.
+ `⋄↑⍪/⍵,∘∇¨⍵∘~¨⍵`: otherwise, remove each character in `⍵` from `⍵`, get the permutations of that, and add the character back in.
* `¨↓`: for each permutation...
* `{`...`}`: a function that gives the winner for that permutation:
+ `⊃,/(,/⍕¨⍵-1),':',{`...`}⍵`: get the permutation as a string, with all the numbers decreased by 1 (to get the required 0..8 output instead of 1..9), followed by a colon, followed by the character denoting the winner:
- `⍉5 2⍴0,⍨⍵`: separate the moves by X from the moves by O. Because O has one move less than X, that space is filled by `0`, which is unused and so does not influence the result.
- `{`...`}¨↓`: for both the X board and the O board, run the following function which determines whether there is a win in one of the nine timesteps:
* `(M∘.≥M)∧[2]M∊⍵`: Generate a bitboard from the move numbers, and `and` this bitboard with the bitstrings `100000000`, `110000000` ... `111111111` to get the state of the board at each of the nine moments in time.
* `{`...`}¨↓`: for each of these, run the following function:
+ `⍉(9⍴2)⊤⎕UCS'㗀㐇㔤㑉㔑㑔'`: get the bitboards for each possible winning situation
+ `⍵∘{⍵≡⍵∧⍺}¨↓`: `and` each winning state with the current bitboard and check if said winning state is still there
* `∨/↑`: `or` these together, giving whether there is a win on this bitboard
- `1∊T←↑`: make a 9x2 matrix, with the 9 X-timesteps on the first row and the 9 O-timesteps on the second row. Store this in T. If there is a 1 in this matrix, someone has won.
- `:'XO'[1+</+/T]`: If someone has won, give 'X' or 'O' depending on whose `1` was first.
- `⋄'D'`: If nobody has won, give 'D'.
* `↑`: make a matrix out of these so that they are each displayed on a separate row.
[Answer]
# Python 2.7 (237)
```
from itertools import*
for z in permutations('012345678'):
k,F=0,[9]*9
for h in z:
F[int(h)]=k=1-k
if any(sum(a)in(0,3)for a in(F[:3],F[3:6],F[6:],F[::3],F[1::3],F[2::3],F[::4],F[2:8:2])):break
else:k=2
print"".join(z)+':','OXD'[k]
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 174 bytes
```
f=(j,w,p,x,o)=>(A=[-1,7,56,73,84,146,273,292,448],g=n=>!A.every(q=>q&n^q),w=w||g(x)|2*g(o),x+o)^511?A.map((_,i)=>x+o>>i&1||f(!j,w,[p]+i,x|!j<<i,o|j<<i)):print(p+':','DXO'[w])
```
[Try it online!](https://tio.run/##FY3BCoJAGAafxUv@f34Ja2YW7obQvWsgFhIpK6SrhRrsu5udZpjL1MVQvB@9Np/NEM9zKanGCIMJLUtFqcw2AnvsIuy3iEOIMEKwaHAIEIZxjko2Ujmp/xye/Zc6qbpVc@sYoxytrWhiG6wrahmT1/JtJ8Qp9V@FIbpDL4elKqVXwtqSnP86M7mnMVmnThKN1v7BfDS9bj5kPPfowj1fL2425jyXxPMP "JavaScript (V8) – Try It Online")
[Or see the statistics](https://tio.run/##XY3daoNAFITvfYqTUOJuPZFozU9j1hLIvZcN2E0jVmVDumtUoqWbZ7fGi1IKB@Yw3wxziq9xlZSiqKfXVddljJywwQJbVJQFZMuiqYNLnC9w@YQrDx1vgW7/us8uet6KY84kC0ZbO72m5Re5sOAykYcLxYY1Wuekpdp9zImi2FqKHuaO87K1P@OCkHcU/ULvBoGYOFpnZHSfjgpuCWz16LTZCFT6LpSui1LImhSWuTbR3O1DM2o47c5pDVUd18AgghkOB9w3hnRv9iOQUGDBkIrGfXFsC/mRtmFGEsotyzcyQn0jUbJS59Q@q5wYAEdzb8KrkNUaHr6HqsNvb/II1gDDf9D9A3dl3FQA8Atn/HY0qN/9AA)
### How?
We use 8 bit-masks stored in the array \$A\$ to identify all possible winning patterns. There's a dummy leading \$-1\$ in \$A\$ (which will always cause the test to fail) so that we have 9 entries. This allows us to re-use \$A\$ to iterate on all squares of the grid.
The bit-masks for X and O are stored in the variables \$x\$ and \$o\$ respectively. The variable \$j\$ is a flag telling which turn it is (*false* or *undefined* for X, *true* for O). The variable \$w\$ holds the winner (\$0\$ for draw, \$1\$ for X, \$2\$ for O) and may not be changed anymore once it's non-zero. The variable \$p\$ is the permutation of moves as a string.
[Answer]
# [Python 3](https://python.org) + [`golfing-shortcuts`](https://github.com/nayakrujul/golfing-shortcuts), 211 bytes
```
from s import*
for Z in Im('012345678'):
K,F=0,[9]*9
for H in Z:
F[int(H)]=K=1-K
if a(s(A)in(0,3)for A in(F[:3],F[3:6],F[6:],F[::3],F[1::3],F[2::3],F[::4],F[2:8:2])):break
else:K=2
p(sj('',Z)+':','OXD'[K])
```
A port of [Daniel's answer](https://codegolf.stackexchange.com/a/11545/114446).
] |
[Question]
[
## Background
A **snake** is a path over the cells of a square grid, such that it doesn't touch itself on a side of a unit square. Touching at a corner is allowed.
An example snake:
```
##.#.
.#.##
##..#
#.###
###..
```
Some example non-snakes:
```
###.#
#.#.#
#####
.#...
.####
###
.#.
##
##
```
## Challenge
Given an empty grid with the two endpoints of a snake marked on it, find the longest possible snake that fits on the grid. If there are multiple answers having the same length, you may choose to output one or all of them.
The input can be given as a character matrix (or equivalent) with two endpoints marked on it, or the dimensions (width, height) and the coordinates of the endpoints. You may choose to output the grid containing the snake or a list of coordinates of cells occupied by the snake (or equivalent).
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Example I/O
Each I/O example is given as a character matrix, `#` being the part of the snake.
```
Input:
..#...#...
Output:
..#####...
Input: (corner case)
......
......
..##..
......
......
......
Output: same as input (no way to get longer without violating no-touch condition)
Input:
..#.#
.....
.....
.....
Output:
###.#
#...#
#...#
#####
Input:
#....
.....
.....
.....
....#
Output:
#####
....#
#####
#....
#####
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~207~~ ~~194~~ 181 bytes
*-7 bytes thanks to @ovs*
### Input
The width \$ w \$, the height \$ h \$, the starting point \$ s \$, and the ending point \$ e \$. \$ s \$ and \$ e \$ are complex numbers which represent the coordinates of the endpoints.
### Output
A list of points, in the form of complex numbers.
---
```
C={1,-1,1j,-1j}
def f(w,h,s,e):P=[[s]];exec("P=[j+[t+(t==e==(A:=j+[t]))]for j in P for k in C if w>(t:=j[-1]+k).real>-1<t.imag<h>0<all({t+l}-{*j}for l in{0}|C-{-k})];"*w*h);return A
```
[Try it online!](https://tio.run/##VZBNb8IwDIbv/RUWOzSmadXypQkIEuLAlXuXQ7WlNKELVQnrpq6/vUs6GJoUxfaj1/abVF@mOOvpc1X3/Y61CQ0Tmih7q857EznkpKEFvVCBywNL0wvnK/EpXsnIVipITUAMY4Ixsl0yV3NEnp9rUCA1HMClJ5fuQObQbIixsjRMeHDCqBZZuQmTtYnke3ZcF5t4nZUlaU1QdmE7Vp3rLm13G3ffu7ANTx3y1WjcjAtc1cJcaw3bvilkKSBZetBQKChcKAhgID6ykkhdXQ1B9DzYW5amfuQPnqTzVGf6KEiBHP4c/6IGufeQuS@4D0a7Bvap1IbIwT/yW@GeYCcx8J98D6raUf9F@5E6S038W5T4mLtHCMBJsE8oJDEFEgcThUNcKPQWFOwhkxucBFMLZxTm/5QzC@d3GA9w5uAP "Python 3.8 (pre-release) – Try It Online")
## Explanation
We use a breadth-first search to search for all possible snakes, starting at \$ s \$, making sure that the next tile is not adjacent to any previous tile, and that we do not go past the boundary. After each iteration, we check for all paths whose last element is \$ e \$, meaning that we have found a complete path from \$ s \$ to \$ e \$. Instead of storing all complete paths and returning the one with maximum length, we can simply return the last path found, since breadth-first search already searches for paths by length.
[Answer]
# [R](https://www.r-project.org/), ~~275~~ ~~272~~ ~~251~~ ~~229~~ ~~206~~ 197 bytes
```
f=function(p,m){a=p+cbind(-1:0,1:0,0:-1,0:1)
v=m[a<-t(a[,!colSums(!a|a>dim(m))])]
t=sum(!!v)
m[t(p)]=2
`if`(t<3&any(v==1),m,if(t<2)(s<-lapply(split(a,seq(v))[!v],f,m))[[which.max(sapply(s,sum))]])}
```
[Try it online!](https://tio.run/##vZLNTsMwDMfveQoqJGSLFDULXKaFGy/Ax6mqWNa1LKJJQ5N2m4BnL0EbEjsAlQooShwllv3z3276qjYPhfP3zsjHQvSlKFuTe1UbsFTjsxT2NF8os4SYTRP6vpNpzMLBkHRCp3IWe5ApjfK6umm1g0i@yMul0qARM8yIF67VEEUdEp16sJiJCZmrcg5@xk@k2UInBEOqqSrD0wTBzeJKWlttwdlKhejUFU/QIaZRl9EyYGGarlcqX51puQG396UhT0iZ4Wt/fORDTW5KnJeN19I3aiN2BnIgnCb7RZJvrwGLmFCYuKCLbVOvxe313RXuotraiRxY8CEHGsLHL/2UHMkXKAnlv4cyGYnygyp8MMr5aFUGNIgPROGjUDhlwxqU/PmsHIwt@x@U/g0 "R – Try It Online")
*Edits 1-4: -69 bytes by using increasingly-arcane golfing obfuscations*
*Edit 5: -9 more bytes by removing useless explicit return of NULL for 'touching' cases, and instead just falling-off the end of the function*
Recursive function:
* find adjacent squares
* count touching squares
* mark position (differently to finish point)
* if touching < 3 and we're touching the finish: return the matrix
* else if touching > 1 (it's either a loop or an illegal position): return NULL
* otherwise (there should always be at least one adjacent empty square left)
+ call self recursively with each adjacent empty square
to get snakes from this position
+ return the longest snake
Code before golfing:
```
longest_snake=function(pos,matrix){
# find adjacent squares
d=dim(matrix)
adjacent_squares=lapply(list(-1:0,1:0,0:-1,0:1),function(p){n=pos+p;if(all(n>0 & n<=d)){n}})
adjacent_squares=do.call(rbind,adjacent_squares)
# count touching squares
adjacent_vals=matrix[adjacent_squares]
touching=sum(!!adjacent_vals)
# mark current position (differently to end, which is 1)
matrix[pos]=2
# if touching<3 & pos is touching finish => return matrix
if((touching<3)&&any(adjacent_vals==1)){ return( matrix ) }
# else if touching>1 then its either an illegal position or a loop
else if(touching>1){ return( NULL ) }
else { # there should always be at least one adjacent empty square
# now consider each of the adjacent empty squares
new_pos=lapply(which(adjacent_vals==0),function(i) adjacent_squares[i,,drop=F])
# get the longest snake from each of them
snakes_from_here=lapply(new_pos,longest_snake,matrix)
# and return the longest of these
longest=which.max(sapply(snakes_from_here,sum))
return(snakes_from_here[[longest]])
}
}
```
[Answer]
# [R](https://www.r-project.org/), ~~178~~ ~~169~~ ~~164~~ 161 bytes
```
f=function(s,e,w,h,l=length,`/`=c,`*`=`%in%`,k=s[1]-1/-1i/-1/1i)if(!any(s[-2]*k))`if`(e*k,s/e,{for(j in k[Re(k)*1:w&Im(k)*1:h])if(l(F)<l(n<-f(j/s,e,w,h)))F=n;F})
```
[Try it online!](https://tio.run/##ZY5Ba8JAEIXv/orpwTITJ6SrpoXWvQq99hoCa@1usyZZyybWtuJvT1cjEhB2h@F97w3Pd52RZufWrd06bFjznguuZKXdZ1uwSpRcs4qUVGPrxopL2WQij0USCxt@IixZg3cr94tNFk/zqCRS1ijUUclNovlgth43YB2U2ZvGkiLxvL9/rfutyE/xCpe0qNAtYoOb5FKCiJbSvSyP1H3bZreq7J@GRQyDsqAZ9gwFwQFGAB4kmKEctC9vXYv@tNYB16vW2x98CDR4zmq2frfuA0MjTwyhoifKg1Vc0zWNjqNrB5xNhGV4Ok8RLgkawOlkGuTZeT6GRzfBtJ8M8yETF5b2LL292Tvmp1z3Dw "R – Try It Online")
This works with complex numbers, similarly to @dingledooper's answer. Inputs are 1-indexed coordinates of start and end points, as well as width and height of the grid. Output is a vector of points which form the snake.
### Explanation
```
f = function(s, e, w, h) # start, end, width, height
{ # Select points to try at next iteration as neighbors of the snake head cell:
k = s[1] + c(-1,1i,1,-1i)
# To avoid touches, only proceed if none of k points are already in snake:
if(!any(s[-2] %in% k)) #s[2] is an exception - this is where we came from
`if`(e %in% k, # If the neighbors include the endpoint, then...
c(s,e) # The loop is closed, add the endpoint to snake and return
{# Loop through k, filtered so that all points fit in 1:w by 1:h grid:
for(j in k[Re(k) %in% 1:w & Im(k) %in% 1:h])
{ # Prepend j to snake, and construct it further by recursive call:
n <- f(c(j, s), e, w, h)
if(length(F) < length(n))
F = n # Select the longest snake that we encountered
}
F # Return the longest snake
}
)
}
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 214 bytes
Takes a 1D boolean array `g` where the endpoints are marked `True`, and returns a 1D boolean array where snake tiles are marked `True`.
[Try it online!](https://tio.run/##dVHBcoIwED3DV@zItCSCiPbSYYg/ghyoBEgLgQlo4OtpEupoHc1ld9/mvX3ZdNNQtfzjsxNzQY5znTVfeQbSr/wyarIRoZr1A2qyDl18kfGSIrmuMMZFK2AExmEB93G8NFgBWV0jdInInxaLwpiwWHUh4zkqE5Zq7uHA3ncYI4YJCaEViL3JQ6ivwAWxjWp5GorlZncFPQ3qpjTBU0GrEbIHbYfd7Cwe/R86kf7c4DmnBQxUPaQULMeRbUkgUFNu6iRMsW1Vd4gqHRC0P9eDQgskfah8SE5ACLiOa6adzLRWmkJHVWpu@oJsJk1pMqb3KncrlNgg0w2psBZ7IcW2W5kmakP/9B52sPCHs@DgHrkbfLeMI/caFUd916KfjN60Vlq07im4wRN3T@xh2@4E4wOyLbPdxLasVRA4gbPyl1SdF6ltKXN4/gU "Python 3.8 (pre-release) – Try It Online")
```
lambda w,h,g:max((list(map(v,range(w*h)))for x in range(2<<(w*h))if all((v:=lambda i:0<=i<w*h and(g[i]or x>>i&1))(i)==0 or(i%w>0 and v(i-1))+(i%w<w-1 and v(i+1))+v(i-w)+v(i+w)+g[i]==2 for i in range(w*h))),key=sum)
```
---
### Explanation:
```
def f(w, h, g):
return max(
(
# Brute force all possible grid configurations by counting in binary.
# For each iteration, let the ith binary digit of x signify
# whether the ith tile is considered part of the snake.
[v(i) for i in range(w*h)] # <- Return a boolean array.
for x in range(2<<(w*h))
# Check if there is a valid snake path.
if all(
# The ith tile is part of the path if it's a given endpoint (g[i])
# or the ith binary digit of x is 1 (x>>i&1).
( v:=lambda i:0<=i<w*h and (g[i] or x>>i&1) )(i) == 0
# For a grid to have a valid snake path,
# every tile must either not be part of the snake (v(i) == 0)...
or
# ...or the tile must have exactly 2 neighbors in the snake path.
# (If the tile is an endpoint (g[i]), count itself as a neighbor.)
(i%w>0 and v(i-1)) + (i%w<w-1 and v(i+1)) + v(i-w) + v(i+w) + g[i]
== 2
# Repeat this check for every tile.
for i in range(w*h)
)
),
# Use max() to find the grid configuration with the most snake tiles;
# that is, the most times that v(i) == True.
key=sum
)
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 199 bytes
```
s=>(o=g=(t,k,h=c=>t.replace(/2/,c),a=h(0),b=h(1),m=2*~s[0].length)=>a==b?[...a].some((_,i)=>_&1&~1<<B[i]>>a[i-m]>>a[i+m]>>a[i-2]>>a[i+2]|k<o)||(o=k,r=a):g(a,k)|g(b,-~k))(B=JSON.stringify(s))&&eval(r)
```
[Try it online!](https://tio.run/##TY69TsMwFEb3PkWn6F64cRuPKNdIHTowwMBoWZUTjGPy4yqOKiFFefUQRAemc74zfV/2ZlM9huuUD/HDrWdeEyuI7BkmaqnhmtUkRnftbO3gIA9UI1lu4IhUbSiQepYPS9JHIzo3@KlBVpa5etZCCGtEir0DuFDY@iUrsqUoy5MORimrQ97/8fHOXN63NHNbRpzn7UtLI1t88mCpxdlDRfnSIsKJX97fXkWaxjD48PkNCTHL3M12MOJaxyHFzokuejiD3u33uiBJhaFflZvK/7oziOsP "JavaScript (Node.js) – Try It Online")
Seems this way is not that good one
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 76 bytes
```
WS⊞υι≔⪫υ¶θ≔⟦ω⟧ηFηFE⁴⁺ικ«J⁰¦⁰Pθ…θ⌕θ@Fκ✳⊗λ#¿∧›KK#‹№KV#²¿⁼KK@«#≔KAζ»⊞ηκ»UMKA§ζκ
```
[Try it online!](https://tio.run/##TZBPT8MwDMXP66ewwsWRQjUhbrus6gBtYqgSiAtwKG22RsuSrkn4s2mfvThlYuTiyH7@@elVTdlVttR9/9koLQHnpg3@0XfKrJFzKIJrMAhQfJJkzqm1wYVVJrbYq2FcwO48eWHsTUBDjZXtABsOQ12WLV4LKHRwqARsOHEPyWgRtu2TxbGAMW2MlkF71dJdjxE5KoZv/l1pmTe2xZ2AW2XqWNmUEYM0A35DLgftTHWy8soanNnwrmWNmpNBdsGiVq0AM9q/62TpZYeFlBs8jQXcS@cwt4EwcfBszYMM29KYs@Qq@o6Um10otTsDohs4nEwM1@AUSJRkWkfVnrpHkNrJ30ybGMQkOSaUTm63dKr@L8/83NTyC/dDXpO@T6cpvSRN/8o0TfrLD/0D "Charcoal – Try It Online") Link is to verbose version of code. Takes input as two `@` endpoints in a field of ASCII characters greater than `#` (e.g. `.`). Explanation:
```
WS⊞υι≔⪫υ¶θ
```
Input the field.
```
≔⟦ω⟧ηFη
```
Start a breadth-first search with an empty path, and for each path...
```
FE⁴⁺ικ«
```
... search over the four possible paths formed by concatenating each direction.
```
J⁰¦⁰Pθ…θ⌕θ@
```
Print the field and move to the position of the first endpoint.
```
Fκ✳⊗λ#
```
Print the path.
```
¿∧›KK#‹№KV#²
```
Test whether the current position is legal (not off the edge, doubled back, or touching itself).
```
¿⁼KK@«
```
If we reached the other endpoint,
```
#≔KAζ
```
then overwrite it with a `#` and save the canvas.
```
»⊞ηκ
```
Otherwise add this path to the search candidates.
```
»UMKA§ζκ
```
Restore the canvas from the saved last (i.e. longest) path that reached the other endpoint.
] |
[Question]
[
For those who wish a lot more challenge then the [old Spanish alphabetical order](https://codegolf.stackexchange.com/questions/75259/old-spanish-alphabetical-order), let's take a look at how the Hungarian alphabet is ordered.
>
> a, á, b, c, cs, d, dz, dzs, e, é, f, g, gy, h, i, í, j, k, l, ly, m, n, ny, o, ó, ö, ő, p, q, r, s, sz, t, ty, u, ú, ü, ű, v, w, x, y, z, zs
>
>
>
actually, `q`, `w`, `x` and `y` are not used in Hungarian words, but they are included for loanwords and foreign names. Foreign accented characters which are not part of the Hungarian alphabet (like `ñ`), have the same priority as the non-accented ones, but we disregard them for this challenge.
# The rules, summarized:
* Digraphs (`cs`, `sz`, etc.) and the trigraph (`dzs`) are considered as they were letters on their own.
>
>
> ```
> cudar
> cukor
> cuppant
> csalit
> csata
>
> ```
>
>
* If the same digraph or trigraph occurs twice directly after each other in a word, they are written in a simplified way: `ssz` instead of `szsz`, `ddzs` instead of `dzsdzs` but for the alphabetical order the non-simplified order is used. For example `kasza` < `kaszinó` < `kassza`, because `kassza` is used as `k`+`a`+`sz`+`sz`+`a` for the sake of ordering. Sometimes you can find the non-contracted version in a word, in case of compound words.
>
>
> ```
> kasza
> kaszinó
> kassza
> kaszt
> nagy
> naggyá
> nagygyakorlat
> naggyal
> nagyít
>
> ```
>
>
* capitalization doesn't matter, with the exception when the two words would be exactly the same without capitalization, in which case the lower case letter has priority
>
>
> ```
> jácint
> Jácint
> Zoltán
> zongora
>
> ```
>
>
* The short and long versions of accented vowels have the same priority (`a - á`, `e -é`, `i - í`, `o - ó`, `ö - ő`, `u - ú` `ü - ű`), with a single exception: if the two words would otherwise be exactly the same, the short vowel has priority over the long vowel. Note, that the vowels with umlaut (`ö` and `ü`) are completely different characters from `o` and `u`.
>
>
> ```
> Eger
> egér
> író
> iroda
> irónia
> kerek
> kerék
> kérek
> szúr
> szül
>
> ```
>
>
* Hyphens or spaces (for example, in compound words, names, etc.) are completely ignored
>
>
> ```
> márvány
> márványkő
> márvány sírkő
> Márvány-tenger
> márványtömb
>
> ```
>
>
# The task
Your program/function receives strings, composed of characters from the Hungarian alphabet (both lower- and upper-case), but a string might contain spaces or hyphens. For simplicity's sake, the minus sign (ASCII 45) can be used as a hyphen. Note that some characters (like the `ő`) are not part of ASCII. You can use any encoding you wish, if it supports all the required characters.
You have to order the lines correctly and display/return the result.
You can use any randomly ordered subset of the above examples for testing.
**EDIT:**
Please don't use any built-in or other way which already knows the Hungarian alphabetical ordering by itself. It would make the competition pointless, and take all the challenge from finding the best regular expression or the best code golfing tricks.
**EDIT2:**
To clear a clarification asked by isaacg: "two strings that only differ by capitalization and long vs. short vowels, but differs in both ways" : Although no rule in [the official document](http://helyesiras.mta.hu/helyesiras/default/akh12) explicitly addresses this question, an example found within points to the length of the vowel having more importance than the capitalization.
[Answer]
# Java 8, 742 bytes
Could reduce by another 3 bytes naming the function `s` instead of `sort` or another 16 bytes if not counting class-definition.
```
public class H{String d="cs|dzs?|gy|ly|sz|ty|zs";void sort(java.util.List<String>l){l.sort((a,b)->{String o="-a-á-b-cs-dzs-e-é-f-gy-h-i-í-j-k-ly-m-ny-o-ó-ö-ő-p-q-r-sz-ty-u-ú-ü-ű-v-w-x-y-zs-";int i=c(r(a),r(b),r(o));return i!=0?i:(i=c(a,b,o))!=0?i:b.charAt(0)-a.charAt(0);});}String r(String a){for(int i=0;i<8;i++)a=a.toLowerCase().replace("ááéíóőúű".charAt(i),"aaeioöuü".charAt(i));return a;}int c(String a,String b,String o){a=n(a);b=n(b);while(!"".equals(a+b)){int i=p(a,o),j=p(b,o);if(i!=j)return i-j;a=a.substring(i%4);b=b.substring(j%4);}return 0;}int p(String a,String o){a=(a+1).replaceAll("("+d+"|.).*","-$1");return o.indexOf(a)*4+a.length()-1;}String n(String a){return a.toLowerCase().replaceAll("(.)(?=\\1)("+d+")| |-","$2$2");}}
```
Can be used like this:
```
new H().sort(list);
```
Test-suite:
```
public static void main(String[] args) {
test(Arrays.asList("cudar", "cukor", "cuppant", "csalit", "csata"));
test(Arrays.asList("kasza", "kaszinó", "kassza", "kaszt", "nagy", "naggyá", "nagygyakorlat", "naggyal",
"nagyít"));
test(Arrays.asList("jácint", "Jácint", "Zoltán", "zongora"));
test(Arrays.asList("Eger", "egér", "író", "iroda", "irónia", "kerek", "kerék", "kérek", "szúr", "szül"));
test(Arrays.asList("márvány", "márványkő", "márvány sírkő", "Márvány-tenger", "márványtömb"));
}
private static void test(final List<String> input) {
final ArrayList<String> random = randomize(input);
System.out.print(input + " -> " + random);
new H().sort(random);
System.out.println(" -> " + random + " -> " + input.equals(random));
}
private static ArrayList<String> randomize(final List<String> input) {
final ArrayList<String> temp = new ArrayList<>(input);
final ArrayList<String> randomOrder = new ArrayList<>(input.size());
final Random r = new Random();
for (int i = 0; i < input.size(); i++) {
randomOrder.add(temp.remove(r.nextInt(temp.size())));
}
return randomOrder;
}
```
yielding
```
[cudar, cukor, cuppant, csalit, csata] -> [csata, cudar, cuppant, csalit, cukor] -> [cudar, cukor, cuppant, csalit, csata] -> true
[kasza, kaszinó, kassza, kaszt, nagy, naggyá, nagygyakorlat, naggyal, nagyít] -> [naggyá, kassza, kaszinó, nagygyakorlat, nagyít, nagy, kaszt, kasza, naggyal] -> [kasza, kaszinó, kassza, kaszt, nagy, naggyá, nagygyakorlat, naggyal, nagyít] -> true
[jácint, Jácint, Zoltán, zongora] -> [Zoltán, jácint, zongora, Jácint] -> [jácint, Jácint, Zoltán, zongora] -> true
[Eger, egér, író, iroda, irónia, kerek, kerék, kérek, szúr, szül] -> [egér, Eger, kerék, iroda, író, kerek, kérek, szúr, irónia, szül] -> [Eger, egér, író, iroda, irónia, kerek, kerék, kérek, szúr, szül] -> true
[márvány, márványkő, márvány sírkő, Márvány-tenger, márványtömb] -> [márványtömb, márványkő, Márvány-tenger, márvány sírkő, márvány] -> [márvány, márványkő, márvány sírkő, Márvány-tenger, márványtömb] -> true
```
Ungolfed:
```
public class HungarianOrder {
String d = "cs|dzs?|gy|ly|sz|ty|zs";
void sort(java.util.List<String> l) {
l.sort((a, b) -> {
String o = "-a-á-b-cs-dzs-e-é-f-gy-h-i-í-j-k-ly-m-ny-o-ó-ö-ő-p-q-r-sz-ty-u-ú-ü-ű-v-w-x-y-zs-";
int i = c(r(a), r(b), r(o));
return i != 0 ? i
: (i = c(a, b, o)) != 0 ? i
: b.charAt(0) - a.charAt(0);
});
}
// toLower + remove long accent
String r(String a) {
for (int i = 0; i < 8; i++)
a = a.toLowerCase().replace("ááéíóőúű".charAt(i), "aaeioöuü".charAt(i));
return a;
}
// iterate over a and b comparing positions of chars in o
int c(String a, String b, String o) {
a = n(a);
b = n(b);
while (!"".equals(a + b)) {
int i = p(a, o), j = p(b, o);
if (i != j)
return i - j;
a = a.substring(i % 4);
b = b.substring(j % 4);
}
return 0;
}
// find index in o, then looking if following characters match
// return is index * 4 + length of match; if String is empty or first character is unknown -1 is returned
int p(String a, String o) {
a = (a+1).replaceAll("("+d+"|.).*", "-$1");
return o.indexOf(a) * 4 + a.length() - 1;
}
// expand ddz -> dzdz and such
String n(String a) {
return a.toLowerCase().replaceAll("(.)(?=\\1)("+ d +")| |-", "$2$2");
}
}
```
I am using Java's `List`-type and the `order()`-function of it, but the comparator is all mine.
[Answer]
## Perl, 250
Includes +11 for `-Mutf8 -CS`.
```
use Unicode::Normalize;$r="(?=cs|zs|dz|sz|[glnt]y)";print map/\PC*
/g,sort map{$d=$_;s/d\Kd(zs)|(.)\K$r\2(.)/\L$+\E$&/gi;s/d\Kzs/~$&/gi;s/$r.\K./~$&/gi;s/(\p{Ll}*)(\w?)\s*-*/\U$1\L$2/g;$c=$_;$b=$_=NFD lc;y/̈̋/~~/d;join$;,$_,$b,$c,$d}<>
```
Uses the **decorate-sort-undecorate** idiom (AKA [Schwartzian Transform](https://en.wikipedia.org/wiki/Schwartzian_transform)), and multilevel sorting†, where the levels are:
* L1: compare base letters, ignore diacritics, case, and some punctuation.
* L2: compare base letters and diacritics, ignore case and some punctuation.
* L3: compare base letters, diacritics and case, ignore some punctuation.
* Ln: tie-breaking byte-level comparison.
Internally, `␜` (ASCII 0x1C Field Separator — whose value is less than any character in the alphabet for this challenge) is used as a level separator.
This implementation has many limitations, amongst them:
* No support for foreign characters.
* Cannot disambiguate between contracted geminated (long) digraphs/trigraphs, and consonant+digraph/trigraph, e.g: *könnyű* should collate as *<k><ö><ny><ny><ű>*, while *tizennyolc* should collate as *<t><i><z><e><n><ny><o><l><c>*; *házszám* 'address = house (ház) number (szám)' should collate as *<h><á><z><sz><á><m>* and not as \**<h><á><zs><z><á><m>*.‡
* Collation for contracted long digraphs is not that consistent (but it is stable): we disambiguate at the identical level (*ssz <n szsz, ..., zszs <n zzs* ); glibc collates the short forms before the full forms (*ssz < szsz, ..., zzs < zszs* ), ICU collates the long forms before the short forms starting at L3 *Case and Variants* (*szsz <3 ssz, ..., zszs <3 zzs* )
Expanded version:
```
use Unicode::Normalize;
$r="(?=cs|zs|dz|sz|[glnt]y)"; # look-ahead for digraphs
print map/\PC*\n/g, # undecorate
sort # sort
map{ # decorate
$d=$_; # Ln: identical level
# expand contracted digraphs and trigraphs
s/d\Kd(zs)|(.)\K$r\2(.)/\L$+\E$&/gi;
# transform digraphs and trigraphs so they
# sort correctly
s/d\Kzs/~$&/gi;s/$r.\K./~$&/gi;
# swap case, so lower sorts before upper
# also, get rid of space, hyphen, and newline
s/(\p{Ll}*)(\w?)\s*-*/\U$1\L$2/g;
$c=$_; # L3: Case
$b=$_=NFD lc; # L2: Diacritics
# transform öő|üű so they sort correctly
# ignore diacritics (acute) at this level
y/\x{308}\x{30b}\x{301}/~~/d;
# L1: Base characters
join$;,$_,$b,$c,$d
}<>
```
---
†. Some well-known multi-level collation algorithms are the [*Unicode Collation Algorithm* (UCA, Unicode UTS#10)](http://unicode.org/reports/tr10/), ISO 14651 (available at the [ISO ITTF site](http://standards.iso.org/ittf/PubliclyAvailableStandards/)) the LC\_COLLATE parts at ISO TR 30112 (draft available at the [ISO/IEC JTC1/SC35/WG5 home](http://www.open-std.org/JTC1/SC35/WG5/)) which obsoletes ISO/IEC TR 14652 (available at the [ISO/IEC JTC1/SC22/WG20 home](http://www.open-std.org/JTC1/SC22/WG20/)) and LC\_COLLATE at POSIX.
‡. Doing this correctly would require a dictionary. ICU treats weirdly capitalized groups as non-contractions/non-digraphs/non-trigraphs, e.g: *ccS <3 CcS <3 c**Cs** <3 c**CS** <3 C**Cs** <3 cS <3 **cs** <3 **Cs** <3 **CS** <3 **ccs** <3 **Ccs** <3 **CCS***
[Answer]
# Python 3, 70
Saved 8 bytes thanks to shooqie.
I love Python. :D
Expects a list of strings.
```
from locale import*;setlocale(0,'hu')
f=lambda x:sorted(x,key=strxfrm)
```
] |
[Question]
[
The task here is to read from a Golly `.rle` or plaintext file (your choice) whose filename is provided (on STDIN or as a command line argument) and identify and count the common patterns in the grid encoded therein.
Alternatively, you may choose to have the contents of the file provided directly over STDIN instead.
Your program should be able to identify and distinguish at least the [fifteen most common strict still lifes](http://www.conwaylife.com/wiki/List_of_common_still_lifes) and the [five most common oscillators](http://www.conwaylife.com/wiki/List_of_common_oscillators), plus [gliders](http://www.conwaylife.com/wiki/Glider).
All phases of these oscillators should be recognized, as should all four phases of the glider.
It should output a list containing the final count of each pattern, with the name and quantity of each pattern on a separate line. Your program may include in the ouput list either all of these patterns or only the ones of which at least one was found.
Patterns which are part of other patterns being counted should not be counted. (for example, the 8-cell phase of a beacon should not also be counted as two blocks, and a ship-tie should not also be counted as two ships)
You may assume that the input has already stabilized and contains no patterns not in the aformentioned set. You may also assume that the input grid will fit within a 1024x1024 box.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program wins.
**RLE file format description**
An RLE file contains a run-length encoded life grid. All lines starting with `#` are comments and should be ignored.
The first non-empty, non-comment line is of the form `x=<width>,y=<height>,rule=<rule>`. For the purposes of this task, the rule will always be `B3/S23`. It may contain spaces which should be stripped before processing this line (of course, it is not necessary to process this line at all.)
Non-comment lines after the first should be treated as a single string. This should consist only of decimal digits, the characters `$`, `b`, and `o`, and line breaks, and will not end with a digit. Line breaks are to be ignored, but you may assume that line breaks will not interrupt strings of digits.
This may be terminated by a single `!`.
`b` represents a dead cell, `o` represents a live cell, and `$` represents the end of a row. Any decimal number indicates that the following symbol is to be treated as repeating that many times.
**Plaintext pattern encoding**
The other option is to read the pattern in another plaintext format described [here.](http://www.conwaylife.com/wiki/Plaintext) In this encoding, off cells are represented with hyphens and on cells are represented with uppercase Os, with newlines separating rows.
You may assume that all non-comment lines will be padded to equal length with hyphens.
Lines starting with `!` are comments and are to be ignored.
**Some test cases**
RLE:
```
#This is a comment
x = 35, y = 16, rule = B3/S23
bo$2o$obo5$22bo$22bo$22bo2$18b3o3b3o2$22bo$22bo10b2o$22bo10b2o!
```
Plaintext:
```
!This is a comment
-O---------------------------------
OO---------------------------------
O-O--------------------------------
-----------------------------------
-----------------------------------
-----------------------------------
-----------------------------------
----------------------O------------
----------------------O------------
----------------------O------------
-----------------------------------
------------------OOO---OOO--------
-----------------------------------
----------------------O------------
----------------------O----------OO
----------------------O----------OO
```
Results:
```
Glider 1
Blinker 4
Block 1
```
RLE:
```
x = 27, y = 15, rule = B3/S23
5b2o$5b2o9$11bo$o9bobo$o9bobo$o10bo12b3o!
#Here's a comment at the end
```
Plaintext:
```
-----OO--------------------
-----OO--------------------
---------------------------
---------------------------
---------------------------
---------------------------
---------------------------
---------------------------
---------------------------
---------------------------
-----------O---------------
O---------O-O--------------
O---------O-O--------------
O----------O------------OOO
!Here's a comment at the end
```
Results:
```
Block 1
Blinker 2
Beehive 1
```
RLE:
```
#You may have multiple comments
#As shown here
x = 13, y = 11, rule = B3/S23
2o$2o2$12bo$12bo$12bo$2b2o$2b2o4b2o$7bo2bo$7bobo$8bo!
```
Plaintext:
```
!You may have multiple comments
!As shown here
OO-----------
OO-----------
-------------
------------O
------------O
------------O
--OO---------
--OO----OO---
-------O--O--
-------O-O---
--------O----
```
Results:
```
Block 2
Blinker 1
Loaf 1
```
RLE:
```
# Pentadecathlon
# Discovered by John Conway
# www.conwaylife.com/wiki/index.php?title=Pentadecathlon
x = 10, y = 3, rule = B3/S23
2bo4bo2b$2ob4ob2o$2bo4bo!
```
Plaintext:
```
! Pentadecathlon
! Discovered by John Conway
! www.conwaylife.com/wiki/index.php?title=Pentadecathlon
--O----O--
OO-OOOO-OO
--O----O--
```
Results:
```
Pentadecathlon 1
```
**Bonus**
If you support *both* input formats (using the file extension [`.rle` for rle files and `.cells` for plaintext- how other extensions are to be read is undefined] or a command line flag to distinguish between them) you may subtract 5% from your score.
[Answer]
## Haskell, 2417 bytes
This took quite a while and there are still a few bugs, but I got several tricks working so it was worth it.
Notes:
* It only accepts the plaintext format, passed to STDIN
* It takes something like O(n^20) time
* I assumed that the number of characters in non-comment lines is constant (within a specific input), as that's how it is in the examples
* Craziest trick was how the patterns are unpacked, extracting the elements at positions (column number) modulo (the length of the output) to build the array.
It combines a few key ideas:
* patterns and symmetries can be pre-computed
* a single pattern can be packed into an integer, with dimensions known
* finding all submatrices is easy
* counting equalities is easy
Here's the code:
```
r=[1..20]
a!0=a!!0
a!x=tail a!(x-1)
u[_,x,y,l]=[[odd$div l$2^i|i<-[0..y],mod i x==j]|j<-[0..x-1]]
main=interact(\s->let q=[map(=='O')l|l<-lines s,l!0/='!']in let g=[i|i<-[[[0,3,11,3339,0,4,11,924,0,4,11,3219,0,3,11,1638,1,4,15,19026,1,4,15,9636,2,3,11,1386,2,4,11,1686,3,7,48,143505703994502,3,7,48,26700311308320,3,7,48,213590917399170,3,7,48,8970354435120,4,2,3,15,5,3,8,171,5,3,8,174,5,3,8,426,5,3,8,234,6,4,15,36371,6,4,15,12972,6,4,15,51313,6,4,15,13644,6,4,15,50259,6,4,15,12776,6,4,15,51747,6,4,15,6028,7,4,15,26962,7,4,15,9622,7,4,15,19094,7,4,15,27044,8,5,24,9054370,8,5,24,2271880,9,4,15,51794,9,4,15,13732,9,4,15,19027,9,4,15,9644,10,4,19,305490,10,5,19,206412,10,5,19,411942,10,4,19,154020,11,3,8,427,11,3,8,238,12,6,35,52217012547,12,6,35,3306785328,13,3,8,170,14,3,8,428,14,3,8,458,14,3,8,107,14,3,8,167,14,3,8,482,14,3,8,302,14,3,8,143,14,3,8,233,14,3,8,241,14,3,8,157,14,3,8,286,14,3,8,370,14,3,8,181,14,3,8,115,14,3,8,346,14,3,8,412,15,4,15,51219,15,4,15,12684,15,4,15,52275,15,4,15,13260,16,1,2,7,16,3,2,7,17,3,29,313075026,17,10,29,139324548,17,3,23,16252911,17,8,23,16760319,17,5,49,152335562622276,17,10,49,277354493774076,17,7,69,75835515713922895368,17,10,69,138634868908666122360,17,9,89,135722011765098439128942648,17,10,89,58184575467336340020006960,17,5,59,160968502306438596,17,12,59,145347113669124612,17,5,59,524156984170595886,17,12,59,434193401052698118,17,5,69,164495599269019571652,17,14,69,222245969722444385292,17,5,69,517140479305239282702,17,14,69,222262922122170485772,17,3,47,83020951028178,17,16,47,39740928107556,17,3,35,62664969879,17,12,35,40432499049,17,3,41,1581499314234,17,14,41,1293532058322,17,3,41,4349006881983,17,14,41,3376910168355,17,3,47,92426891685930,17,16,47,83780021865522,17,3,47,79346167206930,17,16,47,11342241794640,18,13,168,166245817041425752669390138490014048702557312780060,18,15,224,1711376967527965679922107419525530922835414769336784993839766570000,18,13,168,141409121010242927634239017227763246261766273041932,19,2,7,126,19,4,7,231,19,4,7,126,19,2,7,189,19,4,15,24966,19,4,15,18834,19,4,15,10644,19,4,15,26646]!p|p<-[h..h+3]]|h<-[0,4..424]],j<-[[[q!y!x|x<-[a..a+c]]|y<-[b..b+d]]|c<-r,d<-r,a<-[0..(length$q!0)-c-1],b<-[0..length q-d-1]],u i==j]in show[(words"aircraftcarrier barge beehive biloaf1 block boat eater1 loaf longbarge longboat mango ship shiptie tub glider beacon blinker pentadecathlon pulsar toad"!(e!0),sum[1|f<-g,e!0==f!0])|e<-g])
```
Here's the Mathematica code used to pack an array of 0,1's into the format later unpacked by the haskell program:
```
rotate[m_]:=Transpose[Map[Reverse,m]]
findInversePermutation[m_]:=Block[{y=Length[First[m]], x=Length[m]}, InversePermutation[FindPermutation[Flatten[m], Flatten[Table[Table[Flatten[m][[i+1]], {i, Select[Range[0, x * y - 1], Mod[#, x]==j&]}], {j, 0, x - 1}]]]]]
enumShape[m_]:=Partition[Range[1, Length[Flatten[m]]], Length[m[[1]]]]
pack[m_]:={Length[rotate[rotate[m]]], Length[Flatten[rotate[rotate[m]]]], FromDigits[Permute[Flatten[rotate[rotate[m]]], findInversePermutation[enumShape[rotate[rotate[m]]]]], 2]}
```
Here's a much more complete ungolfing of the code:
```
range = [1..16] -- all of the patterns fall within this range
list ! 0 = list !! 0 -- this is a simple generic (!!)
list ! position = (tail list) ! (position - 1)
unpack [_, unpackedLength, unpackedSize, packed] = [ [odd $ div packed (2^i) | i <- [0..unpackedSize], (mod i unpackedLength) == j] | j <- [0..unpackedLength - 1]]
main=interact doer
doer input = show $ tallyByFirst (words nameString) foundPatterns -- this counts equalities between the list of patterns and the submatrices of the input
where
parsed = parse input -- this selects the non-comment lines and converts to an array of Bool's
foundPatterns = countOccurrences partitioned subArrays
subArrays = allSubArrays parsed
partitioned = modPartition compressed 428 4 -- this partitions the compressed patterns into the form [name number, x length, x length * y length, packed integer]
countOccurrences patterns subArrays = [pattern | pattern <- patterns, subArray <- allSubArrays q, unpack pattern == subArray]
subArray m offsetX subSizeX offsetY subSizeY = [[m ! y ! x | x <- [offsetX..offsetX + subSizeX]] | y <- [offsetY..offsetY + subSizeY]]
allSubArrays m = [subArray m offsetX subSizeX offsetY subSizeY | subSizeX <- range, subSizeY <- range, offsetX <- [0.. (length $ head m) - subSizeX - 1], offsetY <- [0..(length m) - subSizeY - 1]]
tallyByFirst names list = [ (names ! (a ! 0), sum [1 | a <- list, (head a) == (head b)]) | b <- list]
parse string = [map (=='O') line | line <- lines string, head line /= '!']
modPartition list chunksize = [ [list ! position | position <- [offset..offset + chunksize - 1]] | offset <- [0, chunksize..(length list) - chunksize]]
```
] |
[Question]
[
Bonjour, PPCG ! Quelle heure est-il ? This means what time is it in French, for that is exactly what this challenge is about.
Telling time in French (at least formally) is a bit different from telling time in English. Telling the time starts out with *Il est* (It is). Then, you put the hour followed by *heures* (o'clock). (In case you don't know French numbers, here's a list: <http://blogs.transparent.com/french/french-numbers-learn-how-to-count-from-1-to-1000/>). If it is 1 o'clock, do *une heure* for this. For noon, use *midi* (with no heures), and for midnight use *minuit*.
Unless the minutes is 00, you then follow it with the number of minutes. There are a few exceptions to this however. For 15 minutes, you want to say *et quart*, and for 30 minutes you want to say *et demi*. For anything after 30 minutes, you increase the hour number by one, then add the word *moins* and 60 - the minutes. So 6:40 P.M is *Il est sept heures moins vingt* (vingt = 20). 45 minutes would be *moins le quart*.
Finally, you end it with the time of day. For the morning (1 A.M to 12 P.M), you say *du matin*. For the afternoon (subjective, but I'll define it as 1 P.M to 5 P.M), you say *de l'apres-midi* (technically there should be an accent above the e, but eh). And for night (5 P.M to 12 A.M) you say *du soir*. Note that for midnight and noon (*minuit* and *midi*) you don't put any of these afterwards -- the time of day is implied based on which one you use.
As you've probably already ascertained, the challenge here is to print out the current local time in French using these rules. Here's what sample output should look like at assorted times. (The time in the parenthesis does not have to be printed obviously, it's just there so you know what times are):
```
Il est sept heures du matin. (7:00 A.M)
Il est deux heures de l'apres-midi. (2:00 P.M)
Il est une heure du matin. (1:00 A.M)
Il est huit heures du soir. (8:00 P.M)
Il est midi. (12:00 P.M, Noon)
Il est minuit. (12:00 A.M, Midnight)
Il est cinq heures vingt du soir. (5:20 P.M)
Il est six heures et quart du matin. (6:15 A.M)
Il est neuf heures et demi du matin. (9:30 A.M)
Il est quatre heures moins dix de l'apres-midi. (3:50 P.M, not 4:50!)
Il est midi moins le quart. (11:45 A.M)
```
This is code-golf, so shortest code wins. Good luck!
EDIT: The period is required.
[Answer]
## PHP - ~~521~~ 473 bytes
I've added some newlines for readability:
```
$w=split(A,'AuneAdeuxAtroisAquatreAcinqAsixAseptAhuitAneufAdixAonzeAdouzeAtreizeA
quatorzeAAseizeAdix-septAdix-huitAdix-neufAvingtAvingt et une');$h=idate('H');if(
$r=($m=idate('i'))>30){$h=++$h%24;$m=60-$m;}echo'Il est '.($h?$h==12?midi:$w[$h%12]
.' heure'.($h%12<2?'':s):minuit).($r?' moins':'').($m==15?($r?' le ':' et ').quart
:($m==30?' et demi':($m?' '.($m<22?$w[$m]:"$w[20]-".$w[$m%10]):''))).($h%12?($h-=$r
)<12?' du matin':($h<17?" de l'après-midi":' du soir'):'').'.';
```
The method used to converting a number to its numeral in French is inspired by [this answer on an other challenge](https://codegolf.stackexchange.com/a/35483/11713) by [edc65](https://codegolf.stackexchange.com/users/21348/edc65).
Here is the ungolfed version:
```
/** Define numerals **/
$numerals = [
'', 'une', 'deux', 'trois', 'quatre',
'cinq', 'six', 'sept', 'huit', 'neuf',
'dix', 'onze', 'douze', 'treize', 'quatorze',
'', 'seize', 'dix-sept', 'dix-huit', 'dix-neuf',
'vingt', 'vingt et une'
];
/** Get current time **/
$hours = idate('H');
$minutes = idate('i');
/** Check if we need to count in reverse **/
$reverse = $minutes > 30;
if ($reverse) {
$hours = ($hours + 1) % 24;
$minutes = 60 - $minutes;
}
echo 'Il est ';
/** Print hours **/
if ($hours === 12) {
echo 'midi';
}
else if ($hours === 0) {
echo 'minuit';
}
else
{
echo $numerals[$hours % 12] .' heure';
if ($hours % 12 !== 1) {
echo 's';
}
}
/** Print minutes **/
if ($reverse) {
echo ' moins';
}
if ($minutes === 15)
{
if ($reverse) {
echo ' le ';
}
else {
echo ' et ';
}
echo 'quart';
}
else if ($minutes === 30) {
echo ' et demi';
}
else if ($minutes !== 0)
{
echo ' ';
if ($minutes < 22) {
echo $numerals[$minutes];
}
else {
echo $numerals[20] .'-'. $numerals[$minutes % 10];
}
}
/** Print daytime **/
if ($hours % 12 !== 0)
{
if ($reverse) {
--$hours;
}
if ($hours < 12) {
echo ' du matin';
}
else if ($hours < 17) {
echo " de l'après-midi";
}
else {
echo ' du soir';
}
}
echo '.';
```
[Answer]
# Python 3, ~~586~~ ~~547~~ ~~556~~ ~~506~~ ~~505~~ ~~502~~ ~~498~~ ~~497~~ 493 Bytes
My first attempt at golfing anything. I’m really not sure about the way I choose, especially the `n` list. But I wanted to give it a try.
```
from datetime import*;t=datetime.now()
n='/une/deux/trois/quatre/cinq/six/sept/huit/neuf/dix/onze/douze/treize/quatorze/et quart/seize/dix-sept/dix-huit/dix-neuf/vingt//et demi'.split('/')
n[21:22]=['vingt-'+i for i in['et-une']+n[2:10]]
h,m=t.hour,t.minute;s=h//12;h%=12
e=' d'+('u matin',("e l'après-midi","u soir")[h>4])[s]
try:m=' '[:m]+n[m]
except:m=' moins '+(n[60-m],'le quart')[m==45];h+=1
e,h=('',e,('minuit','midi')[h//12^s],n[h]+' heures'[:h+5])[h%12>0::2]
print('Il est',h+m+e+'.')
```
Ungolfed:
```
from datetime import datetime
time = datetime.now()
numbers = [
'', 'une', 'deux', 'trois', 'quatre',
'cinq', 'six', 'sept', 'huit', 'neuf',
'dix', 'onze', 'douze', 'treize', 'quatorze',
'et quart', 'seize', 'dix-sept', 'dix-huit', 'dix-neuf',
'vingt', 'vingt-et-une', 'vingt-deux', 'vingt-trois', 'vingt-quatre',
'vingt-cinq', 'vingt-six', 'vingt-sept', 'vingt-huit', 'vingt-neuf',
'et demi']
status, hour = divmod(time.hour, 12)
if status:
ending = " du soir" if h>4 else " de l’après-midi"
else:
ending = " du matin"
try:
if not time.minute:
minutes = ""
else:
minutes = " " + numbers[time.minute]
except IndexError:
hour += 1
if time.minute == 45:
minutes = " moins le quart"
else:
minutes = " moins " + numbers[60 - time.minute]
if hour%12: # 'whole' hours
hours = numbers[hour] + " heures"
if hour == 1:
# removing extra 's'
hours = hours[:-1]
else: # midnight or noon
ending = ""
if (hour == 12 and status) or (hour == 0 and status == 0):
hours = "minuit"
else:
hours = "midi"
print('Il est', hours + minutes + ending + '.')
```
[Answer]
# Javascript (ES6), ~~506~~ 495 bytes
Edit: Compressed `a` to save a few bytes.
```
a=`
un
j
k
yre
h
six
w
v
p}
onldoultreilyorl
seize}-w}-v}-p~~ et un{j{k{yre{h{six{w{v{p
et demi`,[...`hjklpvwy{}~`].map((x,w)=>a=a.split(x).join(`cinq|deux|trois|ze
|neuf|huit|sept|quat|~-|
dix|
vingt`.split`|`[w])),a=a.split`
`,alert(`Il est ${(e=(d=((b=(z=new Date).getHours())+(y=(c=z.getMinutes())>30))%24)%12)?a[e]+` heure${e-1?"s":""}`:d?'midi':'minuit'} ${y?"moins ":""}${y?c-45?a[60-c]:'le quart':c-15?a[c]:'et quart'}${e?[' du matin'," de l'apres-midi",' du soir'][(b>12)+(b>16)]:""}.`)
```
Explanation:
```
a = 'compressed string of french numbers with 'et demi' for 30 and 15 removed';
a = // code that decompresses a
// a,b,c,d,e,y,z are all inlined into the first expression that uses them
z = new Date();
b = z.getHours();
c = z.getMinutes();
y = c > 30; // true if 60 - minutes, false otherwise
d = (b + y) % 24; // the next hour if y
e = d % 12; // is it not noon and not midnight?
alert(
"Il est " +
// add the hour
// if d is not 0 or 12, add d + 'heure(s)'
(e ? a[e] + ` heure${e-1?"s":""}` : d ? 'midi' : 'minuit') +
" " +
(y ? "moins " : "") + // add 'moins' if necessary
( // add the minute
y? // necessary to subtract from 60?
c-45?
a[60-c] // add normal number word
:'le quart' // handle special case for 45
:c-15?
a[c] // add normal word
:'et quart' // handle special case for 15
) +
( // select appropriate ending
e? // is it not noon and not midnight?
// create array of endings
[" du matin"," de l'apres-midi"," du soir"]
// selects item 0 if b in [0, 12], item 1 if b in [13, 16] and item 2 if b > 16
[(b > 12) + (b > 16)]
:"" // if it's noon or midnight, no ending is necessary
) +
"." // add period
)
```
[Answer]
# **C, ~~860 835~~ 794 bytes**
Absolutely horrendous, but can probably be made even shorter. Many newlines were added for formatting purposes on this site. The actual source code has newlines after the #includes and #defines, but everything starting from char\* to the last w(".\n");} are all in one line. I shortened it by removing the values from 22,...,29 in the string array, instead reusing the strings for 2,...,9 and prepending a "vingt-" when appropriate. (I really hope I didn't introduce a bug!)
```
#include <sys/time.h>
#define w printf
#define q tm_min
#define r tm_hour
char*a[]={"minuit","une","deux","trois","quatre","cinq","six","sept","huit","neuf","dix",
"onze","douze","treize","quatorze","quart","seize","dix-sept","dix-huit","dix-
neuf","vingt","vingt-et-une",0,0,0,0,0,0,0,0,"demi"};
h=1,s=1,m,e,l,t,p,o,v;struct tm j;
main(){struct timeval i;gettimeofday(&i,0);localtime_r(&i.tv_sec,&j);
j.q>30?m=1,++j.r,j.q=60-j.q:j.q==15||j.q==30?e=1:0;j.q>21&&j.q<30?v=1:0;
j.r%12?j.r<12?t=1:j.r-m<17?p=1:(o=1):0;
j.q==15&&m?l=1:0;j.r%12?j.r%12==1?s=0:0:(h=0,s=0);
w("Il est ");j.r==12?w("midi"):w("%s",a[j.r%12]);h?w(" heure"):0;s?w("s"):0;
m?w(" moins"):0;e?w(" et"):0;l?w(" le"):0;
j.q?v?w(" vingt-"):w(" "),w("%s",a[j.q-20*v]):0;
t?w(" du matin"):p?w(" de l'apres-midi"):o?w(" du soir"):0;w(".\n");}
```
Like this:
```
#include <sys/time.h>
#define w printf
#define q tm_min
#define r tm_hour
char*a[]={"minuit","une","deux","trois","quatre","cinq","six","sept","huit","neuf","dix","onze","douze","treize","quatorze","quart","seize","dix-sept","dix-huit","dix-neuf","vingt","vingt-et-une",0,0,0,0,0,0,0,0,"demi"};h=1,s=1,m,e,l,t,p,o,v;struct tm j;main(){struct timeval i;gettimeofday(&i,0);localtime_r(&i.tv_sec,&j);j.q>30?m=1,++j.r,j.q=60-j.q:j.q==15||j.q==30?e=1:0;j.q>21&&j.q<30?v=1:0;j.r%12?j.r<12?t=1:j.r-m<17?p=1:(o=1):0;j.q==15&&m?l=1:0;j.r%12?j.r%12==1?s=0:0:(h=0,s=0);w("Il est ");j.r==12?w("midi"):w("%s",a[j.r%12]);h?w(" heure"):0;s?w("s"):0;m?w(" moins"):0;e?w(" et"):0;l?w(" le"):0;j.q?v?w(" vingt-"):w(" "),w("%s",a[j.q-20*v]):0;t?w(" du matin"):p?w(" de l'apres-midi"):o?w(" du soir"):0;w(".\n");}
```
Ungolfed version, with no "space optimizations" (also pretty ugly):
```
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
int main(int argc, char *argv[])
{
struct timeval tv;
struct tm local_time;
char *nums[] = {"minuit", "une", "deux", "trois", "quatre", "cinq", "six", "sept", "huit", "neuf", "dix", "onze", "douze", "treize", "quatorze", "quart", "seize", "dix-sept", "dix-huit", "dix-neuf", "vingt", "vingt-et-une", "vingt-deux", "vingt-trois", "vingt-quatre", "vingt-cinq", "vingt-six", "vingt-sept", "vingt-huit", "vingt-neuf", "demi"};
int heure = 1;
int s = 1;
int moins = 0;
int et = 0;
int le = 0;
int matin = 0, aprem = 0, soir = 0;
memset(&local_time, 0, sizeof local_time);
gettimeofday(&tv, NULL);
localtime_r(&tv.tv_sec, &local_time);
#if 0
local_time.tm_min = atoi(argv[1]);
local_time.tm_hour = atoi(argv[2]);
#endif
if (local_time.tm_min > 30) {
moins = 1;
local_time.tm_hour += 1;
local_time.tm_min = 60 - local_time.tm_min;
} else if (local_time.tm_min == 15 || local_time.tm_min == 30) {
et = 1;
}
if (local_time.tm_hour % 12) {
if (local_time.tm_hour < 12)
matin = 1;
else if (local_time.tm_hour < 17)
aprem = 1;
else if (local_time.tm_hour == 17 && moins)
aprem = 1;
else
soir = 1;
}
if (local_time.tm_min == 15 && moins)
le = 1;
if (local_time.tm_hour % 12 == 0) {
heure = 0;
s = 0;
} else if (local_time.tm_hour % 12 == 1) {
s = 0;
}
printf("Il est ");
if (local_time.tm_hour == 12)
printf("midi");
else
printf("%s", nums[local_time.tm_hour % 12]);
if (heure)
printf(" heure");
if (s)
printf("s");
if (moins)
printf(" moins");
if (et)
printf(" et");
if (le)
printf(" le");
if (local_time.tm_min)
printf(" %s", nums[local_time.tm_min]);
if (matin)
printf(" du matin");
else if (aprem)
printf(" de l'apres-midi");
else if (soir)
printf(" du soir");
printf(".\n");
return 0;
}
```
(The #if 0 stuff was just for testing different time values through the command-line).
] |
[Question]
[
Help! My math exam is coming up soon and I didn't study! 1 Part of the exam is to classify a quadrilateral given its vertex coordinates, which I, unfortunately, do not know how to do. 2
So, your challenge is to write a program to do this for me so I don't fail!
# Challenge
Given four vertices such that no three of them are colinear, determine the most specific classification of the quadrilateral formed by those four vertices.
What I mean by "most specific classification" is that even though all squares are rectangles, if the shape is a square, you should indicate that it is a square and not indicate that it is a rectangle.
# Input
Input will be given as four (x, y) coordinates. You may take these as a list of length 4 of lists/tuples of length 2. Alternatively, you can take input as a list of the x-coordinates and a list of the respective y-coordinates.
For example, if my shape has vertices at points `(0, 0)`, `(5, 0)`, `(6, 1)`, and `(1, 1)`, you may choose to take input in either of the following formats or something similar:
```
[(0, 0), (5, 0), (6, 1), (1, 1)]
([0, 5, 6, 1], [0, 0, 1, 1])
```
You may assume that the quadrilateral is not self-intersecting and that the points are given in the correct order (that is, two consecutive points in the input will be connected by a line segment in the quadrilateral).
# Output
You will need a unique output for each of the following classes of quadrilaterals:
* Square
* Rectangle
* Rhombus
* Parallelogram
* Trapezoid/Trapezium
* Kite
* Quadrilateral
This could be the exact name itself, a character, an integer, etc.
# Rules
* Standard Loopholes Apply
* If your programming language has a built-in that will perform this exact task, that built-in is not allowed.
* Built-ins for finding the distance between two points are allowed.
* Built-ins for finding the angle between two lines are allowed.
At this point, if you know all of the terms, you are ready to start programming! (Test Cases are at the end)
# Terminology
This section is for anyone who needs clarification on the definitions of the different shapes.
## Square
A quadrilateral is a square if and only if all 4 of its sides are equal in length and every pair of adjacent sides is perpendicular (that is, it is both a rectangle and a rhombus).
## Rectangle
A quadrilateral is a rectangle if and only if every pair of adjacent sides is perpendicular.
## Rhombus
A quadrilateral is a rhombus if and only if all 4 of its sides are equal.
## Parallelogram
A quadrilateral is a parallelogram if and only if each pair of opposite sides is parallel and each pair of opposite angles is equal. Both of these conditions imply each other so you only need to check for one of them.
## Trapezoid/Trapezium
A quadrilateral is a trapezoid/trapezium if and only if it has at least one pair of parallel sides.
## Kite
A quadrilateral is a kite if two opposite pairs of adjacent sides are equal in length; that is, two of its adjacent sides are equal and the other two are also equal.
# Test Cases
```
input as (x, y) * 4 -> full name
[(0, 0), (1, 0), (1, 1), (0, 1)] -> square
[(0, 0), (1, 1), (-1, 3), (-2, 2)] -> rectangle
[(0, 0), (5, 0), (8, 4), (3, 4)] -> rhombus
[(0, 0), (5, 0), (6, 1), (1, 1)] -> parallelogram
[(0, 0), (4, 0), (3, 1), (1, 1)] -> trapezoid/trapezium
[(0, 0), (1, 1), (0, 3), (-1, 1)] -> kite
[(0, 0), (2, 0), (4, 4), (0, 1)] -> quadrilateral
```
# Links (Desmos Graphing Calculator)
Here are links to visualizations of each of the test cases.
[Square](https://www.desmos.com/calculator/e5vul3m2cx)
[Rectangle](https://www.desmos.com/calculator/60oirur3qe)
[Rhombus](https://www.desmos.com/calculator/5oyw7fdijk)
[Parallelogram](https://www.desmos.com/calculator/d9qay92ec2)
[Trapezoid/Trapezium](https://www.desmos.com/calculator/osazierary)
[Kite](https://www.desmos.com/calculator/l4uek0xowk)
[Quadrilateral](https://www.desmos.com/calculator/odfufsmdua)
# Winning Criteria
I can't bring a computer into the exam obviously, so I need you to write the shortest code possible so I can memorize it. I need to write it into the margins and run it using TryItOfflineTM so to fit it into the margins your program needs to be as small as possible!
1 Of course I actually did :P
2 Of course I actually do :P
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~104~~ ~~89~~ ~~80~~ ~~82~~ ~~81~~ ~~79~~ 78 bytes
```
⍙←{⍵⍺⍺1⌽⍵}
⎕←(|x){⍵≡2⌽⍵:≡⍙¨0⍺⍵⋄2 4=+/1=2|+⍙↑⍵(=⍙⍺)}2|1+-⍙(12○x←-⍙⎕+.×1 0J1)÷○1
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v//Ue/MR20Tqh/1bn3UuwuIDB/17AVyarke9U0FSmjUVGiCJTsXGkFkrIBMoKZDKwzAGrY@6m4xUjCx1dY3tDWq0QYbNxEorGELYvbu0qw1qjHU1gVyNAyNHk3vrgAaCuIBjdfWOzzdUMHAy1Dz8HagjOGolaNWDi0rgdmnbaKGgYKBpoYhhDDUBHINNbmQxIFCh9YbKhiDKCMFIyQ5UxBhoWCiqWEMJNDEzUAaDVHMMgERxpjiUGuNIRYhyxhBtJlAXAUA "APL (Dyalog Classic) – Try It Online")
---
# Input/Output
Takes a 4×2 matrix of coordinates as input
Outputs
* `1 1 1` for Square
* `1 1 0` for Rhombus
* `1 0 1` for Rectangle
* `1 0 0` for Parallelogram
* `1 0` for Kite
* `0 1` for Trapezium
* `0 0` for Quadrilateral
---
# Algorithm
First, find all 4 side lengths and angles of the quadrilateral
If both pairs of opposite angles are equal (`OA`), then the shape is some kind of parallelogram. Determine if all side lengths are equal (`AS`, Adjacent Sides) and if all angles are equal (`AA`).
```
+--------+----------------+----------------+
| | AA | ~AA |
+--------+----------------+----------------+
| AS | Square | Rhombus |
|--------+----------------+----------------+
| ~AS | Rectangle | Parallelogram |
+--------+----------------+----------------+
```
If not `OA`, then:
* Determine if there are exactly 2 pairs of equal adjacent sides and if they are separated (`aabb` instead of `aaab`). If so, the shape is a kite.
* Determine if there are exactly 1 pair of parallel opposite sides. If so, the shape is a trapezium.
* Otherwise, the shape is a quadrilateral.
---
# Code
`⍙←{⍵⍺⍺1⌽⍵}` defines a new operator. In APL, an operator means a [higher-order function](https://en.wikipedia.org/wiki/Higher-order_function). This operator takes 1 functional argument (`⍺⍺`) and returns a monadic function that:
1. Rotates (`1⌽`) the argument (`⍵`)
2. Apply `⍺⍺` between it and `⍵`
This is especially useful for scalar functions since most of them implicitly map across array arguments, allowing `⍙` to apply those between each adjacent pair of elements with wrap around. For example `+⍙1 2 3 4` is `1 2 3 4 + 2 3 4 1` which evaluates to `3 5 7 5`.
---
`x←-⍙⎕+.×1 0J1` converts the input coordinate matrix into an array of complex numbers representing the vectors of the 4 sides of the shape.
* `⎕`, when referenced, takes and returns input
* `1 0J1` represents the vector [1,i] ("vector" in the mathematical sense, and "i" as the square root of -1). In APL, a complex number `a+bi` is written `aJb`
* `+.×` matrix multiplication. Mathematically, the result would be a 4×1 matrix. However, `+.×` is called "inner product" in APL which generalizes matrix multiplication and vector inner product and allows you to do even stuff like "multiply" a 3-dimensional array with a 2-dimensional one. In this case, we are multiplying a 4×2 matrix and a 2-element vector, resulting in a 4-element vector (of the complex number representations of the 4 given vertices).
* `-⍙` is pairwise subtraction with wrap around as noted above. This gives the vectors of the 4 sides of the shape (as complex numbers). These vectors point in the "reverse" direction but that doesn't matter.
* `x←` stores that into the variable `x`
---
`2|1+-⍙(12○x)÷○1` finds (a representation of) the exterior angles at the 4 vertices of the shape.
* `12○x` finds the [principal argument](https://en.wikipedia.org/wiki/Argument_(complex_analysis)), in radians, of each of the 4 side vectors.
* `÷○1` divides by π so that the angles are easier to work with. Thus, all angles are expressed as a multiple of a straight angle.
* `-⍙` Pairwise subtraction with wrap around as noted above. This gives the 4 exterior angles.
* `2|1+` The principal argument is capped (-1,1] and pairwise subtraction makes the range (-2,2]. This is bad since the same angle has 2 different representations. By doing "add 1 mod 2", the angle is re-capped at (0,2]. Although all angles are 1 more than what it should be, it's fine if we keep that in mind.
---
`|x` finds the [magnitude](https://en.wikipedia.org/wiki/Magnitude_(mathematics)#Complex_numbers) of each of the 4 side vectors
---
`{⍵≡2⌽⍵:≡⍙¨0⍺⍵⋄2 4=+/1=2|+⍙↑⍵(=⍙⍺)}` defines and applies a function with the array of 4 exterior angles as right argument `⍵` and the array of 4 side lengths as right argument `⍺`.
* The function has a guarded expression. In this case, `⍵≡2⌽⍵` is the guard.
* If the guard evaluates to `1` then the next expression `≡⍙¨0⍺⍵` is executed and its value returned.
* If the guard evaluates to `0`, that expression is skipped and the one after that `2 4=...=⍙⍺)` gets executed instead.
---
`⍵≡2⌽⍵` checks if both pairs of opposite angles are equal.
* `2⌽⍵` rotates the angles array by 2 places.
* `⍵≡` checks if that is the same as `⍵` itself
---
`≡⍙¨0⍺⍵` returns a unique value for each parallelogram-type shape.
* `0⍺⍵` is the 3-element array of the scalar `0`, the side lengths array `⍺`, and the angles array `⍵`.
* `≡⍙¨` executes `≡⍙` for each of those elements.
* `≡⍙` checks if all values of an array are equal by checking if rotating it by 1 gives the same array. Scalars do not rotate so `≡⍙0` returns `1`. As noted above, `≡⍙⍺` checks for a rhombus and `≡⍙⍵` checks for a rectangle.
---
`2 4=+/1=2|+⍙↑⍵(=⍙⍺)` returns a unique value for each non-parallelogram-type shape. This is achieved by intertwining the checks for kite and trapezium.
---
`2=+/1=2|+⍙⍵` checks for a trapezium.
* `+⍙⍵` gives the adjacent angle sums. The interior angles of parallel lines sum to a straight angle, thus so does the exterior angles of parallel sides of a quadrilateral. So, each pair of parallel sides should lead to two `1` or `-1` in the adjacent angle sums.
* `1=2|` However, the angles in `⍵` are 1 more than what they should be, so the angles actually sum to `1` or `3`. This can be checked by "mod 2 equals 1".
* `+/` sums the array. This gives a count of adjacent angle sums which is `1` or `3`.
* `2=` check if that equals 2. (I.e. if there is exactly one pair of parallel sides)
---
`4=+/1=2|+⍙(=⍙⍺)` checks for a kite.
* `(=⍙⍺)` gives an array indicating which adjacent sides are equal. Unlike `≡`, `=` work element-wise. Thus, this is a 4-element array with `1`s where the length of that side is equal to that of the "next" side.
* `+⍙` Pairwise sum with wrap around.
* `1=2|` Since `(=⍙⍺)` gives a boolean array (one with only `0`s and `1`s), the only possible values of pairwise sum are `0`, `1` and `2`. So `1=2|` is same as just `1=`.
* `+/` sums the array. This gives a count of pairwise sums which is `1`.
* `4=` check if that equals 4. The only way that happens is if `(=⍙⍺)` is `1 0 1 0` or `0 1 0 1`. As noted above, this means the shape is a kite.
---
`2 4=+/1=2|+⍙↑⍵(=⍙⍺)` intertwines the above checks.
* `⍵(=⍙⍺)` is the 2-element nested array of the array `⍵` and the array `(=⍙⍺)`
* `↑` promotes the nested array to a proper matrix. Since `⍵(=⍙⍺)` is a 2-element array of 4-element arrays, the result is a 2×4 matrix.
* `+⍙` Since `⌽` (and, by extension, `⍙`) rotates the last (horizontal) axis, `+⍙` to a matrix is same as applying `+⍙` to each row individually.
* `1=2|` both residue/mod (`|`) and equals (`=`) works on a per-element basis, even to matrices.
* `+/` By default, reduce (`/`) works along the last (horizontal) axis. So `+/` sums along rows and turn a 2×4 matrix into a 2-element simple array.
* `2 4=` Since `=` works per-element, this checks the kite and trapezium conditions simultaneously.
[Answer]
## Mathematica, 195 bytes
```
Which[s=Differences@{##,#};l=Norm/@s;r=#.#2==#2.#3==0&@@s;Equal@@l,If[r,1,2],#==#3&==#4&@@l,If[r,3,4],MatchQ[l,{a_,b_,b_,a_}|{a_,a_,b_,b_}],5,#+#3=={0,0}||#2+#4=={0,0}&@@Normalize/@s,6,1>0,7]&
```
With whitespace:
```
Which[
s = Differences @ {##,#};
l = Norm /@ s;
r = #.#2 == #2.#3 == 0& @@ s;
Equal @@ l, If[r, 1, 2],
# == #3 && #2 == #4& @@ l, If[r, 3, 4],
MatchQ[l, {a_,b_,b_,a_}|{a_,a_,b_,b_}], 5,
#+#3 == {0,0} || #2+#4 == {0,0}& @@ Normalize /@ s, 6,
1 > 0, 7
]&
```
Outputs `1` for squares, `2` for rhombi, `3` for rectangles, `4` for parallelograms, `5` for kites, `6` for trapezoids, and `7` for anything else. I'd post a TIO link, but this apparently doesn't work in Mathics.
If the four points are `P`, `Q`, `R`, and `S`, then `{##,#}` is `{P,Q,R,S,P}`, so `s` is the list of side vectors `{Q-P,R-Q,S-R,P-S}`, `l` is the lengths of those vectors, and `r` is the condition that the angle between `Q-P` and `R-Q` as well as the angle between `R-Q` and `S-R` are both `90` degrees.
Thus, if all the sides lengths are equal, then the quadrilateral is a rhombus. If `r` holds, it is in fact a square, otherwise it's just a plain rhombus.
Ruling out rhombi, if both pairs of opposite side lengths are equal, then the quadrilateral is still parallelogram. If `r` holds, it is in fact a rectangle, otherwise, it's just a plain parallelogram.
Ruling out parallelograms, the list of side lengths `l` is of the form `{a,b,b,a}` or `{a,a,b,b}` for some `a` and `b`, then the quadrilateral is a kite. Note that it can't additionally be a trapezoid or it would in fact be a rhombus.
Ruling out parallelograms and kites, if the quadrilateral has a pair of parallel sides, then it is a trapezoid. We check this by `Normalize`ing the side vectors and checking whether a pair of opposite vectors adds to `{0,0}`.
Ruling out all of the above, if `1 > 0` (it better be), then the quadrilateral is just a plain old quadrilateral.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~463~~ ~~410~~ ~~408~~ 397 bytes
Saved 53 bytes by using a tuple in the sixth line instead of indexing into a list.
Saved 11 bytes by shifting to output integers 1 through 7 instead of the first letter of each shape. The integers correspond as follows:
1. Square
2. Rectangle
3. Rhombus
4. Parallelogram
5. Trapezoid
6. Kite
7. Quadrilateral
```
from numpy import *;D=dot
from numpy.linalg import *;N=norm
def P(a,b):x=D(a,b);y=N(a)*N(b);return x==y or x==-y
def Q(a,b):return int(N(a)==N(b))
L=input()
a,b,c,d=tuple([(L[i][0]-L[(i+1)%4][0],L[i][1]-L[(i+1)%4][1]) for i in range(4)])
g=7
e=Q(a,c)+Q(b,d)
if e==2:
g=(1if D(a,b)==0 else 3) if Q(a,b) else 2 if D(a,b)==0 else 4
elif P(a,c) or P(b,d):
g = 5
elif Q(a,b) or Q(b,c):
g = 6
print g
```
[Try it online!](https://tio.run/##ZVBNb4MwDL3nV/gyyW7TCWi3Sa1867Gq2jPiQCGwSBBQFqTy61kCrappJz/7@T1/9KP77kwyTZXtWjBD24@g276zDlaHI5edEy/mvdEmb@pXw5lNZ1tRqgoumMsb7e98nMFh5DPmtDqjx1a5wRq4M4/Q2RA34yy6LqIHr43DIGIOKhIn1qYfHJLwXbKQJbuhbxSmeEp1lkbZ5pSiXsf0tguZnKvxn2qcEVR@pPbmYHNTK9xRRqLmL6E4jC9ofcWbLEnoChRzshdQM8Y@Wy5hjkA1Pwq2BPq58lJJ4H/XTqhGL@8oKFx7md2DKzB8LOzDxLNhdvFkP0Vv/ROgnqYUIwkRScBYQhzixoPtDBIJCWW/ "Python 2 – Try It Online")
## Ungolfed to show the logic
Shown as a function, to show output for the different test input. note I changed the "Rectangle" test example from the one originally provided in the question, which was not a rectangle.
The logic rests on dot products and the norm (length) of the vectors formed by the sides of the quadrilateral to assess whether sides are equal in length, parallel on opposite sides, or perpendicular to adjacent sides.
```
def S(va, vb):
return (va[0]-vb[0], va[1]-vb[1])
def dot(sa,sb): # Eventually replaced with numpy.dot
return(sa[0]*sb[0]+sa[1]*sb[1])
def norm(s): # Eventually replaced by numpy.linalg.norm
return (s[0]**2+s[1]**2)**.5
def isperp(a,b): # Test if lines/vectors are perpendicular
return dot(a,b)==0
def ispar(a,b): # Test if lines/vectors are parallel
x = dot(a,b)
y = norm(a)*norm(b)
return x == y or x == -y
def iseq(a,b): # Test if lines/vectors are equal in length
return norm(a)==norm(b)
def f(L):
#Define the four sides
s = []
for i in range(4):
s.append(S(L[i],L[(i+1)%4])) # I refer often so shorter names may eventually
guess = 'Q'
eqsides = 0 # These 6 lines eventually golfed using integer arithmetic by returning an int from iseq()
if iseq(s[0], s[2]):
eqsides += 1
if iseq(s[1],s[3]):
eqsides += 1
if eqsides == 2:
# Opposite sides are equal, so square, rhombus, rectangle or parallelogram
if iseq(s[0],s[1]): #Equal adjacent sides, so square or rhombus
guess='S' if isperp(s[0], s[1]) else 'H'
else: # rectangle or Parallelogram
guess='R' if isperp(s[0], s[1]) else 'P'
elif ispar(s[0],s[2]) or ispar(s[1],s[3]):
guess = 'T'
elif iseq(s[0],s[1]) or iseq(s[1],s[2]):
guess = 'K'
return guess
#test suite:
print f([(0, 0), (1, 0), (1, 1), (0, 1)]) # -> square
print f([(0, 0), (1, 1), (-1, 3), (-2, 2)]) # -> rectangle
print f([(0, 0), (5, 0), (8, 4), (3, 4)]) # -> rhombus
print f([(0, 0), (5, 0), (6, 1), (1, 1)]) # -> parallelogram
print f([(0, 0), (4, 0), (3, 1), (1, 1)]) # -> trapezoid/trapezium
print f([(0, 0), (1, 1), (0, 3), (-1, 1)]) #-> kite
print f([(0, 0), (2, 0), (4, 4), (0, 1)]) #-> quadrilateral
```
[Try it online!](https://tio.run/##hVRNb9pAEL3zK0ZCFTYYgg2JqkjuqZFaNVLTkpvFYcFjs62/srumpX@ezq7XxjSE@sCOx/Pem6@lOqhdWQTHY4wJrJw982C/ce8HQI9AVYsCyBnN19P9hn7pK4t88@Kv3YEGxaVyJPMkocA8Q3jYY6FqlmUH4qgytsUYfnG1g6LOq8OMED1@AhPxWGr6idTs2m7Zi1Lkjmyp32TfHCx3xguWpTMNO6tBao1xMJGafxy44/Hs1ghwWaGoHOa1@Q/hGaUCngBxobzZ41aVQgITCDoUi5hv64yJPr9ugqYIw3nLykSP9DorE1QNZobwN4Qdm3EcyGG6wNyxOa3fKlN8SDGlaKzpwerjS1/@qj6@UDeBF5Bhkapdn90Kh2FP2QgkzqPdkuFHTIgS1A4hKWsBkscozSdJqUdrYyaUINcaghUpOksLNlEzVumuOivnMeJr7zFy@MR33y3XrqsT/0zJJCigTBQWIEuQu1IochQsRwk5OwB2KzEwtGmNUouPvo3MO76YpMgzB@it0vMOJcJd05MeC6RlltBa1ZIXKWWtMCU9JmiHc1R8q/et6ZD@zgodAoko86bxzYC4HYM090ZGwbpXdJvRJAT/n2h/7clo8b/grqQQAjsI@FpVpeQKmxGcZuuZrpEl0AOxK/NNLcmgFaBhZKiXp93BMhUs74TPStCZnfbpwSwNi3/Q/aPijWJPR3NapUGv5c1kwtFq1HCbu9c2iOgBMxrI6NPoVDs57uHSMzyv4OliBT3N79c1n@yqZLy9vrZqmpvmb32vx9Nt2/MZxVnfGobTfIOLBF9G/ctn3MYxGAyVvr6ypuneDyph9s2JnLkHc9cDxz@dvj7n@iTVIUw/2IlcRpnoKRkLYwQeBB2ua@8F6K0933uw1OdCnwZokHbyb@PurLTfJapx51v4Gr205@IVmsBKsAr/lDy@aSxe51dqnrcldxxE8VNfHriACk4JLM/6SyDqbix4xugviWXH418 "Python 2 – Try It Online")
[Answer]
## Batch, 287 bytes
```
@set/aa=%3-%1,b=%4-%2,c=%5-%1,d=%6-%2,e=%7-%1,f=%8-%2,g=a*a+b*b,h=(h=c-a)*h+(h=d-b)*h,i=(i=c-e)*i+(i=d-f)*i,j=e*e+f*f,p=!(i-g)+!(j-h),q=!(h-g),r=!(a*e+b*f),k=q+!(j-i)^|!(j-g)+!(h-i),t=!(a*(f-d)-b*(e-c))+!((c-a)*f-(d-b)*e)
@if %p%==2 (echo 1%r%%q%)else if %k%==2 (echo 1)else (echo 1%t%)
```
Outputs in binary: `1` = Kite, `10` = Quadrilateral, `11` = Trapezium, `100` = Parallelogram, `101` = Rhombus, `110` = Rectangle, `111` = Square.
Explanation: `g, h, i, j` are the squares of the lengths of the sides. `p` is the number of pairs of opposite sides with the same length, `q` distinguishes between parallelograms/rectangles and rhobmi/squares by checking whether the opposite pairs are in fact equal, `r` distinguishes between parallelograms/rhombi and rectangles/squares via a perpendicularity check, `k` checks for a kite by looking for pairs of equal adjacent sides and `t` checks for a trapezium via a couple of parallel side checks.
] |
[Question]
[
Write functions \$x(a)\$, \$y(a)\$ and \$z(a)\$ such that for any rational \$a\$ **all functions return rational numbers** and
$$x(a) \times y(a) \times z(a) \times (x(a) + y(a) + z(a)) = a$$
You may assume \$a \ge 0\$
You do not need to use rational types or operations in your program, as long as your program is mathematically sound. E.g. if you use a square root in your answer you must show that its argument is always a square of a rational number.
You may write three named functions `x`, `y`, `z` or write three programs instead if functions are cumbersome or non-existent for your language. Alternatively you may also write a single program/function that returns three numbers \$x\$, \$y\$, \$z\$. Finally, if you so prefer you may input/output the rational numbers as a numerator/denominator pair. Your score is the total size of the three functions or three programs in bytes. Smallest score wins.
Brute forcing is not allowed. For any \$a = \frac p q\$ where \$p, q \le 1000\$, your program should run in under 10 seconds.
---
An example (this does not mean your decomposition has to give these numbers):
```
x = 9408/43615
y = 12675/37576
z = 1342/390
x*y*z*(x+y+z) = 1
```
[Answer]
## CJam (59 bytes)
```
{[WZ~C24X8TT]f*[4XGYC6 4Y].+_0=!>2%Z65135Zb+:(3/.f#:.*)W*+}
```
This is an anonymous block (function) which takes an integer or double on the stack and produces an array with three doubles. It has two cases internally to handle all non-negative inputs, since with only one case it would break on either `0.25` or `4`. It still breaks for inputs `-12` and `-1.3333333333333333`, but the spec allows that...
The [online demo](http://cjam.aditsu.net/#code=5.%0A%0A%7B%5BWZ~C24X8TT%5Df*%5B4XGYC6%204Y%5D.%2B_0%3D!%3E2%25Z65135Zb%2B%3A(3%2F.f%23%3A.*)W*%2B%7D%0A%0A~%0A_%3A%2B%2B_p%3A*) executes it and then adds up the values, prints all four, and multiplies them to show that it gets the original value (modulo rounding error).
### Mathematical background
Following [Noam Elkies](http://www.math.harvard.edu/~elkies/euler_14t.pdf) we define the auxiliary \$w = - x - y - z\$. Then \$x + y + z + w = 0\$ and \$-xyzw = a\$ or \$xyzw + a = 0\$. This has lots of symmetry; any solution will have four formulae and we can pick the three golfiest ones.
Elkies gives four families of sets of solutions. Euler's:
$$\begin{eqnarray\*}
x & = & \frac{6ast^3(at^4-2s^4)^2}{(4at^4+s^4)(2a^2t^8 + 10as^4t^4 - s^8)} \\
y & = & \frac{3s^5(4at^4+s^4)^2}{2t(at^4-2s^4)(2a^2t^8+10as^4t^4-s^8)} \\
z & = & \frac{2(2a^2t^8+10as^4t^4-s^8)}{3s^3t(4at^4+s^4)} \\
w & = & \frac{-(2a^2t^8+10as^4t^4-s^8)}{6s^3t(at^4-2s^4)}
\end{eqnarray\*}$$
One related to Euler's:
$$\begin{eqnarray\*}
x & = & \frac{(8s^8+a^2)(8s^8-88as^4-a^2)}{12s^3(s^4-a)(8s^8+20as^4-a^2)}\\
y & = & \frac{(8s^8+a^2)(8s^8-88as^4-a^2)}{12s^3(8s^4+a)(8s^8+20as^4-a^2)}\\
z & = & \frac{192as^5(s^4-a)^2(8s^4+a)^2}{(8s^8+a^2)(8s^8-88as^4-a^2)(8s^8+20as^4-a^2)}\\
w & = & \frac{-3s(8s^8+20as^4-a^2)^3}{4(s^4-a)(8s^4+a)(8s^8+a^2)(8s^8-88as^4-a^2)}\\
\end{eqnarray\*}$$
A simpler one:
$$\begin{eqnarray\*}
x & = & \frac{(s^4-4a)^2}{2s^3(s^4+12a)} \\
y & = & \frac{2a(3s^4+4a)^2}{s^3(s^4-4a)(s^4+12a)} \\
z & = & \frac{s^5+12as}{2(3s^4+4a)} \\
w & = & \frac{-2s^5(s^4+12a)}{(s^4-4a)(3s^4+4a)} \\
\end{eqnarray\*}$$
And one related to that one:
$$\begin{eqnarray\*}
x & = & \frac{s^5(s^4-3a)^3}{2(s^4+a)(s^{12}+12as^8-3a^2s^4+2a^3)} \\
y & = & \frac{s^{12}+12as^8-3a^2s^4+2a^3}{2s^3(s^4-3a)(3s^4-a)} \\
z & = & \frac{2a(s^4+a)^2(3s^4-a)^2}{s^3(s^4-3a)(s^{12}+12as^8-3a^2s^4+2a^3)} \\
w & = & \frac{-2s(s^{12}+12as^8-3a^2s^4+2a^3)}{(s^4-3a)(s^4+a)(3s^4-a)}
\end{eqnarray\*}$$
Observe that every family has at least two denominators of the form \$ps^4 - qa\$ for positive \$p\$ and \$q\$: since all the terms involved are rational, that means that there's some positive \$a\$ for which we get division by zero. Therefore we must use at least two sets of solutions which have their singularities at different values of \$a\$. Intuitively it's going to be golfiest to choose two sets from the same family. I've chosen the simplest family (the third one) with parameters \$s=1\$ and \$s=2\$.
[Answer]
# Axiom, 191 bytes
```
f(s,a)==(b:=s^4-4*a;c:=s^4+12*a;x:=3*s^4+4*a;[b^2/(2*c*s^3),2*a*x^2/(b*c*s^3),s*c/(2*x)])
g(a:FRAC INT):List FRAC INT==(s:=1;repeat(s^4=4*a or s^4=-12*a or 3*s^4=4*a=>(s:=s+1);break);f(s,a))
```
It is the traslation of the formula Peter Taylor report in this page
with some code would make the denominators not be 0.
one test
```
(7) -> y:=g(1)
9 98 13
(7) [--,- --,--]
26 39 14
Type: List Fraction Integer
(8) -> y.1*y.2*y.3*(y.1+y.2+y.3)
(8) 1
Type: Fraction Integer
```
] |
[Question]
[
# Introduction
[Nine Mens's Morris](https://en.wikipedia.org/wiki/Nine_Men%27s_Morris) (also called Mills) is a board game for two players which is played on the following board (image taken from the linked Wikipedia-page):
[](https://i.stack.imgur.com/0sS03.png)
Each player has 9 men, colored black and white. The concrete rules are not important for this challenge, but check out the [Wikipedia-page](https://en.wikipedia.org/wiki/Nine_Men%27s_Morris) if you are interested.
# The Challenge
Given a grid as input, which represents a certain boardstate, output the total mill count `m` with `0<=m<=8`.
Three men of the same color form a mill when they are in a straight row of connected points. `b2` to `f2` is not a mill since the men are of different color. Also `d2` to `d5` would not form a mill since the three points have to be connected.
The board in the image above contains two mills for example. One from `f2` to `f6` and one from `e3` to `e5`.
# Input
The board is represented as a 2D grid with 24 points which are connected as shown in the example image above. The example uses letters from `a-g` for the columns and numbers from `1-7` for the rows, but you may choose any reasonable input format as long as it maps 24 unique coordinates to one of the following states:
* Empty
* Taken by black
* Taken by white
The concrete repersentation is up to you you are not restricted to "b" or "w" for the colors.
Besides this, your input may not contain any additional information.
### Additional notes
* You don't have to map the points by any kind of values. If you want to take the input as a 2D array, that's fine as well. But keep in mind that not all points in there are used and that you have to consider the connections between them.
* The input might be empty, in which case you have to output zero (empty board -> no mills).
* Since each player has 9 men, the input will never contain more than 18 taken points.
* You may leave out emtpy points in the input and therefore only input points which are taken.
* The input may be ordered in any way. You can't rely on a specific order.
* You may assume that the input will always be valid. This means that there won't be more than 9 men of each color and that each point will be unique.
# Rules
* Make clear which input format you use in your solution. Providing an example run of your program is hightly encouraged.
* Function or full program allowed.
* [Default rules](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) for input/output.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest byte-count wins. Tiebreaker is earlier submission.
# Test cases
The input format here is a list of tuples with the coordinates as in the example above as first element and the state of the point second element. A point taken by white is marked as "w" and a point taken by black as "b". All other points are left out and are empty.
```
[("a4","w"),("b2","b"),("b4","b"),("c4","b"),("d1","w"),("d2","w"),("e3","w"),("e4","w"),("e5","w"),("f2","b"),("f4","b"),("f6","b"),("g4","w")] -> 2
[("a1","b"),("a4","b"),("a7","b"),("b4","b"),("c4","b"),("d3","w"),("d2","w"),("d1","w")] -> 3
[] -> 0
[("b4", "b"),("a4",b"),("c4",w")] -> 0
[("b4", "b"),("a4",b"),("c4",b")] -> 1
[("a1", "b"),("a4", "b"),("a7", "b"),("b2", "b"),("b4", "b"),("b6", "b"),("c3", "b"),("c4", "b"),("c5", "b"),("e3", "w"),("e4", "w"),("e5", "w"),("f2", "w"),("f4", "w"),("f6", "w"),("g1", "w"),("g4", "w"),("g7", "w")] -> 8
```
**Happy Coding!**
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~26~~ 25 bytes
-1 thanks to FrownyFrog
```
≢{|∊(+/⍵⍪↓⍵),⊢/4 2⍴+⌿⍵}∩≢
```
[Try it online!](https://tio.run/##jVHLattAFN3rKwYtOnKtkEgzskKgX5JmMZqHYupYwhpbLal3wcRJVQohyy6aVZtNFm0pZBNo/2R@xL1jORoCpg2C0dG9554554qVox3xjo2KfIePWFUN@WqlzOKTWd6cvjfnF0F/1zQ/TXNrFlcAeqG5uNmlKDbNj7758ACluTn/BuzVyjSfEUe8GM/kRFdIF4gINByXU41UMTlh2uMgfHps1RdXcboWwSxilKUiElSkeZTTPM3ijGYDEUNloGJF1YATTnkiCFQSSSSVCTaXZyWatVKmWVYgZZqvcWiPP7/gBEsVtPHruo/Nx@sKv8Bg3Wa5PGPQIAgemNqD7yBkvcNj03wvj6Dz@y56OXuFa3sHm3s2lkZaVpApMM39gXxbSq6lQMVUQ7gQgejBdLwJLjeZe562aWHALL8oxC0JF2@sKFZsOMLrtd5P5l6s8WHgM@qHfu33wsDPYoBZC2kHuYMi6rgi7qAkDjoxmXRQOV3lxNSgg/lm7Ah7pDUVdT3mJlj6P39km79H16C@B@qb1xMNe4lTa7nRv0nZmrT/TLtbN5u5DXCyLQ9POvi8JdduybVbcgtz9/NyR8jTx@X8BQ "APL (Dyalog Classic) – Try It Online")
The argument is a 3x3x3 array of `1`(black), `¯1`(white), and `0`(empty).
The first dimension is along the concentric squares' nesting depth.
The other two dimensions are along the vertical and horizontal axis.
```
000---------001---------002
| | |
| 100-----101-----102 |
| | | | |
| | 200-201-202 | |
| | | | | |
010-110-210 212-112-012
| | | | | |
| | 220-221-222 | |
| | | | |
| 120-----121-----122 |
| | |
020---------021---------022
```
We have a mill whenever summation along any axis yields a `3` or `¯3`, except we must discard the four corners when summing along the first axis.
`{}` is a function with implicit argument `⍵`
`↓⍵` is *split* - in our case it turns a 3x3x3 cube into a 3x3 matrix of nested length-3 vectors
`⍵⍪↓⍵` takes the original cube and glues the 3x3 matrix of 3-vectors below it, so we get a 4x3x3 mixed array of scalars and vectors
`+/` sums along the last axis; this has the combined effect of summing the original cube along the last axis (`+/⍵`) and summing it along the middle axis due to the split we did (`+/↓⍵`)
Now we must take care of the special case for the first axis.
`+⌿⍵` sums along the first axis, returning a 3x3 matrix
`4 2⍴` but we must not count the corners, so we reshape it to a 4x2 matrix like this:
```
ABC AB
DEF -> CD
GHI EF
GH ("I" disappears)
```
now we are only interested in the last column (`BDFH`), so we use the idiom `⊢/`
`,` concatenates `BDFH` to the matrix we obtained before for the 2nd&3rd axis (`BDFH` and the matrix both happen to have a leading dimension of 4)
`∊` flattens everything we obtained so far into a single vector
`|` takes the absolute values
`{ }∩≢` filters only the threes - the length (≢) of the input is always 3
`≢` counts them
[Answer]
# JavaScript (ES6), ~~276~~ ~~228~~ ~~125~~ ~~117~~ 105 bytes
```
a=>btoa`i·yø!9%z)ª»-ºü1j;ÝÈ%¥·¡ªÜ"·ç¹Ê1`.replace(/.../g,b=>(a[b[0]]+a[b[1]]+a[b[2]])/3&1||'').length
```
(the above contains some unprintable ascii characters that won't show up here, so here's a version without the `btoa` that can be copied and run)
```
a=>'abcdefghijklmnopqrstuvwxajvdksglpbehqtwimrfnucox'.replace(/.../g,b=>(a[b[0]]+a[b[1]]+a[b[2]])/3&1||'').length
```
Breaks a reference string into letter triplets that match up with mill group keys. Input is in the form of an object, where keys are the letters `a-x`, starting from the bottom left and ending in the top right, moving left-to-right first. Values are `1` for white, `-1` for black, and `0` for blank.
### Example
```
{b:1,d:-1,e:1,f:-1,i:1,k:-1,l:-1,m:1,n:-1,r:1,u:-1} => 2
{j:1,d:-1,k:-1,l:-1,b:1,e:1,i:1,m:1,r:1,f:-1,n:-1,u:-1,o:1} => 2
{a:-1,j:-1,v:-1,k:-1,l:-1,h:1,e:1,b:1} => 3
{} => 0
{k:-1,j:-1,l:1} => 0
{k:-1,j:-1,l:1} => 1
{a:-1,j:-1,v:-1,d:-1,k:-1,s:-1,g:-1,l:-1,p:-1,i:1,m:1,r:1,f:1,n:1,u:1,c:1,o:1,x:1} => 8
```
These examples are taken from OP's examples, converted to the letter-key and number-value object. The first is from the example image, while the others are from the example set.
[Answer]
# Mathematica, ~~217~~ 131 Bytes
While I'm sure this is not particularly competitive, here's an entry for you.
```
Count[Total/@{{a1,d1,g1},{b2,d2,f2},{c3,d3,e3},{a4,b4,c4},{e4,f4,g4},{c5,d5,e5},{b6,d6,f6},{a7,d7,g7},{a1,a4,a7},{b2,b4,b6},{c3,c4,c5},{d1,d2,d3},{d5,d6,d7},{e3,e4,e5},{f2,f4,f6},{g1,g4,g7}}/.#/.{"w"->1,"b"->2},3|6]&
```
Input example:
```
{a4 -> "w", b2 -> "b", b4 -> "b", c4 -> "b", d1 -> "w", d2 -> "w", e3 -> "w", e4 -> "w", e5 -> "w", f2 -> "b", f4 -> "b", f6 -> "b", g4 -> "w"}
```
Allowing single-character coordinate names trivially golfs off 51 characters, making this a 166 byte solution. Naming the players 1 and 2 rather than "w" and "b" golfs off 17 further characters.
So we get
```
Count[Total/@{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,a,j,v,d,k,s,g,l,p,b,e,h,q,t,w,r,i,m,f,u,n,c,o,x}~Partition~3,3|6]/.#&
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 50 bytes
### "The Objects' Solution"
While longer (29 chars) than [@ngn's solution](https://codegolf.stackexchange.com/a/116352/43319), it uses an entirely different approach: The input has the same overall structure as that solution, but all slots are represented as objects. Empty slots (including the non-existing center column) must be empty objects. while all black men must be references to the "black man" object, and all white men must be references to the "white man" object. All the objects may optionally have nice [**D**isplay **F**orm](http://help.dyalog.com/15.0/Content/Language/System%20Functions/df.htm)s for readability, and so the center column can optionally be made invisible.
```
+/1=(≢¨(,∪/,∪⌿⍤2),(⊢/4 2⍴∪⌿))
```
[Try it online!](https://tio.run/nexus/apl-dyalog#@5/2qG2Ctr6hrcajzkWHVmjoPOpYpQ8iHvXsf9S7xEhTR@NR1yJ9EwWjR71bIMKamv//OwF1Vec96lqskQdkPeqb6hf8qHeNph6Q5eKmoH5ou3rtoRXGCkAI0ta7hsspWsNQwUjBSFPDCEIZg6lYoG5cxqgrqEO0GSoYa4J1gyljEAVkQwwxhhpSDjKkHIshj6b3q8NsNwRpNIToh/KMYKYZQihjsGlJINOSsJrWDTSNK03BCQA "APL (Dyalog Unicode) – TIO Nexus")
`+/` the sum of
`1=(`…`)` ones in
`≢¨(`…`)` the tallys of
`,` the raveled (flattened)
`∪/` unique sets across
`,` concatenated to
`∪⌿⍤2` unique sets down
`,(`…`)` concatenated to
`⊢/` the rightmost column of
`4 2⍴` the, reshaped into four rows and two columns,
`∪⌿` unique columnar sets
An *atop* operator, as supplied with AGL (`ä`), [would bring the length down to 27 characters](https://tio.run/nexus/apl-dyalog#e9Q31c0zQj0tMyfVSl9fP7@gRD8xPUff0d1HL6UyMSc/Xf1/2qO2Cdr6hrYaOo86VumDiEc9@x/1LjHSfNS56NCKw0t0TBSMHnUt0j@85FHvFoj0//9OQF3VeY@6FmvkAVmP@qb6BT/qXaOpB2S5uKkf2q5ee2iFsQIQgvT0ruFyitYwVDBSMNLUMIJQxmAqFqgZpykK6hBthgrGmmDdYMoYRAHZEEOMoYaUgwwpx2LIo@n96jDbDUEaDSH6oTwjmGmGEMoYbFoSyLQkrKZ1A03jSlNwAgA "APL (Dyalog Unicode) – TIO Nexus").
] |
[Question]
[
Consider a sequence based on recurrence relations, `f(n) = f(n-1)+f(n-2)`, starting with `f(1) = x1, f(2) = x2`. For `x1 = 2, x2 = 1`, the sequence begins like this:
```
2 1 3 4 7 11 18 29 47 76 123 199 322 521 843
```
Concatenating this into a string will give:
```
213471118294776123199322521843
```
Now, divide this list into the smallest possible numbers that gives `y(n) > y(n-1)`. Start with the first number, then the second etc. The first output number should always be a single digit. Pad the last number with the required number of zeros.
```
2 13 47 111 829 4776 12319 93225 218430
```
You will get two numbers, `(x1, x2)` as input, on any convenient format, and the challenge is to output the sorted list.
**Rules:**
* Function and programs are OK
* The initial sequence shall have exactly 15 numbers (The last number is `f(15)`).
* `x1` and `x2` are non-negative (zero is possible).
* The output can be on any convenient format
* The output vector `y` must be created so that `y2 > y1`.
+ First the smallest possible `y1`, then the smallest possible `y2`, then `y3` and so on.
* If `x1 = x2 = 0` then output 15 zeros (on the same format as other output, i.e. not `000000000000000`).
**Examples**:
```
Input: 1 1
Output: 1 12 35 81 321 345 589 1442 3337 7610
Input: 3 2
Output: 3 25 71 219 315 0811 3121 23435 55898 145300
|
Optional leading zero
Input: 0 0
Output: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
```
The shortest code in bytes wins. Please include a link to an online interpreter if possible.
[Answer]
# JavaScript ES6, 127 ~~135~~
```
(a,b)=>eval("for(n=r=[],v=13,o=a+n+b;v--;a=b,b=t)o+=t=b+a;for(d of o+'0'.repeat(99))(n+=d)>+v&&(r.push(v=n),n='');+v?r:[...o]")
```
**Test**
```
F=(a,b)=>eval("for(n=r=[],v=13,o=a+n+b;v--;a=b,b=t)o+=t=b+a;for(d of o+'0'.repeat(99))(n+=d)>+v&&(r.push(v=n),n='');+v?r:[...o]")
// less golfed
U=(a,b)=>{
for(n=r=[], o=a+n+b, v=13; v--; a=b, b=t)
o+= t= b+a;
for(d of o+'0'.repeat(99))
if ((n+=d) > +v)
r.push(v=n), n='';
return +v ? r : [...o]
}
function test(){
var i = I.value.match(/\d+/g)
O.textContent = i.length > 1 ? F(+i[0],+i[1]) : ''
}
test()
```
```
A,B : <input id=I value='0 1' oninput='test()'>
<pre id=O></pre>
```
[Answer]
## JavaScript ES6, ~~187~~ ~~180~~ ~~187~~ ~~184~~ ~~182~~ ~~179~~ ~~175~~ ~~172~~ ~~165~~ ~~160~~ ~~155~~ 154 bytes
```
(a,b)=>eval('d=""+a+b;for(i=-12,j=1;++i<99;)i<2?(c=b,d+=b=a+b,a=c,r=a?[d[0]]:"0,".repeat(15)):(f=+d.slice(j,i))>r[r.length-1]?(r.push(f),j=++i-1):d+=0;r')
```
I get similar results when run it for `1,1` and `3,2` test cases. `0,0` has taken an excess 26 bytes...
De-golf + converted to ES5 + demo:
```
function s(a, b) {
d = "" + a + b;
for (i = -12, j = 1; ++i < 99;)
i < 2 ?
(c = b, d += b = a + b, a = c, r = a ? [d[0]] : "0,".repeat(15))
: (f = +d.slice(j, i)) > r[r.length - 1] ?
(r.push(f), j = ++i - 1)
: d += 0;
return r
}
document.write(
s(1,1)+"<br>"+
s(3,2)+"<br>"+
s(0,0)
)
```
[Answer]
# Pyth, 56 bytes
```
LsgM.:sMb2?sQsM.WyHX_1Z`0u?yGX_1GHaGHjkhM.u,eNsN14QYmZ15
```
[Test suite](https://pyth.herokuapp.com/?code=LsgM.%3AsMb2%3FsQsM.WyHX_1Z%600u%3FyGX_1GHaGHjkhM.u%2CeNsN14QYmZ15&test_suite=1&test_suite_input=2%2C+1%0A1%2C+1%0A3%2C+2%0A0%2C+0&debug=0)
**Explanation:**
First, we check whether the input is precisely `0, 0`. If so, print 15 zeros.
Otherwise, we produce the sequence, with `jkhM.u,eNsN14Q`. This is similar to the standard Pyth algorithm for the Fibonacci sequence.
Next, we reduce over this string. The accumulator is a list of strings, representing each number in the divided sequence. At each reduction step, we take the next character, and check whether the accumulator is in order, using the helper function `y`, defined with `LsgM.:sMb2`, which is truthy iff the input is out of order. If it is in order, we append the next character to the list as its own number. If not, we add the next character to the end of last string. This is accomplished with `u?yGX_1GHaGH ... Y`.
Next, we perform a functional while loop. The loop continues until the running list is in order, reusing the helper function. At each step, a `0` is added to the end of the last string in the list. This is accomplished with `.WyHX_1Z`0`.
Finally, the strings are converted to integers, with `sM`, and printed.
---
# Pyth, 51 bytes
```
LsgM.:sMb2?sQsM.WyHX_1Z`0hf!yT_./jkhM.u,eNsN14QmZ15
```
I believe this works, but it is far too slow to test - it's a brute force solution for dividing the string.
---
I will be making some improvements to the `X` function, but the above code works in the version of Pyth that was most recent when the question was posted.
[Answer]
# JavaScript (ES6), 162 bytes
```
(a,b)=>(k=[...Array(15).keys(y="")],p=-1,z=k.map(_=>0),a|b?[...k.map(f=n=>n--?n?f(n)+f(n-1):b:a).join``,...z].map(d=>+(y+=d)>p?(p=y,y=" ",p):"").join``:z.join` `)
```
## Explanation
```
(a,b)=>(
k=[...Array(15).keys(y="")], // k = array of numbers 0 to 14, initialise y
p=-1, // initialise p to -1 so that 0 is greater than p
z=k.map(_=>0), // z = array of 15 zeroes
a|b?[ // if a and b are not 0
...k.map // for range 0 to 14
(f=n=>n--?n?f(n)+f(n-1):b:a) // recursive sequence function (0 indexed)
.join``, // join result of f(0) to f(14) as a string
...z // append zeroes for padding
].map(d=> // for each digit of concatenated result
+(y+=d) // append the digit to the current number y
>p?( // if the current number is greater than the previous p
p=y, // set previous to the current number
y=" ", // reset y (with space as a separator)
p // output the current number (with space at the start)
):"" // else add nothing to the output
)
.join`` // return the output as a string
:z.join` ` // return a bunch of zeroes if a and b are 0
)
```
## Test
```
var solution = (a,b)=>(k=[...Array(15).keys(y="")],p=-1,z=k.map(_=>0),a|b?[...k.map(f=n=>n--?n?f(n)+f(n-1):b:a).join``,...z].map(d=>+(y+=d)>p?(p=y,y=" ",p):"").join``:z.join` `)
```
```
x1 = <input type="number" id="x1" value="3" /><br />
x2 = <input type="number" id="x2" value="2" /><br />
<button onclick="result.textContent=solution(+x1.value,+x2.value)">Go</button>
<pre id="result"></pre>
```
[Answer]
# Mathematica, 192 bytes
```
f[{0,0}]:=0~Table~15
f@l_:=(t=0;q={};If[#>0,q~Join~{10^⌈Log10[t/#]⌉#},q]&[Last@#]&@FoldList[If[#>t,AppendTo[q,t=#];0,#]&[10#+#2]&,0,Flatten@IntegerDigits@SequenceFoldList[#+#2&,l,Range@13]])
```
Test cases:
```
f[{2, 1}]
(* {2, 13, 47, 111, 829, 4776, 12319, 93225, 218430} *)
f[{3, 2}]
(* {3, 25, 71, 219, 315, 811, 3121, 23435, 55898, 145300} *)
f[{0, 0}]
(* {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} *)
```
The lengths of the function names are killing me.
[Answer]
## Haskell, ~~165~~ ~~159~~ ~~152~~ ~~142~~ 141 bytes
```
w=take 15
x#y=x:scanl(+)y(x#y)
0%0=w[0,0..]
x%y=g(-1)(w(x#y)++0%0>>=show)(-1)
g _""_=[]
g b l@(h:t)a|b>a=b:g 0l b|1<2=g(max 0b*10+read[h])t a
```
Usage example: `3 % 2` -> `[3,25,71,219,315,811,3121,23435,55898,145300]`.
[Online demo](http://goo.gl/3kaQ7x) (with a `main` wrapper).
How it works:
```
w=take 15
x#y=x:scanl(+)y(x#y) -- fibonacci sequence generator for x and y
0%0=w[0,0..] -- special case 0%0
x%y=g(-1)(w(x#y)++0%0>>=show)(-1) -- calculate fib sequence, add some extra 0 and
-- flatten all digits into a single string.
-- start calculating the resulting sequence
g _""_=[] -- if we don't have digits left, stop.
-- the final 0 in the second parameter is ignored.
g b l@(h:t)a
|b>a=b:g 0l b -- if the current number is greater than the
-- previous one, take it and start over.
|1<2=g(max 0b*10+read[h])t a -- otherwise add the next digit and retry.
-- The "max" fixes the initial call with -1.
```
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), 61 bytes
```
(|/<':){@[x;t-1;(0^x t)+10*]_t:1+*&~0>':x}/.',/$13{x,+/-2#x}/
```
[Try it online!](https://tio.run/##Dci7CoAgFADQXxGKfOe9umlE/xHVZkPg5CBY/bp1xnPpdKbWome3majndVlLyBoDg72QzCWC2I7sUYrhhZn68piRKtOjq0VJo233T4uUIcHgiA1AgLcP "K (ngn/k) – Try It Online")
* `.',/$13{x,+/-2#x}/` builds the sequence, converting it into a list of (integer) digits
* `(|/<':)` is used as the while condition, causing iteration to continue so long as there is any number in the list smaller than its predecessor
* `t:1+*&~0>':x` identifies the index immediately after the first value less than or equal to its predecessor
* `@[x;t-1;(0^x t)+10*]` is used to merge numbers in the list together; e.g. `1 2` becomes `12 2`. Since indexing a list out of bounds returns a null, we zero-fill with `0^`. This handles the last iteration, where we may need to append additional 0's
* `@[...]_t` removes the "leftover" value at index `t` from the left-hand-side list (e.g. `12 2` becomes `12`)
[Answer]
## PowerShell, ~~167~~ 166 bytes
```
param($x,$w)if($w-lt($x-eq0)){"0`n"*15;exit}[char[]]("$x"+-join(0..13|%{$w;$w=$x+($x=$w)}))|%{$z+="$_";if(+$z-gt$y){($y=$z);$z=""}};if($z){while(+$z-lt$y){$z+="0"}$z}
```
Saved a byte by eliminating the `$s` variable and just feeding the output loop directly.
### Ungolfed and commented:
```
param($x,$w) # Take input parameters as x and w
if($w-lt($x-eq0)){ # If x=0, ($x-eq0)=1, so $w-lt1 implies w=0 as well
"0`n"*15 # Print out 15 0's separated by newlines
exit # And exit program
} # otherwise ...
[char[]]( # Construct the sequence string as a char-array
"$x"+-join( # Starting with x and concatenated with a joined array
0..13|%{ # Loop
$w # Add on w
$w=$x+($x=$w) # Recalculate for next loop iteration
}
))|%{ # Feed our sequence as a char-array into a loop
$z+="$_" # z is our output number, starts with the first digit
if(+$z-gt$y){ # If z is bigger than y (initialized to 0)
($y=$z) # Set y equal to z and print it
$z="" # Reset z to nothing to start building the next number
}
}
if($z){ # If there is remaining digits, we need to pad zeroes
while(+$z-lt$y){ # Until z is bigger than y
$z+="0" # Tack on a zero
}
$z # Print the final number
}
```
[Answer]
# [Perl 6](http://perl6.org), 107 bytes
```
{$_=@=(|@_,*+*...*)[^15].join.comb;.sum??[.shift,{last if !@$_;until (my$a~=.shift//0)>$^b {};$a}...*]!!$_} # 107
```
### Usage:
```
# give it a lexical name for ease of use
my &code = {...}
# use 「eager」 because the anonymous block returns a lazy array
# and 「say」 doesn't ask it to generate the values
say eager code 2, 1;
# [2 13 47 111 829 4776 12319 93225 218430]
say eager code 1, 1;
# [1 12 35 81 321 345 589 1442 3337 7610]
say eager code 3, 2;
# [3 25 71 219 315 0811 3121 23435 55898 145300]
say eager code 0, 0;
# [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
say eager code 0, 1;
# [0 1 12 35 81 321 345 589 1442 3337 7000]
```
### Explanation
creates a Fibonacci like sequence, starting with the arguments (`@_`) slipped (`|`) in
```
|@_,*+*...*
```
takes the first 15 elements of that sequence
```
(…)[^15]
```
combines that into a single string (`.join`), splits it into a sequence of individual characters (`.comb`) and stores that in the "default" scalar (`$_`) after coercing the sequence into a mutable array, by first storing it in an anonymous array (`@`)
```
$_=@=(…)[^15].join.comb;
```
it finds the sum of the values in the default scalar, and if that is zero returns the default scalar, which will contain an array of 15 zeros
```
.sum?? … !!$_
```
if the sum isn't zero, it creates a list by first shifting off the first element in the default scalar
```
.shift, …
```
followed by generating the rest of the values, checking it against the previous one (`$^b`)
if the default scalar runs out of values, use 0 instead (`//0`)
```
…,{ … ;until (my$a~=.shift//0)>$^b {};$a}...*
```
stopping when there is no elements left in the default scalar
```
…,{last if !@$_; … }...*
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 39 bytes
```
-.ị
ÇSṭƊ13¡DFŒṖḌ<ƝṖẠƊƇḢṪ×⁵ṭƲÇ>/$¿µṁS?15
```
[Try it online!](https://tio.run/##y0rNyan8/19X7@Hubq7D7cEPd6491mVofGihi9vRSQ93Tnu4o8fm2FwQY9eCY13H2h/uWPRw56rD0x81bgUp3XS43U5f5dD@Q0BeY7C9oen///@jjXQMYwE "Jelly – Try It Online")
This is unbelievably inefficient, both time-wise and memory-wise. You can see it in action for up to \$f(11)\$ on TIO, but it times out if you include up to \$f(15)\$. Luckily, the run time does not heavily depend on the input, so is generally constant. However, Python will usually error due to memory restrictions
## How it works
This works by generating all partitions of the digits of the sequence and keeping those which are strictly ascending, ignoring the last element. Due to the way Jelly generates the partitions of a list, this yields the intended array as the first such partition.
```
-.ị - Helper link. Takes an array, A, on the left
-. - Yield -0.5
ị - Take the -0.5th element of A, which returns the last 2 elements
ÇSṭƊ13¡DFŒṖḌ<ƝṖẠƊƇḢṪ×⁵ṭƲÇ>/$¿µṁS?15 - Main link. Takes [a,b] on the left
? - If statement:
S - Condition: sum (i.e. a ≠ 0, b ≠ 0)
µ - If:
Ɗ - Define a monad f(A):
Ç - Take the last two elements of A
S - Take their sum
ṭ - Tack the sum to the end of A
13¡ - Repeat f(A) 13 times, starting with A = [a, b]
D - Convert to digits
F - Flatten into an array, D
ŒṖ - Yield all partitions of D
Ḍ - Convert arrays back to decimals
Ɗ - Define a monad g(A):
Ɲ - Over overlapping pairs of A:
< - Is less than?
Ṗ - Remove the last
Ạ - All true?
Ƈ - Keep the partitions which are true under g(A)
Ḣ - Take the first one, P
¿ - While loop:
$ - Condition:
Ç - Last 2 elements of P
>/ - First is greater than the second
Ʋ - Body:
Ṫ - Last element of P
×⁵ - Times 10
ṭ - Tack to the end of P
ṁ 15 - Else: Repeat to length 15
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~53~~ 52 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
Ü⌐↓├¶cRU!>πf_╙ⁿεd╔╘≥↔IQ┘┼▐↓▒Φ╙ε☺ÉL╚Jö┤Å☺╠╓§j╨áuf░╢A╬
```
[Run and debug it](https://staxlang.xyz/#p=9aa919c314635255213ee3665fd3fcee64c9d4f21d4951d9c5de19b1e8d3ee01904cc84a94b48f01ccd6156ad0a07566b0b641ce&i=1,1%0A3,2%0A0,0%0A&m=2)
Not too well optimized, can probably be shortened a lot.
However, pretty proud that I managed to make it work for all the testcases.
It uses the X and Y registers to store previous values while comparing them in the loop, then pushes X to stack when the Y is greater than it.
] |
[Question]
[
# Challenge
Write a program/function that accepts an "image" and outputs a [picture maze](https://en.wikipedia.org/wiki/Picture_maze) formed from that image.
# Input
Your program should accept two arguments:
* I, the image to form the maze from
* S, a boolean specifying whether or not to display the solution to the maze
I is given in the following form:
```
.......
.#####.
.#####.
#######
.#####.
.#####.
.......
```
where `#`'s are cells to be included in the solution path and `.`'s are cells to be excluded.
You may swap out the `.`'s, `#`'s and newlines with any character of your choosing as long as they differ from each other.
Alternatively, you may accept an actual bitmap of the input image.
# Output
Your resulting maze should be in the following form:
```
###############
# #
# ### ####### #
# #.........# #
# #.#######.# #
# #.#.......# #
###.#.#########
....#.#........
#####.#.#######
# ...#..... #
# #.#######.# #
# #.........# #
# ####### ### #
# # # #
###############
```
where `#`'s denote walls, `.`'s denote portions of the path that are part of the solution, and spaces are paths excluded from the solution. The `.`'s may be replaced by spaces if S is false. Again, characters may be swaped with other characters of your choosing or you may output an actual bitmap of the maze with the solution highlighted.
# Additional Details
* Paths must be one cell wide (cannot have giant pool of empty space be the path)
* The maze must not contain any loops
* The maze must be fully connected (all cells must be reachable from the entrance/exit)
* The maze must be surrounded by walls (unless its an entrance/exit)
* The solution path must not include dead-ends
* There must be exactly 1 entrance and 1 exit for the maze
* The entrance and exit must be aligned to the edge of the grid and adjacent to a cell included in the solution path
* You may choose where the entrance and exit are placed
* You may assume that a valid path can be formed from the given input image
(Added for clarification) The diagram below shows how the solution path is correlated to the input image:
```
Input (I): | Output: | Corresponding Cells:
| | (@'s denote #'s from I)
| |
....... | ############### | ###############
.#####. | # # | # #
.#####. | # ### ####### # | # ### ####### #
####### | # #.........# # | # #@.@.@.@.@# #
.#####. | # #.#######.# # | # #.#######.# #
.#####. | # #.#.......# # | # #@#@.@.@.@# #
....... | ###.#.######### | ###.#.#########
| ....#.#........ | .@.@#@#@.@.@.@.
| #####.#.####### | #####.#.#######
| # ...#..... # | # @.@#@.@.@ #
| # #.#######.# # | # #.#######.# #
| # #.........# # | # #@.@.@.@.@# #
| # ####### ### # | # ####### ### #
| # # # # | # # # #
| ############### | ###############
| |
```
# Test Cases
Watering can example from [Wikipedia](https://en.wikipedia.org/wiki/Picture_maze):
Input:
```
..................
..................
.......####.......
......##..##......
.....##....##....#
.....#......#...##
.#############.##.
##..############..
#...###########...
#...##########....
#...##########....
#...##########....
#...##########....
....##########....
....##########....
....##########....
..................
..................
```
Output (S=false):
```
#####################################
# # # # # # #
# ### ### ### # # ##### ### ### ### #
# # # # # # # # # # #
# ### # ##### # ########### # ### # #
# # # # # # # # #
# # # ### ##### # ### ### # ### ### #
# # # # # # # # # # # # #
# ### # ##### ##### ### ##### # # ###
# # # # # # # # #
### ####### ### ### # ### ##### ### #
# # # # # # # # # # #
# ### ##### # ### ####### # # # # # #
# # # # # # # #
# # ##### ############# ### ### ### #
# # # # # # # # # #
# ### # ####### # ### ### # # ### # #
# # # # # # # # # #
# # # ### ######### # # ##### # #####
# # # # # # # # # # # #
# ##### # # ##### # ##### # # ### # #
# # # # # # # # # # #
# ### ### ### # ### # ##### ####### #
# # # # # # # # # #
# # # # ####### # ### # ##### # ### #
# # # # # # # # # # #
### # # # # # ############# # ### # #
# # # # # # # # # # #
##### # # ##### ####### # ### ##### #
# # # # # # # # #
##### # # # # ####### # ### #########
# # # # # #
# ### ######### ############# # #####
# # # # # # # # #
# # ######### # ####### ####### ### #
# # # #
#####################################
```
Output (S=true):
```
#####################################
# # # # # # #
# ### ### ### # # ##### ### ### ### #
# # # # # # # # # # #
# ### # ##### # ########### # ### # #
# # # #....... # # # # #
# # # ### #####.# ###.### # ### ### #
# # # # #...# # #...# # # # #
# ### # #####.##### ###.##### # # ###
# # # ...# # #... # # #..
### #######.### ### # ###.##### ###.#
# # #.# # # #.# # #...#
# ### #####.# ### #######.# # # #.# #
# #.......#.............#...# #...# #
# #.#####.#############.###.###.### #
#...# #.......#.....#...#.#...# # #
#.### # #######.#.###.###.#.#.### # #
#.# # # .......#...#.#...#...# #
#.# # ###.#########.#.#.##### # #####
#.# # #.#.......#.#...#...# # # #
#.##### #.#.#####.#.#####.#.# ### # #
#. #.#...#...#.#.....#.# # # #
#.### ###.###.#.###.#.#####.####### #
#. # # #.....#.#...#.#..... # #
#.# # # #######.#.###.#.##### # ### #
..# # # #...#...#.....#.....# # # #
### # # #.#.#.#############.# ### # #
# # # #.#...#.........#...# # # #
##### # #.#####.#######.#.### ##### #
# # #.#...#.......#.#...# #
##### # #.#.#.#######.#.###.#########
# # ...#.........#..... # #
# ### ######### ############# # #####
# # # # # # # # #
# # ######### # ####### ####### ### #
# # # #
#####################################
```
Bitmap example (same maze as above):
Input: [](https://i.stack.imgur.com/E45ky.png) Output (S=false): [](https://i.stack.imgur.com/Bj3wT.png) Output (S=true): [](https://i.stack.imgur.com/PgcuR.png)
[Answer]
# Python 3, 1491 Bytes
I found this to be a fun project and very interesting (and somewhat lengthy). When I saw this, I was reminded of the summer I spent exclusively writing and improving a maze generation algorithm and instantly got to work on this.
After a while, I had an initial draft around 6000 bytes long and I spent the next couple of hours condensing it into the following program:
```
import random;R=range;L=len;T=sorted;P=print;N=random.randint;d='#';A=abs
def M(I,S):
I=I.rsplit('\n');G=[[0]*(1+L(I[0])*2)for i in R(1+L(I)*2)]
for i in R(L(I)):*G[1::2][i][1::2],=I[i]
l=L(G[0])-2;c=E(G,l,-2);G[c][-1]=1;e=[c,l];c=E(G,1,2);G[c][:2]=1,1;s=[c,1]
while s!=e:
o=[];Q(G,s,e,-2,0,o,0);Q(G,s,e,0,2,o,1);Q(G,s,e,2,0,o,2);Q(G,s,e,0,-2,o,3);o=T(o,key=lambda x:(x[2],-x[1]))[0][0]
if o==0:G[s[0]-1][s[1]]=1;s[0]-=2
elif o==1:G[s[0]][s[1]+1]=1;s[1]+=2
elif o==2:G[s[0]+1][s[1]]=1;s[0]+=2
else:G[s[0]][s[1]-1]=1;s[1]-=2
G[s[0]][s[1]]=1
while 1 in['.'in x for x in G]:
r=N(1,L(I))*2-1;c=N(1,L(I[0]))*2-1
if G[r][c]in[1,2]:
o=[];F(G,r-2,c,o,0);F(G,r,c+2,o,1);F(G,r+2,c,o,2);F(G,r,c-2,o,3)
try:
if o[0]==0:G[r-1][c]=2;G[r-2][c]=2
elif o[0]==1:G[r][c+1]=2;G[r][c+2]=2
elif o[0]==2:G[r+1][c]=2;G[r+2][c]=2
else:G[r][c-1]=2;G[r][c-2]=2
except:0
*s,='# '
if S:s[1]='.'
for x in G:P(*[s[y]for y in x],sep='')
def Q(G,s,e,x,y,o,a,n=0):
c=lambda x,y:G[s[0]+x][s[1]+y]is d
try:
if c(x,y):
try:n+=c(2*x,2*y)
except:0
try:n+=c(x+A(x)-2,y+A(y)-2)
except:0
try:n+=c(x-A(x)+2,y-A(y)+2)
except:0
o+=[[a,((s[0]+x-e[0])**2+(s[1]+y-e[1])**2)**.5,n]]
except:0
def F(G,r,c,o,a):
try:
if G[r][c]is'.':o+=[a]
except:0
def E(G,y,z):
c=[]
for x in R(1,L(G)-1,2):
n=0
try:n+=G[x-2][y]==d
except:0
try:n+=G[x+2][y]==d
except:0
n+=G[x][y+z]==d
if G[x][y]==d:c+=[[x,n]]
if L(c)>1:c=T(c,key=lambda x:x[1])
return c[0][0]
```
Which is about as non-sensical to look at as an ascii-art maze is...
It's worth noting that, since the random function is not used until after the correct path has been found, no matter how many times the same input is given, the route from the start to the end will be the same and, while this program does work for the above examples, sometimes it will be unable to find a solution if it 'drives itself into a wall' so to speak.
When running the above examples, it gives this:
```
>>> M('''.......
.#####.
.#####.
#######
.#####.
.#####.
.......''',True)
###############
# # # # # #
# # # ### # # #
# #...#.....# #
# #.#.#.###.###
# .#.#.#...# #
###.#.#.#.### #
....#.#.#.#....
# ###.#.#.#.###
# #...#.#.#. #
# #.###.#.#.# #
# #.....#...# #
### ####### # #
# # # #
###############
>>>
```
this:
```
>>> M('''..................
..................
.......####.......
......##..##......
.....##....##....#
.....#......#...##
.#############.##.
##..############..
#...###########...
#...##########....
#...##########....
#...##########....
#...##########....
....##########....
....##########....
....##########....
..................
..................''',False)
#####################################
# # # # # # # # # # # # # #
# ### ##### # # # ### # ### # # # # #
# # # # # # # # # # # # # #
### # # ### # ### # # # ### # ### # #
# # # # # # # # # # # #
# ### ##### # # ##### ### # # # # # #
# # # # # # # # # # # # # #
# # # ##### # ##### ### # # # # # # #
# # # # # # # #
# # # # # # ##### # ### # ######### #
# # # # # # # # # # # # # # # #
# # ####### # ### # # ### # # # # # #
# # # # # # #
### ##### # # ######### ### ### ### #
# # # # # # # # # # #
# ### ### # # # # # # ####### ### # #
# # # # # # # # # # # # #
# ##### # # # # # # # # # # # ##### #
# # # # # # # # # # # # # #
# ####### # # # # # # # #############
# # # # # # # # # # #
# ####### # # # # # # ##### ##### # #
# # # # # # # # # # #
# ### ### # # # # # ######### ### ###
# # # # # # # # # #
# ### # # # # # # ######### ##### ###
# # # # # # # # # #
# # # ### # # # ################### #
# # # # # # # # # #
# ### # # # # ############# ### ### #
# # # # # # #
# # ##### # # # ##### # # ##### ### #
# # # # # # # # # # # #
### ##### # ### # # # ##### # ### # #
# # # # # # # # # # #
#####################################
>>>
```
and this:
```
>>> M('''..................
..................
.......####.......
......##..##......
.....##....##....#
.....#......#...##
.#############.##.
##..############..
#...###########...
#...##########....
#...##########....
#...##########....
#...##########....
....##########....
....##########....
....##########....
..................
..................''',True)
#####################################
# # # # # # # # # # # #
##### # # ### ### # # # # # # ### # #
# # # # # # # # # # # # # # # # #
# # # ### # # ##### # # # # # # # ###
# # # # # #.......# # # # #
### # ### # # #.#####.# # ####### # #
# # # # #...# #...# # # # #
### # ### # #.# # ### #.# ### ### # #
# # # # # #...# # # #... # # #..
# # # # # #.# ### #######.### ### #.#
# # # .# # # # # . # #...#
# # #######.##### # # ###.##### #.# #
# .......#.#...........#...# #...# #
###.# ###.#.#.#########.###.# #.### #
#...# # .#.#.#...#...#.....#... # #
#.#######.#.#.#.#.#.#.#######.#######
#. # .#.#.#.#.#.#.#...#...# #
#.#######.#.#.#.#.#.#.#.#.#.### #####
#. # .#.#.#.#.#.#.#.#... #
#.#######.#.#.#.#.#.#.#.#############
#. # #.#.#.#.#.#.#.#..... #
#.##### #.#.#.#.#.#.#.#####.#########
#. # .#.#.#.#.#.#....... # # #
#.# # ###.#.#.#.#.#.########### # ###
..# # # .#.#.#.#.#.........# # # #
# # #####.#.#.#.#.#########.# ### # #
# # # .#.#.#.#........... #
#########.#.#.#.############### #####
# # .#.#.#.............# # #
### # ###.#.#.#############.# ##### #
# # ...#............... # #
##### # # ### # # # # ### # # ##### #
# # # # # # # # # # # # #
####### # ### # # # ##### # ####### #
# # # # # # # # # #
#####################################
>>>
```
For anyone who'd like to try running this program themselves, use the command `M(Image, Show solution)`. I would recommend using the triple-quotes to input the image since otherwise there'll be a lot of back slashes or newline characters involved.
] |
[Question]
[
Let's plot a function *f(x) = sin(πx) + 0.5 sin(3πx)* over the domain *[-3,3]*. We can interpret this as a loose string lying on a board. Now let's drive *n* nails into the board at positions *(x1, y1)* to *(xn, yn)*, where the *xi ∈ (-3,3)* and *yi ∈ [-1,1]*. Imagine that there are two eyelets at the end of the string, that is at positions *(-3,0)* and *(3,0)*. We can now take the ends of string and pull the through the eyelets until the string is taut. This will deform our graph into a piecewise linear function.
Some pictures might help. Take 8 nails at *(-2.8, -0.7), (-2.5, -0.9), (-1.2, .2), (-0.5, .8), (0.5, .4), (1.2, -0.9), (1.5, -0.6), (1.8, -0.8)*. The following three plots show the process described above:

For larger version: Right-click --> Open in new tab
And here is an animation of the string tightening if you have some difficulty visualising it:

## The Challenge
Given a list of "nails" (which is not necessarily sorted), plot those nails and the taut string if it starts from the shape of the above function *f*.
You may write a program or function and take input via STDIN, ARGV or function argument. You can either display the result on the screen or save an image to a file.
If the result is rasterised, it needs to be at least 300 pixels wide and 100 pixels tall. The coordinate range from (-3,-1.1) to (3,1.1) must cover at least 75% of the horizontal and vertical extent of the image. The length scales of *x* and *y* do not have to be the same. You need to show the nails (using at least 3x3 pixels) and the string (at least 1 pixel wide). You may or may not include the axes.
Colours are your choice, but you need at least two distinguishable colours: one for the background and one for the nails and the string (those may have different colours though).
You may assume that all nails are at least 10-5 units away from *f* (so that you don't need to worry about floating-point inaccuracy).
This is code golf, so the shortest answer (in bytes) wins.
## More Examples
Here are two more (simpler) examples:
```
{{-2.5, 1}, {-1.5, -1}, {-0.5, 1}, {0.5, -1}, {1.5, 1}, {2.5, -1}}
```

(The string coincides with the *x*-axis.)
```
{{-2.7, -0.5}, {-2.3, -0.5}, {-1.7, 0.5}, {-1.3, 0.5}, {-0.7, -0.5}, {-0.3, -0.5}, {0.5, 1}, {1.5, -1}, {2.5, 1}}
```

## Want another Challenge?
[Here is Part II!](https://codegolf.stackexchange.com/q/38576/8478)
[Answer]
## Python ~~+ Pycairo~~, ~~727~~ ~~708~~ ~~608~~, + PyLab, 383
```
from pylab import*
def f(N):
def P(u,w,N):
T=lambda v,p:(C(v-u,p-u)>0)==(C(w-v,p-v)>0)==(C(u-w,p-w)>0);M=[(i,n)for i,n in enumerate(N)if T(V([n[0],sin(pi*n[0])+sin(3*pi*n[0])/2]),n)]
if M:i,n=max(M,key=lambda n:C(n[1]-u,w-u)**2);M=P(u,n,N[:i])+[n]+P(n,w,N[i+1:])
return M
V=array;C=cross;a=V([3,0]);plot(*zip(*([-a]+P(-a,a,map(V,sorted(N)))+[a])));N and scatter(*zip(*N));show()
```
**Example**
```
f([(-2.8,-0.7),(-2.5,-0.9),(-1.2,0.2),(-0.5,0.8),(0.5,0.4),(1.2,-0.9),(1.5, -0.6),(1.8, -0.8)])
```

**How it works**
>
> Suppose we know that the taut string passes through two points *A* and
> *B* (we can always start with
> *A = (-3, 0)* and *B = (3, 0)*.) As we pull the string, it "wants" to take the shortest path possible between
> *A* and *B*, that is, ideally, the segment *AB*. However, if there are any nails in the area bounded by the function (*sin πx + ...*)
> and *AB*, then at least one of them must block the string. In
> particular, the nail(s) farthest away from *AB* within the said area
> must block the string. Hence, if *C* is this nail, we know that the
> taut string must pass through *C*, in addition to *A* and *B*. We can
> now repeat the process for the segments *AC* and *CB*, and continue in
> this fashion until eventually there are no more intervening nails.
> 
>
>
>
> This is a binary divide-and-conquer algorithm with a linear scan in
> each step, so it has a best-case complexity of *O(n log n)* and
> worst-case complexity of *O(n2)*.
>
>
>
[Answer]
# Python + pylab, 576 bytes
### Algorithm:
>
> I interpreted the problem as finding the shortest path from *(-3, 0)* to *(3, 0)* such that a vertical line segment connecting a point on the path to a point on *f(x)* never crosses a nail.
>
>
>
> At each *x* where exists at least one nail, find the least upper bound
> and greatest lower bound given by the nails at that *x*. Consider the
> points given by these bounds plus the starting and ending points to be
> the vertices on a graph. Add an edge with weight given by the
> Euclidean distance between two vertices iff the line segment between
> them falls within the upper and lower bounds for each intervening x
> coordinate. Find the shortest path on this graph.
>
>
>
### Example with 27 random points:
```
(-0.367534, -0.722751), (-0.710649, -0.701412), (1.593101, -0.484983), (1.771199, 0.681435), (-1.878764, -0.491436), (-0.061414, 0.628570), (-0.326483, -0.512950), (0.877878, 0.858527), (1.256189, -0.300032), (1.528120, -0.606809), (-1.343850, -0.497832), (1.078216, 0.232089), (0.930588, -0.053422), (-2.024330, -0.296681), (-2.286014, 0.661657), (-0.009816, 0.170528), (2.758464, 0.099447), (-0.957686, 0.834387), (0.511607, -0.428322), (-1.657128, 0.514400), (1.507602, 0.507458), (-1.469429, -0.239108), (0.035742, 0.135643), (1.194460, -0.848291), (2.345420, -0.892100), (2.755749, 0.061595), (0.283293, 0.558334),
```

**Golfed**
What appears as several spaces of indentation in the `for j in R(i&~1)` loop should actually be a tab.
```
from pylab import*
P=((3,0),(-3,0))+input()
X=sorted(set(zip(*P)[0]))
l=len(X)*2
if l>4:scatter(*zip(*P[2:]))
f=lambda x:sin(pi*x)+sin(3*pi*x)/2
B=[[max([-9]+[p[1]for p in P if x==p[0]and p[1]<f(x)]),min([9]+[p[1]for p in P if x==p[0]and p[1]>f(x)])]for x in X]
b=zeros(l);b[2:]=inf
v=list(b)
R=range
for i in R(l):
for j in R(i&~1):
A=B[j/2][j&1];D,d=B[i/2][i&1]-A,X[i/2]-X[j/2];K=1;c=b[j]+norm((d,D))
for k in R(j/2+1,i/2):C=A+D/d*(X[k]-X[j/2]);K&=C<B[k][1];K&=C>B[k][0]
if(c<b[i])&K:b[i]=c;v[i]=j,(X[j/2],A)
l-=2
s=P[:1]
while l/2:l,p=v[l];s+=(p,)
plot(*zip(*s))
show()
```
**Ungolfed**
```
from pylab import*
P = input()
Xn,Yn = zip(*P)
X = set(Xn+(3,-3))
f = lambda x:sin(pi*x)+sin(3*pi*x)/2
ylb = {x: max([-9]+[p[1] for p in P if p[0] == x and p[1] < f(x)]) for x in X}
yub = {x: min([9]+[p[1] for p in P if p[0] == x and p[1] > f(x)]) for x in X}
ylb[-3] = yub[3] = ylb[3] = 0
X = sorted(X)
l = len(X)
best = zeros((l,2))
best[1:] = inf
prev = [ [0,0] for i in range(l) ]
for i in range(l): # calculate min path to X[i] lb or ub
for ib in 0,1:
for j in range(i): # point to come from
for jb in 0,1:
Y2, Y1 = (ylb, yub)[ib][X[i]], (ylb, yub)[jb][X[j]]
dy,dx = Y2 - Y1, X[i] - X[j]
if all([Y1 + dy/dx*(x - X[j]) < yub[x] and Y1 + dy/dx*(x - X[j]) > ylb[x] for x in X[j+1:i]]):
c = best[j][jb] + (dy**2+dx**2)**.5
if c < best[i][ib]:
best[i][ib] = c
prev[i][ib] = j, jb, (X[j], Y1)
j, jb = l-1,0
pts = [(3,0)]
while j:
j, jb, p = prev[j][jb]
pts += [p]
plot(*zip(*pts))
scatter(Xn,Yn)
show()
```
] |
[Question]
[
**Goal:**
Write a function that takes a number as input and returns a short-hand roman numeral for that number as output.
**Roman Numeral Symbols:**
```
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1,000
```
For an example of what I mean when I say "short-hand roman numerals", let's consider finding a roman numeral to represent 1983, because that is the year I was born. One option is to do this the normal way (10 letters):
**1983** = **MCMLXXXIII** = (1000 - 100 + 1000 + 50 + 30 + 3)
The other option is to do it the short-hand way (6 characters):
**1983** = **MXVIIM** = (1000 - (10 + 10) + 1000 + 3)
Do you know what this means?!?!!?? If I was roman I could have saved 4 characters every single time I wrote my birth date! Woot Woot!!
However, before I get ahead of myself in excitement, I have a question to write, so I should probably define the short-hand roman numeral rules so we are all on the same page:
**Short-Hand Roman Numeral Rules:**
1. Always consider symbols from left to right until there are no more characters to consider.
2. If there are no higher-valued symbols to the right of the current symbol:
* Add the value of the current symbol to the running total of this roman numeral.
3. If there are higher-valued symbols to the right of the symbol you are considering:
* Locate the rightmost highest-valued symbol to the right of the current symbol
* Consider all the characters up to that symbol as one roman numeral
* Calculate the value of that roman numeral using these steps
* Subtract the value of that roman numeral from the running total of this roman numeral.
* Move to the next symbol after the group you just considered
4. Each roman numeral must have at least 1 symbol in it.
5. That's it! Anything following these rules will be accepted!
**Examples:**
```
IIIIV = (-(1+1+1+1)+5) = 1 //Don't ask me why you'd want to do this!
VVX = (-(5+5) + 10) = 0 //Who said you couldn't represent 0 with roman numerals?!!?
VVXM = (-(-(5+5) + 10) + 1000) = 1000 //Again...don't ask me why you'd want to do this!
MXIIXMI = (1000-(10-(1+1)+10)+1000+1) = 1983 //Ahhh...such a great year :)
```
**Question Rules:**
1. Make a function that takes a single number as input and returns a roman numeral for that number as output using the above rules. Calculate the **codeGolfScore** of this function.
```
example input: 2011
example possible output: MMXI
another possible output: MMVVIVV //(2000 + 10 - 4 + 5)
```
2. Using your function from rule 1, generate the roman numerals between -1000 (that's right, NEGATIVE one-thousand) and 3000. Then sum up the character length of these roman numerals to get your **totalCharacterCount**. Here's some pseudocode to clarify:
```
totalCharacterCount = 0;
for(currentNumber = -1000; currentNumber <= 3000; currentNumber++){
totalCharacterCount += getRomanNumeral(currentNumber).length;
}
return totalCharacterCount;
```
3. **finalScore** = **codeGolfScore** + **totalCharacterCount**
4. Lowest **finalScore** wins!
Note: As the totalCharacter count will be in the ten-thousands+, the character-length algorithm should be top priority. Code-golf scores are just the tie-breaker in case multiple users find the optimal algorithm or algorithms that are close to each other.
Good luck, and have fun at your MMXII celebrations tomorrow night!!!
[Answer]
## Haskell, 25637 (= 268 + 25369) 26045 (= 222+25823)
```
r 0="VVX"
r n=s(zip[1000,500,100,50,10,5]"MDCLXV")n ξ
ξ='ξ'
s[]q f
|q<0=s[](5-q)f++"V"
|q<1=""
|r<-q-1='I':s[]r f
s ω@((v,a):l)q f
|q>=v,f/=a=a:s ω(q-v)ξ
|f==a,γ<-'I':a:s l(q-v+1)ξ,η γ<η(s l q ξ)=γ
|f==ξ,γ<-s ω(v-q)a++[a],η γ<η(s l q ξ)=γ
|True=s l q ξ
η=length
```
to be used as e.g.
```
GHCi> r 7
"VII"
GHCi> r 39
"XIL"
GHCi> r (-39)
"ICXLC" -- "LLXILC" in my original version
GHCi> r 1983
"MXVIIM"
GHCi> r 259876
"MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMCXXIVM"
```
You can evaluate the length sum with the straightforward
```
GHCi> sum . map(length.r) $ [-1000..3000]
25369
```
Which takes something in the order of a minute.
[Answer]
## C++, 345 characters of code, 25021 roman numeral digits = 25366
```
int N[]={1,5,10,50,100,500,1000};int V(int s,int L){if(!L)return 0;int K=0,B,m=s%7+1;for(int k=1,b=7;k<L;k++,b*=7){if(s/b%7>=m){K=k;B=b;m=s/b%7;}}return K?V(s/B,L-K)-V(s%B,K):N[s%7]+V(s/7,L-1);}char r[99];char*f(int n){for(int L=1,B=7,i,j;1;L++,B*=7){for(i=0;i<B;i++){if(V(i,L)==n){for(j=0;j<L;j++){r[j]="IVXLCDM"[i%7];i/=7;}r[L]=0;return r;}}}}
```
deobfuscated a bit, with a driver:
```
int N[]={1,5,10,50,100,500,1000};
int V(int s,int L){
if(!L)return 0;
int K=0,B,m=s%7+1;
for (int k=1,b=7;k<L;k++,b*=7) {
if(s/b%7>=m){K=k;B=b;m=s/b%7;}
}
return K ? V(s/B,L-K)-V(s%B,K) : N[s%7]+V(s/7,L-1);
}
char r[99];
char *f(int n){
for(int L=1,B=7;1;L++,B*=7) {
for(int i=0;i<B;i++) {
if(V(i,L)==n){
for(int j=0;j<L;j++) {
r[j]="IVXLCDM"[i%7];i/=7;
}
r[L]=0;
return r;
}
}
}
}
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
printf("%s\n", f(atoi(argv[1])));
}
```
`V` computes the numerical value of a given roman numeral string `s` of length `L`. Strings are encoded base 7 (first digit is s%7, second digit is s/7%7, ...). Each digit is encoded with I=0, V=1, ..., M=6. `f` does a brute-force enumeration of possible roman numeral strings to find one that `V` evaluates to `n`.
The total number of roman numeral digits is optimal. The longest roman numeral needed for [-1000,3000] is 11 digits (e.g. -827=CMDDMLXXIII), which takes about 5 minutes on my machine.
[Answer]
## Ruby, 25987 (= 164 + 25823)
```
h=->i,d,v,k{i==0?'':i<v ?(a=h[v-i,x=d[1..-1],v/k,k^7]+d[0];i<0?a:(b=h[i,x,v/k,k^7];a.size<b.size ? a :b)):d[0]+h[i-v,d,v,k]}
r=->i{i==0?'DDM':h[i,'MDCLXVI',1000,2]}
```
You can call `r` directly to get the results. The sum over the specified range yields
```
> (-1000..3000).map{|i|r[i].size}.reduce &:+
25823
```
which is the optimal sum as with the other solutions.
[Answer]
# C# 23537 (639 characters of code + 22898 characters of output)
```
class M
{
public static string R(int n, int? s = new int?())
{
var r = "";
var D = new Dictionary<int, string> {{ 1000, "M"}, { 900, "CM"},{ 800, "CCM"},{ 500, "D"}, { 400, "CD"},{ 300, "CCD"},{100, "C"}, {90, "XC"},{80, "XXC"},{50, "L"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {8, "IIX"}, {5, "V"}, {4, "IV"},{1, "I"}};
if (n == 0) return "VVX";
if (n == -1) return "IIIIIIV";
if (n < 0) return N(n * -1);
foreach(int k in D.Keys)
{
if (s.HasValue && k > s) continue;
while(k <= n)
{
n -= k;
r += D[k];
}
}
return r;
}
public static string N(int n)
{
var D = new Dictionary<int, string> {{1, "I"}, {5, "V"}, {10, "X"}, {50, "L"}, {100, "C"}, { 500, "D"}, {1000, "M"}};
int i = D.Keys.First(v => v >= n), m = D.Keys.Where(v => v < i).Max();
return R(n + i, m) + D[i];
}
}
```
To Calculate:
`Enumerable.Range(-1000, 3000).Sum(i => M.R(i).Length);`
] |
[Question]
[
Given two positive integers X and Y, output any combination of the following three ASCII-art animals such that the output contains exactly X commas (`,`) and Y periods (`.`), if it is possible.
1. **Koala:** 1 comma, 2 periods
```
<.,.>
```
2. **Crab:** 2 commas, 2 periods
```
,<..>,
```
3. **Commapillar:** 3 or more commas, 1 period
```
<,,,.>
```
or `<,,,,.>` or `<,,,,,.>` or `<,,,,,,.>` or `<,,,,,,,.>` etc.
If no combination of these animals can produce exactly X commas and Y periods, output a single commaleon who will camouflage the failure:
```
~<.,,>~~
```
The output animals can be in any amounts and any order. They may be in a string, space or newline separated, or else in a list where each animal is one element.
For example, for X = 7, Y = 5, these would all be valid outputs (separated by empty lines):
```
<.,.> <.,.> <,,,,,.>
<.,.>
<,,,,,.>
<.,.>
,<..>, <.,.> <,,,,.>
<,,,,.>
,<..>,
<.,.>
,<..>, <,,,.> ,<..>,
[",<..>,", ",<..>,", "<,,,.>"] (list syntax depends on language)
```
Note that (at least in this example) there are multiple sets of animals than can work. But remember you only need to output any *one* valid solution, if one exists. The number of animals or number of distinct animals does not matter.
For inputs such as X = 3, Y = 3 or X = 1, Y = 5 where there is no solution, the output will always be
```
~<.,,>~~
```
perhaps in a single-element list.
**The shortest code in bytes wins.**
[Answer]
# Ruby, 139 bytes
Lambda function, takes x and y as arguments and returns a string
```
->x,y{c=y-2*n=y-(x>y ?1:0)>>1
x+=-c/2*s=[x-n,c*3].max
x<n||x>n*2?'~<.,,>~~':',<..>, '*(x-n)+'<.,.> '*(2*n-x)+"<%s.> "*c%[?,*s-=c/2*3,?,*3]}
```
If a solution exists, it can be done with all koalas+commapillars or all koalas+crabs.
The principle is to use a minimum of commapillars. If the number is odd, we use 1 commapillar. if even we use 0 commapillars, unless there are more commas than periods, in which case we use 2.
The number of periods used in noncommapillars (crabs + koalas) is necessarily even, and the number of noncommapillars is half `(number of periods)-(number of commapillars)`. If there are insufficient commas for all koalas, or too many for all crabs, no solution is possible. Otherwise, we return a solution.
**Commented in test program**
uses "fail" instead of chameleon for clarity
```
f=->x,y{c=y-2*n=y-(x>y ?1:0)>>1
#n=noncommapillars=y>>1 as they have 2 periods. c=commapillars=y-2*n, 1 for odd y, 0 for even y.
#if x>y there are too many commas to have 0 commapillars for even y. noncommapillars= y-1 >> 1, so 2 commapillars
x+=-c/2*s=[x-n,c*3].max
# s=number of commas allocated to commapillars. x-n to allow all noncommapillars to be koalas, but at least 3 per commapillar.
#-c/2 == -1 if there are commapillars, 0 if not (Ruby truncates toward -inf). Subtract commas for commapillars from x if necessary
x<n||x>n*2?'fail':',<..>, '*(x-n)+'<.,.> '*(2*n-x)+"<%s.> "*c%[?,*s-=c/2*3,?,*3]}
#if x<n (insufficient commas for all koalas) or x>n*2 (too many for all crabs) return fail. Else...
#return string off crabs, koalas, and (using % operator like sprintf) c commapillars (0..2), the second with 3 commas (if present) and the first with the rest.
10.times{|j|10.times{|i|puts "%-20s %s"%[?.*j+?,*i,f[i,j]]}}
#all x,y from 0..9
```
**Output**
```
, fail
,, fail
,,, fail
,,,, fail
,,,,, fail
,,,,,, fail
,,,,,,, fail
,,,,,,,, fail
,,,,,,,,, fail
. fail
., fail
.,, fail
.,,, <,,,.>
.,,,, <,,,,.>
.,,,,, <,,,,,.>
.,,,,,, <,,,,,,.>
.,,,,,,, <,,,,,,,.>
.,,,,,,,, <,,,,,,,,.>
.,,,,,,,,, <,,,,,,,,,.>
.. fail
.., <.,.>
..,, ,<..>,
..,,, fail
..,,,, fail
..,,,,, fail
..,,,,,, <,,,.> <,,,.>
..,,,,,,, <,,,,.> <,,,.>
..,,,,,,,, <,,,,,.> <,,,.>
..,,,,,,,,, <,,,,,,.> <,,,.>
... fail
..., fail
...,, fail
...,,, fail
...,,,, <.,.> <,,,.>
...,,,,, <.,.> <,,,,.>
...,,,,,, <.,.> <,,,,,.>
...,,,,,,, <.,.> <,,,,,,.>
...,,,,,,,, <.,.> <,,,,,,,.>
...,,,,,,,,, <.,.> <,,,,,,,,.>
.... fail
...., fail
....,, <.,.> <.,.>
....,,, ,<..>, <.,.>
....,,,, ,<..>, ,<..>,
....,,,,, fail
....,,,,,, fail
....,,,,,,, <.,.> <,,,.> <,,,.>
....,,,,,,,, <.,.> <,,,,.> <,,,.>
....,,,,,,,,, <.,.> <,,,,,.> <,,,.>
..... fail
....., fail
.....,, fail
.....,,, fail
.....,,,, fail
.....,,,,, <.,.> <.,.> <,,,.>
.....,,,,,, <.,.> <.,.> <,,,,.>
.....,,,,,,, <.,.> <.,.> <,,,,,.>
.....,,,,,,,, <.,.> <.,.> <,,,,,,.>
.....,,,,,,,,, <.,.> <.,.> <,,,,,,,.>
...... fail
......, fail
......,, fail
......,,, <.,.> <.,.> <.,.>
......,,,, ,<..>, <.,.> <.,.>
......,,,,, ,<..>, ,<..>, <.,.>
......,,,,,, ,<..>, ,<..>, ,<..>,
......,,,,,,, fail
......,,,,,,,, <.,.> <.,.> <,,,.> <,,,.>
......,,,,,,,,, <.,.> <.,.> <,,,,.> <,,,.>
....... fail
......., fail
.......,, fail
.......,,, fail
.......,,,, fail
.......,,,,, fail
.......,,,,,, <.,.> <.,.> <.,.> <,,,.>
.......,,,,,,, <.,.> <.,.> <.,.> <,,,,.>
.......,,,,,,,, <.,.> <.,.> <.,.> <,,,,,.>
.......,,,,,,,,, <.,.> <.,.> <.,.> <,,,,,,.>
........ fail
........, fail
........,, fail
........,,, fail
........,,,, <.,.> <.,.> <.,.> <.,.>
........,,,,, ,<..>, <.,.> <.,.> <.,.>
........,,,,,, ,<..>, ,<..>, <.,.> <.,.>
........,,,,,,, ,<..>, ,<..>, ,<..>, <.,.>
........,,,,,,,, ,<..>, ,<..>, ,<..>, ,<..>,
........,,,,,,,,, <.,.> <.,.> <.,.> <,,,.> <,,,.>
......... fail
........., fail
.........,, fail
.........,,, fail
.........,,,, fail
.........,,,,, fail
.........,,,,,, fail
.........,,,,,,, <.,.> <.,.> <.,.> <.,.> <,,,.>
.........,,,,,,,, <.,.> <.,.> <.,.> <.,.> <,,,,.>
.........,,,,,,,,, <.,.> <.,.> <.,.> <.,.> <,,,,,.>
```
[Answer]
## Befunge, ~~249~~ 218 bytes
```
&::00p&::00g\`-2/:20p2*-3*:30p\20g-`:!00g20g-*\30g*+:30g-v>:#,_@
"~<.,,>~~"0_v#\g03+`g050`\0:-g02\p05:-\*2g02:-*/6+3g03p04<^
$"<">:#,_40p>:!#|_3-0" >.,,"40g3>3g#<\#-:#1_
0" ,>..<,">:#,_$>:!#|_1-
#@_1-0" >.,.<">:#,_$>:!
```
[Try it online!](http://befunge.tryitonline.net/#code=Jjo6MDBwJjo6MDBnXGAtMi86MjBwMiotMyo6MzBwXDIwZy1gOiEwMGcyMGctKlwzMGcqKzozMGctdj46IyxfQAoifjwuLCw-fn4iMF92I1xnMDMrYGcwNTBgXDA6LWcwMlxwMDU6LVwqMmcwMjotKi82KzNnMDNwMDQ8XgokIjwiPjojLF80MHA-OiEjfF8zLTAiID4uLCwiNDBnMz4zZyM8XCMtOiMxXwowIiAsPi4uPCwiPjojLF8kPjohI3xfMS0KI0BfMS0wIiA-LiwuPCI-OiMsXyQ-OiE&input=NyA1)
This is now based on the algorithm in the [Ruby answer](/a/101217/62101) by [Level River St](/users/15599/level-river-st), which provided greater scope for golfing and a significant reduction in size compared to my original solution.
[Answer]
## C#6, ~~321~~ 303 bytes
```
using System.Linq;string F(int x,int y)=>S(x,y)??"~<.,,>~~";string S(int x,int y)=>x<0|y<0?null:y<1?x<1?"":null:y*3>x?S(x-1,y-2)!=null?S(x-1,y-2)+"<.,.> ":S(x-2,y-2)!=null?S(x-2,y-2)+",<..>, ":null:string.Concat(new int[y].Select((_,k)=>k<1?C(x-y*3+3):C(3)));string C(int x)=>$"<{new string(',',x)}.> ";
```
Call `F()`. The other two functions are helpers. [repl.it demo](https://repl.it/E8ME/1)
```
// Coalesce failed combinations with commaleon
string F(int x,int y)=>S(x,y)??"~<.,,>~~";
// Get successful combination or null
string S(int x,int y)=>
x<0|y<0
// Fail: Out of range
?null
:y<1
?x<1
// Successful: All commas and periods accounted for
?""
// Fail: Not enough periods for commas
:null
:y*3>x
// Not all commapillars
?S(x-1,y-2)!=null
// Try koala
?S(x-1,y-2)+"<.,.> "
// Try crab
:S(x-2,y-2)!=null
?S(x-2,y-2)+",<..>, "
// Epic fail
:null
// All commapillars
:string.Concat(new int[y].Select((_,k)=>k<1
// This commapillar takes most of commas
?C(x-y*3+3)
// The rest each takes 3
:C(3)));
// Generate single commapillar
string C(int x)=>$"<{new string(',',x)}.> ";
```
] |
[Question]
[
Recently, I have found a bijective mapping \$f\$ from positive integers to finite, nested sequences. The purpose of this challenge is to implement it in the language of your choice.
## The Mapping
Consider a number \$n\$ with the factors \$2^{a\_1}3^{a\_2}5^{a\_3}\cdots p^{a\_i}\$ where \$a\_i > 0\$
$$f(n) = \{f(a\_2+1),f(a\_3+1),\cdots,f(a\_i+1),\underbrace{\{\},\{\},\cdots,\{\}}\_{a\_1}\}$$
For example:
$$\begin{align} f(22308) & = \{f(2),f(1),f(1),f(2),f(3),\{\},\{\}\} \\
& = \{\{\{\}\},\{\},\{\},\{\{\}\},\{f(2)\},\{\},\{\}\} \\
& = \{\{\{\}\},\{\},\{\},\{\{\}\},\{\{\{\}\}\},\{\},\{\}\}
\end{align}$$
## Rules
* You may write a full program or a function to do this task.
* Output can be in any format recognisable as a sequence.
* Built-ins for prime factorization, primality testing, etc. are **allowed**.
* Standard loopholes are disallowed.
* Your program must complete the last test case in under 10 minutes on my machine.
* This is code-golf, so the shortest code wins!
## Test Cases
* `10`: `{{},{{}},{}}`
* `21`: `{{{}},{},{{}}}`
* `42`: `{{{}},{},{{}},{}}`
* `30030`: `{{{}},{{}},{{}},{{}},{{}},{}}`
* `44100`: `{{{{}}},{{{}}},{{{}}},{},{}}`
* `16777215`: `{{{{}}},{{}},{{}},{},{{}},{{}},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{{}}}`
* `16777213`: [pastebin](http://pastebin.com/28MmezyT)
[Answer]
# CJam, ~~51~~ ~~48~~ ~~44~~ ~~42~~ ~~41~~ ~~39~~ ~~34~~ ~~33~~ 31 bytes
```
{mf_W=)1|{mp},\fe=(0a*+{)J}%}:J
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=ri%0A%20%20%7Bmf_W%3D)1%7C%7Bmp%7D%2C%5Cfe%3D(0a*%2B%7B)J%7D%25%7D%3AJ%0A~%60&input=16777215).
*Thanks to @MartinBüttner for golfing off 3 bytes!*
*Thanks to @PeterTaylor for golfing off 3 bytes and paving the way for 1 more!*
At least on my computer, downloading the file takes longer than running the program...
### I/O
This is a named function that pops and integer from STDIN and pushes an array in return.
Since CJam does not distinguish between empty arrays and empty strings – a string is simply a list that contains only characters –, the string representation will look like this:
```
[[""] "" [""] ""]
```
referring to the following, nested array
```
[[[]] [] [[]] []]
```
### Verification
```
$ wget -q pastebin.com/raw.php?i=28MmezyT -O test.ver
$ cat prime-mapping.cjam
ri
{mf_W=)1|{mp},\fe=(0a*+{)J}%}:J
~`
$ time cjam prime-mapping.cjam <<< 16777213 > test.out
real 0m25.116s
user 0m23.217s
sys 0m4.922s
$ diff -s <(sed 's/ //g;s/""/{}/g;y/[]/{}/' < test.out) <(tr -d , < test.ver)
Files /dev/fd/63 and /dev/fd/62 are identical
```
### How it works
```
{ }:J Define a function (named block) J.
mf Push the array of prime factors, with repeats.
_W= Push a copy and extract the last, highest prime.
)1| Increment and OR with 1.
{mp}, Push the array of primes below that integer.
If 1 is the highest prime factor, this pushes
[2], since (1 + 1) | 1 = 2 | 1 = 3.
If 2 is the highest prime factor, this pushes
[2], since (2 + 1) | 1 = 3 | 1 = 3.
If p > 2 is the highest prime factor, it pushes
[2 ... p], since (p + 1) | 1 = p + 2, where p + 1
is even and, therefor, not a prime.
\fe= Count the number of occurrences of each prime
in the factorization.
This pushes [0] for input 1.
( Shift out the first count.
0a* Push a array of that many 0's.
+ Append it to the exponents.
This pushes [] for input 1.
{ }% Map; for each element in the resulting array:
Increment and call J.
```
[Answer]
# Mathematica, 88 bytes
```
f@1={};f@n_:=f/@Join[1+{##2},1&~Array~#]&@@SparseArray[PrimePi@#->#2&@@@FactorInteger@n]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
ÆEµ“”WẋḢ;@‘߀$
```
[Try it online!](https://tio.run/##y0rNyan8//9wm@uhrY8a5jxqmBv@cFf3wx2LrB0eNcw4PP9R0xqV/4fbgdTRSQ93zgDSkWCF0bFAoroWqB6o29BAR8HIUEfBxAhIGxkbWOgoGBsYGANFTUwMDYCUoZm5ubmRoSkA "Jelly – Try It Online")
The last test case times out on TIO. The Footer runs the program over the inputs, gets their raw form (Jelly doesn't display empty lists well) and replaces the `[]` with `{}`
## How it works
```
ÆEµ“”WẋḢ;@‘߀$ - Main link. Takes n on the left
ÆE - Compute the prime exponents of n
µ - Begin a new link with the exponents E as the argument
“” - []
W - [[]]
Ḣ - Take the first exponent, a
ẋ - Repeat each element of [[]] a times
$ - Group the previous 2 links as a monad f(E):
‘ - Increment each exponent
€ - Over each:
ß - Recursively run the main link
;@ - Append the [[]] to the recursive call result
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÓćÅ0«ε¯sF¸
```
Output with `[]` instead of `{}`.
[Try it online](https://tio.run/##ASAA3/9vc2FiaWX//8OTxIfDhTDCq861wq9zRsK4//8yMjMwOA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w5OPtB9uNTi0@tzWQ@uL3Q7t@F9bq/M/2sjI2MBCx9BAx8hQx8RIx9jAwNhAx8TE0MBAx9DM3NzcyNAUKGtgqQOU0zHVMdcxNNQxNI4FAA), where test case `16777213` is replaced with `1009` (another prime number) - the output for `16777213` would be similar, just with *a lot* more leading `[],` ..
**Explanation:**
```
Ó # Get the exponents of the prime factorization of the (implicit) input
# ([a,b,c,d,...] in 2^a*3^b*5^c*7^d*...=input)
ć # Extract head; pop and push remainder-list and first item separated
Å0 # Get a list of 0s with a length equal to the `a` exponent
« # Merge that as trailing items to the remainder-list
ε # Map over each integer in the list:
¯ # Push an empty list
s # Swap so the current number is at the top of the stack
F # Loop that many times
¸ # And wrap the list into a list every iteration
# (after which the result is output implicitly)
```
[Answer]
# Pyth, 29 bytes
```
L+'MhMtbmYhbL&JPby/LJf}TPTSeJ
```
[Demonstration](https://pyth.herokuapp.com/?code=L%2B%27MhMtbmYhbL%26JPby%2FLJf%7DTPTSeJ%27Q&input=16777215&debug=0)
This defines a function, `'`, which performs the desired mapping.
A helper function, `y`, performs the mapping recursively given a prime decomposition. The base case and the prime decomposition are performed in `'`.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 34 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ÑE│♂█ⁿt2N╔₧Ñ↓Ls&ûΦ}eóâÇΔ-ë╖»8Kq+╔r
```
[Run and debug it](https://staxlang.xyz/#p=a545b30bdbfc74324ec99ea5194c732696e87d65a28380ff2d89b7af384b712bc972&i=10%0A21%0A42&m=2)
There's very likely a better way to do this with recursion, but I just can't seem to find anything related to it in the builtin docs. So, this is a manually built implementation.
Takes very, very long after the third test case.
## Explanation (Unpacked)
```
z]Yx{c2>{|nBs{y@msz]s|*+c]ys+Yd}{vy@}?F|u
z] array [[]]
Y write that to register Y
x{ F for i in [1..input]
c2> if i < 2,
{vy@} increment and take element at that index from y
{|n otherwise take prime exponents
Bs push the first element and the rest of the array separately
{ m map the rest of the array to:
y@ elements in y at those indices
sz]s push [[]] and first element
|* repeat it's elements that many times
+ add those together
c]ys+Y and append that to register Y
d} then delete it
|u convert the last element on stack to string
implicit output
```
] |
[Question]
[
# Bowl Pile Height
The goal of this puzzle is to compute the height of a stack of bowls.
[](https://i.stack.imgur.com/9dZsZm.jpg)
A bowl is defined to be a radially symmetric device without thickness.
Its silhouette shape is an even polynomial. The stack is described by a list of radii, each associated with an even polynomial, given as input as a list of coefficients (e.g. the list `3.1 4.2` represents the polynomial \$3.1x^2+4.2x^4\$).
The polynomial may have arbitrary degree. For simplicity, the height of the pile is defined as the altitude of the center of the top-most bowl (see plot of Example 3 for an illustration).
Test cases are in the format `radius:coeff1 coeff2 ...`: each line starts with a float number representing the radius of the bowl, followed by a colon and a space-separated list containing the coefficients for the even powers, starting with power 2 (zero constant part is implied). For example, the line `2.3:3.1 4.2` describes a bowl of radius `2.3` and the shape-polynomial `3.1 * x^2 + 4.2 * x^4`.
## Example 1
```
42:3.141
```
describes a pile of zero height since a single bowl has no height.
## Example 2
```
1:1 2
1.2:5
1:3
```
describes a pile of height `2.0` (see plot).
[](https://i.stack.imgur.com/eyrxF.png)
## Example 3
```
1:1.0
0.6:0.2
0.6:0.4
1.4:0.2
0.4:0 10
```
describes a pile of height 0.8 (see green arrow in the plot).
[](https://i.stack.imgur.com/9wFYRm.png)
This is code golf, so the shortest code wins.
I have [reference code](https://gist.github.com/pasbi/89f86df9fb1049bd3dfb6cffeac093b2).
# Edit:
The reference implementation relies on a library to compute the roots of polynomials.
You may do that as well but you don't need to.
Since the reference implementation is only a (quite good) numerical approximation, I will accept any code which produces correct results within common floating-point tolerances.
The idea counts. I don't care if there are small erros \$<\varepsilon\$.
Another variant of this puzzle is to minimize the height by reordering the bowls. I'm not sure if there's a fast solution (I guess it's NP-hard). If anyone has a better idea (or can prove NP-completeness), please tell me!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~54~~ 53 bytes
```
J×$ÆrAƑƇ«⁹;⁹*€J{ḋ⁸ŻṀ
Œcz€0ḢṂç@I0;ⱮFƲƲ€ṚṁL’R€Ɗ;+Ṁ¥¥ƒ0Ṁ
```
[Try it online!](https://tio.run/##TY0/SwMxGMb3fIp36KQYkty1YAKii2BxchCcxUU6uVWXSwcPdPIc/IMuSnFQBIuUC4UOCZfvkXyR873QgkPyPO/z/p7k/Gw0Grft0D303PXFnr/zpf2M2ig8G3HyNbwK9W3UdbMIpiBNdXqJIQv1WzAT97F7wFT8@d73Mz/DPJjnYPRhLJ6OcPI3ahNLdmqnvmLo2qYK5lHF4gW2diAWr8qVKeqRqJcSxmHxG8w7VnEHx52mN11JmvtuoZd2bueuxPikbXMhM8pzTgiXHAThVMg@@iwFlBFGB5JRsdIcgXw1owJnyNFEwpoRkK9pyP7x24mHASGp2UfJGKDrvuqQ7uaA7g8 "Jelly – Try It Online")
A monadic link that takes as its argument the list of bowls from top to bottom in the format `[[b1_radius, b1_coef1, ...], [b2_radius, b2_coef1, ...]]` and returns the y position of the bottom of the top bowl.
Now correctly handles bowls which meet at places other than the minimal radius.
## Explanation
### Helper link: takes as left argument `l` the differences in coefficients of the polynomials representing the bowls from 1 upwards, and its right argument `r` the minimum radius; returns the maximum y value where the two bowls meet
```
$ | Following as a monad:
J | - Sequence from 1..<len(l)>
× | - Multiply (by l)
Ær | Roots of polynomial
AƑƇ | Keep only those invariant when passed through absolute function (excludes negative, imaginary and complex numbers)
«⁹ | Min of these filtered roots and r
;⁹ | Concatenate r to the list
*€ | Each root/radius to the power of:
J{ | - Sequence from 1..<len(l)>
ḋ⁸ | Dot product with l
Ż | Prepend zero
Ṁ | Maximum
```
### Main link, takes a bowl pile as its argument and returns y value of base of top bowl
```
Œc | Combinations length 2
z€0 | Transpose each using 0 as a filler
Ʋ€ | For each one, do the following as a monad:
Ḣ | - Take the head (the radii)
Ṃ | - Minimum
ç@ Ʋ | - Call the helper link with this (min radius) as right argument and the following as left argument:
I | - Increments (difference between second and first polynomial for each coefficient)
0;Ɱ | - Prepend each with a zero (odd coefficients are all zero)
F | - Flatten
Ṛ | Reverse
ṁ Ɗ | Mould to the following as a monad:
L | Length
’ | Decrease by 1
R€ | Range of each (e.g. [1],[1,2],[1,2,3],[1,2,3,4]
¥ƒ0 | Reduce using the following as a dyad and starting with 0
; ¥ | - Concatenate the following as a dyad
+ | - Add
Ṁ | - Take the maximum
Ṁ | Finally take the overall maximum
```
### Python reference
[Finally, here’s a TIO version of the Python reference that @pasbi included for the main problem.](https://tio.run/##lVXbbqMwEH3nK0bpi91SBNmq0qJ2fwQhyw1OcJcYhEmb7M93Z3xJIG1XWl7AczkzczwzDKep7c2Pjw@9H/pxAnPYDyeQFsyQBJE92SS5gYEdOTyDPexZBQPcwvH2VsO2H0GneNYGFDqrUU6KDZbXPGnUFhq93apRmUkHeZkAPqOaDqMBD/QPFKiroqwTBzX2/WQ/QZghi4qqLO8LjOus1ZvsDh4lhePS5z9qCEXYSZqNYvjRCpmCe79EUNnogxV5CraVgxI5suQN5@oiqouofpmpUbbXhl2gohd3RsQicR/w7yOUVzYOcc4znbznIBw7aOFZahqsyXlhXdqKvTzqPdJB2lDPjKgziU2TOgAOvyDP8gWENmKUZqe@wUBzeHLO8PQc6lr4j0p23/jKF@s0md7LHSd/RPNPccEgC7HV3aTGb3CuCwVpms@pR@klIR/jBmkctZnYynFYwiqNvF6TXPlCqaPcB3ZUVOovEoU6XK/vL49wIR1vMdL@FeK1890X3sgXTz9BukuI0bHxxDwDZIqdz3w@NwvLMJRKNiRrWaeNWkwEkkRwJM/s0Gnkr1zxZdNvu15Ooe29Sr0pI5wjTrYcR3lilbfaeBY2jgIbIWFFY@puITj9UWNv2fq2U4YFNH5XRJtqXZbrGi2Dal7fJW9f3CAbtz5MqAvPjWrEMpDhS11VUmDaHmi1xD/bBPgO24G4U5b5V4gjrVW4eAknyGnsnMr1QUjTLQFiwxuVcG57g6GLPD@fjyFjvAs7SFxk9xEjvkMV9Jyu2tCFoR3qgh8p4DE2n6u8mzIqhR0R5xRHAoWd2inTMD9hs2L4xcS2/TvDMcPhEMLIvRICnp9hJXBesdnEqow93obpuGo4lxN9UVr4p8rs1GiTkRVJLeM0eAYHx/fhJMfJvuupZaubFQcsI4mEUd9XlKYrOIzcJ5Zrfp0RQyPqlMCT4d@5xmAn0W@3VoWFQfuxPt@tJnPPGP4x5qRdltpyXSx@TspWr3Ua4lW69qm8XkA1n93cOZFMDgNd1XL0@Tyix6uKuspr2jRnX5T6stBt81u0Su/aCeYG@FP2F@6W6NyMf3wUWVEWSME6ybPHMs/W8BC@HuBHUmQPJEPJzzLHlobHvw) It reads from stdin.
[Answer]
# [Python 3](https://docs.python.org/3/) + numpy + scipy, ~~248~~ 240 bytes
```
from scipy.optimize import*
from numpy import*
def f(b,i=0):
for r,c in b:p=zeros(2*len(c)+1);p[-3::-2]=c;p[-1]=h=max([0,*(-fminbound(lambda x:polyval(polysub(p,d),x),0,min(s,r),full_output=1)[1]for s,d in b[:i])]);b[i][1]=p;i+=1
return h
```
[Try it online!](https://tio.run/##bVLBjtsgEL37K0a@BLLEMk6y2jr1qad@g2NF2MYNEgYEeDfZn0/BjrLZqlxmmPfe8AYwV3/Wanu7DVaP4Dphrpk2Xozik4MYjbZ@ncyYmkZzfZR6PsCAWiKqHJcJDNqCJR0IBW1pqk9utUPFWnKFOvxC8cHUm21Zboqm6mJOm@pcjeyC6pys0WYYhWr1pHok2dj2DC6l0fL6ziSK0U0tMqTH5IJJTgIXOWIxGSYpT3ryZvIVxTVtogtH@tlFXYoGN/jQ1qIJUGUO4qWiCVjuJ6vgfPPc@VPHHHdQQZ2gdFeU24zuaEogxyQU0vSY0JJCkdCsKPch3x6TUCXFM5zlSZ69lnlW3OMu0Hf3fYhA80WVZ285fShnZB/CNoeQ3RvT14y@/djjpEmSOE3PPCPAL4Z3ns@DfdkO1x5Wqz/kPEEzb6NIRl5UZs5I4aVQ3CG80OOyrBeTI@DOzPBTN9l3HhrIhY1W5Qo/qN8p8R84b4X6g56A0IibagVPstlUxozh4UnrQWrm0XIq/nZss0jCG8buaJYtJTEAax2KyOYxP4afQPlm9xjFBC8epb@0tYEATLkPbtOlA5eO/0v8rbr/UR@E2QCJfr4u/T7eUa3w7S8 "Python 3 – Try It Online")
*-8 bytes thanks to @xnor*
The function takes a list of `[radius, polynomial]` pairs as input and returns the pile height.
This solution uses more or less the same algorithm as the reference code except that it does not compute the maximum using derivatives. Meanwhile, it is written using built-in `numpy` and `scipy` functions in Python. The ungolfed version is shown in the following. This serves as an alternative version of the reference code for those who wants a shorter version to capture the idea quickly.
```
from scipy.optimize import fminbound
import numpy as np
def compute_pile_height(bowl_data):
for i, (r, curve) in enumerate(bowl_data):
distances = [0] # Initialize the distances array with 0 as the lower bound for max
# Construct a complete polynominal coefficient array
curve_poly = np.zeros(2 * len(curve) + 1)
curve_poly[-3::-2] = curve
# Iterate over all bowls under the current bowl
for j in range(i):
b_r, b_curve_poly = bowl_data[j]
# Calculate the difference polynominal between the current bowl and bowl j
diff = np.polysub(curve_poly, b_curve_poly)
# Find the maximum height difference between bowl j and the current bowl in the range [0, min(b_r, r)]
max_height_diff = -fminbound(lambda x:np.polyval(diff, x), 0, min(b_r, r), full_output=True)[1]
distances.append(max_height_diff)
# Compute the maximum distance as the height for the current bowl,
# update the polynominal using the height as the constant coefficient
curve_poly[-1] = height = max(distances)
# Update stored data for the current bowl
bowl_data[i][1] = curve_poly
return height
```
[Try it online!](https://tio.run/##dVXBcpswEL3zFTvuIdBiBmynkzLNKTOdyb09OR5GxkusjJA0kkji/ny6QpiAk3IBxO7bt09vhT65o5Lrt7fGqBZszfUpU9rxlv9F4K1WxkHTcrlXnTxEw4LsWn0CZkHqKDpgA7Vqdeew0lxgdUT@eHTxXr2I6sAcS8oI6GqUAZ5CbFKoO/OMCXAJSFBomMMP4f46cOuYrNHCLWzzHcAXuJfccSY8O3fESQQzhp3ghbsj5J6a/yrUCxroqfflW/Y6Yn@BOyWtM13tgPUNCHQIWomTVNQwE7SITcNrjtIF@DG5b6DyscRM6uwvGmXjFXwFgTIe2vsGRfJJxna5LsvlakeZ/eIYMqF273pRQD0TfyYEeHUsUB/07jujTONp@fUxz7f45FU1TD5izCdK@mtfkfT7asZ9VH37tItm0aQPE3UnPI2gdNMg1aznGu3RvSDKD6SAkeb9w9MM1sMEzTyK7fbxO585u@SSzy9OkL4ObSNvuxaC0abMzmxC4Z7DB2I8kO01IlelQI3EvTYm2c1KUp3BzNVAezmOQixYuz8weC2HVp6ZiH1UCq9JCnPYFJpOiEp1jqbk9rfpMNkWuwtdBiNnTGsk/IviEzW8c/txm4lxBjh7fxDHe@JSgnRqtU4fzls83dfOcvk4BRpgaz80jIAmw/GpyQtv8CH31rOMxxZnvfwJ9a1TBg/grfgp5zHj3bF8ty3GKeqr9kEGXWfkUPrNoXVVzWw4Q6J4sVmV66zYFAvapCSlhcXiISrKAlZRka3Ka3peP0S0mq6mn7M8yrPvZZ6thvuGwjfDO92hyENWnt3kxZjZf7mm2zqnY6kYgIvvWXHz4zqJaOZ8s76dFPBVY@1IBO/QkXaY4TD/1MFuPEt7J/vMzGrBneASbTwZecMOvLMp2CPTGOaKAESIjq/Kq/fDaR5ChvY/AzobyQLx5Bthob69gklmz@ts2W0jFHNxKJzMKu9CCk2A37D//C1sCOINsL2NfexyFCWBn1DgcjP2p4mdixd3ijzij3Bp6axfBAQUFi8D72X9WegY0BNIPcP3nRgafpBXyds/ "Python 3 – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~104~~ 93 bytes
```
FoldPair[{(R=#;F=#2)&@@#2;H=Max[0,{#2-F,0<x<#~Min~R}~MaxValue~x&@@@#],#~Join~{R|H+F}}&,{},#]&
```
[Try it online!](https://tio.run/##XY7NisJAEITvPkWgIazYzs5MRi8xklOQBUFy8BIMDK5hA/6ARBiY7Xn12Ansgh6rvuqqvtju53SxXXu0fZP1xe38vbPtvfIfZQZpkYGexnkOOt1kW@sqiR70vEC5cisI2/YaSgoM9vb8OAXH0RwOCOHrxsiXv5tZQRSjJ4RD3O/u7bWrYL5uOBV/5n7ivdERJkIZ5WpNhOyoKEIWM@1qw0bkldC4GPAomCbv2ZFIsUQp9Ks0/3fCvFKDSg4LY4/hHrX4GxxUIocfXL0kmlD/BA "Wolfram Language (Mathematica) – Try It Online")
Takes input as a List of `{radius, polynomial}` pairs representing bowls, with polynomials in terms of \$x\$.
For decimal instead of symbolic output, use `NMaxValue` instead (or just call `N` on the result).
```
(* Step through a list of bowls: *)
(* At each step, calls a function taking {previous-bowls-list},current-bowl *)
(* which returns {height,{bowls-list}} *)
(* and returns the final height *)
FoldPair[
(R=#;F=#2)&@@#2; (* extract Radius and Function*)
{
H=Max[0, (* Height - at least zero; the greatest of *)
MaxValue[{#2-F, (* the required heights *)
0<x<#~Min~R},x] (* within the relevant domain *)
&@@@#] (* given all previous bowls *)
,
#~Join~{R|H+F} (* append to list of bowls *)
}&,
{}, (* initial list of bowls (empty) *)
# (* list of bowls *)
]&
```
[Answer]
# [R](https://www.r-project.org/), ~~451~~ 436 bytes
```
function(x){x=c(x[1],x);a=rev(pmax(0,c(combn(x,2,function(y,z=sapply(y,"length<-",max(lengths(y)))){z[is.na(z)]=0
b=rep(0,2*(n=nrow(z)-1))
b[2*1:n]=e=z[-1,2]-z[-1,1]
b=b*1:(2*n)
while(!c(b,1)[1])b=b[-1]
b=rev(b)
s=`if`(length(b)>1,eigen(rbind(-(b/b[1])[-1],cbind(diag(length(b)-2),0)))$va,0)
max(outer(c(pmin(abs(s[s==abs(s)]),r<-min(z[1,])),r),2*1:n,`^`)%*%e)}))))
o={}
for(i in seq(a=x[-1])){o=c(o,max(c(0,o)+a[1:i+F]));F=F+i}
max(o)}
```
[Try it online!](https://tio.run/##bVLbjpswEH33V7ioK40TQzFhVyob70ulfeofsFQxxCGWiKGYZEmifHs6kEsjtUjYczlnfDzj9ryS59XWFp2pLfTs2MsC@lRkvGevSrZ6B81G9RDyAop6kyOGR/xO2PODdKppqj2aXqVt2a3nvscHysVzsGf4HQ@pcYFVcGCZDEmOlRssGk3AStvWnxj3BWMkT6OJSGwmtTykvuBR5o@7yJCTYwqiiWXkc20qDV8KyLlgqJZhEmHZWHgHOSNOLsxqcRWBgTfBtSm1hTY3dgk@5N/ygTiweDHGlkaVfwl@xHiIyr/uFO5kuFG97XQLBXbEWFC5A5c6KUeDZYy3c39IHFLBM4Yu4@Nd@OLXgj1NnjQ7DZ0gtTyeyKpuwVBjqdO/Qcl@kIFdqrH79di9ArtTs6lKRWKm75h7fZfvU3O6CGGnc0nnPn2YHD2S4erVZRqua11TmQ5Kt83BSzxOPYpLq9Xyp7HaQaf77kdtrb4VQMkIYVzhnLYb3ZoCxZ7I@t9zelmiQQrVgVcZhyunjXKdhutb6B9eCBszIXjFHRbiY6FFXaFWp6kcdOG5@Huo4b8J6r8NzgqPRffDou10MyC8USN4cRJS8UziZBZStDA8BKNkFoj46olE0IiIIEqeiUhm92AQkjB4ScIguu4xguKrP9YNr9hgRNMbLqLxjUFnD5zvI4e@eOz8Bw "R – Try It Online")
[Try it online!](https://tio.run/##bVJdk5owFH3Pr0iZ7syNBkqQ3ZmyZl/62n9AaRcwahwMlKCLOv52e4lonWmZgdyPc24OJ2kvS3lZ7kzZ6dpAz069LKFPRcZ79prLVu2h2eY9hLyEst4WiOERvxMO/Cht3jTVAUOvUmbVree@xwfKNbNwYPicjqm2gcnhyDIZkgInNzg0moCRpq0/sO4LxkiRRhORmEwqeUx9waPMd6vIkFNgC6KJYeRjrSsFn0oouGColmETYZkbvIeCESv1cpSA6ZtgSq@UgbbQZgE@FF@KgTZweOlqC52v/hL8iPEQdX/e51RVVtGQDP9U7zrVQomeaAN5YcGmVkoXsIzxdu4PjWMqeMYwZdz9DX//@c6eJk@KnQcvSI0eM7JBH5Z1C5pqQ636/Qs3vwnonRunAVg7M0s0q2bTPBWJnm5w@OtGbqb6fFXFzpcVnfv04SDpiQxOVNfDsV1rm0p3sLK7ArzE49Sj@GlVvviujbLQqb77VhujbgNQP0IYz/HYdlvV6hKVn8n63316ucKAlHkHXqUtfjltctspGK9G/3BhmOuE4JV3WIh3h5Z1hVrRaDnown3x9VDDfxvUfxuSJW6L6Q@DsVXNgPCcRvDiJKTimcTJLKQYYXkoRsksEPGYiUTQiIggSp6JSGb3YhCSMHhJwiAa1xhB8Zi7ueGIDRya3nARjW8MOnvgfHUc@uKxyx8 "R – Try It Online")
Broadly speaking an R port of my Jelly answer, though since base R has no function to find the roots of polynomials this is implemented using the method found in `polynom::solve.polynomial`.
A function taking a list of numeric vectors from top to bottom of pile.
Thanks to @RobinRyder for golfing off 15 bytes!
] |
[Question]
[
# Cyclically self-describing lists
A list \$L\$ of positive integers is *cyclically self-describing*, if the following conditions hold.
1. \$L\$ is nonempty.
2. The first and last elements of \$L\$ are different.
3. If you split \$L\$ into runs of equal elements, the element of each run equals the length of the next run, and the element of the last run equals the length of the first run.
For example, consider \$L = [1,1,1,2,3,3,1,1,1,3]\$.
It is nonempty, and the first and last elements are different.
When we break it into runs, we get \$[[1,1,1],[2],[3,3],[1,1,1],[3]]\$.
* The first run is a run of \$1\$s, and the length of the next run, \$[2]\$, is \$1\$.
* The second run is a run of \$2\$s, and the length of the next run, \$[3,3]\$, is \$2\$.
* The third run is a run of \$3\$s, and the length of the next run, \$[1,1,1]\$, is \$3\$.
* The fourth run is a run of \$1\$s, and the length of the next run, \$[3]\$, is \$1\$.
* Finally, the last run is a run of \$3\$s, and the length of the first run, \$[1,1,1]\$, is \$3\$.
This means that \$L\$ is a cyclically self-describing list.
For a non-example, the list \$[3,2,2,2,1,4,1,1,1]\$ is not cyclically self-describing, since a run of \$2\$s is followed by a run of length \$1\$.
The list \$[2,2,4,4,3,3,3,3]\$ is also not cyclically self-describing, since the last run is a run of \$3\$s, but the first run has length \$2\$.
# The Task
In this challenge, your input is an integer \$n \geq 1\$.
Your output shall be the number of cyclically self-describing lists whose sum equals \$n\$.
For example, \$n = 8\$ should result in \$4\$, since the cyclically self-describing lists whose sum is \$8\$ are \$[1,1,1,1,4]\$, \$[1,1,2,1,1,2]\$, \$[2,1,1,2,1,1]\$ and \$[4,1,1,1,1]\$.
The lowest byte count wins, and other standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
Here are the correct output values for inputs from \$1\$ to \$50\$:
```
1 -> 0
2 -> 0
3 -> 0
4 -> 2
5 -> 0
6 -> 2
7 -> 0
8 -> 4
9 -> 0
10 -> 6
11 -> 6
12 -> 12
13 -> 0
14 -> 22
15 -> 10
16 -> 32
17 -> 16
18 -> 56
19 -> 30
20 -> 96
21 -> 56
22 -> 158
23 -> 112
24 -> 282
25 -> 198
26 -> 464
27 -> 364
28 -> 814
29 -> 644
30 -> 1382
31 -> 1192
32 -> 2368
33 -> 2080
34 -> 4078
35 -> 3844
36 -> 7036
37 -> 6694
38 -> 12136
39 -> 12070
40 -> 20940
41 -> 21362
42 -> 36278
43 -> 37892
44 -> 62634
45 -> 67154
46 -> 108678
47 -> 118866
48 -> 188280
49 -> 209784
50 -> 326878
```
[Answer]
# [Haskell](https://www.haskell.org/), 75 bytes
Thanks Ørjan for saving one byte!
```
g n=sum[x#n|x<-[1..n],let a#n=sum$[b#(n-a*b)|b<-[1..n],a/=b]++[0^n^2|a==x]]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P10hz7a4NDe6QjmvpsJGN9pQTy8vVicntUQhURksoxKdpKyRp5uolaRZkwRXkKhvmxSrrR1tEJcXZ1STaGtbERv7PzcxM0/BVqGgKDOvREFFITexQCFdAaTByDT2PwA "Haskell – Try It Online")
The problem is equivalent to:
How many ways can \$n\$ be written as \$\sum\_{i=0}^ka\_ia\_{i+1}\$ with \$a\_i\in\mathbb N,a\_i\neq a\_{i+1},a\_0=a\_k\$
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes
```
ṗⱮ¹Ẏ;ḷ/$€IẠ$Ƈ×Ɲ€§ċ
```
[Try it online!](https://tio.run/##ATEAzv9qZWxsef//4bmX4rGuwrnhuo474bi3LyTigqxJ4bqgJMaHw5fGneKCrMKnxIv///8z "Jelly – Try It Online")
Idea: Each cyclically self-describing list can be described as a list of values for each block, and we can deduce the lengths from the values. Note that two adjacent values must be different. Of course there can be at most `n` blocks and the length of each block is at most `n`.
[Answer]
## Haskell, ~~118~~ ~~105~~ 103 bytes
Edit: -13 bytes thanks to @Ørjan Johansen, -2 bytes thanks to @H.PWiz
```
g s=sum[b#a$s|b<-[1..s],a<-[1..s],let(d#l)s|d==a,d/=b,l*d==s=1|n<-s-d*l=sum[i#d$n|i<-[1..s],d/=i,n>=0]]
```
[Try it online!](https://tio.run/##PYwxDsIwDAC/YikZoEoKRWKr@UiVwVGqEuFYFS5b/h4KQ7cb7u5J@pqZW1tAUT9lioas1jj6aeh7DY4O4nk7JcNnrQmRXLpgdNztrDhUGb361PH/kU2yUvNR7mp28sBrCK1QFkBY31k2sFBohQV@3u0e2hc "Haskell – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 25 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Åœεœʒ¬sθÊ}ÙεγĆü‚ε`gå}P]˜O
```
[Try it online](https://tio.run/##ATYAyf9vc2FiaWX//8OFxZPOtcWTypLCrHPOuMOKfcOZzrXOs8SGw7zigJrOtWBnw6V9UF3LnE///zg) or [verify the first 9 test cases](https://tio.run/##AUcAuP9vc2FiaWX/OUVOPyIg4oaSICI/TiL/w4XFk861xZPKksKsc864w4p9w5nOtc6zxIbDvOKAms61YGfDpX1QXcucT/8iLlYs/w) (times out for \$n\geq10\$).
**Explanation:**
```
Ŝ # Get all lists of positive integers that sum to the (implicit) input
ε # Map over each inner list:
œ # Get all its permutations
ʒ # Filter this list of permutation-lists by:
¬ # Get the first element (without popping the list itself)
sθ # Swap to get the list, and pop and push its last element
Ê # Check that they are NOT equal
}Ù # After the inner filter: uniquify all remaining permutations
ε # Map each permutation to:
γ # Split the list into groups of equal adjacent elements
Ć # Enclose it: add the first group as trailing item
ü‚ # Create overlapping pairs of groups
ε # Map over each pair:
` # Pop and push both lists separated to the stack
g # Pop and get the length of the second list
å # And check that it's in the first list
}P # After this inner-most map: verify all pairs were truthy (product)
] # Close the two still open nested maps
˜ # Flatten the list of lists
O # And take the sum
# (after which this is output implicitly as result)
```
[Try it online with a step-by-step output.](https://tio.run/##ZZKxThwxEIZ7nsK6KpE2fRQJRQglHQoSoYyUYXd2dzivbewx6DqEBAVlqILSpqOLEqWgYqEh0j0EL3IZ23cIEu0Wq/X/fzPzj22APcLFYrKhtdIUOCjbKmcDMR2iIsPYoQ@Ke2AV4qDYync6cJHfqEm1Np7eXazf/Hq7NnmRGA79EBmYrMkohLoXtUGf8YqCClNyDptKBTI1ZpyNLLx0eAQzqWGVtqZ7Oaky@D1pFr@IFPxb4qhHXxgteeGDaZQG@UCNAxqZB@QcDyLo3O78593F/ZebqzD/PZ5/Ko3vGjqI1M4yxuMAZMh0z@pk78PJ1fi1WHacJl4NJ5l03kZXBk6lFDT7UEv5xzZWAHnnPwrjnam1DVgoORyxF9AT9e1ZUW96BJakDtFrcC43CDJyMqW@/zOO1w/Hl8W7BS4bS6msrHJSdY/1VFEhaDQd9ytewNqKIovTYsg8STn/XeaZns/d@H0Z5keYln04b5tY8/NL8GqwYs/DSmrSUoo9LTVtiX3kfvaI3V4SN6SNloyoZEMrequBGQ026VZWcg0olZA0ol/epsz58@1DtVi8/gs)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 27 bytes
```
#§=oṙ1mLm←fo¬εumgfo=¹ΣṖṁḣ´R
```
[Try it online!](https://tio.run/##ATUAyv9odXNr//8jwqc9b@G5mTFtTG3ihpBmb8KszrV1bWdmbz3Cuc6j4bmW4bmB4bijwrRS////NA "Husk – Try It Online")
A direct bruteforce. Struggles for n above 4.
] |
[Question]
[
Recently at the newly released [Puzzling.SE](https://puzzling.stackexchange.com/), there was [a problem about spies throwing stones into a river](https://puzzling.stackexchange.com/questions/625/two-spies-throwing-stones-into-a-river) that was actually quite challenging:
>
> Two spies must pass each other two secret numbers (one number per spy), unnoticed by their enemies. They have agreed on a method for doing this using only 26 indistinguishable stones in advance.
>
>
> They meet at a river, where there is a pile of 26 stones. Starting with the first spy, they take turns throwing a group of stones into the river: the first spy throws some number of stones, then the second one, then the first one again...
>
>
> Each spy must throw at least one stone on his turn, until all the stones are gone.
>
>
> They observe all throws and diverge when there are no more stones. They keep silence all the time and no information is exchanged except number of stones thrown at each turn.
>
>
> How can they exchange the numbers successfully if the numbers can be from 1 to M?
>
>
>
Your task is to build a pair of programs, `spy1` and `spy2`, that can solve this problem for the highest possible `M`.
Your programs will each take a number from `1` to your chosen `M` as input. Then, `spy1` will output a number representing the number of stones it throws into the river, which will be input to `spy2` which will also output a number to be input to `spy1`, and so on until the numbers output add up to `26`. At the end of throwing, each program will output the number it believes the other program had, which must match the number that was actually input to the other program.
Your program must work for all possible ordered pairs of numbers `(i, j)` where both `i` and `j` can vary from `1` to `M`.
The program that works for the largest `M` will be the winner, with the first answer to be posted breaking a tie. Additionally, I will award a +100 reputation bounty to the first solution that is proven to work for `M >= 2286`, and +300 to the first solution that is proven to work for `M >= 2535`.
[Answer]
## C#, M = 2535
This implements\* the system which I described mathematically on the thread which provoked this contest. I claim the 300 rep bonus. The program self-tests if you run it either without command-line arguments or with `--test` as a command-line argument; for spy 1, run with `--spy1`, and for spy 2 with `--spy2`. In each case it takes the number which I should communicate from stdin, and then does the throws via stdin and stdout.
\* Actually, I've found an optimisation which makes a massive difference (from several minutes to generate the decision tree, to less than a second); the tree which it generates is fundamentally the same, but I'm still working on a proof of that. If you want a direct implementation of the system which I described elsewhere, see [revision 2](https://codegolf.stackexchange.com/revisions/31707/2), although you might want to backport the extra logging from `Main` and the better inter-thread comms from `TestSpyIO`.
If you want a test case which completes in less than a minute, change `N` to `16` and `M` to `87`.
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace CodeGolf
{
internal class Puzzle625
{
public static void Main(string[] args)
{
const int N = 26;
const int M = 2535;
var root = BuildDecisionTree(N);
if (args.Length == 0 || args[0] == "--test")
{
DateTime startUtc = DateTime.UtcNow;
Console.WriteLine("Built decision tree in {0}", DateTime.UtcNow - startUtc);
startUtc = DateTime.UtcNow;
int ok = 0;
int fail = 0;
for (int i = 1; i <= M; i++)
{
for (int j = 1; j <= M; j++)
{
if (Test(i, j, root)) ok++;
else fail++;
}
double projectedTimeMillis = (DateTime.UtcNow - startUtc).TotalMilliseconds * M / i;
Console.WriteLine("Interim result: ok = {0}, fail = {1}, projected test time {2}", ok, fail, TimeSpan.FromMilliseconds(projectedTimeMillis));
}
Console.WriteLine("All tested: ok = {0}, fail = {1}, in {2}", ok, fail, DateTime.UtcNow - startUtc);
Console.ReadKey();
}
else if (args[0] == "--spy1")
{
new Spy(new ConsoleIO(), root, true).Run();
}
else if (args[0] == "--spy2")
{
new Spy(new ConsoleIO(), root, false).Run();
}
else
{
Console.WriteLine("Usage: Puzzle625.exe [--test|--spy1|--spy2]");
}
}
private static bool Test(int i, int j, Node root)
{
TestSpyIO io1 = new TestSpyIO("Spy 1");
TestSpyIO io2 = new TestSpyIO("Spy 2");
io1.Partner = io2;
io2.Partner = io1;
// HACK! Prime the input
io2.Output(i);
io1.Output(j);
Spy spy1 = new Spy(io1, root, true);
Spy spy2 = new Spy(io2, root, false);
Thread th1 = new Thread(spy1.Run);
Thread th2 = new Thread(spy2.Run);
th1.Start();
th2.Start();
th1.Join();
th2.Join();
// Check buffer contents. Spy 2 should output spy 1's value, so it's lurking in io1, and vice versa.
return io1.Input() == i && io2.Input() == j;
}
private static Node BuildDecisionTree(int numStones)
{
NodeValue[] trees = new NodeValue[] { NodeValue.Trivial };
for (int k = 2; k <= numStones; k++)
{
int[] prev = trees.Select(nv => nv.Y).ToArray();
List<int> row = new List<int>(prev);
int cap = prev.Length;
for (int i = 1; i <= prev[0]; i++)
{
while (prev[cap - 1] < i) cap--;
row.Add(cap);
}
int[] next = row.OrderByDescending(x => x).ToArray();
NodeValue[] nextTrees = new NodeValue[next.Length];
nextTrees[0] = trees.Last().Reverse();
for (int i = 1; i < next.Length; i++)
{
int cp = next[i] - 1;
nextTrees[i] = trees[cp].Combine(trees[i - prev[cp]]);
}
trees = nextTrees;
}
NodeValue best = trees.MaxElement(v => Math.Min(v.X, v.Y));
return BuildDecisionTree(numStones, best, new Dictionary<Pair<int, NodeValue>, Node>());
}
private static Node BuildDecisionTree(int numStones, NodeValue val, IDictionary<Pair<int, NodeValue>, Node> cache)
{
// Base cases
// NB We might get passed val null with 0 stones, so we hack around that
if (numStones == 0) return new Node(NodeValue.Trivial, new Node[0]);
// Cache
Pair<int, NodeValue> key = new Pair<int, NodeValue>(numStones, val);
Node node;
if (cache.TryGetValue(key, out node)) return node;
// The pair-of-nodes construction is based on a bijection between
// $\prod_{i<k} T_i \cup \{(\infty, 0)\}$
// and
// $(T_{k-1} \cup \{(\infty, 0)\}) \times \prod_{i<k-1} T_i \cup \{(\infty, 0)\}$
// val.Left represents the element of $T_{k-1} \cup \{(\infty, 0)\}$ (using null for the $(\infty, 0)$)
// and val.Right represents $\prod_{i<k-1} T_i \cup \{(\infty, 0)\}$ by bijection with $T_{k-1} \cup \{(\infty, 0)\}$.
// so val.Right.Left represents the element of $T_{k-2}$ and so on.
// The element of $T_{k-i}$ corresponds to throwing $i$ stones.
Node[] children = new Node[numStones];
NodeValue current = val;
for (int i = 0; i < numStones && current != null; i++)
{
children[i] = BuildDecisionTree(numStones - (i + 1), current.Left, cache);
current = current.Right;
}
node = new Node(val, children);
// Cache
cache[key] = node;
return node;
}
class Pair<TFirst, TSecond>
{
public readonly TFirst X;
public readonly TSecond Y;
public Pair(TFirst x, TSecond y)
{
this.X = x;
this.Y = y;
}
public override string ToString()
{
return string.Format("({0}, {1})", X, Y);
}
public override bool Equals(object obj)
{
Pair<TFirst, TSecond> other = obj as Pair<TFirst, TSecond>;
return other != null && object.Equals(other.X, this.X) && object.Equals(other.Y, this.Y);
}
public override int GetHashCode()
{
return X.GetHashCode() + 37 * Y.GetHashCode();
}
}
class NodeValue : Pair<int, int>
{
public readonly NodeValue Left;
public readonly NodeValue Right;
public static NodeValue Trivial = new NodeValue(1, 1, null, null);
private NodeValue(int x, int y, NodeValue left, NodeValue right) : base(x, y)
{
this.Left = left;
this.Right = right;
}
public NodeValue Reverse()
{
return new NodeValue(Y, X, this, null);
}
public NodeValue Combine(NodeValue other)
{
return new NodeValue(other.X + Y, Math.Min(other.Y, X), this, other);
}
}
class Node
{
public readonly NodeValue Value;
private readonly Node[] _Children;
public Node this[int n]
{
get { return _Children[n]; }
}
public int RemainingStones
{
get { return _Children.Length; }
}
public Node(NodeValue value, IEnumerable<Node> children)
{
this.Value = value;
this._Children = children.ToArray();
}
}
interface SpyIO
{
int Input();
void Output(int i);
}
// TODO The inter-thread communication here can almost certainly be much better
class TestSpyIO : SpyIO
{
private object _Lock = new object();
private int? _Buffer;
public TestSpyIO Partner;
public readonly string Name;
internal TestSpyIO(string name)
{
this.Name = name;
}
public int Input()
{
lock (_Lock)
{
while (!_Buffer.HasValue) Monitor.Wait(_Lock);
int rv = _Buffer.Value;
_Buffer = null;
Monitor.PulseAll(_Lock);
return rv;
}
}
public void Output(int i)
{
lock (Partner._Lock)
{
while (Partner._Buffer.HasValue) Monitor.Wait(Partner._Lock);
Partner._Buffer = i;
Monitor.PulseAll(Partner._Lock);
}
}
}
class ConsoleIO : SpyIO
{
public int Input()
{
return Convert.ToInt32(Console.ReadLine());
}
public void Output(int i)
{
Console.WriteLine("{0}", i);
}
}
class Spy
{
private readonly SpyIO _IO;
private Node _Node;
private bool _MyTurn;
internal Spy(SpyIO io, Node root, bool isSpy1)
{
this._IO = io;
this._Node = root;
this._MyTurn = isSpy1;
}
internal void Run()
{
int myValue = _IO.Input() - 1;
int hisValue = 1;
bool myTurn = _MyTurn;
Node n = _Node;
while (n.RemainingStones > 0)
{
if (myTurn)
{
if (myValue >= n.Value.X) throw new Exception("Internal error");
for (int i = 0; i < n.RemainingStones; i++)
{
// n[i] allows me to represent n[i].Y values: 0 to n[i].Y - 1
if (myValue < n[i].Value.Y)
{
_IO.Output(i + 1);
n = n[i];
break;
}
else myValue -= n[i].Value.Y;
}
}
else
{
int thrown = _IO.Input();
for (int i = 0; i < thrown - 1; i++)
{
hisValue += n[i].Value.Y;
}
n = n[thrown - 1];
}
myTurn = !myTurn;
}
_IO.Output(hisValue);
}
}
}
static class LinqExt
{
// I'm not sure why this isn't built into Linq.
public static TElement MaxElement<TElement>(this IEnumerable<TElement> e, Func<TElement, int> f)
{
int bestValue = int.MinValue;
TElement best = default(TElement);
foreach (var elt in e)
{
int value = f(elt);
if (value > bestValue)
{
bestValue = value;
best = elt;
}
}
return best;
}
}
}
```
### Instructions for Linux users
You'll need `mono-csc` to compile (on Debian-based systems, it's in the `mono-devel` package) and `mono` to run (`mono-runtime` package). Then the incantations are
```
mono-csc -out:codegolf31673.exe codegolf31673.cs
mono codegolf31673.exe --test
```
etc.
[Answer]
# Python Tester Program
I figure it would be useful to have a test program which can verify that your implementation is working. Both scripts below work with either Python 2 or Python 3.
Tester program (`tester.py`):
```
import sys
import shlex
from subprocess import Popen, PIPE
def writen(p, n):
p.stdin.write(str(n)+'\n')
p.stdin.flush()
def readn(p):
return int(p.stdout.readline().strip())
MAXSTONES = 26
def test_one(spy1cmd, spy2cmd, n1, n2):
p1 = Popen(spy1cmd, stdout=PIPE, stdin=PIPE, universal_newlines=True)
p2 = Popen(spy2cmd, stdout=PIPE, stdin=PIPE, universal_newlines=True)
nstones = MAXSTONES
writen(p1, n1)
writen(p2, n2)
p1turn = True
while nstones > 0:
if p1turn:
s = readn(p1)
writen(p2, s)
else:
s = readn(p2)
writen(p1, s)
if s <= 0 or s > nstones:
print("Spy %d output an illegal number of stones: %d" % ([2,1][p1turn], s))
return False
p1turn = not p1turn
nstones -= s
n1guess = readn(p2)
n2guess = readn(p1)
if n1guess != n1:
print("Spy 2 output wrong answer: expected %d, got %d" % (n1, n1guess))
return False
elif n2guess != n2:
print("Spy 1 output wrong answer: expected %d, got %d" % (n2, n2guess))
return False
p1.kill()
p2.kill()
return True
def testrand(spy1, spy2, M):
import random
spy1cmd = shlex.split(spy1)
spy2cmd = shlex.split(spy2)
n = 0
while 1:
i = random.randrange(1, M+1)
j = random.randrange(1, M+1)
test_one(spy1cmd, spy2cmd, i, j)
n += 1
if n % 100 == 0:
print("Ran %d tests" % n)
def test(spy1, spy2, M):
spy1cmd = shlex.split(spy1)
spy2cmd = shlex.split(spy2)
for i in range(1, M+1):
print("Testing %d..." % i)
for j in range(1, M+1):
if not test_one(spy1cmd, spy2cmd, i, j):
print("Spies failed the test.")
return
print("Spies passed the test.")
if __name__ == '__main__':
if len(sys.argv) != 4:
print("Usage: %s <M> <spy1> <spy2>: test programs <spy1> and <spy2> with limit M" % sys.argv[0])
exit()
M = int(sys.argv[1])
test(sys.argv[2], sys.argv[3], M)
```
Protocol: The two spy programs specified on the command-line will be executed. They are expected to interact solely though stdin/stdout. Each program will receive its assigned number as the first line of input. In each turn, spy 1 outputs the number of stones to throw, spy 2 reads a number from stdin (representing spy 1's throw), and then they repeat (with positions reversed). When either spy determines that 26 stones have been thrown, they stop and output their guess for the other spy's number.
Example session with a compatible spy1 (`>` denotes input to the spy)
```
> 42
7
> 5
6
> 3
5
27
<program quits>
```
If you choose a very large M, and it takes too long to run, you can switch `test(` for `testrand(` in the last line to run random tests. In the latter case, leave the program running for at least a few thousand trials to build up confidence.
Example program (`spy.py`), for M=42:
```
import sys
# Carry out the simple strategy for M=42
def writen(n):
sys.stdout.write(str(n)+"\n")
sys.stdout.flush()
def readn():
return int(sys.stdin.readline().strip())
def spy1(n):
m1,m2 = divmod(n-1, 6)
writen(m1+1)
o1 = readn() # read spy2's number
writen(m2+1)
o2 = readn()
rest = 26 - (m1+m2+o1+o2+2)
if rest > 0:
writen(rest)
writen((o1-1)*6 + (o2-1) + 1)
def spy2(n):
m1,m2 = divmod(n-1, 6)
o1 = readn() # read spy1's number
writen(m1+1)
o2 = readn()
writen(m2+1)
rest = 26 - (m1+m2+o1+o2+2)
if rest > 0:
readn()
writen((o1-1)*6 + (o2-1) + 1)
if __name__ == '__main__':
if len(sys.argv) != 2:
print("Usage: %s [spy1|spy2]" % (sys.argv[0]))
exit()
n = int(input())
if sys.argv[1] == 'spy1':
spy1(n)
elif sys.argv[1] == 'spy2':
spy2(n)
else:
raise Exception("Must give spy1 or spy2 as an argument.")
```
Example usage:
```
python tester.py 42 'python spy.py spy1' 'python spy.py spy2'
```
[Answer]
# Java, M = 2535
OK, here is my implementation. At each step one spy makes a move. Each possible move represents a range of codes. The spy chooses the move matching his secret code. As they throw more stones, the range of possible codes reduces until, at the end, for both spies, only one code remains possible according to the moves they did.
To recover the secret codes, you can replay all the moves and compute the corresponding code ranges. At the end, only one code remains for each spy, that is the secret code he wanted to transmit.
Unfortunately, the algorithm relies on a large precomputed table with hundred of thousands of integers. The method couldn't be applied mentally with more than 8-10 stones maybe.
The first file implements the Spy's algorithm. The static part precomputes a `codeCount` table that is later used to compute each move. The second part implements 2 procedures, one to select how many stones to throw, the other to replay a moves to help reconstruct the secret codes.
The second file tests the Spy class extensively. The method `simulate` simulates the process. It uses the Spy class to generate a sequence of throws from the secret codes and then reconstructs the codes from the sequence.
**Spy.java**
```
package stackexchange;
import java.util.Arrays;
public class Spy
{
// STATIC MEMBERS
/** Size of code range for a number of stones left to the other and the other spy's range */
static int[][] codeCount;
// STATIC METHODS
/** Transpose an array of code counts */
public static int[] transpose(int[] counts){
int[] transposed = new int[counts[1]+1];
int s = 0;
for( int i=counts.length ; i-->0 ; ){
while( s<counts[i] ){
transposed[++s] = i;
}
}
return transposed;
}
/** Add two integer arrays by element. Assume the first is longer. */
public static int[] add(int[] a, int[] b){
int[] sum = a.clone();
for( int i=0 ; i<b.length ; i++ ){
sum[i] += b[i];
}
return sum;
}
/** Compute the code range for every response */
public static void initCodeCounts(int maxStones){
codeCount = new int[maxStones+1][];
codeCount[0] = new int[] {0,1};
int[] sum = codeCount[0];
for( int stones=1 ; stones<=maxStones ; stones++ ){
codeCount[stones] = transpose(sum);
sum = add(codeCount[stones], sum);
}
}
/** display the code counts */
public static void dispCodeCounts(int maxStones){
for( int stones=1 ; stones<=maxStones ; stones++ ){
if( stones<=8 ){
System.out.println(stones + ": " + Arrays.toString(codeCount[stones]));
}
}
for( int s=1 ; s<=maxStones ; s++ ){
int[] row = codeCount[s];
int best = 0;
for( int r=1 ; r<row.length ; r++ ){
int min = r<row[r] ? r : row[r];
if( min>=best ){
best = min;
}
}
System.out.println(s + ": " + row.length + " " + best);
}
}
/** Find the maximum symmetrical code count M for a number of stones */
public static int getMaxValue(int stones){
int[] row = codeCount[stones];
int maxValue = 0;
for( int r=1 ; r<row.length ; r++ ){
int min = r<row[r] ? r : row[r];
if( min>=maxValue ){
maxValue = min;
}
}
return maxValue;
}
// MEMBERS
/** low end of range, smallest code still possible */
int min;
/** range size, number of codes still possible */
int range;
/** Create a spy for a certain number of stones */
Spy(int stones){
min = 1;
range = getMaxValue(stones);
}
/** Choose how many stones to throw */
public int throwStones(int stonesLeft, int otherRange, int secret){
for( int move=1 ; ; move++ ){
// see how many codes this move covers
int moveRange = codeCount[stonesLeft-move][otherRange];
if( secret < this.min+moveRange ){
// secret code is in move range
this.range = moveRange;
return move;
}
// skip to next move
this.min += moveRange;
this.range -= moveRange;
}
}
/* Replay the state changes for a given move */
public void replayThrow(int stonesLeft, int otherRange, int stonesThrown){
for( int move=1 ; move<stonesThrown ; move++ ){
int moveRange = codeCount[stonesLeft-move][otherRange];
this.min += moveRange;
this.range -= moveRange;
}
this.range = codeCount[stonesLeft-stonesThrown][otherRange];
}
}
```
**ThrowingStones.java**
```
package stackexchange;
public class ThrowingStones
{
public boolean simulation(int stones, int secret0, int secret1){
// ENCODING
Spy spy0 = new Spy(stones);
Spy spy1 = new Spy(stones);
int[] throwSequence = new int[stones+1];
int turn = 0;
int stonesLeft = stones;
while( true ){
// spy 0 throws
if( stonesLeft==0 ) break;
throwSequence[turn] = spy0.throwStones(stonesLeft, spy1.range, secret0);
stonesLeft -= throwSequence[turn++];
// spy 1 throws
if( stonesLeft==0 ) break;
throwSequence[turn] = spy1.throwStones(stonesLeft, spy0.range, secret1);
stonesLeft -= throwSequence[turn++];
}
assert (spy0.min==secret0 && spy0.range==1 );
assert (spy1.min==secret1 && spy1.range==1 );
// System.out.println(Arrays.toString(throwSequence));
// DECODING
spy0 = new Spy(stones);
spy1 = new Spy(stones);
stonesLeft = stones;
turn = 0;
while( true ){
// spy 0 throws
if( throwSequence[turn]==0 ) break;
spy0.replayThrow(stonesLeft, spy1.range, throwSequence[turn]);
stonesLeft -= throwSequence[turn++];
// spy 1 throws
if( throwSequence[turn]==0 ) break;
spy1.replayThrow(stonesLeft, spy0.range, throwSequence[turn]);
stonesLeft -= throwSequence[turn++];
}
int recovered0 = spy0.min;
int recovered1 = spy1.min;
// check the result
if( recovered0 != secret0 || recovered1 != secret1 ){
System.out.println("error recovering (" + secret0 + "," + secret1 + ")"
+ ", returns (" + recovered0 + "," + recovered1 + ")");
return false;
}
return true;
}
/** verify all possible values */
public void verifyAll(int stones){
int count = 0;
int countOK = 0;
int maxValue = Spy.getMaxValue(stones);
for( int a=1 ; a<=maxValue ; a++ ){
for( int b=1 ; b<=maxValue ; b++ ){
count++;
if( simulation(stones, a, b) ) countOK++;
}
}
System.out.println("verified: " + countOK + "/" + count);
}
public static void main(String[] args) {
ThrowingStones app = new ThrowingStones();
Spy.initCodeCounts(26);
Spy.dispCodeCounts(26);
app.verifyAll(20);
// app.verifyAll(26); // never managed to complete this one...
}
}
```
For reference, the precomputed codeCount array contains the following values:
```
1: [0, 1]
2: [0, 1, 1]
3: [0, 2, 1, 1]
4: [0, 3, 2, 1, 1, 1]
5: [0, 5, 3, 2, 2, 1, 1, 1, 1]
6: [0, 8, 5, 4, 3, 2, 2, 2, 1, 1, 1, 1, 1, 1]
```
This related directly to Peter Taylor's Tk sets. We have:
```
(x,y) in Tk <=> y <= codeCount[x]
```
[Answer]
# ksh/zsh, M = 126
In this simple system, each spy throws binary digits to the other spy. In each throw, the first stone is ignored, the next stones are each bit 0, and the last stone is bit 1. For example, to throw 20, a spy would throw 4 stones (ignore, 0, 2, add 4), then throw 3 stones (ignore, 8, add 16), because 4 + 16 = 20.
The set of numbers is not contiguous. 0 to 126 are in, but 127 is out. (If both spies have 127, they need 28 stones, but they have 26 stones.) Then 128 to 158 are in, 159 is out, 160 to 174 are in, 175 is out, 176 to 182 are in, 183 is out, 184 to 186 is in, 187 is out, and so on.
Run an automatic swap with `ksh spy.sh 125 126`, or run individual spies with `ksh spy.sh spy1 125` and `ksh spy.sh spy2 126`. Here, `ksh` can be ksh93, pdksh or zsh.
EDIT 14 Jun 2014: Fix a problem with some co-processes in zsh. They would idle forever and fail to exit, until the user killed them.
```
(( stones = 26 ))
# Initialize each spy.
spy_init() {
(( wnum = $1 )) # my number
(( rnum = 0 )) # number from other spy
(( rlog = -1 )) # exponent from other spy
}
# Read stone count from other spy.
spy_read() {
read count || exit
(( stones -= count ))
# Ignore 1 stone.
(( count > 1 )) && {
# Increment exponent. Add bit to number.
(( rlog += count - 1 ))
(( rnum += 1 << rlog ))
}
}
# Write stone count to other spy.
spy_write() {
if (( wnum ))
then
# Find next set bit. Prepare at least 2 stones.
(( count = 2 ))
until (( wnum & 1 ))
do
(( wnum >>= 1 ))
(( count += 1 ))
done
(( wnum >>= 1 )) # Remove this bit.
(( stones -= count ))
print $count # Throw stones.
else
# Throw 1 stone for other spy to ignore.
(( stones -= 1 ))
print 1
fi
}
# spy1 writes first.
spy1() {
spy_init "$1"
while (( stones ))
do
spy_write
(( stones )) || break
spy_read
done
print $rnum
}
# spy2 reads first.
spy2() {
spy_init "$1"
while (( stones ))
do
spy_read
(( stones )) || break
spy_write
done
print $rnum
}
(( $# == 2 )) || {
name=${0##*/}
print -u2 "usage: $name number1 number2"
print -u2 " or: $name spy[12] number"
exit 1
}
case "$1" in
spy1)
spy1 "$2"
exit;;
spy2)
spy2 "$2"
exit;;
esac
(( number1 = $1 ))
(( number2 = $2 ))
if [[ -n $KSH_VERSION ]]
then
eval 'cofork() { "$@" |& }'
elif [[ -n $ZSH_VERSION ]]
then
# In zsh, a co-process stupidly inherits its own >&p, so it never
# reads end of file. Use 'coproc :' to close <&p and >&p.
eval 'cofork() {
coproc {
coproc :
"$@"
}
}'
fi
# Fork spies in co-processes.
[[ -n $KSH_VERSION ]] && eval 'coproc() { "$@" |& }'
cofork spy1 number1
exec 3<&p 4>&p
cofork spy2 number2
exec 5<&p 6>&p
check_stones() {
(( stones -= count ))
if (( stones < 0 ))
then
print -u2 "$1 is in trouble! " \
"Needs $count stones, only had $((stones + count))."
exit 1
else
print "$1 threw $count stones. Pile has $stones stones."
fi
}
# Relay stone counts while spies throw stones.
while (( stones ))
do
# First, spy1 writes to spy2.
read -u3 count report1 || mia spy1
check_stones spy1
print -u6 $count
(( stones )) || break
# Next, spy2 writes to spy1.
read -u5 count report2 || mia spy2
check_stones spy2
print -u4 $count
done
mia() {
print -u2 "$1 is missing in action!"
exit 1
}
# Read numbers from spies.
read -u3 report1 || mia spy1
read -u5 report2 || mia spy2
pass=true
(( number1 != report2 )) && {
print -u2 "FAILURE: spy1 put $number1, but spy2 got $report2."
pass=false
}
(( number2 != report1 )) && {
print -u2 "FAILURE: spy2 put $number2, but spy1 got $report1."
pass=false
}
if $pass
then
print "SUCCESS: spy1 got $report1, spy2 got $report2."
exit 0
else
exit 1
fi
```
] |
[Question]
[
# Introduction
The arena is a flatland dotted with skyscrapers, which your enemies use for cover. You and your enemies shoot each other with lasers. All of you carry jet packs, allowing flight.
Which enemies can you hit with your laser, and which are hiding?
# Problem
First, the size of an arena is given by an integer `n` on a single line. The following `n` lines contain `n` integers per line separated by a space. Each integer represents the height of the building at that location. Each building is a rectangular solid, 1 unit by 1 unit by height units.
Next, your location is given on a single line as three floating point numbers `x`, `y`, `z`.
Finally, the number of enemies are given by an integer `m` on a single line. The following `m` lines contain three floating point numbers per line separated by a space. These represent the `x`, `y`, and `z` coordinates of an enemy. The coordinate system is defined as follows:
* `x` is measured from left to right in the city input
* `y` is measured from top to bottom
* `z` is measured from the ground up
For each enemy, if an unobstructed line can be drawn from you to that enemy, output a *positive* integer. Otherwise, output a *negative* integer. Separate outputs with a new line.
# Sample Input
Comments, denoted by '#', are present to help you quickly see what each line does. They will not be present in the actual input.
```
5 # Size of the map
0 0 0 0 0 # Buildings
0 0 0 0 0 # Buildings
4 4 4 4 4 # Buildings
0 0 0 0 0 # Buildings
0 0 0 0 0 # Buildings
2.5 0.0 4.0 # Your location
3 # Number of enemies
2.5 5.0 0.1 # Enemy location
2.5 5.0 5.0 # Enemy location
0.0 2.7 4.5 # Enemy location
```
# Sample output
For the sample input above, we output the following:
```
-1
1
1
```
# Assumptions
* 0 < `n` < 100
* 0 < `m` < 100
* 0 <= `x` <= `n`
* 0 <= `y` <= `n`
* 0 <= `z` < `n`
* Players will not be located on or inside of a corner, edge, or side of a building
* Your line of sight to an enemy will never be tangent to the corner, edge, or side of a building
* A player is not an obstruction
[Answer]
## Perl, ~~301 296~~ 282
**Edit 2:** Actually, competition or not, there is no reason not to golf it a little further. Test it [online](http://ideone.com/R182Pn).
**Edit:** Couple of parentheses gone, simpler regex to check for non-zero integer.
With newlines and indentation for readability:
```
sub i{<>=~/\S+/g}
@b=map[i],@r=0..<>-1;
print.1<=>(map{
@a[1,0,2,4,3]=@a;
@b=map{$i=$_;[map$b[$_][$i],@r]}@r;
grep$a[3]
&&($k=(($x=$_)-$a[0])/$a[3])**2<=$k
&&pop[sort map@{$b[$_]}[$x-!!$x,$x],
($_=$a[1]+$k*$a[4]),$_-/^\d+$/]
>=$a[2]+$k*$a[5]
,@R=@r
}@a=map$_-shift@v,i,@u=@v=@$_),$/for([i])x<>
```
It requires `5.14` because of scalar (array reference) argument to `pop`.
[Answer]
# Python 2.7 - ~~429~~ ~~420~~ ~~308~~ 308 chars
I thought of this challenge more of as a math problem than a code golf problem, so don't be too harsh to me if I missed some obvious optimizations. Anyways, here is the code:
```
b=lambda:raw_input().split()
m=map
d=range(input())
h=[m(int,b())for _ in d]
x,y,z=m(float,b())
for e,f,g in[m(float,b())for _ in[1]*input()]:o=lambda x,y,u,v,i,j:i<=x+u/v*(j+1-y)<=i+1<[]>z+(g-z)/v*(j+1-y)<=max(h[i][j:j+2])if v else 0;print 1-2*any(o(x,y,e-x,f-y,j,i)+o(y,x,f-y,e-x,i,j)for j in d for i in d)
```
This should work for edge and corner cases (pun unintended) and is pretty solid. Ouput for the provided example:
```
-1
1
1
```
And here is a "short" explanation:
```
fast_read = lambda : raw_input().split() # define a helper
# m = map another helper
grid_range = range(input())
houses = [map(int, fast_read()) for _ in grid_range]
# 'map(int,...)' is a shorter version of '[int(a) for a in ...]'
pos_x,pos_y,pos_z = map(float, fast_read()) # read the player position
# the following loops through all enemy coordinates
for ene_x, ene_y, ene_z in [map(float,fast_read()) for _ in[1]*input()]:
vec_z = ene_z - pos_z
# is_hit macro uses vector math to detemine whether we hit a specific wall
# wallhit -> 1
# no wallhit -> 0
is_hit = lambda pos_x, pos_y, vec_x, vec_y, co_x, co_y:\
(co_x <= pos_x + vec_x/vec_y * (co_y + 1 - pos_y) <= co_x + 1 # check if hit_x is good
< [] > # an effective and
pos_z + (ene_z - pos_z)/vec_y * (co_y + 1 - pos_y) <= max(houses[co_x][co_y:co_y + 2]) # check if hit_z is good
if vec_y else 0) # if vec_y is 0 we can't hit the wall parallel to y
print (.5 - # can hit -> 0.5 - 0 = 0.5, hit -> 0.5 - 1 = -0.5
any( # if we hit any wall
# we swap x and y-coordinate because we read them "incorrect"
is_hit(pos_x, pos_y, ene_x-pos_x, ene_y-pos_y, cur_y, cur_x) # check for hit in x-direction
+ # effective 'or'
is_hit(pos_y, pos_x, ene_y-pos_y, ene_x-pos_x, cur_x, cur_y) # check for hit in y-direction
for cur_y in grid_range # loop y
for cur_x in grid_range)) # loop x
```
I guess this is full of flaws. Btw I saved chars at nesting (first level is one space, second one tab, then one tab and a space...).
I hope after all this answer can point to the way to do it.
[Answer]
# C - 2468
Not golfed at all, but hopefully it's a starting point for more interesting implementations. The implementation of `intersect` is cribbed heavily from [Adrian Boeing](http://adrianboeing.blogspot.com/2010/02/intersection-of-convex-hull-with-line.html). His pseudo-code was incomplete, but his explanation of the math was invaluable. The basic idea is that you take a line from the player to the target and clip it against all the walls of each building, updating the length for each wall. The remaining length is the portion inside the building, so if it's zero, there was no intersection.
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
float x;
float y;
float z;
} vec3;
float
dot(vec3 a, vec3 b)
{
return a.x * b.x + a.y * b.y + a.z * b.z;
}
vec3
scale(float s, vec3 a)
{
vec3 r;
r.x = s * a.x;
r.y = s * a.y;
r.z = s * a.z;
return r;
}
vec3
add(vec3 a, vec3 b)
{
vec3 r;
r.x = a.x + b.x;
r.y = a.y + b.y;
r.z = a.z + b.z;
return r;
}
int
intersect(vec3 a, vec3 b, vec3 *normals, vec3 *points, int nnormals)
{
vec3 ab = add(b, scale(-1, a));
float tfirst = 0;
float tlast = 1;
int i;
for(i = 0; i < nnormals; i++)
{
float d = dot(normals[i], points[i]);
float denom = dot(normals[i], ab);
float dist = d - dot(normals[i], a);
float t = dist / denom;
if(denom > 0 && t > tfirst)
{
tfirst = t;
}
else if(denom < 0 && t < tlast)
{
tlast = t;
}
}
return tfirst < tlast ? 1 : 0;
}
const vec3 N = {0,-1,0};
const vec3 S = {0,1,0};
const vec3 W = {-1,0,0};
const vec3 E = {1,0,0};
const vec3 D = {0,0,-1};
int
main(void)
{
vec3 normals[5];
vec3 player;
vec3 *targets;
int i;
int j;
vec3 *buildings;
vec3 *b;
int nbuildings = 0;
int n;
int m;
char line[300];
normals[0] = N;
normals[1] = S;
normals[2] = W;
normals[3] = E;
normals[4] = D;
fgets(line, 300, stdin);
n = atoi(line);
/*5 sides for each building*/
buildings = calloc(n * n * 5, sizeof(*buildings));
b = buildings;
for(i = 0; i < n; i++)
{
char *z;
fgets(line, 300, stdin);
for(j = 0; j < n && (z = strtok(j ? NULL : line, " \n")) != NULL; j++)
{
vec3 bottom;
vec3 top;
if(z[0] == '0') continue;
nbuildings++;
bottom.x = j;
bottom.y = i;
bottom.z = 0;
top.x = j + 1;
top.y = i + 1;
top.z = atoi(z);
b[0] = top;
b[1] = bottom;
b[2] = top;
b[3] = bottom;
b[4] = top;
b += 5;
}
}
fgets(line, 300, stdin);
player.x = atof(strtok(line, " "));
player.y = atof(strtok(NULL, " "));
player.z = atof(strtok(NULL, " \n"));
fgets(line, 300, stdin);
m = atoi(line);
targets = calloc(m, sizeof(*targets));
for(i = 0; i < m; i++)
{
int hit = 1;
fgets(line, 300, stdin);
targets[i].x = atof(strtok(line, " "));
targets[i].y = atof(strtok(NULL, " "));
targets[i].z = atof(strtok(NULL, " \n"));
for(j = 0; j < nbuildings; j++)
{
b = &buildings[j * 5];
if(intersect(player, targets[i], normals, b, 5) == 1)
{
hit = 0;
break;
}
}
printf("%d\n", hit ? 1 : -1);
}
free(buildings);
free(targets);
return 0;
}
```
] |
[Question]
[
Write a program to determine if the input polygon is [convex](http://en.wikipedia.org/wiki/Convex_and_concave_polygons). The polygon is specified with one line containing *N*, the number of vertices, then *N* lines containing the *x* and *y* coordinates of each vertex. The vertices will be listed clockwise starting from an arbitrary vertex.
## example 1
### input
```
4
0 0
0 1
1 1
1 0
```
### output
```
convex
```
## example 2
### input
```
4
0 0
2 1
1 0
2 -1
```
### output
```
concave
```
## example 3
### input
```
8
0 0
0 1
0 2
1 2
2 2
2 1
2 0
1 0
```
### output
```
convex
```
*x* and *y* are integers, *N<1000*, and *|x|,|y|<1000*. You may assume that the input polygon is simple (none of the edges cross, only 2 edges touch each vertex). Shortest program wins.
[Answer]
# J, 105
```
echo>('concave';'convex'){~1=#=(o.1)([:>-.~)(o.2)|3([:-/12 o.-@-/@}.,-/@}:)\(,2&{.)j./"1}.0&".;._2(1!:1)3
```
Passes all three tests above.
**Edit:** (111->115) Handle co-linear points by eliminating angles of pi. Gained a few characters elsewhere.
**Edit:** (115->105) Less dumb.
Explanation for the J-impaired:
* `(1!:1)3` read STDIN to EOF. (I think.)
* `0&".;._2` is a nice idiom for parsing this kind of input.
* `j./"1}.` lop off first line of input (N 0) and convert pairs to complexes.
* `(,2&{.)` tack first two points onto the end of the list.
* `3(f)\` applies f to sliding window of length 3 (3 points for an angle)
* `[:-/12 o.-@-/@}.,-/@}:` is a verb that transforms each 3 points into an angle between -pi and pi.
+ `-@-/@}.,-/@}:` produces (p1 - p2),(p3 - p2). (Recall that these are complexes.)
+ `12 o.` gives an angle for each complex.
+ `[:-/(...)` gives the difference of the two angles.
* `(o.1)([:>-.~)(o.2)|` mod 2 pi, eliminate angles of pi (straight segments), and compare to pi (greater than, less than, doesn't matter unless the points are supposed to be wound in one direction).
* `1=#=` if all those comparison result 1 or 0 (With self-classify. This seems dumb.)
* `echo>('concave';'convex'){~` print convex.
[Answer]
## Python - 149 chars
```
p=[map(int,raw_input().split())for i in[0]*input()]*2
print'ccoonncvaevxe'[all((a-c)*(d-f)<=(b-d)*(c-e)for(a,b),(c,d),(e,f)in zip(p,p[1:],p[2:]))::2]
```
[Answer]
## Ruby 1.9, 147 133 130 124 123
```
gets
puts ($<.map{|s|s.split.map &:to_i}*2).each_cons(3).any?{|(a,b),(c,d),(e,f)|(e-c)*(d-b)<(d-f)*(a-c)}?:concave: :convex
```
[Answer]
### scala: 297 chars
```
object C{class D(val x:Int,val y:Int)
def k(a:D,b:D,c:D)=(b.y-a.y)*(c.x-b.x)>=(c.y-b.y)*(b.x-a.x)
def main(a:Array[String]){val s=new java.util.Scanner(System.in)
def n=s.nextInt
val d=for(x<-1 to n)yield{new D(n,n)}print((true/:(d:+d.head).sliding(3,1).toList)((b,t)=>b&&k(t(0),t(1),t(2))))}}
```
] |
[Question]
[
Your task is, given `x`, output `2*x`. Easy right!? But there's a catch: `x` will be given as a (possibly infinite) [continued fraction](https://en.wikipedia.org/wiki/Continued_fraction "Continued Fraction Wikipedia Page"), and the output must be a continued fraction. The input is guaranteed to be a real algebraic number whose degree is at most 2.
**Input**: The continued fraction of `x`. This is split into 3 parts: the integer part, the prefix, and the repeating part. The integer part consists of a single integer. The prefix and repeating part are (possibly empty) arrays of positive integers which describe the prefix and repeating part of the continued fraction. For example, the input `(3, [1], [2, 4])` represents the continued fraction `[3; 1, 2, 4, 2, 4, ...]`.
If the repeating part is empty, that indicates a rational number. For example, `(3, [1, 2], [])` represents `[3; 1, 2] = 11/3`. You must accept both forms of a rational number (i.e. `(3, [1, 1, 1], [])`, which is `[3; 1, 1, 1] = 11/3` should also be valid input).
**Output**: Output the continued fraction of twice the input, in the same format as the input. If the output is rational, you may output either form of the continued fraction. As long as the answer is equivalent to the correct answer, it is fine; no "compression" is necessary, so the infinite part might be "unrolled" a little (e.g. `[1; 4, 2, 3, 2, 3...]` may be written `(1, [4], [2, 3])` or `(1, [4, 2, 3], [2, 3])`). All answers must be exact.
**Test cases**: The exact form column is given for convenience.
```
Input Exact Form Output
(0, [] []) 0 (0, [] []) or (-1, [1], [])
(-5, [1, 1], []) -4.5 (-9, [], []) or (-10, [1], [])
(3, [1, 2], []) 11/3 (7, [3], []) or (7, [2, 1], [])
(1, [], [2]) sqrt(2) (2, [], [1, 4])
(-1, [2], [2, 1]) -1/sqrt(3) (-2, [1, 5], [2, 6])
```
And finally a slightly larger test case to ensure precision: `(0, [1], [6, 1, 3, 1, 42, 1, 3, 1, 6, 2]) --> (1, [], [1, 2, 1, 8, 1, 20, 1, 8, 1, 2, 1, 2])`.
Shortest code wins!
**Hint**: You can perform arithmetic in a rather straightforward manner on continued fractions as described [here](https://perl.plover.com/classes/cftalk/TALK/slide028.html "Arithmetic on Continued Fractions"). Doubling a continued fraction is just a special case of this algorithm (although the tricky part may be to find when the continued fraction repeats).
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 44 bytes
```
ContinuedFraction[2FromContinuedFraction@#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zk/ryQzrzQ1xa0oMbkkMz8v2sitKD8XQ9hBOVbtf5pDtaFOtVFt7f//ugVFmXklAA "Wolfram Language (Mathematica) – Try It Online")
Mathematica has a builtin! Yay! Mathematica's builtin is super long. Aww.
Mathematica's continued fractions look like `{integer, ...prefix, {...repeating}}`
-1 thanks to JungHwan Min
[Answer]
# JavaScript (ES6), 267 bytes
```
(n,f,r)=>eval(`f=[0,...f];e=i=[0,2,1,0];o=j=[];k=[];m={};while([a,b,c,d]=e,c|d&&o)i*m[s=i+m+(e=c*d&&(q=a/c|0)==(b/d|0)?(o.push(q),[c,d,a-c*q,b-d*q]):1/(++i,[p,...f]=f+f?f:(i=r[0],r),p)?[b,a+b*p,d,c+d*p]:[b,b,d,d])]?k+(o=k)?o=0:(m={})[s]=1:m[s]=1;[2*n+j.shift(),j,k]`)
```
Accepts 3 arguments (n = integer part, f = prefix, r = repeating part). Outputs
the three parts in an array. [Try it online!](https://tio.run/##XU5dc4IwEHzvr8iTXsiJgK0PMCc/JJMZw1eNggGhdsba324Dth3bh1xu93Zvb6/Pus9Pph0WR1uUtwvd4IgVnjhtyrOuYVuRDND3/UolJZkRRBhioBJLe5IqOYyloY/P5H1n6hKkxgxzLBSVmF@L2cxy4zWyJyMaASXlnuOgI73MrwEngmxZuCYF67dv/Q46jtLZUS9yr8NsUXid4nG4BCEMyvZ@ClWiSqsYDJ1koNy12PJUZqhF5rXOnIvCa1XsmMyhQnGVHgRYOvDUUhDDeC@XvaIwbqYvkZF3FHu/35lqAI57PKgtvw2MGLhEzRltGOT22Nu69Gv7ChrZnDZzZJe7gOPjlPOnAQJkUo1vBIsX14XIwl9mdSei/8QfUfi9I7ovCad2LKPoJ2SSryfnaqrP0QNYjxn89gU "JavaScript (Node.js) – Try It Online")
# Explanation
It's a fairly direct implementation of the algorithm for computing
continued fraction arithmetic linked in the challenge [here](https://perl.plover.com/classes/cftalk/TALK/slide028.html). Repeating terms are handled by storing intermediate matrices in a lookup table, waiting for a duplicate, and outputting the terms until the next appearance of that duplicate. It's inelegant and nearly doubles the bytes needed to handle continued fractions, but I could not think of a better alternative.
The leading term is computed separately to ensure that negative continued
fractions retain positive values for all terms barring the first.
To prevent false positives when awaiting a repeated cycle, the lookup table
stores the data as follows: `<index of input repeating part><delimiter><matrix values>`.
Note that the golfed version uses `eval` to save 1 byte.
```
(n, f, r) => {
f = [0, ...f]; // use a 0 to chop off the integer part
e = i = [0,2,1,0]; // e: matrix with starting values to handle doubling
// 0 + 2x
// ------
// 1 + 0x
// i: tracks index of repeating part; until the function loops through the
// repeating part, i is equivalent to NaN
o = j = []; // o: alias for group of terms currently being computed
// j: output array of non-repeating terms
k = []; // k: output array of repeating terms
m = {}; // lookup table
while ([a,b,c,d] = e, c | d && o) // destructure matrix
// c | d stops loop if both a/c and b/d equal infinity
i * m[s = i + m + ( // m also serves as the delimiter; JS will stringify it as "[object Object]"
// if i equals a value that is coerced to NaN, this multiplication
// will be falsy
e = c * d && (q=a/c|0) == (b/d|0) // checks if either c or d is 0 to avoid converting an Infinity value to 0 using the bitwise or
? (o.push(q), [c, d, a - c*q, b - d*q]) // append the output term and compute the new matrix
: 1/(++i, [p, ...f] = f+f ? f : (i=r[0], r), p) // 1/(... p) checks if p is a valid number
// f+f is a short way to check length of f; if f is an empty
// array, f+f = '' (which is falsy)
// if f is empty, try to replace with r
// if r is empty, the value of i will be set to undefined (e.g. NaN)
? [b, a + b*p, d, c + d*p]
: [b,b,d,d]
)
] // checks if matrix has been cached in lookup table
? k+(o=k) // if the repeating part of the output has a value...
? o=0 // o serves as a flag to halt the loop
: (m={})[s] = 1 // reset lookup table to only hold the first duplicate matrix
: m[s] = 1; // otherwise flag a matrix as seen
return [2*n + j.shift(), j, k] // add the doubled integer part to the first term
}
```
] |
[Question]
[
You are in a one-floor dungeon. There is a treasure which is protected by locked doors. Doors can be opened by finding the corresponding keys. Your goal is to find the shortest path to the treasure.
## Input
Input will be a two-dimensional grid representing the initial layout of the dungeon.
```
###########
#$ # g#
# # ####
###G## #
# ####C#
#c @ #
###########
```
This is you: `@`
These are walls: `#`
This is the treasure: `$`
Locked doors are capital letters: `A`...`Z`
Each door has a corresponding lower-case key: `a`...`z`
* There will always be one `@` and one `$`.
* The dungeon will always be rectangular.
* It is not guaranteed that the outside edge of the dungeon is a wall. This is a valid dungeon:
```
$
A##
@ a
```
* It is not guaranteed that the treasure is reachable. Some dungeons may not be solvable.
* There may be doors without a key, and there may be keys that do not open any doors.
* There will never be duplicate doors or keys.
## Output
Your program should print a sequence of `R`, `L`, `U`, `D` (or 4 other distinct symbols) to represent the *shortest* possible path to the treasure. Here, `RLUD` stands for right, left, up, and down, respectively. If there are multiple shortest paths, your program only needs to print one of them.
* You cannot move onto a wall.
* You cannot move outside of the dungeon boundaries.
* You cannot move onto a door without picking up it's key.
* Move onto a key to pick it up.
* It is not necessary to open every single door.
If it is not possible to reach the treasure through a valid sequence of moves, then your program must terminate without printing anything. (A trailing newline is allowed.)
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the answer with the lowest byte count wins.
## Test Cases
Each test case will have the height and width of the dungeon on the first line, and one possible path, with the optimal number of moves, on the last line.
```
1 2
@$
R (1)
3 3
$
#Z#
@ z
RRLUUR (6)
3 5
c#d#$
#C#D
@
UUDDRRUUDDRRUU (14)
7 16
c # b # ###@
### #
A ##### ####
d # e
B ## #####
### C ##
# a DE $
RDDDDDDL (8)
16 37
#####################################
# #ijk #a M ##m## # # R #
# # # # # ####
###J#### ############# ### # P b#
#e N h # ####
########## ########### ###### #
# # # $ # # # ####
# D H # # # Q f#
# EcF # #####A##### ###### ####
# G # #####B##### # #
# K #####C##### ############
# # #
########### # #### ##### ####
# # p # # n # #
# d # @ # o# r #
#################Z###################
UUULLLLLLDDLLLDLLLLLLRRRRRRRRRUUURRRRRRRRRRRRRRRDDLLRRUULLUUUUUUURRRRRUURRRDRRRLLLLULLLLLDDLLLLUULLLUDLLLLLULLLRRRRRDRRRRRRDDLLLLLLLLLLLLDDDLLLLLLLDURRRRRRRRDDDDRRRRRRUUUUU (172)
```
It is not possible to reach the treasure in the following dungeons. For these test cases, there should be no output.
```
1 3
@#$
7 11
#a#j#$#i#f#
# #E#F#c#H#
# #K#D#A#G#
# #
#C#J# #I#B#
#h#d# #L#g#
#l#e#@#b#k#
10 25
#########################
# fgh # # c B b # #
$ # # # # # #
###### # ##H###E## #
# #
# ######### ##e##
Z @ D y # # #
# ######### F C#
# G # Ad#
#########################
```
The following snippet can be used to validate answers.
```
function run() {var dungeonText = document.getElementById("dungeon").value;var dungeonLines = dungeonText.split("\n");var height = dungeonLines.length;var width = dungeonLines[0].length;var dungeon = new Array(height);for (i = 0; i < dungeon.length; i++) {var dungeonLine = dungeonLines[i];if (dungeonLine.length != width) {return error("The dungeon is not rectangular");} dungeon[i] = dungeonLines[i].split("");} var movesText = document.getElementById("moves").value;var moves = movesText.trim().split("");var moveCount = moves.length;var rowAt, colAt;for (r = 0; r < dungeon.length; r++) {for (c = 0; c < dungeon[r].length; c++) {if (dungeon[r][c] == '@') {rowAt = r;colAt = c;}}} var treasure = false;while (moves.length > 0) {var move = moves[0];var row = rowAt,col = colAt;switch (move) {case 'R':col++;break;case 'L':col--;break;case 'U':row--;break;case 'D':row++;break;default:return print(dungeon, moves, "Invalid move");} if (row < 0 || col < 0 || row >= height || col >= width) {return print(dungeon, moves, "Out of bounds");} var target = dungeon[row][col];if (target.match(/[A-Z#]/)) {return print(dungeon, moves, "Path blocked");} if (target.match(/[a-z]/)) {var door = target.toUpperCase();for (r = 0; r < dungeon.length; r++) {for (c = 0; c < dungeon[r].length; c++) {if (dungeon[r][c] == door) {dungeon[r][c] = ' ';}}}} if (target == '$') {treasure = true;} dungeon[row][col] = '@';dungeon[rowAt][colAt] = '.';rowAt = row;colAt = col;moves.shift();} if (treasure) {print(dungeon, moves, "Got the treasure in " + moveCount + " moves!");} else {print(dungeon, moves, "Failed to reach treasure");}} function error(message) {var result = document.getElementById("result");result.innerHTML = message;} function print(dungeon, moves, message) {var output = message + "\n";for (r = 0; r < dungeon.length; r++) {for (c = 0; c < dungeon[r].length; c++) {output += dungeon[r][c];} output += "\n";} for (i = 0; i < moves.length; i++) {output += moves[i];} var result = document.getElementById("result");result.innerHTML = output;}
```
```
Dungeon:<br/><textarea id="dungeon" name="dungeon" rows="20" cols="40"></textarea><br/>Moves:<br/><textarea id="moves" name="moves" cols="40"></textarea><br/><button id="run" name="run" onclick="run();">Start</button><br/><br/>Result:<br/><textarea id="result" name="result" rows="20" cols="40" disabled></textarea><br/>
```
[Answer]
# Perl, ~~157~~ ~~152~~ 151 bytes
Includes +4 for `-p0` (cannot be counted as just an extension of `-e` because it uses `'` in several places)
Run with the maze on STDIN:
```
./keymaze.pl < maze.txt
```
`keymaze.pl`:
```
#!/usr/bin/perl -p0
1until$n{map/\n/&&"L1R-1U@+D-@+"=~s%\pL%$t=$1{$_}.$&;pos=$^H=-$'+s'@' '*"@-",s/\G[a-z\$ ]/\@/+s/$&/ /i?/\$/?$1{$_}:$\||=$t:0for"$_"%reg,$_,%1}++.$\}{
```
Replace `\n` and `^H` by their literal versions for the claimed score. Needs about 1 hour and a bit less than 2 Gigabytes on my machine to solve the big maze.
[Answer]
# Java 8 - ~~1282~~ ~~1277~~ ~~1268~~ ~~1259~~ 1257 bytes
This passes all the tests. However, for some of them it gives some slightly different results (when there is more than one optimal way, which isn't a problem).
For the 4th test, it gives this:
```
RDDDDDLD
```
Instead of this:
```
RDDDDDDL
```
For the 5th test, it gives this:
```
LLLLUUULLDDLLLLDLLLLLRRRRRRURRRUURRRRRRRRRRRRRRRDDLLRRUULLUUUUUUURRRRRUURRRDRRRLLLLULLLDDLLLLLLUULLLUDLLLLLULLLRRRRRDRRRRRRDDLLLLLLLLLLLLDDDLLLLLLLDURRRRRRRRDDDDRRRRRRUUUUU
```
Instead of this:
```
UUULLLLLLDDLLLDLLLLLLRRRRRRRRRUUURRRRRRRRRRRRRRRDDLLRRUULLUUUUUUURRRRRUURRRDRRRLLLLULLLLLDDLLLLUULLLUDLLLLLULLLRRRRRDRRRRRRDDLLLLLLLLLLLLDDDLLLLLLLDURRRRRRRRDDDDRRRRRRUUUUU
```
# Golfed version:
```
import java.util.*;class G{int y,w,h,p;String C="",S,o,v;Map m=new HashMap();String q(int a){return a<1?"":"#"+q(a-1);}public static void main(String[]a)throws Exception{new G(new String(java.nio.file.Files.readAllBytes(new java.io.File(a[0]).toPath())));}G(String a){w=(a+"\n").indexOf(10)+3;String t=q(w)+a.replace("\n","##")+q(w);for(char j=65,k=97;j<91;j++,k++){if(t.indexOf(j)*t.indexOf(k)<0)t=t.replace(j,'#').replace(k,' ');}h=t.length()/--w;S=v=q(w*h);t=g(t);if(t!=v)System.out.print(t);}String g(String t){o=(String)m.get(t);if(o!=null)return o;if(t.indexOf(36)<0){if(S.length()>C.length())S=C;return"";}String d="";int f=t.indexOf(64),M[]=new int[w*h],N[]=new int[w*h];Queue<Integer>s=new ArrayDeque();s.add(f);while(!s.isEmpty()){y=s.poll();int[]P={y+1,y-1,y+w,y-w};for(int v:P){char j=t.replaceAll("[A-Z]","#").charAt(v);if(v!=f&j!=35&(N[v]<1|M[y]+1<M[v])){M[v]=M[y]+1;N[v]=y;s.add(v);if(j>32)d+=j;}}}o=d.chars().distinct().mapToObj(e->{String z="",c=C;for(y=t.indexOf(e);y!=f;y=N[y]){p=y-N[y];z=(p==w?"D":p==-w?"U":p==1?"R":"L")+z;}if(S.length()<=(C+z).length())return v;C+=z;String u=g(t.replace('@',' ').replace((char)e,'@').replace((char)(e-32),' '));C=c;return u==v?v:z+u;}).reduce(v,(a,b)->a.length()<b.length()?a:b);m.put(t,o);return o;}}
```
# Ungolfed version
Features:
* Informative variable names;
* Explicative and detailed comments;
* Proper identation.
```
import java.util.*;
/**
* @author Victor Stafusa
*/
class TreasureHunt {
// Note: on normal (non-golfing programming) those variables should have been scoped properly.
// They are instance variables just for golfing purposes.
// On the golfed version, nextCellIndex and waypointCellIndex are the same variable. The same also happens to cachedValue and result. This happens is for golfing purposes.
int nextCellIndex,
width,
height,
waypointCellIndex,
cellIndexDifference;
String previousPath = "",
bestSolutionSoFar,
cachedValue,
result,
failureFlag;
// This should be Map<String, String>, but the generics were omitted for golfing.
// It is needed to avoid recomputing long partial dungeons (i.e. dynamic programming).
Map cachedResults = new HashMap();
// Returns a lot of hashes. Like aLotOfHashes(7) will return "#######".
String aLotOfHashes(int howMany) {
return howMany < 1 ? "" : "#" + aLotOfHashes(howMany - 1);
}
// Here is where our program starts.
public static void main(String[] args) throws Exception {
// Read all the content of the file from args[0] and put it into a string.
// Pass that string as a parameter to the constructor.
// The instance itself is useless - it is just a golfing trick.
new TreasureHunt(new String(java.nio.file.Files.readAllBytes(new java.io.File(args[0]).toPath())));
}
// Pre-processs the source in order to format it in the way that we want:
// * No separators between rows. It uses the (row * width + column) formula, so no separators are needed.
// * An extra layer of wall is added in all sides. This naturally fix up problems about walking out of the edges of the board, wrapping-around or acessing invalid array indexes.
// This is a constructor just for golfing purposes. Its instances are worthless.
TreasureHunt(String originalSource) {
// Finds the width by searching the first line-feed.
// If there is just one line and no line-feed, the [+ "\n"] will ensure that it will not break.
// The [+ 3] is because we will add a layer of walls around, so it will be widen by one cell in the left and one in the right (which is +2).
// We still get one more in the width that will be decremented later to use that in the aLotOfHashes method below.
// 10 == '\n'.
width = (originalSource + "\n").indexOf(10) + 3;
// Add a layer of walls in the top and in the bottom (using a lot of hashes for that).
// Replaces the line-feed by a pair of walls, representing the rightmost wall of a row and the leftmost row of the following row.
// Since there is no line-feed before the first line nor after the last line, we add more two walls to fill those.
String newSource = aLotOfHashes(width) + originalSource.replace("\n", "##") + aLotOfHashes(width);
// Remove the keys without door (replaces them as blank spaces) and the doors without keys (replaces them with walls.
// This way, the resulting dungeon will always have matching keys and doors.
// 65 == 'A', 97 == 'a', 91 == 'z'+1
for (char door = 65, key = 97; door < 91; door++, key++) {
// Now a little math trick. For each key or door, we find an index. If the key or door exist, it will be a positive number. Otherwise it will be negative.
// The result will never be zero, because the zeroey position is filled with part of the layer of wall that we added.
// If only one of the key and the door exist, the multiplication will be the product of two numbers with opposite signals, i.e. a negative number.
// Otherwise (both exists or both don't), then the product will be positive.
// So, if the product is negative, we just remove the key and the door (only one of them will be removed of course, but we don't need to care about which one).
if (newSource.indexOf(door) * newSource.indexOf(key) < 0) {
newSource = newSource.replace(door, '#').replace(key, ' ');
}
}
// Knowing the source length and the width (which we fix now), we can easily find out the height.
height = newSource.length() / --width;
// Creates a special value for signaling a non-existence of a path. Since they are sorted by length, this must be a sufficiently large string to always be unfavoured.
bestSolutionSoFar = failureFlag = aLotOfHashes(width * height);
// Now, do the hard work to solve the dungeon...
// Note: On the golfed version, newSource and solution are the same variable.
String solution = solvingRound(newSource);
// If a solution is found, then show it. Otherwise, we just finish without printing anything.
// Note: It is unsafe and a bad practice to compare strings in java using == or != instead of the equals method. However, this code manages the trickery.
if (solution != failureFlag) System.out.print(solution);
}
// This does the hard work, finding a solution for a specific dungeon. This is recursive, so the solution of a dungeon involves the partial solution of the dungeon partially solved.
String solvingRound(String dungeon) {
// To avoid many redundant computations, check if this particular dungeon was already solved before. If it was, return its cached solution.
cachedValue = (String) cachedResults.get(dungeon);
if (cachedValue != null) return cachedValue;
// If there is no treasure in the dungeon (36 == '$'), this should be because the adventurer reached it, so there is no further moves.
if (dungeon.indexOf(36) < 0) {
if (bestSolutionSoFar.length() > previousPath.length()) bestSolutionSoFar = previousPath;
return "";
}
String keysOrTreasureFound = ""; // Initially, we didn't found anything useful.
int adventurerSpot = dungeon.indexOf(64), // 64 == '@', find the cell index of the adventurer.
cellDistance[] = new int[width * height],
previousWaypoint[] = new int[width * height];
// Use a queue to enqueue cell indexes in order to floodfill all the reachable area starting from the adventurer. Again, screw up the proper user of generics.
Queue<Integer> floodFillQueue = new ArrayDeque();
floodFillQueue.add(adventurerSpot); // Seed the queue with the adventurer himself.
// Each cell thies to populate its neighbours to the queue. However no cell will enter the queue more than once if it is not featuring a better path than before.
// This way, all the reachable cells will be reached eventually.
while (!floodFillQueue.isEmpty()) {
nextCellIndex = floodFillQueue.poll();
// Locate the four neighbours of this cell.
// We don't need to bother of checking for wrapping-around or walking into an invalid cell indexes because we added a layer of walls in the beggining,
// and this layer of wall will ensure that there is always something in each direction from any reachable cell.
int[] neighbourCells = {nextCellIndex + 1, nextCellIndex - 1, nextCellIndex + width, nextCellIndex - width};
// For each neighbouring cell...
for (int neighbourCellIndex : neighbourCells) {
// Find the cell content. Considers doors as walls.
char neighbourCellContent = dungeon.replaceAll("[A-Z]", "#").charAt(neighbourCellIndex);
if (neighbourCellIndex != adventurerSpot // If we are not going back to the start ...
& neighbourCellContent != 35 // ... nor walking into a wall or a door that can't be opened (35 == '#') ...
& (previousWaypoint[neighbourCellIndex] < 1 // ... and the neighbour cell is either unvisited ...
| cellDistance[nextCellIndex] + 1 < cellDistance[neighbourCellIndex])) // ... or it was visited before but now we found a better path ...
{ // ... then:
cellDistance[neighbourCellIndex] = cellDistance[nextCellIndex] + 1; // Update the cell distance.
previousWaypoint[neighbourCellIndex] = nextCellIndex; // Update the waypoint so we can track the way from this cell back to the adventurer.
floodFillQueue.add(neighbourCellIndex); // Enqueue the cell once again.
if (neighbourCellContent > 32) keysOrTreasureFound += neighbourCellContent; // If we found something in this cell (32 == space), take a note about that.
}
}
}
// Brute force solutions chosing each one of the interesting things that we found and recursively solving the problem as going to that interesting thing.
// Warning: This has an exponential complexity. Also, if we found something interesting by more than one path, it will compute that redundantly.
result = keysOrTreasureFound.chars().distinct().mapToObj(keyOrTreasure -> {
String tracingWay = "", savedPreviousPath = previousPath;
// From our keyOrTreasure, trace back the path until the adventurer is reached, adding (in reverse order) the steps needed to reach it.
for (waypointCellIndex = dungeon.indexOf(keyOrTreasure); waypointCellIndex != adventurerSpot; waypointCellIndex = previousWaypoint[waypointCellIndex]) {
// Use the difference in cell indexes to see if it is going up, down, right or left.
cellIndexDifference = waypointCellIndex - previousWaypoint[waypointCellIndex];
tracingWay = (cellIndexDifference == width ? "D" : cellIndexDifference == -width ? "U" : cellIndexDifference == 1 ? "R" : "L") + tracingWay;
}
// If this path is going to surely be longer than some other path already found before, prune the search and fail this path.
if (bestSolutionSoFar.length() <= (previousPath + tracingWay).length()) return failureFlag;
// Prepare for recursion, recording the current path as part of the next level recursion's previous path.
previousPath += tracingWay;
// Now that we traced our way from the adventurer to something interesting, we need to continue our jorney through the remaining items.
// For that, create a copy of the dungeon, delete the door of the key that we found (if it was a key),
// move the adventurer to the thing that we just found and recursively solve the resulting simpler problem.
String nextRoundPartialSolution = solvingRound(dungeon
.replace('@', ' ') // Remove the adventurer from where he was...
.replace((char) keyOrTreasure, '@') // ... and put him in the spot of the key or treasure.
.replace((char) (keyOrTreasure - 32), ' ')); // ... and if it was a key, delete the corresponding door ([- 32] converts lowercase to uppercase, won't do anything in the case of the treasure).
// Recursion finished. Now, get back the previous path of the previous recursion level.
previousPath = savedPreviousPath;
// If the subproblem resulted in a failure, then it is unsolvable. Otherwise, concatenates the subproblem solution to the steps that we took.
return nextRoundPartialSolution == failureFlag ? failureFlag : tracingWay + nextRoundPartialSolution;
// From all the paths we took, choose the shorter one.
}).reduce(failureFlag, (a, b) -> a.length() < b.length() ? a : b);
// Now that we have the result of this recursion level and solved this particular dungeon instance,
// cache it to avoid recomputing it all again if the same instance of the dungeon is produced again.
cachedResults.put(dungeon, result);
return result;
}
}
```
# Taking input
To run it, try this:
```
javac G.java
java G ./path/to/file/with/dungeon.txt
```
Or if you are running the ungolfed version, replace the `G`'s with `TreasureHunt`.
The file should contain the dungeon. The input should **not** end with a line-feed. Further, it only accepts line-ends in the `\n` format. It won't work with `\r\n` or with `\r`.
Also, it does not validates or sanitizes the input. If the input is malformed, then the behaviour is undefined (likely to throw an exception). If the file can't be found, then an exception will be thrown.
# Remarks
My first implementation somewhere near 1100 bytes could not solve the 5th test case in reasonable time. The reason for that is because my implementation it brute-forces all the possible permutations of collectible items (i.e. the keys and the treasure) that are acessible (i.e. not locked in an inacessible room).
In the worst case, with all the 26 keys and the treasure, this would be 27! = 10,888,869,450,418,352,160,768,000,000 different permutations.
The OP did not specified that the answer should be something that runned in reasonable time. However, I consider that this is a loophole that I would not like to exploit. So, I decided to make it run in acceptable time for all the test cases. In order to achieve that, my revised program features pruning in search paths that are proved to be worse than some already know solution. Further, it also caches subsolutions (i.e. dynamic programming) to avoid recomputing many identical dungeons that might arise. With that, it is able to solve the 5th test case in just over one minute in my computer.
The solution is recursive. The idea is first to get the adventurer to some item (a key or the treasure). In case of a key, after the adventurer reaches it, a new similar dungeon is generated with both the key and the door deleted and the adventurer moved to where the key was. With that, the generated simpler dungeon is solved recursively until the point when the treasure is reached or the algorithm concludes that there isn't any reachable item. The order of the items to be visited is brute-forced with pruning and caching as explained above.
The path-finding between the adventurer and the items is made with an algorithm that resembles both floodfill and Dijkstra.
Finally, I suspect that this problem is NP-complete (well, the generalized version of it without a limitation on the number of doors/keys). If this is true, don't expect solutions that optimally solve very large dungeons with miryads of doors and keys in reasonable time. If sub-optimal paths were allowed, then it would be easily tractable with some heuristics (just go to the treasure if possible, otherwise go to the nearest key).
] |
[Question]
[
## Introduction
In the field of mathematics known as [topology](https://en.wikipedia.org/wiki/Topology), there are things called [separation axioms](https://en.wikipedia.org/wiki/Separation_axiom).
Intuitively, you have a set `X` and a collection of subsets of `X`, which we can think of as properties.
The system is well separated, if one can distinguish between all items of `X` based on their properties.
The separation axioms formalize this idea.
In this challenge, your task is to check three separation axioms, given `X` and the list of properties.
## Input
Your inputs are an integer `n ≥ 2`, and a list of lists `T` of integers.
The integers in `T` are drawn from `X = [0, 1, ..., n-1]`.
The lists in `T` may be empty and unsorted, but they will not contain duplicates.
## Output
Your output is one of four strings, determined by three separation axioms, each stronger than the last.
There are other axioms, but we stick with these for simplicity.
* Suppose that for all distinct `x` and `y` in `X`, there exists a list in `T` containing exactly one of them.
Then `X` and `T` satisfy *axiom T0*.
* Suppose that for all distinct `x` and `y` in `X`, there exist two lists in `T`, one of which contains `x` but not `y`, and the other contains `y` but not `x`.
Then `X` and `T` satisfy *axiom T1*.
* Suppose that the two lists above also contain no common elements.
Then `X` and `T` satisfy *axiom T2*.
Your output is one of `T2`, `T1`, `T0` or `TS`, depending on which of the above conditions holds (`TS` means none of them do).
Note that T2 is stronger than T1, which is stronger than T0, and you should always output the strongest possible axiom.
## Rules and scoring
You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
## Test cases
```
2 [] -> TS
2 [[],[1]] -> T0
2 [[0],[1]] -> T2
3 [[0],[0,1,2],[1,2]] -> TS
3 [[],[0],[0,1],[2]] -> T0
3 [[0],[0,1],[2,1],[0,1,2]] -> T0
3 [[0],[0,1],[2,1],[2,0]] -> T1
6 [[0,2,4],[0,3,5],[1,2],[3,4,5]] -> TS
6 [[0,2,4],[0,3,5],[1,2],[2,5],[3,4,5]] -> T0
6 [[0,2,4],[0,3,5],[1,2],[2,5],[3,1],[3,4,5]] -> T1
6 [[0,1],[0,2,3],[1,4],[2,4],[2,3,5],[1,3],[4,5]] -> T2
```
[Answer]
# Haskell, ~~317~~ ~~209~~ ~~174~~ 168 bytes
The function f does the job.
```
(#)=elem
x?y=[1|a<-x,b<-y,not$any(#a)b]
f n l|t(++)="TS"|t zip="T0"|t(?)="T1"|1>0="T2"where
t p=any null[p(x%y)(y%x)|x<-[0..n-1],y<-[0..x-1]]
x%y=[z|z<-l,x#z,not$y#z]
```
tests :
```
main=do
putStrLn $ f 2 []
putStrLn $ f 2 [[],[1]]
putStrLn $ f 2 [[0],[1]]
putStrLn $ f 3 [[0],[0,1,2],[1,2]]
putStrLn $ f 3 [[],[0],[0,1],[2]]
putStrLn $ f 3 [[0],[0,1],[2,1],[0,1,2]]
putStrLn $ f 3 [[0],[0,1],[2,1],[2,0]]
putStrLn $ f 6 [[0,2,4],[0,3,5],[1,2],[3,4,5]]
putStrLn $ f 6 [[0,2,4],[0,3,5],[1,2],[2,5],[3,4,5]]
putStrLn $ f 6 [[0,2,4],[0,3,5],[1,2],[2,5],[3,1],[3,4,5]]
putStrLn $ f 6 [[0,1],[0,2,3],[1,4],[2,4],[2,3,5],[1,3],[4,5]]
```
output:
```
TS
T0
T2
TS
T0
T0
T1
TS
T0
T1
T2
```
] |
[Question]
[
Apply an indefinite integral to a given string. The only rules you will be using are defined as such:
```
∫cx^(n)dx = (c/(n+1))x^(n+1) + C, n ≠ -1
c, C, and n are all constants.
```
# Specifications:
* You must be able to integrate polynomials with any of the possible features:
+ A coefficient, possibly a fraction in the format `(numerator/denominator)`.
+ Recognition that e and π are constants, and in their use, be able to form fractions or expressions containing them (can be held in a fraction like `(e/denominator)` or `(numerator/e)`, or, if in exponents, `x^(e+1)`)
- Aside of these two special constants, all coefficients will be rational, real numbers.
+ An exponent, possibly a fraction, in the format `x^(exponent)`
- Expressions with `e` or `π` in them, aside of themselves, will not be in exponents. (you will not have to integrate stuff like `x^(e+1)`, but you might integrate `x^(e)`)
+ Can use non-x 1-char variables (i.e. `f`)
- This is only for ASCII ranges 65-90 and 97-122.
+ You do not have to use chain rule or integrate `x^(-1)`.
* Output must have padding (separation between terms, i.e. `x^2 + x + C`.
* If it is unknown how to integrate with the above features, the program should print out `"Cannot integrate "+input`.
* It must be a full program.
# Bonuses:
* -10% if you print out the "pretty" exponents formatted for markdown (instead of `x^2`, `x<sup>2</sup>`).
* -10% if you print out the equation (i.e. `∫xdx = (1/2)x^2 + C`)
# Examples:
Input:
```
x
```
Output:
```
(1/2)x^(2) + C
```
---
Input:
```
-f^(-2)
```
Output:
```
f^(-1) + C
```
---
Input:
```
(1/7)x^(1/7) + 5
```
Output:
```
(1/56)x^(8/7) + 5x + C
```
---
Input:
```
πx^e
```
Output:
```
(π/(e+1))x^(e+1) + C
```
---
Input:
```
(f+1)^(-1)
```
Output:
```
Cannot integrate (f+1)^(-1)
```
[Answer]
# MATLAB, 646 x 0.9 = 581.4 bytes
```
t=input('','s');p=char(960);s=regexprep(t,{p,'pi([a-zA-Z])','([a-zA-Z])pi','([\)e\d])([a-zA-Z])','([a-zA-Z])(([\(\d]|pi))','e^(\(.+?\))','e'},{'pi','pi*$1','$1*pi','$1*$2','$1*$2','exp($1)','exp(1)'});r=[s(regexp(s,'\<[a-zA-Z]\>')),'x'];r=r(1);e=0;try
I=int(sym(strsplit(s,' + ')),r);S=[];for i=I
S=[S char(i) ' + '];end
b=0;o=[];for i=1:nnz(S)
c=S(i);b=b+(c==40)-(c==41);if(c==42&&S(i+1)==r)||(b&&c==32)
c='';end
o=[o c];end
o=regexprep(char([8747 40 t ')d' r ' = ' o 67]),{'pi','exp\(1\)','exp','\^([^\(])',['1/' r]},{p,'e','e^','^($1)',[r '^(-1)']});catch
e=1;end
if e||~isempty(strfind(o,'log'))
disp(['Cannot integrate ' t]);else
disp(o);end
```
This is currently a work-in-progress using MATLABs built in symbolic integration capabilities. Currently the requirements have been updated so the format now matches the requirements. It also does qualify for the second -10% bonus.
If anyone wants to pitch in and suggest ways of correcting the output, or use this code as a basis for another answer, feel free :). If I can find the time, I'll keep playing with it and see if I can think how to reformat the output.
**Update:** Ok, so after a bit more work, here is how the code currently stands. It is still a work in progress, but now getting closer to matching the required output.
```
t=input('','s'); %Get input as a string
p=char(960); %Pi character
s=regexprep(t,{p,'pi([a-zA-Z])','([a-zA-Z])pi','([\)e\d])([a-zA-Z])','([a-zA-Z])(([\(\d]|pi))','e^(\(.+?\))','e'},{'pi','pi*$1','$1*pi','$1*$2','$1*$2','exp($1)','exp(1)'}); %Reformat input to work with built in symbolic integration
r=[s(regexp(s,'\<[a-zA-Z]\>')),'x'];r=r(1); %determine the variable we are integrating
e=0; %Assume success
try
I=int(sym(strsplit(s,' + ')),r); %Integrate each term seperately to avoid unwanted simplificaiton
S=[];
for i=I
S=[S char(i) ' + ']; %Recombine integrated terms
end
%Now postprocess the output to try and match the requirements
b=0;o=[];
for i=1:nnz(S)
%Work through the integrated string character by character
c=S(i);
b=b+(c=='(')-(c==')'); %Keep track of how many layers deep of brackets we are in
if(c=='*'&&S(i+1)==r)||(b&&c==' ') %If a '*' sign preceeds a variable. Also deblank string.
c=''; %Delete this character
end
o=[o c]; %merge into new output string.
end
o=regexprep([char(8747) '(' t ')d' r ' = ' o 'C'],{'pi','exp\(1\)','exp','\^([^\(])',['1/' r]},{p,'e','e^','^($1)',[r '^(-1)']});
catch
e=1; %failed to integrate
end
if e||~isempty(strfind(o,'log'))
disp(['Cannot integrate ' t]) %bit of a hack - matlab can integrate 1/x, so if we get a log, we pretend it didn't work.
else
disp(o)% Display it.
end
```
Here are some examples of what it currently produces. As you can see, it's not quite right, but getting closer.
Inputs:
```
x
-f^(-2)
(1/7)x^(1/7) + 5
πx^e
(f+1)^(-1)
```
Outputs:
```
∫(x)dx = x^(2)/2 + C
∫(-f^(-2))df = f^(-1) + C
∫((1/7)x^(1/7) + 5)dx = x^(8/7)/8 + 5x + C
∫(πx^(e))dx = (πx^(e+1))/(e+1) + C
Cannot integrate (f+1)^(-1)
```
[Answer]
## Mathematica 478 \* 0.9 = 430.2
```
φ=(α=ToExpression;Π=StringReplace;σ="Cannot integrate "<>#1;Λ=DeleteDuplicates@StringCases[#1,RegularExpression["[a-df-zA-Z]+"]];μ=Length@Λ;If[μ>1,σ,If[μ<1,Λ="x",Λ=Λ[[1]]];Ψ=α@Π[#1,{"e"->" E ","π"->" π "}];Φ=α@Λ;Θ=α@Π[#1,{"e"->" 2 ","π"->" 2 "}];λ=Exponent[Θ,Φ,List];Θ=Simplify[Θ*Φ^Max@@Abs@λ];Θ=PowerExpand[Θ/.Φ->Φ^LCM@@Denominator@λ];If[Coefficient[Ψ,Φ,-1]==0&&PolynomialQ[Θ,Φ],"∫("<>#1<>")d"<>Λ<>" = "<>Π[ToString[Integrate[Ψ,Φ],InputForm],{"E"->"e","Pi"->"π"}]<>" + C",σ]])&
```
This creates a true function φ that takes one String as Input.
(Does that count as complete program for Mathematica?)
The ungolfed version would be:
```
φ=(
σ="Cannot integrate "<>#1;
Λ=DeleteDuplicates@StringCases[#1,RegularExpression["[a-df-zA-Z]+"]];
If[Length@Λ>1,σ,
If[Length@Λ<1,Λ="x",Λ=Λ[[1]]];
Ψ=ToExpression@StringReplace[#1,{"e"->" E ","π"->" π "}];
Φ=ToExpression@Λ;
Θ=ToExpression@StringReplace[#1,{"e"->" 2 ","π"->" 2 "}];
λ=Exponent[Θ,Φ,List];
Θ=Simplify[Θ*Φ^Max@@Abs@λ];
Θ=PowerExpand[Θ/.Φ->Φ^LCM@@Denominator@λ];
If[Coefficient[Ψ,Φ,-1]==0&&PolynomialQ[Θ,Φ],
"∫("<>#1<>")d"<>Λ<>" = "<>StringReplace[ToString[Integrate[Ψ,Φ],InputForm],{"E"->"e","Pi"->"π"}]<>" + C",
σ
]
]
)&
```
Note that the Greek letters are necessary to be able to use all the other letters in the input.
] |
[Question]
[
There is a variant of the well-known N-queens problem which involves queens and knights and is said to be *"considerably more difficult"* **1**. The problem statement is as follows:
>
> You must place an equal number of knights ♞ and queens ♛ on a chessboard
> such that no piece attacks any other piece. What is the maximum number
> of pieces you can so place on the board, and how many different ways
> can you do it?
>
>
>
In this [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, you will be given an input *n* between 3 and 32 (in a way that is the most suitable for your language). For a given *n*, there might be zero or more solutions to the above problem. In case there is no solution, you must output/return *nothing* (*nil*, *empty string*, *false*, ...). Otherwise, you must give two results:
1. A solution board (see below) for size *n* where it is not possible to add a queen or a knight chess piece without having any piece being under attack. **There must be an equal number of queens and knights**.
2. The source of a program to be run which accepts no input and gives (i) *another* solution (or *nothing*) for the same size *n*, in the same format, as well as (ii) another program for the next solution (and so on...).
Note that:
* The sequence of programs must never return the same board twice, must cover all possible solutions for the problem of size *n* and eventually has to terminate (producing no output).
* You can either return two values, return one and print the other, or print the two return values.
* *However*, if you print both the board and the next program, the board must not be considered to be a part of the next program (I'd recommend printing the board in comment, or use both standard output and error streams).
* The program-as-a-return-value must be a string, not a closure.
### Board format
* A board is a square of size *n*.
* A board cell can be empty, a queen or a knight.
* You must choose distinct values for each kind of cells (i.e. you can use other symbols than Q, N when printing the board).
* If you return a non-string board, it must be an *ordered* collection of the *n2* values of the board (e.g. matrix, vector or list in row/column-major order, ...).
* If you print the board, you can either print it squared, or as a line.
For example, a solution board of size 4 can be printed as follows (spaces not required; symbols at your discretion):
```
Q - - -
- - - -
- - - -
- - N -
```
If you feel so, you can also output:
```
♛ · · ·
· · · ·
· · · ·
· · ♞ ·
```
... but this is sufficient:
```
Q-------------N-
```
It does not matter if you iterate through cells in a row-major or column-major order, because there are symmetrical solutions.
For example, the solutions for n=4 are:
```
Q------N--------
Q----------N----
Q------------N--
Q-------------N-
-Q----------N---
-Q------------N-
-Q-------------N
--Q---------N---
--Q----------N--
--Q------------N
---QN-----------
---Q----N-------
---Q---------N--
---Q----------N-
---NQ-----------
----Q------N----
----Q----------N
N------Q--------
-------QN-------
-------Q----N---
---N----Q-------
-------NQ-------
--------Q------N
N----------Q----
----N------Q----
-----------QN---
-N----------Q---
--N---------Q---
-------N----Q---
-----------NQ---
N------------Q--
--N----------Q--
---N---------Q--
N-------------Q-
-N------------Q-
---N----------Q-
-N-------------Q
--N------------Q
----N----------Q
--------N------Q
```
You can also look at the solutions for n=5 [as matrices](http://dpaste.com/0WHJZFT); the boards contains `#`, `q` and `n` symbols, which are empty cells of different kinds (see my answer below).
I count [2836 boards](http://dpaste.com/2Y56DNG) for *n=6*, like in Sleafar's answer (I introduced a bug when reducing byte count, but it is fixed now).
*Many thanks to Sleafar for finding not one but two bugs in my code.*
### Score
Shortest code in bytes win.
We measure the size of the first program, the one which accepts *n*.
---
**1**. [Queens and Knights](http://archive.vector.org.uk/art10003900), by Roger K.W. Hui **(beware! contains a solution)**
[Answer]
## Common Lisp, 737
self-answer
```
(lambda(n &aux(d 1))#2=(catch'$(let((s(* n n))(c d))(labels((R(w % @ b ! &aux r h v a)(loop for u from % below s do(setf h(mod u n)v(floor u n)a #4=(aref b u))(when(< 0(logand a w)4)(and(= 6 w)!(throw'! t))(let((b(copy-seq b))(o 5))(loop for(K D)on'(-1 -2 -1 2 1 -2 1 2)for y =(+ K v)for x =(+(or D -1)h)for u =(and(< -1 y n)(< -1 x n)(+(* y n)x))if u do #1=(if(< #4#4)(setf #4#(logand #4#o(if(= w o)3 0)))))(#8=dotimes(y N)(#8#(x N)(let((u(+(* y n)x))(o 6))(if(or(= x h)(= y v)(=(abs(- h x))(abs(- v y))))#1#))))(setf #4#w r(or(cond((= w 5)(R 6 @ U b !))((R 5 @ U b())t)((catch'!(R 5 0 0 b t))t)(t(and(=(decf c)0)(incf d)(or(format t"~%(lambda(&aux(n ~A)(d ~A))~%~S)"n d'#2#)(throw'$ B)))t))r)))))r))(R 5 0 0(fill(make-array s)3)())))))
```
## Example
Paste the above in the REPL, which returns a function object:
```
#<FUNCTION (LAMBDA (N &AUX (D 1))) {1006D1010B}>
```
Call it (the star is bound to the last returned value):
```
QN> (funcall * 4)
```
This prints the following to the standard output:
```
(lambda(&aux(n 4)(d 2))
#1=(CATCH '$
(LET ((S (* N N)) (C D))
(LABELS ((R (W % @ B ! &AUX R H V A)
(LOOP FOR U FROM % BELOW S
DO (SETF H (MOD U N)
V (FLOOR U N)
A #2=(AREF B U)) (WHEN (< 0 (LOGAND A W) 4)
(AND (= 6 W) !
(THROW '! T))
(LET ((B (COPY-SEQ B))
(O 5))
(LOOP FOR (K D) ON '(-1
-2
-1 2
1 -2
1 2)
FOR Y = (+ K V)
FOR X = (+
(OR D -1)
H)
FOR U = (AND
(< -1 Y N)
(< -1 X N)
(+ (* Y N)
X))
IF U
DO #3=(IF (< #2# 4)
(SETF #2#
(LOGAND
#2#
O
(IF (=
W
O)
3
0)))))
(DOTIMES (Y N)
(DOTIMES (X N)
(LET ((U
(+ (* Y N) X))
(O 6))
(IF (OR (= X H)
(= Y V)
(=
(ABS
(- H X))
(ABS
(- V
Y))))
#3#))))
(SETF #2# W
R
(OR
(COND
((= W 5)
(R 6 @ U B !))
((R 5 @ U B
NIL)
T)
((CATCH '!
(R 5 0 0 B
T))
T)
(T
(AND
(= (DECF C)
0)
(INCF D)
(OR
(FORMAT T
"~%(lambda(&aux(n ~A)(d ~A))~%~S)"
N D
'#1#)
(THROW '$
B)))
T))
R)))))
R))
(R 5 0 0 (FILL (MAKE-ARRAY S) 3) NIL)))))
```
Also, the value returned by this function is:
```
#(5 0 0 0 0 0 0 6 0 0 0 2 0 2 0 0)
```
... which is an array literal. Number 5 represents queens, 6 is for knights and anything else stands for an empty cell, except there are more informations stored internally. If we copy-paste the returned function to the repl, we obtain a new function.
```
#<FUNCTION (LAMBDA (&AUX (N 4) (D 2))) {100819148B}>
```
And we can call it to, without arguments:
```
QN> (funcall * )
```
This call returns a new solution `#(5 0 0 0 0 0 0 2 0 0 0 6 0 0 2 0)` and the source of another function (not shown here). In case the original function or the last generated one does not find a solution, nothing is printed and nothing is returned.
## Internal values
```
|----------+--------+---------+--------+-----------------|
| | Binary | Decimal | Symbol | Meaning |
|----------+--------+---------+--------+-----------------|
| Empty | 000 | 0 | - | safe for none |
| | 001 | 1 | q | safe for queen |
| | 010 | 2 | n | safe for knight |
| | 011 | 3 | # | safe for both |
|----------+--------+---------+--------+-----------------|
| Occupied | 101 | 5 | Q | a queen |
| | 110 | 6 | K | a knight |
|----------+--------+---------+--------+-----------------|
```
I used to generate too few solutions. Now, I propagate what cell is safe for a queen and for a knight, independently. For example, here is an output for n=5 with pretty-printing:
```
Q - - - -
- - - n N
- q - n n
- # n - n
- n # # -
```
When we placed the queen `Q`, positions that are a knight-move away from this queen are still safe for queens and denoted `q`. Likewise, knights that are reachable only by queens are safe for other knights.
Values are bitwise *and*-ed to represent the possible moves and some cells are reachable by no kind of piece.
More precisely, here is the sequence of boards leading to the following solution (from left to right), where free cells are gradually constrained with different values:
```
# # # # # # q - - - q # - - - - - # - - - - - # - - - - - n
# # # # # # - - Q - - - - - Q - - - - - Q - - - - - Q - - -
# # # # # # q - - - q # q - - - - - Q - - - - - Q - - - - -
# # # # # # - q - q - # - q - - - n - - - - - n - - - - - n
# # # # # # # # - # # - n n - n N - - - - n N - - - - - N -
# # # # # # # # - # # # # # - n n n - # - - n n - n - - n N
```
## Non-quine approach
### Ungolfed, commented version
```
(defun queens-and-knights
(n ; size of problem
fn ; function called for each solution
;; AUX parameters are like LET* bindings but shorter.
&aux
;; total number of cells in a board
(s (* n n)))
(labels
;; Define recursive function R
((R (w ; what piece to place: 5=queen, 6=knight
% ; min position for piece of type W
@ ; min position for the other kind of piece
b ; current board
! ; T iff we are in "check" mode (see below)
&aux
r ; result of this function: will be "true" iff we can
; place at least one piece of type W on the board b
h ; current horizontal position
v ; current vertical position
a ; current piece at position (h,v)
)
(loop
;; only consider position U starting from position %,
;; because any other position below % was already visited
;; at a higher level of recursion (e.g. the second queen
;; we place is being placed in a recursive call, and we
;; don't visit position before the first queen).
for u from % below s
do
(setf h (mod u n) ; Intialize H, V and A
v (floor u n) ;
a (aref b u)) ;
;; Apply an AND mask to current value A in the board
;; with the type of chess piece W. In order to consider
;; position U as "safe", the result of the bitwise AND
;; must be below 4 (empty cell) and non-null.
(when (< 0 (logand a w) 4)
;; WE FOUND A SAFE PLACE TO PUT PIECE W
(when (and ! (= 6 w))
;; In "check" mode, when we place a knight, we knwo
;; that the check is successful. In other words, it
;; is possible to place an additional queen and
;; knight in some board up the call stack. Instead
;; of updating the board we can directly exit from
;; here (that gave a major speed improvement since
;; we do this a lot). Here we do a non-local exit to
;; the catch named "!".
(throw '! t))
;; We make a copy of current board b and bind it to the
;; same symbol b. This allocates a lot of memory
;; compared to the previous approach where I used a
;; single board and an "undo" list, but it is shorter
;; both in code size and in runtime.
(let ((b (copy-seq b)))
;; Propagate knights' constraints
(loop
;; O is the other kind of piece, i.e. queen here
;; because be propagate knights. This is used as
;; a mask to remove knights pieces as possible
;; choices.
with o = 5
;; The list below is arranged so that two
;; consecutive numbers form a knight-move. The ON
;; iteration keyword descend sublist by sublist,
;; i.e. (-1 -2), (-2 -1), (-1 2), ..., (2 NIL). We
;; destructure each list being iterated as (K D),
;; and when D is NIL, we use value -1.
for (K D) on '(-1 -2 -1 2 1 -2 1 2)
;; Compute position X, Y and index U in board,
;; while checking that the position is inside the
;; board.
for y = (+ K v)
for x = (+ (or D -1) h)
for u = (and (< -1 y n)
(< -1 x n)
(+(* y n)x))
;; if U is a valid position...
if u
do
;; The reader variable #1# is affected to the
;; following expression and reused below for
;; queens. That's why the expression is not
;; specific to knights. The trick here is to
;; use the symbols with different lexical
;; bindings.
#1=(when (< (aref b u) 4) ; empty?
(setf (aref b u)
(logand
;; Bitwise AND of current value ...
(aref b u)
;; ... with o: position U is not a
;; safe place for W (inverse of O)
;; anymore, because if we put a W
;; there, it would attack our
;; current cell (H,V).
o
;; ... and with zero (unsafe for
;; all) if our piece W is also a
;; knight (resp. queen). Indeed, we
;; cannot put anything at position
;; U because we are attacking it.
(if (= w o) 3 0)))))
;; Propagate queens' constraints
(dotimes (y N)
(dotimes (x N)
(let ((u(+(* y n)x))(o 6))
(if (or (= x h)
(= y v)
(= (abs(- h x)) (abs(- v y))))
;; Same code as above #1=(if ...)
#1#))))
(setf
;; Place piece
(aref b u) w
;; Set result value
r (or (cond
;; Queen? Try to place a Knight and maybe
;; other queens. The result is true only if
;; the recursive call is.
((= w 5) (R 6 @ U b !))
;; Not a queen, so all below concern
;; knights: we always return T because
;; we found a safe position.
;; But we still need to know if
;; board B is an actual solution and
;; call FN if it is.
;; ------------------------------------
;; Can be place a queen too? then current
;; board is not a solution.
((R 5 @ U b()) t)
;; Try to place a queen and a knight
;; without constraining the min positions
;; (% and @); this is the "check" mode that
;; is represented by the last argument to
;; R, set to T here. If it throws true,
;; then board B is a duplicate of a
;; previous one, except that it is missing
;; pieces due to constraints % and @. The
;; "check" mode is a fix to a bug where we
;; reported as solutions boards where there
;; was still room for other pieces.
((catch'!(R 5 0 0 b t)) t)
;; Default case: we could not add one more
;; layer of pieces, and so current board B
;; is a solution. Call function FN.
(t (funcall fn b) t))
;; R keeps being true if it already was for
;; another position.
r)))))
;; Return result R
r))
;; Start search with a queen and an empty board.
(R 5 0 0 (fill (make-array s) 3) nil)))
```
### Duplicates and bugs
My very first solution outputted duplicate solutions. In order to solve it, I introduced two counters for queens and knights. The counter for queens (resp. knights) keep track of the first position in the board where a queen (resp. knight) exists: I add a queen (resp. a knight) only at positions that follow that minimal position.
That methods prevents me from revisiting solutions that were already found in previous iterations, because I iterate with an increasing queen (resp. knight) position.
However, Sleafar noticed that there were solutions for which there could be room for queens and knights, which is against the rules. For a while I though I had to revert to a normal search and store all the known solutions to prevent duplicates, which felt too costly (both in terms of bytes and memory usage).
Instead, here is what I do now: when a potential solution board is found, I try to add exactly *one* queen and *one* knight, without taking into account the counters (i.e. for all cells on the board). If this is possible, then current board is a duplicate of a previous one, and I reject the solution.
### Tests
```
|---+---------+------------+--------------|
| N | boards | seconds | bytes |
|---+---------+------------+--------------|
| 3 | 0 | 0 | 32768 |
| 4 | 40 | 0 | 360416 |
| 5 | 172 | 0 | 3440016 |
| 6 | 2836 | 0.085907 | 61251584 |
| 7 | 23876 | 1.265178 | 869666288 |
| 8 | 383586 | 24.991300 | 17235142848 |
| 9 | 6064506 | 524.982987 | 359952648832 |
|---+---------+------------+--------------|
```
## Quine-ification
I had different ideas to make successive quines.
The easiest one is probably to generate all solutions first as a list of strings and write sequential quines which pop from that list at each generation. However this did not seem to be shorter than current approach.
Alternatively, I tried to rewrite the recursive code with a custom stack and dump all the state variables each time I find a solution; the goal is that the next step can be processed as a continuation of current step.
Maybe this would be better suited for a stack based language.
The current one is quite simple and rely on Common Lisp reader variables, which are always fun to use.
[Answer]
# Groovy, 515 bytes
```
X=0;Y="N="+args[0]+";M=N*N;S=[];def f(b,i,j,v){(i..<j).findAll{k->!(0..<M).any{l->w=b[l];r=(k.intdiv(N)-l.intdiv(N)).abs();c=(k%N-l%N).abs();s=v+w;w>0&&(k==l||(r==0||c==0||r==c?s<4:r<3&&c<3&&s>2))}}.collect{a=b.clone();a[it]=v;[it,a]}};def r(b,q,n){f(b,q,M,1).each{i->f(i[1],n,M,2).each{j->if(f(j[1],0,M,1).any{f(it[1],0,M,2)}){r(j[1],i[0],j[0])}else{S.add(j[1])}}}};r(new int[M],0,0);if(x<S.size()){sprintf('//%s%cX=%d;Y=%c%s%c;print(Eval.xy(X,Y,Y))',S[x].toString(),10,x+1,34,y,34)}else{''}";print(Eval.xy(X,Y,Y))
```
## Testing
Provide **n** as a command line argument:
```
groovy qak.groovy 4
```
The first line of the output is always a solution as a comment (0=empty, 1=queen, 2=knight), followed by the code in the second line:
```
//[1, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0]
X=1;Y="N=4;M=N*N;S=[];def f(b,i,j,v){(i..<j).findAll{k->!(0..<M).any{l->w=b[l];r=(k.intdiv(N)-l.intdiv(N)).abs();c=(k%N-l%N).abs();s=v+w;w>0&&(k==l||(r==0||c==0||r==c?s<4:r<3&&c<3&&s>2))}}.collect{a=b.clone();a[it]=v;[it,a]}};def r(b,q,n){f(b,q,M,1).each{i->f(i[1],n,M,2).each{j->if(f(j[1],0,M,1).any{f(it[1],0,M,2)}){r(j[1],i[0],j[0])}else{S.add(j[1])}}}};r(new int[M],0,0);if(x<S.size()){sprintf('//%s%cX=%d;Y=%c%s%c;print(Eval.xy(X,Y,Y))',S[x].toString(),10,x+1,34,y,34)}else{''}";print(Eval.xy(X,Y,Y))
```
The following script can be used for automated testing (provide **n** as an argument again):
```
#!/bin/bash
set -e
test -n "$1"
groovy qak.groovy "$1" > t
while test -s t; do
head -n1 t
groovy t > t2
mv t2 t
done
```
Because I tried to make the solution as small as possible, it is **very slow** (see below for details). I tested only n=4 with this version to see if the quineification works.
## Results
**n=4:** [40 solutions](http://pastebin.com/raw/K1f09hNi) ([converted format](http://pastebin.com/raw/b2jPQhPa))
**n=5:** [172 solutions](http://pastebin.com/raw/2fckKUV5) ([converted format](http://pastebin.com/raw/twc3bcLn))
**n=6:** [2836 solutions](http://pastebin.com/raw/VMWC6E4n) ([converted format](http://pastebin.com/raw/P6KqRVFb))
## Algorithm
This is a slightly ungolfed non-quine version of the solution:
```
N=args[0] as int
M=N*N
S=[]
/**
* Generate a list of valid posibilities to place a new piece.
* @param b Starting board.
* @param i Start of the index range to check (inclusive).
* @param j End of the index range to check (exclusive).
* @param v Value of the new piece (1=queen, 2=knight).
* @return A pair with the index of the new piece and a corresponding board for each possibility.
*/
def f(b,i,j,v){
(i..<j).findAll{k->
!(0..<M).any{l->
w=b[l]
r=(k.intdiv(N)-l.intdiv(N)).abs()
c=(k%N-l%N).abs()
s=v+w
w>0&&(k==l||(r==0||c==0||r==c?s<4:r<3&&c<3&&s>2))
}
}.collect{
a=b.clone();a[it]=v;[it,a]
}
}
/**
* Recursively look for solutions.
* @param b Starting board.
* @param q Start of the index range to check for queens.
* @param n Start of the index range to check for knights.
*/
def r(b,q,n){
f(b,q,M,1).each{i->
f(i[1],n,M,2).each{j->
if(f(j[1],0,M,1).any{f(it[1],0,M,2)}){
r(j[1],i[0],j[0])
}else{
S.add(j[1])
}
}
}
}
r(new int[M],0,0)
S.each{println(it)}
```
## Quineification
I used a very simple approach here to keep the code size low.
```
X=0;Y="...";print(Eval.xy(X,Y,Y))
```
The variable **X** holds the index of the solution to print next. **Y** holds a modified copy of the algorithm above, which is used to calculate **all** solutions and then select only one of them, which is the reason for it being so slow. The advantage of this solution is, that it doesn't require much additional code. The code stored in **Y** is executed with help of the **Eval** class (a true quine is not required).
The modified code prints the solution pointed to by **X**, increases **X** and appends a copy of itself:
```
//[...]
X=1;Y="...";print(Eval.xy(X,Y,Y))
```
I also tried to output all solutions as code for the second step, but for n=6 it was producing too much code for Groovy to handle.
] |
[Question]
[
Congratulations! You've just been hired by NASA to work on the new Horizons 2 project.
Sadly, there have been huge budget cuts recently, so the top management has decided to fake the whole planned Pluto flyby (as they did for the moon landings in the 70s).
Your task is to write a program that will accept as input a date in the format `yyyymmdd`, and will provide a fake photograph of Pluto for this date. You can assume the entered date will be in the year 2015 or 2016.
The photograph is a 15x15 grid of ASCII characters. The characters on the grid have their x- and y-coordinates within the range `[-7, 7]` - the top-left character is at `(-7, -7)` while the bottom-right character is at `(7, 7)`.
The photograph will be computed with the following rules:
* The probe will be the nearest to Pluto on 25/12/2015
* The distance `d` to Pluto is given by this formula : `square root of ((difference in days to christmas) ^ 2 + 10)`
* The radius `r` of Pluto's image on the photo is given by : `22 / d`
* A character with coordinates `(x, y)` on the grid must be set to `#` if `x^2 + y^2 <= r^2` ; it must be set to space otherwise.
* There are stars at positions `(-3, -5)`, `(6, 2)`, `(-5, 6)`, `(2, 1)`, `(7, -2)`. Stars are represented by a dot `.`, and they are of course hidden by Pluto.
One more thing: The NASA board has come to the conclusion that the discovery of life on Pluto would likely result in a substantial budget increase. Your program should then add clues of life on Pluto:
* When the distance to Pluto is <= 4, add a plutonian at coordinates `(-3,-1)` : `(^_^)`
*Example photograph for input `20151215`: (Your code should have all the newlines as this code does)*
```
.
# .
###
#####
###.
# .
.
```
*Photograph for input `20151225`:*
```
#######
#########
###########
#############
#############.
###(^_^)#####
#############
#############
#############
#############
###########
#########
. #######
```
As a comparison, here's a photo of Pluto's satellite Hydra as taken by New Horizons. Differences are hardly noticeable with our ASCII art.
[](https://i.stack.imgur.com/5bGwA.png)
This is code golf, so the shortest code in bytes wins!
[Answer]
# JavaScript (ES6), 237 bytes
```
f=(n)=>(t=new Date('201'+n[3],n[4]+n[5],n[6]+n[7])/864e5-403805/24,r=484/(t*t+10),(g=(i)=>(++i<8?(h=(j)=>(i*i+j*j<=r?r>30.25&!~i&&'(^_^)'[j+3]||'#':~'p-3-5p62p-56p21p7-2'.indexOf('p'+j+i)?'.':' ')+(++j<8?h(j):''))(-7)+'\n'+g(i):''))(-8))
```
[Live demo](http://jsfiddle.net/intrepidcoder/b1ucasw0/). Run in Firefox.
## Original version
```
f=function(n) {
t = (new Date('201'+n[3],''+n[4]+n[5],''+n[6]+n[7]) // Find the time difference in milliseconds,
- new Date(2015,12,25)) / 864e5; // then divide by 86400000 to convert to days.
r=22 / Math.sqrt(t*t+10); // Calculate the radius.
s=[]; // s is the array that contains each line as a string.
for(i=-7;i<8;i++) // Loop through rows.
for(j=-7,s[i+7]='';j<8;j++) // Loop through columns, appending one character per column.
// s is zero based, so add 7 to the row.
s[i+7]+=i*i+j*j<=r*r ? // Choose which character to add to s.
(r>5.5&i==-1&&'(^_^)'[j+3]||'#') : // Add a '#' if the position is inside the radius.
// If distance < 4, then the radius > 5.5
// Then add the face at the right position.
{'-3-5':1,'62':1,'-56':1,'21':1,'7-2':1} // Add the stars if outside. Create an associative array.
[j+''+i]?'.':' '; // If i concat j is in the array, the expression will be 1,
// which is truthy, else it will be undefined, which is falsey.
return s.join`\n` // Join all the rows with a new-line.
}
```
## Golfing
This was fun to golf.
I don't need to create a Date object, so I hardcoded the value in milliseconds to save 13 bytes:
```
t=(new Date('201'+n[3],n[4]+n[5],n[6]+n[7])-new Date(2015,12,25))/864e5 // Before
t=new Date('201'+n[3],n[4]+n[5],n[6]+n[7])/864e5-403805/24 // After
```
Replace the associative array with a delimited string to eliminate 9 bytes:
```
{'-3-5':1,'62':1,'-56':1,'21':1,'7-2':1}[j+''+i]?'.':' ' // Before
~'p-3-5p62p-56p21p7-2'.indexOf('p'+j+i)?'.':' ' // After
```
The biggest refactor was replacing the for loops with nested, recursive [IIFE](https://en.wikipedia.org/wiki/Immediately-invoked_function_expression)s to knock off 10 bytes:
```
s=[];for(i=-7;i<8;i++)for(j=-7,s[i+7]='';j<8;j++)s[i+7]+= /* Chooses char at i,j */ ;return s.join`\n` // Before
(g=(i)=>(++i<8?(h=(j)=>( /* Chooses char at i,j */ )+(++j<8?h(j):''))(-7)+'\n'+g(i):''))(-8) // After
```
I also got rid of `Math.sqrt` for 8 more bytes.
```
r=22/Math.sqrt(t*t+10),(g=(i)=>(++i<8?(h=(j)=>(i*i+j*j<=r*r?r>5.5 // Before
r=484/(t*t+10),(g=(i)=>(++i<8?(h=(j)=>(i*i+j*j<=r?r>30.25 // After
```
## Issues
~~I could only get the correct photograph for the test cases by changing the closest date to 2015/12/24, and I don't know if the problem lies in my code or the question. Please clarify and I will update my answer.~~
~~Here is my output using the differences from 2015/12/25.~~
Edit: Updated answer to use Christmas as the closest date.
Photograph for "20151215":
```
.
# .
###
#####
###.
# .
.
```
Photograph for "20151225":
```
#######
#########
###########
#############
#############.
###(^_^)#####
#############
#############
#############
#############
###########
#########
. #######
```
[Answer]
# C# 4.0, 393 bytes
```
string p(string s){int i=Convert.ToInt32(s),Y=i/10000,m,x,y;s="";i-=Y*10000;m=i/100;i-=m*100;double d=Math.Sqrt(Math.Pow((new DateTime(2015,12,25)-new DateTime(Y,m,i)).Days,2)+10);string o,k=".-3-5.62.-56.21.7-2";for(y=-7;y<8;y++){for(x=-7;x<8;x++){o="#";if(d<=4&&x==-3&&y==-1){o="(^_^)";x+=4;}s+=Math.Pow(x,2)+Math.Pow(y,2)<=Math.Pow(22/d,2)?o:k.Contains("."+x+y)?".":" ";}s+="\n";}return s;}
```
## Example:
```
string userInput = Console.ReadLine();
Console.WriteLine(p(userInput));
```
## Output:
```
20151216
.
### .
#####
#####
#####
### .
.
20151224
#####
#########
###########
###########
#############.
###(^_^)#####
#############
#############
#############
###########
###########
#########
. #####
```
[Answer]
## CJam, 165 bytes
```
q'-%:i~\0\({X1=29W$2%-X7<X+2%30+?+}fX+\2%-359 6?+:DD*A+mq:Z22Z/_*:R-7:Y];F{-7:X;F{XX*YY*+R>XYF*+[-78II+85H-23]#)'.S?Z4<Y-1=X-4>X2<&&&X-3="(^_^)"L?'#??X):X;}*NY):Y;}*
```
The first part computes the day difference and stores it in the `D` variable.
The rest is a double loop that iterates through `X` and `Y`.
Test it [here](http://cjam.aditsu.net/#code=q'-%25%3Ai~%5C0%5C(%7BX1%3D29W%242%25-X7%3CX%2B2%2530%2B%3F%2B%7DfX%2B%5C2%25-359%206%3F%2B%3ADD*A%2Bmq%3AZ22Z%2F_*%3AR-7%3AY%5D%3BF%7B-7%3AX%3BF%7BXX*YY*%2BR%3EXYF*%2B%5B-78II%2B85H-23%5D%23)'.S%3FZ4%3CY-1%3DX-4%3EX2%3C%26%26%26X-3%3D%22(%5E_%5E)%22L%3F'%23%3F%3FX)%3AX%3B%7D*NY)%3AY%3B%7D*&input=2015-12-25)
] |
[Question]
[
**Introduction**
Arithmetic Gaol is a special facility that incarcerates positive integers. However, recently, the positive integers have been trying to escape. Therefore the wardens have decided to, um, *eliminate* some of the positive integers to send a message to the other integers. They have hired a software engineer to write a program to figure out which integers to eliminate for maximum effect.
**Input Description**
Input is given via STDIN, command line arguments, or a user input function (such as `raw_input`). You can't have it as a function argument or a preinitialized variable (e.g. this program expects input in a variable `x`).
The first line of input contains a single positive integer `n` where `8 >= n >= 3`. Following that are `n` lines containing `n` characters from the set `[1,2,3,4,5,6,7,8,9]`. Here is an example input:
```
5
22332
46351
65455
24463
65652
```
**Output Description**
The wardens would like to eliminate numbers so that the following conditions are met:
* In each row and column of the resulting grid, no number will appear twice;
* No two eliminated numbers may be adjacent horizontally or vertically;
* The surviving numbers must form an orthogonally contiguous group -- it will be possible to travel from any surviving number to any other surviving number moving only horizontally and vertically and never crossing any eliminated number.
Output the input (minus the first line), with the eliminated numbers replaced with `#`.
There may be more than one solution. If that is the case, you may output any solution.
There may also be no solution. If that is the case, output the string `no answer`.
Here is a possible output for the example input:
```
#2#3#
46351
6#4#5
24#63
#56#2
```
**Example Inputs and Outputs**
There are multiple outputs for each input, so these outputs are just examples.
Input:
```
5
46551
51565
32654
14423
43244
```
Output:
```
46#51
#156#
326#4
1#423
#324#
```
Input:
```
7
7183625
1681563
5238564
8786268
1545382
3814756
5325345
```
Output:
```
71#362#
#6815#3
5238#64
#7#62#8
154#382
3814756
#325#4#
```
Input:
```
8
21534768
75196287
68392184
96244853
44865912
76516647
89751326
43698979
```
Output:
```
21#34768
#5196287
683#21#4
9#24#853
#4865912
7#51#64#
89751326
436#8#7#
```
Input:
```
4
2222
2331
3112
1322
```
Output:
```
no answer
```
[Answer]
# Ruby - ~~541...,~~ 394
The basic algorithm is a recursive depth-first search of duplicates to affirmatively select, looking through row 1, then column 1, then row 2, etc, and checking that two neighbors are not killed and that the grid is connected (that's the `break if` clause in there, and the bit that comes before it).
```
K=(0...(N=gets.to_i)*N).to_a
J=gets(p).split*''
H=->m{K&[m+1,m-1,m+N,m-N]}
Q=->k{s=[k[j=0]]
(j=s.size
s.map{|x|(s+=H[x]&k).uniq!})while s[j]
break if(K-k).any?{|m|(H[m]-k)[0]}||k!=k&s
$><<K.map{|m|[k.index(m)?J[m]:?#,m%N>N-2?"
":p]}*''|exit if !g=((0...N*2).map{|x|(k.select{|m|m.divmod(N)[x/N]==x%N}.group_by{|m|J[m]}.find{|l,c|c[1]}||[])[1]}-[p]).min
g.map{|d|Q[k-g<<d]}}
Q[K]
puts"no answer"
```
### Some neat tricks:
`if w[1]` is much shorter than `if !w.one?` and if you know there's at least one member, it's the same result.
Similarly, `[0]` is shorter than `any?` if there's no block, and `s[j]` is a cute shortcut for `j<s.size` (technically, it's more like `j.abs<s.size`)
And `y%N+(y/N).i` is much shorter than `Complex(y%N,y/N)`
Also, when there's two complicated conditionals to generate strings, it might be shorter to do `[cond1?str1a:str1b,cond2?str2a:str2b]*''` than to add all the parens or `#{}`s in.
## Ungolfing and explanation:
(This is from the 531 byte version. I've made changes. Most notably, I've since eliminated the call to product - just solve one digit per row/column at a time, and J is now just an array, indexed by integers. All coordinates are just integers.)
`H` calculates neighbors
```
def H m
# m, like all indices, is a complex number
# where the real part is x and the imaginary is y
# so neighbors are just +/-i and +/-1
i='i'.to_c
neighborhood = [m+1, m-1, m+i, m-i]
# and let's just make sure to eliminate out-of-bounds cells
K & neighborhood
end
```
`N` is the size of the grid
```
N = gets.to_i
```
`K` are the keys to the map (complex numbers)
```
# pretty self-explanatory
# a range of, e.g., if N=3, (0..8)
# mapped to (0+0i),(1+0i),(2+0i),(0+1i),(1+1i),(2+1i),...
K = (0..N**2-1).map{|y| (y%N) +(y/N).i }
```
`J` is the input map (jail)
```
# so J is [[0+0,"2"],[0+1i,"3"],....].to_h
J=K.zip($<.flat_map {|s|
# take each input line, and...
# remove the "\n" and then turn it into an array of chars
s.chomp.chars
}).to_h
```
`k` are the non-killed keys
```
# starts as K
```
`Q` is the main recursive method
```
def Q k
j=0 # j is the size of mass
# the connected mass starts arbitrarily wherever k starts
mass=[k[0]]
while j < s.size # while s hasn't grown
j = mass.size
mass.each{|cell|
# add all neighbors that are in k
(mass+=H[cell] & k).uniq!
}
end
# if mass != k, it's not all orthogonally connected
is_all_connected = k!=k&mass
# (K-k) are the killed cells
two_neighbors_killed = (K-k).any?{|m|
# if any neighbors of killed cells aren't in k,
# it means it was killed, too
(H[m]-k)[0]
}
# fail fast
return if two_neighbors_killed || is_all_connected
def u x
x.group_by{|m|J[m]}.select{|l,c|c[1]}
end
rows_with_dupes = Array.new(N){|r|u[k.select{|m|m.imag==r}]}
cols_with_dupes = Array.new(N){|r|u[k.select{|m|m.real==r}]}
# dupes is an array of hashes
# each hash represents one row or column. E.g.,
# {
# "3"=>[(0+0i),(1+0i),(3+0i)],
# "2"=>[(2+0i),(4+0i)]
# }
# means that the 0th, 1st and 3rd cells in row 0
# all are "3", and 2nd and 4th are "2".
# Any digits without a duplicate are rejected.
# Any row/col without any dupes is removed here.
dupes = (rows_with_dupes+cols_with_dupes-[{}])
# we solve one row at a time
first_row = dupes[0]
if !first_row
# no dupes => success!
J.map{|m,v|k.member?(m)?v:?#}.each_slice(N){|s|puts s*''}
exit
else
# the digit doesn't really matter
t=first_row.values
# cross-multiply all arrays in the row to get a
# small search space. We choose one cell from each
# digit grouping and drop the rest.
t.inject(:product).map{ |*e|
# Technically, we drop all cells, and add back the
# chosen cells, but it's all the same.
new_k = k-t.flatten+e.flatten
# and then search that space, recursively
Q[new_k]
}
end
end
```
The code is executed with:
```
# run with whole board
Q[K]
# if we get here, we didn't hit an exit, so we fail
puts"no answer"
```
## Changelog
**394** added @blutorange's suggestion below, and chopped out a lot more manipulation
**408** revised output once more. Also use `.min` instead of `.inject(:+)` since I'm just taking one row anyway.
**417** shorter output calculation
**421** dropped complex numbers. Just use integers. Save a bundle
**450** more input improvements
**456** input improvements
**462** incremental improvements - esp. `find`, not `select`
**475** dropped `u` and squashed the row/col dupe builder
**503** only solve one duplicate digit per row/column at a time.
**530** use `map &:pop` instead of `values`
**531** pull out the lambda that makes the dupes array
**552** oops! missed a requirement
**536** marginally improved population of dupes array (what was formerly `d`)
**541** initial
[Answer]
# HTML + JavaScript (*ES6*) 459
Using an HTML textarea to get multiline input.
To test, run the snippet in Firefox.
Enlarge the textarea if you like, paste the input inside the textarea (beware: exact input, no extra spaces on any line), and tab away. The result is appended.
Method: a recursive Depth First Serarch. It finds non-optimal solutions for all the test cases in seconds (it's gode golf, but a valid answer *should* terminate for common test cases)
```
<textarea onchange="s=this.value,
z=s[0],o=-~z,k=[],X='no answer',f='#',
(R=(s,t,h={},r=[],d=0)=>(
s.map((v,i)=>v>0&&[i%o,~(i/o)].map(p=>h[p+=v]=[...h[p]||[],i])),
[h[i][1]&&h[i].map(p=>r[d=p]=p)for(i in h)],
d?r.some(p=>(
(s[p+o]!=f&s[p-o]!=f&s[p-1]!=f&s[p+1]!=f)&&
(
g=[...s],g[p]=f,e=[...g],n=0,
(F=p=>e[p]>0&&[1,-1,o,-o].map(d=>F(p+d),e[p]=--n))(p<o?p+o:p-o),
t+n==0&&!k[g]&&(k[g]=1,R(g,t-1))
)
)):X=s.join('')
))([...s.slice(2)],z*z-1),this.value+=`
`+X"></textarea>
```
**First try**
Method: a Depth First Serarch, non-recursive, using a user stack.
The function could be easily transformed in a Breadth First Search, chaging `l.pop` to `l.shift`, so using a queue instead of a stack, but it's too slow and I'm not sure it can find an optimal solution anyway.
```
S=s=>{
z=s[0],o=-~z,s=[...s.slice(2)];
k=[];
l=[[z*z,s]];
for(d=1;d&&(t=l.pop());)
{
[t,s]=t,--t,
s.map((v,i)=>v>0&&[i%o,~(i/o)].map(p=>h[p+=v]=[...h[p]||[],i]),h={},r=[])
d=0
for(i in h)h[i][1]&&h[i].map(p=>r[d=p]=p)
r.map(p=>
(s[p+o]!='#'&s[p-o]!='#'&s[p-1]!='#'&s[p+1]!='#')&&
(
g=[...s],g[p]='#',
f=[...g],n=0,
(F=p=>f[p]>0&&[1,-1,o,-o].map(d=>F(p+d),f[p]=--n))(p<o?p+o:p-o),
t+n||k[g]||(k[g]=l.push([t,g]))
)
)
}
return d?'no answer':s.join('')
}
// TEST
cases=[
['5\n22332\n46351\n65455\n24463\n65652','#2#3#\n46351\n6#4#5\n24#63\n#56#2']
,['5\n46551\n51565\n32654\n14423\n43244','46#51\n#156#\n326#4\n1#423\n#324#']
,['7\n7183625\n1681563\n5238564\n8786268\n1545382\n3814756\n5325345'
,'71#362#\n#6815#3\n5238#64\n#7#62#8\n154#382\n3814756\n#325#4#']
,['8\n21534768\n75196287\n68392184\n96244853\n44865912\n76516647\n89751326\n43698979'
,'21#34768\n#5196287\n683#21#4\n9#24#853\n#4865912\n7#51#64#\n89751326\n436#8#7#']
,['4\n2222\n2331\n3112\n1322','no answer']
]
var out = ''
var nt=0
var exec =_=>{
var t=cases[nt++];
if (t) {
var r = S(t[0]).replace(/#/g,'<b>#</b>');
var k = t[1].replace(/#/g,'<b>#</b>');
out += '<tr><th>Input<th>Result<th>Expected</tr>'+
'<tr><td>'+t[0]+'</td><td>'+r+'</td><td>'+k+'</td></tr>';
T.innerHTML = out + 'test ' + nt + ' done';
setTimeout(exec, 100);
}
else
{
T.innerHTML = out;
}
}
T.innerHTML = "...wait ..."
setTimeout(exec, 100);
```
```
table {
font-size: 12px;
}
td {
font-family: monospace;
white-space: pre;
vertical-align: bottom;
margin: 2x 4px;
}
b {
color: #ccc;
}
```
```
<table id=T>
</table>
```
[Answer]
# Ruby, ~~346~~ ~~344~~ ~~329~~ 316 bytes, sl∞∞∞∞∞∞w
This is code-golf, not code-fast, so...
```
N=/!/=~G=$*[1..-1]*?!
M=N*N
g=->i{(!G[i]||G[i]<?*||i<0||A[i])&&break
A[i]=0
[1,N+1,-1,-1-N].map{|a|g[i+a]}}
f=->w,a{A=[];g[/\d/=~G=a];/#.{#{N}}?#/!~G&&/(\d)([^!]*|.{#{N}}.{#{O=N+1}}*)\1/!~G&&A.count(0)+w==M&&N.times.map{|m|puts G[m*(1+N),N]}&&exit
(w...M).map{|j|b=a+'';b[j]=?#
w<M&&f[w+1,b]}}
f[0,G]
$><<"no answer"
```
Use it like:
```
mad_gaksha@madlab ~/Applications/Tools $ ruby -W0 c50442.rb 3 323 312 231
#23
312
231
```
The flag `-W0` is not necessary, but I suggest you either add it to disable warnings or redirect `stderr`...
Tell me if you had enough patience to run it on the examples for n=6,7,8
# Changelog
* `each` ⇨ `map`, thanks to @NotThatCharles
* check for adjacent deletions and same digits by two `regexp`s, similar to what @NotThatCharles suggested
* optimized reading input a little
* smaller & slower
] |
[Question]
[
## Background
Consider a (closed) chain of rods, each of which has integer length. How many distinct hole-free [polyominoes](http://en.wikipedia.org/wiki/Polyomino) can you form with a given chain? Or in other words, how many different non-self-intersecting polygons with axis-aligned sides can you form with a given chain?
Let's look at an example. Consider a particular chain consisting of 8 rods of length 1 and 2, which we can represent as `[1, 1, 2, 2, 1, 1, 2, 2]`. Up to rotations and translations, there are only 8 possible polyominoes (we do count different reflections):

This first rod is dark blue, and then we traverse the polygon in a *counter-clockwise* sense.
The sense of rotation doesn't affect the result in the above example. But let's consider another chain, `[3, 1, 1, 1, 2, 1, 1]`, which yields the following 3 polyominoes:

Notice that we do *not* include a reflection of the last polyomino, because it would require clockwise traversal.
If we had a more flexible chain of the same length, `[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]`, we would actually be able to form both reflections among some other polyoninoes, totalling 9:

## The Challenge
Given a description of a chain, as an array or similar, determine the number of distinct polyominoes you can form (up to rotations and translations) by using the rods *in order* while going around the perimeter in a counter-clockwise sense.
Please write a full program and include commands to compile (if applicable) and run your code from the command line. Please also include a link to a free compiler/interpreter for your language.
Your program should read the input from STDIN. The first line will contain an integer *M*. The next *M* lines will be test cases, each of which will be a space-separated list of rod lengths. Your program should print *M* lines to STDOUT, each of which consists of a single integer - the number of distinct polyominoes that can be formed.
You must only use a single thread.
Your program must not use more than 1 GB of memory at any time. (This is not a completely strict limit, but I will monitor your executable's memory usage, and kill any process that consistently uses more than 1 GB, or spikes significantly above it.)
To prevent excessive amounts of pre-computation, your code must not be longer than 20,000 bytes, and you must not read any files.
You must also not optimise towards the specific test cases chosen (e.g. by hardcoding their results). If I suspect that you do, I reserve the right to generate new benchmark sets. The test sets are random, so your program's performance on those should be representative for its performance on arbitrary input. The only assumption you're allowed to make is that the sum of the rod lengths is even.
## Scoring
[I have provided benchmark sets](https://gist.github.com/m-ender/eabb883dcc7c0eb734c7) for chains of *N* = 10, 11, ..., 20 rods. Each test set contains 50 random chains with lengths between 1 and 4 inclusive.
Your primary score is the largest *N* for which your program completes the entire test set within 5 minutes (on my machine, under Windows 8). The tie breaker will be the actual time taken by your program on that test set.
If anyone beats the largest test set, I will keep adding larger ones.
## Test Cases
You can use the following test cases to check the correctness of your implementation.
```
Input Output
1 1 0
1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 3
1 1 1 1 1 1 1 1 1 1 9
1 1 1 1 1 1 1 1 1 1 1 1 36
1 1 1 1 1 1 1 1 1 1 1 1 1 1 157
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 758
1 1 2 2 1 1 2 2 8
1 1 2 2 1 1 2 2 1 1 23
1 1 2 2 1 1 2 2 1 1 2 2 69
1 2 1 2 1 2 1 2 3
1 2 1 2 1 2 1 2 1 2 1 2 37
1 2 3 2 1 2 3 2 5
1 2 3 2 1 2 3 2 1 2 3 2 23
3 1 1 1 2 1 1 3
1 2 3 4 5 6 7 1
1 2 3 4 5 6 7 8 3
1 2 3 4 5 6 7 8 9 10 11 5
2 1 5 3 3 2 3 3 4
4 1 6 5 6 3 1 4 2
3 5 3 5 1 4 1 1 3 5
1 4 3 2 2 5 5 4 6 4
4 1 3 2 1 2 3 3 1 4 18
1 1 1 1 1 2 3 3 2 1 24
3 1 4 1 2 2 1 1 2 4 1 2 107
2 4 2 4 2 2 3 4 2 4 2 3 114
```
You find an input file with these [over here](https://gist.github.com/mbuettner/c0f23c3d92dc5b70be8f).
## Leaderboard
```
User Language Max N Time taken (MM:SS:mmm)
1. feersum C++ 11 19 3:07:430
2. Sp3000 Python 3 18 2:30:181
```
[Answer]
# C++11
Updates:
Added the first line of `c` which breaks out early if the distance is too far from the origin (which was the whole purpose of the variable `rlen`, but I forgot to write it in the first version). I changed it to use much less memory, but at the cost of time. It now solves N=20 in just under 5 minutes for me.
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <map>
#include <ctime>
#define M std::map
#define MS 999
#define l (xM*2+1)
#define KITTENS(A,B)A##B
#define CATS(A,B)KITTENS(A,B)
#define LBL CATS(LBL,__LINE__)
#define unt unsigned
#define SU sizeof(unt)
#define SUB (SU*8)
#define newa (nb^SZ||fail("blob"),nb+++blob)
#define D
struct vec {int x, y;};
unt s[MS*2];
int xM, sl[MS];
vec X[MS];
struct a;
struct a { M<unt,unt>v;};
#define SZ ((1<<29)/sizeof(a))
a*blob;
unt nb;
int fail(const char*msg)
{
printf("failed:%s", msg);
exit(1);
return 1;
}
struct
{
unt*m;
bool operator()(int x, int y) { return m[(x+l*y)/SUB] >> (x+l*y)%SUB & 1; }
void one(int x, int y) { m[(x+l*y)/SUB] |= 1U << (x+l*y)%SUB; }
void zero(int x, int y) { m[(x+l*y)/SUB] &= ~(1U << (x+l*y)%SUB); }
} g;
unt c(a*A, vec x, unt rlen, unt sn) {
if((unt)x.y+abs(x.x) > rlen) return 0;
if(!rlen) {
vec *cl=X, *cr=X, *ct=X;
for(unt i=1; i<sn; i++) {
#define BLAH(Z,A,B,o,O) \
if(X[i].A o Z->A || (X[i].A == Z->A && X[i].B O Z->B)) \
Z = X+i
BLAH(cl,x,y,<,>);
BLAH(cr,x,y,>,<);
BLAH(ct,y,x,>,>);
}
unt syms = 1;
#define BLA(H,Z) {bool sy=1;for(unt o=0; o<sn; o++) sy &= (int)(1|-(H))*sl[o] == sl[(Z-X+o)%sn]; syms += sy;}
BLA(~o&1,cl)
BLA(1,ct)
BLA(o&1,cr)
#ifdef D
//printf("D");for(int i=0;i<sn;i++)printf(" %u",sl[i]);printf("\n");
if(syms==3) fail("symm");
#endif
return syms;
}
if(!(x.x|x.y|!sn)) return 0;
X[sn] = x;
unt k = 0;
for(auto it: A->v) {
int len = it.first;
bool ve = sn&1;
int dx = ve?0:len, dy = ve?len:0;
#define PPCG(O)(x.x O (ve?0:z), x.y O (ve?z:0))
#define MACR(O) { \
vec v2 = {x.x O dx, x.y O dy}; \
if(v2.y<0||(!v2.y&&v2.x<0)||abs(v2.x)>xM||v2.y>xM) \
goto LBL; \
for(int z=1; z<=len; z++) \
if(g PPCG(O)) \
goto LBL; \
for(int z=1; z<=len; z++) \
g.one PPCG(O); \
sl[sn] = O len; \
k += c(blob+it.second, v2, rlen - len, sn+1); \
for(int z=1; z<=len; z++) \
g.zero PPCG(O); \
} LBL: \
MACR(+);
MACR(-);
}
return k;
}
void stuff(a *n, unt j, unt r, unt len1)
{
unt t=0;
for(unt i=j; i<j+r; i++) {
t += s[i];
if((int)t > xM || (len1 && t>len1)) break;
if(len1 && t < len1) continue;
int r2 = r-(i-j)-1;
if(r2) {
unt x;
if(n->v.count(t))
x = n->v[t];
else
n->v[t] = x = newa - blob;
stuff(blob+x, i+1, r2, 0);
} else n->v[t] = -1;
}
}
int main()
{
time_t tim = time(0);
blob = new a[SZ];
int n;
scanf("%u",&n);
while(n--) {
nb = 0;
unt ns=0, tl=0;
while(scanf("%u",s+ns)) {
tl += s[ns];
if(++ns==MS) return 1;
if(getchar() < 11) break;
}
xM = ~-tl/2;
g.m = (unt*)calloc((xM+1)*l/SU + 1,4);
memcpy(s+ns, s, ns*SU);
unt ans = 0;
for(unt len1 = 1; (int)len1 <= xM; len1++) {
a* a0 = newa;
for(unt i=0; i<ns; i++)
stuff(a0, i, ns, len1);
ans += c(a0, {}, tl, 0);
for(unt i=0; i<nb; i++)
blob[i].v.clear();
}
printf("%d\n", ans/4);
free(g.m);
}
tim = time(0) - tim;
printf("time:%d",(int)tim);
return 0;
}
```
Compile with
```
g++ --std=c++11 -O3 feersum.cpp -o feersum.exe
```
[Answer]
# Python 3 (with [PyPy](http://pypy.org/download.html)) — N = 18
```
ANGLE_COMPLEMENTS = {"A": "C", "F": "F", "C": "A"}
MOVE_ENUMS = {"U": 0, "R": 1, "D": 2, "L": 3}
OPPOSITE_DIR = {"U": "D", "D": "U", "L": "R", "R": "L", "": ""}
def canonical(angle_str):
return min(angle_str[i:] + angle_str[:i] for i in range(len(angle_str)))
def to_angles(moves):
"""
Convert a string of UDLR to a string of angles where
A -> anticlockwise turn
C -> clockwise turn
F -> forward
"""
angles = []
for i in range(1, len(moves)):
if moves[i] == moves[i-1]:
angles.append("F")
elif (MOVE_ENUMS[moves[i]] - MOVE_ENUMS[moves[i-1]]) % 4 == 1:
angles.append("C")
else:
angles.append("A")
if moves[0] == moves[len(moves)-1]:
angles.append("F")
elif (MOVE_ENUMS[moves[0]] - MOVE_ENUMS[moves[len(moves)-1]]) % 4 == 1:
angles.append("C")
else:
angles.append("A")
return "".join(angles)
def solve(rods):
FOUND_ANGLE_STRS = set()
def _solve(rods, rod_sum, point=(0, 0), moves2=None, visited=None, last_dir=""):
# Stop when point is too far from origin
if abs(point[0]) + abs(point[1]) > rod_sum:
return
# No more rods, check if we have a valid solution
if not rods:
if point == (0, 0):
angle_str = to_angles("".join(moves2))
if angle_str.count("A") - angle_str.count("C") == 4:
FOUND_ANGLE_STRS.add(canonical(angle_str))
return
r = rods.pop(0)
if not visited:
visited = set()
move_dirs = [((r, 0), "R")]
moves2 = []
else:
move_dirs = [((r,0), "R"), ((0,r), "U"), ((-r,0), "L"), ((0,-r), "D")]
opp_dir = OPPOSITE_DIR[last_dir]
for move, direction in move_dirs:
if direction == opp_dir: continue
new_point = (move[0] + point[0], move[1] + point[1])
added_visited = set()
search = True
for i in range(min(point[0],new_point[0]), max(point[0],new_point[0])+1):
for j in range(min(point[1],new_point[1]), max(point[1],new_point[1])+1):
if (i, j) != point:
if (i, j) in visited:
search = False
for a in added_visited:
visited.remove(a)
added_visited = set()
break
else:
visited.add((i, j))
added_visited.add((i, j))
if not search:
break
if search:
moves2.append(direction*r)
_solve(rods, rod_sum-r, new_point, moves2, visited, direction)
moves2.pop()
for a in added_visited:
visited.remove(a)
rods.insert(0, r)
return
_solve(rods, sum(rods))
return len(FOUND_ANGLE_STRS)
num_rods = int(input())
for i in range(num_rods):
rods = [int(x) for x in input().split(" ")]
print(solve(rods))
```
Run with `./pypy <filename>`.
---
This is the reference implementation I wrote when discussing the question with Martin. It wasn't made with speed in mind and is quite hacky, but it should provide a good baseline to kick things off.
N = 18 takes about 2.5 minutes on my modest laptop.
## Algorithm
Rotations are checked by converting each shape into a series of `F` for forward, `A` for anticlockwise turn and `C` for clockwise turn at each lattice point on the boundary of the shape — I call this an *angle string*. Two shapes are rotationally identical if their angle strings are cyclic permutations. Rather than always checking this by comparing two angle strings directly, when we find a new shape we convert to a canonical form before storing. When we have a new candidate, we convert to the canonical form and check if we already have this (thus exploiting hashing, rather than iterating through the whole set).
The angle string is also used to check that the shape is formed anticlockwise, by making sure that the number of `A`s exceeds the number of `C`s by 4.
Self-intersection is naïvely checked by storing every lattice point on the boundary of the shape, and seeing if a point is visited twice.
The core algorithm is simple, placing the first rod to the right, then trying all possibilities for the remaining rods. If the rods reach a point which is too far from the origin (i.e. sum of remaining rod lengths is less than the Manhattan distance of the point from the origin), then we prematurely stop searching that subtree.
## Updates (latest first)
* 6/12: Introduced canonical form, added a few micro-optimisations
* 5/12: Fixed error in algorithm explanation. Made the quadratic cyclic-permutation-checking algorithm linear using the A,B cyclic permutations iff A substring of B+B method (I have no idea why I didn't do this earlier).
] |
[Question]
[
**Plot**: Jimmy is missing; we have to find him. We should split up.
**Plot twist**: Jimmy is already dead.
But, our cast doesn't know that, so they need to search the whole area anyway. There is an N columns x M rows (1<=M,N<=256) grid of cells,
either marked as "S" for the starting point, "." for open space, or "#" for an obstacle. This is the **map**.
There are 0<=p<=26 **costars**, 0<=q<=26 **extras**, and 1 **star**. Everyone is initially in the cell marked S.
## The Rules
Each person has a sight radius shown below:
```
...
.....
..@..
.....
...
```
The star is denoted by "@", the costars by capital letters, starting with "A", and the extras by lowercase letters, starting with "a". Initially, the sight radius surrounding the starting point is already marked as searched. If this constitutes the entire open space of the map, the game ends. Each turn, **in the following order**:
1. Each person simultaneously makes a king move (either standing still, or moving to one of the 8 neighboring cells).
2. All of the cells in the sight radius around each person are counted as searched.
3. If a costar cannot see anyone else, she dies. If an extra cannot see either a costar, the star, or at least 2 other extras, he dies. **These happen simultaneously** -- that is, there can be no chain reaction of deaths on a single turn; the above conditions are checked, and everyone who is going to die dies at once.
4. If all of the open space on the map has been searched, the search is over.
## Notes
Multiple people can be on the same square at any point, and these people can see each other.
Obstacles never impede sight, only movement; people can see each other across the, er... lava?
The open spaces on the map are guaranteed to be connected by king moves.
The initial "S" is also considered to be open space, rather than an obstacle.
Any king move that lands on an open space is valid. For instance, the following move is legal:
```
.... ....
.@#. ---> ..#.
.#.. .#@.
.... ....
```
## Input
The input will be in the format
```
N M p q
[N cols x M rows grid with characters ".", "#", and "S"]
```
Sample inputs:
```
6 5 0 0
......
......
..S...
......
......
```
and
```
9 9 1 1
S.......#
.......##
......##.
..#####..
...##....
...##....
...#.....
....#..#.
.........
```
p and q are the numbers of costars and extras, respectively.
## Output
The output should be, for each turn, the moves that are made, with directions indicated by
```
789
456
123
```
The order of the moves does not matter, as they are all enacted simultaneously. Not listing a move for a person is fine, and is equivalent to moving him in direction 5. Moves should be listed in the following format:
```
@9 A2 a2 B7.
```
"." denotes the end of your moves for a turn.
After the map has been searched, the final line of output should be three integers, separated by spaces: the number of turns that it took you to finish searching the board, the number of living costars, and the number of living extras. For the first example input
```
6 5 0 0
......
......
..S...
......
......
```
the following is valid output:
```
@4.
@6.
@6.
@6.
4 0 0
```
A final note: the star cannot die and the open space on the map is guaranteed to be connected, so the search will always succeed eventually.
## Scoring
Your score is the **total number of turns** taken over a set of benchmark tests; you're welcome to submit your own test case along with your answer. The sum of the number of living costars over the benchmark set will be used as a tie-breaker, and in the event there is still a tie, the sum of the number of living extras will be used.
## Test Set and Controller
Currently, 5 maps are online at <https://github.com/Tudwell/HorrorMovieSearchParty/>. Anyone submitting an answer may also submit a test case, which I reserve the right to reject for any reason (if I reject your map for some reason, you may submit another). These will be added to the test set at my discretion.
A Python **(tested in 2.7.5)** controller is provided on github as
**[controller.py](https://github.com/Tudwell/HorrorMovieSearchParty/blob/master/controller.py)**. A second controller there, **[controller\_disp.py](https://github.com/Tudwell/HorrorMovieSearchParty/blob/master/controller_disp.py)**, is identical except that it shows graphical output during the search (requires Pygame library).

**Usage**:
```
python controller.py <map file> <your execution line>
```
I.e.:
```
python controller.py map1.txt python solver.py map1.txt
```
The controller has output (to your program's **stdin**) of the form
```
Turn 1
@:2,3 A:2,3 B:2,3.
##...##
#ooo..#
ooooo..
ooooo..
ooooo..
#ooo...
##.....
###....
----------------------------------------
```
This is the turn number (turn 1 is before you have moved), a '.'-terminated list of all the actors and their x,y coordinates (the upper left character is (0,0)), a representation of the entire board, and a line with 40 '-'s. It then waits for input (from your program's **stdout**) of the form
```
@9 A2 B7.
```
This is the output format specified above. The controller outputs a 'o' for open space that has been searched, '.' for open space that has not been searched, and '#' for obstacles. It includes only living people in its list of people and their coordinates, and tracks all rules of the game. The controller will exit if an illegal move is attempted. If the moves for a given turn finish the search, the output is not as above; instead it is of the form
```
Finished in 4 turns
4 1 0
```
"4 1 0" here denotes 4 total turns, 1 living costar, and 0 living extras. You do not need to use the controller; feel free to use it or modify it for your own entry. If you decide to use it and encounter problems, let me know.
Thanks to @githubphagocyte for helping me write the controller.
**Edit:**
For a randomized entry, you can choose any run on a particular map as your score for that map. Note that due to the scoring requirements, you should always choose the fewest turns, then the fewest dead costars, then the fewest dead extras for each map.
[Answer]
## Ruby, Safety First + BFS + Randomness, Score ≤ 1458
I'm not sure how you'll be scoring random submissions. If all answers have to be deterministic, let me know and I'll pick a seed or get rid of the randomness altogether.
Some features and shortcomings of this solution:
* No one ever dies. At the start I group all the actors such that everyone is safe. The characters in each of these groups move in unison. That's good for keeping everyone alive but not optimally efficient.
* Each of the groups searches for the nearest unexplored spot on the map via breadth-first search and takes the first move of that branch of the search. If there is tie between multiple optimal moves a random one is picked. This is to ensure that not all groups always head in the same direction.
* This program doesn't know about field-of-view. It actually tries to move to every unexplored cell. Taking this into account might considerably increase the performance, since then you could also quantify the quality of each move by how many cells it will uncover.
* The program doesn't keep track of information between turns (except the actor groups). That makes it quite slow on the larger test cases. `map5.txt` takes between 1 and 13 minutes to complete.
Some results
```
Map Min turns Max turns
map1 46 86
map2 49 104
map3 332 417
map4 485 693
map5 546 887
```
Now here is the code:
```
start = Time.now
map_file = ARGV.shift
w=h=p=q=0
File::open(map_file, 'r') do |file|
w,h,p,q = file.gets.split.map(&:to_i)
end
costars = p > 0 ? (1..p).map {|i| (i+64).chr} : []
extras = q > 0 ? (1..q).map {|i| (i+96).chr} : []
groups = []
costars.zip(extras).each do |costar, extra|
break unless extra
groups << (costar + extra)
costars.delete(costar)
extras.delete(extra)
end
costars.each_slice(2) {|c1, c2| groups << (c1 + (c2 || '@'))} unless costars.empty?
extras.each_slice(3) {|c1, c2, c3| groups << (c1 + (c2 || '') + (c3 || '@'))} unless extras.empty?
groups << '@' unless groups.join['@']
#$stderr.puts groups.inspect
directions = {
1 => [-1, 1],
2 => [ 0, 1],
3 => [ 1, 1],
4 => [-1, 0],
5 => [ 0, 0],
6 => [ 1, 0],
7 => [-1,-1],
8 => [ 0,-1],
9 => [ 1,-1]
}
loop do
break unless gets # slurp turn number
coords = {}
input = gets
input.chop.chop.split.each{|s| actor, c = s.split(':'); coords[actor] = c.split(',').map(&:to_i)}
#$stderr.puts input
#$stderr.puts coords.inspect
map = []
h.times { map << gets.chomp }
gets # slurp separator
moves = groups.map do |group|
x, y = coords[group[0]]
distances = {[x,y] => 0}
first_moves = {[x,y] => nil}
nearest_goal = Float::INFINITY
best_move = []
active = [[x,y]]
while !active.empty?
coord = active.shift
dist = distances[coord]
first_move = first_moves[coord]
next if dist >= nearest_goal
[1,2,3,4,6,7,8,9].each do |move|
dx, dy = directions[move]
x, y = coord
x += dx
y += dy
next if x < 0 || x >= w || y < 0 || y >= h || map[y][x] == '#'
new_coord = [x,y]
if !distances[new_coord]
distances[new_coord] = dist + 1
first_moves[new_coord] = first_move || move
active << new_coord if map[y][x] == 'o'
end
if dist < distances[new_coord]
distances[new_coord] = dist + 1
first_moves[new_coord] = first_move || move
end
if map[y][x] == '.'
if dist + 1 < nearest_goal
nearest_goal = dist + 1
best_move = [first_moves[new_coord]]
elsif dist + 1 == nearest_goal
best_move << first_moves[new_coord]
end
end
end
end
#if group['@']
# distances.each{|k,v|x,y=k;map[y][x]=(v%36).to_s(36)}
# $stderr.puts map
#end
dir = best_move.sample
group.chars.map {|actor| actor + dir.to_s}
end * ' '
#$stderr.puts moves
puts moves
$stdout.flush
end
#$stderr.puts(Time.now - start)
```
There are a few commented out debug outputs in there. Especially the `if group['@']` block is quite interesting because it prints out a visualisation of the BFS data.
**Edit:** Significant speed improvement, by stopping the BFS if a better move has already been found (which was kinda the point of using BFS in the first place).
] |
[Question]
[
Given an 8x8 grid of letters representing the current state of a game of chess, your program's task is to find a next move for white that results in checkmate (the answer will always be mate in one move).
## Input
Input will be on STDIN - 8 lines of 8 characters each. The meanings of each character are as follows:
```
K/k - king
Q/q - queen
B/b - bishop
N/n - knight
R/r - rook
P/p - pawn
- - empty square
```
Upper case letters represent white pieces, and lower case represents black.
The board will be oriented so that white is playing up from the bottom and black is playing down from the top.
## Output
A move for white that results in checkmate, in [algebraic notation](http://en.wikipedia.org/wiki/Algebraic_notation_%28chess%29). You do not need to notate when a piece has been taken, nor do you need to be concerned about disambiguating between two identical pieces which can make the same move.
## Sample input
**Example 1**
Input:
```
------R-
--p-kp-p
-----n--
--PPK---
p----P-r
B-------
--------
--------
```
Output:
```
c6
```
**Example 2**
Input:
```
--b-r--r
ppq-kp-p
-np-pn-B
--------
---N----
--P----P
PP---PP-
R--QRBK-
```
Output:
```
Nf5
```
**Example 3**
Input:
```
---r-nr-
-pqb-p-k
pn--p-p-
R-------
--------
-P-B-N-P
-BP--PP-
---QR-K-
```
Output:
```
Rh5
```
You can assume that the solution will not involve castling or en-passant.
This is code-golf - shortest solution wins.
(~~Examples taken from mateinone.com - puzzles 81, 82 and 83~~ Website has been replaced with spam)
[Answer]
### Ruby, 589 512 510 499 493 characters
```
R=0..7
a=->b{o=[];R.map{|r|R.map{|c|v=Hash[?K,[6,7,8,11,13,16,17,18],?R,s=[157,161,163,167],?B,t=[156,158,166,168],?Q,s+t,?N,[1,3,5,9,15,19,21,23],?P,[32,181,183]][z=b[r][c]];v&&v.map{|s|k=2!=l=s/25+1;u=r;v=c;l.times{u+=s/5%5-2;v+=s%5-2;R===u&&R===v||break;t=b[u][v];j=t<?.&&l<8;(j||t=~/[a-z]/&&k)&&o<<=(h=b.map &:swapcase;h[u][v]=h[r][c];h[r][c]=?-;[z+"%c%d"%[97+v,8-u],h.reverse]);j&&(k||r==6)||break}}}};o}
a[$<.map{|l|l}].map{|m,b|a[b].any?{|f,x|a[x].all?{|g,y|y*""=~/K/}}||$><<m[/[^P]+/]}
```
Input is given via stdin, e.g.:
```
> ruby mateinone.rb
--------
--------
--------
-k------
b-------
-N-P----
--------
-----K-Q
^Z
Qb7
```
The output is not just one move that forces a mate in one but every move that does so.
*Edit 1:* The function `e` was used only once so I inlined it. Second, the encoding now is based on number 5 instead of 10. And refactoring the cloning of the board saved quite a few chars.
*Edit 2:* Still not as much improvement as I wanted. Changing the hash from `{a=>b,c=>d}` to `Hash[a,b,c,d]`. This costs 4 characters but saves one per key-value pair.
*Edit 3:* Only minor reductions: inlining M (4 characters), `t==?-` -> `t<?.` (2), removing Pawn in algebraic notation at the end (2), replaced puts (3). The program is now less than 500 characters.
*Edit 4:* It is interesting how much one can still find in such a program. Moved an invariant outside the loop and found another duplicate calculation.
] |
[Question]
[
In this challenge, you are given two overlapping rectangles, and you need to calculate the rectangles created by removing one from the other.
For example, if you remove the red rectangle from the black one:
[](https://i.stack.imgur.com/cisSA.png)
You end up with one of the following two rectangle sets:
[](https://i.stack.imgur.com/N6TeR.png) [](https://i.stack.imgur.com/MNbb6.png)
You'll also need to handle the following:
[](https://i.stack.imgur.com/0kFov.png)
To be more explicit:
* You will input the coordinates of two rectangles, A and B.
* You need to output the fewest non-overlapping rectangles that cover all of the area of A without B. Any possible covering is allowed
* Rectangular coordinates are passed as 4 integers. You can pass them in two pairs (representing the two corner points), or as a tuple/list of 4 integers. Your inputs and outputs need to be consistent.
* A and B will not necessarily overlap or touch, and each will have an area of at least 1
# Test cases:
```
[(0 0) (5 5)] [(3 4) (8 7)] -> [(0 0) (5 4)] [(0 4) (3 5)] # or [(0 0) (3 5)] [(3 0) (5 4)]
[(2 4) (10 11)] [(5 5) (6 6)] -> [(2 4) (10 5)] [(2 5) (5 6)] [(6 5) (10 6)] [(2 6) (10 11)] #Other sets of 4 rectangles are possible
[(3 3) (8 8)] [(0 1) (10 8)] -> #No rectangles should be output
[(0 0) (5 5)] [(1 1) (10 2)] -> [(0 0) (1 5)] [(1 0) (2 1)] [(2 0) (5 5)] #Other sets of 3 rectangles are possible
[(1 5) (7 8)] [(0 0) (1 10)] -> [(1 5) (7 8)] #Only possible output
[(4 1) (10 9)] [(2 5) (20 7)] -> [(4 1) (10 5)] [(4 7) (10 9)] #Only possible output
[(1 1) (8 8)] [(0 6) (9 9)] -> [(1 1) (8 6)] #Only possible output
```
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so make your code as short as possible!
[Answer]
# [Python 2](https://docs.python.org/2/), ~~375~~ ~~360~~ ~~345~~ 343 bytes
```
from itertools import*;P=product
def f(S,M):(l,t),(r,b)=S;(L,T),(R,B)=M;u,v,x,y=(L>=r)+(l<L),(T>=b)+(t<T),(R>=r)+(l<R),(B>=b)+(t<B);return[S]if v==y!=1or u==x!=1else[list(p(p(*zip(*(S+M))),repeat=2))[[43,197,6,199,9,231,142,229,53,189,134,181][int(i,36)]]for i in '38,491,258,2058,8,4B,28,208,7,41,27,461,,4,2,4A'.split(',')[u+2*v+4*x+8*y-12]]
```
[Try it online!](https://tio.run/##ZZBRb5swFIXf@RXsCRvOJmwcAk0dadlrIk1N3xAP7QqaJRqQMVGyP59d3KbbMpAuHJ/vcIyHs/vZH@Tl0tr@NTSusa7vuzE0r0NvXbz6rgfbv0w/XPDStGHL9tjxO9bBcTCLZ673K7bFI6kHbLjerSYcccJZs@1aW56w7n5L5uNaP5Nw9568Og8kNldnw1e2cZM9VPvatOFR6/MnLXobTlqf6K3pxqbqzOjYQHf8y9Bg@2THOYdthubJacl5VakMolwip1mihMwEhJKQssSCrKKEyBQ9RV2Zg2MGWc7ruqUiE5pDGGUFVCkgFwVkSoPkBnIWBZZQ5NDMBaAgob5GX8ahM45FiHg1JTI@Jio@JUV8/ixkXV/mY3PN6L49jQ2zAlbyuyCka7BUH/oVRHodoX23g@CDr1iKlA5pgQWvUbEMihTtg9f8b0r6dZFCCM/NPFiO/IbLkPl84SnC31LFDfZvqbhi8gYTvmX58bU5RHB6g6lrvvSc9CmZ/vcTbz1/NpeTKucQDy6/AQ "Python 2 – Try It Online")
EDITS: -15 from suggestions from @notjagan; another -15 by re-encoding the array of solution rectangles to int36 format and a short lookup table; another -2 by replacing product with p as per @musicman.
A function that takes two rectangles, each rect being a tuple of ((left,top), (right,bottom)); returns a list of the resulting rectangles.
The basic strategy:
```
| |
0,0 | 1,0 | 2,0
-----A-----+-----
| |
0,1 | 1,1 | 2,1
-----+-----B-----
| |
0,2 | 1,2 | 2,2
| |
```
In the above diagram, the points A and B are the upper left and lower right, respectively, of the 'Source' rectangle (the first rect).
We find the placement of each of the the upper left `(u,v)` and lower right `(x,y)` of the 'Mask' rectangle in that grid.
If both these points are in the first or last column; or first or last row; then there is no overlap; and we can return just the Source rect.
Otherwise, there are 16 cases remaining; for example, the OP's first example is the case we can label `(1,1),(2,2)`. Each case can be mapped to a set of resulting rectangles whose corners are always coordinates with horizontal values in either Source rectangles left,right, or the Mask rectangles left,right; and similarly for the vertical values, the Source's top,bottom or the masks.
For example, for the `(1,1),(2,2)` case, the rectangles would be `((l,t),(T,r))` and `((l,T),(R,b))`, where `l,t,r,b` and `L,T,R,B` are the left, top, right and bottom of the Source and Mask rectangles, respectively.
So we can create a lookup table that maps the coordinates to the set of all such possible combinations (which is what the `product(product(*zip(*)))` bit is about) to a set of rectangles that should be provided for each of the cases (which, after some golfy-decompression, is what the rest of the list stuff is about).
[Answer]
# JavaScript, 115 bytes
```
f=a=>b=>b.some((n,i)=>(a[i^2]<n)^i/2)?[a]:b.map((n,i)=>a[i&1]<n&&n<a[i|2]&&(p=[...a],p[i^2]=a[i]=n,p)).filter(x=>x)
```
overlapping version:
```
f=a=>b=>b.some((n,i)=>(a[i^2]<n)^i/2)?[a]:b.map((n,i)=>a[i&1]<n&&n<a[i|2]&&(p=[...a],p[i^2]=n,p)).filter(x=>x)
```
Input in following format: `f([1,1,8,8])([0,6,9,9])`
---
Denote input as ((x1, y1), (x2, y2)), ((x3, y3), (x4, y4))
If any one of following conditions is met, return first rectangle as is:
* x3 > x2
* x4 < x1
* y3 > y2
* y4 < y1
otherwise
* If x1 < x3 < x2 then we generate a rectangle ((x1, y1), (x3, y2)); and set x1 := x3
* If x1 < x4 < x2 then we generate a rectangle ((x4, y1), (x2, y2)); and set x2 := x4
* If y1 < y3 < y2 then we generate a rectangle ((x1, y1), (x2, y3)); and set y1 := y3
* If y1 < y4 < y2 then we generate a rectangle ((x1, y4), (x2, y2)); and set y2 := y4
[Answer]
# Java, 268 bytes
```
class W{public static void main(String[]z) {int a[]={0,0,0,0},i,j,y[]={0,1,4,3,6,1,2,3,4,1,6,5,4,7,6,3};for(i=0;i<4;i+=1){for(j=0;j<4;j+=1){a[j]=Integer.parseInt(z[y[i*4+j]]);}if(a[0]<a[2] && a[1]<a[3]){for(j=0;j<4;j+=1){System.out.println(String.valueOf(a[j]));}}}}}
```
Ungolfed
```
class W{
public static void main(String[]z) {
int a[]={0,0,0,0},i,j,y[]={0,1,4,3,6,1,2,3,4,1,6,5,4,7,6,3};
for(i=0;i<4;i+=1){
for(j=0;j<4;j+=1){
a[j]=Integer.parseInt(z[y[i*4+j]]);
}
if(a[0]<a[2] && a[1]<a[3]){
for(j=0;j<4;j+=1){
System.out.println(String.valueOf(a[j]));
}
}
}
}
}
```
Pass input as arguments. Example
```
java -jar W.jar 0 0 5 5 3 4 8 7
```
[Answer]
# [Python 2](https://docs.python.org/2/), 272 bytes
```
lambda((a,b),(c,d)),((e,f),(g,h)):[([([[(a,b),(e,min(h,d))]]+[[(g,max(b,f)),(c,d)]]*2+[[(max(a,e),b),(c,f)]]*4+[[(a,h),(min(c,g),d)]])[m-1]for m in M&{1,2,4,8}]if M&{0}else[(a,b),(c,d)])for M in[{(x<e)*1+(x>g)*2+(y<f)*4+(y>h)*8 for x in range(a,c)for y in range(b,d)}]][0]
```
[Try it online!](https://tio.run/##fZLdbqMwEIXveYqRKm3tZCphQwip2tzsdXcfgPUFJCZEIhABkRJVefbs2PyW/YELZM93zhyPOd@arCzkI33/9cjjU7KPGYsx4ch2uOf0YRpT@hww4/w1YvRGHaDxdCxYZjCllrR9wFN8ZQnxnVyphTQFsx2j5p1vagr@0hpltGNsdnjgVsGj04tQaVnBCY4FfHz7FCjRx/CujqlZuned1zqapFTc4B@ER5/s@qb5QizZdXvg1J3d3lJOzdhtm/FFCIa8GuMqLg6aTHZWfBu3EnK8KxW56rHXKTS6br7HtWaVwEryVwfoOVfHogG7g8/v22dMu7LjDHzEXHQp4QpXXGHEPPRpFeKa8k4pafeFi0JYzvDIAgxmnIee1YeWIrxVhTPsa1PRY3KGCdtlPbgZEcHuDPN7/cZy0qqk@8ch2j5juIBWGyPizoPW4HJgK6BMQAcBn1YhkAeN8mULI@BbwLWAZ/EnoNvpAW9wGHCHQllcuGAGSFXTB1gAgfG39gPRyqUFVhaICFy1xaArBhM3ep5@NpmuoNZNDWUKPlR619Cfkusa4krDuazrY5Jrx@Ty7MnC7hiidQr7gxq3H@XUoM7KS76HREN5ac6XxpkPS/Qmcj4tMRBmJUF08Uf1PLr3n@jCTmE9RG87mP@h7zolyLnIb4N@DO/3cTeTSUt3etcD0sb3qTYo/unbjmGcrLmjTSsZ87WIvfa/G/0G "Python 2 – Try It Online")
This works by testing every cell inside the first rectangle for leftness=1,aboveness=4,rightness=2,and belowness=8 w/r to the other, and ORing the result. If the other does not intersect=0 with the first, then the original is returned, otherwise some combination of a left slice, right slice, upper slice and lower slice is returned, with accomodation for overlap.
] |
[Question]
[
In math, a [permutation](https://en.wikipedia.org/wiki/Permutation) ***σ*** of order ***n*** is a bijective function from the integers 1...***n*** to itself. This list:
```
2 1 4 3
```
represents the permutation ***σ*** such that ***σ***(1) = 2, ***σ***(2) = 1, ***σ***(3) = 4, and ***σ***(4) = 3.
A square root of a permutation ***σ*** is a permutation that, when applied to itself, gives ***σ***. For example, `2 1 4 3` has the square root ***τ*** =`3 4 2 1`.
```
k 1 2 3 4
τ(k) 3 4 2 1
τ(τ(k)) 2 1 4 3
```
because ***τ***(***τ***(k)) = ***σ***(k) for all 1≤k≤n.
### Input
A list of ***n***>0 integers, all between 1 and ***n*** inclusive, representing a permutation. The permutation will always have a square root.
You may use a list of 0...***n-1*** instead as long as your input and output are consistent.
### Output
The permutation's square root, also as an array.
### Restrictions
Your algorithm must run in polynomial time in ***n***. That means you can't just loop through all ***n***! permutations of order ***n***.
Any builtins are permitted.
### Test cases:
Note that many inputs have multiple possible outputs.
```
2 1 4 3
3 4 2 1
1
1
3 1 2
2 3 1
8 3 9 1 5 4 10 13 2 12 6 11 7
12 9 2 10 5 7 4 11 3 1 13 8 6
13 7 12 8 10 2 3 11 1 4 5 6 9
9 8 5 2 12 4 11 7 13 6 3 10 1
```
[Answer]
# Perl, ~~124~~ 122 bytes
Includes +3 for `-alp`
Run with the 1 based permutation on STDIN:
```
rootperm.pl <<< "8 3 9 1 5 4 10 13 2 12 6 11 7"
```
`rootperm.pl`:
```
map{//;@{$G[-1]^$_|$0{$_}}{0,@G}=(@G=map{($n+=$s{$_=$F[$_-1]}++)?():$_}(0+$',0+$_)x@F)x2,%s=$n=0for@F}@F;$_="@0{1..@F}"
```
Complexity is ***O(n^3)***
[Answer]
# Mathematica, 165 ~~167~~ bytes
An unnamed function.
```
PermutationList[Cycles@Join[Riffle@@@#~(s=Select)~EvenQ@*(l=Length)~SortBy~l~Partition~2,#[[Mod[(#+1)/2Range@#,#,1]&@l@#]]&/@#~s~OddQ@*l]&@@PermutationCycles@#,l@#]&
```
Semi-ungolfed:
```
PermutationList[
Cycles@Join[
Riffle@@@Partition[SortBy[Select[#,EvenQ@*Length],Length], 2],
#[[Mod[(Length@#+1)/2Range@Length@#,Length@#,1]]]& /@ Select[#,OddQ@*Length]
]& @@ PermutationCycles @ #,
Max@#
]&
```
[Answer]
# Prolog - 69 chars
```
p([],_,[]). p([H|T],B,[I|U]):-p(T,B,U),nth1(H,B,I). f(X,Y):-p(Y,Y,X).
```
Explanation:
```
permutate([], _, []). % An empty permutation is empty
permutate([X|Xs], List, [Y|Ys]) :- % To permutate List
permutate(Xs, List, Ys), % Apply the rest of the permutation
nth1(X, List, Y). % Y is the Xth element of List
root(Permutation, Root) :- % The root of Permutation
permutate(Root, Root, Permutation). % Applied to itself, is Permutation
```
] |
[Question]
[
Given a polynomial, determine whether it's prime.
A polynomial is `ax^n + bx^(n-1) + ... + dx^3 + ex^2 + fx + g`, where each term is a constant number (the coefficient) multiplied by a nonnegative integer power of `x`. The highest power with a nonzero coefficient is called the degree. For this challenge, we only consider polynomials of at least degree 1. That is, each polynomial contains some `x`. Also, we only use polynomials with integer coefficients.
Polynomials can be multiplied. For example, `(x+3)(2x^2-2x+3)` equals `2x^3+4x^2-3x+9`. Thus, `2x^3+4x^2-3x+9` can be factored into `x+3` and `2x^2-2x+3`, so it is composite.
Other polynomials can not be factored. For example, `2x^2-2x+3` is not the product of any two polynomials (ignoring constant polynomials or those with non-integer coefficients). Hence, it is prime (also known as irreducible).
## Rules
* Input and output can be through any standard way.
* Input can be a string like `2x^2-2x+3`, a list of coeffecients like `{2,-2,3}`, or any similar means.
* Output is either a truthy value if it's prime, or a falsey value if it's composite. You must yield the same truthy value for all primes, and the same falsey value for all composite polynomials.
* The input will be of at least degree 1 and at most degree 10.
* You may not use built-in tools for factorization (of integers or expressions) or equation solving.
## Examples
### True - prime
```
x+3
-2x
x^2+x+1
x^3-3x-1
-2x^6-3x^4+2
3x^9-8x^8-3x^7+2x^3-10
```
### False - composite
```
x^2
x^2+2x+1
x^4+2x^3+3x^2+2x+1
-3x^7+5x^6-2x
x^9-8x^8+7x^7+19x^6-10x^5-35x^4-14x^3+36x^2+16x-12
```
[Answer]
# Mathematica, 224 bytes
```
f@p_:=(e=p~Exponent~x;r=Range[⌈e/-4⌉,(e+2)/4];e<2||FreeQ[PolynomialRemainder[p,Thread@{r,#}~InterpolatingPolynomial~x,x]&/@Tuples[#~Join~-#&[Join@@Position[#/Range@Abs@#,_Integer]]&/@#]~DeleteCases~{(a_)..},0|{}]&[p/.x->r])
```
---
**Explanation**:
[Kronecker's method](https://en.wikipedia.org/wiki/Factorization_of_polynomials#Classical_methods) is used here. This method generates certain lower degree polynomials and tests whether there exists a factor of the original polynomial.
**Test cases**:
```
f/@{x+3, -2x, x^2+x+1, x^3-3x-1, -2x^6-3x^4+2, 3x^9-8x^8-3x^7+2x^3-10}
(* {True, True, True, True, True, True} *)
f/@{x^2, x^2+2x+1, x^4+2x^3+3x^2+2x+1, -3x^7+5x^6-2x, x^9-8x^8+7x^7+19x^6-10x^5-35x^4-14x^3+36x^2+16x-12}
(* {False, False, False, False, False} *)
```
It takes 14s on my laptop to conclude that `3x^9-8x^8-3x^7+2x^3-10` is prime.
[Answer]
## PARI/GP, 16 bytes, cheap as hell
For some reason this wasn't disallowed (noting that the command doesn't factor or equation-solve):
```
polisirreducible
```
Test case
```
%(x^2+x+1)
```
returns `1` (true). The other examples work similarly.
But to show that this is solvable the hard way, here's a full solution.
## Less cheap, but sloooooooooow
There's really no point golfing this.
```
Beauzamy(P)=
{
my(d=poldegree(P),s,c);
s=sum(i=0,d,polcoeff(P,i)^2/binomial(d,i));
c = 3^(3/2 + d);
c *= s / (4*d*Pi);
abs(c * pollead(P))
}
factorpol(P)=
{
my(B=Beauzamy(P)\1, t=B*2+1, d=poldegree(P)\2, Q);
for(i=0,t^(d+1)-1,
Q=Pol(apply(n->n-B, digits(i,t)));
if(Q && poldegree(Q) && P%Q==0, return(Q))
);
0
}
irr(P)=
{
factorpol(P)==0
}
```
Edit: Commenters have pointed out that the first method may be disallowed by good taste, the spirit of the rules, the Geneva Convention, standard loophole rules, etc. I don't agree, but in any case I posted the second version along with the first and certainly it seems acceptable.
] |
[Question]
[
A complete [deterministic finite automaton](https://en.wikipedia.org/wiki/Deterministic_finite_automaton) is a machine, with some states. Each state in the automaton has, for each character in the alphabet, a pointer to a state (not necessarily a different one). The automaton starts at some state, and then reads a string, character by character. For each character, the automaton moves to the pointer of its current state for the character.
For a given automaton, a [synchronizing word](https://en.wikipedia.org/wiki/Synchronizing_word) is a string which will bring the automaton to the same state, regardless of which state it started in.
For example, the following automaton:
[](https://i.stack.imgur.com/rJccR.png)
Has `0100` as a synchronizing word, which synchronizes all states to 2.
Not all automata have a synchronizing word. For example, the following automaton:
[](https://i.stack.imgur.com/p8OZU.png)
Doesn't have any synchronizing word - if the length of the string is even then 0 will stay in 0 and 1 will stay in 1, and if it's odd they will swap - in any case, they won't go into the same state.
Your challenge is to write the shortest program you can that checks, given a complete automaton over an alphabet with two characters, if there exists a synchronizing word for it.
# Test cases
Using a 0-indexed, 2Xn array.
```
[[0, 1], [0, 1]] -> true
[[1, 1], [0, 0]] -> false
[[0, 0], [1, 1]] -> false
[[4, 1], [0, 3], [0, 0], [0, 1], [4, 3]] -> true
[[2, 1], [3, 4], [0, 4], [2, 1], [0, 3]] -> true
[[4, 4], [0, 4], [2, 1], [0, 3], [0, 0]] -> false
[[8, 5], [0, 8], [0, 0], [8, 2], [2, 6], [5, 2], [3, 8], [7, 3], [8, 4], [3, 0]] -> true
[[9, 2], [8, 4], [2, 5], [6, 9], [8, 9], [9, 5], [4, 0], [4, 2], [0, 7], [2, 1]] -> true
[[5, 0], [3, 7], [9, 2], [9, 0], [1, 8], [8, 4], [6, 5], [7, 1], [2, 4], [3, 6]] -> true
[[5, 1], [4, 9], [8, 1], [8, 6], [2, 3], [7, 0], [2, 3], [5, 6], [4, 9], [7, 0]] -> false
[[6, 3], [1, 1], [7, 5], [7, 1], [4, 5], [6, 6], [4, 6], [5, 1], [3, 4], [2, 4]] -> false
```
# Rules
* You can use any reasonable I/O format. In particular, any of the following input methods are allowed:
+ A map, multidimensional array, or array of maps, denoting, for each state and character, to which state the automaton transitions. The states can be either 0-indexed or 1-indexed.
+ Any builtin directed graph object which can support multiedges, self-loops, and labeled edges.
+ Any builtin DFA object.
+ You can choose any two characters to be the alphabet.
* You can output any two distinct values, or a truthy/falsey (or reversed) value in your language.
* You may **not** assume Černý's conjecture (which states that if there exists a synchronizing word, there must be one of length \$(n-1)^2\$).
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed.
[Answer]
# [Python](https://www.python.org), ~~92~~ 91 bytes
```
f=lambda a,s,n=0:n<len(s)**3and any(f(a,[a[t][d]for t in s],n+1)for d in"01")or len({*s})<2
```
[Attempt This Online!](https://ato.pxeger.com/run?1=fZG_asMwEIfpqqcQymI5V9AfD8HEa58gm_BwrWNqcJRgKUMwfpIuWdJ3ap-milyDwU0Xcfdx-vRD9_F5uvj3o71eb2dfP2--TF20eHitkCI4sIXI7bbd28TxNNVoK4r2ktQJgkHjS1OV9bGjnjaWuhLsWvJ7X4WeCcl4qO-X-9QNfKvGJ76f3lYv2Lo9aWhBjQBZEgxVTygVec8EyyUwGc4BApIjEhGJgQzk1DXWxwwN54Q81oilRj7UrHbd-Z9If7gmtHRNFlCgIVu41G-ImUtHlEWk5voR6Xl6FVE2n9KLEONfT2v9AQ)
Takes in an automaton `a` which is a dictionary of dictionaries where `a[x][c]` describes the state to travel to from state `x` given character `c`, and an array `s` which contains all of the states of the automaton. The characters in the alphabet are the strings `0` and `1`.
This code does a very inefficient brute force iteration over all possible words with length less than \$n^3\$ (where \$n\$ is number of states).
---
-1 byte from @Steffan
# [Python](https://www.python.org), 87 bytes
```
f=lambda a,s,q,n=0:n<q**3and any(f(a,{a[t][d]for t in s},q,n+1)for d in"01")or len(s)<2
```
[Attempt This Online!](https://ato.pxeger.com/run?1=fZFLasMwEIbpVqcYlI2VTEEPF4KJtz1BoQvjxRTH1NRVEltZBOOTdJNNe6f2NFXkGkzz2AzDx_DNP9LH1_bgXjf2ePzcu_J--f1cpjW9vxQEhC3u0KYysavdfG7IFkD2EJURYUeZy7MiLzcNOKgstP1pdqHEiRSecKm48H29tlErVnrQ_9y9zR6pbtesghQyiSpn5LuOAcik45InCrnytUeP1IBkQLJnPds2lXUhQoVaCMaui-S5SN0QzZ6a_Y1YF2wjumQbPajRYHxm039BJjYTUByQni4YkJleoAOKp1Pmf4wHIYY3H7_2Fw)
Same as above, except it also takes in a parameter `q` which describes the number of states in the automaton.
[Answer]
# [Haskell](https://www.haskell.org/), 73 bytes
```
r!w|let[_]%_=1>0;s%y=all(/=s)y&&or[[u|u<-w,elem u$k<$>s]%(s:y)|k<-r]=w%[]
```
[Try it online!](https://tio.run/##tY3BToQwFEX3fsWdBCZtQlFgJ5SNW92b1IZUqEoozKQdgkT8dStDTFzMxo2rl3vuyX1vynXaGO/tblqMPolKhhVPypvchTNXxpBr7ui83x@sEOMyFmyKtNE9xqArgtLJkLjbmS5dwazkUyik71U7gKM5XAG9Oj5UIDjadjghxjjUo7UzyI6CIlgNCBDRNjKCSOI4k/TMopU91cppfCRgJdIc1fkmn3/1IvzwdMs5tj7LkW3ef@68szK9xBv5jW2zLl@a0n/VL0a9Os8e71X/3Ki79fs3 "Haskell – Try It Online")
Takes input as a list of states, and a list of transitions as functions between states.
Not complicated, does a depth first search.
[Answer]
# Python3, 471 bytes:
```
E=enumerate
def f(n,m,c=[]):
yield c,n
for i,(I,a)in E(m[n]):M=eval(str(m));del M[n][i];yield from f(a,M,c+[(a,I)])
def M(m,B,p):
if''==p:return B
return M(m,dict(m[B])[int(p[0])],p[1:])
def F(m):
r={}
for i,_ in E(m):
for c,n in f(i,m,[(i,-1)]):
if c[-1][-1]!=-1 or c[-1][1]:r[n]=r.get(n,[])+[(i,c)]
for n in r:
if not(V:={i for i,_ in E(m)})-{a for a,_ in r[n]}:
if any(all(M(m,B,''.join(str(K)for _,K in c[1:]))==n for B in V)for _,c in r[n]):return 1
```
[Try it online!](https://tio.run/##fVTLbtswEDxHX8H6IrKhDcuSnwF7MJAAQeAec2EJQ5WllIVECTRdIAjy7S5JLW01LWrAXmt2d2Z2Ral7NT9ala46fT7fs1KdmlLnpowOZYUqrGhDC8YF2UToVZb1ARVURahqNZIUP9KcSIXuccOVLdmx8lde46PRuCHk7lDWaGcTXIq7vrfSbWNJc7qjxS238ZEI4pV2uKFb2jkZWcUxY91Gl@akFdpGCP65moMsjFXbCsKlMrjjU0EE7XiyAaIHK21JNHt7Dzb3qPfocA/ZERxUYWmn4/Z3nBA/IbLiqODjRLjvJzZOkCv3QCI22g7D9OSlNHYvdie3rrcgohfynNqxWBLVGvy8YW/yo4d3Mn7LPZj3oCN9D9q5esV5XeN@HXE8@dlK5Rf6RFzPnj65nsLPSxhTnmnrsGcoKAIpCRtMzrLpWm1QfjR@R6bdv@BnO/ANVHD@@R5LInqznk1E0ZGNRiPOpxQlgqI@CjT@gow@lRHnyTUx7RNVXh9dxiM2k1xaQia79qSX3kBuY@bwocgMEilFGRT6OBsSDRuy/xX@0@2KojlkVkNPFp8Bw8LFOVynULcExhUopRdmsLKGhtXVihdaULQG3Mc14BkIZ9BnjSwvIwyJ51CYQkEQWl/3vhoKL0BgCbuYXR0vPhKH2xAcJhAX0JgC0XR4PYd86Fv@teQFVIZDs/xgKbvuJjCFpf9x/731AbM9otHl1FayNqXGX1tVUnScHLtaGhx/UzFxhz2n6DtiSAbckcQkuum0e5U8YP9Y2GdkYrP2HVjv/dssJ/Zz/g0)
A little longer than the other solutions, but solves all the test cases pretty quickly. Returns `1` when a synchronizing word exists and `None` when one does not exist.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 21 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
WZ€ị®ẎƊ⁸©L*3¤Ð¡ẎZ€ẎEƇ
```
A monadic Link that accepts a 1-indexed list of nodes, each of which is a pair of positive integers identifying the nodes pointed to by each of the two transition characters (i.e. like the test cases in the question but incremented by one) and yields an empty list (falsey) if no synchronising word exists or a non-empty list (truthy) if one does.
**[Try it online!](https://tio.run/##y0rNyan8/z886lHTmoe7uw@te7ir71jXo8Ydh1b6aBkfWnJ4wqGFQCGw9K4@12Pt////j4421FEwitVRgNCxAA "Jelly – Try It Online")**
...Too slow for the length 5 and greater tests, but since all of those that do have synchronising words are much shorter [this](https://tio.run/##dVExS8QwGN3vV2RwESK0TZqmCDq5uYuGDg7nIJ1OHdyqy4HCIU4ddBBcBHHWc@vh/Y/mj9Q0fUl6gtP35eV97718OZ@W5XXXHZ3o2/f2@775aJeL9Z2@@WzeDnVVN6@rh@bFYPZ@uThYz7ufx/ar3tXVE9nZI7p67tvL2dXUtKY7K08vhrZezbf2t4@7TikVURIXlAy1mFCl4oBEA2I7g8SewwOHea5TMZX3uGUmQBglHAxbk7GC0/yfsZFHUpICkWN3gyeYFH1NcWbgZVCScGBeMQdTBm/rICjJgduaA@dw5JgzCTKf2SqmYDDcOIc87FKOHQWUM7w6CRmFV3S7dZliVIEJBoVofE5x7@Yy/2oBhvvx7E8GHrbgFNxeN/7UZi0mxS8), which searches only up to length \$n+2\$ gives the correct output for all test cases.
### How?
Full brute force - generates the list of nodes (by starting node) pointed to by all words from length one up to length \$n^3+1\$ (more than the current known upper bound) and keeps any that are all equal.
```
WZ€ị®ẎƊ⁸©L*3¤Ð¡ẎZ€ẎEƇ - Link: list of pairs of integers, A
W - wrap A in a list
С - collect and repeat... (includes the original wrapped A)
¤ - ...number of times: nilad followed by links as a nilad:
⁸ - chain's left argument = A
© - (copy to the register)
L - length
*3 - to the third power
Ɗ - ...action: last three links as a monad:
Z€ - transpose each
ị® - index into the register
Ẏ - tighten
Ẏ - tighten
Z€ - transpose each
Ẏ - tighten
Ƈ - keep those for which:
E - all equal? (i.e. all point to the same node)
```
---
**20 bytes** if a full program can output nothing if no synchronising word exists or a (not consistent) list representation if one does - uses the same method:
```
WZ€ị³ẎƊ³L*3¤Ð¡ẎZ€ẎEƇ
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~100~~ 91 bytes
```
->s{a,*k=r=s.transpose;r|=k|=a.map{|i|s[i]}.transpose-r while a=k.pop;r.any?{|x|!(x|x)[1]}}
```
[Try it online!](https://tio.run/##dVLLasMwELz7K1QKJSmK8VOyCWo/ROigQkKN28TILXWw/O2urYwjp9DToNHs7OxK5vvtMh7FuHtpe02fa2FEG34ZfWqbc3vYGytqK3T4qZveVraVlRr89c6Qn/fq40C0qMPm3OxNqE@X19529mHT2W4rYzUMY0NkIGVESawouaKiE5N5JgVGN8WE2cw7ZQImpSSDwmGydnDKgpIcTLH2nPgEFWzGHOcUOo4MBZzTuc45llAWvqfrwCgpwTsswWfomKFuSsBvWSfHRzk3j9CEozQBOj5GqKUlgzXHuIkPyZQK1Pw8m6fjNgiuq479WjBE5J398v9f5V1t7p9jGTgGMlSmSBetzznulzp@c2RQLDn5n/kyv@LFYXm0u2/g9rCaf/wF "Ruby – Try It Online")
] |
[Question]
[
Recently I've been writing a new [language](https://github.com/vihanb/Blocks), to avoid needing to handle *order of operations*, I simply parenthesize each expression properly to avoid this entirely.
Because parenthesis are at char-codes 40-41, your code will need to be as short as possible.
---
## Examples
```
1+2*3
(1+(2*3))
2*(3+4)
(2*(3+4))
2*3/4+3
(((2*3)/4)+3)
342*32/8
((342*32)/8)
```
## Rules
The only operations you'll need to handle are: `*` (multiplication), `/` (division), `+` (addition), and `-` (subtraction).
* The **order of operations** is:
+ Parenthesis
+ Multiplication, Division
+ Adition, Subtraction
* You should prefer to go left-right
* The input numbers will always be positive integers (see bonuses)
## Bonuses
**-20%** if you handle negation:
```
3+-5
(3+(-5))
```
**-5%** if you allow spaces to be placed inside the input:
```
3 + 4
(3+4)
```
**-10%** if you can handle decimals in the input:
```
1+.12
(1+.12)
1+0.21/3
(1+(0.21/3))
```
**500 bounty:** if you manage to write an answer in [Unnamed](http://vihanserver.tk/p/langs/Unnamed/)/[Blocks](https://github.com/vihanb/Blocks)
[Answer]
# JavaScript (ES6) 179 (263 -20% -5% -10%)
```
(x,W=[],Q=['('],z=1,w=v='',h=p=>'*/+-))('.indexOf(p)|1,C=n=>{for(;h(q=Q.pop())<=h(n);)W[0]=`(${W[1]+q+W.shift()})`;z&&Q.push(q,n)})=>(x+')').replace(/[\d.]+|\S/g,t=>t>'('?t>')'?~h(t)?z?(w+='('+t,v+=')'):C(t,z=1):W=[w+t+v,...W,z=w=v='']:C(t,z=0):z=Q.push(t))&&W[0]
```
As the other two answers are currently both wrong, I'll post mine. It's a variation of the expression parser that I used [here](https://codegolf.stackexchange.com/questions/61358/operations-of-order/61598#61598) and [here](https://codegolf.stackexchange.com/questions/61463/dames-do-some-math/61486#61486) and somewhere else. Look there for more detailed algorithm explanations.
It's quite bulky but it should work.
**Test snippet**
```
f=(x,W=[],Q=['('],z=1,w=v='',h=p=>'*/+-))('.indexOf(p)|1,C=n=>{for(;h(q=Q.pop())<=h(n);)W[0]=`(${W[1]+q+W.shift()})`;z&&Q.push(q,n)})=>(x+')').replace(/[\d.]+|\S/g,t=>t>'('?t>')'?~h(t)?z?(w+='('+t,v+=')'):C(t,z=1):W=[w+t+v,...W,z=w=v='']:C(t,z=0):z=Q.push(t))&&W[0]
// More readable
x=(x,W=[],Q=['('],z=1,w=v='',
h=p=>'*/+-))('.indexOf(p)|1,
C=n=>{
for(;h(q=Q.pop())<=h(n);)W[0]=`(${W[1]+q+W.shift()})`;
z&&Q.push(q,n)
}
)=>(
(x+')')
.replace(/[\d.]+|\S/g,t=>
t>'('
?t>')'
?~h(t)
?z
?(w+='('+t,v+=')')
:C(t,z=1)
:W=[w+t+v,...W,z=w=v=''] // overfill W to save 2 chars ()
:C(t,z=0)
:z=Q.push(t)
),
W[0]
)
console.log=(...x)=>O.textContent+=x.join` `+'\n'
// TEST
;[
['1+2*3','(1+(2*3))'],['2*(3+4)','(2*(3+4))'],['2*3/4+3','(((2*3)/4)+3)'],['342*32/8','((342*32)/8)'],
['3+-5','(3+(-5))'],['-3+-4*7','((-3)+((-4)*7))'], // bonus 20%
['3 + 4','(3+4)'], // bonus 5%
['1+.12','(1+.12)'],['1+0.21/3','(1+(0.21/3))'] // bonus 10%
].forEach(t=>{var k=t[1],i=t[0],r=f(i); console.log(i+' : '+r+(r==k? ' OK':' Fail expecting '+k))})
```
```
<pre id=O></pre>
```
[Answer]
# Python, 153 \* 0.9 = 137.7 bytes
```
def p(e):
for o in"+-*/":
for i,c in enumerate(e):
if(c==o)*(0==sum([(d=="(")-(d==")")for d in e[:i]])):return"("+p(e[:i])+o+p(e[i+1:])+")"
return e
```
This program handles decimal input.
The second line begins with a space, the second begins with a tab, the third with two tabs and the third with a space. This saved one byte. Here's a hexdump (`xxd`p p):
```
0000000: 6465 6620 7028 6529 3a0a 2066 6f72 206f def p(e):. for o
0000010: 2069 6e22 2b2d 2a2f 223a 0a09 666f 7220 in"+-*/":..for
0000020: 692c 6320 696e 2065 6e75 6d65 7261 7465 i,c in enumerate
0000030: 2865 293a 0a09 0969 6628 633d 3d6f 292a (e):...if(c==o)*
0000040: 2830 3d3d 7375 6d28 5b28 643d 3d22 2822 (0==sum([(d=="("
0000050: 292d 2864 3d3d 2229 2229 666f 7220 6420 )-(d==")")for d
0000060: 696e 2065 5b3a 695d 5d29 293a 7265 7475 in e[:i]])):retu
0000070: 726e 2228 222b 7028 655b 3a69 5d29 2b6f rn"("+p(e[:i])+o
0000080: 2b70 2865 5b69 2b31 3a5d 292b 2229 220a +p(e[i+1:])+")".
0000090: 2072 6574 7572 6e20 650a return e.
```
Here's a program I used for testing: (Save the program above as `paren.py`)
```
import paren
cases = {
"2+3*4": "(2+(3*4))",
"(2+3)*4": "((2+3)*4)",
"1+2+3+4": "(1+(2+(3+4)))",
"3/2+5": "((3/2)+5)",
"1+2-3": "(1+(2-3))",
"2-1+2": "((2-1)+2)",
"3+-5": "(3+(-5))",
"1+.12": "(1+.12)",
"1+0.21/3": "(1+(0.21/3))",
}
for num, case in enumerate(cases):
print "\n\n\033[1m\033[38;5;14mCase #%d: %s" % (num + 1, case)
result = paren.p(case)
print "\033[38;5;4mParenthesize returned: %s" % (result)
solution = cases[case]
if result == solution:
print "\033[38;5;76mCorrect!"
else:
print "\033[38;5;9mNot correct!"
```
Make sure that your terminal uses the `\033[38;5;<COL>m` escape code for colors.
[Answer]
## Python, 241 \* 0.8 \* 0.95 \* 0.9 = 164.84 characters
I'm using the [ast (Abstract Syntax Trees) library](https://docs.python.org/2/library/ast.html), and a homebrew string replacement dict. The string replacement costs a lot, but the bonus helps in keeping the score somewhat low. Maybe (the string replacement part) can be golfed further.
Note that this solution adds an extra set of parenthesis around each number, but I think that's within the spirit of the question
```
import ast;def p(e):
r,s={"Module([":"",")])":"","Expr(":"","BinOp":"","Num":"",", Add(), ":"+",", Sub(), ":"-",", Div(), ":"/",", Mult(), ":"*"},ast.dump(ast.parse(e),annotate_fields=False)
for f,t in r.iteritems():s=s.replace(f,t)
return s
```
Test suite:
```
cases = {
"2+3*4",
"(2+3)*4",
"1+2+3+4",
"3/2+5",
"1+2-3",
"2-1+2",
"3+-5",
"1+.12",
"1+0.21/3"
}
for num,case in enumerate(cases):
result = p(case)
print "Case {}: {:<16} evaluates to: {}".format(num+1,case,result)
```
Output of the test suite:
```
Case 1: 3+-5 evaluates to: ((3)+(-5))
Case 2: 3/2+5 evaluates to: (((3)/(2))+(5))
Case 3: 2+3*4 evaluates to: ((2)+((3)*(4)))
Case 4: 1+2+3+4 evaluates to: ((((1)+(2))+(3))+(4))
Case 5: 1+0.21/3 evaluates to: ((1)+((0.21)/(3)))
Case 6: (2+3)*4 evaluates to: (((2)+(3))*(4))
Case 7: 2-1+2 evaluates to: (((2)-(1))+(2))
Case 8: 1+.12 evaluates to: ((1)+(0.12))
Case 9: 1+2-3 evaluates to: (((1)+(2))-(3))
```
] |
[Question]
[
Any regular hexagon can be tiled with diamonds, for instance like so (stolen from [this question](https://codegolf.stackexchange.com/q/50562/25180)):
```
______
/_/_/\_\
/_/\_\/\_\
/\_\/_/\/_/\
\/_/\_\/_/\/
\_\/_/\_\/
\_\_\/_/
```
We'll consider the above a tiling of size 1 (since the diamonds' sides are made of one / or \ each). The same tiling of size 2 would look like:
```
____________
/ / /\ \
/___/___/ \___\
/ /\ \ /\ \
/___/ \___\/ \___\
/\ \ / /\ / /\
/ \___\/___/ \/___/ \
\ / /\ \ / /\ /
\/___/ \___\/___/ \/
\ \ / /\ \ /
\___\/___/ \___\/
\ \ \ / /
\___\___\/___/
```
Your task is to rotate diamond tilings by a multiple of 60 degrees. The diamond tiling in the input can be in any size (and the size is not explicitly specified in the input). But it would always be a valid tiling, and all sides of the hexagon would have the same length.
These are the above examples rotated by 60 degrees clockwise:
```
______
/_/\_\_\
/\_\/_/\_\
/\/_/\_\/_/\
\/\_\/_/_/\/
\/_/\_\_\/
\_\/_/_/
____________
/ /\ \ \
/___/ \___\___\
/\ \ / /\ \
/ \___\/___/ \___\
/\ / /\ \ / /\
/ \/___/ \___\/___/ \
\ /\ \ / / /\ /
\/ \___\/___/___/ \/
\ / /\ \ \ /
\/___/ \___\___\/
\ \ / / /
\___\/___/___/
```
The input is a non-negative integer and a diamond tiling. Your program (or function) should rotate it by the integer \* 60 degrees. You decide whether to rotate clockwise or counterclockwise, as long as it is consistent. Both the input and output shouldn't have extra leading or trailing spaces.
This is code-golf. Shortest code wins.
Related questions:
* [Rotate a Chinese checkerboard](https://codegolf.stackexchange.com/q/51964/25180)
* [Rotate a two-dimensional list by 45 degrees](https://codegolf.stackexchange.com/q/26541/25180)
* [Scale up a Diamond Tiling](https://codegolf.stackexchange.com/q/50562/25180)
[Answer]
# Pyth, 81 bytes
```
ju.es.e.reh|@s.e.e[yYykZ)bGCa+LV,t-y+k*3Y*5J-+kY/lG2Jc2j406610 4K"_/\\_\\"dKbGQ.z
```
[Try it online](https://pyth.herokuapp.com/?code=ju.es.e.reh%7C%40s.e.e%5ByYykZ%29bGCa%2BLV%2Ct-y%2Bk%2a3Y%2a5J-%2BkY%2FlG2Jc2j406610+4K%22_%2F%5C%5C_%5C%5C%22dKbGQ.z&input=5%0A++++++____________%0A+++++%2F+++%2F+++%2F%5C+++%5C%0A++++%2F___%2F___%2F++%5C___%5C%0A+++%2F+++%2F%5C+++%5C++%2F%5C+++%5C%0A++%2F___%2F++%5C___%5C%2F++%5C___%5C%0A+%2F%5C+++%5C++%2F+++%2F%5C++%2F+++%2F%5C%0A%2F++%5C___%5C%2F___%2F++%5C%2F___%2F++%5C%0A%5C++%2F+++%2F%5C+++%5C++%2F+++%2F%5C++%2F%0A+%5C%2F___%2F++%5C___%5C%2F___%2F++%5C%2F%0A++%5C+++%5C++%2F+++%2F%5C+++%5C++%2F%0A+++%5C___%5C%2F___%2F++%5C___%5C%2F%0A++++%5C+++%5C+++%5C++%2F+++%2F%0A+++++%5C___%5C___%5C%2F___%2F)
Rotates counterclockwise.
Each 60° rotation is performed using the following algorithm. Suppose the input is a hexagon of order *k*, so it has 2⋅*k* + 1 rows and 4⋅*k* columns. To find the rotated character at row *i* column *j*, let
* *u* = *i* + *j* − *k*
* *v* = *j* − 3⋅*i* + 5⋅*k*
Then the output character is
* `\`, if the input has `/` at row (*u* + 1)/2 column (*v* + 1)/2; else
* `/`, if the input has `_` at row *u*/2 column *v*/2 or row *u*/2 column (*v* + 2)/2; else
* `_`, if the input has `\` at row (*u* + 2)/2 column *v*/2 or row (*u* + 1)/2 column (*v* − 1)/2; else
* space.
(We do not count characters at half-integer indices.)
[Answer]
## JavaScript (ES6), ~~452~~ ~~356~~ 315 bytes
Where `\n` represents the literal newline character. Edit: Saved 96 bytes by realising that my algorithm doesn't need to know the number and size of diamonds separately, plus a few minor golfs that I missed the first time around. Saved 41 bytes by rearranging the code so that the destination was always the same pair of characters, plus a minor golf that I missed when converting to my previous algorithm.
```
r=
(s,n)=>(z=s.search`_`,l=(f,n=z*2+1)=>[...Array(n)].map(f),a=s.split`\n`,l(_=>(o=a.map(s=>[...s].fill` `),l((_,r)=>l((_,c)=>(d=z+c*2-r,a[s=z+r-c]&&(a[s][r+c]=='/'?o[r][d]=o[r][d+1]='_':0,a[s][r+c-1]=='\\'?o[r][d]='/':0),a[--s]&&(a[s][r+c]==`_`||a[s][r+c-1]==`_`?o[r][d+1]=`\\`:0)))),a=o.map(a=>a.join``)),n),a.join`\n`)
;
```
```
<pre id=i1>
______
/_/_/\_\
/_/\_\/\_\
/\_\/_/\/_/\
\/_/\_\/_/\/
\_\/_/\_\/
\_\_\/_/
</pre>
<input type=button value="Rotate!" onclick="i1.textContent = r(i1.textContent, 1)">
<pre id=i2>
____________
/ / /\ \
/___/___/ \___\
/ /\ \ /\ \
/___/ \___\/ \___\
/\ \ / /\ / /\
/ \___\/___/ \/___/ \
\ / /\ \ / /\ /
\/___/ \___\/___/ \/
\ \ / /\ \ /
\___\/___/ \___\/
\ \ \ / /
\___\___\/___/
</pre>
<input type=button value="Rotate!" onclick="i2.textContent = r(i2.textContent, 1)">
```
Explanation: Considers each pair of output characters, which could be `__`, `/_`, `_\`, `/` or `\`, checking for the appropriate characters in the input which map to those output characters. Ungolfed:
```
function rotate(str, num) {
// Measure the size using the indent of the _ in the first row.
var size = str.indexOf('_');
var arr = str.split('\n');
while (num--) {
// We build a character array to represent the output by turning the
// input into a nested array and replacing everything with spaces.
// Note that the output will have any trailing spaces from the input.
var res = arr.map(s => Array.from(s).fill(' '));
// Loop over a diamond that encloses the hexagon.
for (var destrow = 0; destrow <= size * 2; destrow++) {
for (var col = 0; col <= size * 2; col++) {
var destcol = size + col * 2 - destrow;
var srcrow = size + destrow - col;
var srccol = destrow + col;
// Map / to __, \ to / and __ to \.
// We write __ first in case it gets overwritten by / or \.
if (arr[srcrow]) {
if (arr[srcrow][srccol] == '/') {
res[destrow][destcol] = res[destrow][destcol + 1] = '_';
}
if (arr[srcrow][srccol - 1] == '\\') {
res[destrow][destcol] = '/';
}
}
// Need to check both positions in case one was overwritten.
if (arr[srcrow - 1] &&
(arr[srcrow - 1][srccol] == '_' || arr[srcrow - 1][srccol - 1] == '_')) {
res[destrow][destcol + 1] = '\\';
}
}
}
arr = res.map(a => a.join(''));
}
return arr.join('\n');
}
```
] |
[Question]
[
## Background
One source of ennui in tabletop role-playing games is dealing with rolls involving many dice. Casting a Disintegration spell may be instantaneous, but rolling and adding together 40 dice certainly isn't!
A number of suggestions for handling this [are discussed at rpg.stackexchange.com](https://rpg.stackexchange.com/questions/58530/dealing-with-large-amount-of-dice-rolls-for-a-single-damage-roll-without-making). Some of them, however, such as using a roller program or averaging dice, take away some of the fun and sense of control from the players. Others, such as rolling 4 dice and multiplying the total by 10, make the results far more swingy (while averaging dice acts in the opposite direction).
This question concerns a method of reducing the number of dice rolls *without* changing either the average result (mean) or its swinginess (variance).
## Notation and math
In this question, we'll use the following notation to represent dice rolls:
* *n*d*k* (e.g. 40d6) refers to the sum of n rolls of a k-sided die.
* *n*d*k*\**c* (e.g. 4d6\*10) describes multiplying the result by a constant c.
* We can also add rolls (e.g. 4d6\*10 + 40d6) and constants (e.g. 4d6 + 10).
For a single die roll, we can show that:
* **Mean**: E[1d*k*] = (k+1)/2
* **Variance**: Var(1d*k*) = (k-1)(k+1)/12
Using the basic properties of mean and variance, we can furthermore infer that:
* **Mean**: E[*m*d*k*\**a* + *n*d*l*\**b* + *c*] = *a.m*.E[1d*k*] + *b.n*.[1d*l*] + *c*
* **Variance**: Var(*m*d*k*\**a* + *n*d*l*\**b* + *c*] = *a*².*m*.Var(1d*k*) + *b*².*n*.Var(1d*l*)
## Task
Given three integers *n*, *k* and *r*, your program should output a way of approximating *n*d*k* in at most *r* rolls, with the following constraints:
* The solution should have the same mean and variance as *n*d*k*.
* The solution should contain the *largest possible number of rolls* less than or equal to *r*, as more rolls produces a smoother distribution.
* You should restrict your solutions to only using *k*-sided dice, unless you're aiming for the Bonus (see below).
* If there is no solution (as *r* is too small), the program should output the string "I AM A SEXY SHOELESS GOD OF WAR!".
* The parameters are passed in as a single space-separated string.
* You may assume that 1 ≤ *n* ≤ 100, 1 ≤ *r* ≤ *n* and that *k* is one of 4, 6, 8, 10, 12 and 20 (the standard dice used in tabletops).
* The output should be in the format described in Notation (e.g. 4d6\*10+5), with optional spaces around +s but nowhere else.
Unit multipliers are also optional: both 4d6\*1 and 4d6 are valid.
You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument. Results should be printed to STDOUT (or closest alternative) or returned as a string.
## Examples
```
>> "10 6 10"
10d6
>> "10 6 4"
2d6*2+2d6+14
>> "10 6 3"
1d6*3+1d6+21
>> "10 6 2"
1d6*3+1d6+21
>> "10 6 1"
I AM A SEXY SHOELESS GOD OF WAR!
```
## Scoring
Shortest code wins. Standard rules apply.
## Bonus
**-33%** (rounded down before subtraction) if your program also return solutions that include valid dice other than *k* (where the valid values, as mentioned above, are 4, 6, 8, 10, 12 and 20). If you choose to do so, then you should *always* return such solutions when appropriate, and handle solutions that use multiple types of die. Example:
```
>> "7 4 3"
3d6+7
```
[Answer]
## GolfScript (163 143 133 bytes)
```
~@:^\?,{^base 0-}%{0\{.*+}/^=},.{{,}$-1=..&{[[1$[1$]/,(3$@]'d*+'1/]zip}%^@{-}/@)*.2/\1&'.5'*}{];'I AM A SEXY SHOELESS GOD OF WAR!'}if
```
[Online demo](http://golfscript.apphb.com/?c=OyI1IDIgMiIKCn5AOl5cPyx7XmJhc2UgMC19JXswXHsuKit9L149fSwue3ssfSQtMT0uLiZ7W1sxJFsxJF0vLCgzJEBdJ2QqKycxL116aXB9JV5Aey19L0ApKi4yL1wxJicuNScqfXtdOydJIEFNIEEgU0VYWSBTSE9FTEVTUyBHT0QgT0YgV0FSISd9aWY%3D)
When not mixing types of dice, the problem reduces to expressing `n` as a sum of no more than `r` squares, and `k` is irrelevant except for the calculation of the constant at the end. The bulk of this answer is the bookkeeping required to express the result in the desired format: the actual calculation is `^\?,{^base}%{0\{.*+}/^=},` to find the multiplication factors `a`, `b`, etc.; and `^@{-}/@)*.2/` to calculate the constant.
### Dissection
```
~ # Stack: n k r
@:^\?,{ # Store n in ^, and for 0 to n**r
^base 0- # convert to base n and remove 0s.
}% # Stack: k [arrays of up to r values from 1 to n-1]
{0\{.*+}/^=}, # Filter them to arrays whose sum of squares is n,
# i.e. to multipliers which have the right variance
.{ # If any multiplier array passes the filter...
{,}$-1= # Pick one with the greater number of rolls
# Stack: k [multipliers]
..&{ # Map each distinct multiplier a...
[[ # Gather in nested array for later zip
1$[1$]/,( # Split a copy of the multipliers around a to count the as
# Let's denote that count as m
# Stack: k [multipliers] a [ [ m
3$@ # Copy k and rotate the a inside the nested array
] # Stack: k [multipliers] [ [m k a]
'd*+'1/ # Push an array ['d' '*' '+'] and close nested array
]zip # Giving [[m 'd'] [k '*'] [a '+']]
# which will be printed as mdk*a+
}% # Stack: k [multipliers] [string representations of dice]
^@{-}/@)* # Compute (n - sum(multipliers)) * (k + 1)
# That's twice the constant we need to add to fix the mean
.2/\1&'.5'* # And convert it to a renderable form, including .5 if needed
}{ # Otherwise clear the stack and push the error message
];'I AM A SEXY SHOELESS GOD OF WAR!'
}if
```
[Answer]
## Python, ~~487~~ ~~461~~ 452 - 33% = 303 bytes
Since nobody else has done so, here is a solution that handles different types of dice. Like the other solution, it generates a range of possible solutions and filters them down. It uses the fact that (k+1)(k-1) = k^2-1 and two semi-loopholes in the spec (oops!): the lack of ban on printing the redundant form 0d*k*\**a* (which saves all of 5 bytes!), and the lack of running time restriction (it gets slow fairly quickly, though does run all the examples given).
```
from itertools import*
N,K,R=map(int,input().split())
S=lambda l:sum([x[0]for x in l])
s=[x for x in product(*[[(n,k,a)for n in range(N*(K**2-1)/((k**2-1)*a**2)+1)]for a in range(1,N+1)for k in[4,6,8,10,12,20]if a**2<=N])if sum([n*(k**2-1)*a**2 for n,k,a in x])==N*K**2-N and S(x)<=R]
if s:s=max(s,key=S);print"+".join(["%sd%s*%s"%x for x in s]+[str(int(N*(K+1)/2.-sum([n*a*(k+1)/2.for n,k,a in s])))])
else:print"I AM A SEXY SHOELESS GOD OF WAR!"
```
For prettier output add `if x[0]` after `"%sd%s*%s"%x for x in s`:
```
>> "7 4 3"
3d6+7
>> "10 6 3"
1d6*1+1d8*1+1d8*2+18
>> "10 6 2"
1d6*1+1d6*3+21
>> "10 6 1"
I AM A SEXY SHOELESS GOD OF WAR!
```
] |
[Question]
[
# Task
Given the x,y coordinates (coordinates are guaranteed to be integers) of the vertices of two [simple polygons](https://en.wikipedia.org/wiki/Simple_polygon) in clockwise or anti-clockwise order. Output a Truthy value if both the polygons are [similar](https://en.wikipedia.org/wiki/Similarity_(geometry)) otherwise a Falsy value
A simple polygon is a polygon that does not intersect itself and has no holes. That is, it is a flat shape consisting of straight, non-intersecting line segments or "sides" that are joined pairwise to form a single closed path. If the sides intersect then the polygon is not simple. Two edges meeting at a corner are required to form a an angle that is not not straight (180°)
Two polygons are similar if either polygon can be rescaled, repositioned, and reflected, so as to coincide precisely with the other polygon.
# Testcases
**Input**
```
[(0, 0), (1, 0), (1, 1), (0, 1)]
[(-1, 0), (2, 1), (1, 4), (-2, 3)]
```
[Graph](https://i.stack.imgur.com/m2lJj.png)
**Output**
```
Truthy
```
---
**Input**
```
[(2, 3), (0, 0), (4, 0)]
[(-3, 0), (-2, 2), (0, 1), (1, -1), (-1, -2), (-2, -2)]
```
[Graph](https://i.stack.imgur.com/6fOUn.png)
**Output**
```
Falsy
```
---
**Input**
```
[(1, 4), (1, 3), (0, 2), (1, 1), (-3, 2)]
[(2, 0), (2, -1), (3, -1), (4, -2), (-2, -2)]
```
[Graph](https://i.stack.imgur.com/2N3hM.png)
**Output**
```
Falsy
```
---
**Input**
```
[(-1, 0), (2, 1), (1, 4), (-2, 3)]
[(1, 4), (2, 1), (-1, 0), (-2, 3)]
```
[Graph](https://i.stack.imgur.com/DMFHp.png)
**Output**
```
Truthy
```
---
**Input**
```
[(-2, 0), (-1, 1), (0, 1), (1, 3), (1, 0)]
[(5, 4), (4, 2), (3, 2), (2, 1), (5, 1)]
```
[Graph](https://i.stack.imgur.com/CLxMF.png)
**Output**
```
Truthy
```
---
**Input**
```
[(2, 13), (4, 8), (2, 3), (0, 8)]
[(0, 0), (5, 0), (8, 4), (3, 4)]
```
[Graph](https://i.stack.imgur.com/7YRst.png)
**Output**
```
Falsy
```
---
**Input**
```
[(-1, 0), (-5, 3), (-5, 9), (-1, 6)]
[(0, 0), (5, 0), (8, 4), (3, 4)]
```
[Graph](https://i.stack.imgur.com/qUSJs.png)
**Output**
```
Falsy
```
---
**Input**
```
[(0, 0), (1, 2), (1, 0)]
[(2, 0), (2, 2), (3, 0)]
```
[Graph](https://i.stack.imgur.com/FPDfs.png)
**Output**
```
Truthy
```
---
[Answer]
# Mathematica, 97 bytes (SBCS)
```
Or@@(Equal@@(a@u/#)&/@(a/@NestList[RotateLeft,v,Length@v]))
a@l_:=Norm[#〚1〛-#〚2〛]&/@l~Subsets~{2}
```
You can [try it online](https://tio.run/##hZLRaoMwFIbvfYpAYdSiaKLeFARvtivpxrY7kZKWdAraMhOFIpY@x/Z4fRCXaKJ2vfDqPybH8/3/0RyzhOSYpXvcHqJya1TbGKz99rUIguXzd4kzrjgorYX@ZPHKCjaEsjClLHo/McxISA7MqIyQHL9YElSxrms4yLZrf3Mq8mhxu/7A2/XXFAXiRcynZJePckcJo5caNe1yBfaYEgDBZ1Gy5AxWulYCH9S1bQC7MUANR4VCbaGNVnVNprpF8pY/u0JNfuDwtrciPbKIZzNAFceapngIvOCMniWra@5nd9NcoQPDkadiJhos9DCzK4QNE6keXv0Hi1gD2@nZY1RlGo420DSycIAGP2iM3NMdVbgzLkYL7sO6ZzdZ3VlVXcNrcwv3HokqiHn3aSd7gNPP4EmyK5fjSFVOvP6/GPkc3/4B)!
The function `a` computes all the pairwise distances between any two vertices of the polygon.
The main function applies this to the first list and to every rotation of the second list, to try and find the corresponding vertices. The rotation of the second list is correct if all the corresponding distances have been scaled accordingly.
Thanks to @J42161217 for saving me some 3 bytes
] |
[Question]
[
# Detect Duplicate Questions
Once upon a time, there was a golfing site. It had a problem: people would post similar or identical questions again and again. You have been ~~chosen selected forced conscripted blackmailed~~ requested to automate the process of deciding whether a question is a duplicate of an existing one, by whatever means necessary (see Rules).
## Input
Your program must accept a single URL as input. It may assume that this leads to a question on [codegolf.stackexchange.com](http://codegolf.stackexchange.com).
## Output
Search the site for similar questions. If you think that the input question is a duplicate of an existing question (or vice versa), output the other question's URL. You may output multiple URLs, separated by new lines. At the end of your output, output `end` (on a separate line).
## Scoring
* If a question that you output was indeed marked as a duplicate of the input question (or vice versa), you score 4 points. This is a "correct guess".
* For each false positive (aka "incorrect guess"), you lose 2 points.
* For each question that was actually a duplicate but does not appear in your output (aka "missing guess"), lose 1 point.
The highest score after handling 32 input questions wins. These 32 questions are a "round". At the beginning of each round, the scores will be reset to 0. One round will be run every few days, and the leaderboard updated after each round.
## Rules
* If questions A and C are both closed as duplicates of B, A will count as a duplicate of C and vice versa.
* At the start of each round, your program may not possess any data about any questions (i.e. **no hardcoding**), except on how to parse the website.
* However, you may keep data in external files during a round.
* No data may be kept between rounds.
* Your output must have a trailing new line.
* **You may not use any data from the website except search results and the URL, title, tags and text of a question**, with or without formatting. For example, you may not use the text "marked as duplicate by foo, bar..." that appears on duplicate questions.
* You may retrieve this data directly from the site, via data.SE or via the API.
* **Each submission must have a name.**
* Each submission must have clear version numbering.
* **If a submission does not produce output after a time limit (to be decided; please state how long your submission takes) it will be killed and lose 8 points.**
[Answer]
# Python 3
I am giving this entry the name `The Differ`.
Code:
```
import urllib.request, gzip, re, json, difflib, sys
API_URL = "https://api.stackexchange.com/"
qurl = input()
qid = int(re.search("\d+",qurl).group(0))
def request(url,wrapper=False,**params):
params.setdefault("filter","withbody")
params.setdefault("site","codegolf")
url = API_URL + url + "?"+"&".join([str(k)+"="+str(v) for k,v in params.items()])
compressed_response = urllib.request.urlopen(url)
response = gzip.decompress(compressed_response.read()).decode("utf8")
response_object = json.loads(response)
if wrapper:
return response_object
else:
return response_object["items"]
question = request("questions/%s"%qurl)[0]
tags = ";".join(question["tags"])
title = question["title"]
escaped = title.replace(" ","%20")
related = request("similar",title=escaped,pagesize=100)
hasmore = False
length = sys.maxsize
for tag in question["tags"]:
result = request("search",tagged=tag,
wrapper=True,
filter="!-*f(6rc.cI8O",
pagesize=100)
if result["total"] < length:
length = result["total"]
related.extend(result["items"])
hasmore = result["has_more"]
besttag = tag
related.extend(best)
if length < 1500:
for page in itertools.count(2):
if not hasmore:
break
response = request("search",
tagged=besttag,
page=page,
pagesize=100,
filter="!-*f(6rc.cI8O",
wrapper=True)
hasmore = response["has_more"]
related.extend(result["items"])
matcher = difflib.SequenceMatcher(None, question["body"], None)
titlematcher = difflib.SequenceMatcher(None, question["title"], None)
seen = set()
seen.add(question["question_id"])
for possible in related:
matcher.set_seq2(possible["body"])
titlematcher.set_seq2(possible["title"])
score = matcher.ratio()+titlematcher.ratio()
qid = possible["question_id"]
if score > .85 and qid not in seen:
print(qid)
seen.add(qid)
print("end")
```
The filter `"!-*f(6rc.cI8O"` included the `total` parameter on the global wrapper object and the `body` parameter on questions.
This entry makes two API requests plus one per tag on the question plus one per hundred questions in its least used tag. If it hits an api throttle (which it doesn't check for), it will raise an `urllib.error.HTTPError: HTTP Error 400: Bad Request`
] |
[Question]
[
[Fillomino](http://en.wikipedia.org/wiki/Fillomino) is a puzzle where you fill a grid with [*polyominoes*](http://en.wikipedia.org/wiki/Polyomino). Each polyomino is an area of contiguous cells. The grid representation shows what size polyomino is covering each cell. For example, a pentomino(5) would be shown as `5` in each of five contiguous cells (see below). Two polyominoes of the same size cannot share a border, but may border diagonally.
For each puzzle, you're started with a number of *givens* and must fill in the remaining cells. An easy example puzzle and solution:

Your task: Given a square puzzle, solve it and output the answer. Input may be via stdin, a single command line argument, or text file. Input will be given as an integer `n`, followed by `n` lines of `n` digits each. Empty cells will be given as periods(`.`). For the example puzzle above, it would be:
```
5
3..66
5.4.6
.54.6
.1.6.
..312
```
Output is the solved puzzle, given on `n` lines of `n` digits, to console or text file:
```
33366
55446
55466
51462
33312
```
If the puzzle is not valid, output `0`. A puzzle could be invalid if the input is malformed or there is no solution. If there are multiple solutions, you may output any one or all of them.
Since each cell is represented by a single digit, all puzzles will consist of polyominoes size `9` and under only. If it is not possible to solve without larger polyominoes, consider it invalid.
Valid answers will *solve* any given puzzle, not simply output solutions to test cases. No external resources, be it online or local. If there *happens* to be a language with a built-in fillomino solving function, you can't use it. In short, [play fair](http://meta.codegolf.stackexchange.com/q/1061/14215).
**Test Case:**
Input:
```
9
..21.3..5
.5...5..5
.1.44.334
...53.4..
2.3.3..5.
1.15.5.15
..45..1..
.24.53.53
....2....
```
Output (a possible solution):
```
322133315
355445555
315443334
235531444
233135551
141535515
344553155
324553553
321223133
```
Remember that some polyominoes have *no* given numbers, and some have more than one. There is *not* a one-to-one relationship between the number of givens and the number of polyominoes.
Score is standard code-golf, size of the program in bytes.
[Answer]
4882 characters - Java
Not a very golfed solution (ie 4800 characters is a lotttttttttttt)
Could be golfed a bit more in that 1 or 2 debug printlines are still in there. I think I can reduce a fair bit still in terms of useless/optimized code.
```
import java.util.*;import java.awt.Point;public class G{public static void main(String[]args){new G();}Scanner z=new Scanner(System.in);public G(){s=z.nextInt();z.nextLine();int g[][]=new int[s][s];for(int i=0;i<s;i++)Arrays.fill(g[i],-1);for(int i=0;i<s;i++){String line=z.nextLine();for(int j=0;j<s;j++)if(line.charAt(j)!='.')g[i][j]=Integer.parseInt(Character.toString(line.charAt(j)));}System.out.println();if(y(g)){for(int i=0;i<s;i++)for(int j=0;j<s;j++)System.out.print(g[i][j]);System.out.println();}else System.out.println(0);}private boolean x(Collection<Point>c,int[][]d){if(c.size()==0)return true;int j=0;for(Iterator<Point>k=c.iterator();k.hasNext();k.next(),j++){for(int sol=9;sol>=0;sol--){int[][]a=new int[s][s];for(int i=0;i<s;i++)a[i]=Arrays.copyOf(d[i],s);List<Point>b=new ArrayList<Point>();for(Point p:c)if(!b.contains(p))b.add(new Point(p));a[b.get(j).x][b.get(j).y]=sol;if(w(a,b.get(j))){if(x(b,a)){for(int i=0;i<s;i++)d[i]=Arrays.copyOf(a[i],s);c.clear();c.addAll(b);return true;}}}}return false;}int s;private boolean y(int[][]d){int[][] a=new int[s][s];for (int i = 0; i<s;i++)a[i]=Arrays.copyOf(d[i],s);List<Point> incomplete=new ArrayList<Point>();if(r(a)&&s(a)){a(a);System.exit(0);}else if(!r(a)){q("INVALID FROM MAIN, ",12);return false;}for(int i=0;i<s;i++)for(int j=0;j<s;j++){if(a[i][j]!=-1)if(t(new Point(i,j),a,null,a[i][j]).size()!=a[i][j]){if(w(a,new Point(i,j))){a(a);if(y(a)){for(int i=0;i<s;i++)d[i]=Arrays.copyOf(a[i],s);return true;}else return false;}else return false;}}for(int i=0;i<s;i++)for(int j=0;j<s;j++)if(a[i][j]==-1){Set<Point>c=t(new Point(i,j),a,null,-1);if(x(c,a)){if(y(a)){for(int i=0;i<s;i++)d[i] = Arrays.copyOf(a[i], s);return true;}else return false;}else return false;}q("How did you get here",1);return false;}private boolean w(int[][]d,Point b){List<Point>c;Set<Point>a;a=t(b,d,null,d[b.x][b.y]);c=new ArrayList<Point>(u(b,d,null,d[b.x][b.y]));int h=d[b.x][b.y];int g=h-a.size();if(c.size()<g){return false;}else if(v(c,h,h,new ArrayList<Point>(a),0,d))return true;else return false;}private boolean v(List<Point>c,int h,int g,List<Point>e,int f,int[][]d){if(e==null)e=new ArrayList<Point>();int[][]a=new int[s][s];for(int i=0;i<s;i++)for(int k=0;k<s;k++)a[i][k]=d[i][k];if(f<g&&e.size()<g){for(int i=0;i<c.size();i++){if(!e.contains(c.get(i))){if(d[c.get(i).x][c.get(i).y]==h){for(Point c:e){a[c.x][c.y]=h;}Set<Point> u=t(e.get(0),a,null,h);Set<Point>v=t(c.get(i),a,null,h);if(!Collections.disjoint(u,v)){u.addAll(v);List<Point>uList=new ArrayList<Point>(u);if(v(c,h,g,uList,f+1,a)){q("this e sucess",2);if(y(d)){e.addAll(uList);return true;}}else;}for(int l=0;l<s;l++)for(int k=0;k<s;k++)a[l][k]=d[l][k];}else if(e.add(c.get(i))){if(v(c,h,g,e,f+1,d)){q("this e sucess",2);if(y(d))return true;}}if(e.contains(c.get(i)))e.remove(c.get(i));}}return false;}else if(f>g||e.size()>g){if(f>g){q("Your over the g. ");return false;}else return false;}else{for(Point c:e){a[c.x][c.y]=h;}if(r(a)){if(y(a)){for(int i=0;i<s;i++)d[i]=Arrays.copyOf(a[i],s);q("complete(a) is true, ",4);return true;}else{return false;}}else{return false;}}}private void q(String out,int i){System.err.println(out+". exit code: "+i);System.exit(i);}private void q(String a){q(a,0);}private boolean r(int[][] d){for(int i=0;i<s;i++)for(int j=0;j<s;j++)if(d[i][j]!=-1){Set<Point>same=t(new Point(i,j),d,null,d[i][j]);if(same.size()>d[i][j]){return false;}Set<Point>fae=u(new Point(i,j),d,null,d[i][j]);if(u(new Point(i,j),d,null,d[i][j]).size()<d[i][j]){return false;}}return true;}private Set<Point> u(Point p,int[][]d,Set<Point>u,int i){u=(u==null)?new HashSet<Point>():u;if(d[p.x][p.y]==i||d[p.x][p.y]==-1)u.add(p);int x=p.x,y=p.y;Point t=new Point();if(x+1<s&&(d[x+1][y]==i||d[x+1][y]==-1)){if(u.add(new Point(x+1,y)))u=u(new Point(x+1,y),d,u,i);}if(y+1<s&&(d[x][y+1]==i||d[x][y+1]==-1)){if(u.add(new Point(x,y+1)))u=u(new Point(x,y+1),d,u,i);}if(x-1>=0&&(d[x-1][y]==i||d[x-1][y]==-1)){if(u.add(new Point(x-1,y)))u=u(new Point(x-1,y),d,u,i);}if(y-1>=0&&(d[x][y-1]==i||d[x][y-1]==-1)){if(u.add(new Point(x,y-1)))u=u(new Point(x,y-1),d,u,i);}return u;}private Set<Point> t(Point p,int[][]d,Set<Point>u,int i){u=(u==null)?new HashSet<Point>():u;if(d[p.x][p.y]==i)u.add(p);int x=p.x,y=p.y;Point t=new Point(p);if(x+1<s&&d[x+1][y]==i){if(u.add(new Point(x+1,y)))u=t(new Point(x+1,y),d,u,i);}if(y+1<s&&d[x][y+1]==i){if(u.add(new Point(x,y+1)))u=t(new Point(x,y+1),d,u,i);}if(x-1>=0&&d[x-1][y]==i){if(u.add(new Point(x-1,y)))u=t(new Point(x-1,y),d,u,i);}if(y-1>=0&&d[x][y-1]==i){if(u.add(new Point(x,y-1)))u=t(new Point(x,y-1),d,u,i);}return u;}private boolean s(int[][]d){for(int i=0;i<s;i++)for(int j=0;j<s;j++)if(t(new Point(i,j),d,null,d[i][j]).size()!=d[i][j])return false;return true;}private void a(int[][]d){for(int i=0;i<s;i++){for(int j=0;j<s;j++){System.out.printf("%1s",d[i][j]==-1?".":Integer.toString(d[i][j]));}System.out.println("");}}}
```
Having never seen Polyominoes before this, I read up on what they are and without looking at solving alrogithms just made up my own (quite slow).
Basically, uses recursion a lot... Finds a Polyomino that's incomplete, tries to complete it.
Finds an empty space, Loops 1-9 through all squares in the pocket, sets that pocket to that value. If the pocket is complete, it tries to find another pocket, then repeats until finished. I couldn't get it to work for a grid of size 9... I have at least one optimisation in mind that could make it work within a reasonable time for 9. Might try to put that in place soon.
] |
[Question]
[
# Introduction
Write a program or function that adds a drop capital to a paragraph. The program will input the text to format, the column width, and the number of lines to drop the capital. The drop capitals look like this:
```
Lines: 2 3 4
Drop capital: A| A.| A..|
~' ..| ...| etc.
~~' ...|
~~~'
```
This is a [typography](/questions/tagged/typography "show questions tagged 'typography'") related challenge.
# Input
* Input a string of printable ASCII characters (no tabs or newlines) and 2 integers greater than one.
* One integer is the number of columns that the output should have.
* The other is the number of lines spanned by the drop capital.
* The text string contains words separated by single spaces.
* **Assume none of the words will be longer than the column width.**
That is, `column width > longest word + drop capital height`
* All lines will have at least one word.
* For this challenge, a word consists of any character other than a space.
* Input may be in any convenient format following the rules above.
# Output
* A left-justified block of text containing a drop capital with the specified number of lines.
* A line should contain as many words as possible without being longer than the column width.
* There is a space between the drop capital and the rest of each line.
* One trailing space or newline is allowed.
# Examples
```
Lines: 2 Columns: 10 Text: The quick brown fox jumped over the lazy dog.
T| he
~' quick
brown fox
jumped
over the
lazy dog.
Lines: 3 Columns: 10 Text: (Same as above)
T.| he
..| quick
~~' brown
fox jumped
over the
lazy dog.
Lines: 4 Columns: 10 Text: (Same as above)
T..| he
...| quick
...| brown
~~~' fox
jumped
over the
lazy dog.
Lines: 2 Columns: 80 Text: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur. Donec ut libero sed arcu vehicula ultricies a non tortor.
L| orem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus.
~' Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec
consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero
egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem
lacinia consectetur. Donec ut libero sed arcu vehicula ultricies a non tortor.
Lines: 3 Columns: 80 Text: (Same as above)
L.| orem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus.
..| Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec
~~' consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget
libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta
lorem lacinia consectetur. Donec ut libero sed arcu vehicula ultricies a non
tortor.
Lines: 4 Columns: 80 Text: (Same as above)
L..| orem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam
...| lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra
...| nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam
~~~' eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim,
ut porta lorem lacinia consectetur. Donec ut libero sed arcu vehicula ultricies
a non tortor.
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") and standard loopholes apply.
[Answer]
# Python 2, 202 bytes
```
def f(l,c,t):
l-=1;s=['.'*l+'|']*l+['~'*l+"'"]
s[0]=t[0]+s[0][1:];t=t[1:].split();j=0
while t:
w=t.pop(0)
if len(s[j]+w)>=c:j+=1
if j>=len(s):s.append(w)
else:s[j]+=' '+w
return '\n'.join(s)
```
Call as `f(Lines, Columns, Text)`
`f(4,100,'Stuff')` gives
```
S..| tuff
...|
...|
~~~'
```
[Answer]
# C#, 244 bytes
```
string F(int d,int c,string t){var w=t.Substring(1).Split(' ');t=""+t[0];for(int i=0,x=c,y=0;i<w.Length;x+=w[i++].Length+1)t+=(1>(x=x+w[i].Length>c?0:x)?"\n"+(y++<d?(y<d?"| ":"' ").PadLeft(x=d+1,y<d?'.':'~'):""):" ")+w[i];return t.Remove(1,2);}
```
Indentation, new lines and comments for clarity:
```
string F(int d,int c,string t){
var w=t.Substring(1).Split(' ');
t=""+t[0];
for(int i=0,x=c,y=0;i<w.Length;x+=w[i++].Length+1)
t+=(1>(x=x+w[i].Length>c?0:x)?"\n"+(y++<d?(y<d?"| ":"' ").PadLeft(x=d+1,y<d?'.':'~'):""):" ")+w[i];
return t.Remove(1,2);
}
```
] |
[Question]
[
Your task make a bot that plays [Atomas](http://sirnic.com/atomas), with the highest score.
## How the game works:
The gameboard starts with a ring of 6 "atoms", with numbers ranging from `1` to `3`. You can "play" an atom between two atoms, or on another atom, depending on the atom itself.
You can either have a normal atom, or a special atom.
### The normal atom:
You can play a normal atom between any two available atoms on the board.
You start off with atoms in the range `1 to 3`, but the range increases by 1 once every 40 moves (so after 40 moves, the range becomes `2 to 4`).
If there are atoms on the board that are lower than the range, it has a `1 / no. of atoms of that number on the board` chance of spawning.
Let's say you have a `2` to play, and the board looks like this:
```
1 1 2 1
```
Let's place the `2` to the right of the `1`.
The board now becomes:
```
1 1 2 1 2
```
**Note: the board wraps around, so the `1` on the far left is actually next to the `2` on the far right. This will be important later.**
There are 4 types of "special" atoms, and they are:
### The `+` atom:
This atom is played between two atoms. It has a 1 in 5 chance of spawning.
If the atoms on both sides of the `+` atom are the same, fusion occurs. Here's how it works:
```
The two atoms fuse together to create an atom one higher.
(So, two 3 atoms fuse together to form one 4 atom.)
While the atoms on both sides of the fused atom are equal:
If the atoms on the side >= the fused atom:
The new fused atom = the old fused atom's value + 2.
If the atoms on the side < the fused atom:
The new fused atom = the old fused atom's value + 1.
```
Example:
```
1 1 3 2 2 3 (the 1 on the left-hand side "wraps back"
to the 3 on the right-hand side)
Let's use the + on the two 2's in the middle.
-> 1 1 3 3 3 (the two 2's fused together to make a 3)
-> 1 1 5 (the two 3's fused with the 3, and because 3 >= 3,
the new fused atom = 3 + 2 = 5)
-> 6 (the two 1's fused with the 5, since the board wraps,
and because 1 < 5, the new fused atom = 5 + 1 = 6)
Because the atoms on the sides of the 6 don't exist, fusion stops,
and the board is now [6].
```
If the atoms on both sides of the `+` atom are different, then the `+` stays on the board.
Example:
```
1 3 2 3 1 1
Let's use the + on the 2 and 3 in the middle.
-> 1 3 2 + 3 1 1 (2 != 3, so the + stays on the board)
```
### The `-` atom:
This atom is played on another atom. It has a 1 in 10 chance of spawning.
The `-` atom removes an atom from the board, and gives you a choice to either:
* play the removed atom next round, or
* turn it into a + atom to play next round.
Example:
```
1 3 2 3 1 1
Let's use the - on the left-hand 2.
-> 1 3 3 1 1 (the 2 is now removed from the board)
Let's turn it into a +, and place it in between the 3's.
-> 1 4 1 1 (the two 3's fused together to make a 4)
-> 5 1 (the two 1's fused with the 4, and because 1 < 4,
the new fused atom = 4 + 1 = 5)
```
### The black `+` atom (`B`):
This atom is played between 2 atoms. It has a 1 in 80 chance of spawning, and only spawns once your score > 750.
This atom is basically the same as the `+` atom, except that it fuses any two atoms together, even `+`'s. From then on, it follows the `+` rule (it only fuses atoms together if the atoms on both sides of the fused atom are equal).
The fused atom as a result of the black `+` is equal to:
* the higher number atom in the fusion + 3
* `4` if the two fused atoms are `+`'s
Example:
```
1 3 2 1 3 1
Let's use the black + on the 2 and 1 in the middle.
-> 1 3 5 3 1 (the 2 and 1 fused together to make a 2 + 3 = 5)
-> 1 6 1 (+ rule)
-> 7 (+ rule)
```
Another example:
```
2 + + 2
Let's use the black + on the two +'s.
-> 2 4 2 (the two +'s fused together to make a 4)
-> 5 (+ rule)
```
### The clone atom (`C`):
This atom is played on another atom. It has a 1 in 60 chance of spawning, and only spawns once your score > 1500.
The clone atom allows you to choose an atom, and play it next round.
Example:
```
1 1 2 1
Let's use the clone on the 2, and place it to the right of the 1.
-> 1 1 2 1 2
```
Here is my build of the game, in Python 2:
```
import random
import subprocess
logs='atoms.log'
atom_range = [1, 3]
board = []
score = 0
move_number = 0
carry_over = " "
previous_moves = []
specials = ["+", "-", "B", "C"]
def plus_process(user_input):
global board, score, previous_moves, matches
previous_moves = []
matches = 0
def score_calc(atom):
global score, matches
if matches == 0:
score += int(round((1.5 * atom) + 1.25, 0))
else:
if atom < final_atom:
outer = final_atom - 1
else:
outer = atom
score += ((-final_atom + outer + 3) * matches) - final_atom + (3 * outer) + 3
matches += 1
if len(board) < 1 or user_input == "":
board.append("+")
return None
board_start = board[:int(user_input) + 1]
board_end = board[int(user_input) + 1:]
final_atom = 0
while len(board_start) > 0 and len(board_end) > 0:
if board_start[-1] == board_end[0] and board_end[0] != "+":
if final_atom == 0:
final_atom = board_end[0] + 1
elif board_end[0] >= final_atom:
final_atom += 2
else:
final_atom += 1
score_calc(board_end[0])
board_start = board_start[:-1]
board_end = board_end[1:]
else:
break
if len(board_start) == 0:
while len(board_end) > 1:
if board_end[0] == board_end[-1] and board_end[0] != "+":
if final_atom == 0:
final_atom = board_end[0]
elif board_end[0] >= final_atom:
final_atom += 2
else:
final_atom += 1
score_calc(board_end[0])
board_end = board_end[1:-1]
else:
break
if len(board_end) == 0:
while len(board_start) > 1:
if board_start[0] == board_start[-1] and board_start[0] != "+":
if board_start[0] >= final_atom:
final_atom += 2
else:
final_atom += 1
score_calc(board_start[0])
board_start = board_start[1:-1]
else:
break
if matches == 0:
board = board_start + ["+"] + board_end
else:
board = board_start + [final_atom] + board_end
for a in range(len(board) - 1):
if board[a] == "+":
if board[(a + 1) % len(board)] == board[a - 1]:
board = board[:a - 1] + board[a:]
plus_process(a)
break
def minus_process(user_input, minus_check):
global carry_over, board
carry_atom = board[int(user_input)]
if user_input == len(board) - 1:
board = board[:-1]
else:
board = board[:int(user_input)] + board[int(user_input) + 1:]
if minus_check == "y":
carry_over = "+"
elif minus_check == "n":
carry_over = str(carry_atom)
def black_plus_process(user_input):
global board
if board[int(user_input)] == "+":
if board[int(user_input) + 1] == "+":
inter_atom = 4
else:
inter_atom = board[int(user_input) + 1] + 2
else:
if board[int(user_input)] + 1 == "+":
inter_atom = board[int(user_input)] + 2
else:
inter_list = [board[int(user_input)], board[int(user_input) + 1]]
inter_atom = (inter_list.sort())[1] + 2
board = board[int(user_input) - 1:] + [inter_atom] * 2 + board[int(user_input) + 1:]
plus_process(int(user_input) - 1)
def clone_process(user_input):
global carry_over
carry_over = str(board[int(user_input)])
def regular_process(atom,user_input):
global board
if user_input == "":
board.append(random.randint(atom_range[0], atom_range[1]))
else:
board = board[:int(user_input) + 1] + [int(atom)] + board[int(user_input) + 1:]
def gen_specials():
special = random.randint(1, 240)
if special <= 48:
return "+"
elif special <= 60 and len(board) > 0:
return "-"
elif special <= 64 and len(board) > 0 and score >= 750:
return "B"
elif special <= 67 and len(board) > 0 and score >= 1500:
return "C"
else:
small_atoms = []
for atom in board:
if atom not in specials and atom < atom_range[0]:
small_atoms.append(atom)
small_atom_check = random.randint(1, len(board))
if small_atom_check <= len(small_atoms):
return str(small_atoms[small_atom_check - 1])
else:
return str(random.randint(atom_range[0], atom_range[1]))
def specials_call(atom, user_input):
specials_dict = {
"+": plus_process,
"-": minus_process,
"B": black_plus_process,
"C": clone_process
}
if atom in specials_dict.keys():
if atom == "-":
minus_process(user_input[0], user_input[1])
else:
specials_dict[atom](user_input[0])
else:
regular_process(atom,user_input[0])
def init():
global board, score, move_number, carry_over, previous_moves
board = []
score = 0
for _ in range(6):
board.append(random.randint(1, 3))
while len(board) <= 18:
move_number += 1
if move_number % 40 == 0:
atom_range[0] += 1
atom_range[1] += 1
if carry_over != " ":
special_atom = carry_over
carry_over = " "
elif len(previous_moves) >= 5:
special_atom = "+"
else:
special_atom = gen_specials()
previous_moves.append(special_atom)
bot_command = "python yourBot.py"
bot = subprocess.Popen(bot_command.split(),
stdout = subprocess.PIPE,
stdin = subprocess.PIPE)
to_send="/".join([
# str(score),
# str(move_number),
str(special_atom),
" ".join([str(x) for x in board])
])
bot.stdin.write(to_send)
with open(logs, 'a') as f:f.write(to_send+'\n')
bot.stdin.close()
all_user_input = bot.stdout.readline().strip("\n").split(" ")
specials_call(special_atom, all_user_input)
print("Game over! Your score is " + str(score))
if __name__ == "__main__":
for a in range(20):
with open(logs, 'a') as f:f.write('round '+str(a)+'-'*50+'\n')
init()
```
## How the bot thing works:
### Input
* Your bot will get 2 inputs: the atom that is currently in play, and the state of the board.
* The atom will be like so:
+ `+` for a `+` atom
+ `-` for a `-` atom
+ `B` for a Black `+` atom
+ `C` for a Clone atom
+ `{atom}` for a normal atom
* The state of the board will be like so:
+ `atom 0 atom 1 atom 2... atom n`, with the atoms separated by spaces (`atom n` wraps back to `atom 1`, to simulate a "ring" gameboard)
* These two will be separated by a `/`.
Example inputs:
```
1/1 2 2 3 (the atom in play is 1, and the board is [1 2 2 3])
+/1 (the atom in play is +, and the board is [1] on its own)
```
### Output
* You will output a string, depending on what the atom in play is.
+ If the atom is meant to be played between two atoms:
- Output the gap you want to play the atom in. The gaps are like in between each atom, like so:
```
atom 0, GAP 0, atom 1, GAP 1, atom 2, GAP 2... atom n, GAP N
```
(`gap n` indicates you want to place the atom between `atom 1` and atom `n`)
So output `2` if you want to play the atom on `gap 2`.
+ If the atom is meant to be played on an atom:
- Output the atom you want to play it on, so `2` if you want to play the atom on `atom 2`.
+ If the atom is a `-`:
- Output the atom you want to play it on, followed by a space, followed by a `y/n` choice of turning the atom into a `+` later, so `2, "y"` if you want to play the atom on `atom 2`, and you want to turn it into a `+`. **Note: this requires 2 inputs, instead of 1.**
Example outputs:
```
(Atom in play is a +)
2 (you want to play the + in gap 2 - between atom 2 and 3)
(Atom in play is a -)
3 y (you want to play the - on atom 3, and you want to change it to a +)
2 n (you want to play the - on atom 2, and you don't want to change it)
```
* To make the bot work, you have to go to the `Popen` bit (at around the end of the code), and replace it with whatever makes your program run as a Pythonic list (so if your program is `derp.java`, replace `["python", "bot.py"]` with `["java", "derp.java"]`).
## Answer-specific Specs:
* Place the entire code of your bot into the answer. If it doesn't fit, it doesn't count.
* Each user is allowed to have more than 1 bot, however, they should all be in separate answer posts.
* Also, give your bot a name.
## Scoring:
* The bot with the highest score wins.
+ Your bot will be tested for 20 games, and the final score is the average of the 20 games.
* The tie-breaker will be the time of the upload of the answer.
* So your answer will be formatted like this:
```
{language}, {bot name}
Score: {score}
```
Good luck!
[Answer]
## Python, draftBot, Score = 889
```
import random
def h(b):
s=0
for x in b:
try:
s+=int(x)
except:
s+=0
return s
def d(i):g=i.split("/");a=g[0];b=g[1].split(" ");return(a,b)
def p(a,_,j):
v=[]
for x in _:
try:
v.append(int(x))
except:
v.append(0)
try:
v=v[:j+1]+[int(a)]+v[j+1:]
except:
v=v[:j+1]+[a]+v[j+1:]
r1=[[]];b=[x for x in v];m=range(len(b)+1)
for k in m:
for i in m:
for j in range(i):
c = b[j:i + 1]
if len(c)%2==0 and c==c[::-1] and 0 not in c:r1.append(c)
b.insert(0, b.pop())
q1=max(r1,key=len)
r2=[[]];b=[x for x in v];m=range(len(b)+1)
for k in m:
for i in m:
for j in range(i):
c = b[j:i + 1]
if len(c)>2 and len(c)%2==1 and c==c[::-1] and "+" in c and 0 not in c:r2.append(c)
b.insert(0, b.pop())
q2=max(r2,key=h)
with open('f.log', 'a') as f:f.write('pal '+str(_)+' : '+str(q1)+' : '+str(q2)+'\n')
if q2!=[]:return 100+h(q2)
else:return len(q1)
i=raw_input()
(a,b)=d(i)
if a in ['C','B']:print('0')
elif a=='-':print("0 y" if random.randint(0, 1) == 1 else "0 n")
else:q,j=max((p(a,b,j),j)for j in range(len(b)));print(str(j))
```
I found that the controller:
* crashes when score exceeds 1500;
* does not properly merge atoms in same cases.
[Answer]
## Python, RandomBot, Score = 7.95
Nothing too fancy, just a random bot.
```
import random
game_input = raw_input().split("/")
current_atom = game_input[0]
board = game_input[1].split(" ")
if current_atom != "-":
print(random.randint(0, len(board) - 1))
else:
random_choice = " y" if random.randint(0, 1) == 1 else " n"
print(str(random.randint(0, len(board) - 1)) + random_choice)
```
[Answer]
## Python, BadPlayer, Score = 21.45
```
import random
try:
raw_input
except:
raw_input = input
game_input = raw_input().split("/")
current_atom = game_input[0]
board = game_input[1].split(" ")
def get_chain(board, base):
chain = []
board = board[:]
try:
while board[base] == board[base + 1]:
chain = [board[base]] + chain + [board[base + 1]]
del board[base]
del board[base]
base -= 1
except IndexError:
pass
return chain
def biggest_chain(board):
chains = []
base = 0
i = 0
while i < len(board) - 1:
chains.append([i, get_chain(board, i)])
i += 1
return sorted(chains, key=lambda x: len(x[1]) / 2)[-1]
def not_in_chain():
a, b = biggest_chain(board)
if len(b) == 0:
print(random.randint(0, len(board) - 1))
elif random.randint(0, 1) == 0:
print(random.randint(a + len(b)/2, len(board) - 1))
else:
try:
print(random.randint(0, a - len(b)/2 - 1))
except:
print(random.randint(a + len(b)/2, len(board) - 1))
if current_atom in "+B":
a, b = biggest_chain(board)
if len(b) == 0:
print(0)
else:
print(a)
elif current_atom == "C":
not_in_chain()
elif current_atom == "-":
a, b = biggest_chain(board)
if len(b) == 0:
print(str(random.randint(0, len(board) - 1)) + " n")
elif random.randint(0, 1) == 0:
print(str(random.randint(a + len(b)/2, len(board) - 1)) + " n")
else:
try:
print(str(random.randint(0, a - len(b)/2 - 1)) + " n")
except:
print(str(random.randint(0, len(board) - 1)) + " n")
else:
not_in_chain()
```
Just a very bad bot that often make the controller crash
] |
[Question]
[
# Challenge Summary
In summary, the challenge is to provide the glider synthesis for a Game of Life configuration, which is your input.
# What does this mean?
Well, firstly, let me explain a few terms.
By Game of Life, I mean Conway's Game of Life. If you don't know what this is, you can read the Wikipedia article at <https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life>. It explains it pretty well.
If you don't know what a glider synthesis is, it's pretty much a bunch of gliders that will form a specific configuration after a certain number of steps. Read <http://www.conwaylife.com/wiki/Glider_synthesis> for more details.
# Okay, what are the rules?
* [Standard Loopholes Apply](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default "Standard Loopholes Apply")
* The glider synthesis must only consist of the standard 5-cell gliders, but they can start in any of their 4 states/colors.
* The glider synthesis is allowed to create other things, as long as they do not share a neighbor with and are not a neighbor of any living cell within the desired outcome. Moving structures can be created as byproducts as well.
* The desired outcome will be at most 10x10.
* The desired outcome will be achievable with a glider synthesis.
# Actual Specifics
Input will be given as a 2D array of truthy/falsy values, which indicates the desired outcome (the desired outcome will be reachable). The array will be at most 10 by 10 in size. The desired outcome will not necessarily be a stable configuration. Output will also be given in the same format, indicating a valid glider synthesis (as defined by the rules above) to produce this outcome (the output can be as large as necessary). The output doesn't have a size limit. It doesn't necessarily need to be the fastest or the smallest; as long as it's valid, it's fine.
# Summary of Everything
You will be given input as a 10x10 or smaller 2D array of truthy/falsy values of some sort. This could be a 2D array of something, an array of strings, a multi-line string, etc. Your task is to find a configuration using only standard 5-cell diagonal gliders that will eventually result in this outcome, where other byproducts are permitted so long as they do not interact in any way with the desired outcome. Given this configuration, you are to output a 2D array of truthy/falsy values in some format.
# Winning
This is a code-golf challenge, so the shortest program will win. Tiebreak is by earlier submission.
# In terms of test cases, you can just put the program output into a GoL emulator and run it and see if you get the desired output eventually.
# Tips/Ideas
I don't have many well developed ideas myself, but what you could try to do is find all possible reverses of a GoL scenario (i.e. find all configurations that could evolve to the current one), though that's going to take a lot of power quickly.
]
|
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** [Update the question](/posts/2303/edit) so it's [on-topic](/help/on-topic) for Code Golf Stack Exchange.
Closed 10 years ago.
[Improve this question](/posts/2303/edit)
How to determine if a number is odd or even without mod -or- bitwise operations?
This challenge is grossly inefficient, but challenges your ability to think outside the box for a creative solution.
***EDIT***:
Please create a function. Also, while regex is a fun response, the function should accept *any* valid number.
***BACKGROUND***:
This question stems from my earliest programming days. The homework for our first day of class was to write a simple program that printed 'odd' or 'even'. Being the brat I was, I didn't read the book we had for the class where it simply showed us how to use `%` to determine that. I spent about a half hour pacing back in forth in my room trying to think of a way to do this and had remembered from the lecture that numbers can lose and gain precision as they are cast from one primitive type to another. Therefore, if you took the number, divided it by two and then multiplied it back didn't equal the original number, then you would know that the number was odd.
I was stunned the next day, while our instructor was evaluating our programs, that he thought that it was the most original, if inefficient, way of solving the problem.
[Answer]
## Python
```
print('even' if (-1)**n==1 else 'odd')
```
[Answer]
In most programming languages division returns quotient for integers. So you can simply check this
```
(i/2)*2==i
```
[Answer]
## Brainf\*\*\* (179)
This is one of the more interesting problems involving conditional logic that I have done in BF.
```
+[>,]<--------------------------------------->>+++++[>+++++++
++++++>+++++++++++++++<<-]>++++>++++<<+<+<-[>-<-[>+<-[>-<-[>+<-[>-<-[>
+<-[>-<-[>+<-[>-<[-]]]]]]]]]]>[>>>.<<-<-]>[>.<-]
```
It takes a text input with a number. If the number is even, it outputs `E`, and if it is odd, it outputs `O`.
I'm proud enough of it that I'll show off a more human readable form:
```
+[>,] steps through input until it reaches eof.
<--------------------------------------- gets the numerical value of the last digit
>>+++++[>+++++++++++++>+++++++++++++++<<-]>++++>++++ store E and O
<<+<+< store a bit indicating parity, and a temporary bit
-[>-< !1
-[>+< && !2
-[>-< && !3
-[>+< && !4
-[>-< && !5
-[>+< && !6
-[>-< && !7
-[>+< && !8
-[>-<[-]] && !9
]
]
]
]
]
]
]
]
>[>>>.<<-<-]>[>.<-] Display E or O based on the value of the parity bit.
```
[Answer]
## Mathematica
```
SawtoothWave[x / 2] == 0
Exp[I Pi x] - 1 == 0
Sin[5 x / Pi] == 0
```
[Answer]
## C
Multiplied by itself a few times any even number will overflow to 0 given a finite size integer, and any odd number will continue to have at least the least significant bit set.
```
#include "stdio.h"
long long input=123;
int main(){
int a;
for(a=6;a;a--){
input*=input;
}
if(input){
printf("Odd");
}
else{
printf("Even");
}
return 0;
}
```
Edit: As a simple function:
```
int isOdd(long long input){
int a;
for(a=6;a;a--){
input*=input;
}
return !!input;
}
```
[Answer]
## JavaScript
```
/[02468]$/.test(i)
```
yields `true` for an even number. This only works with reasonably sized integers (e.g. not scientific notation when converted to a string and not having a fractional part.)
[Answer]
**Python** (Slow)
```
n=1234
while n > 1: n -= 2 #slow way of modulus.
print "eovdedn"[n::2]
```
[Answer]
## Python
Since I'm not really sure what the scoring criteria are, here's a bunch of solutions I've come up with for amusement's sake. Most of them use `abs(n)` to support negative numbers. Most, if not all, of them should never be used for real calculation.
This one is kind of boring:
```
from __future__ import division
def parity(n):
"""An even number is divisible by 2 without remainder."""
return "Even" if n/2 == int(n/2) else "Odd"
```
---
```
def parity(n):
"""In base-10, an odd number's last digit is one of 1, 3, 5, 7, 9."""
return "Odd" if str(n)[-1] in ('1', '3', '5', '7', '9') else "Even"
```
---
```
def parity(n):
"""An even number can be expressed as the sum of an integer with itself.
Grossly, even absurdly inefficient.
"""
n = abs(n)
for i in range(n):
if i + i == n:
return "Even"
return "Odd"
```
---
```
def parity(n):
"""An even number can be split into two equal groups."
g1 = []
g2 = []
for i in range(abs(n)):
g1.append(None) if len(g1) == len(g2) else g2.append(None)
return "Even" if len(g1) == len(g2) else "Odd"
```
---
```
import ent # Download from: http://wstein.org/ent/ent_py
def parity(n):
"""An even number has 2 as a factor."""
# This also uses modulo indirectly
return "Even" if ent.factor(n)[0][0] == 2 else "Odd"
```
---
And this is my favorite although it unfortunately doesn't work (as pointed out by March Ho below: just because all even numbers are the sum of two primes, doesn't mean that all odd numbers aren't).
```
import itertools
import ent # Download from: http://wstein.org/ent/ent_py
def parity(n)
"""Assume Goldbach's Conjecture: all even numbers greater than 2 can
be expressed as the sum of two primes.
Not guaranteed to be efficient, or even succeed, for large n.
"""
# A few quick checks
if n in (-2, 0, 2): return "Even"
elif n in (-1, 1): return "Odd"
if n < 0: n = -n # a bit faster than abs(n)
# The primes generator uses the Sieve of Eratosthenes
# and thus modulo, so this is a little bit cheating
primes_to_n = ent.primes(n)
# Still one more easy way out
if primes_to_n[-1] == n: return "Odd"
# Brutish!
elif n in (p1+p2 for (p1, p2) in itertools.product(primes_to_n, primes_to_n)):
return "Even"
else:
return "Odd"
```
[Answer]
## Haskell
This is, of course, in no way the creative, thinking-outside-the-box solution you're looking for, but how many times am I going to get to post a Haskell answer shorter than GolfScript, really? It's really a shame this isn't a code golf.
```
odd
```
But more seriously:
```
data Parity = Even | Odd
deriving (Show)
parity = p evens odds
where p (x:xs) (y:ys) i | i == x = Even
| i == y = Odd
| otherwise = p xs ys i
evens = interleave [0,2..] [-2,-4..]
odds = interleave [1,3..] [-1,-3..]
interleave (x:xs) ys = x : interleave ys xs
```
[Answer]
Using a deliberately perverse reading of the question, "How to determine if a number is odd or even", here's a C implementation (assume `bool` and `true` are defined appropriately):
```
bool is_odd_or_even(int n)
{
return true;
}
```
[Answer]
What, no randomized algorithms yet??
## C
```
#include<stdio.h>
#include<stdlib.h>
void prt_parity_of(int n){
int i,j=2;
char o[]="eovdedn"
, f[n=abs(n)]; for(i=n;i-->0;f[i]=1);
while(j>1){
while((i=rand()%n)
== (j=rand()%n)
|| (f[i]&f[j]>0)
&& (f[i]=f[j]=0)
);for(i=j=0; ++i<n; j+=f[i])
;}for(;j<7;j+=2)putchar(o[j]);
}
```
Randomly pairs numbers in the range 0..*n*-1 until less than 2 are left. It's quite amazingly inefficient: *O*(*n*3).
---
Completely different:
## Haskell
```
import Data.Complex
ft f = (\ω -> sum[ f(t) * exp(0:+2*pi*ω*t) | t<-[-1,-0.9..1] ] )
data Parity = Even | Odd deriving (Show)
parity n
| all (\(re:+im) -> abs re > abs im) [ft ((:+0).(^^n)) ω | ω<-[0..20]] = Even
| otherwise = Odd
```
Uses the fact that the Fourier transform of an even function (e.g. `\x->x^^4`) is real, while the Fourier transform of an odd function is imaginary.
[Answer]
## Coq, 103
```
Fixpoint even n:=match n with O=>true|S n=>odd n end with odd n:=match n with O=>false|S n=>even n end.
```
As far as I can tell this is the first coq entry on codegolf.
Even shorter (59):
```
Fixpoint even n:=match n with O=>true|S n=>negb(even n)end.
```
[Answer]
## Windows PowerShell
```
function OddOrEven([long]$n) {
if (0,2,4,6,8 -contains "$n"[-1]-48) {
"Even"
} else {
"Odd"
}
}
```
1. Convert to string
2. Pick last letter (digit) (essentially a mod 10).
3. Check if it is 0, 2, 4, 6 or 8.
No bitwise operators, no modulus, as requested.
[Answer]
## Ruby
```
n.odd?
```
If you want to print out the result:
```
f[n] = ->(n){puts n.odd?? 'odd' : 'even'}
```
[Answer]
## Unlambda
The world needs more Unlambda.
Unlambda has a killer advantage here: its default (*ahem*) representation for numbers are Church numerals, so all that's needed is to apply them to function binary-not to function true. Easy!
PS: Markdown and Unlambda are definitely not made for one another.
```
true = i
false = `ki
not = ``s``s``s`k``s``si`k`kk`k`kii`k`ki`ki
even? = ``s``si`k``s``s``s`k``s``si`k`kk`k`kii`k`ki`ki`ki
```
Verification for the first few integers:
```
```s``si`k``s``s``s`k``s``si`k`kk`k`kii`k`ki`ki`ki`ki => i
```s``si`k``s``s``s`k``s``si`k`kk`k`kii`k`ki`ki`kii => `ki
```s``si`k``s``s``s`k``s``si`k`kk`k`kii`k`ki`ki`ki``s``s`kski => i
```s``si`k``s``s``s`k``s``si`k`kk`k`kii`k`ki`ki`ki``s``s`ksk``s``s`kski =>`ki
```
[Answer]
## Golfscript
```
~,2/),1=\;
```
[Answer]
## Python
```
print (["even"] + (["odd", "even"] * abs(n)))[abs(n)]
```
Similar performance to the earlier version. Works for 0 now.
**Incorrect Earlier version:**
```
print ((["odd", "even"] * abs(n))[:abs(n)])[-1]
```
Not particularly efficient; time and memory both obviously O(n): 32 msec for 1,000,000; 2.3 msec for 100000; 3.2 usec for 100. Works with negative numbers. Throws an error for 0, because 0 is neither even nor odd.
[Answer]
### Fractran
```
[65/42,7/13,1/21,17/7,57/85,17/19,7/17,1/3]
```
applied to
```
63*2^abs(n)
```
yields either `5` if `n` is odd or `1` if `n` is even.
**Update**: Much shorter but not so interesting:
```
[1/4](2^abs(n))
```
is `2` for odd `n` and `1` for even `n`.
[Answer]
## MMIX (4 Bytes)
This is kind of cheating. I use neither mod nor bit fiddling operations. It's rather that testing for odd / even numbers is builtin. Assuming that `$3` contains the number to test and the result goes into `$2`:
```
ZSEV $2,$3,1
```
sets `$2` to `1` if `$3` is even and to `0` if not. The mnemnoric `ZSEV` means *zero-set even* and has the following semantics:
```
ZSEV a,b,c: if (even b) a = c; else a = 0;
```
For the above line, `mmixal` generates these four bytes of assembly:
```
7F 02 03 01
```
[Answer]
# Scheme
This is the most inefficient solution I know of.
```
(letrec ([even? (lambda (n)
(if (zero? n) "even"
(odd? (- n 2))))]
[odd? (lambda (n)
(if (= n 1) "odd"
(even? (- n 2))))])
(even? (read)))
```
[Answer]
## Perl
What about
```
use Math::Trig;
print(cos(pi*@ARGV[0])>0?"even":"odd")
```
[Answer]
## JavaScript, 36
```
function(i){while(i>0)i-=2;return!i}
```
Returns `true` if even, `false` if not.
[Answer]
## Perl
```
$n x '0' =~ /^(00)*$/
```
[Answer]
## Python
```
zip((False, True)*(i*i), range(i*i))[-1][0]
```
testing the square of i, so it works for negative numbers too
[Answer]
# F#
Mutual recursion for the win.
A number n is even if it is zero or (n-1) is odd.
A number n is odd if it is unequal to zero and (n-1) is even.
(abs added in case anyone's interested in the parity of negative numbers)
```
let rec even n = n = 0 || odd (abs n - 1)
and odd n = n <> 0 && even (abs n - 1)
```
[Answer]
# Clojure
```
(defmacro even?[n]
`(= 1 ~(concat (list *) (repeat n -1))))
```
[Answer]
What qualifies as bitwise operations? Under the hood, integer division by 2 is likely to be implemented as a bit-shift.
Assuming bitshifts aren't out:
# C/C++
```
(unsigned char)((unsigned char)(n > 0 ? n : -n) << 7) > 0 ? "odd" : "even"
```
*edit* Missed some parentheses, and ultimately changed to remove a shift to make it do less. You can test this with the following (in \*nix):
```
echo 'main(){ std::cout<< (unsigned char)((unsigned char)(n > 0 ? n : -n) << 7) > 0 \
? "odd\n" : "even\n";}' \
| gcc --include iostream -x c++ -o blah -
./blah
```
... though in Linux/tcsh, I had to escape the backslash on `\n` even though it was in single-quotes. I tested in little & big-endian, it works correctly in both. Also, I hand-copied this; the computer I'm posting with doesn't have a compiler, so it may have mistakes.
# x86 asm
```
mov eax, n # Get the value
cmp eax,0 # Is it zero?
jge pos_label # If >= 0, skip the next part
neg eax
pos_label:
```
.
```
imul al, 128
```
or
```
shl al, 7
```
or
```
lea eax, [eax*8] # Multiply by 2^3 (left-shift by 3 bits)
lea eax, [eax*8] # ... now it's n*2^6
lea eax, [eax*2] # ... 2^7, or left-shift by 7 bits
```
... followed by:
```
cmp al, 0 # Check whether the low byte in the low word is zero or not
jz even_label # If it's zero, then it was an even number
odd_label # ... otherwise it wasn't
```
Alternatively, the shift & compare stuff could be done this way as well:
```
sar al,1 # signed integer division by 2 on least-significant byte
jc odd_label # jump if carry flag is set
```
[Answer]
On a 68000 processor you could move a word value from the address defined by the value to test:
```
move.l <number to test>,a0
move.w (a0),d0
; it's even if the next instruction is executed
```
and let the hardware trap for address error determine the odd/even nature of the value - if the exception is raised, the value was odd, if not, the value was even:
```
<set up address error trap handler>
move.l <pointer to even string>,d1
move.l <number to test>,a0
move.w (a0),d0
<reset address error trap handler>
<print string at d1>
<end>
address_error_trap_handler:
move.l <pointer to odd string>,d1
rte
```
Doesn't work on Intel x86 CPUs as those are more flexible about data access.
[Answer]
# Python
I decided to try for the ugliest, most confusing solution I could think of:
```
n=input();r=range(n+1)
print [j for i in zip(map(lambda x:str(bool(x))[4],[8&7for i in r]),
map(lambda x:str(x)[1],[[].sort()for x in r])) for j in i][n]
```
Prints e if even, o if odd.
[Answer]
# Q
Keep subtracting 2 until x<2 then convert to bool
```
{1b$-[;2]/[2<=;abs x]}
```
] |
[Question]
[
*Inspired by [this](https://codegolf.stackexchange.com/q/210638/95792) challenge, which got closed. This is meant to be an easier, but no less interesting version of that.*
This is the robbers thread of a [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge. For the cops thread, see [here](https://codegolf.stackexchange.com/q/213962/95792).
Cops will provide a program/function and a flag. Robbers will guess a password. When the password is given to the cop's program, the flag should be outputted.
## Robber rules
* When the cop's program is given the password you guess, it should output the flag.
* Your password does not have to be the same as the cop's password.
* You are allowed to take advantage of ambiguous descriptions of the flag by cops.
Cop answers will be safe if they haven't been cracked for two weeks.
## Example
Cop:
## Scala, 4 bytes
```
x=>x
```
Flag: `Yay, you cracked it!` (an object of type `String` is returned from the lambda above)
[Try it online!](https://tio.run/##K05OzEn8n5@UlZpcouCbmJmnkFpRkpqXUqzgWFCgUM2loFCWmKOQZqUQXFKUmZeuYGsHZ/2vsLWr@A9RkF6aWlysYKugFFBaolCZX1oEFclILUpVAhpSANRSkpOnkaYBFtfU5Kr9DwA "Scala – Try It Online")
Robber:
Password: the string "Yay, you cracked it!"
[Try it online!](https://tio.run/##K05OzEn8n5@UlZpcouCbmJmnkFpRkpqXUqzgWFCgUM2loFCWmKOQZqUQXFKUmZeuYGsHZ/2vsLWr@A9RkF6aWlysYKugFJlYqaNQmV@qkFyUmJydmqKQWaKoBDSlAKinJCdPI00DrFRTk6v2PwA)
[Answer]
# [Sisyphus, PHP](https://codegolf.stackexchange.com/a/213984/98889)
Password:
A string `golf` with 1,000,000 leading whitespaces and 1,000,000 trailing whitespaces
Output: `golf`
Reason: 1,000,000 is the default backtracking limit of PCRE (which you can get by `var_dump(ini_get('pcre.backtrack_limit'));`). And `preg_match` will return `FALSE` other than 0 or 1 when this limit is breaked.
[Try it online!](https://tio.run/##7dBJCsJAAETRvadQCGRAzN4BjxIkdgaISaO98PbRe@S93ad2FYe4rtd7HOIu@966cQpNH1LTLnMKc/oU@X851/UnPcc5Ly@7sSsO8R365vVI7VDk9anql6k7VXV@zL5lGdph2af3@Cr@dVnXPQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAsFH9MnVeAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACArfoB)
[Answer]
# [ovs, Python 2](https://codegolf.stackexchange.com/a/213978/39531)
Password:
```
class m:0
m.__init__ = hex.__init__
n = 49374
m.__str__ = n.__hex__
class a: __metaclass__ = m
```
Output: `0xc0de`
[Try it online!](https://tio.run/##PYzfCsIgGMXvfQovgm0hEjWIHHuSVmLOUJpO/L6L7elNDLo5nD8/TtzRruGcs/NxTUiTYbADiWNRDji7wJNRc9sR9y4j9wq1bZvn3Wx6mm36vCZYnJejGBhXAeFxPDQsdsJsRtM4xOQCUpWzXhQA9eJEPJfSBYdS0pFas/0jCaXob5drXxnAVJFQfMHK/vtQgkrpDaoaK@K/)
[Answer]
# [R, Robin Ryder](https://codegolf.stackexchange.com/a/214055/98904)
Password: `as.roman(c(1, 9)))`
It was roman numerals!
[Try it online!](https://tio.run/##K/qfpmCr8D@tNC@5JDM/T6NCUyE5I7GopEhDqaqyorysVElHQSkIDICskvyc/PLUIo2KaMNYBW2FimijWE3N/2kaicV6Rfm5iXkayRqGOgqWmkBBAA "R – Try It Online")
[Answer]
# [Lynn, Haskell](https://codegolf.stackexchange.com/a/214033/64121)
Lynn created a stack based mini-language, the task was to generate the primes up to 500 in 60 or less operation. Here is my 55-operation password:
```
[0,0,2,1,4,1,0,2,1,1,4,4,4,30,0,2,0,2,0,20,10,0,3,10,2,0,3,1,0,10,3,6,6,6,6,5,4,7,5,0,7,3,10,2,0,3,20,2,1,0,3,0,3,30,2]
```
[Try it online!](https://tio.run/##XY/RisIwEEXf8xWFvCRrLGmqFYLxC/wDEQlaMdgNsXYlFf@9zqQ@1GW4M3dOkgu52Pu1bpphcP7sYiYpkTrQaAItdCQFev002GESlfY@EdbPIgdWfrF5Yosv9pPYcsJO7pH1GSZWE9rr5MjqH3uSI5IXu4mDbvl6fg/Ws/WRB9PSP9@5hjFjJM8vtT1xdqM8kgP8IZJf67xpgW79ZmNC63yXM7rb87yz1zqr5DDspJBCiUIsQKNDj1WORx9JUeBe4lCjEYmVovrUEh6toEvok3tqjEWLgli1fwM "Haskell – Try It Online")
The available operations are
```
0 push 1
1 duplicate top of stack
2 add top two values
3 subtract
4 multiply
5 integer divide top value by second value
6 push the second value without popping it
7 swap top two values
c>7 while loop, runs until top of stack is 0
the loops ends at the first instruction >=c
```
---
`0,0,2,1,4,1,0,2,1,1,4,4,4` pushes the initial number `500`.
The remainder of the code is best explained inside out:
`6,6,6,6,5,4,7,5` is a divisibility test. Given `k` and `n` as the top two values on the stack this calculates \$\lfloor {\lfloor {n \over k} \rfloor \cdot k \over n}\rfloor\$, which is only 1 if `k` divides `n`: [Try it online!](https://tio.run/##Xc/vCsIgEADw7z7FgV@03Fh/tkiyJ@gNIkKaNdkysxUuevc17UvlgXf34zi4St5q1TR9r81Re8gwyrjFXlg84R5NQs2fIvxDRtPYd1FIN/Z0sNmPJdHmPzaKln9ZqR/QQdhYfGnHY4UWf/ZEhyAvcmV77ugquVlpyOpArXD4blrdECJERtNKyZKSK6Ye7YcbPEoSCM@ANCXUcLpApZwCeKCz1Ea4YX5j1mthnTZtSvB2xmC5o2krawVF1vfbgn0iZ3O2YPnuDQ "Haskell – Try It Online")
---
`1,0,10,3,div test,0,7,3,10,2,0,3` is a primality test, or a composite test since this returns truthy (non-zero) values for composite numbers:
```
1 -- duplicate n
0 -- push 1 - stack: [1, k=n, n]
-- in the next iterations of the loop,
-- the top of stack will be the inverted result
-- of the divisibility test
10 10 -- while loop:
-- runs until [0, d, n] is on the stack,
-- where d is the largest divisor of n <n
3 -- subtract top value (always 1) from k
div -- the divisibility test
0 -- push 1
7 -- swap top two values
3 -- subtract (1 - div test result)
2 -- add the top 0 to the last k
0,3 -- subtract 1
-- if the loop ended with [0, 1, n], this is now 0
-- otherwise we have a positive number
```
[Try it online!](https://tio.run/##Xc/hisIgAAfw7z6F4Be93HCtbSBzT9AbRISUNWnnmVvh4t59p3IHdQp///4UwV6OVzUMy6LNWXvIEGDcIi8sKrgHRez8KWKGFazTfk6C55Unwco3y5Jt3uwjWfViJ/2AM4wv1i8689RA88@e4BjlG9/ogTvSZqOVBrdHYoVDdzPpAWMhGMl7JU8E3xDx4BD@4EGWwb9h4OVLjbBXTsEH@JTaCBeub03XCeu0mXKMds2e5JO8KlizZdkVlNGC0ZLWv7OiG9qEZCHLeLQOtdz/AA "Haskell – Try It Online")
---
`0,20,10,0,3,10,2,0,3,comp. test,20,2,1` generates the next prime less than `n`:
```
0 -- push 1. This means the current number is composite
-- Even if it isn't, we still want to find a prime <n
20 -- while loop. This iterates until the composite tests returns 0
10 10 -- we have an positive number on the top of the stack ...
0 3 -- by subtracting 1 until it is 0, ...
2 -- and adding this to the last prime candidate ...
-- we can get rid of it.
0 3 -- subtract 1 to get new prime candidate pc
comp -- check if pc is composite
20 -- end of loop, top of stack is now [0, p], with p prime
2 -- add 0+p
1 -- duplicate the prime, such that we store the result,
-- and can use the value to find the next prime
```
[Try it online!](https://tio.run/##Xc/RasMgFAbge59C8EY3E4xpUpDaJ@gblFKkdYs0c9ZkxZS@e6ZujHQK5/x@HA7YqeGi@36ejX0zATIEmHAoSIcqEUCVsrjLVGMHPL@nLHh6DSRa/WRFttWTvWRrFnY2NzjBtLFd6CRyAut/dgenJA98pUfhyaYYnLJ4cyJOevRlR9NjLCUjZafVmeArIgEc4x8CKAr4dyx8/9QD7LTX8AY@lLHSx/md3W6l88aOJUb7hvEDKUd10bBl87xnlDNaMcponRr/CTRbTdvf29AVXcfKYl3M8RSqwzc "Haskell – Try It Online")
---
`30,0,2,0,2,next prime,0,3,0,3,30,2` repeats this until the prime `2` is found:
```
30 30 -- while loop
0 2 -- add 1
0 2 -- add 1
np -- find the prime less than this
0 3 -- subtract 1
0 3 -- subtract 1
-- if the prime was 2, this is now 0
-- and the while loop terminates
2 -- add the 0 to the 2 to remove it
```
[Try it online!](https://tio.run/##XY9va8MgEMbf@ykE3@hmgjFNClL7CfYNSinSukaaOWuyYsq@e6buD@nuuOee@3EcXKeGi@77eTb21QTIEGDCoSAdqkQAVfLiLpPGDniep0zw9BxIZPUDKzJbPbCnzJoFO5kbnGC62C7oJLID63/sDo6JfOIrPQhPNsXglMWbI3HSow87mh5jKRkpO61OBF8RCeAQfwigKOBfWHh@1wPstNfwBt6UsdLH/Re73UrnjR1LjHYNY3tSjuqiYcvmeVczyij/LUarNNep8W9DM6tp@5MNXdF1VBZ1sceTqbJNFc/y/Rc "Haskell – Try It Online")
[Answer]
# [R, Robin Ryder](https://codegolf.stackexchange.com/a/213985/46076)
```
5.099829245500619335478113833945732102551318887107339446461762721i
```
[Try it online!](https://tio.run/##Fcg7CgMhEADQq1hqE@brzBS5xeYEC4KNwq6B3N4kr3zXbumZdnuPc/U58qekPtYxX6t5Puf9i7Jb1gdEOAWJKkDFYFYxR2RnDlFjQiBVZHR3Q7B/S5WKVskIe9lf "R – Try It Online")
[Answer]
# [Sisyphus, Jelly](https://codegolf.stackexchange.com/a/213991/78410)
Password:
```
[1.1071487177940904,1.1071487177940904,1.1071487177940904,1.1071487177940904,1.1071487177940904,1.1071487177940904,1.1071487177940904,0.897846510365972]
```
[Try it online!](https://tio.run/##y0rNyan8/9//cFtIwP///6MN9QwNzA1NLMwNzc0tTQwsDUx06C9koGdhaW5hYmZqaGBsZmppbhQLAA "Jelly – Try It Online")
The code `OÆTP`, when taken literally, means `product(math.tan(ord(c)) for c in input)`. But the ord function in Jelly does nothing for numbers, so we can ignore that. Now the problem is to generate that *very* specific number. I figured that as product is likely to have precision loss, I'd use 2's as multiplicands. The number `1.1071487177940904` is equal to `arctan(2)`, and I use seven copies of it to reduce the problem to `arctan(x)` where `x<2` so that I have better chance at getting that exact result. Finally I computed `arctan(answer/128)` and put it as the last term of the input array, and it worked perfectly.
[Answer]
# [att, Wolfram Language (Mathematica)](https://codegolf.stackexchange.com/a/213979/98349)
Password:
```
flag /: Head[flag] = flag
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78r6yvr5cYb2XnkZqY4pCoFv0/LScxXUHfSgEkEA3ixCrYKoDo/7H6@gFFmXkl/wE "Wolfram Language (Mathematica) – Try It Online")
.
We can adapt this kind of solution to work with any Mathematica program:
```
a /: _[a] = flag; a
```
With this argument, any function returns `flag`.
[Answer]
# [JavaScript](https://codegolf.stackexchange.com/a/238174/64121) by tjjfvi
The flag is: `()*` (Or `()?` / `(){0}`)
[Try it online!](https://tio.run/##LcYxFsIgDADQq/iYElsZ3NvNC3iDFPIQxZAHqPT0dPFP/0lfqq5EbZeq0XN5Z3nxPobLUnNim3IA07uxVVNsIPw73TncuoIuhcmnKAyIaAv7j2MAmjdcVpq22Ri0iSW0x3qd9F8cA/B8AA "JavaScript (SpiderMonkey) – Try It Online")
This splits between the two x's (it matches the empty string) without actually capturing anything with the group. The return value of `split` includes capturing groups, which results in `["x", undefined, "x"]`. This gets reduced to `"xundefinedx"`.
[Answer]
# [Sisyphus, Python3](https://codegolf.stackexchange.com/a/213987/11006)
All you need to do is keep the processor busy for more than 9 seconds.
Any regex that requires lots of backtracking will gum up the parser. The only real difficulty is not slowing it up so much that Tio runs over its 60-second limit.
```
'b(.*.*.*)*z|baaaaaaay'
```
[Try it online here.](https://tio.run/##K6gsycjPM/7/PzO3IL@oRKEoVackMzeVK8k2M6@gtERDM9rKxCCWK9EWJKoHIjQ0uYpS9XITS5IzNJJ0kjS5MtMUkCR1E@0srQqKMvNKNAw0//9XT9LQ0wJBTa2qmqRECKhUBwA)
[Answer]
# [JavaScript (SpiderMonkey), tsh](https://codegolf.stackexchange.com/a/213997/48931)
Password hexdump:
```
61 61 61 00
```
(3 `a` followed by a null byte).
[Try it online!](https://tio.run/##JYy7CsMwDAB3f4U2JxTjdMnW/otiC6I8bCGbkkL/3W0TbrnhuAnL3BqFOYPFhxLGjRN1vRHlVDu8YW/hCSFHMubKxvufYbDwgeOI4BSc/NxnqX7BF5agLNUV4Ui657TS20@c/FLOT2tf "Bash – Try It Online")
[Answer]
# [Eric Duminil, Ruby](https://codegolf.stackexchange.com/a/214092)
My password is
```
14127792144400463565475544498208881214759697720904563865426051592050217695592754443713601541725640031x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000123456789
```
According to the Ruby documentation, to\_i discards everything after the first integer it finds.
[Try it online!](https://tio.run/##tY9BCsJADEX3nqJ01Qodk8wkmSx6kiKCUKWbKraF0cvXqYI3MItPPi8/8B/L@bmuqb3287S7L/NUVKkD59zYJjcNr/5ARzffTsM@daNzDX5dvelUeamL4VKkrrEPa9sSyQcWjVauKwYkVSMMIQAE8SwclDlbiwQxRsxM2cRUCQxy0sd8QwKMbAQMhCrGedct5hW9AHJAJZb81GOCf82vyhs "Ruby – Try It Online")
Alternative solution:
```
9164214512877268290754278122624834497733309914632715416260853069873976599113800182718102190123456789
```
I factored the semiprime with cado-nfs.
[Try it online!](https://tio.run/##PY1JCsJAFAX3niJkZYS0f@o/LHKSIIKgkk0UE6H18nECNwWPelC3@@GxLKU7H@dpdb3PU7UuPaSUxq6kaXget7RL82U/bEo/ptTibzUfTmvWphpOVenb@Lquq5FYsppHvSyBKoSSkdyM1CnAspA5EimJs0iYMTNEoCiTYRZUUvDMoOHGYZrfEtkB0N8HRyAM@Gde "Ruby – Try It Online")
[Answer]
# [JavaScript (V8)](https://codegolf.stackexchange.com/a/214153/44718) by PkmnQ
```
({toString(){return this.i--;},i:43})
```
[Try it online!](https://tio.run/##PYtBDoIwEEWvMiYuIAEWysJg0EN4ASpOYUyZajvFGMLZa6OJu//@y7urWfne0UPK@RCjbrk98aatd@duu/AK5EEBh@mKrmv@l4wIiv0LHYj9UjBCkxKEZ0AvZBmsBkMai59mmtH5RIpvgGm/ZSQeuthb9tZgZeyQ6WwRexGXRJYvDiU4Tjn5isryuBbU1Ps1z@MH "JavaScript (V8) – Try It Online")
JavaScript variables like: `({toString(){return this.i.shift();},i:[1,2,3,4,5]})` would be useful in many [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") answers.
---
```
({valueOf:()=>43,toString:()=>42})
```
[Try it online!](https://tio.run/##PcpBDoIwEAXQq4yJC0jQBbIwJIUjuPACVJxCTZlqO60xhLNXIom7//7/Dxml751@8iGeU1KCREM7UZVtt59pAe1BAoXphq6r/xWPCJL8Gx2w/SkY1pNkhFdAz9oSWAVGKyy2mXRE51dJugOu@cOjpqFLvSVvDR6NHTKVzVGagBdVZ7loqlPB9spu/W0ulzxPXw "JavaScript (V8) – Try It Online")
It is strange: While, let `p=({valueOf:()=>43,toString:()=>42})`: `''+p` results `"43"` but ``${p}`` results `"42"`...
[Answer]
# [ZippyMagician, Arn](https://codegolf.stackexchange.com/a/214040/11006)
Password: `J0e_Biden!`
I'm sure this isn't the password that ZippyMagician was thinking of, but it works at least. The flag is equal to 296, and the uncompressed code starts with `:*:*`, which raises something to the 4th power. I'm not sure what's going on in the middle, but the last few bytes of code (`:i0^:i"n`) calculate the value of *a**b*, where *a* and *b* are the indexes of the characters `0` and `n` in some transformed version of the input. So if the second character is `0`, it's just a matter of tweaking the input until the `n` is in the right place.
[Answer]
# [Python 3.7](https://docs.python.org/3/), [ovs's answer](https://codegolf.stackexchange.com/a/218895/69850)
```
@print
@int.__invert__
@len
@ascii
@ascii
@ascii
@ascii
@ascii
@ascii
@ascii
@ascii
@ascii
@ascii
@str.lstrip
@min
@ascii
class a:
pass
```
[Try it online!](https://tio.run/##pY5BDsIgFAX3nKJdAY0hJt1VMRzEhOAvRgz9EMBGbXp2bFx4ATfzZvUy8VVuAftaQYZoke25SNaMjJOlg/W4dPSMzU4MB6m0ucBor@7uJwwx5TK/6drK/gQCwgMLo@BNzpS30j4tMOC1qpgcFqI2CK0dzjYVrYnyFokyGZz7e3JJwm9wkajJ/W6/LY0ZSBM3@QA "Python 3 – Try It Online")
I used a brute force program to find the solution, although in the end it ends up being quite nice: [Try it online!](https://tio.run/##hVTLctowFF1bX6GIBRJxHNNONk7dCdNV990RxiNsuSgxskcSFEz4dnolPxLSRVl40H3fc47UHO2mVl8vl8nN/Vqq@8afkdw2tbZYKtOI3CL4yRLHCQoaLZWlRlhK8o0m7O40mz4rHEbJY/qU8XVeiFK@VFtVN9rYfTs9MxRoLo3Ac4Ta9HRGCEIwLwrahljxrWBQFqqfZu5w/vbfghAeWH1MsErFnlfU1wCbOOSisQnWwu60AgMUlQVVDKvarYJblxm0S29cpT4RRmCwXVlrnLuYQmqaZeudrCwsn2X9cN5H6kYo7BGAwiQyTSUtZQnOawXRO4GCfq2cdSWLrkXhspezNoJxd8JQtoKqbgWYx4U1zr/n2tCC@RmhY5OmJMuMbEVdZhn52CQY2pTk5Duco1NzJoDBAEHDjYGt4CuARUp4VZEQw5f9M0mIW5RXEIkXfZ4WPN/wdSXSEyC1gP0oJQsSshAv2NmzV1bc0kOPjTSAlOUqF/QQYrtrKk@p34y7focEH6WoClzqetvlcjdsZcTgOSDvy@uqAr3JWhncS/BHvVNWaGSPjchyd0h7E2XICKEyIGQrrdyL1MmSocmfjawE/qV3IvEsSAjmrqgbRnP1W9B5HLNRzeTnEJBggGkMZ916wzFNH9xaoOHXBO@xq/wawh@nrAiitgCnI8cl7ZfxyjmoNwQE2kRZJtUe@AA2w97MTS4ltCSVUIMRIEYeO1lkIaZAhVQhrtcvAEzm@RsJivK6OVI2NHfTTaA5uSMuzFhNh7SBj7ITZNkNPYjAa66/UuWY44yDoD6K7/O1GsfxZQKbOqqoGrHwQRQQCN1IXTPvAETv5vGXh94ysFECvcUNYdfWJ4JvMbwMT9PopZaKagFYGlHQ5cwryuPEVgxUSp7Vs3p7Gyv0SjJH8@g@kTi4a/s@hgfrSknXCwfBtTdy1889G87lVTzWelfp0q6@pw9xHH@udRVym867MpNuzSnu1/M7DeR71phfDdbyT5bLGYEfX7SreIhD6HL5Cw "Python 3 – Try It Online")
Initially I found one with `__sizeof__`, but it doesn't work on TIO (being implementation-specific).
I had to made quite a few tweaks for it to fork (disable `open` and
`id`, as the former will read from stdin with `list(open(1))` or something similar)
It's also possible to get `import inspect` and quite a few other modules, but I didn't consider that possibility.
In retrospect, `repr` would work as well, but `ascii` comes before `repr` in my generator program.
[Answer]
# [JavaScript (Node.js) by emanresu A](https://codegolf.stackexchange.com/a/237515/104752)
```
[Math.PI, 2n]
```
[Try it online!](https://tio.run/##ZY7NSsQwFEZfZVxI7sWa1lnMwjYjiJsR/AGXtTAhpk2GcBPSTHSoffbqgDu/7TlwvoPMclTRhnRN/kMvSxBZbKcUT5MUbVdDL5TYqrseVLmh74oKycNxNMAu2g7wirXqckMd4m1FCEbc22FHCR7fXp75mKKlwfYnyMijDk4qDeX7QzkUjCFifa5kobN0IPnBW9rvcVYyKQMap6jTMdKql27Uc217MM0NNc26@h1hMtF/si/2z89t1QkhnmQy/HU3z4vyNHqnufMDBGj/QLFan28vPw "JavaScript (Node.js) – Try It Online")
`JSON.stringify` throws a `TypeError` if it finds a `BigInt`, thus executing `catch(e){return v[0]===Math.PI}`, and then it is simple to make that true.
[Answer]
# [JavaScript by tjjfvi](https://codegolf.stackexchange.com/a/238444/104752)
```
document.all.toString = ()=>"length", document.all
```
[`document.all` is an object that is unique in several ways, including being falsy.](https://tc39.es/ecma262/multipage/additional-ecmascript-features-for-web-browsers.html#sec-IsHTMLDDA-internal-slot)
`in` uses `toString`, so the first part can be made true by changing `toString`.
[Answer]
# [HyperNeutrino, Python 3](https://codegolf.stackexchange.com/a/213965)
Password: `import sys;sys.exit()`
[Try it online!](https://tio.run/##HYpBCoAgEEXXeYpwo4JE0c7oNDHQgNlkEyXR2c1aPPjv8yjxvIY@53NGD3XnRMUxOT9ioIO1ERVcExCXR6lPYNLe3o@9JVzI0rVWbsc/nhJTxMC6MznjQmvkek/7UGi@WJsX "Python 3 – Try It Online")
Output: nothing
I'm not sure if erroring would be OK. It would not output anything to STDOUT, only STDERR.
[Answer]
# [HyperNeutrino, Python 3](https://codegolf.stackexchange.com/a/213965)
Password: `raise SystemExit`
[Try it online!](https://tio.run/##K6gsycjPM/7/vzwjMydVwdCKi7OkqNIqxzYzr6C0REOTizO1Ijm1oAQooq4O4qQma@ToVNfqVCulVmSWKFkZ6CgVloIZtUDFBUWZeSUahpr//xclZhanKgRXFpek5roCVQIA "Python 3 – Try It Online")
Output: nothing
[Answer]
# [ThisIsAQuestion, Python 2.7](https://codegolf.stackexchange.com/users/15100/thisisaquestion)
```
True=False
The
Flag
```
[Try it online!](https://tio.run/##XY3BDoMgDIbvfYqGjAQWs8OOS7j6BN50W9DhJFFgCHF7egbxZk/t169/3S9M1lxT0ouzPqBXANo4FOjl9sxdDIyDHtHYsrwsMgwT8@TRdlv3EvfziVSYNX4DzPWJuvjqqwZWKIA8RPWHeZzlO6OsCeyhfNqJwMZHtac6r01ghK5IV0KZrLDnPKUiiFrOq4JmUlDnuz8 "Python 2 – Try It Online")
Output is `The Flag`. *Sadly* reassigning `True` doesn't work in Python 3 anymore.
[Answer]
# [Perl 5](https://www.perl.org/), cracks [Nahuel Fouilleul](https://codegolf.stackexchange.com/a/213976/17602)
Password: `"^^@@^^:@@@^"^".,).*||,!'|"`
[Try it online!](https://tio.run/##K0gtyjH9/z8nNS@9JEND08bIQkFNTUFRP6ZcH8RILUvMARP//yvFxTk4xMVZOQBJpTglPR1NPa2aGh1F9Rqlf/kFJZn5ecX/dfMA "Perl 5 – Try It Online")
[Answer]
# [SE - stop firing the good guys, ><>](https://codegolf.stackexchange.com/a/214022/64121)
One password is
```
5 8a*3+o ab*1+o ab*1-o aa*1+o ab*6+o aa*4+o aa*5+o ab*o aa*3+o 48*o ab*5+o ab*1-o aa*1+o aa*8+o aa*8+o ab*5+o 48*o aa*o aa*1+o aa*8+o aa*5+o aa*1-o aa*5+o ab*1+o ab*7+o ab*5+o 95*1+o 95*1+o 95*1+o;
```
[Try it online!](https://tio.run/##S8sszvj/P9PQoOD/f1MFi0QtY@18hcQkLUMopQukEmE8M20wzwRCmUIEwWyQLhMLLbCAKabWRC0LJAqiBKI8UQuLKlMIBTXBFMVF5ggTLE3BgiiUNQA "><> – Try It Online")
The program was `i10p`. `i` reads one character of input `1` and `0` push `1` and `0`, and `p` changes the value at `x=1, y=0` to the inputted character.
Whit the first input the program is modified to `i50p`, which allows to execute arbitrary commands from input.
`0-9a-f` push their hexadecimal value to the stack, `*+-` work as expected, `o` outputs a value as a character and `;` terminates the program.
[Answer]
# [SunnyMoon, !@#$%^&\*()\_+](https://codegolf.stackexchange.com/a/213975)
```
1728
```
I read the code, and it seemed to parse decimal input, divide it by 48 (not halting if it's not divisible) and print the corresponding character 3 times.
[Try it online!](https://tio.run/##S03OSylITkzMKcop@P9fK05DVUEhXlsrTlNVwyBeW1UTzI1T0VCJj4sHY21FGNCGgTgVTW2gFEilikZ8HBzEq4BkKirAwgbaEK6iooODw///huZGFgA "!@#$%^&*()_+ – Try It Online")
[Answer]
# [Kevin Cruijssen, 05AB1E](https://codegolf.stackexchange.com/a/214006/64121)
The password is
```
2
,*xžIž?¶
```
The `.E` builtin seems to push the Python code back to stack when it failed.
The first input is just any number for the loop. The second input is a reversed 05AB1E program to produce the correct output:
```
¶ # push newline character
? # print without trailing newline
žI # push 2**31
žx # push 2**6 = 64
* # multiply these numbers => 2**37 = 137438953472
, # print this with trailing newline
# since there was explicit output, implicit is now disabled
```
[Try it online!](https://tio.run/##AScA2P8wNWFiMWX//0Z9xb5o0Lw5wqMuRVIuVir//zIKLCp4xb5Jxb4/wrY "05AB1E (legacy) – Try It Online")
---
After some more experimenting, I found a cleaner password:
```
3
print()
3
```
[Try it online!](https://tio.run/##MzBNTDJM/f/frfbovowLeywPLdZzDdIL0/r/35iroCgzr0RDk8sYAA "05AB1E (legacy) – Try It Online")
`.E` executed on `"print()"` returns `None`, reversed is `enoN`. This is then executed as 05AB1E code, which seems to return the right result. I'm not sure how though, there might some features of the legacy version used here that I don't know of. Beacuse Python was used to print the newline, the value is still implicitly outputted.
[Answer]
# [Python 3.8 pre-release, pxeger](https://codegolf.stackexchange.com/a/214073/46076)
```
("unittest.mock",("mock","sentinel","pxeger","name"),())
```
Probably not the intended solution.
[Try it online!](https://tio.run/##bU5BTsQwDLz3FVa4JKuIA3BARfsA3rBaVd7UaSNSJ0odYF@/hAA3Th7P2DOTr7ImfnzO5eZL2sBXdpJS3CFsORWBw3AHF3JYd4JXYKIZkP9EFJCVYBcsYmGPwRHU3DmXZgJJsJBA4njtZHcPieEjtNgq4FbkJfDS1Ui8yArJ923DwN1l8Ed6x6iVUv93PLxE3C4zAtqLdaOex2OhuToy@lcg60c6@bN1dtatEYqUdjtNPwbTpNEYc2sJp4en8WyGIZfAor0@9OjAuYo23zdaVQ4itMv9ltybslr9TLUTS2CKDeZPWqg0wLiRMra9fgE "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Ruby, Dingus' answer](https://codegolf.stackexchange.com/a/214106/48931)
```
system gets;exit
echo '"""'
```
[Try it online!](https://tio.run/##KypNqvz/X1E/Ojg5raAsRs8qxl5dSdUmQSNWX02tQCO1LDFHJV7z///iyuKS1FyF9NSSYuvUiswSrtTkjHwFdSUlJfV/@QUlmfl5xf918wA "Ruby – Try It Online")
[Answer]
# [r3mainer, C](https://codegolf.stackexchange.com/a/214125)
I'm really sorry, but [this](https://stackoverflow.com/a/31515396) answer on Stack Overflow has code that directly undoes elementary xorshift operations... It made running xorshift in reverse much easier (I only had to copy-paste some code and write 6 lines of Python).
```
07RtUrVE
```
[Try it online!](https://tio.run/##S9ZNT07@/z83MTNPIzOvRCFRJzkjsUhLK0mzOi2/SKM0rzgzPS81RSEnPy9dQavCVktbO0kn09bU0sjS1DpTV9daqyLOVqvCxsbQWAfCtLMz14EJmmpaF5SWFGsAjbOu/f//v4F5UEloUZjrv@S0nMT04v@65QA "C (gcc) – Try It Online")
[Answer]
# [Conor O'Brien, Javascript](https://codegolf.stackexchange.com/a/214185/36445)
```
^^^Z_][_\\\\\]_\\]]]]]]]]]]]]]]]]]]]]]_\\\]_\\\\\\\]_\\\\\\\\\\\\\\\\\\\\\\\\]b_\\\\\\\\\]aa
```
The code seems to generate a random maze (the seed is based on our input, but I don't use that) without loops. We must solve it (in at most 999 steps) with a program in a stack-based language with these 8 commands:
```
0, rotate stack: S.push(S.shift())
1, pop twice, compare and push difference: [a,b]=S.splice(-2);F=a==b;S.push(a-b)
2, increment register: M++
3, push register: S.push(M)
4, pop and discard: S.pop();
5, reset register: M=0
6, pop to register: M=S.pop();
7, set answer to ToS and halt: R=S.pop();O=[]
8, pop pop() numbers, and if the last equality comparison was true then
insert the numbers into the program: n=S.pop();n=S.splice(-n);if(F)O=n.concat(O)
```
The program receives its input as the lengths of the lines of sight in 4 directions, and must output one or more commands in base 4 (digits 0 and 3 are errors, 1 is "rotate left" and 2 is "move forward").
My algorithm checks if the line of sight to the left is zero; if it's zero, then it rotates right (by returning 21), otherwise it rotates left and moves forward (by returning 9). I might have confused left and right completely, though.
Our "program" is obtained from our input by concatenating all char codes in it (as decimal integers). However, nines are discarded. So I used characters with codes from 90 to 98 to access the commands.
[Try it online!](https://tio.run/##bVYNb9o8EP4rfIjKbowX2Ca9bXZUbbdW00aZgOndlnlbCAFSkUDjlA@B99e7s53Q9n0XCXK2z/fx3HMHt8EqkGEWL/NmuhhHD8tskSzzClQIrUCngsswkpIH2XTlt4X38AWIzznvCTYAX1Do7OZRXumyKxawEeuz1OvCFbjeehbPI9Lj8yid5jMarYI5IbWzAZezeJITSus@XhDVNvWuIAAYeWdBc0TrXcepn3VpvVHvgoufRr0PjR66qqfQSKsp9eIJuaI9SHm4SMMgJz1a43I5j/Nf9V9@r7Qv9vtajfIsWs6DMCIvGi@mrDbgy8WSUO/pwfez4uRezsjTg6reh4GxjetmjVIvi/L7LK30lYfOZV75DBYvQosQfvEkWJJIQxfxcBZklwjquc6X3y7iFM8P9k@0/VpxkWjJXIWOE1GvDzt52nZZcupu/nHtw4LTVst9@br1uv3qNQtPW@2X@J4i/HeE7srQuATS58ExCsdOn4e00eeJYjFZPdG5e/G7idvHq72rjIXRUwsxaVPFZqbQgaC7ySIjMfxuBkU1vbjjenGzSXe3oLVjp0U9P/BjwQL/Vgjw9YvpDaEKq4FSno7tMwIwvsf8yZKFSJ@lEzKXeuE8kLIy2BlYs/swR5drloJLd/kslnwNa88IKaRWkLBTVgpRUjdkCHp1SCON1pUBGfI1G/KUqk@Hc52N5myMLI3foIIXOw5FVlWHPMSQ6ZCfk1jfwu2y4kPVJZLlrDSiDZyDviAFuzBCLrwhl/65APva7327c2F3Lh53zoWlG@JrT2ihaCgQYlNpg6GAc0W9cYTOoopVUAOi@@w/uWrtQIAJYyTUOQmZPOgUpqQDtZpxI2088jEeWcQTUnXsD7bJaDHncR5lAZZBIDO2cTQfH/dGt1GY8yjNsziSxFaBqm9kApNgLqNn4FxilCFbsRuWsSmbs8S7xCb2RuCH4ApPF8EL3/xuavxDBHqHBRjyAUYeIpv2e1KdHB31@YjS3aUNbkTNbaclVITeMK9uoe2NivBRVupRfaU93mCyN8SMjerkUH0/ZlIsJpWhjfbO8FgW/G62rPodvXMcb4pnMyKxUc0ccNkdWj7Ub0q9aVm1G66RjykGkWnXl@VBaAQSsZgFZmQCtgzAoZ8SqM6P216yh9YxWfE4HUeb3oREtAqgg8msu4Sqwwzyb/gnQlkmlMyDPA4rV2QNLZfN8MvmJMG2wJpaTTYF328JwTTxDf7xG8v9qe8WBGgx9Pa8QWZGZedL9AWSf8NJAGAgmh5AeE8yTLog4xQ7XV9/DyRjFezr3NKj/K14CxgFe6e/MbGS8G@tMZc5hIRHbQrY@tR7Z3fNXsvsYYDqgMFb9k6oYnZcPJ8dj1gYniY4yBEhNqN2ZmSYmxGuAa9EVp4QqgKyMSzmG7a1wvbQZtaSvxX@RqgJeWywDXJsi59oC63il2/IA4Llc3GabJBEeFbYTTTYJc@eKGuN4kK0aTbVv@S53w3Y@9Hm6MjGVW5s1ZhkVs4Od3zfZQiz32wxF18ua@qVXggfSfORFMBkGJwVGvBKXRHLnUWJwbLAgI2tMCYFgBsHxpiJXWz1AsuJTWPWmDpAq/CwgUWhBcsSc0MIVapjqtRUbzGP@HwxJbV1nNboc2UcwDq7Ik8n83TAhmgJ9shjfBll/6tgAXMRG@4j0BhemUMZfuI4JYkTNSQTi0UikarsJXNZW7AVTEgiy19qY7CLfYpUtS5WRXGubfJ@7cPHqw81f9V4JQQfYWObICiiuOp0oK2eVvha9UufX@Hk5ORp1NdHR1@bzY5LzUrHphTR/X2h/1r0SQCdL@QzThf68PDw48ePbz@F//O7fgS@xN@en8XhQevvjxg9Hokg@AM "JavaScript (Node.js) – Try It Online")
[Answer]
# [Dingus, Ruby](https://codegolf.stackexchange.com/questions/213962/guess-my-password-cops-thread/214164#214164) and [Dingus, Ruby](https://codegolf.stackexchange.com/a/214106/65905)
One password for both Ruby challenges by Dingus is:
```
G=->*x{i=0;i+=1 while x[0][i]!~x[1];x[0][i]};Q=method G[methods,/^[o-q]ri/];C=method G[q=Q[],/[o-r]ut[b-d]/];D=method G[q,/^de/];P=G[q,/^[o-r]\z/];D[P]{|x|};C[34];C[34];C[34];C[10]
```
[Try it online!](https://tio.run/##XYtLC4JAFIX/yhSFPXxSq6aphYFbpeXtRg8nGijUSU1L@@tmGRRtDufxHZns8qoKCU@3p15nqku@9fVYKsv9IUxzfTJfKe3udNNT1I7RryqHabNBdhfMpGLILHI9ihMnGZgIAluPDCykn1RSj515fAx84kBjLqqxhkCLUAoDqf2dI@YBqka9SUxi2Gk@1sDiB6ifPq87lzXhja5uLwpcvBdZUVIbRmP8U8vEJw "Ruby – Try It Online") & [Try it online!](https://tio.run/##XYvJDoJAEER/BYy74kD05Dh6wMQrxGPTrmCYBAEBFQX8dEdcEo2XSi2vouPmIoRMYL7dhSerN7QmjUpttGoiqdfDpnNae9VlS4gZU8btNONMpbzDNOnscs@RUlAROMq3FDSkn1RQk@2dxA1saQZvE3fJAgLlgBEnSPXvfGAmYJeUW4THBDaKjSUw/QHKp@2UncHe4YVa1ycFBmZ5mhdUh/4A/1RT8R6ECQ/8WCj@Aw "Ruby – Try It Online")
* Gets access to [`putc`](https://ruby-doc.org/core-2.7.0/Kernel.html#method-i-putc) by listing all the available (private) methods and filters them with regexen.
* Also redefines [`p`](https://ruby-doc.org/core-2.7.0/Kernel.html#method-i-p) to not do anything.
* a lambda is used instead of `def`
* `method :method_name` with `[]` is used instead of `()`
* `.` cannot be used, so only the methods for `Object` and `Kernel` are available
* Since `putc` is available, any string could be written.
FORTRAN like code:
```
GREP = lambda do |l,r|
i=0
while l[i]!~r do
i+=1
end
l[i]
end
PRIVATE_METHODs=method GREP[methods,/^[o-q]ri/]
PUTC=method GREP[PRIVATE_METHODs[],/[o-r]ut[b-d]/]
DEFINE_METHOD=method GREP[PRIVATE_METHODs[],/^de/]
P=GREP[PRIVATE_METHODs[],/^[o-r]\z/]
DEFINE_METHOD[P]{|x|}
PUTC[34]
PUTC[34]
PUTC[34]
PUTC[10]
```
[Try it online!](https://tio.run/##KypNqvz/v0AhtSwxR0PFRq8oNTFFr6RIPTg5raCsUs/KPkZdSdUmQUNdR0Vf8/9/9yDXAAVbhZzE3KSURIWUfIWaHJ2iGi4FhUxbAyBZnpGZk6qQE50Zq1hXBJQGCgGltG0NgYzUvBQgCZLjAjEDgjzDHENc431dQzz8XYptc1NLMvJTFEAWREPYxTr6cdH5uoWxRZn6sVwBoSHOKIrQDIiO1dEHqi6KLS2JTtJNiQVqcXF18/SDKSCkNy4lFWSLLU55sOExVejmRgfEVtdU1NSCHRhtbBKLi2FoEAsA "Ruby – Try It Online")
[Answer]
# [R](https://www.r-project.org/), [Robin Ryder](https://codegolf.stackexchange.com/a/214226/67312)
```
function(x,y,z){if(length(ls(1))>1|length(ls())!=3)return("S");LETTERS[lengths(lapply(y,intToUtf8(x),z))*lengths(lapply(y,intToUtf8(x+32),z))]}
```
[Try it online!](https://tio.run/##K/qfpmCr8D@tNC@5JDM/T6NCp1KnSrM6M00jJzUvvSRDI6dYw1BT086wBsHX1FS0NdYsSi0pLcrTUApW0rT2cQ0JcQ0KjoaoKdbISSwoyKnUqNTJzCsJyQ8tSbPQqNAEmquphU@FtrERWFFs7f80DUsTHUMdQyszzf8A "R – Try It Online")
The password is pretty insecure: `94,(numeric vector of length 1),(numeric vector of length 6)`. In particular, `94,1,1:6` was what I used.
The first thing I did was note that the `lengths` have to multiply to `18`, so we need to generate two lists such that the `lengths` are equal to `1,18`,`2,9`,or `3,6`.
Next, noting the `intToUtf8(x)` and `intToUtf8(x+32)` I found all pairs of functions that satisfy that condition with [this script](https://tio.run/##K/r/v0LBRlchsaAovyC/WENJT1tJJzc/JdVWKa00L7kkMz9PSZOrEqQkJ7GgIKdSo0KntCTNIiTfM69Ek6sKSaJSJ0E7QcfYSJOrHCRaDBGt0snMKwnJDwXq0eTiqoguV83MU62I5SqHsf7/BwA). I safely ruled out `nrow` and `ncol` since they would generate the same values, and the `lengths` must be distinct.
After that it was a matter of just trying things out; `lapply` always returns a `list` with length equal to the length of its first argument, so `y` had to be of length `1`. Luckily, R recycles, so `lapply(1,"^",1:6)==list(1^(1:6))`, which has `lengths` equal to `6`.
Finally, `~`, the `formula` builder is very odd, `x ~ y` is a `formula` with length `3`, with three elements, `'~'()`, `x()`, and `y()`, so `lapply(1,"~",1:6` is the same as `1 ~ 1:6` which is also length `3`.
[Answer]
# [Python 3](https://docs.python.org/3/), breaks [pxeger's challenge](https://codegolf.stackexchange.com/a/226206/94093)
```
__builtins__
SyntaxError
__build_class__
```
[Try it online!](https://tio.run/##K6gsycjPM/7/39M2M6@gtIQrwrYssahYA0xoRntqaMZqckWAaVsIxZWck1hcrOBpZahv8P9/fHxSaWZOSWZecXw8V3BlXklihWtRUX4RF0QiJR6sOj4eAA "Python 3 – Try It Online")
The first line loads the dictionary of Python's builtins.
Then, we assign `__build_class__` to `SyntaxError`. Why? Because `__build_class__` is called like so
```
__build_class__(<class_body>, "class_name")
```
While `SyntaxError` is called like so
```
SyntaxError("msg", (filename, lineno, offset, line))
```
When Python tries to call `SyntaxError` as if it were `__build_class__`, it tries to index the class name as a tuple.
] |
[Question]
[
A lottery company wants to generate a random lottery ticket number of length 10 characters.
Write a code in any language to create such a number in which every digit comes only once for example `9354716208` in this number all integers from 0 to 9 comes only once. This number should be a random number.
* The generated number should be shown on screen.
* It must be able to generate all permutations of all allowable characters.
* The code is required to be as small as possible (in bytes).
[Answer]
## J (4 bytes)
Couldn't resist.
```
?~10
```
In J, if `F` is dyadic , `F~ x` is the same as `x F x`.
[Answer]
### J, 5 characters and APL, 8 characters
**J**
```
10?10
```
J has the built-in deal operator (`?`). Thus, we can take 10 out of 10 (`10?10`).
**APL**
```
1-⍨10?10
```
APL has the same operator which unfortunately starts with one instead of zero. We are therefore subtracting one from each number (`1-⍨X` means `X-1` due to the commute operator).
[Answer]
**Python 2.7 (~~64~~ ~~63~~ 57)**
Not a chance here compared to the operator heavy languages and due to the lack of default loaded random :) This is the shortest I could come up with;
```
from random import*
print''.join(sample("0123456789",10))
```
It creates a range and samples 10 numbers from it without replacement.
(Thanks to @xfix for the shorter import format fix and @blkknght for pointing out my somewhat über complicated sampling range)
**Python 2.7 (40)**
If you run it from the interactive prompt and can read comma separated, you can shave it to 40, but it feels a bit like breaking the spirit of the rules;
```
from random import*
sample(range(10),10)
```
[Answer]
**PHP, 29 chars**
`<?=str_shuffle('0123456789');`
With PHP, the closing tag isn't required. But if that's against the rules, then you can replace ; with ?> for 1 net increase.
[Answer]
## Ruby, 18
Run this in `irb`:
```
[*0..9].shuffle*''
```
If you want this to be a stand-alone program, with output to `stdout` (the rules don't seem to *require* this), then add these 4 chars at the start:
```
$><<
```
[Answer]
# PHP - 37 Characters
```
<?=join('',array_rand(range(0,9),10))
```
I had an 18-character solution that should theoretically work but PHP is weird.
Or, if you want an xkcd answer:
```
<?="5398421706" // Chosen by program above; guaranteed to be random ?>
```
EDIT: Thanks xfix, it's now 5 characters shorter and complete.
EDIT AGAIN: [Live example](http://codepad.org/gA8lIBWT).
[Answer]
# Perl 6 (~~18~~ 16 characters)
```
print pick *,^10
```
This generates array containing all random elements (`pick *`) from `0` to `9` and outputs the result (`print`).
Sample output:
```
$ perl6 -e 'print pick *,^10'
4801537269
$ perl6 -e 'print pick *,^10'
1970384265
$ perl6 -e 'print pick *,^10'
3571684902
```
[Answer]
### GolfScript, 12 characters
```
10,{;9rand}$
```
Simply generates the list of digits (`10,`) and sorts it `{...}$` according to some random keys - which yields a random order of the digits.
Examples (try [online](http://golfscript.apphb.com/?c=MTAsezs5cmFuZH0k&run=true)):
```
4860972315
0137462985
```
[Answer]
## R (23 characters)
```
cat(sample(0:9),sep="")
```
Sample output:
```
> cat(sample(0:9),sep="")
3570984216
> cat(sample(0:9),sep="")
3820791654
> cat(sample(0:9),sep="")
0548697132
```
[Answer]
## TI-BASIC, 5 bytes
```
randIntNoRep(1,10
```
[Answer]
**Octave (14)**
```
randperm(10)-1
```
`randperm` unfortunately creates a selection from 1..n, so have to subtract 1 at the end to get 0-9.
[Answer]
# In sql server
```
DECLARE @RandomNo varchar(10)
SET @RandomNo = ''
;WITH num as (
SELECT 0 AS [number]
Union
select 1
Union
select 2
Union
select 3
Union
select 4
Union
select 5
Union
select 6
Union
select 7
Union
select 8
Union
select 9
)
SELECT Top 9 @RandomNo = COALESCE(@RandomNo + '', '') + cast(n.number AS varchar(1))
FROM numbers n
ORDER BY NEWID()
SELECT cast(@RandomNo AS numeric(10,0))
```
# [See Demo](http://www.sqlfiddle.com/#!6/d41d8/13548)
OR something similar (courtesy of @manatwork) using recursion and xml.
```
with c as(select 0i union all select i+1from c where i<9)select i+0from c order by newid()for xml path('')
```
[Answer]
# Javascript (~~79~~ ~~78~~ 68 characters)
Rather than creating an array with the numbers 0-9 and sorting it, I decided to generate random numbers. When it came up with a number that was not already in the array then added it. This repeats ten times and then alerts the output.
`for(a="";!a[9];){~a.indexOf(b=~~(Math.random()*10))||(a+=b)}alert(a)`
[Answer]
## Mathematica, 27
```
Row@RandomSample@Range[0,9]
```

[Answer]
## Shell/Coreutils, 23
```
shuf -i0-9|paste -sd ''
```
[Answer]
## JavaScript, 82 characters
**EDIT:** Thanks to [Rob W](https://codegolf.stackexchange.com/users/13882/rob-w), code length is reduced to 90 characters.
**EDIT:** Thanks to [George Reith](https://codegolf.stackexchange.com/users/11182/george-reith), code length is reduced to 82 characters (using for loop).
Pretty straightforward way: pick random element of `[0,1,2,3,4,5,6,7,8,9]` array and append it to the output, then reduce array and replay.
*Old version (106 characters):*
```
a=[0,1,2,3,4,5,6,7,8,9],l=11,t="";while(--l){r=Math.floor(Math.random()*l);t+=a[r];a.splice(r,1);}alert(t)
```
Readable version:
```
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], l = 10,t = "";
while(l--) {
r = Math.floor(Math.random() * l);
t += a[r];
a.splice(r, 1);
}
alert(t);
```
*Better version (90 characters):*
```
a="0123456789".split(t=""),l=11;while(--l)t+=a[r=0|Math.random()*l],a.splice(r,1);alert(t)
```
*Last version (82 characters):*
```
a="0123456789".split(t='');for(l=11;--l;t+=a.splice(0|Math.random()*l,1));alert(t)
```
JSFiddle: <http://jsfiddle.net/gthacoder/qH3t9/>.
[Answer]
# C#, 145 bytes
## Ungolfed
```
using System;
using System.Linq;
class P
{
static void Main()
{
Enumerable.Range(0,10).OrderBy(g => Guid.NewGuid()).ToList().ForEach(Console.Write);
}
}
```
## Golfed
```
using System;using System.Linq;class P{static void Main(){Enumerable.Range(0,10).OrderBy(g => Guid.NewGuid()).ToList().ForEach(Console.Write);}}
```
[Answer]
# Mathematica 40
The number is created as a string so as to allow zero to be displayed as the first character, when needed.
```
""<>RandomSample["0"~CharacterRange~"9"]
```
**Output examples**
>
> "0568497231"
>
> "6813029574"
>
>
>
**Explanation**
`"0"~CharacterRange~"9"` is infix notation for `CharacterRange["0","9"]`.
Either of these returns the list, `{"0","1","2","3","4","5","6","7","8","9"}`.
`RandomSample[list]` by default returns a permutation of the list. (It can also be used for other kinds of sampling, when parameters are included. E.g. `RandomSample[list, 4]` will return a Random sample of 4 characters, with no repeats.
[Answer]
## K/Kona (6)
```
-10?10
```
As with J, `?` is the deal operator; the `-` forces the values to not repeat.
[Answer]
## Scala, 37
```
util.Random.shuffle(0 to 9).mkString
```
[Answer]
## JavaScript (80 characters)
```
alert("0123456789".split("").sort(function(){return .5-Math.random()}).join(""))
```
JS-Fiddle: <http://jsfiddle.net/IQAndreas/3rmza/>
[Answer]
## Forth, 72
```
needs random.fs : r ': '0 do i loop 9 for i 1+ random roll emit next ; r
```
Room still to golf, maybe, but Forth made this one hard. I think.
[Answer]
# Prolog, 177/302 characters
I'm a beginner on Prolog, so probably this is not the most condensed code.
```
:- use_module(library(clpfd)).
sort(N) :-
N = [N0,N1,N2,N3,N4,N5,N6,N7,N8,N9],
domain([N0],1,9),
domain([N1,N2,N3,N4,N5,N6,N7,N8,N9],0,9),
all_different(N),
labeling([],N).
```
Returns:
```
| ?- sort2(N).
N = [1,0,2,3,4,5,6,7,8,9] ? ;
N = [1,0,2,3,4,5,6,7,9,8] ? ;
N = [1,0,2,3,4,5,6,8,7,9] ? ;
N = [1,0,2,3,4,5,6,8,9,7] ? ;
N = [1,0,2,3,4,5,6,9,7,8] ?
yes
```
If you want it to return an integer:
```
:- use_module(library(clpfd)).
sort(M) :-
N = [N0,N1,N2,N3,N4,N5,N6,N7,N8,N9],
domain([N0],1,9),
domain([N1,N2,N3,N4,N5,N6,N7,N8,N9],0,9),
all_different(N),
labeling([],N),
M is (N0*1000000000)+(N1*100000000)+(N2*10000000)+(N3*1000000)+
(N4*100000)+(N5*10000)+(N6*1000)+(N7*100)+(N8*10)+N9.
```
Returns:
```
| ?- sort(N).
N = 1023456789 ? ;
N = 1023456798 ? ;
N = 1023456879 ? ;
N = 1023456897 ? ;
N = 1023456978 ?
yes
```
Using instead:
```
labeling([down],N)
```
Gives the numbers in the opposite order:
```
| ?- sort(N).
N = 9876543210 ? n
N = 9876543201 ? n
N = 9876543120 ? n
N = 9876543102 ? n
N = 9876543021 ?
yes
```
Unlike some other codes posted, this returns all possibilities (with no repetitions).
[Answer]
# [q/kdb](http://en.wikipedia.org/wiki/Q_%28programming_language_from_Kx_Systems%29) [6 chars]
```
-10?10
```
will generate 10 unique random numbers.
[Answer]
# [√ å ı ¥ ® Ï Ø ¿](https://github.com/ValyrioCode/Valyrio) , 4 bytes
```
XrśO
X › Push 10 to the stack
r › Push the range from [1...10]
ś › Shuffle the stack
O › Output the whole stack separated by spaces
```
[Answer]
**Clojure, 42**
```
(println (apply str (shuffle (range 10))))
```
>
> 6209847315
>
>
>
[Answer]
# Javascript, 83 characters
```
a=[];while(!a[9]){b=Math.floor(Math.random()*10);!a.includes(b)&&a.push(b)}alert(a)
```
While running until array has 10 elements.
Generating random number from 0 - 9 then check if array !includes this number and add it to the array.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 4 bytes
```
kdÞ℅
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwia2TDnuKEhSIsIiIsIiJd)
Explanation:
```
kd # Digits `0123456789`
Þ℅ # Random permutation
# 's' flag - Print the sum of the top of the stack
```
[Answer]
This is not much smaller than JMK's answer, but here's a slightly smaller C# solution (135):
```
using System;
using System.Linq;
class P {
static void Main()
{
Console.Write(string.Join("", "0123456789".OrderBy(g => Guid.NewGuid())));
}
}
```
Compacted (134):
```
using System;using System.Linq;class P{static void Main(){Console.Write(string.Join("", "0123456789".OrderBy(g => Guid.NewGuid())));}}
```
Alternate version (135):
```
using System;
using System.Linq;
class P {
static void Main()
{
"0123456789".OrderBy(g => Guid.NewGuid()).ToList().ForEach(Console.Write);
}
}
```
Compacted:
```
using System;using System.Linq;class P{static void Main(){"0123456789".OrderBy(g => Guid.NewGuid()).ToList().ForEach(Console.Write);}}
```
They're equal in length, but it really just depends on whether you want to use Linq's ForEach function or String's Join function. I was able to remove 10 characters in length by spelling out the range "0123456789" in a string instead of using Enumerable.Range(0, 10).
[Answer]
**LOGO**, 64 characters
```
make "d 1234567890
repeat 10 [
make "n pick d
show n
make "d butmember n d
]
```
**pick** returns random item of the supplied list.
**butmember** returns list with all occurrences of the specified item removed.
*Note: Not all Logo implementations support `butmember` command.*
] |
[Question]
[
**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/100663/edit).
Closed 7 years ago.
[Improve this question](/posts/100663/edit)
Let's take a look on a typical loop, which usually performs 8 iterations:
```
for (int x=0; x<8; ++x);
```
You have to make it infinite!
---
It's a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'") for all languages that support such form of `for` loop. So solution with highest score (upvotes minus downvotes) wins.
If your language has the other form of `for` loop, but you are sure, you can make something cool with it, feel free to post the answer and mark it as noncompeting. I reserve the right to enlarge scope of available constructions and languages, but it will never be shrinked, so don't be afraid of dropping previously correct solutions.
---
# What is solution?
Solution consists of *two programs.*
The first program is a *clean* program. It's the typical program in your language with the `for` loop making 8 iterations. It should be the normal program, any developer could write. No any special hacks for preparation purposes. For example:
```
int main()
{
for (int x=0; x<8; ++x);
return 0;
}
```
The second program is *augmented.* This program should contain all the code from clean program and some additional code. There are limited number of *extension points,* see complete rules section for details. An augmented program for the clean one above can be
```
inline bool operator < (const int &a, const int &b)
{
return true;
}
int main()
{
for (int x=0; x<8; ++x);
return 0;
}
```
That's just an example (noncompilable in C++) to show an idea. The real correct augmented program have to be compilable, working and having infinite loop.
# Complete rules
### Both programs:
* Any language with support of such `for` loops is ok.
* The loop body has to be empty. More precisely, you can place some output or other code into the loop, but loop behavior should be the same in case of empty loop.
### Clean program:
* Loop uses integer or numeric counter and performs 8 iterations:
```
for (int x=0; x<8; ++x); // C, C++, C#
for (var x=0; x<8; ++x); // C#, Javascript
for (auto x=0; x<8; ++x); // C, C++
for (auto signed x=0; x<8; ++x); // C, C++
for (register int x=0; x<8; ++x); // C, C++
```
* User-defined types are disallowed.
* Using of property (except of global variable) instead of loop variable is disallowed.
* Declaration of variable can be inside or outside of the loop. Following code is ok:
```
int x;
for(x=0; x<8; ++x);
```
* Either prefix or postfix increment can be used.
* Loop limit `8` should be written as a constant literal without saving to named constant or variable. It's made to prevent solutions based on declaring variable or constant equal to 8, and then reassigning, overriding or shadowing it by the other value:
```
const double n = 8;
int main()
{
const double n = 9007199254740992;
for (double x=0; x<n; ++x);
return 0;
}
```
### Augmented program:
* Must contain all the code from the clean one.
* Should extend clean program in limited number of extension points.
* Must execute *same* `for` loop as an infinite loop itself.
Placing of the loop into another infinite construction is not ok.
* Runtime or compile-time patching of the code is allowed as long as textual representation of it is unchanged.
* Placing the construction into a string and passing to `eval` is disallowed.
### Extension points:
* Anywhere outside of the fragment with clean code, including other files or other assemblies.
* `for` statement (as single piece - `for` construction and its body) must be kept unchanged.
* Variable declaration must be kept the same.
* Any place between simple statements can be used as extension point.
* If and only if variable was declared outside of the loop and without immediate assignment of the value, such assignment can be added.
```
/* extension point here */
int main()
/* extension point here */
{
/* extension point here */
int x /* extension point for assignment here */;
/* extension point here */
for (x=0; x<8; ++x);
/* extension point here */
return 0;
/* extension point here */
}
/* extension point here */
```
```
int main()
{
/* BEGIN: No changes allowed */ int x = 0; /* END */
/* extension point here */
/* BEGIN: No changes allowed */ for (x=0; x<8; ++x); /* END */
return 0;
}
```
PS: If possible, please provide a link to online IDE.
[Answer]
# Python3
### Clean Program:
This is just a standard countdown while loop.
```
n = 8
while n != 0:
n -= 1
print("done")
```
### Augmented Program:
```
import ctypes
ctypes.cast(id(8), ctypes.POINTER(ctypes.c_int))[6] = 9
n = 8
while n != 0:
n -= 1
print("done")
```
It uses the int cache to redefine `8` as `9` which effectively makes the `n -= 1` a no-op, since `9-1 = 8` which just sets `n` back to `9` again, causing the infinite loop.
You can see the int cache in action online [here](http://repl.it/E4fx/0) (though obviously without the infinite loop cuz its online).
[Answer]
# Python 3
**Clean Program:**
The standard way to do something 8 times in python is:
```
for i in range(8):
# Do something
pass
```
**Augmented Program:**
However, if we override the range generator function to infinitely yield 1, it becomes an infinite loop...
```
def range(x):
while 1: yield 1
for i in range(8):
# Infinite loop
pass
```
We can take this further and create a generator function which, rather than infinitely yielding 1, counts up forever:
```
def range(x):
i = 0
while 1: yield i; i+=1
for i in range(8):
# Counting from 0 to infinity
pass
```
[**Test on repl.it**](https://repl.it/E4gu)
[Answer]
# Perl
**Clean**
```
for($i=0; $i<8; $i++) { }
```
**Augmented**
```
*i=*|;
for($i=0; $i<8; $i++) { }
```
[Ideone](http://ideone.com/VrplTE).
[Answer]
# ES5+ (Javascript)
*EDIT*: Removed explicit variable declaration, as otherwise it was hoisted and a non-configurable *window.x* property was created (unless run line by line in the REPL console).
Explanation:
Makes advantage of the fact that any globally scoped variable is also a property of the *window* object, and redefines "window.x" property to have a constant value of 1.
**Clean**
```
for(x=0; x<8; x+=1) console.log(x);
```
**Augmented**
```
Object.defineProperty(window,'x',{value:1});
for(x=0; x<8; x+=1) console.log(x);
```
*NOTE*: To make this work in Node.js, just replace *"window"* with *"global"* (tested in Node.js 6.8.0)
[Answer]
## C
**Clean program**
```
int main()
{
for (int x=0; x<8; ++x);
return 0;
}
```
**Augmented program**
```
#define for(ever) while(1)
int main()
{
for (int x=0; x<8; ++x);
return 0;
}
```
[Answer]
# Java
**Clean program:**
```
public class Main {
public static void main(String[] args) throws Exception {
for (Integer i = 0; i < 8; i++);
}
}
```
**Augmented program:**
```
import java.lang.reflect.Field;
public class Main {
public static void main(String[] args) throws Exception {
Class cache = Integer.class.getDeclaredClasses()[0];
Field c = cache.getDeclaredField("cache");
c.setAccessible(true);
Integer[] intcache = (Integer[]) c.get(cache);
intcache[129] = intcache[128];
for (Integer i = 0; i < 8; i++);
}
}
```
Sets the Integer in the Integer cache that should contain 1 to 0, effectively making `i++` do nothing (it sets `i` to the cached Integer that should contain 1, but since that Integer actually contains 0, nothing changes).
[Answer]
# C++
```
int main()
{
#define int bool
for (int x=0; x<8; ++x);
return 0;
}
```
`bool` can only be 0 or 1. Inspired by primo's [Perl answer](https://codegolf.stackexchange.com/a/101094/53667).
[Answer]
## Python 3 (3.5.0)
**Clean Program:**
```
for i in range(8):
print(i)
```
**Augmented**
```
import sys
from ctypes import *
code = sys._getframe().f_code.co_code
cast(sys._getframe().f_code.co_code, POINTER(c_char*len(code))).contents[len(code)-4] = 113
cast(sys._getframe().f_code.co_code, POINTER(c_char*len(code))).contents[len(code)-3] = 160
for i in range(8):
print(i)
```
This solution is unlike the others written in Python in that it actually changes the source code on the fly. All the stuff in the for loop can be changed to whatever code is wanted.
The code changes the second to last opcode to be `113` or more readably - `JUMP_ABSOLUTE`. It changes the operand to `160` - the instruction where the for loop begins, in effect creating a GOTO statement at the end of the program.
The augmented program prints the numbers `0..7` infinitely many times without stack-overflowing or similar.
[Answer]
# PHP
I think this is following the extension point rules; I'm not totally clear on point 4. It's very similar to @primo's perl answer so I think it counts.
**Clean**
```
for(;$i<8;$i++);
```
**Augmented**
```
$i='a';
for(;$i<8;$i++);
```
PHP lets you increment certain strings, like so:
```
'a' -> 'b'
'b' -> 'c'
'z' -> 'aa'
'aa' -> 'ab'
'aab' -> 'aac'
etc
```
All of these strings evaluate to 0, so this will loop practically forever (barring somehow running out of memory).
[Answer]
# Perl
## Clean code
```
for ($x = 0; $x < 8; $x++) {}
```
## Augmented code
```
sub TIESCALAR {bless []}
sub FETCH {}
sub STORE {}
tie $x, "";
for ($x = 0; $x < 8; $x++) {}
```
Most Perl variables are just variables. However, the language also has a `tie` feature, which allows you to effectively give variables getters and setters. In this program, I make the main package (whose name is the null string) into the equivalent of a class from an object-oriented language, whilst also having it be a program. That allows me to tie the `for` loop counter to the program itself. Implementing `TIESCALAR` allows `tie` to succeed; the return value of `TIESCALAR` is meant to be a reference to any internal state we need to keep around associated with the variable, but because we don't need any, we return an empty array reference as a placeholder. We then give the simplest possible implementations of the getter and setter; neither of them do anything, so attempts to assign to `$x` have no effect, and attempts to read it always return `undef`, which is numerically less than 8.
[Answer]
# WinDbg
### Clean
```
.for (r$t0 = 0; @$t0 < 8; r$t0 = @$t0 + 1) { }
```
### Augmented
```
aS < |; * Create alias of < as |
.block { * Explicit block so aliases are expanded
.for (r$t0 = 0; @$t0 < 8; r$t0 = @$t0 + 1) { } * Condition is now @$t0 | 8, always true
}
```
This approach creates an alias for `<` as `|`, so when `<` is encountered in the code the alias is expanded to `|` and bitwise-or is done instead of less-than. In WinDbg all non-zero values are truthy so `anything | 8` is always true.
Note: The `.block` is not actually needed if the `aS` and `.for` are actually entered as two different lines as shown here, it's only required when the `aS` and `.for` are on the same line.
[Answer]
# Mathematica
## Clean
```
For[x = 0, x < 8, ++x,]
```
## Augmented
```
x /: (x = 0) := x = -Infinity;
For[x = 0, x < 8, ++x,]
```
[Answer]
## Common Lisp
### Clean code
```
(dotimes(i 8))
```
### Augmented
```
(shadowing-import(defmacro :dotimes(&rest args)'(loop)))
(dotimes(i 8))
```
A macro named `keyword:dotimes`, a.k.a. `:dotimes` (see [11.1.2.3 The KEYWORD Package](http://www.lispworks.com/documentation/HyperSpec/Body/11_abc.htm)) is defined which expands as an infinite loop. The [`defmacro`](http://clhs.lisp.se/Body/m_defmac.htm) macro returns the name of the macro being defined, which can be fed to [`shadowing-import`](http://clhs.lisp.se/Body/f_shdw_i.htm). Thus, this new `dotimes` symbols shadows the standard one (which should not be redefined or lexically bound to another macro in portable programs).
### Augmented (2)
```
(set-macro-character #\8 (lambda (&rest args) '(loop)))
(dotimes(i 8))
```
When we read character 8, we replace it by `(loop)`. That means that the above reads as `(dotimes (i (loop)))` and so the code never terminates computating the upper-bound. This impacts all occurrences of 8, not only the one in the loop.
**In other words, 8 really stands for infinity.**
If you are curious, when the readtable is modified like above, then character 8 becomes "terminating", and detaches itself from other numbers/symbols currently being read:
```
(list 6789)
```
... reads as:
```
(list 67 (loop) 9)
```
You can run tests on Ideone: <https://ideone.com/sR3AiU>.
[Answer]
# Ruby
## Clean
This sort of for loop is not much used in Ruby, but a typical tutorial will tell you that this is the way to go about it:
```
for x in 1..8
# Some code here
end
```
# Augmented
The for loop just calls `(1..8).each` with the given block of code, so we change that method:
```
class Range
def each
i = first
loop { yield i; i+= 1 }
end
end
for x in 1..8
# Some code here
end
```
[Answer]
# Haskell
## Clean version:
```
import Control.Monad (forM_)
main = forM_ [0..8] $ \i -> print i
```
Augmented version:
```
import Control.Monad (forM_)
data T = C
instance Num T where
fromInteger _ = C
instance Enum T where
enumFromTo _ _ = repeat C
instance Show T where
show _ = "0"
default (T)
main = forM_ [0..8] $ \i -> print i
```
It's quite basic, really: we just define our own type `T` such that its `enumFromTo` instance is an infinite sequence, then use type defaulting so that the un-type-annotated values `0` and `8` are taken as type `T`.
[Answer]
# ///
*There are no explicit `for` loops in ///, but can be simulated (it's turing complete after all).*
## Clean:
```
/1/0/
/2/1/
/3/2/
/4/3/
/5/4/
/6/5/
/7/6/
/8/7/
8
```
## Augmented:
```
/0/0/
/1/0/
/2/1/
/3/2/
/4/3/
/5/4/
/6/5/
/7/6/
/8/7/
8
```
What's going on?
While the former program counts down from 8 to 0, the latter one's `/0/0/` rule will replace `0` by `0` until eternity.
[Answer]
# Javascript ES6
OK, here's a version that works using the ES6 for...of loop construct. I'll even give you a clean array so that we're sure there's no funny business:
### Clean
```
for(a of [0,1,2,3,4,5,6,7]);
```
Of course, that doesn't stop someone from messing with the Array prototype...
### Augmented
```
Array.prototype[Symbol.iterator]=function(){return {next: function(){return {done: false}}}}
for(a of [0,1,2,3,4,5,6,7]);
```
This works by over-writing the default iterator so that it never terminates, therefore locking everything into an infinite loop. The code doesn't even have a chance to run the stuff inside the loop.
[Answer]
# C++
Uses 2 extension points:
```
struct True {
True(int x){}
bool operator<(const int&){
return true;
}
void operator++(){}
};
int main()
{
#define int True
for (int x=0; x<8; ++x);
return 0;
}
```
Clean program is same as in the description.
[Answer]
# Brainfuck
I print a '0' each iteration, just to make it easy to count iterations. But any code could be inserted there without changing how the loop works.
## Clean
```
>> ++++++ [-<++++++++>] << b = '0' (value to be printed each iteration)
>> ++++++++ [-<< ++++++++ ++++++++ >>] << for (a = a plus 128;
[ a;
++++++++ ++++++++ a = a plus 16 (mod 256)) {
>.< loop body (print b)
] }
```
[Try it online](http://brainfuck.tryitonline.net/#code=Pj4gKysrKysrIFstPCsrKysrKysrPl0gPDwgICAgICAgICAgICAgICAgICAgYiA9ICcwJyAodmFsdWUgdG8gYmUgcHJpbnRlZCBlYWNoIGl0ZXJhdGlvbikKCj4-ICsrKysrKysrIFstPDwgKysrKysrKysgKysrKysrKysgPj5dIDw8ICAgIGZvciAoYSA9IDEyODsKWyAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBhOworKysrKysrKyArKysrKysrKyAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIGEgPSBhIHBsdXMgMTYgKG1vZCAyNTYpKSB7Cj4uPCAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBsb29wIGJvZHkgKHByaW50cyBiKQpdICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICB9Cg&input=&args=)
The augmented version relies on the common Brainfuck implementation with 8 bit cells. On these implementations, "increment" is actually "increment (mod 256)". Thus to find a loop that will iterate exactly 8 times in the clean version and endlessly in the augmented version, we can simply find a solution to the following system of inequalities.
* a + b\*8 (mod 256) == 0 (for clean version)
* c + a + b\*n (mod 256) > 0 for all n (for augmented version)
* a > 0
In this case, we let a = 128, b = 16, and c = 1. Obviously 128 + 16 \* 8 = 256 (and 256 (mod 256) = 0) and 128 > 0, and since b is even, c + a + b \* n is odd for any odd a + c, and thus will never be an even multiple of 256 in such cases. We select c = 1 for simplicity's sake. Thus the only change we need is a single `+` at the beginning of the program.
## Augmented
```
+ increment a (only change)
>> ++++++ [-<++++++++>] << b = '0' (value to be printed each iteration)
>> ++++++++ [-<< ++++++++ ++++++++ >>] << for (a = a plus 128;
[ a;
++++++++ ++++++++ a = a plus 16 (mod 256)) {
>.< loop body (print b)
] }
```
[Try it online](http://brainfuck.tryitonline.net/#code=Kwo-PiArKysrKysgWy08KysrKysrKys-XSA8PCAgICAgICAgICAgICAgICAgICBiID0gJzAnICh2YWx1ZSB0byBiZSBwcmludGVkIGVhY2ggaXRlcmF0aW9uKQoKPj4gKysrKysrKysgWy08PCArKysrKysrKyArKysrKysrKyA-Pl0gPDwgICAgZm9yIChhID0gMTI4OwpbICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIGE7CisrKysrKysrICsrKysrKysrICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgYSA9IGEgcGx1cyAxNiAobW9kIDI1NikpIHsKPi48ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIGxvb3AgYm9keSAocHJpbnRzIGIpCl0gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIH0K&input=&args=)
I leave it to the OP to determine if this entry is competing. Brainfuck doesn't have an explicit for loop, but the loop form I used is as close as you're likely to get. `++++++++` is also as close to a literal `8` as you can get; I've included quite a few of those.
The clean version almost certainly constitutes a typical program written in this language, as even the [shortest known Brainfuck Hello World](https://codegolf.stackexchange.com/a/68494/44809) depends on a modular recurrence relation to work.
[Answer]
# Haskell
## Clean
```
import Control.Monad (forM_)
main = forM_ [0..8] $ \i -> print i
```
## Augmented
```
import Control.Monad (forM_)
import Prelude hiding (($))
import Control.Monad (when)
f $ x = f (\i -> x i >> when (i == 8) (f $ x))
main = forM_ [0..8] $ \i -> print i
```
Replaces the usual function application operator `$` with one that repeats the loop again every time it finishes. Running the clean version prints 0 to 8 and then stops; the augmented version prints 0 to 8 and then 0 to 8 again, and so on.
I cheat a little, in that `forM_ [0..8] $ \i -> print i` isn't necessarily the "cleanest" way to write that loop in Haskell; many Haskellers would eta-reduce the loop body to get `forM_ [0..8] print` and then there's no `$` to override. In my defense I copied the clean code from [Cactus' answer](https://codegolf.stackexchange.com/a/101432/36334), who didn't need that property, so at least one Haskell programmer actually wrote that code with no motivation to unnecessarily add the `$`!
[Answer]
# C++
```
int main()
{
int y;
#define int
#define x (y=7)
for (int x=0; x<8; ++x);
return 0;
}
```
Lets `x` evaluate to 7. Does not work in C because it requires an lvalue at assignement and increment.
[Answer]
# Nim
The idiomatic version, using `countup`:
### Clean
```
for i in countup(1, 8):
# counting from 1 to 8, inclusive
discard
```
### Augmented
```
iterator countup(a: int, b: int): int =
while true:
yield 8
for i in countup(1, 8):
# counting 8s forever
discard
```
Simple, and very similar to [the Python answer which redefines `range`](https://codegolf.stackexchange.com/a/100671/56755). We redefine `countup`, the idiomatic Nim way of iterating from one int (inclusive) to another, to give 8s infinitely.
The more interesting version, using the range operator `..`:
### Clean
```
for i in 1..8:
# counting from 1 to 8, inclusive
discard
```
### Augmented
```
iterator `..`(a: int, b: int): int =
while true:
yield 8
for i in 1..8:
# counting 8s forever
discard
```
Very similar to the previous solution, except we redefine the range operator `..`, which normally would give an array `[1, 2, 3, 4, 5, 6, 7, 8]`, to the iterator from before.
[Answer]
# GolfScript
## Clean
```
0{.8<}{)}while;
```
## Augmented
```
{.)}:8;
0{.8<}{)}while;
```
It assigns the function returning n+1 to the variable 8
[Answer]
# tcl
Normal:
```
for {set i 0} {$i<8} {incr i} {}
```
Augmented:
```
proc incr x {}
for {set i 0} {$i<8} {incr i} {}
```
The idea is to redefine the `incr` command that is used to increment the variable `i`, to actually not increment!
Can be tested on: <http://rextester.com/live/QSKZPQ49822>
[Answer]
# x86\_64 Assembly
Clean program:
```
mov rcx, 8
loop_start:
sub rcx, 1
cmp rcx,0
jne loop_start
mov rax, 0x01
mov rdi, 0
syscall
```
The sort of loop any Assembly programmer would use, followed by an exit syscall so as not to enable adding a `jmp loop_start` instruction afterwards.
Augmented program:
```
global start
section .text
start:
mov rcx, -1
jmp loop_start
mov rcx, 8
loop_start:
sub rcx, 1
cmp rcx,0
jne loop_start
mov rax, 0x01
mov rdi, 0
syscall
```
Also, sorry if it's bad that the clean program doesn't have an entrypoint or a `section .text`
[Answer]
# JavaScript
## Clean:
```
for (var i = 0; !(i > Math.PI * 2.5); i++);
```
## Augmented:
```
window.Math = {PI: NaN};
for (var i = 0; !(i > Math.PI * 2.5); i++);
```
[Answer]
# C++
## Clean Program
A nice, normal loop, iterating from numbers 0 to 7.
```
#include <iostream>
int main() {
for (short i = 0; i < 8; i++) {
// Print `i` with a newline.
std::cout << i << std::endl;
}
}
```
## Augmented Program
The preprocessor of C++ is quite a dangerous feature...
```
#include <iostream>
#define short bool
int main() {
for (short i = 0; i < 8; i++) {
// Print `i` with a newline.
std::cout << i << std::endl;
}
}
```
The only line we had to add was `#define short bool`. This makes `i` a boolean instead of a short integer, and so the increment operator (`i++`) does nothing after `i` reaches 1. The output then looks like this:
```
0
1
1
1
1
1
...
```
] |
[Question]
[
[Robbers Thread](https://codegolf.stackexchange.com/questions/231410/which-character-to-change-robbers)
Cops, your task is to chose a program that prints a string (you can choose).
Although, if you change 1 character in your code, it should print another string.
But there's a twist: You should make your code hard to read, so that the robbers can't find your "changeable" character.
The winner cop is the user, with the shortest answer that wasn't cracked for a week.
If your submission wasn't cracked for a week, please reveal your character.
Cops, please include the output that should be printed if that specific character is changed in your code.
I will declare the winner cop and robber a week after this challenge is posted.
### Example submission (very easy to understand)
```
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes, prints a and b
1[`a`|`b
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=1%5B%60a%60%7C%60b&inputs=&header=&footer=)
```
[Answer]
# [Python 3](https://docs.python.org/3/), 51 bytes, [cracked by xnor](https://codegolf.stackexchange.com/a/231637/88546)
```
r=(1,)*8**9
r=r,len,
r=r,str,sum
print(len(str(r)))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v8hWw1BHU8tCS8uSq8i2SCcnNU8HzCguAeLSXK6Cosy8Eg2gsAZQRKNIU1Pz/38A "Python 3 – Try It Online")
The code outputs `402653253`. The changed code should instead output `134217728`.
I hope my `8**9` will make it difficult for any brute-force methods to work. Good luck!
[Answer]
# [Python 2](https://docs.python.org/2/), 23 bytes (cracked by [dingledooper](https://codegolf.stackexchange.com/a/231487/20260))
```
print min(0,0)>min(0,0)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EITczT8NAx0DTDsb4/x8A "Python 2 – Try It Online")
Should print `True`. Please don't brute force, I think it's a nice puzzle to solve.
---
**Bonus puzzle!**
**[Python 2](https://docs.python.org/2/), 23 bytes**
```
print min(0,0)<min(0,0)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EITczT8NAx0DTBsb4/x8A "Python 2 – Try It Online")
Should print `True`. Unfortunately this has an unintended solution of `print~min(0,0)<min(0,0)`, let's just pretend that doesn't exist.
[Answer]
# [R](https://www.r-project.org/), 54 bytes, [cracked by Dominic van Essen](https://codegolf.stackexchange.com/a/231442/86301)
```
a=b=c=2
for(a in 0:b)pi=pi+exists("c")/4
intToUtf8(pi)
```
[Try it online!](https://tio.run/##K/r/P9E2yTbZ1ogrLb9II1EhM0/BwCpJsyDTtiBTO7Uis7ikWEMpWUlT34QrM68kJD@0JM1CoyBT8/9/AA "R – Try It Online")
The string to output is `"R"`.
---
>
> The solution is to replace the first line with `a=b=co2`: [Try it online!](https://tio.run/##K/r/P9E2yTY534grLb9II1EhM0/BwCpJsyDTtiBTO7Uis7ikWEMpWUlT34QrM68kJD@0JM1CoyBT8/9/AA "R – Try It Online")
> The built-in dataset `co2` is then assigned to `a` and `b`. When calling `0:b`, only the first element of `co2` is kept (with a warning); it is worth `315.42`, which leads after the `for` loop to `pi=82.246`. This is rounded down to `82` by `intToUtf8`.
>
>
>
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes, [Cracked by pxeger](https://codegolf.stackexchange.com/questions/231410/which-character-to-change-robbers/231414#231414)
```
lyoal
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=lyoal&inputs=&header=&footer=)
Take two.
Should output `name 'this_function' is not defined` and nothing else.
May not work in future versions of Vyxal as this is a bug that must be destroyed.
My intended solution was `lyxal`, which rickrolls you but first outputs the intended text, as you can see in [this version](https://lyxal.pythonanywhere.com?flags=&code=lyxal%23&inputs=&header=&footer=), which adds a NOP.
I then realised `lyoax` works as well.
So yeah, interesting puzzle.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 6 bytes, [Cracked by Daniel H.](https://codegolf.stackexchange.com/a/231433/16766)
```
-PI-PI
```
[Try it online!](https://tio.run/##K8gs@P9fN8ATiP7/BwA "Pip – Try It Online")
Outputs `-6.283185307179586`. The cracked version should output `3.141592653589794`.
---
>
> `PI` is `3.141592653589793`
>
> `-PI` is `-3.141592653589793`
>
> `PZ-PI` is `-3.14159265358979397985356295141.3-` (palindromize)
>
> `-PZ-PI` is `3.141592653589794` (casts to float, rounds ...939 to ...94)
>
>
>
[Answer]
# [R](https://www.r-project.org/), 44 bytes, [cracked by Dominic van Essen](https://codegolf.stackexchange.com/a/231472/86301)
```
a=b=2
for(a in 0:b)pi=a+a-pi
el(LETTERS[pi])
```
[Try it online!](https://tio.run/##K/r/P9E2ydaIKy2/SCNRITNPwcAqSbMg0zZRO1G3IJMrNUfDxzUkxDUoOLogM1bz/38A "R – Try It Online")
The string to output is `"R"`.
This is (deliberately) similar to my [previous answer](https://codegolf.stackexchange.com/a/231427/86301), but the solution uses a different trick.
>
> The solution is to replace `0:b` with `0xb` in the `for` loop: [Try it online!](https://tio.run/##K/r/P9E2ydaIKy2/SCNRITNPwaAiSbMg0zZRO1G3IJMrNUfDxzUkxDUoOLogM1bz/38A "R – Try It Online").
> The number `Oxb` is 11 in hexadecimal. The loop is then just a single call for `a=11`, leading to `pi = 11+11-pi = 18.858...`, which gets rounded down to `18`. The 18th letter is `R`.
>
>
>
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `vKOJdaBoVWT`, 17 bytes (safe)
```
₀h`f⋏⋏`½\zd+∑⇧¨U²
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=vKOJdaBoVWT&code=%E2%82%80h%60f%E2%8B%8F%E2%8B%8F%60%C2%BD%5Czd%2B%E2%88%91%E2%87%A7%C2%A8U%C2%B2&inputs=&header=&footer=)
Solution should output `FFIZZBUZZIFIZZBUZZZFIZZBUZZZFIZZBUZZBFIZZBUZZUFIZZBUZZZFIZZBUZZZFIZZBUZZ`.
Intended Solution:
>
> `₀h`f⋏⋏`½\zd+∑⇧/U²`
>
>
>
> All of the flags are valid flags, but the only one that actually did anything important was the `d` flag, which does a deep sum of the top of the stack before printing.
>
>
>
> The main obfuscated part of the program, `₀h`f⋏⋏`½\zd+∑⇧`, simply makes the string `FIZZBUZZ`.
>
>
>
> When executed online, `¨U` does nothing, and then `²` splits the string, which is put back together by the flag.
>
>
>
> In the solution, `/` causes the string to be wrapped. As a result, `w` would have also worked. `U` uniquifies the list, which does nothing since there's only one element. Now, `²` is acting on a list instead of a string, so it multiplies the string by itself, which creates a list that is summed by the flag and printed.
>
>
>
[Answer]
# [Rattle](https://github.com/DRH001/Rattle), 5 bytes, [Cracked by Shaggy](https://codegolf.stackexchange.com/a/231440/58974)
```
d\|!p
```
[Try it Online!](https://www.drh001.com/rattle/?flags=&code=d%5C%7C!p&inputs=)
This program outputs the string `d`. With one character changed, it should output the exact string `['d', '']`
>
> Cracked version:
>
> `d&|!p`
>
> Explanation:
>
> In the original code, `d\` is the value of a variable and `!p` is the code. `!p` is a program which prints the value at the top of the stack after parsing any input and variables. In this code, `d\` gets parsed to `d` (in this case, `\` is null).
>
> In the cracked code, the program stays the same but the variable is `d&`. The `&` operator in the variable acts as a separator, so the variable gets parsed to a list containing `'d'` and `''` (the second value is a null string). Then, the program converts this list to a string and outputs it.
>
>
>
>
>
>
>
>
>
>
>
>
>
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes, [Cracked](https://codegolf.stackexchange.com/a/231412/100664) by [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy)
```
kaka[|←
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=kaka%5B%7C%E2%86%90&inputs=&header=&footer=)
Uses a quite obscure hack. Should print `z` if changed correctly.
Shaggy found exactly my intended solution - `kaka(|←`.
The 'obscure hack' I mentioned is Vyxal's 'ghost variable'. Vyxal's variables are referenced by `→name` and `←name`, but you can give one no name.
`(...)` is Vyxal's loop construct, but you can add a variable name with `(name|...)` and that variable will contain the current iteration. This also works with no name, so `(|...)` sets the ghost variable to whichever iteration, then `←` gets the current iteration number. Vyxal's structures autocomplete, so `(|...` without a closing paren is fine.
You're iterating over `ka`, which is the lowercase alphabet, so at the end the stack looks like `a , b, c... z`. Finally, Vyxal's implicit output takes care of the rest, returning the `z`.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `o`, 13 bytes, [cracked by A username](https://codegolf.stackexchange.com/a/231441/101522)
```
`₴ḟ `₴`Buzz`F
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=o&code=%60%E2%82%B4%E1%B8%9F%20%60%E2%82%B4%60Buzz%60F&inputs=&header=&footer=)
Solution should print `FizzBuzz`.
Intended solution:
>
> ``₴ḟ `k`Buzz`F`
>
>
>
> I discovered a parsing bug where you could put a string between the two parts of a diagraph, and the diagraph would still work. In this case, the program is being parsed as ``₴ḟ ``Buzz`kF`. The first two strings, which are `Fizz` and `Buzz`, don't matter at all, and instead, the final diagraph simply pushes `FizzBuzz`.
>
>
>
[Answer]
# [R](https://www.r-project.org/), 51 bytes, [cracked by Dominic van Essen](https://codegolf.stackexchange.com/a/231504/86301)
```
x=z=6
yy=0
while(x+yy-1>yy){x=x-1;z=z+1}
LETTERS[z]
```
[Try it online!](https://tio.run/##K/r/v8K2ytaMq7LS1oCrPCMzJ1WjQruyUtfQrrJSs7rCtkLX0LrKtkrbsJbLxzUkxDUoOLoq9v9/AA "R – Try It Online")
The string to output is `"R"`. The [previous version](https://codegolf.stackexchange.com/a/231480/86301) allowed for a crack I hadn't intended, found by pxeger. I hope this version is immune to that.
---
>
> The crack is to replace the while condition `x+yy-1>yy` by `x+yy->>yy`. This uses global leftwards assignment `->>`, replacing the value of `yy` at each iteration. That way, we go through the loop 12 times in total, leading to the intended value `z=18`. In real life, no one ever uses global leftwards assignment, nor should they!
>
> This challenge was inspired by a bug I often see in students' code, in which they expect `if(x<-1)...` to compare `x` to `-1`, but instead it assigns `1` to `x`. The way to avoid this bug is to type `if(x < -1)...` of course. IMO, this regular bug is the main argument against using `<-` instead of `=` for assignment (there are a few other arguments in the other direction).
>
>
>
[Answer]
# [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 28 bytes, [cracked by m90](https://codegolf.stackexchange.com/a/231556/104752)
```
a=9
if(a>0)a=0
a>9&&print(a)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEtLshMSS3Kzc/LTq38/z/R1pIrM00j0c5AM9HWgCvRzlJNraAoM69EI1Hz/38A "JavaScript (SpiderMonkey) – Try It Online")
Output `9` is expected.
~~A very easy trick. Maybe can be cracked soon (as it is quite short).~~
---
>
> Line Feed is a character.
>
>
>
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 34 bytes (safe)
```
u₁7₌I"
∑C$3Ǎ⇧
*C₍⇧⇩+
Ė_"v⇩÷
CĖ›½½∑
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=u%E2%82%817%E2%82%8CI%22%0A%E2%88%91C%243%C7%8D%E2%87%A7%0A*C%E2%82%8D%E2%87%A7%E2%87%A9%2B%0A%C4%96_%22v%E2%87%A9%C3%B7%0AC%C4%96%E2%80%BA%C2%BD%C2%BD%E2%88%91&inputs=&header=&footer=)
Solution should output `29`.
Solution:
>
>
> ```
> u₁7₌I"
> ∑C$3Ǎ⇧
> *C₍⇧⇩+
> Ė_"v⇩÷øCĖ›½½∑
> ```
>
>
>
>
Explanation:
>
> Replaces the last newline with `ø`, which causes the string to be wrapped in `»`, which is the delimiter for compressed numbers. The string is then decompressed by executing it as Vyxal code with the `Ė` command, then it is incremented, halved twice, and the digits are added together, equaling 29.
>
>
>
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 227 bytes, [Cracked by m90](https://codegolf.stackexchange.com/a/237111/106959)
```
\ ÇÇÇÇÇÇÇÇ
/!\; ÇÇÇÇÇÇÇÇ
\n/!<ÇÇÇÇÇÇÇÇ
! ÇÇÇÇÇÇÇÇ
> ^ÇÇÇÇÇÇÇÇ
\\2 \! \/! ~! \
ÇÇÇ\ v! ~ /
ÇÇÇÇÇ\'"a"\ÇÇÇÇÇ
ÇÇÇÇÇÇÇÇ\ /ÇÇÇÇÇ
```
[Try it online!](https://tio.run/##S8sszvj/XyFGQUHhcDsqBAopcOkrxlhjl4nJ01e0wSqjoIjLNAU7BYU47KbFGAGpGEWFGH1FhTogxQU1IUahDCigAAb6XEjGxqgrJSrFIPhcGFbGKOgjOP//AwA "><> – Try It Online")
The output must be `199`
~~I'm not sure if some robbers can crack...~~ Cracked in 6 Days, Same Solution.
[Answer]
# [brainfuck](https://esolangs.org/wiki/brainfuck) (cell-size 32, no change on EOF), 2,970,327,283 bytes
```
(...)[->(...)<]>.
```
>
> It's a start.
>
>
>
>
> This seems like a very boring CnR, any answer will either be trivially brute forceable or take advantage of some weird unicode + halting problem thing that makes it very tedious and not really easily doable by a human anyway. -Dotcomma Programs
>
>
>
Happy new year! The first `(...)` contains 2950107175 `+`s, and the second `(...)` contains 20220101 `+`s. It prints `☃` right now - make it print `❄`.
This is the only brainfuck answer I could write.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes, [cracked](https://codegolf.stackexchange.com/a/231446/66833) by [Aaron Miller](https://codegolf.stackexchange.com/users/101522/aaron-miller)
```
“Y$Ḥß»“¿<ȧ»
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw5xIlYc7lhyef2g3kH1ov82J5Yd2//8PAA "Jelly – Try It Online")
The output should be `hyper-neutrino` cause I'm lazy
>
> `“Y$Ḥß““¿<ȧ»` is a list of compressed strings `[“Y$Ḥß», “», “¿<ȧ»]`.
>
> * `“Y$Ḥß»` decompresses to `hyper-` (and is a suboptimal compression, specifically to [confuse hyper](https://chat.stackexchange.com/transcript/message/58632548#58632548) and get him overthinking about the compression engine :P)
> * `“»` decompresses the the empty string, which doesn't then affect the output
> * `“¿<ȧ»` decompresses to `neutrino`
>
> Then, Jelly smash-prints the string `["hyper-", "", "neutrino"]` into `hyper-neutrino`
>
>
>
>
>
>
>
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 20 bytes, [cracked by Aaron Miller](https://codegolf.stackexchange.com/a/231420/78850)
```
`Ẇ₁¹kḢ`:∧λf⇧\#¯ḣ⌐ƒż1
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%60%E1%BA%86%E2%82%81%C2%B9k%E1%B8%A2%60%3A%E2%88%A7%CE%BBf%E2%87%A7%5C%23%C2%AF%E1%B8%A3%E2%8C%90%C6%92%C5%BC1&inputs=&header=&footer=)
Alright. My turn.
You need to make this epic lambda output `who is joe joe mama`.
---
If you thought that the lambda actually did anything, then you were wrong. The first string in the program is to act as a distraction, as the answer is that everything after the `:` is the compressed version of the output string.
[Answer]
# [Python 2](https://docs.python.org/2/), 72 bytes, [cracked by the default.](https://codegolf.stackexchange.com/a/231463)
```
print pow(2,2**1337133713371337,195889276175237072760362930940173700767)
```
Expected output:
```
188867410716634269084427012487211003700
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 24 bytes
Hoping this one might be *slightly* more challenging than my first attempt but I somehow doubt it. The original outputs `1`, the cracked version should output `11` (both as strings).
```
@TwXµY *!ZøX ªX+YÑ}gB Ìs
```
[Try it online!](https://tio.run/##y0osKPn/3yGkPOLQ1kgFLcWowzsiFA6titCOPDyxNt1J4XBP8f//AA)
[Answer]
# [R](https://www.r-project.org/), 45 bytes, [cracked by pajonk](https://codegolf.stackexchange.com/a/231522/95126)
```
a=b=c=2
for(a in 1:b)c=c*pi
el(LETTERS[-c:0])
```
[Try it online!](https://tio.run/##K/r/P9E2yTbZ1ogrLb9II1EhM0/B0CpJM9k2Wasgkys1R8PHNSTENSg4WjfZyiBW8/9/AA "R – Try It Online")
The string to output is `"R"`.
This is an homage to [Robin Ryder's](https://codegolf.stackexchange.com/a/231427/95126) [series](https://codegolf.stackexchange.com/a/231466/95126) [of](https://codegolf.stackexchange.com/a/231480/95126) [challenges](https://codegolf.stackexchange.com/a/231485/95126), although I think his ones were cleverer...
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 5 bytes, [cracked by user](https://codegolf.stackexchange.com/a/231518/58974)
My turn! Coming up with C&R entries in Japt is always tricky because ... of reasons that would help you solve this! :p (and 'cause I suck at it!) Also, the longer a programme is, the more chance there is for an unintended crack or 2 but, the shorter it is, the easier it is to crack. So this will probably be easily cracked.
Original outputs `0` (as a string), cracked version should output `s`.
```
¤ùÅÔÌ
```
[Try it online!](https://tio.run/##y0osKPn//9CSwzsPtx6ecrjn/38A)
[Answer]
# [R](https://www.r-project.org/), 59 bytes, [cracked by Dominic](https://codegolf.stackexchange.com/a/231527/55372)
```
a=as.numeric
bb=strrep(11,1)
"if"(a(bb),LETTERS[a(bb)],"R")
```
[Try it online!](https://tio.run/##K/r/P9E2sVgvrzQ3tSgzmSspyba4pKgotUDD0FDHUJNLKTNNSSNRIylJU8fHNSTENSg4GsyL1VEKUtL8/x8A "R – Try It Online")
The string to output is `"R"`.
Definitely no match for [@Robin's challenges here](https://codegolf.stackexchange.com/search?q=inquestion%3A231409+user%3A86301), but when already this thread is full of [R](https://www.r-project.org/) submissions, why not another one?
---
Intended crack: [Try it online!](https://tio.run/##K/r/P9E2sdg2rzQ3tSgzmSspyba4pKgotUDD0FDHUJNLKTNNSSNRIylJU8fHNSTENSg4GsyL1VEKUtL8/x8A "R – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 226 bytes - [cracked](https://codegolf.stackexchange.com/a/231593/71631) by Zachary Cotton
```
import operator as o
import inspect as i
a,d = 37,lambda n:n if len(str(n))==1else d(sum(map(int,str(n))))
for k, v in{d(sum(map(ord, n))): f for n, f in i.getmembers(o,i.isbuiltin)[::11]}.items():
a = int(v(a,k**2))
print(a)
```
[Try it online!](https://tio.run/##RY5BasQwDEX3OYWW8mACaRYFQ05SulAmylRMLBtbM1DKnD11IDA78f7jf@Vf@0k67rvEnIpBylzIUgGqkLoTitbMVzuYdOQXmGD89BvFeSHQoCArbKxYraA6N00Db5VhwfqIGCmjqPkzdK5bW/3dw7P1/r2dVBYPhxBghUNR3w5p5f2NLXKcuVRMXnqp80M2E3VfIQzD96sX41jRhQ6o/dbW8Ink75fLR5vL5QDk9v0f "Python 3 – Try It Online")
It currently prints `520`, but it should print `5521`.
I hope you will enjoy this. I think once you find out the parts of the puzzle, you should be able to see what to change.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 19 bytes; [cracked](https://codegolf.stackexchange.com/a/231645/78410) by Bubbler
```
{(⍵ ⍵)(⍵ ⍵)(⍵ ⍵)},8
```
Prints `8 8 8 8 8 8` : [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94H@1xqPerQpArInJqNWxACn6XwAA "APL (Dyalog Unicode) – Try It Online")
Change one character and make it print `1` instead!
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 8 bytes; [cracked](https://codegolf.stackexchange.com/a/231646/78410) by Bubbler
```
≢∊⎕A⍨¨⎕A
```
Prints `676`: [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKO94P@jzkWPOroe9U11fNS74tAKEAMk8b8AAA "APL (Dyalog Extended) – Try It Online")
Change one character and make it print `286` instead!
[Answer]
# [Yggdrasil](https://github.com/cairdcoinheringaahing/Yggdrasil), 3 bytes, [cracked by A username](https://codegolf.stackexchange.com/a/231733/101522)
```
;.:
```
[Try it online!](https://tio.run/##3VjNcuM2DL7rKdi0jcRYdpLpTZvs9gE6Pe0tk6iMRNua6m8oOd1M0331LECKFmVSspXNXuqZRLYIfAA@gCTI@rndVuVvr1lRV6IlzXPj6a@tyMqN5yVVUbAyjZMtEw25Jb7vn/kfbj4uLpaXD@cv0e0neGNJ5VnTBgWrg0qkIRmMUup5reB8LzsYBYM5axryGSQij3SflK9JHGdl1sZx0PB8HRJRVW1Icr5uAeLPquTwKtts9S/aK@sP6q1QDUTw4RboEPExgtBZkU/vwEXBa9G56PBA8HYnSuIH//4XEvVH/dW6EgVrg717Ye9IaJikmpo/OFsHyA@dJCgHsTEWcAxCMAMexGZShbJvC1M6aoUo/fI8BMLXMdZCwIRgzyHB73YCs7UayBo5Yhvs1D7vkVZ1VQdXUGlawsTKmqxsWlYmPEDFUBI6HgbKeKZ@CbRIK6er4AtFdBcDgYIfAymrFKMxA7FkpBsgliljau5EWlUSgd9tRZ43fC8nE@SWs4gzudY1Y@XvRCzNiCq3/wcleuqMcOI5SwQnQcPbGGWarhqfWN4Mi//Ugu0Lja3HJ0vv9XOkvZFRo2Fr4lhkfUl43Q4VHckwozxaBubEcE1u8NOsuuPOaictLcNTlXVTYpiIbv2V2fDmVfJUDLpMZgYxUHNH0a/dgzDkax3HeBW2gj1x0fAgKdJGLcRvK0KFbFjalTFiGsD6/9294ZHDAZkCOimhd0YMYQOBr3d5Hj8KcHMbfG8MJNmKYD@hqDc2ivskJQunfRXC2KDpfc8T5C4kBS8qAatHshOClyqjIakZ/oDgszLlXyDZV4b3uODJdirld3L83rn9KTFo5Fa@HXkNTV8bcFiJb2WApnkVKHVinc3FQl4mAM/8s7nOIZdTLkbv4eL7uPLLqCs239M5vHEhqSJZsboGBweQdiDmKMZySIDT6scfaVX11S6zfznMHiBpL3BRpZ4T5asfEYtmUP1qvXSq/z6ifuW2thgRd1caLBQjleQEX84DX84Cv5gHfjEL/HIe@OXlLPSHeegPs8DP54GfzwJ/mQf@MgruRL91TSDYc8DA4f5kGXRtYrZxRyc43P/d@9qgEzA9/uQ721yLovE293Q23QeDtwMfy8bP7xobWFfcjkp3ayMI3h3pDAKHZ03CSnn9Y42k0KZuYejajkZ2KQvX0D/bLOdwKttNMIwu9c2M9qyz50Sd0KR7zeURzS4eWNIj8ig4@3tUWHKycLdcM7gAm4g0dVTrOl8U03PI7uYDaWOkZ@zazIJlZddiMrF5MtrHTV49snygfHjrgXr66DdoOwdXfjkrHlNGkkgd6zEXMgOxL2cUqQS0BxQ2jCAhP8H7X30aSmijW1IhDk4z/cFaXSN2AXinTQZn8e@76J5KVZdq4IbkXJHlOmxPcI23g/PbeTo1f7wM791KVvA4VmzGmMo4NqaqzK3v@68fVtErPO@uo@X1fdhnhsMpMMRL3hVSB8P3lNLXbw)
Solution should print `..:`.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `O`, 28 bytes (safe)
```
⁺⟇C‛bf½+ṅĖp⇩D∇⇧$⇧∇∇⇧WṄ3ẇḢht₴
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=O&code=%E2%81%BA%E2%9F%87C%E2%80%9Bbf%C2%BD%2B%E1%B9%85%C4%96p%E2%87%A9D%E2%88%87%E2%87%A7%24%E2%87%A7%E2%88%87%E2%88%87%E2%87%A7W%E1%B9%843%E1%BA%87%E1%B8%A2ht%E2%82%B4&inputs=&header=&footer=)
Solution:
>
> `⁺⟇C‛bf½+ṅĖpøD∇⇧$⇧∇∇⇧WṄ3ẇḢht₴`
>
>
>
Explanation:
>
> Changes the lowercasing and triplicating to dictionary compression. The dictionary compressed string is `₴ḟ₴ḣ`, which contains the target string. From there, the rest of the program just does a bunch of random junk to it and winds up with `₴` which is the target string. The `₴` at the end of the program is just a red herring. :)
>
>
>
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 29 bytes, [Cracked by ovs](https://codegolf.stackexchange.com/a/233418/100664)
```
.+[.[->+>+<<]+[>--<+++++]>+<]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fTztaL1rXTttO28YmVjvaTlfXRhsEYoECsf//AwA "brainfuck – Try It Online")
Should output
```
�:sIX=1
×}ð :kAH% ÊoÕàQͺ#y8M!
ÇmÐÙEºñ(µyÊßEÀ¡ý:Ó©]
·]°©õ:Ë¡EéÊOµ ñ-ºÙøm
§My¥ºûQèÕYÊ¿%A]:3 Ø}ñ
=pIU:+ÈeÉÊ/`ºã9¸á
-Pº[±¨õ9Ê@á½:iÑ
w0éµ:a©Êu 1íºCxÁ
g
¹eº»hÊå
```
SE swallowed some unprintables, so here's a hexdump:
```
00000000: 0001 c29d 3a73 4958 3d31 0ac3 977d c3b0 ....:sIX=1...}..
00000010: 09c2 953a 6b41 4825 09c3 8a6f c395 c3a0 ...:kAH%...o....
00000020: 51c3 8dc2 ba23 7938 4d21 0ac3 876d c390 Q....#y8M!...m..
00000030: c399 45c2 bac2 9bc3 b128 c2b5 79c3 8ac3 ..E......(..y...
00000040: 9f45 c380 c2a1 c3bd 3ac3 93c2 a918 5d11 .E......:.....].
00000050: 0ac2 b75d c2b0 c2a9 c3b5 3ac3 8bc2 a108 ...]......:.....
00000060: 45c3 a9c3 8a4f c2b5 20c3 b12d c2ba c283 E....O.. ..-....
00000070: c399 c3b8 6d01 0ac2 a74d c290 79c2 a5c2 ....m....M..y...
00000080: bac3 bb51 c3a8 c395 59c3 8ac2 bf25 c280 ...Q....Y....%..
00000090: 415d 3a33 09c3 987d c3b1 0ac2 973d 7049 A]:3...}.....=pI
000000a0: 553a 2b01 c388 65c3 89c3 8a2f c295 60c2 U:+...e..../..`.
000000b0: 91c2 8dc2 bac3 a339 c2b8 c28d c3a1 0ac2 .......9........
000000c0: 872d 5019 05c2 ba5b c2b1 c2a8 c3b5 39c3 .-P....[......9.
000000d0: 8ac2 9f05 40c3 a1c2 bd3a c293 69c2 98c2 ....@....:..i...
000000e0: 9dc3 910a 771d 30c3 a9c2 b53a c28b 61c2 ....w.0....:..a.
000000f0: 88c2 85c2 a9c3 8a0f 7520 31c3 adc2 ba43 ........u 1....C
00000100: c299 78c2 adc3 810a 670a 10c2 b965 c2ba ..x.....g....e..
00000110: c2bb 1168 1519 c38a 7fc3 a5 ...h.......
```
And no, I don't know *how* I got this result.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 5 bytes, [cracked by Daniel H.](https://codegolf.stackexchange.com/a/231438/16766)
```
****t
```
Outputs `179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216`. ([DON'T Try it online!](https://tio.run/##K8gs@P9fCwhK/v8HAA "Pip – Try It Online") This code requires the current version of Pip. You can run it [here](https://replit.com/@dloscutoff/pip).)
The cracked version should output `42`.
---
The intended solution was
>
> `**E*t`
>
>
>
which is basically the same as Daniel's crack.
In hindsight,
>
> using an operator that's synonymous with `**`
>
>
>
may not have been the *best* idea, but the `42` output was too good to pass up.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 24 bytes, [Cracked](https://codegolf.stackexchange.com/questions/231410/which-character-to-change-robbers/231444#231444) by Aaron Miller.
```
kH:`string`D‟‟Ẋf∑vd∑qĖ₁Ẏ
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=kH%3A%60string%60D%E2%80%9F%E2%80%9F%E1%BA%8Af%E2%88%91vd%E2%88%91q%C4%96%E2%82%81%E1%BA%8E&inputs=&header=&footer=)
Output should be
```
HH\`\`HHmorningHHoccupationalHH\`\`ee\`\`eemorningeeoccupationalee\`\`ll\`\`llmorninglloccupationall
```
A mess.
] |
[Question]
[
# Challenge
Print or return the Stack Exchange favicon, as provided below:
```
___________________
/ \
---------------------
| |
---------------------
| |
---------------------
\__________ _____/
| /
| /
|/
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in each language wins.
[Answer]
# [Operation Flashpoint](https://en.wikipedia.org/wiki/Operation_Flashpoint:_Cold_War_Crisis) scripting language, ~~263~~ 195 bytes
```
f={r=" ";t="---------------------\n";s=" ___________________\n/"+r+"\\n"+t+"|"+r+"|\n"+t+"|"+r+"|\n"+t+"\__________ _____/\n | /\n | /\n |/";s}
```
Not the right tool for the job.
**Call with:**
```
hint call f;
```
**Output:**
The formatting fails, because the font is not monospaced.
[](https://i.stack.imgur.com/4RdFw.jpg)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~38~~ ~~37~~ ~~33~~ 30 bytes
```
←×_χ↓F/||⟦ι¹¹⟧\×_⁹‖B_×ψ⁴↙↙³↑↑³
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMPKJzWtREchJDM3tVhDKV5JR8HQQFPTmss3vyxVw8olvzwPyEnLL1LQUNKvqVHSVIBoi84EKjSMBcpB@EoxMUpwDpJhliCzglLTclKTS5xKS0pSi9JyKjUQ2uLRdVXqKJig2g9yIFwRXERHwRiuKrQAIR9aAJb5//@/btl/3eIcAA "Charcoal – Try It Online") Link is to verbose version of code. Edit: Managed to save a byte with the help of a reflection, although @CarlosAlejo shows that it can in fact be done in 37 bytes without reflecting. Saved a further 4 bytes by drawing the left ¾ and reflecting the final ¼. Edit: Previous 33-byte answer depended on `ReflectButterflyOverlap()` not overprinting the overlap area with the reflection, so in case this behaviour changed, I sought a solution that didn't rely on that, and the result turned out to be shorter anyway, thanks to my creative use of printing an array. Explanation:
```
←×_χ Print 10 `_`s leftwards (top row)
↓ Move down to the next row
F/|| For each character in the string `/||`
ι Current character
¹¹ Integer 11, prints as `-----------`
⟦ ⟧ Put both into an array
Implicitly print on separate lines
\ Implicitly print `\`
×_⁹ Implicitly print 9 `_`s
‖B Reflect right, overlapping the axis
_ Implicitly print `_`
×ψ⁴ Implicitly delete 4 characters
↙↙³ Move down left and print three `/`s
↑↑³ Move up and print three '|'s
```
[Answer]
# [///](https://esolangs.org/wiki////), 98 bytes
```
/'/ //&/
"""
|!! |//%/\\\/
!'|//#/_____//"/-------//!/'''' / ###____
\/!! \\&&
"""
\\##''#%'% %\/
```
[Try it online!](https://tio.run/##JcwxCoAwEETRPqfYZEm2kn@hAbEQLOzS5u4x6qsGhpl@H/06@5wEZtBIpZQ0crYBFUmkHCs7@wsK2w8ysRjm7m@ZxBpKrX0vknuE16hWxZwP "/// – Try It Online") Or, [see it interactively!](http://conorobrien-foxx.github.io/slashes.html?JTJGJyUyRiUyMCUyMCUyRiUyRiUyNiUyRiUwQSUyMiUyMiUyMiUwQSU3QyEhJTIwJTdDJTJGJTJGJTI1JTJGJTVDJTVDJTVDJTJGJTBBISclN0MlMkYlMkYlMjMlMkZfX19fXyUyRiUyRiUyMiUyRi0tLS0tLS0lMkYlMkYhJTJGJycnJyUyMCUyRiUyMCUyMyUyMyUyM19fX18lMEElNUMlMkYhISUyMCU1QyU1QyUyNiUyNiUwQSUyMiUyMiUyMiUwQSU1QyU1QyUyMyUyMycnJTIzJTI1JyUyNSUyMCUyNSU1QyUyRg==)
[Answer]
# [Python 2](https://docs.python.org/2/), 115 bytes, more creative idea
```
t,u,v,w,x,y,z='\n -/\\_|';k=w+t+11*u+z;i=t+21*v+t
print u+19*y+t+w+19*u+x+(i+z+19*u+z)*2+i+x+10*y+4*u+5*y+k+u,k,k+w
```
[Try it online!](https://tio.run/##JYrBCsIwEAXvfkVv1bwtukEPpeRPAl4NgVhkt2mC/x5TPM0wzFrk9U62NSGljTLtVKi60adhunr//I5LdBkCZqOoS3ACy2aDnNZPSDIoeDalD/kQxY5zQP17vRiL0BPf@nLv5dEZoRQpIrf2Aw "Python 2 – Try It Online")
# [Python 2](https://docs.python.org/2/), 102 bytes, boring idea
```
print'eNrjUojHBFz6CpgghksXG+CqwaK2hgpqYxDuASkDM/S5kDUqKKDxUbn6XADUmClx'.decode('base64').decode('zip')
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EPdWvKCs0P8vDya3KzLkgPT0juzjCXdu5sDzR2ygjvaAwssKl1DE428VXP9g02yW00NvbpSI0Kc8swtElNNc5p0JdLyU1OT8lVUM9KbE41cxEXRMuUJVZoK75/z8A "Python 2 – Try It Online")
[Answer]
# JavaScript (ES6), ~~113~~ 112 bytes
(Saved a byte thanks to @Craig Ayre.)
```
let f=
_=>` _19
/ 19\\
-21
| 19|
-21
| 19|
-21
\\_10 4_5/
11| 2/
11| /
11|/`.replace(/.(\d+)/g,([a],b)=>a.repeat(b))
console.log(f());
```
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), ~~32~~ 31 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
^$∙r↑Ψ«2τγæΕž‘╬Æ╬⁷"ƧΡ⅟?0Ξ³‘6«8ž
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JTVFJTI0JXUyMjE5ciV1MjE5MSV1MDNBOCVBQjIldTAzQzQldTAzQjMlRTYldTAzOTUldTAxN0UldTIwMTgldTI1NkMlQzYldTI1NkMldTIwNzclMjIldTAxQTcldTAzQTEldTIxNUYlM0YwJXUwMzlFJUIzJXUyMDE4NiVBQjgldTAxN0U_)
Explanation:
```
...‘ push a quarter of the icon
Β palindromize vertically
╬⁷ palindromize horizontally (these two should be ╬3 together, but spacing doesn't work correctly (though now it does since I fixed it))
"...‘ push the extention
6«8ž at coordinates [12; 8] in the quad-palindromized image put that in
```
The quarter:
```
__________
/
-----------
|
-----------
```
and the other part:
```
| /
| /
|/
```
[Answer]
# Python 2, 124 bytes
```
a,b,d,e,f,g,h=' _-|/\\\n';r=d*21+h+e+a*19+e+h;n=f+h+a*11+e;print a+b*19+h+f+a*19+g+h+r*2+r[:22]+g+b*10+a*4+b*5+n+a*2+n+a+n+f
```
[Try It Online!](https://tio.run/##JYpBDsIwDAS/0lul2AhiwQGivIQglKpJzcVUUS9I/D1sxcH2rGfXz6Zvk94zTzxz4coLaxyH5@F7TCnZGFqcnXhSKpSdv@JosFjxQPRUwtpetg2Zpt0q1X9tATYn1O43kQci9AnqDLiQgWTfmNr7Dw)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 187 bytes
Saved 2 bytes thanks to Cody Gray, and 3 bytes thanks to Keyu Gan!
```
#define a" "
#define s a" "a
#define l"\n---------------------\n"
f(){puts(" ___________________\n/"s"\\"l"|"s"|"l"|"s"|"l"\\__________ _____/\n"a" | /\n"a" | /\n"a" |/");}
```
[Try it online!](https://tio.run/##bY7BCsIwEETv/YplemkPNR@g@CULEpJUA3EV0p5Mvz0mQltB57JvhmVnzXA1JrdeTJito1OcrH8cbufcWjd6caRBq9CsYawx9OYDWIZ/YkEzdv3rOU@xA11@xaIQwYyAVCB9TeZ9rfZ/QJWT9adEtONGCv1xyXftpZSW4mLe "C (gcc) – Try It Online")
[Answer]
# C, 167 bytes
```
i;char*d=" q /()\\ A |()| A |()| A \\h#c/ #&|!/ #&| / #&|/",c,b;main(j){while(c=d[i++],b=c%5==2||c>123?c:c>95?95:c>45?45:c>=32?32:++c,i<47)for(j=c;j-->=b;)putchar(b);}
```
[Try it online!](https://tio.run/##Rc4xDoIwGEDhubdAiKYVkFggBkppPIc40B@UEgRFiIP17CgsLu9bH7hXgMlSLTRjURrJcyhUt6vSSTGo8n5bcNN4IA@TLENHpDHRf7KsssBD1kavlhpLPdMBR7Jbrlpck/erUk2JgRcnZdtnR3JYh5xTrSHdU19ADGkUiij8GYQimOU@FT6NbRsclQQHcul6XHNgteumXDJyH4f5DUvCPtP0BQ "C (gcc) – Try It Online")
Note: a lot of apparent spaces above are actually the tab character.
Readable version:
```
i;
char *d = " q /()\\ A |()| A |()| A \\h#c/ #&|!/ #&| / #&|/", c, b;
main(j) {
while(
c = d[i++],
b = c % 5==2 || c > 123 ? c:
c > 95 ? 95:
c > 45 ? 45:
c >= 32 ? 32:
++c,
i < 47
)
for(j = c; j-- >= b;)
putchar(b);
}
```
Explanation:
The data array, d, encodes the answer in literal single characters and coded repeated characters. Each character, c, in the data array is mapped to a base character, b, and a number of repetitions. It is then printed that many times.
Characters that are used only singly (slashes and the pipe) have ASCII codes 47, 92, and 124. Two of these are divisible by 5 with a remainder of 2 `(c%5=2||c>123)`. I couldn't find a shorter condition to test for all three.
Characters that are repeated (underscore, dash, and space), with ASCII codes 95, 45, and 32 respectively, are coded with a higher ASCII code--increased by one per repetition. So, for example, a single space is just a space, but two spaces can be coded by the next ASCII character, the exclamation point. Where a coded character would be unsuitable because it meets the above modulo condition, it can be split, as with #& to represent eleven spaces. The same technique is used to avoid overlap between the space and dash character ranges.
Finally, the ten newlines are encoded as tabs to save bytes that would have been spent escaping the newlines with a backslash, then incremented for printing (`++c`).
[Answer]
# [Rust](https://www.rust-lang.org/), 181 bytes
```
||" ___________________
/2\\
1
1
3
\\__________ _____/
4| /
4| /
4|/".replace("1","3
|2|").replace("2",&" ".repeat(19)).replace("3",&"-".repeat(21)).replace("4",&" ".repeat(11))
```
[Try it online!](https://tio.run/##ZYvBCsIwEETv@Yp1D7IL0ZCkF/FXAhIkQqGGEuup6bfHNAdbdBaGZd5Mer@m8ojw9H0knsfUx2mIB8J5QUklZ4Tbv4Qyzgldzwrnthyq2qNElwGar6bwnMI4@Hsg1CjRimwy8hYalEeE1gp@In3hHbQrPH2h0XvY/SwrLEzM16V8AA "Rust – Try It Online")
## [Rust](https://www.rust-lang.org/), 184 bytes
This version may be more golfable as adding further `replace` cost fewer bytes each. The first `replace` isn't part of the loop because it pulls double duty changing `s` into a `String` instead of a `&'static str`.
```
||{let mut s=" 5__5__5
/2\\
1
1
3
\\55 5/
4| /
4| /
4|/".replace("1","3
|2|");for p in vec![("2"," ",19),("3","-",21),("4"," ",11),("5","_",5)]{s=s.replace(p.0,&p.1.repeat(p.2))}s}
```
[Try it online!](https://tio.run/##PYzBCsIwEETv@YrtHiQLsTVpcxDxS6yUIhEKNYYk9dL022taxNlh4O3A@CnE9Wnh1Q@W0@z8YONoC47zgoKvKc2jifCaIoQrgu66zaxSbctkvpq1rdaQpSvWJIA9t6iw9MaN/cNwlCiwZkklpMvz7cHBYOFjHsWNo8odoJBnEhzrDEcUSm7Q/JoddIYOhab7HK7hP@3Kkzi4Um4P08fMimgJy0qc6LKsXw "Rust – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 49 37 bytes
```
↓⁵\…_χ↓↓³↗↗³…_⁵↑/↑⁵↖\←…_¹⁹↓ /F³«P²¹¶¶
```
[Try it online!](https://tio.run/##S85ILErOT8z5//9R2@RHjVtjHjUsiz/fDuK0TT60@VHbdCAC0kBRoOyjton6QAxmTYt51DYBJH5o56PGnUDVCvrv9yw7tPnQ6vd7NhzadGjnoW2Htv3/DwA "Charcoal – Try It Online")
At last I could golf this a bit. This answer (unlike all other Charcoal answers) does not use reflection, but draws all the contour in one pass, leaving the horizontal bars for the end.
Link to the [verbose version](https://tio.run/##S85ILErOT8z5/z@gKDOvRMPKJb88T0fBVNOaCyKgFBOjBOcEJealp2ooxSvpGBpoAkV988tSIVrgSqAGGMNlQwuCMtMzShAKoAIQNejmAm1GVqmjoKSvhCpgisz1SU0DGoTiRiuIGJKRhpaa6M5TUgAbm5ZfpKBhrKlQzeVbmlOSWQBWYmSI5Pm8mDyQwtr////rlv3XLc4BAA).
[Answer]
# [Bubblegum](https://esolangs.org/wiki/Bubblegum), 40 bytes
Saved 1 byte by removing a trailing newline, thanks @ovs!
```
00000000: 5388 c704 5cfa 0a98 2086 4b17 1be0 aac1 S...\... .K.....
00000010: a2b6 860a 6a63 10ee 0129 0333 f4b9 9035 ....jc...).3...5
00000020: 2a28 a0f1 51b9 fa00 *(..Q...
```
[Try it online!](https://tio.run/##bYw7DgIxDER7TjElUFh2fptwBSpES@NECRKCcs8fvGJLnjRTzby61vruz/UzJ@9cEH3OaAsHxDYUrCXDcU4IVRZI7QzVJsCdiB4W0JU2Dj@DmENdTciJFUmTh3DvYHEF7L3HCLWgsI/A9ns1qxN567g7nDmcugzlIYhi@6HM@Mv5SHSz85xf "Bubblegum – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 38 bytes
```
←…_χP↑⁵P\F³«↑P¹¹↑»↗¹…_χ‖BM²¦⁷P↓⁴… ⁴↙↙³
```
[Try it online!](https://tio.run/##S85ILErOT8z5//9R24RHDcviz7e/37PhUdvER41bgYyY93uWHdp8aDVQAMg7tPPQTiDr0O5HbdOBLLDqRw3T3u9Z9H7P2kObDi171LgdrHvyo8YtQGkFENU2E4gObf7/HwA "Charcoal – Try It Online")
I used [Carlos's answer in its original form](https://codegolf.stackexchange.com/a/129306/16766) as a jumping-off point, but saved a good bit by using a reflection, taking advantage of horizontal symmetry. (Vertical symmetry wasn't worth it because the underscores ended up on the wrong row.) You can see the evolution of the canvas at each step [here](https://tio.run/##S85ILErOT8z5/1/hUdvER20THjUsiz/f/n7Pkvd7NoBEGrdC2DFgatmhzYdWA4WBAod2HtoJZi05tPtR2/RDO4EsuOZHDdPe71kE1rL20KZDyx41bgebN/lR4xaIOgUoq20mEB3a/P8/AA).
Here's the [verbose version](https://tio.run/##XY9RC4IwFIXf9ysue9qFCZlF0KP0FAki9CaEyKbCcrKmEdFvXw4x0tfvfJxzb1kXptSFci41TWvZ8SKk5ZAVbSUYvVEO4QaRJL2yTTcZ147DfoFonlMkUhtgEcKbJHoQ3ltIYYh/wYekc1vWVPU4OcYTWm9nQipR2ri3VhipXgzJub93bMsPy8NO@tly2K16gHo2b3vHvzhLP8AhQudcMLjgob4).
[Answer]
# Python 2, ~~119~~ ~~117~~ 116 bytes
```
print''.join(' \n-/|\\_'[ord(x)/8-4]*int('1245abjl'[ord(x)%8],36)for x in' V(8&H(7(@&@(7(@&@(7(HT"S8(%@!8(%@ 8(%@8')
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EXV0vKz8zT0NdISZPV78mJiZePTq/KEWjQlPfQtckVguoREPd0MjENDEpKwcmpWoRq2NsppmWX6RQoZCZp64QpmGh5qFhruGg5gAnPUKUgi00VB0UQYQCiLBQ1/z/HwA "Python 2 – Try It Online")
A bit of tortured run-length encoding...
EDIT: Save 3 bytes by replacing the set of lengths:
`[1,2,4,5,10,11,19,21][ord(x)%8]`
with
`int('1245abjl'[ord(x)%8],36)`
[Answer]
# C++ 11 - ~~162~~ ~~159~~ ~~154~~ ~~152~~ 150 bytes
MSVC:
```
void f(){char*i="b t_b\nb/t b\\b\nv-b\nb|t b|b\nv-b\nb|t b|b\nv-b\nb\\k_e f_b/b\nl b|c b/b\nl b|b b/b\nl b|b/";while(*i)cout<<string(*i++-97,*i),i++;}
```
GCC: (+4 chars)
```
int f(){char*i="b t_b\nb/t b\\b\nv-b\nb|t b|b\nv-b\nb|t b|b\nv-b\nb\\k_e f_b/b\nl b|c b/b\nl b|b b/b\nl b|b/";while(*i){cout<<string(*i-97,*(i+1));i+=2;}}
```
Input string `i` is coded in char pairs:
1. Count of chars to repeat (added to 'a' to be a legible character)
2. Char to print
I think, there's still a lot of room for improvement here.
Edit:
1. Replaced putchar with cout<<
2. Remove while, Use string constructor to repeat chars
3. Removed space before pointer and a spurious semi-colon ;;
4. Compounding instructions with comma, removing braces.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 74 bytes
```
J*21\-L*db+d*19\_++\/y19\\V2J++\|y19\|;J++++\\*T\_y4*5\_\/V3+++y11\|y-2N\/
```
[Try it online!](https://tio.run/##K6gsyfj/30vLyDBG10crJUk7RcvQMiZeWztGvxLIiAkz8gKya0DsGmsgE8iJ0QqJia800TKNiY/RDzMGClUaGgKV6Br5xej//w8A "Pyth – Try It Online")
[Answer]
## [R16K1S60 Assembly](http://lbphacker.hu/powdertoy/R16K1S60/manual.md), ~~152~~ 144 Bytes
Writes output to screen peripheral the R16K1S60 in ASCII. Runs on The Powder Toy save `2012356`. (See link in header for info)
The byte size of the program is the compiled result (Cells Used \* 2), not the assembly.
You know you've done well when the logo takes more space than your bytecode.
```
a:
mov ex, ip
mov ax, .string
mov sp, ip
mov dx, 0x1000
send sp, dx
.loop:
mov bx, [ax]
cmp bx, ip
je .end
cmp bx, ip
je .newline
shr bx, cx, 8
and cx, 0x00FF
.inner:
send sp, cx
sub bx, ex
jnz .inner
.reentry:
add ax, ex
jmp .loop
.newline:
add dx, 0x0020
send sp, dx
jmp .reentry
.string:
dw 0x0120
dw 0x135F
dw 0x000C
dw 0x012F
dw 0x1320
dw 0x015C
dw 0x000C
dw 0x152D
dw 0x000C
dw 0x017C
dw 0x1320
dw 0x017C
dw 0x000C
dw 0x152D
dw 0x000C
dw 0x017C
dw 0x1320
dw 0x017C
dw 0x000C
dw 0x152D
dw 0x000C
dw 0x015C
dw 0x0A5F
dw 0x0420
dw 0x055F
dw 0x012F
dw 0x000C
dw 0x0B20
dw 0x017C
dw 0x0220
dw 0x012F
dw 0x000C
dw 0x0B20
dw 0x017C
dw 0x0120
dw 0x012F
dw 0x000C
dw 0x0B20
dw 0x017C
dw 0x012F
dw 0x0009
.end:
hlt
```
## Explanation
The assembly code above implements a simple compression algorithm, with the words 0x000C being a newline and 0x0009 being the command to stop execution.
The other words are encoded simply, like this:
0xTTCC
* T: Times to repeat the value
* C: The ASCII character to print
The ASM uses every register available to it, including some of the less commonly used ones:
* The Instruction Pointer, to get a few known values into quick recall to save some bytes (A constant value in an instuction that's not just a register uses an extra byte to store it)
* The Stack Pointer is used as 6th general purpose register, because none of the code uses the stack.
Only AX, BX, CX, and DX are actually used for important data. EX and SP are used to store some constants that get frequently used.
It's somewhat simple, and has nil chance of winning, but it was fun to write!
See revision history for the old answer (It's just as large in terms of ASM)
funfact: if this was measured in words (in the case of the R16K1S60,16 bits) it'd be smaller than the pyth answer, at 72 bytes
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~50~~ ~~48~~ 45 bytes
```
21“©&Ẇƥ⁸þ/Ẉoụ’ḃ1pF“CṣʠėHẹỊtṡḤḶ’ṃ“ _/\-|”¤xs¹Y
```
[Try it online!](https://tio.run/##AWEAnv9qZWxsef//MjHigJzCqSbhuobGpeKBuMO@L@G6iG/hu6XigJnhuIMxcEbigJxD4bmjyqDEl0jhurnhu4p04bmh4bik4bi24oCZ4bmD4oCcIF8vXC184oCdwqR4c8K5Wf// "Jelly – Try It Online")
[Answer]
# [V](https://github.com/DJMcMayhem/V), 49 bytes
```
i ±¹_
/±¹ \2ÙÒ-jÓÓ/|
3äkGR\±_´ µ_/
±± | /2ñÙlx
```
[Try it online!](https://tio.run/##K/v/P1Ph0MZDO@O59EGUQoy00eGZhyfpZh2efHiyfg2X8eEl2e5BMYc2xh/aonBoa7w@F1DZRoUaBQV9oMqNh2fmVPz/DwA "V – Try It Online")
[Answer]
# Mathematica, 163 bytes
```
Row@Map[Column,Characters/@{" /-|-|-\\ ",r="_ - - -_ ",r,r,r,r,r,r,r,r,r,"_ - - - |||","_ - - - /","_ - - - / ","_ - - - / ",r,r,r,r,r," \\-|-|-/ "},{1}]
```
[Answer]
# [PHP](https://php.net/), 86 bytes
```
<?=gzinflate(base64_decode("U4jHBFz6CpgghksXG+CqwaK2hgpqYxDuASkDM/S5kDUqKKDxUbn6AA"));
```
[Try it online!](https://tio.run/##K8go@P/fxt42vSozLy0nsSRVIymxONXMJD4lNTk/JVVDKdQky8PJrcrMuSA9PSO7OMJd27mwPNHbKCO9oDCywqXUMTjbxVc/2DTbJbTQ29ulIjQpz8zRUUlT0/r/fwA "PHP – Try It Online")
# [PHP](https://php.net/), 118 bytes
```
<?=strtr(' 333____
/00 \
11-
|02
11-
|02
11-
\33 3/
2 /
2 /
2/',[' ','----------'," |",_____]);
```
[Try it online!](https://tio.run/##K8go@P/fxt62uKSopEhDXcHY2DgeCLj0DQwUFBRiuAwNdblqDIxQ6BhjY6CcgrE@l5GCAogAYn11nWh1BShQ11HXhQN1HSUFBKhR0gGZHx@raf3/PwA "PHP – Try It Online")
[Answer]
## Python 2, 171 bytes
```
p,u,q,v,r,s,F=' ','_','/','|','-'*21,'\\',lambda f,m:f+m*19+f;B=lambda n:p*11+v+p*n+q
print'\n'.join([F(p,u),q+p*19+s,r,F(v,p),r,F(v,p),r,s+u*10+p*4+u*5+q,B(2),B(1),B(0)])
```
Each line is exactly 85 bytes! Hoorah!
[Answer]
# Zsh, 244 bytes
This is specifically written for Zsh, not Bash, as it allows a bit more in terms of weird syntax.
```
alias p=printf
function r { p "$1%.s" {0..$2}}
function l { p $1;r $2 19;p $3;p "\n"}
l " " _ " "
l / " " \\
l - - -
l \| " " \|
l - - -
l \| " " \|
l - - -
p \\
r _ 10
r " " 4
r _ 5
p "/\n"
r " " 11
p "| /\n"
r " " 11
p "| /\n"
r " " 11
p \|/
```
Note: when I tried to run it on [tio.run](https://tio.run/##fY3RCsIwDEXf9xUh1EfbZeqDDP@kIEMYFkot7Xxx7bfXtAqCiFxIcs8lySNeS5msmSL4kw/GLXM3391lMTcHAVbwgII2MiKsvZRiyPmT25YLGgOIAeg4stlxQe0wdxaQda6VZ9Wc1jxuq7jr9GLpL/N1KfAd6rnVcN/sgRNU/OlNiSpIAD/YN9JJlfIE) the output is different than on my terminal. The fix to this is replacing
```
function r { p "$1%.s" {0..$2}}
```
with
```
function r { p "$1%.0s" {0..$2}}
```
which would make it 245 bytes ([link](https://tio.run/##fY3BCsIwDIbve4oQ6tG1mXqQ4ZsUZAjDQqmlnRfXPntNqyCISCDJ/@VP8ojXUiZrpgj@5INxy9zNd3dZzM1BgBU8oKBNryLCqvpeDDl/DLYZBI0BxAB0HFnsOKF2mDsLyHGumXvZlNbcbmtw1enF0l/m61LgO6S41OG@yQNPUPKnNyWqIAH8YN9IJ1nKEw)).
**Edit**
Seems like I was too eager to hit that post button and I missed some spaces, making my solution a bit less efficient. My new output seems off though, but I think I counted correctly (but it wouldn't change the length anyway).
[Answer]
# [Retina](https://github.com/m-ender/retina), 74 bytes
```
_18¶/ 18\-| 18|-| 18|-\_9 3_4% % %/
-
¶-20¶
%
/¶ 10|
\d+
$*
+`(.)1
$1$1
```
[Try it online!](https://tio.run/##K0otycxL/P@fSyHe0OLQNn0FQ4sY3RogWQMlY@ItFYzjTVQVFFQVVPW5dLkObdM1Mji0jUuVS//QNgVDgxqumBRtLhUtLu0EDT1NQy4VQxXD//8B "Retina – Try It Online")
[Answer]
# Python 2, ~~159~~ ~~153~~ 139 bytes
```
s=" "*19;e="-"*21;a=" "*9;print" %s\n/%s\\\n%s\n|%s|\n%s\n|%s|\n%s\n\%s %s/\n%s| /\n%s| /\n%s|/"%("_"*19,s,e,s,e,s,e,"_"*8,"_"*7,a,a,a)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v9hWSUFJy9DSOtVWSVdJy8jQOhEsYmldUJSZV6KkoFock6cPJGJi8kDMGtXiGnRWjGqxAhCoFuuD@DUKClAaQukrqWooxYPs0CnWSYVjkJAFmDTXSQRBzf//AQ)
EDIT: Saved 6 bytes by using `%` formatting instead of `.format()`.
EDIT: Saved another 14 bytes by fixing the output, thanks to musicman523.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~79~~ ~~72~~ 71 bytes
```
" _p
/ p\\
{"-r
| p|
"²}-r
\\_g a_b/
h| /
h| /
h|/"r".%l"_g p6nZÅnH
```
[Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=IiBfcAovIHBcXAp7Ii1yCnwgcHwKIrJ9LXIKXFxfZyBhX2IvCiBofCAgLwogaHwgLwogaHwvInIiLiVsIl9nIHA2blrMbkg=&input=)
* 7 bytes saved thanks to ETHproductions' excellent suggestion of using base 32 integers for the repetition values.
[Answer]
# JavaScript (ES6), 151 bytes
```
_=>` 2_________
/0\\
1
|0|
1
|0|
1
\\2 _____/
3| /
3| /
3|/`.replace(/\d/g,a=>a.repeat.call(...[[" ",19],["-",21],["_",10],[" ",11]][a]))
```
## Test Snippet
```
f=
_=>` 2_________
/0\\
1
|0|
1
|0|
1
\\2 _____/
3| /
3| /
3|/`.replace(/\d/g,a=>a.repeat.call(...[[" ",19],["-",21],["_",10],[" ",11]][a]))
O.innerHTML=f()
```
```
<pre id=O>
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 89 bytes
```
1"""____¶/19\¶##-¶|19|¶##-¶|19|¶##-¶\""4"/¶11|2/¶11|1/¶11|/
#
!!
"
_____
!
-----
\d+
$*
```
[Try it online!](https://tio.run/##K0otycxL/P@fy1BJSSkeCA5t0ze0jDm0TVlZ99C2GkPLGkxmjJKSiZL@oW2GhjVGEMoQQulzKXMpKnIpcYEMiudS5NIFAa6YFG0uFS2F//8B "Retina – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 48 bytes
```
↙¹→P¹¹↓↓¹P¹¹‖B↓¦↘→×¹⁰_M⁷↑←←×¹⁰_‖BJ¹¹¦⁶→×⁴ ↙↙³↑↑³
```
[Try it online!](https://tio.run/##S85ILErOT8z5//9R28xDOx@1TXq/Z8OhnSDWZCA6tBPGbZj2fs8ikMiyR20zgMoOTwcKNm6If79n7aPG7Y/aJj5qmwBEMGGI@vd7VoE0A/U0bgPredS4RQFoEciuzWA9Ew9t/v8fAA "Charcoal – Try It Online")
Somewhat different internals than Carlos's, although not visible at first.
[Answer]
# [,,,](https://github.com/totallyhuman/commata), ~~115~~ ~~101~~ 98 [bytes](https://github.com/totallyhuman/commata/wiki/Code_page)
I am absolutely ashamed that this is the best I can produce. >.>
```
"|/
"' 11×:"| /
"⇆:"| /
"⇆'
'/'_5×' 4×'_10×92c'
'|' 19×'|'
'-21×+++++3×110⇆⊣"\
"' 19×'/'
'_19×' #
```
] |
[Question]
[
Take an array which consists of positive integers or arrays, output if it only contains `2`s.
Output should be a truthy or falsey value (Sorry if this destroys answers)
## Truthy Test Cases
```
[2]
[2,2]
[[2],[2,2],2]
[]
[[],[]]
```
## Falsey Test Cases
```
[1]
[22]
[2,2,2,1]
[[1,2],2]
```
[Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) Are forbidden.
[Default IO](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) rules apply.
Code-golf, Fewest bytes wins!
[Answer]
# [Python 2](https://docs.python.org/2/), ~~43~~ 40 bytes
```
f=lambda l:l>=[]and all(map(f,l))or l==2
```
[Try it online!](https://tio.run/nexus/python2#VY5BCsQgDEXX9RShKwVnQJcFexFxkaEIheiUkl3p2a21MDgJfPJfwiclOsL0WRBootn5gHkBJJIJNxk1KfXdgZyzhcGBF3DX4G3Qv1F35l48pIMViaahssGbpvY/orbpYswT0XwQItYnGNYMPDW07WtmGI8TXjMc5/iuBwlZsoYoWalyAQ "Python 2 – TIO Nexus")
---
At time of posting this answer, it was still allowed per [this](https://codegolf.meta.stackexchange.com/a/11908/64121) meta consensus to output via throwing an error / not throwing an error. Therefore this answer at 26 bytes was valid:
```
f=lambda l:l==2or map(f,l)
```
[Try it online!](https://tio.run/nexus/python2#@59mm5OYm5SSqJBjlWNra5RfpJCbWKCRppOj@b9EwVYhmksBBDijjWJ14EwdJA5IAiKCJAgU4gKTsUAxzmhDMGmEagQQGiIZYwgxAsyP5eJKAzqkRCEzT6HECihUUlRpBZYpKMrMK1FQqq5V0LVTqK5V0gOqy00s0SjRUUjTKNHUBCpKrUhOLSjBotw1KMg/CKFD8z8A "Python 2 – TIO Nexus")
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), ~~43~~ 33 bytes
I smell... ***recursion***.
Thanks to *Emigna* and *Leaky Nun* for saving 10 bytes!
### Code
```
a([]).
a([X|T]):-(X=2;a(X)),a(T).
```
[Try it online!](https://tio.run/nexus/prolog-swi#@5@oER2rqccFpCJqQmI1rXQ1ImyNrBM1IjQ1dRI1QjT1/v8HykUbxepEG@kASSOgagA "Prolog (SWI) – TIO Nexus") or [Verify all test cases!](https://tio.run/nexus/prolog-swi#@5@oER2rqccFpCJqQmI1rXQ1ImyNrBM1IjQ1dRI1QjR1FPX@/wfKGkFVGenAWEAhHTAXLgKTAIrHQtmGMG1I@oEQJhxtCNcPAA)
### Explanation:
For non-Prolog users, a list is formatted in the following way: `[Head | Tail]`.
The `Head` is the first element of the list, and tail is the remaining list. [Test it here!](https://tio.run/nexus/prolog-swi#@5@RmpgSX5KYmROfWlFSlJhckl@kEe0BFFSoUQgBCsfqKIB4OmCOpt7//1g1GOooGOkoGOsomKCpBwA). An important case here is that the **tail** of a list with 1 element is equal to `[]`. You can [test that here](https://tio.run/nexus/prolog-swi#@5@RmpgSX5KYmROfWlFSlJhckl@kEe0BFFSoUQgBCsfqKIB4OmCOpt7//1g1GKIpAwA).
```
% State that an empty array is truthy.
a([]).
% If the list is not empty (covered by the previous line), we need to check
% whether the Head is equal to 2 or whether the head is truthy.
% After that, we only need to check if the remaining list is truthy.
a([Head | Tail]) :- (Head = 2; a(Head)), a(Tail).
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
F;2E
```
[Try it online!](https://tio.run/nexus/jelly#@@9mbeT6/3D7o6Y1//9Hc3FGG8XqgEgdCA3iQjgQPkQQKBYLZhnCFAMhhB1tCFHMFQsA "Jelly – TIO Nexus")
## How it works
```
F;2E
F flatten
;2 append 2
E all elements are equal
```
[Answer]
# Octave, 13 bytes
```
@(x)~any(x-2)
```
[**Verify all test cases.**](https://tio.run/nexus/octave#S7PV09P776BRoVmXmFepUaFrpPk/JbO4QEM9pKg01UpdkytNI9ooFkLpQBlAAR0wDyYAFQaKxgKZEP1uiTnFMAMMoQYgDAJCqGC0IdSg/wA)
This is an anonymous function taking one input argument, `x`. It subtracts `2` from all elements, checks if there are any non-zero elements. It negates the output to get `true` for cases where all values are zero.
This works because `x-2` works for matrices of all sizes, including the empty matrix, `[]`.
`x-2` would be sufficient if there couldn't be empty matrices in the input.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 3 bytes
```
2=p
```
[Try it online!](https://tio.run/nexus/matl#@29kW/D/f3S0UaxOtKEOkDSKBQA "MATL – TIO Nexus")
Technically, this could just be
```
2=
```
Since an array containing any zero elements is falsy, but this seems cheap.
[Answer]
# [Mathics](http://mathics.github.io/), 28 bytes
```
Select[Flatten@#,#!=2&]=={}&
```
[Try it online!](https://tio.run/nexus/mathics#S7P9H5yak5pcEu2Wk1hSkprnoKyjrGhrpBZra1tdq/Y/oCgzr8QhzaHaSAeIjGqBiAsuVl2rU12LxAeqMa6t/Q8A "Mathics – TIO Nexus")
[Answer]
## [Retina](https://github.com/m-ender/retina), ~~13~~ 10 bytes
*Thanks to Kritixi Lithos for saving 3 bytes.*
```
\W|\b2
^$
```
[Try it online!](https://tio.run/nexus/retina#U9VwT/gfE14Tk2TExRWn8v9/tFEsV7SRDogEMnXATDAPJADkxwJpQ5ASqDogBHGjDSHqAA "Retina – TIO Nexus")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
˜YQP
```
[Try it online!](https://tio.run/nexus/05ab1e#@396TmRgwP//0dFGsTrRRjpA0igWAA "05AB1E – TIO Nexus")
**Explanation**
```
˜ # flatten list
YQ # check each element for equality to 2
P # product of list
```
[Answer]
# JavaScript (ES6), ~~22~~ ~~19~~ ~~23~~ 22 bytes
```
a=>!/[^2,]|22/.test(a)
```
---
## Test it
```
f=
a=>!/[^2,]|22/.test(a)
console.log(" "+f([2])+": "+JSON.stringify([2]))
console.log(" "+f([2,2])+": "+JSON.stringify([2,2]))
console.log(" "+f([[2],[2,2],2])+": "+JSON.stringify([[2],[2,2],2]))
console.log(" "+f([])+": "+JSON.stringify([]))
console.log(" "+f([[],[]])+": "+JSON.stringify([[],[]]))
console.log(f([1])+": "+JSON.stringify([1]))
console.log(f([22])+": "+JSON.stringify([22]))
console.log(f([2,2,2,1])+": "+JSON.stringify([2,2,2,1]))
console.log(f([[1,2],2])+": "+JSON.stringify([[1,2],2]))
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 5 bytes
```
∧/2=∊
```
[Try it online!](https://tio.run/nexus/apl-dyalog#@@/4qG3Co47l@ka2jzq6/v93VDDiAmIwqfGoq8lIUwdMKQAZIBoo/Kh3DYTUgbAMIRqAEMQCKtIwBKk2AgA "APL (Dyalog Unicode) – TIO Nexus")
### Explanation
```
∧/ Only
2= 2s are equal to
∊ any of the elements in the enlisted form of the right argument
```
[Answer]
# Mathematica, 15 bytes
```
FreeQ[x_/;x!=2]
```
It also works in Mathics. [Try it online!](https://tio.run/nexus/mathics#S1OwVfjvVpSaGhhdEa9vXaFoaxT7P6AoM69EwUFLIU1B30GhutqoVkeh2kgHTIE4EDaYCxYCitSCGIZgdTDVQAgWqDaEqK79DwA)
[Answer]
# Mathematica, 24 bytes
```
Cases[t=Flatten@#,2]==t&
```
Pure function returning `True` or `False`. After `Flatten`ing the nested array and calling it `t`, `Cases[t,2]` returns the list of elements that match the "pattern" `2`, and `==t` checks whether that's the whole list.
# Mathematica, 29 bytes
```
(#//.{2->{},{{}..}->{}})=={}&
```
Not as short, but more fun. Starting from the input `#`, two replacement rules are applied until the result stops changing (`//.`): first, all `2`s are replaced by `{}`s; and then any list whose entries are all empty sets (`{{}..}`) are replaced (repeatedly) by empty sets. If the rest is an empty set (`=={}`), we win.
[Answer]
# [Haskell](https://www.haskell.org/), 36 bytes
An anonymous function, takes a `String` and returns a `Bool`.
Use as `(all((==2).fst).(reads=<<).scanr(:)[]) "[2,2,2,1]"`
```
all((==2).fst).(reads=<<).scanr(:)[]
```
[Try it online!](https://tio.run/nexus/haskell#LYpBCsMgEEX3PYWELmYwEeKyxFzEuhBrqWBscSw9vlUJA3/@@7zDhqRCKj5bV67fFEPyJA77gTstO3E@sWVnE@f0ev/AMUIUw6lO2RgBlJIonlRQQPb2QWrbUJCzKcMNtalVS3PRcu7Z6jzqoD40Nu2vXTm9dh31enp/ "Haskell – TIO Nexus")
# How it works
* Haskell doesn't have builtin mixed-type lists, so we take a string as argument.
* `scanr(:)[]` generates a list of all suffixes of the string.
* `(reads=<<)` tries to parse a number at the beginning of each suffix, combining the successes into a list of tuples `(n,restOfString)`.
* `all((==2).fst)` checks if all the parsed numbers are `2`.
[Answer]
# [Python 2](https://docs.python.org/2/), 38 bytes
```
lambda l:l.strip('[],2')==l*('22'in l)
```
[Try it online!](https://tio.run/nexus/python2#VY7RCoMwDEWf7VcEX9KOTrCPQvcjXcHOKQjVlZo38dtdrTBcApfkXHLJoJ@7d9Pr7cA3vloojoGjsVKh0NrfOCqF4wxe7AQaDIOjCqOs/I3yshzGSS4wIZbVJlaYOqv6j0hdX2LqMyLvlrHhE4Eg/UFNRp1bet1SW8U@eNf1HAEloshmiONMUK4b3B@wbmWVridHnCQM/LgUYv8C "Python 2 – TIO Nexus")
Takes in a string without spaces, outputs a bool.
Checks if removing all the characters `'[],2'` of `l` gives the empty string. Also checks that `22` is not a substring -- if it is, the input `l` is used in place of the empty string to compare to the result of removal, and that always fails.
[Answer]
# Ruby, ~~28~~ ~~23~~ 22 bytes - 5 bytes saved by G B
```
->x{x.flatten-[2]==[]}
```
Despite "flatten" being really long, it's still shorter than regex based solutions or recursive stuff that has to rescue errors in the base case. Ruby's built-in conflation of sets and arrays, however, is amazingly useful sometimes.
[Answer]
## JavaScript (ES6), 26 bytes
```
f=a=>a.map?a.every(f):a==2
```
### Test cases
```
f=a=>a.map?a.every(f):a==2
console.log(f([2]))
console.log(f([2,2]))
console.log(f([[2],[2,2],2]))
console.log(f([]))
console.log(f([[],[]]))
console.log(f([1]))
console.log(f([22]))
console.log(f([2,2,2,1]))
console.log(f([[1,2],2]))
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 4 bytes
```
2-a~
```
[Try it online!](https://tio.run/nexus/matl#@2@km1j3/3@0kQ4QxgIA "MATL – TIO Nexus")
**Breakdown:**
```
% Implicit input
2- % Push 2 to the stack, and subtract from input
a % Any non-zero elements?
~ % Negate to get true for cases where all elements are zero.
```
---
Well, [outgolfed](https://codegolf.stackexchange.com/a/120365/31516). But I'm keeping this, since I'm quite happy I managed this all on my own (even though the task is super simple).
[Answer]
# R, 28 bytes
```
function(x)!any(unlist(x)-2)
```
`unlist(x)` turns a (nested) list into a vector. Then `2` is subtracted from that vector. `any` converts (with a warning) numeric to logical and checks if there are any `TRUE`s. This is inverted with `!` and output.
This works with nested lists because `unlist` by default works recursively to unlist all list entries of the initial list.
This also works with empty lists, because `unlist(list())` becomes `numeric()`, an empty numerical vector. Coercion by `any` makes it `logical()`, which is interpreted as `FALSE` by `any`, and then reversed to `TRUE` by `!`.
[Answer]
# [Python 3](https://docs.python.org/3/), 55 bytes
No cheating. Uses nested list as input.
```
f=lambda a:all(type(x)!=int and f(x)for x in a if x!=2)
```
[Try it online!](https://tio.run/nexus/python3#PY3BCoAgEETP@RXbTaGLHQW/RDxsmCCYiXSwrzdtKRZm5w0D07yOeGwOARXGyK8777yKWYd0ASYHvpM/C1QICRCChzrrVbQ/M2wyq12GLvQHEhBT2DP7OvmV@5E3ksrMKjbl0qf5mBXtAQ "Python 3 – TIO Nexus")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
F=2Ạ
```
[Try it online!](https://tio.run/nexus/jelly#@@9ma/Rw14L///9HRxvF6ihEG@kogGijWAA "Jelly – TIO Nexus")
Slightly different than Leaky's algorithm.
Explanation:
```
F=2Ạ
F Flatten
=2 Check if equal to 2 (vectorizes)
Ạ Check if there isn't any falsey value
```
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~14~~ 11 bytes
```
^(\W|2\b)+$
```
[Try it online!](https://tio.run/nexus/retina#U9VwT/gfpxETXmMUk6SprfL/f7RRLFe0kQ6IBDJ1wEwwDyQA5McCaUOIEpCoCYQJhCDBaEOIagA "Retina – TIO Nexus")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
2‚˜Ë
```
[Try it online!](https://tio.run/nexus/05ab1e#@2/0qGHW6TmHu///j442itWJNtIBkkaxAA "05AB1E – TIO Nexus")
[Answer]
## JavaScript (ES6), ~~53~~ ~~50~~ 48 bytes
```
_=>(_+"").split`,`.map(c=>!c?2:c).every(c=>c==2)
```
*Saved 5 bytes, thanks to @Shaggy!*
### Test Cases :
```
let f =
_=>(_+"").split`,`.map(c=>!c?2:c).every(c=>c==2)
console.log(f([2]))
console.log(f([2,2]))
console.log(f([[2],[2,2],2]))
console.log(f([]))
console.log(f([[],[]]))
console.log(f([1]))
console.log(f([22]))
console.log(f([2,2,2,1]))
console.log(f([[1,2],2]))
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes
```
˜DOsg·Q
```
[Try it online!](https://tio.run/nexus/05ab1e#@396jot/cfqh7YH//0cb6UBhLAA "05AB1E – TIO Nexus") or [Try All Tests!](https://tio.run/nexus/05ab1e#K6v8f3qOi39x@qHtgf8rlQ7vt1JQstf5Hx1tFKsTbaQDIhFMEAMkAKKA2BAkDpUEQhA32hCiLhYA "05AB1E – TIO Nexus")
```
˜D # Flatten and duplicate
O # Sum one copy
sg· # Get double the length of the other copy
Q # Check if they are equal
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 21 bytes
```
->x{x*?!!~/[^2!]|22/}
```
Using a regex is actually shorter, because joining an array also flattens it.
## How it works
```
->x{
x*?! -> Join array using an exclamation mark
!~ -> String does not contain
/[^2!] -> characters different from '2' or '!'
| -> or
22/ -> '2' repeated at least twice
}
```
[Try it online!](https://tio.run/nexus/ruby#S7P9r2tXUV2hZa@jWKcfHWekE1tjZKRf@79AIS062ig2lgvMgNGGMIYRUOo/AA "Ruby – TIO Nexus")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
2ṁ⁼
```
[Try it online!](https://tio.run/##y0rNyan8/9/o4c7GR417/h9uf9S0Bojc//@PjuZSUIg2itUBUzpQBkgAwoMKQIWBorGxXApACsQ1hOpC6AZCqGC0IUx3bCwA "Jelly – Try It Online")
### How it works
```
2ṁ⁼ Main link. Argument: A (array)
2ṁ Mold 2 like A. This replaces each number in A by 2.
⁼ Test if the result is equal to A.
```
[Answer]
# Java 8, ~~126~~ ~~55~~ 27 bytes
```
s->s.matches("(\\W|2\\b)+")
```
Port of [*@KritixiLithos*'s amazing Retina answer](https://codegolf.stackexchange.com/a/120356/52210), excluding the `^...$`, since `String#matches` always matches the entire String and adds the `^...$` implicitly.
-2 bytes thanks to @Jakob for reminding me of `^...$` isn't necessary for `String#matches`.
[Try it here.](https://tio.run/##jZCxDoIwEIZ3nuLC1EYggZXoG8ji4AAMR6lahJbYamKUZ8eCLC7YNLmkue@@P3cNPjBUPZdNfR1Zi1rDHoV8eQBCGn47IeOQTV@ASqmWowRGDuYm5Bk0TW1j8GzRBo1gkIGELYw63OmoQ8MuXBOfFMXxnRRFRTc@HdMJ7@9Va/Fl6qFEDZ2NXcR5CUi/mYenNryL1N1EvW2ZVhIZMeLnSenTOX6NCVwoqwpm1Il2EVpfucr9M8QuyzlewD4XXR7/XGDwhvED)
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 4 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
Ḟ2=p
```
[Try it online!](https://Not-Thonnu.github.io/run#P2hlYWRlcj0mY29kZT0lRTElQjglOUUyJTNEcCZmb290ZXI9JmlucHV0PSU1QjIlNUQlMjAtJTNFJTIwMSUwQSU1QjIlMkMyJTVEJTIwLSUzRSUyMDElMEElNUIlNUIyJTVEJTJDJTVCMiUyQzIlNUQlMkMyJTVEJTIwLSUzRSUyMDElMEElNUIlNUQlMjAtJTNFJTIwMSUwQSU1QiU1QiU1RCUyQyU1QiU1RCU1RCUyMC0lM0UlMjAxJTBBJTVCMSU1RCUyMC0lM0UlMjAwJTBBJTVCMjIlNUQlMjAtJTNFJTIwMCUwQSU1QjIlMkMyJTJDMiUyQzElNUQlMjAtJTNFJTIwMCUwQSU1QiU1QjElMkMyJTVEJTJDMiU1RCUyMC0lM0UlMjAwJmZsYWdzPUM=)
#### Explanation
```
Ḟ2=p # Implicit input
Ḟ # Flatten the list
2= # Check for == 2
p # All are true?
# Implicit output
```
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-e`, 3 bytes
```
2-ž
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpJuqlLsgqWlJWm6FkuMdI_uW1KclFwMFVhw0z7aKJYr2kgHRAKZOmAmmAcSAPJjgbQhSAlUHRCCuNGGEHUQcwA)
```
2- Minus 2
ž Check if all elements are zero
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~13~~ 10 bytes
```
2#2&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73@j9hO3KQGyk9j@gKDOvJFpZ1y7NQTlWrS44OTGvrpqr2qhWB0jogCkQB8IGc8FCQJFaIIOr2hCsEKYcCMEC1YYQ5Vy1/wE "Wolfram Language (Mathematica) – Try It Online")
`` is `\[VectorLessEqual]`.
] |
[Question]
[
(Based on [this closed challenge](https://codegolf.stackexchange.com/questions/229794/drawing-a-grid-using-and-in-python-using-the-least-bytes-possible#229794), [related](https://codegolf.stackexchange.com/questions/58243/16-bit-binary-grid))
Given an integer n > 1, draw a grid composed of the characters: "-" "+" and "|". However, since I want the grid to look nice, the horizontal component should be 2 wide.
Trailing spaces for each line are not required.
#### Examples:
n = 2
```
|
--+--
|
```
n = 3
```
| |
--+--+--
| |
--+--+--
| |
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins!
[Answer]
# [Python 3](https://docs.python.org/3/), 49 bytes
```
lambda n:f'\n{"--+"*~-n}--\n'.join([' |'*~-n]*n)
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPKk09Jq9aSVdXW0mrTjevVlc3Jk9dLys/M08jWl1BoUYdJBqrlaf5Py2/SCFTITNPoSgxLz1Vw0hHwUzTikuhoCgzr0QjTSNTUxPG0fwPAA "Python 3 – Try It Online")
[Answer]
# Python 3, ~~70 62 60~~ 58 bytes
```
lambda n:f"-{'-+-'*~-n}-\n".join([f" {' | '*~-n} \n"]*n)
```
Thanks to @Underslash, @Jonathan Allan for removing 4 bytes.
[Answer]
# JavaScript (ES6), ~~67~~ 66 bytes
Recursive.
```
f=(n,k=n*2*(n*=3)-n)=>k--?` -|+
`[k%n?~-k%n%3&2|k/n&1:4]+f(n,k):''
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYjTyfbNk/LSEsjT8vWWFM3T9PWLltX1z5BQbdGmyshOls1z75OF0iqGqsZ1WTr56kZWpnEaqeB9Glaqav/T87PK87PSdXLyU/XSNMw0tTkQhUxxhAx0dT8DwA "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), ~~61~~ 58 bytes
*Saved 3 bytes thanks to @EliteDaMyth*
The straightforward way.
```
n=>`${s=' |'[R='repeat'](--n)}
${'--+'[R](n)}--
`[R](n)+s
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1i5BpbrYVl1BoUY9OshWvSi1IDWxRD1WQ1c3T7OWS6VaXVdXGygTqwHk6upyJUCY2sX/k/PzivNzUvVy8tM10jSMNDW5kEVQeWkaxgTkTTQ1/wMA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes
```
UO⊖׳N⊖⊗θ |¶--+
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98/KSc/L13DJTW5KDU3Na8kNUUjJDM3tVjDWEfBM6@gtMSvNDcptUhDU1NTRwFZlUt@aVIOkC4ESSgpKNTE5OnqaitpWv//b/xftywHAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
UO
```
Draw a rectangle...
```
⊖׳N
```
... width `3n-1`...
```
⊖⊗θ
```
... height `2n-1`...
```
|¶--+
```
... filled with `|` and `--+` on alternate lines.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `rj`, 15 bytes
```
`+--| `½*ẋfḢvḢ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=rj&code=%60%2B--%7C%20%20%60%C2%BD*%E1%BA%8Bf%E1%B8%A2v%E1%B8%A2&inputs=3&header=&footer=)
Port of [hyper-neutrino's Jelly answer](https://codegolf.stackexchange.com/a/229980/80050)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
“+--“| ”ẋḊ¥⁺€
```
[Try it online!](https://tio.run/##y0rNyan8//9RwxxtXV0gWaOg8Khh7sNd3Q93dB1a@qhx16OmNf8Pt0f@/28KAA "Jelly – Try It Online")
-2 bytes thanks to Jonathan Allan
Returns a matrix of characters.
```
“+--“| ”ẋḊ¥⁺€ Main Link
“+--“| ” ["+--", "| "]
¥ Apply last two to a list and X
ẋ Repeat the list X times
Ḋ Remove the first element
€ To each row,
⁺ Do the above
```
[Answer]
# Haskell, 42 bytes
```
n%a=tail$[1..n]>>a
f n=n%[n%"+--",n%"| "]
```
[Try it online!](https://tio.run/##PcgxCgIxEAXQ3lN8BgO7aAIKlpkTaGUZU0zh4mB2CGvsvHtUBKsH7yaP@7WU3s1JbKJlnXYhWGaW1QSL5pI52nhP248vgHKfRQ0Rs9QThovCM@qi1qBg/nV9tnNbjoZhgo7f/g/RiLQP4ZD7Gw "Haskell – Try It Online")
Defines `f :: Integer -> [String]`.
`[1..n]>>a` means: for each element of `[1..n]`, cycle through all elements of `a`. Then, `tail` removes the first one. So `3%"+--"` evaluates to `"--+--+--"`.
`%` does double duty, first acting on `String`s to make the two grid rows, and then on `[String]` to transform them into whole grid.
(The tempting 39-byte `f n|g<-tail.([1..n]>>)=g[g"+--",g"| "]` is thus foiled by the [monomorphism restriction](https://wiki.haskell.org/Monomorphism_restriction).)
[Answer]
# Excel, 62 bytes
```
=LEFT(REPT(IF(MOD(SEQUENCE(2*A1-1),2)," |","--+"),A1),3*A1-1)
```
With gridlines turned off, it looks the same as the single string with line feeds.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 37 bytes
```
->n{[' |'*~-n]*n*"
#{['--']*n*?+}
"}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOlpdQaFGXatONy9WK09LiUsZKKKrqw7i2GvXcinV/k/LL1LIVMjMUzDS0zPlUigoLSlWSIvOjIUwuVLzUv4DAA "Ruby – Try It Online")
### [Ruby](https://www.ruby-lang.org/), 37 bytes
A very similar approach, also 37 bytes:
```
->n{[' |'*~-n]*n*"
#{'--+'*~-n}--
"}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOlpdQaFGXatONy9WK09LiUu5Wl1XVxssUKury6VU@z8tv0ghUyEzT8FIT8@US6GgtKRYIS06MxbC5ErNS/kPAA "Ruby – Try It Online")
[Answer]
# APL, 44 bytes
```
{1 1↓⊃⍪/,/⍵ ⍵⍴⊂2 3⍴'+--| '}
```
`2 3⍴'+--| '` gives:
```
+--
|
```
`⍵ ⍵⍴⊂2 3⍴'+--| '` gives n×n tiles, and `⍪/,/` joins them together.
For example n = 3:
```
+--+--+--
| | |
+--+--+--
| | |
+--+--+--
| | |
```
And finally `1 1↓⊃` discloses and drops the first column and row.
```
| |
--+--+--
| |
--+--+--
| |
```
Works in both Dyalog APL and GNU APL.
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqQwXDR22TH3U1P@pdpa@j/6h3qwIQP@rd8qiryUjBGMhQ19bVrVFQUK8F6lAw4kpTMAUA)
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `j`, 19 bytes
```
:`+--``| `"*$ẋfḢvḢ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=j&code=%3A%60%2B--%60%60%7C%20%20%60%22*%24%E1%BA%8Bf%E1%B8%A2v%E1%B8%A2&inputs=5&header=&footer=)
Ports my Jelly answer. I'll stop for a bit to give other people time to answer.
```
:`+--``| `"*$ẋfḢvḢ Full Program
: Duplicate X
`+--` Push "+--"
`| ` Push "| "
" Pair into ["+--", "| "]
* Repeat each X times
$ẋ Repeat that X times
f Flatten
Ḣ Remove first row
vḢ Remove first column from each
j flag: output top of stack separated by newlines
```
[Answer]
# [J](http://jsoftware.com/), 34 bytes
```
'| +-'{~<:@+:$#:@6(,:+&2)@$~*&3-1:
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/1WsUtHXVq@tsrBy0rVSUrRzMNHSstNWMNB1U6rTUjHUNrf5rcqUmZ@QrpCkYQRjq6jABY3QBk/8A "J – Try It Online")
Consider 3 as input:
* `#:@6...$~*&3-1:` Six in binary `#:@6` expands to `1 1 0` and "input times 3 minus 1" is 8 `*&3-1:`, so we extend `1 1 0` that far:
```
1 1 0 1 1 0 1 1
```
* `(,:+&2)@` Stack that with 2 added to itself:
```
1 1 0 1 1 0 1 1
3 3 2 3 3 2 3 3
```
* `<:@+:$` Now extend that to length "2 times input minus 1":
```
1 1 0 1 1 0 1 1
3 3 2 3 3 2 3 3
1 1 0 1 1 0 1 1
3 3 2 3 3 2 3 3
1 1 0 1 1 0 1 1
```
* `'| +-'{~` And use that to index into the grid characters:
```
| |
--+--+--
| |
--+--+--
| |
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-l`, ~~28~~ ~~24~~ 23 bytes
```
@>*@>:["+--""| "]XaRLa
```
[Try it online!](https://tio.run/##K8gs@P/fwU7Lwc4qWklbV1dJqUZBQSk2IjHIJ/H///@6Of@NAQ "Pip – Try It Online")
### Explanation
Same idea as [my Python answer](https://codegolf.stackexchange.com/a/230001/16766), implemented a bit more directly:
```
["+--""| "] List of two strings
Xa Repeat each string n times
RLa Repeat the whole list n times
@>: All but the first item of the list (: forces @> to be
lower precedence than X and RL)
@>* All but the first item of each string in the list
Autoprint (implicit), one string per line (-l flag)
```
[Answer]
# [C (clang)](http://clang.llvm.org/), 71 bytes
```
l;f(n){for(l=n*3,n=n*2*l-l;--n;)putchar(n%l?"| +--"[n/l%2*3+n%3]:10);}
```
[Try it online!](https://tio.run/##LYzNCgIhFIX38xQXQfAnqRRaZEMPUi1EsIQ7t5im1eSzm0JncT74DpxoIga614o@CZJres4CR1JuQ62tQoPeGPLy9VniI8yCOJ7ZF0Abwy60RW6V08Td7bjfSV9qpgWmkEnIdYD@1kWGESz4xhMcGrXO0HdIIkvf2N7fgl1J/cO6LUOpPw "C (clang) – Try It Online")
```
l=n*3 line length (\n included)
n=n*2*l-l total characters count
for(..;--n) while we iterate backwards :
n%l?..:10 > put a return at end of line or..
"| +--"[n/l%2*3+n%3] > take the proper char to put
```
[Answer]
# [Python 2 or 3](https://docs.python.org/), ~~49~~ ~~46~~ 42 bytes
*-4 bytes thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546)*
```
lambda n:([("+--"*n)[1:]," |"*~-n]*n)[1:]
```
Returns a list of lines. [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPSiNaQ0lbV1dJK08z2tAqVkdJQaFGSatONy8WKvI/Ma9YwVYhTcNYk4uroCgzr0QDKKIJZSopaXKl5RcpFOWXK2TmKQBlrLgUIFJAIc3/AA "Python 2 – Try It Online")
### Explanation
It's easy to generate this grid:
```
+--+--+--
| | |
+--+--+--
| | |
+--+--+--
| | |
```
Then we can trim off the first line as well as the first character of each line.
Since the latest golf, the code works a *little* differently:
```
([("+--"*n)[1:]," |"*~-n]*n)[1:]
"+--"*n # Repeat the horizontal line pattern n times
( )[1:] # and remove the first character
" |"*~-n # Repeat the other pattern n-1 times
# (trailing spaces aren't required, so
# we don't have to remove anything)
[ , ] # Put those two strings in a list
*n # Repeat the list n times
( )[1:] # and remove the first element
```
[Answer]
# 6502 machine code, Apple 2, 61 bytes
I got a bit carried away...
$130 - $F3 = $3D (61 decimal) bytes
Listing:
```
0000F3r 1 n := $f0
0000F3r 1 c := $f1
0000F3r 1 ; X register contains n
0000F3r 1 86 F0 grid: stx n
0000F5r 1 CA dex
0000F6r 1 86 F1 stx c
0000F8r 1 A6 F1 @loop: ldx c
0000FAr 1 A9 rr @cloop: lda #<coldiv
0000FCr 1 A0 rr ldy #>coldiv
0000FEr 1 20 rr rr jsr msgoutay
000101r 1 CA dex
000102r 1 D0 F6 bne @cloop
000104r 1 20 8E FD jsr CROUT
000107r 1 C6 F0 dec n
000109r 1 F0 19 beq @done
00010Br 1 A6 F1 ldx c
00010Dr 1 A9 rr @rloop: lda #<rowdiv
00010Fr 1 A0 rr ldy #>rowdiv
000111r 1 20 rr rr jsr msgoutay
000114r 1 CA dex
000115r 1 D0 F6 bne @rloop
000117r 1 A9 rr lda #<rowend
000119r 1 A0 rr ldy #>rowend
00011Br 1 20 rr rr jsr msgoutay
00011Er 1 20 8E FD jsr CROUT
000121r 1 4C rr rr jmp @loop
000124r 1 60 @done: rts
000125r 1
000125r 1
000125r 1 A0 A0 FC 00 coldiv: ASZ " |"
000129r 1 AD AD AB 00 rowdiv: ASZ "--+"
00012Dr 1 AD AD 00 rowend: ASZ "--"
000130r 1
```
Example run called with
```
ldx #4
jsr grid
```
[](https://i.stack.imgur.com/pwnue.png)
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 71 bytes
```
n->[print(concat([[" ","--";"|","+"][j+1,t+1]|j<-r]))|t<-r=[2..2*n]%2]
```
[Try it online!](https://tio.run/##DcZBCoAgEADAr8hCoOkK2bHsI8seIjDysIl49O/Waaac9cG7jBSH4EGlPtL09cp1Nk0ESoEDRNig/7HAlO3iml245x0rG9Pbb6TgfZiFp8Aj6dWMDw "Pari/GP – Try It Online")
Thanks to alephalpha for saving 39 bytes.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 46 bytes
```
->n{(2..n*2).map{|x|[" -"[x%=2]*2]*n*"|+"[x]}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWsNITy9Py0hTLzexoLqmoiZaSUFXKbpC1dYoVguI8rSUarSB/Nja2v8FpSXFCmnRRrFcIBYXlGsW@x8A "Ruby – Try It Online")
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), ~~46~~29 bytes [SBCS](https://github.com/abrudz/SBCS)
```
{⍉1↓⍉⊃,/⍵⍴⊂(⍵+⍵-1)3⍴'| +--'}
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q37U22n4qG0ykHrU1ayj/6h366PeLY@6mjSALG0g1jXUNAaKqNcoKGjr6qrXAgA&f=S1Mw4kpTMAZiEyA2BQA&i=AwA&r=tryAPL&l=apl-dyalog&m=train&n=f)
* saved 17 thanks to @Razetime tips!
(⍵+⍵-1)3⍴'| +--' we build the entire column e.g.
```
|
+--
|
+--
|
```
Then :
```
⍵⍴⊂ ⍝ n copies of that column
,/ ⍝ concatenate
⊃ ⍝ disclose
⍉1↓⍉ ⍝ transpose, drop line, re transpose
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 841 bytes
```
->>>>>+++++[>+++++>+++++<<-],[+>-[<-->-]>[>>>>+>+<<<<<-]>>>,]+++[<+++>-]+[-<<<<<[->+>+>+<<<]>>>[<<<+>>>-]<<<+]->>>>>->->->>>[<+++++++++[>+>+>+<<<-]>>>>>>]->--[<<+>>-]>[<<+++++>>-]<<[[->>>>>+<<<<<]<]<+[--[>>>>>>>..>.<<<<<<<<-]+<<<<<[[<<<+>>>-]<<<[->>>+>+>+<<<<<]>>>>+>-<[>[[-]<[-]<->>>>>[+++++++++>>>>>]<<<<<+>>>>]<[--<<<<<]]>[++>>>--<<[>>>>>]>]<<]<<+]++++++++++.[-]-<+[--[->>++[-<<<+[->>[-]<<[<+>-]<[>+>>+<<<-]<<<<+]-[>>>>>]<<<+[--[>[>+>-<<-]>[<+>-]>+[->->>>..>.<<<<<]>+[->>>+++++++++++++..--.-----------<<<]<<<<-]+<<<<<[[<<<+>>>-]<<<[->>>+>+>+<<<<<]>>>>+>-<[>[[-]<[-]<->>>>>[+++++++++>>>>>]<<<<<+>>>>]<[--<<<<<]]>[++>>>--<<[>>>>>]>]<<]<<+]>[>+>+<<-]>[<+>-]>[->>>>+++++++++++++..-------------<<<<]<++++++++++.[-]<]<<]+<<<<<[[<<+>>-]<<[->>+>>+>+<<<<<]>>>>+>-<[>[[-]<[-]<<->>>>>[+++++++++>>>>>]<<<<<+>>>>>]<[--<<<<<]]>[++>>--<[>>>>>]>]<<<]<<+]
```
edit1, thank you for the suggestion by [Radvylf Programs](https://codegolf.stackexchange.com/users/79857/radvylf-programs)
this work by using 5 cells per digit, 1 for original number, 1 for row number, 1 for column number, and 2 for verifying that help to make the number system work.
[Try it online!](https://tio.run/##zVJBTsQwDLznFb17nRNHyx@xfAAkpBUSByTeX2bsULpoBVfSNmljjz0z6dP74/Xt5eP5dd/VOYQjeunZTPMS4hqm6poelecIGGP4uCRBRoimbKEVCmVW5TEpsApWTb5kt9O6GKxe2@q@YFUcIwey0J94ErDO7loRi3k1TVwSSG6kz@nT1gC3JnZDpeByCMpWpzbCUTqNT3eIg6I0rQJIv6Jn43MMZrI8dppHQgJCg8K/hcpEbTQaRVhpfnsn/IgSZ7TUaMlyxNq9OBgsuEextvKHIGcVPVvQW@uMt2OeUxU3xrbm8vHfGFbK5KysT/yOjJ8q@DPc2g27kp6dlH39RzwA/13W37ruCsPGWdbSte8Pnw "brainfuck – Try It Online")
also, I edited the first one(adding "+" version) to get a better result. here
# [brainfuck](https://github.com/TryItOnline/brainfuck)(adding "+" version) ,~~273~~ 198 bytes
```
-[>+>+>+<<<-]>>> >>> >>> >+++++[<+++<+++++<<++++++<++>>>>>-]<<[<+++++>-]>[<+++>-]<<-<++<<<[->>>..>.<<<<]>>.<<<<[->[->+>+<<]>[<+>-]>[>>>>..--.++<<<<-]>>>>..<<<.<<<[->+>+<<]>[<+>-]>[>>..>.<<<-]>.<<<<]
```
[Try it online!](https://tio.run/##ZU5BCoAwDPuK99G@IPQjYwcVBBE8CL5/Zql4sVvXNEu6Lde8n9u9Hr1kdKtRxgJgLSKmL3VfwQOCyDK6GGENqMkRh6BIwxCjGkXu4cTgaFWS3HpPFjlDQjOXL/9BgtDT8tO/Y9nk9N4f "brainfuck – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 43 bytes
```
.+
$*
1
$_¶$_¶
1
+--
T`-+` |`¶.+¶
1A`
%`^.
```
[Try it online!](https://tio.run/##K0otycxL/P9fT5tLRYvLkEsl/tA2EAYytXV1uUISdLUTFGoSDm3T0wYJOiZwqSbE6XH9/28MAA "Retina 0.8.2 – Try It Online") Explanation:
```
.+
$*
```
Convert to unary.
```
1
$_¶$_¶
```
Create `2n` rows of `n` `1`s.
```
1
+--
```
Replace each `1` with `+--`.
```
T`-+` |`¶.+¶
```
Change those to `|` on alternate lines.
```
1A`
```
Delete the first line of `--+`s.
```
%`^.
```
Delete the leading `+`s or `|`s on each line.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 93 bytes
```
n=>(' |'[r='repeat'](--n)+' 0')[r](n+1).slice(0,-1).split(0).join('\n'+'--+'[r](n)+'--\n');
```
[Try it online!](https://tio.run/##HcoxDgIhEEDRq2w3M8Eh2NgYvMi6BUHWsCEDAWLl3ZG1@3n5h/u45mssnSW/wtjtEPtAWJYvrNVCDSW4DhsyC6nJBmitG4q6km4p@oDmwmeXFDsa0keOgvAUUMCs4D/T2ZPoPnyWllPQKb9xxxtN@gE "JavaScript (Node.js) – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 14 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
╬^û╗i§║╜P◙ƒ═½\
```
[Run and debug it](https://staxlang.xyz/#p=ce5e96bb6915babd500a9fcdab5c&i=2%0A3%0A4%0A5%0A6&m=2)
Similar to the Jelly answer.
[Answer]
# [PowerShell], 53 bytes
```
&{$c=$n-1;@(" |"*$c)*$n -join "`n$(""--+""*$c)--`n"}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNydFNzi9K/a@SZ2vyX61aJdlWJU/X0NpBQ0lBoUZJSyVZU0slT0E3Kz8zT0EpIU9FQ0lJV1dbCSyjq5uQp1T7/z8A "PowerShell Core – Try It Online")
] |
[Question]
[
June 2020 is a month in which June 1st corresponds to Monday, June 2nd corresponds to Tuesday, ... June 7th corresponds to Sunday. For reference, here's the `cal` of June 2020.
```
June 2020
Su Mo Tu We Th Fr Sa
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
```
Given a year and a month in the format `[year, month]`, output two distinct values that tell whether this month starts on a Monday.
## Test cases
```
[2020,6] -> True
[2021,2] -> True
[1929,4] -> True
[1969,1] -> False
[1997,5] -> False
[2060,1] -> False
```
## Specification
* The input can be in any format you prefer for your answer, e.g. numeric list, numeric tuple, etc. It doesn't have to be taken in this rigid format (it's JSON by the way).
* However, making the input a Date object is a loophole here. You shouldn't make the input a Date object.
* The month in the input doesn't have to be 1-indexed - it can also be 0-indexed.
* You need to support all years after 1582 (the start of the Proleptic Gregorian calendar), up to the year 9999.
[Answer]
# Excel, ~~44~~ ~~34~~ ~~23~~ ~~19~~ 18 bytes
```
=2=MOD(A3&"-"&A2,7
```
*-11 thanks to Adam* and *-4 thanks to Shazback*
*-1 thanks to [this](https://codegolf.meta.stackexchange.com/a/19037/78850)*
## Original Answer
```
=(TEXT(DATE(A2,A3,1),"ddd")="Mon")
```
Ensure that the year is placed in cell `A2` and the month in `A3`.
*:( Crossed out 44 is still 44.*
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~26~~ 24 bytes
```
->d{Time.gm(*d).monday?}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6lOiQzN1UvPVdDK0VTLzc/LyWx0r72f4FCWnS0kYGRgY5ZbCwXjGeoYwTjGVoaWeqYIHhmljqGCJ6luY4pQp@ZAUjuPwA "Ruby – Try It Online")
You'll never guess what this does.
Edit: -2 bytes from Dingus.
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + GNU utilities, ~~25~~ ~~22~~ 19 bytes
```
date -d$1-1|grep ^M
```
[Try it online!](https://tio.run/##S0oszvj/PyWxJFVBN0XFUNewJr0otUAhzvf/f67/RgZmBrqGAA "Bash – Try It Online")
Or [verify the test cases online](https://tio.run/##NY1BCsIwEEX3OcUQupPYJmglUOtKd@INhNgMppA2JbbqwrvHsdjNPIY3f/7NPFxqzAg1DDHco@mgqvjxcuLJmhFB2EwK@blHHOB6TiQYa1wXLEyr9xJh7OVajxDRWPBtjwzABhoA63x5y7Of4VSUW3zm/eT9fIGNC38J@xqyA5/TPSZVqEKUjCCFYlIrLTaEUgtJ0DuxJVcWtH0B).
The input is passed as an argument in the format `year-month`, and the output is the exit code (0 for truthy, 1 for falsey, as usual).
[Answer]
# JavaScript (ES61), ~~33 26~~ 25 bytes
*1: This works in Chrome, Node and Edge Chromium*
*Saved 7 bytes thanks to @Shaggy*
*Saved 1 byte thanks to @l4m2*
Using a built-in. Takes input as `([year, month])`.
```
a=>/^M/.test(new Date(a))
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1k4/zldfryS1uEQjL7VcwSWxJFUjUVPzf3J@XnF@TqpeTn66RppGtJGBkYGOWaympoK@vkJIUWkqF6YCQx0jPAoMLY0sdUyQFWCqMLPUMYSqcEvMKcZihqW5jik@FUYGZgaoZvwHAA "JavaScript (Node.js) – Try It Online")
## How?
### Converting the input to a Date object
The `Date()` constructor expects either:
```
Date(year, month [ , date [ , hours [ , minutes [ , seconds [ , ms ] ] ] ] ])
```
or:
```
Date(value)
```
In the first syntax, `month` must be 0-indexed.
In the second syntax, *value* is coerced to a string (unless it's *undefined* or it's an object) and parsed as such. Therefore, a 1-indexed month is expected in that case.
According to the ECMAScript specification:
>
> The function first attempts to parse the format of the String
> according to the rules (including extended years) called out in Date
> Time String Format ([20.3.1.15](https://www.ecma-international.org/ecma-262/9.0/index.html#sec-date-time-string-format)). If the String does not conform to
> that format the function may fall back to any implementation-specific
> heuristics or implementation-specific date formats.
>
>
>
So `[2020,6]` is turned into `"2020,6"` and parsed using implementation-specific heuristics which happen to work in V8-based engines when a comma is used as a separator. This also works with [several other symbols](https://tio.run/##hcxLDoIwAADRvafA@mkhgmBYiYoLT@GugcZISGss0YTL13AAnPXLTKc/2jfv52tIrWtNCI2z3vUm691DWfONbnowShzyvIhKEceLeV/Ou5xclPJvv4L/GnwDvgWX4An4DjwFz8D34EfwCvwEfga/gNfgV/A7@Dh5CD8).
### Regular expression
When passed as the argument of `/^M/.test()`, the Date object is implicitly converted into a string in the following format:
```
"DDD MMM 01 YYYY 00:00:00 GMT[...]"
```
where:
* `DDD` is the 3-letter abbreviation of the day of the week
* `MMM` is the 3-letter abbreviation of the month
* `YYYY` is the year in numerical format
Therefore, the string begins with a `"M"` iff the day of the week is **Mon**day.
---
# JavaScript (ES6), ~~62 61~~ 60 bytes
Using a formula. Takes input as `(year)(month)`, where *month* is 0-indexed.
```
y=>m=>(y-=m<2,y+=(y&~3)-3*~~(y/100)>>2)%7=='045204263153'[m]
```
[Try it online!](https://tio.run/##fcwxDoIwFADQ3VN0Uf5XK@0HSkhsR0/gZhwIgtEANaAmXbh6dTOxCfvLu5fvcqyG2@PJe3upfaO906bTBhzX3Z62bqPBraYEebKeJnCxFAKNIVzmWkcizUikpBKZJdGpO/vK9qNt611rr9AACRIIinEmEVkcs@PwqheBkQg0a2RBBUL6ZwKkvkj@0KFsx3AqcoRsHpFQIpz8Bw "JavaScript (Node.js) – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/) 18.0, 9 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?") ([SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set"))
Anonymous tacit prefix function.
```
1=7|1⎕DT⊂
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/@vnpJYWaz@qG@qc6R6SlpesTrXo442l5BHbRMMtUFSjzpmPOpq/m9oa15jCJHpavqfBpR@1NsHlHjUu@ZR75ZD640ftU0EGhIc5AwkQzw8g/@nKRgZGBnomHGBGYY6RkCGoaWRpY4JmGFmqWMIZlia65iC1ZgZ6BgCAA "APL (Dyalog Unicode) – Try It Online") (uses a model, `∆DT`, instead of `⎕DT` so it can run using TIO's current version)
`⊂` enclose the argument (because we need the date to be a scalar)
`1⎕DT` convert Date-Time to days since 1899-12-31 (this will "pad" the date to the first of the month)
`7|` division remainder when divided by 7
`1=` does one equal that?
[Answer]
# Wolfram Language 36 bytes
```
DayName@DateObject@{#,#2,1}==Monday&
```
**examples**
Naming the function `f`, to save space and increase clarity.
```
f = DayName@DateObject@{#, #2, 1} == Monday &
f[2020, 6]
f[2021, 2]
f[1929, 4]
f[1969, 1]
f[1997, 5]
f[2060, 1]
(*True*)
(*True*)
(*True*)
(*False*)
(*False*)
(*False*)
```
[Answer]
# [Red](http://www.red-lang.org), 33 bytes
```
func[b][1 = pick(to now b)+ 1 10]
```
[Try it online!](https://tio.run/##Pc3NCsIwEATge59i6EkRIQkaiaAP4XXZQ5sfLNqkhIiPH3/JnuZjGDZ7Vy/eEXfhWMMjWhqZJE5YJntblYSYnhjXG0hIwTWk7Ad7hRuKB3V4HymhBDQ3SKg/pFEGuwZtIBvMAfu20eLTMC15igU0p7v7vei35x7hm5nrCw "Red – Try It Online")
The argument `b`is a block containing the year and the month. `now` is function returning the current date and time; `to now b` converts the input to a `date!` datatype. The odd thing is that currently [Red](http://www.red-lang.org) assigns the missing data (the day of month) 0 by default, but [Red](http://www.red-lang.org) being 1-indexed, thus calculates the last day of the previos month instead of the first day of the given month:
`to now [2020 6]` gives `31-May-2020`
That's why I add 1 to the resulting date. `date!` has among its path accessors `/weekday`, wich can be queried using indexing instead - `10` (tenth item). Too bad I can't use direct indexing using paths `/10`, because it only works on `words` (variables) and not on literal / unnamed data. That's why I use `pick`date `10`.
Finally I check if the weekday is 1 (for Monday).
[Answer]
# T-SQL, 47 bytes
```
SELECT 1/datepart(w,datefromparts(y,m,7))FROM i
```
(10 bytes saved thanks to @t-clausen.dk)
Assumes the [input is in a table](https://codegolf.meta.stackexchange.com/a/5341/38979) `i` with two columns, `y` and `m`. It assumes Sunday is set as the first day of week, which [is the default setting](https://docs.microsoft.com/en-us/sql/t-sql/statements/set-datefirst-transact-sql?view=sql-server-ver15). Outputs 1 if the month starts on a Monday, 0 otherwise.
`datepart(w,datefromparts(y,m,7))`, the day of week of the *seventh* day of the month returns 1 (=Sunday) if the month starts on a Monday, and a higher number otherwise. Since it's an integer, the division is rounded down to zero in the latter case.
[Demo](http://sqlfiddle.com/#!18/53ba04/5)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 36 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Ð3‹12*+>₂*T÷s3‹Xα©т%D4÷®т÷©4÷®·(O7%Θ
```
Here we go again. 05AB1E has no date builtins, so everything is done manually. This solution is a derivative of [my answer here](https://codegolf.stackexchange.com/a/173126/52210).
Takes both inputs separated, the \$month\$ as first input and \$year\$ as second.
[Try it online](https://tio.run/##yy9OTMpM/f//8ATjRw07DY20tO0eNTVphRzeXgwS8Dy38dDKi02qLiaHtx9ad7EJSK4EMw9t1/A3Vz034/9/My4jAyMDAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVCcej/wxOMHzXsNDTS0rZ71NSkFXJ4ezFIIOLcxkMrLzapupgc3n5o3cUmILkSzDy0XcPfXPXcjP86/6OjjQyMDHTMYnUUQCxDHSMQy9DSyFLHBMIys9QxhLAszXVMIerMDIBisQA).
**Explanation:**
The general formula to calculate the *Day of the Week* manually is:
$${\displaystyle h=\left(q+\left\lfloor{\frac{13(m+1)}{5}}\right\rfloor+K+\left\lfloor{\frac{K}{4}}\right\rfloor+\left\lfloor{\frac{J}{4}}\right\rfloor-2J\right){\bmod{7}}}$$
Where for the months March through December:
* \$q\$ is the \$day\$ of the month (`[1, 31]`)
* \$m\$ is the 1-indexed \$month\$ (`[3, 12]`)
* \$K\$ is the year of the century (\$year \bmod 100\$)
* \$J\$ is the 0-indexed century (\$\left\lfloor {\frac {year}{100}}\right\rfloor\$)
And for the months January and February:
* \$q\$ is the \$day\$ of the month (`[1, 31]`)
* \$m\$ is the 1-indexed \$month + 12\$ (`[13, 14]`)
* \$K\$ is the year of the century for the previous year (\$(year - 1) \bmod 100\$)
* \$J\$ is the 0-indexed century for the previous year (\$\left\lfloor {\frac {year-1}{100}}\right\rfloor\$)
Resulting in in the day of the week \$h\$, where 0 = Saturday, 1 = Sunday, ..., 6 = Friday.
[Source: Zeller's congruence](https://en.wikipedia.org/wiki/Zeller%27s_congruence)
Since we only care about \$q=1\$, we can use that to golf 2 bytes. With the formula above, the result would be \$2\$ for Mondays (and thus requiring a leading `$` to push both 1 AND the input-month; as well as a trailing `2Q` to check if the result equal 2). But if we remove the \$q+\$ part, the result would be \$1\$ for Mondays (in which case we can use the implicit input-month, removing the `$`; and also use the `==1` builtin `Θ` instead of `2Q`).
```
Ð # Triplicate the (implicit) input-month
3‹ # Check if the month is below 3 (Jan. / Feb.),
# resulting in 1 or 0 for truthy/falsey respectively
12* # Multiply this by 12 (either 0 or 12)
+ # And add it to the month
# This first part was to make Jan. / Feb. 13 and 14
> # Month + 1
₂* # Multiplied by 26
T÷ # Integer-divided by 10
s3‹ # Check if the month is below 3 again (resulting in 1 / 0)
Iα # Take the absolute difference with the second input-year
© # Store this potentially modified year in the register
т% # mYear modulo-100
D4÷ # mYear modulo-100, integer-divided by 4
®т÷©4÷ # mYear integer-divided by 100, and then integer-divided by 4
®·( # mYear integer-divided by 100, doubled, and then made negative
O # Take the sum of all values on the stack
7% # And then take modulo-7 to complete the formula,
# resulting in 0 for Sunday, and [1, 6] for [Monday, Saturday]
Θ # Check if this is equal to 1 (thus a Monday)
# (after which the result is output implicitly)
```
Note that I've also used \$\left\lfloor{\frac{26(m+1)}{10}}\right\rfloor\$ instead of \$\left\lfloor{\frac{13(m+1)}{5}}\right\rfloor\$, since 05AB1E has a 1-byte builtin for both `26` and `10` (`₂` and `T` respectively), saving a byte on the `13`.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-!`](https://codegolf.meta.stackexchange.com/a/14339/), ~~6~~ 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ÓÐN e
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LSE&code=09BOIGU&input=MjAyMAo2)
```
ÓÐN e :Implicit input of integers U=y and V=m
Ð :Create date object from
N : The array of inputs [U,V] with the date defaulting to the 1st
e :0-indexed day of the week
Ó :Decrement
:Implicit output of Boolean negation
```
[Answer]
# [Python 2](https://docs.python.org/2/), 56 bytes
```
lambda y,m:date(y,m,1).weekday()<1
from datetime import*
```
[Try it online!](https://tio.run/##TY3BCgIhFEX3foVLjUeolGHUn8zGUEnqjSIPwq93pja5u@ceuLd2epbVjHRfxtvjI3jeAa/BUxR7AC2PnxhfwXchb5qlVpB/JWWMPGMtjQ6jtrwST8Ioo8BKNrEG82ftjIOTZFNh3X4xsbvAeR6wava/AyfHBg "Python 2 – Try It Online")
[Answer]
# [Julia 1.0](http://julialang.org/), 39 bytes
```
using Dates
x*y=dayofweek(Date(x,y))==1
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/v7Q4My9dwSWxJLWYq0Kr0jYlsTI/rTw1NVsDJKZRoVOpqWlrawhVF5JaXMLlAFRbomBkYGSgZYbgGGoZQTmGlkaWWiZccJ6ZpZahgq2tQlpiTnEqXNTSXMsUXdTIwMwASe1/AA "Julia 1.0 – Try It Online")
I am posting this seperate from [my other answer](https://codegolf.stackexchange.com/a/206079/4397), since it doesn't use the point-free style, and thus doesn't have the cool side-benifits of also working for year only etc.
But it is shorter
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~61~~ ~~60~~ 59 bytes
Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
Saved a byte thanks to [nununoisy](https://codegolf.stackexchange.com/users/95691/nununoisy)!!!
```
f(y,m){y-=m<2;m=(y+y/4-y/100+y/400+"bed=pen+fad."[m])%7<1;}
```
[Try it online!](https://tio.run/##bVDLboMwELznK1ZISFCWYshLyNBL1a8AVBEwjQ88hDlAEd9OlyQgDvXK411rZuRxZv9k2TwXxoClOQ52WAYeL0NjsAbnZA@Oy9jSEWo3kYeNqKwizd@1qExM/Rq4fJrLVFaGCeMBaMmqg0Gk7XcXJRDC6DGPIYGLru/5BJcF/CvdXdjEN01ZV919FZ3RxSMyPOGeIvpG9J3IHxwYyZGKLfUiZfe0fYP26aHF/ZcX9/4n7bOGsJ@P2s5WPduibsFYZklqxukIQMlfUdPXPPKYzmskksnBsuSaeVmKVCszkglugWRi8o3VtCQuDE3PEfQc7I8FdRVX9MB/tQgKKZEKwy29TFbH6TDNfw "C (gcc) – Try It Online")
Straight-up calculation that uses 0-based months.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 53 bytes
```
lambda x:date(*x,1).weekday()<1
from datetime import*
```
[Try it online!](https://tio.run/##HcpLDsIgFIXheVdxh9DcGECtYnQlyAADRKI8QkhsV49tZ1/@c8rS3jkdr6V2/3j2r4kva2C@WdMcGWfk9PBz7mPNQuidD77mCNvWQnQQYsm1jb3UkBoZlCeBgs8VAoQESgkmGE4aN3AUK7gUEk87Jol8h7zgef9MbC1aD7T/AQ "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + Standard Unix Tools, 17 bytes
```
cal $1|grep ' 6$'
```
* Input like "06 2020".
* Exit Code is `0` if first day of month is Monday and `1` if not.
[Try it online!](https://tio.run/##S0oszvj/PzkxR0HFsCa9KLVAQV3BTEX9/3@u/wZmCkYGRgYA "Bash – Try It Online")
In some implementations, additional two bytes are necessary:
```
cal $1|grep ' 6 *$'
```
[Answer]
# [Perl 5](https://www.perl.org/) `-MTime::Local -pa`, ~~38~~ 33 bytes
*Shaved 5 bytes with help from @DomHastings*
```
$_=(gmtime timegm 0,0,0,1,@F)=~Mo
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3lYjPbckMzdVAUSk5yoY6ICgoY6Dm6ZtnW/@//@mCkYGRgb/8gtKMvPziv/r@oYAFVpZ@eQnJ@YAeaZ6hgZ6Bv91CxIB "Perl 5 – Try It Online")
Input is space separated: 0-indexed month followed by year.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 28 21 bytes
```
(d $i -U %A)-like'M*'
```
[Try it online!](https://tio.run/##RcuxCsIwEIDhvU9xlEpbyUESNJKxIDjpIroHe6GHsRXb4iA@e@wiGT9@/ufwptfYUQjxTBM2gd0IeHIPghbw6sJMcFjC3k2U@bm/TTz04KuCa/jEqoWCAS@wamoMfKfyuC7jN/OADLmWWgqTJymh/1JWW7FJMlaoJLsT2/QZubT4Aw "PowerShell – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), 35 bytes
```
m->{m.set(5,1);return m.get(7)==2;}
```
[Try it online!](https://tio.run/##jVDBaoNAEL3nKwYhoMXdqDQJxppLTymEFnIqIYetrmZTXWV3FELIt9vVJtLSSw/LY@a9eTvzTqxl5JR@dqKsK4VwMjVtUBT0IZr86WWNTFBUsieTgmkNWyYkXCYAdfNRiAQ0MjTQViKF0nD2DpWQ@f4ATOXaGaQAb4qnImHIn55ZwWXK1BoyiLuSrC8l1Rztues7keLYKAklzU1n6cRxEF27aHDIKmW3TAFyjatf3gBCIpy5IWPYSOQ5V7RlRcNfM7uXU10XAm2LWM7eOzjRj6myknj8x5h/cIgfwWwG75wdXXjpE6L05nS/aVhie7O8N/tbNtLEJBNuj5@PyuH4vnK/l3HBn4@q3VkjL2nVIK1NqpjZ1lSvYKqn0nKHKFzIaI/2aOjcpq@T/l27LvACjyx68EnQ@WEQkkcDi5D4BsIlmRtu4RH/Cw "Java (JDK) – Try It Online")
## Explanation
The input is taken as a `java.util.Calendar`. First we modify the calendar to force the first of the month, then we check if that day of week is a Monday.
```
m -> {
m.set(Calendar.DAY_OF_MONTH, 1); // DAY_OF_MONTH is the constant 5
return m.get(Calendar.DAY_OF_WEEK) // DAY_OF_WEEK is the constant 7
== Calendar.MONDAY // MONDAY is the constant 2. Don't ask why, no one knows.
}
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 108 bytes
```
\d+
$*
^(11? )1
12$*1$1
\G1
13$*
(1+)\1{4}1{27,} (?=(1*)\2{399})(?=(1*)\3{3})(1*)(?=\4{99})
$1$2$3
^(1{7})*$
```
[Try it online!](https://tio.run/##NYyxCgIxEET7/YoUKyQ5i8zmTEghV95PBFHQwsZC7EK@PW4QqzdvBub9@Dxft3Gw@3XU@0Ls6WKBzTgQhD0YVHfN8bcsrqKtHU3ysRu7nS28q9JiKd39NbaookmLurY5EYOF47xouTvPYyQjQQLJBGg1KFIIilTopChZTUIKXw "Retina 0.8.2 – Try It Online") Link includes speedup `^` so that the included test cases complete within TIO's time limit. Takes 1-indexed month first, then the year. Explanation:
```
\d+
$*
```
Convert to unary.
```
^(11? )1
12$*1$1
```
If the month is January or February, then add 12 and subtract 1 from the year.
```
\G1
13$*
```
Multiply the month by 13, which begins a form of [Zeller's congruence](https://en.wikipedia.org/wiki/Zeller%27s_congruence).
```
(1+)\1{4}1{27,} (?=(1*)\2{399})(?=(1*)\3{3})(1*)(?=\4{99})
$1$2$3
```
The month is integer divided by 5, but with 27 subtracted, which allows the calculation to result in Monday = 0. The year is separately divided by both 400 and 4, after which 1% of the year is skipped thus effectively subtracting it. The month calculation, `y/400` and `y/4` are then added to the remaining `(y-y/100)`. Note that Retina will attempt to match this expression more than once but will always fail because there is only one space in the input. However, these attempts make it very slow, so to optimise this the TIO link includes a leading `^`. The code will work without it eventually though.
```
^(1{7})*$
```
Test whether the result is a multiple of 7.
[Answer]
# Julia 41 bytes
(37 characters)
```
using Dates
isequal(1)∘dayofweek∘Date
```
It's fairly rare to find a code-golf that can be answered in point-free style in Julia.
An interesting side effect of this, is that if you give this just 1 input it will tell you if the year starts with a Monday.
And if you give it 3 inputs it will tell you if a given day is a Monday.
[Answer]
# [R](https://www.r-project.org/), 39 bytes
```
strftime(paste0(scan(,''),'-1'),'%u')<2
```
[Try it online!](https://tio.run/##K/r/v7ikKK0kMzdVoyCxuCTVQKM4OTFPQ0ddXVNHXdcQRKqWqmvaGP03MjAy0DX7DwA "R – Try It Online")
[Answer]
# PHP 7.4, 43 bytes
This code creates an anonymous function where you pass the month and year, returning `true` for monday, and `false` if the 1st day it isn't on a monday.
```
fn($Y,$M)=>!~-date(N,strtotime("$Y-$M-1"));
```
You can try this on: <http://sandbox.onlinephpfunctions.com/code/5bf01ff098ef40b4b45bbc82e3b13a5e1b83f8d1>
---
An alternative solution could be just this (40 bytes):
```
fn($Y,$M)=>date(N,strtotime("$Y-$M-1"));
```
Which returns the week day, where 1 is monday, 2 is tuesday ....
I don't think this is in the spirit of the question.
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 80 bytes
```
from calendar import Calendar as C
f=lambda x:C().monthdayscalendar(*x)[0][0]==1
```
[Try it online!](https://tio.run/##NYxLCsMgGIT3OcW/1CJFbZvGgqscQ1zYphIhPjAuktNbGwjM4pthZtJe5hhuQ8q12hw9fMzyDZPJ4HyKucB4erPC2Fm5GP@eDGyvEeGrj6HMk9nXc4UuG1ZUN0nJasouFNQpixwGG9snuABKccop6TX5AyO8ARNckPsBvSDsAPEkj6PT05Zo3eH6Aw "Python 3.8 (pre-release) – Try It Online")
[Answer]
# T-SQL, 43 bytes
```
PRINT datediff(d,0,concat(@+@y*100,14))%7/6
```
the expression
```
datediff(d,0,concat(@+@y*100,14))%7
```
will return 0-6. 6 represent Monday - this is divided by 6(rounding off)
Mondays returns 1, other weekdays returns 0
**[Try it online](https://data.stackexchange.com/stackoverflow/query/1251596/does-this-month-start-on-a-monday)**
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 582 bytes
```
->+++[[>]>,>++++++[<-------->-]<[<++++++++++>-],>++++++[<-------->-]<[<+>-]+[-<+]->-]>>>[->>>>+>+<<<<<]>>>>[<<<<+>>>>-]<+>>>+++<+>+<[->-[>]<<]<[-]<[-<<<<->>>]>[-]>[-]>[-]>[-]>[-]+++>++>+++++>>+++>+++++>+>++++>++++++>++>+++++[-<+]->>>>[>>+>+<<<-]>>[>>>[-<<<<+>>>>]<<[->+<]<[->+<]>-]>>>[-<+<<+>>>]<<<[->>>+<<<]>[[-<+>]>[-<+>]<<<<[->>>>+<<<<]>>-]>>++++++++++[<+++++++>-]<<<<<<<[>>+>>>>--<<<<<<-]>>[-[->>+<]>[<]<]>>[-[->>+<]>[<]<]<<<[->+>>>>+<<<<<]>[-[->>+<]>[<]<]>>[-[->>+<]>[<]<]>>[-<<<<<<<+>>>>>>>]<<<<<<+++++++<<+>[>->+<[>]>[<+>-]<<[<]>-]>[-]+>[[-]<->]<[->+<]>>++++++++[<++++++>-]<.
```
[Try it online!](https://tio.run/##hVLLCgIxDPygGFk9eAr5kdCDCoIIHgS/f51J2gqKGLabR5NmJu3pcbzeL8/zbV3VRSTCm29o0THt4tosTKbA/5kEJaEmjQF3D8XPxcUojHjQElooocY5xgzkKhAgDSYXE1nfcMzXIpD8aLhMs3THNzM6JrYfcIgvEuIEhN4AIQmAanAwqQTsWzKSJBPcSXRUNjaLbPOsfo9tjpC8SxILB6HlJyTlIWwewPEdqC4y@zD@p2RwHDQ7E7oljIeTMl9AXSPa1AA4a1JtuIs5GP9kxYrtuu6Xw7LsXg "brainfuck – Try It Online")
Definitely not the shortest program here, this was more to see if it was possible to do. Expects input in the form of `YYYYMM` - the month needs to be 1-indexed and 2 characters wide. Outputs `1` if the month starts on Monday, `0` otherwise. This could be shortened by 21 bytes if the output was not ASCII.
Ungolfed:
```
-> reference
+++[ input 3 sets of 2 numbers
[>] find next zero
>,>++++++[<-------->-]< input number and sub 48 ascii
[<++++++++++>-] mul by 10
,>++++++[<-------->-] input next number and sub 48
<[<+>-] copy to previous cell
+[-<+]- move back to reference
>- dec counter
] end input
>>>
[->>>>+>+<<<<<] copy the month variable for comparison
>>>>[<<<<+>>>>-]<+>>>+++<+>+<[->-[>]<<]
<[-]<[-< if month is less than 3
<<<->>> decrement the year
]>[-]>[-]>[-]>[-]>[-] clear out comparison cells to store lookup table
0 3 2 5 0 3 5 1 4 6 2 4
+++>++>+++++>>+++>+++++>+>++++>++++++>++>++++ lookup table
+[-<+]- move back to reference
>>>> move to month
[>>+>+<<<-]
>>[>>>[-<<<<+>>>>]<<[->+<]<[->+<]>-] access lookup table for month
>>>[-<+<<+>>>]<<<[->>>+<<<]>
[[-<+>]>[-<+>]<<<<[->>>>+<<<<]>>-] copy table value to result
>>++++++++++[<+++++++>-]<<<<<<< add 70 to result to prevent wrap
[>>+>>>>--<<<<<<-]
>>[-[->>+<]>[<]<]
>>[-[->>+<]>[<]<] add century div by 4
<<<[->+>>>>+<<<<<]> add year
[-[->>+<]>[<]<]
>>[-[->>+<]>[<]<]>> add year div by 4
[-<<<<<<<+>>>>>>>] set up modulo
<<<<<<+++++++<<+>[>->+<[>]>[<+>-]<<[<]>-] all modulo 7
>[-]+>[[-]<->]<[->+<]>>++++++++[<++++++>-]<. display result
```
[Answer]
# [Befunge-93](https://github.com/catseye/Befunge-93), 81 78 bytes
```
&&:2`!#v_2->267+**2-55+/\:"d"/02-*\:"d"%\:"d"%4/\"d"/4/++++7%!.@
-1\++55< ^\
```
[Try it online!](https://tio.run/##S0pNK81LT/3/X03NyihBUbks3kjXzsjMXFtLy0jX1FRbP8ZKKUVJ38BIVwvMUoWQJvoxIGETfW0gMFdV1HPg0jWM0dY2NbVRUFCIi/n/38jAyEDBGAA "Befunge-93 – Try It Online")
## How does it work?
This is based on [a formula](https://cs.uwaterloo.ca/~alopez-o/math-faq/mathtext/node39.html) which gives the day of the
week given a date:
```
W = (k + floor(2.6m - 0.2) - 2C + Y + floor(Y/4) + floor(C/4)) mod 7
```
where
* `k` is the day of month,
* `m` is the month of the year, if years start with March (so
Mar = 1, Apr = 2, ..., Dec = 10, Jan = 11, Feb = 12).
* `C` is the century of the March adjusted year (so year = year - 1
in January and February).
* `Y` is the year in the century (March adjusted).
* `W` is the weekday, (Sun = 0, ..., Sat = 6).
We will be calculating
```
W' = floor((26m - 2)/10) - 2C + Y + floor(Y/4) + floor(C/4)) mod 7
```
the month will start with a Monday, iff `W' == 0`.
Breaking down the program gives us:
```
&& Reads year and month
:2`!#v_2-> If the month is January or February, subtract 1 from
-1\++55< ^\ the year, and add 10 to the month; else, subtract
2 from the month. (Years start in March).
267+**2-55+/ Calculate (2.6 * month - 0.2).
\:"d"/02-* -2 * Century (= int (year / 100))
\:"d"% Year in century (year % 100)
\:"d"%4/ 4 year leap year cycle adjustment (int ((year % 100) / 4))
\"d"/4/ 400 year leap year cycle adjustment
(int (int (year / 100) / 4))
++++ Sum them all
7% Mod 7.
!.@ Negate the result and print it -- if 0 (hence, first
day of the month is a Monday), then 1, else (not a
Monday) 0.
```
Edit: Saved three bytes.
[Answer]
# q, ~~33~~ 32 bytes
accepting the inputs as strings:
```
{2=mod["d"$"M"$x,".",-2#"0",y]7}
```
explanation
```
-2#"0",y /append "0" to 2nd input and take last 2 chars from result
x,".", /join by "."
"M"$ /tok, convert string to month type
"d"$ /cast to date type - returns 1st of month
mod[ ]7 /date mod 7, 0->sat,1->sun,2->mon,etc
2= /check if equal 2
```
run like:
```
q){2=mod["d"$"M"$x,".",-2#"0",y]7}["1929";"4"]
1b
```
[Answer]
# [Factor](https://factorcode.org/), 20 bytes
```
[ 1 <date> monday? ]
```
[Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQWFycn1yskJyYk5qXklikUFCUWlJSWVCUmVeiYM3FVc2lAATVCkYGRgYKZgq1CK6hghGca2hpZKlggsQ1s1QwROJamiuYIuk1MwDL1v6PBtI2KYklqXYKuflA6yvtFWL/p0HcZJebWKCg9x8A "Factor – Try It Online")
* `1 <date>` Create a timestamp object from the given year, month, and using 1 as the day.
* `monday?` Is it Monday? A builtin from the `calendar` vocabulary.
[Answer]
# TI-Basic, 15 bytes
```
2=dayOfWk(Ans(1),Ans(2),1
```
Input is taken from `Ans` as a list. Output is stored in `Ans` and is displayed. Assumes that the time and date are set correctly before the program is run. Outputs `1` if the month starts on a Monday and `0` if it does not. Only works on TI-84+/SE.
[Answer]
# [jq](https://stedolan.github.io/jq/), 50 bytes
```
.+[1]+(now|gmtime[3:8])|mktime|strftime("%w")=="1"
```
[Try it online!](https://tio.run/##yyr8/19PO9owVlsjL7@8Jj23JDM3NdrYyiJWsyY3G8SpKS4pSgMxNJRUy5U0bW2VDJX@/482tDSy1DGOBQA "jq – Try It Online")
Not that short, but it's different enough that I thought it might be interesting enough to post...
It expects a year and a 0-indexed month as a list, meaning `[2021,3]` for April, 2021.
```
.+[1]+( ) - append "day 1" to input
now|gmtime[3:8] - curr time breakout, drop Y/m/d fields
|mktime - convert to epoch time
|strftime("%w")=="1" - compare "day of week" to Monday
```
] |
[Question]
[
"Talk" is a baroquified accumulator-based language that is created in response to Dennis's [quote](https://chat.stackexchange.com/transcript/message/31809962#31809962) on talk.tryitonline.net.
```
Waiting for someone to create an esolang called talk.
```
. The "Talk" language has 4 commands:
* `00` If the accumulator is 0, set the accumulator to 0.
* `01` If the accumulator is 0, set the accumulator to 1.
* `10` If the accumulator is 1, set the accumulator to 0.
* `11` If the accumulator is 1, set the accumulator to 1.
## Input:
* The input can be taken via any acceptable input method by our standard I/O rules.
* There are two inputs, the initial accumulator value and the program. You can merge these two inputs into one input or split your input into valid commands (e.g. taking them as a list; e.g. `[00, 01, 00]`) if you like.
## Output:
* On the end of a command execution, the accumulator is outputted implicitly.
## Rules:
* The input *can* be a single string or character list.
* As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer, in bytes, wins.
* We take digits or strings/characters.
## Test cases:
```
0 0001111101 -> 1
0 000100 -> 1
0 11001000 -> 0
```
## Leaderboards
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
# Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
# Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
# Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the leaderboard snippet:
```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
```
var QUESTION_ID=190819;
var OVERRIDE_USER=8478;
var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&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(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.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(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}}
```
```
body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;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="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]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
y@/
```
Input is a single list: the accumulator, followed by the pairs.
[Try it online!](https://tio.run/##y0rNyan8/7/SQf//4fZHTWsi//@P5uKMNtBRAGKDWDBlCKIMUSiQYKwOVoUgHlzKECEG5hkgqYgFAA "Jelly – Try It Online")
### How it works
The `y` atom performs transliteration; **[a,b]**`y`**c** replaces **a** with **b**, so it returns **b** if **a=c** and **c** if **a≠c**.
`y@/` folds/reduces the input by `y` with swapped arguments, performing one transliteration per pair.
[Answer]
# [Python 3](https://docs.python.org/3/), 43 bytes
```
lambda s:re.sub("00|11","",s)[-1]
import re
```
[Try it online!](https://tio.run/##VY3LCsIwEEX3/YohqwajTHBXyJfUImmbasA8yGMh@O8xEbF4l2fOYfwz3Z09l01cykOaeZUQh6BOMc89QXxxThghLNLxyKdOG@9CgqBKUjFdFxlVBAFjVauGiLwNW8MJZTtG/EPVaexzJXTqNhfABX1jsDhjpF0jA5eTzwm0hf3X0EGdD9qmfutbAYdfQkGIb0XLGw "Python 3 – Try It Online")
The function takes a single string as input, where the first character is the initial state and the rest of the string represents the commands. This solution can be easily ported to other languages that have better support for regular expressions.
The difficult part is to prove the solution yields the correct outcome. To see this, we need a deep analysis of the commands. Firstly, we can see the commands have the following properties:
* **Property (1)**: commands `00` and `11` retain the accumulator state.
* **Property (2)**: commands `01` and `10` make the accumulator state the same as the second bit regardless of its original state.
Therefore, the final accumulator state is:
* **Case 1**: If no `01` or `10` command exists, the final state is the same as the initial state.
* **Case 2**: Otherwise, the last bit of the last `10` or `01` command.
Next we will show the solution yields the correct outcome in both cases. We will prove the statement for the final state `0` and the final state of `1` can be proved analogously. If the final state is `0` the input is in either of the following forms:
* `^0{2k+1}11(11|00)*`
For **Case 1**, the input string `s` must start with `2k+1` 0s, followed by `11` and `00` commands. Eliminating `00`s and `11`s yields a single `0`, which is the final state.
* `.+10{2k+1}11(11|00)*`
For **Case 2**, the input string ends with a `10` command, followed by zero or more `00` and `11` s. This pattern is equivalent to a `1` followed by `2k+1` 0s, and then zero or more `11`s and `00`s. Eliminating `00`s and `11`s leaves behind the last one of the `2k+1` 0s at the end of the string, which represents the final state.
Based on all the above, after eliminating `00`s and `11`s **simultaneously in one single pass** (`01001` is a counter-example if `00` is eliminated in one pass and then `11` in another pass) from the input `s`, the last character is the final state. Hence the correctness of the solution is proved.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 17 bytes
```
{m/.)>[(.)$0]*$/}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzpXX0/TLlpDT1PFIFZLRb/2vzVXWn6RgkZOZl5qsaZCNRdnrlW6fkyKtr41F2dxYqVCXZqGikGdiqEmV@1/AwUDAwNDEDAwVNC1UzDkgogYGMB4QBkQF8w34DJUQMhAxQA "Perl 6 – Try It Online")
Takes advantage of "You can merge these two inputs into one input if you like" by taking input as the accumulator value concatenated with the commands e.g. `1,[00,11]` is `10011`. If this isn't okay, than it's only 5 extra bytes to take it as [`f(accumulator, commands)`](https://tio.run/##K0gtyjH7n1upoJamYKvwvzpXX0/TLlpDT1PFIFZLRb82Xy26Lva/NVdafpGCRk5mXmqxpkI1F2euVbp@TIq2vjUXZ3FipUJdmoaKgY6KoSZX7X8DBQMDA0MQMDBU0LVTMOSCiBgYwHhAGRAXzDfgMlRAyEDFAA). Returns a match object that can be coerced to a string.
### Explanation:
```
{ } # Anonymous code block
m/ / # Find the first match from the input
.)> # Capture a number
[ ]* # Followed by any number of
(.)$0 # Pairs of identical characters
$ # Ending the string
```
Basically this works because the `00` and `11` commands do literally nothing, while the `01` and `10` commands just set the accumulator to the second digit of the command. If there are no commands, then it takes the initial value of the accumulator instead.
[Answer]
# [Zsh](https://www.zsh.org/), 33 bytes
The character list is passed as arguments, the initial value of the accumulator is passed as stdin.
```
read a
for x y;a=$[x^a?a:y]
<<<$a
```
[Try it online!](https://tio.run/##dYvBCsIwEETv@xUDBqqHQuKxTdX/EIWFJrQQGmhFW0u/PVqt8SDOwDLsm7l3VbDrzRhawyWYrG/RY8i5EMf@zHvOhhNprQWHiW5V7QxeTVc3JkfpyVzZoTMXpCnE/CULMR6y7YTnDEJR6RsTJN5W0XNeodhB0RfO96MI1QLUUotQkkKS4Edx@RdKegA "Zsh – Try It Online")
---
**39 bytes**: If the commands must be a single string
Input is `accumulator` `commands` as arguments.
```
for x y (${(s::)2})1=$[x^$1?$1:y]
<<<$1
```
[Try it online!](https://tio.run/##VcrBCsIwEITh@z7FgAttbrsea0TfQxQKSWihtNCItpY@ezQWD/7Hb@YVmxRKs6QwjJgwo@SljFVl9qvRI1@mG@uJtZqvZK1lTSs9m7bzGH3t0LW9P8AN5B91h@jv4EwUwGdyQ@@TQEQ0J4odlDYQQW6Dz5ZFviCkKAr82h5/IPQG "Zsh – Try It Online")
---
For fun, here's a **50 byte** recursive one-liner ([TIO](https://tio.run/##JcxBCsIwEIXhfU7xwFkoEpjJMhY8SIm0kJQWQgtWFAw5e0zsW/18A/Pd5zKdL6l0XUeJkrkOE6gnedTuxeU7iW1pXHaoYU0estUkuWT1mZcY8AyjR1zWcIPfVHiPEXt4QWtQU1UfCsgov62hMJhZ2lhwgqgDmNF2QL014T@w@gE "Zsh – Try It Online")):
```
<<<${${2+`f $[$1^${2[1]}?$1:${2[2]}] ${2:2}`}:-$1}
```
[Answer]
# [Python 3](https://docs.python.org/3/), 52 bytes
```
f=lambda a,s:s and f([s[1],a][s[0]==s[1]],s[2:])or a
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRIVGn2KpYITEvRSFNI7o42jBWJzEWSBvE2tqCeLE6xdFGVrGa@UUKif8LijLzSjTSNJQMlHQUlAwMDAxBwMBQSVOTC1POwABTHKgaJIEkg6TCEKwTqARFH1gUpA2LKBRgswcu8x8A "Python 3 – Try It Online")
*Fixed inconsistent return type thanks to Chas Brown*
Takes input as two strings; the accumulator and the code.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~11~~ 9 bytes
```
tġ₂≠ˢtt|h
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wv@TIQiDvUeeC04tKSmoy/v@PjlYyUNJRMjAwMAQBA0OlWB2EkIEBnAuUA/GBArEA "Brachylog – Try It Online")
Since it's been long enough that I've been able to forget the notion of [printing the accumulator after each command](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompkcdyx/u2vFwV2ftw60T/h9ZCBR6uHV6@qkNydXVJRl1GfYlJTUZteVA4drTC///j45WMlDSUTIwMDAEAQNDpVgdhJCBAZwLlAPxgQKxAA), I've formulated a significantly less naïve solution with some inspiration from Jo King's Perl answer.
```
| The output is
tt the last element of the last element of
t the last element of the input
ġ₂ split into length-2 slices
≠ˢ with equal pairs removed.
| If there is no such element, the input
h 's first element is the output.
```
Old solution:
# [Brachylog](https://github.com/JCumin/Brachylog), ~~18~~ 16 bytes
```
ġ₂ᵗc{th~h?tt|h}ˡ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w/8hCEGfr9OTqkoy6DPuSkpqM2tML//@Pjo5WMlCK1VEyMDAwBAEDQyAPWdDAAEkAKA8SAbJjAQ "Brachylog – Try It Online")
-2 bytes from changing the input format.
[Answer]
# JavaScript (ES6), 27 bytes
Takes input as `(a)(code)`, where *code* is a is list of 2-bit integers.
```
a=>c=>c.map(x=>a^=x==a+1)|a
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i4ZiPRyEws0KmztEuNsK2xtE7UNNWsS/yfn5xXn56Tq5eSna6RpGGhqRBskGRjoAAlDIGEIJwwMYzU1FfT1FQy58GsxMAApRACcWiDGgvQZGqDqA2ox@A8A "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), ~~47~~ 40 bytes
Takes input as `(a)(code)`, where *code* is a string.
```
a=>c=>c.replace(/../g,x=>a^=x%4==a+1)&&a
```
[Try it online!](https://tio.run/##dcxBCoAgEIXhfaeIoFAqHaHtdJRgMItCMjKi25tCy/p5y4@30kVeH8t@tpsbTZgwEPY6Thxmt6QNk0LIubmxpwHvskOkWvGqoqDd5p01wrqZTQw4KwBApUAVnOdS5ir7RgAJpH5Q/EjqZRFBeAA "JavaScript (Node.js) – Try It Online")
### How?
All possible cases are summarized below. The only two cases where we need to toggle the accumulator are \$(a=0,x=01\_2)\$ and \$(a=1,x=10\_2)\$.
```
a | x (bin) | int(x) % 4 | a + 1 | equal?
----+---------+------------+-------+--------
0 | "00" | 0 % 4 = 0 | 1 | N
1 | "00" | 0 % 4 = 0 | 2 | N
0 | "01" | 1 % 4 = 1 | 1 | Y
1 | "01" | 1 % 4 = 1 | 2 | N
0 | "10" | 10 % 4 = 2 | 1 | N
1 | "10" | 10 % 4 = 2 | 2 | Y
0 | "11" | 11 % 4 = 3 | 1 | N
1 | "11" | 11 % 4 = 3 | 2 | N
```
[Answer]
# [sed](https://www.gnu.org/software/sed/) -E, ~~26~~ 19 bytes
*A whopping **-7 bytes** from @Cowsquack by realizing removing all pairs works as well.*
```
s/(.)\1//g
s/.*\B//
```
Takes input concatenated together on stdin. Inspired by [Jo King's Perl answer](https://codegolf.stackexchange.com/a/190830/86147).
~~Strip trailing pairs~~ Remove all pairs, then get last digit.
~~[Try it online!](https://tio.run/##K05N0U3PK/3/v1hfw8CgxtBQU0tFX5@rWF9PS0NPU0U/xlD//38DIDAEAQNDLjDbwIALKABmGHABxbj@5ReUZObnFf/XdQUA "sed – Try It Online")~~
[Try it online!](https://tio.run/##K05N0U3PK/3/v1hfQ08zxlBfP52rWF9PK8ZJX///fwMgMAQBA0MuMNvAgAsoAGYYcAHFuEAsw3/5BSWZ@XnF/3VdAQ "sed – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~18~~ 11 bytes
```
(.)\1
!`.$
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0NPM8aQi0sxQU/l/38DIDAEAQNDLjDbwIALKABmGHDhlzWEqAAA "Retina 0.8.2 – Try It Online") Link includes test cases. Takes input concatenated. Saved 6 bytes thanks to @CowsQuack for pointing out that removing all doubled characters and then taking the last remaining character works, although in fact the port of @JoKing's original answer could have been golfed by 3 bytes even without that trick.
[Answer]
# [Haskell](https://www.haskell.org/), 29 bytes
Defines an unnamed function on the first line with type `(Foldable t, Eq b) => b -> t [b] -> b`. For the purposes of this code golf, we can instantiate it as `Char -> [String] -> Char` where the first argument is the accumulator and the second is a list of string with each string being a single command.
```
foldl(#)
a#[x,y]|a==x=y|1>0=a
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZvtfIS0/JyVHQ1mTK1E5ukKnMrYm0da2wrayxtDOwDbxf25iZp6CrUJKPpeCQkFRZl6JgopCmoK6gbpCtJKBgZKOgpKBIYg0RCKBIrEElAPZ2JQYwiRBZhnAFf4HAA "Haskell – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 38 bytes
```
lambda l:[y for*x,y in l if[y]!=x][-1]
```
[Try it online!](https://tio.run/##bYzBDoIwAEPvfEXlMqYz2eKNZF8yd5gCsmRsC4LC1yMkaNB4aZr2tXHs6uBPUyXPkzPNpTBwuRpRhXY/sBHWw8FWatQ7OWh1FHp61taVEHmC0NobwzU0jfHFnSH0Xew7yPJhXGb97DNKk/kjQkIttMbhwyeIrfVdVi0ohZTrnk4Z4YRBpZynDCkXi4qNzolmIILQ5B86@99avIvlg28g/g2t0Qs "Python 3 – Try It Online")
Based on [Joel's solution](https://codegolf.stackexchange.com/a/190840/20260). Takes input as a list of the initial accumulator value (length-one string) followed by the commands (length-two strings). Finds the last command with two unequal values, and outputs its second character.
To make this fall through to the initial accumulator value when there are no such commands, we make it so that the single-char initial value string passes the test. We do so by checking if a singleton list with the last character is unequal to a list of all preceding characters, which is passed by any length-one string or length-two string with two different characters.
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, ~~37~~ 33 bytes
```
$\=<>;s/(.)(.)/$\=$2if$\==$1/ge}{
```
[Try it online!](https://tio.run/##K0gtyjH9/18lxtbGzrpYX0NPE4j0gVwVo8w0IGWrYqifnlpb/f@/gYGBIQgYGHIZ/MsvKMnMzyv@r1uQAwA "Perl 5 – Try It Online")
Input is two lines: first line is the command sequence, second is the accumulator.
[Answer]
# [Python 2](https://docs.python.org/2/), 56 bytes
```
f=lambda a,c:f([a,1,0,a][int(c[:2],2)],c[2:])if c else a
```
[Try it online!](https://tio.run/##Xcq7DoAgDIXh3afoJiQdWkYSn4QwVJRo4i3q4tNjGVw843f@47mnfXOl5G6RtR8EBJPPJggyEkoM83abFLyL6GzEFJyPds6QYFyuEaQcpxaQDWNLxMTc2qb5kBBUFXVUn/9B9EPtqiqXFw "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 6 bytes
```
EÐḟṪṪo
```
[Try it online!](https://tio.run/##y0rNyan8/9/18ISHO@Y/3LkKiPL/FxsdXs51ePmxuY@a1kT@/x8drWRgYGAIAgaGSjpKBkqxOhAhAwM4FygH4qMJQFQYKsXGAgA "Jelly – Try It Online")
-2 bytes thanks to Nick Kennedy informing me of a rules change. (His proposed golf, `EÐḟFȯṪ`, seems somewhat more clever but has the same length as my previous solution minus `s2`.) The input format now takes the commands as a list of two-character strings, but the testing footer translates from the old format for convenience.
Translated from my newer Brachylog solution.
Old version:
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
ḢẎ⁼⁹a⁸o
s2ç@ƒ
```
[Try it online!](https://tio.run/##y0rNyan8///hjkUPd/U9atzzqHFn4qPGHflcxUaHlzscm/T/8PJjcx81rYn8/z86WsnAwMAQBAwMlXSUDJRidSBCBgZwLlAOxIcKxAIA "Jelly – Try It Online")
I'm not 100% sure this is correct, but it succeeds on all three test cases. Takes the commands as the left argument and the initial accumulator as the right argument.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 16 bytes
```
(+⌷13⍴0 1,9/⊢)/⌽
```
A tacit function which takes initial accumulator value and the program as a single integer list.
Maps the relevant sums of instruction and accumulator to an array.
Table: `(a→accumulator, i→instruction)`
```
a i a+i result
00 0 0 0
01 0 1 1
10 1 11 0
11 1 12 1
```
All other cases return the same value, so they are assigned to the preexisting value of `a`.
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/zW0H/VsNzR@1LvFQMFQx1L/UdciTf1HPXv/pwGlH/X2PepqPrTe@FHbRKCW4CBnIBni4Rn8P03BQMEAiAwVDMHIwJALIWRgAOaAhIGkAZxvAAA "APL (Dyalog Unicode) – Try It Online")
### Explanation
```
(+⌷13⍴0 1,9/⊢)/⌽ accumulator→a
/⌽ reduce the reversed array using th following function: (reducing happens from the right)
9/⊢) replicate a 9 times
13⍴0 1, concatenate with (0,1) and expand to 13 elements → (0 1 a a a a a a a a a 0 1)
(+⌷ sum first two elements and find element at that index in the array
```
### Solution which accepts a string
```
{{(13⍴0 1,9/⍺)[⍺+⍵]}/⌽(⍎¨((⍴⍵)⍴1 0)⊂('0',⍵))}
```
It was pretty ambiguous how the input was supposed to be taken, so I decided I'd leave this one in as well.
This was the original dfn, which was golfed down using Adám and Bubbler's advice.
[Answer]
# Regex (JS flavor), 32 bytes
```
^(0(..)*01|1((..)*01)?)(00|11)*$
```
[Try it online!](https://regexr.com/6nmi7)
Matches if output is 1, doesn't if output is 0. Global and multiline flags enabled in link to verify multiple test cases at once, but not necessary for solution. Did I format this submission correctly?
[Answer]
# Python, 111 bytes
```
def f(a,b):
c=a
for i in range(0,len(b)-1,2):
c=(not b[i])*(c or b[i] or b[i+1]) or c*b[i]*b[i+1]
return c
```
Ungolfed. EDIT: AHHH Someone beat me to it!
[Answer]
# [Haskell](https://www.haskell.org/), 36 bytes
```
f(x:y:s)=f s.last.(:[y|x/=y])
f _=id
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P02jwqrSqljTNk2hWC8nsbhET8MqurKmQt@2MlaTK00h3jYz5X9uYmaegq1CQVFmXomCikKagpKBgYEhCBgYKimoG6j/BwA "Haskell – Try It Online")
Takes input as `f(string)(char)` where the character is the accumulator and the string is the list of commands.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes
```
ø`:
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8I4Eq///o6MNdAxidRSAlCGIMkSh4IJYlED1geRiuQwA "05AB1E – Try It Online")
Zip, dump on the stack, replace.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 3 bytes
```
F|t
```
[Run and debug it](https://staxlang.xyz/#c=F%7Ct&i=%220%22+[%2200%22+%2201%22+%2211%22+%2211%22+%2201%22]%0A%220%22+[%2200%22+%2201%22+%2200%22]%0A%220%22+[%2211%22+%2200%22+%2210%22+%2200%22]%0A&a=1&m=2)
For each instruction, perform character translation.
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg), `-ir`, 16 bytes
```
"(!;½|':"=['_"|_
```
[Try it online!](https://tio.run/##y05N//9fSUPR@tDeGnUrJdto9Xilmvj//w0MDQ0MgMjgv25mEQA "Keg – Try It Online")
## Explained:
1. Takes the implicit input and right shifts the accumulators value to the bottom
2. Repeat the following (length of stack - 1 divided by 2) times
2.1. Shift the accumulator back to the top
2.2. Compare for equality with the first part of the command
2.2.1. If true, replace the accumulator, otherwise pop the replacement
Input is taken as the initial acc value concatenated with the source. E.g.
```
010011000
```
* First char is acc value
* Rest is program
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 8 bytes
```
{{)er}/}
```
[Try it online!](https://tio.run/##S85KzP1fWPe/uloztahWv/Z/3X8lAyWFaCUDIKlkYAgkDOEEkBsLAA "CJam – Try It Online")
Takes input on the stack in the form of `"0" ["00" "01" "11" "11" "01"]`. Does string replacement using every command.
[Answer]
# [Headass](https://esolangs.org/wiki/Headass), 22 bytes
```
U[{N-()]PNE:U(])U[:U;}
```
[Try It Online!](https://dso.surge.sh/#@WyJoZWFkYXNzIixudWxsLCJVW3tOLSgpXVBORTpVKF0pVVs6VTt9IiwiIiwiMFxuMFxuMFxuMFxuMVxuMVxuMVxuMVxuMVxuMFxuMSIsIiJd)
```
U[{N-()]PNE:U(])U[:U;} full program
U[ save initial state of accumulator to storage register
{ : } while
N-() input remains
U(]) ; if input == accumulator state
U[ set accumulator to next input
: else
U discard next input
]P print final state of accumulator
NE go to code block 1
block does not exist, exits with error
```
There is room for golfing maybe if I can avoid storing anything in the comparison register (i.e. having it remain 0 for the entirety of the program and never using `(`), but it might not be possible.
[Answer]
# Regex (any flavor), 15 bytes
```
(^|0)1(00|11)*$
```
[Try it on regex101!](https://regex101.com/r/ySrh84/1)
It was pointed out before that the problem can be simplified:
* `00` and `11` are no-ops. `01` unconditionally sets the value to 1 while `10` sets to 0.
* The output is 1 if and only if the input is 1 and the entire code is no-op or the last non-no-op command is `01`.
The regex precisely does the job: `(00|11)*$` after discarding no-ops at the end, the last thing found is `(^|0)1` the input 1 or a `01` command.
`1(00|11)*$` does not work because the 1 may be part of another no-op command `11`.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), ~~58~~ 40 bytes
Add one byte for a full program: change `f` to `$0`.
```
(($1=$2-a?a:$3,1))&&f $1 ${@:4}||echo $1
```
~~[58 bytes](https://tio.run/##VcxBCsIwEIXh/ZzigYEqUpjpMiIeRJRGO6WF0oIVXZScPWYsLnyrP99AbmHuUrvdLSkc3VLt6xbu7OSa27OXeHLirSX3BVZVrCPpvZvyK/jSSUyR3l0/KB4aGgz9qAc0E@krDJj1ibKEM6X8t8BV1EyjJgYzi40FGwitwAzbCvlmwl/gDEWB3wzkH4Q@ "Bash – Try It Online")~~
[Try it online!](https://tio.run/##dYtRC4JAEITf91cMdKgHCW71ZFj@lStXFA4PMupB/e2Xkl0P0Qwsu/vNXEzf@DrRg08SxYXapeZscrXfstZRVEMx1FDmh2kc5dq4@fYTPZvWCm5iKti2kyMqR/IwFr3ckaZQy5fmckmV68RneJuDl32D4gSmL1zmRwHyCniNBZgRI47xo9D8CzN6AQ "Bash – Try It Online")
The ternary will return false when `$1` is set to `0`, but the `,1` at the end ensures the whole `((expression))` will return true, *except* a syntax error.
When all the arguments are consumed, a syntax error happens and the recursion ends.
---
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes
```
F⪪η²F⁼θ§ι⁰≔§ι¹θθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBI7ggJ7NEI0NHwUhTUwEs4lpYmphTrFGoo@BY4pmXklqhkamjYKAJlHYsLs5Mz9NAEjbU1FEo1LTmCijKzCvRALL@/zdQMDAwMAQBA8P/umU5AA "Charcoal – Try It Online") Link is to verbose version of code. Takes separate arguments. Explanation:
```
F⪪η²
```
Split the instructions into pairs of digits and loop over them.
```
F⁼θ§ι⁰
```
If the accumulator is equal to the first digit...
```
≔§ι¹θ
```
... then assign the second digit to it.
```
θ
```
Print the accumulator at the end of the loop.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~13~~ 12 bytes
```
!dh2Ol4$Ys0)
```
Takes the input as a 2-column matrix where each row is a command, and a number
[Try it online!](https://tio.run/##y00syfn/XzElw8g/x0QlsthA8///aAMFA2sFAwVDawVDOAHkxnIZAAA) Or [verify all test cases](https://tio.run/##y00syfmf8F8xJcPIP8dEJbLYQPO/S8j/aAMFA2sFAwVDawVDOAHkxnIZcCHJAVlgEai0AUihAVTYEAA)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
fؽḂ⁹;Ṫ
```
A dyadic Link accepting the program as a list of integers on the left and the initial accumulator on the right which yields an integer.
**[Try it online!](https://tio.run/##ASQA2/9qZWxsef//ZsOYwr3huILigbk74bmq////WzMsMCwyLDBd/zA "Jelly – Try It Online")** Or see a [test-suite](https://tio.run/##y0rNyan8/z/t8IxDex/uaHrUuNP64c5V/w8vd9B/1LTm///oaAMdIDLUMQZCw9hYLh2YgAGMY6xjoGME5RrqRMOEYXwDhEoDhCqgcQj9xjBRIx0jGNMQwTQCWxwLAA "Jelly – Try It Online")
[Answer]
# [PHP](https://php.net/), 38 bytes
```
<?=strtr($argn,['00'=>'',11=>''])[-1];
```
[Try it online!](https://tio.run/##K8go@P/fxt62uKSopEhDJbEoPU8nWt3AQN3WTl1dx9AQRMVqRusaxlr//28ABIYgYGD4L7@gJDM/r/i/rhsA "PHP – Try It Online")
Basically port of [Jo King's idea](https://codegolf.stackexchange.com/a/190830/81663).
[Answer]
# [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 28 bytes
```
/~@/i~/i<
/=?/~iR:l}i{l1-=?!
```
[Try it online!](https://tio.run/##KyrNy0z@/1@/zkE/s04/04ZL39Zevy4zyCqnNrM6x1DX1l7x/38DBUMgNFAwgJIGAA "Runic Enchantments – Try It Online")
Takes input as a series of space separated bytes (Runic does not understand lists). The first byte is the initial state and every other byte is the program. No validation is performed (i.e. it assumes only valid programs are given as input and it doesn't care what value is used to represent `0` and `1`).
] |
[Question]
[
# Input
This task takes no input.
# Output
Your code should compute and print (or return)
\$\pi^y\$ for all \$y = \frac11, \frac12, \frac13, \frac14, \frac15, \frac16, \frac17, \frac18, \frac19, \frac1{10}, \frac1{11}, \frac1{12}\$. The first 20 digits of the output (truncated and without any rounding) should be correct in each case.
Here are the answers:
```
3.1415926535897932384
1.7724538509055160272
1.4645918875615232630
1.3313353638003897127
1.2572741156691850593
1.2102032422537642759
1.1776640300231973966
1.1538350678499894305
1.1356352767378998683
1.1212823532318632987
1.1096740829646979321
1.1000923789635869829
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~9~~ 8 [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")
```
(‚ç≥12)‚àö‚óã1
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG9qQMCjtgnGJlxAplsQkGloZGHO9aijveC/xqPezYZGmo86Zj2a3m34Hyj2XwEMCgA "APL (Dyalog Extended) – Try It Online") (`⎕PP←34` is Print Precision: 34 digits; `⎕FR←1287` is Float Representation: 128-bit decimal)
`○1` \$π×1\$
`(`…`)√` take the following roots of that:
‚ÄÉ`‚ç≥12`‚ÄÉ**…©**ndices 1 through 12
[Answer]
# JavaScript (ES7), 121 bytes
Computes as many digits as the precision of IEEE 754 allows and hardcodes the other ones.
```
_=>[32384,60272,2630,7127,[n=0]+593,2759,3966,4305,8683,2987,9321,69829].map(v=>(Math.PI**(1/++n)+'').slice(0,~(n==2))+v)
```
[Try it online!](https://tio.run/##Dci7DoIwFADQz7GXXmu5hT6GsjuYuBNiGgTFYEuEMPrr1TOeV9jD2n@mZTvGdB/y6PPNN60iZSvUkgwhaSXRlGSwjV52vHYKydQOldMaKyVrtNr@z1mDTlGJ2llynXiHhe2@YZewPcX1XBSsPHEegR8OINZ56gcm8cui9wTAd8h9imuaBzGnBxsZQP4B "JavaScript (Node.js) – Try It Online")
### Commented
```
_ => // input is ignored
[ 32384, 60272, 2630, 7127, // hard-coded digits for n=1 to n=4
[n = 0] + 593, // initialize n to 0, and set this entry to '0593' (n=5)
2759, 3966, 4305, 8683, // hard-coded digits for n=6 to n=9
2987, 9321, 69829 // hard-coded digits for n=10 to n=12
].map(v => // for each entry in the above array:
(Math.PI ** (1 / ++n) + '') // increment n; compute π**(1/n) and coerce it to a string
.slice(0, ~(n == 2)) // remove the last 2 digits if n=2,
// or only the last digit otherwise
+ v // append the hard-coded digits
) // end of map()
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + bc ~~+ coreutils~~, ~~51~~, ~~40~~, ~~39~~, 36 bytes
following @ChristianSievers comment `|cut -c -21` could be removed.
-3 bytes thanks to @DigitalTrauma.
```
echo "e(l(4*a(1))/"{1..12}");"|bc -l
```
[Try it online!](https://tio.run/##S0oszvj/PzU5I19BKVUjR8NEK1HDUFNTX6naUE/P0KhWSdNaqSYpWUE35/9/AA "Bash – Try It Online")
Some explanations
* `bc -l` define math functions and set scale to 20, see `man bc` for more details
* `a()` atan function, so `4*a(1)` is `pi`
* `e()` exp function
* `l()` log function, so `e(l(x)/y)` is `x^(1/y)`
[Answer]
# [Julia 1.0](http://julialang.org/), 18 bytes
```
@.π^(1/big(1:12))
```
[Try it online!](https://tio.run/##Hc67CsJAFITh2n2KQRETEHVTCkJaKy0sRVD2diSeld0T1FS@oY8UNeX8xcdc24bO@tl3m4v1xH29@LxPhV5eyBd6rauy7C0b1WZij30iFqfqHOIDHSaIxjQvSLC4p@jT@Qahm82IrSAyDtsdHiThPyVQVi4mOBCjU6P6PmjFeLqotDvyeO7KHzlUVBqGPElGjoNfrSSAMs8EKbZsrFG/X/0X "Julia 1.0 – Try It Online")
`(1./big(1:12))` divides a `BigInt` 1 by each of 1 thru 12, then `π.^` raises pi to each of those values. So long as there is one `BigInt` or `BigFloat` involved in each computation, it will calculate the result at that precision. The `@.` macro transforms the code to add dots to every function call (thus the dots that appear in my explanation that don't appear in the code snippet), this causes it to "broadcast" which for this purpose means do it all elementwise.
20->19 thanks to Robin Ryder
19->18 thanks to TimD
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~22~~ ~~20~~ 19 bytes
-2 bytes thanks to game0ver
-1 byte thanks to LegionMammal978
```
Pi^(1`11/Range@12)&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE7872b7PyAzTsMwwdBQPygxLz3VwdBIU@2/W3Ts//@6BUWZeSUA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~47~~ ~~43~~ 40 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
•u¬Œo¡õ≠ÎĆζw1Á4¼©éßw–xùó1O•5ôεžqN>zm16£ì
```
-7 bytes thanks to *@Grimy*.
[Try it online.](https://tio.run/##AVAAr/8wNWFiMWX//@KAonXCrMWSb8Khw7XiiaDDjsSGzrZ3McOBNMK8wqnDqcOfd@KAk3jDucOzMU/igKI1w7TOtcW@cU4@em0xNsKjw6z/XcK7/w)
Uses the legacy version, because for some reason [the new version outputs \$1.0\$ for \$\pi^{\frac{1}{1}}\$](https://tio.run/##yy9OTMpM/f//6L5Cw6rc//8B).. :S
**Explanation:**
```
•u¬Œo¡õ≠ÎĆζw1Á4¼©éßw–xùó1O•
# Push compressed integer 323846027232630971275059342759739669430598683329877932169829
5ô # Split it into parts of size 5:
# [32384,60272,32630,97127,50593,42759,73966,94305,98683,32987,79321,69829]
ε # Then map each integer to:
N> # Take the 0-based map-index, and increase it by 1
z # Calculate 1/(index+1)
žq m # Then calculate PI the power of this
16£ # Only leave the first 16 characters (including decimal dot)
ì # And prepend it before the current integer we're mapping
# (after which the mapped 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 `•u¬Œo¡õ≠ÎĆζw1Á4¼©éßw–xùó1O•` is `323846027232630971275059342759739669430598683329877932169829`.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~61~~ ~~69~~ 63 bytes
Variant of Jitse's [answer](https://codegolf.stackexchange.com/questions/195268/pi-to-the-power-y-for-small-ys/195272#195272), who wants to stick to standard libraries. As mentioned by @Seb & @Jitse, `Rational` or `E/E` are needed because `1/i` isn't precise enough as float.
```
from sympy import*;i=E/E
while i<13:print(N(pi**(1/i),99));i+=1
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P60oP1ehuDK3oFIhM7cgv6hEyzrT1lXflas8IzMnVSHTxtDYqqAoM69Ew0@jIFNLS8NQP1NTx9JSU9M6U9vW8P9/AA)
As a bonus, [`sympy`](https://www.sympy.org/en/index.html) allows to output 99 decimals with the same byte count as for 20 decimals:
```
3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211707
1.77245385090551602729816748334114518279754945612238712821380778985291128459103218137495065673854467
1.46459188756152326302014252726379039173859685562793717435725593713839364979828626614568206782035382
1.33133536380038971279753491795028085330936622381810425845370748286670076101723561496824589105670695
1.25727411566918505938452211411044829390616631003965817353418162262716270074393519788994784267497245
1.21020324225376427596603076175994353105276255513631810467305643780646240044814351479113420061960303
1.17766403002319739668470085583704641096763145003350008756991802723553566109741289228117335907046316
1.15383506784998943054096521314988190017738887987082462087415032873413337243208073328092932090341440
1.13563527673789986837981146453309184806238366027985302804182074656192075351096762716281170420998022
1.12128235323186329872203095522015520934269381296656043824699758762377264153679046528721553289724806
1.10967408296469793211291254568401340513968966612239757917494488030006513039871082996506101420959919
1.10009237896358698298222864697784031503277459309498017808547779493972810083028975298933600450861044
```
[Answer]
# [Python 3](https://docs.python.org/3/), 91 bytes
```
import fractions as f;p=f.Decimal('%s2384'%f.math.pi);i=p/p
while i<13:print(p**i**-1);i+=1
```
[Try it online!](https://tio.run/##DcpBDoMgEAXQfU/Bxqg0xSBdmCo7L0KMhJ8ITGCSpqfHvvWjH4ecTGuIlAsLX9zByKkKV4VfyXq1nweiu4a@q7NZ3n3nVXQcFGFcYWmixzfgOgU2bT5UkHggKSHlS//D0@rWbg "Python 3 – Try It Online")
*-23 bytes thanks to flornquake*
[Answer]
# [bc](https://www.gnu.org/software/bc/manual/html_mono/bc.html) -l, 28
```
for(;i<12;)e(l(4*a(1))/++i)
```
[Try it online!](https://tio.run/##S0r@/z8tv0jDOtPG0MhaM1UjR8NEK1HDUFNTX1s7U5Pr//9/@QUlmfl5xf91cwA "bc – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-rbigdecimal/math`, ~~65~~ 50 bytes
Conveniently, even though `BigMath.PI(9)` only *guarantees* precision up to 9 digits, it actually is precise up to 26, which is enough to calculate the exponents, which use the builtin `Rational` fractions instead of floats to ensure the precision is still good enough. (Also, making a `Rational` saves a byte over dividing it normally, since Ruby uses integer division if both arguments are integers, necessitating the use of `1.0` somewhere in the code.)
-15 bytes from histocrat!
```
1.upto(12){|i|puts BigMath.PI(9).**(1r/i).to_s ?F}
```
[Try it online!](https://tio.run/##KypNqvz/31CvtKAkX8PQSLO6JrOmoLSkWMEpM903sSRDL8BTw1JTT0tLw7BIP1NTryQ/vljB3q32//9/@QUlmfl5xf91i5Iy01NSkzNzE3P0c4F6AA "Ruby – Try It Online")
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 20 bytes
```
vector(12,n,Pi^n^-1)
```
[Try it online!](https://tio.run/##K0gsytRNL/hfZvu/LDW5JL9Iw9BIJ08nIDMuL07XUPN/QVFmXolGmeZ/AA "Pari/GP – Try It Online")
(TIO needs some supporting code, but this works as is in the REPL.
[Answer]
# [cQuents](https://github.com/stestoltz/cQuents), 268 bytes
```
#1&"3.1415926535897932384
1.7724538509055160272
1.4645918875615232630
1.3313353638003897127
1.2572741156691850593
1.2102032422537642759
1.1776640300231973966
1.1538350678499894305
1.1356352767378998683
1.1212823532318632987
1.1096740829646979321
1.1000923789635869829"
```
[Try it online!](https://tio.run/##Hc8xboNRCAPgvcdIpYwR2GDgPFHXSlHb8//lZf2QLfN8/X19//5c16ffb3x4eA6UzJ4agh0f/qhCJDttLNNlKKyGIse7K@UJQrRV0smk2GbcEketIgsV7iltJC2HR91gRADJUqByVr1KCqMZ6FMc6egOYJqqY6YnaHmUKSZKxep19el1OBq7YgtaxPTZ4DaqsMYo9P7O32o2OOktas2eb9f1Dw "cQuents – Try It Online")
There is no way to get more precision out of floats in cQuents, so the values must be hardcoded as strings.
# [cQuents](https://github.com/stestoltz/cQuents), 11 bytes
```
#12&`p^(1/$
```
[Try it online!](https://tio.run/##Sy4sTc0rKf7/X9nQSC2hIE7DUF/l/38A "cQuents – Try It Online")
Does not reach the required precision levels.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 23 bytes
```
vpa(pi,22).^(1./(1:12))
```
[Try it online!](https://tio.run/##Hc87agNhDATgPifZhbCWZvT0YQImpHBlF8bX3@h3@4kZRo/f1@39d57v52173r@B/fjZ9LhselXs@3nyUFNvhNOrswmWfemRCXOWS4u7hiAxamHeWpUe6iCCMkoq6QyWCKdEkaPwRJqqR0zExZtLVSCEAc4MQ3qPamaECUVA7WRHLJ0BdIks6642ii@lBx0ZyazxqNWrUBRmxRRUEF1rg0pHmhQ6LD7f6UdFGis9RRU9538 "Octave – Try It Online")
Declares a variable precision arithmetic (VPA) pi. Octave then cleverly infers that the double constant `pi` actually means pi, not whatever the double constant contains.
[Answer]
# [R](https://www.r-project.org/) + Rmpfr, 80 bytes
Requires package [Rmpfr](https://cran.r-project.org/web/packages/Rmpfr/index.html).
```
mpfr("1.00000000238982476721842284052415179434",30 *log2(10))^(479001600/(1:12))
```
Gives the following, with truncations mine and some minor formatting
```
12 'mpfr' numbers of precision 99 bits
3.1415926535897932384...
1.7724538509055160272...
1.4645918875615232630...
1.3313353638003897127...
1.2572741156691850593...
1.2102032422537642759...
1.1776640300231973966...
1.1538350678499894305...
1.1356352767378998683...
1.1212823532318632987...
1.1096740829646979321...
1.1000923789635869829...
```
See below for why simpler versions don't work. Direct calculation using exponents 1/N for N=1,12 returned inaccurate value fairly early. I figured that was probably due to R or Rmpfr rounding 1/3 early, so whole number exponents would be preferred. So I calculated pi^(12!) (12!=479001600) using Mathematica, then raised it to the power of 12!/N, which would always be a whole number. I had to further tune it by passing the number to Rmpfr as a character vector (so R wouldn't round it), and by using an arbitrarily high precision in both Mathematica and Rmpfr so it would truncate accurately. Because of those arbitrary additions, I can probably shave off a few bytes, but I'm good with it as is.
# ~~[R](https://www.r-project.org/), 29 bytes~~
This only works if R value for pi is accurate, which it isn't. Even reassigning the variable pi to a more accurate representation does not improve accuracy, as it rounds or something around 17 decimals.
```
format(pi^(1/1:12),nsmall=20)
```
[Try it online](https://tio.run/##K/r/Py2/KDexRKMgM07DUN/QytBIUyevODcxJ8fWyEDz/38A)
Or, for 30 bytes
```
options(digits=20);pi^(1/1:12)
```
There's a package that gives a more accurate value for pi and other floating point numbers, [Rmpfr](https://cran.r-project.org/web/packages/Rmpfr/index.html), which you'll find referenced in [questions about pi in R](https://stackoverflow.com/a/31925622). One might expect the following to give the desired output.
```
library(Rmpfr)
Const("pi",20 *log2(10))^(1/1:12)
```
It doesn't. It gives
```
12 'mpfr' numbers of precision 66 bits
[1] 3.1415926535897932385 1.7724538509055160273 1.464591887561523232
[4] 1.3313353638003897128 1.2572741156691850754 1.2102032422537642632
[7] 1.177664030023197386 1.1538350678499894305 1.1356352767378998604
[10] 1.1212823532318633058 1.1096740829646979353 1.1000923789635869772
```
This is wrong on all counts by rounding or being a few off in the last digits (sidenote: the rnd.mode flag for mpfr does not fix this). Now one might think if we went up to many digits (say 100), then it would surely be correct to the first 20 digits. Nope
```
12 'mpfr' numbers of precision 332 bits
[1] 3.1415926535897932384...
[2] 1.7724538509055160272...
[3] 1.4645918875615232319...
[4] 1.3313353638003897127...
[5] 1.2572741156691850753...
[6] 1.2102032422537642631...
[7] 1.1776640300231973859...
[8] 1.1538350678499894305...
[9] 1.1356352767378998603...
[10] 1.1212823532318633058...
[11] 1.1096740829646979353...
[12] 1.1000923789635869771...
```
(Truncations mine). These don't all match OP or the other responses.
[Answer]
# C (gcc [`-lm`](https://codegolf.meta.stackexchange.com/questions/14337/command-line-flags-on-front-ends)), ~~171~~ ~~131~~ 122 bytes
Shaved off ~~40~~ 49 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat).
```
i;p(){for(;i<12;)printf("%.14f%d ",pow(acos(~fesetround(1024)),1./++i),L"Á∫ÄÓ≠∞ÁΩ∂ó≠ßÏñ°ÍúáíÉÆóŰòÖªËÉõìóôëÉÖ"[i]);}
```
[Try it online!](https://tio.run/##AZoAZf9jLWdjY///aTtwKCl7Zm9yKDtpPDEyOylwcmludGYoIiUuMTRmJWQgIixwb3coYWNvcyh@ZmVzZXRyb3VuZCgxMDI0KSksMS4vKytpKSxMIue6gO6tsOe9tvCXrafslqHqnIfwkoOu8JeBofCYhbvog5vwk5eZ8JGDhSJbaV0pO33/bWFpbigpe3AoKTt9//5jZmxhZ3P/LWxt "C (gcc) – Try It Online")
Output:
```
3.1415926535897932384 1.7724538509055160272 1.4645918875615232630 1.3313353638003897127 1.2572741156691850593 1.2102032422537642759 1.1776640300231973966 1.1538350678499894305 1.1356352767378998683 1.1212823532318632987 1.1096740829646979321 1.1000923789635869829
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/) with [libquadmath](https://gcc.gnu.org/onlinedocs/gcc-4.6.4/libquadmath/), 107
* 2 bytes saved thanks to @ceilingcat.
This uses `__float128` to get the required precision.
```
#import<quadmath.h>
s[9];main(i){for(;i<13;puts(s))quadmath_snprintf(s,36,"%.99Qf",expq(logq(M_PIq)/i++));}
```
[Try it online!](https://tio.run/##Ncy7CsIwFADQ3c@oCDc0rUhBCCnuDoLOIiVEkwbyvikI4q8bp@6HIzstZa1b42LIZUyLeDpR5n4@bfDOHtwJ48GQjwoZuBkPA49LQUBCVjqhj9n4ogDpcKTNrmfsphr6escENugEl@l6TmRv2pYQ/q31J5UVGmtn1@MP)
---
I was curious to try this using the GNU MPFR library too:
# [C (gcc)](https://gcc.gnu.org/) with [libmpfr](https://www.mpfr.org/mpfr-current/mpfr.html), 123
* 13 bytes saved thanks to @ceilingcat.
```
#include<mpfr.h>
i;main(){MPFR_DECL_INIT(p,99);for(;i<12;){mpfr_const_pi(p,99);mpfr_root(p,p,++i,MPFR_RNDN);mpfr_printf("%.19Rf\n",p);}}
```
[Try it online!](https://tio.run/##S9ZNT07@/185M7cgv6jEJrcgrUgvw44rNzEzTyNTs9o3wC0o3sXV2Sfe088zRKNAx9JS0zotv0jDOtPG0NgapDy@oCgzryRNQ0lVz9IyKC0mT0mnQFMTLJOcn1dcEl@QCdGnAxYrys8vAfILdDK1tXUMNK1r////l5yWk5he/F83B6QCAA)
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 30 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
6«{“≥αyHT.─C¹„1.0000ŗ┤“^m„┘÷^]
```
[Don't try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjE2JUFCJXVGRjVCJXUyMDFDJXUyMjY1JXUwM0IxJXVGRjU5JXVGRjI4VC4ldTI1MDAldUZGMjMlQjkldTIwMUUxLjAwMDAldTAxNTcldTI1MjQldTIwMUMlNUVtJXUyMDFFJXUyNTE4JUY3JXVGRjNFJXVGRjNE,v=8) It'll take a while to calculate all those digits (it took ~15 minutes to run for me). Rather, [here's](https://dzaima.github.io/Canvas/?u=JXVGRjEzJXVGRjVCJXVGRjE5JXVGRjBCJXUyMDFDJXUyMjY1JXUwM0IxJXVGRjU5JXVGRjI4VC4ldTI1MDAldUZGMjMlQjkldTIwMUUxLjAwMDAldTAxNTcldTI1MjQldTIwMUMlNUVtJXUyMDFFJXUyNTE4JUY3JXVGRjNFJXVGRjNE,v=8) a version of the same code, only outputting the last 3 items.
Computes `C ^ (27720/N)` where `C` is the hard-coded constant `pi^(1/27720)` = `1.000041297024626834690309` and N is looped over from 1 to 12. The big number library decided to expand the amount of significant digits for successively bigger N, making the code take unreasonable amounts of time to run.
[Answer]
# [Python 3](https://docs.python.org/3/), 146 bytes
```
import math
for i in range(1,13):print(str(math.pi**(1/i))[:~(i==2)]+str([32384,60272,2630,7127,'0593',2759,3966,4305,8683,2987,9321,69829][i-1]))
```
[Try it online!](https://tio.run/##Fco7EoIwEADQ3lOkI8FVk13yY4aTMBQUKlsQMjGNjVePQ/1e/tbtSNQa7/koVexr3S6vowgWnERZ0/spDRhSYy6cqvzUIs9zz9z30jxYqXn8SZ4mVMv11JmQwgBOo0dARxq8QQ@dtpE6QG8jUHQOBtIWggsEGIOHSGjAxYBxmflmFqVa@wM "Python 3 – Try It Online")
This uses a similar method to Arnauld's JavaScript solution, by using the inbuilt pi value with the extra precision added to the end.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 46 bytes
```
12İ€ØP*×ȷ19Ḟ+“Ṿẏ⁽)¬ọƓỴ³ɲỊUị&ıİḣl’ḃ4ȷ¤_2ȷD;"€”.
```
[Try it online!](https://tio.run/##AWUAmv9qZWxsef//MTLEsOKCrMOYUCrDl8i3MTnhuJ4r4oCc4bm@4bqP4oG9KcKs4buNxpPhu7TCs8my4buKVeG7iybEscSw4bijbOKAmeG4gzTIt8KkXzLIt0Q7IuKCrOKAnS7/wqJZ/w "Jelly – Try It Online")
Similar to some other answers, but encodes the difference between the Jelly answer and the correct answer (with big integer arithmetic). Full explanation to follow.
[Answer]
# Java 10, ~~316~~ ~~299~~ ~~268~~ 259 bytes
```
v->Math.PI+"2384 1.7724538509055160272 1.4645918875615232630 1.3313353638003897127 1.2572741156691850593 1.2102032422537642759 1.1776640300231973966 1.1538350678499894305 1.1356352767378998683 1.1212823532318632987 1.1096740829646979321 1.1000923789635869829"
```
-40 bytes by just hard-coding the output instead of calculating it.. >.>
-9 bytes thanks to *@ceilingcat*.
[Try it online.](https://tio.run/##LZDBSgNBDIbvfYqhpy3ikkkmyYSidw8tguBFPKzbqlu329LdLoj02dcZ7SWQL@Tn59tVY3W723xNdVv1vVtVTfczc67phu3pvaq3bp1X556GU9N9uLp4PjQbNy6WiV5mafRDNTS1W7vO3blpvL1fVcNn@fhwM0eKwflSFQNTZDBg9gKomGiQwOZjVBbPSCgEiRJ5IiahCEDR1KMmiqyowXsWSS8MbJSpBwTCgMikElDZEvWqIgEIAMmbkolkmgoQg2gMZtECAWdKLMSooqQxcYk516PHiKlFCohCaDF38GCiASKaBDE1Qv9HAQzzdwqKYuk8n5ZZy/H81iYtVztjlrZPbot/jy@vrlpcxX73w3ZfHs5DeUynoe2KrqyL7ty2i6vly/QL)
**Old ~~299~~ 291 bytes answer with actual calculations..**
```
v->{var P=new java.math.BigDecimal(Math.PI+"2384");var x=P;for(int i=0;++i<13;System.out.println(x)){var p=P;for(x=P.divide(P.valueOf(i),21,5);x.subtract(p).abs().compareTo(P.ONE.movePointLeft(22))>0;)x=P.valueOf(i-1).multiply(p=x).add(P.divide(x.pow(i-1),21,5)).divide(P.valueOf(i),21,5);}}
```
Not entirely precise, but good enough to have the first 20 digits correct.
[Try it online.](https://tio.run/##fZA/b8IwEMV3PsWJyRZgQWilSm4YqnaoVCASFUvVwTgONfU/JY4JQvnsqQOIsYut8917z/c7sMAmh/y344pVFSyZNOcBgDRelAXjAlZ9CRCszIGjbX8FTONbO4hH5ZmXHFZgIIUuTBbnwErIUiOOcIjWRDP/Q17k/lVwqZlCy77O3kfDZP70MMS0H2/SjBa2RDEUZDqlo5F8ns3p5lR5oYmtPXFl7CmDGowvAe6miEqSyyBzgTISmKrFukASj5PZ@BHThlT1zpeMe@QwYbsKYcKtdqwUnzYK1qs3om0QmY3uH6LwKEkwXkwp7n3vdpMZJrpWXjp1Qi5tolWeo3twQ5w9XqausfifH7VtR3tsrt6piO1G78JWR/Jo4@Oi@69vYPiK3RCOTK3UjXjb/QE)
**Explanation:**
Most bytes come from the fact that `BigDecimal` doesn't have a builtin for `BigDecimal.pow(BigDecimal)` nor the \$n\$th root, so [we'll have to calculate this manually](https://stackoverflow.com/a/34074999/1682559)..
```
v->{ // Method with empty unused parameter and no return-type
var P=new java.math.BigDecimal(Math.PI+"2384");
// Create a BigDecimal for PI
var x=P; // Create a BigDecimal to print after every iteration
for(int i=0;++i<13; // Loop `i` in the range [1,12]:
System.out.println(x)){// After every iteration: print `x` to STDOUT
var p=P; // Create a BigDecimal to save the previous value
for(x=P.divide(P.valueOf(i),
// Set `x` to PI divided by `i`
21,5); // (with precision 21 and rounding mode HALF_DOWN)
// Continue an inner loop as long as:
x.subtract(p).abs() // The absolute difference between `x` and `p`
.compareTo(P.ONE.movePointLeft(22))>0;)
// is larger than 1e-22
x= // Set `x` to:
P.valueOf(i-1) // `i-1`
.multiply(p=x) // Multiplied by `x` (and store the previous `x` in `p`)
.add( // And add:
P.divide( // PI divided by
x.pow(i-1),21,5)) // `x` to the power `i-1`
.divide(P.valueOf(i),21,5);}}
// Divided by `i`
```
[Answer]
# [Perl 5](https://www.perl.org/), 72 bytes
```
$n=1;print substr(Math::BigFloat->bpi()**(1/$n++),0,21).$/ while($n<13);
```
Even using \$\pi\$ from BigFloat, it doesn't seem to exactly match the given outputs. I'm sure it's truncated properly, though.
[Try it online!](https://tio.run/##K0gtyjH9X1qcquCbWJJhZRVSlJluzYXgO2Wmu@XkJ5ZYc/1XybM1tC4oyswrUSguTSouKdJAVaJrl1SQqaGppaVhqK@Sp62tqWOgY2Soqaeir1CekZmTqqGSZ2NorGn9/z8A "Perl 5 – Try It Online")
[Answer]
# [Fortran (GFortran)](https://gcc.gnu.org/fortran/), 48 bytes
```
print*,(acos(-1._16)**(1/real(i,16)),i=1,12)
end
```
[Try it online!](https://tio.run/##Jc9NbsJQDATgPScJUaC2x7@LnqWKWqgiVVAF7p86dOf3PXk0vt7X5zrfTt/X/2Hbftfl9hynYf68P4YTnz/Yj@M48Nt6mX@GZerncVreeWI5Hi63r23DmZWtxA2WFQVB6oHPEaKGNCoyYycJaVVXK84MczaBOKgVYMDgSCJ0CEu0ioWEMpt7rxhZYVcmIYiKGMJVwqqVI9yVQCTgCpT7rl0ARh6pVVkKsl1hDpPwQGS7557LwpLSLTogHVK5d2AqD6WUcvXXdfxSopJ9u4PSq7//AA "Fortran (GFortran) – Try It Online")
Just an implicit loop with quad-precision vars. Not transferable, but works with GCC.
] |
[Question]
[
Take an input, and convert it from Two's Complement notation (binary where the first bit is negated, but the rest are taken as normal) into an integer (in a somewhat standard output form). Input can be as a string, a list of digits, a number, or pretty much any other format which is recognizably Two's Complement. Leading zeroes must function properly. Both returning and outputting the value are fine.
Examples:
```
0 -> 0
1 -> -1
111 -> -1
011 -> 3
100 -> -4
1001 -> -7
0001 -> 1
```
Example conversion:
Say our input is 1101. We can see that the first bit is in position 4, so has a positional value of 2^3. Therefore, since it's a 1, we add -8 to our total. Then, the rest of the bits are converted just the same as regular binary (with 101 being the same as 5), so the result is -3.
Example implementation (Mathematica, 40 characters):
`Rest@#~FromDigits~2 - 2^Length@#/2*#[[1]] &`
This implementation takes input as a list of digits.
Code-golf, so shortest solution wins.
[Answer]
# JavaScript (ES6), 31 bytes
Expects a binary string.
```
s=>(q=1<<s.length-1,'0b'+s^q)-q
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/Y1k6j0NbQxqZYLyc1L70kQ9dQR90gSV27OK5QU7fwf3J@XnF@TqpeTn66RpqGkoGSpqYCEOjrKxhwockZIuR0DTEkDSHSWCUNEJLGGBoNDOAaTbBIgnWCJM0xTEVIGv4HAA "JavaScript (Node.js) – Try It Online")
Uses the classic sign extension formula:
```
sign_extended = (value XOR mask) - mask
```
where only the sign bit is set in `mask` (e.g. `0x80` for a byte).
---
# JavaScript (ES6), 26 bytes
Expects an array of bits.
```
f=a=>1/a?-a:a.pop()+2*f(a)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbR1s5QP9FeN9EqUa8gv0BDU9tIK00jUfN/cn5ecX5Oql5OfrpGmka0QawCGGhqKujrKxhwoUkbokjrGmLI6wBhLG55AxR5Y0ztBjoGCO0mWOWBBkDlzTGNR5Y3/A8A "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
N1¦Ḅ
```
A monadic link that accepts a list of `1`s and `0`s and yields an integer.
**[Try it online!](https://tio.run/##y0rNyan8/9/P8NCyhzta/v//H22oY6hjoGMYCwA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/9/P8NCyhzta/h9uf9S05v//6GiDWJ1oQxDWAUIgbQClDXUMdAxgNFQGwooFAA "Jelly – Try It Online").
### How?
```
N1¦Ḅ - Link: list of 1s and 0s, A
¦ - sparse application to A...
1 - ...indices: 1
N - ...action: negate
Ḅ - convert from binary (conversion from base functions allow non-base digits)
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 26 bytes
```
s=>'0b'+s-s[0]*2**s.length
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/Y1k7dIEldu1i3ONogVstIS6tYLyc1L70k439yfl5xfk6qXk5@ukaahpKBkqamAhDo6ysYcKHJGSLkdA0xJA0h0lglDRCSxhgaDQzgGk2wSIJ1giTNMUxFSBr@BwA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 33 bytes
```
lambda n:2*int(n,2)-int(n[0]+n,2)
```
[Try it online!](https://tio.run/##NczBCsIwDAbge58i7NRqO9JNUAbzRdRDZR0Walq6Ivj01W6aS77w/yS@8yNQf4qpzOO1ePO8TwZo6HaOMifZCbXigrd9vcocEnhwBCFa4ijaZM3kHdmFi4HBd5wMMIJvl@hd5g2oMzRiTWKqv5y0L@N5EHLmToiCtYFM16U00/ov3NQzjWtHHaq29MjwR80@ "Python 3.8 (pre-release) – Try It Online")
This is essentially `2 x n - n'` where n is the input and n' is the input with its highest bit repeated. It can be rewritten `2 x n - 2 x h - n = n - 2 x h` where h is the highest bit of `n`
## [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 34, 33 bytes (@GB)
```
lambda n:eval(f"0b{n[1:]}0-0b"+n)
```
[Try it online!](https://tio.run/##NYxBCsIwFET3OcUnqwSb8kMFJVAvoi5SmmAg/oS0CCKePdpWZzMP3jD5Od8Sdcdcqu8vNdr7MFog4x42Cs9xeNFZm@sbFQ58R7L6VCBCIEjZkUDZFmfHGMhNQhoG34QmQQ@xnXIMs@CgTsDlanIJNIvQrOdJNl4EKSsuC2R6KaWZ1n/CjTqmcd2o/UKbPTD8oWYf "Python 3.8 (pre-release) – Try It Online")
This boils down to `2 x n' - n` where n is the input and n' is the input with the highest bit cleared. This can be rewritten as `2 x n - 2 x h - n = n - 2 x h` where `h` is the highest bit of `n` (in position).
[Answer]
# [Perl 5](https://www.perl.org/) `-pl`, 31 bytes
```
s/.//;$_=-$&*2**y///c+oct"0b$_"
```
[Try it online!](https://tio.run/##K0gtyjH9/79YX09f31ol3lZXRU3LSEurUl9fP1k7P7lEySBJJV7p/39DQ0MuAyA2NDAAYSAHSPzLLyjJzM8r/q/ra6pnYGjwX7cgBwA "Perl 5 – Try It Online")
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 38 bytes
```
lambda n:(a:=int(n,2))-(a*2&2**len(n))
```
[Try it online!](https://tio.run/##JYxBCsMgEEXXzSlmVWckAbWbItiLtF1YGqmQTsS4CSFnt8Ru3ocH/6W1fGa@XFOuwT3q5L@vtwe26K2LXJB7QzSgl@ZspJxGRiaqZVzKAg7uQmsteqEatVJ/NnXMswtzhgiRoV1sd0r5yAaxxR2GG2wBI@2C6g8 "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 20 bytes
```
Fold[#+##&,-#,!##2]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73y0/JyVaWVtZWU1HV1lHUVnZKFbtf0BRZl5JtLKuXZqDg3KsWl1wcmJeXTVXtaEOENbqcFUbwBiGOgY6BnAGTBLBBEvVctX@BwA "Wolfram Language (Mathematica) – Try It Online")
Input `[digits...]`.
Negates the first bit, and takes the rest as normal.
[Answer]
# x86-16 machine code, 25 bytes
Binary:
```
00000000: 33c0 9903 f1f9 4e13 d2f6 0401 7402 0bc2 3.....N.....t...
00000010: e2f4 7404 33c2 2bc2 c3 ..t.3.+..
```
Listing:
```
33 C0 XOR AX, AX ; AX = 0 (working sum)
99 CWD ; DX = 0 (mask bit)
03 F1 ADD SI, CX ; SI = end of input string
F9 STC ; set CF so DX = 1 on first loop
TC_LOOP:
4E DEC SI ; get next significant bit
13 D2 ADC DX, DX ; shift left with CF to least sig bit
F6 04 01 TEST BYTE PTR[SI], 1 ; this bit a '1'?
74 02 JZ NEXT_BIT ; if not, go to next
0B C2 OR AX, DX ; flip bit on working sum, CF = 0
NEXT_BIT:
E2 F4 LOOP TC_LOOP ; loop until end of input string
74 04 JZ TC_DONE ; was most sig bit a 1?
33 C2 XOR AX, DX ; if so, sign extend
2B C2 SUB AX, DX
TC_DONE:
C3 RET ; return to caller
```
Callable function. Input string at `DS:[SI]`, length in `CX`. Output to `AX`.
[](https://i.stack.imgur.com/yRsWl.png)
[Answer]
# [C (GCC)](https://gcc.gnu.org), 88 bytes
```
n;main(i,v)char**v;{char*s=*++v;for(;*s;)n=n*2|(*s++-=48);printf("%d\n",n-(**v<<s-*v));}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=fZDBCoJAEIbp2lPIRjC7uuGWkbDac3QIQsy1Bdtk17xUT9JFAh-qnibJk0I7l5nDNz8f_7NND3maNi8Rt9dK0PC9U_ycSAXSq3F6SjQhNb_9DhMT1625uGjgxHCsYkWWdyDGdWkchJiXWqpKAJof9wp5ikL3G0WGkhpj_ujzP5O1gMQsOjLLMw1ZAabSpixkBYgxhjyEcDczh24dyqb_YX8Eryws8_1hcGCHRxobm8aYtjoPSN8mMSqib69p-v0F)
Indented code:
```
n;
main(i,v)char**v;{
char*s=*++v;
for(;*s;)
n=n*2|(*s++-=48);
printf("%d\n",n-(**v<<s-*v));
}
```
The input is passed through `argv[1]`.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes
```
ḣ$NpB
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuKMkTnBCIiwiIiwiWzEsMSwxXSJd)
When you steal ideas from Jelly
```
ḣ$NpB # Expects a list of digits
ḣ # Push the first item and then the rest
$ # Swap
N # Negate the first item
p # Prepend the result to the rest of the list
B # Binary to decimal
```
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
```
h[†B›N|B
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJoW+KAoELigLpOfEIiLCIiLCJbMSwxLDFdIl0=)
My original pre-Jelly answer
```
h[†B›N|B # Takes input as a list of binary digits
h[ # If the first bit is 1...
† # Vectorized not
B # Convert to decimal
› # Add one
N # Negate
| # Otherwise...
B # Convert to decimal
```
[Answer]
# [R](https://www.r-project.org), ~~42~~ ~~40~~ ~~39~~ ~~37~~ 36 bytes
*Edit: -2 bytes thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe) and -2 bytes thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen).*
```
\(x)2^rev(a<-seq(x)-1)%*%(x*(-1)^!a)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3VWI0KjSN4opSyzQSbXSLUwuBXF1DTVUtVY0KLQ0gK04xUROi9hajaZpGYrFeZl5JanpqkUZqjkZxSVFxQU5miYaSoaGhko6SkiYQKCvo2inoGnLhVmyAptgYj1pDAwNUg03wK0Zzhjk-Z6CrxutmFJUG-ByBFhCQ0FuwAEIDAA)
Takes input as a list of digits.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ć(š2β
```
Input as a list of bits.
Same approach as [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/245505/52210), but found independently.
[Try it online](https://tio.run/##yy9OTMpM/f//SLvG0YVG5zb9/x9tqGOoY6BjGAsA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/I@0aRxcandv0X@d/dLRBrE60IQjrACGQNoDShjoGOgYwGioDYcUCAA).
**Explanation:**
```
ć # Extract head of the (implicit) input-list; push remainder-list and first
# item separated to the stack
( # Negate this head
š # Prepend it back to the list
2β # Convert it from a base-2 list to an integer
# (after which the result is output implicitly)
```
[Answer]
# [R](https://www.r-project.org/), 34 bytes
```
\(x)sum(a<-x*2^rev(seq(x)))/2-a[1]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3lWI0KjSLS3M1Em10K7SM4opSyzSKUwuBgpqa-ka6idGGsRCVtxhN0zQSi_Uy80pS01OLNFJzNIpLiooLcjJLNJQMDQ2VdJSUgHo0lRV07RR0DblwKzZAU2yMR62hgQGqwSb4FaM5wxyfM9BV43UzikoDfI5ACwhI6C1YAKEB)
Test setup borrowed from [pajonk's R answer](https://codegolf.stackexchange.com/a/245495/95126).
[Answer]
# x86 machine code, 7 bytes
Function that works in 32 or 64-bit mode, with inputs:
* length `n` of the bitstring, in ECX (really just CL)
* bit-pattern in the low `n` bits of EAX. (bits in "a number" is an allowed input format)
Output: Signed integer in the full width of EAX.
In binary 2's complement format, as standard for x86.
Apparently a "number" is a valid output, with no need to convert it ourselves to something having anything to do with decimal, judging by other existing answers, except for a C answer that actually calls `printf` after sign-extending to fill an `int`. (And languages that implicitly print numeric output as a decimal string, but most of the non-golf-language answers are functions that return a number.)
NASM listing: address, machine-code bytes, source
```
sign_extend_nbits:
00 F7D9 neg ecx ; 32-n = -n after masking to &31
02 D3E0 shl eax, cl ; x86 shifts implicitly mask the count &31
04 D3F8 sar eax, cl
06 C3 ret
```
[Try it online!](https://tio.run/##hVCxTsMwEN37FW9ialHTIlSBGBgYWEBCDGyR4zjpqc658l1K@vXBDkg0EhIezj6/e0/3nhFxXeXPKzbSjaNQy6Ub1HF9twDArgWcHTA799huVowHpGIadRGdkQNxCw242hbwdHAYdreQPTUKYtHYW6XAklVl75OqGZawfupNnPXR6dj6UBmPUtREXXxf00pdOP0Mr6uiWBdlLr@ATcAut9Z4jws/i7/Ic97NP7yalpk8F9okv1MmZfnyljikZRtDf5yMnWWSu0guDyC50V5AgpQLW6OuztHtVlUCDdc4RuL8aQQ952XSuzrj/fn1OhGWkADd06RgGNQdXWycVZzIfSI0CXQ5xVNKkBhPjx/jFw "Assembly (nasm, x64, Linux) – Try It Online")
**Algorithm**: Left shift so the MSB of the narrow input is at the top of the full register (count = 32-n), then arithmetic right-shift back to where it was, leaving the upper bits filled with copies of the MSB. x86 is a 2's complement machine; its arithmetic right shift does 2's complement sign extension.
This problem reduces to 2's complement sign-extension, with no need to read an ASCII string of base 2 digits, as stated by the question's input formats. (But this output format intentionally violates the stated "decimal" output requirement of the question the same way many other answers do. We could `div` in a loop, or maybe `fild` / `fbstp` to make BCD in about twice as many bytes.)
[x86 shifts](https://www.felixcloutier.com/x86/sal:sar:shl:shr) mask their count with `&31` (for 8, 16, and 32-bit operand-size), so the `-n` = `CHAR_BIT*sizeof(int)-n` trick only works for 32 or 64-bit shifts, not 8 or 16. 8086 didn't mask shift counts at all, and [I think when they introduced masking for performance reasons in 186 and 286](https://stackoverflow.com/questions/61745808/why-any-modern-x86-masks-shift-count-to-the-5-low-bits-in-cl/61779201#61779201), they wanted to still allow shifting out all the bits of a 16-bit register. But when 32-bit regs were new, masking was already a thing so they could choose whatever semantics they wanted.
---
This "protest" answer is intended to show how trivial the problem is with the stated allowed input formats, if we follow the precedent of other answers ignoring the "decimal" output requirement.
Computers, and most computer languages, use binary integers. In most of those languages, operators like bitwise `n & 1` being the same as `% 2` (for positive numbers), and `x<<1` being the same as `x*2`, prove that numbers are binary. Converting an integer to an array or ASCII string of decimal digits takes extra work, as in <https://stackoverflow.com/questions/13166064/how-do-i-print-an-integer-in-assembly-level-programming-without-printf-from-the/46301894#46301894> (Or perhaps use x86 `fild` / [`fbstp`](https://www.felixcloutier.com/x86/fbstp) to store the float as packed BCD. Yes this instruction exists, and yes it's microcoded and *very* slow)
If you don't want to require that, don't say "decimal", just say "integer".
But don't maybe don't allow input formats that are already 2's complement integers? A C answer of `f(x){return x;}` is arguably valid if we say that the 2's complement input number must already be in an `int`, which is a fixed-width type and thus requires 2's complement sign-extension for valid integers. I decided to support variable widths by taking a value + length instead of just writing a 1-byte `C3 ret` as a full protest answer, to stick to the spirit of what seemed to be the challenge, 2's complement sign extension without any actual conversion necessary.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~63~~ ~~57~~ 46 bytes
```
b;f(char*n){for(b=48-*n;*++n;)b+=b+*n-48;n=b;}
```
[Try it online!](https://tio.run/##XU/RaoQwEHy/r1gEIWpCTc/SK2n6UvoV1QeN8U7axsMEKhV/vTbRnNw1sGwyOzObEeQoxDxXrEHiVPaxisam61HFswOJFYuTRLGoSniVxIpkB6Z4xaa5VQa@ylahCMYd2LNowUht9HsBfAwopQGGIF0bTVPfVtT1iS1KZyWHsxRG1k4KI6EY9hhIZusRA/VE0Slt/CJxkuJD9is/yIe3@3x4erX14Oyv3vvLGhsKkNvVqloOVpYyf30G3f7IrkGXX0R3Hog3hEGSLOxoMVszX@W2fmv2hVSwbe42ajttkIluUWnRLfd/2bm3lAYFoQbyAmENoc6VjWYwaLyll5zrwttOu2n@Fc1nedQz@f4D "C (gcc) – Try It Online")
*Saved 11 bytes thanks to [att](https://codegolf.stackexchange.com/users/81203/att)!*
Inputs a string of two's complement \$1\$s and \$0\$s.
Returns its `int` value.
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 5 bytes [SBCS](https://github.com/abrudz/SBCS)
Takes input as a vector of digits.
```
2⊥-@1
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=M3rUtVTXwRAA&f=e9Q2UeNRV5POo44ZaY96@w6t0Dy0Ql1BXeNR54JHXW2PuhZpqhsoGCoYGhoqGACxoYEBCAM5QEIdAA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f)
Port of [att's answer](https://codegolf.stackexchange.com/a/245498/64121). Negate the first (most significant) bit and convert from base 2.
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 8 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
å∞l├∞▌å-
```
Input as a string.
Port of [*@loopyWalt*'s top Python answer](https://codegolf.stackexchange.com/a/245534/52210)
[Try it online.](https://tio.run/##y00syUjPz0n7///w0kcd83IeTZkDpB5N6zm8VPf/fyUDJS4lQxA2BJEGYNLQwABCgoUglKEhkAIA)
**Explanation:**
```
å # Convert the (implicit) input-string from binary to an integer
∞ # Double it
l # Push the input-string again
├ # Pop and push its first character
∞ # Double it to two of those characters
▌ # Prepend it back
å # Convert it from a binary-string to an integer
- # Subtract the two integers from each other
# (after which the entire stack is output implicitly as result)
```
[Answer]
# [Haskell](https://www.haskell.org/), 21 bytes
```
(0-).foldl1((-).(2*))
```
[Try it online!](https://tio.run/##y0gszk7Nyflfraus4OPo5x7q6O6q4BwQoKCsW8uVZhvzX8NAV1MvLT8nJcdQQwPI1DDS0tT8n5uYmWebks@lUFCUmVeikqYQbRCLxDFE4egAIbKAAbqAoY6BjgGGALomkMB/AA "Haskell – Try It Online")
A modification of [Aiden Chow's answer](https://codegolf.stackexchange.com/a/245587/78410) to avoid head-tail dissection.
Given that `(+).(2*)` is a shorthand for `\x y -> 2*x+y`, we can replace `+` with `-` to get `\x y -> 2*x-y`. When used with `foldl1`, the modification has the effect of negating every single number of input list `l`, except the first. Then it suffices to negate back the entire result to get the intended answer.
[Answer]
# [Haskell](https://www.haskell.org/), ~~38~~ ~~32~~ ~~29~~ 27 bytes
*Thanks [@Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string) and [@Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler) for helping me golf this in TNB chatroom.*
*Thanks [@Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler) for another -2 bytes by directly setting* `-h` *as the initial value of* `foldl`
```
f(h:t)=foldl((+).(2*))(-h)t
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00jw6pE0zYtPyclR0NDW1NPw0hLU1NDN0Oz5H9uYmaebUo@l0JBUWZeiUqaQrRBLBLHEIWjA4TIAgboAoY6BjoGGALomkAC/wE "Haskell – Try It Online")
### Explanation
```
f(h:t)=foldl((+).(2*))(-h)t
f(h:t)= list input, with the list's head being h and tail being t
example: [1,0,0,1]
foldl( .... )(-h) starting with initial value -h...
(+).(2*) t iteratively apply the function (+).(2*) == \x y->2*x+y
across the list t from left to right
this converts from a binary list to decimal, with the
head of the list negated
example: [1,0,0,1] -> -1 (initial -h) * 2 + 1 = -1
[0,0,1] -> -1 * 2 + 0 = -2
[0,1] -> -2 * 2 + 0 = -4
[1] -> -4 * 2 + 1 = -7 (output)
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 29 bytes
I don't think this should work but it does.
```
f(v)=v[1]*=-1;fromdigits(v,2)
```
[Try it online!](https://tio.run/##K0gsytRNL/j/P02jTNO2LNowVstW19A6rSg/NyUzPbOkWKNMx0gTJB1tEKtpa2vABWQZgli6hmCmDhAiuAYwrjFE0kAHrEvXBM6FqjaHqIYLGHIBAA "Pari/GP – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~51~~ 49 bytes
```
s=>2**s.length/2*-s[0]+parseInt(s.slice(1)||0,2)
```
*-2 bytes because dividing by 2 is golfier than subtracting 1 from length*
*-1 byte thanks to Matthew Jensen's suggestion to use `slice` over `substr`*
[Try it online!](https://tio.run/##dcxNDoMgEEDhfS8iYMUZto3d9wyNC4LjT0PAOKQr747ptoHtl5f3sV/L7tj21IU4UZ6HzMPTKMXaU1jS2hvV8RvGdrcH0yskwZr95kigPE@4G5ldDBw9aR8XMYsGERspH7c/hjIjQIXLl4ojVvqKl@Mf5gs "JavaScript (Node.js) – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 8 bytes
```
-:@ggFD2
```
Takes input as a list of bits, given as separate command-line arguments. [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhYrdK0c0tPdXIwgXKjoymhDHQMgNIyFCgAA)
### Explanation
Same approach as [Jonathan Allen's Jelly answer](https://codegolf.stackexchange.com/a/245505/16766):
```
-:@ggFD2
g List of cmdline args
@ First element
-: Negate in place
g Updated list
FD Convert from a list of digits
2 In base 2
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 10 bytes
```
I↨EA⎇κι±ι²
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwymxOFXDN7FAwzOvoLREQ1NHISS1KC@xqFIjW0chU0fBLzU9sSRVI1NTEyhlBCSt//@PjjbUUTAAI8PY2P@6ZTkA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
A Input array
E Map over elements
κ Current index
⎇ If nonzero then
ι Current bit else
ι Current bit
± Negated
↨ ² Convert from base `2`
I Cast to string
Implicitly print
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 46 bytes
```
^1
-
1
01
+`(-|1)0
0$1$1
+`-1|0
^(-?).*
$1$.&
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wP86QS5fLkMvAkEs7QUO3xlDTgMtAxVAFxNU1rDHg4orT0LXX1NPiAgrqqf3/bwBUbGgI0gCkDQxAGMgBEgA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
^1
-
```
Change a leading `1` to a `-`.
```
1
01
+`(-|1)0
0$1$1
```
Perform binary to unary conversion, counting `-` as a digit, which causes it to be raised to the appropriate power of 2.
```
+`-1|0
```
Subtract the value of the lower order bits from that power of 2.
```
^(-?).*
$1$.&
```
Convert to decimal, keeping the leading sign if the number is negative.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 28 bytes
```
->n{eval"0b#{n}0-0b"+n[0]+n}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOrUsMUfJIEm5Oq/WQNcgSUk7L9ogVjuv9n9BaUmxQrS6oaGhuo66AZg0NDCAkGAhEBWrl5tYoKGWpvkfAA "Ruby – Try It Online")
[Answer]
# APL+WIN, 27 bytes
Prompts for two's compliment as vector of integers
```
(1+¯2×n)×n+2⊥1↓2|(n←↑b)+b←⎕
```
[Try it online! Thanks to Dyalog APL Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tv4ah9qH1Roen52kCsbbRo66lho/aJhvVaOQB1Txqm5ikqZ0EYvVN/Q9Uz/U/jctQAQi50rgMoLShgoGCAYyGyoBZAA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Desmos](https://desmos.com/calculator), 52 bytes
```
L=l.length-2
f(l)=total(2^{[L...0]}l[2...])-2^Ll[1]2
```
\$f(l)\$ takes in a list of bits and outputs the corresponding decimal form.
[Try It On Desmos!](https://www.desmos.com/calculator/tkfvixmsgg)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/zqcdshn9dh)
[Answer]
# TI-Basic, ~~35~~ 29 bytes
```
sum(Ansseq(2^(dim(Ans)-I)(1-2(I=1)),I,1,dim(Ans
```
Takes input as a list of digits in `Ans`. Output is as an integer in `Ans` and is displayed.
[Answer]
# Javascript (ES2020), 33 chars
```
s=>BigInt.asIntN(s.length,"0b"+s)
```
Test:
```
f=s=>BigInt.asIntN(s.length,"0b"+s)
console.log(`0 -> 0
1 -> -1
111 -> -1
011 -> 3
100 -> -4
1001 -> -7
0001 -> 1`.split`
`.map(x=>x.match(/^(\S+) -> (\S+)$/))
.every(([,s,key])=>f(s)==key))
```
[Answer]
# [Piet](https://github.com/cincodenada/bertnase_npiet) + [ascii-piet](https://github.com/dloscutoff/ascii-piet), 46 bytes
```
tlrdveccsittttttbbbuebV???? vuikuemmaiitdem vV
```
Input the binary as a string space separated bits, with `2` being the [sentinel value](https://codegolf.meta.stackexchange.com/a/24639/96039) (`2` is a valid sentinel value because the input only contains `0`'s and `1`'s). For example, `1001` is inputted as `1 0 0 1 2`.
[Try It Online!](https://tio.run/##rVltb9s4Ev6uX8FTgK3cOIqd7hZ3QdxF2rptcGkSJN0WuFwgUBZtM7EoLUU5yd3u/fXeDCnJpOTa6fVcoJWo4fCZ9xk2psX864QqcnREno3P3z0jrwgtJpzv5ZypMH/0dv6yXxZyP@ZiP39U80y88Dye5plUpHgs@oRnfULlLKeyYN5UZim5ODklFcVJSmfM8z78No4@Hl/9nYzIIB4Oh97r0@M35m0wGMDbb@PqZei9vxyPz8zbcOBdjt@aTUD25cPJp3HDwjs9ef/h09n46spmjezeHl82vOH17Pzy4/FpzREW9MaaK7wDRTQ@P7XYmI1ewqaEiUmWsEiw@wUXrAi0ciJUTu/QI/AzC/ojbF59Dot8wZXZ1NOUhlXS0F7f6OVpJgkuES5sZoY7/vhUf18t4G@HfCqlIGrOCHJdELAhvjCRkAxg08m85qoywlVBQMQWB/Z7yZd0wYRyPixooaLJnEpkDDgzmQTI6npveNPbQPnTiPzHUmXrsJOpxpfS4o6oLLsz0Ou9WakQdi4BLo0XjEgqZqzf4lHM@VSBMCSmkzsjWWuHswEV5yA8Ii8OXDV2pdgdkZc/OzS13ZAE1DGZy8DZ0ltLrY0Y0jwHixj1HYL@yK7DzmyVTKEtfT@8zbgIHA4944YJ2@KG@BjdczVvaACq7zcepsE3HobUjoMZ2WDHP4XfcbQ5kwx0n5WLRDwD5TNCxSNpzuGi8jwNmyyZLHgmWkxiBigYEPKCTEsxUUBCaJIUuDd1iCeZUFyUK1u2fHGlOAu88UBi@V9bjOMqUNQcQgVQiExh0FQBo2NlxiBOcloUIIaay6yczVtMAPkc/Sxx1tcof3ekYTVkbFGwbYjWoUHPADR1FLc4iGwPxLUCGSyTEFrbhhj3eyJaGTSK/MNWZA@cFv3CM2deGm9Fk8N@LQJBbkRJyoHdbOUZkqXZsjq9cvLu4aEslOR5gEdU3m6cVGURx/phOXvfaCwq@L9YHz0tzgo2ekdBuVUc7JCP9A68tZTGSyEHM0kXHW/lIoeUQ@XKb7WK4VPFBvUa1xpfIQAf3FASvMojK2Qrg@s0FRUqYVIG/vHVm5OTvfrgC2TLC79PwII2tz7x40cFpcDvrWfUPrlD0POaEBakNltqpc@2errSbsg8T5T2CzpHo3@IeZb8qERPL7rag8DhEsAwgurzEKCSkaL3rcprb5wzPpujGlamsWm2yT71L2Q2kzQl6LEY4/@2AP1J4sd6wRz0p9/vlCf9m/qBvfO5s8kERdHza3Nf0ATzNTRgRkU6PIucTuA5iBdo/WrLGm1e40O4uC0LFVhHgjMS/5s6M62MYfodrY1dmbo9zsa8j795ycjITv91o@l2KagkOLZwad3@sd04aNYjYnpOQFm968a120LskC9ziCSdfY1@kwxL5SRLmZENIOwnVN6RJZWcilYmb8M0PWunmVlRjAh2uV0g4HtMFFxxbcpg0CfDvx20GpRFm5U57SnMDn75ZRszrdatvADVGm68kJAPRyTOskWAGv@JwADQpplJBtnModJDQ5suXmj3sMhw0HCp5CxGOBa6aw3iZm0cumQax1MIEUirczaRUreHgKJOOjOAo6emEDJm4F@@fw11wY1DO/Z7zb4Q6llCFQ3syN4hVxPoC0zFw22kzDHpUDKlEwVuDZ0DZH8oBKu6@sSs/p4JqBwK673hrJOMaWiQjW/X6o3JXDK6aDK0na@ft1FpyiYlOxm6Q2tUiYqRDBeDYHVO3@bUw7eCpvmCjYzmz8bHl@OrT05zDoxMb5LrAgZ7HwJRpn2iGY4GVfsByxEsw8kVQe/64PCmVqkR6xUZrJTqbMCnUOrMW@fcge/AqIgMlIeHJNANAvRPYrZCkJRpvur@Oc60@ul@zsEXOIxBWM06O@3d0BBagvI@@avuAg@J35DGiwzyHMRXw@eaH/Ld4csbmxtaxRpF6qR/i1lRT2w6R72EZNBzk0azd3fUTEYWpBh3aFYxstJgrm8Pb3cPbjRSC6glU820Km8/D3rrqGAzsqgOxcY47qH5XhyQI5AX/xoevNQtPfFDf33Fdqq3A3P9mXWDbUwGK8OXLcMjad0sV41ynmGSWbIIgipwjAnjALr/arkJa/gAAlguCG07CPKZQpYaS5lBbKegHDPm6Uw2Y5JAsqPQKuKsIkjLKYFlBccO7udUzop6OsUPZqVPpuCFo@KxCA0hiOIBrigSNGVRpKfQKEopF1FUzaL1/RKO3/VzeCxnZQojz4X@UjeGNWUIrhLRiiTw97C99vf2qswEYGm5UKNhn6jHnI1sPfY32XPOFvnIPy@Vnh6Enfowx86Ah3CS4CZmKVMU2oGR/@b87fg0ujr5x9jfIsaDEQMiHx6onqJHfgGZnEVKllvOc8EXmD8aF@SiUIzq4VPSexPU28AsDZiqUPwoIPYAAyTggGBJqbkeiPFaCPWqR6SNgebnVaMNtcz41Rb0cBD4IYAW6JUj/1fLLc4ywZ4A/Cor5YRpf9Yh7o51ZsLcDDqoTjzEgpQQfX0K6LnobUEPivlh@G8hbXNhVN3IcHH2Hi/jvge69h@jdthZI89yZFxYEStD/Q9K0Uxn05ou3NJuvMkEUOh2Q2tpzQgNEAC971wN1dyNtetrH1SQW23cwyzDHoJeXSa9DXc632ZDjrRdX62HV5nzqfjalrNBVqyejrLDTEMFNq/8jW3bE7Wr5KN7uk6WGfS9QUuvmJKm3cnBuY2YhhgogSXdw4TlapN8b/DeUgNrYmyDTZuC6HV1py@xRUYqce8BL2SdJQcP7LcD2FsLv6p6XNhimE51w51XjdW99WoFTscokN1t6G91lDZzADQjmP5NsiXm5osUOZvwKYeAMilgnat24rSrcZPQdaxiOtHKAl1Vpcbyqqp1ZBT7X56Fr/H95NwyL/bvBV2yYEUKNccN81XHazXEQBjOmFpiVxP0/reg63pqtaVPnt0/@5a/TsN7yRULKlhbA9EldIn@L3pv1/PvVQMMkWABy3eAJ9UnVG5TB4E@0R3Ca/N1FNiy4brrcRNsTajp3qpvqg2KZLDgyLsqPusPr6IOvodxOZ0y2Rw/Pn/nTeZplpDdh9b/e3rO/4r@QcJ95ztMcfi0h/UnzMXsq1rIZMkmE2gk9S@O45LFn3@FH1mW/K5kKfS0HEyVkuXnr3iytw9q2Uc2@0IniL3fW0yHZAB/huTgvw)
Image format (46 codels)
[](https://i.stack.imgur.com/iqwXk.png)
Enlarged for clarity (codel size = 50)
[](https://i.stack.imgur.com/Zs2M3.png)
] |
[Question]
[
Your challenge today is to write a program or function which takes a list `l` and gives the positions in `l` at which each successive element of `l` sorted appears.
In other words, output the index of the smallest value, followed by the index of the second smallest value, etc.
You can assume that the input array will contain only positive integers, and will contain at least one element.
Test cases:
```
Input | Output (1-indexed)
[7, 4, 5] | [2, 3, 1]
[1, 2, 3] | [1, 2, 3]
[2, 6, 1, 9, 1, 2, 3] | [3, 5, 1, 6, 7, 2, 4]
[4] | [1]
```
When two or more elements with the same value appear, their indices should appear next to each other from smallest to largest.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), fewest bytes wins!
[Answer]
# Dyalog APL, 1 byte
```
⍋
```
Dyalog APL has a built in operator function (thank you Zacharý for clearing this up) to do this.
## Example
```
⍋11 2 4 15
2 3 1 4
{⍵[⍋⍵]}11 4 2 15
2 4 11 15
```
Here I'm indexing into the list by the sorted indices to return the list in ascending order.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 1 byte
```
Ụ
```
[Try it online!](https://tio.run/##y0rNyan8///h7iX/D7c/alrj/v9/dLS5joKJjoJprA6XQrShjoKRjoIxmA1kmOkoAEUswSRc3CQ2FgA "Jelly – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~43~~ 42 bytes
`1`-indexed:
```
import Data.List
map snd.sort.(`zip`[1..])
```
[Try it online!](https://tio.run/##ZY7BCsIwEETv@Yo5thAD1ap48KRHhR6FWGzQRoNJDN2c/HhjKIKIe1jYecvM3BTde2uTceExRGxVVGJnKDKNNY7JqQDyF0EZiqJ7mtDJSoi2TLGnSPlHQi45ao55y/AZDllxTDlmP1oWFhyZrMb9x@vv1TLmlPHZPzfYn1CEwfgodIkxN73O2qorpclh0zRv "Haskell – Try It Online")
`-1` byte thanks to @ØrjanJohansen!
[Answer]
# [Python 2](https://docs.python.org/2/), 56 bytes
This solution is 0-indexed. This abuses the fact that `sorted()` creates a copy of the original list.
```
l=input()
for k in sorted(l):a=l.index(k);print a;l[a]=0
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8c2M6@gtERDkystv0ghWyEzT6E4v6gkNUUjR9Mq0TZHLzMvJbVCI1vTuqAoM69EIdE6Jzox1tbg//9oIx0FMx0FQx0FSzAJ5BrHAgA "Python 2 – Try It Online")
[Answer]
# Javascript (ES6), 39 bytes
-2 bytes thanks to @powelles
This only works in browsers where `Array.prototype.sort` is stable.
```
a=>[...a.keys()].sort((b,c)=>a[b]-a[c])
```
1-indexed version (47 bytes):
```
a=>a.map((_,i)=>i+1).sort((b,c)=>a[b-1]-a[c-1])
```
**Example code snippet:**
```
f=
a=>[...a.keys()].sort((b,c)=>a[b]-a[c])
console.log("7,4,5 => "+f([7,4,5]))
console.log("1,2,3 => "+f([1,2,3]))
console.log("2,6,1,9,1,2,3 => "+f([2,6,1,9,1,2,3]))
console.log("4 -> "+f([4]))
```
[Answer]
# [Python 2](https://docs.python.org/2/), 48 bytes
```
lambda x:sorted(range(len(x)),key=x.__getitem__)
```
[Try it online!](https://tio.run/##HcdRCoMwDADQq@QzgTKYgjDBk2yjVBq1TNNSI9TTV9nPg5dOXaI0dRo@dXXb6B2Ufo9Z2WN2MjOuLFiIzI/PoTysnVmD8mYt1ZSDKEwYJB2KRPXdGOgMPA28/t5tvxc "Python 2 – Try It Online")
[Answer]
# [Perl 6](https://perl6.org), ~~27~~ 21 bytes
```
*.pairs.sort(*.value)».key
```
[Test it](https://tio.run/##ZZBBasMwEEX3OsVfFTuVBU4ch2ISfIAuuyiELIw9BVE3FpZsYkpOll0v5o7lhJBWC6GZ//5oZgy1dTp2ltCnqszE14CnsqkI23GhTKFbq2zTumCh@qLuKPy5qE8aRg/mjqzDFoEA9huJRGJ9wMOR2C8lVhLxQU5ULDHF/6mb4Cl@pWyRePH31cEUF1r7FMsbLySzI/lT8V6X9TAT04Bv3G0mTF0c8Ty3Xukey0x8NO11lmiHXB9N5yRyOhkqHVX45g@0jSoiUw@YlhPMUKhetWU0uLPvEeJbeoaU4Q2L8/gL "Perl 6 – Try It Online")
```
->\x{sort {x[$_]},^x}
```
[Test it](https://tio.run/##ZZDBaoNAEIbv@xT/oRRDR8HEGIok@AA99lAwphSdgmDj4m6CQXx2O64JIe0elp35v392ZjS3dTyeDOMcB0Wifi54LpqSsR393b7rTdNa9F329JkPdOiG0SGpZWOxhaeAbEOICOscD4eQLQkrQpjTRIWEKf5P3QRHySsWC@HV3VeHUFJo7VIib5wQzY7oT8V7XdEXiZpGe5duE6XrryNe5tbL6oxlor6b9jqLv0NaHfXJElLuNBeWS/TyQWX8klnXF0xr8WZoEbxVRlDvzn74CG/pGQq07FYN4y8 "Perl 6 – Try It Online")
Inspired by a [Python answer](https://codegolf.stackexchange.com/questions/136637/get-the-indices-of-an-array-after-sorting/136656#136656)
## Expanded:
```
-> # pointy block lambda
\x # declare sigilless parameter
{
sort
{ x[$_] }, # sort by the value in 「x」 at the given position
^x # Range up-to the number of elements in 「x」
}
```
[Answer]
# Bash + coreutils, 20
```
nl|sort -nk2|cut -f1
```
[Try it online](https://tio.run/##S0oszvj/Py@npji/qERBNy/bqCa5FMhIM/z/34jLjMuQyxKIjbiMAQ).
[Answer]
# [Swift 4](https://github.com/apple/swift), 82 bytes
```
func f(l:[Int]){var l=l;for k in l.sorted(){let a=l.index(of:k)!;print(a);l[a]=0}}
```
[Test Suite.](http://swift.sandbox.bluemix.net/#/repl/597d9e77c5cfd27e04c56f0e)
## Explanation
In Swift, `l.sorted()` creates a sorted copy of the original Array. We loop through the sorted elements in the list and after printing each item's index in the original Array with `let a=l.index(of:k)!;print(a)`, and then, in order to keep the correct indexes in the Array, we assign `l[a]` to `0`, because it does not affect our normal output.
---
Take note that this is 0-indexed, since it is a port of my Python solution. If you want it to be 1-indexed, replace `print(a)` with `print(a+1)` or [Try it online!](http://swift.sandbox.bluemix.net/#/repl/597da09cc5cfd27e04c56f0f).
[Answer]
# [J](http://jsoftware.com/), 2 bytes
```
/:
```
[Try it online!](https://tio.run/##y/r/X98KhBXMFUwUTLmADEMFIwXj/2AuAA "J – Try It Online")
Zero-based indexing.
[Answer]
# [R](https://www.r-project.org/), 5 bytes
There is a builtin function for this.
```
order
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 40 bytes
```
->a{a.zip([*1..a.size]).sort.map &:last}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6xOlGvKrNAI1rLUE8vUa84syo1VlOvOL@oRC83sUBBzSonsbik9n@BQlp0tJGOgpmOgqGOgiWYBHKNY2P/AwA "Ruby – Try It Online")
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 17 bytes
```
@(i)[~,y]=sort(i)
```
[Try it online!](https://tio.run/##y08uSSxL/f/fQSNTM7pOpzLWtji/qATI@Z@YV6yRmVdQWqKhrq6p@T/aSEfBTEfBUEfBEkwCucaxAA "Octave – Try It Online")
Octave is like MATLAB but with inline assignment, making things possible that gives the folks at Mathworks HQ headaches. It doesn't matter what you call `y`, but you can't do without that dummy variable, as far as I know.
[Answer]
# [Julia](https://julialang.org), 8 bytes
```
sortperm
```
[Attempt This Online!](https://ato.pxeger.com/run?1=nY8xTsMwGIXn-BRPmRzJRRTSlg6NWDlDlMFJ_7ZGqWvZjmDIJZhZulTiMhwgt8FJGiFg4x8s_e89f3r_--W5qZU8d5-7k4WC0rAkt7XS5HjCEEYKlNjAmVp5rgTiNk5YpLRpfJBzI60j_qT9MhX-5ih9dUjQw3wPI1kdBo3bmOe3s3WRxAIyKVhEr4YqT9v_QsoeIrV7IRsQY582Q0l7pS-N380ePtzJekP2OK5dFpHesshYpX2t-fWEDCMkHPUonSPrMVE3mEqy8HOknLu3fCWQCiwK_JgW-Z3AvcC8YPlcoF_-RiaD9eFlCAush_caD5GAWAxSsFeDkYZ4-ov1TSzGZl8)
[Answer]
# [MATL](https://github.com/lmendo/MATL), 2 bytes
```
&S
```
[Try it online!](https://tio.run/##y00syfn/Xy34//9oIx0FMx0FQx0FSzAJ5BrHAgA "MATL – Try It Online")
Input and output are implicit.
[Answer]
# [MY](https://bitbucket.org/zacharyjtaylor/my-language/src/5984ac62a269d7a763c1ef664f5b7d745b7f9390?at=master), 3 bytes
MY also has a builtin for this!
```
⎕⍋↵
```
[Try it online!](https://tio.run/##y638//9R39RHvd2P2rb@/x9tqGOkY6xjomMQCwA)
### How?
Evaluated input, grade up, then output with a newline.
Indexed however you set the index, with `⌶`/`0x48`. (Can even be some weird integer like `-1` or `2`, the default is `1`).
[Answer]
# Java 8, 128 + 19 = 147 bytes
Based on Mr. Xcoder's [solution](https://codegolf.stackexchange.com/a/136643). 0-based. Lambda takes input as an `Integer[]` and returns `Integer[]`. Byte count includes lambda expression and required import.
```
import java.util.*;
```
```
l->{Integer o[]=l.clone(),s[]=l.clone(),i=0;for(Arrays.sort(s);i<l.length;)l[o[i]=Arrays.asList(l).indexOf(s[i++])]=0;return o;}
```
[Try It Online](https://tio.run/##VZBNS8NAEIbPya@Y465NFz9AkDQFL0JB8dBjyGFNtnHqdjbsTqql5LfHrUZLL8N8zzzvVu/13HWGts3HiLvOeYZtzKme0aqrPE27/s1iDbXVIcCLRoJjmnQe95oNBNYci@eJTU81oyP1NDmLFbFpjS@rDP7dJYR4yDQrarA2AYrRzpfHqQyurAqrauvICJmFiwiL63zjvHj0Xh@COq0RQea4sMoaavk9l7Z0JVbF1KHDMwYWViqkxny9bkQocTarZBU3ecO9J3D5MCYRNZlYJ6q9wwZ2kVis2SO1ZQXat0GeBEjWh8Bmp1zPKopBbOnvJ3a/7eKCUemuswdB5vMsAxxvM7jP4CaDhx8bw7tBSpmnyZAO4zc)
## Ungolfed lambda
```
l -> {
Integer
o[] = l.clone(),
s[] = l.clone(),
i = 0
;
for (Arrays.sort(s); i < l.length; )
l[o[i] = Arrays.asList(l).indexOf(s[i++])] = 0;
return o;
}
```
## Notes
I use `Integer[]` instead of `int[]` to allow use of [`Arrays.asList`](http://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#asList-T...-), which has no primitive versions. `Integer` is preferred to `Long` because values are used as array indices and would require casting.
This ended up being shorter than my best procedural-style `List` solution because of the cost of class and method names.
This also beat a solution I tried that streamed the inputs, mapped to *(value, index)* pairs, sorted on values, and mapped to indices, mostly because of the baggage needed to collect the stream.
## Acknowledgments
* -5 bytes thanks to *Nevay*
[Answer]
# [Factor](https://factorcode.org/), 8 bytes
```
arg-sort
```
[Try it online!](https://tio.run/##bczBCoJAEAbg@z7F3wMkmJZUDyBdukSn6DDIJNKybrMbZOKzb6t0EZzDMMP/8T@o8q2E6@V0Lg9w/Hqzqdgl/PFCDlbY@85KYzyeLIY1ajYspJsv@aY1DkelehTIscWA2azQY4MMKYZI0uleIP9AjXgXv/2cjiSL5WkMixjkE40bN2CpbVCBpF67Vny4R2jIWt0hcag0k4Qf "Factor – Try It Online")
0-indexed
[Answer]
# Common Lisp, 82 bytes
```
(lambda(l)(loop as i in(sort(copy-seq l)'<)do(setf(elt l(print(position i l)))0)))
```
[Try it online!](https://tio.run/##DcsxCsMwDEbhq2jLr6HQJlAo9DJO4oBAsdRIS07veviWB29TCe/o0HKue4Ey1MypBAlJQ9iV2MzvR9QfKU9f3g1R80DVJIVf0hJuISnWxqTM/Bz6hJne9KLPMNMyyh8)
[Answer]
## Clojure, 39 bytes
```
#(map key(sort-by val(zipmap(range)%)))
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 12 bytes
```
{ee{1=}$0f=}
```
[Try it online!](https://tio.run/##S85KzP1fWPe/OjW12tC2VsUgzbb2f13C/2gjBTMFQwVLIDZSMI4FAA "CJam – Try It Online")
[Answer]
# MATLAB / [Octave](https://www.gnu.org/software/octave/), 29 bytes
```
[~,y]=sort(input(''));disp(y)
```
[Try it online!](https://tio.run/##y08uSSxL/f8/uk6nMta2OL@oRCMzr6C0RENdXVPTOiWzuECjUhMobaSjYKajYKijYAkmgVzjWAA "Octave – Try It Online")
[Answer]
## JavaScript (ES6), 69 bytes
0-indexed. Works for lists containing up to 65,536 elements.
```
a=>[...a=a.map((n,i)=>n<<16|i)].sort((a,b)=>a-b).map(n=>a.indexOf(n))
```
### Test cases
```
let f =
a=>[...a=a.map((n,i)=>n<<16|i)].sort((a,b)=>a-b).map(n=>a.indexOf(n))
console.log(JSON.stringify(f([7, 4, 5])))
console.log(JSON.stringify(f([1, 2, 3])))
console.log(JSON.stringify(f([2, 6, 1, 9, 1, 2, 3])))
console.log(JSON.stringify(f([4])))
```
[Answer]
# [Python 3](https://docs.python.org/3/), 52 bytes
0-indexed. Based on [Bruce Forte's Haskell answer here](https://codegolf.stackexchange.com/a/136639/47581) and [G B's Ruby answer here](https://codegolf.stackexchange.com/a/136765/47581).
```
lambda l:list(zip(*sorted(zip(l,range(len(l))))))[1]
```
[Try it online!](https://tio.run/##HcZNCoAgEEDhq7QcYzZlPxB0knJhaCVMJjqburyFb/O@8PB5e5n3ec2kr83oiiZyieF1Aep0R7ammDBqf1gg64FEaWlUDtF5hh0WiR1K7LEtb3DA8XevhMgf "Python 3 – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~10~~ 7 bytes
This is a direct port of my [Haskell answer](https://codegolf.stackexchange.com/a/136639/48198), also `1`-indexed:
```
m→O`z,N
```
[Try it online!](https://tio.run/##yygtzv7/P/dR2yT/hCodv////0cb6ZjpGOpYArGRjnEsAA "Husk – Try It Online")
### Ungolfed/Explained
```
Code Description Example
-- implicit input [2,6,1]
N -- natural numbers [1,2,3,..]
`z, -- zip, but keep input left [(2,1),(6,2),(1,3)]
O -- sort [(1,3),(2,1),(6,2)]
m→ -- keep only indices [3,1,2]
```
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 72 bytes
```
l->l.stream().sorted().map(i->{int j=l.indexOf(i);l.set(j,0);return j;})
```
[Try it online!](https://tio.run/##fVLLTsMwEDzHX7FHG6UWbwRpI3FBqgTiwBFxMIlTOU2cyHZKS9VvD5tHaVpaLn7szs6Ox5uKhRgVpdRpPK9VXhbGQYoxXjmV8bOA/IkllY6cKjR/6g9HMNYZKXL@1m4BIWX1makIokxYCy9CabImXh@0TjjcFoWKIccUxSqlZ@8fIMzMMuIh1Csx5GiEdE4@GiNWz8o6eufDtQ83jAUnIZc@3Ppw4cN9u@L16j/4ELIhHmlgC0RsVf4ix1Pt5EyaEA4pkJZzDqpXfqRCwAS0/BqQhbTVlBQGmnpYwgMSeIKLOKbLNmekq4wGcUJYa1/3pmMdezFvK@tkzovK8Rab6Q5tuSs626lV33KqY7mkgmG0TVM2MGTv17of3jXaVR9RMe9VbAdnvJf2D8lCSNCoOhuF24GijFscNBnjIRclVaNw3diVTjKumq6vCVUsQLh0NPXPWdC7lgYbVg9cTLgoy2xF592zNqT@AQ "Java (OpenJDK 8) – Try It Online")
Takes a `List<Integer>`, returns a `Stream<Integer>` containing the results.
We get a Stream based off the initial list, sort it, then map each number to it's index in the list. In order to accommodate duplicate elements, we set the original element in the list to `0`.
[Answer]
# SmileBASIC, 67 bytes
```
DEF I(A)DIM B[0]FOR I=1TO LEN(A)PUSH B,I
NEXT
SORT A,B
RETURN B
END
```
Very simple, all it does is generate a list of numbers from 1 to (length of array) and sort this by the same order as the input.
[Answer]
# [Python 3](https://docs.python.org/3/) with [Numpy](http://www.numpy.org/), ~~38~~ 26 bytes
*12 bytes saved thanks to [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king) (no need to give the function a name)*
```
import numpy
numpy.argsort
```
Output is 0-based.
[Try it online!](https://tio.run/##K6gsycjPM/7/PzO3IL@oRCGvNLegkgtM6iUWpRcDxf6nKdgqoIhwFRRl5pVopGlEG@komOkoGOooWIJJINc4VlPzPwA "Python 3 – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 1 byte
```
⇧
```
[Try It Online!](https://vyxapedia.hyper-neutrino.xyz/tio#WyIiLCLih6ciLCIiLCIiLCJbMiwgNiwgMSwgOSwgMSwgMiwgM10iXQ==)
0-indexed
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 1 [byte](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
ƙ
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDNiU5OSZmb290ZXI9JUUyJTgxJUJBJmlucHV0PSU1QjclMkMlMjA0JTJDJTIwNSU1RCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMC0lM0UlMjAlNUIyJTJDJTIwMyUyQyUyMDElNUQlMEElNUIxJTJDJTIwMiUyQyUyMDMlNUQlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAtJTNFJTIwJTVCMSUyQyUyMDIlMkMlMjAzJTVEJTBBJTVCMiUyQyUyMDYlMkMlMjAxJTJDJTIwOSUyQyUyMDElMkMlMjAyJTJDJTIwMyU1RCUyMCUyMC0lM0UlMjAlNUIzJTJDJTIwNSUyQyUyMDElMkMlMjA2JTJDJTIwNyUyQyUyMDIlMkMlMjA0JTVEJTBBJTVCNCU1RCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMC0lM0UlMjAlNUIxJTVEJmZsYWdzPUM=)
Same as the other golflangs - built-in for "grade up".
] |
[Question]
[
You must produce a function which nests a string `s` inside an array, `n` times
```
>>> N("stackoverflow",2)
[['stackoverflow']]
```
# Parameters:
1. `s` - An ascii string
2. `n` - An integer `>= 0`
## Rules
* Shortest code wins.
* The output will be a nested `array`, `list` or `tuple` (or similar type based off an array)
## Test Cases
```
>>> N("stackoverflow",0)
'stackoverflow'
>>> N("stackoverflow",1)
['stackoverflow']
>>> N("stackoverflow",5)
[[[[['stackoverflow']]]]]
```
---
Inspired by: [Nesting a string inside a list n times ie list of a list of a list](https://stackoverflow.com/questions/40083007/nesting-a-string-inside-a-list-n-times-ie-list-of-a-list-of-a-list#40083670)
[Answer]
# Java and C#, 62 bytes
```
Object f(String s,int n){return n<1?s:new Object[]{f(s,n-1)};}
```
Should work without modification in both Java and C#.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 3 bytes
**Code**
```
`F)
```
**Explanation**
```
` # Flatten the input array on the stack.
F # Element_2 times do:
) # Wrap the total stack into a single array.
```
This means that this also works for the **0**-testcase, since the string is already on the stack.
[Try it online!](http://05ab1e.tryitonline.net/#code=YEYp&input=WyJzdGFja292ZXJmbG93IiwgNV0)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 2 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
W¡
```
Slightly confusing, since: (1) Jelly has no strings, only lists of characters; and (2); the output wont show the nesting. To see that this actually is doing what is asked look at a Python string representation of the result with:
```
W¡ŒṘ
```
An extra pair of `[]` will be present since the string itself will be a list of characters. [For example](http://jelly.tryitonline.net/#code=V8KhxZLhuZg&input=&args=InN0YWNrb3ZlcmZsb3ci+NQ)
### How?
```
W¡ - Main link: s, n
W - wrap left, initially s, in a list
¡ - repeat previous link n times
```
The proof-of-concept code adds:
```
W¡ŒṘ - Main link: s, n
ŒṘ - Python string representation
```
[Answer]
## JavaScript (ES6), 20 bytes
```
d=>g=n=>n--?[g(n)]:d
```
Although people normally nag me to curry my functions for the 1-byte saving, this is a case where it actually contributes to the solution.
[Answer]
## Mathematica, 13 bytes
```
List~Nest~##&
```
[Answer]
# [CJam](//sourceforge.net/projects/cjam), ~~7~~ 6 bytes
```
{{a}*}
```
[Online interpreter](//cjam.aditsu.net#code=r%7E%7E%7Ba%7D*&input=%5B%22stackoverflow%225%5D)
This is an unnamed function that takes its arguments from the stack as `S N`, `S` being the string and `N` being the wraps. You can execute it with the `~` operator, meaning eval.
Explanation:
```
{{a}*}
{ Open block [A B]
{ Open block [A]
a Wrap in array [[A]]
} Close block [A B λwrap]
* Repeat [A:wrap(*B)]
} Close block ["S" N λ(λwrap)repeat]
```
[Answer]
# Javascript ES6, 23 bytes
Recursive function
```
f=(a,i)=>i?f([a],--i):a
console.log(f("stackoverflow",0))
console.log(f("stackoverflow",1))
console.log(f("stackoverflow",2))
console.log(f("stackoverflow",5))
```
Currying results in the same length
```
f=a=>i=>i?f([a])(--i):a
```
[Answer]
# [Brachylog](http://github.com/JCumin/Brachylog), 10 bytes
```
tT,?h:T:gi
```
[Try it online!](http://brachylog.tryitonline.net/#code=dFQsP2g6VDpnaQ&input=WyJzdGFjayBvdmVyZmxvdyI6NV0&args=Wg)
### Explanation
```
tT, T is the integer (second element of the Input)
?h:T:g The list [String, T, built-in_group]
i Iterate: Apply built-in_group T times to String
```
This would be 3 bytes if it wasn't bugged. Here we need all this to get the list `[String, T, built-in_group]` even though `[String, T]` is already our input.
Unfortunately `:g` directly results in `[[String, T], built-in_group]`, which is not recognized properly by `i` because the integer `T` is inside the first list.
[Answer]
# MATL, 6 bytes
```
ji:"Xh
```
This produces a nested cell array as the output. With MATL's default display, however, you can't necessary *see* that's what it is since it won't show all of the curly braces. The demo below is a slightly modified version which shows the string representation of the output.
```
ji:"Xh]&D
```
[**Try it Online**](http://matl.tryitonline.net/#code=amk6IlhoXSZE&input=c3RhY2tvdmVyZmxvdwo1)
**Explanation**
```
j % Explicitly grab the first input as a string
i % Explicitly grab the second input as an integer (n)
:" % Create an array [1...n] and loop through it
Xh % Each time through the loop place the entire stack into a cell array
% Implicit end of for loop and display
```
[Answer]
## Pyke, 3 bytes
```
V]1
```
[Try it here!](http://pyke.catbus.co.uk/?code=V%5D1&input=4%0Astackoverflow)
[Answer]
# Python, 32 bytes
```
N=lambda s,n:n and[N(s,n-1)]or s
```
[Answer]
# [Pyth](//github.com/isaacg1/pyth), 3 bytes
```
]Fw
```
[Permalink](//pyth.herokuapp.com?code=%60%5DFw&input=4%0A3&test_suite=1&test_suite_input=0%0Astackoverflow%0A1%0Astackoverflow%0A5%0Astackoverflow&input_size=2)
This will output something like `...[[[[['string']]]]]...`. It will not quote for zero depth: `string`.
Explanation:
```
]Fw
Q Implicit: Eval first input line
] Function: Wrap in array
w Input line
F Apply multiple times
```
If you want quoting on zero depth, use this 4-byte solution instead (explanation):
```
`]Fw
Q Implicit: Eval first input line
] Function: Wrap in array
w Input line
F Apply multiple times
` Representation
```
[Answer]
# PHP, 60 Bytes
```
for($r=$argv[1];$i++<$argv[2];)$r=[$r];echo json_encode($r);
```
48 Bytes if it looks only like the task
```
for($r=$argv[1];$i++<$argv[2];)$r="[$r]";echo$r;
```
[Answer]
# Ruby: 23 bytes
```
->n,s{n.times{s=[s]};s}
```
This is updated to make it a callable Proc rather than the original snippet. I'd be interested to know whether there's a way to have `s` implicitly returned rather than having to explicitly return it.
[Answer]
## C, ~~44 bytes~~, 41 bytes
```
int*n(int*s,int a){return a?n(&s,a-1):s;}
```
You can test it by doing the following:
```
int main(void) {
char* s = "stackoverflow";
/* Test Case 0 */
int* a = n(s,0);
printf("'%s'\n", a);
/* Test Case 1 */
int* b = n(s,1);
printf("['%s']\n", *b);
/* Test Case 2 */
int** c = n(s,2);
printf("[['%s']]\n", **c);
/* Test Case 3 */
int*** d = n(s,3);
printf("[[['%s']]]\n", ***d);
/* Test Case 4 */
int********** e = n(s,10);
printf("[[[[[[[[[['%s']]]]]]]]]]\n", **********e);
return 0;
}
```
The output:
```
'stackoverflow'
['stackoverflow']
[['stackoverflow']]
[[['stackoverflow']]]
[[[[[[[[[['stackoverflow']]]]]]]]]]
```
Of course, you'll get warnings. This works on `gcc` on bash on my Windows machine (`gcc version 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04.3)`, as well as on a true Linux machine (`gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5)`).
[Answer]
# k, 3 bytes
```
,:/
```
Taken as a dyadic function, `/` will iteratively apply the left-hand function `,:` (`enlist`) n times to the second argument.
Example:
```
k),:/[3;"hello"]
,,,"hello"
```
[Answer]
# [Thunno](https://github.com/Thunno/Thunno), \$ 5 \log\_{256}(96) \approx \$ 4.12 bytes
```
s{KZO
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhZLi6u9o_whbKjQgvXFJYnJ2fllqUVpOfnlXKYQYQA)
If the inputs could be taken in any order, the leading `s` could be dropped.
#### Explanation
```
s{KZO # Implicit input
s # Swap so the number is on top
{K # Loop input number of times:
ZO # Wrap in a list
# Implicit output
```
[Answer]
# Ruby, 25 characters
Rewrite of [jamylak](https://codegolf.stackexchange.com/users/4094/jamylak)'s [Python solution](https://codegolf.stackexchange.com/a/96488).
```
f=->s,n{n>0?[f[s,n-1]]:s}
```
Sample run:
```
irb(main):001:0> f=->s,n{n>0?[f[s,n-1]]:s}
=> #<Proc:0x00000002006e80@(irb):1 (lambda)>
irb(main):002:0> f["stackoverflow",0]
=> "stackoverflow"
irb(main):003:0> f["stackoverflow",1]
=> ["stackoverflow"]
irb(main):004:0> f["stackoverflow",5]
=> [[[[["stackoverflow"]]]]]
```
[Answer]
## C# 6, 50 bytes
```
dynamic a(dynamic s,int n)=>n<2?s:a(new[]{s},n-1);
```
[Answer]
# Ruby, 24 bytes
```
f=->*s,n{s[n]||f[s,n-1]}
```
Called the same as in [manatwork's answer](https://codegolf.stackexchange.com/a/96491/6828), but a weirder implementation. `*s` wraps the input (a possibly-nested string) in an array. Then if `n` is zero, `s[n]` returns the first element of `s`, turning the function into a no-op. Otherwise, it returns `nil` since `s` will only ever have one element, so we pass through to the recursive call.
[Answer]
# [V](http://github.com/DJMcMayhem/V), 6 bytes
```
Àñys$]
```
[Try it online!](http://v.tryitonline.net/#code=w4DDsXlzJF0&input=J0hlbGxvLCB3b3JsZCEi&args=NA)
Explanation:
```
À "Arg1 times
ñ "repeat:
ys$ "surround this line
] "with square brackets
```
[Answer]
# [Perl 6](https://perl6.org), 23 bytes
```
{($^a,{[$_]}...*)[$^b]}
```
## Expanded:
```
{ # bare block lambda with two placeholder parameters 「$a」 and 「$b」
(
# generate Sequence
$^a, # declare first input
{ [ $_ ] } # lambda that adds one array layer
... # do that until
* # Whatever
)[ $^b ] # index into the sequence
}
```
[Answer]
## Agda, 173 bytes
Since the return type of the function depends on the number given as argument, this is clearly a case where a dependently typed language should be used. Unfortunately, golfing isn't easy in a language where you have to import naturals and lists to use them. On the plus side, they use `suc` where I would have expected the verbose `succ`. So here is my code:
```
module l where
open import Data.List
open import Data.Nat
L : ℕ -> Set -> Set
L 0 a = a
L(suc n)a = List(L n a)
f : ∀ n{a}-> a -> L n a
f 0 x = x
f(suc n)x = [ f n x ]
```
(I hope I found all places where spaces can be omitted.) `L` is a type function that given a natural `n` and a type `a` returns the type of `n` times nested lists of `a`, so `L 3 Bool` would be the type of lists of lists of lists of `Bool` (if we had imported `Bool`). This allows us to express the type of our function as `(n : ℕ) -> {a : Set} -> a -> L n a`, where the curly braces make that argument implicit. The code uses a shorter way to write this type. The function can now be defined in an obvious way by pattern matching on the first argument.
Loading this file with an `.agda` extension into emacs allows to use `C-c C-n` (evaluate term to normal form), input for example `f 2 3` and get the correct answer in an awkward form: `(3 ∷ []) ∷ []`. Now of course if you want to do that with strings you have to import them...
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
@[X]}gNÅ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QFtYXX1nTsU&input=OAoiSmFwdCIKLVE)
[Answer]
## [Jellyfish](http://github.com/iatorm/jellyfish), 8 bytes
```
p\Ai
;i
```
[Try it online!](http://jellyfish.tryitonline.net/#code=cFxBaQogO2k&input=NAoidGVzdCI)
Unary `;` wraps its argument in a list. Binary `\` on a function and a value `n` iterates that function `n` times.
[Answer]
# PHP, 44 bytes
```
function n($s,$n){return$n?n([$s],--$n):$s;}
```
nothing sophisticated, just a recursive function
[Answer]
## Python 2, 32 bytes
```
lambda s,n:eval('['*n+`s`+']'*n)
```
Puts `n` open brackets before the string and `n` close brackets before it, then evals the result. If a string output is allowed, the `eval` can be removed.
[Answer]
# [Actually](http://github.com/Mego/Seriously), 4 bytes
Input is `string` then `n`. Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=YGtgbg&input=InN0YWNrb3ZlcmZsb3ciCjU)
```
`k`n
```
**Ungolfing**
```
Implicit input string, then n.
`...`n Run the function n times.
k Wrap the stack in a list.
Implicit return.
```
[Answer]
## R, 39 40 bytes
EDIT: Fixed the `n=0` issue thanks to @rturnbull.
Function that takes two inputs `s` (string) and `n` (nestedness) and outputs the nested list. Note that R-class `list` natively prints output differently than most other languages, however, is functionally similar to a key/value map (with possibly unnamed keys) or a list in python.
```
f=function(s,n)if(n)list(f(s,n-1))else s
```
**Example**
```
> f=function(s,n)if(n)list(f(s,n-1))else s
> f("hello",3)
[[1]]
[[1]][[1]]
[[1]][[1]][[1]]
[1] "hello"
> # to access the string nested 5 times in the "list-object" named "list" we can do the following
> list = f("nested string",5)
> list[[1]][[1]][[1]][[1]][[1]]
[1] "nested string"
```
[Answer]
## Racket 83 bytes
```
(for((c n))(set! s(apply string-append(if(= c 0)(list"[\'"s"\']")(list"["s"]")))))s
```
Ungolfed:
```
(define (f s n)
(for ((c n))
(set! s (apply string-append
(if (= c 0)
(list "[\'" s "\']")
(list "[" s "]"))
)))
s)
```
Testing:
```
(f "test" 3)
```
Output:
```
"[[['test']]]"
```
] |
[Question]
[
Given a lower case string. Ex:
```
s = 'abcdefghijklmnopqrstuvwxyz'
```
The goal is to make every other [vowel](https://en.m.wikipedia.org/wiki/Vowel) uppercase.
Desired output here:
```
abcdEfghijklmnOpqrstuvwxyz
```
As you can see, from `aeiou`, \$`e`\$ and \$`o`\$ get uppercased.
For `aeiou`, the desired output is:
```
aEiOu
```
There are only lowercase characters in the strings in all cases.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins.
*P.S. The [vowels](https://en.m.wikipedia.org/wiki/Vowel) are `aeiou`*
[Answer]
# [Perl 5](https://www.perl.org/), 23 bytes
```
s/[aeiou]/$&^$"x$|--/ge
```
[Try it online!](https://tio.run/##K0gtyjH9/79YPzoxNTO/NFZfRS1ORalCpUZXVz899f9/sOi//IKSzPy84v@6BQA "Perl 5 – Try It Online")
## Explanation
`s///`ubstitutes each of the lowercase vowels with itself XORed with either 1 or 0 spaces (`$"` defaults to space) based on `$|--` which will alternate each time it's decremented.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 61 bytes
A full program, where input is taken from STDIN.
```
x;main(c){for(;read(0,&c,1);)putchar('Xz'%c?c:c^x++%2*32);}
```
[Try it online!](https://tio.run/##BcFJDkAwAAXQJRdBa0gMO124hpWkvnlWUxFnr/fg1YBSko28nQjoW82CMFHygviuCTegjC7HjoYLYqWPrlkGEsTIpOMYoR2FlH1K8RxFWdVN2/XDOM3LKrb9OC95Pz8 "C (gcc) – Try It Online")
### Checking for vowels
Vowels are `aeiou`, which have the corresponding ASCII codes `97,101,105,111,117`. The LCM of these numbers is `1484392455`, which has the property of being evenly divisible by only the letters `aeiou`. Therefore, we can say that `c` is a vowel if `1484392455%c` equals `0`. We can compress this number by the use of multi-character constants, giving `'Xz\x08\x07'`.
# [C (clang)](http://clang.llvm.org/), 48 bytes
As offered by [@AZTECCO](https://codegolf.stackexchange.com/users/84844/aztecco), a function which takes a wide string as input, and modifies the string in-place.
```
x;f(*s){for(x=0;*s;)*s++^='Xz'%*s?0:x++%2*32;}
```
[Try it online!](https://tio.run/##S9ZNzknMS///v8I6TUOrWLM6Lb9Io8LWwFqr2FpTq1hbO85WPaKKg11dVavY3sCqQltb1UjL2Mi69n9mXolCcXSsgq2Cj1JiUnJKalp6RmZWdk5uXn5BYVFxSWlZeUVllZI1FxdIZW5iZp6GpkI1l0KaRrGmNZdCQRFQOE1DSTWnWElHASRU@x@3MQA "C (clang) – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 17 bytes
```
1,2,T`l`L`[aeiou]
```
[Try it online!](https://tio.run/##K0otycxLNPyvquGe8N9Qx0gnJCEnwSchOjE1M7809v//xKTklNS09IzMrOyc3Lz8gsKi4pLSsvKKyiousBKu3MTsVIXUstSiSoX8kozUIoWy/PLUHIXSgoLUouTE4lQA "Retina – Try It Online") Link includes test cases. Explanation:
```
[aeiou]
```
Match lower case vowels.
```
1,2,
```
Only process every other vowel.
```
T`l`L`
```
Upper case them.
Although the transliterate command has a shortcut code for vowels, they aren't of any help here so I haven't used them.
[Answer]
# [R](https://www.r-project.org/), 57 bytes
```
function(s,t=s%in%utf8ToInt("aeiou"))s-t*32*!cumsum(t)%%2
```
[Try it online!](https://tio.run/##fYw7EsIwDAV7TgGZ8YydIU1oKOAA6cMBHGODIJHAlvhd3piOBl67uy/mMN80OQg6BkKdlrxNClAJh3VPHbKurAeSypjUcL1q64WTKcmk2SjVZkDuaVdkHfR3M7i9D4cjnM7jhHS5xsRyuz@er3JkZj@qwY4WHUH0/yxb9uH5DQ "R – Try It Online")
Input is vector of character codes (for comparison to [pajonk's answer](https://codegolf.stackexchange.com/a/240507/95126)). Would be [77 bytes](https://tio.run/##NYqxDsIgFAB3v0JJSKBpl7o4SJjd616KoE/bh5aHVn8ecfCmy@Xm7Nf7JvuEliCgWOpe9yqR33XhgFRHpZeaVOSAXDPjICQmAakLx/KI2FC1bauNTVNMkyDJeSuzF4KZwZ6cP1/gehsnDPfHHCk9X8v7w6Rc/Y7BjAZtgNn9iykUz18) with input as string (for comparison to [Maël's answer](https://codegolf.stackexchange.com/a/240492/95126)).
---
*Edit*: this approach would be only [48 bytes](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T6NYp8RW0dDEwsTY0sjE1FRVtVizWLdEy9hISzG5NLe4NFejRFNV1eh/Zl5JSH5oSZqFRppGKZAKyffMK9FQSkxKTklNS8/IzMrOyc3LLygsKi4pLSuvqKxS0tTU5MKhKykxJzEvOT@zKBWfqkQgAMn/BwA) by porting [dingledooper's great modulo trick](https://codegolf.stackexchange.com/a/240487/95126)...
[Answer]
# [Python](https://www.python.org), ~~73~~ ~~71~~ ··· 58 bytes
```
lambda s,c=0:bytes(a^c|(c:=c^34087456>>a-97&32)for a in s)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3rXISc5NSEhWKdZJtDaySKktSizUS45JrNJKtbJPjjE0MLMxNTM3s7BJ1Lc3VjI000_KLFBIVMvMUijWhJqgXFGXmlWikaSQpJSYlp6SmpWdkZmXn5OblFxQWFZeUlpVXVFYpaUKVL1gAoQE)
Inputs and outputs as a byte string.
Explanation (I use a `$` sigil on variables to distinguish them from letters):
* Consider the lookup table for "letter `$a` is a vowel": this is the binary array `10001000100000100000100000` (the `1`s are at the alphabet positions of `aeiou`)
* If we store this as an integer (converting the binary array into a decimal number `35784736`), we can lookup into it using `35784736 >> 97 - alphabet_index($a) & 1`
* If `$a` is actually the ASCII code of the character, we can get its alphabet index using `$a - 97` (since `'a' == 97`)
* By taking input and output as `bytes` in Python, we can get this ASCII code basically for free
* We can reverse the lookup table to make it shorter by changing `$a - 97` to `97 - $a`, because by reversing it the trailing zeroes (for `vwxyz`) become leading zeroes and make the number smaller
* The reverse lookup table is `00000100000100000100010001 = 100000100000100010001`, or `1065233` in decimal, giving us `1065233 >> $a - 97 & 1`
* We can toggle the flag variable `$c` if `$a` is a vowel, using `$c := $c ^ (1065233 >> $a - 97 & 1)`
* We also want to uppercase `$a` sometimes. Observe that the uppercase ASCII letters differ from the lowercase letters by exactly `32`, so we can toggle the case of `$a` using `$a ^ 32`
* The case toggling should happen if both:
+ `$c` is *on* (since we initialise it to `0`, and every vowel starting with the *second* should be capitalised)
+ `$a` is a vowel
* This is equivalent to `$a ^ 32 * ($c & (1065233 >> $a - 97 & 1))`
* If we store "on" as `32` rather than just `1`, and we adjust the lookup table to return `32`/`0` rather than `1`/`0`, we'll save bytes.
* We can do this by using `1065233 * 32 = 34087456` as the magic number and `&`-ing with `32` instead of `1`. The resulting expression is `34087456 >> ($a - 97) & 32`
* We want to avoid using `34087456 >> ($a - 97) & 32` in more than one place, because it's a long expression
* Since we're modifying `$c` with a `:=` expression, we can do a computation on its value before and after modification to extract the correct value. Let `$c` be the value before modification and `$c'` be the new value
* `$c'` is different to `$c` if and only if `$a` is a vowel, so we want to capitalise if `$c` is *on* and `$c' != $c`, i.e. **`$c` is on and `$c'` is off**
* Recall that lowercase letters have the `32`s bit set, and to uppercase a letter we need to unset it. This means `$a` has the `32`s bit set initially
* By `xor`ing `$a` and `$c`, when `$c` is on, we remove the `32`s bit, uppercasing the letter
* But we only want to do this when `$a` is a vowel, so we can re-set the `32`s bit when it isn't. Thus by adding `| $c'`, the `32`s bit is added again when `$c'` is `32`. This is the case if `$c` was `32` and `$a'` was not a vowel, so the bit is only removed when `$a` is a vowel *and* `$c` is `32`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 13 bytes
```
e€ØẹTḊm2
Œuç¦
```
[Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCJl4oKsw5jhurlU4biKbTJcbsWSdcOnwqYiLCIiLCIiLFsidGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZ3MiXV0=)
```
e€ØẹTḊm2 Helper Link; get every other vowel
e€ For each element, is it in
Øẹ the list of vowels ("aeiou")?
T Get said indices
Ḋm2 Pop off the first one and take every other one
Œuç¦ Main Link
¦ Apply
Œu to-uppercase
ç to every other vowel
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes
```
ATy$_⁽⇧¨M
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJBVHkkX+KBveKHp8KoTSIsIiIsImFlaW91Il0=)
The power of triads!
## Explained
```
ATy$_⁽⇧¨M
AT # indices of vowels
y # uninterleave into two lists - this pushes a list of every second vowel and every first vowel
$_ # remove the list of every first vowel
⁽⇧¨M # and apply upper-case (a function pushed by ⁽⇧) to those indices (¨M)
```
[Answer]
# [R](https://www.r-project.org/), 94 bytes
*-26 bytes thanks to Giuseppe. -2 bytes thanks to Robin Ryder*
```
function(s){s=el(strsplit(s,""))
s[i]=toupper(s[i<-grep("[aeiou]",s)[!1:0]])
Reduce(paste0,s)}
```
See [pajonk](https://codegolf.stackexchange.com/a/240507/108550)'s and [Dominic van Essen](https://codegolf.stackexchange.com/a/240509/108550)'s answers for a clever use of `intToUtf8` and `utf8ToInt`.
[Try it online!](https://tio.run/##HcpNDsIgEEDhfU@hs2KSNqlbYy/htmFB6VBRBGTA33h2bFy@fC9Vszl01RSvsw1eMH54ICc4J47OZsEtAGLDo5VDDiVGSmKNQ7ckigJGRTYUCS3juN3teymxOdJcNImoOFO/wrcawQOoSc9klpM9X9zVh3hLnMv98Xy9AZv/MSmnvA42EWD9AQ "R – Try It Online")
[Answer]
# x86 / x86-64 machine code, 22 bytes
Takes pointer (RSI), length (RCX) in registers, modifies the string in-place. Callable from C with the x86-64 SysV calling convention as `void vowel_alt_caseflip(int dummy, char *RSI, int dummy, size_t RCX)`. Same machine code works in 32-bit mode, although none of the standard 32-bit C calling conventions match.
NASM listing, with address, machine-code bytes, and source the machine-code answer was generated from.
```
1 ;;; char *str /* RSI */, size_t len /* RCX */
2 vowel_alt_caseflip:
3 00000000 BF22822000 mov edi, 0x0208222 ; ASCII vowel bitmap, 1-indexed like ASCII codes are with 'a' = 0x61 not 0x60
4 00000005 31D2 xor edx, edx ; first vowel is not flipped
5 .loop:
6 00000007 AC lodsb ; al = *str++
7 00000008 0FA3C7 bt edi, eax ; if (bitmap & (1<<(al&31)))
8 0000000B 7306 jnc .non_vowel
9 0000000D 3056FF xor [rsi-1], dl ; caseflip or not the current character
10 00000010 80F220 xor dl, 0x20 ; toggle state for the next
11 .non_vowel:
12 00000013 E2F2 loop .loop
13 00000015 C3 ret
; next address is 0x16, size is 0x16 = 22 bytes
```
Since the input string is guaranteed to be all lowercase alphabetic, I just used XOR instead of AND with `~0` / `~0x20` to flip instead of clear the ASCII lower-case bit. It would work out to the same size with `mov dl, 0xFF` / `and [rsi-1], dl`.
[Try it online!](https://tio.run/##zVM9b9swEN35K24oYruxDUkBiiJOh6JTlg7tmAYKJZ5lxhSpkGdb7p93T5S/8oV2LAdRpN69e/fuJEPAujDbiZWh3u3WboMml4byUgacG91cC@BVuzWg0mNI2iRLPmdZBnHN4OvPb7e3EOOg0FTLZgzpRFuFLSoweol7SOkUBpAeYaNpAQM5gC9M9ykF66h7SWKm1nnO1I67B5ytGcy1D7TPpEOM6gQ2qMTUOLdXapwKBbxeM5CGE34M5C8vI7Ig6GtC@SKTnsOwrwUuYJje3AylubhKR6NRDHy0JUyts3nUclR954OepPdjUOaM6@AjMKKTTAuEcuU9WoJyIb0sCf2RQ5nO4ix5rodcVRmEQJIQ5gzrSCy2JE4yDtW7BiDaEc8eSQhRGVdw9TkTeBL9duprb0Lax6PkoMDnuzpU9@cYbglfTQ3as1vJt@kbXuf59x/5xmvCCA7bUEpjAN5sTMQN08g/Zgl2JP4ipjyJgclBwAyUswPqPFiC7J0mL7XRtmK3Nrz3aqKU15Mu/n9HTimyq/Q4NPspVvofmLHVlFferZphwqQK53JliOfEiIAlaWdhqiRJwZmvuxBVwIMsSgZWC/24NLV1zRP/iKv1pt3@fv/LL/sQ5cQe4dMKPkyYUux2fwA "Assembly (nasm, x64, Linux) – Try It Online") with a Linux `_start` caller that passes it the alphabet twice and makes write system calls before/after, so we can see that it correctly treats `u` as a vowel.
For more about the immediate bitmap strategy, and variations like using it branchlessly, see SO and two of my previous x86 answers:
* GCC turning a `switch()` statement into `bt` on a register, in [an SO answer](https://stackoverflow.com/questions/97987/advantage-of-switch-over-if-else-statement/32356125#32356125)
* [User Appreciation Challenge #1: Dennis ♦](https://codegolf.stackexchange.com/questions/123194/user-appreciation-challenge-1-dennis/123458#123458)
* [Vowels up, consonants down](https://codegolf.stackexchange.com/questions/201508/vowels-up-consonants-down/201568#201568)
---
#### Alternate version, same size
I had hoped to be able to use `xor al, 0x20` to save a byte vs. DL, but we need AL for efficient string-reading via `lodsb`. (We need a char from the string in a register to use as a source for `bt`.) We could start with `mov` there and use `stosb` to store, but that would have to be separate from a reg-reg XOR or AND, and still doesn't free up AL.
We could use `scasb` as a 1-byte `inc rdi`. Using `mov dl, [rdi]` to start, and saving the `-1` in the memory-dest addressing mode, and another byte from `xor al, 0x20` short-form, that's break-even for size and worse for efficiency (useless `scasb` reload). Or similar efficiency in 32-bit mode since we could use `inc edi` there.
```
;;; char *str /* RDI */, size_t len /* RCX */
vowel_alt_caseflip_scasb:
mov esi, 0x0208222 ; ASCII vowel bitmap, 1-indexed like ASCII codes are with 'a' = 0x61 not 0x60
xor eax, eax ; first vowel is not flipped
.loop:
mov dl, [rdi]
bt esi, edx ; if (bitmap & (1<<(c&31)))
jnc .non_vowel
xor [rdi], al ; caseflip or not the current character
xor al, 0x20 ; toggle state for the next
.non_vowel:
scasb ; inc rdi in one byte even on x86-64
loop .loop
ret
```
[Answer]
# [Dyalog APL](https://dyalog.com), 23 bytes
```
1∘⎕C@(=\≠⍨)@(∊∘'aeiou')
```
`1∘⎕C` uppercase…
`@(`…`)` at…
`=\` XNOR scan (i.e. every other) of the
`≠⍨` XOR selfie (i.e. all 0s)
`@(`…`)` at…
`∊` member
`∘` of
`'aeiou'` vowels
[Try APL online!](https://tryapl.org/?clear&q=f%E2%86%901%E2%88%98%E2%8E%95C%40(%3D%5C%E2%89%A0%E2%8D%A8)%40(%E2%88%8A%E2%88%98%27aeiou%27)%20%E2%8B%84%20f%27abcdefghijklmnopqrstuvwxyz%27%20%E2%8B%84%20f%27aeiou%27&run "TryAPL")
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 19 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
```
⊢-32×·≠`⊸<∊⟜"aeiou"
```
[Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oqiLTMyw5fCt+KJoGDiirg84oiK4p+cImFlaW91IgoKRiAiYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXoi)
Textbook use for under, but character arithmetic is much, much shorter. -10 from Marshall, then -3 from Marshall.
# Explanation
```
⊢-32×·≠`⊸<∊⟜"aeiou"
∊⟜"aeiou" bitmask of vowels
≠` inequality scan(XOR scan)
⊸< lesser than original bitmask?
32×· 32 × that
⊢- subtract from the input
```
[Answer]
# Javascript, 57 5654 bytes
```
s=>s.replace(/[aeiou]/g,c=>(s=!s)?c.toUpperCase():c)
```
-1 Thanks to Patrick Stephansen.
-2 Thanks to tsh.
-2 Thanks to l4m2.
Usage:
```
console.log((s=>s.replace(/[aeiou]/g,c=>(s=!s)?c.toUpperCase():c)))("string goes here"))
```
[Try it online](https://tio.run/##BcExDsIwDADAr7SdbAnSvVLKwBuYKgbLuCEoiiM78P1w96EfOVtu/Vr1JeOMw@PuwaQVYoH1IMn6fa7pwnEHj7PjjUPXR2tid3IB3BgHa3UtEoomOGHxbrmmKan49BaTBXH8AQ)
[Answer]
# [R](https://www.r-project.org/), 65 bytes
```
function(s){s[i]=s[i<-which(s%in%utf8ToInt("aeiou"))[!1:0]]-32;s}
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T6NYs7o4OjPWFkjY6JZnZCZnaBSrZuaplpakWYTke@aVaCglpmbmlyppakYrGloZxMbqGhtZF9f@z8wrCckPBarSSNNAVpyUnJKalp6RmZWdk5uXX1BYVFxSWlZeUVkFNEGTC4eupMScxLzk/MyiVHyqEoEAJP8fAA "R – Try It Online")
Takes input and outputs as vectors of char codes.
Some parts borrowed from [@Maël's R answer](https://codegolf.stackexchange.com/a/240492/55372).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
e€Øcn\<$a32^OỌ
```
[Try it online!](https://tio.run/##y0rNyan8/z/1UdOawzOS82JsVBKNjeL8H@7u@f//f0lGqkJhaWZytkJSUX55nkJafoVCVmluQbFCfllqkQJIOiexqlIhJT8dAA "Jelly – Try It Online")
```
e€Øc For each input character: is it in Øc (vowels)?
This gets a mask with 1s where vowels are, e.g.
“b x d e f h i z k o m u p”
0 0 0 1 0 0 1 0 0 1 0 1 0
n\<$ scanl(≠, mask) < mask: This selects every other 1.
scanl(≠): 0 0 0 1 1 1 0 0 0 1 1 0 0
original: 0 0 0 1 0 0 1 0 0 1 0 1 0
<: 0 0 0 0 0 0 1 0 0 0 0 1 0
a32 Replace all 1s by 32.
^O XOR by ord(input string).
Ọ chr()
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 41 bytes
Uses the `-p` flag.
```
i=1
gsub(/[aeiou]/){[$&,$&.upcase][i^=1]}
```
[Try it online!](https://tio.run/##FchRCsIwDADQ/54iwhgK6tgBdpJSoZ2xy89SmkYo4tWN@vM@XtXUzWiZXRZNx8lHJNYwnV5@GM/DeNWyRsHg6bbM4W0W03pwP@74yG7DDp0V@IkV2oYVnbRKe4bMKPCPD5dGvItdyhc "Ruby – Try It Online")
[Answer]
# APOL, 35 bytes
`j(ƒ(i ¿(&(c(Ⓔ ↓(∋)) ≐(∈)) ∋ ↑(∋))))`
## Explanation
```
j( Join a list to a string
ƒ( Listbuilder for
i Input
¿( Returning if (called for each item in the input)
&( And (condition)
c( String contains
Ⓔ The constant string "aeiou"
↓( To lowercase
∋ Current character
)
)
≐( Is even
∈ For loop counter
)
)
∋ For loop item (executed if true)
↑( To uppercase
∋ For loop item
)
)
)
)
```
[Answer]
# [C (tcc)](http://savannah.nongnu.org/projects/tinycc), ~~174~~ 111 bytes
*Saved 63 bytes thanks to [manatwork](https://codegolf.stackexchange.com/users/4198/manatwork)*
```
i,b;f(char*a,int l){for(i=0;i<l;i++)if(a[i]==97||a[i]=='e'||a[i]=='i'||a[i]=='o'||a[i]=='u')if(b++%2)a[i]-=32;}
```
[Try it online!](https://tio.run/##Rc5BCsMgEAXQdTyFBIpaDZSUUor1JCELI4YOpFpEV0nObpVCs3t/4PPHdNGYnEFMcqbmpcNZC3ARL2ydfaCgLhKeiwTOGcxUDzAq9bhv20/Ekj/hoD@YSO1NnJ96Vk@duvZyz28NjjK8oqZuYj2MWOFWW/CplagpSwLfWNEnlG9KrA42puAk2vMX "C (tcc) – Try It Online")
### Unminified
```
i, b;
f(char* a, int l) {
for (i = 0; i < l; i++)
if (a[i] == 97 || a[i] == 'e' || a[i] == 'i' || a[i] == 'o' || a[i] == 'u')
if (b++ % 2)
a[i] -= 32;
}
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0, 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
r\vÈpu gT°
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=clx2yHB1IGdUsA&input=ImFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6Ig)
[Answer]
# [J](http://jsoftware.com/), 33 31 bytes
```
(>~:/\)@e.&'aeiou'`(,:toupper)}
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NezqrPRjNB1S9dTUE1Mz80vVEzR0rErySwsKUos0a/9rcqUmZ@QrpCmoV1RUgBWUghiJiWAiUf0/AA "J – Try It Online")
-2 thanks to Lynn
Kind of shockingly long, but best I could find so far...
[Answer]
# Python 2, 86 bytes
-26 thanks to ElPedro.
-2 thanks to Daniel.
```
c,S=0,''
for i in input():
if i in'aeiou':S+=(i,i.upper())[c];c^=1
else:S+=i
print S
```
**[Try it online](https://tio.run/##HclNDsIgEEDhPaeY3UAkRl3WcAqWRpOKYEcrjBTUenn8Sd7qezyXIcVNa05bs9KIIqQMBBS/cS1SdQIo/AV7T6liZxdGkqZlZfZZKrVz@607mLUAP07@t0lwpljAtob90Z18OA90uY63mPiep1Ifz9f8xg8)**
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes
```
⭆S⎇№aeiouι§⁺↥ιιL⊞Oυιι
```
[Try it online!](https://tio.run/##JcpBCsIwEAXQq0hXU6gncCWuCooF9QBjOjbRmMRkprZePqZ0Mf/zeaM0RuXR5txF4xguXGo4YYDWBeF1Qt1srhQdxhkOXspbhWS8VM3GFNpz63qaoLOS4BYCRYWJYKHljuQG1tBJ0udiyD6CLFTXa@5yxrvq6TFo83zZt/PhExPL@J3mX96O9g8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
S Input string
⭆ Map over characters and join
№ Count of
ι Current character
aeiou In literal string `aeiou`
⎇ If exists then
ι Current character
↥ Uppercase
⁺ Plus
ι Current character
§ Indexed by
ι Current character
⊞O Pushed to
υ Predefined empty list
L Length after push
ι Otherwise current character
Implicitly print
```
[Answer]
# APL+WIN, 39 bytes
Prompts for string
```
⎕av[(⎕av⍳s)-32×1=i+i×≠\i←(s←⎕)∊'aeiou']
```
Index offset from lower to upper case changed in TIO from -32 to +48 to account for differences between APL+WIN and Dyalog atomic vectors.
[Try it online!Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz0NJJFYFq0Bph71bi7W1DaxODzd0DZTO/Pw9EedC2IygWo1ioEEUInmo44u9cTUzPxS9dj/QO1c/9O4oHwuECspOSU1LT0jMys7Jzcvv6CwqLiktKy8orJKHQA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 25 bytes
```
0T-1=`l`L`(.*?[aeiou]){2}
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7w3yBE19A2ISfBJ0FDT8s@OjE1M780VrPaqPb//8Sk5JTUtPSMzKzsnNy8/ILCouKS0rLyisoqLrAyrtzE7FSF1LLUokqF/JKM1CKFsvzy1ByF0oKC1KLkxOJUAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
(.*?[aeiou]){2}
```
Match the shortest possible substrings containing two vowels.
```
-1=
```
Only transliterate the last character of each match. (The `0` indicates that this modifier applies to the characters of the match rather than the matches themselves.)
```
T`l`L`
```
Upper case them.
[Answer]
# [Lua](https://www.lua.org/), 81 bytes
```
print(((...):gsub("[aeiou]",function(x)u=not u;return u and x or(x):upper()end)))
```
[Try it online!](https://tio.run/##HczBCcMwDAXQVYRPEhQPkJBJQg5u4wRDkI3qD26XV0PPD96F5N6saGfmGKNM5xtPDmvKpWILjwP66qUqD8GitRNmyx2mBEq606Bqt01oLRtL1l1E3H18vv/iBw "Lua – Try It Online")
Expects the input as first argument, prints output. Is one character shorter if `return` instead of `print` is used.
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), ~~148~~ 123 bytes
```
S =INPUT
N S ARB . L ANY('aeiou') . C REM . S :F(O)
X =1 - X
C =CHAR(ORD(C) - 32) EQ(X)
O =O L C :(N)
O OUTPUT =O S
END
```
[Try it online!](https://tio.run/##FY3LDoIwFETX7VfcHe1CEx8rki6wYDTRVgskuARFRZGqiK@fr9fVTE5OZtrGFrYeO0diEHO1ShOqsAZmAn1YQKA2zMvLynYeRyDBREvMmPhTpjklGYgB9CCjRIKQs8AwbUImObLRkEO0ZhlaGoTGMUl8pjjVRKcJHv1hTCMVOpcX2125Pxyr07m@NPZ6u7eP7vl6f74/ "SNOBOL4 (CSNOBOL4) – Try It Online")
## Explanation:
```
S =INPUT ;* Read input
N S ARB . L ANY('aeiou') . C REM . S :F(O)
;* Match in S:
;* ARBitrary string (store as L), ANY single vowel (store as C)
;* and the REMainder of the string (store as S).
;* If there is no match, goto O.
X =1 - X ;* Set X (initially treated as 0) to 1-X.
C =CHAR(ORD(C) - 32) EQ(X) ;* if X == 0, set C to uppercase, otherwise do nothing.
O =O L C :(N) ;* append to O L and C, then goto N.
O OUTPUT =O S ;* Output updated string
END
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
žMÃDεNÉiu]‡
```
[Try it online.](https://tio.run/##yy9OTMpM/f//6D7fw80u57b6He7MLI191LDw///EpOSU1LT0jMys7JzcvPyCwqLiktKy8orKKgA)
Or alternatively the `εNÉiu]` could be `2ι`u.ι`.
[Try it online.](https://tio.run/##yy9OTMpM/f//6D7fw80uRud2JpTqndv5qGHh//@JSckpqWnpGZlZ2Tm5efkFhUXFJaVl5RWVVQA)
**Explanation:**
```
žM # Push the constant "aeiou"
à # Only keep those letters from the (implicit) input
D # Duplicate it
ε # Map the vowels in the copy to:
NÉi # If the 0-based index is odd:
u # Uppercase the vowel
] # Close the if-statement and map
‡ # Transliterate the lowercase vowels to the alternating cased vowels
# in the (implicit) input
# (after which the result is output implicitly)
2ι # Uninterleave into two parts
` # Pop and push both parts separated to the stack
u # Uppercase the second part
.ι # And interleave the two parts back again (to a list of characters)
```
[Answer]
# [Headascii](https://esolangs.org/wiki/Headass#Headascii), 142 bytes
```
----[]]]][]][++++^^^^D^^^^^+^{{D^(U):++++(R):++++(R):++++++(R):++++++(R):R()+E:P};RP{D^(U):++++(R):++++(R):++++++(R):++++++(R):R()+E:P};R]P}.!
```
[Try it here!](https://replit.com/@thejonymyster/HA23) Code will have to be copied, and executed like this:
```
erun("----[]]]][]][++++^^^^D^^^^^+^{{D^(U):++++(R):++++(R):++++++(R):++++++(R):R()+E:P};RP{D^(U):++++(R):++++(R):++++++(R):++++++(R):R()+E:P};R]P}.!","your input")
```
This one was fun, not sure if there's any room for serious golfing without a different approach. Maybe something with an oscillator to decide whether to uppercase a given vowel? But the 3 main storage registers are used up for comparison, storing -32 (uppercase constant), and storing 97 (ascii a, first vowel). So I'm not sure where the constant would be held. I'll take another whack at it sometime though.
```
----[]]]][]][++++^^^^D^^^^^+^ Constants -32 and 97
---- -4
[]]]] *4
[]][ *2, and store
++++ 4
^^^^ *4
D^^^^^+^ *6+1, already stored
{{...};RP{...};R]P}. The rest of block 0
{ } Loop
{ } Loop until a vowel is found
;RP Concatenate it to the string register
{ } Loop until a vowel is found
;R]P Subtract 32 (uppercase) and concatenate to string register
. Block separator
{D^(U):++++(R):++++(R):++++++(R):++++++(R):R()+E:P} First loop
{ } Loop
D^(U) If byte is "a",
++++(R) "e"
++++(R) "i"
++++++(R) "o"
++++++(R) or "u",
: : : : : Exit loop.
Else,
R() If byte is null (i.e. string ended)
+E Go to block 1
: Else,
P Concatenate byte to string register
{D^(U):++++(R):++++(R):++++++(R):++++++(R):R()+E:P} Second Loop is identical to the first
Avoiding two identical loops would be
a major golfing opportunity
! Block 1
! Print string register, end of execution
```
[Answer]
# [Factor](https://factorcode.org/), 65 bytes
```
[ dup [ "aeiou"in? ] arg-where <odds> over [ 32 - ] change-nths ]
```
[Try it online!](https://tio.run/##RYoxEoIwEAB7XnGTHgvt1NHSsbFhrBiKMzlIJCRwSQD9fKSz2WJ3W5TRc35W98ftCD2xIwuBYtgwJXKSwo7WyBhgwKj/FoyHU1EIfElFbafNu7eD8@PEIaZ5WT9fkWtQaYQaBJLxSRh3hQaQu3LRxARnr1S4gJ@Jt@mwh3LLUqPrqHRRB2iyRGthZONi/gE "Factor – Try It Online")
## Explanation
Get the indices of the vowels from the input, take the odd-indexed elements of those, then subtract 32 from the input at those indices. `change-nths` is a mutating word which has the usual `( indices seq -- )` stack effect which is why we need an extra copy on the stack before we call it.
```
! "abcdefghijklmnopqrstuvwxyz"
dup ! "abcdefghijklmnopqrstuvwxyz" "abcdefghijklmnopqrstuvwxyz"
[ "aeiou"in? ] arg-where ! "abcdefghijklmnopqrstuvwxyz" V{ 0 4 8 14 20 }
<odds> ! "abcdefghijklmnopqrstuvwxyz" { 4 14 }
over ! "abcdefghijklmnopqrstuvwxyz" { 4 14 } "abcdefghijklmnopqrstuvwxyz"
[ 32 - ] change-nths ! "abcdEfghijklmnOpqrstuvwxyz"
```
[Answer]
# [Uiua](https://uiua.org), 17 [bytes](https://codegolf.stackexchange.com/a/265917/97916)
```
-×32×\≠.∊,"aeiou"
```
[Try it!](https://uiua.org/pad?src=ZiDihpAgLcOXMzLDl1ziiaAu4oiKLCJhZWlvdSIKCmYgImFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6IgpmICJhZWlvdSIK)
Port of Razetime's [BQN answer](https://codegolf.stackexchange.com/a/240488/97916).
```
-×32×\≠.∊,"aeiou"
∊,"aeiou" # mask of where vowels are in input
. # duplicate
\≠ # inequality scan
× # multiply
×32 # multiply by 32
- # subtract (capitalize)
```
] |
[Question]
[
Write shortest code to print the following Multiplication Table:
```
1×1=1
1×2=2 2×2=4
1×3=3 2×3=6 3×3=9
1×4=4 2×4=8 3×4=12 4×4=16
1×5=5 2×5=10 3×5=15 4×5=20 5×5=25
1×6=6 2×6=12 3×6=18 4×6=24 5×6=30 6×6=36
1×7=7 2×7=14 3×7=21 4×7=28 5×7=35 6×7=42 7×7=49
1×8=8 2×8=16 3×8=24 4×8=32 5×8=40 6×8=48 7×8=56 8×8=64
1×9=9 2×9=18 3×9=27 4×9=36 5×9=45 6×9=54 7×9=63 8×9=72 9×9=81
```
[Answer]
## Excel, ~~92~~ 91 Bytes
From the VBA editor's immediate window, run the following command:
`Range("A1:I9").Formula="=IF(ROW()<COLUMN(),"""",COLUMN()&""×""&ROW()&""=""&COLUMN()*ROW())"`
The output is directly on the active worksheet.
[](https://i.stack.imgur.com/8r4jl.png)
I golfed an extra byte by swapping the order of an `if` to change `>=` to `<`. I didn't update the screenshot, but it only affects the formula at the top, not the output.
[Answer]
# Python (75)
```
r=range(1,10)
for i in r:print''.join('%sx%s=%-3s'%(j,i,i*j)for j in r[:i])
```
a little better golfed than the other two Python versions.
[Answer]
# C++, ~~106~~ 98 bytes
I used two loops and a few tricks.
```
#import <cstdio>
main(){for(int i,j;i++-9;j=0)while(j++-i)printf("%dx%d=%d%c",j,i,i*j,j<i?32:10);}
```
[Answer]
# J: 57 51 characters
```
([:;"2*\#"2(":@],'x',":@[,'=',":@*,' '"_)"0/~)>:i.9
```
No loops.
[Answer]
## APL (37)
```
∆∘.{⊃(⍺≥⍵)/,/(⍕⍺)'×'(⍕⍵)'=',⍕⍺×⍵}∆←⍳9
```
And it's not even just two for-loops. In APL, the following construct:
```
x ∘.F y
```
where `x` and `y` are lists, and `F` is a function, applies `F` to each pair of items in `x` and `y` and gives you a matrix.
So: `∆∘.×∆←⍳9` gets you a multiplication table from 1 to 9. The above function generates the required string for each pair, i.e. `(⍕⍺)`, string representation of the first number, followed by `×`, followed by `(⍕⍵)`, string representation of the second number, followed by `=`, followed by `⍕⍺×⍵`, as long as `⍺≥⍵`.
[Answer]
# Ruby: ~~60~~ 59 characters
```
1.upto(9){|i|puts (1..i).map{|j|"%dx%d=%-3d"%[j,i,i*j]}*""}
```
Sample run:
```
bash-4.2$ ruby -e '1.upto(9){|i|puts (1..i).map{|j|"%dx%d=%-3d"%[j,i,i*j]}*""}'
1x1=1
1x2=2 2x2=4
1x3=3 2x3=6 3x3=9
1x4=4 2x4=8 3x4=12 4x4=16
1x5=5 2x5=10 3x5=15 4x5=20 5x5=25
1x6=6 2x6=12 3x6=18 4x6=24 5x6=30 6x6=36
1x7=7 2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49
1x8=8 2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64
1x9=9 2x9=18 3x9=27 4x9=36 5x9=45 6x9=54 7x9=63 8x9=72 9x9=81
```
[Answer]
# Perl, 54 Characters
```
printf"%dx$?=%-3d"x$?.$/,map{$_,$_*$?}1..$?while$?++<9
```
[Answer]
## APL (Dyalog), 28
```
↑{⍵{⍕⍵,'×',⍺,'=',⍺×⍵}¨⍳⍵}¨⍳9
```
Analogous to a double loop in other languages
`{⍵{...}¨⍳⍵}¨⍳9` sets up the double loop
`⍕⍵,'×',⍺,'=',⍺×⍵` creates the string for each pair
`↑` Convert array of array of strings to a matrix of stings
**Output**
```
1 × 1 = 1
1 × 2 = 2 2 × 2 = 4
1 × 3 = 3 2 × 3 = 6 3 × 3 = 9
1 × 4 = 4 2 × 4 = 8 3 × 4 = 12 4 × 4 = 16
1 × 5 = 5 2 × 5 = 10 3 × 5 = 15 4 × 5 = 20 5 × 5 = 25
1 × 6 = 6 2 × 6 = 12 3 × 6 = 18 4 × 6 = 24 5 × 6 = 30 6 × 6 = 36
1 × 7 = 7 2 × 7 = 14 3 × 7 = 21 4 × 7 = 28 5 × 7 = 35 6 × 7 = 42 7 × 7 = 49
1 × 8 = 8 2 × 8 = 16 3 × 8 = 24 4 × 8 = 32 5 × 8 = 40 6 × 8 = 48 7 × 8 = 56 8 × 8 = 64
1 × 9 = 9 2 × 9 = 18 3 × 9 = 27 4 × 9 = 36 5 × 9 = 45 6 × 9 = 54 7 × 9 = 63 8 × 9 = 72 9 × 9 = 81
```
[Answer]
## *Mathematica*, 45
Pretty boring, but I guess it serves as a syntax comparison:
```
Grid@Table[Row@{a, "x", b, "=", a b}, {a, 9}, {b, a}]
```
[Answer]
# D, 75 chars
```
foreach(i,1..10){foreach(j,1..i+1){writef("%dx%d=%d ",i,j,i*j);}writeln();}
```
you just said code not function or full program
[Answer]
## VBScript (133); without loops.
```
g=""
sub m(x,y)
g=x&"x"&y&"="&x*y&vbTab&g
if x>1 then
m x-1,y
elseif y>1 then
g=vbLf&g
m y-1,y-1
end if
end sub
m 9,9
wscript.echo g
```
On request of the challenger: no loops. This code uses recursive subroutine calls.
[Answer]
# Maple, 64
```
seq(printf(seq(printf("%ax%a=%a ",j,i,i*j),j=1..i),"\n"),i=1..9)
```
[Answer]
# x86\_64 machine code (linux), ~~175~~ ~~99~~ 76 bytes
```
0000000000400080 <_start>:
400080: 66 bf 09 00 mov $0x9,%di
0000000000400084 <_table.L2>:
400084: 6a 0a pushq $0xa
400086: 89 fe mov %edi,%esi
0000000000400088 <_table.L3>:
400088: 89 f0 mov %esi,%eax
40008a: f7 e7 mul %edi
000000000040008c <_printInteger>:
40008c: 6a 20 pushq $0x20
40008e: 3c 0a cmp $0xa,%al
400090: 7d 02 jge 400094 <_printInteger.L1>
400092: 6a 20 pushq $0x20
0000000000400094 <_printInteger.L1>:
400094: 66 31 d2 xor %dx,%dx
400097: b3 0a mov $0xa,%bl
400099: 66 f7 f3 div %bx
40009c: 83 c2 30 add $0x30,%edx
40009f: 52 push %rdx
4000a0: 66 85 c0 test %ax,%ax
4000a3: 75 ef jne 400094 <_printInteger.L1>
4000a5: 6a 3d pushq $0x3d
4000a7: 66 57 push %di
4000a9: 80 04 24 30 addb $0x30,(%rsp)
4000ad: 6a 78 pushq $0x78
4000af: 66 56 push %si
4000b1: 80 04 24 30 addb $0x30,(%rsp)
4000b5: ff ce dec %esi
4000b7: 75 cf jne 400088 <_table.L3>
4000b9: ff cf dec %edi
4000bb: 75 c7 jne 400084 <_table.L2>
00000000004000bd <_printChars>:
4000bd: 66 ba 00 08 mov $0x800,%dx
4000c1: b0 01 mov $0x1,%al
4000c3: 66 bf 01 00 mov $0x1,%di
4000c7: 48 89 e6 mov %rsp,%rsi
4000ca: 0f 05 syscall
```
~~This is a dump of the binary file, and all of this is 175 bytes. It basically does the same two loops that all the answers do, but printing to the console is a bit harder and basically requires pushing the characters to print onto the stack in reverse, and then making a (linux specific) syscall to actually put those chars into stdout.~~
I've now optimized this so that only 1 write operation is performed (faster!) and has magic numbers (wow!) and by pushing the entire result onto the stack backwards before making the syscall. I also took out the exit routine because who needs proper exit code?
Here's a link to my [first](https://bitbucket.org/daveyhughes/ppcg/raw/8d730dafacaf6492673e3d348d2003e1485b8697/asm/mult_table.asm) and [second](https://bitbucket.org/daveyhughes/ppcg/raw/8d730dafacaf6492673e3d348d2003e1485b8697/asm/mult_table2.asm) attempts, in their original nasm syntax.
I welcome anyone who has any other suggestions on how it can be improved. I can also explain the logic in more detail if anyone is curious.
~~(Also, it doesn't print the extra spaces to make all the columns aligned, but if that's required I can put the logic in at the cost of a few more bytes).~~
EDIT: Now prints extra spaces and is golfed down even more! It's doing some pretty crazy stuff with the registers, and is probably unstable if this program were to be expanded.
[Answer]
## Javascript, 190 bytes
Late to the party, but I was piqued by @jdstankosky 's comment and decided to take a different approach. Here's a Javascript entry that mauls a template and evals itself along the way.
```
t="a*b=c ";u="";r=u;for(i=1;i<10;i++){a=0;u=u+t;r+=u.split(' ').map(x=>x.replace('a',++a).replace('b',i)).map(x=>x.replace('*','x').replace('c',eval(x.substr(0,3)))).join(' ')+'\n'}alert(r);
```
Un-golfed version (slightly older version in which a function returns the table instead of a script alerting it, but the same principles apply):
```
function f()
{
t="a*b=c "; // template for our multiplication table
u="";r=""; // tmp- and return values
for(i=1;i<10;i++)
{
a=0; // is auto-incremented in MAP
u=u+t;// extend the template once per iteration
v=u.split(' '); // Smash the template to pieces
w=v.map(x=>x.replace('a', ++a).replace('b', i)) // MAP replaces the A and B's with the correct numbers
w=w.map(x=>x.replace('*', 'x').replace('c', eval(x.substring(0,3)))).join(' '); // second map evals that and replaces c with the answer, makes the asteriks into an X
r=r+w+'\n' // results get concatenated
}
return r;
}
```
[Answer]
# Fourier, ~~756~~ 632 bytes
Thanks @BetaDecay for 124 bytes!
```
1o120~Ea1o61a1o10~Na1oEa2o61a2o32~Saa2oEa2o61a4oNa1oEa3o61a3oSaa2oEa3o61a6oSaa3oEa3o61a9o^a1oEa4o61a4oSaa2oEa4o61a8oSaa3oEa4o61a12oSa4oEa4o61a16oNa1oEa5o61a5oSaa2oEa5o61aNoSa3oEa5o61a15oSa4oEa5o61a20oSa5oEa5o61a25oNa1oEa6o61a6oSaa2oEa6o61a12oSa3oEa6o61a18oSa4oEa6o61a24oSa5oEa6o61a30oSa6oEa6o61a36oNa1oEa7o61a7oSaa2oEa7o61a14oSa3oEa7o61a21oSa4oEa7o61a28oSa5oEa7o61a35oSa6oEa7o61a42oSa7oEa7o61a49oNa1oEa8o61a8oSaa2oEa8o61a16oSa3oEa8o61a24oSa4oEa8o61aSoa5oEa8o61a40oSa6oEa8o61a48oSa7oEa8o61a56oSa8oEa8o61a64oNa1oEa9o61a9oSaa2oEa9o61a18oSa3oEa9o61a27oSa4oEa9o61a36oSa5oEa9o61a45oSa6oEa9o61a54oSa7oEa9o61a63oSa8oEa9o61a72oSa9oEa9o61a81o
```
[Answer]
# [Pascal (FPC)](https://www.freepascal.org/), ~~128 125~~ 138 bytes
One recursive procedure takes care of everything. Call with `m(9,9)`.
```
procedure m(i,j:int8);begin if i<1then Exit;if i=j then begin m(i-1,j-1);writeln;end;m(i-1,j);write(i,'x',j,'=',i*j,' ':2-i*j div 10);end;
```
Ungolfed:
```
procedure m(i, j: int8);
begin
if i<1 then
Exit;
if i=j then
begin
m(i-1, j-1);
writeln;
end;
m(i-1, j);
write(i,'x',j,'=',i*j,' ':2-i*j div 10);
end;
```
The reason for the byte count going up: the output was not aligned correctly. It is fixed now.
[Try it online!](https://tio.run/##LYxBEsIgFEP3PcXfUZyPI65ssUsPUoHqZ1pkELW3R8SukrxJEsanHmcxBZ1ziA9tzStaWFpC15NPJ66u9kYeaAI6y3S3Hi4rJfXLg4MK/o2yERKdkFx9IiU7e2W9URveYPllK0OHbGBIu6LA@qMoDgy9QR54HeV62Sxthx1XTUH7/AU "Pascal (FPC) – Try It Online")
[Answer]
# [ConTeXt](https://wiki.contextgarden.net/Main_Page), ~~67~~ 60 bytes
```
\let~\dorecurse\starttext~9{~#1{##1x#1=\luaexpr{#1*##1} }
}
```
[](https://i.stack.imgur.com/R9maS.png)
[Answer]
## vba 55
(immediate window)
```
for f=1 to 9:for j=1 to f:?f;"x";j;"=";f*j,:next:?:next
```
note - GWBasic only needs 2 extra characters:
```
1 for f=1 to 9:for j=1 to f:?f;"x";j;"=";f*j,:next:?:next
```
[Answer]
## Javascript, 75
```
for(s="",a=b=1;a<10;b=a==b?(a++,alert(s),s="",1):b+1)s+=b+"x"+a+"="+a*b+" "
```
I wonder if something better than two (combined?) for loops is possible...
[Answer]
# Coreutils/Bash: 147 136 135
```
for i in {1..9}; do
yes $'\n' | head -n $[i-1] > $i
paste -dx= <(yes $i) <(seq $i 9) <(seq $[i*i] $i $[9*i]) |head -n$[10-i] >> $i
done
paste {1..9}
```
Golfed, using explicit newline and, using deprecated head option (thanks manatwork):
```
for i in {1..9};do yes '
'|head -$[i-1]>$i;paste -dx= <(yes $i) <(seq $i 9) <(seq $[i*i] $i $[9*i])| head -$[10-i]>>$i;done;paste {1..9}
```
Output:
```
1x1=1
1x2=2 2x2=4
1x3=3 2x3=6 3x3=9
1x4=4 2x4=8 3x4=12 4x4=16
1x5=5 2x5=10 3x5=15 4x5=20 5x5=25
1x6=6 2x6=12 3x6=18 4x6=24 5x6=30 6x6=36
1x7=7 2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49
1x8=8 2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64
1x9=9 2x9=18 3x9=27 4x9=36 5x9=45 6x9=54 7x9=63 8x9=72 9x9=81
```
[Answer]
# Python 2, 72
```
i=1;exec"j=1;exec'print\"%sx%s=%-2s\"%(j,i,j*i),;j+=1;'*i;print;i+=1;"*9
```
Output:
```
1x1=1
1x2=2 2x2=4
1x3=3 2x3=6 3x3=9
1x4=4 2x4=8 3x4=12 4x4=16
1x5=5 2x5=10 3x5=15 4x5=20 5x5=25
1x6=6 2x6=12 3x6=18 4x6=24 5x6=30 6x6=36
1x7=7 2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49
1x8=8 2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64
1x9=9 2x9=18 3x9=27 4x9=36 5x9=45 6x9=54 7x9=63 8x9=72 9x9=81
```
[Answer]
## LOLCODE, 202 bytes
```
IM IN YR o UPPIN YR b TIL BOTH SAEM b AN 10
c R ""
IM IN YR i UPPIN YR a TIL BOTH SAEM a AN SUM OF b AN 1
c R SMOOSH c SMOOSH a "x" b "=" PRODUKT OF a AN b " " MKAY
IM OUTTA YR i
VISIBLE c
IM OUTTA YR o
```
Ungolfed:
```
HAI 1.3 BTW Unnecessary in current implementations
IM IN YR outer UPPIN YR multiplicand TIL BOTH SAEM multiplicand AN 10
I HAS A output ITZ ""
IM IN YR inner UPPIN YR multiplier TIL BOTH SAEM multiplier AN SUM OF multiplicand AN 1
output R SMOOSH output AN SMOOSH multiplier AN "x" AN multiplicand AN "=" AN PRODUCKT OF multiplicand AN multiplier AN " " MKAY MKAY BTW AN is optional to separate arguments, a linebreak is an implicit MKAY.
IM OUTTA YR inner
VISIBLE output
IM OUTTA YR outer
KTHXBYE BTW Unnecessary in current implementations
```
Pythonated for non-leetspeakers:
```
for multiplicand in range(1, 10):
output = ""
for multiplier in range(1, multiplicand + 1):
output = output + (multiplier + "x" + multiplicand + "=" + str(multiplicand * multiplier) + " ")
print(output)
```
[Answer]
**c#, 142 bytes**
```
Enumerable.Range(1,9).ToList().ForEach(i =>Enumerable.Range(1,i).ToList().ForEach(j=>Console.Write("{0}x{1}={2}{3}",j,i,j*i,j==i?"\n":"\t")));
```
And not a for in sight...
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 50 bytes
```
1v
1
?\::n"x"o{::n"="o}*n" "o1+:{:})
\~1+:a=?;ao
```
You can try it on the [online interpreter](https://fishlanguage.com/playground).
Note that there is trailing spaces on each lines, which might make it incorrect (OP hasn't stated on this point as of this answer).
[Answer]
# [///](https://esolangs.org/wiki////), 268 bytes
```
/_/\/\///x/×_N/x9=_E/x8=_V/x7=_S/x6=_F/x5=_R/x4=_O/
1_t/ 2_h/ 3/1x1=1Ox2=2tx2=4Ox3=3tx3=6 hx3=9OR4tR8 hR12 4R16OF5tF10hF15 4F20 5F25OS6tS12hS18 4S24 5S30 6S36OV7tV14hV21 4V28 5V35 6V42 7V49OE8tE16hE24 4E32 5E40 6E48 7E56 8E64ON9tN18hN27 4N36 5N45 6N54 7N63 8N72 9N81
```
[Answer]
# JAVA, ~~103 94 92~~ 90 bytes
Using JShell from Java 9 SDK allows me to save large amount of space
```
for(int i=0,j;i++<9;)for(j=1;j<=i;)System.out.print(i+"*"+j+"="+i*j+"\t"+(j++<i?"":"\n"))
```
Following Kevin's suggestion I reduced solution by 2 bytes.
Thanks to cliffroot, I was able to reduce it by another 1 byte
[Answer]
## Pyke, ~~17~~ 16 bytes (noncompeting)
Pyke was created after this question was asked
```
TFjSF\xj\=ij*s(P
```
[Try it here!](http://pyke.catbus.co.uk/?code=TFjSF%5Cxj%5C%3Dij%2as%28P&warnings=0)
```
TFj ( - for j in range(10):
SF ( - for i in range(1,j+1):
\xj\=ij*s - sum(i,"x",j,"=",i*j)
P - pretty_print(^)
```
[Answer]
## Tcl 98 chars
```
while {[incr a]<10} {set b 0;while {[incr b]<=$a} {puts -nonewline "$a×$b=[expr $a*$b] "};puts ""}
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 23 bytes
```
9õÈõ_[X'×Z'=X*Z]¬ú6ø÷
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=OfXI9V9bWCfXWic9WCpaXaz6NsO4w7c=&input=)
---
## Explanation
```
9õ :Range [1,9]
È Ã :Pass each integer X through a function
õ : Range [1,X]
_ Ã : Pass each integer Z through a function
[X'×Z'=X*Z] : Array [X,"×",Z,"=",X*Z]
¬ : Join to a string
ú6 : Pad end with spaces to length 6
¸ : Join with spaces
· :Join with newlines
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~54~~ 52 bytes
```
1..9|%{''+(1..($l=$_)|%{"$_`×$l={0,-2}"-f($_*$l)})}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/31BPz7JGtVpdXVsDyNRQybFVidcECiipxCccng7kVhvo6BrVKummaajEa6nkaNZq1v7/DwA "PowerShell – Try It Online")
] |
[Question]
[
Write the shortest code, in number of bytes, to display, return, or evaluate to the golden ratio (that is, the positive root of the quadratic equation: \$x^2-x-1=0\$, approximately
1.618033988749895), to at least 15 significant figures. No input will be given to your program.
Sample in Stutsk programming language:
```
1 100 { 1 + 1 swp / } repeat print
```
[Answer]
## Perl, Python - 10 chars
probably other languages too
```
.5+5**.5/2
```
[Answer]
# [Julia 0.7](http://julialang.org/), 2 bytes
```
φ
```
[Try it online!](https://tio.run/##yyrNyUw0/@9QUJSZV5KmoaSqZ2iapqTz/3zbf83/AA "Julia 0.7 – Try It Online")
I'm surprised nobody has posted this yet...
[Answer]
# Mathematica 11
```
GoldenRatio
```
This is the irrational number itself, not an approximation of it.
**Examples** (first 2 examples from Mathematica documentation)
```
FullSimplify[GoldenRatio^4 - GoldenRatio]
FullSimplify[GoldenRatio^20 + 1/GoldenRatio^20]
FullSimplify[GoldenRatio^2 - GoldenRatio - 1]
```
>
> 3 + Sqrt[5]
>
>
> 15127
>
>
> 0
>
>
>
[Answer]
# [Desmos](https://www.desmos.com/calculator), 8 bytes
```
aa-a~1
a
```
[Try it on Desmos!](https://www.desmos.com/calculator/fpodwh2z33)
[Answer]
**PHP 17 chars**
This one is just trolling, but hey.
```
1.618033988749895
```
[Answer]
# k (10 chars)
As continued fraction:
```
{%x%x+1}/1
```
Or in closed form for 11:
```
%2%1+sqrt 5
```
[Answer]
# J, 7 chars
```
-:1+%:5
```
some more text for the filter (my first J solution, heh)
[Answer]
# APL, 7
```
2÷⍨1+√5
÷2÷1+√5
.5×1+√5
.5+√5÷4
```
Curses! I can't find a way to do it in less than 7 characters! Dialect is Nars2000.
[Answer]
## JavaScript (ECMAScript), 10 chars
```
5**.5/2+.5
```
This is the same as the Perl & Python submission - thanks to **Redwolf Programs** for telling me about this.
However, back in 2012, when this answer was originally written, the `**` operator did not exist in JavaScript. While almost all browsers and do now support the exponentiation operator, according to [Can I Use](https://caniuse.com/#feat=mdn-javascript_operators_exponentiation), as of July 2020, around 9% of users still does not support it, including the latest version of Internet Explorer. Thus, the old version of the answer:
**JavaScript (backwards-compatible), 17 chars**
```
Math.sqrt(5)/2+.5
```
[Answer]
# Language Agnostic, 15 chars
```
9227465/5702887
```
If all you need is enough precision for an IEEE 32 bit float, you can do it in 9 chars:
```
6765/4181
```
This will only work for languages that don't treat integer division specially.
[Answer]
# dc, 8 chars
```
Fk5v1+2/
```
The value is on top of the stack - can be printed by adding `p` to the end of the program.
`F` pushes 15 on the stack ([trick found here](https://codegolf.stackexchange.com/a/17050/2800)), `k` sets the precision to 15 digits. The rest is normal postfix notation :-) `v` is a square root. Trailing `p` for print was omitted.
[Answer]
**J, 10 9 8 chars**
```
p.1,1,_1
```
(root of polynomial: -x^2+x+1)
```
>:@%^:_+1
```
(continued fraction (9 chars))
```
%:@>:^:_+1
```
(continued root: (10 chars))
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
```
5X‚t;O
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fNOJRw6wSa////wE "05AB1E – Try It Online")
# Explanation
```
5 Push 5
X Push 1
‚ Pair: [5, 1]
t Square root: [2.23606797749979, 1.0]
; Halve: [1.118033988749895, 0.5]
O Sum: 1.618033988749895
```
[Answer]
# [Arn](https://github.com/ZippyMagician/Arn), 3 bytes
```
phi
```
Just a builtin, too short to be compressed. Returns `1.61803398874989484820458683436563811`.
A more interesting one. If running in the downloadable version, this will print `n` digits, given the command:
```
arn run file.arn -p n
```
or 25 digits if the `-p` flag is not provided.
If running in the online version, this will print the first 50 digits.
## [6 bytes](https://github.com/ZippyMagician/Arn/wiki/Carn)
```
l[├Qn0
```
[Try it!](https://zippymagician.github.io/Arn?code=Oi0xKzovNQ==&input=)
### Explanation
Unpacked: `:-1+:/5`
```
:- Halve
1 Literal one
+ Plus
:/ Square root of
5 Literal five
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 4 bytes
**(floating-point; accurate to 15 significant figures)**
```
½→√5
```
[Try it online!](https://tio.run/##yygtzv7//9DeR22THnXMMv3/HwA "Husk – Try It Online")
This seems (to me) to be surprisingly readable for a golfing language...
```
√5 # square root of 5
→ # increment
½ # halve
```
---
# [Husk](https://github.com/barbuz/Husk), 9 bytes
**(calculation as arbitrary precision rational number)**
```
!Ẋ/İf!5İ⁰
```
[Try it online!](https://tio.run/##yygtzv6fqaVoaGBgcGTDo8YNj5oa/ys@3NWlf2RDmqIpWOj/fwA "Husk – Try It Online") (TIO header converts the rational number [expressed in [Husk](https://github.com/barbuz/Husk) as a fraction] to its first 1000 decimal digits)
```
/ # get the ratio of
Ẋ # every pair of elements of
İf # the fibonacci sequence;
! # now select the ratio at position
!5İ⁰ # 10^5 (change to !9İ⁰ for more accuracy with same byte-count)
```
[Answer]
# [Malbolge](https://github.com/TryItOnline/malbolge), 102 bytes
```
(C%;_#!7[}{3Wyw/St,+0/(-&Jlk"FEg|{A?~,`<^:r[Y64m3kT0Rg,xwc;J`&%#5"!~Bji.-,X;POsMppn"2GFEiCg+e?>b<;_#
[Answer]
# [brainf](https://github.com/TryItOnline/brainfuck), 93 bytes
```
+++++++[>+++++++<-]>.---.++++++++.-----.+++++++.--------.+++..++++++.-..-.---.+++++.-.+.----.
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fGwKi7aAMG91YOz1dXV09KF8bxEFwITyogJ4eTFAPiOCqgGyIOr3//wE "brainfuck – Try It Online")
It works :/
Not very optimised though. I can’t think of any way to optimize this, although I’m sure a way exists.
Explanation:
```
+++++++ Add seven to cell at 0.
[ Begin a loop.
>+++++++ Add seven to cell at 1.
< Go back to cell 0.
- Decrement the counter there (soon it will reach 0).
] End loop when cell 0 reaches 0 after 7 repetitions.
> Go to cell 1 which is now 49.
. Print it (1).
---. Decrement 3 to get 46 (period) then print it.
Afterwards, not much explanation is needed. Just add some
or subtract some and repeat until everything is printed.
++++++++.-----.+++++++.--------.+++..++++++.-..-.---.+++++.-.+.----.
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 8 bytes
```
(1+1%)/1
```
[Try it online!](https://ngn.codeberg.page/k#eJxlzMEOgjAMgOF7n4KLicaw2qCw8TZN6cA4N3Ql8eSzy93z/+WP45HOdDghAcTm25DryV+6Lng/XIMPNwCExWytI6KUSeeSoqvG8tCPLJxndVKe+Nq02r3kiv3gCYWTbIlN291Pmts37xXgb/8DC40lmw==)
Adapted from the [built-in docs](https://codeberg.org/ngn/k/src/commit/875e1d94e181ea59f63cedc366095bc40fb507a7/repl.k#L180).
* `(...)/1` set up a converge-reduce, seeded with 1 and run until two successive iterations return the same result
+ `(1+1%)` add one to the inverse of the current value, and feed that into the next iteration
[Answer]
# Ruby - 14 chars
```
(5**0.5)/2+0.5
```
Based on the Javascript Perl answer above.
[Answer]
# Almost language agnostic, 9 chars
### (tested in R):
```
.5+5^.5/2
```
In R, evaluates full double precision. More digits can be seen by setting `options(digits=99)`. The question says "evaluate", so that goes with the rules.
[Answer]
# x86 machine code, 13 bytes
Hexdump:
```
b1 7f d9 e8 d9 e8 de c1 d9 fa e2 f8 c3
```
Disassembly:
```
100139D0 B1 7F mov cl,7Fh
100139D2 D9 E8 fld1
again:
100139D4 D9 E8 fld1
100139D6 DE C1 faddp st(1),st
100139D8 D9 FA fsqrt
100139DA E2 F8 loop again (100139D4h)
100139DC C3 ret
```
Uses the converging sequence `an = sqrt(an-1 + 1)`.
The number of iterations is determined by the contents of `ecx`, which is mostly garbage. The minimal number of iterations is 127, which guarantees good precision (actually, 30 iterations should be enough). In the worst case, the calculation will take a few minutes (232-1 iterations), and in the best case, it's instantaneous (127 iterations).
[Answer]
## Python 3, 11 bytes
```
(1+5**.5)/2
```
= 1.618033988749895
[Answer]
# Whispers v3, 16 bytes
```
> φ
>> Output 1
```
[Try it online!](https://tio.run/##K8/ILC5ILSo2@v/fTuF8G5ednYJ/aUlBaYmC4f//AA)
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~29~~, 25 bytes
Saved **4 bytes**!
After posting this answer I noticed the example Stutsk program and realized that I could probably save a few bytes. My new answer is based off the example given in the question. This program works because the golden ration can be expressed as a [continued fraction](https://en.wikipedia.org/wiki/Golden_ratio#Alternative_forms).
`golden_ratio = 1+1/(1+1/(1+1/...))`
```
ff*101.;n~<
$1$,1+$:?!^1-
```
[Try it online!](https://tio.run/##S8sszvj/Py1Ny9DAUM86r86GS8VQRcdQW8XKXjHOUPf/fwA "><> – Try It Online")
## Old Answer
```
f201.;n,2+1~<
$:5$,+2,$:?!^1-
```
The second line approximates the sqrt of 5. After looping 15 times, this value is used to calculate the golden ratio.
[Try it online!](https://tio.run/##S8sszvj/P83IwFDPOk/HSNuwzoZLxcpURUfbSEfFyl4xzlD3/38A "><> – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 3 bytes
```
.n3
```
[Try it online!](https://tio.run/##K6gsyfj/Xy/P@P9/AA "Pyth – Try It Online")
11 bytes without builtin:
```
+c@5 2 2 .5
```
[Try it online!](https://tio.run/##K6gsyfj/XzvZwVTBCAj1TP//BwA "Pyth – Try It Online")
[Answer]
# dc - 11 chars
```
15k5v2/.5+p
```
The most character-consuming task is setting the decimal precision..
[Answer]
# Mathematica - 31
```
N[x/.Solve[x^2-x-1==0][[2]],16]
1.618033988749895
```
(It's going to be the longest code, I expect...:)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 2 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
MQ
```
[Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=TVE)
Or 6 bytes without the built-in:
```
½+5¬/2
```
[Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=vSs1rC8y)
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 1 [byte](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
φ
```
Builtins ftw ¯\\_(ツ)\_/¯
[Try it online.](https://tio.run/##y00syUjPz0n7//982///AA)
**Without builtins it's 6 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py):**
```
51α√½Σ
```
[Try it online.](https://tio.run/##y00syUjPz0n7/9/U8NzGRx2zDu09t/j/fwA)
**Explanation:**
```
φ # Push golden ratio builtin 1.618033988749895
# (output the entire stack joined together implicitly as result)
5 # Push 5
1 # Push 1
α # Wrap the last two values into a list: [5,1]
√ # Take the square-root of each value: [2.23606797749979,1.0]
½ # Halve each: [1.118033988749895,0.5]
Σ # And sum this list: 1.618033988749895
# (after which the entire stack joined together is output implicitly as result)
```
[Answer]
# [CJam](https://esolangs.org/wiki/CJam), 7 bytes
```
X5mq+2/
```
[Try it online](https://tio.run/##S85KzP3/P8I0t1DbSP//fwA)
Just one more byte than 05AB1E! Pretty simple stack-based translation of the equation on the [Wikipedia page](https://en.wikipedia.org/wiki/Golden_ratio):
```
X5 Push 1 and 5 on to the stack
mq Square root the top number
+ Add the top two numbers on the stack
2/ Divide by two
(implicit) output the stack
```
] |
[Question]
[
We will think of a partition as a sequence of non-increasing integers.
For a given partition into \$n\_1, n\_2, \dots, n\_k\$ with \$n\_1 \geq n\_2 \dots n\_{k-1} \geq n\_k = n\$ we write it out with \$n\_i\$ dots on row \$i\$. So for \$6, 1, 1\$ we would write six dots on the first row, one on the second and one on the third
# Task
Given a partition, you should output its [conjugate](https://en.wikipedia.org/wiki/Partition_(number_theory)#Conjugate_and_self-conjugate_partitions). That is you should output how many dots there are in each column of the dot diagram. For the input \$6, 1, 1\$ the output should be \$3, 1, 1, 1, 1, 1\$.
# Examples
```
5, 2, 1 gives output 3, 2, 1, 1, 1
4, 3, 1 gives output 3, 2, 2, 1
4, 2, 2 gives output 3, 3, 1, 1
3, 3, 2 gives output 3, 3, 2
4 gives output 1, 1, 1, 1
```
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 3 [bytes](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
```
⊒⌾/
```
Try it [here.](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oqS4oy+LwoK4oCiU2hvdyBGIDXigL8y4oC/MQrigKJTaG93IEYgNOKAvzPigL8xCuKAolNob3cgRiA04oC/MuKAvzIK4oCiU2hvdyBGIDPigL8z4oC/MgpA)
Explanation via example:
```
/ 4‿3‿1 # use each element as a count to replicate its index
⟨ 0 0 0 0 1 1 1 2 ⟩
⊒/ 4‿3‿1 # take a running occurrence count
⟨ 0 1 2 3 0 1 2 0 ⟩
/⁼⊒/ 4‿3‿1 # the inverse of /, applied via ⌾, counts occurrences
⟨ 3 2 2 1 ⟩
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
L˜{Åγ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m73MwDQxyTB1wYKlpSVpuhYrfE7PqT7cem7zkuKk5GKo4ILl0WY6hjqGsRAuAA)
```
L # range, so [6,1,1] is [[1,2,3,4,5,6],[1],[1]]
˜ # flatten, [1,2,3,4,5,6,1,1]
{ # sort, [1,1,1,2,3,4,5,6]
Åγ # run length encode, [3, 1, 1, 1, 1, 1]
```
If we can have extraneous zeros in the output, then by porting [@frasiyav's great BQN answer](https://codegolf.stackexchange.com/a/266339/92727) we have:
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
L˜ā¢
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m73MwDQxyTB1wYKlpSVpuhbLfU7POdJ4aNGS4qTkYqjYguXRZjqGOoaxEC4A)
```
L˜ # same as previously
ā # length range, [1, 2, 3, ..., len(arr)] (without popping)
¢ # count each
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/) / MATLAB, 17 bytes
```
@(x)sum(1:x<=x,1)
```
Anonymous function that inputs a column vector and outputs a row vector.
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0KzuDRXw9Cqwsa2QsdQ83@aRrSptYKRtYJhrCYXkGNirWCMzAHKGEE4xmAZIOc/AA "Octave – Try It Online")
### Explanation
```
@(x) % Define anynomous function of x: column vector
1:x % Range from 1 to (first entry of) x. Gives a row vector
<=x % Less than/equal to x? Element-wise with broadcast. Gives a matrix
sum( ,1) % Sum of each column
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
b1S
```
[Try it online!](https://tio.run/##y0rNyan8/z/JMPj/4XZN9///o011FIx0FAxjdRSiTXQUjBFMoKgRiGkMFjWKBQA "Jelly – Try It Online")
For some reason, I almost feel like I've seen this even shorter as part of a different solution...
```
b1 Convert each element of the input to base 1.
S Sum across columns.
```
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands/2649a799300cbf3770e2db37ce177d4a19035a25), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Å1ζO
```
[Try it online](https://tio.run/##MzBNTDJM/f//cKvhuW3@//9Hm@kY6hjGAgA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfeX/w62G57b5/9f5Hx1tpmOoYxirE22qYwSmTXSMobSRjhGQNgbyjWJjAQ).
Doesn't work in the new version of 05AB1E, unless we add `0` or `¾` before the `ζ`.
**Explanation:**
```
Å1 # Convert each value in the (implicit) input-list into a list of that many 1s
ζ # Zip/transpose; swapping rows/columns,
# implicitly using a space " " as filler for unequal length rows
O # Sum each inner list, which ignores the spaces in the legacy version of 05AB1E
# (after which the resulting list is output implicitly)
```
[Answer]
# [R](https://www.r-project.org), 26 bytes
```
\(x)Map(\(z)sum(x>=z),1:x)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuha7YjQqNH0TCzRiNKo0i0tzNSrsbKs0dQytKjQhClanaSRrmOkY6hhqQkUWLIDQAA)
A function taking a vector of integers and returning a list of integers.
[Answer]
# [R](https://www.r-project.org), ~~28~~ 22 bytes
*Edit: -6 bytes thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe).*
```
\(x)table(sequence(x))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhbbYjQqNEsSk3JSNYpTC0tT85JTgQKaEMlbjFrFqSV-ibmpxRppGskaZjqGOoaamjoKfqE-PppcKHKmOgpGOgoIWWWF9Myy1GKF_NKSgtISBWOINASh6jTRAckS0GmETRtIHI82Y2y2QcQJaDNC1WOoY4jT5yYwQUiQLVgAoQE)
~~Port of~~ Based on [@Command Master's 05AB1E answer](https://codegolf.stackexchange.com/a/266333/55372).
[Answer]
# [Python](https://www.python.org), ~~52~~ 50 bytes
-2 thanks to @mousetail
```
lambda a:[sum(i<x for x in a)for i in range(a[0])]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3jXISc5NSEhUSraKLS3M1Mm0qFNLyixQqFDLzFBI1QcxMELMoMS89VSMx2iBWMxaq0wckmQiSjI421VEw0lEwjNVRiDbRUTBGMIGiRiCmMVjUKDbWiouzoCgzr0QjUUdBXddOXUchTSNRUxNi5oKVcD0QAQA)
[Answer]
# [J](https://www.jsoftware.com), 7 bytes
```
I.i.@{.
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FNVUtFK8NYM0UrS3V1LiU99TQFWysFdQUdBQMFKyDW1VNwDvJxW1pakqZrsdxTL1PPoVoPwruZqMmVmpyRr2CsYKRgCIa6VgppCqYgLkLGCCZuAuTCxY0R6k1AihDiRhBRMBNi0YIFEBoA)
* `I.` What is the "insert before" index when inserting into the input...
* `i.@{.` Of each of the numbers 0 through n-1, where n is the first input element.
## [J](https://www.jsoftware.com), straightforward alternate, 9 bytes
```
[:+/#"0&1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FNVUtFK8NYM0UrS3V1LiU99TQFWysFdQUdBQMFKyDW1VNwDvJxW1pakqZrsTLaSltfWclAzRDCv5moyZWanJGvYKxgpGAIhrpWCmkKpiAuQsYIJm4C5MLFjRHqTUCKEOJGEFEwE2LRggUQGgA)
[Answer]
# [Python](https://www.python.org), 45 bytes
```
def f(a,j=0):
for c in-1,*a:a[:c]=c*[j];j+=1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PYxBCsIwFAX3PcXfmcQETFpBIjlJyOITG2yRNJQoeBY33eidehvTVtwNj5n3-qRnvg5xmt73HMRpFpc2QCDIe3OguoIwjOChi0Jyhhqt9s54Znt37vdG_qJmsbBYMKQ2kjVEMNA-8EaQVpDGLmYiGfJyTWGx6dZO884eOSgO0lW24VD_qWyqUL1uym3-Fw)
Takes a list and modifies it in place.
# [Python](https://www.python.org), 34 bytes
```
lambda a:sum(a[:,1>0]>range(a[0]))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PYxBCsIwFET3OcXHjQlEaauCFNoDeIWaxRcbLTQ_IU2FnsVNQfROvY3Rirt5b4a5v9wQrpbGhy6Ozz7o1X5atGhOZwTMu95wrHKZlokqPdKljpgoIX7LQ2Oc9QGoN24A7IAc09YDQkNgXU08ETmLWMRmjd7jwOsbthyFYOB8Q4Gj1B-cH8dpWe0kZBJSxaqthM0_RZfFtPm6TM37Nw)
### -4 thanks to @att.
Expects a NumPy array.
Ports @Command Master's pure Python.
[Answer]
# [R](https://www.r-project.org), 30 bytes
```
\(l)rowSums(outer(1:l,l,"<="))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhb7YjRyNIvyy4NLc4s18ktLUos0DK1ydHJ0lGxslTQ1IYpu7krTSNYw0zHUMdTU5AKxTXUUjHQUgDxlhfTMstRiBaDWgtISBWOIOASBVZrogARxqTRCUgbiYlNmjGQahItLmRFYjaGOIdylJlAfLFgAoQE)
Slightly longer compared to [pajonk's](https://codegolf.stackexchange.com/a/266336/67312), based on [this other answer of mine](https://codegolf.stackexchange.com/a/142047/67312).
[Answer]
# [sclin](https://github.com/molarmanful/sclin), 18 bytes
```
1X>b tpose \+/ map
```
[Try it on scline!](https://scline.fly.dev/#H4sIAJ7cP2UCA4s2VTBSMIxVsAYAg8mRlAkAAAA#H4sIAJ7cP2UCAzOMsEtSKCnIL05ViNHWV8hNLAAAO25ryBIAAAA#)
1 repeated by n, transpose, sum each.
[Answer]
# [Uiua](https://uiua.org), 8 [bytes](https://codegolf.stackexchange.com/a/265917/97916)
```
⍘⊚⊐/⊂⊐∵⇡
```
[Try it!](https://uiua.org/pad?src=ZiDihpAg4o2Y4oqa4oqQL-KKguKKkOKIteKHoQoKZiBbNSAyIDFdCmYgWzQgMyAxXQpmIFs0IDIgMl0KZiBbMyAzIDJdCg==)
```
⍘⊚⊐/⊂⊐∵⇡ # [5 2 1]
⊐∵⇡ # [⟦0 1 2 3 4⟧ ⟦0 1⟧ ⟦0⟧] range of each
⊐/⊂ # [0 1 2 3 4 0 1 0] join
⍘⊚ # [3 2 1 1 1] occurrences
```
[Answer]
# [Haskell](https://www.haskell.org), 35 bytes
```
f a=[sum[1|j<-a,i<=j]|i<-[1..a!!0]]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GCpaUlaboWN5XTFBJto4tLc6MNa7JsdBN1Mm1ss2JrMm10ow319BIVFQ1iYyFKbzGylqQWlyhk5hWUliikVhSkJpekpijYKqTkc3HmpJYo5JeWgGRsFdIgarg4gURwSZFPnoKKQnFGfrmCBkyJLVy_poK2toJSTIkSiAYrgqoBCYMUIiRgWri4chMz86AWg50UbaqjYKSjYBirEG0MYUFQLEzeREfBGFneCE0SJASRNEbTCRFCSBpBQwMWgAA)
-1 byte thanks to [matteo\_c](https://codegolf.stackexchange.com/users/73593/matteo-c)
Basically a port of Command Master's [python answer](https://codegolf.stackexchange.com/a/266335/46901)
[Answer]
# JavaScript (ES6), 44 bytes
```
a=>a.map(g=v=>v&&g(--v,b[v]=-~b[v]),b=[])&&b
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i5RLzexQCPdtszWrkxNLV1DV7dMJym6LNZWtw5Eaeok2UbHaqqpJf1Pzs8rzs9J1cvJT9dI04g21VEw0lEwjNXUVNDXVzCG8CCIC02piQ5IHlWpEXZ1IBmEOmPs5kFkUNUZ/QcA "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // a[] = input array
a.map(g = v => // for each value v in a[], using a recursive
// callback function g:
v && // stop if v = 0
g( // otherwise do a recursive call:
--v, // decrement v
b[v] = -~b[v] // increment b[v] (set it to 1 if undefined)
), // end of recursive call
b = [] // start with b = []
) && b // end of map(); return b[]
```
[Answer]
# [Rust](https://www.rust-lang.org), 58 bytes
```
|a|(0..a[0]).map(move|i|a.iter().filter(|x|i<**x).count())
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZVDdSsMwFMbL7imiFyUZXZitgnRbH8ObUkqoJxDon006imZP4k0v9KHm03jSKCqDQA7f-f44b-_DqM18vpEtaYRqKSOvqxoMkals6SNU-zGJM7bJysPHaOTm4ZxaYemWc5FvC8Yb0dOmO4JVVnBlYKCMS1W7wU5W7dfrifGqG1tDGfMOn1fBbrVkGNCGHIhVbT-alIQ5ZhURgamHysDTgmj1AoXFUoFTDKBT4lqVGQolXZTcdOURKgzApLpGLWW7VSC0hsGU8HxNUfZri7sTFnDhNMzvIxJH5BZjwzzxs38F8r45dxFJ_nPiC4IDfwjJhYMH_xJitz35i8yz_78A)
Basically a port of Command Master's [python answer](https://codegolf.stackexchange.com/a/266335/46901)
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0 [`-Q`](https://codegolf.meta.stackexchange.com/a/14339/), 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
*-2 bytes from @AZTECCO*
```
mo yl
```
## [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LVE&code=bW8geWw&input=WzUsMiwxXQ)
---
# [Japt](https://github.com/ETHproductions/japt) v2.0a0 [`-Q`](https://codegolf.meta.stackexchange.com/a/14339/), 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
There must be a shorter way
```
co ü ml
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LVE&code=Y28g/CBtbA&input=WzUsMiwxXQ)
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 37 bytes
```
a->Vecrev(vecsum([x^i-1|i<-a])/(x-1))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN1UTde3CUpOLUss0ylKTi0tzNaIr4jJ1DWsybXQTYzX1NSp0DTU1oYrdEgsKcio1EhV07RQKijLzSoBMJRBHSSFNI1FTU0chOtpUx0jHMBbIMtExhjGMdIxADGOgiFFsLNS0BQsgNAA)
---
# [PARI/GP](https://pari.math.u-bordeaux.fr), 37 bytes
```
a->[vecsum([t>=n|t<-a])|n<-[1..a[1]]]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN1UTde2iy1KTi0tzNaJL7GzzakpsdBNjNWvybHSjDfX0EqMNY2NjoYrdEgsKcio1EhV07RQKijLzSoBMJRBHSSFNI1FTU0chOtpUx0jHMBbIMtExhjGMdIxADGOgiFFsrCbEtAULIDQA)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 26 bytes
```
Plus@@PadRight[1^Range@#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277PyCntNjBISAxJSgzPaMk2jAuKDEvPdVBOVbtf0BRZl6Jgr5Dur5DdbWZjqGOYa1OtamOEZg20TGG0kY6RkDaGMg3qq39/x8A "Wolfram Language (Mathematica) – Try It Online")
-12 bytes from @att
[Answer]
# Google Sheets, ~~92~~ 86 bytes
`=join(",",byrow(map(split(A1,","),lambda(n,sequence(n,1,,))),lambda(r,len(join(,r)))))`
Put the input in as a text string in cell `A1` and the formula in `B1`.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 3 bytes
```
ẋ∩@
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLhuoviiKlAIiwiIiwiWzQsIDIsIDJdIl0=)
```
ẋ Repeat (each value in list times value)
∩ Transpose list
@ Length of each item in list
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 10 bytes
```
IE⌈θΣX⁰÷ιθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzexAIgrMnNLczUKNXUUgoF0QH55apGGgY6CZ16JS2ZZZkqqRqaOQqEmGFj//x8dbaqjYKSjYBgb@1@3LAcA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ Input list
⌈ Maximum
E Map over implicit range
⁰ Literal integer `0`
X Vectorised raise to power
ι Current value
÷ Vectorised integer divided by
θ Input list
Σ Take the sum
I Cast to string
Implicitly print
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 44 bytes
```
\d+
$*_
\G_(?<=(?=(\2_*,?)+)(_+))
$#1,
\D+$
```
[Try it online!](https://tio.run/##K0otycxL/K@qkaDA9T8mRZtLRSueK8Y9XsPexlbD3lYjxiheS8deU1tTI15bU5NLRdlQhyvGRVuF678Ol47Cf1MdBSMdBUMuEx0FYygN5BtxGYP5RgA "Retina 0.8.2 – Try It Online") Takes I/O as comma-separated integers but test cases removes and reinserts spaces for convenience. Explanation:
```
\d+
$*_
```
Convert to unary.
```
\G_(?<=(?=(\2_*,?)+)(_+))
$#1,
```
For `1` up to the first array entry, count how many entries are less than or equal the value.
```
\D+$
```
Remove the trailing junk.
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 6 bytes [SBCS](https://github.com/abrudz/SBCS)
```
+⌿≤⌸∘⍸
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=037Us/9R55JHPTsedcx41LsDAA&f=S1MwVTBSMORKUzBRMIbSRgpGQNoYCI0A&i=AwA&r=tryapl&l=apl-dyalog&m=train&n=f)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 37 bytes
```
->l{l[0].times.map{|x|l-=[x];l.size}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6nOifaIFavJDM3tVgvN7GguqaiJkfXNroi1jpHrzizKrW29n@BQlp0tKmOkY5hbCwXmGOiY4zMMdIxio39DwA "Ruby – Try It Online")
[Answer]
# [Desmos](https://desmos.com/calculator), 36 bytes
```
f(l)=[l[l>=i].lengthfori=[1...l[1]]]
```
[Try It On Desmos!](https://www.desmos.com/calculator/pqkwzsfya1?nographpaper)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/jxxuj0y1bk?nographpaper)
This works because we can assume that the input is always in descending order as per [OP's comment](https://codegolf.stackexchange.com/questions/266332/compute-the-conjugate-of-a-partition#comment580757_266332).
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 9 bytes
```
.#'=,/!:'
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs9JTVrfV0Ve0UufiSlMwUzBUMATSpgpGYNpEwRhKGykYAWljIDTiAgAEJwlP)
[Answer]
# [Scala 3](https://www.scala-lang.org/), 41 bytes
Saved some bytes thanks to the comment of @Kjetil S
---
```
a=>(1to a(0)).map{i=>a.count(_>=i)}.toSeq
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VU7BSsNAEL3nKx6hhx1Igm0UJLgBj4KeiqcQZE2TspLu1s1WkZAv8VIPevGL-h9-gNtde_Aw8-bNvHkz719DI3qRf1dxqvSrMCquDz_68altLO6EVBgjYNV22DjChFkPBa6NEW_V0hqp1jUVuFfSgnsl8CJ69HKwg-vcOmQ-XSRYJJhTEnrnCfL_1E0XJ5r76YIo8o6dNmBHS1ylwZr-bgFb94PtFRvimVekJWZj59U0xeRVU3SMKLzWFWDL9rm6Ubbm5aki8M-d7dLLAwlesrnVEOyMKNuI7Sh5KbJG75RlDyWXNGVWu8Ww8DEF3O8D_gI)
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~59~~ 53 bytes
```
i;f(*a,z){for(i=0;z;i+=i<a[--z]&&printf("%d ",++z));}
```
[Try it online!](https://tio.run/##bZLBioMwEIbveYpB2BLXEUyMXlL7IqWH0K4lsGtLantQfHZXE7VagjnI9yX5h5mc4/Ovqq59r2VJvxU2YVveDNVFIhupo0Lv1TGOm9Nudze6qksafF0gwChqwlB2/YDgomqVHE9FmyND1kkyQzbCDPkG8hEKhBRhjdMJ82HBiouRp3a75YtIjDNs/tbBkxtvY26tK7AWnOYfZTgHLnE8uClmObmUY92f0hUNW1JSWxmmoST3Z/2gQTD8Ocq8lHtp6qViS996zjWY@4INZr5kg8IX7cfC2HDS9fnQEgYA@6I4AOTv/pPMdROu@vXzgNuzHi6BzRDINHffFj55@wA@/TQLMnfe4zn5Bw "C (clang) – Try It Online")
* -1 thanks to @ceilingcat
`i<=*a;` -> `*a/i`
* Golfed another 5 Bytes by @att.
`for(i=1;i<=*a;)` loops until we print a[0] times
`i>a[z-1]?` check i against last value in input
`z--` move to previous position in input if greater
`:printf("%d ",z` else print position in input
`,i++)` and increment printed count
I think there can be a way to iterate i backwards.. e.g. `for(i=*a;i..` but my brains are cooking.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 9 bytes
```
#*<|ZJ1Xg
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCIjKjx8WkoxWGciLCIiLCIiLCItcCA1IDIgMSJd)
] |
[Question]
[
I just had a genius idea for making the work-life easier - a countdown to a specific date which only counts workdays.
---
The basic task is to create a countdown to a specific date which only includes the workdays in the countdown.
As workday counts *Monday*, *Tuesday*, *Wednesday*, *Thursday* and *Friday*.
**The Input** should be a specific date in the "unofficial" European standard format `dd.MM.yyyy` and must be today or a day in the future.
**The Output** should only be the number of days left.
As it's [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") the shortest code wins.
---
**Test case:**
```
Today | Input | Output
10.12.2018 | 17.12.2018 | 5
02.10.2018 | 16.10.2018 | 10
```
---
*If I missed a few things in the question, please forgive me - it's my first question :)*
**EDIT:**
* You can use `false` as output instead of `0` *<- but it's not beautiful*
* No need for respecting DST
[Answer]
## [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~130~~ ~~128~~ ~~133~~ ~~131~~ ~~124~~ ~~123~~ ~~122~~ ~~121~~ 120 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
žežfžg)V0[Y`UD3‹©12*+>₂*T÷®Xα©т%D4÷®т÷©4÷®·()ćsO7%2@+Y`т‰0Kθ4ÖUD<i\28X+ë<7%É31α}‹iY¬>0ëY1¾ǝDÅsD12‹i>1ë\1Dǝ¤>2}}ǝVYI'.¡Q#
```
I'm out of my mind..
For the golfing language 05AB1E it doesn't matter at all whether the input is with `.` or `-`. However, 05AB1E doesn't have any builtins for Date objects or calculations. The only builtin regarding dates it has is today's year/month/day/hours/minutes/seconds/microseconds.
So because of that, almost all of the code you see are manual calculations to go to the next day, and calculating the day of the week.
+5 bytes due to a part I forgot in Zeller's formula (year-1 for months January and February)..
-1 byte thanks to @Grimmy, by changing \$\left\lfloor{\frac{13(m+1)}{5}}\right\rfloor\$ to \$\left\lfloor{\frac{26(m+1)}{10}}\right\rfloor\$ in the code, since 05AB1E has single-byte builtins for both `26` and `10` (being `₂` and `T` respectively), as opposed to the 3 bytes of `13` and `5`.
[Try it online](https://tio.run/##yy9OTMpM/f//6L7Uo/vSju5L1wwziI5MCHUxftSw89BKQyMtbbtHTU1aIYe3H1oXcW7joZUXm1RdTEC8i01AciWYeWi7huaR9mJ/c1UjB@3IhItNjxo2GHif22FyeFqoi01mjJFFhPbh1Tbmqoc7jQ3PbawFmp0ZeWiNncHh1ZGGh/Ydn@tyuLXYxdAIJG5neHh1jKHL8bmHltgZ1dYenxsW6amud2hhoPL//4ameoYGekYGRkYA) or [Try it online with an emulated self-specified date of 'today'](https://tio.run/##yy9OTMpM/a8UUFqikKiQkliSqpCZp1CSkaqQll@Um1iikJKi6@urWwkECiX5CqXFqQqJxQqJOSWpRXmJJZllqQrFJYlFJZl56RDNGqm5pTlARgqEm5@moF6Sn5JYqa5ppRTDxaVkYKRraKBrZGBooaSue2jh/zCD6MiEUBfjRw07D600NNLStnvU1KQVcnj7oXUR5zYeWnmxSdXFBMS72AQkV4KZh7ZraB5pL/Y3VzVy0I5MuNj0qGGDgfe5HSaHp4W62GTGGFlEaB9ebWOuerjT2PDcxlqg2ZmRh9bYGRxeHWl4aN/xuS6HW4tdDI1A4naGh1fHGLocn3toiZ1Rbe3xuWGRnup6hxYGKv//b2imZ2igB3IrAA).
### Explanation:
*Wall of text incoming.*
In general, the code follows the following pseudo-code:
```
1 Date currentDate = today;
2 Integer counter = 0;
3 Start an infinite loop:
4* If(currentDate is NOT a Saturday and currentDate is NOT a Sunday):
5 Counter += 1;
6* currentDate += 1; // Set currentDate to the next day in line
7 If(currentDate == parsed input-string):
8 Stop the infinite loop, and output the counter
```
1) `Date currentDate = today;` is this part of the 05AB1E program:
```
že # Push today's day
žf # Push today's month
žg # Push today's year
) # Wrap them into a single list
V # Pop and store this list in variable `Y`
```
2) `Integer counter = 0;` and 3) `Start an infinite loop:` are straight-forward in the 05AB1E program:
```
0 # Push 0 to the stack
[ # Start an infinite loop
```
4) `If(currentDate is NOT a Saturday and currentDate is NOT a Sunday):` is the first hard part with manual calculations. Since 05AB1E has no Date builtins, we'll have to calculate the *Day of the Week* manually.
The general formula to do this is:
$${\displaystyle h=\left(q+\left\lfloor{\frac{13(m+1)}{5}}\right\rfloor+K+\left\lfloor{\frac{K}{4}}\right\rfloor+\left\lfloor{\frac{J}{4}}\right\rfloor-2J\right){\bmod{7}}}$$
Where for the months March through December:
* \$q\$ is the \$day\$ of the month (`[1, 31]`)
* \$m\$ is the 1-indexed \$month\$ (`[3, 12]`)
* \$K\$ is the year of the century (\$year \bmod 100\$)
* \$J\$ is the 0-indexed century (\$\left\lfloor {\frac {year}{100}}\right\rfloor\$)
And for the months January and February:
* \$q\$ is the \$day\$ of the month (`[1, 31]`)
* \$m\$ is the 1-indexed \$month + 12\$ (`[13, 14]`)
* \$K\$ is the year of the century for the previous year (\$(year - 1) \bmod 100\$)
* \$J\$ is the 0-indexed century for the previous year (\$\left\lfloor {\frac {year-1}{100}}\right\rfloor\$)
Resulting in in the day of the week \$h\$, where 0 = Saturday, 1 = Sunday, ..., 6 = Friday.
[Source: Zeller's congruence](https://en.wikipedia.org/wiki/Zeller%27s_congruence)
We can see this in this part of the 05AB1E program:
```
Y # Push variable `Y`
` # Push the day, month, and year to the stack
U # Pop and save the year in variable `X`
D # Duplicate the month
3‹ # Check if the month is below 3 (Jan. / Feb.),
# resulting in 1 or 0 for truthy/falsey respectively
© # Store this in variable `®` (without popping)
12* # Multiply it by 12 (either 0 or 12)
+ # And add it to the month
# This first part was to make Jan. / Feb. 13 and 14
> # Month + 1
₂* # Multiplied by 26
T÷ # Integer-divided by 10
® # Push month<3 from variable `®` again
Xα # Take the absolute difference with the year
© # Store this potentially modified year as new `®` (without popping)
т% # mYear modulo-100
D4÷ # mYear modulo-100, integer-divided by 4
®т÷©4÷ # mYear integer-divided by 100, and then integer-divided by 4
®·( # mYear integer-divided by 100, doubled, and then made negative
) # Wrap the entire stack into a list
ć # Extract the head (the counter variable that was also on the stack)
s # Swap so the calculated values above are as list at the top
O # Take the sum of this entire list
7% # And then take modulo-7 to complete the formula,
# resulting in 0 for Saturday, 1 for Sunday, and [2, 6] for [Monday, Friday]
2@ # Check if the day is greater than or equal to 2 (so a working day)
```
5) `Counter += 1;` is straight-forward again:
```
# The >=2 check with `2@` results in either 1 for truthy and 0 for falsey
+ # So just adding it to the counter variable is enough
```
6) `currentDate += 1; // Set currentDate to the next day in line` is again more complex, because we have to do it manually. So this will be expanded to the following pseudo-code:
```
a Integer isLeapYear = ...;
b Integer daysInCurrentMonth = currentDate.month == 2 ?
c 28 + isLeapYear
d :
e 31 - (currentDate.month - 1) % 7 % 2;
f If(currentDate.day < daysInCurrentMonth):
g nextDate.day += 1;
h Else:
i nextDate.day = 1;
j If(currentDate.month < 12):
k nextDate.month += 1;
l Else:
m nextDate.month = 1;
n nextDate.year += 1;
```
Sources:
~~[Algorithm for determining if a year is a leap year.](http://www.dispersiondesign.com/articles/time/determining_leap_years)~~ (EDIT: No longer relevant, since I use [an alternative method](https://codegolf.stackexchange.com/a/177019/52210) to check leap years which saved 7 bytes.)
[Algorithm for determining the number of days in a month.](http://www.dispersiondesign.com/articles/time/number_of_days_in_a_month)
6a) `Integer isLeapYear = ...;` is done like this in the 05AB1E program:
```
Y # Push variable `Y`
` # Push the days, month and year to the stack
т‰ # Divmod the year by 100
0K # Remove all items "00" (or 0 when the year is below 100)
θ # Pop the list, and leave the last item
4Ö # Check if this number is visible by 4
U # Pop and save the result in variable `X`
```
Also used in [this 05AB1E answer of mine](https://codegolf.stackexchange.com/a/177019/52210), so there some example years are added to illustrate the steps.
6b) `currentDate.month == 2 ?` and 6c) `28 + isLeapYear` are done like this:
```
D # Duplicate the month that is now the top of the stack
< # Decrease it by 1
i # And if this is now 1 (thus February):
\ # Remove the duplicated month from the top of the stack
28X+ # Add 28 and variable `X` (the isLeapYear) together
```
6d) `:` and 6e) `31 - (currentDate.month - 1) % 7 % 2;` are done like this:
```
ë # Else:
< # Month - 1
7% # Modulo-7
É # Is odd (shortcut for %2)
31 # Push 31
α # Absolute difference between both
} # Close the if-else
```
6f) `If(currentDate.day < daysInCurrentMonth):` is done like this:
```
‹ # Check if the day that is still on the stack is smaller than the value calculated
i # And if it is:
```
6g) `nextDate.day += 1;` is done like this:
```
Y # Push variable `Y`
¬ # Push its head, the days (without popping the list `Y`)
> # Day + 1
0 # Push index 0
# (This part is done after the if-else clauses to save bytes)
}} # Close the if-else clauses
ǝ # Insert the day + 1 at index 0 in the list `Y`
V # Pop and store the updated list in variable `Y` again
```
6h) `Else:` and 6i) `nextDate.day = 1;` are then done like this:
```
ë # Else:
Y # Push variable `Y`
1 # Push a 1
¾ # Push index 0
ǝ # Insert 1 at index 0 (days part) in the list `Y`
```
6j) `If(currentDate.month < 12):`:
```
D # Duplicate the list `Y`
Ås # Pop and push its middle (the month)
D12‹ # Check if the month is below 12
i # And if it is:
```
6k) `nextDate.month += 1;`:
```
> # Month + 1
1 # Push index 1
# (This part is done after the if-else clauses to save bytes)
}} # Close the if-else clauses
ǝ # Insert the month + 1 at index 1 in the list `Y`
V # Pop and store the updated list in variable `Y` again
```
6l) `Else:`, 6m) `nextDate.month = 1;` and 6n) `nextDate.year += 1;` are then done like this:
```
ë # Else:
\ # Delete the top item on the stack (the duplicated month)
1 # Push 1
D # Push index 1 (with a Duplicate)
ǝ # Insert 1 at index 1 (month part) in the list `Y`
¤ # Push its tail, the year (without popping the list `Y`)
> # Year + 1
2 # Index 2
# (This part is done after the if-else clauses to save bytes)
}} # Close the if-else clauses
ǝ # Insert the year + 1 at index 2 in the list `Y`
V # Pop and store the updated list in variable `Y` again
```
And finally at 7) `If(currentDate == parsed input-string):` and 8) `Stop the infinite loop, and output the counter`:
```
Y # Push variable `Y`
I # Push the input
'.¡ '# Split it on dots
Q # Check if the two lists are equal
# # And if they are equal: stop the infinite loop
# (And output the top of the stack (the counter) implicitly)
```
[Answer]
# Excel 24 Bytes
Assumes input in Cell A1
```
=NETWORKDAYS(NOW()+1,A1)
```
Uses built-in function. Unfortunately the function includes both today and the end date. OP has since clarified to not count today, so I add one to NOW so as to not count today.
To address comments on format of number, again, this is Excel standard:
[](https://i.stack.imgur.com/WScdh.png)
[Answer]
# [R](https://www.r-project.org/), 76 bytes
[Please also have a look at this 72 byte R answer that is also locale-independent.](https://codegolf.stackexchange.com/a/173303/79980)
```
sum(!grepl("S",weekdays(seq(Sys.Date(),as.Date(scan(,""),"%d.%m.%Y"),1))))+1
```
[Try it online!](https://tio.run/##K/r/v7g0V0MxvSi1IEdDKVhJpzw1NTslsbJYozi1UCO4sljPJbEkVUNTJxHKKk5OzNPQUVLS1FFSTdFTzdVTjQSyDTWBQNvwv4GFnqGBnpGBocV/AA "R – Try It Online")
`weekdays` gives text days of week, so we count the days in the sequence between today and the input that do not contain `S`, and add one to the result.
[Answer]
# Java 10, ~~233~~ ~~232~~ 226 bytes
```
import java.util.*;d->{int r=0;var s=Calendar.getInstance();s.setTime(new Date());var e=s.getInstance();for(e.setTime(new java.text.SimpleDateFormat("dd.MM.yyyy").parse(d));!s.after(e);s.add(5,1))if(s.get(7)%7>1)r++;return r;}
```
Date always reminds me how verbose Java really is..
NOTE: There are now two shorter Java answers (below 175 bytes), [one with smart use of deprecated methods from earlier Java versions](https://codegolf.stackexchange.com/a/173151/52210) by *@LukeStevens*, and [one using the `java.time.LocalDate` that's new since Java 8](https://codegolf.stackexchange.com/a/173176/52210) by *@OlivierGrégoire*.
[Try it online.](https://tio.run/##fZBNSwMxEIbv@yvGgpBYm24KWmVpL36Ah4pQb@Ih3czW1N1kSWb7QdnfXrO1FxUMITAvz8zkfVdqrQYr/XkwVe08wSrWoiFTiosMYDiEFxVVVwB9ICx2hIPcNZaA9eUtT/JShQAzZew@ATCW0BcqR3juyqMAOZuTN3YJmscZ3m0CPGxzrMk4m0WqTeITSJHJ4RksTOCgB9N91@onabZWHsLkTpVotfJiifRkI21zZDwLIiC9mgqZxQ3cK4oiP7bgJPxiC@cZ/uCPVgm3JObRfIld/6PzlSLW01rMZmIXT4@LWvmATMfRZ0GoIppk2C1XWrOrS8m5KdhxHRvz8/FUct/vZx6p8RZ81h6yzmLdLMpo8eR07YyGKuZ2SuftHdTffL5TnO8CYSVcQ6KOLJWWWZGznrwWMhWjVN704tf@RVMp4h3JND2hbdIevgA)
**Explanation:**
```
import java.util.*; // Required import for both Calendar and Date
d->{ // Method with String parameter and integer return-type
int r=0; // Result-integer, starting at 0
var s=Calendar.getInstance();// Create a Calendar instance for the start-date
s.setTime(new Date()); // Set the start date to today
var e=s.getInstance(); // Create a Calendar instance for the end-date
for(e.setTime( // Set the end date to:
new java.text.SimpleDateFormat("dd.MM.yyyy")
// Create a formatter for the "dd.MM.yyyy" format
.parse(d)); // And parse the input-String to a Date
!s.after(e) // Loop as long as we haven't reached the end date yet
; // After every iteration:
s.add(5,1)) // Increase the start-date by 1 day
if(s.get(7)%7>1) // If the day of the week is NOT a Saturday or Sunday:
// (SUNDAY = 1, MONDAY = 2, ..., SATURDAY = 7)
r++; // Increase the result-sum by 1
return r;} // Return the result-sum
```
[Answer]
# JavaScript (ES6), ~~116~~ 103 bytes
```
f=(d,n=+new Date)=>(D=new Date(n)).toJSON()<d.split`.`.reverse().join`-`&&(D.getDay()%6>0)+f(d,n+864e5)
```
[Try it online!](https://tio.run/##XY9BawIxEIXv@yvmUjNDTFhKK4JmT3vyUA/2Vgob3KxElkSSoIj0t69ZxVp6esy84b1v9vqo4zbYQxLOt2YYOoXt1CnuzAlqnQypCmv1mNARyeRXm/UH0rKV8dDb1MhGBnM0IRokuffWNaKZTLCWO5NqfUZ6mVUl8W5M5vPZm3mnYetd9L2Rvd8h@/StPoMCBhzwt4uIiqLzAW22yim4LKMhnT8hLcDCEl7LrJwTXAqAmEI@eQY44ArufU/qO3PuZPRVfj8mwejfD8gko0VO/Us6NvCMKUR1g@3GDeWzn@EK "JavaScript (Node.js) – Try It Online")
### How?
A JavaScript timestamp is defined as the number of *milliseconds* elapsed since the [UNIX epoch](https://en.wikipedia.org/wiki/Unix_time). The current timestamp is hold in the variable \$n\$.
At each iteration, we use \$n\$ to generate a date \$D\$ (as a JavaScript object). This date is converted to [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format with the `.toJSON()` method:
```
*YYYY*-*MM*-*DD*T*hh*:*mm*:*ss.sss*Z
```
Since this string starts with `YYYY-MM-DD`, it is safe to perform a lexicographical comparison with another string in a similar format. This is why we want to convert the input string \$d\$ to `YYYY-MM-DD` rather than converting our computed date to the input string format `DD.MM.YYYY` (which cannot be sorted lexicographically):
```
d.split`.`.reverse().join`-`
```
Before each recursive call, we increment the final result if `D.getDay()` is neither \$0\$ (Sunday) nor \$6\$ (Saturday), i.e. if it's not congruent to \$0\$ modulo \$6\$:
```
(D.getDay() % 6 > 0) + f(d, n + 864e5)
```
We add \$86,400,000\$ milliseconds to \$n\$ to reach the next day.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 24 bytes
```
46tQZt24&YO:Z':X-9XO83-z
```
[Try it online!](https://tio.run/##y00syfn/38SsJDCqxMhELdLfKkrdKkLXMsLfwli36v9/dUMzPUMDPSMDQwt1AA)
>
> I don't want to have any input format so that specific code golf languages got a big advantage
>
>
>
You half succeeded :-)
### Explanation
```
46 % Push 46 (ASCII for '.')
tQ % Duplicate, add 1: gives 47 (ASCII for '/')
Zt % Implicit input. Replace '.' by '/' in the input string
24&YO % Convert string with date format 24 ('dd/mm/yyyy') to serial date number.
% This is an integer representing day starting at Jan-1-0000
: % Inclusive range from 1 to that
Z' % Push current date and time as a serial number. Integer part is day;
% decimal part represents time of the day
: % Inclusive range from 1 to that
X- % Set difference. Gives serial numbers of days after today, up to input
9XO % Convert each number to date format 9, which is a letter for each day
% of the week: 'M', 'T', 'W', 'T', ' F', 'S', 'S'
83- % Subtract 83 (ASCII for 'S')
z % Number of nonzeros. Implicit display
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~64~~ 56 bytes
```
DayCount[Today,""<>#~StringTake~{{4,6},3,-4},"Weekday"]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/d8lsdI5vxTICslPSazUUVKysVOuCy4BSqaHJGan1lVXm@iY1eoY6@ia1OoohaemZgOVKcWq/VdwUFAyNtQzNNIzMjC0UIr9DwA "Wolfram Language (Mathematica) – Try It Online")
`DayCount[x,y,"Weekday"]` counts the number of weekdays between `x` and `y`.
The inputs `x` and `y` can be many things, including a fancy `DateObject` like the one returned by `Today`, or a string in the format (unfortunately) `mm.dd.yyyy`.
My previous attempt tried to turn the `dd.mm.yyyy` input into a `DateObject` by telling Mathematica how to parse it; the new solution simply rearranges the string to put day and month in the order Mathematica expects.
It's worth noting that the 28-byte solution `DayCount[Today,#,"Weekday"]&` not only works perfectly for a month-day-year input format, but also correctly handles *unambiguous* day-month-year inputs such as `31.12.2018`, which couldn't possibly mean "the 12th day of the 31st month". So it's correct more than 60% of the time :)
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 61 bytes
```
{+grep 6>*.day-of-week,Date.today^..Date.new(|[R,] m:g/\d+/)}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Wju9KLVAwcxOSy8lsVI3P023PDU1W8clsSRVryQfKBSnpwfm5KWWa9REB@nEKuRapevHpGjra9b@L06sVEjTUInXVEjLL1KwMbDQMzTQMzIwtFAwNtQzNIIwDYz1DAyBTCMDO@v/AA "Perl 6 – Try It Online")
[Answer]
# R, 72 chars
A variation on the answer provided by @ngm which avoids the grepl to save a few characters and works in non-English locales.
`sum(strftime(seq(Sys.Date(),as.Date(scan(,""),"%d.%m.%Y"),1),'%u')<6)+1`
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 174 166 165 bytes
With a bit of inspiration from Kevin's answer and a good ol' trawl through the deprecated Date API, I've managed to get a more succinct Java solution.
*-8 bytes thanks to Kevin's inventive regex date parsing*
*-1 bytes thanks to Nevay's clever bitwise operation*
```
import java.util.*;d->{long r=0,s=new Date().getTime(),e=Date.parse(d.replaceAll("(..).(..).","$2/$1/"));for(;s<=e;s+=864e5)r-=-new Date(s).getDay()%6>>-1;return r;}
```
[Try it online!](https://tio.run/##jZBRa8IwFIXf@ysuZYNk2jSRKUpWYeAeJwP3NvYQ2@ji2qQkqU6kv71LnexlMIRwuTl8ufec7MReJKaWeld8dqqqjfWwCxppvCrJHQdIU3gRQTUb8B8S1kcvk9w02gMasBmO8lI4B89C6VMEoLSXdiNyCcv@ClAavYUcrbxVoSlwGGLNwcHTVy5rr4zmAWujUJwXXuWwBA0ZdEUyP53f2owOXablARbCS4TJVvpXVYVuKLNeIrWwTqKCWFmXYfNjWaIYEYLJucTD@GaU3rA0xphvjEXcPWSSu0E2ndzLMbZJlvxOd@fxC3FE@HYynyeMW@kbq8HytuO9y7pZl8HlxezeqAKqkP0S8O0dxN@IPz@xOjovK2IaT@rA@lIjTXIU0ymhMzKibNo7/B8dE0avQ9nkapQyEs6IUXpB26jtvgE "Java (OpenJDK 8) – Try It Online")
**Explanation**
```
import java.util.*; // Required import for Date
long r=0, // Initialise result variable
s=new Date().getTime(), // Current date in millis
e=Date.parse(
d.replaceAll("(..).(..).","$2/$1/")// Use regex to convert to MM/dd/yyyy
); // Parse date arg using deprecated API
for(;s<=e; // Loop while current millis are less than date arg (e.g. date is before)
s+=864e5) // Add 86400000 ms to current date (equiv of 1 day)
r-=-new Date(s).getDay()%6>>-1; // If day is Sunday (0) or Saturday (6) don't increment, else add 1
return r; // When loop finished return result
```
[Answer]
# [Red](http://www.red-lang.org), 72 bytes
```
func[a][b: now/date s: 0 until[if b/weekday < 6[s: s + 1]a < b: b + 1]s]
```
[Try it online!](https://tio.run/##HcvBCoQgFEbh/TzFvx8iLYiQeYq2FxeaV5DCiTSkpzdp@XE4J7u6sCP98ar6K65kNFmF@C@9M5mRFASumMNOwcP2hXlz5sYPE7WW8IXUprFN9kXS9ThDzPAYZSdFNwg51wc "Red – Try It Online\"")
Takes the date in format dd-mm-yyyy, for example 31-10-2018 (also works with 10-Oct-2018)
## Strict input:
# [Red](http://www.red-lang.org), 97 bytes
```
func[a][a: do replace/all a".""-"b: now/date s: 0 until[if b/weekday < 6[s: s + 1]a < b: b + 1]s]
```
[Try it online!](https://tio.run/##HctBCsMgEEbhfU/xM9tSoy2UIj1FtuJijCNIxYSYEHp6G7r8eLxVYh8lOn9Jtqe9To69Y4s4Y5Wl8CQDlwImRXSjYFHnY4i8CZqFxl63XFxOCMMh8on8xRtPd7aGK4znk@cU/mi@L2uuGxLoYZTR6q7Ni/oP "Red – Try It Online")
## Bonus:
Returns a list of the dates/weekdays of the working days up to the given date:
# [Red](http://www.red-lang.org), 235 bytes
```
f: func [ a ] [
b: now/date
d: system/locale/days
collect [
until [
if b/weekday < 6 [
keep/only reduce [ b ":" d/(b/weekday) ]
]
a < b: b + 1
]
]
]
```
[Try it online!](https://tio.run/##XY5BCoMwEEX3OcXHVUuRaAulhJ6iW8kiJhMQ00Q0Ip4@jS5K7dv9@fOGGcmkF5lGsmQF7Ow1GihINAyZVsCHhRsVac9GYFqnSG/uglaOcrNOe6ODc6Rjtve4MfvYud/BRmfR8oWozyaeuP/3Gz3RwIN3K0Yys6a806IQBQw/feUz5EE8JpVv5@dbXFCz44pkMg1j5yMsbnVZV@W1qh/pAw "Red – Try It Online")
[Answer]
# JavaScript, ~~87~~ 85 bytes
Returns `false` for `0`.
```
s=>([d,m,y]=s.split`.`,g=_=>new Date<(x=new Date(y,~-m,d--))&&(x.getDay()%6>0)+g())()
```
[Try it online](https://tio.run/##NcYxDsIgFADQq5gmNv9HIMWhcfAz9RbGWFIoqaHQCNGyeHWcfNN76rdO02vZMg/R2DpTTaTgZtjKyp2SSJtf8ihG5uhBKtjPYdDZXmGn/6GwL1@Z4RyxbWEXzuZBF8Bjrzo8OUAErFMMKXorfHQwQyN7ITtx7uSlQaw/) or [check the next 31 days](https://tio.run/##RY69asMwFEZfxUMa7q2li/sXSokcCpk6tEPHJETCUoyDLRlJpDIhfXXXQ0K3A@fj4xzVSYXKN33k1mkzHsQYRAkbzTo27ESg0LdNlCRZLfaitOYnW6tolpDEjWFgv7xjmnPE@RwS1Sau1QB4tygLzGtABBwrZ4NrDbWuhg0RvXs/bZ4ecUed6gH2LKEo5eys/4/zG@Wvi2fzcp@Qovv4/voEpNA2lYGCPRR4beSSvDkZH8ykj66xU/UlE9nsnFYH0Pgmo9NqkBd51VsrcfwD)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~163~~ ~~156~~ ~~149~~ 147 bytes
```
lambda s:sum((date.today()+timedelta(x)).weekday()<5for x in range((date(*map(int,(s.split(".")[::-1])))-date.today()).days))
from datetime import*
```
[Try it online!](https://tio.run/##TY3LCsIwEEX3fkXIaqbaYAqCFP0SdRFposHmQTLF9utjqhtXF@7j3LjQM/iumPO1jMrdB8VynycHMCjSgsKgFsAtWacHPZKCGVG8tX59/dPBhMRmZj1Lyj/0bwWNUxGspx1kkeNoCbjgeOn7Vt4Qsf1Ho6iSETcmBcfWZP1i1sWQqCkxVQ4zlRYnqu3CpZBSdHt55B8 "Python 2 – Try It Online")
-7 with thanks to @mypetlion
-7 more with thanks to @ovs
+30 due to the very restrictive input format which I only noticed just before I posted my previous code which took input as e.g. `(2018,11,1)` :-(
[Answer]
# [Java (JDK 10)](http://jdk.java.net/), 171 bytes
```
s->{int c=0;for(var t=java.time.LocalDate.now();!t.parse(s.replaceAll("(..).(..).(.*)","$3-$2-$1")).equals(t);t=t.plusDays(1))c-=t.getDayOfWeek().getValue()/6-1;return c;}
```
[Try it online!](https://tio.run/##bVFdS8MwFH3fr7iGDZKxxrbikNUOBkMQFB8m@iA@xC4d2dK0JreTIf3tM23HXibkg3PuyT05yVbsRbBd746qqEqLsPWY16g0HyeDCy6vTYaqNG0x08I5eBbKwO8AoKq/tMrAoUC/7Uu1hsLX6AqtMpuPTxB241gnBXgtHw0@nJrd95I55JAeXTD/VQYhS8MkLy3dCwuYdjdAVUj@VGZCLwVKbsofypIr5JWwTlLHray0yORCa0oo54yfljEjEzK8CYZxMIwIY1x@10I7iizB1B/XtVuKg6MRY1ngiY1Ej1/ydyl3lLXwTehaUnY9DaLESqytgSxpjkmX5RwQpUMH6SkiAAljHoU8DqM7Mjlzt5dcNP1HF3E/4igMSUc1vVn7JL1hZzfrTdnZc3VwKAte1j6XV2FOycjNYLQeGTLpxBPIuagqfVg4/we0pRjrmzeDdjbHPw "Java (JDK 10) – Try It Online")
## Credits
* -4 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~168~~ ~~160~~ ~~139~~ 133 bytes
*35 bytes less thanks to [Quintec](https://codegolf.stackexchange.com/users/20438/quintec) and [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)*
```
D=>{var i=D.split('.'),n=0;for(var d=new Date();d<=new Date(i[2],i[1]-1,i[0]);d.setDate(d.getDate()+1))n+=-~d.getDay()%7>1;return n;}
```
[Try it online!](https://tio.run/##RcnPCoMgHAfwV@ky9Ecp2mEbODv1FtFB0sIRGuoaY2yv7toIdvr@@VzVquIQ7JKI89rkUeZWNs9VhcLKlsZltgkjiqBykonRB/wlLZ25F61KBoPQl/@yXd1XtuM94VuwflMaTfqZptPeoOQArpTkvX8PDIdTw0Uw6RZc4cQrD95FPxs6@wmPGPEj5YzWjJ8RgMgf "JavaScript (Node.js) – Try It Online")
```
D=>{
var i=D.split('.'), // Splits the date string by .
n=0; // Counter variable
for(var d=new Date(); // For the actual date
d<=new Date(i[2],i[1]-1,i[0]); // As long as the date is less or equal the requested date
d.setDate(d.getDate()+1)) // Count the date one up
n+=-~d.getDay()%7>1; // If the date is not a Sunday or Saturday
return n; // Return the counter variable
}
```
[Answer]
# [Python3](https://docs.python.org/3/) & [Numpy](http://www.numpy.org/), 96 bytes
I couldn't get smaller than the boring pre-made solution...
```
from numpy import*
d=datetime64
lambda s:busday_count(d('today'),d(f'{s[6:]}-{s[3:5]}-{s[:2]}'))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P60oP1chrzS3oFIhM7cgv6hEiyvFNiWxJLUkMzfVzIQrJzE3KSVRodgqqbQ4JbEyPjm/NK9EI0VDvSQfyFXX1EnRSFOvLo42s4qt1QXSxlamEIaVUWytuqbm//8A "Python 3 – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~107~~ 99 bytes
*-8 bytes thanks to mazzy*
```
$d,$m,$y=$args-split'\.';for($a=date;$a-lt(date "$y-$m-$d");$a=$a|% *ys 1){$o+=($a|% D*k)-in1..5}$o
```
[Try it online!](https://tio.run/##HcvRCsIgAEbhV5Hxh7pNmUERDO96jG4ErUYuhwpDqme31d3hg7OE1cV0d97XCttj7lE0TLwlkRY/ZXqRdLyGyGC0NdmNMMJn9kvSoAjMArbhG2/Xe0fakojiL4ROsz@c2wcX01NJefgg1FqpOko1yP2gTvQL "PowerShell – Try It Online")
Performs a regex `-split` on the input `$args`, stores the values into `$d`ays, `$m`onths, and `$y`ears, respectively. Then, enters a `for` loop, initializing `$a` to today's date. The loop continues while `$a` is `-l`ess`t`han our input target date. Each iteration we're adding `1` da`ys` to `$a`, and checking whether the current `D*k` (short for `DayOfWeek`) is in the range `1..5` (i.e., Monday to Friday). That Boolean result is accumulated into `$o` and once we're out of the loop that value is left on the pipeline and output is implicit.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~147~~ ~~143~~ ~~141~~ 140 bytes
```
from datetime import*
lambda e,s=date.today():sum((s+timedelta(x+1)).weekday()<5for x in range((date(*map(int,e.split(".")[::-1]))-s).days))
```
[Try it online!](https://tio.run/##nZPdjtMwEIWvm6cYBVWyd7NW3KUCKgrPgapeuMmEWiS25Zkq26cvdlqgIBak3FnjOf7O/Dic@ejd6nLpoh@gNYxsBwQ7BB/5oejNcGgNYEXbfKfYt@Ys5IZOgxD0mHNb7NmIl0ctpRoRv00JH9edj/AC1kE07isKkeXiYTBBWMcVKgq9ZVGqUu42mye9l/KJpEpikvLCSEzbXbEQPxwp50ch74A5c7tOTOLY5bAol61aDmr5pZTVf5VvZyufZytXs5V6trKez/xHi94ABWxsZxvIo4LGEAIfDcNoKA@djwgtUhNtYOtdgpX6ndIrtar1@7L6uWgZEK4AXf@6v6OpaXHklTpmxNGEgC5hOhgR4inTLIF3YCAvILr2M4gQ/cEc@jP4E4PvgBofUGYja5VQr/t4rlX94XUfxb4o8m5PdedK86purubQAbGJPD0LydOtS9gWi@S2Rydy@q7eS/gEOqkWIabvALdodT3odOjEn7HkHXvC30V3FUxD/PvAbq/Jy3c "Python 2 – Try It Online")
Takes a string, e, which represents the end date in the format "dd.MM.YYYY". Optionally also takes the start date, but this is expected to be a datetime.date.
The start date, s, is defaulted to today's date as a datetime.date object in order to disregard time. The end time is parsed into a datetime.datetime object then converted to a date, since datetime.date objects do not have a parse method and datetimes cannot be added to/subtracted from dates. Iterates through every day in (start, end] and adds 1 to the total if its weekday number is < 5. ([0-4] are [Mon-Fri], [5-6] are [Sat-Sun]).
Datetime parsing is the worst, you guys.
EDIT: Stole [ElPedro](https://codegolf.stackexchange.com/a/173117/73368)'s map(int,thing) trick to save 4 bytes.
EDIT 2: ELECTRIC BOOGALOO: Saved 2 bytes by making it an anonymous function. (Thanks Aaron!)
EDIT 3: xrange -> range. (Thanks again Aaron!)
[Answer]
# PHP (with [Carbon](https://carbon.nesbot.com/docs/)), 107 bytes
```
function a($d){return Carbon\Carbon::parse($d)->diffInDaysFiltered(function($e){return!$e->isWeekend();});}
```
[Answer]
# [K4](http://kx.com/download/), 40 bytes
**Solution:**
```
{+/1<.q.mod[d+!(."."/:|"."\:x)-d:.z.d]7}
```
**Explanation:**
Calculate the difference between the dates, use modulo 7 to ignore weekends, sum up.
```
{+/1<.q.mod[d+!(."."/:|"."\:x)-d:.z.d]7} / the solution
.q.mod[ ]7 / modulo with 7
.z.d / UTC date
d: / save as d
- / subtract from
( ) / do this together
"."\:x / split input on "."
| / reverse
"."/: / join back with "."
. / take the value
! / range 0..the difference
d+ / add today's date to range
1< / is 1 less than the modulo (ie is this mon-fri)?
+/ / sum up
```
**Notes:**
* same byte alternative to the date parsing: `"D"$,/|"."\:x`
[Answer]
# PHP, 66 bytes
```
for($t=time();$t<strtotime($argn);)$r+=date(N,$t+=86400)<6;echo$r;
```
empty output for `0`; insert `+` between `echo` and `$r` to fix.
Run as pipe with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/f75fa3bef0bf297b428c74ae7583b55fff543da6).
---
60 bytes with unary output:
```
for($t=time();$t<strtotime($argn);)echo date(N,$t+=86400)<6;
```
[Answer]
# q, 52 79 bytes
```
{x:"D"$"."sv reverse"."vs x;i:0;while[x-.z.d;$[2>x mod 7;x-:1;[i+:1;x-:1]]];:i}
```
in q, each date has an underlying integer value, based on how many days have passed since the start of the millenium. Applying 'mod 7' to this, you get unique values for each day of the week (0 for Saturday, 6 for Friday). So when 2 > x mod 7, don't increment the counter, to avoid counting weekends.
EDIT: Missed strict date format, editing
EDIT2: Included
[Answer]
# IBM/Lotus Notes Formula - 99 bytes
```
d:=i;c:=0;@While(d>@Today;@Set("c";c+@If(@Weekday(d)=1:7;0;1));@Set("d";@Adjust(d;0;0;-1;0;0;0)));c
```
Takes input from a date/time field `i`. The input format of `i` is set to `.` separated so there is no need to convert the input. Notes can take a date input with any separator as long as you tell it before what it is going to be (hope that's not cheating!). Formula is in computed numeric field `o` on the same form.
Interesting aside: Ever since `@For` and `@While` were introduced into the Formula language in (I think) R6 by the great [Damien Katz](http://www.damienkatz.net/2005/01/formula-engine-rewrite.html "Damien Katz") the only use I have found for them is code golfing. I have never used them in a production app.
There is no TIO available for formula so here is a screenshot taken on 02.10.2018:
[](https://i.stack.imgur.com/6wIz1.png)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 81 bytes
```
->e{require'date';(Date.today...Date.strptime(e,'%d.%m.%Y')).count{|d|6>d.cwday}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y61uii1sDSzKFU9JbEkVd1awwVI6ZXkpyRW6unpgTnFJUUFJZm5qRqpOuqqKXqquXqqkeqamnrJ@aV5JdU1KTVmdil6yeVAHbW1/wsU0qLVjUz0DI30jAwMLdRj//8HAA "Ruby – Try It Online")
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~209~~ ~~208~~ 205 bytes
Compiler flags `-DU=u=localtime(&b)` `-DW=tm_wday` `-DY=tm_year` `-DT=tm_yday` (52 bytes).
```
#import<time.h>
i;f(char*a){long b;struct tm t,*u;time(&b);U;strptime(a,"%d.%m.%Y",&t);for(i=0;u->T^t.T|u->Y^t.Y;u->W&&u->W^6&&i++,b+=86400,U);return i;}
```
[Try it online!](https://tio.run/##bY9va4MwEIdfr59CHAZTY4hlSCGzr/YRlCKMjhj/NGCipOdG6frV56Kj7wbH8dzvHjhOxrIXppvnZ6XHwcIrKN3Q82GjeBvKs7BbgW/9YDqv4hewkwQPtAdkO/HFDFGFebFsxnUUxA9qGmgalD5BgHk72FBljE/xIT8Bzb8dlA7KJTkitPRTipCKIlJF2T59YYwUmNsGJms8xe@zMuBpoUz4Oaga3zZPo3VRG7pL78YnDpKUJozuWLL3Meb/CCyhrnYJY6twn39k24vuMsdvxwz0x1ctro7Lha@NsI7zlf/yIpuyfpCif7z8Cw "C (clang) – Try It Online")
-1 byte thanks to @JonathanFrech
[Answer]
# [Scala](https://www.scala-lang.org/), 251 bytes
Port of [@Olivier Grégoire's Java answer](https://codegolf.stackexchange.com/a/173176/110802) in Scala.
---
Golfed version. [Try it online!](https://tio.run/##bVBdS8MwFH3vr7gWhAQlNHtQWak4XAdDpuAEEZER27sto0tLct0mo7@9poWJTkMI4XzlnrhMFarR66q0BCu1UeKDdCFmwU@IcEdi6pECh4pwVNq1oiAo31eYEUyUNuAVaHIHg6qCfQBAVmmC@@4OcENLW27da7rLsCJdmrcOznEOGcv7MCWrzYL3YWzIM3Xgj40qwPR9RAIGt11U0BwcB4PXJ/uNsmCTKG4dLrlVhZ9EWbFAGhtHymQYO@GQnvQaWZvVluCdHP@X4y/5cXMW5rmYTMSnXyEXlbIOWc55vF3qAtkJc6DmhBaQ872eM9dms@@HhoOX2cNo9pymd/z08lpye5ZIP6HK8z@il3TweC55Hdu6OXxM5atTYZgRGQvlhZCR6EXyKuT8mIyk8Lsno6gl66D5Ag)
```
def c(d:String):Int={var r=0;val s=Calendar.getInstance;s.setTime(new Date);val e=Calendar.getInstance;e.setTime(new SimpleDateFormat("dd.MM.yyyy").parse(d));while(!(s after e)){if(s.get(Calendar.DAY_OF_WEEK)%7>1)r+=1;s.add(Calendar.DAY_OF_YEAR,1)};r}
```
Ungolfed version. [Try it online!](https://tio.run/##hVBtS8MwEP7eX3EWhAQltPugMpg43AZDpuAEGSIjNrctI0tLcm6K7LfXtM6yqWAoSe@el3vxmTSyLPWqyB3BUq6leCVtxDTaTxG@kRiHjMGeJBzkbiUpivKXJWYEI6ktBAZa5aFbFPARAZCTmuC2/ge4ooXLN/6p/5ZhQTq3z3Va4QwyptowJqftnLdhaCkg2yhca2nAtoNFByxuGqs/NYHzhVYyBy7ESRMb8CG@liY0KJ2YIw2tJ2kzZHxH8sIjPegVsqpUNSPjfM8A/zPAA4Ofq2KxUmI0Eu/hxFwU0nlkqqmwWWiDwI68kDNCx5DzZhwAPQPmq6Ks6aDXnUzvBtPHfv@GwzGcwyWkPEx90oG00QU3pX5pJv3u/Wlg72jb3eui76jefRFWS8YyKzIWp2ciTUQrSS/iuuUDMElF@FppklTgNirLTw)
```
import java.util._
import java.text.SimpleDateFormat
object Main extends App {
trait N {
@throws[Exception]
def c(d: String): Int
}
val n: N = new N {
def c(d: String): Int = {
var r = 0
val s = Calendar.getInstance()
s.setTime(new Date())
val e = Calendar.getInstance()
e.setTime(new SimpleDateFormat("dd.MM.yyyy").parse(d))
while (!s.after(e)) {
if (s.get(Calendar.DAY_OF_WEEK) % 7 > 1) r += 1
s.add(Calendar.DAY_OF_YEAR, 1)
}
r
}
}
println(n.c("16.10.2018"))
println(n.c("01.01.2100"))
}
```
] |
[Question]
[
Given two integers as input in an array, draw a rectangle, using the first integer as width and second as height.
Or, if your language supports it, the two integers can be given as separate inputs.
Assume the width and height will never be less than 3, and they will always be given.
Example Outputs:
**[3, 3]**
```
|-|
| |
|-|
```
**[5, 8]**
```
|---|
| |
| |
| |
| |
| |
| |
|---|
```
**[10, 3]**
```
|--------|
| |
|--------|
```
This is code-golf, so the answer with the lowest amount of bytes wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
,þ%,ỊḄị“-|| ”Y
```
[Try it online!](http://jelly.tryitonline.net/#code=LMO-JSzhu4rhuIThu4vigJwtfHwg4oCdWQ&input=&args=MTM+OA) or [verify all test cases](http://jelly.tryitonline.net/#code=LMO-JSzhu4rhuIThu4vigJwtfHwg4oCdWQrDpy_igqxq4oCcwrbCtg&input=&args=WzMsIDNdLCBbNSwgOF0sIFsxMCwgM10).
### How it works
```
,þ%,ỊḄị“-|| ”Y Main link. Left argument: w. Right argument: h
,þ Pair table; yield a 2D array of all pairs [i, j] such that
1 ≤ i ≤ w and 1 ≤ j ≤ h.
, Pair; yield [w, h].
% Take the remainder of the element-wise division of each [i, j]
by [w, h]. This replaces the highest coordinates with zeroes.
Ị Insignificant; map 0 and 1 to 1, all other coordinates to 0.
Ḅ Unbinary; convert each pair from base 2 to integer.
[0, 0] -> 0 (area)
[0, 1] -> 1 (top or bottom edge)
[1, 0] -> 2 (left or right edge)
[1, 1] -> 3 (vertex)
“-|| ” Yield that string. Indices are 1-based and modular in Jelly, so the
indices of the characters in this string are 1, 2, 3, and 0.
ị At-index; replace the integers by the correspoding characters.
Y Join, separating by linefeeds.
```
[Answer]
# Matlab, ~~69~~ ~~65~~ 56 bytes
Thanks @WeeingIfFirst and @LuisMendo for some bytes=)
```
function z=f(a,b);z(b,a)=' ';z([1,b],:)=45;z(:,[1,a])='|'
```
This is really simple in Matlab: First make a matrix of the desired size, then index the first and last row to insert the `-`, and do the same with the first and last column to insert `|`.
For example `f(4,3)` returns
```
|--|
| |
|--|
```
[Answer]
## JavaScript (ES6), 63 bytes
```
f=
(w,h,g=c=>`|${c[0].repeat(w-2)}|
`)=>g`-`+g` `.repeat(h-2)+g`-`
;
```
```
<div oninput=o.textContent=f(w.value,h.value)><input id=w type=number min=3 value=3><input id=h type=number min=3 value=3><pre id=o>
```
[Answer]
## Haskell, ~~62~~ 55 bytes
```
f[a,b]n=a:(b<$[3..n])++[a]
g i=unlines.f[f"|-"i,f"| "i]
```
Usage example:
```
*Main> putStr $ g 10 3
|--------|
| |
|--------|
```
The helper function `f` takes a two element list `[a,b]` and a number `n` and returns a list of one `a` followed by `n-2` `b`s followed by one `a`. We can use `f` thrice: to build the top/bottom line: `f "|-" i`, a middle line: `f "| " i` and from those two the whole rectangle: `f [<top>,<middle>] j` (note: `j` doesn't appear as a parameter in `g i` because of partial application).
Edit: @dianne saved some bytes by combining two `Char` arguments into one `String` of length 2. Thanks a lot!
[Answer]
# Python 2, ~~61~~ 58 bytes
-3 bytes thanks to @flornquake (remove unnecessary parentheses; use `h` as counter)
```
def f(w,h):exec"print'|'+'- '[1<h<%d]*(w-2)+'|';h-=1;"%h*h
```
Test cases are at **[ideone](http://ideone.com/goqHuN)**
[Answer]
# PHP, 74 Bytes
```
for(;$i<$n=$argv[2];)echo str_pad("|",$argv[1]-1,"- "[$i++&&$n-$i])."|\n";
```
[Answer]
# Vimscript, ~~93~~ ~~83~~ ~~75~~ ~~74~~ ~~73~~ ~~66~~ ~~64~~ 63 bytes
# Code
```
fu A(...)
exe "norm ".a:1."i|\ehv0lr-YpPgvr dd".a:2."p2dd"
endf
```
## Example
```
:call A(3,3)
```
## Explanation
```
fun A(...) " a function with unspecified params (a:1 and a:2)
exe " exe(cute) command - to use the parameters we must concatenate :(
norm " run in (norm) al mode
#i| " insert # vertical bars
\e " return (`\<Esc>`) to normal mode
hv0l " move left, enter visual mode, go to the beginning of the line, move right (selects inner `|`s)
r- " (r)eplace the visual selection by `-`s
YpP " (Y) ank the resulting line, and paste them twice
gv " re-select the previous visual selection
r<Space> " replace by spaces
dd " Cut the line
#p " Paste # times (all inner rows)
2dd " Remove extra lines
```
Note that it is not using `norm!` so it might interfere with vim custom mappings!
[Answer]
# Jolf, 6 bytes
```
,ajJ'|
```
[Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=LGFqSid8&input=MTAKCjM) My box builtin finally came in handy! :D
```
,ajJ'|
,a draw a box
j with width (input 1)
J and height (input 2)
' with options
| - corner
- the rest are defaults
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), 19 bytes
```
'|-| '2:"iqWQB]E!+)
```
[Try it online!](http://matl.tryitonline.net/#code=J3wtfCAnMjoiaXFXUUJdRSErKQ&input=NQo4)
### Explanation
The approach is similar to that used in [this other answer](https://codegolf.stackexchange.com/a/93700/36398). The code builds a numerical array of the form
```
3 2 2 2 3
1 0 0 0 1
1 0 0 0 1
1 0 0 0 1
1 0 0 0 1
1 0 0 0 1
1 0 0 0 1
3 2 2 2 3
```
and then its values are used as (1-based, modular) indices into the string `'|-| '` to produce the desired result.
```
'|-| ' % Push this string
2:" ] % Do this twice
i % Take input
q % Subtract 1
W % 2 raised to that
Q % Add 1
B % Convert to binary
E % Multiply by 2
! % Transpose
+ % Add with broadcast
) % Index (modular, 1-based) into the string
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~23~~ ~~22~~ 20 bytes
Input taken as height, then width.
```
F„ -N_N¹<Q~è²Í×'|.ø,
```
**Explanation**
```
F # height number of times do
N_ # current row == first row
~ # OR
N¹<Q # current row == last row
„ - è # use this to index into " -"
²Í× # repeat this char width-2 times
'| # push a pipe
.ø # surround the repeated string with the pipe
, # print with newline
```
[Try it online!](http://05ab1e.tryitonline.net/#code=RuKAniAtTl9Owrk8UX7DqMKyw43Dlyd8LsO4LA&input=MwoxMA)
Saved 2 bytes thanks to [Adnan](https://codegolf.stackexchange.com/users/34388/adnan)
[Answer]
# C, 73 bytes
```
i;f(w,h){for(i=++w*h;i--;)putchar(i%w?~-i%w%~-~-w?i/w%~-h?32:45:124:10);}
```
[Answer]
# Python 2, 56 bytes
```
w,h=input()
for c in'-%*c'%(h-1,45):print'|'+c*(w-2)+'|'
```
flornquake saved one byte.
[Answer]
## Common Lisp, 104 bytes
Golfed:
```
(defun a(w h)(flet((f(c)(format t"|~v@{~A~:*~}|~%"(- w 2)c)))(f"-")(loop repeat(- h 2)do(f" "))(f"-")))
```
Ungolfed:
```
(defun a (w h)
(flet ((f (c) (format t "|~v@{~A~:*~}|~%" (- w 2) c)))
(f "-")
(loop repeat (- h 2) do
(f " "))
(f "-")))
```
[Answer]
# [Turtlèd](https://github.com/Destructible-Watermelon/Turtl-d/), 40 bytes
Interpreter is ~~slightly~~ no longer buggèd
```
?;,u[*'|u]'|?@-[*:l'|l[|,l]d@ ],ur[|'-r]
```
## Explanation
```
? - input integer into register
; - move down by the contents of register
, - write the char variable, default *
u - move up
[* ] - while current cell is not *
'| - write |
u - move up
'| - write | again
? - input other integer into register
@- - set char variable to -
[* ] - while current char is not *
:l'|l - move right by amount in register, move left, write |, move left again
[|,l] - while current cell is not |, write char variable, move left
d@ - move down, set char variable to space (this means all but first iteration of loop writes space)
,ur -write char variable, move up, right
[| ] -while current char is not |
'-r - write -, move right
```
[Answer]
# Mathematica, ~~67~~ 64 bytes
*Thanks to lastresort and TuukkaX for reminding me that golfers should be sneaky and saving 3 bytes!*
Straightforward implementation. Returns an array of strings.
```
Table[Which[j<2||j==#,"|",i<2||i==#2,"-",0<1," "],{i,#2},{j,#}]&
```
[Answer]
# Python 3, ~~104~~ 95 bytes
( feedback from @mbomb007 : -9 bytes)
```
def d(x,y):return'\n'.join(('|'+('-'*(x-2)if n<1or n==~-y else' '*(x-2))+'|')for n in range(y))
```
(my first code golf, appreciate feedback)
[Answer]
## Batch, 128 bytes
```
@set s=
@for /l %%i in (3,1,%1)do @call set s=-%%s%%
@echo ^|%s%^|
@for /l %%i in (3,1,%2)do @echo ^|%s:-= %^|
@echo ^|%s%^|
```
Takes width and height as command-line parameters.
[Answer]
# Haxe, ~~112~~ 106 bytes
```
function R(w,h){for(l in 0...h){var s="";for(i in 0...w)s+=i<1||i==w-1?'|':l<1||l==h-1?'-':' ';trace(s);}}
```
## Testcases
```
R(5, 8)
|---|
| |
| |
| |
| |
| |
| |
|---|
R(10, 3)
|---------|
| |
|---------|
```
[Answer]
# Java 135 bytes
```
public String rect(int x, int y){
String o="";
for(int i=-1;++i<y;){
o+="|";
for(int j=2;++j<x)
if(i<1||i==y-1)
o+="-";
else
o+=" ";
o+="|\n";
}
return o;
}
```
Golfed:
```
String r(int x,int y){String o="";for(int i=-1;++i<y;){o+="|";for(int j=2;++j<x;)if(i<1||i==y-1)o+="-";else o+=" ";o+="|\n";}return o;}
```
[Answer]
## PowerShell v3+, 55 bytes
```
param($a,$b)1..$b|%{"|$((' ','-')[$_-in1,$b]*($a-2))|"}
```
Takes input `$a` and `$b`. Loops from `1` to `$b`. Each iteration, we construct a single string. The middle is selected from an array of two single-length strings, then string-multiplied by `$a-2`, while it's surrounded by pipes. The resulting strings are left on the pipeline, and output via implicit `Write-Output` happens on program completion, with default newline separator.
Alternatively, also at 55 bytes
```
param($a,$b)1..$b|%{"|$((''+' -'[$_-in1,$b])*($a-2))|"}
```
This one came about because I was trying to golf the array selection in the middle by using a string instead. However, since `[char]` times `[int]` isn't defined, we lose out on the savings by needing to cast as a string with parens and `''+`.
Both versions require v3 or newer for the `-in` operator.
### Examples
```
PS C:\Tools\Scripts\golfing> .\draw-an-ascii-rectangle.ps1 10 3
|--------|
| |
|--------|
PS C:\Tools\Scripts\golfing> .\draw-an-ascii-rectangle.ps1 7 6
|-----|
| |
| |
| |
| |
|-----|
```
[Answer]
# PHP, 82 bytes
```
list(,$w,$h)=$argv;for($p=$h--*$w;$p;)echo$p--%$w?$p%$w?$p/$w%$h?" ":"-":"|
":"|";
```
indexing a static string including the newline
```
list(,$w,$h)=$argv; // import arguments
for($p=$h--*++$w;$p;) // loop $p through all positions counting backwards
// decrease $h and increase $w to avoid parens in ternary conditions
echo" -|\n"[
$p--%$w // not (last+1 column -> 3 -> "\n")
? $p%$w%($w-2) // not (first or last row -> 2 -> "|")
?+!($p/$w%$h) // 0 -> space for not (first or last row -> 1 -> "-")
:2
:3
];
```
[Answer]
# Ruby, ~~59~~ ~~54~~ 52 bytes
Oh, that's a lot simpler :)
```
->x,y{y.times{|i|puts"|#{(-~i%y<2??-:' ')*(x-2)}|"}}
```
[Test run at ideone](http://ideone.com/4RlTzz)
[Answer]
# Perl, 48 bytes
Includes +1 for `-n`
Give sizes as 2 lines on STDIN
```
perl -nE 'say"|".$_ x($`-2)."|"for"-",($")x(<>-1-/$/),"-"'
3
8
^D
```
Just the code:
```
say"|".$_ x($`-2)."|"for"-",($")x(<>-1-/$/),"-"
```
[Answer]
# Lua, 120 93 bytes
Saved quite a few bytes by removing stupid over complexities.
```
function(w,h)function g(s)return'|'..s:rep(w-2)..'|\n'end b=g'-'print(b..g' ':rep(h-2)..b)end
```
Ungolfed:
```
function(w,h) -- Define Anonymous Function
function g(s) -- Define 'Row Creation' function. We use this twice, so it's less bytes to function it.
return'|'..s:rep(w-2)..'|\n' -- Sides, Surrounding the chosen filler character (' ' or '-'), followed by a newline
end
b=g'-' -- Assign the top and bottom rows to the g of '-', which gives '|---------|', or similar.
print(b..g' ':rep(h-2)..b) -- top, g of ' ', repeated height - 2 times, bottom. Print.
end
```
[Try it on Repl.it](https://repl.it/Dc0e/8)
[Answer]
# Python 2, 67 bytes
```
def f(a,b):c="|"+"-"*(a-2)+"|\n";print c+c.replace("-"," ")*(b-2)+c
```
**Examples**
```
f(3,3)
|-|
| |
|-|
f(5,8)
|---|
| |
| |
| |
| |
| |
| |
|---|
f(10,3)
|--------|
| |
|--------|
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~21~~ 17 bytes
```
Z"45ILJhY('|'5MZ(
```
This is a slightly different approach than the one of the [MATL-God](https://codegolf.stackexchange.com/a/93725/24877).
```
Z" Make a matrix of spaces of the given size
45ILJhY( Fill first and last row with '-' (code 45)
'|'5MZ( Fill first and last column with '|' (using the automatic clipboard entry 5M to get ILJh back)
```
Thanks @LuisMendo for all the help!
[Try it Online!](http://matl.tryitonline.net/#code=WiI0NUlMSmhZKCd8JzVNWig&input=WzUgOF0)
[Answer]
# PHP 4.1, 76 bytes
```
<?$R=str_repeat;echo$l="|{$R('-',$w=$W-2)}|
",$R("|{$R(' ',$w)}|
",$H-2),$l;
```
This assumes you have the default `php.ini` settings for this version, including [`short_open_tag`](http://php.net/manual/en/ini.core.php#ini.short-open-tag) and [`register_globals`](http://php.net/manual/en/ini.core.php#ini.register-globals) enabled.
This requires access through a web server (e.g.: Apache), passing the values over session/cookie/POST/GET variables.
The key `W` controls the width and the key `H` controls the height.
For example: `http://localhost/file.php?W=3&H=5`
[Answer]
# Python 3, 74 chars
```
p="|"
def r(w,h):m=w-2;b=p+"-"*m+p;return b+"\n"+(p+m*" "+p+"\n")*(h-2)+b
```
[Answer]
# Swift(2.2) 190 bytes
```
let v = {(c:String,n:Int) -> String in var s = "";for _ in 1...n {s += c};return s;};_ = {var s = "|"+v("-",$0-2)+"|\n" + v("|"+v(" ",$0-2)+"|\n",$1-2) + "|"+v("-",$0-2)+"|";print(s);}(10,5)
```
I think Swift 3 could golf this a lot more but I don't feel like downloading Swift 3.
[Answer]
## F#, 131 bytes
```
let d x y=
let q = String.replicate (x-2)
[for r in [1..y] do printfn "%s%s%s" "|" (if r=y||r=1 then(q "-")else(q " ")) "|"]
```
] |
[Question]
[
Characters in strings are sometimes represented as their ASCII hexadecimal codes. Printable characters have two hex digits in their representation. Swapping those digits leads to another character, which will be our output.
The table of relevant character codes can be found on [Wikipedia](https://en.wikipedia.org/wiki/ASCII#Printable_characters).
## Details
1. Take a string as input.
2. For each character:
1. Find corresponding hex value of ASCII code.
2. Swap (reverse) the hex digits.
3. Convert back to character.
3. Output the new string.
## Rules
* To make thinks easier, let's consider only characters "reversible" within standard printable ASCII range - that is codepoints (in hex): `22-27,32-37,42-47,52-57,62-67,72-77` or characters: `"#$%&'234567BCDEFGRSTUVWbcdefgrstuvw`.
* Input and output should be strings or closest equivalent in your language of choice.
* You may assume the input is non-empty.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the usual rules apply.
## Example
```
input: debug
hex codes: 64 65 62 75 67
reversed: 46 56 26 57 76
output: FV&Wv
```
## Test cases
```
bcd <-> &6F
234 <-> #3C
screw <-> 76'Vw
debug <-> FV&Wv
BEEF <-> $TTd
7W66V77 <-> success
"#$%&'234567BCDEFGRSTUVWbcdefgrstuvw <-> "2BRbr#3CScs$4DTdt%5EUeu&6FVfv'7GWgw
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 5 bytes
```
CHRHC
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwiQ0hSSEMiLCIiLCJiY2QiXQ==)
Look ma, no unicode, and it's a palindrome!
```
C C # To charcodes...
H H # To hexadecimal versions of charcodes
R # Reverse each
# (s flag transforms output into string)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 26 bytes
Accepts input from STDIN.
```
$<.bytes{|c|putc c*257>>4}
```
[Try it online!](https://tio.run/##KypNqvz/X8VGL6myJLW4uia5pqC0JFkhWcvI1NzOzqT2/3/zcDOzMHNzAA "Ruby – Try It Online")
Alternative 26s:
```
$<.bytes{|c|putc c*16%255}
$<.bytes{|c|putc c*16.065} # was discovered by @Arnauld
```
# [Ruby](https://www.ruby-lang.org/), 28 bytes
```
->s{s.unpack('H*').pack'h*'}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1664ulivNK8gMTlbQ91DS11TD8RUz9BSr/1fUFpSrJAWrW4ebmYWZm6uHvsfAA "Ruby – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~55~~ 54 bytes
```
lambda x:''.join(chr(c%16*16|c>>4)for c in map(ord,x))
```
[Try it online!](https://tio.run/##JY7BjoIwGITvfYo/KrRsXBNFS2IWDyp4V4TLXkpblI0CaQu4yb67Yvc2M/kyM82vudaV/yzC7@eN3XPB4LHGePZTlxXhV0W4M6cfc/rHN5ulV9QKOJQV3FlDaiWmD8972pBp@c5LIxUpq6Y1U8DYWyNgU8ghtMBMN7fSEAxfnxvAHoJGlZUhBWEehOGAsUoAe8uC5ENxzoVFXRqjhb@0euzvkOZK9tYFFKc9EjJvL9bHqZt1aBtFsbWTJBEoyChNg8AGuuVcao1G44nj4qFzRYPtbh/Fh@MpOafZsCiLi9Km7f4HRovtMVfD6InryXKfCOOsorNsh0tp0eHgkF16hF4 "Python 3 – Try It Online")
Can be shorter if bytestrings are permitted:
# [Python 3](https://docs.python.org/3/), 38 bytes
```
lambda x:bytes(c%16*16|c>>4for c in x)
```
[Try it online!](https://tio.run/##JY5Nj4IwEIbv/RUTFdtuXBO/SmIWDyh4V4TLXvqFS@IioQU02f/OYr29z@SdeaZ62p97uerz4Lu/8V@hODy24mm1IdJbsI8F@5O73Tq/1yChKOFBe5e50S8srK5JUVaNnQHGdIuAz0BA4ApzXcq70oTOTXUrLBEYvj53gCmCqi5KS3LCKQTBsMBLBfwVcyIo7YVUrjplMVqu1i6PV3tkZK07Rz7DaYeUFs3VcZxOsxaFURQ7nCSJQn7GWOr7bmAaKbUxaDSeeFM83NwwP9wfovh4OieXNBuMOr/WxjbtWzBahidRD9KzNJP1IVHW20QX3QwvpXmL/WN27RD6Bw "Python 3 – Try It Online")
[Answer]
# [APL (dzaima/APL)](https://github.com/dzaima/APL), ~~14~~ 13 bytes
−1 thanks to Unrelated String
Anonymous tacit prefix function.
```
⊖⍢(0 16⊤⎕UCS)
```
[Try it online!](https://tio.run/##SyzI0U2pSszMTfyf9qhtgsb/R13THvUu0jBQMDR71LXkUd/UUOdgzf@aXEAWUD5NPSk5RR3OMTI2QXCKk4tSyxHclNSk0nQE18nV1Q3BMw83MwszN0cIKCmrqKqpgww0NTN3cnZxdXMPCg4JDQsH2peall5UXFJaVq7@HwA "APL (dzaima/APL) – Try It Online")
`⊖` flip…
`⍢(`…`)` while argument is represented as…
`0 16⊤`… two-digit hexadecimal representation of…
`⎕UCS` Universal Character Set code points
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~33~~ 32 bytes
*Saved 1 byte thanks to @dingledooper*
```
s=>Buffer(s).map(n=>n*257>>4)+''
```
[Try it online!](https://tio.run/##XdBNj4IwEAbgu7/CKFLYzWKC0J7ggIJ3xHIV@kE0LhiGws9na9YY0zk/mXnfuVVjBay/PoaftuNiltEMUZwoKUXvgOv9Vg@njeL2yw9JHAfuN0Iz61ro7sK7d40jnUvN@MV1l8/Zbpc2zhYG8HfBB1jv9ibQAcT0TzQgGNHJJFzUqnmTjNrlaJIkTbPXHU2souCmICXGlJAn0gIUYwLARKu1tbGRzhxikuwPaXbMT8WZlrqmkE0Pgxqn14aVn@R1rwudGFjBoeDDJkzPQukfUDkiciybaf4D "JavaScript (Node.js) – Try It Online")
### How?
When `map`'ing over a `Buffer`, the updated values are implicitly truncated to bytes, so we can just do `n * 257 >> 4` without worrying about the upper nibble.
[Answer]
# [Perl 5](https://www.perl.org/) + `-p`, 22 bytes
A port of [@dingledooper's second Ruby answer](https://codegolf.stackexchange.com/a/247813/9365).
```
$_=pack'h*',unpack'H*'
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3rYgMTlbPUNLXac0D8z00FL//784uSi1/F9@QUlmfl7xf90CAA "Perl 5 – Try It Online")
[Answer]
# sh + coreutils, 34 bytes
```
xxd -p|tr -d \\n|rev|xxd -r -p|rev
```
[Try it online!](https://tio.run/##S0oszvj/v6IiRUG3oKakSEE3RSEmJq@mKLWsBixYBBIH8v7/T0lNKk3/DwA "Bash – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 11 bytes
```
m(cB16↔B16c
```
[Try it online!](https://tio.run/##yygtzv7/P1cj2cnQ7FHbFCCZ/P///5TUpNJ0AA "Husk – Try It Online")
`m`ap `(` `c`haracters of `B`ase-16 values of `↔`=reverse of `B`ase-16 representation of `c`haracter codes of the input.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 33 bytes
```
T`#-'4-7E-GVWgvuet\dTscSCrbRB2`Ro
```
[Try it online!](https://tio.run/##JY65EoMgAER7vsKJB5WNBzSZFCjaK0KTwnDopElmQPTzjUO6fVvsW2u29@d1nmyOc1jlmOY9F@vuzfbUzKmxsXIgxTx8z1MqHd3zR5ShDhRlFXJcNsApa45AGEF@AG2kXwN3PBM7IJR2ARPGNMACIY5xKJxXyjgHbnGSZvDarBEmTUu7fhjZxMVlNMtq3eb3v@BWkEHaSzoql1Qt01ta08n46xJfdoh7sR4/ "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: `o` substitutes for the transliteration string and `R` reverses it so each listed character gets mapped to the one opposite. Character ranges are used twice to reduce the byte count and once to avoid quoting the `E` but as `d` maps to `F` I can't use character ranges for both `d` and `E`.
[Answer]
# [GeoGebra](https://www.geogebra.org/calculator), 107 bytes
```
s=""
InputBox(s)
UnicodeToText(Zip(FromBase(Sum(Reverse(Split(ToBase(a,16),{""}))),16),a,TextToUnicode(s)))
```
To enter this code into GeoGebra, copy/paste in one line at a time and press enter to go to a new line. Do not copy paste directly; it won't work.
Input goes in the Input Box. It was a bit of a challenge to get this working, as GeoGebra has a pretty limited set of tools for working with strings.
[Try It On GeoGebra!](https://www.geogebra.org/calculator/qztmdptq)
### Explanation
`Zip(...,a,TextToUnicode(s))`: For every integer element `a` in the list of char codes of each character in the input string `s`:
```
FromBase(Sum(Reverse(Split(ToBase(a,16),{""}))),16)
ToBase(a,16) Convert a to a base 16 string
Split( ,{""}) Split the string into a list of characters
Reverse( ) Reverse the list
Sum( ) Concatenate the characters into a string
FromBase( ,16) Convert the base 16 string back to base 10
```
`UnicodeToText(...)`: Convert the list of char codes back to a string
[Answer]
# JavaScript (ES6), ~~113~~ ~~107~~ 77 bytes
```
s=>String.fromCharCode(...[...s].map(c=>c.charCodeAt()).map(c=>c%16*16|c>>4))
```
77 bytes if we use [Unrelated String's method](https://codegolf.stackexchange.com/a/247806).
[Try it online!](https://tio.run/##XdBbb4IwFADg9/0Ko1xak9Wo2D5BMhB8F4SHZYlQCrooNS2Xl/13VjNiljY5Lz1fzu0773NJxfXRvje8ZGPljtL14lZcmxpVgt@DSy4ClQEIoU8V8gvd8wegrkcRnXIfLYDw9W2u8XKNf6jnORCOlDeS3xi68RpU4FzQ8gzh7PlWq5mFozcNbLbOP7DYBjpQ07LhjyhAsJ0OOilZ0dUvEqVW1uvED8No6qOIkSSlLkiGcUrIEykhO0qZlDqaLwzTstXMO0z8YB9Gh2OcnNJMrcmqWsi264epwnzjHwuhFoqpNJx9UrbmLjyxTt0grXqbHLJ6GH8B "JavaScript (Node.js) – Try It Online")
---
107: Slightly better.
```
s=>String.fromCharCode(...[...s].map(c=>parseInt([...c.charCodeAt().toString(16)].reverse().join(''), 16)))
```
[Try it online!](https://tio.run/##XdBNi4MwEAbg@/4KaW1NYDdl@6EnC6vVstdq9bAUqjG6ltZIEvXnuyOVshjIZeZhMm9uSZtIKspafVQ8Y31u99LeB0qUVUFywR/ubyJc6CBCyA9ceSGPpEbU3teJkOy7UmgoU0JH@KUQJoo/R6BPE1@IYC0DC/UbLytkGPhdgwbGPeWV5HdG7rxAObqmNLtirA1ntdKWpv82AevN9h@Yb9wpgCysexIAlmlE3ZRkLG2KF/GjZdxOieN5/vgOED0Ms6mwYtOMLGtAIGRDKZNyimZzfbE0YOedaTnuwfOPpyA8RzHEZHkhpGrabpwwWzunVECggEp9ewgztdh5Z9bAH0R5a1jHuOj6Pw "JavaScript (Node.js) – Try It Online")
---
Original 113 byte answer:
```
s=>[...s].map(c=>String.fromCharCode(parseInt([...c.charCodeAt().toString(16)].reverse().join(''), 16))).join('')
```
[Try it online!](https://tio.run/##XdBdb4IwFAbg@/0KoihtstXMj/YKk4FgdisIF4uJUArDKCVtgZ/PSiTbQu96ztOP99ySNpFUlLV6q3jG@tzupb3/QgjJC3okNaD2PlCirAqUC/5wvxPhagfqREj2WSkwUIroWP9QACLFnyfAO4YXJFjLtNX1Gy8rYFnw1dAN@LfvKa8kvzN05wXIwTWl2RVCY1irlbHE/ssErDfbf2C@cadAJ2Ldk2hAsBV1U5KxtCl@iR8t43ZKHM/zx3c0McMwmwoSYxwRMiAtZEMpk3KKZnNzsbT0n3eYOO7B84@nIDxHsY7J8kJI1bTdeMNs7ZxSoQMFVJrbQ5ipxc47s0bPIMpbixzjout/AA "JavaScript (Node.js) – Try It Online")
This is my first time ever posting here. Obviously not the best solution but I wanted to compete.
[Answer]
# Rust, 49 bytes
```
fn f(s:&mut[u8]){for c in s{*c=c.rotate_left(4)}}
```
Rust doesn't have a string type for plain-ASCII strings, only UTF-8 with enforcement. An [SO answer](https://stackoverflow.com/questions/22118221/how-do-you-iterate-over-a-string-by-character/67308339#67308339) recommends `&[u8]` slices for working with ASCII bytes. I realize this is bending the rules, so I did also find sufficient incantations to get Rust to let me do this to the bytes of an actual `str` primitive type (a slice of which is like a C `char*` + length). IDK if there's any shorter way to write this, or a way to use compiler options instead of the `unsafe{}`.
# Rust using `str` strings, 72 bytes
```
fn h(s:&mut str){unsafe{for c in s.as_bytes_mut(){*c=c.rotate_left(4)}}}
```
These could [apparently](https://codegolf.stackexchange.com/questions/74096/tips-for-golfing-in-rust/74097#74097) be smaller as closures, but I'm just taking baby steps towards learning some Rust. Suggestions welcome.
Expanding ASCII codes to hex-strings and then swapping pairs is equivalent to rotating the original integer by 4, to swap nibbles. Rust is fun for that because it has as language built-in most of the common things many CPU instructions can do to integers. Instead of needing voodoo that a compiler has pattern-recognize back to a rotate or popcount for portable code to run efficiently. [The `u8` docs](https://doc.rust-lang.org/std/primitive.u8.html#method.rotate_left) include all these operations.
These compile to x86-64 asm that rotates the bytes in an array, as you can see [on Godbolt](https://godbolt.org/z/Te48r4bW6). (Note the `rol byte ptr [rcx], 4` in the cleanup loop if the SIMD code isn't easy to follow. (2x shifts and vpternlogd as a bit-blend.) Unfortunately the `-C opt-level=1` asm is rather hard to follow, and the opt-level=2 code vectorizes, so I couldn't get just a simple scalar loop to look at more easily. But I'm just using range-for stuff so I don't have to worry about loop bounds.)
Unlike many languages, Rust does *not* do implicit promotion to wider types for operators like `*`, or even implicit conversion of integer types on assignment. The `*16%255` hack does not save space over `.rotate_left(4)`. I don't know if both sets of `()` are truly necessary around the `as i32` and so on, but I'm pretty sure the `as something` and `as u8` are necessary.
```
fn g(s:&mut[u8]){for c in s{*c=((*c as i32)*16%255) as u8}}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
⁴ɓObUḅỌ
```
[Try it online!](https://tio.run/##y0rNyan8//9R45aTk/2TQh/uaH24u@f/w91bDm09OvnhzsWPGuYo2OjaKTxqmHu4/VHTmoc7Z6kcm6j5/39ScgpYQs3MjcvI2ATMVjZ25ipOLkotB/PMzdTDyrlSUpNK08F8tzC18DIuJ1dXNzBXJSQkhcs83MwszNwcLFBcmpycWlzMpaSsoqqmDjTT1MzcydnF1c09KDgkNCwcaGNqWnpRcUlpGcQCJSOnoKQioKXBycUqJi4hKSWqpq6hqaVAJ4Wllambu4enlwMA "Jelly – Try It Online")
Not a palindrome, but still sounds kind of goofy.
```
O Character codes.
b Convert to base
⁴ɓ 16,
U reverse each,
⁴ɓ ḅ convert from base 16,
Ọ and convert from character codes.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÇhíHçJ
```
[Try it online](https://tio.run/##yy9OTMpM/f//cHvG4bUeh5d7/f@fkppUmg4A) or [verify all test cases](https://tio.run/##HY05DsIwEEWvgpytSZXFLiNlRZRZnAIosOMEKqQ4i3IB6LkEFafITbhIGNPMG43@f3OXF3YT27QEaPd9vHYoWLb1eV0/@/V92OztiBhvkI0c14MpeS9mYCPY2AHDJEkBpMaYEgLbCWm6YVqQ9jEJozhJs7woK1qDRbRdL4dxUgITq57mRqqNLapuKTXrCaiXpfooR86FlH@pE@ash3TBpe7FZTMYflKJESy0nSyS1d2Mzj8).
**Explanation:**
```
Ç # Convert the (implicit) input-string to a list of codepoint integers
h # Convert each integer to a hexadecimal string
í # Reverse each string in the list
H # Convert each string from hexadecimal to a base-10 integer
ç # Convert each codepoint-integer to a character
J # Join them together to a string, since a string I/O that overwrites the
# default I/O ruling is mandatory for this challenge
# (after which it is output implicitly as result)
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 6 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
Æ$¢x¢$
```
I guess it could be a palindrome by adding a trailing no-op `Æ`. ;)
[Try it online.](https://tio.run/##HY09EoMgEEb7HANRe3@gV9FeEZs0EZEUyWRGRHOCHMSjmIORJc2@nZ3ve/u8rXf9eszOfT/4PN7ngZ1Do5zQBSVpBtPIRe3ASY1WAwvGagAdCBGUwnZFAQ6jGNI5oUVZsbppO96LASxq1otZ7eYFEfG9IC19m8TC32oRDRsQc@4/GiulMuYvTYp2XCDdSYOzik9rmLNeWbCIeYtpM@gd/QA)
**Explanation:**
```
Æ # Loop over the characters of the (implicit) input-string,
# using five characters as inner code-block:
$ # Convert the character to a codepoint-integer
¢ # Convert the integer to a hexadecimal string
x # Reverse it
¢ # Convert it from a hexadecimal string to an integer
$ # Convert it from a codepoint-integer to a character
# (after the loop, implicitly output the entire stack joined together)
```
[Answer]
# x86 32-bit machine code, 7 bytes
```
C0 02 04 42 E2 FA C3
```
[Try it online!](https://tio.run/##bVFNTxsxED17fsWwNNSGgCBJE0TYHpIGTpWqNIVWKYocr72x5HhXa2@DhPjrLJMQDq16sTzva5406jRXqmlkWCPHacLhLHfFUjo0YK5YVTgc/ZpN8NtsinOdPT60sQfMeoU0AHNFUZKSVTqCSFAMYbGQMVZ2WUe9WHBuZIhKOicEqpWs0HDrI/r223QcyAGHFOfqTON1iJktzlaf/4Iq6/MttjWupfVcwBOwnT/MLzqXD0Ngm5V1GnlQ0huetELSxiAwTfFCACM1M5yCnPY8iC1FFlbWMfDd9xlYSVsiWX/7r1KtrNeoikxfJVtaFT5ErH2wudfZvnmJKfL/MsIM/4EUhWQFvu/A1nnnJzVU6XF5ciKGuG@v8CDF88dxl5Y@N81SZdDp9iCoSm8g08s6h9FkcgOD@37/bjCA5PBD6@gjST71B6Pxl8nN7fT77MfdPRm1yasQ6z@bF2WczENzuu526KEzp1RCu1c)
Following the `fastcall` calling convention, this takes the length and address of a string in ECX and EDX, respectively, and modifies the string in place.
In assembly:
```
f: rol BYTE PTR [edx], 4 # Rotate the character left by 4 bits, swapping its nybbles.
inc edx # Add 1 to EDX, advancing the pointer.
loop f # Subtract 1 from ECX and jump back if it is nonzero.
ret # Return.
```
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~36~~ \$\cdots\$ ~~34~~ 29 bytes
```
f(*s){for(;*s++=*s*16%255;);}
```
[Try it online!](https://tio.run/##bZFRU7JAFIbv@xX7keiCNpUG1FDfhYbddFWGF@EFLrvmRMhwFrUcf7sdd0WtiRng5ex7nnc5y85YGmeTzUZQG6yVmBXUt6HZvLPBvnTNtuP4lr/eTDNJPuJpRi2yOiF4YcEmkoOE1xG5I6tHY8wSo0UejXbnSr2BFXyhVMLH5USpbhD0lfCGrht6ntKnNbPewC7H9bq9@6D/8PQ8eAmHyONiUoAs5wtj7R9S@TLnTPKkCq67mnna6Wm22wh1cD@sD@dK1QYDvTsoGeMAeqfdp3GBXc8Malf3g0SaTvDCS@SFYt7wHoaTfTCbZSAJe4sLG5@cvfNCxxvRMmhHy5se3g5Sj787VTdOldDtCKdZwpfYduHv5C2B6RefCVr9lHW@K9j7ik@aTeW2FEzP/3AGiNPnoDwj/@fyuBQCHSxO0xmjCwYpz6i0WuTaOjixzPJPuvW2iDxaEKpm/WJyBO4P4Y9UkscA6Pm35X7kOy4/wuQF2gQ1IsNMITLI2X9SSROiDOcoW0S3VdPeMkc7xPpkvfkG "C (clang) – Try It Online")
*Saved a byte thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!!!*
*Saved a byte thanks to [Juan Ignacio Díaz](https://codegolf.stackexchange.com/users/112488/juan-ignacio-d%c3%adaz)!!!*
*Saved 5 bytes thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)!!!*
Inputs a pointer to a wide string.
Returns the reverse hex cipher through the input pointer.
[Answer]
# Java 8, ~~116~~ ~~61~~ 57 bytes
```
s->s.chars().forEach(c->System.out.printf("%c",c*16%255))
```
-55 bytes by porting [*@UnrelatedString*'s Python answer](https://codegolf.stackexchange.com/a/247806/52210), so make sure to upvote him/her as well!
-4 bytes thanks to *@dingledooper*
Input as String (which is mandatory according to the rules and overwrites [the default rules](https://codegolf.meta.stackexchange.com/questions/2214/whats-a-string)..), but outputs directly to STDOUT.
[Try it online.](https://tio.run/##XZHBcoIwEIbvPsVOFIVWmKkKdOrUg4qe6kEpHNoeQgiIRXRIwOk4PDtNKPZgDrvJ5t9vd5MDLrF@CL9rkmLG4A0n2bUDkGSc5hEmFDbyCFCekhCIuuN5ksXAtKmIVh1hGMc8IbCBDF5rps@YQfY4Z6pmRKfcwWSvEn22@2GcHo1TwY2zAPBIRQpBQ/LwZCkj09S0eipZ5yJIBatFNiWPoqG26scX1v6aEeRbJ5wyDi@Q0QvcVFcUkBAN0Wg8EZaRnF6ED2lQxMLPHWclnO1blmfbYveJuj2lPxBq07Lni6WzWm937rvnCwqN4pzxopSAviXzuuOFzLYGnoytvL5fCt9zXVmRFYRQxhroaL4NcqHeEdabLN2QK6bzTgtB8aJyYK/9@IKqdh6A@wdS5VyPCJCR0zPFXB0/6zJkpDSL@V7VtOYH5MoM0qj/A/esNFPbu6r5tKr@BQ)
**Explanation:**
```
s-> // Method with String parameter and no return-type
s.chars().forEach(c->// Loop over the input-characters as integers:
System.out.printf( // Print:
"%c", // Converting a codepoint-integer to character:
c*16 // The integer multiplied by 16
%255)) // Modulo-255
```
With default I/O rules this could have been 21 bytes, by having the I/O as a stream of codepoint integers: `s->s.map(c->c*16%255)` - [Try it online.](https://tio.run/##fVFLb9swDL7nVxBqHvayCGjS2EOL9pAndlgGNK5z6HaQZcW158iBKDsogvz2jEqz04BeSOrjx098FKIRgyL9c5alQIQfItfHFkCurTJbIRWs3BOgIB6vbV5ytEaJHf@u7foSgfQ@SaL/QPWnFhm0wuYSVqDh8YyDJ@Q7sffk4El@uQ06w/HYPz843r5OSuJd6U2Vp7CjtjxSzHX2@lv4Hy1tK3PFwCq0cA9aHeAf68gSmbKvbDi6I4vSqAP5VCV1Rn4yny/IhZsgiMOQol/spt3p9og9DsLJdDZfLJ/X0Uu8IRW1zQzaunEC3cDV3YymrjroxQ5bxN1NQ74dRe5HrKVUiBfR4eQ5McReS2zfzaLUdsbzF1WTSrxteuFykx3Yyb@MA7B@R6t2vKot39MQttSeG6zPgHGj9kpYb/Rt4CBeKp3ZN8/3@5rLC4vLN2GQELfVqPqZFG61jPU9l/Clz2VVlkra/681/UhUBnlR5ZrWRzLXu53OfwE)
### Original 116 bytes answer:
```
s->s.chars().forEach(c->{var t="".format("%02x",c).split("");System.out.print((char)Long.parseLong(t[1]+t[0],16));})
```
Again input as a String and output directly to STDOUT.
[Try it online.](https://tio.run/##ZVFNUyIxEL37K7oiH0kJKQWd2ZLSAzp4cT0IDgeWQ8iEYXQIU0lm0KLmt7OdWdzDbg7d6ZfO6/eSd1GJ/nvycZS5sBZ@ikwfzgAy7ZRZC6ngxZcA1S5LQNKpM5lOwbIRovUZBuuEyyS8gIa7o@3fWy43wljK@HpnIiE3VPbvD5Uw4O4I8eBWOEral4NP0pOM2yLPsCZsNP2yTm35rnS8wCmOUs/Ennc65QVSKr@jbnG1vHCLy2XvKmBsVLPjyMsoylWOMk5qGrVb9HISvFgK9scHzv824ZR1cAta7eG760BWMiE9MhheY7TSqD3mRK3KFPM4iiaYwnkQxGGIu1/kvNXudLH7JgjHD4/R5Ol1OnuL58ii1qmxrqw8QSfw986HD/520I09Nok78wpzazbzE20ppbK2IR2MX1cGu6fStq4fZ4lr30RvqkSWeF11w6d5uif1yQ/Af8/mfV0QINyoQuFbD3/0PcRzpVO3oYw1n@eX5rLp/gv8y5Vrejqrm/@uj78B)
**Explanation:**
```
s-> // Method with String parameter and no return-type
s.chars().forEach(c->{// Loop over the input-characters as integers:
var t="".format("%02x",c)
// Convert the integer to a hexadecimal string of two hex-digits
.split(""); // Convert it to a String-array
System.out.print( // Print:
(char) // Cast a long to character:
Long.parseLong( // Convert a string to a long:
t[1]+t[0], // The hex-digits in reversed order
16));}) // Converted from base-16 to base-10
```
Some notes:
* It loops over the array as integers with `for(int c:s)` so we can use `c` in the `"".format(...,c)`, instead of as characters with `for(var c:s)` so we would need an explicit cast to integer `(int)c`.
* Although [`Long.valueOf`](https://docs.oracle.com/javase/8/docs/api/java/lang/Long.html#valueOf-java.lang.String-int-) is 2 bytes shorter, it'll return an object `Long`, which requires a cast to `long` before the cast to `char` (`(char)(long)Long.valueOf(...)`). So instead we use [`Long.parseLong`](https://docs.oracle.com/javase/8/docs/api/java/lang/Long.html#parseLong-java.lang.String-int-), which already returns a primitive `long`.
[Answer]
# [Factor](https://factor), ~~29~~ 23 bytes
```
[ [ 4 8 bitroll ] map ]
```
[Try it online!](https://tio.run/##FY09D4IwGIR3fsWb@rU5KFKjGwrExUEEBmSAUqAJArZFBuNvr6/LPZfL5a7Kme6licLLNTiA4q@Rd4wreOa6WRdCT0JxED0cLesDpGAlAbLZ2qiKST4hS16MNdL1PB9BE8eJKUX3ILP5YrnC9s6h7uns@cEtvEdxgiu8qqXS4xsHviaFFGzYA97Jvm0hw/cBMvPXFAYpOo0Zz1ljfg "Factor – Try It Online")
Roll each code point 4 bits to the left, wrapping around after 8 bits.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 10 bytes
```
`c$16/|16\
```
[Try it online!](https://ngn.codeberg.page/k#eJyNkM1ygjAUhfd5CgZR24WmVUw60OlCBfeKsFBn1HABRys2CYjTn2dvCD6Au5xvJnPOdxNny6xXgn9eyRoh6Xxbq9sfdxLDMCp3mx/dp22yO5zcyr25/Hnzi+TK3LPYdM0O8c1NHQdDW8XWcNJEwThcFaCkG14bFMO+SBXyw05UNmjseb4iVhDEDaARISGliomCMRCiwWuzZbU7XdUxInQ8mXr+bL4IlmGkRkCSciGLsm5bm4PxfM/VigUTlj0NYtkeeUso1MwwKbt0FqX1GoRRJuVFOBizPIY0PyV9IXfsCBXLducU+iz/xF8FCHnIzwIPbPr2YmMOJXABvQyqHjtcMuAIqQXGe+/DUA1I7dNv1Y/0AXTSJ0DaXmftj2p1HWt5dPfW4G6OHnHWHx6R/gcJcotN)
* `16\` treating the string input as if it is integers (corresponding to the ASCII codes), convert it to a base-16 representation
* `|` reverse the digits
* `16/` convert back from the base-16 representation
* ``c$` convert back to a character/string format and (implicitly) return
[Answer]
# [Fig](https://github.com/Seggan/Fig), \$8\log\_{256}(96)\approx\$ 6.585 bytes
```
CmHe$mHC
```
[Try it online!](https://fig.fly.dev/#WyJDbUhlJG1IQyIsImRlYnVnIl0=)
Input as string, output as list of chars.
```
CmHe$mHC
C # Charcodes
mH # To hex
e$ # Reverse each
mH # From hex
C # To chars
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes
```
⭆S℅↨¹⁶⮌↨℅ι¹⁶
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaHjmFZSWQLgamjoKzkCFicklqUUaTonFqRqGZjoKQallqUVANljAvyglMy8xRyMTqNbQTBMMrP//dwtTCy/7r1uWAwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
S Input string
⭆ Map over characters and join
ι Current character
℅ ASCII code
↨ Convert to base
¹⁶ Literal integer `16`
⮌ Reversed
↨ Convert from base
¹⁶ Literal integer `16`
℅ ASCII Character
Implicitly print
```
If both parameters to `Base` are integers then the second is always the base but if one parameter is an array then the other is the base. This allows the two `16`s to be naturally separated in the code thus avoiding an explicit separator.
[Answer]
# [R](https://www.r-project.org/), 50 bytes
```
function(s,r=utf8ToInt(s))intToUtf8(16*r%%16+r/16)
```
[Try it online!](https://tio.run/##K/qflpNZEJ@ckViUnJ@SWmz7P600L7kkMz9Po1inyLa0JM0iJN8zr0SjWFMzM68kJD8UKKJhaKZVpKpqaKZdpG9opolmhIZSSmpSabqS5n8A "R – Try It Online")
Much more boring than my previous approach, but 7 bytes shorter.
---
Previous approach:
# [R](https://www.r-project.org/), 57 bytes
```
function(s)intToUtf8(t(matrix(0:255,16))[utf8ToInt(s)+1])
```
[Try it online!](https://tio.run/##K/qflpNZEJ@ckViUnJ@SWmz7P600L7kkMz9Po1gzM68kJD@0JM1Co0QjN7GkKLNCw8DKyNRUx9BMUzO6FCgRku@ZVwJUqW0Yq4lmkoZSSmpSabqS5n8A "R – Try It Online")
[Answer]
# [StackCell](https://esolangs.org/wiki/StackCell) (u32), 20
`'.[@:'ÿ'␂+*'␐x/'ÿ&;]` ~~(due to an interpreter bug, programs are required to contain valid UTF-8 - the 255 bytes need to be converted to `#FF` to run this, losing two bytes; however, by the language's specification this is a well-formed program - therefore I have not counted the two lost bytes as part of my score; let me know if I need to)~~ I have just fixed this interpreter bug
Explanation:
```
'.[@:'ÿ'␂+*'␐x/'ÿ&;]
'. Push a non-null byte (46) to the stack
[ ] Loop until EOF
@: Input a byte (0xXY) and duplicate it
'ÿ'␂+ Push the bytes 255 and 2 to the stack, and add them together
* Multiply the inputted character by 0x101 (-> 0xXYXY)
'␐x Push the byte 16 to the stack and swap it below the multiplied character
/ Divide the character by 16 (-> 0xXYX)
'ÿ& Mask the character with 0xFF (-> 0xYX)
; Print the swapped character
```
[Answer]
# [J-uby](https://github.com/cyoce/J-uby), 26 bytes
```
~:unpack&'H*'|~:pack&'h*'
```
[Try it online!](https://tio.run/##y9ItTar8n6Zgq/C/zqo0ryAxOVtN3UNLvabOCsLO0FJX@F9QWlKskKanoZSSmlSarqTJBRdISk5B5hoZmyBzi5OLUsuRBTD0O7m6uiHzzcPNzMLMzZGFYpSUVVTV1IFGm5qZOzm7uLq5BwWHhIaFA@1OTUsvKi4pLQNZwvUfAA "J-uby – Try It Online")
packing and unpacking turns out to be the same length as the optimal ruby solution.
# [J-uby](https://github.com/cyoce/J-uby), 37 bytes
```
:bytes|:*&(:*&257|~:>>&4)|~:pack&'c*'
```
[Try it online!](https://tio.run/##y9ItTar8n6Zgq/DfKqmyJLW4xkpLTQOIjUzNa@qs7OzUTDSBdEFicraaerKW@v@C0pJihTQ9DaWU1KTSdCVNLrhAUnIKMtfI2ASZW5xclFqOLICh38nV1Q2Zbx5uZhZmbo4sFKOkrKKqpg402tTM3MnZxdXNPSg4JDQsHGh3alp6UXFJaRnIEq7/AA "J-uby – Try It Online")
# [J-uby](https://github.com/cyoce/J-uby), 52 bytes
```
:bytes|:*&(~:to_s&16|:reverse|~:to_i&16)|~:pack&'c*'
```
[Try it online!](https://tio.run/##y9ItTar8n6Zgq/DfKqmyJLW4xkpLTaPOqiQ/vljN0KzGqii1LLWoOLUGLJQJFNIEMgsSk7PV1JO11P8XlJYUK6TpaSilpCaVpitpcsEFkpJTkLlGxibI3OLkotRyZAEM/U6urm7IfPNwM7Mwc3NkoRglZRVVNXWg0aZm5k7OLq5u7kHBIaFh4UC7U9PSi4pLSstAlnD9BwA "J-uby – Try It Online")
[Answer]
# Desmos, ~~105~~ 17 bytes
```
f(a)=mod(16a,255)
```
[Try it on Desmos!](https://www.desmos.com/calculator/upw0fjsnet)
Input and output are list of codepoints because Desmos doesn't support strings.
[Answer]
# ><>, ~~22~~ 21 bytes
-1 byte thanks to enigma
```
i:0(?;:a6+,$a6+:@%*+o
```
[E'—–GöæÆ–æV](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiaTowKD87OmE2KywkYTYrOkAlKitvIiwiaW5wdXQiOiJkZWJ1ZyIsInN0YWNrIjoiIiwibW9kZSI6Im51bWJlcnMifQ==)
## Explanation
`a6+` is 16. Basically, divide by 16, mod 16, `* 16`, sum up and print.
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 13 bytes
```
m{**b6<-b6L[}
```
[Try it online!](https://tio.run/##JY67DoMgAEV3vsKo1cTEpPEBi@ngc@nkA4ZuILrYQRAZjN9uDd3uucM9lyqxcLkqfh3rU@rrewQBhVlI4ftzXidZLspGKwtflgdrEMWJyU5cAMkE14YQ9LEGI6dqNlxjj@wgr6raoNv3I0AEQoyQKaRijEsJbMd9eP69mUKUF2VVN23XD5jcRj7NQm5q/wvsKG@puKUdk25S9uP2SKuBq/sSnnYfNWTWPw "Burlesque – Try It Online")
```
m{ # Map
** # Codepoint
b6 # To hex
<- # Reverse
b6 # From hex
L[ # To char
}
```
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/index.html), 17 bytes
```
16(@+⟜⌊÷˜+⊣×|)-⟜@
```
[Try it at BQN online REPL](https://mlochbaum.github.io/BQN/try.html#code=RmxpcF9oZXgg4oaQIDE2KEAr4p+c4oyKw7fLnCviiqPDl3wpLeKfnEAKRmxpcF9oZXggImRlYnVnIgo=)
```
-⟜@ # subtract null character (@) to get ASCII codepoints
16( ) # now, with this as right arg and 16 as left arg:
| # right arg (codepoints) modulo left arg (16)
× # multiplied by
⊣ # left arg (16)
+ # plus
÷˜ # right arg (codepoints) divided by left arg (16)
⟜⌊ # now use the floor of this
@+ # to add to null character (@) to get ASCII characters
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~70~~ ~~66~~ 60 bytes
*-7 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)*
```
main(t,v)char**v;{for(++v;t=**v;++*v)putchar(t>>4|t%16<<4);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z83MTNPo0SnTDM5I7FIS6vMujotv0hDW7vMusQWxNXW1irTLCgtAUlrlNjZmdSUqBqa2diYaFrX/v//PyU1qTQdAA "C (gcc) – Try It Online")
] |
[Question]
[
Your work is to recreate this piece of art:
```
_____
|
|
|
|
_____|
|
|
|
|
_____|
|
|
|
|
_____|
|
|
|
|
_____|
```
The answer must recreate this and print this as a result. All languages allowed, no direct printing of art, ofc, some level of manipulation is required. The answer with the least bytes wins.
*Closes on Thursday 6:30 AM UTC or so.*
The original thing was shown to me by my friend who did this with Java, he refused to show me the source code and now I'll dazzle him with the brilliance of other languages possibly. :D
**You cannot use any alternative character** *(makes it easier?).*
---
**Current leader board**
1. *Pyth* - 28 bytes - isaacg
2. *CJam* - 30 bytes - Runer112
3. *CJam* - 32 bytes - Martin Büttner
**Highest votes:** *C* - 73 bytes - Paul R
---
isaacg takes the crown for passing the Staircase Challenge with Pyth. Watch out for more challenges like these on PPCG!
[Answer]
# C, ~~86~~ ~~80~~ ~~76~~ ~~75~~ 73 bytes
```
c;main(i){for(i=21;i--;c='|')printf("%*s%c\n",i/5*6+5,i%5?"":"_____",c);}
```
[Answer]
# Java, ~~198~~ ~~158~~ ~~156~~ 146 bytes
This can probably be shortened a lot. As usual, suggestions are welcome.
```
void a(){String a="",b="_____",c=b;for(int i=-1;i<20;b=i%5<1?b.replace(c," "):i%5>3?b+" "+c:b)a=b+(++i>19?"":"|")+"\n"+a;System.out.print(a);}
```
Indented (kinda):
```
void a(){
String a="",b="_____",c=b;
for(int i=-1;i<20;b=i%5<1?b.replace(c," "):i%5>3?b+" "+c:b)
a=b+(++i>19?"":"|")+"\n"+a;
System.out.print(a);
}
```
Thanks Martin Büttner, Rainbolt, and Geobits.
[Answer]
**Brainfuck (1065 Bytes)**
It's not pretty, it's not short...but i'll optimize later on!
```
++++[->++++++++<]>........................
[->+++<]>-.....>++++++++++.[->+++<]>++....
...................-[->++++<]>.>++++++++++
.[->+++<]>++.......................-[->+++
+<]>.>++++++++++.[->+++<]>++..............
.........-[->++++<]>.>++++++++++.[->+++<]>
++.......................-[->++++<]>.>++++
++++++.[->+++<]>++..................[->+++
<]>-.....[->++++<]>.>++++++++++.[->+++<]>+
+.................-[->++++<]>.>++++++++++.
[->+++<]>++.................-[->++++<]>.>+
+++++++++.[->+++<]>++.................-[->
++++<]>.>++++++++++.[->+++<]>++...........
......-[->++++<]>.>++++++++++.[->+++<]>++.
...........[->+++<]>-.....[->++++<]>.>++++
++++++.[->+++<]>++...........-[->++++<]>.>
++++++++++.[->+++<]>++...........-[->++++<
]>.>++++++++++.[->+++<]>++...........-[->+
+++<]>.>++++++++++.[->+++<]>++...........-
[->++++<]>.>++++++++++.[->+++<]>++......[-
>+++<]>-.....[->++++<]>.>++++++++++.[->+++
<]>++.....-[->++++<]>.>++++++++++.[->+++<]
>++.....-[->++++<]>.>++++++++++.[->+++<]>+
+.....-[->++++<]>.>++++++++++.[->+++<]>++.
....-[->++++<]>.>++++++++++.[--->++<]>+++.
....[->++++<]>.
```
[Answer]
# CJam, ~~36~~ 30 bytes
[Try it online.](http://cjam.aditsu.net/#code=L%7B%7BS5*%5C%2B%7D%2FS'%7C5*%2B%5D'_5*%2B%7D5*1%3EzN*)
```
L{{S5*\+}/S'|5*+]'_5*+}5*1>zN*
```
My initial 36-byte solution generated the result in the output orientation. Despite my attempts to squeeze more bytes out of the algorithm, I couldn't. Then I saw [Martin's brilliant strategy](https://codegolf.stackexchange.com/a/47245/18144) of generating *columns* instead of rows and transposing the result. I realized that was probably a better approach, so I set off to create a transposition-based solution.
However, my approach to implementing that strategy varies quite a bit. Instead of generating full columns, I use an iterative solution that indents any already-generated "steps" and adds adds a new step at each iteration. So the first iteration of the main loop generates this:
```
|||||
_
_
_
_
_
```
The second iteration of the main loop indents the existing step and adds a new one after it:
```
|||||
_
_
_
_
_
|||||
_
_
_
_
_
```
And the full five iterations of the main loop generate this:
```
|||||
_
_
_
_
_
|||||
_
_
_
_
_
|||||
_
_
_
_
_
|||||
_
_
_
_
_
|||||
_
_
_
_
_
```
After this, all that needs to be done is eliminate the first line, which would otherwise become the unwanted riser for the bottom step, and transpose.
[Answer]
# Python 2, ~~80~~ ~~77~~ 74 bytes
```
n=24;exec"print' '*n+'_'*5+'|'*(n<24)+('\\n'+~-n*' '+'|')*4*(n>0);n-=6;"*5
```
Got rid of the double `exec` and fit everything into the one `print`!
[Answer]
# [Clip, 46](http://esolangs.org/wiki/Clip)
```
{:24S:5'_m[z{*4,:+5*6zS"|
":*6zS:5'_"|
"`}vR4`
```
## Explanation
```
{ .- Put everything in a list -.
:24S .- 24 spaces -.
:5'_ .- 5 underscores -.
m[z .- Map... -.
{ .- A list -.
*4 .- 4 of the following -.
, .- Append -.
:+5*6zS .- 5 + 6 * the iteration of spaces -.
"| .- A pipe and newline -.
"
:*6zS .- 6 * the iteration of spaces -.
:5'_ .- 5 underscores -.
"| .- A pipe and newline -.
"
` .- End list (per iteration -.
}vR4 .- The mapping is onto {3,2,1,0} -.
```
[Answer]
# CJam, ~~36~~ 32 bytes
```
{5*S*'_+a5*~_W<S+5'|*+}5/;]W%zN*
```
[Test it here.](http://cjam.aditsu.net/#code=%7B5*S*'_%2Ba5*~_W%3CS%2B5'%7C*%2B%7D5%2F%3B%5DW%25zN*)
I also tried using an explicit formula, but it's longer in CJam... maybe it helps someone else:
```
21,29,ff{_2$5/)6*(=@@6/5*=_++" |_|"=}W%N*
```
## Explanation
I found that the staircase can be built much more easily if you a) transpose the grid and b) reverse the lines:
```
_
_
_
_
_
|||||
_
_
_
_
_
|||||
_
_
_
_
_
|||||
_
_
_
_
_
|||||
_
_
_
_
_
```
So first I'm building that, then reverse, then transpose.
```
{ }5/ "For i in [0 .. 4].";
5*S*'_+ "Get a string of 5*i spaces and append _.";
a5*~ "Get five such lines.";
_W<S+ "Duplicate the last, remove the _, add a space.";
5'|*+ "Add 5 copies of |.";
; "The above creates a row too many, so discard the last one.";
]W%zN* "Wrap everything in an array, reverse, transpose, riffle
with newlines.";
```
[Answer]
# Python 2, 59
```
n=21
exec"n-=1;print n/5*6*' '+' _'[n%5<1]*5+'|'*(n<20);"*n
```
The 21 lines are indexed by `n` in `[20,19,...,1,0]`. First prints 6 spaces for each "step" we're up (minus 1), computed as `n/5*6`. Then, prints five spaces, except these are instead underscores for multiples of five. Finally, prints a vertical line, except for the top line `n=20`.
[Answer]
# JavaScript, ~~115~~ ~~107~~ ~~96~~ ~~94~~ ~~89~~ ~~87~~ 83 bytes
This is too long to win, but it's the first time I've come up with an answer on PCG.SE, and I'm kind of proud to have made something postable.
With some helpful syntactical advice I shortened the code significantly - even below the scrollbar threshold!
```
for(s='',y=22;--y;s+='\n')for(x=0;++x<29;)s+=6*~(~-y/5)-~x?4+5*~(x/6)+y?' ':'_':'|'
```
[Answer]
# ECMAScript 6, ~~142~~ ~~138~~ ~~129~~ 91 bytes
Special thanks to @edc65 for really reworking this.
```
a=o='',[for(x of!0+o)(o=(a+' |\n').repeat(4)+a+'_____|\n'+o,a+=' ')],a+'_____\n'+o
```
```
out.value=(a=o='',[for(x of!0+o)(o=(a+' |\n').repeat(4)+a+'_____|\n'+o,a+=' ')],a+'_____\n'+o)
```
```
textarea{
width:300px;
height:400px;
}
```
```
<textarea id="out";></textarea>
```
The logic of the original version check @edc65 comment for how it morphed.
```
((f,l,p)=> //variables
f(24)+l+p[1]+ //add the non pattern line
[0,1,2,3].map(b=>f(18-6*b)) //add the right number of spaces in front of the 4 steps
.map((a,b)=>f(4,a+f(5)+p) //the four repeating lines of the step
+a+l) //the landing line
.join(p)+p) //put it all together
((n,s=' ')=>s.repeat(n) //create an variable array of some character
,'_____','|\n') //string literals
```
[Answer]
# MATLAB, 68 bytes
I have the strong feeling MATLAB should be able to do better, but I can't think of a way.
```
p(1:5,6)='|';p(1,1:5)=95;w=blkdiag(p,p,p,p);w(21,25:29)=95;flipud(w)
```
Creates the stairs upside-down and flips it. My thaumometer broke because of all the magic constants around.
`'|'` is intentionally left as-is (instead of ascii codepoint) to initialize `p` and `w` as a char array.
[Answer]
# Ruby, 48
```
25.times{|i|puts" "*(4-i/6)*5+(i%6==0??_*5:?|)}
```
## Old approach, 68
```
4.times{|i|(?_*5+"
|"*5).each_line{|l|puts" "*(4-i)*5+l}}
puts"_"*5
```
[Answer]
# Pyth, ~~29~~ 28
```
V21++**6/-20N5d*5?d%N5\_<\|N
```
[Try it here.](https://pyth.herokuapp.com/)
A pretty straightforward solution, with the "append five spaces or five underscores" trick from @xnor's solution, but with the loop from 0 to 20, not 20 to 0.
[Answer]
# Julia, 83 bytes
```
for n=24:-6:0 print(" "^n*"_"^5*"|"^(n<24)*"\n"*(" "^(n>0?n-1:0)*"|\n"^(n>0))^4)end
```
In Julia, string concatenation is performed using the `*` operator and string repetition is performed using `^`.
[Answer]
# [><>](http://esolangs.org/wiki/Fish), ~~108~~ ~~104~~ 100 bytes
```
cc+::?v~'_____'o\/' 'o \
?:o'|'\' 'o1-30.o\v!?:-1<}:{oav!?:<4;!
-20.12^?(+cc:ooo/ \~1-'!|'o1. \~ao6
```
A simple ><> solution, using the same strategy as my [Python answer](https://codegolf.stackexchange.com/a/47254/21487). The main difference is that ><> doesn't have string multiplication (or even strings), so all of that is done with loops.
## Explanation
```
cc+ Push 24 (call this "n")
[outer loop]
[loop 1, print n spaces]
: Copy n (call this "i")
:? If i is not zero...
' 'o1-30. Print space, decrement i and go to start of loop 1
~'_____'ooooo Pop i and print five underscores
:cc+(? If n < 24...
'|'o Print a pipe
21. Otherwise skip pipe printing
[loop 2: print vertical parts of stairs]
?!; If n is zero, halt
4 Push 4 (call this "j")
?! If j is zero...
~ao6-20. Pop j, print a newline, minus 6 from n and go to start of outer loop
ao Print a newline
}:{ Copy n (call this "k")
[loop 3: print n-1 spaces]
1- Decrement k
:?! If k is zero...
~1-'!|'o1. Pop k, decrement j, print a pipe and go to start of loop 2
' 'o Otherwise print a space and go to start of loop 3
```
[Answer]
# Perl, 50
```
#!perl -l
print$"x6x(-$_/5),($_%5?$":_)x5,"|"x$|++for-20..0
```
Try [me](http://ideone.com/61qMXw).
[Answer]
# T-SQL, 276 bytes
```
declare @x int declare @y int declare @w varchar(30) declare @l char(5) set @l='_____' set @x=23 while @x > 4 begin set @w=replicate(' ',@x) set @y=0 if @x=23 print @w+' '+@l else print @w+' '+@l+'|' while @y < 4 begin set @y=1+@y print @w+'|' end set @x=@x-6 end print @l+'|'
```
[Answer]
# Visual FoxPro 9.0, 261 bytes
### n = Number of Steps
total of 175 characters, but had to output to file to display correctly - so minus 43 chars for file operations = 132 chars.
```
n=10
c=CHR(13)
f="st.t"
ERAS (f)
FOR i=n TO 1 STEP -1
p=(i-1)*6
=STRTO(PADL("_____",p+5)+IIF(i<n,"|","")+c+IIF(i>1,REPLI(PADL("|"+c,p+1),4),""),f,.t.)
?PADL("_____",p+5)+IIF(i<n,"|","")+c+IIF(i>1,REPLI(PADL("|"+c,p+1),4),"")
ENDFOR
MODI COMM (f)
```
**Note to answerer:** Byte count is for the absolute working source code, and the byte counter says that it's 261 bytes, so it is.
[Answer]
# Bash (+tac from coreutils): 110 bytes
This can be pasted directly into the terminal.
```
(n=;set {1..4};for i do echo "${n}_____|";n+=' ';for i do echo "$n|";done;n+=\ ;done;echo "${n}_____")|tac
```
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/64763/edit).
Closed 1 year ago.
[Improve this question](/posts/64763/edit)
Come November 1, Programming Puzzles and Code Golf will graduate, so in the next 11 months, we'll want to save some memories from when we were ungraduated.
Write a program that produces the PPCG favicon, seen below.
[](https://i.stack.imgur.com/6Tpou.png)
* The image must be at least 64x64 pixels.
* The blue must be the color #62B0DF. The background can be white or a light gray.
* The image need not be pixelated like it is here.
* Alternatively, create text (with dimensions at least 64x64 non-whitespace characters) using standard bright [ANSI color codes](https://en.wikipedia.org/wiki/ANSI_escape_code#) of Cyan and White.
* Built in images and importing the PPCG logo are not allowed.
---
This is code golf, so standard rules apply. Shortest code in bytes wins.
[Answer]
# Bash (OSX), ~~33~~ ~~27~~ ~~23~~ 18 Bytes
You heard the man, any way we like.
```
open http:yon.se/q
```
~~I am aware that this is a popularity contest. But hey, when you can code golf it, why not?~~
It is now a code golf. \o/ This was valid at the time of posting.
>
> [](https://i.stack.imgur.com/sxyCJ.png)
>
>
>
There was even an exception made for me at some point! But, as @AlexA. pointed out...
>
> "*You can use whatever methods you want (except loading the image, with the exception of VoteToClose's response)*" It isn't fair to allow exceptions for specific users/answers. - Alex A.
>
>
>
I agree with this, and, as of such, do not wish this to be picked as the answer. Doesn't mean I won't still try to golf it down more. ;)
Thanks to @ΚριτικσιΛίθος for shaving off 6 bytes with a fancy short URL!
Thanks to @ev3commander for shaving off ANOTHER 5 bytes with an even fancier, shorter URL!
Thanks to @kennytm for pointing out that I can reduce the protocol size *and* remove the quotes, saving me another 4 bytes!
[Answer]
# [BitShift](https://esolangs.org/wiki/BitShift), 2795 bytes
```
10100110010101101001010111001010110100101011100101011010010101110010101101001010111001010110100101011100101011010010101110010101101001010111001010110100101011100101011010010101110010101101111011101010000000110101001011010100011010100010101101010010101101010010101101010010101101010010101101010010101101010011010100101101010001101010010110101001100110010101111111001010111010100101011010100101011010100101011010100101011010100101011010100101011010100101011010100101011001010110100101011001100110101000000011010100010101101010010101101010010101101010010101101010010101101010010101101010010101101010010101101010011010100101101010011001100101011111110010101110101001010110101001010110101001010110101001010110101001010110101001010110101001010110101001010110010101101001010110011001101010000000110101000101011001010110100101011100101011101010010101101010011010100101101010001010110101001010110010101101001010111001010111010100110101001011010100110011001010111111100101011101010011010100010101101010011010100010101100101011101010010101100101011101010011010100010101101010010101101010011010100101101010011001100101011111110010101110101001101010010110101000110101000101011010100110101000101011010100101011010100110101000101011001010110100101011101010011010100101101010011001100101011111110010101110101001101010001010110101001010110101001101010001010110101001101010001010110010101110101001010110010101110101001101010010110101001100110010101111111001010111010100110101000101011010100101011010100101011001010110100101011101010010101101010011010100101101010001010110101001101010010110101001100110010101111111001010111010100101011010100101011010100101011010100101011010100101011010100101011010100101011010100101011001010110100101011001100110101000000011010100101101010001010110101001010110101001010110101001010110101001010110101001010110101001010110101001101010010110101000110101001000010001010111111100101011010010101110010101110101001010110101001010110101001010110101001010110101001010110101001010110010101101001010111001010110100101011001100110101000000011010100101101010001101010010110101000110101001011010100011010100101101010001101010001010110101001010110010101101001010111001010110100101011100101011010010101110010101101111011101010000000110101001011010100011010100101101010001101010010110101000110101001011010100011010100010101101010011010100101101010001101010010110101000110101001011010100011010100101101010011001100101011111110010101101001010111001010110100101011100101011010010101110010101101001010111001010111010100110101001011010100011010100101101010001101010010110101000110101001011010100011010100100001000101011111110010101101001010111001010110100101011100101011010010101110010101101001010111001010110100101011100101011010010101110010101101001010111001010110100101011100101011010010101110010101
```
This outputs
```
@@@@@@@@@@@@
@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@
@ @@@ @@@ @
@ @@ @ @@ @ @@@@
@ @@ @@@@ @ @
@ @@@@ @@ @ @@ @
@ @@@@@ @@@ @@
@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@
@@@@@@@@@@@@
@@@
@@
@
```
This is probably the shortest code with which you can actually still recognize the logo... I created a terrible language :(
Try it [here](https://dl.dropboxusercontent.com/u/10914578/Bitshift.html)
**Note**
This was submitted before the rules were changed, by the current rules this answer is invalid. I will leave it here to perhaps inspire people
[Answer]
# JavaScript
*Note: This answer was made before the rules were **significantly** changed so this answer is **not** competing.*
---
This prints in into the your browser console, through some crazy and awesome string processing.
I've made a shorter version of this but I can't seem to find it anywhere.
**Chrome/Firefox**
This version just doubles up on each pixel so it looks more proportional
```
var a = `<long_string_here>`;
console.log.apply(console, [].concat.apply( [Array(+a.split('\n')[1].split(' ')[1] ).join(' ').split(' ').map(function(l){return'%c█'.repeat(+a.split('\n')[1].split(' ')[0]).repeat(2)}).join('\n')], a.split`
`.slice(3).map(function(l){return [].concat.apply([], l.match(/\d+ \d+ \d+/g).map(function(l){return [l.replace(/(\d+) (\d+) (\d+)/,"color:rgb($1,$2,$3)"),l.replace(/(\d+) (\d+) (\d+)/,"color:rgb($1,$2,$3)")]}))})))
```
**Safari**
```
var a = `<long_string_here>`;
console.log.apply(console, [].concat.apply( [Array(+a.split('\n')[1].split(' ')[1] ).join(' ').split(' ').map(function(l){return'%c█'.repeat(+a.split('\n')[1].split(' ')[0])}).join('\n')], a.split`
`.slice(3).map(function(l){return l.match(/\d+ \d+ \d+/g).map(function(l){return l.replace(/(\d+) (\d+) (\d+)/,"color:rgb($1,$2,$3)")})})))
```
---
The `long_string_here` is an *ppm*, I wrote this script a while back to print an arbitrary image **to the console**.
---
How does this work? Well JavaScript has a feature in `console.log` where you can provide css to style the message.
I the unicode character `█` and color that the correct color, which is retrieved from the ppm.
---
To display any other image run: `convert my_img.png -resize 50x50 -trim -compress none -blur 1x2 -flatten -background white ppm:-`, then copy the output to `<long_string_here>`
### Full code
Because this is quite massive, I've put the full code in pastebins so you can run them
**Chrome/Firefox:** [pastebin](http://pastebin.com/raw.php?i=YyNJdfDk)
**Safari:** [pastebin](http://pastebin.com/raw.php?i=3RiRqbeH)
---
## Result
[](https://i.stack.imgur.com/fdM3s.png)
[Firefox Result](https://i.stack.imgur.com/OTMdd.png)
[Safari Result](https://i.stack.imgur.com/jSOhU.png)
[Answer]
# Ruby with Shoes
```
zoom = 10
Shoes.app(width: 19 * zoom, height: 18 * zoom) {
background white
stroke fill '#62B0DF'
rect 1 * zoom, 1 * zoom, 17 * zoom, 13 * zoom, 3 * zoom
skew 0, -45
rect 10 * zoom, 11 * zoom, 5 * zoom, 4 * zoom
stack(left: 1 * zoom, top: 3 * zoom) {
para('PCG').style size: (5.66 * zoom).to_i, weight: 700, stroke: white
}
}
```
Sample output:

[Answer]
## Javascript (ES2015), 199 bytes
*(+72 bytes of CSS)*
My code prints the logo into the `<body>` element of a page through some unicode sequences. Suggestions improving the code are welcome (especially for `0`-pads task)
>
> Demo (tested on MacOsX/Chrome 46): <http://codepen.io/anon/pen/EVBmKN?editors=011>
>
>
>
---
**Javascript**
(newlines inserted for readability)
```
f=l=>{for(l of[49155,0,0,0,29070,19024,29206,16978,16780,0,0,32769,49155,65311,
65343,65407].map(r=>(1e15+r.toString(2)).slice(-16)))document.body.innerText+=
[...l].map(b=>["▉", " "][b]).join``+"\n"}
```
**CSS**
```
*{letter-spacing:-.1em;font:1em/.96 arial;white-space:pre;color:#62B0DF}
```
---
**Result**
[](https://i.stack.imgur.com/fP8fn.png)
---
**Ungolfed and Explained**
If we consider the original 16x16 PCG icon originally posted, we could encode the information in a binary format.
E.g. the first line would be encoded as `1100 0000 0000 0011` where `[0, 1]` maps to `[blue, white]`. Every binary number can be easily stored in decimal format so `1100 0000 0000 0011` is `49155`. The array
```
[49155,0,0,0,29070,19024,29206,16978,16780,0,0,32769,49155,65311,65343,65407]
```
contains all the information (in decimal format) about each pixel color. Each element of the array represents a line to draw. Note that some lines are `0` (full-blue lines) or their length is less than `16` digits (a line starting with a blue pixel): then we need to right-pad these binary numbers
```
[...].map(r=>(1e15+r.toString(2)).slice(-16))
```
The `map` function add 15 zeroes to the left plus the binary number concatenated. Thus the result is sliced by `16` pixel to the left. Now the array is actually
```
0: "1100000000000011"
1: "0000000000000000"
2: "0000000000000000"
3: "0000000000000000"
4: "0111000110001110"
5: "0100101001010000"
6: "0111001000010110"
7: "0100001001010010"
8: "0100000110001100"
9: "0000000000000000"
10: "0000000000000000"
11: "1000000000000001"
12: "1100000000000011"
13: "1111111100011111"
14: "1111111100111111"
15: "1111111101111111"
```
Take a look closer at the digits above: we can almost see the PCG logo. :)
*Note that if we store this information in the array, we need to use 16x18 bytes (288 bytes). This approach requires instead 135 bytes*
The next step is draw each line. The construct
```
for(l of [...].map(...))
```
loop over the array `values` (ES6 feature) and we add to the body
```
document.body.innerText += [...l]
```
where `[...l`] represent the binary string as an array . E.g. the first line would be read as
```
["1", "1", "0", "0" ... , "0", "0", "1", "1"]
```
then again we use `map()` to transform each value:
```
b=>["▉", " "][b]
```
if the value is `0` then it becomes a `LEFT SEVEN EIGHTHS BLOCK (U+2589)` otherwise it is a space `EM SPACE (U+2003)`. In short this assignment
```
document.body.innerText += [...l].map(b=>["▉", " "][b]).join``+"\n"
```
converts each `0` or `1` either into a squared block or into a space: then the array is joined and, along with a trailing newline sequence, is appended to the body.
The CSS I've used fixes the `line-height` and the `letter-spacing` (I've tested on Chrome, so the result may slightly vary in other browsers)
[Answer]
# Brainfuck, 120148 bytes
### This answer is now non-competitive. This was before the rules were changed, and this has absolutely no hope of winning as code-golf.
Brainfuck code to output hex value of image. Very, very, long.
Here is a pastebin link, and the first couple lines.
<https://paste.ee/p/LtcCy>
```
+[--------->+<]>-.+.----.-----.++++.-[--->++++<]>+.>-[----->+<]>+.+++.-------.--[-->+++<]>-.+[--->++<]>++.[--->++++<]>+.-[---->+++<]>+.-[--->++++<]>+.-[---->+++<]>.[--->++++<]>+.-[---->+++<]>.......--[-->+++<]>-.[---->+++<]>+.+++++.-----.++++.----..+.---.--......+.++.---......+.+.--.++++++++.--------.++++++.------......----[-->+++<]>.---------.---------.--[-->+++<]>--.++.-[------>+<]>-.+.+++.---------....+.+++++++.------.+++.+.+++.-----.-.+.-.++.-----.++++.+++++.-----.-.+.-.-.--.+++++.-----.+++++++.-----.++++.[->++++++<]>++.--[------>+<]>...+++.--
```
[Answer]
# [Snap](http://snap.berkeley.edu/snapsource/snap.html#open:http://snap.berkeley.edu/snapsource/tools.xml), 16 blocks

Tell me if this is invalid.
[Answer]
# Javascript ES6, 461 bytes
I need to work on the compression more.
```
x.style.cssText='display:block;font:4px/2px monospace;color:#62B0DF',x.innerHTML=` 28
38
31
${a=`5
`.repeat(8)}6 a a 7
6 8 8 8 8 8 6
6 8 + 7 71
6 +9 6
6 a9 6
6 6a 8 1 6
698 + 6
6 7+ 1+ 7
${a} 31
38
3+
28
47
46
41+
41
48
4+`[r='replace'](/a/g,' 1')[r](/9/g,' 7 + ')[r](/8/g,'++')[r](/7/g,11)[r](/6/g,'1++')[r](/5/g,'31+')[r](/4/g,Array(18).join` `)[r](/3/g,21)[r](/2/g,11111111)[r](/1/g,'+++')
```
```
<pre id=x></pre>
```
[Answer]
# [Bubblegum](https://esolangs.org/wiki/Bubblegum), 175 bytes
One of the rare times Bubblegum is useful for [graphical-output](/questions/tagged/graphical-output "show questions tagged 'graphical-output'")!
Run in a terminal that supports ANSI escape codes.
```
0000000: e060 3e00 a75d 000d 97c4 b1da c813 35e1 .`>..]........5.
0000010: 9ebb 75d8 b95a ea28 a23d e9c6 5d80 7ce0 ..u..Z.(.=..].|.
0000020: 8d72 884f 2eb0 23f0 a6dc 406b 5724 9b78 .r.O..#...@kW$.x
0000030: 229d 11b7 29c8 9be6 7b76 26d4 f41a 69e0 "...)...{v&...i.
0000040: e626 1923 061a 07fc 4ca6 3cc9 f947 7760 .&.#....L.<..Gw`
0000050: 86df 1d86 37a8 6825 dd9d a3b4 a050 573c ....7.h%.....PW<
0000060: 7efa 920a 446d 98f8 eeb9 91f7 f912 ca3b ~...Dm.........;
0000070: 9360 ddba 3450 30ff cee0 fb32 31d1 06cd .`..4P0....21...
0000080: 0d46 2f2d 5371 896c 6bb0 5fb8 3d6d f096 .F/-Sq.lk._.=m..
0000090: 67e9 8cb8 f92f 9eaa 7d35 0914 a742 6315 g..../..}5...Bc.
00000a0: 1a62 f54d b969 b980 c832 8a3f 8c00 00 .b.M.i...2.?...
```
Reverse the hexdump with `xxd -r`
Here's a screenshot of output:
[](https://i.stack.imgur.com/aGYf1.png)
Note: On my Windows machine with the MinGW terminal, the Windows Python binary [doesn't output ANSI codes correctly](http://prntscr.com/97ogkg) so the above was `python <esolangs reference implementation>.py <infile> | cat` but it should work correctly on Linux machines.
[Answer]
## Javascript (ES6), 192 bytes
```
document.body.innerHTML='<svg><path fill=#62B0DF d="'+"m01Q0010L60Q7071L74Q7565L55L37L35L15Q0504z".split('').map(v=>v*20||v).join(" ")+'"/><text y=65 fill=#FFF style="font:38pt arial">\xa0PCG'
```
This takes a compressed version of a SVG D path. Spaces are removed, so all arguments have to be a single decimal, so any number is multiplied by 20 before being written to the actual svg.
Output:
[](https://i.stack.imgur.com/Fwk1A.png)
Demo: <https://jsfiddle.net/Luy6qj80/>
[Answer]
# [LibreLogo](https://help.libreoffice.org/Writer/LibreLogo_Toolbar#LibreLogo_programming_language), ~~122~~ ~~116~~ 115 bytes
>
> Using [Logo](https://en.wikipedia.org/wiki/Logo_(programming_language)) to create a [Logo](https://i.stack.imgur.com/6Tpou.png). Does this count as recursion?
>
>
>
**Code:**
```
fontsize 20 fontcolor [3]fontweight "bold pc [24]fc 6402271 bk 40 rt 45 fd 40 fill home rectangle[64,52,5]text "PCG
```
**Result:**
[](https://i.stack.imgur.com/kquCt.png)
**Explanation:**
```
fontsize 20 ; Font Size = 20pt
fontcolor [3] ; Font Color = white
fontweight "bold ; Font Weight = bold
pc [24] ; Pen Color = invisible
fc 6402271 ; Fill Color = #61B0DF
bk 40 ; Move Back 40pt
rt 45 ; Turn Clockwise 45 Degrees
fd 40 ; Move Forward 40pt
fill ; Close and Fill the Line Shape
home ; Reset Initial Turtle Settings and Position
rectangle[64,52,5] ; Draw a Rectangle with Rounded Corners
text "PCG ; Set Text of the Actual Drawing Object as "PCG"
```
**Previous Attempts:**
116 Bytes:
```
fontsize 20 fontcolor [3]fontweight "bold pc [24]fc 0x61b0df bk 40 rt 45 fd 40 fill home rectangle[64,52,5]text "PCG
```
122 Bytes:
```
ht fontsize 20 fontcolor [3]fontweight "bold pc [24]fc [97,176,223]bk 40 rt 45 fd 40 fill home rectangle[64,52,5]text "PCG
```
[Answer]
# JavaScript, 680 bytes
Well, I had this already finished for the original contest, which rules were changed drastically. This is definitely not the shortest code you can come up with. It was designed for the popularity contest and it creates the original favicon pixel by pixel. It has some more features, too. :)
```
f=c=>{x=(d=document).body.appendChild(d.createElement`canvas`).getContext`2d`;if(c.b)x.scale(4,4);x.fillStyle=c.m?'#2d2d2d':'#62b0df';x.fillRect(0,0,16,16);x.fillStyle='#fff';for(i=0;i<(w=[0,0,1,0,14,0,15,0,0,11,15,11,0,12,1,12,14,12,15,12,0,13,1,13,2,13,3,13,4,13,5,13,6,13,7,13,11,13,12,13,13,13,14,13,15,13,0,14,1,14,2,14,3,14,4,14,5,14,6,14,7,14,10,14,11,14,12,14,13,14,14,14,15,14,0,15,1,15,2,15,3,15,4,15,5,15,6,15,7,15,9,15,10,15,11,15,12,15,13,15,14,15,15,15,1,4,2,4,3,4,7,4,8,4,12,4,13,4,14,4,1,5,4,5,6,5,9,5,11,5,1,6,2,6,3,6,6,6,11,6,13,6,14,6,1,7,6,7,9,7,11,7,14,7,1,8,7,8,8,8,12,8,13,8,]).length;i++)(t=a=>setTimeout(_=>x.fillRect(w[a++],w[a++],1,1),(c.a||0)*i))(i++)}
```
You can call the function with up to three parameters:
```
f({});
f({m:true});
f({b:true});
f({a:50});
f({m:true,b:true,a:50});
```
`m` goes *meta* and changes the color accordingly. And if you find it to small, use `b` to supersize it from *16x16px* to *64x64px*. Finally `a` animates the logo, like it is engraved into a blue board. The value is the speed for each animation step.
**Ungolfed**
```
f=c=>{
x=(d=document).body.appendChild(d.createElement`canvas`).getContext`2d`;
if (c.b) x.scale(4,4);
x.fillStyle = c.m?'#2d2d2d':'#62b0df';
x.fillRect(0,0,16,16);
x.fillStyle='#fff';
for(i=0;i<(w=[0,0,1,0,14,0,15,0,0,11,15,11,0,12,1,12,14,12,15,12,0,13,1,13,2,13,3,13,4,13,5,13,6,13,7,13,11,13,12,13,13,13,14,13,15,13,0,14,1,14,2,14,3,14,4,14,5,14,6,14,7,14,10,14,11,14,12,14,13,14,14,14,15,14,0,15,1,15,2,15,3,15,4,15,5,15,6,15,7,15,9,15,10,15,11,15,12,15,13,15,14,15,15,15,1,4,2,4,3,4,7,4,8,4,12,4,13,4,14,4,1,5,4,5,6,5,9,5,11,5,1,6,2,6,3,6,6,6,11,6,13,6,14,6,1,7,6,7,9,7,11,7,14,7,1,8,7,8,8,8,12,8,13,8,]).length;i++)
(t=a=>setTimeout(_=>x.fillRect(w[a++],w[a++],1,1),(c.a||0)*i)
)(i++);
}
```
**Output**
*Default*

*Animated*

[Answer]
# Python 3, 10,069 bytes
Writes the hex from the original logo to a new file.
```
with open('test.png', 'w+b') as image_file:
for line in ['\x89PNG\r\n', '\x1a\n', '\x00\x00\x00\rIHDR\x00\x00\x00\x13\x00\x00\x00\x12\x08\x06\x00\x00\x00\xb9\x0c\xe5i\x00\x00\n', '\xa3iCCPICC Profile\x00\x00H\x89\x95\x97\x07T\x13\xe9\x16\xc7\xbf\x99I/\x94\x04"\x9d\xd0;R\x04\x02H\xaf\xa1\x08\xd2\xc1FH\x02\t%\x84@\x10\xb1#\xe2\n', '\xac\x05\x15\x91bAW)\n', "V@\xd6\x82\x88baQ\xec}A\x16\x01u],\xd8Py\x03<\xc2{\xef\xbc=\xef\xbc{\xce\x9d\xf9\x9d{\xee\xfc\xe7\xce7\xf3\x9d\xf3\x1f\x00(]\x1c\xb18\x15V\x00 M\x94%\t\xf3\xf3d\xc6\xc4\xc61\xf1\xbf\x03\x02\xc0\x00\x1ap\x02\xca\x1cn\xa6\xd8#44\x08\xfcm|\xbc\x07\xa0\x89\xf3m\x8b\t\xad\xbf\xef\xfb\xaf\xa1\xc8\xe3gr\x01\x80BQN\xe0er\xd3P>9\x91\\\xb1$\x0b\x00D\x80\xd6\xf5\x96f\x89'\xb8\x18e%\t: \xca{'8i\x8aONp\xc2\x14_\x99\xec\x89\x08\xf3B\xf9\t\x00\x04\n", "\x87#I\x02\x80<\x84\xd6\x99\xd9\xdc$T\x87B@\xd9J\xc4\x13\x8aPf\xa1\xec\xca\x15px(\xe7\xa0l\x9e\x96\x96>\xc1\x07P6N\xf8\x17\x9d\xa4\x7f\xd3L\x90ir8I2\x9ez\x96\xc9 x\x0b3\xc5\xa9\x9ce\xff\xe7r\xfc\xefHK\x95N\xdfC\x17M\x8a@\xe2\x1f6qF\xd7\xac&%=P\xc6\xa2\x84y!\xd3,\xe4M\xf6O\xb2@\xea\x1f9\xcd\xdcL\xaf\xb8i\xe6q\xbc\x03\xa7Y\x9a\x12\xe91\xcd\x1c\xc9\xcc\xb5\xc2,v\xc44K\xd2\xc3d\xfa\xfcL\x9fp\x99>\x9f\x1d$\x9b!u\x9e\x8c\x13\x85\xbe\xeci\xce\x15DDOs\xb60j\xde4g\xa6\x84\x07\xce\xf4x\xc9\xea\x12i\x98l\xe6D\x89\xaf\xec\x19\xd32gf\xe3rff\xc8\x12D\xf8\xcf\xcc\x16#\x9b\x81\xc7\xf7\xf6\x91\xd5E\x91\xb2~q\x96\xa7LS\x9c\x1a*\xeb\xe7\xa7\xfa\xc9\xea\x99\xd9\xe1\xb2k\xb3\xd0\x0fl\x9a\x939\x01\xa13:\xa1\xb2\xf5\x01^@\x08D\x80\x0f\xd2\x00'\x8b\x9f\x9351\xa8W\xbax\x99D\x98$\xc8bz\xa0;\x85\xcfd\x8b\xb8\x96\xe6L\x1b+k;\x00&\xf6\xdd\xd4k}\xcf\x98\xdcO\x10\xe3\xdaLm\xb91\x00\xeee\x00\xc053\xb5\xe8c\x00\x1cv\x07@\xf9\xecLM\xef;\x00t\xb4\xb7\xb5\x93+\x95dO\xd50\x13\x07, \x01y\xa0\x04T\x81\x16\xd0\x03\xc6\xc0\x02\xd8\x00{\xe0\x0c\xdc\x81\x0f\x08\x00! \x02\xc4\x82\xc5\x80\x0b\x04\xe8\xbc\x12\xb0\x14\xac\x00kA\x01(\x02[\xc0\x0eP\x0e\xf6\x80\xfd\xa0\x06\x1c\x01\xc7A38\x03.\x80\xcb\xe0:\xb8\t\xee\x82\xc7\xa0\x17\x0c\x80W`\x04|\x04c\x10\x04\xe1!*D\x87T!m\xc8\x002\x83l \x16\xe4\n", '\xf9@AP\x18\x14\x0b\xc5CI\x90\x08\x92B+\xa0uP\x11T\x02\x95C\xfb\xa0Z\xe8\x18t\x1a\xba\x00]\x85z\xa0\x87P\x1f4\x0c\xbd\x83\xbe\xc2\x08L\x81\x95`M\xd8\x10\x9e\r\xb3`\x0f8\x10\x8e\x80\x17\xc1Ip\x06\x9c\x0b\xe7\xc3\x9b\xe02\xb8\x1a>\x0c7\xc1\x17\xe0\xeb\xf0]\xb8\x17~\x05\x8f"\x00!#\x0cD\x07\xb1@X\x88\x17\x12\x82\xc4!\x89\x88\x04Y\x85\x14"\xa5H5\xd2\x80\xb4"\x9d\xc8m\xa4\x17y\x8d|\xc1\xe00t\x0c\x13c\x81q\xc6\xf8c"1\\L\x06f\x15\xa6\x18S\x8e\xa9\xc14a:0\xb71}\x98\x11\xcc\x0f,\x15\xab\x815\xc3:a\xd9\xd8\x18l\x12v)\xb6\x00[\x8a=\x88=\x85\xbd\x84\xbd\x8b\x1d\xc0~\xc4\xe1p\x0c\x9c\x11\xce\x01\xe7\x8f\x8b\xc5%\xe3\x96\xe3\x8aqU\xb8F\\\x1b\xae\x07\xd7\x8f\x1b\xc5\xe3\xf1\xaax3\xbc\x0b>\x04\xcf\xc1g\xe1\x0b\xf0\xbb\xf0\x87\xf1\xe7\xf1\xb7\xf0\x03\xf8\xcf\x042A\x9b`C\xf0%\xc4\x11D\x84<B)\xa1\x8ep\x8ep\x8b0H\x18#*\x10\r\x88N\xc4\x10"\x8f\xb8\x8c\xb8\x99x\x80\xd8J\xbcA\x1c \x8e\x91\x14IF$\x17R\x04)\x99\xb4\x96TFj ]"=!\xbd\'\x93\xc9\xbadG\xf2|\xb2\x90\xbc\x86\\F>J\xbeB\xee#\x7f\xa1\xd0(\xa6\x14/\xcaB\x8a\x94\xb2\x89r\x88\xd2FyHyO\xa5R\r\xa9\xee\xd48j\x16u\x13\xb5\x96z\x91\xfa\x8c\xfaY\x8e.g)\xc7\x96\xe3\xc9\xad\x96\xab\x90k\x92\xbb%\xf7F\x9e(o \xef!\xbfX>W\xbeT\xfe\x84\xfc\r\xf9\xd7\n', 'D\x05C\x05/\x05\x8e\xc2*\x85\n', '\x85\xd3\n', '\xf7\x15F\x15\xe9\x8a\xd6\x8a!\x8ai\x8a\xc5\x8au\x8aW\x15\x87hx\x9a!\xcd\x87\xc6\xa3\xe5\xd3\xf6\xd3.\xd2\xfa\xe9\x08]\x8f\xeeE\xe7\xd2\xd7\xd1\x0f\xd0/\xd1\x07\x94pJFJl\xa5d\xa5"\xa5#J\xddJ#\xca4\xe59\xcaQ\xca9\xca\x15\xcag\x95{\x19\x08\xc3\x90\xc1f\xa4263\x8e3\xee1\xbe\xce\xd2\x9c\xe51\x8b?k\xe3\xac\x86Y\xb7f}RQWqW\xe1\xab\x14\xaa4\xaa\xdcU\xf9\xaa\xcaT\xf5QMQ\xdd\xaa\xda\xac\xfaT\r\xa3f\xaa6_m\xa9\xdan\xb5Kj\xaf\xd5\x95\xd4\x9d\xd5\xb9\xea\x85\xea\xc7\xd5\x1fi\xc0\x1a\xa6\x1aa\x1a\xcb5\xf6kti\x8cjji\xfai\x8a5wi^\xd4|\xad\xc5\xd0r\xd7J\xd6\xda\xaeuNkX\x9b\xae\xed\xaa-\xd4\xde\xae}^\xfb%S\x99\xe9\xc1Le\x961;\x98#:\x1a:\xfe:R\x9d}:\xdd:c\xbaF\xba\x91\xbay\xba\x8d\xbaO\xf5Hz,\xbdD\xbd\xedz\xedz#\xfa\xda\xfa\xc1\xfa+\xf4\xeb\xf5\x1f\x19\x10\rX\x06\x02\x83\x9d\x06\x9d\x06\x9f\x0c\x8d\x0c\xa3\r7\x186\x1b\x0e\x19\xa9\x18\xb1\x8dr\x8d\xea\x8d\x9e\x18S\x8d\xdd\x8c3\x8c\xab\x8d\xef\x98\xe0LX&)&U&7MaS;S\x81i\x85\xe9\r3\xd8\xcc\xdeLhVe\xd6c\x8e5w4\x17\x99W\x9b\xdf\xb7\xa0XxXd[\xd4[\xf4Y2,\x83,\xf3,\x9b-\xdf\xcc\xd6\x9f\x1d7{\xeb\xec\xce\xd9?\xac\xec\xacR\xad\x0eX=\xb6\xa6Y\x07X\xe7Y\xb7Z\xbf\xb31\xb5\xe1\xdaT\xd8\xdc\xb1\xa5\xda\xfa\xda\xae\xb6m\xb1};\xc7l\x0e\x7f\xce\xee9\x0f\xec\xe8v\xc1v\x1b\xec\xda\xed\xbe\xdb;\xd8K\xec\x1b\xec\x87\x1d\xf4\x1d\xe2\x1d*\x1d\xee\xb3\x94X\xa1\xacb\xd6\x15G\xac\xa3\xa7\xe3j\xc73\x8e_\x9c\xec\x9d\xb2\x9c\x8e;\xfd\xe5l\xe1\x9c\xe2\\\xe7<4\xd7h.\x7f\xee\x81\xb9\xfd.\xba.\x1c\x97}.\xbd\xaeL\xd7x\xd7\xbd\xae\xbdn:n\x1c\xb7j\xb7\xe7\xeez\xee<\xf7\x83\xee\x83\x1e&\x1e\xc9\x1e\x87=\xdexZyJ<Oy~\xf2r\xf2Z\xe9\xd5\xe6\x8dx\xfby\x17zw\xfb\xd0|"}\xca}\x9e\xf9\xea\xfa&\xf9\xd6\xfb\x8e\xf8\xd9\xf9-\xf7k\xf3\xc7\xfa\x07\xfao\xf5\xbf\xcf\xd6ds\xd9\xb5\xec\x91\x00\x87\x80\x95\x01\x1d\x81\x94\xc0\xf0\xc0\xf2\xc0\xe7A\xa6A\x92\xa0\xd6`88 x[\xf0\x93y\x06\xf3D\xf3\x9aC@\x08;d[\xc8\xd3P\xa3\xd0\x8c\xd0_\xe7\xe3\xe6\x87\xce\xaf\x98\xff"\xcc:lEXg8=|Ix]\xf8\xc7\x08\xcf\x88\xcd\x11\x8f#\x8d#\xa5\x91\xedQ\xf2Q\x0b\xa3j\xa3>E{G\x97D\xf7\xc6\xcc\x8eY\x19s=V-V\x18\xdb\x12\x87\x8f\x8b\x8a;\x187\xba\xc0g\xc1\x8e\x05\x03\x0b\xed\x16\x16,\xbc\xb7\xc8hQ\xce\xa2\xab\x8b\xd5\x16\xa7.>\xbbD~\tg\xc9\x89xl|t|]\xfc7N\x08\xa7\x9a3\x9a\xc0N\xa8L\x18\xe1zqwr_\xf1\xdcy\xdby\xc3|\x17~\t\x7f0\xd1%\xb1$q(\xc9%i[\xd2\xb0\xc0MP*x-\xf4\x12\x96\x0b\xdf&\xfb\'\xefI\xfe\x94\x12\x92r(e<5:\xb51\x8d\x90\x16\x9fvZD\x13\xa5\x88:\xd2\xb5\xd2s\xd2{\xc4f\xe2\x02qo\x86S\xc6\x8e\x8c\x11I\xa0\xe4`&\x94\xb9(\xb3%K\t58]Rc\xe9zi_\xb6kvE\xf6\xe7\xa5QKO\xe4(\xe6\x88r\xba\x96\x99.\xdb\xb8l0\xd77\xf7\x97\xe5\x98\xe5\xdc\xe5\xed+tV\xac]\xd1\xb7\xd2c\xe5\xbeU\xd0\xaa\x84U\xed\xab\xf5V\xe7\xaf\x1eX\xe3\xb7\xa6f-im\xca\xda\xdf\xf2\xac\xf2J\xf2>\xac\x8b^\xd7\x9a\xaf\x99\xbf&\xbf\x7f\xbd\xdf\xfa\xfa\x02\xb9\x02I\xc1\xfd\r\xce\x1b\xf6\xfc\x84\xf9I\xf8S\xf7F\xdb\x8d\xbb6\xfe(\xe4\x15^+\xb2**-\xfaV\xcc-\xbe\xf6\xb3\xf5\xcfe?\x8foJ\xdc\xd4\xbd\xd9~\xf3\xee-\xb8-\xa2-\xf7\xb6\xbam\xad)Q,\xc9-\xe9\xdf\x16\xbc\xadi;s{\xe1\xf6\x0f;\x96\xec\xb8Z:\xa7t\xcfN\xd2N\xe9\xce\xde\xb2\xa0\xb2\x96]\xfa\xbb\xb6\xec\xfaV.(\xbf[\xe1Y\xd1X\xa9Q\xb9\xb1\xf2S\x15\xaf\xea\xd6n\xf7\xdd\r{4\xf7\x14\xed\xf9\xbaW\xb8\xf7\xc1>\xbf}M\xd5\x86\xd5\xa5\xfbq\xfb\xb3\xf7\xbf8\x10u\xa0\xf3\x17\xd6/\xb5\x07\xd5\x0e\x16\x1d\xfc~Ht\xa8\xb7&\xac\xa6\xa3\xd6\xa1\xb6\xb6N\xa3ns=\\/\xad\x1f>\xbc\xf0\xf0\xcd#\xdeGZ\x1a,\x1a\xf652\x1a\x8b\x8e\x82\xa3\xd2\xa3/\x8f\xc5\x1f\xbbw<\xf0x\xfb\t\xd6\x89\x86\x93\x06\'+O\xd1O\x156AM\xcb\x9aF\x9a\x05\xcd\xbd-\xb1-=\xa7\x03N\xb7\xb7:\xb7\x9e\xfa\xd5\xf2\xd7Cgt\xceT\x9cU>\xbb\xf9\x1c\xe9\\\xfe\xb9\xf1\xf3\xb9\xe7G\xdb\xc4m\xaf/$]\xe8o_\xd2\xfe\xf8b\xcc\xc5;\x1d\xf3;\xba/\x05^\xbar\xd9\xf7\xf2\xc5N\x8f\xce\xf3W\\\xae\x9c\xb9\xeat\xf5\xf45\xd6\xb5\xe6\xeb\xf6\xd7\x9b\xba\xec\xbaN\xfdf\xf7\xdb\xa9n\xfb\xee\xa6\x1b\x0e7Zn:\xdel\xed\x99\xdbs\xee\x96\xdb\xad\x0b\xb7\xbdo_\xbe\xc3\xbes\xfd\xee\xbc\xbb=\xf7"\xef=\xb8\xbf\xf0~\xef\x03\xde\x83\xa1\x87\xa9\x0f\xdf>\xca~4\xf6x\xcd\x13\xec\x93\xc2\xa7\n', 'OK\x9fi<\xab\xfe\xdd\xe4\xf7\xc6^\xfb\xde\xb3}\xde}]\xcf\xc3\x9f?\xee\xe7\xf6\xbf\xfa#\xf3\x8fo\x03\xf9/\xa8/J\x07\xb5\x07k\x87l\x86\xce\x0c\xfb\x0e\xdf|\xb9\xe0\xe5\xc0+\xf1\xab\xb1\xd7\x05\x7f*\xfeY\xf9\xc6\xf8\xcd\xc9\xbf\xdc\xff\xea\x1a\x89\x19\x19x+y;\xfe\xae\xf8\xbd\xea\xfbC\x1f\xe6|h\x1f\r\x1d}\xf61\xed\xe3\xd8\xa7\xc2\xcf\xaa\x9fk\xbe\xb0\xbet~\x8d\xfe:8\xb6\xf4\x1b\xfe[\xd9w\x93\xef\xad?\x02\x7f<\x19O\x1b\x1f\x17s$\x9cI+\x80\xa0\t\'&\x02\xf0\xee\x10\x00\xd4X\xd4+\xdc\x04\x80$7\xe5\x8b\'\x03\x9a\xf2\xf2\x93\x04\xfe\x8e\xa7\xbc\xf3d\xd8\x03\xb0\xbf\r\xf5"(\x06\xa0^\xa4j\r\x00\x06(\xd3\xd0\x9c\xb0E\x11\xee\x00\xb6\xb5\x95\xe5?#3\xd1\xd6fJ\x8b\x82\xbaK\xec\xe7\xf1\xf1\xf7\x9a\x00\xe0[\x01\xf8.\x19\x1f\x1f\xab\x1a\x1f\xff\x8e\xfao\xe4!\x00m\x19S~|"p\xe8_J\x89:\x0cUyv0\x13\xc1\x7f\xc6?\x00\xea\xa4\xff\x86H\x07*\xad\x00\x00\x01\x9biTXtXML:com.adobe.xmp\x00\x00\x00\x00\x00<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="XMP Core 5.4.0">\n', ' <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">\n', ' <rdf:Description rdf:about=""\n', ' xmlns:exif="http://ns.adobe.com/exif/1.0/">\n', ' <exif:PixelXDimension>19</exif:PixelXDimension>\n', ' <exif:PixelYDimension>18</exif:PixelYDimension>\n', ' </rdf:Description>\n', ' </rdf:RDF>\n', '</x:xmpmeta>\n', '\x92\xfc\xe9\xf6\x00\x00\x01\xdcIDAT8\x11\xad\x94\xdfM\x1cA\x0c\xc6?\xcf\xcc\xbe\x11@\xa9 u\xa0\x1c\xa2\x03\x8aH\x0b\x89\x94\x16\x82\xeeJ\xa0\x88T\x90\x874\x92\xe7D,\xdc\xf3\xee\x8c\xf9ya\xc2\xe9 \x12\x87\xe2\x95\xd6\xf3\xc7\xfe\xc6\x1e\x7fc\xbb\xbb\xbdu7W\xae\xae)\x15e\xb9Rn\x9a\xbdH6+M\xae6\x984I%\x9bfK\x12\xb6B\xbb5\x15g?\x99Z5\xc6\x8b\xfb\xa4Z\x92\xbe\xfc\x18u\x88\xacW\xa7\x80\x9aR\xe3\xb08\xfbf\xbb\xf5CA\xf6\x0f\xdc\x9c\xbfW\xf6\x16\x19\xd5\xfd\xbd\x83\xe7$\xaaVH\x93+\xfa\x0f\xc2=G\xa6\x1e\xf9"\xd7\x97\x1f\x16\x1d\xbfO\xdf\x7f\xfd\x1d\xf7\xf5\x97\xd6\xba-\xa5\x90G\x01Z\xa6:\x8f\xd2\x1d\x02 \xc6]\xc7v\x1fw\xdd}\x1et\xa2\xcaN\x9a\x94\xb7K\x18\x86t\xd0e\xf2\xf8\xdb_\xdb\xb5\r\x8a\xc0&\n', '\xe0\x0fiv\x90}\xa7\x0e\xd8\x9d\xfb|\xd7\xce=\xc3\xcb\x14<{\x8a\xac\x1bv\x1d\x0e\x1d\xa4;\xbf\xb4\x96\xa2\x88\xfcl\xbc\x19\xfd\xf3\xcfm\xf7\x7f\x93\xde\\\x1c\xa9R\xc8\xd2\xd2\xbf#{-rk\x03\xa4\x85\x1e\xaaI\xeb\x8f\'\xaf\xf5{f\xf7-|\t\xc8\xad*%\xee\xac\xc2\xde\xcd\xeap\xc0\xab\xf3\xd3x\x9aD\x14<\xcb\xb2\xdft\x8d<U\xd9@\x90\x00\x1b\x1d!\xca\xbc\x14\x19\x0e\xce\x0c\xbe\xee\xdc\xe9\xd5\xea\x1dl"\x00\x1f\x82\n', '\xf2\xb8x|\x88Me\x98]\x80\xaaE\xce\xf0\xc5(s\xe5\x13@\xf4&N}\x92\xf5\xea\x88\t\xb9\x10\xce\x90*\xfb\x94q\xc6>\xb8J\x8eeyM\xac\xe5\x16,6e\x98\x9chK\xd1\xb2\xc28\xee"d}v\xbc\x90(z\x9f\xe1\x14Y\x84\xa5\x91F\x99y\xe2t\r\xfb3\x8e\xd0\x8d-\xc0"\xf7\x16\xa4\xe1\x9d1\xa4\x19\xbaf\x80\x97\xce\xb2DOTX+s\xd9\x14N\x98Y#3\x0e\x8b\xfey\x0f\x08\xf5\xf5\xc8\xe0\xdd\\\x98\x00\x00\x00\x00IEND\xaeB`\x82']:
image_file.write(line)
```
[Answer]
# R, 189 bytes
```
image(t(matrix(as.integer(sapply(c(32736,28784,62968,62968,64504,65528,63736,63352,63359,64254,65532,63736,63352,62840,29936,32736),intToBits)[1:16,]),nr=16)),ax=F,col=c("white","#62B0DF"))
```
With indents for clarity:
```
image(t(matrix(as.integer(sapply(c(32736,28784,62968,62968,
64504,65528,63736,63352,
63359,64254,65532,63736,
63352,62840,29936,32736),
intToBits)[1:16,]),nr=16)),
ax=F,col=c("white","#62B0DF"))
```
I'm shamelessly stealing the method from an [old answer of mine](https://codegolf.stackexchange.com/a/19298/6741): I take the base-2 representation of 16 numbers, make it into a 16x16 matrix of 1s and 0s and plot it as is.
[](https://i.stack.imgur.com/kaJmL.png)
[Answer]
# [Google Blockly](https://blockly-games.appspot.com/turtle?lang=en&level=10), 140 blocks
[](https://i.stack.imgur.com/FsdwM.png)
Produces
[](https://i.stack.imgur.com/SV2Gm.png)
Will add an explanation if requested. Try it [here](https://blockly-games.appspot.com/turtle?lang=en&level=10#vi76iz)
Suggestions to reduce the massive function on the left are welcome!
[Answer]
# Python 2, 211 bytes
```
from PIL import Image
I=Image.new('P',(16,16))
I.putdata(map(int,bin(eval('0xc003'+'0'*12+'718e4a5072164252418c'+'0'*8+'8001c003ff1fff3fff7f'))[2:]))
I.putpalette([111,174,221]+[255]*3)
I.resize((64,64)).show()
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 49 bytes
```
•(!o4¯ZD5µå¹p‹^Ô%í2\AO-Ö"w™ÈõžvlXäà`AF•bT„.@‡19ô»
```
[Try it online!](https://tio.run/nexus/05ab1e#AU4Asf//4oCiKCFvNMKvWkQ1wrXDpcK5cOKAuV7DlCXDrTJcQU8tw5Yid@KEosOIw7XFvnZsWMOkw6BgQUbigKJiVOKAni5A4oChMTnDtMK7//8 "05AB1E – TIO Nexus")
```
...@@@@@@@@@@@@....
.@@@@@@@@@@@@@@@@..
.@@@@@@@@@@@@@@@@..
.@@@@@@@@@@@@@@@@..
.@...@@@..@@@...@..
.@.@@.@.@@.@.@@@@..
.@...@@.@@@@.@..@..
.@.@@@@.@@.@.@@.@..
.@.@@@@@..@@@..@@..
.@@@@@@@@@@@@@@@@..
..@@@@@@@@@@@@@@...
...@@@@@@@@@@@@....
.........@@@.......
.........@@........
.........@.........
```
[Answer]
# Excel VBA, ~~252~~ ~~246~~ ~~245~~ 237 Bytes
Saved 6 bytes thanks to Taylor Scott.
Saved another 8 bytes thanks to inspiration from Taylor Scott
```
Sub p()
Set s=Shapes.AddShape(106,0,0,99,82)
With s.TextEffect
.Text="PCG
.FontSize=56
.Alignment=2
End With
s.TextFrame2.WordWrap=0
s.Adjustments.Item(1)=.1
s.Adjustments.Item(2)=.9
s.Line.Visible=0
s.Fill.ForeColor.RGB=14659682
End Sub
```
The code must be run from a worksheet's code page and will add the shape to that worksheet. It's nothing fancy but it does directly use the rounded rectangular callout upon which the icon is based. (For `AddShape`, `106` corresponds to `msoShapeRoundedRectangularCallout`.)
[](https://i.stack.imgur.com/a8HuI.png)
Formatting doesn't add much but it does make it easier to read:
```
Sub p()
Set s = Shapes.AddShape(106, 0, 0, 99, 82)
With s.TextEffect
.Text = "PCG"
.FontSize = 56
.Alignment = 2
End With
s.TextFrame2.WordWrap = 0
s.Adjustments.Item(1) = 0.1
s.Adjustments.Item(2) = 0.9
s.Line.Visible = 0
s.Fill.ForeColor.RGB = 14659682
End Sub
```
There's also a one-line solution meant to be run in the immediate window that is 1 byte longer:
```
Set s=Sheet1.Shapes.AddShape(106,0,0,99,82):s.TextEffect.Text="PCG":s.TextEffect.FontSize=56:s.TextEffect.Alignment=2:s.TextFrame2.WordWrap=0:s.Adjustments.Item(1)=.1:s.Adjustments.Item(2)=.9:s.Line.Visible=0:s.Fill.ForeColor.RGB=14659682
```
[Answer]
# MATLAB, ~~153 150~~ 140 bytes
```
a=65535;imshow(imresize(dec2bin([16380,a,a,a,36465,46511,36329,48557,48755,a,a,32766,16380,32*[7 6 4]],16)-47,8,'n'),[1 1 1;0.39 0.69 0.88])
```
The code takes an array of 16bit numbers (sadly there is no way of encoding them that reduces the byte count apart from reading from a presaved binary file). EDIT: With a little bit of creativity in how the array is made, I've saved 3 bytes, and with a little bit more and an extra variable, I can save another 10 on top of that.
With this array, it is converted to a binary string where an ascii '1' represents blue and an ascii '0' is white. The array is 2D at this point because each of the 16 numbers becomes a 16 character string.
I subtract 47 to convert this into an array of 1's and 2's (needed for the next bit), where each element represents one pixel. Again this remains as 2D and is our image data.
The image is then scaled up by a factor of 8 using nearest neighbour to produce an image which is at least the required 64x64px minimum size - in fact it is 128x128 because somehow I divided 64 by 16 to get 8 >\_< (don't ask!).
Finally this is displayed using a colour map where any 1 becomes white and any 2 becomes the required #62B0DF shade of blue.
This is the output:
[](https://i.stack.imgur.com/SD0EX.png)
[Answer]
## Processing, 211 bytes
```
noStroke();int[]n={49155,0,173175182,1245866062,12674,-2147418112,-117456893,-16777985};for(int x=0;x<256;x++){if(((n[floor(x/32)]>>(x%32))&1)>0)fill(255);else fill(98,176,223);rect(4*(x%16),4*floor(x/16),4,4);}
```
Storing the pixels inside signed integers (seems to be the most efficient way, I'll maybe try 2^64 integers) and then printing them in a frame.
[](https://i.stack.imgur.com/TLFma.png)
[Answer]
# Swift (Playground), 599 Bytes
```
import UIKit;class P:UIView {var b=UIBezierPath();func a(x:CGFloat,y:CGFloat){b.addLineToPoint(CGPoint(x:x,y:y))};override func drawRect(rect:CGRect){UIColor(red:0.384,green:0.690,blue:0.875,alpha:1).setFill();UIBezierPath(roundedRect:CGRectMake(0,0,200,159),cornerRadius:45).fill();b.moveToPoint(CGPoint(x:102, y:146));a(102,y:200);a(157,y:146);a(102,y:146);b.closePath();b.fill();"PCG".drawInRect(CGRectMake(35,41,200,121),withAttributes:[NSFontAttributeName: UIFont(name:".AppleSystemUIFontBold",size: 64)!,NSForegroundColorAttributeName:UIColor.whiteColor()])}}
P(frame: CGRectMake(0,0,200,200))
```
I decided to give it a go, since drawing in Swift is pretty straightforward, and it's not usually golfed like this. Ended up loosing precious bytes with the text... Damn you `NSDescriptiveVariableNames`!
Here's how it looks in the playground:
[](https://i.stack.imgur.com/XYlYl.png)
I think I could golf it more by aliasing things like `CGRectMake`, grouping objects in the a function etc.
[Answer]
# PHP, 145 bytes, not competing
```
for(;$i<64;)echo strtr(sprintf("%016b\n",[49155,0,0,0,29070,19024,29206,16978,16780,0,0,32769,49155,65311,65343,65407][$i++/4]),["####"," "]);
```
I should use non-blank and colors instead, but I´m too tired atm.
Guess that will add 10 bytes or so to the count, maybe more.
[Answer]
# Excel VBA, 178 Bytes
Anonymous VBE Immediate window function that takes no input and outputs the PCG Favicon (exactly as in the prompt above) to the range
```
Cells.RowHeight=48:[C1:N13,A2:P11,B12:O12,I14:I16,J14:J15,K14].Interior.Color=&HDFB062:[B5:B9,C5:D5,C7:D7,E6,G6:G8,H5:I5,J6,J8,H9:I9,L6:L8,O7:O9,M5:O5,M9:N9,N7].Interior.Color=-1
```
[](https://i.stack.imgur.com/ANHrA.png)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 188 bytes
```
y;main(x){int d[]={16380,~0,~0,~0,36465,62893,38833,46525,52861,~0,~0,32766,16380,1792,768,256};for(;y<64;y++){for(x=0;x<16;)printf("\33[48;5;%dm%*s",(d[y/4]>>x++)&1?14:7,8,"");puts("");}}
```
[Try it online!](https://tio.run/##NY3dCoJAFIRfJYRizRO5f2fXjtqDmBehGF5oogaK2KubEsJczAfzMdnllWXLMlL1LGs2uFNZ94c8SaOJo7Q@fPdIVKgBhQ0kSGulhJWFBi0s8n0jDCL8RW4CAQYtCI0zFe@W0RiiotHz3GnDIfJpCDmS27TracGch5SJsqTpmFfHc@cAy5PxqtI4HlbpxO9c3QxYcByXmk/fsa3M87L8AA "C (gcc) – Try It Online")
Uses ANSI escape codes to print 128 horizontal and 64 vertical colored spaces.
[](https://i.stack.imgur.com/8167H.png)
*(Image resized.)*
[Answer]
## C++ with [SFML](https://www.sfml-dev.org/index.php), 607 bytes
```
#include<SFML\Graphics.hpp>
using namespace sf;using c=Color;using x=Vector2f;RenderWindow w(VideoMode(324,324),"");void p(){RectangleShape r({224.f,144.f});r.setFillColor(c(98,176,223));Vertex v[3]={x(162,324),x(243,224),x(162,224)};for(int i=0;i<3;++i)v[i].color=c(c(98,176,223));Font f;if(!f.loadFromFile("a.ttf"))return;Text t("PCG",f,150);t.setPosition(50,20);while(w.isOpen()){Event e;while(w.pollEvent(e))if(e.type==0)w.close();w.clear(c::White);for(int i=0;i<628;++i){r.setPosition(50+cos(float(i)/100.f)*50,50+sin(float(i)/100.f)*50);w.draw(r);}w.draw(v,3,PrimitiveType(3));w.draw(t);w.display();}}
```
Code that calls the function :
```
int main() {
w.setFramerateLimit(60);
w.setVerticalSyncEnabled(true);
p();
}
```
Requirements :
* You need to have a valid ttf file called `a.ttf` in the current directory where the executable is running, so it can load the fonts to display the text
* You need to have the corresponding SFML DLLs in the current directory where the executable is running
Result :
[](https://i.stack.imgur.com/TfNyw.jpg)
Explanations :
```
#include<SFML\Graphics.hpp>
using namespace sf;
using c=Color;
using x=Vector2f;
//Create the window that will display stuff. 324x324 dimensions
RenderWindow w(VideoMode(324,324),"");
void p(){
//Creation of the rectangle
RectangleShape r({224.f,144.f});
r.setFillColor(c(98,176,223)); //Logo Color wanted
//Vertex to draw a blue triangle
Vertex v[3]={x(162,324),x(243,224),x(162,224)};
for(int i=0;i<3;++i)
v[i].color=c(c(98,176,223));
//Creation an load of the font
Font f;
if(!f.loadFromFile("a.ttf"))
return;
//Creating the text object that will be used to draw the PCG text
Text t("PCG",f,150);
t.setPosition(50,20);
//Main loop, will run while the window is open
while(w.isOpen()){
Event e;
while(w.pollEvent(e))
//sf::Event::Close int value is 0
//It will be triggered if you click on the red cross, or press Alt+F4
if(e.type==0)
w.close();
//Clear the window in white
w.clear(c::White);
//6.28 = 2*PI, the number of radians that nearly equals 360 degrees
for(int i=0;i<628;++i){
//It draws 628 rectangles, the top left part of the rectangle will do a circle
//Same for every points of the rectangle
r.setPosition(50+cos(float(i)/100.f)*50,50+sin(float(i)/100.f)*50);
w.draw(r);
}
//sf::PrimitiveType::Triangle int value is 3
w.draw(v,3,PrimitiveType(3));
//Draw the text
w.draw(t);
w.display();
}
}
```
[Answer]
# tcl/tk, 113
```
grid [canvas .c]
.c cr o 2 2 66 48 -f #62B0DF
.c cr t 36 24 -te PCG -fi #FFF
.c cr p 30 66 30 47 44 47 -f #62B0DF
```
# Tcl/tk, 144
```
grid [canvas .c]
.c create oval 2 2 66 48 -fill #62B0DF
.c create text 36 24 -text PCG -fill #FFF
.c create poly 30 66 30 47 44 47 -fill #62B0DF
```
[](https://i.stack.imgur.com/tOZUk.png)
] |
[Question]
[
Given a string as an input (which can be any acceptable/convenient format in your language), implement pendulum encoding. The test cases are split into individual items (which aren't quoted) for a visually appealing explanation.
## How do I do that?
The current **iteration index** starts at `0`.
* If the iteration index is even, append the current item onto the output string.
* If the iteration index is odd, prepend the current item onto the output string.
## An example
```
The input is [a b c d e f g].
Note that the letters a-g are individual one-character strings, to prevent confusion from the iteration index.
N: the iteration index
N:0 Out: [a]
N:1 Out: [b a]
N:2 Out: [b a c]
N:3 Out: [d b a c]
N:4 Out: [d b a c e]
N:5 Out:[f d b a c e]
N:6 Out:[f d b a c e g]
```
The output should be `[f d b a c e g]`.
# Another example
```
The input is [u d l n u e m p].
N:0 Out: [u]
N:1 Out: [d u]
N:2 Out: [d u l]
N:3 Out: [n d u l]
N:4 Out: [n d u l u]
N:5 Out: [e n d u l u]
N:6 Out: [e n d u l u m]
N:7 Out:[p e n d u l u m]
```
## Test cases
[Here](https://tio.run/##lVLNaoQwEL77FHNZMBhl22OXLeToZdmjyxJK6o5LQKONkV767naibbQUSp1LyMz3MzMJ2lqZe4p9aXXnxjHq0NyGemjiq@QgOLwwSJ9BHKJV5fJRzMXcFyOg2IFun96tdhgLxpeUqeOvq66mw0cOFht4hOMR9l59B6Lz6llA@Ah@BXlBksD1Qq45JPDADgHp7ICzxtni3yLE9zLiW2QCToxltiJMtGLSKvaMUI3ShvYSIGHkZTWKv/KS3zjyit8lY/znDn4T5Lpb@AdBya2EuSW5hSA3OyjyIB@5JmT0KqfWpIPRb/RKDnuXlqpHqGzb0B@gZO@ycfwE)'s a sample program doing this encoding.
Take note that the characters in the string aren't always unique.
```
Your output *has* to be flattened.
[a,b,c,d,e,f,g] -> [f,d,b,a,c,e,g]
[] -> []
[a] -> [a]
[a,b,c,d] -> [d,b,a,c]
[a,b] -> [b,a]
[a,b,d] -> [b,a,d]
[a,b,a,c,b,c] -> [c,c,b,a,a,b]
[a,a,b,b,c,c] -> [c,b,a,a,b,c]
[u,d,l,n,u,e,m,p] -> [p,e,n,d,u,l,u,m]
```
[Answer]
# [Python 3](https://docs.python.org/3/), 29 bytes
```
lambda l:l[1::2][::-1]+l[::2]
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHHKifa0MrKKDbaykrXMFY7JxrE@V9QlJlXopGmoVSakpNXmppboKSpyQUXTExKTklNS8ciBhT6DwA "Python 3 – Try It Online")
**Input**: A sequence
**Output**: The pendulum encoding of that sequence
**How**
Consider the sequence `[0,1,2,3,4,5]`, whose pendulum encoding is `[5,3,1,0,2,4]`. We can see that all even indices ended up in order on the right, and all odd indices are in reversed order on the left.
* `l[1::2][::-1]` takes all odd indices and reverses them, e.g `[5,3,1]`
* `l[::2]` takes all even indices, e.g `[0,2,4]`
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), ~~24 21~~ 18 bytes
```
,[[<],[>],<]>>[.>]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fJzraJlYn2i5WxybWzi5azy72///SlJy80tTcAgA "brainfuck – Try It Online")
Thanks to Jo King for -3 bytes
```
,[ while input
[<], add new character to start of memory
[>], add new character to end of memory
< go one back, so the loop will run another time, moving the pointer to the start of memory
]
>>[.>] print memory
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 11 bytes
I promised you'll see at least one interesting answer :)
```
{⍵[⍋-\⍳≢⍵]}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR79boR73dujGPejc/6lwE5MbW/k971DbhUW/fo76pnv6PupoPrTd@1DYRyAsOcgaSIR6ewf/TFNQTk5JTUtPS1bmA7NKUnLzS1NwCdQA "APL (Dyalog Unicode) – Try It Online")
Uses [my own tip about `-\⍳`](https://codegolf.stackexchange.com/a/200637/78410), specifically the `⍋` variation, to generate the permutation needed for this challenge.
### How it works
`⍋-\⍳≢⍵` generates the target permutation for both even- and odd-length arrays:
```
⍋-\⍳≢⍵ ⍝ Length-7 vector | Length-8 vector
≢ ⍝ Length
⍝ 7 | 8
⍳ ⍝ Range (1..n)
⍝ 1 2 3 4 5 6 7 | 1 2 3 4 5 6 7 8
-\ ⍝ Cumulative alternating difference
⍝ 1 -1 2 -2 3 -3 4 | 1 -1 2 -2 3 -3 4 -4
⍋ ⍝ Grade up; permutation that will sort the input array
⍝ 6 4 2 1 3 5 7 | 8 6 4 2 1 3 5 7
```
Then `⍵[...]` arranges the original elements in that particular order.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ι`Rì
```
I/O as a list of characters.
[Try it online](https://tio.run/##yy9OTMpM/f//3M6EoMNr/v@PVipV0lFKAeIcIM4DYhA/FYhzgbhAKRYA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXR/3M7E4IOr/mv8z9aKTEpOSU1LV1JRwmIEkEYKACmwASEmZiclAxiJCYlJYMYpSk5eaWpuQVKsQA).
**Explanation:**
```
ι # Uninterleave the (implicit) input-list (into 2 parts by default for lists)
# i.e. ["u","d","l","n","u","e","m","p"] → [["u","l","u","m"],["d","n","e","p"]]
` # Push both parts separated to the stack
R # Reverse the second part
# → ["p","e","n","d"]
ì # And prepend it in front of the first
# → ["p","e","n","d","u","l","u","m"]
# (after which the result is output implicitly)
```
[Answer]
# JavaScript, 36 bytes
Feels like forever since I posted a JS solution here!
Input as an array, output as a string. Handling the empty array cost 3 bytes.
```
a=>a.reduce((x,y,z)=>z%2?y+x:x+y,"")
```
[Try it online!](https://tio.run/##XckxCoAgFADQvWMIgaL9oTHQDhINor8oTKMytMtbc@t7q771aY5lvxofLJZJFi2VhgNtNEhpElk8TKqnbvvMU5d4FoSwYoI/g0NwYaYTHQCAROt8xG0nI2PV7z8qLw)
[Answer]
# [Haskell](https://www.haskell.org/), ~~53~~ 37 bytes
```
([]#)
p#(a:b:s)=(b:p++[a])#s
p#l=p++l
```
[Try it online!](https://tio.run/##PYhBDoMgEEX3nmICLiC2FyDhJMhiQLHG0Uyk5@@oiXbz3vv/g3UZiaT4XkyI2jasDbrkqvUmOe66gNHqet7kz0Wy4ryBB97n7QstrMhQIChMWb0uDrfGx@Ufk4ryy4VwqvLOzAc "Haskell – Try It Online")
*Golfed 16 bytes thanks to @xnor*
[Answer]
# JavaScript (ES6), 42 bytes
A recursive function taking and returning a string.
```
f=([c,...a],k,o='')=>c?f(a,!k,k?c+o:o+c):o
```
[Try it online!](https://tio.run/##bc5BDoIwEIXhvaeoqymhlj0JchDjYjptiVI6RMTrI0SiIMz6y//mji/s6HFrn6fI1g2DL@SFlNYar6pWXAAkxZlKL1Eda1WXlHLOKSU5D8Sx4@B04Ep6CWjIOl@BSBKRZQK8NUiugsOfAzHf7DYAYQ1wK8YpWIhpaQfBKmP2Op/Mj9gdg2QIvobI4JjeMDSGlmxS26d6G2LvmhZm1rpo@9A3MLwB "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 thanks to [Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string)! (Use an initial value for reduction.)
```
;ṭƭƒ“
```
**[Try it online!](https://tio.run/##y0rNyan8/9/64c61x9Yem/SoYc7////VS1Ny8kpTcwvUAQ "Jelly – Try It Online")**
A full program that accepts a string and prints the result.
### How?
```
;ṭƭƒ“ - Main Link: list of characters, S
“ - get an empty list -> X
ƒ - reduce (X + S) using:
ƭ - tie - this groups the last n (default 2) links together and calls them cyclically:
; - concatenate (i.e. on the first, third, fifth,... we append)
ṭ - tack ( while on the second, fourth,... we prepend)
- implicit, smashing print to STDOUT
```
It could be considered a bug that Jelly barfs if the non-initialised version of reduce, `/`, is provided with an empty list. If that were 'fixed' this becomes just the four-byte `ṭ;ƭ/`.
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg), `-lp`, `-ir`, `-hd`, 15 bytes
```
⑫&(&⑶+&)⒁2%[⒂|&
```
[Try it online!](https://tio.run/##y05N////0cTVahpqjyZu01bTfDSp0Ug1@tGkphq1//9LU3LySlNzC/7r5gBxZtF/3YwUAA "Keg – Try It Online")
Purely a literal interpretation of the question plus a bit to ensure even length strings don't break.
## Explained
```
⑫&
```
First, we start by storing an empty string (pushed by `⑫`) in the register. This will be used as the final output, meaning that it needs to be initalised.
```
(&⑶+&)
```
Then, we enter the main for loop, which has the implicit condition `!` (take length of stack), as no explicit condition is provided. Now, there isn't anything on the stack at this point, so doing such a thing may seem pointless. But, by using the `-lp` flag (`--lengthpops`), we can have the `!` command take input if the stack is empty and push the length of the input. Also, the `-ir` (`--inputraw`) command ensures that the input word is taken as a series of letters, rather than a single string.
Inside the for loop, we push the contents of the register, reverse it (`⑶` reverses the top item of the stack) and then add whatever is next to the register. By doing so, we achieve the process behind the main algorithm, as consecutive letters are appended in the desired order.
```
⒁2%
```
At this point, the encoding has been fully completed. However, if the string is of an even length, the result will be reversed in the register. This requires us to push the length of the register (`⒁`) and check to see if it is even.
```
[⒂|&
```
If the register is of odd length, then we reverse the register and push it onto the stack (`⒂`). Otherwise, we simply push the register. `-hd` will then ensure that only the top item on the stack is printed.
[Answer]
# [Red](http://www.red-lang.org), 52 bytes
```
func[a][append reverse extract next a 2 extract a 2]
```
[Try it online!](https://tio.run/##PcgxDoAgDAXQnVM0HMHRY7gShko/xkQbUsF4e2Rie3kG6RskRJfXnpumwDFwKVAhwwt7QPiqcaqkA8S0zBiOvdiplTJ53pMgH97NaXJpw118/wE "Red – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 13 bytes
```
{~[:/:[:-/\#\
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/q@uirfStoq109WOUY/5rcilwpSZn5CukKagnJiWnpKalq8MFSlNy8kpTcwvgIoYKRgrGCiYKpgpm/wE "J – Try It Online")
A [J](http://jsoftware.com/) port of [Bubbler's APL solution](https://codegolf.stackexchange.com/a/201563/75681) - don't forget to upvote his answer!
```
#\ length of successive prefixes
-/\ cumulative alternating difference
[: function composition (caps the previous two verbs as a fork)
/: grade up
[: caps the fork
{~ use the list to index into the input (arguments reversed)
```
[Answer]
# [Perl 5](https://www.perl.org/) `+p`, 30 bytes
```
$\=--$|%2?$\.$_:$_.$\for/./g}{
```
[Try it online!](https://tio.run/##K0gtyjH9X5xYqaESo6mjUmNroKMSY6uunpmmEmP9H8jU1VWpUTWyV4nRU4m3UonXU4lJyy/S19NPr63@/z8xKTklNS2dqzQlJ680NbfgX35BSWZ@XvF/3YL/ur6megaGAA "Perl 5 – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `r`, 3 bytes
```
yṘJ
```
Uninterleave, reverse the second argument, merge b + a. Requires the r flag because there's no way to merge to my knowledge the other way around in one command.
[Try it Online!](https://lyxal.pythonanywhere.com?flags=r&code=y%E1%B9%98J&inputs=%5B%22a%22%2C%22b%22%2C%22c%22%2C%22d%22%2C%22e%22%2C%22f%22%2C%22g%22%5D&header=&footer=)
And flagless from @AaronMiller if the input is taken as a string:
## [Vyxal](https://github.com/Vyxal/Vyxal), 3 bytes
```
yṘp
```
Instead of J to merge, it prepends the element.
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=y%E1%B9%98p&inputs=udlnuemp&header=&footer=)
[Answer]
# [Zsh](https://www.zsh.org/), 26 bytes
```
for x y;a=($y $a $x)
<<<$a
```
[Try it online!](https://tio.run/##Lcq5DYAwDAXQPlO4sOR4BsIw5jAUXAIhJSxvHEHxin8812waOZruJ2QojbQRC6AAZg4pJRTjEBRICKhzvRvc6NRNVNf7bxe30ZfrY3UH2Qs "Zsh – Try It Online")
Input is a list of characters.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 20 bytes
```
*>^`.(.)?
$1
1,2,`.
```
[Try it online!](https://tio.run/##K0otycxLNPyvquGe8F/LLi5BT0NP055LxZDLUMdIJ0GP679eDFAmMSk5JTUtnas0JSevNDW3AAA "Retina – Try It Online") Link includes test suite. Explanation:
```
*>`
```
Execute this stage and immediately output the result without actually changing the working string.
```
^`
```
Before making the replacements, reverse their order.
```
.(.)?
$1
```
Keep only alternate characters.
```
1,2,`.
```
Delete alternate characters.
29 bytes as a reusable function:
```
,V,2,`
O^$`.((?=(..)*$))?
$#1
```
[Try it online!](https://tio.run/##K0otycxLNPyvquGe8F8nTMdIJ4HLP04lQU9Dw95WQ09PU0tFU9OeS0XZ8P//xKTklNS0dK7SlJy80tTcAgA "Retina – Try It Online") Link includes test cases. Explanation:
```
,V,2,`
```
Reverse all the characters except alternate characters.
```
O^$`.((?=(..)*$))?
$#1
```
Sort all characters by the parity of their position from the end, and then reverse the result. This means that alternate characters end up reversed and sorted to the start, leaving the remaining characters at the end, although technically having been reversed twice.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes
```
F²«P✂θιLθ²←↷⁴
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBw0hToZqL07c0pySzoCgzr0QjOCczOVWjUEchU0fBJzUvvSRDo1BTR8FIU9MaqC6/LFXDyic1rQTEC8gsyy8JykzPKNEwAfJr//8vTcnJK03NLfivW5YDAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F²«
```
Loop over the even and alternate characters.
```
P✂θιLθ²
```
Print the current set of characters.
```
←↷⁴
```
Prepare to print the alternate characters backwards.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 42 bytes
```
f=->s,*w{s ?f[s[2..-1],s[1],*w,s[0]]:w*''}
```
[Try it online!](https://tio.run/##KypNqvz/P81W165YR6u8uljBPi26ONpIT0/XMFanOBpIaJUDaYPYWKtyLXX12v8FpSXFCmnRSqUpOXmlqbkFSrFcMKHEpOSU1LR0DBGl2P8A "Ruby – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), 60 bytes
```
a->{var r="";for(var c:a)r=r.length()%2<1?r+c:c+r;return r;}
```
[Try it online!](https://tio.run/##VU5Nb4MwDL3zKywkJFhptO4IpdM0abedeux6MIHQMAjISZBQxW/PAu1lkr@e7efnFifct9Wvk/04kIHWY2aN7Jiwihs5KPaSB6MtO8mBd6g1fKNUcA8Anl1t0Pg0DbKC3s/isyGpmssVkBqdbKsAX89zR35DulzTx9IJROFwf7pPSEBFGOZioHgFPMOECmJdrRpzi5Po7Xh4px3P@I5yqo0lBZQvLt@uexZsNC@Z/dMFOM/a1D0brGGj1zQiDqPDq87gJ4y0dxWmKyMFwXAcuzn2gJnh0//5QYRznCTJQ2UJVl@cw5JXtWh8sZU@eFsT8pI7xLLk3NmqU7buxz8 "Java (JDK) – Try It Online")
## Alternative with Streams (62 bytes)
```
s->{int[]x={0};return s.reduce("",(a,b)->x[0]++%2<1?a+b:b+a);}
```
[Try it online!](https://tio.run/##bVBNb4MwDL33V1hISGHQqN2xtEy77LZTj10PTggoHYQoH1Writ@eBcpl2iLbz/Gz86xc8IrrS/0dZK8H4@AS79Q72dGXcvWn1njFnRzUv6R1RmA/UdqzTnLgHVoLnygVPFYAS9U6dBGug6yhjxw5OiNVezoDmtZmcyvAx6K0P86v7p9NVbEgNIdg19VDKnc63w6PzVga4bxRYKkRteeCJElBsGDZurqdNuc8T1/32zfM2Y7lmJVjKGedZjBArmgm8d2vDQCOd@tETwfvqI6qriFJut3YHXwlqY2ukmKaKKChqHV3J@/G4N0uH0EiRa3upIurZPE8BcfV5GMIyHgtmjYmcxpDtAmQMx4QGeM8@LpTXvT6Bw "Java (JDK) – Try It Online")
[Answer]
# [PHP](https://php.net/), ~~49~~ 48 bytes
```
for(;$a=$argv[++$i];)$s=$i%2?$s.$a:$a.$s;echo$s;
```
[Try it online!](https://tio.run/##DcVBCoAgFAXAy7ygEFy0zMSDRItPWQqVotT1X25mcsicXW4eqfQGYiHl/BalEFczoFrEbnSoGjJBNKrxW0gtki93XnzanjfzDw "PHP – Try It Online")
Again, not a really great score for PHP..
EDIT: Thanks for @OlivierGrégoire for saving 1 byte
[Answer]
# [Icon](https://github.com/gtownsend/icon), 62 bytes
```
procedure f(s)
t:=""
t[k:=|(0|1)\*s:k]:=pop(s)&\z
return t
end
```
[Try it online!](https://tio.run/##Xc2xCsMgEMbx3aeQG4qWDu0q@CRJhlTPImlULkqg5N3Ta8lQOvym@39cdDnte6Hs0DdCGdSiRTUWQNRuMnZT1@2m@/NipsHYkgvfT/1LENZGSVaByf/M5zEmpYWUcqVYUQXVwQgXuDPHPEMW2AMG/Ze2I3myxNqRz6x888@7Nw "Icon – Try It Online")
Takes the input as a list of chars.
# [Icon](https://github.com/gtownsend/icon), 66 bytes
```
procedure f(s)
t:=""
i:=1to*s&t[1-i%2:1-i%2]:=s[i]&\z
return t
end
```
[Try it online!](https://tio.run/##VcyxCsIwEIDhPU9xBCyJ4FDHQJ6kdqjJRQ7spVwuCL58pU66/MM3/JQq7/smNWHuglBc80ZDtNZQiKPWcxt0Gi90uoZv5xDbRPNwextB7cKgBjn/LNaF2HkDAC8hRVecXe4pY3lY/889P7njuh1@PD4 "Icon – Try It Online")
Takes the input as a string.
`procedure`, `return` and `end` add a lot to the byte count :)
[Icon](https://github.com/gtownsend/icon)'s `slice` operator `:` can be used to insert substrings into strings, if the the two indices are equal. This `s[1:1]:="a"` prepends `s` with "a"; `s[0:0]:="b"` appends "b" to `s`. I start with an empty string `t`, scan the input string `s` and use the odd/even index `i` with the slice operator to prepend/append to `t`.
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 93 bytes
```
public static string P(this string a){int z=0;return a.Aggregate("",(x,y)=>z++%2>0?y+x:x+y);}
```
[Try it online!](https://tio.run/##VY3BasMwEETv@goRKEg4NabHiqSEXFsw5JBDyEF1FlVgS@nuqtgJ/nbVqVto5rIMvHnb0GMTEXIiH5zcDcTQGfG/la8@fBohzum99Y0ktjydprVEssbo0HbiKuQt98hX9Cf5Zn1QxDj5Dkdp0ZGe2d/JT7YxUGyh3KNnmN6BuoGH6ljWSmszk2O@189SWSv@8PTXrL76wPKyqgwCJwzSlhvnEJxlUIvFUvXLQa/Wl6J4eFpXL0PRP/fFoM2Yx5zTqQ0JuvM3 "C# (.NET Core) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-P`](https://codegolf.meta.stackexchange.com/a/14339/), ~~7~~ ~~6~~ 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
I/O as a string.
```
ó ÔvÔ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVA&code=8yDUdtQ&input=InVkbG51ZW1wIg)
```
ó ÔvÔ :Implicit input of string > "udlnuemp"
ó :Uninterleave > ["ulum","dnep"]
Ô :Reverse > ["dnep","ulum"]
vÔ :Reverse first element > ["pend","ulum"]
:Implicitly join and output > "pendulum"
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 10 bytes
```
ORVDQUW:aa
```
[Try it online!](https://tio.run/##K8gs@P/fPyjMJTA03Cox8f///6UpOXmlqbkFAA "Pip – Try It Online")
-4 from DLosc.
## Similar solution, 14 bytes
```
UW:a(RVa@1).@a
```
[Try it online!](https://tio.run/##K8gs@P8/NNwqUSMoLNHBUFPPIfH///@lKTl5pam5Bf91CwA "Pip – Try It Online")
[Answer]
# Scala, 51 bytes
```
_./:(0,""){case(i->a,c)=>i+1->Seq(a+c,c+a)(i%2)}._2
```
[Try it online](https://scastie.scala-lang.org/PI3QQdwmQwC2ZuxLscF48Q)
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 26 bytes
```
s/(.)(.)/$\="$2$\$1";''/ge
```
[Try it online!](https://tio.run/##K0gtyjH9/79YX0NPE4j0VWJslVSMVGJUDJWs1dX101P//y9NyckrTc0t@JdfUJKZn1f8X7fgv66vqZ6BoQEA "Perl 5 – Try It Online")
[Answer]
# [Factor](https://factorcode.org/), 47 bytes
```
[ dup <odds> ""reverse-as swap <evens> append ]
```
[Try it online!](https://tio.run/##RY67DsIwDEX3fIWVnX4AIFbEwoKYEIOTuAi1TYOd8BDi20MkaOPF99wz2C3aOHI@Hnb77RI6Yk89CN0SeUtSU0PPyCgQmGJ8Bb76CCul3grKaDTWUXvRP/ov1FXOcQ61QmvsBGiMnSC53icaglaffAKXAqxH52RTDjDdiYUW5SF5YBGFfTEYAnkH5zyUUiLarslf "Factor – Try It Online")
## Explanation
It's a quotation (anonymous function) that takes a string from the data stack as input and leaves a string on the data stack as output. Assuming `"udlnuemp"` is on top of the data stack when this quotation is called...
* `dup` Duplicate whatever's on top of the stack.
**Stack:** `"udlnuemp" "udlnuemp"`
* `<odds>` Get the odd-indexed elements as a virtual sequence.
**Stack:** `"udlnuemp" T{ odds f "udlnuemp" }`
* `""` Push an empty string to the stack.
**Stack:** `"udlnuemp" T{ odds f "udlnuemp" } ""`
* `reverse-as` Take a source sequence and an exemplar sequence, and create a new sequence where the source sequence is reversed, but with the type of the exemplar sequence.
**Stack:** `"udlnuemp" "pend"`
* `swap` Swap the top two objects on the data stack.
**Stack:** `"pend" "udlnuemp"`
* `<evens>` Get the even-indexed elements as a virtual sequence.
**Stack:** `"pend" T{ evens f "udlnuemp" }`
* `append` Append two sequences. The result of `append` has the same type as the first argument.
**Stack:** `"pendulum"`
[Answer]
# [Rockstar](https://codewithrockstar.com/), ~~135~~ ~~125~~ ~~115~~ 96 bytes
```
listen to S
cut S
X's 0
O's ""
while S
let X be not X
let O be X and O+roll S or roll S+O
say O
```
[Try it here](https://codewithrockstar.com/online) (Code will need to be pasted in)
[Answer]
# [minigolf](https://github.com/jfioasd/minigolf/), 36 bytes
```
0,;i,unx2%!,,__a,n_nx2%,,__xo,;o_s,_
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iNzMvMz0_J23BgqWlJWm6FjdVDHSsM3VK8yqMVBV1dOLjE3Xy4kEcELsiX8c6P75YJx6iFqplwcpoAx1DHSMd41iIAAA)
## Explanation
```
0,; Start with an empty list
i, Foreach item in input:
u Store list to acc
n Push curr. item
x2%!, If iteration index is even:
,_ drop TOS
_ end
a Push acc
,n_ Dump acc onto stack
n Push curr. item
x2%, If iteration index is odd:
,_ drop TOS
_ end
xo Iteration index + 1
,;o Wrap last n items of stack into array
_ End foreach
s,_ (For some reason we have an extra implicit input,
so swap it upwards and drop it)
```
[Answer]
# [Python 2](https://docs.python.org/2/), 25 bytes
```
lambda s:s[-1::-2]+s[::2]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/PycxNyklUaHYqjha19DKStcoVrs42srKKPb/fwA "Python 2 – Try It Online")
Wrote this before I took a look at the submissions. The Python 3 answer is basically the same, but I improved the slicing to reverse the odd indices all in one.
But yeah, you can construct the pendulum encoding in two parts. First, the odd indices in reverse order. Second, the even indices in normal order.
[Answer]
# [Lua](https://www.lua.org/), 56 bytes
```
s=''(...):gsub('(.)(.?)',load'a,b=...s=b..s..a')print(s)
```
[Try it online!](https://tio.run/##DclhCoAwCEDh46gwPEAgnUVZRLDWyDy/@efxwRuhmS4AyMy0nR6GZULeCdp4tIM2k5ouVmFWoPVe80OnzIw@Zhz3@gE "Lua – Try It Online")
] |
[Question]
[
# Task
Given a string `s`, output a truthy value if the ASCII code of each letter is divisible by the length of `s`, and a falsey otherwise.
## Input/Output
Input is a nonempty string containing only ASCII `[32-126]`. Output is a standard truthy/falsey value. Note that you can switch the values, for example returning `0`/`False` if divisible and vice versa
## Test cases
```
Input Output
Hello False (72 101 108 108 111), 5
lol True (108 111 108), 3
Codegolf False (67 111 100 101 103 111 108 102), 8
A True (65), 1
nope False (110 111 112 101),4
8 8 True (56 32 32 56), 4
```
[Answer]
# [Befunge-98 (FBBI)](https://github.com/catseye/FBBI), 31 bytes
Output is via exit code, `1` for truthy, `0` for falsey cases.
```
#v~\1+
v>53p
>:#v_1q
^ >' %#@_
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tPj/X7msLsZQm6vMztS4gMvOSrks3rCQK05BwU5dQVXZIf7//5z8HAA "Befunge-98 (FBBI) – Try It Online")
---
Code running with inputs `lol` and `ab`:
[](https://i.stack.imgur.com/aZPF6.gif)
[](https://i.stack.imgur.com/N7R0s.gif)
small numbers represent literal byte values
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
ÇsgÖP
```
[Try it online!](https://tio.run/##yy9OTMpM/f//cHtx@uFpAf//5@TnAAA "05AB1E – Try It Online")
**Commented**
```
# implicit input "lol"
Ç # push ASCII value [108, 111, 108]
s # swap (with input) [108, 111, 108], "lol"
g # length [108, 111, 108], 3
Ö # is divisible? [1, 1, 1]
P # product 1
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~42~~ 39 bytes
```
(<1).sum.(map=<<flip(mod.fromEnum).length)
```
```
f s=sum[fromEnum c`mod`length s|c<-s]<1
```
3 fewer bytes thanks to ovs and xnor!
[Try it online!](https://tio.run/##BcExDoAgDADArzTE1cEdRl9hTCAIQmyLobD593pXgjwJUTWDOJl05N5o50kQPbXLY@J7FJAv2lVOuymFyuDg7ZUHLJDBYEOjPw "Haskell – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 4 bytes
```
tn\~
```
* For divisible strings the output is a vector containing only `1`s, which is [truthy](https://codegolf.stackexchange.com/a/95057/36398).
* Otherwise the output is a vector containing several `1`s and at least one `0`, which is [falsy](https://codegolf.stackexchange.com/a/95057/36398).
[Try it online!](https://tio.run/##y00syfn/vyQvpu7/f/Wc/Bx1AA) Or [verify all test cases](https://tio.run/##bY7BCsIwDIbve4pcpA5k5@FFRA8@gEcFx5atgdiUNUV20FevlSFMMJDwJ3z8@e@NcrrBt1bQSVVVD0uMsCbXkyNFYBFfJnWXV9oZHaPayWSWepiXLfgYLKilAEFHckPxNH3DIWOZQw74B7ku3qLriuMyBgXPzVScF7fZYIy4ARXwo3SxRWgc/OTMse@eqSX9mJbJnJBZTGFYOM@DdDgI91nuc9cAtXkD) including truthiness/falsihood test.
### How it works
```
t % Implicit input. Duplicate
n % Number of elements
\ % Modulo
~ % Negate. Implicit display
```
[Answer]
# JavaScript, 32 bytes
Ouput is reversed.
```
s=>Buffer(s).some(c=>c%s.length)
```
[Try it online!](https://tio.run/##bc0xDoMwEAXRPqdASEh2Edc0RiJpcg1kdg1o449YJ9c31Mjtm2K26T9pONY9PxNmKuyL@uH1Y6bDqHWKL5ngh9CpE0oxL7YEJIWQE0TDpv2QCFprHzcXSEXf1yVCuJLGiiXsVOG@afqLywk)
[Answer]
# [Rockstar](https://codewithrockstar.com/), ~~205~~ ~~192~~ ~~175~~ 162 bytes
Well, this was fun. Rockstar has no way of reading the length of a string directly, can't convert characters to codepoints and has no modulo operator. Surprised it worked out this short!
```
listen to S
cut S
X's0
D's0
while S at X
N's32
while N-127
cast N into C
if C is S at X
let M be N/S
turn down M
let D be+N-S*M
let N be+1
let X be+1
say not D
```
[Try it here](https://codewithrockstar.com/online) (Code will need to be pasted in)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~8~~ 7 bytes
-1 byte thanks to [@isaag](https://codegolf.stackexchange.com/users/20080/isaacg)
```
!%#lQCM
```
[Try it online!](https://tio.run/##K6gsyfj/X1FVOSfQ2ff/f/Wc/Bz1f/kFJZn5ecX/dVMA "Pyth – Try It Online")
```
!%#lQCM
! - logical negation of
# - filtering
CM - ascii values of input with
% lQ - func(x): return x % len(input)
```
[Answer]
# [PHP](https://php.net/), ~~56~~ 52 bytes
```
for(;$c=ord($argn[$i++]);$c%strlen($argn)?die(f):1);
```
[Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNKxVkm3zi1I0VBKL0vOiVTK1tWM1gWKqxSVFOal5EGFN@5TMVI00TStDTev//z1Sc3Ly/@UXlGTm5xX/13UDAA "PHP – Try It Online")
Output is reversed
Execution stops with `f` if any char is not divisible, or empty string (falsy in PHP) if all are divisible
EDIT: saved 4 bytes thanks to @640KB
[Answer]
# [Python 2](https://docs.python.org/2/), ~~41~~ 39 bytes
```
lambda s:all(ord(i)%len(s)<1for i in s)
```
[Try it online!](https://tio.run/##BcExDoAgDADAr3QxtKOORie/4YKBapNKCbD4@npXv/FYWZz30zW@V4rQ16iK1hIKTZoLdtpmtgYCUqCT1yZlIGM4LOXblAOR/w "Python 2 – Try It Online")
-2 bytes thanks to @ovs
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 11 bytes
```
{~+/(#x)!x}
```
[Try it online!](https://tio.run/##y9bNz/7/P82quk5bX0O5QlOxovZ/mrqGkkdqTk6@krWCUk5@Dohyzk9JTc/PSQOxHUFEXn5BKoi2UFCwUNL8DwA "K (oK) – Try It Online")
[Answer]
# [Rust](https://www.rust-lang.org/), 36 bytes
```
|s|s.iter().all(|x|1>x%s.len()as u8)
```
[Try it online!](https://tio.run/##jczBCoJAEMbxu0@xCsUslNBNKoQIpHeIiBVnRZjccnZBaH12W4OgS@Ech//36xzbUbfippoWpHhGIpxFtjB69pw2FjuQqSIC3/tN3i84JQypYuEyOU653EVDFIxpti@2omhheXbZRa7z0hjKQYffx1bM2NkrPmKoyjoGDWVyQiKTSLkSWhFj8H6VZOjd2c79y46mwtqQnmUe5oitueMsLRMi@waH8QU "Rust – Try It Online")
Takes the input as a `&[u8]`, outputs a `bool`.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~43~~ ~~37~~ ~~36~~ 32 bytes
```
->a{a.bytes.all?{|n|n%a.size<1}}
```
if only map could be used on strings..
-10 bytes from ovs.
-1 byte from Dingus.
[Try it online!](https://tio.run/##dVBLi8IwEL7PrxgKgkItndbWHqwiwrJ72svexEOKqQRCUvo4@Prt3Ym2uxcd8iWT4ZtvHnVXnPu8kCdl4MtUXYujfXctfwE@pdb2L/ohdCMHf7qMkEJiZE8QzXxMQFuN//ZTd2MCTgeaozM1hp09ypPV5QvxdDkww6FIPGYyIs7OYIv4rlCaMIPA2Eri6@aJwqcgPaaY@QvIELM3ekmKceROkrLwAnJpjgBl3s/X4iqC4tzKJhBab643czMTETTqIld0v/elrVGhMrj3Hqv0fI8XxPc4O7tbhmuVH9eDdwCssNyrA7gy/S8 "Ruby – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-pF`, 20 bytes
```
$_=!grep ord()%@F,@F
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3lYxvSi1QCG/KEVDU9XBTcfB7f9/j9ScnHyunPwcLuf8lNT0/Jw0LkeuvPyCVC6Lf/kFJZn5ecX/dXMK3AA "Perl 5 – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 40 bytes
```
{0}==##&@@ToCharacterCode@#~Mod~Tr[1^#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277v9qg1tZWWVnNwSEk3zkjsSgxuSS1yDk/JdVBuc43P6UupCjaME45Vu1/QFFmXomCvkO6gxZcXbG@Q7WSR2pOTr6SjlJOfg6QBGlNz89JAzIdgdhCQcECLFemVPv/PwA "Wolfram Language (Mathematica) – Try It Online")
thanks to @att for saving some bytes
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~54~~ 53 bytes
```
l;r;f(char*s){l=strlen(s);for(r=0;*s;)r|=*s++%l;l=r;}
```
[Try it online!](https://tio.run/##bY/BSsQwEIbv@xRjoJC0XayKsBIryCL4DraHpU3WQkxKJodi7bPXJK3dPRhIZjLzzz98zf7cNPOsuOWSNp8nmyIbVYnOKqEpMi6NpbYseIqc2Z8yxSxLFFel5dPcaQdfp05Ttht34E80ACfQ4UcNJYzkXShlSA5EGRXC0bTibJQM@Wt4tOlFiAeAA5l4tAm@YujF4EQbfWAscrjL4fKuymWhXZdVw9t9NTwd/X0Mnlf/h@AdRzwQ0LCh060Y/FzB1/QZsPsWRtK/3ex2LaRbhUOWRTWDBfkK23st6FFQ860feXx3Y/pPgF5wI6ljl3JvfUNSUpEEKwL7F0ha8Kn2cC4HzD259y0B63Vq2k3zLw "C (gcc) – Try It Online")
Returns falsey if the ASCII value of each character is divisible by the length of the input string or truthy otherwise.
### Explanation:
```
l;r;f(char*s){l=strlen(s);for(r=0;*s;)r|=*s++%l;l=r;}
l;r; // Declare 2 int variables
f( // Function f taking
char*s){ // string parameter s
l=strlen(s); // Store length of s in l
for( // Loop
r=0; // initialising r to 0
*s;) // until end of s
r|= // Bitwise or r with
*s // the ASCII value of the next
// character...
++ // Aside: push s pointer forward
%l; // ... mod the string length
l=r; // Return r (r will be 0
// iff every character was
// divisible by the length of the
// input string)
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), ~~8~~ 5 bytes
```
₌CLœΠ
```
Thanks @Lyxal for saving 3 bytes
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%82%8CCL%C5%93%CE%A0&inputs=%5B%22A%22%5D%20&header=&footer=)
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), ~~40~~ 33 bytes
```
$l=$args.Count
!($args|?{+$_%$l})
```
7 bytes saved thanks to *mazzy*
[Try it online!](https://tio.run/##K8gvTy0qzkjNydFNzi9K/a@SZlv9XyXHViWxKL1Yzzm/NK@ES1EDzKuxr9ZWiVdVyanV/F/LxaVSomCroOQB1JmvxKWmkqbgUAIVy8nPQRNxzk9JTc/PSUMTdkTj5@UXpKIJWSgoWMCE/gMA "PowerShell Core – Try It Online")
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 7 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?") ([SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set"))
Anonymous tacit prefix function
```
⍱≢|⎕UCS
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1Hvxkedi2oe9U0NdQ7@n/aobcKj3r5HXc2Petc86t1yaL3xo7aJQMngIGcgGeLhCVSj7pGak5OvzpWmnpOfA6Kc81NS0/Nz0kBsRxCRl1@QCqItFBQs1AE "APL (Dyalog Extended) – Try It Online")
`⍱` are not any of the following true (non-zero)?
`≢` the length
`|` divides (lit. division remainder when dividing)
`⎕UCS` the code points
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 25 bytes
```
a=>a.All(x=>x%a.Length<1)
```
[Try it online!](https://tio.run/##jZBBa8MwDIXP8a8QhUECa2DnNIFSGD10MLbDDmMHzVFdg2Jttjs6Sn975iSs9LBB30GgxyfpIR3mWjz1@2CdgefvEKmr1GVXbqz7rJRSDjsKH6gJVtKSEd6qo4IkzRgCPHoxHrvRmfxBIWK0Gr7EtvCA1uUh@rT79Q3Qm1CcuaPKMoD7vdOLibiFdxFuYJssqHusGyyXzPmhbg43WG7Imbhb3BV9ipZl2UpcEKbyxdtIKTHlw2A@WxOzzIqiOl8a9B/Nwlezv0@4emA5kn@iT4TtSF6sOqmpnvof "C# (.NET Core) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-e`](https://codegolf.meta.stackexchange.com/a/14339/), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
c vNÎÊ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWU&code=YyB2Ts7K&input=IkhlbGxvIg)
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 4 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
$h÷╓
```
Input as a list of characters.
[Try it online.](https://tio.run/##y00syUjPz0n7/18l4/D2R1Mn//8freShpKOUCsQ5UJyvFMsVDWWBREA8ZygvBao2HS6ro5QGVuEIJvOg4gVgdSARCyBLAYotlGIB)
**Explanation:**
```
$ # Get the codepoint of each character in the (implicit) input-list
h # Push the length of this list (without popping the list itself)
÷ # Check for each codepoint if it's divisible by this length
╓ # Pop and push the minimum of the list
# (after which the entire stack joined together is output implicitly as result)
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 12 bytes
```
!$+(A_Ma)%#a
```
[Try it online!](https://tio.run/##K8gs@P9fUUVbwzHeN1FTVTnx////efkFqQA "Pip – Try It Online")
## Explanation
```
!$+(A_Ma)%#a a → input
(A_Ma) Map a to Unicode/ASCII codepoints
%#a Modulo the list by it's length
$+ Sum up the remainders
! Not(returns 0 for any positive number, 1 for 0)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
LḍOP
```
[Try it online!](https://tio.run/##y0rNyan8/9/n4Y5e/4D////n5OcAAA "Jelly – Try It Online") or [Verify all cases!](https://tio.run/##y0rNyan8/9/n4Y5e/wCuw@2PmtZkPWrc/v//fyUPoFS@ko6CUk5@Dohyzk9JTc/PSQOxHUFEXn5BKoi2UFCwUAIA "Jelly – Try It Online")
**Commmented:** (At least I think it works like this)
```
P # product of ...
L # does the length
ḍ # ... divide ...
O # the char codes
```
[Answer]
# [R](https://www.r-project.org/), ~~39~~ 38 bytes
*Edit: -1byte thanks to the new rule that we can output TRUE for FALSE and FALSE for TRUE*
```
function(s)any(utf8ToInt(s)%%nchar(s))
```
[Try it online!](https://tio.run/##K/qfk5qXXpIRn5JZlpmSWhyfk1pSklpUbPs/rTQvuSQzP0@jWDMxr1KjtCTNIiTfM68EyFdVzUvOSCwCsjRxaNdQ8kjNyclX0uTCJZ@Tn4NH1jk/JTU9PycNjxJHPHJ5@QWpeKQtFBQs8EiHBkQ5BgDl/wMA "R – Try It Online")
Or try the [original 39-byte version](https://tio.run/##fcsxDoMwDAXQvaegSEjJDbJ0QF1gYyhLF4SIA5Esu0oM109zAbx9/fd/Kgi0y7H4eEUPeUEQgZRfJZy0SWQy2a6I5nlKcB8eSWrRdbQda6rJ3vxNOwAit/Zx58io6Js97IxBmfSKEf9AYdc0TuF5@vZT9fIH) that outputs TRUE for TRUE...
[Answer]
# [Python 3](https://docs.python.org/3/), ~~55~~ 52 bytes
```
N=input();print(not sum([ord(i)%len(N) for i in N]))
```
[Try it online!](https://tio.run/##BcExCoBQCADQq7gEOjdGV/AC0VaRYCrmHzq9vRdf3W5zN69iMQppiRQrNC94x4Ob54FCk56GTHB5goAY8E7Ura4/)
[Answer]
# [Zsh](https://www.zsh.org/), 31 bytes
```
for c (${(s::)1})((r||=#c%$#1))
```
[Try it online!](https://tio.run/##JcqxCsIwEAbg/X@Kg8ZyN3YtOIiLryExZ4TDk6QO1fjsKcXxg@9Tc1cW7uqFInH4cp1nmX7CXFo7DvEQhkmkC7CXSoxLMnOc/ZbuboqnvxJOMDe4KvRRIFAKlcaRUsxOerW6Umt/LeW95LVv "Zsh – Try It Online")
If we accept a "list of characters" as arguments, then we don't have to split the string for **19 bytes**:
```
for c;((r||=#c%$#))
```
[Try it online!](https://tio.run/##JchBCsJADAXQ/T9FoLUkV6i4EDdeQ8aJIwQjk7poHc8@Ii7f26J0ZeGuXintmWtrhyHtxkGkC/DrIMY5mzlOfs03N8XDnxlHmBtcFXqvECiNb455lvjQNFFOxUkvFiu19tdSX0tZ@xc "Zsh – Try It Online")
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 20 bytes
```
.,0@{(3$%@+\}3$*;!\;
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/X0/HwKFaw1hF1UE7ptZYRctaMcb6//@c/BwA "GolfScript – Try It Online")
This outputs 1 if the string is divisible and 0 if it isn't.
Let S be the string and L its length.
```
.,0@ # The stack from bottom up will be: L 0 S
{ }3$* # Execute this block L times
( # Separate first char from the string as a number
3$% # Previous number mod L
@+\ # Add result to the acumulator
; # Discard the ""
! # 1 iff the acumulator is 0
\; # Discard L
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 8 bytes
```
¬⊙θ﹪℅ιLθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMvv0TDMa9So1BHwTc/pTQnX8O/KCUzLzFHI1NTR8EnNS@9JEOjUBMErP//t1BQsOD6r1uWAwA "Charcoal – Try It Online") Link is to verbose version of code. Output is a Charcoal boolean, i.e. `-` for true, nothing for false. Explanation:
```
θ Input string
⊙ Is there a character where
ι Current character
℅ Ordinal
﹪ Modulo (i.e. is not divisible by)
θ Input string
L Length
¬ Boolean NOT
Implicitly print
```
`⬤θ¬﹪℅ιLθ` also works of course.
[Answer]
# [Factor](https://factorcode.org/), 62 bytes
```
: f ( s -- ? ) dup length [ mod ] curry [ + ] map-reduce 0 = ;
```
[Try it online!](https://tio.run/##JYy9asMwFIX3PsXBU0ux6WhsSggptF68lEwlgyJfOaKypF5JAVP67M4lHc7v8Bmlc@Dt@DmM7x0Us1oTvok9OSwqX@7WmOJ1tsEnJPop5DUlRKac18jWZ/QPw9jhzV5tsmdHdcpyz2nrYPCIhLrGDk@YSoQjPwv2C0uYcIIuzKusZ@mLijXTVDThBa/ot19UH@RcqFC54MQPYaI5OCN1L/IhkkQLtBX@hGL@KWi2Gw "Factor – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 81 bytes
```
(s)=>{var bs = ASCIIEncoding.ASCII.GetBytes(s);return bs.All(b=>b%s.Length==0);};
```
[Try it online!](https://tio.run/##ZY47C8IwFIX3/opQEFLQ4B5TaOur0M3BuYmXGgg3kpsWRPztNbSj4zl852FoZ8jO2XlEc6AYLA5bVnvvoMeSrUZLRztZstoBU2zmVKjyM/WBaUq6ujVte0LjHwkVixIXiPU7AiVUBohjwMSKyjmuVak3JDrAIT6V2hfyK@d1hll8jTE15ldwzucyazxSeiLuwUboLAL/O8SXUFHI@Qc "C# (Visual C# Interactive Compiler) – Try It Online")
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 27 26 bytes
```
s=>s.All(c=>c%s.Length<1);
```
[Try it online!](https://tio.run/##ZczLCsIwEIXhfZ9iKAgpaMB1m4AXRKF71zoMdWCYSCf19WOwS7eH/3xoOzQuzWVRHCzPrNMWjikJPTTCOtzszB82fgpBgGIhmj@IOAwRN@ZH0im/hn3Xl7UH1veSa9peSSS1fXNKapX095kzjazk/mT3O3UV@QI "C# (Visual C# Interactive Compiler) – Try It Online")
] |
[Question]
[
Given a list of Integers greater than zero, Sort each of the unique values in ascending order, then repeat the process on the remaining duplicate values and append.
Example:
```
[1,5,2,2,8,3,5,2,9] ==> [1,2,3,5,8,9,2,5,2]
[8,5] ==> [5,8]
[2,2,2] ==> [2,2,2]
```
[Answer]
# [Haskell](https://www.haskell.org/), 44 bytes
```
import Data.List
concat.transpose.group.sort
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRzyezuIQrzTY5Py85sUSvpCgxr7ggvzhVL70ov7RArxio7n9uYmaebUFRZl6JSlq0oY6pjhEQWugYg1mWsf8B "Haskell – Try It Online") (has an extra 2 bytes for `f=`)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
ṢŒgZF
```
[Try it online!](https://tio.run/##y0rNyan8///hzkVHJ6VHuf3//99Qx1THCAgtdIzBLEsA "Jelly – Try It Online")
A monadic link taking an unsorted list of integers and returning the list sorted as described.
## Explanation
```
·π¢ | Sort
Œg | Group runs of identical digits together
Z | Transpose
F | Flatten
```
[Answer]
# [Uiua](https://uiua.org), 11 [bytes](https://codegolf.stackexchange.com/a/265917/97916)
```
▽≠0.♭⍉⬚0⊕∘.
```
[Try it!](https://uiua.org/pad?src=0_6_1__ZiDihpAg4pa94omgMC7ima3ijYnirJow4oqV4oiYLgoKZiBbMSA1IDIgMiA4IDMgNSAyIDldCmYgWzEgMSAyIDIgMyAzXQpmIFsxIDIgMiAzIDMgM10KZiBbMV0KZiBbXQo=)
* `.` duplicate input
[](https://i.stack.imgur.com/DehWp.png)
* `⬚0⊕∘` group by identity, filling with zeros
[](https://i.stack.imgur.com/bXvrh.png)
* `‚çâ` transpose
[](https://i.stack.imgur.com/BqDLS.png)
* `‚ô≠` deshape
[](https://i.stack.imgur.com/gGsvW.png)
* `▽≠0.` keep non-zeros
[](https://i.stack.imgur.com/7kQ7k.png)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2), 28 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 3.5 bytes
```
sĠ∩f
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyI9IiwiIiwic8Sg4oipZiIsIiIsIlsxLDUsMiwyLDgsMyw1LDIsOV0iXQ==)
Bitstring:
```
1000100001100101100111101000
```
Port of the Uiua answer except without the 0 filling because it's not needed here. And they say having a fixed array model is a good thing! :p
## Explained
```
sĠ∩f­⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁤‏‏​⁡⁠⁡‌­
s # ‎⁡Sort the input
Ġ # ‎⁢Group on consecutive items
∩ # ‎⁣Transpose
f # ‎⁤and flatten
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-1`, 5 bytes
```
oOᵐůj
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpKuoVLsgqWlJWm6Fivy_R9unXB0fdaS4qTkYqjggpuK0YY6pjpGQGihYwxmWcZyRZvoACGQttAxjYWoBAA)
```
oOᵐůj
o Sort
O Find a set partition
ᵐů such that no part contains duplicates
j Join
```
The flag `-1` finds only the first solution.
The built-in `O` (`\setPartition`) uses the following algorithm (taken from [Curry's Combinatorial package](https://cpm.curry-lang.org/DOC/combinatorial-3.0.0/Combinatorial_curry.html#partition)), which ensures that the first solution is exactly the one we want:
```
partition :: [a] -> [[a]]
partition [] = []
partition (x:xs) = insert x (partition xs)
where insert e [] = [[e]]
insert e (y:ys) = ((e:y):ys) ? (y:insert e ys)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ĠZFị
```
A monadic Link that accepts a list and yields the "sorted" list.
**[Try it online!](https://tio.run/##y0rNyan8///Igii3h7u7////H22oY6pjBIQWOsZglmUsAA "Jelly – Try It Online")**
### How?
```
ĠZFị - Link: list A e.g. [8,8,8,3,7,7,3,3]
Ġ - Group indices of A by value [[4,7,8],[5,6],[1,2,3]]
Z - transpose [[4,5,1],[7,6,2],[8,3]]
F - flatten [4,5,1,7,6,2,8,3]
ị - index into A [3,7,8,3,7,8,3,8]
```
[Answer]
# [R](https://www.r-project.org/), 40 bytes
```
function(x)x[order(ave(!x,x,FUN=seq),x)]
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T6NCsyI6vygltUgjsSxVQ7FCp0LHLdTPtji1UFOnQjP2f5pGsoahjqmOERBa6BiDWZaamlxpGpl5JanpQH0Gmpr/AQ "R – Try It Online")
Shorter to use `order` than `split`.
# [R](https://www.r-project.org/), 55 bytes
```
function(x,y=sort(x))unlist(split(y,ave(!y,y,FUN=seq)))
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T6NCp9K2OL@oRKNCU7M0LyezuESjuCAns0SjUiexLFVDsVKnUsct1M@2OLVQU1Pzf5pGsoahjqmOERBa6BiDWZaamlxpGpl5JanpqUUaBkBVAA "R – Try It Online")
Noticed the `split` and `ave` characterization about 2 minutes after posting the longer answer below. Rough R equivalent to the Jelly answer.
# [R](https://www.r-project.org/), 73 bytes
```
f=function(x,o={},d=duplicated(x))'if'(sum(x),f(x[d],c(o,sort(x[!d]))),o)
```
[Try it online!](https://tio.run/##HccxCgIxEEbh3ltY7fwwha4IWuQkssWSyUhAM5JNICCePYblNd/LvavTmnyJlqixue@PxUn9vKJfSxBqwBR1oq2@h1mpPWRhT8ab5TLuKAsANnQlT2e@8jy68WXXHTgoxVTCM2Q6Af0P "R – Try It Online")
Naive implementation: sort unique values and recurse on remainder, appending as you go. Probably there's a shorter way.
[Answer]
# [Haskell](https://www.haskell.org/), ~~62~~ 52 bytes
```
import Data.List
f[]=[]
f x|z<-sort$nub x=z++f(x\\z)
```
[Try it online!](https://tio.run/##PYvLCoMwFET3@YpZdGHotVBbQcHsuuwfxCzSYmioL0wKIv67jfbBbM6cO/eh3bOq62WxTd8NHhft9eFqnWdGKiEVMxjnqYhdOO7a1w2jmPZ7E41lOfGl0baFQD/Y1kMaWAiBDjMiS@g4ihi@cv6uXeUUY38OP5IBkTxSSklIRqeNckUIMtlqRnmgoBWnbX2mkHXxga/NKF1d2P/MWhVXbHkD "Haskell – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 13 bytes
```
/:],.~1#.]=]\
```
[Try it online!](https://tio.run/##RYvBCsIwEETv/YqhHmrtdjdRhHYhEBQ8iQevNqdiES/@gOTXY1oUGQYeb5hnKrma4BQVCAaa2zKO1/MpiQbiaFccXBhSXVwOjLXoV9ReNP7cTRtxm0aG0nr3X0zL0ZB/axCOiy3u4@OFCZb2tM3paLdQD8wHm3EWHfWZ8pA@ "J – Try It Online")
* `/:` Sort by
* `1#.]=]\` Running sum count of each unique value *first*
* `,.~` Followed by
* `]` The original value
That is, we form pairs `<running count for this value, this value>` and sort by those pairs.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 45 bytes
Expects an `Uint16Array` filled with unsigned bytes and returns a `Buffer`.
```
a=>Buffer(a.map(o=v=>o[v]=o[v]+256|v).sort())
```
[Try it online!](https://tio.run/##HYnRCsIgGEZfxUt/MseMje3CQb1DV@KFLI3F8h9qRtC7m40PPg7nPEw2cQ7Llo4eb7Y4WYycLi/nbKCGP81GUWY5ocpa/u8guv6bgUcMiQKUGX3E1fIV71Rxzh319k2ui09tfw7BfKhqWcdE3cBOO40aQANpGlKT2OXAxko16vID "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // a[] = input Uint16Array
Buffer( // coerce to bytes:
a.map(o = // o = object to keep track of the number
// of times each value appears
v => // for each value v in a[]:
o[v] = // update o[v]:
o[v] + 256 // increment the high byte
// (no effect on the 1st iteration)
| v // use v as the low byte
) // end of map()
.sort() // sort the 16-bit values
) // end of Buffer()
```
---
# JavaScript (ES6), 51 bytes
Expects an `Uint16Array` filled with unsigned bytes and returns an array in the same format.
(This version could be updated to support larger integers at the cost of a few extra bytes.)
```
a=>a.map(o=v=>o[v]=o[v]+256|v).sort().map(v=>v&255)
```
[Try it online!](https://tio.run/##HYpBCsMgFESv4qootYZYDMnCQA/RVXDxSU1JSfxBxVLo3a2VgeExb16QIMx@PeLF4cPmRWfQI4gdDoo66RGnZPS/zlJ138REQB8pq4ei00kqxfKMLuBmxYZPulBn3@S@uth2N@/hQ6eWKy5Len6tNBjGGGkaUoysW8@HQsWZ/AM "JavaScript (Node.js) – Try It Online")
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 6 bytes
```
⍋∘⊒⊸⊏∧
```
[Try it online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4o2L4oiY4oqS4oq44oqP4oinCgoi8J2VqSLigL8iRvCdlaki4oi+4oi+4p+cKEbCqCnLmOKfqApbMSw1LDIsMiw4LDMsNSwyLDldLApbOCw1XSwKWzIsMl0sCuKfqDHin6ksCuKfqOKfqQrin6k=)
Or alternatively, [`∾⊒⊸⊔∘∧`](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oi+4oqS4oq44oqU4oiY4oinCgoi8J2VqSLigL8iRvCdlaki4oi+4oi+4p+cKEbCqCnLmOKfqApbMSw1LDIsMiw4LDMsNSwyLDldLApbOCw1XSwKWzIsMl0sCuKfqDHin6ksCuKfqOKfqQrin6k=)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 38 bytes
```
mO$`(.+)(?<=((^\1$)|.|¶)*)
$#3$*1,$&$*
```
[Try it online!](https://tio.run/##K0otycxL/B@coPM/118lQUNPW1PD3sZWQyMuxlBFs0av5tA2TS1NLhVlYxUtQx0VNRWt/4e2cen8N9Qx1TECQgsdYzDLEgA "Retina 0.8.2 – Try It Online") Takes input on separate lines but link splits on commas for convenience. Explanation: Sorts each value by a key made up of its occurrence count and value, expressed in unary.
@TwiNight's idea of sorting twice (since the sort is stable) saves 10 bytes, since the second sort doesn't have to guard against extraneous matches:
```
O#`
O#$`(.+)(?<=(¶?\1)+)
$#2
```
[Try it online!](https://tio.run/##K0otycxL/B@coPPfXzmBy19ZJUFDT1tTw97GVuPQNvsYQ01tTS4VZaP/h7Zx6fw31DHVMQJCCx1jMMsSAA "Retina 0.8.2 – Try It Online") Takes input on separate lines but link splits on commas for convenience.
Note that each link can be turned into a test suite by prefixing `%(` to the header.
[Answer]
# [BQN (CBQN)](https://mlochbaum.github.io/BQN/), 10 bytes
```
{‚àæ‚à߬®ùï©‚äîÀú‚äíùï©}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m704qTBvwdK0R20TqpeWlqTpWuyqftSx71HH8kMrPsyduvJR15TTcx51TQKxayEKbjrWcj1qWBSckV-u4KYQbahjqmMEhBY6xmCWZSyyrIkOEKKIWOiYxkIMWrAAQgMA)
[Answer]
# [Perl 5](https://www.perl.org/) `-MList::Util=uniq -a`, 59 bytes
```
map$t{$_}++,@F;1while@F=grep{say;--$t{$_}}sort{$a-$b}uniq@F
```
[Try it online!](https://tio.run/##K0gtyjH9/z83sUClpFolvlZbW8fBzdqwPCMzJ9XBzTa9KLWgujix0lpXFyJfW5xfBGQk6qok1ZbmZRY6uP3/b6hgqmAEhBYKxmCW5b/8gpLM/Lzi/7q@pnoGhgZA2iezuMTKKrQkM8cWpO2/biIA "Perl 5 – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~30~~ 26 bytes
```
N`
N$`(.+)(?<=(¶?\1)+)
$#2
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sKLUkMy9xwYKlpSVpuha7_RK4_FQSNPS0NTXsbWw1Dm2zjzHU1NbkUlE2WlKclFwMVbdgoyGXKZcREFpwGYNZlhAJAA)
Edit: -4 bytes thanks to Neil, by changing I/O format
Input and output are newline-separated decimals.
First sort normally, then sort (stably) again using the occurrence index
[Answer]
# [Ruby](https://www.ruby-lang.org/), 41 bytes
```
->l,*r{l.sort_by{|x|[(r<<x).count(x),x]}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5HR6uoOkevOL@oJD6psrqmoiZao8jGpkJTLzm/NK9Eo0JTpyK2tvZ/gUJadLShjqmOERBa6BiDWZaxsf8B "Ruby – Try It Online")
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 15 bytes
-2 bytes thanks to att.
```
{0~⍨,⍉⊣¨⌸⍵[⍋⍵]}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbhGqDuke9K3Qe9XY@6lp8aMWjnh2PerdGP@rtBlKxtUA1CoYKpgpGQGihYAxmWXKlAVlGQGwIoYF8ExAE0hYKpkDyUe8aHUMIDQA "APL (Dyalog Classic) – Try It Online")
**Explanation**
```
{0~⍨,⍉⊣¨⌸⍵[⍋⍵]}­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢⁡⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏‏​⁡⁠⁡‌⁣​‎⁠⁠⁠⁠‎⁡⁠⁣⁣‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁣⁢‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁣⁡​‎‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌­
{ } # ‎⁡dfn
⍵[⍋⍵] # ‎⁢sort
⊣¨⌸ # ‎⁢⁢groups into matrix, padding with zeros
⍉ # ‎⁢⁣transpose
, # ‎⁢⁤ravel (flatten)
0~⍨ # ‎⁣⁡remove zeros
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
I think that using a *dfn* rather than tacit is probably shorter here, since we are applying a bunch of monadic functions, and sorting is no shorter in tacit: `⊂∘⍋⌷⊢`.
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 73 bytes
```
$f={param($a)if($a){($g=$a|group).Name
&$f($g|%{,$_.Name*($_.Count-1)})}}
```
[Try it online!](https://tio.run/##bVDRaoMwFH3PVwTJ1mQkhToK9kEQpHvcxtq3MUrmUmvRxiWRDdRvd4midmMJhJNzzr33JKX8EkqfRJ6zRCrRdegY1iVXvMCIk@zozhqjNES8SZWsSrJ85IUAt8hKaXNTU3TomTtsQSyri2Er0pK27SIMoF0URthb0TX17Q7ofY82HoWW9PtrQDcWWdojc0VA185j1WvW9fAdPwACCGzgg1RbnpzY0/tZJAbWvR0ZoU3MtaAQie/SCuIDhhAdfquOmjDTZZ4ZuKALMLiU0FVurMc@d/b9FUfEzjK7zNWvz7u40kYWQ663aAjm1q5KEqE1dMVTOCY@x1bLvcoKTCb//t@007jR9jLkgHOmSdpefcE4sRdb0ILuBw "PowerShell Core – Try It Online")
Recursive function
Takes an array as a parameter
Returns an array
### Explanation
```
param($a) # The array in variable $a
if($a){...} # If the array is empty, do nothing, otherwise:
($g=$a|group).Name # Group the numbers in the array, store the groups in $g and return the unique elements sorted
$g|%{,$_.Name*($_.Count-1)} # From the groups, rebuild a list with one element less for each elements
&$f(...) # Recursively invoke the function on the rebuilt list
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes
```
o·∏Öz‚ÇÅc
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P//hjtaqR02Nyf//RxvqmOoYAaGFjjGYZRn7PwoA "Brachylog – Try It Online")
### Explanation
```
o Sort in ascending order
·∏Ö Group consecutive elements together
z‚ÇÅ Zip without cycling
c Concatenate
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes
```
UMθ⟦№…θκιι⟧W⁻θυ⊞υ⌊ιIEυ⊟ι
```
[Try it online!](https://tio.run/##HY29CgIxEIR7nyLlBtbCE0GxTH2QPqQI8SDB/JyXW8WnjxsZFob5lhkf3OarS73PblU1Z1ce8EJhVKWyg/r6tKhQ15E9JYo4zsr74RNiWgTMsVAbkKQUmloAQsFhzJQhSn7UWxxFru3AEwNrrmPEsHdjTnjBiXXF89/drO3Hd/oB "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
UMθ⟦№…θκιι⟧
```
Replace each value with a tuple of its occurrence index and value.
```
W⁻θυ⊞υ⌊ι
```
Sort the tuples into order.
```
IEυ⊟ι
```
Output the sorted values.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
{γζ˜þ
```
[Try it online.](https://tio.run/##yy9OTMpM/f@/@tzmc9tOzzm87///aEMdUx0jILTQMQazLGMB)
**Explanation:**
```
{ # Sort the (implicit) input-list
γ # Group it into equal adjacent values
ζ # Zip/transpose; swapping rows/columns,
# using " " implicitly as filler for unequal length lists
Àú # Flatten this list of lists
þ # Remove all " " by only keeping integers
# (after which the resulting list is output implicitly)
```
[Answer]
**APL(NARS), 23 chars**
```
{0≥≢⍵:⍬⋄a[⍋a],∇⍵∼⍦a←∪⍵}
```
use:
```
{0≥≢⍵:⍬⋄a[⍋a],∇⍵∼⍦a←∪⍵}1 5 2 2 8 3 5 2 9
┌9─────────────────┐
│ 1 2 3 5 8 9 2 5 2│
└~─────────────────┘
```
zilde has to be as void set for all the types
[Answer]
# APL+WIN, 30 bytes
Prompts for list of integers:
```
(,⍉⊃(⌈/¨⍴¨n)↑¨n←n⊂n←m[⍋m←⎕])~0
```
[Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tv4bOo97OR13NGo96OvQPrXjUu@XQijzNR20TgRRQVd6jriYQnRv9qLc7F8gAao/VrDP4D9TM9T@Ny1DBVMEICC0UjMEsSy4A "APL (Dyalog Classic) – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 62 bytes
```
a=>a.map(t=$=>[t[$]=9+t[$]||Array($)+t,$]).sort().map(x=>x[1])
```
[Try it online!](https://tio.run/##HYpBCoMwFESv4iKLfEwjWgpm8QM9R8jiY7W0WCNJEAvePcYwi3nMmy9tFAb/WeNtca8xTZgINckfrTwiQ22iYRZVfdVxPL2nP2dQR8EsyOB85FDOO@rdtBbS4Jbg5lHO7s0nblrxEF1OL@6FlAWomqbKoitTL1SmrGw6AQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ü Õcf
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=/CDVY2Y&input=WzEsNSwyLDIsOCwzLDUsMiw5XQotUQ)
```
ü Õcf :Implicit input of array
ü :Group & sort by value
Õ :Transpose
c :Flatten after
f : Filtering (to remove null values)
```
[Answer]
# [Haskell](https://www.haskell.org) + [hgl](https://www.gitlab.com/wheatwizard/haskell-golfing-library), 11 bytes
```
cx<tx<sr<bg
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8FN58zcgvyiEoXC0sSczLTM1BSFgKLUnNKUVC6oBJSroKEJF-FKs7KK9swridW1A1NLS0vSdC3WptkmV9iUVNgUF9kkpUPEbvrlJmbmKdgqpORzKSgUFCmoKKQpRBvqGMUicWNRpXQM0QUsgRhMQm1asABCAwA)
## Alternative
```
cx<tx<gr<sr
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8FN58zcgvyiEoXC0sSczLTM1BSFgKLUnNKUVC6oBJSroKEJF-FKs7KK9swridW1A1NLS0vSdC3WptkmV9iUVNikF9kUF0HEbvrlJmbmKdgqpORzKSgUFCmoKKQpRBvqGMUicWNRpXQM0QUsgRhMQm1asABCAwA)
## Explanation
* `bg` group the input into bags of equal elements
* `sr` sort the bags by value
* `tx` transpose
* `cx` concat
## Reflection
There are a couple of ways hgl could be improved I'm seeing here:
* There are two options for how to sort the bags in `bg`
+ Sort by how many items are in a bag
+ Sort by how early the earliest item appearsNeither of these is really helpful in this case. It might be nice to have a case function to sort by the value in the bags which would save us here, but really we need an option for the user to specify how to sort (wouldn't help here since `sr<bg` is already quite short).
* There's probably an argument to be made to have a combined `cx<tx`. I can see that being used in more places than just here.
[Answer]
# [Python](https://www.python.org), 53 bytes
```
f=lambda L:[*map(L.remove,x:={*L})]and sorted(x)+f(L)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3TdNscxJzk1ISFXysorVyEws0fPSKUnPzy1J1Kqxsq7V8ajVjE_NSFIrzi0pSUzQqNLXTNHw0oZot0_KLFCoUMvMUog11THWMgNBCxxjMsozVibbQMQWSIFGjWCsuhYKizLwSjTSgGZpcEANgrgAA)
Straight-forward method used by many other answers previously:
Pick, sort and remove uniques and start over.
[Answer]
# [Scala 3](https://www.scala-lang.org/), 118 bytes
A Port of [@matteo\_c's Haskell answer](https://codegolf.stackexchange.com/a/268516/110802) in Scala.
---
Golfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=XVFNTwIxEI1XfsW48dCGsokgCWB2E7yZ-HHQeCGE1N2u1CzddTuLEMIv8cJFL_4i_DXOdoGISdP2zby-eZ35-LKRTGXne-S1TPYuC-ONt_3s-VVFCLdSG1ALVCa2MMxzWDUA5jKFZMAe1Nvo2uA4CPc3DgF8lpi0etv5BGYSo-kqklbBnU6DkLZLhxZBuPBtVqCK_Vhb1CbCZjNhh-BLkZX51ZLpWBnUuOT-TOZPMi2VZRMfpU65P3fQT1KJ5M7HjEzwdV3950TXLlFZrEpaMnZDlRi5B2Duei6gK6DtVk9AZw_7XABpVfn2Pkz5voMVhXPxR-ZCQLXo0RE84tDz7p5QqR1lXefYLr0DnNK8QdvhA36SFUpGU1iB6yHTJi9R0GxympOK70skTAMInbK0VhXIkppG4eAfU4D1HkkcEuqmioHkwXEHcOZOr_KwrjzkhTaYGuYN07qjFvJKPz4lzq7jm019_gI)
```
_ match{case Nil=>Nil;case x=>x.sorted.distinct++f(x.sorted.groupBy(identity).mapValues(_.tail).values.flatten.toSeq)}
```
Ungolfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=ZZLNSgMxEMfBY59iXDwkuF2wtaCFChU8CH5cxEspEnezGkmzy2a2tkifxEsvevHg-_g0TrK7dWshkMzML_9kPt4_bSy06H9Ngq7JXkVhgun6o8S0e_Kz9509vsgY4VooA3KB0iQWxnkObx2ARKaQMm1xCFfK4uTS4JS3zjACCsJMYPzsLwDEwkq4URpGZ2778y3I4y2AudBgswJlQgKLqDq2YgnpKxPjhZYzadASVTFRE2nBT0VW5jLZZX3gfMlUQn6FSx7NRH4vdCkte4hQKM2juTejVAukzCPMXGq1-M4vDg-pGP-e4wSvOp3qKygtulzdJ5wQ80rMH49CGITQ8-skhH5jnvIQGqDX-Ak49aZjOA9bOschuNXcaswthq4PGsCpbUV941gdrg2XBXdZbDKI0qyQwnW16h5TJi8xpAnJaVpkclsi2bzpqbBWFsjSCiP36B8Zgg3uSBxSqjv1neTBs0M48HuwqWReKIPasGCsq5JayJ1-sk_MqprbenzX9f4L)
```
object Main extends App {
def f(lst: List[Int]): List[Int] = lst match {
case Nil => Nil
case x =>
val sorted = x.sorted
val distinctElements = sorted.distinct
val groupedElements = sorted.groupBy(identity).mapValues(_.tail).values.flatten.toList
distinctElements ++ f(groupedElements)
}
val testcases = List(
(List(1, 5, 2, 2, 8, 3, 5, 2, 9), List(1, 2, 3, 5, 8, 9, 2, 5, 2)),
(List(4, 4, 4), List(4, 4, 4)),
(List(8, 5), List(5, 8)),
(List[Int](), List[Int]())
)
testcases.foreach { case (input, expectedOutput) =>
assert(f(input) == expectedOutput, s"Test failed for input: $input")
}
println("All tests passed!")
}
```
[Answer]
# [Desmos](https://desmos.com/calculator), 63 bytes
```
f(l)=sort(l,[l[1...i][l=l[i]].countfori=[1...l.count]]2l.max+l)
```
Port of some other answers which sort by running occurrence count and value of the corresponding element.
[Try It On Desmos!](https://www.desmos.com/calculator/ksmat6jvbu)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/bmxtlobv65)
[Answer]
**[Q](https://code.kx.com/q/), 51 Bytes**
```
{$[x~();x;asc[key g],.z.s x asc(,/)_[1]'[g:(=:)x]]}
```
The above function takes an implicit parameter, *x*, and:
* returns *x* if it is empty
* otherwise, groups the items in *x* using K function *=:* which is equivalent to Q function *group*. This yields a dictionary where each key is a unique items in *x* and each value is a list of the indexes at which the item occurs in *x*
* and returns:
1. the sorted, unique items in *x*. The unique items are found by taking the keys of the group dictionary
concatenated with
2. the results of a recursive call to the function (*.z.s*) with the remaining items as the parameter. The remaining items are found by dropping the first index from each list in the group dictionary values (using *\_[1]'*), merging the lists (using *,/*), and grabbing the items at those indices from *x*
] |
[Question]
[
The \$\text{argwhere}\$ function takes a list of values and a predicate/boolean function as arguments and returns a list of indices where the predicate function returns true in the input list. For example,
```
argwhere([1, 2, 3, -5, 5], x -> x > 2)
```
would produce an output of `[2, 4]` because those are the (0-indexed) indices whose values are greater than two.
## Challenge
Implement the \$\text{argwhere}\$ function in your language of choice.
## Format
For the purposes of this challenge, we will deal with lists of integers. You must accept a list of integers and a [black box function](https://codegolf.meta.stackexchange.com/questions/1324/standard-definitions-of-terms-within-specifications/13706#13706) and return a list of integers in [any reasonable format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). You may assume the input list will never be empty. Your output may be either 0-indexed or 1-indexed — please specify which.
## Rules
* Builtins are allowed, but please consider adding a less trivial answer so we can see how \$\text{argwhere}\$ might be implemented in your language.
* Explaining your answer(s) is encouraged!
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the fewest bytes (in each language) wins.
###### Why argwhere?
argfoo is a naming convention where you don't want the elements themselves ‚Äî you want their indices or some other quality. \$\text{argmax}\$, \$\text{argmin}\$, and \$\text{argsort}\$ are examples of this. Read more about it [here](https://stackoverflow.com/questions/22679684/why-is-argsort-called-argsort). (Also, because my favorite programming language comes with this function and it's called `arg-where`. ü§´)
## Test cases
0-indexed
| Input | Output |
| --- | --- |
|
```
[1, 2, 0, 0, 3, 0, 0, 0, 4], x -> x == 0[4, 3, 5, 7, 11, 13, 17], x -> x % 2 == 0[8, 9, 10, 11, 12, 13], x -> x + 10 > 20[5, -5, 2, -2, 0], x -> x < 0[5, 2, 0], x -> x < 0
```
|
```
[2, 3, 5, 6, 7][0][3, 4, 5][1, 3][]
```
|
1-indexed
| Input | Output |
| --- | --- |
|
```
[1, 2, 0, 0, 3, 0, 0, 0, 4], x -> x == 0[4, 3, 5, 7, 11, 13, 17], x -> x % 2 == 0[8, 9, 10, 11, 12, 13], x -> x + 10 > 20[5, -5, 2, -2, 0], x -> x < 0[5, 2, 0], x -> x < 0
```
|
```
[3, 4, 6, 7, 8][1][4, 5, 6][2, 4][]
```
|
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 45 bytes
```
lambda l,F:[i for i,e in enumerate(l)if F(e)]
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPqfZhvzPycxNyklUSFHx80qOlMhLb9IIVMnVSEzTyE1rzQ3tSixJFUjRzMzTcFNI1Uz9n9BUWZeiUaaRrShjpGOARAag0kDHZNYHahJFVYKFQq2tgoGmpr/AQ "Python 3.8 (pre-release) – Try It Online")
Looks like it won't get much shorter than this.
Explanation: keep all indexes (found by unpacking; the index is the first item of each 2-element tuple in the return value of `enumerate`) for which the function returns `True` for the corresponding element.
[Answer]
# [Haskell](https://www.haskell.org/), 28 bytes
```
p!v=[i|(i,x)<-zip[0..]v,p x]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/v0CxzDY6s0YjU6dC00a3KrMg2kBPL7ZMp0ChIvZ/bmJmnm1BUWZeiYqGnaGhpmK0pZ6eoUXsfwA "Haskell – Try It Online")
## Explanation
To get the indices we `zip` the list with the natural numbers `[0..]`. Then we use a list comprehension to get only the correct indices.
[Answer]
# [R](https://www.r-project.org/), 24 bytes
```
function(x,f)which(f(x))
```
[Try it online!](https://tio.run/##jc/RCsIgFMbx@57iuxkonYHaxopl7xIyczcLRjEhenZTaXTjIDgXCv5/eOZwnW@LG@ZBB/uczGO8T8yT5YsbjWOWec6D14ZJgiKIPIf1EKfhPaz@pfzloTXEu8cqZ2@XkCa3LaEjyCjKeJNdQagqqG3mSDjFUHwRlaACso9PcIEqI/EXdZuXqtNihf6MzfL/InwA "R – Try It Online")
Uses [R](https://www.r-project.org/)'s built-in `which` function, which is pretty-close to `argwhere` except for the manner in which `x` and `f` are supplied...
---
# [R](https://www.r-project.org/), 26 bytes
```
function(x,f)seq(!x)[f(x)]
```
[Try it online!](https://tio.run/##jc/RCsIgFMbx@57i62Kg5EBtY8WyF4kuYszqZpEVCdGz21Ea3TgIzoWC/x8eFw7u@Dz1rjfBPobufr4MzAvLb/2VzT3fWeb5PnjTMSWgBWSa5XigqXgLa34xf3kYA/luMdpJnEWkSm0t0AgoEhXdVJMRigJ6mlkJrCmUX0RHKIMs6Am20HmEflHWaakyLpbpN5gs/y/CBw "R – Try It Online")
Roll-your-own version without any built-in.
Note that many/most [R](https://www.r-project.org/) functions vectorize, and this is assumed here (and indeed applies to all the test-cases). However, this isn't universal, so if `f` is a non-vectorizing function we'd need [+7 bytes](https://tio.run/##K/qfWJRenpFalGr7P600L7kkMz9Po0InTbM4tVBDsUIzujixoCCnEiwU@7/CNlnDUEfBSEfBAIyMYQwgMtG0VkizRZihWV2hYGurYFBrrQCzAmwKF8gQE7BeUx0Fcx0FQ6CJhkCeoTkWE1RVFYxwG2Oho2AJ1GgANcQIZBAWQ7SBShTsFIywGwJ0ha4p2FO6II9h0W@jgFMn8Tr@AwA): `function(x,f)seq(!x)[sapply(x,f)]`.
[Answer]
# [Raku](http://raku.org/), 13 bytes
```
{grep :k,|@_}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Or0otUDBKlunxiG@9n9xYqVCmoaWgo2CgY6CjamCrqmCkYKukYKBneZ/AA "Perl 6 – Try It Online")
Raku's `grep` filtering built-in can return matching indices instead of matching values if given the adverb `:k`. This is just an anonymous function that adds `:k` to the arguments it's given and passes them all to `grep`.
Raku's function objects actually have an `assuming` method that returns a new function with some of the arguments to the original function fixed in advance, so this code would more idiomatically be written `&grep.assuming(:k)` or the even terser `&grep.assuming:k`, but that's too long for golf.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 2 bytes
```
MT
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCJgWzgsIDksIDEwLCAxMSwgMTIsIDEzXWBFXG7OuzEwKzIwPjsiLCJNVCIsIiIsIiJd)
100% pure ascii. 0-indexed
## Explained
```
MT
M # Map the function to the list
T # and return indicies where the result is truthy
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 34 bytes
```
a=>f=>a.map((x,i)=>f(x)&&print(i))
```
[Try it online!](https://tio.run/##hc7RCoIwFAbg@57iJ0h2aIZbioZtl75EdDGCYEEhJuLbr@MqEBKCw9hh/3d2bm5wz0vn2z4dqtCY4Iy9Gut2d9cKMUpP3IuRkqTt/KMXnijUq0aclISWyGLtvxeu/EwCI4ydDoOMarzlek0R5jFfSJQSiqco7lQ5UxvoZVlJHDibfZye7Mxt@QkW@hfyZ2kR902nnWfmiMX0n1R4AQ "JavaScript (V8) – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 4 bytes
Full program. Prompts for array, then function.
```
⍸⎕¨⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94P@j3h2P@qYeWgEkQAL/FcCggAvI9wr291OPNtRRMNJRMAAjYxgDiExi1bmqDRRsFR71bq0FannUO1ehQkHXDkjY2ioYcGEYZALWb6qjYK6jYAg01RDIMzSHmWKkUIPFJFWgOHbTLHQULIH6DaBmGYHMA5llZKBgAxRW0MZimjZIwk7BCItxQGfpmoJ9qgvyLcRVdljMsFHArpugLgA "APL (Dyalog Unicode) – Try It Online")
`‚ç∏`‚ÄÉwhere
`‚éï`‚ÄÉthe function
`¨` mapped to
`‚éï`‚ÄÉthe array
[Answer]
# Java 8, ~~74~~ 73 bytes
```
f->a->{for(int i=0;i<a.length;i++)if(f.test(a[i]))System.out.println(i);}
```
-1 byte thanks to *@Unmitigated*
0-based. Outputs the indices on separated newlines to STDOUT.
[Try it online.](https://tio.run/##1ZJdS8MwFIbv9ysOBaGhaWg7x9R@gAjCLkRhl2MXsU1rZpeWJp0bo7@9Zu1EkA109EYCIck57znnecmKbqi9St7bOKdSwhPlYj8CkIoqHsNKR0mteE7SWsSKF4I8Hg/BidhLxRIeU8WCmVAsY1WET2Q9FELWa1YFXKjFMooghrBN7Yja0T4tKlM/Aw8dnweU5Exk6s3nloV4aqZEMalMuuBLhOY7qdiaFLUiZaU1uTA58pvWH@n5y/o11/MfMTYFT2Ct0cy50qnZYgm0yiQ6kAJ0YwCFEAT76G97F3vY0Wvc7Q6@bvwu90RTYybKWsk7MKxv2PuqojtJVNE3NCmyDKAigW0YOgY6X@y5VrqaLnbM@ZXLkOrht3Z0KN7LYkLLMt@ZKSI0jlmpTTvfFHWWwQ8LrjX8BE@x62J3jN3pYA5ceX/04IuuEw7Gd4Nvset0eJ4mHAzPcp3Iu4ivVw4GOMH2RH9jW//kweCCi8CCIaH@Lw5AM2raTw)
**Explanation:**
```
f->a->{ // Method with Function & integer-array parameters and no return
for(int i=0;i<a.length;i++)
// Loop `i` in the range [0,length):
if(f.test(a[i])) // If the Function for the `i`'th integer of the array is truthy:
System.out.println(i);}
// Print index `i` with trailing newline
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 20 bytes
-9 bytes thanks to @Joe Slater. Didn't know that `select` can take a flag.
```
(a,g)->select(g,a,1)
```
[Try it online!](https://tio.run/##Zc7dCoMwDAXgVzkIg5alYDvFDaYvIl4EURHKKOqFe/qudT@9GOQi4XwJcbzManJ@RO0F0yRVsw526DcxEZOWnp2zT8FQDdwyP7bQZnHI0LO1YiSwlIS2bTXBEPKjLt8mVNER9riyo66RdxEXBykJFUGHRR0mXSV4gkn4SriFOP9QE3mi55CggXnbcFKVxyMqPpPYHT/wH3TSvwA "Pari/GP – Try It Online")
---
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 29 bytes
```
(a,g)->[i|i<-[1..#a],g(a[i])]
```
[Try it online!](https://tio.run/##Zc7dCoMwDAXgVzk4Bi1LxbqJG6gvUnoRBkpBRpFdONi7d6376cUgFwnnS4jnxanJhxF9EEyTVINxT9cpo8tyx5YmwcZZaQN7Pz8EQw3wi7vdY1ukocCV51mMBJaSYIzRhJpQbXX8NrFOlrCmlRV9j8omfNpIQ2gJOi7qOOk2wz3qjM@ES4yrD60Tz/QQEwyo3zaeVM32iErPZNbhB/4DK8ML "Pari/GP – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 35 bytes
```
->a,f{(0..a.size).select{f[a[_1]]}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGiNNulpSVpuhY3lXXtEnXSqjUM9PQS9Yozq1I19YpTc1KTS6rTohOj4w1jY2troUpVChTSoqMNdYx0DIDQGEwa6JjE6ujaVVRXKNjaKhjUxkLULlgAoQE)
[Answer]
# Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 19 bytes
```
(cx<ixm pM).^m<m gu
```
## Explanation
Here's the same code converted to a more convenient format:
```
f q x =
cx $ ixM pM $ m (gu q) x
```
To start we have `gu` which takes a boolean and produces `[]` if false and `[()]` if true.
We map `gu q` across the input list, this converts things that pass the test to `[()]` and things that fail to `[]`.
`pM` takes a list and a value and replaces everything in that list with that value. `ixM` is an index map. It combines every element with its index using some function. Here we use `pM` as the function so that our `[()]`s get replaced with `[index]`.
Then `cx` concats everything back together.
You can reorganize things a bit to get:
# 19 bytes
```
cx.^ixm<(pM^.)<m gu
```
Which is equivalent to
```
f q x =
cx $ ixM (\x y -> pM x $ gu $ q y)
```
But this is also 19 bytes so nothing is saved.
There is also:
# 19 bytes
```
(st.^^fl<fm cr)^.eu
```
This solution uses an entirely different set of tools to solve the problem but is the same length.
This can be translated to the more conventional
```
f q x =
m st $ fl (q < cr) $ eu x
```
First `eu` pairs every element with its index in the list. Then `fl (q < cr)` filters using `q` on the second element of each pair. Finally `m st` gets all the indices from the remaining list.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~5~~ 4 bytes
*Edit: -1 byte thanks to Razetime*
```
`fNm
```
[Try it online!](https://tio.run/##yygtzv7/qKnx3G47IwNtQ4NHjRs0/yek@eX@//8/2kLHUsfQQMfQUMfQSMfQOBYA "Husk – Try It Online")
Razetime already pointed-out in the comments that [Husk](https://github.com/barbuz/Husk) has a one-byte built-in for `argwhere`: the `where` or `W` function.
So this is an implementation without `W` or any other function that acts-on or returns indices.
```
`f # filter (select the elements that satisfy a condition)
N # the natural numbers
# using this list to represent yes/no:
m # map
# the black-box function provided as (implicit) argument 1
# across all elements of (implicit) argument 2
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 18 bytes
```
Position[1>0]@*Map
```
[Try it online!](https://tio.run/##bY3BCoJAEEDvfoWw4KFG2FkVC1LsAwSjo3hYTGkPulF7G/TXt0UTIpqBubzHvEGaezdIo1pp@8xW@qWM0mONOW@KXSkftnqq0dQszPuiYE0wX1s5zuQRyzIegP8ZQhDA3UbL5RBPE3hU6lvNQDSrS7HDCaSACBgBpovD9shzsf2iAxwB@aIIZ63K6SvlUwJh4nKhK/7HGzgbPVzgF3iTfQM "Wolfram Language (Mathematica) – Try It Online")
Input `[f, list]`. Returns a list of 1-indexed `{index}`s.
Finds the positions of `True`s when the function is mapped onto the list.
---
### [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 13 bytes
```
Position@_?#&
```
[Try it online!](https://tio.run/##bY3BCsIwDEDv@4pBYBczaLuNKbhZP0CY51JkqMMetoL2FvrttWwOREwgl/fIG3v3uI@9M9c@DE3o7Ms4Yyd5OUAWuqeZnCIAn7eDAq1AaJ1JKSkhaBqWYfoZ4iiQxS3my7D0HhM62ZsCFHpxqYy4who5R14gr2cHNpy1Yv1FW9whZ7MiorUo@69UShXmVczlsfgfr@Do7HjGX5D48AY "Wolfram Language (Mathematica) – Try It Online")
Input `[f][list]`. Returns a list of 1-indexed `{index}`s.
Finds the positions of elements that satisfy a predicate - basically a built-in. However, this can possibly include the index of the head of the expression (`{0}`) if the predicate returns `True` when applied to that head (`List`).
[Answer]
# [Nim](http://nim-lang.org/), 60 bytes
```
proc a[S,F](s:S,f:F):S=
for i,x in s:
if f x:result.add i
```
[Try it online!](https://tio.run/##NY07CsMwEAV7n@KVEizB@VQLglS@gErjQrEtsuB4g2SDbq84gcAUU82s8qr1nXRE6D11g8nsKXJn2bsGUROECmRF5gaQiIjCac77sp3CNEHqPD4Vwdz7M@FCaH9c/3JwGwjfgyl8hDbLeKgucChwDq2tHw "Nim – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-xp`, 7 bytes
```
bMa@*:1
```
Takes a list and a function that returns 0 (falsey) or 1 (truthy) as command-line arguments. Uses 0-indexing. [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgebSSbkWBUuyCpaUlaboWy5N8Ex20rAwhPKjgTcVopWgLa0trQwNrQ0NrQyNrQ-NYJR2l6kRtQwM7I4NauHYA)
### Explanation
```
b ; Second argument (the function)
M ; Mapped to each element of
a ; First argument (the list)
@*: ; Find all indices of
1 ; 1 (truthy)
```
[Answer]
# [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 84 bytes
```
(d w(q((L F N)(i L(i(F(h L))(c N(w(t L)F(a 1 N)))(w(t L)F(a N 1)))L
(q((L F)(w L F 0
```
The second line is an anonymous function that implements argwhere; the first line is a helper function. Uses 0-indexing (though it could just as easily be 1-indexing; simply change the number on the second line). [Try it online!](https://tio.run/##XY6xDsIwEEN3vsKjb0tSKmDq1qnqCmsgEUQqBdoKBD9fjoqhoJMiy37n3JDaZ5P66zgy4MEbWaFELUyomFjyhEqEB9R8cFBd0qOGFTX/jWqhHdtvh8b4VJmRzcUHNGnf@e4pC25B/XGAhYPRyabXYCl4xe5SzJClhjlWsBY2g10J4j22c2KNDayZAKeMqO3P@@DB3UfHvi/gDOhDcNgpqnfO1nOwjUfkordMygmMQJUf0j0WP6j7jcY3 "tinylisp – Try It Online")
### Explanation
The helper function `w`, in addition to `L` (the list) and `F` (the function), gets an extra argument `N` (the current index). Its logic boils down to:
* If `L` is nonempty:
+ If the result of calling `F` on the `h`ead of `L` is truthy, `c`ons `N` to the front of a recursive call to `w` with arguments:
- `t`ail of `L`
- `F`
- `a`dd 1 to `N`
+ Else, just do the recursive call
* Else, return `L` (empty list)
The anonymous function calls `w` with an initial index of 0.
[Answer]
# [Julia 1.0](http://julialang.org/), 16 bytes
```
l/f=findall(f,l)
```
[Try it online!](https://tio.run/##bY7RCsIwDEXf/Yr7IrTYsrZuTMHuR8SHgRQqochQ2N/XrChWJoSQkHOS3J4URzvnTE3wIabrSCSCIpnvU0wPSgJnq@AUTIn9p@BoL43ADD1w8h5Gys1XagvbKfQKljdY7mxfGVu4tXVQODJn3o5bvMrZ8QgD3K/ER3RXftTLnxV/wor8S@QX "Julia 1.0 – Try It Online")
Boring builtin, just change of order of parameters, let's move on. (The answers are all 1-indexed, by the way.)
### [Julia 1.0](http://julialang.org/), 18 bytes
```
l/f=findall(f.(l))
```
[Try it online!](https://tio.run/##bY7RCsIwDEXf/Yr7IrTYurZuTMHuR8SHgRQqoYgo7O9rVhQrE0JIyDlJrk@Ko51ypib4ENNlJBJhK0jKfLvH9KAkcLIKTsGU2H0KjvbcCEzQAyfvYaRcfaW2sJ1Cr2B5g@XO9pWxhltae4UDc@btuNmrnA2PMMD9SnxEd@VHPf9Z8UcsyL9EfgE "Julia 1.0 – Try It Online")
This looks very similar, but works differently and shows off Julia's generalized broadcasting feature: `f.(l)` automatically maps `f` over each element of `l`, collects the results into an Array, type-infers that to be as a `BitVector` (a 1-D array of booleans), and passes that on to `findall`. This single argument version of `findall` accepts only arrays of booleans, and returns indices where there are `true` values.
### [Julia 1.0](http://julialang.org/), 21 bytes
```
l/f=axes(l)[1][f.(l)]
```
[Try it online!](https://tio.run/##bY7dCsIwDEbvfYrvRmixdW3dmILdi5Re7MLBpIzhD/Tta1YUKxNCSMg5Sa7PMPY6phSqwfbxcmeBO@3dsKfCp/k2To8wMTgtYARUjsOnoKh9xRAhO0rWQnG@@Up1ZhuBVkDTBk2dbgtjC7O2jgIn4tTbMYtXODsaoYP5leiIbPKPcvmz4M9YkX@J9AI "Julia 1.0 – Try It Online")
Even avoiding `findall` altogether, the answer isn't too much longer!
`axes(l)` returns the indices in each dimension of `l`. Here since `l` is one dimensional, we take `axes(l)[1]` which gives the indices of the list. On that, we use [Logical indexing](https://docs.julialang.org/en/v1/manual/arrays/#Logical-indexing): As seen above, `f.(l)` returns an array of booleans. When we use that to index within the list of indices, we get back the indices where the function `f` returns `true`.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 43 bytes
```
x=>y=>x.reduce((a,b,i)=>y(b)?[...a,i]:a,[])
```
[Try it online!](https://tio.run/##NYhBCsIwEAC/kuMurEurnoSNDwk5bNNUIqWRtkr6@hgEYRiGeepHt7Cm135a8hjrJLWIPcQWXuP4DhFAaaCEbcKAd8fMSsnflJzHGvKy5TnynB8wgevJnMl0Py7/aFw9QjFiTZOYDrF@AQ "JavaScript (Node.js) – Try It Online")
0-indexed, takes input in curry format f(array)(function)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
δ.Vƶ0K
```
The input black-box function is a string. 1-based.
[Try it online](https://tio.run/##yy9OTMpM/f//3Ba9sGPbDLz//w/RNjJ41LCLK9pCR8FSR8HQAIgNgdgIiI1jAQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC8f9zW/TCjm0z8P6v8z86WileSSfaUMdIxwAIjcGkgY5JbKyOQrTS4Q6gnAlQ1FTHXMfQUMfQWMfQHCIVom1k8KhhF1DeQsdSx9AALG0EVAGRBsrtBMqZ6uiaAo3WBZqOJg4WiQUA).
**Explanation:**
```
δ # Map over the (implicit) second input-list,
# using the first (implicit) input-string as argument:
.V # Evaluate the string as 05AB1E code
∆∂ # Multiply each item by its 1-based index
0K # Remove all 0s
# (after which the result is output implicitly)
```
[Answer]
# [Python 3](https://docs.python.org/3/), 45 bytes
```
def f(L,F,t=0):F(L[t])and print(t);f(L,F,t+1)
```
[Try it online!](https://tio.run/##hZFfa9swFMXf9SkujFKbKsF2kmZLlsIeaiiErZT2yZiiRfIm5kjCuh3Op8@uLDuUvswI68@9v3OObHfC39YszmepGmiSPS857rJ0Uyb7CutUGAmu0wYTTLdj@SZPz/robIfgT56xT1DaDlB51OYXh6M9/IkMNG/mgNoaQAtCymGCVnsEbTwqIcE2sZVIsG/Inu6/7V8fnx6@P8MuVtiPl@fHl7CtahZCxjh9umEAsTYXzikj6YyxhqK02ihyCOnmHqU2oXX/6rHjUMZJ9U4dUMmwI@mjcAmtqLvTjg8Cc@9ajcn19jpNA05d6q9ok0EnnJR00orjTymg38TaIF4tN3WoTxYT@N6Sgk7h48UAsDuFmBB/QhQ4KIfwYKTq77vOdrHuhPe0oPHuYyWT2O7iy0eD9FzlHAoO2TAW04LGsoYtQA@zO3oRmkF86LAqhtYVh1sO65pVy2m/5pCTYE67fF2P7aPGFRSTTtDIiPvM4Qt1ZiNVBLK@2IzcDTXAHRRZ5Eia7FZEk99sNaSfhRuM4Af66yX4QJPNIqIfkf@i9T8 "Python 3 – Try It Online")
A function that prints the indices to STDOUT and terminates with an error.
[Answer]
# [Desmos](https://desmos.com/calculator), 34 bytes
```
a=[1...l.length]b(l)
f(l)=a[a<1/0]
```
\$b(l)\$ is the inputted black box function, which you will need to change for each test case (Desmos doesn't support inputting functions as arguments). \$f(l)\$ is the argwhere function. The output will be 1-indexed.
Further details in the graph links.
[Try It On Desmos!](https://www.desmos.com/calculator/cmv1jhnh15)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/dyanvc3doi)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 85 bytes
1-based.
Takes an integer array with a length and a function taking an integer.
```
m;f(s,l,p)int*s,p();{putchar(91);for(m=l;l--;s++)p(*s)&&printf("%d,",m-l);puts("]");}
```
[Try it online!](https://tio.run/##bZLLboMwEEX3fMWIKpFNTIUhNI0c8gVRd11FLBCExhIPi0cVKeLb6dhJ0wgqGT/m3DszFk7drzQdx1LkpGUFU1RWndMyRai4qr5Lz0lDtpyKvG5IGRWicF3RrlZUEaely6VqUJ8Te5Exm5VuQQWaWmLHNhXD@CKrtOizE@zaLpP163lvWagHxYleLhSu0Jy6vqngsvcFDDfqz2kUeQ8czPHCfxas54IV9/b@nyKcK3aGGlwmsiLftcyQWwA65MhjHOkDgLYeY3rlDHwGAQM3ZBAO7B/omRH8bnCsJ7q1wZhgw4CjieOJbyaidwZbDHt3ia9lE0l4awORq@vO6VP04/NwwM3AoHhcKjQlsIk3001w44mw7vcnjsJEhN7lCvtQmFJhuwrvoEL9aZNx6MeS6B8ij0ksIMH3Ymw50QFdV88KZyqsYfwB "C (gcc) – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 34 bytes
```
x=>y=>x.flatMap((b,i)=>y(b)?i:[]);
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/C1q7S1q5CLy0nscQ3sUBDI0knUxMoppGkaZ9pFR2raf0/OT@vOD8nVS8nP10jTSPaUEfBSEfBAIyMYQwgMonV1KhQsLVTABK2Cgaamv8B "JavaScript (Node.js) – Try It Online")
```
f = x => y => x.flatMap((b, i) => y(b) ? i : []);
console.log(f([1, 2, 0, 0, 3, 0, 0, 0, 4])(x => x == 0))
console.log(f([4, 3, 5, 7, 11, 13, 17])(x => x % 2 == 0))
console.log(f([8, 9, 10, 11, 12, 13])(x => x + 10 > 20))
console.log(f([5, -5, 2, -2, 0])(x => x < 0))
console.log(f([5, 2, 0])(x => x < 0))
```
[Answer]
# [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 48 bytes
```
(load library
(d A(q((L F)(all-indices(map F L)1
```
[Try it online!](https://tio.run/##VY7BCsIwEETv/Yo57h6EJFqqp9KLp36A12iCBNKoTRHqz8e1B7W7sAw7b2CmkOYY8r0UijfrEMN5tONckUNHD6IeRyYb4yYkFy4@02DvOKJnXagDSXSChoGS3S5XYcd4@fHWcvVFdmLWaKA19Ba6YfinT//EHgdotQBGGJa3Hc7Ogk4f7XNuYRTIOmdwEpRlfvEalPwVNUuXRRmGYoiyU3j6doWatVXe "tinylisp – Try It Online")
The `library` unsurprisingly contains some rather useful functions for golfing; not sure if this should be scored as `tinylisp + library`. Takes the test harness from [DLosc's answer](https://codegolf.stackexchange.com/a/241431/67312).
[Answer]
# [Ruby](https://www.ruby-lang.org/), 31 bytes
```
->a,f{a.zip(0..){f[_1]&&p(_2)}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGiNNulpSVpuhb7de0SddKqE_WqMgs0DPT0NKvTouMNY9XUCjTijTRrayGqbmqmRUcb6igY6SgY6yjomuoomMYCabuK6go7o9pYBWUFWzuFaKCsSSxEw4IFEBoA)
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~12~~ ~~10~~ ~~9~~ 6 bytes
```
{&x'y}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6pWq1CvrOXiSos2srE2VDBSMFYwUTCNBfIN7cB8XSAyVtAFCxnYgoUMgNAYTBoomMQCACIADpE=)
*Down 3 bytes thanks to Steffan*
Takes `x` as black box function and `y` as list of integers.
Explanation:
```
{&x'y} Main function.
x'y Apply each value y to x (x(y)), return a binary list
& Get all the truthy indices
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 2 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Black box function is pre-assigned to variable V.
```
√∞V
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=Clh7WD4y&code=8FY&input=WzEsIDIsIDMsIC01LCA1XQ)
[Answer]
# [Fig](https://github.com/Seggan/Fig), \$2\log\_{256}(96)\approx\$ 1.646 bytes
```
TM
```
[Try it online!](https://fig.fly.dev/#WyJUTSc+KzEweDIwIiwiWzgsOSwxMCwxMSwxMiwxM10iXQ==)
The `'>+10x20` bit in the link is the function \$f(x) = x + 10 > 20\$.
```
TM # Takes a function and a list in any order
M # Map the list by the function
T # Return the truthy indexes of the resulting list
```
[Answer]
# [J](http://jsoftware.com/), ~~13~~ 11 bytes
*2 bytes saved thanks to [Razetime](https://codegolf.stackexchange.com/users/80214/razetime)'s approach of using `I.`*
```
1 :'I.u"+y'
```
[Try it online!](https://tio.run/##jdBRC4IwFAXg9/2KQxAWTtmWw5L0oSAIoodeQyJCil6CIDLov9uZWGZPwRw6d757ueeqF3r76/F@Kq4F0gQeJBQSPkGI@Wa1qDQSbxneev7Dq4ZClO5WLsR6FmKrJQzv12v0fuGKcokSQcYtTaFEcThdMFBIUQ7xKadhWEdhVO8KUaNGNWYlYgnNEppfOm7JPnM/rMGzQ0dELWLGmWa4kccSE1qqcY2zW9fnH2Qwb9goTN2R36HHmLhDJxvGG5ndBraeRuAm0qLTrz6zDmSxs2x8xyG0yP9hxqoX "J – Try It Online") Assumes the given predicate is a true boolean predicate, which yields `1` for truthy and `0` for falsey, as is standard in J.
I don't think there's a tacit way to make an adjective as complex as this. Technically, as per [standard IO](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/13707#13707), we can have ~~8~~ bytes by assuming the function is stored in a predefined variable `u`:
```
[:I.u"+
```
## Explanation
Approach c/o Razetime:
```
I.u"+y
u the given boolean function
"+ applied at each cell of
y y, the input list
I. obtain indices where truthy
```
Old approach:
```
u"0#i.@#
i. the indices from 0 to
@# the length of the input, right-exclusive
# and keeping only the elements corresponding to
u the given boolean function
"0 applied to each cell of the input
```
[Answer]
# [Go](https://go.dev), 85 bytes
```
func(f func(int)bool,L[]int)(A[]int){for i,e:=range L{if f(e){A=append(A,i)}}
return}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=hZLRSsMwGIXBO_sUPwMhZam03cqmWKH3u_DGK_EibmkNrmkN7RyUPok3RfCh5tP4J2lBsVQIJKHfOefPoe8fWdGd5iXbvrCMQ86EdEReFqqCS5ileTVznANTwFT29swVh_izrlJvfbpPa7klKZhNyMp9Koo93Tw86jNJ7N6khQJB-XWsmET7TSNQQbjbJDErSy53JKHCbVtH8apWsrXmX2fnOjOrQohtwBGGiMaScIRbCFszG3_1p7g4Bt-CO3GYdLyA8AeN8ZO-cwh8PUSPS55N0Tfa1tGfTcnEhca5U8jtJRnKJRhJTXNNQCGksKDgRRSi1nX_wvjsX7Bv1mI44FqO6nQLvXBpeExYUQjQJcBbsBpV6TZ61ZrCFXJ-rwm1blSDlfSSyD4EUU9P-j89UP0f0XV2_wY)
# [Go](https://go.dev), generic, 90 bytes
```
func g[T any](f func(T)bool,L[]T)(A[]int){for i,e:=range L{if f(e){A=append(A,i)}}
return}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=hZLBSsQwEIbx2qcYFoQEU2m7W3YVK_S-Bw89WXqIu2kJbtMa2mWl9Em8LIJP4ZPouwhO2i6olAoDk8D3_5P5yctrVhzfS7555JmAnEtlybwsdAWXMEvzavZWV6m9-rhPa7WBLI6Aq-eEpGDuJKIPRbFj6ziJKAnjRKqKNmmhQTJxHWiu0HPdSKSJoE0Y8LIUaktCJmnbWlpUtVZtP-Hz7GvPNWSVB0FvfgBjZwY0PQkHuAWvtQwnnpwpLgjA6cGt3E86noP3g8bxk74X4DrmEQOuRDZF3xhbq0vOJEsoNNadRm6nSBZjTwgOZF1ujcvAYzBnYPsM_JbSvyiu_At1upqfDliLEZXZf5AtOhrdlwxc9HDx5i5HNCaFQbNicIWUMyg8oxpRYBCDwO8XQNA2b_yPPTHDLzge-_4N)
] |
[Question]
[
Let's solve [this user's homework](https://stackoverflow.com/q/64768698/509868); I think it's an interesting exercise!
### Input
Two 3-digit natural numbers.
### Outputs
Two 2-digit numbers. In each of the output numbers, one digit is taken from one input number, and the other from the other number. The choice is independent. The first output number should be the minimal possible to create using these constraints, and the second one should be the maximal such number (or vice versa).
* Input numbers never have leading zeros; output numbers should also not have leading zeros.
* Input and output can be encoded as numbers, strings, lists of digits, etc.
---
Examples (in format `input` - `output`):
```
123, 912 - 11, 93
888, 906 - 68, 98
100, 100 - 10, 11
222, 222 - 22, 22
123, 222 - 12, 32
798, 132 - 17, 93
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~15 14 13~~ 9 bytes
```
§,▼▲f←ṁP*
```
[Try it online!](https://tio.run/##yygtzv7//9BynUfT9jyatintUduEhzsbA7T@//8fbahjpGMc@z/aUgfIigUA "Husk – Try It Online")
Takes two input arrays, outputs pair `(min,max)`.
-1 byte from Dominic Van Essen.
-1 more byte from Dominic Van Essen (after some more struggling).
-4 bytes taking arrays of digits as input.
## Explanation
```
§,▼▲f←ṁP*
* cartesian product pairs of the inputs
ṁP map each to permuations, and flatten the list
f← remove elements where first digit is falsy(<10)
§, create pair with
▼▲ minimum and maximum
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~11~~ 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
â€Â9ÝKWsà‚
```
-1 byte thanks to *@ovs*.
[Try it online](https://tio.run/##ASMA3P9vc2FiaWX//8Oi4oKsw4I5w51LV3PDoOKAmv//MTIzCjkxMg) or [verify a few more test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXC/8OLHjWtOdxkeXiud3jx4QWPGmb91/kfHW1sYKZjYWQSqxNtaGCgA8RAlrGlkY6lsQVIzNBQx9LSMjYWAA).
**Explanation:**
```
â # Take the cartesian product of the digits of the two (implicit) inputs
€Â # Bifurcate each value within the list (short for Duplicate & Reverse copy)
9Ý # Push the list [0,1,2,3,4,5,6,7,8,9]
K # Remove those integers (so all integers with leading 0s)
W # Take the minimum of this list (without popping the list itself)
s # Swap so the list is at the top of the stack again
à # Pop and push its maximum
‚ # And pair the minimum and maximum together
# (after which it is output implicitly as result)
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 15 bytes
```
{∋ᵐpcℕ₁₀}ᶠ⟨⌋≡⌉⟩
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFSu9qhtw6Ompoe7Omsfbp3wv/pRRzeQLkh@1DL1UVPjo6aG2ofbFjyav@JRT/ejzoWPejofzV/5/390tKGRsY6CpaFRrI5CtIWFBZBtYAZiGxoY6CgACRDbyMhIRwFIxMYCAA "Brachylog – Try It Online")
```
{∋ᵐpcℕ₁₀}ᶠ⟨⌋≡⌉⟩
{ }ᶠ find all possible outputs:
∋ᵐ select a digit from each number
p permute them
c merge them to a number
ℕ₁₀ that number is >= 10
with the list of all possible numbers:
⟨⌋≡⌉⟩ [minimum, maximum]
```
First time using `⟨⟩`! :-⟩
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 10 bytes
```
p;p@ḷ/ƇṢ.ị
```
[Try it online!](https://tio.run/##y0rNyan8/7/AusDh4Y7t@sfaH@5cpPdwd/f/w8uV/v@P5oo21DHSMY7V4Yq20AFCEMNQx0DHAMQwAkoZARmxIHWWOoZgDpBhoGOGXR0A "Jelly – Try It Online")
Dyadic link. Input and output is a list of digits.
## Explanation
```
p;p@ḷ/ƇṢ.ị
p Cartesian product
; Join with
@ Reverse arguments
p Cartesian product
Ƈ Filter by
/ Reduce by
ḷ First argument
Ṣ Sort
.ị First and last element
```
*-1 byte by using the `.ị` technique to get the first and last element, thanks to caird*
[Answer]
# [Python 3](https://docs.python.org/3/), 81 bytes
```
lambda a,b:[m(k for i in a for j in b for k in(i+j,j+i)if'1'<k)for m in(min,max)]
```
[Try it online!](https://tio.run/##VcpNDsIgEIbhvadgN5Cy4CcxaOpJ1AXEEAeENk0XenpkujB2M3nzfDN/1udUbYuXW3v5Eh6eeRnO18Izi9PCkGFlfstEGbbMPTkOSaYBBUbQMGZBQ6GhYJXFv8W9zQvWlUcO2liQcNIGhDj81DlHqo471Up1pfuvxpiudHeq6dcq3bV9AQ "Python 3 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 62 bytes
```
a!b=(`foldl1`[s|i<-a,j<-b,s<-[[i,j],[j,i]],s>"1"])<$>[min,max]
```
[Try it online!](https://tio.run/##JY7RaoQwEEXf/Ypb2QeFyWKysFiI@7Zv/YMQMGK2jY2xqNAt9N/thL7cOVxmDvPhtk8f43G4l6Gr@scSxyh7s/0GLRxNWgy0aWFMoMmSmShYS9utlKWt9elm5pBodk97zC4kdBiXAjCOBnrSj4UW@F7WccMZjxB3v6Lq07Lfo597lCTKGmzBu9/fQvJ8@rWGtOOEit@pu85kC9fZfkh1IbxKBQEpmS5F27Y8mys310xtIZuGwJF3MslCKUXg4Oaf/gA "Haskell – Try It Online")
This is the same approach as Jitse's Python answer.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~233~~ \$\cdots\$ ~~189~~ 185
Saved 4 bytes thanks to [gastropner](https://codegolf.stackexchange.com/users/75886/gastropner)!!!
Saved ~~9~~ 13 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
```
#define d(a,i)for(qsort(a,i=3,1,L"\xf06be0f\xd02917beǃ");a[--i]<49;);
s;j;i;f(a,b)char*a,*b;{d(a,i)d(b,j)s=a[2];i=a[i]<b[j]?s=b[2],a[i]:b[j];j=*a;*b++=j>*b?j=*b,*a:*b;*a++=i;*a=s;*b=j;}
```
[Try it online!](https://tio.run/##bZPfb5swEMff81dYVJGAOBo/UgJ1aR@6ve0/AFTZxrSQFTLMJNYoT/vj@l8tOwxhkAYJzv7q7nN3@MzXL5yfTjepyPJSoFSnODeyqtZ/yqpuul3oYht/1@I2szwmrCxuU8sJ7C0TH380g9Bovc6T@01ADLKQpCA5ySCMGfyV1ibFJiOHnprqDBeGDGnkJCQHA2EsKpJHGTKQcCfcdQIpQpMSk61WYfFgskfYMmzSO0CZFMQcTCjBISzI8ZSXDXqjeakbi8MCwaMSo0bI5plGCQghOmi242oYab7vd8a2rM44g3EcJTpWb9yJ2Qa@diSXXDZyA1vFBpY34QYzrrtRu82tN03mOnOuaPeCNyIFsqrXxihQFXg@rIaqMbLtvnDQnB6H0UAEbdOvNhh5QxMYub22VbxZSv4q@E7UYy9x@82J2@Br3PpPXcywf4J3jITRQHr3y/MyFS2EWWRY3iOZv4sq08@dGF8GwRwVglYr5W2g/qz@F0OfeVXKBojDySm/hMzcEI3gF09E2dR8/xvGawg3yAWWzbHsOpZdxzLMPmH3NXSf6dpSYrSUaP2ANEwxYhOXfv4vUlS/msibphhAoGNtyZcccPDVYNDhJtgJXBwMZSWfOhLQyzgsl910J1PtwKPr4G2v6EhcLR@qj0s4ZuVyHoVqF4bWOedxcTz95dkP@iJP63fRCi4bynf/AA "C (gcc) – Try It Online")
Inputs two \$3\$-digit strings and returns the min and the max as \$2\$-digit substrings in the first \$2\$ digits of the first and second input string respectively.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 38 bytes
```
Lw$`(.).*,.*(.)
$1$2¶$2$1
A`0.
O`
,,G`
```
[Try it online!](https://tio.run/##K0otycxLNPyvquGe8N@nXCVBQ09TT0tHTwtIc6kYqhgd2qZipGLI5ZhgoMfln8ClowNU99/QyFjH0tCIy8LCQsfSwIzL0MBAB4i5jIyMdIAYAA "Retina – Try It Online") Link includes test cases. Explanation:
```
Lw$`(.).*,.*(.)
$1$2¶$2$1
```
Take the cartesian product of the inputs and their reverses.
```
A`0.
```
Remove entries with leading zeros.
```
O`
```
Sort.
```
,,G`
```
Take the first and last result.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 11 bytes
```
p;U$Ḍ>Ƈ9Ṣ.ị
```
[Try it online!](https://tio.run/##y0rNyan8/7/AOlTl4Y4eu2Ptlg93LtJ7uLv7v8vhdv1HTWv@/482NDLWUbA0NIrVUYi2sLAAsg3MQGxDAwMdBSABYhsZGekoAIlYAA "Jelly – Try It Online")
Input as a list of digits (which the Footer does for you)
-1 byte [thanks to](https://codegolf.stackexchange.com/questions/214981/make-a-minimal-and-maximal-2-digit-number-from-digits-of-two-3-digit-numbers/214988?noredirect=1#comment502676_214988) [Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string)
## How it works
```
p;U$Ḍ>Ƈ9Ṣ.ị - Main link. Takes x on the left and y on the right
p - Cartesian product of the digits. Call this list X
$ - Group the previous two commands into a monad f(X):
U - Reverse each pair in X
; - And append it to X
Ḍ - Convert each pair back to an integer
Ƈ - Keep those which:
> - Are greater than:
9 - 9
Ṣ - Sort
.ị - Take the first and last elements
```
[Answer]
# [Python 2](https://docs.python.org/2/), 70 bytes
```
lambda*l:[m(m(set(l[i])-{'0'})+m(l[~i])for i in(0,1))for m in min,max]
```
[Try it online!](https://tio.run/##VcpBCsIwEIXhvafILolGmElBWsGT1C4iGgxk0lKzUESvHicuxG4e/B9veuTrmGzxh2OJjk5nt477nhSp2yWr2IdBb58S5EtviPPN7cdZBBGSAoP6W8QlKCRD7j6UaQ4pK68k2kYa2aGVWq9@2rZtVdgtFAFY6/6rtZa17kKxfhtA1vIB "Python 2 – Try It Online")
**[Python 3](https://docs.python.org/3/), 70 bytes**
```
lambda a,b:[m(m({*a}-{'0'})+m(b),m({*b}-{'0'})+m(a))for m in(min,max)]
```
[Try it online!](https://tio.run/##VcpNCsIwEEDhvafIbmY0Qn5AquBJ1MUECQactJQulNKzx2Qj7eYtPt7wnV599iVe7@XNEp6sWIfLTVBw3vNynMHAQgfBQLpRWBETxX5UolJGSVkLf@hRhjHlCSOCdR40nK0Dot1fu65rak4btcZUbV2rc65q60Zte72xVcsP "Python 3 – Try It Online")
These could be shorter if we can take a list of digits as numbers.
[Answer]
# JavaScript (ES6), 80 bytes
Expects a pair of 3-digit strings. Returns a pair of 2-digit integers.
```
a=>[(g=n=>(a+[,a]).match(~~(n/10)+'\\d*,\\d*'+n%10)?n:g(n+d%7-2))(d=10),g(d=99)]
```
[Try it online!](https://tio.run/##dc9LCoMwEAbgvadwI0lq1CSCJoXYg6iL4KstNpYqXXp1m0ilpdLFzA/DxzBzVU81Vo/LfQr0UDdLKxclsxx2UssMKj/HqkThTU3VGc4z1BElyAdFUR@wbcDXnpmc9LGD2q@9NGAIwVqaGe5MCoHKpRr0OPRN2A8dbGEOKIsBdoGgDJQIuVHkUopdETu/kHO@QpJsMOEG8h2khFhoY9tIsNm6g4wxC228IWPYlPPnxi9IDYz3MBXrjTT@wNQ@s7wA "JavaScript (Node.js) – Try It Online")
### How?
We use `a+[,a]` to concatenate `a[]` with itself, with a comma in between. For instance, `['123', '912']` is turned into `'123,912,123,912'`. (We only need the first 3 entries, but the 4th one is harmless.)
We use the recursive function `g` to look for some 2-digit integer `n` such that the above string matches `~~(n/10)+'\\d*,\\d*'+n%10`. That is to say:
* \$\lfloor n/10\rfloor\$ (the 'left' digit of \$n\$)
* followed by some optional digits
* followed by a comma
* followed by some other optional digits
* followed by \$n\bmod 10\$ (the 'right' digit of \$n\$)
We add \$(d\bmod 7)-2\$ to \$n\$ between each recursive call, where \$d\$ is also the starting point:
* \$d=10\rightarrow (d\bmod7)-2=1\$, so we go from \$n=10\$ to \$n=99\$ (looking for the lowest valid integer)
* \$d=99\rightarrow (d\bmod7)-2=-1\$, so we go from \$n=99\$ to \$n=10\$ (looking for the highest valid integer)
[Answer]
# [Desmos](http://desmos.com/calculator), ~~9+68+147+30+49+64+27+27+8+8+51=488~~ 9+68+93+30+49+28+9+9+8+8+33+31+27=402 bytes
Before you even go on I just want to say that I tried my hardest to golf this, but in the middle of doing this I already knew this was far from a competing answer. But by that time though, I was too far in, so I decided to continue. Upvote for effort? Or not.
## Expression 1: 9 bytes
```
g=[0,1,2]
```
## Expression 2: 68 bytes
```
f(n)=\operatorname{floor}(\frac{\operatorname{mod}(n,10^g10)}{10^g})
```
## Expression 3: ~~147~~ 93 bytes
```
h(a,b)=\left\{s[1]p[1]=0:j(\min(s[k(s)+1],p[k(p)+1]),q(s)+q(p)),d(j(\min(s),\min(p)))\right\}
```
## Expression 4: 30 bytes
```
q(a)=\left\{k(a)=0:a,0\right\}
```
## Expression 5: 49 bytes
```
k(a)=\operatorname{total}(\left\{a=0:1,0\right\})
```
## Expression 6: ~~64~~ 28 bytes
```
l(a,b)=d(j(\max(s),\max(p)))
```
## Expression 7: ~~27~~ 9 bytes
```
s=d(f(a))
```
## Expression 8: ~~27~~ 9 bytes
```
p=d(f(b))
```
## Expression 9: 8 bytes
```
w=h(a,b)
```
## Expression 10: 8 bytes
```
z=l(a,b)
```
## Expression 11: ~~51~~ 33 bytes
```
m(a,b)=j(10w[1]+w[2],10z[2]+z[1])
```
## Expression 12: 31 bytes
```
j(a,b)=\operatorname{join}(a,b)
```
## Expression 13: 27 bytes
```
d(a)=\operatorname{sort}(a)
```
[Try It On Desmos](https://www.desmos.com/calculator/bgn7vdhzux)
[](https://i.stack.imgur.com/0DYnP.png)
The function \$m(a,b)\$ is the function where you need to input the two numbers in.
Prettified version: [Try It On Desmos!](https://www.desmos.com/calculator/lw1da4lh3r)
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 19 bytes
```
q~m*_Wf%+:iA,-$(\W=
```
[Try it online!](https://tio.run/##S85KzP3/v7AuVys@PE1V2yrTUUdXRSMm3Pb/fyULCwslBSVLAzMlAA "CJam – Try It Online")
Takes input as two strings and outputs two integers.
```
q~ e# Push inputs "888" "906"
m* e# Cartesian product ["89" "80" "86" "89" "80" "86" "89" "80" "86"]
_Wf% e# Make a reversed copy ["89" "80" "86" "89" "80" "86" "89" "80" "86"] ["98" "08" "68" "98" "08" "68" "98" "08" "68"]
+:i e# Join and parse to integers [89 80 86 89 80 86 89 80 86 98 8 68 98 8 68 98 8 68]
A,- e# Remove the numbers from 0 to 9 [89 80 86 89 80 86 89 80 86 98 68 98 68 98 68]
$ e# Sort [68 68 68 80 80 80 86 86 86 89 89 89 98 98 98]
(\ e# Uncon from left 68 [68 68 80 80 80 86 86 86 89 89 89 98 98 98]
W= e# Get the last element 68 98
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 30 bytes
```
F²⊞υS⟦⌊Eυ⁺⌊⁻ι0⌊§υ¬κ⌈E⟦υ⮌υ⟧⭆ι⌈λ
```
[Try it online!](https://tio.run/##RY1PC8IwDMXv@xRlpwQqVK87edxhUvQ4diizumLXjv4Z@/a1VZyBQPJ@7yXjJNxohU7pYR2BExIe/QSRktYsMdyCU@YJiE3F8xSg75RRc5yhE0txcR097JoyeVOU1KxGpOSnn0Nr7nIr/osN8MJPZS62/Vaf4VWu0nkJEQdKvq8LUn@nLsEBm5SOjFW502HVbw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F²⊞υS
```
Input the two numbers as a pair of strings.
```
⟦
```
Separate the two outputs.
```
⌊Eυ⁺⌊⁻ι0⌊§υ¬κ
```
For each string, string take the minimum digit with `0` excluded and the minimum digit of the other string, then take the minimum result.
```
⌈E⟦υ⮌υ⟧⭆ι⌈λ
```
Of the pair and its reverse, take the maximum digit of each string, then take the maximum result.
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt#L187), ~~33~~ 32 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
─■myG‼<≥xα─6ö6‼≥<3≥\;]─gÅ£(_╓\╙α
```
Input as a paired list of digits.
Sometimes this language is so frustrating to work with.. :/ It has a cartesian builtin, but it only works on single lists (creating pairs of itself). It also has a convenient `‼` builtin to apply two commands separately to the stack, but this isn't implemented (yet?) for the minimum/maximum builtins (otherwise the `_╓\╙α` could have been `‼╓╙α`)..
[Try it online.](https://tio.run/##y00syUjPz0n7///RlIZH0xbkVro/athj86hzacW5jUAhs8PbzIACQL6NMZCIsY4FCqYfbj20WCP@0dTJMY@mzjy38f//6GgLHSCM1Ym21DHQMYuN5YqONgSyDIAiEBokYqQDhEARCA0SMQar1gHqNtIxgeoy0jEGm2OhY45TDRCC1QBhbCwA)
**Explanation:**
```
─ # Flatten the list of list of digits
■ # Take the cartesian product of this flattened list
m # Map over each pair:
y # And join them together to a single integer
# (note: since we're joining integers, the `m` implicitly converts them to
# integers as well, removing potential leading 0s)
G # Push 12
‼ # Apply the following two commands separated on the stack:
< # Slice to only keep the first 12 items in the list
≥ # Slice to remove the first 12 items from the list and keep the remainder
x # Reverse the second list
α─ # Merge the lists together again (wrap in a pair; flatten)
6ö # Loop 6 times, using the following 7 commands as body:
6 # Push 6
‼ # Apply the following two commands separated on the stack:
≥ # Slice to remove the first 6 items from the list and keep the remainder
< # Slice to only keep the first 6 items in the list
3≥ # Slice to remove the first 3 items of this sextet
\ # Swap the top two lists on the stack so the remainder is at the top
; # After the loop: discard the top of the stack (the final remainder)
] # Wrap all triplets into a list
─ # And flatten it
```
We now have all possible pairs (including their reversed pairs).
```
g # Filter this list of pairs by,
Å # using the following 2 commands as body:
£ # Get the length of this integer
( # Decrease it by 1
# (so 0 for single digit numbers; 1 for intended two-digit numbers)
_ # Duplicate this list of pairs
╓ # Pop and get its minimum
\ # Swap so the duplicated list is at the top
╙ # Pop and get its maximum
α # And pair them together
# (after which the entire stack joined together is output implicitly)
```
[Answer]
# Scala, 78 bytes
```
a=>b=>{val z=for(x<-a;y<-b;c<-Seq(""+x+y,""+y+x)if"09"<c)yield c;z.min->z.max}
```
[Try it online!](https://scastie.scala-lang.org/ysthakur/yMNczRpGSYunrPUN9CFq4A/30)
Apparently, just storing it in a variable is shorter than folding over all the permutations. Accepts two strings (curried) and returns a 2-tuple of strings.
# Scala, 109 bytes
```
a=>b=>((-1>>>1,0)/:(for(x<-a;y<-b;c<-Seq(""+x+y,""+y+x)if"09"<c)yield c.toInt)){(t,|)=>(t._1 min|,t._2 max|)}
```
[Try it online!](https://scastie.scala-lang.org/ysthakur/yMNczRpGSYunrPUN9CFq4A/26)
[Answer]
# [Zsh](https://www.zsh.org/), 90 bytes
```
for d (${(o)=${(s::)@}})((e&~a&&(a=e,b=d),${z=$d},f=e,e=d))
<<<${z/0/$a}${z/[^0]/$b}\ $d$f
```
[Try it online!](https://tio.run/##LYrLCsMgEEX3foWLQWZA0FgoJij0P/oAg0p3gWaXYH/djtDFuRwO99jfvSJhr9tHZolw4kaRd18WurVGiEV9k1KYYtFrzKThPCLkpiuHwoFECIGjsQZSG3J/2aeBtT0kZKidhKhychc5T47Ney9nex3N2gGbc27w/7H1Hw "Zsh – Try It Online")
`${(o)=${(s::)@}}` sorts the digits, which we loop over. By the end of the loop, we have the following parameters set:
* `z`: The smallest digit
* `a`: The smallest non-zero digit
* `b`: The second-smallest non-zero digit
* `d`,`e`: The largest digit
* `f`: The second-largest digit.
If `z` is zero, then the first number is `$a$z`. If `z` is non-zero, then the first number is `$z$b`.
[Answer]
# [Perl 5](https://www.perl.org/), ~~98~~ 94 bytes
```
sub{@i="@_"=~/./g;(sort grep!/^0/,map{/./;$i[$&].$i[$'],$i[$'].$i[$&]}<{0,1,2}{4,5,6}>)[0,-1]}
```
[Try it online!](https://tio.run/##ZZDRToMwFIbveYojaUabVGjLIGyI4QW8825BorEQjFsRmHMheOkD@Ii@CLZjCZme9OQ0//fnP8mpZfMajNsjKpKx3T/1aZXYaW4nn57rlTFuVdNB2cj6yntgHt0@1r0GMao2aJG5ZjgZnYY7icNNzyinYuiXNKDhcEs2jF7zbBhja99KuJdtt17fqUbGVqEavHk7YGBcgL8MgPsQCCAZtUDXCXHhw0pjzmHlX6IoimDFQgj1iP4go7EIQvYPccbObTIvkBDi3OaRjFj9CW6PGKmdpKg7KJrKj5okKcrjM4O0VB0ksEDFbCMTrVoML6raYQccanxkWmdq1k3irNsFBpMDJgcI/Hx9w7QD3lv9025bxw/Wszblnb5ntSvj8Rc "Perl 5 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
I/O as an array of digit arrays.
```
rï cá fÎÍé ¯2
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=Tm3s&code=cu8gY%2bEgZs7N6SCvMg&footer=Vm3s&input=OTAxCjEwOQ)
```
rï cá fÎÍé ¯2 :Implicit input of array
r :Reduce by
ï : Cartesian product
c :Flat map
á : Permutations
f :Filter by
Î : First element (0 is falsey)
Í :Sort
é :Rotate right
¯2 :Slice to second element
```
[Answer]
# APL+WIN, 30 bytes.
Index origin = 0. Prompts for input numbers as strings:
```
(⌊/n~⍳10),⌈/n←,⍎¨(⌽¨n),n←⎕∘.,⎕
```
[Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlwPWooz3tv8ajni79vLpHvZsNDTR1HvV06OcBJXUe9fYdWgGU23toRZ6mDkgIqO9Rxww9HSD9H6iT638al7qhkbE6l7qloZE6F5BnYWEB4hmYgXmGBgbqUBLIMzICqoGQAA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~77~~ ~~74~~ ~~70~~ 53 bytes
-17 bytes thanks to [Dingus](https://codegolf.stackexchange.com/users/92901/dingus)!!
```
->x,y{((x-[0]).product(y)+(y-[0]).product(x)).minmax}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf165Cp7JaQ6NCN9ogVlOvoCg/pTS5RKNSU1ujElWoQlNTLzczLzexovZ/QVFmXolCWnS0oY6RjnGsTrSlDpAVG8tVUFpSzIUka6BjAJSF0OiylkBRM6CshQ4QYsgaAU02AspCaEyTIfZilzXXsQSaCLLXGC77HwA "Ruby – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 62 bytes
```
q l=[minimum,maximum]<*>[filter(>"1")$mapM id=<<[l,reverse l]]
```
[Try it online!](https://tio.run/##JYzLasMwFET3/orBeJGU62ApEFyQvMuu@QIhiIrVVlSSE9nN4@tdiWxmDsO958fMv9b7db3CSxVcdOEvUDCP0lq8DerL@cWmzVCzetsEcznBjVII5SnZm02zhdd6DcZFSIxTBShDn/Sgp4ZocZ/SOGOHlwabc5yWo7fhjJraegvRDPi2y4eLNr9ekosLGlyLQ0upiibvRb8yvie8M44WjGXaV33f5@4OeTkU6ivWdYQc5aYQqzjnhBx5edE/ "Haskell – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 77 bytes
```
MinMax@Select[FromDigits/@Join@@Permutations/@Tuples[IntegerDigits/@#],#>9&]&
```
[Try it online!](https://tio.run/##NYpBB8MwGED/Sig9haQZ0x42OdTYKGW7VQ9Rnyw0yaRfGZHfnqWHHR7P86zCN1iFZlFZX/Jg3KC@8gkrLDjdgre90QY3Jh/eOClHCHbHsntX2mv/rLBNd4egIfzPaqbVtavnOo/BOCRMaiZJjI04UdI1IlES27Ytzs@HN5zTwqFCCFpIKecf "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 17 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ïV cVïU)Íf¨A é v2
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=71YgY1bvVSnNZqhBIOkgdjI&input=IjEwMCIKIjIwMCI)
```
ïV - pair each digits
Í - sort
f¨A - remove if <10
é - rotate array
v2 - return first 2 elements ( Max , Min )
```
* Thanks to @Shaggy for spotting an error, fixed by adding `cVïU`
[Answer]
# [Perl 5](https://www.perl.org/) `-MList::Util=min,max -p`, 89 bytes
```
s/.\K/,/g;s/ /}{/ for($b=reverse),$_;$_=min(@a=grep$_>9,glob("{$_}"),glob"{$b}").$".max@a
```
[Try it online!](https://tio.run/##HY27CoMwAEV3vyJIBoWYV7H4wOLeduxWCApRAtGEREpB/PWmaYfDPXe510qnyxA8wc8rQWRuPQHk2AmYjMvg2Dn5ks7LHEHRQtEtas36oZudtFBcajRrM2bpDsWR5v8SfYyOYYqX4d0PIdSMA8ZPSVVVoKbnhFEKIgnnHEQ@xm7KrD4U9xJTRmPelN@a5rEp/ftDcScUVn8B "Perl 5 – Try It Online")
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 126 153 158 bytes
```
for n in {10..99}; {
t=$[n/10]
o=$[n%10]
([[ $1 =~ $t && $2 =~ $o ]]||[[ $2 =~ $t && $1 =~ $o ]])&&A+=($n)
}
echo $A-${A[-1]}
```
[Try it online!](https://tio.run/##TcmxCsIwFAXQ/X3FHZ6hRVqbWoUgGfIdIYOKUpcEtFsaf/1JHMTtwLmcX7PIPT0R8YjIeuh7Y8oJmRbLPu70EChVbaoa78Ea9g1eoBR4/DohhHWtN/6d/l2rlNvahmNLhW7XOYFdx9n5TodCIjIdJznszQc "Bash – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 76 bytes
```
(a,b)=>[(e=a.map(c=>b.map(d=>[c+d,d+c])).flat(3).sort()).find(x=>x>9),e[17]]
```
[Try it online!](https://tio.run/##LY7RboMgFIbveYpzV0iRCiadTYN3ewpHUkTsXKgYJY3Lsmd3x7qbcz6@/Jz8X/ZpZzf1Y8qG2Pq10yu1vGG6qqnXVjzsSJ2umhe0aN2x5e3RGcZEF2yiBRNznBLd3v3Q0kVXS3Vh3NfyzZg1@Tk5O3vQcCNSFRwuUkEGUiIVpCxL3PkZzXmjksg854Bjy2wkiVKKAw40O@13diPRFIrcRJr6B8UuY@gTPXwMB@wTp3frPmkAXcEPAXjaCWrLoeGwcPg2WCr8/zjVHDJzPLEr5lwc5hi8CPFO93hHayGENRy23RiG8DqB@V92Xf8A "JavaScript (Node.js) – Try It Online")
Input as two lists of character, output as two strings.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~147 144~~ 141 bytes
```
#define g(x,d)x%q!=d&x/q%q!=d&x/100!=d
v,d=1,q=10;f(a,b){for(v=q;g(a,v/q)|g(b,v%q)&&g(b,v/q)|g(a,v%q)||printf("%d ",v)&&(v=99,d=-d)<0;v+=d);}
```
[Try it online!](https://tio.run/##dY/RboMwDEXf@xUeEyjRgoiD1IKy/MleKGkQ0saWbsqQSn99mRtU7YW9WNe@x1d2Xw59H@OjPblxOsHAZmH5nPsHY4u58neBUpLYBWENCm9Qasc6ceQX935mwXg9UBsqz5eBHUXIPS@KpNZRl0bL8nEepy/HstxCJgIxtNu2FFpa/ix1eDKW62skCN66cWIcLjsAx1DVAlpUXMM94mXKqKsqQCSrTljTNKTlfgvb36xmTZNSAJXNtJuFCVNKCaCyha3W323/YEhYvWKHlg7Aehs7pBeu8ad3r93wGcvvXw "C (gcc) – Try It Online")
### How?
The macro `g(x,d)` checks whether the digit `d` appears in the 3-digit integer `x` by testing \$x\bmod 10\$, \$\lfloor x/10\rfloor\bmod 10\$ and \$\lfloor x/100\rfloor\$. It returns a falsy value if successful.
We look for the first `v` such that \$\lfloor v/10\rfloor\$ appears in `a` and \$v \bmod 10\$ appears in `b`, or the other way around. We do it once by going from \$v=10\$ to \$v=99\$ and once by going from \$v=99\$ to \$v=10\$, to get the lowest and highest valid integers respectively.
[Answer]
# [R](https://www.r-project.org/), ~~138~~ ~~134~~ ~~128~~(thanks pajonk) ~~121~~ 117 bytes
```
k=t(t(expand.grid(strsplit(scan(,""),""))));class(k)=class(1);a=c(A<-k[,1],B<-k[,2]);b=c(B,A);range(10*a[a>0]+b[a>0])
```
[Try it online!](https://tio.run/##JYhBCoMwEEWvIq5mbCqJGytpCnoNyWKMIhIJksmit4/Wfni8x485e5MgwfI9KMz1GrcZOEU@9i0BOwogyhJ/XNNuJ2bwaP6hUJNx0L@ffhTKiuGOxqKernsQPepIYV1AyYpG@kj7mG5hbrtXoWSTTw "R – Try It Online")
Another solution that takes input as a list of digits, allowed per the rules:
# [R](https://www.r-project.org/), ~~110~~(thanks pajonk) ~~103~~ ~~99~~ 93 bytes
```
i=scan();k=expand.grid(i[1:3],i[4:6]);a=c(A<-k[,1],B<-k[,2]);b=c(B,A);range(10*a[a>0]+b[a>0])
```
[Try it online!](https://tio.run/##HchLCoAgFEDReatwqGWhFf3MQLchDl4lIYGETdq9RaN7OTElL@8NAibilO65IOzVEf2OveFTY6k37dRZIkBuWM3laSi3VP9Tf7x@rKkiIkI4HOYsBwMLs8X6h6QejWjIOGKoTi8 "R – Try It Online")
[Answer]
# C (MinGW), ~~150~~ 146 bytes
-4 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)
The TiO link needs `-lm` but MinGW does not.
```
M,m,x,y,c,t=10;f(a,b){for(M=0,m=99;a;a/=t)for(c=b;c;c/=t)M=fmax(fmax(x=a%t*t+c%t,M),y=c%t*t+a%t),m=y<m&y>9?y:m,m=x<m&x>9?x:m;printf("%d %d",m,M);}
```
[Try it online!](https://tio.run/##TY9RboMwEES/wyksS1R2ulEx0Ajiuj0BN@iPMYFGipMqQRUoytVLd52g9GeZecwOi1t1zk1TBR4GGMFBb1SiW2Ghlpf2eBKVScCbstRW2xfTS2LO1NppR7YyrbeDCGMwNu6X/bOLe6gkjMYFi1Bixfjmn8b38mPceHQDugHdsPH6@7Q79K3gccPihuMlldTX6ee4a1gn8BWzwOhRA3Nf9sSWWxldosVjDXCPrRgHStZSRwv6gZuaU0zEZ/l5wMwW8TWKqNHb3UGEsk6oNANWqhQYVwpVxmm9E0VRoEvWyNekijtXSQIsDK5IqTtPCZWBp6TSmadYHQa/qbmHUlk@9@QPjvfkr/RdlQNbZ//5rYeOzUL@Ov26dm@787Ta@z8 "C (gcc) – Try It Online")
] |
[Question]
[
We haven't had any nice, easy challenges in a while, so here we go.
Given a list of integers each greater than \$0\$ and an index as input, output the percentage of the item at the given index of the total sum of the list.
Output should be whatever the natural representation for floats/integers is in your language (unary, decimal, Church numerals etc.). If you choose to round the output in any way, it must have at minimum 2 decimal places (when reasonable. \$1.2\$ doesn't *need* to be rounded, but \$1.20\$ is also perfectly acceptable).
Indexes can be either 1-indexed or 0-indexed, and will always be within the bounds of the array.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins!
## Examples
Using 1-indexed and rounded to 2 d.p
```
list, index => output
[1, 2, 3, 4, 5], 5 => 5 / 15 => 33.33
[7, 3, 19], 1 => 7 / 29 => 24.14
[1, 1, 1, 1, 1, 1, 1, 1, 1], 6 => 1 / 9 => 11.11
[20, 176, 194, 2017, 3], 1 => 20 / 2410 => 0.83
[712], 1 => 712 / 712 => 100
```
Or, as three lists:
```
[[1, 2, 3, 4, 5], [7, 3, 19], [1, 1, 1, 1, 1, 1, 1, 1, 1], [20, 176, 194, 2017, 3], [712]]
[5, 1, 6, 1, 1]
[33.33, 24.14, 11.11, 0.83, 100]
```
[Answer]
# [Python 3](https://docs.python.org/3/), 26 bytes
```
lambda i,a:a[i]/sum(a)*100
```
An unnamed function accepting an integer (0-indexed index) and a list which returns the percentage.
**[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSFTJ9EqMTozVr@4NFcjUVPL0MDgf0FRZl6JRpqGiU60oY6RjrGOiY5prKbmfwA "Python 3 – Try It Online")**
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 9 [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 infix function. Takes index as left argument and list as right argument.
```
100×⌷÷1⊥⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///39DA4PD0Rz3bD283fNS19FHXov9pj9omPOrte9Q31dP/UVfzofXGj9omAnnBQc5AMsTDM/g/kPYK9vfTgNLq0aY6CoY6CmZg0jBWXTPt0Aq4XDRQzEhHwVhHwURHwTRWRyHaHMwztASxDSF6MBFI0sgAyDAHGWsJ1GtkYAjSCTbB0Cg2Vh0A "APL (Dyalog Unicode) – Try It Online")
`100` one hundred
`×` times
`⌷` the indexed element
`÷` divided by
`1⊥` the sum (lit. the base-1 evaluation) of
`⊢` the right argument
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 22 bytes
```
x=>y=>x[y]*100/x.Sum()
```
[Try it online!](https://tio.run/##bZBLT4NAFIXX5VeMrAY7xRnoQ62QuFA3mhpdmFhZUDqkUyttYFAI4bfjHV6pj4RkuPd@59wzEySjIBHVbRoFV@t9utrxpUfqSkSSNB3XDZ0qc9zccbNl7p0ySs8y8zn9wEY11z79GInokEqGHBTxL9TZLL3iuCwYQRZBNkFjgiYl@cEWs3rCLn73QfT/9xu0KDRnU@UB/hZlyvHPFmaV5VFkq4kMk0ntOm29GyTmSbqTPWLbpg0ZrbHJYANjJgOWmucqN6WggRdDAnBIslXHXAv3MfeDDVZu2CcrA9a2j2W@igNuQhCckdxw3PowDFRog8cYzLBvzLvf1Yipoo0F7g@@3JhP@zRa4xDAGiBWx/DswAPJ1wA2t1iK4dCDoQgRVgYnTs/UCwcvsZAc6zedsKDweHd7iQpW6qSHifJTWwbb4RCOUhvwXcJRK1@kEm50qdR6j9azexHB/C3SoVNqKsYWuYganRIUSPJEBn4C8UJf7PgaLLaAHy@4Hi3e/RxMqm8 "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ị÷S}ȷ2×
```
A dyadic Link accepting an integer, one-based index on the left and a list of numbers on the right which yields the percentage.
**[Try it online!](https://tio.run/##y0rNyan8///h7u7D24NrT2w3Ojz9////pv@jDXUUjHQUjHUUTHQUTGMB "Jelly – Try It Online")**
### How?
```
ị÷S}ȷ2× - Link: integer, i; list, L
ị - (i) index into (L)
} - use right argument:
S - sum (L)
÷ - divide
ȷ2 - literal 10^2 = 100
× - multiply
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
è²O/т*
```
A full program taking the index then the list. Uses 0-indexing.
**[Try it online!](https://tio.run/##yy9OTMpM/f//8IpDm/z1LzZp/f9vwhVtqGOkY6xjomMaCwA "05AB1E – Try It Online")**
### How?
```
è²O/т*
è - index (input 1) into (input 2)
² - push 2nd input
O - sum
/ - divide
т - push 100
* - multiply
- print top of stack
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 47 bytes
```
a->i->1e2*a[i]/java.util.Arrays.stream(a).sum()
```
[Try it online!](https://tio.run/##bZFRa4MwFIXf@ysuBUFL6tS1K2tXoTAGe9jT9iY@ZDWWdGokuZYV8bd3SXTt6IoGyfluzvXc7OmBTvfZ14mXtZAIe733G@SFP1mN/ml5U22Ri8rAbUGVgjfKK2hHAHXzWfAtKKSoPwfBMyg1c99R8mqXpEDlTnm2FOBl8HniFSYp@RDPQh9nZ/m1QrZjMo4hh/WJTmM@jUMWTWjC07vL72ykpEflK5SMli71fNWUrnda2R7W2jyATKGC9dAboIU2JBARuCcwIzDviNFm0EFHLiULy8NHTVsIrqA@f/u11fOr6ijQZPFg3HS/KAiN903fRRgZPTirXR8mFxLcIZHNs@xTeedQFuoh64noqAYmQbq6QL0y9v2LwvQPfT8qZKUvGvRrfVmYu2NHEXCyJTjKqcYEhkGj6G/TtW080nsSyH1a18VxkPvNRvV36toaz@ubdSOzutMP "Java (JDK) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 10 bytes
```
100*{%1#.]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DQ0MtKpVDZX1Yv9rcilwpSZn5CuYKKQpGCoYKRgDWaYQIQOgkDlQwNASwjcFK0GDCKVGBgqG5mZA1SZApiFQI5Iphkb/AQ "J – Try It Online")
0-indexed
[Answer]
# [R](https://www.r-project.org/) 28 bytes
```
function(n,l)100*l[n]/sum(l)
```
[Try it online!](https://tio.run/##K/qfVpqnYKMLopJLMvPzNPJ0cjQNDQy0cqLzYvWLS3M1cjT/5wBVKBhamXKBlCqYcgEVA9UpAGW4AA)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 64 bytes
0-indexed. The only fun bit was the realization that `1e2` is a `double`, saving a byte over `100.`!
```
float f(v,n,t)int*v;{n=v[n];for(t=0;*v;t+=*v++);return n*1e2/t;}
```
[Try it online!](https://tio.run/##VZDRboMgFIbvfYoTF1sEumm3rNkY3YM0vaAoLYnFRtGLNT47A6wXvYAc/gPf/x/k5iylc6pphQWFRmqozbWxeGR3w8eDOTLVdsjygnnJEo5HQnLW1XboDBhc1ts3yyb3oo1shqqGn95Wun297JMnqdGnoCUeDVehDQqF6M6SgryIDjD2hzGHewIQWngUTU8BawpmuLIkyD6eF7kUTdNKND/u9V/dqkDL8/k1QAis@Qy4DTbw0fqwzlk03GxgtQKENRe21QgTEp1999Z5jEJp1mdVGrwJ4TwG@U3Tb69E0d@MLj5OwC2mEHI@I9mjsXCPFLIK@B4ylcaxKMwjxcPCnZKw/Pb444Ilk3PbwpW7T1d@ffiy3Ll3V7jiHw "C (gcc) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~20~~ 18 bytes
```
i?a=a!!i/sum a*100
```
A dyadic operator (`?`) taking the (0-indexed) index on the left and a list on the right which yields the percentage.
**[Try it online!](https://tio.run/##y0gszk7Nyfn/P9M@0TZRUTFTv7g0VyFRy9DA4H9uYmaegq1CSj6XgoJCQVFmXomCioKJgr1CtKGOgpGOgrGOgomOgmnsfwA "Haskell – Try It Online")**
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 15 bytes
```
100##[[]]/Tr@#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b739DAQFk5Ojo2Vj@kyEFZ7X9AUWZeSbSyrl2ag4NyrJq@QzVXdbWhjpGOsY6JjmktCAEFzIFcQ8taHUMwz1AHDcIkjAx0DM3NgCpNdIwMDIGaYBLmhkYgJlftfwA "Wolfram Language (Mathematica) – Try It Online")
Input as `list, index`
[Answer]
# JavaScript (ES6), 30 bytes
Takes input as `(array)(index)`, where *index* is 0-based.
```
a=>n=>a[n]*100/eval(a.join`+`)
```
[Try it online!](https://tio.run/##dc/fCoIwFMfxe5/iXGrZPGebmRf6IiI4zEKRLTJ8fdvsD6U1ZLALP3x/nRrVUF/by22nzbGZTtmkslxnuSp0uSHEqBlV7yvWmVZX2yqYaqMH0zesN2f/5BcUAg9BhCBDiMvAl0EAXyeKIIYIKHaPLAchmBDeQklmglIL4BJ4KYlVePpUuGQkvXXL78@ysWOtQlaZEacQMaKlwtH@kexdjt3EkVzcZ5hVOLoYSegUZIf1IOJ/t7wHEYfH7VIQpzs "JavaScript (Node.js) – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 9 bytes
```
)1Gs/100*
```
[Try it online!](https://tio.run/##y00syfn/X9PQvVjf0MBA6///aEMdIx0zIx1jnVguYwA "MATL – Try It Online")
### Explanation
```
implicitly take two inputs
) get the entry within the first input at the index specified by the second
1G push the first input onto the stack again
s compute the sum
/ divide first entry of the stack by this number (the sum)
100* multiply by 100
```
[Try it online!](https://tio.run/##y00syfn/X9PQvVj///9oQx0jHTMjHWOdWC5jAA "MATL – Try It Online")
[Answer]
# [PHP](https://php.net/) (7.4), 35 bytes
```
fn($l,$i)=>100/array_sum($l)*$l[$i]
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwMWlkmb7Py1PQyVHRyVT09bO0MBAP7GoKLEyvrg0FyiqqaWSE62SGfvfmosrNTkjX0ElTSPaUEfBSEfBWEfBREfBNBZIaVpz/QcA "PHP – Try It Online")
Input index is 0-based.
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), ~~15~~ 14 bytes
-1 byte thanks to ngn!
```
{100*x[y]%+/x}
```
[Try it online!](https://tio.run/##y9bNz/7/P82q2tDAQKsiujJWVVu/ovZ/mkK0kYGCobmZgqGliYKRgaG5grG1gkHsfwA "K (oK) – Try It Online")
0-indexed
[Answer]
# [TI-Basic](http://en.wikipedia.org/TI-Basic), [12 bytes (12 tokens)](https://codegolf.meta.stackexchange.com/questions/1541/how-to-score-ti-basic)
```
Prompt X
Ans(X)E2/sum(Ans
```
1-indexed
Takes the list in [`Ans`](https://codegolf.meta.stackexchange.com/a/8580/44694) and prompts the user for the index
[Example run](https://i.stack.imgur.com/ZP69c.jpg)
Explanation:
```
Prompt X # Prompt the user for the index
Ans(X)E2/sum(Ans
Ans(X) # The value at the Xth index in the list
E2 # times 100
/sum(Ans # Divided by the sum of the list
# The result of the last expression in a program is implicitly returned
```
[Answer]
# [Red](http://www.red-lang.org), ~~31~~ 29 bytes
-2 bytes thanks to ErikF
```
func[b i][1e2 * b/:i / sum b]
```
[Try it online!](https://tio.run/##XcsxDsIwEETR3qf4NU2ySxKLHIPW2sbEllwQoUDO77hCAU01o3lbWuo9LcFcnql5Xx8hUixIUi7Ebi50vPcn0eprK@uHTBCUKwOjMYL77r6tcjPEna5/MaaT0B7xU0MD2kvzP9iLtl4P "Red – Try It Online")
[Answer]
# [Factor](https://factorcode.org/), 46 bytes
```
: f ( i l -- n ) dup [ nth ] dip sum / 1e2 * ;
```
[Try it online!](https://tio.run/##XYwxDoJAFAV7TjGlmqAsgkQ4gKGhMVbGgsCiRFgQlsIYz46rFBrzm/cmb36RZrrpxsM@TnYhV9kpWVGn@kIvb4NUmexpO6n1ve1KpYmsOAnJmlyem6oYQwpmlFTYNoo5@dByRBn/RF629EPNCiFdFkSjxwOByxoPn6eRl5ZjWGCI2E4Ay/@s/u@7dh1EsDGCZ6J4uz@fhDu18QU "Factor – Try It Online")
0-indexed
[Answer]
# [Zsh](https://www.zsh.org/), ~~32~~ 30 bytes
***-1** thanks to @ErikF, using `1e2` instead of `100.`.*
```
<<<$[1e2*$@[`<&0`]/(${@/#/+})]
```
~~[Try it online!](https://tio.run/##qyrO@J@moVn938bGRiXa0MBAT0vFITrBRs0gIVZfQ6XaQV9ZX7tWM/Z/LVeagqGCkYKxgomCqQJQtYIpUMQcyDe0VAACkIjhfwA "Zsh – Try It Online")~~
[Try it online!](https://tio.run/##qyrO@J@moVn938bGRiXaMNVIS8UhOsFGzSAhVl9DpdpBX1lfu1Yz9n8tV5qCoYKRgrGCiYKpAlCxgilQxBzIN7RUAAKQiOF/AA "Zsh – Try It Online")
Accepts the list as arguments and the index on stdin.
```
<<<$[1e2*$@[`<&0`]/(${@/#/+})] # $[ arithmetic ]
$[ `<&0` ] # capture stdin
$[ $@[ ] ] # index into the arguments
$[1e2*$@[`<&0`] ] # multiply by 100.0 (casts to float)
$[ (${@/#/+})] # prepend each element with + and add
$[ / ] # divide
<<< # print to stdout
```
[Alternate **30 byte** solution](https://tio.run/##qyrO@J@moVn9v9hWQ1slzkGTy8bGRiXaMNVIS8UhOsFGzSAhVr849n8tV5qCoYKRgrGCiYKpAlCNgilQxBzIN7RUAAKQiOF/AA "Zsh – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 34 bytes
```
param($l,$n)$l|%{$i+=$_};$l[$n]/$i
```
[Try it online!](https://tio.run/##bY7dCoJAEEbvfYoBp3Bp0Z3dNZOwF4kIL5SEzcQuujCf3XbzhwKX2YsP5sz5mseraJ@3wpgBy6wbmrzN7wEajjVD8950WO0yvPZHNGesLxFWQ@95WywhIA6Sg@KgOcQMNPjw87ITxBABxVNQKlRqBJMvRSkD8c/MYGJBmU5B6pD0YlwfZl2@3SULpvMVopBoBKWwS8neSW1ZKchVWPROIpxSk3BBhIe5KUkGqy3npiQj@yfh8AE "PowerShell – Try It Online")
Shame parameters are so dang expensive in Powershell.
[Answer]
# Scratch 3.0 ~~24~~ 23 blocks/~~239~~ 228 bytes
[](https://i.stack.imgur.com/fBloX.png)
*Alternatively in SB syntax*
```
when gf clicked
set[s v]to(0
ask()and wait
repeat until<(answer)=(
add(answer)to[m v
ask()and wait
end
set[n v]to(item(length of(n))of(m
repeat(length of((m)-(1
change[s v]by(item(1)of[m v
delete (1)of[m v
end
say(((n)/(s))*(100
```
*Saved 11 bytes thanks to @JoKing*
[Try it on scratch](https://scratch.mit.edu/projects/333497999/)
## Answer History
[](https://i.stack.imgur.com/kWVww.png)
*Alternatively in SB syntax*
```
when gf clicked
set[s v]to(0
ask()and wait
repeat until<(answer)=(
add(answer)to[m v
ask()and wait
end
set[n v]to(item(length of(n))of(m
delete(n)of[m v
repeat(length of(m
change[s v]by(item(1)of[m v
delete (1)of[m v
end
say(((n)/(s))*(100
```
[Try it on scratch](https://scratch.mit.edu/projects/333497999/)
Input is in the form of:
```
item1
item2
...
itemN
index
```
I really should stop doing this to myself. But it *is* very fun!
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 13 bytes
```
c*100@hQeQshQ
```
[Try it online!](https://tio.run/##K6gsyfj/P1nL0MDAISMwNbA4I/D//2hDHQUjHQVjHQUTHQXTWCALAA "Pyth – Try It Online")
First time using Pyth so theres probably some pretty big optimizations here, but I dont know where they are...
0-index, takes input as `list, index`
[Answer]
# [Go](https://golang.org/), 79 bytes
```
func f(a[]float64,i int)float64{s:=0.
for _,v:=range a{s+=v}
return a[i]/s*100}
```
This has a nice amount of accuracy. It takes a Go slice and uses `range` to calculate the sum.
[Try it online!](https://tio.run/##PY5NCoMwFIT3OcXDlWmDjbYoteQO3YuUhxgJ1URidBNydpv@0FkMDAzfzGD2GbsnDj1MqDQhapqNdZDIySW7XHUHMsWmlaNBV16YAqUd/SW/1IJnRBoLD7bVwqKOHPTLUWyB2N6tVgM2qj0th5zz8OW9d1IKnkAUQi3gj/cFZ5BXZbTrhUHB84rBOXya8VB2t3F91Gm8xIBTeiNhfwE "Go – Try It Online")
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), ~~7~~ 6 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
§\Σ/♀*
```
0-based indexing.
[Try it online.](https://tio.run/##y00syUjPz0n7///Q8phzi/UfzWzQ@v8/2lDPQMcIiI2B2ASITfUMYnVMuKLNoWKGliABAy6wQgI4VseUK9rIAMQxNwPrBZloZGAINQxsjrmhEZgFAA)
**Explanation:**
```
§ # Index the (implicit) second input-integer into the first (implicit) input-list
\ # Swap so the first (implicit) input-list is at the top of the stack
Σ # Take the sum of that input-list
/ # Divide the earlier indexed number by this sum
♀* # Multiply it by 100
# (after which the entire stack joined together is output implicitly as result)
```
[Answer]
# [Snap!](https://snap.berkeley.edu), 79 bytes (scratchblocks syntax)
```
((L)(i))::hat
report((combine(L)using((()+()@addInput)@addInput::grey ring))/(i
```
This is a "custom block" (function), and it takes a "list" (array) as the first argument and the idnex as the second argument.
Wow, having to manually mark hats/grey rings/grey ring inputs really makes short Snap! code in scratchblocks look relatively ugly.
[Answer]
# Erlang 41 bytes
```
f(X,N)->lists:nth(N,X)/lists:sum(X)*100.
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), ~~14~~ 12 bytes
*-2 bytes thanks to @luis-mendo*
```
_@=\:+d/1e2*
```
[Try it online!](https://tio.run/##S85KzP1voBBtrmCsYGgZ@z/ewTbGSjtF3zDVSOv/fwA "CJam – Try It Online")
0-indexed. Takes input as `index [list]`
# Explanation
```
code | explanation
-------------|------------
_@=\:+d/1e2* | whole program
@= | get the item at the index
_ \:+ | sum the array
d | convert to a *d*ouble
/ | divide
1e2* | multiply by 100
```
[Answer]
# [Perl 5](https://www.perl.org/) `-ap -MList::Util=Sum`, 19 bytes
```
$_=100*$F[<>]/sum@F
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3tbQwEBLxS3axi5Wv7g018Ht/39DBSMFYy7Df/kFJZn5ecX/dRML/uv6@mQWl1hZhZZk5tgC1QEA "Perl 5 – Try It Online")
Take the list, space separated on the first line, the index (0-based) on the second.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
gV
*L/Vx
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Z1YKKkwvVng&input=NApbMSwgMiwgMywgNCwgNV0)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 102 bytes
```
\d+
$*
^(1)+((?<-1>.(1+))+)
$3$2
,
\G1
10000$*
;(1+)\1
$1;$1$1
r`.*(\2)*;(1+)
$#1
+`^..?$
0$&
..$
.$&
```
[Try it online!](https://tio.run/##XYs9DsIwFIN3X4NHlTSPKE7/hILo2EtEqEgwsDBU3D@kjNiL5c/enp/X@16OZllLfjhIi5uhdcbMlxOv3tBZ6yykkwgF8kIwVNVh2mEmhEkoxLb61uRo2x@AHAi33ryfBUEaeC/w0pQyJGrUTnsdwDTVxDPGWv65whiU01h5rzGwTvcD4xc "Retina 0.8.2 – Try It Online") Link includes test cases. Takes input as `index;list,...`. Explanation:
```
\d+
$*
```
Convert to unary.
```
^(1)+((?<-1>.(1+))+)
$3$2
```
Index into the list.
```
,
```
Sum the list.
```
\G1
10000$*
;(1+)\1
$1;$1$1
r`.*(\2)*;(1+)
$#1
```
Multiply the desired value by 10000 and divide by the sum with rounding by adding on half of the sum first.
```
+`^..?$
0$&
```
Ensure that the result has at least three digits.
```
..$
.$&
```
Insert a decimal point at the second last position.
] |
[Question]
[
# Task
Build a calculator, that takes any string, from a file, stdin or whatever, and adds up all the values of the chars.
Example
```
Input
Hello World!
Output
1085
```
# Rules
The calculator needs to accept just ASCII encoding.
The shortest code wins.
# Notes
Regarding to the comment of m.buettner, I need to say, I didn't thought of the multibyte part.
So I leave it as a bonus thing aswell.
The calculator should be run as written, so no need to modify before compiling or interpreting.
# Bonus
Thanks to [Synthetica](https://codegolf.stackexchange.com/users/18638/synthetica), here is one more bonus,
>
> The program that has the lowest output when you use its code as its input wins gets a star.
>
>
>
I don't want to modify it completly.
If you write it additional to output the (right) value in UTF-8 you get a star.
The code that executes fastest on my Laptop (Lenovo Yoga 13 Intel Core i5 3317U 1.7Ghz, 8GB RAM, 128GB SSD, Intel HD 4000, Windows 8) gets a star.
Web codes will run first under IE11 with [chakra](http://en.wikipedia.org/wiki/Chakra_(JScript_engine)) and then in FireFox 29.0.1 with [SpiderMonkey](http://en.wikipedia.org/wiki/SpiderMonkey_(software))
Linux code will run on a Raspberry Pi with Raspbian.
The teststring is this:
```
q/%8hnp>T%y?'wNb\},9krW &D9']K$n;l.3O+tE*$*._B^s!@k\&Cl:EO1zo8sVxEvBxCock_I+2o6 yeX*0Xq:tS^f)!!7=!tk9K<6#/E`ks(D'$z$\6Ac+MT&[s[]_Y(`<g%"w%cW'`c&q)D$0#C$QGf>?A$iawvc,}`9!('`c&q)D$0#C$QGf>?A$iawvc,}`9!(
```
Have fun coding :)
# Bonusscoring
I plan to do the scoring at this Saturday so the 07.06.14, all answers after that date won't get bonus points ;)
You can download the code I gonna use for testing [here](https://github.com/DerKnerd/Application-Speedtest) feel free to fork and improve it :)
Little update because of the bonus, my laptop is partially broken so I will do it probably next weekend, I am really sorry for that :(
[Answer]
# GolfScript, 4 characters
```
{+}*
```
Simply uses the fold operator (`*`) to add up all the characters.
If it has to work with the empty string, 9 chars:
```
{{+}*}0if
```
Thanks to @PeterTaylor for providing an alternative 6-char version that works with empty string:
```
0\{+}/
```
[Answer]
# APL (8)
```
+/⎕UCS⍞
```
Explanation:
* `+/` sum of
* `⎕UCS` unicode values of
* `⍞` character input
[Answer]
# Haskell 36
```
main=interact$show.sum.map fromEnum
```
[Answer]
# Shell+GNU tools, 29 bytes
```
echo `od -An -tuC`|tr \ +|bc
```
Takes input from stdin:
```
$ printf "%s" 'Hello World!' | ./addchars.sh
1085
$
```
Own score: 2385
---
# c, 52 bytes
```
c;main(p){while(~(p=getchar()))c+=p;printf("%d",c);}
```
Compile with (some warnings produced):
```
gcc addchars.c -o addchars
```
Takes input from stdin:
```
$ printf "%s" 'Hello World!' | ./addchars
1085 $
```
Own score: 4354
[Answer]
# Javascript (*ES6*) 51
```
alert([...prompt(x=0)].map(y=>x+=y.charCodeAt())|x)
```
[Answer]
# 8086 Assembly (16-bit) - 47 41 bytes
The contents of the `test.com` file are:
```
98 01 c3 b4 01 cd 21 3c 0d 75 f5 89 c7 c6 05 24
89 d8 b1 0a 4f 31 d2 f7 f1 80 ca 30 88 15 09 c0
75 f2 89 fa b4 09 cd 21 c3
```
Actual work is done in the first 11 bytes; I need the rest to print the result in decimal notation.
Source code (give as input to the DOS `debug.com` assembler):
```
a
; input the string; count the sum
cbw
add bx, ax
mov ah, 1
int 21
cmp al, d
jne 100
; Prepare for output: stuff an end-of-line marker
mov di, ax
mov [di], byte 24
mov ax, bx
mov cl, a
; 114
; Divide by 10; write digits to buffer
dec di
xor dx, dx
div cx
or dl, 30
mov [di], dl
or ax, ax
jne 114
; Print the string
mov dx, di
mov ah, 9
int 21
ret
rcx 29
n test.com
w
q
```
Some notes on the code:
* Only handles one line (up to end-of-line character 13); hangs if no end-of-line
* Only 7-bit characters are supported (results are incorrect otherwise)
* Outputs 0 for empty input
* Cannot handle output greater than 64K
* Instruction at address 0x10d overwrites itself (pure coincidence)
* Have to use DOS emulators like [DosBox](http://www.dosbox.com/) to assemble and run this program
[Answer]
# [gs2](https://github.com/nooodl/gs2/blob/master/gs2.py), 1 byte
```
d
```
`d` (`0x64` / `sum`), of course, sums up all bytes in standard input.
[Answer]
# CJam, 3 bytes (sum 260)
```
q1b
```
You can [try it online](http://cjam.aditsu.net/#code=q1b&input=Hello%20World!).
Thanks jimmy23013 for helping chop off 2 characters :)
**Explanation:**
```
q read the input into a string
1b convert from base 1, treating each character as its numeric value
```
[Answer]
## Ruby, ~~13~~ 12 bytes
```
p~9+gets.sum
```
`sum` is a built-in function that sums the characters of a string. Subtracts 10 to account for the newline at the end of `gets`'s return value.
(Edited 4 years later to change `x-10` to `~9+x`... the value of `~9` is `-10`, but it lets us remove the space between `p` and its argument, saving a byte.)
[Answer]
# Python 3 - 28 bytes
```
print(sum(map(ord,input())))
```
Example run:
```
$ ./sum_string.py <<< 'Hello World!'
1085
```
Gets input from stdin, `map`s the `ord` function to it to get the ASCII value of each character, `sum`s it and `print`s.
[Answer]
## Befunge98, 6 bytes, sum: 445
```
2j@.~+
```
Any interpreter should be fine. I use [CCBI](http://users.tkk.fi/~mniemenm/befunge/ccbi.html).
Use as follows:
```
printf 'Hello World!' | ccbi calc.fg
```
Works for multibyte chars and empty strings.
**Explanation**
* `2j` - jump over the next two instructions (`@` and `.` - see below)
* `~` - put the next char on the stack
* `+` - add the code value of the new char to the current sum. The instruction pointer wraps to the beginning and the cycle repeats
* when `~` encounters an EOF it inverses the direction of the pointer and the two "hidden" instructions are executed:
* `.` - print the sum
* `@` - exit
[Answer]
# Python, 24 bytes
This is shorter than any Python solution so far: an unnamed anonymous function, which takes the string as an argument, and returns the sum.
```
lambda x:sum(x.encode())
```
[**Try it online!**](https://tio.run/nexus/python3#@59mm5OYm5SSqFBhVVyaq1Ghl5qXnJ@SqqGp@b@gKDOvRCNNQ8kjNScnXyE8vygnRVEJKAEA)
First, `x.encode()` transforms it into a `bytes` object. Then, `sum` adds the char-code values. As this is a lambda function, the value is implicity returned.
Additionally, one could have `lambda x:sum(map(ord,x))` for the same byte count.
[Answer]
## PowerShell - 27
```
[char[]]$args[0]|measure -s
```
**Example**
```
> SumChars.ps1 'Hello World!'
Count : 12
Average :
Sum : 1085
Maximum :
Minimum :
Property :
```
[Answer]
# Julia - ~~11~~ 7 characters, resultant sum = ~~943~~ 536
Since the question allows the input to come from whatever source you want, I choose an existing variable. Assume that `A` contains the string we wish to evaluate.
```
sum(A)1
```
As it turns out, you can sum the string directly, and it will evaluate... however, due to the way that summing of chars is handled, if there is an odd number of characters in the string, it will output a character, rather than an integer of any sort. As such, we force it to cast to int by multiplying by 1.
Old version:
```
sum(A.data)
```
Will output in a hexadecimal notation (if the sum is less than 256, it'll be `0x??`, otherwise it'll be 8 byte as `0x????????`). If used in code where the result is used, it will operate just like any other number (it's just how Julia displays unsigned ints).
To see the value of the result in decimal, enclose the above in `int()`, as in `int(sum(A.data))`.
For anybody who doesn't know Julia, you assign to `A` exactly the same way you do other assignments to variables. So, `A="Hello World!"` or `A="sum(n.data)"`. In the case where you need to put in `"` or `'` characters, there are multiple options, the easiest of which (because it avoids need for knowledge of the nuances of Julia string literals) is `A=readline()`, followed by simply typing in the string into STDIN (won't handle newlines, though). The escape sequence for newline is, as usual, `\n`, but I don't believe you can use that with readline().
[Answer]
# K5, 2 bytes (function), 5 bytes (program)
## Function
```
+/
```
## Program
```
+/0:`
```
Not sure if K5 was created before or after this challenge was posted. Regardless...THIS IS AWESOME!!
In K5, if you perform arithmetic operations on strings, it converts the characters to their ASCII codes. So this just uses the sum operator `+/` (actually, it's plus + over).
[Answer]
# Matlab/Octave 4 bytes (bonus: 405)
This code is an anonymous function, that does the job, it will take a string, and return the required number.
```
@sum
```
[Answer]
# Go (59 characters)
```
func d(s string)(t int){for _,x:=range s{t+=int(x)};return}
```
Everything in Go is utf8 by default. Codetext in ` delimeters run through itself gives an output of: 5399.
[Answer]
# Javascript ES6, 41 bytes
```
_=>[..._].map(y=>x+=y.charCodeAt(),x=0)|x
```
*Thanks to @ETHproductions for 2 bytes saved!*
[Answer]
# SML, ~~42~~ 36
Just adding another language.
```
fun$x=foldl op+0(map ord(explode x))
```
Converts String to char array, calculates ascii number of each value and calculates the sum of all ascii numbers.
[Answer]
# [Gol><>](https://golfish.herokuapp.com/), 4 bytes
```
iEh+
```
[Answer]
# Jolf, 2 bytes
[Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=dWk&input=SGVsbG8gV29ybGQh)
```
ui
u sum of
i the input string
```
Umm... I don't know what else to say.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 2 bytes
```
C∑
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJD4oiRIiwiIiwiSGVsbG8gV29ybGQhIl0=)
### Explained
```
C∑
C # char
∑ # sum
```
[Answer]
# C 32
```
f(char*s){return*s?*s+f(s+1):0;}
```
[Answer]
## D (function: 60)
Definitely not in it to win it.
Assuming it doesn't need to be a complete program
```
int c(string i){int s;foreach(e;i){s+=cast(int)e;}return s;}
```
Called like so
```
void main ()
{
import std.stdio;
auto hw = "Hello World!";
writefln("%s = %d", hw, c(hw));
}
```
Output:
```
Hello World! = 1085
```
## D (program: 133)
Does not count line breaks.
```
void main(){import std.algorithm,std.stdio;stdin.byLine.map!((a){int s;foreach(e;a){s+=cast(int)e;}return s;}).reduce!"a+b".writeln;}
```
With more whitespace and longer variable names for readability
```
void main () {
import std.algorithm, std.stdio;
stdin.byLine
.map!((line) {
int sum;
foreach (ch; line) {
sum += cast(int)ch;
}
return sum;
})
.reduce!"a+b"
.writeln;
}
```
To support line breaks in the input, I could either use `byLine(KeepTerminator.yes)` — the correct way, for 20 characters — or append a `'\n'` to my line — which breaks single-line input and may give the wrong sum on Windows because of CRLF, for 18 characters.
[Answer]
## JavaScript (ES6) 54 58
```
alert([].reduce.call(prompt(),(v,c)=>v+c.charCodeAt(0),0))
```
54 bytes thanks to **nderscore**:
```
alert([...prompt()].reduce((v,c)=>v+c.charCodeAt(),0))
```
[Answer]
# Delphi (87 83)
```
function x(s:string):int64;var c:char;begin x:=0;for c in s do x:=result+ord(c)end;
```
### Ungolfed
```
function x(s:string):int64;
var
c:char;
begin
x:=0;
for c in s do
x:=result+ord(c)
end;
```
Loops through `S` adding the `ord` value of the char to the result. where x==result
## Edits:
Saved 4 characters by switching to int64 and changing the adding to the sum.
[Answer]
# k (8 chars)
```
+/6h$0:0
```
Q translation
```
sum `int$read0 0
```
Bonus value:
```
k)+/6h$0:0
+/6h$0:0
438i
```
[Answer]
# J (7)
So close, yet so far... Oh well, I guess 7 is decent enough, since this answer also accepts empty strings. (I'm basing my usage of a variable as input on the phrase `from a file, stdin or whatever`)
```
+/a.i.b
```
## Explanation:
```
a.
┌┬┐├┼┤└┴┘│─ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~��������������������������������������������������������������������������������������������������������������������������������
```
`a.` contains all ASCII chars.
```
'people' i. 'pow'
0 2 6
```
`x i. y` is similar to python's `[x.index(i) for i in y]`.
```
a. i. 'Hello World!'
72 101 108 108 111 32 87 111 114 108 100 33
```
Therefor, `a. i. y` converts `y` to an array of its ASCII values
```
+/1 2 3 4 5 6
21
```
`+/` is like `sum`: `+/1 2 3 4 5 6` means `1+2+3+4+5+6`
```
+/ a. i. 'Hello World!'
1085
```
The whole thing in action
For the bonus:
```
b=:'+/a.i.b'
+/a.i.b
482
```
Not bad, I guess.
```
b=:'0\{+}/'
+/a.i.b
478
```
Well, darn.
```
A=:'+/a.i.A'
+/a.i.A
449
```
Thanks @algorithmshark
```
A=:'+/3 u:A'
+/3 u:A
413
```
Thanks @marinus
[Answer]
## R, ~~35 characters (sum of 3086)~~ 26 bytes (sum of 2305)
```
sum(utf8ToInt(readline()))
```
`readline()` is one character longer than `scan(,"")` but `scan` split the input on spaces by default.
Usage:
```
> sum(utf8ToInt(readline()))
Hello World!
[1] 1085
> sum(utf8ToInt(readline()))
sum(utf8ToInt(readline()))
[1] 2305
> sum(utf8ToInt(readline()))
q/%8hnp>T%y?'wNb\},9krW &D9']K$n;l.3O+tE*$*._B^s!@k\&Cl:EO1zo8sVxEvBxCock_I+2o6 yeX*0Xq:tS^f)!!7=!tk9K<6#/E`ks(D'$z$\6Ac+MT&[s[]_Y(`<g%"w%cW'`c&q)D$0#C$QGf>?A$iawvc,}`9!('`c&q)D$0#C$QGf>?A$iawvc,}`9!(
[1] 14835
```
[Answer]
# Java 8, 113 chars
```
BigInteger C(String s){BigInteger i=BigInteger.ZERO;s.chars().forEach(x->i=i.add(BigInteger.valueOf());return i;}
```
*Note* each character in Java is Unicode 1-4 bytes unsigned integer, using `sum` function would easily overflow.
**Detailed**
```
BigInteger C (String s)
{
BigInteger i = BigInteger.ZERO;
s.chars().forEach(x -> i = i.add(BigInteger.valueOf(x));
return i;
}
```
# Java 8, 57 chars
*ASCII only solution*
```
int C(String s){return s.chars().filter(x->x<128).sum();}
```
**Detailed** [try here](http://ideone.com/FB1d8x)
```
public static int C (String s)
{
return s
.chars() // stream the characters
.filter(x -> x < 128) // filter ASCII (optional)
.sum(); // return the sum
}
```
] |
[Question]
[
Let \$Z\$ be either the integers, the positive integers, or the non-zero integers; pick whatever's convenient. Give two functions \$f\$ and \$g\$, each \$Z \to Z\$, such that:
* \$f(g(a)) = g(f(a))\$, for infinitely many integers \$a\$, and
* \$f(g(b)) \ne g(f(b))\$, for infinitely many integers \$b\$.
## Rules
Many of the rules from [f(g(x)) decreases while g(f(x)) increases](https://codegolf.stackexchange.com/questions/115507/fgx-decreases-while-gfx-increases) are stolen here:
* Please provide an argument for why your functions fulfill the requirements.
* Interpret "function" in the mathematical sense. That is, they must be total (defined over all of \$Z\$) and pure (given the same input, it must produce the same output).
* You may submit the functions as a single program or two separate ones.
+ A single program must either have two named functions \$f\$ and \$g\$, or, when run, have output that can be interpreted as a pair of two functions \$f\$ and \$g\$.
+ Two separate programs must have one give \$f\$, and the other give \$g\$. The two programs may not refer to each other. In this case, [functions may be unnamed](https://codegolf.meta.stackexchange.com/questions/1501/should-function-literals-be-allowed-when-a-function-is-asked-for/1503#1503).
* Standard [submission rules](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet) and [input/output methods](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) apply, but we require that \$f\$ and \$g\$ must have identical input and output representations; that is, they can be directly composed without manually converting in between. Conceptually, they must be functions over integers, so you can't cheat by using two different string representations of the same number or anything like that.
* The usual [integer overflow rules](https://codegolf.meta.stackexchange.com/questions/2280/rulings-on-machine-limits) apply: your solution must be able to work for arbitrarily large integers in a hypothetical (or perhaps real) version of your language in which all integers are unbounded by default, but if your program fails in practice due to the implementation not supporting integers that large, that doesn't invalidate the solution.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). If you submit a single program, your score is the number of bytes of that program. If you submit two programs, your score is the sum of the number of bytes of both programs.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 0 + 1 = 1 byte
[Try it online!](https://tio.run/##K0otycxLNPwPBIZGxiamZuYWlgA "Retina – Try It Online")
This is a Count stage that matches an empty string at the start, between every two consecutive digits, and at the end. This produces the number of digits plus 1.
---
```
.
```
[Try it online!](https://tio.run/##K0otycxLNPz/X@//f0MjYxNTM3MLSwA "Retina – Try It Online")
This is a Count stage that matches every digit, producing the number of digits.
---
Applying these in the two possible orders gives \$\mathrm{ndigits}(\mathrm{ndigits}(n))+1\$ and \$\mathrm{ndigits}(\mathrm{ndigits}(n)+1)\$, which are equal if and only if \$\mathrm{ndigits}(n)\$ is 1 less than a power of 10.
[Answer]
# Python, 3+4 = 7 bytes
`abs`
`hash`
These two builtins commute for most integers.
But not all:
The following depends on an implementation detail of CPython; I didn't find an official spec, below I give my best guess:
`hash` maps integers onto themselves modulo `2**61-1` (which appears to be the 9th Mersenne prime; also, this may depend on the bitness (32/64 etc.) of the C long of the platform) while keeping the sign (so `-4` does not map to `2**61-5` but to `-4`). Therefore `hash(-n)==-hash(n)` for all integers except those which equal `+/-1` modulo `2**61-1` because in the underlying `C` implementation `-1` is used as an error indicator. So, whenever the hash would be `-1`, `-2` is returned instead.
[Minimal demo at TIO](https://tio.run/##K6gsycjPM/7/Py2/SKFCITNPIdpQR9dQx0hLywzIgFDGWlqmBjq6YCrWikuhoCgzr0SjQicjsThDo0JTR6NCVQOsUtdQUzMzTaHCzkAhNac4VUFXQxdZSvP/fwA)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 1 + 1 = 2 bytes
```
Ḃ
```
\$f(x) = x \bmod 2\$ ([Try it online!](https://tio.run/##y0rNyan8///hjqb///8bGhkDAA "Jelly – Try It Online")).
```
Ḥ
```
\$g(x) = 2x\$ ([Try it online!](https://tio.run/##y0rNyan8///hjiX///83NDIGAA "Jelly – Try It Online")). These functions commute only for even input.
[Answer]
# [Pascal (FPC)](https://www.freepascal.org/), 7 bytes
```
succ
```
```
odd
```
[Try it online!](https://tio.run/##NYtBCoMwFET3OcXbmYAtdat4g14iTaJ8KInEtB4/TQUXA2/eMJvdnX3fls3VCl@bkRGJJawhT@oVVokKltQ848xASQwPfOLa4MhSwjNq6enoepL3ev84p8UYZk78u1bN1B4hetVyr/UH "Pascal (FPC) – Try It Online")
`succ` acted as \$x \rightarrow x+1\$; while `odd` acted as \$x \rightarrow x \bmod 2\$. So `succ(odd(x)) = odd(succ(x))` iff x is even.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 1 byte (or 2 bytes if including call modifier)
```
b
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/qG3Do6bGOgj1P@n/fyMj0/9RAA "Brachylog – Try It Online")
**I don’t know exactly if that’s bending the rules or not, let me know.**
In this single program, `f(x)` is `b - behead`, with a given input and an unknown output, and `g(x)` is also `b - behead`, but with a given output and an unknown input.
You can run `f(g(x)` with `↰₁~↰₁` in the header, and `g(f(x))` with `~↰₁↰₁`. This is why I’m ok with this being scored as 2 bytes, as you need to use `~` to "reverse" the program’s calling order.
### Explanation
`b` asserts that its output is the input without the first element.
* For all positive integers that begin with a leading `1` (except `1` itself), `f(g(x))` will remove this leading 1, and then add an unknown leading digit back. Since `0` cannot be a leading digit, this leading digit will unify with `1` as the next possibility, and so `f(g(x)) = x`. Similarily, `g(f(x))` will append an unknown leading digit first, and then remove it, so once again `g(f(x)) = x = f(g(x))`.
* For all positive integers that don’t begin with a leading `1` (and `1`), `f(g(x))` will remove the leading digit, and then append an unknown leading digit, which will unify with `1` as it is the first possibility. Since the initial leading digit wasn’t `1`, we have `f(g(x)) ≠ x`. On the other hand, `g(f(x))` will append an unknown leading digit, and then remove it, leaving `x` unchanged. So we have `g(f(x)) = x ≠ f(g(x))`.
Obviously, there are infinitely many positive integers that start with a leading `1`, and infinitely many positive integers that don’t.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 7 bytes
```
Abs
```
```
#+1&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/z/N1jGpmCvdVlnbUO1/QFFmXolDSGJSTmp0mkO6Q4WtbbpDmkOFTnWFjq6ljmVt7H8A "Wolfram Language (Mathematica) – Try It Online")
\$(f\circ g)(x)=|x+1|\$, the distance of \$x\$ from \$-1\$. \$(g\circ f)(x)=|x|+1\$, one more than the distance of \$x\$ from \$0\$. These are equal when \$x\ge0\$, and unequal when \$x<0\$.
[](https://i.stack.imgur.com/rLE9K.png)
I suspect this is minimal. Trig functions such as `Sin` unfortunately are not \$\mathbb Z\to\mathbb Z\$.
[Answer]
# [Zsh](https://www.zsh.org/), 6 + 6 = 12 bytes
```
tr 1 2
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhbLSooUDBWMIByo2IIlhkbGJhA2AA)
```
tr 2 3
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhbLSooUjBSMIRyo2IIlhkbGJhA2AA)
The first program replaces `1`s with `2`s; the second replaces `2`s with `3`s. These commute only for numbers not containing the digit `1`.
---
Old answer:
## [Zsh](https://www.zsh.org/), 10 + 10 = 20 bytes
\$ f(x) = \lfloor \frac x 2 \rfloor \$
```
<<<$[$1/2]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuharbGxsVKJVDPWNYiECUPGl0WbmxrFQDgA)
\$ g(x) = 2x \$
```
<<<$[$1*2]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuharbGxsVKJVDLWMYiECUPGl0cbGZrFQDgA)
For even \$ x \$, \$ f(x) = \frac x 2 \$, so \$ g(f(x)) = x \$.
But for odd \$ x \$, `/2` rounds downwards, so \$ f(x) = f(x-1) \$, so \$ g(f(x)) = x - 1 \ne x \$
\$ g(x) \$ is always even, so for all \$ x \$, \$ f(g(x)) = x \$.
Therefore, \$ f(g(x)) = g(f(x)) \$ if and only if \$ x \$ is even.
[Answer]
# [Python](https://www.python.org), 9 + 3 = 12 bytes
\$ f(x) = \operatorname{bitwise\\_or}(x, 1) = \begin{cases} x & x \text{ is odd} \\ x + 1 & x \text{ is even} \end{cases} \$
```
1 .__or__
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhYrDRX04uPzi-LjIfxtBUWZeSUaaRogMjOvoLREQxMIIJILFukaQ1gA)
\$ g(x) = \lvert x \rvert = \begin{cases} x & x \ge 0 \\ -x & x \le 0 \end{cases} \$
```
abs
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhaLE5OKIaxtBUWZeSUaaRogMjOvoLREQxMIIJILFukaQ1gA)
Commutes for all \$ x \$ except negative even numbers.
If \$ x \$ is positive or odd, then at least one of \$ f \$ and \$ g \$ will act as the identity function \$ \operatorname{id} \$ and return \$ x \$ unchanged. In that case, clearly, they commute:
$$
h(\operatorname{id}(x)) = h(x) = \operatorname{id}(h(x))
$$
[Answer]
# [R](https://www.r-project.org), 5 + 3 = 8 bytes
```
nchar
```
```
abs
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGCpaUlaboWa9Ns85IzEou40m0Tk4ohYjedixMLCnIqNXQNDawMDXTSSvOSSzLz8zQqNNM00oGkpiYXThXpGmlgFRCjYNYAAA)
Commutative for positive values & zero, non-commutative for negative values (since the minus sign is counted as a character by `nchar`).
[Answer]
# Julia, 17
```
f(n)=n%2;g(n)=n%3
```
consider the numbers of form 6k and 6k+3.
[ATO](https://ato.pxeger.com/run?1=m700qzQnM3HBgqWlJWm6FhvTNPI0bfNUjazTIQxjiPjNzKLEciUlJQxpoFiNXU5qXnpJhkKNnUJBUWZeSU4eV1p-kUKeQmaegoGVqQEXJ1RYQ0klT0HXTkFFI00DZICmpoI9kJOukQbmKGlypealQCyEOQgA)
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 2 + 2 = 4 bytes
```
0=
1>
```
[Try it online!](https://ngn.bitbucket.io/k#eJxLszKw5Uq3MrTj4rKqsNJQ1DU00NRRNDTgSldPU6/gSlNPV68AAI43CBA=)
* f: `0=`, returns 1 if the input is 0, 0 otherwise.
* g: `1>`, returns 1 if the input is 0 or negative, 0 otherwise.
`g` is boolean negation when the domain is limited to booleans (0 and 1). `f(x)` and `g(x)` are the same for `x>=0` and different otherwise, and the same can be said for `g(f(x))` (negation of `f(x)`) and `f(g(x))` (negation of `g(x)`).
4 bytes is optimal in ngn/k since any monadic function is at least two bytes long.
[Czylabson Asa's mod-2 and mod-3](https://codegolf.stackexchange.com/a/248540/78410) are also the same length in K: `2!` and `3!`.
[Answer]
# [J](http://jsoftware.com/), 3 bytes
`|` absolute value
`>:` increment
[Try it online!](https://tio.run/##y/r/P83WqoYr3dbKzup/anJGvkKaQrpCvJlCvKlCvIlCvLFCvJFCvKGCgYKhgpGCsYKJgqmCGRdYYTpQKQGF/wE "J – Try It Online")
See [att's answer](https://codegolf.stackexchange.com/a/248546/43319) for explanation.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 14 bytes
I haven't seen anyone use this one yet, it might work better in another language. (And it is definitely possible to do better in Octave!)
```
@(x)x<0
@(x)x>0
```
The key here is that `true == 1` and `false == 0`.
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0KzwsaAC0zbGfxPt03MK@aqULBV0DW1MrXmqjQEMtM00oHSmkCeEZCXrpEG4aVkFhdogBTYKlQaaVr/BwA "Octave – Try It Online")
[Answer]
# JavaScript (ES6), 6 + 5 = 11 bytes
These functions commute for odd negative values and for even non-negative values. They do not commute for the other cases.
```
f=
x=>x%2 // 6 bytes
g=
x=>~x // 5 bytes
```
[Try it online!](https://tio.run/##ZU5BTsMwELznFXtBXitxSgpFguDyiB6jHEzqhFRpHDlWZEThBUhcOMI/eA8f4AnBToMEYrWWRzO7O7MTg@gLXXeGtWorx7HkgeVre7KExQIu4PbeyD6oJvLJgidXR3IsVNurRsaNqpCAhQOUWKGl1KEKyxnthSnuCE2DP@OMsZD91D/kx4NSabTAga1Sd/yag//DkMJDANBIA/rUqbNl5DhfOnHcbJ467rdpZiO3414SASF5vBcd4hBBTYGvAYfYqI3RdVshhRAIkFjLTgqDmVs4nzrJszqnNO7EdmOEdtJZBJdTL2dpp@oWyYH4G@gjch/qBsjn2@vXxwuBKwffn4nP9zh@Aw "JavaScript (Node.js) – Try It Online")
### Explanation
The sign of the modulo in JS is the sign of the numerator. So the functions are more formally defined as:
$$\begin{align}&f(x)=\cases{0&if $x$ is even\\-1&if $x<0$ and $x$ is odd\\1&if $x>0$ and $x$ is odd}\\
&g(x)=-x-1\end{align}$$
For odd negative values, we have: \$\cases{g(f(x))=g(-1)=0\\f(g(x))=f(-x-1)=0}\$
For even negative values, we have: \$\cases{g(f(x))=g(0)=-1\\f(g(x))=f(-x-1)=1}\$
For odd non-negative values, we have: \$\cases{g(f(x))=g(1)=-2\\f(g(x))=f(-x-1)=0}\$
For even non-negative values, we have: \$\cases{g(f(x))=g(0)=-1\\f(g(x))=f(-x-1)=-1}\$
### Generalization
We can actually use any modulo \$m>1\$ for \$f\$, making the non-commutative cases more and more sparse as \$m\$ increases (but obviously, we'd still get infinitely many of them).
[Try it online!](https://tio.run/##ZY5LSsRAEIb3OUVtpKvJY4wYQWOPh5hlyKLNJDFDJh06TWhx9ASCG5d6D8/jBTxCrM5EUCyq4Oerx187Ocqh0E1vwk5ty2mqhGfF2p4ksFrBBdzem3Lw6hk@WXAwOcKpUN2g2jJqVY0MwMIBKqzRck6qxmpRe2mKO8ZT7898SOGHP/FPuXmvUhotCAjjJKXz1wJm4fscHjyAtjSgT6m/uAbEXOiY2OKfEvvtm9mAdqjiABjLo73sEccAGg5iDThGRm2MbroaOfjAgEW67EtpMKOF8znjPGtyzqNebjdGamoRvJzzbGntVNMhOzB3A92Lwj11A@zz7fXr44XBFcn3Z@b@e5y@AQ "JavaScript (Node.js) – Try It Online") (example with \$m=5\$)
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 4 bytes
`|` absolute value
`1∘+` increment (lit. 1 curried to plus)
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v8bwUccMbS4wWfM/7VHbhEe9fY@6mh/1rnnUu@XQetNHbRMf9U0NDnIGkiEensFc6RhqTNDVAM3pmJF@aIXCofVmQGwKxCZAbAzERkBsqGCgYKhgpGCsYKJgqmAGNLFjRhqxqgE "APL (Dyalog Unicode) – Try It Online")
See [att's answer](https://codegolf.stackexchange.com/a/248546/43319) for explanation.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 8 + 4 = 12 bytes
```
V`[1-9]+
```
[Try it online!](https://tio.run/##K0otycxLNPz/Pywh2lDXMlb7/39dQwMjEy4gaWLEZWhkbGJqZm5hacBlaWFuZmpibGRoAAA "Retina – Try It Online") Link includes test cases. Explanation: Reverses all runs of non-zero digits.
```
L`.$
```
[Try it online!](https://tio.run/##K0otycxLNPyvquGe8N8nQU/l/39dQwMjEy4gaWLEZWhkbGJqZm5hacBlaWFuZmpibGRoAAA "Retina – Try It Online") Link includes test cases. Explanation: Outputs the last digit, without a sign.
The functions commute in a lot of cases such as the trivial ones of the input being a multiple of 10 or a repdigit.
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 3 bytes (SBCS)
```
|¬
|
```
[Try it online!](https://mlochbaum.github.io/BQN/try.html#code=RuKGkHzCrApH4oaQfAp44oaQwq8xMCvihpUyMAooRiBHIHgp4omNKEcgRiB4KQ==)
`abs(1-x)` and `abs(x)` respectively. `f(g(x)) = abs(1-abs(x))` and `g(f(x)) = abs(abs(1-x)) = abs(1-x)`. The results differ if and only if `x` is negative.
```
F←|¬
G←|
x←¯10+↕20
(F G x)≍(G F x)
┌─
╵ 9 8 7 6 5 4 3 2 1 0 1 0 1 2 3 4 5 6 7 8
11 10 9 8 7 6 5 4 3 2 1 0 1 2 3 4 5 6 7 8
┘
```
[Answer]
# x86 32-bit machine code, 2 + 2 = 4 bytes
```
40 C3
98 C3
```
[Try it online!](https://tio.run/##nVJNT8MwDD03v8IUTUrWDXUbArRSLpy5cEJiaErTJIvUplM/tE7b@OkUp9OGEAcQFz/Z79nPiSzGWoiu41UO9NmnRM09YwVI3hKvlDXRc09sUnlMmM8islzyui5N0tSS0lLqNS9zOmGMgbE1KOpi@6tOn3XkEg2zJpVwX9WpKa5WD8RxOTeWMrIjnipK6OUcYggjhIsYrhGDgBHvi06QHk8iROSniEfeMwooh/0e3pM@37ng9f7YwWEIs@ntzR0EkEQ9tS6RVNRXVNOBwY1jGJiF9UfQjsAVW3zGd6mm6qfUFc/SA/HIWb6wC/vExcpYCaJI5RxbnOy0VDiCLaZpAbtTyyCcvgDO3caUNrYy2soUxIqXQ6bYaxsEbyw6wGZlMgl0674gbB9nbuhpAi4IybaWFTsu6Lje7O9O@v9OeEBNaZ3Zoes@hMq4rrpxPptiwPOLsVNmnw "C (gcc) – Try It Online")
Uses the `regparm(1)` calling convention – argument in EAX, result in EAX.
In assembly:
`inc eax; ret` – \$f\$ simply adds 1 to a number.
`cwde; ret` – \$g\$ sign-extends the low 16 bits of EAX, duplicating bit 15 into all the higher bits.
If the low 15 bits are not all 1, these two functions do not interact, thus they commute.
If the low 16 bits are 1111 1111 1111 1111, either order of functions results in 0.
If the low 16 bits are 0111 1111 1111 1111, applying \$f\$ then \$g\$ results in -32768, while applying \$g\$ then \$f\$ results in 32768.
[Answer]
# 22 bytes total
# [R](https://www.r-project.org), 15 bytes
```
\(x)round(x,-2)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGSNAVbhaWlJWm6FutjNCo0i_JL81I0KnR0jTQhomsKijLzSjTSNEwNNKFCCxZAaAA)
# [R](https://www.r-project.org), 7 bytes
```
\(x)x^2
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGSNAVbhaWlJWm6FstjNCo0K-KMILw1BUWZeSUaaRqmBpqaEKEFCyA0AA)
Commutes for x 0 mod 100, doesn't for x 0 mod 10 but not 0 mod 100.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 1+1 = 2 bytes
```
ṗ
¬
```
[Try it online!](https://tio.run/##yygtzv6fe2h5qsajpsZHTU2aQLoJyNT8/3DndK5Da/7//x9tqGOkY6xjomOqY6ZjrmOhY6ljaKBjaBgLAA "Husk – Try It Online")
There are several 1+1 bytes pairs that work in [Husk](https://github.com/barbuz/Husk) (including a port of the absolute-value/offset approach [[`a`/`→`](https://tio.run/##yygtzv6fe2h5qsajpsZHTU2aQLoJyNT8n8j1qG3S////o3VNdXRNdHSNdXSNdHQNdQx0DHWMdIx1THRMYwE)] that separates `a`/`b` by positive/negative values, and [some](https://tio.run/##yygtzv6fe2h5qsajpsZHTU2aQLoJyNT8/6htCpfLf2WF5Pzc3NKSxJLMslSFtPwihbzS3KTUomKF8sySDIXEnByFlMz0zJJiBRvT//@jDXWMjHVMTHUMjYyMjXWMTU3NzYFsYxMdM3MLSxDLMhYA) [other](https://tio.run/##yygtzv6fe2h5qsajpsZHTU2aQLoJyNT8n8h1bsF/ZYXk/Nzc0pLEksyyVIW0/CKFgvziTDAnrzQ3KbWoWEEjv7SkoLSkWCEtMbkkvygzMUfTGqwyLzU9EUWleuK5BeoKMOWGCol5KQrq5xYkIsTgRvz/H61rqqNroqNrrKNrpKNrqGOgY6hjpGOsY6JjGgsA) interesting approaches).
But I like this one best: `ṗ` and `¬` are commutative only for prime numbers, and non-commutative for all positive non-prime integers.
```
ṗ # index of x in the infinite list of primes, or zero if non-prime
D # logical NOT
```
So:
```
ṗ¬ # outputs zero for all nonzero inputs
¬ṗ # outputs 1 for non-primes, zero for prime numbers
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 1 + 1 = 2 bytes
f(x) = [`‹`](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigLkiLCIiLCIiXQ==) and g(x) = [`ȧ`](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLIpyIsIiIsIiJd).
`ȧ` is absolute value and `‹` is decrement, so \$f(g(x))\$ = \$\left|x-1\right|\$ and \$g(f(x))\$ = \$ \left|x\right| - 1\$, which are the same only on positive integers.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 3 + 3 = 6 bytes
```
I↔N
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzGpOD@ntCRVwzOvoLTErzQ3KbVIQxMIrP//1zU0MDL5r1uWAwA "Charcoal – Try It Online") Link is to verbose version of code.
```
I⊕N
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzMvuSg1NzWvJDUFyC4oLfErzU1KLdLQBALr//91DQ2MTP7rluUAAA "Charcoal – Try It Online") Link is to verbose version of code.
Another port of @att's Mathematica answer.
[Answer]
# Haskell, 3 + 4 bytes
```
abs
(+1)
```
If `x` is non-negative the functions commute, otherwise they do not.
# Haskell, 4 + 8 bytes
```
(*2)
(`div`2)
```
If `x` is even, the functions commute.
If `x` is odd, `(``div`` 2) $ (*2) x` is equl to `x`, while `(*2) $ (``div`` 2) x` is equal to `x-1`.
[Answer]
# [Factor](https://factorcode.org/), 3 + 3 = 6 bytes
```
abs
```
```
?1+
```
[Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQm1iSoVBQlFpSUllQlJlXopCZr2D9/7@pQmJSsYK9obaCHpcpmAbx9bjycrh0keV0kST/AwA "Factor – Try It Online")
Absolute value and increment. (`?1+` is a single word/function that always increments integers by one or changes `f` [Factor's canonical false value] to `0`.) Factor does not come with a 'normal' increment word, such as `1+` in Forth.
[Answer]
# sh + coreutils, 16 + 7 bytes
```
(cat;echo +1)|bc
tr -d -
```
The first function adds one to the number given in input; the second function calculates the absolute value. The composition here is intended as piping the output of one into the other, that is:
```
echo -n "-12" | (cat;echo +1)|bc | tr -d -
echo -n "-12" | tr -d - | (cat;echo +1)|bc
```
] |
[Question]
[
I honestly cannot believe that this is not a question yet on Code Golf, but....
Print the local time (with a.m. or p.m.) as a string to the console, preceded by "It's ".
Example:
```
Run code....
```
**Output:**
```
It's 12:32p.m.
```
Shortest code wins.
Code away!
### Leaderboard
```
var QUESTION_ID=57552,OVERRIDE_USER=42854;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
## Bash, ~~39~~ 33 bytes
```
date "+It's %I:%M%P."|sed s/m/.m/
```
Wasted a bunch of chars because the spec requires `a.m.` or `p.m.` while `date` outputs `am` or `pm`. Thanks to @DigitalTrauma for saving 6 bytes!
This might not be very portable. It works on Ubuntu 15.04.
A solution that uses essentially the same method in Ruby~~, which is surprisingly the exact same length~~:
## Ruby, 39 bytes
```
$><<`date "+It's %I:%M%P"`[0..-3]+'.m.'
```
[Answer]
# AppleScript, 198
Because AppleScript. Because why not:
```
set AppleScript's text item delimiters to {":"," "}
set d to (current date)'s time string's every text item
"It's "&d's item 1&":"&d's item 2&string id ((d's item 4's first character's id)+32)&".m."
```
That was painful.
[Answer]
# PHP, ~~35~~ 33 bytes
Using the wrong tool for the job!
```
It's <?=trim(date('h:ia'),m)?>.m.
```
It simply removes the `m` at the end of `am` or `pm`, to allow to add the dots. The date comes as `00:00am`, and with `trim` it becomes `00:00a`.
---
**Old answer (PHP 5.4+ only):**
```
It's <?=date('h:i'),date(a)[0]?>.m.
```
This works because you can de-reference a value returned from a function. This isn't possible in PHP5.3 or older.
[Answer]
## Visual Basic 6 / VBA, ~~42~~ 41 bytes
```
MsgBox"It's "&Format(Now,"h:mma/p")&".m."
```
Using `MsgBox`, as VB6 does not have a console (unless you intercept the linking, link as a console executable, use some Windows API hacks, and do some other *dodgy* stuff).
[Answer]
# R, ~~68~~ ,~~59~~ ~~62~~ ~~60~~ 55
```
cat("It's",sub("m",".m",format(Sys.time(),"%I:%M%P.")))
```
(Thanks to @Alex.A. and @flodel for the comments) Takes the current system time (`Sys.time()`), formats it correctly using `%I:%M%P` combination, adds a dot at the end, and replaces the `m` with `.m.`.
[Answer]
# Julia, ~~74~~ ~~54~~ 43 bytes
```
print(strftime("It's %I:%M%P\b.m.",time()))
```
You can [try it online](http://goo.gl/4ZU9F8)!
The `time()` function returns the current time. When passed to `strftime` with the format `%I:%M%P`, this results in `HH:MMam/pm`, where the hours are per a 12-hour clock. We back up one character with `\b` to remove the `m`, leaving a trailing `a` or `p`, then tack `.m.` onto the end.
Saved **31 bytes** thanks to Glen O!
[Answer]
# Haskell, 135 bytes
```
import Data.Time.Format
import Data.Time.LocalTime
main=getZonedTime>>=putStr.(++".m.").init.formatTime defaultTimeLocale"It's %I:%M%P"
```
I found a much more amusing `main` that's five bytes longer:
```
getZonedTime>>=putStr.formatTime(TimeLocale[][]("a","p")""""""""[])"It's %I:%M%P.m."
```
Or 66 bytes on Unix:
```
import System.Cmd;main=system"date \"+It's %I:%M%P.\"|sed s/m/.m/"
```
[Answer]
# Pyth, ~~38~~ 36 bytes
```
s["It's "|%J.d6K12K\:.d7?gJK\p\a".m.
```
Saved 2 bytes thanks to @Jakube!
[Answer]
# MATLAB, 59 bytes
```
disp(sprintf('It''s%s\b.m.',lower(datestr(now,'HH:MMam'))))
```
>
> It's 5:38p.m.
>
>
>
If it's allowed to have a whitespace between time and a.m./p.m., then it could be as low as **52 bytes**:
```
disp(sprintf('It''s%s\b.m.',lower(datestr(now,16))))
```
>
> It's 5:39 p.m.
>
>
>
[Answer]
# Perl 5.10+, ~~58~~ 62 bytes
```
localtime=~/(..)(:..)/;say"It's ",$1%12||12,$2,$1>11?p:a,".m."
```
Must be run with the `-M5.010` command line flag to get `say`.
I didn't account for a couple of edge cases in my original solution (namely, `00:**` and `12:**`); fixed at a cost of 4 additional bytes.
## How it works
In scalar context, [`localtime`](http://perldoc.perl.org/functions/localtime.html) returns a string like this:
```
Sat Sep 12 03:13:22 2015
```
The minutes field is already zero-padded, which saves some bytes (in list context, `localtime` returns numbers instead of strings, so you have to pad them yourself).
Here it is ungolfed:
```
localtime=~/(..)(:..)/; # Store hour in $1 and minutes in $2
say"It's ", # Print "It's " followed by...
$1%12||12, # hour in 12-hour format
$2, # minutes
$1>11?p:a, # "p" if hour > 11, otherwise "a"
".m."' # ".m."
```
---
# Perl 5.14+, 57 bytes
(Just for fun, since it stretches the rules a bit.)
```
say"It's ",(strftime"%l:%M%P",localtime)=~s/m/.m./r
```
51 bytes + 6 bytes for `-MPOSIX`. Must also be run with the `-M5.010` command line flag to get `say`.
This solution is dependent on your locale, so will not work on all systems. It also uses the POSIX module, which might be stretching the definition of a "built-in", even though it is a core module.
Perl 5.14+ is required for the non-destructive `r` modifier to the substitution operator. An equivalent solution that works on 5.10+ is:
```
$_=strftime"%l:%M%P",localtime;chop;say"It's $_.m."
```
This is also 57 bytes (51 bytes + 6 bytes for `-MPOSIX`).
[Answer]
# Perl 5, 74 bytes
A small showcase of how the variables are evaluated from right to left.
```
($s,$m,$h)=localtime;printf"It's %d:%02d%s.m.",$h<13?$h:$h%12,$m,$h<12?a:p
```
### Using POSIX: 80 bytes
```
use POSIX;$_=strftime"It's %I:%Mx.m.",@_=localtime;$x=$_[1]<13?a:p;s/x/$x/;print
```
### Using POSIX with time locale dependence & switches : 54 bytes (48 + 6)
```
$_=strftime"It's %I:%M%P",localtime;s/m/.m./;say
```
**Test**
```
$ export LC_TIME="en_DK.UTF-8"
$ perl -MPOSIX -M5.01 whatsthetimechap.pl
It's 3:09p.m.
```
[Answer]
# CJam, 40 bytes
```
"It's "et3=CmdCe|\'p'a?':et4=s2Ue[@".m."
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=%22It's%20%22et3%3DCmdCe%7C%5C'p'a%3F'%3Aet4%3Ds2Ue%5B%40%22.m.%22).
### How it works
```
"It's " e# Push that string.
et3= e# Select the fourth element of the date/time array (hours).
Cmd e# Push quotient and remainder of the hour divided by 12.
Ce| e# Logical OR with 12 to map 0 to 12.
\'p'a? e# Select 'p' if the quotient is 1 and 'a' if it is 0.
': e# Push that character.
et4= e# Select the fifth element of the date/time array (minutes).
s2Ue[ e# Cast to string and left-pad with zeroes to a length of 2.
@".m." e# Rotate 'a' or 'p' on top of the stack and push ".m.".
```
[Answer]
# Mathematica ~~49 90 92 90~~ 84 bytes
-6 bytes thanks to user202729
The solution is straightforward, but a bit wordy, in Mathematica.
```
(d=DateString)@{"It's ","Hour12",":","Minute"}<>(d@"AMPM"/."AM"->"a.m."/."PM"->"p.m .")
```
[Answer]
# T-SQL (2012+), ~~67~~ 65 bytes
SQL Server 2012 finally gave us a reasonable formatting function for dates. I still had to muck around with the AM/PM to get the format right though.
```
PRINT 'It''s '+LOWER(STUFF(FORMAT(GETDATE(),'hh:mmtt.'),7,0,'.'))
```
In previous versions it would have needed something like this (93 bytes)
```
PRINT'It''s'+LOWER(STUFF(STUFF(RIGHT(CONVERT(VARCHAR,GETDATE(),109),15),6,7,''),8,0,'.'))+'.'
```
[Answer]
# PHP, 49 bytes
If only it were `am/pm` instead of `a.m./p.m.`...
```
It's <?=@preg_replace(~Фž’¢Ð,~ÛÏÑ,date(~˜Å–ž));
```
I used a lot of nasty bytes to save a bit of length so here's the hex:
```
00000000: 49 74 27 73 20 3C 3F 3D - 40 70 72 65 67 5F 72 65 |It's <?=@preg_re|
00000010: 70 6C 61 63 65 28 7E D0 - A4 9E 92 8F A2 D0 2C 7E |place(~ ,~|
00000020: DB CF D1 2C 64 61 74 65 - 28 7E 98 C5 96 9E 29 29 | ,date(~ ))|
00000030: 3B - |;|
00000031;
```
Readable version:
```
It's <?=preg_replace("/[amp]/", "$0.", date("g:ia"));
```
[Answer]
# C, 103 94 bytes
```
int main(){time_t r;char b[80];time(&r);strftime(b,80,"It's %I:%M %p",localtime(&r));puts(b);}
```
**Ungolfed**
```
int main()
{
time_t r;
char b[80];
time(&r);
strftime(b,80,"It's %I:%M %p",localtime(&r));
puts(b);
}
```
[Answer]
# PHP, 41 bytes
`It's <?=strtr(date('g:ia'),['m'=>'.m.']);`
First time I've played this. Not sure if I'm supposed to update/edit the previous PHP answer (49 bytes) or just add my own...
[Answer]
# SQL (PostgreSQL), ~~42~~ 41 bytes
Another SQL variant, however this one is in a query.
```
select to_char(now(),'"It''s" HH:MIa.m.')
```
As a note either p.m. or a.m. works to get the am/pm part. The formatting options in PostgreSQL are really quite flexible.
Thanks to @manatwork for the tip to move the `it's` into the format string.
[SQLFiddle](http://sqlfiddle.com/#!15/9eecb7db59d16c80417c72d1e1f4fbf1/3173/0)
[Answer]
# Javascript, 103 bytes
Javascript executed from the console.
```
d="It's "+new Date().toLocaleTimeString();l=d.length;d.slice(0,l-6)+d.slice(-2,l-1).toLowerCase()+'.m.'
```
# C#, 63 bytes
C# executed from the immediate window.
```
?"It's "+System.DateTime.Now.ToString("h:MMt").ToLower()+".m.";
```
[Answer]
# Bash, 44 characters
Pure Bash, just shell builtins, no \*\*\*utils.
```
printf -vt "It's %(%I:%M%P)T"
echo ${t%m}.m.
```
Sample run:
```
bash-4.3$ printf -vt "It's %(%I:%M%P)T";echo ${t%m}.m.
It's 01:04p.m.
```
[Answer]
# Powershell, 49 bytes
```
"It's {0:hh:mm}$("ap"[($d=date).hour/23]).m."-f$d
```
`(date).hour/23` seems to work as an index for `"ap"` because it rounds to `0` for hours less than 12 and `1` for 12 and above.
[Answer]
# Locale-dependent
For browser environments that have the locale set to `en-CA` or any locale that outputs a 12-hour time by default:
## CoffeeScript, 81 bytes
```
alert "It's #{(x=(new Date).toLocaleTimeString().toLowerCase())[..4]} #{x[9]}.m."
```
## JavaScript (ES5), 90 bytes
```
alert("It's "+(x=(new Date).toLocaleTimeString().toLowerCase()).slice(0,5)+' '+x[9]+".m.")
```
# Locale-independent
## CoffeeScript, ~~113~~ 96 bytes
```
alert "It's #{(h=(d=new Date).getHours())%12}:#{('0'+d.getMinutes())[-2..]} #{'ap'[+(h>11)]}.m."
```
Previous:
This one works in all browser environments regardless of locale. Requires Chrome 24+, Firefox 29+, IE 11+, Opera 15+ or any derivatives of such. Does not work in Safari. See [`Intl.DateTimeFormat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat).
```
alert "It's #{new Intl.DateTimeFormat('en',{hour:f='2-digit',minute:f}).format(new Date).toLowerCase()[..-2]}.m."
```
[Answer]
## **Swift - 124 102 bytes**
```
import Cocoa
var f=NSDateFormatter()
f.dateFormat="hh:mma"
print("It's \(f.stringFromDate(NSDate()))")
```
[Answer]
# C, 154 bytes
```
#include <time.h>
#define l localtime(&r)
main(){time_t r=time(0);printf("It's %02i:%02i%c.m.",(l->tm_hour+11)%12+1,l->tm_min,(l->tm_hour>=12)?'p':'a');}
```
In contrast to the other C answer, this one uses the correct "a.m."/"p.m." format. The other poster omitted `#include <time.h>` – if your compiler allows this, we get down to 136 bytes. Which one should we count?
[Answer]
## Moonscript - 56 bytes
```
print "It's "..(os.date'%I:%M%p'\gsub 'M','.M.')\lower!
```
Unfortunately the Lua standard library only implements %p for uppercase AM/PM, so I have to call the method lower.
[Answer]
# SpecBAS - 64 bytes
```
PRINT "It's ";LOW$(REPLACE$(TIME$(TIME,"h:mm p$"),"M",".M."))
```
The built-in `p$` of the time function returns AM or PM, so this then has to be formatted with `REPLACE$` to change it so it has a full stop before/after that letter.
Then the time output had to be converted to lowercase.
[Answer]
# MATLAB, 66 bytes
```
['It''s' lower(datestr(now,'HH:MMam'))];disp([ans(1:end-1),'.m.'])
```
Displays:
```
It's 2:48p.m.
```
[Answer]
# Python 2, ~~75~~ ~~67~~ 66 bytes
```
import time;print"It's %s.m."%time.strftime("%I:%M%p")[:6].lower()
```
old version, 75 bytes
```
import time
t=time.strftime("%I:%M%p")
print"It's",t[:5]+t[5].lower()+".m."
```
old version, 75 bytes
```
import time
print"It's",time.strftime("%I:%M%p").lower().replace("m",".m.")
```
[Answer]
# Python 3, ~~117~~ ~~87~~ 79 bytes
```
from datetime import*
print(datetime.now().strftime("It's %I:%M%P")[:-1]+".m.")
```
This gets the hours and minutes from a 12-hour clock using the format `%I:%M`, plus `am` or `pm` using `%P`. We then select everything but the last `m` and append `.m.`.
Saved a few bytes thanks to Ruth Franklin!
[Answer]
# AutoIt, 73 bytes
Even though AutoIt is generally a verbose language, this is quite short (converts time from 24h format):
```
$h=@HOUR>12
ConsoleWrite("It's "&@HOUR-12*$h&":"&@MIN&($h?"p":"a")&".m.")
```
# [ß](https://github.com/minxomat/-S-), 56 bytes
```
H=@HOUR>12µ€"It's "&@HOUR-12*H&":"&@MIN&H?"p.m.":"a.m.")
```
] |
[Question]
[
## The Challenge
Given a finite list of integers, split it into the fewest partitions possible such that no partition contains a number more than once.
## Rules
Input can be in any format and any order.
Output can be in any format, as long as it's clear that each group is separate.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest score wins!
## Example I/O
```
Input: [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2]
Output: [[1,2],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1]]
Input: [1,3,4,2,6,5,1,8,3,8]
Output: [[1,3,4,2,6,5,8],[1,3,8]]
Input: [5,9,12,5,2,71,23,4,7,2,6,8,2,4,8,9,0,65,4,5,3,2]
Output: [[5,9,12,2,71,23,4,7,6,8,0,65,3],[5,4,8,9,2],[4,5,2],[2]]
```
[Answer]
# [Python 2](https://docs.python.org/2/), 50 bytes
```
l=input()
while l:s=set(l);print s;map(l.remove,s)
```
[Try it online!](https://tio.run/##DcZLCoAgFAXQeatoqHCJemVfWkk0aCAkvEzSilZvTg7HfWE/LcXIs7HuDkJm725Y5zz62esgWE7uMjbkfjo2J7i49HE@Gl7GuCgMqAgKhK4C1WjQpbfok01yQIlWpSrUoPUH "Python 2 – Try It Online")
Repeatedly prints the unique of elements of the list, then removes one of each such element. A rare imperative use of `map`.
[Answer]
# [Haskell](https://www.haskell.org/), 39 bytes
First we collect all equal elements in separate lists using `sort` and then `group`. By `transpose`ing the resulting list of lists we get at most one of each of those elements in the resulting lists.
```
import Data.List
f=transpose.group.sort
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRzyezuIQrzbakKDGvuCC/OFUvvSi/tECvGKjgf25iZp5tQVFmXolKWnS0oY6xjomOkY6ZjqmORawOmG8RG/sfAA "Haskell – Try It Online")
### Example
```
[1,2,3,2,4,2,1,5] --input
sort$[1,2,3,2,4,2,1,5] --[1,1,2,2,2,3,4,5]
group.sort$[1,2,3,2,4,2,1,5] --[[1,1],[2,2,2],[3],[4],[5]]
transpose.group.sort$[1,2,3,2,4,2,1,5] --[[1,2,3,4,5],[1,2],[2]]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ĠZị
```
A monadic Link accepting a list, which yields a shortest set-wise partition such that each part is a set.
**[Try it online!](https://tio.run/##y0rNyan8///IgqiHu7v///8fbahjrGOiY6RjpmOqY6hjAeRZxAIA "Jelly – Try It Online")**
### How?
```
ĠZị - Link: list, L e.g. [8,2,4,2,9,4,1]
Ġ - group indices of L by their values [[7],[2,4],[3,6],[1],[5]]
Z - transpose [[7,2,3,1,5],[4,6]]
ị - index into L [[1,2,4,8,9],[2,4]]
```
[Answer]
# [J](http://jsoftware.com/), ~~20~~ 17 bytes
```
_<@-."1~0|:1%%/.~
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/420cdPWUDOsMaqwMVVX19er@a3KlJmfkK6QpGOoY6hiAoSEeaIRQbqxjomOkY6ZjChS2APIsYFKmOpY6hkZAcSMdc6AOkDpzsEoLIGkCJC2BlpiZApmmQG1G/wE "J – Try It Online")
```
% divide 1 by each, 0 becomes infinity
/.~ group equal values, every group gets padded with zeroes
1% invert back
0|: transpose
_<@-."1~ remove the infinities, put each row in a box
```
I suspect `0|:1%%/.~` is acceptable, we get
```
5 9 12 2 71 23 4 7 6 8 0 65 3
5 9 _ 2 _ _ 4 _ _ 8 _ _ _
5 _ _ 2 _ _ 4 _ _ _ _ _ _
_ _ _ 2 _ _ _ _ _ _ _ _ _
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
¹ƙ`Z
```
[Try it online!](https://tio.run/##y0rNyan8///QzmMzE6L@6xxuPzrp4c4Zj5rWZD1qmKOga6fwqGEu1@F2oEDk///R0YY6xEGjWB0uoGJjHRMdIx0zHVOgkAWQZwESNtWx1DE0AooZ6ZgDVYLUmINVWQBJEyBpqWOgY2YKZJoCtRjFxgIA "Jelly – Try It Online")
A monadic link that takes a list of integers and returns a list of lists of integers. Simply groups identical numbers and then transposes.
[Answer]
# [Haskell](https://www.haskell.org/), 54 bytes
```
(a:b)%n|elem n a=a:b%n|s<-n:a=s:b
_%n=[[n]]
foldl(%)[]
```
[Try it online!](https://tio.run/##DcdBCoMwFEXRuatw0IDCK9RotIZmJSGUSBMqxq80HXbv6Z9czn37vIWUSmm8XlpBv5DCXlPtDT9vflxJe5P1Uj0FGWvJuSqaeKRXakRrXdn9Sub8rPS9RKswo5NQkJg6yB4DJvaIO3fgzrhhVEyFHtKVPw "Haskell – Try It Online")
We define a function `%` which takes a single number and adds it to a partition scheme and we fold it across the input starting with an empty partition scheme.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 3 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ü y
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=/CB5&input=WzEsMSwxLDEsMSwxLDEsMSwxLDEsMSwxLDEsMSwxLDEsMSwxLDEsMSwyXQotUQ)
Sorts & partitions by value and then transposes the result.
[Answer]
# JavaScript (ES6), 59 bytes
```
a=>a.map(o=n=>b[i=o[n]=-~o[n],--i]=[...b[i]||[],n],b=[])&&b
```
[Try it online!](https://tio.run/##jU27DsIwDNz5kKqVnIiGpo/B/ZHIQ1JaFFSSiiKmil8PLisMyNL5bN@dr/Zp1@Hul4cI8TymCZPF3sqbXfKIAXtnPEYTCMVrbyCEJzRSSj7QthkCXjo0VGSZS0MMa5xHOcdLPuWmhP9KUVEcvrwnqEBBDZoVLU/tD5WGDkrFEgUN5@yW5mNqGSvGDo5Qa6aaE/Y/6Q0 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 30 bytes
```
{roundrobin map &[xx],.Bag.kv}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/uii/NC@lKD8pM08hN7FAQS26oiJWR88pMV0vu6z2vzVXcWKlQpqGSrymQlp@EVe0oQ5x0ChWB6TYWMdEx0jHTMcUKGQB5FmAhE11LHUMjYBiRjrmQJUgNeZgVRZA0gRIWuoY6JiZApmmQC1Gsf8B "Perl 6 – Try It Online")
Inspired by the Jelly answers.
### Explanation
```
{ } # Anonymous block
.Bag # Convert to Bag (multiset)
.kv # Key-value sequence
map &[xx], # Repeat each key n times
roundrobin # Transpose
```
### Old solution, 32 bytes
```
{(.Bag,{$_∖.Set}...^!*)>>.Set}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WkPPKTFdp1ol/lHHNL3g1JJaPT29OEUtTTs7MO@/NVdxYqVCmoZKvKZCWn4RV7ShDnHQKFYHpNhYx0THSMdMxxQoZAHkWYCETXUsdQyNgGJGOuZAlSA15mBVFkDSBEha6hjomJkCmaZALUax/wE "Perl 6 – Try It Online")
### Explanation
```
{ } # Anonymous block
, ...^ # Create sequence
.Bag # starting with input converted to Bag (multiset)
{$_∖.Set} # Decrease weights by one each iteration
!* # Until bag is empty
( )>>.Set # Convert all bags to sets
```
[Answer]
# [R](https://www.r-project.org/), 54 bytes
```
for(i in 1:max(t<-table(scan())))print(names(t)[t>=i])
```
[Try it online!](https://tio.run/##K/r/Py2/SCNTITNPwdAqN7FCo8RGtyQxKSdVozg5MU9DEwgKijLzSjTyEnNTizVKNKNL7GwzYzX/GyoYK5goGCmYKZgqGCpYAHkW/wE "R – Try It Online")
Builds a table of the counts of the values. For input `1 3 4 2 6 5 1 8 3 8`, this gives
```
t = 1 2 3 4 5 6 8
2 1 2 1 1 1 2
```
where the first row is `names(t)` (the different values in the input) and the second is the counts in `t`.
Then in the for loop, at iteration `i`, print only the names corresponding to counts ≥`i`.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 4 bytes
```
.T.g
```
[Try it online!](https://tio.run/##Dca7DcAgDEDBhZ4QGMxnj3QRNSlT0DC9cXO6/@zPLDxhmb3KIAmK0BKSKTR/pbvFHUSqepWMzAs "Pyth – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 23 bytes
```
(}:,(~:</.])&>@{:)^:_@<
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NWqtdDTqrGz09WI11ewcqq0046ziHWz@a3KlJmfkK6QpGOoQB40QGox1THSMdMx0TIHCFkCeBUzKVMdSx9AIKG6kYw7UAVJnDlZpASRNgKSljoGOmSmQaQrUZvQfAA "J – Try It Online")
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 6 bytes
```
rasgtp
```
[Try it online!](https://tio.run/##SyotykktLixN/f@/KLE4vaTg//9oQx1jHRMdIx0zHVMdQx0LIM8iFgA "Burlesque – Try It Online")
```
ra # Read input as array
sg # Sort and group like values
tp # Transpose
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 17 bytes
```
IE⌈Eθ№θιΦθ⁼№…θμλι
```
[Try it online!](https://tio.run/##JYvBCoMwGINfxWMLGcxqdbJj2W6D3cVDKYKFdtVqx/b03T89JHwhiZl0NEG7nJ/Rvjam9Lqxh55JH@uT33lBoUKilsByzlHcrdvG@M@3JWm3sqNXX@NGNYX94mnn@PHg/Jpz30t0KAUkBNoSokKNlrjBhbwm73BGIwklKohhyKe3@wE "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ Input array
E Map over elements
№ Count of
ι Current element in
θ Input array
⌈ Maximum
E Map over implicit range
θ Input array
Φ Filter elements where
№ Count of
λ Current element in
θ Input array
… Truncated to length
μ Inner index
⁼ Is equal to
ι Outer index
I Cast to string
Implicitly print
```
[Answer]
# [Red](http://www.red-lang.org), ~~67~~ 61 bytes
```
func[b][until[print a: unique b foreach e a[alter b e]b =[]]]
```
[Try it online!](https://tio.run/##jYxLCsMwDET3OcWQfaBx4/ygl@hWaOEkMg0EtzHx@V2l3XVVBIMk3psoS77LQlz4EdmnMNPElMKxbvSKazjgRqSw7kkwwT@juPkBgSO3HRL1JzzhRsycPajGf2O4@LaXVVWVhcepXtHAoIVVoNer/4XIYkBtFDDotOQUuo/SazaaAy5ora5WfcP5DQ "Red – Try It Online")
Inspired by [xnor's Python answer](https://codegolf.stackexchange.com/a/197292/75681) - don't forget to upvote it!
This was a rare opportunity to use `alter`- `If a value is not found in a series, append it; otherwise, remove it`
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 25 bytes
```
*.classify({%.{$_}++}){*}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfSy85J7G4ODOtUqNaVa9aJb5WW7tWs1qr9r81V3FipUKahkq8pkJafhFXtKEOcdAoVgek2FjHRMdIx0zHFChkAeRZgIRNdSx1DI2AYkY65kCVIDXmYFUWQNIESFrqGOiYmQKZpkAtRrH/AQ "Perl 6 – Try It Online")
Groups each element of the input by how many times it has appeared in the sequence so far, then take only the values
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 114 bytes
```
W;*P;S(D,E)int*D,*E;{do for(P=D;P<E;*P==W?printf("%d ", W),*P=*D,*D++=W,P=E:++P);while(++W);puts("");D-E&&S(D,E);}
```
This solution takes a while to run because it iterates over all possible integer values from -2^31 to 2^31-1.
Here is a TIO link to a slightly longer solution that runs a lot faster, the only difference is, that it uses short instead of int. Groups are separated by line breaks.
[Try it online!](https://tio.run/##jZBRa4MwEMff@ykOYSUxVzZjbW2zsBd9FzrwYd3DsLoKmxZ1DCZ@dneN7cD50gSO3OX//10uyeI9Sfq@PpZVA7GyI7VjAYY8Lxo7QDtU7aGErKxYpAMVPYak0Dp@OlUkyJh1dwALIeZI5bM@EELHGOlwK0TE1fcx/0iZEDFXp6@mZpbFVbAI5/Ohiep6wsDnW14wPmtnQOtceE7rxnl5BQ0tOHjbltCpEUD@AVxcosQVeiTzKfP/S92L1MMNOpJ0EtdEPPvWxulTXFLc4AOuPDp6hDEdDef6G/vCvHy7L2hOc7NjpoLDSCCgzn/SMhuqHO6vOfn5xTKGyQlMDjA5hslbYO4E5g4wdwxzp7Cu/wU "C (gcc) – Try It Online")
How does it work?
```
For every possible integer value
if value in array
print value
remove found value entry from list
print endline
if array is not empty
recursively call function on remaining array
```
```
int W;
int *P;
S(int* D, int* E)
{
// this loop will run once for every possible integer value
do
{
// search for the integer value W
for(P=D;P<E;++P)
// if the value is found
if (*P == W)
{
// output the value, can happen only once per integer value
printf("%d ", W);
// overwrite the found value with the first value of the array
// because we have to output the first value later
*P = *D;
// reduce the size of the remaining array by one
D++;
// jump out of for loop to seach for next possible value of W
P = E;
}
}
while(++W); // after the while loop W==0 again
puts(""); // output new line
if (D!=E)
S(D,E); // if end is not reached, search again in ramaining array
}
```
[Answer]
# [Zsh](https://www.zsh.org/), 58 bytes
```
for x (${(u)@})<<<$x&&argv[$@[(i)$x]]=
<<<"
${*:+`$0 $@`}"
```
[Try it online!](https://tio.run/##qyrO@J@moanxPy2/SKFCQUOlWqNU06FW08bGRqVCTS2xKL0sWsUhWiNTU6UiNtaWCyiuxKVSrWWlnaBioKDikFCr9F@TiytNwVDBSMFYwQSJNgaxQBrUbYFAHaoGho0VjP8DAA "Zsh – Try It Online")
Yay, recursion!
For each element `$x` of `(u)`nique `${@}`rguments, print it, and set the first `(i)`nstance of it to the empty string.
Finally, print a newline as a list delimiter, and if the remaining arguments are nonempty, substitute `$0 $@`, which is this program, called with all remaining nonempty elements.
[Answer]
# [R](https://www.r-project.org/), 41 bytes
```
split(sort(s<-scan()),sequence(table(s)))
```
[Try it online!](https://tio.run/##K/r/v7ggJ7NEozi/CEjY6BYnJ@ZpaGrqFKcWlqbmJadqlCQm5aRqFGtqav43VDBWMFEwUjBTMFUwVLAA8iz@AwA "R – Try It Online")
Like [Robin Ryder's answer](https://codegolf.stackexchange.com/a/197347/67312), this makes use of `table` to get counts of the unique elements in the input.
A fuller explanation to follow.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
{γζþ
```
[Try it online](https://tio.run/##DcYxDoAgDEDRC/2BFgpyFuOgiafwWCaOLOxcqXZ5ecnOS273Z73rm8N9NzqiGEoTNFNo8coWlrCTqBY1Mnr8) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfeX/6nObz207vO@/zv/oaEMd4qBRrA5QrbGOiY6RjpmOKVDEAsizAIqa6ljqGBoBhYx0zIHqQErMwYosgKQJkLTUMdAxMwUyTYE6jGJjAQ).
**Explanation:**
```
{ # Sort the (implicit) input-list
# i.e. [5,9,12,5,2,71,23,4,7,2,6,8,2,4,8,9,0,65,4,5,3,2]
# → [0,2,2,2,2,3,4,4,4,5,5,5,6,7,8,8,9,9,12,23,65,71]
γ # Group it into chunks of the same subsequent value
# → [[0],[2,2,2,2],[3],[4,4,4],[5,5,5],[6],[7],[8,8],[9,9],[12],[23],[65],[71]]
ζ # Zip/transpose; swapping rows/columns, with a space character as filler by default
# → [[ 0, 2, 3, 4, 5, 6, 7, 8, 9, 12, 23, 65, 71],
# [' ', 2, ' ', 4, 5, ' ', ' ', 8, 9, ' ', ' ', ' ', ' '],
# [' ', 2, ' ', 4, 5, ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
# [' ', 2, ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']]
þ # Remove all spaces by only keeping digits
# → [[0,2,3,4,5,6,7,8,9,12,23,65,71],[2,4,5,8,9],[2,4,5],[2]]
# (after which the result is output implicitly)
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/) with `-m32` flag, ~~231~~ ~~213~~ ~~210~~ 209 bytes
Thanks to ceilingcat (-22 bytes) for the suggestions.
The function goes through the list of values and builds a reverse list of the unique values, incrementing its count on a match. After the list has been built, the function then goes through the list again, printing any values that have a non-zero count and decrementing the count: It repeats this until all values have a zero count.
```
g(v,c,p)int*v,*p;{int*i=p,w[3]={p,*v,!c};if(c){for(;i&&i[1]-w[1];i=*i);2[i=i?:w]++;g(++v,--c,p=i-w?p:i);}else for(;w[2];p=*w)for(w[2]=!puts("");p;p=*p)p[2]?printf("\t%d",p[1]),p[2]-=w[2]=1:0;}f(v,c){g(v,c,0);}
```
[Try it online!](https://tio.run/##jVFdb6MwEHznV7ickmK8VECaNo3PzQ9J88CZj2xEwAoJSIe4n350DW1Pd08npJV3dnZmbHRQaD2OhdeCBsOxuvot@Eb29oTKQLdfHVRvgOA7PUjMPc37vL54EpdL3EeHoKMiUfnIZbxHhbttdxBCFp4QLQQBySoMup3ZEmHIyiZj03q3jw/SKL/jtrWdujO3a@O5LpfGTgw3hO7MhbLknvt2XaQuGHLjYAeBmpaibSiH3Obn/XyNkHzGb1jp8pZm7HtzTbF@OL46f0El/vgXI5/CYg75sXOCldfWmHLWO4zpY3JhPlaUEJivJUGW5bdJ2QDT9a0iHIGdpEOj6YLsV6OTioIvzo0LbDktc8nyS5Z5czNrz/xJQ0Wg1TSTTCuKpI80AXYP97SphfjwEoJPRozZAEonZVnrWQIa/JnVOTmQvvwjP8sCqpMKJWvmbCTtLlJYVBTQKgm0FssTfw2tnTp92tAD25tODh@qXz@LusEZxgj@74udCFbwCDE8wZr6DXUbZw0vEMUExPBMHEt4nigbqo9UXyCEpzUd18SPf@u8TIpmDM6reAy6dw "C (gcc) – Try It Online")
[Answer]
# [C++ (clang)](http://clang.llvm.org/), ~~230~~ \$\cdots\$ ~~198~~ 162 bytes
Saved 11 bytes thanks to @ErikF!!!
Saved ~~8~~ a whopping 44 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
```
#import<bits/stdc++.h>
void f(std::vector<int>v){for(;v.size();puts(""))for(int e:std::set<int>(&v[0],&*end(v)))printf("%d ",e),v.erase(find(begin(v),end(v),e));}
```
[Try it online!](https://tio.run/##lZDLboMwEEX3fIVF1chuJmlCQx5A@ZE2CwImtRRsZBsvGvnb08HpI@qqHUsec@dcc6Hu@1l9quTxcrkTXa@0LQ7Cmkdjm3o6nb@VkVOiIS1FIcscr63ShZC2dOzcKk1zNzfinVOW94M1NI4ZG2UkCM@Cx3AbDHTiXhZ7mDxw2VDHGOs1yi2N7xsSA2fg5lxXhtNWIHDgRyERgyuNc5Z7jCjr09BwUghlrOZVV0bjq7oKYUbOEcG6Tfo7dUksN9aQ5092rPMS/rYSD1@eW/MTrCCBNaSIbPFp6@FnnMIOlgnOEtjgDSO7CfQW9xXuO1jAOsVjitbEB6fPQ8MfSWg1WBVCk@yand1Eb@kosfxbCN9bq8GSoiDx7N/1KuPrZT4KTXM7aEkWeeQvHw "C++ (clang) – Try It Online")
Basic port of @xnor's algorithm without the clever stuff.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 3 bytes
```
TkI
```
[Try it online!](https://tio.run/##Dca5DcAgEEXBhl4AC8tRgnNniNwSoeX6vzcZzfO9R7rPJWk5k2w4Rs9YodLjjRHWcJJoHnUKtn8 "Husk – Try It Online")
Key on value, then transpose.
[Answer]
# [Perl 5](https://www.perl.org/) `-a`, 46 bytes
```
say%k=()while s/\d+/$k{$&}++?$&:(say$&)&&''/ge
```
[Try it online!](https://tio.run/##K0gtyjH9/784sVI121ZDszwjMydVoVg/JkVbXyW7WkWtVlvbXkXNSgOoQEVNU01NXV0/PfX/f0MFYwUTBSMFMwVTBUMFCyDP4l9@QUlmfl7xf11fUz0DQ4P/uokA "Perl 5 – Try It Online")
Input is on one line, whitespace separated.
Output is one element per line with a blank line between groups.
] |
[Question]
[
[Inspired by wezl.](https://chat.stackexchange.com/transcript/message/61328796#61328796)
Your challenge is to take words (sequences of `[a-zA-Z]`) and truncate them to length 3. For example, `never gonna give you up` would become `nev gon giv you up`.
Words will not necessarly be delimited by spaces - for example, [`youtube.com/watch?v=dQw4w9WgXcQ`](https://www.youtube.com/watch?v=dQw4w9WgXcQ) will become `you.com/wat?v=dQw4w9WgX`. Input will be printable ASCII.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins!
## Testcases
```
never gonna give you up -> nev gon giv you up
youtube.com/watch?v=dQw4w9WgXcQ -> you.com/wat?v=dQw4w9WgX
code golf -> cod gol
happy_birthday_to_you -> hap_bir_to_you
*hello world* -> *hel wor*
abcd1234fghi -> abc1234fgh
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~21~~ 20 bytes
-1 byte thanks to [coltim](https://codegolf.stackexchange.com/users/98547/coltim)!
```
{5>1(1+*)\~"a{"'_x}#
```
[Try it online!](https://ngn.codeberg.page/k#eJwdjEsKwjAYhPc9RYgLtYISrQsF9Qxd6UIIeScQ+5eQNpaiZzdmNzPfzOjzfLySFdnU6+cXsxkv6fuzqCqNcKdGFZCBrmPIuFGhCQY09PjPsowDV1sBr11iUdjbeJFtatLpbh6iLR0BUuW518VZ1vcT5S5EK9lEI9D8UUhtlfeAEgQv65IwLiTZHxptrMM/b4k0OA==)
`{ ... }#` Filter the input using the boolean mask returned by the left function.
`_x` Convert the string to lowercase.
`~"a{"'` For each character, is it in `["a", "{")`?
`1(1+*)\` A scan that converts each 1 to the number of consecutive 1s up to it, incremented by 1. 0s are mapped to 1.
`5>` Keep the indices where this is at most 4.
[Answer]
# x86-64 machine code, 29 bytes
```
83 C9 FF AC 88 07 2C 41 72 06 24 1F 3C 1A 72 02 31 C9 83 F9 FC 7E EC B0 00 AE E0 E7 C3
```
[Try it online!](https://tio.run/##dVJNj9MwED17fsVQVCnppmXTrVbQUjggceOwXHalXVQ5tpMYOXZkO/0A7V@nTPqlBcHFE795b96zHTGuhNjveWgwwa@DBCaVcQU3WEI5B@Y8KrHNcJxDiNxH41xLsHEyFMAat8ZHL/W3DLkBFrqCaobX21kO7HuB1kWjYlQeGLfy1Ms/AxNNe9hNbw88HU60i4A8tmdvWuDMmB@1x0wzEhuFl2DHQAcXCiN4H7HH7Y@XHK8ipANMF7B2WmKZiJp7HPkMjx@BOvBaW2E6qfB9iFK7Sf3hD8hrW/WYthEbrm2Swk9K1uvDYz59SxfiD3UBbFNrCpmUlYohCRkSnGE/1aYpMJKxMiHz3paxlibHMhkMw4BG9NAzXMAn@4WLWluFwkk1H/Rt4WyI2NmgK6vk6QgtLjH5ZyctF39BgoZIh2cPHF5PH8hbLEft1VW6wFN8ga@W9HifbnrTCzkZaix2UYX0yZKoHf/PlVTP@71Va@WxctZyrPRa4c512LVAJXaFmgjXvNnwKOqP66W828w27@6rB3EH/XFJZkqoedvuVoX2sZZ8t4puRVoY1coYhxvnjRwBL4TMpzezsqo1/BKl4VXYj5vbGS30ny8puzK/AQ "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 byte string; and the address of the input, as a null-terminated byte string, in RSI.
In assembly:
```
f:
or ecx, -1
startloop:
lodsb
mov [rdi], al
sub al, 0x41
jb notletter
and al, 0x1F
cmp al, 26
jb isletter
notletter:
xor ecx, ecx
isletter:
cmp ecx, -4
jle startloop
mov al, 0
scasb
loopnz startloop
ret
```
[Answer]
# [Python](https://www.python.org), 52 bytes
```
lambda s,c=0:[i for i in s if(c:=-~c*i.isalpha())<4]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3TXISc5NSEhWKdZJtDayiMxXS8osUMhUy8xSKFTLTNJKtbHXrkrUy9TKLE3MKMhI1NDVtTGKhelUKijLzSjS00jSUEp2cXVLjE5OSgTg-Md5QSVOnOLXAVklJE6J2wQIIDQA)
Outputs as a list of characters.
If that's not allowed:
## [Python](https://www.python.org), 58 bytes
```
lambda s,c=0:"".join(i*((c:=-~c*i.isalpha())<4)for i in s)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3rXISc5NSEhWKdZJtDayUlPSy8jPzNDK1NDSSrWx165K1MvUyixNzCjISNTQ1bUw00_KLFDIVMvMUijUhJuwpKMrMK9FI01BKdHJ2SY1PTEoG4vjEeEMlTaiSBQsgNAA)
[Answer]
# [Zsh](https://www.zsh.org/), 39 bytes
```
<<<${1//(#m)[a-zA-Z](#c3,)/$MATCH[1,3]}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwebi1JL8ghKF1IqS1LyU1JT0nPykpaUlaboWN9VtbGxUqg319TWUczWjE3WrHHWjYjWUk411NPVVfB1DnD2iDXWMY2shyhdAqC3RSolOzi6p8YlJyUAcnxhvqBQLlQMA)
[Answer]
# [JavaScript (V8)](https://v8.dev/), 39 bytes
```
x=>x.replace(/(?<=[a-z]{3})[a-z]/gi,"")
```
[Try it online!](https://tio.run/##JY7BboQgGITvfQrCCbVq2vXQJsv6DJ62SdOYX0CgYYWwiNqmz27JepuZbzKZb4hwZ167UMa3faT7Si9r5YUzwASpSXumn1D@fP2e/rKHqKV@xjjbJU1N5/UUyFpgVF4QLkayZtmTJHgSUXgk7TQBkjoKtNkZzQ4/YNJhHkTF7K1eIDDVRsq7pVner/KDdUeJWS7SgBkPq8C5rR@0D4rD1gfbp5UD5UoYY9FiveH5EcHA@MvrqRml0unqPw "JavaScript (V8) – Try It Online")
Pretty straightforward.
```
x=>x.replace(/(?<=[a-z]{3})[a-z]/gi,"")
x=>x.replace( , ) // standard regex replace setup
/ /gi // case insensitive, replace all occurences of
[a-z] // an alphabetical character
"" // with the empty string
(?<= ) // given that it is immediately following
[a-z]{3} // 3 consecutive alphabet characters
```
[Answer]
# BQN, 22 bytes
```
⊣/˜3≥·(×+⊢)`2|"A[a{"⊸⍋
```
[Try it here!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oqjL8ucM+KJpcK3KMOXK+KKoilgMnwiQVtheyLiirjijYsKCuKAolNob3fiiJhGwqgg4p+oCiJuZXZlciBnb25uYSBnaXZlIHlvdSB1cCIKInlvdXR1YmUuY29tL3dhdGNoP3Y9ZFF3NHc5V2dYY1EiCiJjb2RlIGdvbGYiCiJoYXBweV9iaXJ0aGRheV90b195b3UiCiIqaGVsbG8gd29ybGQqIgoiYWJjZDEyMzRmZ2hpIgrin6kKCkA=)
-5 bytes thanks to @ovs!
## Explanation
* `⊣/˜...` filter input by constructing this binary array...
* `2|"A[a{"⊸⍋` for each char, 1 if alphabetical and 0 otherwise
+ more literally: check if ordering the char into `A[a{` will yield an odd index
* `(×+⊢)`` count consecutive runs of 1s
* `3≥·` for each element, check if >= 3
Example of how the input is manipulated under the hood:
```
never gonna give you up # input
11111011111011110111011 # 2|"A[a{"⊸⍋
12345012345012340123012 # (×+⊢)`
11100111100111101111111 # 3≥·
nev██ gon██ giv█ you up # ⊣/˜
```
[Answer]
# [brev](https://idiomdrottning.org/brev), 81 bytes
```
(print (strse (read-line) '(+ alpha) (as-list (fn (take x (min (length x) 3))))))
```
I would've wanted:
```
(print (strse (read-line) 'word (as-list (fn (take x (min (length x) 3))))))
```
but that YouTube example looks differently.
Reading and writing stdin/out adds 13 bytes, it's just 68 as a function:
```
((over (strse x '(+ alpha) (as-list (fn (take x (min (length x) 3))))))
'("never gonna give you up"
"youtube.com/watch?v=dQw4w9WgXcQ"
"code golf"
"happy_birthday_to_you"
"*hello world*"
"abcd1234fghi"))
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 7 bytes
```
øWƛL3∵Ẏ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwiw7hXxptMM+KIteG6jiIsIiIsImhhcHB5X2JpcnRoZGF5X3RvX3lvdSJd)
Would be 5 bytes if not for modular indexing. Undone by something otherwise useful, I say!
## Explained
```
øWƛL3∵Ẏ
øW # Split the input on words (/[A-z]+/). Numbers and punctuation are left as single character strings.
ƛ # To each "word":
L3∵ # get the minimum of the length of the word and the number 3. This is needed to account for modular indexing. This would otherwise just be `3`
Ẏ # get the first amount of characters of the word, where the number of characters is the number we just calculated.
# the s flag joins everything into a single string before printing it.
```
[Answer]
# [R](https://www.r-project.org), 38 bytes
```
\(x)gsub('([a-z]{3})[a-z]+','\\1',x,T)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TZBLboMwFEWVSQdZhUc1ENIqIYNmgLKGSJFSqUTI-ItEMSI2hFZdSSc0UhfVriY2GCkjv3fPeXfg75-6v7L4Vyu2fPl7TLyLz88686D3hpYfp8_oyx-GBQxhkqxgeAkP_mj_zx6YB0va0BpwWZYI8LyhoJMa6Ar6II6BpZZZMoG5OTKj0hl9wvL9uUUKi10Tk327abdH_or37thYk3HPhwYsCTXNBXOu2e06MIGqqkuzvFaCoC5VMjVNzjPMkim0eiBoUUjQyroggdNsZpNgMFCGyWodbRgXuRNM5BI4H7-j78f3Bg)
-2 bytes thanks to pajonk!
Direct application of `gsub`.
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 17 bytes
```
s/\pL{3}\K\pL*//g
```
[Try it online!](https://tio.run/##TY3LDoIwEEX3/YquSQDxsXChfoC6cKULElLa2pJUpsECIcZft84kmLiauefcab3u3CbGZ17602v1Lo84kzw3MbZ60B030LaCm2bQfIKe956ne46KBOGZMhyhr3Um4ZGPIkh7GHbqMq7H7dXc5IWusPLT/5JJUBqfc3cqYaCdWeH9VNVNF6wSUxWgoo@wgILwTFhitXPAR@icSsgToJgwUUtVLFfru7ENGcxz/IAPDbTPmPqYnjfZolh8AQ "Perl 5 – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 21 bytes
```
i`([a-z]{3})[a-z]+
$1
```
[Try it online!](https://tio.run/##HcuxDsIgFEDRna9gcNAaNbVdHIzf0EkTY@orvAIJ8hoCJWj8dmyc7l2Ox2AclGKe6zvs3o9P8938Z8tWdSkOZ/RckXPAlZmRZ4o8TmxJiAPuBb0OCYLQl/ksu9Sm01XdRMcESVyYHZmGacr9YHzQEnIfqF8sqzRaSzyRt7JiMAhZH5t2VNr8AA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Case-insensitively matches runs of three letters followed by at least one more letter and keeps only the first three.
[Answer]
# [Python](https://www.python.org), 84 bytes
```
lambda s:''.join([w,w[:3]][w.isalpha()]for w in re.split('([^a-zA-Z])',s))
import re
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VY9PSsQwFMb3c4rskg5tRWcWWhjEIwwIirUOaZM0kTQvpGlDvYqbguh53HobM8wg9m0efH9-8L1_2clLMPOH2D1_Dl5k1z_3mnY1o6gvMM5fQRlShjSUxaaqypCrnmorKUkqAQ4FpAxyPO-tVp5gUr7Q7O0ue6oSnPZJslKdBedj4sz-Ppb6Y6nEho_coRaMoahVI0cTDGiwOEUr9Hc4in6oed5AdxGob-TtuGP7sA03D-1js8fp_3ADjEeiFktZUmunQ62cl4xOBw-HSF1G1pJrDSiA02y9tGjdsMurzVa0UuGqiJZ1yngiSFx42jXPp_8L)
[Answer]
# [Factor](https://factorcode.org/), ~~58~~ ~~50~~ 48 bytes
```
[ R/ [a-z]+/i [ 3 short head ] re-replace-with ]
```
[Try it online!](https://tio.run/##ddHBSsQwEAbge59izLHSLbp7UVGP4kVYRRRKKWkybQLdJqZpaxWfvSami6uwcwrM988MpKLMKjM/P90/3F2CwRrfNXT41mPLsANt0NpJG9lauIqizwhckRYHNFCrtqVQywFhUj30msC@TiC5Aae88WIBIe3eti9xxdQuHall4na45ttxM1681K9sS0Laqb047IcRTHF0s5vqd@Xf@hnhlEchIqjWU1FKYwWnU2FV4TaQ/xGnvFnaIRkLbBoFozINj8mxZV55E4cQLRk/O19vqlpIcvRCpxYUfUVzBo8pZDT5yE9TCRmsoRPKWBBIOeTucxKDuqEMk1FaAfm8oxpW8zc "Factor – Try It Online")
[Answer]
# [Python](https://www.python.org), 57 bytes
```
lambda s:re.sub('([a-z]{3})[a-z]+',r'\1',s,0,2)
import re
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VY9LasMwGIT3OcW_k50qSfNYNIHQM2SVQhKMrIclkCWhh41bepJuDKU9T7e9TU0TSj2bf5gZPvjfPl0XpTX9u9ifP1IUs4fvrSZ1yQiEnefzkMoMZScye768rF_zX3OHsEfnJcIB3-NVPlG1sz6C5zfAl7AeAigDJ2R4wz1U1hgClWo4dDZBcgjDBP6EhjCmks-prRctiVQ-Nnt2aDft9lg90QPC_8fUMj4QtRjHkjjXFaXyUTLSFdEWA3U8mUqutYXWes2m44qUlC1X642opEKX3VA5r0zMRBby_PpX31_vDw)
A straight port of my regex [R solution](https://codegolf.stackexchange.com/a/248779/98085). `re.IGNORECASE` is 2.
Framework taken from solid.py's answer.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~38~~ 25 bytes
Simple regex solution, matches runs of letters and captures the first 3, replacing matches with the capture group.
```
aR-`([A-Z]{3})[A-Z]*``\1`
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgebSSbkG5UuyCpaUlaboWOxODdBM0oh11o2KrjWs1wQythIQYwwSIPFTZ7milvNSy1CKF9Py8vESF9MyyVIXK_FKF0gK4SQA)
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~78~~ 65 bytes
```
c;*p;f(*s){for(c=0,p=s;*s;p+=c<4)c=iswalpha(*p=*s++)?c+1:0;*p=0;}
```
[Try it online!](https://tio.run/##bZFfb5swFMXf@ynukCqBSdakzR5ayvow7a0vfdqkJoqciw2ojm1hJySL8tXHbP4kqBoSYB@fe/yzL05RUJk3DSZEJzwkJjpxVYWYziY6NQkxiY5TfF5EmJampkIXNCQ6JSaOoxeM508zV5jOknNTSgtbWsowgtMNuMcJBCwz1ryvIIXTayDZnlWQKykp5OWewVHtYKeDCbwGbmh3G/YV1fauphaLl32avdWL@vFX/hvfWg@qjLlywdtZQbU@rjdlZYuMHtdWrV1Gu0IKJoSCWlUiI61CN5jN7x8WPC/K4Jxc@dhBM7QsGyF6QI/3iW4gG3MNVB5qYPJEn2E8ygWk5xgwUEljAQtaEfdl@MGqDiZYHn7eLw@PP9z7zRWP5w9DtWsWhP7qS5mxgyubJf3wGUz5hykeDkeM7nqBXJQE4rh1R21Y17dr71xc17/Ws0rGy7DZcf5eoxFMhjaCGOYjg9NRH0PvmYCNrgu81UZCd3Dmtrq04n@7aWqM83zxwVvdB7NRjq6cjYfBrTAw/Q7@d2uW0t2bnUBnH27XZ6360vPNufmLXNDcNNP6Hw "C (clang) – Try It Online")
*Saved a whopping 13 bytes thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil)!!!*
Inputs a wide character string.
Performs the word truncations in place.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 31 bytes
```
->s{s.gsub(/[a-z]+/i){$&[0,3]}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1664ulgvvbg0SUM/OlG3KlZbP1OzWkUt2kDHOLa29n@BQlq0Ul5qWWqRXlJqap5CaUF8SUZqUaqOno6xiaGOUux/AA "Ruby – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
=ŒskŻḣ€4FḊ
```
[Try it online!](https://tio.run/##y0rNyan8/9/26KTi7KO7H@5Y/KhpjYnbwx1d/w@3a0b@/6@Ul1qWWqSQnp@Xl6iQnlmWqlCZX6pQWqCko6AEZJWUJqXqJefn6pcnliRn2JfZpgSWm5RbhqdHJAeClCTnp6QCNeekgTgZiQUFlfFJmUUlGSmJlfEl@fFAE0ASWhlAV@QrlOcX5aRogQQSk5JTDI2MTdLSMzKVAA "Jelly – Try It Online")
It's absolutely hideous, but the most elegant thing I've come up with is a byte longer: `nŒs‘×¥\<4x@`
```
Ż Prepend a 0 to the input, and
k partition that after indices where
= the original input equals
Œs itself case-swapped.
ḣ€4 Keep the first 4 elements of each slice (one non-letter + up to 3 letters).
F Flatten,
Ḋ and remove the 0.
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
îªZ╛▲?↕
```
[Run and debug it](https://staxlang.xyz/#p=8ca65abe1e3f12&i=never+gonna+give+you+up+%0Ayoutube.com%2Fwatch%3Fv%3DdQw4w9WgXcQ+%0Acode+golf+%0Ahappy_birthday_to_you+%0A*hello+world*+%0Aabcd1234fghi+%0A&m=2)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes
```
ΦθΦ⁴¬№α↥§⁺×_μθκ
```
[Try it online!](https://tio.run/##LYzLCsIwEEX3fsXQ1RTizp0rKShupIu6lpCMNTjJtHmI9OdjRS8cOHDgmoeORjTX2kcXMh4dZ4o4K/jbTsFFMnZS1qoVXKeJotGJ8JDPwdIbey4JB@cpYXNrFPhWwbzybH/bf79ljNp7F0boy7IwJdDBQieW4CR839Ttiz8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Generates all overlapping substrings of up to four characters ending at each character and keeps those containing at least one non-letter.
```
θ Input string
Φ Filtered by
⁴ Literal integer `4`
Φ Any value satisfies
α Predefined variable uppercase alphabet
¬№ Does not contain
_ Literal string `_`
× Repeated by
λ Current value
⁺ Concatenated with
θ Input string
§ Indexed by
κ Current index
↥ Uppercase
Implicitly print
```
Note that I use `Filter` instead of `Any` because the latter does not implicitly convert an integer to a range.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 15 bytes
```
sf<=Z*hZ}rT0G4Q
```
[Try it online!](https://tio.run/##K6gsyfj/vzjNxjZKKyOqtijEwN0k8P9/pYzEgoLK@KTMopKMlMTK@JL8@Mr8UiUA "Pyth – Try It Online")
Port of [pxeger's Python answer](https://codegolf.stackexchange.com/a/248771/65425)
[Answer]
# [Julia](https://julialang.org), ~~46 bytes~~ 42 bytes
~~```
f(s)=replace(s,r"([\p{L}]{3})[\p{L}]*"=>s"\1")
```~~
We do not need the square brackets, thx to @thejonymyster:
```
f(s)=replace(s,r"(\p{L}{3})\p{L}*"=>s"\1")
```
[Attempt This Online!](https://ato.pxeger.com/run?1=vZO_b9NAFMcHtvsrnq4SSiInUdsgCpILA2OXTjBUii7284_WORvfOSGpylAGFhATEwOpSAa2glp-SN38DzgjTP5TuBc7qEjtysnS3Xuf7_fde5Lvw-Iwi0Ix-33n7gYEWifqYbfrxC76ceR1lBbOEb5wAiF97DjxsPs8Q6XDWKruVm_n_r3trk4z6QiN7XGcuqodyrZoK5QapYOMuUILm3POJI4wBT-WUoAfjhAmcQZZAu1dMIgApessM5vOBtWNY6Gd4NHIdvfHvfGDp_4zZ59cRrLG1yGj3oGaJ5EJ6MwCkSST_iBMdeCKSV_HfbrICAygdJ1hrQCjKAYzSuS2iFOCwhYTA8fd3NrueX4QEjFxHdazmVWN1zfrphkrwV-8nhVhFEb5GaFAQH6l1RS0kJP8TFsQ5J9NbKqraX4VHebfJAzRBzGFlcKl2qsCay9ZK9vKck3NillxXlzA8rS4LL4s30HxtfhRXBSXy9PlG6rzD68pK-c_y_l5uXgN5fx9uXhVzr-Xi7fl_BPcTqwbtLd71yfTwX-7jD3JYJjlHzW4GErYwwFKyOfSxVR2qJOaEya6Yh1GP_Ii015751fLa6imnWISCQcbykp54yA53js53j5prg4tbu8qfrDJm7XjpRenEJnbzKeSKNQNehwWP5DcOkJMcJjoie2JSGGTgVElFppnYFdaY7Q4dcYJbiRpKHUkG6TiwFdKAo-FUpjqhkekadtVHqVb9z2bVfsf)
`\p{L}`: <https://stackoverflow.com/questions/3617797/regex-to-match-only-letters>
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.γa}DaÅÏ3£}J
```
[Try it online](https://tio.run/##yy9OTMpM/f9f79zmxFqXxMOth/uNDy2u9fr/vzK/tKQ0KVUvOT9XvzyxJDnDvsw2JbDcpNwyPD0iORAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/vXObE2tdEg@3Hu43PrS41uu/zv9opbzUstQihfT8vLxEhfTMslSFyvxShdICJR0lIKOkNClVLzk/V788sSQ5w77MNiWw3KTcMjw9IjkQqCI5PyUVqDUnDcjOSCwoqIxPyiwqyUhJrIwvyY8H6geKa2Wk5uTkK5TnF@WkaAH5iUnJKYZGxiZp6RmZSrEA).
**Explanation:**
```
.γ } # Adjacent group the (implicit) input-string by:
a # Letters
D # Duplicate this list of groups
a # Check which groups only consist of letters
ÅÏ } # Apply on the truthy indices:
3£ # Keep up to the first 3 characters
J # Join all groups back together to a string
# (which is output implicitly as result)
```
[Answer]
# [Lua](https://www.lua.org/), 41 bytes
```
print(((...):gsub('(%a%a?%a?)%a*','%1')))
```
[Try it online!](https://tio.run/##DcLBCoAwCADQX/EiasSga5e@xWCMQbixctDXW493uUb0Ue1h5pSS7OX2k4lRUY@/oC60Em4kIhFheeYBpZkplDozvM3B@wc "Lua – Try It Online")
[Answer]
# [sed](https://www.gnu.org/software/sed/) -E, 24 bytes
```
s/([A-Z]{3})[A-Z]*/\1/gi
```
[Try it online!](https://tio.run/##Hcu9DsIgFEDhnadg1CaV1HZxMMbBB@ik8ScNhSuQIJe0UNIYX11snM5ZvhFkqVzMeWSr27G8Pt71Z/2fgt0rpkzODiYYqELnOFVmAjpjpNGTJSH2sBH4YokHoQ/TXrapSbuzuoiWCJSwMPskmns/d70ZgpZ87gJ2iyWFBmuRJhysLAjvhay2dfNU2nzRB4NuzOXpBw "sed – Try It Online")
[Answer]
# [Raku](https://raku.org) -p, 20 bytes
### (formerly known as Perl\_6)
```
s:g/<:L>**3<(<:L>*//
```
FYI, Raku regexes tolerate whitespace by default, so a more readable (exploded) version would be:
```
s:g/ <:L>**3 <( <:L>* //
```
[Answer]
# [Rust](https://www.rust-lang.org/), 109 bytes
```
fn f(s:&str)->String{let mut n=0;s.chars().filter(|c|if c.is_alphabetic(){n+=1;n<4}else{n=0;true}).collect()}
```
[Try it online!](https://tio.run/##NVDLTsMwELz3K5YcKju0gUIuUFq@oeIAEkKR42xiS64d2ZtGVepvLy4ox3ns7Gj8EOh6bS20LLwuA3m@3n@Q17abDBIcBwK7e9yGQirhA@NFqw2hZxd50S3IQodKmF6JGklLxid7v9ts7VsZ0QScbqfkB4y8kM4YlMR4vH07Cm0Zh2kB0DoPAbSF5XdCAJnFE3ronLUCOn1COLsBhj5b/csJ0VBjCjw@jIKkej/tmsNYji@f3Zc8zDbpGkwhpp0JJfr@XNXak2rEuSJXpaRZzBUa42B03jT5TIpaNpun57JTOvv56wrQp2nI2DuWTRHWe5hitoI8rNJ@eeB8m0xxEa@/ "Rust – Try It Online")
[Answer]
# [J-uby](https://github.com/cyoce/J-uby), 29 bytes
Port of [G B’s Ruby answer](https://codegolf.stackexchange.com/a/248793/11261).
```
~(:gsub+(~:[]&3&0))&/[a-z]+/i
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qXLBIjfbpaUlaboWe-s0rNKLS5O0NeqsomPVjNUMNDXV9KMTdatitfUzIWq2F5SWFCu4RStpZaTm5OQrlOcX5aRoKcVCZBcsgNAA)
## Explanation
```
(~(:gsub + ) # replace
& /[a-z]+/i) # each word
(~:[] & 3 & 0) # with its first three characters
```
[Answer]
# [Scala](https://www.scala-lang.org/), 54 bytes
Golfed version. [Try it online!](https://tio.run/##RY3NasMwEITvfopF5CCFJqVNLjV1Qx6gh1BKCyEEWZJlFUUysvxX42d3VSfEt53Zb2ZKRjUdbfojmId3qgz0EQAXGVyCwNTJMoa9c7Q7fninjDyRGD6N8pBAP/5zGW7j64sk7dqJQlMm9lpjhHevyZGufk/9ZiDTgR4AITKGheuGDFm4he@1RZBeG1yiRQurN1j0YYIMiERTTmJkRC0cSGsMBalqAZ2toCoCcQOC9lUq1sxeHhvqWb6rE35ots3Ll/xmhxlklotQpLPZymlRdOdUOZ9z2p29PYe2@b3MhdYWGus0X842TRl/et5sM5mryR2iYfwD)
```
def f(x:String)=x.replaceAll("(?<=[a-z]{3})[a-z]", "")
```
[Answer]
# [Uiua](https://uiua.org) [SBCS](https://tinyurl.com/Uiua-SBCS-Jan-14), 18 bytes
```
↘1▽<5\(+1×)≠0±.⊂@a
```
[Try it!](https://uiua.org/pad?src=0_9_0__ZiDihpAg4oaYMeKWvTw1XCgrMcOXKeKJoDDCsS7iioJAYQoKZiAibmV2ZXIgZ29ubmEgZ2l2ZSB5b3UgdXAiCmYgInlvdXR1YmUuY29tL3dhdGNoP3Y9ZFF3NHc5V2dYY1EiCmYgImNvZGUgZ29sZiIKZiAiaGFwcHlfYmlydGhkYXlfdG9feW91IgpmICIqaGVsbG8gd29ybGQqIgpmICJhYmNkMTIzNGZnaGkiCg==)
```
↘1▽<5\(+1×)≠0±.⊂@a
⊂@a # prepend letter a
≠0±. # mask of letters
\(+1×) # multiply-increment scan
▽<5 # keep letters that correspond to less than 5 in scan
↘1 # remove first letter
```
] |
[Question]
[
Your challenge is to read a "password" from the keyboard / standard input.
**Challenge**:
* Read a string `s` invisibly.
* For each of the characters in `s`, print a character `c`.
* In realtime.
**Rules:**
* You must print `c` in realtime. As soon as the user enters a character you must display `c`.
* `c` must be constant, i.e. it must be the same character.
* `c` can be any *visible* character (i.e. it cannot be a newline, space, tab, or unprintable).
* `c` can't be based on `s`, i.e. `c` must be defined/constant before `s` is read.
* `c` must be the same every time the program is run.
* `c` can be one of the characters in `s` if by accident, as long as all other rules are followed.
* None of the characters of `s` may appear on the screen, `c` excepted (see previous rule).
* You may use any reasonable methods of input and output as long as all other rules are followed.
* You may assume that the length of `s` is never longer than the terminal/graphical window width.
* If using a terminal, your program should terminate after a newline or EOF is entered.
**Example**:
If `s` was `password01` and `c` was `*`, the output would look something like:
[](https://i.stack.imgur.com/5R49U.gif)
**Winner**:
The shortest submission in each language wins.
[Answer]
# HTML, 20 bytes
```
<input type=password
```
---
## Alternative: HTML + JavaScript, 51 bytes
Although the OP has confirmed that to be valid, here's a solution using JS for the purists!
```
<input id=i oninput=i.value=i.value.replace(/./g,8)
```
[Answer]
# Vim, 36 bytes:
```
:im <C-v><CR> <C-v><esc>ZQ<CR>:au I<tab><tab> * let v:char=0<CR>i
```
This uses *vim-key notation*, so `<C-v>` is *control-v*, `<CR>` is enter, `<esc>` is the escape key, and `<tab>` is the tab key.
*c* is `'0'`.
Here is a hexdump to prove the byte count is accurate:
```
00000000: 3a69 6d20 160a 2016 1b5a 510a 3a61 7520 :im .. ..ZQ.:au
00000010: 4909 0920 2a20 6c65 7420 763a 6368 6172 I.. * let v:char
00000020: 3d30 0a69 =0.i
```
This works by running the following two ex commands:
```
:imap <CR> <esc>ZQ
:autocmd InsertCharPre * let v:char=0
```
The first one means
```
:imap " Anytime the following is pressed in insert mode:
<CR> " (the 'enter' key)
<esc>ZQ " Then act as if the user instead pressed '<esc>ZQ' (close the buffer)
```
And the second one means
```
:autocmd " Automatically as vim runs:
InsertCharPre " Any time the user is about to insert a char
* " In any type of file
let v:char=0 " Then instead insert a '0' character
```
[Answer]
# Ruby with Shoes, 29 characters
```
Shoes.app{edit_line secret:1}
```
Sample output:

[Answer]
# [str](https://github.com/ConorOBrien-Foxx/str), 5 bytes
```
n=?,1
```
Due to a bug, this is 5 bytes. It should be only 1 byte:
```
1
```
[](https://i.stack.imgur.com/VYDC2.gif)
[Answer]
# [Aceto](https://github.com/aceto/aceto), ~~8~~ ~~7~~ 6 bytes
```
,!`XpO
```
### Explanation:
Read a character (`,`), negate it (`!`) and conditionally exit. Print the zero on top of the stack (`p`) and go back to the beginning.
Run with `-F` to see the effect immediately (because flushing)
My first solution was based on the sandbox post, with spaces allowed as replacement characters and no need to exit on enter (4 bytes):
```
,'p>
```
[Answer]
# C on POSIX, ~~128~~ ~~117~~ ~~113~~ 96 bytes
-11 thanks to Quentin searching through `termios.h`
-4 thanks to Quentin pointing out my stupid mistakes
-17 because Quentin is a freaking wizard.
```
c,t[15];f(){for(tcgetattr(1,t),t[3]&=~10,tcsetattr(1,0,t);(c=getchar())^10&&c^4;)printf(".");}
```
This puts STDIN into raw/invisible mode so that it can get keypresses in realtime. This takes 77 bytes and I'm sure I can golf it in a bit. **Note that this does not reset STDIN upon exiting so it will mess up your terminal if you don't do so manually.**
Here's how you can reset STDIN:
```
void stdin_reset(void)
{
struct termios t;
get_stdin(&t);
t.c_lflag |= ECHO;
t.c_lflag |= ICANON;
set_stdin(&t);
}
```
Output as shown in the GIF :-)
[Answer]
# x86 machine code on MS-DOS - 14 bytes
As usual, this is a full COM file, that can be run on DosBox, plus most DOS variants.
```
00000000 b4 08 b2 2a cd 21 80 f4 0a 3c 0d 75 f7 c3 |...*.!...<.u..|
0000000e
```
Commented assembly:
```
org 100h
section .text
start:
mov ah,8h ; ah starts at 08h (read console, no echo)
mov dl,'*' ; write asterisks (we could have left whatever
; startup value we have here, but given that dx=cs,
; we have no guarantee to get a non-zero non-space
; value)
lop:
; this loop runs twice per character read: the first time with
; ah = 08h (read console, no echo syscall), the second time with
; ah = 02h (write console); a xor is used to switch from one
; mode to the other
int 21h ; perform syscall
xor ah,0ah ; switch syscall 08h <=> 02h
cmp al,0dh ; check if we read a newline (if we wrote stuff
; we are just checking the last value read, so
; no harm done; at the first iteration al starts
; at 0, so no risk here)
jne lop ; loop if it wasn't a newline
quit:
ret ; quit
```
[Answer]
# [Python 2](https://docs.python.org/2/), 50 bytes
```
from msvcrt import*
while'\r'!=getch():print'\b*',
```
Only works on windows
[Answer]
# [AHK](https://autohotkey.com/), 17 bytes
```
InputBox,o,,,HIDE
```
Built-ins are not interesting.
[Answer]
# Java 5-8, ~~125~~ ~~122~~ ~~131~~ 124 bytes
```
class X{public static void main(String[]a){new java.awt.Frame(){{add(new javax.swing.JPasswordField());setVisible(1>0);}};}}
```
# Ungolfed:
```
class X{
public static void main(String[]a){
new java.awt.Frame(){
{
add(new javax.swing.JPasswordField());
setVisible(1>0);
}
};
}
}
```
# Result:
[](https://i.stack.imgur.com/4FI2u.png)
# Credit:
*-3 @MD XF (Pointed out my stupid mistake with `String[]args`)*
*-7 @KritixiLithos (Pointed out `public class` can just be `class`)*
[Answer]
# Mathematica 34 bytes
```
InputString["",FieldMasked->True];
```
An single asterisk appears, after each character is keyed in. The empty quotation marks are for the title that appears in the pop-up input window.
The `;` prevents the password from being printed.
[](https://i.stack.imgur.com/kDmo0.png)
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 54 bytes
```
: f begin key dup 4 - swap 13 - * while ." *" repeat ;
```
### Explanation
```
begin \ enters the loop
key \ waits for a single character as input, places ascii code of character on stack
dup \ duplicates the key value on the stack
4 - \ subtracts 4 from the key value (shorter way of checking for not equals)
swap \ swaps the top two stack values
13 - \ subtract 13 from the key value
* \ multiply top two stack values (shorter version of "and")
while \ if top of stack is true, enter loop body, else exit loop
." *" \ output *
repeat \ go back to beginning of loop
```
[Answer]
# Vim, ~~58~~ ~~50~~ ~~52~~ 50 bytes
Added to make sure it handled spaces properly.
Thanks to @DJMcMayhem for a bunch of help and ideas
```
i:im 32 *Y94pVGg
kWcW<Space>
:im
ZQ
dG@"qi
```
In typical Vim key syntax below. The characters marked like with a `^` are `Ctrl+<char>`, so `^Q`=`Ctrl+q`
```
i:im ^V^V32 *^[Y94pVGg^A
kWcW<Space>^[
:im ^V
ZQ
dG@"qi
```
There's no TIO link, because you'd need to directly input to Vim (as opposed to pre-inputting like normal). To run the code you need to type it into Vim, and then you can type your password and hit enter. It won't do anything with the password. It won't even know what it was. As soon as you hit enter the Vim window will `:q!`
This works by mapping all printable ASCII to `*` in insert mode, and mapping `<CR>` to `<ESC>:q!<CR>`
[Answer]
# FLTK, 47 characters
```
Function{}{}{Fl_Window{}{}{Fl_Input{}{type 5}}}
```
Sample run:
```
bash-4.4$ fluid -c password.fl
bash-4.4$ fltk-config --compile password.cxx
g++ -I/usr/include/cairo -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/pixman-1 -I/usr/include/freetype2 -I/usr/include/libpng16 -I/usr/include/freetype2 -I/usr/include/cairo -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/pixman-1 -I/usr/include/freetype2 -I/usr/include/libpng16 -g -O2 -fPIE -fstack-protector-strong -Wformat -Werror=format-security -fvisibility-inlines-hidden -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE -D_THREAD_SAFE -D_REENTRANT -o 'password' 'password.cxx' -Wl,-Bsymbolic-functions -fPIE -pie -Wl,-z,relro -Wl,-z,now -Wl,--as-needed -lfltk -lX11
bash-4.4$ ./password
```
Sample output:

[Answer]
# Processing, 53 bytes
```
String a="";void draw(){text(keyPressed?a+=0:a,9,9);}
```
This takes input via keypresses from a graphical window. The character it chooses to represent passwords with is `0`. Note that due to the high framerate, each keypress will appear as multiple `0`s (and also due to the fact that this is `keyPressed` and not `keyTyped` (not a boolean) or `keyrelease`).
[](https://i.stack.imgur.com/XoVTL.gif)
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 54 bytes
```
while read -eN1 c 2>&-;[[ ${c/$'\r'/} ]];do printf X;done
```
For scoring purposes, `$'\r'` can be replaced with a literal carriage return.
[Try it online!](https://tio.run/##S0oszvj/vzwjMydVoSg1MUVBN9XPUCFZwchOTdc6OlpBpTpZX0U9pkhdv1YhNtY6JV@hoCgzryRNIQLIzkv9/78gsbi4PL8ohSsvv0QBxgEA "Bash – Try It Online") (not much to look at)
[Answer]
## ZX81 BASIC, 54 bytes
```
10 IF LEN INKEY$ THEN GOTO PI
30 IF NOT LEN INKEY$ THEN GOTO EXP PI
50 IF INKEY$>"Z" THEN STOP
70 PRINT "*";
90 GOTO PI
```
In the ZX81 character set the printable characters are in the range space to `Z`, although you can't actually input a space this way as it's the break character.
## ZX Spectrum BASIC, 24 bytes
```
10 PAUSE NOT PI: IF INKEY$>=" " THEN PRINT "*";:GOTO PI
```
Note that `>=` counts as a single-byte keyword in Sinclair BASIC (codepoint 140 in this case).
[Answer]
# R, 29 bytes
```
invisible(openssl::askpass())
```
Built-in that handles password entries. Opens a new window and replaces the input with dots. `invisible` is used to suppress printing the password to STDOUT.
[Answer]
# Tcl/Tk, 18
```
gri [ent .e -sh *]
```
Must be run on the in the interactive shell (or have abbreviations enabled):
[](https://i.stack.imgur.com/iiMyf.png)
[Answer]
# Vim, 15 keystrokes
```
:cal inp<S-tab>'')|q<cr>
```
`<S-tab>` means `shift + tab`.
Apparently, there is a builtin for this that I wasn't aware of. Since I really like [my manual answer](https://codegolf.stackexchange.com/a/125658/31716), and this approach is radically different, I figured I should post a new answer instead of editing.
This works by calling the `inputsecret` function, then immediately quitting after it exits.
[Answer]
# 6502 machine code (C64), ~~22~~ 21 bytes
```
0e 08 20 9f ff 20 e4 ff f0 f8 c9 0d f0 01 a9 60 20 d2 ff 50 ed
```
**Usage**: `SYS 2062`
Commented disassembly listing (ACME), you can uncomment the first three commented lines to launch with `RUN` once loaded:
```
!cpu 6502
!to "password2.prg",cbm
;* = $0801 ; BASIC starts at #2049
;!byte $0d,$08,$dc,$07,$9e,$20,$32,$30 ; BASIC to load $c000
;!byte $36,$32,$00,$00,$00 ; inserts BASIC line: 2012 SYS 2062
GETIN = $FFE4
SCNKEY = $FF9F
CHROUT = $FFD2
* = $080e
keyScan:
jsr SCNKEY ; get key
jsr GETIN ; put key in A
beq keyScan ; if no key pressed loop
cmp #13 ; check if RETURN was pressed
beq $081b ; if true go to operand of next instruction (#$60 = rts)
lda #$60 ; load char $60 into accumulator
jsr CHROUT ; print it
bvc keyScan ; loop
```
Comments:
* I haven't found anything in the docs, but it seems that, after the GETIN call, beq branches only where no new key presses have been recorded;
* Using #$60 as output char, that byte can be reused as "rts" instruction when RETURN is pressed.
[Answer]
# Python 3 + `tkinter` - ~~63~~ 61 bytes
```
from tkinter import*
t=Tk();Entry(show=1).pack();t.mainloop()
```
Displays a `1` for every character, ends when closing window (OP said it's allowed).
[](https://i.stack.imgur.com/EWqof.gif)
[Answer]
# Groovy, ~~77~~ 73 bytes
```
{new java.awt.Frame(){{add(new javax.swing.JPasswordField());visible=1}}}
```
*This is an anonymous closure, with 0 required inputs.*
# Ungolfed:
```
{
new java.awt.Frame() {
{
add(new javax.swing.JPasswordField())
visible=1
}
}
}
```
---
*Edit 1 (-4 bytes): Component#visible can be directly accessed, [read more here](https://stackoverflow.com/questions/24581927/how-to-make-a-groovy-method-truly-protected).*
[Answer]
# [Micro](http://esolangs.org/wiki/Micro), 35 bytes
```
"":i{L46c:\
i~+:i
i10c=if(,a)}a
i:\
```
## explination:
```
"":i create new blank string 'i'
{ begin input loop
L input a character
46c:\ display ascii char #46 (.) (it is popped, leaving the input char from 'L'
i~+:i push i, flip i and the char around, concatinate them, and store that to i
i10c=if(,a)}a OK, a lot happens here, if a NL is in i, the loop terminates, and the final i:\ will display the input
```
[Answer]
## BF, 24 bytes
```
++++++[->++++++<],[>.<,]
```
Works with [bf.doleczek.pl](http://bf.doleczek.pl/). You can send a zero char to the program with Ctrl+Z.
Alternative solution:
## BF, 1 byte
```
,
```
This is a very tongue-in-cheek solution. My terminal is **0 characters** wide, so please don't enter any passwords longer than that.
[Answer]
## PowerShell, 12 bytes
```
Read-Host -a
```
This reads input from host and, with the -a flag treats it as a securestring/password. In the ISE it pops up a message box which has a similar behavior since the ISE doesn't allow keypress capture.
```
PS C:\Windows\system32> Read-Host -a
************
```
[Answer]
# QBasic, 48 bytes
```
DO
a$=INPUT$(1)
IF ASC(a$)=13THEN END
?"*";
LOOP
```
`INPUT$(1)` reads the next character from keyboard input. (This can include things like tab, backspace, and escape, but since the OP didn't say anything about those I'll assume we don't have to worry about them.) If the character is `\r` (ASCII 13), terminate the program; otherwise, print `*` without a newline. Repeat ad infinitum.
[Answer]
## Perl + Bash, 30 bytes
```
print"*"while$|=1+`read -sn 1`
```
`c` is `*`, uses `read` from bash, so isn't a pure Perl solution.
[Answer]
# brainfuck, 21 bytes
```
-[+>,[<->+[<.>[-]]]<]
```
Last one, I promise. No input = -1, end of input = 0
### How it Works
```
-[ Enters the loop
+>, Get input
[<->+ If not end of input it create the ÿ character and check if the input is not -1
[<.>[-]]] If there was input, print the ÿ character.
<] Exit the loop if end of input
```
[Answer]
# [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 44 bytes
```
{X=inkey$~X<>@`|~X=chr$(13)|_X\Y=Y+@*`_C?Y
```
## Explanation
```
{ DO
X=inkey$ Read a char, set it to X$
Note that INKEY$ doesn't wait for keypress, but simply sends out "" if no key was pressed.
~X<>@`| IF X$ has a value THEN
~X=chr$(13)| IF that value is ENTER
_X THEN END
\ ELSE
Y=Y+@*` append a literal * to Y$
_C Clear the screen
?Y Display Y$ (having 1 * for each char entered)
The IF's and the DO-loop are auto-closed at EOF{ DO
```
] |
[Question]
[
This is tangentially related to my quest to [invent an esoteric programming language](https://cs.stackexchange.com/a/4912/2161).
A table of the binary numbers 0 .. 15 can be used to implement a Universal Binary Function using indexing operations. Given two 1-bit inputs X and Y, *all* 16 possible functions can be encoded in a 4-bit opcode.
```
X Y F|0 1 2 3 4 5 6 7 8 9 A B C D E F
- - - - - - - - - - - - - - - - - -
0 0 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
0 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1
1 0 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1
1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
- - - - - - - - -
0 ~X ~Y ^ & Y X | 1
ZERO NOT-Y AND OR
NOT-X XOR ONE
```
So this set of 16 functions can be applied to binary inputs as the function
>
> *U(f,x,y): (f >> ((x<<1) | y)) & 1*,
>
>
>
or
>
> *U(f,x,y): (f / 2^(x×2 + y)) % 2*,
>
>
>
or with indexing or matrix partitioning.
It will be useful to know the most compact way to represent or generate such a table of values for any possible languages to be built upon this type of binary operation.
## The goal:
Generate this exact text output:
```
0101010101010101
0011001100110011
0000111100001111
0000000011111111
```
That's it! Shortest-code wins.
[Answer]
## J, 10 (13?) characters
```
|.|:#:i.16
```
Number list:
```
i.16
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15`
```
to binary:
```
#:i.16
0 0 0 0
0 0 0 1
0 0 1 0
0 0 1 1
0 1 0 0
0 1 0 1
0 1 1 0
0 1 1 1
1 0 0 0
1 0 0 1
1 0 1 0
1 0 1 1
1 1 0 0
1 1 0 1
1 1 1 0
1 1 1 1
```
Transpose:
```
|:#:i.16
0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1
0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
```
Reverse:
```
|.|:#:i.16
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1
0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1
0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
```
Do we need to remove the spaces? Looking at the other J answer it seems we do so we'll need to add 3 characters and borrow the `1":` from [Jan's answer](https://codegolf.stackexchange.com/a/12109/737).
[Answer]
## Python 2, 40
```
for n in 1,2,4,8:print 8/n*('0'*n+'1'*n)
```
[Answer]
## APL (14)
Assuming `⎕IO=0` (that's a setting):
```
⎕D[⊖(4⍴2)⊤⍳16]
```
Explanation:
* `⍳16`: numbers [0,16)
* `(4⍴2)⊤`: encode each number in base 2 using 4 digits
* `⊖`: horizontal reverse (so the MSB ends up on top)
* `⎕D[`...`]`: select these values from `⎕D` which is the string `0123456789`. (A numeric matrix is displayed with spaces between the values, a character matrix is not. So this converts each numerical bit to one of the chars `'0' '1'`).
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~42~~ 7 [bytes](//github.com/DennisMitchell/jelly/wiki/Code-page)
```
⁴ḶBUz0Y
```
[Try it online!](//jelly.tryitonline.net#code=4oG04bi2QlV6MFk)
Thanks to Dennis for his help. [Here](//chat.stackexchange.com/transcript/message/32374772#32374772) is the first message, [here](//chat.stackexchange.com/transcript/message/32384887#32384887) is the last (other discussions also occured). With his help, I apparently (almost) square-rooted the score.
[Answer]
# [///](https://esolangs.org/wiki////), 51 bytes
[Try it online](http://slashes.tryitonline.net/#code=L2EvMDEwMS9hYWFhCi9iLzAwMTEvYmJiYgovei8wMDAwLy9vLzExMTEvem96bwp6em9v&input=)
```
/a/0101/aaaa
/b/0011/bbbb
/z/0000//o/1111/zozo
zzoo
```
[Answer]
## GolfScript (18 17 15 chars)
(With thanks to Howard)
```
16,zip{','-~n}%
```
I don't understand why the 10-char
```
16,zip{n}/
```
doesn't work; I suspect that a bug in the standard interpreter is resulting in unsupported types on the stack.
An alternative at 18 characters which I understand fully is:
```
4,{2\?.2,*$8@/*n}%
```
A more mathematical approach is a bit longer, at 28 chars:
```
4,{2.@??)2.4??.@/+2base(;n}/
```
A lot of that is for the base conversion and zero-padding. Without those, it drops to 19 chars,
```
4,{2.@??)2.4??\/n}/
```
with output
```
21845
13107
3855
255
```
[Answer]
## Postscript ~~108~~ ~~177~~ ~~126~~ ~~77~~ ~~74~~ 70
```
[43690 52428 61680 65280]
{16{dup 2 mod =only 2 idiv}repeat<>=}forall
```
Reversed the values for a simpler *mod-* off method.
## ~~151~~ ~~131~~ 119
Applying a more *APL*-ish approach. *edit:* replaced string chopping and array zipping with indexing and for-loops.
```
[[0 1 15{}for]{16 add 2 5 string cvrs}forall]4
-1 1{0 1 15{2 index exch get 1 index 1
getinterval =only}for pop<>=}for
```
Indented:
```
[[0 1 15{}for]{16 add 2 5 string cvrs}forall]
4 -1 1{ % [] i
0 1 15{ % [] i j
2 index exch get % [] i [](j)
1 index 1 % [] i [](j) i
getinterval % [] i [](j)<i>
=only % [] i
}for
pop<>= % []
}for
```
Reimplementing the functions used in the winning J answer leads to this (with a lot of [support code](https://gist.github.com/luser-dr00g/9382217)).
```
-1 16 i + #: |: |.{{==only}forall()=}forall
```
`i` here is 1-based vector described in Iverson's *Elementary Functions*, hence the `-1 ... +` to produce `0 .. 15`.
[Answer]
# CJam - 16
```
4,{G,f{\m>2%}N}/
```
Equivalent java code (as explanation):
```
public class Lookup {
public static void main(final String... args) {
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 16; ++j) {
System.out.print((j >> i) % 2);
}
System.out.println();
}
}
}
```
[Answer]
# Javascript (ECMA6), 67
```
s=(k,n)=>n-.5?s((k<<n/2)^k,n/2)+"0".repeat(n)+k.toString(2)+"\n":""
```
To use this, call
```
s(255,8)
```
Bitshift!
And also XOR and a bit of recursion.
The first thing to notice is that if we take any line and you shift it (# of continuous 0's) / 2 left, we get a nice XOR to get the next line up.
For example,
```
0000000011111111 //line 4
0000111111110000 //shifted 4 to the left
```
XOR these bitwise give us
```
0000111100001111 //XOR'ed. This is line 3!
```
which is the next line up (line 3).
Applying the same process for line 3, shift 2 left and we get...
```
0000111100001111
0011110000111100
```
XOR'ed gives
```
0011001100110011
```
which is line 2.
Notice that the amount we shift halves each time.
Now we simply call this function recursively, with 2 arguments. The integer value of this line, and N, which is how much we need to shift. When we do recursing just pass in the shifted XOR'ed value and n/2.
```
"0".repeat(n)
```
is to pad 0's to the beginning of each line because toString takes out leading 0's.
[Answer]
### J, 21 characters
```
1":<.2|(2^i.4)%~/i.16
```
* `i.16` is a list of 0..15
* `2^i.4` is a list (1,2,4,8)
* `%~/` produces the table of divisions where the left argument forms rows but is the right argument to division
* `2|` calculates the remainder after dividing [each cell] by two
* `<.` floors that value to 0 or 1
* `1":` formats the table with one character per cell
[Answer]
### GolfScript, 19 chars
Another GolfScript approach
```
4,{2\?{&!!}+16,%n}%
```
[Answer]
# Ruby (44)
Boring and long: Just printing the 0-padded binary representations of the numbers.
```
[21845,13107,3855,255].map{|i|puts"%016b"%i}
```
[Answer]
# Perl (36+1)
+1 for `say`, as usual. the double `0` is not a typo :)
```
map say((00x$_,1x$_)x(8/$_)),1,2,4,8
```
[Answer]
# JavaScript (ECMA6), 108
Trying a different approach here. Even though it was encouraged to use binary operators, I allowed myself to submit this solution since the challange is also [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") and I was thinking - how can I reduce the amount of code representing those values...? **Bases**.
```
['gut','a43','2z3','73'].forEach(n=>{a=parseInt(n,36).toString(2);
alert(('00000000'+a).substr(a.length-8))})
```
(Line break for convenience).
It's a shame I had to mess with padding with leading zeros, but the point of this code is simply representing the target binary result in Base 36, which are exactly those `gut, a43, 2z3, 73` values.
Note: I realize it won't be anywhere near the winning answer, but just for the sake of the idea...
[Answer]
# [Sprects](//dinod123.neocities.org/interpreter.html), 44 bytes
```
aaaa
bbbb
zozo
zzoo o1111 z0000 b0011 a0101
```
Cedric's answer ported to Sprects.
[Answer]
# JavaScript (ES6), ~~58~~ 52 bytes
Builds the string recursively.
```
f=(n=64)=>n--?f(n)+(!n|n&15?'':`
`)+(n>>(n>>4)&1):''
```
### How it works
This recursion is based on the fact that the pattern is made of the vertical binary representation of nibbles 0x0 to 0xF:
```
0101010101010101 bit #0 <- Y = 0
0011001100110011 bit #1
0000111100001111 bit #2
0000000011111111 bit #3 <- Y = 3
----------------
0123456789ABCDEF
^ ^
X = 0 X = 15
```
Therefore, each position (X,Y) in this pattern can be expressed as the Y-th bit of X: `X & (1 << Y)`. We can also isolate this bit with: `(X >> Y) & 1`. Rather than keeping track of X and Y, we iterate on a single variable `n` ranging from 0 to 63. So, the formula becomes: `(n >> (n >> 4)) & 1`. It's actually easier to iterate from 63 to 0, so the string is built in reverse order. In other words, character *n-1* is appended to the left of character *n*.
As a side note, recursion doesn't bring anything here except shorter code.
Without the linebreaks, the code is 35 bytes long:
```
f=(n=64)=>n--?f(n)+(n>>(n>>4)&1):''
```
We need 17 more bytes to insert the linebreaks. This could be shortened to 14 bytes if a leading linebreak is acceptable.
### Demo
```
f=(n=64)=>n--?f(n)+(!n|n&15?'':`
`)+(n>>(n>>4)&1):''
console.log(f());
```
[Answer]
# Bash + coreutils, 65 bytes
Not the shortest, but not the longest either:
```
for i in {1,2,4,8};{ eval echo \$\[\({0..15}\&$i\)/$i];}|tr -d \
```
(The last character is a space)
[Try it online](https://tio.run/nexus/bash#@5@WX6SQqZCZp1BtqGOkY6JjUWtdrZBalpijkJqcka8QoxITHaNRbaCnZ2haG6Omkhmjqa@SGWtdW1NSpKCbohCj8P8/AA).
[Answer]
# [MATL](http://github.com/lmendo/MATL), 8 bytes
```
16:qYB!P
```
[Try it online!](http://matl.tryitonline.net/#code=MTY6cVlCIVA&input=)
### Explanation
```
16: % Generate range [1 2 ... 16]
q % Subtract 1, element-wise
YB % Convert to binary. Gives a 16×4 char array. Each original number is a row
! % Transpose
P % Reverse vertically. Implicitly display
```
[Answer]
# [CJam](http://sourceforge.net/projects/cjam/), ~~10~~ 9 bytes
*Thanks to @Dennis for 1 byte off!*
```
Y4m*zW%N*
```
[Try it online!](http://cjam.tryitonline.net/#code=WTRtKnpXJU4q&input=)
### Explanation
```
Y e# Push 2
4 e# Push 4
m* e# Cartesian power of 2 (interpreted as [0 1]) with exponent 4
z e# Zip
W% e# Reverse the order of rows
N* e# Join with newlines. Implicitly display
```
[Answer]
## NARS2000 APL, 22
```
"01"[⊖1+(4⍴2)⊤(⍳16)-1]
```
Derived from marinus's APL answer, which doesn't seem to work on NARS2000.
Generate vector
```
⍳16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
```
Change to zero-based
```
(⍳16)-1
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
```
Generate shape for encode
```
(4⍴2)
2 2 2 2
```
Encode
```
(4⍴2)⊤(⍳16)-1
0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1
0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
```
Adjust for 1-based indexing
```
1+(4⍴2)⊤(⍳16)-1
1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2
1 1 1 1 2 2 2 2 1 1 1 1 2 2 2 2
1 1 2 2 1 1 2 2 1 1 2 2 1 1 2 2
1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2
```
Reverse primary axis
```
⊖1+(4⍴2)⊤(⍳16)-1
1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2
1 1 2 2 1 1 2 2 1 1 2 2 1 1 2 2
1 1 1 1 2 2 2 2 1 1 1 1 2 2 2 2
1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2
```
Index
```
"01"[⊖1+(4⍴2)⊤(⍳16)-1]
0101010101010101
0011001100110011
0000111100001111
0000000011111111
```
[Answer]
# C, 73 chars
```
i;main(){for(;i<64;)i&15||puts(""),putchar(48|1&~0xFF0F0F33335555>>i++);}
```
This is just a general solution for outputting 64 bits in four 16-bit blocks; you just need to change the number `0xFF0F0F33335555` to output an other bit sequence.
simplified & ungolfed:
```
int main() {
int i;
for(i = 0; i < 64; i++) {
if(i % 16 == 0) {
puts("");
}
int bit = ~0xFF0F0F33335555 >> i;
bit &= 1;
putchar('0' + bit);
}
}
```
[Answer]
# Haskell, 73
Yikes, 73 chars! I can't for the love of god get this any smaller though.
```
r=replicate
f n=r(div 8n)("01">>=r n)>>=id
main=mapM(putStrLn.f)[1,2,4,8]
```
The real sad part about this is that if you were to echo the output using bash, you'd only need 74 characters.
[Answer]
# JavaScript (ES5) 69
`for(x="";4>x;x++){z="";for(n=0;16>n;)z+=1-!(n++&1<<x);console.log(z)}`
[Answer]
# [inca2](https://github.com/luser-dr00g/inca), ~~33~~ ~~27~~ 24
```
4 16#(,`2|(~16)%.2^~4){D
```
This is based on [Jan Dvorak's answer](https://codegolf.stackexchange.com/a/12109/2381). inca2 is able to execute this as of yesterday's bugfixes. Technically invalid since the language was invented after the question, *but* invention of a language was part of my goal in posing the question. So here's some payback in gratitude to the other answers. :)
Explanation:
```
4 16#(,`2|(~16)%.2^~4){D
(~16) integers 0 .. 15
2^~4 first 4 powers of 2: 1 2 4 8
(~16)%.2^~4 division table
2| mod 2 (and floor)
` transpose
, ravel
( ){D map to chars '0'..'9'
4 16# reshape to 4x16
```
Some of the parentheses should be unnecessary, but apparently there are some remaining issues with my interpretation of the grammar. And "ravel => map => reshape" is really clumsy: map needs to be smarter. *Edit:* bugfixes allow elimination of parens.
---
Factoring the base conversion into a separate function `N:x|y%.x^~1+[]/x.y` yields this ~~**19**~~ **16** char version.
```
4 16#(,`2N~16){D
```
---
And while I'm cheating anyway here, I've gone ahead and made this a built-in function. But, even though it's a *niladic* function (not requiring an argument), there is no support for niladic functions, and it must be supplied with a dummy argument.
# inca2, 2
```
U0
```
[Answer]
# Pyth 24 / 26
The shortest method was grc's [answer](https://codegolf.stackexchange.com/a/12104/15203) translated to Pyth which I felt was cheap so I did my own method:
### Mine: 26 characters
```
mpbjk*/8dS*d[0 1)[1 2 4 8
```
### grc's: 24 characters
```
Fd[1 2 4 8)*/8d+*\0d*\1d
```
[Answer]
## C++ 130
Converts hex to binary
```
#define B std::bitset<16>
#define C(x) cout<<x<<endl;
void main(){
B a(0xFF),b(0xF0F),c(0x3333),d(0x5555);
C(d)C(c)C(b)C(a)
}
```
[Answer]
# Haskell (Lambdabot), 47 bytes
```
unlines$reverse$transpose$replicateM 4['1','0']
```
Kinda cheaty because it uses *transpose* from Data.List and *replicateM* from Control.Monad, however both are loaded by default from Lambdabot.
Also, I'm sure there is room for improvement, just wanted to share the idea
[Answer]
# Julia (39 Bytes)
Second script I've ever written in Julia, gotta admit I'm liking Julia, she's a pretty beast.
```
hcat(map(x->collect(bin(x,4)),0:15)...)
```
**Returns**
```
[0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1
0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1]
```
Explanation:
* `bin(x,4)` - Convert int to binary integer with padding to 4 characters.
* `collect(_)` - Split string into char array.
* `map(x->_,0:15)` - Do this for the first 16 digits in the range.
* `hcat(_...)` - Splat and horizontally concatenate into a matrix.
[Answer]
## C ~~83~~ ~~77~~ ~~76~~ ~~74~~ 71
```
x;f(n){for(;x<4;x++,puts(""))for(n=0;n<16;)putchar(49-!(n++&(1<<x)));}
```
Pretty straightforward.
```
x;
f(n){
for(;x<4;x++,puts(""))
for(n=0;n<16;)
putchar(49-!(n++&(1<<x)));
}
```
[Answer]
# R, ~~53~~ 41 bytes
A translation of @grc's python answer. Shaved off 12 bytes from the original translation through use of `rep()`'s `each` and `length` arguments (and partial argument matching), and by remembering that `0:1` is equivalent to `c(0,1)`.
```
for(n in 2^(0:3))print(rep(0:1,e=n,l=16))
```
```
for(n in 2^(0:3))print(rep(c(rep(0,n),rep(1,n)),8/n))
```
You can also attempt a translation of @Gareth's J answer, something like this (34 bytes):
```
t(e1071::bincombinations(4))[4:1,]
```
However, it uses a function that's not part of base R, and outputs a matrix which is hard to format into exact printed text like in the specification.
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.