title: Date Occurrences

text:
# Question
Title: Date Occurrences
Given three non-negative integers `y`, `m`, and `d` (of which at least one must be positive) and a valid date with a positive year (in any reasonable format that includes the year, month, and day, and no additional information), output the date that is `y` years, `m` months, and `d` days after the original date.

The Gregorian calendar is to be used for all dates (even dates prior to the adoption of the Gregorian calendar).

The method for computing the next date is as follows:

1. Add `y` to the year
2. Add `m` to the month
3. Normalize the date by applying rollovers (e.g. `2018-13-01` -\> `2019-01-01`)
4. If the day is past the last day of the month, change it to the last day in the month (e.g. `2018-02-30` -\> `2018-02-28`)
5. Add `d` to the day
6. Normalize the date by applying rollovers (e.g. `2019-01-32` -\> `2019-02-01`)

Leap years (years divisible by 4, but not divisible by 100 unless also divisible by 400) must be handled appropriately. All inputs and outputs will be within the representable integer range of your language.

# Test Cases

Test cases are provided in the format `input => output`, where `input` is a JSON object.

```
{"date":"2018-01-01","add":{"d":1}} => 2018-01-02
{"date":"2018-01-01","add":{"M":1}} => 2018-02-01
{"date":"2018-01-01","add":{"Y":1}} => 2019-01-01
{"date":"2018-01-30","add":{"M":1}} => 2018-02-28
{"date":"2018-01-30","add":{"M":2}} => 2018-03-30
{"date":"2000-02-29","add":{"Y":1}} => 2001-02-28
{"date":"2000-02-29","add":{"Y":4}} => 2004-02-29
{"date":"2000-01-30","add":{"d":2}} => 2000-02-01
{"date":"2018-01-01","add":{"Y":2,"M":3,"d":4}} => 2020-04-05
{"date":"2018-01-01","add":{"Y":5,"M":15,"d":40}} => 2024-05-11

```

You may use this JSFiddle for testing.

This is , so the shortest solution (in each language) wins.

# Answer
# C (gcc), 291 bytes

This one was pretty fun to get returning the same values as the JS builtin.

```
z,m=0xEEFBB3;int*y;g(){z=28+(m>>y[1]*2&3)+!(y[1]-1)*(!(*y%4)&&(*y%100)||!(*y%400));}h(a){z=(a>g())?g():a;}j(){*y+=y[1]/12;y[1]%=12;y[2]=h(y[2]);}f(int*a){y=a+6;for(z=0;z<3;z++)y[z]=a[z];y[1]--;j();*y+=a[3];y[1]+=a[4];j();y[2]+=a[5];for(;y[2]>h(y[2]);(y[1]=++y[1]%12)||++*y)y[2]-=g();y[1]++;}

```

Try it online!

Un-golfed:

```
// De No Oc Se Au Jl Jn Ma Ap Mr Fe Ja
// 31 30 31 30 31 31 30 31 30 31 28 31 = Month length
// 11 10 11 10 11 11 10 11 10 11 00 11 = Offset (2-bit representation)
//   E     E     F     B     B     3   = Hex representation

int m=0xEEFBB3; // Month lengths-28 in reverse order, stored as 2 bits/month
int *y; // Pointer to the output date, shared as a global between calls

// Regenerate month length and add leap day
int days_month(void) {
  return 28+(m>>y[1]*2&3)+!(y[1]-1)*(!(*y%4)&&(*y%100)||!(*y%400));
}

int calendar_day(int day) { return day>days_month()?days_month():day; }

void truncate_date(void) {
  *y+=y[1]/12; y[1]%=12;
  y[2]=calendar_day(y[2]);
}

void f(int *a) {
  int z;
  y=a+6;
  for(z=0;z<3;z++)y[z]=a[z];y[1]--; // Convert month to 0-based
  truncate_date();
  *y+=a[3]; y[1]+=a[4]; truncate_date();
  y[2]+=a[5];
  for(;y[2]>calendar_day(y[2]);(y[1]=++y[1]%12)||++*y)
    y[2]-=days_month();
  y[1]++; // Return month to 1-based
}

```

Try it online!
> 3 votes

# Answer
# perl -MDate::Calc=:all -E, 28 bytes

```
$,=$";say Add_Delta_YMD@ARGV

```

This takes 6 arguments: the input year, month and date (as separate arguments), and the number of years, months and days to add.
> 1 votes

# Answer
# , 88 bytes

```
function(Y,M,D,y,m,d,o=M+m){while(is.na(x<-ISOdate(Y+y+o%/%12,o%%12,D)))D=D-1;x+864e2*d}

```

Try it online!

A function that takes 3 arguments (`Y,M,D`) for the date, and other 3 arguments (`y,m,d`) for the values to be added.

The output comes with prepended `12:00:00 GMT` which is the default format for `ISOdate`'s
> 1 votes

# Answer
# Perl 6,  ~~60 50 45~~  44 bytes

```
{Date.new($^a).later(:$:year).later(:$:month).later(:$:day)}

```

Test it (60)
Input is `( "2000-02-29", year => 1, month => 0, day => 0 )`

---

```
{$^a.later(:$:year).later(:$:month).later(:$:day)}

```

Test it (50)
Input is `( Date.new("2000-02-29"), year => 1, month => 0, day => 0 )`

---

```
{$/=$^a;$/.=later(|$_) for |[R,] $^b.sort;$/}

```

Test it (45)
Input is `( Date.new("2000-02-29"), %( year => 1 ) )`
(No need to include keys with a value of 0)

---

```
{$/=$^a;$/.=later(|$_) for |[R,] %_.sort;$/}

```

Test it (44)
Input is `( Date.new("2000-02-29"), year => 1 )`

### Expanded:

```
{  # bare block lambda

  $/ = $^a; # store only positional param into a modifiable scalar
            # (params are readonly by default)

  # do a loop over the data to add

  $/ .= later(    # add using Date.later()
    |$_           # turn current iterated Pair into a named parameter
  )

    for

      |           # flatten so that `for` will iterate

        [R,]      # shorter than `reverse` (year=>1, month=>0, day=>0)

          %_.sort # sort the named arguments (day=>0, month=>0, year=>1)
  ;

  # return new Date
  $/
}

```
> 1 votes

# Answer
# C# (.NET Core), 48 bytes

```
(a,y,m,d)=>a.AddYears(y).AddMonths(m).AddDays(d)

```

Try it online!
> 1 votes

# Answer
# Java 8, 51 bytes

```
(s,y,m,d)->s.plusYears(y).plusMonths(m).plusDays(d)

```

Input (`s`) and output are both `java.time.LocalDate`.

Try it online.

**Explanation:**

```
(s,y,m,d)->        // Method with LocalDate and 3 int parameters and LocalDate return-type
  s.plusYears(y)   //  Add the years to the input start-Date
   .plusMonths(m)  //  Add the months as well
   .plusDays(d)    //  And add the days as well

```
> 1 votes

# Answer
# , 65 bytes

```
function(x,y){require(lubridate)
x%m+%period(y,c("ye","mo","d"))}

```

Uses the `lubridate` package. The `%m+%` infix operator is sugar for the `add_with_rollback` function which essentially implements what the question asks for.

TIO doesn't have `lubridate` so you can Try It Here Instead with `f <-` prepended to the function above along with test cases:

```
f(as.Date("2018-01-01"),c(0,0,1))
f(as.Date("2018-01-01"),c(0,1,0))
f(as.Date("2018-01-01"),c(1,0,0))
f(as.Date("2018-01-30"),c(0,1,0))
f(as.Date("2018-01-30"),c(0,2,0))
f(as.Date("2000-02-29"),c(1,0,0))
f(as.Date("2000-02-29"),c(4,0,0))
f(as.Date("2000-01-30"),c(0,0,2))
f(as.Date("2018-01-01"),c(2,3,4))
f(as.Date("2018-01-01"),c(5,15,40))

```
> 1 votes

# Answer
# Bash, ~~150~~ 149 bytes

```
a=$2+$5-1+b
y=$1+$4+a/12
m=1+a%12
d=date
$d -d@$[$($d +%s+$6*86400 -d$[y]-$[m]-$($d +$3%n%d -d@$[`b=1;$d +%s-86400 -d$[y]-$[m]-1`]|sort -n|head -1))]

```

Try it online!

Takes input via command line arguments in order: old year, old month, old day. year change, month change, day change. Outputs a string like `Wed Feb 28 00:00:00 UTC 2018` to stdout.
> 0 votes

# Answer
# PHP, 203 bytes

```
<?list(,$a,$y,$m,$d)=$argv;$b=new DateTime($a);$j=$b->format('j');$b->modify("+$y year +$m month");$j==$b->format('j')?:$b->modify('last day of last month');$b->modify("+$d day");echo$b->format('Y-m-d');

```

To run it:

```
php -n <filename> <date> <y> <m> <d>

```

Example:

```
php -n date_occurrences.php 2018-01-01 5 15 40

```

Or Try it online!

Tests: Try it online!
> 0 votes

# Answer
# T-SQL, 53 Bytes

```
SELECT DATEADD(D,d,DATEADD(M,m,DATEADD(Y,y,a)))FROM t

```

I'm not sure that it matters, but I'm applying the Year adjustment, followed by the Month adjustment, followed by the Day. All test values check out.

Per our IO standards, input is taken from a pre-existing table **t** with date field **a** and integer fields **y**, **m**, and **d**.

Note interestingly that it isn't the capitalization that matters between the *date type codes* (**D**, **M**, and **Y**) and my *input values* (**d**, **m**, and **y**) its simply the order of parameters in the SQL `DATEADD` function.
> 0 votes

---
Tags: code-golf, date
---


title: Manoeuvre the grid!

text:
# Question
Title: Manoeuvre the grid!
## Briefing

You are a bot, in a 2D grid that extends infinitely in all four directions, north, south, east and west. When given a number, you must move the bot so that you get to the target number.

Here's how the grid works:

