问:
Golf the xᵗʰ root of x
While bored in high-school (when I was half my current age...), I found that \$f(x) = x^{x^{-1}}\$ had some interesting properties, including e.g. that the maximum \$f\$ for \$0 ≤ x\$ is \$f(e)\$, and that the binding energy per nucleon of an isotope can be approximated as \$6 × f(x ÷ 21)\$...

Anyway, write the shortest function or program that calculates the xth root of x for any number in your language's domain.

Examples cases

For all languages

```<code>     -1   >       -1
   ¯0.2   >    -3125
   ¯0.5   >        4
    0.5   >     0.25
      1   >        1
      2   >    1.414
      e   >    1.444
      3   >    1.442
    100   >    1.047
  10000   >    1.001
</code>```

For languages that handle complex numbers

```<code>   -2   >        -0.7071i
    i   >            4.81
   2i   >    2.063-0.745i
 1+2i   >   1.820-0.1834i
 2+2i   >   1.575-0.1003i
</code>```

For languages that handle infinities

```<code>-1/∞   >   0    (or ∞ or ̃∞)
   0   >   0    (or 1 or ∞)
 1/∞   >   0
   ∞   >   1
  -∞   >   1
</code>```

For languages that handle both infinities and complex numbers

```<code> -∞-2i   >   1      (or ̃∞)
</code>```

 ̃∞ denotes directed infinity.

答:
Mumps, 14 Bytes

```<code>R I W I**(1/I)
</code>```

R reads from input into variable I, and the W (write) statement does the mathematical calculations.

I will warn you: the output will be ugly as there are no implied newlines in Mumps, and at least the way I read the challenge, the OP didn't require them. If you did want cleaner output, add 2 bytes and add a newline:

```<code>R I W !,I**(1/I)
</code>```

Title: Golf the xᵗʰ root of x

Body:
Mumps, 14 Bytes

R I W I**(1/I)

R reads from input into variable I, and the W (write) statement does the mathematical calculations.

I will warn you: the output will be ugly as there are no implied newlines in Mumps, and at least the way I read the challenge, the OP didn't require them. If you did want cleaner output, add 2 bytes and add a newline:

R I W !,I**(1/I)


问:
Tips for golfing in Racket / Scheme
What general tips do you have for golfing in Racket / Scheme? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Racket / Scheme (e.g. "remove comments" is not an answer).

I'm aware Scheme and Racket (formerly PLT Scheme) are technically different languages but are quite similar in many ways and much code (I suspect) will run mostly as intended in either. If your tip only applies to one of the aforementioned languages, note as such.

答:
In Racket, require forms can have multiple arguments.

```<code>(require net/url net/uri-codec)
</code>```

Is way shorter than

```<code>(require net/url)(require net/uri-codec)
</code>```

I don't know much about Scheme, but it doesn't seem to have a require builtin.

ContentLicense: CC BY-SA 3.0

Title: Tips for golfing in Racket / Scheme

Body:
In Racket, require forms can have multiple arguments.

(require net/url net/uri-codec)

Is way shorter than

(require net/url)(require net/uri-codec)

I don't know much about Scheme, but it doesn't seem to have a require builtin.


问:
De-Snakify a String
A regular string looks like this:

```<code>Hello,IAmAStringSnake!
</code>```

And a string snake looks something like this:

```<code>Hel
  l      rin
  o,IAmASt g
           S
       !ekan
</code>```

Your Task

String snakes are dangerous, so you must make a program that takes a string snake as input and outputs it as a regular string.

Specifications

Input can be a multiline string or an array of strings.

Each line of the input will be padded with spaces to form a rectangular grid.

Characters in the snake can only connect to adjacent characters above, below, left or right of them (just like in the game Snake). They cannot go diagonal.

The snake characters will never be adjacent to another part of the snake, only the connected characters.

The first character of the string is the end character with the shortest Manhattan distance from the top-left corner of the input grid (i.e. the minimum number of moves it would take for a snake to go directly from the end character to the top-left corner). Both ends will never have the same distance.

The string can contain any ASCII character between code points 33 and 126 inclusive (no spaces or newlines).

The string will be between 2 and 100 characters long.

Shortest code in bytes wins.

Test Cases

(Input grid, followed by the output string)

```<code>Hel
  l      rin
  o,IAmASt g
           S
       !ekan

Hello,IAmAStringSnake!

----------

Python

Python

----------

P  ngPu  Code
r  i  z  d  G
o  m  z  n  o
gram  lesA  lf

ProgrammingPuzzlesAndCodeGolf

----------

   ~ zyx tsr XWVUTSR
   }|{ wvu q Y     Q
!          p Z `ab P
"#$ 6789:; o [ _ c O
  % 5    < n \]^ d N
('& 432  = m     e M
)     1  > lkjihgf L
*+,-./0  ?         K
         @ABCDEFGHIJ

!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

----------

  tSyrep
  r    p
  in Sli
   g    Sile
   Snakes  n
Ser      ylt
a eh   ilS
fe w   t
   emo h
     Sre

SlipperyStringSnakesSilentlySlitherSomewhereSafe
</code>```

答:
Python (2 and 3), 640 624 604 583 575 561 546 538 bytes

I'm still a golfing n00b so this is a bit large.

Edit: Thanks to @porglezomp for the suggestions! I didn't remove all the 'and' operators as that would break Python 3.

Edit2: Thanks to @Aleksi Torhamo for the comment about isspace(). The resulting reduction compensates for the bugfix I put in. Also thanks to anonymous for the syntax highlighting!

Edit3: Thanks to @mbomb007 for a few additional bytes.

import sys;s=sys.stdin.read().split('\n');m={};q=[];o=len;j=o(s);r=range;g='!'
for y in r(j):
 v=s[y];f=o(v);d=y+1
 for x in r(f):
  n=[];a=n.append;U=s[y-1]
  if v[x]>=g:j>=y>0==(U[x]<g)<=x<o(U)and a((x,y-1));j>y>=0==(v[x-1]<g)<x<=f and a((x-1,y));j>y>-1<x+1<f>(v[x+1]<g)<1and a((x+1,y));j>d>-1<x<o(s[d])>(s[d][x]<g)<1and a((x,d));m[x,y]=[v[x],n];o(n)-1or q.append((x,y))
t=min(q,key=sum);w=sys.stdout.write;w(m[t][0]);c=m[t][1][0]
while o(m[c][1])>1:
 b=m[c][1];w(m[c][0])
 for k in r(o(b)):
  if b[k]!=t:t=c;c=b[k];break
print(m[c][0])
```

<p>And here's my pre-golf version</p>

<pre class="lang-python prettyprint-override"><code>import sys

lines = sys.stdin.read().split('\n')
startend = []
mydict = {}
for y in range( 0, len(lines)):
  for x in range( 0, len(lines[y])):
    if not lines[y][x].isspace():
      neighbors = []
      if x>=0 and x<len(lines[y-1]) and y-1>=0 and y-1<len(lines):
        if not lines[y-1][x].isspace():
          neighbors.append( (x,y-1) )
      if x-1>=0 and x-1<len(lines[y]) and y>=0 and y<len(lines):
        if not lines[y][x-1].isspace():
          neighbors.append( (x-1,y) )
      if x+1>=0 and x+1<len(lines[y]) and y>=0 and y<len(lines):
        if not lines[y][x+1].isspace():
          neighbors.append( (x+1,y) )
      if x>=0 and x<len(lines[y+1]) and y+1>=0 and y+1<len(lines):
        if not lines[y+1][x].isspace():
          neighbors.append( (x,y+1) )
      mydict[(x,y)] = [ lines[y][x], neighbors ]

      if len( neighbors ) == 1:
        startend.append( (x,y) )

startend.sort( key=lambda x : x[0]*x[0] + x[1]*x[1] )

last = startend[0]
sys.stdout.write( mydict[ last ][0] )
current = mydict[last][1][0]
while len( mydict[current][1] ) > 1:
  sys.stdout.write( mydict[current][0] )
  for k in range( 0, len( mydict[current][1] ) ):
    if mydict[current][1][k] != last:
      last = current
      current = mydict[current][1][k]
      break

print(mydict[current][0])
</code>```

Title: De-Snakify a String

Body:
Python (2 and 3), 640 624 604 583 575 561 546 538 bytes

I'm still a golfing n00b so this is a bit large.

Edit: Thanks to @porglezomp for the suggestions! I didn't remove all the 'and' operators as that would break Python 3.

Edit2: Thanks to @Aleksi Torhamo for the comment about isspace(). The resulting reduction compensates for the bugfix I put in. Also thanks to anonymous for the syntax highlighting!

Edit3: Thanks to @mbomb007 for a few additional bytes.

import sys;s=sys.stdin.read().split('\n');m={};q=[];o=len;j=o(s);r=range;g='!'
for y in r(j):
 v=s[y];f=o(v);d=y+1
 for x in r(f):
  n=[];a=n.append;U=s[y-1]
  if v[x]>=g:j>=y>0==(U[x]<g)<=x<o(U)and a((x,y-1));j>y>=0==(v[x-1]<g)<x<=f and a((x-1,y));j>y>-1<x+1<f>(v[x+1]<g)<1and a((x+1,y));j>d>-1<x<o(s[d])>(s[d][x]<g)<1and a((x,d));m[x,y]=[v[x],n];o(n)-1or q.append((x,y))
t=min(q,key=sum);w=sys.stdout.write;w(m[t][0]);c=m[t][1][0]
while o(m[c][1])>1:
 b=m[c][1];w(m[c][0])
 for k in r(o(b)):
  if b[k]!=t:t=c;c=b[k];break
print(m[c][0])

And here's my pre-golf version

import sys

lines = sys.stdin.read().split('\n')
startend = []
mydict = {}
for y in range( 0, len(lines)):
  for x in range( 0, len(lines[y])):
    if not lines[y][x].isspace():
      neighbors = []
      if x>=0 and x<len(lines[y-1]) and y-1>=0 and y-1<len(lines):
        if not lines[y-1][x].isspace():
          neighbors.append( (x,y-1) )
      if x-1>=0 and x-1<len(lines[y]) and y>=0 and y<len(lines):
        if not lines[y][x-1].isspace():
          neighbors.append( (x-1,y) )
      if x+1>=0 and x+1<len(lines[y]) and y>=0 and y<len(lines):
        if not lines[y][x+1].isspace():
          neighbors.append( (x+1,y) )
      if x>=0 and x<len(lines[y+1]) and y+1>=0 and y+1<len(lines):
        if not lines[y+1][x].isspace():
          neighbors.append( (x,y+1) )
      mydict[(x,y)] = [ lines[y][x], neighbors ]

      if len( neighbors ) == 1:
        startend.append( (x,y) )

startend.sort( key=lambda x : x[0]*x[0] + x[1]*x[1] )

last = startend[0]
sys.stdout.write( mydict[ last ][0] )
current = mydict[last][1][0]
while len( mydict[current][1] ) > 1:
  sys.stdout.write( mydict[current][0] )
  for k in range( 0, len( mydict[current][1] ) ):
    if mydict[current][1][k] != last:
      last = current
      current = mydict[current][1][k]
      break

print(mydict[current][0])


问:
Find the first word starting with each letter
Given a string, find the first word starting with each letter (case insensitive).

Sample

Using Ferulas flourish in gorgeous gardens. as input:

```<code>"Ferulas flourish in gorgeous gardens."
 ^^^^^^^          ^^ ^^^^^^^^
 |                |  |
 |                |  --> is the first word starting with `g`
 |                --> is the first word starting with `i`
 --> is the first word starting with `f`
