title: Evaluate a chain of inequalities

text:
# Question
Title: Evaluate a chain of inequalities
Write code to evaluate whether a chain of inequalities is true or false. An example input is the string

`3<=4!=9>3==3`

This is true because each of its components is true:

`(3<=4) and (4!=9) and (9>3) and (3==3)`

**Input:**

A string that represents a chain of one or more inequalities. The allowed comparison operators are

```
==   equals
!=   does not equal
>    is greater than
>=   is greater than or equal to
<    is less than
<=   is less than or equal to

```

The allowed numbers are single-digit numbers `0` through `9`. There won't be any spaces, parentheses, or other symbols.

**Output:**

The correctness of the inequality as a consistent Truthy or Falsey value. Consistent means every Truthy output is the same and every Falsey output is the same.

**Restriction:**

The intent of this challenge is for you to write code that processes the inequalities, rather than have them be evaluating them as code, even for a single inequality in the chain. As such, methods like Python's `eval` and `exec` that evaluate or execute code are banned. So are functions which look up a method or operator given its name as a string. Nor is it allowed to launching processes or programs to do the evaluation for you.

**Test cases:**

```
3<=4!=9>3==3
True

3<=4!=4
False

5>5
False

8==8<9>0!=2>=1
True

```

# Answer
# Ruby, 71 + 1 = 72

With command-line flag `-n`, run

```
p (0..99).none?{|i|~/#{a=i%10}(#{%w/!=|. <?=* >?=*/[a<=>b=i/10]})#{b}/}

```

Generates all possible failing regular expressions, and checks whether the input string matches any of them. Outputs `true` if none do, else `false`. Takes input via STDIN, separated by newlines.

Tricks:

* We get all possible pairs of digits by looping from 0 to 99 and extracting the 10s and 1s digits.
* The only actual comparison we do is `a<=>b`, which returns -1,0,or 1 for less than, equal to, or greater. These all slice to different elements of a three-string array, finding the regular expression for comparisons that don't match.
> 8 votes

# Answer
# Perl, 82

```
$_=<>;($'<=>$&)-61+ord$1&&($2&&$&==$')^('$'lt$1)&&die"\n"while/\d(.)(=?)/g;print 1

```

Prints 1 when true and a blank line when false, since the empty string is Perl's main falsey value.

The while loop goes over the string matching the regex `\d(.)(=?)`. Then the variables `$1` and `$2` correspond to the characters of the operator, and the special variables `$&` and `$'` will behave as the two operands in a numerical context. The operands are compared with `<=>` and the result matched against the first character of the operator. Then equality and inequality is dealt with specially.
> 6 votes

# Answer
# JavaScript (ES6) 110 ~~116~~

Straightforward:scan string, c is current digit, l is last digit, o is operator.

```
F=x=>(l='',[for(c of x)10-c?(v=!l||v&&(o<'<'?l!=c:(o[1]&&c==l)||(o<'='?l<c:o<'>'?c==l:l>c)),l=c,o=''):o+=c],v)

```

**Test** In Firefox / FireBug console

```
;['3<=4!=9>3==3','3<=4!=4','5>5','8==8<9>0!=2>=1']
.forEach(s=>console.log(s,F(s)))

```

> 3\<=4!=9\>3==3 true
> 3\<=4!=4 false
> 5\>5 false
> 8==8\<9\>0!=2\>=1 true
> 4 votes

# Answer
# CJam, 60 bytes

This code seems a bit ugly and potentially not fully optimized, but it's the best I've got so far.

Try it online.

```
q_A,sSer_S%@@-(])1\@z{~:X\:^i['=")<"P"(>"P'<'^'>PPP]=~e&X}/;

```

### Explanation

```
q               "Read the input";
_A,sSer         "Copy the input and replace each digit with a space";
_S%             "Split around spaces to obtain the operation list";
@@-             "Remove operations from the input to obtain the operand list";
(])1\@z         "Remove the first operand from the list to be the initial left
                 operand, initialize the result to 1 (true), and pair up the
                 operations and remaining operands";
{               "For each operation-operand pair:";
  ~:X             "Let the operand be the right operand of this operation";
  \:^i            "Hash the operation (bitwise XOR of all characters)";
  [               "Begin cases:";
    '=              " 0: Equals";
    ")<"            " 1: Less than or equal to";
    P               " 2: (Invalid)";
    "(>"            " 3: Greater than or equal to";
    P               " 4: (Invalid)";
    '<              " 5: Less than";
    '^              " 6: Bitwise XOR (stand-in for not equal to)";
    '>              " 7: Greater than";
    P               " 8: (Invalid)";
    P               " 9: (Invalid)";
    P               "10: (Invalid)";
  ]=~             "Execute the case selected by the operation hash modulo 11";
  e&              "Compute the logical AND of the result and the value produced
                   by this operation to be the new result";
  X               "Let the right operand be the new left operand";
}/              "End for each";
;               "Clean up and implicitly print result";

```
> 4 votes

# Answer
# Haskell, 156 bytes

```
r a=read[a]::Int
l"!"=(/=)
l"="=(==)
l">"=(>=)
l"<"=(<=)
k">"=(>)
k"<"=(<)
[]#_=1<2
(a:'=':b:c)#i=l[a]i(r b)&&c#r b
(a:b:c)#i=k[a]i(r b)&&c#r b
f(h:t)=t#r h

```

Usage example:

```
f "3<=4!=9>3==3"        -> True
f "3<=4!=4"             -> False
f "5>5"                 -> False
f "8==8<9>0!=2>=1"      -> True

```

Ungolfed version:

```
digitToInt d = read [d] :: Int

lookup2 "!" = (/=)
lookup2 "=" = (==)
lookup2 ">" = (>=)
lookup2 "<" = (<=)

lookup1 ">" = (>)
lookup1 "<" = (<)

eval []              _ = True
eval (op:'=':d:rest) i = lookup2 [op] i (digitToInt d) && eval rest (digitToInt d)
eval (op:d:rest)     i = lookup1 [op] i (digitToInt d) && eval rest (digitToInt d)

evalChain (hd:rest) = eval rest (digitToInt hd)

```

`eval` takes two arguments: the string to parse (starting always with a comparison operator) and a number `i` which is the left argument for comparison (and was the right argument in the previous round). The operator is returned by `lookup2` if it's a two character operator (check only 1st char, because 2nd is always `=`) and by `lookup1` if it's just a single character. `eval` calls itself recursively and combines all return values with logical and `&&`.
> 4 votes

# Answer
# Common Lisp - ~~300~~ ~~185~~  ~~169~~ 165

```
(lambda(s)(loop for(a o b)on(mapcar'read-from-string(cdr(ppcre:split"([0-9]+)"s :with-registers-p t)))by #'cddr always(if o(funcall(case o(=='=)(!='/=)(t o))a b)t)))

```

# Example

```
(mapcar (lambda(s) ...)
       '("2<=3<=6>2<10!=3"
         "3<=4!=9>3==3"
         "3<=4!=4"
         "5>5"
         "8==8<9>0!=2>=1"))
=> (T T NIL NIL T)

```

# Explanation

```
(lambda (s)
  (loop for (a o b) on (mapcar
                        'read-from-string
                        (cdr
                         (cl-ppcre:split "([0-9]+)" s
                                         :with-registers-p t))) by #'cddr
        always (if o
                   (funcall (case o
                                  (== '=)
                                  (!= '/=)
                                  (t o))
                            a b)
                   t)))

```
* `ppcre:split` splits on digits; for example:

```
(ppcre:split "([0-9]+)" "2<=3<=6>2<10!=3" :with-registers-p t)
=> ("" "2" "<=" "3" "<=" "6" ">" "2" "<" "10" "!=" "3")

```

Notice the first empty string, which is discarded using `cdr`
* Mapping `read-from-string` to this list calls the `read` function for each strings, which returns symbols and numbers.
* `loop for (a op b) on '(3 < 5 > 2) by #'cddr` iterates over the list by a step of **2** and thus binds `a`, `op` and `b` as follows, for each successive pass.

```
a  op  b
----------
3  <    5
5  >    2
2  nil  nil

```
* `always` checks whether the next expression is always true: either the operator is `nil` (see above) or the result of the comparison holds (see below).
* the `case` selects a Common-Lisp comparison function, according to the symbol previously read; since some operators are identical in Lisp and the given language we can simply return `o` in the default case.
> 3 votes

# Answer
# Python 2, ~~95~~ 102

```
t=1
n=o=3
for c in map(ord,raw_input()):
 o+=c
 if 47<c<58:t&=627>>(o-c+3*cmp(n,c))%13;n=c;o=0
print t

```

The loop is a straightforward pass through the string one character at a time. The `t&=...` part is where the magic happens. Basically, I hash the operator together with the value of `cmp(lhs,rhs)` (-1, 0, or 1 depending on if `lhs` is less, equal, or greater than `rhs`). The result is a key into a lookup table that gives 0 or 1 depending on whether the numbers compare properly given that operator. What lookup table, you ask? It's the number 627 = `0001001110011` in binary. Bitwise operators do the rest.

This works on the four given test cases; let me know if you find an error for another case. I haven't tested it very rigorously.
> 2 votes

# Answer
# 05AB1E, 37 bytes

```
þS¡¦Uþü.S"=<!>"2×Sć«'<š'>ª3ôÀsèXδåÅ\P

```

Try it online or verify all test cases.

**Explanation:**

```
þ         # Only leave the digits of the (implicit) input-string
          #  i.e. "3<=4!=9>3==3" → "34933"
 S        # Convert it to a list of digits
          #  → [3,4,9,3,3]
  ¡       # Split the (implicit) input-string by those, to have a list of the comparisons
          #  → ["","<=","!=",">","==",""]
   ¦      # Remove the first item (which is an empty string)
          #  → ["<=","!=",">","==",""]
          # (it also contains a trailing empty string, but we'll ignore that)
    U     # Pop and store it in variable `X`
þ         # Only leave the digits of the (implicit) input-string again
 ü        # For each overlapping pair of digits:
  .S      #  Compare them: -1 if a<b; 0 if a==b; 1 if a>b
          #   → [[3,4],[4,9],[9,3],[3,3]] → [-1,-1,1,0]
"=<!>"    # Push string "=<!>"
      2×  # Double it to "=<!>=<!>"
        S # Convert it to a list of characters: ["=","<","!",">","=","<","!",">"]
ć         # Extract the head: pop and push remainder-list and head separately
 «        # Append this "=" to each: ["<=","!=",">=","==","<=","!=",">="]
  '<š'>ª  # Prepend a "<" and append a ">": ["<","<=","!=",">=","==","<=","!=",">=",">"]
3ô        # Split it into parts of size 3: [["<","<=","!="],[">=","==","<="],["!=",">=",">"]]
  À       # Rotate this list once left: [[">=","==","<="],["!=",">=",">"],["<","<=","!="]]
   sè     # Index the digit-comparisons into it (where the -1 indexes into the last item)
          #  → [["<","<=","!="],["<","<=","!="],["!=",">=",">"],[">=","==","<="]]
X         # Push the input-comparisons from variable `X` again
 δ        # Apply double-vectorized:
  å       #  Check if the current comparison is in the current list
          #   → [[1,1,0,0,0],[1,1,0,0,0],[0,1,1,0,0],[1,0,0,1,0]]
   Å\     # Leave the main diagonal of these double-vectorized checks
          #  → [1,1,1,1]
     P    # And check if all are truthy by taking their product
          #  → 1
          # (after which the result is output implicitly)

```
> 2 votes

# Answer
# Javascript 101 bytes

a different approach from the js solution posted here

```
F=(s,i=0,l=o="")=>[...s].every(c=>c>=0?[l^c,l==c,,l<c,l>c,l<=c,,l>=c]["!==<><=>=".search(o,l=c,o="")]:o+=c,l=o="")

console.log(F("3<=4!=9>3==3")==true)
console.log(F("3<=4!=4")==false)
console.log(F("5>5")==false)
console.log(F("8==8<9>0!=2>=1")==true)
```
> 1 votes

# Answer
# Java 8, ~~283~~ 270 bytes

```
s->{String[]a=s.split("\\d"),b=s.split("\\D+");int i=0,r=1,x,y;for(;i<a.length-1;y=new Byte(b[++i]),r-=a[i].equals("==")&x!=y|a[i].equals("!=")&x==y|a[i].equals(">")&x<=y|a[i].equals(">=")&x<y|a[i].equals("<")&x>=y|a[i].equals("<=")&x>y?1:0)x=new Byte(b[i]);return r>0;}

```

-13 bytes thanks to *@ceilingcat*.