You can move in 4 directions: north, south, east or west. Once you move off a cell, you are not allowed to go back to that cell again (so effectively, it's been wiped off the map).

There is a "counter", which goes `1234567890` (so it goes from `1` to `2`... all the way to `9`, then to `0`, then back to `1` again), which changes every time you move.

You also have a "value", which starts off at 0.

Once you move in any direction, a mathematical operation occurs, depending on what direction you move:

* North: Your value is increased by counter (`value += counter`).
* East: Your value is decremented by counter (`value -= counter`).
* South: Your value is multiplied by counter (`value *= counter`).
* West: Your value is divided by counter (`value /= counter`).
    + Division is integer division, so `5/2 -> 2`.
    + You are not allowed to divide by `0`.

Example:

If the bot moves north 3 times:

* The first "north" move increments the counter to `1`, and adds that to the value (which is now `1`).
* The second "north" move increments the counter to `2`, and adds that to the value (which is now `3`).
* The third "north" move increments the counter to `3`, and adds that to the value (which is now `6`).

The final value is `6`.

Move north, then south again:

* The first "north" move increments the counter to `1`, and adds that to the value (which is now `1`).
* The second "south" move errors, because the cell the bot is trying to move on is removed (from the first move).

There is no final value, because the bot errored.

## Challenge

Your challenge is to write a program when, given a number, produce the suitable directions for the bot to go in so that the final value of the bot is equal to that number.

So if the number is `6`, a valid solution to that would be:

```
nnn

```

(The bot moves north 3 times in a row).

Your test values are:

```
49445094, 71259604, 78284689, 163586986, 171769219, 211267178, 222235492, 249062828, 252588742, 263068669, 265657839, 328787447, 344081398, 363100288, 363644732, 372642304, 374776630, 377945535, 407245889, 467229432, 480714605, 491955034, 522126455, 532351066, 542740616, 560336635, 563636122, 606291383, 621761054, 648274119, 738259135, 738287367, 748624287, 753996071, 788868538, 801184363, 807723631, 824127368, 824182796, 833123975, 849666906, 854952292, 879834610, 890418072, 917604533, 932425141, 956158605, 957816726, 981534928, 987717553

```

(These are 50 random numbers from 1 to 1 billion.)

Your score is the total amount of moves made for all 50 numbers - the fewer moves, the better. In case of a tie, the person who submitted their code earlier wins.

## Specs

* You are guaranteed receive a positive integer for input.
* Your `value` variable must not go above `2^31-1` or below `-2^31` at any point for your generated paths.
* Your final program must fit in an answer (so, `< 30,000` bytes).
* You may only hard-code 10 numbers.
* Your program must run within 5 minutes on a reasonable laptop for any test case.
* The results MUST be the same every time the program is run for each number.

# Answer
# C++: score = 453,324,048

OK, needed some time to rework this, but here's the way I solved it.

After studying the solution space, I decided that my strategy would be:

1. Uses the south steps to get as close to the target number
    1. if the target is positive, follow this path: nnnesssssessssssss
    2. if the target is negative, follow this path: esssssssseessssss c. if the target is between 0 and 20, solve it "the old fashion way" (trail and error over every possible path til we reach it).
    3. Once we have our "best place" (get as close to the target, without going "over"), we may be able to get closer by multiplying by 2 or 3; so take between 0 to 9 steps east, and then one step south. keep the path that gets us the closest to the target.
    4. "Run" north, or east til we are within 45 points of the target (every 10 steps north, add 45 points to the score, like wise, every 10 steps east, reduces the score by 45).
2. Take a few more steps in the same direction, til we are within 10 points of the target
3. Do "the old fashion way" from this point, it shouldn't be that hard now.

Here's my result: total score is 453324048

And the paths:

```
  0) to reach   49445094, it takes   1311037 steps, by doing: nnnesssssesssssseeeeese(n *     1311010)enen
  1) to reach   71259604, it takes   1320313 steps, by doing: nnnesssssesssssseeeeeese(n *     1320280)nnnnnneee
  2) to reach   78284689, it takes   1956998 steps, by doing: nnnesssssesssssseeeeeees(e *     1956970)eeee
  3) to reach  163586986, it takes   2483885 steps, by doing: nnnesssssessssssse(n *     2483860)nnnnnnn
  4) to reach  171769219, it takes   4302163 steps, by doing: nnnesssssessssssse(n *     4302130)nnnnnnnnnnennnn
  5) to reach  211267178, it takes  13079485 steps, by doing: nnnesssssessssssse(n *    13079460)nnnnnen
  6) to reach  222235492, it takes  15516886 steps, by doing: nnnesssssessssssse(n *    15516860)nnnnnnnn
  7) to reach  249062828, it takes  12390325 steps, by doing: nnnesssssessssssseeees(e *    12390290)eeeeenenneene
  8) to reach  252588742, it takes  11606785 steps, by doing: nnnesssssessssssseeees(e *    11606760)een
  9) to reach  263068669, it takes   9277915 steps, by doing: nnnesssssessssssseeees(e *     9277880)eeeeenennneee
 10) to reach  265657839, it takes   8702543 steps, by doing: nnnesssssessssssseeees(e *     8702510)eeeeenennee
 11) to reach  328787447, it takes   5326312 steps, by doing: nnnesssssessssssseeeese(n *     5326280)nnnnennnn
 12) to reach  344081398, it takes   8724966 steps, by doing: nnnesssssessssssseeeese(n *     8724940)enn
 13) to reach  363100288, it takes  12951386 steps, by doing: nnnesssssessssssseeeese(n *    12951360)enn
 14) to reach  363644732, it takes  13072373 steps, by doing: nnnesssssessssssseeeese(n *    13072340)nnnnnnnnen
 15) to reach  372642304, it takes  15071833 steps, by doing: nnnesssssessssssseeeese(n *    15071800)nnnnnnnenn
 16) to reach  374776630, it takes  15546133 steps, by doing: nnnesssssessssssseeeese(n *    15546100)nnnnnenene
 17) to reach  377945535, it takes  16250331 steps, by doing: nnnesssssessssssseeeese(n *    16250300)nnnnennn
 18) to reach  407245889, it takes  11107325 steps, by doing: nnnesssssessssssseeeees(e *    11107300)ne
 19) to reach  467229432, it takes   2222403 steps, by doing: nnnesssssessssssseeeeese(n *     2222370)nnnnnnnee
 20) to reach  480714605, it takes   5219109 steps, by doing: nnnesssssessssssseeeeese(n *     5219080)neenn
 21) to reach  491955034, it takes   7716983 steps, by doing: nnnesssssessssssseeeeese(n *     7716950)nnnnennnn
 22) to reach  522126455, it takes  14421745 steps, by doing: nnnesssssessssssseeeeese(n *    14421710)nnnnnneneee
 23) to reach  532351066, it takes  16693875 steps, by doing: nnnesssssessssssseeeeese(n *    16693850)n
 24) to reach  542740616, it takes  14866179 steps, by doing: nnnesssssessssssseeeeees(e *    14866150)eeeen
 25) to reach  560336635, it takes  10955953 steps, by doing: nnnesssssessssssseeeeees(e *    10955920)eeeeennen
 26) to reach  563636122, it takes  10222731 steps, by doing: nnnesssssessssssseeeeees(e *    10222700)eeeeene
 27) to reach  606291383, it takes    743785 steps, by doing: nnnesssssessssssseeeeees(e *      743760)e
 28) to reach  621761054, it takes   2693968 steps, by doing: nnnesssssessssssseeeeeese(n *     2693940)nnn
 29) to reach  648274119, it takes   8585761 steps, by doing: nnnesssssessssssseeeeeese(n *     8585730)nnnnnn
 30) to reach  738259135, it takes   5286413 steps, by doing: nnnesssssessssssseeeeeees(e *     5286380)eeneneee
 31) to reach  738287367, it takes   5280141 steps, by doing: nnnesssssessssssseeeeeees(e *     5280110)nneenn
 32) to reach  748624287, it takes   2983042 steps, by doing: nnnesssssessssssseeeeeees(e *     2983010)eeeenee
 33) to reach  753996071, it takes   1789313 steps, by doing: nnnesssssessssssseeeeeees(e *     1789280)eeeennee
 34) to reach  788868538, it takes   5960183 steps, by doing: nnnesssssessssssseeeeeeese(n *     5960150)nnenene
 35) to reach  801184363, it takes   8697033 steps, by doing: nnnesssssessssssseeeeeeese(n *     8697000)nnenene
 36) to reach  807723631, it takes  10150197 steps, by doing: nnnesssssessssssseeeeeeese(n *    10150170)n
 37) to reach  824127368, it takes  13795475 steps, by doing: nnnesssssessssssseeeeeeese(n *    13795440)nnnnnnnne
 38) to reach  824182796, it takes  13807795 steps, by doing: nnnesssssessssssseeeeeeese(n *    13807760)nnnnnenee
 39) to reach  833123975, it takes  15794722 steps, by doing: nnnesssssessssssseeeeeeese(n *    15794690)nennnn
 40) to reach  849666906, it takes  14397917 steps, by doing: nnnesssssessssssseeeeeeees(e *    14397880)eeeeeeeenee
 41) to reach  854952292, it takes  13223389 steps, by doing: nnnesssssessssssseeeeeeees(e *    13223350)eeeeeeeeneeen
 42) to reach  879834610, it takes   7693981 steps, by doing: nnnesssssessssssseeeeeeees(e *     7693950)eeenn
 43) to reach  890418072, it takes   5342102 steps, by doing: nnnesssssessssssseeeeeeees(e *     5342070)eeennn
 44) to reach  917604533, it takes    699395 steps, by doing: nnnesssssessssssseeeeeeeese(n *      699360)nnnneene
 45) to reach  932425141, it takes   3992863 steps, by doing: nnnesssssessssssseeeeeeeese(n *     3992830)nennnn
 46) to reach  956158605, it takes   9266963 steps, by doing: nnnesssssessssssseeeeeeeese(n *     9266930)nnnnen
 47) to reach  957816726, it takes   9635434 steps, by doing: nnnesssssessssssseeeeeeeese(n *     9635400)nnnennn
 48) to reach  981534928, it takes  14906145 steps, by doing: nnnesssssessssssseeeeeeeese(n *    14906110)nnnnnnnn
 49) to reach  987717553, it takes  16280059 steps, by doing: nnnesssssessssssseeeeeeeese(n *    16280030)nn

```

I'm sure there's a way to improve on this by doing some cleaver "south/west" moves (dividing by 4 and multiplying by 5; for example); but coding it, and making sure you don't over lap or get trapped, is tricky.

Another solution path, may be to try to go back down from the target, to a "reasonable" number, and then, just find a path to that smaller number; but you'll have to "aim" it right, so that the step number will match. tricky, but might be the best way to solve this.

Anyway, here is my code code:

```
#include <stdio.h>
#include <vector>
#include <queue>;

using namespace std;

long long upperLimit;
long long lowerLimit;
bool bDebugInfo = false;
//bool bDebugInfo = true;

//  a point struct (x and y)
struct point
{
    int x;
    int y;

    point():x(0),y(0)
    {
    }

    bool operator ==(const point& other)
    {
        return (x==other.x) && (y==other.y);
    }

    void ApplyDirection(char direction)
    {
        switch (direction)
        {
        case 'n':
            y++;
            break;
        case 'w':
            x--;
            break;
        case 'e':
            x++;
            break;
        case 's':
            y--;
            break;
        }
    }
};

// each state is of this formate
struct botState
{
    int nStep;
    long long number;
    vector<char> path;

    botState()
        :nStep(0),
        number(0)
    {
    }

    botState* clone()
    {
        botState* tmp = new botState();
        tmp->nStep = nStep;
        tmp->number = number;
        tmp->path = path;
        return tmp;
    }

    void clone(botState* other)
    {
        nStep = other->nStep;
        number = other->number;
        path = other->path;
    }

};

bool changeNumberWithDirection(long long &number, char direction, int step)
{
    switch (direction)
    {
    case 'n':
        number += (step%10);
        break;
    case 'w':
        if (step%10)
            number /= (step%10);
        else
            return false;
        break;
    case 'e':
        number -= (step%10);
        break;
    case 's':
        number *= (step%10);
        break;

    default:
        return false;
    }

    return true;
}

bool tryToAddStep(queue<botState*>& queueOfStates, const botState* pState, char direction, char cStarDirection)
{
    botState* pTmpState;
    long long newNumber;
    int newStep = pState->nStep+1;

    newNumber = pState->number;
    if (!changeNumberWithDirection(newNumber, direction, newStep))
        return false;

    if (newNumber > upperLimit)
        return false;

    if (newNumber < lowerLimit)
        return false;

    if ((newNumber == 0) && (newStep%10 == 0))
        return false;                // no need to return back to 0 after 10 or more steps, we already have better ways to do this.

    // build the x,y points of the path up to this point
    point tmpPoint;
    vector<point> pointsInPath;
    pointsInPath.push_back(tmpPoint);

    for (int i=0; i<pState->path.size(); i++)
    {
        if (pState->path.at(i) == '*')
        {
            for (int j=0; j<100; j++)
            {
                tmpPoint.ApplyDirection(cStarDirection);
                pointsInPath.push_back(tmpPoint);
            }
        }
        else
        {
            tmpPoint.ApplyDirection(pState->path.at(i));
            pointsInPath.push_back(tmpPoint);
        }
    }

    tmpPoint.ApplyDirection(direction);

    // check for over lap
    for (int i=0; i<pointsInPath.size(); i++)
    {
        if (tmpPoint == (pointsInPath.at(i)))
            return false;
    }

    pTmpState = new botState();
    pTmpState->nStep = newStep;
    pTmpState->number= newNumber;
    pTmpState->path  = pState->path;

    pTmpState->path.push_back(direction);

    queueOfStates.push(pTmpState);

    return true;
}

bool isBetterNum(long long newNum, long long oldBest, long long target)
{
    long long newDiff = (newNum  > target) ? newNum  - target : target - newNum ;
    long long oldDiff = (oldBest > target) ? oldBest - target : target - oldBest;

    return (newDiff < oldDiff);
}

bool tryToJumpDown(long long num, botState* pState, int& nTimes)
{
    // if where the bot is, we have a clear path to go as far east as we could ever want, we can just do as many sets of eeeeeeeeee (e*10) as needed, til we are close enough to the target
    point tmpPoint;
    vector<point> pointsInPath;
    pointsInPath.push_back(tmpPoint);

    for (int i=0; i<pState->nStep; i++)
    {
        tmpPoint.ApplyDirection(pState->path.at(i));
        pointsInPath.push_back(tmpPoint);
    }

    for (int i=0; i<pointsInPath.size(); i++)
    {
        if ((pointsInPath.at(i).x > tmpPoint.x) && (pointsInPath.at(i).y == tmpPoint.y))
            return false;  // we have a point blocking our path up!
    }

    long long tmpTimes = (pState->number - num)/45;
    if ((tmpTimes>1) && (tmpTimes<upperLimit))
    {
        tmpTimes--;
        tmpTimes*=10;
        nTimes = (int)tmpTimes;
        pState->nStep+=nTimes;
        pState->number-=(tmpTimes/10)*45;
        pState->path.push_back('*');
        return true;
    }

    return false;
}

bool tryToJumpUp(long long num, botState* pState, int& nTimes)
{
    // if where the bot is, we have a clear path to go as far north as we could ever want, we can just do as many sets of nnnnnnnnnn (n*10) as needed, til we are close enough to the target
    point tmpPoint;
    vector<point> pointsInPath;
    pointsInPath.push_back(tmpPoint);

    for (int i=0; i<pState->nStep; i++)
    {
        tmpPoint.ApplyDirection(pState->path.at(i));
        pointsInPath.push_back(tmpPoint);
    }

    for (int i=0; i<pointsInPath.size(); i++)
    {
        if ((pointsInPath.at(i).x == tmpPoint.x) && (pointsInPath.at(i).y > tmpPoint.y))
            return false;  // we have a point blocking our path up!
    }

    long long tmpTimes = (num - pState->number)/45;
    if ((tmpTimes>1) && (tmpTimes<upperLimit))
    {
        tmpTimes--;
        tmpTimes*=10;
        nTimes = (int)tmpTimes;
        pState->nStep+=nTimes;
        pState->number+=(tmpTimes/10)*45;
        pState->path.push_back('*');
        return true;
    }

    return false;
}

typedef char* PChar;

bool buildPath(long long num, PChar& str, int& nLen, int& nScore, botState* startState, int nTimes)
{
    long long nBest = 0;
    int nMaxSteps = 0;
    long long nMax = 0;
    long long nMin = 0;
    int nCleanUpOnStep= 12;
    long long nFromLastCleanUp = 0;
    bool bInCleanUp = false;
    char cDirection = ' ';

    if (nTimes>0)
        cDirection = 'n';
    else if (nTimes<0)
    {
        cDirection = 'e';
        nTimes*=-1;
    }

    if (startState->nStep >= nCleanUpOnStep)
        nCleanUpOnStep= startState->nStep+10;

    str  = NULL;
    nLen = 0;
    botState* bestState = new botState();
    bestState->clone(startState);
    queue<botState*> queueOfStates;
    queueOfStates.push(bestState);  // put the starting state into the queue

    while (!queueOfStates.empty())       // while we still have states in the queue, process them
    {
        botState* pState = queueOfStates.front();
        queueOfStates.pop();             // take a state out of the queue

        if (!str)                        // no solution yet
        {
            if (pState->number == num)   // check if this is a solution
            {
                // we solved it!
                int nOffset=0;
                nLen = pState->nStep - nTimes + 17;
                str = new char[nLen+1];
                if (bDebugInfo)
                    printf("solved!\n");
                nScore = pState->nStep;
                for (int i=0; i<pState->path.size(); i++)
                {
                    if (pState->path.at(i)=='*')
                    {
                        sprintf(str+i, "(%c * %11d)", cDirection, nTimes);
                        if (bDebugInfo)
                            printf("(%c * %11d)", cDirection, nTimes);
                        nOffset=16;
                    }
                    else
                    {
                        str[i+nOffset] = pState->path.at(i);
                        if (bDebugInfo)
                            printf("%c", str[i+nOffset]);// print solution while making the string
                    }
                }
                if (bDebugInfo)
                    printf("\n");
                str[nLen]='\0';
            }
            else
            {                            // no solution yet, we need to go deeper
                if (pState->number < nMin)
                    nMin = pState->number;

                if (pState->number > nMax)
                    nMax = pState->number;

                if ((!bInCleanUp) && (queueOfStates.size()>1000000))
                {
                    nCleanUpOnStep=nMaxSteps+10;
                    bInCleanUp = true;
                }
                if (pState->nStep > nMaxSteps)
                {                        // a little tracing, so we can see progress
                    nMaxSteps = pState->nStep;
//                    printf("current states have %d steps, reached a max of %lld, and a min of %lld\n", nMaxSteps, nMax, nMin);
                    if (nMaxSteps >= nCleanUpOnStep)
                    {
                        nCleanUpOnStep+=10;
                        bInCleanUp = true;
                    }
                }

                if (isBetterNum(pState->number, nBest, num))
                {                        // a little tracing, so we can see progress
                    nBest = pState->number;
                    if (bDebugInfo)
                        printf("Got closer to the target, %lld, with %d steps (target is %lld, diff is %lld)\n", nBest, pState->nStep, num, num-nBest);
                    if (bestState != pState)
                        delete bestState;
                    bestState = pState;
                }

                if (!bInCleanUp)
                {
                    tryToAddStep(queueOfStates, pState, 'n', cDirection);
                    tryToAddStep(queueOfStates, pState, 'e', cDirection);

                    if (!nTimes)  // once we did the "long walk in one direction" don't do the west or south moves any more
                    {
                        tryToAddStep(queueOfStates, pState, 'w', cDirection);
                        tryToAddStep(queueOfStates, pState, 's', cDirection);
                    }
                }
            }
        }
        if (pState!=bestState)
            delete pState;                  // this is not java, we need to keep the memory clear.

        if ((bInCleanUp) && (queueOfStates.empty()))
        {
            queueOfStates.push(bestState);  // put the starting state into the queue
            bInCleanUp = false;
            long long diff = nFromLastCleanUp-bestState->number;
            if (!nTimes)
            {
                if ((diff>0) && (diff<100))
                    if (tryToJumpDown(num, bestState, nTimes))
                        cDirection = 'e';
                if ((diff<0) && (diff>-100))
                    if (tryToJumpUp(num, bestState, nTimes))
                        cDirection = 'n';

                if (nTimes)
                    nCleanUpOnStep = bestState->nStep;
            }
            nFromLastCleanUp = bestState->number;
        }
    }

    delete bestState;                  // this is not java, we need to keep the memory clear.
    return str!=NULL;
}

char* positiveSpine = "nnnesssssessssssss";
char* negativeSpine = "esssssssseessssss";

bool canReachNumber(long long num, PChar& str, int& nLen, int& nScore)
{
    int nTimes = 0;
    botState tmpState;
    if ((num>=0) && (num<=20))
        return buildPath(num, str, nLen, nScore, &tmpState, nTimes);

    botState bestState;
    bestState.clone(&tmpState);

    char* spine = NULL;
    if (num>0)
    {
        spine = positiveSpine;
    }
    else
    {
        spine = negativeSpine;
    }

    for (int i=0; spine[i]; i++)
    {
        tmpState.nStep++;
        tmpState.path.push_back(spine[i]);
        if (!changeNumberWithDirection(tmpState.number, spine[i], tmpState.nStep))
            return false;

        if ((num>0) && (tmpState.number<num))
        {
            bestState.clone(&tmpState);
        }
        else if ((num<0) && (tmpState.number>num))
        {
            bestState.clone(&tmpState);
        }
    }

    if (bestState.number == num)
        return buildPath(num, str, nLen, nScore, &bestState, nTimes);

    botState tryPath;
    tmpState.clone(&bestState);
    for (int i=0; i<9; i++)
    {
        tryPath.clone(&tmpState);
        bool pathOK = true;
        for (int j=0; j<i; j++)
        {
            tryPath.nStep++;
            tryPath.path.push_back('e');
            if (!changeNumberWithDirection(tryPath.number, 'e', tryPath.nStep))
            {
                pathOK = false;
                break;
            }
        }
        tryPath.nStep++;
        tryPath.path.push_back('s');
        if (!changeNumberWithDirection(tryPath.number, 's', tryPath.nStep))
        {
            pathOK = false;
            break;
        }

        if ((pathOK) && (isBetterNum(tryPath.number, bestState.number, num)))
        {
            bestState.clone(&tryPath);
        }
    }

    // in case we'll need to add, but last step was south, move one to the east.
    if ((bestState.path.at(bestState.path.size()-1) == 's') && (bestState.number<num))
    {
        bestState.nStep++;
        bestState.path.push_back('e');
        if (!changeNumberWithDirection(bestState.number, 'e', bestState.nStep))
            return false;
    }

    if (bestState.number<num)
    {
        long long diff = num - bestState.number;
        diff/=45;
        nTimes = (int)diff*10;
        bestState.nStep += nTimes;
        bestState.path.push_back('*');
        bestState.number += 45*diff;
        while (num - bestState.number > 10)
        {
            bestState.nStep++;
            bestState.path.push_back('n');
            if (!changeNumberWithDirection(bestState.number, 'n', bestState.nStep))
                return false;
        }
        return buildPath(num, str, nLen, nScore, &bestState, nTimes);
    }
    else
    {
        long long diff = bestState.number - num;
        diff/=45;
        nTimes = (int)diff*10;
        bestState.nStep += nTimes;
        bestState.path.push_back('*');
        bestState.number -= 45*diff;
        while (bestState.number - num > 10)
        {
            bestState.nStep++;
            bestState.path.push_back('e');
            if (!changeNumberWithDirection(bestState.number, 'e', bestState.nStep))
                return false;
        }
        return buildPath(num, str, nLen, nScore, &bestState, -nTimes);
    }

    return false;
}
long long aVals[] = {49445094, 71259604, 78284689, 163586986, 171769219, 211267178, 222235492, 249062828, 252588742, 263068669, 265657839, 328787447, 344081398, 363100288, 363644732, 372642304, 374776630, 377945535, 407245889, 467229432, 480714605, 491955034, 522126455, 532351066, 542740616, 560336635, 563636122, 606291383, 621761054, 648274119, 738259135, 738287367, 748624287, 753996071, 788868538, 801184363, 807723631, 824127368, 824182796, 833123975, 849666906, 854952292, 879834610, 890418072, 917604533, 932425141, 956158605, 957816726, 981534928, 987717553};

void main(void)
{
    upperLimit =     2147483647;       //  2^31 - 1
    lowerLimit =-1;       // -2^31
    lowerLimit *=2147483648;       // -2^31
    long long num=0;
    char* str=NULL;
    int nLen = 0;
    int nItems = sizeof(aVals)/sizeof(aVals[0]);
    int nScore = 0;
    long long nTotalScore = 0;
//  nItems=1;

    for(int i=0; i<nItems; i++)
    {
        if (canReachNumber(aVals[i], str, nLen, nScore))  //try to reach it
        {
            printf("%3d) to reach %10lld, it takes %9d steps, by doing: %s\n", i, aVals[i], nScore, str);

            nTotalScore+=nScore;
            delete str;
        }
        else
        {
            if (aVals[i]>0)
                printf("Failed to reach %lld, use nenenenenenen..... ('n', followed by %lld pairs of 'en')\n", aVals[i], aVals[i]-1);
            else
                printf("Failed to reach %lld, use enenenenenene..... ('e', followed by %lld pairs of 'ne')\n", aVals[i], aVals[i]-1);
            nTotalScore+=2*aVals[i]-1;
        }
    }

    printf("done, total score is %lld\n", nTotalScore);
    return;
}

```
> 3 votes

# Answer
# Python, Score = 56068747912

```
def move(n):
    print("n" + "en" * (n - 1))

```

Just prints `nenenenenenenen...` for every number.

Will add an explanation later.
> 2 votes

# Answer
# Rust, score = 1758 (optimal among paths with no west)

Runs in about 7 seconds total for 50 numbers, using a bidirectional search.

```
use std::collections::HashSet;
use std::io::{self, prelude::*};

#[derive(Debug, Eq, Clone, Copy, Hash, Ord, PartialEq, PartialOrd)]
enum Dir {
    N,
    E,
    S,
}
use Dir::{E, N, S};

fn dir_char(dir: Dir) -> char {
    match dir {
        N => 'n',
        E => 'e',
        S => 's',
    }
}

#[derive(Debug, Eq, Clone, Hash, Ord, PartialEq, PartialOrd)]
struct State {
    counter: i32,
    value: i32,
    next: Dir,
}

fn step(s: &State) -> impl Iterator<Item = State> {
    let (values, nexts): (_, &[Dir]) = match s.next {
        N => (s.value.checked_add(s.counter), &[N, E]),
        E => (s.value.checked_sub(s.counter), &[N, E, S]),
        S => (
            if s.counter != 0 {
                s.value.checked_mul(s.counter)
            } else {
                None
            },
            &[E, S],
        ),
    };
    let counter = (s.counter + 1) % 10;
    values.into_iter().flat_map(move |value| {
        nexts.iter().map(move |&next| State {
            counter,
            value,
            next,
        })
    })
}

fn unstep(s: &State) -> impl Iterator<Item = State> {
    let counter = (s.counter + 9) % 10;
    (match s.next {
        N | E => s.value.checked_sub(counter).map(|value| State {
            counter,
            value,
            next: N,
        }),
        _ => None,
    }).into_iter()
        .chain(s.value.checked_add(counter).map(|value| State {
            counter,
            value,
            next: E,
        }))
        .chain(match s.next {
            E | S if counter != 0 && s.value % counter == 0 => {
                s.value.checked_div(counter).map(|value| State {
                    counter,
                    value,
                    next: S,
                })
            }
            _ => None,
        })
}

fn search(value: i32) -> String {
    let mut lefts: Vec<HashSet<State>> = Vec::new();
    let mut left = [N, E, S]
        .iter()
        .map(|&next| State {
            counter: 1,
            value: 0,
            next,
        })
        .collect::<HashSet<_>>();
    let mut rights: Vec<HashSet<State>> = Vec::new();
    let mut right = (0..10)
        .map(|counter| State {
            counter,
            value,
            next: E,
        })
        .collect::<HashSet<_>>();
    loop {
        if let Some(mid) = left.intersection(&right).min() {
            let mut path = Vec::new();
            let mut mid1 = mid.clone();
            for left in lefts.into_iter().rev() {
                let mid2 = unstep(&mid1)
                    .filter(|mid2| left.contains(mid2))
                    .next()
                    .unwrap();
                mid1 = mid2;
                path.push(mid1.next);
            }
            path.reverse();
            let mut mid1 = mid.clone();
            for right in rights.into_iter().rev() {
                let mid2 = step(&mid1)
                    .filter(|mid2| right.contains(mid2))
                    .next()
                    .unwrap();
                path.push(mid1.next);
                mid1 = mid2;
            }
            return path.into_iter().map(dir_char).collect::<String>();
        }
        if left.len() <= right.len() {
            let left1 = left.iter().flat_map(step).collect::<HashSet<_>>();
            lefts.push(left);
            left = left1;
        } else {
            let right1 = right.iter().flat_map(unstep).collect::<HashSet<_>>();
            rights.push(right);
            right = right1;
        }
    }
}

fn main() {
    let stdin = io::stdin();
    let values = stdin
        .lock()
        .lines()
        .flat_map(|line| {
            line.unwrap()
                .split(", ")
                .map(|s| s.parse().unwrap())
                .collect::<Vec<i32>>()
        })
        .collect::<Vec<_>>();

    for value in values {
        println!("{} {}", value, search(value));
    }
}

```

Try it online!

### Output

```
49445094 nennesseseenenesseseeseseeeeseess
71259604 nnnnnnessennnessseeesssenesenesses
78284689 ennnesssseeeneenesenesssseeesese
163586986 ennnesesseneeeeessennesseeseseeneesen
171769219 ennnessenessssessseesesseeseenesee
211267178 sennnnneseeenessssenessssenenneseseee
222235492 ennnnnesseeeneseesseeesseseneesseesee
249062828 nnnnnesseneneseesssenennesseenesse
252588742 nennnessenneeeessesesesseseeseseeseee
263068669 nennnesseessseeessseesseeenesesssen
265657839 nnnesssseneesesssennneenesseeeses
328787447 eennnesssenesseesssesennnneeseenese
344081398 sennnnesennnesesessesesssseeseennnn
363100288 sennnnesseeneseesssenneesessennenee
363644732 nnnesssenneessesseeesseseseesenees
372642304 nnnnesseneseneseesseneneesssennesese
374776630 sennnnesseseesseneseeeseseessenesen
377945535 nnnesssseneeennesseesseeessseeses
407245889 nnnesseneesessseseseeeeessessenenee
467229432 nnnnesesennnnnesessesessesseeneess
480714605 nnnnessennneseesssenenesenesseesesen
491955034 nnnnnessseeneeeessseeeseenesseseeee
522126455 nnnnesssseeneeesesseesesseeeenese
532351066 nennnessenneeenesesesesessessesenesen
542740616 sennnnesseeneenesssesseenesseesesesen
560336635 nnnesssesesesssseeennessseseeneee
563636122 sennnnnesennneseseennesesssesenesenes
606291383 nnnessssenneeeseseseeseseeeeseesese
621761054 nnnessseennessesssenneeseseseess
648274119 nnnnessseneesseseeseenessseeneseeese
738259135 eennnnnesenennnesseneessssssennnees
738287367 nnnessesseessseseseneeesesseennen
748624287 nennnesseesseeenneseessseseeseneseseese
753996071 nnnnessseneeeseesssenesesenennnesesen
788868538 nnnessesseeseeeneeseesesseesseseeseee
801184363 ennnesseseeseeeeseseeeeseeseseessse
807723631 nnnessessessssesseennnnesssen
824127368 nnnnessesenessseseennnessseesesennnnn
824182796 nnnnessesenesssseenesssesssenesee
833123975 ennnnnneseeeennnessesssessseennnneeesse
849666906 sennnessseeeeseesesesssenesseneeeesen
854952292 nnnnnnesenenesssseeneeessessseseeeeeeee
879834610 nennnnesseessseneeseeesessseseneee
890418072 nnnesssennnnessesesennnesessennnnees
917604533 ennnnesseneeseeesesenennesesseeneesse
932425141 ennnnesssesseesesenesssessseeneesen
956158605 nnnnesseseeeeesesssennneseseenesseee
957816726 enennnesseseeseesseessessssenesss
981534928 eennnessennessseesseesessseenessseenn
987717553 nnnessseeneeesssesseesssesennessee

```
> 2 votes

# Answer
# PHP, Score=1391462099

```
function manoeuvre($n){
  $i=0;
  $c=0;
  $char='';
  while($i!=$n){
    $c=($c+1)%10;
    if($char!='n' and $c>0 and $i>0 and $i*$c<=$n){
      $char='s';
      $i=$i*$c;
    }
    else if($char!='s' and $i+$c<=$n and ($i-$c<=0 or ($i-$c)*max(($c+1)%10,2)>$n or $c==9)){
      $char='n';
      $i=$i+$c;
    }
    else{
      $char='e';
      $i=$i-$c;
    }
    echo $char;
  }
}

```

A quick attempt, never goes west to simplify path checking and has few rules to decide direction at each step.
> 0 votes

---
Tags: math, code-challenge
---


title: Make a hammer animation

text:
# Question
Title: Make a hammer animation
The goal is to make a two frame animation with ASCII art of a hammer smacking a table.

Trailing white-space is allowed and the frames need to repeat continuously. The program should iterate over both frames with a time of 0.5 seconds between frames.

Lowest byte count wins for each language!

**Sample:**

Animation Frames:

```
Frame 1:
 -------------------
|                   |
|                   |
|                   |
 -------------------
         /  /
        /  /
       /  /
      /  /
     /  /
    /  /
   /  /
  /  /
 /  /
 \ /

                        ---------------------------
                       |                           |

Frame 2:

                                        ----------
                                       |          |
                                       |          |
                                       |          |
 --------------------------------------|          |
|                                      |          |
 --------------------------------------|          |
                                       |          |
                                       |          |
                                       |          |
                                        ----------
                                  -------------------------------
                                |                                |

```

# Answer
## Perl 5, 391 355 293 286 296 bytes

Whack whack whack, golfing those chars off, down to 296 b :) .5s sleep as per the question specs.

