title: What's the Binary Time?

text:
# Question
Title: What's the Binary Time?
# What's the Binary Time?

Everybody knows what the normal time is. It's up there in the top-right (or wherever you put it) of your screen. But a question people rarely seem to ask themselves is this: What's the *binary* time?

## Binary Time

Binary Time (True Binary Time) works by first reading the most significant bit (MSB) of the number. If that number is `0`, the time expressed is before noon. If that number is `1`, the time expressed is after noon. The next bit splits the half of the day the first bit expressed into two more equal halves, this time of 6 hours. The following bit splits into 3 hours, the next 90 minutes, and so on. Times like `12:00:00`, where it seems it should be neither, become `1`.

I can only understand this strange system of timing, so I need a program to convert to that for me. But as binary numbers are Base-2, and 2 is a small number, your program must be as short as possible.

## Requirements

* Your program should take a time (as 24-hour-time) as input and output the corresponding binary time number.
* The output number should have 16-bit precision (the number should be 16 digits long).
* You cannot use a builtin that does all of that conversion for you.
* You should floor if it needs to be rounded.

## Rules

## Test Cases

`00:00:00` ==\> `0000000000000000`
`12:00:00` ==\> `1000000000000000`
`01:30:00` ==\> `0001000000000000`
`10:33:06` ==\> `0111000010001101`
`09:57:30` ==\> `0110101000111000`
`06:00:00` ==\> `0100000000000000`
`18:00:00` ==\> `1100000000000000`

## Scoring

To win, as I mentioned earlier, you must have the least bytes.

## Submissions

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

```

## Leaderboard

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

```
/* Configuration */

var QUESTION_ID = 81057; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 53406; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://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 "https://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,]*[^\s,]),.*?(\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,
      });

  });

  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;
    if (/<a/.test(lang)) lang = jQuery(lang).text();

    languages[lang] = languages[lang] || {lang: a.language, 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 > b.lang) return 1;
    if (a.lang < b.lang) 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);
  }

}
```

```
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;
}
```

```
<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
> 1 votes
# MATL, 15 bytes

```
YOtk-KWW*k16&YB

```

Uses a builtin for converting a string representing time to a serial date/time number, which is allowed by the challenge.

**Try it online!**

### Explanation

```
YO       % Input time string. Convert to serial date/time. Time is fractional part
tk-      % Duplicate, round down, subtract. This keeps fractional part only
KWW      % 34, 2 raised to, 2 raised to (`16W` would require an extra space)
*        % Multiply
k        % Round down
16&YB    % Convert to binary string with 16 digits. Display

```

# Answer
> 5 votes
## CJam, 20 bytes

```
l':/60b9m<675/2bG0e[

```

Test suite.

### Explanation

Makes use of the fact that 65536 (216) over 86400 (the number of seconds in a day) simplifies to 512 over 675.

```
l     e# Read input.
':/   e# Split around ':', so we get ["hh" "mm" "ss"].
60b   e# Interpret as base-60 digits, which computes hh*60^2 + mm*60 + ss,
      e# i.e. it computes the total number of seconds. Note that this implicitly
      e# converts all three strings to integers.
9m<   e# Bitwise left-shift by 9 positions, which is the same as multiplying by
      e# 2^9 = 512.
675/  e# Divide by 675, flooring the result.
2b    e# Convert to binary.
G0e[  e# Left-pad with zeros to 16 digits.

```

# Answer
> 3 votes
# Pyth, ~~31~~ 27 bytes

```
.[\016.Bs*512cisMcQ\:60 675

```

Test suite.

Converts the input into number of seconds passed, multiply by a factor of `2^16 / 24*60*60`, and then floor and convert to 16-bit binary.

Saved 4 bytes by simplifying `65536/86400` into `512/675` (stupid me).

## Input/output

```
00:00:00    0000000000000000
11:00:00    0111010101010101
12:00:00    1000000000000000
01:30:00    0001000000000000
10:33:06    0111000010001101
09:57:30    0110101000111000
06:00:00    0100000000000000
18:00:00    1100000000000000
23:59:59    1111111111111111

```

# Answer
> 3 votes
# TSQL(sqlserver 2012), 103 bytes

```
DECLARE @d datetime = '10:33:06'

DECLARE @ char(16)='',@x INT=cast(@d as real)*131072WHILE
len(@)<16SELECT @x/=2,@=concat(@x%2,@)PRINT @

```

Try it online

Ungolfed

```
DECLARE @d datetime = '10:33:06'

DECLARE @ char(16)='',
        @x INT=cast(@d as real)*131072
WHILE len(@)<16
SELECT @x/=2,@=concat(@x%2,@)
PRINT @

```

# TSQL(sqlserver 2012), ~~119~~ 106 bytes

Also included a different version without the variable @x, however it was a few bytes longer. Including the ungolfed version for those interested:

```
DECLARE @d datetime = '23:59:59'

DECLARE @ varchar(16) =''
WHILE LEN(@)<16
SET @+=LEFT(CAST(@d as decimal(9,9))*2*POWER(2,LEN(@))%2,1)
PRINT @

```

# Answer
> 2 votes
# JavaScript (ES6), 72 ~~76~~ bytes

**Edit** 4 bytes save thx @Neil

~~Still unclear about the rounding.~~ This one truncates and that's ok.

```
t=>(t.split`:`.map(v=>t=+v+60*~~t),t*512/675|65536).toString(2).slice(1)

```

**Test**

```
f=t=>(t.split`:`.map(v=>t=+v+60*~~t),t*512/675|65536).toString(2).slice(1)

function test() {
  var v=I.value
  R.textContent=f(v)
}

test()

;`00:00:00 ==> 0000000000000000
12:00:00 ==> 1000000000000000
01:30:00 ==> 0001000000000000
10:33:06 ==> 0111000010001101
09:57:30 ==> 0110101000111000
06:00:00 ==> 0100000000000000
18:00:00 ==> 1100000000000000`
.split('\n').forEach(t=>{
  [i,k]=t.split(' ==> ')
  r=f(i)
  ok=r==k
  O.textContent += (ok ? 'OK ':'KO ')+ i + ' -> ' + r + (ok? '\n' : ' Expected '+k+'\n')
})
```

```
<input id=I value='12:34:56' oninput=test()>
<span id=R></span>
<pre id=O></pre>
```

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

The rules have now been clarified.

Prompts for time as 3-element list.

```
(16/2)⊤⌊512×675÷⍨60⊥⎕

```

Edit: Updated () to match new result for 10:33:06.

Try it online!

prompt for input

`60⊥` evaluate in base-60

`675÷⍨` divide by 675

`512×` multiply by 512

floor

`(``)⊤` convert to (mnemonic: upside-down base is anti-base) the following number system:

`16/2` replicate 2 sixteen times (i.e. 16-bit binary)

# Answer
> 0 votes
## Q, 32 Bytes

```
48_0b\:_(512%675)*60/:"I"$":"\:

```

**Test**

```
   t "00:00:00"
0000000000000000b
   t "12:00:00"
1000000000000000b
   t "01:30:00"
0001000000000000b
   t "10:33:06"
0111000010001101b
   t "09:57:30"
0110101000111000b
   t "06:00:00"
0100000000000000b
   t "18:00:00"
1100000000000000b

```
* In order to reduce display cluttering, i assume a slight modification to the original expression, that gives name `t` to the lambda
* b suffix indicates binary

**Explanation**

NOTE.- read left to right, evaluates right to left

Reads as: 48 drop from binary representation of floor of 512 divideb by 675 and multiplied by 60 scalarFromVector over integer cast from splits at ":" original string

Evaluation:

`":"\:x` splits string x (implicit arg of the lambda) at ":" character (Q uses "" to denote char)

`"I"$x` cast string(s) x to int(s) -\> hours, minutes, seconds

`60/:x` uses base 60 to calculate a single value from a sequence of ints -\> seconds total

`(512%675)*x` calculates ratio `512%675` (% is divide) and multiplies seconds. 512%675 is the simplified form of the fraction (totalSecondsPerDay%64K)

`_ x` indicates floor of float x

`0b\:x` calculates binary representation of x (64 bits)

`48_ x` drop first 48 bits, so we have our 16 bits representation

Example (x="01:30:00"). NOTE.- "/" indicates comment to end of line

`":"\:"01:30:00" /-> ("01";"30";"00")
"I"$ /-> 1 30 0
60/: /-> 5400
(512%675)* /-> 4096.0
_ /-> 4096
0b\: /-> 0000000000000000000000000000000000000000000000000001000000000000b
48_ /-> 0001000000000000b`

# Answer
> 0 votes
# PHP, ~~47~~ ~~46~~ 43 bytes

Uses IBM-850 encoding.

```
printf(~┌Ø,strtotime($argn.UTC,0)*512/675);

```

Run like this:

```
echo "18:00:00" | php -nR 'printf(~┌Ø,strtotime($argn.UTC,0)*512/675);';echo

```

# Tweaks

* Saved a byte by using IBM-850 encoding.
* Saved 3 bytes by using `$argn`

# Answer
> 0 votes
# Ruby, 75 bytes

```
h,m,s=t.split(':').map &:to_i;((h*3600+m*60+s<<9)/675).to_s(2).rjust 16,'0'

```

I feel like there must be a shorter method of converting the time to seconds, but this is all I could think of.

# Answer
> 0 votes
# Python, 45 bytes

```
lambda h,m,s:bin((s+m*60+h*3600)*512/675)[2:]

```

Came up with the `512/675` factor myself, then saw others did it the same.

# Answer
> 0 votes
# C, 91 bytes

```
f(h,m,s,n,i){i=0;n=(s+m*60+h*3600)*512/675;while(i<16)printf((n&32768)?"1":"0"),n<<=1,i++;}

```

---
Tags: code-golf, number, date, binary
---


title: monthconcatenation

text:
# Question
Title: monthconcatenation
The goal is to output the number of the months given as input in a compact concatenated form which is still parsable if one knows the construction rules:

If either:

* January is followed by January, February, November or December; or
* November is followed by January or February

There must be a separator placed between.
Otherwise there should be no separator.

As such the output may be parsed. For example:

* **March, April and September** -\> `349`
* **January, January and February** -\> `1-1-2`
* **January, January and December** -\> `1-1-12`
* **January, November and February** -\> `1-11-2`
* **November, January and February** -\> `11-1-2`
* **November and December** -\> `1112`

Thus any run of ones is either a run of Novembers, a run of Novembers followed by a December, a run of Novembers followed by an October, or a January followed by an October. This may be parsed by looking to the right of such runs as the resulting string is read from left to right.

# Input

A list of months numbers (`[1-12]`) in any format you want (list, JSON, separated by one or more characters, entered one by one by user, …).

the same month can be present more than once.

# Output

The compact concatenated form described above. If a separator is needed, you can freely choose one.

Output examples for **January, February and March (1-2-3)**:

* `1-23` (chosen for the test cases below)
* `1 23`
* `1/23`
* `1,23`
* ...

# Test cases

```
[1]       => 1
[1, 2]    => 1-2
[2, 1]    => 21
[12]      => 12
[1, 11]   => 1-11
[11, 1]   => 11-1
[1, 1, 1] => 1-1-1
[2, 11]   => 211
[11, 2]   => 11-2
[1, 2, 3] => 1-23
[11, 11]  => 1111
[1,1,11,1,12,1,11,11,12]     => 1-1-11-1-121-111112
[10,11,12,11,11,10,1,10,1,1] => 1011121111101101-1
[2,12,12,2,1,12,12,1,1,2,12,12,2,11,2,12,1] => 2121221-12121-1-21212211-2121

```

# Rules

# Answer
> 1 votes
# Python 2.7 96 bytes

## Try it out here!

### Huge thanks to Jonathan Allan for shortening the answer.

### golfed:

```
b,o=input(),""
for a,n in zip(b,b[1:]):o+=`a`+"-"*(a%10==1and a+n in(2,3,12,13))
print o+`b[-1]`

```

### Explanation:

runs through the input, checks if the current item is a special case and if so handles it, otherwise just concatenates the input, prints the output string.

### ungolfed:

```
input = [2,12,12,2,1,12,12,1,1,2,12,12,2,11,2,12,1]
output = ""
for i in range(len(input) - 1):
    next = input[i + 1]
    item = input[i]
    if item == 1 and (next == 1 or next == 2 or next == 11 or next == 12) or item == 11 and (next == 1 or next == 2):
        output += str(item) + "-"
    else:
        output += str(item)

output += str(input[-1])

print output

```

