答:
HungryBot

Uses a point system to add weight to the value of pursuing each token. Uses a variety of different factors in its consideration, and reevaluates them each turn to ensure its following the best strategy.

function hungryBot(first) {
  // Set up "self"
  var self = this;

  // Determine player order
  this.player = -(first - 2);
  this.enemy = first + 1;

  // Action associative array
  this.actions = ['EAT', 'LEFT', 'RIGHT', 'UP', 'DOWN'];

  //Logic handler
  this.yourMove = function(board) {
    // Determine player object
    var player = board['player' + self.player];
    var enemy = board['player' + self.enemy];

    // Point value action grid
    var actions = [0, 0, 0, 0, 0]; // Associative with "this.actions"

    // Board dimensions
    var size = board.tokens.length;
    var maxDist = size * 2;

    // Colors remaining
    var colors = {
      '#FF0000': 0,
      '#00FF00': 0,
      '#0000FF': 0
    };

    // Averaged value weight
    var average = [0, 0];

    // Total points
    var points = 0;

    // Token holder
    var tokens = [];

    // Token parser
    for (var i = 0, x = 0, y = 0; i < size * size; i += 1, x = i % size, y = i / size | 0) {
      if (!board.tokens[x][y]) {
        continue;
      } else {
        var token = {};
        token.points = board.tokens[x][y].points;
        token.color = board.tokens[x][y].color;
        token.x = x - player.pos[0];
        token.y = y - player.pos[1];
        token.distX = Math.abs(token.x);
        token.distY = Math.abs(token.y);
        token.dist = token.distX + token.distY;
        token.distE = Math.abs(x - enemy.pos[0]) + Math.abs(y - enemy.pos[1]);
        token.value = -token.points - (player.colorBonus + 1) * (token.color == player.lastColor) * ((token.dist == 0) + 1) * 1.618 - (enemy.colorBonus + 1) * (token.color == enemy.lastColor);
        tokens.push(token);
        colors[token.color] += 1;
        points += token.points;
        average[0] += x * token.points;
        average[1] += y * token.points;
      }
    }

    // Determine actual average
    average[0] = average[0] / points | 0;
    average[1] = average[1] / points | 0;

    // Pick best token
    var best = 0;

    // Calculate point values of tokens
    for (i = 0; i < tokens.length; i++) {
      var token = tokens[i];
      // Add remaining numbers of tokens of color as factor
      token.value -= (colors[token.color] / tokens.length) * 1.618;
      // Subtract distance as a factor
      token.value += token.dist;
      // Add distance to average to value
      token.value += (Math.abs(average[0] - (token.x + player.pos[0])) + Math.abs(average[1] - (token.y + player.pos[1]))) / Math.sqrt(2);
      // Consider them higher value if we are closer, and lower if they are
      token.value += ((token.dist - token.distE) / (token.dist + token.distE + 0.001)) * token.dist;
      // Don't go for it if enemy is already there
      token.value += (token.distE == 0 && token.dist > 0) * 100;

      if (tokens[best].value > tokens[i].value || (tokens[best].value === tokens[i].value && Math.round(Math.random()))) {
        best = i;
      }
    }

    // Set token to best token
    var token = tokens[best];

    // What to respond with
    var response = 'PASS';

    // Find best action to get token
    if (token.dist == 0) {
      response = 'EAT'; // We're on the token
    } else if (token.distX >= token.distY) { // Token is more horizontal
      if (token.x < 0) { // Token is left
        response = 'LEFT';
      } else if (token.x > 0) { // Token is right
        response = 'RIGHT';
      }
    } else if (token.distX < token.distY) { // Token is more vertical
      if (token.y < 0) { // Token is above
        response = 'UP';
      } else if (token.y > 0) { // Token is below
        response = 'DOWN';
      }
    }

    // Return response
    return response;
  }
};
```

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>

```


问:
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>

