# Question
Title: Chase the Easter Bunny™, be the Easter Bunny™
---

The garden is a 2-dimensional grid with 49 rows and 49 columns.

The Easter Bunny™ is in the center of the garden, minding his own business, holding on to 100 Easter eggs.

Unfortunately, there's a team of 4 children who aren't content to collect chocolate eggs, they want to capture the Easter Bunny™.

The game starts with 4 kids, one in each corner of the garden.

The kids can take 1 step each turn, in one of the 4 cardinal directions (North, South, East or West). When they've each taken a step (or decided not to), the bunny will take a move.

The kids can only see the Easter Bunny or its eggs when they are 5 steps away or nearer.

Kids visibility (yellow) and movement options (green):

The bunny can hop up to 2 spaces away on both axes (describing a 5 x 5 square he can hop to).

The Easter Bunny™ can only see the kids when they are 5 steps away or nearer.

Bunny's visibility (yellow) and movement options (green)

Neither kids nor the Easter Bunny™ can leave the garden.

The game ends when:

* The Easter Bunny™ drops his last egg, or
* The kids catch the bunny, or
* The game reaches turn 1000.

The Goals:

* The Easter Bunny™ wants to give the children as many Easter Eggs as possible while evading capture.
* The kids want to collect as many eggs as possible, AND catch the Easter Bunny™.

This means that:

* The Easter Bunny™ will ONLY score points if it evades capture by dropping it's last egg, or by finishing the time limit.
* The team of kids will ONLY score points if they capture the Easter Bunny™.
* In either case the points scored is the number of eggs the kids have picked up.

The challenge is to write behaviour for the Easter Bunny™ or for the team of kids. Your code will be run against all of the other kind of entry.

## Config

You can edit `conig.js` to change two things about the run:

* `match_limit` will allow you to end the game when you decide (competition will use 1,000 turns)
* `turn_time` (ms) will set the interval when the game is rendering.

# As the kids:

(See instructions for the bunny below)

Your goal is to collect as many eggs as you can, and then catch the Easter Bunny™.

Your code will take the form of an array of 4 JS functions, which will each control a kid starting in these positions (in this order):

* North West (0, 0)
* North East (0, 48)
* South East (48, 48)
* South West (48, 0)

If you're watching a match, these are represented by the numbers 1 to 4.

The functions should each have this fingerprint:

```
function(api) {
}

```

`api` is your function's interface to the game (see below).

## The Kid API

The `api` object presents these four movement functions:

* `api.north()`
* `api.east()`
* `api.south()`
* `api.west()`

If any of these are called during your function, the kid will take one step in that direction (or the last called of these four directions). If none of these are called during your function, the kid will stand still.

It also provides information about the state of the game with these methods:

* `api.my_storage()` \- an object you can use to store data and functions for just this kid.
* `api.shared_storage()` \- an object you can use to store data and functions for the whole team.
* `api.turn()` \- Returns a number of turns taken in this game so far.
* `api.bunny()` \- Returns an object of bunny-related info if the bunny can be seen

{ x: 24, y: 24, eggs\_left: 100 }
* `api.kids()` tells you where all the kids are

\[ {x: 0, y: 0, me: true}. ... \]
* `api.eggs()` tells you where the eggs are that your child can currently see:

{ x: 25, y: 25, age: 10 }

Age is the number of turns since the bunny dropped the egg.

## Kid Template

```
Teams.push(
  {
    name: 'template',
    shared_storage: {},
    functions: [
      function(api) {
        // NW kid
      },
      function(api) {
        // NE kid
      },
      function(api) {
        // SE kid
      },
      function(api) {
        // SW kid
      }
    ]
  }
);

```
* `name` must be a single-word identifier, if you want to run just a single entry.
* `shared_storage` sets the initial state of `api.shared_storage`, it can be used to set data and functions for your team.
* The array `functions` is the behaviour of the 4 kids chasing the bunny.

## How to participate

You will need nodejs installed.

Change `my_entry` to your own team name.

* `git clone https://github.com/AJFaraday/easter_bunny_hunt.git`
* `npm install terser -g`
* `cd easter_bunny_hunt`
* `cp team_template.js teams/my_entry.js`
* (Write your team code)
* `script/run.sh my_entry basic` to watch a game. The first entry is the name of your team, the second is the name of an entry in bunnies/.
* `script/run.sh` to run all matches and see all results (if you import more entries)

When you're happy with the result, copy it in to an answer like so:

```

    # Team: my_entry - 10 points

    Any description you want to add goes here

        Teams.push(
          {
            name: 'template',
            shared_storage: {},
            functions: [
              function(api) {
                // NW kid
              },
              function(api) {
                // NE kid
              },
              function(api) {
                // SE kid
              },
              function(api) {
                // SW kid
              }
            ]
          }
        );

```

Then have a try at writing an entry for the Easter Bunny™.

# As the Bunny

Your goal is to give away as many Easter eggs as you can and, crucially, to evade capture.

The bunny starts at the centre of the garden, at coordinates 24, 24.

Your code takes the form of a function with this finger print which runs once a turn, after the children have moved.

```
function(api) {
}

```

## The Bunny API

The api object provides this method to tell the bunny how to move:

* `api.hop(x, y)`

The two arguments tell the bunny where to hop to relative to it's current position:

* They can have values from -2 through to 2.
* If `x` is positive, it will hop east, negative, it'll hop west.
* If `y` is positive, it will hop south, negative, it'll hop north.
* If the values provided are out of range, it will force it to 2 or -2.
* Each time the bunny hops, it leaves behind an Easter egg.

It also provides this functions to give you storage between turns:

* `api.storage()` \- Returns an object you can use to store variables.

And these functions to give you information about the game:

* `api.turn()` \- Returns the turn number the game is currently at.
* `api.eggs()` \- Returns the positions of all Easter eggs in the garden.

{ x: 25, y: 25, age: 10 }
* `api.bunny()` \- Provides information on the current state of the bunny

{ x: 24, y: 24, eggs\_left: 100 }
* `api.kids()` \- Provides information on all the kids the bunny can currently see.

{ x: 0, y: 0 }

## Bunny Template

```
Bunnies.push(
  {
    name: 'template',
    storage: {},
    function: function(api) {

    }
  }
);

```
* `name` is the name of your bunny behaviour. Keep it to 1 word (underscores allowed).
* `storage` is the current state of your storage object, available via the api.
* `function` is the function which will be run every turn to control the bunny.

## How to participate

You will need nodejs installed.

Change `my_entry` to your own bunny name.

* `git clone https://github.com/AJFaraday/easter_bunny_hunt.git`
* `npm install terser -g`
* `cd easter_bunny_hunt`
* `cp bunny_template.js bunnies/my_entry.js`
* (Write your team code)
* `script/run.sh get_egg my_entry` to watch a game. The first argument is the name of a team in teams/, the second is the name your bunny.
* `script/run.sh` to run all matches and see all results (if you import more entries)

When you're happy with the result, copy it in to an answer like so:

```
    # Bunny: my_entry - 10 points

    Any description you want to add goes here

    Bunnies.push(
      {
        name: 'template',
        storage: {},
        function: function(api) {

        }
      }
    );

```

Then have a try at writing an entry for a team of kids.

# Answer
# Bunny: smartish (2 points, but, of course, as of posting)

Hops to the middle when it doesn't see anybody, and tries to escape the kids (using an algorithm I probably implemented incorrectly).

```
Bunnies.push(
{
    name: 'smartish',
    storage: {},
    function: function(api)
    {
        let x = api.bunny().x;
        let y = api.bunny().y;
        if(api.kids().length == 0)
        {
            //hop towards middle
            let dx = 24 - x;
            let dy = 24 - y;
            api.hop(dx, dy);
            return;
        }
        //else build an array of safe cells
        safe = [[1,1,1,1,1],[1,1,1,1,1],[1,1,1,1,1],[1,1,1,1,1],[1,1,1,1,1]];
        for(let i in api.kids())
        {
            let kid = api.kids()[i];
            let dx = x - kid.x;
            let dy = y - kid.y;
            if(dx >= -2 && dx <= 2 && dy >= -2 && dy <= 2)
                safe[dx+2][dy+2] = false;
            dx++;
            if(dx >= -2 && dx <= 2 && dy >= -2 && dy <= 2)
                safe[dx+2][dy+2] = false;
            dx -= 2;
            if(dx >= -2 && dx <= 2 && dy >= -2 && dy <= 2)
                safe[dx+2][dy+2] = false;
            dx++; dy++;
            if(dx >= -2 && dx <= 2 && dy >= -2 && dy <= 2)
                safe[dx+2][dy+2] = false;
            dy -= 2;
            if(dx >= -2 && dx <= 2 && dy >= -2 && dy <= 2)
                safe[dx+2][dy+2] = false;
            dy++;
        }
        //find the farthest safe cell and hop there
        let bestx = 0, besty = 0, bestd = 0;
        for(let dx = -2; dx <= 2; dx++)
        for(let dy = -2; dy <= 2; dy++)
        {
            if(!safe[dx+2][dy+2]) continue;
            let d = 9999;
            for(let kid of api.kids())
                d = Math.min(d, (kid.x-x)*(kid.x-x) + (kid.y-y)*(kid.y-y));
            if(d > bestd)
                bestd = d, bestx = dx, besty = dy;
        }
        api.hop(bestx, besty);
    }
}
);

```
> 4 votes

---
Tags: grid, king-of-the-hill, javascript, asymmetric
---


title: Build a minimum-clue Sudoku unsolver

text:
# Question
Title: Build a minimum-clue Sudoku unsolver
My attempt at stating this question, but with a more objective solving criterion.

