答:
R, 261 bytes

I think I spent way too much time just to get this working and I believe this is an unnecessarily complicated solution, although it works. Takes input from stdin, it's important that the string is enclosed in quotes.

```<code>x=el(strsplit(toupper(scan(,""))," "))
cat(apply(sapply(c("A","O"),function(y)sapply(sapply(regmatches(x,gregexpr("[AEIOU]{2,}",x,)),paste,collapse=""),function(s)min(sum(el(strsplit(s,""))%in%y),4)))+1,1,function(z)t(matrix(LETTERS[-10],5))[z[1],z[2]]),sep="")
</code>```

The use of four nested apply-family could theoretically be reduced to only two by making use of mapply instead. But because inputs to mapply will not be of the same length, the shorter one is recycled which complicates things and I couldn't figure out a working solution.

If anyone is interested I'll add an ungolfed explanation later.

Try all the test cases on R-fiddle

Please note that this version takes input as a function argument instead from stdin because scan doesn't work on R-fiddle. Furthermore, added a newline to make it easier to read.

Title: Decode Baby-talk!

Body:
When babies open their mouths, they're not just spewing gibberish. They're actually talking in a highly advanced, adult-proof cipher...

The Baby-talk Cipher

When a baby talks, it could look something like gogooa gagooook aagaaoooy
Each single-space separated section represents a character (so the example above represents 3 characters).

To decipher a section, we must count number of As and Os it contains. However, we only count those which are adjacent to another vowel. For example, the A in 'gag' would not count, but both the A and O in 'gaog' would.

Counting the example above would look like this:

```<code>Section    | Num Os | Num As

gogooa     | 2      | 1
gagooook   | 4      | 0
aagaaoooy  | 3      | 4
</code>```

We then use these values to convert the input into plaintext on a Polybius square. This is a 5x5 representation of the English alphabet, omitting 'J' (please note that, in baby-talk, 0-counting rules apply to the table):

```<code>  0 1 2 3 4
0 A B C D E
1 F G H I K
2 L M N O P
3 Q R S T U
4 V W X Y Z
</code>```

Using the number of Os as the column, and number of As as the row, we find which character each section represents:

```<code>Section    | Num Os | Num As | Character

gogooa     | 2      | 1      | (2,1) -> H
gagooook   | 4      | 0      | (4,0) -> E
aagaaoooy  | 3      | 4      | (3,4) -> Y
</code>```

Which tells us that the baby was just saying "HEY".

Notes:

- If a section representing a character has more than 4 As or Os, ignore the extras, because 4 is the maximum value on the table.
- For this task, Y is not a vowel - only A, E, I, O and U.

The Challenge

Your task is to create a full program which takes one input, a word in baby-speak, and prints it in plaintext.

Your program must be able to take input in uppercase, lowercase, and a mix of both.

The input will only contain ASCII alphabet letters (A-Z and a-z), with single spaces to seperate the baby words.

The output text can be in any case.

You should the take the input from STDIN and print the plaintext on STDOUT. If your language does not have these, use the nearest equivalent.

This is code-golf, so the shortest code in bytes wins - but any solution is welcome.

Test Cases

```<code>'GLOOG KAKAAOOO ARGOOO OOOOOGUGUU' -> CODE
'oaka pooopaa gaau augu' -> GOLF
'Aoao U oOOAoa oaoAoo aoAoAOa' -> NAPPY
'GUG gAGaA gOougOou' -> ALE
'OOaGOG GoGOOoGoU gAA bLAA GOUGoOUgAIGAI' -> HELLO
</code>```

Body:
R, 261 bytes

I think I spent way too much time just to get this working and I believe this is an unnecessarily complicated solution, although it works. Takes input from stdin, it's important that the string is enclosed in quotes.

x=el(strsplit(toupper(scan(,""))," "))
cat(apply(sapply(c("A","O"),function(y)sapply(sapply(regmatches(x,gregexpr("[AEIOU]{2,}",x,)),paste,collapse=""),function(s)min(sum(el(strsplit(s,""))%in%y),4)))+1,1,function(z)t(matrix(LETTERS[-10],5))[z[1],z[2]]),sep="")

The use of four nested apply-family could theoretically be reduced to only two by making use of mapply instead. But because inputs to mapply will not be of the same length, the shorter one is recycled which complicates things and I couldn't figure out a working solution.

If anyone is interested I'll add an ungolfed explanation later.

Try all the test cases on R-fiddle

Please note that this version takes input as a function argument instead from stdin because scan doesn't work on R-fiddle. Furthermore, added a newline to make it easier to read.


问:
Count trailing truths

Inspired by, and in memory of, my dear friend and colleague,

Dan Baronet, 1956 – 2016. R.I.P.

He found the shortest possible APL solution to this task:

Task

Given a Boolean list, count the number of trailing truth values.

Example cases

{} → 0

{0} → 0

{1} → 1

{0, 1, 1, 0, 0} → 0

{1, 1, 1, 0, 1} → 1

{1, 1, 0, 1, 1} → 2

{0, 0, 1, 1, 1} → 3

{1, 1, 1, 1, 1, 1} → 6

答:
Perl 5.10, 22 bytes

21 bytes + 1 byte for -a flag.
Since the regex-based expression was done... :p

The input values for the array must be separated by a space.

```<code>$n++while pop@F;say$n
</code>```

Try it online!

ContentLicense: CC BY-SA 4.0

Title: Count trailing truths

Body:
Perl 5.10, 22 bytes

21 bytes + 1 byte for -a flag.
Since the regex-based expression was done... :p

The input values for the array must be separated by a space.

$n++while pop@F;say$n

Try it online!

ContentLicense: CC BY-SA 3.0


答:
Vim, <s> 44 </s> 27 bytes

EDIT Lot of bytes won thanks to @DrMcMoylex:

```<code>5i\<esc>5a/<esc>0y$5PY4P5x$pY3PyGPP
</code>```

Original answer:

I'm not sure that really fits the rules of this site but I thought that was fun to try it:

```<code>i\<esc>59.:s;\v(.{5})\1;\1/////;g<CR>Y4P5x$pY3PyGPP
</code>```

Which can be decomposed like this:

```<code>i\<esc>                       Insert a \
59.                           Repeat 59 time the insertion
:s;\v(.{5})\1;\1/////;g<CR>   Match 5 characters followed by the same 5 characters
                              And replace them by these 5 characters followed by 5 /
Y4P                           Copy the line and repeat it 4 times
5x$p                          On the current line delete 5 characters and put them
                              at the end of the line
Y3P                           Copy the line and repeat it 3 times
yG                            Copy all the lines
PP                            Repeat them 2 times
</code>```

Title: This is my pillow

Body:
...will you help me immortalize it?

I've had this pillow a few years now, and apparently it's time to get rid of it. Can you please write a function or program, that I can bring with me and use to recreate this pillow whenever I want to reminisce a bit.

It must work with no input arguments.

The output should look exactly like this (trailing newlines and spaces are OK).

```<code>/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
</code>```

This is code golf, so the shortest code in bytes win!

Leaderboard

