title: My Pet Peeve Challenge

text:
# Question
Title: My Pet Peeve Challenge
There's something (well, many things ) that really annoys me. It is when dictionaries (English, not Pythonic) use the defining word itself to define the word, also called circular definitions. Example:

> reticence: the quality of being reticent

-- Apple Dictionary

> Circular definition: a definition that is circular

-- Wikipedia (in jest)

Anyway,

# Challenge

You are given a set of dictionary definitions. Your program should output the number of circular definitions in the input. As usual, code golf, lowest bytes wins, no standard loopholes, yada yada.

## Input

Input can be in any reasonable form, including:

* A dictionary (oh, the irony)
* A list of strings
* Line-by-line input, from STDIN or equivalent

You will be given the defined word (it is a single word without spaces) and its definition, possibly containing the defined word itself.

### Circular definitions?

A definition is circular for the purposes of this challenge if it satisfies one of the following conditions:

* The definition contains the defined word
* The definition contains the defined word minus one of these suffixes:
    + -ing
    + -ed
    + -ly
* The definition contains the defined word plus one of the above suffixes

## Output

You should output an integer stating the number of circular definitions in the input. If there are none, you can output zero, a falsy, or a nully.

Good luck!

## Leaderboards

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

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

```
# Language Name, N bytes

```

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

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

```

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

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

```

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

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

```

```
/* Configuration */

var QUESTION_ID = 100007; // Obtain this from the url
// It will be likes://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 47670; // 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;
}
```

```
<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
# Pyth, 28 bytes

Really want to condense the logic.

```
sm}hKm:k"(ing|ed|ly)$";cd;tK

```

Try it online here.
> 2 votes

# Answer
# Python, ~~187~~ 185, self-disqualified!

**EDIT**: I've decided to disqualify this due to its bugginess, but its good for the pun.

---

Takes a Pythonic dictionary (hehe) and outputs the number to the console. This is quite buggy, though, should've done more tests...

```
def c(i):
 for k, v in i.items():
  l,c,t,y="",0,k[-2:],k[:-2]
  if t=="ed":l=y
  if t=="ly":l=y
  if k[-3:]=="ing":l=k[:-3]
  if" "+k+" "in v:c+=1
  if" "+l in v:c+=1
 print(c)

```
> 0 votes

# Answer
# Python, 129 bytes

Takes a list of two item lists where the first item is the word and the second is the definition. It returns the amount circular definitions it found.

```
def f(d,n=0):
 for k,v in d:k,v=k.lower(),v.lower();n+=any(k+_ in v or k.rstrip(_)in v for _ in("","ing","ed","ly"))
 return n

```
> 0 votes

---
Tags: code-golf, natural-language
---


title: Generating Binary shapes

text:
# Question
Title: Generating Binary shapes
## How could we generate shapes or images using binary?

I got to messing around trying to create something that looked matrix like and got to thinking, wouldn't a great CodeGolf be to see who can make the best shortest code to generate a binary image?

Please advise me of any rules I should add.

### Rules:

* Create a binary image art of a Meme using 40 chars wide by 20 chars tall.
* Shortest code out of top 3 voted images wins.

### Example Output:

```
00000000000000000000000000000000000000000
00000000000000000000000000000000000000000
00000000000000000000000000000000000000000
00000000000000000000000000000000000000000
00000000000000000000000000000000000000000
00000000000000000000000000000000000000000
00000000000000000000000000000000000000000
00000000000000000000000000000000000000000
00000000001111000000000000011110000000000
00000000111111110000000001111111100000000
00000011110000111100001111000001111000000
00000011110000111100001111000001111000000
00000011110000111100001111000001111000000
00000011110000001111111100000001111000000
00000011110000000011110000000001111000000
00000011110000000000000000000001111000000
00000011110000000000000000000001111000000
00001111000000000000000000000000011110000
00111100000000000000000000000000000111100
11110000000000000000000000000000000001111

```

# Answer
> 7 votes
## YO DAWG, I HERD YOU LIKE ... (Python - 151)

```
a,b,c,d,e=9663681096,78383190025,559419527177,9663713289,628289966664
print'%040o\n'*20%tuple(map(lambda x:(x|x<<48|x<<96)>>21,[0,a,b,c]+[d]*5+[e])*2)

```

Output:

```
0000000000000000000000000000000000000000
0001100000111100000110000011110000011000
0011100001100110001110000110011000111000
0101100001100110010110000110011001011000
0001100001100110000110000110011000011000
0001100001100110000110000110011000011000
0001100001100110000110000110011000011000
0001100001100110000110000110011000011000
0001100001100110000110000110011000011000
0111111000111100011111100011110001111110
0000000000000000000000000000000000000000
0001100000111100000110000011110000011000
0011100001100110001110000110011000111000
0101100001100110010110000110011001011000
0001100001100110000110000110011000011000
0001100001100110000110000110011000011000
0001100001100110000110000110011000011000
0001100001100110000110000110011000011000
0001100001100110000110000110011000011000
0111111000111100011111100011110001111110

```

# Answer
> 4 votes
# QBASIC - 1157 Characters

Ok, this one isn't that short, but definitely qualifies for the meme factor.

```
CLS
l$="1"
FOR i=1 TO 20
s$=""
FOR j=1 TO 40
s$=s$+"0"
NEXT
?s$
NEXT
A=20
C=16
D=12
E=27
FOR i=2 TO 6
        b=ABS(4-i)
        LOCATE i,8-i:?1$
        LOCATE i,4+i:?1$
        LOCATE 4,b+5:?1$
        LOCATE i,22:?1$
        LOCATE i,13:?1$
        LOCATE 6,11+i:?1$
        LOCATE 6,A+i:?1$
        LOCATE 10-b,3+i:?1$
        LOCATE D-b,7:?1$
        LOCATE 6+i,13:?1$
        LOCATE 8,11+i:?1$
        LOCATE 6+i,17:?1$
        LOCATE D,11+i:?1$
        LOCATE 6+i,22:?1$
        LOCATE 6+i,26:?1$
        LOCATE D,A+i:?1$
        LOCATE 6+i,29:?1$
        LOCATE 8,E+i:?1$
        LOCATE 10,E+i:?1$
        LOCATE 9,34:?1$
        LOCATE 6+i,E+i:?1$
        LOCATE D+i,5:?1$
        LOCATE 14,b+6:?1$
        LOCATE C,b+6:?1$
        LOCATE 18,b+6:?1$
        LOCATE 15+b,9:?1$
        LOCATE D+i,17-i:?1$
        LOCATE D+i,13+i:?1$
        LOCATE C,b+14:?1$
        LOCATE 14,A+i:?1$
        LOCATE C,A+i:?1$
        LOCATE 18,A+i:?1$
        LOCATE C-b,22:?1$
        LOCATE C+b,26:?1$
        LOCATE 14,E+i:?1$
        LOCATE C,30+b:?1$
        LOCATE 18,E+i:?1$
        LOCATE D+i,29:?1$
NEXT

```

Here's a screen shot for the odd person who doesn't have QBasic installed.

# Answer
> 3 votes
## New\*** Can't Triforce (Perl, 85 chars)

```
map{$j=$_<10;$_=sprintf"%010d",1x($_%10+1);s/1(.*)/$&$1$`0/;say$_.($j?0 x20:$_)}0..19

```

output:

```
0000000001000000000000000000000000000000
0000000011100000000000000000000000000000
0000000111110000000000000000000000000000
0000001111111000000000000000000000000000
0000011111111100000000000000000000000000
0000111111111110000000000000000000000000
0001111111111111000000000000000000000000
0011111111111111100000000000000000000000
0111111111111111110000000000000000000000
1111111111111111111000000000000000000000
0000000001000000000000000000010000000000
0000000011100000000000000000111000000000
0000000111110000000000000001111100000000
0000001111111000000000000011111110000000
0000011111111100000000000111111111000000
0000111111111110000000001111111111100000
0001111111111111000000011111111111110000
0011111111111111100000111111111111111000
0111111111111111110001111111111111111100
1111111111111111111011111111111111111110

```

# Answer
> 2 votes
## The Weight Lifter *or* The Keyboard Player *or* ... (188 characters)

Not really too sure if this fits the `meme` requirement, but it is not *too* long I hope...

```
from math import*;r=range;q=r(20)
s=[["1"for x in q*2]for x in q];s[14][2:38]=["0"]*36
for j in r(18,21):
 for i in q:v=int(j+7*sin(i/7.0*pi));s[i][v]=s[i][40-v]="0"
for l in s:print''.join(l)

```

> Output:

# Answer
> 1 votes
**The Mandelbrot set written in 194 characters of coffeescript on node.js:**

```
m=(x,y)->
 a=x
 b=y
 z=0
 for i in [0..9]
  return 0 if z > 4
  l=y*y
  z=x*x+l
  y=2*x*y+b
  x=x*x-l+a
 1
console.log (m x,y for x in [-1.5..0.5] by 2/39).join '' for y in [-1.3..1.3] by 2.6/19