```

答:
KindaRandomAI

Every turn, do the following:
If there is a token at your position, "EAT".
Otherwise, move in a random viable direction, i.e. if you're at the left edge don't say "LEFT".

```<code>kindaRandomAI = function(player1) {
    this.player1 = player1;
    this.yourMove = function(b) {
        var me;
        if (this.player1) {
            me = b.player1;
        } else {
            me = b.player2;
        }
        if (b.tokens[me.pos[0]][me.pos[1]] != false) {
            return "EAT";
        } else {
            var dirs = this.getViableDirections(b, me.pos);
            var rand = Math.floor(Math.random() * dirs.length);
            return dirs[rand];
        }
    }
    this.getViableDirections = function(b, p) {
        var dirs = [];
        if (p[0] > 0) {
            dirs.push("LEFT");
        }
        if (p[1] > 0) {
            dirs.push("UP");
        }
        if (p[1] < b.tokens.length - 1) {
            dirs.push("DOWN");
        }
        if (p[0] < b.tokens.length - 1) {
            dirs.push("RIGHT");
        }
        return dirs;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: KOTH: Everybody loves tokens

Body:
KindaRandomAI

Every turn, do the following:
If there is a token at your position, "EAT".
Otherwise, move in a random viable direction, i.e. if you're at the left edge don't say "LEFT".

kindaRandomAI = function(player1) {
    this.player1 = player1;
    this.yourMove = function(b) {
        var me;
        if (this.player1) {
            me = b.player1;
        } else {
            me = b.player2;
        }
        if (b.tokens[me.pos[0]][me.pos[1]] != false) {
            return "EAT";
        } else {
            var dirs = this.getViableDirections(b, me.pos);
            var rand = Math.floor(Math.random() * dirs.length);
            return dirs[rand];
        }
    }
    this.getViableDirections = function(b, p) {
        var dirs = [];
        if (p[0] > 0) {
            dirs.push("LEFT");
        }
        if (p[1] > 0) {
            dirs.push("UP");
        }
        if (p[1] < b.tokens.length - 1) {
            dirs.push("DOWN");
        }
        if (p[0] < b.tokens.length - 1) {
            dirs.push("RIGHT");
        }
        return dirs;
    }
}


问:
Insert semi-sorted into unsorted array
Welcome to your first day at PPCG Inc. As our newest junior assistant document sorter, you are responsible for making sure all documents we sent down to you are archived in alphabetical order. It's so easy a monkey can do it. Well, metaphorically speaking, as we did hire a monkey to do it. Guess what? Turns out monkeys lack an understanding of our alphabet. Anyway, there's no time to fix the mess there is right now, so just try to not make the situation any worse, ok? Then get to it! If you get hungry, there's bananas over by the water cooler. Good luck!

Job Description

Input

You will receive a list of strings (the archive) and a string that needs to be added to that list (the document)

All strings will contain only uppercase letters, lowercase letters and spaces

Strings will always start and end with a letter

Task

Determine the target position of the document: the position it should receive in the archive. The target position can be determined as follows:

For each position:

Count the amount of strings in the archive before that position that are alphabetically before the document

Count the amount of strings in the archive after that position that are alphabetically after the document

Define the score of the position as the sum of the above two counts

The target position of the document is the position with the highest score

In case of a tie, all positions with the highest score are equally valid as target position. Only one needs to be selected.

When sorting:

Uppercase and lowercase letters are equivalent

Spaces come before letters

Output

The archive with the document added to it in any form

OR

The target position of the document, in either a 0-based or 1-based index

Job evaluation

Fewest bytes wins!

Example I/O

```<code>Archive:
    Applebuck Season
    Friendship is Magic
    The Ticket Master
    Griffon the BrushOff
    Boast Busters
    Bridle Gossip

Document: Dragonshy

Position scores (0-based index):
0: 0 + 3 = 3
1: 1 + 3 = 4
2: 1 + 2 = 3
3: 1 + 1 = 2
4: 1 + 0 = 1
5: 2 + 0 = 2
6: 3 + 0 = 3

Target position: 1
</code>```

答:
Pyth, <s>54</s> <s>52</s> <s>47</s> 45 bytes

```<code>AQVhlG=Ys+m>rH0rd0:G0Nm<rH0rd0gGNI>YZ=ZY=kN;k
</code>```

Expect input is a list, first element is a list of strings (archive), second element is a string (document)

```<code>AQ                                            # initialize G and H with the archive and the document
  VhlG                                        # iterate over the indexes on archive
      =Ys+                                    # concatenate and sum the following scores
          m>rH0rd0:G0N                        # map a string comparison between the document and the archives up to the index, returning true(1) for lower, and false(0) for higher
                      m<rH0rd0gGN             # same as above, but starts at the index and goes up to the end of the archive, returning false(0) for lower, and true(1) for higher
                                 I>YZ         # Check if score is higher than highest
                                     =ZY      # update highest score
                                        =kN;  # update index
                                            k # print index
</code>```

Test here

 Saved 5 bytes on input initialization (thanks @Kenny Lau)

Title: Insert semi-sorted into unsorted array

Body:
Pyth, <s>54</s> <s>52</s> <s>47</s> 45 bytes

AQVhlG=Ys+m>rH0rd0:G0Nm<rH0rd0gGNI>YZ=ZY=kN;k

Expect input is a list, first element is a list of strings (archive), second element is a string (document)

AQ                                            # initialize G and H with the archive and the document
  VhlG                                        # iterate over the indexes on archive
      =Ys+                                    # concatenate and sum the following scores
          m>rH0rd0:G0N                        # map a string comparison between the document and the archives up to the index, returning true(1) for lower, and false(0) for higher
                      m<rH0rd0gGN             # same as above, but starts at the index and goes up to the end of the archive, returning false(0) for lower, and true(1) for higher
                                 I>YZ         # Check if score is higher than highest
                                     =ZY      # update highest score
                                        =kN;  # update index
                                            k # print index

Test here

 Saved 5 bytes on input initialization (thanks @Kenny Lau)


答:
NaiveAI

Starting with r=0, look at all tokens with taxicab distance r away from your position. If there are any, pick one that would give you the highest score if you got it right now. Otherwise, increase r by 1 and try again.

```<code>naiveAI = function(player1) {
  this.player1 = player1;
  this.yourMove = function(b) {
    var me;
    if (this.player1) {
      me = b.player1;
    } else {
      me = b.player2;
    }
    var d = 0;
    var tokenP;
    while (tokenP == undefined) {
      var arr = this.findTokensAtDistance(me.pos, d)
      tokenP = this.findBestToken(arr, b.tokens, me);
      d += 1;
    }
    return this.startAndGoalToCommand(me.pos, tokenP);
  }
  this.findTokensAtDistance = function(p, d) {
    if (d == 0) {
      return [
        [p[0], p[1]]
      ];
    }
    var myArr = [];
    for (i = 0; i <= d; i++) {
      myArr[i] = [i, d - i];
    }
    var mySecArr = [];
    for (i = 0; i <= d; i++) {
      mySecArr[i] = [myArr[i][0] + p[0], myArr[i][1] + p[1]];
    }
    mySecArr[mySecArr.length] = [myArr[0][0] + p[0], -myArr[0][1] + p[1]];
    for (i = 1; i < myArr.length - 1; i++) {
      mySecArr[mySecArr.length] = [-myArr[i][0] + p[0], myArr[i][1] + p[1]]
      mySecArr[mySecArr.length] = [myArr[i][0] + p[0], -myArr[i][1] + p[1]]
      mySecArr[mySecArr.length] = [-myArr[i][0] + p[0], -myArr[i][1] + p[1]]
    }
    mySecArr[mySecArr.length] = [-myArr[myArr.length - 1][0] + p[0], myArr[myArr.length - 1][1] + p[1]];
    return mySecArr;
  }
  this.findBestToken = function(arr, t, player) {
    var tokenPos;
    for (i = 0; i < arr.length; i++) {
      if (arr[i][0] >= 0 && arr[i][0] < t.length && arr[i][1] >= 0 && arr[i][1] < t.length) {
        if (t[arr[i][0]][arr[i][1]] != false && ((tokenPos == undefined) || (this.tokenScore(player, t[arr[i][0]][arr[i][1]]) > this.tokenScore(player, t[tokenPos[0]][tokenPos[1]])))) {
          tokenPos = [arr[i][0],
            [arr[i][1]]
          ];
        }
      }
    }
    return tokenPos;
  }
  this.tokenScore = function(player, token) {
    if (player.lastColor == token.color) {
      return player.colorBonus + 1 + token.points;
    } else {
      return token.points;
    }
  }
  this.startAndGoalToCommand = function(start, goal) {
    var diff = [goal[0] - start[0], goal[1] - start[1]];
    if (diff[0] > 0) {
      return "RIGHT";
    } else if (diff[1] > 0) {
      return "DOWN";
    } else if (diff[1] < 0) {
      return "UP";
    } else if (diff[0] < 0) {
      return "LEFT";
    } else {
      return "EAT";
    }
  }
}
</code>```

Title: KOTH: Everybody loves tokens

Body:
NaiveAI

Starting with r=0, look at all tokens with taxicab distance r away from your position. If there are any, pick one that would give you the highest score if you got it right now. Otherwise, increase r by 1 and try again.

naiveAI = function(player1) {
  this.player1 = player1;
  this.yourMove = function(b) {
    var me;
    if (this.player1) {
      me = b.player1;
    } else {
      me = b.player2;
    }
    var d = 0;
    var tokenP;
    while (tokenP == undefined) {
      var arr = this.findTokensAtDistance(me.pos, d)
      tokenP = this.findBestToken(arr, b.tokens, me);
      d += 1;
    }
    return this.startAndGoalToCommand(me.pos, tokenP);
  }
  this.findTokensAtDistance = function(p, d) {
    if (d == 0) {
      return [
        [p[0], p[1]]
      ];
    }
    var myArr = [];
    for (i = 0; i <= d; i++) {
      myArr[i] = [i, d - i];
    }
    var mySecArr = [];
    for (i = 0; i <= d; i++) {
      mySecArr[i] = [myArr[i][0] + p[0], myArr[i][1] + p[1]];
    }
    mySecArr[mySecArr.length] = [myArr[0][0] + p[0], -myArr[0][1] + p[1]];
    for (i = 1; i < myArr.length - 1; i++) {
      mySecArr[mySecArr.length] = [-myArr[i][0] + p[0], myArr[i][1] + p[1]]
      mySecArr[mySecArr.length] = [myArr[i][0] + p[0], -myArr[i][1] + p[1]]
      mySecArr[mySecArr.length] = [-myArr[i][0] + p[0], -myArr[i][1] + p[1]]
    }
    mySecArr[mySecArr.length] = [-myArr[myArr.length - 1][0] + p[0], myArr[myArr.length - 1][1] + p[1]];
    return mySecArr;
  }
  this.findBestToken = function(arr, t, player) {
    var tokenPos;
    for (i = 0; i < arr.length; i++) {
      if (arr[i][0] >= 0 && arr[i][0] < t.length && arr[i][1] >= 0 && arr[i][1] < t.length) {
        if (t[arr[i][0]][arr[i][1]] != false && ((tokenPos == undefined) || (this.tokenScore(player, t[arr[i][0]][arr[i][1]]) > this.tokenScore(player, t[tokenPos[0]][tokenPos[1]])))) {
          tokenPos = [arr[i][0],
            [arr[i][1]]
          ];
        }
      }
    }
    return tokenPos;
  }
  this.tokenScore = function(player, token) {
    if (player.lastColor == token.color) {
      return player.colorBonus + 1 + token.points;
    } else {
      return token.points;
    }
  }
  this.startAndGoalToCommand = function(start, goal) {
    var diff = [goal[0] - start[0], goal[1] - start[1]];
    if (diff[0] > 0) {
      return "RIGHT";
    } else if (diff[1] > 0) {
      return "DOWN";
    } else if (diff[1] < 0) {
      return "UP";
    } else if (diff[0] < 0) {
      return "LEFT";
    } else {
      return "EAT";
    }
  }
}


问:
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>```

答:
MATL, 80 bytes

Thanks to @LevelRiverSt for a correction

```<code>32>2#fJ*+X:4Mt1Y6Z+l=*2#fJ*+ttXjwYj+K#X<)wt!"tbb6#Yk2#)yw]xxvtXjwYjqGZy1)*+Gw)1e
</code>```

Input is as a 2D array of char, with rows separated by ;. The test cases in this format are

```<code>['Hel         ';'  l      rin';'  o,IAmASt g';'           S';'       !ekan']
['Python']
['P  ngPu  Code ';'r  i  z  d  G ';'o  m  z  n  o ';'gram  lesA  lf']
['   ~ 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']
['  tSyrep    ';'  r    p    ';'  in Sli    ';'   g    Sile';'   Snakes  n';'Ser      ylt';'a eh   ilS  ';'fe w   t    ';'   emo h    ';'     Sre    ']
</code>```

Try it online!

Explanation

The coordinates of each nonspace character is represented by a complex number. For each current character, the next is obtained as that which is closest (minimum absolute difference of their complex coordinates).

To determine the initial char, the two endpoints need to be found. This is done as follows. An endpoint is a nonspace char that has exactly one nonspace neighbour. The number of neighbours is obtained by 2D convolution with a suitable mask. The initial point is the endpoint whose complex coordinate has the least sum of real and imaginary parts; i.e. is closest in Manhattan distance to the complex number 0, or equivalently to 1+1j, which is the complex coordinate of the upper left corner.

```<code>32>      % Take input as 2D char array. Compute 2D array with true for nonspace,
         % false for space
2#f      % Arrays of row and column indices of nonspaces
J*+      % Convert to complex array. Real part is row, imaginary part is column
X:       % Convert to column array
4Mt      % Push arrays of zeros and ones again. Duplicate
1Y6      % Push array [0 1 0; 1 0 1; 0 1 0]. Used as convolution mask to detect
         % neighbours that are nonspace
Z+       % 2D convolution with same size as the input
1=       % True for chars that have only one neighbour (endpoints)
*        % Multiply (logical and): we want nonspaces that are endpoints
2#fJ*+   % Find complex coordinates (as before)
ttXjwYj  % Duplicate. Take real and imaginary parts
+        % Add: gives Manhattan distance to (0,0)
K#X<     % Arg min. Entry with minimum absolute value has least Manhattan
         % distance to (0,0), and thus to (1,1) (top left corner)
)        % Apply as an index, to yield complex coordinate of initial endpoint
wt!      % Swap, duplicate, transpose.
         % The stack contains, bottom to top: complex coordinates of initial
         % endpoint, column array with all complex coordinates, row array of all
         % coordinates. The latter is used (and consumed) by the next "for"
         % statement to generate that many iterations
"        % For loop. Number of iterations is number of nonspaces
  tbb    %   Duplicate, bubble up twice (rearrange is stack)
  6#Yk   %   Find which of the remaining points is closest to current point. This
         %   is the next char in the string
  2#)    %   Remove the point with that index from the array of complex
         %   coordinates. Push that point and the rest of the array
  yw     %   Duplicate extracted point, swap
]        % End for
xx       % Delete top two elements of the stack
v        % Concatenate all stack contents into a column array. This array
         % contains the complex coordinates of chars sorted to form the string