Your task is to build a program or function that takes a solved Sudoku grid `S` in the format of your choice and attempts to generate a problem grid with as few clues as possible that has `S` as its unique solution. (It doesn't matter what method `S` is the unique solution by, including brute force, as long as the solution is provably unique.)

---

Your program will be scored by running it through a set of 100,000 solution grids found in this file (7.82 MB download), and adding up the number of clues in all 100,000 problem grids that your solution produces.

The Sudoku solutions in the above test file are expressed as an 81-character string, from left-to-right, then top-to-bottom. The code required to turn the input in the test file into a usable solution will not count towards your solution's byte count.

As in my Flood Paint challenge, your program must actually produce a valid output for all 100,000 puzzles to be considered a valid solution. The program that outputs the fewest total clues for all 100,000 test cases is the winner, with shorter code breaking a tie.

---

Current scoreboard:

1. 2,361,024 \- nutki, C
2. 2,580,210 \- es1024, PHP
3. 6,000,000 \- CarpetPython, Python 2
4. 7,200,000 \- Joe Z., Python

# Answer
> 2 votes
# C++ / Tdoku - 2,081,604 clues

Below are results from running random minimization using tdoku on each puzzle N times and taking the result with the least clues. Results are shown for various N as powers of 2. No heuristics are involved at all. Each minimization just takes a random permutation of range(81) and then tries to remove clues in that order, putting a clue back whenever its removal results in multiple solutions.

Of note is the fact that the curve isn't flattening quickly and lower numbers can clearly be achieved without being any smarter just by running for larger N.

```
# (1) fetch tdoku
git clone https://github.com/t-dillon/tdoku.git
cd tdoku

# (2) pick your compiler (recent clang is best for tdoku):
export CC=clang-8
export CXX=clang++-8

# (3) place ppcg_sudoku_testing.txt, minimize.cc (below),
#     and run.sh (below) in the current directory

# (4) build the tdoku solver library
./BUILD.sh

# (5) build minimize.cc
$CXX -std=c++11 -O3 -march=native -o minimize minimize.cc build/libtdoku.a

# (6) run with concurrency appropriate for your system.
#     results below were run on a 32core/64thread TR-2990WX
chmod a+x run.sh
./run.sh 64
    1:    2438970  0 sec
    2:    2377595  1 sec
    4:    2329366  2 sec
    8:    2288410  3 sec
   16:    2254275  7 sec
   32:    2223342  14 sec
   64:    2195642  27 sec
  128:    2174050  55 sec
  256:    2153351  109 sec
  512:    2127972  218 sec
 1024:    2105589  436 sec
 2048:    2091738  871 sec
 4096:    2081604  1740 sec

```

**minimize.cc:**

```
#include "include/tdoku.h"
#include <cstdio>
#include <cstring>
#include <fstream>

int NumClues(const char *puzzle) {
    int num_clues = 0;
    for (int i = 0; i < 81; i++) {
        if (puzzle[i] != '.') num_clues++;
    }
    return num_clues;
}

int main(int argc, char **argv) {
    int limit = std::stoi(argv[1]);

    std::ifstream file;
    file.open(argv[2]);

    std::string line;
    while (getline(file, line)) {
        char puzzle[81], min_puzzle[81];
        int min_clues = 81;
        for (int j = 0; j < limit; j++) {
            memcpy(puzzle, line.c_str(), 81);
            TdokuMinimize(false, puzzle);
            int clues = NumClues(puzzle);
            if (clues <= min_clues) {
                min_clues = clues;
                memcpy(min_puzzle, puzzle, 81);
            }
        }
        printf("%.81s %d\n", min_puzzle, min_clues);
    }
}

```

**run.sh**

```
#!/bin/bash

concurrency=$1

killall minimize 2>/dev/null
rm -f ppcg_?? ppcg_??.done
split -n l/$concurrency ppcg_sudoku_testing.txt ppcg_

for p in {0..20}; do
    t1=$(date +%s)
    lim=$((2**p))
    for f in ppcg_??; do
    ./minimize $lim $f > $f.done &
    done
    wait
    t2=$(date +%s)
    cat *.done | awk -F' ' -v t=$((t2 - t1)) -v n=$lim '{ x += $2 } END { printf("%5d: %10d  %d sec\n",n,x,t); }'
done

```

# Answer
> 8 votes
# C - 2,361,024 ~~2,509,949~~ clues

Remove clues starting from the last cell if a brute force solver finds only one unique solution.

Second try: use heuristic to decide in which order to remove clues instead of starting from the last. This makes the code run much slower (20 minutes instead of 2 to calculate the result). I could make the solver faster, to experiment with different heuristics, but for now it will do.

```
#include <stdio.h>
#include <string.h>
char ll[100];
short b[81];
char m[81];
char idx[81][24];
int s;
char lg[513];
void pri2() {
    int i;
    for(i=0;i<81;i++) putchar(lg[b[i]]);
    putchar('\n');
}
void solve(pos){
int i,p;
if (s > 1) return;
if (pos == 81) { s++; return; }
if (b[pos]) return solve(pos+1);
for (p=i=0;i<24;i++) p |= b[idx[pos][i]];
for (i = 0; i < 9; i++) if (!(p&(1<<i))) {
    b[pos] = 1 << i;
    solve(pos + 1);
}
b[pos] = 0;
}
int main() {
    int i,j,t;
    for(i=0;i<9;i++) lg[1<<i]='1'+i;
    lg[0] = '.';
    for(i=0;i<81;i++) {
    t = 0;
    for(j=0;j<9;j++) if(i/9*9 + j != i) idx[i][t++] = i/9*9 + j;
    for(j=0;j<9;j++) if(i%9 + j*9 != i) idx[i][t++] = i%9 + j*9;
    for(j=0;j<81;j++) if(j/27 == i/27 && i%9/3 == j%9/3 && i!=j) idx[i][t++] = j;
    }
    while(scanf("%s ",ll)>0) {
    memset(m, 0, sizeof(m));
    for(i=0;i<81;i++) b[i] = 1 << (ll[i]-'1');
    for(i=0;i<81;i++) {
    int j,k,l = 99;
    for(k=0;k<81;k++) if (m[k] <= l) l = m[k], j = k;
    m[j] = 24;
    t = b[j]; b[j] = 0;
    s = 0; solve(0);
    if (s > 1) b[j] = t;
    else for(k=0;k<24;k++) m[idx[j][k]]++;
    }
    pri2();
    }
    return 0;
}

```

# Answer
> 2 votes
# Python — 7,200,000 clues

As usual, here is a last-place reference solution:

```
def f(x): return x[:72] + "." * 9

```

Removing the bottom row of numbers provably leaves the puzzle solvable in all cases, as each column still has 8 of 9 numbers filled, and each number in the bottom row is simply the ninth number left over in the column.

If any serious contender manages to legally score worse than this one, I will be astonished.

# Answer
> 1 votes
# Python 2 - 6,000,000 clues

A simple solution that uses the 3 common methods of solving these puzzles:

```
def f(x):
    return ''.join('.' if i<9 or i%9==0 or (i+23)%27 in (0,3) else c
        for i,c in enumerate(x))

```

This function produces clue formats like this:

```
.........
.dddddddd
.dddddddd
.ddd.dd.d
.dddddddd
.dddddddd
.ddd.dd.d
.dddddddd
.dddddddd

```

This can always be solved. The 4 3x3 parts are solved first, then the 8 columns, then the 9 rows.

# Answer
> 1 votes
# PHP — 2,580,210 clues

This first removes the last row and column, and bottom right corner of every box. It then tries to clear out each cell, running the board through a simple solver after each change to ensure the board is still unambiguously solvable.

Much of the code below was modified from one of my old answers. `printBoard` uses 0s for empty cells.

```
<?php
// checks each row/col/block and removes impossible candidates
function reduce($cand){
    do{
        $old = $cand;
        for($r = 0; $r < 9; ++$r){
        for($c = 0; $c < 9; ++$c){
            if(count($cand[$r][$c]) == 1){ // if filled in
                // remove values from row and col and block
                $remove = $cand[$r][$c];
                for($i = 0; $i < 9; ++$i){
                    $cand[$r][$i] = array_diff($cand[$r][$i],$remove);
                    $cand[$i][$c] = array_diff($cand[$i][$c],$remove);
                    $br = floor($r/3)*3+$i/3;
                    $bc = floor($c/3)*3+$i%3;
                    $cand[$br][$bc] = array_diff($cand[$br][$bc],$remove);
                }
                $cand[$r][$c] = $remove;
            }
        }}
    }while($old != $cand);
    return $cand;
}

// checks candidate list for completion
function done($cand){
    for($r = 0; $r < 9; ++$r){
    for($c = 0; $c < 9; ++$c){
        if(count($cand[$r][$c]) != 1)
            return false;
    }}
    return true;
}

// board format: [[1,2,0,3,..],[..],..], $b[$row][$col]
function solve($board){
    $cand = [[],[],[],[],[],[],[],[],[]];
    for($r = 0; $r < 9; ++$r){
    for($c = 0; $c < 9; ++$c){
        if($board[$r][$c]){ // if filled in
            $cand[$r][$c] = [$board[$r][$c]];
        }else{
            $cand[$r][$c] = range(1, 9);
        }
    }}
    $cand = reduce($cand);

    if(done($cand))  // goto not really necessary
        goto end;    // but it feels good to use it
    else return false;

    end:
    // back to board format
    $b = [];
    for($r = 0; $r < 9; ++$r){
        $b[$r] = [];
        for($c = 0; $c < 9; ++$c){
            if(count($cand[$r][$c]) == 1)
                $b[$r][$c] = array_pop($cand[$r][$c]);
            else
                $b[$r][$c] = 0;
        }
    }
    return $b;
}

function add_zeros($board, $ind){
    for($r = 0; $r < 9; ++$r){
    for($c = 0; $c < 9; ++$c){
        $R = ($r + (int)($ind/9)) % 9;
        $C = ($c + (int)($ind%9)) % 9;
        if($board[$R][$C]){
            $tmp = $board[$R][$C];
            $board[$R][$C] = 0;
            if(!solve($board))
                $board[$R][$C] = $tmp;
        }
    }}
    return $board;
}

function generate($board, $ind){
    // remove last row+col
    $board[8] = [0,0,0,0,0,0,0,0,0];
    foreach($board as &$j) $j[8] = 0;

    // remove bottom corner of each box
    $board[2][2] = $board[2][5] = $board[5][2] = $board[5][5] = 0;

    $board = add_zeros($board, $ind);

    return $board;
}
function countClues($board){
    $str = implode(array_map('implode', $board));
    return 81 - substr_count($str, '0');
}

function generateBoard($board){
    return generate($board, 0);
}

function printBoard($board){
    for($i = 0; $i < 9; ++$i){
        echo implode(' ', $board[$i]) . PHP_EOL;
    }
    flush();
}
function readBoard($str){
    $tmp = str_split($str, 9);
    $board = [];
    for($i = 0; $i < 9; ++$i)
        $board[] = str_split($tmp[$i], 1);
    return $board;
}
// testing
$n = 0;
$f = fopen('ppcg_sudoku_testing.txt', 'r');
while(($l = fgets($f)) !== false){
    $board = readBoard(trim($l));
    $n += countClues(generateBoard($board));
}
echo $n;

```

---
Tags: code-challenge, optimization, sudoku, test-battery
---


# Question
Title: Check if hand from card game "Rooster" is valid for the second stage
Here in Russia, we have a little-known card game with the name, when translated directly, means Rooster.

The cards used are two full 54-card decks of playing cards from 2 through aces, with jokers. The game for each player divides into two stages. In the first stage, each player has 14 cards dealt, and with those cards has to get 51 or more points with card combinations.

## Rules:

1.Each combination has to be at least three cards long, with no cards repeating, and can be either:

* A combination of cards of the same value (not points), for example:

```
        Ace of spades, ace of hearts, ace of clubs
        Six of hearts, six of clubs, six of diamonds, six of spades

```
* A combination of cards that are in a row, like a straight in poker, examples:

```
        Jack of clubs, queen of clubs, king of spades, ace of hearts
        Seven of spades, eight of diamonds, nine of clubs
        Ace of diamonds, two of clubs, three of hearts, four of diamonds, five of spades

```
2. Your hand score is calculated by the sum of points in every card combination according to the chart below:

```
2-10: according to the cards face value for each card (For example, Three of spades is 3 points)
Jack,Queen,King: 10 points for each card
Ace: 1 point if used before a Two, otherwise 11 points for each card
Joker: 0 points

```
4. Jokers can substitute any card in a combination, but **cannot** be used more than once in each combination. The cards they substitute cannot be used again in the same combination.
5. Cards cannot be used twice. If you used a card, you can't then use it in a different combination
6. But remember, since the deck is two 54-card decks, duplicates of one card are possible, and, if duplicates are in a hand, using one card will not forbid you from using the other duplicate.

## The task:

Taking a hand of 14 cards, output one of the possible things:

1. A truthy value if the cards given can form combinations in such a way that your hand score is more or equal than 51
2. A falsy value if your hand does not reach the score of 51

## Input:

Each card is given in a format VS, where:

1. V is the face value. Possible values: \[2,3,4,5,6,7,8,9,T,J,Q,K,A\]
2. S is the suit of a card. Possible values: \[S,H,D,C,J\] A joker will be represented as JJ

Your input may be in any form you wish, as long as each card values are not separated. For example:

1. A list of cards. (\['TS','3H','JJ','9C',etc...\])
2. Cards separated from each other with a whitespace. (TS 3H JJ 9C etc...)

## Output:

Either:

1. A Truthy/Falsy
2. A 1/0

This is codegolf, so lowest bytecount for each language wins! I hope the rules are clear, and good luck!

edit 1: got mixed up in terminology

# Answer
> 2 votes
# Ruby, ~~415~~ 376 bytes

```
->a{s=[*2..9]+[10]*4+[11,1]
g=->d,j{x=0
65.times{|r|v=r/5;r%=5
p=w=0
c=d*1
y=[r,c[v]/5,c[v]%5].min
z=v+1+r
r<3?z<13?(v-1).upto(z){|n|p+=s[n];c[n]>4?c[n]-=5:w+=1}:w=2:r>y+1?w=2:(p+=s[v]*r;c[v]-=y*5;w=r-y)
w>1||w>j||(x=[p+g[c,j-w],x].max)}
x}
b=(0..12).map{[]}
a.map{|i|b["23456789TJQKA".index i[0]]<<i[1]}
h=b[9].size-(b[9]-=[?J]).size
b.map!{|i|i.size*5+(i&i).size}
g[b,h]>50}

```

Try it online!

Revised version, using recursive search tree instead of brute force search. This version runs to completion on TIO.

The TIO generates random test cases. It is interesting to modify the `x>50` to simply `x` to see the raw scores achieved. Sometimes the way to achieve the best score is not obvious and it can take a moment's scribbling to work out manually how the computer got as high a score as it did.

**Explanation**

Cards are taken as an unsorted array `a` and the suit letters are parsed into 13-element array `b`, one element for each card value. After jokers have been removed and counted separately, the total number of cards and number of distinct suits are stored as a single number `5*total + distinct suits.` Distinct suits are only important when dealing with `n of a kind` type groups: the number of available cards is `max(total cards, distinct suits)` plus jokers.

Searching is done recursively by "nested" function `g`. There are 5 different types of groups of cards to search for, as below. Note that the best use of `34567` would be a 5 straight but if a second `5` is available the best use would be two separate 3 straights `345` and `567`, so greedily assigning to the largest possible group is not always the best strategy. Instead we look for groups separately. Straights of 6 and over will be found as a combination of shorter straights.

```
Type          corresponding value of r%5
3 straight    0
4 straight    1
5 straight    2
3 of a kind   3
4 of a kind   4

```

There are 13 possible starting values for each type, so **the total number of distinct possible groups to search for is 13\*5=65** (some straights are not possible with the highest starting values.)

When function `g` finds a group, it passes the remaining cards on recursively to a new instance of itself, then compares the score of the group it found (plus any additional groups found by recursion) with the highest score found so far in variable `x`, and updates `x` if necessary.

Return value of recursive function `g` is the highest score found. Return value of outer function `f` is `true` or `false` from `g>50`.

**Commented code**

```
->a{s=[*2..9]+[10]*4+[11,1]             #14-element array of card scores. Final element is ace low, accessed as s[-1]
g=->d,j{                                #function g takes an array of card data, and a joker count as input
  x=0                                     #largest score found so far is 0
  65.times{|r|v=r/5;r%=5                  #iterate through 13 possible card values and 5 possible group types
  p=w=0                                   #p=points for this iteration;w=wildcards required
  c=d*1                                   #make a copy of d for this iteration
  y=[r,c[v]/5,c[v]%5].min                 #y=number of cards removed by successful n of a kind. [cards required,cards available,distinct suits].min
  z=v+1+r                                 #z=top value of straight
  r<3?                                    #if r<3 consider a straight
     z<13?(v-1).upto(z){|n|               #if z is in range (no more than ace high) iterate through cards
       p+=s[n];c[n]>4?c[n]-=5:w+=1}:      #add score to p. If card available, remove from c, else increment wildcards required
     w=2:                                 #if z out of range set wildcards to 2 to indicate failure
     r>y+1?w=2:                           #if r>2 consider a straight. If insufficient cards for r with 1 joker, set w to 2 to indicate failure.
     (p+=s[v]*r;c[v]-=y*5;w=r-y)          #add score to p, remove cards from c, set wildcards required
  w>1||w>j||(x=[p+g[c,j-w],x].max)}       #if wildcards required no more than 1 or jokers available, take the score, sum with results of further recursion and compare with x
  x}                                      #return x, the highest score of all 65 iterations
b=(0..12).map{[]}                       #make a 13 element array to store totals of cards
a.map{|i|b["23456789TJQKA".index i[0]]<<i[1]}   #add the suit letter for each card to b
h=b[9].size-(b[9]-=[?J]).size           #any "jacks" of suit J are actually jokers. count jokers into h and remove from b.
b.map!{|i|i.size*5+(i&i).size}          #collate the suit letters into a single number: total cards*5 + number of distinct suits
g[b,h]>50}                              #call g to find highest score. return truthy if over 50, else falsy.

```

---
Tags: code-golf, card-games
---


title: Program that compiles into itself

text:
# Question
Title: Program that compiles into itself
We've had lots of questions about s, programs where the source code and output are identical. For compiled languages, there are other combinations: we've already had a question about writing a program where the executable and output are identical. But there's one combination left.

## The task

Using a compiled language (i.e. a language which has a compiler that converts source code to executables, which are then executed), write a program which, when compiled, will produce an executable which is bit-for-bit identical to the source code.

## Clarifications

* As with all challenges that do not state otherwise, you must obey the site's proper quine rules. In particular, this excludes zero-byte programs, and programs where all the commands compile into themselves.
* At least for this challenge, it doesn't matter what the resulting executable does when run; this is purely a challenge. (If it turns out to be easy, I'm sure that someone will end up posting a "write a program where the source code, executable and output when executed are all the same" challenge, but you don't need to go to that level of complexity for *this* challenge.)
* Your program will, in effect, be a between the source language, and the language it compiles into. This means that you will need to pick a source language, and executable format, for which such a combination is possible.
* Multistep compiling (e.g. compiling an esoteric language into C, which then compiles into an executable) is a legal way to answer the problem. However, this is limited to the use of three compilation steps at most (in order to avoid answers that encode the desired output in the sequence of compilers used rather than in the source code).
* Don't use unusual compiler flags to loophole the question via abusing the `-D` option of a C compiler to hide code (or similar techniques that move code from the program into the compiler flags). You might well need to use unusual compiler flags to produce the executable in the right format, but these should be flags that would generally be useful for compiling programs, not flags specific to the program you've written (and that embed information about it); remember that on this site, the language you're using is defined by the interpreter and compiler flags that you're using.
* Likewise, it's possible that your solution will require a specific filename for the source code; in order to prevent you using this to store code, any specific filename should consist of one character, possibly followed by a standard file extension for the language you are using.
* Please state the exact compiler and version you're using to compile your program, together with the compiler flags you need to build it, because your answer may be hard to reproduce / verify for correctness otherwise; solutions to this question are likely to inherently be somewhat compiler-specific.
* This problem is mostly aimed at compilation into executable formats used by operating systems, but if you have a language that compiles into something else (e.g. bytecode), feel free to submit an answer for that setup, too, even if it won't be quite as impressive. We aren't in the business of unnecessarily restricting what languages you can use here.

## Victory condition

This is effectively a (minimize size of the source) and sizecoding (minimize size of the executable) challenge at the same time (because the two are the same): in this challenge, a program is considered to score better than another if it has a shorter length in bytes. So once you've figured out how to solve this problem at all, you can see if you can do better by fitting the program into fewer bytes.

# Answer
# CoffeeScript to JavaScript, 2 bytes

```
a;

```

Try it

---

Without ban "programs where all the commands compile into themselves", js2js would be a much better choice, IMO.
> 8 votes

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


# Question
Title: Make a rectangle from a collection of (sliced) squares
Inspired by Make a Rectangle from a Triangle.

## Task

There is a famous formula on the sum of first \\$n\\$ squares:

$$ 1^2 + 2^2 + \dots + n^2 = \frac{n(n+1)(2n+1)}{6} $$

It is known that this number is composite for any \\$n \ge 3\\$.

Now, imagine a collection of row tiles (a tile of shape \\$1 \times k\\$ with the number \\$k\\$ written on each cell), and you have 1 copy of size-1 tile, 2 copies of size-2 tiles, ... and \\$n\\$ copies of size-\\$n\\$ tiles.

```
[1]  [2 2]  [2 2]  [3 3 3]  [3 3 3]  [3 3 3] ...

```

Then arrange them into a rectangle whose width and height are both \\$ \ge 2\\$. You can place each tile horizontally or vertically.

```
+-----+---+-+-+
|3 3 3|2 2|1|2|
+-----+---+-+ |
|3 3 3|3 3 3|2|
+-----+-----+-+

```

Output such a matrix if it exists. You don't need to indicate the boundaries; just output the resulting matrix of integers. Your program may do whatever you want if the solution doesn't exist.

I believe there exists a solution for any \\$n \ge 3\\$. Please let me know if you find a proof or counterexample!

Standard rules apply. The shortest code in bytes wins.

## Examples

```
n = 3: (2x7 example)
3 3 3 3 3 3 1
3 3 3 2 2 2 2

n = 4: (3x10 example)
4 4 4 4 4 4 4 4 2 2
4 4 4 4 3 3 3 2 2 1
4 4 4 4 3 3 3 3 3 3

n = 5: (5x11 example)
5 5 5 5 5 4 4 4 3 3 3
5 5 5 5 5 4 4 4 3 3 1
5 5 5 5 5 4 4 4 3 3 2
5 5 5 5 5 4 4 4 3 3 2
5 5 5 5 5 4 4 4 4 2 2

n = 6: (7x13 example)
6 6 6 6 6 5 5 5 5 5 3 3 3
6 6 6 6 6 5 5 5 5 3 3 3 1
6 6 6 6 6 5 5 5 5 4 3 3 3
6 6 6 6 6 5 5 5 5 4 4 4 2
6 6 6 6 6 5 5 5 5 4 4 4 2
6 6 6 6 6 5 5 5 5 4 4 4 2
6 6 6 6 6 6 4 4 4 4 4 4 2

```

# Answer
# Python 2, ~~238 ...~~ 186 bytes

*-2 bytes thanks to @Arnauld!*

*-5 bytes thanks to @ovs!!*

*-6 bytes thanks to @Jonathan Allan!!*

```
n=input()
p=w=~n*n*(~n-n)/6
e=range(n+1)
def f(a,b,c,d=[]):1>a>exit(c);1>b>f(a-1,w,c+[d]);g=n;exec"e[g]-=1;g<=b>-1<e[g]>f(a,b-g,c,d+[g]*g);e[g]+=1;g-=1;"*n
while 1:1>p%w>f(p/w,w,[]);w-=1

```

Try it online!

Notice that the above code only used horizontal tiles. To prove it's correct...

---

# C++ (gcc), 4355 bytes

This code is an explicit construction using only horizontal tiles for \\$n\>6\\$. It can produce correct solutions (at least) up to \\$n=99\\$.

```
#include <bits/stdc++.h>
using namespace std;
void dim(int x,int&p,int&q)
{
	int u[]={x,x+1,x+x+1},o=0;
	while(u[o]%2) ++o; u[o]/=2;
	o=0; while(u[o]%3) ++o; u[o]/=3;
	sort(u,u+3);if(x%3==1)swap(u[0],u[1]);
	p=u[0];q=u[1]*u[2];
}
int o[100][99999],c[99999],g[99999];
void brute(int n,int& v,int& u,bool t)
{
	for(int i=1;i<=n;++i) c[i]=i;
	if(t)
	{
		u=n*(n+1)*(2*n+1)/6,v=2;
		while(u%v) ++v;
		if(n>=5) v=u/v;
		u/=v; c[2]-=n==6;
	}
	for(int i=1;i<=v;++i)
	{
		int s=u,cnt=0;
		for(int j=n;j>=1;--j) while(s>=j&&c[j])
		{
			s-=j, --c[j]; for(int k=j;k--;) o[i][++cnt]=j;
		}
	}
	c[2]+=t&&n==6;
	for(int i=u;i>=u-1&&i;--i)
		for(int j=1;j<=v;++j) if(!o[j][i])
		{
			int x=0; while(!c[x]) ++x;
			--c[x]; int l=x; --j;
			while(l--) o[++j][i]=x;
		}
}
int s0[99999],s1[99999];
//find a subset of a with sum b
//guaranteed b is half of a's sum
//guaranteed a is consecutive
pair<vector<int>,vector<int>> solve2(vector<int> a,int b)
{
	if(!a.size()) return make_pair(a,a);
	int w=0,s=0,as=a.size();
	for(int i=0;i<as;++i)
		s0[i+1]=s0[i]+a[i],
		s1[i+1]=s1[i]+a[as-1-i];
	while(w<a.size()&&s+a[w]<=b)
		s+=a[w++];
	assert(w!=a.size()&&w>0);
	for(int l=0;l<w;++l)
	{
		int r=w-1-l;
		int p=s0[l]+s1[r];
		if(p>b) continue;
		int q=b-p;
		if(!(a[l]<=q&&q<=a[as-r-1]))
			continue;
		//first l, last r, q.
		vector<int> A,B;
		for(int j=0;j<l;++j) A.push_back(a[j]);
		A.push_back(q);
		for(int j=as-r;j<as;++j) A.push_back(a[j]);
		for(int j=l;j<as-r;++j)
		{
			if(a[j]==q) q=-1;
			else B.push_back(a[j]);
		}
		return make_pair(A,B);
	}
	assert(0);
}
int main()
{
	int n,p,q;
	cin>>n;
	assert(n>=3);
	if(n<=6) brute(n,p,q,1);
	else
	{
		if(n%3==1)
		{
			int x=n%3,pp,qq;
			dim(x,p,q);
			brute(x,p,q,0);
			while(n!=x)
			{
				//x+1...x+3
				int xx=x+3; dim(xx,pp,qq);
				assert(pp-p==2&&qq-q==x*3+6);
				for(int i=x+1;i<=x+3;++i) c[i]=i;
				int mr=x/6;
				for(int i=1;i<=p;++i)
				{
					int cnt=q;
					vector<int> rv;
					if(i<=mr) rv=vector<int>{x+2,x+2,x+2};
					else rv=vector<int>{x+1,x+2,x+3};
					for(int j:rv)
					{
						assert(c[j]); --c[j];
						for(int k=j;k--;) o[i][++cnt]=j;
					}
				}
				vector<int> rv;
				for(int i=x+1;i<=x+3;++i)
					for(int j=c[i];j;--j) rv.push_back(i);
				pair<vector<int>,vector<int>> s=solve2(rv,qq);
				for(int i=p+1;i<=pp;++i)
				{
					int cnt=0;
					for(auto j:(i==pp)?s.first:s.second)
					{
						assert(c[j]); --c[j];
						for(int k=j;k--;) o[i][++cnt]=j;
					}
				}
				p=pp; q=qq; x=xx;
			}
		}
		else
		{
			int x=n%6,pp,qq;
			dim(x,p,q);
			brute(x,p,q,0);
			while(n!=x)
			{
				int xx=x+6; dim(xx,pp,qq);
				if(n%6==0)
					assert(pp-p==1&&qq-q==24*x+90); //[1 2 3 4 5 6]*3+[2 3 5 5 6 6]
				else if(n%6==2)
					assert(pp-p==2&&qq-q==12*x+39); //[1 2 3 4 5 6]+[1 1 2 3 5 6]
				else if(n%6==3)
					assert(pp-p==2&&qq-q==12*x+45); //[1 2 3 4 5 6]+[1 2 4 5 6 6]
				else if(n%6==5)
					assert(pp-p==1&&qq-q==24*x+78); //[1 2 3 4 5 6]*3+[1 1 2 2 4 5]
				else assert(0);
				vector<int> uv;
				if(n%6==0) uv=vector<int>{2,3,5,5,6,6};
				else if(n%6==2) uv=vector<int>{1,1,2,3,5,6};
				else if(n%6==3) uv=vector<int>{1,2,4,5,6,6};
				else uv=vector<int>{1,1,2,2,4,5};
				for(int j=1;j<4/(pp-p);++j)
					for(int k=1;k<=6;++k) uv.push_back(k);
				for(int i=x+1;i<=x+6;++i) c[i]=i;
				for(int i=1;i<=p;++i)
				{
					int cnt=q;
					for(auto j_:uv)
					{
						int j=j_+x;
						assert(c[j]); --c[j];
						for(int k=j;k--;) o[i][++cnt]=j;
					}
				}
				vector<int> rv;
				for(int i=x+1;i<=x+6;++i)
					for(int j=c[i];j;--j) rv.push_back(i);
				if(pp-p==2)
				{
					pair<vector<int>,vector<int>> s=solve2(rv,qq);
					for(int i=p+1;i<=pp;++i)
					{
						int cnt=0;
						for(auto j:(i==pp)?s.first:s.second)
						{
							assert(c[j]); --c[j];
							for(int k=j;k--;) o[i][++cnt]=j;
						}
					}
				}
				else
				{
					int i=pp,cnt=0;
					for(auto j:rv)
					{
						assert(c[j]); --c[j];
						for(int k=j;k--;) o[i][++cnt]=j;
					}
				}
				p=pp; q=qq; x=xx;
			}
		}
	}
	cerr<<p<<","<<q<<"\n";
	for(int i=1;i<=p;++i,cout<<"\n")
		for(int j=1;j<=q;++j)
			cout<<setw(2)<<o[i][j]<<" ";
	if(n>6)
	{
		for(int i=1;i<=n;++i) c[i]=i;
		for(int i=1;i<=p;++i)
			for(int j=1;j<=q;++j)
			{
				int u=o[i][j];
				assert(u>=1&&u<=n);
				for(int k=2;k<=u;++k)
					assert(o[i][++j]==u);
				--c[u];
			}
		for(int i=1;i<=n;++i) assert(!c[i]);
	}
}

```

Try it online!

---

# How does the construction work?

It's an incremental construction. Consider \\$n \bmod 6\\$, we can have these values for height and width of rectangles:

* \\$n/6\times (n+1)(2n+1)~(n\bmod 6=0)\\$
* \\$(2n+1)/3\times n(n+1)/2~(n\bmod 6=1)\\$
* \\$(n+1)/3\times n(2n+1)/2~(n\bmod 6=2)\\$
* \\$n/3\times (n+1)(2n+1)/2~(n\bmod 6=3)\\$
* \\$(2n+1)/3\times (n+1)n/2~(n\bmod 6=4)\\$
* \\$(n+1)/6\times n(2n+1)~(n\bmod 6=5)\\$

(dimensions might be \\$1\\$ for \\$n\leq 6\\$ so these small cases are handled manually)

So the main idea of my construction is:

* We construct rectangles with the heights and widths as in above list.
* If \\$n\bmod 3 \neq 1\\$, construct the solution for \\$n-6\\$ recursively, add in \\$n-5,n-4\cdots n\\$. The height of the rectangle will only increase 1 or 2.
* If \\$n\bmod 3=1\\$, construct the solution for \\$n-3\\$ recursively and add in \\$n-2,n-1,n\\$. The height of the rectangle will only increase 2.
* We first carefully assign the new numbers to the added columns, and then put rest of the numbers into one or two added rows.

The rest of the job is some careful casework to pick the numbers. These details are left as an exercise to the readers (Be ready for some long and tedious casework!). If you complete all the details, this should become a formal proof for the existence of the solutions (and using only horizontal tiles!).
> 12 votes

# Answer
# JavaScript (ES6), 188 bytes

A shorter version inspired by @newbie's answer.

```
f=(n,w=2)=>(g=(h,a,m,r=[])=>h%1||r[w]?1:r[w-1]?--h*g(h,a,M=[...m,r]):a.every((_,j,[...a])=>a[j]++>j++||g(h,a,m,[...r,...Array(j).fill(j)])))(n*(~n-n)*~n/6/w,Array(n).fill(0),[])?f(n,w+1):M

```

Try it online!

### Commented

```
f = (                           // f is a recursive function taking:
  n, w = 2                      //   n = input, w = width of matrix
) => (                          //
g = (                           // g is a recursive function taking:
  h, a,                         //   h = height of matrix, a[] = array of counters
  m, r = []                     //   m[] = matrix, r[] = current row
) =>                            // (g returns 0 for success or 1 for failure)
  h % 1 ||                      // if h is not an integer or
  r[w] ?                        // the length of r[] is w + 1 (i.e. r[] is too long):
    1                           //   abort
  :                             // else:
    r[w - 1] ?                  //   if the length of r[] is w:
      --h *                     //     decrement h and force success if h = 0
      g(                        //     do a recursive call with:
        h, a,                   //       h and a[] unchanged
        M = [...m, r]           //       a new matrix M[] with r[] appended
      )                         //     end of recursive call
    :                           //   else:
      a.every((_, j, [...a]) => //     for each entry at position j in a[]:
        a[j]++ > j++ ||         //       unless a[j] is greater than j,
        g(                      //       do a recursive call with:
          h, a, m,              //         h, a[] and m[] unchanged
          [ ...r,               //         j added j times to the current row
            ...Array(j).fill(j) //         NB1: both j and a[j] where incremented above
          ]                     //         NB2: a[] is a local copy defined in this loop
        )                       //       end of recursive call
      )                         //     end of every()
)(                              // initial call to g with:
  n * (~n - n) * ~n / 6 / w,    //   h = n(n+1)(2n+1) / 6 / w
  Array(n).fill(0),             //   a[] initialized to n 0's
  []                            //   an empty matrix
) ? f(n, w + 1) : M             // return M[] on success, or try again with w + 1

```

---

# JavaScript (ES6),  ~~297~~  287 bytes

A brute-force search, which always try to put the biggest available rectangles first.

```
f=(n,i=2,k=n*(~n-n)*~n/6,A=n=>n?[0,...A(n-1)]:[])=>k%i||!(g=(m,a,x,y=m.findIndex(r=>r.some(v=>!v*~++x,x=-1)))=>~y?a.some((v,j)=>[0,1].some(r=>v<(o=n-j)&o<=(r?i-y:k/i-x)&&g(M=m.map(r=>[...r]),b=[...a],b[(h=p=>p--?h(p,M[y+r*p][x+!r*p]=o):j)(o)]++))):1)(A(i).map(_=>A(k/i)),A(n))?f(n,i+1):M

```

Try it online!
> 6 votes

# Answer
# Wolfram Language (Mathematica), 148 bytes

finds random matrix with only horizontal tiles.
It is very slow for n\>5 but this is code-golf...

```
(While@!MatrixQ[Join@@@(w=TakeList[d=RandomSample@Flatten[Table[#~Table~#,#]&/@Range@#,1],r=RandomChoice@IntegerPartitions[#(#+1)/2][[2;;-2]]])];w)&

```

Try it online!

here is also a very quick random generator for test cases up to 6

# Wolfram Language (Mathematica), 97 bytes

```
(While@!MatrixQ[Join@@@(w=Partition[RandomSample@Flatten[Table[#~Table~#,#]&/@Range@#,1],3])];w)&

```

Try it online!
> 1 votes

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


title: Where am I now?

text:
# Question
Title: Where am I now?
# Where am I now?

Given a string `d`, containing only the letters `NSWE`, determine the coordinates I've traveled (from left to right, consuming greedily) and the final coordinate where I reside.

The rules for reading coordinates from left-to-right:

* ***If the next character is `N` or `S`***:
    + **If the character after the `N` or `S` is another `N` or `S`**:
        - Consume only the first `N` or `S`.
        - Output `[0,1]` for `N`
        - Output `[0,-1]` for `S`
    + **If the character after the `N` or `S` is `W` or `E`**:
        - Consume both the `N` or `S` and the `W` or `E`.
        - Output `[1,1]` or `[-1,1]` for `NE` and `NW`, respectively.
        - Output `[1,-1]` or `[-1,-1]` for `SE` and `SW`, respectively.
* ***If the character is an `E` or `W` not preceded by an `S` or `N`***:
    + Consume the `E` or `W`.
    + Output `[1,0]` for `E`.
    + Output `[-1,0]` for `W`.

---

# Worked Example

***NSWE***

```
[0,1]   (North      N)
[-1,-1] (South-west SW)
[1,0]   (East       E)
[0,0]   (N+SW+E = Didn't actually move)

```

Note this can be in any format, here are other examples of valid output:

```
[[0,1],[-1,-1],[1,0],[0,0]]

[[[0,1],[-1,-1],[1,0]],[0,0]]

"0,1\n0,-1\n-1,0\n1,0\n0,0"

```

Etc...

---

# More Examples

***SWSENNESWNE***

```
[-1,-1]
[1,-1]
[0,1]
[1,1]
[-1,-1]
[1,1]
[1,0]

```

***NNEESESSWWNW***

```
[0,1]
[1,1]
[1,0]
[1,-1]
[0,-1]
[-1,-1]
[-1,0]
[-1,1]
[0,0]

```

**NENENEE**

```
[1,1]
[1,1]
[1,1]
[1,0]
[4,3]

```

**NEN**

```
[1,1]
[0,1]
[1,2]

```

**EEE**

```
[1,0]
[1,0]
[1,0]
[3,0]

```

---

# Rules

* You may output in any convenient format that doesn't violate loopholes.
* You must consume greedily, `NWE` is never `N,W,E`, it is always `NW,E`.
    + This applies to: `SW*`, `SE*`, `NW*`, `NE*`.
    + You are consuming left to right, greedily.
* The is , lowest byte-count wins.

# Answer
# Python 2, 116 bytes

```
import re
a=[(int(s,35)%5-3,('N'in s)-('S'in s))for s in re.findall('[NS][EW]?|.',input())]
print a,map(sum,zip(*a))

```

Try it online!

## With output as `[(3+4j), 1, -1j, …]`, 91 bytes

```
lambda x:[sum(1j**(ord(c)%8%5)for c in s)for s in[x]+re.findall('[NS][EW]?|.',x)]
import re

```

Try it online!

This lambda returns a list of Gaussian integers: the first is the final coordinate, and all others are the steps required to get there.
> 8 votes

# Answer
# Attache, 80 bytes

```
V#Sum##{Chop[1-ToBase[22260446188,3],2][Sum@Ords=>MatchAll[_,/"[NS][WE]|."]%11]}

```

Try it online!

This is an anonymous function which takes one string argument.

## Explanation

The first task is to implement the parsing phase of this question. I found it shortest to use a simple Regex to parse the input (`_`):

```
MatchAll[_,/"[NS][WE]|."]

```

This matches all occurrences of the regex `[NS][WE]|.`, as seen in many other answers. This greedily yields the requested directions.

Now, we're going to apply a hash function to each direciton. We take the codepoints of each direction and sum them. This gives the following mapping:

```
Direction       Ord-sum
E               69
N               78
S               83
W               87
NE              147
SE              152
NW              165
SW              170

```

We shall try to map these values to a smaller domain; modulo is useful for this, and we can demonstrate that the smallest modulo which results in unique values for all given inputs is 11. Sorting by remainders, this gives us the following table:

```
Direction       Ord-sum         % 11
NW              165             0
N               78              1
E               69              3
NE              147             4
SW              170             5
S               83              6
SE              152             9
W               87              10

```

Now, we have an input correspondence, as encoding by `Sum@Ords=>[...]%11`. Next, we have to transform these remainders into points. We shall try to derive another mapping, which means inserting "sparse-filling values" to hashes which do not correspond to directions shall be useful:

```
Direction       Hash        Coordinates
NW              0           [-1, 1]
N               1           [0, 1]
--             (2)          [0, 0]
E               3           [1, 0]
NE              4           [1, 1]
SW              5           [-1, -1]
S               6           [0, -1]
--             (7)          [0, 0]
--             (8)          [0, 0]
SE              9           [1, -1]
W               10          [-1, 0]

```

We currently have a series of points, which can gives a list indexable by the hash:

```
[-1, 1] [0, 1] [0, 0] [1, 0] [1, 1] [-1, -1] [0, -1] [0, 0] [0, 0] [1, -1] [-1, 0]

```

Now, we shall compress this, seeing as how its only composed of `-1`s, `0`s, and `1`s. Since the list represents pairs, we can flatten the list without losing data. Then, if we take each number `x` and calculate `1-x`, we get the following list:

```
2 0 1 0 1 1 0 1 0 0 2 2 1 2 1 1 1 1 0 2 2 1

```

We can convert this into a base 3 number:

```
2010110100221211110221<sub>3</sub>
```

Converting to base 10:

```
2010110100221211110221<sub>3</sub> ≡ 22260446188<sub>10</sub>
```

To summarize, we've taken our points, un-paired them, took each element subtracted from `1`, and converted from base `3`, giving us `22260446188`. We can decompress as such:

1. Convert to base 3: `ToBase[22260446188,3]`
2. Take each number subtracted from one (self-inverse): `1-ToBase[22260446188,3]`
3. Re-pair the list: `Chop[1-ToBase[22260446188,3],2]`

This gives us our original set of pairs. Then, we can perform the aforementioned indexing like this:

```
(chopped value)[hashes]

```

Since, in Attache, indexing by an array returns all elements corresponding to those indices. (So, `[1,2,3,4][ [0,0,-1,1] ] = [1,1,4,2]`.) Now, we have the directions of the path that the OP walked. What's left is to calculate the sum.

So we capture this result in a lambda `{...}` and put it as the first function in a function composition (`a##b`), with the second being `V#Sum`. This is a fork, which, given input `x`, expands to be:

```
V[x, Sum[x]]

```

`Sum`, when given an 2D array, happens to sum every column in the array (as a result of vectorized summation). So, this pairs the directions with the final destination, and we have our final result.
> 5 votes

# Answer
# JavaScript (ES6), 102 bytes

Returns a string.

```
s=>s.replace(/[NS][EW]|./g,s=>(D=d=>!!s.match(d),x+=h=D`E`-D`W`,y+=v=D`N`-D`S`,[h,v]+`
`),x=y=0)+[x,y]

```

Try it online!
> 4 votes

# Answer
# MATL, 45 bytes

```
'NS' 'WE'Z*Z{2MhX{h'eklihfmj'X{YX9\3_2&YAqts

```

Try it online! Or verify all test cases.

### Explanation (with example)

Consider input `'NSWE'` as an example.

```
'NS' 'WE'  % Push these two strings
           % STACK: 'NS', 'WE'
Z*         % Cartesian product. Gives a 4×2 char matrix
           % STACK: ['NW'; 'NE'; 'SW'; 'SE']
Z{         % Cell array of rows (strings)
           % STACK: {'NW', 'NE', 'SW', 'SE'}
2M         % Push again the inputs of the second-last function call
           % STACK: {'NW', 'NE', 'SW', 'SE'}, 'NS', 'WE'
h          % Concatenate horizontally
           % STACK: {'NW', 'NE', 'SW', 'SE'}, 'NSWE'
X{         % Cell array of individual elements (chars)
           % STACK: {'NW', 'NE', 'SW', 'SE'}, {'N', 'S', 'W', 'E'}
h          % Concatenate horizontally
           % STACK: {'NW', 'NE', 'SW', 'SE', 'N', 'S', 'W', 'E'}
'eklihfmj' % Push this string
           % STACK: {'NW', 'NE', 'SW', 'SE', 'N', 'S', 'W', 'E'}, 'eklihfmj'
X{         % Cell array of individual elements (chars)
           % STACK: {'NW','NE','SW','SE','N','S','W','E'},{'e','k','l','i','h','f','m','j'}
YX         % Implicit input. Regexp replace: replaces 'NW' by 'e', then 'NE' by 'k', etc.
           % Note that the two-letter combinations are replaced first, which implements
           % the greediness; and the target letters do not appear in the source, which
           % avoids unwanted interactions between replacements
           % STACK: 'hlj'
9\         % Modulo 9 (of codepoints), element-wise
           % STACK: [5, 0, 7]
3_2&YA     % Convert to base 3 with 2 digits. Gives a 2-column matrix
           % STACK: [1, 2; 0, 0; 2, 1]
q          % Subtract 1, element-wise
           % STACK: [0, -1; -1, -1; 1, 0]
tXs        % Duplicate. Sum of each column
           % STACK: [0, -1; -1, -1; 1, 0], [0, 0]
           % Implicit display

```
> 4 votes

# Answer
# Java (JDK), 167 bytes

```
s->{var r="";int i=0,l=s.length,c,x=0,y=0,Y,X;for(;i<l;x+=X=c>1||i<l&&(c=~-s[i]/6%4)>1&&++i>0?c*2-5:0,r+=X+","+Y+" ")y+=Y=(c=~-s[i++]/6%4)<2?1-c*2:0;return r+x+","+y;}

```

Try it online!

## Explanations

Thanks to `c=~-s[i]/6%4`, the following mapping is done:

```
'N' -> ascii: 78 -> -1 = 77 -> /6 = 12 -> %4 = 0
'S' -> ascii: 83 -> -1 = 83 -> /6 = 13 -> %4 = 1
'W' -> ascii: 87 -> -1 = 86 -> /6 = 14 -> %4 = 2
'E' -> ascii: 69 -> -1 = 68 -> /6 = 11 -> %4 = 3

```
* `NS` is checked with `c<2` and mapped to `+1`/`-1` using `1-c*2`;
* `EW` is checked with `c>1` and mapped to `+1`/`-1` using `c*2-5`.

## Credits
> 4 votes

# Answer
# Retina 0.8.2, 93 bytes

```
.+
$&¶$&
\G[NS]?[EW]?
$&¶
G`.
W
J
%O`.
+`EJ|NS

m`^((J)?[EJ]*)((S)?[NS]*)
$#2$*-$.1,$#4$*-$.3

```

Try it online! Explanation:

```
.+
$&¶$&

```

Duplicate the input.

```
\G[NS]?[EW]?
$&¶

```

Split the first copy up into directions.

```
G`.

```

Remove extraneous blank lines created by the above process.

```
W
J

```

Change `W` into `J` so that it sorts between `E` and `N`. (Moving `E` to between `S` and `W` would also work.)

```
%O`.

```

Sort each line into order.

```
+`EJ|NS

```

Delete pairs of opposite directions (this only affects the last line of course).

```
m`^((J)?[EJ]*)((S)?[NS]*)
$#2$*-$.1,$#4$*-$.3

```

Count the number of horizontal and vertical movements, adding signs where necessary.

Those of you who know the differences between Retina 0.8.2 and Retina 1 will want to point out that I can save 2 bytes in Retina 1 because it uses `*` instead of `$*`. While I was there I tried to simplify the splitting process but I was unable to reduce the byte count further, I was only able to equal it with this:

```
L$`$(?<=(.*))|[NS]?[EW]?
$&$1

```
> 3 votes

# Answer
# Java 10, ~~269~~ ~~265~~ ~~243~~ ~~238~~ ~~224~~ 219 bytes

```
s->{var r="";int x=0,y=0,t,X,Y,a;for(;!s.isEmpty();r+=X+"|"+Y+" ",s=s.substring(t+1)){a=s.charAt(t=0);var b=s.matches("[NS][EW].*");x+=X=b?1-s.charAt(t=1)/70*2:a<70?1:-a/87;y+=Y=b|a>69&a<87?1-a%2*2:0;}return r+x+"|"+y;}

```

-10 bytes thanks to *@ceilingcat*.

Try it online.

**Explanation:**

```
s->{                  // Method with String as both parameter and return-type
  var r="";           //  Result-String, starting empty
  int x=0,            //  Ending `x`-coordinate, starting at 0
      y=0,            //  Ending `y`-coordinate, starting at 0
      t,X,Y,a;        //  Temp-integers
  for(;!s.isEmpty()   //  Loop as long as the input-String is not empty yet:
      ;               //    After every iteration:
       r+=X+"|"+Y+" ",//     Append the current steps to the result-String
       s=s.substring(t+1)){
                      //     Remove the first `t+1` characters from the input-String
    a=s.charAt(t=0);  //   Set `a` to the first character of the input to save bytes,
                      //   and reset `t` to 0
    var b=s.matches("[NS][EW].*");
                      //   Check if the input-String starts with N/S followed by E/W
    x+=X=             //   Set `X` to (and increase `x` by `X` afterwards):
      b?              //    If the boolean check was truthy:
        1-s.charAt(t=1)/70*2
                      //     Set `X` to 1 if 'E', -1 if 'W'
                      //     And set `t` to 1
       :              //    Else:
        a<70?1:-a/87; //     Set `X` to 1 if 'E', -1 if 'W', 0 if 'N' or 'S'
    y+=Y=             //   Set `Y` to (and increase `y` by `Y` afterwards):
      b|a>69&a<87?1-a%2*2
                      //    Set `Y` to 1 if 'N', -1 if 'S'
       :              //    And if the boolean check was falsey:
        0;}           //     Set `Y` to 0 if 'E' or 'W'
  return r+x+"|"+y;}  //  Append the ending coordinates, and return the result-String

```
> 3 votes

# Answer
# APL (Dyalog Unicode), <sup>~~40~~</sup> 32 bytes

```
2((⊢,+/)1⊥¨0j1*⊢⊂⍨1,2≤/|)'NWS'∘⍳

```

Try it online!

It turns out that we don't need PCRE.

### How it works

```
2((⊢,+/)1⊥¨0j1*⊢⊂⍨1,2≤/|)'NWS'∘⍳
                         'NWS'∘⍳  ⍝ V←Map 'NWSE' into 1,2,3,4
2(                     |)  ⍝ Modulo 2 (1 if NS, 0 otherwise)
                    2≤/    ⍝ For each consecutive pair,
                           ⍝ 0 if [NS][EW] combination, 1 otherwise
                  1,  ⍝ Add a leading 1
               ⊢⊂⍨    ⍝ Chunkify V at ones
           0j1*  ⍝ Power of imaginary unit
        1⊥¨      ⍝ Sum within each chunk
  (⊢,+/)  ⍝ Append the grand total to the vector

```

---

# APL (Dyalog Unicode), 40 bytes

```
(⊢,+/)1⊥¨0j1*(⊂'NWS')⍳¨'[NS][EW]|.'⎕S'&'

```

Try it online!

Uses PCRE to divide into segments, and then the power of `0j1` (imaginary unit) to convert the directions to complex numbers. `EW` is mapped to the real part (`E` being positive) and `NS` to the imaginary part (`N` being positive).

`9 11∘.○` in the footer converts the vector of complex numbers into a two-row matrix, by splitting each complex number into its real (top row) and imaginary (bottom row) parts.

### How it works

```
(⊢,+/)1⊥¨0j1*(⊂'NWS')⍳¨'[NS][EW]|.'⎕S'&'
                       '[NS][EW]|.'⎕S'&'  ⍝ Regex search; split into greedy segments
             (⊂'NWS')⍳¨  ⍝ Index of each char within 'NWS' (1 2 3)
                         ⍝ 'E' becomes 4 since it is not found
         0j1*  ⍝ Power of imaginary unit
      1⊥¨      ⍝ Sum within each segment
(⊢,+/)         ⍝ Append its sum on its right

```
> 3 votes

# Answer
# Perl 5 `-n`, ~~94~~ 74 bytes

```
map{say$v=/N/-/S/,',',$h=/E/-/W/;$y+=$v;$x+=$h}/[NS][EW]?|E|W/g;say"$x,$y"

```

Try it online!
> 2 votes

# Answer
## JavaScript (ES6), 102 bytes

```
f=
s=>s.replace(/((N)|(S))?((E)|(W))?/g,(m,v,n,s,h,e,w)=>(x+=h=!w-!e,y+=v=!s-!n,m?[h,v]+`
`:[x,y]),x=y=0)
```

```
<input oninput=o.textContent=/[^NSEW]/.test(this.value)?``:f(this.value)><pre id=o>0,0
```

Returns a string.
> 1 votes

# Answer
# F# (Mono), 269 bytes

```
let f s=
 let l,h=(string s).Replace("NW","A").Replace("NE","B").Replace("SW","C").Replace("SE","D")|>Seq.map(function 'N'->0,1|'S'->0,-1|'W'-> -1,0|'E'->1,0|'A'-> -1,1|'B'->1,1|'C'-> -1,-1|'D'->1,-1)|>Seq.mapFold(fun(x,y) (s,t)->(s,t),(x+s,y+t))(0,0)
 Seq.append l [h]

```

Try it online!
> 1 votes

# Answer
# Ruby, ~~75~~ 71 bytes

```
->x{[*x.scan(/[NS][EW]?|./),x].map{|s|s.chars.sum{|c|1i**(c.ord%8%5)}}}

```

Try it online!

-4 bytes thanks to benj2240.

Since returning complex numbers looks to be an acceptable output format, I guess it won't get much golfier than just making a port of the very nice Lynn's answer.
> 1 votes

# Answer
# sed, 125

The *taking liberties with output format* version:

Score includes +1 for the `-r` parameter to sed.

```
s/(N|S)(E|W)/\L\2,\1 /g
s/N|S/,& /g
s/E|W/&, /g
s/N|E/A/gi
s/S|W/a/gi
p
:
s/(\S*),(\S*) (\S*),(\S*)/\1\3,\2\4/
t
s/Aa|aA//
t

```

Try it online.

Output is as follows:

* coordinate elements are comma-separated
* each set of coordinates are TAB-separated
* the final coordinate is on a new line
* all numbers are in ℤ-unary:
    + a string of `A` characters represents the +ve integer `len(string)`
    + a string of `a` characters represents the -ve integer `-len(string)`
    + the empty string represents `0`

For example:

* `,` is \[0,0\]
* `,AA` is \[0,2\]
* `aaa,` is \[-3,0\]

---

# sed 4.2.2 including GNU exec extension, 147

The *sensible output format* version:

Score includes +1 for the `-r` parameter to sed.

```
s/(N|S)(E|W)/\L\2 \1\n/g
s/N|S/0 &\n/g
s/E|W/& 0\n/g
s/N|E/1/gi
s/S|W/-1/gi
p
:
s/(\S+) (\S+)\n(\S+) (\S+)/\1+\3 \2+\4/
t
s/\S+/$[&]/g
s/^/echo /e

```

Output is given as space-separated coordinates, one per line. There is an extra newline between the penultimate and ultimate sets of coordinates - not sure if that is problematic or not.

Try it online!
> 1 votes

# Answer
# PHP, 153 bytes

let a regex do the splitting; loop through the matches, print and sum up the intermediate results:

```
preg_match_all("/[NS][EW]?|E|W/",$argn,$m);foreach($m[0]as$s){$x+=$p=strtr($s[-1],NEWS,1201)-1;$y+=$q=strtr($s[0],NEWS,2110)-1;echo"$p,$q
";}echo"$x,$y";

```

Run as pipe with `-nR` or try it online.
> 1 votes

# Answer
# C (gcc), 173 bytes

It's interesting doing this one in a language with no regex support!

```
f(char*s){char*t="[%d,%d]\n";int x[4]={0},i;for(;*s;*x=x[1]=!printf(t,x[1],*x))for(i=-1;i<5;)if(*s=="S NW E"[++i]){x[i/3+2]+=x[i/3]=i%3-1;i+=2-i%3;s++;}printf(t,x[3],x[2]);}

```

Try it online!
> 1 votes

---
Tags: code-golf
---


# Question
Title: Counting shortest paths on a triangular grid
## Background

An Eisenstein integer is a complex number of the form \\$ z = a + b\omega \\$ where \\$a, b\\$ are integers and \\$\omega\\$ is the third root of unity \\$\frac{1-\sqrt3i}{2}\\$. The Eisenstein integers can be viewed as the triangular lattice points, as shown in the image below (from Wikipedia):

Following the triangular grid, one step of movement can be done in six directions:

$$ \begin{array}{r|r} \text{Direction} & \text{Step} \\ \hline E & 1 \\ NE & 1 + \omega \\ NW & \omega \\ W & -1 \\ SW & -1 - \omega \\ SE & -\omega \end{array} $$

## Task

Given an Eisenstein integer \\$z\\$, count all shortest paths from the origin (\\$0\\$) to the point equivalent to \\$z\\$ on the triangular grid.

Since \\$z = a + b \omega\\$ can be represented by two integers \\$ a, b \\$, you can take the input as two integers \\$a, b\\$ in any consistent order and structure of your choice.

One way to compute this is (thanks to @xnor):

```
Take the absolute values of [a, b, a-b], and call it L
Calculate binomial(max(L), any other value in L)

```

## Test cases

```
 a  b  ans
 0  0    1
 2  0    1
 5  3   10
 4  4    1
 2  3    3
 0  2    1
-2  2    6
-4  0    1
-5 -3   10
-1 -1    1
-3 -5   10
 0 -3    1
 4 -1    5
-4 -9  126
 7 -4  330
 8  1    8
 3 -3   20

```

# Answer
> 3 votes
# Wolfram Language (Mathematica), 38 bytes

```
Max[l=Abs@{#,#2,#-#2}]~Binomial~Min@l&

```

Try it online!

# Answer
> 3 votes
# Jelly, 7 bytes

```
;IAṀc$Ṁ

```

**Try it online!**

### How?

```
;IAṀc$Ṁ - Link: list of two integers   e.g. [-4, -9]
 I      - incremental differences           [-5]           (since -9 - -4 = -5)
;       - concatenate                       [-4, -9, -5]
  A     - absolute values                   [4, 9, 5]
     $  - last two links as a monad:
   Ṁ    -   maximum                         9
    c   -   choose (vectorises)             [126, 1, 126]  (9c4=9c5=126 and 9c9=1)
      Ṁ - maximum                           126

```

# Answer
> 2 votes
# Python 3.8, <sup>~~69~~</sup> 68 bytes

Saved a byte thanks to newbie!!!

```
lambda a,b:math.comb(*sorted(map(abs,[a,b,a-b]))[2::-2])
import math

```

Try it online!

# Answer
> 2 votes
# APL (Dyalog), ~~13~~ 12 bytes

*1 byte saved thanks to @ngn!*

```
(⌊/!⌈/)∘|,,-

```

Try it online!

# Answer
> 1 votes
# Pyth, 11 bytes

Seems rather long.

```
.cF_tSa0+aF

```

**Test suite**

### Explanation

Uses xnor's description.

```
.cF_tSa0+aF           Full program. Input: a 2-element list [a,b].
        +aF           Add |a-b| to the list of inputs. Produces [|a-b|,a,b]
      a0              Absolute difference with 0 (i.e. absolute value). Vectorizes.
    tS                Sort the list of absolute values and remove the first element.
.cF_                  Reverse the above and apply nCr to its elements.

```

# Answer
> 1 votes
# C (gcc), ~~92~~ 82 bytes

```
g(n,k){k=k<0?n=-n,-k:k;n=n<0?k-n:n;k^=n<k?n^=k^=n:0;n=n---k&&k?g(n,k-1)+g(n,k):1;}

```

Try it online!

*10 bytes shorter thanks to ceilingcat!*

This is longer than most of the other entries, but I think it's respectable since C doesn't have a built-in for binomial coefficients.

The code uses the fact that the four Eisenstein integers $$n+k\omega,$$ $$-n-k\omega,$$ $$k-n+k\omega,$$ and $$n-k-k\omega$$ are symmetrically located about the origin. Since the original triangular lattice is symmetrical about the origin, all four of those points will have the same number of paths to the origin.

Because of this, we can replace the input point with a point with non-negative Eisenstein coordinates which has the same number of paths to the origin, and that simplifies the computation.

Here's how it works:

1. If `k < 0`, replace `n` by `-n`, and `k` by `-k`. So now `k` is non-negative, but the output will be the same as for the original values of `n` and `k`.
2. If `n < 0`, replace `n` by `k-n`. Now `n` is also non-negative, but again the output will be the same.
3. If `k > n`, swap `n` and `k`, so that `n` is the larger of the two (or they're equal).
4. Compute the binomial coefficient \\$\binom{n}{k}\\$ using the recursive formula for it.

# Answer
> 0 votes
# Charcoal, 33 bytes

```
⊞υＮ⊞υ±Ｎ⊞υΣυ≔…⌊↔υ⌈↔υθＩ∨¬θ÷Π⊕θΠ⊕Ｅθκ

```

Try it online! Link is to verbose version of code. Uses @xnor's formula. Explanation:

```
⊞υＮ

```

Input `a` and push it to the list.

```
⊞υ±Ｎ

```

Input `b` and push `-b` to the list.

```
⊞υΣυ

```

Take the sum of the list, `a-b`, and push that to the list.

```
≔…⌊↔υ⌈↔υθ

```

Take the minimum and maximum of the list and form a range between the two.

```
Ｉ∨¬θ

```

If the range is empty then just output `1` (unfortunately in Charcoal the product of an empty list isn't `1`)...

```
÷Π⊕θΠ⊕Ｅθκ

```

... otherwise output the quotient of the products of the ranges `min+1..max` and `1..max-min`.

# Answer
> 0 votes
# JavaScript (ES6), 83 bytes

Takes input as `(a)(b)`. Uses @xnor's formula.

```
with(Math)f=a=>g=(b,k=min(...a=[a,b,a-b].map(abs),n=max(...a)))=>k?n--*g(0,k-1)/k:1

```

Try it online!

# Answer
> 0 votes
# 05AB1E, 7 bytes

```
¥«ÄZscà

```

Port of *@JonathanAllan*'s Jelly answer, so make sure to upvote him as well!!

Try it online or verify all test cases.

**Explanation:**

```
¥        # Get deltas / forward-difference of the (implicit) input-pair
 «       # Merge it to the (implicit) input-pair
  Ä      # Take the absolute value of each
   Z     # Push the maximum of this list (without popping)
    s    # Swap so the list is at the top of the stack again
     c   # Choose; get the binomial coefficient of each value with this maximum
      à  # And pop and push the maximum of those result
         # (after which it is output implicitly)

```

# Answer
> 0 votes
# Io, 79 bytes

Port of most answers.

```
method(a,b,list(2,0)map(i,list(a,b,a-b)map(abs)sort at(i))reduce(combinations))

```

Try it online!

---
Tags: code-golf, hexagonal-grid, complex-numbers
---


# Question
Title: Counting Queen's paths on a rectangular chessboard
## Task

Given two positive integers \\$m,n\\$, imagine a chessboard of size \\$m \times n\\$. A chess queen is on the upper-left corner. In how many ways can it reach the lower-right corner, by moving only right, down, or diagonally right-down (possibly moving many steps at once, because it's a queen)?

The resulting 2D sequence is A132439.

Standard rules apply. The shortest code in bytes wins.

## Test cases

```
m n result
1 1      1
1 2      1
1 3      2
1 4      4
1 5      8
2 2      3
2 3      7
2 4     17
2 5     40
3 3     22
3 4     60
3 5    158
4 4    188
4 5    543
5 5   1712

```

# Answer
> 6 votes
# Haskell, ~~94~~ ~~91~~ ~~64~~ 54 bytes

```
1!1=1;m!n=sum[m!(n-x)+(m-x)!n+(m-x)!(n-x)|x<-[1..m+n]]

```

Try it online!

Initially a boring port of the comment on OEIS

-27 from some tricks off dingledooper's answer

-10 from Christian Sievers

# Answer
> 6 votes
# Python 2, 75 bytes

@xnor's idea which is 2 bytes smaller than the one below. Returns `True` for `1 1`.

```
f=lambda m,n:sum(f(m-i,n)+f(m,n-i)+f(m-i,n-i)for i in range(1,n|m))or m>0<n

```

Try it online!

---

# Python 2, ~~79~~ 77 bytes

```
f=lambda m,n:(m==n==1)+sum(f(m-i,n)+f(m,n-i)+f(m-i,n-i)for i in range(1,n+m))

```

Try it online!

# Answer
> 5 votes
# K (ngn/k), 36 bytes

```
{(x~1 1)+/o'x-/:{|/'~x,'-/'x}#1_+!x}

```

Try it online!

`!x` odometer

`+` transpose

`1_` drop the first

`{` `}#` filter

`|/'~x,'-/'x` either element or their difference is 0

`x-/:` subtract each right

`o'` recur each

`+/` sum

`(x~1 1)` does `x` match `1 1`? use as initial value for the sum

# Answer
> 3 votes
# Erlang (escript), 92 bytes

Boring port of the Haskell answer.

```
f(1,1)->1;f(M,N)->lists:sum([f(M,N-X)+f(M-X,N)+f(M-X,N-X)||X<-lists:seq(1,max(M,N)),M*N>0]).

```

Try it online!

# Answer
> 1 votes
# Charcoal, 40 bytes

```
ＮθＦＮＦθ⊞υ∨¬υΣΦυ∨∨⁼ι÷μθ⁼κ﹪μθ⁼⁻ικ⁻÷μθ﹪μθＩ⊟υ

```

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

```
Ｎθ

```

Input the number of columns.

```
ＦＮ

```

Loop over the rows.

```
Ｆθ

```

Loop over each column.

```
⊞υ∨¬υ

```

The first result is always `1`...

```
ΣΦυ∨∨⁼ι÷μθ⁼κ﹪μθ⁼⁻ικ⁻÷μθ﹪μθ

```

... otherwise find the existing results that are a Queen's move away, take the total, and push that to the list of results. The list therefore simulates a matrix, requiring its index to be divided or taken modulo the number of columns as appropriate to compare with the loop variables.

```
Ｉ⊟υ

```

Output the last result calculated.

# Answer
> 1 votes
# , 60 50 bytes

```
_2{(],1#.]#~(#:#)(0=*/*-/)@:-"1(#:i.@#))^:(*/@[)&1

```

Try it online!

---
Tags: code-golf, grid, chess
---


title: Alphabet Histogram

text:
# Question
Title: Alphabet Histogram
Given an input sentence consisting of one or more words `[a-z]+` and zero or more spaces , output an ASCII-art histogram (bar graph) of the letter distribution of the input sentence.

The histogram must be laid out horizontally, i.e. with the letter key along the bottom in alphabetical order from left to right, with a Y-axis labeled `1-` and every 5 units. The Y-axis must be the smallest multiple of five that is at least as tall as the tallest bar, and must be right-aligned. The X-axis is labeled with the input letters, with no gaps between. For example, input `a bb dd` should have label `abd` and not `ab d`, skipping the `c`. The bars themselves can be made of any consistent ASCII character -- I'll be using `X` here in my examples.

```
test example

5-

   X
   X   X
1-XXXXXXXX
  aelmpstx

```

Since there are three `e`, two `t`, and one of `almsx`.

**More examples:**

```
the quick brown fox jumped over the lazy dogs

5-
      X         X
      X         X
     XX  X      X  X XX
1-XXXXXXXXXXXXXXXXXXXXXXXXXX
  abcdefghijklmnopqrstuvwxyz

now is the time for all good men to come to the aid of their country

10-
              X
              X
              X  X
      X       X  X
 5-   X       X  X
      X   X   X  X
      X  XX XXXX X
   XXXXX XXXXXXX X
 1-XXXXXXXXXXXXXXXXXX
   acdefghilmnorstuwy

a bb ccc dddddddddddd

15-

      X
      X
10-   X
      X
      X
      X
      X
 5-   X
      X
     XX
    XXX
 1-XXXX
   abcd

a bb ccccc

5-  X
    X
    X
   XX
1-XXX
  abc

```

## I/O and Rules

* Input can be taken in any reasonable format and by any convenient method. This also means you can take input in all-uppercase, if that makes more sense for your code.
* Leading/trailing newlines or other whitespace are optional, provided that the characters line up appropriately.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* Output can be to the console, returned as a list of strings, returned as a single string, etc.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
# , ~~239~~ 230 bytes

```
K=table(el(strsplit(gsub(" ","",scan(,"")),"")));m=matrix(" ",L<-sum(K|1)+1,M<-(M=max(K))+-M%%5+1);m[2:L,M]=names(K);m[1,M-g]=paste0(g<-c(1,seq(5,M,5)),"-");m[1,]=format(m[1,],j="r");for(X in 2:L)m[X,M-1:K[X-1]]=0;write(m,1,L,,"")

```

Try it online!

`table` does the heavy lifting here, uniquifying the characters, sorting them, and returning their counts.

Everything else is just ensuring the offsets are right for printing, which is the "real" work of an ascii-art challenge.

Thanks to @dylnan for pointing out a bug.

Thanks to @rturnbull for the `scan` approach, dropping 2 bytes.
> 7 votes

# Answer
# Stax, 37 bytes

```
ü╣úwóΓµ┐Wh0íJ▌Ñìs┤►ï╖öz<à↔/Ü@τ|:╢Ω$‼φ

```

Run and debug it
> 7 votes

# Answer
# Dyalog APL, ~~109~~ ~~97~~ ~~96~~ ~~95~~ ~~93~~ 88 bytes

```
{⊖(⍉r),⍨⍕↑(⊂'')@{1@0~⍵∊1,5×⍵}⍳≢⍉↑r←↑r,⍨⊂' -','   - '⍴⍨5×⌈5÷⍨≢1↓⍉↑r←↓{⍺,∊⍕¨0×⍵}⌸⍵[⍋⍵]∩⎕A}

```

Try it online!

Requires `⎕IO←0`

*Way* too many bytes saved thanks to Adám and Cows quack!
> 6 votes

# Answer
# 05AB1E, ~~58~~ 47 bytes

```
áê©S¢Z5‰`Ā+L5*1¸ì'-«ð5×ý#À¦Áí.Bís'X×ζ‚ζJR»,®3ú,

```

Try it online!

-11 bytes thanks to @Emigna
> 6 votes

# Answer
# gnu sed -r, ~~516~~ ~~490~~ ~~278~~ 249 + 1 bytes

```
s/$/:ABCDEFGHIJKLMNOPQRSTUVWXYZ /
:a
s/(.)(:.*\1)/\2\1/I
ta
s/[A-Z]+/ /g
h
z
:b
s/ \w/ /g
G
s/:/&I/g
/:II{5}+ *$/M!bb
s/[a-z]/X/g
G
s/:(I{5}+|I)\b/0\1-/g
s/:I*/  /g
s/ (\w)\1*/\1/g
s/$/; 10123456789I0/
:c
s/(.)I(.*\1(I?.))|;.*/\3\2/
/\nI/s/^/ /Mg
tc

```

Try it online!

---

I am sure this can be improved~~, but for now, this should be good considering it is made in sed, where you don't have native arithmetic or sorting.~~ So I lied, this wasn't good enough, so I improved (rewrote) it by another 212 bytes, with a tip regarding the sorting algorithm from Cows quack, which gave me a idea to make the unary to decimal conversion shorter too.
Description of inner workings:

```
s/$/:ABCDEFGHIJKLMNOPQRSTUVWXYZ /
:a
s/(.)(:.*\1)/\2\1/I
ta
s/[A-Z]+/ /g
h
z

```

This sorts the input and separates the groups with spaces. This works by first appending an uppercase alphabet plus space separated by a colon to the end. Then it moves each character in front of the colon to a matching character behind the colon using a case-insensitive substitution in a loop. The uppercase letters are then replaced by spaces and the string is copied to the holding space.

```
:b
s/ \w/ /g
G
s/:/&I/g
/:II{5}+ *$/M!bb

```

This loop works by reducing each character group size by one, appending the sorted original line and incrementing unary counters after the colon that remained from the sorting. It loops until an empty line with a number of 5\*n + 1 is reached (since the last line ultimately results in whitespace). The pattern space looks something like this after the loop:

```
:IIIIII
:IIIII
:IIII
:III  e
:II  ee     t
:I a eee l m p s tt x

```

Then the formatting follows:

```
s/[a-z]/X/g            # makes bars consistent
G                      # appends line that becomes x-axis
s/:(I{5}+|I)\b/0\1-/g  # moves zero in front of line 1 or 5-divisible
                       # lines for the decimal conversion and adds -
s/:I*/  /g             # removes numbers from other lines
s/ (\w)\1*/\1/g        # collapses groups of at least 1 into 1
                       # character, deleting the space before it
                       # so that only size-0-groups have spaces

```

And finally, the unary to decimal converter remains:

```
s/$/; 10123456789I0/
:c
s/(.)I(.*\1(I?.))|;.*/\3\2/
/\nI/s/^/ /Mg
tc

```

It basically appends a string where the knowledge of conversion is. You can interprete it as :space:-\>1 and 0-\>1-\>2-\>3-\>4-\>5-\>6-\>7-\>8-\>9-\>I0. The substitution expression `s/(.)I(.*\1(I?.))|;.*/\3\2/` works similar to the sorting one, replacing the characters in front of I's \[ `(.)I` \] by the character that is next to the one from the front of the I in the conversion string \[ `(.*\1(I?.))` \] and if there is no I left, it removes the appended string \[ `|;.*` \]. The substitution \[ `/\nI/s/^/ /Mg` \] adds padding if needed.

Thanks to Cows quack for reducing the size by 26 bytes and for the shorter sorting algorithm.
> 6 votes

# Answer
# Python 2, 192 bytes

```
s=input()
d={c:s.count(c)for c in s if' '<c}
h=-max(d.values())/5*-5
for y in range(h,-1,-1):print('%d-'%y*(y%5==2>>y)).rjust(len(`-h`))+''.join(('X '[y>v],k)[y<1]for k,v in sorted(d.items()))

```

Try it online!

## Explanation

Line 2 computes the histogram values in a fairly straightforward way, discarding `' '`.

Line 3 uses the trick of computing `ceil(x/5)` as `-(-x/5)`: we round the maximal frequency up to the next multiple of 5 using the formula `-x/5*-5`. This is `h`.

Line 4 is a loop counting from `h` down to `0` inclusive, printing each row:

* If `y%5==2>>y` we print a label. This is when `y` ∈ {1, 5, 10, 15, 20, …}

(This formula could maybe be shorter. We just need something that's **1** or **True** for {1, 5, 10, …}, and **0** or **False** or even a negative integer for all other values of `y`.)
* We right-justify the label (or empty space) into `len(`-h`)` spaces: this is a neat one-byte saving over `len(`h`)+1`!
* Then, we print either `X`'s and spaces for this row (if `y` ≥ 1) or the letters (if `y` = 0), running through key-value pairs in `d` in ascending order.
> 3 votes

# Answer
# Pyth, 65 bytes

```
J.tm+ed*hd\Xr8S-Qd)=+J*]d%_tlJ5_.e+?q<k2%k5.F"{:{}d}-",klQ*dhlQbJ

```

Try it here

### Explanation

```
J.tm+ed*hd\Xr8S-Qd)=+J*]d%_tlJ5_.e+?q<k2%k5.F"{:{}d}-",klQ*dhlQbJ
J.tm+ed*hd\Xr8S-Qd)
     Get the bars.
                   =+J*]d%_tlJ5
     Round up the height to the next number that's 1 mod 5.
                               _.e+?q<k2%k5.F"{:{}d}-",klQ*dhlQbJ
     Stick the axis labels on.

