title: Most efficient cubifier

text:
# Question
Title: Most efficient cubifier
Cubically is too tedious to manually write any code in. Your challenge is to translate ASCII text into Cubically source code.

# Cubically

This is just a quick run-down of Cubically; the repository has a more complete guide and details.

Cubically is an esolang I wrote a while ago, designed to be painful to use. It contains two pieces of memory, a 3x3x3 Rubik's Cube and a register called the "notepad".

### Memory

The internal Rubik's Cube is initialized like this:

```
   000
   000          top face
   000
111222333444    left, front, right, and back faces, respectively
111222333444
111222333444
   555
   555          down face
   555

```

After performing a clockwise 90° turn on the right face, the memory cube would look like this:

```
   002
   002
   002
111225333044
111225333044
111225333044
   554
   554
   554

```

### Commands

A non-integer character sets the default command. For each integer before the default command is set once again, the command is performed with that integer. For example, `x524y312` would perform command `x` with 5, then with 2, then with 4, then perform command `y` with 3, then with 1, then with 2.

The integers that commands use represent face indexes. So `x0` would perform `x` on the UP (0-indexed) face. `x1` would perform `x` on the LEFT (1-indexed) face, and so on.

Performing any command with `6` will perform that command on the notepad value. Performing any command with any integer over 6 will result in an error.

Here are some example commands:

* `R1` \- turn the RIGHT face clockwise 90° so the internal cube will look like the second example above
* `R11` \- turn the RIGHT face clockwise 90° twice, identical to `R2`
* `+0` \- add all values of the UP face to the notepad
* `+000` \- add all values of the UP face to the notepad three times
* `@6` \- print the nonexistent 6th-indexed face (memory) as a character
* `%4` \- print the sum of all values on the BACK face as an integer

A complete list of commands and syntax is available at the repository.

# Challenge

You will take ASCII text as input and print a Cubically program as output.

Examples (stolen from here and here):

```
Input -> Output
Hello, World! -> +53@6+1F2L2+0@6L2F2U3R3F1L1+2@66L3F3R1U1B3+0@6:4U1R1+00@6-000@6*0-4+000@6-00@6+2-000000@6-5+4000@6-00@6/0+00@6:0+0/0+00@6
1$2$3$4$5$6$7$8$9$10$ -> B1+2/2%6@4+00/0%6@4+00/1%6@4+21/1%6@4+30/0%6@4+22/1%6@4+22/1%6@4+40/1%6@4+52/1%6@4+42/1%6@4

```

# Rules

* Your program may not contain a dictionary containing the translations for the 100 testcases.
* Your program must finish in less than 180 seconds (no brute-force programs that take weeks).
* Your program must output valid Cubically code that finishes in less than 180 seconds.
* Your program will take input via standard input, unless you want to mess with the test driver.
* Your program must output Cubically code that produces nothing but your program's input when run. ಠ\_ಠ

# Scoring

You will test your program with 100 pseudorandom strings of pseudorandom length. (A bash script is provided that will do this for you.) Here is how you will score:

* Let the length of the output program be **o**.
* Let the length of the input string be **l**.
* Let a variable **r** be the result of **o/l**.
* Find the average of all **r**: **(r1 \+ r2 \+ r... \+ r100) / 100**.

Test with this script. You'll have to modify it as instructed. Note that the program does not check whether the output is valid Cubically code. If you can't get the script working, I can help. Ping me in the Cubically chat room.

# Answer
> 5 votes
# C++11, Score: 6.37

```
#include <iostream>
#include <vector>
#include <array>
#include <limits>
#include <algorithm>

const int inf = std::numeric_limits<int>::max(),
maxDiff = 128, nFace = 6;
std::array<int, maxDiff+1> plusvalue, totalvalue, plustrace, totaltrace;
std::array<int, nFace> input;

void prtrace(int value) {
    while (value) {
        std::cout << plustrace[value];
        value -= input[plustrace[value]];
    }
}

void prexpr(int i) {
    char xorwt = 0;
    if (i < 0) {
        xorwt = '+' ^ '-';
        i = -i;
    }
    if (totalvalue[i] != 0 && totalvalue[i] != inf) {
        std::cout << (char)('+' xor xorwt);
        prtrace(totaltrace[i]);
        if (totaltrace[i] != i) {
            std::cout << (char)('-' xor xorwt);
            prtrace(totaltrace[i] - i);
        }
    }
}

int main() {
    std::cout << "RU";
    input = {6, 15, 27, 26, 19, 42};
    std::cin >> std::noskipws;

    std::fill(plusvalue.begin(), plusvalue.end(), inf);
    plusvalue[0] = 1; // '+'
    for (int i = 0; i < nFace; ++i) { // knapsack, each value repeated inf times
        int val = input[i];
        if (val == 0) continue;
        for (int p = 0; p <= maxDiff - val; ++p) {
            if (plusvalue[p] != inf && plusvalue[p + val] > plusvalue[p] + 1) {
                plusvalue[p + val] = plusvalue[p] + 1;
                plustrace[p + val] = i;
            }
        }
    }
    for (int p = 0; p <= maxDiff; ++p) totalvalue[p] = plusvalue[p], totaltrace[p] = p;
    totalvalue[0] = 0;
    for (int sub = 1; sub <= maxDiff; ++sub) {
        if (plusvalue[sub] == inf) continue;
        for (int p = 0; p <= maxDiff - sub; ++p) {
            if (plusvalue[p+sub] != inf && totalvalue[p] > plusvalue[p+sub] + plusvalue[sub]) { // include '+'s
                totalvalue[p] = plusvalue[p+sub] + plusvalue[sub];
                totaltrace[p] = p+sub;
            }
        }
    }

//    // Note: plustrace[x] = i<=nFace : plustrace[x-input[i]] + 1 = plustrace[x]
//    long long sum = 0;
//    for (int i = 0; i <= maxDiff; ++i) {
//        sum += totalvalue[i];
//        std::cout << i << '\t' << totalvalue[i] << '\t';
//        prexpr(i);
//        std::cout << '\n';
//    }
//
//    std::cout << "_______________________________\n\nAverage = " << sum / (maxDiff + 1.) << '\n';

// RU 3.98131

    char ch;
    int cur = 0;
    while (std::cin >> ch) {
        int diff = ch - cur;
        prexpr(diff);
        std::cout << "@6";
        cur += diff; // cur = ch
    }
}

/*
RU 3.98131
*/

```

Try it online! (generate Cubically code from ASCII) and (run Cubically code)

Explanation:

* First the program prints "RU", which make the face sum from `{0,9,18,27,36,45}` to `{6, 15, 27, 26, 19, 42}`. What makes that face sum set useful is that the gcd is 1, so by Bézout's identity there exist a way to construct any number `d` from a sum (or difference) of those numbers.
* Therefore, if the next char is `ch` and the current notepad value is `n`, then let `d = ch - n`, we can execute Cubically commands in the form `+{digits from 0 to 5}-{digits from 0 to 5}` such that the notepad value becomes `ch`. Then just execute `%6` to print notepad value.
* To find the most efficient way to express `d` as a sum/difference of numbers in the face sum set, I use Knapsack algorithm for all numbers from 0 to 128. E.g., for `d=1`, the program gets `27 - 26 = 1`, so it prints `+2-3`, which is `27 - 26 = 1`. Which can be seen when run the program with input `abc`, the program output
> RU+4333@6**+2-3**@6**+2-3**@6

# Answer
> 17 votes
# Lua, Score: ~~85.91~~ ~~13.50~~ ~~13.20~~ ~~12.70~~ ~~9.41~~ ~~9.32~~ ~~9.83~~ ~~9.66~~ ~~9.12~~ ~~9.06~~ 8.03 (Average)

```
-- Get input
local inp = io.read("*a")

local out = ""
local faces = { [5] = 45, [4] = 36, [3] = 27, [2] = 18, [1] = 9 }
local lastChar = nil

-- Mode the program is in
-- 2 = not set (needs :), 1 = just set (needs +), 0 = normal
local mode = 1;
for i = 1, inp:len() do
  -- Character value at current position
  local c = string.byte(inp, i)

  if c == lastChar then
    -- Repeat character
    out = out .. "6"
  elseif c % 9 == 0 and c <= 45 then
    if #out == 0 then
      out = out .. "@"
    end
    out = out .. (c / 9)
  else
    local c2 = c

    -- Handle if difference from lastChar is divisible by 9
    if lastChar and (c - lastChar) % 9 == 0 then
      local difference = c - lastChar
      if difference > 0 then
        out = out .. "+"
      else
        out = out .. "-"
        difference = difference * -1
      end

      for index = 5, 1, -1 do
        local face = faces[index]
        while difference >= face do
          difference = difference - face
          out = out .. index
        end
      end
      c = 0
    end

    -- Handle anything not divisible by 9
    local extra = c % 9
    if extra > 0 then
      -- Try to optimize by dividing by 9, if possible
      if lastChar and math.floor(lastChar / 9) == extra then
        out = out .. "/1"
        mode = 1
        extra = 0
      else
        while extra > 0 do
          local n = extra > 5 and 5 or extra

          if mode == 2 then
            out = out .. ":"
            mode = 1
          elseif mode == 1 then
            out = out .. "+"
            mode = 0
          end
          out = out .. n
          extra = extra - n
        end
        out = out .. "/1"
        mode = 1
      end

      c = c - (c % 9)
    end

    -- Handle anything divisible by 9
    for index = 5, 1, -1 do
      local face = faces[index]
      while c >= face do
        if mode == 2 then
          out = out .. ":"
          mode = 1
        elseif mode == 1 then
          out = out .. "+"
          mode = 0
        end
        c = c - face
        out = out .. index
      end
    end

    out = out .. "@6"
    lastChar = c2
  end

  mode = 2
end
print(out)

```

Try it online!

Okay, I don't think I can optimize this anymore.