```

# Answer
> 1 votes
I could make no sense out of that knowyourmeme site. So here's a riff on your first reference: something matrix like.

## Postscript ~~(287)~~ (310)

*Edit:* Better output (more 'ones', less apparent *waves*).

Run with `gs -dNODISPLAY -q -- matrix.ps 60`. Replace `60` with the number of columns to generate.

```
%!
<<
0{(1)print}
1{(0)print}
10{()=}
/#{load exec}
/rho ARGUMENTS 0 get cvi
/enn 0
/set{[rho{rand rand 30 mod 2 idiv 3 mul neg bitshift}repeat]}
/lin{[exch{dup 2 idiv exch 2 mod #}forall]10 #}
/zer{/enn enn 1 add def enn 6 mod 0 eq{dup 0 exch{add}forall rho 1.1 exp lt{pop set}if}if}
>>begin
set{lin zer}loop

```

It generates infinite output like this, mostly ones with vertical zero "signals":

```
011001110110110001100101111110011111001101101111110111011101
010011111101100011110110110111010101001101111111111110011101
111111110111110001111100010110110011011101111111110110011101
110110111111110011111011110110111110111111101111110111111101
010101111111110101101100011100100110001101101111111110011101
110101111111101101101010011110101111001101111111110111111111
011111111111101001100111011100000011111101101111110111011011
010111111111111101101100111110100001101111111111111110011101
010100111111101001111011011111011001111111111111111110111001
011111111111101011110100011101001101101111111111110110111111
111100111111111101111100011111110001101111101111111111011011
111100111111101011110001011101111101101111111111111111111101
111101111111111001111001011111010101111101101111111110111111
011110111111111001100101011111011101111111101111111111111101
011101111111111101110001111111011101111111111111111111011101
111101111111111111110111111111111111111111111111110110011111
011101111111101011100111011111110101111111101111111111111111
011100111111111101111011111111111111111101101111110111011101
011111111111101111110111111111010111111111111111111111111111
011100111111111011110101111111111101111111111111111111011111
011101111111111111110101111111110111111111111111111111011111
111111111111111101111111111111111111111111111111111111011111
111111111111101101111101111111111111111111111111111111011111
111111111111101111111111111111111111111111111111111111011111
111111111111101111111111111111111111111111111111111111111111
111111111111111111111111111111111111111111111111111111011111
010011010111011111001101111111011001011011011011111010111111
110011011111001111001111011100111011111011110011111101100110
110101111111111011111011111000110101110011011010111111110110
010111111111001111111001111000110001111111011111111110101110
010001111111111111110001011100110001100011110111101010111101
011011111011001011111001011100111111110111110110111011100110
011001011111101111110111011100110111100111111110111111111100
011101111011101111110001111110111111111111110111111010111111
011101111011101011111101111110110011011111010111101110101111
111101111011111011110001011101110001111011011111111000111100
111101011111011111111011111110111001101111111111111101111111
111101111111001111111111111110110011000011111111111100100111
11010101111110^C
Command terminated

```

# Answer
> 1 votes
# 05AB1E, 354 bytes

```
•4¤Q}qV¸dí¼ÔÁpoEW"Eáãø>jÎ®\å¢»kq;Çl:&»"6*²h†z¬e™/[Î§Ä…èRÝ\iåÚˆ2-dŠX‹öäùœUqBÍ¸©Ùì)z«×íP÷»éuøêB9hŽÒ>·Ä.ãò‰Z‡*…4:W&.½ñÝm·›mìQ[Š,í5(/øé‡”¿ô¿®P4^eã$–…l÷¿6?z·RˆN¥eWIãÀ}áÎåÇ)PÍ2ž?cLnfýµ‚áIípÐ¿ÖÝYp~FüÇ@jÉZßÝÓóÜåÀÑ=EôÿwµŽk`"ÍÝ8*$ˆœ¢7œÄÕw(A®?®h:rGPO¯7¥‘Å)UôÛ€¦—“ÇÙ(áÖ©£ŠÂ”áÊ¡õZ‘]½Æ¬„Š½Mâ$¾)Yé:â#æ»«Z=hõ¹‚.ðË7_Î#@¹OH—?9PyÆIð¼S%³zëJïzGÍä\{g…Ë;nEwÀ@É³_ˆ92ŽÚ@C’•b81ô}»

```

Try it online!

```
111111111111111110001111111111111111100000000000111111111111100000001111111111111
111111111111111111001111111111111111110000000111111111111111100001111111111111111
111111111111111111101111111111111111111000011111111111111111100111111111111111111
111111110000011111111111111100000111111100111111111111111111101111111111111111111
001111110000011111110011111100000111111101111111000000011111111111110000000111111
001111110000011111110011111100000111111111111110000000000000111111100000000000000
001111111111111111100011111111111111111011111110000000000000111111100000000000000
001111111111111111000011111111111111110011111110000000000000111111100001111111111
001111111111111100000011111111111111000011111110000000000000111111100001111111111
001111110000000000000011111100000000000011111110000000000000111111100001111111111
001111110000000000000011111100000000000011111110000000000000111111100000000111111
001111110000000000000011111100000000000001111111000000011111111111110000000111111
111111111100000000001111111111000000000000111111111111111111101111111111111111111
111111111100000000001111111111000000000000011111111111111111100111111111111111111
111111111100000000001111111111000000000000000111111111111111100001111111111111111
111111111100000000001111111111000000000000000000111111111111100000001111110001111
000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000111111111111111000000000111111111111111111111100000000000000000
000000000000000011111111111111111100000000111111111111111111111100000000000000000
000000000000000111111111111111111100000000111111111111111111111100000000000000000
000000000000000111111100000111111100000000111111111111111111111100000000000000000
000000000000000111111100000000000000000000001111111000000011111100000000000000000
000000000000000111111100000000000000000000001111111000000000000000000000000000000
000000000000000011111111100000000000000000001111111111111111100000000000000000000
000000000000000001111111111111000000000000001111111111111111100000000000000000000
000000000000000000011111111111110000000000001111111111111111100000000000000000000
000000000000000000000011111111111000000000001111111111111111100000000000000000000
000000000000000000000000000111111100000000001111111000000000000000000000000000000
000000000000000000000000000111111100000000001111111000000011111100000000000000000
000000000000000111111100000111111100000000111111111111111111111100000000000000000
000000000000000111111111111111111101111110111111111111111111111101111110000000000
000000000000000111111111111111111001111110111111111111111111111101111110000000000
000000000000000011111111111111100001111110111111111111111111111101111110000000000

```

---
Tags: code-golf, ascii-art, popularity-contest, binary
---


title: Alphabet wings!

text:
# Question
Title: Alphabet wings!
Your task is to print this exact text:

```
az                                               za
abyz                                           zyba
abcxyz                                       zyxcba
abcdwxyz                                   zyxwdcba
abcdevwxyz                               zyxwvedcba
abcdefuvwxyz                           zyxwvufedcba
abcdefgtuvwxyz                       zyxwvutgfedcba
abcdefghstuvwxyz                   zyxwvutshgfedcba
abcdefghirstuvwxyz               zyxwvutsrihgfedcba
abcdefghijqrstuvwxyz           zyxwvutsrqjihgfedcba
abcdefghijkpqrstuvwxyz       zyxwvutsrqpkjihgfedcba
abcdefghijklopqrstuvwxyz   zyxwvutsrqpolkjihgfedcba
abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba
  abcdefghijklopqrstuvwxyzyxwvutsrqpolkjihgfedcba
    abcdefghijkpqrstuvwxyzyxwvutsrqpkjihgfedcba
      abcdefghijqrstuvwxyzyxwvutsrqjihgfedcba
        abcdefghirstuvwxyzyxwvutsrihgfedcba
          abcdefghstuvwxyzyxwvutshgfedcba
            abcdefgtuvwxyzyxwvutgfedcba
              abcdefuvwxyzyxwvufedcba
                abcdevwxyzyxwvedcba
                  abcdwxyzyxwdcba
                    abcxyzyxcba
                      abyzyba
                        aza

```

The following are allowed:

* Leaving out trailing spaces at the end of lines
* Doing everything in uppercase instead of lowercase
* Trailing newlines

Remember, this is , so the code with the smallest number of bytes wins.

# Answer
> 4 votes
# 05AB1E, 36 bytes

Code:

```
A13F¦¨DAsKDˆ13N>-·ð×«û,}¯R¦ð2×ì€û.c,

```

Doesn't work on TIO yet, but it does work with the offline interpreter.

# Answer
> 4 votes
# Vim, ~~94~~ 91 bytes

This one was tricky.

```
:se ri|h<_
jjYZZpqqpi  <Esc>@=17-line('.')
 xxYq11@qy2G:g/^/m0
qqD0Pwq12@q"0pdkGqq$y0A<C-r>"<Esc>kq24@q

```

Here it is in action:

Here's an xxd dump with the unprintable characters:

```
0000000: 3a73 6520 7269 7c68 3c5f 0a6a 6a59 5a5a  :se ri|h<_.jjYZZ
0000010: 7071 7170 6920 201b 403d 3137 2d6c 696e  pqqpi  .@=17-lin
0000020: 6528 272e 2729 0a20 7878 5971 3131 4071  e('.'). xxYq11@q
0000030: 7932 473a 672f 5e2f 6d30 0a71 7144 3050  y2G:g/^/m0.qqD0P
0000040: 7771 3132 4071 2230 7064 6b47 7171 2479  wq12@q"0pdkGqq$y
0000050: 3041 1222 1b6b 7132 3440 71              0A.".kq24@q

```

## Explanation:

Credit for the first two lines goes to DJMcMayhem and Lynn.

```
:se ri|       " Turn on reverse-insert mode
h<_<CR>jjYZZ  " Yank the lowercase alphabet from help
p             " Paste it
qq            " Start recording a macro
  pi  <Esc>              " Paste, then insert two spaces before the cursor
  @=17-line('.')<CR> xx  " Delete the middle two letters
  Y                      " Yank the current line
q11@q         " Stop recording, execute 11 times
y2G           " Yank everything except the first (blank) line
:g/^/m0<CR>   " Reverse the order of every line
qq            " Record
  D0P           " Delete until the end of the line (i.e. just the letters)
  w             " Skip to the first letter on the next line
q12@q         " Stop recording, execute 12 times
"0p           " Paste the lines yanked above
dk            " Delete this line and the line above
G             " Go to the last line
qq            " Record
  $y0           " Move to the end of the line, then yank all but the last letter
  A<C-r>"<Esc>  " Append (in insert mode so it's reversed)
  k             " Go up a line
q24@q         " Stop recording, execute 24 times

```

# Answer
> 3 votes
## Batch, ~~395~~ 391 bytes

```
@echo off
set q=
set r=
set s=
set t=
for /l %%i in (1,1,51)do call set s= %%s%%
for %%p in (az by cx dw ev fu gt hs ir jq kp lo mn)do call:u %%p
for /l %%i in (1,1,12)do call:l
exit/b
:u
set p=%1
set q=%q%%p:~,1%
set r=%p:~1%%r%
set s=%s:~4%%p:~1%
set t=%p:~,1%%t%
echo %q%%r%%s%%t%
exit/b
:l
set q=  %q:~,-1%
set r=%r:~1%
set s=%s:~,-1%
set t=%t:~1%
echo %q%%r%%s%%t%

```

# Answer
> 3 votes
# PHP, 158 Bytes

```
for(;$i++<25;)echo($a=str_pad)(($t=($f=substr)($j=join(range(a,z)),0,$x=$i>13?13-$i%13:$i).$f($j,-$x)).$a("",51-$i*4," ").$f(strrev($t),$i>12),51," ",2)."\n";

```

# Answer
> 2 votes
## Pyke, 27 bytes

```
13FhG'<R>+26{)DFl826^)_+msX

```

Try it here!

```
13F          )              -    for i in range(13):
   h                        -       i+1
    G'<R>+                  -      alphabet[:^]+alphabet[-^:]
          26{               -     ^.rpad(26)
              D        +    -   ^ + V
               F     )      -     for i in ^^:
                l8          -       ^.lstrip()
                  26^       -      ^.lpad(26)
                      _     -    reversed(^)
                        ms  -  map(palindromise, ^)
                          X - splat(^)

```

# Answer
> 1 votes
# J, 52 bytes

```
(,.}.@|."1)(}:,|.|.~"#:_2*i.@#)(a.{~97+],25-|.)\i.13

```

## Usage

```
   (,.}.@|."1)(}:,|.|.~"#:_2*i.@#)(a.{~97+],25-|.)\i.13
az                                               za
abyz                                           zyba
abcxyz                                       zyxcba
abcdwxyz                                   zyxwdcba
abcdevwxyz                               zyxwvedcba
abcdefuvwxyz                           zyxwvufedcba
abcdefgtuvwxyz                       zyxwvutgfedcba
abcdefghstuvwxyz                   zyxwvutshgfedcba
abcdefghirstuvwxyz               zyxwvutsrihgfedcba
abcdefghijqrstuvwxyz           zyxwvutsrqjihgfedcba
abcdefghijkpqrstuvwxyz       zyxwvutsrqpkjihgfedcba
abcdefghijklopqrstuvwxyz   zyxwvutsrqpolkjihgfedcba
abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba
  abcdefghijklopqrstuvwxyzyxwvutsrqpolkjihgfedcba
    abcdefghijkpqrstuvwxyzyxwvutsrqpkjihgfedcba
      abcdefghijqrstuvwxyzyxwvutsrqjihgfedcba
        abcdefghirstuvwxyzyxwvutsrihgfedcba
          abcdefghstuvwxyzyxwvutshgfedcba
            abcdefgtuvwxyzyxwvutgfedcba
              abcdefuvwxyzyxwvufedcba
                abcdevwxyzyxwvedcba
                  abcdwxyzyxwdcba
                    abcxyzyxcba
                      abyzyba
                        aza

```

# Answer
> 1 votes
# Jelly, 35 bytes

```
Ḳṙ-K
CrịØaṙµL26_⁶ẋ;
13RµŒḄÇ€Ñ€⁸¦ŒBY

```

**TryItOnline!**

### How?

```
13RµŒḄÇ€Ñ€⁸¦ŒBY - Main link: no arguments
13R             - range(13) -> [1,2,3,...,12,13]
   µ            - monadic chain separation
    ŒḄ          - bounce    -> [1,2,3,...,12,13,12,...,3,2,1]
      Ç€        - call last link (2) as a monad for €ach
           ¦    - apply to indexes
          ⁸     -    left argument (13R)
        Ñ€      -    next link (1) as a monad for €ach
            ŒB  - bounce with vectorisation at depth 1 (creates the right hand side)
              Y - join with line feeds

CrịØaṙµL26_⁶ẋ; - Link 2: make the left side of a row, with spaces at the left: i (e.g. 3)
C              - complement (1-i)       e.g. 1-3=-2
 r             - range(1-i, i)          e.g. [-2,-1,0,1,2,3]
  ị            - index into
   Øa          - lowercase alphabet     e.g. "xyzabc"
      µ        - monadic chain separation
     ṙ         - rotate left by i       e.g. "abcxyz"
        26_    - literal 26 minus
       L       - length                 e.g. 26-6=20
           ⁶   - literal ' '
            ẋ  - repeat 26-length times e.g. "                    "
             ; - concatenate            e.g. "                    abcxyz"

Ḳṙ-K - Link 1, swap spaces to the right: left half of a row
Ḳ    - split on spaces                  e.g. [[],[],...,"abcxyz"]
 ṙ   - rotate left by
  -  - literal -1                       e.g. ["abcxyz",...,[],[]]
   K - join with spaces                 e.g. "abcxyz                    "

```

# Answer
> 1 votes
# Bubblegum, 165 bytes

Hexdump:

```
00000000: 4aac 5220 0d54 25f2 7201 e896 8b03 86a2  J.R .T%.r.......
00000010: 1806 60ab bcd5 fa99 19a7 2f43 ec3a 77e9  ..`......./C.:w.
00000020: 129d a2f9 e58c 9e29 3e64 d3e5 88df 29d9  .......)>d....).
00000030: a9f9 654f be29 dda8 7965 4b4d ca56 6aba  ..eO.)..yeKM.Vj.
00000040: ac19 a47c 518d ca92 532a 6668 aacc c55f  ...|Q...S*fh..._
00000050: 2a27 6e54 a652 a46a c446 65ac 64aa 0768  *'nT.R.j.Fe.d..h
00000060: 5886 da49 4d8f cd94 be71 53db d966 4ad7  X..IM....qS..fJ.
00000070: 620a c136 2771 8124 0b07 2822 20a7 c07c  b..6'q.$..(" ..|
00000080: 424c 9c30 52c2 4011 1235 1019 c12f 4344  BL.0R.@..5.../CD
00000090: ec8d 9010 7a12 1784 701b a8d4 a884 48e3  ....z...p.....H.
000000a0: 5050 9508 00                             PP...