```
> 2 votes

# Answer
# Charcoal, 62 bytes

```
≔Ｅ²⁷⟦⟧ηＦθ⊞§η⌕βιι≔⊟ηθ≦ＬηＰ⭆β⎇§ηκιω↑↑ΦηιＦ÷⁺⁹⌈η⁵«≔∨×⁵ι¹ιＪ±¹±ι←⮌⁺ι-

```

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

```
≔Ｅ²⁷⟦⟧η

```

Create a list of 27 lists.

```
Ｆθ⊞§η⌕βιι

```

Push each input character to the list corresponding to its position in the lowercase alphabet. Non-lowercase characters get pushed to the 27th list.

```
≔⊟ηθ

```

Discard the 27th element of the list.

```
≦Ｌη

```

Take the lengths of all the elements of the list.

```
Ｐ⭆β⎇§ηκιω

```

Print the lowercase letters corresponding to non-zero list elements.

```
↑↑Φηι

```

Print the non-zero list elements upwards. Since this is an array of integers, each integer prints as a (now vertical) line, each in a separate column.

```
Ｆ÷⁺⁹⌈η⁵«

```

Calculate the number of tick marks on the Y-axis and loop over them.

```
≔∨×⁵ι¹ι

```

Calculate the position of the next tick mark.

```
Ｊ±¹±ι

