title: D&D point buy cost

text:
# Question
Title: D&D point buy cost
When making a *Dungeons & Dragons* character, an alternative to rolling ability scores is to assign them within a power budget called point buy. Higher ability scores cost more points, especially towards the upper end: a score of 8 is free, and raising a score by 1 costs 1 point, except raising to 15 or 16 costs 2 points, and raising to 17 or 18 costs 3 points.

```
+-------+------+
| Score | Cost |
+-------+------+
|     8 |    0 |
|     9 |    1 |
|    10 |    2 |
|    11 |    3 |
|    12 |    4 |
|    13 |    5 |
|    14 |    6 |
|    15 |    8 |
|    16 |   10 |
|    17 |   13 |
|    18 |   16 |
+-------+------+

```

In list form:

```
[(8, 0), (9, 1), (10, 2), (11, 3), (12, 4), (13, 5), (14, 6), (15, 8), (16, 10), (17, 13), (18, 16)]

```

The point buy cost is summed for all six ability scores.

```
Ability scores: 16   17   8  13   8  12
Point buy cost: 10 + 13 + 0 + 5 + 0 + 4  = 32

```

Given six ability scores, each 8 through 18, output the total point buy cost. Fewest bytes wins.

```
    var QUESTION_ID=67472,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/67472/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>

**Leaderboard:**
```

# Answer
# JavaScript (ES7), ~~44~~ ~~42~~ 40 bytes

