title: Write a Polyquine

text:
# Question
Title: Write a Polyquine
A polyquine is both quine and polyglot.1 You are to write a quine which is valid in at least two different languages. This is code golf, so the shortest answer (in bytes) wins.

1 I made that up. Or rather, Geobits did. Apparently, he wasn't the first one either, though.

### Rules for Quines

Only *true* quines are accepted. That is, you need to print the entire source code verbatim to STDOUT, **without**:

* reading your source code, directly or indirectly.
* relying on a REPL environment which just simply evaluates and prints every expression you feed it.
* relying on language features which just print out the source in certain cases.
* using error messages or STDERR to write all or part of the quine. (You may write things to STDERR or produce warnings/non-fatal errors as long as STDOUT is a valid quine and the error messages are not part of it.)

Furthermore, your code *must* contain a string literal.

### Rules for Polyglots

The two languages used must be distinctly different. In particular:

* They must not be different versions of the same language (e.g. Python 2 vs. Python 3).
* They must not be different dialects of the same language (e.g. Pascal vs. Delphi).
* One language may not be a subset of the other one (e.g. C vs. C++).

# Answer
# CJam/GolfScript, 34 bytes

```
{"__X.0#@@?LL
;~"N}__X.0#@@?LL
;~

```

The byte count contains a trailing linefeed, since the program wouldn't be a quine without it.

While CJam and GolfScript are *very* similar in some aspects, there are *a lot* of differences. To make this an "honest" polyquine, I decided to rely on the *differences* as much as possible. Except for the block and string syntax (which the languages share with oh so many others), no part of the code achieves exactly the same in both languages.

The online GolfScript interpreter has a bug; this program works only with the official interpreter.

### Example run

```
$ cat polyquine
{"__X.0#@@?LL
;~"N}__X.0#@@?LL
;~
$ md5sum polyquine <(cjam polyquine) <(golfscript polyquine)
e2f1f3cd68abbbceec58080513f98d9a  polyquine
e2f1f3cd68abbbceec58080513f98d9a  /dev/fd/63
e2f1f3cd68abbbceec58080513f98d9a  /dev/fd/62

```

### How it works (CJam)

```
" Push that block.                                                                        ";

{"__X.0#@@?LL
;~"N}

" Push two copies of the block, 1 (computed as 1**0) and rotate the block copies on top.  ";

__X.0#@@

" If 1 is truthy (oh, the uncertainty), execute the first copy; else, execute the second.
  Evaluating the block pushes the string it contains; N pushes a linefeed.                ";

?

" Push two empty arrays.                                                                  ";

LL

" Discard one empty array and dump the second.                                            ";

;~

" (implicit) Print all items on the stack.                                                ";

```

### How it works (GolfScript)

```
# Push that block.

{"__X.0#@@?LL
;~"N}

# Push a copy of the block; _ and X are noops, # initiates an inline comment.

__X.0#@@?LL

# Discard the 0 and execute the copy of the block.
# Evaluating the block pushes the string it contains; N is a noop.

;~

# (implicit) Print all items on the stack, followed by a linefeed.

```

---

# CJam/GolfScript, 12 bytes

```
{"0$~"N}0$~

```

Cheaty solution that avoids the languages' differences as much as possible.

Try it online:

### How it works (CJam)

```
 "0$~"       " Push that string.                                                          ";
      N      " Push a linefeed.                                                           ";
{      }0$~  " Push a copy of the block and execute it.                                   ";
             " (implicit) Print the stack.                                                ";

```

### How it works (GolfScript)

```
 "0$~"       # Push that string.
      N      # Undefined token (noop).
{      }0$~  # Push a copy of the block and execute it.
             # (implicit) Print the stack, followed by a linefeed.

```
> 15 votes

# Answer
## C#/Java, 746 bytes

I use the property that chars in Java can be written as identical unicode sequences. If we have `A` instruction for C# compiler and `B` instruction for Java, we can use the following code fragment:

```
//\u000A\u002F\u002A
A//\u002A\u002FB

```

It will be "recognized" by the following way with C#:

```
//\u000A\u002F\u002A
A//\u002A\u002FB

```

And by the following way by Java:

```
//
/*
A//*/B

```

Because of `\u000A` is line break, `\u002F` is `/` and `\u002A` is `*` in Java.

So the final polyglot-quine is:

```
//\u000A\u002F\u002A
using System;//\u002A\u002F
class Program{public static void//\u000A\u002F\u002A
Main//\u002A\u002Fmain
(String[]z){String s="//@#'^using System;//'#^class Program{public static void//@#'^Main//'#main^(String[]z){String s=!$!,t=s;int[]a=new int[]{33,94,38,64,35,39,36};String[]b=new String[]{!&!!,!&n!,!&&!,!&@!,!&#!,!&'!,s};for(int i=0;i<7;i++)t=t.//@#'^Replace//'#replace^(!!+(char)a[i],b[i]);//@#'^Console.Write//'#System.out.printf^(t);}}",t=s;int[]a=new int[]{33,94,38,64,35,39,36};String[]b=new String[]{"\"","\n","\\","\\u000A","\\u002F","\\u002A",s};for(int i=0;i<7;i++)t=t.//\u000A\u002F\u002A
Replace//\u002A\u002Freplace
(""+(char)a[i],b[i]);//\u000A\u002F\u002A
Console.Write//\u002A\u002FSystem.out.printf
(t);}}

```

However, the size is too huge because of languages verbosity.

Compilation available on ideone.com: C#, Java.
> 15 votes

# Answer
### Python 3 and JavaScript, 134 bytes

Here's my (final?) attempt:

```
a='eval(a.split(" ")[2%-4]),1//2# q=String.fromCharCode(39);console.log("a="+q+a+q+a.slice(-8)) print(a[-12:]%a) a=%r;eval(a)';eval(a)

```

It can probably be golfed a bit more, especially if anyone knows a better way to get single quotes in JavaScript.

---

Boiled down, the program looks like this:

```
a='a long string';eval(a)

```

The `eval()` function will evaluate expressions in both languages. So the long string gets executed:

```
eval(a.split(" ")[2%-4]),1//2# ... the rest gets commented out

```

This splits the long string by spaces and evaluates the substring indexed by `2%-4`. JavaScript will run the third substring (`2 % -4 == 2`) and Python the second last (`2 % -4 == -2`), because their modulo operators behave differently for negatives.

The rest of the string gets ignored in both languages. JavaScript stops at the `//`, while Python sees it as integer division and stops at the `#`.

So JavaScript prints the source code to the console here:

```
q=String.fromCharCode(39);console.log("a="+q+a+q+a.slice(-8))

```

And Python here:

```
print(a[-12:]%a)

```

Both make use of the final part of the string, which is a template of the program:

```
a=%r;eval(a)

```
> 13 votes

# Answer
# Ruby/Perl/PHP, 52

```
$b='$b=%c%s%c;printf$b,39,$b,39;';printf$b,39,$b,39;

```

Copied verbatim from Christopher Durr's Perl quine.

This is rules abuse. Ruby and Perl are definitely not the same language, nor is Perl a subset of Ruby (most of the linked Perl quines don't work in Ruby, for example). But Ruby was designed to be able to look a lot like Perl if you want it to, and this happens a lot when golfing.
> 10 votes

# Answer
# PHP/Perl - 171

```
#<?PHP$s=1;$t="";
$a='%s<%cPHP$s=1;$t="";%c$a=%c%s%c;$t==$s?$t="#":$s;printf($a,$t,63,10,39,$a,39,10,63);%c#%c>';$t==$s?$t="#":$s;printf($a,$t,63,10,39,$a,39,10,63);
#?>

```

Run with:

```
$ php quine.pl
$ perl quine.pl

```

The `php` code is actually running (not just printing itself).
> 6 votes

# Answer
# Bash/Ruby, ~~104~~ 82

```
"tee`#";puts <<a*2+'a'#`" -<<'a';echo a
"tee`#";puts <<a*2+'a'#`" -<<'a';echo a
a

```

Older version:

```
"alias" "puts=f()(tee -;echo a);f"
puts <<a *2+"a"
"alias" "puts=f()(tee -;echo a);f"
puts <<a *2+"a"
a

```

# Bash/Ruby, 128 without undefined behavior

```
"alias" 'puts=f()(a=`cat`;echo "$a
$a
a");f'
puts <<'a' *2+"a"
"alias" 'puts=f()(a=`cat`;echo "$a
$a
a");f'
puts <<'a' *2+"a"
a

```
> 6 votes

# Answer
# Bash/GolfScript, 73

```
.~0 ()
{
    declare "-f" @* ".~0" " ()
"+@n.;
    echo '.~0;'
}
.~0;

```

There is a trailing space on each of the first 3 lines.

# Bash/GolfScript, 78

```
alias :a~a.='eval "alias :a~a."\
;set [61 39]+a[39]+n"":a;echo ":a~a."'
:a~a.

```
> 6 votes

# Answer
## Perl 5/Ruby/JavaScript (Node.js)/Bash/Python 2/PHP, 1031 bytes

```
s=1//2;_=r'''<?#/.__id__;s=+0;#';read -d '' q<<'';s=\';Q='echo s=1//2\;_=r$s$s$s\<\?\#/.__id__\;s=+0\;#$s\;read -d $s$s q\<\<$s$s\;s=\\$s\;Q=$s$Q$s\;eval\ \$Q;echo $q';eval $Q
$_='eval("0"?0?"def strtr(s,f,t);s.tr(f,t) end;class String;def chr(n);self+n.chr end;end":"$u=strtr=(s,f,t)=>[...f].reduce((s,a,i)=>s.replace(RegExp(a,`g`),t[i]),s);printf=console.log;(S=String).prototype.chr=function(n){return this+S.fromCharCode(n)}":[]&&"sub strtr{eval q(q(X)=~y/X/X/r)=~s/X/shift/ger}");printf(strtr("%s<?#/.__id__;s=+0;#j;read -d jj q<<jj;s=zj;Q=jecho s=1//2z;_=rksksksz<z?z#/.__id__z;s=+0z;#ksz;read -d ksks qz<z<ksksz;s=zzksz;Q=kskQksz;evalz zkQ;echo kqj;eval kQwk_=j%sj;eval(k_);//;#jjj;f=jjjs=1//2;_=r%%s%%s%%s;f=%%s%%s%%s;q=_[18]*3;print f%%%%(q,_,q,q,f,q)jjj;q=_[18]*3;print f%%(q,_,q,q,f,q)%s","jkwz","".chr(39).chr(36).chr(10).chr(92).chr(92)),[]&&"s=1//2;_=r".chr(39).chr(39).chr(39),$_,$u?"":"".chr(10));';eval($_);//;#''';f='''s=1//2;_=r%s%s%s;f=%s%s%s;q=_[18]*3;print f%%(q,_,q,q,f,q)''';q=_[18]*3;print f%(q,_,q,q,f,q)

```

Verify it online!

Based on my updates to this answer, I thought I'd try and optimise out the code that prints a different permutation, but ended up adding in Bash, which added a load more bytes anyway. Whilst this is more optimised than my first attempt (saved over 300 bytes) I'm sure it can still be golfed further.

---

## Alternative Perl 5/Ruby/JavaScript (Node.js)/Bash/Python 2/PHP, 1040 bytes

```
s=1//2;_=r'''<?#/.__id__;s=+0;#';read -d '' q<<'';s=\';Q='echo s=1//2\;_=r$s$s$s\<\?\#/.__id__\;s=+0\;#$s\;read -d $s$s q\<\<$s$s\;s=\\$s\;Q=$s$Q$s\;eval\ \$Q;echo $q';eval $Q
$_='$z=0?"$&".next+92 .chr+10 .chr: 0..a||eval("printf=console.log;unescape`$%27%5C%0Ak`");$q=$z[1]?$z[1]:h^O;printf("%s%s%s%s<?#/.__id__;s=+0;#%s;read -d %s%s q<<%s%s;s=%s%s;Q=%secho s=1//2%s;_=r%ss%ss%ss%s<%s?%s#/.__id__%s;s=+0%s;#%ss%s;read -d %ss%ss q%s<%s<%ss%ss%s;s=%s%s%ss%s;Q=%ss%sQ%ss%s;eval%s %s%sQ;echo %sq%s;eval %sQ%s%s_=%s%s%s;eval(%s_);//;#%s%s%s;f=%s%s%ss=1//2;_=r%%s%%s%%s;f=%%s%%s%%s;q=_[18]*3;print f%%%%(q,_,q,q,f,q)%s%s%s;q=_[18]*3;print f%%(q,_,q,q,f,q)%s",[]&&"s=1//2;_=r",$r=[]&&$q,$r,$r,$q,$q,$q,$q,$q,$b=$z[2]?$z[2]:chr(92),$q,$q,$b,$d=$z[0]?$z[0]:h^L,$d,$d,$b,$b,$b,$b,$b,$d,$b,$d,$d,$b,$b,$d,$d,$b,$b,$b,$d,$b,$d,$d,$d,$b,$b,$b,$d,$d,$q,$d,$n=$z[3]?$z[3]:chr(10),$d,$q,$_,$q,$d,$q,$q,$q,$q,$q,$q,$q,$q,$q,$z[4]?"":$n);';eval($_);//;#''';f='''s=1//2;_=r%s%s%s;f=%s%s%s;q=_[18]*3;print f%%(q,_,q,q,f,q)''';q=_[18]*3;print f%(q,_,q,q,f,q)

```

Verify it online!

A little closer to my original approach, but the repetition of the args for `printf` is still insane. Using positional arguments instead make this only work in Chrome and is tricky to get working in PHP as well because the `$s` in `%1$s` is interpolated, but could save a lot of bytes, perhaps using a combination of the two approaches...
> 6 votes

# Answer
## Ruby/Mathematica, 225 bytes

Here is my own very beatable polyquine (which serves as example and proof-of-concept):

```
s="s=%p;puts s%%s;#Print[StringReplace[s,{(f=FromCharacterCode)@{37,112}->ToString@InputForm@s,f@{37,37}->f@37}]]&@1";puts s%s;#Print[StringReplace[s,{(f=FromCharacterCode)@{37,112}->ToString@InputForm@s,f@{37,37}->f@37}]]&@1

```

The first part is based on this Ruby quine and is basically:

```
s="s=%p;puts s%%s;#MathematicaCode";puts s%s;#MathematicaCode

```

The string assignment is exactly the same in Mathematica. The `puts s%s` is interpreted as a product of 4 symbols: `puts`, the string `s`, `%` (the last REPL result or `Out[0]` if it's the first expression you evaluate) and another `s`. That's of course completely meaningless, but Mathematica doesn't care and `;` suppresses any output, so this is just processed silently. Then `#` makes the rest of the line a comment for Ruby while Mathematica continues.

As for the Mathematica code, the largest part of it, is to simulate Ruby's format string processing without using any string literals. `FromCharacterCode@{37,112}` is `%p` and `FromCharacterCode@{37,112}` is `%%`. The former gets replaced with the string itself, (where `InputForm` adds the quotes) the latter with a single `%`. The result is `Print`ed. The final catch is how to deal with that `#` at the front. This is Mathematica's symbol for the first argument of a pure (anonymous) function. So what we do is we *make* all of that a pure function by appending `&` and immediately invoke the function with argument `1`. Prepending a `1` to a function call "multiplies" the result with `1`, which Mathematica again just swallows regardless of what kind of thing is returned by the function.
> 5 votes

# Answer
# reticular/befunge-98, 28 bytes \[noncompeting\]

```
<@,+1!',k- ';';Oc'43'q@$;!0"

```

Try reticular! Try befunge 98!

Anything in between `;`s in befunge is ignored, and `!` skips into the segment between `;`s for reticular. Thus, reticular sees:

```
<@,+1!',k- ';';Oc'43'q@$;!0"
<                             move left
                           "  capture string
                          0   push zero
                        ;!    skip `;` (end program)
                       $      drop zero
                     q@       reverse TOS
                 '43'         push 34 (")
                c             convert to char
               O              output all
              ;               end program

```

Befunge sees:

```
<@,+1!',k- ';';Oc'43'q@$;!0"
<                            move left
                           " capture string
                         !0  push 1
              ;         ;    skip this
         - ';'               push 27
       ,k                    output top 27 chars
   +1!'                      push 34 (")
  ,                          output "
 @                           end program

```
> 5 votes

# Answer
# C/PHP, ~~266~~ ~~304~~ ~~300~~ ~~282~~ ~~241~~ 203 + 10 bytes

```
//<?php
function main($a){printf($a="%c//<?php%cfunction main(%ca){printf(%ca=%c%s%c,13,10,36,36,34,%ca,34,36,10,10,10);}%c#if 0%cmain();%c#endif",13,10,36,36,34,$a,34,36,10,10,10);}
#if 0
main();
#endif

```

+10 bytes because compiling in C requires the GCC compiler flag `-Dfunction=`.

How it works (in PHP):

* The PHP interpreter simply prints everything before the `<?php` as HTML. `//` is not a comment in HTML, so it's simply printed.
* `main` is declared as a function with a variable `a`.
* `printf` prints a carriage return (to override the already-printed `//`) and then the source code, using a standard C/PHP quining method.
* `#if 0` is ignored by PHP.
* `main($a)` initializes an empty variable `a`. (Previously used `error_reporting(0)` to ignore errors caused by calling `main()`)
* `#endif` is also ignored by PHP.

How it works (in C):

* `//<?php` is a single-line comment, so it is ignored.
* The `function` keyword is ignored due to the command-line compiler argument `-Dfunction=`.
* GCC and Clang don't care if variables start with or contain `$`. (This saved the day.)
* `printf` prints a carriage return (useless in this instance) and then the source code, using a standard C/PHP quining method.
* `#if 0` ignores everything until the `endif`, so PHP can call `main`.
* `#endif` ends the "ignore me" block.
> 4 votes

# Answer
# Wumpus/\>\<\>/Befunge-98 31 bytes

```
"]#34[~#28&o@,k+deg0 #o#!g00

```

Try it in Wumpus!, Try it in \>\<\>!, Try it in Befunge-98!

## How it Works:

### Wumpus Code:

```
  " Start string literal
    Bounce off end of line and come back
  " End string literal
    ]      Push top of stack to bottom
     #34   Push double quote
        [~ Get bottom of stack and swap it with the double quote
          #31    Push 31
             &o@ Print the top 31 items on stack and terminate program

```

### \>\<\> Code:

```
  "    Start string literal
       Wrap when it reaches the end of the line
  "    End string literal
    ]# Clear stack and reflect
  "    Wrapping string literal again, but backwards
                        +2: Copy the space and add 2 to get "
                    #o#!    Skip into the printing loop
                            Exit with an error

```

### Befunge-98 Code:

```
  "   Wrapping string literal
    ] Turn right
    ] Turn right again, going West
  "   Wrapping string literal going West
                    !+2: Get double quote and invert it
                 #o#     Skip over the o instruction
            +2:$         Get double quote
         +ff             Push 30
      @,k                Print 30+1 items from the stack and terminate program.

```
> 3 votes

# Answer
## \>\<\> and CJam, 165 bytes

```
"~~~~~~~~~~~~~~~~~~~~~~~r00gol?!v93*0.Hi
'                               <       .1*5av!?log10oar~~~r
'"`{"`"\"_~e#.21 <.2+4*96;!?log10oa"}_~e#.21 <.2+4*96;!?log10oa

```

To CJam, the program starts with a multi-line string literal. This is escaped with ```, and then it uses the standard quine to print the quine code, as well as a trailing comment.

To \>\<\>, the first `"` starts a string literal that goes through the entire first row, pushing every character to the stack. After that, the trailing spaces (created due to the input being padded) are deleted, and then the stack is reversed. Every character in the stack (i.e. the entire first row) is output, and then it moves down to the second row.

The second row essentially does the same thing, except that it's in the opposite direction, so you don't need to reverse the stack. (I do anyway, because I have to delete the trailing spaces.)

Finally, it moves on to the third line. The only major difference is that you must skip the CJam block, which is done using `.` The single quote captures the entire line (again, backwards), and then it is output.
> 2 votes

# Answer
# C/Lisp, 555 bytes

```
t(setq /*;*/){}main(){char q='\"',s='\\';char*a=
"~%t(setq /*;*/){}main(){char q='~A';char*a=
~S;char*b=/*
)(setq a ~S)
(setq */ ~S;printf(b,s,q,s,s,q,a,q,q,s,s,s,q,s,s,s,s,q,q,b,q/*
)(format t /* a /* a */);}~%";char*b=/*
)(setq a "\\\"',s='\\\\")
(setq */ "
t(setq /*;*/){}main(){char q='%c%c',s='%c%c';char*a=
%c%s%c;char*b=/*
)(setq a %c%c%c%c%c',s='%c%c%c%c%c)
(setq */ %c%s%c;printf(b,s,q,s,s,q,a,q,q,s,s,s,q,s,s,s,s,q,q,b,q/*
)(format t /* a /* a */);}
";printf(b,s,q,s,s,q,a,q,q,s,s,s,q,s,s,s,s,q,q,b,q/*
)(format t /* a /* a */);}

```

Intentionally blank first line.
> 2 votes

# Answer
# Vyxal `D`, 70 bytes/ Python 3, 77 bytes

```
a="`q‛:Ė+34Cp‛a=print('a=%r;exec(a[13:])#\\140:Ė'%a)";exec(a[13:])#`:Ė

```

Vyxal : Try it Online!

```
a="`q‛:Ė+34Cp‛a=print('a=%r;exec(a[13:])#\\140:Ė'%a)";exec(a[13:])#`:Ė

```

Python : Try it online!

The difference beetween the number of bytes is due to the fact that vyxal and python doesn't use the same charset

## Explanation :

* Vyxal

```
a="                            # do nothing revelent here
   `q‛:Ė+                 `:Ė  # structure for a quine
         34Cp‛a=p              # prepend `a="` to the string
                 rint          # do stuff that somehow push 0 to the stack
                     (         # for loop over 0 (do nothing)
                        #      # comment and implicily close the loop
                               # implicit output

```
* Python

The quine is a variation of `a="print('a=%r;exec(a)'%a)";exec(a)`
> 2 votes

# Answer
# 05AB1E/2sable, 14 bytes, non-competing

```
0"D34çý"D34çý

```

Try it online! (05AB1E)
Try it online! (2sable)

2sable is derived from 05AB1E and is similar, but has major differences.

Trailing newline.
> 1 votes

# Answer
# C/TCL, 337 bytes

```
#define set char*f=
#define F
#define proc main(){
set F "#define set char*f=
#define F
#define proc main(){
set F %c%s%c;
proc /* {} {}
puts -nonewline %cformat %cF 34 %cF 34 91 36 36]
set a {*/printf(f,34,f,34,91,36,36);}
";
proc /* {} {}
puts -nonewline [format $F 34 $F 34 91 36 36]
set a {*/printf(f,34,f,34,91,36,36);}