var QUESTION_ID=98701,OVERRIDE_USER=31516;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+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+)(?=[^\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

```

Body:
Vim, <s> 44 </s> 27 bytes

EDIT Lot of bytes won thanks to @DrMcMoylex:

5i\<esc>5a/<esc>0y$5PY4P5x$pY3PyGPP

Original answer:

I'm not sure that really fits the rules of this site but I thought that was fun to try it:

i\<esc>59.:s;\v(.{5})\1;\1/////;g<CR>Y4P5x$pY3PyGPP

Which can be decomposed like this:

i\<esc>                       Insert a \
59.                           Repeat 59 time the insertion
:s;\v(.{5})\1;\1/////;g<CR>   Match 5 characters followed by the same 5 characters
                              And replace them by these 5 characters followed by 5 /
Y4P                           Copy the line and repeat it 4 times
5x$p                          On the current line delete 5 characters and put them
                              at the end of the line
Y3P                           Copy the line and repeat it 3 times
yG                            Copy all the lines
PP                            Repeat them 2 times


答:
MATLAB, <s>58</s> 44 bytes

Thanks to @Stewie Griffin for saving a bunch of bytes ;)

```<code>[repmat(kron(['/\';'\/'],ones(4,5)),3,6),'']
</code>```

Old version:<s>

```<code>p=@()char(47+45*kron(ones(3,6),kron([0 1;1 0],ones(4,5))))
</code>```

</s>

Title: This is my pillow

Body:
MATLAB, <s>58</s> 44 bytes

Thanks to @Stewie Griffin for saving a bunch of bytes ;)

[repmat(kron(['/\';'\/'],ones(4,5)),3,6),'']

Old version:<s>

p=@()char(47+45*kron(ones(3,6),kron([0 1;1 0],ones(4,5))))

</s>


问:
Palindrome polyglot
Your task is to write a program that runs in two different languages, and does the following:

In one language, it palindromizes a given string.

Take the string. abcde

Reverse the string. edcba

Remove the first character. dcba

Glue it onto the original string. abcdedcba

In another language, it depalindromizes a given string.

Take a string palidromized by the above method. abcdedcba

Get the characters from the start to the middle. abcde

Remember, this is code-golf, so the code with the fewest characters (not bytes) wins.

Leaderboards

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

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

```<code># Language 1/Language 2, N bytes
</code>```

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

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

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

```<code># Perl/C, 43 + 2 (-p flag) = 45 bytes
</code>```

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

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

var QUESTION_ID=98776,OVERRIDE_USER=12537;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+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+)(?=[^\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

```

答:
JavaScript ES6 / JavaScript ES3, 143 bytes

function(x){'use strict';function a(){return x+x.split('').reverse().slice(1).join('')}{function a(){return x.slice(0,-x.length/2)}}return a()}
```

Palindromizes in JavaScript ES6, depalindromizes in JavaScript ES3. Non competing, it's just a try to make a polyglot for two versions of the same language.

In ES3 functions are allowed in blocks, but as blocks don't define scopes the new function just replaces the first function. In ES5 strict mode it fails because it don't allow functions to be defined in blocks. In ES6 it's allowed and, because blocks now define scopes, the first function isn't replaced.

Tested in Internet Explorer 5 (emulated) for ES3 and Node.JS and Firefox for ES6.

Title: Palindrome polyglot

Body:
JavaScript ES6 / JavaScript ES3, 143 bytes

function(x){'use strict';function a(){return x+x.split('').reverse().slice(1).join('')}{function a(){return x.slice(0,-x.length/2)}}return a()}

Palindromizes in JavaScript ES6, depalindromizes in JavaScript ES3. Non competing, it's just a try to make a polyglot for two versions of the same language.

In ES3 functions are allowed in blocks, but as blocks don't define scopes the new function just replaces the first function. In ES5 strict mode it fails because it don't allow functions to be defined in blocks. In ES6 it's allowed and, because blocks now define scopes, the first function isn't replaced.

Tested in Internet Explorer 5 (emulated) for ES3 and Node.JS and Firefox for ES6.


问:
Fibonacci reversed!

Introduction

We all know and love our Fibonacci sequence and have seen a myriad of challenge on it here already. However, we're still lacking a very simple case which this answer is going to provide: Reversed fibonacci! So given F_n your job is to find n.

Specification

Input

Your input will be a non-negative integer, which is guaranteed to be part of the fibonacci sequence.

Output

The output must be a non-negative integer as well.

What to do?

The introduction already said: Given a fibonacci number, output its index. Fiboancci number hereby is defined as F(0)=0, F(1)=1, F(n)=F(n-1)+F(n-2) and you're given F(n) and must return n.

Potential Corner Cases

0 is a valid in- and output.

If given "1" as input you may either output "1" or "2", as you prefer.

You may always assume that your input actually is a fibonacci number.

You may assume that the input is representable as a 32-bit signed integer.

Who wins?

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

Standard rules apply of course.

Test-cases

```<code>0 -> 0
2 -> 3
3 -> 4
5 -> 5
8 -> 6
13 -> 7
1836311903 -> 46
</code>```

答:
C#, 130 Bytes

Golfed:

```<code>int F(int n){var a=new int[4];a[1]=1;int i=0;while(a[3]<n){a[3]=a.ToList().GetRange(1,2).Sum();a[1]=a[2];a[2]=a[3];i++;}return i;}
</code>```

Ungolfed:

```<code>public int F(int n)
{
  var a = new int[4];

  a[1] = 1;

  int i = 0;

  while (a[3] < n)
  {
    a[3] = a.ToList().GetRange(1, 2).Sum();

    a[1] = a[2];
    a[2] = a[3];

    i++;
  }

  return i;
}
</code>```

Test:

```<code>var fibonacciReversed = new FibonacciReversed();

var fr = fibonacciReversed.F(0);
Console.WriteLine(fr);
0

fr = fibonacciReversed.F(2);
Console.WriteLine(fr);
3

fr = fibonacciReversed.F(3);
Console.WriteLine(fr);
4

fr = fibonacciReversed.F(5);
Console.WriteLine(fr);
5

fr = fibonacciReversed.F(8);
Console.WriteLine(fr);
6

fr = fibonacciReversed.F(13);
Console.WriteLine(fr);
7

fr = fibonacciReversed.F(1836311903);
Console.WriteLine(fr);
46
</code>```

Title: Fibonacci reversed!

Body:
C#, 130 Bytes

Golfed:

int F(int n){var a=new int[4];a[1]=1;int i=0;while(a[3]<n){a[3]=a.ToList().GetRange(1,2).Sum();a[1]=a[2];a[2]=a[3];i++;}return i;}

Ungolfed:

public int F(int n)
{
  var a = new int[4];

  a[1] = 1;

  int i = 0;

  while (a[3] < n)
  {
    a[3] = a.ToList().GetRange(1, 2).Sum();

    a[1] = a[2];
    a[2] = a[3];

    i++;
  }

  return i;
}

Test:

var fibonacciReversed = new FibonacciReversed();

var fr = fibonacciReversed.F(0);
Console.WriteLine(fr);
0

fr = fibonacciReversed.F(2);
Console.WriteLine(fr);
3

fr = fibonacciReversed.F(3);
Console.WriteLine(fr);
4

fr = fibonacciReversed.F(5);
Console.WriteLine(fr);
5

fr = fibonacciReversed.F(8);
Console.WriteLine(fr);
6

fr = fibonacciReversed.F(13);
Console.WriteLine(fr);
7

fr = fibonacciReversed.F(1836311903);
Console.WriteLine(fr);
46


问:
Fizz Buzz for Turtles

Problem Description

Imagine you're a turtle on a grid.  You're given two numbers f and b, and you're facing east. You perform a march across the grid, counting each of the cells you encounter, according to the following rules:

By default, you write the count to the cell you're in, then walk forward.

If the count is divisible by f, you write F to the cell you're in, then turn right, then walk forward.

If the count is divisible by b, you write B to the cell you're in, then turn left, then walk forward.

If the count is divisible by both f and b, you write FB to the cell you're in, then walk forward.

If you reach a square you've already been to, you stop.

For example, following these rules using f = 3 and b = 5 will generate a pattern like this:

```<code>    F 28 29 FB  1  2  F
   26                 4
 F  B                 B  F
23                       7
22                       8
 F  B                 B  F
   19                11
    F 17 16 FB 14 13  F
</code>```

The challenge

Write a program or function that accepts two numbers as input, corresponding to f and b, and produces as output the pattern for these numbers given by the rules above.

Formatting requirements:

Each cell is two characters wide

Cell contents are right aligned within these two characters

Cells on the same row are delimited by a space

The first column of cells must contain a non-empty cell

All rows must contain non-empty cells

Trailing whitespace is not required, but allowed

However, the total width of each row must not exceed 3 times the number of non-empty columns

Your code must work for provided test cases.

Standard loopholes are disallowed.

This is code golf; shortest answer in bytes wins.

Test cases

(f=3, b=5 case repeated here as a courtesy convenience).

```<code>f=3, b=5 ->
    F 28 29 FB  1  2  F
   26                 4
 F  B                 B  F
23                       7
22                       8
 F  B                 B  F
   19                11
    F 17 16 FB 14 13  F

f=4, b=10 ->
 F 25 26 27  F
23          29
22        1  2  3  F
21                 5
FB                 6
19                 7
18           B  9  F
17          11
 F 15 14 13  F

f=3, b=11 ->
 F 16 17  F
14       19
13     1  2  F
 F  B        4
   10        5
    F  8  7  F

f=5, b=9 ->
    F 41 42 43 44  1  2  3  4  F
   39                          6
   38                          7
   37                          8
 F  B                          B  F
34                               11
33                               12
32                               13
31                               14
 F 29 28  B              B 17 16  F
         26             19
          F 24 23 22 21  F

f=5, b=13 ->
    F 31 32 33 34  F
   29             36
   28        1  2  3  4  F
   27                    6
 F  B                    7
24                       8
23                       9
22              B 12 11  F
21             14
 F 19 18 17 16  F
</code>```

答:
Excel VBA, <s>347</s> 421 bytes

New version, to deal with the whitespace-requirements. Not having this in my first version was an oversight n my part, but this takes its toll in the bytecount... It now cuts and pastes the used range to cell A1.

Sub t(f, b)
x=70:y=70:Do:s=s+ 1
If Cells(y,x).Value<>"" Then
ActiveSheet.UsedRange.Select:Selection.Cut:Range("A1").Select:ActiveSheet.Paste:Exit Sub
End If
If s Mod f=0 Then Cells(y,x).Value="F":q=q+1
If s Mod b=0 Then Cells(y,x).Value=Cells(y,x).Value & "B":q=q+3
If Cells(y,x).Value="" Then Cells(y,x).Value=s
Select Case q Mod 4
Case 0:x=x+1
Case 1:y=y+1
Case 2:x=x-1
Case 3:y=y-1
End Select:Loop:End Sub
```
<hr />
<p>Here's the old version that did not move the end result to <code>A1</code></p>
<pre class="lang-vb prettyprint-override"><code>Sub t(f,b)
x=70:y=70:Do:s=s+1:if Cells(y,x).Value<>"" then exit sub
If s Mod f=0 Then
Cells(y,x).Value="F":q=q+1
End If
If s Mod b=0 Then
Cells(y,x).Value=Cells(y,x).Value & "B":q=q+3
End If
If Cells(y,x).Value="" Then Cells(y,x).Value=s
Select Case q mod 4
Case 0:x=x+1
Case 1:y=y+1
Case 2:x=x-1
Case 3:y=y-1
End Select:Loop:End Sub
</code>```

Starts at 70, 70 (or BR70 in Excel) and walks around it. Function is called with the f and b as parameters: Call t(4, 16)

@Neil just saved me a bunch of bytes, thanks!

Title: Fizz Buzz for Turtles

Body:
Excel VBA, <s>347</s> 421 bytes

New version, to deal with the whitespace-requirements. Not having this in my first version was an oversight n my part, but this takes its toll in the bytecount... It now cuts and pastes the used range to cell A1.

Sub t(f, b)
x=70:y=70:Do:s=s+ 1
If Cells(y,x).Value<>"" Then
ActiveSheet.UsedRange.Select:Selection.Cut:Range("A1").Select:ActiveSheet.Paste:Exit Sub
End If
If s Mod f=0 Then Cells(y,x).Value="F":q=q+1
If s Mod b=0 Then Cells(y,x).Value=Cells(y,x).Value & "B":q=q+3
If Cells(y,x).Value="" Then Cells(y,x).Value=s
Select Case q Mod 4
Case 0:x=x+1
Case 1:y=y+1
Case 2:x=x-1
Case 3:y=y-1
End Select:Loop:End Sub

Here's the old version that did not move the end result to A1

Sub t(f,b)
x=70:y=70:Do:s=s+1:if Cells(y,x).Value<>"" then exit sub
If s Mod f=0 Then
Cells(y,x).Value="F":q=q+1
End If
If s Mod b=0 Then
Cells(y,x).Value=Cells(y,x).Value & "B":q=q+3
End If
If Cells(y,x).Value="" Then Cells(y,x).Value=s
Select Case q mod 4
Case 0:x=x+1
Case 1:y=y+1
Case 2:x=x-1
Case 3:y=y-1
End Select:Loop:End Sub

Starts at 70, 70 (or BR70 in Excel) and walks around it. Function is called with the f and b as parameters: Call t(4, 16)

@Neil just saved me a bunch of bytes, thanks!


答:
Ruby <s>37</s> 32 bytes

```<code>->n{n.size-1-(n.rindex(!0)||-1)}
</code>```

Creates an anonymous function that finds the right-most instance of a false value, and counts the size of the subarray starting at that value.

It uses !0 as false, as 0 are truthy values in Ruby. rindex finds the last index of a value in an array.

Usage:

```<code>boolean_list = [true, false, false, true]
->n{n.size-1-(n.rindex(!0)||-1)}[boolean_list]
</code>```

Returns 1

If I was allowed to be passed a string of 0s and 1s as command line parameters (which is not how ruby represents lists of booleans), I could get it down to 24:

```<code>$*[0]=~/(1*)\z/;p$1.size
</code>```

This uses regular expressions and prints the length of the string returned by the regular expression /(1*)\z/, where \z is the end of the string. $*[0] is the first argument passed and is a string of 0s and 1s.

Usage:

```<code>trailing_truths.rb 011101
</code>```

Returns 1.

Title: Count trailing truths

Body:
Inspired by, and in memory of, my dear friend and colleague,

Dan Baronet, 1956 – 2016. R.I.P.

He found the shortest possible APL solution to this task:

Task

Given a Boolean list, count the number of trailing truth values.

Example cases

{} → 0

{0} → 0

{1} → 1

{0, 1, 1, 0, 0} → 0

{1, 1, 1, 0, 1} → 1

{1, 1, 0, 1, 1} → 2

{0, 0, 1, 1, 1} → 3

{1, 1, 1, 1, 1, 1} → 6

Body:
Ruby <s>37</s> 32 bytes

->n{n.size-1-(n.rindex(!0)||-1)}

Creates an anonymous function that finds the right-most instance of a false value, and counts the size of the subarray starting at that value.

It uses !0 as false, as 0 are truthy values in Ruby. rindex finds the last index of a value in an array.

Usage:

boolean_list = [true, false, false, true]
->n{n.size-1-(n.rindex(!0)||-1)}[boolean_list]

Returns 1

If I was allowed to be passed a string of 0s and 1s as command line parameters (which is not how ruby represents lists of booleans), I could get it down to 24:

$*[0]=~/(1*)\z/;p$1.size

This uses regular expressions and prints the length of the string returned by the regular expression /(1*)\z/, where \z is the end of the string. $*[0] is the first argument passed and is a string of 0s and 1s.

Usage:

trailing_truths.rb 011101

Returns 1.


答:
C#6, <s>103</s> 72 bytes

```<code>using System.Linq;
int a(bool[] l)=>l.Reverse().TakeWhile(x=>x).Count();
</code>```

Using non-generic list beats generic list by 1 byte lol

-31 bytes thanks to Scott

Title: Count trailing truths

Body:
C#6, <s>103</s> 72 bytes

using System.Linq;
int a(bool[] l)=>l.Reverse().TakeWhile(x=>x).Count();

Using non-generic list beats generic list by 1 byte lol

-31 bytes thanks to Scott


问:
Primenary Strings

A Primenary (binary-prime) string is one which, when written as a binary grid, every row and column has a prime total.

That's quite a vague explanation, so let's break it down with a worked example...

For this example we'll use the string bunny:

First, find the ASCII code point of each character and its binary representation:

```<code>Char | ASCII | Binary

b      98      1100010
u      117     1110101
n      110     1101110
n      110     1101110
y      121     1111001
</code>```

Take these binary values, from top to bottom, and arrange them into grid (adding leading zeros if necessary):

```<code>1 1 0 0 0 1 0
1 1 1 0 1 0 1
1 1 0 1 1 1 0
1 1 0 1 1 1 0
1 1 1 1 0 0 1
</code>```

Then, count the number of 1s in each row and column:

```<code>1 1 0 0 0 1 0   > 3
1 1 1 0 1 0 1   > 5
1 1 0 1 1 1 0   > 5
1 1 0 1 1 1 0   > 5
1 1 1 1 0 0 1   > 5

v v v v v v v

5 5 2 3 3 3 2
</code>```

If, and only if, every single total is prime (such as here) then the string is a valid binary-prime.

The Challenge

Your task is to create a function or program which, when given a string, returns/outputs truthy if the string is primenary, and falsy otherwise.

Rules/Details

You may assume that the string's characters will always be in the ASCII range 33-126 (inclusive).

The string will not be empty.

A primenary string does not have to have a prime length - for example, W1n* is valid, despite having 4 characters.

This is code-golf, so the shortest answer (in bytes) wins - but all submissions are welcome.

Standard loopholes are banned.

Test Cases

```<code>'husband'     -> True
'HOTJava'     -> True
'COmPaTIBILE' -> True
'AuT0HACk'    -> True

'PPCW'        -> False
'code-golf'   -> False
'C++'         -> False
'/kD'         -> False

'HI'          -> False
'A'           -> False
</code>```

There is also a working, but incredibly verbose Python example on repl.it that you can test your solution against.

Title: Primenary Strings

Body:
PHP, 173 bytes

for($r=1;$b=substr_count($t[$i]=sprintf('%07b',ord($argv[1][$i++])),1);)$r&=$b==2|$b%2&$b>2;for(;$k++<7;){for($b=$j=0;$t[++$j];$b+=$t[$j][$k-1]);$r&=$b==2|$b%2&$b>2;}echo$r;

Test it online


答:
PHP, <s>58</s> <s>54</s> 53 bytes

```<code>function f($a){while(array_pop($a))$i++;return+$i;}
</code>```

Since PHP has no list I use an array instead

-4 bytes thanks to  user59178

All tests

Title: Count trailing truths

Body:
PHP, <s>58</s> <s>54</s> 53 bytes

function f($a){while(array_pop($a))$i++;return+$i;}

Since PHP has no list I use an array instead

-4 bytes thanks to  user59178

All tests


Title: This is my pillow

Body:
GolfSharp, 59 bytes

r(0,1440).s(n=>n%10<5^n%480<240?"\\":"/").j().S(60).j("\n")


问:
Print a letter Fibonacci
Given N (2 <= N), print N lines of the letter Fibonacci series like this (i.e. N = 5)
First, start with a and b:

```<code>a
b
</code>```

Next, add the two lines.

```<code>a
b
ab
</code>```

Keep adding the last two lines.

```<code>a
b
ab
bab
</code>```

Keep going...

```<code>a
b
ab
bab
abbab
</code>```

And we're done.

Remember, this is code-golf, so the code with the fewest bytes wins.

答:
C#, 142 Bytes

Edit: only had it printing the last line out... V2:

Golfed:

```<code>string L(int n){var r=new List<string>(){"a","b"};int i=3;while(i<=n){r.Add(string.Concat(r[i-3],r[i-2]));i++;}return string.Join("\r\n", r);}
</code>```

Ungolfed:

```<code>public string L(int n)
{
  var r = new List<string>() { "a", "b" };

  int i = 3;

  while (i <= n)
  {
    r.Add(string.Concat(r[i-3], r[i-2]));
    i++;
  }

  return string.Join("\r\n", r);
}
</code>```

Test:

```<code>var printALetterFibonacci = new PrintALetterFibonacci();
Console.WriteLine(printALetterFibonacci.L(5));

a
b
ab
bab
abbab

var printALetterFibonacci = new PrintALetterFibonacci();
Console.WriteLine(printALetterFibonacci.L(7));

a
b
ab
bab
abbab
bababbab
abbabbababbab
</code>```

Title: Print a letter Fibonacci

Body:
C#, 142 Bytes

Edit: only had it printing the last line out... V2:

Golfed:

string L(int n){var r=new List<string>(){"a","b"};int i=3;while(i<=n){r.Add(string.Concat(r[i-3],r[i-2]));i++;}return string.Join("\r\n", r);}

Ungolfed:

public string L(int n)
{
  var r = new List<string>() { "a", "b" };

  int i = 3;

  while (i <= n)
  {
    r.Add(string.Concat(r[i-3], r[i-2]));
    i++;
  }

  return string.Join("\r\n", r);
}

Test:

var printALetterFibonacci = new PrintALetterFibonacci();
Console.WriteLine(printALetterFibonacci.L(5));

a
b
ab
bab
abbab

var printALetterFibonacci = new PrintALetterFibonacci();
Console.WriteLine(printALetterFibonacci.L(7));

a
b
ab
bab
abbab
bababbab
abbabbababbab


问:
Print some JSON
This challenge is straightforward, but hopefully, there are plenty of avenues you can approach it:

You need to print/return a valid JSON object of at least 15 characters, not counting unessential whitespace.  Your program should work without any input.

In the interest of clarity, a JSON object starts and ends with curly braces {}, and contains zero or more key:value pairs separated by commas.  The full JSON specification can be found at json.org, and the output of your code must pass this validator.

Therefore, any of the following would not be valid:

```<code>4                               //Too short, not an object
"really, really long string"    //A string, not an object
["an","array","of","values"]    //An array is not a JSON object
{"this":4      }                //You can't count unessential whitespace
{"1":1,"2":3}                   //Too short
{"a really long string"}        //Not valid JSON, it needs a value
{'single-quoted':3}             //JSON requires double-quotes for strings
</code>```

However, the following would be valid:

```<code>{"1":1,"2":2,"3":3,"4":4}       //Long enough
{"whitespace      ":4}          //This whitespace isn't unessential
</code>```

Non-programming languages are allowed on this challenge.  You may return a string from a function, or print it out.  This is a code-golf, so answer it with as little code as possible!

答:
Rust, 21 bytes

||"{\"a\":0.1234567}"
```

<p>String substitution would be too verbose, but at least there's always terse lambdas with implicit returns.</p>

<p>With "test code":</p>

<pre class="lang-rs prettyprint-override"><code>fn main(){
    let f=||"{\"a\":0.1234567}";
    println!("{}", f());
}
</code>```

Title: Print some JSON

Body:
Rust, 21 bytes

||"{\"a\":0.1234567}"

String substitution would be too verbose, but at least there's always terse lambdas with implicit returns.

With "test code":

fn main(){
    let f=||"{\"a\":0.1234567}";
    println!("{}", f());
}


问:
How many significant figures?
Given a number as input, determine how many significant figures it has. This number will should be taken as a string because you have to do some special formatting. You'll see what I mean soon (I think).

A digit is a sig-fig if at least one of the following apply:

Non-zero digits are always significant.

Any zeros between two significant digits are significant.

final zero or trailing zeros in the decimal portion only are significant.

all digits are significant if nothing follows the decimal place.

when there are only zeroes, all but the last zero are considered leading zeroes

Input

A string or string array of the number. It might have a decimal point at the end without a digit after it. It might not have a decimal point at all.

Output

How many sig-figs there are.

Examples

```<code>1.240 -> 4
0. -> 1
83900 -> 3
83900.0 -> 6
0.025 -> 2
0.0250 -> 3
2.5 -> 2
970. -> 3
0.00 -> 1
</code>```

答:
C#6, 163 bytes

```<code>using System.Linq;
int a(string s)=>System.Math.Max(s.Contains('.')?(s[0]<'1'?s.SkipWhile(x=>x<'1').Count():s.Length-1):s.Reverse().SkipWhile(x=>x<'1').Count(),1);
</code>```

Ungolfed

```<code>int a(string s)=>
    System.Math.Max(
        s.Contains('.')                                // Has decimal place?
            ?(                                         // Has decimal place!
                s[0]<'1'                               // Start with '0' or '.'?
                    ?s.SkipWhile(x=>x<'1').Count()     // Yes: Skip leading '0' and '.', then count rest... But gives 0 for "0." and "0.00"
                    :s.Length-1)                       // No: Count length without decimal place
            :s.Reverse().SkipWhile(x=>x<'1').Count()   // No decimal place: Skip trailing '0' and count rest
    ,1);                                               // For "0." and "0.00"
</code>```

Title: How many significant figures?

Body:
C#6, 163 bytes

using System.Linq;
int a(string s)=>System.Math.Max(s.Contains('.')?(s[0]<'1'?s.SkipWhile(x=>x<'1').Count():s.Length-1):s.Reverse().SkipWhile(x=>x<'1').Count(),1);

Ungolfed

int a(string s)=>
    System.Math.Max(
        s.Contains('.')                                // Has decimal place?
            ?(                                         // Has decimal place!
                s[0]<'1'                               // Start with '0' or '.'?
                    ?s.SkipWhile(x=>x<'1').Count()     // Yes: Skip leading '0' and '.', then count rest... But gives 0 for "0." and "0.00"
                    :s.Length-1)                       // No: Count length without decimal place
            :s.Reverse().SkipWhile(x=>x<'1').Count()   // No decimal place: Skip trailing '0' and count rest
    ,1);                                               // For "0." and "0.00"


答:
C++17, <s>82</s> 66 bytes

int f(){return 0;}int f(int H,auto... L){return(H*...*L)+f(L...);}
```
<p>Uses the C++17 template parameter fold expression and essentially the same idea as Dennis. Saving 16 bytes by using Generic Variadic Lambda.</p>
<p>Explanation:</p>
<pre class="lang-c++ prettyprint-override"><code>int f(){return 0;} //base case for empty list

int f(int H, auto... L) { //first element, variadic arguments
    return (H*...*L)      //a_0*a_1*a_2*...
         + f(L...);       //+ f(a_1,a_2,...)
}
</code>```

Usage:

f(1,1,0,1,1,0,1,1,1,1,1) -> 5
f() -> 0
f(1,0,1,0) -> 0
```
<h2>Non competing</h2>
<p>Albeit longer, this also works with template constants:</p>
<pre class="lang-c++ prettyprint-override"><code>template <int...L> int C=0;
template <int H, int...L> int C<H,L...> = (H*...*L)+C<L...>;
</code>```

Usage:

std::cout << C<1,0,1,1>  << std::endl;
std::cout << C<1,0,1,0,1>  << std::endl;
std::cout << C<1,1,1,0,1,0,1,1>  << std::endl;
std::cout << C<1,1,1,0,1,0,1,1,1,1,1,1>  << std::endl;
std::cout << C<> << std::endl;
```

Title: Count trailing truths

Body:
C++17, <s>82</s> 66 bytes

int f(){return 0;}int f(int H,auto... L){return(H*...*L)+f(L...);}

Uses the C++17 template parameter fold expression and essentially the same idea as Dennis. Saving 16 bytes by using Generic Variadic Lambda.

Explanation:

int f(){return 0;} //base case for empty list

int f(int H, auto... L) { //first element, variadic arguments
    return (H*...*L)      //a_0*a_1*a_2*...
         + f(L...);       //+ f(a_1,a_2,...)
}

Usage:

f(1,1,0,1,1,0,1,1,1,1,1) -> 5
f() -> 0
f(1,0,1,0) -> 0

Non competing

Albeit longer, this also works with template constants:

template <int...L> int C=0;
template <int H, int...L> int C<H,L...> = (H*...*L)+C<L...>;

Usage:

std::cout << C<1,0,1,1>  << std::endl;
std::cout << C<1,0,1,0,1>  << std::endl;
std::cout << C<1,1,1,0,1,0,1,1>  << std::endl;
std::cout << C<1,1,1,0,1,0,1,1,1,1,1,1>  << std::endl;
std::cout << C<> << std::endl;


Title: This is my pillow

Body:
Python 2.7 66 -> 56 -> 55 bytes

a="/"*5+"\\"*5;b=a[::-1];c=6*a+"\n";d=6*b+"\n";e=4*c+4*d;print e*3

new to code golfing

a="/"*5+"\\"*5;print(4*(6*a+"\n")+4*(6*a[::-1]+"\n"))*3

Thanks Stewie Griffin

Forgot a silly whitespace ;)


问:
Solve the Laplace equation

Introduction to Numerical Mathematics

This is the "Hello, World!" of PDEs (Partial Differential Equations). The Laplace or Diffusion Equation appears often in Physics, for example Heat Equation, Deforming, Fluid Dynamics, etc... As real life is 3D but we want to say "Hello, World!" and not sing "99 bottles of beer,..." this task is given in 1D. You may interpret this as a rubber robe tied to a wall on both ends with some force applied to it.

On a \$[0,1]\$ domain, find a function \$u\$ for given source function \$f\$ and boundary values \$u_L\$ and \$u_R\$ such that:

\$-u'' = f\$

\$u(0) = u_L\$

\$u(1) = u_R\$

\$u''\$ denotes the second derivative of \$u\$

This can be solved purely theoretically but your task is it to solve it numerically on a discretized domain \$x\$ for \$N\$ points:

\$x = \{\frac i {N-1} : 0 \le i \le N-1\}\$ or 1-based: \$\{\frac {i-1} {N-1} : 0 \le i \le N-1\}\$

\$h = \frac 1 {N-1}\$ is the spacing

Input

\$f\$ as a function, expression or string

\$u_L\$, \$u_R\$ as floating point values

\$N \ge 2\$ as an integer

Output

Array, List, some sort of separated string of \$u\$ such that \$u_i = u(x_i)\$

Examples

Example 1

Input: \$f = -2\$, \$u_L = u_R = 0\$, \$N = 10\$ (Don't take \$f=-2\$ wrong, it is not a value but a constant function that returns \$-2\$ for all \$x\$. It is like a constant gravity force on our rope.)

Output: [-0.0, -0.09876543209876543, -0.1728395061728395, -0.22222222222222224, -0.24691358024691357, -0.24691358024691357, -0.22222222222222224, -0.1728395061728395, -0.09876543209876547, -0.0]

There exists an easy exact solution: \$u = -x(1-x)\$

Example 2

Input: \$f = 10x\$, \$u_L = 0\$, \$u_R = 1\$, \$N = 15\$ (Here there is a lot of upwind on the right side)

Output: [ 0., 0.1898688, 0.37609329, 0.55502915, 0.72303207, 0.87645773, 1.01166181, 1.125, 1.21282799, 1.27150146, 1.29737609, 1.28680758, 1.2361516, 1.14176385, 1.]

The exact solution for this states: \$u = \frac 1 3(8x-5x^3)\$

Example 3

Input: \$f = \sin(2\pi x)\$, \$u_L = u_R = 1\$, \$N = 20\$ (Someone broke gravity or there is a sort of up- and downwind)

Output: [ 1., 1.0083001, 1.01570075, 1.02139999, 1.0247802, 1.0254751, 1.02340937, 1.01880687, 1.01216636, 1.00420743, 0.99579257, 0.98783364, 0.98119313, 0.97659063, 0.9745249, 0.9752198, 0.97860001, 0.98429925, 0.9916999, 1.]

Here the exact solution is \$u = \frac {\sin(2πx)} {4π^2}+1\$

Example 4

Input: \$f = \exp(x^2)\$, \$u_L = u_R = 0\$, \$N=30\$

Output:
[ 0.          0.02021032  0.03923016  0.05705528  0.07367854  0.0890899 0.10327633  0.11622169  0.12790665  0.13830853  0.14740113  0.15515453 0.16153488  0.1665041   0.17001962  0.172034    0.17249459  0.17134303 0.16851482  0.1639387   0.15753606  0.1492202   0.13889553  0.12645668 0.11178744  0.09475961  0.07523169  0.05304738  0.02803389  0.        ]

Note the slight asymmetry

FDM

One possible method to solve this is the Finite Difference Method:

Rewrite \$-u_i'' = f_i\$ as \$\frac {-u_{i-1} + 2u_i - u_{i+1}} {h^2} = f_i\$, which equals \$-u_{i-1} + 2u_i - u_{i+1} = h^2 f_i\$

Setup the equations:

$$
u_0 = u_L \\
\frac {-u_0 + 2u_1 - u_2} {h^2} = f_1 \\
\frac {-u_1 + 2u_2 - u_3} {h^2} = f_2 \\
\dots = \dots \\
\frac {-u_{n-3} + 2u_{n-2} - u_{n-1}} {h^2} = f_{n-2} \\
u_{n-1} = u_R
$$

Which are equal to a matrix-vector equation:

$$
\begin{pmatrix}
 1 & & & & & & \\
-1 & 2 & -1 & & & & \\
 & -1 & 2& -1& & & \\
 & & \ddots & \ddots & \ddots & & \\
 & & & -1 & 2 & -1 & \\
 & & & & -1 & 2 & -1 \\
 & & & & & & 1
\end{pmatrix}
\begin{pmatrix}
u_0 \\ u_1 \\ u_2 \\ \vdots \\ u_{n-3} \\ u_{n-2} \\ u_{n-1}
\end{pmatrix}
=
\begin{pmatrix}
u_L \\ h^2 f_1 \\ h^2 f_2 \\ \vdots \\ h^2 f_{n-3} \\ h^2 f_{n-2} \\ u_R
\end{pmatrix}
$$

Solve this equation and output the \$u_i\$

One implementation of this for demonstration in Python:

```<code>import matplotlib.pyplot as plt
import numpy as np
def laplace(f, uL, uR, N):
 h = 1./(N-1)
 x = [i*h for i in range(N)]

 A = np.zeros((N,N))
 b = np.zeros((N,))

 A[0,0] = 1
 b[0] = uL

 for i in range(1,N-1):
  A[i,i-1] = -1
  A[i,i]   =  2
  A[i,i+1] = -1
  b[i]     = h**2*f(x[i])

 A[N-1,N-1] = 1
 b[N-1]     = uR

 u = np.linalg.solve(A,b)

 plt.plot(x,u,'*-')
 plt.show()

 return u

print laplace(lambda x:-2, 0, 0, 10)
print laplace(lambda x:10*x, 0, 1, 15)
print laplace(lambda x:np.sin(2*np.pi*x), 1, 1, 20)
</code>```

Alternative implementation without Matrix Algebra (using the Jacobi method)

```<code>def laplace(f, uL, uR, N):
 h=1./(N-1)
 b=[f(i*h)*h*h for i in range(N)]
 b[0],b[-1]=uL,uR
 u = [0]*N

 def residual():
  return np.sqrt(sum(r*r for r in[b[i] + u[i-1] - 2*u[i] + u[i+1] for i in range(1,N-1)]))

 def jacobi():
  return [uL] + [0.5*(b[i] + u[i-1] + u[i+1]) for i in range(1,N-1)] + [uR]

 while residual() > 1e-6:
  u = jacobi()

 return u
</code>```

You may however use any other method to solve the Laplace equation. If you use an iterative method, you should iterate until the residual \$|b-Au| < 10^{-6}\$, with \$b\$ being the right hand side vector \$u_L,f_1 h^2,f_2 h^2, \dots\$

Notes

Depending on your solution method you may not solve the examples exactly to the given solutions. At least for \$N \to \infty\$ the error should approach zero.

Standard loopholes are disallowed, built-ins for PDEs are allowed.

Bonus

A bonus of -30% for displaying the solution, either graphical or ASCII-art.

Winning

This is codegolf, so shortest code in bytes wins!

答:
Haskell, <s>195</s> 168 bytes

```<code>import Numeric.LinearAlgebra
p f s e n|m<-[0..]!!n=((n><n)(([1,0]:([3..n]>>[[-1,2,-1]])++[[0,1]])>>=(++(0<$[3..n]))))<\>(col$s:map((/(m-1)^2).f.(/(m-1)))[1..m-2]++[e])
</code>```

The readability took quite a hit. Ungolfed:

```<code>laplace f start end _N = linearSolveLS _M y
  where
  n = fromIntegral _N
  _M = (_N><_N) --construct n×n matrix from list
        ( ( [1,0]           --make a list of [1,0]
          : ([3.._N]>>[[-1,2,-1]]) --         (n-2)×[-1,2,-1]
          ++ [[0,1]])       --               [0,1]
        >>= (++(0<$[3.._N])) --append (n-2) zeroes and concat
        )                   --(m><n) discards the extra zeroes at the end
  h  = 1/(n-1) :: Double
  y  = asColumn . fromList $ start : map ((*h^2).f.(*h)) [1..n-2] ++ [end]
</code>```

TODO: Printing in <s>83</s> 71 bytes.

Lemme see:

```<code>import Graphics.Rendering.Chart.Easy
import Graphics.Rendering.Chart.Backend.Cairo
</code>```

D'oh!

Title: Solve the Laplace equation

Body:
Haskell, <s>195</s> 168 bytes

import Numeric.LinearAlgebra
p f s e n|m<-[0..]!!n=((n><n)(([1,0]:([3..n]>>[[-1,2,-1]])++[[0,1]])>>=(++(0<$[3..n]))))<\>(col$s:map((/(m-1)^2).f.(/(m-1)))[1..m-2]++[e])

The readability took quite a hit. Ungolfed:

laplace f start end _N = linearSolveLS _M y
  where
  n = fromIntegral _N
  _M = (_N><_N) --construct n×n matrix from list
        ( ( [1,0]           --make a list of [1,0]
          : ([3.._N]>>[[-1,2,-1]]) --         (n-2)×[-1,2,-1]
          ++ [[0,1]])       --               [0,1]
        >>= (++(0<$[3.._N])) --append (n-2) zeroes and concat
        )                   --(m><n) discards the extra zeroes at the end
  h  = 1/(n-1) :: Double
  y  = asColumn . fromList $ start : map ((*h^2).f.(*h)) [1..n-2] ++ [end]

TODO: Printing in <s>83</s> 71 bytes.

Lemme see:

import Graphics.Rendering.Chart.Easy
import Graphics.Rendering.Chart.Backend.Cairo

D'oh!


问:
Divide a number by 3 without using *, /, +, -, % operators
Quoting this question on SO (Spoiler alert!):

This question has been asked in an Oracle interview.

How would you divide a number by 3 without using *, /, +, -, %,
  operators?

The number may be signed or unsigned.

The task is solvable, but see if you can write the shortest code.

Rules:

Perform the required integer division (/3)

Do not use the non-text-based operators *, /, +, -, or % (or their equivalents, such as __div__ or add()). This also applies to incrementing and decrementing operators, like i++ or i--. Use of operators for string concatenation and formatting are OK. Using these characters for different operators, such as unary - operator for negative numbers, or * to represent a pointer in C is OK as well.

Input value can be arbitrarily large (whatever your system can handle), both positive and negative

Input can be on STDIN or ARGV or entered any other way

Create the shortest code you can to do the above

答:
Jelly, 5 bytes

```<code>b3Ṗḅ3
</code>```

Try it online!

Explanation:

```<code> b3Ṗḅ3 Main link. Arguments: z
⁸      (implicit) z
  3    3
 b     Convert x to base y
   Ṗ   Trim last element off x
     3 3
    ḅ  Convert x from base y
</code>```

Body:
Jelly, 5 bytes

b3Ṗḅ3

Try it online!

Explanation:

 b3Ṗḅ3 Main link. Arguments: z
⁸      (implicit) z
  3    3
 b     Convert x to base y
   Ṗ   Trim last element off x
     3 3
    ḅ  Convert x from base y


问:
Index of a multidimensional array
Lower level languages, such as C and C++ actually have no concept of multidimensional arrays. (Other than vectors and dynamic arrays) When you create a multidimensional array with

```<code>int foo[5][10];
</code>```

This is actually just syntactic sugar. What C really does is create a single contiguous array of 5 * 10 elements. This

```<code>foo[4][2]
</code>```

is also syntactic sugar. This really refers to the element at

```<code>4 * 10 + 2
</code>```

or, the 42nd element. In general, the index of element [a][b] in array foo[x][y] is at

```<code>a * y + b
</code>```

The same concept applies to 3d arrays. If we have foo[x][y][z] and we access element [a][b][c] we are really accessing element:

```<code>a * y * z + b * z + c
</code>```

This concept applies to n-dimensional arrays. If we have an array with dimensions D1, D2, D3 ... Dn and we access element S1, S2, S3 ... Sn the formula is

```<code>(S1 * D2 * D3 ... * Dn) + (S2 * D3 * D4 ... * Dn) + (S3 * D4 ... * Dn) ... + (Sn-1 * Dn) + Sn
</code>```

The challenge

You must write a program or function that calculates the index of a multidimensional array according to the formula above. Input will be two arrays. The first array is the dimensions, and the second array is the indices. The length of these two arrays will always be equal and at least 1.

You can safely assume that every number in the arrays will be an non-negative integer. You can also assume that you will not get a 0 in the dimension array, although a 0 might be in the indices. You can also assume that indices will not be larger than the dimensions.

Test IO

```<code>Dimensions: [5, 10]
Indices: [4, 2]
Output: 42

Dimensions: [10, 10, 4, 62, 7]
Indices: [1, 2, 3, 4, 5]
Output: 22167

Dimensions: [5, 1, 10]
Indices: [3, 0, 7]
Output: 37

Dimensions: [6, 6, 6, 6, 6, 6, 6, 6, 6, 6]
Indices: [3, 1, 5, 5, 3, 0, 5, 2, 5, 4]
Output: 33570178
</code>```

答:
C++17, <s>133</s> 115 bytes

-18 bytes for using auto...

template<int d,int ...D>struct M{int f(int s){return s;}int f(int s,auto...S){return(s*...*D)+M<D...>().f(S...);}};
```

<p>Ungolfed:</p>

<pre class="lang-c++ prettyprint-override"><code>template <int d,int ...D> //extract first dimension
struct M{
 int f(int s){return s;} //base case for Sn
 int f(int s, auto... S) { //extract first index
  return (s*...*D)+M<D...>().f(S...);
  //S_i * D_(i+1) * D(i+2) * ... + recursive without first dimension and first index
 }
};
</code>```

Usage:

M<5,10>().f(4,2)
M<10,10,4,62,7>().f(1,2,3,4,5)
```

<h2>Alternative, only functions, 116 bytes</h2>

<pre class="lang-c++ prettyprint-override"><code>#define R return
#define A auto
A f(A d){R[](A s){R s;};}A f(A d,A...D){R[=](A s,A...S){R(s*...*D)+f(D...)(S...);};}
</code>```

Ungolfed:

auto f(auto d){
  return [](auto s){
   return s;
  };
}
auto f(auto d, auto...D){
  return [=](auto s, auto...S){
    return (s*...*D)+f(D...)(S...);
  };
}
```

<p>Usage:</p>

<pre class="lang-c++ prettyprint-override"><code>f(5,10)(4,2)
f(10,10,10)(4,3,2)
f(10,10,4,62,7)(1,2,3,4,5)
</code>```

Title: Index of a multidimensional array

Body:
C++17, <s>133</s> 115 bytes

-18 bytes for using auto...

template<int d,int ...D>struct M{int f(int s){return s;}int f(int s,auto...S){return(s*...*D)+M<D...>().f(S...);}};

Ungolfed:

template <int d,int ...D> //extract first dimension
struct M{
 int f(int s){return s;} //base case for Sn
 int f(int s, auto... S) { //extract first index
  return (s*...*D)+M<D...>().f(S...);
  //S_i * D_(i+1) * D(i+2) * ... + recursive without first dimension and first index
 }
};

Usage:

M<5,10>().f(4,2)
M<10,10,4,62,7>().f(1,2,3,4,5)

Alternative, only functions, 116 bytes

#define R return
#define A auto
A f(A d){R[](A s){R s;};}A f(A d,A...D){R[=](A s,A...S){R(s*...*D)+f(D...)(S...);};}

Ungolfed:

auto f(auto d){
  return [](auto s){
   return s;
  };
}
auto f(auto d, auto...D){
  return [=](auto s, auto...S){
    return (s*...*D)+f(D...)(S...);
  };
}

Usage:

f(5,10)(4,2)
f(10,10,10)(4,3,2)
f(10,10,4,62,7)(1,2,3,4,5)


问:
Draw a hollow square of # with given width
I got this challenge from Codingame and am curious about better solutions than mine:

Given a width via standard input draw a hollow square of '#' in given width and length.

Example:

5 results in

```<code>#####
#   #
#   #
#   #
#####
</code>```

I used python to solve this so i am particulary interested in other python code. But please feel free to post your solution in any language you want.

答:
Python, 109 bytes

n=int(input())
for x in range(n):
 r=list(' '*n);r[0]=r[-1]='#'
 if x%(n-1)==0:r='#'*n
 print("".join(r))
```


答:
PHP, 55 bytes

```<code>for(;$i<1440;)echo"/\\"[($i/5^$i/240)&1],"\n"[++$i%60];
</code>```

toggles between forward and backward slash every 5 characters, inverted every 240 characters;

not counting newlines; newlines inserted every 60 characters.

has one trailing newline. Run with -r.

recursive program for 66 bytes:

```<code><?="/\\"[($i/5^$i/240)&1]."\n"[++$i%60];if($i<1440)include"p.php";
</code>```

save to file p.php; call from CLI (or insert ($i?"":"```"). after <?=)

Title: This is my pillow

Body:
...will you help me immortalize it?

I've had this pillow a few years now, and apparently it's time to get rid of it. Can you please write a function or program, that I can bring with me and use to recreate this pillow whenever I want to reminisce a bit.

It must work with no input arguments.

The output should look exactly like this (trailing newlines and spaces are OK).

```<code>/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
</code>```

This is code golf, so the shortest code in bytes win!

Leaderboard

var QUESTION_ID=98701,OVERRIDE_USER=31516;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+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+)(?=[^\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

```

Body:
PHP, 55 bytes

for(;$i<1440;)echo"/\\"[($i/5^$i/240)&1],"\n"[++$i%60];

toggles between forward and backward slash every 5 characters, inverted every 240 characters;

not counting newlines; newlines inserted every 60 characters.

has one trailing newline. Run with -r.

recursive program for 66 bytes:

<?="/\\"[($i/5^$i/240)&1]."\n"[++$i%60];if($i<1440)include"p.php";

save to file p.php; call from CLI (or insert ($i?"":"<pre>"). after <?=)


答:
C, <s>83</s> <s>82</s> <s>80</s> <s>78</s> 77 Bytes

```<code>i,j;f(n){for(i=n;i--;puts(""))for(j=n;j--;putchar(i*j&&i^n-1&&j^n-1?32:35));}
</code>```

Sneak in a multiply and save a byte...

```<code>i,j;f(n){for(i=n;i--;puts(""))for(j=n;j--;putchar(i&&j&&i^n-1&&j^n-1?32:35));}
</code>```

Also count down j and save a few more...

```<code>i,j;f(n){for(i=n;i--;puts(""))for(j=0;j++<n;putchar(i&&j^1&&i^n-1&&j^n?32:35));}
</code>```

Count down i from n to zero and save a few bytes...

```<code>i,j;f(n){for(i=0;i++<n;puts(""))for(j=0;j++<n;putchar(i^1&&j^1&&i^n&&j^n?32:35));}
</code>```

A bit easier to understand and 1 byte more

```<code>i,j;f(n){for(i=0;i++<n;puts(""))for(j=0;j++<n;putchar(i==1|i==n|j==1|j==n?35:32));}
</code>```

Title: Draw a hollow square of # with given width

Body:
I got this challenge from Codingame and am curious about better solutions than mine:

Given a width via standard input draw a hollow square of '#' in given width and length.

Example:

5 results in

```<code>#####
#   #
#   #
#   #
#####
</code>```

I used python to solve this so i am particulary interested in other python code. But please feel free to post your solution in any language you want.

Body:
C, <s>83</s> <s>82</s> <s>80</s> <s>78</s> 77 Bytes

i,j;f(n){for(i=n;i--;puts(""))for(j=n;j--;putchar(i*j&&i^n-1&&j^n-1?32:35));}

Sneak in a multiply and save a byte...

i,j;f(n){for(i=n;i--;puts(""))for(j=n;j--;putchar(i&&j&&i^n-1&&j^n-1?32:35));}

Also count down j and save a few more...

i,j;f(n){for(i=n;i--;puts(""))for(j=0;j++<n;putchar(i&&j^1&&i^n-1&&j^n?32:35));}

Count down i from n to zero and save a few bytes...

i,j;f(n){for(i=0;i++<n;puts(""))for(j=0;j++<n;putchar(i^1&&j^1&&i^n&&j^n?32:35));}

A bit easier to understand and 1 byte more

i,j;f(n){for(i=0;i++<n;puts(""))for(j=0;j++<n;putchar(i==1|i==n|j==1|j==n?35:32));}


答:
Java 7, <s>113</s> <s>112</s> 110 bytes

```<code>String c(int n){String r="";for(int i=n,j;i-->0;r+="\n")for(j=0;j<n;r+=i*j<1|n-i<2|n-j++<2?"#":" ");return r;}
</code>```

1 byte saved thanks to @OlivierGrégoire;

2 bytes saved thanks to @cliffroot.

Derived solution based on my Creating a Crossed Square answer.

Try it here.

Body:
Java 7, <s>113</s> <s>112</s> 110 bytes

String c(int n){String r="";for(int i=n,j;i-->0;r+="\n")for(j=0;j<n;r+=i*j<1|n-i<2|n-j++<2?"#":" ");return r;}

1 byte saved thanks to @OlivierGrégoire;

2 bytes saved thanks to @cliffroot.

Derived solution based on my Creating a Crossed Square answer.

Try it here.


Body:
C, 98 bytes

f(n,i){i=n*(n+1);while(i--){putchar(i%(n+1)==n?10:i<n||i>n*n-1||i%(n+1)==0||i%(n+1)==n-1?35:32);}}

Usage:

f(5)


答:
PowerShell v2+, <s>48</s> 47 bytes

```<code>param($n)($z='#'*$n--);,("#$(' '*--$n)#")*$n;$z
</code>```

-1 byte thanks to JohnLBevan

Takes input $n, sets $z as $n hashmarks, with $n post-decremented. Encapsulates that in parens to place a copy on the pipeline. Then uses the comma operator to create an array of pre-decremented $n lines of #,spaces,#. Those are left on the pipeline. Then places $z again on the pipeline. Output via implicit Write-Output at the end introduces a newline between elements, so we get that for free.

Since the OP's code doesn't work for input n <= 1, I took that to mean we don't need to support input 1, either.

Examples

```<code>PS C:\Tools\Scripts\golfing> 2..6|%{"$_";.\draw-a-hollow-square.ps1 $_;""}
2
##
##

3
###
# #
###

4
####
#  #
#  #
####

5
#####
#   #
#   #
#   #
#####

6
######
#    #
#    #
#    #
#    #
######
</code>```

Body:
PowerShell v2+, <s>48</s> 47 bytes

param($n)($z='#'*$n--);,("#$(' '*--$n)#")*$n;$z

-1 byte thanks to JohnLBevan

Takes input $n, sets $z as $n hashmarks, with $n post-decremented. Encapsulates that in parens to place a copy on the pipeline. Then uses the comma operator to create an array of pre-decremented $n lines of #,spaces,#. Those are left on the pipeline. Then places $z again on the pipeline. Output via implicit Write-Output at the end introduces a newline between elements, so we get that for free.

Since the OP's code doesn't work for input n <= 1, I took that to mean we don't need to support input 1, either.

Examples

PS C:\Tools\Scripts\golfing> 2..6|%{"$_";.\draw-a-hollow-square.ps1 $_;""}
2
##
##

3
###
# #
###

4
####
#  #
#  #
####

5
#####
#   #
#   #
#   #
#####

6
######
#    #
#    #
#    #
#    #
######


答:
Python 2, <s>62</s> 54 bytes

f=lambda n:'#'*n+'\n#%s#'%(' '*(n-2))*(n-2)+'\n'+'#'*n
```

<p>Returns <code>#\n#</code> when the input is <code>1</code><br/></p>

<p>55 Bytes version that prints</p>

<pre class="lang-python prettyprint-override"><code>def f(n):a=n-2;print'#'*n,'\n#%s#'%(' '*a)*a,'\n'+'#'*n
</code>```

62 Bytes version that works for any input:

f=lambda n:'#'*n+'\n#%s#'%(' '*(n-2))*(n-2)+('\n'+'#'*n)*(n>1)
```

Body:
Python 2, <s>62</s> 54 bytes

f=lambda n:'#'*n+'\n#%s#'%(' '*(n-2))*(n-2)+'\n'+'#'*n

Returns #\n# when the input is 1

55 Bytes version that prints

def f(n):a=n-2;print'#'*n,'\n#%s#'%(' '*a)*a,'\n'+'#'*n

62 Bytes version that works for any input:

f=lambda n:'#'*n+'\n#%s#'%(' '*(n-2))*(n-2)+('\n'+'#'*n)*(n>1)


Body:
Groovy, <s>51</s> 50 bytes

{n->a="*"*n+"\n";n-=2;print(a+"*${' '*n}*\n"*n+a)}


问:
Avoid repeating letters between five simple programs
You're challenge is to write 5 different full programs for the 5 following tasks:

Print Hello, World!

Given an input with STDIN, output the factorial, you can assume that the input is an integer >= 0

Given an integer N, calculate the sum of the primes <= N

Given an input with STDIN, output the letters used in the input. For example: the input is Hello world, you need to output helowrd. Note that the output is in lowercase. You can assume that the input is always alphabetic with whitespaces, the whitespaces are ignored.

Output the following diamond exactly like this:

```<code>  *
 ***
*****
</code>```

```<code>*****
 ***
  *
</code>```

All these challenges are probably very easy, but there is a catch. Every letter you use cannot be used again in the other programs. This is not prohibited, but will give you a penalty of +8 bytes. For example, if this is your program for the first task:

```<code>print("Hello, World!");
</code>```

Then you cannot use the following letters (in uppercase or lowercase form): p, r, i, n, t, h, e, l, o, w, d in the other programs. If you do have to use them, you can 'buy' each letter for 8 bytes. So if you want to use the letter l again in another program, you get a penalty of 8 bytes. After you have paid the penalty, you can use each letter as much as you want in this program. Other characters don't matter. Also, all 5 programs should be in the same language.

This is a code-challenge, least amount of bytes wins!

答:
Jelly, 46 bytes (non-competing)

```<code>“3ḅaė;œ»
Ɠ!
ÆRS
ɠQḲŒl
4Ḷ¤‘+¤ṖṚṭ×”*Fµ4Ḷṭ4ḶṚṖ¤F×⁶+⁸Y
</code>```

Try it online! (Copy/paste each snippet)

Apparently, the restriction did not restrict golfing :) Just suggestions for the last one, of course, please.

Body:
Jelly, 46 bytes (non-competing)

“3ḅaė;œ»
Ɠ!
ÆRS
ɠQḲŒl
4Ḷ¤‘+¤ṖṚṭ×”*Fµ4Ḷṭ4ḶṚṖ¤F×⁶+⁸Y

Try it online! (Copy/paste each snippet)

Apparently, the restriction did not restrict golfing :) Just suggestions for the last one, of course, please.


答:
05AB1E, 20 bytes

```<code>'#×D¹Íð×'#.ø¹Í×sJ¹ä»
</code>```

Try it online!

Or 18 bytes if we can ignore 1 <= n:

```<code>F„ #N¹<%_è¹Í×'#.ø,
</code>```

Try it online!

Body:
05AB1E, 20 bytes

'#×D¹Íð×'#.ø¹Í×sJ¹ä»

Try it online!

Or 18 bytes if we can ignore 1 <= n:

F„ #N¹<%_è¹Í×'#.ø,

Try it online!


答:
Jolf, 8 bytes

```<code>,ajj"###
,ajj      draw a box with height (input) and width (input)
    "###  with a hash border
</code>```

Body:
Jolf, 8 bytes

,ajj"###
,ajj      draw a box with height (input) and width (input)
    "###  with a hash border


Body:
MATL, 12 bytes

:G\1>&*~35*c

Try it online!

Explanation

:     % Input n implicitly. Push range [1 2 ... n]
      % STACK: [1 2 3 4 5]
G     % Push n again
      % STACK: [1 2 3 4 5], 5
\     % Modulo
      % STACK: [1 2 3 4 0]
1>    % Does each entry exceed 1?
      % STACK: [0 1 1 1 0]
&*    % Matrix with all pair-wise products
      % STACK: [0 0 0 0 0;
                0 1 1 1 0;
                0 1 1 1 0;
                0 1 1 1 0;
                0 0 0 0 0]
~     % Negate
      % STACK: [1 1 1 1 1;
                1 0 0 0 1;
                1 0 0 0 1;
                1 0 0 0 1;
                1 1 1 1 1]
35*   % Multiply by 35
      % STACK: [35 35 35 35 35;
                35  0  0  0 35;
                35  0  0  0 35;
                35  0  0  0 35;
                35 35 35 35 35]
c     % Convert to char. 0 is interpreted as space. Display implicitly
      % STACK: ['#####';
                '#   #';
                '#   #';
                '#   #';
                '#####']


答:
Charcoal, 6 bytes

Code:

```<code>ＮβＢββ#
</code>```

Explanation:

```<code>Ｎβ        # Get input from the command line and store into β
   Ｂ      # Draw a hollow box with...
     β     #  Width β
      β    #  Height β
       #   #  Filled with the character '#'
           # Implicitly output the box
</code>```

Try it online!

Body:
Charcoal, 6 bytes

Code:

ＮβＢββ#

Explanation:

Ｎβ        # Get input from the command line and store into β
   Ｂ      # Draw a hollow box with...
     β     #  Width β
      β    #  Height β
       #   #  Filled with the character '#'
           # Implicitly output the box

Try it online!


答:
Python 2, <s>59</s> 58 bytes

n=i=input()
while i:print'#%s#'%((' #'[i%n<2])*(n-2));i-=1
```

repl.it

Note: An input of 1 produces an output of ##, but a hollow square would never be produced for an input less than 3, so I guess this is fine.

Body:
Python 2, <s>59</s> 58 bytes

n=i=input()
while i:print'#%s#'%((' #'[i%n<2])*(n-2));i-=1

repl.it

Note: An input of 1 produces an output of ##, but a hollow square would never be produced for an input less than 3, so I guess this is fine.


Title: This is my pillow

Body:
Python 2, <s>83</s> 55 bytes

x=('/'*5+'\\'*5)*6;print((x+'\n')*4+(x[::-1]+'\n')*4)*3

Try it online!

-28 bytes thanks to Leaky Nun


Title: Fibonacci reversed!

Body:
Introduction

We all know and love our Fibonacci sequence and have seen a myriad of challenge on it here already. However, we're still lacking a very simple case which this answer is going to provide: Reversed fibonacci! So given F_n your job is to find n.

Specification

Input

Your input will be a non-negative integer, which is guaranteed to be part of the fibonacci sequence.

Output

The output must be a non-negative integer as well.

What to do?

The introduction already said: Given a fibonacci number, output its index. Fiboancci number hereby is defined as F(0)=0, F(1)=1, F(n)=F(n-1)+F(n-2) and you're given F(n) and must return n.

Potential Corner Cases

0 is a valid in- and output.

If given "1" as input you may either output "1" or "2", as you prefer.

You may always assume that your input actually is a fibonacci number.

You may assume that the input is representable as a 32-bit signed integer.

Who wins?

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

Standard rules apply of course.

Test-cases

```<code>0 -> 0
2 -> 3
3 -> 4
5 -> 5
8 -> 6
13 -> 7
1836311903 -> 46
</code>```

Body:
Groovy, 38 bytes

{a=c=0;b=1;for(;a<it;b+=(a=b-a))c++;c}


答:
GNU sed, 43 Bytes

Includes +2 for -rn.

```<code>s/1/a\nb\n/
:
P
s/(.*)\n(.*\n)./\2\1\2/
t
</code>```

Takes input in unary (see this consensus).

Try it Online!

Explanation:

```<code>s/1/a\nb\n/              # prepend an 'a' and a 'b' on their own lines and remove a '1'
:                        # nameless label
P                        # print everything before the first newline
s/(.*)\n(.*\n)./\2\1\2/  # replace the first two lines and the next character
                         # (one of the '1's) with the second line then the first line
                         # concatenated with the second
                         # E.g.
                         #     a           b
                         #     b      ->   ab
                         #     11111       1111
t                        # loop to the label if there was a '1' left (i.e. there was
                         # a substitution)
</code>```

Title: Print a letter Fibonacci

Body:
Given N (2 <= N), print N lines of the letter Fibonacci series like this (i.e. N = 5)
First, start with a and b:

```<code>a
b
</code>```

Next, add the two lines.

```<code>a
b
ab
</code>```

Keep adding the last two lines.

```<code>a
b
ab
bab
</code>```

Keep going...

```<code>a
b
ab
bab
abbab
</code>```

And we're done.

Remember, this is code-golf, so the code with the fewest bytes wins.

Body:
GNU sed, 43 Bytes

Includes +2 for -rn.

s/1/a\nb\n/
:
P
s/(.*)\n(.*\n)./\2\1\2/
t

Takes input in unary (see this consensus).

Try it Online!

Explanation:

s/1/a\nb\n/              # prepend an 'a' and a 'b' on their own lines and remove a '1'
:                        # nameless label
P                        # print everything before the first newline
s/(.*)\n(.*\n)./\2\1\2/  # replace the first two lines and the next character
                         # (one of the '1's) with the second line then the first line
                         # concatenated with the second
                         # E.g.
                         #     a           b
                         #     b      ->   ab
                         #     11111       1111
t                        # loop to the label if there was a '1' left (i.e. there was
                         # a substitution)


答:
PHP, <s>81</s> 69 bytes

```<code>for($n=-1+$i=$argv[1];$i--;)echo str_pad("#",$n," #"[$i%$n<1]),"#\n";
</code>```

Run with -r; provide input as argument.

Throws a DivisionByZeroError for input=1.

Body:
I got this challenge from Codingame and am curious about better solutions than mine:

Given a width via standard input draw a hollow square of '#' in given width and length.

Example:

5 results in

```<code>#####
#   #
#   #
#   #
#####
</code>```

I used python to solve this so i am particulary interested in other python code. But please feel free to post your solution in any language you want.

Body:
PHP, <s>81</s> 69 bytes

for($n=-1+$i=$argv[1];$i--;)echo str_pad("#",$n," #"[$i%$n<1]),"#\n";

Run with -r; provide input as argument.

Throws a DivisionByZeroError for input=1.


答:
Python 2, <s>60</s> <s>65</s> <s>69</s> <s>62</s> 61 bytes

```<code>x=input();h='#';print h*x+'\n'+(h+' '*(x-2)+h+'\n')*(x-2)+h*x
</code>```

My first attempt at this problem, I will golf it down hopefully.

+5 bytes I forgot to put newlines between the lines :(

+4 bytes I forgot to add 2 to the last x :(

-7 bytes If I don't subtract 2 from the input at the beginning and subtract it where it would make sense to do so, I can actually save 7 bytes :)

-1 byte Thanks to @Cyoce for helping me save 1 byte by assigning '#' to a variable (which I called h because that's what he was thinking in the comments :P)

Still 1 byte longer than before... :(

Body:
Python 2, <s>60</s> <s>65</s> <s>69</s> <s>62</s> 61 bytes

x=input();h='#';print h*x+'\n'+(h+' '*(x-2)+h+'\n')*(x-2)+h*x

My first attempt at this problem, I will golf it down hopefully.

+5 bytes I forgot to put newlines between the lines :(

+4 bytes I forgot to add 2 to the last x :(

-7 bytes If I don't subtract 2 from the input at the beginning and subtract it where it would make sense to do so, I can actually save 7 bytes :)

-1 byte Thanks to @Cyoce for helping me save 1 byte by assigning '#' to a variable (which I called h because that's what he was thinking in the comments :P)

Still 1 byte longer than before... :(


问:
Decode Baby-talk!
When babies open their mouths, they're not just spewing gibberish. They're actually talking in a highly advanced, adult-proof cipher...

The Baby-talk Cipher

When a baby talks, it could look something like gogooa gagooook aagaaoooy
Each single-space separated section represents a character (so the example above represents 3 characters).

To decipher a section, we must count number of As and Os it contains. However, we only count those which are adjacent to another vowel. For example, the A in 'gag' would not count, but both the A and O in 'gaog' would.

Counting the example above would look like this:

```<code>Section    | Num Os | Num As

gogooa     | 2      | 1
gagooook   | 4      | 0
aagaaoooy  | 3      | 4
</code>```

We then use these values to convert the input into plaintext on a Polybius square. This is a 5x5 representation of the English alphabet, omitting 'J' (please note that, in baby-talk, 0-counting rules apply to the table):

```<code>  0 1 2 3 4
0 A B C D E
1 F G H I K
2 L M N O P
3 Q R S T U
4 V W X Y Z
</code>```

Using the number of Os as the column, and number of As as the row, we find which character each section represents:

```<code>Section    | Num Os | Num As | Character

gogooa     | 2      | 1      | (2,1) -> H
gagooook   | 4      | 0      | (4,0) -> E
aagaaoooy  | 3      | 4      | (3,4) -> Y
</code>```

Which tells us that the baby was just saying "HEY".

Notes:

- If a section representing a character has more than 4 As or Os, ignore the extras, because 4 is the maximum value on the table.
- For this task, Y is not a vowel - only A, E, I, O and U.

The Challenge

Your task is to create a full program which takes one input, a word in baby-speak, and prints it in plaintext.

Your program must be able to take input in uppercase, lowercase, and a mix of both.

The input will only contain ASCII alphabet letters (A-Z and a-z), with single spaces to seperate the baby words.

The output text can be in any case.

You should the take the input from STDIN and print the plaintext on STDOUT. If your language does not have these, use the nearest equivalent.

This is code-golf, so the shortest code in bytes wins - but any solution is welcome.

Test Cases

```<code>'GLOOG KAKAAOOO ARGOOO OOOOOGUGUU' -> CODE
'oaka pooopaa gaau augu' -> GOLF
'Aoao U oOOAoa oaoAoo aoAoAOa' -> NAPPY
'GUG gAGaA gOougOou' -> ALE
'OOaGOG GoGOOoGoU gAA bLAA GOUGoOUgAIGAI' -> HELLO
</code>```

答:
APL, 60

```<code>{⎕A[a+9<a←5⊥+/¨'ao'∊⍨¨⊂⍵/⍨0(,∨,⍨)2∧/⍵∊'aeiou']}¨' '(≠⊂⊢)819⌶
</code>```

Note that ⎕IO←0 and ⎕ML←3

Example:

```<code>fn←{⎕A[a+9<a←5⊥+/¨'ao'∊⍨¨⊂⍵/⍨0(,∨,⍨)2∧/⍵∊'aeiou']}¨' '(≠⊂⊢)819⌶
fn 'Aoao U oOOAoa oaoAoo aoAoAOa'
NAPPY
</code>```

Works in Dyalog 15.0, since it's the version in which 819⌶ was introduced to lowercase a string.

Title: Decode Baby-talk!

Body:
APL, 60

{⎕A[a+9<a←5⊥+/¨'ao'∊⍨¨⊂⍵/⍨0(,∨,⍨)2∧/⍵∊'aeiou']}¨' '(≠⊂⊢)819⌶

Note that ⎕IO←0 and ⎕ML←3

Example:

fn←{⎕A[a+9<a←5⊥+/¨'ao'∊⍨¨⊂⍵/⍨0(,∨,⍨)2∧/⍵∊'aeiou']}¨' '(≠⊂⊢)819⌶
fn 'Aoao U oOOAoa oaoAoo aoAoAOa'
NAPPY

Works in Dyalog 15.0, since it's the version in which 819⌶ was introduced to lowercase a string.


答:
R, 123.2 102.9 98.7 bytes (141-30%)

Edit: Saved a handful of bytes thanks to @Angs!

If someone wants to edit the pictures feel free to do so. This is basically an R adaptation of both the matlab and python versions posted.

```<code>function(f,a,b,N){n=N-1;x=1:N/n;A=toeplitz(c(2,-1,rep(0,N-2)));A[1,1:2]=1:0;A[N,n:N]=0:1;y=n^-2*sapply(x,f);y[1]=a;y[N]=b;plot(x,solve(A,y))}
</code>```

Ungolfed & explained:

```<code>u=function(f,a,b,N){
    n=N-1;                                              # Alias for N-1
    x=0:n/n;                                            # Generate the x-axis
    A=toeplitz(c(2,-1,rep(0,N-2)));                     # Generate the A-matrix
    A[1,1:2]=1:0;                                       # Replace first row--
    A[N,n:N]=0:1;                                       # Replace last row
    y=n^-2*sapply(x,f)                                  # Generate h^2*f(x)
    y[1]=a;y[N]=b;                                      # Replace first and last elements with uL(a) and uR(b)
    plot(x,solve(A,y))                                  # Solve the matrix system A*x=y for x and plot against x
}
</code>```

Example & test cases:

The named and ungolfed function can be called using:

```<code>u(function(x)-2,0,0,10)
u(function(x)x*10,0,1,15)
u(function(x)sin(2*pi*x),1,1,20)
u(function(x)x^2,0,0,30)
</code>```

Note that the f argument is an R-function.

To run the golfed version simply use (function(...){...})(args)

Title: Solve the Laplace equation

Body:
Introduction to Numerical Mathematics

This is the "Hello, World!" of PDEs (Partial Differential Equations). The Laplace or Diffusion Equation appears often in Physics, for example Heat Equation, Deforming, Fluid Dynamics, etc... As real life is 3D but we want to say "Hello, World!" and not sing "99 bottles of beer,..." this task is given in 1D. You may interpret this as a rubber robe tied to a wall on both ends with some force applied to it.

On a \$[0,1]\$ domain, find a function \$u\$ for given source function \$f\$ and boundary values \$u_L\$ and \$u_R\$ such that:

\$-u'' = f\$

\$u(0) = u_L\$

\$u(1) = u_R\$

\$u''\$ denotes the second derivative of \$u\$

This can be solved purely theoretically but your task is it to solve it numerically on a discretized domain \$x\$ for \$N\$ points:

\$x = \{\frac i {N-1} : 0 \le i \le N-1\}\$ or 1-based: \$\{\frac {i-1} {N-1} : 0 \le i \le N-1\}\$

\$h = \frac 1 {N-1}\$ is the spacing

Input

\$f\$ as a function, expression or string

\$u_L\$, \$u_R\$ as floating point values

\$N \ge 2\$ as an integer

Output

Array, List, some sort of separated string of \$u\$ such that \$u_i = u(x_i)\$

Examples

Example 1

Input: \$f = -2\$, \$u_L = u_R = 0\$, \$N = 10\$ (Don't take \$f=-2\$ wrong, it is not a value but a constant function that returns \$-2\$ for all \$x\$. It is like a constant gravity force on our rope.)

Output: [-0.0, -0.09876543209876543, -0.1728395061728395, -0.22222222222222224, -0.24691358024691357, -0.24691358024691357, -0.22222222222222224, -0.1728395061728395, -0.09876543209876547, -0.0]

There exists an easy exact solution: \$u = -x(1-x)\$

Example 2

Input: \$f = 10x\$, \$u_L = 0\$, \$u_R = 1\$, \$N = 15\$ (Here there is a lot of upwind on the right side)

Output: [ 0., 0.1898688, 0.37609329, 0.55502915, 0.72303207, 0.87645773, 1.01166181, 1.125, 1.21282799, 1.27150146, 1.29737609, 1.28680758, 1.2361516, 1.14176385, 1.]

The exact solution for this states: \$u = \frac 1 3(8x-5x^3)\$

Example 3

Input: \$f = \sin(2\pi x)\$, \$u_L = u_R = 1\$, \$N = 20\$ (Someone broke gravity or there is a sort of up- and downwind)

Output: [ 1., 1.0083001, 1.01570075, 1.02139999, 1.0247802, 1.0254751, 1.02340937, 1.01880687, 1.01216636, 1.00420743, 0.99579257, 0.98783364, 0.98119313, 0.97659063, 0.9745249, 0.9752198, 0.97860001, 0.98429925, 0.9916999, 1.]

Here the exact solution is \$u = \frac {\sin(2πx)} {4π^2}+1\$

Example 4

Input: \$f = \exp(x^2)\$, \$u_L = u_R = 0\$, \$N=30\$

Output:
[ 0.          0.02021032  0.03923016  0.05705528  0.07367854  0.0890899 0.10327633  0.11622169  0.12790665  0.13830853  0.14740113  0.15515453 0.16153488  0.1665041   0.17001962  0.172034    0.17249459  0.17134303 0.16851482  0.1639387   0.15753606  0.1492202   0.13889553  0.12645668 0.11178744  0.09475961  0.07523169  0.05304738  0.02803389  0.        ]

Note the slight asymmetry

FDM

One possible method to solve this is the Finite Difference Method:

Rewrite \$-u_i'' = f_i\$ as \$\frac {-u_{i-1} + 2u_i - u_{i+1}} {h^2} = f_i\$, which equals \$-u_{i-1} + 2u_i - u_{i+1} = h^2 f_i\$

Setup the equations:

$$
u_0 = u_L \\
\frac {-u_0 + 2u_1 - u_2} {h^2} = f_1 \\
\frac {-u_1 + 2u_2 - u_3} {h^2} = f_2 \\
\dots = \dots \\
\frac {-u_{n-3} + 2u_{n-2} - u_{n-1}} {h^2} = f_{n-2} \\
u_{n-1} = u_R
$$

Which are equal to a matrix-vector equation:

$$
\begin{pmatrix}
 1 & & & & & & \\
-1 & 2 & -1 & & & & \\
 & -1 & 2& -1& & & \\
 & & \ddots & \ddots & \ddots & & \\
 & & & -1 & 2 & -1 & \\
 & & & & -1 & 2 & -1 \\
 & & & & & & 1
\end{pmatrix}
\begin{pmatrix}
u_0 \\ u_1 \\ u_2 \\ \vdots \\ u_{n-3} \\ u_{n-2} \\ u_{n-1}
\end{pmatrix}
=
\begin{pmatrix}
u_L \\ h^2 f_1 \\ h^2 f_2 \\ \vdots \\ h^2 f_{n-3} \\ h^2 f_{n-2} \\ u_R
\end{pmatrix}
$$

Solve this equation and output the \$u_i\$

One implementation of this for demonstration in Python:

```<code>import matplotlib.pyplot as plt
import numpy as np
def laplace(f, uL, uR, N):
 h = 1./(N-1)
 x = [i*h for i in range(N)]

 A = np.zeros((N,N))
 b = np.zeros((N,))

 A[0,0] = 1
 b[0] = uL

 for i in range(1,N-1):
  A[i,i-1] = -1
  A[i,i]   =  2
  A[i,i+1] = -1
  b[i]     = h**2*f(x[i])

 A[N-1,N-1] = 1
 b[N-1]     = uR

 u = np.linalg.solve(A,b)

 plt.plot(x,u,'*-')
 plt.show()

 return u

print laplace(lambda x:-2, 0, 0, 10)
print laplace(lambda x:10*x, 0, 1, 15)
print laplace(lambda x:np.sin(2*np.pi*x), 1, 1, 20)
</code>```

Alternative implementation without Matrix Algebra (using the Jacobi method)

```<code>def laplace(f, uL, uR, N):
 h=1./(N-1)
 b=[f(i*h)*h*h for i in range(N)]
 b[0],b[-1]=uL,uR
 u = [0]*N

 def residual():
  return np.sqrt(sum(r*r for r in[b[i] + u[i-1] - 2*u[i] + u[i+1] for i in range(1,N-1)]))

 def jacobi():
  return [uL] + [0.5*(b[i] + u[i-1] + u[i+1]) for i in range(1,N-1)] + [uR]

 while residual() > 1e-6:
  u = jacobi()

 return u
</code>```

You may however use any other method to solve the Laplace equation. If you use an iterative method, you should iterate until the residual \$|b-Au| < 10^{-6}\$, with \$b\$ being the right hand side vector \$u_L,f_1 h^2,f_2 h^2, \dots\$

Notes

Depending on your solution method you may not solve the examples exactly to the given solutions. At least for \$N \to \infty\$ the error should approach zero.

Standard loopholes are disallowed, built-ins for PDEs are allowed.

Bonus

A bonus of -30% for displaying the solution, either graphical or ASCII-art.

Winning

This is codegolf, so shortest code in bytes wins!

Body:
R, 123.2 102.9 98.7 bytes (141-30%)

Edit: Saved a handful of bytes thanks to @Angs!

If someone wants to edit the pictures feel free to do so. This is basically an R adaptation of both the matlab and python versions posted.

function(f,a,b,N){n=N-1;x=1:N/n;A=toeplitz(c(2,-1,rep(0,N-2)));A[1,1:2]=1:0;A[N,n:N]=0:1;y=n^-2*sapply(x,f);y[1]=a;y[N]=b;plot(x,solve(A,y))}

Ungolfed & explained:

u=function(f,a,b,N){
    n=N-1;                                              # Alias for N-1
    x=0:n/n;                                            # Generate the x-axis
    A=toeplitz(c(2,-1,rep(0,N-2)));                     # Generate the A-matrix
    A[1,1:2]=1:0;                                       # Replace first row--
    A[N,n:N]=0:1;                                       # Replace last row
    y=n^-2*sapply(x,f)                                  # Generate h^2*f(x)
    y[1]=a;y[N]=b;                                      # Replace first and last elements with uL(a) and uR(b)
    plot(x,solve(A,y))                                  # Solve the matrix system A*x=y for x and plot against x
}

Example & test cases:

The named and ungolfed function can be called using:

u(function(x)-2,0,0,10)
u(function(x)x*10,0,1,15)
u(function(x)sin(2*pi*x),1,1,20)
u(function(x)x^2,0,0,30)

Note that the f argument is an R-function.

To run the golfed version simply use (function(...){...})(args)


答:
APL, 16

```<code>4⌿5/1↓⍉12 7⍴'\/'
</code>```

Try it on tryapl.org

Title: This is my pillow

Body:
...will you help me immortalize it?

I've had this pillow a few years now, and apparently it's time to get rid of it. Can you please write a function or program, that I can bring with me and use to recreate this pillow whenever I want to reminisce a bit.

It must work with no input arguments.

The output should look exactly like this (trailing newlines and spaces are OK).

```<code>/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
</code>```

This is code golf, so the shortest code in bytes win!

Leaderboard

var QUESTION_ID=98701,OVERRIDE_USER=31516;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+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+)(?=[^\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

```

Body:
APL, 16

4⌿5/1↓⍉12 7⍴'\/'

Try it on tryapl.org


问:
Count without 3

Background

When I was in elementary school, we used to play a game in math class that goes as follows.

All kids sit in a big circle and take turns counting, starting from 1.

However, the following numbers must be skipped while counting:

Numbers that are multiples of 3.

Numbers that have a 3 in its decimal representation.

The first 15 numbers the kids should say are

```<code>1 2 4 5 7 8 10 11 14 16 17 19 20 22 25
</code>```

Whenever somebody gets a number wrong – says a number that isn't in the sequence or skips a number that is – he's removed from the circle. This goes on until there's only one kid left.

Task

You're bad at this game, so you decide to cheat. Write a program or a function that, given a number of the sequence, calculates the next number of the sequence.

You don't have to handle numbers that cannot be represented using your language's native numeric type, provided that your program works correctly up to input 251 and that your algorithm works for arbitrarily large inputs.

Input and output can use any convenient base.

Since you have to conceal your code, it must be as short as possible. In fact, this is code-golf, so the shortest code in bytes wins.

Test cases

```<code>  1 ->   2
  2 ->   4
 11 ->  14
 22 ->  25
 29 ->  40
251 -> 254
</code>```

答:
Labyrinth, 117 102 bytes

```<code>?       """""""""""_
):_3    (         0/{!@
;  %;:}_';:_3-_10 1
"  1            %;_
""""_""""""""{;;'
</code>```

Try it online!

Labyrinth is a two-dimensional, stack-based programming language and at junctions, direction is determined by the top of the stack (positive goes right, negative goes left, zero goes straight). There are two main loops in this programs. The first mods the integer input by 3 and increments if 0. The second repeatedly checks if the last digit is 3 (by subtracting 3 and modding by 10) and then dividing by 10 to get a new last digit.

Title: Count without 3

Body:
Labyrinth, 117 102 bytes

?       """""""""""_
):_3    (         0/{!@
;  %;:}_';:_3-_10 1
"  1            %;_
""""_""""""""{;;'

Try it online!

Labyrinth is a two-dimensional, stack-based programming language and at junctions, direction is determined by the top of the stack (positive goes right, negative goes left, zero goes straight). There are two main loops in this programs. The first mods the integer input by 3 and increments if 0. The second repeatedly checks if the last digit is 3 (by subtracting 3 and modding by 10) and then dividing by 10 to get a new last digit.