</code>```

Then, the output for this sample should be the matched words joined by one single space:

```<code>"Ferulas in gorgeous"
</code>```

Challenge

Both input and output must be a string representation, or the closest alternative in your language.

Program or function allowed.

You can consider a word being at least one of: lowercase or uppercase letters, digits, underscore.

This is code-golf, shortest answer in bytes wins.

Another samples:

```<code>input: "Take all first words for each letter... this is a test"
output: "Take all first words each letter is"
</code>```

```<code>input: "Look ^_^ .... There are 3 little dogs :)"
output: "Look _ There are 3 dogs"
</code>```

```<code>input: "...maybe some day 1 plus 2 plus 20 could result in 3"
output: "maybe some day 1 plus 2 could result in 3"
</code>```

答:
Python, 103 bytes

```<code>import re
lambda s,d=[]:[w for w in re.findall("\w+",s)if(d.append(w.lower()[0])or d[-1])not in d[:-1]]
</code>```

Body:
Python, 103 bytes

import re
lambda s,d=[]:[w for w in re.findall("\w+",s)if(d.append(w.lower()[0])or d[-1])not in d[:-1]]


问:
Showcase of Languages

Notes

This thread is open and unlocked only because the community decided to make an exception. Please do not use this question as evidence that you can ask similar questions here. Please do not create additional showcase questions.

This is no longer a popularity-contest, nor are snippet lengths limited by the vote tally. If you know this thread from before, please make sure you familiarize yourself with the changes.

This thread is dedicated to showing off interesting, useful, obscure, and/or unique features your favorite programming languages have to offer. This is neither a challenge nor a competition, but a collaboration effort to showcase as many programming languages as possible as well as possible.

How this works

All answers should include the name of the programming language at the top of the post, prefixed by a #.

Answers may contain one (and only one) factoid, i.e., a couple of sentences without code that describe the language.

Aside from the factoid, answers should consist of snippets of code, which can (but don't have to be) programs or functions.

The snippets do not need to be related. In fact, snippets that are too related may be redundant.

Since this is not a contest, all programming languages are welcome, whenever they were created.

Answers that contain more than a handful of code snippets should use a Stack Snippet to collapse everything except the factoid and one of the snippets.

Whenever possible, there should be only one answer per programming language. This is a community wiki, so feel free to add snippets to any answer, even if you haven't created it yourself. There is a Stack Snippet for compressing posts, which should mitigate the effect of the 30,000 character limit.

Answers that predate these guidelines should be edited. Please help updating them as needed.

Current answers, sorted alphabetically by language name

$.ajax({type:"GET",url:"https://api.stackexchange.com/2.2/questions/44680/answers?site=codegolf&filter=withbody",success:function(data){for(var i=0;i<data.items.length;i++){var temp=document.createElement('p');temp.innerHTML = data.items[i].body.split("\n")[0];$('#list').append('
' + temp.innerText || temp.textContent + '');}}})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><base href="http://codegolf.stackexchange.com"><ul id="list"></ul></code>```

答:
MIPS

Factoid: Though many see MIPS's heyday is in the past with ARM taking over the market, the classic RISC design often taught in universities continues to be widely used in embedded devices and newer small devices in Asian markets.

Length 1

Being assembly, not much can be done in one instruction. That being said, MIPS does offer an interesting native (not psuedo-) instruction: BGEZAL, Branch on greater than or equal to zero and link.

```<code>Hex code      Syntax
0x05110000    bgezal $t0, label
</code>```

Title: Showcase of Languages

Body:
MIPS

Factoid: Though many see MIPS's heyday is in the past with ARM taking over the market, the classic RISC design often taught in universities continues to be widely used in embedded devices and newer small devices in Asian markets.

Length 1

Being assembly, not much can be done in one instruction. That being said, MIPS does offer an interesting native (not psuedo-) instruction: BGEZAL, Branch on greater than or equal to zero and link.

Hex code      Syntax
0x05110000    bgezal $t0, label


问:
KOTH: Everybody loves tokens
In this game two players compete to eat the most points worth of tokens, but there's a twist! Eating multiple tokens in a row of the same color gives an ever-growing bonus, but watch out, or your opponent will thwart your plans by eating the tokens you want before you can!

Rules:

1 versus 1

n by n board (random size between 5x5 and 15x15)

You and your opponent will spawn in the same random cell

Throughout the board will be randomly generated numbers in some cells ranging in value from 1-3

2 * (the width of the board) tokens will be generated, but there can be overrides, so there may be fewer by chance.

Each number will be one of 3 colors: Red, Green, or Blue, in hex RGB format

Each round, player 1 moves and the board is updated, then player 2 moves, and the board is updated. So each player can effectively tell what move the previous player made based on the change in the board state. This continues until the game ends, as described later.

You have 6 possible actions for a turn: UP, RIGHT, DOWN, LEFT, EAT, and PASS

The 4 move commands are self-explanatory, and you CAN pass your turn. If you return a nonsensical move, we will assume you meant pass. If you try to move off the edge of the board, you will not move. The edges don't wrap.

EAT consumes the number you are currently in the same space as

You gain as many points as the number you consume

If you eat 2 numbers in a row of the same color, you get +1

If you eat 3 numbers in a row of the same color, you get +2

If you eat m numbers in a row of the same color, you get +(m-1)

These bonuses are added cumulatively, so getting m numbers in a row leads to m*(m-1)/2 in total bonus by the time you eat a different color.

Game end conditions:

All numbers are consumed