tXjwYj   % Extract real part and imaginary part
GZy1)    % Number of rows of input. Needed to convert to linear index
*+       % Convert rows and columns to linear index
Gw       % Push input below that
)        % Index to get the original chars with the computed order
1e       % Force the result to be a row array (string). Implicitly display
</code>```

Title: De-Snakify a String

Body:
MATL, 80 bytes

Thanks to @LevelRiverSt for a correction

32>2#fJ*+X:4Mt1Y6Z+l=*2#fJ*+ttXjwYj+K#X<)wt!"tbb6#Yk2#)yw]xxvtXjwYjqGZy1)*+Gw)1e

Input is as a 2D array of char, with rows separated by ;. The test cases in this format are

['Hel         ';'  l      rin';'  o,IAmASt g';'           S';'       !ekan']
['Python']
['P  ngPu  Code ';'r  i  z  d  G ';'o  m  z  n  o ';'gram  lesA  lf']
['   ~ 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']
['  tSyrep    ';'  r    p    ';'  in Sli    ';'   g    Sile';'   Snakes  n';'Ser      ylt';'a eh   ilS  ';'fe w   t    ';'   emo h    ';'     Sre    ']

Try it online!

Explanation

The coordinates of each nonspace character is represented by a complex number. For each current character, the next is obtained as that which is closest (minimum absolute difference of their complex coordinates).

To determine the initial char, the two endpoints need to be found. This is done as follows. An endpoint is a nonspace char that has exactly one nonspace neighbour. The number of neighbours is obtained by 2D convolution with a suitable mask. The initial point is the endpoint whose complex coordinate has the least sum of real and imaginary parts; i.e. is closest in Manhattan distance to the complex number 0, or equivalently to 1+1j, which is the complex coordinate of the upper left corner.

32>      % Take input as 2D char array. Compute 2D array with true for nonspace,
         % false for space
2#f      % Arrays of row and column indices of nonspaces
J*+      % Convert to complex array. Real part is row, imaginary part is column
X:       % Convert to column array
4Mt      % Push arrays of zeros and ones again. Duplicate
1Y6      % Push array [0 1 0; 1 0 1; 0 1 0]. Used as convolution mask to detect
         % neighbours that are nonspace
Z+       % 2D convolution with same size as the input
1=       % True for chars that have only one neighbour (endpoints)
*        % Multiply (logical and): we want nonspaces that are endpoints
2#fJ*+   % Find complex coordinates (as before)
ttXjwYj  % Duplicate. Take real and imaginary parts
+        % Add: gives Manhattan distance to (0,0)
K#X<     % Arg min. Entry with minimum absolute value has least Manhattan
         % distance to (0,0), and thus to (1,1) (top left corner)
)        % Apply as an index, to yield complex coordinate of initial endpoint
wt!      % Swap, duplicate, transpose.
         % The stack contains, bottom to top: complex coordinates of initial
         % endpoint, column array with all complex coordinates, row array of all
         % coordinates. The latter is used (and consumed) by the next "for"
         % statement to generate that many iterations
"        % For loop. Number of iterations is number of nonspaces
  tbb    %   Duplicate, bubble up twice (rearrange is stack)
  6#Yk   %   Find which of the remaining points is closest to current point. This
         %   is the next char in the string
  2#)    %   Remove the point with that index from the array of complex
         %   coordinates. Push that point and the rest of the array
  yw     %   Duplicate extracted point, swap
]        % End for
xx       % Delete top two elements of the stack
v        % Concatenate all stack contents into a column array. This array
         % contains the complex coordinates of chars sorted to form the string
tXjwYj   % Extract real part and imaginary part
GZy1)    % Number of rows of input. Needed to convert to linear index
*+       % Convert rows and columns to linear index
Gw       % Push input below that
)        % Index to get the original chars with the computed order
1e       % Force the result to be a row array (string). Implicitly display


问:
Ponderous primality testing
One of my favorite algorithms was posted on Stack Overflow as an answer to What is the fastest way to generate prime number recursively?. In pseudocode:

Nathan's algorithm

```<code>bool isPrime(int n):
    if (n < 2) return false
    for p in 2..n-1:
        if (isPrime(p) && n%p == 0) return false
    return true
</code>```

This program is lovely because it doesn't have any wasted steps (in the author's words, "it's quite efficient because it only needs to test the prime factors") but still manages to take far longer than any reasonable algorithm. For example, compare the naive algorithm:

Unoptimized trial division

```<code>bool isPrime(int n):
    if (n < 2) return false
    for p in 2..n-1:
        if (n%p == 0) return false
    return true
</code>```

This requires 10005 ≈ 104 divisions to test 10007, the smallest 5-digit prime. By contrast, Nathan's algorithm takes more than 10370 divisions, making it 10366 times slower. If every electron was a 1-googol GHz computer, and this program had been running across all electrons in the universe since the Big Bang, it wouldn't even be close to 1% done.

The task is to write a program, in the language of your choice to test if a given number is prime as slowly as possible. The programs may not simply waste time by idling or executing unused loops; it should be clever in its sloth.

Scoring

This is a popularity-contest, so the (valid) answer with the most votes wins. Golfing is neither required nor recommended. Suggested criteria for voting:

Creativity: How does the program manage to do so much work?

Originality: Does the program use a novel approach?

Reasonableness: Does the code look reasonable at a glance? It's best if there are not sections which could obviously be excised to speed it up.

Simplicity: A single, well-executed idea is better than a combination of unrelated ideas (though cleverly combining approaches is encouraged).

I consider Nathan's program to embody all four principles. As such, if the original author posts the original program here I will upvote it.

答:
Python 2, Really slow

```<code>import time

def isPrime(n):
    if type(n) is not int: return False
    if n < 2: return False
    if n == 2: return True
    has_composite_factor = False
    for i in range(2, n):
        i_is_prime = isPrime(i)
        if n % i == 0:
            if not has_composite_factor and i_is_prime:
                has_composite_factor  = True
    return not has_composite_factor

def time_it(n):
    start = time.clock()
    prime = isPrime(n)
    end = time.clock()

    return end - start

for i in range(20, 30):
    print "{}: {}".format(i, time_it(i))
</code>```

If a number is prime, it stands to reason that all of it's factors must also be prime. If we can find a single composite factor, then this number cleary isn't prime. We must also check to see if the number is valid, which is why we check type(n) and n < 2.

This runs decently fast on n < 20 but takes several seconds once you hit 25. Here is how long it takes to calculate 20-30:

```<code>20: 0.141494
21: 0.282143
22: 0.565975
23: 1.132836
24: 2.266971
25: 4.525667
26: 9.050018
27: 18.110675
28: 36.372516
29: 72.920298
</code>```

Title: Ponderous primality testing

Body:
Python 2, Really slow

import time

def isPrime(n):
    if type(n) is not int: return False
    if n < 2: return False
    if n == 2: return True
    has_composite_factor = False
    for i in range(2, n):
        i_is_prime = isPrime(i)
        if n % i == 0:
            if not has_composite_factor and i_is_prime:
                has_composite_factor  = True
    return not has_composite_factor

def time_it(n):
    start = time.clock()
    prime = isPrime(n)
    end = time.clock()

    return end - start

for i in range(20, 30):
    print "{}: {}".format(i, time_it(i))

If a number is prime, it stands to reason that all of it's factors must also be prime. If we can find a single composite factor, then this number cleary isn't prime. We must also check to see if the number is valid, which is why we check type(n) and n < 2.

This runs decently fast on n < 20 but takes several seconds once you hit 25. Here is how long it takes to calculate 20-30:

20: 0.141494
21: 0.282143
22: 0.565975
23: 1.132836
24: 2.266971
25: 4.525667
26: 9.050018
27: 18.110675
28: 36.372516
29: 72.920298


问:
N-queen-and-equine quine
There is a variant of the well-known N-queens problem which involves queens and knights and is said to be "considerably more difficult" 1. The problem statement is as follows:

You must place an equal number of knights ♞ and queens ♛ on a chessboard
  such that no piece attacks any other piece. What is the maximum number
  of pieces you can so place on the board, and how many different ways
  can you do it?

In this code-golf challenge, you will be given an input n between 3 and 32 (in a way that is the most suitable for your language). For a given n, there might be zero or more solutions to the above problem. In case there is no solution, you must output/return nothing (nil, empty string, false, ...). Otherwise, you must give two results:

A solution board (see below) for size n where it is not possible to add a queen or a knight chess piece without having any piece being under attack. There must be an equal number of queens and knights.

The source of a program to be run which accepts no input and gives (i) another solution (or nothing) for the same size n, in the same format, as well as (ii) another program for the next solution (and so on...).

Note that:

The sequence of programs must never return the same board twice, must cover all possible solutions for the problem of size n and eventually has to terminate (producing no output).

You can either return two values, return one and print the other, or print the two return values.

However, if you print both the board and the next program, the board must not be considered to be a part of the next program (I'd recommend printing the board in comment, or use both standard output and error streams).

The program-as-a-return-value must be a string, not a closure.

Board format

A board is a square of size n.

A board cell can be empty, a queen or a knight.

You must choose distinct values for each kind of cells (i.e. you can use other symbols than Q, N when printing the board).

If you return a non-string board, it must be an ordered collection of the n2 values of the board (e.g. matrix, vector or list in row/column-major order, ...).

If you print the board, you can either print it squared, or as a line.
For example, a solution board of size 4 can be printed as follows (spaces not required; symbols at your discretion):

```<code>Q - - -
- - - -
- - - -
- - N -
</code>```

If you feel so, you can also output:

```<code>♛ · · ·
· · · ·
· · · ·
· · ♞ ·
</code>```

... but this is sufficient:

```<code>Q-------------N-
</code>```

It does not matter if you iterate through cells in a row-major or column-major order, because there are symmetrical solutions.
For example, the solutions for n=4 are:

```<code>Q------N--------
Q----------N----
Q------------N--
Q-------------N-
-Q----------N---
-Q------------N-
-Q-------------N
--Q---------N---
--Q----------N--
--Q------------N
---QN-----------
---Q----N-------
---Q---------N--
---Q----------N-
---NQ-----------
----Q------N----
----Q----------N
N------Q--------
-------QN-------
-------Q----N---
---N----Q-------
-------NQ-------
--------Q------N
N----------Q----
----N------Q----
-----------QN---
-N----------Q---
--N---------Q---
-------N----Q---
-----------NQ---
N------------Q--
--N----------Q--
---N---------Q--
N-------------Q-
-N------------Q-
---N----------Q-
-N-------------Q
--N------------Q
----N----------Q
--------N------Q
</code>```

You can also look at the solutions for n=5 as matrices; the boards contains #, q and n symbols, which are empty cells of different kinds (see my answer below).
I count 2836 boards for n=6, like in Sleafar's answer (I introduced a bug when reducing byte count, but it is fixed now).

Many thanks to Sleafar for finding not one but two bugs in my code.

Score

Shortest code in bytes win.

We measure the size of the first program, the one which accepts n.

1. Queens and Knights, by Roger K.W. Hui (beware! contains a solution)

答:
Groovy, 515 bytes

X=0;Y="N="+args[0]+";M=N*N;S=[];def f(b,i,j,v){(i..<j).findAll{k->!(0..<M).any{l->w=b[l];r=(k.intdiv(N)-l.intdiv(N)).abs();c=(k%N-l%N).abs();s=v+w;w>0&&(k==l||(r==0||c==0||r==c?s<4:r<3&&c<3&&s>2))}}.collect{a=b.clone();a[it]=v;[it,a]}};def r(b,q,n){f(b,q,M,1).each{i->f(i[1],n,M,2).each{j->if(f(j[1],0,M,1).any{f(it[1],0,M,2)}){r(j[1],i[0],j[0])}else{S.add(j[1])}}}};r(new int[M],0,0);if(x<S.size()){sprintf('//%s%cX=%d;Y=%c%s%c;print(Eval.xy(X,Y,Y))',S[x].toString(),10,x+1,34,y,34)}else{''}";print(Eval.xy(X,Y,Y))
```

