title: Cell phone Charge

text:
# Question
Title: Cell phone Charge
Challenge Taken with permission from my University Code Challenge Contest

---

The dependence we have on mobile phones makes us charge them every night up to the maximum level of the battery, so we do not run the risk of running out of power by the middle of the next day. There are even people who, when they see a free outlet during the day, put it to charge for what may happen.

I am one of them.

Over the years, I have refined my technique to not charge the battery to the maximum every night. With my perfectly known repetitive routines, I am clear on what times of the day I will be able to do those partial recharges (and how many units the level will increase) and what lowers the battery level between each charge. With these data, every night I calculate the minimum battery level I have to leave the house the next day with so that it never falls below my self-imposed threshold of two units.

What I have not yet managed to master is that same calculation when I leave the established routine and I have several alternatives to do things. It happens, for example, on the days when I'm en route to another city to which I can arrive in different ways.

In my first approach to the problem, I am assuming that I want to move around a "chessboard", from the upper-left corner to the lower-right corner. In each "cell" I can either charge the mobile a specific amount, or I cannot and its load level goes down.

**Challenge**

Given a FxC matrix of integers, output the minimal battery level amount I need to go from the top-left corner to the bottom-right without the load level ever falling below 2 units.

In the matrix, a positive number indicates how much I can charge my mobile phone before I have to resume following my path, while a negative number indicates that there are no outlets and that the mobile's battery drops its charge level by that amount. It is guaranteed that the quantities in the source and destination cells (top-left and bottom-right corner) are always 0 and that the rest of the values (absolute value) do not exceed 100.

**Example**
Given: $$ \begin{bmatrix} &-1&1&-1 \\ -1&-1&-1&-1 \\ -1&1&-1&-1 \\ 1&1&-1&0 \end{bmatrix}$$

The path I need less battery is:

$$ \begin{bmatrix} &-1&1&-1 \\ \color{blue}{-1}&-1&-1&-1 \\ \color{blue}{-1}&1&-1&-1 \\ \color{blue}{1}&\color{blue}{1}&\color{blue}{-1}&0 \end{bmatrix}$$

And the minimal battery level amount I need is 4

**Notes**

* The Start is always going to be the top-left corner
* The End is always going to be the bottom-right corner
* You cannot go to a cell you've already passed. Example: Once in position (0,1), you cannot go to the initial point (0,0)
* Your battery level cannot (for any reason) go under 2
* You can assume there will always be a beginning and an end
* You can take the 1-dimensional arrays as multidimensional if you need to `[1,2,3] == [[1,2,3]]`
* There can be multiple correct (minimal needed charge) paths
* Your goal is to only output the lowest initial battery level needed, not the route
* You can only go vertically and horizontally (not diagonally)

**Test Cases**

```
[0, 0] => 2
[0, 1, 0] => 2
[0, -1, 0] => 3
[0, 15, -20, 5, 0] => 7
[[0, -3],[-5, 0]] => 5
[[0, -5, -9, 5], [-3, 5, 2, -2], [2, -4, -4, 0]] => 5
[[0, -1, 1, -1], [-1, -1, -1, -1], [-1, 1, -1, -1], [1, 1, -1, 0]] => 4

```

# Answer
# Python 2, ~~208~~ 202 bytes

```
lambda s:2-f(s)
def f(s,x=0,y=0):
 if x>-1<y<s[y:]>[]<s[y][x:]!="">s[y][x]:k=s[y][x];s[y][x]="";return k+min(0,max([len(s[y+1:]+s[y][x+1:])and f(eval(`s`),x+a/3-1,y+a%3-1)for a in 7,1,5,3]))
 return-9e9

```

Try it online!

---

# Python 2, ~~217~~ 211 bytes

```
i=input()
X,Y=len(i[0]),len(i)
s=[[0]*4+[i]];r=[]
for m,l,x,y,g in s:
 if X>x>-1<y<Y<"">g[y][x]:r+=[m]*(Y-y<2>X-x);l+=g[y][x];g[y][x]="";s+=[[min(m,l),l,x+a/3-1,y+a%3-1,eval(`g`)]for a in 7,1,5,3]
print 2-max(r)

```

Try it online!
> 3 votes

# Answer
# JavaScript (ES7),  ~~162 156~~  154 bytes

```
m=>(M=g=(x,y,n,k)=>m.map((r,Y)=>[r[x+1]]+[m[y+1]]?r.map((v,X)=>r[1/v&&(x-X)**2+(y-Y)**2==1&&g(X,Y,u=v+n,k<u?k:u,r[X]=g),X]=v):M=M>k?M:k))(0,0,0)|M<0?2-M:2

```

Try it online!

### Commented

```
m => (                          // m[] = input matrix
  M =                           // initialize M to a non-numeric value
  g = (x, y, n, k) =>           // g = recursive depth-first search function
    m.map((r, Y) =>             // for each row r[] at position Y in m[]:
      [r[x + 1]] +              //   if either r[x + 1]
      [m[y + 1]] ?              //   or m[y + 1] is defined:
        r.map((v, X) =>         //     for each value v at position X in r[]:
          r[                    //
            1 / v &&            //       if v is numeric
            (x - X) ** 2 +      //       and the squared Euclidean distance
            (y - Y) ** 2 == 1   //       between (x, y) and (X, Y) is 1:
            &&                  //
              g(                //         do a recursive call:
                X, Y,           //           with (X, Y)
                u = v + n,      //           with n = n + v
                k < u ? k : u,  //           with k = min(k, n + v)
                r[X] = g        //           set r[X] to a non-numeric value
              ),                //         end of recursive call
            X                   //       then restore r[X]
          ] = v                 //       to its initial value
        )                       //     end of inner map()
      :                         //   else (we've reached the bottom right corner):
        M = M > k ? M : k       //     update M to max(M, k)
    )                           // end of outer map()
)(0, 0, 0) |                    // initial call to g with x = y = n = 0 and k undefined
M < 0 ? 2 - M : 2               // return 2 - M if M is negative, or 2 otherwise

```
> 3 votes

# Answer
# , ~~224~~ ~~220~~ ~~217~~ ~~213~~ 210 bytes

```
f=function(x,m=rbind(0,cbind(0,x,0),0),i=2,j=2,p=F,k=c(1:-1,0,0,-1:1),b=Inf,`^`=min){m[i,j]=0
for(h in 1:4)b=b^'if'(all(c(R<-i+k[h],C<-j+k[h+4])>dim(x)),max(2,2-cumsum(p)^0),if(v<-m[R,C])b^f(x,m,R,C,c(p,v)))
b}

```

Try it online!
> 1 votes

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

```
a=>{int m=1<<31,n=~m;void g(int w,int x,int y,int z){for(int i=4,t,c,d,e;i-->0;)try{t=a[c=i<1?w-1:i<2?w+1:w,d=i>2?x-1:i>1?x+1:x];n=t==0&z<n?z:n;a[c,d]=m;e=y+t<2?2-y-t:0;if(t!=m)g(c,d,y+t+e,z+e);a[c,d]=t;}catch{}}a[0,0]=m;g(0,0,2,2);return n;}

```

Try it online!

```
//a: input matrix
a=>{
  // m: marker for used cells
  // n: result, initialized to a huge value
  int m=1<<31,n=~m;
  // recursive function
  // w: 1st dim coordinate
  // x: 2nd dim coordinate
  // y: current charge level
  // z: initial charge for current path
  void g(int w,int x,int y,int z){
    // i: loop variable
    // t: temp holds overwritten value
    // c: adjacent 1st dim coordinate
    // d: adjacent 2nd dim coordinate
    // e: delta charge needed
    for(int i=4,t,c,d,e;i-->0;)
      // avoid index out of range errors
      // by using try/catch
      try{
        // determine neighbor
        // coordinates and save value
        t=a[c=i<1?w-1:i<2?w+1:w,
            d=i>2?x-1:i>1?x+1:x];
        // if we have found a 0, check if
        // initial charge is lower than the
        // lowest so far. save it if it is.
        n=t==0&z<n?z:n;
        // mark current cell used
        a[c,d]=m;
        // determine if we need to
        // increase the initial charge
        e=y+t<2?2-y-t:0;
        // make recursive call if current
        // cell was not previously in use
        if(t!=m)g(c,d,y+t+e,z+e);
        // restore current cell value
        a[c,d]=t;
      }catch{}
  }
  // mark starting cell used
  a[0,0]=m;
  // start the recursive function
  g(0,0,2,2);
  // return the result to the caller
  return n;
}

```
> 1 votes

---
Tags: code-golf, matrix, path-finding
---


title: Superpermutations

text:
# Question
Title: Superpermutations
# Introduction

You're a criminal tasked with stealing some secret plans from the new tech startup Dejavu. You sneak in over the back wall, but find a door that requires a pin to open it. You recognize the make of the lock and know that it takes a 5 digit pin using all numbers from 0 to 4. After each digit entered, the lock checks the last 5 digits entered and opens if the code is correct. You have to get past this lock, and fast.

# Superpermutations in a Nutshell

A permutation is all possible combinations of a certain set of digits. for example, all the permutations of the digits 0, 1, 2 are:

012, 021, 102, 120, 201, and 210.

If we concatenate all these permutations together, we get a superpermutation:

012021102120201210

this superpermutation contains all the permutations of 0, 1, 2, but it's possible to make one shorter than this. I'm going to skip a bit here, but the shortest superpermutation of these digits is:

012010210

For our intents and purposes, this is essentially the shortest string of digits that contains all possible permutations of those digits, i.e. a superpermutation.

# Task

Your task is a bit harder than the superpermutation example as shown above, because you have two more digits to worry about. - If you haven't read about superpermutations, or my example above was a bit unclear, I highly suggest you read this great article by Patrick Honner on the subject (this challenge was quite heavily inspired by his article, so kudos to him): https://www.quantamagazine.org/unscrambling-the-hidden-secrets-of-superpermutations-20190116/. Your goal is to write the shortest program possible that generates a superpermutation of the digits 0 to 4.

# Scoring

Your program does not take any input of any sort, and produce a superpermutation of the digits from 0 to 4. This resulting superpermutation must be printed to the console or visibly displayed to the user to the extent provided by your language of choice. This doesn't have to be the shortest permutation possible, it just has to be a valid superpermutation. Because of this, the goal is to write the shortest program with the shortest superpermutation, so you should calculate your score like so:

**file size (bytes) * generated superpermutation length (digits)**

for example, if I had a 40 byte program, and my superpermutation is 153 digits long, my score will be:

**40 * 153 = 6120**

as always, the goal is to get this score as low as possible.

# Template

Here is how you should post your answer:

> ## Language | Score
>
> link to code in working environment (if possible)
>
> `code snippet`
>
> code explanation, etc.

# Finalities

This is one of my first questions on this site. So please tell me if I'm missing anything or a section of my challenge is unclear. Thank you, and have fun golfing!

# Answer
# 05AB1E, score = 1673 (7 bytes · 239)

```
žBœ∊{3ý

```

Try it online!

### How it works

```
žB          push 1024
  œ         permutations: ["1024", "1042", …, "4201"]
   ∊        vertically mirror: ["1024", "1042", …, "4201", "4201", …, "1042", "1024"]
    {       sort: ["0124", "0124", "0142", "0142", …, "4210", "4210"]
     3      push 3
      ý     join: "01243012430142301423…3421034210"

```

# Pyth, score = 1944 (9 bytes · 216)

```
s+R+4d.p4

```

Try it online!

### How it works

```
 +R   .p4   append to each permutation d of [0, 1, 2, 3]:
   +4d        [4] + d
s           concatenate

```
> 6 votes

# Answer
# Brachylog, score = 2907 (19 bytes × 153)

```
4⟦pᶠP∧~l.g;Pz{sᵈ}ᵐ∧

```

Too slow to see anything, but if you change `4` by `2` you can test it: Try it online!

This finds the shortest superpermutation as such:

```
4⟦                   The range [0,1,2,3,4]
  pᶠP                P is the list of all permutations of this range
     ∧
      ~l.            Try increasing lengths for the output
         g;Pz        Zip the output with P
             {sᵈ}ᵐ   For each permutation, it must be a substring of the output
                  ∧

```
> 3 votes

# Answer
# Python 2, Score: ~~24327~~ ~~15147~~ ~~12852~~ 12628 (154\*82 bytes)

```
S=str(int('OH97GKT83A0GJRVO309F4SGSRWD0S2T292S1JBPVKJ6CRUY8O',36))
print S+S[::-1]

```

Try it online!

---

Also:

# Python 2, 12628 (154\*82 bytes)

```
S=oct(int('FS02C3XQJX14OTVMGM70CGCPWU41MNJZ0CO37ZMU0A0Y',36))[:-1]
print S+S[::-1]

```