4 * (the width of the board) turns have gone by with no effective eating (just saying “EAT” with no token where you are doesn't count) occurring by either player (any token is reachable in 2 * (the width) moves, so this bound will only be surpassed if both players have no single target token in mind)

Your AI should take less than a second to make a move, else PASS will be assumed as your choice.

The tournament will be round robin with a large number of rounds, say 100 or 1000. A random board is generated, and each ordered pair of different players is run on that board. After the tournament completes we will rank people by their total score. So even if you are player 2 for a game, your goal is still to get as many points as possible.

AI Submission: The language my controller supports is Javascript. Multiple submissions are allowed. Everyone submits a constructor for an object like this:

```<code>function (player1) {
    this.yourMove = function (b) {
        return "MOVE";
    }
}
</code>```

The input player1 is a boolean saying whether you are player 1 or not.
Your constructor must have the yourMove function, but it can have
any number of additional functions or values as well. Don't define any
global variables, just put them as variables on your object. A new version
of your object will be created at the beginning of each match, and
yourMove will be called on it, with the current board as input, on each of your turns, and should return a valid move.

b, the input to yourMove, is a copy of the current board, here are the
constructors, with input examples, though you can't call them yourself:

```<code>function token(color, points) {
    this.color = color; //"#FF0000"
    this.points = points; //5
}

function player(pos, score, colorBonus, lastColor) {
    this.pos = pos; //[5, 5]
    this.score = score; //9
    this.colorBonus = colorBonus; //i.e. 2 if you just ate 3 blue tokens in a row
                                  //0 if you just ate two different colors.
    this.lastColor = lastColor; //"#00FF00", is "#000000" at start
}

function board(player1, player2, tokens) {
    this.player1 = player1; //new player([5, 5], 9, 2, "#00FF00")
    this.player2 = player2; //new player([5, 5], 9, 2, "#00FF00")
    this.tokens = tokens; //[[new token("#0000FF", 5), false],
                      // [new token("#0000FF", 5), false]]
}
</code>```

The token array has "false" for any empty squares, and tokens[a][b] is
the token at x = a, y = b, numbered starting from the upper-left corner.

Controller:
Here's a link to the controller in GitHub. It's an html file that you can run to see how the game and the round-robin works, and it comes with two AIs, a random one that moves in a random direction each turn but eats tokens at its position, and a naive algorithm that goes for the nearest token that gives the most points. I will add in each AI as it is submitted.

Below is a snippet that allows you to run the controller on the default AI.
Current AIs:

KindaRandomAI

NaiveAI

MirrorBot

HungryBot

<!DOCTYPE html>

  <canvas id="myCanvas" width="700" height="600" style="border:1px solid #c3c3c3;">
    Your browser does not support the HTML5 canvas tag.
  </canvas>

```

答:
PATH bot

Acronym stands for Pathfinding And Tree Heuristics Bot

EDIT: As of now, here are the rankings for the AIs, with the points

HungryBot (6422)

PATH bot (4591)

NaiveAI (3811)

KindaRandomAI (618)

MirrorBot (193)

LazyBot (25)

Link to complete controller on github

Description: Like NaiveAI, this bot finds the nearest token that will give it the most points. However, it also simulates the outcomes of each of its moves, up to 6 times.

Rationale: Because NaiveAI is already pretty good, I though I would make it better. Without looking at the code first (big mistake).

Beats: All except HungryBot

Looses to: None except HungryBot

Problems:

Cannot simulate increased streak

Hangs while calculating best token

<s>Can teleport</s>

I still don't know why it was teleporting, but I fixed it. Old video here: https://youtu.be/BIhSKycF9iA

Full code:

```<code>pathBot = function (player1)
{
    this.pathNode = function(pos,ppt,parents,par)
    {
        this.pos = pos;this.ppt = ppt;this.parents = parents;this.par=par;
        this.childs=[];
    }
    this.addChildren = function (pn,children)
    {
        pn.childs=[];
        for(var i=0; i<children.length; i=i+1)
        {
            if(pn.parents.indexOf(children[i].pos)==-1&&pn.pos!=children[i].pos)
                pn.childs.push(
                    new this.pathNode(
                        children[i].pos,
                        children[i].ppt*pn.ppt,
                        pn.parents.concat([pn.pos]),
                        pn
                    )
                );
        }
    }
    this.orderTokensByPPT = function(b,pos){
        var tokens = [];
        for(var y=0; y<b.tokens.length; y=y+1)
        {
            for(var x=0; x<b.tokens[y].length; x=x+1)
            {
                var tok = b.tokens[y][x];
                if(tok)
                {
                    tokens.push(
                        new this.pathNode(
                            [y,x],
                            (tok.points+(tok.color==this.color ? this.streak : 0)) / this.lenOfMovesTo(pos,[y,x]),
                            [],
                            undefined
                        )
                    );
                }
            }
        }
        tokens.sort(function(a,b){
            return b.ppt - a.ppt;
        });
        return tokens;
    }
    this.lenOfMovesTo = function(cur,pos)
    {
        return Math.abs(cur[0]-pos[0])+Math.abs(cur[1]-pos[1])+1;
    }
    this.startAndGoalToCommand = function (start, goal) {
        var diff = [goal[0] - start[0], goal[1] - start[1]];
        if (diff[0] > 0) { return "RIGHT"; }
        else if (diff[1] > 0) { return "DOWN"; }
        else if (diff[1] < 0) { return "UP"; }
        else if (diff[0] < 0) { return "LEFT"; }
        else { return "EAT"; }
    }
    this.color = 0;
    this.streak = 0;
    this.eatTok = function(b)
    {
        if(b.tokens[this.me.pos[0]][this.me.pos[1]].color==this.color)
        {
            this.streak++;
        }
        else{
            this.streak = 0;
            this.color = b.tokens[this.me.pos[0]][this.me.pos[1]].color;
        }
        this.bestToken = false;
        return "EAT";
    }

    this.recurLen = 6;
    this.include = 4;
    this.recurDown = function(b,pn,level)
    {
        if(level==0) return pn;
        this.addChildren(pn,this.orderTokensByPPT(b,pn.pos));
        var newChilds = [];
        for(var i=0; i<pn.childs.length&&i<this.include; i=i+1)
        {
            newChilds.push(this.recurDown(b,pn.childs[i],level-1));
        }
        pn.childs = newChilds;
        return pn;
    }
    this.findMax = function(pn)
    {
        if(pn.childs)
        {
            var maxList = [];
            for(var i=0; i<pn.childs.length; i=i+1)
                maxList.push(this.findMax(pn.childs[i]));
            maxList.sort(
                function(a,b)
                {
                    return b.ppt-a.ppt;
                }
            );
            return maxList[0];
        }
        return pn;
    }
    this.findMaxList = function(pnList)
    {
        for(var i=0; i<pnList.lenght; i=i+1)
        {
            pnList[i] = this.findMax(pnList[i]);
        }
        pnList.sort(function(a,b){return b.ppt-a.ppt;});
        return pnList[0];
    }
    this.bestToken=false;
    this.yourMove = function(b){
        this.op = player1 ? b.player2 : b.player1;
        this.me = player1 ? b.player1 : b.player2;
        if(this.bestToken)
        {
            if(b.tokens[this.bestToken.pos[0]][this.bestToken.pos[1]]==undefined)
                this.bestToken = false;
        }
        if(!this.bestToken)
        {
            var paths = this.orderTokensByPPT(b,this.me.pos);
            for(var i=0; i<paths.length; i++)
            {
                paths[i] = this.recurDown(b,paths[i],this.recurLen);
            }
            var max = this.findMaxList(paths);
            while(max.par)
            {
                max = max.par;
            }
            this.bestToken = max;
        }
        var move = this.startAndGoalToCommand(this.me.pos,this.bestToken.pos);
        if(move=="EAT") return this.eatTok(b);
        else return move;
    }
}
</code>```

Title: KOTH: Everybody loves tokens

Body:
PATH bot

Acronym stands for Pathfinding And Tree Heuristics Bot

EDIT: As of now, here are the rankings for the AIs, with the points

HungryBot (6422)

PATH bot (4591)

NaiveAI (3811)

KindaRandomAI (618)

MirrorBot (193)

LazyBot (25)

Link to complete controller on github

Description: Like NaiveAI, this bot finds the nearest token that will give it the most points. However, it also simulates the outcomes of each of its moves, up to 6 times.

Rationale: Because NaiveAI is already pretty good, I though I would make it better. Without looking at the code first (big mistake).

Beats: All except HungryBot

Looses to: None except HungryBot

Problems:

Cannot simulate increased streak

Hangs while calculating best token

<s>Can teleport</s>

I still don't know why it was teleporting, but I fixed it. Old video here: https://youtu.be/BIhSKycF9iA

Full code:

pathBot = function (player1)
{
    this.pathNode = function(pos,ppt,parents,par)
    {
        this.pos = pos;this.ppt = ppt;this.parents = parents;this.par=par;
        this.childs=[];
    }
    this.addChildren = function (pn,children)
    {
        pn.childs=[];
        for(var i=0; i<children.length; i=i+1)
        {
            if(pn.parents.indexOf(children[i].pos)==-1&&pn.pos!=children[i].pos)
                pn.childs.push(
                    new this.pathNode(
                        children[i].pos,
                        children[i].ppt*pn.ppt,
                        pn.parents.concat([pn.pos]),
                        pn
                    )
                );
        }
    }
    this.orderTokensByPPT = function(b,pos){
        var tokens = [];
        for(var y=0; y<b.tokens.length; y=y+1)
        {
            for(var x=0; x<b.tokens[y].length; x=x+1)
            {
                var tok = b.tokens[y][x];
                if(tok)
                {
                    tokens.push(
                        new this.pathNode(
                            [y,x],
                            (tok.points+(tok.color==this.color ? this.streak : 0)) / this.lenOfMovesTo(pos,[y,x]),
                            [],
                            undefined
                        )
                    );
                }
            }
        }
        tokens.sort(function(a,b){
            return b.ppt - a.ppt;
        });
        return tokens;
    }
    this.lenOfMovesTo = function(cur,pos)
    {
        return Math.abs(cur[0]-pos[0])+Math.abs(cur[1]-pos[1])+1;
    }
    this.startAndGoalToCommand = function (start, goal) {
        var diff = [goal[0] - start[0], goal[1] - start[1]];
        if (diff[0] > 0) { return "RIGHT"; }
        else if (diff[1] > 0) { return "DOWN"; }
        else if (diff[1] < 0) { return "UP"; }
        else if (diff[0] < 0) { return "LEFT"; }
        else { return "EAT"; }
    }
    this.color = 0;
    this.streak = 0;
    this.eatTok = function(b)
    {
        if(b.tokens[this.me.pos[0]][this.me.pos[1]].color==this.color)
        {
            this.streak++;
        }
        else{
            this.streak = 0;
            this.color = b.tokens[this.me.pos[0]][this.me.pos[1]].color;
        }
        this.bestToken = false;
        return "EAT";
    }

    this.recurLen = 6;
    this.include = 4;
    this.recurDown = function(b,pn,level)
    {
        if(level==0) return pn;
        this.addChildren(pn,this.orderTokensByPPT(b,pn.pos));
        var newChilds = [];
        for(var i=0; i<pn.childs.length&&i<this.include; i=i+1)
        {
            newChilds.push(this.recurDown(b,pn.childs[i],level-1));
        }
        pn.childs = newChilds;
        return pn;
    }
    this.findMax = function(pn)
    {
        if(pn.childs)
        {
            var maxList = [];
            for(var i=0; i<pn.childs.length; i=i+1)
                maxList.push(this.findMax(pn.childs[i]));
            maxList.sort(
                function(a,b)
                {
                    return b.ppt-a.ppt;
                }
            );
            return maxList[0];
        }
        return pn;
    }
    this.findMaxList = function(pnList)
    {
        for(var i=0; i<pnList.lenght; i=i+1)
        {
            pnList[i] = this.findMax(pnList[i]);
        }
        pnList.sort(function(a,b){return b.ppt-a.ppt;});
        return pnList[0];
    }
    this.bestToken=false;
    this.yourMove = function(b){
        this.op = player1 ? b.player2 : b.player1;
        this.me = player1 ? b.player1 : b.player2;
        if(this.bestToken)
        {
            if(b.tokens[this.bestToken.pos[0]][this.bestToken.pos[1]]==undefined)
                this.bestToken = false;
        }
        if(!this.bestToken)
        {
            var paths = this.orderTokensByPPT(b,this.me.pos);
            for(var i=0; i<paths.length; i++)
            {
                paths[i] = this.recurDown(b,paths[i],this.recurLen);
            }
            var max = this.findMaxList(paths);
            while(max.par)
            {
                max = max.par;
            }
            this.bestToken = max;
        }
        var move = this.startAndGoalToCommand(this.me.pos,this.bestToken.pos);
        if(move=="EAT") return this.eatTok(b);
        else return move;
    }
}


答:
LazyBot

Only eats something if he spawns on it.
This has no chance to win, but the challenge didn't have one of these, so why not.

```<code>lazyBot = function (player1) {
    this.yourMove = function(b) {
        return "EAT";
    }
}
</code>```

Title: KOTH: Everybody loves tokens

Body:
In this game two players compete to eat the most points worth of tokens, but there's a twist! Eating multiple tokens in a row of the same color gives an ever-growing bonus, but watch out, or your opponent will thwart your plans by eating the tokens you want before you can!

Rules:

1 versus 1

n by n board (random size between 5x5 and 15x15)

You and your opponent will spawn in the same random cell

Throughout the board will be randomly generated numbers in some cells ranging in value from 1-3

2 * (the width of the board) tokens will be generated, but there can be overrides, so there may be fewer by chance.

Each number will be one of 3 colors: Red, Green, or Blue, in hex RGB format

Each round, player 1 moves and the board is updated, then player 2 moves, and the board is updated. So each player can effectively tell what move the previous player made based on the change in the board state. This continues until the game ends, as described later.

You have 6 possible actions for a turn: UP, RIGHT, DOWN, LEFT, EAT, and PASS

The 4 move commands are self-explanatory, and you CAN pass your turn. If you return a nonsensical move, we will assume you meant pass. If you try to move off the edge of the board, you will not move. The edges don't wrap.

EAT consumes the number you are currently in the same space as

You gain as many points as the number you consume

If you eat 2 numbers in a row of the same color, you get +1

If you eat 3 numbers in a row of the same color, you get +2

If you eat m numbers in a row of the same color, you get +(m-1)

These bonuses are added cumulatively, so getting m numbers in a row leads to m*(m-1)/2 in total bonus by the time you eat a different color.

Game end conditions:

All numbers are consumed

4 * (the width of the board) turns have gone by with no effective eating (just saying “EAT” with no token where you are doesn't count) occurring by either player (any token is reachable in 2 * (the width) moves, so this bound will only be surpassed if both players have no single target token in mind)

Your AI should take less than a second to make a move, else PASS will be assumed as your choice.

The tournament will be round robin with a large number of rounds, say 100 or 1000. A random board is generated, and each ordered pair of different players is run on that board. After the tournament completes we will rank people by their total score. So even if you are player 2 for a game, your goal is still to get as many points as possible.

AI Submission: The language my controller supports is Javascript. Multiple submissions are allowed. Everyone submits a constructor for an object like this:

```<code>function (player1) {
    this.yourMove = function (b) {
        return "MOVE";
    }
}
</code>```

The input player1 is a boolean saying whether you are player 1 or not.
Your constructor must have the yourMove function, but it can have
any number of additional functions or values as well. Don't define any
global variables, just put them as variables on your object. A new version
of your object will be created at the beginning of each match, and
yourMove will be called on it, with the current board as input, on each of your turns, and should return a valid move.

b, the input to yourMove, is a copy of the current board, here are the
constructors, with input examples, though you can't call them yourself:

```<code>function token(color, points) {
    this.color = color; //"#FF0000"
    this.points = points; //5
}

function player(pos, score, colorBonus, lastColor) {
    this.pos = pos; //[5, 5]
    this.score = score; //9
    this.colorBonus = colorBonus; //i.e. 2 if you just ate 3 blue tokens in a row
                                  //0 if you just ate two different colors.
    this.lastColor = lastColor; //"#00FF00", is "#000000" at start
}

function board(player1, player2, tokens) {
    this.player1 = player1; //new player([5, 5], 9, 2, "#00FF00")
    this.player2 = player2; //new player([5, 5], 9, 2, "#00FF00")
    this.tokens = tokens; //[[new token("#0000FF", 5), false],
                      // [new token("#0000FF", 5), false]]
}
</code>```

The token array has "false" for any empty squares, and tokens[a][b] is
the token at x = a, y = b, numbered starting from the upper-left corner.

Controller:
Here's a link to the controller in GitHub. It's an html file that you can run to see how the game and the round-robin works, and it comes with two AIs, a random one that moves in a random direction each turn but eats tokens at its position, and a naive algorithm that goes for the nearest token that gives the most points. I will add in each AI as it is submitted.

Below is a snippet that allows you to run the controller on the default AI.
Current AIs:

KindaRandomAI

NaiveAI

MirrorBot

HungryBot

<!DOCTYPE html>

  <canvas id="myCanvas" width="700" height="600" style="border:1px solid #c3c3c3;">
    Your browser does not support the HTML5 canvas tag.
  </canvas>

```

Body:
LazyBot

Only eats something if he spawns on it.
This has no chance to win, but the challenge didn't have one of these, so why not.

lazyBot = function (player1) {
    this.yourMove = function(b) {
        return "EAT";
    }
}


问:
Average an image
Here is an image:

```<code>%%%%%%%%%%%%%
% Hello,    %
%    world! %
%%%%%%%%%%%%%
</code>```

But it is too confusing for our undersized brains to compute. So we average it like this:

Split it into 2 x 2 sections. If the picture ends before a section is complete, imagine that there are spaces there.

Average the values of the ASCII characters in each section.

Round this average and convert it to an ASCII character.

Finally, replace all characters in the section to the average character.

Repeat this for all sections.

So the average of the image above looks like this:

```<code>$$>>II99######
$$>>II99######
$$##88KKGG####
$$##88KKGG####
</code>```

Your task: Write  a program that takes an ASCII image as input and outputs its average.

Note Integers are rounded by function floor(x+0.5) or similar function - in other words, round halves upwards.

Title: Average an image

Body:
Ruby, <s>235</s> 230 bytes

->i{i=i.split($/).map{|s|s.bytes+[s.size%2>0?32:0]}
w=i[0].size;h=i.size;h+=h%2;r=[[]]*h
(h/2).times{|y|y*=2
(w/2).times{|x|x*=2
c=((i[y][x,2]+(i[y+1]||[32]*w)[x,2]).inject(:+)/4.0).round.chr
r[y+1]=r[y]+=[c,c]}}
r.map(&:join)*$/}


问:
"Stair-ify" a string
You must write a program or function that creates a "stair-ified" string. Here is how you "stair-ify" a string:

For each character in the string:

If the character is an upper or lowercase vowel, not including 'y', output it then move the rest of the string up a column.

If the character is a space or a tab, output it then move the rest of the string down a colum.

If the character is neither, output it normally.

IO can be in any reasonable format. The input will not contain any newlines. If you want, you can remove any trailing whitespace.

If you choose to return the string, rather than printing it, please also include a short program that will print your string so that it can be visualized. This is not mandatory, nor will it go towards your byte-count. This is just a convenience for users who don't understand golf or esolangs (like me) to be able to verify output or tinker with the code.

Sample IO:

Output for "bcdef ghijkl":

```<code>    f    jkl
bcde  ghi
</code>```

Output for "Programming Puzzles And Code-Golf":

```<code>                               lf
                            -Go
                  s  nd   de
         ng   zzle  A   Co
      mmi   Pu
   gra
Pro
</code>```

Output for "Abcdefghijklmnopqrstuvwxyz":

```<code>                     vwxyz
               pqrstu
         jklmno
     fghi
 bcde
A
</code>```

As usual, this is code-golf, so shortest answer in bytes wins.

答:
JavaScript (Firefox 30-57), 151 bytes

```<code>s=>[...s].map((c,i)=>r[c<'!'?n++:/[AEIOU]/i.test(c)?n--:n][i]=c,n=s.length,r=[for(_ of s+s)[]])&&[for(a of r)if(s=[for(c of a)c||' '].join``)s].join`\n`
</code>```

Where \n represents the literal newline character.

Title: "Stair-ify" a string

Body:
JavaScript (Firefox 30-57), 151 bytes

s=>[...s].map((c,i)=>r[c<'!'?n++:/[AEIOU]/i.test(c)?n--:n][i]=c,n=s.length,r=[for(_ of s+s)[]])&&[for(a of r)if(s=[for(c of a)c||' '].join``)s].join`\n`

Where \n represents the literal newline character.


答:
Python 2, 141 137 bytes

```<code>def S(s,l=[0]):
 for c in s:l+=[l[-1]-(c in"aeiouAEIOU")+(c<"!")]
 for h in sorted(set(l)):print"".join([" ",c][i==h]for i,c in zip(l,s))
</code>```

Title: "Stair-ify" a string

Body:
You must write a program or function that creates a "stair-ified" string. Here is how you "stair-ify" a string:

For each character in the string:

If the character is an upper or lowercase vowel, not including 'y', output it then move the rest of the string up a column.

If the character is a space or a tab, output it then move the rest of the string down a colum.

If the character is neither, output it normally.

IO can be in any reasonable format. The input will not contain any newlines. If you want, you can remove any trailing whitespace.

If you choose to return the string, rather than printing it, please also include a short program that will print your string so that it can be visualized. This is not mandatory, nor will it go towards your byte-count. This is just a convenience for users who don't understand golf or esolangs (like me) to be able to verify output or tinker with the code.

Sample IO:

Output for "bcdef ghijkl":

```<code>    f    jkl
bcde  ghi
</code>```

Output for "Programming Puzzles And Code-Golf":

```<code>                               lf
                            -Go
                  s  nd   de
         ng   zzle  A   Co
      mmi   Pu
   gra
Pro
</code>```

Output for "Abcdefghijklmnopqrstuvwxyz":

```<code>                     vwxyz
               pqrstu
         jklmno
     fghi
 bcde
A
</code>```

As usual, this is code-golf, so shortest answer in bytes wins.

Body:
Python 2, 141 137 bytes

def S(s,l=[0]):
 for c in s:l+=[l[-1]-(c in"aeiouAEIOU")+(c<"!")]
 for h in sorted(set(l)):print"".join([" ",c][i==h]for i,c in zip(l,s))


答:
Pyth, 63 bytes

```<code>V_Q aY?}rN0"aeiou"=hZ?}N"     "=tZZ;Jh.mbYKh.MZYjC.b++*d+JNY*dK_YQ
                         ^^^^^
                         |||||
                         |tabs
                        space
</code>```

The spaces in the middle is actually a single tab character, but StackExchange renders it as four spaces.

Try it online!

Title: "Stair-ify" a string

Body:
Pyth, 63 bytes

V_Q aY?}rN0"aeiou"=hZ?}N"     "=tZZ;Jh.mbYKh.MZYjC.b++*d+JNY*dK_YQ
                         ^^^^^
                         |||||
                         |tabs
                        space