**Explanation:**

Try it here.

```
s->{                             // Method with String parameter and boolean return-type
  String[]a=s.split("\\d"),      //  All the inequalities
          b=s.split("\\D+");     //  All the digits
  int i=0,                       //  Index-integer (starting at 0)
      r=1,                       //  Flag integer for the result, starting at 1
      x,y;                       //  Temp integer `x` and `y`
  for(;i<a.length-1              //  Loop `i` in the range [0, length]:
      ;                          //    After every iteration:
       y=new Byte(b[++i]),       //     Convert the `i+1`'th digit from String to integer,
                                 //     and store it in `y`
       r-=                       //     Decrease the result by:
          a[i].equals("==")&x!=y //      If "==" and `x` and `y` are not equal
          |a[i].equals("!=")&x==y//      or if "!=" and `x` and `y` are equal
          |a[i].equals(">")&x<=y //      or if ">" and `x` is smaller than or equal to `y`
          |a[i].equals(">=")&x<y //      or if ">=" and `x` is smaller than `y`
          |a[i].equals("<")&x>=y //      or if "<" and `x` is larger than o equal to `y`
          |a[i].equals("<=")&x>y //      or if "<=" and `x` is larger than `y`:
           1                     //       Decrease the result by 1
          :0;                    //      Else: keep it the same by decreasing with 0
    x=new Byte(b[i]);            //   Convert the `i`'th digit from String to integer,
                                 //   and store it in `x`
  return r>0;}                   //  Return whether the result is still 1

```
> 0 votes

---
Tags: code-golf, decision-problem
---


title: Game of Game of Life

text:
# Question
Title: Game of Game of Life
# Game of Game of Life

Conway's Game of Life is a 0-player game. But that's okay! We can make it a multi-player game.

This game is played on the smallest square grid that will accommodate a 6x6 square for each player (12x12 for 2-4 players, 18x18 for 5-9 players, etc). This grid is actually a torus, so it wraps in both directions. The rules of Life are:

* If a cell has exactly 3 neighbours, it comes to life (or remains alive) in the next generation.
* If a cell has exactly 2 neighbours, it does not change in the next generation.
* If it does not have exactly 2 or 3 neighbours, it dies in the next generation.

A cell's neighbours are those cells adjacent to it orthogonally or diagonally; each cell has 8 neighbours. In this game, there are only a few differences from the standard Game of Life:

* Each player has a different colour of life, with dead cells being white and neutral living cells being black.
* When a cell becomes alive, it takes on the colour of its most common neighbour, or black (no player) if there are three different colours. Cells do not change colour as long as they are alive.
* Each generation, each bot can cause one nearby cell to come alive in their colour or one of their own cells to die. This happens before a generation is processed; a cell that is killed may come back to life and a cell brought to life may die in the subsequent generation.

# Winning the game

The game lasts 1000 generations, or until there is only one colour of living cells remaining. If all coloured cells die on the same generation, the game is a draw, and no bot receives points. Each bot scores points equal to the percentage of living coloured cells it has at that time (out of the total number of coloured cells). 10000 games will be run, and the winner is the bot with the highest average score. Ties are broken with a 1v1 cage match.

# Starting conditions

Each bot will start with the following layout of living cells:

```
......
......
..##..
..##..
......
......

```

These will be randomly arranged into the square playing area. Each 6x6 area without a bot will have the same configuration, but with black living cells.

# Bot parameters

Your bot will be written in Javascript, and will not have an average call time of over 50ms (bots that do may be disqualified, but bots may use `performance.now()` to police their own time). It will accept as parameters:

```
grid - The grid on which the game is played.  This should not be modified.
botId - The bot's ID, corresponding to the colour on the grid.
lastMoves - An array of each bot's most recent move, as it's (usually) possible but computationally intensive to get this information otherwise.

```

