Title: Theoretically output Graham's number

Body:
Binary lambda calculus, 114 bits = 14.25 bytes

Hexdump:

00000000: 4457 42b0 2d88 1f9d 740e 5ed0 39ce 80    DWB.-...t.^.9..

Binary:

010001000101011101000010101100000010110110001000000111111001110101110100000011100101111011010000001110011100111010

Explanation

01 00                                           (λx.
│    01 00                                        (λy.
│    │    01 01 01 110                              x
│    │    │  │  └─ 10                               y
│    │    │  └─ 00                                  (λm.
│    │    │       01 01 01 10                         m
│    │    │       │  │  └─ 00                         (λg.
│    │    │       │  │       00                         λn.
│    │    │       │  │         01 01 10                  n
│    │    │       │  │         │  └─ 110                 g
│    │    │       │  │         └─ 00                     (λz.
│    │    │       │  │              10                     z))
│    │    │       │  └─ 00                            (λn.
│    │    │       │       00                            λf.
│    │    │       │         01 111110                    x
│    │    │       │         └─ 01 110                    (n
│    │    │       │            └─ 10                      f))
│    │    │       └─ 1110                             x)
│    │    └─ 10                                     y)
│    └─ 00                                        (λf.
│         00                                        λz.
│           01 110                                   f
│           └─ 01 01 1110                            (x
│              │  └─ 110                              f
│              └─ 10                                  z)))
└─ 00                                           (λf.
     00                                           λz.
       01 110                                      f
       └─ 01 110                                   (f
          └─ 01 110                                 (f
             └─ 10                                   z)))

This is (λx. (λy. x y (λm. m (λg. λn. n g 1) (λn. λf. x (n f)) x) y) (λf. λz. f (x f z))) 3, where all numbers are represented as Church numerals.  Church numerals are the standard lambda calculus representation of natural numbers, and they are well suited to this problem because a Church number is defined by function iteration: n g is the nth iterate of the function g.

For example, if g is the function λn. λf. 3 (n f) that multiplies 3 by a Church numeral, then λn. n g 1 is the function that takes 3 to the power of a Church numeral. Iterating this operation m times gives

m (λg. λn. n g 1) (λn. λf. 3 (n f)) n = u(3, n, m).

(We use multiplication u(–, –, 0) rather than exponentiation u(–, –, 1) as the base case, because subtracting 1 from a Church numeral is unpleasant.)

Substitute n = 3:

m (λg. λn. n g 1) (λn. λf. 3 (n f)) 3 = u(3, 3, m).

Iterating that operation 64 times, starting at m = 4, gives

64 (λm. m (λg. λn. n g 1) (λn. λf. 3 (n f)) 3) 4 = G.

To optimize this expression, substitute 64 = 4^3 = 3 4:

3 4 (λm. m (λg. λn. n g 1) (λn. λf. 3 (n f)) 3) 4 = G.

Remember 4 = succ 3 = λf. λz. f (3 f z) as a lambda argument:

(λy. 3 y (λm. m (λg. λn. n g 1) (λn. λf. 3 (n f)) 3) y) (λf. λz. f (3 f z)) = G.

Finally, remember 3 = λf. λz. f (f (f z)) as a lambda argument:

(λx. (λy. x y (λm. m (λg. λn. n g 1) (λn. λf. x (n f)) x) y) (λf. λz. f (x f z))) 3 = G.


问:
bfcat - encode a file as a brainf*** program

Challenge

Write a program or function that given a string, returns a valid Brainfuck program that when compiled and executed as Brainfuck, returns that string..

Assume all inputs are encoded as ASCII.

Assume the outputted BF program will execute in an environment with an infinite tape.

Assume the pointer starts at cell 0 with every cell initialized to a value of zero.

Each example below represent one possible correct output for the given input. In particular, the examples include extra newlines and spaces to help human readability. Solutions are free to format the outputted BF code in any way.

The tape is doubly infinite.

All cells provided by the interpreter are exactly 8-bit cells. Overflow and underflow wrap around in a predictable and sane matter.

Examples

Space string

Given the input  , your program/function could return:

```<code>+++++ +++++
+++++ +++++
+++++ +++++
++ .
</code>```

Exclamation point

Given the input ! , your program/function could return:

```<code>+++++ +++++
+++++ +++++
+++++ +++++
+++
.
</code>```

Two letters

Given the input hi , your program/function could return:

```<code>+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++

+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++

++++
.
+
.
</code>```

This is code-golf, so the code with the smallest number of bytes wins. Good luck.

答:
ES6, <s>119</s> 115 bytes

f=s=>{a='';for(i in[...s]){b=s[c='charCodeAt'](i)-(s[c](i-1)|0);a+=(b>0?'+'.repeat(b):'-'.repeat(-b))+'.'}return a}

Saved 4 bytes, thanks to @Leibrug

ContentLicense: CC BY-SA 3.0


问:
Visualise Bit Weaving
The esoteric programming language evil has an interesting operation on byte values which it calls "weaving". It is essentially a permutation of the eight bits of the byte (it doesn't matter which end we start counting from, as the pattern is symmetric):

Bit 0 is moved to bit 2

Bit 1 is moved to bit 0

Bit 2 is moved to bit 4

Bit 3 is moved to bit 1

Bit 4 is moved to bit 6

Bit 5 is moved to bit 3

Bit 6 is moved to bit 7

Bit 7 is moved to bit 5

For convenience, here are two other representations of the permutation. As a cycle:

```<code>(02467531)
</code>```

And as a list of pairs of the mapping:

```<code>[[0,2], [1,0], [2,4], [3,1], [4,6], [5,3], [6,7], [7,5]]
</code>```

Your task is to visualise this permutation, using the box-drawing characters ─, │, ┌, ┐, └, ┘, ┼ (Unicode code points: U+2500, U+2502, U+250C, U+2510, U+2514, U+2518, U+253C). This visualisation should satisfy the following constraints:

The first and last line are exactly:

```<code>0 1 2 3 4 5 6 7
</code>```

Between those, you can use as many lines as you want of up to 15 characters each to fit your box drawing characters (you will need at least 4 lines). The lines should start vertically beneath one of the digits on the first row and end vertically above the corresponding digit on the last row. The eight lines must be connected, and may only cross via ┼ (which is always a crossing, never two turning lines which are touching). The exact paths of the lines are up to you (and finding a particularly golfable layout is the core of this challenge). One valid output would be:

```<code>0 1 2 3 4 5 6 7
│ │ └─┼┐│ │ └┐│
└─┼─┐ ││└─┼─┐││
┌─┘ │ ││  │ │││
│ ┌─┼─┘│  │ │││
│ │ │ ┌┼──┘ │││
│ │ │ │└┐ ┌─┼┼┘
│ │ │ │ │ │ │└┐
0 1 2 3 4 5 6 7
</code>```

However, any other layout that correctly connects the right digits is fine too. Please show your chosen output in your answer.

You may write a program or function and will not take any input. Output the diagram either to STDOUT (or closest alternative) or as a function return value in the form of a string or a list of strings (each representing one line).

Standard code-golf rules apply, so the shortest code (in bytes) wins.

答:
JavaScript (ES6), <s>137</s> 134 bytes

f=
_=>`0
│2525252
1 1 1 1
24242423525252 3 1 1 1 3 242424│
0`.replace(/\d/g,d=>`0 1 2 3 4 5 6 7,└┼┐,┌┘,│
│,│ , │`.split`,`[d])
;
o.textContent=f();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><pre id=o>``````

As a bell-ringer I immediately recognised this as the first two rows of Plain Hunt Major (note that the linked image uses 1-8 instead of 0-7).

Title: Visualise Bit Weaving

Body:
JavaScript (ES6), <s>137</s> 134 bytes

f=
_=>`0
│2525252
1 1 1 1
24242423525252 3 1 1 1 3 242424│
0`.replace(/\d/g,d=>`0 1 2 3 4 5 6 7,└┼┐,┌┘,│
│,│ , │`.split`,`[d])
;
o.textContent=f();

<pre id=o></pre>

As a bell-ringer I immediately recognised this as the first two rows of Plain Hunt Major (note that the linked image uses 1-8 instead of 0-7).


问:
The Ackermann function
The Ackermann function is notable for being the one of the simplest examples of a total, computable function that isn't primitive recursive.

We will use the definition of \$A(m,n)\$ taking in two nonnegative integers where

$$\begin{align}
A(0,n) & = n+1 \\
A(m,0) & = A(m-1,1) \\
A(m,n) & = A(m-1,A(m,n-1))
\end{align}$$

You may implement

a named or anonymous function taking two integers as input, returning an integer, or

a program taking two space- or newline-separated integers on STDIN, printing a result to STDOUT.

You may not use an Ackermann function or hyperexponentiation function from a library, if one exists, but you may use any other function from any other library. Regular exponentiation is allowed.

Your function must be able to find the value of \$A(m,n)\$ for \$m \le 3\$ and \$n \le 10\$ in less than a minute. It must at least theoretically terminate on any other inputs: given infinite stack space, a native Bigint type, and an arbitrarily long period of time, it would return the answer. Edit: If your language has a default recursion depth that is too restrictive, you may reconfigure that at no character cost.

The submission with the shortest number of characters wins.

Here are some values, to check your answer:

$$\begin{array}{c|cccccccccc}
A & n = 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 \\
\hline
m=0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 \\
1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 \\
2 & 3 & 5 & 7 & 9 & 11 & 13 & 15 & 17 & 19 & 21 & 23 \\
3 & 5 & 13 & 29 & 61 & 125 & 253 & 509 & 1021 & 2045 & 4093 & 8189 \\
4 & 13 & 65533 & \text{big}
\end{array}$$

答:
Binary lambda calculus, 54 bits = 6.75 bytes

Hexdump:

```<code>00000000: 1607 2d88 072f 68                        ..-../h
</code>```

Binary:

```<code>000101100000011100101101100010000000011100101111011010
</code>```

This is λm. m (λg. λn. g (n g 1)) (λn. λf. λx. f (n f x)), where all numbers are represented as Church numerals.

ContentLicense: CC BY-SA 4.0

Title: The Ackermann function

Body:
Binary lambda calculus, 54 bits = 6.75 bytes

Hexdump:

00000000: 1607 2d88 072f 68                        ..-../h

Binary:

000101100000011100101101100010000000011100101111011010

This is λm. m (λg. λn. g (n g 1)) (λn. λf. λx. f (n f x)), where all numbers are represented as Church numerals.


问:
Autonest an array
Everybody loves nested lists! However, sometimes it's hard to make a nested list. You have to decide if you want to nest it deeper, or if you need to nest it shallower. So for your challenge, you must "Autonest" a list. To autonest a list, compare every pair of items in the list.

If the second item is smaller, separate the two elements by inserting closing and opening brackets between them, like this:

```<code>  } {
{2 , 1}
</code>```

For example, {2, 1} becomes {2}, {1}, and {3, 2, 1} becomes {3}, {2}, {1}

If the second item is the same, then change nothing. For example, {1, 1, 1} stays the same, and {2, 1, 1, 1} would become {2}, {1, 1, 1}.

If the second item is larger, then nest every following item one level deeper. For example, {1, 2} would become {1, {2}} and {1, 2, 3} would become {1, {2, {3}}}

The Challenge

You must write a program or function that takes in a list of numbers, and returns the same list after being autonested. Take this input in your languages native list format (or the closest alternative) or as a string. You do not have to use curly braces like I did in my examples. You can use whichever type of brackets are most natural in your language, as long as this is consistent. You can safely assume the list will only contain integers. You can also assume the list will have at least 2 numbers in it. Here is some sample IO:

```<code>{1, 3, 2}                         -->   {1, {3}, {2}}
{1, 2, 3, 4, 5, 6}                -->   {1, {2, {3, {4, {5, {6}}}}}}
{6, 5, 4, 3, 2, 1}                -->   {6}, {5}, {4}, {3}, {2}, {1}
{7, 3, 3, 2, 6, 4}                -->   {7}, {3, 3}, {2, {6}, {4}}
{7, 3, 1, -8, 4, 8, 2, -9, 2, 8}  -->   {7}, {3}, {1}, {-8, {4, {8}, {2}, {-9, {2, {8}}}}}
</code>```

Standard loopholes apply, and the shortest answer in bytes wins!

答:
Java 8 197 187 193 192 bytes

Thanks to all the commenters who worked with me on this monstrosity. It was golfed down to 187 bytes until I found a costly bug. However due to the power of Black Magic the "runs down to" operator "-->" the byte count is at a healthy 192 bytes.

```<code>String a(int[]b){int l=b.length,d=1,i=0;String c="{";for(;i<l-1;i++)if(b[i]>b[i+1])c+=b[i]+"},{";else if(b[i]<b[i+1]){d++;c+=b[i]+",{";}else c+=b[i]+",";c+=b[l-1];while(d-->0)c+="}";return c;}
</code>```

Title: Autonest an array

Body:
Java 8 197 187 193 192 bytes

Thanks to all the commenters who worked with me on this monstrosity. It was golfed down to 187 bytes until I found a costly bug. However due to the power of Black Magic the "runs down to" operator "-->" the byte count is at a healthy 192 bytes.

String a(int[]b){int l=b.length,d=1,i=0;String c="{";for(;i<l-1;i++)if(b[i]>b[i+1])c+=b[i]+"},{";else if(b[i]<b[i+1]){d++;c+=b[i]+",{";}else c+=b[i]+",";c+=b[l-1];while(d-->0)c+="}";return c;}


答:
Mouse-2002, 27 bytes

```<code>(?'l:l.^(l.^"+"l.1-l:)".>")
</code>```

This works in theory and according to the language's documentation, but the reference implementation of Mouse's interpreter seems to have a bug where string input appends a ', so for a this outputs

```<code>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++.>
</code>```

Which in turn outputs a'. That may or may not be okay, so here's a 39 byte  long one which doesn't output ' ever and thus is likely more invalid.

```<code>(?'l:l.39=l.0=+0=^(l.0>^"+"l.1-l:)".>")
</code>```

Which gives right output in the reference impl. as long as there are no 's :)

Explained:

```<code>(              ~ while (true) {
  ?' l:        ~   l = getchar()
  l. ^         ~   if (! (l) ) { break }
  (            ~   while (true) {
    l. ^       ~     if (! (l) ) { break }
    "+"        ~     puts("+")
    l. 1 - l:  ~     l-- // l = l - 1
  )            ~   }
  ".>"         ~   puts(".>")
)              ~ }
</code>```

Title: bfcat - encode a file as a brainf*** program

Body:
Challenge

Write a program or function that given a string, returns a valid Brainfuck program that when compiled and executed as Brainfuck, returns that string..

Assume all inputs are encoded as ASCII.

Assume the outputted BF program will execute in an environment with an infinite tape.

Assume the pointer starts at cell 0 with every cell initialized to a value of zero.

Each example below represent one possible correct output for the given input. In particular, the examples include extra newlines and spaces to help human readability. Solutions are free to format the outputted BF code in any way.

The tape is doubly infinite.

All cells provided by the interpreter are exactly 8-bit cells. Overflow and underflow wrap around in a predictable and sane matter.

Examples

Space string

Given the input  , your program/function could return:

```<code>+++++ +++++
+++++ +++++
+++++ +++++
++ .
</code>```

Exclamation point

Given the input ! , your program/function could return:

```<code>+++++ +++++
+++++ +++++
+++++ +++++
+++
.
</code>```

Two letters

Given the input hi , your program/function could return:

```<code>+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++

+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++

++++
.
+
.
</code>```

This is code-golf, so the code with the smallest number of bytes wins. Good luck.

Body:
Mouse-2002, 27 bytes

(?'l:l.^(l.^"+"l.1-l:)".>")

This works in theory and according to the language's documentation, but the reference implementation of Mouse's interpreter seems to have a bug where string input appends a ', so for a this outputs

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++.>

Which in turn outputs a'. That may or may not be okay, so here's a 39 byte  long one which doesn't output ' ever and thus is likely more invalid.

(?'l:l.39=l.0=+0=^(l.0>^"+"l.1-l:)".>")

Which gives right output in the reference impl. as long as there are no 's :)

Explained:

(              ~ while (true) {
  ?' l:        ~   l = getchar()
  l. ^         ~   if (! (l) ) { break }
  (            ~   while (true) {
    l. ^       ~     if (! (l) ) { break }
    "+"        ~     puts("+")
    l. 1 - l:  ~     l-- // l = l - 1
  )            ~   }
  ".>"         ~   puts(".>")
)              ~ }


问:
Golf you a quine for great good!
Using your language of choice, golf a quine.

A quine is a non-empty computer program which takes no input and produces a copy of its own source code as its only output.

No cheating -- that means that you can't just read the source file and print it. Also, in many languages, an empty file is also a quine: that isn't considered a legit quine either.

No error quines -- there is already a separate challenge for error quines.

Points for:

Smallest code (in bytes)

Most obfuscated/obscure solution

Using esoteric/obscure languages

Successfully using languages that are difficult to golf in

The following Stack Snippet can be used to get a quick view of the current score in each language, and thus to know which languages have existing answers and what sort of target you have to beat:

var QUESTION_ID=69;
var OVERRIDE_USER=98;

var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,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:!0,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=!1;comment_page=1;getComments()}})}
function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,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=(function(){var headerTag=String.raw `h\d`
var score=String.raw `\-?\d+\.?\d*`
var normalText=String.raw `[^\n<>]*`
var strikethrough=String.raw `<s>${normalText}</s>|<strike>${normalText}</strike>|<del>${normalText}</del>`
var noDigitText=String.raw `[^\n\d<>]*`
var htmlTag=String.raw `<[^\n<>]+>`
return new RegExp(String.raw `<${headerTag}>`+String.raw `\s*([^\n,]*[^\s,]),.*?`+String.raw `(${score})`+String.raw `(?=`+String.raw `${noDigitText}`+String.raw `(?:(?:${strikethrough}|${htmlTag})${noDigitText})*`+String.raw `</${headerTag}>`+String.raw `)`)})();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='
'+c.body.replace(OVERRIDE_REG,'')+'
'});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;lang=jQuery(''+a.language+'').text().toLowerCase();languages[lang]=languages[lang]||{lang:a.language,user:a.user,size:a.size,link:a.link,uniq:lang}});var langs=[];for(var lang in languages)
if(languages.hasOwnProperty(lang))
langs.push(languages[lang]);langs.sort(function(a,b){if(a.uniq>b.uniq)return 1;if(a.uniq<b.uniq)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)}}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

  <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654">