The spaces in the middle is actually a single tab character, but StackExchange renders it as four spaces.

Try it online!


问:
Find the program that prints this integer sequence (Cops' thread)
This is the cops' thread. The robbers' thread goes here.

The last cops-and-robbers thread was already 4 months ago.

The cop's task

The cop's task is to write a program/function that takes a positive (or non-negative) integer and outputs/returns another integer.

The cop must state it if the program is intolerant towards zero.

The cop will provide at least 2 sample inputs/outputs.

For example, if I have decided to write the Fibonacci sequence, I would write this in my answer:

```
a(0) returns 0
a(3) returns 2
```

The number of examples is up to the cop's discretion.

However, the sequence must actually exist in the On-Line Encyclopedia of Integer Sequences®, so no pseudo-random number generator for you. :(

The cop can hide as many characters as is so wished.

For example, if my program is:

```<code>function a(n)
    if n>2 then
        return n
    else
        return a(n-1) + a(n-2)
    end
end
</code>```

Then I would hide these characters as I want:

```<code>function a(n)
    if ### then
        ########
    else
        ######################
    end
end
</code>```

The robber's task

is obviously to find the original source code.

However, any proposed source code that produces the same set of output also counts as valid, as long as it is also found in OEIS.

Tips for the cops

<s>The search function in the OEIS only works for consecutive terms, so if you want to hide your sequence, then just leave a hole anywhere.</s>

Apparently there is no way to hide the sequence. Put this in mind when you choose the sequence.

Your score is the number of bytes in your code.

The winner will be the submission with the lowest score that hasn't been cracked in 7 days.

Only submissions that are posted in 2016 April are eligible for the win. Submissions that are posted later than this are welcome, but cannot win.

In order to claim the win you need to reveal the full code and the OEIS sequence (after 7 days).

Your post should be formatted like this (NN is the number of characters):

Lua, 98 bytes

Output:

```<code>a(0) returns 0
a(3) returns 2
</code>```

Code (# marks unrevealed characters):

```<code>function a(n)
    if ### then
        ########
    else
        ######################
    end
end
</code>```

If the code is cracked, insert [Cracked](link to cracker) in the header.
If the submission is safe, insert "Safe" in the header and reveal the full code in your answer. Only answers that have revealed the full code will be eligible for the win.

答:
Jolf, 5 bytes, cracked

Output:

```<code>a(2) = 8
a(10) = 4738245926336
</code>```

All of it is crucial, and I have shown 1 of 5.

```<code>####x
</code>```

Original code:

```<code>mPm$x
mP     cube
  m$   catalan number
    x  input
</code>```

Try it online!

Body:
Jolf, 5 bytes, cracked

Output:

a(2) = 8
a(10) = 4738245926336

All of it is crucial, and I have shown 1 of 5.

####x

Original code:

mPm$x
mP     cube
  m$   catalan number
    x  input

Try it online!


问:
Find the program that prints this integer sequence (Robbers' thread)
This is the robbers' thread. The cops' thread goes here.

In the cops thread, the task was to write a program/function that takes a positive (or non-negative) integer and outputs/returns another number (not necessarily integer). The robbers task is to unscramble the code the cops used to produce this output.

The cracked code doesn't have to be identical, as long as it has the same length and any revealed characters are in the correct positions. The language must also be the same (version numbers can be different). The output must of course be identical.

No-ops can be used in robber's solution.

The winner of the robbers thread will be the user who has cracked the
most submissions by May 7th 2016. If there's a tie, the user who has cracked submissions with the longest combined code will win.

The submission should be formatted like this:

Language, nn characters (including link to answer), Cop's username

Code:

```<code>function a(n)
    if n<2 then
        return n
    else
        return a(n-1) + a(n-2)
    end
end
</code>```

Output

```<code>a(0) returns 0
a(3) returns 2
</code>```

Optional explanation and comments.

Body:
Jolf, 5 characters, Cᴏɴᴏʀ O'Bʀɪᴇɴ, A033536

Code:

!K!8x

Output:

a(2) = 8
a(10) = 4738245926336


答:
J, 7 bytes, cracked

Output:

```<code>a(0) = 6
a(2) = 27
</code>```

Code (I have shown more for added difficulty):

```<code>#+#:###
</code>```

Is a tacit verb.

Title: Find the program that prints this integer sequence (Cops' thread)

Body:
This is the cops' thread. The robbers' thread goes here.

The last cops-and-robbers thread was already 4 months ago.

The cop's task

The cop's task is to write a program/function that takes a positive (or non-negative) integer and outputs/returns another integer.

The cop must state it if the program is intolerant towards zero.

The cop will provide at least 2 sample inputs/outputs.

For example, if I have decided to write the Fibonacci sequence, I would write this in my answer:

```
a(0) returns 0
a(3) returns 2
```

The number of examples is up to the cop's discretion.

However, the sequence must actually exist in the On-Line Encyclopedia of Integer Sequences®, so no pseudo-random number generator for you. :(

The cop can hide as many characters as is so wished.

For example, if my program is:

```<code>function a(n)
    if n>2 then
        return n
    else
        return a(n-1) + a(n-2)
    end
end
</code>```

Then I would hide these characters as I want:

```<code>function a(n)
    if ### then
        ########
    else
        ######################
    end
end
</code>```

The robber's task

is obviously to find the original source code.

However, any proposed source code that produces the same set of output also counts as valid, as long as it is also found in OEIS.

Tips for the cops

<s>The search function in the OEIS only works for consecutive terms, so if you want to hide your sequence, then just leave a hole anywhere.</s>

Apparently there is no way to hide the sequence. Put this in mind when you choose the sequence.

Your score is the number of bytes in your code.

The winner will be the submission with the lowest score that hasn't been cracked in 7 days.

Only submissions that are posted in 2016 April are eligible for the win. Submissions that are posted later than this are welcome, but cannot win.

In order to claim the win you need to reveal the full code and the OEIS sequence (after 7 days).

Your post should be formatted like this (NN is the number of characters):

Lua, 98 bytes

Output:

```<code>a(0) returns 0
a(3) returns 2
</code>```

Code (# marks unrevealed characters):

```<code>function a(n)
    if ### then
        ########
    else
        ######################
    end
end
</code>```

If the code is cracked, insert [Cracked](link to cracker) in the header.
If the submission is safe, insert "Safe" in the header and reveal the full code in your answer. Only answers that have revealed the full code will be eligible for the win.

Body:
J, 7 bytes, cracked

Output:

a(0) = 6
a(2) = 27

Code (I have shown more for added difficulty):

#+#:###

Is a tacit verb.


答:
Reng v.3.3, 36 bytes. Cracked, A005449

Output:

```<code>a(1) = 2
a(3) = 15
</code>```

# denotes a gone character. There are no other #s in the program.

```<code>i#:#+##-##)####¡#~
##########!</div>
</code>```

Alright this is the last one for a while. Other people need to answer >_>. A description of each character can be found in the source code, where all the ops are defined. A comment proceeds each operator.

Original code:

```<code>i>:1+(1-?v)v/a+¡n~
~^<$:$:$:>!</div>
</code>```

Body:
Reng v.3.3, 36 bytes. Cracked, A005449

Output:

a(1) = 2
a(3) = 15

# denotes a gone character. There are no other #s in the program.

i#:#+##-##)####¡#~
##########!</div>

Alright this is the last one for a while. Other people need to answer >_>. A description of each character can be found in the source code, where all the ops are defined. A comment proceeds each operator.

Original code:

i>:1+(1-?v)v/a+¡n~
~^<$:$:$:>!</div>


答:
Vim, 36 keystrokes -- Safe!

```<code>i****<esc>:let @q="^*i****$**@***"<cr><n>@qbD
</code>```

(Note: <n> is where you type your input)

Here is the code unrelated to number generation:

```<code>          :let @q="              "<cr><n>@qbD
</code>```

Meaning I am revealing 5 out of 19 characters.

<n> is the input. Here are some sample outputs:

```<code>1@q:    1
2@q:    3
6@q:    18
</code>```

Answer

This code prints The Lucas Numbers (A000032), which are just like The Fibonnaci Sequence, except that it starts on 2, 1 instead of 1, 1. Here are the first 15 numbers:

```<code>2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, 199, 322, 521, 843
</code>```

Here's the revealed code:

```<code>i2 1 <esc>:let @q="^diwwyw$pb@-<c-v><c-a>"<cr><n>@qbD
</code>```

Explanation:

```<code>i2 1 <esc>                          "Insert the starting numbers
          :let @q="....."<cr>       "Define the macro 'Q'
</code>```

Explanation of the macro:

```<code>^                      "Move to the first non-whitespace character on the line.
 diw                   "(d)elete (i)nner (w)ord. This is different then 'dw' because it doesn't grab the space.
                      "It also throws people off since 'i' is usually used for inserting text.
    wyw$               "Move to the next number, yank it then move to the end of the line
        pb             "(p)aste the yanked text and move (b)ack
          @-     <c-a> "@- is the register holding the word we deleted. Increment the current number that many times.
            <c-v>      "Since we're adding <c-a> this from the command line, we need to type it as a literal.
</code>```

Now, we just need to remove the second number, since the first number is the lucas number we want. So we do

```<code>b   "move (b)ack
 D  "(D)elete to the end of the line.
</code>```

Also, if I'm not mistaken, this is the first safe submission! That's kinda cool.

Body:
Vim, 36 keystrokes -- Safe!

i****<esc>:let @q="^*i****$**@***"<cr><n>@qbD

(Note: <n> is where you type your input)

Here is the code unrelated to number generation:

          :let @q="              "<cr><n>@qbD

Meaning I am revealing 5 out of 19 characters.

<n> is the input. Here are some sample outputs:

1@q:    1
2@q:    3
6@q:    18

Answer

This code prints The Lucas Numbers (A000032), which are just like The Fibonnaci Sequence, except that it starts on 2, 1 instead of 1, 1. Here are the first 15 numbers:

2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, 199, 322, 521, 843

Here's the revealed code:

i2 1 <esc>:let @q="^diwwyw$pb@-<c-v><c-a>"<cr><n>@qbD

Explanation:

i2 1 <esc>                          "Insert the starting numbers
          :let @q="....."<cr>       "Define the macro 'Q'

Explanation of the macro:

^                      "Move to the first non-whitespace character on the line.
 diw                   "(d)elete (i)nner (w)ord. This is different then 'dw' because it doesn't grab the space.
                      "It also throws people off since 'i' is usually used for inserting text.
    wyw$               "Move to the next number, yank it then move to the end of the line
        pb             "(p)aste the yanked text and move (b)ack
          @-     <c-a> "@- is the register holding the word we deleted. Increment the current number that many times.
            <c-v>      "Since we're adding <c-a> this from the command line, we need to type it as a literal.

Now, we just need to remove the second number, since the first number is the lucas number we want. So we do

b   "move (b)ack
 D  "(D)elete to the end of the line.

Also, if I'm not mistaken, this is the first safe submission! That's kinda cool.


答:
Jolf, 11 bytes, Cracked.

Output:

```<code>a(10) = 4
a(20) = 6
a(30) = 8
</code>```

And the partially hidden code:

```<code>####xd###x#
</code>```

Hint:

 When I looked through the sequences in order, I didn't go very far before finding this one.

The cracked version isn't quite the same as my original code. I'm not currently at my computer, so I don't have it exactly, but it was something like this:

 l fzxd!m%xH

(The only part I'm unsure about is the !m. It's whatever checks if a variable is zero.)

Body:
Jolf, 11 bytes, Cracked.

Output:

a(10) = 4
a(20) = 6
a(30) = 8

And the partially hidden code:

####xd###x#

Hint:

 When I looked through the sequences in order, I didn't go very far before finding this one.

The cracked version isn't quite the same as my original code. I'm not currently at my computer, so I don't have it exactly, but it was something like this:

 l fzxd!m%xH

(The only part I'm unsure about is the !m. It's whatever checks if a variable is zero.)


答:
Element, 10 bytes, cracked

Output:

```<code>a(3) = 6561
a(4) = 4294967296
</code>```

There's probably only a few ways to compute this sequence in Element.  I found a 9-char solution, but I figured this 10-char solution is actually more difficult.  The # are hidden characters.

```<code>#_####@^#`
</code>```

For convenience, here's the Try It Online and Esolang wiki pages.

The original was

```<code>2_3:~2@^^`
</code>```

Body:
Element, 10 bytes, cracked

Output:

a(3) = 6561
a(4) = 4294967296

There's probably only a few ways to compute this sequence in Element.  I found a 9-char solution, but I figured this 10-char solution is actually more difficult.  The # are hidden characters.

#_####@^#`

For convenience, here's the Try It Online and Esolang wiki pages.

The original was

2_3:~2@^^`


答:
J, 7 bytes, Cᴏɴᴏʀ O'Bʀɪᴇɴ

Code

```<code>2+*:@p:
</code>```

Output

```<code>   f =: 2+*:@p:
   f 0
6
   f 2
27
</code>```

Try it with J.js.

How it works

Sequence A061725 is defined as a(n) := pn² + 2, where pn is the (n + 1)th prime number.

```<code>2+*:@p:  Monadic verb. Argument: n

    @    Atop; combine the verbs to the right and to the left, applying one after
         the other.
     p:  Compute the (n+1)th prime number.
  *:     Square it.
2+       Add 2 to the result.
</code>```

Title: Find the program that prints this integer sequence (Robbers' thread)

Body:
This is the robbers' thread. The cops' thread goes here.

In the cops thread, the task was to write a program/function that takes a positive (or non-negative) integer and outputs/returns another number (not necessarily integer). The robbers task is to unscramble the code the cops used to produce this output.

The cracked code doesn't have to be identical, as long as it has the same length and any revealed characters are in the correct positions. The language must also be the same (version numbers can be different). The output must of course be identical.

No-ops can be used in robber's solution.

The winner of the robbers thread will be the user who has cracked the
most submissions by May 7th 2016. If there's a tie, the user who has cracked submissions with the longest combined code will win.

The submission should be formatted like this:

Language, nn characters (including link to answer), Cop's username

Code:

```<code>function a(n)
    if n<2 then
        return n
    else
        return a(n-1) + a(n-2)
    end
end
</code>```

Output

```<code>a(0) returns 0
a(3) returns 2
</code>```

Optional explanation and comments.

Body:
J, 7 bytes, Cᴏɴᴏʀ O'Bʀɪᴇɴ

Code

2+*:@p:

Output

   f =: 2+*:@p:
   f 0
6
   f 2
27

Try it with J.js.

How it works

Sequence A061725 is defined as a(n) := pn² + 2, where pn is the (n + 1)th prime number.

2+*:@p:  Monadic verb. Argument: n

    @    Atop; combine the verbs to the right and to the left, applying one after
         the other.
     p:  Compute the (n+1)th prime number.
  *:     Square it.
2+       Add 2 to the result.


问:
How many elves does Santa need to deliver gifts?
Santa needs some help determining how many elves he will need to help him deliver gifts to each house.

Coal is considerably heavier than presents, so santa will need three elves for every naughty person in the house. Only two elves are needed to help santa carry presents.

On santa's map, a house is represented by a *, and each house is split by a +.

There will be a number on either side of the house - the one on the left representing the number of naughty people in the house, and the one on the right representing the number of nice people in the house. If there is no number on one side it is interpreted as a 0.

Santa doesn't visit those who are not in the christmas spirit (they don't even deserve coal), so sometimes, a house may not have a number on either side of it. In this case, santa doesn't need help from any elves

For example, one of santa's maps may look like this

```<code>1*3+2*2+1*+*2
</code>```

In the first house there is 1 naughty and 3 nice, santa will need nine elves. In the second, there are 2 naughty and 2 nice, santa will need ten elves. In the third house there is 1 naughty and 0 nice, santa will need three elves, and in the last house there are 0 naughty and 2 nice, santa will need four elves.

This is an over-simplified version of one of santa's maps, though. Normally, santa's maps have multiple lines, and are in a square shape as to better fit on his list. A normal map might look something like this (a \n at the end of each line)

```<code>1*2+*+*4+1*
2*4+3*+1*6+*
*+*+4*2+1*1
*4+*3+1*+2*3
3*10+2*+*5+*
</code>```

In this map, santa needs ((1 + 0 + 0 + 1 + 2 + 3 + 1 + 0 + 0 + 0 + 4 + 1 + 0 + 0 + 1 + 2 + 3 + 2 + 0 + 0) * 3) + ((2 + 0 + 4 + 0 + 4 + 0 + 6 + 0 + 0 + 0 + 2 + 1 + 4 + 3 + 0 + 3 + 10 + 0 + 5 + 0) * 2) = 151 elves

Challenge

Help santa determine how many elves he needs to deliver goods to each house!

Houses

A house is represented by a *

Houses are split by +

The number on the left of the house symbolizes the number of naughty people (no number means 0)

The number on the right symbolizes the number of nice people (no number means 0)

There may be newlines (\n) in the input, which should also be handled as a split

Elves

Santa needs help from three elves for naughty people (coal is much heavier than presents)

Santa needs help from two elves for nice people

If there is no number on either side, santa will not visit that house, and therefor does not need any elves

What to do

Print the number of elves santa needs to help him deliver presents to the houses to. Because all Santa needs to know is how many elves to bring, you only need to print the added number of elves he needs for the list of houses

Test Cases

```<code>1*1 => 5
1*2 => 7
2*1 => 8
1* => 3
*1 => 2
* => 0

1*1+1*1 => 10
1*2+2*1 => 15
1*+*1 => 5
1*1+*+1*1 => 10
*+*+*+* => 0
</code>```

Rules

The input can be either taken as an argument in a function, or from STDIN or equivalent

The output can either be the return value of a function, or printed to STDOUT or equivalent

The input will only contain numbers, +, *, and newlines \n

The output should be only the total number of elves that Santa needs help from to deliver on Christmas

Standard loopholes apply

Scoring

Santa's sleigh is full of gifts giving him less space to run code, so he needs the shortest code he can get (don't worry if this doesn't make sense. If you question Santa's logic you'll end up on the naughty list). Due to Santa's CORRECT reasoning, the shortest submission in bytes wins!

Leaderboard

This is a Stack Snippet that generates both a leaderboard and an overview of winners by language.

To ensure your answer shows up, please start your answer with a headline using the following Markdown template

```<code>## Language Name, N bytes
</code>```

Where N is the size, in bytes, of your submission

If you want to include multiple numbers in your header (for example, striking through old scores, or including flags in the byte count), just make sure that the actual score is the last number in your header

```<code>## Language Name, <s>K</s> X + 2 = N bytes
</code>```

var QUESTION_ID=67600;var OVERRIDE_USER=20634;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(-?\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

答:
I'm super late, but I wanted to give it a shot anyways.

Ruby, <s>84</s> 55 bytes

I found this question again after so many years and was thinking up a fresh answer before I realized I'd already answered this before. Whoops! Anyways, here's a drastically improved answer.

->m{m.scan(/(\d*)\*(\d*)/).sum{|a,b|3*a.to_i+2*b.to_i}}
```

<p>Try it online!</p>

<p>Old 84-byte answer from when I first answered this 2 years ago:</p>

<pre class="lang-ruby prettyprint-override"><code>->m{m.split(/[+\n]/).map{|h|b,g=h.split(?*).map &:to_i
3*(b||0)+2*(g||0)}.inject :+}
</code>```

Try it online!

Body:
I'm super late, but I wanted to give it a shot anyways.

Ruby, <s>84</s> 55 bytes

I found this question again after so many years and was thinking up a fresh answer before I realized I'd already answered this before. Whoops! Anyways, here's a drastically improved answer.

->m{m.scan(/(\d*)\*(\d*)/).sum{|a,b|3*a.to_i+2*b.to_i}}

Try it online!

Old 84-byte answer from when I first answered this 2 years ago:

->m{m.split(/[+\n]/).map{|h|b,g=h.split(?*).map &:to_i
3*(b||0)+2*(g||0)}.inject :+}

Try it online!

ContentLicense: CC BY-SA 4.0


Body:
Element, 10 bytes, PhiNotPi, A097547

2_4:/2@^^`

Try it online!

Output

a(3) = 6561
a(4) = 4294967296


答:
Perl, 110 bytes (108 bytes script + 2 bytes flags)

$h=0;map{$h{$h}.=' 'x($p-$p{$h}).$_;$p{$h}=++$p;$h+=/[aeiou]/i-/\s/}split//;print for@h{sort{$b<=>$a}keys%h}
```
<p>Run with <code>perl -nl script.pl</code>, input is on stdin, output is on stdout.</p>
<h2>Deobfuscated</h2>
<p>I've renamed the variables more sensibly, made the code <code>use strict</code> and <code>use warnings</code> compliant, and made explicit a lot of the magic perl does automatically.</p>
<p>This is just run as <code>perl script.pl</code>, because it replicates the effects of the <code>-nl</code> flags inside the script.</p>
<pre class="lang-perl prettyprint-override"><code>use strict;
use warnings;
use English;

# The effect of -l in perl's flags
$INPUT_RECORD_SEPARATOR = "\n";
$OUTPUT_RECORD_SEPARATOR = "\n";

# These variables are magicked into existence
our $column = 0;
our %line_col = ();
our %lines = ();

# The implicit while-loop is the effect of -n in perl's flags
while (defined(my $line = <>)) {
    # The "chomp" is part of perl's -l flag too
    chomp $line;

    # Here starts the actual script. "$h=0" turns into...
    our $height = 0;
    for my $char (split '', $line) {
        if (!exists $line_col{$height}) {
            # Setting it to 0 is a bit of a white lie, but it might as well be 0.
            # Perl would otherwise have called the value "undef", which is
            # similar to 0 in numeric contexts.
            $line_col{$height} = 0;
        }

        $lines{$height} .= ' ' x ($column - $line_col{$height});
        $lines{$height} .= $char;

        $column++;
        $line_col{$height} = $column;

        $height++ if $char =~ /[aeiou]/i;
        $height-- if $char =~ /\s/;
    }

    # Sort line heights numerically descending (so the greatest is printed first)
    my @heights = sort { $b<=>$a } keys %lines;

    for my $line (@lines{ @heights }) {
        print $line;
    }
}
</code>```

Title: "Stair-ify" a string

Body:
Perl, 110 bytes (108 bytes script + 2 bytes flags)

$h=0;map{$h{$h}.=' 'x($p-$p{$h}).$_;$p{$h}=++$p;$h+=/[aeiou]/i-/\s/}split//;print for@h{sort{$b<=>$a}keys%h}

Run with perl -nl script.pl, input is on stdin, output is on stdout.

Deobfuscated

I've renamed the variables more sensibly, made the code use strict and use warnings compliant, and made explicit a lot of the magic perl does automatically.

This is just run as perl script.pl, because it replicates the effects of the -nl flags inside the script.

use strict;
use warnings;
use English;

# The effect of -l in perl's flags
$INPUT_RECORD_SEPARATOR = "\n";
$OUTPUT_RECORD_SEPARATOR = "\n";

# These variables are magicked into existence
our $column = 0;
our %line_col = ();
our %lines = ();

# The implicit while-loop is the effect of -n in perl's flags
while (defined(my $line = <>)) {
    # The "chomp" is part of perl's -l flag too
    chomp $line;

    # Here starts the actual script. "$h=0" turns into...
    our $height = 0;
    for my $char (split '', $line) {
        if (!exists $line_col{$height}) {
            # Setting it to 0 is a bit of a white lie, but it might as well be 0.
            # Perl would otherwise have called the value "undef", which is
            # similar to 0 in numeric contexts.
            $line_col{$height} = 0;
        }

        $lines{$height} .= ' ' x ($column - $line_col{$height});
        $lines{$height} .= $char;

        $column++;
        $line_col{$height} = $column;

        $height++ if $char =~ /[aeiou]/i;
        $height-- if $char =~ /\s/;
    }

    # Sort line heights numerically descending (so the greatest is printed first)
    my @heights = sort { $b<=>$a } keys %lines;

    for my $line (@lines{ @heights }) {
        print $line;
    }
}


问:
A simple TCP server
Write a program or function that listens for incoming TCP traffic on port N. It offers a simple service: it calculates sum of IP address fields of incoming connection and returns.

Program or function reads integer N from arguments or stdin. It listens to incoming TCP connections on port N. When someone connects to that port, the program calculates sum of its IP address fields and sends it back to the client with trailing newline and closes connection.

Port number N is a valid port, and 210 < N < 215

Trailing newline can be either \nor \r\n

You can use either IPv4 or IPv6. Since IPv6 addresses are written in hexadecimal form, you must also provide result in same format, for example 2001:0db8:0000:0042:0000:8a2e:0370:7334 => 12ecd.

This is code-golf. Standard rules and loopholes apply.

Example

You run your server with ./server 1234. The server is now running and waiting for connections on port 1234. Then a client from 127.0.0.1 connects to your server. Your server performs a simple calculation: 127+0+0+1 => 128 and sends the result to the client (with trailing newline): 128\n. Then server closes connection and waits for next client.

Leaderboard

var QUESTION_ID=76379,OVERRIDE_USER=20569;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

答:
Factor, <s>155</s> <s>146</s> <s>131</s> <s>206</s> 190 bytes

Well, I just learned a lot about low-level socket programming. I don't think I ever wanna do that again, because my <s>thr</s>head hurts.

```<code>[ utf8 <threaded-server> readln 10 base> >>insecure [ remote-address get host>> "." split [ 10 base> ] map sum 10 >base print flush ] >>handler [ start-server ] in-thread start-server drop ]
</code>```

Oh yeah, threaded, and doesn't return, right.

Title: A simple TCP server

Body:
Factor, <s>155</s> <s>146</s> <s>131</s> <s>206</s> 190 bytes

Well, I just learned a lot about low-level socket programming. I don't think I ever wanna do that again, because my <s>thr</s>head hurts.

[ utf8 <threaded-server> readln 10 base> >>insecure [ remote-address get host>> "." split [ 10 base> ] map sum 10 >base print flush ] >>handler [ start-server ] in-thread start-server drop ]

Oh yeah, threaded, and doesn't return, right.


答:
Element, 7 bytes, cracked

Output:

```<code>a(3) = 111
a(7) = 1111111
</code>```

The # are hidden characters, and they are all printable ASCII.  I think this one is actually reasonably difficult (for only having 5 missing characters).

```<code>###,##}
</code>```

For convenience, here's the Try It Online and Esolang wiki pages.

My original program was:

 _'[,$`}

The trick is that

] and } are functionally identical (both translate to } in Perl).  Also, I used ,$ to produce a 1 as an additional layer of confusion, although it is possible to ignore the , completely by doing ,1 instead.

Body:
Element, 7 bytes, cracked

Output:

a(3) = 111
a(7) = 1111111

The # are hidden characters, and they are all printable ASCII.  I think this one is actually reasonably difficult (for only having 5 missing characters).

###,##}

For convenience, here's the Try It Online and Esolang wiki pages.

My original program was:

 _'[,$`}

The trick is that

] and } are functionally identical (both translate to } in Perl).  Also, I used ,$ to produce a 1 as an additional layer of confusion, although it is possible to ignore the , completely by doing ,1 instead.


答:
Reng v3.3, 36 bytes, Cᴏɴᴏʀ O'Bʀɪᴇɴ, A005449

```<code>iv:#+##->>)2%æ~¡#~
#>:3*1+*^##</div>
</code>```

Output

```<code>a(1) = 2
a(3) = 15
</code>```

Explanation

I completely ignored the prespecified commands, except the ) because I did not have enough space.