This version iterates through each character, adding c % 9 (where c is the character's decimal value) by doing `:5+2/1`, then adds the parts divisible by 9 by adding that face's value. For example: `:2/1+551@` to print "e", where `:2/1` adds 2, `+551` adds 99 (9 * (5 + 5 + 1), or 9 * 11), and `@` prints the output. Input is read with `io.read()`.

Optimizations include directly adding/subtracting after printing if the difference between characters is a multiple of 9, dividing the current value if possible rather than setting c % 9 from scratch, and repeating characters by printing the current value again rather than recalculating it. Additionally, I've implemented Kamil's method of instantly printing any face that already contains the target value, and MD XF's suggestion to not use `:` at the beginning, but instead just start with a `+`.

# Answer
> 16 votes
# Cubically, Score: 86.98

```
U3D1R3L1F3B1U1D3~:7+1(-1@3(-1%1)6:1+3111@6%1-31111+004@6:1+11111%6:1+45@6:1-1%6~:7+1)6

```

Try it online!

Turns out, all you need is conditional loops, a face equal to 1, and consistent End-Of-Input behavior.

```
U3D1R3L1F3B1U1D3     set LEFT face sum to 1
~:7                  read input, set notepad to input
+1                   add 1 to notepad

(                    open loop that can always be jumped to
 -1                   subtract 1 from notepad
 @3                   print RIGHT face (ASCII 43 '+')

            ##   the following mechanism gets the output program's   ##
            ##   notepad to the current inputted ASCII value:        ##

 (                    open loop that can always be jumped to
  -1                   subtract 1 from notepad
  %1                   print '1'
 )6                   jump back to loop while notepad is nonzero

            ##   the following mechanism prints "/1@6:1"             ##

 :1+3111@6            set notepad to 47,    print (ASCII 47 '/')
 %1                   print LEFT face       print (integer '1')
 -31111+004@6         set notepad to 64,    print (ASCII 64 '@')
 :1+11111%6           set notepad to 6,     print (integer 6)
 :1+45@6              set notepad to 58,    print (ASCII 58 ':')
 :1-1%6               set notepad to 0,     print (integer 1)

 ~                    read input
 :7+1                 set notepad to input plus 1, so EOF changes to zero
)6                    loop if notepad is truthy

```

The adding/subtracting of the LEFT face is to get the loop to end when EOF is read.

# Answer
> 10 votes
# C# (.NET Core), Score: ~~129.98~~ ~~11.73~~ ~~10.82~~ ~~9.62~~ ~~10.33~~ ~~10.32~~ 10.20

-1.2 point from MD XF's suggestion to use `@6666...` instead of `@6@6@6@6...` for repeating character, and superior initialization sequence

```
static void Main()
{
	List<byte> input = new List<byte>();
            int inChar = Console.Read();
            while (inChar != -1)
            {
                input.Add((byte)inChar);
                inChar = Console.Read();
            }

            Console.Write("U3D1R3L1F3B1U1D3");
            byte[] sides = new byte[] { 20, 1, 14, 43, 24, 33 };

            byte currentChar = 0;

   	    if(currentChar == input[0] || sides.Contains(input[0])) Console.Write("@");

            foreach (byte character in input)
            {
		if (currentChar == character)
		{
			Console.Write("6");
			continue;
		}

		if (sides.Contains(character))
		{
			Console.Write(Array.IndexOf(sides, character));
			continue;
		}
                if (currentChar < character)
                {
                    Console.Write("+");
                    while (currentChar < character)
                    {
                        byte nextAdd = sides.Where(s => s + currentChar <= character).Max();
                        currentChar = (byte)(currentChar + nextAdd);
                        Console.Write(Array.IndexOf(sides, nextAdd));
                    }
                }

                if (currentChar > character)
                {
                    Console.Write("-");
                    while (currentChar > character)
                    {
                        byte nextSub = sides.Where(v => currentChar - v >= character).Max();
                        currentChar = (byte)(currentChar - nextSub);
                        Console.Write(Array.IndexOf(sides, nextSub));
                    }
                }

                Console.Write("@6");
            }
}

```

Try it online!

My newest version actually does some manipulation of the cube! Yay!

That first `Console.Write` up there is a fixed manipulation MD XF worked out that creates this cube:

```
   242
   202
   242
000131555313
010121535343
000131555313
   424
   454
   424

```

The significance of this cube is that one of its sides has a sum of 1, allowing manipulations of the Notepad on a smaller scale than multiples of nine, and in particular it simplifies relative movement rather than needing to start from zero each character; in this algorithm both addition and subtraction are used to take the shortest path between characters.

MD XF's version of the initialization causes side 2 to have a sum of 14, which saves many bytes of output for ASCII distances between 14 and 20.

Now can handle inputs with internal newlines, Console.Read() gets individual characters until End of File; see the TIO link which should have the input

```
Hello,
World!

```

Shaved a couple fractions of a point by immediately outputting a character if its ASCII value just happens to already exist on a side.

Test Script courtesy of MDXF

---

Previous submission here and explanation:

This is kinda boring, but as far as I can tell it works. Admittedly I only tried `Hello, World!` but I ran the output in the TIO Cubically interpreter and it output "Hello, World!" so I assumed it works.

Rather than actually manipulating the cube at all, the notepad is simply incremented by the sum of the 1 face (9) repeatedly until it has the right value for each character, then prints it.

# Answer
> 3 votes
# C++, score: ~~4.026~~ 3.998

improvement: added M, E and S rotations; now eats even more RAM
Fortunately, there is no memory limit here! This program can use over 10 GB of RAM, if you are unlucky enough.

Uses a heavily modified A\*-like algorithm that doesn't find even nearly optimal solutions.

It takes at least 2 bytes to cause any change to the notepad, and another byte to print it, so getting a score below 3 is almost certainly impossible.

Uses a shamelessly stolen large part of the https://codegolf.stackexchange.com/a/104881 answer to "Simulate a Rubik's cube" (by user "cmaster - reinstate monica") (for some reason I remember golfing that answer, but I can't find any related comments).

```
//#define _GLIBCXX_DEBUG
#include <x86intrin.h>
#include <cstring>
#include <iostream>
#include <streambuf>
#include <bitset>
#include <cstdio>
#include <atomic>
#include <vector>
#include <algorithm>
#include <cmath>
#include <climits>
#include <random>
#include <set>
#include <list>
#include <map>
#include <unordered_map>
#include <deque>
#include <stack>
#include <queue>
#include <string>
#include <iomanip>
#include <unordered_set>
#include <thread>

#define faceMove(offset) {offset,offset+1,offset+2,offset+15,offset+28,offset+27,offset+26,offset+13}
int faceMoves[9][8] = {
    faceMove(3),    //Up
    faceMove(39),   //Left
    faceMove(42),   //Front
    faceMove(45),   //Right
    faceMove(48),   //Back
    faceMove(81),    //Down
    {0,0,0,0, 0,0,0,0}, //M
    {0,0,0,0, 0,0,0,0}, //E
    {0,0,0,0, 0,0,0,0}, //S (these 3 move the centers in Cubically)
}, lineMoves[9][12] = {
    {50,49,48,47,46,45,44,43,42,41,40,39},    //Up
    {3,16,29,42,55,68,81,94,107,76,63,50},    //Left
    {29,30,31,45,58,71,83,82,81,67,54,41},    //Front
    {109,96,83,70,57,44,31,18,5,48,61,74},    //Right
    {39,52,65,107,108,109,73,60,47,5,4,3},    //Back
    {65,66,67,68,69,70,71,72,73,74,75,76}, //Down
    {0*13 + 4, 1*13 + 4, 2*13 + 4, 3*13 + 4, 4*13 + 4, 5*13 + 4, 6*13 + 4, 7*13 + 4, 8*13 + 4, 5*13 + 10, 4*13 + 10, 3*13 + 10}, //M
    {4*13 + 0, 4*13 + 1, 4*13 + 2, 4*13 + 3, 4*13 + 4, 4*13 + 5, 4*13 + 6, 4*13 + 7, 4*13 + 8, 4*13 + 9, 4*13 + 10, 4*13 + 11}, //E
    {1*13 + 3, 1*13 + 4, 1*13 + 5, 3*13 + 7, 4*13 + 7, 5*13 + 7, 7*13 + 5, 7*13 + 4, 7*13 + 3, 5*13 + 1, 4*13 + 1, 3*13 + 1} //S
};
#undef faceMove
void cubeRotate(std::string& cube, int* move, int rotation)
{
    int sign = rotation < 0 ? -1 : 1;
    for(int* submove = move; submove != move + rotation; submove += sign)
    {
        char takeout = cube[submove[3*rotation]];
        for(int j = 3; j --> 0;) cube[submove[j * rotation + rotation]] = cube[submove[j*rotation]];
        cube[*submove] = takeout;
    }
}
std::string cubeMove(std::string cube, int move, int inverted)
{
    cubeRotate(cube, faceMoves[move + inverted] - inverted, inverted ? -2 : 2);
    cubeRotate(cube, lineMoves[move + inverted] - inverted, inverted ? -3 : 3);
    return cube;
}
std::string cubeStart = 1+R"(
   000
   000
   000
111222333444
111222333444
111222333444
   555
   555
   555      )";
std::array<char, 6> faceVals(const std::string& s)
{
    std::array<char, 6> fvs {};
    int xs[6] { 3, 0, 3, 6, 9, 3};
    int ys[6] { 0, 3, 3, 3, 3, 6};
    for(int i = 0; i < 6; i++)
    {
        char ts = 0;
        for(int y = ys[i]; y < ys[i] + 3; y++)
        for(int x = xs[i]; x < xs[i] + 3; x++)
            ts += s[y * 13 + x] - '0';
        fvs[i] = ts;
    }
    return fvs;
}
std::string target;
struct sstate
{
    int i;
    std::string cube;
    int notepad;
    char prevCmd;
    int movesSincePrint = 0;
    bool operator < (const sstate& rhs) const
    {
        return std::tie(i, notepad, cube, prevCmd) < std::tie(rhs.i, rhs.notepad, rhs.cube, rhs.prevCmd);
    }
    int heur() const
    {
        return 3 * (target.size() - i);
    }
};
std::vector<std::pair<sstate, char>> neighbours(sstate of)
{
    std::array<char, 6> fvs = faceVals(of.cube);
    std::vector<std::pair<sstate, char>> ans;
    if(target[of.i] == of.notepad) return {{{of.i+1, of.cube, of.notepad, '@', 0}, '@'}};
    for(char c : "+-*/X&|:_")
        ans.push_back({{of.i, of.cube, of.notepad, c}, c});
    if(of.prevCmd == '+' && of.notepad < 512)
        for(int i = 0; i < 6; i++)
        {
            if(of.notepad + fvs[i] > 512) continue;
            auto next = of; next.notepad += fvs[i]; ans.push_back({next, i+'0'});
        }
    if(of.prevCmd == '-' && of.notepad < 512)
        for(int i = 0; i < 6; i++)
        {
            if(of.notepad - fvs[i] > 512) continue;
            auto next = of; next.notepad -= fvs[i]; ans.push_back({next, i+'0'});
        }
    if(of.prevCmd == '*' && of.notepad < 512)
        for(int i = 0; i < 6; i++)
        {
            if(fvs[i] * of.notepad > 65536) continue;
            auto next = of; next.notepad *= fvs[i]; ans.push_back({next, i+'0'});
        }
    if(of.prevCmd == '/')
        for(int i = 0; i < 6; i++)
        {
            if(fvs[i] == 0) continue;
            auto next = of; next.notepad /= fvs[i]; ans.push_back({next, i+'0'});
        }
    if(of.prevCmd == 'X' && of.notepad < 512)
        for(int i = 0; i < 6; i++)
        {
            if((of.notepad ^ fvs[i]) > 512) continue;
            auto next = of; next.notepad ^= fvs[i]; ans.push_back({next, i+'0'});
        }
    if(of.prevCmd == '&')
        for(int i = 0; i < 6; i++)
        {
            auto next = of; next.notepad &= fvs[i]; ans.push_back({next, i+'0'});
        }
    if(of.prevCmd == '|' && of.notepad < 512)
        for(int i = 0; i < 6; i++)
        {
            if((of.notepad | fvs[i]) > 512) continue;
            if(fvs[i] == 0) continue;
            auto next = of; next.notepad |= fvs[i]; ans.push_back({next, i+'0'});
        }
    if(of.prevCmd == '_')
        for(int i = 0; i < 6; i++)
        {
            if(fvs[i] == 0) continue;
            auto next = of; next.notepad %= fvs[i]; ans.push_back({next, i+'0'});
        }
    if(of.prevCmd == ':')
        for(int i = 0; i < 6; i++)
        {
            auto next = of; next.notepad = fvs[i]; ans.push_back({next, i+'0'});
        }
    if(of.cube != cubeStart) { auto next = of; next.prevCmd = '~'; next.cube = cubeStart; ans.push_back({next, '#'}); }
    std::string moves = "ULFRBDMES";
    for(int i = 0; i < 9; i++)
    if(of.prevCmd == moves[i])
    {
        auto next = of;
        next.cube = cubeMove(next.cube, i, false);
        next.cube = cubeMove(next.cube, i, false);
        next.prevCmd = '~';
        ans.push_back({next, '\''});
    }
    if(of.movesSincePrint < 1 || (of.movesSincePrint == 1 && 'A' <= of.prevCmd && of.prevCmd <= 'Z'))
    for(int i = 0; i < 9; i++)
    {
        auto next = of;
        next.cube = cubeMove(next.cube, i, false);
        next.prevCmd = moves[i];
        next.movesSincePrint++;
        ans.push_back({next, moves[i]});
    }
    return ans;
}
struct astate
{
    sstate ss;
    int f;
    bool operator < (const astate& rhs) const
    {
        if(f != rhs.f) return f < rhs.f;
        if(ss.heur() != rhs.ss.heur()) return ss.heur() < rhs.ss.heur();
        return ss < rhs.ss;
    }
};
std::string metagolf(std::string target)
{
    ::target = target;
    std::map<sstate, std::pair<sstate, std::string>> prev;
    astate start = {{0, cubeStart, 0, '~'}, 0};
    std::map<sstate, int> dists; dists[start.ss] = 0;
    std::set<astate> openset; openset.insert(start);
    int nodes = 0;
    std::vector<int> ics(target.size() + 3);
    sstate best; int bestdist = INT_MAX; bool done = false;
    std::vector<std::set<std::string>> cubes(target.size() + 1);
    int itsleft = 10000;
    int curI = 0;
    int lastChange = 0;
    while(!openset.empty() && (!done || itsleft --> 0))
    {
        auto it = openset.begin();
        auto[cs, cf] = *it; openset.erase(it);
        int cd = dists[cs];
        if(cs.i == target.size()) { if(cd < bestdist) bestdist = cd, best = cs; done = true; continue; }
        if(cs.i < curI) continue;
        if(cs.i > curI) cubes[cs.i].insert(cs.cube);
        if((cubes[cs.i].size() > 1000 && cs.i > curI) || (cubes[cs.i].size() > 0 && cs.i > curI && nodes - lastChange > 5e4)) curI = cs.i, lastChange = nodes;
        if(nodes % 128 == 0) printf("n=%d, cf=%d, i=%d, notepad=%d, tc=%d\r", nodes, cf, cs.i, cs.notepad, target[cs.i]);
        nodes++;
        for(auto[next, cmd] : neighbours(cs))
        {
            if(dists.count(next) && dists[next] <= cd + 1) continue;
            dists[next] = cd + 1;
            prev[next] = {cs, std::string(1, cmd)};
            openset.insert((astate){next, cd + 1 + next.heur()});
        }
    }
    std::string ans = "";
    while(prev.count(best))
    {
        auto[pr, cmd] = prev[best];
        best = pr;
        ans += cmd;
    }
    std::reverse(ans.begin(), ans.end());
    return ans;
}
std::string gen_random(int len)
{
    static const char alphanum[] = "0123456789"
            "~!@#$%^&*()_+`-=[]\\;',./{}|:\"<>?" //this is obviously not alphanumeric
            "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
            "abcdefghijklmnopqrstuvwxyz";
    std::string s;
    while(len --> 0) s += alphanum[rand() % (sizeof(alphanum) - 1)];
    return s;
}
int main()
{
    //auto cube = cubeStart;
    //for(int i = 0; i < 9; i++) cube = cubeMove(cube, i, 0);
    //for(int i = 0; i < 9; i++) cube = cubeMove(cube, i, 1);
    //printf("%s\n", cube.data());
    double ans = 0;
    for(int i = 0; i < 100; i++)
    {
        std::string s = gen_random(rand() % 35 + 5);
        std::string code = metagolf(s);
        printf("%s: %s\n", s.data(), code.data());
        ans += code.size() * 1.0 / s.size();
    }
    printf("%lf\n", ans * 1.0 / 100);
    //std::string ts = "Hello, World!";
    //int n = ts.size();
    //printf("%s\n", metagolf(ts).data());
}

