答:
Scala, 41 bytes

```<code>def?(n:Int,p:Int)=n-(1 to p).map{n+_}.sum
</code>```

Testing code:

```<code>println(?(2,3))
println(?(100,5))
println(?(42,0))
println(?(0,3))
println(?(0,0))

// Output
-10
-415
42
-6
0
</code>```

Title: Subtract the next numbers

Body:
Description

Subtract the next P numbers from a N number. The next number of N is N + 1.

Look at the examples to get what I mean.

Examples:

```<code>Input: N=2,P=3
Calculate: n - (n+1) - (n+2) - (n+3)     //Ending with 3, because P=3
Calculate: 2 -  2+1  -  2+2  - 2+3       //Replacing N with 2 from Input
Calculate: 2 -  3    -  4    - 5
Output: -10

Input: N=100,P=5
Calculate: n - (n+1) - (n+2) - (n+3) - (n+4) - (n+5)
Calculate: 100-  101 -  102  -  103  -  104  - 105
Output: -415

Input: N=42,P=0
Calculate: n
Calculate: 42
Output: 42

Input: N=0,P=3
Calculate: n - (n+1) - (n+2) - (n+3)
Calculate: 0 -  1    -  2    -  3
Output: -6

Input: N=0,P=0
Calulate: n
Calculate: 0
Output: 0
</code>```

Input:

N: Integer, positive, negative or 0

P: Integer, positive or 0, not negative

Output:

Integer or String, leading 0 allowed, trailing newline allowed

Rules:

No loopholes

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

Input and Output must be as described

Body:
Scala, 41 bytes

def?(n:Int,p:Int)=n-(1 to p).map{n+_}.sum

Testing code:

println(?(2,3))
println(?(100,5))
println(?(42,0))
println(?(0,3))
println(?(0,0))

// Output
-10
-415
42
-6
0


问:
Is this a Smith number?

Challenge description

A Smith number is a composite number whose sum of digits is equal to the sum of sums of digits of its prime factors. Given an integer N, determine if it's a Smith number or not.

The first few Smith numbers are 4, 22, 27, 58, 85, 94, 121, 166, 202, 265, 274, 319, 346, 355, 378, 382, 391, 438 (sequence A006753 in OEIS).

Sample input / output

```<code>18: False (sum of digits: 1 + 8 = 9; factors: 2, 3, 3; sum of digits of factors: 2 + 3 + 3 = 8)
22: True
13: False (meets the digit requirement, but is prime)
666: True (sum of digits: 6 + 6 + 6 = 18; factors: 2, 3, 3, 37; sum of digits of factors: 2 + 3 + 3 + 3 + 7 = 18)
-265: False (negative numbers can't be composite)
0: False (not composite)
1: False (not composite)
4937775: True
</code>```

Notes

Your code can be a function (method) or a full working program,

Instead of words like True and False, you can use any truthy and falsy values, as long as it's clear what they are,

This is a code-golf challenge, so make your code as short as possible!

答:
PowerShell v3+, 183 bytes

```<code>param($n)$b=@();for($a=$n;$a-gt1){2..$a|?{'1'*$_-match'^(?!(..+)\1+$)..'-and!($a%$_)}|%{$b+=$_;$a/=$_}}$n-notin$b-and(([char[]]"$n")-join'+'|iex)-eq(($b|%{[char[]]"$_"})-join'+'|iex)
</code>```

No built-in prime checking. No built-in factoring. No built-in digit-sum. Everything's hand made. :D

Takes input $n as an integer, sets $b equal to an empty array. Here, $b is our collection of prime factors.

Next is a for loop. We first set $a equal to our input number, and the conditional is until $a is less-than-or-equal-to 1. This loop is going to find our prime factors.

We loop from 2 up to $a, uses Where-Object (|?{...}) to pull out primes that are also factors !($a%$_). Those are fed into an inner-loop |%{...} that places the factor into $b and divides $a (thus we'll eventually get to 1).

So, now we have all of our prime factors in $b. Time to formulate our Boolean output. We need to verify that $n is -notin $b, because if it is that means that $n is prime, and so isn't a Smith number. Additionally, (-and) we need to make sure that our two sets of digit sums are -equal. The resulting Boolean is left on the pipeline and output is implicit.

NB - Requires v3 or newer for the -notin operator. <s>I'm still running the input for 4937775 (this is slow to calculate), so I'll update this when that finishes.</s> After 3+ hours, I got a stackoverflow error. So, there's some upper-bound somewhere. Oh well.

This will work for negative input, zero, or one, because the right-hand of the -and will barf out an error while it tries to calculate the digit sums (shown below), which will cause that half to go to $false when evaluated. Since STDERR is ignored by default, and the correct output is still displayed, this is fine.

Test cases

```<code>PS C:\Tools\Scripts\golfing> 4,22,27,58,85,94,18,13,666,-265,0,1|%{"$_ -> "+(.\is-this-a-smith-number.ps1 $_)}
4 -> True
22 -> True
27 -> True
58 -> True
85 -> True
94 -> True
18 -> False
13 -> False
666 -> True
Invoke-Expression : Cannot bind argument to parameter 'Command' because it is an empty string.
At C:\Tools\Scripts\golfing\is-this-a-smith-number.ps1:1 char:179
+ ... "$_"})-join'+'|iex)
+                    ~~~
    + CategoryInfo          : InvalidData: (:String) [Invoke-Expression], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.InvokeExpressionCommand

-265 -> False
Invoke-Expression : Cannot bind argument to parameter 'Command' because it is an empty string.
At C:\Tools\Scripts\golfing\is-this-a-smith-number.ps1:1 char:179
+ ... "$_"})-join'+'|iex)
+                    ~~~
    + CategoryInfo          : InvalidData: (:String) [Invoke-Expression], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.InvokeExpressionCommand

0 -> False
Invoke-Expression : Cannot bind argument to parameter 'Command' because it is an empty string.
At C:\Tools\Scripts\golfing\is-this-a-smith-number.ps1:1 char:179
+ ... "$_"})-join'+'|iex)
+                    ~~~
    + CategoryInfo          : InvalidData: (:String) [Invoke-Expression], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.InvokeExpressionCommand

1 -> False
</code>```

ContentLicense: CC BY-SA 3.0

Title: Is this a Smith number?

Body:
PowerShell v3+, 183 bytes

param($n)$b=@();for($a=$n;$a-gt1){2..$a|?{'1'*$_-match'^(?!(..+)\1+$)..'-and!($a%$_)}|%{$b+=$_;$a/=$_}}$n-notin$b-and(([char[]]"$n")-join'+'|iex)-eq(($b|%{[char[]]"$_"})-join'+'|iex)

No built-in prime checking. No built-in factoring. No built-in digit-sum. Everything's hand made. :D

Takes input $n as an integer, sets $b equal to an empty array. Here, $b is our collection of prime factors.

Next is a for loop. We first set $a equal to our input number, and the conditional is until $a is less-than-or-equal-to 1. This loop is going to find our prime factors.

We loop from 2 up to $a, uses Where-Object (|?{...}) to pull out primes that are also factors !($a%$_). Those are fed into an inner-loop |%{...} that places the factor into $b and divides $a (thus we'll eventually get to 1).

So, now we have all of our prime factors in $b. Time to formulate our Boolean output. We need to verify that $n is -notin $b, because if it is that means that $n is prime, and so isn't a Smith number. Additionally, (-and) we need to make sure that our two sets of digit sums are -equal. The resulting Boolean is left on the pipeline and output is implicit.

NB - Requires v3 or newer for the -notin operator. <s>I'm still running the input for 4937775 (this is slow to calculate), so I'll update this when that finishes.</s> After 3+ hours, I got a stackoverflow error. So, there's some upper-bound somewhere. Oh well.

This will work for negative input, zero, or one, because the right-hand of the -and will barf out an error while it tries to calculate the digit sums (shown below), which will cause that half to go to $false when evaluated. Since STDERR is ignored by default, and the correct output is still displayed, this is fine.

Test cases

PS C:\Tools\Scripts\golfing> 4,22,27,58,85,94,18,13,666,-265,0,1|%{"$_ -> "+(.\is-this-a-smith-number.ps1 $_)}
4 -> True
22 -> True
27 -> True
58 -> True
85 -> True
94 -> True
18 -> False
13 -> False
666 -> True
Invoke-Expression : Cannot bind argument to parameter 'Command' because it is an empty string.
At C:\Tools\Scripts\golfing\is-this-a-smith-number.ps1:1 char:179
+ ... "$_"})-join'+'|iex)
+                    ~~~
    + CategoryInfo          : InvalidData: (:String) [Invoke-Expression], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.InvokeExpressionCommand

-265 -> False
Invoke-Expression : Cannot bind argument to parameter 'Command' because it is an empty string.
At C:\Tools\Scripts\golfing\is-this-a-smith-number.ps1:1 char:179
+ ... "$_"})-join'+'|iex)
+                    ~~~
    + CategoryInfo          : InvalidData: (:String) [Invoke-Expression], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.InvokeExpressionCommand

0 -> False
Invoke-Expression : Cannot bind argument to parameter 'Command' because it is an empty string.
At C:\Tools\Scripts\golfing\is-this-a-smith-number.ps1:1 char:179
+ ... "$_"})-join'+'|iex)
+                    ~~~
    + CategoryInfo          : InvalidData: (:String) [Invoke-Expression], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.InvokeExpressionCommand

1 -> False


Title: Is this a Smith number?

Body:
Challenge description

A Smith number is a composite number whose sum of digits is equal to the sum of sums of digits of its prime factors. Given an integer N, determine if it's a Smith number or not.

The first few Smith numbers are 4, 22, 27, 58, 85, 94, 121, 166, 202, 265, 274, 319, 346, 355, 378, 382, 391, 438 (sequence A006753 in OEIS).

Sample input / output

```<code>18: False (sum of digits: 1 + 8 = 9; factors: 2, 3, 3; sum of digits of factors: 2 + 3 + 3 = 8)
22: True
13: False (meets the digit requirement, but is prime)
666: True (sum of digits: 6 + 6 + 6 = 18; factors: 2, 3, 3, 37; sum of digits of factors: 2 + 3 + 3 + 3 + 7 = 18)
-265: False (negative numbers can't be composite)
0: False (not composite)
1: False (not composite)
4937775: True
</code>```

Notes

Your code can be a function (method) or a full working program,

Instead of words like True and False, you can use any truthy and falsy values, as long as it's clear what they are,

This is a code-golf challenge, so make your code as short as possible!

Body:
Haskell, <s>120</s> 105 bytes

1%_=[];a%x|mod a x<1=x:div a x%x|0<1=a%(x+1)
p z=sum[read[c]|c<-show z]
s x|z<-x%2=z<[x]&&sum(p<$>z)==p x

ContentLicense: CC BY-SA 4.0


答:
MATL, 17 bytes

```<code>YftV!UsGV!Us=wnqh
</code>```

Outputs truthy or falsey arrays where a truthy output requires that all elements be non-zero.

Try it online

Title: Is this a Smith number?

Body:
MATL, 17 bytes

YftV!UsGV!Us=wnqh

Outputs truthy or falsey arrays where a truthy output requires that all elements be non-zero.

Try it online


答:
Jelly, <s>27 25</s> 23 bytes

(further golfing <s>probably</s> definitely possible)