```

Jump to the next tickmark.

```
←⮌⁺ι-

```

Print the tickmark reversed and back-to-front, effectively right-aligning it.
> 2 votes

# Answer
# Jelly, 48 bytes

What a mine-field to traverse!

```
J’⁶D;”-Ɗ%5^ỊƲ?€Uz⁶ZU
ḟ⁶ṢµĠ¬;⁶$L%5Ɗ¿€;"@Qz⁶Ç;"$ṚY

```

A full-program printing the result (as a monadic link it would return a list containing characters and integers from `[0,9]`)

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

### How?

```
J’⁶D;”-Ɗ%5^ỊƲ?€Uz⁶ZU - Link 1, get y-axis: list of columns (including x-axis & top-spaces)
J                    - range of length  [1,2,3,4,5,6,...,height+1] (+1 for x-axis)
 ’                   - decrement        [0,1,2,3,4,5,...] (line it up with the content)
             ?€      - if for €ach...
            Ʋ        - ...condition: last four links as a monad:
        %5           -   modulo by five
           Ị         -   insignificant? (1 for 0 and 1, else 0)
          ^          -   XOR (0 for 1 or multiples of 5 greater than 0, else 0)
  ⁶                  - ...then: literal space character
       Ɗ             - ...else: last three links as a monad:
   D                 -   decimal list of the number, e.g. 10 -> [1,0]
     ”-              -   literal '-' character
    ;                -   concatenate, e.g. [1,0,'-']
               U     - upend (reverse each)
                z⁶   - transpose with a filler of space characters
                  Z  - transpose
                   U - upend (i.e. Uz⁶ZU pads the left with spaces as needed)