This also requires perl -E

```
$r="| 19|n"x 3;$p="| 10|n";$R=" 39$p"x 3;$T=" -38$p";$t=" 40-10n";$m=" -19n$r -19n 9H 8H 7H 6H 5H 4H 3H 2H 2\\ /n3 24-27n 23| 27|n";$M="$t$R$T| 38$p$T$R$t 34-30n 33| 30|n";for($m){say"\033[2J";map{s:H:/  /n:;y!n!\n!;print$1x($2?$2:1)if/(\D+)(\d*)/}(split/(.\d*)/);($m,$M)=($M,$m);select$v,$V,$v,.5;redo}

```

Explanation/comments:

```
# initial vars build strings that the print will understand later
$r="| 19|n"x 3;
$p="| 10|n";
$R=" 39$p"x 3;
$T=" -38$p";
$t=" 40-10n";

# set $_ to first frame
$_=" -19n$r -19n 9H 8H 7H 6H 5H 4H 3H 2H 2\\ /n3 24-27n 23| 27|n";

# M is second frame
$M="$t$R$T| 38$p$T$R$t 34-30n 33| 30|n";

# main loop
{

# clear screen
say"\033[2J";

# or windows, -1b
# system"cls";

# start map...
map{

# sed replace H for /  /n
s:H:/  /n:;

# tr replace n for newline
y!n!\n!;

# parens around ?: necessary due to x operator precedence
# if/regex/ prints $1 $2 times
print$1x($2?$2:1)if/(\D+)(\d*)/

# map runs on char followed by a number or not
}(split/(.\d*)/);

# rotate frames
($_,$M)=($M,$_);

# sleep for 1 second would be shorter, but perl does
# not deal with integer sleep without time::hires
# sleep 1;

# select for decimal second sleep
select$v,$v,$v,.5;

# do the current block again
redo
}

```