```<code>ḢDS×
ÆFÇ€SḢ
DS=Ça<2oÆP¬
</code>```

Returns 0 for False or 1 for True

All test cases at TryItOnline

How?

```<code>DS=Ça<2oÆP¬ - main link takes an argument, n
DS          - transform n to a decimal list and sum up
   Ç        - call the previous link (ÆFÇ€SḢ)
  =         - test for equality
     <2     - less than 2?
    a       - logical and
        ÆP  - is prime?
       o    - logical or
          ¬ - not
            - all in all tests if the result of the previous link is equal to the digit
              sum if the number is composite otherwise returns 0.

ÆFÇ€SḢ - link takes an argument, n again
ÆF     - list of list of n's prime factors and their multiplicities
  Ç€   - apply the previous link (ḢDS×) for each
    S  - sum up
     Ḣ - pop head of list (there will only be one item)

ḢDS× - link takes an argument, a factor, multiplicity pair
Ḣ    - pop head, the prime factor - modifies list leaving the multiplicity
 DS  - transform n to a decimal list and sum up
   × - multiply the sum with the multiplicity
</code>```

Title: Is this a Smith number?

Body:
Jelly, <s>27 25</s> 23 bytes

(further golfing <s>probably</s> definitely possible)

ḢDS×
ÆFÇ€SḢ
DS=Ça<2oÆP¬

Returns 0 for False or 1 for True

All test cases at TryItOnline

How?

DS=Ça<2oÆP¬ - main link takes an argument, n
DS          - transform n to a decimal list and sum up
   Ç        - call the previous link (ÆFÇ€SḢ)
  =         - test for equality
     <2     - less than 2?
    a       - logical and
        ÆP  - is prime?
       o    - logical or
          ¬ - not
            - all in all tests if the result of the previous link is equal to the digit
              sum if the number is composite otherwise returns 0.

ÆFÇ€SḢ - link takes an argument, n again
ÆF     - list of list of n's prime factors and their multiplicities
  Ç€   - apply the previous link (ḢDS×) for each
    S  - sum up
     Ḣ - pop head of list (there will only be one item)

ḢDS× - link takes an argument, a factor, multiplicity pair
Ḣ    - pop head, the prime factor - modifies list leaving the multiplicity
 DS  - transform n to a decimal list and sum up
   × - multiply the sum with the multiplicity


问:
Convert the Binary Champernowne Constant to Decimal
The Champernowne constant is a transcendental decimal number whose digits are the concatination of all positive integers.

C10 =  0.12345678910111213141516...10

The binary version of this is

C2 = 0.1101110010111011110001...2

Write a program that prints C2 in decimal.  The program should never halt.  It should continue printing digits such that given infinite time and memory, it will print an infinite number of correct digits.

To illustrate this, you must account for integer overflow, since integer overflow will either cause an error or print incorrect digits, even with infinite memory available.

To test your code, here are the first 150 digits of this number.

```<code>0.862240125868054571557790283249394578565764742768299094516071214557306740590516458042038441438618133400466718933678923129464456214392016383510596824661
</code>```

Shortest code wins.

答:
GolfScript, 71 characters

```<code>1.0.){:q,{\.+)q*+\.+q*\.)3$*2$/1$4$*3$/:&-!{&10%print@10*@@}*}/q.+s}:s~
</code>```

Maybe not the best puzzle for GolfScript but tried a solution anyways. The code does iterates infinitely due to an unlimited recursion and prints the digits one after the next (one of the rare cases where the print built-in is needed).

Note that the online version has a cutoff for the recursion.

Body:
GolfScript, 71 characters

1.0.){:q,{\.+)q*+\.+q*\.)3$*2$/1$4$*3$/:&-!{&10%print@10*@@}*}/q.+s}:s~

Maybe not the best puzzle for GolfScript but tried a solution anyways. The code does iterates infinitely due to an unlimited recursion and prints the digits one after the next (one of the rare cases where the print built-in is needed).

Note that the online version has a cutoff for the recursion.


答:
Python 2, <s>122</s> <s>115</s> <s>110</s> 106 bytes

n=m=input()
s=0
for d in range(2,n):
 while n%d<1:n/=d;s+=sum(map(int,`d`))
print n<m>s==sum(map(int,`m`))
```

<p>Saved 4 bytes thanks to Dennis</p>

<p>Try it on ideone.com</p>

<h3>Explanation</h3>

<p>Reads a number on stdin and outputs <code>True</code> if the number is a Smith number or <code>False</code> if it is not.</p>

<pre class="lang-py prettyprint-override"><code>n=m=input()                  # stores the number to be checked in n and in m
s=0                          # initializes s, the sum of the sums of digits of prime factors, to 0
for d in range(2,n):         # checks all numbers from 2 to n for prime factors
 while n%d<1:                # while n is divisible by d
                             #   (to include the same prime factor more than once)
  n/=d                       # divide n by d
  s+=sum(map(int,`d`))       # add the sum of the digits of d to s
print                        # print the result: "True" if and only if
      n<m                    #   n was divided at least once, i.e. n is not prime
      >                      #   and m>s (always true) and
      s==sum(map(int,`m`))   #   s is equal to the sum of digits of m (the input)
</code>```

Title: Is this a Smith number?

Body:
Python 2, <s>122</s> <s>115</s> <s>110</s> 106 bytes

n=m=input()
s=0
for d in range(2,n):
 while n%d<1:n/=d;s+=sum(map(int,`d`))
print n<m>s==sum(map(int,`m`))

Saved 4 bytes thanks to Dennis

Try it on ideone.com

Explanation

Reads a number on stdin and outputs True if the number is a Smith number or False if it is not.

n=m=input()                  # stores the number to be checked in n and in m
s=0                          # initializes s, the sum of the sums of digits of prime factors, to 0
for d in range(2,n):         # checks all numbers from 2 to n for prime factors
 while n%d<1:                # while n is divisible by d
                             #   (to include the same prime factor more than once)
  n/=d                       # divide n by d
  s+=sum(map(int,`d`))       # add the sum of the digits of d to s
print                        # print the result: "True" if and only if
      n<m                    #   n was divided at least once, i.e. n is not prime
      >                      #   and m>s (always true) and
      s==sum(map(int,`m`))   #   s is equal to the sum of digits of m (the input)


Title: Is this a Smith number?

Body:
JavaScript (ES6), <s> 87 86 </s> 84 bytes

m=>(i=2,S=0,g=n=>([...i+''].map(v=>s-=v,s=S),i-m?n%i?g(n,i++):g(n/i,S=s):s==2*S))(m)

Try it online!


问:
As Easy as One-Two-Three
Write a program or function that takes in a positive integer. You can assume the input is valid and may take it as a string. If the number is any of

```<code>123
234
345
456
567
678
789
</code>```

then output a truthy value. Otherwise, output a falsy value. For example, the inputs

```<code>1
2
3
12
122
124
132
321
457
777
890
900
1011
1230
1234
</code>```

