title: Plan your Sundays!

text:
# Question
Title: Plan your Sundays!
Who doesn't like to chill on a Sunday morning in summer with a chilled beer and TV or in winter playing badminton or ultimate with friends?

I always think knowing how many days you have to chill in a month keeps you well-informed and helps you plan what you want to do. Be it sitting in front of your pc and solving a code-golf problem or going out to play football.

So, help me write a program or function which takes as input 2 positive integers, `Y` and `M` and outputs the number of Sundays in that particular year(`Y`) and month(`M`) (according to the Gregorian Calendar), followed by the date of each Sunday.

Also, do keep in mind that the shortest code wins.

## Input Constraints

1000 \<= Y \<= 9999

1 \<= M \<= 12

## Output

These test cases will have output will have the dates of each Sunday of that month in that year in the format `DD-MM-YYYY`.

# Sample Test Cases

## Test Case 1

Sample Input

```
2017 1

```

Sample Output

```
5
01-01-2017
08-01-2017
15-01-2017
22-01-2017
29-01-2017

```

## Test Case 2

Sample Input

```
2018 2

```

Sample Output

```
4
04-02-2018
11-02-2018
18-02-2018
25-02-2018

```

## Test Case 3

Sample Input

```
2016 11

```

Sample Output

```
4
06-11-2016
13-11-2016
20-11-2016
27-11-2016

```

# Answer
> 0 votes
# MATL, ~~46~~ ~~45~~ ~~42~~ 35 bytes

```
8BhtYOw47B~+YOq&:t8XO!s310=)tnw24XO

```

Input is an array of the form `[2017 1]`. Output format is `29/01/2017`.

Try it online! Or verify all test cases.

### Explanation

```
8B       % Push [1 0 0 0] (8 in binary)
h        % Implicit input. Concatenate. Gives something like [2017 1 1 0 0 0],
         % corresponding to the first day of input year and month
tYO      % Duplicate. Convert to serial date number
w        % Swap
47B~     % Push [0 1 0 0 0 0] (47 in binary, then negated)
+        % Add. Gives something like [2017 2 1 0 0 0]: first day of next month
YO       % Convert to serial number
q        % Subtract 1. This corresponds to last day of input month
&:       % Binary range. Gives an array with 28, 29, 30 or 31 days
t8XO     % Duplicate. Convert each number to three letters telling day of the week
!s       % Transpose, Sum of each column
310=     % True for values that equal 310, which is the sum of 'Sun' in ASCII
)        % Apply as a logical index
tnw      % Duplicate, number of elements, swap. This is the first part of output
24XO     % Convert to date format 'dd/mm/yyyy'. Gives 2D char array. Implicit display

```

# Answer
> 4 votes
## JavaScript (ES6), 107 bytes

```
f=
(y,m,a=[...Array(32)].map((_,i)=>new Date(y,m-1,i)).filter(d=>d.getMonth()==m-1&!d.getDay()))=>[a.length,a]
```

```
<div oninput=o.textContent=[].concat(...f(y.value,m.value)).map((d,i)=>i?d.toDateString():d).join`\n`><input id=y type=number min=1000 max=9999 value=2017><input id=m type=number min=1 max=12><pre id=o>
```

Edit: Adding an explicit count cost 15 bytes. Formatting the output would cost at least another 33 bytes depending on how strict the output format is.

# Answer
> 4 votes
# Python 2, ~~150,148,~~145 bytes

```
from calendar import*
y,m=map(int,input().split())
z=filter(None,zip(*monthcalendar(y,m))[6])
print len(z)
for i in z:print'%02d-%02d-%s'%(i,m,y)

```

Try it online!

-3 bytes making stuff more pythonic (using zip and filter!)

# Answer
> 2 votes
# PowerShell, 91 bytes

```
param($y,$m)($a=(1..31|%{Date "$m/$_/$y"}|?{!$_.dayofweek})).count;$a|%{"{0:d-M-yyyy}"-f$_}

```

Try it online!

*(Special note - this is locale and culture settings dependent. Since TIO is running as `en-us`, it works correctly there as-is. This code may need to be changed for different locales.)*

Takes input as two integers `$y` and `$m`. Loops from `1` to `31`, getting a new `datetime` object for each possible date (via the `Get-Date` cmdlet). Will toss errors to STDERR (ignored by default on code-golf challenges) for months with fewer than 31 days, but that doesn't affect output. We take each of those `datetime` objects and use a `Where-Object` (`|?{...}`) on them, with the clause of `!$_.dayofweek`. The property `.dayofweek` is a number from `0` to `6`, with `0` conveniently corresponding to `Sunday`, so the `!` of that is truthy, which saves a couple bytes compared to an equality check like `-eq0`.

The Sundays are then gathered in parens and stored into `$a`. We then take the `.count` thereof, and that's placed on the pipeline. Next, we loop through `$a` and use the `-f`ormat operator to construct the correct output format. Note that this doesn't output leading zeros for days or months. Those date strings are also left on the pipeline, and an implicit `Write-Output` at program completion prints them with newline separators.

---

NB - if the output format was more flexible, we could just leave `$a` on the pipeline and not need to loop through it. That will stringify the `datetime` objects as the long-date format including time information, but gets us down to 69 bytes, which would (currently) only be beaten by Mathematica and MATL.

# Answer
> 1 votes
# Octave, 72 bytes

```
@(y,m)cellfun(@disp,flip({datestr(x=nweekdate(1:6,1,y,m)(x>1)),nnz(x)}))

```

`nweekdate` returns the date number corresponding to the `N`-th occurrence of a particular weekday in the specified month/year. We use the array `1:6` in place of `N` to get *all* occurrences in a month. If there are fewer than `N` occurrences of that weekday in a month, then the resulting date number is `0`. For this reason, we select only the valid dates using `(x>1)` and then convert them to strings using `datestr`.

Then to count the number of Sundays, we count the number of non-zero (`nnz`) date numbers in the result.

We then wrap the entire thing in `cellfun` to display each value.

# Answer
> 0 votes
# Mathematica, ~~82~~ 68 bytes

```
d=DateObject;{Length[x=DayRange[d@{#,#2,1},d@{#,#2+1,0},Sunday]],x}&

```

Anonymous function. Outputs a list of the number of days, followed by a list of the Sundays as `DateObject`s. Turns out, in Mathematica the 0th day of a month is interpreted as the last day of the previous month.

# Answer
> 0 votes
# Ruby, ~~140~~ ~~132~~ ~~129~~ 118 bytes

```
require'date'
d=Date.parse gets.split*?-+'-1'
s=(d...d>>1).select &:sunday?
puts s.size,s.map{|d|d.strftime'%d-%m-%Y'}

```

# Answer
> 0 votes
# Excel – 103 characters

Put the year in cell `A1`, and month in cell `A2`.

The count is in cell `D1`, and Sundays in cells `D2:D6`.

Assumes `D2:D6` are formatted DD-MM-YYYY.

```
   A      B       C              D
1  [year] [month] =DATE(A1,B1,1) =COUNTIF(D2:D7,">0")
2                                =C1+7-WEEKDAY(C1,2)
3                                =D2+7
4                                =D3+7
5                                =D4+7
6                                =IF(MONTH(D5+7)=MONTH(C1),D5+7,"")

```

# Answer
> 0 votes
# C#, 183 bytes

```
y=>m=>{var s=new string[6];int i=1,n=0;for(DateTime d;i<=DateTime.DaysInMonth(y,m);)if((int)(d=new DateTime(y,m,i++)).DayOfWeek<1)s[++n]=d.ToString("dd-MM-yyyy");s[0]=n+"";return s;};

```

Anonymous method which returns an array of string, containing first the number of Sundays and then each Sunday in the specified format. If there are only 4 Sunday in a month, the last string is null.

Full program with ungolfed method and test cases:

```
using System;

class P
{
    static void Main()
    {
        Func<int, Func<int, string[]>> f =
        y=>m=>
        {
            var s=new string[6];
            int i=1,n=0;
            for(DateTime d;i<=DateTime.DaysInMonth(y,m);)
                if((int)(d=new DateTime(y,m,i++)).DayOfWeek<1)
                    s[++n]=d.ToString("dd-MM-yyyy");

            s[0]=n+"";
            return s;
        };

        // test cases:
        var result = f(2017)(1);
        foreach (var x in result)
            Console.WriteLine(x);

        result = f(2018)(2);
        foreach (var x in result)
            Console.WriteLine(x);

        result = f(2016)(11);
        foreach (var x in result)
            Console.WriteLine(x);
    }
}

```

# Answer
> 0 votes
## REXX, 168 bytes

```
arg y m
signal on syntax
do d=1 to 31
  m=right(m,2,0);d=right(d,2,0)
  if date(w,y||m||d,s)='Sunday' then queue d'-'m'-'y
  end
syntax:n=queued()
say n
do n
  pull a
  say a
  end

```

# Answer
> 0 votes
# Bash + bsdmainutils, 94 bytes

```
a=(`for i in $(cal $2 $1|cut -b1-2);{ echo $i-$2-$1;}`);echo $[${#a[@]}-1];fmt -1 <<<${a[@]:1}

```

Uses the command `cal` which prints a calendar, is installed by default in several UNIX/LINUX/BSD (unfortunately not in TIO).

To try it save to `file`, `chmod +x file`, and run `./file 2017 9`

Saves to array a the first two bytes of cal output appended with the string "MM-YYYY" passed as second and first parameters (needs change if your locale does not starts weeks on sundays).

Next echoes array length substracted by one (first element is the word representing sunday) and the array without the first elemet, one per line `fmt -1`

# Answer
> 0 votes
# SAS, 182 bytes

```
%macro s(y,m);%let c=%eval(%sysfunc(intck(week,%sysfunc(nwkdom(1,1,&m,&y)),%sysfunc(nwkdom(5,1,&m,&y))))+1);%put&c;%do i=1%to&c;%put%sysfunc(nwkdom(&i,1,&m,&y),ddmmyy10.);%end;%mend;

```

# Answer
> 0 votes
# T-SQL, 316 311 bytes

```
DECLARE @ DATE=DATEADD(ww,-52*(2017-@y),'20170101')IF DATEPART(d,@)>7SET @=DATEADD(ww,-1,@);WITH c(d)AS(SELECT d FROM(SELECT DATEADD(ww,ROW_NUMBER()OVER(ORDER BY name)-1,@)d FROM sys.stats)a WHERE @y=DATEPART(yy,d)AND @m=DATEPART(m,d))SELECT CAST(COUNT(*)AS CHAR(1))FROM c UNION SELECT CAST(d AS CHAR(10))FROM c

```

I don't know if it is a valid answer though, since it outputs the number of sundays after the dates

Try it here

ungolfed:

```
DECLARE @m INT = 1,@y INT = 2017

DECLARE @ DATE=DATEADD(ww,-52*(2017-@y),'20170101')

IF DATEPART(d,@)>7
    SET @=DATEADD(ww,-1,@)

;WITH c(d)
AS
(SELECT d
 FROM (SELECT DATEADD(ww,ROW_NUMBER()OVER(ORDER BY name)-1,@)d
       FROM sys.stats) a
 WHERE @y = DATEPART(yy,d)
   AND @m = DATEPART(m,d)
)

SELECT CAST(COUNT(*) AS CHAR(1))
FROM c
UNION
SELECT CAST(d AS CHAR(10))
FROM c

```

# Answer
> 0 votes
# PHP, ~~127 118 112~~ 107 bytes

```
for([,$y,$m]=$argv;$d++<date(t,($t=strtotime)($y.-$m));)date(w,$t($s="
$d.$m.$y"))?:$r.=$s.!++$c;echo$c,$r;

```

takes input from command line arguments; run with `-r` or test it online.

**breakdown**

```
for([,$y,$m]=$argv;                     # import arguments to $y and $m
    $d++<date(t,strtotime($y.-$m))      # loop while ($d < number of days in that month)
    ;)
    date(w,strtotime($s="\n$d.$m.$y"))?:    # if date(w) is falsy (0 == sunday)
        $r.=$s.!++$c;                       # then append date to $r and increment $c
echo$c,$r;                              # print result

```

# Answer
> 0 votes
# Excel VBA, 190 bytes

```
Function p(y, m)
d = CDate("1/" & m & "/" & y)
e = DateAdd("m", 1, d)
Do While d < e
    If Weekday(d) = 1 Then Debug.Print d: i = i + 1
    d = d + 1
Loop
Debug.Print i
End Function

```

> Sample Output for **p(2000, 1)** (not sure if this qualifies)

```
02-01-2000
09-01-2000
16-01-2000
23-01-2000
30-01-2000
 5

```

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