# Answer
> 1 votes
# Jelly, 20 bytes

```
%⁵=1a+e“£¤€Æ‘⁶ẋ⁸,⁹µ/

```

**TryItOnline!** or run all test cases

### How?

```
%⁵=1a+e“£¤€Æ‘⁶ẋ⁸,⁹µ/ - Main link: the list
                   / - reduce
                  µ  - monadic chain separation
%⁵                   - left item mod 10
  =1                 - equal to 1? (Jan or Nov)
    a                - and
     +               - left item plus right item
      e              - is in
       “£¤€Æ‘        - jelly code page index list:  [2,3,12,13]
                           now True (1) for any of:
                               [1,1], [1,2], [1,11], [1,12], [11,1], or [11,2]
             ⁶       - literal space (the separator being used)
              ẋ      - repeated that many times
               ⁸     - left argument
                ,    - pair
                 ⁹   - right argument

```

---
Tags: code-golf
---


title: Chained Binary Operations

text:
# Question
Title: Chained Binary Operations
# Chained Binary Operations

Here's a challenge involving truth tables and binary operations. For this specific challenge, your task is to use the following table of operations:

To create a function that takes in two inputs `f(p,a)`, where `p` is the initial truthy/falsy value and `a` is a list of tuples representing multiple values of `q` and the operations to be performed. For instance, `f(T,[[T,0],[T,1]])` would return `ContradictionOP(T,T)=F`. You would then chain the output of this result into the next operation, which would be `LogicalNOR(F,T)=F`, where the 2nd `p` is the previous output of `F`. The final result being `false`. A better breakdown of what each operation actually is is described below:

The first part should be rather simplistic in nature, as the operators are arranged in an increasing binary pattern (hint, hint). However, recursing through the additional inputs to chain binary operations is probably the harder part to accomplish.

# Examples:

```
f(T,[])=T
f(F,[[F,15]])=T
f(T,[[F,15],[T,0],[F,6]])=F
f(T,[[F,15],[F,14],[F,13],[F,12],[F,11]])=F

```

# Extrapolated Example:

```
f(T,[[F,15],[F,14],[F,13],[F,12],[F,11]])=F
[T,[F,15]]=T*
[T*,[F,14]=T*
[T*,[F,13]=T*
[T*,[F,12]=T*
[T*,[F,11]=F
FALSE.

```

# Rules:

* You MUST use the order specified for the operations as stated above.
* The input format for `a` can be a 2D array, array of tuples, command line pairwise arguments or any other representation of pairs of boolean/operations. Could even be a single array that you parse pairwise.
* You may use `0` for `false` and `1` for `true`, it is **not** acceptable to reverse the two.
* The output should be simply a truthy or falsy value.
* No loopholes, this is code-golf, standard CG rules apply.

**Example Single Iteration Algorithm:**

```
f={
    p,q,o->
    op=Integer.toBinaryString(o);     // Calculate the binary OP string (15=1111)
    binaryIndex="$p$q"                // Calculate binary combination of p/q (T/F=10)
    i=Integer.parseInt(binaryIndex,2) // Convert to decimal index (T/F=2)
    op.charAt(i)                      // Get the binary char at the calculated index (T/F/15=1).
}
f(1,0,15)                             // "1"

```

# Answer
## CJam (15 bytes)

```
{{+)2@2b#/1&}/}

```

Online demo. This is an anonymous block (function) which takes the two values on the stack and leaves the result on the stack.

### Dissection

```
{         e# Define a block:
  {       e#   For each pair in the array...
    +)2@  e#     Prepend the accumulator, pop the op, push a 2, and rot 3
          e#     Stack is now: op 2 [accum arg]
    2b#   e#     Find 2**(2*accum + arg)
    /1&   e#     Test the corresponding bit of op, setting it as the new accum
  }/
}

```
> 1 votes

# Answer
## JavaScript (ES6), 34 bytes

```
a=>a.reduce((l,[r,o])=>o>>l+l+r&1)

```

Accepts true/false but prefers 1/0 format.
> 3 votes

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


title: Ghosts and Pumpkins

text:
# Question
Title: Ghosts and Pumpkins
Here's an ASCII pumpkin carved into a Jack-o-Lantern. Isn't it cute?

```
((^v^))

```

Here's an ASCII ghost. Look how spooky it is!

```
\{O.O}/

```

Obviously, the pumpkins have to be on the ground, with a space between them so they don't rot.

Ghosts, however, like to stand on top of pumpkins, so they're *even spookier*. However, they have to stand on *two* pumpkins, else their ghostly weight will crush the pumpkin beneath them. But, due to how their ghostly *magic* works, multiple ghosts can stack and share pumpkins, provided that the ghosts are either split evenly on the lower pumpkins or the lower ghosts. In other words, forming a shape like a human pyramid. Note that ghosts can't stack on ghosts unless there's a pumpkin underneath (that's how the magic works).

Given two non-negative integers, `g` and `p`, representing the number of `g`hosts and `p`umpkins, output the most-compact left-most formation possible, following the above pyramid stacking rules. Leftover pumpkins and ghosts (that is, those not forming the pyramid) go on the ground to the right.

For clarification, these formations are OK (blank newline separated), and serve as example I/O:

```
0p 1g
\{O.O}/

1p 0g
((^v^))

1p 1g
((^v^)) \{O.O}/

2p 1g
    \{O.O}/
((^v^)) ((^v^))

2p 2g
    \{O.O}/
((^v^)) ((^v^)) \{O.O}/

3p 1g
    \{O.O}/
((^v^)) ((^v^)) ((^v^))

3p 2g
    \{O.O}/ \{O.O}/
((^v^)) ((^v^)) ((^v^))

3p 3g
        \{O.O}/
    \{O.O}/ \{O.O}/
((^v^)) ((^v^)) ((^v^))

0p 4g
\{O.O}/ \{O.O}/ \{O.O}/ \{O.O}/

3p 0g
((^v^)) ((^v^)) ((^v^))

7p 6g
            \{O.O}/
        \{O.O}/ \{O.O}/
    \{O.O}/ \{O.O}/ \{O.O}/
((^v^)) ((^v^)) ((^v^)) ((^v^)) ((^v^)) ((^v^)) ((^v^))

```

These formations are Not OK

```
\{O.O}/
((^v^))

    \{O.O}/
((^v^))

((^v^)) ((^v^)) \{O.O}/

    \{O.O}/
    \{O.O}/
((^v^)) ((^v^))

            \{O.O}/
\{O.O}/ ((^v^)) ((^v^))

    ((^v^))
((^v^)) ((^v^))

      \{O.O}/
((^v^)) ((^v^))

```

### Input

Two non-negative integers in any convenient format. At least one of the numbers will be non-zero. You can take the inputs in either order (i.e., in the examples I had pumpkins first) -- please specify how you take input in your answer.

### Output

An ASCII-art representation of the ghosts and pumpkins, following the above rules. Leading/trailing newlines or other whitespace are optional, provided that the ghosts and pumpkins line up appropriately.

### Rules

* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
## JavaScript (ES7), ~~166~~ ~~164~~ 159 bytes

*Saved 5 bytes thanks to Neil*

```
f=(p,g,j=(g*2)**.5+.5|0,G=j>p-1?p?p-1:0:j,P=`
`,i=~j?g-G*++G/2:G,n=i>0?i>g?g:i:0)=>p|g?f(0,g-n,-1,G-1,P+'    ')+P+'((^v^)) '.repeat(p)+'\\{O.O}/ '.repeat(n):''

```

### Formatted and commented

```
f = (                                    // given:
  p,                                     // - p = number of pumpkins
  g,                                     // - g = number of ghosts
  j = (g * 2) ** .5 + .5 | 0,            // - j = ceil(triangular root of g)
  G = j > p - 1 ? p ? p - 1 : 0 : j,     // - G = max(0, min(p - 1, j))
  P = '\n',                              // - P = padding string (+ line-break)
  i = ~j ?                               // - i =
    g - G * ++G / 2                      //   first iteration: g - G * (G + 1) / 2
  : G,                                   //   next iterations: G
  n = i > 0 ? i > g ? g : i : 0          // - n = max(0, min(i, g)) = number of
) =>                                     //   ghosts to print at this iteration
p | g ?                                  // if there's still something to print:
  f(                                     //   do a recursive call with:
    0,                                   //   - no pumpkin anymore
    g - n,                               //   - the updated number of ghosts
    -1,                                  //   - j = -1 (so that ~j == 0)
    G - 1,                               //   - one less ghost on the pyramid row
    P + '    '                           //   - updated padding string
  ) +                                    //
  P +                                    //   append padding string
  '((^v^)) '.repeat(p) +                 //   append pumpkins
  '\\{O.O}/ '.repeat(n)                  //   append ghosts
: ''                                     // else: stop

```

### Underlying math

The tricky part is to find out the optimal width `G` of the ghost pyramid.

The number of ghosts `g` in such a pyramid is given by:

```
g = 1 + 2 + 3 + ... + G = G(G + 1) / 2

```

Reciprocally, the width of a pyramid containing `g` ghosts is the real root of the resulting quadratic equation:

```
G² + G - 2g = 0

Δ = 1² - 4(-2g)
Δ = 8g + 1

G = (-1 ± √Δ) / 2

```

Which leads to the following real root (also known as the *triangular root*):

```
G = (√(8g + 1) - 1) / 2

```

However, the width of the pyramid is also limited by the number of pumpkins: we can have no more than `p-1` ghosts over `p` pumpkins. Hence the final formula used in the code:

```
j = ⌈(√(8g + 1) - 1) / 2⌉
G = max(0, min(p - 1, j))

```

### ES6 version, ~~173~~ ~~171~~ 166 bytes

```
f=(p,g,j=Math.pow(g*2,.5)+.5|0,G=j>p-1?p?p-1:0:j,P=`
`,i=~j?g-G*++G/2:G,n=i>0?i>g?g:i:0)=>p|g?f(0,g-n,-1,G-1,P+'    ')+P+'((^v^)) '.repeat(p)+'\\{O.O}/ '.repeat(n):''

```

### Test cases (ES6)

```
f=(p,g,j=Math.pow(g*2,.5)+.5|0,G=j>p-1?p?p-1:0:j,P=`
`,i=~j?g-G*++G/2:G,n=i>0?i>g?g:i:0)=>p|g?f(0,g-n,-1,G-1,P+'    ')+P+'((^v^)) '.repeat(p)+'\\{O.O}/ '.repeat(n):''

console.log(f(0, 1));
console.log(f(1, 0));
console.log(f(1, 1));
console.log(f(2, 1));
console.log(f(2, 2));
console.log(f(3, 1));
console.log(f(3, 2));
console.log(f(3, 3));
console.log(f(0, 4));
console.log(f(3, 0));
console.log(f(7, 6));
```
> 5 votes

# Answer
# Perl, 246 bytes (newlines are not part of the code and are provided solely for readability)

```
($c,$d)=<>=~/(\d+)/g;
$p="((^v^)) ";$g="\\{O.O}/ ";
for($f[0]=$c;$d>0;$d--){$f[$b+1]+1<$f[$b]?$f[++$b]++:$f[$b]++;$f[0]+=$d,$d=0 if$b==$c-1;$f[$b]==1?$b=0:1}
$h[0]=($p x$c).$g x($f[0]-$c);$h[$_].=$"x(4*$_).$g x$f[$_]for(1..$#f);
say join$/,reverse@h;

```

Accepts two numbers: pumpkins first, followed by ghosts. Sample input:

```
5 20

```

Sample output:

```
                \{O.O}/
            \{O.O}/ \{O.O}/
        \{O.O}/ \{O.O}/ \{O.O}/
    \{O.O}/ \{O.O}/ \{O.O}/ \{O.O}/
((^v^)) ((^v^)) ((^v^)) ((^v^)) ((^v^)) \{O.O}/ \{O.O}/ \{O.O}/ \{O.O}/ \{O.O}/ \{O.O}/ \{O.O}/ \{O.O}/ \{O.O}/ \{O.O}/ \{O.O}/

```
> 3 votes

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


title: Superstitious Programming

text:
# Question
Title: Superstitious Programming
Your challenge is extremely simple. Given a year as input, print all the months in that year that will contain a Friday the 13th according to the Gregorian calendar. Note that even though the Gregorian Calendar wasn't introduced until 1582, for simplicity's sake we will pretend that it has been in use since 0001 AD.

# Rules