GIF of original in action:
> 1 votes

# Answer
# Python 3, ~~337~~  ~~331~~ 319 bytes

-12 bytes thanks to Amphibological

```
import os,time
t,e,q,p='- \n|'
j=e+t*19+q
L=p+e*19+p+q
l=j+3*L+j
for i in range(9):l+=e*(9-i)+'/  /'+q
l+=' \\ /'+3*q+e*24+t*27+q+e*23+p+27*e+p+q
c=39*e
C=p+10*e+p+q
m=10*t+q
R=e+38*t+C
f=(c+C)*3
r=q+c+e+m+f+R+p+38*e+C+R+f+c+e+m+34*e+31*t+q+32*e+p+32*e+q
b=0
while 1:print([r,l][b]);time.sleep(.5);os.system('cls');b=~b

```

Try it online!

It uses 'cls', so will only work on Windows, use 'clear' for Linux with +2 bytes.

Will add a gif later.
> 2 votes

# Answer
# Python 3.6, 413 bytes

```
from os import*
from time import*
s,y=' -';b=y*19;d=b+b;f=y*10;i=y*26;g=s*9;c=s+g;h=s*26;j=s*32;a=c+g;e=a+a;p=print;k=f'\n|{a}|';t,v=system,sleep;z='cls'
while 1:
 t(z);p(f' {b} {k*3}\n {b}')
 for x in range(9):p(f'{g[x:]}/  /')
 p(f' \\ /\n {a} {i}\n {a}|{h}|');v(1);t(z);p(f' {e} {f}')
 for w in range(7):p(f' {e}|{c}|')if w!=3else p(f' {d}|{c}|\n|{e}|{c}|\n {d}|{c}|')
 p(f' {e} {f}\n {j} {i}\n {j}|{h}|');v(1)

```