Try it online!
> 2 votes

# Answer
# 05AB1E, score: ~~5355~~ 2160 (216 * 10 bytes)

```
3ÝœJε4yJ}J

```

Port of *@AndersKaseorg*'s Pyth answer, so make sure to upvote him!

Try it online.

**Explanation:**

```
3Ý           # Push a list in the range [0,3]: [0,1,2,3]
  œ          # Get all possible permutations of this list
   J         # Join each inner list together to a single string
    ε        # Map each string `y` to:
             #  (Push string `y` implicitly)
     4       #  Push 4
      y      #  Push string `y` again
       J     #  Join all three together
        }J   # After the map: Join all strings together to a single string
             # (and output it implicitly as result)

```
> 2 votes

# Answer
# Jelly, 3000 (600\*5 bytes)

```
5ḶŒ!F

```

Try it online!
> 2 votes

# Answer
# JavaScript (ES6), 26975 (325 * 83 bytes)

With this scoring system, there's little room for something between *'hardcode the optimal supermutation'* and *'just use a short built-in to concatenate all permutations'*, at least in non-esolangs.

Here's an attempt anyway.

```
f=(a=[0,1,2,3,4],p=r='')=>a.map((v,i)=>f(a.filter(_=>i--),p+v))|~r.search(p)?r:r+=p

```

Try it online!

It generates a string of 325 bytes:

```
012340124301324013420142301432021340214302314023410241302431031240314203214032410341203421
041230413204213042310431204321102341024310324103421042310432201342014320314203412041320431
210342104330124301423021430241304123042131024310423201432041321044012340132402134023140312
4032141023410324201342031421034301243021431024320143210

```
> 2 votes

# Answer
# Octave, 27 x 442 = 11934

```
'01234'(perms(1:5)'(4:445))

```

Try it online!

So, it turns out, naively generating *all* the permutations and then truncating to the shortest substring that is still a valid superpermutation is shorter than generating the shortest superpermutation. Sadly, this time the score is not a palindrome.

### Octave, 97 x 153 = 14841

```
a=sym(9);while i<120
i=0;a+=1;q='01234';for t=q(perms(1:5))'
i+=any(regexp(char(a),t'));end
end
a

```

Try it online!

Entry updated for a few things

* `a++` is not implemented for symbolic numbers.
* `contains()` is not implemented in Octave. Replaced with `any(regexp())`.
* In the online link, I manually entered an `a` very close to the 153-length superpermutation. This allows for the solution to be verified.
> 2 votes

# Answer
## CJam (6 * 240 = 1440)

```
5e!72>

```

Online demo, validation (outputs the index at which each permutation of `0..4` can be found; it needs to flatten the output because the original program gives suitable output to stdout but what it places on the stack is not directly usable).

Approach stolen from Sanchises, although the permutation order of CJam is different, giving a different substring.

---

## CJam (22 * 207 = 4554)

```
0a4{)W@+W+1$)ew\a*W-}/

```

Online demo, validation.

### Dissection

This uses a simple recursive construction.

```
0a       e# Start with a superpermutation of one element, [0]
4{       e# for x = 0 to 3:
  )      e#   increment it: n = x+1
  W@+W+  e#   wrap the smaller superpermutation in [-1 ... -1]
  1$)ew  e#   split into chunks of length n+1
  \a*    e#   insert an n between each chunk
  W-     e#   remove the -1s from the ends
}/

```
> 2 votes

# Answer
# Japt -P, 2376 (11 x 216)

```
4o ¬á Ë+4+D

```

Try it!

-1 byte thanks to @ Shaggy!

Port of Anders Kaseorg's Pyth answer.
> 1 votes

# Answer
# Charcoal, 29 bytes, output length 153, score 4437

```
”)⊞⧴�r3⁼Ｈ⁴↓¦σ✳ＬïpＷＳ [Ｔ↑ZωÞ”‖Ｏ

```

Try it online! Link is to verbose version of code. Explanation: Like @TFeld, I just print half of a superpermutation and mirror it. I calculated the superpermutation using the following code:

```
Push(u, w);
for (u) {
    Assign(Plus(Plus(i, Length(i)), i), h);
    Assign(Ternary(i, Join(Split(w, i), h), h), w);
    Assign(Incremented(Length(i)), z);
    if (Less(z, 5)) for (z) Push(u, Slice(h, k, Plus(k, z));
}
Print(w);

```

This translates to a 45-byte program in Charcoal so would have scored 6885.
> 1 votes

# Answer
# MATL, 16 x 442 = 7072

```
4Y25:Y@!)K442&:)

```

Try it online!

MATL port of my Octave answer. -442 thanks to Luis Mendo
> 1 votes

# Answer
# Perl 6, 7191 (153\*47 bytes)

```
say first *.comb(permutations(5).all.join),0..*

```

Try it online!

Finds the first number that contains all permutations of the digits 0 to 4. This will take a *long* time to execute, but you can test it with the first two permutations `0` and `0,1`
> 0 votes

# Answer
# Wolfram Language (Mathematica), 153\*95 bytes, 14535

```
Nest[Flatten[Join[#,{Max@#+1},#]&/@Partition[#,Max@#+1,1]]//.{b__,a__,a__,c__}:>{b,a,c}&,{0},4]

```

Try it online!
> 0 votes

---
Tags: code-challenge, sequence, permutations
---


title: Prime or highest factor

text:
# Question
Title: Prime or highest factor
# Challenge:

Given an array of non-negative whole numbers numbers ~~in the range of `0 to Infinity`~~, Check whether all of them are primes or not. (You can take input as a string too if you want)

# Input:

Input: An array of numbers

Output: The array with every element replaced by one of these:

```
-1                 -----> If 0, 1
1                  -----> If it is a prime number greater than 1
the highest factor -----> If that number is not prime

```

Return either -1 (0, 1), 1 (for primes \>= 2) or the highest factor of given number (for non-primes)

# Examples:

```
[1, 2, 3, 4, 10, 11, 13]                        ---> [-1, 1, 1, 2, 5, 1, 1]
[100, 200, 231321, 12312, 0, 111381209, 123123] ---> [50, 100, 77107, 6156, -1, 1, 41041]

```

# Note:

Input will always be valid, i.e it will consist only of numbers and decimals are not tested for. The array can be empty, if so, return the empty array.

# Restriction:

This is so shortest code in bytes for each language wins.

# LeaderBoard :

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
# Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
# Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
# Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the leaderboard snippet:

```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

```
var QUESTION_ID=163882,OVERRIDE_USER=8478;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
# Jelly,  ~~7~~ 6 bytes

```
ÆḌṪ€o-

```

A monadic link accepting a list of non-negative integers and returing a list of integers greater than or equal to -1.

**Try it online!**

### How?

Note that:

* All primes have a single proper divisor (one)
* All composites have multiple proper divisors (one plus the others)
* No number has itself as a *proper* divisor
* Jelly's get-proper-divisors atom, `ÆḌ`, yields a list of proper divisors in ascending order
* Zero and one have no proper divisors (they are neither prime, nor composite)
* Applying Jelly's tail atom, , to an empty list yields zero
* No number has a proper divisor of zero (let alone being the maximal one)
* All non-zero numbers are truthy in Jelly, while zero is falsey

```
ÆḌṪ€o- | Link: list of integers   e.g. [ 0, 1,  2,  5,     10,    5183]
ÆḌ     | proper divisors (vectorises)  [[],[],[1],[1],[1,2,5],[1,71,73]]
  Ṫ€   | tail €ach                     [ 0, 0,  1,  1,      5,      73]
     - | literal minus one
    o  | logical OR (vectorises)       [-1,-1,  1,  1,      5,      73]

```
> 9 votes

# Answer
# Jelly, ~~9~~ 8 bytes

*Saved 1 byte thanks to @Dennis*

```
:ÆfṂ€$~~

```

Try it online! or run all test cases

### Commented

We take advantage of the fact that both `nan` and `inf` become `0` in Jelly when a bitwise NOT is applied to them.

```
:ÆfṂ€$~~ - main link, taking the input list
 ÆfṂ€$   - treat these two links as a monad:
 Æf      -   get the lists of prime factors (0 --> 0; 1 --> empty list; prime --> itself)
    €    -   for each list,
   Ṃ     -   isolate the minimum prime factor (turns empty lists into 0)
:        - divide each entry by its minimum prime factor (0/0 --> nan; 1/0 --> inf)
      ~~ - bitwise NOT x2 (nan or inf --> 0 --> -1; other entries are unchanged)

```
> 8 votes

# Answer
# R, ~~68~~ 62 bytes

```
Map(function(n,v=rev(which(!n%%1:n)))"if"(n<2,-1,v[2]),scan())

```

A solution using only base R, no libraries! Thanks to Giuseppe for golfing away 6 bytes.

Uses `scan` to read in a space separated list of numbers, `%%` to identify which are factors. `v` then contains a vector of all factors in ascending order (including 1 and n). This has the nice property that when we `rev`erse `v`, the number we want will be in the second place, avoiding an expensive call to `length` or `tail`(if `n` was prime, `v` contains `n 1`, else it contains `n (factors in descending order) 1`).

Example output (TIO link here):

```
> Map(function(n,v=rev(which(!n%%1:n)))"if"(n<2,-1,v[2]),scan())
1: 0 1 2 3 4 5 6 7 8 9
11:
Read 10 items
[[1]]
[1] -1

[[2]]
[1] -1

[[3]]
[1] 1

[[4]]
[1] 1

[[5]]
[1] 2

[[6]]
[1] 1

[[7]]
[1] 3

[[8]]
[1] 1

[[9]]
[1] 4

[[10]]
[1] 3

```

If you think a list is not an acceptable return type, then swap out `Map` for `sapply` and add 3 bytes.
> 7 votes

# Answer
# 05AB1E, ~~11~~ ~~9~~ 8 bytes

```
Ñε¨àDd<+

```

-3 bytes thanks to *@Emigna*, changing `©d1-®+` to `Dd<+` and `€¨€à` to `ε¨à`.

Only my second 05AB1E answer, ~~so can definitely be golfed~~.

Try it online.

**Explanation:**

```
Ñ           # Divisors of each item in the input-list (including itself)
            #  [1,2,10,3] → [[1],[1,2],[1,2,5,10],[1,2,3]]
 ε          # For each:
  ¨         #  Remove last item (so it's now excluding itself)
            #   [[1],[1,2],[1,2,5,10],[1,2,3]] → [[],[1],[1,2,5],[1,2]]
   à        #  And get the max
            #   [[],[1],[1,2,5],[1,2]] → ['',1,5,2]
    D       # Duplicate the list
     d      # Is it a number (1 if it's a number, 0 otherwise)
            #  ['',1,5,2] → [0,1,1,1]
      <     # Subtract 1
            #  [0,1,1,1] → [-1,0,0,0]
       +    # Add both lists together
            #  ['',1,5,2] and [-1,0,0,0] → ['-1',1,5,2]

```
> 6 votes

# Answer
# , 21 bytes