Winners by Language

Language	User	Score

Leaderboard

	Author	Language	Size

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}

{{LANGUAGE}}	{{NAME}}	{{SIZE}}

 ```

Title: Golf you a quine for great good!

Body:
S.I.L.O.S, 3057 bytes

A = 99
def S set
S A 112
A + 1
S A 114
A + 1
S A 105
A + 1
S A 110
A + 1
S A 116
A + 1
S A 76
A + 1
S A 105
A + 1
S A 110
A + 1
S A 101
A + 1
S A 32
A + 1
S A 65
A + 1
S A 32
A + 1
S A 61
A + 1
S A 32
A + 1
S A 57
A + 1
S A 57
A + 1
S A 10
A + 1
S A 72
A + 1
S A 32
A + 1
S A 61
A + 1
S A 32
A + 1
S A 56
A + 1
S A 51
A + 1
S A 10
A + 1
S A 112
A + 1
S A 114
A + 1
S A 105
A + 1
S A 110
A + 1
S A 116
A + 1
S A 32
A + 1
S A 100
A + 1
S A 101
A + 1
S A 102
A + 1
S A 32
A + 1
S A 10
A + 1
S A 112
A + 1
S A 114
A + 1
S A 105
A + 1
S A 110
A + 1
S A 116
A + 1
S A 67
A + 1
S A 104
A + 1
S A 97
A + 1
S A 114
A + 1
S A 32
A + 1
S A 72
A + 1
S A 10
A + 1
S A 112
A + 1
S A 114
A + 1
S A 105
A + 1
S A 110
A + 1
S A 116
A + 1
S A 76
A + 1
S A 105
A + 1
S A 110
A + 1
S A 101
A + 1
S A 32
A + 1
S A 32
A + 1
S A 83
A + 1
S A 32
A + 1
S A 10
A + 1
S A 67
A + 1
S A 32
A + 1
S A 61
A + 1
S A 32
A + 1
S A 57
A + 1
S A 57
A + 1
S A 10
A + 1
S A 66
A + 1
S A 32
A + 1
S A 61
A + 1
S A 32
A + 1
S A 103
A + 1
S A 101
A + 1
S A 116
A + 1
S A 32
A + 1
S A 67
A + 1
S A 10
A + 1
S A 108
A + 1
S A 98
A + 1
S A 108
A + 1
S A 68
A + 1
S A 10
A + 1
S A 67
A + 1
S A 32
A + 1
S A 43
A + 1
S A 32
A + 1
S A 49
A + 1
S A 10
A + 1
S A 112
A + 1
S A 114
A + 1
S A 105
A + 1
S A 110
A + 1
S A 116
A + 1
S A 67
A + 1
S A 104
A + 1
S A 97
A + 1
S A 114
A + 1
S A 32
A + 1
S A 72
A + 1
S A 10
A + 1
S A 112
A + 1
S A 114
A + 1
S A 105
A + 1
S A 110
A + 1
S A 116
A + 1
S A 32
A + 1
S A 32
A + 1
S A 65
A + 1
S A 32
A + 1
S A 10
A + 1
S A 112
A + 1
S A 114
A + 1
S A 105
A + 1
S A 110
A + 1
S A 116
A + 1
S A 73
A + 1
S A 110
A + 1
S A 116
A + 1
S A 32
A + 1
S A 66
A + 1
S A 10
A + 1
S A 112
A + 1
S A 114
A + 1
S A 105
A + 1
S A 110
A + 1
S A 116
A + 1
S A 76
A + 1
S A 105
A + 1
S A 110
A + 1
S A 101
A + 1
S A 32
A + 1
S A 65
A + 1
S A 32
A + 1
S A 43
A + 1
S A 32
A + 1
S A 49
A + 1
S A 10
A + 1
S A 66
A + 1
S A 32
A + 1
S A 61
A + 1
S A 32
A + 1
S A 103
A + 1
S A 101
A + 1
S A 116
A + 1
S A 32
A + 1
S A 67
A + 1
S A 10
A + 1
S A 105
A + 1
S A 102
A + 1
S A 32
A + 1
S A 66
A + 1
S A 32
A + 1
S A 68
A + 1
S A 10
A + 1
S A 70
A + 1
S A 32
A + 1
S A 61
A + 1
S A 32
A + 1
S A 57
A + 1
S A 57
A + 1
S A 10
A + 1
S A 69
A + 1
S A 32
A + 1
S A 61
A + 1
S A 32
A + 1
S A 103
A + 1
S A 101
A + 1
S A 116
A + 1
S A 32
A + 1
S A 70
A + 1
S A 10
A + 1
S A 108
A + 1
S A 98
A + 1
S A 108
A + 1
S A 71
A + 1
S A 10
A + 1
S A 70
A + 1
S A 32
A + 1
S A 43
A + 1
S A 32
A + 1
S A 49
A + 1
S A 10
A + 1
S A 112
A + 1
S A 114
A + 1
S A 105
A + 1
S A 110
A + 1
S A 116
A + 1
S A 67
A + 1
S A 104
A + 1
S A 97
A + 1
S A 114
A + 1
S A 32
A + 1
S A 69
A + 1
S A 10
A + 1
S A 69
A + 1
S A 32
A + 1
S A 61
A + 1
S A 32
A + 1
S A 103
A + 1
S A 101
A + 1
S A 116
A + 1
S A 32
A + 1
S A 70
A + 1
S A 10
A + 1
S A 105
A + 1
S A 102
A + 1
S A 32
A + 1
S A 69
A + 1
S A 32
A + 1
S A 71
A + 1
printLine A = 99
H = 83
print def
printChar H
printLine  S
C = 99
B = get C
lblD
C + 1
printChar H
print  A
printInt B
printLine A + 1
B = get C
if B D
F = 99
E = get F
lblG
F + 1
printChar E
E = get F
if E G

<a href="http://silos.tryitonline.net/#code=QSA9IDk5CmRlZiBTIHNldCAKUyBBIDExMgpBICsgMQpTIEEgMTE0CkEgKyAxClMgQSAxMDUKQSArIDEKUyBBIDExMApBICsgMQpTIEEgMTE2CkEgKyAxClMgQSA3NgpBICsgMQpTIEEgMTA1CkEgKyAxClMgQSAxMTAKQSArIDEKUyBBIDEwMQpBICsgMQpTIEEgMzIKQSArIDEKUyBBIDY1CkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNjEKQSArIDEKUyBBIDMyCkEgKyAxClMgQSA1NwpBICsgMQpTIEEgNTcKQSArIDEKUyBBIDEwCkEgKyAxClMgQSA3MgpBICsgMQpTIEEgMzIKQSArIDEKUyBBIDYxCkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNTYKQSArIDEKUyBBIDUxCkEgKyAxClMgQSAxMApBICsgMQpTIEEgMTEyCkEgKyAxClMgQSAxMTQKQSArIDEKUyBBIDEwNQpBICsgMQpTIEEgMTEwCkEgKyAxClMgQSAxMTYKQSArIDEKUyBBIDMyCkEgKyAxClMgQSAxMDAKQSArIDEKUyBBIDEwMQpBICsgMQpTIEEgMTAyCkEgKyAxClMgQSAzMgpBICsgMQpTIEEgMTAKQSArIDEKUyBBIDExMgpBICsgMQpTIEEgMTE0CkEgKyAxClMgQSAxMDUKQSArIDEKUyBBIDExMApBICsgMQpTIEEgMTE2CkEgKyAxClMgQSA2NwpBICsgMQpTIEEgMTA0CkEgKyAxClMgQSA5NwpBICsgMQpTIEEgMTE0CkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNzIKQSArIDEKUyBBIDEwCkEgKyAxClMgQSAxMTIKQSArIDEKUyBBIDExNApBICsgMQpTIEEgMTA1CkEgKyAxClMgQSAxMTAKQSArIDEKUyBBIDExNgpBICsgMQpTIEEgNzYKQSArIDEKUyBBIDEwNQpBICsgMQpTIEEgMTEwCkEgKyAxClMgQSAxMDEKQSArIDEKUyBBIDMyCkEgKyAxClMgQSAzMgpBICsgMQpTIEEgODMKQSArIDEKUyBBIDMyCkEgKyAxClMgQSAxMApBICsgMQpTIEEgNjcKQSArIDEKUyBBIDMyCkEgKyAxClMgQSA2MQpBICsgMQpTIEEgMzIKQSArIDEKUyBBIDU3CkEgKyAxClMgQSA1NwpBICsgMQpTIEEgMTAKQSArIDEKUyBBIDY2CkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNjEKQSArIDEKUyBBIDMyCkEgKyAxClMgQSAxMDMKQSArIDEKUyBBIDEwMQpBICsgMQpTIEEgMTE2CkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNjcKQSArIDEKUyBBIDEwCkEgKyAxClMgQSAxMDgKQSArIDEKUyBBIDk4CkEgKyAxClMgQSAxMDgKQSArIDEKUyBBIDY4CkEgKyAxClMgQSAxMApBICsgMQpTIEEgNjcKQSArIDEKUyBBIDMyCkEgKyAxClMgQSA0MwpBICsgMQpTIEEgMzIKQSArIDEKUyBBIDQ5CkEgKyAxClMgQSAxMApBICsgMQpTIEEgMTEyCkEgKyAxClMgQSAxMTQKQSArIDEKUyBBIDEwNQpBICsgMQpTIEEgMTEwCkEgKyAxClMgQSAxMTYKQSArIDEKUyBBIDY3CkEgKyAxClMgQSAxMDQKQSArIDEKUyBBIDk3CkEgKyAxClMgQSAxMTQKQSArIDEKUyBBIDMyCkEgKyAxClMgQSA3MgpBICsgMQpTIEEgMTAKQSArIDEKUyBBIDExMgpBICsgMQpTIEEgMTE0CkEgKyAxClMgQSAxMDUKQSArIDEKUyBBIDExMApBICsgMQpTIEEgMTE2CkEgKyAxClMgQSAzMgpBICsgMQpTIEEgMzIKQSArIDEKUyBBIDY1CkEgKyAxClMgQSAzMgpBICsgMQpTIEEgMTAKQSArIDEKUyBBIDExMgpBICsgMQpTIEEgMTE0CkEgKyAxClMgQSAxMDUKQSArIDEKUyBBIDExMApBICsgMQpTIEEgMTE2CkEgKyAxClMgQSA3MwpBICsgMQpTIEEgMTEwCkEgKyAxClMgQSAxMTYKQSArIDEKUyBBIDMyCkEgKyAxClMgQSA2NgpBICsgMQpTIEEgMTAKQSArIDEKUyBBIDExMgpBICsgMQpTIEEgMTE0CkEgKyAxClMgQSAxMDUKQSArIDEKUyBBIDExMApBICsgMQpTIEEgMTE2CkEgKyAxClMgQSA3NgpBICsgMQpTIEEgMTA1CkEgKyAxClMgQSAxMTAKQSArIDEKUyBBIDEwMQpBICsgMQpTIEEgMzIKQSArIDEKUyBBIDY1CkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNDMKQSArIDEKUyBBIDMyCkEgKyAxClMgQSA0OQpBICsgMQpTIEEgMTAKQSArIDEKUyBBIDY2CkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNjEKQSArIDEKUyBBIDMyCkEgKyAxClMgQSAxMDMKQSArIDEKUyBBIDEwMQpBICsgMQpTIEEgMTE2CkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNjcKQSArIDEKUyBBIDEwCkEgKyAxClMgQSAxMDUKQSArIDEKUyBBIDEwMgpBICsgMQpTIEEgMzIKQSArIDEKUyBBIDY2CkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNjgKQSArIDEKUyBBIDEwCkEgKyAxClMgQSA3MApBICsgMQpTIEEgMzIKQSArIDEKUyBBIDYxCkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNTcKQSArIDEKUyBBIDU3CkEgKyAxClMgQSAxMApBICsgMQpTIEEgNjkKQSArIDEKUyBBIDMyCkEgKyAxClMgQSA2MQpBICsgMQpTIEEgMzIKQSArIDEKUyBBIDEwMwpBICsgMQpTIEEgMTAxCkEgKyAxClMgQSAxMTYKQSArIDEKUyBBIDMyCkEgKyAxClMgQSA3MApBICsgMQpTIEEgMTAKQSArIDEKUyBBIDEwOApBICsgMQpTIEEgOTgKQSArIDEKUyBBIDEwOApBICsgMQpTIEEgNzEKQSArIDEKUyBBIDEwCkEgKyAxClMgQSA3MApBICsgMQpTIEEgMzIKQSArIDEKUyBBIDQzCkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNDkKQSArIDEKUyBBIDEwCkEgKyAxClMgQSAxMTIKQSArIDEKUyBBIDExNApBICsgMQpTIEEgMTA1CkEgKyAxClMgQSAxMTAKQSArIDEKUyBBIDExNgpBICsgMQpTIEEgNjcKQSArIDEKUyBBIDEwNApBICsgMQpTIEEgOTcKQSArIDEKUyBBIDExNApBICsgMQpTIEEgMzIKQSArIDEKUyBBIDY5CkEgKyAxClMgQSAxMApBICsgMQpTIEEgNjkKQSArIDEKUyBBIDMyCkEgKyAxClMgQSA2MQpBICsgMQpTIEEgMzIKQSArIDEKUyBBIDEwMwpBICsgMQpTIEEgMTAxCkEgKyAxClMgQSAxMTYKQSArIDEKUyBBIDMyCkEgKyAxClMgQSA3MApBICsgMQpTIEEgMTAKQSArIDEKUyBBIDEwNQpBICsgMQpTIEEgMTAyCkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNjkKQSArIDEKUyBBIDMyCkEgKyAxClMgQSA3MQpBICsgMQpwcmludExpbmUgQSA9IDk5CkggPSA4MwpwcmludCBkZWYgCnByaW50Q2hhciBICnByaW50TGluZSAgUyAKQyA9IDk5CkIgPSBnZXQgQwpsYmxECkMgKyAxCnByaW50Q2hhciBICnByaW50ICBBIApwcmludEludCBCCnByaW50TGluZSBBICsgMQpCID0gZ2V0IEMKaWYgQiBECkYgPSA5OQpFID0gZ2V0IEYKbGJsRwpGICsgMQpwcmludENoYXIgRQpFID0gZ2V0IEYKaWYgRSBH&input=" rel="nofollow noreferrer">Try it online!

I am ashamed to say this took me a while to write even though most of it was generated by another java program. Thanks to @MartinEnder for helping me out. This is the first quine I have ever written. Credits go to Leaky Nun for most of the code. I "borrowed his code" which was originally inspired by mine. My answer is similar to his, except it shows the "power" of the preprocessor. Hopefully this approach can be used to golf of bytes if done correctly. The goal was to prevent rewriting the word "set" 100's of times.

Please check out his much shorter answer!


问:
Generate a Kolakoski sequence

Definition1

A Kolakoski sequence is a self-describing infinite sequence {kn} of alternating blocks of 1's and 2's, given by the following rules:

k0 = 1

kn = the length of the (n+1)'th block

The Task

Given a positive integer n, generate the first n elements of the Kolakoski sequence.

Details

Input will be provided as a single command line argument n. Please write a full program that will print the first n elements of the Kolakoski sequence (in order) to STDOUT, with each element separated by your favorite whitespace.

Scoring

Lets count source code bytes this time with all whitespace included. Fewest number of bytes wins. In the event of a tie, the solution with the earliest submission time wins.

The Sequence2

1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 2, ...

References

John Smith, Ariel Scolnicov, yark. "Kolakoski sequence" (version 3). PlanetMath.org. Freely available at http://planetmath.org/KolakoskiSequence.html.

The Online Encyclopedia of Integer Sequences http://oeis.org/A000002

Other resources

Kolakoski Sequence at Wikipedia http://en.wikipedia.org/wiki/Kolakoski_sequence

Kolakoski Sequence at Wolfram MathWorld http://mathworld.wolfram.com/KolakoskiSequence.html

Title: Generate a Kolakoski sequence

Body:
Ruby (73 characters)

s=[1,2,2];n=2;ARGV[0].to_i.times{puts s[n-2];s[n].times{s+=[1+n%2]};n+=1}


答:
Actually, 69 bytes

```<code>"│ ┌┘│ │└┐ │└┐└┐""┌┘└┼┐└┼┐ └┼┐└┐""└┼┐│└┐┌┘└┐┌┘│""┌┼─┘"3*"│┌┘"+8r' j;)
</code>```

Try it online! (the alignment is a little messed up in the online interpreter)

Actually has a HUGE advantage here - all of the box drawing characters are in CP437, so they're only a byte each. Though each character needed could theoretically be encoded in 4 bits (since there are only 9 unique characters), the 31 bytes saved by compressing the string would be lost due to Actually's very poor string processing capabilities. This also means that any 8x4 configuration would result in the same score. Since 8x4 appears to be the (vertically) shortest possible configuration, this is optimal.

Thanks to Martin for 3 bytes!

Thanks to TimmyD for 4 more bytes!

Explanation:

```<code>"│ ┌┘│ │└┐ │└┐└┐""┌┘└┼┐└┼┐ └┼┐└┐""└┼┐│└┐┌┘└┐┌┘│""┌┼─┘"3*"│┌┘"+8r' j;)
"│ ┌┘│ │└┐ │└┐└┐""┌┘└┼┐└┼┐ └┼┐└┐""└┼┐│└┐┌┘└┐┌┘│""┌┼─┘"3*"│┌┘"+         push the individual lines, using string multiplication to shorten repeated sections
                                                              8r' j   push the string "0 1 2 3 4 5 6 7" (range(8), join on spaces)
                                                                   ;)  make a copy and move it to the bottom of the stack