Your bot will return an array with two elements, x and y. This is the cell that your bot wishes to play. It must be within 2 cells of one of your living cells. If the selected cell is alive and not one of your cells, it does nothing unless the bot whose colour it is removes it on the same generation, in which case it causes it to be your colour. If it is alive and one of your cells, that cell is killed before the next generation. If it is a dead cell, it comes alive before the next generation (it comes alive as your bot's colour unless some other bot also picks it, in which case it comes alive black).

A play too far away from one of your cells is a pass. Alternately, \[-1,-1\] is an explicit pass. A play off of the board in any other way is illegal and grounds for disqualification.

On the grid, -1 is black (neutral living), 0 is white (dead), and all other numbers are the id of the bot whose life is in that cell.

# Other Restrictions

* You may make a maximum of 3 bots.
* If your bots uses random numbers you can use `Math.random`.
* Your bot may, if it wishes, store data on `this`. It will be cleared between games.
* You may not make a bot which targets a single, prechosen bot. Your bot may target the tactics of a class of bots.
* Cooperation is legal between bots, but communication is not - you can cooperate with a strategy, but not attempt to make a specific sequence of moves which identifies your bot. For example, identifying a bot based on specific starting sequence is not allowed, but knowing "target bot prefers moving up and left, all else equal" is okay. IDs are randomized and bots will not know in advance what other bots' IDs are.

# Controller

This isn't quite complete, but it's a good start. I plan to keep track of scores, add a box so it's easy to test a new bot, etc. Of course, some of that is hard to test without real competitors, but I'll get around to it.

It seems that I made x the major axis and y the minor one, so if your bot is going a different way than you expect, that might be why. Sorry.

Code Run it here

# Example bot

It seems traditional to include a bad bot in the competition to get things started. This bot is *bad*. It chooses uniformly at random from cells in the grid and tries to move there. I haven't yet had it survive 1000 generations.

```
function randomMovesBot(grid, botId, lastMoves){
    return [Math.floor(Math.random() * grid.length), Math.floor(Math.random() * grid.length)];
}

```

# Winner

Two weeks after the last new submission (or a significant change to a bot), I'll close this by running 10000 games (number subject to possible revision). I'll leave the controller up afterward if someone wants to make a new submission, but official standings won't change.

# Chat

# Answer
> 8 votes
# Do-nothing

```
function rgs_do_nothing(grid, id, last_moves) {
    return [-1, -1];
}

```

As of the time of posting, this wins against all other bots in the competition fairly consistently.

This bot is funny because in the branch of numerical analysis where I did some research, sometimes we have *partial differential equations* with these *do-nothing boundary conditions* and for a method I implemented, it **literally** amounted to doing nothing to handle the boundary conditions... My best type of work is when it is legit to do nothing :')

# Answer
> 4 votes
# planBbot

I took planBot as a blue print. With simple enhancements/changes:

### Version 1.1

* improved move selection: never delete own colour cells
* improved scoring
* improved time management: used a PD-Controller to stay at 50ms
* changed policy: dropped endgame mode
* result of playing 100 games:

```
Name            Score
BestNowBot        0
planBbot v1.1   100
planBot           0
randomMovesBot    0
rgs_do_nothing    0

```

### Version 1.0

* simple time management: Try to stay within 50 ms per move on average while using as much time as possible for lookaheads.
* some performance tweaks: Undone caching of results. (Identical board states are too unlikely.)
* scoring: The idea: Stay sparse and don't feed the opponent.
* endgame aware: If planBbot survived until generation 990 it starts to look deep ahead to generation 1000.
* result of playing 100 games:

```
Name            Score
BestNowBot        0.64
planBbot v1.0    85.40
planBot          13.94
randomMovesBot    0
rgs_do_nothing    0

```

```
// version 1.1
function planBbot(grid, botId, lastMoves) {
    let t0=performance.now();
    let best_cell = [-1, -1];
    let max_score = -10000000;
    let size = grid.length;
    let possible_moves = new Set();
    let dist = 1
    for (let x = 0; x < size; x++) {
        for (let y = 0; y < size; y++) {
            if (grid[x][y] == botId) {
                for (let dx = -dist; dx <= dist; dx++) {
                    for (let dy = -dist; dy <= dist; dy++) {
                        let x1 = (size + x + dx) % size;
                        let y1 = (size + y + dy) % size;
                        if (grid[x1][y1] == 0) {
                            possible_moves.add([x1, y1]);
                        }
                    }
                }
            }
        }
    }
    if (possible_moves.size == 0) {
        return best_cell;
    }

    let new_grid = Array(size).fill(0).map(() => new Array(size).fill(0));
    if (typeof this.A == "undefined" || typeof this.A.dtime == "undefined") {
        this.A={iters:4, dtime:49, count:0, e0:0};
        this.A.lookahead=function(old_grid, new_grid){
            let iscore = 0;
            let oscore = 0;
            let neighbours = [];
            for (let x = 0; x < size; x++) {
                for (let y = 0; y < size; y++) {
                    neighbours.length = 0;
                    for (let dx = -1; dx <= 1; dx++) {
                        for (let dy = -1; dy <= 1; dy++) {
                            if ((dx == 0) && (dy == 0)) {
                                continue;
                            }
                            let cell = old_grid[(size + x + dx) % size][(size + y + dy) % size];
                            if (cell != 0) {
                                neighbours.push(cell);
                            }
                        }
                    }

                    let next=old_grid[x][y];
                    switch(neighbours.length) {
                    case 2: break;
                    case 3: if (next == 0) {
                            if (neighbours[0] == neighbours[1] || neighbours[0] == neighbours[2]) {
                                next = neighbours[0];
                            } else if (neighbours[1] == neighbours[2]) {
                                next = neighbours[1];
                            } else {
                                next = -1;
                            }
                        }
                        break;
                    default: next = 0;
                    }

                    new_grid[x][y] = next;
                    if (next == botId) {
                        iscore++;
                    } else if (next != 0) {
                        oscore++;
                    }
                }
            }
            if (oscore==0) {
                return 100000
            }
            return (iscore)-4*(oscore);
        }
    }

    let me=this.A;
    me.count++;
    let e=49-me.dtime;
    me.iters+=0.05*e+0.0005*(e-me.e0);
    me.e0=e;
    let iters=0.3*size*size*Math.max(me.iters, 2)/possible_moves.size;
    iters=Math.min(Math.max(iters+0.5, 3), 7);
    for (cell of possible_moves) {
        let old_grid = grid.map(x => x.slice());
        old_grid[cell[0]][cell[1]] = botId - old_grid[cell[0]][cell[1]];
        let score = 0;
        for (let i = 0; i < iters; i++) {
            score += me.lookahead(old_grid, new_grid);
            let tmp = new_grid;
            new_grid = old_grid;
            old_grid = tmp;
        }

        if (score >= max_score) {
            max_score = score;
            best_cell = cell;
        }
    }
    me.dtime=performance.now() - t0;
    return best_cell;
}

```

# Answer
> 2 votes
# Best Now Bot

```
function BestNowBot(grid, botId, lastMoves){
    let wrap = coord => coord < 0 ? coord + grid.length : coord >= grid.length ? coord - grid.length : coord;
    let adj_life = (x, y) => {
        let sum = 0, sum_mine = 0;
        for (let i = -1; i <= 1; i++){
            for (let j = -1; j <= 1; j++){
                if (!i && !j) continue;
                if (grid[wrap(x+i)][wrap(y+j)]) sum++;
                if (grid[wrap(x+i)][wrap(y+j)] == botId) sum_mine++;
            }
        }
        return [sum, sum_mine];
    }
    let my_cells = [];
    for (let i = 0; i < grid.length; i++){
        for (let j = 0; j < grid.length; j++){
            if (grid[i][j] == botId){
                my_cells.push([i, j]);
            }
        }
    }
    let legal_moves = my_cells.slice();
    my_cells.forEach(cell => {
        for (let i = -2; i <= 2; i++){
            for (let j = -2; j <= 2; j++){
                let x = wrap(cell[0] + i),
                    y = wrap(cell[1] + j);
                if (grid[x][y] == 0 && !legal_moves.some(m => m[0] == x && m[1] == y)){
                    legal_moves.push([x, y]);
                }
            }
        }
    });
    // Calculate results of each move.
    legal_moves.forEach(move => {
        let move_score = 0;
        if (grid[move[0]][move[1]] == botId) move_score--;
        for (let i = -1; i <= 1; i++){
            for (let j = -1; j <= 1; j++){
                let x = wrap(move[0] + i),
                    y = wrap(move[1] + j);
                let [adj, adj_mine] = adj_life(x, y);
                if (grid[x][y] == botId && adj == 3){
                    move_score--;
                } else if (grid[x][y] == 0 && adj == 2 && adj_mine > 0){
                    move_score++;
                }
            }
        }
        move.push(move_score);
    });
    let best = Math.max(...legal_moves.map(m => m[2]));
    let good_moves = legal_moves.filter(m => m[2] == best);
    return good_moves[Math.floor(Math.random() * good_moves.length)].slice(0, 2);
}

```

BestNowBot looks at all the available options and determines which of them are positive for it, and then selects randomly from them. Feel free to use BestNowBot as a basis for an answer - I figure it's kind of a baseline for an effective bot.

At time of posting, wins ~99% of games.

# Answer
> 2 votes
```
function advance(hash_grid, old_grid, new_grid){
    let hash = 0;
    let size = old_grid.length;
    let neighbours = [];
    for (let x = 0; x < size; x++) {
        for (let y = 0; y < size; y++) {
            neighbours.length = 0;
            for (let dx = -1; dx <= 1; dx++) {
                for (let dy = -1; dy <= 1; dy++) {
                    if ((dx == 0) && (dy == 0)) {
                        continue;
                    }
                    let cell = old_grid[(size + x + dx) % size][(size + y + dy) % size];
                    if (cell != 0) {
                        neighbours.push(cell);
                    }
                }
            }
            if (neighbours.length < 2 || neighbours.length > 3) {
                new_grid[x][y] = 0;
            } else if (neighbours.length == 3 && old_grid[x][y] == 0) {
                if (neighbours[0] == neighbours[1] || neighbours[0] == neighbours[2]) {
                    new_grid[x][y] = neighbours[0];
                } else if (neighbours[1] == neighbours[2]) {
                    new_grid[x][y] = neighbours[1];
                } else {
                    new_grid[x][y] = -1;
                }
            } else {
                new_grid[x][y] = old_grid[x][y];
            }
            hash += hash_grid[x][y] * new_grid[x][y];
        }
    }
    return hash;
}

function planBot(grid, botId, lastMoves) {
    let size = grid.length;
    let possible_moves = new Set();
    let count = 0;
    for (let x = 0; x < size; x++) {
        for (let y = 0; y < size; y++) {
            if (grid[x][y] == botId) {
                count++;
                for (let dx = -1; dx <= 1; dx++) {
                    for (let dy = -1; dy <= 1; dy++) {
                        let x1 = (size + x + dx) % size;
                        let y1 = (size + y + dy) % size;
                        if ((grid[x1][y1] == 0) || (grid[x1][y1] == botId)) {
                            possible_moves.add([x1, y1]);
                        }
                    }
                }
            }
        }
    }
    let possible_move_array = Array.from(possible_moves);
    if (possible_move_array.length == 0) {
        return [0,0];
    }
    let neighbor_scores = function(n) {
        if ((n >= 2) && (n <= 3)) {
            return 0;
        }
        return -1;
    }
    let best_cell = [0, 0];
    let max_score = -10000;
    let memo = new Map();
    let hash_grid = Array(size).fill(0).map(() => new Array(size).fill(0).map(() => Math.random()));
    let new_grid = Array(size).fill(0).map(() => new Array(size).fill(0));
    let iters = 4;
    for (cell of possible_move_array) {
        let old_grid = grid.map(x => x.slice());
        old_grid[cell[0]][cell[1]] = botId - old_grid[cell[0]][cell[1]];
        let hashes = []
        let score = 0;
        let hit = false;
        for (let i = 0; i < iters; i++) {
            let hash = advance(hash_grid, old_grid, new_grid);
            hashes.push(hash);
            if (memo.has(hash)) {
                score = memo[hash];
                hit = true;
                break;
            }
            let tmp = new_grid;
            new_grid = old_grid;
            old_grid = tmp;
        }
        if (!hit) {
            for (let x = 0; x < size; x++) {
                for (let y = 0; y < size; y++) {
                    if (old_grid[x][y] == botId) {
                        score++;
                    } else if (old_grid[x][y] > 0) {
                        score -= 1e-7;
                    }
                }
            }
        }
        for (hash of hashes) {
            memo.set(hash, score);
        }
        score += 1e-9 * Math.random();
        if (score >= max_score) {
            max_score = score;
            best_cell = cell;
        }
    }
    return best_cell;
}

```

Rolls ahead a few steps for each potential move and picks the move which resulted in the greatest area for itself, breaking ties by total opponent area. It also caches the results to avoid simulating identical board states.

---
Tags: game, king-of-the-hill, javascript, cellular-automata, game-of-life
---


# Question
Title: Computing a specific coefficient in a quotient of polynomials
# Context

After "Computing a specific coefficient in a product of polynomials", asking you to compute a specific coefficient of polynomial multiplication, I wish to create a "mirror" challenge, asking you to compute a specific coefficient from polynomial division.

# Polynomial division

Let us establish an analogy with integer division. If you have two integers `a` and `b`, then there is a unique way of writing `a = qb + r`, with `q, r` integers and `0 <= r < b`.

Let `p(x), a(x)` be two polynomials. Then there is a unique way of writing `a(x) = q(x)p(x) + r(x)`, where `q(x), r(x)` are two polynomials and the degree of `r(x)` is strictly less than the degree of `p(x)`.

# Algorithm

Polynomial division can be performed through an iterative algorithm:

1. Initialize the quotient at `q(x) = 0`
2. While the degree of `a(x)` is at least as big as the degree of `p(x)`:
    * let `n = degree(a) - degree(p)`, let `A` be the coefficient of the term of highest degree in `a(x)` and `P` be the coefficient of highest degree in `p(x)`.
    * do `q(x) = q(x) + (A/P)x^n`
    * update `a(x) = a(x) - p(x)(A/P)x^n`
3. `q(x)` is the quotient and what is left at `a(x)` is the remainder, which for our case will always be `0`.

# Task

Given two polynomials `a(x)`, `p(x)` such that there exists `q(x)` satisfying `a(x) = p(x)q(x)` (with all three polynomials having integer coefficients), find the coefficient of `q(x)` of degree `k`.

(Yes, we are assuming the remainder is `0`)

# Input

Two polynomials (with integer coefficients) and an integer.

Each input polynomial can be in any sensible format. A few suggestions come to mind:

* A string, like `"1 + 3x + 5x^2"`
* A list of coefficients where index encodes exponent, like `[1, 3, 5]`
* A list of `(coefficient, exponent)` pairs, like `[(1, 0), (3, 1), (5, 2)]`

An input format must be sensible AND completely unambiguous over the input space.

The integer `k` is a non-negative integer. You may take it in any of the usual ways. You can assume `k` is less than or equal to the differences of the degrees of `a(x)` and `p(x)`, i.e. `k <= deg(a) - deg(p)` and you can assume `deg(a) >= deg(p)`.

# Output

The **integer** corresponding to the coefficient of `x^k` in the polynomial `q(x)` that satisfies the equality `a(x) = q(x)p(x)`.

# Test cases

The input order for the test cases is `a(x)`, `p(x)`, integer `k`.

```
[12], [4], 0 -> 3
[0, 0, 6], [0, 3], 0 -> 0
[0, 0, 6], [0, 3], 1 -> 2
[0, 70, 70, 17, 70, 61, 6], [0, 10, 10, 1], 0 -> 7
[0, 70, 70, 17, 70, 61, 6], [0, 10, 10, 1], 1 -> 0
[0, 70, 70, 17, 70, 61, 6], [0, 10, 10, 1], 2 -> 1
[0, 70, 70, 17, 70, 61, 6], [0, 10, 10, 1], 3 -> 6
[0, -50, 20, -35, -173, -80, 2, -9, -10, -1], [0, 10, 10, 1], 0 -> -5
[0, -50, 20, -35, -173, -80, 2, -9, -10, -1], [0, 10, 10, 1], 1 -> 7
[0, -50, 20, -35, -173, -80, 2, -9, -10, -1], [0, 10, 10, 1], 2 -> -10
[0, -50, 20, -35, -173, -80, 2, -9, -10, -1], [0, 10, 10, 1], 3 -> -8
[0, -50, 20, -35, -173, -80, 2, -9, -10, -1], [0, 10, 10, 1], 4 -> 1
[0, -50, 20, -35, -173, -80, 2, -9, -10, -1], [0, 10, 10, 1], 5 -> 0
[0, -50, 20, -35, -173, -80, 2, -9, -10, -1], [0, 10, 10, 1], 6 -> -1

```

---

This is so shortest submission in bytes, wins! If you liked this challenge, consider upvoting it... And happy golfing!

(This is **not** part of the RGS Golfing Showdown)

# Answer
# MATL, 6 bytes

```
Y-PiQ)

```

The inputs contain the coefficients in order of decreasing powers.

Try it online! Or verify all test cases

### Explanation

> (De)convolution is the key to success

```
     % Implicit inputs: two numerical vectors
Y-   % Deconvolution
P    % Flip
i    % Input: integer
Q    % Add 1
)    % Get the entry at that position
     % Implicit display

```
> 6 votes

# Answer
# Wolfram Language (Mathematica), 31 bytes

```
Coefficient[Factor[#/#2],x,#3]&

```

Try it online!
> 3 votes

# Answer
# JavaScript (ES6), 81 bytes

Takes input as `(a,p,k)`. The polynomial coefficients are expected from highest to lowest.

```
(a,[c,...p],k)=>a.slice(p.length+k).map((_,n)=>p.map(v=>a[++n]-=v*q,q=a[n]/c))&&q

```

Try it online!
> 2 votes

# Answer
# Python 3, ~~51 49~~ 48 bytes

Input: `a`, `p`, `k`. The format for the polynomials `a` and `p` is a list of coefficients, in order of highest to lowest degree.

```
lambda*p,k:numpy.polydiv(*p)[0][~k]
import numpy

```

Try it online!
> 1 votes

# Answer
# Pari/GP, 24 bytes

```
f(a,p,k)=polcoeff(a/p,k)

```

Try it online!
> 1 votes

---
Tags: code-golf, math, integer, polynomials
---


# Question
Title: Counting Distinct Real Roots of Low-Degree Polynomials
**Challenge:** I want to know about the real roots of polynomials. As a pure mathematician, I care about the existence of such roots, rather than their numeric values.

The challenge is to write the shortest program that takes a polynomial, of degree at most 4, and simply returns how many distinct real roots said polynomial has. Polynomials with degree 4 or less have the unique property that there exist closed forms (such as the quadratic formula), which give all their roots. You can google these forms or find some useful related information in the appendix.

**Input:** the coefficients of a polynomial. For simplicity, we shall only care about polynomials with integer coefficients.

You may input this as a list, get the coefficients one at a time, or use any other reasonable method. You may, for example, require polynomials of degree d to inputted as lists of length d+1.

You should specify how you convert a polynomial of degree at most 4 into a valid input.

**Output:** the number of distinct real roots of said polynomial. (meaning roots with multiplicity are only counted once)

You must output one of the integers 0,1,2,3,4 for valid polynomials, and trailing spaces are completely fine. (the special case of the polynomial, \\$P(x) = 0\\$, is discussed in the scoring section)

**Examples:** in these examples, we represent a polynomial, \\$P\\$, as a list L, where `L[i]` contains the coefficient of \\$x^i\\$ in \\$P\\$. (with index starting at 0)

\\$P(x) = 1\\$, `input: [1], output: 0`

\\$P(x) = 1+2x\\$, `input: [1,2], output: 1`

\\$P(x) = 1+x^2\\$, `input: [1,0,1], output: 0`

\\$P(x) = 1+x+x^2+x^3 = (x+1)(1+x^2)\\$, `input: [1,1,1,1], output: 1`

\\$P(x) = 2+3x+x^2 = (x+2)(x+1)\\$, `input: [2,3,1], output: 2`

\\$P(x) = 1-2x+x^2 = (x-1)^2\\$, `input: [1,-2,1], output: 1`

**Scoring:**

*-5 bytes* if the polynomial, \\$P(x) = 0\\$, outputs a representation of infinity, such as: the infinity float in python, the Unicode symbol , or a string that can be mathematically interpreted to evaluate to infinity, like "1/0". (otherwise, you don't need to handle this case)

Otherwise, shortest code wins. (however I am personally quite interested in seeing answers which don't rely on built-in root finders)

**Appendix: Closed Forms**

Starting with the basics:

*Degree 0:* \\$P(x) = a\\$, roots: none, (or all reals, if a = 0)

*Degree 1:* \\$P(x) = ax+b\\$, roots: \\$x=-b/a\\$

*Degree 2:* \\$P(x) = ax^2+bx+c\\$, roots: \\$x = \frac{-b \pm \sqrt{b^2-4ac}}{2a}\\$

Then, we have the harder ones. For these, it becomes quite verbose to state the closed forms. I've paraphrased some ways you can deduce the number of roots by considering discriminants, you may also seek to find the closed forms of the roots.

*Degree 3:* From Wikipedia. \\$ P(x) = ax^3+bx^2+cx+d\\$. We define the discriminant as \\$\Delta = 18abcd -4b^3d+b^2d^2-4ac^3-27a^3d^2\\$.

If \\$\Delta \> 0\\$ then there are 3 distinct roots, if \\$\Delta = 0\\$, then there are two distinct real roots, otherwise then \\$ \Delta \< 0\\$ and there is only one real root.

*Degree 4:* From Wikipedia.\\$ P(x) = ax^4+bx^3+cx^2+dx+e\\$. We define the discriminant as $$\begin{align} \Delta\ =\ &256 a^3 e^3 - 192 a^2 b d e^2 - 128 a^2 c^2 e^2 + 144 a^2 c d^2 e - 27 a^2 d^4 \\ &+ 144 a b^2 c e^2 - 6 a b^2 d^2 e - 80 a b c^2 d e + 18 a b c d^3 + 16 a c^4 e \\ &- 4 a c^3 d^2 - 27 b^4 e^2 + 18 b^3 c d e - 4 b^3 d^3 - 4 b^2 c^3 e + b^2 c^2 d^2 \end{align}$$

If \\$\Delta \> 0\\$ then there are two distinct real roots. Otherwise things get more complicated.

Defining \\$P = 8ac - 3b^2\\$, \\$D = 64 a^3 e - 16 a^2 c^2 + 16 a b^2 c - 16 a^2 bd - 3 b^4\\$, then if \\$ \Delta \< 0 \\$ and \\$ P \< 0\\$ and \\$ D \< 0 \\$ then there are 4 distinct real roots. Otherwise, if \\$ \Delta \< 0\\$, there are 2 distinct real roots.

Finally, if \\$\Delta = 0\\$, we define \\$\Delta\_0=c^2-3bd+12ae\\$ and \\$R= b^3+8da^2-4abc\\$.

If \\$D =0\\$, then:

* \\$ P \< 0\\$ implies two distinct real roots
* \\$ P \> 0\\$ implies zero distinct real roots
* \\$P = 0\\$ implies four distinct real roots

Else, if \\$\Delta\_0 = 0\\$, then there are two distinct real roots.

Else, if \\$P\<0\\$ and \\$D \<0\\$ there are three distinct real roots.

Else, there are one real root.

# Answer
# JavaScript (Node.js),  ~~285 ... 248~~  247 - 5 = 242 bytes

<sup>*Fixed a bug and saved a couple of bytes by borrowing @Grimmy's method for the final count of the real roots*</sup>

Expects the coefficients from highest to lowest.

This is an implementation of Sturm's theorem, and therefore works for **any degree**, which might be a bit overkill for this challenge.

```
p=>1/p[1]?(h=(A,[[c,...q],[...p]]=A,n=q.length)=>n?h([(g=i=>1/p[(j=i)+n]?g(i+1,q.map(v=>p[++j]-=v*p[i],p[i]/=c)):p.slice(-n).map(v=>-v))(0),...A]):A)([p.flatMap(v=>1/p[++i]?(p.length-i)*v:[],i=k=s=0),p]).map(p=>s+=Math.sign(k*(k=p[0])))|s:1/!!+p-1

```

Try it online!

### How?

We first test whether the degree is \\$0\\$, which is an edge case:

```
p =>                   // p[] = polynomial coefficients
  1 / p[1] ?           // if p[1] is defined:
    ...                //   general case
  :                    // else:
    1 / !!+p - 1       //   return +Infinity if p[0] = 0, or 0 otherwise

```

For the general case, we use the recursive function \\$h\\$ to build the Sturm sequence of polynomials in reverse order \\$\[p\_n,...,p\_1,p\_0\]\\$, where \\$p\_0\\$ is the input and \\$p\_n\\$ is of degree \\$0\\$.

The initial call to \\$h\\$ is performed with \\$\[q,p\]\\$ where \\$q\\$ is the derivative of \\$p\\$ computed as follows:

```
p.flatMap(v =>         // for each coefficient v in p[]:
  1 / p[++i] ?         //   increment i; if p[i] is defined:
    (p.length - i) * v //     multiply v by the exponent at this position - 1
  :                    //   else:
    [],                //     this is the constant term: discard it
  i = k = s = 0        //   start with i = 0 (k and s are used later)
)                      // end of flatMap()

```

Below is the definition of \\$h\\$:

```
h = (                  // h is a recursive function taking:
  A,                   //   A[] = current Sturm sequence, which is split into:
  [[c, ...q], [...p]]  //     c = 1st coefficient of the divisor
  = A,                 //     q[] = other coefficients of the divisor
                       //     p[] = copy of the dividend
  n = q.length         //   n = number of coefficients in q[]
) =>                   //
  n ?                  // if n is not equal to 0:
    h([g(0), ...A])    //   preprend a new polynomial to A[], using g (see below)
  :                    // else:
    A                  //   end of recursion: return A[]

```

Where \\$g\\$ computes the remainder of \\$p/q\\$, multiplied by \\$-1\\$:

```
g = i =>               // g is a recursive function taking a counter i
  1 / p[(j = i) + n] ? // copy i into j; if p[j + n] is defined:
    g(                 //   do a recursive call:
      i + 1,           //     with i + 1
      q.map(v =>       //     for each coefficient v in q[]:
        p[++j] -=      //       increment j; subtract from p[j]:
          v * p[i],    //         v multiplied by p[i]
        p[i] /= c      //       start by normalizing p[i], using c
      )                //     end of map()
    )                  //   end of recursive call
  :                    // else:
    p.slice(-n)        //   end of recursion: isolate the remainder
    .map(v => -v)      //   and invert all signs

```

Finally, we compute the number of real roots by applying the following code to the Sturm sequence:

```
.map(p =>              // for each polynomial p in the sequence:
  s += Math.sign(      //   add to s the sign of:
    k *                //     multiply the previous leading coefficient
    (k = p[0])         //     by the leading coefficient of p (and update k)
  )                    //   NB: k and s are initialized to 0 earlier in the code
) | s                  // end of map(); yield s

```
> 9 votes

# Answer
# 05AB1E, 39 bytes

```
gŠ¦ƶ‚íλ£¬/D₂0š*₂-2£δ*˜0š2ôO+(¦¦}€нüP.±O

```

Try it online!

05AB1E doesn't have a built-in to get the roots of a polynomial, so we use Sturm's theorem

```
g                   # length of the input (degree + 1)
 Š                  # push two more copies of the input
  ¦                 # drop the first coefficient
   ƶ                # multiply each coefficient by its 1-based index
                    # => this is the derivative of the input
    ‚               # pair the input with its derivative
     í              # reverse both, so the constant coeff is now last

λ£            }     # recursively compute the Sturm's sequence:
                    # (initially, a(n-2) = input and a(n-1) = derivative)
  ¬/                #  divide a(n-1) by its first element
    D               #  duplicate
     ₂              #  push a(n-2)
      0š            #  prepend a 0
        *           #  multiply
         ₂-         #  subtract a(n-2)
           2£       #  keep the first two coefficients
                    #  => this is the polynomial division -a(n-2) / a(n-1)
  δ*                #  double-vectorized multiplication
    ˜               #  flatten
     0š             #  prepend a 0
       2ô           #  split in groups of 2
         O          #  sum each group
          +         #  add a(n-2)
                    #  => this is the remainder
           (        #  negate
            ¦¦      #  drop the two leading zeroes

€н                  # keep only the highest-order coefficient of each polynom
  üP                # pairwise product
    .±              # sign of each
      O             # sum

```
> 6 votes

# Answer
# Wolfram Language (Mathematica), ~~25~~ ~~32~~ ~~31~~ 27 bytes

*+7 bytes for bugfix*

*-4 bytes thanks to @JungHwanMin*

```
Length@#&@@RootIntervals@#&

```

Try it online!
> 3 votes

# Answer
# Jelly, 12 bytes \- 5 = 7

```
ÆrQṠṠƑ€SµİẸ?

```

A monadic link accepting a list of coefficients from highest degree to lowest which yields a number or the list `[inf]` if all the integers given were zero. As a full program prints the number or `inf`.

**Try it online!**

### How?

```
ÆrQṠṠƑ€SµİẸ? - Link: list of coefficients
           ? - if...
          Ẹ  - ...condition: any?
        µ    - ...then: the monadic chain:
Ær           -   roots
  Q          -   de-duplicate
   Ṡ         -   sign if real; complex conjugate if complex (vectorises)
      €      -   for each:
     Ƒ       -     is invariant under?:
    Ṡ        -       sign if real; complex conjugate if complex
       S     -   sum
         İ   - ...else: inverse

```
> 2 votes

# Answer
# Pari/GP, 8 bytes

Pari/GP has a built-in for this.

It takes an polynomial as input, e.g., `1-2*x+x^2`.

```
polsturm

```

Try it online!
> 2 votes

# Answer
# Python 3, 91 bytes

```
lambda c:sum(f.real==f for f in set(polyroots(c)))
from numpy.polynomial.polynomial import*

```

Try it online!

Had to include `set()` to take care of "double" roots. `polyroots([1, -2, 1])` gives `[1., 1.]`...
> 2 votes

# Answer
# , 44 bytes

```
sum(!Im(unique(zapsmall(polyroot(scan())))))

```

Try it online!

`zapsmall` is necessary to deal with numerical imprecision, as otherwise e.g. `2 3 1` test case would fail.
> 0 votes

# Answer
# Jelly, ~~9~~ 13 - 5 = 8 bytes

Monadic link expecting list of coefficients from lowest to highest.

```
ÆrÆiṪÐḟQLµİẸ?

```

You can try it online! How it works:

```
Ær        Find the roots of the polynomial
  Æi       and split each root into [real part, imaginary part]
     Ðḟ   Filter the list, removing elements
    Ṫ      where the imaginary part is Truthy (i.e. other than 0)
       Q  Remove duplicates
        L  and return the length of that.

```

This is the main part. Then `µİẸ?` checks if there is any non-zero coefficient. If not, returns infinity. If there is, just run the previous program I described.

Borrowed the final four bytes `µİẸ?` from Jonathan Allan's Jelly answer, increasing my count by 4 but gaining the bonus -5, for a total of -1.
> 0 votes

---
Tags: code-golf, math, number, polynomials
---


title: Ain't there nothing up my sleeves

text:
# Question
Title: Ain't there nothing up my sleeves
Note: reference to Nothing up my sleeve number.

Your task is to take no input and generate this exact output:

```
d76aa478 e8c7b756 242070db c1bdceee f57c0faf 4787c62a a8304613 fd469501
698098d8 8b44f7af ffff5bb1 895cd7be 6b901122 fd987193 a679438e 49b40821
f61e2562 c040b340 265e5a51 e9b6c7aa d62f105d 02441453 d8a1e681 e7d3fbc8
21e1cde6 c33707d6 f4d50d87 455a14ed a9e3e905 fcefa3f8 676f02d9 8d2a4c8a
fffa3942 8771f681 6d9d6122 fde5380c a4beea44 4bdecfa9 f6bb4b60 bebfbc70
289b7ec6 eaa127fa d4ef3085 04881d05 d9d4d039 e6db99e5 1fa27cf8 c4ac5665
f4292244 432aff97 ab9423a7 fc93a039 655b59c3 8f0ccc92 ffeff47d 85845dd1
6fa87e4f fe2ce6e0 a3014314 4e0811a1 f7537e82 bd3af235 2ad7d2bb eb86d391

```

A trailing newline is optional.

The MD5 hash for the version **with** trailing newline is:

* `FC1D37B5295177E7F28509EC9197688F`

The MD5 hash for the version **without** trailing newline is:

* `FAC194EC5EFD2E5A5AC07C2A4925699B`

### How the string is generated

Those 64 strings are actually the 64 hexadecimal numbers used in the MD5 hash.

The pseudocode for them:

```
numbers = floor(2^32 × abs(sin(i))) for i in [1,2,...,64]

```

The reference Python code:

```
from math import*
for i in range(8):print" ".join("{:08x}".format(int(abs(2**32*sin(-~j))))for j in range(8*i,8*i+8))

```

Ungolfed:

```
from math import*
for i in range(8):
    temp = []
    for j in range(8*i,8*i+8):
        temp += ["{:08x}".format(int(abs(2**32*sin(j+1))))]
    print " ".join(temp)

```

# Answer
> 3 votes
# Jelly, ~~26~~ ~~24~~ 23 bytes

```
64RÆSA‘æ«32Ḟb⁴Ḋ€‘ịØhs8G

```

Try it online!

### How it works

```
64RÆSA‘æ«32Ḟb⁴Ḋ€‘ịØhs8G  Main link. No arguments.

64R                      Yield [1, ..., 64].
   ÆS                    Apply sine to each.
     A                   Take absolute values.
      ‘                  Increment.
                         This avoid padding the hex strings to 8 characters.
       æ«32              Left-shift by 32 units.
           Ḟ             Floor.
            b⁴           Convert to base 16 (list of integers).
              Ḋ€         Remove the first digit of each, undoing the increment.
                ‘        Increment each base 16 digit (for 1-based indexing).
                 ịØh     Index into "0123456789abcdef".
                    s8   Split into chunks of length 8.
                      G  Grid; separate columns by spaces, rows by linefeeds.

```

# Answer
> 3 votes
# Python 2, ~~86~~ ~~77~~ 76 bytes

```
import math
n=0;exec(",\nn+=1;print'%08x'%(2**32*abs(math.sin(n)))"*8)[1:]*8

```

Test it on Ideone.

### How it works

Python 2's `print` statement has a quirk: It appends a newline to the result of its expression, unless it is followed by a trailing `,`; in this case, it appends a space. While that's usually annoying when golfing (as there's no short way to print without trailing whitespace), it's perfect for this task.

We repeat the string `,\nn+=1;print'%08x'%(2**32*abs(math.sin(n)))` eight times, chop off the leading comma with `[1:]`, and repeat the result eight times. The string that `exec` executes composed of eight identical copies of the following code.

```

n+=1;print'%08x'%(2**32*abs(math.sin(n))),
n+=1;print'%08x'%(2**32*abs(math.sin(n))),
n+=1;print'%08x'%(2**32*abs(math.sin(n))),
n+=1;print'%08x'%(2**32*abs(math.sin(n))),
n+=1;print'%08x'%(2**32*abs(math.sin(n))),
n+=1;print'%08x'%(2**32*abs(math.sin(n))),
n+=1;print'%08x'%(2**32*abs(math.sin(n))),
n+=1;print'%08x'%(2**32*abs(math.sin(n)))

```

Each line increments the variable **n** (initialized by `n=0`), applies the format string `%08x` (lowercase hexadecimal representation, left-padded with zeroes to length 8, of the integer part of its argument) to **232** times the absolute value of the sine of **n**, and prints the resulting string either with a trailing space or a trailing linefeed.

# Answer
> 2 votes
# Pyth, ~~31~~ 27 bytes

Thanks to @Dennis for saving 4 bytes!

```
jjL;c8mt.Hs*^2 32h.a.tdZS64

```

Try it here!

## Explanation

```
jjL;c8mt.Hs*^2 32h.a.tdZS64

      m                 S64   # map over [1...64]
          s*^2 32h.a.tdZ      # floor(2^32 * abs(sin(d))+1)
       t.H                    # convert to hex-string and discard the first digit
    c8                        # split into 8 parts
jjL;                          # join on whitespaces and then on newlines

```

# Answer
> 2 votes
# MATL, 28 bytes

```
64:Y,|32W*k16YAkZ{Zc72e!3LZ)

```

**Try it online!**

Pretty straightforward computation. Getting the required output format takes almost half the byte count.

# Answer
> 1 votes
# PHP, ~~131~~ 81 bytes

```
for(;++$i<65;){echo str_pad(dechex(2**32*abs(sin($i))),8,"0",0).($i%8?" ":"\n");}

```

This is a pretty straight-forward loop with a few conditions for spacing.

@insertusernamehere's shortcuts cut it down by 50 bytes.

# Answer
> 1 votes
# Julia, ~~69~~ ~~63~~ 58 bytes

```
[@printf "%08x%c"√sin(n)^2÷.5^32 n%8>0?32:10for n=1:64]

```

Try it online!

### How it works

For each **n** between **1** and **64**, we compute `√sin(n)^2÷.5^32` and `n%8>0?32:10`, apply string formatting with `"%08x%c"` and print to STDOUT.

* `√sin(n)^2` computes the absolute value of **sin(n)**. `abs(sin(n))` is equally short (in bytes), but it would require a space to separate it from the format string.

`÷.5^32` divides the previous result by **0.532 = 1 / 232**, effectively multiplying it by **232**. However, `÷` performs *integer* divsion, so the result is truncated.
* `n%8>0?32:10` returns **32** (the code point of a space) whenever **n** is not divisible by **8** and **10** (the code point of a linefeed) otherwise.
* `"%08x%c"` turns the first result into lowercase hexadecimal representation, left-padded with zeroes to length 8; and the second result into a character.

Finally, the array comprehension returns an array of **64** instances of `Nothing`, the return value of `@printf`. Outside a REPL, this does not affect output.

# Answer
> 1 votes
## JavaScript (ES7), 115 bytes

```
_=>`_ _ _ _ _ _ _ _
`.repeat(8).replace(/_/g,_=>(0+(Math.abs(Math.sin(++n))*2**32>>>0).toString(16)).slice(-8),n=0)

```

Includes the trailing newline.

# Answer
> 1 votes
# ///, ~~568~~ 567 bytes

```
/!/ f//@/fa/d76aa478 e8c7b756 242070db c1bdceee!57c0@f 4787c62a a8304613!d469501
698098d8 8b44f7af!fff5bb1 895cd7be 6b901122!d987193 a679438e 49b40821
f61e2562 c040b340 265e5a51 e9b6c7aa d62f105d 02441453 d8a1e681 e7d3fbc8
21e1cde6 c33707d6!4d50d87 455a14ed a9e3e905!ce@3f8 676f02d9 8d2a4c8a
ff@3942 8771f681 6d9d6122!de5380c a4beea44 4bdec@9!6bb4b60 bebfbc70
289b7ec6 eaa127@ d4ef3085 04881d05 d9d4d039 e6db99e5 1@27cf8 c4ac5665
f4292244 432aff97 ab9423a7!c93a039 655b59c3 8f0ccc92!feff47d 85845dd1
6@87e4f!e2ce6e0 a3014314 4e0811a1!7537e82 bd3af235 2ad7d2bb eb86d391

```

Try it online!

Too bad I can only golf ~~6~~ 7 bytes :-(

To convince you that I can't golf it further, I challenge you to do better in just ///, should you accept it. If you do, you're a magician, since Martin Ender's code says otherwise (checked)!

People that won the challenge and are worth of crediting (format: `name (id), bytes_golfed`):

* daHugLenny (56258), 1

# Answer
> 1 votes
# Perl 5, ~~56~~ ~~54~~ 52 bytes

```
printf'%08x%s'x64,map{0|2**32*abs sin,$_%8?$":$/}1..64

```

Saved ~~2~~ 4 bytes thanks to @XCali

Try it online!

# Answer
> 1 votes
# K4, 48 bytes

**Solution:**

```
-1@" "/:'8 8#(,/$4_0x0\:)'_abs sin[1+!64]*/32#2;

```

**Example:**

```
q)k)-1@" "/:'8 8#(,/$4_0x0\:)'_abs sin[1+!64]*/32#2;
d76aa478 e8c7b756 242070db c1bdceee f57c0faf 4787c62a a8304613 fd469501
698098d8 8b44f7af ffff5bb1 895cd7be 6b901122 fd987193 a679438e 49b40821
f61e2562 c040b340 265e5a51 e9b6c7aa d62f105d 02441453 d8a1e681 e7d3fbc8
21e1cde6 c33707d6 f4d50d87 455a14ed a9e3e905 fcefa3f8 676f02d9 8d2a4c8a
fffa3942 8771f681 6d9d6122 fde5380c a4beea44 4bdecfa9 f6bb4b60 bebfbc70
289b7ec6 eaa127fa d4ef3085 04881d05 d9d4d039 e6db99e5 1fa27cf8 c4ac5665
f4292244 432aff97 ab9423a7 fc93a039 655b59c3 8f0ccc92 ffeff47d 85845dd1
6fa87e4f fe2ce6e0 a3014314 4e0811a1 f7537e82 bd3af235 2ad7d2bb eb86d391

```

**Explanation:**

First pass, probably a few tricks left to golf further...

```
-1@" "/:'8 8#(,/$4_0x0\:)'_abs sin[1+!64]*/32#2; / the solution
                                           32#2  / take 2, 32 times (2 2 2 2 2...)
                                         */      / product beginning with left argument
                               sin[     ]        / built-in sine function
                                     !64         / range 0..63
                                   1+            / add 1, so 1..64
                           abs                   / built-in abs function
                          _                      / floor
             (          )'                       / do this together for each
                   0x0\:                         / convert to byte representation
                 4_                              / drop first 4 elements
                $                                / convert to string
              ,/                                 / flatten
         8 8#                                    / reshape to 8x8
   " "/:'                                        / join each with a single space
-1@                                            ; / print to stdout and swallow return

```

# Answer
> 0 votes
## Racket 125 bytes

```
(λ()(for((i(range 1 65)))(printf"~x "(inexact->exact(floor(*(expt 2 32)(abs(sin i))))))(when(= 0(modulo i 8))(printf"~n"))))

```

Ungolfed:

```
(define f
  (λ ()
    (for ((i (range 1 65)))
      (printf "~x " (inexact->exact(floor (*(expt 2 32) (abs (sin i)) ))))
      (when(= 0 (modulo i 8)) (printf "~n"))
      )))

```

Testing:

```
(f)

```

Output:

```
d76aa478 e8c7b756 242070db c1bdceee f57c0faf 4787c62a a8304613 fd469501
698098d8 8b44f7af ffff5bb1 895cd7be 6b901122 fd987193 a679438e 49b40821
f61e2562 c040b340 265e5a51 e9b6c7aa d62f105d 2441453 d8a1e681 e7d3fbc8
21e1cde6 c33707d6 f4d50d87 455a14ed a9e3e905 fcefa3f8 676f02d9 8d2a4c8a
fffa3942 8771f681 6d9d6122 fde5380c a4beea44 4bdecfa9 f6bb4b60 bebfbc70
289b7ec6 eaa127fa d4ef3085 4881d05 d9d4d039 e6db99e5 1fa27cf8 c4ac5665
f4292244 432aff97 ab9423a7 fc93a039 655b59c3 8f0ccc92 ffeff47d 85845dd1
6fa87e4f fe2ce6e0 a3014314 4e0811a1 f7537e82 bd3af235 2ad7d2bb eb86d391

```

# Answer
> 0 votes
## Pip, 37 bytes

36 bytes of code, +1 for `-S` flag.

```
0X8-#_._MMLC(2**32*ABSI++,64)TB16<>8

```

Pretty straightforward implementation. Unfortunately, 10 bytes are needed to left-pad some of the values with `0`. Try it online!

```
                         ,64          Numbers 0 to 63
                       ++             Increment to get 1 to 64
                     SI               Sine
                   AB                 Absolute value
             2**32*                   Multiply by 2^32
            (               )TB16     Convert to hex (implicitly truncating to int)
          LC                          Lowercase--Pip's base conversion uses uppercase :(
                                 <>8  Group into sublists of size 8
        MM                            Map this function to each item of each sublist:
  8-#_                                  1 if item is length 7, 0 if length 8
0X                                      That many zeros
      ._                                Concatenate to beginning of item
                                      Print separated first by newline then by space (-S)

```

# Answer
> 0 votes
# Burlesque, 34 bytes

```
64{Tsab2 32**.*pd-.b68'0lp}GO8cosp

```

Try it online!

```
64      # Literal 64
{
 Ts     # Sin
 ab     # Abs
 2 32** # 2**32
 .*     # Times-by
 pd     # Floor
 -.     # Decrement by 1
 b6     # To base 16
 8'0lp  # Left pad to length 8 with 0s
}GO     # Range from [1, 64] and map
8co     # Chunks of 8
sp      # Pretty print array

```

# Answer
> 0 votes
# 05AB1E, ~~19~~ 17 bytes

```
64LÅ½ÄžJ*hl8jð0:8ô»

```

-2 bytes by taking inspiration from *@Dennis*' Jelly answer regarding the leading 0s, so make sure to upvote him!

Outputs with trailing newline.

Try it online.

**Explanation:**

```
64L                # Push a list in the range [1,64]
   Å½              # Take the sine of each
     Ä             # Take the absolute value of that
      >            # Increase it by 1 (to avoid having to pad leading 0s later on)
       žJ*         # Multiply it by builtin 4294967296
          h        # Convert it from integer to hexadecimal
                   # (which implicitly truncates the decimals; and uses uppercase [A-F])
           l       # Convert that hexadecimal string to lowercase
            €¦     # Remove the first character from each (undoing the earlier increment)
              8ô   # Split the list into parts of size 8
                »  # Join each inner list by spaces, and then those strings by newlines
                   # (after which it is output implicitly with trailing newline)

```

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


# Question
Title: Polyglot "Hello world" in Fortran and Lisp
Simple challenge: The code must be both valid Lisp and valid Fortran, and must print out "hello world" in both.

Note: I've sunk about 5 hours into this at this point, I'm not even sure it's possible at this point...

Details:

* Must be in a single source file.
* Any version of Fortran and any Lisp are allowed (specify which).
* Smallest source code (by bytes) satisfying this wins.

# Answer
> 7 votes
# Fortran (GFortran) -ffixed-form, ~~183~~ 53+12=65 bytes

```
	;print*,"Hello world!"
	;end
*(print "Hello world!")

```

Try it online!

# Common Lisp, 53 bytes

Try it online!

---
Tags: code-golf, polyglot, lisp
---


title: Interpreter for number theory, modulo n

text:
# Question
Title: Interpreter for number theory, modulo n
A *sentence* of number theory (for our purposes) is a sequence of the following symbols:

* `0` and `'` (successor) - successor means `+1`, so `0'''' = 0 + 1 + 1 + 1 + 1 = 4`
* `+` (addition) and `*` (multiplication)
* `=` (equal to)
* `(` and `)` (parentheses)
* the logical operator `nand` (`a nand b` is `not (a and b)`)
* `forall` (the universal quantifier)
* `v0`, `v1`, `v2`, etc. (variables)

Here is an example of a sentence:

```
forall v1 (forall v2 (forall v3 (not (v1*v1*v1 + v2*v2*v2 = v3*v3*v3))))

```

Here `not x` is shorthand for `x nand x` -- the actual sentence would use `(v1*v1*v1 + v2*v2*v2 = v3*v3*v3) nand (v1*v1*v1 + v2*v2*v2 = v3*v3*v3)`, because `x nand x = not (x and x) = not x`.

This states that for every combination of three natural numbers `v1`, `v2`, and `v3`, it is not the case that v13 \+ v23 = v33 (which would be true because of Fermat's Last Theorem, except for the fact that it would get 0^3+0^3=0^3).

Unfortunately, as proved by Gödel, it is not possible to determine whether or not a sentence in number theory is true.

It *is* possible, however, if we restrict the set of natural numbers to a finite set.

So, this challenge is to determine whether or not a sentence of number theory is true, when taken modulo `n`, for some positive integer `n`. For example, the sentence

```
forall v0 (v0 * v0 * v0 = v0)

```

(the statement that for all numbers x, x3 = x)

Is not true for ordinary arithmetic (e.g. 23 = 8 ≠ 2), but *is* true when taken modulo 3:

```
0 * 0 * 0 ≡ 0 (mod 3)
1 * 1 * 1 ≡ 1 (mod 3)
2 * 2 * 2 ≡ 8 ≡ 2 (mod 3)

```

### Input and output format

The input is a sentence and positive integer `n` in any "reasonable" format. Here are some example of reasonable formats for the sentence `forall v0 (v0 * v0 * v0 = v0)` in number theory modulo 3:

```
("forall v0 (v0 * v0 * v0 = v0)", 3)
"3:forall v0 (((v0 * v0) * v0) = v0)"
"(forall v0)(((v0 * v0) * v0) = v0) mod 3"
[3, "forall", "v0", "(", "(", "(", "v0", "*", "v0", ")", "*", "v0", ")", "=", "v0", ")"]
(3, [8, 9, 5, 5, 5, 9, 3, 9, 6, 3, 9, 6, 4, 9, 6]) (the sentence above, but with each symbol replaced with a unique number)
"f v0 = * * v0 v0 v0 v0"
[3, ["forall", "v0", ["=", ["*", "v0", ["*", "v0", "v0"]], "v0"]]]
"3.v0((v0 * (v0 * v0)) = v0)"

```

Input can be from stdin, a command line argument, a file, etc.

The program can have any two distinct outputs for whether the sentence is true or not, e.g. it could output `yes` if it's true and `no` if it's not.

You do not need to support one variable being the subject of a `forall` twice, e.g. `(forall v0 (v0 = 0)) nand (forall v0 (v0 = 0))`. You can assume that your input has valid syntax.

### Test cases

```
forall v0 (v0 * v0 * v0 = v0) mod 3
true

forall v0 (v0 * v0 * v0 = v0) mod 4
false (2 * 2 * 2 = 8 ≡ 0 mod 4)

forall v0 (v0 = 0) mod 1
true (all numbers are 0 modulo 1)

0 = 0 mod 8
true

0''' = 0 mod 3
true

0''' = 0 mod 4
false

forall v0 (v0' = v0') mod 1428374
true

forall v0 (v0 = 0) nand forall v1 (v1 = 0) mod 2
true (this is False nand False, which is true)

forall v0 ((v0 = 0 nand v0 = 0) nand ((forall v1 (v0 * v1 = 0' nand v0 * v1 = 0') nand forall v2 (v0 * v2 = 0' nand v0 * v2 = 0')) nand (forall v3 (v0 * v3 = 0' nand v0 * v3 = 0') nand forall v4 (v0 * v4 = 0' nand v0 * v4 = 0')))) mod 7
true
(equivalent to "forall v0 (v0 =/= 0 implies exists v1 (v0 * v1 = 0)), which states that every number has a multiplicative inverse modulo n, which is only true if n is 1 or prime)

forall v0 ((v0 = 0 nand v0 = 0) nand ((forall v1 (v0 * v1 = 0' nand v0 * v1 = 0') nand forall v2 (v0 * v2 = 0' nand v0 * v2 = 0')) nand (forall v3 (v0 * v3 = 0' nand v0 * v3 = 0') nand forall v4 (v0 * v4 = 0' nand v0 * v4 = 0')))) mod 4
false

```

This is , so try to make your program as short as possible!

# Answer
# Python 2, ~~252~~ 236 bytes

```
def g(n,s):
 if str(s)==s:return s.replace("'","+1")
 o,l,r=map(g,[n]*3,s);return['all((%s)for %s in range(%d))'%(r,l,n),'not((%s)*(%s))'%(l,r),'(%s)%%%d==(%s)%%%d'%(l,n,r,n),'(%s)%s(%s)'%(l,o,r)]['fn=+'.find(o)]
print eval(g(*input()))

```

Try it online!

Takes input as the nested prefix-syntax, with `f` instead of `forall` and `n` instead of `nand`:

```
[3, ["f", "v0", ["=", ["*", "v0", ["*", "v0", "v0"]], "v0"]]]

```
> 3 votes

# Answer
# APL (Dyalog Unicode), 129 bytesSBCS

```
{x y z←3↑⍵⋄7≤x:y×7<x⋄5≡x:∧/∇¨y{⍵≡⍺⍺:⍵⍺⋄x y z←3↑⍵⋄7≤x:⍵⋄6≡x:x(⍺∇y)⋄x(⍺∇⍣(5≢x)⊢y)(⍺∇z)}∘z¨⍳⍺⍺⋄y←∇y⋄6≡x:1+y⋄y(⍎x⊃'+×⍲',⊂'0=⍺⍺|-')∇z}

```

Try it online!

Takes a prefix syntax tree as in TFeld's python answer, but using an integer encoding. The encoding is

```
plus times nand eq forall succ zero ← 1 2 3 4 5 6 7

```

and each variable is assigned a number starting from 8. This encoding is slightly different from the one used in the ungolfed version below, because I tweaked it while golfing the code.

The task involves only two inputs (the AST and the modulo), but writing it as an operator instead of a function avoids mentioning the modulo many times (as it is always carried over recursive calls).

### Ungolfed with comments

```
⍝ node types; anything ≥8 will be considered a var
plus times eq nand forall succ zero var←⍳8
⍝ AST nodes have 1~3 length, 1st being the node type
⍝ zero → zero, succ → succ arg, var → var | var value (respectively)

⍝ to (from replace) AST → transform AST so that 'from' var has the value 'to' attached
replace←{
  ⍵≡⍺⍺:⍵⍺             ⍝ variable found, attach the value
  x y z←3↑⍵
  zero≤x: ⍵           ⍝ zero or different variable: keep as is
  succ≡x: x(⍺∇y)      ⍝ succ: propagate to y
  forall≡x: x y(⍺∇z)  ⍝ forall: propagate to z
  x(⍺∇y)(⍺∇z)         ⍝ plus, times, eq, nand: propagate to both args
}
⍝ (mod eval) AST → evaluate AST with the given modulo
eval←{
  x y z←3↑⍵
  zero≡x:   0
  var≤x:    y                    ⍝ return attached value
  forall≡x: ∧/∇¨y replace∘z¨⍳⍺⍺  ⍝ check all replacements for given var
  succ≡x:   1+∇y
  plus≡x:   (∇y)+∇z
  times≡x:  (∇y)×∇z
  eq≡x:     0=⍺⍺|(∇y)-∇z         ⍝ modulo equality
  nand≡x:   (∇y)⍲∇z              ⍝ nand symbol does nand operation
}

```

Try it online!
> 1 votes

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


title: Creating words by structure

text:
# Question
Title: Creating words by structure
# Context

As a conlanger, I am interested in creating a uniform, naturalistic language. One of the tricks is to create vocabulary according to certain structures of words. An example from English: In English, we have the word “tap” structured consonant-vowel-consonant. Usually, this means that there are many other words of this structure: “cat”, “dog”, “rock”, “fog”, “good”, etc.

# Task

As input, you have:

* an array `C` containing strings: consonants (`C` is the first letter in the word consonants). Identical consonants cannot be repeated on this list. For example, this list cannot contain \['b', 'b'\].
* an array `V` containing strings: vowels (`V` is the first letter of the word vowels). Identical vowels cannot be repeated on this list.
* string `S`, which contains something like this "CVCCV" (any combination of "C" and "V")

Your task is to replace “C” in the string with a randomly taken string from array `C` and replace “V” in the string with a randomly taken string from array `V` and return (or display) this string.

"randomly" is defined as all possibilities having an equal chance of being selected. This is a kind of simplification: in real languages as well as in conlangs, there are very frequent (for example 'r' in English) and not very frequent sounds but this is just a code-golf.

# Rules

This is code-golf so the lowest byte count wins.

# Examples

```
Input:
C = ['p', 'b', 't', 'd', 'k', 'g', 'm', 'n', 'w']
V = ['a', 'o', 'u', 'i', 'e', 'ä']
S = 'CVCCV'

Output:
pakto

```

```
Input:
C = ['p', 'b', 't', 'd', 'k', 'g', 'v', 's', 'r']
V = ['a', 'o', 'u', 'i', 'e', 'ä', 'ᵫ']
S = 'CVVCCVCCV'

Output:
koebrᵫvtä

```

# Answer
# 05AB1E, 4 bytes

Takes input as `S`, `[V,C]`

```
Çè€Ω

```

Try it online!
> 5 votes

# Answer
# Jelly,  ~~5~~  4 bytes

-1 thanks to Neil!

```
OịX€

```

A dyadic Link accepting a list of characters, `S`, on the left and a list of two lists of characters, `[C, V]`, on the right which yields a list of characters.

**Try it online!**

If we could take `S` as a list of `1`s and `0`s we'd have the three byte solution `ịX€`.

### How?

```
OịX€ - Link: S, [C,V]
O    - ordinals (of S)          i.e. 'C':67 'V':86
 ị   - index into [C,V] (vectorises)      C      V   [Jelly indexing is 1-indexed and modular]
   € - for each:
  X  -   random choice

```
> 4 votes

# Answer
# Python 3, ~~92~~ ~~68~~ 61 bytes

Takes input as `S`, `C`, `V`:

```
lambda s,*w:[random.choice(w[a>"u"])for a in s]
import random

```

You can try it online! How it works:

The `*w` is used so that the lists of consonants and vowels are packed in a list `w`.

When we do `w[a > "u"]` we are essentially checking if `a` (a character of `s`) is "v" or not. If it is, then `a > "u"` returns `True`, which indexes as `1` into `w`. If `a` is "c", then `a > "u"` returns `False`, which indexes as `0`.

We use those indices to retrieve the correct list of letters from `w` and then choose randomly from that list, picking the list of choices.

Thanks @Arnauld for saving one byte and to @Jonathan Allan for citing this meta, saving me 7 bytes.
> 3 votes

# Answer
# APL+WIN, ~~35~~ 34 bytes

One byte saved thanks to Adam

Prompts for consonants and vowels as continuous strings and the desired output as a comma separated string

```
c←⍞⋄v←⍞⋄C←',c[?⍴c]'⋄V←',v[?⍴v]'⋄⍎⎕

```

Try it online! Courtesy of Dyalog Classic
> 3 votes

# Answer
# Ruby, ~~45~~ 40 bytes

```
->s,*l{s.bytes.map{|x|l[x%2].sample}*''}

```

Try it online!
> 2 votes

# Answer
# Charcoal, 7 bytes

```
⭆η‽§θ℅ι

```

Try it online! Link is to verbose version of code. Takes the input in the form `[V, C], S` where each value can be either a string or an array of characters as desired. Explanation:

```
 η      `S`
⭆       Map over elements/characters
    θ   `[V, C]`
   §    Cyclically indexed by
     ℅  Ordinal of
      ι Current element/character
  ‽     Random element/character
        Implicitly print

```
> 2 votes

# Answer
# C# (Visual C# Interactive Compiler), 66 bytes

```
(C,V,s)=>s.Select(x=>(x<68?C:V).OrderBy(l=>Guid.NewGuid()).Last())

```

Try it online!
> 2 votes

# Answer
# Japt, 6 bytes

```
ËcgV ö

```

Takes input as `S`, `[V,C]`

Try it
> 2 votes

# Answer
# `f` `j`, 4 bytes

Hmm, let's do a pure-ASCII port of that.

```
C[gr

```

## Explanation

C    % Convert the string to its codepoints
 [   % Index into the other list
   r % For every indexed item:
  g  % "g"et a random item in this list

Flag:f % Flatten the output list
Flag:j % Join the flattened output list
```
</code></pre>
> 2 votes

# Answer
# JavaScript (ES6),  ~~65~~  64 bytes

```
(C,V,s)=>s.replace(/./g,x=>eval(x).sort(_=>Math.random()-.5)[0])

```

Try it online!

Or 55 bytes if we can use an array of characters as I/O.
> 1 votes

# Answer
# PHP, 68 bytes

```
function($C,$V,$s){for(;$r=$s[$i++];)echo$$r[rand(0,count($$r)-1)];}

```

Try it online!
> 1 votes

# Answer
# C (gcc), 92 bytes

```
f(s,c,v,m,n)char*s,**c,**v;{for(srand(&s);*s;)printf("%s",*s++/86?v[rand()%n]:c[rand()%m]);}

```

Takes as input a string (`s`), an array of consonant strings (`c`), an array of vowel strings `v`, the length of `c` (`m`), and the length of `v` (`n`).

Could use a temporary variable for the result of `rand` but it wouldn't save me anything.

Try it online!
> 1 votes

---
Tags: code-golf, string, random
---


title: Different tasks, same characters

text:
# Question
Title: Different tasks, same characters
In this challenge, you need to solve 4 different tasks using the same set of characters. You can rearrange the characters, but you can't add or remove characters.

The winner will be the submission that solves all tasks using the smallest number of characters. All tasks must be solved in the same language.

Note that it's the smallest number of characters, not the smallest number of *unique* characters.

**Task 1:**

Output the first `N` numbers of every third composite number. The codeblock below shows the first 19 composite numbers in the first row, and every third composite number on the row below.

```
4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 26, 27, 28, 30
4,       9,         14,         18,         22,         26,         30

```

If `N=5` then the output should be `4, 9, 14, 18, 22`. You must support `1<=N<=50`.

Composite numbers are positive numbers that aren't prime numbers or 1.

The result for `N=50` is:

```
4, 9, 14, 18, 22, 26, 30, 34, 38, 42, 46, 50, 54, 57, 62, 65, 69, 74, 77, 81, 85, 88, 92, 95, 99, 104, 108, 112, 116, 119, 122, 125, 129, 133, 136, 141, 144, 147, 152, 155, 159, 162, 166, 170, 174, 177, 182, 185, 188, 192

```

**Task 2:**

Output a `N-by-N` multiplication table. You must support `1<=N<=20`

Example:

```
N = 4
1   2   3   4
2   4   6   8
3   6   9  12
4   8  12  16

```

The output format is optional, the following is acceptable output `[[1,2,3,4],[2,4,6,8],[3,6,9,12],[4,8,12,16]]`.

**Task 3:**

Determine if a number is a Fibonacci number. You must support positive `N` up to the default integer limit of your language. If there are both 32-bit integers and 64-bit integers then you can choose to use the one that requires the shortest code. For instance, use `int` instead of `long int` if you have the choice. You can not choose a smaller integers than 32-bit unless that's default (you can't use 8-bit integers if 32-bit is default).

`true/false`, `false/true`, `1/0`, `1/-1`, `a/b` are all acceptable output as long as it's consistent.

**Task 4:**

Take `N` as input and output the result of `1^1+2^2+3^3+...N^N`. You must support `1<=N<=10`.

The 10 different results are:

```
1, 5, 32, 288, 3413, 50069, 873612, 17650828, 405071317, 10405071317

```

---

This is , so the shortest submission in each language wins!

This Stack Snippet will help check your solution. It measures the minimum set of characters needed to include all four solutions, and shows the leftover characters.

```
function update() {
  var m = {};
  var a = [q1.value, q2.value, q3.value, q4.value];
  var o = [{}, {}, {}, {}]
  for (var i = 0; i < 4; i++) {
    for (var j = 0; j < a[i].length; j++) o[i][a[i][j]] = -~o[i][a[i][j]];
    for (var c in o[i]) if (!(o[i][c] < m[c])) m[c] = o[i][c];
  }
  var t = 0;
  for (var c in m) t += m[c];
  for (var i = 0; i < 4; i++) {
    t += "\n";
    for (var c in m) t += c.repeat(m[c] - ~~o[i][c]);
  }
  p.textContent = t;
}
```

```
<div oninput="update();">
  <textarea id="q1"></textarea>
  <textarea id="q2"></textarea>
  <textarea id="q3"></textarea>
  <textarea id="q4"></textarea>
</div>
<pre id="p"></pre>
```

# Answer
# Python, 88 87 bytes

```
lambda n:[a for a in range(11*n)if any(a%b<1for b in range(2,a))][:3*n:3]#1,,,=====bd++
lambda n:[[a*b for b in range(1,n+1)]for a in range(1,n+1)]#,,::ybaaa(*i%n< =====2)d33f
f=lambda n,a=1,b=1:a<n and f(n,b,a+b)or n==a#2eerrrfo::((**iii11[[aannn+     ]]y))%33gg
f=lambda n,a=1:a<=n and a**a+f(n,a+1)#::ooeeiii]]      y))bbbgg,,rrrra((11[[nnnnf==2%33

```

Didn't put too much effort into sharing characters or the golfs themselves, this will almost surely be beat.
> 13 votes

# Answer
# Jelly, ~~19~~ ~~18~~ 17 characters

### Task 1

```
Ḟþe*S
×5µḊḟÆRm3ḣ³

```

Try it online!

### Task 2

```
5µḊḟÆRm3ḣ³Ḟe*S
×þ

```

Try it online!

### Task 3

```
5µḊḟmḣþ*S
×3RÆḞ³e

```

Try it online!

### Task 4

```
×5ḊḟÆm3ḣ³þe
Rµ*ḞS

```

Try it online!

## How it works

Every line in a Jelly program defines a separate *link* (function). The last one is the *main link* and is called automatically when the program is executed. Unless that main link references the others somehow, they have no effect. Note that even uncalled links may not contain parser errors.

### Task 1

```
×5µḊḟÆRm3ḣ³  Main link. Argument: n

×5           Yield 5n.
  µ          Begin a new chain, with argument 5n.
   Ḋ         Dequeue; yield [2, ..., 5n].
     ÆR      Prime range; yield all primes in [1, ..., 5n].
    ḟ        Filter; remove the elements to the right from the ones to the left.
       m3    Pick every third element.
         ḣ³  Keep the first n results.

```

### Task 2

This one's trivial: `×` is the multiplication atom, and the quick `þ` (table) applies `×` to each combination of elements in the left and in the right argument. If the arguments are integers (which they are here), it also casts them to range first.

### Task 3

```
×3RÆḞ³e  Main link. Argument: n

×3       Yield 3n.
  R      Range; yield [1, ..., 3n].
   ÆḞ    Fibonacci; yield [F(1), ... F(3n)].
     ³e  Test if n exists in the result.

```

### Task 4

```
Rµ*ḞS  Main link. Argument: n

R      Range; yield [1, ..., n].
 µ     Begin a new chain with argument [1, ..., n].
   Ḟ   Floor; yield [1, ..., n].
  *    Yield [1**1, ..., n**n].
    S  Take the sum.

```
> 13 votes

# Answer
## Mathematica, 60 characters

### Task 1: Composites

```
#/AFF^abcinoruy{};Select[Range[2,9#],!PrimeQ@#&][[;;3#;;3]]&

```

### Task 2: Multiplication Table

```
!29;F@FPQRS[];a^b;c[c[e]];eeegiilmnnotu;Array[3##&,{#,#}]/3&

```

### Task 3: Fibonacci

```
##&;239;A/PS[]^e[];lmrtuy;{,};!FreeQ[Fibonacci@Range[3#],#]&

```

### Task 4: Sum of powers

```
!###&;23/39;A@F;F[P[Q[]]];Raabccegiilnnorrty;Sum[e^e,{e,#}]&

```

Each submission is a set of expressions that are ignored, followed by an unnamed function which implements the given task.

I wrote a simple CJam script which "optimally" combines raw solutions by prepending a comment. I then ended up saving three bytes on top of that by manually getting rid of each comment (which required some rearranging to get valid syntax in each case). The script made it a lot easier to try out simple variations of the solutions to see if they would bring down the overall score. Feel free to use the script yourself.
> 10 votes

# Answer
# MATL, ~~29~~ ~~28~~ 26 characters

### Task 1 (every third composite number)

```
6*:tZp~)G:3*q)%G"$]vwm^sl+

```

Try it online!

### Task 2 (multiplication table)

```
:l$*%6*tZp~)G:3q)G"]vwm^s+

```

Try it online!

### Task 3 (Fibonacci detector)

```
l6Zp~G:"3q$t+]vGwm%):*)^s*

```

This displays `1` / `0` for Fibonacci / non-Fibonacci respectively.

Try it online!

### Task 4 (sum of powers)

```
:t^s%6*Zp~)G:3*q)G"$]vwml+

```

Try it online!

### Check

This program inputs the four strings and displays them sorted, to visually check that they use the same characters.

## Explanations

`%` is the comment symbol. Everything to its right is ignored.

### Task 1 (every third composite number)

```
6*    % Input N. Multiply by 6
:     % Range [1 2 ... 6*N]. This is enough because every even number is composite,
      % so this contains at least 3*N composite numbers
t     % Duplicate
Zp    % Isprime
~     % Negate
)     % Use as index to select composite numbers, including 1, from [1 2 ... 6*N]
G:    % Push [1 2 ... N]
3*q   % Multiply by 3 and subtract 1: gives [2 5 ... 3*N-1]
)     % Pick those composite numbers. Implicitly display