```
_1:`(%{.@q:)@.(>&1)"0

```

Try it online!

## Explanation:

`(>&1)"0` is each number greater than 1?

`@.` if not, return `_1:`

`(%{.@q:)` if its 2 or greater, divide `%` the number by the first `{.`of the prime factors `q:`
> 5 votes

# Answer
# Japt, 6 bytes

After golfing, ended up being almost identical to, and just as short as, Jonathan's solution.

```
®â¬ÌªJ

```

Try it

---

## Explanation

```
®          :Map
 â¬        :  Proper divisors
   Ì       :  Get last element (returns null if the array is empty)
    ª      :  Logical OR
     J     :  -1

```
> 4 votes

# Answer
# Java 8, ~~105~~ ~~103~~ 87 bytes

```
a->{for(int i=a.length,n,x;i-->0;a[i]=n<2?-1:n/x)for(n=a[i],x=1;++x<n;)if(n%x<1)break;}

```

Modifies the input-array instead of returning a new one to save bytes.

Try it online.

**Explanation:**

```
a->{                  // Method with integer-array parameter and no return-type
  for(int i=a.length,n,x;i-->0;
                      //  Loop backward over the array
      a[i]=           //    After every iteration: change the current item to:
           n<2?       //     If the current item is 0 or 1:
            -1        //      Change it to -1
           :          //     Else:
            n/x)      //      Change it to `n` divided by `x`
     for(n=a[i],      //   Set `n` to the current item
         x=1;++x<n;)  //   Inner loop `x` in range [2,`n`)
       if(n%x<1)      //    If `n` is divisible by `x`:
         break;}      //     Stop the inner loop (`x` is now the smallest prime-factor)
                      //   (if the loop finishes without hitting the `break`,
                      //    it means `n` is a prime, and `x` and `n` will be the same)

```
> 3 votes

# Answer
# Python 3, 62 bytes

```
lambda l:[max([k for k in range(1,n)if n%k<1]+[-1])for n in l]

```

Try it online!

For `0` and `1` `range(1,n)` is empty, therefore the code evaluates to `max([]+[-1]) = -1`. For prime numbers, the only divisor in the \[1, n) is `1`, which is the desired output.

---

# Coconut, 50 bytes

```
map$(n->max([k for k in range(1,n)if n%k<1]+[-1]))

```

Try it online!
> 3 votes

# Answer
## Haskell, ~~52~~ 49 bytes

```
map(\x->last$[d|d<-[1..x-1],mod x d<1]++[-1|x<2])

```

Try it online!

```
map                     -- for each element in the input array
  \x->                  -- apply the lambda function
    last                -- pick the last element of the following list
     [d|d<-[1..x-1]     --  all d from 1 to x-1
           ,mod x d<1]  --    where d divides x
     ++[-1|x<2]         --  followed by -1 if x<2

```
> 3 votes

# Answer
# Husk, 8 bytes

```
m(|_1→hḊ

```

Try it online!

### Explanation

```
m(|_1→hḊ  Implicit Input         [1,2,3,4,10]
m(        Map each element
       Ḋ    List of divisors     [[1],[1,2],[1,3],[1,2,4],[1,2,5,10]]
     →h     Penultimate element  [0,1,1,2,5]
  |_1       If falsy then -1     [-1,1,1,2,5]

```
> 3 votes

# Answer
# Attache, 23 bytes

```
@{Max&-1!Divisors@_@-2}

```

Try it online!

29 bytes, pointfree: `@(Max&-1@Last@ProperDivisors)`

24 bytes, also pointfree: `@(Max&-1@`@&-2@Divisors)`

This simply gets the second-to-last divisor of `n` then takes the max of it and `-1`. The second-to-last element in an array with less than two elements is `nil`, and `Max[-1, nil]` is `-1`. `@` simply vectorizes this function, making it apply to each atom.
> 3 votes

# Answer
# Brachylog, 10 bytes

```
{fkt|∧_1}ˢ

```

Try it online!

The following explanation is mostly phrased imperatively for the sake of brevity, and does not accurately reflect Brachylog's declarative nature.

```
{          Start of inline predicate.
           Implicit input to the predicate.
 f         Create a list of all of the input's factors (including itself).
  k        Remove the last item of this list so that it no longer contains the original number.
   t       Take the last item of the list with the last item removed.
           Implicitly unify the output with the aforementioned last item.
    |      If that failed, because one of the lists was empty...
     ∧     discarding the input, (there's probably some obvious reason ∨ won't work here but I don't know what it is)
      _1   unify the output with -1 instead.
        }  End of the inline predicate.
         ˢ For every item of the input, unify it with the predicate's input and get a list of the corresponding outputs.

```

I decided I'd learn Brachylog so I could have some fun with code golf while hoping to learn some of the behavior of actual Prolog through osmosis, and I'm really enjoying it so far, even if I'm not entirely sure how the execution control characters work.
> 3 votes

# Answer
# Wolfram Language (Mathematica), 33 bytes

```
Divisors[#][[-2]]/._Part:>-1&/@#&

```

Try it online!
> 2 votes

# Answer
# \+ `numbers`, ~~88~~ 79 bytes

Thanks to the comments for some advice mainly about how to make submissions.

```
function(y)sapply(y,function(x)"if"(x<2,-1,prod(numbers::primeFactors(x)[-1])))

```

Uses the product of all prime factors except the smallest one, and the fact that the product of elements of an empty vector is defined to be `1`.

Try it online!
> 2 votes

# Answer
# JavaScript (Node.js), ~~61~~55 bytes

-6 bytes thanks to @shaggy

```
_=>_.map(_=>eval('for(v=_/(d=_>>1);v!=~~v;v=_/--d);d'))

```

Try it online!

---

# Explanation :

```
_ =>                                     // input i.e : the original array
    _.map(                               // map over all elements of the array
        eval('                           // eval a string
            for(v=_/(d=_>>1);            // set v = _ / _ >> 1 and set that to d
                v!=~~v;                  // and keep going until v !== floor(v)
                        v=_/d--);        // to _ / d again (d was changed)
                    d'                   // return d
            ))                           // end eval and map and function

```

**This is still for old code haven't updated this.**

# ES5 friendly as well:

```
 const primeOrNot = function(input) { // the function with argument input
      return input.map(function(value) { // returns the array after mapping over them
           d = Math.floor(value * 0.5); // multiply each element by 0.5 and floor it
           for(let v = value / d; v != Math.floor(v);) { // for loop goes until v!=~~v
                d --; // subtract one from d
                v = value / d; // set v again to value / d
           }
           return d; // return d
      })
 };

```
> 1 votes

# Answer
# Stax, ~~14~~ 13 bytes

```
ü±p╞Ö*«òτ♀╣â▀

```

Run and debug it

Explanation (unpacked):

```
m|fc%c{vsH1?}U? Full program, implicit input-parsing
m               Map
 |fc%c            Get factorisation and length of it (0 and 1 yield [])
      {     } ?   If length != 0:
       v            Decrement
           ?        If still != 0:
        sH            Last element of factorisation
           ?        Else:
          1           Push 1
              ?   Else:
             U      Push -1

```

Pseudocode inside map:

```
f = factorisation(i)
l = length(f)
if l:
    if --l:
        return f[-1]
    else:
        return 1
else:
    return -1

```
> 1 votes

# Answer
# Pari/GP, 37 bytes

```
a->[if(x<2,-1,x/divisors(x)[2])|x<-a]

```

Try it online!
> 1 votes

# Answer
# Japt, ~~14~~ ~~11~~ 8 bytes

```
®/k v)ªÉ
®        // For each input number,
 /k v    // return the number divided by it's first prime factor,
     )ªÉ // or -1 if such a number doesn't exist (the previous result is NaN).

```

Try it online!

Shaved off those three pesky bytes thanks to Shaggy.
> 1 votes

# Answer
# , 14 bytes

```
1(%0{q:,-)@>.]

```

Try it online!

For every number n take the maximum of (n,1) instead.
Append the negated number to the list of its prime factors (empty list for 1), and divide the number by the first item in the list.

### Also 14 bytes

```
(%0{q:) ::_1"0

```

Try it online!

Divide every number by the first of its prime factors. 0 raises a domain error with `q:`, and we look for the 0th item in an empty list for 1 — that’s an error as well. For any number that errors, return −1.
> 1 votes

# Answer
# Pyth, 12 bytes

```
me+_1f!%dTSt

```

Try it here

### Explanation

```
me+_1f!%dTSt
m            Q    For each number d in the (implicit) input...
          Std     ... get the range [1, ..., d - 1]...
     f!%dT        ... take the ones that are factors of d...
  +_1             ... prepend -1...
 e                ... and take the last.

```
> 1 votes

# Answer
# Bash \+ GNU utilities, 49

* 9 bytes saved thanks to @Cowsquack

```
factor|sed '/:$/c-1
/: \w+$/c1
s%: %/%
y/ /#/'|bc

```

### Explanation

* `factor` reads input numbers from STDIN, one per line and outputs in the format `<input number>: <space-separated list of prime factors (ascending)>`
* `sed` processes this as follows:
    + `/:$/c-1` The input numbers 0 and 1 have no prime factors and are replaced with `-1`
    + `/: \w+$/c1` Numbers with one prime factor (themselves) are prime. Replace these with `1`
    + `s%: %/%` Replace `:` with `/`. This builds an arithmetic expression to divide the (non-prime) input number by its smallest prime factor to give the largest factor
    + `y/ /#/` Remove the list of other (unneeded) factors (by commenting out)
* `bc` Arithmetically evaluate and display

Try it online!
> 1 votes

# Answer
# Python 2, ~~61~~ 59 bytes

```
lambda x:[max(k for k in[-1]+range(1,n)if n%k<1)for n in x]

```

Try it online!

---

**Improvements**
> 1 votes

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

```
x=>x.map(a=>(f=t=>a%--t<1?t:f(t))(a))

```

Try it online!

Recursive, stack overflow for large input

# JavaScript (Node.js), 41 bytes

```
x=>x.map(a=>eval('for(t=a;a%--t!=0;);t'))

```

Try it online!
> 1 votes

# Answer
# Racket, 105 bytes

```
(λ(L)(map(λ(n)(if(< n 2)-1(p n(- n 1))))L))(define(p n d)(if(= d 1)1(if(=(modulo n d)0)d(p n(- d 1)))))

```

Try it online!
> 1 votes

# Answer
# Befunge-98 (FBBI), 39 bytes

```
j&:!+f0p1-1:::' -:!j;3k$.nbj;-\%!!j:1+a

```

Try it online!

Ends with the `&` when there are no more numbers. This causes the program to stall for 60 seconds until TIO ends the program. This is unavoidable for Befunge-98, at least on TIO because both interpreters do this. After hitting play, you can stop the program after a bit in order to see what would be output if you did wait the minute.

---

Essentially, for every new number, if it is 0, it turns it into a 1. Then it puts a -1 onto the stack followed by a number that starts from 1 and counts up until it reaches the input number, in which case it prints out the second number on the stack (-1 for an input of 0 or 1, and the highest factor for others). Every time through the loop, we add the value of the iterator to the stack behind it if (`input % iterator == 0`). This means that when we get to the input, we just have to throw away the iterator and print. Then, we clear the stack with `n` and return to the read input function.

I may expand of the explanation later, we'll see...
> 1 votes

# Answer
# Retina 0.8.2, 33 bytes

```
%(`^0|^1$
-1
\d+
$*
^(1+)\1+$
$.1

```

Try it online! Link includes those test cases that aren't too slow. Explanation:

```
%(`

```

Loop over each input number.

```
^0|^1$
-1

```

Special-case 0 and 1.

```
\d+
$*

```

Convert to unary (doesn't affect -1).

```
^(1+)\1+$
$.1

```

Replace each number with its largest proper factor in decimal.
> 0 votes

# Answer
# tinylisp, 75 bytes

```
(load library
(q((L)(map(q((N)(i(l N 2)(- 1)(/ N(min(prime-factors N))))))L

```

Try it online! (Contains 4 extra bytes to give the anonymous function a name so we can call it in the footer.)

### Ungolfed/explanation

Observe that returning 1 for prime \\$n\\$ and the largest factor less than \\$n\\$ for composite \\$n\\$ can be combined into returning \\$n/p\\$ where \\$p\\$ is the smallest prime factor of \\$n\\$.

```
(load library)               Library gives us map, -, /, min, and prime-factors functions

(lambda (L)                  Anonymous function, takes a list of numbers L
 (map                         Map
  (lambda (N)                  Anonymous function, takes a number N
   (if (less? N 2)              If N < 2
    (- 1)                        -1; else
    (/ N                         N divided by
     (min                        the minimum
      (prime-factors N)))))      of the prime factors of N
  L)))                        ... to L

```
> 0 votes

---
Tags: code-golf, math, primes
---


title: How fast can I say your program?

text:
# Question
Title: How fast can I say your program?
I recently decided to download some dictation software, in order to help with my writing. However, it doesn't work very well when I'm coding, since I have to change from saying words to symbols and back again. It's even worse when I'm coding in an esoteric language which is *all* symbols.

In order to make my use of the dictation program more consistent, I decided to switch it over to character mode, where I just say the name of each character instead. Problem solved! Though this does delay my novel's release date a little bit...

So, assuming that the longer the name of a character, the longer it takes to say, how long will it take me to spell out some of my programs/sentences?

## Specifications

Given a string consisting of only printable ASCII, return the sum of each character's unicode name. For example, `/` is called `SOLIDUS` with 7 characters, and `A` is `LATIN CAPITAL LETTER A` with 22 characters.

But remember, I have to say your programs out loud to execute them, so their score will be based on how long it takes me to say them, i.e. as the sum of the lengths of each character's unicode name.

## Test Cases:

In format `input => output` with no trailing/leading spaces in input.

```
A      => 22
/      => 7
Once upon a time...           => 304
slurp.uninames>>.comb.sum.say => 530
JoKing => 124
!" #$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~        =>  1591
Double-check your \s on the last test case ;)   => 755
<say "<$_>~~.EVAL">~~.EVAL     => 388
,[.,]  => 58
19     => 19

```

### Rules:

* Input to your program will only consist of printable ASCII characters, that is, the codepoints 32 (space) to 126 (tilde).
    + For convenience sake, here is the list of lengths of the characters you have to handle: `[5,16,14,11,11,12,9,10,16,17,8,9,5,12,9,7,10,9,9,11,10,10,9,11,11,10,5,9,14,11,17,13,13,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,19,15,20,17,8,12,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,18,13,19,5]`
* Here is a reference program you can use to score your program.
    + Peter Taylor has pointed out that the reference program normalises some unicode characters. It should still work for most solutions, but feel free to correct it if you need
* Since you're saying what the characters actually look like, your solution will be scored by the *characters* that are displayed, not the bytes involved. This is directed at languages with custom encodings.
    + You can assume that I've memorised the entire Unicode library and can say whatever strange characters you use.
* Sorry Rogem, but answers have to be composed of displayable characters. Unprintables are fine, I just have to be able to read the characters out loud.
* Whatever you do, do not use  in your program.

# Answer
> 13 votes
# Java 8, score ~~846~~ ~~838~~ ~~822~~ 816

```
ௐ->ௐ.map(ˇ->Character.getName(ˇ).length()).sum()

```

-8 score thanks to *@tsh* replacing the `_1` with .
-22 score thanks to *@ASCII-only* replacing the  with `ˇ` and `$` with .

Try it online.

**Explanation:**

The  and `ˇ` are used instead of the `s` and `c` I would normally use, because lowercase letters are all 20 (i.e. `LATIN SMALL LETTER S`), but  (`TAMIL OM`) is 8 and `ˇ` (`CARON`) is 5.

```
ௐ->                         // Method with IntStream parameter and integer return-type
  ௐ.map(ˇ->                 //  Map each character to:
      Character.getName(ˇ)  //   Get the name of the character
               .length())   //   Get the length of that name
   .sum()                   //  And after the map: sum all lengths together,
                            //  and return it as result

```

# Answer
> 11 votes
# Perl 6, score 337

```
+*.uninames.&[~].ords

```

Try it online!

# Answer
> 7 votes
# Japt v2.0a1 `-x`, Score ~~926~~ ~~908~~ ~~875~~ ~~865~~ ~~829~~ ~~791~~ 789

Takes input as an array of characters.

```
®cg`061742//0.450./..//.2/5117385`c+51 r\A_p26}  n#

```

Try it or run all test cases on TIO

(`APOSTROPHE` is omitted from the 6th test case on TIO as Japt can't handle both single and double quotes in the same input string)

---

## Explanation

```
®cg`...`c+51 r\A_p26}  n#      :Implicit input of character array
®                              :Map
 c                             :  Character code
  g                            :  Index into (0-based, with wrapping)
   `...`                       :    The string described below
        c+51                   :    Increment the codepoint of each by 51 (="8cKidj55gebbc9agh895c97a99baa9bba59ebhddMjfkh")
                               :    (Space closes the above method)
             r                 :    Replace
              \A               :      RegEx /[A-Z]/g
                _              :      Pass each match through a function
                 p26           :        Repeat 26 times
                    }          :      End function
                               :    (Space closes the replace method)
                               :  (Space closes the indexing method)
                       n       :  Convert to integer
                        #      :    From base 32 (note the trailing space)
                               :Implicitly reduce by addition and output

```

---

## Building The String

(Scores include the steps and extra characters needed to reverse each modification)

1. The array gave a baseline score of 2161.
2. Converting each to a single character in a base `>=23` and joining to a string scored 1832.
3. Replacing both runs of `m` and `k` with a single, uppercase character scored 963.
4. There were still too many expensive letters so next I tried to get rid of them by reducing the codepoints of all characters. `5` was the character with the lowest codepoint (`53`) so I started with 52, which scored 756
5. After trying all numbers that would leave *no* letters in the string, `51` gave the best score of 738
6. Finally, replacing the quotation marks with slightly cheaper backticks gave a score of 734. Backticks in Japt are usually used to enclose and decompress a compressed string but, luckily, none of the characters in this string are contained in Shoco's library

The final string, so, contains the characters at the following codepoints:

```
[5,48,24,54,49,55,2,2,52,50,47,47,48,6,46,52,53,5,6,2,48,6,4,46,6,6,47,46,46,6,47,47,46,2,6,50,47,53,49,49,26,55,51,56,53]

```

# Answer
> 4 votes
# 05AB1E, score 963

```
Îv•Fδà‚<0?9½mΣ@×ƶC₁vc-™uΔ_ε'•21вεD3‹i22α₂и}}˜yÇ32-è+

```

Try it online or verify all test cases.

**Explanation:**

```
Î               # Push 0 and the input-string
 v              # Loop `y` over the characters of this input-string:
  •Fδà‚<0?9½mΣ@×ƶC₁vc-™uΔ_ε'•
               '#  Push compressed integer 87235805968599116032550323044578484972930006625267106917841
   21в          #  Converted to Base-21 as list: [5,16,14,11,11,12,9,10,16,17,8,9,5,12,9,7,10,9,9,11,10,10,9,11,11,10,5,9,14,11,17,13,13,0,19,15,20,17,8,12,2,18,13,19,5]
    ε           #  Map over this list:
     D3‹i       #   If the value is smaller than 3:
         22α    #    Take the absolute difference of this value with 22
            ₂и  #    Repeat it 26 times as list
    }}          #  Close the if-statement and map
      ˜         #  Flatten the list
       yÇ       #  Get the unicode value of the current character
         32-    #  Subtract 32
            è   #  Index it into the list of integers
             +  #  And add it to the sum
                # (and output the sum implicitly as result after the loop)