Crossed out 44 is still regular 44 :(

```
a=>a.map(s=>t+=s-9-~((s-14)**1.3),t=0)|t

```

*Thanks to @apsillers for saving 2 bytes!*

## Explanation

The interesting part is `-1-~((s-14)**1.3)`. `(s-14)**1.3` produces `1`, `2`, `4` and `6` for the values `15 - 18`. Any number that is less than `15` causes an error because the JavaScript implementation of exponential cannot operate on negative values with a fractional exponent. Basically, any value for `s < 15` causes it to return `NaN`, so the `-1-~` is there to cast it to a number (`0`).

```
a=>                       // a = input scores as an array of numbers
  a.map(s=>               // for each passed score
    t+=                   // add to the total
      s-9                 // point value = s - 8 (-1 used for next line)
      -~((s-14)**1.3),    // add extra points for scores 15 - 18
    t=0                   // t = total points (this happens BEFORE the map call)
  )
  |t                      // return the total points

```

### ES6 Solution (42 bytes)

```
a=>a.map(s=>t+=s-9-~[1,2,4,6][s-15],t=0)|t

```

## Test

This test uses `Math.pow` instead the exponential operator (`**`) so that it can run in any standard browser.

```
var solution = a=>a.map(s=>t+=s-9-~Math.pow(s-14,1.3),t=0)|t
```

```
Scores separated by spaces = <input type="text" id="input" value="16 17 8 13 8 12" />
<button onclick="result.textContent=solution(input.value.split(' '))">Go</button>
<pre id="result"></pre>
```
> 11 votes

# Answer
## CJam, 18 bytes

```
l~[8EG]ff-:~0fe>:+

```

or

```
l~[8EG]m*::m0fe>:+

```

Test it here.

### Explanation

The idea is decompose the point cost into three components:

```
 Score: 8  9 10 11 12 13 14 15 16 17 18
        0  1  2  3  4  5  6  7  8  9 10
        0  0  0  0  0  0  0  1  2  3  4
        0  0  0  0  0  0  0  0  0  1  2
       --------------------------------
 Cost:  0  1  2  3  4  5  6  8 10 13 16

```

All three components can be computed via a single subtraction and restricting the result to non-negative values.

```
l~    e# Read and evaluate input.
[8EG] e# Push [8 14 16].
ff-   e# For each pair from the two lists, subtract one from the other.
:~    e# Flatten the result.
0fe>  e# Clamp each difference to non-negative values.
:+    e# Sum them all up.

```
> 8 votes

# Answer
# Pyth, 14 bytes

```
s>#0-M*Q+14yB8

```

Test suite

This uses the same fundamental means of calculation as Martin Büttner, namely:

```
max(n-8, 0) + max(n-14, 0) + max(n-16, 0)

```

That being said, the means of calculation are very different. To generate the list of numbers to subtract, I use the expression `+14yB8`. `yB8` means "Bifurcate 8 on the function y". y doubles numbers, so this gives `[8, 16]`. Then, we add on 14, giving the list `[14, 8, 16]`.

Next, we take the Cartesian product with the input and subtract every pair of values.

Next, perform the maximization operation, we simply filter for positive values only, and sum the remainder.
> 8 votes

# Answer
# Samau, 19 bytes

Not sure if the question is posted after the last commit of my new language. They are both 2 hours ago. But all the features used here was added before that.

```
▐[8 14 16]`-o;0>*ΣΣ

```

Samau uses CP737 as its default character encoding.

```
▐[8 14 16]`-o;0>*ΣΣ
▐                      read a list of numbers
 [8 14 16]             push [8 14 16]
          `-           push the function [-]
            o          outer product
             ;         duplicate
              0>       for each element, test if it's larger than 0
                *      times
                 ΣΣ    take the sum twice because it's a 2d array

```
> 4 votes

# Answer
## PowerShell, 48 Bytes

```
$args|%{$t+=$_-8+@{15=1;16=2;17=4;18=10}[$_]};$t

```

(Pretty sure this isn't optimal.)

Takes input command-line arguments and pipes them into a loop `|%{...}`. Each iteration, we increment our total `$t+=` with the current number minus 8 `$_-8` plus the result of indexing into a hashtable for the more-expensive values `@{...}[$_]`. Then we simply output `$t` at the end.
> 0 votes

# Answer
# () Ox++, 248 bytes (62 characters)

```

```

Language I'm working on. Paste in the code here.
> 0 votes

---
Tags: code-golf, arithmetic
---


title: Card pair probability

text:
# Question
Title: Card pair probability
Given a deck consisting of **N** copies of cards with integer values \[**1**,**M**\] for a total of **N\*M** cards, compute the probability that a card with the value of **1** is adjacent to a card with the value of **2**.

Your solution may be exact or approximated, and it does not need to be the same for every run given the same inputs. The given answer should be within +/-5% of the true solution (barring really rare chances the RNG is not in your favor). Your program should give the answer in a reasonable amount of time (say, less than 10 minutes on whatever hardware you have). You may assume that **M** and **N** are reasonable small and error checking is not required.

The deck is *not* cyclical, so if the first card is a **1** and the last card is a **2**, this does not meet the adjacency requirements.

As a test case, for **N=4** and **M=13** (a standard 52-card deck) the expected solution is ~48.6%.

Here is an example un-golfed implementation in Python+NumPy using random shuffles:

```
from __future__ import division
from numpy import *

def adjacent(N, M):
    deck = array([i for i in range(1, M+1)]*N)
    trials = 100000
    count = 0
    for i in range(trials):
        random.shuffle(deck)
        ores = (deck == 1)
        tres = (deck == 2)
        if(any(logical_and(ores[1:], tres[:-1])) or
           any(logical_and(ores[:-1], tres[1:]))):
            count += 1
    return count/trials

```

The output may be in any form you find convenient (function return value, terminal output, file, etc.), and input may be in any form you find convenient (function parameter, terminal input, command line arg, etc.)

Standard loop-holes apply.

This is code golf, the shortest code (in bytes) wins.

# Leaderboard

```
var QUESTION_ID=67431,OVERRIDE_USER=31729;function answersUrl(e){return"http://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"http://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
> 2 votes
# MATL, 44 ~~46~~ bytes

This uses release 3.1.0 of the language, which is earlier than this challenge.

The computation is done with a loop that draws 1000 random realizations. It takes a couple of seconds to run. It could be done faster in a vectorized way. Input is of the form `[N M]`.

**Old version**: generates a random deck of cards and checks it twice: first in the forward and then in the backward direction.

```
itpw1)1e3:"2$twZ@w/Y]t1HhXfnwH1hXfn|bb]xxN$hYm

```

**New version**: generates a random deck of cards and then appends a flipped version of it with a `0` in between. That way checking can be done just once, in the forward direction. This saves two bytes.

```
itpw1)1e3:"2$twZ@w/Y]tP0whh1HhXfngbb]xxN$hYm

```

### Example

```
>> matl itpw1)1e3:"2$twZ@w/Y]tP0whh1HhXfngbb]xxN$hYm
> [4 13]
0.469

```

### Explanation

```
i                 % input: [N M]
tpw1)             % produce N*M and N
1e3:"             % repeat 1000 times
  2$twZ@w/Y]      % produce random deck of cards from 1 to N*M
  tP0whh          % append 0 and then flipped version of deck
  1Hh             % vector [1 2]
  Xf              % find one string/vector within another
  ng              % was it found at least once?
  bb              % bubble up element in stack, twice
]                 % end
xx                % delete top of the stack, twice
N$h               % vector with all elements in stack
Ym                % mean value

```

# Answer
> 2 votes
# Pyth, ~~23~~ 22 bytes

```
csm}1sM.:.S*vzUQ2J^T4J

```

Runs 10000 iterations. The number can be changed at no byte cost. Input is newline separated. Takes about 9 seconds on my computer.

Demonstration

```
csm}1sM.:.S*vzUQ2J^T4J
                 J^T4     J = 10000
  m              J        Do the following J times.
           *vzUQ          Set up the deck. (0 .. n-1, repeated m times.)
         .S               Shuffle the deck.
       .:       2         Find all 2 elment substrings.
     sM                   Add them up.
   }1                     Check if any pairs add to 1 ([0, 1] or [1, 0])
 s                        Add up the results (True = 1, False = 0)
c                     J   Divide by J.

```

# Answer
> 1 votes
# LabVIEW, 58 LabVIEW Primitives

creats card arrays then shuffles them. Search for 1s then check adjacent cards for 2s.

# Answer
> 1 votes
# MATL, ~~44~~ 38 bytes

This also uses MATL version 3.1.0, which is earlier than this challenge.

New version, thanks to Luis Mendo for saving 4 bytes!

```
iiXI*XJxO1e4XH:"JZ@I\TTo3X53$X+1=a+]H/

```

Old version (44 bytes):

```
OiitXIx*XJx1e4XH:"JJZrI\[1 1]3X5,3$X+1=a+]H/

```

Explanation

```
i               % take input for N
i               % take input for M
XI              % save M into clipboard I
*XJ             % multiply N and M and store in clipboard J
x               % clear the stack
O               % make a zero to initialise count of pairs
1e4XH:"         % 1e4=10000, XH saves into clipboard H, : makes the vector 1:1e4
                % which is used to index a for loop, started using "
    JZ@         % Use randperm to generate a random permutation of the vector 1:N*M
    I\          % take the result mod M, now each card has a value one less than before
    TTo3X53$X+  % convolve vector of card values with [1 1] to do pairwise summation
    1=a         % find if any sums equal 1, which means there is a [0 1] or [1 0]
    +           % add the logical value to the count of pairs
]
H/              % divide the count by the number of deals to get the probability

```

For example,

```
>> matl 'iiXI*XJxO1e4XH:"JZ@I\TTo3X53$X+1=a+]H/'
> 4
> 13
0.4861

```

Note (21/5/16): As of MATL release 18.0.0, `X+` has been removed, but `Y+` can be used in its place. The changes from MATL version 3.1.0 to 18.0.0 mean that this answer can now be written in just 31 bytes, `*xO1e4:"2:Gtb*Z@w\TT2&Y+1=ah]Ym`.

# Answer
> 1 votes
# Pyth, 16 bytes

```
JE?>J1-1^-1c2JQZ

```

Demonstration.

This follows the

* make an educated guess,
* check that it's close enough,
* repeat

strategy of programming. The winning educated guess in this case is

```
1 - (1 - 2 / M) ** N

```

which roughly says that there are `N` chances to fall into buckets, and fraction of valid buckets is `2 / M`. The buckets being slots places next to `0`s, and the chances being `1`s.

The error never seems to go above 3% (surprisingly), and seems to converge to 0% as the parameters get larger (as I would expect).

Input is newline separated.

```
              Q  Q = eval(input())
JE               J = eval(input())
  ?>J1           if J > 1
      -1^-1c2JQ  then 1 - (1 - 2 / J) ** Q
               Z else 0

```

You can save a character if you accept the plainly obvious fact that `False == 0`, and do `JE&>J1-1^-1c2JQ` instead.

# Answer
> 0 votes
## Mathematica, ~~93~~ ~~92~~ 91 bytes

```
N@Count[RandomSample@Flatten[Range@#~Table~{#2}]~Table~{a=1*^5},{b=___,1,2,b}|{b,2,1,b}]/a&

```

Still looking for a closed form...

---
Tags: code-golf, probability-theory, simulation
---


title: Does the string contain 2016?

text:
# Question
Title: Does the string contain 2016?
Given a string input, your task is to write a program that prints a truthy value to STDOUT or equivalent if the input contains "2016" anywhere in it without using any built-in `contains`, `match`, `replace`, `split` or other functions that use patterns or regexes.

A truthy value also must be printed if the input contains "2016" with the *same* number of spaces between each number.

## Test Cases

```
2016
    => true
"2016"
    => true
2202012016016166
      ^^^^ => true
220201 2 0 1 6 016166
    => true
Happy New Year! It's 2016!
    => true
2016 is coming!
    => true

2_0_1_6
    => false
22001166
    => false
It's not 2015 any more
    => false
6102
    => false
201.6
    => false
20 16
    => false
2 0  1   6
    => false

```

## Rules

* Regexes and pattern matching cannot be used
* Built-in `contains`, `match`, and `replace` cannot be used
* Built-in `split` functions cannot be used (the only exception is when splitting the string into individual characters for looping through them, such as `input.split("")`)
* The code cannot contain the string "2016" in any form (unicode literals and constructing the string included - that *doesn't* mean that the characters 0, 1, 2, or 6 can't be used)
* The input may either be taken from `STDIN` or as an argument to a function
* It is safe to assume that the input will *not* contain linefeeds or newlines.
* The input may contain any printable ASCII characters (spaces included)
* A truthy value must be printed to `STDOUT` or equivalent if the input contains **2016**.
* A falsey value must be printed to `STDOUT` or equivalent if the input does *not* contain **2016**
* If using a function, instead of using `STDOUT`, the output can be the return value of the function
* The truthy/falsey value cannot be printed to `STDERR`.
* Standard loopholes apply
* This is , so the shortest program in bytes wins. Good luck!

## Bonus

**-30 Bytes** if the input also returns a truthy value if the spaces between the characters in 2016 are the same.

```
Happy 2 0 1 6
    => true
I can't wait for  2   0   1   6
    => true
It's almost 2 0  1   6
    => false

```

## Leaderboard

This is a Stack Snippet that generates both a leaderboard and an overview of winners by language.

To ensure 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, in bytes, of your submission

If you want to include multiple numbers in your header (for example, striking through old scores, or including flags in the byte count), just make sure that the actual score is the *last* number in your header

```
## Language Name, <s>K</s> X + 2 = N bytes

```

```
var QUESTION_ID=67575;var OVERRIDE_USER=20634;function answersUrl(e){return"http://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"http://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
# CJam, 35 - 30 = 5 bytes

```
qS*_,,_Sf*{"2 0 1 6"\*}%\:)@few:+&`

```

## Explanation

```
qS*                                   Push s p a c e d   i n p u t.
   _,,                                Push [0..N-1] where N = len(input).
      _Sf*                            Push ["", " ", "  ", "   ", ...].
          {"2 0 1 6"\*}%              Make it ["2 0 1 6", "2   0   1   6", ...].
                        \             Swap [0..N-1] to top of stack.
                         :)           Increment each, giving [1..N].
                           @          Rotate spaced input I to top of stack.
                            few       Push [I1ew I2ew .. INew], i.e.
                               :+      when concatenated, all substrings of I.
                                 &    Intersect sets.
                                  `   Print as CJam syntax.

```

Essentially, given an input string `abcd`, this executes a "substring search" by intersecting the sets:

* `2 0 1 6`, `2 0 1 6`, ... up to `2*len(input())-1` = more than enough spaces,
* `a`, , `b`, ..., `a b`, ... `a b c d`.

If a result is found, such a spaced `2016` string appeared as a substring of the input, and a truthy list containing this result is printed, like `["2 0 1 6"]`. Otherwise, the empty list is printed.

The string `"2016"` is never constructed as the code runs; only its spaced-out versions are.
> 1 votes

# Answer
# JavaScript (ES6), 125 - 30 = 95 bytes

```
x=>(y=[...x]).map((_,i)=>y.map((_,j)=>r?0:(n=x.substr(j,a.length),r=n<a&n>b),s=" ".repeat(i),a=2+s+0+s+1+s,b=a+5,a+=7),r=0)|r

```

## Explanation

Returns `1` if it matched, otherwise `0`.

Brute forces every possible combination of spaces between `2016` and checks for a match at each substring. Note that it never constructs the string `2016` because it generates `a` as `2017` and `b` as `2015` (both with spaces) and checks if `b < substring < a`.

```
x=>                             // x = input string
  (y=[...x])                    // y = input as array
  .map((_,i)=>                  // loop over every possible amount of spaces between digits
    y.map((_,j)=>               // loop over every character to check for a match
      r?0:(                     // if r is set we don't have to do anything, if not:
        n=x.substr(j,t.length), // n = substring to compare
        r=n<a&n>b               // check if r is 2016
      ),
      s=" ".repeat(i),          // s = spaces between letters
      a=2+s+0+s+1+s,            // get string to compare with
      b=a+5,                    // b = 2015 (with spaces)
      a+=7                      // a = 2017 (with spaces)
    ),
    r=0                         // r = result
  )
  |r                            // return result

```

## Test

```
var solution = x=>(y=[...x]).map((_,i)=>y.map((_,j)=>r?0:(n=x.substr(j,a.length),r=n<a&n>b),s=" ".repeat(i),a=2+s+0+s+1+s,b=a+5,a+=7),r=0)|r
```

```
<input type="text" id="input" value="I can't wait for  2   0   1   6" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
> 1 votes

# Answer
## Swift 2, ~~307~~ 297 - 30 = 267 Bytes

```
func d(s:String)->Int{var c=0;var n=0;var l=0;for v in s.characters{if(v=="2"){c=1;l=0;n=0};if(c==1&&v=="0"){c=2;l=n;n=0};if(c==2&&v=="1"){c=(l==n ?3:0);l=n;n=0};if(c==3&&v=="6"){if(l==n){return 1}else{c=0}};if(!(v=="2" || v=="0" || v=="1" || v=="6")){if(v==" "){n++}else{c=0;l=0;n=0;}}};return 0}

```

### Ungolfed

```
func d(s: String) -> Int{
    var c=0
    var n=0
    var l=0
    for v in s.characters{
        if(v == "2"){
            c = 1
            l = 0
            n = 0
        }
        if(c == 1 && v == "0"){
            c = 2
            l = n
            n = 0
        }
        if(c == 2 && v == "1"){
            c = (l == n ? 3 : 0)
            l = n
            n = 0
        }
        if(c == 3 && v == "6"){
            if(l == n){
                return 1
            }
            else{
                c = 0
            }
        }
        //you may be wondering why I didn't use &&. It's because
        //using && would require me to use !=, which needs spaces
        //on both sides
        if(!(v == "2" || v == "0" || v == "1" || v == "6")){
            if(v == " "){
                n++
            }
            else{
                c=0
                l=0
                n=0
            }
        }
    }
    return 0
}

```
> 0 votes

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


title: Properties of Binary Functions

text:
# Question
Title: Properties of Binary Functions
Many important topics in abstract algebra involve a binary function acting on a set. A number of properties of such functions have been defined in the investigation of such topics.

Your challenge will be to determine whether a given binary function on a given domain possesses five of these properties.

## Properties

**Closure**

A binary function is closed if every possible output is in the domain.

**Associativity**

A binary function is associative if the order in which the function is applied to a series of inputs doesn't affect the result. That is, `$` is associative if `(a $ b) $ c` always equals `a $ (b $ c)`. Note that since the value `(a $ b)` is used as an input, associative functions must be closed.

**Commutativity**

A binary function is commutative if swapping the order of the inputs doesn't change the result. In other words, if `a $ b` always equals `b $ a`.

**Identity**

A binary function has an identity element if there exists some element `e` in the domain such that `a $ e = a = e $ a` for all `a` in the domain.

**Idempotence**

A binary function is idempotent if applying it to two identical inputs gives that number as the output. In other words, if `a $ a = a` for all `a` in the domain.

## Input

You will be given a function in the form of a matrix, and the domain of the function will be the numbers `0 ... n-1`, where `n` is the side length of the matrix.

The value `(a $ b)` is encoded in the matrix as the `a`th row's `b`th element. If the input matrix is `Q`, then `a $ b` = `Q[a][b]`

For example, the exponentiation function (`**` in Python) on the domain `[0, 1, 2]` is encoded as:

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

```

The left and right domains are the same, so the matrix will always be square.

You may use any convenient matrix format as input, such as a list of lists, a single list in row- or column- major order, your language's native matrix object, etc. However, you may not take a function directly as input.

For simplicity, the matrix entries will all be integers. You may assume that they fit in your language's native integer type.

## Output

You may indicate which of the above properties hold in any format you choose, including a list of booleans, a string with a different character for each property, etc. However, there must be a distinct, unique output for each of the 24 possible subsets of the properties. This output must be easily human-readable.

## Examples

The maximum function on domain n=4:

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

```

This function has the properties of closure, associativity, commutativity, identity and idempotence.

The exponentiation function on domain n=3:

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

```

This function has none of the above properties.

The addition function on domain n=3:

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

```

This function has the properties of commutativity and identity.

The K combinator on domain n=3:

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

```

This function has the properties of closure, associativity and idempotence.

The absolute difference function on domain n=3:

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

```

This function has the properties of closure, commutativity and identity.

The average function, rounding towards even, on domain n=3:

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

```

This function has the properties of closure, commutativity, identity and idempotence.

The equality function on domain n=3:

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

```

This function has the properties of closure and commutativity.

## Challenge

This is code golf. Standard loopholes apply. Least bytes wins.

# Answer
> 4 votes
# Pyth, 51 bytes

```
[qKUQ@VQKCIQ}]Km{@RdCBQKJ!-sQK&JqF.bsm@L@QdYN.p,sQK

```

Try it online: Demonstration or Test Suite

This prints a list of 5 boolean values. They indicate the properties in the order:

```
[Idempotence, Commutativity, Identity, Closure, Associativity]

```

Here is a better output format: Demonstration or Test Suite

### Explanation:

**Idempotence:**

```
qKUQ@VQK
   Q       Q = input matrix
  UQ       [0, 1, ..., len(matrix)-1]
 K         assign to K
    @VQK   vectorized lookup of Q and K //gets the diagonal elements
qK         check, if this is equal to K

```

**Commutativity:**

```
CIQ   check if transpose(Q) is equal to Q

```

**Identity:**

```
}]Km{@RdCBQK
   m       K   map each d in K to:
        CBQ       the list [Q, transpose(Q)]
     @Rd          take the d-th element of each ^
    {             remove duplicates
}]K            check if [K] is in ^

```

**Closure:**

```
J!-sQK
   sQ    sum(Q) //all elements of Q
  -  K   remove the elements, that also appear in K
 !       ckeck, if the results in an empty list
J        store the result in J

```

**Associativity:**

```
&JqF.bsm@L@QdYN.p,sQK
               .p,sQK  all permutations of [sum(Q), K] //all 2 ;-)
    .b                 map each pair (N,Y) of ^ to:
       m      N           map each d of N to:
          @Qd                the row Q[d]
        @L   Y               map each element of Y to the corr. element in ^
      s                   unfold this 2-d list
  qF                   check if they result in identically lists
&J                     and J

```

# Answer
> 5 votes
## Haskell, ~~178~~ 171 bytes

```
import Data.List
f x=[c,c&&and[(m%n)%o==m%(n%o)|m<-b,n<-b,o<-b],x==t,all(elem b)[x,t],b==[i%i|i<-b]]where c=all(l>)(id=<<x);b=[0..l-1];a%b=x!!a!!b;l=length x;t=transpose x

```

Returns a list with five booleans, which are in order closure, associativity, commutativity, identity and idempotence.

Usage example: `f [[1, 0, 0],[0, 1, 0],[0, 0, 1]]` -\> `[True,False,True,False,False]`.

How it works:

```
f x=[
  c,                         -- closure (see below)
  c&&and[(m%n)%o==m%(n%o)|   -- assoc: make sure it's closed, then check the
          m<-b,n<-b,o<-b],   --        assoc rule for all possible combinations
  x==t,                      -- comm: x must equal it's transposition
  all(elem b)[x,t],          -- identity: b must be a row and a column
  b==[i%i|i<-b]              -- idemp: element at (i,i) must equal i
  ]
  where                      -- some helper functions
  c=all(l>)(id=<<x);         -- closure: all elements of the input must be < l
  b=[0..l-1];                -- a list with the numbers from 0 to l-1
  a%b=x!!a!!b;               -- % is an access function for index (a,b)
  l=length x;                -- l is the number of rows of the input matrix
  t=transpose x

```

Edit @xnor found some bytes to save. Thanks!

# Answer
> 4 votes
# CJam, 95 bytes

```
q~:Ae_A,:Bf<:*'**B3m*{_{A==}*\W%{Az==}*=}%:*'A*A_z='C*B{aB*ee_Wf%+{A==}f*B,2*='1*}%Ae_B)%B,='I*

```

Prints a subsequence of `*AC1I`. `*` is the symbol for **closure**, `A` is for **associative**, `C` is for **commutative**, `1` is for **identity** and `I` is for **idempotent**.

---

The input array is read `q~` and stored in A (`:A`).

### Closure

```
Ae_A,:Bf<:*'**

```

If all (`:*`) elements in the matrix (`Ae_`) are smaller `f<` than B=size(A) (`A,:B`), print a `*` (`'**`).

### Associativity

```
B3m*{_{A==}*\W%{Az==}*=}%:*'A*

```

Generate all triples in the domain (`B3m*`). We print `A` if they all satisfy a condition (`{...}%:*'A*`).

The condition is that, for some triple `[i j k]`, left-folding that list with **A** (`_{A==}*`) and left-folding its reverse `[k j i]` (`\W%`) with **Aop** (`{Az==}*`), the flipped version of `A`, are equal (`=`).

### Commutativity

**A** must equal its transpose: `A_z=`. If so, we print `C` (`'C=`).

### Identity

```
B{                         }%   For each element X in the domain (0..N-1):
  aB*                           Make N copies.
     ee                         [[0 X] [1 X] ...]
       _Wf%+                    [[0 X] [1 X] ... [X 0] [X 1] ...]
            {A==}f*             [A(0, X) A(1, X) ... A(X, 0) A(X, 1)]
                   B,2*=        This list should equal the domain list repeated twice.
                        '1*     If so, X is an identity: print a 1.

```

The identity is necessarily unique, so we can only print one `1`.

### Idempotent

```
Ae_B)%B,='I*

```

Check if the diagonal equals `B,`. If so, print an `I`.

# Answer
> 3 votes
# Matlab, 226

```
a=input('');n=size(a,1);v=1:n;c=all(0<=a(:)&a(:)<n);A=c;for i=v;for j=v(1:n*c);for k=v(1:n*c);A=A&a(a(i,j)+1,k)==a(i,a(j,k)+1);end;end;b(i)=all(a(i,:)==v-1 & a(:,i)'==v-1);end;disp([c,A,~norm(a-a'),any(b),all(diag(a)'==v-1)])

```

An important thing to notice is that non-closed implies non-associative. Many of those properties can easily be checked using some properties of the matrix:

* **Closure**: All all matrix entries in the given range?
* **Associativity**: As always the most difficult one to check
* **Commutativity**: Is the matrix symmetric?
* **Identity**: Is there an index k such that the k-th row and k-th column are exactly the list of the indices?
* **Idempotence**: Does the diagonal correspond to the list of indices?

Input via standar Matlab notation: `[a,b;c,d]` or `[[a,b];[c,d]]` or `[a b;c d]` e.t.c.

Output is a vector of ones a zeros, 1 = true, 0 = false, for each of the properties in the given order.

Full code:

```
a=input('');
n=size(a,1);
v=1:n;
c=all(0<=a(:)&a(:)<n);               %check for closedness
A=c;
for i=v;
   for j=v(1:n*c);
      for k=v(1:n*c);
          A=A&a(a(i,j)+1,k)==a(i,a(j,k)+1);   %check for associativity (only if closed)
      end;
   end;
   b(i)=all(a(i,:)==v-1 & a(:,i)'==v-1);      %check for commutativity
end
%closure, assoc, commut, identity, idempotence
disp([c,A,~norm(a-a'),any(b),all(diag(a)'==v-1)]);

```

# Answer
> 3 votes
# JavaScript (ES6) 165

An anonymous function returning an array with five 0/1 values, which are in order Closure, Associativity, Commutativity, Identity and Idempotence.

```
q=>q.map((p,i)=>(p.map((v,j)=>(w=q[j][i],v-w?h=C=0:v-j?h=0:0,q[v]?A&=!q[v].some((v,k)=>v-q[i][q[j][k]]):A=K=0),h=1,p[i]-i?P=0:0),h?I=1:0),A=P=K=C=1,I=0)&&[K,A,C,I,P]

```

**Less golfed**

```
f=q=>(
  // A associativity, P idempotence, K closure, C commuativity
  // assumed true until proved false
  A=P=K=C=1,
  I=0, // Identity assumed false until an identity element is found
  q.map((p,i)=> (
      h=1, // assume current i is identity until proved false
      p[i]-i? P=0 :0, // not idempotent if q[i][i]!=i for any i
      p.map((v,j)=> (
          w=q[j][i], // and v is q[i][j]
          v-w // check if q[j][i] != q[i][j]
          ? h=C=0 // if so, not commutative and i is not identity element too
          : v-j // else, check again for identity
            ? h=0 // i is not identity element if v!=j or w!=j
            : 0,
          q[v] // check if q[i][j] in domain
            ? A&=!q[v].some((v,k)=>v-q[i][q[j][k]]) // loop for associativity check
            : A=K=0 // q[i][j] out of domain, not close and not associative
        )
      ),
      h ? I=1 : 0 // if i is the identity element the identity = true
    )
  ),
  [K,A,C,I,P] // return all as an array
)

```

**Test**

```
f=q=>
  q.map((p,i)=>(
    p.map((v,j)=>(
      w=q[j][i],
      v-w?h=C=0:v-j?h=0:0,
      q[v]?A&=!q[v].some((v,k)=>v-q[i][q[j][k]]):A=K=0
    ),h=1,p[i]-i?P=0:0),
    h?I=1:0
  ),A=P=K=C=1,I=0)
  &&[K,A,C,I,P]

// test

console.log=x=>O.textContent+=x+'\n';

T=[
 [
  [[0, 1, 2, 3],
   [1, 1, 2, 3],
   [2, 2, 2, 3],
   [3, 3, 3, 3]]
 ,[1,1,1,1,1]] // has the properties of closure, associativity, commutativity, identity and idempotence.
,[ // exponentiation function on domain n=3:
  [[1, 0, 0],
   [1, 1, 1],
   [1, 2, 4]]
 ,[0,0,0,0,0]] // has none of the above properties.
,[ // addition function on domain n=3:
  [[0, 1, 2],
   [1, 2, 3],
   [2, 3, 4]]
 ,[0,0,1,1,0]] // has the properties of commutativity and identity.
,[ // K combinator on domain n=3:
  [[0, 0, 0],
   [1, 1, 1],
   [2, 2, 2]]
 ,[1,1,0,0,1]] // has the properties of closure, associativity and idempotence.
,[ // absolute difference function on domain n=3:
  [[0, 1, 2],
   [1, 0, 1],
   [2, 1, 0]]
 ,[1,0,1,1,0]] // has the properties of closure, commutativity and identity.
,[ // average function, rounding towards even, on domain n=3:
  [[0, 0, 1],
   [0, 1, 2],
   [1, 2, 2]]
 ,[1,0,1,1,1]] // has the properties of closure, commutativity, identity and idempotence.
,[ // equality function on domain n=3:
  [[1, 0, 0],
   [0, 1, 0],
   [0, 0, 1]]
 ,[1,0,1,0,0]] // has the properties of closure, commutativity,
]

T.forEach(t=>{
  F=t[0],X=t[1]+'',R=f(F)+'',console.log(F.join`\n`+'\n'+R+' (expected '+X+') '+(X==R?'OK\n':'Fail\n'))
  })
```

```
<pre id=O></pre>
```

---
Tags: code-golf, math, function
---


# Question
Title: Recreate an xkcd graph procedurally with your favorite plotting tool
Lately there have been quite a number of questions regarding the recreation of xkcd-style graphs like the following one (1064) in various languages.

Your goal is to recreate any existing xkcd comic as close to the original as possible. The comic has to have at least one simple graph or pie chart or similar element.

**The highest voted answer wins**, not sooner than 10 days after the first valid answer.

Your entry must contain code that displays an xkcd-comic as described above in a graphing language, making at least some use of its plotting tool (Mathematica, MatLab, etc.)

* the comic must not be stored as an image, it has to be generated procedulally
* there must not be any link whatsoever to the original website, or a mirror of it, or its contents on your hard drive, etc.

Votes should evaluate the similarity of the results to the original, and to a lesser extent, the beauty of the solution. No code golf here, but a solution as short and simple as possible is expected.

# Answer
> 8 votes
Here's a stab.

## Postscript

\[*Count deleted because this isn't a golf question.*\]

Added a "style" section to make it look more hand-drawn.

*Edit:* Helvetica responds better than Courier. Tweaked and enhanced this "style" section. And added comments.

```
%!

%futz with a coordinate pair
/f { 2 { rand 100 mod 100 div 1.47 mul
        dup .4 mul sub add
        exch } repeat } def

/op 2 array def %original point
/cp 2 array def %current point
/setcp { 2 copy cp astore pop } def %set current point
/difcp { cp aload pop %x' y' x y   %diff between cp and point on stack
    3 2 roll exch sub %x' x y'-y
    3 1 roll sub %y'-y x'-x
    exch %dx dy
} def
/scale2 { /n exch def  %scale two values
    n mul exch n mul exch
} def
/add2 {
    3 2 roll add
    3 1 roll add exch
} def
%futz with a path
/fpath {
    2 {
    %flattenpath
    % replace lines with curves
    [ { setcp cp op copy pop /moveto cvx }
        {
            %cp aload pop 4 2 roll 2 copy
            2 copy difcp %x3 y3 x30 y30
            2 copy 1 4 div scale2 %x3 y3 x30 y30 (1/3)x30 (1/3)y30
            cp aload pop add2 %x3 y3 x30 y30 x1 y1
            4 2 roll 3 4 div scale2 %x3 y3 x1 y1 (2/3)x30 (2/3)y30
            cp aload pop add2 %x3 y3 x1 y1 x2 y3
            6 4 roll %x1 y1 x2 y2 x3 y3
            setcp
            /curveto cvx }
        { setcp /curveto cvx }
        { op cp copy pop /closepath cvx } pathforall ] cvx newpath exec
    % chop the curves
    flattenpath
    % futz all the points
    [ { f
        /moveto cvx }
        { f
            /lineto cvx }
        { %f
            f 6 2 roll
            f 6 2 roll
            f 6 2 roll
            2 copy
            /curveto cvx
            3 1 roll
            3{f}repeat /lineto cvx % extra triple-futz'd line after each curve
        }
        { /closepath cvx } pathforall ] cvx newpath exec
    } repeat
} def

%futz with strokes
/oldstroke /stroke load def
/stroke { fpath oldstroke } def

%futz with fills
/oldfill /fill load def
/fill { fpath oldfill } def

%make sure rectstroke doesn't bypass being futzed with
/rectstroke {
    4 2 roll moveto
    1 index 0 rlineto
    0 exch rlineto
    neg 0 rlineto
    closepath
    stroke
} def

%futz with strings
%by making sure show uses our futz'd fill
/show { gsave currentpoint newpath moveto dup
    false charpath 1{fpath}repeat fill grestore stringwidth rmoveto } def

%fatter lines
1 setlinejoin %round joins
currentlinewidth 1.9 mul setlinewidth
%chop curves very small so there's lots of points for futzing
currentflat 6 div setflat

/Helvetica 10 selectfont

<<
/in{72 mul}
>>begin
1 in 1 in translate

0 0 6 in 4 in rectstroke
1 in 3 in moveto (WALKING BACK TO MY) show
1 in 2.8 in moveto (FRONT DOOR AT NIGHT:) show

36 3.5 in moveto
0 -2.8 in rlineto
5 in 0 rlineto
3.45 in .55 in moveto
0 20 rlineto
4.05 in .55 in moveto
0 20 rlineto
2.7 in .40 in moveto
(YARD  STEPS DOOR  INSIDE ) show
0 .05 in rmoveto
.4 in 0 rlineto
currentpoint
stroke
moveto
-10 3 rlineto
0 -6 rlineto fill

2.6 in .45 in moveto
-2 in 0 rlineto
currentpoint
stroke
moveto
10 3 rlineto
0 -6 rlineto fill

(FEAR) .9 in 2.3 in moveto show
(THAT THERE'S) .9 in 2.1 in moveto show
(SOMETHING) .9 in 1.9 in moveto show
(BEHIND ME) .9 in 1.7 in moveto show
1.8 in 1.86 in moveto
2 -26 rlineto
stroke

(FORWARD) 2.2 in 2.1 in moveto show
(SPEED) 2.2 in 1.9 in moveto show
2.75 in 2 in moveto
3 -13 rlineto
stroke

(EMBARRASSMENT) 4.5 in 2.5 in moveto show
4.6 in 2.65 in moveto
-2 20
-5 22
-27 25 rcurveto
stroke

.6 setgray %gray
40 1.6 in moveto
2.7 in 0
2.9 in 20
3.2 in 1.5 in rcurveto
10 20
20 20
30 0 rcurveto
15 -1.7 in
30 -1.8 in
1.4 in -2 in rcurveto
stroke

0 0 1 setrgbcolor %blue
40 1.2 in moveto
.9 in 27
.8 in 20
1.4 in 21 rcurveto
1 in -20
1.2 in 6
1.3 in 1.6 in rcurveto
    10 20
    20 20
    30 0 rcurveto
15 -1.8 in
30 -1.9 in
1.8 in -2.1 in rcurveto
stroke

1 0 0 setrgbcolor %red
40 .9 in moveto
3.3 in 0
3.5 in 20
3.6 in 1.5 in rcurveto
10 72
20 80
30 80 rcurveto
.7 in -10
.3 in -35
1.1 in -40 rcurveto
stroke

%thank you for scrolling all the way down to here. :)

```

# Answer
> 6 votes
# HTML5

```
@font-face {
  font-family: 'Humor Sans';
  font-style: normal;
  font-weight: 400;
  src: local('Humor Sans'), local('Humor Sans-Regular'), url("data:font/woff;base64,[encoded data, 14384 characters]") format('woff');
}
body {
    font-family: 'Humor Sans';
    margin: 2em;
    background: #DDD;
    text-shadow: 1px 1px 2px #FFF;
}
h1 {
    font-family:Lucida,Helvetica,sans-serif;
}
.h1d {
    display: inline;
    font-size: .8em;
}
path,rect { fill: none;
    stroke:#000000;
    stroke-width:0.00329859;
    stroke-linecap:butt;
    stroke-linejoin:round;
    stroke-miterlimit:10.43299961;
 }
text {
    text-align:start;
    letter-spacing:0px;
    word-spacing:0px;
    writing-mode:lr-tb;
    font-size:14px;
    text-anchor:start;
    fill:#000000;
    fill-opacity:1;
    stroke:none;
    font-family:Humor Sans;
}
text {
    font-size:0.01944444px;
    text-anchor:middle;
    fill:#000000;
    fill-opacity:1;
    stroke:none;
    font-family:Humor Sans;
}
```

```
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Front Door ( from xkcd.com 1064 )</title>
  </head>
<body><h1>Front Door <div class="h1d">( from xkcd.com 1064 )</div></h1>
<svg xmlns="http://www.w3.org/2000/svg" width="640" height="434"
   version="1.1" viewBox="0 0 0.7876308 0.53355077">
  <defs>
    <marker id="Aen" style="overflow:visible">
      <path d="M 0,0 5,-5 -12.5,0 5,5 0,0 z" transform="matrix(-0.4,0,0,-0.4,-4,0)"
         style="fill-rule:evenodd;fill:#000;stroke:#000000;stroke-width:1pt" />
    </marker>
    <marker orient="auto" id="Ast" style="overflow:visible">
      <path d="M 0,0 5,-5 -12.5,0 5,5 0,0 z"
         transform="matrix(-0.4,0,0,-0.4,-1.4,0)"
         style="fill-rule:evenodd;fill:#000;stroke:#000000;stroke-width:1pt" />
    </marker>
  </defs>
  <rect width="0.75612795" height="0.50201935" x="0.015758738" y="0.015780471" />
  <path d="m 0.08162198,0.08036774 c -3.384e-4,3.2166e-4 -7.6617e-4,0.35262886 -7.6617e-4,0.35262886 0,0 0.20318503,-6.6026e-4 0.29000566,-0.003213 0.0402085,3.6731e-4 0.0806898,-1.3866e-4 0.12100339,-4.2191e-4 0.0422491,-4.676e-5 0.0848177,0.001196 0.12714108,1.4026e-4 0.0292134,0.0012 0.0579496,7.8663e-4 0.0872307,8.041e-5" />
  <path d="M 0.45045642,0.44967094 C 0.45097434,0.43767424 0.44992661,0.42569324 0.4498655,0.41370014" />
  <path d="m 0.52462262,0.44857719 c 0.001364,-0.0112841 -0.001303,-0.022673 8.8508e-4,-0.0339046" />
  <path d="m 0.34455432,0.46185837 c -0.0838098,-0.00177 -0.16763839,9.02e-5 -0.25145536,-4.499e-4" style="marker-end:url(#Ast)" />
  <path d="m 0.36372087,0.26833529 c 3.15e-6,-3.093e-5 0.003925,0.021959 0.003958,0.0219625" />
  <path d="m 0.59455272,0.18635665 c 0.00168,-0.0249062 -0.0194278,-0.0449558 -0.0436226,-0.042955 -0.001466,-1.5486e-4 -0.002932,-3.0973e-4 -0.004398,-4.6459e-4" />
  <path d="m 0.08896568,0.31883844 c 0.0589995,-0.004388 0.11835478,4.8486e-4 0.17689559,-0.007727 0.0452821,-0.002558 0.0920316,-0.008761 0.13292997,-0.0296799 0.0495136,-0.0206019 0.0702543,-0.0754087 0.082167,-0.12423165 -0.001544,-0.0316524 0.0363005,-0.0771322 0.0574533,-0.031946 0.009799,0.0468904 0.0124403,0.0957944 0.0257953,0.14199884 0.0103229,0.0424564 0.0381648,0.0821154 0.0814383,0.0955288 0.0230248,0.006738 0.0463641,0.0136174 0.0701731,0.01698" style="stroke:#888" />
  <path d="m 0.08766361,0.36678952 c 0.0463076,-0.0161779 0.0920382,-0.0420708 0.14283849,-0.0357173 0.0467333,-0.004581 0.0974621,0.0266481 0.14082991,-0.00179 0.0400306,-0.0301432 0.041483,-0.0866619 0.0490443,-0.13214834 0.003929,-0.030081 -0.00375,-0.0999028 0.0422392,-0.0879794 0.0291414,0.0376662 0.0177989,0.0902038 0.0319018,0.1336763 0.009362,0.0507676 0.0330856,0.10817744 0.0871312,0.12415282 0.0508722,0.0193263 0.0767224,0.0174745 0.11889504,0.0257316" style="stroke:#00f" />
  <path d="m 0.08912193,0.4046365 c 0.10169167,1.097e-5 0.2041028,3.5438e-4 0.3047905,-0.0155419 0.0458292,-0.008171 0.0971567,-0.0242812 0.12178371,-0.0670869 0.025388,-0.0534434 0.0183231,-0.11451516 0.0333489,-0.17061477 -0.003977,-0.0433016 0.0436224,-0.0993166 0.0831427,-0.0568712 0.0246552,0.0226559 0.0477548,0.0560862 0.0858377,0.0521295" style="stroke:#f00" />
  <path d="m 0.70840577,0.46185837 c -0.002849,8.248e-5 -0.0849355,0.001616 -0.0849355,0.001616" style="marker-start:url(#Aen)" />
  <path d="m 0.24465913,0.2858699 c 9.6794e-4,0.0147144 0.001383,0.0294673 0.002814,0.0441494" />
  <text x="100.15588" y="48.485607" transform="scale(0.00138889,0.00138889)"
    style="font-size:14px;text-anchor:start">
    <tspan x="100.15588" y="48.485607" id="tspan7010">WALKING BACK TO MY</tspan>
    <tspan x="100.15588" y="65.285591" id="tspan7012">FRONT DOOR AT NIGHT:</tspan></text>
  <rect width="0.24843951" height="0.065260872" x="0.12345294" y="0.039088331" />
  <text x="0.23551519" y="0.20231472"><tspan x="0.23551519" y="0.20231472">fear</tspan>
    <tspan x="0.23551519" y="0.22564805">ThAT there's</tspan>
    <tspan x="0.23551519" y="0.24898137">something</tspan>
    <tspan x="0.23551519" y="0.2723147">behing me</tspan></text>
  <text x="0.36015913" y="0.22917171"><tspan x="0.36015913" y="0.22917171">fORWarD</tspan>
    <tspan x="0.36015913" y="0.25250503">SPEED</tspan></text>
  <text x="0.37393194" y="0.46812996"><tspan x="0.37393194" y="0.46812996">yarD</tspan>
    <tspan x="0.45037103" y="0.46812996">step</tspan>
    <tspan x="0.52267832" y="0.46812996">door</tspan>
    <tspan x="0.58878779" y="0.46812996">inside</tspan></text>
  <text x="0.63905853" y="0.20506927">
    <tspan x="0.63905853" y="0.20506927">emBARRASSMENT</tspan></text>
</svg>
</body></html>
```

# Answer
> 6 votes
# Python

Makes use of the slightly cheat-y xkcd method in matplotlib:

```
import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage.filters import gaussian_filter1d

plt.xkcd()

x = np.linspace(0,10,1000)
unit = np.linspace(0,1,100)

speed = np.r_[np.ones(500)*3,3+5*unit**4.,np.ones(100)*8,1+7*unit[::-1]**2,np.ones(200)]
speed = gaussian_filter1d(speed,18)

fear = np.r_[np.linspace(0.5,2,450),2+6*unit**4,np.ones(100)*8,8*unit[::-1]**2,np.zeros(250)+0.1]
fear = gaussian_filter1d(fear,18)
fear_gauss_bump = 0.8*np.exp(-np.power(x-2.5,2.)/(2*np.power(1, 2.)))
fear += fear_gauss_bump

embarrassment = np.r_[np.zeros(600)+0.1, 9.5*unit**2, 9.5-np.linspace(0,1.5,300)]
embarrassment = gaussian_filter1d(embarrassment,60)

plt.figure(figsize=(12,6))
plt.plot(x,speed,c="gray")
plt.plot(x,fear,c="#1E9FDB")
plt.plot(x,embarrassment,c="r")

plt.plot([2.5,2.7],[3.9,2.3],c='k')
plt.plot([4.3,4.5],[3.6,3.1],c='k')
plt.plot(np.linspace(7.3,7.8,15),(0.25-(np.linspace(7.3,7.8,15)-7.3)**2)**0.5+7,c='k')

ax = plt.gca()
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.get_xaxis().tick_bottom()
ax.get_yaxis().tick_left()
#plt.ylim([0,10])
ax.set_xticks([6,7])
ax.set_xticklabels(["STEPS","DOOR"])
ax.set_yticks([])

ax.text(2,4,"FEAR\nTHAT THERE'S\nSOMETHING\nBEHIND ME",horizontalalignment='center')
ax.text(3.9,3.4,"FORWARD\nSPEED",horizontalalignment='center')
ax.text(7.4,6.6,"EMBARRASSMENT")
ax.text(1,8,"WALKING BACK TO MY\nFRONT DOOR AT NIGHT:",bbox={'facecolor':'none', 'edgecolor':'black'})
ax.annotate("YARD", xy=(0.5,-0.3), xytext=(4.5,-0.4),annotation_clip=False,arrowprops={'facecolor':'black', 'shrink':0.01, 'width':0.5})
ax.annotate("INSIDE", xy=(10,-0.3), xytext=(7.5,-0.4),annotation_clip=False,arrowprops={'facecolor':'black', 'shrink':0.01, 'width':0.5})

plt.show()

```

---
Tags: popularity-contest, graphical-output
---


title: The Kimberling Sequence

text:
# Question
Title: The Kimberling Sequence
### Introduction

Of course, we've got a lot of challenges, so here is another one.

The Kimberling sequence (A007063) goes as following:

```
1, 3, 5, 4, 10, 7, 15, 8, 20, 9, 18, 24, 31, 14, 28, 22, ...

```

This is produced by shuffling the normal iteration:

```
[1] 2  3  4  5  6  7  8

```

The first term of the sequence is `1`. After that, we reshuffle the sequence until all the terms on the left are used. The shuffling has the pattern `right - left - right - left - ...`. Since there are no terms at the left of the `1`, there is no shuffling. We get the following:

```
 2 [3] 4  5  6  7  8  9

```

On the ith iteration, we discard the ith item and put that in our sequence. This is the **2nd** iteration, so we discard the **2nd** item. The sequence becomes: `1, 3`. For our next iteration, we are going to shuffle the current iteration with the pattern above. We take the first unused item at the right of the ith item. This happens to be `4`. We will append this to our new iteration:

```
 4

```

Now we're going to take the first unused item at the left of the ith item. This is `2`. We will append this to our new iteration:

```
 4  2

```

Since there are no items left at the left of the ith item, we'll just append the rest of the sequence to the new iteration:

```
 4  2 [5] 6  7  8  9  10  11  ...

```

This is our **3rd** iteration, so we'll discard the **3rd** item, which is `5`. This is the third item in our sequence:

```
 1, 3, 5

```

To get the next iteration, just repeat the process. I've made a gif if it isn't clear:

The gif took me longer than writing the actual post

### Task

* Given an non-negative integer **n**, output the first **n** terms of the sequence
* You may provide a function or a program
* This is , so the submission with the least amount of bytes wins!

### Test cases:

```
Input: 4
Output: 1, 3, 5, 4

Input: 8
Output: 1, 3, 5, 4, 10, 7, 15, 8

Input: 15
Output: 1, 3, 5, 4, 10, 7, 15, 8, 20, 9, 18, 24, 31, 14, 28

```

**Note:** The commas in the output are not necessary. You may for example use newlines, or output a list, etc.

# Answer
# Pyth, 22 bytes

```
JS*3QVQ@JN=J.i>JhN_<JN

```

Try it online: Demonstration

Simply performs the shuffling technique described in the OP.

### Explanation:

```
JS*3QVQ@JN=J.i>JhN_<JN
JS*3Q                    assign the list [1, 2, ..., 3*input-1] to J
     VQ                  for N in range(Q):
       @JN                  print J[N]
            .i              interleave
              >JhN             J[N+1:] with
                  _<JN         reverse J[:N]
          =J                assign the resulting list to J

```
> 3 votes

# Answer
# Julia, ~~78~~ 71 bytes

```
n->[(i=j=x;while j<2i-3 j=i-(j%2>0?1-j:j+2)÷2;i-=1end;i+j-1)for x=1:n]

```

This is an unnamed function that accepts an integer and returns an integer array. To call it, assign it to a variable.

The approach here is the same as that described on OEIS.

Ungolfed:

```
# This computes the element of the sequence
function K(x)
    i = j = x
    while j < 2i - 3
        j = i - (j % 2 > 0 ? 1 - j : j + 2)÷2
        i -= 1
    end
    return i + j - 1
end

# This gives the first n terms of the sequence
n -> [K(i) for i = 1:n]

```

Saved 7 bytes thanks to Mauris!
> 6 votes

# Answer
# APL, ~~56~~ 44 bytes

```
{⍵<⍺+⍺-3:(⍺-1)∇⍺-4÷⍨3+(1+2×⍵)×¯1*⍵⋄⍺+⍵-1}⍨¨⍳

```

This is an unnamed monadic train that accepts an integer on the right and returns an array. It's roughly the same approach as my Julia answer.

The innermost function is a recursive dyadic function that returns the *n*th term in the Kimberling sequence, given *n* as identical left and right arguments.

```
{⍵<⍺+⍺-3:                                    ⍝ If ⍵ < 2⍺ - 3
         (⍺-1)∇⍺-4÷⍨3+(1+2×⍵)×¯1*⍵           ⍝ Recurse, incrementing a and setting
                                             ⍝ ⍵ = ⍺ - (3 + (-1)^⍵ * (1 + 2⍵))/4
                                   ⋄⍺+⍵-1}   ⍝ Otherwise return ⍺ + ⍵ - 1

```

With that in hand, we're able to get individual terms of the sequence. However, the problem then becomes that this is a *dyadic* function, meaning it requires arguments on both sides. Enter the  operator! Given a function `f` and an input `x`, `f⍨x` is the same as `x f x`. So in our case, referring to the aforementioned function as `f`, we can construct the following monadic train:

```
f⍨¨⍳

```

We apply `f` to each integer from 1 to the input, yielding an array.

Saved 12 bytes thanks to Dennis!
> 3 votes

# Answer
# Mathematica 130 bytes

```
(n=0;s={};Nest[(n++;AppendTo[s,z=#[[n]]];Flatten[TakeDrop[#,1+2(n-1)]/.{t___,z,r___}:>
Riffle[{r},Reverse@{t}]])&,Range[3*#],#];s)&

```

We begin with a list consisting of the range from `1` to `3x`, where `x` is the desired number of Kimberling sequence terms.

At each step, `n`, `TakeDrop` breaks the the current list into a front list of `2n+1` terms (where the work is done) and rear list (which will be later joined with the reworked front list). The front list is matched with the following pattern, `{t___,z,r___}` where z is the Kimberling term at the center of the front list. `r` is `Riffle`'d with the reverse of `t` and then the rear list is appended. `z` is removed and appended to (`AppendTo`) the growing Kimberling sequence.

`n` is incremented by `1` and the current list is processed by the same function via `Nest.`

---

**Example**

```
(n=0;s={};Nest[(n++;AppendTo[s,z=#[[n]]];Flatten[TakeDrop[#,1+2(n-1)]/.{t___,z,r___}:>
Riffle[{r},Reverse@{t}]])&,Range[3*#],#];s)&[100]

```

> {1, 3, 5, 4, 10, 7, 15, 8, 20, 9, 18, 24, 31, 14, 28, 22, 42, 35, 33, 46, 53, 6, 36, 23, 2, 55, 62, 59, 76, 65, 54, 11, 34, 48, 70, 79, 99, 95, 44, 97, 58, 84, 25, 13, 122, 83, 26, 115, 82, 91, 52, 138, 67, 90, 71, 119, 64, 37, 81, 39, 169, 88, 108, 141, 38, 16, 146, 41, 21, 175, 158, 165, 86, 191, 45, 198, 216, 166, 124, 128, 204, 160, 12, 232, 126, 208, 114, 161, 156, 151, 249, 236, 263, 243, 101, 121, 72, 120, 47, 229}
> 3 votes

# Answer
# Python 2, 76 bytes

```
for a in range(input()):
 b=a+1
 while-~b<2*a:b=a-(b^b%-2)/2;a-=1
 print a+b

```

## Explanation

This is the OEIS formula after many golf-y transformations! It worked out *beautifully*. The original code was

```
i=b=a+1
while b<2*i-3:b=i-(b+2,1-b)[b%2]/2;i-=1
print i+b-1

```

I first got rid of `i`, replacing it with `a+1` everywhere and expanding the expressions:

```
b=a+1
while b<2*a-1:b=a+1-(b+2,1-b)[b%2]/2;a-=1
print a+b

```

Then, rewrote `b<2*a-1` as `-~b<2*a` to save a byte of whitespace, and moved the `+1` into the selection, division by 2, and negation:

```
while-~b<2*a:b=a-(b,-b-1)[b%2]/2;a-=1

```

Then, `-b-1` is just `~b`, so we can write `(b,~b)[b%2]`. This is equivalent to `b^0 if b%2 else b^-1` using the XOR operator, or alternatively, `b^b%-2`.

```
while-~b<2*a:b=a-(b^b%-2)/2;a-=1

```
> 2 votes

# Answer
# Pyth, ~~29~~ 25 bytes

```
VQ+.W<hHyN-~tN/x%Z_2Z2hNN

```

Jakube saved 4 bytes, but I have no clue how to read the code anymore.

Here is the old solution:

```
VQKhNW<hKyN=K-~tN/x%K_2K2)+KN

```

Translation of my Python answer. I'm not very good at Pyth, so maybe there's still ways to shorten this.

```
VQ                              for N in range(input()):
  KhN                             K = N+1
     W<hKyN                       while 1+K < 2*N:
           =K-~tN/x%K_2K2)         K = (N--) - (K%-2 xor K) / 2
                          +KN     print K + N

```
> 2 votes

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


title: Binary Run-Length Encoding

text:
# Question
Title: Binary Run-Length Encoding
# Overview

> Run-length encoding — sequences in which the same data value occurs in many consecutive data elements are stored as a single data value and count

When using run-length encoding:

```
Input:  ABBBCCACB
Output: 1A3B2C1A1C1B

```

This sample has an output that is larger than the input.

---

Instead, it can be simplified for binary inputs by removing the data value in the result,

```
Input:  10001110101
Output: 1331111

```

which is significantly smaller. This works because, logically, if the there is a "next subset" then it must be of a different data value than the current subset. Since there are only two possible values (1 and 0), you always know the "next" data value subset.

---

# Challenge

Implement binary run-length encoding demonstrated above.

* Take input through STDIN or suitable alternative.
* Output to STDOUT or suitable alternative.

---

# Examples

```
In:  101011101011000011
Out: 11113111242

In:  01001010001
Out: 11211131

In:  000000000
Out: 9

```

You may assume that no subsets will be longer than 9 characters (there won't be 10 adjacent zeroes).

# Answer
> 2 votes
# Pyth - 5 bytes

```
hMrz8

```

Test Suite.

# Answer
> 2 votes
# Ruby, ~~37~~ 29 bytes

```
->s{s.gsub(/0+|1+/){$&.size}}

```

Test:

```
->s{s.gsub(/0+|1+/){$&.size}}["10001110101"]
=> "1331111"

```

# Answer
> 2 votes
# Stuck, 5 bytes

```
soT]y

```

Takes a binary string as input and outputs an array.

## Explanation

```
soT]y

s       get input string
 o      run-level encoding
  T     zip
   ]    flatten
    y   pops the data values off

```

# Answer
> 1 votes
# CJam, 6 bytes

```
le`s2%

```

Try it here.

# Answer
> 1 votes
## Haskell, 39 bytes

```
import Data.List
(show.length=<<).group

```

Unfortunately `group` is in `Data.List`, so I need the `import`.

Usage example: `(show.length=<<).group $ "101011101011000011"` -\> `"11113111242"`.

---
Tags: code-golf, binary
---


title: Adding Semicolons

text:
# Question
Title: Adding Semicolons
**Objective**

Write the shortest program possible that adds semicolons to the end of all lines of code in a file **unless**:

* it already has a semicolon at the end
* the line is blank.

Must be a complete program.

**Bonuses**

Write the program so it won't produce any compiler errors when running the program on a C Header File.

# Answer
> 3 votes
# Retina, 12 bytes

```
m`[^;¶]$
$0;

```

Try it online!

### How it works

```
m`        Activate multi-line mode.
  [^;¶]   Match any character but a semicolon or a linefeed...
       $  followed by the end of the line.
$0        Replace the match with itself...
  ;       followed by a semicolon.

```

# Answer
> 2 votes
# Perl, ~~19~~ ~~15~~ 14 bytes

```
s/[^;]$/$&;/

```

Try this fiddle online or this test suite.

Must be run with the `-pl` flags; this is accounted for in the score.

Thanks to @manatwork for -4 bytes.

# Answer
> 0 votes
## JavaScript ES6, 69 bytes

```
alert(prompt().split`\\n`.map(x=>x.match(/;$|^$/g)?x:x+';').join`\n`)
```

In the input, separate the newlines by `\n`, e.g. `some;\ncode\nthere`

---
Tags: code-golf
---


title: Numerology Calculator

text:
# Question
Title: Numerology Calculator
The goal of this challenge is to compute *one kind of* numerology digit from strings containing characters and numbers.

* The input may be through any convenient method (standard input, arguments, separated file).
* The input may contain any printable ASCII chars, but only alphanumerical (`A-Z`, `a-z`, and `0-9`) have to be considered.
* The output must be a digit between `1` and `9` or a star `*` if no letter and no digit where found... (or even `0` if input contain any number of `0` *and* nothing else but this doesn't matter).
* Letter values are mapped in this way:

```
1  2  3  4  5  6  7  8  9
a  b  c  d  e  f  g  h  i
j  k  l  m  n  o  p  q  r
s  t  u  v  w  x  y  z

```
* The *numerology digit* is computed by adding each value of string, then repeat until there is only one digit. Sample for `13579`, `Hello, world!`, `00 0 00`, `!@#$%^&*();`,  and `3.141592`:

```
13579 => 1 + 3 + 5 + 7 + 9 = 25 => 2 + 5 = 7
Hello, world! => 8 + 5 + 3 + 3 + 6 + 5 + 6 + 9 + 3 + 4 = 52 => 5 + 2 = 7
00 0 00 => 0 + 0 + 0 + 0 + 0 = 0
!@#$%^&*(); => *
  => *
3.141592 => 3 + 1 + 4 + 1 + 5 + 9 + 2 = 25 => 2 + 5 = 7
3.1415926535897932384 =>
 3 + 1 + 4 + 1 + 5 + 9 + 2 + 6 + 5 + 3 + 5 + 8 + 9 + 7 + 9 + 3 + 2 + 3 + 8 + 4
 = 97 => 9 + 7 = 16 => 1 + 6 = 7

```

(This is great, most of this samples give `7`! But it's just sample ;)

Some more tests:

```
Bob  => 2 + 6 + 2 = 10 => 1 + 0 = 1
Charlie => 3 + 8 + 1 + 9 + 3 + 9 + 5 = 38 => 3 + 8 = 11 => 1 + 1 = 2
Anna => 1 + 5 + 5 + 1 = 12 => 1 + 2 = 3
Fana => 6 + 1 + 5 + 1 = 13 => 1 + 3 = 4
Gregory => 7 + 9 + 5 + 7 + 6 + 9 + 7 = 50 => 5 + 0 = 5
Denis => 4 + 5 + 5 + 9 + 1 = 24 => 2 + 4 = 6
Erik => 5 + 9 + 9 + 2 = 25 => 2 + 5 = 7
Helen => 8 + 5 + 3 + 5 + 5 = 26 => 2 + 6 = 8
Izis => 9 + 8 + 9 + 1 = 27 => 2 + 7 = 9

```

This is a , so the shortest answer in bytes wins.

### Shortest by language

```
<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><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="language-list"> <h2>Shortest Solution 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> <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> <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><script>var QUESTION_ID = document.referrer.split("/")[4]; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 0; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "//api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "//api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(42), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>
```

# Answer
# Matlab, 121 bytes

```
s=[input('','s'),'*'];while nnz(s)>1;s=num2str(sum(mod([s(48<s&s<58)-4,s(96<s&s<123)+2,s(64<s&s<91)-2],9)+1));end;disp(s)

```

Matlab is just not made for strings =(
> 6 votes

# Answer
## Mathematica, ~~174~~ ~~168~~ 163 bytes

```
Catch[#-9Floor[Max[#-1,1]/9]&@If[(a=Tr[Characters@#/.{(b=a_String)?DigitQ:>FromDigits@a,b?LetterQ:>LetterNumber@a~Mod~9,b->0}])<1&&#~StringFreeQ~"0",Throw@"*",a]]&

```

Does the first step, then computes the digital root.
> 3 votes

# Answer
# Ruby, ~~97~~ 74 characters

```
n=->s{(t=eval s.tr('a-z9A-Z','1-9'*6).scan(/\d/)*?+)&&t>9?n[t.to_s]:t||?*}

```

Sample run:

```
2.1.5 :001 > n=->s{(t=eval s.tr('a-z9A-Z','1-9'*6).scan(/\d/)*?+)&&t>9?n[t.to_s]:t||?*}
 => #<Proc:0x00000001b4b3f0@(irb):4 (lambda)>

2.1.5 :002 > puts ['13579', 'Hello, world!', '00 0 00', '!@#$%^&*();', ' ', '3.141592', '3.1415926535897932384', 'Bob', 'Charlie', 'Anna', 'Izis'].map{|s|'%s : %s'%[n[s],s]}
7 : 13579
7 : Hello, world!
0 : 00 0 00
* : !@#$%^&*();
* :
7 : 3.141592
7 : 3.1415926535897932384
1 : Bob
2 : Charlie
3 : Anna
9 : Izis

```
> 3 votes

# Answer
# Perl, ~~91 89 76~~ 74 bytes

73 + 1 for `-p` switch

```
s/[a-z]/(ord($&)%32-1)%9+1/eig;$t="*",s/\d/$t+=$&/eg,$_=$t until/^[*\d]$/

```

Tests

```
for test in '13579' 'Hello, world!' '00 0 00' '!@#$%^&*();' ' ' \
    '3.141592' '3.1415926535897932384' \
    Bob Charlie Anna Fana Gregory Denis Erik Helen Izis ;do
    perl -pe '
      s/[a-z]/(ord($&)%32-1)%9+1/eig;$t="*",s/\d/$t+=$&/eg,$_=$t until/^[*\d]$/
      ' < <(echo -n "$test")
    echo "  $test"
done

```

```
7  13579
7  Hello, world!
0  00 0 00
*  !@#$%^&*();
*
7  3.141592
7  3.1415926535897932384
1  Bob
2  Charlie
3  Anna
4  Fana
5  Gregory
6  Denis
7  Erik
8  Helen
9  Izis

```

Thanks @manatwork for helping me to save **~~2 14 16 15~~ 17** chars!!

... I've thinked about: *`N % 32 + Y` may replace `( N & 31 ) + Y`*!
> 3 votes

# Answer
## ES6, 98 bytes

```
s=>(m=s.match(/[1-9a-z]/gi))?(t=8,m.map(c=>t+=c>'@'?c.charCodeAt()&31:+c),t%9+1):/0/.test(s)?0:'*'

```

Ungolfed:

```
function(s) {
    var m = s.match(/[1-9a-z]/gi);
    if (m) {
        var t = 0;
        for (var i = 0; i < m.length; i++) {
            if (m[i] > '@')
                t += m[i].charCodeAt(0) & 31;
            else
                t += parseInt(m[i]);
        }
        return t % 9 || 9;
    }
    return /0/.test(s) ? 0 : "*";
}

```

94-byte version that only works on short strings:

```
s=>(m=s.match(/[1-9a-z]/gi))?m.map(c=>c>'@'?c.charCodeAt()&31:c).join``%9||9:/0/.test(s)?0:'*'

```

Using `match`, `map` and `join` turned out to be shorter than using `replace` twice:

```
s=>(m=s.replace(/[^1-9a-z]/gi,''))?m.replace(/[a-z]/gi,c=>c.charCodeAt()&31)%9||9:/0/.test(s)?0:'*'

```

Test it here: https://jsbin.com/zizosayisi/edit?js,console
> 3 votes

# Answer
# Gema, 161 characters

```
*=@n{*}
n:\A=@set{t;};<L1>=@set{t;@add{$t;@add{@mod{@sub{@mod{@char-int{$0};32};1};9};1}}};<D1>=@set{t;@add{$t;$0}};?=;\Z=@cmps{$t;;;\*;@cmpn{$t;9;$t;$t;@n{$t}}}

```

(Written only to try whether recursive domain calls work.)

Sample run:

```
bash-4.3$ for input in '13579' 'Hello, world!' '00 0 00' '!@#$%^&*();' ' ' '3.141592' '3.1415926535897932384'; do
>     echo -n "'$input' : "
>     gema '*=@n{*};n:\A=@set{t;};<L1>=@set{t;@add{$t;@add{@mod{@sub{@mod{@char-int{$0};32};1};9};1}}};<D1>=@set{t;@add{$t;$0}};?=;\Z=@cmps{$t;;;\*;@cmpn{$t;9;$t;$t;@n{$t}}}' <<< "$input"
>     echo
> done
'13579' : 7
'Hello, world!' : 7
'00 0 00' : 0
'!@#$%^&*();' : *
' ' : *
'3.141592' : 7
'3.1415926535897932384' : 7

```
> 2 votes

# Answer
# MATL, 64 bytes

```
jk42ht`YUt'[a-z]'XXY}3+w'[1-9]'XXY}6+h,9X\st9>]w2Y24Y2h!=~?x'*']

```

This uses current version (4.0.0) of the language.

I have a feeling that it could be made shorter...

### Test cases

```
>> matl
 > jk42ht`YUt'[a-z]'XXY}3+w'[1-9]'XXY}6+h,9X\st9>]w2Y24Y2h!=~?x'*']
 >
> 13579
7

>> matl
 > jk42ht`YUt'[a-z]'XXY}3+w'[1-9]'XXY}6+h,9X\st9>]w2Y24Y2h!=~?x'*']
 >
