答:
R, 72 69 bytes

Takes input from stdin and returns an R-vector of probabilities.

```<code>apply(abs(t(expand.grid(rep(list(1:0),length(x<-scan())))-x)),1,prod)
</code>```

Edit: Removed one unnecessary transpose, the permutation matrix is now the transposed version of the one below and the probabilities are calculated as the column-wise product rather than row-wise.
Example output:

```<code>[1] 0.129195 0.157905 0.262305 0.320595 0.019305 0.023595 0.039195 0.047905
</code>```

Note that the probabilities are in a different order due to the fact that the permutation-matrix generated by expand.grid produces the following (generation of this matrix can probably be golfed using external packages):

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

The first probability corresponds to the inverted outcome of the first row in the above matrix and the second to the inverted second row etc. Formatting output to see this even more clearly makes the program longer (164 bytes):

```<code>m=expand.grid(rep(list(1:0),length(x<-scan())))
cat(paste0("[",apply(abs(m-1),1,function(x)paste0(x,collapse=",")),"] = ",apply(abs(t(t(m)-x)),1,prod),"\n"),sep="")
</code>```

which instead produces:

```<code>[0,0,0] = 0.129195
[1,0,0] = 0.157905
[0,1,0] = 0.262305
[1,1,0] = 0.320595
[0,0,1] = 0.019305
[1,0,1] = 0.023595
[0,1,1] = 0.039195
[1,1,1] = 0.047905
</code>```

Title: Probability of All Combinations of Given Events

Body:
Given a sequences of events with probabilities between 0.0 and 1.0, generate and derive the probability of each combination occurring. You may presume that a sequence of numbers is provided in whatever construct your chosen language provides.

Here's an example; you may presume that the length of the sequence's combinations fit into memory:

```<code>{ 0.55, 0.67, 0.13 }
</code>```

The program shall print each combination and the associated probability of that sequence occurring. A 1 shall denote that the event in that index of the input sequence occurred and a 0 shall denote that that event did not occur. The desired output is below (I don't care about printing the work, that's just for informational purposes of the algorithm):

```<code>[0,0,0] = (1 - 0.55) * (1-0.67) * (1-0.13) = 0.129195
[0,0,1] = (1 - 0.55) * (1-0.67) * (0.13)   = 0.019305
[0,1,0] = (1 - 0.55) * (0.67)   * (1-0.13) = 0.262305
[0,1,1] = (1 - 0.55) * (0.67)   * (0.13)   = 0.039195
[1,0,0] = (0.55)     * (1-0.67) * (1-0.13) = 0.157905
[1,0,1] = (0.55)     * (1-0.67) * (0.13)   = 0.023595
[1,1,0] = (0.55)     * (0.67)   * (1-0.13) = 0.320595
[1,1,1] = (0.55)     * (0.67)   * (0.13)   = 0.047905
</code>```

This problem is tangentially related to calculating a "Cartesian product".

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

Body:
R, 72 69 bytes

Takes input from stdin and returns an R-vector of probabilities.

apply(abs(t(expand.grid(rep(list(1:0),length(x<-scan())))-x)),1,prod)

Edit: Removed one unnecessary transpose, the permutation matrix is now the transposed version of the one below and the probabilities are calculated as the column-wise product rather than row-wise.
Example output:

[1] 0.129195 0.157905 0.262305 0.320595 0.019305 0.023595 0.039195 0.047905

Note that the probabilities are in a different order due to the fact that the permutation-matrix generated by expand.grid produces the following (generation of this matrix can probably be golfed using external packages):

1    1    1    1
2    0    1    1
3    1    0    1
4    0    0    1
5    1    1    0
6    0    1    0
7    1    0    0
8    0    0    0

The first probability corresponds to the inverted outcome of the first row in the above matrix and the second to the inverted second row etc. Formatting output to see this even more clearly makes the program longer (164 bytes):

m=expand.grid(rep(list(1:0),length(x<-scan())))
cat(paste0("[",apply(abs(m-1),1,function(x)paste0(x,collapse=",")),"] = ",apply(abs(t(t(m)-x)),1,prod),"\n"),sep="")

which instead produces:

[0,0,0] = 0.129195
[1,0,0] = 0.157905
[0,1,0] = 0.262305
[1,1,0] = 0.320595
[0,0,1] = 0.019305
[1,0,1] = 0.023595
[0,1,1] = 0.039195
[1,1,1] = 0.047905


问:
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

答:
Batch, 57 bytes

```<code>@set n=0
@for %%n in (%*)do @set/an=n*%%n+%%n
@echo %n%
</code>```

Takes input as command-line parameters. Works by multiplying the accumulator by the current value before adding it on, so that any zeros in the command line reset the count. Note that %%n is not the same as the n or %n% variable.

ContentLicense: CC BY-SA 4.0

Title: Count trailing truths

Body:
Batch, 57 bytes

@set n=0
@for %%n in (%*)do @set/an=n*%%n+%%n
@echo %n%

Takes input as command-line parameters. Works by multiplying the accumulator by the current value before adding it on, so that any zeros in the command line reset the count. Note that %%n is not the same as the n or %n% variable.

ContentLicense: CC BY-SA 3.0


问:
Probability of All Combinations of Given Events
Given a sequences of events with probabilities between 0.0 and 1.0, generate and derive the probability of each combination occurring. You may presume that a sequence of numbers is provided in whatever construct your chosen language provides.

Here's an example; you may presume that the length of the sequence's combinations fit into memory:

```<code>{ 0.55, 0.67, 0.13 }
</code>```

The program shall print each combination and the associated probability of that sequence occurring. A 1 shall denote that the event in that index of the input sequence occurred and a 0 shall denote that that event did not occur. The desired output is below (I don't care about printing the work, that's just for informational purposes of the algorithm):

```<code>[0,0,0] = (1 - 0.55) * (1-0.67) * (1-0.13) = 0.129195
[0,0,1] = (1 - 0.55) * (1-0.67) * (0.13)   = 0.019305
[0,1,0] = (1 - 0.55) * (0.67)   * (1-0.13) = 0.262305
[0,1,1] = (1 - 0.55) * (0.67)   * (0.13)   = 0.039195
[1,0,0] = (0.55)     * (1-0.67) * (1-0.13) = 0.157905
[1,0,1] = (0.55)     * (1-0.67) * (0.13)   = 0.023595
[1,1,0] = (0.55)     * (0.67)   * (1-0.13) = 0.320595
[1,1,1] = (0.55)     * (0.67)   * (0.13)   = 0.047905
</code>```

This problem is tangentially related to calculating a "Cartesian product".

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

答:
C, 110 bytes

i,k;f(float* a,int n){for(k=0;k<1<<n;++k){float p=1;for(i=0;i<n;++i)p*=k&(1<<i)?a[i]:1-a[i];printf("%f,",p);}}
```
<p>Ungolfed:</p>
<pre class="lang-c prettyprint-override"><code>i,k;f(float* a,int n){
 for(k=0; k<1<<n; ++k){
  float p=1;
  for (i=0; i<n; ++i)
   p*=k&(1<<i)?a[i]:1-a[i];
  printf("%f,",p);
 }
}
</code>```

Works up to 32 items, +5+1 bytes for 64 items (declare long k; and add L in the first loop so that k<1L<<N).

Body:
C, 110 bytes

i,k;f(float* a,int n){for(k=0;k<1<<n;++k){float p=1;for(i=0;i<n;++i)p*=k&(1<<i)?a[i]:1-a[i];printf("%f,",p);}}

Ungolfed:

i,k;f(float* a,int n){
 for(k=0; k<1<<n; ++k){
  float p=1;
  for (i=0; i<n; ++i)
   p*=k&(1<<i)?a[i]:1-a[i];
  printf("%f,",p);
 }
}

Works up to 32 items, +5+1 bytes for 64 items (declare long k; and add L in the first loop so that k<1L<<N).


问:
Big or Little Endian
Write a program or function that outputs an L if run on a little endian architecture or a B if run on a big endian architecture. Lower case output l or b is also acceptable.

There is no input.

Scoring is code golf, so the code with the fewest bytes wins.

Edit: As per the comments below, I am clarifying that the entry must be able to run on either architecture.

I believe that there is only one answer that this affects, and that answer has clearly indicated that this is the case.

答:
GNU Utils, 35 bytes