```

See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*) to understand why `•Fδà‚<0?9½mΣ@×ƶC₁vc-™uΔ_ε'•21в` is `[5,16,14,11,11,12,9,10,16,17,8,9,5,12,9,7,10,9,9,11,10,10,9,11,11,10,5,9,14,11,17,13,13,0,19,15,20,17,8,12,2,18,13,19,5]`.

# Answer
> 4 votes
# R; Score: 3330 1586 1443

Also challenging in R due to lack of built-ins.

Well the code is now mostly @Giuseppe's but that's alright. I was able to make a small edit to golf further by replacing the * with the ~, and the s with the dot.

Thanks to @Nick Kennedy for getting this down to 1443 by using arcane magic "a UTF8 encoded version of the number sequence"

```
function(.)sum((c(+",752230178/0,30.1002110221,052844",61~26,+":6;8/3",59~26,+"94:,")-39)[+.-31]);`+`=utf8ToInt;`~`=rep

```

Try it online

# Answer
> 4 votes
## C# (Visual C# Interactive Compiler) (score 1627 1116 1096 1037 1019 902)

```
Ω=>Ω.Sum(ˇ=>(31&-ˇ)>5&ˇ>62?22-ˇ/91*2:"♁♌♊♇♇♈♅♆♌♍♄♅♁♈♅♃♆♅♅♇♆♆♅♇♇♆♁♅♊♇♍♉♉♏♋♐♍♄♈♎♉♏♁"[ˇ-6-ˇ/33*26]-9788)

```

This uses no built-in database: just some special-casing for letters and a lookup table.

Online test suite.

It can't score itself, because most of the characters are not in range, including the variables `CARON` and `OHM SIGN` and the zodiac symbols used to encode the lookup table.

Thanks to ASCII-only for many suggestions.

# Answer
> 3 votes
# Python 3, Score of 993

```
lambda _:len(''.join(map(__import__('unicodedata').name,_)))

```

Try it online!

Below 1000 now, any tips still appreciated.

-16 thanks to Kirill L.

# Answer
> 2 votes
# Perl 5 `-pl`, score 723

```
s,\N{OX}*.,_charnames'viacode ord$&,ge,$_=y,,,c

```

Try it online!

### Explanation

```
s,        ,                        ,ge  # Replace globally
  \N{OX}*   # zero or more OX characters , loads the
            # _charnames module as side effect,
         .  # any character
           _charnames'viacode ord$&  # with its Unicode character name
                                     # (using old package delimiter).
                                      ,$_=y,,,c  # Set $_ to its length

```

# Answer
> 2 votes
# Attache, 1934

```
Sum@{ToBase[FromBase[Ords@"!ZByru=#9fBYb$a3Si0^pU,ZP#3$cd'(c-_lhu]h(]5;!W|?M4:<_^sU;N&XFN`t:u"-32,95],23][Ords@_-32]}

```

Try it online!

Simple compression and indexing.

# Answer
> 1 votes
# C# (Visual C# Interactive Compiler), Score: ~~4007~~ ~~3988~~ ~~3759~~ ~~3551~~ 2551

```
ˇ=>ˇ.Sum(_=>new[]{5,16,14,11,11,12,9,10,16,17,8,9,5,12,9,7,10,9,9,11,10,10,9,11,11,10,5,9,14,11,17,13,13,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,19,15,20,17,8,12,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,18,13,19,5}[_-32])

```

I feel crushed by Peter Taylor's solution up above. Thanks to Peter Taylor for pointing out a simple lookup table was better than my previous dictionary solution.

Try it online!

---
Tags: code-challenge, unicode
---


# Question
Title: Python code to produce C++14 hex integer literal with ticks
> tl;dr? See bottom for **The Competition**

## Integer literals

While programming, the 64-bit hexadecimal literal `0x123456789abcdefL` is difficult to gauge the size of. I find myself mentally grouping digits from the right by fours to see that it's 15 digits' worth.

Python PEP 515 allows you to express the above literal, inside code, as `0x123_4567_89ab_cdefL`. If you prefer binary, then it's even more invaluable: `0b1_0010_0011_0100_0101_0110_0111_1000_1001_1010_1011_1100_1101_1110_1111L`

## String representations

Python can also convert an integer into strings with spacing characters, as follows:

```
'{:#_b}'.format(81985529216486895L)
'{:#_x}'.format(81985529216486895L)
'{:,}'.format(81985529216486895L)

```

The first two produce what's shown above (although without the `L` suffix), while the last will produce

```
"81,985,529,216,486,895"

```

> Although with PEP 515, they would be better expressed as:
>
> ```
> '{:#_b}'.format(81_985_529_216_486_895L)
> '{:#_x}'.format(81_985_529_216_486_895L)
> '{:,}'.format(81_985_529_216_486_895L)
>
> ```

Note, though, the following:

* `'_'` is only legal for binary and hexadecimal strings - and Python will insert them every four characters (from the right);
* `','` is only legal for decimal strings - and Python will insert them every three characters (from the right);
* No other separator characters are allowed.

---

## Enough with the Python syntax lesson; on to C++!

C++14 also allows separators inside an integer literal to allow grouping, much like the above. Only (of course) it's a different character: the tick (single quote `'`). So the above literals would be:

```
0b1'0010'0011'0100'0101'0110'0111'1000'1001'1010'1011'1100'1101'1110'1111uL
0x123'4567'89ab'cdefuL
81'985'529'216'486'895uL

```

Python is often used to machine-generate C/C++ code, because it's so easy to do! But there's no native Python way to generate these new 'tick'-based identifiers - `.format()` can only use `_`. So, here's some code that I wrote to do it:

```
# Hex function with tick marks
def HexTicks(num) :
  # Convert to hex (without leading 0x - yet)
  s = '{:x}'.format(num)
  # Insert tick marks
  for i in range(len(s)-4, 0, -4) :
    s = s[:i] + "'" + s[i:]
  # Return the result
  return "0x" + s + "uLL"

```

## The Competition

> Sorry @ASCII-only !

Write a Python 2.7.3 expression or lambda, smaller than the above function (not including whitespace or comments), that:

1. Takes any non-negative integer;
2. Produces the correct hexadecimal string for that integer;
3. With a leading `0x` and trailing `uLL`;
4. No leading zeroes as part of the hex number;
5. With tick marks (`'`) every four digits, counting backwards from the right;
6. No tick mark straight after the `0x`.

### ILLEGAL

```
0x0uLL       # If integer was anything other than zero (2.)
12'3456      # No 0x or uLL (3.)
0x0'1234uLL  # Leading zero (4.)
0x12'345uLL  # Not grouped by four (5.)
0x'1234uLL   # Tick mark before hex number (6.)

```

### Bonuses

A. Can be easily modified to produce capital hex letters - but not the `0x` or `uLL` parts;

> Note that `.format()` allows `'{:_X}'` to capitalise the hex characters - but `'{:#_X}'` will capitalise the `0X` too

B. An extra `digits` parameter that **will** add leading zeros to that number of digits (not resultant characters; just hex digits) - unless it's already got that many.

> For example: `HexTick(0x1234,6)` would produce `"0x00'1234uLL"`

# Answer
> 2 votes
# Python 2, ~~68~~ 65 bytes

-3 bytes for both thanks to tsh

```
lambda n:"0x"+re.sub("(?!^)(?=(....)+u)","'","%xuLL"%n)
import re

```

Try it online!

### Eligible for both bonuses, ~~76~~ 73 bytes