</code>```

Title: Visualise Bit Weaving

Body:
The esoteric programming language evil has an interesting operation on byte values which it calls "weaving". It is essentially a permutation of the eight bits of the byte (it doesn't matter which end we start counting from, as the pattern is symmetric):

Bit 0 is moved to bit 2

Bit 1 is moved to bit 0

Bit 2 is moved to bit 4

Bit 3 is moved to bit 1

Bit 4 is moved to bit 6

Bit 5 is moved to bit 3

Bit 6 is moved to bit 7

Bit 7 is moved to bit 5

For convenience, here are two other representations of the permutation. As a cycle:

```<code>(02467531)
</code>```

And as a list of pairs of the mapping:

```<code>[[0,2], [1,0], [2,4], [3,1], [4,6], [5,3], [6,7], [7,5]]
</code>```

Your task is to visualise this permutation, using the box-drawing characters ─, │, ┌, ┐, └, ┘, ┼ (Unicode code points: U+2500, U+2502, U+250C, U+2510, U+2514, U+2518, U+253C). This visualisation should satisfy the following constraints:

The first and last line are exactly:

```<code>0 1 2 3 4 5 6 7
</code>```

Between those, you can use as many lines as you want of up to 15 characters each to fit your box drawing characters (you will need at least 4 lines). The lines should start vertically beneath one of the digits on the first row and end vertically above the corresponding digit on the last row. The eight lines must be connected, and may only cross via ┼ (which is always a crossing, never two turning lines which are touching). The exact paths of the lines are up to you (and finding a particularly golfable layout is the core of this challenge). One valid output would be:

```<code>0 1 2 3 4 5 6 7
│ │ └─┼┐│ │ └┐│
└─┼─┐ ││└─┼─┐││
┌─┘ │ ││  │ │││
│ ┌─┼─┘│  │ │││
│ │ │ ┌┼──┘ │││
│ │ │ │└┐ ┌─┼┼┘
│ │ │ │ │ │ │└┐
0 1 2 3 4 5 6 7
</code>```

However, any other layout that correctly connects the right digits is fine too. Please show your chosen output in your answer.

You may write a program or function and will not take any input. Output the diagram either to STDOUT (or closest alternative) or as a function return value in the form of a string or a list of strings (each representing one line).

Standard code-golf rules apply, so the shortest code (in bytes) wins.

Body:
Actually, 69 bytes

"│ ┌┘│ │└┐ │└┐└┐""┌┘└┼┐└┼┐ └┼┐└┐""└┼┐│└┐┌┘└┐┌┘│""┌┼─┘"3*"│┌┘"+8r' j;)

Try it online! (the alignment is a little messed up in the online interpreter)

Actually has a HUGE advantage here - all of the box drawing characters are in CP437, so they're only a byte each. Though each character needed could theoretically be encoded in 4 bits (since there are only 9 unique characters), the 31 bytes saved by compressing the string would be lost due to Actually's very poor string processing capabilities. This also means that any 8x4 configuration would result in the same score. Since 8x4 appears to be the (vertically) shortest possible configuration, this is optimal.

Thanks to Martin for 3 bytes!

Thanks to TimmyD for 4 more bytes!

Explanation:

"│ ┌┘│ │└┐ │└┐└┐""┌┘└┼┐└┼┐ └┼┐└┐""└┼┐│└┐┌┘└┐┌┘│""┌┼─┘"3*"│┌┘"+8r' j;)
"│ ┌┘│ │└┐ │└┐└┐""┌┘└┼┐└┼┐ └┼┐└┐""└┼┐│└┐┌┘└┐┌┘│""┌┼─┘"3*"│┌┘"+         push the individual lines, using string multiplication to shorten repeated sections
                                                              8r' j   push the string "0 1 2 3 4 5 6 7" (range(8), join on spaces)
                                                                   ;)  make a copy and move it to the bottom of the stack


问:
Remove duplicate words from a sentence
In this challenge, you will remove duplicate words from each sentence.

Examples

```<code>Hello Hello, World!
Hello, World!

Code Code! Golf Code
Code! Golf Code

Hello  hello   World
Hello   World

Programming Golf Programming!
Programming Golf!
</code>```

Specification

Input will be a string of ASCII characters.

A sentence is defined as anything until the end of the string, a linefeed (\n), or punctuation (.!?).

A word is defined as a sequence of A-Za-z.

Words are case insensitive (Hello == heLlO).

Only the first occurrence of a word in a sentence is kept.

If a word is removed, the spaces before the removed word should be removed. (e.g. A   A B -> A B).

As always standard loopholes are disallowed.

This is code-golf so shortest code in bytes wins!

答:
Vim, 27 bytes

```<code>:s/\v\c(<\a+>).{-}\zs\s+\1
</code>```

Note that the 27 bytes is including a trailing carriage return at the end.

Try it online! Side note: This is a link to a different language I'm writing called "V". V is mostly backwards compatible with vim, so for all intents and purposes, it can count as a vim interpreter. I also added one byte % so that you can verify all test cases at once.

Explanation:

```<code>:s/\v                       "Substitute with the 'Magic flag' on. This magic flag allows us
                            "to shorten the regex by removing a lot of \ characters.
     \c(<\a+>)              "A case-insensitive word
              .{-}          "Any character (non-greedy)
                  \zs       "Start the selection. This means everything after this atom
                            "will be removed
                     \s+    "One or more whitespace characters,
                        \1  "Followed by the first word