```

### Task 2 (multiplication table)

```
:     % Input N. Range [1 2 ... N]
l     % Push 1
$     % Specify that next function will take 1 input
*     % Product of array. With 1 input it produces all pair-wise products
      % Implicitly display

```

### Task 3 (Fibonacci detector)

```
l     % Push 1
6     % Push 6
Zp    % Isprime. Gives false
~     % Negate. Gives true, or 1
G:    % Push [1 2 ... N], where N is the input
"     % For each
  3q  %   3, subtract 1
  $   %   Specify that next function will take 2 inputs
  t   %   Duplicate the top two elements of the stack
  +   %   Add
]     % End
v     % Vertically concatenate the entire stack. This produces a column vector
      % with a sufficient amount of Fibonacci numbers
G     % Push input N
w     % Swap
m     % Ismember. Gives true if input is in the vector of Fibonacci numbers
      % Implicitly display

```

### Task 4 (sum of powers)

```
:     % Implicitly input N. Push [1 2 ... N]
t     % Duplicate
^     % Power, element-wise
s     % Sum of array. Implicitly display

```
> 9 votes

# Answer
# Perl 6, 61 bytes

```
{(4..*).grep(!*.is-prime)[0,3...^*>=$_*3]}#$$&+1==>X[]__oot{}