```

Just ran the string through Zopfli for many iterations.

# Answer
> 0 votes
## JavaScript (ES6), ~~215~~ 211 bytes

```
_=>[...Array(25)].map((_,i)=>` `.repeat(++i>13&&i*2-26)+a.slice(0,j=i>13?26-i:i)+a.slice(-j)+` `.repeat(i<13&&51-i*4)+b.slice(i>12,j)+b.slice(-j),a=`abcdefghijklmnopqrstuvwxyz`,b=[...a].reverse().join``).join`\n`

```

Where `\n` represents the literal newline character. This just edged out my character building answer at 213 bytes:

```
_=>[...Array(25)].map((_,i)=>` `.repeat(51).replace(/./g,(b,j)=>(j=i<13?j<i?j+10:j<h?36+j-h:j<51-h?0:j<51-i?86-h-j:60-j:j<h-26?0:j<i?36+j-h:j<26?j+10:j<51-i?60-j:j<77-h?86-h-j:0)?j.toString(36):b,h=++i+i)).join`\n`

```

# Answer
> 0 votes
# Ruby, 109 bytes

Full program that prints a string as required by the question. One byte could be saved by changing to a lambda function that returns an array of strings.

```
s=[*(?a..?z)]*""
puts (-12..12).map{|i|(t="%#{(i<=>0)*26}s"%(s[0,13-i.abs]+s[13+i.abs..26]))+t[0,25].reverse}

```

**Ungolfed**

```
s=[*(?a..?z)]*""                     #Convert range 'a'..'z' into an array, then a string.
puts (-12..12).map{|i|               #Iterate over -12..12, make an array of lines then print them.
  (t=                                #t= left side of pattern.
    "%#{(i<=>0)*26}s"%               #Compose format string %-26s or %26s to pad to 26 chars and left/right justify depending on sign.
     (s[0,13-i.abs]+s[13+i.abs..26]) #In this format, print the appropriate number of beginning and ending letters of the alphabet.
   )+
     t[0,25].reverse                 #Righthand side of pattern. Remove the rightmost column from t, reverse it, and concatenate to left side.
}

```

# Answer
> 0 votes
# Japt, 49 bytes

```
;1o14@CjX26-2*XÃê £Y<12?X+S²p12-Y :S²pY-12 +X êÃ·

```

I mainly wrote this answer to try out the (somewhat) new `ê` function (bounce; `"abc" -> "abcba"`). Test it online!

### Explanation

```
;1o14@CjX26-2*X} ê £Y<12?X+S²p12-Y :S²pY-12 +X ê} ·

;                                                    // Set C to "abc...xyz".
 1o14                                                // Create the range [1, 14).
     @         }                                     // Map each item X by this function:
         26-2*X                                      //   Take 26 - 2X.
      CjX                                            //   Remove this many chars from index X in C.
                                                     // We now have ["az", "abyz", ..., "abc...xyz"].
                 ê                                   // Bounce. This gives us ["az", "abyz", ..., "abc...xyz", ..., "abyz", "az"].
                   £                            }    // Map each item X and index Y by this function:
                    Y<12?                            //   If Y is less than 12,
                         X+S²p12-Y                   //   append 12 - Y double-spaces.
                                   :S²pY-12 +X       //   Otherwise, prepend Y - 12 double-spaces.
                                                     //   This gives us the left half of the wings.
                                               ê     //   Bounce. This creates the right half.
                                                  ·  // Join the resulting array with newlines.
                                                     // Implicit: output last expression

```

# Answer
> 0 votes
# C#, 473 Bytes

*"Concat", "Reverse", "Substring"... So many big words...*

Golfed:

```
string A(){string a="abcdefghijklmnopqrstuvwxyz",r=string.Concat(a.Reverse()),o="",x="",y="",z="";int i=0;var l=new List<string>();for(i=0;i<13;i++){x=a.Substring(0,i);y=r.Substring(0,i);z=x+string.Concat(y.Reverse())+string.Concat(Enumerable.Repeat(" ",51-i*4))+y+string.Concat(x.Reverse())+"\n";o+=z;l.Add(z.Replace(" ","").Replace("zz","z"));}o+=a+r.Substring(1,r.Length-1)+"\n";l.Reverse();for(i=0;i<12;i++)o+=string.Concat(Enumerable.Repeat(" ",i+i+2))+l[i];return o;}

```

Ungolfed:

```
public string A()
{
  string a = "abcdefghijklmnopqrstuvwxyz", r = string.Concat(a.Reverse()), o = "",x="",y="",z="";
  int i=0;
  var l = new List<string>();
  for (i = 0; i < 13; i++)
  {
    x = a.Substring(0, i);
    y = r.Substring(0, i);
    z = x + string.Concat(y.Reverse()) +
      string.Concat(Enumerable.Repeat(" ", 51-i*4)) +
      y + string.Concat(x.Reverse()) + "\n";
    o += z;
    l.Add(z.Replace(" ", "").Replace("zz", "z"));
  }
  o += a + r.Substring(1, r.Length - 1) + "\n";
  l.Reverse();
  for (i = 0; i < 12; i++)
    o += string.Concat(Enumerable.Repeat(" ", i + i + 2)) + l[i];
  return o;
}

```

Outputs:

```
az                                               za
abyz                                           zyba
abcxyz                                       zyxcba
abcdwxyz                                   zyxwdcba
abcdevwxyz                               zyxwvedcba
abcdefuvwxyz                           zyxwvufedcba
abcdefgtuvwxyz                       zyxwvutgfedcba
abcdefghstuvwxyz                   zyxwvutshgfedcba
abcdefghirstuvwxyz               zyxwvutsrihgfedcba
abcdefghijqrstuvwxyz           zyxwvutsrqjihgfedcba
abcdefghijkpqrstuvwxyz       zyxwvutsrqpkjihgfedcba
abcdefghijklopqrstuvwxyz   zyxwvutsrqpolkjihgfedcba
abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba
  abcdefghijklopqrstuvwxyzyxwvutsrqpolkjihgfedcba
    abcdefghijkpqrstuvwxyzyxwvutsrqpkjihgfedcba
      abcdefghijqrstuvwxyzyxwvutsrqjihgfedcba
        abcdefghirstuvwxyzyxwvutsrihgfedcba
          abcdefghstuvwxyzyxwvutshgfedcba
            abcdefgtuvwxyzyxwvutgfedcba
              abcdefuvwxyzyxwvufedcba
                abcdevwxyzyxwvedcba
                  abcdwxyzyxwdcba
                    abcxyzyxcba
                      abyzyba
                        aza