</code>```

Title: Remove duplicate words from a sentence

Body:
Vim, 27 bytes

:s/\v\c(<\a+>).{-}\zs\s+\1

Note that the 27 bytes is including a trailing carriage return at the end.

Try it online! Side note: This is a link to a different language I'm writing called "V". V is mostly backwards compatible with vim, so for all intents and purposes, it can count as a vim interpreter. I also added one byte % so that you can verify all test cases at once.

Explanation:

:s/\v                       "Substitute with the 'Magic flag' on. This magic flag allows us
                            "to shorten the regex by removing a lot of \ characters.
     \c(<\a+>)              "A case-insensitive word
              .{-}          "Any character (non-greedy)
                  \zs       "Start the selection. This means everything after this atom
                            "will be removed
                     \s+    "One or more whitespace characters,
                        \1  "Followed by the first word


问:
Knight on the Rim is Grim

Introduction

Aron Nimzowitsch was a leading chess master and a influential chess writer.

In his book 'My System', the first chapter deals about the importance of the center and why you should dominate it. The simple reason is that your pieces have more possible direct next moves when being in the center which again gives the player more power.

This gets very clear when looking at different positions of a knight and its potential next moves (shown in pink) on an empty board:

Objective

Evaluate the number of potential direct next moves of a knight on an empty board based on its position.

Input Specs

The position of the knight.

First the x (column) and then the y (row). 0 0 is the left bottom corner.

For simplicity, I changed the labels of a chess board to numbers only. For our examples and test cases we use a 0-based index, you are free to use a 1-based index though.

You can use any type of possible input formats, an array, function arguments, etc.

Output Specs

The number of potential direct next moves for a knight on an empty board.

Test Cases

```<code>3 4 => 8
4 6 => 6
7 7 => 2
1 0 => 3
</code>```

Test cases are employing a 0-based index. The full grid of values is:

```<code>2 3 4 4 4 4 3 2
3 4 6 6 6 6 4 3
4 6 8 8 8 8 6 4
4 6 8 8 8 8 6 4
4 6 8 8 8 8 6 4
4 6 8 8 8 8 6 4
3 4 6 6 6 6 4 3
2 3 4 4 4 4 3 2
</code>```

答:
Pyth - <s>33</s> 15 bytes

Thanks to @LeakyNun for reducing my size by half.

Rearranging the maps and V's will probably lemme golf a little off.

```<code>/sM*Fm^R2-Rd8Q5
</code>```

Test Suite.

Title: Knight on the Rim is Grim

Body:
Pyth - <s>33</s> 15 bytes

Thanks to @LeakyNun for reducing my size by half.

Rearranging the maps and V's will probably lemme golf a little off.

/sM*Fm^R2-Rd8Q5

Test Suite.


答:
Java - <s>160</s> 150 bytes

```<code>int m(int r,int c){int m=0,i,j;for(i=0;i<3;i+=2)for(j=0;j<3;j+=2){m+=r+i>0&r+i<9&c+2*j>1&c+2*j<11?1:0;m+=r+2*i>1&r+2*i<11&c+j>0&c+j<9?1:0;}return m;}
</code>```

Ungolfed:

```<code>public static int m(int r, int c) {
    int m=0;
    for(int i=-1;i<2;i+=2)
        for(int j=-1;j<2;j+=2){
            m += r+i>-1 && r+i<8 && c+2*j>0 && c+2*j<8 ? 1:0;
            m += r+2*i>0 && r+2*i<8 && c+j>1 && c+j<8 ? 1:0;
        }
    return m;
}
</code>```

The ungolfed code is identical except for changing the bounds of the for loop to save 4 bytes. Works by iterating through each possible move and performing a bounds check (>0 and <8). Uses the fact that the offsets are (1, 2), (2, 1), (-1, 2), (-2, 1), etc. and is able to check 2 moves for each value of i and j.

Edit: 10 bytes saved thanks to suggestions by Leaky Nun and u902383.

Title: Knight on the Rim is Grim

Body:
Introduction

Aron Nimzowitsch was a leading chess master and a influential chess writer.

In his book 'My System', the first chapter deals about the importance of the center and why you should dominate it. The simple reason is that your pieces have more possible direct next moves when being in the center which again gives the player more power.

This gets very clear when looking at different positions of a knight and its potential next moves (shown in pink) on an empty board:

Objective

Evaluate the number of potential direct next moves of a knight on an empty board based on its position.

Input Specs

The position of the knight.

First the x (column) and then the y (row). 0 0 is the left bottom corner.

For simplicity, I changed the labels of a chess board to numbers only. For our examples and test cases we use a 0-based index, you are free to use a 1-based index though.

You can use any type of possible input formats, an array, function arguments, etc.

Output Specs

The number of potential direct next moves for a knight on an empty board.

Test Cases

```<code>3 4 => 8
4 6 => 6
7 7 => 2
1 0 => 3
</code>```

Test cases are employing a 0-based index. The full grid of values is:

```<code>2 3 4 4 4 4 3 2
3 4 6 6 6 6 4 3
4 6 8 8 8 8 6 4
4 6 8 8 8 8 6 4
4 6 8 8 8 8 6 4
4 6 8 8 8 8 6 4
3 4 6 6 6 6 4 3
2 3 4 4 4 4 3 2
</code>```

Body:
Java - <s>160</s> 150 bytes

int m(int r,int c){int m=0,i,j;for(i=0;i<3;i+=2)for(j=0;j<3;j+=2){m+=r+i>0&r+i<9&c+2*j>1&c+2*j<11?1:0;m+=r+2*i>1&r+2*i<11&c+j>0&c+j<9?1:0;}return m;}

Ungolfed:

public static int m(int r, int c) {
    int m=0;
    for(int i=-1;i<2;i+=2)
        for(int j=-1;j<2;j+=2){
            m += r+i>-1 && r+i<8 && c+2*j>0 && c+2*j<8 ? 1:0;
            m += r+2*i>0 && r+2*i<8 && c+j>1 && c+j<8 ? 1:0;
        }
    return m;
}

The ungolfed code is identical except for changing the bounds of the for loop to save 4 bytes. Works by iterating through each possible move and performing a bounds check (>0 and <8). Uses the fact that the offsets are (1, 2), (2, 1), (-1, 2), (-2, 1), etc. and is able to check 2 moves for each value of i and j.

Edit: 10 bytes saved thanks to suggestions by Leaky Nun and u902383.


问:
Fred's water bill
Fred is a quasi-friendly guy, but in reality he is mean.

Because of this, Fred lives alone in a small apartment in Los Altos, CA. Fred is so mean because he is very particular about water. He, therefore, needs your help with figuring out what his water bill is.

Your job is to write a function or program that returns his water bill given the amount of water used as input (which is always an integer).

Water consumption comes in tiers. This means that there are ranges of prices depending on the amount of water.

These are the tiers, their prices, and the amounts of water they correspond to:

```<code>Tier I
   First 10 Ccf: $3.8476/Ccf
Tier II
   Next 17 Ccf: $4.0932/Ccf
Tier III
   All subsequent water: $4.9118/Ccf
</code>```

For n hundreds of cubic feet (Ccf), there are the following additional charges as well:

```<code>CPUC fee: 1.5% of above charges
LIRA quantity surcharge: $0.047*n
PBOP amoritization surcharge: $0.004*n
</code>```

The sum of the Tier I, Tier II, Tier III, CPUC, LIRA, and PBOP fees is the total water bill. This sum you should either return or print to the console rounded to two decimal places.

Here are two examples:

```<code>Input: 15
... Calculations which you do not need to output but here to help explain:
Tier I: 10*3.8476 = 38.476
Tier II: (15-10)*4.0932 = 20.466
Tier III: 0*4.9118 = 0
Tiers sum: 58.942
CPUC: 1.5% of 58.942 = 0.88413
LIRA: 0.047*15 = 0.705
PBOP: 0.004*15 = 0.06
Total sum: 58.942 + 0.88413 + 0.705 + 0.06 = 60.59113
...
Output: 60.59

Input: 100
... Calculations which you do not need to output but here to help explain:
Tier I: 10*3.8476 = 38.476
Tier II: 17*4.0932 = 69.5844
Tier III: (100-10-17)*4.9118 = 358.5614
Tiers sum: 466.6218
CPUC: 1.5% of  = 6.999327
LIRA: 0.047*100 = 4.7
PBOP: 0.004*100 = 0.4
Total sum: 478.721127
...
Output: 478.72
</code>```

This is code golf so shortest code in bytes wins!

Title: Fred's water bill

Body:
Pyth - <s>58</s> 51 bytes

.Rs+*Bs*V++m3.8476Tm4.0932 17m4.9118Qm1Q.015*.051Q2

Test Suite.


答:
Perl 5, 73 bytes

The obvious solution. 72 bytes, plus 1 for -ne instead of -e.

```<code>printf'%.2f',$_*3.956314+($_-10)*($_>10)*.249284+($_-27)*($_>27)*.830879
</code>```

Saved 5 bytes thanks to LLlAMnYP. Thanks!

Title: Fred's water bill

Body:
Fred is a quasi-friendly guy, but in reality he is mean.

Because of this, Fred lives alone in a small apartment in Los Altos, CA. Fred is so mean because he is very particular about water. He, therefore, needs your help with figuring out what his water bill is.

Your job is to write a function or program that returns his water bill given the amount of water used as input (which is always an integer).

Water consumption comes in tiers. This means that there are ranges of prices depending on the amount of water.

These are the tiers, their prices, and the amounts of water they correspond to:

```<code>Tier I
   First 10 Ccf: $3.8476/Ccf
Tier II
   Next 17 Ccf: $4.0932/Ccf
Tier III
   All subsequent water: $4.9118/Ccf
</code>```

For n hundreds of cubic feet (Ccf), there are the following additional charges as well:

```<code>CPUC fee: 1.5% of above charges
LIRA quantity surcharge: $0.047*n
PBOP amoritization surcharge: $0.004*n
</code>```

The sum of the Tier I, Tier II, Tier III, CPUC, LIRA, and PBOP fees is the total water bill. This sum you should either return or print to the console rounded to two decimal places.

Here are two examples:

```<code>Input: 15
... Calculations which you do not need to output but here to help explain:
Tier I: 10*3.8476 = 38.476
Tier II: (15-10)*4.0932 = 20.466
Tier III: 0*4.9118 = 0
Tiers sum: 58.942
CPUC: 1.5% of 58.942 = 0.88413
LIRA: 0.047*15 = 0.705
PBOP: 0.004*15 = 0.06
Total sum: 58.942 + 0.88413 + 0.705 + 0.06 = 60.59113
...
Output: 60.59