The actually useful commands are here:

```<code>iv      >>)2%æ~
 >:3*1+*^
</code>```

Stretched to a straight line:

```<code>i:3*1+*)2%æ~
</code>```

With explanation:

```<code>i:3*1+*)2%æ~ stack
i            [1]      takes input
 :           [1,1]    duplicates
  3          [1,1,3]  pushes 3
   *         [1,3]    multiplies
    1        [1,3,1]  pushes 1
     +       [1,4]    adds
      *      [4]      multiplies
       )     [4]      shifts (does nothing)
        2    [4,2]    pushes 2
         %   [2]      divides
          æ  []       prints
           ~ []       halts
</code>```

The formula is a(n) = n(3n+1)/2.

Body:
Reng v3.3, 36 bytes, Cᴏɴᴏʀ O'Bʀɪᴇɴ, A005449

iv:#+##->>)2%æ~¡#~
#>:3*1+*^##</div>

Output

a(1) = 2
a(3) = 15

Explanation

I completely ignored the prespecified commands, except the ) because I did not have enough space.

The actually useful commands are here:

iv      >>)2%æ~
 >:3*1+*^

Stretched to a straight line:

i:3*1+*)2%æ~

With explanation:

i:3*1+*)2%æ~ stack
i            [1]      takes input
 :           [1,1]    duplicates
  3          [1,1,3]  pushes 3
   *         [1,3]    multiplies
    1        [1,3,1]  pushes 1
     +       [1,4]    adds
      *      [4]      multiplies
       )     [4]      shifts (does nothing)
        2    [4,2]    pushes 2
         %   [2]      divides
          æ  []       prints
           ~ []       halts