```
> 1 votes

# Answer
# C/Vim 4.0, 1636 bytes

Contains control characters.

```
map () {}/*
map g ;data0df"f"cf"
f"cf"
f"D2kyyP;g6k2dd4x5jA"JxA","JxA","jyyPkJxA"jok;g2kdd4xkJx3jdd
map ;g O"vdldd0i# 0# 1# 2# 3# 4# 5# #0lx2lx2lx2lx2lx2lx2lx:s/##/#/g
o:s//"/gk0y2lj02lp"addk@ao:s//\\/gk0ly2lj02lp"addk@ao:s///gk04ly2lj02lp05l"vp"addk@ao:s///gk05ly2lj02lp05l"vp"vp"addk@ao:s//
/gk06ly2lj02lp05l"vp"vp"vp"addk@ao:s//
/gk02ly2lj02lp05l"vp"addk@a
unmap ()

map ;data o*/ char*g[]={"map () {}/*#2map g ;data0df#0f#0cf#0#5#3f#0cf#0#5#3f#0D2kyyP;g6k2dd4x5jA#0#3JxA#0,#0#3JxA#0,#0#3jyyPkJxA#0#3jo#3k;g2kdd4xkJx3jdd#2map ;g O#4#4#4#4#3#0vdldd0i## 0## 1## 2## 3## 4## 5## ###30lx2lx2lx2lx2lx2lx2lx:s/####/##/g#5o:s//#0/g#3k0y2lj02lp#0addk@ao:s//#1#1/g#3k0ly2lj02lp#0addk@ao:s//#4#4#3/g#3k04ly2lj02lp05l#0vp#0addk@ao:s///g#3k05ly2lj02lp05l#0vp#0vp#0addk@ao:s//#4#4#5/g#3k06ly2lj02lp05l#0vp#0vp#0vp#0addk@ao:s//#4#4#5/g#3k02ly2lj02lp05l#0vp#0addk@a#2unmap ()#2#2map ;data o*/ char*g[]={","#A#0#a#0,#0#b#0,#0#c#0#C#2","}; /*#3#2#2#0*/  print(char*s){char*t=s,c,d;while(c=*t++)if(c==35){c=*t++;if(c==35)putchar(c);else if(c==48)putchar(34);else if(c==49)putchar(92);else if(c==50)printf(#0#1n#0);else if(c==51)putchar(27);else if(c==52)putchar(22);else if(c==53)putchar(13);else if(c>64&&c<91)print(g[c-65]);else printf(g[c-97]);}else putchar(c);}  main(){print(g[1]);}"}; /*

"*/  print(char*s){char*t=s,c,d;while(c=*t++)if(c==35){c=*t++;if(c==35)putchar(c);else if(c==48)putchar(34);else if(c==49)putchar(92);else if(c==50)printf("\n");else if(c==51)putchar(27);else if(c==52)putchar(22);else if(c==53)putchar(13);else if(c>64&&c<91)print(g[c-65]);else printf(g[c-97]);}else putchar(c);}  main(){print(g[1]);}

```

Your Vim needs to have the following set:

```
set noai
set wm=0
set nosi
set tw=0
set nogdefault

```
> 1 votes

# Answer
## Perl/Javascript (SpiderMonkey), 106 bytes

```
$_='$q=+[]?h^O:unescape("%27");print("$_="+$q+$_+$q+";eval($_)"||(q($_),"=$q$_$q;",q(eval($_))))';eval($_)

```

Try the Perl online!
Try the JavaScript online!

### Explanation

The quine data is stored in `$_` in both languages and then `eval`ed, which is pretty much standard procedure in Perl. I chose SpiderMonkey on TIO as it has a `print` function, but this could easily be ported to browser for + 20 bytes (add `eval("print=alert");` to the beginning of `$_`s definition).

Perl sees the data stored in `$_` and `eval`s it as usual. Since `+[]` is truthy in Perl,`'` is stored in `$q` via the stringwise-XOR of `h` and `O`. The final trick is in the call to `print` where the first part for JavaScript uses `+`, which in Perl treats all items as numbers, and adds up to `0`, then we use the `||` operator to return what we actually want `(q($_),"=$q$_$q;",q(eval($_)))` which is equivalent to `"\$_=$q$_$q;eval(\$_)"`.