```

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


title: North by North by North by South East

text:
# Question
Title: North by North by North by South East
Given a string of N, S, E and W, output a bearing (angle clockwise from North in degrees), correct to 5 decimal places.

In traditional compass notation, a string is made up of only 2 of these characters (like NNW or ESE). **Here you must also accept strings that contain all 4 (like WNNNSE)**. Using only 2 symbols allows humans to intuitively understand the meaning. Allowing 4 symbols makes it horrible to read, but allows shorter ways of describing a bearing to a given accuracy.

*(As pointed out in the comments by user2357112, it turns out you can prove that for any given bearing, the 4 symbol string will be exactly the same length as the 2 symbol string, so I've based this challenge on a false assumption. Hopefully this lack of a practical purpose doesn't detract from your enjoyment of the challenge...)*

The exact method is described below, and is equivalent to the traditional notation (it expands on it rather than changing it).

# Input

* The input is a single string containing only the characters `NESW`.
* The input may be a sequence of characters if you prefer, provided this does not include any preprocessing. For example, taking a nested list `[N, [E, [S, [W]]]]` to help with the order of processing is not permitted.
* Taking different characters is not permitted. You may not take a string of `1234` instead of `NESW`.

# Output

* The output must be a decimal number or string representation of one (not a rational/fraction).
* Trailing zeros do not need to be displayed. If the bearing is `9.00000`, then the output `9` also counts as correct to 5 decimal places.
* The output is in the range \[0, 360). That is, including 0 but excluding 360.
* Correctness is checked by rounding the output to 5 decimal places. If the bearing is 0.000005, this rounds to 0.00001. Outputs 0.00001 and 0.000005 are both correct.
* Output in scientific notation for some inputs is acceptable. For example, `1e-5` instead of `0.00001`.

# Conversion

* The single character compass points `N`, `E`, `S`, and `W` correspond to 0, 90, 180, and 270 degrees respectively.
* Prepending one of these to a string results in the bearing that bisects the bearing of the single character and the bearing of the original string.
* The closest of the two possible bisecting bearings is chosen, so that NE represents 45 degrees, not 225 degrees.
* This is unambiguous except where the angle to be bisected is 180 degrees. Therefore `NS`, `SN`, `WE`, and `EW` correspond to undefined bearings, and the input will never end in any of these. They may however appear anywhere else in the input string, as this causes no ambiguity.
* If the final two characters are identical, the final character will be redundant as the bisection will return the same bearing. Since this adds nothing to the notation, your code does not need to handle this. Therefore `NN`, `EE`, `SS`, and `WW` correspond to undefined bearings, and the input will never end in any of these. They may however appear anywhere else in the input string.

# Examples

```
N: 0
E: 90
S: 180
SE: halfway between S and E: 135
NSE: halfway between N and SE: 67.5
NNSE: halfway between N and NSE: 33.75
NNNSE: halfway between N and NNSE: 16.875
NNNNSE: halfway between N and NNNSE: 8.4375

```

# Test cases

A submission is only valid if it gives correct output for all of the test cases. Note that the test cases push to the limits of what can be handled with double precision. For languages that default to single precision, you will probably need to spend the bytes to specify double precision in order to get correct outputs.

Test case outputs are shown rounded to 5 decimal places, and also to arbitrary precision. Both are valid outputs.

```
WNE 337.5 337.5
WEN 337.5 337.5
WEWEWEWEWEWEWEWEWEWEWEN 330.00001 330.000007152557373046875
NESWNESWNESWNESWNESWNESWNESW 90 89.99999932944774627685546875
NNNNNNNNNNNNNNNNNNNNNNNE 0.00001 0.0000107288360595703125
NNNNNNNNNNNNNNNNNNNNNNNW 359.99999 359.9999892711639404296875
SNNNNNNNNNNNNNNNNNNNNNNNE 90.00001 90.00000536441802978515625
SNNNNNNNNNNNNNNNNNNNNNNNW 269.99999 269.99999463558197021484375

```

# Scoring

This is . The score is the length of the source code in bytes, and the shortest wins.

---

# Pedantry

> I made the mistake of thinking that "North by North West" was a valid compass direction. A happy mistake, since it led to a challenge idea, but I then discovered from the Wikipedia page:
> *"The title of the Alfred Hitchcock 1959 movie, North by Northwest, is actually not a direction point on the 32-wind compass, but the film contains a reference to Northwest Airlines."*
> It also turns out that the method used for this challenge is only consistent with traditional compass points up to and including the 16 point compass. The 32-wind compass described on that page is subtly different and I have conveniently overlooked its existence for this challenge.
> Finally, for anyone who thinks I should use "Southeast" instead of "South East", it seems to be a regional difference.

# Answer
# JavaScript (ES6), ~~84~~ ~~80~~ ~~78~~ ~~74~~ 72 bytes

*Saved a byte thanks to @Titus, 1 thanks to @Neil*

```
f=([c,...s],b="NESW".search(c))=>b*90-(s[0]?(b-=f(s)/90)-4*(b*b>4):0)*45

```

It took a while, but I think I've finally perfected the formula...

### Test snippet

```
f=([c,...s],b="NESW".search(c))=>b*90-(s[0]?(b-=f(s)/90)-4*(b*b>4):0)*45
g=(s,n)=>console.log('f("'+s+'"):',f(s),"expected:",n)

g("N", 0)
g("NE", 45)
g("E", 90)
g("SE", 135)
g("S", 180)
g("SW", 225)
g("W", 270)
g("NW", 315)
g("WNE", 337.5)
g("WEN", 337.5)
g("WEWEWEWEWEWEWEWEWEWEWEN", 330.00001)
g("NESWNESWNESWNESWNESWNESWNESWNESWNESWNESWNESWNESWNESW", 90)
g("NNNNNNNNNNNNNNNNNNNNNNNE", 0.00001)
g("NNNNNNNNNNNNNNNNNNNNNNNW", 359.99999)
g("SNNNNNNNNNNNNNNNNNNNNNNNE", 90.00001)
g("SNNNNNNNNNNNNNNNNNNNNNNNW", 269.99999)
```

### Explanation

Let's start with the simplest case: a single-char string. The result is simply its (0-indexed) position in the string `NESW`, multiplied by 90.

For a two-char string, the result lies halfway between the result of the first char and the result of the second. However, there's a catch: if the absolute difference between the two is greater than 180 (e.g. `NW` or `WN`), we must 180 to the angle so that it's not pointing the opposite direction.

For any longer string, the result lies halfway between the result of the first char and the result of the rest of the string. This can be generalized in the following way:

* If the input is a single char, return its index in the string `NESW` times 90.
* Otherwise, return the index of the first char in the string `NESW` times 45, plus half the result of the rest of the string; add an extra 180 if the absolute difference between the two is greater than 90.
> 13 votes

# Answer
## C#6, ~~226~~ ~~217~~ ~~207~~ 185 bytes

```
using System.Linq;double N(string s){double b=f(s.Last());foreach(var c in s.Reverse()){b=(b+f(c)+(b-f(c)>2?4:f(c)-b>2?-4:0))/2;b=(b+4)%4;}return b*90;}int f(char x)=>"NESW".IndexOf(x);

```

Edit: -10 bytes by "borrowing" idea from ETHproductions's submission
-22 bytes thanks to @Titus

Ungolfed

```
// Call this method
double N(string s){
    // Initialize bearing with last direction
    double b=f(s.Last());
    // Do backward. Doing last direction once more doesn't impact result
    foreach(var c in s.Reverse()){
        // Average current bearing with new bearing, adjusted with wrapping
        b=(b+f(c)+(b-f(c)>2?4:f(c)-b>2?-4:0))/2;
        // Make bearing back to range [0,4)
        b=(b+4)%4;
    }
    // Change from "full circle = 4" unit to degree
    return b*90;
}
// helper method to convert direction to bearing. This returns bearing with full circle = 4.
int f(char x)=>"NESW".IndexOf(x);

```
> 10 votes

# Answer
# PHP, ~~95~~ ~~88~~ ~~86~~ ~~100~~ ~~127~~ ~~104~~ 101 bytes

* -7 bytes with the null coalescing operator
* -2 bytes by not replacing `N` (and more, because that allows to put the translation to the loop head: `N` is truthy, but evaluates to `0` in the calculation.)
* +41 bytes for fixing the bisection (*cough*)
* -7 bytes directly and -16 indirectly inspired by @ETHproductions´ code
* -3 bytes by replacing `strtr` with one of my bit jugglings

---

```
for($i=strlen($s=$argv[1]);$i--;$p=($q+$p=$p??$q)/2+2*(abs($q-$p)>2))$q=ord($s[$i])/.8+3&3;echo$p*90;

```

This is officially the first time ever that I use the null coalescing operator. Run with `-r`.

## PHP 7.1

Negative string offsets in the upcoming PHP version will save 12 bytes:
Replace `strlen($s=$argv[1])` with `0` and `$s` with `$argv[1]`.

---

**Free bytes for (almost) everyone:**

* Calculating with 0,1,2,3 instead of 0,90,180,270 and multiplying the final result with 90 will save two bytes *and* probably allow further golfing.
* There are some patterns in the ASCII codes of the characters. Try one of these in your language:
    + `(a/2%6+2)%5`
    + `a<87?a/2&3^3:3` or `a/2&3^3*(a<87)`
    + `a&1?a&2|a/4&1:0`
    + `a/.8-1&3`
> 8 votes

# Answer
# Python 3, ~~146~~ ~~145~~ ~~117~~ ~~107~~ ~~97~~ ~~94~~ ~~93~~ 92 bytes

```
f(s):u='NESW'.find(s[0])*90;return(u+f(s[1:]))/2+180*(abs(u-f(s[1:]))>180)if s[1:]else u

```

Call `f` with the string.
> 5 votes

# Answer
# C, 184 bytes

```
double h(char c){return ((c=='E')+(c=='S')*2+(c=='W')*3);}double d(char*s){double f=h(*s);if(s[1]){double t=f;f=(f+d(s+1)/90)/2;if(((t-f)>1)||((f-t)>1))f+=2;if(f>=4)f-=4;}return f*90;}

```

**Ungolfed**

```
// a helper function
double direction_(char ch)
{
    if (ch=='N')
        return 0.;
    else if (ch=='E')
        return 90.;
    else if (ch=='S')
        return 180.;
    else
        return 270.;
}