The formula is a(n) = n(3n+1)/2.


答:
Element, 7 bytes, PhiNotPi, A000042

```<code>_'[,1`}
</code>```

Notes: I was misled by the } for soooooo long. So it also matches [.

Try it online!

How it works:

```<code>_'[,1`}
_        main_stack.push(input());
 '       control_stack.push(main_stack.pop());
  [      Object temp = control_stack.pop();
         for(int i=0;i<temp;i++){
   ,         Object a = main_stack.pop(); //is actually zero
             main_stack.push(a.toChars()[0]);
             main_stack.push(a);
    1        main_stack.push(1);
     `       System.out.println(main_stack.pop());
      }  }
</code>```

Body:
Element, 7 bytes, PhiNotPi, A000042

_'[,1`}

Notes: I was misled by the } for soooooo long. So it also matches [.

Try it online!

How it works:

_'[,1`}
_        main_stack.push(input());
 '       control_stack.push(main_stack.pop());
  [      Object temp = control_stack.pop();
         for(int i=0;i<temp;i++){
   ,         Object a = main_stack.pop(); //is actually zero
             main_stack.push(a.toChars()[0]);
             main_stack.push(a);
    1        main_stack.push(1);
     `       System.out.println(main_stack.pop());
      }  }


问:
Switching Gravity

Challenge

You are given an ASCII-art representation of characters on a plane as input by any reasonable method. This will only contain:

[a-z] representing moveable characters. Every letter will appear on the board at most once.

# representing immovable walls

. representing empty space

For example:

```<code>abcdef.gh#..
.......ij.#.
#..#.......#
...#.#...###
.#.......#q#
.........###
</code>```

You are also given a string representing the changes in gravity. This will only contain:

> representing a change to rightward gravity

< representing a change to leftward gravity

^ representing a change to upward gravity

v representing a change to downward gravity

For example:

```<code>v>^
</code>```

Your program must simulate the each change in gravity sequentially until all characters stop moving (they hit a wall, or another character). Characters that "fall off the edge of the map" are permanently removed, and characters can "stack" on top of each other.

In this example, at the start there is downward gravity (v), so c, e, g, h, i, and j fall off the bottom of the map. All other characters slide downwards until hitting a wall, leaving the map like this:

```<code>.........#..
a..d......#.
#..#.f.....#
.b.#.#...###
.#.......#q#
.........###
</code>```

Then, we move on to rightward gravity (>), which leaves us with this:
Note how the a stacks next to the d.

```<code>.........#..
........ad#.
#..#......f#
..b#.#...###
.#.......#q#
.........###
</code>```

Finally, we simulate upward gravity (^), during which the a and the b fall off the map.

```<code>.........#..
.........d#.
#..#......f#
...#.#...###
.#.......#q#
.........###
</code>```

Your task is to output the remaining characters after the gravitational shifts. They can be given in any order. For this example, you could output any permutation of dfq.

Testcases

For the following map:

```<code>abcde
.....
##.##
</code>```

```<code>v   =  abde
v>  =  <nothing>
</code>```

For the following map:

```<code>######
#....#
abcdef
#.gh..
######
</code>```

```<code>>   = <nothing>
<   = gh
^>  = bcde
v<  = bghef
</code>```

答:
Ruby, 306 bytes

Anonymous function. Pretty circuitous technique that could probably be optimized.

```<code>->s,d{w=[];x=y=0;m={}
s.chars.map{|c|c>?!?(c<?A?c<?.?w<<[x,y]:0:m[c]=[x,y]
x+=1):(x=0;y+=1)}
d.chars.map{|c|q=[c<?=?-1:c<?A?1:0,c>?a?1:c>?A?-1:0];e=1
(n=m.clone.each{|k,v|z=[v[0]+q[0],v[1]+q[1]]
w.index(z)||m.value?(z)?0:m[k]=z}
m.reject!{|k,v|i,j=v;i<0||i>=x||j<0||j>y}
e=(m!=n ?1:p))while e}
m.keys.join}
</code>```

Title: Switching Gravity

Body:
Ruby, 306 bytes

Anonymous function. Pretty circuitous technique that could probably be optimized.

->s,d{w=[];x=y=0;m={}
s.chars.map{|c|c>?!?(c<?A?c<?.?w<<[x,y]:0:m[c]=[x,y]
x+=1):(x=0;y+=1)}
d.chars.map{|c|q=[c<?=?-1:c<?A?1:0,c>?a?1:c>?A?-1:0];e=1
(n=m.clone.each{|k,v|z=[v[0]+q[0],v[1]+q[1]]
w.index(z)||m.value?(z)?0:m[k]=z}
m.reject!{|k,v|i,j=v;i<0||i>=x||j<0||j>y}
e=(m!=n ?1:p))while e}
m.keys.join}


答:
05AB1E, 3 bytes, cracked

Output:

```<code>a(9) = 165
a(10) = 220
</code>```

Hidden code:

```<code>##O
</code>```

Try it online might come in handy.

Body:
05AB1E, 3 bytes, cracked

Output:

a(9) = 165
a(10) = 220

Hidden code:

##O

Try it online might come in handy.


答:
Hexagony, 7 bytes, cracked

Output:

```<code>a(1) = 2
a(2) = 4
</code>```

Hidden code:

```<code>?#####@
</code>```

Or alternatively:

```<code> ? #
# # #
 # @
</code>```

Try it online might come in handy.

Body:
This is the cops' thread. The robbers' thread goes here.

The last cops-and-robbers thread was already 4 months ago.

The cop's task

The cop's task is to write a program/function that takes a positive (or non-negative) integer and outputs/returns another integer.

The cop must state it if the program is intolerant towards zero.

The cop will provide at least 2 sample inputs/outputs.

For example, if I have decided to write the Fibonacci sequence, I would write this in my answer:

```
a(0) returns 0
a(3) returns 2
```

The number of examples is up to the cop's discretion.

However, the sequence must actually exist in the On-Line Encyclopedia of Integer Sequences®, so no pseudo-random number generator for you. :(

The cop can hide as many characters as is so wished.

For example, if my program is:

```<code>function a(n)
    if n>2 then
        return n
    else
        return a(n-1) + a(n-2)
    end
end
</code>```

Then I would hide these characters as I want:

```<code>function a(n)
    if ### then
        ########
    else
        ######################
    end
end
</code>```

The robber's task

is obviously to find the original source code.

However, any proposed source code that produces the same set of output also counts as valid, as long as it is also found in OEIS.

Tips for the cops

<s>The search function in the OEIS only works for consecutive terms, so if you want to hide your sequence, then just leave a hole anywhere.</s>

Apparently there is no way to hide the sequence. Put this in mind when you choose the sequence.

Your score is the number of bytes in your code.

The winner will be the submission with the lowest score that hasn't been cracked in 7 days.

Only submissions that are posted in 2016 April are eligible for the win. Submissions that are posted later than this are welcome, but cannot win.

In order to claim the win you need to reveal the full code and the OEIS sequence (after 7 days).

Your post should be formatted like this (NN is the number of characters):

Lua, 98 bytes

Output:

```<code>a(0) returns 0
a(3) returns 2
</code>```

Code (# marks unrevealed characters):

```<code>function a(n)
    if ### then
        ########
    else
        ######################
    end
end
</code>```

If the code is cracked, insert [Cracked](link to cracker) in the header.
If the submission is safe, insert "Safe" in the header and reveal the full code in your answer. Only answers that have revealed the full code will be eligible for the win.

Body:
Hexagony, 7 bytes, cracked

Output:

a(1) = 2
a(2) = 4

Hidden code:

?#####@

Or alternatively:

 ? #
# # #
 # @

Try it online might come in handy.


答:
05AB1E, 4 bytes (Cracked)

Sample output :

```<code>a(5) = 51
a(8) = 257
</code>```

And for the code :

```<code>###^
</code>```

I revealed the last one. Should be easy enough though, I had quite a hard time finding a sequence :(

All hidden characters are printable.

Body:
05AB1E, 4 bytes (Cracked)

Sample output :

a(5) = 51
a(8) = 257

And for the code :

###^

I revealed the last one. Should be easy enough though, I had quite a hard time finding a sequence :(

All hidden characters are printable.


答:
05AB1E, 3 bytes, Adnan, A000292

```<code>LLO
</code>```

Output

```<code>a(9) = 165
a(10) = 220
</code>```

How it works

```<code>LLO Stack
L   [1,2,3,4,5,6,7,8,9]                         range
 L  [1,1,2,1,2,3,1,2,3,4,...,1,2,3,4,5,6,7,8,9] range of range
  O sum all of them
</code>```

The mathematical equivalent is sum(sum(n)), where sum is summation.

Body:
05AB1E, 3 bytes, Adnan, A000292

LLO

Output

a(9) = 165
a(10) = 220

How it works

LLO Stack
L   [1,2,3,4,5,6,7,8,9]                         range
 L  [1,1,2,1,2,3,1,2,3,4,...,1,2,3,4,5,6,7,8,9] range of range
  O sum all of them

The mathematical equivalent is sum(sum(n)), where sum is summation.


答:
Pyth, 143 bytes

(Do we really need that much bytes?)

```<code>JhQKeQMe.u:N+"\."H+H"."G;DybVkI}NG=gkN;D'bVlJ=k@JNykVkI}HG=:kH\.).?B)=XJNk;VKIqN\<'J)IqN\v=C_J'J=_CJ)IqN\>=C_CJ'J=C_CJ)IqN\^=CJ'J=CJ;VJVNI}HGpH
</code>```

Try it online!

How it works

We define a function left which does the leftward gravity thing.

Then, the other directions are implemented by messing with the array so that the desired direction is leftwards, then do left.

The algorithm of left is here:

Do the following until idempotent:

Replace ".X" with "X.", where X represents a letter.

The whole program is divided into the following 6 sections:

```<code>JhQKeQ
Me.u:N+"\."H+H"."G;
DybVkI}NG=gkN;
D'bVlJ=k@JNykVkI}HG=:kH\.).?B)=XJNk;
VKIqN\<'J)IqN\v=C_J'J=_CJ)IqN\>=C_CJ'J=C_CJ)IqN\^=CJ'J=CJ;
VJVNI}HGpH
</code>```

First section

```<code>JhQKeQ     Q auto-initialized to evaluate(input())
JhQ        J = Q[0]
   KeQ     K = Q[len(Q)-1]