> Hello, world!
7

>> matl
 > jk42ht`YUt'[a-z]'XXY}3+w'[1-9]'XXY}6+h,9X\st9>]w2Y24Y2h!=~?x'*']
 >
> 00 0 00
0

>> matl
 > jk42ht`YUt'[a-z]'XXY}3+w'[1-9]'XXY}6+h,9X\st9>]w2Y24Y2h!=~?x'*']
 >
> !@#$%^&*();
*

>> matl
 > jk42ht`YUt'[a-z]'XXY}3+w'[1-9]'XXY}6+h,9X\st9>]w2Y24Y2h!=~?x'*']
 >
> 3.141592
7

>> matl
 > jk42ht`YUt'[a-z]'XXY}3+w'[1-9]'XXY}6+h,9X\st9>]w2Y24Y2h!=~?x'*']
 >
> 3.1415926535897932384
7

>> matl
 > jk42ht`YUt'[a-z]'XXY}3+w'[1-9]'XXY}6+h,9X\st9>]w2Y24Y2h!=~?x'*']
 >
> Bob
1

>> matl
 > jk42ht`YUt'[a-z]'XXY}3+w'[1-9]'XXY}6+h,9X\st9>]w2Y24Y2h!=~?x'*']
 >
> Charlie
2

>> matl
 > jk42ht`YUt'[a-z]'XXY}3+w'[1-9]'XXY}6+h,9X\st9>]w2Y24Y2h!=~?x'*']
 >
> Anna
3

>> matl
 > jk42ht`YUt'[a-z]'XXY}3+w'[1-9]'XXY}6+h,9X\st9>]w2Y24Y2h!=~?x'*']
 >