// this is the main function to call
double direction(char* str)
{
    double fAngle = direction_(str[0]);
    if (str[1])
    {
        double tmp = fAngle + direction(str+1);
        if (tmp>=360.)
            tmp-=360.;
        tmp/=2;

        if (((tmp-fAngle)>90.) || ((tmp-fAngle)<-90.))
        { //  check if we need to take the "other side"; if the resulting angle is more than 90 degrees away, we took the wrong on
            if (tmp>=180.)
                tmp-=180.;
            else
                tmp+=180.;
        }
        fAngle = tmp;
    }
    return fAngle;
}

```
> 5 votes

# Answer
## Python 3, 133 113 bytes

Just improving on @L3viathan's answer because I just made this account and therefore can't make comments yet.

```
d={"N":0,"E":.5,"S":1,"W":1.5}
def B(s):
 b=d[s[-1]]
 for c in s[::-1]:b=(b+d[c])/2+(abs(b-d[c])>1)
 return b*180

```
> 5 votes

# Answer
# 05AB1E, ~~48~~ ~~42~~ ~~37~~ 32 bytes

Saved 6 bytes thanks to Emigna. Saved 5 bytes thanks to Titus' idea to work on range \[0,4\[ and multiply by 90 at the end. Saved 5 bytes thanks to Adnan's mastery of ancient xor/modulo metamorphosis.

So every angle is reduced from range \[0,360\[ to range \[0,4\[ throughout the execution. Result is then multiplied by 90 and displayed.

```
Ç30^5%R¬U¦vXy+;DX-Ä0›2*+4%U}X90*