```
lambda x,d:"0x"+re.sub("(?!^)(?=(....)+u)","'","%%0%dxuLL"%d%x)
import re

```

Try it online!

---
Tags: code-golf, python, hexadecimal
---


title: Exploding Numbers

text:
# Question
Title: Exploding Numbers
<sup>sandbox (deleted) </sup>

Lets define a matrix of 9s as: $$ N = \begin{bmatrix} 9&9&9\\9&9&9\\9&9&9 \end{bmatrix} $$

Lets define an exploding number as a number at position \\$(x,y)\\$ that can be decomposed into equal integers between all its adjacent neighbors (including itself) and the absolute value of each portion is greater than 0.

From the previous matrix, lets explode the number at position \\$(1,1)\\$ (0 indexed) $$ N = \begin{bmatrix} 9&9&9\\9&\color{red}9&9\\9&9&9 \end{bmatrix} $$ $$ N = \begin{bmatrix} 9+\color{red}1&9+\color{red}1&9+\color{red}1\\9+\color{red}1&\color{blue}0+\color{red}1&9+\color{red}1\\9+\color{red}1&9+\color{red}1&9+\color{red}1 \end{bmatrix} $$

$$ N = \begin{bmatrix} 10&10&10\\10&\color{red}1&10\\10&10&10 \end{bmatrix} $$

Sometimes, decomposing result into a rational number greater than 1. This is something we need to avoid when exploding numbers. In this cases the remainder will be assigned to the exploded number.

To demonstrate it, lets continue working with our previous matrix. This time we will explode the number at position \\$(0,0)\\$

$$ N = \begin{bmatrix} \color{red}{10}&10&10\\10&1&10\\10&10&10 \end{bmatrix} $$

Here we have 3 neightbors and the number itself. Here the equation is something like \\$10/4\\$ which give us **2** for each and **2** as remainder.

$$ N = \begin{bmatrix} \color{blue}2+\color{red}{2}&\color{red}{10+2}&10\\\color{red}{10+2}&\color{red}{1+2}&10\\10&10&10 \end{bmatrix} $$

$$ N = \begin{bmatrix} \color{red}{4}&12&10\\12&3&10\\10&10&10 \end{bmatrix} $$

As well, sometimes a number wont be big enough to be decomposed in equal parts (where the abs is greater than 0) between his neighbors (|rational number| \< 1). In this cases we need to *"borrow"* from the exploded number in order to maintain the *"greater than 0"* condition. Lets continue with our previous example and explode the number at position \\$(1,1)\\$.

$$ N = \begin{bmatrix} 4&12&10\\12&\color{red}3&10\\10&10&10 \end{bmatrix} $$

$$ N = \begin{bmatrix} 4+\color{red}1&12+\color{red}1&10+\color{red}1\\12+\color{red}1&\color{blue}0+\color{red}{1}-\color{green}6&10+\color{red}1\\10+\color{red}1&10+\color{red}1&10+\color{red}1 \end{bmatrix} $$ $$ N = \begin{bmatrix} 5&13&11\\13&\color{red}{-5}&11\\11&11&11 \end{bmatrix} $$

---

**The challenge** is, given a list of \\$(x,y)\\$ positions and an finite non-empty array of natural numbers, return the exploded form after each number from the positions list has been exploded.

---

**Test cases**

Input: `initial matrix: [[3, 3, 3], [3, 3, 3], [3, 3, 3]], numbers: [[0,0],[0,1],[0,2]]`

Output: `[[1, 0, 1], [5, 6, 5], [3, 3, 3]]`

---

Input: `Initial matrix: [[9, 8, 7], [8, 9, 7], [8, 7, 9]], numbers: [[0,0],[1,1],[2,2]]`

Output: `[[4, 11, 8],[11, 5, 10],[9, 10, 4]]`

---

Input: `Initial matrix: [[0, 0], [0, 0]], numbers: [[0,0],[0,0],[0,0]]`

Output: `[[-9, 3],[3, 3]]`

---

Input: `Initial Matrix: [[10, 20, 30],[30, 20, 10],[40, 50, 60]], numbers: [[0,2],[2,0],[1,1],[1,0]]`

Output: `[[21, 38, 13], [9, 12, 21], [21, 71, 64]]`

---

Input: `Initial Matrix: [[1]], numbers: [[0,0]]`

Output: `[[1]]`

---

Input: `Initial Matrix: [[1, 2, 3]], numbers: [[0,0], [0, 1]]`

Output: `[[1, 1, 4]]`

---

**Notes**

* Input/Output rules apply
* You can assume input matrix will never be empty
* You can assume coordinates are always going to be valid
* Input coord in test cases is given as (row, column). If you need it to be (x, y) you can swap the values. If so, please state that in your answer

# Answer
# C(GCC) ~~220~~ ~~216~~ ~~214~~ 212 bytes

credit to @ceilingcat for 2 bytes

```
#define L(v)for(int v=2;~v--;)
#define P l/C+r<0|l/C+r>=R|l%C+c<0|l%C+c>=C
f(int R,int C,int*m){for(int*i=m+R*C;~*i;) {int*M,l=*i+++C**i++,a=0,b;L(r)L(c)P?:++a;M=m+l;b=*M/a;b+=!b;*M- =b*a;L(r)L(c)M[r*C+c]+=P?0:b;}}

```

Run it here

a slightly less golfed version

```
#define L(v)for(int v=2;~v--;)
#define P l/C+r<0|l/C+r>=R|l%C+c<0|l%C+c>=C
f(int R, int C, int*m) {
    for(int*i=m+R*C;~*i;) {
        int*M,l=*i+++C**i++,a=0,b;
        L(r)
            L(c)
                P?:++a;
        M=m+l;
        b=*M/a;
        b+=!b;
        *M-=b*a;
        L(r)
            L(c)
                M[r*C+c]+=P?0:b;
    }
}

```

The calling code with an example

```
int main()
{
  int matrix[] = {3,3,3,3,3,3,3,3,3,0,0,0,1,0,2,-1};
  int rows = 3;
  int columns = 3;
  f(rows,columns,matrix);
  for(int r = 0; r < rows; ++r) {
    for(int c = 0; c < columns; ++c) {
      printf("%03d,",matrix[r*columns + c]);
    }
    printf("\n");
  }
}

```

and the output

```
001,005,003,
000,006,003,
001,005,003,

```
> 9 votes

# Answer
# JavaScript (ES7),  ~~126 125 123~~  121 bytes

*Saved 2 bytes thanks to @Shaggy*

Takes input as `(matrix)(list)`. Outputs by modifying the matrix.

```
m=>a=>a.map(([Y,X])=>(g=n=>m[m.map((r,y)=>r.map((_,x)=>(x-X)**2+(y-Y)**2<3&&r[n++,x]++)),(m[Y][X]+=~n)<n||g``,Y][X]++)``)

```

Try it online!

### How?

If we were to strictly follow the algorithm described in the challenge, we'd have to perform the following operations for each position pair \\$(x,y)\\$:

1. walk through the matrix to compute the number of neighbors \\$n\\$
2. compute \\$\lfloor m(x,y) / n\rfloor\\$ and deduce the quantity \\$q\\$ that needs to be added to each neighbor
3. walk through the matrix again to update each neighbor
4. update \\$m(x,y)\\$

Instead of that, we use a recursive function which executes a simpler flow of operations, repeated as many times as needed:

1. for each neighbor and for the reference cell itself: increment the cell and increment a counter \\$n\\$ (initialized to \\$0\\$)
2. subtract \\$n+1\\$ from the reference cell
3. if the above result is greater than or equal to \\$n\\$, do a recursive call
4. increment the reference cell (all steps of this kind are executed *in succession* when the last recursive call has completed)

The main benefit is that we only need one loop over the matrix. The second benefit is that we don't have to compute any quotient at all.

### Example

$$M=\begin{pmatrix} 0&0&0\\ 0&26&0\\ 0&0&0 \end{pmatrix}\text{ and }(x,y)=(1,1)$$

After **step 1** of the **first iteration**, we have:

$$M=\begin{pmatrix} 1&1&1\\ 1&27&1\\ 1&1&1 \end{pmatrix}\text{ and }n=9$$

And after **step 2** of the **first iteration**:

$$M=\begin{pmatrix} 1&1&1\\ 1&17&1\\ 1&1&1 \end{pmatrix}$$

The key point here is that the reference cell is updated by taking only the cost (\\$-9\\$) into account without the gain (\\$+1\\$), so that we know how much we can still draw from it.

Consequently, the sum of the cells is no longer equal to \\$26\\$ at this point. But this will be corrected at the end of the process, where all gains on the reference cell are accounted at once.

**Step 3** of the **first iteration**: because \\$17\\$ is greater than \\$9\\$, we do a recursive call.

After **step 1** of the **second iteration**, we have:

$$M=\begin{pmatrix} 2&2&2\\ 2&18&2\\ 2&2&2 \end{pmatrix}\text{ and }n=9$$

And after **step 2** of the **second iteration**:

$$M=\begin{pmatrix} 2&2&2\\ 2&8&2\\ 2&2&2 \end{pmatrix}$$

**Step 3** of the **second iteration**: this time, we have \\$8\<9\\$, so we stop there.

We now increment the reference cell twice (**step 4** of **both iterations**), leading to the final result:

$$M=\begin{pmatrix} 2&2&2\\ 2&10&2\\ 2&2&2 \end{pmatrix}$$

### Commented

```
m => a =>                     // m[] = input matrix, a[] = list of positions
  a.map(([Y, X]) => (         // for each pair (X, Y) in a[]:
    g = n =>                  //   g = recursive function expecting n = 0
      m[                      //
        m.map((r, y) =>       //     for each row r[] at position y in m[]:
          r.map((_, x) =>     //       for each value at position x in r[]:
            (x - X) ** 2 +    //         if the quadrance between (x, y)
            (y - Y) ** 2 < 3  //         and (X, Y) is less than 3:
            && r[n++, x]++    //           increment n and increment r[x]
          )                   //       end
        ),                    //     end
        (m[Y][X] += ~n)       //     subtract n + 1 from m[Y][X]
        < n                   //     if the result is greater than or equal to n:
        || g``,               //       do a recursive call
        Y                     //
      ][X]++                  //     increment m[Y][X]
    )``                       //   initial call to g
  )                           // end

```
> 7 votes

# Answer
# , ~~163~~ ~~162~~ ~~161~~ ~~159~~ ~~155~~ 146 bytes

```
function(m,l){for(e in l){v=m[i<-e[1],j<-e[2]];s=m[x<--1:(i<dim(m))+i,y<--1:(j<ncol(m))+j];z=sum(1|s);d=max(1,v%/%z);m[x,y]=s+d;m[i,j]=v+d-d*z};m}

```

Try it online!

### Explanation

(Corresponds to a previous version of the code)

```
function(m,l) {          # Take input as matrix m and 1-indexed list of explosion points l
  for(e in l) {          # Loop over the list of explosion points
    i=e[1]; j=e[2]       # Assign current coordinates to (i,j) for brevity
    x=-1:1+i             # Assign the ranges of neighboring cells: (i-1) to (i+1),
    y=-1:1+j             # and (j-1) to (j+1)
    s=                   # Take the submatrix s=m[x,y]
      m[x<-x[x<=dim(m)]  # But first trim x and y from above to prevent out of bounds errors,
     ,y<-y[y<=ncol(m)]]  # trimming from below isn't necessary, as R tolerates index 0
    z=sum(1|s)           # Count the neighbors
    d=max(1,m[i,j]%/%z)  # Estimate, how much we'll distribute to each neighbor
    m[x,y]=s+d           # Add the distributed amount to each cell of the submatrix
    m[i,j]=m[i,j]-d*z    # Subtract the total amount from the exploded cell
  }
  m                      # Return the modified matrix
}

```
> 6 votes

# Answer
# Clean, ~~181~~ 167 bytes

```
import StdEnv;

```

#

```
foldl\m(x,y)={{if(d>2)0b+e-if(d>0)0b*n\\e<-:l&v<-[0..],let{b=max m.[y,x]n/n;$a b=2+sign a-(a+1)/size b;n= $x l* $y m;d=(v-x)^2+(u-y)^2}}\\l<-:m&u<-[0..]}

```

Try it online!

In the form of a partially-applied function literal.

Expanded (first version):