Doesn't work on TIO, so here's a GIF:

Not the prettiest thing in the world, but I'm pretty proud of it. Suggestions on golfing it further are welcome!

P.S.: I used a 1 second delay because it looked better to me, but you can replace `1` with `.5` to change that, at +2 bytes.

P.P.S: This will only work on Windows, to try on Unix, change `cls` to `clear` at +2 bytes.
> 1 votes

---
Tags: code-golf, ascii-art, kolmogorov-complexity, animation
---


title: create an ascii progress bar

text:
# Question
Title: create an ascii progress bar
well, it's something similar to this question but with a little differences. you have to write a program to ask for width of progress bar and how much work is done. and then draw a progress bar with following features:

* width indicates how many characters you have to use to draw progress bar
* progress is given via a floating point value between 0..1.
* first and last character in progress bar should be something different from all other character, for example "\[" and "\]"
* your program should use two different characters to how much progress passed since the start
* you have to write how much work is done right in the middle of progress bar, using a decimal number + "%" sign.

**bonus point** for handling extreme inputs, such as 150% or -5% work done.

**scoring** number of characters * (1 without bonus or 0.75 width bonus)

**some examples of valid outputs**

```
79 0.15
[||||||||||||                         15%                                     ]

```

---

```
25 0.76
[##########76%#####.....]

```

---

```
39 -0.12
[                 -12%                 ]

```

---

```
25 7.6
[##########760%#########]

```

# Answer
> 3 votes
## PHP 84 x 0.75 = 63

Edit: A less 'pretty' version, but it should be valid according to the rules:

```
[<?=str_pad(!fscanf(STDIN,~Ú›Ú™,$a,$b),$a*min(1,$b),~ß)|str_pad(100*$b.~Ú,$a,_,2)?>]

```

Output:

```
$ echo 79 0.15 | php progress-bar.php
[⌂⌂⌂⌂⌂⌂⌂⌂⌂⌂⌂___________________________15%______________________________________]
$ echo 25 0.76 | php progress-bar.php
[⌂⌂⌂⌂⌂⌂⌂⌂⌂⌂⌂76%⌂⌂⌂⌂⌂______]
$ echo 39 -0.12 | php progress-bar.php
[_________________-12%__________________]
$ echo 25 7.6 | php progress-bar.php
[⌂⌂⌂⌂⌂⌂⌂⌂⌂⌂760%⌂⌂⌂⌂⌂⌂⌂⌂⌂⌂⌂]

```

### Original (98 x 0.75 = 73.5)

```
[<?=strtr(str_pad(!fscanf(STDIN,~Ú›Ú™,$a,$b),$a*min(1,$b),~ß)|str_pad(100*$b.~Ú,$a,~ü,2),~ü,~ß)?>]

```

Output:

```
$ echo 79 0.15 | php progress-bar.php
[###########                           15%                                      ]
$ echo 25 0.76 | php progress-bar.php
[###########76%#####      ]
$ echo 39 -0.12 | php progress-bar.php
[                 -12%                  ]
$ echo 25 7.6 | php progress-bar.php
[##########760%###########]

```

# Answer
> 4 votes
# J, 78×0.75 = 58.5

```
'w p'=:_".1!:1]3
1!:2&4('%',~":100*p)(i.@[-<.@-:@-)&#}'[]'0 _1}' |'{~(w*p)>i.w

```

```
$ echo -n 79 0.15 | jconsole test.ijs
[|||||||||||                          15%                                     ]
$ echo -n 25 0.76 | jconsole test.ijs
[||||||||||76%|||||     ]
$ echo -n 39 -0.12
[                 _12%                ]
$ echo -n 25 7.6 | jconsole test.ijs
[|||||||||760%||||||||||]

```

(Negative numbers in J are prefixed by `_`, not `-`. Luckily, dyadic `".` can parse both formats.)

# Answer
> 3 votes
# Perl, 96×¾ = 72

```
#!/usr/bin/perl -ap
formline'[@'.'|'x($F[0]-3).']',100*$F[1].'%';
$_=$^A;s# |(.)#$1//($-[0]<$F[0]*$F[1]?'|':$&)#eg

```

That's by traditional Perl golf rules (`#!` line not counted, except for the `-` and switches if any).

```
$ echo 79 0.15 | perl test.pl
[|||||||||||                          15%                                     ]
$ echo 25 0.76 | perl test.pl
[||||||||||76%|||||     ]
$ echo 39 -0.12 | perl test.pl
[                -12%                 ]
$ echo 25 7.6 | perl test.pl
[|||||||||760%||||||||||]

```

# Answer
> 2 votes
## Python - 158 155 148 143 138 characters (score of 103.5)

```
x,y=raw_input().split()
x=int(x)-2
y=float(y)
p=`int(y*100)`+"%"
b="|"*int(x*y+.5)+" "*x
print"["+b[:(x-len(p))/2]+p+b[(x+len(p))/2:x]+"]"

```

It could be 30 characters shorter if the input was separated by a comma.

# Answer
> 2 votes
### Ruby - score 93 (124 characters)

```
w=gets.to_i-2
f=$_[/ .+/].to_f
e=f<0?0:f>1?w:(f*w).to_i
b='#'*e+' '*(w-e)
b[(w-l=(s='%d%'%(100*f)).size)/2,l]=s
puts"[#{b}]"

```

Yet another ruby implementation. Reads input from STDIN in the form described above. You may exchange characters `'#'`, `' '` and `'['`, `']'` directly in the code.