```

To avoid Unicode handling, this program performs certain character substitutions: `X` corresponds to , `&` to `·`, and `#` to .

I used this to create an answer to "Hello, World!": https://codegolf.stackexchange.com/a/206322

---
Tags: code-challenge, cubically
---


title: Metagolf the OEIS

text:
# Question
Title: Metagolf the OEIS
We've had Meta Regex Golf and Display OEIS Sequences. Now, it is time for Meta OEIS Golf.

## Challenge

Given a sequence of integers, your program/function should output a program/function in the same language that then outputs the same sequence.

A simple example in Python would be

```
def f(sequence):
  # generate a dictionary/table lookup
  dc = {index: element for (index, element) in enumerate(sequence)}
  s = "lambda n: " + repr(dc) + "[n]"
  # at this point, eval(s) gives a lambda function, so
  # eval(s)(n) = sequence[n] = n-th element of sequence
  # as required
  return s

```

The function `f` takes as input a sequence of integers and outputs the source code to a `lambda` function. When the `lambda` function is called on an index `n`, it outputs the `n`-th element of that sequence.

Try it Online

## Output

The program that is output should be able to be submitted as an entry on this site for a challenge. Hence, it could be a program or function and can use one of the following input/output methods (from the tag):

* Indexing: Allowed are both 0- and 1-based indexing, and the following rules can be applied with both these types of indexing.
* Output:
    + Given some index n it can return the n-th entry of the list.
    + Given some index n it can return all entries up to the nth one in the sequence.
    + Without taking any index, it can return a (potentially infinite) lazy list or generator that represents the whole sequence.

Behavior past the final given term in the sequence is undefined. For example, your program may be given A000004 as

```
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0

```

This consists of 101 `0`s. The generated program must then output `0` for each `n` from `1` to `101` (assuming 1-indexing), but it can output anything (even a string or non-integer) for `n=102` and onward. Consequently, the generated program *can* output an infinite generator, as long as the first 101 terms are right.

## Scoring

Your score will be the sum of your program's length and the length of all 100 programs it generates from the A000001 to A000100 sequences (the program does not necessarily have to work for other sequences). This file has sequence A000001 on line 6, A000002 on line 7, in order up to A000100 on line 105, so each sequence is one line. The sequences have varying number of terms; for example, A000066 (line 71) only has 10 terms.

The ungolfed Python example above would score 46713 + 261 = 46974 points.

If the program outputs an auxiliary file (I'm not sure how this could help, but it might come into play), then follow the part of this ruling before the horizontal line.

Lowest score wins, as usual.

# Answer
> 5 votes
# JavaScript (Node.js),  ~~15604 15329 15204~~  944 + 14168 = 15112

*Saved 2 bytes thanks to @Neil*

The main program expects an array of BigInt's. Each generated program expects a 0-indexed integer and returns the **n**th term as a Number, a BigInt or a string.

```
a=>eval(require('zlib').inflateRawSync(Buffer.from('lZRNb9pAEIZ/CxHYO94PbFfJwWKxVNpKPbSXHh1LXn8IUicTBDRKheG3d3ZtCKW5VELGO/vO+JnZ185Qz0NBF7bUtZ7XnsdwUs8i4EtWywiAcY4wCFo9x3RJkVag1H1GO5GypmANST2LgbUASQsshiBQt50rzUc4FGAoWo1AWVLSk1aaGVHSskxXrBRmUkJibBGSWQD7RwseOYDIXXhfC7nvQxbmQ2wSuxvPbSLn8sjQAnB163Lj4MzwX01cc4/aDmdhGia2BAWlGxTKlkiTiFih6xynH/lq06wbszvzUx1Dz5aSUjND7JwdjyaLc88zWZSDtKsozoVSyuQ0CZIAszsnin5YfQUaF7fjAhaKYT48DoJTl9h3KSXSQcQoCRJ4hEmMwD4+LL8icYFLo/Odsm9mt1KfZQxd+P6YVq6i541WDD10xhiGFF3hHd/jk9GFSFQXXVRWx6tBeerlrBT1X9q6V/P6rD9lXPRO6MfW2YvWI+w6DIjaMSNM7W0ctDCljJZWzmltvzuf98XIO9HJvRjQCX4g+RWXaK7IGhEHDa9lReVLaS4JRQy52j4/NeyLnhvVvDSb34y9CGupF63ZQn+xbADpgnydFPSk8b7UoVjoIhvvjXoya0bB77+eymZjj9L3tcYUEz989Tmq3fOP3eYBCUVHd7SLPqifzw9YiOKQF6JMF0nW+6+v97ZnXfpoqoZNWTob3dedBKYE7O/EQbFU33+C6VJsqfOt3r5pBQXpBYQsDvO0IMOGr+P94KstvOEQzMG+qkViRTfj/fZwU9Ckje576hsiIy5ZH6j0XLI1/XRF0bUOgbo57ay55pUL+pcJg/wftdSD2M5+s2ODQY16bHC5W8lyuLHfkUOGefEH','base64'))+'')

```

Try it online!

### How?

Most sequences are stored as arrays, using several compression strategies:

* Large integers are stored as BigInt's in hexadecimal notation.

```
/* before */ 805381710463762432000n
/* after  */ 0x2ba8ea9e9255100000n

```
* Spread syntax is used on lists of at least 7 consecutive single-digit, positive entries. If there are more than 20 digits, the string is turned into a BigInt in hexadecimal notation.

```
/* before */ 1,0,1,0,1,1,1,1,1,1,3,1,3,1,3,3,3,3,3,3,6,3,6,3,6,6,6,6,6,6
/* step 1 */ ..."101011111131313333336363666666"
/* step 2 */ ...0x146626ecaafee6bfa04ca8cean+''

```
* Positive or negative delta-encoding is used if it turns out to be shorter.

```
[...].map(c=>p+=+c,p=0) /* or */ [...].map(c=>p-=c,p=0)

```

Dedicated functions are used for a couple of easy sequences:

```
/* A000004 */ n=>0
/* A000005 */ n=>(g=d=>d&&(n%d<1)+g(d-1))(++n)
/* A000006 */ n=>(g=k=>n?g(++k,n-=(g=d=>k%--d?g(d):d<2)(k)):k)(2)**.5|0
/* A000007 */ n=>+!n
/* A000010 */ n=>(g=(n,k=n)=>k--&&(h=(a,b)=>b?h(b,a%b):a<2)(n,k)+g(n,k))(n+1)
/* A000012 */ n=>1
/* A000027 */ n=>1+n
/* A000030 */ n=>(n+'')[0]
/* A000034 */ n=>1+n%2
/* A000035 */ n=>1&n
/* A000037 */ n=>n++-~(n**.5+.5)
/* A000038 */ n=>2*!n
/* A000040 */ n=>(g=k=>n?g(++k,n-=(g=d=>k%--d?g(d):d<2)(k)):k)(2)
/* A000041 */ n=>(g=(n,k=n)=>!k|n<0?0:n?g(n,k-1)+g(n-k,k):1)(n)||1
/* A000042 */ n=>'1'.repeat(n+1)
/* A000044 */ n=>(g=a=>n--?g([a[0]+(~~a[2]&&a[1])-~~a[12],...a]):a[0])([1])
/* A000045 */ n=>(g=(a,b)=>n--?g(b,a+b):a)(0,1)
/* A000051 */ n=>1+2**n
/* A000058 */ n=>(g=n=>n?g(--n)**2n-g(n)+1n:2n)(BigInt(n))
/* A000062 */ n=>++n/(Math.E-2)|0
/* A000069 */ n=>(g=k=>n?g(++k,n-=(h=n=>n&&!h(n&n-1))(k)):k)(1)
/* A000071 */ n=>(g=(a,b)=>~n--?g(b,a+b):a)(0,1)-1
/* A000073 */ n=>(g=(a,b,c)=>n--?g(b,c,a+b+c):a)(0,0,1)
/* A000078 */ n=>(g=(a,b,c,d)=>n--?g(b,c,d,a+b+c+d):a)(0,0,0,1)
/* A000079 */ n=>2**n
/* A000085 */ n=>(g=k=>~k&&(h=n=>!n||n*h(n-1))(n)/h(n-2*k)/2**k/h(k)+g(k-1))(n>>1)
/* A000093 */ n=>n**1.5|0
/* A000096 */ n=>n*(n+3)/2
/* A000100 */ n=>(g=(a,b,c,d,e)=>n--?g(b,c,d,e,2*e+d-c-2*b-a):a)(0,0,0,1,2)

```

# Answer
> 2 votes
# 05AB1E, score ~~20925~~ ~~11038~~ 10270 (110 + 10160 output bytes)

```
ÙgiнëW0‹iWÄDU+}¬_iÌ2U}Z>©β®X)I‚εNVεƵ0ƵÿŸyåiƵ0-₅B‘Ƶ‘ìë₅Byт‹Y≠*iyëDg<i‘Ž‘ìë‘•‘.ø}}}}YiJ')«ë`'вsXi\ë'-}J}}éн}„IèJ

```

-768 score thanks to a tip of *@JonathanAllan*.

Takes each input sequence as a list of integers.

Resulting programs take an integer \\$n\\$ as input and output the 0-based \\$n^{th}\\$ value in the sequence (although outputting the first \\$n\\$ values instead of \\$n^{th}\\$ value would be the same byte-count by replacing the trailing `è` with `£` in all output programs).

Test suite to verify the results or try a single output program with \\$n\\$ input (which currently uses the first A1 program).

**Explanation of the generator program:**

```
Ùgi                            # If all values in the (implicit) input-list are the same:
   н                           #  Only leave that unique value
  ë                            # Else:
   W                           #  Get the minimum (without popping)
    0‹i     }                  #  If this minimum is negative:
       WÄ                      #   Take the absolute value of this minimum
         DU                    #   Store a copy in variable `X` (1 by default)
           +                   #   And add it to each value in the list
   ¬_i   }                     #  If the first value is 0 (without popping)
      Ì                        #   Increase each value in the list by 1
       2U                      #   And store 2 in variable `X` (1 by defaul)
   Z                           #  Get the maximum of this new list (without popping)
    >                          #  Increase this maximum by 1
     ©                         #  Store it in variable `®` (without popping)
      β                        #  Convert the list from base-`®` to an integer
       ®                       #  Push `®`
        X                      #  Push `X`
         )                     #  Wrap all three values into a list
   I‚                          #  Pair it with the input-list
     ε                         #  Map both inner lists to:
      NV                       #   Store the outer map-index in variable `Y`
      ε                        #   Map all three values to:
       Ƶ0ƵÿŸ                   #    Push a list in the range [101,355]
            yåi                #    If the current value is in this list:
               Ƶ0-             #     Subtract 101 from the value
                  ₅B           #     Convert that to a base-255 string
                    ‘Ƶ‘ì       #     And prepend a "Ƶ"
              ë                #    Else:
               ₅B              #     Convert it to a base-255 string
                 yт‹           #     If the current value is less than 100
                 Y≠*i          #     and `Y` is NOT 1:
                     y         #      Just leave the current value as is
                    ë          #     Else:
                     Dg<i      #      If the length of the base-255 string is 2:
                         ‘Ž‘ì  #       Prepend a "Ž"
                        ë      #      Else:
                         ‘•‘.ø #       Surround the base-255 string with "•"
     }}}}                      #   Close the inner map and three if-else statements
         Yi                    #   If `Y` is 1 (thus the second map-iteration):
           J                   #    Join all individual compressed strings together
            ')«               '#    And append a trailing ")"
          ë                    #   Else (thus the first map-iteration):
           `                   #    Dump all three values separated to the stack
            'в                '#    Push "в"
              s                #    Swap the top two values on the stack
               Xi              #    If `Y` is still the default 1:
                 \             #     Discard the mapped value of `Y`
                ë              #    Else:
                 '-           '#     Push a "-"
                }J             #    After this if-else statement: join the stack together
     }}                        #  Close the if-statement and outer map
       é                       #  Take the shortest compressed list by first sorting on length
        н                      #  and then pop and pushing its first (shortest) string
   }                           # Close the outer if-statement
    „IèJ                       # And append "Iè" at the end of the string
                               # (after which the generated program is output implicitly)

```