title: Draw a network of nodes

text:
# Question
Title: Draw a network of nodes
There is a network of up to 26 nodes (named `A` to `Z` or `a` to `z` as per your wish). Every pair of nodes may be connected or disconnected. A node may be connected to at most 4 other nodes. Your task is to draw the network in a 2D diagram. Input will be given such that this task is possible (see more constraints in output section).

---

**Format**

**Input**

* Pairs of letters (`A` to `Z` or `a` to `z` as per your wish). They are not sorted in any order.
* Optional - number of pairs

**Output**

* An ASCII drawing that shows the actual links between the nodes. Nodes are given by `a` to `z` or `A` to `Z`. Use `-` for horizontal links and `|` for vertical links. Links may be of any (non-zero) length but they should be straight horizontal/vertical lines *that do not bend*. Spaces can be added provided they don't disfigure the picture.

You may not use built-ins that help in layout of the graph. Other graph-related built-ins may be allowed (though solutions without built-ins would be more appreciated). Shortest code wins.

---

**Sample data**

**Input**

```
A B
B F
B L
F K
L K
K R
K S
R P
S J
S P
J A
T V
V N

```

**Output**

```
A - B - F   T - V
|   |   |       |
|   L - K - R   N
|       |   |
J ----- S - P

```

**Input**

```
H C
G H
A B
B F
B C
F G
C D
D A

```

**Output**

```
A - B ----- F
|   |       |
D - C - H - G

```

# Answer
> 3 votes
# CJam, 142

You didn't ask for an optimal, deterministic or fast solution, so here you go:

```
qN%Sf%::c_s_&:Aff#:E;{A{;[DmrDmr]2f*}%:C;E{Cf=~.-:*}%0m1{E{Cf=$~1$.-_:g:T\:+,1>\ff*\f.+T0="-|"=f+~}%CA.++:L2f<__&=!}?}gS25*a25*L{~2$4$=\tt}/N*

```

Try it online

This generates random coordinates for each letter and tests if the layout is acceptable (edge letters lining up and no intersections), until it is. It gets mind-numbingly slow as you add more edges.

The two `D` letters in the code specify the maximum x and y coordinates; I picked `D` (=13) because I think it should be sufficient for all cases, feel free to prove me wrong. But you can change them to other values to speed up the program, e.g. the 2nd example should finish within a minute or two if you use 3 and 4 instead.

# Answer
> 3 votes
# C, 813 bytes

```
#include<map>
#include<set>
#include<cstdlib>
typedef int I;typedef char*C;I a,t,s,h;struct p{I x,y;}j,k;std::map<I,std::set<I>>l;std::map<I,p>g;C m,M="  |-";I L(I n,C q,C Q){j=g[n],h=1;for(I o:l[n])if(g.find(o)!=g.end())if(!(a=(k=g[o]).y==j.y)&&k.x^j.x)h=0;else for(I x=j.x,y=j.y,e=k.y*s+k.x,b,d=(k.x<j.x||k.y<j.y)?-1:1;a?x+=d:y+=d,(b=y*s+x)^e;m[b]=q[a])if(m[b]^Q[a]){h=0;break;}}I N(){for(auto i:g)for(I n:l[i.first])if(g.find(n)==g.end())return n;for(auto i:l)if(g.find(a=i.first)==g.end())return a;exit(puts(m));}I f(){for(I n=N(),x,y=0,b;y<s;y+=2)for(x=0;x<s;x+=2)m[b=y*s+x]==*M?g[n]={x,y},m[b]=n,L(n,M+2,M),h&&f(),L(n,M,M+2),m[b]=*M,g.erase(n):0;}I main(I c,C*v){for(;--c;l[a].insert(s),l[s].insert(a))a=v[c][0],s=v[c][1];t=l.size(),s=t|1;memset(m=(C)calloc(s,s),*M,s*s-1);for(a=1;a<s;++a)m[a*s-1]=10;f();}

```

Takes input as commandline arguments, e.g.:

```
./network AB BF BL FK LK KR KS RP SJ SP JA TV VN

```

Nowhere near competitive with aditsu's answer by size, but much more efficient!