```

```
{[X*](1..$_,!0..$_).rotor($_)}#&***+-..334===>>[]^eegiimpps{}

```

```
{(1,&[+]...*>=$_)[*-!0]==$_}#$()**....334>X^_eegiimoopprrst{}

```

```
{[+]((1..$_)>>.&{$_**$_})}#!**,-....0334===X[]^eegiimoopprrst

```

---

The second one returns `((1,2,3,4),(2,4,6,8),(3,6,9,12),(4,8,12,16))` when given `4`

Perl 6 doesn't really have a maximum integer, but the third one works instantly with an input of `15156039800290547036315704478931467953361427680642`. The only limiting factors would be memory and time.

Otherwise they will all run "instantly" for inputs well beyond what is necessary.

Try it online
> 7 votes

# Answer
## JavaScript (ES6), ~~101~~ ~~100~~ ~~95~~ ~~93~~ 91 bytes

```
(n,r=[],a=(y,m)=>n?y%m?a(y,++m):a(y+1,2,y==m||n--%3||r.push(y)):r)=>a(4,2,n*=3)//>....p*A&&
n=>[...Array(n)].map((r,y,m)=>m.map((s,n)=>y*++n,y+=1))//22334(,,,,===ayy)??%%::||||--uh*&&
r=(n,y=1,a=2)=>n==y||n>y&&r(n,a,y+a)//2334((((,,,,r=[]ayymmmm))))>??%%++::||--.....ppush**A
r=y=>y&&y**y+r(y-1)//22334(((((nnnn,,,,,,,,r=====[]aaaaymmmm)))))>>??%%++::||||-.....ppushA