* Full programs or functions are allowed.
* You can take input as function arguments, from STDIN, or as command line arguments.
* You are not allowed to use any date and time builtins.
* You can safely assume that the input will be a valid year. If the input is smaller than 1, not a valid integer, or larger than your languages native number type, you do not have to handle this, and you get undefined behaviour.
* Output can be numbers, in English, or in any other human readable format, so long as you specify the standard.
* Make sure you account for leap-years. And remember, leap-years do not happen every 4 years!

# Tips

Since there are so many different ways to go about this, I don't want to tell you how to do it. However, it might be confusing where to start, so here are a couple different reliable ways of determining the day of the week from a date.

# Sample IO

```
2016 --> May
0001 --> 4, 7
1997 --> Jun
1337 --> 09, 12
123456789 --> January, October

```

As usual, this is code-golf, so standard-loopholes apply, and shortest answer wins.

```
var QUESTION_ID=69510,OVERRIDE_USER=31716;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
> 1 votes
# Pyth, 73 Bytes

```
L?>b2QtQfq%+++13+/-*2.6?qT2 12%-T2 12 .2 1*5%yT4*4%yT100*6%yT400 7 5r1 13

```

Try it online!

Using the Gauss-Algorithm, like in my Python answer. ~55 bytes of the code are for the weekday calculation, so choosing a better algorithm could get this down by a lot I suppose...but hey, at least its working now! :)

# Answer
> 2 votes
# Python 2, ~~157~~ ~~144~~ 136 Bytes

My solution uses the Gauss-Algorithm. Input is the year as Integer. Output is the list of months with a friday 13th as numbers (1-12). Probably some more golfing possible, but its getting late... Gonna edit this one tomorrow und get this down a bit more. Suggestions are always welcome in the meantime!

```
def f(i):y=lambda m:(i-1,i)[m>2];print[m for m in range(1,13)if(13+int(2.6*((m-2)%12,12)[m==2]-.2)+y(m)%4*5+y(m)%100*4+y(m)%400*6)%7==5]

```

**edit:** Got it down to 144 by replacing the for-loop with a list comprehesion und making some other small adjustments.

**edit2:** Golfed it down to 136 with the suggestions from Morgan Thrapp and fixed the bug he discovered. Thanks a lot! :)

# Answer
> 2 votes
# C - ~~164~~ ~~153~~ 112 bytes

I found a nice little solution using a heavily modified version of Schwerdtfeger's method. It encodes the necessary table in an integer using base 7, modified to fit in a signed 32-bit word. It outputs the month as an ASCII-character, with January encoded as `1`, February as `2` and so on, with October encoded as `:`, November encoded as `;` and December encoded as `<`.

```
t=1496603958,m;main(y){for(scanf("%d",&y),y--;(y%100+y%100/4+y/100%4*5+t+5)%7||putchar(m+49),t;t/=7)2-++m||y++;}

```

Here it is slightly ungolfed:

```
t=1496603958,m;
main(y){
  for(
    scanf("%d",&y),y--;
    (y%100+y%100/4+y/100%4*5+t+5)%7||putchar(m+49),t;
    t/=7
  )
    2-++m||y++;
}

```

I am sure there are a few ways to make it even smaller, but I think the algorithm, or a slight variation thereof, is nearly ideal for finding the months where Friday the 13th occurs (with respect to code size). Notes:

1. If a 64-bit word could have been used it would be possible to get rid of an annoying addition (`+5`).
2. The variable `m` isn't actually necessary, since the month we are looking at is deducible from `t`.

I leave my older answer below, seeing as it uses a completely different method not seen in other answers here.

---

This is based on a solution to a related problem (https://codegolf.stackexchange.com/a/22531/7682).

```
Y,M,D,d;main(y){for(scanf("%d",&y);Y<=y;++D>28+(M^2?M+(M>7)&1^2:!(Y&3)&&(Y%25||!(Y&15)))&&(D=1,M=M%12+1)<2&&Y++)(d=++d%7)^1||D^13||y^Y||printf("%d,",M);}

```

It basically simulates the Gregorian calendar, advancing one day at a time, printing the month when it is a Friday and the 13th. Here it is in a slightly more readable form:

```
Y,M,D,d;
main(y){
  for(
    scanf("%d",&y);
    Y<=y;
    ++D>28+(
      M^2
        ?M+(M>7)&1^2
        :!(Y&3)&&(Y%25||!(Y&15))
    )&&(
      D=1,
      M=M%12+1
    )<2&&Y++
  )
    (d=++d%7)^1||D^13||y^Y||
      printf("%d,",M);
}

```

# Answer
> 1 votes
# Perl - ~~141~~ ~~107~~ 103 bytes

```
$y=<>-1;map{$y++if++$i==3;print"$i "if($y+int($y/4)-int($y/100)+int($y/400))%7==$_}'634163152042'=~/./g

```

This uses a modified version of the formula for the Julian day to calculate the day of the week of March 13th, then uses the number of days of the week each month is offset from January to find the day of the week for the rest of the months, starting with the last 2 months of the previous year beginning in March then the first 10 months of the current year (to avoid calculating leap years twice).

# Answer
> 0 votes
# Excel, 137 bytes

Takes input year in A1. Output is non-separated list of Hexidecimal. (January = 0, December = B)

Uses Gauss's Algorithm for January and August.

```
=CHOOSE(MOD(6+5*MOD(A1-1,4)+4*MOD(A1-1,400),7)+1,"","",1,"","",0,"")&CHOOSE(MOD(5*MOD(A1-1,4)+4*MOD(A1-1,400),7)+1,9,35,"8B",5,"2A",7,4)

```

# Answer
> 0 votes
**C,  ~~276~~  219 bytes**

```
#define R return
#define L(i) for(;i-->0;)
u(y,m){R m-1?30+((2773>>m)&1):28+(y%4==0&&y%100||y%400==0);}s(y,m,g){g+=4;L(m)g+=u(y,m),g%=7;L(y)g+=1+u(y,1),g%=7;R g;}z(y,m,r){m=12;L(m)s(y,m,13)-4||(r|=1<<(m+1));R r;}

```

input from stdin output in stdout try to http://ideone.com/XtuhGj \[the debug function is z\]

```
w(y,m,r){m=12;L(m)s(y,m,u(y,m))||(r|=1<<(m+1));R r;}
/*
// ritorna il numero dei giorni di anno=y mese=m con mese in 0..11
// m==1 significa febbraio   y%4?0:y%100?1:!(y%400) non funziona
u(y,m){R m-1?30+((2773>>m)&1):28+(y%4==0&&y%100||y%400==0);}

// argomenti anno:y[0..0xFFFFFFF]  mese:m[0..11]  giorno:g[1..u(y,m)]
// ritorna il numero del giorno[0..6]
s(y,m,g)
{g+=4; // correzione per il giorno di partenza anno mese giorno = 0,1,1
 L(m)g+=  u(y,m),g%=7; // m:0..m-1  somma mod 7 i giorni del mese dell'anno y
 L(y)g+=1+u(y,1),g%=7; // y:0..y-1  somma mod 7 gli anni da 0..y-1
                       // g+=1+u(y,1) poiche' (365-28)%7=1 e 1 e' febbraio
 R g;
}

// argomenti anno:y[0..0xFFFFFFF], m=0 r=0
// calcola tutti gli ultimi giorni del mese dell'anno y che cadono di lunedi'
// e mette tali mesi come bit, dal bit 1 al bit 12 [il bit 0 sempre 0] in r
w(y,m,r){m=12;L(m)s(y,m,u(y,m))||(r|=1<<(m+1));R r;}

// argomenti anno:y[0..0xFFFFFFF], m=0 r=0
//ritorna in r il numero dei mesi che ha giorno 13 di venerdi[==4]
// e mette tali mesi come bit, dal bit 1 al bit 12 [il bit 0 sempre 0] in r
z(y,m,r){m=12;L(m)s(y,m,13)-4||(r|=1<<(m+1));R r;}
*/

#define P printf
#define W while
#define M main
#define F for
#define U unsigned
#define N int
#define B break
#define I if
#define J(a,b)  if(a)goto b
#define G goto
#define P printf
#define D double
#define C unsigned char
#define A getchar()
#define O putchar
#define Y malloc
#define Z free
#define S sizeof
#define T struct
#define E else
#define Q static
#define X continue
M()
{N y,m,g,r,arr[]={1,297,1776,2000,2016,3385}, arr1[]={2016,1,1997,1337,123456789};
 C*mese[]={"gen","feb","mar","apr","mag","giu","lug","ago","set","ott","nov","dic"};
 C*giorno[]={"Lun","Mar","Mer","Gio","Ven","Sab","Dom"};
 P("Inserisci Anno mese giorno>");r=scanf("%d %d %d", &y, &m, &g);
 P("Inseriti> %d %d %d r=%d\n", y, m, g, r);
 I(r!=3||m>12||m<=0||g>u(y,m-1))R 0;
 r=s(y,m-1,g);// 12-> 11 -> 0..10
 P("Risultato=%d giorno=%s\n", r, giorno[r]);
 r=w(y,0,0);P(" r=%d ", r);P("\n");
 F(m=0;m<6;++m)
        {P("N anno=%d -->",arr[m]);
         r=w(arr[m],0,0); // ritorna in r i mesi tramite i suoi bit...
         F(y=1;y<13;++y) I(r&(1<<y))P("%s ",mese[y-1]);
         P("\n");
        }
 F(m=0;m<4;++m)
        {P("N anno=%d -->",arr1[m]);
         r=z(arr1[m],0,0); // ritorna in r i mesi tramite i suoi bit...
         F(y=1;y<13;++y) I(r&(1<<y))P("%s ",mese[y-1]);
         P("\n");
        }

}

```

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


title: The Switching Sequence

text:
# Question
Title: The Switching Sequence
## Intro

The Switching sequence is defined like so:

Start with `n` people standing in a circle (`6` for this example).

```
 1  2
6    3
 5  4

```

Starting from person `1`, the person that is to the left of the "chosen" person is removed.

```
 1
6    3
 5  4

```

The removed person can "switch" the removal method up:

* If the removed person is even (which it is in this case), the next removed person will be to the right of the next "chosen" person.
* If the removed person is odd, the next removed person will be to the left of the next "chosen" person.

The next chosen person is also dependent on the previously removed person.

* If the removed person is even, the next chosen person will be to the right of the previous chosen person.
* If the removed person is odd, see above, but replace "right" with "left".

So the next chosen person is then `6`.

Now we remove the person to the right of `6`, which is `5`:

```
 1
6    3
    4

```

Because `5` is odd, the removed person is now to the left. The new chosen person is `1`.

We now remove `3`:

```
 1
6
    4

```

We continue this process, until we're left with 1 number - in this example, the final number is `1`. So therefore `S(6) = 1`.

The first few numbers are:

```
 n | S(n)
---------
 1 | 1
 2 | 1
 3 | 3
 4 | 1
 5 | 5
 6 | 1
 7 | 3
 8 | 6
 9 | 5
10 | 6
11 | 9

```

## Task

Your task is to make a program (or a function) that returns `S(n)` (the `n`th number in the Switching sequence) when given `n`, using the least amount of bytes.

Example inputs and outputs:

```
1  -> 1
10 -> 6
13 -> 13

```

You are guaranteed to get a positive integer.

This is , so shortest code in bytes wins!

*Note: There is no OEIS sequence (what?), to save you the trouble of searching.*

# Answer
> 4 votes
# Python 2, ~~183~~ 94 bytes

-4 bytes thanks to Artyer (use `input()` and `print` rather than `def` and `return`)
-1 byte thanks to FlipTack (use `print-~p[0]` rather than `print p[0]+1`)

```
p=range(input())
d=i=1
while p[1:]:m=p.pop(i)%2;i-=m+m-(d<0);d=-m|1;i+=d;i%=len(p)
print-~p[0]

```

**repl.it**

This just follows the instructions given, I've noticed some pattern, maybe it could be exploited?

The only changes are:

* to use `0` based indexing (so even people are odd and vice-versa) - this is saves 5 bytes in the golfed logic and is corrected at the end with `+1`
* to use `1` as left and `-1` as right (to use a range - just like everyone is facing outwards instead)
* to change the logic of the step where the next chosen individual is found to account for `pop`ing from the list making the "pointer" index already step one to the right in the list (or to the left in original terminology).

Ungolfed:

```
def circle(n):
    people = range(n) # p
    direction = 1 # d
    removeIndex = 1 # i
    while n > 1:
        removingMod2 = people.pop(removeIndex) % 2 # m
        removeIndex -= removingMod2 + removingMod2 - (direction == -1)
        direction = -removingMod2 or 1
        removeIndex += direction
        n -= 1
        removeIndex %= n
    return people[0] + 1