```
f // functinon f on {{Int}} and [(Int,Int)]
    = foldl \m (x, y) // fold :: (a -> b -> a) a [b] -> a with first argument \ {{Int}} (Int,Int) -> {{Int}} giving \ {{Int}} [(Int,Int)] -> {{Int}}
        = {                     // an array of
            {                   // arrays of
                if(d > 2) 0 b   // the amount we give to the neighbors
                + e             // plus the current entry
                - if(d > 0) 0 b // minus the amount taken from the target entry
                * n             // times the number of neighbors, if we're on the target
            \\                  // for each
                e <-: l         // element of row l
                & v <- [0..]    // and x-index v
                , let           // local definitions:
                    b           // the amount given to the neighbors
                        = max   // we need at least 1 each, so take the largest of
                            m.[y, x] // the target entry
                            n   // or the number of neighbors
                        / n     // divide it by the number of neighbors
                    n           // the number of neighbors
                        = (     // sum of
                            1   // one
                            + s x // if x is at the left edge = 0 else 1
                            + s ( // if x is at the right edge = 0 else 1
                                size l
                                - x
                                - 1
                            )
                        ) * (   // times the sum of
                            1   // one
                            + s y // if y is at the top edge = 0 else 1
                            + s ( // if y is at the bottom edge = 0 else 1
                                size m
                                - y
                                - 1
                            )
                        )
                    d           // distance from the target point
                        = (v - x)^2
                        + (u - y)^2
            }
        \\                      // for each
            l <-: m             // row l in matrix m
            & u <- [0..]        // and y-index u
        }

```
> 4 votes

# Answer
# Rust - 295 bytes

```
fn explode(p:(i8,i8),v:&mut Vec<Vec<i8>>){let x=v[p.0 as usize][p.1 as usize];let q=|x,y|x*x+y*y;loop{let mut t=0;for i in 0..v.len(){for j in 0..v[i].len(){if q(i as i8-p.0,j as i8-p.1)<3{v[i][j]+=1;v[p.0 as usize][p.1 as usize]-=1;t+=1;}}}if v[p.0 as usize][p.1 as usize]<=(x/t+x%t){break;}}}

```

This is pretty long due to Rust requiring unsigned integer indexing of vectors, but requiring signed integers to do subtraction resulting in negatives. However I believe my algorithm is the "shortest algorithm" so far. There is actually no need to deal with detecting edges, bottom, etc.

Notice three things: One, the sum of all cells is always constant. Two, this is a division / remainder situation, so we can apply Bresenham-algorithm style thinking. Three, the question always adds the same number to all cells within a certain distance of the special position cell, before dealing with the "extra" stuff in the special position.

Algorithm:

Store original value of cell at position P into M.

Begin Loop:

Iterate over each cell I in the matrix. If the position of cell I is within 3 Quadrance (squared distance) of the position P, then subtract 1 from cell P and add 1 to the cell I. Count how many times this is done in one iteration through the matrix.

If the value leftover in the cell at position P is less than or equal to M / Count + M modulo Count, then break the loop. Otherwise perform the loop again.

The resulting matrix will be the exploded version. Count is basically a way to count neighbors without dealing with edges. Looping is a way to break down the division/addition stuff into a repeated single addition/subtraction of one. The modulo check ensures we will have appropriate remainder left at position P to deal with 'explosions' that are not evenly divisible amongst neighbors. The do/while loop structure allows P\<0 to work properly.

Ungolfed version on the Rust Playground
> 4 votes

# Answer
# Java 10, ~~194~~ ~~193~~ ~~191~~ ~~190~~ ~~184~~ ~~182~~ 171 bytes

```
M->C->{for(var q:C){int n,X=q[0],Y=q[1],x,y,c=0;do{c++;x=n=0;for(var r:M){y=0;for(int $:r)r[y]+=Math.hypot(x-X,y++-Y)<2?++n/n:0;x++;}}while((M[X][Y]+=~n)>=n);M[X][Y]+=c;}}

```

Iterative port of *@Arnauld*'s JavaScript answer.
-17 bytes thanks to *@Arnauld*.

Modifies the input-matrix instead of returning a new one to save bytes.

Try it online.

**Explanation:**

```
M->C->{                      // Method with two integer-matrix parameters and no return-type
  for(var q:C){              //  Loop over the coordinates:
    int n,                   //   Count integer
        X=q[0],Y=q[1],       //   The current X,Y coordinate
        x,y,                 //   Temp x,y coordinates
        c=0;                 //   Counter, starting at 0
    do{                      //   Do-while:
      c++;                   //    Increase the counter `c` by 1
      x=n=0;                 //    (Re)set both `x` and the count `n` to 0
      for(var r:M)           //    Loop over the rows `r`:
        y=0;                 //     (Re)set `y` to 0
        for(int $:r)         //     Loop over the cells of the current row:
          r[y]+=             //      Increase the value at x,y by:
            Math.hypot(      //       If the hypot (builtin for `sqrt(a*a, b*b)`) of:
              x-X,           //        the difference between `x` and `X`,
                  y++-Y)     //        and difference between `y` and `Y`
                             //        (and increase `y` by 1 afterwards with `y++`)
              <2?            //       Is smaller than 2:
                 ++n/n       //        Increase count `n` and the value at x,y both by 1
                :            //       Else:
                 0;          //        Leave the value at x,y the same by increasing by 0
       x++;}}                //     Increase `x` by 1
    while((M[X][Y]+=~n)      //    Decrease the value at X,Y by n+1
          >=n);              //    Continue the do-while if this new value is still larger
                             //    than or equal to count `n`
    M[X][Y]+=c;}}            //   Increase the value at X,Y with counter `c`

```
> 3 votes

# Answer
# Common Lisp, 498 bytes

```
(defmacro s(l c x)`(incf(aref m,l,c),x))
(defmacro w(a &rest f)`(if(,a(or(= l 0)(= l(d 0)))(or(= c 0)(= c(d 1)))),@f))
(defmacro d(n)`(1-(array-dimension m,n)))
(defmacro p(i l m &rest f)`(loop for,i from(1-,l)to(1+,l)when(and(>=,i 0)(<=,i,m))do,@f))
(defmacro g()`(or(p i l(d 0)(p j c(d 1)(s i j 1)))(s l c(- v))))
(defun f(m l c)(let((v(w and 4(w or 6 9))))(if (<(/(s l c 0)v)1)(g)(loop for i to(1-(/(s l c 0)v))do(g)))))
(defun c(m n)(dotimes(i(length n))(f m(nth 0(nth i n))(nth 1(nth i n))))m)