This will result in one of the following programs:

1. `abвIè`: This is the base program template, where `a` and `b` are both a (compressed) integer, in one of the following forms:
    1. `d`/`dd`: A hard-coded integer, where `d` is a digit (when below 100)
    2. `•...•`: A large compressed integer, where `...` are three or more 05AB1E characters (when above 65024)
    3. `Ƶ.`: A small compressed integer, where `.` is a single 05AB1E character (when within the range \[101, 355\])
    4. `Ž..`: A medium compressed integer, where `..` are both 05AB1E characters (when within the range \[356, 65024\])
2. `abвc-Iè`: Similar as above, but `c` is a (compressed) integer as well.
3. `dIè`: Where `d` is a digit.
4. `abc...xyz)Iè`: Where `[a,z]` are each compressed integers in the form of 1.2, 1.3, or 1.4. And we also use compression method 1.2 instead of hard-coded 1.1 integers, since we join everything together at the end.

The third program type is used for the two sequences of the same integer. I could have also just used `0` instead, but the generator program would increase by more than it would save in that case.
See sequences A4 and A12.
The second program type is used for sequences that either start with a leading `0`, or contain negative values. Neither of which can be compressed by the 05AB1E base-conversion list compression I'm using.
See sequences A1; A25; A30; A35; A36; A39; A45; A65; A71; A72; A76; A93; A94; A96; and A100.
The fourth program type is used for if that method is shorter for the sequence than any of the other three program types.
See sequences A11; A14; A18; A21; A22; A23; A24; A33; A42; A49; A50; A55; A58; A60; A63; A75; A78; A80; A81; A83; A84; A85; A87; A88; and A90.
All other sequences use the default first program type.
See sequences A2; A3; A5; A6; A7; A8; A9; A10; A13; A15; A16; A17; A19; A20; A26; A27; A28; A29; A31; A32; A34; A37; A38; A40; A41; A43; A44; A46; A47; A48; A51; A52; A53; A54; A56; A57; A59; A61; A62; A64; A66; A67; A68; A69; A70; A73; A74; A77; A79; A82; A86; A89; A91; A92; A95; A97; A98; and A99.

See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*) for a bit more in-depth information of how the compressed integers and compressed lists work.

# Answer
> 1 votes
## Javascript (Node) 40 + 21058 = 21098

```
z=>`i=>[${z.map(x=>x===+x+''?x:x+'n')}]`

```

Takes inputs as arrays of strings, outputs a program which outputs an array containing numbers and BigInts.

## Javascript (Node) 14 + 20852 = 20866

```
z=>`i=>[${z}]`

```

It seems to be acceptable for the generated programs to return an array?

## Javascript (Node) 17 + 21152 = 21169

```
z=>`i=>[${z}][i]`

```

I'm not sure I entirely understood the challenge? Given an array (\[1,2,3\]), it outputs:

```
i=>[1,2,3][i]

```

---
Tags: code-challenge, sequence, integer, metagolf
---


title: Which Go rank is higher?

text:
# Question
Title: Which Go rank is higher?
Players of the traditional board game Go measure their skill in a system of ranks:

* Players new to the game are ranked 30th *kyū* (written `30k`) and progress **counting down** to 1st *kyū* (written `1k`). These are considered the *student* ranks.
* A player may promote from 1st *kyū* to 1st *dan* rank (written `1d`), and then progress **counting up** to 7th *dan* rank (written `7d`). These are the *master* ranks.
* Exceptionally skilled players past `7d` may promote to the 1st *professional dan rank* `1p`, and progress **counting up** to 9th *professional dan* rank (written `9p`). This is the highest rank.

In short: ranks are ordered `30k < 29k < ··· < 1k < 1d < 2d < ··· < 7d < 1p < 2p < ··· < 9p`.

# Task

Given two strings among {`30k`, …, `1k`, `1d`, …, `7d`, `1p`, …, `9p`} as input, output the **higher** rank of the two. (If they are equal, simply output either input.)

(As usual, I/O is flexible — your answer may be a function or a full program, reading input in any reasonable fashion and producing output in any reasonable fashion.)

This is : the objective is to minimize your code's byte count.

# Test cases

(Format: `input1 input2 output`.)

```
29k 9k    9k
21k 27k   21k
6d 1p     1p
5d 17k    5d
1k 1d     1d
1d 1d     1d
1d 2d     2d
9p 1d     9p
2d 30k    2d
1p 1k     1p
1d 1p     1p
1p 2d     1p
7p 8p     8p
30k 30k   30k

```

# Answer
# JavaScript (ES7), 58 bytes

Takes the two strings in currying syntax `(a)(b)`.

```
a=>b=>(g=s=>parseInt(s)*'_dp'.search(s[1])**3)(a)>g(b)?a:b

```

Try it online!

### How?

The helper function **g()** translate the input string **s** into a score.

1) We look for **s\[1\]** into the string **"\_dp"**. This gives:

* **1** for a *dan* rank **"xd"**
* **2** for a *professional dan* rank **"xp"**
* **-1** for a *kyū* rank **"xk"** or **"xxk"** because **s\[1\]** is either **"k"** or a digit

2) We cube this result, which leaves **1** and **-1** unchanged but gives **8** for a *professional dan* rank.

3) We multiply by the decimal part of the rank.
> 36 votes

# Answer
# Jelly,  ~~11~~  10 bytes

Inspired to go back to the drawing board by Arnauld!

```
⁾kNyv9FµÞṪ

```

A monadic link accepting a list of strings\* (as described) which yields the highest rank found.

* Also works with numbers other than two.

**Try it online!** Or see a test-suite.

### How?

Sorts by a key function and returns the rightmost (i.e. a maximum).

The key function first changes any **k** to become an **N** using the dyadic atom `y`, translate, with the two-character list `⁾kN` (Jelly code for `['k','N']`) and then evaluates the string as a monad with an argument of nine (by use of the code `v9`).

In Jelly:

* `N` is a monadic atom which negates its input

+ so the code `9 30N` does not actually use the nine and results in the integer `-30`
* `d` is a dyadic atom which yields the result of a Python divmod of two values - the pair of the results of integer division and modulo

+ so the code `9 7d` results in \\$\lfloor \frac 7 9 \rfloor\\$ paired with \\$7 \pmod 9\\$ which is `[0,7]`
* `p` is a dyadic atom which performs a Cartesian product, which includes implicit 1-indexed range-ification of its inputs

+ so the code `9 p3` yields the Cartesian product of `[1,2,3]` and `[1,2,3,4,5,6,7,8,9]` which is `[[1,1],[1,2],...,[1,9],[2,1],[2,2],...,[2,9],[3,1],[3,2],...,[3,9]]`

Once such evaluations have been performed using the strings to be compared we need to be able to compare the results; since ints are not comparable with lists we need to wrap the negated values in a list, but since the ordering would still work after the `p` lists are flattened (e.g. `[[1,1],[1,2],...]` -\> `[1,1,1,2]`) we can use the single-byte monadic atom `F` applied to all evaluations.

A table of the inputs to their key-value is as follows:

```
in    ⁾kNy    ⁾kNyv9F
30k   30N     [-30]
29k   29N     [-29]
...
 2k    2N     [-2]
 1k    1N     [-1]
 1d    1d     [0,1]
 2d    2d     [0,2]
 ...
 6d    6d     [0,6]
 7d    7d     [0,7]
 1p    1p     [1,1,1,2,...,1,9]
 2p    2p     [1,1,1,2,...,1,9,2,1,...,2,9]
 ...
 8p    8p     [1,1,1,2,...,1,9,2,1,...,7,9,8,1,...,8,9]
 9p    9p     [1,1,1,2,...,1,9,2,1,...,7,9,8,1,...,8,9,9,1,...,9,9]

```

Code commentary:

```
⁾kNyv9FµÞṪ - Link: list of lists of characters
       µÞ  - sort by (Þ) the monadic link to the left (µ):
⁾kN        -   two-char list = ['k', 'N']
   y       -   translate the current string (change 'k's to 'N's)
     9     -   literal nine
    v      -   evaluate (the left) as Jelly code with the input as given on the right (9)
      F    -   flatten the result
         Ṫ - tail (get the rightmost, and hence (a) maximum)

```
> 15 votes

# Answer
# Jelly, 14 bytes

```
OṪ|8-2*×ṖV$µÞṪ

```

A monadic link accepting a list of strings\* (as described) which yields the highest rank found.

* Also works with numbers other than two.

**Try it online!** Or see a test-suite.

### How?

Sorts by a key function and returns the rightmost (i.e. a maximum).

The letters \\$k\\$, \\$d\\$, and \\$p\\$ have ordinals \\$107\\$, \\$100\\$, and \\$112\\$ respectively. In binary \\$107\\$ has the eight bit set while the others do not, hence bitwise OR-ing with 8 we get 107, 108, and 120 respectively - these are now in the order required to sort the classes they identify.

The amateur ranks are in descending order so to complete our key function we could concatenate our class-identifier with the number given in the string, negating if the string ends in \\$k\\$ (e.g. `'7k'` -\> `[107,-7]` while `7p` -\> `[120,7]`). In the code this requires storing the class-identifier and exponentiating minus one for the multiplication - `OṪ|©8-*×ṖV$®,µÞṪ` \- which is \\$16\\$ bytes.

To improve upon this we can use minus two instead and multiply the elements together, which may be achieved with a single multiplication.

```
OṪ|8-2*×ṖV$µÞṪ - Link: list of lists of characters
           µÞ  - sort by (Þ) the monadic link to the left (µ):
O              -   ordinals
 Ṫ             -   tail
   8           -   literal eight
  |            -   bitwise OR
    -2         -   literal minus two
      *        -   exponentiate
          $    -   last two links as a monad (of the current list of characters):
        Ṗ      -     pop (get all but rightmost character)
         V     -     evaluate as Jelly code (gets the number)
       ×       -   muliply
             Ṫ - tail (get the rightmost)

```

Table of the key-function's action...

```
in    ṖV$  OṪ   OṪ|8       OṪ|8-2*×ṖV$
30k   30   107  107       -4867778304876400901747340308643840 = ((-2)^107)*30
29k   29   107  107       -4705519028047187538355762298355712 = ((-2)^107)*29
...
 2k    2   107  107        -324518553658426726783156020576256 = ((-2)^107)*2
 1k    1   107  107        -162259276829213363391578010288128 = ((-2)^107)*1
 1d    1   100  108         324518553658426726783156020576256 = ((-2)^108)*1
 2d    2   100  108         649037107316853453566312041152512 = ((-2)^108)*2
 ...
 8d    8   100  108        2596148429267413814265248164610048 = ((-2)^108)*8
 9d    9   100  108        2920666982925840541048404185186304 = ((-2)^108)*9
 1p    1   112  120     1329227995784915872903807060280344576 = ((-2)^120)*1
 2p    2   112  120     2658455991569831745807614120560689152 = ((-2)^120)*2
 ...
 8p    8   112  120    10633823966279326983230456482242756608 = ((-2)^120)*8
 9p    9   112  120    11963051962064242856134263542523101184 = ((-2)^120)*9

```
> 12 votes