In JavaScript, `+[]` returns `0`, so we call `unescape("%27")` to store `'` in `$q` (unfortunately, `atob` doesm't exist in SpirderMonkey...). In the call to `print`, since `+` is the concatenation operator in JavaScript, the first block builds the desired output and the second part after the `||` is ignored.

**Thanks to Patrick Roberts' comment for the `unescape` trick!**

---

## Perl/JavaScript (Browser), 108 bytes

```
$_='eval("q=_=>_+``;printf=console.log");printf(q`$_=%s%s%s;eval($_)`,$q=+[]?h^O:atob("Jw"),$_,$q)';eval($_)

```

Try the Perl online!

```
$_='eval("q=_=>_+``;printf=console.log");printf(q`$_=%s%s%s;eval($_)`,$q=+[]?h^O:atob("Jw"),$_,$q)';eval($_)
```

### Explanation

We store the quine data in `$_` in both languages and then `eval` it, which is pretty much standard procedure in Perl.

Perl sees the data stored in `$_` and `eval`s it as usual. The `eval` within `$_` is executed and fails to parse, but since it's `eval`, doesn't error. `printf` is then called, with a single quoted string `q()`, with ``` as the delimter, as just using ``` would result in commands being executed in shell, then for the first use of `$q`, since `+[]` is truthy in Perl, `'` is stored in `$q` via stringwise-XOR of `h` and `O`.

In JavaScript, the `eval` block within `$_` sets up a function `q`, that `return`s its argument as a `String` and aliases `console.log` to `printf`, since `console.log` formats string like `printf` in Perl. When `printf` is called `+[]` returns `0`, so we call `atob` to decode `'` and store in `$q`.
> 1 votes

# Answer
# Perl 5/Ruby/PHP/JavaScript (Browser), 153 bytes

```
$_='$z=0?"$&".next: 0..a||eval("printf=console.log;atob`JCc`");printf("%s_=%s%s%s;eval(%s_);",$d=$z[0]?$z[0]:h^L,$q=$z[1]?$z[1]:h^O,$_,$q,$d);';eval($_);

```

Try the Perl online!
Try the Ruby online!
Try the PHP online!

```
$_='$z=0?"$&".next: 0..a||eval("printf=console.log;atob`JCc`");printf("%s_=%s%s%s;eval(%s_);",$d=$z[0]?$z[0]:h^L,$q=$z[1]?$z[1]:h^O,$_,$q,$d);';eval($_);
```
> 1 votes

# Answer
# C/dc, 152 bytes

```
z1d//[[z1d//]P91PP93P[dx]Pq
;main(){char*a="z1d//[[z1d//]P91PP93P[dx]Pq%c;main(){char*a=%c%s%c;printf(a,10,34,a,34);}//]dx";printf(a,10,34,a,34);}//]dx

```

Taking advantage of comments, yeah!
> 0 votes

---
Tags: code-golf, quine, polyglot
---


title: Write a Metaquine

text:
# Question
Title: Write a Metaquine
A metaquine is a program which is not a quine, but whose output, when run as a program in the same language, is a quine.

The goal of this challenge is to write a metaquine. This is , so shortest code wins, with earliest answer used as a tiebreaker. Note that only full programs are acceptable, due to the definition of a quine.

### Rules for Quines

Only *true* quines are accepted. That is, you need to print the entire source code verbatim to STDOUT, **without**:

* reading your source code, directly or indirectly.
* relying on a REPL environment which just simply evaluates and prints every expression you feed it.
* relying on language features which just print out the source in certain cases.
* using error messages or STDERR to write all or part of the quine. (You may write things to STDERR or produce warnings/non-fatal errors as long as STDOUT is a valid quine and the error messages are not part of it.)
* the source code consisting purely of literals (whether they be string literals, numeric literals, etc.) and/or NOPs.

Any non-suppressible output (such as copyright notices, startup/shutdown messages, or a trailing line feed) may be ignored in the output for the sake of the validity of the quine.

## Example

Ignoring the rule which forbids literal-only programs and built-in quining, this would be a metaquine in Seriously:

```
"Q"

```

The program consists of the single string literal `"Q"`, which is implicitly printed at output. When the output (`Q`) is run, it is a quine (`Q` is the built-in quine function).

# Answer
> 14 votes
## CJam, 6 bytes

```
"_p"_p

```

Prints

```
"_p"
_p

```

which is the shortest proper quine in CJam.

Test it here.

### Explanation

Both programs work exactly the same, since the linefeed inside the proper quine is a no-op and only included because it's more expensive to remove it from the output. How the programs work:

```
"_p"  e# Push this string.
_     e# Duplicate it.
p     e# Print a string representation of the top of the stack (i.e. the string with
      e# quotes) followed by a linefeed.
      e# The other copy is then printed automatically at the end of the program, without
      e# stringifying it.

```

### Side Note

The same works in GolfScript as

```
".p".p

```

which prints

```
".p"
.p

```

with a trailing linefeed, which in turn is one of the shortest known quines.

# Answer
> 10 votes
# Pyth, ~~12~~ ~~11~~ ~~10~~ 9 bytes

Knocked off one more byte thanks to @Pietu1998.

```
jN B".[9N

```

This prints

```
.[9N".[9N

```

which is a quine in Pyth. You can try it out here.

# Answer
> 8 votes
## Fission, 6 bytes

```
!+OR"'

```

Prints

```
'!+OR"

```

Which is the shortest Fission quine. This works because cyclic shifts of the program leave its output completely unaffected.

Try it online!

# Answer
> 5 votes
# Javascript ES6, 21 bytes

```
$=_=>`$=${$};$()`
$()

```

Trivial.

# Answer
> 4 votes
## Python 2, 29 bytes

```
_="_=%r;print _%%_";print _%_

```

Turns out the well-known short python quine is easily turned into a metaquine :)

And, since we don't have to worry about matching the trailing newline, the metaquine is actually shorter!

# Answer
> 3 votes
# Japt, ~~15~~ 13 bytes

```
Q+"+Q ³s7J" ²

```

Test it online!

This program outputs

```
"+Q ³s7J"+Q ³s7J

```

which is the shortest known quine in Japt.

### How it works

```
Q+"..." // Take a quotation mark plus this string.  "+Q ³s7J
²       // Repeat it twice.                         "+Q ³s7J"+Q ³s7J
        // Implicit output

```

### 11 bytes

```
Q+"+Q ²é" ²

```

I've just added `é`, a "rotate" command. So

```
"+Q ²é"+Q ²é

```

is now a valid quine.

# Answer
> 1 votes
# Ruby, ~~25~~ 23

```
puts"puts <<2*2,2
"*2,2

```

Generates the classic Ruby HEREdoc quine

```
puts <<2*2,2
puts <<2*2,2
2

```

# Old solution

```
_='_=%p;$><<_%%_';$><<_%_

```

Generates itself except with the single quotes replaced with double quotes.

# Answer
> 1 votes
# JavaScript, 50 bytes

```
a="a=%s;console.log(a,uneval(a))";eval(a.slice(5))

```

Based on the shortest non-source-reading JS quine known to man, but a good 8 bytes shorter. Prints

```
a="a=%s;console.log(a,uneval(a))";console.log(a,uneval(a))

```

which is a quine.

# Answer
> 1 votes
# Fish (\>\<\>), 17 bytes

This works using the classic fish quine `"r00g!;oooooooo|` but adds a `{` which shifts the entire stack to the left so that the original program isn't a quine, but it's output, when run, is.

```
"{r00g!;oooooooo|

```

Outputs:

```
"r00g!;oooooooo|

```

which is a fish quine!

# Answer
> 1 votes
# Jelly, 3 bytes (non-competing)

Unfortunately, the required atoms are roughly 2 weeks younger than the challenge.

## Metaquine

```
”Ṙv

```

Try it online!

### How it works

```
”Ṙv  Main link. No arguments.

”Ṙ   Set the left argument and the return value to the character 'Ṙ'.
  v  Dyadic eval; evaluate the return value with the left argument as argument.
     Executing the atom Ṙ on the argument 'Ṙ' prints a string representation of
     the character, i.e., the string "”Ṙ".
     Finally, v returns its unaltered argument, which is printed implicitly.

```

## Quine

```
”ṘṘ

```

Try it online!

### How it works

```
”ṘṘ  Main link. No arguments.

”Ṙ   Set the left argument and the return value to the character 'Ṙ'.
  Ṙ  Print a string representation of the character, i.e., the string "”Ṙ".
     (implicit) Print the unaltered return value.

```

Since the second  prints the first two characters (`”Ṙ`), this is a proper quine by our definition.

# Answer
> 1 votes
# Octopen-Baru, 22 bytes

\** Non competing answer

```
愛[35211].pack歩U')

```

### Ruby output

```
puts [35211].pack(' U')

```

Which outputs . Which is a quine in Octopen-Baru!

# Answer
> 1 votes
# , 2 bytes, language postdates challenge

The program is two bytes long, and can be interpreted in several ways; as a hex dump:

```
00000000: 4ff4                                     O.

```

as codepage 437:

```
O⌠

```

or, most readably, in octal (which 7 natively uses):

```
237723

```

Try it online!

The workings of this are very simple: it's the standard 7 quine with a no-op stack element inserted between the two halves, to make it different (in this context, `7` separates stack elements). (I could also have inserted it at the start, `723723`. I couldn't have interpreted it at the end because trailing 7s are like trailing whitespace, and ignored in the packed encoding, thus it wouldn't be any different from the output program.)

Incidentally, this program is a in hexadecimal, but that's mostly just coincidence.

# Answer
> 1 votes
# Underload, 11 bytes

```
(:aSS)::aSS

```

Pretty simple. It prints out `(:aSS):aSS`, which is the standard Underload quine.

# Answer
> 1 votes
# Brachylog, 12 bytes

```
"~k;?w₁"gjw₃

```

Try it online!

One of 132 same-length metaquine variations on the quine I translated from Fatalize's Brachylog v1 (non-cheating) quine. I actually wrote a (non-golfed, and overall silly) program to print all of them out:

```
{[[";?","gj","jḍ"],"₁₃₅₇"]j∋ᵐ{ḍ≠&};"\"~~k~ww~w\"~ww~w~n"}ᶠ{lw" metaquines generated:
"ẉ&}w₁ᵐ

```

Try it online!

There are two parts of the original quine which could be replaced inconsequentially: `;?` can be changed to `gj` or `jḍ`, and  can be changed to , , or . If we keep or change them outside the string literal in one way and inside the string literal in a different way, then the output won't match the source, because whichever variants were present within the string literal will be printed both inside and outside it, resulting in a quine which was not the initial program run.

`;?`, `gj`, and `jḍ` are interchangeable because all three pair the string literal with itself: due to the layout of the program, the input variable `?` is unified with the string, so `;?` pairs the string with itself; regardless of the layout, `gj` wraps the string in a list which is then concatenated to itself; likewise `jḍ` concatenates the string to itself then splits it in half.

The odd-numbered `w` subscripts are interchangeable because, although originally `w` could only take 0 or 1, with 0 printing the input to `w` and 1 printing the first element formatted with the second, the subscript inventory for `w` has grown into something that externally functions as a bitfield: the low bit of the subscript encodes whether it's direct or formatted, the middle bit encodes whether the output variable from `w` is unconstrained or set to the input, and the high bit encodes whether the printing is done immediately or if it's delayed until the end of the program so it can be subject to backtracking. (Those subscripts were my first and so far largest contribution to Brachylog.) Since the quine and metaquine don't use the output variable and don't backtrack, all four odd subscripts are equivalent.

# Answer
> 1 votes
# Vyxal, 3 bytes

```
\II

```

Try it Online!

which prints :

```
`I`I

```

Try it Online!

which is a quine

## Explanation :

```
  I  # quote and prepend
\I   # the char `I`
     # Implicit output => `I`I

   I # quote and prepend
`I`  # a string containing `I`
     # implicit output => `I`I

```

# Answer
> 0 votes
# Befunge-93, 22 bytes

```
"+1_@#`+39:,g0:">:#,_@

```

I just took the standard quine, put it in quotes, reversed it (so it is loaded on the stack correctly), and then added a stack-print at the end.

It's 8 characters added to the normal quine, so it's very possible there's a better solution.

# Answer
> 0 votes
# Turtlèd, 52 bytes (noncompeting)

1 less than original quine

```
@##'@r,r,r-{ +.r_}r{ +.r_}"#'@r,r,r-{ +.r_}r{ +.r_}"

```

Works in the same way, except that it does not have a character at the end, when run, it will have a character at the end, that does not effect output, because it writes # on to a #. Note the output is slightly different to the quine I have made for the quine challenge, but works the same: " writes #, which is its own last character, like the quine I made. Check out the explanation there.

# Answer
> 0 votes
## Lua, 45 bytes

Quine code not mine.

```
s="s=%qprint(s:format(s))"print(s:format(s));

```

will result in

```
s="s=%qprint(s:format(s))"print(s:format(s))

```

which is a quine. Glad the `;` is **optional** in Lua.

# Answer
> 0 votes
# Pushy, 7 bytes

Non-competing as the language postdates the challenge.

This is the standard quine, but with newlines removed. Newlines mean nothing in Pushy, but are the print operator's standard separator, and therefore needed for a true quine.

```
95 34_"

```

**Try it online!** This outputs:

```
95 34
_"

```

Which is the shortest Pushy quine - an explanation on how it works can be found here.

Alternatively, `H5-34_"` works for the same byte count.

# Answer
> 0 votes
## Foam, 14 bytes

```
[. .'|: ~|]: ~

```

This prints the second Foam quine that can be found here. This is actually shorter because `.` will always put a space between each element, but the bar in the third token allows me to omit the space before it.

# Answer
> 0 votes
# Husk, 6 bytes

```
D"S+s¨

```

Try it online!

Prints the standard Husk quine `S+s"S+s"`.

```
 "S+s¨    The string S+s"
D         concatenated with itself.

```

The quine explained:

```
   "S+s"    The string S+s
 +          concatenated with
S           itself passed through
  s         the function which returns its string representation.

```

---
Tags: code-golf, quine, code-generation
---


title: Implement OADD_MONTHS

text:
# Question
Title: Implement OADD_MONTHS
### Introduction

A function that adds months to a date (without overflowing ends of months) is implemented in many languages/packages. In Teradata SQL it's ADD\_MONTHS, here are some examples:

```
ADD_MONTHS('2021-01-31', 1)   => 2021-02-28
ADD_MONTHS('2021-01-30', 1)   => 2021-02-28
ADD_MONTHS('2021-02-28', 1)   => 2021-03-28
ADD_MONTHS('2021-02-28', -12) => 2020-02-28

```

Teradata SQL has also a function that goes a step further, namely OADD\_MONTHS. Here, when given an end-of-month date, it always returns an end-of-month date.
To illustrate the difference:

```
ADD_MONTHS('2021-02-28', 1)  => 2021-03-28
OADD_MONTHS('2021-02-28', 1) => 2021-03-31

```

### The task

You are given a date and an integer. Your output should mimic the behaviour of OADD\_MONTHS described above.

Any reasonable input/output form is acceptable (including your language's native date/datetime type, a string, number of days/seconds from a fixed point, etc.)

You may assume the input and target dates are after `1600-01-01` and the date is well defined (so no `2021-03-32`). You may use the Georgian calendar or any similar calendar implementing standard month lengths and taking into account leap years.

If you have a builtin specifically for this, consider including a non-builtin answer as well to make your answer more interesting.

### Test cases

```
Date      , offset => output      (explanation)
2021-01-31, 0      => 2021-01-31  (boring)
2021-01-31, 1      => 2021-02-28  (no overflow)
2020-12-31, 1      => 2021-01-31  (next year)
2020-12-07, 1      => 2021-01-07  (next year)
2021-01-31, -1     => 2020-12-31  (previous year)
2021-01-30, -1     => 2020-12-30  (previous year)
2021-01-01, -1     => 2020-12-01  (previous year)
2020-12-30, 2      => 2021-02-28  (no overflow)
2021-02-28, 1      => 2021-03-31  (end-of-month -> end-of-month)
2021-09-30, 1      => 2021-10-31  (end-of-month -> end-of-month)
2021-02-28, -12    => 2020-02-29  (end-of-month -> end-of-month)
2020-02-28, 1      => 2020-03-28  (leap year - 28.02 is not end-of-month)
1995-02-28, -1140  => 1900-02-28  (not a leap year)

```

# Answer
# JavaScript (Node.js), ~~142~~ ~~140~~ ~~135~~ ~~131~~ 130 bytes

```
d=>f=x=>O(x)>O((D=a=>new Date(x-a*864e5))(-1))?D(1,x=f(D(-1))):O(y=D``,y.setMonth(x.getMonth()+d))<O(x)?f(D(-1),d):y
O=x=>(x+x)[8]

```

Try it online!
> 5 votes

# Answer
# Julia 1.0, 53 bytes

```
using Dates
~ =lastdayofmonth
a\b=a<~a ? a+b : ~(a+b)

```

Try it online!

expects `Date("2021-02-28")\Month(1)`, returns a `Date`
> 5 votes

# Answer
# Wolfram Language (Mathematica), 63 61 bytes

Without considering `d=` which was used to apply to the input.

```
t="EndOfMonth";d=DatePlus[#,{#2,If[DayMatchQ[#,t],t,"Month"]}]&

```

Try it online!
> 2 votes

# Answer
# Charcoal, 95 bytes

```
≔Ｉ⪪Ｓ-θ≔⊟θζ≔⊟θη≔⊟θθＦ²«≔⎇⁼η²⁺²⁸¬﹪∨﹪θ¹⁰⁰÷θ¹⁰⁰¦⁴⁻³¹﹪﹪⊖η⁷¦²ε¿ι⪫⟦θη⌊⟦ζε⟧⟧-«≧⁺⊖Ｎη≧⁺÷η¹²θ≔⊕﹪η¹²η¿⁼ζε≔φζ

```

Try it online! Link is to verbose version of code. Date I/O is in YYYY-m-d format i.e. no leading zeros. Explanation:

```
≔Ｉ⪪Ｓ-θ≔⊟θζ≔⊟θη≔⊟θθ

```

Read in the date.

```
Ｆ²«

```

Calculate the number of days in the month twice (first for the input month and second for the output month).

```
≔⎇⁼η²⁺²⁸¬﹪∨﹪θ¹⁰⁰÷θ¹⁰⁰¦⁴⁻³¹﹪﹪⊖η⁷¦²ε

```

The formula for the number of days in the month is `m == 2 ? 28 + !((m % 100 || m / 100) % 4) : 31 - (m - 1) % 7 % 2`, the latter part of which I appropriated from this Stack Overflow answer.

```
¿ι⪫⟦θη⌊⟦ζε⟧⟧-«

```

If this is the second pass, then output the year and month, and the minimum of the day and the number of days in the month (in case the original month had more days).

```
≧⁺⊖Ｎη

```

Add the input number of months.

```
≧⁺÷η¹²θ≔⊕﹪η¹²η

```

Adjust the years to bring the month to between `1` and `12` again.

```
¿⁼ζε≔φζ

```

If this was the last day of the input month then set the day to a large number so that it gets truncated to the last day of the output month.
> 2 votes

# Answer
# 05AB1E, ~~66~~ 63 bytes

```
¦R1Ý-12β+12‰`>¹н)R¹"`т‰0Kθ4ÖUD<i\28X+ë<7%É31α"©.VQiт0ǝ}D®.V‚ß0ǝ