must all result in falsy output. (The input will not have leading zeroes so you needn't worry about things like 012.)

The shortest code in bytes wins.

答:
PHP 5.6, 48 bytes

<?=($a=$argv[1])==join("",range($a[0],$a[0]+2));
```

<p>Wanted to try something a little different from the other PHP answers (and a different approach to most of the posted answers). Take the first number of the input string, add two to it and create a <code>range</code> array, then join those together to create a new string and then return if they're equal or not.</p>

<p>Run with:</p>

<pre class="lang-php prettyprint-override"><code>echo '<?=($a=$argv[1])==join("",range($a[0],$a[0]+2));' | php -- 123
</code>```

Title: As Easy as One-Two-Three

Body:
PHP 5.6, 48 bytes

<?=($a=$argv[1])==join("",range($a[0],$a[0]+2));

Wanted to try something a little different from the other PHP answers (and a different approach to most of the posted answers). Take the first number of the input string, add two to it and create a range array, then join those together to create a new string and then return if they're equal or not.

Run with:

echo '<?=($a=$argv[1])==join("",range($a[0],$a[0]+2));' | php -- 123


问:
Golf all the 16 logic gates with 2 inputs and 1 output!
For example, the gate A and B is a logic gate with 2 inputs and 1 output.

There are exactly 16 of them, because:

each logic gate takes two inputs, which can be truthy or falsey, giving us 4 possible inputs

of the 4 possible inputs, each can have an output of truthy and falsey

therefore, there are 2^4 possible logic gates, which is 16.

Your task is to write 16 programs/functions which implement all of them separately.

Your functions/programs must be independent.

They are valid as long as they output truthy/falsey values, meaning that you can implement A or B in Python as lambda a,b:a+b, even if 2 is produced for A=True and B=True.

Score is total bytes used for each function/program.

List of logic gates

0,0,0,0 (false)

0,0,0,1 (and)

0,0,1,0 (A and not B)

0,0,1,1 (A)

0,1,0,0 (not A and B)

0,1,0,1 (B)

0,1,1,0 (xor)

0,1,1,1 (or)

1,0,0,0 (nor)

1,0,0,1 (xnor)

1,0,1,0 (not B)

1,0,1,1 (B implies A)

1,1,0,0 (not A)

1,1,0,1 (A implies B)

1,1,1,0 (nand)

1,1,1,1 (true)

Where the first number is the output for A=false, B=false,
the second number is the output for A=false, B=true,
the third number is the output for A=true, B=false,
the fourth number is the output for A=true, B=true.

Leaderboard

var QUESTION_ID=82938,OVERRIDE_USER=48934;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+(?:\.\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

```

答:
C 34 bytes

```<code>#define g(n,a,b)((n-1)>>3-b-2*a)&1
</code>```

Where n is the function number to use, but I think it would be refused so I propose this other one:

C 244 bytes (using memory)

```<code>typedef int z[2][2];
z a={0,0,0,0};
z b={0,0,0,1};
z c={0,0,1,0};
z d={0,0,1,1};
z e={0,1,0,0};
z f={0,1,0,1};
z g={0,1,1,0};
z h={0,1,1,1};
z i={1,0,0,0};
z j={1,0,0,1};
z k={1,0,1,0};
z l={1,0,1,1};
z m={1,1,0,0};
z n={1,1,0,1};
z o={1,1,1,0};
z p={1,1,1,1};
</code>```

it uses double indexed array. n[0][1] is (A implies B)(0,1)

Forth 138 bytes

I just learned Forth. I suppose that's Ansi Forth compatible as it run also on gforth.

```<code>: z create dup , 1+ does> @ -rot 3 swap - swap 2* - rshift 1 and ;
0
z a z b z c z d z e z f z g z h z i z j z k z l z m z n z o z p
drop
</code>```

Function z  create a new function with the name provided then put the logic gate number from the top of stack to the new function address. It leaves the next (n+1) logic gate function in the stack for the next declaration.

you can test it :

And A B

```<code>0 0 b . cr
0 1 b . cr
1 0 b . cr
1 1 b . cr
</code>```

( "." print top of stack "cr" is cariage return )

Body:
C 34 bytes

#define g(n,a,b)((n-1)>>3-b-2*a)&1

Where n is the function number to use, but I think it would be refused so I propose this other one:

C 244 bytes (using memory)

typedef int z[2][2];
z a={0,0,0,0};
z b={0,0,0,1};
z c={0,0,1,0};
z d={0,0,1,1};
z e={0,1,0,0};
z f={0,1,0,1};
z g={0,1,1,0};
z h={0,1,1,1};
z i={1,0,0,0};
z j={1,0,0,1};
z k={1,0,1,0};
z l={1,0,1,1};
z m={1,1,0,0};
z n={1,1,0,1};
z o={1,1,1,0};
z p={1,1,1,1};

it uses double indexed array. n[0][1] is (A implies B)(0,1)

Forth 138 bytes

I just learned Forth. I suppose that's Ansi Forth compatible as it run also on gforth.

: z create dup , 1+ does> @ -rot 3 swap - swap 2* - rshift 1 and ;
0
z a z b z c z d z e z f z g z h z i z j z k z l z m z n z o z p
drop

Function z  create a new function with the name provided then put the logic gate number from the top of stack to the new function address. It leaves the next (n+1) logic gate function in the stack for the next declaration.

you can test it :

And A B

0 0 b . cr
0 1 b . cr
1 0 b . cr
1 1 b . cr

( "." print top of stack "cr" is cariage return )


答:
Pyth, 21 bytes

```<code>&&>Q1!P_QqsjQTssmjdTP
</code>```

A program that takes input of an integer and prints True or False as relevant.

Try it online

How it works

```<code>&&>Q1!P_QqsjQTssmjdTP  Program. Input: Q
           jQT         Yield digits of the base-10 representation of Q as a list
          s            Add the digits
                    P  Yield prime factors of Q (implicit input fill)
                mjdT   Map base-10 representation across the above, yielding digits of each
                       factor as a list of lists
               s       Flatten the above
              s        Add up the digits
         q             Those two sums are equal
&                      and
  >Q1                  Q>1
 &                     and
     !P_Q              Q is not prime
                       Implicitly print
</code>```

Title: Is this a Smith number?

Body:
Pyth, 21 bytes

&&>Q1!P_QqsjQTssmjdTP

A program that takes input of an integer and prints True or False as relevant.

Try it online

How it works

&&>Q1!P_QqsjQTssmjdTP  Program. Input: Q
           jQT         Yield digits of the base-10 representation of Q as a list
          s            Add the digits
                    P  Yield prime factors of Q (implicit input fill)
                mjdT   Map base-10 representation across the above, yielding digits of each
                       factor as a list of lists
               s       Flatten the above
              s        Add up the digits
         q             Those two sums are equal
&                      and
  >Q1                  Q>1
 &                     and
     !P_Q              Q is not prime
                       Implicitly print


问:
Is it a leap year?
This challenge is quite simple. You will take an input which will be a year from 1801 to 2400, and output if it is a leap year or not.

Your input will have no newlines or trailing spaces:

```<code>1954
</code>```

You will output in any way that you like that clearly tells the user if it is or isn't a leap year (I will accept y or n for yes/no)

You can get a list of leap years here: http://kalender-365.de/leap-years.php
I would note that leap years are not ever four years always. 1896 is a leap year, but 1900 is not. The years that follow this "skip" are:

```<code>1900
2100
2200
2300
</code>```

Test cases:

```<code>1936 ->  y
1805 ->  n
1900 ->  n
2272 ->  y
2400 ->  y
</code>```

EDIT: This is based on a standard Gregorian calendar: http://www.epochconverter.com/date-and-time/daynumbers-by-year.php

The Catalogue

The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

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

```<code>## Language Name, 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, <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, 43 + 2 (-p flag) = 45 bytes
</code>```

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

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

/* Configuration */

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

/* App */

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

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '
' + c.body.replace(OVERRIDE_REG, '') + '
';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    else console.log(body);
  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    lang = jQuery(''+lang+'').text();

    languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
    if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  text-align: left !important;
  display: block !important;
}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 500px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}</code>```

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

Title: Is it a leap year?

Body:
BASH, 68 bytes

((!(y % 4) && ( y % 100 || !(y % 400)))) &&  echo "leap" || echo "no"


问:
Draw an Empty Scrabble Board
A standard Scrabble board is a 15×15 grid of spaces to place letter tiles. Most of the spaces are blank but some are double word scores (pink), triple word scores (red), double letter scores (light blue), and triple letter scores (blue). There is usually a star in the very center (which counts as a double word score).

Write a program or function that outputs a standard, empty Scrabble board in ASCII form where:

. represents an empty space

D represents a double word score

T represents a triple word score

d represents a double letter score

t represents a triple letter score

X represents the center star

That is, your exact output must be

```<code>T..d...T...d..T
.D...t...t...D.
..D...d.d...D..
d..D...d...D..d
....D.....D....
.t...t...t...t.
..d...d.d...d..
T..d...X...d..T
..d...d.d...d..
.t...t...t...t.
....D.....D....
d..D...d...D..d
..D...d.d...D..
.D...t...t...D.
T..d...T...d..T
</code>```

optionally followed by a trailing newline.

The shortest code in bytes wins.

答:
05AB1E, <s>57</s> 53 bytes

Code

```<code>•jd]31‚ŽÔc¦Ïïì¹Ep.Üì8Ìa;“•6B4ÝJ".TdDt"‡5'.3×:Â'Xý15ô»
</code>```

Uses the CP-1252 encoding. Try it online!

Explanation (outdated)

The •4ç“–šã&$W§ñçvßÖŠ_æá_VFÛÞýi~7¾¬ÏXôc•5B decompresses to this number:

```<code>1002000100020010400030003000400040002020004002004000200040020000400000400000300030003000300020002020002001002000
</code>```

With 4ÝJ".TdtD"‡, we transliterate the following in this big number:

```<code>0 -> .
1 -> T
2 -> d
3 -> t
4 -> D
</code>```

We bifurcate the whole string, leaving the string and the string reversed on the stack and join them by "X" using ý. We split the entire string into pieces of 15 using th 15ô code and join the whole array by newlines using ».

Title: Draw an Empty Scrabble Board

Body:
05AB1E, <s>57</s> 53 bytes

Code

•jd]31‚ŽÔc¦Ïïì¹Ep.Üì8Ìa;“•6B4ÝJ".TdDt"‡5'.3×:Â'Xý15ô»

Uses the CP-1252 encoding. Try it online!

Explanation (outdated)

The •4ç“–šã&$W§ñçvßÖŠ_æá_VFÛÞýi~7¾¬ÏXôc•5B decompresses to this number:

1002000100020010400030003000400040002020004002004000200040020000400000400000300030003000300020002020002001002000

With 4ÝJ".TdtD"‡, we transliterate the following in this big number:

0 -> .
1 -> T
2 -> d
3 -> t
4 -> D

We bifurcate the whole string, leaving the string and the string reversed on the stack and join them by "X" using ý. We split the entire string into pieces of 15 using th 15ô code and join the whole array by newlines using ».


问:
Render the top-down view of a hip roof in ASCII
First, some terminology (source):

A hip roof is (quoting Wikipedia) "a type of roof where all sides slope downwards to the walls, usually with a fairly gentle slope"

A slope is a planar surface that is a part of the roof

A ridge is an edge where two opposite roof slopes meet

A hip is a convex edge where two slopes belonging to perpendicular walls meet

A valley is a concave edge where two slopes belonging to perpendicular walls meet

Hips and valleys shall be collectively referred to as diagonal edges.

Possible input:

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

Corresponding output:

```<code>    +-------+   +---+   +-----------+
    |\     /|   |\ /|   |\         /|
    | \   / |   | V |   | \   ^---< |
    |  \ /  |   | | |   |  \ / \   \|
+---+   V   +---+ | +---+   X   +---+
|\   \  |  /     \|/     \ / \  |
| >---> | <-------X-------V   > |
|/   /  |  \     /|\         /| |
+---+   ^   +---+ | +-------+ | +---+
    |  / \  |   | | |       | |/   /|
    | /   \ |   | ^ |       | /---< |
    |/     \|   |/ \|       |/     \|
    +-------+   +---+       +-------+
</code>```

A couple more test cases:

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

Corresponding outputs :

```<code>+-------+   +-----------+           +---+               +---+           +---+   +---+
|\     /|   |\         /|           |\ /|               |\ /|           |\ /|   |\ /|
| \---< |   | >-------< |           | V |               | V |           | V |   | X |
| |\   \|   |/         \|           | | |               | | |           | | |   |/ \|
| | +---+   +-----------+       +---+ | +---+           | | +-----------+ | |   +---+
| | |                           |\   \|/   /|           | |/             \| |
| ^ |                           | \   V   / |           | <               > |
|/ \|                           |  \     /  |           |  \             /  |
+---+           +-------+   +---+   \   /   +---+       |   \-----------/   |
                |\     /|   |\   \   \ /   /   /|       |   |\         /|   |
                | >---/ |   | >--->   X   <---< |       |   | \       / |   |
                |/   /| |   |/   /   / \   \   \|       |   |  \     /  |   |
+---+   +---+   +---+ | |   +---+   /   \   +---+   +---+   ^   +---+   ^   +---+
|\ /|   |\ /|       | | |       |  /     \  |       |\   \ / \  |   |  / \ /   /|
| V |   | V |       | | |       | /   ^   \ |       | >---V   > |   | <   V---< |
| | |   | | |       | | |       |/   /|\   \|       |/       /| |   | |\       \|
| | |   | | +-------+ | |       +---+ | +---+       +-------+ | |   | | +-------+
| | |   | |/         \| |           | | |                   | | |   | | |
| ^ |   | /-----------\ |           | ^ |                   | ^ |   | ^ |
|/ \|   |/             \|           |/ \|                   |/ \|   |/ \|
+---+   +---------------+           +---+                   +---+   +---+
</code>```

Your input will be a bitmap - a 2D array of square pixels - of the area that should be covered by roof. You may assume the boundary of this area will be a Jordan curve - that is, continuous and non-self-intersecting - that is, the roofed area will be continuous, without holes and there will never be four walls meeting at a single point. Valid input formats include a single string with newline separators, a list of strings and a 2D array of chars or booleans.

The rules of building the roof are:

Each straight segment of the roofed area (henceforth referred to as a wall) shall have exactly one adjoining slope. The slope shall rise away from the wall. Each slope shall have at least one adjoining wall, and all walls adjoining to a slope must be collinear.

All slopes shall have the same (nonzero) angle against the horizontal surface. That is, they must have the same pitch.

The slopes shall form a surface whose boundary is the boundary of the roofed area. That is, no surfaces other than the slopes may be used.

Any scenario where more than one solution (up to vertical scaling) is allowed by this specification is considered a bug in the specification. Any corrections apply retroactively.

Equivalently, the roof may be defined by the rule that each point of the roof is  placed as high as possible without exceeding the maximum slope for that roof as measured using the Chebyshev distance in top-down view.

Your output shall be an ASCII art representation of the roof - either a single string containing newline characters or an array of strings, each denoting a single line of the output. The roof shall be rendered in top-down view at a 4x scale - that is, each square of the floor-plan should affect a 5x5 area of the output such that the corners of this 5x5 area are shared with neighboring squares (such that each corner character is affected by four different input squares), as indicated by the example output. Extra whitespace is allowed as long as the output shape is preserved. The characters in output shall be:

an environment-defined newline marker shall be used (usually U+000A, U+000D or a pair of both) if the output is in the form of a single string

 (U+0020 space) represents a point outside a roofed area or a point interior to a slope

+ (U+002B plus sign) represents a point with two perpendicular walls adjoined to it

- (U+002D hyphen-minus) represents a wall or a ridge oriented horizontally (east-west)

/ (U+002F solidus) represents a hip or a valley oriented north-east to south-east, or a point adjoined to two of those

< (U+003C less-than sign) represents a point with two diagonal edges adjoined to it on the east

> (U+003E greater-than sign) represents a point with two diagonal edges adjoined to it on the west

\ (U+005C reverse solidus) represents a hip or a valley oriented north-west to south-east, or a point adjoined to two of those

^ (U+005E circumflex accent) represents a point with two diagonal edges adjoined to it on the south

V (U+0056 latin capital letter v) represents a point with two diagonal edges adjoined to it on the north

X (U+0058 latin capital letter x) represents a point with diagonal edges adjoined to it on all four sides

| (U+007C vertical bar) represents a wall or a ridge oriented vertically (north-south)

Note that it is not possible for an odd number of diagonal edges to end at the same point (except on walls). We can visualize that by partitioning the neighborhood of each point into north slope + south slope  and into east slope + west slope. The boundary between both partitions has to be composed of diagonal edges.

If your environment uses a character encoding incompatible with ASCII, you may use the equivalent characters (same glyph or closest available) in the character encoding your environment uses.

The following (ugly) reference implementation in Ruby is normative with respect to the non-whitespace output. Note particularly the render method:

```<code>def pad ary
  row = ary.first.map{-1}
  ([row] + ary + [row]).map{|r| [-1] + r + [-1]}
end

def parse str
  str.split("\n").map{|r| r.chars.map(&{" " => -1, "*" => Float::INFINITY})}
end

def squares ary, size
  ary.each_cons(size).map do |rows|
    rows.map{|row| row.each_cons(size).to_a}.transpose
  end
end

def consmap2d ary, size
  squares(ary, size).map{|sqrow| sqrow.map{|sq| yield sq}}
end

def relax ary
  loop do
    new = consmap2d(pad(ary), 3){|sq| sq[1][1] == -1 ? -1 : sq.flatten.min + 1}
    return new if new == ary
    ary = new
  end
end

def semidouble ary, op
  ary.zip(ary.each_cons(2).map{|r1,r2|r1.zip(r2).map(&op)}).flatten(1).compact.transpose
end

def heightmap str
  relax(semidouble(semidouble(semidouble(semidouble(pad(parse str),:max),:max),:min),:min))
end

def render heightmap
  puts consmap2d(heightmap, 3){|sq|
    next " " if sq[1][1] == -1
    hwall = sq[0][1] == -1 || sq[2][1] == -1
    vwall = sq[1][0] == -1 || sq[1][2] == -1
    next "+" if hwall && vwall
    next "-" if hwall
    next "|" if vwall
    next "+" if sq.flatten.min == -1

    nws = sq[0][1] == sq[1][0]
    nes = sq[0][1] == sq[1][2]
    sws = sq[2][1] == sq[1][0]
    ses = sq[2][1] == sq[1][2]

    next "X"  if nws && nes && sws && ses
    next "V"  if nws && nes
    next "^"  if sws && ses
    next ">"  if nws && sws
    next "<"  if nes && ses
    next "/"  if nes && sws
    next "\\" if nws && ses
    next " "  if sq[0][1] != sq[2][1] || sq[1][0] != sq[1][2]
    next "|"  if sq[0][1] == sq[1][1]
    next "-"  if sq[1][0] == sq[1][1]
    ??
  }.map(&:join)
end

render heightmap $<.read if __FILE__ == $0
</code>```

Body:
Python 2, 500 bytes

z=input()
W=4*len(z[0])+1
H=4*len(z)+1
R=range
s=[-~W*[0]for _ in R(-~H)]
for y in R(H/4):
 for x in R(W/4):
        for h in R(25):s[y*4+h%5][x*4+h/5]|=z[y][x]
F=[(x/3-1,x%3-1)for x in[1,7,3,5,0,6,8,2]]
exec'for y in R(H):\n for x in R(W):s[y][x]+=0<s[y][x]<=min(s[y+d][x+e]for(e,d)in F)\n'*H
for y in R(H):
 l=''
 for x in R(W):h=s[y][x];a=[s[y+d][x+e]for(e,d)in F[:4]];l+=r' XabcVde^f ||g>h\\+//+<<jk<l//+\\+>>m --^^oVVqrX'[h and int(''.join(`int(n==h)`for n in a),2)*3+((h==1)*2or max(a)==h)+1]
 print l

Tired of golfing it down, and I got to a nice round score, so here it is.

The eight-space indentation is a tab.

Pass a binary matrix over STDIN, like so:

python2.7 roof.py <<<"[[1,1,0,1,1,1,0,0,0,1,0,0,0,0,1,0,0,0,1,0], [1,0,0,0,0,0,0,0,1,1,1,0,0,0,1,1,1,1,1,0], [0,0,0,0,1,1,0,1,1,1,1,1,0,0,1,1,1,1,1,0], [1,0,1,0,0,1,0,0,1,1,1,0,0,1,1,1,0,1,1,1], [1,0,1,1,1,1,0,0,0,1,0,0,0,0,0,1,0,1,0,0]]"


答:
Jelly, <s>12</s> 11 bytes

```<code>Æfḟȯ.DFżDSE
</code>```

Returns 1 for Smith numbers and 0 otherwise. Try it online! or verify all test cases.

Background

Æf (prime factorization) and D (integer-to-decimal) are implemented so that P (product) and Ḍ (decimal-to-integer) constitute left inverses.

For the integers -4 to 4, Æf returns the following.

```<code>-4 -> [-1, 2, 2]
-3 -> [-1, 3]
-2 -> [-1, 2]
-1 -> [-1]
 0 -> [0]
 1 -> []
 2 -> [2]
 3 -> [3]
 4 -> [2, 2]
</code>```

For the numbers -10, -1, -0.5, 0, 0.5, 1, 10, D returns the following.

```<code>-11   -> [-1, -1]
-10   -> [-1, 0]
 -1   -> [-1]
 -0.5 -> [-0.5]
  0   -> [0]
  0.5 -> [0.5]
  1   -> [1]
 10   -> [1, 0]
 11   -> [1, 1]
</code>```

How it works

```<code>Æfḟȯ.DFżDSE  Main link. Argument: n (integer)

Æf           Yield the prime factorization of n.
  ḟ          Filter; remove n from its prime factorization.
             This yields an empty array if n is -1, 0, 1, or prime.
   ȯ.        If the previous result is an empty array, replace it with 0.5.
     D       Convert all prime factors to decimal.
      F      Flatten the result.
        D    Yield n in decimal.
       ż     Zip the results to both sides, creating a two-column array.
         S   Compute the sum of each column.
             If n is -1, 0, 1, or prime, the sum of the prime factorization's
             digits will be 0.5, and thus unequal to the sum of the decimal array.
             If n < -1, the sum of the prime factorization's digits will be
             positive, while the sum of the decimal array will be negative.
          E  Test both sums for equality.
</code>```

Title: Is this a Smith number?

Body:
Jelly, <s>12</s> 11 bytes

Æfḟȯ.DFżDSE

Returns 1 for Smith numbers and 0 otherwise. Try it online! or verify all test cases.

Background

Æf (prime factorization) and D (integer-to-decimal) are implemented so that P (product) and Ḍ (decimal-to-integer) constitute left inverses.

For the integers -4 to 4, Æf returns the following.

-4 -> [-1, 2, 2]
-3 -> [-1, 3]
-2 -> [-1, 2]
-1 -> [-1]
 0 -> [0]
 1 -> []
 2 -> [2]
 3 -> [3]
 4 -> [2, 2]

For the numbers -10, -1, -0.5, 0, 0.5, 1, 10, D returns the following.

-11   -> [-1, -1]
-10   -> [-1, 0]
 -1   -> [-1]
 -0.5 -> [-0.5]
  0   -> [0]
  0.5 -> [0.5]
  1   -> [1]
 10   -> [1, 0]
 11   -> [1, 1]

How it works

Æfḟȯ.DFżDSE  Main link. Argument: n (integer)

Æf           Yield the prime factorization of n.
  ḟ          Filter; remove n from its prime factorization.
             This yields an empty array if n is -1, 0, 1, or prime.
   ȯ.        If the previous result is an empty array, replace it with 0.5.
     D       Convert all prime factors to decimal.
      F      Flatten the result.
        D    Yield n in decimal.
       ż     Zip the results to both sides, creating a two-column array.
         S   Compute the sum of each column.
             If n is -1, 0, 1, or prime, the sum of the prime factorization's
             digits will be 0.5, and thus unequal to the sum of the decimal array.
             If n < -1, the sum of the prime factorization's digits will be
             positive, while the sum of the decimal array will be negative.
          E  Test both sums for equality.


问:
Simulate any 1D cellular automaton

The Challenge

You are to write a complete program that takes seven numbers from STDIN, and prints the two dimensional history of the cellular automaton (CA) to STDOUT. This is code golf.

Input Formatting
The input will be seven integers/strings separated by commas. The first number is the number of the rule according to Wolfram code (the standard name for each rule). The second is the initial starting configuration. The third and fourth describe what pattern and how many times it should be appended to the left of the starting config. as padding. The fifth and sixth do the same for the right side. The last number is the number of generations to run the simulation.

So, an example of input is 90,11,0,4,0,4,5. This should tell your program that you are running rule 90. It should also tell the program that you want the initial configuration to be 11 with the string 0 appended 4 times to both ends, so the actual starting pattern is 0000110000. It also tells your program to run this simulation for 5 generations.

Output Your program should print the entire array of cells each generation (separated by newlines), so that the output is the space-time diagram of the CA. For each generation, the state of each cell is determined by its state and the states of the cells to the immediate left and right, in accordance to the rule provided as input. The simulation should wrap around the edges. The first thing printed should be the starting array as gen. 0.

The input 90,11,0,4,0,4,5 should result in the following output as exactly as possible.

```<code>0000110000
0001111000
0011001100
0111111110
1100000011
0110000110
</code>```

Notice that the starting state is not included in the five generations. Also notice that the simulation wraps around the edges.

More Examples

input:

```<code>184,1100,01,2,01,1,4
</code>```

output:

```<code>0101110001
1011101000
0111010100
0110101010
0101010101
</code>```

input:

```<code>0,1011,1,0,0,1,2
</code>```

output:

```<code>10110
00000
00000
</code>```

More information on how 1D CA's work and how they are numbered

答:
C, <s>303 305 301 294</s> 292

305 Edit: oops. Forgot that calloc() takes two args. It was blowing up on larger input.

301 Edit: Ah HA! Used my calloc() boo-boo to save 2 more bytes by upping the block size of the requested memory.

294 Edit: Broke 300! Eliminated one of the strcat()s and tweaked a few loops. Got to use maximal munch, which is as much fun to say as use.

292 Edit: Didn't need the +2 in memory allocation.

I used luser droog's answer as the base idea, but changed up the wrapping algorithm, as well as a lot of tweaking and factoring out of constants.

```<code>r,A,C,n,j;main(){char*s,*p,*t,a[9],b[9],c[9];scanf("%d,%[01],%[01],%d,%[01],%d,%d",&r,b,a,&A,c,&C,&n);for(s=calloc(A+++C,9);A--;)strcat(s,A?a:b);for(;C--;)strcat(s,c);p=strdup(s);for(C=strlen(s);A++<n;puts(s),t=p,p=s,s=t)for(j=C;j--;)p[j]=(1<<(s[j?j-1:C-1]*4+s[j]*2+s[(j+1)%C])-336)&r?49:48;}

r,A,C,n,j;
main(){
    char*s,*p,*t,a[9],b[9],c[9];
    scanf("%d,%[01],%[01],%d,%[01],%d,%d",&r,b,a,&A,c,&C,&n);
    for(s=calloc(A+++C,9);A--;)
        strcat(s,A?a:b);
    for(;C--;)
        strcat(s,c);
    p=strdup(s);
    for(C=strlen(s);A++<n;puts(s),t=p,p=s,s=t)
        for(j=C;j--;)
            p[j]=(1<<(s[j?j-1:C-1]*4+s[j]*2+s[(j+1)%C])-336)&r?49:48;
}
</code>```

Title: Simulate any 1D cellular automaton

Body:
C, <s>303 305 301 294</s> 292

305 Edit: oops. Forgot that calloc() takes two args. It was blowing up on larger input.

301 Edit: Ah HA! Used my calloc() boo-boo to save 2 more bytes by upping the block size of the requested memory.

294 Edit: Broke 300! Eliminated one of the strcat()s and tweaked a few loops. Got to use maximal munch, which is as much fun to say as use.

292 Edit: Didn't need the +2 in memory allocation.

I used luser droog's answer as the base idea, but changed up the wrapping algorithm, as well as a lot of tweaking and factoring out of constants.

r,A,C,n,j;main(){char*s,*p,*t,a[9],b[9],c[9];scanf("%d,%[01],%[01],%d,%[01],%d,%d",&r,b,a,&A,c,&C,&n);for(s=calloc(A+++C,9);A--;)strcat(s,A?a:b);for(;C--;)strcat(s,c);p=strdup(s);for(C=strlen(s);A++<n;puts(s),t=p,p=s,s=t)for(j=C;j--;)p[j]=(1<<(s[j?j-1:C-1]*4+s[j]*2+s[(j+1)%C])-336)&r?49:48;}

r,A,C,n,j;
main(){
    char*s,*p,*t,a[9],b[9],c[9];
    scanf("%d,%[01],%[01],%d,%[01],%d,%d",&r,b,a,&A,c,&C,&n);
    for(s=calloc(A+++C,9);A--;)
        strcat(s,A?a:b);
    for(;C--;)
        strcat(s,c);
    p=strdup(s);
    for(C=strlen(s);A++<n;puts(s),t=p,p=s,s=t)
        for(j=C;j--;)
            p[j]=(1<<(s[j?j-1:C-1]*4+s[j]*2+s[(j+1)%C])-336)&r?49:48;
}


问:
Print numbers from 1 to 10
This might be a very simple challenge, but I am surprised it hasn't been done on code-golf yet:

Print all Integers from 1 to 10 inclusive in ascending order to standard output.

Your output format can be whatever your language supports. This includes arbitrary separators (commas, semicolons, newlines, combinations of those, etc., but no digits), and prefixes and postfixes (like [...]). However, you may not output any other numbers than 1 through 10. Your program may not take any input. Standard loopholes are disallowed.

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

Leaderboard

var QUESTION_ID=86075,OVERRIDE_USER=42570;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

```

答:
Silicon, 3 bytes

(Silicon uses CP037, so 3 bytes, not 4.)

```<code>0Â\
</code>```

Explanation:

```<code>0Â\
  \     Push a list with the numbers in the range...
0       Zero
 Â      Ten
</code>```

Title: Print numbers from 1 to 10

Body:
Silicon, 3 bytes

(Silicon uses CP037, so 3 bytes, not 4.)

0Â\

Explanation:

0Â\
  \     Push a list with the numbers in the range...
0       Zero
 Â      Ten


答:
PowerShell v2+, <s>147</s> 143 bytes

($x='T..d...T...d..T')
($y='.D...t..','..D...d.','d..D...d','....D...','.t...t..','..d...d.'|%{$_+-join$_[6..0]})
'T..d...X...d..T'
$y[5..0]
$x
```

<p>Try it online!</p>

<p>Takes advantage of how the default <code>Write-Output</code> at end of program execution handles arrays (i.e., it inserts a newline between elements). Might be a better way to generate the middle of the board -- I'm still working at it.</p>

<p>The first line outputs the top line of the board, also storing it in <code>$x</code> for use later.</p>

<p>The next line generates all the Double-Word lines by taking the left "half" of each, mirroring them (the <code>-join$_[6..0]</code> statement), and storing them as elements in array <code>$y</code>.</p>

<p>The next line is the middle row, with an <code>X</code> in the middle, thanks to <code>-replace</code>.</p>

<p>The next line outputs <code>$y</code> in reverse order, giving us the bottom Double-Word lines.</p>

<p>The final line is just <code>$x</code> again.</p>

<pre class="lang-powershell prettyprint-override"><code>PS C:\Tools\Scripts\golfing> .\draw-empty-scrabble-board.ps1
T..d...T...d..T
.D...t...t...D.
..D...d.d...D..
d..D...d...D..d
....D.....D....
.t...t...t...t.
..d...d.d...d..
T..d...X...d..T
..d...d.d...d..
.t...t...t...t.
....D.....D....
d..D...d...D..d
..D...d.d...D..
.D...t...t...D.
T..d...T...d..T
</code>```

-4 bytes thanks to Veskah.

Title: Draw an Empty Scrabble Board

Body:
A standard Scrabble board is a 15×15 grid of spaces to place letter tiles. Most of the spaces are blank but some are double word scores (pink), triple word scores (red), double letter scores (light blue), and triple letter scores (blue). There is usually a star in the very center (which counts as a double word score).

Write a program or function that outputs a standard, empty Scrabble board in ASCII form where:

. represents an empty space

D represents a double word score

T represents a triple word score

d represents a double letter score

t represents a triple letter score

X represents the center star

That is, your exact output must be

```<code>T..d...T...d..T
.D...t...t...D.
..D...d.d...D..
d..D...d...D..d
....D.....D....
.t...t...t...t.
..d...d.d...d..
T..d...X...d..T
..d...d.d...d..
.t...t...t...t.
....D.....D....
d..D...d...D..d
..D...d.d...D..
.D...t...t...D.
T..d...T...d..T
</code>```

optionally followed by a trailing newline.

The shortest code in bytes wins.

Body:
PowerShell v2+, <s>147</s> 143 bytes

($x='T..d...T...d..T')
($y='.D...t..','..D...d.','d..D...d','....D...','.t...t..','..d...d.'|%{$_+-join$_[6..0]})
'T..d...X...d..T'
$y[5..0]
$x

Try it online!

Takes advantage of how the default Write-Output at end of program execution handles arrays (i.e., it inserts a newline between elements). Might be a better way to generate the middle of the board -- I'm still working at it.

The first line outputs the top line of the board, also storing it in $x for use later.

The next line generates all the Double-Word lines by taking the left "half" of each, mirroring them (the -join$_[6..0] statement), and storing them as elements in array $y.

The next line is the middle row, with an X in the middle, thanks to -replace.

The next line outputs $y in reverse order, giving us the bottom Double-Word lines.

The final line is just $x again.

PS C:\Tools\Scripts\golfing> .\draw-empty-scrabble-board.ps1
T..d...T...d..T
.D...t...t...D.
..D...d.d...D..
d..D...d...D..d
....D.....D....
.t...t...t...t.
..d...d.d...d..
T..d...X...d..T
..d...d.d...d..
.t...t...t...t.
....D.....D....
d..D...d...D..d
..D...d.d...D..
.D...t...t...D.
T..d...T...d..T

-4 bytes thanks to Veskah.


答:
MATL, <s>59</s> <s>54</s> 52 bytes

```<code>4t:g2I5vXdK8(3K23h32h(H14(t!XR+8: 7:Pht3$)'DtdTX.'w)
</code>```

Try it online!

Explanation

The code follows three main steps:

Generate the 8x8 matrix

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

Extend it to the 15x15 matrix

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

Index the string 'DtdTX.' with that matrix to produce the desired result.

Step 1

```<code>4        % Push 4
t:       % Duplicate, range: pushes [1 2 3 4]
g        % Logical: convert to [1 1 1 1]
2I5      % Push 2, then 3, then 5
v        % Concatenate all stack vertically into vector [4 1 1 1 1 2 3 5]
Xd       % Generate diagonal matrix from that vector
</code>```

Now we need to fill the nonzero off-diagonal entries. We will only fill those below the diagonal, and then make use symmetry to fill the others.

To fill each value we use linear indexing (see this answer, length-12 snippet). That means accessing the matrix as if it had only one dimension. For an 8×8 matrix, each value of the linear index refers to an entry as follows:

```<code>1   9         57
2  10         58
3  11
4
5  ...       ...
6
7             63
8  16 ... ... 64
</code>```

So, the following assigns the value 4 to the lower-left entry:

```<code>K        % Push 4
8        % Push 8
(        % Assign 4 to the entry with linear index 8
</code>```

The code for the value 3 is similar. In this case the index is a vector, because we need to fill several entries:

```<code>3        % Push 3
K        % Push 4
23h      % Push 23 and concatenate horizontally: [4 23]
32h      % Push 32 and concatenate horizontally: [4 23 32]
(        % Assign 4 to the entries specified by that vector
</code>```

And for 2:

```<code>H        % Push 2
14       % Push 14
(        % Assign 2 to that entry
</code>```

We now have the matrix

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

To fill the upper half we exploit symmetry:

```<code>t!       % Duplicate and transpose
XR       % Keep the upper triangular part without the diagonal
+        % Add element-wise
</code>```

Step 2

The stack now contains the 8×8 matrix resulting from step 1. To extend this matrix we use indexing, this time in the two dimensions.

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

Step 3

The stack now contains the 15×15 matrix resulting from step 2.

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

Title: Draw an Empty Scrabble Board

Body:
MATL, <s>59</s> <s>54</s> 52 bytes

4t:g2I5vXdK8(3K23h32h(H14(t!XR+8: 7:Pht3$)'DtdTX.'w)

Try it online!

Explanation

The code follows three main steps:

Generate the 8x8 matrix

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

Extend it to the 15x15 matrix

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

Index the string 'DtdTX.' with that matrix to produce the desired result.

Step 1

4        % Push 4
t:       % Duplicate, range: pushes [1 2 3 4]
g        % Logical: convert to [1 1 1 1]
2I5      % Push 2, then 3, then 5
v        % Concatenate all stack vertically into vector [4 1 1 1 1 2 3 5]
Xd       % Generate diagonal matrix from that vector

Now we need to fill the nonzero off-diagonal entries. We will only fill those below the diagonal, and then make use symmetry to fill the others.

To fill each value we use linear indexing (see this answer, length-12 snippet). That means accessing the matrix as if it had only one dimension. For an 8×8 matrix, each value of the linear index refers to an entry as follows:

1   9         57
2  10         58
3  11
4
5  ...       ...
6
7             63
8  16 ... ... 64

So, the following assigns the value 4 to the lower-left entry:

K        % Push 4
8        % Push 8
(        % Assign 4 to the entry with linear index 8

The code for the value 3 is similar. In this case the index is a vector, because we need to fill several entries:

3        % Push 3
K        % Push 4
23h      % Push 23 and concatenate horizontally: [4 23]
32h      % Push 32 and concatenate horizontally: [4 23 32]
(        % Assign 4 to the entries specified by that vector

And for 2:

H        % Push 2
14       % Push 14
(        % Assign 2 to that entry

We now have the matrix

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

To fill the upper half we exploit symmetry:

t!       % Duplicate and transpose
XR       % Keep the upper triangular part without the diagonal
+        % Add element-wise

Step 2

The stack now contains the 8×8 matrix resulting from step 1. To extend this matrix we use indexing, this time in the two dimensions.

8:       % Push vector [1 2 ... 7 8]
7:P      % Push vector [7 6 ... 1]
h        % Concatenate horizontally: [1 2 ... 7 8 7 ... 2 1]. This will be the row index
t        % Duplicate. This will be the column index
3$       % Specify that the next function will take 3 inputs
)        % Index the 8×8 matrix with the two vectors. Gives a 15×15 matrix

Step 3

The stack now contains the 15×15 matrix resulting from step 2.

'DtdTX.' % Push this string
w        % Swap the two elements in the stack. This brings the matrix to the top
)        % Index the string with the matrix


答:
><> (Fish), 153 Bytes

```<code>\!o;!?l
\'T..d...T...d..T'a'.D...t...t...D.'a'..D...d.d...D..'a'd..D...d...D..d'a'....D.....D....'a'.t...t...t...t.'a'..d...d.d...d..'a'T..d...'
\'X/'02p
</code>```

A horribly, awfully, inefficient way of doing things. Currently looking into a way of shortening it down by mirroring both horizontally and vertically properly.

Try it online! (If you don't want to be there all day make sure you either set execution speed to max or run without the animation.)

Title: Draw an Empty Scrabble Board

Body:
><> (Fish), 153 Bytes

\!o;!?l
\'T..d...T...d..T'a'.D...t...t...D.'a'..D...d.d...D..'a'd..D...d...D..d'a'....D.....D....'a'.t...t...t...t.'a'..d...d.d...d..'a'T..d...'
\'X/'02p

A horribly, awfully, inefficient way of doing things. Currently looking into a way of shortening it down by mirroring both horizontally and vertically properly.

Try it online! (If you don't want to be there all day make sure you either set execution speed to max or run without the animation.)


答:
Perl 6, <s>92</s> <s>88</s> 87 bytes

<s>

```<code>{sub f(\i){my \n=first i%%*,2..i-1;n??n~f i/n!!i}
!.is-prime&&$_>1&&.comb.sum==.&f.comb.sum}
</code>```

</s>

```<code>{sub f(\i){my \n=first i%%*,2..^i;n??[n,|f i/n]!!|i}
$_>.&f>1&&.comb.sum==.&f.comb.sum}
</code>```

An anonymous function that returns a Bool.

Now does 100% manual factorization and primality checking.

Saved some bytes by testing both "input > 1" and "number of factors > 1" with one chained comparison, since m > Ω(m).

(try it online)

EDIT: -1 byte thanks to b2gills

Title: Is this a Smith number?

Body:
Challenge description

A Smith number is a composite number whose sum of digits is equal to the sum of sums of digits of its prime factors. Given an integer N, determine if it's a Smith number or not.

The first few Smith numbers are 4, 22, 27, 58, 85, 94, 121, 166, 202, 265, 274, 319, 346, 355, 378, 382, 391, 438 (sequence A006753 in OEIS).

Sample input / output

```<code>18: False (sum of digits: 1 + 8 = 9; factors: 2, 3, 3; sum of digits of factors: 2 + 3 + 3 = 8)
22: True
13: False (meets the digit requirement, but is prime)
666: True (sum of digits: 6 + 6 + 6 = 18; factors: 2, 3, 3, 37; sum of digits of factors: 2 + 3 + 3 + 3 + 7 = 18)
-265: False (negative numbers can't be composite)
0: False (not composite)
1: False (not composite)
4937775: True
</code>```

Notes

Your code can be a function (method) or a full working program,

Instead of words like True and False, you can use any truthy and falsy values, as long as it's clear what they are,

This is a code-golf challenge, so make your code as short as possible!

Body:
Perl 6, <s>92</s> <s>88</s> 87 bytes

<s>

{sub f(\i){my \n=first i%%*,2..i-1;n??n~f i/n!!i}
!.is-prime&&$_>1&&.comb.sum==.&f.comb.sum}

</s>

{sub f(\i){my \n=first i%%*,2..^i;n??[n,|f i/n]!!|i}
$_>.&f>1&&.comb.sum==.&f.comb.sum}

An anonymous function that returns a Bool.

Now does 100% manual factorization and primality checking.

Saved some bytes by testing both "input > 1" and "number of factors > 1" with one chained comparison, since m > Ω(m).

(try it online)

EDIT: -1 byte thanks to b2gills


问:
Tips for golfing in Ruby
What general tips can you give for golfing in Ruby?

I'm looking for ideas that can be applied to code golf problems in general that are specific to Ruby. (For example, "Remove comments" would not be an answer.)

Please post one tip per answer.

答:
Re(ab)use predefined globals

There is a whole bunch of predefined global variables that you can use instead of initialising new variables.

A very common example is that you have some golfed one-liner that loops, but you also need to keep a counter for later:

i=0
s.gsub!(/../){i+=1;"foo"}while s=~/.../
p i
```

<p>So frustrating. Luckily, <code>$.</code> comes to the rescue! It is initially <code>0</code>, and is incremented each time you read a line from input. This is of course incredibly useful if you actually need to keep track of the amount of lines you have read, but otherwise you can just manually update it:</p>

<pre class="lang-rb prettyprint-override"><code>s.gsub!(/../){$.+=1;"foo"}while s=~/.../
p$.
</code>```

That's 3 bytes saved.

If you for example need to append your counter to a string s, you may save some more bytes though string interpolation because the variable has a sigil:

i=0;i+=1;s+i.to_s
i=0;i+=1;s+"#{i}"
$.+=1;s+"#$."
```

Another interesting global is $:. It's an alias for $LOAD_PATH and is an array full of strings. I haven't actually used this in a golf yet, but I imagine it could come in handy if you need a cache for checking previously visited values or something, and don't care if it's completely empty. Your values are unlikely to crash with any of its initial contents anyways.

Title: Tips for golfing in Ruby

Body:
Re(ab)use predefined globals

There is a whole bunch of predefined global variables that you can use instead of initialising new variables.

A very common example is that you have some golfed one-liner that loops, but you also need to keep a counter for later:

i=0
s.gsub!(/../){i+=1;"foo"}while s=~/.../
p i

So frustrating. Luckily, $. comes to the rescue! It is initially 0, and is incremented each time you read a line from input. This is of course incredibly useful if you actually need to keep track of the amount of lines you have read, but otherwise you can just manually update it:

s.gsub!(/../){$.+=1;"foo"}while s=~/.../
p$.

That's 3 bytes saved.

If you for example need to append your counter to a string s, you may save some more bytes though string interpolation because the variable has a sigil:

i=0;i+=1;s+i.to_s
i=0;i+=1;s+"#{i}"
$.+=1;s+"#$."

Another interesting global is $:. It's an alias for $LOAD_PATH and is an array full of strings. I haven't actually used this in a golf yet, but I imagine it could come in handy if you need a cache for checking previously visited values or something, and don't care if it's completely empty. Your values are unlikely to crash with any of its initial contents anyways.


答:
><> (Fish), 28 Bytes

```<code>l3-0=?v0n;>
?+1-@:<;n1^?+2-!
</code>```

Input is via an execution argument to add each digit to stack, left to right.

Checks if the length of the stack (number) is three, then that there's a difference of one between the third and second digits, then that there's a difference of two between the first and third digits.

Try it online!

Title: As Easy as One-Two-Three

Body:
Write a program or function that takes in a positive integer. You can assume the input is valid and may take it as a string. If the number is any of

```<code>123
234
345
456
567
678
789
</code>```

then output a truthy value. Otherwise, output a falsy value. For example, the inputs

```<code>1
2
3
12
122
124
132
321
457
777
890
900
1011
1230
1234
</code>```

must all result in falsy output. (The input will not have leading zeroes so you needn't worry about things like 012.)

The shortest code in bytes wins.

Body:
><> (Fish), 28 Bytes

l3-0=?v0n;>
?+1-@:<;n1^?+2-!

Input is via an execution argument to add each digit to stack, left to right.

Checks if the length of the stack (number) is three, then that there's a difference of one between the third and second digits, then that there's a difference of two between the first and third digits.

Try it online!


问:
Help: Aliens Programmers only speak ASCII

Setting the Scene:

It is an average afternoon, as you unwind after a long day by engaging in your favorite pastime: answering the plethora of captivating questions on PPCG. It hasn't been a good day for you; those damned Pyth programmers keep getting best answer and it's killing your vibe. Suddenly, you notice a new question has been posted! You make up your mind; not this time CJammers. Furiously, you begin to type, birthing a stream of characters; a fetus of the glorious BrainFuck loop that your end product will be. You type and type. Faster! Faster still! You're so focused you don't even notice the lights on your screen start to flicker on and off. Suddenly, the monitor glows green, an alien like symbol branded upon the desktop. Using your impeccable skills you cat ~/Desktop/aliensymbol and get presented with a bunch of numbers, a message! Being the shrewd PPCG programmer that you are, you notice that it looks like ASCII. No matter for you, you print(chr(i) for i in file) and decipher the message. Your first thought: "I need to share this with the community!".

...

Who would've thought it? That the first people to make contact with aliens would be the humble programmers of PPCG. Why us? Maybe it is because we are the epitome of human intelligence. Or maybe because BrainFuck is about as close as we have to an alien language. Nevertheless, the aliens - being the ultra-intelligent life forms that they are - want to test whether they should classify the human race as  intelligent or not. As a test of our mental prowess, the aliens have asked us to send them a few computer programs to demonstrate that we are technologically cultured. The issue is, the only human language they understand is numerical ASCII!

Help humankind show those creatures who the real intellectual alpha is. We need to send them a script that will convert our text based source codes into their numerical ASCII versions. Unfortunately, due to our underdeveloped technology (thanks Obama), we must send as small a translating program as possible. Good thing they chose to contact PPCG!

The Challenge:

The premise of this challenge is simple: you are to write a program that will take any program's source code (or any general text file for that matter), and output a space separated version of it with an ASCII translation below each line. That is, given an input of a text file, you need to output each line of that file followed by a line containing the ASCII representation of each character in the line above it (with each number lining up with the character it represents).

An example will greatly clarify this. Taking the source code of the infamous hello world as the input:

```<code>#include <stdio.h>

int main() {
    printf("hello, world\n");
    return 0;
}
</code>```

your program should output:

```<code>#   i   n   c   l   u   d   e       <   s   t   d   i   o   .   h   >
35  105 110 99  108 117 100 101 32  60  115 116 100 105 111 46  104 62  10

10
i   n   t       m   a   i   n   (   )       {
105 110 116 32  109 97  105 110 40  41  32  123 10
                p   r   i   n   t   f   (   "   h   e   l   l   o   ,       w   o   r   l   d   \   n   "   )   ;
32  32  32  32  112 114 105 110 116 102 40  34  104 101 108 108 111 44  32  119 111 114 108 100 92  110 34  41  59  10
                r   e   t   u   r   n       0   ;
32  32  32  32  114 101 116 117 114 110 32  48  59  10
}
125 10
</code>```

Implementation Details:

You may choose to take the input in whatever form you wish (opening file, command line pipe, function parameter etc.) and you should output to stdout or return the output from a function.

Things to note

Each character in the output is separated by a '\t' to allow for the space of 3 digits in the line below to line up (we are going to assume your tab is set to 4 spaces or more).

The newlines are displayed on the line that the return key was pressed (notice the 10's in the example)

The '\t' and '\n' printing requirements are lax. Your output must, in the general sense, look pleasing to the eye (need to show those aliens we have aesthetic sense as well), and if you can bend the previous two points while maintaining visual integrity, you will be forgiven.

You can choose to assume whether or not there is a newline at the end of the last line.

Scoring

This is code-golf so shortest program wins. Note, even if your program isn't the shortest, but uses really neat tricks relative to the language you are using, many +1's to you!

Good luck. The intergalactic intelligence ranking of humanity rests on your shoulders.

Note: Please forgive the plot holes. I'm not a writer :D

答:
PowerShell v2+, 85 bytes

```<code>gc $args|%{$a=$b='';$_-split'(.)'-ne''|%{$a+="$_`t";$b+="$(+[char]$_)`t"};$a;$b+"10"}
</code>```

Input is via a path to a file. We then Get-Content (alias gc) on that file, which automatically splits on newlines. We loop over each of those |%{...}. Start by setting $a and $b to an empty string -- these are our ASCII characters and code points respectively. We then -split the input line on every character, keeping it (.), and removing the empty values -ne'' (it's due to how .NET regex parses), then send those into another loop.

Each inner loop, we string concatenate the current character with a tab `t and add that onto $a. Similarly for $b, excepting we're explicitly casting as a char and then as an int +.

Outside the inner loop, we place the resulting $a and $b (with a linefeed designator, since that'll never come up in our looping) on the pipeline. Those are gathered up with an implicit Write-Output at program completion.

Example

(with the understanding that I've got a trailing linefeed and Markdown mangles the tab character)

```<code>PS C:\Tools\Scripts\golfing> .\aliens-only-understand-ascii.ps1 '.\aliens-only-understand-ascii.txt'
#   i   n   c   l   u   d   e       <   s   t   d   i   o   .   h   >
35  105 110 99  108 117 100 101 32  60  115 116 100 105 111 46  104 62  10

10
i   n   t       m   a   i   n   t   (   )       {
105 110 116 32  109 97  105 110 116 40  41  32  123 10
                p   r   i   n   t   f   (   "   h   e   l   l   o   w   ,       w   o   r   l   d   \   n   "   )   ;
32  32  32  32  112 114 105 110 116 102 40  34  104 101 108 108 111 119 44  32  119 111 114 108 100 92  110 34  41  59  10
                r   e   t   u   r   n       0   ;
32  32  32  32  114 101 116 117 114 110 32  48  59  10
}
125 10
</code>```

Body:
PowerShell v2+, 85 bytes

gc $args|%{$a=$b='';$_-split'(.)'-ne''|%{$a+="$_`t";$b+="$(+[char]$_)`t"};$a;$b+"10"}

Input is via a path to a file. We then Get-Content (alias gc) on that file, which automatically splits on newlines. We loop over each of those |%{...}. Start by setting $a and $b to an empty string -- these are our ASCII characters and code points respectively. We then -split the input line on every character, keeping it (.), and removing the empty values -ne'' (it's due to how .NET regex parses), then send those into another loop.

Each inner loop, we string concatenate the current character with a tab `t and add that onto $a. Similarly for $b, excepting we're explicitly casting as a char and then as an int +.

Outside the inner loop, we place the resulting $a and $b (with a linefeed designator, since that'll never come up in our looping) on the pipeline. Those are gathered up with an implicit Write-Output at program completion.

Example

(with the understanding that I've got a trailing linefeed and Markdown mangles the tab character)

PS C:\Tools\Scripts\golfing> .\aliens-only-understand-ascii.ps1 '.\aliens-only-understand-ascii.txt'
#   i   n   c   l   u   d   e       <   s   t   d   i   o   .   h   >
35  105 110 99  108 117 100 101 32  60  115 116 100 105 111 46  104 62  10

10
i   n   t       m   a   i   n   t   (   )       {
105 110 116 32  109 97  105 110 116 40  41  32  123 10
                p   r   i   n   t   f   (   "   h   e   l   l   o   w   ,       w   o   r   l   d   \   n   "   )   ;
32  32  32  32  112 114 105 110 116 102 40  34  104 101 108 108 111 119 44  32  119 111 114 108 100 92  110 34  41  59  10
                r   e   t   u   r   n       0   ;
32  32  32  32  114 101 116 117 114 110 32  48  59  10
}
125 10


答:
Javascript (ES6), 150 bytes

```<code>_=>(r='',"T2d3T3d2T.D3t3t3D3D3d.d3D2d2D3d3D2d4D5D5t3t3t3t3d3d.d3d2T2d3".replace(/./g,c=>(c=+c?'.'.repeat(c):c,r=c+r,c))+'X'+r).match(/.{15}/g).join`
`
</code>```

How it works

The string "T2d3T3d2T.D3t3t3D3D3d.d3D2d2D3d3D2d4D5D5t3t3t3t3d3d.d3d2T2d3" describes the board from its top left corner to the square just before the 'X', with consecutive empty squares encoded as digits. The replace() function both unpacks the empty squares and builds the mirror string r for the bottom of the board. Then both parts are put together and carriage returns are inserted every 15 characters.

Demo

let f =
_=>(r='',"T2d3T3d2T.D3t3t3D3D3d.d3D2d2D3d3D2d4D5D5t3t3t3t3d3d.d3d2T2d3".replace(/./g,c=>(c=+c?'.'.repeat(c):c,r=c+r,c))+'X'+r).match(/.{15}/g).join`
`
console.log(f())```

Title: Draw an Empty Scrabble Board

Body:
Javascript (ES6), 150 bytes

_=>(r='',"T2d3T3d2T.D3t3t3D3D3d.d3D2d2D3d3D2d4D5D5t3t3t3t3d3d.d3d2T2d3".replace(/./g,c=>(c=+c?'.'.repeat(c):c,r=c+r,c))+'X'+r).match(/.{15}/g).join`
`

How it works

The string "T2d3T3d2T.D3t3t3D3D3d.d3D2d2D3d3D2d4D5D5t3t3t3t3d3d.d3d2T2d3" describes the board from its top left corner to the square just before the 'X', with consecutive empty squares encoded as digits. The replace() function both unpacks the empty squares and builds the mirror string r for the bottom of the board. Then both parts are put together and carriage returns are inserted every 15 characters.

Demo

let f =
_=>(r='',"T2d3T3d2T.D3t3t3D3D3d.d3D2d2D3d3D2d4D5D5t3t3t3t3d3d.d3d2T2d3".replace(/./g,c=>(c=+c?'.'.repeat(c):c,r=c+r,c))+'X'+r).match(/.{15}/g).join`
`
console.log(f())


Title: Draw an Empty Scrabble Board

Body:
brainfuck, <s>598</s> <s>596</s> 590 bytes

Golfing tips welcome.

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

Explanation

Initialize the tape to [10 116 68 46 100 84 92] i.e. [nl t D . d T \]

>-[++++[<]>->+]<[>++++>+++++>+++>++<<<<-]>[>>>>+>+>+<<<<<<-]<++++++++++[>+>>>>+>-<<<<<<-]>>+>->>-->++

Each line here then prints one line of the board.

The middle line also decreases 92 to 88 i.e. \ to X

.<<..>.<...>>.<<...>.<..>>.<<<<<.
>>>.<.>...<<.>>...<<.>>...<.>.<<<.
>>>..<.>...>.<.>.<...<.>..<<<.
>>>>.<..<.>...>.<...<.>..>.<<<<.
>>>....<.>.....<.>....<<<.
>>>.<<.>>...<<.>>...<<.>>...<<.>>.<<<.
>>>..>.<...>.<.>.<...>.<..<<<.
>>>>>.<<..>.<...>>>----.<<<...>.<..>>.<<<<<.
>>>..>.<...>.<.>.<...>.<..<<<.
>>>.<<.>>...<<.>>...<<.>>...<<.>>.<<<.
>>>....<.>.....<.>....<<<.
>>>>.<..<.>...>.<...<.>..>.<<<<.
>>>..<.>...>.<.>.<...<.>..<<<.
>>>.<.>...<<.>>...<<.>>...<.>.<<<.
>>>>>.<<..>.<...>>.<<...>.<..>>.

<a href="http://brainfuck.tryitonline.net/#code=Pi1bKysrK1s8XT4tPitdPFs-KysrKz4rKysrKz4rKys-Kys8PDw8LV0-Wz4-Pj4rPis-Kzw8PDw8PC1dPCsrKysrKysrKytbPis-Pj4-Kz4tPDw8PDw8LV0-Pis-LT4-LS0-KysuPDwuLj4uPC4uLj4-Ljw8Li4uPi48Li4-Pi48PDw8PC4-Pj4uPC4-Li4uPDwuPj4uLi48PC4-Pi4uLjwuPi48PDwuPj4-Li48Lj4uLi4-LjwuPi48Li4uPC4-Li48PDwuPj4-Pi48Li48Lj4uLi4-LjwuLi48Lj4uLj4uPDw8PC4-Pj4uLi4uPC4-Li4uLi48Lj4uLi4uPDw8Lj4-Pi48PC4-Pi4uLjw8Lj4-Li4uPDwuPj4uLi48PC4-Pi48PDwuPj4-Li4-LjwuLi4-LjwuPi48Li4uPi48Li48PDwuPj4-Pj4uPDwuLj4uPC4uLj4-Pi0tLS0uPDw8Li4uPi48Li4-Pi48PDw8PC4-Pj4uLj4uPC4uLj4uPC4-LjwuLi4-LjwuLjw8PC4-Pj4uPDwuPj4uLi48PC4-Pi4uLjw8Lj4-Li4uPDwuPj4uPDw8Lj4-Pi4uLi48Lj4uLi4uLjwuPi4uLi48PDwuPj4-Pi48Li48Lj4uLi4-LjwuLi48Lj4uLj4uPDw8PC4-Pj4uLjwuPi4uLj4uPC4-LjwuLi48Lj4uLjw8PC4-Pj4uPC4-Li4uPDwuPj4uLi48PC4-Pi4uLjwuPi48PDwuPj4-Pj4uPDwuLj4uPC4uLj4-Ljw8Li4uPi48Li4-Pi4&input=" rel="nofollow">Try it online!


问:
Subtract the next numbers

Description

Subtract the next P numbers from a N number. The next number of N is N + 1.

Look at the examples to get what I mean.

Examples:

```<code>Input: N=2,P=3
Calculate: n - (n+1) - (n+2) - (n+3)     //Ending with 3, because P=3
Calculate: 2 -  2+1  -  2+2  - 2+3       //Replacing N with 2 from Input
Calculate: 2 -  3    -  4    - 5
Output: -10

Input: N=100,P=5
Calculate: n - (n+1) - (n+2) - (n+3) - (n+4) - (n+5)
Calculate: 100-  101 -  102  -  103  -  104  - 105
Output: -415

Input: N=42,P=0
Calculate: n
Calculate: 42
Output: 42

Input: N=0,P=3
Calculate: n - (n+1) - (n+2) - (n+3)
Calculate: 0 -  1    -  2    -  3
Output: -6

Input: N=0,P=0
Calulate: n
Calculate: 0
Output: 0
</code>```

Input:

N: Integer, positive, negative or 0

P: Integer, positive or 0, not negative

Output:

Integer or String, leading 0 allowed, trailing newline allowed

Rules:

No loopholes

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

Input and Output must be as described

答:
Clojure/Clojurescript, 30 bytes

```<code>#(reduce -(range %(+ 1 % %2)))
</code>```

The straightforward approach is shorter than the mathematically clever ones.

Title: Subtract the next numbers

Body:
Clojure/Clojurescript, 30 bytes

#(reduce -(range %(+ 1 % %2)))

The straightforward approach is shorter than the mathematically clever ones.


答:
PHP, <s>131</s> 115 bytes

Just a FGITW, maybe I can improve upon it more. Turns out, I can!

First version at 131 bytes:

```<code><?$s=file($argv[1]);foreach($s as$l){$a=str_split(trim($l));echo join(' ',$a).'
';$i=0;while($c=ord($l{$i++}))echo$c.'  ';echo'
';};
</code>```

The filename is supplied as the first argument after the script name: php aliens.php helloworld.c

Second version at 115 bytes:

```<code>function($s){foreach($s as$l){$a=str_split($l);echo join('  ',$a);$i=0;while($c=ord($a[$i++]))echo$c.'  ';echo'
';}};
</code>```

The first version accounts for missing newlines at the end of the line, but after the additional clarification, we can leave that code out and put everything in a function to save 16 bytes.

The whitespace characters in join('    ',$a) as well as in echo$c.'  ' are tab characters = \t. The newlines in the code are on purpose.

Title: Help: Aliens Programmers only speak ASCII

Body:
Setting the Scene:

It is an average afternoon, as you unwind after a long day by engaging in your favorite pastime: answering the plethora of captivating questions on PPCG. It hasn't been a good day for you; those damned Pyth programmers keep getting best answer and it's killing your vibe. Suddenly, you notice a new question has been posted! You make up your mind; not this time CJammers. Furiously, you begin to type, birthing a stream of characters; a fetus of the glorious BrainFuck loop that your end product will be. You type and type. Faster! Faster still! You're so focused you don't even notice the lights on your screen start to flicker on and off. Suddenly, the monitor glows green, an alien like symbol branded upon the desktop. Using your impeccable skills you cat ~/Desktop/aliensymbol and get presented with a bunch of numbers, a message! Being the shrewd PPCG programmer that you are, you notice that it looks like ASCII. No matter for you, you print(chr(i) for i in file) and decipher the message. Your first thought: "I need to share this with the community!".

...

Who would've thought it? That the first people to make contact with aliens would be the humble programmers of PPCG. Why us? Maybe it is because we are the epitome of human intelligence. Or maybe because BrainFuck is about as close as we have to an alien language. Nevertheless, the aliens - being the ultra-intelligent life forms that they are - want to test whether they should classify the human race as  intelligent or not. As a test of our mental prowess, the aliens have asked us to send them a few computer programs to demonstrate that we are technologically cultured. The issue is, the only human language they understand is numerical ASCII!

Help humankind show those creatures who the real intellectual alpha is. We need to send them a script that will convert our text based source codes into their numerical ASCII versions. Unfortunately, due to our underdeveloped technology (thanks Obama), we must send as small a translating program as possible. Good thing they chose to contact PPCG!

The Challenge:

The premise of this challenge is simple: you are to write a program that will take any program's source code (or any general text file for that matter), and output a space separated version of it with an ASCII translation below each line. That is, given an input of a text file, you need to output each line of that file followed by a line containing the ASCII representation of each character in the line above it (with each number lining up with the character it represents).

An example will greatly clarify this. Taking the source code of the infamous hello world as the input:

```<code>#include <stdio.h>

int main() {
    printf("hello, world\n");
    return 0;
}
</code>```

your program should output:

```<code>#   i   n   c   l   u   d   e       <   s   t   d   i   o   .   h   >
35  105 110 99  108 117 100 101 32  60  115 116 100 105 111 46  104 62  10

10
i   n   t       m   a   i   n   (   )       {
105 110 116 32  109 97  105 110 40  41  32  123 10
                p   r   i   n   t   f   (   "   h   e   l   l   o   ,       w   o   r   l   d   \   n   "   )   ;
32  32  32  32  112 114 105 110 116 102 40  34  104 101 108 108 111 44  32  119 111 114 108 100 92  110 34  41  59  10
                r   e   t   u   r   n       0   ;
32  32  32  32  114 101 116 117 114 110 32  48  59  10
}
125 10
</code>```

Implementation Details:

You may choose to take the input in whatever form you wish (opening file, command line pipe, function parameter etc.) and you should output to stdout or return the output from a function.

Things to note

Each character in the output is separated by a '\t' to allow for the space of 3 digits in the line below to line up (we are going to assume your tab is set to 4 spaces or more).

The newlines are displayed on the line that the return key was pressed (notice the 10's in the example)

The '\t' and '\n' printing requirements are lax. Your output must, in the general sense, look pleasing to the eye (need to show those aliens we have aesthetic sense as well), and if you can bend the previous two points while maintaining visual integrity, you will be forgiven.

You can choose to assume whether or not there is a newline at the end of the last line.

Scoring

This is code-golf so shortest program wins. Note, even if your program isn't the shortest, but uses really neat tricks relative to the language you are using, many +1's to you!

Good luck. The intergalactic intelligence ranking of humanity rests on your shoulders.

Note: Please forgive the plot holes. I'm not a writer :D

Body:
PHP, <s>131</s> 115 bytes

Just a FGITW, maybe I can improve upon it more. Turns out, I can!

First version at 131 bytes:

<?$s=file($argv[1]);foreach($s as$l){$a=str_split(trim($l));echo join(' ',$a).'
';$i=0;while($c=ord($l{$i++}))echo$c.'  ';echo'
';};

The filename is supplied as the first argument after the script name: php aliens.php helloworld.c

Second version at 115 bytes:

function($s){foreach($s as$l){$a=str_split($l);echo join('  ',$a);$i=0;while($c=ord($a[$i++]))echo$c.'  ';echo'
';}};

The first version accounts for missing newlines at the end of the line, but after the additional clarification, we can leave that code out and put everything in a function to save 16 bytes.

The whitespace characters in join('    ',$a) as well as in echo$c.'  ' are tab characters = \t. The newlines in the code are on purpose.


Title: Draw an Empty Scrabble Board

Body:
C 234 Bytes

#define g(t) while(i++<8)putchar(*b++);b-=2;--i;while(--i>0)putchar(*b--);putchar('\n');b+=t;
char*r="T..d...T.D...t....D...d.d..D...d....D....t...t....d...d.T..d...X";i;f(){char*b=r;do{g(9);}while(*b);b-=16;do{g(-7);}while(b>=r);}

Here's the output:

T..d...T...d..T
.D...t...t...D.
..D...d.d...D..
d..D...d...D..d
....D.....D....
.t...t...t...t.
..d...d.d...d..
T..d...X...d..T
..d...d.d...d..
.t...t...t...t.
....D.....D....
d..D...d...D..d
..D...d.d...D..
.D...t...t...D.
T..d...T...d..T


答:
Vim, <s>86,</s> 77 keystrokes

```<code>:g/^/norm A<C-v><C-v>10<C-v><esc>Yp:s/./\=char2nr(submatch(0))."\t"/g<C-v><cr>k:s/./&\t/g<C-v><cr>
:%s/<C-v><cr>0<cr>
</code>```

This is way too long, but that's what you get when you use vim's eval feature (\=).

Body:
Vim, <s>86,</s> 77 keystrokes

:g/^/norm A<C-v><C-v>10<C-v><esc>Yp:s/./\=char2nr(submatch(0))."\t"/g<C-v><cr>k:s/./&\t/g<C-v><cr>
:%s/<C-v><cr>0<cr>

This is way too long, but that's what you get when you use vim's eval feature (\=).


答:
Python 2, 105 bytes

This uses a slightly different approach than the OP's answer. Note that SO messes up my literal tabs with spaces.

def f(s):
 o=x=''
 for c in s:
    o+=c+"  ";x+="%s    "%ord(c)
    if"\n"==c:print o[:-1],x;o=x=''
 print o+"\n"+x
```

Try it online

Body:
Python 2, 105 bytes

This uses a slightly different approach than the OP's answer. Note that SO messes up my literal tabs with spaces.

def f(s):
 o=x=''
 for c in s:
    o+=c+"  ";x+="%s    "%ord(c)
    if"\n"==c:print o[:-1],x;o=x=''
 print o+"\n"+x

Try it online


问:
Minesweeper At Work
Everyone knows the old minesweeper game that shipped with Windows XP. It's a simple grid with a 9x9 matrix of cells containing either a number (indicating how many mines are adjacent to it) or a mine.

The challenge is to generate a random 9x9 grid with 10 bombs given any integer seed (up to whatever your machine/language's largest int is) with brownie points if you implement the PRNG yourself

example output: cells contain either numerals 0-8 or * for mines

```<code>*101*1000
110111000
123210000
1***10000
123210011
00000002*
00000114*
000112*3*
0001*2121
</code>```

Shortest code in bytes wins.. standard rules etc, etc..

答:
Python 2, <s>269</s> <s>266</s> 264 bytes

from random import*
seed(input())
z=1,0,-1
n=range(9)
m=[[0]*9 for _ in n]
for x,y in sample([[x,y]for x in n for y in n],10):
 m[x][y]=-9
 for a in z:
  for b in z:
    if 0<=x+a<9>0<=y+b<9:m[x+a][y+b]+=1 # it gets displayed as 4 spaces, but the beginning of this line is a single tab
print("\n".join("".join([`c`,'*'][c<0]for c in l)for l in m))
```

Try it on ideone.com

Saved 2 bytes thanks to Aaron.

Most likely still golfable.

Explanation

random is imported for using seed to seed the PRNG and sample to select ten bomb locations randomly. m is a 9 x 9 matrix saving the board. For each of the bomb locations, the corresponding entry in m gets set to -9 and all neighbouring entries get incremented. This way m ends up containing the count of adjacent bombs for non-bomb cells and a negative number for bomb cells. The final print prints the whole board by iterating through all lines l in m and all cells c in l.

Title: Minesweeper At Work

Body:
Python 2, <s>269</s> <s>266</s> 264 bytes

from random import*
seed(input())
z=1,0,-1
n=range(9)
m=[[0]*9 for _ in n]
for x,y in sample([[x,y]for x in n for y in n],10):
 m[x][y]=-9
 for a in z:
  for b in z:
    if 0<=x+a<9>0<=y+b<9:m[x+a][y+b]+=1 # it gets displayed as 4 spaces, but the beginning of this line is a single tab
print("\n".join("".join([`c`,'*'][c<0]for c in l)for l in m))

Try it on ideone.com

Saved 2 bytes thanks to Aaron.

Most likely still golfable.

Explanation

random is imported for using seed to seed the PRNG and sample to select ten bomb locations randomly. m is a 9 x 9 matrix saving the board. For each of the bomb locations, the corresponding entry in m gets set to -9 and all neighbouring entries get incremented. This way m ends up containing the count of adjacent bombs for non-bomb cells and a negative number for bomb cells. The final print prints the whole board by iterating through all lines l in m and all cells c in l.