> Izis
9

```
> 1 votes

# Answer
## JavaScript (ES6), ~~162~~ ~~159~~ 157 bytes

```
f=_=>{for(_=_.replace(/\W+/g,''),g=$=>''+[...$.toUpperCase()].reduce((p,a)=>isNaN(a)?p+(a.charCodeAt()-64)%9:+a+p,0);1<(l=_.length);_=g(_));return!l?'*':g(_)}

```

Still trying to look for a way to use implicit return in the outer function.

### Ungolfed + unminified

```
f = str => {
  str = str.replace(/\W+/g, '');
  recursiveFunc = $ => String([...$.toUpperCase()].reduce(
    (prev, val) => isNaN(val) ? prev + (val.charCodeAt() - 64) % 9 : Number(val) + prev,
    0
  ));
  while (1 < (len = str.length)) {
    str = recursiveFunc(str);
  }
  return len === 0 ? '*' : recursiveFunc(str)
}

```
1. Strips out all non-alphanumeric characters
2. Calls a function recursively to reduce the characters to their respective values while the string is longer than 1 character.
    1. Converts the string to uppercase to easily work with ASCII codes
    2. Convert to array using spread operator and run an accumulator
    3. Use the global `isNaN` function (which casts its input) to check if it's not a number
        * If it isn't, convert to ASCII code and mod 9 to get its respective value
        * If it is a number, cast it
3. If the length is 0, no alphanumeric characters were present (return an asterisk), otherwise return the output of the recursive function.
> 1 votes

# Answer
## Haskell, 126 bytes

```
l x=[n|(c,n)<-zip(['0'..'9']++['a'..'z']++'\0':['A'..'Z'])$0:cycle[1..9],c==x]
g[]="*"
g[x]=show x
g x=f$show$sum x
f=g.(l=<<)