</code>```

Second section

```<code>Me.u:N+"\."H+H"."G;   @memoized
M                 ;   def g(G,H):
  .u             G      repeat_until_idempotent(start:G, as N):
    :Nxxxxxxyyyyy         return N.replace(xxxxxx,yyyyy)
      +"\."H                               "\."+H
            +H"."                                 H+"."
</code>```

Third section

```<code>DybVkI}NG=gkN;    @memoized
Dyb          ;    def y(b):
   Vk               for N in k:     --TAKES GLOBAL VARIABLE k
     I}NG             if N in G:    --G pre-initialized to "abcde...z"
         =gkN           k = g(k,N)
</code>```

Fourth section

```<code>D'bVlJ=k@JNykVkI}HG=:kH\.).?B)=XJNk;  @memoized
D'b                                ;  def single_quote(b):
   VlJ                       )          for N in range(len(J)): --TAKES GLOBAL VARIABLE J
      =k@JN                               k = J[N] --SETS GLOBAL VARIABLE k
           yk                             y(k) --returns nothing, but MODIFIES GLOBAL VARIABLE k
             Vk                           for H in k:
               I}HG      )                  if H in G:
                   =:kH\.                     k = k.replace(H,".")
                          .?                else:
                            B                 break
                              =XJNk     J[N] = k --MODIFIES GLOBAL VARIABLE J