<h2>Testing</h2>

<p>Provide <strong>n</strong> as a command line argument:</p>

```groovy qak.groovy 4
```

<p>The first line of the output is always a solution as a comment (0=empty, 1=queen, 2=knight), followed by the code in the second line:</p>

```//[1, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0]
X=1;Y="N=4;M=N*N;S=[];def f(b,i,j,v){(i..<j).findAll{k->!(0..<M).any{l->w=b[l];r=(k.intdiv(N)-l.intdiv(N)).abs();c=(k%N-l%N).abs();s=v+w;w>0&&(k==l||(r==0||c==0||r==c?s<4:r<3&&c<3&&s>2))}}.collect{a=b.clone();a[it]=v;[it,a]}};def r(b,q,n){f(b,q,M,1).each{i->f(i[1],n,M,2).each{j->if(f(j[1],0,M,1).any{f(it[1],0,M,2)}){r(j[1],i[0],j[0])}else{S.add(j[1])}}}};r(new int[M],0,0);if(x<S.size()){sprintf('//%s%cX=%d;Y=%c%s%c;print(Eval.xy(X,Y,Y))',S[x].toString(),10,x+1,34,y,34)}else{''}";print(Eval.xy(X,Y,Y))
```

<p>The following script can be used for automated testing (provide <strong>n</strong> as an argument again):</p>

```#!/bin/bash
set -e
test -n "$1"
groovy qak.groovy "$1" > t
while test -s t; do
    head -n1 t
    groovy t > t2
    mv t2 t
done
```

<p>Because I tried to make the solution as small as possible, it is <strong>very slow</strong> (see below for details). I tested only n=4 with this version to see if the quineification works.</p>

<h2>Results</h2>

<p><strong>n=4:</strong> 40 solutions (converted format)<br>
<strong>n=5:</strong> 172 solutions (converted format)<br>
<strong>n=6:</strong> 2836 solutions (converted format)</p>

<h2>Algorithm</h2>

<p>This is a slightly ungolfed non-quine version of the solution:</p>

<pre class="lang-groovy prettyprint-override"><code>N=args[0] as int
M=N*N
S=[]

/**
 * Generate a list of valid posibilities to place a new piece.
 * @param b Starting board.
 * @param i Start of the index range to check (inclusive).
 * @param j End of the index range to check (exclusive).
 * @param v Value of the new piece (1=queen, 2=knight).
 * @return A pair with the index of the new piece and a corresponding board for each possibility.
 */
def f(b,i,j,v){
    (i..<j).findAll{k->
        !(0..<M).any{l->
            w=b[l]
            r=(k.intdiv(N)-l.intdiv(N)).abs()
            c=(k%N-l%N).abs()
            s=v+w
            w>0&&(k==l||(r==0||c==0||r==c?s<4:r<3&&c<3&&s>2))
        }
    }.collect{
        a=b.clone();a[it]=v;[it,a]
    }
}

/**
 * Recursively look for solutions.
 * @param b Starting board.
 * @param q Start of the index range to check for queens.
 * @param n Start of the index range to check for knights.
 */
def r(b,q,n){
    f(b,q,M,1).each{i->
        f(i[1],n,M,2).each{j->
            if(f(j[1],0,M,1).any{f(it[1],0,M,2)}){
                r(j[1],i[0],j[0])
            }else{
                S.add(j[1])
            }
        }
    }
}

r(new int[M],0,0)
S.each{println(it)}
</code>```

Quineification

I used a very simple approach here to keep the code size low.

```<code>X=0;Y="...";print(Eval.xy(X,Y,Y))
</code>```

The variable X holds the index of the solution to print next. Y holds a modified copy of the algorithm above, which is used to calculate all solutions and then select only one of them, which is the reason for it being so slow. The advantage of this solution is, that it doesn't require much additional code. The code stored in Y is executed with help of the Eval class (a true quine is not required).

The modified code prints the solution pointed to by X, increases X and appends a copy of itself:

```<code>//[...]
X=1;Y="...";print(Eval.xy(X,Y,Y))
</code>```

I also tried to output all solutions as code for the second step, but for n=6 it was producing too much code for Groovy to handle.

Title: N-queen-and-equine quine

Body:
Groovy, 515 bytes

X=0;Y="N="+args[0]+";M=N*N;S=[];def f(b,i,j,v){(i..<j).findAll{k->!(0..<M).any{l->w=b[l];r=(k.intdiv(N)-l.intdiv(N)).abs();c=(k%N-l%N).abs();s=v+w;w>0&&(k==l||(r==0||c==0||r==c?s<4:r<3&&c<3&&s>2))}}.collect{a=b.clone();a[it]=v;[it,a]}};def r(b,q,n){f(b,q,M,1).each{i->f(i[1],n,M,2).each{j->if(f(j[1],0,M,1).any{f(it[1],0,M,2)}){r(j[1],i[0],j[0])}else{S.add(j[1])}}}};r(new int[M],0,0);if(x<S.size()){sprintf('//%s%cX=%d;Y=%c%s%c;print(Eval.xy(X,Y,Y))',S[x].toString(),10,x+1,34,y,34)}else{''}";print(Eval.xy(X,Y,Y))

Testing

Provide n as a command line argument:

groovy qak.groovy 4

The first line of the output is always a solution as a comment (0=empty, 1=queen, 2=knight), followed by the code in the second line:

//[1, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0]
X=1;Y="N=4;M=N*N;S=[];def f(b,i,j,v){(i..<j).findAll{k->!(0..<M).any{l->w=b[l];r=(k.intdiv(N)-l.intdiv(N)).abs();c=(k%N-l%N).abs();s=v+w;w>0&&(k==l||(r==0||c==0||r==c?s<4:r<3&&c<3&&s>2))}}.collect{a=b.clone();a[it]=v;[it,a]}};def r(b,q,n){f(b,q,M,1).each{i->f(i[1],n,M,2).each{j->if(f(j[1],0,M,1).any{f(it[1],0,M,2)}){r(j[1],i[0],j[0])}else{S.add(j[1])}}}};r(new int[M],0,0);if(x<S.size()){sprintf('//%s%cX=%d;Y=%c%s%c;print(Eval.xy(X,Y,Y))',S[x].toString(),10,x+1,34,y,34)}else{''}";print(Eval.xy(X,Y,Y))

The following script can be used for automated testing (provide n as an argument again):

#!/bin/bash
set -e
test -n "$1"
groovy qak.groovy "$1" > t
while test -s t; do
    head -n1 t
    groovy t > t2
    mv t2 t
done

Because I tried to make the solution as small as possible, it is very slow (see below for details). I tested only n=4 with this version to see if the quineification works.

Results

n=4: 40 solutions (converted format)

n=5: 172 solutions (converted format)

n=6: 2836 solutions (converted format)

Algorithm

This is a slightly ungolfed non-quine version of the solution:

N=args[0] as int
M=N*N
S=[]

/**
 * Generate a list of valid posibilities to place a new piece.
 * @param b Starting board.
 * @param i Start of the index range to check (inclusive).
 * @param j End of the index range to check (exclusive).
 * @param v Value of the new piece (1=queen, 2=knight).
 * @return A pair with the index of the new piece and a corresponding board for each possibility.
 */
def f(b,i,j,v){
    (i..<j).findAll{k->
        !(0..<M).any{l->
            w=b[l]
            r=(k.intdiv(N)-l.intdiv(N)).abs()
            c=(k%N-l%N).abs()
            s=v+w
            w>0&&(k==l||(r==0||c==0||r==c?s<4:r<3&&c<3&&s>2))
        }
    }.collect{
        a=b.clone();a[it]=v;[it,a]
    }
}

/**
 * Recursively look for solutions.
 * @param b Starting board.
 * @param q Start of the index range to check for queens.
 * @param n Start of the index range to check for knights.
 */
def r(b,q,n){
    f(b,q,M,1).each{i->
        f(i[1],n,M,2).each{j->
            if(f(j[1],0,M,1).any{f(it[1],0,M,2)}){
                r(j[1],i[0],j[0])
            }else{
                S.add(j[1])
            }
        }
    }
}

r(new int[M],0,0)
S.each{println(it)}

Quineification

I used a very simple approach here to keep the code size low.

X=0;Y="...";print(Eval.xy(X,Y,Y))

The variable X holds the index of the solution to print next. Y holds a modified copy of the algorithm above, which is used to calculate all solutions and then select only one of them, which is the reason for it being so slow. The advantage of this solution is, that it doesn't require much additional code. The code stored in Y is executed with help of the Eval class (a true quine is not required).

The modified code prints the solution pointed to by X, increases X and appends a copy of itself:

//[...]
X=1;Y="...";print(Eval.xy(X,Y,Y))

I also tried to output all solutions as code for the second step, but for n=6 it was producing too much code for Groovy to handle.


答:
C, 272 bytes

```<code>#define E j+(p/2*i+1)*(p%2*2-1)
#define X(Y) a[Y]&&a[Y]-32
char A[999],*a=A+99;j,p,t;i;main(c){for(;gets(++j+a);j+=i)i=strlen(a+j);for(c=j;j--;){for(t=p=4;p--;)t-=X(E);t==3&&X(j)?c=c%i+c/i<j%i+j/i?c:j:0;}for(j=c;c;){putchar(a[j]),a[j]=0;for(c=0,p=4;!c*p--;)X(E)?c=j=E:0;}}
</code>```

Look at @Zunga's source. Now look at mine. Want to know how I got the extra 91-bytes?

Ungolfed:

```<code>#define E j+(p/2*i+1)*(p%2*2-1)
#define X(Y) a[Y]&&a[Y]-32  //can be more concise, see @Zunga's
  //and then doesn't need the define
char A[999],*a=A+99;j,p,t;i;
main(c){for(;gets(++j+a);j+=i)
i=strlen(a+j); //we don't need to know the length of a line
  //in @Zunga's solution, lines are spaced a constant distance apart
for(c=j;j--;){
for(t=p=4;p--;)t-=X(E);  //a ton of bytes can be saved with determining
  //the neighbors, see @Zunga's source
t==3&&X(j)?
c=c%i+c/i<j%i+j/i?c:j:0;}  //we search for ends of the snake,
  //and compute the Manhattan distance
for(j=c;c;){putchar(a[j]),a[j]=0;
for(c=0,p=4;!c*p--;)  //determining the neighbors again
X(E)?c=j=E:0;}}
</code>```

Title: De-Snakify a String

Body:
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>```