```

Usage: `f "Hello, world!"` -\> `"7"`.

`l` is a lookup table for characters to list of integers (singleton list, if char is found, empty list otherwise). `f` lookups every char of it's argument and flattens the returned list of lists into a simple list of integers and calls `g` to check the end condition (empty list (-\> `*`) or single integer) or to call `f` with the sum of the list for another round.
> 1 votes

# Answer
# Pure bash, ~~199~~ 194 bytes

```
eval a+={a..z};r="$1";while [ "${r:1}" ];do o=;for ((i=0;i<${#r};i++));do
l=${r:i:1};case $l in [a-zA-Z])d=${a%${l,}*};((o+=$((${#d}%9+1))));;[0-9])
((o+=l));;esac;done;r="$o";done;echo "${o:-*}"

```

(second line break is only for avoiding scrollbar)

Test rule:

```
numerology() {
    eval a+={a..z};
    r="$1";
    while [ "${r:1}" ]; do
        o=;
        for ((i=0; i<${#r}; i++))
        do
            l=${r:i:1};
            case $l in
                [a-zA-Z])
                    d=${a%${l,}*};
                    ((o+=$((${#d}%9+1))))
                ;;
                [0-9])
                    ((o+=l))
                ;;
            esac;
        done;
        r="$o";
    done;
    echo "${o:-*}"
}

for test in '13579' 'Hello, world!' '00 0 00' '!@#$%^&*();' ' ' \
            '3.141592' '3.1415926535897932384'\
            Bob Charlie Anna Fana Gregory Denis Erik Helen Izis ;do
    echo "$(numerology "$test")" $test
done

```

```
7 13579
7 Hello, world!
0 00 0 00
* !@#$%^&*();
*
7 3.141592
7 3.1415926535897932384
1 Bob
2 Charlie
3 Anna
4 Fana
5 Gregory
6 Denis
7 Erik
8 Helen
9 Izis

```
> 1 votes

# Answer
## Seriously, 50 bytes

```
,$ù;ú1╤▀+;#pX╗@-@-;Y`'*.`╬X1WX`╜í;s9*@%u`MΣ$;lDWX

```

Hex Dump:

```
2c24973ba331d1df2b3b237058bb402d402d3b5960272a2e7f
60ce5831575860bda13b73392a402575604de4243b6c445758

```

Try It Online

Explained:

```
,$ù                                               Read input, make it a string, lowercase
    ú                                             Push lowercase alphabet
     1╤▀+                                         Prepend base 10 digits.
         ;#pX╗                                    Remove "0" from a copy and stash in reg0
   ;          @-                                  Remove alphanumerics from input copy
                @-                                Remove nonalphanumerics from input
                  ;Y                              Push 1 if string is empty, else 0
                    `'*.`╬                        If top is truthy, output * and halt
                          X                       Discard boolean
                           1                      Push 1 to enter loop
                            WX                 WX Loop while top of stack is truthy
                              `         `M        Map this function over the string
                               ╜                  Push alphanumeric string from reg0
                                í                 Push index of this char in it
                                 ;s9*             Push 9 if found, else -9
                                     @%u          Take index mod previous: this yields the
                                                  correct conversion from the numerology
                                          Σ       Sum the resulting digits.
                                           $      Convert the sum to a string.
                                            ;lD   push 1 less than its length

```
> 1 votes

# Answer
## Pyth, 39 bytes

```
IK@J+jkUTGrz0WtK=K`smh%xtJd9-K\0)K).?\*

```

Try It Online

I'm just doing this because I can't sleep. Maybe I'll explain it tomorrow...
> 1 votes

# Answer
# JavaScript (ES6), 78 ~~83~~

Recursive solution. Being tail recursion, the variables t and r have not to be local.

```
f=x=>(t=r=0,x.replace(/\w/g,d=>t+=1+~-parseInt(d,r=36)%9),t>9?f(''+t):r?t:'*')

```

**Explained**

```
f=x=>(
  t = 0, // set initial value of counter to 0
  r = 0, // flag to verify that we found at last one alphanumeric chars
  x.replace(/\w/g, d => ( // execute the following for each alphanumeric character
    // t += 1 + ~-parseInt(d,r=36) % 9 explained below
    r = 36, // set flag, could be any nonzero value
    d = parseInt(d,36), // convert to numeric. a..z -> 10..25, case insensitive.
    d = 1 + (d-1) % 9, // this is the arithmetic conversion required (
                       // works also with 0 because the strange implementation of % in javascript for negative numbers
    t = t + d // add to global counter
  ) ),
  t > 9 // if t > 9 then we found some alphanumeric char, but we must repeat the loop on t
    ? f(''+t) // recursive call, t is numeric and must become a string
    : r // check flag r
      ? t // if alphanumeric found, return t
      : '*' // else return '*'
)

```

**Test snippet**

```
f=x=>(t=r=0,x.replace(/\w/g,d=>t+=1+~-parseInt(d,r=36)%9),t>9?f(''+t):r?t:'*')

console.log=x=>O.textContent+=x+'\n';

;[['13579',7],['Hello, world!',7],['00 0 00',0],['!@#$%^&*();','*'],
['3.141592',7],['3.1415926535897932384',7],
['Bob', 1],['Charlie', 2],['Anna', 3],['Fana', 4],['Gregory', 5],
['Denis', 6],['Erik', 7],['Helen', 8],['Izis', 9]]
.forEach(t=>{
  i=t[0]+''
  k=t[1]
  r=f(i)
  console.log(i+' -> ' + r + (k==r? ' OK':' Fail - expected '+k))
  })
```

```
<pre id=O></pre>
```
> 1 votes

# Answer
## Mathematica, 133 bytes

```
f[s_]:= ToCharacterCode@ToUpperCase@s-64/.{a_/;17>-a>6:>a+16,b_/;b<1||b>26:>""}//If[Or@@NumberQ/@#,Tr@#/.""->0//.a_:>Tr@IntegerDigits@a,"*"]&

```

A bit different from LegionMammal978's above. My function turns everything into a character code, then filters out the non-alphanumeric things (replacing them with empty strings). If there are no alphanumerics, then it returns \*, otherwise it takes the digital root. This could be significantly (~15B) shorter if I didn't have to deal with the all-zeros-string case. C'est la vie.

Mathematica magic, for the uninitiated: `foo//.a_:>Tr@IntegerDigits@a` is a repeated replacement: it replaces any numbers `a` in foo with the sum of their digits, then it replaces again until it hits a fixed point, i.e. `a` stops changing under replacement.

**Tests:**

```
f /@ {"13579", "Hello,world!", "00 0 00", "!@#$%^&*()", "3.141592","3.1415926535897932384"}
     => {7, 7, 0, "*", 7, 7}
f /@ {"Bob", "Charlie", "Anna", "Fana", "Gregory", "Denis", "Erik",  "Helen", "Izis"}
     => {1, 2, 3, 4, 5, 6, 7, 8, 9}

```
> 0 votes

---
Tags: code-golf
---