</code>```

Fifth section

```<code>VKIqN\<'J)IqN\v=C_J'J=_CJ)IqN\>=C_CJ'J=C_CJ)IqN\^=CJ'J=CJ;
VK                                                       ; for N in K:
  IqN\<  )                                                   if N == '<':
       'J                                                      single-quote(J)
          IqN\v          )                                   if N == 'v':
               =C_J                                            J = transpose(reverse(J))
                   'J                                          single-quote(J)
                     =_CJ                                      J = reverse(transpose(J))
                          IqN\>            )                 if N == '>':
                               =C_CJ                           J = transpose(reverse(transpose(J)))
                                    'J                         single-quote(J)
                                      =C_CJ                    J = transpose(reverse(transpose(J)))
                                            IqN\^            if N == '^':
                                                 =CJ           J = transpose(J)
                                                    'J         single-quote(J)
                                                      =CJ      J = transpose(J)
</code>```

Sixth section

```<code>VJVNI}HGpH
VJ           for N in J:
  VN           for H in N:
    I}HG         if H in G: --G = "abc...z"
        pH         print(H)
</code>```

Title: Switching Gravity

Body:
Challenge

You are given an ASCII-art representation of characters on a plane as input by any reasonable method. This will only contain:

[a-z] representing moveable characters. Every letter will appear on the board at most once.

# representing immovable walls

. representing empty space

For example:

```<code>abcdef.gh#..
.......ij.#.
#..#.......#
...#.#...###
.#.......#q#
.........###
</code>```

You are also given a string representing the changes in gravity. This will only contain:

> representing a change to rightward gravity

< representing a change to leftward gravity

^ representing a change to upward gravity

v representing a change to downward gravity

For example:

```<code>v>^
</code>```

Your program must simulate the each change in gravity sequentially until all characters stop moving (they hit a wall, or another character). Characters that "fall off the edge of the map" are permanently removed, and characters can "stack" on top of each other.

In this example, at the start there is downward gravity (v), so c, e, g, h, i, and j fall off the bottom of the map. All other characters slide downwards until hitting a wall, leaving the map like this:

```<code>.........#..
a..d......#.
#..#.f.....#
.b.#.#...###
.#.......#q#
.........###
</code>```

Then, we move on to rightward gravity (>), which leaves us with this:
Note how the a stacks next to the d.

```<code>.........#..
........ad#.
#..#......f#
..b#.#...###
.#.......#q#
.........###
</code>```

Finally, we simulate upward gravity (^), during which the a and the b fall off the map.

```<code>.........#..
.........d#.
#..#......f#
...#.#...###
.#.......#q#
.........###
</code>```

Your task is to output the remaining characters after the gravitational shifts. They can be given in any order. For this example, you could output any permutation of dfq.

Testcases

For the following map:

```<code>abcde
.....
##.##
</code>```

```<code>v   =  abde
v>  =  <nothing>
</code>```

For the following map:

```<code>######
#....#
abcdef
#.gh..
######
</code>```

```<code>>   = <nothing>
<   = gh
^>  = bcde
v<  = bghef
</code>```

Body:
Pyth, 143 bytes

(Do we really need that much bytes?)

JhQKeQMe.u:N+"\."H+H"."G;DybVkI}NG=gkN;D'bVlJ=k@JNykVkI}HG=:kH\.).?B)=XJNk;VKIqN\<'J)IqN\v=C_J'J=_CJ)IqN\>=C_CJ'J=C_CJ)IqN\^=CJ'J=CJ;VJVNI}HGpH

Try it online!

How it works

We define a function left which does the leftward gravity thing.

Then, the other directions are implemented by messing with the array so that the desired direction is leftwards, then do left.

The algorithm of left is here:

Do the following until idempotent:

Replace ".X" with "X.", where X represents a letter.

The whole program is divided into the following 6 sections:

JhQKeQ
Me.u:N+"\."H+H"."G;
DybVkI}NG=gkN;
D'bVlJ=k@JNykVkI}HG=:kH\.).?B)=XJNk;
VKIqN\<'J)IqN\v=C_J'J=_CJ)IqN\>=C_CJ'J=C_CJ)IqN\^=CJ'J=CJ;
VJVNI}HGpH

First section

JhQKeQ     Q auto-initialized to evaluate(input())
JhQ        J = Q[0]
   KeQ     K = Q[len(Q)-1]

Second section

Me.u:N+"\."H+H"."G;   @memoized
M                 ;   def g(G,H):
  .u             G      repeat_until_idempotent(start:G, as N):
    :Nxxxxxxyyyyy         return N.replace(xxxxxx,yyyyy)
      +"\."H                               "\."+H
            +H"."                                 H+"."

Third section

DybVkI}NG=gkN;    @memoized
Dyb          ;    def y(b):
   Vk               for N in k:     --TAKES GLOBAL VARIABLE k
     I}NG             if N in G:    --G pre-initialized to "abcde...z"
         =gkN           k = g(k,N)

Fourth section

D'bVlJ=k@JNykVkI}HG=:kH\.).?B)=XJNk;  @memoized
D'b                                ;  def single_quote(b):
   VlJ                       )          for N in range(len(J)): --TAKES GLOBAL VARIABLE J
      =k@JN                               k = J[N] --SETS GLOBAL VARIABLE k
           yk                             y(k) --returns nothing, but MODIFIES GLOBAL VARIABLE k
             Vk                           for H in k:
               I}HG      )                  if H in G:
                   =:kH\.                     k = k.replace(H,".")
                          .?                else:
                            B                 break
                              =XJNk     J[N] = k --MODIFIES GLOBAL VARIABLE J

Fifth section

VKIqN\<'J)IqN\v=C_J'J=_CJ)IqN\>=C_CJ'J=C_CJ)IqN\^=CJ'J=CJ;
VK                                                       ; for N in K:
  IqN\<  )                                                   if N == '<':
       'J                                                      single-quote(J)
          IqN\v          )                                   if N == 'v':
               =C_J                                            J = transpose(reverse(J))
                   'J                                          single-quote(J)
                     =_CJ                                      J = reverse(transpose(J))
                          IqN\>            )                 if N == '>':
                               =C_CJ                           J = transpose(reverse(transpose(J)))
                                    'J                         single-quote(J)
                                      =C_CJ                    J = transpose(reverse(transpose(J)))
                                            IqN\^            if N == '^':
                                                 =CJ           J = transpose(J)
                                                    'J         single-quote(J)
                                                      =CJ      J = transpose(J)

Sixth section

VJVNI}HGpH
VJ           for N in J:
  VN           for H in N:
    I}HG         if H in G: --G = "abc...z"
        pH         print(H)


答:
Hexagony, 7 bytes, Adnan, A005843

```<code>?{2'*!@
</code>```

or

```<code> ? {
2 ' *
 ! @
</code>```

Try it online!

Simply doubles the input (and assumes positive input). The code is (for once) simply executed in reading order. The code uses three memory edges A, B, C with the memory pointer starting out as shown:

```<code>?    Read integer from STDIN into edge A.
{    Move memory pointer forwards to edge B.
2    Set edge B to 2.
'    Move memory pointers backwards to edge C.
*    Multiply edges A and B and store result in C.
!    Print result to STDOUT.
@    Terminate program.
</code>```

Body:
This is the robbers' thread. The cops' thread goes here.

In the cops thread, the task was to write a program/function that takes a positive (or non-negative) integer and outputs/returns another number (not necessarily integer). The robbers task is to unscramble the code the cops used to produce this output.

The cracked code doesn't have to be identical, as long as it has the same length and any revealed characters are in the correct positions. The language must also be the same (version numbers can be different). The output must of course be identical.

No-ops can be used in robber's solution.

The winner of the robbers thread will be the user who has cracked the
most submissions by May 7th 2016. If there's a tie, the user who has cracked submissions with the longest combined code will win.

The submission should be formatted like this:

Language, nn characters (including link to answer), Cop's username

Code:

```<code>function a(n)
    if n<2 then
        return n
    else
        return a(n-1) + a(n-2)
    end
end
</code>```

Output

```<code>a(0) returns 0
a(3) returns 2
</code>```

Optional explanation and comments.

Body:
Hexagony, 7 bytes, Adnan, A005843

?{2'*!@

or

 ? {
2 ' *
 ! @

Try it online!

Simply doubles the input (and assumes positive input). The code is (for once) simply executed in reading order. The code uses three memory edges A, B, C with the memory pointer starting out as shown:

?    Read integer from STDIN into edge A.
{    Move memory pointer forwards to edge B.
2    Set edge B to 2.
'    Move memory pointers backwards to edge C.
*    Multiply edges A and B and store result in C.
!    Print result to STDOUT.
@    Terminate program.


答:
05AB1E, 4 bytes, Paul Picard, A001317

Code:

```<code>$Fx^
</code>```

Try it online!

Explanation:

```<code>$      # Pushes 1 and input
 F     # Pops x, creates a for-loop in range(0, x)
  x    # Pops x, pushes x and 2x
   ^   # Bitwise XOR on the last two elements
       # Implicit, ends the for-loop
       # Implicit, nothing has printed so the last element is printed automatically
</code>```

The sequence basically is a binary Sierpinski triangle:

```<code>f(0)=      1                    =1
f(1)=     1 1                   =3
f(2)=    1 0 1                  =5
f(3)=   1 1 1 1                 =15
f(4)=  1 0 0 0 1                =17
</code>```

And translates to the formula a(n) = a(n - 1) XOR (2 × a(n - 1))

Luckily, I remembered this one :)

Body:
05AB1E, 4 bytes, Paul Picard, A001317

Code:

$Fx^

Try it online!

Explanation:

$      # Pushes 1 and input
 F     # Pops x, creates a for-loop in range(0, x)
  x    # Pops x, pushes x and 2x
   ^   # Bitwise XOR on the last two elements
       # Implicit, ends the for-loop
       # Implicit, nothing has printed so the last element is printed automatically

The sequence basically is a binary Sierpinski triangle:

f(0)=      1                    =1
f(1)=     1 1                   =3
f(2)=    1 0 1                  =5
f(3)=   1 1 1 1                 =15
f(4)=  1 0 0 0 1                =17

And translates to the formula a(n) = a(n - 1) XOR (2 × a(n - 1))

Luckily, I remembered this one :)