It can be divided into two sequentially called subprograms.
First program: convert input string into an array of the corresponding angles in range [0,4[
Ç      Take the ascii value of all input characters
 30^5% Dark ascii manipulation that yields [0,1,2,3] for [N,E,S,W]

Now we have an array of integers in range [0,4[.

Second program: actually compute the final angle
R                          Reverse the array
 ¬                         Take the first value (the last of the non-reversed array)
  U                        Pop it from the stack and set X to the same value
   ¦                       Strip the first element
    v                      For each remaining element
     Xy+;                  Compute the average value between the leftmost value and X
         DX-Ä0›            Push 1 if angular distance cast to integer is > 0 (i.e. if it is >= 1), 0 otherwise. It's equivalent to checking >= 90 degrees
               2*+         Multiply by 2 (=2 if angular distance is >= 1 and 0 otherwise) and add it to the formerly computed average value. It's equivalent to multiplying by 180
                  4%       Perform mod 4. It's equivalent to performing mod 360
                    U      Store the result back to X
                     }     End for, mandatory if input has only one character
                      X90* Push X*90 and implicitly display it

```

Try it online!

Potential axes of golfing:

* Not sure if that mod 4 is required (it would save 2 bytes). All test cases work without it, but maybe there exists a tricky case. A mathematical proof to either validate it or nullify it would be top-notch.
* There is no implicit stuff besides displaying the result (closing quote marks, closing brackets).
> 5 votes

# Answer
# Dyalog APL, ~~55~~ ~~45~~ 38 bytes

### Solution

Requires `⎕IO←0`, which is default on many systems. Asks for direction.

```
360|÷○÷180×12○(+÷(|+))/¯12○○2÷⍨'NES'⍳⍞

```

### Explanation

Goes around the problem by converting each letter to a complex number 1∠*θ**a* \+ *b · i*, then doing a sum reduction from right-to-left (APL's forte) while normalizing at each step. The final *θ* is then converted to degrees and normalized to be within \[0, 360):

`'NES'⍳⍞` the indices of each input letter in "NES"; N→0, E→1, S→2, anything else→3

`○2÷⍨` convert to angles in radians; *θ* = *π* · ***x***2

`¯12○` convert to complex numbers on the unit circle; *ei · θ*

`(`...`)/` reduce the list with... (i.e. insert the function between the elements of...)

`+÷(|+)` ... the normalized sum; ***x****n* \- 1 \+ ***x****n*|***x****n* \- 1 \+ ***x****n*|

`12○` convert to angle; *θ*

`÷○÷180×` convert to degrees; 1*π* · 1180 · ***x***

`360|` division remainder when divided by 360

TryAPL online!

### Anecdote

If input and output was as orthogonal complex units, the entire solution would be just:

```
(+÷(|+))/

```

The rest of the code is parsing input and formatting output.
> 3 votes

# Answer
## R, 172 146 bytes

```
z=rev((0:3*90)[match(scan(,""),c("N","E","S","W"))]);p=z[1];l=length(z);for(i in 2:l)p=(p+z[i])/2+(abs(p-z[i])>180)*180;if(l<2)p=z;sprintf("%f",p)

```

**Ungolfed**

```
z=rev((0:3*90)[match(scan,""),c("N","E","S","W"))]); #1
p=z[1];                                              #2
l=length(z)                                          #3
for(i in 2:l)p=(p+z[i])/2+(abs(p-z[i])>180)*180;     #4
if(l<2)p=z                                           #5
sprintf("%f",p)                                      #6

```

**Explained**

1. Read input from stdin
    * Match input by index to `c("N","E","S","W")`
    * From matched indices: match to the vector of degrees `0:3*90` (instead of `c(0,90,180,270)`)
    * Reverse and store as `z`
2. Initialize `p` to the degree equivalent to last char in input
3. Store length of input as `l`
4. Iteratively, calculate the closest of the two possible bisecting bearings.
5. If only one input is given, set `p` to `z`
6. Format and print

Try the test cases on R-fiddle (note that this is a function due to `scan` not working on R-fiddle)
> 3 votes

# Answer
# Haskell, ~~109 105~~ 103 bytes

```
h=180
a#b|abs(a-b)<h=n|n>h=n-h|1>0=n+h where n=(a+b)/2 -- calculates the new "mean" on the cirlce
f 'N'=0                                          -- translates characters to angles
f 'E'=90
f 'S'=h
f _=270
foldr1(#).map f                                  -- traverses the whole string

```

Thanks for -2 byte @xnor!
> 3 votes

# Answer
# Common Lisp, ~~347~~ 327 bytes

*Thanks to @Titus for taking off a few*

This can probably be golfed more, but at least it works (I think):

```
(defun d(c)(if(eql c #\N)0(if(eql c #\E)1(if(eql c #\S)2(if(eql c #\W)3)))))(defun m(a b)(if(> a b)(rotatef a b))(if(<(+(- 4 b)a)(- b a))(+(/(+(- 4 b)a)2)b)(+(/(- b a)2)a)))(defun f(s)(let((c))(setf c(d(char s(1-(length s)))))(do((a)(p(-(length s)2)(1- p)))((< p 0))(setf a(char s p))(setf c(m(d a)c)))(format t"~5$"(* c 90))))

```

Usage:

```
* (f "WNE")
337.50000
NIL

```

Function `d` takes a character `N`, `E`, `W`, or `S` and returns the appropriate degree. Function `m` gets the approprate combined degree of two given directions. Function `f` iterates through the provided string, computes the appropriate degree, and prints it as a floating point.
> 2 votes

# Answer
# Befunge, ~~183~~ ~~181~~ 175 bytes

```
>~#+:#25#%6*#/`#2_$>5%4*:00p"Z}"4*:***20g#v_+2/00g10g-:8`\0\-8`+!v
v5:+*:*:"d"/+55+5$_^#!:\p01/**:*4"}Z":p020<%**:*"(2Z"+**5*:*"0}"!<
>5>+#<%#56#58#:*#/+\#5:#5_$$$,,,".">:#,_@

```

Try it online!

**Explanation**

This follows a similar algorithm to many of the other answers, only it's using fixed point calculations emulated with integers since Befunge doesn't support floating point.

Thanks to @Titus for the ASCII-to-int routine.

```
 ~ : 5 6* ` _$        while ((c = getchar()) > 30)  // ends with any ctrl char or EOF
> + 2 %6 / 2            push(c / 2 % 6 + 2)         // partial conversion to int

                      do {
  5%                    dir = pop() % 5             // completes the conversion to int
  4*:00p                dir *= 4; lowres_dir = dir  // used by the 180-flip calculation
  "Z}"4*:***            dir *= 22500000             // this is 90000000 / 4
  20g_                  if (!first_pass) {
    +2/                   dir = (dir+last_dir)/2    // last_dir is second item on stack
    00g10g-               diff = lowres_dir - last_lowres_dir
    :8`\0\-8`+!!          flip = diff>8 || -diff>8
    "}0"*:*5**+           dir += flip * 180000000   // add 180 degrees if we need to flip
    "Z2("*:**%            dir %= 360000000          // keep within the 360 degree range
                        }
  020p                  first_pass = false
  :"Z}"4*:**/10p        last_lowres_dir = dir / 22500000
  \                     last_dir = dir              // saved as second item on stack
  :!_                 } while (!stack.empty())

$                     pop()                         // this leaves the final dir on top
5+55+/                dir = (dir + 5)/10            // round down to 5 decimal places
"d":*:*+              dir += 100000000              // add a terminating digit
                      while (true) {                // convert into chars on stack
:55 + % 6 8 * +\ : _    push(dir%10+'0'); if (!dir) break
   > < 5 5 : /+ 5 5     dir /= 10
                      }

$$$                   pop() x 3                     // drop the chars we don't need
,,,                   putchar(pop()) x 3            // output first three chars
"."                   push('.')                     // add a decimal point
>:#,_@                while(c=pop()) putchar(c)     // output the remaining chars

```
> 2 votes

# Answer
# APL (Dyalog Classic), ~~30~~ 27 bytes

```
90×(4|2÷⍨+-4×2<∘|-)/'NES'⍳⎕

```

Try it online!
> 1 votes

---
Tags: code-golf
---


# Question
Title: On this site we obey the laws of thermodynamics!
And in particular the second law: *the entropy of an isolated system undergoing an irreversible process increases with time*.

For this challenge,

* An "*isolated system*" will be taken to be a *program or function* (abbreviated as "program" from now on);
* The "*irreversible process*" will be *execution* of code;
* The passing of "*time*" will correspond to *iterated executions of the program's output*, considered as a new program;
* "*Entropy*" will be taken as *Shannon's first-order entropy* (to be defined below), which is a measure of how diverse the characters of the string are.

## The challenge

Your program should produce a non-empty string that when executed as a program in the same language produces a string with more entropy than the previous one. Infinitely iterating this execute-the-output process must produce a **strictly increasing sequence of entropy values**.

The strings can contain any Unicode 9.0 characters. The sequence of strings must be deterministic (as opposed to random).

The **entropy** for a given string will be defined as follows. Identify its unique characters and their number of occurrences in the string. The frequency *pi* of the *i*-th unique character is the number of occurrences of that character divided by the length of the string. The entropy is then

where the sum is over all unique characters of the string. Technically, this corresponds to the entropy of a discrete random variable with distribution given by the frequencies observed in the string.

Let *Hk* denote the entropy of the string produced by the *k*-th program, and let *H*0 denote the entropy of the initial program's code. Also, let *L*0 denote the length of the initial program in characters. The sequence {*Hk*} is monotone as per the challenge requirements, and is bounded (because the number of existing characters is finite). Therefore it has a limit, *H*.

The **score** of a submission will be (*H**H*0)/*L*0:

* The numerator, *H**H*0, reflects to what extent your code "obeys" the law of increasing entropy over an infinite time span.
* The denonimator, *L*0, is the length of the initial code in characters (not in bytes).

The code with the **highest score wins**. Ties will be resolved in favour of the earliest submission/edit.

To compute the entropy of a string, you can use the JavaScript snippet (courtesy of @flawr and with corrections by @Dennis and @ETHproductions) at the end of this post.

If obtaining the limit *H* is difficult in your specific case, you can use any lower bound, say *H*20, to compute the score (so you would use (*H*20*H*0)/*L*0). But in any case, the infinite sequence of entropies must be strictly increasing.

Please include an explanation or short proof that the sequence of entropies is increasing, if that's not evident.

## Example

In a fictional language, consider the code `aabcab`, which when run produces the string `cdefgh`, which when run produces `cdefghi`, which ...

The unique characters of the original code are `a`, `b` and `c`, with respective frequencies 3/6, 2/6 and 1/6. Its entropy is 1.4591. This is *H*0.

The string `cdefgh` has more entropy than `aabcab`. We can know this without computing it because for a given number of characters the entropy is maximized when all the frequencies are equal. Indeed, the entropy *H*1 is 2.5850.

The string `cdefghi` again has more entropy than the previous one. We can know without computing because adding a non-existing character always increases the entropy. Indeed, *H*2 is 2.8074.

If the next string were `42` the chain would be invalid, because *H*3 would be 1, smaller than 2.8074.

If, on the other hand, the sequence went on producing strings of increasing entropy with limit *H* = 3, the score would be (3−1.4597)/6 = 0.2567.

## Acknowledgments

Thanks to

* @xnor for his help improving the challenge, and in particular for convincing me that infinite chains of increasing entropy obtained from iterated execution are indeed possible;
* @flawr for several suggestions, including modifying the score function, and for writing the very useful snippet;
* @Angs for pointing out an essential drawback in a previous definition of the score function;
* @Dennis for a correction in the JavaScript snippet;
* @ETHproductions for another correction in the snippet;
* @PeterTaylor for a correction in the definition of entropy.

## Snippet for calculating the entropy

```
function calculateEntropy() {
  var input = document.getElementById("input").value; // fetch input as string
  if (/[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)|([^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/.test(input)) {
    document.getElementById("output").innerHTML = " invalid (unmatched surrogates)";
    return;
  }
  var charArray = input.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^]/g);
  var frequency = {};
  for (var ind in charArray) {
    frequency[charArray[ind]] = 0;
  }
  var total = 0;
  for (var ind in charArray) {
    frequency[charArray[ind]] ++;
    total++;
  }
  var entropy = 0;
  for (var key in frequency) {
    var p = frequency[key] / total;
    entropy -= p * Math.log2(p);
  }
  document.getElementById("output").innerHTML = " " + entropy;
};
```

```
<button type="button" onClick="javascript:calculateEntropy();">calculate</button>Entropy: <span id="output">NaN</span>
<br/>
<textarea id="input">asdf asdf</textarea>
```

# Answer
> 5 votes
# Jelly, 0.68220949

```
“ȷ6ȷ5rỌ,®Ṿ€ṁṾY⁾©v⁸⁵”©v⁵

```

**H90 = 19.779597644909596802, H0 = 4.088779347361360882, L0 = 23**

I used long doubles to compute **H90**. Double precision floats incorrectly reported that **H47 \< H46**

The first program prints

```
“…”
“ȷ6ȷ5rỌ,®Ṿ€ṁṾY⁾©v⁸⁵”©v1010

```

where  serves as a placeholder for all Unicode characters with code points between **100,000** and **1,000,000**. The actual length is **900,031** characters.

The seconds program prints

```
“…”
“ȷ6ȷ5rỌ,®Ṿ€ṁṾY⁾©v⁸⁵”
“…”
“ȷ6ȷ5rỌ,®Ṿ€ṁṾY⁾©v⁸⁵”©v101010

```

which, in turn, prints

```
“…”
“ȷ6ȷ5rỌ,®Ṿ€ṁṾY⁾©v⁸⁵”
“…”
“ȷ6ȷ5rỌ,®Ṿ€ṁṾY⁾©v⁸⁵”
“…”
“ȷ6ȷ5rỌ,®Ṿ€ṁṾY⁾©v⁸⁵”©v10101010

```

etc.

None of these programs works in the online interpreter, which has a **100 KB** output limit. However, if we modify the program to print `0123456789` instead of the aforementioned **900,000** Unicode characters, you can Try it online!

# Answer
> 6 votes
# MATLAB, ~~9.6923e-005~~ 0.005950967872272

```
H0 =  2.7243140535197345, Hinf = 4.670280547752703, L0 = 327

```

This new version is an improved version of the first "proof of concept". In this version I get a great score increase from the first iteration. This was achieved by "blowing up" the output of the first program, that is replicated by all the subsequent ones. Then I also tried to find the minimal `H0` by just appending the most common symbol of the code as many times as possible. (This had obviously a limit, since it does not only decrease `H0` but also increases `L0` at the same time. You can see the development of the score plotted against the size of the program where the size is varied by just adding or removing `1`.) The subsequent iterations still are equivalent to the previous version below.

```
a=['ns}z2e1e1116k5;6111gE16:61kGe1116k6111gE16:6ek7;:61gg3E1g6:6ek7;:61gg3E1'];11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111;;disp(['[''',a+1,'''];',0,'a=[''',a,'''];',0,[a-10,']]);'],0,[a-10,']]);']]);

```

### Previous version:

```
H0 = 4.22764479010266, Hinf = 4.243346286312808, L0 = 162

```

The following code is inspired by the matlab quine. It basically outputs just itself again *twice*. The clue is that for any iteration we have `n` lines of code and `n-1` newline symbols `\n`. So as `n` approaches to infinity, the ratio of lines of code to newlines approaches 1, and at the same time this guarantees that we have a strictly monotonous growth in entropy. That also means we can easily calculate `Hinf` by just considering the zero-th generation code with equally many newlines as lines of code. (Which one can experimentally confirm, as it converges quite quickly.)

```
a=['ns}z2e1kGe1116k6111gE16;:61kGe1116k6111gE16;:6ek7;:61gg3E1g6;:6ek7;:61gg3E1'];
disp(['a=[''',a,'''];',10,'a=[''',a,'''];',10,[a-10,']]);'],10,[a-10,']]);']]);

```

---
Tags: string, code-challenge, sequence
---


title: Do the auto-super-logarithm

text:
# Question
Title: Do the auto-super-logarithm
Given a positive integer *n* and a number *a*, the *n*-th tetration of *a* is defined as *a*^(*a*^(*a*^(...^*a*))), where *^* denotes exponentiation (or power) and the expression contains the number *a* exactly *n* times.

In other words, tetration is right-associative iterated exponentiation. For *n*=4 and *a*=1.6 the tetration is 1.6^(1.6^(1.6^1.6)) ≈ 3.5743.

The inverse function of tetration with respect to *n* is the super-logarithm. In the previous example, 4 is the super-logarithm of 3.5743 with "super-base" 1.6.

# The challenge

Given a positive integer *n*, find *x* such that *n* is the super-logarithm of itself in super-base *x*. That is, find *x* such that *x*^(*x*^(*x*^(...^*x*))) (with *x* appearing *n* times) equals *n*.

# Rules

Program or function allowed.

Input and output formats are flexible as usual.

The algorithm should theoretically work for all positive integers. In practice, input may be limited to a maximum value owing to memory, time or data-type restrictions. However, the code must work for inputs up to `100` at least in less than a minute.

The algorithm should theoretically give the result with `0.001` precision. In practice, the output precision may be worse because of accumulated errors in numerical computations. However, the output must be accurate up to `0.001` for the indicated test cases.

Shortest code wins.

# Test cases

```
1    ->  1
3    ->  1.635078
6    ->  1.568644
10   ->  1.508498
25   ->  1.458582
50   ->  1.448504
100  ->  1.445673

```

# Reference implementation

Here's a **reference implementation** in Matlab / Octave (try it at Ideone).

```
N = 10; % input
t = .0001:.0001:2; % range of possible values: [.0001 .0002 ... 2]
r = t;
for k = 2:N
    r = t.^r; % repeated exponentiation, element-wise
end
[~, ind] = min(abs(r-N)); % index of entry of r that is closest to N
result = t(ind);
disp(result)

```

For `N = 10` this gives `result = 1.5085`.

The following code is a **check** of the output precision, using variable-precision arithmetic:

```
N = 10;
x = 1.5085; % result to be tested for that N. Add or subtract 1e-3 to see that
            % the obtained y is farther from N
s = num2str(x); % string representation
se = s;
for n = 2:N;
    se = [s '^(' se ')']; % build string that evaluates to iterated exponentiation
end
y = vpa(se, 1000) % evaluate with variable-precision arithmetic

```

This gives:

* For `x = 1.5085`: `y = 10.00173...`
* For `x = 1.5085 + .001`: `y = 10.9075`
* For `x = 1.5085 - .001` it gives `y = 9.23248`.

so `1.5085` is a valid solution with `.001` precision.

# Answer
> 3 votes
# Dyalog APL, ~~33~~ 25 bytes

Needs `⎕IO←0` which is default on many systems.

```
⌈/⎕(⊢×⊣≥(*/⍴)¨)(1+⍳÷⊢)1E4

```

Theoretically calculates for all integers, but practically limited to very small one only.

TryAPL online!

# Answer
> 10 votes
# Haskell, ~~55~~ ~~54~~ 52 bytes

```
s n=[x|x<-[2,1.9999..],n>iterate(x**)1!!floor n]!!0

```

Usage:

```
> s 100
1.445600000000061

```

Thanks to @nimi for 1 byte!
Thanks to @xnor for 2!

# Answer
> 6 votes
## Javascript, ES6: 77 bytes / ES7: ~~57~~ 53 bytes

### ES6

```
n=>eval("for(x=n,s='x';--x;s=`Math.pow(x,${s})`);for(x=2;eval(s)>n;)x-=.001")

```

### ES7

Using `**` as suggested by DanTheMan:

```
n=>eval("for(x=2;eval('x**'.repeat(n)+1)>n;)x-=.001")

```

### Example

```
let f =
n=>eval("for(x=n,s='x';--x;s=`Math.pow(x,${s})`);for(x=2;eval(s)>n;)x-=.001")

console.log(f(25));
```

# Answer
> 4 votes
# J, ~~39~~ ~~31~~ 28 bytes

```
(>./@(]*[>^/@#"0)1+i.%])&1e4

```

Based on the reference implementation. It is only accurate to three decimal places.

Saved 8 bytes using the method from @Adám's solution.

## Usage

Extra commands used to format multiple input/output.

```
   f =: (>./@(]*[>^/@#"0)1+i.%])&1e4
   (,.f"0) 1 3 6 10 25 50 100
  1      0
  3  1.635
  6 1.5686
 10 1.5084
 25 1.4585
 50 1.4485
100 1.4456
   f 1000
1.4446

```

## Explanation

```
(>./@(]*[>^/@#"0)1+i.%])&1e4  Input: n
                         1e4  The constant 10000
(                      )      Operate on n (LHS) and 10000 (RHS)
                   i.           The range [0, 10000)
                      ]         Get (RHS) 10000
                     %          Divide each in the range by 10000
                 1+             Add 1 to each
     (          )               Operate on n (LHS) and the range (RHS)
             #"0                  For each in the range, create a list of n copies
          ^/@                     Reduce each list of copies using exponentation
                                  J parses from right-to-left which makes this
                                  equivalent to the tetration
        [                         Get n
         >                        Test if each value is less than n
      ]                           Get the initial range
       *                          Multiply elementwise
 >./@                           Reduce using max and return

```

# Answer
> 4 votes
# Python, 184 bytes

```
def s(n):
 def j(b,i):
  if i<0.1**12:
   return b
  m = b+i
  try:
   v = reduce(lambda a,b:b**a,[m]*n)
  except:
   v = n+1
  return j(m,i/2) if v<n else j(b,i/2)
 return j(1.0,0.5)

```

Test output (skipping the actual print statements):

```
   s(1) 1.0
   s(3) 1.63507847464
   s(6) 1.5686440646
  s(10) 1.50849792026
  s(25) 1.45858186605
  s(50) 1.44850389566
 s(100) 1.44567285047

```

# Answer
> 4 votes
# Mathematica, ~~40~~ 33 bytes

*Thanks to murphy for an almost 20% savings!*

```
1//.x_:>x+.001/;Nest[x^#&,1,#]<#&

```

`Nest[x^#&,1,n]` produces the nth tetration of x. So `Nest[x^#&,1,#]<#` tests whether the (input)th tetration of x is less than (input). We simply start at x=1 and add 0.001 repeatedly until the tetration is too large, then output the last x value (so the answer is guaranteed to be larger than the exact value, but within 0.001).

As I'm slowly learning: `//.x_:>y/;z` or `//.x_/;z:>y` means "look for anything that matches the template x, but only things for which the test z returns true; and then operate on x by the rule y; repeatedly until nothing changes". Here the template `x_` is just "any number I see", although in other contexts it could be further constrained.

When the input is at least 45, the tetration increases so rapidly that that last step causes an overflow error; but the value of x is still updated and output correctly. Decreasing the step-size from 0.001 to 0.0001 fixes this problem for inputs up to 112, and gives a more precise answer to boot (and still runs quickly, in about a quarter second). But that's one extra byte, so forget that!

Original version:

```
x=1;(While[Nest[x^#&,1,#]<#,x+=.001];x)&

```

# Answer
> 3 votes
## Racket 187 bytes

```
(define(f x n)(define o 1)(for((i n))(set! o(expt x o)))o)
(define(ur y(l 0.1)(u 10))(define t(/(+ l u)2))(define o(f t y))
(cond[(<(abs(- o y)) 0.1)t][(> o y)(ur y l t)][else(ur y t u)]))

```

Testing:

```
(ur 1)
(ur 3)
(ur 6)
(ur 10)
(ur 25)
(ur 50)
(ur 100)

```

Output:

```
1.028125
1.6275390625
1.5695312499999998
1.5085021972656247
1.4585809230804445
1.4485038772225378
1.4456728475168346

```

Detailed version:

```
(define (f x n)
  (define out 1)
  (for((i n))
    (set! out(expt x out)))
  out)

(define (uniroot y (lower 0.1) (upper 10))
  (define trying (/ (+ lower upper) 2))
  (define out (f trying y))
  (cond
    [(<(abs(- out y)) 0.1)
     trying]
    [(> out y)
     (uniroot y lower trying)]
    [else
      (uniroot y trying upper)]))

```

# Answer
> 2 votes
# Perl 6, 42 bytes

```
{(0,.0001…2).min:{abs $_-[**] $^r xx$_}}

```

( Translation of example Matlab code )

## Test:

```
#! /usr/bin/env perl6
use v6.c;
use Test;

my &code = {(0,.0001…2).min:{abs $_-[**] $^r xx$_}}

my @tests = (
  1   => 1,
  3   => 1.635078,
  6   => 1.568644,
  10  => 1.508498,
  25  => 1.458582,
  50  => 1.448504,
  100 => 1.445673,
);

plan +@tests + 1;

my $start-time = now;

for @tests -> $_ ( :key($input), :value($expected) ) {
  my $result = code $input;
  is-approx $result, $expected, "$result ≅ $expected", :abs-tol(0.001)
}

my $finish-time = now;
my $total-time = $finish-time - $start-time;
cmp-ok $total-time, &[<], 60, "$total-time.fmt('%.3f') is less than a minute";

```

```
1..8
ok 1 - 1 ≅ 1
ok 2 - 1.6351 ≅ 1.635078
ok 3 - 1.5686 ≅ 1.568644
ok 4 - 1.5085 ≅ 1.508498
ok 5 - 1.4586 ≅ 1.458582
ok 6 - 1.4485 ≅ 1.448504
ok 7 - 1.4456 ≅ 1.445673
ok 8 - 53.302 seconds is less than a minute

```

# Answer
> 1 votes
# PHP , 103 Bytes

```
$z=2;while($z-$a>9**-9){for($r=$s=($a+$z)/2,$i=0;++$i<$n=$argv[1];)$r=$s**$r;$r<$n?$a=$s:$z=$s;}echo$s;

```

# Answer
> 1 votes
**Axiom 587 bytes**

```
l(a,b)==(local i;i:=1;r:=a;repeat(if i>=b then break;r:=a^r;i:=i+1);r);g(q,n)==(local r,y,y1,y2,t,v,e,d,i;n<=0 or n>1000 or q>1000 or q<0 => 0;e:=1/(10**(digits()-3));v:=0.01; d:=0.01;repeat(if l(v,n)>=q then break;v:=v+d;if v>=1 and n>25 then d:=0.001;if v>=1.4 and n>40 then d:=0.0001;if v>=1.44 and n>80 then d:=0.00001;if v>=1.445 and n>85 then d:=0.000001);if l(v-d,n)>q then y1:=0.0 else y1:=v-d;y2:=v;y:=l(v,n);i:=1;if abs(y-q)>e then repeat(t:=(y2-y1)/2.0;v:=y1+t;y:=l(v,n);i:=i+1;if i>100 then break;if t<=e then break;if y<q then y1:=v else y2:=v);if i>100 then output "#i#";v)

```

less golfed + numbers

```
l(a,b)==
  local i
  i:=1;r:=a;repeat(if i>=b then break;r:=a^r;i:=i+1)
  r
g(q,n)==
 local r, y, y1,y2,t,v,e,d, i
 n<=0 or n>1000 or q>1000 or q<0 => 0
 e:=1/(10**(digits()-3))
 v:=0.01; d:=0.01
 repeat  --cerco dove vi e' il punto di cambiamento di segno di l(v,n)-q
    if l(v,n)>=q then break
    v:=v+d
    if v>=1     and n>25 then d:=0.001
    if v>=1.4   and n>40 then d:=0.0001
    if v>=1.44  and n>80 then d:=0.00001
    if v>=1.445 and n>85 then d:=0.000001
 if l(v-d,n)>q then y1:=0.0
 else               y1:=v-d
 y2:=v; y:=l(v,n); i:=1  -- applico il metodo della ricerca binaria
 if abs(y-q)>e then      -- con la variabile i di sicurezza
    repeat
       t:=(y2-y1)/2.0; v:=y1+t; y:=l(v,n)
       i:=i+1
       if i>100 then break
       if t<=e  then break
       if  y<q  then y1:=v
       else          y2:=v
 if i>100 then output "#i#"
 v

(3) -> [g(1,1), g(3,3), g(6,6), g(10,10), g(25,25), g(50,50), g(100,100)]
   Compiling function l with type (Float,PositiveInteger) -> Float
   Compiling function g with type (PositiveInteger,PositiveInteger) ->
      Float

   (3)
   [1.0000000000 000000001, 1.6350784746 363752387, 1.5686440646 047324687,
    1.5084979202 595960768, 1.4585818660 492876919, 1.4485038956 661040907,
    1.4456728504 738144738]
                                                             Type: List Float

```

# Answer
> 1 votes
# Common Lisp, 207 bytes

```
(defun superlog(n)(let((a 1d0)(i 0.5))(loop until(< i 1d-12)do(let((v(or(ignore-errors(reduce #'expt(loop for q below n collect(+ a i)):from-end t))(1+ n))))(when(< v n)(setq a (+ a i)))(setq i(/ i 2)))) a))

```

Using `reduce` with `:from-end t` avoids the need of doing a "reversing exponentiation" intermediate lambda (basically `(lambda (x y) (expt y x))`, saving 14 bytes (12, if you remove removable spaces).

We still need to handle float overflow, but an `ignore-errors` form returns `nil` if an error happened, so we can use `or` to provide a default value.

---
Tags: code-golf, math, number
---


title: This Is A Self-Referential Problem

text:
# Question
Title: This Is A Self-Referential Problem
# Tupper's Self-Referential Formula (copied from Wikipedia)

Tupper's self-referential formula is a formula defined by Jeff Tupper that, when graphed in two dimensions at a very specific location in the plane, can be "programmed" to visually reproduce the formula itself. It is used in various math and computer science courses as an exercise in graphing formulae.

$$ \frac{1}{2} \< \left\lfloor \text{mod}\left( \left\lfloor \frac{y}{17} \right\rfloor 2^{ -17 \lfloor x \rfloor -\text{mod}\left( \lfloor y \rfloor ,17 \right) } ,2 \right) \right\rfloor $$

where \\$\lfloor\cdot\rfloor\\$ is the floor function.

Let \\$k\\$ be the following 543-digit number: `960939379918958884971672962127852754715004339660129306651505519271702802395266424689642842174350718121267153782770623355993237280874144307891325963941337723487857735749823926629715517173716995165232890538221612403238855866184013235585136048828693337902491454229288667081096184496091705183454067827731551705405381627380967602565625016981482083418783163849115590225610003652351370343874461848378737238198224849863465033159410054974700593138339226497249461751545728366702369745461014655997933798537483143786841806593422227898388722980000748404719`

If one graphs the set of points \\$(x, y)\\$ in \\$0 \le x \< 106\\$ and \\$k \le y \< k + 17\\$ satisfying the inequality given above, the resulting graph looks like this (note that the axes in this plot have been reversed, otherwise the picture comes out upside-down):

# So what?

The interesting thing about this formula is that it can be used to graph any possible black and white 106x17 image. Now, actually searching through to search would be extremely tedious, so there's a way to figure out the k-value where your image appears. The process is fairly simple:

1. Start from the bottom pixel of the first column of your image.
2. If the pixel is white, a 0 will be appended to the k-value. If it is black, append a 1.
3. Move up the column, repeating step 2.
4. Once at the end of the column, move to the next column and start from the bottom, following the same process.
5. After each pixel is analyzed, convert this binary string to decimal, and multiply by 17 to get the k-value.

# What's my job?

Your job is to create a program which can take in any 106x17 image, and output its corresponding k-value. You can make the following assumptions:

1. All images will be exactly 106x17
2. All images will only contain black (#000000) or white (#FFFFFF) pixels, nothing in between.

There's a few rules, too:

1. Output is simply the k-value. It must be in the proper base, but can be in any format.
2. Images must be read from either a PNG or PPM.
3. No standard loopholes.

# Test Images

\[ \] should produce ~1.4946x10542

\[ \] should produce ~7.2355x10159

\[ \] should produce 21801 * 17

\[ \] should produce (21802-1) * 17

Check out this Gist for the exact solutions.

This is , so least number of bytes wins.

---

**Helpful Links**

Wikipedia

Wolfram Mathworld

# Answer
> 13 votes
# CJam, 16

```
l,l~q:~f*/W%ze_b

```

With big thanks to Dennis. Try it online

In case you're having problems with the url, this is the input I tested:

```
P1
106 17
0000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000011111100000000000000000000000
0000000000000000000000000000000000000000000000000000000000000111111000
0000011111100110000000000000000000000000000000000000000000000000000000
0000000000000000000000000110011111100000100111100001000000000000001100
0110000000000000000000000000000000000000000000000000000000001000011110
0100010011111100001000000000000100101001110000000000000000000000000000
0011000000000000000000000100001111110010010110000110001000000000000100
0110010010000000011000000000000000000100100000000000000000000100011000
0110101111000000111111000000000001000110010011111100100100111001111100
0111001011110000000000000011111100000011111111000000110111000000000001
0000100111100000110000110001100000101000001100001000000000000011101100
0000111110110000001000010000000000010010000100100110011001100100100110
0100110010011001000000000000100001000000110110011000011000010000000000
0100110001001001100110011000001001100100110010011001000000000000100001
1000011001100111111111001100000000000100110001001001100110011001111001
1001001100100110010000000000001100111111111001101111111111111100000000
0001001010010010011001100101000110011001100000110000100000000000001111
1111111111010111001001001110000000000000110001101101100110011000111001
1001100111110011110000000000000001110010010011100010001001000100000000
0000000000000000000000000000000000000000000000000000000000000000000000
1000100100010000100000000001000000000000000000000000000000000000000000
0000000000000000000000000000000000001000000000010000010000000010000000
0000000000000000000000000000000000000000000000000000000000000000000000
0001000000001000000011111111000000000000000000000000000000000000000000
0000000000000000000000000000000000000000111111110000

```

I used the format that GIMP generated when exporting as ASCII pbm, with the comment removed.

**Explanation:**

```
l,    read the first line ("P1" magic number) and get its length (2)
l~    read and evaluate the second line (106 17)
q     read the rest of the input (actual pixels)
:~    evaluate each character ('0' -> 0, '1' -> 1, newline -> nothing)
f*    multiply each number by 17
/     split into rows of length 106
W%    reverse the order of the rows
z     transpose
e_    flatten (effectively, concatenate the lines)
      now we have all the pixels in the desired order, as 0 and 17
b     convert from base 2 "digits" to a number

```

# Answer
> 17 votes
# Pyth - 21 bytes

Simple to do with pyth's `i` base conversion. Takes input as `PBM` file name and reads using `'` command. I had to use `!M` to negate blacks and whites. Everything else is self-explanatory.

```
*J17i!MsC_cJrstt.z7 2

```

Try it here online. (Web interpreter can't read files, so is modified and takes file as input).

# Answer
> 9 votes
# Python 2: 133 110 bytes

A first attempt in python using PIL:

```
from PIL.Image import*
j=open(input()).load()
a=k=0
while a<1802:k=(j[a/17,16-a%17][0]<1)+k*2;a+=1
print k*17

```

Thanks to helpful commenters below

# Answer
> 7 votes
# C#, 199

This was fun! There's nothing wrong with reloading a bitmap 106 * 17 times, right? I did it as a function to save some bytes, not sure if that's legal.

```
BigInteger s(string i){return (Enumerable.Range(0,106).SelectMany(x=>Enumerable.Range(0,17).Select(y=>new BigInteger(new Bitmap(i).GetPixel(x,y).B==0?1:0)).Reverse()).Aggregate((x,y)=>(x<<1)+y)*17);}

```

`i` is the input file name.

Also, as a single expression, just because it is one expression, with `i` provided or subbed (167 bytes)

```
(Enumerable.Range(0,106).SelectMany(x=>Enumerable.Range(0,17).Select(y=>new BigInteger(new Bitmap(i).GetPixel(x,y).B==0?1:0)).Reverse()).Aggregate((x,y)=>(x<<1)+y)*17)

```

# Answer
> 2 votes
# Wolfram Language (Mathematica) ~~69~~ 50 Bytes

Update: After revisiting this code a few years later due to @Matt's comment, I've found a few bytes of savings. Note that the test pictures must be `Binarized` first, because they are 24 bit color PNGs as downloaded from the posted question, instead of being monochrome format as posted in the assumptions.

```
17Fold[#+##&,1-Join@@Reverse/@Thread@ImageData@#]&

```

old code

```
17*FromDigits[1-Flatten[Reverse/@Transpose[ImageData@Binarize@#]],2]&

```

This function will reproduce the image:

```
   ArrayPlot[Table[Boole[1/2<Floor[Mod[Floor[y/17]2^(-17Floor[x]-Mod[Abs[y],17]),2]]],{y,1+#,17+#},{x,106,1,-1}]]&

```

---
Tags: code-golf, image-processing
---


title: Write a third order quine

text:
# Question
Title: Write a third order quine
This challenge is an extension of 'Golf a mutual quine'.

Using three languages of your choice, create a third order Ouroboros program.

That is, in language A, write a program pA which outputs program pB in language B. Program pB should output program pC in language C, which in turn outputs the original program pA in language A.

No two languages in A, B, and C can be the same or subsets or supersets of each other. **None of pA, pB or pC may be identical.**

For example, a Haskell program outputs a Perl program which outputs a java program which outputs the original Haskell program would be valid.

On the other hand, a C# 4 program which outputs a C# 3 program which outputs a C# 2 program is invalid. Even a Perl -\> Ruby -\> Bash combination would be invalid if, say, the Perl program and the Ruby program were identical.

This is code golf, so the shortest program pA wins.

# Answer
## Python -\> Perl -\> Ruby, 48 characters

Adaption of my previous answer. Running

```
s='print q<puts %%q{s=%r;print s%%s}>';print s%s

```

with Python generates this Perl snippet

```
print q<puts %q{s='print q<puts %%q{s=%r;print s%%s}>';print s%s}>

```

which generates the following Ruby code

```
puts %q{s='print q<puts %%q{s=%r;print s%%s}>';print s%s}

```

which then prints the original Python snippet:

```
diff -s <(ruby <(perl <(python thirdorderquine.py))) thirdorderquine.py
Files /dev/fd/63 and thirdorderquine.py are identical

```
> 21 votes

# Answer
## Perl -\> PHP -\> HTML + JavaScript, 105 chars

I wanted to make the chain of languages somehow meaningful, so I figured I'd write a PHP script that generates a HTML page containing JavaScript. For the third language I chose Perl, just because I like Perl. :)

Some might consider this *four* languages, but I don't really count HTML as separate from JavaScript here — it's a markup language, not a programming language. Anyway, here are the three versions:

Perl (105 chars):

```
printf+(q(<script>alert(unescape("<?=urlencode(<<<E%sprintf+(q(%s),$/)x2,$/%sE%s)?>"))</script>),$/)x2,$/

```

PHP (165 chars):

```
<script>alert(unescape("<?=urlencode(<<<E
printf+(q(<script>alert(unescape("<?=urlencode(<<<E%sprintf+(q(%s),$/)x2,$/%sE%s)?>"))</script>),$/)x2,$/
E
)?>"))</script>

```

HTML + JavaScript (235 chars):

```
<script>alert(unescape("printf%2B%28q%28%3Cscript%3Ealert%28unescape%28%22%3C%3F%3Durlencode%28%3C%3C%3CE%25sprintf%2B%28q%28%25s%29%2C%24%2F%29x2%2C%24%2F%25sE%25s%29%3F%3E%22%29%29%3C%2Fscript%3E%29%2C%24%2F%29x2%2C%24%2F"))</script>

```

(Ps. Yes, I know I could've made the PHP step an almost-noop, e.g. just generating HTML + JS code in Perl and appending `<?php` to it, but that felt too much like cheating. In this solution, the code is actually processed in PHP instead of just being copied verbatim.)
> 13 votes

# Answer
# Underload → sed → Perl, 23 bytes

Can probably get this down lower with better choices of languages. Arguably noncompeting because the rule "sed programs can take an empty line as argument" postdates the contest.

The Underload program:

```
((iprint+q)Sa(:^)*aS):^

```

generates the sed program:

```
iprint+q(((iprint+q)Sa(:^)*aS):^)

```

which generates the Perl program:

```
print+q(((print+q)Sa(:^)*aS):^)

```

(note: there are two trailing newlines here), which generates the original Underload program again:

```
((iprint+q)Sa(:^)*aS):^

```

The main aim here is to find languages in which strings are nestable (i.e. you can just quote a string by enclosing it in delimiters, rather than having to escape it); Underload has `()`, Perl has `q()`, and in sed a string continues until whitespace (which is implicitly nestable if there's no whitespace in the program). There's probably an esolang or golfing language out there with a "print the rest of the current line, not followed by newlines" instruction, which would be ideal here, but I haven't spent all that much time looking for one; you could save 8 bytes minus the length of the instruction in that case. (Jelly *almost* works but its  instruction doesn't quote itself. Besides, it postdates the challenge.)

You can reduce this to **22 bytes** like this:

```
((csay+q)Sa(:^)*aS):^

```

(with one trailing newline, like a regular text file, rather than the zero you normally get in golf). However, this requires an Underload interpreter that's OK with treating newline as a no-op. Try It Online!'s does, but I think it postdates the challenge.
> 3 votes

---
Tags: code-golf, quine
---