Body:
C, 272 bytes

#define E j+(p/2*i+1)*(p%2*2-1)
#define X(Y) a[Y]&&a[Y]-32
char A[999],*a=A+99;j,p,t;i;main(c){for(;gets(++j+a);j+=i)i=strlen(a+j);for(c=j;j--;){for(t=p=4;p--;)t-=X(E);t==3&&X(j)?c=c%i+c/i<j%i+j/i?c:j:0;}for(j=c;c;){putchar(a[j]),a[j]=0;for(c=0,p=4;!c*p--;)X(E)?c=j=E:0;}}

Look at @Zunga's source. Now look at mine. Want to know how I got the extra 91-bytes?

Ungolfed:

#define E j+(p/2*i+1)*(p%2*2-1)
#define X(Y) a[Y]&&a[Y]-32  //can be more concise, see @Zunga's
  //and then doesn't need the define
char A[999],*a=A+99;j,p,t;i;
main(c){for(;gets(++j+a);j+=i)
i=strlen(a+j); //we don't need to know the length of a line
  //in @Zunga's solution, lines are spaced a constant distance apart
for(c=j;j--;){
for(t=p=4;p--;)t-=X(E);  //a ton of bytes can be saved with determining
  //the neighbors, see @Zunga's source
t==3&&X(j)?
c=c%i+c/i<j%i+j/i?c:j:0;}  //we search for ends of the snake,
  //and compute the Manhattan distance
for(j=c;c;){putchar(a[j]),a[j]=0;
for(c=0,p=4;!c*p--;)  //determining the neighbors again
X(E)?c=j=E:0;}}


问:
Greatest Common Divisor
Your task is to compute the greatest common divisor (GCD) of two given integers in as few bytes of code as possible.

You may write a program or function, taking input and returning output via any of our accepted standard methods (including STDIN/STDOUT, function parameters/return values, command-line arguments, etc.).

Input will be two non-negative integers. You should be able to handle either the full range supported by your language's default integer type, or the range [0,255], whichever is greater. You are guaranteed that at least one of the inputs will be non-zero.

You are not allowed to use built-ins that compute either the GCD or the LCM (least common multiple).

Standard code-golf rules apply.

Test Cases

```<code>0 2     => 2
6 0     => 6
30 42   => 6
15 14   => 1
7 7     => 7
69 25   => 1
21 12   => 3
169 123 => 1
20 142  => 2
101 202 => 101
</code>```

答:
Pyth, 2 bytes

```<code>iE
</code>```

Try it here!

Input as integer on two separate lines. Just uses a builtin.

Title: Greatest Common Divisor

Body:
Pyth, 2 bytes

iE

Try it here!

Input as integer on two separate lines. Just uses a builtin.


答:
Jelly, 7 bytes

```<code>ṛß%ðḷṛ?
</code>```

Recursive implementation of the Euclidean algorithm. Try it online!

If built-ins weren't forbidden, g (1 byte, built-in GCD) would achieve a better score.

How it works

```<code>ṛß%ðḷṛ?  Main link. Arguments: a, b

   ð     Convert the chain to the left into a link; start a new, dyadic chain.
 ß       Recursively call the main link...
ṛ %        with b and a % b as arguments.
     ṛ?  If the right argument (b) is non-zero, execute the link.
    ḷ    Else, yield the left argument (a).
</code>```

Title: Greatest Common Divisor

Body:
Your task is to compute the greatest common divisor (GCD) of two given integers in as few bytes of code as possible.

You may write a program or function, taking input and returning output via any of our accepted standard methods (including STDIN/STDOUT, function parameters/return values, command-line arguments, etc.).

Input will be two non-negative integers. You should be able to handle either the full range supported by your language's default integer type, or the range [0,255], whichever is greater. You are guaranteed that at least one of the inputs will be non-zero.

You are not allowed to use built-ins that compute either the GCD or the LCM (least common multiple).

Standard code-golf rules apply.

Test Cases

```<code>0 2     => 2
6 0     => 6
30 42   => 6
15 14   => 1
7 7     => 7
69 25   => 1
21 12   => 3
169 123 => 1
20 142  => 2
101 202 => 101
</code>```

Body:
Jelly, 7 bytes

ṛß%ðḷṛ?

Recursive implementation of the Euclidean algorithm. Try it online!

If built-ins weren't forbidden, g (1 byte, built-in GCD) would achieve a better score.

How it works

ṛß%ðḷṛ?  Main link. Arguments: a, b

   ð     Convert the chain to the left into a link; start a new, dyadic chain.
 ß       Recursively call the main link...
ṛ %        with b and a % b as arguments.
     ṛ?  If the right argument (b) is non-zero, execute the link.
    ḷ    Else, yield the left argument (a).


答:
Python 3, 31

Saved 3 bytes thanks to Sp3000.

```<code>g=lambda a,b:b and g(b,a%b)or a
</code>```

Title: Greatest Common Divisor

Body:
Python 3, 31

Saved 3 bytes thanks to Sp3000.

g=lambda a,b:b and g(b,a%b)or a


Title: Greatest Common Divisor

Body:
C#, 24 bytes

x=(a,b)=>b<1?a:x(b,a%b);


答:
Python 3, 135 167 Bytes

```<code>def a(b,c):a=[sum(map(lambda x:x.lower()>c.lower(),b[i:]))+sum(map(lambda x:x.lower()<c.lower(),b[:i]))for i in range(0,len(b)+1)];b.insert(a.index(max(a)),c);print(b)
</code>```

Title: Insert semi-sorted into unsorted array

Body:
Welcome to your first day at PPCG Inc. As our newest junior assistant document sorter, you are responsible for making sure all documents we sent down to you are archived in alphabetical order. It's so easy a monkey can do it. Well, metaphorically speaking, as we did hire a monkey to do it. Guess what? Turns out monkeys lack an understanding of our alphabet. Anyway, there's no time to fix the mess there is right now, so just try to not make the situation any worse, ok? Then get to it! If you get hungry, there's bananas over by the water cooler. Good luck!

Job Description

Input

You will receive a list of strings (the archive) and a string that needs to be added to that list (the document)

All strings will contain only uppercase letters, lowercase letters and spaces

Strings will always start and end with a letter

Task

Determine the target position of the document: the position it should receive in the archive. The target position can be determined as follows:

For each position:

Count the amount of strings in the archive before that position that are alphabetically before the document

Count the amount of strings in the archive after that position that are alphabetically after the document

Define the score of the position as the sum of the above two counts

The target position of the document is the position with the highest score

In case of a tie, all positions with the highest score are equally valid as target position. Only one needs to be selected.

When sorting:

Uppercase and lowercase letters are equivalent

Spaces come before letters

Output

The archive with the document added to it in any form

OR

The target position of the document, in either a 0-based or 1-based index

Job evaluation

Fewest bytes wins!

Example I/O

```<code>Archive:
    Applebuck Season
    Friendship is Magic
    The Ticket Master
    Griffon the BrushOff
    Boast Busters
    Bridle Gossip

Document: Dragonshy

Position scores (0-based index):
0: 0 + 3 = 3
1: 1 + 3 = 4
2: 1 + 2 = 3
3: 1 + 1 = 2
4: 1 + 0 = 1
5: 2 + 0 = 2
6: 3 + 0 = 3

Target position: 1
</code>```

Body:
Python 3, 135 167 Bytes

def a(b,c):a=[sum(map(lambda x:x.lower()>c.lower(),b[i:]))+sum(map(lambda x:x.lower()<c.lower(),b[:i]))for i in range(0,len(b)+1)];b.insert(a.index(max(a)),c);print(b)


答:
Julia, <s>21</s> 15 bytes

a\b=a>0?b%a\a:b
```

<p>Recursive implementation of the Euclidean algorithm. Try it online!</p>

<p>If built-ins weren't forbidden, <code>gcd</code> (3 bytes, built-in GCD) would achieve a better score.</p>

<h3>How it works</h3>

```a\b=             Redefine the binary operator \ as follows:
    a>0?     :       If a > 0:
        b%a\a        Resursively apply \ to b%a and a. Return the result.
              b      Else, return b.
```

Title: Greatest Common Divisor

Body:
Julia, <s>21</s> 15 bytes

a\b=a>0?b%a\a:b

Recursive implementation of the Euclidean algorithm. Try it online!

If built-ins weren't forbidden, gcd (3 bytes, built-in GCD) would achieve a better score.

How it works

a\b=             Redefine the binary operator \ as follows:
    a>0?     :       If a > 0:
        b%a\a        Resursively apply \ to b%a and a. Return the result.
              b      Else, return b.


答:
Javascript, 21 bytes.

I think I'm doing this right, I'm still super new to Javascript.

```<code>g=a=>b=>b?g(b)(a%b):a
</code>```

Title: Greatest Common Divisor

Body:
Javascript, 21 bytes.

I think I'm doing this right, I'm still super new to Javascript.

g=a=>b=>b?g(b)(a%b):a


答:
05AB1E, 10 bytes

Code:

```<code>EàF¹N%O>iN
</code>```

Try it online!

With built-ins:

```<code>¿
</code>```

Explanation:

```<code>¿   # Implicit input, computes the greatest common divisor.
    # Input can be in the form a \n b, which computes gcd(a, b)
    # Input can also be a list in the form [a, b, c, ...], which computes the gcd of
      multiple numbers.