```

-3 bytes thanks to *@Neil*.

Try it online or verify all test cases.

**Explanation:**

Here we go again.. 05AB1E lacks any date builtins, so everything is done with manual calculations. The isLeapYear calculation is taken from this answer of mine and determining the day at the end of the month is taken from this answer of mine (steps 6a-6d).

Step 1: Add the given input amount of months to the date:

```
¦            # Remove the day from the (implicit) input date-list
 R           # Reverse it to [y,m]
  1Ý-        # Subtract [0,1] from it, to make the month 0-based
     12β     # Convert from a base-12 list to an integer
        +    # Add the second (implicit) input-integer
         12‰ # Divmod this by 12, pushing the pair [n//12,n%12]
`            # Pop and push both separated to the stack
 >           # Increase the 0-based month back to a 1-based month
  ¹          # Push the first date-input again
   н         # Pop and only leave its day
    )        # Wrap all three values back into a list
     R       # Reverse it to [d,m,y] again

```

Step 2: If the input-date was at the end of the month, change the resulting date to the end of the month as well:

```
¹            # Push the first date-input again
 "..."       # Push the string defined below
      ©      # Store it in variable `®` (without popping)
       .V    # Pop and execute it as 05AB1E code
Qi           # If the top two values are equal
             # (thus the input was at the end of the month)
  т0ǝ        #  Replace the current day with 100: [100,m,y]
 }           # Close the if-statement

`            # Pop and push d,m,y separated to the stack
 т‰          # Divmod the year by 100
   0K        # Remove all 0s from this pair
     θ       # Pop and leave just the last value
      4Ö     # Check if this is divisible by 4
             # (1 for leap years; 0 if not)
        U    # Pop and store this isLeapYear check in variable `X`
 D           # Duplicate the month
  <i         # If it's 2 (thus February):
    \        #  Discard the month
     28X+    #  And push 28 + isLeapYear instead
   ë         # Else:
    <        #  Decrease the month by 1 to make it 0-based
     7%      #  Modulo-7
       É     #  Modulo-2
        31α  #  Pop and push its absolute difference with 31
             # (the stack will now contain the day, and the amount of days in
             # this month)

```

Step 3: Fix potential overflow for the resulting date, after which we can output the result:

```
D            # Duplicate the result
 ®.V         # Determine the amount of days of this month
    ‚        # Pair the current day and end of month day together
     ß       # Pop and push the minimum of the two
      0ǝ     # Insert this day back into the [d,m,y]
             # (after which the result is output implicitly)

```
> 2 votes

# Answer
# JavaScript (Node.js), 100 bytes

```
(y,m,d,i)=>(D=(m,d)=>(a=new Date(y,m,d)).getMonth(),D(i+=m+!(b=D(m,d+1)==m),b)-D(i,b*d)&&D(i+1,0),a)

```

Try it online!

Input 4 parameters `year, month, date, increase`, while `month` is 0-indexed (as what JavaScript `Date` type do: Jan = 0, Dec = 11). Output a `Date` Object. Only work if user is using UTC timezone. If you want change to 1-indexed month, it could be fixed +2 bytes (add a `--`).
> 1 votes

---
Tags: code-golf, date
---


# Question
Title: Calculate a user's privileges on CodeGolf.SE
# The Challenge

Your goal is to write the shortest program possible that will take a list of events (such as upvote, downvote, etc) and return the user's reputation and the privileges that he has earned.

## What sort of events?

Here is a chart of the events, listed in order of reputation earned:

```
-15 answer unaccepted
-10 answer unupvoted
-5  question unupvoted
-2  answer downvoted
-2  question downvoted
-2  unaccept answer
-1  downvote answer
+1  join website
+1  undownvote answer
+2  accept answer
+2  question undownvoted
+2  answer undownvoted
+5  question upvoted
+10 answer upvoted
+15 answer accepted
+100 association bonus

```

## What sort of privileges?

Here is a list of privileges, in order of reputation required.

```
1 create posts
5 participate in meta
10 remove new user restrictions
10 create wiki posts
15 vote up
15 flag posts
20 talk in chat
50 comment everywhere
75 set bounties
100 edit community wiki
100 create chat rooms
125 vote down
150 create tags
200 retag questions
250 view close votes
500 cast close and reopen votes
750 established user
1000 edit questions and answers
1000 create gallery chat rooms
1250 create tag synonyms
1500 approve tag wiki edits
2000 access to moderator tools
3500 protect questions
4000 trusted user

```

## Input

Input (on STDIN) will be a list of events, one per line, exactly how they appear in the first chart (except for the amount of reputation). A blank line represents the end of input. Here is an example (there should be a blank line at the end):

```
join website
association bonus
answer upvoted
answer upvoted
question upvoted
answer accepted
answer upvoted
accept answer
unaccept answer
question unupvoted
accept answer
question upvoted

```

## Output

The first line of output (to STDOUT) should name the amount of rep accumulated. Each line after that should list one privilege earned, exactly as they appear and in the same order as the second chart. The expected output for the above input:

```
153 reputation
1 create posts
5 participate in meta
10 remove new user restrictions
10 create wiki posts
15 vote up
15 flag posts
20 talk in chat
50 comment everywhere
75 set bounties
100 edit community wiki
100 create chat rooms
125 vote down
150 create tags