```
45 0.88
[####################88%##############      ]

60 1.22
[###########################122%###########################]

```

# Answer
> 1 votes
### Scala 149:

```
val w=readInt
val p=readFloat
println(("["+"|"*(p*w).toInt+" "*((w-p*w).toInt)+"]").replaceAll("(^.{"+(w/2-3)+"}).{5}","$1 "+(p*100).toInt+("% ")))

```

ungolfed:

```
def progressbar (width: Int, pos: Double) {
  println ((
    "["+
    "|"*(pos*width).toInt+
    " "*((width-pos*width).toInt)+
    "]").
    replaceAll ("(^.{" + (width/2-3) + "}).{5}", "$1 " + (p * 100).toInt + ("% ")))}
}

```

I decided, for readability, you really need a space around the progress number:

```
(44 to 54).map (x => b (100, x/100.0))
[||||||||||||||||||||||||||||||||||||||||||||   44%                                                  ]
[|||||||||||||||||||||||||||||||||||||||||||||  45%                                                  ]
[|||||||||||||||||||||||||||||||||||||||||||||| 46%                                                  ]
[|||||||||||||||||||||||||||||||||||||||||||||| 47%                                                  ]
[|||||||||||||||||||||||||||||||||||||||||||||| 48%                                                  ]
[|||||||||||||||||||||||||||||||||||||||||||||| 49%                                                  ]
[|||||||||||||||||||||||||||||||||||||||||||||| 50%                                                  ]
[|||||||||||||||||||||||||||||||||||||||||||||| 51%                                                  ]
[|||||||||||||||||||||||||||||||||||||||||||||| 52% |                                                ]
[|||||||||||||||||||||||||||||||||||||||||||||| 53% ||                                               ]
[|||||||||||||||||||||||||||||||||||||||||||||| 54% |||                                              ]

```

# Answer
> 1 votes
# Q,90 chars, no bonus

```
{-1 @[x#" ";(1+(!)(_)x*y;0;((_)x%2)+(!)(#)($)a;x-1);:;("|";"[";a:,[;"%"]($)(100*y);"]")];}

```

usage

```
q){-1 @[x#" ";(1+(!)(_)x*y;0;((_)x%2)+(!)(#)($)a;x-1);:;("|";"[";a:,[;"%"]($)(100*y);"]")];}[50;0.15]
[|||||||                 15%                     ]

q){-1 @[x#" ";(1+(!)(_)x*y;0;((_)x%2)+(!)(#)($)a;x-1);:;("|";"[";a:,[;"%"]($)(100*y);"]")];}[30;0.35]
[||||||||||    35%           ]

q){-1 @[x#" ";(1+(!)(_)x*y;0;((_)x%2)+(!)(#)($)a;x-1);:;("|";"[";a:,[;"%"]($)(100*y);"]")];}[40;0.85]
[|||||||||||||||||||85%||||||||||||    ]

```

# Answer
> 1 votes
## C, 145 characters, score = 108.75

```
float p;s;m;char x[99];main(){scanf("%d%f",&s,&p);sprintf(x+s/2-1,"%.0f%%",p*100);for(;m<s;)x[++m]||(x[m]=m<p*s?35:32);x[s-1]=93;*x=91;puts(x);}

```

# Answer
> 1 votes
## JavaScript ~~127~~ 125, no bonus

```
l=9,p="0.99",f=l*p|0,m=l/2|0,x=["]"];for(;l--;)x.unshift(l>=f?"-":"+");x[m++]=p[2],x[m++]=p[3],x[m]="%";alert("["+x.join(""))
//[+++99%++-]

```

**Usage:** Change `l=9` with other *length* and/or change `p="0.99"` with other *percent*

<sub>**Note:** end with zero `0.X0` instead of `0.X`</sub>

# Answer
> 1 votes
## PHP-128x0.75=\>96

```
<?fscanf(STDIN,'%d%d',$w,$p);$v='[';for($i=1;$i<$w-1;)$v.=($i++==$w/2-1)?$p*($i+=2)/$i.'%':(($i<$w*$p/100)?'|':' ');echo"$v]";?>

```

```
<?fscanf(STDIN,'%d%f',$w,$p);$v='[';for($i=1;$i<$w-1;)$v.=($i++==$w/2-1)?$p*100*($i+=2)/$i.'%':(($i<$w*$p)?'|':' ');echo"$v]";?>

```

## C, 149\*0.75=111.75

```
main(w,i){float p;for(i=printf("[",scanf("%d%f",&w,&p));i<w-1;)(i++==w/2-1)?printf("%.0f%%",p*100*(i+=2)/i):printf("%c",i<=(p*w)?'|':' ');puts("]");}

```

Output:

```
80
0.75
[||||||||||||||||||||||||||||||||||||||75%||||||||||||||||||                   ]

80
7.60
[||||||||||||||||||||||||||||||||||||||760%|||||||||||||||||||||||||||||||||||||]

80
-0.12
[                                      -12%                                     ]

```

# Answer
> 1 votes
node.js: 135chars, \*0.75 for bonus points, so 101.25chars.

```
a=process.argv,i=a[2],p=a[3],o=i/2|0,f=i-i*p,x=['['];for(;i--;){x.push((i<f?' ':'|')+(i-o?'':p*100+'%'));}console.log(x.join('')+']');

```

ungolfed:

```
a = process.argv, // console inputs
i = a[2], // input 1 -> width
p = a[3], // input 2 -> percent complete
o = i / 2 | 0, // half of i, without any decimal places
f = i - i * p, // how far along the bar to draw spaces
x = ['[']; // start an array
while(i--){ // while i > 0
    x.push( // add to the array
    (i < f ? ' ' : '|') // a space, or | depending on how far along the bar we are
    + (i - o ? '' : p * 100 + '%')); // and if we're halfway, add the percentage complete
}
console.log(x.join('') + ']'); // then write out the array as a string, with a trailing ]

```

output:

```
D:\mercurial\golf\ascii>node progressBar.js 25 7.6
[|||||||||||||760%||||||||||||]

D:\mercurial\golf\ascii>node progressBar.js 39 -0.12
[                    -12%                   ]

D:\mercurial\golf\ascii>node progressBar.js 79 0.15
[|||||||||||                             15%                                       ]

```

# Answer
> 0 votes
# MATL, score 35.25 (47 * 0.75)

```
qqtl&O61bti*Xl:(HG100*V37hyn2/kyny+q&:(91w93v!c

```

Try it online!

### Explanation:

```
         % implicit input, say w = 79
qq       % decrement input by 2 (to allow brackets on either side)
tl&O     % duplicate and create array with that many zeros
61       % Push '=' character
b        % bubble up w-2 from below
ti*      % duplicate and multiply by second input, say p = 0.15
         %  stack: [[0;0;0;...;0], 61, 77, 11.55]
Xl       % take minimum of (w-2) and (w-2)*p
         %  (used when p > 1, makes eligible for bonus)
:        % create range 1 to that value
         %  stack: [[0;0;0;...;0], 61, [1 2 3 4 5 ... 11]]
(        % assign into the first array the value 61 ('=') at the
         %  indices denoted by the third array
HG       % push second input again
100*V    % multiply by 100 and convert to string
37h      % append the '%' symbol to it
yn2/k    % compute half of the length of the output array
yny+q    % copy of that + length of the 'N%' string - 1
         % stack: [[61;61;61;...;0;0;0], '15%', 38, 40]
&:       % make a range from the first to the second (38 to 40)
(        % assign the 'N%' string at those places into the output array
91w93    % surround by '[' (ASCII 91) and ']' (93) characters
v!       % combine into a single array, make it horizontal for display,
c        % change it to character type (implicitly displayed)

```

# Answer
> 0 votes
# Excel VBA, 108\*.75 = 81 bytes

A function that takes input from `[A1]` and `[B1]` and outputs to the console

```
s=""&[MID(IFERROR(REPT("",A1*B1),"")&REPT("",A1),2,A1-2)]&"":n=100*[B1]:Mid(s,([A1]-len(n))/2)=n &"%":?s

```

### Output

with input `[A1]=25` and `[B1]=.76`

```
76%

```

With input `[A1:B1].Resize(1,2)=Split("32 -.5")`

```
-50%

```

With input `[A1:B1].Resize(1,2)=Split("40 10.01")`

```
1001%

```

---
Tags: code-golf, printable-ascii
---


title: The Traveling Toothbrush

text:
# Question
Title: The Traveling Toothbrush
## Introduction

Today's challenge is all about teeth. Specifically, how long it takes to brush from one tooth to another. Your challenge is, given the locations of two teeth, output the shortest amount of time possible to brush from the first to the second.

## Challenge

For this challenge we will be using a layout of an average adult human mouth:

This diagram shows the widely used ISO numbering system. The system divides the mouth in four parts and assigns them each a number: upper right (1), upper left (2), lower left (3), and lower right (4). They then number the teeth of each section from the middle of the mouth out from 1-8. Therefore the fourth tooth from the center in the upper right side (section 1) is tooth number 14.

Let's assume brushing one tooth takes 1 unit of time. Moving from one tooth to the next one sideways takes 0 units of time. You can also cross from a tooth to the tooth directly above or below it, which also takes 1 unit of time. So how long does it take you to brush from tooth 14 to tooth 31? By looking at the diagram above, you will see it takes 7 units of time. Here is how that's calculated:

```
Action : Unit of time
Brushing tooth 14 : 1 unit
Brushing tooth 13 : 1 unit
Brushing tooth 12 : 1 unit
Brushing tooth 11 : 1 unit
Brushing tooth 21 : 1 unit
Cross to bottom of mouth : 1 unit
Brushing tooth 31 : 1 unit
------------------------------
Total: 7 units

```

Note his is not the only route we could have took, but there are no shorter routes.

So your challenge is:

* You will write a full program or function which accepts two arguments that are teeth numbers, and outputs (or returns) the shortest time to brush from one to the other.
* You make take input as numbers or strings, and output how ever you wish (within acceptable methods).
* Standard loopholes are forbidden by default.
* This question is , so shortest bytecount wins.
* Here are some testcases (*Thanks Jonathan Allan*):

```
14, 21 => 5
14, 44 => 3
14, 14 => 1
33, 37 => 5

```

Good luck!

# Answer
# Jelly,  ~~24~~  20 bytes

```
d30%20ị2¦⁵R;C$¤)ạ/Ḅ‘

```

A monadic link accepting a list of two integers (e.g. `[14,31]` for the from 14 to 31 example) which yields the brushing-time.

**Try it online!**

---

Previous 24 byter built the mouth and used base 8, input was a list of lists of digits:

```
8R;C$C+⁴U,+ɗ⁴
ḅ8¢œiⱮạ/Ḅ‘

```
> 3 votes

# Answer
## JavaScript (ES6), 65 bytes