</code>```

Try it online! or Try with multiple numbers.

Title: Greatest Common Divisor

Body:
05AB1E, 10 bytes

Code:

EàF¹N%O>iN

Try it online!

With built-ins:

¿

Explanation:

¿   # Implicit input, computes the greatest common divisor.
    # Input can be in the form a \n b, which computes gcd(a, b)
    # Input can also be a list in the form [a, b, c, ...], which computes the gcd of
      multiple numbers.

Try it online! or Try with multiple numbers.


答:
TI-Basic, 27 bytes

```<code>Prompt A,B:While B:B→T:BfPart(A/B→B:T→A:End:A
</code>```

35 byte recursive solution without gcd( or lcm( built-ins (requires 2.53 MP operating system or higher, must be named prgmG):

```<code>If Ans(2:Then:{Ans(2),remainder(Ans(1),Ans(2:prgmG:Else:Disp Ans(1:End
</code>```

You would pass arguments to the recursive variant as {A,B} so for example {1071, 462}:prgmG would yield 21.

TI-Basic, 10 bytes

```<code>Prompt A,B:gcd(A,B
</code>```

Not allowed due to new rule forbidding gcd built-ins

17 byte solution without gcd( built-in

```<code>Prompt A,B:abs(AB)/lcm(A,B
</code>```

Not allowed due to new rule forbidding lcm built-ins

Title: Greatest Common Divisor

Body:
TI-Basic, 27 bytes

Prompt A,B:While B:B→T:BfPart(A/B→B:T→A:End:A

35 byte recursive solution without gcd( or lcm( built-ins (requires 2.53 MP operating system or higher, must be named prgmG):

If Ans(2:Then:{Ans(2),remainder(Ans(1),Ans(2:prgmG:Else:Disp Ans(1:End

You would pass arguments to the recursive variant as {A,B} so for example {1071, 462}:prgmG would yield 21.

TI-Basic, 10 bytes

Prompt A,B:gcd(A,B

Not allowed due to new rule forbidding gcd built-ins

17 byte solution without gcd( built-in

Prompt A,B:abs(AB)/lcm(A,B

Not allowed due to new rule forbidding lcm built-ins

ContentLicense: CC BY-SA 4.0


答:
Hoon, 20 bytes

```<code>|=
{@ @}
d:(egcd +<)
</code>```

--

Hoon #2, 39 bytes

```<code>|=
{a/@ b/@}
?~
b
a
$(a b, b (mod a b))
</code>```

Oddly, the only implementation in Hoon's stdlib for GCD is the one in use for its RSA crypto, which also returns some other values. I have to wrap it in a function that takes only d from the output.

The other implementation is just the default recursive GCD definition.

Title: Greatest Common Divisor

Body:
Hoon, 20 bytes

|=
{@ @}
d:(egcd +<)

--

Hoon #2, 39 bytes

|=
{a/@ b/@}
?~
b
a
$(a b, b (mod a b))

Oddly, the only implementation in Hoon's stdlib for GCD is the one in use for its RSA crypto, which also returns some other values. I have to wrap it in a function that takes only d from the output.

The other implementation is just the default recursive GCD definition.


答:
GML, 57 bytes

```<code>a=argument0
b=argument1
while b{t=b;b=a mod b;a=t}return a
</code>```

Title: Greatest Common Divisor

Body:
GML, 57 bytes

a=argument0
b=argument1
while b{t=b;b=a mod b;a=t}return a


答:
Mathematica, 27 bytes

```<code>If[#<1,#2,#0[#2,#~Mod~#2]]&
</code>```

Not much to see here.

Title: Greatest Common Divisor

Body:
Mathematica, 27 bytes

If[#<1,#2,#0[#2,#~Mod~#2]]&

Not much to see here.


问:
Create a Boolean parser
What you need to do is create a Boolean parser.

Boolean expressions, in case you haven't heard of them yet, have two inputs and one output. There are four 'gates' in boolean arithmetic, namely OR (represented by |), AND (represented by &), NOT (which are used a bit like brackets : / and \ note, I could have used !, but you can't use them as brackets, since !!!! is ambiguous (//\\ or /\/\)) and XOR (represented by ^). These gates operate on their inputs which are either true or false. We can list the possible inputs (A and B in this case) and the outputs (O) using a truth table as follows:

```<code>XOR
A|B|O
-----
0|0|0
0|1|1
1|0|1
1|1|0

OR
A|B|O
-----
0|0|0
0|1|1
1|0|1
1|1|1

AND
A|B|O
-----
0|0|0
0|1|0
1|0|0
1|1|1
</code>```

NOT is only 1 input, and it goes from true to false and vice versa.

In Boolean expressions, they are used like this:

```<code>1^((0&1&1)&/(1&0&1)\)
</code>```

Evaluating as follows:

```<code>1^(( 1 |1)&/(1&0&1)\)  |  0 OR 1 = 1, order of operations left to right - no brackets
1^(( 1   )&/(1&0&1)\)  |  1 OR 1 = 1
1^(  1    &/(1&0&1)\)  |  Remove brackets
1^(  1    &/( 0 &1)\)  |  1 AND 0 = 0
1^(  1    &/( 0   )\)  |  0 AND 1 = 0
1^(  1    &/  0    \)  |  Remove brackets
1^(  1    &   1     )  |  NOT 0 = 1
1^(  1              )  |  1 AND 1 = 1
1^   1                 |  Remove brackets
0                      |  1 XOR 1 = 0
</code>```

so 0 is the result.

Task: create a program to do this!*

I/O examples

```<code>Input -> Output
1v(0.1) -> 1
1v(0.1./1\) -> 1
/0\v(0+1) -> 0
0v1v1 -> 0
</code>```

Notes

There is no order of precedence. We will treat 0.1v0+1 as (((0.1)v0)+1)

Leaderboard

var QUESTION_ID=77254,OVERRIDE_USER=42854;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+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

```

答:
GNU Sed 4.2.2, 102

Score includes +1 for -r option to sed:

```<code>y/+./oa/
:
s%/0\\%1%
s%/1\\|\b(0o0|(\w)v\2)%0%
s%\b(\wo\w|\wv\w|1a1)%1%
s/\b\wa\w/0/
s/\((\w)\)/\1/
t
</code>```

Ideone.

Incomplete Retina port.

Title: Create a Boolean parser

Body:
GNU Sed 4.2.2, 102

Score includes +1 for -r option to sed:

y/+./oa/
:
s%/0\\%1%
s%/1\\|\b(0o0|(\w)v\2)%0%
s%\b(\wo\w|\wv\w|1a1)%1%
s/\b\wa\w/0/
s/\((\w)\)/\1/
t

Ideone.

Incomplete Retina port.


答:
32-bit little-endian x86 machine code, 14 bytes

Generated using nasm -f bin

d231 f3f7 d889 d389 db85 f475

```<code>    gcd0:   xor     edx,edx
            div     ebx
            mov     eax,ebx
            mov     ebx,edx
            test    ebx,ebx
            jnz     gcd0
</code>```

Title: Greatest Common Divisor

Body:
32-bit little-endian x86 machine code, 14 bytes

Generated using nasm -f bin

d231 f3f7 d889 d389 db85 f475

    gcd0:   xor     edx,edx
            div     ebx
            mov     eax,ebx
            mov     ebx,edx
            test    ebx,ebx
            jnz     gcd0


答:
Delphi 7, 148

Well, I think I've found the new worst language for golfing.

```<code>unit a;interface function g(a,b:integer):integer;implementation function g(a,b:integer):integer;begin if b=0then g:=a else g:=g(b,a mod b);end;end.
</code>```

Title: Greatest Common Divisor

Body:
Delphi 7, 148

Well, I think I've found the new worst language for golfing.

unit a;interface function g(a,b:integer):integer;implementation function g(a,b:integer):integer;begin if b=0then g:=a else g:=g(b,a mod b);end;end.


答:
Windows Batch, 76 bytes

Recursive function. Call it like GCD a b with file name gcd.

```<code>:g
if %2 equ 0 (set f=%1
goto d)
set/a r=%1 %% %2
call :g %2 %r%
:d
echo %f%
</code>```

Title: Greatest Common Divisor

Body:
Windows Batch, 76 bytes

Recursive function. Call it like GCD a b with file name gcd.

:g
if %2 equ 0 (set f=%1
goto d)
set/a r=%1 %% %2
call :g %2 %r%
:d
echo %f%


答:
Seriously, 23 bytes

```<code>,,;'XQ1╟";(%{}"f3δI£ƒkΣ
</code>```

This makes use of the Quine command, which is currently the only sane way to do recursion.

Try it online!

Explanation:

```<code>,,;'XQ1╟";(%{}"f3δI£ƒkΣ
,,;                      get a and b inputs, duplicate b
   'X                    push "x"
     Q1╟                 push a list containing the program's source code as the singular element
        ";(%{}"f         push the string ";(%{}".format(source_code) (essentially "gcd(b, a % b)")
                3δ       bring the second copy of b to TOS
                  I      if: pop b, recursive call, and "X", and push recursive call if b != 0 else "X"
                   £ƒ    call the string as a function
                     kΣ  sum stack elements (without this, the stack contains the gcd and possibly several 0's)
</code>```

Title: Greatest Common Divisor

Body:
Seriously, 23 bytes

,,;'XQ1╟";(%{}"f3δI£ƒkΣ

This makes use of the Quine command, which is currently the only sane way to do recursion.

Try it online!

Explanation:

,,;'XQ1╟";(%{}"f3δI£ƒkΣ
,,;                      get a and b inputs, duplicate b
   'X                    push "x"
     Q1╟                 push a list containing the program's source code as the singular element
        ";(%{}"f         push the string ";(%{}".format(source_code) (essentially "gcd(b, a % b)")
                3δ       bring the second copy of b to TOS
                  I      if: pop b, recursive call, and "X", and push recursive call if b != 0 else "X"
                   £ƒ    call the string as a function
                     kΣ  sum stack elements (without this, the stack contains the gcd and possibly several 0's)


问:
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>```

答:
Ruby 76 Bytes

```<code>s;f={};s.scan(/(([\w])[\w]*)/).map{|h,i|f[j=i.upcase]?nil:(f[j]=!p; h)}.compact.*' '
</code>```

Or with method definition 88 bytes

```<code>def m s;f={};(s.scan(/((\w)\w*)/).map{|h,i|f[j=i.upcase]?nil:(f[j]=1; h)}-[p]).*' ';end
</code>```

Ungolfed and with unit test:

```<code>def m_long(s)
  #found  - Hash with already found initials
  f={}
  #h=hit, i=initial, j=i[0].downcase
  s.scan(/(([\w\d])[\w\d]*)/).map{|h,i|
    f[j=i.upcase] ? nil : (f[j] = true; h)
  }.compact.join(' ')
end
#true == !p
#~ def m(s)
  #~ f={};s.scan(/(([\w\d])[\w\d]*)/).map{|h,i|f[j=i.upcase]?nil:(f[j]=!p; h)}.compact.join' '
#~ end
def m s;f={};s.scan(/(([\w\d])[\w\d]*)/).map{|h,i|f[j=i.upcase]?nil:(f[j]=!p; h)}.compact.join' ';end

#~ s = "Ferulas flourish in gorgeous gardens."
#~ p s.split

require 'minitest/autorun'
class FirstLetterTest < Minitest::Test
  def test_1
    assert_equal("Ferulas in gorgeous",m("Ferulas flourish in gorgeous gardens."))
    assert_equal("Ferulas in gorgeous",m_long("Ferulas flourish in gorgeous gardens."))
  end
  def test_2
    assert_equal("Take all first words each letter is",m("Take all first words for each letter... this is a test"))
    assert_equal("Take all first words each letter is",m_long("Take all first words for each letter... this is a test"))
  end
  def test_3
    assert_equal("Look _ There are 3 dogs",m("Look ^_^ .... There are 3 little dogs :)"))
    assert_equal("Look _ There are 3 dogs",m_long("Look ^_^ .... There are 3 little dogs :)"))
  end
  def test_4
    assert_equal("maybe some day 1 plus 2 could result in 3",m("...maybe some day 1 plus 2 plus 20 could result in 3"))
    assert_equal("maybe some day 1 plus 2 could result in 3",m_long("...maybe some day 1 plus 2 plus 20 could result in 3"))
  end
end
</code>```

Body:
Ruby 76 Bytes

s;f={};s.scan(/(([\w])[\w]*)/).map{|h,i|f[j=i.upcase]?nil:(f[j]=!p; h)}.compact.*' '

Or with method definition 88 bytes

def m s;f={};(s.scan(/((\w)\w*)/).map{|h,i|f[j=i.upcase]?nil:(f[j]=1; h)}-[p]).*' ';end

Ungolfed and with unit test:

def m_long(s)
  #found  - Hash with already found initials
  f={}
  #h=hit, i=initial, j=i[0].downcase
  s.scan(/(([\w\d])[\w\d]*)/).map{|h,i|
    f[j=i.upcase] ? nil : (f[j] = true; h)
  }.compact.join(' ')
end
#true == !p
#~ def m(s)
  #~ f={};s.scan(/(([\w\d])[\w\d]*)/).map{|h,i|f[j=i.upcase]?nil:(f[j]=!p; h)}.compact.join' '
#~ end
def m s;f={};s.scan(/(([\w\d])[\w\d]*)/).map{|h,i|f[j=i.upcase]?nil:(f[j]=!p; h)}.compact.join' ';end

#~ s = "Ferulas flourish in gorgeous gardens."
#~ p s.split

require 'minitest/autorun'
class FirstLetterTest < Minitest::Test
  def test_1
    assert_equal("Ferulas in gorgeous",m("Ferulas flourish in gorgeous gardens."))
    assert_equal("Ferulas in gorgeous",m_long("Ferulas flourish in gorgeous gardens."))
  end
  def test_2
    assert_equal("Take all first words each letter is",m("Take all first words for each letter... this is a test"))
    assert_equal("Take all first words each letter is",m_long("Take all first words for each letter... this is a test"))
  end
  def test_3
    assert_equal("Look _ There are 3 dogs",m("Look ^_^ .... There are 3 little dogs :)"))
    assert_equal("Look _ There are 3 dogs",m_long("Look ^_^ .... There are 3 little dogs :)"))
  end
  def test_4
    assert_equal("maybe some day 1 plus 2 could result in 3",m("...maybe some day 1 plus 2 plus 20 could result in 3"))
    assert_equal("maybe some day 1 plus 2 could result in 3",m_long("...maybe some day 1 plus 2 plus 20 could result in 3"))
  end
end


问:
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

```

答:
C, 243 188 bytes (or perhaps 217 162 bytes)

V2: see below for the explanations.

188 bytes:

```<code>s;main(g,v)char**v;{short S[8]={2,htons(atoi(v[1]))};char C[g=16];bind(s=socket(2,1,0),&S,g);for(listen(s,8);g=fdopen(accept(s,&C,&g),"w");fclose(g))fprintf(g,"%d\n",C[4]+C[5]+C[6]+C[7]);}
</code>```

Slightly circumspect 162 bytes:

```<code>s;main(g){short S[8]={2,g};char C[g=16];bind(s=socket(2,1,0),&S,g);for(listen(s,8);g=fdopen(accept(s,&C,&g),"w");fclose(g))fprintf(g,"%d\n",C[4]+C[5]+C[6]+C[7]);}
</code>```

Probably more golfing possible tomorrow morning. I'll tidy this post up after those updates.

V1:

This one was really quite fun to golf.

```<code>#include<netdb.h>
s,c,q;main(g,v)char**v;{struct sockaddr_in S={2,htons(atoi(v[1]))},C;bind(s=socket(2,1,0),&S,g=16);for(listen(s,8);c=accept(s,&C,&g);q=fclose(g)){for(g=4;g;q+=C.sin_addr.s_addr>>8*--g&255);fprintf(g=fdopen(c,"w"),"%d\n",q);}}
</code>```

It works for IPv4. Mostly it's a straightforward implementation. The three main components are

Creating the socket:

```
struct sockaddr_in S={2,htons(atoi(v[1]))},C;bind(s=socket(2,1,0),&S,g=16);
```

We use the various explicit forms of the constants AF_INET etc, and make use of the fact that when a struct is initialised in C in this way the non-specified elements are set to zero.

Listen for clients, accept them, and close their connections:

```
for(listen(s,8);c=accept(s,&C,&g);q=fclose(g))
```

Finally to send each client the data:

```
for(g=4;g;q+=C.sin_addr.s_addr>>8*--g&255);fprintf(g=fdopen(c,"w"),"%d\n",q);
```

The IP is stored in C.sin_addr.s_addr as a 32 bit integer where each octet is represented by one of the four bytes. We sum these bytes with the for loop and then print them to the stream using fprintf.

I have a shorter 217 byte solution but I'm not entirely sure it doesn't violate the standard loopholes since it requires that the port is given in unary in network byte order as command line arguments. That is, to run the server on port 12345 one would need to call

```
$ ./tcp 1 1 1 1 ... 1 1 1
```

where the total number of 1s is 14640. To say the least it's a little... cumbersome. But here it is anyway:

```<code>#include<netdb.h>
s,c,q;main(g){struct sockaddr_in S={2,g},C;bind(s=socket(2,1,0),&S,g=16);for(listen(s,8);c=accept(s,&C,&g);q=fclose(g)){for(g=4;g;q+=C.sin_addr.s_addr>>8*--g&255);fprintf(g=fdopen(c,"w"),"%d\n",q);}}
</code>```

Title: A simple TCP server

Body:
C, 243 188 bytes (or perhaps 217 162 bytes)

V2: see below for the explanations.

188 bytes:

s;main(g,v)char**v;{short S[8]={2,htons(atoi(v[1]))};char C[g=16];bind(s=socket(2,1,0),&S,g);for(listen(s,8);g=fdopen(accept(s,&C,&g),"w");fclose(g))fprintf(g,"%d\n",C[4]+C[5]+C[6]+C[7]);}

Slightly circumspect 162 bytes:

s;main(g){short S[8]={2,g};char C[g=16];bind(s=socket(2,1,0),&S,g);for(listen(s,8);g=fdopen(accept(s,&C,&g),"w");fclose(g))fprintf(g,"%d\n",C[4]+C[5]+C[6]+C[7]);}

Probably more golfing possible tomorrow morning. I'll tidy this post up after those updates.

V1:

This one was really quite fun to golf.

#include<netdb.h>
s,c,q;main(g,v)char**v;{struct sockaddr_in S={2,htons(atoi(v[1]))},C;bind(s=socket(2,1,0),&S,g=16);for(listen(s,8);c=accept(s,&C,&g);q=fclose(g)){for(g=4;g;q+=C.sin_addr.s_addr>>8*--g&255);fprintf(g=fdopen(c,"w"),"%d\n",q);}}

It works for IPv4. Mostly it's a straightforward implementation. The three main components are

Creating the socket:

struct sockaddr_in S={2,htons(atoi(v[1]))},C;bind(s=socket(2,1,0),&S,g=16);

We use the various explicit forms of the constants AF_INET etc, and make use of the fact that when a struct is initialised in C in this way the non-specified elements are set to zero.

Listen for clients, accept them, and close their connections:

for(listen(s,8);c=accept(s,&C,&g);q=fclose(g))

Finally to send each client the data:

for(g=4;g;q+=C.sin_addr.s_addr>>8*--g&255);fprintf(g=fdopen(c,"w"),"%d\n",q);

The IP is stored in C.sin_addr.s_addr as a 32 bit integer where each octet is represented by one of the four bytes. We sum these bytes with the for loop and then print them to the stream using fprintf.

I have a shorter 217 byte solution but I'm not entirely sure it doesn't violate the standard loopholes since it requires that the port is given in unary in network byte order as command line arguments. That is, to run the server on port 12345 one would need to call

$ ./tcp 1 1 1 1 ... 1 1 1

where the total number of 1s is 14640. To say the least it's a little... cumbersome. But here it is anyway:

#include<netdb.h>
s,c,q;main(g){struct sockaddr_in S={2,g},C;bind(s=socket(2,1,0),&S,g=16);for(listen(s,8);c=accept(s,&C,&g);q=fclose(g)){for(g=4;g;q+=C.sin_addr.s_addr>>8*--g&255);fprintf(g=fdopen(c,"w"),"%d\n",q);}}


答:
Python 3.5, 70 82 73 bytes:

```<code>lambda*a:max([i for i in range(1,max(*a)+1)if not sum(g%i for g in[*a])])
</code>```

The not in this case will make sure the sum all the numbers in *args modulo i are zero.

Also, now this lambda function can take in as many values as you want it to, as long as the amount of values is >=2, unlike the gcd function of the math module. For instance, it can take in the values 2,4,6,8,10 and return the correct GCD of 2.

Title: Greatest Common Divisor

Body:
Your task is to compute the greatest common divisor (GCD) of two given integers in as few bytes of code as possible.

You may write a program or function, taking input and returning output via any of our accepted standard methods (including STDIN/STDOUT, function parameters/return values, command-line arguments, etc.).

Input will be two non-negative integers. You should be able to handle either the full range supported by your language's default integer type, or the range [0,255], whichever is greater. You are guaranteed that at least one of the inputs will be non-zero.

You are not allowed to use built-ins that compute either the GCD or the LCM (least common multiple).

Standard code-golf rules apply.

Test Cases

```<code>0 2     => 2
6 0     => 6
30 42   => 6
15 14   => 1
7 7     => 7
69 25   => 1
21 12   => 3
169 123 => 1
20 142  => 2
101 202 => 101
</code>```

Body:
Python 3.5, 70 82 73 bytes:

lambda*a:max([i for i in range(1,max(*a)+1)if not sum(g%i for g in[*a])])

The not in this case will make sure the sum all the numbers in *args modulo i are zero.

Also, now this lambda function can take in as many values as you want it to, as long as the amount of values is >=2, unlike the gcd function of the math module. For instance, it can take in the values 2,4,6,8,10 and return the correct GCD of 2.


问:
Split string into n pieces (or pieces of length n)

The Challenge

In this challenge you have to do two different (but related) tasks depending of the order of the input.

Your program will recieve a string s and an integer n as input and will

split s into pieces of length n if s comes first. The last element will be shorter if necessary.

split s into n pieces of equal length if n comes first. If len(s) is not a multiple of n the first len(s) mod n elements will be one longer.

You may only take those 2 inputs. s will never contain only digits.

Notes

You may use the reverse mapping. Note this in your answer if you do that.

s will only contain printable ASCII characters (no newlines).

You may not use any builtins that solve either those two tasks directly. All other builtins are allowed.

You have to take both arguments from the same source.

You may take the arguments in an ordered list or any other format which clearly indicates their order as long as it is unambiguous.

You may take the input as one string/ stream and use a character which is not a valid input (like a nullbyte) to separate them.

n will always be equal or less than the length of s and greater than zero.

You may output the resulting list in any resonable format as long as it clearly indicates the particular pieces and their order.

Example

Input:  programming, 3

The last element contains only 2 characters, because 11 is not divisible by 3.

Output: ["pro", "gra", "mmi", "ng"]

Input: 3, programming

11 is not a multiple of 3, so the first 2 elements will be one longer:

Output: ["prog", "ramm", "ing"]

Rules

Function or full program allowed.

Default rules for input/output.

Standard loopholes apply.

This is code-golf, so lowest byte-count wins. Tiebreaker is earlier submission.

Test cases

The test cases got generated with this Pyth program (uses builtins, so no valid answer). Thanks to @FryAmTheEggman for providing the base version of that!

```
3, helloworld -> ['hell', 'owo', 'rld']
helloworld, 3 -> ['hel', 'low', 'orl', 'd']
1, programming -> ['programming']
programming, 1 -> ['p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g']
8, programming -> ['pr', 'og', 'ra', 'm', 'm', 'i', 'n', 'g']
programming, 8 -> ['programm', 'ing']
9, code golf -> ['c', 'o', 'd', 'e', ' ', 'g', 'o', 'l', 'f']
code golf, 9 -> ['code golf']
4, 133tspeak -> ['133', 'ts', 'pe', 'ak']
133tspeak, 4 -> ['133t', 'spea', 'k']
```

Happy Coding!

答:
JavaScript (ES6), 132 bytes

```<code>(s,t)=>+t?[...Array(-~(~-s.length/+t))].map((_,i)=>s.substr(i*t,t)):[...Array(s=+s)].map(_=>t.slice(p,p-=~((t.length-p-1)/s--)),p=0)
</code>```

This is probably hopelessly over-engineered.

Body:
JavaScript (ES6), 132 bytes

(s,t)=>+t?[...Array(-~(~-s.length/+t))].map((_,i)=>s.substr(i*t,t)):[...Array(s=+s)].map(_=>t.slice(p,p-=~((t.length-p-1)/s--)),p=0)

This is probably hopelessly over-engineered.


答:
C, 28 bytes

A rather straightforward function implementing Euclid's algorithm. Perhaps one can get shorter using an alternate algorithm.

```<code>g(a,b){return b?g(b,a%b):a;}
</code>```

If one writes a little main wrapper

```<code>int main(int argc, char **argv)
{
  printf("gcd(%d, %d) = %d\n", atoi(argv[1]), atoi(argv[2]), g(atoi(argv[1]), atoi(argv[2])));
}
</code>```

then one can test a few values:

```
$ ./gcd 6 21
gcd(6, 21) = 3
$ ./gcd 21 6
gcd(21, 6) = 3
$ ./gcd 6 8
gcd(6, 8) = 2
$ ./gcd 1 1
gcd(1, 1) = 1
$ ./gcd 6 16
gcd(6, 16) = 2
$ ./gcd 27 244
gcd(27, 244) = 1
```

Title: Greatest Common Divisor

Body:
C, 28 bytes

A rather straightforward function implementing Euclid's algorithm. Perhaps one can get shorter using an alternate algorithm.

g(a,b){return b?g(b,a%b):a;}

If one writes a little main wrapper

int main(int argc, char **argv)
{
  printf("gcd(%d, %d) = %d\n", atoi(argv[1]), atoi(argv[2]), g(atoi(argv[1]), atoi(argv[2])));
}

then one can test a few values:

$ ./gcd 6 21
gcd(6, 21) = 3
$ ./gcd 21 6
gcd(21, 6) = 3
$ ./gcd 6 8
gcd(6, 8) = 2
$ ./gcd 1 1
gcd(1, 1) = 1
$ ./gcd 6 16
gcd(6, 16) = 2
$ ./gcd 27 244
gcd(27, 244) = 1


答:
AWK, 121 130 128 122 Bytes

```<code>$1~/^[0-9]+$/{s=1}{a=$(s+1)
b=s?$1:$2
$0=""
for(j=-b;j<=c=length(a);)$0=$0 substr(a,j+=b+s,b+(s=s&&j<c%b*(b+1)?1:0))" "}1
</code>```

The only issue is if the first entry is a string that starts with a numeric value.  This would cause AWK to see the string as that number and the second entry as the string.

OK... fixed the numeric issue, but it added 9 bytes :(.

Reworked a bit to save a couple bytes.

Almost back to the original length. :)

Title: Split string into n pieces (or pieces of length n)

Body:
The Challenge

In this challenge you have to do two different (but related) tasks depending of the order of the input.

Your program will recieve a string s and an integer n as input and will

split s into pieces of length n if s comes first. The last element will be shorter if necessary.

split s into n pieces of equal length if n comes first. If len(s) is not a multiple of n the first len(s) mod n elements will be one longer.

You may only take those 2 inputs. s will never contain only digits.

Notes

You may use the reverse mapping. Note this in your answer if you do that.

s will only contain printable ASCII characters (no newlines).

You may not use any builtins that solve either those two tasks directly. All other builtins are allowed.

You have to take both arguments from the same source.

You may take the arguments in an ordered list or any other format which clearly indicates their order as long as it is unambiguous.

You may take the input as one string/ stream and use a character which is not a valid input (like a nullbyte) to separate them.

n will always be equal or less than the length of s and greater than zero.

You may output the resulting list in any resonable format as long as it clearly indicates the particular pieces and their order.

Example

Input:  programming, 3

The last element contains only 2 characters, because 11 is not divisible by 3.

Output: ["pro", "gra", "mmi", "ng"]

Input: 3, programming

11 is not a multiple of 3, so the first 2 elements will be one longer:

Output: ["prog", "ramm", "ing"]

Rules

Function or full program allowed.

Default rules for input/output.

Standard loopholes apply.

This is code-golf, so lowest byte-count wins. Tiebreaker is earlier submission.

Test cases

The test cases got generated with this Pyth program (uses builtins, so no valid answer). Thanks to @FryAmTheEggman for providing the base version of that!

```
3, helloworld -> ['hell', 'owo', 'rld']
helloworld, 3 -> ['hel', 'low', 'orl', 'd']
1, programming -> ['programming']
programming, 1 -> ['p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g']
8, programming -> ['pr', 'og', 'ra', 'm', 'm', 'i', 'n', 'g']
programming, 8 -> ['programm', 'ing']
9, code golf -> ['c', 'o', 'd', 'e', ' ', 'g', 'o', 'l', 'f']
code golf, 9 -> ['code golf']
4, 133tspeak -> ['133', 'ts', 'pe', 'ak']
133tspeak, 4 -> ['133t', 'spea', 'k']
```

Happy Coding!

Body:
AWK, 121 130 128 122 Bytes

$1~/^[0-9]+$/{s=1}{a=$(s+1)
b=s?$1:$2
$0=""
for(j=-b;j<=c=length(a);)$0=$0 substr(a,j+=b+s,b+(s=s&&j<c%b*(b+1)?1:0))" "}1

The only issue is if the first entry is a string that starts with a numeric value.  This would cause AWK to see the string as that number and the second entry as the string.

OK... fixed the numeric issue, but it added 9 bytes :(.

Reworked a bit to save a couple bytes.

Almost back to the original length. :)


答:
T-SQL, 153 <s>169</s> bytes

Someone mentioned worst language for golfing?

```<code>CREATE FUNCTION G(@ INT,@B INT)RETURNS TABLE RETURN WITH R AS(SELECT 1D,0R UNION ALL SELECT D+1,@%(D+1)+@B%(D+1)FROM R WHERE D<@ and D<@b)SELECT MAX(D)D FROM R WHERE 0=R
</code>```

Creates a table valued function <s>that uses a recursive query to work out the common divisors.  Then it returns the maximum</s>.
Now uses the euclidean algorithm to determine the GCD derived from my answer here.

Example usage

```<code>SELECT *
FROM (VALUES
        (15,45),
        (45,15),
        (99,7),
        (4,38)
    ) TestSet(A, B)
    CROSS APPLY (SELECT * FROM G(A,B))GCD

A           B           D
----------- ----------- -----------
15          45          15
45          15          15
99          7           1
4           38          2

(4 row(s) affected)
</code>```

Title: Greatest Common Divisor

Body:
T-SQL, 153 <s>169</s> bytes

Someone mentioned worst language for golfing?

CREATE FUNCTION G(@ INT,@B INT)RETURNS TABLE RETURN WITH R AS(SELECT 1D,0R UNION ALL SELECT D+1,@%(D+1)+@B%(D+1)FROM R WHERE D<@ and D<@b)SELECT MAX(D)D FROM R WHERE 0=R

Creates a table valued function <s>that uses a recursive query to work out the common divisors.  Then it returns the maximum</s>.
Now uses the euclidean algorithm to determine the GCD derived from my answer here.

Example usage

SELECT *
FROM (VALUES
        (15,45),
        (45,15),
        (99,7),
        (4,38)
    ) TestSet(A, B)
    CROSS APPLY (SELECT * FROM G(A,B))GCD

A           B           D
----------- ----------- -----------
15          45          15
45          15          15
99          7           1
4           38          2

(4 row(s) affected)