```

# Rules, Restrictions, and Notes

This is code golf. Standard code golf rules apply.

(EDIT: Since I have had two entries that access files, I would like to point out that the length of the file needs to be added to code length as part of the standard rules for code golf)

# Answer
> 11 votes
## GolfScript (569 568 475 473 chars)

This uses non-printable characters to compress the required strings, so in xxd format:

```
0000000: 305c 6e2f 7b2e 2775 6e27 2f27 272a 2e2d  0\n/{.'un'/''*.-
0000010: 3162 6173 6527 6e3f 696d 646f 700a 705f  1base'n?imdop.p_
0000020: 6c27 3132 2a3d 3131 302d 4040 3d7b 7e29  l'12*=110-@@={~)
0000030: 7d2a 2b7d 2f3a 5e2e 6e27 7978 0a51 b318  }*+}/:^.n'yx.Q..
0000040: 34fd e3ad 76f0 9f48 a7db efe2 2e06 9a7a  4...v..H.......z
0000050: 0733 c726 2c43 7e1c 4bf6 bbbc dae7 3bd8  .3.&,C~.K.....;.
0000060: 835b d3b5 23ed c195 f733 6257 0741 296e  .[..#....3bW.A)n
0000070: a97c b473 e67b 3f95 5218 0256 8c58 067c  .|.s.{?.R..V.X.|
0000080: 1358 e5a6 0e7a 2894 3f26 9d0f afbc 0697  .X...z(.?&......
0000090: 9048 7845 0041 d335 0c6f e88b 0b97 e9d9  .HxE.A.5.o......
00000a0: d840 6808 c17d c1b2 5e79 f423 2436 dc33  .@h..}..^y.#$6.3
00000b0: 8da5 03d8 f563 f61a 7687 cff9 d489 24de  .....c..v.....$.
00000c0: 5a70 4966 e614 d632 d4ba c9e4 5b1e f561  ZpIf...2....[..a
00000d0: 9308 215f b7bc f475 edc0 1686 a212 d4d0  ..!_...u........
00000e0: 75c6 bab8 c4a0 1c85 d0b8 7f3f 53d1 8920  u..........?S..
00000f0: 3923 895f 15d5 6c2e 965e c295 62c7 00cd  9#._..l..^..b...
0000100: 8b46 6e2a 3d7b 9ac3 7f90 e526 b960 dbe5  .Fn*={.....&.`..
0000110: 5242 defa 24cf 5976 8378 f958 34f6 657d  RB..$.Yv.x.X4.e}
0000120: 41da 28a9 cc4f 3930 dd25 d982 3b67 9400  A.(..O90.%..;g..
0000130: 3a19 cf72 6ae9 3c19 ee5a 6fd2 ef52 e29c  :..rj.<..Zo..R..
0000140: 4872 8a86 c243 dcc1 23b1 7958 dcbc 307d  Hr...C..#.yX..0}
0000150: 7c26 67d3 dd6a fbd2 1680 4de3 156b 8a4d  |&g..j....M..k.M
0000160: ad31 d6fa 08ca 92a7 76d4 8e6e 8b71 167f  .1......v..n.q..
0000170: 3582 9d84 8038 d6c1 da9d 8b30 1805 c1aa  5....8.....0....
0000180: b05d dfe2 4474 b26f 14be fc7f ccba c499  .]..Dt.o........
0000190: 856a c31f c361 90f1 8c27 3235 3662 6173  .j...a...'256bas
00001a0: 6520 3134 3962 6173 655b 305d 2f28 3236  e 149base[0]/(26
00001b0: 2c7b 5c5b 3124 295d 2f5c 3224 3d2a 7d2f  ,{\[1$)]/\2$=*}/
00001c0: 5c2c 297b 2d7d 2b25 2b6e 257b 2761 272d  \,){-}+%+n%{'a'-
00001d0: 7e5e 5c3c 217d 2c6e 2a                   ~^\<!},n*

```

Modulo the string compression, the program is

```
0\n/{.'un'/''*.-1base'n?imdop
p_l'12*=110-@@={~)}*+}/:^.'
 reputation
1 create posts
5 participate in meta
10 remove new user restrictions
10 create wiki posts
15 vote up
15 flag posts
20 talk in chat
50 comment everywhere
75 set bounties
100 edit community wiki
100 create chat rooms
125 vote down
150 create tags
200 retag questions
250 view close votes
500 cast close and reopen votes
750 established user
1000 edit questions and answers
1000 create gallery chat rooms
1250 create tag synonyms
1500 approve tag wiki edits
2000 access to moderator tools
3500 protect questions
4000 trusted user'n%{'a'-~^\<!},n*

```

Pretty trivial in most respects, but there are two points of interest.

The first is the hash function for the input strings. I was astonished by how simple a hash function produces unique results for each of the 9 (once `un` is removed) different strings, and as a bonus it also produces a different result for the empty string, which saves stripping out the final blank line from the input.

The calculation of rep for an individual line is

```
.'un'/''*.-1base'n?imdop
p_l'12*=110-@@={~)}*

```

First, it removes `un` from the string, and makes a note of whether it was found. Then it applies a super-simple hash function, `h(s) = ( sum over i: (-1)^i s[i] ) % 11`. (You can see why I was surprised when I found it). The string

```
'n?imdop
p_l'

```

is a lookup table which maps the hash value to the change in rep (subtract 110 from the ASCII value), and then if it found `un` at the start it negates the change.

The second point of interest is the filter for the privileges. I tried a slightly simpler one:

```
{~^\<!},

```

which evaluates the line (undefined words do nothing) in order to get its score for comparison with the reputation (stored in `^`). It *almost* works. The thing which breaks it is that `and` occurs in some of the strings, and is a pre-defined function. Solution: mangle the lines enough that `and` no longer occurs. (There is a case to be made that removing spaces would be better than removing the letter `a`, but it doesn't make any difference to the length).

# Answer
> 8 votes
## Ruby 1.9.3, 514 467 459 (507 460 452 + 7 for flags)

Run with `ruby -rzlib <program>`.

```
#coding:binary
r=0
$<.each{|l|b=l.sub!('un','')?-1:1
r+=('cvuwdsaifo'[/.#{l[9]||break}/].ord-2)*b}
puts"#{r} reputation"
Zlib.inflate('xÚ]QKrÃ Ýû:BìÖ“ó(XM˜`D‘lo_‰ÒL¦;ÐÓûÁ¡*AaQf(X5†X|3¬¤8Œ¨´òNé€M¨Ú]´Æ ‘³8ÞUŽøŒ]jœagmÅ_ ï˜. ˜ž®¨Ãll^WÊ
´S=U®3)ÜxËÉ=.@KÔ¶»å¨g3kónîjP™WÛžºûÂG6ÿ×ŽâÝx!;Â÷f=Z‡ÉvöhõBb¡F¶çpqíCÌ‹ñ¸PîøÕH&€·åAK{OÔ£¾Ô³Tåïqî˜’Uþý=-È™9Ÿx,¥úG8ÒÛZ#ÃB P†•ª¨\\íÂI†§Q)¼¥>¥uýËþ²d').lines{|l|l.to_i<=r&&$><<l}

```

If the binary string literals didn't paste properly (which they probably didn't), here's a hex dump:

```
0000: 23 63 6F 64 69 6E 67 3A 62 69 6E 61 72 79 0A 72   #coding:binary.r
0010: 3D 30 0A 24 3C 2E 65 61 63 68 7B 7C 6C 7C 62 3D   =0.$<.each{|l|b=
0020: 6C 2E 73 75 62 21 28 27 75 6E 27 2C 27 27 29 3F   l.sub!('un','')?
0030: 2D 31 3A 31 0A 72 2B 3D 28 27 11 63 0C 76 07 75   -1:1.r+=('.c.v.u
0040: 00 77 00 64 04 73 01 61 03 69 66 6F 27 5B 2F 2E   .w.d.s.a.ifo'[/.
0050: 23 7B 6C 5B 39 5D 7C 7C 62 72 65 61 6B 7D 2F 5D   #{l[9]||break}/]
0060: 2E 6F 72 64 2D 32 29 2A 62 7D 0A 70 75 74 73 22   .ord-2)*b}.puts"
0070: 23 7B 72 7D 20 72 65 70 75 74 61 74 69 6F 6E 22   #{r} reputation"
0080: 0A 5A 6C 69 62 2E 69 6E 66 6C 61 74 65 28 27 78   .Zlib.inflate('x
0090: DA 5D 51 4B 72 C3 20 0C DD FB 14 3A 42 EC D6 93   .]QKr. ....:B...
00A0: F3 28 58 4D 98 60 44 91 6C 8F 6F 5F 89 D2 4C A6   .(XM.`D.l.o_..L.
00B0: 3B D0 D3 FB C1 08 A1 12 2A 41 61 51 19 66 28 58   ;.......*AaQ.f(X
00C0: 35 86 58 7C 16 33 AC A4 38 8C 17 A8 B4 F2 4E 90   5.X|.3..8.....N.
00D0: E9 80 4D A8 DA 5D B4 C6 A0 91 B3 38 DE 55 8E F8   ..M..].....8.U..
00E0: 8C 5D 6A 9C 61 67 1B 6D C5 8F 5F 09 EF 1D 98 2E   .]j.ag.m.._.....
00F0: A0 98 9E AE 1E 1E A8 C3 6C 6C 5E 57 CA 0A B4 53   ........ll^W...S
0100: 3D 8F 07 55 1A AE 33 08 29 DC 78 CB 1A C9 3D 2E   =..U..3.).x...=.
0110: 40 4B D4 B6 BB E5 A8 67 33 6B F3 6E EE 6A 50 99   @K.....g3k.n.jP.
0120: 57 DB 9E BA FB C2 47 36 FF D7 8E E2 DD 13 78 21   W.....G6......x!
0130: 3B C2 F7 66 3D 5A 87 C9 76 F6 68 F5 42 62 A1 46   ;..f=Z..v.h.Bb.F
0140: B6 E7 70 71 14 ED 43 CC 8B F1 B8 50 EE F8 D5 48   ..pq..C....P...H
0150: 26 80 B7 14 E5 41 4B 7B 1A 4F D4 A3 BE D4 1B 13   &....AK{.O......
0160: B3 1C 54 E5 17 EF 71 EE 98 92 55 FE 17 FD 3D 2D   ..T...q...U...=-
0170: C8 99 39 9F 0E 78 1A 2C A5 FA 47 38 D2 1E DB 8D   ..9..x.,..G8....
0180: 5A 23 C3 42 20 11 50 86 95 17 AA A8 5C 5C ED C2   Z#.B .P.....\\..
0190: 49 86 0F A7 1A 51 29 BC A5 1A 3E 9D A5 75 13 FD   I....Q)...>..u..
01A0: CB FE 03 06 1A B2 64 27 29 2E 6C 69 6E 65 73 7B   ......d').lines{
01B0: 7C 6C 7C 6C 2E 74 6F 5F 69 3C 3D 72 26 26 24 3E   |l|l.to_i<=r&&$>
01C0: 3C 3C 6C 7D                                       <<l}

```

# Answer
> 5 votes
## Haskell, 787 characters

```
main=interact$unlines.f.z(l 0[521,471,703,455,687,320,355,0,582,93,914,682,476,244,294,545][-15,-10,-5,-2,-2,-2,-1,1,1,2,2,2,5,10,15,100].g).s
f r=[show x++" "++y|(x,y)<-(r,"reputation"):takeWhile((<=r).fst)(zip[1,5,10,10,15,15,20,50,75,100,100,125,150,200,250,500,750,1000,1000,1250,1500,2000,3500,4000].s$"A E@participate in meta@remove new I restrictions@A K E@J up@flag E@talk in C@comment everywhere@set bounties@B community K@A C G@J down@A Hs@reH F@view D Js@cast D and reopen Js@established I@B F and answers@A gallery C G@A H synonyms@approve H K Bs@access to moderator tools@protect F@trusted I">>=h)]
g x=z fromEnum x-1219
h x=l[x]['@'..]("\n":words"create edit chat close posts questions rooms tag user vote wiki")x
l d k v x=maybe d id.lookup x$zip k v
s=lines
z=(sum.).map

```

# Answer
> 5 votes
## C# ~~1271~~ ~~1208~~ 1206

```
public class D:Dictionary<string,int>{}
void A(){
string a="answer",q="question",c="create",y="accept",x=y+"ed",u="upvote",d="downvote";
var p=new D{{c+" posts",1},{"participate in meta",5},{"remove new user restrictions",10},{c+" wiki posts",10},{"vote up",15},{"flag posts",15},{"talk in chat",20},{"comment everywhere",50},{"set bounties",75},{"edit community wiki",100},{c+" chat rooms",100},{"vote down",125},{c+" tags",150},{"retag "+q+"s",200},{"view close votes",250},{"cast close and reopen votes",500},{"established user",750},{"edit "+q+"s and "+a+"s",1000},{c+" gallery chat rooms",1000},{c+" tag synonyms",1250},{"approve tag wiki edits",1500},{"access to moderator tools",2000},{"protect "+q+"s",3500},{"trusted user",4000}};
var e=new D{{a+" un"+x,-15},{a+" un"+u+"d",-10},{q+" un"+u+"d",-5},{a+" "+d+"d",-2},{q+" "+d+"d ",-2},{"un"+y+" "+a,-2},{d+" "+a,-1},{"join website",1},{"un"+d+" "+a,1},{y+" "+a,2},{q+" un"+d+"d",2},{a+" un"+d+"d",2},{q+" "+u+"d",5},{a+" "+u+"d",10},{a+" "+x,15},{"association bonus",100}};
var s=0;
for(var l=Console.ReadLine();l!="";l=Console.ReadLine())s+=e[l];
Console.WriteLine(s+" reputation");foreach(var i in p.Where(i=>i.Value<=s))Console.WriteLine(i.Key);}

```

# Answer
> 4 votes
# C - 1083 1069

I realize that I'm a bit late to the game, but C's not represented, so I figured I'd take a stab at it.

```
#include <stdio.h>
H(char*c){int h,n;for(h=n=0;*c!=0;++n,++c)h=(h^*c)+n;return h;}
main(){int h,r=0,R[483];R[110]=-15;R[122]=-10;R[153]=2;R[157]=1;R[189]=-2;R[20]=-2;R[235]=5;R[238]=15;R[28]=10;R[30]=2;R[351]=-5;R[388]=100;R[482]=-2;R[52]=2;R[77]=-1;R[87]=1;char L[99];while(h=H(gets(&L)))r+=R[h];
#define G(x)if(r<x)goto E;
#define P(x)printf("%s\n",x);
P("1 create posts")G(5)P("5 participate in meta")G(10)P("10 remove new user restrictions\n10 create wiki posts")G(15)P("15 vote up\n15 flag posts")G(20)P("20 talk in chat")G(50)P("50 comment everywhere")G(75)P("75 set bounties")G(100)P("100 edit community wiki\n100 create chat rooms")G(125)P("125 vote down")G(150)P("150 create tags")G(200)P("200 retag questions")G(250)P("250 view close votes")G(500)P("500 cast close and reopen votes")G(750)P("750 established user")G(1000)P("1000 edit questions and answers\n1000 create gallery chat rooms")G(1250)P("1250 create tag synonyms")G(1500)P("1500 approve tag wiki edits")G(2000)P("2000 access to moderator tools")G(3500)P("3500 protect questions")G(4000)P("4000 trusted user")E:}

```

```
#include <stdio.h>
H(char*c){int h,n;for(h=n=0;*c;++n,++c)h=(h^*c)+n;return h;}
main(){int h,r=0,R[483];R[110]=-15;R[122]=-10;R[153]=2;R[157]=1;R[189]=-2;R[20]=-2;R[235]=5;R[238]=15;R[28]=10;R[30]=2;R[351]=-5;R[388]=100;R[482]=-2;R[52]=2;R[77]=-1;R[87]=1;char L[99];while(h=H(gets(&L)))r+=R[h];
#define G(x)if(r<x)return;
#define P(x)puts(x);
P("1 create posts")G(5)P("5 participate in meta")G(10)P("10 remove new user restrictions\n10 create wiki posts")G(15)P("15 vote up\n15 flag posts")G(20)P("20 talk in chat")G(50)P("50 comment everywhere")G(75)P("75 set bounties")G(100)P("100 edit community wiki\n100 create chat rooms")G(125)P("125 vote down")G(150)P("150 create tags")G(200)P("200 retag questions")G(250)P("250 view close votes")G(500)P("500 cast close and reopen votes")G(750)P("750 established user")G(1000)P("1000 edit questions and answers\n1000 create gallery chat rooms")G(1250)P("1250 create tag synonyms")G(1500)P("1500 approve tag wiki edits")G(2000)P("2000 access to moderator tools")G(3500)P("3500 protect questions")G(4000)P("4000 trusted user")}

```

Here's a slightly less golfed version:

```
#include <stdio.h>
int hash(char * c){int h,n;for(h=n=0;*c!=0;++n,++c)h=(h^*c)+n;return h;}
int main(int argc, char *argv[])
{
int R[483];
R[110]=-15;// answer unaccepted
R[122]=-10;// answer unupvoted
R[153]=2;  // question undownvoted
R[157]=1;  // join website
R[189]=-2; // question downvoted
R[20]=-2;  // answer downvoted
R[235]=5;  // question upvoted
R[238]=15; // answer accepted
R[28]=10;  // answer upvoted
R[30]=2;   // answer undownvoted
R[351]=-5; // question unupvoted
R[388]=100;// association bonus
R[482]=-2; // unaccept answer
R[52]=2;   // accept answer
R[77]=-1;  // downvote answer
R[87]=1;   // undownvote answer
int h,r=0;
char L[99];
while(h=hash(gets(&L)))r+=R[h];
#define G(x)if(r<x)goto end;
#define P(x)printf("%s\n",x);
P("1 create posts")
G(5)
P("5 participate in meta")
G(10)
P("10 remove new user restrictions")
P("10 create wiki posts")
G(15)
P("15 vote up")
P("15 flag posts")
G(20)
P("20 talk in chat")
G(50)
P("50 comment everywhere")
G(75)
P("75 set bounties")
G(100)
P("100 edit community wiki")
P("100 create chat rooms")
G(125)
P("125 vote down")
G(150)
P("150 create tags")
G(200)
P("200 retag questions")
G(250)
P("250 view close votes")
G(500)
P("500 cast close and reopen votes")
G(750)
P("750 established user")
G(1000)
P("1000 edit questions and answers")
P("1000 create gallery chat rooms")
G(1250)
P("1250 create tag synonyms")
G(1500)
P("1500 approve tag wiki edits")
G(2000)
P("2000 access to moderator tools")
G(3500)
P("3500 protect questions")
G(4000)
P("4000 trusted user")
end:
return 0;
}

```

I think the basic idea is similar to many other people's approaches. I use a little home-made hash to deal with recognizing inputs. The hash conveniently gives zero for an empty string, making the input-reading line very compact. I'm sure that the hash could be greatly improved. Some good character savings could be gotten by allowing some strategic hash collisions for things that have the same reputation.

I also had some real perverse fun hiding a `goto` inside a macro (my first time ever using a `goto`, I'm proud to say).

The one place where I'm sure I have a *lot* of room for improvement is in the output section. I haven't even attempted to compress the actual printing logic, so I'm sure that I could save some characters there as well.

# Answer
> 3 votes
# C (~~765~~ 737 chars)

```
#define P(x,m) if(s>=x)puts(#x" "#m);
s;char*e="&g 5 x$hg54  $  G5UC vg",l[99];main(){while(gets(l))s+=e[(l[11]%8^l[7])-97]*7%118-15;printf("%d reputation\n",s);P(1,create posts)P(5,participate in meta)P(10,remove new user restrictions)P(10,create wiki posts)P(15,vote up)P(15,flag posts)P(20,talk in chat)P(50,comment everywhere)P(75,set bounties)P(100,edit community wiki)P(100,create chat rooms)P(125,vote down)P(150,create tags)P(200,retag questions)P(250,view close votes)P(500,cast close and reopen votes)P(750,established user)P(1000,edit questions and answers)P(1000,create gallery chat rooms)P(1250,create tag synonyms)P(1500,approve tag wiki edits)P(2000,access to moderator tools)P(3500,protect questions)P(4000,trusted user)}

```

Or a bit more readable with added linebreaks and indentation:

```
#define P(x,m) if(s>=x)puts(#x" "#m);
s;char*e="&g 5 x$hg54  $  G5UC vg",l[99];
main(){
 while(gets(l))s+=e[(l[11]%8^l[7])-97]*7%118-15;
 printf("%d reputation\n",s);
 P(1,create posts)
 P(5,participate in meta)
 P(10,remove new user restrictions)
 P(10,create wiki posts)
 P(15,vote up)
 P(15,flag posts)
 P(20,talk in chat)
 P(50,comment everywhere)
 P(75,set bounties)
 P(100,edit community wiki)
 P(100,create chat rooms)
 P(125,vote down)
 P(150,create tags)
 P(200,retag questions)
 P(250,view close votes)
 P(500,cast close and reopen votes)
 P(750,established user)
 P(1000,edit questions and answers)
 P(1000,create gallery chat rooms)
 P(1250,create tag synonyms)
 P(1500,approve tag wiki edits)
 P(2000,access to moderator tools)
 P(3500,protect questions)
 P(4000,trusted user)
}

```

The above codes assumes a single newline at the end of the file. If there are two, then one needs to write `s+=*l?e[…]:0` instead of `s+=e[…]`, at an **additional cost of 5 chars**. Writing `while(*gets(l))` would be shorter but won't work since I don't include headers, so the compiler assumes `gets` returns `int` not `char*`.

The hashing expression `(l[11]%8^l[7])-97` was found by trying all expressions of the following forms, looking for the one with shortest resulting code length:

```
for i in range(13):
    for j in range(13):
        pat("a[i]^a[j]", i=i, j=j)
        pat("a[i]-a[j]", i=i, j=j)
        pat("a[i]|a[j]", i=i, j=j)
        pat("a[i]&a[j]", i=i, j=j)
        pat("a[i]*a[j]", i=i, j=j)
        pat("a[i]%a[j]", i=i, j=j)
        for k in range(13):
            pat("a[i]^a[j]^a[k]", i=i, j=j, k=k)
            pat("a[i]%a[j]^a[k]", i=i, j=j, k=k)
            pat("a[i]*a[j]^a[k]", i=i, j=j, k=k)
            pat("a[i]+a[j]^a[k]", i=i, j=j, k=k)
            pat("a[i]-a[j]^a[k]", i=i, j=j, k=k)
            pat("a[i]^a[j]|a[k]", i=i, j=j, k=k)
            pat("a[i]%a[j]|a[k]", i=i, j=j, k=k)
            pat("a[i]*a[j]|a[k]", i=i, j=j, k=k)
            pat("a[i]+a[j]|a[k]", i=i, j=j, k=k)
            pat("a[i]-a[j]|a[k]", i=i, j=j, k=k)
            pat("a[i]*k^a[j]", i=i, j=j, k=k)
            pat("a[i]%k^a[j]", i=i, j=j, k=k)
            pat("a[i]%k+a[j]", i=i, j=j, k=k)
            pat("a[i]%k-a[j]", i=i, j=j, k=k)
            pat("a[i]%k|a[j]", i=i, j=j, k=k)
            for l in range(13):
                pat("a[i]%k^a[j]%l", i=i, j=j, k=k, l=l)
        for k in range(100):
            pat("a[i]+k^a[j]", i=i, j=j, k=k)
            pat("a[i]-k^a[j]", i=i, j=j, k=k)

```

A suitable printable ASCII character representation was found using a similar brute force search.

# Python 3 (~~743~~ 715 chars)

In the same spirit as above. This one relies on a second newline at the end of the input, though.

```
s=0
while 1:
 l=input()
 if not l:break
 s+=b'>-/1/.04-1*//0//91%\x93/ -'[(ord(l[11])%8^ord(l[7]))-97]-47
print(s,"reputation")
for p in "1 create posts|5 participate in meta|10 remove new user restrictions|10 create wiki posts|15 vote up|15 flag posts|20 talk in chat|50 comment everywhere|75 set bounties|100 edit community wiki|100 create chat rooms|125 vote down|150 create tags|200 retag questions|250 view close votes|500 cast close and reopen votes|750 established user|1000 edit questions and answers|1000 create gallery chat rooms|1250 create tag synonyms|1500 approve tag wiki edits|2000 access to moderator tools|3500 protect questions|4000 trusted user".split("|"):
 if s>=int(p.split(" ")[0]):print(p)

```

# Answer
> 2 votes
**Java - 1519 chars**

```
import java.util.*;public class A{static List m=new ArrayList();static String c="create",p="posts",w="wiki",e="edit",v="vote",t="tag",q="questions";
static void g(String a){m.add(a);}public static void main(String a[]){
g("1 "+c+" "+p);g("5 participate in meta");g("10 remove new user restrictions");g("10 "+c+" "+w+" "+p);g("15 "+v+" up");g("15 flag "+p);g("20 talk in chat");g("50 comment everywhere");g("75 set bounties");g("100 "+e+" community "+w);g("100 "+c+" chat rooms");g("125 "+v+" down");g("150 "+c+" "+t+"s");g("200 re"+t+" "+q);g("250 view close "+v+"s");g("500 cast close and reopen "+v+"s");g("750 established user");g("1000 "+e+"s "+q+" and answers");g("1000 "+c+" gallery chat rooms");g("1250 "+c+" "+t+" synonyms");g("1500 approve "+t+" "+w+" "+e+"s");g("2000 access to moderator tools");g("3500 protect "+q);g("4000 trusted user");
Scanner s=new Scanner(System.in);String i=s.nextLine();int r=0;int b;
while(!i.equals("")){b=r(i);if(b==1740)r-=15;if(b==1690)r-=10;if(b==1922)r-=5;if(b==1674||b==1906||b==1539)r-=2;if(b==1574)r-=1;if(b==1219||b==1801)r+=1;if(b==1312||b==2133||b==1901)r+=2;if(b==1695)r+=5;if(b==1463)r+=10;if(b==1513)r+=15;if(b==1764)r+=100;i=s.nextLine();}
System.out.println(r+" reputation");for(Object q:m)if(c(q,r))System.out.println((String)q);}
static boolean c(Object q,int r){StringTokenizer t=new StringTokenizer((String)q);if(Integer.parseInt(t.nextToken())<=r)return true;return false;}
static int r(String i){int r=0;for(int k=0;k<i.length();)r+=i.charAt(k++);return r;}}

```

To find reputation, it adds all the character in input string (example 'join website' adds to form 1219) and when b==1219, r=r+1.

# Answer
> 2 votes
### Scala 1089

```
object R extends App{val t=List(("j.*",1),(".*s",100),(".*r a.*",15),(".*r d.*",-2),(".*n d.*",-2),(".* una.*",-15),("u.*",-2),("ac.*",2),("und.*",1),("d.*",-1),(".*r up.*",10),(".*n up.*",5),(".*r unu.*",-10),(".*r .*",2),(".*n unu.*",-5),(".*n .*",2))
def a(s:String)=t.find(x=>s.matches(x._1)).map(x=>x._2).getOrElse(0)
var(r,s)=(0,"")
do{s=readLine
r+=a(""+s)}while(s!=null)
println(r+" reputation")
val (q,c)=(" questions","create ")
val d=List(1->(c+"posts"),5->"participate in meta",10->"remove new user restrictions",10->(c+"wiki posts"),15->"vote up",15->"flag posts",20->"talk in chat",50->"comment everywhere",75->"set bounties",100->"edit community wiki",100->(c+"chat rooms"),125->"vote down",150->(c+"tags"),200->("retag"+q),250->"view close votes",500->"cast close and reopen votes",750->"established user",1000->("edit"+q+" and answers"),1000->(c+"gallery chat rooms"),1250->(c+"tag synonyms"),1500->"approve tag wiki edits",2000->"access to moderator tools",3500->("protect"+q),4000->"trusted user")
d.filter(_._1<=r).toList.sortBy(_._1).map(v=>println((v._1)+" "+v._2))}

```

Rewrote from scratch, nearly. If I have to calculate the data in, it is cheaper (while ugly) to include the data directly.

First approach, reading event prices and privilege tab from files:

### reading data from file: 405

```
object R extends App{import io.Source._
import java.util._
def m(n:String)={fromFile(n).getLines.toList.map{l=>val s=new Scanner(l);(s.next(),s.nextLine())}}
val e=m("e").map(a=>(a._2.trim->a._1.replaceAll("\\+","").toInt)).toMap
val p=m("p").map(b=>(b._1.toInt,b._2))
var(r,t)=(0,"")
for(t<-stdin.getLines)r+=e(t)
println(r+" reputation")
p.filter(_._1<=r).toList.sortBy(_._1).map(v=>println(v._1+v._2))}

```

# Answer
> 1 votes
## J (704)

The program consists of four parts:

1. the following decoder script (**277** bytes)

```
b=:,@#:@(a.i.fread)
s=:(15+6*#.@(3{.12&}.))({.;$:^:(40<#)@}.)]
r=:3 :'(15-~#.12{.y);;:^:_1[(#._6>\15}.y){u:@(96&+)&.>0 cut#._5>\b''w'''&.>@s@b
f=:3 :'>>{.&.>e#~;((<y)=}.)&.>e=:r''e'''
echo' reputation',~":R=:+/;f&.>LF cut 1!:1[3
echo>((":@>@{.),' ',>@{:)&.>p#~R>>>{.&.>p=:r'p'

```
2. a binary words file, called `w`, also **277** bytes (download here).

The file format is as follows: each word is encoded as a group of five-bit "bytes". Each group of five bits can have a value from `1` to `27` representing letters, or `0` being the separator. Every unique word in the description of the events and privileges is stored here.
3. a binary events file, called `e`, which is **54** bytes (download here).

Each event consists of a 12-byte reputation and one or more 6-byte words. For example, `accept answer` is encoded as follows:

```
 rep+15       Nwords  word1    word2
 000000010001 010     000110   011101
 17           2       6        29     <- these are indices in "w"
                      "accept" "answer"

```
4. a binary privileges file, called `p`, which is **96** bytes (download here).

The file format is the same as `e`, e.g. `access to moderator tools` is encoded as follows:

```
rep+15       Nwords word1    word2  word3       word4
011111011111 100    011010   011011 100000      010000
2015         4      26       27     32          16
                    "access" "to"   "moderator" "tools"

```

# Answer
> 0 votes
# Perl, ~~856~~ 849 characters

```
$_="reputaT,A unPed,-15,A unU,-10,Q unU,-5,A DVd,-2,Q DVd,-2,unP A,-2,DV A,-1,join website,1,unDV A,1,P A,2,Q unDVd,2,A unDVd,2,Q U,5,A U,10,A Ped,15,associaT bonus,100,1,C Ps,5,participate in meta,10,remove new R restricTs,10,C wiki Ps,15,V up,15,flag Ps,20,talk in H,50,comment everywhere,75,set bounties,100,edit community wiki,100,C H rooms,125,V D,150,C tags,200,retag Qs,250,view close Vs,500,cast close and reopen Vs,750,established R,1000,edit Qs and As,1000,C gallery H rooms,1250,C tag synonyms,1500,approve tag wiki edits,2000,access to moderator tools,3500,protect Qs,4000,trusted R";$s="UupVd;Paccept;Aanswer;QquesT;Ccreate;Vvote;Ddown;Ttion;Opost;Hchat;Ruser;";$s=~s,(.)(.+?);,s/$1/$2/g;,g;eval $s;@D=split/,/;%R=@D[1..32];@P=@D[33..80];while(<>){chomp;$r+=$R{$_}}print("$r $D[0]\n");for(0..23){print"@P[$_*2,$_*2+1]\n"if$r>=$P[$_*2]}

```

just adding linebreaks after some semicolons for readability ;) :

```
$_="reputaT,A unPed,-15,A unU,-10,Q unU,-5,A DVd,-2,Q DVd,-2,unP A,-2,DV A,-1,join website,1,unDV A,1,P A,2,Q unDVd,2,A unDVd,2,Q U,5,A U,10,A Ped,15,associaT bonus,100,1,C Ps,5,participate in meta,10,remove new R restricTs,10,C wiki Ps,15,V up,15,flag Ps,20,talk in H,50,comment everywhere,75,set bounties,100,edit community wiki,100,C H rooms,125,V D,150,C tags,200,retag Qs,250,view close Vs,500,cast close and reopen Vs,750,established R,1000,edit Qs and As,1000,C gallery H rooms,1250,C tag synonyms,1500,approve tag wiki edits,2000,access to moderator tools,3500,protect Qs,4000,trusted R";
$s="UupVd;Paccept;Aanswer;QquesT;Ccreate;Vvote;Ddown;Ttion;Opost;Hchat;Ruser;";
$s=~s,(.)(.+?);,s/$1/$2/g;,g;eval $s;
@D=split/,/;%R=@D[1..32];@P=@D[33..80];
while(<>){chomp;$r+=$R{$_}}print("$r $D[0]\n");
for(0..23){print"@P[$_*2,$_*2+1]\n"if$r>=$P[$_*2]}

```

# Answer
> 0 votes
# Java (1470 chars)

---

**Note:** It's a modification of Aman ZeeK Verma's answer but since my edit wasn't accepted and my answer is significantly shorter than his, I'm posting it here.

*Readable Version:*

```
import java.util.*;

public class A {

    static List m = new ArrayList();
    static String c = "create", p = "posts", w = "wiki", e = "edit", v = "vote", t = "tag", q = "questions";

    static void g(String a) {
        m.add(a);
    }

    public static void main(String a[]) {
        g("1 " + c + " " + p);
        g("5 participate in meta");
        g("10 remove new user restrictions");
        g("10 " + c + " " + w + " " + p);
        g("15 " + v + " up");
        g("15 flag " + p);
        g("20 talk in chat");
        g("50 comment everywhere");
        g("75 set bounties");
        g("100 " + e + " community " + w);
        g("100 " + c + " chat rooms");
        g("125 " + v + " down");
        g("150 " + c + " " + t + "s");
        g("200 re" + t + " " + q);
        g("250 view close " + v + "s");
        g("500 cast close and reopen " + v + "s");
        g("750 established user");
        g("1000 " + e + "s " + q + " and answers");
        g("1000 " + c + " gallery chat rooms");
        g("1250 " + c + " " + t + " synonyms");
        g("1500 approve " + t + " " + w + " " + e + "s");
        g("2000 access to moderator tools");
        g("3500 protect " + q);
        g("4000 trusted user");
        Scanner s = new Scanner(System.in);
        String i = s.nextLine();
        int r = 0;
        int b;
        while (!i.equals("")) {
            b = r(i);
            if (b == 1740) {
                r -= 15;
            }
            if (b == 1690) {
                r -= 10;
            }
            if (b == 1922) {
                r -= 5;
            }
            if (b == 1674 || b == 1906 || b == 1539) {
                r -= 2;
            }
            if (b == 1574) {
                r -= 1;
            }
            if (b == 1219 || b == 1801) {
                r += 1;
            }
            if (b == 1312 || b == 2133 || b == 1901) {
                r += 2;
            }
            if (b == 1695) {
                r += 5;
            }
            if (b == 1463) {
                r += 10;
            }
            if (b == 1513) {
                r += 15;
            }
            if (b == 1764) {
                r += 100;
            }
            i = s.nextLine();
        }
        System.out.println(r + " reputation");
        for (Object o : m) {
            if (c(o, r)) {
                System.out.println((String) o);
            }
        }
    }

    static boolean c(Object q, int r) {
        return Integer.parseInt(new StringTokenizer((String) q).nextToken()) <= r;
    }

    static int r(String i) {
        int r = 0;
        for (int k = 0; k < i.length();) {
            r += i.charAt(k++);
        }
        return r;
    }
}

```

*Minified Version:*

```
import java.util.*;public class A{static List m=new ArrayList();static String c="create",p="posts",w="wiki",e="edit",v="vote",t="tag",q="questions";static void g(String a){m.add(a);}public static void main(String a[]){g("1 "+c+" "+p);g("5 participate in meta");g("10 remove new user restrictions");g("10 "+c+" "+w+" "+p);g("15 "+v+" up");g("15 flag "+p);g("20 talk in chat");g("50 comment everywhere");g("75 set bounties");g("100 "+e+" community "+w);g("100 "+c+" chat rooms");g("125 "+v+" down");g("150 "+c+" "+t+"s");g("200 re"+t+" "+q);g("250 view close "+v+"s");g("500 cast close and reopen "+v+"s");g("750 established user");g("1000 "+e+"s "+q+" and answers");g("1000 "+c+" gallery chat rooms");g("1250 "+c+" "+t+" synonyms");g("1500 approve "+t+" "+w+" "+e+"s");g("2000 access to moderator tools");g("3500 protect "+q);g("4000 trusted user");Scanner s=new Scanner(System.in);String i=s.nextLine();int r=0;int b;while(!i.equals("")){b=r(i);if(b==1740)r-=15;if(b==1690)r-=10;if(b==1922)r-=5;if(b==1674||b==1906||b==1539)r-=2;if(b==1574)r-=1;if(b==1219||b==1801)r+=1;if(b==1312||b==2133||b==1901)r+=2;if(b==1695)r+=5;if(b==1463)r+=10;if(b==1513)r+=15;if(b==1764)r+=100;i=s.nextLine();}System.out.println(r+" reputation");for(Object o:m)if(c(o,r))System.out.println((String)o);}static boolean c(Object q,int r){return Integer.parseInt(new StringTokenizer((String)q).nextToken())<=r;}static int r(String i){int r=0;for(int k=0;k<i.length();)r+=i.charAt(k++);return r;}}

```

# Answer
> 0 votes
## PHP: 676 chars

It won't win any prizes but gosh darn it I just can't figure out how to make this any smaller, so I'll just post it:

```
<?php
while($l=fgets(STDIN))foreach(@[j=>1,bo=>100,pt=>2,pte=>13,'r un?u?p'=>5,up=>5,wn=>-2,'e '=>1]as$k=>$v)@$r+=$v*ereg($k,$l)*(ereg(un,$l)?-1:1);$p=@preg_replace;foreach(split('
',$p('/[A-Z]/e','" ".$p("/.*?$0|[A-Z].*/","",@AaCcreateEeditGtagHchatIinLcloseMcommPpostsQquestionsRroomsTtUuserVvoteWwikiZre)',$r."Zputation
1CP
5 participateI meta
10Zmove newUZstrictions
10CWP
15V up
15 flagP
20TalkIH
50Ment everywhere
75 set bounties
100EMunityW
100CHR
125V down
150CGs
200ZtagQ
250 viewLVs
500 castLAndZopenVs
750 establishedU
1000EQAndAnswers
1000C galleryHR
1250CG synonyms
1500ApproveGWEs
2000AccessTo moderatorTools
3500 protectQ
4000TrustedU"))as$i)$r>=$i&&print"$i
";

```

Since the part that calcs the rep is very hard to read, here it is with extra formatting. It abuses undefined constants and uses @ to shut them up:

```
while($l=fgets(STDIN))
foreach(@[
        j=>1, // join website
        bo=>100, // association bonus
        pt=>2, // (un)?accept answer|answer (un)?accepted
        pte=>13, // answer (un)?accepted
        'r un?u?p'=>5, // answer (un)?upvoted
        up=>5, // (answer|question) (un)?upvoted
        wn=>-2, // (answer|question) (un)?downvoted|(un)?downvote answer
        'e '=>1 // (un)?downvote answer
        ]as$k=>$v)
    @$r+=$v*ereg($k,$l)*(ereg(un,$l)?-1:1);

```

# Answer
> 0 votes
## APL (549)

This one packs the data in Unicode characters.

```
P
D←{,⍉(20/2)⊤⎕UCS⍵}
M←{×⍴⍵:(2⊥⍺↑⍵),⍺∇⍺↓⍵⋄⍬}
Z←{15<⍴⍵:(⊂(15-⍨2⊥12↑⍵),' ',.,w[6M 15↓r↑⍵]),∇⍵↓⍨r←15+6×2⊥3↑12↓⍵⋄⍬}
w←⎕UCS¨96+1↓¨w⊂⍨0=w←5M D'崫퀖䢴鰒ᒉ৮멷ᛅ칯䉏⧩ᒉ鰕킠ؐ倬'
⎕←'reputation',⍨r←+/{⊃⊃e/⍨⍵∘{⍺≡⊃1↓⍵}¨e←Z D'Oڧ詻礽'}¨{×⍴⍵:(⊂' ',⍵),∇⍞⋄⍬}⍞
⎕←↑↑{⍵,⍨⍕⍺}/¨p/⍨r≥⊃¨p←Z D'၌ᦚ㋘爁㲦节殃䇍'

```

# Answer
> 0 votes
# Python 3.x (801 chars)

Best I can do so far, just need to work out a better encoding than base64 (hint hint: can somebody assist?).

```
import base64,zlib
exec(zlib.decompress(base64.b64decode(b'eJxtU93O2jAMve9T+K7tCJ+ArZqExpMgLkJrICNNsvxQoel799kplI7toqLYPsfHx27hxVkoIYXbrcT+IJRxKVa1+F0m09nB3GxEkCYM6MvtWpSybdHFKbKhSH6FMYEdVTWi/GmVgQGPQUUccSHYVsmorIGjNSlQdLUS5a+EIQeT41YEJ3Qyb22Wm3nlJKybC5gFufwf8cv1VJrM1G25not445jKX8MtebqZlBdRM6v/r8CpdL36JH899vaGYHCAFCjtidOrlnmzOYRzznNJlGcY1FUBdipyrmHnWo8yjslwN9bce05tGkoFjGRyMlEhxb6TMkZCa/s+GRXvme2xgOxRcuPaqF/ENsJzQEJ/nTc7S63R36G9yAje2n5cIxcQN5oIeKP8cEFPa2/+UjkKp4gMJEXbwKvpaGzr0ADLCAx5YfLIzob4sCNKfQU6K25OvrJ2ReaNVA98Hj8PO42Qu4wreKkdOzzJx7MOAaKF3nboZbSe/ljNlBlBZPKoVbhgl9fFtrImn0KcQt/m5G8ekbnSR9Uqx0kao8co87V75B3OLN9w9UlT8CmweeyJ7yov+bM4kULNPOojOK1iVZZlQU+9LUCdQNMP+MVO7vWhcF6ZWHluRV93/gjLOjMoZnAjxO3V4cfOM/D8QbeHpqvoJCuO14sSyoWqH1RfgvU0dnUWV7zvtOyPnQS5Bc7Jpx4o6/3qUNcioNs91RV/ACHUeCw=')).decode())

```

# Answer
> 0 votes
# Python 3.8 (pre-release), 714 bytes

```
r=0
L=' questions'
C=',create '
K=f'j,nv,n u,r u,ss,e ,t ,pte,reputation{C}posts,participate in meta,remove new user restrictions{C}wiki posts,vote up,flag posts,talk in chat,comment everywhere,set bounties,edit community wiki{C}chat rooms,vote down{C}tags,retag{L},view close votes,cast close and reopen votes,established user,edit{L} and answers{C}gallery chat rooms{C}tag synonyms,approve tag wiki edits,access to moderator tools,protect{L},trusted user'.split(',')
while 1:
 i=input()
 if not i:break
 r+=[1,-2,5,10,100,-1,2,15][[a in i for a in K].index(1)]*(1-2*('un'in i))
for R,j in zip([r,1,5,10,10,15,15,20,50,75,100,100,125,150,200,250,500,750,1e3,1e3,1250,1400,2e3,3500,4e3],K[8:]):
 if R<=r:print(R,j)

```

Try it online!

Yay, I'm 1 byte below the best answer!

Uses the restricted input format (input through STDIN, output through STDOUT).

Surprisingly, switching to a lambda only saves thirteen bytes.

---
Tags: code-golf, kolmogorov-complexity
---


title: Distance to closest subsequent value

text:
# Question
Title: Distance to closest subsequent value
*Inspired by this SO post.*

Given a vector (first parameter), e.g.:

```
char = ["A", "B", "C", "A", "A"]

```

For each element of the vector, find the distance to the closest **subsequent** specified value (second parameter). When the element is identical to the specified value, return 0.

```
f(char, "A") -> [0 2 1 0 0]

```

**Explanation**

`f(char, "A")` returns `[0 2 1 0 0]` because `f` returns the distance to the closest following value that equals "A". The first value of `char` is "A", so as the element is equal to the desired value, return 0. For the second element, "B", the closest "A" is two positions away from it (position 4 - position 2 = 2). For the third element "C", the closest subsequent "A" is 1 position away from it.

When there are no subsequent values that match the specified value, return nothing. When the specified value is not part of the vector, the function can either return an empty vector or throw an error.

The function should work for string vectors or integer vectors.

**Tests**

```
char = ["A", "B", "C", "A", "A"]
f(char, "B") -> [1 0]
f(char, "C") -> [2 1 0]
f(char, "D") -> []

int = [1, 1, 0, 5, 2, 0, 0, 2]
f(int, 0) -> [2 1 0 2 1 0 0]
f(int, 1) -> [0 0]
f(int, 2) -> [4 3 2 1 0 2 1 0]

```

This is so the shortest code in each language wins.

# Answer
# Haskell, 42 bytes

```
x#(a:b)|x==a=0:x#b|y:q<-x#b=y+1:y:q
_#_=[]

```

Try it online!

For every element, if it equals the search value then it's `0`, if it doesn't then it is 1 greater than the next value.
> 6 votes

# Answer
# , 48 bytes

*-2 bytes thanks to Giuseppe. -1 byte thanks to Dominic van Essen.*

```
\(v,x)sequence(d<-diff(c(0,which(v==x))),d-1,-1)

```

**output**

```
f(int, 0)
# [1] 2 1 0 2 1 0 0
f(int, 1)
# [1] 0 0
f(int, 2)
# [1] 4 3 2 1 0 2 1 0
f(int, 3)
# integer(0)

f(char, "A")
# [1] 0 2 1 0 0
f(char, "B")
# [1] 1 0
f(char, "C")
# [1] 2 1 0
f(char, "D")
# integer(0)

```

Works for R \>= 4.1.0.
> 5 votes

# Answer
# Python, 38 bytes

```
def f(a,x):f(a[1:print(a.index(x))],x)
```

Attempt This Online!

Finishes with an exception

-5 bytes thanks to AnttiP

-1 thanks to dingledooper

## Whython, 40 bytes

```
def f(a,x):f(a[1:print(a.index(x))],x)?0
```

Attempt This Online!

No error
> 4 votes

# Answer
# , ~~56~~ 51 bytes

*Edit: -5 bytes thanks to Giuseppe*

```
f=function(l,x)if(y<-match(x,l,0))c(y-1,f(l[-1],x))

```

Try it online!

Works for any version of .
For  version ≥4.1.0, change "`function`" to "`\`" for 44 bytes.
> 4 votes

# Answer
# Vyxal, 11 bytes

```
ṘKRṘ=vTvßhf

```

Try it Online!

```
ṘKRṘ        # Get suffixes
    =       # Find those that are equal
     vT     # Get truthy indices of each
       vßh  # For each, if it is truthy, get the first
          f # Flatten (remove empty values)

```

Or if we can return zeroes if the required value is not at the end:

# Vyxal, 8 bytes

```
ṘKRṘ=ƛTh

```

Try it Online!

```
ṘKRṘ     # Over suffixes...
    =    # Check if each value is equal to the second input
     ƛ   # Map...
      Th # Find the first index where it is equal

```
> 3 votes

# Answer
# JavaScript (Node.js), 49 bytes

```
c=>g=z=>~(r=z.indexOf(c))?[r,...g(z.slice(1))]:[]

```

Try it online!

Byte shorter than Arnauld and tsh

# Python 3, ~~51~~ 49 bytes

1 byte from AnttiP

```
f=lambda a,k:a*(k in a)and[a.index(k)]+f(a[1:],k)

```

Try it online!
> 3 votes

# Answer
# tinylisp, ~~73~~ 71 bytes

```
(load library
(d F(q((L V)(filter inc(i L(c(first-index L V)(F(t L)V))(

```

Try it online!

Ports, e.g., Dominic van Essen's answer.

Uses this tip to filter out `nil` results from `first-index`.

# tinylisp, 79 bytes

```
(d I(q((L V)(i L(c(i(e(h L)V)0(a(h(I(t L)V))1))(i(a(h(I(t L)V))1)(I(t L)V)()))(

```

Try it online!

Without `library` it's a little longer, but the recursion was fun to figure out (and likely still golfable somehow).
> 3 votes

# Answer
# Ruby 2.7.4, ~~56~~ 54 bytes

```
->(a,l){a.filter_map.with_index{|_,i|a[i..].index(l)}}

```

Filter maps over the array and finds the index of the target offset from the current index.

Try it on Replit!

Excited to have gotten my first Golf!
> 3 votes

# Answer
# Python 3.8 (pre-release), 62 bytes

```
lambda n,k:[n[i:].index(k)for i in range(len(n))if k in n[i:]]

```

Try it online!

Pretty straightforward: for each index `i`, find the index of the list starting at index `i` of `k` (second argument) and add it to the output if `k` is in fact in the list starting at index `i`.
> 2 votes

# Answer
# Jelly, 5 bytes

```
iÐƤ¹Ƈ

```

Try it online!

Returns values 1-indexed. Tack on a  for 0-indexed values. Port of my Vyxal answer.

```
 ÐƤ    Map over the suffixes...
i      Find the first index of the other value in each
   ¹Ƈ  Filter out zeroes

```
> 2 votes

# Answer
# Factor, 56 bytes

```
[ indices -1 prefix differences [ 0 (a,b] ] map concat ]

```

Try it online!

## Explanation

Takes input as `element sequence`.

```
                 ! 0 { 1 1 0 5 2 0 0 2 }
indices          ! V{ 2 5 6 }
-1 prefix        ! V{ -1 2 5 6 }
differences      ! { 3 3 1 }
[ 0 (a,b] ] map  ! { { 2 1 0 } { 2 1 0 } { 0 } }
concat           ! { 2 1 0 2 1 0 0 }

```
> 2 votes

# Answer
# BQN, 18 bytesSBCS

```
{∾⌽∘↕¨+`⁼1+/⊸≡¨}

```

Run online!

`⊸≡¨` binary mask with 1's where the left argument appears in the right.
`1+/` 1-based indices.
`+`⁼` differences between adjacent indices with the first value staying.
`⌽∘↕¨` reversed range for each difference.
join into a single list.
> 1 votes

# Answer
# JavaScript (Node.js), 52 bytes

```
a=>v=>a.map((u,i)=>a.indexOf(v,i)-i).filter(x=>x>=0)

```

Try it online!
> 1 votes

# Answer
# APL(Dyalog Unicode), 32 bytes SBCS

```
{∊(⍳≢⍵)(×∘≢⍴|)⍤(-⊢⍤⌿⍨0≥-)¨⊂⍸⍺=⍵}

```

Try it on APLgolf!

or

# APL(Dyalog Unicode), 32 bytes SBCS

```
(∊⍳∘≢⍤⊢(×∘≢⍴|)⍤(-⊢⍤⌿⍨0≥-)¨⊂∘⍸⍤=)

```

Try it on APLgolf!

Equivalent submissions, first one is a dfn and second one is tacit.
> 1 votes

# Answer
# JavaScript (ES10), 50 bytes

Expects `(list)(value)`.

```
a=>v=>a.flatMap((_,i)=>~(j=a.indexOf(v,i))?j-i:[])

```

Try it online!
> 1 votes

# Answer
# 05AB1E, 8 bytes

```
.sRIδk®K

```

Try it online or verify all test cases.

**Explanation:**

```
.s        # Get the suffixes of the first (implicit) input-list
  R       # Reverse it
    δ     # Map over each inner suffix:
   I k    #  Get the (first) 0-based index of the second input
          #  (or -1 if it isn't present)
      ®K  # Remove all -1s
          # (after which the result is output implicitly)

```
> 1 votes

# Answer
# Wolfram Language (Mathematica), 47 bytes

```
Min[p=p-1/.-1->{}]&~Array~Max[0,p=Position@##]&

```

Try it online!

Input `[vector, value]`.
> 1 votes

# Answer
# Charcoal, 14 bytes

```
ＩΦＥθ⌕✂θκＬθ¹η⊕ι

```

Try it online! Link is to verbose version of code. Explanation:

```
   θ            Input array
  Ｅ             Map over elements
    ⌕           Find index of
           η    Value to match in
      θ         Input array
     ✂          Sliced from
       κ        Current index to
         θ      Input array
        Ｌ       Length
          ¹     Step literal integer `1`
 Φ              Filtered where
             ι  Current value
            ⊕   Is not -1
Ｉ               Cast to string
                Implicitly print

```

Slicing arrays is very awkward in Charcoal but it's the same length as filtering (`ＩΦＥθ⌕Φθ¬‹μκη⊕ι`).
> 0 votes

# Answer
# Burlesque, 13 bytes

```
iSjqFi_+m[:+.

```

Try it online!

Takes input as value as a list and the list of search, i.e. `{1} {1 2 3}`. The filter works because the `+.` increment operation works as: `-1+. -> 0`, `0+. -> 1`, `1+. -> 2...` and `0` is falsy.

```
iS  # Generate all tails
j   # Swap stack
qFi # Quoted Find index (returns -1 on fail)
_+  # Append to value (making {value Fi})
m[  # Map block as function
:+. # Filter for not -1

```
> 0 votes

# Answer
# Python 3, 58 bytes

```
lambda a,k:[[a.index(k),a.pop(0)][0]for i in[*a]if k in a]

```

Try it online!
> 0 votes

# Answer
# Julia 1.0, 48 bytes

```
x\y=[(:).(diff([0;findall(x.==y)]).-1,-1,0)...;]

```

Try it online!
> 0 votes

# Answer
# C (gcc), 81 bytes

```
j;i;f(a,n,h)int*a;{for(j=i=0;i<n&j<n;a[i++]=j-i)for(j=i;j<n&&a[j]-h;++j);i-=j/n;}

```

Try it online!

Inputs a pointer to an array of integers, its length (because pointers in C carry no length info), and a target value.
Returns the length of the the array of distances to the closest subsequent target and that array is returned in the input array.
> 0 votes

# Answer
# Pari/GP, 51 bytes

```
f(a,b)=[l[1]-i|i<-[1..#a],l=[j|j<-[i..#a],a[j]==b]]

```

Try it online!

---

# Pari/GP, 53 bytes

```
f(a,b)=s=t=0;r=Vecrev;r([s=!d*s++|c<-r(a),t+=d=c==b])

```

Try it online!
> 0 votes

---
Tags: code-golf
---


title: Find my Māori pronouns

text:
# Question
Title: Find my Māori pronouns
The Māori language has quite simple pronouns. It uses a single word for he/she/they/etc (`ia`), and the words for "you" and "me" are `koe` and `au` respectively.

There are also words for groups of exactly two people:

* `tāua` \- You and me (we, `au` and `koe`)
* `māua` \- Me and them (we, `au` and `ia`)
* `rāua` \- Them (third person plural - two of them, `ia` and `ia`)
* `kōrua` \- You two (`koe` and `koe`)

And for three or more people:

* `tātou` \- All of you and me (we, `au` and multiple `koe`)
* `mātou` \- Me and all of them (we, `au` and multiple `ia`)
* `rātou` \- All of them (third person plural, multiple `ia`)
* `koutou` \- All of you (multiple `koe`)

Your challenge is to take a list of `ia`, `koe` and `au` and return the correct pronoun. You may assume that there is at most one `au` and that `ia` and `koe` will never both be in the input.

You may take input in any reasonable format - An array of `ia`, `koe` and `au` or three distinct values (within reason) representing those, an array of the counts of each word, a dictionary containing the counts of each word, space-separated words etc.

When there is only one word, you should output that.

Note that some of the outputs contain Unicode (`ā` and `ō`). You may output these as they are or as double letters - `aa` and `oo`.

For example, `ia ia` becomes `rāua` as it is two `ia`. `au ia ia ia ia` becomes `mātou` as it is one `au` and more than two `ia`. `koe koe` becomes `kōrua`.

# Testcases

```
ia -> ia
koe -> koe
koe au -> tāua
ia ia -> rāua
koe koe koe koe koe -> koutou
ia ia au ia -> mātou
ia ia ia ia ia ia ia -> rātou

```

# Answer
# JavaScript (Node.js), 94 bytes

```
a=>(g=r=>!!a.match(r))` `?'krtm'[h=g`u`*2+g`i`]+(g` .* `?h?'aatou':'outou':h?'aaua':'oorua'):a

```

Try it online!
> 5 votes

# Answer
# JavaScript (Node.js), 121 bytes

```
x=>x[1]?'koutou0tātou0rātou0mātou0kōrua0tāua0rāua0māua'.split(0)[g=y=>x.includes(y+''),g`au`+g`ia`*2+4*!x[2]]:x[0]

```

Try it online!

Tabling n\>2, "ia" exist, and "au" exist
> 3 votes

# Answer
# Charcoal, 53 bytes

```
≔№θ η¿¬ηθ«≔⁺∧№θia²№θauζ¿ζ⁺§rtmζaa¿⊖ηkou¦koor¿⊖ηtou¦ua

```

Try it online! Link is to verbose version of code. Output uses double vowels. Explanation:

```
≔№θ η

```

Count the number of spaces in the input. (Note that due to Charcoal's input format autodetection, you need a trailing newline in the input for this to work.)

```
¿¬ηθ«

```

If there are no spaces, then just print the input.

```
≔⁺∧№θia²№θauζ

```

Count `2` if `ia` is present, plus `1` if a (assumed single) `au` is present.

```
¿ζ⁺§rtmζaa

```

If either are present then output `taa`, `maa` or `raa` as appropriate, ...

```
¿⊖ηkou¦koor

```

... otherwise output `kou` or `koor` depending on the number of words.

```
¿⊖ηtou¦ua

```

Output `tou` or `ua` depending on the number of words.
> 3 votes

# Answer
# Python 3.8 (pre-release), 124 bytes

```
lambda n:[n,'rmkt'[2*('k'in n)+('u'in n)]+['ou','oa'['a'in n]*2][[*n].count('k')<3]+['ua','tou'][len(n.split())>2]][' 'in n]

```

Try it online!
> 1 votes

# Answer
# Retina 0.8.2, ~~110~~ 79 bytes

```
^(?=(.*au)?)(?=(?<1>.*ia)?){2}\w+ \w+
$#1aaua
T`d`ktmr
ua .*
tou
kaa
kou
uu
oru

```

Try it online! Link includes test cases. Output uses double vowels as those accented characters aren't in Retina's default code page. Explanation:

```
^(?=(.*au)?)(?=(?<1>.*ia)?){2}\w+ \w+

```

See whether the input contains `au`, matching as `$#1`, plus add two further matches to `$#1` if the input contains `ia`. Also delete two words from the input (this fails if the input only contains one word).

```
$#1aaua

```

Replace the first two words with the count of matches suffixed with `aaua`.

```
T`d`ktmr

```

Replace the count with the appropriate letter.

```
ua .*
tou

```

If there were more than two words then change the `ua` to `tou`.

```
kaa
kou

```

`kaatou` should be `koutou`.

```
uu
oru

```

But `kouua` should be `koorua`.
> 1 votes

# Answer
# Ruby `-apl`, 71 bytes

```
k=$F[2]?:koutou: :kōrua;$_=!/a/?k:(/k/??t:/u/??m:?r)+?ā+k[3,3]if$F[1]

```

Try it online!
> 1 votes

# Answer
# Jelly,  ~~57 52 51 49~~  47 bytes

```
“mtr”;€⁾aa;“kou“koor”⁽ñỌ,ḥ;Lị““ua“tou”Ɗ
Ṣḣ3ÇḢḊ?

```

A monadic Link accepting a list of lists of characters that yields a list of characters, the pronoun.

**Try it online!** Or see the test-suite.

### How?

```
“mtr”;€⁾aa;“kou“koor”... - Link 1: list of lists of characters, X
“mtr”                    - "mtr"
       ⁾aa               - "aa"
     ;€                  - concatenate each -> ["maa", "taa", "raa"]
           “kou“koor”    - ["kou", "koor"]
          ;              - concatenate
                         -> domain = ["maa", "taa", "raa", "kou", "koor"]

...⁽ñỌ,ḥ;Lị““ua“tou”Ɗ - Link 1 (continued)
   ⁽ñỌ                - 7932
      ,               - pair
       ḥ              - hash X with a salt of 7932 and our domain (from above)
                    Ɗ - last three links as a monad - f(X):
         L            -   length (2 or 3)
           ““ua“tou”  -   ["", "ua", "tou"]
          ị           -   index into
        ;             - concatenate

Ṣḣ3ÇḢḊ? - Main Link: list of lists of characters, I
Ṣ       - sort I
 ḣ3     - keep up to the first three
      ? - if...
     Ḋ  - ...condition: dequeue (i.e. is length > 1 ?)
   Ç    - ...then: call Link 1
    Ḣ   - ...else: head of I

```
> 1 votes

---
Tags: code-golf, string, natural-language
---


title: All sequences as substrings

text:
# Question
Title: All sequences as substrings
Make a program that outputs a sequence of integers so that every finite sequence of positive integers is a substring (continuous subsequence) of the output.

For example, the following sequence satisfies the rules:

`1,1,1,2,1,1,1,1,2,2,1,3,1,1,1,1,1,1,2,1,2,1,1,3,2,1,1,3,1,4,...`

To see the underlying pattern, let's format the sequence a bit differently:

```
1,
1,1, 2,
1,1,1, 1,2, 2,1, 3,
1,1,1,1, 1,1,2, 1,2,1, 1,3, 2,1,1, 2,2, 3,1, 4,
1,1,1,1,1, 1,1,1,2, 1,1,2,1, 1,1,3, 1,2,1,1, 1,2,2, 1,3,1, 1,4, 2,1,1,1, 2,1,2, 2,2,1, 2,3, 3,1,1, 3,2, 4,1, 5
...

```

Here you can see that every row contains every sequence of positive numbers that sum to the index of the row. For example, row 3 has all sequences whose sum is 3. This means that every sequence is included somewhere in the list.

Standard rules apply. As stated before, your sequence may also contain 0 or negative numbers. These non-positive numbers are not ignored, meaning that your output must contain arbitrarily long substrings of only positive integers.

# Answer
> 10 votes
# 05AB1E, 3 bytes

```
∞Ó˜

```

Try it online!

Outputs the exponents of numbers' prime factorization, flattened. It can be easily seen that all sequences will appear - a sequence \\$ a\_i \\$ will appear when we go over the number \\$ \prod {p\_i}^{a\_i} \\$ (\\$ p\_i \\$ is the i-th prime)

# Answer
> 7 votes
# Haskell, 39 bytes

```
do y<-[1..];q<-mapM id$[1..y]<$[1..y];q

```

Try it online!

Start with the positive integers `[1..]`. Draw an integer `y`. Then take the cartesian product of `y` copies of `[1..y]`. This is just all the ways to choose `y` numbers less than or equal to `y`.

# Answer
> 5 votes
# Vyxal, 8 bytes

```
Þ∞ƛṄvṖ;f

```

Try it Online!

Pretty much the sequence in the question, but with a lot more 1s. Outputs as an infinite lazy list.

```
  ƛ   ;  # Over each element of...
Þ∞       # 1...∞
   Ṅ     # Get integer partitions
    vṖ   # Get all permutations
       f # Flatten the result

```

# Answer
> 5 votes
# , 22 bytes

```
repeat cat(rpois(9,9))

```

Try it online!

Outputs a random sequence of integers (realizations of the Poisson(9) distribution). They are printed in batches of 9, including some 0s (which is allowed by OP).

There is a theoretical guarantee that any finite sequence will almost surely be printed eventually.

# Answer
> 4 votes
# JavaScript (Node.js), ~~50~~ 49 bytes

```
for(x=0n;y=++x;)for(b=1n;y/=b;)console.log(y%++b)

```

Try it online!

Shortened by @l4m2.

This outputs the mixed-radix digital expansion of each positive integer *n*, where the radices used are 2, 3, 4, ... Any finite sequence of positive (or even nonnegative) integers will occur in the digits of some *n*.

# Answer
> 3 votes
# Python, 54 bytes

```
j=k=t=2
while t:=k%2>0!=print(t)or-~t:k=k//2or(j:=-~j)
```

Attempt This Online!

This version consistently outputs `True` for `1`.

### Old Python, 57 bytes

```
j=k=1
while[print(t:=len(f"{k&-k:b}"))]:k=k>>t or(j:=-~j)
```

Attempt This Online!

### Old Python, 63 bytes (@pxeger)

```
j=k=1
while 1:j+=k<1;k=k or j;t=len(f"{k&-k:b}");k>>=t;print(t)
```

Attempt This Online!

#### Old Python, 73 bytes

```
def f(j=1,k=1):
 while 1:j+=k<1;k=k or j;t=len(f"{k&-k:b}");k>>=t;yield t
```

Attempt This Online!

This goes through all positive integers and outputs for each the sequence of distances between `1`s in its binary representation.

For example:

```
1616 -> 11001010000 -> 5,2,3,1

```

# Python, 53 bytes

```
j=k=t=1
while k:=k//t or(j:=j+(t:=1)):print(k%t);t+=1
```

Attempt This Online!

Port of @Polichinelle's JS answer.

# Answer
> 2 votes
# 05AB1E, 7 bytes

```
∞Åœ€€œ˜

```

Outputs the infinite example sequence, but without an unquify of the permutations.

Try it online.

**Explanation:**

```
∞        # Push an infinite positive list: [1,2,3,...]
 Åœ      # Map each to a list of all possible lists of positive integers that sum
         # to that integer:
         #  [[[1]], [[1,1],[2]], [[1,1,1],[1,2],[3]], ...]
   €     # Map over each list:
    €    #  Map over each inner list:
     œ   #   Get all permutations of this list
         #    [[[[1]]], [[[1,1],[1,1]],[[2]]], [[[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1]],[[1,2],[2,1]],[[3]]], ...]
      ˜  # Flatten this list of lists
         #  [1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,1,3,...]
         # (after which the result is output implicitly)

```

# Answer
> 2 votes
# Pari/GP, 39 bytes

```
for(i=1,oo,[print(p[2])|p<-factor(i)~])

```

Try it online!

A port of @Command Master's 05AB1E answer.

---

## Pari/GP, 44 bytes (@Polichinelle)

```
for(i=9,oo,[print(d)|d<-digits(i,log(i)\1)])

```

Try it online!

---

## Pari/GP, 47 bytes

```
for(i=9,oo,[print(d)|d<-digits(i,log(i)^.9\1)])

```

When \\$i\\$ is larger enough, \\$b = \lfloor\log(i)^{0.9}\rfloor\\$ will satisfy \\$b^b \< i\\$. So the code will print the base-\\$b\\$ digits of a sequence of more than \\$b^b\\$ consecutive integers, which will contain all sequences of integers in \\$1,\dots,b-1\\$ with length \\$\<b\\$.

Try it online!

---

## Pari/GP, 50 bytes

```
for(i=2,oo,for(j=1,i^i,[print(d)|d<-digits(j,i)]))

```

Try it online!

---
Tags: code-golf, sequence, subsequence, open-ended-function
---