This will brute-force all possible solutions, but will quickly recognise failure as it goes. For the two test cases, it finishes almost immediately, and it seems to only take a few seconds on more awkward inputs. It also has no limitation to the accepted node names (though you can't name one space, `|` or `-`) and has no limit on the number of nodes (as long as all names fit in a byte, so the practical limit is 252 nodes, and it will get slow long before reaching that many).

There's plenty of scope for speeding this up; a lot of short-circuit exiting was lost to the golfing, and there's parts which could be moved out of hot-loops. Also some observations of symmetry can dramatically reduce the positioning of the first 2 nodes, among other things.

---

Breakdown:

```
#include<map>
#include<set>
#include<cstdlib>
typedef int I;
typedef char*C;
I a,t,s,h;                // Variables shared between functions
struct p{I x,y;}          // Coord datatype
j,k;                      // Temporary coord references
std::map<I,std::set<I>>l; // Bidirectional multimap of node links
std::map<I,p>g;           // Map of nodes to positions
C m,                      // Rendered grid
M="  |-";                 // Lookup table for output characters

// Line rendering function
// Sets h to 1 if all lines are drawn successfully, or 0 if there is a blocker
I L(I n,C q,C Q){
  j=g[n],h=1;
  for(I o:l[n])                  // For each connection to the current node
    if(g.find(o)!=g.end())       // If the target node has been positioned
      if(!(a=(k=g[o]).y==j.y)&&k.x^j.x)h=0; // Fail if the nodes are not aligned
      else
        for(I x=j.x,y=j.y,             // Loop from node to target
          e=k.y*s+k.x,
          b,d=(k.x<j.x||k.y<j.y)?-1:1;
          a?x+=d:y+=d,(b=y*s+x)^e;
          m[b]=q[a])                   // Render character (| or -)
          if(m[b]^Q[a]){h=0;break;}    // Abort if cell is not blank
}

// Next node selection: finds the next connected node to try,
// or the next unconnected node if the current connected set is complete.
// Displays the result and exits if the entire graph has been rendered.
I N(){
  for(auto i:g)for(I n:l[i.first])  // Search for a connected node...
    if(g.find(n)==g.end())return n; // ...and return the first available
  for(auto i:l)                     // Else search for an unconnected node...
    if(g.find(a=i.first)==g.end())
      return a;                     // ...and return the first available
  exit(puts(m));                    // Else draw the grid to screen and stop
}

// Recursive brute-force implementation
I f(){
  for(I n=N(),x,y=0,b;y<s;y+=2) // Loop through all grid positions
    for(x=0;x<s;x+=2)
      m[b=y*s+x]==*M            // If the current position is available
       ?g[n]={x,y},             // Record the location for this node
        m[b]=n,                 // Render the node
        L(n,M+2,M),             // Render lines to connected nodes
        h&&f(),                 // If line rendering succeeded, recurse
        L(n,M,M+2),             // Un-render lines
        m[b]=*M,g.erase(n)      // Un-render node
       :0;
}

// Input parsing and grid setup
I main(I c,C*v){
  // Parse all inputs into a bidirectional multi-map
  for(;--c;l[a].insert(s),l[s].insert(a))a=v[c][0],s=v[c][1];
  t=l.size(),s=t|1; // Calculate a grid size
  // Allocate memory for the grid and render newlines
  memset(m=(C)calloc(s,s),*M,s*s-1);
  for(a=1;a<s;++a)m[a*s-1]=10;
  f(); // Begin recursive solving
}

```

---
Tags: code-golf, ascii-art, graph-theory
---


title: Never odd or even

text:
# Question
Title: Never odd or even
Did you notice, that this is a palindrome?

**Input**
Non-negative integer number or string representing it

**Output**
4 possible outputs, representing two properties of number:

* is it palindrome
* tricky #2

**Tricky #2 property**
If number is not palindrome, this property answers the question "Do the first and the *last* digits have the same parity?"
If number is palindrome, this property answers the question "Do the first and *middle* digit have the same parity?". For even lengths, the middle digit is one of the center two digits.

**Examples**

> 12345678 -\> False False
> It is not palindrome, first and last digits have different parity
>
> 12345679 -\> False True
> It is not palindrome, first and last digits have same parity
>
> 12344321 -\> True False
> It is palindrome, the first digit 1 and middle digit 4 have different parity
>
> 123454321 -\> True True
> It is palindrome, the first digit 1 and middle digit 5 have same parity

**P.S.**
You are up to decide output type and format. It could be any 4 distinct values. Just mention it in your answer.

# Answer
# 05AB1E, ~~15~~, ~~14~~ 13 bytes (Thanks to Riley and carusocomputing)

```
ÐRQi2ä¨}È¹RÈQ

```

Try online

Returns with brackets if it is a palindrome

Returns with 0 if the parity is different, 1 if it is the same

`Ð` Add input, such that I have enough input to work with

`R` Reverse the last element of the stack

`Q` Look if it is the same (takes the two top elements and performs ==)

`i` If statement, so only goes through when it is a palindrome

`2` Push the number 2

`ä` Split the input in 2 equal slices

`¨` Push the first element of the split (1264621 results in 1264)

`}` End if

`È` Check if last element is even

`¹` Push the first input again

`R` Reverse that input

`È` Check if it is even now

`Q` Check if those even results are the same and implicitly print
> 6 votes

# Answer
# PHP, ~~55~~ 52 bytes

```
echo$p=strrev($n=$argn)==$n,$n-$n[$p*log($n,100)]&1;

```

takes input from STDIN; run with `-R`.

output:

* `10` for palindrome and same parity
* `11` for palindrome and different parity
* `0` for non-palindrome and same parity
* `1` for non-palindrome and different parity

notes:

* `strlen($n)/2` == `log($n,10)/2` == `log($n,100)`
* if palindrome, compare middle digit `$n[1*log($n,100)]`
* if not, first digit `$n[0*log($n,100)]`
* ... to whole number (\<- lowest bit \<- last digit)
> 8 votes

# Answer
# Jelly, ~~16~~ 14 bytes

```
DµŒḂṄHC×LĊị+ḢḂ

```

Try it online!

Outputs two lines:

* `1` for palindrome, `0` for not
* `0` for *tricky #2*, `1` for not

### Explanation

```
DµŒḂṄHC×LĊị+ḢḂ    Main link. Argument: n (number)
D                 Get the digits of n
 µ                Start a new monadic chain
  ŒḂ              Check if the digit array is a palindrome (1 if yes, 0 if no)
    Ṅ             Print the result with a newline
     H            Halve (0.5 if palindrome, 0 if not)
      C           Subtract from 1 (0.5 if palindrome, 1 if not)
       ×          Multiply by...
        L         ...length of array (length/2 if palindrome, length if not)
         Ċ        Round up
          ị       Take item at that index from the digits
           +      Add...
            Ḣ     ...first item of digits
             Ḃ    Result modulo 2

```
> 7 votes

# Answer
# Python 2, ~~70~~ ~~68~~ 66 bytes

```
lambda n:(n==n[::-1],(ord(n[-1])+ord(n[(n==n[::-1])*len(n)/2]))&1)

```

Try it online!
> 6 votes

# Answer
# PowerShell, ~~114~~ 99 bytes

```
param($n)((0,(($z=$n[0]%2)-eq$n[-1]%2)),(1,($z-eq$n[$n.length/2]%2)))[($n-eq-join$n[$n.length..0])]

```

Try it online!

*Saved 15 bytes thanks to @Sinusoid.*

Inputs as a string. Outputs an array of type `(0|1) (True|False)`, with the `0` indicating "not a palindrome" and the `1` indicating "palindrome", and the `True` indicating parity matches and `False` otherwise.

This is done by using a pseudo-ternary and indexing into the appropriate place `(a,b)[index]`. The index `($n-eq-join$n[$n.length..0])` checks whether the input is a palindrome. If it is not, we take the `a` portion, which is a `0` coupled with whether the parity of the first digit `$n[0]` is `-eq`ual to the parity of the last digit `$n[-1]`. Otherwise, we're in the `b` portion, which is a `1` coupled with whether `$z` (the parity of the first digit) is `-eq`ual to the parity of the middle digit `$n[$n.length/2]`.

Previously, I had `"$($n[0])"` to get the first digit to cast correctly as an integer, since `$n[0]` results in a `char` and the modulo operator `%` coalesces `char`s based on the ASCII value, not the literal value, whereas a `string` does the literal value. However, @Sinusoid helped me to see that `0,1,2,...,9` as literal values all have the same parity as `48,49,50,...,57`, so if it uses the ASCII value we still get the same result.

That array is left on the pipeline, and output is implicit.
> 5 votes

# Answer
# Java 8, ~~205~~ ~~197~~ ~~182~~ ~~168~~ 134 bytes

```
n->{int l=n.length(),a=n.charAt(0)%2;return n.equals(new StringBuffer(n).reverse()+"")?a==n.charAt(l/2)%2?4:3:a==n.charAt(l-1)%2?2:1;}

```

Outputs: `1` for false-false; `2` for false-true; `3` for true-false; `4` for true-true.

**Explanation:**

Try it here.

```
n->{                     // Method with String parameter and integer return-type
  int l=n.length(),      //  The length of the input String
      a=n.charAt(0)%2,   //  Mod-2 of the first digit
  return n.equals(new StringBuffer(n).reverse()+"")?
                         //  If the String is a palindrome
    a==n.charAt(l/2)%2?  //   And if the first and middle digits are both even/odd
     4                   //    return 4
    :                    //   Else
     3                   //    Return 3
   :a==n.charAt(l-1)%2 ? //  Else-if the first and last digits are both even/odd
    2                    //   Return 2
   :                     //  Else
    1;                   //   Return 1
}                        // End of method

```
> 3 votes

# Answer
# Perl 6, 48 bytes

```
{($/=.flip==$_),[==] .ords[0,($/??*/2!!*-1)]X%2}

```

Try it

results in `(True True)` `(True False)` `(False True)` or `(False False)`

## Expanded:

```
{                  # bare block lambda with implicit parameter ｢$_｣

  (
    $/ =           # store in ｢$/｣
    .flip == $_    # is ｢$_｣ equal backwards and forwards
  ),

  [==]             # reduce the following using &infix:<==> (are they equal)

    .ords\         # list of ordinals (short way to make ｢$_｣ indexable)
    [
      0,           # the first digit's ordinal
      (
        $/         # if the first test is True (palindrome)
        ??   * / 2 # get the value in the middle
        !!   * - 1 # else get the last value
      )
    ]
    X[%] 2         # cross those two values with 2 using the modulus operator
}

```
> 3 votes

# Answer
# VBA, ~~117~~ 99 bytes

Saved 18 bytes thanks to Titus

```
Sub p(s)
b=s
If s=StrReverse(s)Then r=2:b=Left(s,Len(s)/2+.1)
Debug.?r+(Left(s,1)-b And 1);
End Sub

```

It doesn't expand much once formatted:

```
Sub p(s)
    b = s
    If s = StrReverse(s) Then r = 2: b = Left(s, Len(s) / 2 + 0.1)
    Debug.Print r + (Left(s, 1) - b And 1);
End Sub

```

Here are the given test case results:

```
s = 12345678     p(s) = 1 = False False
s = 12345679     p(s) = 0 = False True
s = 12344321     p(s) = 3 = True False
s = 123454321    p(s) = 2 = True True

```
> 3 votes

# Answer
# Haskell, 89 bytes

```
(x:r)#y=mod(sum$fromEnum<$>[x,y])2
f x|reverse x/=x=2+x#last x|y<-length x`div`2=x#(x!!y)

```

Try it online! Usage: `f "12345"`. Returns `0` for True True, `1`for True False, `2` for False True and `3` for False False.

The function `#` converts both digit characters into their ascii character codes and sums them. If both are even or both are odd the sum will be even, otherwise if one is even and the other odd the sum will be odd. Calculating modulo two, `#` returns `0` for equal parity and `1` otherwise. `f` checks if the input string `x` is a palindrome. If not then `#` is called with `x` and the last character of `x` and two is added to the result, otherwise if `x` is palindromic call `#` with the middle character of `x` instead and leave the result as is.
> 1 votes

# Answer
# Kotlin, 142 bytes

```
fun Char.e()=toInt()%2==0;
val y=x.reversed()==x;val z=x.first();println("${y},${if(y)z.e()==x.get(x.length/2).e();else z.e()==x.last().e()}")

```

Try it online!

```
fun Char.e() = toInt() % 2 == 0; //character extension function, returns if character(as int) is even

val y = x.reversed() == x
val z = x.first()

println(
"${y} //returns whether or not input is a palindrome
, //comma separator between the values
${if(y) z.e() == x.get(x.length/2).e() // if it's a palindrome compare first and middle parity
else z.e() == x.last().e()}" //else compare first and last parity
)

```
> 1 votes

# Answer
## CJam, 32 bytes

```
q:N_W%=N0=~2%NW=~2%N_,2/=~2%3$?=

```

Input is a number on top of the stack.

Explanation:

```
q                                 e# Read input:          | "12345679"
 :N                               e# Store in N:          | "12345679"
   _                              e# Duplicate:           | "12345679" "12345679"
    W%                            e# Reverse:             | "12345679" "97654321"
      =                           e# Check equality:      | 0
       N                          e# Push N:              | 0 "12345679"
        0=~                       e# First digit:         | 0 1
           2%                     e# Modulo 2:            | 0 1
             N                    e# Push N:              | 0 1 "12345679"
              W=~                 e# Get last digit:      | 0 1 9
                 2%               e# Modulo 2:            | 0 1 1
                   N              e# Push N:              | 0 1 1 "12345679"
                    _             e# Duplicate:           | 0 1 1 "12345679" "12345679"
                     ,            e# Length:              | 0 1 1 "12345679" 8
                      2/          e# Divide by 2:         | 0 1 1 "12345679" 4
                        =         e# Get digit (as char): | 0 1 1 '5
                         ~        e# Eval character       | 0 1 1 5
                          2%      e# Modulo 2:            | 0 1 1 1
                            3$    e# Copy stack element:  | 0 1 1 1 0
                              ?   e# Ternary operator:    | 0 1 1
                               =  e# Check equality:      | 0 1

```
> 1 votes

# Answer
## REXX, ~~104~~ 100 bytes

```
arg a
parse var a b 2''-1 c
e=a=reverse(a)
b=b//2
if e then f=b&centre(a,1)//2
else f=b&c//2
say e f

```

Returns logical value pair `0 0`, `0 1`, `1 0` or `1 1`.
> 1 votes

# Answer
# R, ~~115~~ ~~109~~ 105 bytes

```
w=strtoi(el(strsplit(scan(,""),"")))
c(p<-all(w==rev(w)),w[1]%%2==switch(p+1,tail(w,1),w[sum(1|w)/2])%%2)

```

Takes input from stdin. Returns `FALSE FALSE` for False False, `FALSE TRUE` for False True, `TRUE FALSE` for True False, and `TRUE TRUE` for True True.
> 1 votes

# Answer
# AWK, ~~97~~ 96 bytes

```
{n=split($0,a,"")
for(;j<n/2;)s+=a[j+1]!=a[n-j++]
x=(a[1]%2==a[s?n:int(n/2)+1]%2)+(s?0:2)
$0=x}1

```

Simplest usage is to place the code into file: `OddEven` then do:

```
awk -f OddEven <<< "some number here"

```

Output is essentially the bit-sum of the comparisons in the Question, e.g.

```
0, Not palindrome and first and last digits have different parity
1, Not palindrome and first and last digits have same parity
2, Palindrome and the first digit and middle digit have different parity
3, Palindrome and the first digit and middle digit have same parity

```

I tried removing the `()` from `(s?0:2)` but this messes up operator precedence somehow.
> 1 votes

# Answer
# Ruby, 60 + 1 = 61 bytes

Uses the `-n` flag.

```
r=->i{$_[i].to_i%2}
p e=$_.reverse==$_,r[0]==r[e ?~/$//2:-1]

```

Try it online!
> 1 votes

# Answer
# Groovy, 326 303 bytes

Shrunk Code:

```
String str="12345678";char pal,par;pal=str==str.reverse()?'P':'N';if(pal=='P'){par=(int)str.charAt(0).toString()%2==str.charAt((int)str.length()-1-(int)((str.length()-1)/2))%2?'S':'N'}else{par = (int)str.charAt(0).toString()%2==str.charAt((int)(str.length()-1)%2)?'S':'N'};print((String)pal+(String)par)

```

Original Code (with Explanation):

```
Declare str as String                        String str = "12345678"
Declare pal and par as char                  char pal, par
Check if Palindrome or not                   pal = str==str.reverse()?'P':'N'
If Palindrome...                             if (pal=='P') {
and has same parity (S) and if not (N)       par = (int)str.charAt(0).toString()%2==str.charAt((int)str.length()-1-(int)((str.length()-1)/2))%2?'S':'N'
else if not palindrome...                    } else {
and has same parity (S) and if not (N)       par = (int)str.charAt(0).toString()%2==str.charAt((int)(str.length()-1)%2)?'S':'N'
closing tag for if                           }
Print desired output                         print((String)pal+(String)par)

```

Original Code (without Explanation):

```
String str = "12345678"
char pal, par
pal = str==str.reverse()?'P':'N'
if (pal=='P') {
    par = (int)str.charAt(0).toString()%2==str.charAt((int)str.length()-1-(int)((str.length()-1)/2))%2?'S':'N'
} else {
    par = (int)str.charAt(0).toString()%2==str.charAt((int)(str.length()-1)%2)?'S':'N'
}
print((String)pal+(String)par)

```

Input:

```
Just change "12345678" to another set of non-negative digits.

```

Output:

```
"PS" - Palindrome with Same Parity
"PN" - Palindrome with Diff Parity
"NS" - Non-palindrome with Same Parity
"NN" - Non-palindrome with Diff Parity

```
> 1 votes

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


title: Help Pac-Man count the Pac-Dots

text:
# Question
Title: Help Pac-Man count the Pac-Dots
On the advice of Ms. Pac-Man who's worried about him getting overweight, Pac-Man has decided to keep track of his daily Pac-Dot intake. Help him count the number of Pac-Dots on a given path in the maze!

## The maze

To help you build your own encoding of the maze, you can **get some raw data here**.

## Pac-Man's journey

In the context of this challenge, the following rules apply:

* First, the good news: the ghosts aren't there.
* Pac-Man always starts his race at the position indicated on the above picture, heading to the East. There is no Pac-Dot at the starting position.
* As long as he's following a straight path, he keeps advancing to the next squares.
* When he encounters a *90° turn* without any other available path (orange squares on the map), he automatically and systematically takes the turn.
* When he encounters a *junction* where several paths are available (green squares on the map), he may either continue on the same direction -- if applicable -- or choose another direction (including doing a U-turn).
* When Pac-Man passes through one of the exits on the middle left or middle right side of the maze, he immediately reappears on the opposite side.
* Pac-Man eats all the Pac-Dots on the path he's following. Once a Pac-Dot has been eaten, it is removed from the maze.

## The challenge

### Input

You'll be given a string describing Pac-Man's behavior on the junctions that he's going to reach. This string will be made of the following characters:

* `L`: do a 90° turn to the left
* `R`: do a 90° turn to the right
* `F`: go forwards (no direction change)
* `B`: go backwards (do a U-turn)

When all characters have been processed, Pac-Man stops at the next junction he encounters.

### Output

You have to print or output the number of Pac-Dots eaten along the input path.

### Rules

* You can write a full program or a function.
* You can take input in either uppercase or lowercase, as either a string or an array of characters. You may also use other characters (but only one character per direction) or integers in `[0 .. 9]`. If you do so, please specify it clearly in your answer.
* You can assume that the input is always valid. (The jsFiddle below will detect errors, but you're not supposed to.)
* This is code-golf, so the shortest code in bytes wins.
* Standard loopholes are forbidden.

### Hint

It may not be required nor optimal to store the exact shape of the maze.

## Test cases and demo

The following test cases -- or any other input -- **can be tested in this jsFiddle**.

```
1. Input  : ""
   Output : 1
   Comment: Pac-Man just advances to the first junction, eats the Pac-Dot on it and stops.

2. Input  : "L"
   Output : 7

3. Input  : "FFR"
   Output : 13

4. Input  : "LFLR"
   Output : 17
   Comment: Pac-Man will exit on the middle right side and re-appear on the left side.

5. Input  : "BBBB"
   Output : 2

6. Input  : "BRRFFFL"
   Output : 15

7. Input  : "LFFRLFFFFRF"
   Output : 50

8. Input  : "BRFRLRFRLFR"
   Output : 54
   Comment: Pac-Man will exit on the middle left side and re-appear on the right side.

9. Input  : "FFLRLFFLLLLFFBFLFLRRRLRRFRFLRLFFFLFLLLLFRRFBRLLLFBLFFLBFRLLR"
   Output : 244
   Comment: All cleared!

```

# Answer
# Pyth, ~~356~~ 345 + 1 = 346 bytes

The code contains some unprintables, so here is the reversible `xxd` hexdump.

```
0000000: 4a4b 304c 2c3d 2b4b 4062 4a58 624a 3041  JK0L,=+K@bJXbJ0A
0000010: 2c63 6a43 2201 e120 49b4 efbc e267 27f4  ,cjC".. I....g'.
0000020: a11b f5d5 7f79 d1a0 ab8a 7689 449f 0c50  .....y....v.D..P
0000030: b2d4 7c30 99c3 368e aa67 4213 ab9b d276  ..|0..6..gB....v
0000040: d75f 6e99 5757 04a6 08cc 99d0 7141 3d2f  ._n.WW......qA=/
0000050: d854 7cf7 4a70 954e 6e35 f9b9 e0c5 1d53  .T|.Jp.Nn5.....S
0000060: 36d5 63f9 cf13 0f66 c113 4dec 956e 5225  6.c....f..M..nR%
0000070: b14a 1659 dcb5 6822 3534 2034 6a43 2203  .J.Y..h"54 4jC".
0000080: ffe3 8fff 2232 3d59 636a 4322 0b8a 4624  ...."2=YcjC"..F$
0000090: 7815 4a94 192c 79f6 d6e5 e098 5e97 76bc  x.J..,y.....^.v.
00000a0: 23cf 027c 35c5 5098 2a83 68f1 823a 83f6  #..|5.P.*.h..:..
00000b0: dfa4 7e12 443f 0257 7adb ab2d 8e6f 1199  ..~.D?.Wz..-.o..
00000c0: 9a3e 3f9d a524 d331 c5ff 94ae e5a2 3507  .>?..$.1......5.
00000d0: bd22 3334 2032 3d6b 2b30 6a43 2202 25f2  ."34 2=k+0jC".%.
00000e0: f55c 2252 c250 0002 c250 0000 065c 225c  .\"R.P...P...\"\
00000f0: 2247 5289 3698 4227 5350 8822 3136 3d64  "GR.6.B'SP."16=d
0000100: 636a 4322 8223 a80e 5c22 981d d272 729d  cjC".#..\"...rr.
0000110: d88d 981d 5c22 5c22 2bd7 91dd 9428 73d7  ....\"\"+....(s.
0000120: 1dd7 2234 2032 5651 2079 483d 547e 4a40  .."4 2VQ yH=T~J@
0000130: 4047 4a2b 5a78 2246 5242 4c22 4e20 796b  @GJ+Zx"FRBL"N yk
0000140: 3d5a 4040 647e 4a40 4059 4a3d 5421 7840  =Z@@d~J@@YJ=T!x@
0000150: 594a 5454 2968 7948 0a                   YJTT)hyH.

```

Requires the `-M` flag to disable memoization. Unfortunately, this can't be done in any online executor I know of.

Here is a ~~readable~~ printable ASCII version:

```
JK0L,=+K@bJXbJ0A,cj746957013238413906925468440008893181365431681519974815772691846219267045007717553452313017550830370829477591340658010575885616582299429376501117428763541235628345630376341520044712982918668584832091126800263024965443560007480163218792 54 4j17178005503 2=Ycj664551201217474826979459068682259492333017695780569003557724234375880492114440213266014621594427584622393511454741615093293082181365458295035985321888753898774398909 34 2=k+0j883734055588186287049718559289059922762611092840989558085734536 16=dcj53536195844172273707047543644202986760006840011986146398708374999 4 2VQ yH=T~J@@GJ+Zx"FRBL"N yk=Z@@d~J@@YJ=T!x@YJTT)hyH

```

## Explanation

This is very much work in progress, so I won't post a complete explanation yet.

Basically, the program represents the board as a (somewhat weird) graph using five lookup tables: 2 for connectivity, 1 for junction directions, and 2 for dot counts. This was built by a 200-line Python script I spent way too many hours on. Then the program just walks through the input and counts the dots, updating the dot tables to zero as the dots are collected.

### TODO:

* Write Python routine for reordering the nodes until the lookup table contains as few escape-requiring characters as possible
* Try to remove section handling altogether (should remove one lookup table)
    + **UPDATE:** tried this, seems to not remove the table and lengthen code
* Rewrite Pyth-side logic (the current one isn't very golfed)
    + **UPDATE:** somewhat done, code's still imperfect
> 10 votes

# Answer
# k, 264 bytes

```
b:,/16 16\'108_a:-135#0+1:"p.k"
(#(?27,r 1)^(12+!8)^14 17)+/b@?*|r:+1 27 0{i:a?64/(4!2+y+*x;x 1);(4 64\a i+1-2*2!i),_i%2}\0:""
\
...binary data...

```

Hex dump:

```
$ xxd p.k
00000000: 623a 2c2f 3136 2031 365c 2731 3038 5f61  b:,/16 16\'108_a
00000010: 3a2d 3133 3523 302b 313a 2270 2e6b 220a  :-135#0+1:"p.k".
00000020: 2823 283f 3237 2c72 2031 295e 2831 322b  (#(?27,r 1)^(12+
00000030: 2138 295e 3134 2031 3729 2b2f 6240 3f2a  !8)^14 17)+/b@?*
00000040: 7c72 3a2b 3120 3237 2030 7b69 3a61 3f36  |r:+1 27 0{i:a?6
00000050: 342f 2834 2132 2b79 2b2a 783b 7820 3129  4/(4!2+y+*x;x 1)
00000060: 3b28 3420 3634 5c61 2069 2b31 2d32 2a32  ;(4 64\a i+1-2*2
00000070: 2169 292c 5f69 2532 7d5c 303a 2222 0a5c  !i),_i%2}\0:"".\
00000080: 0a02 4005 c006 4109 c103 8008 8143 c244  ..@...A......C.D
00000090: c345 c446 c547 c648 c749 c84a 820a 830c  .E.F.G.H.I.J....
000000a0: 840d 870b 8889 cb0e 8a11 8b0f 4c4d cc10  ............LM..
000000b0: cd4e d14f ce51 d014 8e12 8f13 9017 9153  .N.O.Q.........S
000000c0: d215 9216 931e 5455 d41a d51b 5657 d61f  ......TU....VW..
000000d0: d718 941d 9759 d85a d95b da5c db5d dc98  .....Y.Z.[.\.]..
000000e0: de20 9921 9c5f 9d5e 60df e161 e089 9833  . .!._.^`..a...3
000000f0: 4222 2247 2662 7550 0000 0500 5000 c255  B""G&buP....P..U
00000100: 2c22 2202 2588 5ff2                      ,"".%._.

```

The binary data at the end encodes two arrays:

* `a` consists of pairs of bytes, each representing (64\*direction)+junctionId
* `b` is the number of Pacman dots between each pair of junctions in `a`

The program reads its own source file (`p.k`) and decodes the data.

The input comes from stdin and uses 0x00,0x01,0x02,0x03 (a.k.a. NUL,SOH,STX,ETX - the first four ASCII codes) instead of FLBR.

I use my own implementation of k which is limited, bloated, crashy, and slow compared to the real thing. I test with the following program:

```
t:{e:($y),"\n"; a:`sys[("/path/to/k";"./p.k");`c$"FLBR"?x]
   1@$[a~e;"ok\n";"failed ",x,"\n expected: ",e," actual: ",a,"\n"];}
t["";1]
t[,"L";7]
t["FFR";13]
t["LFLR";17]
t["BBBB";2]
t["BRRFFFL";15]
t["LFFRLFFFFRF";50]
t["BRFRLRFRLFR";54]
t["FFLRLFFLLLLFFBFLFLRRRLRRFRFLRLFFFLFLLLLFRRFBRLLLFBLFFLBFRLLR";244]
\

```
> 2 votes

---
Tags: code-golf, graph-theory, maze
---


title: Should we be friends?

text:
# Question
Title: Should we be friends?
### Note this is a question primarily focusing on

## Introduction

Bacefook wants people to be friendlier! As such, they are implementing a new system to suggest friends! Your task is to help Bacefook to implement their new suggesting system.

### Specifications:

Your program must be a REPL (read-eval-print loop) supporting 3 types of command: `FRIEND`, `SUGGEST` and `KNOW`.

`FRIEND X Y` \- Specifies that `X` and `Y` are friends in the social network.

* If X is friends with Y, then Y is friends with X
* Can, but doesn't have to have output
* X is always friends with X

`KNOW X Y` \- Output a truthy value if X and Y are friends, falsy otherwise

* `KNOW X X` will always output a truthy value

`SUGGEST X Y` \- Output a truthy value if X and Y should be friends, falsy otherwise. X and Y should be friends if:

* X and Y are not friends
* X and Y have at least 1 friend in common

You are allowed to replace `FRIEND`, `SUGGEST` and `KNOW` with your own strings, but you must mention what string you have replaced each command with.

Your program can take in input/produce output in any way desirable, as long as it is reasonably easy to recognize how it works.

The number of people in the social network `N` is between 1 and 100,000, but there may be any number of "friend links" (edges).

> If you haven't noticed yet, this is a graph searching problem. The (likely) easiest (and possibly fastest) data structure to implement this in would be an adjacency matrix.

### Test cases

```
FRIEND A B
FRIEND A C
FRIEND B D
SUGGEST A B -> Falsy, as they are friends
SUGGEST A D -> Truthy, as they share B as a common friend
SUGGEST C D -> Falsy, they do not share a common friend
KNOW D B -> Truthy, they are friends
KNOW B C -> Falsy, not friends
=============
FRIEND Tom Tim
KNOW Tom Tim -> Truthy
KNOW Tim Tom -> Truthy
KNOW Tom Kit -> Falsy
=============
KNOW Tim Kit -> Falsy
FRIEND Tim Tom
KNOW Tim Kit -> Falsy
FRIEND Tom Kit
SUGGEST Tim Kit -> Truthy
=============
FRIEND X Y
SUGGEST X Y -> Falsy since X is friends with X

```

Here's some more test cases in image form

### Win condition

This is , shortest code wins!

# Answer
> 44 votes
# SWI-Prolog, 62 47 41 bytes

```
X*Y:-X+Y;Y+X;X==Y.
X?Y:-not(X*Y),X*Z,Y*Z.

```

Prolog isn't too often useful, but when it is it's just beautiful. We'll use `a+b` to notate that `a` is friends with `b`, `a*b` that `a` knows `b` and `a?b` that `b` should be suggested to `a` or not. The first line simply says that `X*Y` is true if either `X+Y`, `Y+X` or `X == Y` is true. This implements the symmetry of knowing eachother. Asking if there should be a suggestion is incredibly simple. We just ask if there is a `Z` such that `X*Y` is false and `X*Z` and `Y*Z` is true. Exactly as described in the challenge.

If you save this as a file (e.g. `friends.pl`) and open SWI-Prolog with this file (`prolog -l friends.pl`) you get dropped into a REPL.

You can assert friendships like this:

```
assert('a' + 'b').
assert('a' + 'c').
assert('b' + 'd').

```

You can check if people know eachother or suggestion should be made:

```
'a'*'b'.
'a'?'d'.

```

# Answer
> 14 votes
# PHP, ~~138 133~~ 129 bytes

PHP beats Mathematica - a rare occurence.

```
for(;$s=fgets(STDIN);$s>G?print$$a[$b]?$s<L:$s>L&&@array_intersect_key($$a,$$b):$$a[$b]=$$b[$a]=1)[,$a,$b]=explode(" ",trim($s));

```

prints `1` for truthy, empty string for falsy. Run with `-nr` or test it online.
needs PHP 7.1 for the list assignment; user names are case sensitive and should exclude `a`, `b`, `s`.

**breakdown**

```
for(;$s=fgets(STDIN);                       # loop through input
    $s>G                                        # 2. evaluate command
        ?print$$a[$b]
            # command KNOW: true if $$a[$b]
            ?$s<L
            # command SUGGEST: true if !$$a[$b] and array_intersect_key returns truthy
            :$s>L&&@array_intersect_key($$a,$$b)
        # command FRIEND: set keys in $$a and $$b
        :$$a[$b]=$$b[$a]=1
)
    [,$a,$b]=explode(" ",trim($s));             # 1. parse user names to $a and $b

```
* `$s` has to be trimmed because it includes the newline character.
* `array_intersect_key` has to be muted or it would yield warnings for empty `$$a` or `$$b`.
* ~~+18~~ +15 bytes for all user names: Replace `$$a` with `$f[$a]` and `$$b` with `$f[$b]`.

# Answer
> 12 votes
## CMD (Batch), 50 + 20 + 135 = 205 bytes

* FRIEND.CMD

```
@for %%f in (%1.%1 %1.%2 %2.%2 %2.%1)do @set %%f=1

```
* KNOW.CMD

```
@call echo(%%%1.%2%%

```

Prints `1` for friends, a blank line for strangers.
* SUGGEST.CMD

```
@call set k=0%%%1.%2%%
@set k=1&if %k%==0 for /f "tokens=2 delims=.=" %%f in ('set %1.')do @call set k=%%k%%%%%%f.%2%%
@echo(%k:~1,1%

```

Prints `1` or a blank line. I think six consecutive `%`s might be a new personal best.

# Answer
> 6 votes
# Python 3, ~~163~~ ~~149~~ 143+2=145 bytes

-6 bytes thanks to @FelipeNardiBatista

```
l=[]
def f(a,b):l.extend([(a,b),(b,a)])
k=lambda a,b:a==b or(a,b)in l
s=lambda a,b:k(a,b)-1and{c for c,d in l if d==a}&{c for c,d in l if d==b}

```

Save it to a file and run it as `python3 -i file.py`
Use
\- `f("a", "b")` instead of `FRIENDS a b`
\- `k("a", "b")` instead of `KNOW a b`
\- `s("a", "b")` instead of `SUGGEST a b`

Falsey output : 0, set(), False
Truthy output : non-empty set, True

Try it online

---

164 bytes when not using python interpreter as REPL:

```
f=[]
while 1:c,a,b=input().split();i=(a,b)in f;f+=c=="f"and[(a,b),(b,a)]or[(i+(a==b),-i+1and{c for c,d in f if d==a}&{c for c,d in f if d==b})];print(f[-1][c=="s"])

```

Uses
\- `f` for `FRIEND`
\- `s` for `SUGGEST`
\- anything else for `KNOW`

Try it online

# Answer
> 6 votes
# Python 3, 122 118+2=120 bytes

```
l={}
def f(*r):l[r]=l[r[::-1]]=1
k=lambda a,b:a==b or(a,b)in l
s=lambda a,b:1-k(a,b)and any(k(a,z)&k(b,z)for z,_ in l)

```

Usage is exactly the same as ovs's answer.

# Answer
> 5 votes
# Mathematica, 164 bytes

```
f={}
p:=Union@@f
i=Position[p,#][[1,1]]&
m:=Outer[Boole@MemberQ[f,{##}]&,p,p]
a=(#[[i@#2,i@#3]]/._@__->0)>0&
F=(f=#~Tuples~2~Join~f;)&
K=m~a~##&
S=a[m.m,##]&&!K@##&

```

Defines three main functions `F`, `S`, and `K` with the desired behavior. For example, the sequence of commands

```
F@{David, Bob}
F@{Bob, Alex}
F@{Alex, Kitty}
F@{Daniel, David}
F@{David, Kit}
S[David, Alex]
S[Bob, Kitty]
S[David, Kitty]
S[David, Bob]
K[David, Bob]
F@{Kit, Kitty}
S[David, Kitty]

```

is the last test case from the image linked in the OP; the `F` commands yield no output (the single semicolon seems a small price to pay for this), while the six `S` and `K` commands yield

```
True
True
False
False
True
True

```

as desired.

At any moment, `f` is the list of ordered pairs of the form `{A, B}` where `A` knows `B`, while `p` is the list of people appearing in some element of `f`. Calling `F@{A, B}` adds the four ordered pairs `{A, B}`, `{B, A}`, `{A, A}`, and `{B, B}` to `f`.

Also, at any moment, `m` is the adjacency matrix of the underlying graph (a person is adjacent to themselves and to all their `F`riends); the rows and columns are indexed by `p`, and `i` converts a person to the corresponding row/column number. The helper function `a` takes a matrix and two people as inputs and looks up the entry of the matrix whose "coordinates" are the two people, returning `True` if the number is positive and `False` if it's zero. (It's also possible to call `a` when one of the input people isn't yet recognized—for example, making a KNOW or SUGGEST query before any FRIEND declarations, or asking about some poor person who has no friends; this throws errors, but the rule `/._@__->0` forces the output to be `False` anyway.)

Calling `K[A, B]` therefore looks up whether `m[A, B]` is positive, which implements the `K`now verb. The matrix product `m.m` is the length-2-path matrix, containing the number of ways to go from one person to another along a path of length 2; this allows `S[A, B]` to implement the `S`uggest verb, as long as we additionally check by hand (`&&!K@##`) that the input people don't already know each other.

Fun fact: for free, this implementation allows us to declare cliques of friends—the command `F@{A, B, C, D}` is equivalent to all of `F@{A, B}`, `F@{A, C}`, `F@{A, D}`, `F@{B, C}`, `F@{B, D}`, and `F@{C, D}` combined.

# Answer
> 2 votes
# Python 2, 118 bytes

```
F=[]
def s(f,c):c=set(c);r=c in F;return F.append(c)if f%2 else not r^(4 in[len(x|c)for x in F])if f else 2>len(c)or r

```

Try it online!

Since I couldnt find repl online tool for python 2, I've added the TIO Nexus(in REPL format).

**Query for option and its possible output**

0 for Known - None

1 for Friends - True or False

2 for Suggest - True or False

**Example of usage and sample output in an repl python interpreter.**

```
>>> F=[]
>>> def s(f,c):c=set(c);r=c in F;return F.append(c)if f%2 else not r^(4 in[len(x|c)for x in F])if f else 2>len(c)or r
...
>>> s(1,['A','B'])
>>> s(1,['A','C'])
>>> s(1,['B','D'])
>>> s(2,['A','B'])
False
>>> s(2,['A','D'])
True
>>> s(2,['C','D'])
False
>>> s(0,['D','B'])
True
>>> s(0,['D','C'])
False

```

# Answer
> 0 votes
## GNU sed, 158 + 2(rn flags) = 160 bytes

Since sed is a regex based language, there are no primitive types, not to mention abstract data structures. The network data is stored as free format text, in this case as redundant friend links like `A-B;B-A;`etc., which is then matched against various regex patterns.

```
G
/^F/{s:. (.+) (.+)\n:\1-\1;\1-\2;\2-\1;\2-\2;:;h}
/^K |^S /{s:(.) (.+) (.+)\n.*\2-\3.*:\1:;/^K$/p}
/^S /s:(.) (.+) (.+)\n.*(.+)-(\2.*\4-\3|\3.*\4-\2).*:\1:p

```

**Try it online!**

By design, sed runs the whole script for each input line. I recommend testing in interactive mode, to see the output of a command immediately after typing.

**Usage:** there are no truthy / falsy values in sed, so the output convention I use is borrowed from bash, whereby a non-empty string is considered as truthy, and an empty string as falsy.

* `F X Y` for `FRIEND X Y`. It has no output.
* `K X Y` for `KNOW X Y`. Outputs 'K' as truthy, and nothing as falsy.
* `S X Y` for `SUGGEST X Y`. Outputs 'S' as truthy, and nothing as falsy.

**Explanation:**

```
G
# append stored network data, if any, to the current input line
/^F/{
# if command is 'F' (FRIEND), for ex. 'F X Y'
   s:. (.+) (.+)\n:\1-\1;\1-\2;\2-\1;\2-\2;:
   # generate friend links, for ex. 'X-X;X-Y;Y-X;Y-Y'
   h
   # store updated network data
}
/^K |^S /{
# if command is either 'K' (KNOW) or 'S' (SUGGEST), for ex. 'K X Y'
   s:(.) (.+) (.+)\n.*\2-\3.*:\1:
   # search friend link 'X-Y'. If found, delete pattern except the command letter.
   /^K$/p
   # if only letter K left, print it (command is 'K', 'X' and 'Y' are friends)
}
/^S /
# if command is 'S', for ex. 'S X Y', but 'X' and 'Y' aren't friends
   s:(.) (.+) (.+)\n.*(.+)-(\2.*\4-\3|\3.*\4-\2).*:\1:p
   # search if 'X' and 'Y' have a friend in common (for ex. 'C'), and if so print
   #letter S. The search is for ex. 'C-X.*C-Y' and 'C-Y.*C-X'.

```

---
Tags: code-golf, graph-theory, data-structures
---


title: Is the time linear?

text:
# Question
Title: Is the time linear?
I like patterns in time. My favorite is when the time lines up. For example, all of these line up:

```
3:45
12:34
23:45
3:21
6:54

```

This is because each digit in the hour/minute is increasing/decreasing by one each time.

Your task is to take the current time and check if it "lines up" in this pattern in a program. (You will output a truthy or falsey value according to this check.) Along with the times above, your program should match these:

```
1:23
4:32
2:10

```

And *not* match these:

```
1:00
12:13
1:21
1:34

```

You may take the time as an argument to a function/through STDIN, but this incurs a **+125%** byte penalty on your program. You may take the time from UTC or system time; 12-hour or 24-hour. This is a code golf, so the shortest program in bytes wins.

# Answer
# Jolf, ~~10~~ ~~21~~ ~~19~~ 28 bytes

Replace  with `\x11`, or use this link.

```
 eZd♂Μf5dpq+EH20d&=FnH h±01H

```

This can be golfed (?).

Explanation:

```
 eZd♂Μf5dpq+EH20d&=FnH h±01H
       f5                      [hours, minutes]
      Μ  dpq+EH20              pad (>_>)
     ♂                         singleton; so [13,45] => [1,3,4,5]
  Zd                           delta list; [1,3,4,5] => [2,1,1]
_e               d             check if
                   =FnH        each member is equal to the first
                  &    _h±01H  and if it is in the array [-1,1] (0 +- 1)

```
> 5 votes

# Answer
## Pyth, ~~67.5~~ ~~54~~ 38 bytes

```
sm.v%"q1l.{.e%skvb+`.d6.[\0`.d7 2"d"+-

```

Or old version, 30 bytes (takes input from stdin)

```
 zsm.v%"q1l.{.e%skvb:z\:k"d"+-

```

Thanks @drobilc for reminding me of the other `.d` arguments ;)

Explanation:

```
sm.v%"q1l.{.e%skvb+`.d6.[\0`.d7 2"d"+-
 m                                 "+- -  [V for d in "+-"]
    %                             d    -   V%d
     "                           "     -    stringify code V
                   `.d6                -          repr(current_hour)
                  +                    -         ^+V
                           `.d7        -           repr(current_minute)
                       .[\0     2      -          pad("0",^,2)
           .e                          -        [V for k,b in enumerate(^)]
                vb                     -          eval(b)
             %s                        -         V (either + or -) ^
               k                       -          k
         .{                            -       set(^)
        l                              -      len(^)
      q1                               -     ^==1
  .v                                   -  eval(^)
s                                      - True in ^

```

Basically, for both `+` and `-` it tests to see if by performing that operation on the index on the character and the character itself you get the same values.

Try it here!

Or try a test suite!
> 4 votes

# Answer
## Bash, ~~79~~ 78 bytes

```
[[ $(date +%-H%M|fold -1|sed 'p;{1d;$d}'|paste -sd-\\n|bc|sort -u) =~ ^-?1$ ]]

```

Remarkably competitive for the usually-painfully-verbose Bash.

Thanks to @DigitalTrauma for 2 bytes!

Walkthrough:

* `date +%-H%M`: returns the date in HHMM form (ex. `1234`).
* `fold -1`: puts each character on a separate line (so now we have `1\n2\n3\n4\n`).
* `sed`:

+ `p`: duplicate each line.
    + `{1d;$d}`: delete the first and last lines.

Now we have `1 2 2 3 3 4` (spaces used in place of newlines for readability).
* `paste -sd '-\n'`: turns this into `1-2 2-3 3-4`.
* `bc`: piped through an arithmetic calculator, now we have `-1 -1 -1`.
* `sort -u`: remove duplicates, so now we have `-1`.
* `[[ $(...) =~ ^-?1$ ]]`: check if the resulting string matches the regex `/^-?1$/`.

If the time is "linear," the differences between each consecutive line will all be either `1` or `-1`.
> 3 votes

# Answer
## Pyth, 23 22 bytes

```
}+.d6%"%02d".d7jks_BU7

```

Constructs the string "0123456543210" and check if the time without the colon is a substring of it.

In pythonic pseudocode:

```
                   k = ""
}+.d6%"%02d".d7    ( currentHour() + format("%02d",currentMinute()) ) in \
  jks_BU7             sum([range(7),range(7)[::-1]]).join(k)

```
> 3 votes

# Answer
# 05AB1E, 10 × 125% = ~~24.75~~ 22.5 bytes

Code:

```
R.d¬¹1£ŸJQ

```

Explanation:

```
R           # Reverse the input
 .d         # Keep the digits
   ¬        # Head, push the first character of the string
    ¹       # First value from the input register
     1£     # Take the first character from the input
       Ÿ    # Inclusive range
        J   # Join the list to a string
         Q  # If equal to the input, return 1, else 0

```

Try it online! or Try all test cases at once!
> 2 votes

# Answer
# Jelly, ~~24.75~~ 22.5 bytes

```
~ḟ0IµḢ×=1P

```

The code is **10 bytes** long and is subject to the **125% penalty**.

Try it online!

### How it works

```
~ḟ0IµḢ×=1P  Main link. Input: S (time string)

~           Apply bitwise NOT to all characters.
            This attempts to cast to integer, and returns 0 on failure.
            For example, '1'~ -> 1~ -> -2, but ':'~ -> 0.
 ḟ0         Filter out the 0, which corresponds to the colon.
   I        Compute all increments/deltas.
    µ       Begin a new, monadic chain. Argument: A (list of deltas)
     Ḣ      Pop the first delta.
      ×     Multiply the remaining list items by the popped one.
            The list should now consist of 1's for a truthy test case.
       =1   Compare the list items with 1.
         P  Take the product of the resulting Booleans.

```
> 2 votes

# Answer
# MATL, 24 ~~18~~ ~~19~~ bytes

```
'%i%2i'1$4:5Z'YDdtdw|qh~

```

Try it online!

Output is an array consisting of only ones (which is truthy) if the time matches, and an array with at least one zero (that's falsy) otherwise.

To test the code it's better to split it in two parts as follows:

* `1$4:5Z'` produces a 2-number vector with the current hour and minute.
* `'%i%2i'iYDdtdw|qh~` takes from stdin a 2-number vector with hours and minutes and computes the result.

In the combined code, the second part takes its input from the stack as produced by the first.

### Explanation

A matching occurs if the following two conditions are met:

* All differences between consecutive digits have absolute value 1;
* All differences between those consecutive differences are 0.

Minutes have to be zero padded (*thanks to Dennis for that!*). Zero-padding, if it actually occurs (minute is 9 or less) will always produce a falsy result. So I use space-padding instead, whivh has the same effect.

Code:

```
'%i%2i'     % format string for sprintf, including padding for minutes
1$4:5Z'     % get current hour and minute as a 2x1 numeric array
d           % differences between consecutive digits (chars)
td          % duplicate. Compute differences again. Will be all zero if time matches
w|q         % swap, absolute value, subtract 1. Will be all zero if time matches
h~          % concatenate both arrays and apply logical negate

```
> 2 votes

# Answer
## Batch, 130 bytes

```
@set t=%time:~,5%
@goto %t::=% 2>nul
:0012
:0123
:0210
:0234
:0321
:0345
:0432
:0456
:0543
:0654
:1234
:2345
@echo 1

```

Edit: Back to the old approach. `%time%` contains the time in hh:mm:ss.ss format. The first 5 characters are extracted into `t` and the colon is deleted. If the result is one of the 12 possible linear times then `1` is output to indicate a truthy value, otherwise there is no output to indicate a falsy value.
> 2 votes

# Answer
# JavaScript (ES6), ~~75~~ 73 bytes

```
_=>"0123456543210".match((m=(new Date+"").match`([1-9].?):(..)`)[1]+m[2])

```

*2 bytes saved thanks to @Neil!*

## Explanation

*Credit to @busukxuan for the digit string idea!*

Checks the digits of the current time in the string `0123456543210`. Returns `null` for `false` and an array containing the time digits for `true`.

```
_=>
  "0123456543210".match(     // check if the time digits are in this string
    (m=
      (new Date+"")          // get a string with the current time (among other things)
      .match`([1-9].?):(..)` // get time digits with leading zero removed
    )
    [1]+m[2]                 // construct a string of only the time digits
  )

```
> 2 votes

# Answer
# Julia, ~~92~~ 71 bytes

```
f(d=diff(["$(Dates.hour(now()))""$(now())"[15:16]...]))=all(d[1]d.==1)

```

This is a function that takes no arguments and returns a boolean. To call it, simply execute `f()`.

We define the keyword argument `d` of `f` to be the cumulative difference in the ASCII codes associated with the digits of the hours and minutes of the current time. Then, for each difference, we multiply the first difference in the list by each successive difference and determine whether all are equal to 1. If so, the digits of the time are either monotone increasing by 1 or monotone decreasing by 1.

Saved 21 bytes and fixed an issue thanks to Dennis!
> 1 votes

# Answer
# Pyth, 38\*2.25 = 86 bytes

```
JsMfnT\:zK.b-NYt.>J1tJ|qlKlx1KqlKlx_1K

```

Try it here!

### Explanation

Works by converting the time to a list of integers, mapping this to a list of differences and checking if this list only contains -1 or 1.
Difference checking works by rotating the integer list one to right and doing an elementwise subtraction with the original integer list using all elements but the first one in each list.

```
JsMfnT\:zK.b-NYt.>J1tJ|qlKlx1KqlKlx_1K  # z = input

   fnT\:z                               # filter the : out
 sM                                     # map the digits to integers
J                                       # assign the list to J
          .b                            # parallel  map (with N and Y) to
            -NY                         # difference of N and Y
               t.>J1                    # over all but the first element of J, rotated right
                    tj                  # and all but the first element of J
         K                              # assign the result to K
                      |qlKlx1KqlKlx_1K  # check if K only contains -1 or 1

```
> 1 votes

# Answer
# Mathematica, ~~85~~ 84 bytes

```
#==Range[#[[1]],Last@#,Sign[Last@#-#[[1]]]]&@Flatten@IntegerDigits@DateList[][[4;;5]]

```

Pretty basic. Compares the time (as a list of digits) to a range from \[first digit\] to \[last digit\].
> 1 votes

# Answer
# Retina, ~~78~~ ~~63~~ ~~62~~ 60 * 125% = 135

```
:

.
$0$*aa:
^(a*)(:\1a:\1aa(:\1aaa)?|aaa:\1aa:+\1a(:\1)?):$

```

15 bytes thanks to Maria^H^H^H^H^HDigital Trauma, and for paving the way for 3 additional bytes.

Prints 1 for success, 0 for failure. I imagine this isn't optimal, but I can't think of a better approach. This method requires that 1 be added to each of the time digits, otherwise 0 causes some problems.

Try it online!

You can try a slightly modified program here that runs on multiple lines.
> 1 votes

# Answer
# Bash + coreutils, 59

```
t=`date +%-H%M`
((`eval printf %s {${t::1}..${t: -1}}`==t))

```

Shell return code is set to `0` (truthy) or `1` (falsey).

* Save just the hours and minutes numbers of the date in variable `t`
* Construct a bash brace expansion that runs from the first digit to the last digit of `$t`. The run produced by the expansion will automatically run in the right direction
* `eval` allows the variable expansions to happen before the brace expansion
* `printf` outputs the concatenated expansion as one string with no space separators
* The result will be equal to `$t` in the truthy case - arithmetic evaluation to test this is shorter than the usual `[ ... ]` test.

Ideone.
> 1 votes

# Answer
# Perl, ~~90~~ 65 bytes

```
@i=`date +%R`=~/\d/g;@n=reverse@m=0..9;print"@m"=~/@i/|"@n"=~/@i/

```

New approach: generate strings `"0 1 2 3 4 5 6 7 8 9"` and it's reverse and do a regexp match.

---

The previous approach (90 bytes):
```
@l=map{("$_=>1,","$_-")}`date +%R`=~/\d/g;@a=%h=eval"@l[1..$#l-1]";print@a==2&&1==abs$a[1]

```

Commented:

```
@l=
    map{
        ("$_=>1,","$_-")      # return parts of expressions
    }
    `date +%R`=~              # grab the time, quick 'n' dirty, and apply a regexp
       /\d/g;                 # match all digits and return a list

@a=                           # 'cast' the hash to a list
   %h=                        # 'cast' the list to a hash
      eval                    # evaluate the string
           "@l                # this string is interpolated as join ' ', @l
            [1..$#l-1]";      # but only after discarding the first and last element

print @a==2 && 1==abs $a[1]   # check that the hash has 1 key and that it's value is +1/-1

```

It's not going to win any prizes, but I had fun on this one so I'll share my work. The basic idea is the same as some/most other answers: calculate the deltas and make sure they are all either -1 or +1.

The expression that is `eval`ed for the time `12:34` is constructed as follows:

```
@l=                     [1,      $#l]          "@l[...]"                    %h
(("1=>1", "1-"),        (        "1-",
 ("2=>1", "2-"),  ->     "2=>1", "2-",   ->    1-2=>1, 2-3=>1, 3-4=>1      (-1 => 1)
 ("3=>1", "3-"),         "3=>1", "3-",
 ("4=>1", "4-"))         "4=>1",      )

```

Some things I tried that don't work:

* using `exit` to save a byte. It sometimes returns `2`.
* merely calculating the number of hash keys (74 bytes). This also matches all the time pattern where all the digits are the same.

```
@l=map{("$_=>1,","$_-")}`date +%F`=~/\d/g;%h=eval"@l[1..$#l-1]";print%h==1

```
* calculating the absolute normalized sum of the deltas (79 bytes). This grew from the approach to `eval` into a scalar. The total sum would have to be ±2 for 3 digits and ±3 for 4 digits, easily normalized with the `$#array` syntax. The false positive `12:24` made this approach unfeasible:

```
@l=map{($_,"+","$_-")}@x=`date +%R`=~/\d/g;print 1==eval"abs(@l[2..$#l-2])/$#x"

```
> 0 votes

# Answer
# Python 2, 93 bytes

```
import time,numpy
print len(set(numpy.diff([int(time.asctime()[10+k])for k in[1,2,4,5]])))==1

```

Not subject to the byte penalty. Small chance this doesn't work if `time.asctime()` changes during the loop. +4 bytes to fix this:

```
import time,numpy
x=time.asctime()
print len(set(numpy.diff([int(x[10+k])for k in[1,2,4,5]])))==1

```
> 0 votes

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


title: Let's do some “enciph5r47g”

text:
# Question
Title: Let's do some “enciph5r47g”
This is the inverse of Let's do some "deciph4r4ng"

---

In this challenge, your task is to encipher a string. Luckily, the algorithm is pretty simple: reading from left to right, each typical writing character (ASCII range 32-126) must be replaced by a number ***N*** (0-9) to indicate that it is the same as the character ***N+1*** positions before it. The exception is when the character does not appear within the previous 10 positions in the original string. In that case, you should simply print the character again. Effectively, you should be able to reverse the operation from the original challenge.

### Example

The input string `"Programming"` would be encoded this way:

Hence, the expected output is `"Prog2am0in6"`.

### Clarifications and rules

* The input string will contain ASCII characters in the range 32 - 126 exclusively. You can assume that it will never be empty.
* The original string is guaranteed not to contain any digit.
* Once a character has been encoded, it may in turn be referenced by a subsequent digit. For instance, `"alpaca"` should be encoded as `"alp2c1"`.
* References will never wrap around the string: only previous characters can be referenced.
* You can write either a full program or a function, which either prints or outputs the result.
* This is code golf, so the shortest answer in bytes wins.
* Standard loopholes are forbidden.

### Test cases

```
Input : abcd
Output: abcd

Input : aaaa
Output: a000

Input : banana
Output: ban111

Input : Hello World!
Output: Hel0o W2r5d!

Input : this is a test
Output: this 222a19e52

Input : golfing is good for you
Output: golfin5 3s24o0d4f3r3y3u

Input : Programming Puzzles & Code Golf
Output: Prog2am0in6 Puz0les7&1Cod74G4lf

Input : Replicants are like any other machine. They're either a benefit or a hazard.
Output: Replicants 4re3lik448ny3oth8r5mac6in8.8T64y'r371it9376a1b5n1fit7or2a1h2z17d.

```

# Answer
> 6 votes
# 05AB1E, ~~20 19~~ 18 bytes

-2 Thanks to Emigna

```
õ¹vDyåiDykëy}?yìT£

```

Try it online!

```
õ                  # Push an empty string
 ¹v y              # For each character in input
   D               # Duplicate the string on the stack (call this S)
     åi            # If this character is in S
       Dyk         #   Push the index of that that character
          ë }      # Else
           y       #   Push the character
             ?     # Print without newline
              yì   # Prepend this character to S
                T£ # Remove all but the first 10 elements from S

```

# Answer
> 12 votes
# Retina, ~~24~~ 23 bytes

```
(.)(?<=\1(.{0,9}).)
$.2

```

Try it online!

A fairly simple regex substitution. We match each character and try to find a copy of it 0-9 characters before it. If we find it, we replace the character with the number of characters we had to match to get to the copy.

The results don't quite match the test cases, because this one uses the largest possible digit instead of the smallest possible one.

# Answer
> 8 votes
## JavaScript (ES6), ~~74~~ ~~57~~ 54 bytes

*Saved 3 bytes thanks to ETHproductions with the brilliant `p=/./g` instead of `p={}` (inspired by Neil)*

```
s=>s.replace(p=/./g,(c,i)=>(i=p[c]-(p[c]=i))>-11?~i:c)

```

### Test cases

```
let f =

s=>s.replace(p=/./g,(c,i)=>(i=p[c]-(p[c]=i))>-11?~i:c)

console.log(f("abcd"));
console.log(f("aaaa"));
console.log(f("banana"));
console.log(f("Hello World!"));
console.log(f("this is a test"));
console.log(f("golfing is good for you"));
console.log(f("Programming Puzzles & Code Golf"));
console.log(f("Replicants are like any other machine. They're either a benefit or a hazard."));
```

# Answer
> 7 votes
# Haskell, ~~72~~ 66 bytes

*Thanks to Laikoni for golfing 6 bytes!*

```
(a:r)%s=last(a:[n|(n,b)<-zip['0'..'9']s,b==a]):r%(a:s)
e%s=e
(%"")

```

Try it online!

The function `%` keeps the partially processed string in reverse in its second argument, so it's able to search the first 10 elements of this string for occurences of the character it's examinating. The submission consists of the unnamed function `(%"")` which calls the previous function with the empty string as its second argument.

# Answer
> 5 votes
# Python 2, 64 bytes

```
s=''
for c in input():d=s[:~10:-1].find(c);s+=-d*c or`d`
print s

```

Try it online!

# Answer
> 3 votes
# Perl 5, 36 bytes

35 bytes of code + `-p` flag.

```
s/(\D)(.{0,9})\K\1/length$2/e&&redo

```

Try it online!

Some explanations:
The goal is to replace a non-digit character (`\D` but it correspond to the backreference `\1` in my regex) that is preceded by less than 10 characters (`.{0,9}`) and the same character (`(\D)`...`\1`) by the length of the `.{0,9}` group (`length$2`). And `redo` while characters get replaced.

# Answer
> 3 votes
# Python 2, ~~89~~ 84 bytes

```
m=input()[::-1];j=1;t=''
for i in m:s=m[j:].find(i);t=[i,`s`][0<s<10]+t;j+=1
print t

```

Try it Online!

Iterates throught the string in reverse, and builds a new string with the correct numbers inserted.

# Answer
> 3 votes
# Japt, 18 bytes

```
£¯Y w bX s r"..+"X

```

Try it online!

### Explanation

```
£   ¯  Y w bX s r"..+"X
mXY{s0,Y w bX s r"..+"X}
                          // Implicit: U = input string
mXY{                   }  // Replace each char X and index Y in U by this function:
    s0,Y                  //   Take U.slice(0,Y), the part of U before this char.
         w bX             //   Reverse, and find the first index of X in the result.
                          //   This gives how far back this char last appeared, -1 if never.
              s           //   Convert the result to a string.
                r"..+"X   //   Replace all matches of /..+/ in the result with X.
                          //   If the index is -1 or greater than 9, this will revert to X.
                          // Implicit: output result of last expression

```

# Answer
> 2 votes
# Python 3, ~~125~~ 118 bytes

```
def p(x):print(x,end='')
l={}
for i,c in enumerate(input()):
 if l.get(c,i+9)<i+9:
  p(i-l[c]-1)
 else:
  p(c)
 l[c]=i

```

Try it online!

# Answer
> 2 votes
# JavaScript, ~~100~~ 80 bytes

```
x=>x.split``.map((c,b,a)=>{for(i=0;i++<=9&&a[b-i]!=c;);return i>9?c:i-1}).join``

```

Try it online!

# Answer
> 2 votes
# 05AB1E, 20 bytes

```
õIv¹N£RT£©yåi®ykëy}J

```

Try it online!

**Explanation**

```
õ                     # push an empty string
 Iv                   # for each [index,char] [N,y] in input
   ¹N£                # push the first N characters of input
      R               # reverse
       T£             # take the first 10 characters of this string
         ©            # save a copy in register
          yåi         # if y is in this string
             ®yk      #   push the index of y in the string in register
                ë     # else
                 y    #   push y
                  }   # end if
                   J  # join stack as one string

```

# Answer
> 2 votes
# C (tcc), 113 bytes

Since the function creates a copy of an input string, the maximum size of input is 98 characters (more than enough to fit the longest test input). Of course, this can be changed to any other value.

```
i,j;f(char*s){char n[99];strcpy(n,s);for(i=1;s[i];i++)for(j=i-1;j>-1&&i-j<11;j--)if(n[i]==n[j])s[i]=47+i-j;j=-1;}

```

Try it online!

**Edit**

-15 bytes. Thanks **Johan du Toit**.

# Answer
> 2 votes
# Java 7, ~~102~~ 101 bytes

```
void a(char[]a){for(int b=a.length,c;--b>0;)for(c=b;c-->0&c+11>b;)if(a[c]==a[b])a[b]=(char)(b-c+47);}

```

Try it online!

-1 byte thanks to Kevin Cruijssen. I always enjoy an excuse to use the goes-to operator.

# Answer
> 1 votes
# MATL, ~~31~~ 30 bytes

```
&=R"X@@f-t10<)l_)t?qV}xGX@)]&h

```

Try it at **MATL Online!**

**Explanation**

```
        % Implicitly grab input as a string
&=      % Perform element-wise comparison with automatic broadcasting.
R       % Take the upper-triangular part of the matrix and set everything else to zero
"       % For each column in this matrix
X@      % Push the index of the row to the stack
@f      % Find the indices of the 1's in the row. The indices are always sorted in
        % increasing order
-       % Subtract the index of the row. This result in an array that is [..., 0] where
        % there is always a 0 because each letter is equal to itself and then the ...
        % indicates the index distances to the same letters
t10<)   % Discard the index differences that are > 9
l_)     % Grab the next to last index which is going to be the smallest value. If the index
        % array only contains [0], then modular indexing will grab that zero
t?      % See if this is non-zero...
  qV    % Subtract 1 and convert to a string
}       % If there were no previous matching values
  x     % Delete the item from the stack
  GX@)  % Push the current character
]       % End of if statement
&h      % Horizontally concatenate the entire stack
        % Implicit end of for loop and implicit display

```

# Answer
> 1 votes
# PHP, 104 Bytes

forward solution

```
for($i=0;$i<strlen($a=&$argn);$f[$l]=$i++)$a[$i]=is_int($f[$l=$a[$i]])&($c=$i-$f[$l]-1)<10?$c:$l;echo$a;

```

Backwards solutions

Online Versions

## PHP, 111 Bytes

```
for(;++$i<$l=strlen($a=&$argn);)!is_int($t=strrpos($argn,$a[-$i],-$i-1))?:($p=$l-$i-$t-1)>9?:$a[-$i]=$p;echo$a;

```

## PHP, 112 Bytes

```
for(;++$i<$l=strlen($a=&$argn);)if(false!==$t=strrpos($argn,$a[-$i],-$i-1))($p=$l-$i-$t-1)>9?:$a[-$i]=$p;echo$a;

```

Online Version

# Answer
> 1 votes
## REXX, ~~124~~ 125 bytes

```
a=arg(1)
b=a
do n=1 to length(a)
  m=n-1
  c=substr(a,n,1)
  s=lastpos(c,left(a,m))
  if s>0&m-s<=9 then b=overlay(m-s,b,n)
  end
say b

```

# Answer
> 1 votes
# C (gcc), ~~117~~ ~~103~~ 93 bytes

```
i,j;f(char*s){for(i=strlen(s)-1;s[--i];)for(j=i-1;s[j]&&i-j--<10;)if(s[i]==s[j])s[i]=47+i-j;}

```

Try it online!

No string.h import, works w/ warning. If this is against the rules, I'll pull it.

## Pretty Code:

```
i,j;
f(char *s) {
    // Chomp backwards down the string
    for(i=strlen(s)-1; s[--i];)
        // for every char, try to match the previous 10
        for(j=i-1; s[j] && i-j-- < 10;)
            // If there's a match, encode it ('0' + (i-j))
            if (s[i] == s[j])
                s[i] = 47+i-j;
}

```

## Edits:

* Changed from LLVM to gcc to allow implicit i,j declaration, removed lib import.
* Added function wrapper for compliance
* Decrement in loop boundaries thanks to **ceilingcat**
* Removed `break` and braces from loop, first match modifies \`s\[i\]

---
Tags: code-golf, string, cipher
---


title: Make me a real-time reputation counter!

text:
# Question
Title: Make me a real-time reputation counter!
Recently, I have found my reputation changing time to time. I would like to know my reputation changing real-time.

---

# The job

Given an id of a user on PPCG (ex.64499), Print the user's reputation every 10 seconds. You may ignore the daily quota.

---

# Examples

```
64499
3808
40695

```

---

# Possible output format

```
12345
12,345

```

# Answer
> 4 votes
# Bash \+ coreutils + w3m, ~~90~~ ~~71~~ ~~69~~ 67 bytes

```
watch -tn10 w3m codegolf.stackexchange.com/u/$1\|grep -Pom1 ^[,-9]+

```

Takes the user ID as a command line argument and displays the reputation of the corresponding user (e.g., `135,249`) in the upper left corner of the terminal.

### Alternate version, 57 bytes, invalid?

```
watch -tn10 w3m codegolf.stackexchange.com/u/$1\|sed 44!d

```

This displays `135,249 reputation` instead of `135,249`.

---
Tags: code-golf, stack-exchange-api
---


title: My source is in order, is yours?

text:
# Question
Title: My source is in order, is yours?
Your challenge is to write a program, function, etc. that calculates if the passed string is "in order". That means that the characters of the string have character codes that are in order from smallest to largest. The smallest char code must be the first. By that I mean lowest unicode codepoints to highest. It doesn't matter what code page you language uses.

You must return one value if the input is "in order" and another if it is not. The values must be distinct, but there is no other restriction on the output values. For example, you may print/return/output `true` for `!1AQaq¡±` (in order) and `false` for `aq!QA`. The two distinct values don't need to be truthy or falsy or anything like that, just two distinct values. Repeated strings (eg. `aa`) are in order.

You only need to support up to unicode `U+007E` (`~`) (ascii 126)

However, the characters of your program must itself be in order. Good luck and happy ing!

# Answer
# Brachylog, 2 bytes

```
.o

```

Try it online!

## Explanation

```
.o
.   Assert that {the input} equals the output of the last command in the program
 o  Sort {the input}

```

As a full program, an assertion failure gives `false.`, any successful run that doesn't violate any assertions gives `true.`
> 13 votes

# Answer
# Jelly, 2 bytes

```
Ṣ⁼

```

Try it online!

## Explanation

```
Ṣ⁼
Ṣ    Sort {the input}
 ⁼   Compare that to {the input} for equality of the whole structure

```

`⁼Ṣ` also has the right functionality ("compare the input to the sorted input"), so it was just a case of running the two programs on themselves to figure out which was in order (I certainly don't have the Unicode codepoints of this part of Jelly's weird character set memorized).
> 8 votes

# Answer
# MATL, 5 bytes

```
GGS\a

```

Outputs `0` if input is in order, `1` otherwise.

Try it online!

### Explanation

This computes the modulus of (the code points of) each char from the input with that at the same index in the sorted input. The input is in order if and only if all results are `0`.

For example, consider the input string `BCD!`. Sorting it gives `'!BCD`. The arrays of code points are respectively `[66 67 68 33]` and `[33 66 67 68]`. Computing the moduli gives `[0 1 1 33]`, so the input is not in order. Note how some results can be `0` even if the values were not the same (here that happens at the first position), but that cannot happen in *all* entries unless the input is in order.

```
G     % Push input string
GS    % Push input string and sort it
\     % Modulus, element-wise. This gives all zeros iff the input was in order
a     % Any: gives 1 if any entry is non-zero. Implicitly display

```
> 8 votes

# Answer
# 05AB1E, ~~3~~ 2 bytes

Thanks to Kevin for cutting out 33% of my source code!

Try it online!

Explanation:

```
      There used to be a D here for 'Duplicate stack'
      but we now use the same input twice implicitly
 {    Sort the copy
  å   Check if the sorted copy is a substring of the original
      This will only return 1 if the original input is sorted, 0 otherwise.

```
> 7 votes

# Answer
# Pyke, 2 bytes

```
Sq

```

Try it online!

```
S  - sorted(input)
 q - ^ == input

```
> 5 votes

# Answer
# 2sable, 2 bytes

Try it online!

**Explanation**

```
{    # sorted input
 Ê   # not equals (implicit input)

```

Outputs **0** if it is order, else **1**.
> 4 votes

# Answer
# Pyth, 2 bytes

```
<S

```

`False` means sorted, `True` means unsorted.

Test suite

This was fairly nontrivial to come up with. The most obvious solution to this problem, without the restricted source, is `SI`, invariant under sorting. But that's not sorted. Then I thought of `qS`, which implicitly uses the input variable twice, checking if it's equal to its sorted self. But while `q < s`, `q > S`, so this didn't work either. But `<` comes before `S`, and the only way that the sorted version can not be less than the original is if the original was sorted, since the sorted version is the lexicographically minimal permutation of the elements.
> 2 votes

# Answer
# CGL (CGL Golfing Language), 4 bytes

```
-:Sc

```

Explanation:

```
- Decrement the stack counter so the current stack is where input is put
: Split the first element of the current stack (input) into an array of single strings, make that the next stack, and increment the stack counter
S Sort the current stack
c Compare the current stack and the one before, push that to the next stack and increment the stack counter
(implicit) Output the first element of the current stack, true if in order, false if not.

```
> 1 votes

---
Tags: code-golf, restricted-source
---


title: Lego Gear Train

text:
# Question
Title: Lego Gear Train
Inspired by the Lego gear ratios challenge by Keith Randall.

I, too, plan on building a giant lego robot that will eventually be able to destroy the other robots in the never-before-mentioned competition.\* In the process of constructing the robot, I will be using a lot of gear trains to connect different parts of the robot. I want you to write me the shortest program that will help me construct the complex gear trains that are required for such a complex task. I will, of course, only be using gears with radii 1, 2, 3, and 5 arbitrary-lego-units.

Each gear in the gear train has a specific integer coordinate on a 2D grid. The first gear is located at (0,0) and the final gear will be located at non-negative coordinates. The location and size of the first and last gears will be provided as input, your program must tell what gears go where to fill in the gaps.

Additionally, your program must use the **minimum possible number** of gears in the gear train. Fewer gears / train = more trains\** = bigger and better robot of destruction.

**Input** will consist of one line:

```
X,Y,B,A

```

X and Y are the coordinates of the final gear. The first gear is always located at (0,0). B and A are the radii of the final and initial gears, respectively. To add some difficulty, you need to make sure that the output gear **rotates in the correct direction.** If A and B have the same sign, then the output gear needs to rotate in the same direction, and an odd number of gears must be used. If they have opposite signs, then an even number of gears need to be used.

**Output** should be a list of the X location, Y location, and radii of each additional gear, one gear per line. If there are multiple minimal-gear solutions, print only one of your choice. The order of gears in the output does not matter.

**Examples (more equivalent solutions may be possible):**

```
in
4,0,1,1
out
2,0,1

in
7,7,-2,-2
out
4,3,3
OR
0,7,5
OR
the above reflected over y=x line

in
7,8,-1,2
out
7,0,5
7,6,1
OR
7,0,5
1,8,5

in
7,7,2,-2
out
4,-3,3
7,1,2
12,1,3
12,7,3
OR
any permutation of the above, or reflected over y=x line
Now you're thinking with gear trains!

```

Here's the solutions to the above examples, visualized:

As far as I know, no problem is impossible unless the two input gears overlap or directly connect. You won't have to deal with this.

This is code golf, shortest answer wins.

---

\*A future KOTH, anyone?

\**CHOO CHOO!!

# Answer
# C#, 660 bytes

```
using System.Linq;using System;class P{int p=1,x,y,r;P l;static void Main(){var Q="$&.$'7$(@$*R$'/$(8$)A'(A('A$+S$(0$)9'(9('9$*B$,T$*2$+;$,D$.V*,V,*V";var I=Console.ReadLine().Split(',').Select(int.Parse).ToList();int i=0,t,s=7,u,v,w,p=I[3]*I[2];for(var D=new[]{new P{r=Math.Abs(I[3]),l=new P{r=Math.Abs(I[2]),x=I[0],y=I[1],p=3}}}.ToList();i>=0;){P c=D[i++],l=c.l;for(;(l=l?.l)!=null&&(s=(t=c.x-l.x)*t+(t=c.y-l.y)*t-(t=c.r+l.r)*t)>0;);if(s==0&&l.p>2&p*c.p<0)for(i=-1;c.l.p<3;c=c.l)Console.WriteLine(c.x+","+c.y+","+c.r);for(t=0;s>0&t<66;t++)for(u=Q[t++]-36,v=Q[t++]-36,s=1;s++<5&Q[t]%9==c.r;w=u,u=v,v=-w,D.Add(new P{l=c,r=Q[t]/9-4,x=c.x+u,y=c.y+v,p=-c.p}));}}}

```

Try It Online

This was a *lot* of fun!! Complete program, accepts input from STDIN, output to STDOUT. Output is the gears in order from the end to the start. Usage:

Performs a simple Breadth First Search, which solves a 4-gear problem in less than a second. Branching factor isn't actually that large, so it's it should be good for considerably more (not really tested it). Sadly it uses Linq.

The `Q` string is a table of all allowed gear connections (i.e an `r=3` and connect to an `r=1` if `dx=4` and `dy=0`) in one quadrant, which is then rotated to find the others. Every set of 3 bytes is the `dx`, `dy`, and radius information for a legal connection. The choice of `(` as an offset was *very* deliberate: it was fun for once to be choosing an ASCII character for nice properties, rather than desperately trying to find nice properties for imposed ASCII characters.

I can probably do a better job of reading the input, but I've had no luck yet, not least because the Linq is paid for by the need for a list. I'm also very disappointed by the rotate code, I feel like that could be done in considerably fewer bytes.

Formatted and Commented Code with `Q` generator:

```
using System.Linq; // seems to pay today
using System;

class P
{
    static void GenQ()
    {
        int t, k = 0, m = 0;
        Func<P, P, int> C = (P c, P l) => (t = c.x - l.x) * t + (t = c.y - l.y) * t - (t = c.r + l.r) * t; // ==0 -> touching, <0 -> not touching, >0 -> overlap

        string str = "";

        string T(int i) => "" + (char)('$' + i); // $ is zero, '$' == 36, so we can mod and div by 9, and greater than " so we don't have to escape it

        foreach (int r in new[] { 1, 2, 3, 5 }) // at 0,0 (current gear)
            foreach (int s in new[] { 1, 2, 3, 5 }) // gear to place
                for (int i = 0; i <= r + s; i++) // x
                    for (int j = 1; j <= r + s; j++, m++) // y
                        if (C(new P { r = r }, new P { r = s, x = i, y = j }) == 0) //
                        {
                            str += T(i) + T(j) + T(r + s * 9);
                            k++;
                        }

        System.Console.WriteLine("K : " + k);
        System.Console.WriteLine("M : " + m);
        System.Console.WriteLine(str);
        System.Console.ReadKey(true);
        return;
    }

    int p=1, // parity
        x, // x
        y, // y
        r; // radias (TODO: store radias^2 ?)
    P l; // previous in search list

    static void Main()
    {
        //GenQ();

        // '$' == 36 (4*9)
        // 3char blocks: x,y,r+9*s
        var Q="$&.$'7$(@$*R$'/$(8$)A'(A('A$+S$(0$)9'(9('9$*B$,T$*2$+;$,D$.V*,V,*V"; // quarter table

        // primative read ints
        var I=Console.ReadLine().Split(',').Select(int.Parse).ToList();

        int i=0, // position in Due
            t, // check differential cache, position in Q
            s=7, // check cache, rotation counter (>0)
            u, // rotation x
            v, // rotation y
            w, // rotation x cache
            p=I[3]*I[2]; // parity (>0 -> same, even ; <0 -> different, odd)

        // due (not point using a queue, the search space grows exponentially)
        for(var D=new[]{
                new P{r=Math.Abs(I[3]), // start (p==1)
                    l=new P{r=Math.Abs(I[2]),x=I[0],y=I[1],p=3} // terminal (detect with p==3)
                }}.ToList();
            i>=0;) // infinite number of configurations, no bounds, i is escape term
        {
            P c=D[i++], // current
                l=c.l; // check, initially the one before the previous (we know we are touching last already)

            // 'checks' c against l
            //Func<int>C=()=>(t=c.x-l.x)*t+(t=c.y-l.y)*t-(t=c.r+l.r)*t; // ==0 -> touching, >0 -> not touching, <0 -> overlap

            // check we arn't touching any before us (last thing we check is terminal)
            for(;(l=l?.l)!=null&& // for each before us (skipping the first one)
                (s=(t=c.x-l.x)*t+(t=c.y-l.y)*t-(t=c.r+l.r)*t)>0;); // check c against l and cache in s, ==0 -> touching, >0 -> not touching, <0 -> overlap

            if(s==0&& // touching last checked?
                l.p>2& // stopped on terminal?
                p*c.p<0) // correct parity? -> win
                for(i=-1; // escape
                    c.l.p<3;c=c.l) // for each that wasn't the first
                    Console.WriteLine(c.x+","+c.y+","+c.r);

            // enumerate possible additions, and queue them in due
            for(t=0;
                s>0& // not touching or overlapping anything (including terminal)
                t<66;t++) // 66 = Q.Length
                for(
                    u=Q[t++]-36, // '$'
                    v=Q[t++]-36,
                    s=1;s++<5& // rotate 4 times
                    Q[t]%9==c.r; // our raidus matches
                        w=u, // chache y value
                        u=v, // rotate
                        v=-w,
                        D.Add(new P // add
                        {
                            l=c,
                            r=Q[t]/9-4, // radius
                            x=c.x+u,
                            y=c.y+v,
                            p=-c.p // flip parity
                        }));
        }
    }
}

```
> 2 votes

---
Tags: code-golf, geometry
---


title: Help Gödel with his β function

text:
# Question
Title: Help Gödel with his β function
Gödel's β function takes three natural numbers as arguments.

It is defined as `β(x,y,z) = rem(x, 1 + (z + 1) · y) = rem(x, (z · y + y + 1) )`

where rem(a, b) denotes the remainder after integer division of a by b.

The β Lemma now states that:

> For any sequence of natural numbers (k\_0, k\_1, … , k\_n), there are natural numbers b and c such that, for every i ≤ n, β(b, c, i) = k\_i.

Gödel needs help to find `b` and `c` for any given input `(k_0, k_1, … , k_n), k_i ∈ ℕ`.

---

Write a function that takes in an array of length `n`, filled with natural numbers, and gives a possible `b,c` output that fulfilles the Lemma for the array.

---

Do not get solutions by brute force!

(In my totally unprofessionall opinion, it is brute force when you first get a number and then do the calculation. That is guessing the number and then looking if the guess was correct. What I want to be coded here is a solution which calculates the numbers and does not have to check whether they fulfill the lemma because they were calculated to do so. )

Construct them with the equations and information given. Shortest code wins, bonus points if you do it in `Javascript` because I am just getting into it `:)`

---

Example:

```
[5, 19, 7, 8] -> (1344595, 19)
1344505 % (1 + (0 + 1) * 19) = 5
1344505 % (1 + (1 + 1) * 19) = 19
1344505 % (1 + (2 + 1) * 19) = 7
1344505 % (1 + (3 + 1) * 19) = 8

```

# Answer
## JavaScript (ES6), 104 bytes

```
a=>[c=a.reduce(c=>c*++i,Math.max(...a),i=0),a.reduce(g=(x,k)=>x%m-k?g(x+n,k):(n*=m,m+=c,x),0,n=1,m=c+1)]

```

Returns `[c, b]` as an array. The solution it returns isn't minimal in `c` but I think it is minimal in `b` for the given `c`. For 120 bytes this returns solutions minimal in `c` and in `b` for the given `c`:

```
f=(a,c=1,b=a.reduce(g=(x,k)=>x%m-k?d--?g(x+n,k):0/0:n%m?g(x,k,n+=o):(o=n,d=m+=c,x),0,o=n=1,d=m=c+1))=>1/b?[b,c]:f(a,c+1)

```

Ungolfed minimal solution solver:

```
function godel(a) {
    for (c = 0;; c++) {
        var b = 0, n = 1, i = 0;
        for (;;) {
            var m = c * i + c + 1;
            // Increase b until β(b,c,i) = a[i]
            // Adding n won't change output for smaller i
            for (j = 0; j < m; j++) if (b % m != a[i]) b += n;
            if (j == m) break; // couldn't find a remainder, c too low
            i++;
            if (i == a.length) return [b, c]; // Result!
            // Next time we want adding n to b not to change β(b,c,i)
            for (j = 1; n * j % m != 0; j++);
            n *= j;
        }
    }
}

```
> 3 votes

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