ḟ⁶ṢµĠ¬;⁶$L%5Ɗ¿€;"@Qz⁶Ç;"$ṚY - Main link: list of characters
ḟ⁶                          - filter out space characters
  Ṣ                         - sort
   µ                        - start a new monadic chain, call that S
    Ġ                       - group indices of S by their values
     ¬                      - logical NOT (vectorises) (getting 0 for the X "characters")
             ¿€             - while for €ach...
            Ɗ               - ...condition: last three links as a monad:
         L                  -   length
          %5                -   modulo by five
        $                   - ...do: last two links as a monad:
      ;⁶                    -   concatenate a space character
                  Q         - deduplicate S (get the x-axis)
               ;"@          - zip with (") concatenation (;) with swapped arguments (@)
                   z⁶       - transpose a with filler of space characters
                        $   - last two links as a monad:
                     Ç      -   call last link (1) as a monad (get y-axis)
                      ;"    -   zip with concatenation (complete the layout)
                         Ṛ  - reverse (otherwise it'll be upside-down)
                          Y - join with newlines
                            - implicit print

```
> 2 votes

# Answer
# Java (JDK), 295 bytes

```
s->{int d[]=new int[26],m=0;char a;for(int c:s.getBytes())m=c>32&&++d[c-=65]>m?(d[c]+4)/5*5:m;String r=m+"-",z=r.replaceAll("."," ");for(;m>0;r+="\n"+(--m%5>0&m!=1|m<1?z:z.format("%"+~-z.length()+"s-",m)))for(a=0;a<26;a++)r+=d[a]>0?m>d[a]?" ":"x":"";for(a=64;a++<90;)r+=d[a-65]>0?a:"";return r;}

```

Try it online!

## Credits
> 2 votes

# Answer
# Ruby, ~~250~~ ~~248~~ ~~234~~ ~~188~~ ~~173~~ ~~157~~ 153 bytes

```
->s{a=s.scan(/\w/).sort|[]
m=-(c=a.map{|l|s.count l}).max/5*-5
m.downto(1).map{|i|(i%5<1||i<2?"#{i}-":'').rjust(m)+c.map{|l|l<i ?' ':?X}*''}<<' '*m+a*''}

```

Try it online!

Thanks to:

* dylnan for -16 bytes with less strict padding
* Lynn for -2 bytes by rounding up with `-x/5*-5`
* Kirill L. for -2 bytes by getting unique array elements with `|[]`
> 2 votes

# Answer
# APL (Dyalog Classic), 56 bytes

```
⊖h,⍨{∊⍺'-'/⍨~×5|⍵-⍵<2}⌸⍕⍪⍳≢h←(⊢↑⍨≢+5|1-≢)⍉(⊢,⌸⊣\)∊⍞∘∩¨⎕a

```

Try it online!
> 2 votes

# Answer
# JavaScript (Node.js), 262 256 bytes

\*Thanks to @Shaggy for reducing by 2 bytes

```
a=>[...a].map(x=>x>" "&&(d=c[x]=(c[x]||x)+"X")[m]?m=d.length-1:0,c={},m=i=0)&&Object.keys(c).sort().map(x=>[...c[x].padEnd(m)].map((l,j)=>A[m-j-1]+=l),A=[...Array(m+=6-m%5)].map(x=>(++i>=m||((D=m-i)%5&&m-i^1)?"":D+"-").padStart((m+" ").length)))&&A.join`
`

```

Try it online!
> 1 votes

# Answer
# Python 2, ~~249~~ ~~224~~ ~~219~~ ~~215~~ ~~205~~ ~~197~~ ~~187~~ ~~188~~ ~~182~~ 176 bytes

```
def f(s):S=sorted(set(s)^{' '});C=map(s.count,S);P=max(C)+4;return zip(*(zip(*[('%d-'%y*(y%5==2>>y)).rjust(P)for y in range(P,0,-1)])+[(n*'#').rjust(P)for n in C]))+[[' ']*P+S]

```

Try it online!

Returns a list of lists of characters representing lines.

* Saved some bytes by including a lot of extra whitespace.
* Had an unnecessary `map(list,yticks)` in there.
* Changed space padding to save some bytes.
* I thought I was sorting but I was not: +2 bytes. But I saved one independently at the same time. `y==1` replaced by `y<2`.
* -6 bytes thanks to Lynn by using `'%d-'%y*(y%5==2>>y)` instead of `(`y`+'-')*(not y%5or y<2)`.

Slightly ungolfed:

```
def f(s):
	S=sorted(set(s)^{' '})  # sorted list of unique letters (without ' ')
	C=map(s.count,S)        # count of each unique letter in the input
	P=max(C)+4              # used for padding and getting highest y tick
	B=[(n*'#').rjust(P)for n in C]     # create bars
	yticks = [('%d-'%y*(y%5==2>>y)).rjust(P)for y in range(P,0,-1)]  # create y ticks at 1 and multiples of 5
	yticks = zip(*yticks)                      # need y ticks as columns before combining with bars
	return zip(*(yticks+B))+[[' ']*P+S]        # zip ticks+bars then add row of sorted unique letters.

```
> 1 votes

# Answer
# C# (.NET Core), ~~344~~ ~~340~~ 338 + 18 bytes

Includes 18 bytes for `using System.Linq;`

Saved 6 bytes thanks to @KevinCruijssen.

```
n=>{var l=n.Where(c=>c!=32).GroupBy(c=>c).OrderBy(c=>c.Key).ToDictionary(k=>k.Key,c=>c.Count());int h=(l.Values.Max()/5+1)*5,o=(h+"").Length+1,m=l.Keys.Count+o,t=h+1,i=0,j;var a=new string[t];for(string p,q;i<t;a[i++]=q)for(q=(p=i>0&i%5<1|i==1?i+"-":"").PadLeft(j=o);j<m;){var c=l.ElementAt(j++-o).Key;q+=i<1?c:l[c]>=i?'X':' ';}return a;}

```

Try it online!
> 1 votes

# Answer
# Bash \+ coreutils, 332 324 323 318 312 302 298 296 293 291 bytes

```
c()(cut -d\  -f$@)
p=printf
cd `mktemp -d`
grep -o [^\ ]<<<$@|sort|uniq -c|c 7->a
sort -k2<a>b
r=$[`c 1 <a|sort -n|tail -1`+5]
s=${#r}
t()($p \ ;((i++<s))&&t;i=)
for((;--r;));{
((r%5&&r>1))&&t||$p %${s}s- $r;IFS='
'
for l in `<b`;{ ((r<=`c 1 <<<$l`))&&$p X||$p \ ;}
echo
}
t
c 2 <b|tr -d \\n

```

Try it online!

Annotated:

```
c()(cut -d\  -f$@)
p=printf              # saving a few bytes

cd `mktemp -d`        # for temp files

grep -o [^\ ]<<<$@    # grabs all non-space characters
    |sort|uniq -c     # get character frequency
    |c 7->a           # slightly hacky way of stripping leading spaces;
                      #     uniq -c adds 6 spaces in front of each line

sort -k2<a>b          # store frequencies sorted alphabetically in b

r=$[`                 # r = highest frequency +5:
    c 1 <a            #     get frequencies
    |sort -n|tail -1  #     get maximum frequency
    `+5]              #     +4 so at least one multiple of 5 is
                      #     labeled, +1 because r gets pre-decremented

s=${#r}                    # s = length of r as a string
t()($p \ ;((i++<s))&&t;i=) # pad line with s+1 spaces

for((;--r;));{         # while (--r != 0)
    ((r%5&&r>1))&&     # if r isn't 1 or a multiple of 5
        t||            #     then indent line
        $p %${s}s- $r; # otherwise print right-aligned "${r}-"
        IFS='
'                      # newline field separator
    for l in `<b`;{          # for all letters and their frequencies:
        ((r<=`c 1 <<<$l`))&& #     if frequency <= current height
            $p X||           #         then print an X
            $p \ ;}          #     otherwise print a space
    echo
}
t # indent x-axis labels
c 2 <b|tr -d \\n # print alphabetically sorted characters

```

Thanks to @IanM\_Matrix for saving 3 bytes.
> 1 votes

# Answer
# C, 201 bytes

```
char c[256],*p,d;main(int a,char **b){for(p=b[1];*p;p++)++c[*p|32]>d&*p>64?d++:0;for(a=(d+4)/5*5;a+1;a--){printf(!a||a%5&&a!=1?"    ":"%3i-",a);for(d=96;++d>0;c[d]?putchar(a?32|c[d]>=a:d):0);puts(p);}}

```

Input is taken from the command line (first argument). Uses exclamation marks instead of X's to further reduce code size. Counter on the left is always three characters long.

Tested with GCC and clang.
> 0 votes

# Answer
# JavaScript (ES8), 200 bytes

Takes input as an array of characters. Returns a string.

```
s=>(s.sort().join``.replace(/(\w)\1*/g,s=>a.push(s[0]+'X'.repeat(l=s.length,h=h<l?l:h)),h=a=[]),g=y=>y--?(y<2^y%5?'':y+'-').padStart(`${h}_`.length)+a.map(r=>r[y]||' ').join``+`
`+g(y):'')(h+=5-~-h%5)

```

Try it online!

### Commented

```
s => (                    // s[] = input array of characters (e.g. ['a','b','a','c','a'])
  s.sort()                // sort it in lexicographical order (--> ['a','a','a','b','c'])
  .join``                 // join it (--> 'aaabc')
  .replace(/(\w)\1*/g,    // for each run s of consecutive identical letters (e.g. 'aaa'):
    s => a.push(          //   push in a[]:
      s[0] +              //     the letter, which will appear on the X-axis
      'X'.repeat(         //     followed by 'X' repeated L times
        L = s.length,     //     where L is the length of the run (--> 'aXXX')
        h = h < L ? L : h //     keep track of h = highest value of L
    )),                   //   initialization:
    h = a = []            //     h = a = empty array (h is coerced to 0)
  ),                      // end of replace() (--> a = ['aXXX','bX','cX'] and h = 3)
  g = y =>                // g = recursive function taking y
    y-- ?                 //   decrement y; if there's still a row to process:
      (                   //     build the label for the Y-axis:
        y < 2 ^ y % 5 ?   //       if y != 1 and (y mod 5 != 0 or y = 0):
          ''              //         use an empty label
        :                 //       else:
          y + '-'         //         use a mark
      ).padStart(         //     pad the label with leading spaces,
        `${h}_`.length    //     using the length of the highest possible value of y
      ) +                 //     (padStart() is defined in ECMAScript 2017, aka ES8)
      a.map(r => r[y]     //     append the row,
                 || ' ')  //     padded with spaces when needed
      .join`` + `\n` +    //     join it and append a linefeed
      g(y)                //     append the result of a recursive call
    :                     //   else:
      ''                  //     stop recursion
)(h += 5 - ~-h % 5)       // call g() with h adjusted to the next multiple of 5 + 1

```
> 0 votes

# Answer
# Excel VBA, 316 bytes

An Anonymous VBE immediate window function that takes input from cell `[A1]` and outputs to the VBE immediate window.

```
For i=1To 26:Cells(2,i)=Len(Replace([Upper(A1)],Chr(i+64),11))-[Len(A1)]:Next:m=-5*Int(-[Max(2:2)]/5):l=Len(m)+1:For i=-m To-1:?Right(Space(l) &IIf(i=-1Xor i Mod 5,"",-i &"-"),l);:For j=1To 26:?IIf(Cells(2,j),IIf(Cells(2, j) >= -i, "X", " "),"");:Next:?:Next:?Spc(l);:For i=1To 26:?IIf(Cells(2,i),Chr(i+96),"");:Next

```

### Ungolfed Version

```
Public Sub bar_graph()
    For i = 1 To 26
        ''  gather the count of the letter into cells
        Cells(2, i) = Len(Replace([Upper(A1)], Chr(i + 64), 11)) - [Len(A1)]
    Next
    m = -5 * Int(-[Max(2:2)] / 5)   ''  get max bar height
    l = Len(m) + 1                  ''  length of `m` + 1
    For i = -m To -1
        ''  print either a label or free space (y-axis)
        Debug.Print Right(Space(l) & IIf((i = -1) Xor i Mod 5, "", -i & "-"), l);
        For j = 1 To 26
            ''  print 'X' or ' ' IFF the count of the letter is positive
            If Cells(2, j) Then Debug.Print IIf(Cells(2, j) >= -i, "X", " ");
        Next
        Debug.Print                 ''  print a newline
    Next
    Debug.Print Spc(l);             ''  print spaces
    For i = 1 To 26
        ''  print the letters that were used (x-axis)
        Debug.Print IIf(Cells(2, i), Chr(i + 96), "");
    Next
End Sub

```
> 0 votes

# Answer
# Perl 5 `-n`, ~~198~~ 168 bytes

```
s/[a-z]/$\<++${$&}?$\=${$&}:0/eg;$\++while$\%5;$;=1+length$\++;printf"%$;s".'%s'x26 .$/,$\%5&&$\-1?"":"$\-",map$$_>=$\?X:$$_&&$",a..z while--$\;say$"x$;,map$$_&&$_,a..z

```

Try it online!
> 0 votes

# Answer
# Python 3, 177 bytes

```
lambda s:[[list(("%d-"%i*(i%5==2>>i)).rjust(len(q)))+["* "[s.count(c)<i]for c in q]for i in range(max(map(s.count,q))+4,0,-1)]+[[" "]*len(q)+q]for q in[sorted(set(s)-{' '})]][0]

```

Try it online!

This may not be the most byte-efficient approach in Python, but I really wanted to solve this with a "true one-liner" lambda.

Outputs a list of character lists. Abuses multiple leading newlines and spaces just like everybody else. It may actually be further reduced to 174 bytes if it is acceptable to wrap the result in another list, so that we could transfer the final `[0]` indexing to the footer.
> 0 votes

# Answer
# PHP, 180 bytes

```
$c=count_chars($argn,1);unset($c[32]);for($s=max($c)+4;$s;){printf($s%5&&$s>1?$z='   ':'%2d-',$s--);foreach($c as$d)echo$d>$s?X:' ';echo"
";}foreach($c as$a=>$d)$z.=chr($a);echo$z;

```

Try it online!
> 0 votes

---
Tags: code-golf, ascii-art, counting
---