Input: 100
... Calculations which you do not need to output but here to help explain:
Tier I: 10*3.8476 = 38.476
Tier II: 17*4.0932 = 69.5844
Tier III: (100-10-17)*4.9118 = 358.5614
Tiers sum: 466.6218
CPUC: 1.5% of  = 6.999327
LIRA: 0.047*100 = 4.7
PBOP: 0.004*100 = 0.4
Total sum: 478.721127
...
Output: 478.72
</code>```

This is code golf so shortest code in bytes wins!

Body:
Perl 5, 73 bytes

The obvious solution. 72 bytes, plus 1 for -ne instead of -e.

printf'%.2f',$_*3.956314+($_-10)*($_>10)*.249284+($_-27)*($_>27)*.830879

Saved 5 bytes thanks to LLlAMnYP. Thanks!


答:
MATL, <s>17</s> <s>14</s> <s>13</s> 12 bytes

Thanks to @Neil for 1 byte off!

```<code>8:HZ^ZP5X^=s
</code>```

Input is 1-based.

Try it online!

Explanation

This computes the Euclidean distance from the input to each of the 64 positions in the chessboard, and finds how many of those values equal the square root of 5.

Since the coordinates are integer values, we can be sure that the two floating-point values representing the square root of 5 (that computed from the coordinates and that computed directly) are indeed the same.

```<code>8:      % Push array [1 2 ... 8]
H       % Push 2
Z^      % Cartesian power. Gives 2D array [1 1; 1 2; ... 1 8; 2 1; ... 8 8]
ZP      % Implicit input. Compute Euclidean distances, considering each row as a point
5X^     % Square root of 5
=s      % Compute how many squared distances equal sqrt(5). Implicit display
</code>```

Title: Knight on the Rim is Grim

Body:
MATL, <s>17</s> <s>14</s> <s>13</s> 12 bytes

Thanks to @Neil for 1 byte off!

8:HZ^ZP5X^=s

Input is 1-based.

Try it online!

Explanation

This computes the Euclidean distance from the input to each of the 64 positions in the chessboard, and finds how many of those values equal the square root of 5.

Since the coordinates are integer values, we can be sure that the two floating-point values representing the square root of 5 (that computed from the coordinates and that computed directly) are indeed the same.

8:      % Push array [1 2 ... 8]
H       % Push 2
Z^      % Cartesian power. Gives 2D array [1 1; 1 2; ... 1 8; 2 1; ... 8 8]
ZP      % Implicit input. Compute Euclidean distances, considering each row as a point
5X^     % Square root of 5
=s      % Compute how many squared distances equal sqrt(5). Implicit display


答:
Python, 94 bytes

```<code>lambda x,y,a=[2,1,-1,-2,-2,-1,1,2]:list((9>x+a[i]>0)&(9>y+a[5-i]>0)for i in range(8)).count(1)
</code>```

Uses 1 based indexing.

Demo at https://repl.it/C6gV.

Title: Knight on the Rim is Grim

Body:
Python, 94 bytes

lambda x,y,a=[2,1,-1,-2,-2,-1,1,2]:list((9>x+a[i]>0)&(9>y+a[5-i]>0)for i in range(8)).count(1)

Uses 1 based indexing.

Demo at https://repl.it/C6gV.


答:
Python 93

Adapted from my solution to Calculate the nth term of Golomb's self-describing sequence:

```<code>import sys;n=int(sys.argv[1]);a=[1,2,2];
for i in range(3,n):a+=[~i%2+1]*a[i-1]
print a[:n]
</code>```

Still trying to figure out how to do this with list comprehension which I just learned about today, but I'm running into problems with self-reference.

EDIT: Instead of breaking if list was too long, just printed the appropriate slice.

EDIT: Now pulling arg from command line

Title: Generate a Kolakoski sequence

Body:
Definition1

A Kolakoski sequence is a self-describing infinite sequence {kn} of alternating blocks of 1's and 2's, given by the following rules:

k0 = 1

kn = the length of the (n+1)'th block

The Task

Given a positive integer n, generate the first n elements of the Kolakoski sequence.

Details

Input will be provided as a single command line argument n. Please write a full program that will print the first n elements of the Kolakoski sequence (in order) to STDOUT, with each element separated by your favorite whitespace.

Scoring

Lets count source code bytes this time with all whitespace included. Fewest number of bytes wins. In the event of a tie, the solution with the earliest submission time wins.

The Sequence2

1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 2, ...

References

John Smith, Ariel Scolnicov, yark. "Kolakoski sequence" (version 3). PlanetMath.org. Freely available at http://planetmath.org/KolakoskiSequence.html.

The Online Encyclopedia of Integer Sequences http://oeis.org/A000002

Other resources

Kolakoski Sequence at Wikipedia http://en.wikipedia.org/wiki/Kolakoski_sequence

Kolakoski Sequence at Wolfram MathWorld http://mathworld.wolfram.com/KolakoskiSequence.html

Body:
Python 93

Adapted from my solution to Calculate the nth term of Golomb's self-describing sequence:

import sys;n=int(sys.argv[1]);a=[1,2,2];
for i in range(3,n):a+=[~i%2+1]*a[i-1]
print a[:n]

Still trying to figure out how to do this with list comprehension which I just learned about today, but I'm running into problems with self-reference.

EDIT: Instead of breaking if list was too long, just printed the appropriate slice.

EDIT: Now pulling arg from command line


答:
Mathematica, <s>44</s> 40 bytes

I've currently got three solutions at the same byte count:

```<code>2[3,4,6,8][[Tr@⌊3.2-.8Abs[#-4.5]⌋]]&
Tr@⌈.85(4-Abs[#-4.5])⌉/.{5->6,6->8}&
⌊Tr@⌈.85(4-Abs[#-4.5])⌉^1.1608⌋&
</code>```

All of those are unnamed functions that take pair of coordinates like {3, 4}, which are 1-based.

I tried coming up with a somewhat explicit formula. The general pattern on the entire board looks like this:

The actual values of those colours (from lightest to darkest) are 2, 3, 4, 6, 8. That is:

```<code>2 3 4 4 4 4 3 2
3 4 6 6 6 6 4 3
4 6 8 8 8 8 6 4
4 6 8 8 8 8 6 4
4 6 8 8 8 8 6 4
4 6 8 8 8 8 6 4
3 4 6 6 6 6 4 3
2 3 4 4 4 4 3 2
</code>```

We first exploit the symmetry by shifting the origin to the centre, taking the absolute value and subtracting the result from 4. This gives us coordinates 0.5 to 3.5 increasing from each corner. In order to make the centre coordinates the same we need to map 0.5 and 1.5 to different values and 2.5 and 3.5 to the same value. This is easily done by multiplying by 0.8 (gives{0.4, 1.2, 2., 2.8}) and flooring the result. So now we've got {0, 1, 2, 2} as distances from the centre. If we add up the coordinates in each cell, we get this table:

```<code>0 1 2 2 2 2 1 0
1 2 3 3 3 3 2 1
2 3 4 4 4 4 3 2
2 3 4 4 4 4 3 2
2 3 4 4 4 4 3 2
2 3 4 4 4 4 3 2
1 2 3 3 3 3 2 1
0 1 2 2 2 2 1 0
</code>```

This has unique values for all the different possible results, so we simply use it as an index into 2[3,4,6,8].

In the second version we use ceiling instead floor. This way, 2, 3 and 4 are already correct, but we get 5 and 6 instead of 6 and 8, so we correct those manually with a substitution rule.

Finally, in the third version, we extend 5 and 6 upwards to 6 and 8 by means of exponentiation, followed by another floor operation.

Title: Knight on the Rim is Grim

Body:
Mathematica, <s>44</s> 40 bytes

I've currently got three solutions at the same byte count:

2[3,4,6,8][[Tr@⌊3.2-.8Abs[#-4.5]⌋]]&
Tr@⌈.85(4-Abs[#-4.5])⌉/.{5->6,6->8}&
⌊Tr@⌈.85(4-Abs[#-4.5])⌉^1.1608⌋&

All of those are unnamed functions that take pair of coordinates like {3, 4}, which are 1-based.

I tried coming up with a somewhat explicit formula. The general pattern on the entire board looks like this:

The actual values of those colours (from lightest to darkest) are 2, 3, 4, 6, 8. That is:

2 3 4 4 4 4 3 2
3 4 6 6 6 6 4 3
4 6 8 8 8 8 6 4
4 6 8 8 8 8 6 4
4 6 8 8 8 8 6 4
4 6 8 8 8 8 6 4
3 4 6 6 6 6 4 3
2 3 4 4 4 4 3 2

We first exploit the symmetry by shifting the origin to the centre, taking the absolute value and subtracting the result from 4. This gives us coordinates 0.5 to 3.5 increasing from each corner. In order to make the centre coordinates the same we need to map 0.5 and 1.5 to different values and 2.5 and 3.5 to the same value. This is easily done by multiplying by 0.8 (gives{0.4, 1.2, 2., 2.8}) and flooring the result. So now we've got {0, 1, 2, 2} as distances from the centre. If we add up the coordinates in each cell, we get this table:

0 1 2 2 2 2 1 0
1 2 3 3 3 3 2 1
2 3 4 4 4 4 3 2
2 3 4 4 4 4 3 2
2 3 4 4 4 4 3 2
2 3 4 4 4 4 3 2
1 2 3 3 3 3 2 1
0 1 2 2 2 2 1 0

This has unique values for all the different possible results, so we simply use it as an index into 2[3,4,6,8].

In the second version we use ceiling instead floor. This way, 2, 3 and 4 are already correct, but we get 5 and 6 instead of 6 and 8, so we correct those manually with a substitution rule.

Finally, in the third version, we extend 5 and 6 upwards to 6 and 8 by means of exponentiation, followed by another floor operation.


Title: Fred's water bill

Body:
Oracle SQL 11.2, 151 bytes

SELECT ((DECODE(SIGN(:1-10),1,10,:1)*3.8476)+(DECODE(SIGN(:1-27),1,17,:1-10)*4.0932)+(DECODE(SIGN(:1-27),-1,0,:1-27)*4.9118))*1.015+:1*0.051 FROM DUAL;

Un-golfed

SELECT ((DECODE(SIGN(:1-10),1,10,:1)*3.8476)+
       (DECODE(SIGN(:1-27),1,17,:1-10)*4.0932)+
       (DECODE(SIGN(:1-27),-1,0,:1-27)*4.9118))*1.015+
       :1*0.051
FROM DUAL


答:
Mathematica, 83 76 69 bytes

```<code>1.015{3.8476,.2456(b=Boole)[#>10],.8186b[#>27],51/1015}&~Array~#~Total~2~Round~.01&
</code>```

Anonymous function that constructs an array of the three tiers in the first column plus the LIRA and PBOP represented as an arbitrary-precision number in the fourth column. The whole thing is multiplied by 1.015 and all elements of the array are summed and rounded to .01. Since 51/1015*1.015 will be the desired 0.051 the output is exactly as precise, as the specification in OP.

A shorter solution, in 76 bytes, as I have suggested in my comment under the Perl solution

```<code>{3.956314,.249284(b=Boole)[#>10],.830879b[#>27]}&~Array~#~Total~2~Round~.01&
</code>```

where 1.015 is factored into the prices from the start and then the LIRA and PBOP is added on top of the first tier.

73 bytes (but I'm reluctant to update my byte-count since this is quite close to the straightforward Perl solution):

69 bytes -- ah what the heck, golfing took some effort too.

```<code>.01Round[395.6314#+{24.9284,83.0879}.(UnitStep[#-1]#&/@{#-10,#-27})]&
</code>```

EDIT regarding floating point error

The first three iterations of my answer are indeed exact in their decimal representation, since all coefficients involved have terminating decimal representations. However, since the coefficients are explicitly floats, stored in binary and having non-terminating binary representations, large enough inputs will start to accumulate errors in the least-significant digits of the binary representation. I would guess, when the float is so large, that it fits only 3-4 digits to the right of the decimal point, we can expect errors of around 1 cent. See below for an exact answer.

72 bytes, somewhat-immune to float inaccuracies

```<code>.01Round[{3956314,249284,830879}.(UnitStep[#-1]#&)/@(#-{0,10,27})/10^4]&
</code>```

The multiplication by the leading .01 is done at the very last step. Until that point, all calculation are done with integers. This means, that if the .01 is omitted, there will be an exact result, but expressed in cents, rather than dollars. Of course, the multiplication by a float converts the entire thing to a float, and, as mentioned, it needs to be small enough to fit into 64 bits and still be accurate to .01.

Title: Fred's water bill

Body:
Mathematica, 83 76 69 bytes

1.015{3.8476,.2456(b=Boole)[#>10],.8186b[#>27],51/1015}&~Array~#~Total~2~Round~.01&

Anonymous function that constructs an array of the three tiers in the first column plus the LIRA and PBOP represented as an arbitrary-precision number in the fourth column. The whole thing is multiplied by 1.015 and all elements of the array are summed and rounded to .01. Since 51/1015*1.015 will be the desired 0.051 the output is exactly as precise, as the specification in OP.

A shorter solution, in 76 bytes, as I have suggested in my comment under the Perl solution

{3.956314,.249284(b=Boole)[#>10],.830879b[#>27]}&~Array~#~Total~2~Round~.01&

where 1.015 is factored into the prices from the start and then the LIRA and PBOP is added on top of the first tier.

73 bytes (but I'm reluctant to update my byte-count since this is quite close to the straightforward Perl solution):

69 bytes -- ah what the heck, golfing took some effort too.

.01Round[395.6314#+{24.9284,83.0879}.(UnitStep[#-1]#&/@{#-10,#-27})]&

EDIT regarding floating point error

The first three iterations of my answer are indeed exact in their decimal representation, since all coefficients involved have terminating decimal representations. However, since the coefficients are explicitly floats, stored in binary and having non-terminating binary representations, large enough inputs will start to accumulate errors in the least-significant digits of the binary representation. I would guess, when the float is so large, that it fits only 3-4 digits to the right of the decimal point, we can expect errors of around 1 cent. See below for an exact answer.

72 bytes, somewhat-immune to float inaccuracies

.01Round[{3956314,249284,830879}.(UnitStep[#-1]#&)/@(#-{0,10,27})/10^4]&

The multiplication by the leading .01 is done at the very last step. Until that point, all calculation are done with integers. This means, that if the .01 is omitted, there will be an exact result, but expressed in cents, rather than dollars. Of course, the multiplication by a float converts the entire thing to a float, and, as mentioned, it needs to be small enough to fit into 64 bits and still be accurate to .01.


答:
MS-DOS Batch, 136 bytes

```<code>@echo 0 1 2 3 4 5 6 7
@echo ³ÚÙ ³ÚÙ ³ÚÙ ³ÚÙ
@echo ÀÅÄ¿ÀÅÄ¿ÀÅÄ¿ÀÅ¿
@echo ÚÙÚÅÄÙÚÅÄÙÚÅÄÙ³
@echo ³ ³À¿ ³À¿ ³À¿ ³
@echo 0 1 2 3 4 5 6 7
</code>```

Using @TimmyD's output. This might work in Windows Batch too, but my code page there is CP850, not CP437.

Title: Visualise Bit Weaving

Body:
MS-DOS Batch, 136 bytes

@echo 0 1 2 3 4 5 6 7
@echo ³ÚÙ ³ÚÙ ³ÚÙ ³ÚÙ
@echo ÀÅÄ¿ÀÅÄ¿ÀÅÄ¿ÀÅ¿
@echo ÚÙÚÅÄÙÚÅÄÙÚÅÄÙ³
@echo ³ ³À¿ ³À¿ ³À¿ ³
@echo 0 1 2 3 4 5 6 7

Using @TimmyD's output. This might work in Windows Batch too, but my code page there is CP850, not CP437.


答:
Python 2, 35 bytes

lambda x,y:50/(8+x*x/7-x+y*y/7-y)-4
```

<p>Try it online!</p>

<hr>

<p><strong>Python 2, 39 bytes</strong></p>

<pre class="lang-python prettyprint-override"><code>lambda x,y:50/(8-x*(7-x)/5-y*(7-y)/5)-4
</code>```

Try it online!

Takes inputs 0-indexed.

The expression x*(7-x)/5 takes the coordinate values 0..7 to

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

<p>(<code>min(x,7-x,2)</code> does the same, but is longer.) Summing this for <code>x</code> and <code>y</code> gives the right pattern but with the wrong numbers</p>

<pre class="lang-python prettyprint-override"><code>0 1 2 2 2 2 1 0
1 2 3 3 3 3 2 1
2 3 4 4 4 4 3 2
2 3 4 4 4 4 3 2
2 3 4 4 4 4 3 2
2 3 4 4 4 4 3 2
1 2 3 3 3 3 2 1
0 1 2 2 2 2 1 0
</code>```

(See Neil's solution for better reasoning as to why this gives about the right pattern.)

Finally, the mapping a -> 50/(8-a)-4 with floor-division gives the right values

2 3 4 4 4 4 3 2
3 4 6 6 6 6 4 3
4 6 8 8 8 8 6 4
4 6 8 8 8 8 6 4
4 6 8 8 8 8 6 4
4 6 8 8 8 8 6 4
3 4 6 6 6 6 4 3
2 3 4 4 4 4 3 2
```

<p>An alternative equally-long solution with 1-indexed inputs:</p>

<pre class="lang-python prettyprint-override"><code>lambda x,y:(x*(9-x)/6+y*(9-y)/6)**2/6+2
</code>```

Title: Knight on the Rim is Grim

Body:
Python 2, 35 bytes

lambda x,y:50/(8+x*x/7-x+y*y/7-y)-4

Try it online!

Python 2, 39 bytes

lambda x,y:50/(8-x*(7-x)/5-y*(7-y)/5)-4

Try it online!

Takes inputs 0-indexed.

The expression x*(7-x)/5 takes the coordinate values 0..7 to

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

(min(x,7-x,2) does the same, but is longer.) Summing this for x and y gives the right pattern but with the wrong numbers

0 1 2 2 2 2 1 0
1 2 3 3 3 3 2 1
2 3 4 4 4 4 3 2
2 3 4 4 4 4 3 2
2 3 4 4 4 4 3 2
2 3 4 4 4 4 3 2
1 2 3 3 3 3 2 1
0 1 2 2 2 2 1 0

(See Neil's solution for better reasoning as to why this gives about the right pattern.)

Finally, the mapping a -> 50/(8-a)-4 with floor-division gives the right values

2 3 4 4 4 4 3 2
3 4 6 6 6 6 4 3
4 6 8 8 8 8 6 4
4 6 8 8 8 8 6 4
4 6 8 8 8 8 6 4
4 6 8 8 8 8 6 4
3 4 6 6 6 6 4 3
2 3 4 4 4 4 3 2

An alternative equally-long solution with 1-indexed inputs:

lambda x,y:(x*(9-x)/6+y*(9-y)/6)**2/6+2


Title: Knight on the Rim is Grim

Body:
JavaScript (ES6), 38 bytes

(x,y)=>+"23468"[((7-x)*x+(7-y)*y)/5|0]

Takes 0-indexed inputs. Explanation: Look at the squares of the distances to the centre:

24.5 18.5 14.5 12.5 12.5 14.5 18.5 24.5
18.5 12.5  8.5  6.5  6.5  8.5 12.5 18.5
14.5  8.5  4.5  2.5  2.5  4.5  8.5 14.5
12.5  6.5  2.5  0.5  0.5  2.5  6.5 12.5
12.5  6.5  2.5  0.5  0.5  2.5  6.5 12.5
14.5  8.5  4.5  2.5  2.5  4.5  8.5 14.5
18.5 12.5  8.5  6.5  6.5  8.5 12.5 18.5
24.5 18.5 14.5 12.5 12.5 14.5 18.5 24.5

The number of reachable squares falls into five bands:

8    0-5
6    5-10
4   10-15
3   15-20
2   20-25

I actually calculate 24.5 - (3.5 - x) ** 2 - (3.5 - y) ** 2 = (7 - x) * x + (7 - y) * y as it's a shorter calculation, but all it does is reverse the order of the bands.


Title: Knight on the Rim is Grim

Body:
Haskell, <s>49</s> 48 bytes

w=[0..7]
x%y=sum[1|a<-w,b<-w,(a-x)^2+(b-y)^2==5]


答:
JavaScript ES6, 77 bytes

```<code>x=>(x>27?(x-27)*4.985477+109.681:(x>10?(x-10)*4.1546+39.053:x*3.9053))+.051*x
</code>```

Un-golfed

```<code>f = x => {
  if (x > 27) {
    res = (x - 27) * 4.985477 + 109.681306
  } else if (x > 10) {
    res = (x - 10) * 4.154598 + 39.05314
  } else {
    res = x * 3.905314
  }
  return res + 0.051 * x
}
</code>```

I factored in the LIRA and PBOP coefficients. The extra 1.5% gets added at the end.

Probably not the most efficient solution in terms of golfing but somewhat different from the Perl one.

Floating point error should occur with larger numbers and can be fixed by adding 1 or 2 extra bytes to each coefficient.

f=x=>(x>27?(x-27)*4.985477+109.681:(x>10?(x-10)*4.1546+39.053:x*3.9053))+.051*x

console.log(f(15))
console.log(f(100))
console.log(f(200000))```

Title: Fred's water bill

Body:
JavaScript ES6, 77 bytes

x=>(x>27?(x-27)*4.985477+109.681:(x>10?(x-10)*4.1546+39.053:x*3.9053))+.051*x

Un-golfed

f = x => {
  if (x > 27) {
    res = (x - 27) * 4.985477 + 109.681306
  } else if (x > 10) {
    res = (x - 10) * 4.154598 + 39.05314
  } else {
    res = x * 3.905314
  }
  return res + 0.051 * x
}

I factored in the LIRA and PBOP coefficients. The extra 1.5% gets added at the end.

Probably not the most efficient solution in terms of golfing but somewhat different from the Perl one.

Floating point error should occur with larger numbers and can be fixed by adding 1 or 2 extra bytes to each coefficient.

f=x=>(x>27?(x-27)*4.985477+109.681:(x>10?(x-10)*4.1546+39.053:x*3.9053))+.051*x

console.log(f(15))
console.log(f(100))
console.log(f(200000))


答:
APL, 21 chars

```<code>{+/,5=+/¨×⍨(⍳8 8)-⊂⍵}
</code>```

In English:

(⍳8 8): 8x8 rank-2 array containing the coordinates of all the cells;

+/¨×⍨(⍳8 8)-⊂⍵: square of the euclidean distances of the given cell with respect to every cell on the board;

5=: matrix of 0/1, where the 1s appear at squared distances equal 5;

+/,: sum the flattened matrix

Test (in origin 1):

```<code>    f←{+/,5=+/¨×⍨(⍳8 8)-⊂⍵}
    f¨1+(3 4)(4 6)(7 7)(1 0)
8 6 2 3
</code>```

In this form:

```<code>f←{+/,5=+/¨×⍨(⍳⍺)-⊂⍵}
</code>```

the left argument can specify the dimensions of the board. Hence 8 8 f will work for the standard square chessboard. But on a larger and rectangular board, the test cases would give different results. For instance, on a 12x10 board:

```<code>    g←(10 12)∘f
    g¨1+(3 4)(4 6)(7 7)(1 0)
8 8 8 3
</code>```

Title: Knight on the Rim is Grim

Body:
Introduction

Aron Nimzowitsch was a leading chess master and a influential chess writer.

In his book 'My System', the first chapter deals about the importance of the center and why you should dominate it. The simple reason is that your pieces have more possible direct next moves when being in the center which again gives the player more power.

This gets very clear when looking at different positions of a knight and its potential next moves (shown in pink) on an empty board:

Objective

Evaluate the number of potential direct next moves of a knight on an empty board based on its position.

Input Specs

The position of the knight.

First the x (column) and then the y (row). 0 0 is the left bottom corner.

For simplicity, I changed the labels of a chess board to numbers only. For our examples and test cases we use a 0-based index, you are free to use a 1-based index though.

You can use any type of possible input formats, an array, function arguments, etc.

Output Specs

The number of potential direct next moves for a knight on an empty board.

Test Cases

```<code>3 4 => 8
4 6 => 6
7 7 => 2
1 0 => 3
</code>```

Test cases are employing a 0-based index. The full grid of values is:

```<code>2 3 4 4 4 4 3 2
3 4 6 6 6 6 4 3
4 6 8 8 8 8 6 4
4 6 8 8 8 8 6 4
4 6 8 8 8 8 6 4
4 6 8 8 8 8 6 4
3 4 6 6 6 6 4 3
2 3 4 4 4 4 3 2
</code>```

Body:
APL, 21 chars

{+/,5=+/¨×⍨(⍳8 8)-⊂⍵}

In English:

(⍳8 8): 8x8 rank-2 array containing the coordinates of all the cells;

+/¨×⍨(⍳8 8)-⊂⍵: square of the euclidean distances of the given cell with respect to every cell on the board;

5=: matrix of 0/1, where the 1s appear at squared distances equal 5;

+/,: sum the flattened matrix

Test (in origin 1):

    f←{+/,5=+/¨×⍨(⍳8 8)-⊂⍵}
    f¨1+(3 4)(4 6)(7 7)(1 0)
8 6 2 3

In this form:

f←{+/,5=+/¨×⍨(⍳⍺)-⊂⍵}

the left argument can specify the dimensions of the board. Hence 8 8 f will work for the standard square chessboard. But on a larger and rectangular board, the test cases would give different results. For instance, on a 12x10 board:

    g←(10 12)∘f
    g¨1+(3 4)(4 6)(7 7)(1 0)
8 8 8 3


答:
Jelly, 10 bytes

```<code>8ṗ2_³²S€ċ5
</code>```

1-indexed. Takes a single argument of the form [x,y]. Try it here.

```<code>8ṗ2          Cartesian square [[1,1],[1,2]…[8,8]]
   _³        Subtract the input
     ²S€     Compute the norm of each vector
        ċ5   Count fives
</code>```

Dennis saved a byte!

Title: Knight on the Rim is Grim

Body:
Jelly, 10 bytes

8ṗ2_³²S€ċ5

1-indexed. Takes a single argument of the form [x,y]. Try it here.

8ṗ2          Cartesian square [[1,1],[1,2]…[8,8]]
   _³        Subtract the input
     ²S€     Compute the norm of each vector
        ċ5   Count fives

Dennis saved a byte!


答:
Python (118 characters)

Takes n as a command line argument. Could trim four more characters if the printing of first n  requirement is relaxed to first n or n + 1. I can't think of any more fat to trim...will be interested to see what a more experienced Python golfer could do

```<code>import sys
k,b=[1,2,2],1
n=int(sys.argv[1])
while len(k)<n:k.extend([2,1][b%2]for z in range(k[b+1]));b+=1
print k[:n]
</code>```

Title: Generate a Kolakoski sequence

Body:
Python (118 characters)

Takes n as a command line argument. Could trim four more characters if the printing of first n  requirement is relaxed to first n or n + 1. I can't think of any more fat to trim...will be interested to see what a more experienced Python golfer could do

import sys
k,b=[1,2,2],1
n=int(sys.argv[1])
while len(k)<n:k.extend([2,1][b%2]for z in range(k[b+1]));b+=1
print k[:n]


问:
Manage Trash So
It's become somewhat of a tradition in PPCG that some users temporarily change their names by an anagram (a new name formed by reordering the letters of the old).

Sometimes it gets difficult to find out who is who. I could use a program or function to tell if two phrases are anagrams of each other.

The challenge

The program or function should take two strings and produce a truthy result if they are anagrams of each other, and falsy otherwise.

Rules

Input will only contain letters (ASCII 65 to 90 and 97 to 122), digits (ASCII 48 to 57) or space (ASCII 32).

The anagram relation is independendent of case. So "Arm" and "RAM" are anagrams.

Spaces don't count either. So "keyboard" and "Barked Yo" are anagrams

All builtins allowed

Input format is flexible (two strings, an array of two strings, a string containing both phrases with a suitable separator ...)

Code golf. Fewest bytes wins.

Test cases

Truthy:

```<code>Lynn, Nyl N
Digital Trauma, Tau Digital Arm
Sp3000, P S 3000
Manage Trash So, Those anagrams
</code>```

Falsy

```<code>Calvins Hobbies, Helka Homba
Android, rains odd
In between days, bayed entwine
Code golf, cod elf got
</code>```

答:
APL, 31 chars

```<code>{≡/{x[⍋x←('.'⎕R'\u0')⍵~' ']}¨⍵}
</code>```

To be used so:

```<code>    {≡/{x[⍋x←('.'⎕R'\u0')⍵~' ']}¨⍵}'Sp3000' 'P S 3000'
1
</code>```

In English:

{ ... }¨⍵: for each of the two elements of the argument

x←('.'⎕R'\u0')⍵~' ': transform to uppercase (using a regex...) the string without the spaces and assign the temporary result to x

x[⍋x]: sort x

≡/: compare the two results of the sorting: if they match, return 1.

Title: Manage Trash So

Body:
APL, 31 chars

{≡/{x[⍋x←('.'⎕R'\u0')⍵~' ']}¨⍵}

To be used so:

    {≡/{x[⍋x←('.'⎕R'\u0')⍵~' ']}¨⍵}'Sp3000' 'P S 3000'
1

In English:

{ ... }¨⍵: for each of the two elements of the argument

x←('.'⎕R'\u0')⍵~' ': transform to uppercase (using a regex...) the string without the spaces and assign the temporary result to x

x[⍋x]: sort x

≡/: compare the two results of the sorting: if they match, return 1.


问:
A multiplication table for the Cheela
The Cheela (from the book Dragon's Egg by Robert L. Forward) are creatures that live on the surface of a neutron star. Their body is flat and circular with twelve eyes on the perimeter, so they naturally use a base-12 numbering system.

Among the Cheela, care of the hatchlings and education of the young are tasks carried out by the Old Ones. Since young Cheela need to be taught how to multiply, the Old Ones could use a multiplication table.

Your task is to produce a 12x12 multiplication table in base 12, like the following. Uppercase letters A and B are used for digits corresponding to decimal 10  and 11 respectively.

```<code>  1   2   3   4   5   6   7   8   9   A   B  10
  2   4   6   8   A  10  12  14  16  18  1A  20
  3   6   9  10  13  16  19  20  23  26  29  30
  4   8  10  14  18  20  24  28  30  34  38  40
  5   A  13  18  21  26  2B  34  39  42  47  50
  6  10  16  20  26  30  36  40  46  50  56  60
  7  12  19  24  2B  36  41  48  53  5A  65  70
  8  14  20  28  34  40  48  54  60  68  74  80
  9  16  23  30  39  46  53  60  69  76  83  90
  A  18  26  34  42  50  5A  68  76  84  92  A0
  B  1A  29  38  47  56  65  74  83  92  A1  B0
 10  20  30  40  50  60  70  80  90  A0  B0 100
</code>```

The output shoud be printed on screen. The format should be as follows:

Numbers should be aligned to the right within each column.

Leading spaces before the first column, trailing spaces after the last column, or a trailing new line after the last row are allowed.

Separation between columns can be one space (as shown above) or more than one space, but the number of spaces should be consistent between columns. To measure column separation, consider that displayed numbers include any leading spaces that may have been necessary fo fulfill requirement 1 (so each number occupies three characters, the first of which may be spaces). For example, the table with two-space separation would be as follows:

```<code>  1    2    3    4    5    6    7    8    9    A    B   10
  2    4    6    8    A   10   12   14   16   18   1A   20
  3    6    9   10   13   16   19   20   23   26   29   30
  4    8   10   14   18   20   24   28   30   34   38   40
  5    A   13   18   21   26   2B   34   39   42   47   50
  6   10   16   20   26   30   36   40   46   50   56   60
  7   12   19   24   2B   36   41   48   53   5A   65   70
  8   14   20   28   34   40   48   54   60   68   74   80
  9   16   23   30   39   46   53   60   69   76   83   90
  A   18   26   34   42   50   5A   68   76   84   92   A0
  B   1A   29   38   47   56   65   74   83   92   A1   B0
 10   20   30   40   50   60   70   80   90   A0   B0  100
</code>```

Computer storage on a neutron star is really expensive, so your code should use as few bytes as possible.

Extended challenge and bonus

Ideally your code should be reused in other parts of the universe, where other numbering systems may be in use. To that end, the challenge is optionally extended as follows: Your code accepts a number N as input and generates an NxN multiplication table in base N, with the above format.

Input may be from keyboard or as a function argument. The program or function should work for 2 ≤ N ≤ 36, using as digits the first N characters of the sequence 0, 1, ..., 9, A, B, ..., Z (uppercase letters)

This extended challenge is optional. If you follow this route, take 20% off your byte count (no need to round to an integer number).

答:
APL, <s>32</s> 31×0.8=24.8 bytes

```<code>{¯4↑¨⊃∘(⎕D,⎕A)¨¨⍵⊥⍣¯1¨∘.×⍨1+⍳⍵}
</code>```

In origin 0.
In English:

∘.×⍨1+⍳⍵: multiplication table

⍵⊥⍣¯1¨: express in base ⍵ each element of the multiplication table

⊃∘(⎕D,⎕A)¨¨: convert the table of vector of numbers into a table of vectors of chars

¯4↑¨: right align to length 4 each element of the result

The default APL print routine does the right thing.

```<code>      {¯4↑¨(⍵⊥⍣¯1¨∘.×⍨1+⍳⍵)⊃¨¨⊂⊂⎕D,⎕A}13
    1     2     3     4     5     6     7     8     9     A     B     C    10
    2     4     6     8     A     C    11    13    15    17    19    1B    20
    3     6     9     C    12    15    18    1B    21    24    27    2A    30
    4     8     C    13    17    1B    22    26    2A    31    35    39    40
    5     A    12    17    1C    24    29    31    36    3B    43    48    50
    6     C    15    1B    24    2A    33    39    42    48    51    57    60
    7    11    18    22    29    33    3A    44    4B    55    5C    66    70
    8    13    1B    26    31    39    44    4C    57    62    6A    75    80
    9    15    21    2A    36    42    4B    57    63    6C    78    84    90
    A    17    24    31    3B    48    55    62    6C    79    86    93    A0
    B    19    27    35    43    51    5C    6A    78    86    94    A2    B0
    C    1B    2A    39    48    57    66    75    84    93    A2    B1    C0
   10    20    30    40    50    60    70    80    90    A0    B0    C0   100
</code>```

Title: A multiplication table for the Cheela

Body:
APL, <s>32</s> 31×0.8=24.8 bytes

{¯4↑¨⊃∘(⎕D,⎕A)¨¨⍵⊥⍣¯1¨∘.×⍨1+⍳⍵}

In origin 0.
In English:

∘.×⍨1+⍳⍵: multiplication table

⍵⊥⍣¯1¨: express in base ⍵ each element of the multiplication table

⊃∘(⎕D,⎕A)¨¨: convert the table of vector of numbers into a table of vectors of chars

¯4↑¨: right align to length 4 each element of the result

The default APL print routine does the right thing.

      {¯4↑¨(⍵⊥⍣¯1¨∘.×⍨1+⍳⍵)⊃¨¨⊂⊂⎕D,⎕A}13
    1     2     3     4     5     6     7     8     9     A     B     C    10
    2     4     6     8     A     C    11    13    15    17    19    1B    20
    3     6     9     C    12    15    18    1B    21    24    27    2A    30
    4     8     C    13    17    1B    22    26    2A    31    35    39    40
    5     A    12    17    1C    24    29    31    36    3B    43    48    50
    6     C    15    1B    24    2A    33    39    42    48    51    57    60
    7    11    18    22    29    33    3A    44    4B    55    5C    66    70
    8    13    1B    26    31    39    44    4C    57    62    6A    75    80
    9    15    21    2A    36    42    4B    57    63    6C    78    84    90
    A    17    24    31    3B    48    55    62    6C    79    86    93    A0
    B    19    27    35    43    51    5C    6A    78    86    94    A2    B0
    C    1B    2A    39    48    57    66    75    84    93    A2    B1    C0
   10    20    30    40    50    60    70    80    90    A0    B0    C0   100


答:
05AB1E, <s>64</s> <s>58</s> 51 bytes

```<code>0T27¹)vy¹‚ï{0è})¥•_ÄÄ™wu24@•2'.:7ô)ø€PO¹"5.1"*+ïTn/
</code>```

Explained

```<code>0T27¹)                                               # list of price brackets
      vy¹‚ï{0è})                                     # min of each with input
                ¥                                    # calculate deltas to get amounts within each bracket
                 •_ÄÄ™wu24@•2'.:7ô                   # list of price rates with CPUC included
                                  )ø                 # zip with amounts for each rate
                                    €PO              # multiply amounts by their rates and sum
                                       ¹"5.1"*+      # add LIRA/PBOP
                                               ïTn/  # round to 2 decimals
</code>```

Try it online

Title: Fred's water bill

Body:
Fred is a quasi-friendly guy, but in reality he is mean.

Because of this, Fred lives alone in a small apartment in Los Altos, CA. Fred is so mean because he is very particular about water. He, therefore, needs your help with figuring out what his water bill is.

Your job is to write a function or program that returns his water bill given the amount of water used as input (which is always an integer).

Water consumption comes in tiers. This means that there are ranges of prices depending on the amount of water.

These are the tiers, their prices, and the amounts of water they correspond to:

```<code>Tier I
   First 10 Ccf: $3.8476/Ccf
Tier II
   Next 17 Ccf: $4.0932/Ccf
Tier III
   All subsequent water: $4.9118/Ccf
</code>```

For n hundreds of cubic feet (Ccf), there are the following additional charges as well:

```<code>CPUC fee: 1.5% of above charges
LIRA quantity surcharge: $0.047*n
PBOP amoritization surcharge: $0.004*n
</code>```

The sum of the Tier I, Tier II, Tier III, CPUC, LIRA, and PBOP fees is the total water bill. This sum you should either return or print to the console rounded to two decimal places.

Here are two examples:

```<code>Input: 15
... Calculations which you do not need to output but here to help explain:
Tier I: 10*3.8476 = 38.476
Tier II: (15-10)*4.0932 = 20.466
Tier III: 0*4.9118 = 0
Tiers sum: 58.942
CPUC: 1.5% of 58.942 = 0.88413
LIRA: 0.047*15 = 0.705
PBOP: 0.004*15 = 0.06
Total sum: 58.942 + 0.88413 + 0.705 + 0.06 = 60.59113
...
Output: 60.59

Input: 100
... Calculations which you do not need to output but here to help explain:
Tier I: 10*3.8476 = 38.476
Tier II: 17*4.0932 = 69.5844
Tier III: (100-10-17)*4.9118 = 358.5614
Tiers sum: 466.6218
CPUC: 1.5% of  = 6.999327
LIRA: 0.047*100 = 4.7
PBOP: 0.004*100 = 0.4
Total sum: 478.721127
...
Output: 478.72
</code>```

This is code golf so shortest code in bytes wins!

Body:
05AB1E, <s>64</s> <s>58</s> 51 bytes

0T27¹)vy¹‚ï{0è})¥•_ÄÄ™wu24@•2'.:7ô)ø€PO¹"5.1"*+ïTn/

Explained

0T27¹)                                               # list of price brackets
      vy¹‚ï{0è})                                     # min of each with input
                ¥                                    # calculate deltas to get amounts within each bracket
                 •_ÄÄ™wu24@•2'.:7ô                   # list of price rates with CPUC included
                                  )ø                 # zip with amounts for each rate
                                    €PO              # multiply amounts by their rates and sum
                                       ¹"5.1"*+      # add LIRA/PBOP
                                               ïTn/  # round to 2 decimals

Try it online


问:
Theoretically output Graham's number
Graham's number G is defined in this way:

```<code>u(3,n,1) = 3^n
u(3,1,m) = 3
u(3,n,m) = u(3,u(3,n-1,m),m-1)
[Knuth's up-arrow notation]
[Conway chained arrow notation]

THEN

g1 = u(3,3,4)
g2 = u(3,3,g1)
g3 = u(3,3,g2)
...
G = u(3,3,g63)
</code>```

You are given that u(3,3,2)=7625597484987 to check your code.

Your task is to write a program/function that will output the value of G deterministically, given enough integer size and enough time.

References

Graham's number

Knuth's up-arrow notation

Conway chained arrow notation

Leaderboard

var QUESTION_ID=83873,OVERRIDE_USER=48934;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="
"+e.body.replace(OVERRIDE_REG,"")+"
")});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;/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+(?:\.\d+)?)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

答:
Prolog (SWIPL), 129 / 137 bytes

```<code>g(1,R):-u(3,4,R).
g(L,R):-M is L-1,g(M,P),u(3,P,R).
u(N,1,R):-R is 3**N.
u(1,_,3).
u(N,M,R):-K is N-1,L is M-1,u(K,M,Y),u(Y,L,R).
</code>```

To output Graham's number, query for g(64,G). (if the 8 bytes of this query are to be counted, the length is 137 bytes):

```<code>?- g(64, G).
ERROR: Out of local stack
</code>```

But as can be expected, this runs out of stack.

Test

```<code>?- u(3, 2, X).
X = 7625597484987
</code>```

Backtracking causes it to run out of stack:

```<code>?- u(3, 2, X).
X = 7625597484987 ;
ERROR: Out of local stack
</code>```

Ungolfed

The ungolfed version adds the general up-arrow notation, not just for 3, and uses cuts and checks to avoid backtracking and undefined situations.

```<code>% up-arrow notation
u(X, 1, _M, X) :- !.
u(X, N, 1, R) :-
    R is X**N, !.
u(X, N, M, R) :-
    N > 1,
    M > 1,
    N1 is N - 1,
    M1 is M - 1,
    u(X, N1, M, R1),
    u(X, R1, M1, R).

% graham's number
g(1,R) :- u(3, 3, 4, R), !.
g(L,R) :-
    L > 1,
    L1 is L - 1,
    g(L1,G1),
    u(3, G1, R).
</code>```

Title: Theoretically output Graham's number

Body:
Prolog (SWIPL), 129 / 137 bytes

g(1,R):-u(3,4,R).
g(L,R):-M is L-1,g(M,P),u(3,P,R).
u(N,1,R):-R is 3**N.
u(1,_,3).
u(N,M,R):-K is N-1,L is M-1,u(K,M,Y),u(Y,L,R).

To output Graham's number, query for g(64,G). (if the 8 bytes of this query are to be counted, the length is 137 bytes):

?- g(64, G).
ERROR: Out of local stack

But as can be expected, this runs out of stack.

Test

?- u(3, 2, X).
X = 7625597484987

Backtracking causes it to run out of stack:

?- u(3, 2, X).
X = 7625597484987 ;
ERROR: Out of local stack

Ungolfed

The ungolfed version adds the general up-arrow notation, not just for 3, and uses cuts and checks to avoid backtracking and undefined situations.

% up-arrow notation
u(X, 1, _M, X) :- !.
u(X, N, 1, R) :-
    R is X**N, !.
u(X, N, M, R) :-
    N > 1,
    M > 1,
    N1 is N - 1,
    M1 is M - 1,
    u(X, N1, M, R1),
    u(X, R1, M1, R).

% graham's number
g(1,R) :- u(3, 3, 4, R), !.
g(L,R) :-
    L > 1,
    L1 is L - 1,
    g(L1,G1),
    u(3, G1, R).


答:
Pyth, <s>55</s> 41 bytes

```<code>.R+s*Vv.",9t¬®Ï0NwÝ"lMcUQ,T27*.051Q2
</code>```

The code contains unprintable characters, so here's a xxd hexdump.

```<code>00000000: 2e52 2b73 2a56 762e 222c 3904 1874 c2ac  .R+s*Vv.",9..t..
00000010: c2ae c280 c293 c38f 301c 4e77 c39d 226c  ........0.Nw.."l
00000020: 4d63 5551 2c54 3237 2a2e 3035 3151 32    McUQ,T27*.051Q2
</code>```

Explanation

."…" is a packed string that contains 3.8476,4.0932,4.9118.

v evaluates that to the tuple (3.8476, 4.0932, 4.9118). These are the tiers' prices multiplied with CPUC added.

UQ generates the range 0…n-1.

c…,T27 splits that range at indices 10 and 27, with extra empty lists in the end if the range is too short.

lM finds the length of each part, giving the amount of water for each tier.

*V multiplies that by the tuple from step 2 to get the prices for the tiers.

s sums the results.

+…*Q.051 adds the input multiplied by 0.051, i.e. LIRA + PBOP.

.R…2 rounds the result to 2 decimals.

Try it online.

Title: Fred's water bill

Body:
Pyth, <s>55</s> 41 bytes

.R+s*Vv.",9t¬®Ï0NwÝ"lMcUQ,T27*.051Q2

The code contains unprintable characters, so here's a xxd hexdump.

00000000: 2e52 2b73 2a56 762e 222c 3904 1874 c2ac  .R+s*Vv.",9..t..
00000010: c2ae c280 c293 c38f 301c 4e77 c39d 226c  ........0.Nw.."l
00000020: 4d63 5551 2c54 3237 2a2e 3035 3151 32    McUQ,T27*.051Q2

Explanation

."…" is a packed string that contains 3.8476,4.0932,4.9118.

v evaluates that to the tuple (3.8476, 4.0932, 4.9118). These are the tiers' prices multiplied with CPUC added.

UQ generates the range 0…n-1.

c…,T27 splits that range at indices 10 and 27, with extra empty lists in the end if the range is too short.

lM finds the length of each part, giving the amount of water for each tier.

*V multiplies that by the tuple from step 2 to get the prices for the tiers.

s sums the results.

+…*Q.051 adds the input multiplied by 0.051, i.e. LIRA + PBOP.

.R…2 rounds the result to 2 decimals.

Try it online.


答:
///, 112 bytes (100 chars)

```<code>/8/0 1 2 3 4 5 6 7//9/│//A/└┐//B/┌┼┘/8/C/9 A9 A9 A9//D/9A 9A 9A 9/
AC
B B B B
DA
C 9
9 B B B 9
9 D
8
</code>```

Thanks @MartinEnder for -3 bytes!

Thanks @MartinEnder for -9 bytes!

Thanks @MartinEnder (OP) for pointing 15-char rule out

Uses <s>@TimmyD's</s> @Marco's output```0 1 2 3 4 5 6 7
└┐│ └┐│ └┐│ └┐│
┌┼┘ ┌┼┘ ┌┼┘ ┌┼┘
│└┐ │└┐ │└┐ │└┐
│ └┐│ └┐│ └┐│ │
│ ┌┼┘ ┌┼┘ ┌┼┘ │
│ │└┐ │└┐ │└┐ │
0 1 2 3 4 5 6 7```

Title: Visualise Bit Weaving

Body:
The esoteric programming language evil has an interesting operation on byte values which it calls "weaving". It is essentially a permutation of the eight bits of the byte (it doesn't matter which end we start counting from, as the pattern is symmetric):

Bit 0 is moved to bit 2

Bit 1 is moved to bit 0

Bit 2 is moved to bit 4

Bit 3 is moved to bit 1

Bit 4 is moved to bit 6

Bit 5 is moved to bit 3

Bit 6 is moved to bit 7

Bit 7 is moved to bit 5

For convenience, here are two other representations of the permutation. As a cycle:

```<code>(02467531)
</code>```

And as a list of pairs of the mapping:

```<code>[[0,2], [1,0], [2,4], [3,1], [4,6], [5,3], [6,7], [7,5]]
</code>```

Your task is to visualise this permutation, using the box-drawing characters ─, │, ┌, ┐, └, ┘, ┼ (Unicode code points: U+2500, U+2502, U+250C, U+2510, U+2514, U+2518, U+253C). This visualisation should satisfy the following constraints:

The first and last line are exactly:

```<code>0 1 2 3 4 5 6 7
</code>```

Between those, you can use as many lines as you want of up to 15 characters each to fit your box drawing characters (you will need at least 4 lines). The lines should start vertically beneath one of the digits on the first row and end vertically above the corresponding digit on the last row. The eight lines must be connected, and may only cross via ┼ (which is always a crossing, never two turning lines which are touching). The exact paths of the lines are up to you (and finding a particularly golfable layout is the core of this challenge). One valid output would be:

```<code>0 1 2 3 4 5 6 7
│ │ └─┼┐│ │ └┐│
└─┼─┐ ││└─┼─┐││
┌─┘ │ ││  │ │││
│ ┌─┼─┘│  │ │││
│ │ │ ┌┼──┘ │││
│ │ │ │└┐ ┌─┼┼┘
│ │ │ │ │ │ │└┐
0 1 2 3 4 5 6 7
</code>```

However, any other layout that correctly connects the right digits is fine too. Please show your chosen output in your answer.

You may write a program or function and will not take any input. Output the diagram either to STDOUT (or closest alternative) or as a function return value in the form of a string or a list of strings (each representing one line).

Standard code-golf rules apply, so the shortest code (in bytes) wins.

Body:
///, 112 bytes (100 chars)

/8/0 1 2 3 4 5 6 7//9/│//A/└┐//B/┌┼┘/8/C/9 A9 A9 A9//D/9A 9A 9A 9/
AC
B B B B
DA
C 9
9 B B B 9
9 D
8

Thanks @MartinEnder for -3 bytes!

Thanks @MartinEnder for -9 bytes!

Thanks @MartinEnder (OP) for pointing 15-char rule out

Uses <s>@TimmyD's</s> @Marco's output
0 1 2 3 4 5 6 7
└┐│ └┐│ └┐│ └┐│
┌┼┘ ┌┼┘ ┌┼┘ ┌┼┘
│└┐ │└┐ │└┐ │└┐
│ └┐│ └┐│ └┐│ │
│ ┌┼┘ ┌┼┘ ┌┼┘ │
│ │└┐ │└┐ │└┐ │
0 1 2 3 4 5 6 7


Title: Knight on the Rim is Grim

Body:
C, 44 Bytes

f(x,y){return "23468"[((7-x)*x+(7-y)*y)/5];}

But this is better:

f(x,y){return "2344443234666643468888644688886446888864468888643466664323444432"[x*8+y];}


答:
Mathematica <s>63</s> 43 bytes

With 20 bytes saved thanks to suggestions by Martin Ender!

```<code>EdgeCount[8~KnightTourGraph~8,#+1+8#2/<->_]&
</code>```

The above finds the number of squares that are 1 hop away from the given cell on the  complete knights tour graph.

g=KnightTourGraph[8,8,VertexLabels->"Name",Axes->True]

displays the complete knight's tour graph, with vertex names and coordinates.  Note that Mathematica defaults to one-based indexing for the coordinates.

#+1+8#2&[r,f] converts returns the vertex corresponding to square at rank (row), r, and file (column), f, using zero-based values as input.

For example #+1+8#2&[2,1] returns 11.

EdgeCount gives the number of edges in the neighborhood graph.

The edges for rank 2, file 1 (square 11):

```<code>IncidenceList[8~KnightTourGraph~8, 8 #2 + # + 1] &[2, 1]

(*{1 <-> 11, 5 <-> 11, 11 <-> 17, 11 <-> 21, 11 <-> 26, 11 <-> 28}*)
</code>```

The highlighted edges:

```<code>HighlightGraph[g, {1, 5, 11, 17, 21, 26, 28, Style[1 <-> 11, Thick, Blue], Style[5 <-> 11, Thick, Blue], Style[11 <-> 17, Thick, Blue], Style[11 <-> 21, Thick, Blue], Style[11 <-> 26, Thick, Blue], Style[11 <-> 28, Thick, Blue]},GraphHighlightStyle -> "DehighlightFade", PlotRangePadding -> .5]
</code>```

Method 2: Euclidean distance

70 bytes

This method is longer, but possibly of some interest.  The approach is to check the Euclidean distance between the center of the chessboard and the cell of interest.

```<code>Which[(x=Sqrt@Tr[({3.5, 3.5}-#)^2])<2.2,8,x<3,6,x<4,4,x<4.6,3,x>4.6,2]&
</code>```

Exemplifying

```<code>Which[(x=Sqrt@Tr[({3.5, 3.5}-#)^2])<2.2,8,x<3,6,x<4,4,x<4.6,3,x>4.6,2]&@{0, 0}
Which[(x=Sqrt@Tr[({3.5, 3.5}-#)^2])<2.2,8,x<3,6,x<4,4,x<4.6,3,x>4.6,2]&@{3, 3}
</code>```

2

8

To help visualize how the distance from the center of the chessboard is sufficient for assigning a value.

```<code>values={{2,3,4,4,4,4,3,2},{3,4,6,6,6,6,4,3},{4,6,8,8,8,8,6,4},{4,6,8,8,8,8,6,4},{4,6,8,8,8,8,6,4},{4,6,8,8,8,8,6,4},{3,4,6,6,6,6,4,3},{2,3,4,4,4,4,3,2}};
f[x_]:=Text[x,#]&/@Position[values,x]r_~w~p_:=RegionMember[{3.5`,3.5`}~Disk~r,p]
h@y_:=Which[2.2~w~y,8,3~w~y,6,4~w~y,4,4.6~w~y,3,2<3,2]

Graphics[{Circle[{4.5, 4.5}, 2.3], Circle[{4.5, 4.5}, 3],
</code>```

Circle[{4.5, 4.5}, 4],

Circle[{4.5, 4.5}, 4.6], Flatten[f /@ {2, 3, 4, 6, 8}, 1]}, Axes -> True, AxesOrigin -> {-1, -1}]

The numbers 2.2, 3, 4, and 4.6 are the radii of the circles.

Title: Knight on the Rim is Grim

Body:
Mathematica <s>63</s> 43 bytes

With 20 bytes saved thanks to suggestions by Martin Ender!

EdgeCount[8~KnightTourGraph~8,#+1+8#2/<->_]&

The above finds the number of squares that are 1 hop away from the given cell on the  complete knights tour graph.

g=KnightTourGraph[8,8,VertexLabels->"Name",Axes->True]

displays the complete knight's tour graph, with vertex names and coordinates.  Note that Mathematica defaults to one-based indexing for the coordinates.

#+1+8#2&[r,f] converts returns the vertex corresponding to square at rank (row), r, and file (column), f, using zero-based values as input.

For example #+1+8#2&[2,1] returns 11.

EdgeCount gives the number of edges in the neighborhood graph.

The edges for rank 2, file 1 (square 11):

IncidenceList[8~KnightTourGraph~8, 8 #2 + # + 1] &[2, 1]

(*{1 <-> 11, 5 <-> 11, 11 <-> 17, 11 <-> 21, 11 <-> 26, 11 <-> 28}*)

The highlighted edges:

HighlightGraph[g, {1, 5, 11, 17, 21, 26, 28, Style[1 <-> 11, Thick, Blue], Style[5 <-> 11, Thick, Blue], Style[11 <-> 17, Thick, Blue], Style[11 <-> 21, Thick, Blue], Style[11 <-> 26, Thick, Blue], Style[11 <-> 28, Thick, Blue]},GraphHighlightStyle -> "DehighlightFade", PlotRangePadding -> .5]

Method 2: Euclidean distance

70 bytes

This method is longer, but possibly of some interest.  The approach is to check the Euclidean distance between the center of the chessboard and the cell of interest.

Which[(x=Sqrt@Tr[({3.5, 3.5}-#)^2])<2.2,8,x<3,6,x<4,4,x<4.6,3,x>4.6,2]&

Exemplifying

Which[(x=Sqrt@Tr[({3.5, 3.5}-#)^2])<2.2,8,x<3,6,x<4,4,x<4.6,3,x>4.6,2]&@{0, 0}
Which[(x=Sqrt@Tr[({3.5, 3.5}-#)^2])<2.2,8,x<3,6,x<4,4,x<4.6,3,x>4.6,2]&@{3, 3}

2

8

To help visualize how the distance from the center of the chessboard is sufficient for assigning a value.

values={{2,3,4,4,4,4,3,2},{3,4,6,6,6,6,4,3},{4,6,8,8,8,8,6,4},{4,6,8,8,8,8,6,4},{4,6,8,8,8,8,6,4},{4,6,8,8,8,8,6,4},{3,4,6,6,6,6,4,3},{2,3,4,4,4,4,3,2}};
f[x_]:=Text[x,#]&/@Position[values,x]r_~w~p_:=RegionMember[{3.5`,3.5`}~Disk~r,p]
h@y_:=Which[2.2~w~y,8,3~w~y,6,4~w~y,4,4.6~w~y,3,2<3,2]

Graphics[{Circle[{4.5, 4.5}, 2.3], Circle[{4.5, 4.5}, 3],

Circle[{4.5, 4.5}, 4],

Circle[{4.5, 4.5}, 4.6], Flatten[f /@ {2, 3, 4, 6, 8}, 1]}, Axes -> True, AxesOrigin -> {-1, -1}]

The numbers 2.2, 3, 4, and 4.6 are the radii of the circles.