```

Edit: Saved 1 byte by not supporting `0` as a Fibonacci number. Saved 5 bytes plus a further 2 bytes (1 thanks to @Arnauld) by renaming variables. Saved 2 bytes by switching between `+1`, `++` and `+=1`.
> 6 votes

# Answer
# MATL, 30 characters

The character set I went with is:

```
!%))*+001233::<=GGQZ\]^`pstvyy~

```

I couldn't outgolf the other MATL answer, but I had fun coming up with this solution.

**Task 1:**

Third composite numbers.

```
4t^:QtZp~)G3*:3\1=)%!`yy+<]vGs

```

Try it online!

**Task 2:**

Multiplication table. Definitely the easiest task, due to the way MATL works

```
:t!*%4QZp~)G3:3\1=)`yy+<]vGs^t

```

Try it online!

**Task 3:**

Fibonacci tester. Prints a positive integer (1 or 2) for truthy inputs, and 0 for falsy inputs.

```
1t`yy+tG<]vG=s%4:QZp~)3*:3\)!^

```

Try it online!

**Task 4:**

Sum of powers

```
:t^s%1`yy+tG<]vG=4QZp~)3*:3\)!

```

Try it online!

I'll post a more thorough explanation later, but for now, you should note that `%` is the comment character, so the programs are really:

```
4t^:QtZp~)G3*:3\1=)
:t!*
1t`yy+tG<]vG=s
:t^s

```
> 4 votes

# Answer
# PowerShell, ~~95~~ 94 bytes

(TimmyD savin' my bacon yet again)

### Task 1:

```
(""..999|?{'1'*$_-match'^(?=(..+)\1+$)..'})[(0..("$args"-1)|%{$_*3})]#|$$$$===ss%``iiex!!nnnq;

```

Try it online!

---

### Task 2:

```
($s=1.."$args")|%{"`$s|%{$_*`$_}"|iex}#0113999((((......??''''*$$$--match^===++))))\[]i!!nnnq;

```

Try it online!

---

### Task 3:

```
!!(($i="$args")..($s=1)|?{($n=($s+=$n)-$n)-eq$i})#0113999......||?{''''**__match^+\}[""%%]``x;

```

Try it online!

---

### Task 4:

```
"$args"..1|%{$s+="$_*"*$_+1|iex};$s#013999(((((......|??{''''$$$--match^===)))))\}[%]``i!!nnnq

```

Try it online!
> 4 votes

# Answer
# 05AB1E, 21 bytes

**Task 1**

```
3ÅFOL¦DâPÙï{3ôø¬¹£qåm

```

Try it online!

**Task 2**

```
LDâP¹ôq3m¦Ùï{3ø¬£ÅFåO

```

Try it online!

**Task 3**

```
3mÅF¹åqL¦DâPÙï{3ôø¬£O

```

Try it online!

**Task 4**

```
LDmOq3¦âPÙï{3ôø¬¹£ÅFå

```

Try it online!

**Explanations**

For all tasks, the `q` ends the program so the code that follows never gets executed.

**Task 1**

This is the biggest byte-hog. An small improvement here could go a long way.

```
3ÅFO                 # sum the first 4 fibonacci numbers
    L¦               # range [2 ... above]
      Dâ             # cartesian product with itself
        P            # product
         Ù           # remove duplicates
          ï{         # sort
            3ô       # split in pieces of size 3
              ø      # transpose
               ¬     # get the first lits
                ¹£   # get the first input-nr elements of the list

```

**Task 2**

```
L       # range [1 ... input]
 D      # duplicate
  â     # cartesian product
   P    # product
    ¹ô  # split in pieces of input size

```

**Task 3**

```
3m      # input**3
  ÅF    # get a list of that many (+1) fibonacci numbers
    ¹å  # check if input is in that list

```

**Task 4**

```
L     # range [1 ... input]
 D    # duplicate
  m   # elementwise power of ranges
   O  # sum

```
> 4 votes

# Answer
# Haskell, ~~77~~ 76 characters

```
m n=[[x|x<-[1..],2/=sum[1|0<-mod x<$>[1..x]]]!!y|y<-[1,4..3*n]]--2 n===y();^
s n=[(*y)<$>[1..n]|y<-[1..n]]--0112234mmm  ====[[[xxxx||<<--..]]],,/uod!!y;^
n x|x<2=1|1<3=sum(n<$>[x-1,x-2]);d y=[0|m<-[1..y],y==n m]--4[[[....]]]/o!!*^
o n=sum[x^x|x<-[1..n]]--01112234mm  n====[[[[x||<<<--....]]]],,/d$>!!yyy*();

```

Try it online!

`--` starts a line comment, so all four programs are of the form `<program>--<unused chars>`.

**Task 1:**

```
m n=[[x|x<-[1..],2/=sum[1|0<-mod x<$>[1..x]]]!!y|y<-[1,4..3*n]]

```

The longest program. `[x|x<-[1..],2/=sum[1|0<-mod x<$>[1..x]]]` yields a infinite list of composite numbers plus a starting `1` which corrects the 0-indexing. Usage:

```
Prelude> m 5
[4,9,14,18,22]

```

**Task 2:**

```
s n=[(*y)<$>[1..n]|y<-[1..n]]

```

Usage:

```
Prelude> s 5
[[1,2,3,4,5],[2,4,6,8,10],[3,6,9,12,15],[4,8,12,16,20],[5,10,15,20,25]]

```

**Task 3:**

```
n x|x<2=1|1<3=sum(n<$>[x-1,x-2]);d y=[0|m<-[1..y],y==n m]

```

Returns `[0]` for truthy and `[]` for falsy. Usage:

```
Prelude> d 5
[0]
Prelude> d 6
[]

```

**Task 4:**

```
o n=sum[x^x|x<-[1..n]]

```

Usage:

```
Prelude> o 5
3413

```
> 3 votes

# Answer
## Ruby, ~~83 82 80~~ 78 characters

```
->m{'*+-=';[*0..m-1].map{|b|(4..516).select{|p|(2...p).any?{|n|p%n==0}}[3*b]}}
->n{'()%**+--......00123456==?[[]]clmnsty{||}';(b=1..n).map{|e|b.map{|p|e*p}}}
->m{'%+-......001236bclnnpt[[]]{{||||}}';(1..e=m*m).any?{|p|(p*p-5*e).abs==4}}
->n{'%*.......023456=?[]abbceelnsty{{||||}}';((m=0)..n).map{|p|m+=p**p}[-1]-1}

```

Note: Fibonacci numbers detector using the perfect square method described on Wikipedia: https://en.wikipedia.org/wiki/Fibonacci\_number#Recognizing\_Fibonacci\_numbers
> 2 votes

# Answer
# 05AB1E, 17 bytes

**Bytes used:**

```
δн3FILOPQm£¦ÅÐãêô

```

**Task 1 - every 3rd composite number:**

```
QÅmFÐOL¦ãPê3ôI£δн

```

Try it online or verify all \\$\[1,50\]\\$ inputs.

**Task 2 - multiplication table:**

```
ÅFOQmê3ôãн¦£ILÐδP

```

Try it online or verify all \\$\[1,20\]\\$ inputs.

**Task 3 - Fibonacci check:**

```
£3ôδнã¦LPmIÐÅFQêO

```

Try it online or verify the first \\$\[0,1000\]\\$ inputs.

**Task 4 - exponentiation sum:**

```
ÅFPQê3ôãδн¦£ILÐmO

```

Try it online or verify all \\$\[1,10\]\\$ inputs.

Try all four at once.

### Explanation:

**Task 1 - every 3rd composite number:**

This one takes up most bytes. Not only in general, but also to get a list large enough for input \\$n=1\\$.

```
              # No-ops:
Q             #  Check if the (implicit) input is equal to the (implicit) input: 1
 Åm           #  Get the mean of that (remains 1)
   F          #  Loop that many times:

              # Main part of the program:
Ð             #   Triplicate the (implicit) input
 O            #   Sum all values on the stack
  L           #   Take a list in the range [1,3*input]
   ¦          #   Remove the first to make the range [2,3*input]
    ã         #   Cartesian product with itself, to create all possible pairs
     P        #   Take the product of each pair
      ê       #   Sort & uniquify all values
       3ô     #   Split it into parts of size 3
         I£   #   Leave the first input amount of parts
           δн #   And then leave the first item of each part
              #  (after the no-op loop, the result is output implicitly)

```

**Task 2 - multiplication table:**

```
              # No-ops:
ÅF            #  Get all Fibonacci numbers below or equal to the (implicit) input
  O           #  Take the sum of those
   Q          #  Check if it's equal to the (implicit) input (which will always be 0)
    m         #  Push the input to the power that 0 (which will always be 1)
     ê        #  Sort and uniquify those digits (remains 1)
      3ô      #  Split it into parts of size 3 (which wraps the 1 into a list: [1])
        ã     #  Take the cartesian product of that list with itself (which becomes [[1,1]])
         н    #  Leave the first item of that (which becomes [1,1])
          ¦   #  Remove the first value (which becomes [1])
           £  #  Keep that many digits of the input
              #  (which becomes the first digit of the input, wrapped in a list)

              # Main part of the program:
IL            #  Push a list in the range [1,input]
  Ð           #  Triplicate this list
   δ          #  Using the top two lists, apply double vectorized:
    P         #   Take the product of the two values
              #  (after which the resulting multiplication table is output implicitly)

```

**Task 3 - Fibonacci check:**

```
              # No-ops:
£             #  Keep the first (implicit) input amount of digits of the (implicit) input
 3ô           #  Split this input into parts of size 3
   δн         #  Take the first digit of each part (let's call this digit d)
     ã        #  Take the cartesian product with itself (which becomes [[d,d]])
      ¦       #  Remove the first item (which becomes [])
       L      #  Push a list in the range [1,[]] (which remains [])
        P     #  Take the product of that list (which becomes 1)
         m    #  Push the (implicit) input to the power this 1 (which becomes the input)

              # Main part of the program:
I             #  Push the input
 Ð            #  Triplicate it
  ÅF          #  Get a list of Fibonacci numbers equal to or below this input
    Q         #  Check for each whether it's equal to the input
     ê        #  Sort and uniquify these checks
      O       #  Sum the remaining checks (which will either be [0] or [0,1])
              #  (after which this 0/1 is output implicitly as result)

```

**Task 4 - exponentiation sum:**

```
              # No-ops:
ÅF            #  Get all Fibonacci numbers below or equal to the (implicit) input
  P           #  Take the product of those (which will always be 0)
   Q          #  Check if it's equal to the (implicit) input (remains 0)
    ê         #  Sort and uniquify those digits (remains 0)
     3ô       #  Split it into parts of size 3 (which wraps the 0 into a list: [0])
       ã      #  Take the cartesian product of that list with itself (which becomes [[0,0]])
        δн    #  Leave the first item for each of those (which becomes [0])
          ¦   #  Remove the first value (which becomes [])
           £  #  Keep that many digits of the input (remains [])

              # Main part of the program:
IL            #  Push a list in the range [1,input]
  Ð           #  Triplicate this list
   m          #  Take the power of the values at the same indices of the top two lists
    O         #  And sum those
              #  (after which this sum of exponents is output implicitly as result)

```
> 1 votes

---
Tags: code-golf, math, sequence, restricted-source, multiple-holes
---