```
f=([s,t],[u,v])=>s<3^u<3?f(s+t,5-u+v)+2:s-u?t-+-v:t<v?++v-t:++t-v

for(i=1;i<5;i++)for(j=1;j<9;j++){let o=document.createElement("option");o.text=""+i+j;s.add(o);t.add(o.cloneNode(true));}
```

```
<div onchange=o.textContent=f(s.value,t.value)><select id=s></select><select id=t></select><pre id=o>1
```

Takes input as strings.
> 5 votes

# Answer
# Python 2, 91 bytes

```
def f(a,b):A,B=a/10,b/10;return[abs(a-b)%10+1+2*(A!=B),a%10+b%10+2-(A+B)%2*2][A!=B!=A+B!=5]

```

Try it online!
> 1 votes

# Answer
# JavaScript (ES6), 67 bytes

```
([a,b],[x,y])=>(u=(a==x)+3*!(a+x-5))?Math.abs(b-y)+u:2*!(a-x&1)+b+y

```

Expects inputs as two 2-element arrays of digits. `12` -\> `[1, 2]` I hope this is acceptable.

Try it online!

Looks like a near duplicate to @Chas Brown's Python answer, so I can remove it if necessary (unsure of the conventions here).

# Explanation

```
var g =
([a,b], [x,y]) =>
    (u = (a == x)                // if same quadrant of mouth
     + 3 * !(a + x - 5))         // or strictly traversing vertically (e.g. 1 to 4, or 2 to 3)
        ? Math.abs(b - y) + u    // absolute difference plus additional units of time
        : 2 * !(a - x & 1)       // = 2 if traversing diagonally
            + b + y

```
> 1 votes

# Answer
# Python 2,  ~~80~~  78 bytes

Probably some golfing opportunities here still

```
lambda s,e,l=(range(11)+range(0,-9,-1))*2:abs(l[s%30]-l[e%30]+s/30*2-e/30*2)+1

```

An unnamed function accepting two integers, `s` and `e`, which returns the brushing-time.

**Try it online!**
> 1 votes

# Answer
# Clean, ~~134~~ ~~128~~ 126 bytes

```
import StdEnv
@n=hd[i\\i<-[0..]&k<-[18,17..11]++[21..28]++[48,47..41]++[31..38]|n==k]rem 16
$a b=abs(@a- @b)+a/30bitxor b/30+2

```

Try it online!

Defines the function `$ :: Int Int -> Int`, which just finds the distance between the two teeth as Cartesian coordinates. Pretty boring solution really.
> 0 votes

---
Tags: code-golf
---


title: Ex-Increasing Set Sequence

text:
# Question
Title: Ex-Increasing Set Sequence
# Background

An **ex-increasing set sequence** of order \\$N\\$ is defined as a sequence of integer sets \\$S\_1,S\_2,\cdots,S\_n\\$ which satisfies the following:

* Each \\$S\_i\\$ is a non-empty subset of \\$\\{1,2,\cdots,N\\}\\$.
* For \\$1\le i\<n\\$, \\$S\_i \cap S\_{i+1} = \varnothing\\$, i.e. any two consecutive sets have no elements in common.
* For \\$1\le i\<n\\$, the mean (average value) of \\$S\_i\\$ is strictly less than that of \\$S\_{i+1}\\$.

# Challenge

Given a positive integer `N`, output the length of the longest ex-increasing set sequence of order `N`.

# Test cases

These are based on the results by Project Euler user **thundre**.

```
1 => 1 // {1}
2 => 2 // {1} {2}
3 => 3 // {1} {2} {3}
4 => 5 // {1} {2} {1,4} {3} {4}
5 => 7 // {1} {2} {1,4} {3} {2,5} {4} {5}
6 => 10 // {1} {2} {1,4} {3} {1,4,5} {2,3,6} {4} {3,6} {5} {6}
7 => 15 // {1} {2} {1,4} {3} {1,2,7} {3,4} {1,2,5,7} {4} {1,3,6,7} {4,5} {1,6,7} {5} {4,7} {6} {7}
8 => 21
9 => 29
10 => 39
11 => 49
12 => 63
13 => 79
14 => 99
15 => 121
16 => 145
17 => 171
18 => 203
19 => 237
20 => 277
21 => 321
22 => 369
23 => 419
24 => 477
25 => 537

```

## Rules

Standard rules apply. The shortest valid submission in bytes wins.

# Bounty

This problem has been discussed here on Project Euler forum about 4 years ago, but we failed to come up with a provable polynomial-time algorithm (in terms of `N`). Therefore, I will award +200 bounty to the first submission that achieves this, or prove its impossibility.

# Answer
# Brachylog, 28 bytes

```
⟦₁⊇ᶠk⊇pSs₂ᶠ{c≠&⟨+/l⟩ᵐ<ᵈ}ᵐ∧Sl

```

Try it online!

This is really damn slow. Takes about 30 seconds for `N = 3`, and it didn't complete after 12 minutes for `N = 4`.

### Explanation

```
⟦₁                             Take the range [1, …, Input]
  ⊇ᶠk                          Find all ordered subsets of that range, minus the empty set
     ⊇                         Take an ordered subset of these subsets
      pS                       Take a permutation of that subset and call it S
       Ss₂ᶠ                    Find all substrings of 2 consecutive elements in S
           {           }ᵐ      Map for each of these substrings:
            c≠                   All elements from both sets must be different
              &⟨+/l⟩ᵐ            And the average of both sets (⟨xyz⟩ is a fork like in APL)
                     <ᵈ          Must be in strictly increasing order
                         ∧Sl   If all of this succeeds, the output is the length of L.

```

### Faster version, 39 bytes

```
⟦₁⊇ᶠk⊇{⟨+/l⟩/₁/₁}ᵒSs₂ᶠ{c≠&⟨+/l⟩ᵐ<₁}ᵐ∧Sl

```

This takes about 50 seconds on my computer for `N = 4`.

This is the same program except we sort the subset of subsets by average instead of taking a random permutation. So we use `{⟨+/l⟩/₁/₁}ᵒ` instead of `p`.

```
{         }ᵒ     Order by:
 ⟨+/l⟩             Average (fork of sum-divide-length)
      /₁/₁         Invert the average twice; this is used to get a float average

```

We need to get a float average because I just discovered a ridiculous bug in which floats and integers don't compare by value but by type with ordering predicates (this is also why I use `<ᵈ` and not `<₁` to compare both averages; the latter would require that double inversion trick to work).
> 4 votes

# Answer
## CJam (81 bytes)

```
{YY@#(#{{2bW%ee{)*~}%}:Z~{)Z__1b\,d/\a+}%$}%{_,1>{2ew{z~~&!\~=>}%0&!}{,}?},:,:e>}

```

Online demo. It should execute for input `4` in a reasonable time, but I wouldn't try it with higher inputs.

### Dissection

```
{                 e# Declare a block (anonymous function)
  YY@#(#          e# There are 2^N subsets of [0, N), but the empty subset is problematic
                  e# so we calculate 2^(2^N - 1) subsets of the non-empty subsets
  {               e# Map integer to subset of non-empty subsets:
    {             e#   Define a block to map an bitset to its set indices; e.g. 9 => [0 3]
      2bW%ee      e#     Convert to base 2, reverse, and index
      {)*~}%      e#     If the bit was set, keep the index
    }:Z           e#   Assign the block to variable Z
    ~             e#   Evaluate it
    {             e#   Map those indices to non-empty subsets of [0, N):
      )Z          e#     Increment (to skip the empty set) and apply Z
      __1b\,d/    e#     Sum one copy, take length of another, divide for average
      \a+         e#     Wrap the subset and prepend its average value
    }%
    $             e#   Sort (lexicographically, so by average value)
  }%
  {               e# Filter out subsets of subsets with conflicts:
    _,1>{         e#   If the length is greater than 1
      2ew         e#     Take each consecutive pair of subsets
      {           e#     Map:
        z~        e#       Zip and expand to get [score1 score2] [subset1 subset2]
        ~&!\      e#       No element in common => 1
        ~=        e#       Different scores => 0
        >         e#       1 iff both constraints are met
      }%
      0&!         e#     1 iff no consecutive pair failed the test
    }{
      ,           e#   Otherwise filter to those of length 1
    }?
  },
  :,:e>           e# Map to size of subset and take the greatest
}

```
> 3 votes

# Answer
# JavaScript (ES6), 175 bytes

A naive and rather slow recursive search. Takes about 15 seconds to compute the 7 first terms on TIO.

```
n=>(a=[...Array(n)].reduce(a=>[...a,...a.map(y=>[x,...y],x=n--)],[[]]),g=(p,b=a,n)=>a.map(a=>(m=a.map(n=>s+=++k*b.includes(n)?g:n,s=k=0)&&s/k)>p&&g(m,a,-~n),r=r>n?r:n))(r=0)|r

```

Try it online!

or test this modified version that outputs the longest ex-increasing set sequence.

### How?

We first compute the powerset of \\$\\{1,2,\dots,n\\}\\$ and store it in \\$a\\$:

```
a = [...Array(n)].reduce(a =>
  [...a, ...a.map(y => [x, ...y], x = n--)],
  [[]]
)

```

Recursive part:

```
g = (                         // g = recursive function taking:
  p,                          //   p = previous mean average
  b = a,                      //   b = previous set
  n                           //   n = sequence length
) =>                          //
  a.map(a =>                  // for each set a[] in a[]:
    (m = a.map(n =>           //   for each value n in a[]:
      s +=                    //     update s:
        ++k * b.includes(n) ? //       increment k; if n exists in b[]:
          g                   //         invalidate the result (string / integer --> NaN)
        :                     //       else:
          n,                  //         add n to s
      s = k = 0)              //     start with s = k = 0; end of inner map()
      && s / k                //   m = s / k = new mean average
    ) > p                     //   if it's greater than the previous one,
    && g(m, a, -~n),          //   do a recursive call with (m, a, n + 1)
    r = r > n ? r : n         //   keep track of the greatest length in r = max(r, n)
  )                           // end of outer map()

```
> 2 votes

# Answer
# Python 3, ~~205~~ ~~197~~ ~~184~~ 182 bytes

* Saved ~~eight~~ twenty-one bytes thanks to ovs.
* Saved two bytes thanks to ceilingcat.

```
f=lambda N,c=[[1]]:max([len(c)]+[f(N,c+[n])for k in range(N)for n in combinations(range(1,N+1),k+1)if not{*c[-1]}&{*n}and sum(c[-1])/len(c[-1])<sum(n)/len(n)]);from itertools import*

```

Try it online!
> 1 votes

---
Tags: code-golf, sequence
---


title: Scoring Briscola

text:
# Question
Title: Scoring Briscola
# Introduction