```

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


title: Alphabet Pattern Matching

text:
# Question
Title: Alphabet Pattern Matching
We've had a lot of alphabet challenges. For this challenge, **you are passed the *output* of an alphabet challenge, and you need to output the pattern scaled to size `N`**.

For example, if `N=5` and you were passed the L-phabet:

```
ABCDEFGHIJKLMNOPQRSTUVWXYZ
BBCDEFGHIJKLMNOPQRSTUVWXYZ
CCCDEFGHIJKLMNOPQRSTUVWXYZ
DDDDEFGHIJKLMNOPQRSTUVWXYZ
EEEEEFGHIJKLMNOPQRSTUVWXYZ
FFFFFFGHIJKLMNOPQRSTUVWXYZ
GGGGGGGHIJKLMNOPQRSTUVWXYZ
HHHHHHHHIJKLMNOPQRSTUVWXYZ
IIIIIIIIIJKLMNOPQRSTUVWXYZ
JJJJJJJJJJKLMNOPQRSTUVWXYZ
KKKKKKKKKKKLMNOPQRSTUVWXYZ
LLLLLLLLLLLLMNOPQRSTUVWXYZ
MMMMMMMMMMMMMNOPQRSTUVWXYZ
NNNNNNNNNNNNNNOPQRSTUVWXYZ
OOOOOOOOOOOOOOOPQRSTUVWXYZ
PPPPPPPPPPPPPPPPQRSTUVWXYZ
QQQQQQQQQQQQQQQQQRSTUVWXYZ
RRRRRRRRRRRRRRRRRRSTUVWXYZ
SSSSSSSSSSSSSSSSSSSTUVWXYZ
TTTTTTTTTTTTTTTTTTTTUVWXYZ
UUUUUUUUUUUUUUUUUUUUUVWXYZ
VVVVVVVVVVVVVVVVVVVVVVWXYZ
WWWWWWWWWWWWWWWWWWWWWWWXYZ
XXXXXXXXXXXXXXXXXXXXXXXXYZ
YYYYYYYYYYYYYYYYYYYYYYYYYZ
ZZZZZZZZZZZZZZZZZZZZZZZZZZ

```

You would need to output:

```
ABCDE
BBCDE
CCCDE
DDDDE
EEEEE

```

**For the purposes of explanation, I'll be using only `ABCD`, instead of the full alphabet.** You need to be able to match the L-phabet (above), as well as the following patterns:

The single line:

```
ABCD    or     A
               B
               C
               D

```

The single line repeated `N` times

```
ABCD    or    AAAA
ABCD          BBBB
ABCD          CCCC
ABCD          DDDD

```

The Tabula Recta:

```
ABCD
BCDA
CDAB
DABC

```

This alphabet triangle:

```
A      or   AAAAAAA
AB           BBBBB
ABC           CCC
ABCD           D
ABC
AB
A

```

We also have half triangles in lots of varieties:

```
A           AAAA      A        ABCD
BB          BBB       AB       ABC
CCC         CC        ABC      AB
DDDD        D         ABCD     A

```

Finally, the square:

```
AAAAAAA
ABBBBBA
ABCCCBA
ABCDCBA
ABCCCBA
ABBBBBA
AAAAAAA

```

All of the above patterns are of size 4. However, you will be passed a pattern of size 26, as well as an `N` between 1 and 26, and you need to scale the pattern. You do not need to handle any other patterns.

* The output for 1 will always be the single character `A`
* The output for 26 will always be the same, full-sized pattern passed in.
* Trailing spaces are allowed at the end of each line, as well as a trailing newline at the end
* You can find all patterns of size 26 here

This is a , so do it in as few bytes as possible!

# Answer
# PHP, 502 Bytes

```
<?$c=count($x=explode("\n",$_GET[p]));for($t=$u=$o="",$f="substr",$n=0;$n<$g=$_GET["n"];$n++){if(2651==$l=strlen($s))$o.=$f($x[$n],0,$g).$f($x[$n],1-$g)."\n";elseif($l==1026)echo($t=$f($x[$n],0,$g)).$f(strrev($t),1)."\n";elseif($f($s,-1)=="Y")echo$f($x[$n],0,$g-$n).$f($x[$n],-$n,$n)."\n";elseif($l==376&&$f($s,-2,1)=="\n")echo$f($x[$n],0,$g-$n)."\n";elseif($l==726){$t.=$x[$n]."\n";$n+1==$g?:$u=$x[$n]."\n".$u;}else echo$f($x[$n]??"",0,$g)."\n";}if($o)echo$o.substr(strrev($o),2*$g+1);if($t)echo$t.$u;

```

Works with the string length of a pattern. A pattern has these conditions. Letter at begin an end. CR are removed.

## Expanded

```
foreach($p as$s){ # all patterns in an array
    $c=count($x=explode("\n",$s));
    for($t=$u=$o="",$f="substr",$n=0;$n<$g=$_GET["n"];$n++){
    if(2651==$l=strlen($s))$o.=$f($x[$n],0,$g).$f($x[$n],1-$g)."\n";
# square pattern
    elseif($l==1026)echo($t=$f($x[$n],0,$g)).$f(strrev($t),1)."\n";
#alphabet triangle up down
    elseif($f($s,-1)=="Y")echo$f($x[$n],0,$g-$n).$f($x[$n],-$n,$n)."\n";
# Tabula recta
    elseif($l==376&&$f($s,-2,1)=="\n")echo$f($x[$n],0,$g-$n)."\n";
# two half triangle
    elseif($l==726){$t.=$x[$n]."\n";$n+1==$g?:$u=$x[$n]."\n".$u;}
#alphabet triangle left right
    else echo$f($x[$n]??"",0,$g)."\n";
# all other
    }
    if($o)echo$o.substr(strrev($o),2*$g+1);
    if($t)echo$t.$u;
}

```
> 2 votes

# Answer
# R, 483 412 bytes

```
    x=function(n){d=1:n;a=LETTERS[d];z=rep;f=function(...)cat(...,"\n",sep="");g=c(d,n:2-1);for(i in d)f(a[z(i,i)],if(i!=n)a[(i+1):n]);f(a);for(i in d)f(a[i]);for(i in d)f(a);for(i in d)f(z(a[i],n));for(i in d)f(a[i:n],if(i>1)a[1:i-1]);for(i in g)f(a[1:i]);for(i in d)f(z(" ",i-1),z(a[i],2*(n-i)+1));for(i in d)f(z(a[i],i));for(i in d)f(z(a[i],n-i+1));for(i in g)f(if(i>1)a[2:i-1],z(a[i],2*(n-i)+1),if(i>1)a[i:2-1])}

```

This is my first time posting, I was told I didn't have a recent years experience of R, so just practise a little bit here.

## Expanded

```
    x=function(n){
    # array of 1 to n
    d=1:n
    # first n capital letters
    a=LETTERS[d]
    # use z to represent the repeat function
    z=rep
    # use f to represent concatenate, with new line and close the gap
    f=function(...)cat(...,"\n",sep="");
    # use g to represent 1 to n then n to 1
    g=c(d,n:2-1)

    # L-phabet
    # start and repeat the first letter to i, combine the i+1 to the end
    for(i in d) f(a[z(i,i)],if(i!=n)a[(i+1):n])

    # single line - horizontal
    f(a)

    # single line - vertical
    for(i in d)f(a[i])

    # single line - repeated by row
    for(i in d)f(a)

    # single line - repeated by column
    for(i in d)f(z(a[i],n))

    # Tabula Recta
    # start from i, combine the 1 to i-1
    for(i in d) f(a[i:n],if(i>1)a[2:i-1])

    # alphabet triangle
    for(i in g)f(a[1:i])

    # alphabet triangle - upside down
    for(i in d)f(z(" ",i-1),z(a[i],2*(n-i)+1))

    # half triangles
    for(i in d)f(z(a[i],i))
    for(i in d)f(z(a[i],n-i+1))

    # the square
    # combine the first part from i to i-1 letters, repeat the i in the middle, combine the last part from i-1 to 1 letters
    for(i in g) f(if(i>1)a[2:i-1],z(a[i],2*(n-i)+1),if(i>1)a[i:2-1])
    }

```
> 2 votes

# Answer
# JavaScript (ES6), ~~382~~ ~~380~~ 370 bytes

```
f=(a,N)=>{X=Y=0
if(a[1]){Y=a[1].trim()[0]=='B'
X=z=a[0][1]==a[1][0]?1:!Y
l="ABCDEFGHIJKLMNOPQRSTUVWXYZ"[s='slice'](0,N)
if(z){if(a[0][1]=='A'){for(a=[],i=0,L=l;i<N;i++)a[N-i]=a[N+i]=L[s](0,-1)+l[N-i-1].repeat(i*2)+[...L].reverse().join``
L=L[s](0,-1)
return a}if(a[1][1]=='C')for(i=0;a[i++]=l,i<N;)l=l[s](1)+l[0]}}else X=1
a=X?a.map(l=>l[s](0,N)):a
return Y?a[s](0,N):a}

```

Pass an array of strings to the function `f()`, like this:

```
f(
`AAAAAAA
ABBBBBA
ABCCCBA
ABCDCBA
ABCCCBA
ABBBBBA
AAAAAAA`.split('\n'), 3)

```

---

Less golfed version with comments:

```
f=(a,N)=>{
    // Whether to truncate array horizontally to width N.
    X=0

    // Whether to truncate array vertically to height N.
    Y=0

    // If a second row exists...
    if(I=a[1]){
        // If the first non-whitespace character in the second row == 'B', truncate vertically.
        if(I.trim()[0]=='B')Y=1

        // Truncate horizontally if 2nd character in row 1 == 1st character in row 2; otherwise, if not truncating vertically.
        X=z=a[0][1]==I[0]?1:!Y

        // If 2nd character in row 1 == 1st character in row 2
        if(z){
            // Make an alphabet.
            l="ABCDEFGHIJKLMNOPQRSTUVWXYZ".slice(0,N)

            // If 2nd character in row 1 == 'A', forget everything we just did. Make a new array, generate a Square pattern, then return it.
            if(a[0][1]=='A'){
                for(a=[],i=0,L=l;i<N;i++)
                    a[N-i]=a[N+i]=L.slice(0,-1)+l[N-i-1].repeat(i*2)+[...L].reverse().join``,
                    L=L.slice(0,-1)
                return a
            }

            // If 2nd character in row 2 == 'C', fill array with a Tabula Recta.
            if(I[1]=='C')
                for(i=0;a[i++]=l,i<N;)
                    l=l.slice(1)+l[0]
        }
    }else{
        // If a second row doesn't exist, it's a horizontal line; truncate horizontally.
        X=1
    }

    // Truncate array horizontally if necessary.
    a=X?a.map(l=>l.slice(0,N)):a

    // Truncate array vertically if necessary.
    return Y?a.slice(0,N):a
}

```
> 1 votes

---
Tags: code-golf, alphabet
---


title: Generate a modulo rosace

text:
# Question
Title: Generate a modulo rosace
# The cool stuff

The following rosace can help calculate numbers modulo 7.

In order to do that, you must start at 0 and turn clockwise a number of steps given by the first digit. Then, for each successive digit, follow the arrow and then turn clockwise the number of steps given by that digit.

Here is how you proceed for number 294:

1. You start at circle 0.
2. You turn clockwise the number of steps given by the first digit (which is a 2, you end up at 2).
3. You follow the arrow there (you end up at 6).
4. You turn clockwise the number of steps given by the second digit (which is a 9, you end up at 1).
5. You follow the arrow there (you end up at 3).
6. You turn clockwise the number of steps given by the third number (which is 4, you end up at 0).
7. 294 mod 7 = 0 (meaning 294 is multiple of 7).

(Video explanation if you still didn't get it)

# The goal

Figure out how that works (I know but I won't tell you).

Create a program that takes a number `n` in parameter and that generates a rosace for `mod n`.

The rosace can be displayed by any means you want (ASCII, generate PNG, generate SVG, ...) as long as it could be used by a 8 years old child (**so no list of rules, I want a picture**)!

You can use strait lines, even if it's a bit less clear than what I made for the example, but you *must* show clearly the numbers that point to themselves with some kind of tail-biting arrow.

## Test cases

(I only give the links between the numbers, feel free to edit my question once your program sucessfully generates them)

mod 2:

```
0 -> 0
1 -> 0

