title: Make the biggest and smallest numbers

text:
# Question
Title: Make the biggest and smallest numbers
*Inspired by this post over on Puzzling. Spoilers for that puzzle are below.*

Given three positive integers as input, `(x, y, z)`, construct the inclusive range `[x, y]`, concatenate that range together, then remove `z` not-necessarily-consecutive digits to produce the largest and smallest positive integers possible. Leading zeros are not permitted (i.e., the numbers must start with `[1-9]`). Output those two numbers in either order.

For the example from the Puzzling post, for input `(1, 100, 100)`, the largest number possible is `99999785960616263646566676869707172737475767778798081828384858687888990919293949596979899100`,
and the smallest number is `10000012340616263646566676869707172737475767778798081828384858687888990919293949596979899100`,
following the below logic from jafe's answer posted there:

* We can't influence the number's length (there's a fixed number of digits), so to maximize the value we take the maximal first digit, then second digit etc.
* Remove the 84 first non-nines (16 digits left to remove): `999995051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100`
* The largest number within the next 17 digits is 7, so from here, the next digit in the answer can be at most 7 (we can't remove more than 16 digits). So remove 15 non-7's... (1 digit left to remove): `999997585960616263646566676869707172737475767778798081828384858687888990919293949596979899100`
* From here, the next digit can be at most 8 so remove one non-8 from the middle: `99999785960616263646566676869707172737475767778798081828384858687888990919293949596979899100`
* Similar logic, but reversed (i.e., we want leading `1`s instead of leading `9`s) for the smallest number.

Here's a smaller example: `(1, 10, 5)`.

We construct the range `12345678910` and determine which `5` digits we can remove leaving the largest possible number. Obviously, that means we want to maximize the leading digit, since we can't influence the length of the output. So, if we remove `12345`, we're left with `678910`, and that's the largest we can make. Making the smallest is a little bit trickier, since we can pluck out numbers from the middle instead, leaving `123410` as the smallest possible.

For `(20, 25, 11)`, the result is rather boring, as `5` and `1`.

Finally, to rule out answers that try leading zeros, `(9, 11, 3)` gives `91011` which in turn yields `91` and `10` as the largest and smallest.

## I/O and Rules

* If it's easier/shorter, you can code two programs/functions -- one for the largest and one for the smallest -- in which case your score is the sum of both parts.
* The input and output can be given by any convenient method.
* The input can be assumed to fit in your language's native number type, ***however***, neither the concatenated number nor the output can be assumed to do so.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
> 5 votes
# Haskell, 162 bytes

```
l=length
((m,f)%n)s|n>=l s=[]|n>0,(p,c:r)<-span(/=m(f$take(n+1)s))s=c:((m,id)%(n-l p)$r)|1>0=s
(x#y)z=[p%z$show=<<[x..y]|p<-[(maximum,id),(minimum,filter(>'0'))]]

```

Try it online!

Uses the algorithm described by jafe. Might be shorter to use a less efficient method, but this was more fun to write :)

The `%` operation takes 4 arguments (actually 3, but whatever): `m` which is a function that selects the "optimal" member from a list (either `maximum` or `minimum` depending on what we want); `f` which is a "filter" function; `n` the number of digits left to drop; and `s` the string. First we check whether n is equal to the number of digits left in the string (I used `>=` for safety) and drop the rest of `s` if so. Otherwise we check if we still need to drop digits (`n>0`), then we use `span` to break our string into three pieces: `p` the digits to drop, `c` the optimal reachable digit, and `r` the remaining string. We do this by passing span a predicate that checks for equality against our optimal digit. To find that digit we take the first `n+1` digits of the string, filter it, then pass it to our "chooser" function. Now we just yield our optimal digit and recur, subtracting the length of `p` (the number of digits dropped) from `n`. Notice that we do not pass our filtering function to the recursive call, and, instead, we replace it with `id`. That's because the filter is only there to avoid selecting leading 0s in the `minimum` case which is only relevant on the first iteration. After that we no longer need any filter.

`%` is really only a helper function for `#` which is our "real" function, taking `x`, `y`, and `z`. We use a list comprehension just to avoid a bit of repetition, iterating over our function tuples and passing them to `%` along with `z` and the concatenated string. That string is created using the magic monad operator `(=<<)` which, in this context, works like `concatMap`.

# Answer
> 3 votes
# Jelly, 17 bytes

```
r/VDœcL_¥¥ḷ/ƇVṢ.ị

```

Try it online!

Calculates all possibilities then keeps the largest and smallest.

Left argument: `x,y` to construct the range. Right argument: `z` digits to be removed.

```
r/VDœcL_¥¥ḷ/ƇVṢ.ị
r/                 Inclusive range from x to y
  V                Concatenate the digits together
   D               Get the resulting digits
         ¥         Dyad:
        ¥            Dyad:
      L                Length of the list of digits in the concatenated number.
       _               Subtract the number of digits to be removed.
    œc               Combinations without replacement. (remove z digits)
            Ƈ      Keep lists of digits that:
          ḷ/       have a positive first element (no leading zeros).
             V     Combine digits into integers. (vectorizes to ldepth 1)
              Ṣ    Sort the numbers
               .ị  Indexes at value 0.5 which yields the first and last elements.

```

# Answer
> 2 votes
# Python 2, 143 bytes

```
import itertools
s,e,r=input()
l=''.join(map(str,range(s,e+1)))
L=[i for i in itertools.combinations(l,len(l)-r)if'0'<i[0]]
print min(L),max(L)

```

Try it online!

This works by calculating all combinations of the target size (the element order is preserved) and getting the smallest / biggest numbers from it

# Answer
> 2 votes
# Charcoal, 56 bytes or 21 + ~~46~~ 35 = ~~67~~ 56 bytes

```
≔⪫…·ＮＮωθＦＮ≔⌈ＥθΦθ⁻λνθθ

```

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

```
≔⪫…·ＮＮωθ

```

Input `x` and `y`, create an inclusive range and join the numbers into a string.

```
ＦＮ

```

Loop once for each digit to be removed.

```
≔⌈ＥθΦθ⁻λνθ

```

Create a list of strings formed by removing each possible character from the current string and take the maximum.

```
θ

```

Print the result.

```
≔⪫…·ＮＮωθＦ⊕Ｎ⊞υωΦθ∧⁼ι⌊Φ✂θκＬυ¹∨κＩλ⊞Ｏυω

```

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

```
≔⪫…·ＮＮωθ

```

Input `x` and `y`, create an inclusive range and join the numbers into a string.

```
Ｆ⊕Ｎ⊞υω

```

Input `z` and increment it. I then create a list of that length: I need to be able to increment `z` inside the following filter, but only commands are allowed to increment variables; there is a loophole in that `PushOperator` increments the length of the list.

```
 θ                      String of digits
Φ                       Filter over characters
         κ              Current index
          Ｌυ            Length of list i.e. current `z` value
            ¹           Literal 1
       ✂θ               Slice string of digits
      Φ                 Filter over characters
              κ         Outer index
               Ｉλ       Cast inner character to number
             ∨          Logical OR
     ⌊                  Minimum
   ⁼ι                   Equals the outer character
  ∧              ⊞Ｏυω   And also push to list i.e. increment `z`
                        Implicitly print

```

Filter on the characters that are wanted by checking that there are no lower characters in the sliceable region. The region starts with the first `z+1` characters (since it's possible to slice the first `z` away if necessary) and the end point increments for each character that is kept. Care is taken not to choose a zero for the first character.

The faster algorithm is 30 bytes when used to compute the largest possible number:

```
≔⪫…·ＮＮωθＦ⊕Ｎ⊞υωΦθ∧⁼ι⌈✂θκＬυ¹⊞Ｏυω

```

Try it online! Link is to verbose version of code. Edit: I've since been able to combine the above two into a second 56 byte solution which generates both results:

```
≔⪫…·ＮＮωθＦ⊕Ｎ⊞υω≔⮌υη⟦Φθ∧⁼ι⌈✂θκＬυ¹⊞ＯυωΦθ∧⁼ι⌊Φ✂θκＬη¹∨κＩλ⊞Ｏηω

```

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

```
≔⪫…·ＮＮωθ

```

Generate the initial string.

```
Ｆ⊕Ｎ⊞υω

```

Represent `z+1` as the length of the list.

```
≔⮌υη

```

Reverse the list thus cloning it and save the result.

Print the two results on separate lines. (Another way of doing this is to separate the results with a literal `\r` character.)

```
Φθ∧⁼ι⌈✂θκＬυ¹⊞Ｏυω

```

Generate the largest possible number.

```
Φθ∧⁼ι⌊Φ✂θκＬη¹∨κＩλ⊞Ｏηω

```

Generate the smallest possible number using the cloned list to keep track of `z`.

# Answer
> 1 votes
# Jelly,  ~~19~~  18 bytes

```
rDẎœcL_⁵Ɗ$ị@Ƈ1ḌṢ.ị

```

**Try it online!**

Very inefficient, definately no point going for `1, 100, 100` as \\$\binom{192}{92}=305812874887035355118559193163641366325011573739619723360\\$

# Answer
> 1 votes
# 05AB1E, 16 bytes

```
ŸSDg³-.Æʒ¬Ā}{Ć`‚

```

Try it online!

Full program, reading inputs in this order: **y, x, z**. Outputs a list of two lists of characters.

### Explanation

```
ŸSDg³-.Æʒ¬Ā}{Ć`‚    Full program. Inputs: y, x, z.
Ÿ                   Inclusive binary range from x to y. Push [x ... y].
 S                  Dump the digits separately in a list.
  Dg                Duplicate, and use the second copy to get its length.
    ³-              Subtract z from the length.
      .Æ            Retrieve all combinations of length - z elements from the digits.
        ʒ  }        Keep only those that...
         ¬Ā         Don't start with a 0 (head, then Python-style boolean).
            {       Sort the remaining elements.
             Ć      Enclose. Pushes list + list[0] (appends its tail to itself)
              `     Dump all elements separately on the stack.
               ,    Pair, to get the last two, min and max (after enclosing)

```

# Answer
> 0 votes
## Matlab, 95 bytes

```
function[m]=f(s,e,c),a=sprintf('%d',s:e);x=str2num(combnk(a,length(a)-c));m=[min(x),max(x)];end

```

Try it Online!

Returns an 1x2 matrix with min and max.

**How it works**

```
% Full code
function[m]=f(s,e,c),a=sprintf('%d',s:e);x=str2num(combnk(a,length(a)-c));m=[min(x),max(x)];end

% The function
function[m]=f(s,e,c),                                                                       end

                     % Creates the range in a single string
                     a=sprintf('%d',s:e);

                                                   % Gets all the combinations
                                                   combnk(a,length(a)-c)

                                         % Converts the string combinations to integers
                                         x=str2num(                     );

                                                                          % Finds min and max
                                                                          m=[min(x),max(x)];

```

---
Tags: code-golf, number, number-theory
---


title: Single Perceptron Implementation

text:
# Question
Title: Single Perceptron Implementation
## Challenge

Train a single perceptron with 2 inputs and 1 output.

**Step 1:** Initialize the weights

**Step 2:** Calculate the output

For inputs: \[i1, i2, ..., in\] and weights: \[w1, w2, ..., wn\] the output is:

```
i1 * w1 + i2 * w2 + ... + in * wn

```

**Step 3:** Apply activation function on the output (i.e sigmoid)

**Step 4:** Update the weights

```
w(t + 1) = w(t) + r * (desired_output - actual_output)

```

Where r: learning rate

**Step 5** Repeat steps 2, 3 and 4

## Input

**iterations**: how many times you repeat steps 2, 3 and 4
**input**: a list with 2 input values i.e. `[1, 0]`
**output**: the desired output
**learning\_rate**: the learning rate i.e.`0.3`

## Output

It should print the last calculated output. Keep in mind this should be very close to the desired output i.e `0.96564545` for desired output `1`

## Example

For input (training for XOR):

```
1000, [1 0], 1, 0.3

```

The output should be:

```
0.9966304251639512

```

**Note** The output will never be the same even for identical test cases due to random weights initialization.

Here's some non-golfed code in Python for this test case:

Try it Online!

## Rules

1. The inputs and outputs of the perceptron are fixed to: 2 and 1 respectively.
2. The output needs to be close to the desired output (see example).
3. You can use any activation function you want, just mention it.

# Answer
> 1 votes
# JavaScript (Node.js), ~~121~~ 110 bytes

Same as TFled. A "golfed" version of the example.

*-11 bytes from @Arnauld*

```
with(Math)f=(a,[b,B],c,d)=>(g=w=>a--?g(w.map(_=>_+d*(c-(y=1/(1+exp(B*w[1]-b*w[0])))))):y)([random(),random()])

```

Try it online!

# Answer
> 0 votes
# Python 2, 136 bytes

```
from random import*
import math
def f(n,(i,I),o,r):w,W=random(),random();exec"d=1/(1+math.exp(-i*w-I*W));c=r*(o-d);w+=c;W+=c;"*n;print d

```

Try it online!

Basically just a golfed version of the example

---
Tags: code-golf
---


title: KoTH: Gomoku (Five in a row)

text:
# Question
Title: KoTH: Gomoku (Five in a row)
Gomoku or *Five in a row* is a board game played by two players on a \\$15 \times 15\\$ grid with black and white stones. Whoever is able to place \\$5\\$ stones in a row (horizontal, vertical or diagonal) wins the game.

## Rules

In this KoTH we'll play the Swap2 rule, meaning that a game consists of two phases: In the initial phase the two players determine who goes first/who plays black, after that they'll place one stone each round starting with the player who picked black.

### Initial phase

Let the players be **A** & **B** and **A** shall open the game:

* **A** places two black and one white stone on the board
* **B** can choose one of the following three moves:
    + player **B** decides to play black: initial phase is over
    + player **B** decides to place a white stone and plays white: initial phase is over
    + player **B** decides to play one black and one white stone: **A** gets to pick the color

### Game phase

Each player places one stone of their colour on the board, starting with the player who plays black, this goes on until there are no more free spaces to play (in which case it's a tie) or one player manages to play \\$5\\$ stones in a row (in which case that player wins).

A row means either horizontal, vertical or diagonal. A win is a win - it doesn't matter whether the player managed to score more than one row.

## KoTH game rules

* each player plays against each other player twice:
    + initially it will be randomly decided who goes first
    + in the next game the player that got to play last goes first
* a win is worth 2 points, a tie 1 and a loss 0
* the goal is to score as many points as possible

## Your bot

To make this challenge accessible for as many languages as possible input/output will be via *stdin*/*stdout* (line-based). The judge program will prompt your program by printing a line to your bot's *stdin* and your bot will print one line to *stdout*.

Once you receive an `EXIT` message you'll be given half a second to finish writing to files before the judge will kill the process.

### Randomness

To make the tournaments verifiable the judge uses seeded randomization and your bot must do too, for the same reason. The bot will be given a seed via command-line argument which it should use, please refer to the next section.

### Arguments

The bot receives two command-line arguments:

1. opponent's name
2. seed for randomness

### User state

Because your program will always be started new for each game you'll need to use files to persist any information you want to keep. You are allowed to read/write any files or create/remove sub-folders in your current directory. You are not allowed to access any files in any parent-directory!

### Input/Output format

`BOARD` will denote a list of the current stones, it only lists the positions where a stone is placed and each entry will be of the form `((X,Y),COLOR)` where `X` and `Y` will be an integer in the range \\$\[0,15)\\$ and `COLOR` will either be `"B"` (black) or `"W"` (white).

Furthermore `SP` denotes a single space, `XY` a tuple `(X,Y)` of two integers each in the range \\$\[0,15)\\$ and `|` denotes a choice.

In the initial phase there are three different kinds of messages:

```
Prompt (judge) -> Answer (bot)
"A" SP "[]"  -> XY XY XY
"B" SP BOARD -> "B" | "W" SP XY | XY XY
"C" SP BOARD -> "B" | "W"

```
* The first message asks for three tuples, the first two will be the positions of the black stones and the third one the position for the white one.
* The second message asks either for:
    + `"B"` -\> pick black
    + `"W" SP XY` -\> pick white and place a white stone at `XY`
    + `XY XY` -\> place two stones (first one black and second one white)
* The last one just asks for which colour you want to play

---

After that the regular game will begin and the messages will become much simpler

```
N BOARD -> XY

```

where `N` is the number of the round (beginning with \\$0\\$) and `XY` will be the position where you place a stone.

---

There is one additional message which does not expect an answer

```
"EXIT" SP NAME | "EXIT TIE"

```

where `NAME` is the name of the bot that won. The second message will be sent if the game ends due to nobody winning and no more free spaces to place stones (this implies that your bot can't be named `TIE`).

**Formatting**

Since messages from the bot can be decoded without any spaces, all spaces will be ignored (eg. `(0 , 0) (0,12)` is treated the same as `(0,0)(0,12)`). Messages from the judge only contain a space to separate different sections (ie. as noted above with `SP`), allowing you to split the line on spaces.

Any invalid response will result in a loss of that round (you'll still receive an `EXIT` message), see rules.

**Example**

Here are some examples of actual messages:

```
A []
B [((0,0),"B"),((0,1),"W"),((14,14),"B")]
1 [((0,0),"B"),((0,1),"W"),((1,0),"B"),((1,1),"W"),((14,14),"B")]

```

## Judge

You can find the judge program here: To add a bot to it simply create a new folder in the `bots` folder, place your files there and add a file `meta` containing *name*, *command*, *arguments* and a flag *0/1* (disable/enable *stderr*) each on a separate line.

To run a tournament just run `./gomoku` and to debug a single bot run `./gomoku -d BOT`.

**Note:** You can find more information on how to setup and use the judge in the Github repository. There are also three example bots (Haskell, Python and JavaScript).

## Rules

* on each change of a bot* the tournament will be rerun and the player with the most points wins (tie-breaker is first submission)
* you may submit more than one bot as long as they don't play a common strategy
* you are not allowed to touch files outside of your directory (eg. manipulating other player's files)
* if your bot crashes or sends an invalid response, the current game is terminated and you lose that round
* while the judge (currently) does not enforce a time-limit per round, you are advised to keep the time spent low as it could become infeasible to test all the submissions\**
* abusing bugs in the judge program counts as loophole

* You are encouraged to use Github to separately submit your bot directly in the `bots` directory (and potentially modify `util.sh`)!

\** In case it becomes a problem you'll be notified, I'd say anything below 500ms (that's a lot!) should be fine for now.

## Chat

If you have questions or want to talk about this KoTH, feel free to join the Chat!

# Answer
> 3 votes
## KaitoBot

It uses a very crude implementation of MiniMax principles. The depth of the search is also very low, because otherwise it takes way too long.

Might edit to improve later.

It also tries to play Black if possible, because Wikipedia seems to say that Black has an advantage.

I have never played Gomoku myself, so I set up the first three stones randomly for lack of a better idea.

```
const readline = require('readline');
const readLine = readline.createInterface({ input: process.stdin });

var debug = true;
var myColor = '';
var opponentColor = '';
var board = [];
var seed = parseInt(process.argv[3]);

function random(min, max) {
    changeSeed();
    var x = Math.sin(seed) * 10000;
    var decimal = x - Math.floor(x);
    var chosen = Math.floor(min + (decimal * (max - min)));
    return chosen;
}

function changeSeed() {
    var x = Math.sin(seed++) * 10000;
    var decimal = x - Math.floor(x);
    seed = Math.floor(100 + (decimal * 9000000));
}

function KaitoBot(ln) {
    var ws = ln.split(' ');

    if (ws[0] === 'A') {
        // Let's play randomly, we don't care.
        var nums = [];
        nums[0] = [ random(0, 15), random(0, 15) ];
        nums[1] = [ random(0, 15), random(0, 15) ];
        nums[2] = [ random(0, 15), random(0, 15) ];
        while (nums[1][0] == nums[0][0] && nums[1][1] == nums[0][1])
        {
            nums[1] = [ random(0, 15), random(0, 15) ];
        }
        while ((nums[2][0] == nums[0][0] && nums[2][1] == nums[0][1]) || (nums[2][0] == nums[1][0] && nums[2][1] == nums[1][1]))
        {
            nums[2] = [ random(0, 15), random(0, 15) ];
        }
        console.log('(' + nums[0][0] + ',' + nums[0][1] + ') (' + nums[1][0] + ',' + nums[1][1] + ') (' + nums[2][0] + ',' + nums[2][1] + ')');
    }
    else if (ws[0] === 'B') {
        // we're second to play, let's just pick black
        myColor = 'B';
        opponentColor = 'W';
        console.log('B');
    }
    else if (ws[0] === 'C') {
        // the other player chose to play 2 stones more, we need to pick..
        // I would prefer playing Black
        myColor = 'B';
        opponentColor = 'W';
        console.log('B');
    }
    else if (ws[0] === 'EXIT') {
        process.exit();
    }
    else {
        board = [];
        var json = JSON.parse(ws[1].replace(/\(\(/g,'{"xy":[')
                .replace(/"\)/g,'"}')
                .replace(/\),/g,'],"colour":'));
        // loop over all XYs and make a board object I can use
        for (var x = 0; x < 15; x++) {
            var newRow = []
            for (var y = 0; y < 15; y++) {
                var contains = false;
                json.forEach(j => {
                    if (j.xy[0] == x && j.xy[1] == y) {
                        contains = true;
                        newRow[newRow.length] = j.colour;
                    }
                });
                if (!contains) {
                    newRow[newRow.length] = ' ';
                }
            }
            board[board.length] = newRow;
        }
        // If we never picked Black, I assume we're White
        if (myColor == '') {
            myColor = 'W';
            opponentColor = 'B';
        }
        var bestMoves = ChooseMove(board, myColor, opponentColor);
        var chosenMove = bestMoves[random(0, bestMoves.length)];
        console.log('(' + chosenMove.X + ',' + chosenMove.Y + ')');
    }
}

function IsSquareRelevant(board, x, y) {
    return (board[x][y] == ' ' &&
        ((x > 0 && board[x - 1][y] != ' ')
        || (x < 14 && board[x + 1][y] != ' ')
        || (y > 0 && board[x][y - 1] != ' ')
        || (y < 14 && board[x][y + 1] != ' ')
        || (x > 0 && y > 0 && board[x - 1][y - 1] != ' ')
        || (x < 14 && y < 14 && board[x + 1][y + 1] != ' ')
        || (y > 0 && x < 14 && board[x + 1][y - 1] != ' ')
        || (y < 14 && x > 0 && board[x - 1][y + 1] != ' ')));
}

function ChooseMove(board, colorMe, colorOpponent) {
    var possibleMoves = [];
    for (var x = 0; x < 15; x++) {
        for (var y = 0; y < 15; y++) {
            if (IsSquareRelevant(board, x, y)) {
                possibleMoves[possibleMoves.length] = {X:x, Y:y};
            }
        }
    }
    var bestValue = -9999;
    var bestMoves = [possibleMoves[0]];
    for (var k in possibleMoves) {
        var changedBoard = JSON.parse(JSON.stringify(board));
        changedBoard[possibleMoves[k].X][possibleMoves[k].Y] = colorMe;
        var value = analyseBoard(changedBoard, colorMe, colorOpponent, colorOpponent, 2);
        if (value > bestValue) {
            bestValue = value;
            bestMoves = [possibleMoves[k]];
        } else if (value == bestValue) {
            bestMoves[bestMoves.length] = possibleMoves[k];
        }
    }
    return bestMoves;
}

function analyseBoard(board, color, opponent, nextToPlay, depth) {
    var tBoard = board[0].map((x,i) => board.map(x => x[i]));
    var score = 0.0;
    for (var x = 0; x < board.length; x++) {
        var inARow = 0;
        var tInARow = 0;
        var opponentInARow = 0;
        var tOpponentInARow = 0;
        var inADiago1 = 0;
        var opponentInADiago1 = 0;
        var inADiago2 = 0;
        var opponentInADiago2 = 0;

        for (var y = 0; y < board.length; y++) {
            if (board[x][y] == color) {
                inARow++;
                score += Math.pow(2, inARow);
            } else {
                inARow = 0;
            }
            if (board[x][y] == opponent) {
                opponentInARow++;
                score -= Math.pow(2, opponentInARow);
            } else {
                opponentInARow = 0;
            }
            if (tBoard[x][y] == color) {
                tInARow++;
                score += Math.pow(2, tInARow);
            } else {
                tInARow = 0;
            }
            if (tBoard[x][y] == opponent) {
                tOpponentInARow++;
                score -= Math.pow(2, tOpponentInARow);
            } else {
                tOpponentInARow = 0;
            }

            var xy = (y + x) % 15;
            var xy2 = (x - y + 15) % 15;
            if (xy == 0) {
                inADiago1 = 0;
                opponentInADiago1 = 0;
            }
            if (xy2 == 0) {
                inADiago2 = 0;
                opponentInADiago2 = 0;
            }

            if (board[xy][y] == color) {
                inADiago1++;
                score += Math.pow(2, inADiago1);
            } else {
                inADiago1 = 0;
            }
            if (board[xy][y] == opponent) {
                opponentInADiago1++;
                score -= Math.pow(2, opponentInADiago1);
            } else {
                opponentInADiago1 = 0;
            }
            if (board[xy2][y] == color) {
                inADiago2++;
                score += Math.pow(2, inADiago2);
            } else {
                inADiago2 = 0;
            }
            if (board[xy2][y] == opponent) {
                opponentInADiago2++;
                score -= Math.pow(2, opponentInADiago2);
            } else {
                opponentInADiago2 = 0;
            }

            if (inARow == 5 || tInARow == 5) {
                return 999999999.0;
            } else if (opponentInARow == 5 || tOpponentInARow == 5) {
                return -99999999.0;
            }
            if (inADiago1 == 5 || inADiago2 == 5) {
                return 999999999.0;
            } else if (opponentInADiago1 == 5 || opponentInADiago2 == 5) {
                return -99999999.0;
            }
        }
    }

    if (depth > 0) {
        var bestMoveValue = 999999999;
        var nextNextToPlay = color;
        if (nextToPlay == color) {
            nextNextToPlay = opponent;
            bestMoveValue = -999999999;
        }
        for (var x = 0; x < board.length; x++) {
            for (var y = 0; y < board.length; y++) {
                if (IsSquareRelevant(board, x, y)) {
                    var changedBoard = JSON.parse(JSON.stringify(board));
                    changedBoard[x][y] = nextToPlay;
                    var NextMoveValue = (analyseBoard(changedBoard, color, opponent, nextNextToPlay, depth - 1) * 0.1);

                    if (nextToPlay == color) {
                        if (NextMoveValue > bestMoveValue) {
                            bestMoveValue = NextMoveValue;
                        }
                    } else {
                        if (NextMoveValue < bestMoveValue) {
                            bestMoveValue = NextMoveValue;
                        }
                    }
                }
            }
        }
        score += bestMoveValue * 0.1;
    }
    return score;
}

readLine.on('line', (ln) => {

    KaitoBot(ln);

});

```

EDITS: Made the seed change dynamically because otherwise when seeds exceeded 2^52 javascript couldn't handle the increment correctly

---
Tags: king-of-the-hill, board-game
---