```<code>lscpu|grep -o ':.*n'|grep -Eo 'L|B'
</code>```

Tested on Linux kali 4.6.0-kali1-amd64 #1 SMP Debian 4.6.4-1kali1 (2016-07-21) x86_64 GNU/Linux, but I'm pretty sure the output should be fairly standard on most GNU/Linux distros.

Title: Big or Little Endian

Body:
GNU Utils, 35 bytes

lscpu|grep -o ':.*n'|grep -Eo 'L|B'

Tested on Linux kali 4.6.0-kali1-amd64 #1 SMP Debian 4.6.4-1kali1 (2016-07-21) x86_64 GNU/Linux, but I'm pretty sure the output should be fairly standard on most GNU/Linux distros.


答:
Batch, 132 bytes

```<code>@set s=/////\\\\\
@set s=%s%%s%%s%%s%%s%%s%
@set s=%s% %s:~5%/////
@for %%s in (%s% %s% %s%)do @for /l %%i in (1,1,4)do @echo %%s
</code>```

Works by building up the two types of row, then looping through six rows four times per row.

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:
Batch, 132 bytes

@set s=/////\\\\\
@set s=%s%%s%%s%%s%%s%%s%
@set s=%s% %s:~5%/////
@for %%s in (%s% %s% %s%)do @for /l %%i in (1,1,4)do @echo %%s

Works by building up the two types of row, then looping through six rows four times per row.


答:
Haskell, 24 bytes

foldl(\a b->sum[a+1|b])0
```

<p>Iterates over the list, adding one for each element, resetting to <code>0</code> after it hits a <code>False</code>.</p>

<p><strong>16 bytes</strong> with 0/1 input:</p>

<pre class="lang-haskell prettyprint-override"><code>foldl((*).(+1))0
</code>```

If the list were guaranteed non-empty, we could get 14 bytes:

sum.scanr1(*)1
```

This computes the cumulative product from the back, then sums them. The cumulative product remains 1 until a 0 is hit, and then becomes 0. So, the 1's correspond to trailing 1's.

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:
Haskell, 24 bytes

foldl(\a b->sum[a+1|b])0

Iterates over the list, adding one for each element, resetting to 0 after it hits a False.

16 bytes with 0/1 input:

foldl((*).(+1))0

If the list were guaranteed non-empty, we could get 14 bytes:

sum.scanr1(*)1

This computes the cumulative product from the back, then sums them. The cumulative product remains 1 until a 0 is hit, and then becomes 0. So, the 1's correspond to trailing 1's.


答:
Pyth, 10 bytes

```<code>*MaVLQ^U2l
</code>```

Try it online: Demonstration

Explanation:

```<code>*MaVLQ^U2lQ   implicit Q at the end (Q = input list)
      ^U2lQ   repeated Cartesian product of [0, 1] with itself length(Q)-times
              this gives all combinations of 0s and 1s
  aVLQ        absolute difference between these 0-1-vectors with Q
*M            fold the vectors by multiplication
</code>```

Body:
Pyth, 10 bytes

*MaVLQ^U2l

Try it online: Demonstration

Explanation:

*MaVLQ^U2lQ   implicit Q at the end (Q = input list)
      ^U2lQ   repeated Cartesian product of [0, 1] with itself length(Q)-times
              this gives all combinations of 0s and 1s
  aVLQ        absolute difference between these 0-1-vectors with Q
*M            fold the vectors by multiplication


答:
Lithp, 166 characters

Line split for readability.

```<code>#::((def x #S,N::(invoke S repeat N))(var A (x "/" 5))(var B (x "\\" 5))
(var C (+ (x (+ A B) 6) (nl)))(var D (+ (x (+ B A) 6) (nl)))
(print (x (+ (x C 4) (x D 4)) 5)))
</code>```

Sample usage:

```<code>% pillow.lithp
(
    (def f #::((def x #S,N::(invoke S repeat N))(var A (x "/" 5))(var B (x "\\" 5))(var C (+ (x (+ A B) 6) (nl)))(var D (+ (x (+ B A) 6) (nl)))(print (x (+ (x C 4) (x D 4)) 5))))
    (f)
)
</code>```

Run with:

```<code>./run.js pillow.lithp
</code>```

This is a fairly simple solution that repeats characters. There is no standalone repeat function yet, so invoke is used to call "string".repeat(N) and adds a bit to the count.

Title: This is my pillow

Body:
Lithp, 166 characters

Line split for readability.

#::((def x #S,N::(invoke S repeat N))(var A (x "/" 5))(var B (x "\\" 5))
(var C (+ (x (+ A B) 6) (nl)))(var D (+ (x (+ B A) 6) (nl)))
(print (x (+ (x C 4) (x D 4)) 5)))

Sample usage:

% pillow.lithp
(
    (def f #::((def x #S,N::(invoke S repeat N))(var A (x "/" 5))(var B (x "\\" 5))(var C (+ (x (+ A B) 6) (nl)))(var D (+ (x (+ B A) 6) (nl)))(print (x (+ (x C 4) (x D 4)) 5))))
    (f)
)

Run with:

./run.js pillow.lithp

This is a fairly simple solution that repeats characters. There is no standalone repeat function yet, so invoke is used to call "string".repeat(N) and adds a bit to the count.


问:
The nth numerator
You can create a list of all rationals 0 < r ≤ 1 by listing them ordered first by denominator and then by numerator:

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

Note that we skip any rational number that already occurred before. E.g. 2/4 is skipped because we already listed 1/2.

In this challenge we're interested in the numerators only. Looking at the list above, write a function or program taking a positive integer n that returns the nth numerator from the list.

Testcases:

```<code>1 -> 1
2 -> 1
3 -> 1
4 -> 2
5 -> 1
6 -> 3
7 -> 1
8 -> 2
9 -> 3
50 -> 4
80 -> 15
</code>```

Title: The nth numerator

Body:
Perl, 82 + 2 (-pl flag) = 84 bytes

perl -ple '{{$d>$n?($n++,(grep!($n%$_||$d%$_),2..$d)&&redo):($n=1,$d++)}++$i!=$_&&redo;$_=$n}'

Ungolfed:

while (<>) {  # -p flag
    chomp();  # -l flag

    my $i = 0;
    my $n = 0;
    my $d = 0;

    for (;;) {
        for (;;) {
            if ($d <= $n) {
                $n = 1;
                $d++;
                last;
            }
            else {
                $n++;
                last unless grep { !($n % $_) && !($d % $_) } 2 .. $d;
            }
        }
        if (++$i == $_) {
            $_ = $n;
            last;
        }
    }
}
continue {
    print($_, "\n");
}


Body:
Perl, <s>42</s> 40 bytes

Includes +1 for -a

Give numbers on STDIN:

perl -M5.010 combi.pl <<< "0.55 0.67 0.13"

outputs

0.129195
0.019305
0.262305
0.039195
0.157905
0.023595
0.320595
0.047905

combi.pl:

#!/usr/bin/perl -a
$"=")\\*({1-,}";say eval for<({1-,}@F)>


问:
Wait... what was I going to say again?
I often forget what I wanted to say when the teacher calls on me to speak. Can you make me a tool to solve this?

Requirements:

The program must loop as follows:

First, take in input

If the input is empty, print the last stored question.

Otherwise, store the input as a question.

Notes:

The input will never be empty if there are no questions stored.

Clarification: The program does not need to store multiple questions. I originally wanted it to store multiple, but I changed it after many people misunderstood the question.

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

答:
Python 3, 31 bytes

```<code>while 1: I=input()or I;print(I)
</code>```

Try it out!

-1 byte thanks to Flp.Tkc

Title: Wait... what was I going to say again?

Body:
Python 3, 31 bytes

while 1: I=input()or I;print(I)

Try it out!

-1 byte thanks to Flp.Tkc


答:
GolfSharp, 14 bytes

```<code>n=>n.V().O(F);
</code>```

Title: Count trailing truths

Body:
GolfSharp, 14 bytes

n=>n.V().O(F);


问:
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!

答:
Matlab, <s>84, 81.2</s> 79.1 bytes = 113 - 30%

```<code>function u=l(f,N,a,b);A=toeplitz([2,-1,(3:N)*0]);A([1,2,end-[1,0]])=eye(2);u=[a,f((1:N-2)/N)*(N-1)^2,b]/A;plot(u)
</code>```

Note that in this example the I use row vectors, this means that the matrix A is transposed. f is taken as a function handle, a,b are the left/right side Dirichlet contraints.

```<code>function u=l(f,N,a,b);
A=toeplitz([2,-1,(3:N)*0]);       % use the "toeplitz" builtin to generate the matrix
A([1,2,end-[1,0]])=eye(2);        % adjust first and last column of matrix
u=[a,f((1:N-2)/N)*(N-1)^2,b]/A;   % build right hand side (as row vector) and right mu
plot(u)                           % plot the solution
</code>```

For the example f = 10*x, u_L = 0 u_R = 1, N = 15 this results in:

Title: Solve the Laplace equation

Body:
Matlab, <s>84, 81.2</s> 79.1 bytes = 113 - 30%

function u=l(f,N,a,b);A=toeplitz([2,-1,(3:N)*0]);A([1,2,end-[1,0]])=eye(2);u=[a,f((1:N-2)/N)*(N-1)^2,b]/A;plot(u)

Note that in this example the I use row vectors, this means that the matrix A is transposed. f is taken as a function handle, a,b are the left/right side Dirichlet contraints.

function u=l(f,N,a,b);
A=toeplitz([2,-1,(3:N)*0]);       % use the "toeplitz" builtin to generate the matrix
A([1,2,end-[1,0]])=eye(2);        % adjust first and last column of matrix
u=[a,f((1:N-2)/N)*(N-1)^2,b]/A;   % build right hand side (as row vector) and right mu
plot(u)                           % plot the solution

For the example f = 10*x, u_L = 0 u_R = 1, N = 15 this results in:


问:
N-dimensional Circles!
Write a program that takes two numbers as its input. The first one is the number of dimensions - 0 for a dot, 1 for a straight line, 2 for a circle, 3 for a sphere. The second number is the radius of the object, or, if it's 1-dimensional, the number itself. Output 0 for 0 dimensions. The output is the length/area/volume of the object.

If we call the first number n, the second one r, and the output x, we get that:

for n = 0, x = 1

for n = 1, x = 2×r

for n = 2, x = r2×π

for n = 3, x = (4/3)×r3×π

and so on... if you want, though.

Notes:

Cases when one or both numbers are negative, or when the first number is not whole, don't need to be covered.

The program must not read from any file and the only input are those two numbers.

The output should use only numerals (e.g. not "14*pi"), and should be accurate to at least two decimal digits.

As for n = 0, you can output 0 if it makes the code shorter.

Extra swag for an answer covering even 4 and more-dimensional "spheres"!

It's code-golf, so the shortest answer in bytes wins!

Examples:

```<code> 1 1 -> 2

 2 3 -> 28,27

 3 1 -> 4,19

 3 4,5 -> 381,70

 1 9.379 -> 18.758

 0 48 -> 1
</code>```

答:
Lithp, 96 characters + extra swag

Line split in 2 for readability:

```<code>#N,R::((if (< N 2) ((? (!= 0 N) (* 2 R) 1)) ((/ (* (* (* (* (f (- N 2) R) 2)
        3.1416) R) R) N))))