# Answer
# MATL, ~~30~~ ~~28~~ ~~25~~ 23 bytes

```
,0&)Uw'k'-tUw6*+qw*w]<G

```

Try it online!

*(-2 bytes thanks to Luis Mendo)*
*(another -3 bytes replacing `v&X>` with `>`, this time based on Luis Mendo's answer)*
*(-2 bytes using `&)` syntax)*

### Explanation:

* Subtract 'k' from the last character (gives n = -7, 0, 5 for 'd', 'k', 'p' respectively).
* Compute v = n^2+6n-1 (gives 7, -1, 54 respectively).
* Multiply that value v by the actual rank number (so k levels get negative products, d levels go from 7 to 49, p levels from 54 and above).
* Do that for both input strings, compare the products
* Get the input string corresponding to the greater product

---

Alternate, more straightforward method: :

### 23 bytes

```
,0&)Uwo'dpk'1L6^XE*w]<G

```

Try it online!

```
,              % Do this twice (once for each input):
0&)            % Split the input into number, last letter
U              % str2num i.e. Convert '21' to 21
wo             % Bring the letter out and change it to numeric (its ASCII code)
'dpk'          % Push the array 'dpk'
1L6^           % Push [1 2 1j] and raise to ^6, giving [1 64 -1]
XE             % Find the letter in 'dpk', replace it with its corresponding
               %  number from the second array (d=1, p=64, k=-1)
*              % Multiply the number part by this
w              % Switch to bring out the other input to top
]              % End loop
               % Stack has [second input's value, first input's value]
<              % Is second input < first input? 1 or 0
G              % Retrieve the corresponding input: 1 for 1st input,
               %  0 for last (2nd) input

```

---
> 10 votes

# Answer
# Haskell, ~~73~~ 71 bytes

```
r(x,"k")=0-x
r(x,"d")=x
r(x,"p")=x+7
p=r.head.reads
a#b|p a<p b=b|0<1=a

```

Try it online!

As usual for me, just a straight forward implementation rather than anything particularly golf-y. The "(#)" function takes two ranks as strings and returns the larger one. Works only with exactly the format specified in the question.

(I've also tried a version using `comparing` and `maximumBy` but that ended up being 3 bytes longer - damn you `base` and your occasionally human readable function names!)

(Applied suggestions by Amphibological and Lynn)
> 9 votes

# Answer
# Python 2, 54 bytes

```
lambda s:max(s,key=lambda x:(int(x,27)%9-3)*int(x,26))

```

Try it online!

Using Arnauld's method. The mapping `int(x,27)%9-3` only depends on the last letter of `x`, since all digits but the last one contribute a multiple of `9`. It takes:

```
'k' -> -1
'p' -> 1
'd' -> 4

```

This is barely enough margin for the multiplier for `1p` to beat `7d`, the highest dan rank, when interpreted in base 26.

I found this by brute-forcing expressions of this form and a few others.

---

# Python 2, 64 bytes

```
lambda s:max(s,key=lambda x:(ord(x[-1])|8,int(x,36)^-('k'in x)))

```

Try it online!
> 8 votes

# Answer
# , 73 bytes

```
function(v)v[rank(as.double(chartr('dp','.0',sub('(.+)k','-\\1',v))))][2]

```

Try it online!

* I had to use `as.double` instead of `strtoi` since the latter doesn't handle spaces/points and I couldn't think of another valid character to replace `d`
* -1 byte using `rank` instead of `order`, since they are equal when there are only two elements
> 6 votes

# Answer
# Jelly, 13 bytes

This is quite different from my other Jelly answer, so I'm posting this separately.

Takes input as a list of two (or more) strings.

```
“kNdHp0”yVµÞṪ

```

Try it online!

### Commented

```
“kNdHp0”yVµÞṪ
“kNdHp0”       - literal string
        y      - translate each rank character into a Jelly instruction/symbol:
                   'k' -> 'N' = negate
                   'd' -> 'H' = halve
                   'p' -> '0' = a literal zero
         V     - evaluate as Jelly code
                 examples:
                   '21k' -> '21N' -> -21
                   '7d'  -> '7H'  -> 3.5  (*)
                   '3p'  -> '30'  -> 30
          µÞ   - sort the input using all of the above
            Ṫ  - return the second entry

(*) we don't really need to halve these values, but we do want to get rid of 'd'

```
> 6 votes

# Answer
# Julia 0.7 ~~100~~ 93 bytes

It is not the most efficient way, (contrast @sundar's Julia 0.6 answer) but it is nice because it is purely numeric. Also uses dispatch (though sadly only once)

```
!z=(-z%2+.9)z*z
s(x,y,z)=(10x+y)*!z
s(x,z)=x*!z
~r=s(Int[r...]...)
a|b=[a,b][argmax(.~[a,b])]

```

Very similar code works in 0.6 Try it online

### How:

The trick is all in the `!(z)` function.

It maps the UTF-8 value:

* for `k` into a negative number, so it sorts backwards
* for `d` into a positive number
* for `p` into a larger positive number

As shown:

```
julia> !(Int('k'))
-1144.8999999999996

julia> !(Int('d'))
9000.0

julia> !(Int('p'))
11289.6

```

### Test results

```
julia> @testset "Check it" begin
               @test "29k" | "9k" == "9k"
               @test "21k" | "27k" == "21k"
               @test "6d" | "1p" == "1p"
               @test "5d" | "17k" == "5d"
               @test "1k" | "1d" == "1d"
               @test "1d" | "1d" == "1d"
               @test "1d" | "2d" == "2d"
               @test "9p" | "1d" == "9p"
               @test "2d" | "30k" == "2d"
               @test "1p" | "1k" == "1p"
               @test "1d" | "1p" == "1p"
               @test "1p" | "2d" == "1p"
               @test "7p" | "8p" == "8p"
               @test "30k" | "30k" == "30k"
       end
Test Summary: | Pass  Total
Check it      |   14     14
Test.DefaultTestSet("Check it", Any[], 14, false)

```
> 5 votes

# Answer
# Haskell, 64 bytes

```
r[(n,[c])]=n*(gcd(fromEnum c)28-3)
g=r.reads
a%b|g a>g b=a|1>0=b

```

Try it online!

The expression `gcd(fromEnum c)28-3` maps the character to a multiplier

```
k -> -2
d -> 1
p -> 25

```

The idea was to take their character values `[107,100,112]` and choose `28` to have increasingly large factors in common with them, made easy but the first one 107 being prime. This method saves 2 bytes over explicitly writing out a mapping.

The built-in `reads` is used to separate the number and rank.

```
Prelude> reads "25k" :: [(Int, String)]
[(25,"k")]

```

(Actually, the direct splitting from Sara J is one byte shorter, giving 63 bytes.)

The take-the-bigger-one step takes an annoying number of bytes in my solution. I tried other approaches like iterating over ranks in decreasing order and taking the first one that's an element of `[a,b]`, but they turned out longer.
> 5 votes

# Answer
# MATL, ~~28~~ 27 bytes

```
,w'kdp'X{'*-1 . *8'YbYXU]>G

```

Try it online! Or verify all test cases.

### Explanation

```
,                % Do twice
  w              %   Swap. Takes implicit input
  'kdp'          %   Push this string
  X{             %   Split chars: gives cell array {'k', 'd', 'p'}
  '*-1 . *8'     %   Push this string
  Yb             %   Split at whitespace: gives cell array {'*-1', '.', '*8'}
  YX             %   Regexprep: replaces 'k' by '*-1', 'd' by '.', 'p' by '*8'
  U              %   Convert to number: evaluates string
]                % End
>                % Greater than? Gives a result r which is 0 or 1
G                % Push r-th input (modularly: 0 is last, 1 is first)

```
> 3 votes

# Answer
# Jelly, 16 bytes

Takes input as a list of two strings.

```
OṪ²²%90’’×ṖV$µÞṪ

```

Try it online! (all test cases)

### How?

The ASCII code \\$c\\$ of the rank character is converted to a multiplier \\$m\\$ with the following formula:

$$m=(c^4 \bmod 90)-2$$

Which gives:

```
 char. | ASCII | **4       | mod 90 | -2
-------+-------+-----------+--------+----
  'k'  |   107 | 131079601 |      1 | -1
  'd'  |   100 | 100000000 |     10 |  8
  'p'  |   112 | 157351936 |     76 | 74

```

### Commented

```
OṪ²²%90’’×ṖV$µÞṪ
OṪ²²%90’’        - process the rank character        takes a string, e.g. '28k'
O                - get ASCII codes                   --> [50, 56, 107]
 Ṫ               - pop                               --> 107
  ²²             - square twice                      --> 131079601
    %90          - modulo 90                         --> 1
       ’’        - decrement twice                   --> -1
          ṖV$    - process the decimal part
          Ṗ      - remove the last character         --> '28'
           V     - evaluate as Jelly code            --> 28 (integer)
         ×       - multiply                          --> -28
             µÞ  - sort input using all of the above
               Ṫ - return the second entry

```

### Alternate formula

For 16 bytes as well, we can use:

$$m=((c-1)^9 \bmod 64)-1$$

```
OṪ’*9%64’×ṖV$µÞṪ

```

Try it online!
> 3 votes

# Answer
# JavaScript (ES6), ~~55~~ 54 bytes

-1 byte thanks to @Shaggy

```
a=>b=>(s=x=>parseInt(x)*~-{p:9,d:2}[x[1]])(a)>s(b)?a:b

```

Try it Online!

## Explanation

```
a=>b=>
  (s=x=>                 // Function s(x), that converts x to a "score", where a higher
                         // rank gets a higher score by
    parseInt(x)*         //   taking the integer part of x and multiplying it by
    ~-{p:9,d:2}[x[1]])  //   ~-9 (8) if it is a professional rank, ~-2 (1) if it is a dan
                         //   rank and ~-undefined (-1) if it is a kyū rank by looking up
                         //   the second character of the string
  (a)>s(b)               // Compare s(a) and s(b)
    ?a:b                 //   and return the one with the biggest score

```
> 3 votes

# Answer
# Perl, ~~46~~ 38 bytes

```
s/p/0/g;s/\w*k/-$&/g;/ /;$_=@F[$`<=$']

```

Run as `perl -pae '...'`. Takes input from stdin, space-separated on one line.

Performs a couple of substitutions to make comparison "easier". The regexp substitutions essentially amount to replacing `p` with a trailing zero and `k` with a leading negative sign. So `10k` becomes `-10` (so the ordering is reversed) and `3p` becomes `30` (so that `p` is above everything else). Then it's just a simple numerical comparison.

Thanks to DomHastings for the `$`` / `$'` suggestion, which shaved off 8 bytes.
> 3 votes

# Answer
# Ruby, ~~52~~ 46 bytes

```
->s{s.max_by{|x|(5-x[-1].ord*5%8)*x.to_i(26)}}

```

Straightforward port of xnor's answer.

Try it online!

*EDIT: -6 bytes by realizing I could have used a Proc*
> 3 votes

# Answer
# C# (Visual C# Compiler), ~~136~~ 135 bytes

```
a=>b=>{string c=a.PadLeft(3,'0'),d=b.PadLeft(3,'0');int x=c[2]-d[2];return(x==0?c.CompareTo(d)*(c[2]=='k'?-1:0)>0:x==5|x>9|x==-7)?a:b;}

```

Try it online!

-1 Byte thanks to TheLethalCoder

**Expanation:**

```
static void Main()
{
    System.Func<string, System.Func<string, string>> f =
        a => b =>
        {
            string c = a.PadLeft(3, '0'),
                d = b.PadLeft(3, '0');      //Pad the input with leading '0' to be 3 characters long
            int x = c[2] - d[2];            //Calculate the difference of the letter characer (the character at index 2) as integer
            return                          //return ...
                (x == 0 ?                   //if the letter of the inputs is the same...
                c.CompareTo(d)              //  compare the padded strings resulting in a positive number if the first input is greater or a negative number if the first input is lower
                    * (                     //  multiply the result by...
                    c[2] == 'k' ? -1 : 0    //  if the letter is 'k' then -1 else 0
                    ) > 0                   //  check if the result is greater than 0
                :                           //else (the letters are not the same)
                x == 5 | x > 9 | x == -7    //  check if the letter difference was 5 (input p and k) or 12 (> 9, input p and d) or -7 (input d and k)
                ) ? a : b;                  //  then return the first input else return the second input.
        }
    ;

    System.Console.WriteLine(f("29k")("9k"));
    System.Console.WriteLine(f("21k")("27k"));
    System.Console.WriteLine(f("6d")("1p"));
    System.Console.WriteLine(f("5d")("7k"));
    System.Console.WriteLine(f("1k")("1d"));
    System.Console.WriteLine(f("1d")("1d"));
    System.Console.WriteLine(f("1d")("2d"));
    System.Console.WriteLine(f("9p")("1d"));
    System.Console.WriteLine(f("2d")("30k"));
    System.Console.WriteLine(f("1p")("1k"));
    System.Console.WriteLine(f("1d")("1p"));
    System.Console.WriteLine(f("1p")("2d"));
    System.Console.WriteLine(f("7p")("8p"));
    System.Console.WriteLine(f("30k")("30k"));
}

```
> 3 votes

# Answer
# Java 8, ~~128~~ ~~122~~ 121 bytes

```
a->b->g(a)<g(b)?b:a;float g(String s){return("kdp".indexOf(s.charAt(s.length()-1))-.9f)*new Byte(s.replaceAll(".$",""));}

```

-6 bytes thanks to *@SaraJ*.

Try it online. (See the bottom of the output in the TIO-links to see the mapped values.)

**Explanation:**

```
a->b->                       // Method with two String parameters and String return-type
  g(a)<g(b)?                 //  If the mapped value of `a` is smaller than `b :
   b                         //   Return input `b` as result
  :                          //  Else:
   a;                        //   Return input `a` as result

float g(String s){           // Separated method with String parameter and float return-type
                             // (This method maps all possible Strings to a value)
 return("kdp".indexOf(       //   Take the (0-based) index in the String "kdp"
    s.charAt(s.length()-1))  //   of the last character
    -.9f)                    //   After we've subtracted 0.9
  *(                         //  And multiply it with:
    new Byte(                //   Convert the String to an integer
     s.replaceAll(".$",""));}//   After we've removed the trailing character

```
> 3 votes

# Answer
# , ~~65~~ 62 bytes

```
`+`=paste0;max(ordered(scan(,""),c(30:1+"k",1:7+"d",1:9+"p")))

```

Try it online!

This comes in a bit shorter than the previous R answers, and makes good use of R's statistics functionality :-)

*-3 bytes thanks to Robin Ryder's suggestion to use* `ordered` *instead of* `factor`

Takes input from stdin (although the TIO link restructures slightly for ease of testing). Casts the input ranks into an *ordered* `factor` of all ranks, then takes the max.

Output looks like:

```
[1] MAX_RANK
46 Levels: 30k < 29k < 28k < 27k < 26k < 25k < 24k < 23k < 22k < ... < 9p

```
> 3 votes

# Answer
# Haskell, ~~75~~ ~~70~~ 68 bytes

```
g k=read(init k)*(abs(fromEnum(last k)*2-209)-8)
a?b|g a>g b=a|1>0=b

```

Try it online!

`-5 bytes` thanks to @Laikoni
`-2 bytes` thanks to @ASCII-only
> 3 votes

# Answer
# Python 2, 61 bytes

Uses Arnauld's algorithm.

```
lambda c:max(c,key=lambda i:'_dp'.find(i[-1])**3*int(i[:-1]))

```

Try it online!

---

### Previous answer, 73 bytes

```
lambda c:max(c,key=lambda i:('dp'.find(i[-1]),int('-'*('k'in i)+i[:-1])))

```

Try it online!
> 2 votes

# Answer
# Julia 0.6, ~~75~~ ~~71~~ 65 bytes

```
S->S[indmax((s->parse(s[1:end-1])*(search("_dp",s[2])-1)^3).(S))]

```

Try it online!

*(-4 bytes, parse in 0.6 auto detects it as Int)*

*(-6 bytes, use `(search("_dp",s[2])-1)^3)` based on Arnauld's JS answer, instead of `((c=cmp(s[end],'k'))^2*6+4c-1)`)*
> 2 votes

# Answer
# Retina 0.8.2, 29 bytes

```
O$^`.+((k)|(.))
$3$&$*1$2
1G`

```

Try it online! Accepts any number of ranks and outputs the highest. Explanation:

```
O`

```

Sort the lines...

```
$

```

... using the specified key...

```
^

```

... in reverse order.

```
.+((k)|(.))
$3$&$*1$2

```

The key is created from the input line as follows: a) the (professional) dan rank letter b) the rank in unary c) the kyū letter (where applicable). Since this is a reverse sort, the professional dan rank `p` sorts before the dan rank `d` and the kyū rank which starts with `1` because the kyū letter is left at the end. Within the ranks the (professional) dan ranks sort in descending order due to the length of the unary string, however the trailing `k` for the kyū ranks causes them to sort in ascending order.