```

mod 3:

```
0 -> 0
1 -> 1
2 -> 2

```

mod 4:

```
0 -> 0
1 -> 2
2 -> 0
3 -> 2

```

mod 5:

```
0 -> 0
1 -> 0
2 -> 0
3 -> 0
4 -> 0

```

mod 6:

```
0 -> 0
1 -> 4
2 -> 2
3 -> 0
4 -> 4
5 -> 2

```

mod 7:

```
0 -> 0
1 -> 3
2 -> 6
3 -> 2
4 -> 5
5 -> 1
6 -> 4

```

mod 8:

```
0 -> 0
1 -> 2
2 -> 4
3 -> 6
4 -> 0
5 -> 2
6 -> 4
7 -> 6

```

mod 9:

```
0 -> 0
1 -> 1
2 -> 2
3 -> 3
4 -> 4
5 -> 5
6 -> 6
7 -> 7
8 -> 8

```

mod 10:

```
0 -> 0
1 -> 0
2 -> 0
3 -> 0
4 -> 0
5 -> 0
6 -> 0
7 -> 0
8 -> 0
9 -> 0

```

# Rules

This is , shortest code in bytes wins.

As usual, loopholes and cheats are forbidden.

# Answer
# Mathematica, 192 bytes

This type of challenge (nontrivial mathematical computation together with high-level graphics output) is what Mathematica is made for!

```
(d=#;r_~t~n_:=r{Sin[#],Cos[#]}&[6.3n/d];m=Mod[10#,d]&;Graphics@{Array[#~Text~t[9,#]&,d,0],Array[Arrow@{t[9,#+1/7],t[9,#+6/7]}&,d],Array[Arrow@BezierCurve@{t[8,#+1/9],{0,0},t[8,m@#-1/9]}&,d]})&

```

Expanded and explained:

```
[1] (
[2] d = #; r_~t~n_ := r {Sin[#], Cos[#]} &[6.3 n/d]; m = Mod[10 #, d] &;
[3] Graphics@{
[4]   Array[#~Text~t[9, #] &, d, 0],
[5]   Array[Arrow@{t[9, # + 1/7], t[9, # + 6/7]} &, d],
[6]   Array[Arrow@BezierCurve@{t[8, # + 1/9], {0, 0}, t[8, m@# - 1/9]} &, d]
[7]          }
[8] ) &

```

Lines 1 and 8 delimit an unnamed function of one argument. Lines 3 and 7 delimit several commands that output graphics.

Lines 2 stores the input as `d`; defines a binary function `t` giving the coordinates of a point `n/d` of the way around the circle of radius `r`, clockwise from the top (in the spirit of this site, I saved a byte by rounding 2π to `6.3`!); and defines a unary function `m` calculating the destination of the arrow starting at its argument.

Line 4 renders the numbers `0` to `d–1` equally spaced around the circle of radius 9 (the exact radius unimportant, chosen to maximize aesthetics subject to fitting in one byte).

Line 5 renders the clockwise straight arrows around the circumference of the circle. The `1/7` and `6/7` leave enough space to read the numbers.

Line 6 renders the curved arrows from each number to (10 times the number modulo `d`). `BezierCurve` automatically draws a Bézier curve using the given control points. Fortunately, using the origin as a single interior control point produces reasonable output.

Sample output (note that the cases 9, 10, and 11 are trivial in different ways):

## d = 7

## d = 8

## d = 9

## d = 10

## d = 11

## d = 12

## d = 13

## d = 37

This last input was chosen because 37 divides 10^3–1, and so the interior arrows (not counting the obligatory self-arrow from 0 to 0) form lots of triangular cycles.
> 12 votes

# Answer
# Python 2, 294 bytes

```
n=input()
r,R="",range(n)
for i in R:r+=["   ","__ "][10*i%n==i]
r+="\n"
for i in R:r+=["   ","|/ "][10*i%n==i]
print r
print">>".join(map(str,R))
for i in R:
    o,r=10*i%n,""
    for j in R:
        r+="|"
        if i<=j<o:r+=">>"
        elif i>j>=o:r+="<<"
        else:r+="  "
    print r

```

Prints the diagram in this format:

```
__
|/
0>>1>>2>>3>>4>>5>>6
|  |  |  |  |  |  |
|  |>>|>>|  |  |  |
|  |  |>>|>>|>>|>>|
|  |  |<<|  |  |  |
|  |  |  |  |>>|  |
|  |<<|<<|<<|<<|  |
|  |  |  |  |<<|<<|

```

I don't know if this format is okay, therefore I'll leave this answer as invalid for the time being. Yay, it's valid!

**Try it on repl.it!**
> 10 votes

# Answer
# PHP+SVG, 500 Bytes

little arrow for connections between same values

```
<svg viewBox=0,0,500,500><def><marker id=t viewBox=0,0,9,9 refX=1 refY=5 orient=auto><path d=M0,0L10,5L0,10z /></marker></def><circle cx=250 cy=250 r=150 fill=#ccc /><?for($i=0;$i<$n=$_GET[n];$i++){$w=deg2rad((($i*10%$n)-$i)*360/$n);echo"<g transform=rotate(".$i*360/$n.",250,250)><path d=M250,110L".(250+(sin($w)*135)).",".(250-cos($w)*145)." fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>$i</text></g>";}?></svg>

```

to see the arrows to the same values I use this color value `rgba(255,0,0,0.3)` . it is a possibility to short it down.

expanded

```
    <svg viewBox=0,0,500,500>
<def>
<marker id=t viewBox=0,0,10,10 refX=1 refY=5 markerWidth=5 markerHeight=5 orient=auto>
<path d=M0,0L10,5L0,10z />
</marker>
</def>
<circle cx=250 cy=250 r=150 fill=#ccc stroke=#a00 />
<?php for($i=0;$i<$n=$_GET[n];$i++){
$w=deg2rad((($i*10%$n)-$i)*360/$n);
echo"<g transform=rotate(".$i*360/$n.",250,250)>
<path d=M250,110L".(250+(sin($w)*135)).",".(250-cos($w)*145)." fill=none stroke=#0f0 marker-end=url(#t) />
<circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) />
<text x=250 y=105 text-anchor=middle>$i</text>
</g>";
}?>
</svg>

```

output for n=45

```
<svg viewBox=0,0,500,500><def><marker id=t viewBox=0,0,10,10 refX=1 refY=5 markerWidth=5 markerHeight=5 orient=auto><path d=M0,0L10,5L0,10z /></marker></def><circle cx=250 cy=250 r=150 fill=#ccc stroke=#a00 /><g transform=rotate(0,250,250)><path d=M250,110L250,105 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>0</text></g><g transform=rotate(8,250,250)><path d=M250,110L378.39262969985,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>1</text></g><g transform=rotate(16,250,250)><path d=M250,110L329.35100905948,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>2</text></g><g transform=rotate(24,250,250)><path d=M250,110L170.64899094052,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>3</text></g><g transform=rotate(32,250,250)><path d=M250,110L121.60737030015,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>4</text></g><g transform=rotate(40,250,250)><path d=M250,110L250,105 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>5</text></g><g transform=rotate(48,250,250)><path d=M250,110L378.39262969985,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>6</text></g><g transform=rotate(56,250,250)><path d=M250,110L329.35100905948,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>7</text></g><g transform=rotate(64,250,250)><path d=M250,110L170.64899094052,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>8</text></g><g transform=rotate(72,250,250)><path d=M250,110L121.60737030015,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>9</text></g><g transform=rotate(80,250,250)><path d=M250,110L250,105 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>10</text></g><g transform=rotate(88,250,250)><path d=M250,110L378.39262969985,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>11</text></g><g transform=rotate(96,250,250)><path d=M250,110L329.35100905948,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>12</text></g><g transform=rotate(104,250,250)><path d=M250,110L170.64899094052,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>13</text></g><g transform=rotate(112,250,250)><path d=M250,110L121.60737030015,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>14</text></g><g transform=rotate(120,250,250)><path d=M250,110L250,105 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>15</text></g><g transform=rotate(128,250,250)><path d=M250,110L378.39262969985,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>16</text></g><g transform=rotate(136,250,250)><path d=M250,110L329.35100905948,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>17</text></g><g transform=rotate(144,250,250)><path d=M250,110L170.64899094052,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>18</text></g><g transform=rotate(152,250,250)><path d=M250,110L121.60737030015,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>19</text></g><g transform=rotate(160,250,250)><path d=M250,110L250,105 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>20</text></g><g transform=rotate(168,250,250)><path d=M250,110L378.39262969985,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>21</text></g><g transform=rotate(176,250,250)><path d=M250,110L329.35100905948,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>22</text></g><g transform=rotate(184,250,250)><path d=M250,110L170.64899094052,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>23</text></g><g transform=rotate(192,250,250)><path d=M250,110L121.60737030015,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>24</text></g><g transform=rotate(200,250,250)><path d=M250,110L250,105 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>25</text></g><g transform=rotate(208,250,250)><path d=M250,110L378.39262969985,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>26</text></g><g transform=rotate(216,250,250)><path d=M250,110L329.35100905948,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>27</text></g><g transform=rotate(224,250,250)><path d=M250,110L170.64899094052,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>28</text></g><g transform=rotate(232,250,250)><path d=M250,110L121.60737030015,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>29</text></g><g transform=rotate(240,250,250)><path d=M250,110L250,105 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>30</text></g><g transform=rotate(248,250,250)><path d=M250,110L378.39262969985,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>31</text></g><g transform=rotate(256,250,250)><path d=M250,110L329.35100905948,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>32</text></g><g transform=rotate(264,250,250)><path d=M250,110L170.64899094052,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>33</text></g><g transform=rotate(272,250,250)><path d=M250,110L121.60737030015,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>34</text></g><g transform=rotate(280,250,250)><path d=M250,110L250,105 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>35</text></g><g transform=rotate(288,250,250)><path d=M250,110L378.39262969985,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>36</text></g><g transform=rotate(296,250,250)><path d=M250,110L329.35100905948,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>37</text></g><g transform=rotate(304,250,250)><path d=M250,110L170.64899094052,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>38</text></g><g transform=rotate(312,250,250)><path d=M250,110L121.60737030015,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>39</text></g><g transform=rotate(320,250,250)><path d=M250,110L250,105 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>40</text></g><g transform=rotate(328,250,250)><path d=M250,110L378.39262969985,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>41</text></g><g transform=rotate(336,250,250)><path d=M250,110L329.35100905948,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>42</text></g><g transform=rotate(344,250,250)><path d=M250,110L170.64899094052,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>43</text></g><g transform=rotate(352,250,250)><path d=M250,110L121.60737030015,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>44</text></g></svg>
```

## 320 Bytes working with rect

```
<svg viewBox=0,0,<?=$w=30+10*$n=$_GET[n]?>,<?=20*$n?>><?for($i=0;$i<$n;$i++)echo"<rect x=0 y=".($y=$i*20)." fill=none width=$w height=20 stroke=grey /><text x=5 y=".($y+17).">$i</text><path d=M".($x=$i*10+25).",".($y+17)."L$x,".($m=($i*10%$n)*20+5)." fill=none stroke=blue /><circle cx=$x cy=$m r=2 fill=#0f0 />"?></svg>

```

expanded

```
<svg viewBox=0,0,<?=$w=30+10*$n=$_GET[n]?>,<?=20*$n?>>
<?for($i=0;$i<$n;$i++)
echo"<rect x=0 y=".($y=$i*20)." fill=none width=$w height=20 stroke=grey />
<text x=5 y=".($y+17).">$i</text>
<path d=M".($x=$i*10+25).",".($y+17)."L$x,".($m=($i*10%$n)*20+5)." fill=none stroke=blue />
<circle cx=$x cy=$m r=2 fill=#0f0 />"?>
</svg>

```

output for n=72

```
<svg viewBox=0,0,750,1440><rect x=0 y=0 fill=none width=750 height=20 stroke=grey /><text x=5 y=17>0</text><path d=M25,17L25,5 fill=none stroke=blue /><circle cx=25 cy=5 r=2 fill=#0f0 /><rect x=0 y=20 fill=none width=750 height=20 stroke=grey /><text x=5 y=37>1</text><path d=M35,37L35,205 fill=none stroke=blue /><circle cx=35 cy=205 r=2 fill=#0f0 /><rect x=0 y=40 fill=none width=750 height=20 stroke=grey /><text x=5 y=57>2</text><path d=M45,57L45,405 fill=none stroke=blue /><circle cx=45 cy=405 r=2 fill=#0f0 /><rect x=0 y=60 fill=none width=750 height=20 stroke=grey /><text x=5 y=77>3</text><path d=M55,77L55,605 fill=none stroke=blue /><circle cx=55 cy=605 r=2 fill=#0f0 /><rect x=0 y=80 fill=none width=750 height=20 stroke=grey /><text x=5 y=97>4</text><path d=M65,97L65,805 fill=none stroke=blue /><circle cx=65 cy=805 r=2 fill=#0f0 /><rect x=0 y=100 fill=none width=750 height=20 stroke=grey /><text x=5 y=117>5</text><path d=M75,117L75,1005 fill=none stroke=blue /><circle cx=75 cy=1005 r=2 fill=#0f0 /><rect x=0 y=120 fill=none width=750 height=20 stroke=grey /><text x=5 y=137>6</text><path d=M85,137L85,1205 fill=none stroke=blue /><circle cx=85 cy=1205 r=2 fill=#0f0 /><rect x=0 y=140 fill=none width=750 height=20 stroke=grey /><text x=5 y=157>7</text><path d=M95,157L95,1405 fill=none stroke=blue /><circle cx=95 cy=1405 r=2 fill=#0f0 /><rect x=0 y=160 fill=none width=750 height=20 stroke=grey /><text x=5 y=177>8</text><path d=M105,177L105,165 fill=none stroke=blue /><circle cx=105 cy=165 r=2 fill=#0f0 /><rect x=0 y=180 fill=none width=750 height=20 stroke=grey /><text x=5 y=197>9</text><path d=M115,197L115,365 fill=none stroke=blue /><circle cx=115 cy=365 r=2 fill=#0f0 /><rect x=0 y=200 fill=none width=750 height=20 stroke=grey /><text x=5 y=217>10</text><path d=M125,217L125,565 fill=none stroke=blue /><circle cx=125 cy=565 r=2 fill=#0f0 /><rect x=0 y=220 fill=none width=750 height=20 stroke=grey /><text x=5 y=237>11</text><path d=M135,237L135,765 fill=none stroke=blue /><circle cx=135 cy=765 r=2 fill=#0f0 /><rect x=0 y=240 fill=none width=750 height=20 stroke=grey /><text x=5 y=257>12</text><path d=M145,257L145,965 fill=none stroke=blue /><circle cx=145 cy=965 r=2 fill=#0f0 /><rect x=0 y=260 fill=none width=750 height=20 stroke=grey /><text x=5 y=277>13</text><path d=M155,277L155,1165 fill=none stroke=blue /><circle cx=155 cy=1165 r=2 fill=#0f0 /><rect x=0 y=280 fill=none width=750 height=20 stroke=grey /><text x=5 y=297>14</text><path d=M165,297L165,1365 fill=none stroke=blue /><circle cx=165 cy=1365 r=2 fill=#0f0 /><rect x=0 y=300 fill=none width=750 height=20 stroke=grey /><text x=5 y=317>15</text><path d=M175,317L175,125 fill=none stroke=blue /><circle cx=175 cy=125 r=2 fill=#0f0 /><rect x=0 y=320 fill=none width=750 height=20 stroke=grey /><text x=5 y=337>16</text><path d=M185,337L185,325 fill=none stroke=blue /><circle cx=185 cy=325 r=2 fill=#0f0 /><rect x=0 y=340 fill=none width=750 height=20 stroke=grey /><text x=5 y=357>17</text><path d=M195,357L195,525 fill=none stroke=blue /><circle cx=195 cy=525 r=2 fill=#0f0 /><rect x=0 y=360 fill=none width=750 height=20 stroke=grey /><text x=5 y=377>18</text><path d=M205,377L205,725 fill=none stroke=blue /><circle cx=205 cy=725 r=2 fill=#0f0 /><rect x=0 y=380 fill=none width=750 height=20 stroke=grey /><text x=5 y=397>19</text><path d=M215,397L215,925 fill=none stroke=blue /><circle cx=215 cy=925 r=2 fill=#0f0 /><rect x=0 y=400 fill=none width=750 height=20 stroke=grey /><text x=5 y=417>20</text><path d=M225,417L225,1125 fill=none stroke=blue /><circle cx=225 cy=1125 r=2 fill=#0f0 /><rect x=0 y=420 fill=none width=750 height=20 stroke=grey /><text x=5 y=437>21</text><path d=M235,437L235,1325 fill=none stroke=blue /><circle cx=235 cy=1325 r=2 fill=#0f0 /><rect x=0 y=440 fill=none width=750 height=20 stroke=grey /><text x=5 y=457>22</text><path d=M245,457L245,85 fill=none stroke=blue /><circle cx=245 cy=85 r=2 fill=#0f0 /><rect x=0 y=460 fill=none width=750 height=20 stroke=grey /><text x=5 y=477>23</text><path d=M255,477L255,285 fill=none stroke=blue /><circle cx=255 cy=285 r=2 fill=#0f0 /><rect x=0 y=480 fill=none width=750 height=20 stroke=grey /><text x=5 y=497>24</text><path d=M265,497L265,485 fill=none stroke=blue /><circle cx=265 cy=485 r=2 fill=#0f0 /><rect x=0 y=500 fill=none width=750 height=20 stroke=grey /><text x=5 y=517>25</text><path d=M275,517L275,685 fill=none stroke=blue /><circle cx=275 cy=685 r=2 fill=#0f0 /><rect x=0 y=520 fill=none width=750 height=20 stroke=grey /><text x=5 y=537>26</text><path d=M285,537L285,885 fill=none stroke=blue /><circle cx=285 cy=885 r=2 fill=#0f0 /><rect x=0 y=540 fill=none width=750 height=20 stroke=grey /><text x=5 y=557>27</text><path d=M295,557L295,1085 fill=none stroke=blue /><circle cx=295 cy=1085 r=2 fill=#0f0 /><rect x=0 y=560 fill=none width=750 height=20 stroke=grey /><text x=5 y=577>28</text><path d=M305,577L305,1285 fill=none stroke=blue /><circle cx=305 cy=1285 r=2 fill=#0f0 /><rect x=0 y=580 fill=none width=750 height=20 stroke=grey /><text x=5 y=597>29</text><path d=M315,597L315,45 fill=none stroke=blue /><circle cx=315 cy=45 r=2 fill=#0f0 /><rect x=0 y=600 fill=none width=750 height=20 stroke=grey /><text x=5 y=617>30</text><path d=M325,617L325,245 fill=none stroke=blue /><circle cx=325 cy=245 r=2 fill=#0f0 /><rect x=0 y=620 fill=none width=750 height=20 stroke=grey /><text x=5 y=637>31</text><path d=M335,637L335,445 fill=none stroke=blue /><circle cx=335 cy=445 r=2 fill=#0f0 /><rect x=0 y=640 fill=none width=750 height=20 stroke=grey /><text x=5 y=657>32</text><path d=M345,657L345,645 fill=none stroke=blue /><circle cx=345 cy=645 r=2 fill=#0f0 /><rect x=0 y=660 fill=none width=750 height=20 stroke=grey /><text x=5 y=677>33</text><path d=M355,677L355,845 fill=none stroke=blue /><circle cx=355 cy=845 r=2 fill=#0f0 /><rect x=0 y=680 fill=none width=750 height=20 stroke=grey /><text x=5 y=697>34</text><path d=M365,697L365,1045 fill=none stroke=blue /><circle cx=365 cy=1045 r=2 fill=#0f0 /><rect x=0 y=700 fill=none width=750 height=20 stroke=grey /><text x=5 y=717>35</text><path d=M375,717L375,1245 fill=none stroke=blue /><circle cx=375 cy=1245 r=2 fill=#0f0 /><rect x=0 y=720 fill=none width=750 height=20 stroke=grey /><text x=5 y=737>36</text><path d=M385,737L385,5 fill=none stroke=blue /><circle cx=385 cy=5 r=2 fill=#0f0 /><rect x=0 y=740 fill=none width=750 height=20 stroke=grey /><text x=5 y=757>37</text><path d=M395,757L395,205 fill=none stroke=blue /><circle cx=395 cy=205 r=2 fill=#0f0 /><rect x=0 y=760 fill=none width=750 height=20 stroke=grey /><text x=5 y=777>38</text><path d=M405,777L405,405 fill=none stroke=blue /><circle cx=405 cy=405 r=2 fill=#0f0 /><rect x=0 y=780 fill=none width=750 height=20 stroke=grey /><text x=5 y=797>39</text><path d=M415,797L415,605 fill=none stroke=blue /><circle cx=415 cy=605 r=2 fill=#0f0 /><rect x=0 y=800 fill=none width=750 height=20 stroke=grey /><text x=5 y=817>40</text><path d=M425,817L425,805 fill=none stroke=blue /><circle cx=425 cy=805 r=2 fill=#0f0 /><rect x=0 y=820 fill=none width=750 height=20 stroke=grey /><text x=5 y=837>41</text><path d=M435,837L435,1005 fill=none stroke=blue /><circle cx=435 cy=1005 r=2 fill=#0f0 /><rect x=0 y=840 fill=none width=750 height=20 stroke=grey /><text x=5 y=857>42</text><path d=M445,857L445,1205 fill=none stroke=blue /><circle cx=445 cy=1205 r=2 fill=#0f0 /><rect x=0 y=860 fill=none width=750 height=20 stroke=grey /><text x=5 y=877>43</text><path d=M455,877L455,1405 fill=none stroke=blue /><circle cx=455 cy=1405 r=2 fill=#0f0 /><rect x=0 y=880 fill=none width=750 height=20 stroke=grey /><text x=5 y=897>44</text><path d=M465,897L465,165 fill=none stroke=blue /><circle cx=465 cy=165 r=2 fill=#0f0 /><rect x=0 y=900 fill=none width=750 height=20 stroke=grey /><text x=5 y=917>45</text><path d=M475,917L475,365 fill=none stroke=blue /><circle cx=475 cy=365 r=2 fill=#0f0 /><rect x=0 y=920 fill=none width=750 height=20 stroke=grey /><text x=5 y=937>46</text><path d=M485,937L485,565 fill=none stroke=blue /><circle cx=485 cy=565 r=2 fill=#0f0 /><rect x=0 y=940 fill=none width=750 height=20 stroke=grey /><text x=5 y=957>47</text><path d=M495,957L495,765 fill=none stroke=blue /><circle cx=495 cy=765 r=2 fill=#0f0 /><rect x=0 y=960 fill=none width=750 height=20 stroke=grey /><text x=5 y=977>48</text><path d=M505,977L505,965 fill=none stroke=blue /><circle cx=505 cy=965 r=2 fill=#0f0 /><rect x=0 y=980 fill=none width=750 height=20 stroke=grey /><text x=5 y=997>49</text><path d=M515,997L515,1165 fill=none stroke=blue /><circle cx=515 cy=1165 r=2 fill=#0f0 /><rect x=0 y=1000 fill=none width=750 height=20 stroke=grey /><text x=5 y=1017>50</text><path d=M525,1017L525,1365 fill=none stroke=blue /><circle cx=525 cy=1365 r=2 fill=#0f0 /><rect x=0 y=1020 fill=none width=750 height=20 stroke=grey /><text x=5 y=1037>51</text><path d=M535,1037L535,125 fill=none stroke=blue /><circle cx=535 cy=125 r=2 fill=#0f0 /><rect x=0 y=1040 fill=none width=750 height=20 stroke=grey /><text x=5 y=1057>52</text><path d=M545,1057L545,325 fill=none stroke=blue /><circle cx=545 cy=325 r=2 fill=#0f0 /><rect x=0 y=1060 fill=none width=750 height=20 stroke=grey /><text x=5 y=1077>53</text><path d=M555,1077L555,525 fill=none stroke=blue /><circle cx=555 cy=525 r=2 fill=#0f0 /><rect x=0 y=1080 fill=none width=750 height=20 stroke=grey /><text x=5 y=1097>54</text><path d=M565,1097L565,725 fill=none stroke=blue /><circle cx=565 cy=725 r=2 fill=#0f0 /><rect x=0 y=1100 fill=none width=750 height=20 stroke=grey /><text x=5 y=1117>55</text><path d=M575,1117L575,925 fill=none stroke=blue /><circle cx=575 cy=925 r=2 fill=#0f0 /><rect x=0 y=1120 fill=none width=750 height=20 stroke=grey /><text x=5 y=1137>56</text><path d=M585,1137L585,1125 fill=none stroke=blue /><circle cx=585 cy=1125 r=2 fill=#0f0 /><rect x=0 y=1140 fill=none width=750 height=20 stroke=grey /><text x=5 y=1157>57</text><path d=M595,1157L595,1325 fill=none stroke=blue /><circle cx=595 cy=1325 r=2 fill=#0f0 /><rect x=0 y=1160 fill=none width=750 height=20 stroke=grey /><text x=5 y=1177>58</text><path d=M605,1177L605,85 fill=none stroke=blue /><circle cx=605 cy=85 r=2 fill=#0f0 /><rect x=0 y=1180 fill=none width=750 height=20 stroke=grey /><text x=5 y=1197>59</text><path d=M615,1197L615,285 fill=none stroke=blue /><circle cx=615 cy=285 r=2 fill=#0f0 /><rect x=0 y=1200 fill=none width=750 height=20 stroke=grey /><text x=5 y=1217>60</text><path d=M625,1217L625,485 fill=none stroke=blue /><circle cx=625 cy=485 r=2 fill=#0f0 /><rect x=0 y=1220 fill=none width=750 height=20 stroke=grey /><text x=5 y=1237>61</text><path d=M635,1237L635,685 fill=none stroke=blue /><circle cx=635 cy=685 r=2 fill=#0f0 /><rect x=0 y=1240 fill=none width=750 height=20 stroke=grey /><text x=5 y=1257>62</text><path d=M645,1257L645,885 fill=none stroke=blue /><circle cx=645 cy=885 r=2 fill=#0f0 /><rect x=0 y=1260 fill=none width=750 height=20 stroke=grey /><text x=5 y=1277>63</text><path d=M655,1277L655,1085 fill=none stroke=blue /><circle cx=655 cy=1085 r=2 fill=#0f0 /><rect x=0 y=1280 fill=none width=750 height=20 stroke=grey /><text x=5 y=1297>64</text><path d=M665,1297L665,1285 fill=none stroke=blue /><circle cx=665 cy=1285 r=2 fill=#0f0 /><rect x=0 y=1300 fill=none width=750 height=20 stroke=grey /><text x=5 y=1317>65</text><path d=M675,1317L675,45 fill=none stroke=blue /><circle cx=675 cy=45 r=2 fill=#0f0 /><rect x=0 y=1320 fill=none width=750 height=20 stroke=grey /><text x=5 y=1337>66</text><path d=M685,1337L685,245 fill=none stroke=blue /><circle cx=685 cy=245 r=2 fill=#0f0 /><rect x=0 y=1340 fill=none width=750 height=20 stroke=grey /><text x=5 y=1357>67</text><path d=M695,1357L695,445 fill=none stroke=blue /><circle cx=695 cy=445 r=2 fill=#0f0 /><rect x=0 y=1360 fill=none width=750 height=20 stroke=grey /><text x=5 y=1377>68</text><path d=M705,1377L705,645 fill=none stroke=blue /><circle cx=705 cy=645 r=2 fill=#0f0 /><rect x=0 y=1380 fill=none width=750 height=20 stroke=grey /><text x=5 y=1397>69</text><path d=M715,1397L715,845 fill=none stroke=blue /><circle cx=715 cy=845 r=2 fill=#0f0 /><rect x=0 y=1400 fill=none width=750 height=20 stroke=grey /><text x=5 y=1417>70</text><path d=M725,1417L725,1045 fill=none stroke=blue /><circle cx=725 cy=1045 r=2 fill=#0f0 /><rect x=0 y=1420 fill=none width=750 height=20 stroke=grey /><text x=5 y=1437>71</text><path d=M735,1437L735,1245 fill=none stroke=blue /><circle cx=735 cy=1245 r=2 fill=#0f0 /></svg>
```
> 6 votes

# Answer
# Python 2, ~~540~~ ~~464~~ 431 bytes

Some golfing like using shorter variable names, variable substitution, list comprehension and changing everything to white (except the text). Biggest save was changing precomputed positions to dynamically (see `L`).

```
from cv2 import*
from numpy import*
D=1024
G=zeros((D,D,3),uint8)
n=7
w=(1,1,1)
R=range(n)
c=circle
I=int
L=lambda i,r=400:(I(sin(2*pi*i/n)*r+D/2),I(D/2-cos(2*pi*i/n)*r))
for i in R:
 p,q=L(i),L((i*10)%n)
 line(G,p,L((i+1)%n),w,5)
 line(G,p,q,w,5)
 f=lambda z:I(.15*p[z]+.85*q[z])
 c(G,[(f(0),f(1)),L(i,450)][p==q],25,w,-1)
for i in R:
 c(G,L(i),50,w,-1)
 putText(G,`i`,(L(i)[0]-30,L(i)[1]+30),0,2,(0,0,0),2)
imwrite('m.png',G*255)

```

`L` calculates the positions of the circles by distance to origin for the big ones containing the numbers and the outer small ones that indicate self pointing.

First loop draws the connections: 1st line is the circle around and 2nd line is in the interior, a small circle is added to show direction or self pointing.

Second loop puts big circle and number.

It is obviously not as nice as the Mathematica answers, but everything made from scratch.
> 3 votes

# Answer
# Mathematica, ~~124~~ 121 bytes

```
Graph[Join@@Thread[{k->Mod[k+1,#],k->Mod[10k,#]}~Table~{k,0,#-1}],VertexLabels->"Name",GraphLayout->"CircularEmbedding"]&

```

Creates a figure as a graph with directed edges. The graph output now follows the same pattern except counter-clockwise. I prefer Greg Martin's solution a lot more since the output is much more aesthetically pleasing.

A less visually pleasant graph can be generated for **82 bytes** using

```
Graph[Join@@({k->Mod[k+1,#],k->Mod[10k,#]}~Table~{k,0,#-1}),VertexLabels->"Name"]&

```

For *d* = 8,
> 2 votes

# Answer
## Batch, 394 bytes

```
@echo off
set/an=%1-1
set s=
for /l %%j in (0,1,%n%)do call:h %%j
echo %s%
for /l %%i in (0,1,%n%)do call:r %%i %1
exit/b
:h
set "s=%s%^>%1^>"
exit/b
:r
set/ar=%1*10%%%2
set s=
for /l %%j in (0,1,%n%)do call:l %%j %1
echo %s%
exit/b
:l
if %1==%r% set "s=%s%^>%1^<"&exit/b
if %2 geq %1 if %1 geq %r% set "s=%s%^<%1%^<"&exit/b
if %2 leq %1 if %1 leq %r% goto h
set "s=%s% %1 "

```

Escaping in Batch is ugly at the best of times. Example output for 7:

```
>0>>1>>2>>3>>4>>5>>6>
>0< 1  2  3  4  5  6
 0 >1>>2>>3< 4  5  6
 0  1 >2>>3>>4>>5>>6<
 0  1 >2<<3< 4  5  6
 0  1  2  3 >4>>5< 6
 0 >1<<2<<3<<4<<5< 6
 0  1  2  3 >4<<5<<6<

```
> 1 votes

# Answer
## Python 2 + graphviz, 147 bytes

```
from graphviz import*
d=Digraph()
k=input()
p=d.edge
for j in[d.node(`i`,`i`)or i for i in range(k)]:
 p(`j`,`-~j%k`);p(`j`,`10*j%k`)
d.render("o")

```

Doesn't always draw a circle, outputs a pdf file called `o`
> 1 votes

# Answer
# Haskell, 350 bytes

Inspired by @Loovjo, I also use ASCII art. This works for numbers under 100000 (or something like that).

```
g k="\t"++(foldl (++) ""$map (\y->show y++"|") [0..k])
n k=length$g k
r z x=(show x)++":\t"++(replicate f ' ')++(replicate d s)++"\n" where y=mod (x*10) z;(a,b)=(min x y,max x y);s=(case compare y x of LT->'<';EQ->'.';GT->'>');f=n (a-1)-1;d=n b-f-2
w z=(g (z-1))++"\n"++(foldl1 (++) (map (r z) [0..(z-1)]))
main=do{n<-getLine;putStrLn (w$read n);}

```

Basically you point from x to (x\*10)%n.

You can try this here. But since codepad doesn't support input, change **q** to the value of **n** you want, and resubmit. (Note that forking doesn't work, so copy and resubmit from main page). The code submitted there is a bit different, because the above version takes input from console.

I hope the output is intuitive. Compression suggestions are welcome (particularly if that beats **294** ;)).
> 1 votes

---
Tags: code-golf, math, graphical-output
---


title: Traveling Pumpkin Problem

text:
# Question
Title: Traveling Pumpkin Problem
### Background:

Jack is a pumpkin that enjoys spooking the citizens of the villages near his pumpkin patch every Halloween. However, every year after someone lights the candle inside of him, he has a limited amount of time to spook everyone before the candle burns out, thus being unable to spook any more villagers because nobody can see him. In past years, he has only been able to spook a small amount of villages due to his poor decision making, but now that he has you to help him, he will be able to spook as many villages as possible!

### Task:

Given a list of village locations and a candle lifespan, output the maximum number of villages Jack can visit. You do not have to print the path itself.

### Input:

The lifespan of the candle and a list of village locations in a Cartesian coordinate system. The pumpkin patch Jack originates from will always be at 0,0. You may format the input in anyway you wish. To simplify Jack's movements, he can only move horizontally, vertically, or diagonally, meaning his candle will either lose 1 or 1.5 (he takes a bit longer diagonally) units of life every move. The candle burns out when the lifespan is less than or equal to 0.

### Output:

An integer equal to the maximum number of villages Jack can visit before the candle burns out.

### Rules:

This is , so shortest code in bytes wins. Standard loopholes are not allowed.

### Test cases:

```
// Format [lifespan] [list of village coordinates] -> [maximum visit-able villages]

4 -1,0 1,0 2,0 3,0 4,0 5,0 -> 3
4 1,1 2,2 3,3 -> 2
5 1,1 2,1 3,1 4,1 5,0 5,1 -> 4

```

# Answer
> 9 votes
# Jelly, ~~30~~ ~~29~~ ~~27~~ 25 bytes

```
_AṢæ..
0,0ṭṚç2\+\<S
Œ!ç€Ṁ

```

Try it online!

Apparently Jelly's dot product just ignores a list size mismatch and doesn't multiply the extra elements of the other array, just adds them. Shaves off 2 bytes.

### Explanation

```
_AṢæ..              Helper link to calculate distance. Arguments: a, b
_                     subtract the vertices from each other
 A                    take absolute values of axes
  Ṣ                   sort the axes
   æ..                dot product with [0.5]

0,0ṭṚç2\+\<S        Helper link to calculate max cities. Arguments: perm, max
0,0                   create pair [0,0]
   ṭ                  append that to the permutation
    Ṛ                 reverse the permutation (gets the [0,0] to the beginning)
     ç2\              find distances of each pair using the previous link
        +\            find all partial sums
          <           see if each sum was less than the max
           S          sum to count cases where it was

Œ!ç€Ṁ               Main link. Arguments: cities, max
Œ!                    get permutations of cities
  ç€                  find max cities for each permutation using the previous link
    Ṁ                 take the maximum

```

# Answer
> 5 votes
# Java 7, ~~206~~ 201 bytes

*Thanks to @KevinCruijssen for saving 5 bytes*

```
int f(float e,int[]a,int[]b){int x=0,y=0,c=0,d=0,t;float s;for(int i:a){s=(i!=x&b[c]==y)|(i==x&b[c]!=y)?Math.sqrt((t=i-x)*t+(t=b[c]-y)*t)*1:Math.abs(i-x)*1.5;d+=e-s>=0?1:0;e-=s;x=i;y=b[c++];}return d;}

```

# Ungolfed

```
class Travellingpumpkin {

public static void main(String[] args) {

    System.out.println(f( 5 ,new int[] { 1,2,3,4,5,5 } , new int[] { 1,1,1,1,0,1 } ));

}
static int f( double e , int[]a , int[]b ) {
    int x = 0 , y = 0 , c = 0 , d = 0 , t;
    double s ;

    for ( int i : a ) {
    s = ( i != x & b[c] == y )|( i == x & b[c] != y )
         ? Math.sqrt( ( t = i - x ) * t + ( t = b[c] - y ) * t ) * 1
         : Math.abs( i - x ) * 1.5 ;

        d += e-s >= 0 ? 1 : 0 ;
        e -= s ;
        x = i ; y = b [ c++ ] ;
    }
    return d ;

}

   }

```

# Answer
> 3 votes
# Scala, 196 bytes

```
def f(l:Int,c:(Int,Int)*)=c.permutations.map(x=>((0,0)+:x sliding 2 map{p=>val Seq(c,d)=Seq((p(0)._1-p(1)._1)abs,(p(0)._2-p(1)._2)abs).sorted
c*1.5+(d-c)}scanLeft 0d)(_+_)takeWhile(_<l)size).max-1

```

Ungolfed:

```
def g (l: Int, c: (Int, Int)*) = {
    c.permutations
    .map { x =>
        ((0, 0) +: x).sliding(2).map({ p =>
            val Seq(c, d) = Seq((p(0)._1 - p(1)._1) abs, (p(0)._2 - p(1)._2) abs).sorted
            c * 1.5 + (d - c)
        }).scanLeft(0d)(_ + _).takeWhile(_ < l).size
    }.max - 1
}

```

Explanantion:

```
def f(l:Int,c:(Int,Int)*)= //defien a function with an int and a vararg-int-pait parameter
  c.permutations           //get the permutations of c, that is all possible routes
  .map(x=>                 //map each of them to...
    ((0,0)+:x                //prepend (0,0)
    sliding 2                //convert to a sequence of consecutive elemtens
    map{p=>                  //and map each of them to their distance:
      val Seq(c,d)=Seq(        //create a sequence of
        (p(0)._1-p(1)._1)abs,  //of the absolute distance between the x points
        (p(0)._2-p(1)._2)abs   //and he absolute distance between the y coordinates
      ).sorted                 //sort them and assign the smaller one to c and the larger one to d
      c*1.5+(d-c)              //we do the minimum difference diagonally
    }                        //we now have a sequence of sequence of the distances for each route
    scanLeft 0d)(_+_)       //calculate the cumulative sum
    takeWhile(_<l)          //and drop all elements that are larger than the candle lifespan
    size                    //take the size
  ).max-1                   //take the maximum, taht is the size of the largest route and subtract 1 because we added (0,0) at the beginning

```

# Answer
> 3 votes
# MATL, 27 bytes

```
EH:"iY@OwYc!d|]yyXl++Ys>sX>

```

*EDIT (26 nov 2016): Due to changes in the `Xl` function, it has to be replaced in the above code by `2$X>`. The links below incorporate that modification.*

Try it online! Or verify all test cases.

### Explanation

The *pumpkin distance* between two cities separated Δ*x* and Δ*y* in each coordinate can be obtained as ( |Δ*x*| + |Δ*y*| + max(|Δ*x*|, |Δ*y*|) ) / 2.

The code follows these steps:

1. Generate all permutations of *x* coordinates and of *y* coordinates, and prepend a to each 0. Each permutation represents a possible path.
2. Compute absolute consecutive differences for each path (these are |Δ*x*| and |Δ*y*| above).
3. Obtain the pumpkin distance for each step of each path.
4. Compute the cumulative sum of distances for each path.
5. Find, for each path, the number of steps before the accumulated distance reaches the chandle lifespan.
6. Take the maximum of the above.

Commented code:

```
E        % Input candle lifespan implicitly. Multiply by 2
H:"      % Do thie twice
  i      %   Input array of x or y coordinates
  Y@     %   All permutations. Gives a matrix, with each permutation in a row
  OwYc   %   Prepend a 0 to each row
  !      %   Transpose
  d|     %   Consecutive differences along each column. Absolute value
]        % End
yy       % Duplicate the two matrices (x and y coordinates of all paths)
Xl       % Take maximum between the two, element-wise
++       % Add twice. This gives twice the pumpkin distance
Ys       % Cumulative sum along each column
>        % True for cumulative sums that exceed twice the candle lifespan
s        % Sum of true values for each column
X>       % Maximum of the resulting row array. Inmplicitly display

```

# Answer
> 3 votes
# JavaScript (ES6), 145

Anonymous recursive function, parameter `s` is the candle lifespan, parameter `l` is the village coordinate list.

A *Depth First Search*, stopping when the distance reachs the candle lifespan

```
f=(s,l,x=0,y=0,v=0,A=Math.abs,X=Math.max)=>X(v,...l.map(([t,u],i,[h,...l],q=A(t-x),p=A(u-y),d=(l[i-1]=h,p+q+X(p,q))/2)=>s<=d?v:f(s-d,l,t,u,1+v)))

```

*Less golfed* see the snippet below

**Test**

```
f=(s,l,x=0,y=0,v=0,A=Math.abs,X=Math.max)=>
  X(v,...l.map(
      ([t,u],i,[h,...l],q=A(t-x),p=A(u-y),d=(l[i-1]=h,p+q+X(p,q))/2)=>
      s<=d?v:f(s-d,l,t,u,1+v)
  ))

// ungolfed version

F=(s, l,
   x=0, y=0, // current position
   v=0 // current number of visited sites
  ) =>
   Math.max(v, ...l.map(
     (
       [t,u], i, [h,...l], // lambda arguments
       q = Math.abs(t-x), p = Math.abs(u-y), // locals
       d = (p+q+Math.max(p,q))/2
     ) => (
       l[i-1] = h,
       s <= d
         ? v
         : F(s-d, l, t, u, v+1)
     )
  ))

;[[4,[[-1,0],[1,0],[2,0],[3,0],[4,0],[5,0]], 3]
,[4, [[1,1],[2,2],[3,3]], 2]
,[5, [[1,1],[2,1],[3,1],[4,1],[5,0],[5,1]], 4]
].forEach(test=>{
  var span=test[0],list=test[1],check=test[2],
      result = f(span, list)
  console.log(result==check?'OK':'KO',span, list+'', result)
})
```

# Answer
> 2 votes
# **Python 2.7, 422 bytes**

### thanks to NoOneIsHere for pointing out additional improvements!

### thanks to edc65 for noting not to save the list but use iterators instead!

**Try it online!**

```
from itertools import permutations
def d(s,e):
    d=0
    while s!=e:
        x=1 if s[0]<e[0] else -1 if s[0]>e[0] else 0
        y=1 if s[1]<e[1] else -1 if s[1]>e[1] else 0
        s=(s[0]+x,s[1]+y)
        d+=(1,1.5)[x and y]
return d
l,m=4,0
for o in permutations([(1,1),(2,2),(3,3)]):
    a,c=l-d((0,0),o[0]),1
    for j in range(len(o)-1):
        a-=d(o[j],o[j+1])
        c+=(0,1)[a>0]
    m=max(c,m)
print m

```

# **Explanation:**

The function calculates the distance between two points according to the given rules, the loop iterates through all permutations generated by the generator of the input and calculates the distance, if the distance is lesser than the candle lifespan it subtracts it and adds the place to the counter, if that counter is greater than the current max it substitutes it.

# **ungolfed:**

```
from itertools import permutations

def distance(start_pos, end_pos):
    distance = 0
    while start_pos != end_pos:
        mod_x = 1 if start_pos[0] < end_pos[0] else -1 if start_pos[0] > end_pos[0] else 0
        mod_y = 1 if start_pos[1] < end_pos[1] else -1 if start_pos[1] > end_pos[1] else 0
        start_pos = (start_pos[0] + mod_x, start_pos[1] + mod_y)
        distance += (1, 1.5)[mod_x and mod_y]
    return distance

lifespan, max_amount = 4, 0
for item in permutations([(1,1), (2,2), (3,3)]):
    lifespan_local, current = lifespan - distance((0,0), item[0]), 1
    for j in range(len(item) - 1):
        lifespan_local -= distance(item[j], item[j + 1])
        current += (0, 1)[lifespan_local > 0]
    max_amount = max(current, max_amount)
print max_amount

```

# Answer
> 1 votes
# PHP, 309 bytes

```
function j($x,$y,$c,$v){if($s=array_search([$x,$y],$v))unset($v[$s]);for($c--,$i=4;$c>0&&$i--;)$m=($n=j($x+[1,0,-1,0][$i],$y+[0,1,0,-1][$i],$c,$v))>$m?$n:$m;for($c-=.5,$i=4;$c>0&&$i--;)$m=($n=j($x+[1,-1,-1,1][$i],$y+[1,1,-1,-1][$i],$c,$v))>$m?$n:$m;return$s?++$m:$m;}echo j(0,0,$argv[1],array_chunk($argv,2));

```

Absolutely brute force and not even very short. Use like:

```
php -r "function j($x,$y,$c,$v){if($s=array_search([$x,$y],$v))unset($v[$s]);for($c--,$i=4;$c>0&&$i--;)$m=($n=j($x+[1,0,-1,0][$i],$y+[0,1,0,-1][$i],$c,$v))>$m?$n:$m;for($c-=.5,$i=4;$c>0&&$i--;)$m=($n=j($x+[1,-1,-1,1][$i],$y+[1,1,-1,-1][$i],$c,$v))>$m?$n:$m;return$s?++$m:$m;}echo j(0,0,$argv[1],array_chunk($argv,2));" 5 1 1 2 1 3 1 4 1 5 0 5 1

```

With more whitespace and saved in a file:

```
<?php
function j( $x, $y, $c, $v)
{
    if( $s = array_search( [$x,$y], $v ) )
        unset( $v[$s] );

    for( $c--, $i=4; $c>0 && $i--;)
        $m = ( $n=j($x+[1,0,-1,0][$i],$y+[0,1,0,-1][$i],$c,$v) )>$m ? $n : $m;

    for( $c-=.5, $i=4; $c>0 && $i--;)
        $m = ( $n=j($x+[1,-1,-1,1][$i],$y+[1,1,-1,-1][$i],$c,$v) )>$m ? $n : $m;

    return $s ? ++$m : $m;
}
echo j( 0, 0, $argv[1], array_chunk($argv,2) );

```

# Answer
> 1 votes
## Python, 175 bytes

```
def f(c,l):
 def r(t):p=abs(t[0]-x);q=abs(t[1]-y);return p+q-.5*min(p,q)
 v=0;x,y=0,0
 while c>0 and len(l)>0:
  l.sort(key=r);c-=r(l[0]);x,y=l.pop(0)
  if c>=0:v+=1
 return v

```

`c` is the lifespan of the candle, `l` is a list of tuples - village coordinates, `v` is the number of visited villages, `(x,y)` is pair of coordinates of the village Jack is currently in.

`r(t)` is a function which calculates the distance to the current position and is used to sort the list so that the closest becomes `l[0]`. The formula used is |Δx| + |Δy| - min(|Δx|, |Δy|) / 2.

Try it here!

# Answer
> 1 votes
## Racket

```
(define (dist x1 y1 x2 y2)     ; fn to find distance between 2 pts
  (sqrt(+ (expt(- x2 x1)2)
          (expt(- y2 y1)2))))

(define (fu x1 y1 x2 y2)       ; find fuel used to move from x1 y1 to x2 y2;
  (let loop ((x1 x1)
             (y1 y1)
             (fuelUsed 0))
    (let* ((d1 (dist (add1 x1) y1 x2 y2))        ; horizontal movement
           (d2 (dist x1 (add1 y1) x2 y2))        ; vertical movement
           (d3 (dist (add1 x1) (add1 y1) x2 y2)) ; diagonal movement
           (m (min d1 d2 d3))) ; find which of above leads to min remaining distance;
      (cond
        [(or (= d2 0)(= d1 0)) (add1 fuelUsed)]
        [(= d3 0) (+ 1.5 fuelUsed)]
        [(= m d1) (loop (add1 x1) y1 (add1 fuelUsed))]
        [(= m d2) (loop x1 (add1 y1) (add1 fuelUsed))]
        [(= m d3) (loop (add1 x1) (add1 y1) (+ 1.5 fuelUsed))]))))

(define (f a l)
  (define u (for/list ((i l))
    (fu 0 0 (list-ref i 0) (list-ref i 1))))  ; find fuel used for each point;
  (for/last ((i u)(n (in-naturals)) #:final (>= i a))
    n))

```

Testing:

```
(f 4 '((1 1) (2 2) (3 3))) ;-> 2
(f 5 '((1 1) (2 1) (3 1) (4 1) (5 0) (5 1))) ;-> 4

```

Output:

```
2
4

```

However, above code does not work for negative values of x and y.

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