</code>```

Thinking I need to upgrade my parser to require less spaces. Code size would be cut down nicely, especially in that ((/ (* (* (* (* section.

Usage:

```<code>% n-circle.lithp
(
    (def f #N,R::((if (< N 2) ((? (!= 0 N) (* 2 R) 1)) ((/ (* (* (* (* (f (- N 2) R) 2) 3.1416) R) R) N)))))
    (print (f 1 1))
    (print (f 2 3))
    (print (f 3 1))
    (print (f 3 4.5))
    (print (f 1 9.379))
    (print (f 0 48))
)

#./run.js n-circle.lithp
2
28.274333882308138
4.1887902047863905
381.7035074111598
18.758
1
</code>```

Thanks to Rudolf for shaving a few bytes off.

Title: N-dimensional Circles!

Body:
Lithp, 96 characters + extra swag

Line split in 2 for readability:

#N,R::((if (< N 2) ((? (!= 0 N) (* 2 R) 1)) ((/ (* (* (* (* (f (- N 2) R) 2)
        3.1416) R) R) N))))

Thinking I need to upgrade my parser to require less spaces. Code size would be cut down nicely, especially in that ((/ (* (* (* (* section.

Usage:

% n-circle.lithp
(
    (def f #N,R::((if (< N 2) ((? (!= 0 N) (* 2 R) 1)) ((/ (* (* (* (* (f (- N 2) R) 2) 3.1416) R) R) N)))))
    (print (f 1 1))
    (print (f 2 3))
    (print (f 3 1))
    (print (f 3 4.5))
    (print (f 1 9.379))
    (print (f 0 48))
)

#./run.js n-circle.lithp
2
28.274333882308138
4.1887902047863905
381.7035074111598
18.758
1

Thanks to Rudolf for shaving a few bytes off.


答:
C, <s>73</s> 63 bytes

g(){char a[99],x;for(;;){gets(a);if(*a)x=*a;else*a=x,puts(a);}}
```
<p>Only uses 1 buffer and a single char for handling the logic. If user inputs nothing, only the first char in the buffer gets overwritten by <code>'\0'</code>, in that case it gets restored from <code>x</code> and printed, otherwise copy the first letter into <code>x</code> for later use.</p>
<p>Previous code:</p>
<pre class="lang-c prettyprint-override"><code>main(){char a[99],b[99];for(;;){gets(a);if(*a)strcpy(b,a);else puts(b);}}
</code>```

Title: Wait... what was I going to say again?

Body:
I often forget what I wanted to say when the teacher calls on me to speak. Can you make me a tool to solve this?

Requirements:

The program must loop as follows:

First, take in input

If the input is empty, print the last stored question.

Otherwise, store the input as a question.

Notes:

The input will never be empty if there are no questions stored.

Clarification: The program does not need to store multiple questions. I originally wanted it to store multiple, but I changed it after many people misunderstood the question.

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

Body:
C, <s>73</s> 63 bytes

g(){char a[99],x;for(;;){gets(a);if(*a)x=*a;else*a=x,puts(a);}}

Only uses 1 buffer and a single char for handling the logic. If user inputs nothing, only the first char in the buffer gets overwritten by '\0', in that case it gets restored from x and printed, otherwise copy the first letter into x for later use.

Previous code:

main(){char a[99],b[99];for(;;){gets(a);if(*a)strcpy(b,a);else puts(b);}}


答:
APLX, 19 bytes

```<code>a←⍞⋄→(0=⍴a)/1⋄a⋄→1
</code>```

Explanation:

```<code>⍝ Note: the ⋄ symbols are statement separators, so I've replaced them here with newlines

a←⍞           ⍝ get an input string (⍞) and store it in variable a
→(0=⍴a)/1     ⍝ if the length of a (⍴a) is 0, goto (→) the start of this program (1)
a             ⍝ else, print a
→1            ⍝ goto the start of the program (1)
</code>```

Title: Wait... what was I going to say again?

Body:
APLX, 19 bytes

a←⍞⋄→(0=⍴a)/1⋄a⋄→1

Explanation:

⍝ Note: the ⋄ symbols are statement separators, so I've replaced them here with newlines

a←⍞           ⍝ get an input string (⍞) and store it in variable a
→(0=⍴a)/1     ⍝ if the length of a (⍴a) is 0, goto (→) the start of this program (1)
a             ⍝ else, print a
→1            ⍝ goto the start of the program (1)


问:
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:
Jelly, <s>13 12</s> 11 bytes

OBUZ;$S€ÆPẠ

TryItOnline! or all test cases

How?

OBUZ;$S€ÆPẠ - Main link: word                  e.g. ha!
O           - cast to ordinals                 e.g. [104,97,33]
 B          - convert to binary                e.g. [[1,1,0,1,0,0,0],[1,1,0,0,0,0,1],[1,0,0,0,0,1]]
  U         - reverse each entry (say "b")     e.g. [[0,0,0,1,0,1,1],[1,0,0,0,0,1,1],[1,0,0,0,0,1]]
     $      - last two links as a monad
   Z        - transpose                        e.g. [[0,1,1],[0,0,0],[0,0,0],[1,0,0],[0,0,0],[1,1,1],[1,1]]
    ;       - concatenate with "b"             e.g. [[0,1,1],[0,0,0],[0,0,0],[1,0,0],[0,0,0],[1,1,1],[1,1],[0,0,0,1,0,1,1],[1,0,0,0,0,1,1],[1,0,0,0,0,1]]
      S€    - sum €ach                         e.g. [2,0,0,1,0,3,2,3,3,2]
        ÆP  - is prime (1 if prime, 0 if not)  e.g. [1,0,0,0,0,1,1,1,1,1]
          Ạ - all truthy?                      e.g. 0


答:
Mathematica, 52.5 bytes (= 75 * (1 - 30%))

+0.7 bytes per @flawr 's comment.

```<code>ListPlot[{#,u@#}&/@Subdivide@#4/.NDSolve[-u''@x==#&&u@0==#2&&u@1==#3,u,x]]&
</code>```

This plots the output.

e.g.

```<code>ListPlot[ ... ]&[10 x, 0, 1, 15]
</code>```

Explanation

```<code>NDSolve[-u''@x==#&&u@0==#2&&u@1==#3,u,x]
</code>```

Solve for the function u.

```<code>Subdivide@#4
</code>```

Subdivide the interval [0,1] into N (4th input) parts.

```<code>{#,u@#}&/@ ...
</code>```

Map u to the output of Subdivide.

```<code>ListPlot[ ... ]
</code>```

Plot the final result.

Non-graphing solution: 58 bytes

```<code>u/@Subdivide@#4/.NDSolve[-u''@x==#&&u@0==#2&&u@1==#3,u,x]&
</code>```

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:
Mathematica, 52.5 bytes (= 75 * (1 - 30%))

+0.7 bytes per @flawr 's comment.

ListPlot[{#,u@#}&/@Subdivide@#4/.NDSolve[-u''@x==#&&u@0==#2&&u@1==#3,u,x]]&

This plots the output.

e.g.

ListPlot[ ... ]&[10 x, 0, 1, 15]

Explanation

NDSolve[-u''@x==#&&u@0==#2&&u@1==#3,u,x]

Solve for the function u.

Subdivide@#4

Subdivide the interval [0,1] into N (4th input) parts.

{#,u@#}&/@ ...

Map u to the output of Subdivide.

ListPlot[ ... ]

Plot the final result.

Non-graphing solution: 58 bytes

u/@Subdivide@#4/.NDSolve[-u''@x==#&&u@0==#2&&u@1==#3,u,x]&


答:
Swift 3, <s>100 99</s> 97 bytes

```<code>var a="/////",b="\\\\\\\\\\",c=""
(1...144).map{c+=a+b+($0%6<1 ?"\n":"")
$0%24<1 ?swap(&a,&b):()}
</code>```

Could save 1 byte if Swift print function did not add a newline by default.

Edit 1:

Saved 1 byte by changing the if to ternary

if(i%24<1){swap(&a,&b)} -> i%24<1 ?swap(&a,&b):()

Edit 2:

Changed from for to map over the CountableClosedRange

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:
Swift 3, <s>100 99</s> 97 bytes

var a="/////",b="\\\\\\\\\\",c=""
(1...144).map{c+=a+b+($0%6<1 ?"\n":"")
$0%24<1 ?swap(&a,&b):()}

Could save 1 byte if Swift print function did not add a newline by default.

Edit 1:

Saved 1 byte by changing the if to ternary

if(i%24<1){swap(&a,&b)} -> i%24<1 ?swap(&a,&b):()

Edit 2:

Changed from for to map over the CountableClosedRange


问:
Encode the backwards alphabet cipher
Given a string of text that contains lowercase letters, encode it as follows: (I will be using abcdef)

First, encode the alphabet cipher, but this time, 0-indexed. 000102030405

Reverse it. 504030201000

Loop through the string.

If the next two digits together are 25 or smaller, encode those two numbers. 5 04 03 02 01 00 0

Otherwise, encode one number. f e d c b a a

Join. fedcbaa

Test cases

```<code>abcdef                          fedcbaa
abcdefghijklmnopqrstuvwxyz      fyxwvucjsrqponmlktihgfedcbaa
helloworld                      dbromylloha
ppcg                            gcfpb
codegolf                        fboqedema
programmingpuzzlesandcodegolf   fboqedemddkiobpzuzqdscmkhqerpb
</code>```

Encoder (not golfed)

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

Title: Encode the backwards alphabet cipher

Body:
Perl, 73 + 2 = 75 bytes

Run with the -lp flag

s/./sprintf"%02d",-97+ord$&/eg;$_=reverse;s/2[0-5]|[01]?[0-9]/chr$&+97/eg


问:
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

```

答:
Python 3 / JavaScript, 83 chars

Saved 2 bytes thanks to @LevitatingLion

```<code>1//2;x=input();print(x+x[-2::-1]);"""
x=prompt();alert(x.slice(0,-x.length/2))//"""
</code>```

Python palindromizes, JavaScript depalindromizes.

I tried keeping more code constant between the two, but I couldn't figure out a good way to sneak .slice into Python. Here's an alternate method:

```<code>1//2;prompt=input,alert=print
x=prompt();1//2;x+=x[-2::-1]);"""
x=x.slice(0,-x.length/2))//"""
alert(x)
</code>```

Title: Palindrome polyglot

Body:
Python 3 / JavaScript, 83 chars

Saved 2 bytes thanks to @LevitatingLion

1//2;x=input();print(x+x[-2::-1]);"""
x=prompt();alert(x.slice(0,-x.length/2))//"""

Python palindromizes, JavaScript depalindromizes.

I tried keeping more code constant between the two, but I couldn't figure out a good way to sneak .slice into Python. Here's an alternate method:

1//2;prompt=input,alert=print
x=prompt();1//2;x+=x[-2::-1]);"""
x=x.slice(0,-x.length/2))//"""
alert(x)


Title: This is my pillow

Body:
Racket 156 bytes

(define g #t)(for((k 24))(for((i 12))(for((j 5))(display(if g "/""\\")))(set! g(if g #f #t)))
(when(= 0(modulo(add1 k)4))(set! g(if g #f #t)))(displayln""))

Ungolfed:

(define(f)
  (define g #t)
  (for ((k 24))
    (for ((i 12))
      (for ((j 5))
        (display (if g "/" "\\")))
      (set! g (if g #f #t)))
    (when (= 0 (modulo (add1 k) 4))
      (set! g (if g #f #t)))
    (displayln "")))

Testing:

(f)

Output:

/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////


答:
C90 (gcc), 46 bytes

r;main(c,v)int**v;{while(0<--c&*v[c])r++;c=r;}
```

Input is via command-line arguments (one integer per argument), output via exit code.

Try it online!

How it works

r is a global variable. Its type defaults to int and, being global, it value defaults to 0.

The function argument c defaults to int as well. It will hold the integer n + 1 for arrays of n Booleans; the first argument of main is always the path of the executable.

The function argument v is declared as int**. The actual type of v will be char**, but since we'll only examine the least significant bit of each argument to tell the characters 0 (code point 48) and 1 (code point 49) apart, this won't matter on little-endian machines.

The while loop decrements c and compares it to 0. Once c reaches 0, we'll break out of the loop. This is needed only if the array contains no 0's.

As long as 0<--c returns 1, we takes the cth command-line argument (v[c]) and extract its first character with by dereferencing the pointer (*). We take the bitwise AND of the Boolean 0<--c and the code point of the character (and three garbage bytes that follow it), so the condition will return 0 once a 0 is encountered, breaking out of the loop.

In the remaining case, while the command-line arguments are 1, r++ increments r by 1, thus counting the number of trailing 1's.

Finally, c=r stores the computed value of r in c. With default settings, the compiler optimize and remove the assignment; it actually generates the movl %eax, -4(%rbp) instruction. Since ret returns the value of the EAX register, this generates the desired output.

Note that this code does not work with C99, which returns 0 from main if the end of main is reached.

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:
C90 (gcc), 46 bytes

r;main(c,v)int**v;{while(0<--c&*v[c])r++;c=r;}

Input is via command-line arguments (one integer per argument), output via exit code.

Try it online!

How it works

r is a global variable. Its type defaults to int and, being global, it value defaults to 0.

The function argument c defaults to int as well. It will hold the integer n + 1 for arrays of n Booleans; the first argument of main is always the path of the executable.

The function argument v is declared as int**. The actual type of v will be char**, but since we'll only examine the least significant bit of each argument to tell the characters 0 (code point 48) and 1 (code point 49) apart, this won't matter on little-endian machines.

The while loop decrements c and compares it to 0. Once c reaches 0, we'll break out of the loop. This is needed only if the array contains no 0's.

As long as 0<--c returns 1, we takes the cth command-line argument (v[c]) and extract its first character with by dereferencing the pointer (*). We take the bitwise AND of the Boolean 0<--c and the code point of the character (and three garbage bytes that follow it), so the condition will return 0 once a 0 is encountered, breaking out of the loop.

In the remaining case, while the command-line arguments are 1, r++ increments r by 1, thus counting the number of trailing 1's.

Finally, c=r stores the computed value of r in c. With default settings, the compiler optimize and remove the assignment; it actually generates the movl %eax, -4(%rbp) instruction. Since ret returns the value of the EAX register, this generates the desired output.

Note that this code does not work with C99, which returns 0 from main if the end of main is reached.


问:
Generate a Markdown Template for your Post
Your task is simple: Write a program (or function) that takes no input and outputs something like this:

```<code>## *name*, *length* bytes
    *code*
</code>```

Where *name* is the name of the language you are using, *length* is the number of bytes in your code, and *code* is your program's source code. If *code* contains multiple lines, it have four spaces before each line.

Here's a 124-byte example implementation in Python 3:

```<code>s = "## Python 3, 124 bytes{2}    s = {1}{0}{1}{2}print(s.format(s,chr(34),chr(10)))"
print(s.format(s,chr(34),chr(10)))
</code>```

The output is:

```<code>## Python 3, 124 bytes
    s = "## Python 3, 124 bytes{2}    s = {1}{0}{1}{2}print(s.format(s,chr(34),chr(10)))"
    print(s.format(s,chr(34),chr(10)))
</code>```

Which in Markdown is:

Python 3, 124 bytes

```<code>s = "## Python 3, 124 bytes{2}    s = {1}{0}{1}{2}print(s.format(s,chr(34),chr(10)))"
print(s.format(s,chr(34),chr(10)))
</code>```

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

答:
RProgN 2, 28 Bytes

```<code>«"  %s"F"#RProgN 2, 28 Bytes"
</code>```

Body:
RProgN 2, 28 Bytes

«"  %s"F"#RProgN 2, 28 Bytes"


问:
Given a Diagram, Find X

Find X

I was inspired by math questions in which one is asked to "Find X" for a given shape. Originally, I was just going to have the challenge be to print the x and y location of the character 'x' in a String. But I supposed that would be too simple. So I considered the context they were normally in, and decided finding the length of a Line next to the x just seemed appropriate.

Given a string input containing a Diagram of ascii 'lines' as well as a single 'x' and potentially junk characters, print the length of the only line that has an 'x' directly adjecent to it.

Examples

Input:

```<code>|
|
|x
|
|
</code>```

Ouput:

```<code>5
</code>```

Input:

```<code>|\
| \x
|  \
|___\
</code>```

Output:

```<code>4
</code>```

Input:

```<code>Diagram of a Wobbly Line:
IRRELEVANTTEXT____
____     ____/
    \___/ X ;)
      x
</code>```

Output:

```<code>3
</code>```

Input:

```<code>  ______________
 / ____________ \
 |/ __________ \|
 ||/ ________ \||
 |||/ ______ \|||
 ||||/      \||||
 |||||/  x  |||||
 |||||\_____/||||
 ||||\_______/|||
 |||\_________/||
 ||\___________/|
  \_____________/
</code>```

Output:

```<code>5
</code>```

Notes

The Valid line characters are \/_|

\ connects the top left and bottom right of itself.

/ connects the top right and bottom left of itself.

_ connects the left and right of itself

| connects the top and bottom of itself

A line will always be straight, and only consist of one of the line characters repeated n times.

The x will always be lowercase, and it will always be the only one in the diagram.

Adjecent refers to the x being exactly one character above, below, or besides.

The x will always be next to exactly one Line.

Tabs will never appear in the input.

Input and Output may be any acceptable format.

This is Code Golf, so Shortest Code Wins!

HAVE FUN. DO IT. ENJOY YOURSELF.

Reference Implementation

答:
Python 3, <s>428</s> <s>408</s> <s>385</s> 378 bytes

Working, but has a ton of potential to be golfed. I'm a bit rusty.

Assumes input is padded with spaces to make a rectangle.

EDIT: Thanks to @Artyer for 23 byte savings!

EDIT2: Wow I completely missed a 6 byte savings. Saved 1 more by swapping sides of an equals check.

*i,=map(list,input().split('\n'))
r=c=s=q=e=w=0
o=lambda y,x:len(i[0])>x>=0<=y<len(i)
d='\/_|'
for l in i:
 if'x'in l:r=i.index(l);c=l.index('x')
for a,b in(1,0),(0,1),(-1,0),(0,-1):
 y,x=r+a,c+b;f=o(y,x)and i[y][x]
 if f in d:s=f;w=d.index(f);q,e=y,x
k=lambda y,x,g=[1,1,0,1][w],v=[1,-1,1,0][w]:o(y,x)and s==i[y][x]and(exec('i[y][x]=0')or 1+k(y+g,x+v)+k(y-g,x-v))
print(k(q,e))
```

<p>Expanded version with explanation:</p>

<pre class="lang-py prettyprint-override"><code>inputtt='''  ______________.
 / ____________ \
 |/ __________ \|
 ||/ ________ \||
 |||/ ______ \|||
 ||||/      \||||
 |||||/  x  |||||
 |||||\_____/||||
 ||||\_______/|||
 |||\_________/||
 ||\___________/|
  \_____________/'''

# First, we get the input from STDIN and make it
# into a doubly-nested array

*input_text,=map(list,inputtt.split('\n'))

# A pretty cool Python trick to assign 0 to
# mulitple variables at once.

row=col=line_letter=line_row=line_col=line_char_index=0

# A function to check if a certian row and col is
# in bounds or not. Uses python's comparator chaining

in_bounds=lambda y,x:len(input_text[0])>x>=0<=y<len(input_text)

# A string to store all the line characters.
chars='\/_|'

# Search for the x
for line in input_text:

 # If this line contains the x...
 if'x'in line:

     # Mark the row and column
     row=input_text.index(line);col=line.index('x')

# For each direction...
for down,right in(1,0),(0,1),(-1,0),(0,-1):

 # Move in that direction
 y,x=row+down,col+right

 # If the position is in bounds, mark the char at that position
 line_found=in_bounds(y,x)and input_text[y][x]

 # If the char is a line char, set all the variables saying we found it
 if line_found in chars:
  line_letter=line_found
  line_char_index=chars.index(line_found)
  line_row,line_col=y,x

recur=lambda y,x,\
       # Find which directions we are supposed to recur in based on the line char
       g=[1,1,0,1][line_char_index],v=[1,-1,1,0][line_char_index]:\
       # If the char is in bounds and we are still on the line...
       in_bounds(y,x)and input_text[y][x]==line_letter and\
       # Set the spot to a 0, so we won't go back, increment,
       # and recur in both directions
       (exec('i[y][x]=0')or 1+recur(y+g,x+v)+recur(y-g,x-v))

# Finally, print the answer
print(recur(line_row,line_col))
</code>```

Title: Given a Diagram, Find X

Body:
Python 3, <s>428</s> <s>408</s> <s>385</s> 378 bytes

Working, but has a ton of potential to be golfed. I'm a bit rusty.

Assumes input is padded with spaces to make a rectangle.

EDIT: Thanks to @Artyer for 23 byte savings!

EDIT2: Wow I completely missed a 6 byte savings. Saved 1 more by swapping sides of an equals check.

*i,=map(list,input().split('\n'))
r=c=s=q=e=w=0
o=lambda y,x:len(i[0])>x>=0<=y<len(i)
d='\/_|'
for l in i:
 if'x'in l:r=i.index(l);c=l.index('x')
for a,b in(1,0),(0,1),(-1,0),(0,-1):
 y,x=r+a,c+b;f=o(y,x)and i[y][x]
 if f in d:s=f;w=d.index(f);q,e=y,x
k=lambda y,x,g=[1,1,0,1][w],v=[1,-1,1,0][w]:o(y,x)and s==i[y][x]and(exec('i[y][x]=0')or 1+k(y+g,x+v)+k(y-g,x-v))
print(k(q,e))

Expanded version with explanation:

inputtt='''  ______________.
 / ____________ \
 |/ __________ \|
 ||/ ________ \||
 |||/ ______ \|||
 ||||/      \||||
 |||||/  x  |||||
 |||||\_____/||||
 ||||\_______/|||
 |||\_________/||
 ||\___________/|
  \_____________/'''

# First, we get the input from STDIN and make it
# into a doubly-nested array

*input_text,=map(list,inputtt.split('\n'))

# A pretty cool Python trick to assign 0 to
# mulitple variables at once.

row=col=line_letter=line_row=line_col=line_char_index=0

# A function to check if a certian row and col is
# in bounds or not. Uses python's comparator chaining

in_bounds=lambda y,x:len(input_text[0])>x>=0<=y<len(input_text)

# A string to store all the line characters.
chars='\/_|'

# Search for the x
for line in input_text:

 # If this line contains the x...
 if'x'in line:

     # Mark the row and column
     row=input_text.index(line);col=line.index('x')

# For each direction...
for down,right in(1,0),(0,1),(-1,0),(0,-1):

 # Move in that direction
 y,x=row+down,col+right

 # If the position is in bounds, mark the char at that position
 line_found=in_bounds(y,x)and input_text[y][x]

 # If the char is a line char, set all the variables saying we found it
 if line_found in chars:
  line_letter=line_found
  line_char_index=chars.index(line_found)
  line_row,line_col=y,x

recur=lambda y,x,\
       # Find which directions we are supposed to recur in based on the line char
       g=[1,1,0,1][line_char_index],v=[1,-1,1,0][line_char_index]:\
       # If the char is in bounds and we are still on the line...
       in_bounds(y,x)and input_text[y][x]==line_letter and\
       # Set the spot to a 0, so we won't go back, increment,
       # and recur in both directions
       (exec('i[y][x]=0')or 1+recur(y+g,x+v)+recur(y-g,x-v))

# Finally, print the answer
print(recur(line_row,line_col))


问:
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>```

答:
Brainfuck, 283 bytes

```<code>,[[<[>-[>>>-<<<----[----[>+<------[>-<------[<[-]>>>>[-]->>[-]<<<<<-]]]]]>[>>>>+
<<<<-]>>+<[>[>+<-]>>[>+<-]<<<-]<,<<[>>>+<<<-]>]>+[<+>[-<<]>[[-]+++++[<++++++>-]<
+<]>>>]<]>>[-]>+>>+[[-]>[<+>-[<+>-[<+>-[<+>[-]]]]]<<<]>->[>+<-[[>+<-]>>+>]>[+>--
--[->]]]+[-<+]>>+++++++++++++[>+++++<-]>.,]
</code>```

Formatted:

```<code>,
[
  [
    <
    [
      >-
      [
        not a
        >>>-<<<
        ----
        [
          not e
          ----
          [
            not i
            >+<
            ------
            [
              not o
              >-<
              ------
              [
                consonant
                <[-]>
                >>>[-]->>[-]<<<<<-
              ]
            ]
          ]
        ]
      ]
      >[>>>>+<<<<-]> >+<
      [
        prev was vowel
        >[>+<-]>>[>+<-]<<<-
      ]
      <,<<[>>>+<<<-]
      >
    ]
    >+
    [
      <+>[-<<]
      >[[-]+++++[<++++++>-]<+<]
      >>>
    ]
    <
  ]
  >>[-]>+>>+
  [
    [-]
    >[<+>-[<+>-[<+>-[<+>[-]]]]]<
    <<
  ]
  >->
  [
    >+<-
    [
      [>+<-]
      >>+>
    ]
    >
    [
      +>----[->]
    ]
  ]
  +[-<+]
  >>+++++++++++++[>+++++<-]
  >.,
]
</code>```

This works with or without a trailing newline in the input.

Try it online.

Each character is processed mod 32 (with control flow such that the code implementing the mod operation only occurs once in the program). This enables case insensitivity, as well as collapsing the space character and EOF into a single case. A trailing newline is treated the same as J, which doesn't affect the output.

Sketch of memory layout:

0 x C c y a A b B

where c is the input character, C is the char mod 32, x is whether it is a vowel, y is whether the previous char was a vowel, A and B are the counts of valid (next to vowels) a and o chars respectively, and a and b are their respective buffers that get copied or cleared depending on whether there is an adjacent vowel.

When a space or EOF is reached, some juggling is done to reduce counts greater than 4 and to skip the letter J, and then the decoded character is printed.

Title: Decode Baby-talk!

Body:
Brainfuck, 283 bytes

,[[<[>-[>>>-<<<----[----[>+<------[>-<------[<[-]>>>>[-]->>[-]<<<<<-]]]]]>[>>>>+
<<<<-]>>+<[>[>+<-]>>[>+<-]<<<-]<,<<[>>>+<<<-]>]>+[<+>[-<<]>[[-]+++++[<++++++>-]<
+<]>>>]<]>>[-]>+>>+[[-]>[<+>-[<+>-[<+>-[<+>[-]]]]]<<<]>->[>+<-[[>+<-]>>+>]>[+>--
--[->]]]+[-<+]>>+++++++++++++[>+++++<-]>.,]

Formatted:

,
[
  [
    <
    [
      >-
      [
        not a
        >>>-<<<
        ----
        [
          not e
          ----
          [
            not i
            >+<
            ------
            [
              not o
              >-<
              ------
              [
                consonant
                <[-]>
                >>>[-]->>[-]<<<<<-
              ]
            ]
          ]
        ]
      ]
      >[>>>>+<<<<-]> >+<
      [
        prev was vowel
        >[>+<-]>>[>+<-]<<<-
      ]
      <,<<[>>>+<<<-]
      >
    ]
    >+
    [
      <+>[-<<]
      >[[-]+++++[<++++++>-]<+<]
      >>>
    ]
    <
  ]
  >>[-]>+>>+
  [
    [-]
    >[<+>-[<+>-[<+>-[<+>[-]]]]]<
    <<
  ]
  >->
  [
    >+<-
    [
      [>+<-]
      >>+>
    ]
    >
    [
      +>----[->]
    ]
  ]
  +[-<+]
  >>+++++++++++++[>+++++<-]
  >.,
]

This works with or without a trailing newline in the input.

<a href="http://brainfuck.tryitonline.net/#code=LFtbPFs-LVs-Pj4tPDw8LS0tLVstLS0tWz4rPC0tLS0tLVs-LTwtLS0tLS1bPFstXT4-Pj5bLV0tPj5bLV08PDw8PC1dXV1dXT5bPj4-Pis8PDw8LV0-Pis8Wz5bPis8LV0-Pls-KzwtXTw8PC1dPCw8PFs-Pj4rPDw8LV0-XT4rWzwrPlstPDxdPltbLV0rKysrK1s8KysrKysrPi1dPCs8XT4-Pl08XT4-Wy1dPis-PitbWy1dPls8Kz4tWzwrPi1bPCs-LVs8Kz5bLV1dXV1dPDw8XT4tPls-KzwtW1s-KzwtXT4-Kz5dPlsrPi0tLS1bLT5dXV0rWy08K10-PisrKysrKysrKysrKytbPisrKysrPC1dPi4sXQ&input=R0xPT0cgS0FLQUFPT08gQVJHT09PIE9PT09PR1VHVVUgb2FrYSBwb29vcGFhIGdhYXUgYXVndQ" rel="nofollow noreferrer">Try it online.

Each character is processed mod 32 (with control flow such that the code implementing the mod operation only occurs once in the program). This enables case insensitivity, as well as collapsing the space character and EOF into a single case. A trailing newline is treated the same as J, which doesn't affect the output.

Sketch of memory layout:

0 x C c y a A b B

where c is the input character, C is the char mod 32, x is whether it is a vowel, y is whether the previous char was a vowel, A and B are the counts of valid (next to vowels) a and o chars respectively, and a and b are their respective buffers that get copied or cleared depending on whether there is an adjacent vowel.

When a space or EOF is reached, some juggling is done to reduce counts greater than 4 and to skip the letter J, and then the decoded character is printed.


Title: This is my pillow

Body:
Java 7, 148 bytes

String c(){String r,z,y=z=r="",p="/////\\\\\\\\\\",q="\\\\\\\\\\/////";int i=0;for(;i++<6;y+=p,z+=q);for(i=0;i<24;r+=(i++%8<4?y:z)+"\n");}return r;}

Ungolfed & test code:

Try it here.

class M{
  static String c() {
    String r, z, y = z = r = "",
           p = "/////\\\\\\\\\\",
           q = "\\\\\\\\\\/////";
    int i = 0;
    for(; i++ < 6; y += p, z += q);
    for(i = 0; i < 24; r += (i++%8 < 4 ? y : z)+"\n");
    return r;
  }

  public static void main(String[] a){
    System.out.println(c());
  }
}

Output:

/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////
\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////


Title: The nth numerator

Body:
You can create a list of all rationals 0 < r ≤ 1 by listing them ordered first by denominator and then by numerator:

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

Note that we skip any rational number that already occurred before. E.g. 2/4 is skipped because we already listed 1/2.

In this challenge we're interested in the numerators only. Looking at the list above, write a function or program taking a positive integer n that returns the nth numerator from the list.

Testcases:

```<code>1 -> 1
2 -> 1
3 -> 1
4 -> 2
5 -> 1
6 -> 3
7 -> 1
8 -> 2
9 -> 3
50 -> 4
80 -> 15
</code>```

Body:
JavaScript (ES6), 76

x=>eval("for(g=(a,b)=>b?g(b,a%b):a,d=n=0;x;g(n,d)-1||--x)n=++n>d?(++d,1):n")

Less golfed

x=>{
  g=(a,b) => b ? g(b,a%b) : a; // gcd
  for (d=n=0; x; )
  {
     ++n;
     if (n > d)
     {
        ++d;
        n=1;
     }
     if (g(n,d) == 1) // if the fraction is irreducible
        --x;
  }
  return n
}

Test

f=
x=>eval("for(g=(a,b)=>b?g(b,a%b):a,d=n=0;x;g(n,d)-1||--x)n=++n>d?(d++,1):n")

;`1 -> 1
2 -> 1
3 -> 1
4 -> 2
5 -> 1
6 -> 3
7 -> 1
8 -> 2
9 -> 3
50 -> 4
80 -> 15`.split`\n`.forEach(
  r=>{
    var [a,k]=r.match(/\d+/g),r=f(a)
    console.log(r==k?'OK':'KO',a,r)
  }
)


问:
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>```

Title: Index of a multidimensional array

Body:
Perl, 71 bytes

sub{$s+=$_[1][-$_]*($p*=$_[0][1-$_])for($p=$_[0][$s=0]=1)..@{$_[0]};$s}

Ungolfed:

sub {
    my $s = 0;
    my $p = 1;

    $_[0]->[0] = 1;
    for (1 .. @{$_[1]}) {
        $p *= $_[0]->[1 - $_];
        $s += $_[1]->[-$_] * $p;
    }

    return $s;
}


答:
PHP, <s>105</s> <s>97</s> <s>94 93</s> 87 bytes

```<code>for(;$i<2**$c=count($a=$argv)-$p=1;$i+=print-abs($p))for(;$c;)$p*=$a[$c--]-!($i>>$c&1);
</code>```

Run like this:

```<code>php -r 'for(;$i<2**$c=count($a=$argv)-$p=1;$i+=print-abs($p))for(;$c;)$p*=$a[$c--]-!($i>>$c&1);' -- .55 .67 .13 2>/dev/null;echo
> -0.129195-0.157905-0.262305-0.320595-0.019305-0.023595-0.039195-0.047905
</code>```

Note that the output is little endian:

```<code>[0,0,0]
[1,0,0]
[0,1,0]
[1,1,0]
[0,0,1]
[1,0,1]
[0,1,1]
[1,1,1]
</code>```

Explanation

```<code>for(
  ;
  $i<2**$c=                 # Iterate over possible combinations: 2^c,
    count($a=$argv)-$p=1;   #   where c is input length -p (set p to 1)
  $i+=print-abs($p)         # Increment i and print product after each
)                           #   iteration, dash separated
  for(
     ;
     $c;                    # Iterate over input ($c..0)
  )
    $p*=                    # Multiply the product by difference between:
      $a[$c--]-             # - The $c-th item of the input.
      !($i>>$c&1);          # - The $c-th bit of `$i`, negated (1 or 0)
</code>```

Tweaks

Saved 8 bytes by using binary logic to get bit instead of converting to string

Saved a byte by combining the resetting of $p to 1 with computation of $c

Saved a byte by adding the result of print (1) to $i instead of incrementing

Saved a byte by using underscore as output delimiter

Saved a byte by using minus sign as delimiter (there are no negative chances).

Saved 6 bytes by using $c instead of $$i

Body:
Given a sequences of events with probabilities between 0.0 and 1.0, generate and derive the probability of each combination occurring. You may presume that a sequence of numbers is provided in whatever construct your chosen language provides.

Here's an example; you may presume that the length of the sequence's combinations fit into memory:

```<code>{ 0.55, 0.67, 0.13 }
</code>```

The program shall print each combination and the associated probability of that sequence occurring. A 1 shall denote that the event in that index of the input sequence occurred and a 0 shall denote that that event did not occur. The desired output is below (I don't care about printing the work, that's just for informational purposes of the algorithm):

```<code>[0,0,0] = (1 - 0.55) * (1-0.67) * (1-0.13) = 0.129195
[0,0,1] = (1 - 0.55) * (1-0.67) * (0.13)   = 0.019305
[0,1,0] = (1 - 0.55) * (0.67)   * (1-0.13) = 0.262305
[0,1,1] = (1 - 0.55) * (0.67)   * (0.13)   = 0.039195
[1,0,0] = (0.55)     * (1-0.67) * (1-0.13) = 0.157905
[1,0,1] = (0.55)     * (1-0.67) * (0.13)   = 0.023595
[1,1,0] = (0.55)     * (0.67)   * (1-0.13) = 0.320595
[1,1,1] = (0.55)     * (0.67)   * (0.13)   = 0.047905
</code>```

This problem is tangentially related to calculating a "Cartesian product".

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

Body:
PHP, <s>105</s> <s>97</s> <s>94 93</s> 87 bytes

for(;$i<2**$c=count($a=$argv)-$p=1;$i+=print-abs($p))for(;$c;)$p*=$a[$c--]-!($i>>$c&1);

Run like this:

php -r 'for(;$i<2**$c=count($a=$argv)-$p=1;$i+=print-abs($p))for(;$c;)$p*=$a[$c--]-!($i>>$c&1);' -- .55 .67 .13 2>/dev/null;echo
> -0.129195-0.157905-0.262305-0.320595-0.019305-0.023595-0.039195-0.047905

Note that the output is little endian:

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

Explanation

for(
  ;
  $i<2**$c=                 # Iterate over possible combinations: 2^c,
    count($a=$argv)-$p=1;   #   where c is input length -p (set p to 1)
  $i+=print-abs($p)         # Increment i and print product after each
)                           #   iteration, dash separated
  for(
     ;
     $c;                    # Iterate over input ($c..0)
  )
    $p*=                    # Multiply the product by difference between:
      $a[$c--]-             # - The $c-th item of the input.
      !($i>>$c&1);          # - The $c-th bit of `$i`, negated (1 or 0)

Tweaks

Saved 8 bytes by using binary logic to get bit instead of converting to string

Saved a byte by combining the resetting of $p to 1 with computation of $c

Saved a byte by adding the result of print (1) to $i instead of incrementing

Saved a byte by using underscore as output delimiter

Saved a byte by using minus sign as delimiter (there are no negative chances).

Saved 6 bytes by using $c instead of $$i


答:
ABCR, 14 bytes

```<code>c7iA)7a!xcx!Bp
</code>```

Accepts the formatting [0,1,0,1,0, where any non-numeric character can be replaced with any other non-numeric character.  Empty input is the empty list.

Explanation:  Every 7 input number i is queued up A; every "0" input number (or rather, non-"1") )7 will pop from the queue until it's empty 7a!x; before another input number is queued, a delimiter character is grabbed cx to check for the end of queue.  After all the integers are grabbed, !Bp prints the length of the queue of input numbers (which will be all the trailing "1" values.)

Title: Count trailing truths

Body:
ABCR, 14 bytes

c7iA)7a!xcx!Bp

Accepts the formatting [0,1,0,1,0, where any non-numeric character can be replaced with any other non-numeric character.  Empty input is the empty list.

Explanation:  Every 7 input number i is queued up A; every "0" input number (or rather, non-"1") )7 will pop from the queue until it's empty 7a!x; before another input number is queued, a delimiter character is grabbed cx to check for the end of queue.  After all the integers are grabbed, !Bp prints the length of the queue of input numbers (which will be all the trailing "1" values.)


答:
Java 7, 62 bytes

```<code>int c(boolean[]a){int r=0;for(boolean b:a)r=b?r+1:0;return r;}
</code>```

Ungolfed & test code:

Try it here.

```<code>class M{
  static int c(boolean[] a){
    int r = 0;
    for (boolean b : a){
      r = b ? r+1 : 0;
    }
    return r;
  }

  public static void main(String[] a){
    System.out.print(c(new boolean[]{}) + ", ");
    System.out.print(c(new boolean[]{ false }) + ", ");
    System.out.print(c(new boolean[]{ true }) + ", ");
    System.out.print(c(new boolean[]{ false, true, true, false, false }) + ", ");
    System.out.print(c(new boolean[]{ true, true, true, false, true }) + ", ");
    System.out.print(c(new boolean[]{ true, true, false, true, true }) + ", ");
    System.out.print(c(new boolean[]{ false, false, true, true, true }) + ", ");
    System.out.print(c(new boolean[]{ true, true, true, true, true, true }));
  }
}
</code>```

Output:

```<code>0, 0, 1, 0, 1, 2, 3, 6
</code>```

Title: Count trailing truths

Body:
Java 7, 62 bytes

int c(boolean[]a){int r=0;for(boolean b:a)r=b?r+1:0;return r;}

Ungolfed & test code:

Try it here.

class M{
  static int c(boolean[] a){
    int r = 0;
    for (boolean b : a){
      r = b ? r+1 : 0;
    }
    return r;
  }

  public static void main(String[] a){
    System.out.print(c(new boolean[]{}) + ", ");
    System.out.print(c(new boolean[]{ false }) + ", ");
    System.out.print(c(new boolean[]{ true }) + ", ");
    System.out.print(c(new boolean[]{ false, true, true, false, false }) + ", ");
    System.out.print(c(new boolean[]{ true, true, true, false, true }) + ", ");
    System.out.print(c(new boolean[]{ true, true, false, true, true }) + ", ");
    System.out.print(c(new boolean[]{ false, false, true, true, true }) + ", ");
    System.out.print(c(new boolean[]{ true, true, true, true, true, true }));
  }
}

Output:

0, 0, 1, 0, 1, 2, 3, 6


答:
Clojure, 85 bytes

```<code>#(if(= 1 %)1(numerator(nth(distinct(for[i(range)j(range 1(inc i))](/ j i)))(dec %))))
</code>```

Uses list comprehension to generate list of all rationals, then filters it to get only distinct ones. Takes nth item of the list and returns its numerator. Also separate condition is needed for the first element because Clojure isn't able to take numerator of an integer. (for whatever reason considering an integer to be not Rational – https://goo.gl/XETLo2)

See it online – https://ideone.com/8gNZEB

Title: The nth numerator

Body:
Clojure, 85 bytes

#(if(= 1 %)1(numerator(nth(distinct(for[i(range)j(range 1(inc i))](/ j i)))(dec %))))

Uses list comprehension to generate list of all rationals, then filters it to get only distinct ones. Takes nth item of the list and returns its numerator. Also separate condition is needed for the first element because Clojure isn't able to take numerator of an integer. (for whatever reason considering an integer to be not Rational – https://goo.gl/XETLo2)

See it online – https://ideone.com/8gNZEB


问:
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>```

Title: Fizz Buzz for Turtles

Body:
Python 2, <s>379</s> <s>338</s> 326 bytes

Takes input as two numbers, separated by a comma. Eg. 4,5 or (4,5)

d=x=y=i=q=Q=e=E=0
p={}
f,b=input()
while(x,y)not in p:
 i+=1;l,r=i%b<1,i%f<1;d=(d+r-l)%4;p[x,y]=[[`i`,'F'][r],' F'[r]+'B'][l].rjust(2);q=min(q,x);Q=max(Q,x);e=min(e,y);E=max(E,y)
 if d%2:x+=(d==1)*2-1
 else:y+=(d!=2)*2-1
h,w=E-e+1,Q-q+1
A=[h*['  ']for x in' '*w]
for x,y in p:A[x-q][y-e]=p[x,y]
print'\n'.join(map(' '.join,A))

Version that works if path is longer than 99, <s>384</s> <s>343</s> 330 bytes

Shows 2 significant digits.

d=x=y=i=q=Q=e=E=0
p={}
f,b=input()
while(x,y)not in p:
 i+=1;l,r=i%b<1,i%f<1;d=(d+r-l)%4;p[x,y]=[[`i%100`,'F'][r],' F'[r]+'B'][l].rjust(2);q=min(q,x);Q=max(Q,x);e=min(e,y);E=max(E,y)
 if d%2:x+=(d==1)*2-1
 else:y+=(d!=2)*2-1
h,w=E-e+1,Q-q+1
A=[h*['  ']for x in' '*w]
for x,y in p:A[x-q][y-e]=p[x,y]
print'\n'.join(map(' '.join,A))

Examples:

input=(4,16)

 F 21 22 23  F
19          25
18          26
17          27
FB  1  2  3  F
15           5
14           6
13           7
 F 11 10  9  F

input=(6,7) (truncating version)

                                              F 63 64 65 66 67 FB  1  2  3  4  5  F
                               F 57 58 59 60  B                                   B  8  9 10 11  F
                              55                                                                13
                   F 51 52 53  B                                                                 B 15 16 17  F
                  49                                                                                19
                  48                                                                                20
          F 45 46  B                                                                                B 22 23  F
         43                                                                                25
         42                                                                                26
         41                                                                                27
    F 39  B                                                                                B 29  F
   37                                                                                31
   36                                                                                32
   35                                                                                33
   34                                                                                34
 F  B                                                                                B  F
31                                                                                37
30                                                                                38
29                                                                                39
28                                                                                40
27                                                                                41
FB                                                                                FB
25                                                                                43
24                                                                                44
23                                                                                45
22                                                                                46
21                                                                                47
 F  B                                                                                B  F
   18                                                                                50
   17                                                                                51
   16                                                                                52
   15                                                                                53
    F 13  B                                                                                B 55  F
         11                                                                                57
         10                                                                                58
         09                                                                                59
          F 07 06  B                                                                                B 62 61  F
                  04                                                                                64
                  03                                                                                65
                   F 01 00 99  B                                                                 B 69 68 67  F
                              97                                                                71
                               F 95 94 93 92  B                                   B 76 75 74 73  F
                                              F 89 88 87 86 85 FB 83 82 81 80 79  F

@Edit: Thanks to Jonathan Allan, Copper, and shooqie for savings me a bunch of bytes.


答:
Java 7, <s>189</s> <s>187</s> 178 bytes..

```<code>class M{public static void main(String[]a){String s="",x;do{x=new java.util.Scanner(System.in).nextLine();if(x.isEmpty())System.out.println(s);else s=x;}while(1>0);}}
</code>```

-9 bytes by using new java.util.Scanner directly, thanks to @cliffroot.

Probably the first time I used a do-while in a codegolf challenge..

When functions are allowed instead of programs, it's 135 bytes (still many times more than most other answers..)

Title: Wait... what was I going to say again?

Body:
I often forget what I wanted to say when the teacher calls on me to speak. Can you make me a tool to solve this?

Requirements:

The program must loop as follows:

First, take in input

If the input is empty, print the last stored question.

Otherwise, store the input as a question.

Notes:

The input will never be empty if there are no questions stored.

Clarification: The program does not need to store multiple questions. I originally wanted it to store multiple, but I changed it after many people misunderstood the question.

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

Body:
Java 7, <s>189</s> <s>187</s> 178 bytes..

class M{public static void main(String[]a){String s="",x;do{x=new java.util.Scanner(System.in).nextLine();if(x.isEmpty())System.out.println(s);else s=x;}while(1>0);}}

-9 bytes by using new java.util.Scanner directly, thanks to @cliffroot.

Probably the first time I used a do-while in a codegolf challenge..

When functions are allowed instead of programs, it's 135 bytes (still many times more than most other answers..)