Briscola is one of Italy's most popular card games. It is a trick-taking card game, like Bridge. Briscola is well known for its bizarre point system. In this challenge, given two cards, you will output whether the first one scores more, less, or the same number of points as the second in Briscola's point system.

# Challenge

Briscola is played with a deck of Italian playing cards. There are forty cards in a deck, 1-10 in each of the four suits: cups, swords, clubs, and coins. We will be ignoring the suits for this challenge. Cards 2 - 7 are the numeric cards, and cards 8, 9, and 10 are the face cards. The ranking of the cards, from highest to lowest, are:

```
 +------------------------+-------------+
 |     Cards, by Rank     | Point Value |
 +------------------------+-------------+
 | Ace (1)                |     11      |
 | Three (3)              |     10      |
 | King (10)              |      4      |
 | Knight (9)             |      3      |
 | Jack (8)               |      2      |
 | Numeric Cards (2, 4-7) |      0      |
 +------------------------+-------------+

```

*Thanks to Orphevs for the nice table! :)*

Your task is to create a full program or function which accepts two numbers 1-10 representing card ranks, and outputs (or returns) whether the point value of the first card is greater than, lesser than, or equal to the point value of the second card. Additional Notes:

* Your program may output any three values to indicate less than, greater than, and equal to, however, it must output the same value for each condition each time.
* Your program may use any IO defaults.
* Standard loopholes are disallowed.
* Either a full function or a program is permitted.
* This question is , so lowest byte-count wins.
* Here are some sample inputs and outputs:

```
 1, 4 => more than (ace scores 11 points, 4 scores 0 points, first is  more than second.
 8, 3 => less than (8 scores 2, 3 scores 10, first is less than second.
 5, 2 => equal (5 and 2 both score 0)
```

If you have any questions, don't hesitate to ask. Good luck!

# Answer
> 2 votes
# Jelly, ~~12~~ 11 bytes

```
“®µ½¤¢‘iⱮIṠ

```

Try it online!

* -1 byte by using Luis Mendo's method.

Outputs `0` for equal, `-1` for greater than and `1` for less than. Uses the code-page index `“®µ½¤¢‘` which evaluates to `[8, 9, 10, 3, 1]`.

Takes input as a pair of cards. Use `1,2` as an example.

```
“®µ½¤¢‘iⱮIṠ
“®µ½¤¢‘       [8,9,10,3,1]
       i      index of
        Ɱ     each element in the input -> 5,0
         I    Finds the forward difference: 0-5 = -5.
          Ṡ   Sign -> -1.
                When ranks are equal, Ṡ returns 0 and when the rank of the second
                card is higher, Ṡ returns 1.

```

# Answer
> 5 votes
# JavaScript (ES6), 42 bytes

Takes the two ranks in currying syntax `(a)(b)`. Returns **1** for *more than*, **-1** for *less than* or **0** for *equal*.

```
a=>b=>Math.sign((s="05040000123")[a]-s[b])

```

Try it online!

---

# Using a formula, 48 bytes

This is definitely longer than using a lookup table but also a bit more interesting.

Same I/O format.

```
a=>b=>Math.sign((g=n=>(1<<n&1802)*6%13)(a)-g(b))

```

Try it online!

### How?

Because many cards have a value of \\$0\\$, we first want to mask them out. Given a card rank \\$n\\$, we compute:

$$p=2^n\text{ and }(2^1+2^3+2^8+2^9+2^{10})$$ $$p=2^n\text{ and }1802$$

```
  n (card)   | 2**n | AND 1802
-------------+------+----------
  1 (Ace)    |    2 |      2
  2          |    4 |      0
  3 (Three)  |    8 |      8
  4          |   16 |      0
  5          |   32 |      0
  6          |   64 |      0
  7          |  128 |      0
  8 (Jack)   |  256 |    256
  9 (Knight) |  512 |    512
 10 (King)   | 1024 |   1024

```

We now want to transform the remaining non-zero values in such a way that they can be sorted in the correct order. We use:

$$q=6p \bmod 13$$

```
    p (card)   |   6p | MOD 13
---------------+------+--------
    2 (Ace)    |   12 |   12
    8 (Three)  |   48 |    9
  256 (Jack)   | 1536 |    2     --> Ace > Three > King > Knight > Jack
  512 (Knight) | 3072 |    4
 1024 (King)   | 6144 |    8

```

# Answer
> 5 votes
# MATL, 12 bytes

```
[DEXIl]&mdZS

```

Input is an array of two numbers. Output is `-1`, `0` and `1` respectively for *more than*, *equal to* or *less than*.

Try it online!

### Explanation

Consider input `[1 4]` as an example.

```
[DEXIl]    % Push [8 9 10 3 1]
           % STACK: [8 9 10 3 1]
&m         % Implicit input. Index (1-based) of membership, 0 if not member
           % STACK: [5 0]
d          % Consecutive difference
           % STACK: -5
ZS         % Sign. Implicit display
           % STACK: -1

```

# Answer
> 3 votes
# Japt, ~~25~~ ~~21~~ 16 bytes

* 1 =\> *more than*
* -1 =\> *less than*
* 0 =\> *equal*

---

```
£"78920"bXÉÃr- g

```

Try it online!

# Answer
> 3 votes
# Japt `-g`, 13 bytes

Outputs `-1` for `>`, `1` for `<` and `0` for `===`.

```
m!b#ù991ìD)rn

```

Try it or run multiple tests (The second line replicates the functionality of the `-g` flag to allow the flags to be used to process multiple inputs)

---

## Explanation

```
                   :Implicit input of 2 integer array
m                  :Map
   #ù991           :  249991
        ìD         :  Convert to array of base-13 digits = [8,9,10,3,1]
 !b                :  Get the index of the current element in that
          )        :End map
           rn      :Reduce by subtraction
                   :Implicitly output the sign of the result

```

# Answer
> 2 votes
# , 35 bytes

```
rank(c(6,0,5,1:4*0,1:3)[scan()])[1]

```

Try it online!

* -6 Bytes thanks to @JayCe suggestion to switch to full program instead of function

The program returns `2` for `'greater than'`, `1` for `'less than'`, `1.5` for `'equal'`

**Explanation :**

```
      c(6,0,5,1:4*0,1:3)[v]          # extract the score of each card in v (got from scan());
                                     # cards in v are used as indexes in the cards rank
                                     # vector, which is based on briscola scores vector
                                     # c(11,0,10,0,0,0,0,2,3,4) but divided by 2 and rounded
                                     # to integer preserving the original order

rank(                      )[1]      # rank returns : c(1,  2)   if v[1] < v[2]
                                     #                c(2,  1)   if v[1] > v[2]
                                     #                c(1.5,1.5) if v[1] == v[2]
                                     # and we select the first value

```

# Answer
> 2 votes
# Java 8, ~~69~~ 66 bytes

```
a->b->Math.signum("05040000123".charAt(a)-"05040000123".charAt(b))

```

Lambda taking parameters in currying syntax, port of Arnauld's JavaScript answer.

Returns `0.0` *equal*, `1.0` for *greater than*, and `-1.0` for *less than*. Try it online here.

Thanks to Kevin Cruijssen for golfing 3 bytes.

# Answer
> 2 votes
# MarioLANG, 578 548 530 bytes

```
 )                    <
 ====================="
                   >-[!)
                   "==#)
                >-[!)) )
                "==#=) +
         >-----[!))) + +
         "======#==  + +
     >--[!)))   ++++              -(- <
     "===#===================    ====="
  >-[!)))+++++                    >) [!)+:
; "==#=======================     "===#===
>[!                      )))[!((>[!)[!):
"=#==========================#====#==#===
!;((                         <       >)-:
#============================"       "===

```

Try it online!

Explanation:

* The first, big *castle* reads a card number as input and calculates its equivalent point value until it reads a `0` (no input). This supposes that there will be only two strictly positive values as input.
* Note that I don't actually set the proper point values as they aren't needed, I just set as point value a number between `[1-5]` to help calculate which card has the most point values.
* The second, small *castle* just compares the two calculated point values.
* It returns `1` if the first point value is greater than the second one, `-1` if the second point value is greater than the first one, and `0` if the point values are the same.

# Answer
> 1 votes
# Python 2, 41 bytes

Outputs 1 for more than, -1 for less than, 0 for equal.

```
lambda a,b:cmp(s[a],s[b])
s="05040000123"

```

Try it online!

# Answer
> 1 votes
# C (gcc), 57 bytes

Returns the usual \[-1..1\] for \<, = and \>, respectively.

```
char*s="-FAEAAAABCD";f(a,b){a=s[a];b=s[b];b=(a>b)-(a<b);}

```

Try it online!

# Answer
> 1 votes
# PHP, ~~51~~ 45 bytes

```
<?=($m=_5040000123)[$argv[1]]<=>$m[$argv[2]];

```

Try it online!

To run it:

```
php -n <filename> <card1> <card2>

```

Example:

```
php -n briscola_score.php 3 1

```

**Note:** This code uses PHP 7's spaceship operator. So it won't work on any PHP version before 7.

---

# Output:

* 1 = more than (`card1 > card2`)
* 0 = equal (`card1 == card2`)
* -1 = less than (`card1 < card2`)

---

# How?

Same as the approach used in many other answers, but in PHP. Creates a value map for cards and compares the card values from it. The position of the value in the map is same as card number.

# Answer
> 1 votes
# 05AB1E, 14 bytes

```
ε78920S>sk}`.S

```

Returns `1`, `-1`, or `0` for more than; less than; or equal respectively.

Try it online or verify all test cases.

**Explanation:**

```
ε              # Loop over the input-array
 78920S>       #  Convert 78920 to a list of digits, and increase each by 1,
               #  resulting in [8,9,10,3,1]
        sk     #  Index this list with the input-number (-1 if not found)
               #   i.e. [1,4] → [4,-1]
          }    # Stop the loop
`              # Put all items of the now mapped list separated onto the stack
 .S            # Take the signum (1 if a>b; -1 if a<b; 0 if a==b)
               #  i.e. 4 and -1 → 1

```

# Answer
> 0 votes
# Javascript ES2016+, 73 chars

Not the shortest, but I hope interesting due to math and overflow :)

```
(x,y)=>Math.sign((x&8?x:(16-(x**40|0)%7)^16)-(y&8?y:(16-(y**40|0)%7)^16))

```

And the other version with 74 chars, unfortunately:

```
(x,y)=>eval('(x>y)-(x<y)'.replace(/\w/g,'($&&8?$&:(16-($&**40|0)%7)^16)'))

```

## Test

Open browser console before running

```
f=(x,y)=>Math.sign((x&8?x:(16-(x**40|0)%7)^16)-(y&8?y:(16-(y**40|0)%7)^16))
console.table(Array(11).fill().map((x,i)=>Array(11).fill().map((x,j)=>f(i,j))))
```

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