```

Try it online!

Use this function as `(print (c #2A((3 3 3) (3 3 3) (3 3 3)) '((0 0)(0 1)(0 2))))`

Better readable version:

```
(defmacro s (l c x)
  `(incf (aref m ,l ,c) ,x))

(defmacro w (a &rest f)
  `(if (,a (or (= l 0)
           (= l (d 0)))
       (or (= c 0)
           (= c (d 1))))
       ,@f))

(defmacro d (n)
  `(1- (array-dimension m ,n)))

(defmacro p (i l m &rest f)
  `(loop for ,i from (1- ,l) to (1+ ,l)
     when (and (>= ,i 0) (<= ,i ,m))
     do ,@f))

(defmacro g ()
  `(or(p i l (d 0)
     (p j c (d 1)
        (s i j 1)))
      (s l c (- v))))

(defun f (m l c)
  (let ((v (w and 4 (w or 6 9))))
    (if (< (/ (s l c 0) v) 1)
    (g)
      (loop for i to (1- (/ (s l c 0) v))
        do (g)))))

(defun c (m n)
  (dotimes (i (length n))
    (f m (nth 0 (nth i n))
       (nth 1 (nth i n))))
  m)

```

Output example:

```
(print (c #2A((3 3 3) (3 3 3) (3 3 3) (3 3 3) (3 3 3) (3 3 3)) '((5 0)(4 1)(0 2))))
;; #2A((3 4 0) (3 4 4) (3 3 3) (4 4 4) (5 -4 4) (1 5 4))

(print (c #2A((3 3 3) (3 3 3) (3 3 3)) '((0 0)(0 1)(0 2))))
; #2A((1 0 1) (5 6 5) (3 3 3))  => #2A((1 0 1) (5 6 5) (3 3 3))

(print (c #2A((9 8 7) (8 9 7) (8 7 9)) '((0 0)(1 1)(2 2))))
;; #2A((4 11 8) (11 5 10) (9 10 4))  => #2A((4 11 8) (11 5 10) (9 10 4))

(print (c #2A((0 0) (0 0)) '((0 0)(0 0)(0 0))))
;; #2A((-9 3) (3 3))  => #2A((-9 3) (3 3))

(print (c #2A((10 20 30)(30 20 10)(40 50 60)) '((0 2)(2 0)(1 1)(1 0))))
;; #2A((21 38 13) (9 12 21) (21 71 64))  => #2A((21 38 13) (9 12 21) (21 71 64))

```
> 2 votes

# Answer
# Python 2, 171 bytes

```
M,p=input()
l=len
for i,j in p:
 y=[(i+y,j+x)for x in-1,0,1for y in-1,0,1if l(M)>j+x>-1<i+y<l(M[0])];x=max(M[i][j]/l(y),1);M[i][j]-=x*l(y)
 for i,j in y:M[i][j]+=x
print M

```

Try it online!
> 2 votes

---
Tags: code-golf, matrix
---


title: What have we got?

text:
# Question
Title: What have we got?
# Inspired by, and in memory of, our beloved genius,

# R.I.P.

He invented and implemented dfns — his magnum opus and the subject of the challenge.

For the interested: latest full dfns documentation and videos with John.

## Task

Given an ASCII source code, answer in which of the following four categories it belongs:

1. Dyadic dop
2. Monadic dop
3. Dfn
4. Other

You may return any four consistent values, but please state your mapping if it isn't obvious.

### Details

You may assume that the source code always begins with an opening curly brace `{` and ends with a closing curly brace `}`.

Recursively nested braces can occur (e.g. `{{{}}}`), but categories 1–3 can never have brace nesting depth go below 1 (so `{}{}` is "Other") and all braces must be balanced (so `{{}` is "Other").

Characters in the following contexts on a line are ignored:

1. To the right of `#` (a comment): `significant#ignored`
2. Enclosed in single quotes `'``'` (i.e. in a string): `significant'ignored'significant` (This applies to `#` too: `'#'significant`)
3. To the right of an unpaired quote `'` (pairing quotes from the left): `significant'ignored`

In curly brace level one (i.e. excluding nested braces):

* Dyadic dops contain the uninterrupted phrase `ww`
* Monadic dops do not contain `ww`, but do contain `aa`
* Dfns contain neither `ww` nor `aa`

## Test cases

### Dyadic dops

```
{ww}

```

```
{
    www
}

```

```
{
''ww'
}

```

```
{aa

ww}

```

```
{'#''#'ww?aa}

```

### Monadic dops

```
{aa}

```

```
{aaaa}

```

```
{aa{ww}'ww'}

```

```
{w#w'
aa'
}

```

```
{aaw*w}

```

```
{w'\'aa\''}

```

### Dfns

```
{}

```

```
{a a}

```

```
{aA}

```

```
{
{aa}
}

```

```
{w
w''w#
w}

```

```
{{
}}

```

```
{w\'aa\'}

```

### Other

```
{}{}

```

```
{{}

```

```
{}}

```

```
{ww}}

```

```
{}
{}

```

```
{ww}{}

```

```
{#}

```

```
{'
'}

```

# Answer
> 9 votes
# JavaScript (ES6),  ~~145 ... 138~~  136 bytes

Returns \\$0\\$ for *dyadic dops*, \\$1\\$ for *monadic dops*, \\$2\\$ for *dfns* and \\$3\\$ for *other*.

```
s=>[...s].map(c=>s=(n=`
aw}{#'`.indexOf(c))?n>5?i^=2:i?0:n>4?i=1:n>3?d++:n>2?x+=!d--:(o|=n<0|d|s!=c?0:n,c):i=0,o=i=0,x=d=-1)|x|~d?3:2>>o

```

Try it online!

## Alternate versions

* **131 bytes** by taking an array of characters as input
* **132 bytes** by using *Buffer()* (Node.js)

## How?

The input string is parsed character by character.

### Translation of characters into codes

Each character \\$c\\$ is translated into a code \\$n\\$ according to the following table:

```
 character | code | triggered operation
-----------+------+---------------------------------------------------------
    \n     |   0  | i = 0
     a     |   1* | o |= n < 0 | d | s != c ? 0 : n
     w     |   2* | o |= n < 0 | d | s != c ? 0 : n
     }     |   3* | x += !d--
     {     |   4* | d++
     #     |   5* | i = 1
     '     |   6  | i ^= 2
   other   |  -1* | same as 'a' or 'w', but always fails because of 'n < 0'

```

Codes marked with a '\\$\*\\$' have no effect when \\$i\neq 0\\$.

### Variables describing the parser state

The following variables are used during the parsing:

* \\$o\\$: a bitmask keeping track of encountered phrases

+ bit 0: a valid phrase `aa` has been encountered
    + bit 1: a valid phrase `ww` has been encountered
* \\$i\\$: a bitmask telling whether some characters should be ignored

+ bit 0: we're currently located inside a comment
    + bit 1: we're currently located inside a string (this bit is still updated within a comment, but this is harmless)
* \\$s\\$: the result of the previous iteration
* \\$d\\$: the current depth of nested braces (starting at \\$-1\\$)
* \\$x\\$: the number of times we went from depth \\$0\\$ to depth \\$-1\\$, minus \\$1\\$

### Final result

We output \\$3\\$ if \\$x\\$ is not equal to \\$0\\$ or \\$d\\$ is not equal to \\$-1\\$. Otherwise, we output \\$0\\$, \\$1\\$ or \\$2\\$ according to the value held in \\$o\\$.

# Answer
> 6 votes
# Jelly,  ~~50 48 46~~  45 bytes

```
Ỵµṣ”'m2Kṣ”#Ḣ)KµċⱮƤØ{IF©<-oµ⁾waż¤ẇ€‘Ḅ«5×®¬Ḅ⁼1¤

```

A monadic Link accepting a list of characters which yields:

```
5 - Dyadic dop
4 - Monadic dop
3 - Dfn
0 - Other

```

**Try it online!** Or see a test-suite.
uses Python quoting to avoid the possibility of evaluating input as a Python set or dictionary

### How?

```
Ỵµṣ”'m2Kṣ”#Ḣ)KµċⱮƤØ{IF©<-oµ⁾waż¤ẇ€‘Ḅ«5×®¬Ḅ⁼1¤ - Link: list of characters
                                              - breaking long Link up...
Ỵµṣ”'m2Kṣ”#Ḣ)K      - Replace any strings or comments with (single) spaces
Ỵ                   - split at newline characters
 µ          )       - monadic chain for each:
  ṣ”'               -   split at apostrophe characters
     m2             -   modulo 2 slice (i.e. every other part starting with the first
                    -   - that is, non-string code. Will remove strings from within comments)
       K            -   join with spaces
        ṣ”#         -   split at octothorp characters
           Ḣ        -   head (i.e. non-comment code)
             K      - join with spaces

µċⱮƤØ{IF©<-oµ       - Replace characters of code at depth > 1 with the integer 1
µ           µ       - monadic chain, call previous result A:
    Ø{              -   literal ['{','}']
   Ƥ                -   for prefixes of A:
  Ɱ                 -     map across right argument with:
 ċ                  -       count
      I             -   deltas (i.e. [count('}') - count('{')] for each prefix)
       F            -   flatten (i.e. count('}') - count('{') for each prefix)
                    -   -- i.e -1*depth of each character of A; closing braces at depth+1
        ©           -   (copy this list of depths to the register for later use)
         <-         -   less than -1? (vectorises)
           o        -   logical OR with A (vectorises, replacing deep code with 1s)

⁾waż¤ẇ€‘Ḅ«5×®¬Ḅ⁼1¤ - Categorise the result, R
    ¤              - nilad followed by link(s) as a nilad:
⁾wa                -   literal ['w', 'a']
   ż               -   zip with itself = [['w','w'],['a','a']]
     ẇ€            - for €ach: is a sublist of R?  i.e. one of: [0,0] [1,0] [0,1] [1,1]
       ‘           - increment (vectorises)                     [1,1] [2,1] [1,2] [2,2]
        Ḅ          - unbinary                                     3     5     4     6
         «5        - minimum with five                            3     5     4     5
                 ¤ - nilad followed by link(s) as a nilad:
            ®      -   recall depths from the register
             ¬     -   logical NOT (vectorises) (0->1, other depths->0)
              Ḅ    -   unbinary
               ⁼1  -   equal one -- i.e. depths ends with a 0 and contains no other zero
           ×       - multiply

```

# Answer
> 3 votes
# Clean, ~~309~~ ~~293~~ 284 bytes

We can get away with only using 3 variable names at a time, so we'll call them `a`, `p`, and `l`.

```
import StdEnv,Text,Data.List
a=isInfixOf o zip2[2,2]
@ =['\'']
$p#p=join@[foldl((\[a:p]_|p>[]=a++[';':join@(tl p)]=split['#']a!!0)o split@)l l\\l<-mklines p]
#l=[(?a- ?l,p)\\a<-inits p&[p:l]<-tails p]
|{p\\(a,p)<-l|a<2}<>"{}"=0|a['ww']l=1|a['aa']l=2=3
?l=sum[1\\'{'<-l]-sum[1\\'}'<-l]

```

Try it online!

Defines the function `$ :: [Char] -> Int` and some helpers, giving the mapping:

* `0`: Other
* `1`: Dyadic dop
* `2`: Monadic dop
* `3`: Dfn

Expanded (first version), and with more than 3 variable names:

```
$ s
    # s // remove strings and comments
        = join [';'] [ // join the second argument with semicolons
            limit ( // take the first repeated element of
                iterate // an infinite list of applications of the first argument
                    (
                        (
                            \(p, q) = p ++ case q of // join the first half with a modified second half
                                ['\'\'': q] = [';': q] // replace two quotes with a semicolon
                                [c, _: q] = [c: q] // drop the character after a quote or hash
                                _ = [] // leave unmatched strings unchanged
                        ) o span // split the string on the first occurrence of
                            \c = c <> '\'' && c <> '#' // a quote or hash
                    ) l // applied to l
                )
            \\ l <- mklines s // for line l in s split at newlines
        ]
    # b // generate a map of nesting levels
        = [
            ( // the pair of
                ?i - ?t, // the nesting level
                c // the character c
            )
            \\ i <- inits s // for init i of s
            & // synchronously iterated with
                [c: t] <- tails s // character c at the start of tail [c:t] of s
        ]
    // determine what the code is
    | {c \\(n, c) <- b | n < 2} // if the string made of characters with nesting level of less than 2
        <> "{}" // is not the same as the paired braces at the beginning and end
        = 0 // return zero
    | m ['ww'] b // if there are two consecutive 'w's at nesting level 2
        = 1 // return 1
    | m ['aa'] b // if there are two consecutive 'a's at nesting level 2
        = 2 // return 2
    = 3 // otherwise return 3

```

# Answer
> 0 votes
# Retina 0.8.2, 91 bytes

```
m`'.*?('|$)|#.*
¶
s(+`(?!^)\{[^{}]*\}(?!$)
¶
^(?!\{[^{}]*\}$).+
3
^.+ww.+
2
^.+aa.+
1
..+
0

```

Try it online! Link includes test suite. Explanation:

```
m`'.*?('|$)|#.*
¶

```

Remove strings and comments.

```
s(+`(?!^)\{[^{}]*\}(?!$)
¶

```

Remove matched brackets, working out from the innermost, but leave the first and last brackets.

```
^(?!\{[^{}]*\}$).+
3

```

If we don't have matched brackets then this is Other.

```
^.+ww.+
2

```

Otherwise if we have `ww` then this is Dyadic Dop.

```
^.+aa.+
1

```

Otherwise if we have `aa` then this is Monadic Dop.

```
..+
0

```

Otherwise if this is anything not covered above then this is Dfn.

---
Tags: code-golf, parsing, classification, apl
---


title: Left Center Right (LCR) code golf

text:
# Question
Title: Left Center Right (LCR) code golf
At a party, I was introduced to the game LCR. Now it's not a great game as there's no skill but only random chance. But it got me thinking, I could code this, and I made a quick program in R to model the game.

Rules of the game modified from Wikipedia to match how we played:

> Each player receives at least 3 chips. Players take it in turn to roll three six-sided dice, each of which is marked with "L", "C", "R" on one side, and a single dot on the three remaining sides. For each "L" or "R" thrown, the player must pass one chip to the player to their left or right, respectively. A "C" indicates a chip to the center (pot). A dot has no effect.
>
> If a player has fewer than three chips left, they are still in the game but their number of chips is the number of dice they roll on their turn, rather than rolling all three. When a player has zero chips, they pass the dice on their turn, but may receive chips from others and take their next turn accordingly. The winner is the last player to put chips into the center.

Contest: write a program in your language of choice that takes input for the number of players and the number of starting chips and simulates a game of LCR, showing the state of the game after each player has rolled.

For example, a game might be output as:

```
[[[3,3,3,3],0],[[1,4,3,4],0],[[1,4,3,4],0],[[1,4,1,4],2],[[1,4,1,2],4],
[[0,4,1,3],4],[[0,3,2,3],4],[[0,3,0,3],6],[[0,3,1,1],7],[[0,3,1,1],7],
[[2,0,1,1],8],[[2,0,0,1],9],[[2,0,0,0],10],[[0,1,0,0],11],
[[1,0,0,0],11],[[1,0,0,0],11],[[1,0,0,0],11],[[0,0,0,0],12]]

```

ht: JonathanAllan

The output doesn't have to look exactly like this, but it should be easy to discern the dice roll, how many chips each player has, and how many chips the centre has for each turn.

It's code golf so the shortest code wins.

# Answer
> 4 votes
# Emacs Lisp, 279 bytes

```
(defmacro n(i)`(incf(nth ,i c)))
(defun f(p s)(g(let((a'(0)))(dotimes(i p)(push s a))(princ a))0 p))
(defun g(c v p)(dotimes(i(min(nth v c)3))(decf(nth v c))(case(random 6)(0(n(mod(1- v)p)))(1(n(mod(1+ v)p)))(2(n p))(t(n v))))(princ c)(or(eq(-sum c)(nth p c))(g c(mod(1+ v)p)p)))

```

Use this function as `(f 4 3)`.

Better readable version:

```
(defmacro n (i) `(incf (nth ,i c)))

(defun f(p s)
  (g
   (let ((a '(0)))
     (dotimes (i p)
       (push s a))
     (princ a))
   0
   p))

(defun g (c v p)
  (dotimes (i (min (nth v c) 3))
    (decf (nth v c))
    (case (random 6)
      (0 (n (mod (1- v) p)))
      (1 (n (mod (1+ v) p)))
      (2 (n p))
      (t (n v))))
    (princ c)
    (or (eq (-sum c) (nth p c))
    (g c (mod (1+ v) p) p)))

```

Output example:

```
(3 3 3 3 0)(1 4 3 4 0)(2 2 4 4 0)(2 2 2 5 1)(4 2 2 3 1)(2 2 2 4 2)(2 1 3 4 2)(2 2 0 4 4)(2 2 0 4 4)(1 2 0 4 5)(2 1 0 4 5)(2 1 0 4 5)(2 1 1 3 5)(0 1 1 3 7)(1 0 1 3 7)(1 0 1 3 7)(1 0 3 1 7)(1 0 3 1 7)(1 0 3 1 7)(1 1 2 1 7)(1 1 3 0 7)(0 1 3 0 8)(1 0 3 0 8)(1 1 1 1 8)(1 1 2 0 8)(0 1 2 1 8)(0 1 2 1 8)(0 1 1 1 9)(0 1 1 1 9)(0 1 1 1 9)(0 1 1 1 9)(0 1 1 1 9)(0 1 1 0 10)(0 1 1 0 10)(0 0 1 0 11)(0 0 1 0 11)(0 0 1 0 11)(0 0 1 0 11)(0 0 1 0 11)(0 0 0 0 12)

```

# Answer
> 3 votes
# Java 8, ~~281~~ ~~277~~ ~~275~~ ~~274~~ 253 bytes

**Version which outputs the same state when a turn player has 0 chips left:**

```
p->n->{java.util.Arrays A=null;int c[]=new int[p],i=0,t,r,s=1,u,f=9;for(A.fill(c,n);s>0;f=0,System.out.print(A.toString(c)))for(t=c[++i%p],t=t>3?3:t;t-->f;r*=Math.random(),c[i%p]-=1-r/3,s=c[u=(i+r-1+p)%p]+=1-r&1-r/4,c[u]=s<0?0:s,s=A.stream(c).sum())r=6;}

```

Starts with the third player in the array.

Try it online.

**Version which skips players with 0 chips left (274 bytes):**

```
p->n->{java.util.Arrays A=null;int c[]=new int[p],i=p,t,r,s=1,u,f=9;for(A.fill(c,n);s>0;f=0,System.out.print(A.toString(c))){for(t=c[i%p],t=t>3?3:t;t-->f;r*=Math.random(),c[i%p]-=1-r/3,s=c[u=(i+r-1+p)%p]+=1-r&1-r/4,c[u]=s<0?0:s)r=6;for(s=A.stream(c).sum();s>0&c[++i%p]<1;);}}

```

Starts at the first player in the array.

Try it online.

-7 bytes thanks to *@OlivierGrégoire*.

**Explanation (of the second version):**

```
p->n->{                      // Method with two integer parameters and no return-type
  java.util.Arrays A=null;   //  Create a static Arrays-object to save bytes
  int c[]=new int[p],        //  Integer-array with chips of each player (0 by default)
      i=p,                   //  Index integer, starting at the amount of players
      t,                     //  Temp integer to roll 3 dice
      r,                     //  Temp integer for the dice-result
      s=1,u,                 //  Temp integers (and `s` is also the total-sum integer)
      f=9;                   //  Flag integer, starting at a single digit above 3
  for(A.fill(c,n);           //  Give each player in the array the chips
      s>0                    //  Loop as long as the total-sum is not 0 yet
      ;                      //    After every iteration:
       f=0,                  //     Set the flag to 0
       System.out.print(A.toString(c))){
                             //     Print the current state
    for(t=c[i%p],            //   Set `t` to the current player's chips
        t=t>3?3:t;           //   If this is larger than 3: set it to 3 instead
        t-->f                //   Loop that many times (1, 2, or 3)
                             //   (the flag is used to skip this loop the first iteration,
                             //   so we can print the initial state)
        ;                    //     After every iteration:
         r*=Math.random(),   //      Roll the dice in the range [0,5]
         c[i%p]-=r<3?        //      If the dice-roll is 0, 1 or 2:
                  1          //       Remove a chip from this player
                 :0,         //      Else: Leave the chip-amount the same
         s=c[u=(i+r-1+p)%p]  //      If the dice-roll is 0, go to the player left
                             //      If the dice-roll is 2, go to the player right
             +=1-r&1-r/4,    //       And add a chip to this player
         c[u]=s<0?0:s)       //      Change negative amount of chips to 0
      r=6;                   //    Reset the dice-roll to 6 so we can roll again
    for(s=A.stream(c).sum(); //   Calculate the total sum of the chips of the players
        s>0&                 //   If this sum is larger than 0:
         c[++i%p]<1;);}}     //    Determine the next player in line with at least 1 chip

```

# Answer
> 2 votes
# Python 2, ~~159~~ 148 bytes

```
from random import*
n,c=input()
g=[c]*n;i=0
while sum(g):exec"r=randrange(6);g[i]-=1;g[i-[0,1,~-n][max(0,r-3)]]+=r>0;"*min(3,g[i]);i=(i+1)%n;print g

```

Try it online!

Prints all players chips after every roll

# Answer
> 2 votes
# Jelly, 39 bytes

<sup>+2 to fix repetition behaviour (`¡` must be preceded by a nilad so `«3Ḣ$` -\> `⁸FḢ«3`)
If we can define the output lists to be rotated to have the chips belonging to the player who acted previously at the left we can do away with the right-most 6 bytes for **33 bytes** (however, in my opinion, it is somewhat awkward to read that). </sup>

```
ẋµ’1¦‘.,2ŻX¤¦$¹Ø.X¤?⁸FḢ«3¤¡ṙ1µSÐ¿ṙ"JC$$

```

A dyadic Link accepting chips-per-player on the left and number-of-players on the right which yields a list of players chip counts as at the start of the game and after each turn (including turns where 0 chips forces a pass).

**Try it online!**

### How?

Each player in turn, up to three times, depending on their chip count, flips a coin. When a player flips heads they do nothing but if they flip tails they then roll a three sided die losing a chip to L, C or R. (Note that 0 flips when a player has 0 chips is equivalent to passing.)
This is repeated until the sum of the players chips is 0.
The implementation rotates the players left by one place each turn and then rotates the resulting states back to all be aligned as if they were not.

```
ẋµ’1¦‘.,2ŻX¤¦$¹Ø.X¤?⁸«3Ḣ¤¡ṙ1µSÐ¿ṙ"JC$$ - Link: chipsPerPlayer, C; numberOfPlayers, P
ẋ                                      - repeat C P times (making a list of P Cs)
                              Ð¿       - collect up results in a list while...
                             S         - ...Ð¿ condition: sum (while players have chips)
 µ                          µ          - ...Ð¿ do: the monadic chain:
                         ¡             -   repeat...
                        ¤              -   ...¡ number of times: nilad and link(s) as a nilad:
                    ⁸                  -     chain's left argument (the chip list)
                     «3                -     minimum with three (vectorises)
                       Ḣ               -     head -- i.e. min(left-most player's chips, 3)
                   ?                   -   ...¡ action: if...
                  ¤                    -     ...? clause: nilad and link(s) as a nilad:
               Ø.                      -       the list [0,1]
                 X                     -       random choice (0 is falsey while 1 is truthy)
             $                         -     ...? then: last two links as a monad:
    ¦                                  -       sparsely apply...
   1                                   -       ...¦ to indices: one (the left-most)
  ’                                    -       ...¦ action: decrement (player lost a chip)
            ¦                          -       sparsely apply...
           ¤                           -       ...¦ to indices: nilad and link(s) as a nilad:
      .,2                              -         literal pair of literals .5 and two = [.5,2]
         Ż                             -         prepend a zero = [0,0.5,2]
          X                            -         random choice
                                       -         -- Note application to index .5 is a no-op
                                       -                 index 0 is the right-most entry (L)
                                       -                 index 2 is the second entry (R)
                          ṙ1           -   rotate the list left by one for the next Ð¿ loop
                                     $ - last two links as a monad:
                                    $  -   last two links as a monad:
                                  J    -     range of length -- i.e. [1,2,3,...,turns+1]
                                   C   -     complement = 1-x        [0,-1,-2,...,-turns]
                                 "     -   zipped-appliction of:
                                ṙ      -     rotate left by
                                       -   -- i.e. rotate 1st left by 0, 2nd left by -1, ...)

```

# Answer
> 1 votes
# C#, 356?+13? Bytes

Requires `using System;` for a total of +13 bytes to the code shown below, if I'm required to count that. Otherwise just plonk it in any class and call `L(players, starting chips);`.

```
static int i,j,k,l;public static void L(int p,int s){var r=new Random();var x=new int[p];for(i=0;i<p;i++)x[i]=s;
for(i=0;i<s*p;){for(j=0;j<p;j++){for(l=0;l<x[j]&l<3;l++){k=r.Next(-1,5);if(k<2){if(k==0){x[j]--;i++;}else{x[(p+j+k)%p]++;x[j]--;}}}Console.Write(a(x)+i);}}}public static string a(int[] x){var n="|";for(l=0;l<x.Length;)n+=x[l++]+" ";
return n;}

```

Sample output for a 2,2 game:

```
|1 3 0|2 2 0|1 3 0|1 3 0|0 4 0|0 3 1|0 3 1|2 1 1|1 2 1|1 2 1|0 3 1|0 3 1|0 3 1|1 1 2|1 1 2|1 1 2|0 2 2|1 1 2|0 1 3|1 0 3|0 1 3|0 1 3|0 1 3|1 0 3|1 0 3|1 0 3|0 1 3|1 0 3|0 1 3|0 0 4

```

Less golfed version:

```
using System;
//class omitted.
static int i,j,k,l;
public static void LCR(int pl, int sc){
var r=new Random();
var state = new int[pl];
for(i=0;i<pl;i++)state[i]=sc;
for(i=0;i<sc*pl;){
    for(j=0;j<pl;j++){
        for(l=0;l<state[j] && l<3;l++){
            k=r.Next(-1,5);
            if(k<2){
                if(k==0){state[j]--;i++;}else{state[(pl+j+k)%pl]++;state[j]--;}
            }
        }
        Console.Write(a(state)+i);
    }
}
}
public static string a(int[] x){
    var n="|";
    for(l=0;l<x.Length;)n+=x[l++]+" ";
    return n;
}

```

# Answer
> 1 votes
# 05AB1E, ~~58~~ ~~50~~ ~~49~~ ~~52~~ 49 bytes

**Version which outputs the same state when a turn player has 0 chips left (~~50~~ ~~49~~ ~~52~~ 49 bytes):**

```
и[=ÐO_#¾è3‚Ws\F5ÝΩ©3‹iε¾¹%NQ-}®≠iε®<¾+¹%NQ+}}}}D0›*¼

```

Try it online.

**Version which skips players with 0 chips left (~~58~~ ~~57~~ ~~60~~ 57 bytes):**

```
и[=DO_#[D¾èDĀ#\¼}3‚Ws\F5ÝΩ©3‹iε¾¹%NQ-}®≠iε®<¾+¹%NQ+}}}}D0›*¼

```

Try it online.

The first input is the amount of players, second input the amount of chips per player.

**Explanation (of the second version):**

```
и                    # Create a list with a size of the (first) implicit input,
                     # filled with the second (implicit) input
[                    # Start an infinite loop:
 =                   #  Print the list with trailing newline, without popping the list
 DO_#                #  If the total amount of chips is 0: stop the infinite loop
 [                   #  Start an inner infinite loop:
  D¾è                #   Get the chips of the I'th player (I is 0 by default)
     D               #   Duplicate this
      Ā#             #   If it is NOT 0: stop the inner infinite loop
        \            #   Remove the duplicated chips for the next iteration
         ¼           #   And increase I by 1
 }                   #  After the inner infinite loop:
 3‚ß                 #  If the amount of chips is larger than 3: use 3 instead
    F                #  Loop that many times:
     5ÝΩ             #   Roll a random dice in the range [0,5]
     ©3‹i            #   If the dice-roll is 0, 1, or 2:
         ε¾¹%NQ-}    #    Remove a chip from the I'th player
         ®≠i         #    If the dice-roll is NOT 1:
            ε®<¾+    #     Go to the player left if 0; or right if 2
            ¹%NQ+}   #     And increase that player's chips by 1
    }}}              #  Close both if-statements and the loop
       Dd*           #  Make any negative amount of chips 0
          ¼          #  Increase I by 1

```

# Answer
> 1 votes
# C# (Visual C# Interactive Compiler), ~~201~~ 199 bytes

```
n=>m=>{var r=new Random();var j=Enumerable.Repeat(n,m).ToList();for(int i=0;j.Any(c=>c>0);i++,Print(j))for(int k=0,x=r.Next(6);k++<Math.Min(j[i%m],3);j[((x<1?-1:1)+i+m)%m]+=x<2?1:0,j[i%m]-=x<3?1:0);}

```

Try it online!

```
startingChips=>playerNum=>{
//Instantiate a new random number generator
var rng = new Random();
//Create a list of chips
var players = Enumerable.Repeat(startingChips, playerNum ).ToList();
//Loop as long any player still has chips
for(int turnNum = 0;players.Any(c=>c>0);
//And print the result every iteration
i++,Print(j))
//Get a random number within the range of 0-5 and loop for...
for(int k = 0,randomNum = rng.Next(6);
//either 3 or the amount of chips we have, whichever is smaller
k++<Math.Min(players[turnNum % playerNum ],3);
//Increment either the right player if the random number is 1, else increment the right player if it is 0
players[((randomNum<1?-1:1)+ turnNum + playerNum ) % playerNum ]+=x<2?1:0,
//Decrement current player if the die roll is under 3
players[ turnNum % playerNum ]-=x<3?1:0);}

```

# Answer
> 1 votes
# Charcoal, 61 bytes

```
≔⁰ηＷΣθ«≔Ｅθ⭆⌊⟦κ×³⁼λη⟧‽⁶ιＵＭθ⁻⁺⁺κ№§ι⊕λ3№§ι⊖λ5ＬΦ§ιλ›μ2≔﹪⊕ηＬθη⟦⪫θ,

```

Try it online! Link is to verbose version of code. Alternates between outputting the dice rolls and chips left (neither the initial number of chips nor the number of chips in the centre are included in the output). Explanation:

```
≔⁰η

```

Start with the first player.

```
ＷΣθ«

```

Repeat until nobody has any chips left.

```
≔Ｅθ⭆⌊⟦κ×³⁼λη⟧‽⁶ι

```

Roll up to three dice for the current player. These dice are labelled 0-5, where 0-2 represent the dot, 3 is pass to left, 4 is to centre, 5 is to right.

```
ＵＭθ⁻⁺⁺κ№§ι⊕λ3№§ι⊖λ5ＬΦ§ιλ›μ2

```

Add the number of chips the player on the right passed left and the number of chips the player on the left passed right, but subtract the number of chips the player themselves passed on.

```
≔﹪⊕ηＬθη

```

Advance to the next player.

```
⟦⪫θ,

```

Output the the new numbers of chips held by the players.

It's actually simpler for everyone to roll their dice simultaneously, which can be done in 50 bytes, including printing the dice rolls as well as the chips left:

```
ＷΣθ«≔Ｅθ⭆⌊⟦κ³⟧‽⁶ιＵＭθ⁻⁺⁺κ№§ι⊕λ3№§ι⊖λ5ＬΦ§ιλ›μ2⟦⪫ι,⪫θ,

```

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

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