```
1G`

```

Select the first line, which is now the greatest rank.
> 2 votes

# Answer
# J, 39 bytes

```
[`]@.(<&(".@}:((*_1&^)+]*0=2&|)a.i.{:))

```

Try it online!

## explanation

```
[`]@.(<&(".@}: ((* _1&^) + ] * 0 = 2&|) a. i. {:))    entire phrase
[`]@.(<&(       assign a rank number            ))
      <&                                              "less than" of the ranks of the left and right args
                                                      ie, return 1 if right arg rank is bigger
[`]@.                                                 if so, return right arg.  otherwise left
                                                      breaking down the rank number part now...
        (       assign a rank number            )
        (".@}: ((* _1&^) + ] * 0 = 2&|) a. i. {:)
        (".@}:                                  )     everything but last char, convert to number
        (                               a. i. {:)     index within ascii alphabet of the last char
                                                      these become the left and right args to what follows...
        (      ((* _1&^) + ] * 0 = 2&|)         )
        (      (           ] * 0 = 2&|)         )     the right arg * "is the right arg even?"
                                                      because only 'k' is odd (107), this will be 0 for 'k'
                                                      and will be 100 for 'd' and 112 for 'p'
        (      ((* _1&^)              )         )     left arg (number of go rank) times _1 raised
                                                      to the ascii index.  this will swap the sign
                                                      for k only, hence producing a valid rank function

```
> 2 votes

# Answer
# Python, 59 bytes

```
lambda s:max(s,key=lambda x:(-2)**(ord(x[-1])|8)*int(x,26))

```

An unnamed function accepting an iterable of strings which returns a maximal one by Go rank. Works much like my Jelly answer (just uses the whole string evaluated as an integer in base 26 to save bytes).

**Try it online!**
> 2 votes

# Answer
# C (gcc), 95 91 bytes

Thanks to ceilingcat for the suggestion.

```
#define _(s)(strtol(s,&u,0)+(*u^15)*8)*~-(*u&2)
f(s,t,u)char*s,*t,*u;{puts(_(s)<_(t)?s:t);}

```

Try it online!
> 2 votes

# Answer
# Perl 6, 35 bytes

```
*.max: {{+TR/pd/0 /}(S/(.+)k/-$0/)}

```

Try it online!

A rather different approach to all this search-and-cube stuff. Essentially string replacement: `...k -> -...`, `p -> 0`, `d` deleted. Thus newbies get a minus score, dans get their rank and pros get rank\*10. Using the WhateverStar gets us a closure, and `max` takes a comparator function.
> 2 votes

# Answer
# PHP, ~~100~~ 98 bytes

(-2 bytes by changing function declaration)

```
<?function f($v){return(strpos('!!dp',$v[1])-1)**3*$v;};list(,$a,$b)=$argv;echo f($a)>f($b)?$a:$b;

```

To run it:

```
php -n <filename> <rank1> <rank2>

```

Example:

```
php -n go_rank.php 1p 7d

```

Or Try it online!

---

# PHP (7.4), 74 bytes

```
$g=fn($v)=>(strpos(__dp,$v[1])-1)**3*$v;$f=fn($a,$b)=>$g($a)>$g($b)?$a:$b;

```

Try it online!

---

# How?

Similar to Arnauld's approach, but in PHP. I'm using a function to convert each rank to a numeric value and compare and output the one with higher value.

The rank value comes from input string's second character position in `!!dp`, reduced by one and then powered to 3 and multiplied by the integer part of input string.

So for example, position of second character of `1p` which is `p` in `!!dp` is 3, reduced by one and powered to 3 it will be 8. So integer part of all `*p` ranks will be multiplied by 8. This means `1p = 8`, `2p = 16`, ..., `9p = 72`.

For all `*d` ranks, the integer part will be multiplied by 1 (or simply no multiplication). This means `1d = 1`, ..., `7d = 7`.

And for all `*k` and `**k` ranks, position of second character in `!!dp` will be equal to `false` which is equal to 0 (no explicit), reduced by one and powered by 3, means that the integer part will be multiplied by -1. This means `30k = -30`, ..., `1k = -1`.

This is my first ever golf attempt, not sure how bad it is!
> 2 votes

# Answer
# 05AB1E, 12 bytes

```
Σ'pK°.Vyþ*}θ

```

`.V` (evaluate as 05AB1E code) is inspired by *@Arnauld*'s similar approach in his Jelly answer.

Input as a list of two (or more) of the valid strings.

Try it online or verify all test cases.

**Explanation:**

```
Σ           # Sort the (implicit) input-list by:
 'pK       '#  Remove "p"
    °       #  Take 10 to the power this string
            #  (if the string is not a valid number, the string remains unchanged)
     .V     #  Evaluate the string as 05AB1E code
       yþ*  #  Multiply it with just the digits of the string
}θ          # After the sort: pop and push the last element
            # (which is output implicitly as result)

```
* `k` pops a list and an item, and pushes the index of the item in the list. Since the stack doesn't contain a list, `"30k"` through `"1k"` will always result in `-1`. Multiplied by their number, it will be the range \\$\[-30,-1\]\\$.
* `d` checks if a number is non-negative (`>= 0`). Since this is truthy for all, `"1d"` through `"7d"` will always result in `1`. Multiplied by their number, it will be the range \\$\[1,7\]\\$.
* Removing `p` and using `°` will use 10 to the power \\$a\\$ if \\$a\\$ is a valid number, otherwise \\$a\\$ remains the same. So if \\$a\\$ is `"2k"` or `"2d"`, it will remain `"2k"` or `"2d"` after using `°`, but `"2"` (since we've removed the `p`) with `°` will become `100`. Multiplied by their number, `"1p"` through `"9p"` will be the list \\$\[10, 200, 3000, 40000, 500000, 6000000, 70000000, 800000000, 9000000000\]\\$.

See all mapped values here.
> 2 votes

# Answer
# Scala, 307 61 54 bytes

Great thanks to **Kevin Crujissen** and **ASCII-only** for their work on this answer, that got it down ~250b.

Some algorithm optimization for ordering function of 61b answer.

```
l=>l.maxBy(s=>s.init.toInt*(math.abs(s.last*2-209)-8))

```

Test cases here: Try it online!

# Old 61 bytes answer

```
l=>l.maxBy(s=>(s.init.toInt+s.last)*(math.abs(s.last-105)-3))

```

The trick is to compute distance between `rank letter` and `i` (char code `105`). Then we use this distance as a score (*dan* = 5, *kyu* = 2, *pro* = 7) that we multiply by the rank number. Then we take the maximum on input array using the scoring function.

Try it online too!
> 2 votes

# Answer
# \[R\], 87 \[bytes\]

update:

using JayCe's golfing: `f=function(v,k=-1,d=1,p=10)v[eval(parse(t=paste(gsub('(\\D)','*\\1',v),collapse='<')))+1]`

# \[R\], 150 \[bytes\]

a long answer I find interesting could save a lot of bytes if not sticking to the eval method. inputs are s1 and s2:

```
f=function(s)eval(parse(t=sub("\\D+",paste0("*",c(-1,1,8)[match(tail(el(strsplit(s,"")),1), c("k","d","p"))]),s)));c(s1,s2)[as.numeric(f(s1)<f(s2))+1]

```
> 1 votes

# Answer
# Excel VBA, 129 bytes

An anonymous VBE Immediate window function that takes input in range `A1:A2` and outputs to the console.

```
[B:B]="=SUBSTITUTE(A1,""p"",10)":[C1:C2]="=LEFT(B1,LEN(B1)-1)*-1^IFERROR(FIND(""k"",B1)>0,0)":?[INDEX(A:A,MATCH(MAX(C:C),C:C,0))]

```

### Explaination

```
[B:B]="=SUBSTITUTE(A1,""p"",10)"                            ''  Convert inputs to numerics
                                                            ''  by appending 10 to rank if
                                                            ''  is a professional dan rank
                                                            ''
[C1:C2]="=LEFT(B1,LEN(B1)-1)*-1^IFERROR(FIND(""k"",B1)>0,0)"''  Remove rightmost char; If
                                                            ''  the rank is kyū, then mult
                                                            ''  by -1
                                                            ''
?[INDEX(A:A,MATCH(MAX(C:C),C:C,0))]                         ''  Find the max, return the
                                                            ''  corresponding input

```
> 1 votes

# Answer
# , 83 bytes

```
function(v,k=-1,d=1,p=10)v[1+do.call("<",as.list(parse(t=gsub('(\\D)','*\\1',v))))]

```

Try it online!

Inspired by this answer by Zahiro Mor and digEmAll's comments on the answer. OP has not replied to comments so I am posting it separately, adding my own `do.call` twist to it to save additional bytes.

`do.call` takes arguments to the function as a list, which we do not need to `eval` before passing - a `parse` is sufficient. Still, `as.list` costs a lot of bytes...

Still not as golfy as digEmAll's `chartr` answer!
> 1 votes

# Answer
# JavaScript (Node.js), 53 bytes

```
a=>b=>(s=([d,q])=>-d+q|{p:8*d,d,k:-d}[q])(a)>s(b)?a:b

```

Try it online!

Optimized from tsh's comment in https://codegolf.stackexchange.com/a/168183/
> 1 votes

# Answer
# Jelly, 20 bytes

```
6ị⁾kpiị“¡µ£‘’×ṖV$µÞṪ

```

Try it online!
> 0 votes

# Answer
# Pyth, 15 bytes

Also uses Arnauld's method.

```
eo*^x"_dp"eN3.v

```

Try it here!
> 0 votes

# Answer
# Kotlin, 256 bytes

```
{f:String,s:String->{val e={s:String->if(s.length==2)"0$s"
else s}
val d=e(f)
val n=e(s)
val r=when(d[2]){'k'->if(n[2]=='k')if(d<n)f
else s
else s
'd'->if(n[2]=='d')if(d<n)s
else f
else if(n[2]=='k')f
else s
else->if(n[2]=='p')if(d<n)s
else f
else f}
r}()}

```

Try it online!
> 0 votes

# Answer
# Go, 168 bytes

```
import(."strings"
."strconv")
func g(s string)int{i:=IndexByte("_dp", s[1])
j,_:=Atoi(s[:len(s)-1])
return i*i*i*j}
func f(a,b string)string{if g(a)>g(b){b=a}
return b}

```

Translation of Arnaud's idea. Had to be done for the sake of the language name.
> 0 votes

---
Tags: code-golf, string, go
---


title: Is this a valid Shakashaka solution?

text:
# Question
Title: Is this a valid Shakashaka solution?
## Background

**Shakashaka** is a puzzle on a grid, whose objective is to place some *half-squares* (right triangles) on the empty cells so that all the remaining contiguous regions form rectangles, either upright or 45 degrees rotated. Here is an example puzzle with a solution:

Ignore the number clues for this challenge.

## Challenge

Given a grid with black squares and half-squares placed on some of the cells, determine if it is a valid solution to some Shakashaka puzzle, i.e. all the white regions form rectangles.

The input is a 2D grid (in any valid form) with each cell containing its encoded state. Each cell will be in one of the six states: white square (empty), black square, and four possible orientations of the half-square (NW, NE, SW, SE). You may encode them as six distinct numbers or (possibly multi-dimensional) arrays of numbers, and you can use characters instead of numbers (so strings or string arrays are also acceptable).

Standard rules apply. The shortest code in bytes wins.

## Test cases

Because it is pretty hard to reproduce a Shakashaka board with Unicode chars, I include a Python script to convert the input to any form of your choice. The default configuration renders them using Unicode geometric shapes, so you can roughly see how the actual grid will look like.

```
def gentest(tc,mapping,charjoin='',linejoin='\n',preamble='',postamble=''):
  return preamble+linejoin.join(charjoin.join(mapping[x] for x in line.split())for line in tc.strip().splitlines())+postamble

```

Try it online!

### How to use it

```
tc - the testcase string, which will be supplied in the footer
mapping - the dict of 6 keys 'B', 'W', 'NE', 'NW', 'SE', 'SW' mapped to
          6 distinct strings
          'B' is filled (black) square, 'W' is white square,
          the rest four represent half-cell filled in that direction
charjoin - string to insert between each cell on a horizontal line
linejoin - string to insert between each line of cells
preamble - string to add in front of the entire grid
postamble - string to add at the end of the entire grid

```

---

Alternatively, you can use this Stack Snippet kindly written by @Arnauld to better visualize the test cases (it shows the 10 test cases by default):

```
function draw2() { let grids = document.getElementById("in").value.split('\n\n').map(g => g.split('\n').map(r => r.split(/ +/))), out = ""; grids.forEach(g => { out += '<div class="wrapper" style="width:' + g[0].length * 17 + 'px;height:' + g.length * 17 + 'px;">'; g.forEach(r => { r.forEach(s => { out += '<div class="cell"><div class="cell ' + s + '"></div></div>'; }); }); out += '</div>'; }); document.getElementById("out").innerHTML = out;}window.onload = () => { document.getElementById("in").value = [ "NW NE W W B W NW NE NW NE", "SW W NE NW NE B SW SE SW SE", "B SW SE SW SE W NW NE B W", "W NW NE NW NE W SW W NE W", "NW W SE SW SE B W SW SE B", "SW SE B B W W NW NE NW NE", "B NW NE W B NW W SE SW SE", "NW W W NE W SW SE B NW NE", "SW W W SE B NW NE NW W SE", "B SW SE W W SW SE SW SE B", "", "W W W", "W W W", "W W W", "", "NW NE W", "SW SE W", "W W B", "", "B B B", "B B B", "B B B", "", "SE", "", "W NW", "NW W", "", "NW W SE", "", "W NW NE W", "NW W W NE", "SW W B SE", "W SW SE W", "", "B W", "W W", "", "W NW NE B", "NW W W NE", "SW SE SW SE" ].join('\n'); draw2();};
```

```
textarea { width: 400px; } #wrapper, .wrapper { border-left: 1px solid #555; border-top: 1px solid #555; margin-top: 10px; } .cell { float: left; width: 16px; height: 16px; border-right: 1px solid #555; border-bottom: 1px solid #555; overflow: hidden; } .NW { width: 0; height: 0; border-right: 16px solid #fff; border-top: 16px solid #00b496; } .SW { width: 0; height: 0; border-right: 16px solid #fff; border-bottom: 16px solid #00b496; } .NE { width: 0; height: 0; border-left: 16px solid #fff; border-top: 16px solid #00b496; } .SE { width: 0; height: 0; border-left: 16px solid #fff; border-bottom: 16px solid #00b496; } .W { width: 16px; height: 16px; } .B { width: 16px; height: 16px; background-color: #000; }
```

```
<textarea id="in" oninput="draw2()"></textarea><div id="out"></div>
```

---

### Truthy test cases

```
# The 10x10 puzzle solution above
NW NE W  W  B  W  NW NE NW NE
SW W  NE NW NE B  SW SE SW SE
B  SW SE SW SE W  NW NE B  W
W  NW NE NW NE W  SW W  NE W
NW W  SE SW SE B  W  SW SE B
SW SE B  B  W  W  NW NE NW NE
B  NW NE W  B  NW W  SE SW SE
NW W  W  NE W  SW SE B  NW NE
SW W  W  SE B  NW NE NW W  SE
B  SW SE W  W  SW SE SW SE B

# all white
W  W  W
W  W  W
W  W  W

# a diamond and some rectangles
NW NE W
SW SE W
W  W  B

# all black
B  B  B
B  B  B
B  B  B

```

### Falsy test cases

```
# a triangle
SE

# a larger triangle, with a valid white square
W  NW
NW W

# a parallelogram
NW W SE

# a slanted square with a black hole in the middle
W  NW NE W
NW W  W  NE
SW W  B  SE
W  SW SE W

# a region that contains two rectangles but is not a rectangle by itself
B  W
W  W

# same as above, but 45 degrees rotated
W  NW NE B
NW W  W  NE
SW SE SW SE

```

# Answer
> 14 votes
# Python 3.8 (pre-release), 179 bytes

```
lambda C:all({'','11','1'*4}>={*bin(65793*(a&3|c&12|d&48|b&192)).split("0")[2:-1]}for
i,j in p(C,[0]*len(C[0]))for(a,b),(c,d)in p([*zip(i,j)],(0,0)))
p=lambda l,d:zip([d]+l,l+[d])

```

Try it online!

mapping=`{'B': 0, 'W': 255, 'SE': 180, 'SW': 210, 'NW': 75, 'NE': 45}`

Mapping visualization:

The numbers are the bit position (least significant bit position is 0). Black has value 0, white has value 1. With this bit order, some simple bitmasking will give the state of the 8 triangles around a corner.

Use the method that I posted in chat.

Other key ideas for golfing:

* `65793 = 0x10101`.
* `{'','11','1'*4}>={*bin(65793*X).split("0")[2:-1]}` checks the condition with `X` a 8-bit number.

The function `p` returns the consecutive pairs in the list `l`, with the added first element `(d, l[0])` and last element `(l[-1], d)`.

# Answer
> 5 votes
# Python 3, ~~667~~ ~~554~~ ~~526~~ 461 bytes

*-49 bytes thanks to @ovs and @pppery*

```
C=eval(input())
N=next
E=enumerate
def F(x,y,f):
 try:1/-~x/-~y;c=C[y][x];(x,y)in v<Q;n[c]+=1;c&f<1<Q;C[y][x]=0;v[:0]=[(x,y)];[c>>i&1and F(x+i%2*(2-i),y+(i-1&~i),1<<(i^2))for i in(0,1,2,3)]
 except:1
while l:=[(x,y)for y,r in E(C)for x,e in E(r)if e]:
 a=0;v=[];n={k:0for k in range(16)};F(*l[0],15);a=len(v)+n[15];(len(v)!=n[15]or(N(M:=map(max,zip(*v)))-N(m:=map(min,zip(*v)))+1)*(N(M)-N(m)+1)!=a/2)and(a!=4*n[6]*n[12]or n[6]!=n[9]or n[3]!=n[12]or n[0]>0)and z

```

Try it online! (all testcases)

Throws NameError for false and doesn't throw for true.

Golf notes:

* `or` has a higher precedence than `and`

### Commented, Ungolfed

```
# bit order of a cell:
# truthy bit if that side is white(opeN)
#   0
# 3   1
#   2

# black: 0
# white: 15
# SE: 9
# SW: 3
# NW: 6
# NE: 12

# helper function to flood fill starting at (x,y)
# passes x,y position
# passes down mutable values
  # visited: array of coordinates visited
  # num_visited: dict counting how many of each cell type have been visited
def flood_solve(case, x, y, coming_from):
    global touched0, white_area, visited, num_visited
    # if out-of-bounds in the positive direction, this will throw
    try: c = case[y][x]
    except: return
    if (x,y) in visited: return
    # maybe can include touched0 into num_visited dict, then del num_visited[0] later
    # Keep track if the white region touches a full-black cell (0)
    touched0 = touched0 or c == 0
    # Check if this new cell is white on the side of the previous cell
    if not c & coming_from: return
    # Turn all visited cells to 0 to avoid flood-filling the same region
    case[y][x] = 0
    # Keep track of which cells are visited
    visited += [(x,y)]
    # Keep track of the counts of NE,NW,SE,and SW cells (3,6,9,12)
    num_visited[c] += 1
    # Keep track of the area of cells visited (1 for full-white, 0.5 for all else)
    if c != 15:
        white_area += 0.5
    else:
        white_area += 1
    # Flood recurse in each direction
    # Call flood_solve on (x,y-1) if (x,y) is white on its top side
    # Whether (x,y-1) is white on its bottom side is determined using coming_from
    if c & 1 and y>0: flood_solve(case, x, y-1, 4)
    if c & 2: flood_solve(case, x+1, y, 8)
    if c & 4: flood_solve(case, x, y+1, 1)
    if c & 8 and x>0: flood_solve(case, x-1, y, 2)
    return(visited, num_visited)

def solve(case):
    global touched0, white_area, visited, num_visited
    touched0 = False
    white_area = 0
    visited = []
    num_visited = {3:0,6:0,9:0,12:0,15:0}
    # Pick a cell with white
    for y,row in enumerate(case):
        for x,e in enumerate(row):
            if e > 0:
                # Floodfill whites from it
                # Pass 15 (0b1111) as coming_from since (x,y) can always be reached
                # Pass case mutably
                visited, num_visited = flood_solve(case, x, y, 15); break
                # (Maybe rectangular checks can be moved here to avoid looping by re-calling solve)
        # flooding always visits at least one cell, so visited is equivalent to the proposition
        # "A cell containing some white has already been found"
        if visited: break
    # Base case: if no white remains, then return True
    if not visited:
        return True
    v = list(zip(*visited))
    # v = [list of x positions visited, list of y positions visited]
    top_left = list(map(min, v))
    bottom_right = list(map(max, v))
    # If only entered all-white cells and area of bounding box of cells entered == area of cells entered:
    if len(visited)==num_visited[15] and (bottom_right[1] - top_left[1] + 1) * (bottom_right[0] - top_left[0] + 1) == white_area:
        # looks like an infinite recursion, but visited cells are replaced with 0 in flood_solve
        return solve(case)
    # If touched an all-black cell, can't be an angled rectangle, since angled rectangles only have angled sides
    if touched0:
        return
    n = num_visited
    # Should have #(NW entered)=#(SE entered) and #(NE)=#(SW)
    # (is this check redundant with the next area check? Maybe the area check can be rearranged by using area<=2*(perimeter/2)^?)
    if not n[6] == n[9] or not n[3] == n[12]:
        return
    if 2*n[6]*n[12] == white_area:
        # Success! it's an angled rectangle
        return solve(case)

```

### Pseudo-code algorithm

* Start
* Pick a cell with white; floodfill whites from it
    + (Base case: if no white remains, then return True)
    + While floodfilling:
        - Keep track of which cells are visited
        - Keep track of the counts of cells
        - Keep track if the white region touches a full-black cell (0)
        - Keep track of the area of cells visited (1 for full-white, 0.5 for all else)
        - Turn all visited cells to 0 to avoid flood-filling the same region
* If only entered all-white cells and area of bounding box of cells entered == area of cells entered:
    + Success! it's an upright rectangle.
    + GOTO Start; use the updated case (all visited cells turned black)
* If touched an all-black cell
    + Can't be an angled rectangle, since angled rectangles only have angled sides
    + return False
* Should have #(NW enetered)=#(SE entered) and #(NE)=#(SW) (is this check redundant with the next area check?)
* Each NW cell contributes sqrt(2) to the length of the NW side of the rectangle
* Each NE cell contributes sqrt(2) to the length of the NE side of the rectangle
* If area == 2\*#(NW)\*#(NE):
    + Success! it's an angled rectangle
    + GOTO Start; use the updated case (all visited cells turned black) White region filled can't be angled or upright rectangle anymore return False

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


title: Find the Pisano Period

text:
# Question
Title: Find the Pisano Period
The Fibonacci sequence is a well know sequence in which each entry is the sum of the previous two and the first two entries are 1. If we take the modulo of each term by a constant the sequence will become periodic. For example if we took decided to compute the sequence mod 7 we would get the following:

```
1 1 2 3 5 1 6 0 6 6 5 4 2 6 1 0 1 1 ...

```

This has a period of 16. A related sequence, called the Pisano sequence, is defined such that `a(n)` is the period of the fibonacci sequence when calculated modulo n.

## Task

You will should write a program or function that when given `n` will compute and output the period of the Fibonacci sequence mod `n`. That is the nth term in the Pisano sequence.

You must only support integers on the range `0 < n < 2^30`

This is a competition so you should aim to minimize the size of your source code as scored by bytes.

### Test cases

```
1  -> 1
2  -> 3
3  -> 8
4  -> 6
5  -> 20
6  -> 24
7  -> 16
8  -> 12
9  -> 24
10 -> 60
11 -> 10
12 -> 24

```

# Answer
> 11 votes
## GolfScript (28 25 24 23 chars)

```
~1.{(2$+}{.@+2$%}/+\-,)

```

Takes input in stdin, leaves it on stdout (or the stack, if you want to further process it...)

This correctly handles the corner cases (Demo).

As a point of interest to GolfScript programmers, I think this is the first program I've written with an unfold which actually came out shorter than the other approaches I tried.

# Answer
> 7 votes
### GolfScript, 24 characters

```
~:&1.{.2$+&%.2$(|}do](-,

```

Next iteration of a GolfScript implementation. The second version now also handles 1 correctly. It became quite long but maybe someone can find a way to shorten this version. You can try above version online.

# Answer
> 4 votes
# Python, ~~188~~ ~~132~~ ~~101~~ ~~95~~ 87 characters

```
n=input()
s=[]
a=k=0
b=1
while s[:k]!=s[k:]or k<1:s+=[a%n];k=len(s)/2;a,b=b,a+b
print k

```

## Usage

```
$ echo 10 | python pisano.py
60

```

For example:

```
$ for i in {1..50}; do; echo $i | python pisano.py; done
1
3
8
6
20
24
16
12
24
60
10
24
28
48
40
24
36
24
18
60
16
30
48
24
100
84
72
48
14
120
30
48
40
36
80
24
76
18
56
60
40
48
88
30
120
48
32
24
112
300

```

# Answer
> 4 votes
# Python ~~90~~ ~~85~~ ~~96~~ ~~94~~ ~~90~~ 82

```
n=input();c=[1,1];a=[]
while(c in a)<1%n:a+=[c];c=[c[1],sum(c)%n]
print len(a)or 1

```

Edit: Implemented suggestions by beary and primo

# Answer
> 2 votes
# Mathematica 73

```
p = {1, 0}; j = 0; q = p;
While[j++; s = Mod[Plus @@ p, n]; p = RotateLeft@p; p[[2]] = s; p != q]; j

```

# Answer
> 2 votes
## PHP - ~~61~~ 57 bytes

```
<?for(;1<$a.$b=+$a+$a=!$i+++$b%$n+=fgets(STDIN););echo$i;

```

This script will erroneously report `2` for `n=1`, but all other values are correct.

Sample I/O, a left-truncable series where π(n) = 2n + 2 :

```
$ echo 3 | php pisano.php
8
$ echo 13 | php pisano.php
28
$ echo 313 | php pisano.php
628
$ echo 3313 | php pisano.php
6628
$ echo 43313 | php pisano.php
86628
$ echo 543313 | php pisano.php
1086628
$ echo 4543313 | php pisano.php
9086628
$ echo 24543313 | php pisano.php
49086628

```

# Answer
> 2 votes
# Husk, 9 bytes

```
LU_2M`%İf

```

Try it online!

# Explanation

I'm not sure if I've ever used `U` with a negative argument before.

```
LU_2M`%İf  Implicit input, say n=8.
       İf  Infinite list of Fibonacci numbers:
             [1,1,2,3,5,8,13,21..
    M      Map
     `%    modulo n:
             [1,1,2,3,5,0,5,5,2,7,1,0,1,1,2..
 U_2       Cut at the start of first repeated sublist of length 2 (here [1,1]):
             [1,1,2,3,5,0,5,5,2,7,1,0]
L          Length: 12

```

# Answer
> 1 votes
## PowerShell: 98

**Golfed code:**

```
for($a,$b=0,(1%($n=read-host))){$x++;if($a+$b-eq0-or("$a$b"-eq10)){$x;break}$a,$b=$b,(($a+$b)%$n)}

```

---

**Ungolfed, with comments:**

```
for
(
    # Start with $a as zero, and $b as 1%$n.
    # Setting $b like this at the start helps catch the exceptional case where $n=1.
    $a,$b=0,(1%
    (
        # Grab user input for n.
        $n=read-host
    ))
)
{
    # Increasing the counter ($x) and testing for the end of the period at the start ensures proper output for $n=1.
    $x++;

    # Test to see if we've found the end of the Pisano Period.
    if
    (
        # The first part catches $n=1, since $a and $b will both be zero at this point.
        $a+$b-eq0-or
        (
            # A shorter way of testing $a-eq1-and$b-eq0, which is the end of a "normal" Pisano Period.
            "$a$b"-eq10
        )
    )
    {
        # Pisano Period has reached its end. Output $x and get out of the loop.
        $x;break
    }

    # Pisano Period still continues, perform operation to calculate next number.
    # Works pretty much like a Fibonacci sequence, but uses ($a+$b)%$n for the new $b instead.
    # This takes advantage of the fact we don't really need to track the actual Fibonacci numbers, just the Fibonacci pattern of %$n.
    $a,$b=$b,(($a+$b)%$n)
}

# Variable cleanup - not included in golfed code.
rv n,a,b,x

```

---

**Notes:**

I'm not sure exactly what the maximum reliable limit is for $n with this script. It's quite possibly less than 2^30, as $x could possibly overflow an int32 before $n gets there. Besides that, I haven't tested the upper limit myself because run times for the script already hit around 30 seconds on my system for $n=1e7 (which is only a bit over 2^23). For the same reason, I'm not quickly inclined to test and troubleshoot whatever additional syntax may be needed to upgrade the variables to uint32, int64, or uint64 where needed in order to expand this script's range.

---

**Sample output:**

I wrapped this in another for loop:

```
for($i=1;;$i++)

```

Then set `$n=$i` instead of `=read-host`, and changed the output to `"$i | $x"` to get an idea of the script's general reliability. Here's some of the output:

```
1 | 1
2 | 3
3 | 8
4 | 6
5 | 20
6 | 24
7 | 16
8 | 12
9 | 24
10 | 60
11 | 10
12 | 24
13 | 28
14 | 48
15 | 40
16 | 24
17 | 36
18 | 24
19 | 18
20 | 60

```

...

```
9990 | 6840
9991 | 10192
9992 | 624
9993 | 4440
9994 | 1584
9995 | 6660
9996 | 1008
9997 | 1344
9998 | 4998
9999 | 600
10000 | 15000
10001 | 10212
10002 | 3336
10003 | 5712
10004 | 120
10005 | 1680
10006 | 10008
10007 | 20016
10008 | 552
10009 | 3336
10010 | 1680

```

---

**Sidenote:** I'm not really sure how some Pisano Periods are significantly shorter than $n. Is this normal, or is something wrong with my script? Nevermind - I just remembered that, after 5, Fibonacci numbers quickly become *much* larger than their place in the sequence. So, this makes total sense now.

# Answer
> 1 votes
# Perl, ~~75~~, ~~61~~, 62 + 1 = 63

```
$k=1%$_;$a++,($m,$k)=($k,($m+$k)%$_)until$h{"$m,$k"}++;say$a-1

```

### Usage

```
$ echo 8 | perl -n -M5.010 ./pisano.pl
12

```

### Ungolfed

```
$k = 1 % $_;
$a++, ($m, $k) = ($k, ($m + $k) % $_) until $h{"$m,$k"}++;
say $a - 1

```

+1 byte for `-n` flag. Shaved off 13 bytes thanks to Gabriel Benamy.

# Answer
> 1 votes
# APL (Dyalog Extended), 21 bytes

```
{≢(⍵|1⌽+\)⌂traj⍵|1 1}

```

Try it online!

An anonymous function (dfn) that takes n as its right argument.

### How it works

```
{≢(⍵|1⌽+\)⌂traj⍵|1 1}  ⍝ Anonymous function; Input ⍵←n
{                1 1}  ⍝ Two ones (initial two values of Fibonacci)
               ⍵|      ⍝ Modulo n (to handle special case)
  (      )⌂traj        ⍝ Repeat and collect until the same value appears...
     1⌽+\              ⍝   (a,b) → (a+b,a)
   ⍵|                  ⍝   Modulo n
 ≢                     ⍝ Count the iterations before the same value appears

```

# Answer
> 0 votes
**Clojure, 102 bytes**

Not too exciting, iterates the formula until we reach back `[1 1]` (I hope this is always the case). Special handling of `(f 1)` as it converges to `[0 0]`.

```
#(if(< % 2)1(+(count(take-while(fn[v](not=[1 1]v))(rest(iterate(fn[[a b]][b(mod(+ a b)%)])[1 1]))))1))

```

# Answer
> 0 votes
# 05AB1E, 13 bytes

```
∞.Δ∞ÅfI%sô3£Ë

```

Try it online or verify all test cases.

**Explanation:**

```
∞.Δ            # Find the first positive integer which is truthy for:
   ∞           #  Push a positive infinite list
    Åf         #  Get the n'th Fibonacci number of each value `n` in this list
      I%       #  Take modulo the input on each Fibonacci number
        s      #  Swap so the current integer is at the top of the stack
         ô     #  Split the infinite modular Fibonacci list into parts of that size
          3£   #  Only leave the first 3 parts
            Ë  #  And check if all three sublist parts are the same
               # (after which the result is output implicitly)

```

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