Title: Write a program that always prints N when it is shifted N times up the ASCII alphabet

Body:
Write a program using only printable ASCII characters that takes no input. For reference, here are the 95 printable ASCII characters in order:

```<code> !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
</code>```

When your program is run it should print 0 (plus an optional trailing newline) to stdout, then terminate normally.

When each character in your program is replaced by the character N spaces to its right in printable ASCII, looping around from ~ to space, the resulting printable ASCII string will ideally be a program runnable in the same language that takes no input and outputs N (plus an optional trailing newline) to stdout, then terminates normally, for N = 1 to 94.

For example, if your original program was

```<code>@Cat~(88 !)
</code>```

running it should output 0 and shifting all the characters up the printable ASCII scale by one

```<code>ADbu )99!"*
</code>```

should result in another program that outputs 1. Doing so again will ideally result in another program that outputs 2

```<code>BEcv!*::"#+
</code>```

and so on with 3 and 4, etc. up to the point of shifting 94 times

```<code>?B`s}'77~ (
</code>```

which ideally is a program that outputs 94.

The relief is that this is only the ideal behavior. Your program and its 94 derivatives do not all need to work, but the more that consecutively do from the start the better. (Programs that do not work may have any behavior whatsoever.)

Scoring

Your score is the number of consecutive programs starting from the original (the one that outputs 0) that do work, i.e. correctly output their corresponding N. The answer with the highest score (a maximum of 95) wins. If there's a tie then the program with the shortest length in bytes wins.

For example, if @Cat~(88 !) output 0 and ADbu )99!"* output 1 but BEcv!*::"#+ errored, then your score would be 2. It's 2 even if ?B`s}'77~ ( accurately outputs 94 and even if all the programs for N = 30 to 40 worked. Only the consecutive number of working programs, starting at zero, are counted.

Notes

To combat potential contention and loopholes, competing answers must output their numbers in decimal with no leading zeroes or signs or decimal points (i.e. plain 0 1 2 ... 94).

Languages that use different bases or number formats are allowed but are not eligible to win.

The presence of an optional trailing newline does not need to be consistent across programs.

Functions and REPL commands are not allowed, only full programs.


问:
Generate a "GitHub" Avatar

Background / Description

Note: as @HelkaHomba points out, the actual GitHub identicons are not actually random but based on the hash of a username

The default GitHub avatar is a 5x5-pixel image. A color is picked randomly, and then random pixels are filled in on one side (right or left, 2x5 size) using that color. Then that side is copied & flipped to the other side, across the y-axis. The pixels left over that are not filled in are #F0F0F0, or rgb(240,240,240).

The center column's pixels (1x5 size) are then randomly filled in, using the same color as previously.

Output

Note: for this challenge we will ignore the space that encloses the GitHub avatars

The program should output a 5x5 pixel image file. See http://meta.codegolf.stackexchange.com/a/9095/42499 for specifics

Examples

Note: these were obviously scaled up from 5x5 so you can see them

Good luck!

答:
MATLAB, 102 bytes

Hi, this is my matlab solution:

```<code>p=@(x)(imwrite(floor(randi(2,5,2)*[eye(2) ones(2,1)./2 fliplr(eye(2))]),[0.9412*[1 1 1];rand(1,3)],x))
</code>```

The input x of the function is the name of the output file. For example:

```<code>p('output.png')
</code>```

produces a png image called 'output.png'.

Here the results of some executions of this code.

ContentLicense: CC BY-SA 3.0

Title: Generate a "GitHub" Avatar

Body:
MATLAB, 102 bytes

Hi, this is my matlab solution:

p=@(x)(imwrite(floor(randi(2,5,2)*[eye(2) ones(2,1)./2 fliplr(eye(2))]),[0.9412*[1 1 1];rand(1,3)],x))

The input x of the function is the name of the output file. For example:

p('output.png')

produces a png image called 'output.png'.

Here the results of some executions of this code.


答:
Perl 5, 77 bytes

This is non-competing as it only has a 256 colour palette, only works on terminals that support ANSI escape codes and doesn't actually output a 5 pixel square image, but I thought I'd post it anyway as it was fun golfing this down.

sub x{"\e[48;5;@{[rand>.5?$-||=rand 254:254]}m  "}say$}=x,$b=x,x,$b,$}for 0..4
```

<p><strong>Note:</strong> the <code>\e</code> is actually ASCII char <code>\x1B</code>.</p>

<h3>Usage</h3>

<pre class="lang-sh prettyprint-override"><code>perl -E 'sub x{"\e[48;5;@{[rand>.5?$-||=rand 254:254]}m  "}say$}=x,$b=x,x,$b,$}for 0..4'
</code>```

Explanation

Nothing particularly clever except perhaps:

Use $- to automatically round the colour number for use in the escape sequence, used instead of $n=0|rand 254.

Example output

Title: Generate a "GitHub" Avatar

Body:
Background / Description

Note: as @HelkaHomba points out, the actual GitHub identicons are not actually random but based on the hash of a username

The default GitHub avatar is a 5x5-pixel image. A color is picked randomly, and then random pixels are filled in on one side (right or left, 2x5 size) using that color. Then that side is copied & flipped to the other side, across the y-axis. The pixels left over that are not filled in are #F0F0F0, or rgb(240,240,240).

The center column's pixels (1x5 size) are then randomly filled in, using the same color as previously.

Output

Note: for this challenge we will ignore the space that encloses the GitHub avatars

The program should output a 5x5 pixel image file. See http://meta.codegolf.stackexchange.com/a/9095/42499 for specifics

Examples

Note: these were obviously scaled up from 5x5 so you can see them

Good luck!

Body:
Perl 5, 77 bytes

This is non-competing as it only has a 256 colour palette, only works on terminals that support ANSI escape codes and doesn't actually output a 5 pixel square image, but I thought I'd post it anyway as it was fun golfing this down.

sub x{"\e[48;5;@{[rand>.5?$-||=rand 254:254]}m  "}say$}=x,$b=x,x,$b,$}for 0..4

Note: the \e is actually ASCII char \x1B.

Usage

perl -E 'sub x{"\e[48;5;@{[rand>.5?$-||=rand 254:254]}m  "}say$}=x,$b=x,x,$b,$}for 0..4'

Explanation

Nothing particularly clever except perhaps:

Use $- to automatically round the colour number for use in the escape sequence, used instead of $n=0|rand 254.

Example output

ContentLicense: CC BY-SA 4.0


问:
Find the Factorial!
Create the shortest program or function that finds the factorial of a non-negative integer.

The factorial, represented with ! is defined as such

$$n!:=\begin{cases}1 & n=0\\n\cdot(n-1)!&n>0\end{cases}$$

In plain English the factorial of 0 is 1 and the factorial of n, where n is larger than 0 is n times the factorial of one less than n.

Your code should perform input and output using a standard methods.

Requirements:

Does not use any built-in libraries that can calculate the factorial (this includes any form of eval)

Can calculate factorials for numbers up to 125

Can calculate the factorial for the number 0 (equal to 1)

Completes in under a minute for numbers up to 125

The shortest submission wins, in the case of a tie the answer with the most votes at the time wins.

答:
Racket (scheme) 40 35 29 bytes

Computes 0! to be 1, and computes 125! in 0 seconds according to timer. Regular recursive approach

```<code>(define(f n)(if(= n 0)1(* n(f(- n 1)))))
</code>```

New version to beat common lisp: multiplies all elements of a list (same as that Haskell solution)

```<code>(λ(n)(apply *(build-list n add1)))
</code>```

Newer version to beat the other scheme solution and math the other racket solution by using foldl instead of apply and using range instead of buildlist

```<code>(λ(n)(foldl * n(range 1 n)))
</code>```

Title: Find the Factorial!

Body:
Racket (scheme) 40 35 29 bytes

Computes 0! to be 1, and computes 125! in 0 seconds according to timer. Regular recursive approach

(define(f n)(if(= n 0)1(* n(f(- n 1)))))

New version to beat common lisp: multiplies all elements of a list (same as that Haskell solution)

(λ(n)(apply *(build-list n add1)))

Newer version to beat the other scheme solution and math the other racket solution by using foldl instead of apply and using range instead of buildlist

(λ(n)(foldl * n(range 1 n)))


问:
Remainder When N divided by 2^M
Write the shortest code to find the remainder when an input number N is divided by 2^M. You cannot use /,* and % operator.</p>

```<code>Input Specification
Number of test cases followed by a pair of integers on each line.

Sample Input
1
150 6

Sample Output
22

Limits
1<T<1000
1<N<2^31
1<B<31

Time Limit
1 Sec
</code>```

答:
Racket (scheme) 29 bytes

Kinda cheating because racket doesn't even have the % operator:

```<code>(λ(n m)(modulo n(expt 2 m)))
</code>```

ContentLicense: CC BY-SA 2.5

Title: Remainder When N divided by 2^M

Body:
Racket (scheme) 29 bytes

Kinda cheating because racket doesn't even have the % operator:

(λ(n m)(modulo n(expt 2 m)))


问:
Product over a range
Your task is simple: given two integers \$a\$ and \$b\$, output \$\Pi[a,b]\$; that is, the product of the range between \$a\$ and \$b\$. You may take \$a\$ and \$b\$ in any reasonable format, whether that be arguments to a function, a list input, STDIN, et cetera. You may output in any reasonable format, such as a return value (for functions) or STDOUT. \$a\$ will always be less than \$b\$.

Note that the end may be exclusive or inclusive of \$b\$. I'm not picky. ^_^

Test cases

```<code>[a,b) => result
[2,5) => 24
[5,10) => 15120
[-4,3) => 0
[0,3) => 0
[-4,0) => 24

[a,b] => result
[2,5] => 120
[5,10] => 151200
[-4,3] => 0
[0,3] => 0
[-4,-1] => 24
</code>```

This is a code-golf, so the shortest program in bytes wins.

Leaderboard

The Stack Snippet at the bottom of this post generates the catalog 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>## [><>](http://esolangs.org/wiki/Fish), 121 bytes
</code>```

var QUESTION_ID=66202,OVERRIDE_USER=44713;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

```

答:
Racket (scheme), 29 bytes

Functional programming woot

Apply applies a function to all elements of a list, and range creates a list ranging from a to b. The function being applied is *. Exclusive.

```<code>(λ(a b)(apply *(range a b)))
</code>```

Title: Product over a range

Body:
Racket (scheme), 29 bytes

Functional programming woot

Apply applies a function to all elements of a list, and range creates a list ranging from a to b. The function being applied is *. Exclusive.

(λ(a b)(apply *(range a b)))


答:
Swift 2.3, <s>593</s> 585 bytes

```<code>var t = 0,g = UIGraphicsGetCurrentContext(),c = UIColor(hue:CGFloat(drand48()),saturation:1,brightness:1,alpha:1).CGColor
srand48(time(&t))
UIGraphicsBeginImageContext(CGSizeMake(5,5))
for x in 0..<3 {for y in 0..<5 {CGContextSetFillColorWithColor(g,drand48()>0.5 ? c : UIColor.whiteColor().CGColor)
var r = [CGRect(x:x,y:y,width:1,height:1)]
if x<2 {let m = x==0 ? 4 : 3;r.append(CGRect(x:m,y:y,width:1,height:1))}
CGContextFillRects(g,&r,r.count)}}
let i = UIGraphicsGetImageFromCurrentImageContext()
UIImagePNGRepresentation(i)!.writeToURL(NSURL(string:"/a/a.png")!,atomically:true)
</code>```

Update

Swift 3, 551 bytes

```<code>var t = 0,g = UIGraphicsGetCurrentContext()!,c = UIColor(hue:CGFloat(drand48()),saturation:1,brightness:1,alpha:1).cgColor
srand48(time(&t))
UIGraphicsBeginImageContext(CGSize(width:5,height:5))
for x in 0..<3 {for y in 0..<5 {g.setFillColor(drand48()>0.5 ? c : UIColor.white().cgColor)
var r = [CGRect(x:x,y:y,width:1,height:1)]
if x<2 {let m = x==0 ? 4 : 3;r.append(CGRect(x:m,y:y,width:1,height:1))}
g.fill(&r,count: r.count)}}
let i = UIGraphicsGetImageFromCurrentImageContext()!
try!UIImagePNGRepresentation(i)!.write(to: URL(string:"/a/a.png")!)
</code>```

I'm at WWDC and just got the Xcode 8 beta with Swift 3.  Apple made some of the CoreGraphics calls more "Swifty," and I am able to reduce the bytecount.

Swift 2 code Ungolfed:

```<code>var t = 0
srand48(time(&t))

UIGraphicsBeginImageContext(CGSizeMake(5,5))
let context = UIGraphicsGetCurrentContext()
let color = UIColor(hue: CGFloat(drand48()),saturation:1,brightness:1,alpha:1).CGColor

for x in 0..<3 {
    for y in 0..<5 {
        CGContextSetFillColorWithColor(context, drand48() > 0.5 ? color : UIColor.whiteColor().CGColor)
        var rects = [CGRect(x:x,y:y,width:1,height:1)]

        if x < 2 {
            let mirror = x==0 ? 4 : 3
            rects.append(CGRect(x: mirror, y: y, width: 1, height: 1))
        }

        CGContextFillRects(context, &rects, rects.count)
    }
}

let image = UIGraphicsGetImageFromCurrentImageContext()
UIImagePNGRepresentation(image)!.writeToURL(NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory,inDomains:.UserDomainMask).first!.URLByAppendingPathComponent("a.png"), atomically:true)
</code>```

This answer assumes UIKit is available and uses the Cocoa Touch framework.

Some example output images:

I know I can't compete with most of the other answers but I wanted to give this a shot as a personal challenge.  There is definitely room for improvement with this answer, but I think it will be hard to get this down below a few hundred bytes due to the length of the UIKit and CoreGraphics image writing method names.  I opted to write an actual PNG file rather than PPM values as an exercise for myself, but shorter answers would definitely be possible if I used the PPM format.

I already start out as a loss by having to declare a variable to seed srand48 with time.  I chose this over arc4random() or arc4random_uniform() because ultimately I would lose more bytes with those.  I seed the rng to use drand48 to generate a random color and pick when to write a color to a pixel.

CGSize vs CGSizeMake and CGRect vs CGRectMake:

I switch between the inline C API functions and their Swift extensions to find the shortest constructor for each.  CGSizeMake ends up being shorter than CGSize(), and CGRectends up being shorter than CGRectMake():

```<code>CGSizeMake(5,5)
CGSize(width:5,height:5)

CGRect(x:x,y:y,width:1,height:1)
CGRectMake(CGFloat(x),CGFloat(y),1,1)
</code>```

I would have to create CGFloats x and y due to the nature of the for loop.  I'm really not thrilled with the 2D loop and if equality checks, but I was really struggling to find a shorter way.  There's definitely room to shave off a few bytes here.

Calling CGContextFillRects with an array of CGRect structs is cheaper than calling CGContextFillRect twice with two different values, so I save a few bytes with the array and pointer.

I also save 27 bytes by not calling UIGraphicsEndImageContext().  While this would normally be a "bug" in production code, it's not necessary for this toy program.

Colors:

Colors are also a pain to deal with, since I'm creating UIColor objects but need to write a CGColor opaque type to each pixel.  The shortest code I found to create a random color was to use the UIColor constructor and get the CGColor from that UIColor.  Same with white.  If I were using the Cocoa framework instead of Cocoa Touch, I might be able to save some bytes using CGColorGetConstantColor(), but unfortunately that method is unavailable in the Cocoa Touch SDK.

Writing to to file:

Writing to a file takes almost 100 bytes.  I'm not sure how to even go about optimizing this.  On some systems depending on your permissions, you may need to use the Documents directory which would be even longer:

```<code>UIImagePNGRepresentation(i)!.writeToURL(NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory,inDomains:.UserDomainMask).first!.URLByAppendingPathComponent("a.png"), atomically:true)
</code>```

Definitely open to further optimizations.

Edit 1: Saved a few bytes by rearranging some variable declarations.

Title: Generate a "GitHub" Avatar

Body:
Swift 2.3, <s>593</s> 585 bytes

var t = 0,g = UIGraphicsGetCurrentContext(),c = UIColor(hue:CGFloat(drand48()),saturation:1,brightness:1,alpha:1).CGColor
srand48(time(&t))
UIGraphicsBeginImageContext(CGSizeMake(5,5))
for x in 0..<3 {for y in 0..<5 {CGContextSetFillColorWithColor(g,drand48()>0.5 ? c : UIColor.whiteColor().CGColor)
var r = [CGRect(x:x,y:y,width:1,height:1)]
if x<2 {let m = x==0 ? 4 : 3;r.append(CGRect(x:m,y:y,width:1,height:1))}
CGContextFillRects(g,&r,r.count)}}
let i = UIGraphicsGetImageFromCurrentImageContext()
UIImagePNGRepresentation(i)!.writeToURL(NSURL(string:"/a/a.png")!,atomically:true)

Update

Swift 3, 551 bytes

var t = 0,g = UIGraphicsGetCurrentContext()!,c = UIColor(hue:CGFloat(drand48()),saturation:1,brightness:1,alpha:1).cgColor
srand48(time(&t))
UIGraphicsBeginImageContext(CGSize(width:5,height:5))
for x in 0..<3 {for y in 0..<5 {g.setFillColor(drand48()>0.5 ? c : UIColor.white().cgColor)
var r = [CGRect(x:x,y:y,width:1,height:1)]
if x<2 {let m = x==0 ? 4 : 3;r.append(CGRect(x:m,y:y,width:1,height:1))}
g.fill(&r,count: r.count)}}
let i = UIGraphicsGetImageFromCurrentImageContext()!
try!UIImagePNGRepresentation(i)!.write(to: URL(string:"/a/a.png")!)

I'm at WWDC and just got the Xcode 8 beta with Swift 3.  Apple made some of the CoreGraphics calls more "Swifty," and I am able to reduce the bytecount.

Swift 2 code Ungolfed:

var t = 0
srand48(time(&t))

UIGraphicsBeginImageContext(CGSizeMake(5,5))
let context = UIGraphicsGetCurrentContext()
let color = UIColor(hue: CGFloat(drand48()),saturation:1,brightness:1,alpha:1).CGColor

for x in 0..<3 {
    for y in 0..<5 {
        CGContextSetFillColorWithColor(context, drand48() > 0.5 ? color : UIColor.whiteColor().CGColor)
        var rects = [CGRect(x:x,y:y,width:1,height:1)]

        if x < 2 {
            let mirror = x==0 ? 4 : 3
            rects.append(CGRect(x: mirror, y: y, width: 1, height: 1))
        }

        CGContextFillRects(context, &rects, rects.count)
    }
}

let image = UIGraphicsGetImageFromCurrentImageContext()
UIImagePNGRepresentation(image)!.writeToURL(NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory,inDomains:.UserDomainMask).first!.URLByAppendingPathComponent("a.png"), atomically:true)

This answer assumes UIKit is available and uses the Cocoa Touch framework.

Some example output images:

I know I can't compete with most of the other answers but I wanted to give this a shot as a personal challenge.  There is definitely room for improvement with this answer, but I think it will be hard to get this down below a few hundred bytes due to the length of the UIKit and CoreGraphics image writing method names.  I opted to write an actual PNG file rather than PPM values as an exercise for myself, but shorter answers would definitely be possible if I used the PPM format.

I already start out as a loss by having to declare a variable to seed srand48 with time.  I chose this over arc4random() or arc4random_uniform() because ultimately I would lose more bytes with those.  I seed the rng to use drand48 to generate a random color and pick when to write a color to a pixel.

CGSize vs CGSizeMake and CGRect vs CGRectMake:

I switch between the inline C API functions and their Swift extensions to find the shortest constructor for each.  CGSizeMake ends up being shorter than CGSize(), and CGRectends up being shorter than CGRectMake():

CGSizeMake(5,5)
CGSize(width:5,height:5)

CGRect(x:x,y:y,width:1,height:1)
CGRectMake(CGFloat(x),CGFloat(y),1,1)

I would have to create CGFloats x and y due to the nature of the for loop.  I'm really not thrilled with the 2D loop and if equality checks, but I was really struggling to find a shorter way.  There's definitely room to shave off a few bytes here.

Calling CGContextFillRects with an array of CGRect structs is cheaper than calling CGContextFillRect twice with two different values, so I save a few bytes with the array and pointer.

I also save 27 bytes by not calling UIGraphicsEndImageContext().  While this would normally be a "bug" in production code, it's not necessary for this toy program.

Colors:

Colors are also a pain to deal with, since I'm creating UIColor objects but need to write a CGColor opaque type to each pixel.  The shortest code I found to create a random color was to use the UIColor constructor and get the CGColor from that UIColor.  Same with white.  If I were using the Cocoa framework instead of Cocoa Touch, I might be able to save some bytes using CGColorGetConstantColor(), but unfortunately that method is unavailable in the Cocoa Touch SDK.

Writing to to file:

Writing to a file takes almost 100 bytes.  I'm not sure how to even go about optimizing this.  On some systems depending on your permissions, you may need to use the Documents directory which would be even longer:

UIImagePNGRepresentation(i)!.writeToURL(NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory,inDomains:.UserDomainMask).first!.URLByAppendingPathComponent("a.png"), atomically:true)

Definitely open to further optimizations.

Edit 1: Saved a few bytes by rearranging some variable declarations.


问:
Generate the Abacaba sequence
This challenge is about printing the abacaba sequence of a specific depth.

Here is a diagram of the first 5 sequences (a(N) is the abacaba sequence of depth N, upper/lowercase is just to show the pattern, this is not needed in the output of your program):

```<code>a(0) = A
a(1) = aBa
a(2) = abaCaba
a(3) = abacabaDabacaba
a(4) = abacabadabacabaEabacabadabacaba
...
a(25) = abacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabagabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabahabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabagabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabaiabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabagabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabahabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabagabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabajabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabagabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabahabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabagabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabaia...
</code>```

As you can probably tell, the n'th abacaba sequence is the last one with the n'th letter and itself again added to it. (a(n) = a(n - 1) + letter(n) + a(n - 1))

Your task is to make a program or function that takes an integer and prints the abacaba sequence of that depth. The output has to be correct at least for values up to and including 15.

答:
Pyke, 11 bytes (noncompeting)

```<code>G@QVk?tQG@:
</code>```

Try it here!

```<code>G@          - s = alphabet[input]
  QV        - repeat input times:
     ?tQ    -   input -= 1
        G@  -  alphabet[^]
    k     : - s = s.replace("", ^)
</code>```

Title: Generate the Abacaba sequence

Body:
Pyke, 11 bytes (noncompeting)

G@QVk?tQG@:

Try it here!

G@          - s = alphabet[input]
  QV        - repeat input times:
     ?tQ    -   input -= 1
        G@  -  alphabet[^]
    k     : - s = s.replace("", ^)


问:
Greatest Number in a Range When The Sum of Squares of its Prime Factors are Subtracted
The formula

Take for instance the number 300

The prime factors of 300 are [2, 3, 5] (unique numbers that are
factors of 300 and prime)

Squaring each of those numbers will give
you [4, 9, 25]

Summing that list will give you 4 + 9 + 25 = 38

Finally subtract that sum (38) from your original number 300-38 = 262 (this is the result)

Input

Your input will be a positive integer greater than 2. You must check all numbers from 2 to the input value (inclusive) and find the number that produces the greatest result with the formula above.

Output

Your output will be two numbers separated by a space, comma, newline or whatever you language allows (the separation is necessary to distinguish the two numbers). These can be output to a file, stdout, or whatever your language uses. Your goal is to find the number in the range that produces the maximum output when run through the formula above. The first number displayed should be the starting number (like 300) and the second number should be the output that the formula produced (like 262)

Test Cases

```<code>Input: 3       Output: 2, -2
Input: 10      Output: 8, 4
Input: 50      Output: 48, 35
Input: 1000    Output: 1000, 971
Input: 9999    Output: 9984, 9802
</code>```

Worked Through Example

Consider the input of 10, we must run the formula for all numbers from 2-10 (inclusive)

```<code>Num PrimeFacs PrimeFacs^2 SumPrimeFacs^2 Result
2   [2]       [4]         4              -2
3   [3]       [9]         9              -6
4   [2]       [4]         4               0
5   [5]       [25]        25             -20
6   [2, 3]    [4, 9]      13             -7
7   [7]       [49]        49             -42
8   [2]       [4]         4               4
9   [3]       [9]         9               0
10  [2, 5]    [4, 25]     29             -19
</code>```

As you can see the greatest result is 4, which was a result of inputting the value 8 into the formula. That means the output for an input of 10 should be 8, 4

Scoring & Rules

The default rules for inputs and outputs apply: Default for Code Golf: Input/Output methods

The standard loopholes are forbidden: Loopholes that are forbidden by default

Submissions can be functions or full programs

Shortest code in bytes wins

Body:
J, 44 bytes

[:((],.~2+I.@e.)>./)@:}.1(-[:+/*:@~.@q:)@+i.

Straight-forward approach. Also returns all values of n that result in a maximum value.

Usage

   f =: [:((],.~2+I.@e.)>./)@:}.1(-[:+/*:@~.@q:)@+i.
   f 3
2 _2
   f 10
8 4
   f 50
48 35
   f 1000
1000 971
   f 9999
9984 9802
   f 950
900 862
945 862


问:
Pseudofactorial
There is a rather curious number which shows up sometimes in math problems or riddles. The pseudofactorial(N) is the least (i.e. lowest) common multiple of the numbers 1 through N; in other words, it's the lowest number which has all numbers from 1 through N as factors.

For instance pseudofactorial(7) = 3 * 4 * 5 * 7, which is the same as 7! except that 2 and 6 have been removed because they are contained in other terms.

Write a program to calculate pseudofactorial(N) and as always, shortest code wins.

Here is a short list for your use. More test cases can be found in the OEIS under A003418.

Factorial:

1

2

6

24

120

720

5040

Pseudofactorial:

1

2

6

12

60

60

420

答:
Jelly, 4 bytes

```<code>Ræl/
</code>```

Try it online! or verify all test cases.

How it works

```<code>Ræl/  Main link. Input: n

R     Range; yield [1, ..., n].
   /  Reduce the range...
 æl     by LCM.
</code>```

Title: Pseudofactorial

Body:
Jelly, 4 bytes

Ræl/

Try it online! or verify all test cases.

How it works

Ræl/  Main link. Input: n

R     Range; yield [1, ..., n].
   /  Reduce the range...
 æl     by LCM.


答:
Julia, 11 bytes

!n=lcm(1:n)
```

Try it online!

Title: Pseudofactorial

Body:
There is a rather curious number which shows up sometimes in math problems or riddles. The pseudofactorial(N) is the least (i.e. lowest) common multiple of the numbers 1 through N; in other words, it's the lowest number which has all numbers from 1 through N as factors.

For instance pseudofactorial(7) = 3 * 4 * 5 * 7, which is the same as 7! except that 2 and 6 have been removed because they are contained in other terms.

Write a program to calculate pseudofactorial(N) and as always, shortest code wins.

Here is a short list for your use. More test cases can be found in the OEIS under A003418.

Factorial:

1

2

6

24

120

720

5040

Pseudofactorial:

1

2

6

12

60

60

420

Body:
Julia, 11 bytes

!n=lcm(1:n)

Try it online!


答:
MATL, 4 bytes

```<code>:&Zm
</code>```

Try it online!

Explanation

```<code>:      % Take input N implicitly. Generate range [1 2 ... N]
&Zm    % LCM of the numbers in that array. Display implicitly
</code>```

Title: Pseudofactorial

Body:
MATL, 4 bytes

:&Zm

Try it online!

Explanation

:      % Take input N implicitly. Generate range [1 2 ... N]
&Zm    % LCM of the numbers in that array. Display implicitly


答:
Pyth - 8 bytes

Checks all numbers till it finds one that is divisible by [1..N].

```<code>f!s%LTSQ
</code>```

Test Suite.

Title: Pseudofactorial

Body:
Pyth - 8 bytes

Checks all numbers till it finds one that is divisible by [1..N].

f!s%LTSQ

Test Suite.


问:
Print NxN spiral of ascending numbers
The numbers should be printed with leading zeroes in a field with length = (number of digits of N^2).

Input (N):

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

Output:

```<code>01 12 11 10
02 13 16 09
03 14 15 08
04 05 06 07
</code>```

I am interested in the algorithm and the cleanliness of the implementation.
So, the white space does not count and the upper limit for N is 42.

答:
Python 2.7:

```<code>def spiral(n):
   rows = [[n * n]]
   current = n * n - 1

   while current:
      rows = zip(*([range(current, current - len(rows[0]), -1)] + rows))[::-1]
      current -= len(rows)

   digits = len(str(n * n))
   for row in rows:
      print" ".join(str(cell).zfill(digits) for cell in row)

spiral(5)
</code>```

Title: Print NxN spiral of ascending numbers

Body:
Python 2.7:

def spiral(n):
   rows = [[n * n]]
   current = n * n - 1

   while current:
      rows = zip(*([range(current, current - len(rows[0]), -1)] + rows))[::-1]
      current -= len(rows)

   digits = len(str(n * n))
   for row in rows:
      print" ".join(str(cell).zfill(digits) for cell in row)

spiral(5)


答:
J, 9 bytes

```<code>[:*./1+i.
</code>```

Straight-forward approach. Creates the range of numbers [0, ..., n-1], then adds one to each, and reduce it using the LCM.

Usage

```<code>   f =: [:*./1+i.
   f 7
420
</code>```

Title: Pseudofactorial

Body:
J, 9 bytes

[:*./1+i.

Straight-forward approach. Creates the range of numbers [0, ..., n-1], then adds one to each, and reduce it using the LCM.

Usage

   f =: [:*./1+i.
   f 7
420


答:
Python + SymPy, 45 bytes

import sympy
lambda n:sympy.lcm(range(1,n+1))
```

<p>Fairly self-explanatory.</p>

<hr>

<h1>Python 2, <s>57</s> 54 bytes</h1>

<pre class="lang-python prettyprint-override"><code>i=r=input();exec't=r\nwhile r%i:r+=t\ni-=1;'*r;print r
</code>```

Test it on Ideone.

How it works

The input is stored in variables i and r.

exec executes the following code r times.

t=r
while r%i:r+=t
i-=1
```

While i varies from r to 1, we add the initial value of r (stored in t) as many times as necessary to r itself to create a multiple of i. The result is, obviously, a multiple of t.

The final value of r is thus a multiple of all integers in the range [1, ..., n], where n is the input.

Title: Pseudofactorial

Body:
Python + SymPy, 45 bytes

import sympy
lambda n:sympy.lcm(range(1,n+1))

Fairly self-explanatory.

Python 2, <s>57</s> 54 bytes

i=r=input();exec't=r\nwhile r%i:r+=t\ni-=1;'*r;print r

Test it on Ideone.

How it works

The input is stored in variables i and r.

exec executes the following code r times.

t=r
while r%i:r+=t
i-=1

While i varies from r to 1, we add the initial value of r (stored in t) as many times as necessary to r itself to create a multiple of i. The result is, obviously, a multiple of t.

The final value of r is thus a multiple of all integers in the range [1, ..., n], where n is the input.


答:
Octave, 27 bytes

```<code>@(x)lcm(1,num2cell(1:x){:})
</code>```

Creates an anonymous function that can be invoked as ans(N).

Online Demo

Explanation

This solution creates a list of all numbers between 1 and x (1:x), converts them to a cell array with num2cell. Then the {:} indexing creates a comma-separated-list which is passed to lcm as multiple input arguments to compute the least common multiple. A 1 is always passed as the first argument to lcm because lcm always needs at least two input arguments.

Title: Pseudofactorial

Body:
Octave, 27 bytes

@(x)lcm(1,num2cell(1:x){:})

Creates an anonymous function that can be invoked as ans(N).

Online Demo

Explanation

This solution creates a list of all numbers between 1 and x (1:x), converts them to a cell array with num2cell. Then the {:} indexing creates a comma-separated-list which is passed to lcm as multiple input arguments to compute the least common multiple. A 1 is always passed as the first argument to lcm because lcm always needs at least two input arguments.


问:
1/N probability
Because there are not enough simple code-golf challenges:

Create an optionally unnamed program or function that, given (by any means) an integer 1 ≤ N ≤ 10000, outputs your language's True value with a pseudo-random probability of 1/N, False otherwise.

Please note that the requirement for naming has been removed. Feel free to edit answers and scores accordingly.

Some languages use 1 (or -1) and 0 for True and False, that is fine too.

Example:

Example input tests:

```<code>4 -> True
4 -> False
4 -> False
4 -> False
4 -> False
4 -> True
4 -> False
4 -> False
</code>```

I.e. given 4; it returns True with a 25% chance and False with a 75% chance.

答:
Perl 5, 10 bytes

A subroutine:

```<code>{1>rand@_}
</code>```

It takes input as a list of 1s of the appropriate length.

Hat-tip.

Title: 1/N probability

Body:
Perl 5, 10 bytes

A subroutine:

{1>rand@_}

It takes input as a list of 1s of the appropriate length.

Hat-tip.


问:
Same length sub arrays

Background:

Here's a little simple challenge. You want to be able to find out whether the arrays inside an array have the same length.

Input:

Your input should consist of exactly one array (this is the value passed to the function, not a user input). Your function takes exactly 1 parameter.  It could contain arrays or be empty. No error checking needed, assume only list is ever passed in. Assume a 1-D array such as [1] or [1,2,3,4,5] is never passed in.

Output:

Return true if all the list elements have the same length, false if they don't, and the parameter itself if the list is empty (or null if your language doesn't support multiple return types).

Some test cases:

```<code>List: [] - [] (or null/your language equivalent)
List: [[1], [1], [2]] - True
List: [[1]] - True
List: [[1, 2, 3, 4]] - True
List: [[1, 2, 3, 4, 5], [2], [12, 314123]] - False
List: [[1, 2, 3, 4], [1]] - False
</code>```

No std(in/out) input/output needed (however, it is allowed, just not required!), the function only needs to return boolean values true or false; or the parameter itself if the function is passed an empty list (or null/your language equivalent). Only one return value is returned.

Rules:

Shortest byte count wins, only function is necessary (full programs are allowed if you desire).

答:
Swift 3 - 47 Bytes

```<code>{$0.isEmpty ?nil:Set($0.map{$0.count}).count<2}
</code>```

To invoke, first assign it to a variable:

```<code> let f: ([[Any]]) -> Bool? = {$0.isEmpty ?nil:Set($0.map{$0.count}).count<2}
 f([[1], [1,2], [1,2,3]])
</code>```

Title: Same length sub arrays

Body:
Swift 3 - 47 Bytes

{$0.isEmpty ?nil:Set($0.map{$0.count}).count<2}

To invoke, first assign it to a variable:

 let f: ([[Any]]) -> Bool? = {$0.isEmpty ?nil:Set($0.map{$0.count}).count<2}
 f([[1], [1,2], [1,2,3]])


答:
Pyth - <s>7</s> 5 bytes

Saved 2 bytes thanks to @FryAmTheEggman.

And I was the one who told @issacg to remove the q default...

```<code>?QqCC
</code>```

Test Suite.

Title: Same length sub arrays

Body:
Background:

Here's a little simple challenge. You want to be able to find out whether the arrays inside an array have the same length.

Input:

Your input should consist of exactly one array (this is the value passed to the function, not a user input). Your function takes exactly 1 parameter.  It could contain arrays or be empty. No error checking needed, assume only list is ever passed in. Assume a 1-D array such as [1] or [1,2,3,4,5] is never passed in.

Output:

Return true if all the list elements have the same length, false if they don't, and the parameter itself if the list is empty (or null if your language doesn't support multiple return types).

Some test cases:

```<code>List: [] - [] (or null/your language equivalent)
List: [[1], [1], [2]] - True
List: [[1]] - True
List: [[1, 2, 3, 4]] - True
List: [[1, 2, 3, 4, 5], [2], [12, 314123]] - False
List: [[1, 2, 3, 4], [1]] - False
</code>```

No std(in/out) input/output needed (however, it is allowed, just not required!), the function only needs to return boolean values true or false; or the parameter itself if the function is passed an empty list (or null/your language equivalent). Only one return value is returned.

Rules:

Shortest byte count wins, only function is necessary (full programs are allowed if you desire).

Body:
Pyth - <s>7</s> 5 bytes

Saved 2 bytes thanks to @FryAmTheEggman.

And I was the one who told @issacg to remove the q default...

?QqCC

Test Suite.


答:
Javascript ES6, <s>44</s> <s>43</s> 42 bytes

Saved 1 byte thanks to @Neil

```<code>a=>a[0]?!a.some(b=>b.length-a[0].length):a
</code>```

Alternative solutions

```<code>a=>a[0]?a.every(b=>b.length==a[0].length):a // 43
a=>a[0]?new Set(a.map(b=>b.length)).size==1:a // 45
a=>a[0]?Math.max(...a.map(b=>b.length))==a[0].length:a // 54
a=>a[0]?[a[0].length,...a].reduce((b,d)=>b==d.length):a // 55, doesn't work as intended
</code>```

Somehow the stacksnippet doesn't print [], try it in your console for the actual result.

f=
a=>a[0]?a.every(b=>b.length==a[0].length):a

z.innerHTML = [
  [],
  [[1], [1], [2]],
  [[1]],
  [[1, 2, 3, 4]],
  [[1, 2, 3, 4, 5], [2], [12, 314123]],
  [[1, 2, 3, 4], [1]]
].map(m=>JSON.stringify(f(m))).join`<br>````
<pre class="snippet-code-html lang-html prettyprint-override"><code><pre id=z></code>```

(yay for crossed out 44)

Title: Same length sub arrays

Body:
Javascript ES6, <s>44</s> <s>43</s> 42 bytes

Saved 1 byte thanks to @Neil

a=>a[0]?!a.some(b=>b.length-a[0].length):a

Alternative solutions

a=>a[0]?a.every(b=>b.length==a[0].length):a // 43
a=>a[0]?new Set(a.map(b=>b.length)).size==1:a // 45
a=>a[0]?Math.max(...a.map(b=>b.length))==a[0].length:a // 54
a=>a[0]?[a[0].length,...a].reduce((b,d)=>b==d.length):a // 55, doesn't work as intended

Somehow the stacksnippet doesn't print [], try it in your console for the actual result.

f=
a=>a[0]?a.every(b=>b.length==a[0].length):a

z.innerHTML = [
  [],
  [[1], [1], [2]],
  [[1]],
  [[1, 2, 3, 4]],
  [[1, 2, 3, 4, 5], [2], [12, 314123]],
  [[1, 2, 3, 4], [1]]
].map(m=>JSON.stringify(f(m))).join`<br>`

<pre id=z>

(yay for crossed out 44)


答:
Jelly, 5 bytes

```<code>L€E⁸ȧ
</code>```

Try it online!

How it works

```<code>L€E⁸ȧ  Monadic link. Argument: A (list)

L€     Map length over the list.
  E    Test if all elements are equal.
   ⁸ȧ  Take the logical AND of A and the resulting Boolean.
</code>```

Title: Same length sub arrays

Body:
Jelly, 5 bytes

L€E⁸ȧ

Try it online!

How it works

L€E⁸ȧ  Monadic link. Argument: A (list)

L€     Map length over the list.
  E    Test if all elements are equal.
   ⁸ȧ  Take the logical AND of A and the resulting Boolean.


答:
MATLAB, 49 bytes

```<code>@(x)find(~any(bsxfun(@rem,1:prod(1:x),(1:x)')),1)
</code>```

Title: Pseudofactorial

Body:
MATLAB, 49 bytes

@(x)find(~any(bsxfun(@rem,1:prod(1:x),(1:x)')),1)


答:
Python, 45 bytes

```<code>lambda x:x and min(x,key=len)==max(x,key=len)
</code>```

Title: Same length sub arrays

Body:
Python, 45 bytes

lambda x:x and min(x,key=len)==max(x,key=len)


问:
Code Golf of Death
Write some code that causes a BSOD or kernel panic!

Rules:

On Windows, you must cause a BugCheck (Blue Screen of Death), on Linux (or other *nix systems) you must cause a kernel panic.

Must not damage the system (i.e. it should work on reboot)

Kernel-mode drivers are allowed.

State your OS and version information.

Explain how the crash is caused.

It's not against the rules to use tools that are specifically designed to cause a crash, but doing so isn't very creative!

Highest upvotes wins.

答:
Batch, 15 bytes

```<code>:A
start
goto A
</code>```

Merely overflows the memory in linear time by starting up cmd.exe hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds of times.

There's a deadlier (but probably non-competing) 24-byte program that starts up itself over and over again, thus overflowing the memory in logarithmic time (i.e upgrading your RAM doesn't delay the crash). Suppose the below code is located in C:\a.bat:

```<code>:A
start C:\a.bat
goto A
</code>```

.

Honestly I'm afraid to try those out.

Title: Code Golf of Death

Body:
Batch, 15 bytes

:A
start
goto A

Merely overflows the memory in linear time by starting up cmd.exe hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds and hundreds of times.

There's a deadlier (but probably non-competing) 24-byte program that starts up itself over and over again, thus overflowing the memory in logarithmic time (i.e upgrading your RAM doesn't delay the crash). Suppose the below code is located in C:\a.bat:

:A
start C:\a.bat
goto A

.

Honestly I'm afraid to try those out.


答:
Python 2, 31

```<code>lambda l:l and l==zip(*zip(*l))
</code>```

This requires the lists to be lists of tuples. zip Drops extra elements if the input was ragged, so double zipping is only a noop if the lists all have the same length.

Try it here

Title: Same length sub arrays

Body:
Python 2, 31

lambda l:l and l==zip(*zip(*l))

This requires the lists to be lists of tuples. zip Drops extra elements if the input was ragged, so double zipping is only a noop if the lists all have the same length.

Try it here


答:
Mathematica, 22 bytes

```<code>a@{}={};a@b_:=ArrayQ@b
</code>```

The requirement of a[{}] == {} ruins everything and prevents a 6 byte solution of the built-in ArrayQ, since in Mathematica a zero length array is also an array.

Title: Same length sub arrays

Body:
Mathematica, 22 bytes

a@{}={};a@b_:=ArrayQ@b

The requirement of a[{}] == {} ruins everything and prevents a 6 byte solution of the built-in ArrayQ, since in Mathematica a zero length array is also an array.


答:
Haskell, 20 bytes

```<code>f x=foldr1 lcm[1..x]
</code>```

Usage example: map f [1..7] -> [1,2,6,12,60,60,420].

The lcm trick in Haskell.

Title: Pseudofactorial

Body:
There is a rather curious number which shows up sometimes in math problems or riddles. The pseudofactorial(N) is the least (i.e. lowest) common multiple of the numbers 1 through N; in other words, it's the lowest number which has all numbers from 1 through N as factors.

For instance pseudofactorial(7) = 3 * 4 * 5 * 7, which is the same as 7! except that 2 and 6 have been removed because they are contained in other terms.

Write a program to calculate pseudofactorial(N) and as always, shortest code wins.

Here is a short list for your use. More test cases can be found in the OEIS under A003418.

Factorial:

1

2

6

24

120

720

5040

Pseudofactorial:

1

2

6

12

60

60

420

Body:
Haskell, 20 bytes

f x=foldr1 lcm[1..x]

Usage example: map f [1..7] -> [1,2,6,12,60,60,420].

The lcm trick in Haskell.


答:
Octave, 51 bytes

```<code>@(x)repmat(2>n(unique(cellfun(n=@numel,x))),n(x)>0)
</code>```

Online Demo

Explanation

Loops through the input (a cell array) and determines the number of elements in each entry numel, then from this array of the number of elements, we ensure that there is only one unique value: 2 > numel(unique(numberOfElements)). This will give us the boolean we want. Unfortunately, it is difficult to yield an empty array efficiently so in order to deal with the case of an empty input, we use repmat to repeat this boolean value N times where N is the number of subarrays in the input. If the input is empty this repeats the boolean value 0 times leading to [].

Title: Same length sub arrays

Body:
Octave, 51 bytes

@(x)repmat(2>n(unique(cellfun(n=@numel,x))),n(x)>0)

Online Demo

Explanation

Loops through the input (a cell array) and determines the number of elements in each entry numel, then from this array of the number of elements, we ensure that there is only one unique value: 2 > numel(unique(numberOfElements)). This will give us the boolean we want. Unfortunately, it is difficult to yield an empty array efficiently so in order to deal with the case of an empty input, we use repmat to repeat this boolean value N times where N is the number of subarrays in the input. If the input is empty this repeats the boolean value 0 times leading to [].


问:
Check if a pattern appears in a DNA sequence
In a project I am working on, I am checking to see if certain DNA sequences appear in certain genes in E. coli. I have written a program in Java that performs the below features. However, since I wrote my program in Java, the universe needs to be corrected and rid of verbosity by having you write your code in as few bytes as possible.

My program took a DNA sequences and a regex as input (for this challenge, order doesn't matter). The DNA sequence contains only the letters A, C, G, and T. It will be determined if the DNA sequence contains any subsequences that follow the regex, and the output of the program will be the one-indexed location(s) of the first character of each matching subsequence in the DNA sequence in your choice of format. If there is no such location, you may output any reasonable indicator of this.

The regex I used had the following specifications.

A, C, G, and T match to themselves.

N matches to any of A, C, G, and T

(X/Y) means that at the current location in the sequence, the next character(s) in the sequence match X or Y (note that X and Y can be multiple characters long, and that there can be multiple slashes; for example, (AA/AG/GA) matches to AA, AG or GG; however, X and Y must have the same length)

You may assume that the DNA sequence is longer than any sequence that follows the specifications of the regex, and that both the DNA and the regex are valid.

Test cases

Here, the DNA sequence is first, and the regex is second.

```<code>AAAAAAAAAA
AAA
==> 1 2 3 4 5 6 7 8

ACGTAATGAA
A(A/C)(T/G/A)
==> 1 5

GGGGCAGCAGCTGACTA
C(NA/AN)
==> 5 8 15

ACGTTAGTTAGCGTGATCGTG
CGTNA
==> 2 12
</code>```

This is code-golf. The shortest answer in bytes wins. Standard rules apply.

答:
Pyth, 28 bytes

```<code>fT*VSlQ_:RX+\^z"/N.|")0_M.__
</code>```

Simple regex matching.

I hope there had a function which returns the position of each match, but there is not.

Test suite.

Body:
Pyth, 28 bytes

fT*VSlQ_:RX+\^z"/N.|")0_M.__

Simple regex matching.

I hope there had a function which returns the position of each match, but there is not.

Test suite.


答:
Mathematica, 13 bytes

```<code>LCM@@Range@#&
</code>```

Title: Pseudofactorial

Body:
Mathematica, 13 bytes

LCM@@Range@#&


答:
Julia, 33 bytes

!x=[]==x?x:diff(map(endof,x))⊆0
```

Try it online!

How it works

We redefine the unary operator ! for this task.

If x is the empty array, we simply return x.

Else, we map endof (equivalent to length) over the arrays in x and compute the differences of consecutive lengths with diff. If all length are equal, this will generate an array of 0's. Otherwise, there will be non-zero numbers in the result.

Finally, ⊆0 tests if all differences are 0 and return the corresponding Boolean.

Title: Same length sub arrays

Body:
Julia, 33 bytes

!x=[]==x?x:diff(map(endof,x))⊆0

Try it online!

How it works

We redefine the unary operator ! for this task.

If x is the empty array, we simply return x.

Else, we map endof (equivalent to length) over the arrays in x and compute the differences of consecutive lengths with diff. If all length are equal, this will generate an array of 0's. Otherwise, there will be non-zero numbers in the result.

Finally, ⊆0 tests if all differences are 0 and return the corresponding Boolean.


答:
C (x86-64 gcc -O1), 52 bytes

```<code>d(n,k,b,t){for(b=k=1;b;++k)for(t=n,b=0;t;b+=k%t--);}
</code>```

Checks numbers from 1 upwards. For each number, divides it by all numbers from n down to 1, and sums the remainders. Stops when the sum is 0.

Usage:

```<code>main()
{
    printf("%d\n", d(7)); // outputs 420
}
</code>```

It's not obvious how it returns a value (there is no return statement).

The calling convention for x86 says that the function must return its value in the eax register. Conveniently, the division instruction idiv expects its input in eax, and outputs the result in eax (quotient) and edx (remainder). The last iteration divides k by 1, so eax will contain the right value when the function exits.

This only works with gcc and -O1 optimization option (otherwise, it outputs different results — usually 0 or random-looking numbers, but sometimes 421, while the correct answer is 420).

Try it with Compiler Explorer

Title: Pseudofactorial

Body:
C (x86-64 gcc -O1), 52 bytes

d(n,k,b,t){for(b=k=1;b;++k)for(t=n,b=0;t;b+=k%t--);}

Checks numbers from 1 upwards. For each number, divides it by all numbers from n down to 1, and sums the remainders. Stops when the sum is 0.

Usage:

main()
{
    printf("%d\n", d(7)); // outputs 420
}

It's not obvious how it returns a value (there is no return statement).

The calling convention for x86 says that the function must return its value in the eax register. Conveniently, the division instruction idiv expects its input in eax, and outputs the result in eax (quotient) and edx (remainder). The last iteration divides k by 1, so eax will contain the right value when the function exits.

This only works with gcc and -O1 optimization option (otherwise, it outputs different results — usually 0 or random-looking numbers, but sometimes 421, while the correct answer is 420).

<a href="https://godbolt.org/#g:!((g:!((g:!((g:!((h:codeEditor,i:(filename:%271%27,fontScale:14,fontUsePx:%270%27,j:1,lang:___c,selection:(endColumn:2,endLineNumber:5,positionColumn:2,positionLineNumber:5,selectionStartColumn:2,selectionStartLineNumber:5,startColumn:2,startLineNumber:5),source:%27d(n,k,b,t)%7Bfor(b%3Dk%3D1%3Bb%3B%2B%2Bk)for(t%3Dn,b%3D0%3Bt%3Bb%2B%3Dk%25t--)%3B%7D%0Aint+main()%0A%7B%0A++++printf(%22%25d%22,+d(7))%3B%0A%7D%27),l:%275%27,n:%270%27,o:%27C+source+%231%27,t:%270%27)),k:48.11846689895471,l:%274%27,n:%270%27,o:%27%27,s:0,t:%270%27),(g:!((h:compiler,i:(compiler:cg85,deviceViewOpen:%271%27,filters:(b:%270%27,binary:%271%27,binaryObject:%271%27,commentOnly:%270%27,demangle:%270%27,directives:%270%27,execute:%270%27,intel:%270%27,libraryCode:%270%27,trim:%271%27),flagsViewOpen:%271%27,fontScale:14,fontUsePx:%270%27,j:2,lang:___c,libs:!(),options:%27-O1%27,selection:(endColumn:1,endLineNumber:1,positionColumn:1,positionLineNumber:1,selectionStartColumn:1,selectionStartLineNumber:1,startColumn:1,startLineNumber:1),source:1),l:%275%27,n:%270%27,o:%27+x86-64+gcc+8.5+(Editor+%231)%27,t:%270%27)),header:(),k:51.88153310104531,l:%274%27,n:%270%27,o:%27%27,s:0,t:%270%27)),l:%272%27,m:50,n:%270%27,o:%27%27,t:%270%27),(g:!((h:output,i:(compilerName:%276502-c%2B%2B+11.1.0%27,editorid:1,fontScale:14,fontUsePx:%270%27,j:2,wrap:%271%27),l:%275%27,n:%270%27,o:%27Output+of+x86-64+gcc+8.5+(Compiler+%232)%27,t:%270%27)),header:(),l:%274%27,m:50,n:%270%27,o:%27%27,s:0,t:%270%27)),l:%273%27,n:%270%27,o:%27%27,t:%270%27)),version:4" rel="nofollow noreferrer">Try it with Compiler Explorer


问:
Simplify a Date
This is similar to simplifying fractions, but with Dates!

The input of your program must be of the form mm/dd
For example

```<code>3/4 //March 4
12/15 //December 15
1/1 // January 1
</code>```

We assume that the input will be valid such that the months have these numbers of days in them:

```<code>January 31
February 28
March 31
April 30
May 31
June 30
July 31
August 31
September 30
October 31
November 30
December 31
</code>```

Your program's job is to take the assumed valid input, and iteratively (or recursively) simplify the date, and at each iteration (including the 0th), output the date with the full name of the month as written above.

For example:

Given an input of:

```<code>12/18
</code>```

Would output

```<code>December 18
June 9
February 3
</code>```

An input that is already simplified only outputs itself:

```<code>11/17
</code>```

Outputs:

```<code>November 17
</code>```

The month names cannot come from a function in your language. The strings can be obfuscated, computed, however you like, but you cannot use a standard function like GetMonthString(4) or something, you either have to write that function, or find a way to output the month names as described.

I cannot think of any cases where the simplified date produces an illegal date, but if ever you produce an illegal date along the way, output:

```<code>Illegal Date
</code>```

But if you are sure this cannot happen, you do not need to have code covering this case. The dates outputted just always need to be valid according to what was described above (it goes without saying that months and days start at 1).

The algorithm:

At each iteration you divide by the smallest number that divides numerator and denominator.

That is, you find all the numbers such that, dividing both the numerator and denominator by this number produces a new numerator and denominator that are both integers (common factors). Select the smallest one and individually divide the numerator and denominator to produce a new fraction.
If the only number you can divide by is 1, then you have simplified as much as possible and you stop.

I hope this is clear.

Any language is allowed. This is Code Golf, shortest code wins!

答:
Pyth - <s>116</s> 87 bytes

```<code>jm++@rR3c."ayÖèÈÒ+J÷z4wëÝ~ñ!Õ¥´{mCØóy|å²z¼qP?ë"\qhd;ed.u/RYNPiFKsMcz\/K
</code>```

Test Suite.

Title: Simplify a Date

Body:
Pyth - <s>116</s> 87 bytes

jm++@rR3c."ayÖèÈÒ+J÷z4wëÝ~ñ!Õ¥´{mCØóy|å²z¼qP?ë"\qhd;ed.u/RYNPiFKsMcz\/K

Test Suite.


问:
Sum It Up with a Digital Triangle
Well, sum it down really.

Write a program or function that takes in a nonempty list of decimal integers (0-9) and outputs a downward pointing "triangle" of digits with the input list at the top where every digit after the first line is the sum of the two digits above it modulo 10.

For example, the input [7, 5, 0, 9] has output

```<code>7 5 0 9
 2 5 9
  7 4
   1
</code>```

because 2 is (7 + 5) mod 10, 5 is (5 + 0) mod 10, 9 is (0 + 9) mod 10, etc. all the way to 1 being (7 + 4) mod 10.

If the list has only one item, then the output matches the input; e.g. an input of [4] will yield

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

Here are some additional examples:

```<code>[0]

0

[1, 2]

1 2
 3

[8, 7]

8 7
 5

[0, 0]

0 0
 0

[1, 4, 2]

1 4 2
 5 6
  1

[0, 1, 0]

0 1 0
 1 1
  2

[1, 0, 0, 0]

1 0 0 0
 1 0 0
  1 0
   1

[1, 2, 3, 4]

1 2 3 4
 3 5 7
  8 2
   0

[1, 2, 3, 5, 8]

1 2 3 5 8
 3 5 8 3
  8 3 1
   1 4
    5

[9, 2, 4, 5, 3, 2, 2]

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

Note that in the output:

The first line does not have leading spaces.

Each subsequent line has one more leading space than the line previous.

Digits are separated by a single space.

Each line is allowed to have up to one trailing space.

There may be a single optional trailing newline.

You must use the characters for normal decimal digits (0 through 9).

The shortest code in bytes wins. Tiebreaker is earlier answer.

答:
Pyth - 18 bytes

```<code>j.e+*dkjdbP.ueM+Vt
</code>```

Test Suite.

```<code>j                                       Join by newlines
 .e                                     Loop over seq in var b and index in var k
  +                                     Concatenate
   *dk                                  Space repeated k times
    jdb                                 Join b by spaces
  P                                     [:-1] to get rid of empty line
   .u             (Q implicit)          Cumulative fixed point over input (var G)
    eM                                  Mod 10 mapped over list
     +V                                 Vectorized addition
      t(G implict)                      G[1:]
      (G implict)                       Vectorize cuts this off to G[:-1]
</code>```

Title: Sum It Up with a Digital Triangle

Body:
Pyth - 18 bytes

j.e+*dkjdbP.ueM+Vt

Test Suite.

j                                       Join by newlines
 .e                                     Loop over seq in var b and index in var k
  +                                     Concatenate
   *dk                                  Space repeated k times
    jdb                                 Join b by spaces
  P                                     [:-1] to get rid of empty line
   .u             (Q implicit)          Cumulative fixed point over input (var G)
    eM                                  Mod 10 mapped over list
     +V                                 Vectorized addition
      t(G implict)                      G[1:]
      (G implict)                       Vectorize cuts this off to G[:-1]


Title: Pseudofactorial

Body:
JavaScript (ES6), <s>92</s> <s>88</s> <s>80</s> <s>74</s> 69 bytes:

Thanks @ConorOBrien and @Neil

y=>(g=(a,b)=>b?g(b,a%b):a,[...Array(y)].map((_,i)=>y=y*++i/g(y,i)),y)


答:
Jelly, <s>20</s> <s>19</s> 18 bytes

```<code>Ṛ+2\ṖÐ¿%⁵z”@ṚZGḟ”@
</code>```

Try it online!

Background

Generating the numbers is straightforward in Jelly. The output is a bit more complicated.

Jelly has a built-in grid atom (G) that displays a 2D list with newlines between rows and spaces between columns. We take the 2D array of numbers (generated with each row reversed), and transpose it with fill value @. After revering the resulting array and transposing again, applying G yield the following.

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

To obtain the desired triangular shape, all we have to do is remove the fill value.

How it works

```<code>Ṛ+2\ṖÐ¿%⁵z”@ṚZGḟ”@  Main link. Argument: A (list of integers)

Ṛ                   Reverse A.
    ṖÐ¿             While there's more than one element:
 +2\                  Compute the pairwise sum.
                    Collect all intermediate results in a list.
       %⁵           Take all resulting integers modulo 10.
         z”@        Transpose with fill value '@'.
            Ṛ       Reverse the order of the rows.
             Z      Transpose.
              G     Grid.
               ḟ”@  Filter; remove the fill value.
</code>```

Title: Sum It Up with a Digital Triangle

Body:
Well, sum it down really.

Write a program or function that takes in a nonempty list of decimal integers (0-9) and outputs a downward pointing "triangle" of digits with the input list at the top where every digit after the first line is the sum of the two digits above it modulo 10.

For example, the input [7, 5, 0, 9] has output

```<code>7 5 0 9
 2 5 9
  7 4
   1
</code>```

because 2 is (7 + 5) mod 10, 5 is (5 + 0) mod 10, 9 is (0 + 9) mod 10, etc. all the way to 1 being (7 + 4) mod 10.

If the list has only one item, then the output matches the input; e.g. an input of [4] will yield

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

Here are some additional examples:

```<code>[0]

0

[1, 2]

1 2
 3

[8, 7]

8 7
 5

[0, 0]

0 0
 0

[1, 4, 2]

1 4 2
 5 6
  1

[0, 1, 0]

0 1 0
 1 1
  2

[1, 0, 0, 0]

1 0 0 0
 1 0 0
  1 0
   1

[1, 2, 3, 4]

1 2 3 4
 3 5 7
  8 2
   0

[1, 2, 3, 5, 8]

1 2 3 5 8
 3 5 8 3
  8 3 1
   1 4
    5

[9, 2, 4, 5, 3, 2, 2]

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

Note that in the output:

The first line does not have leading spaces.

Each subsequent line has one more leading space than the line previous.

Digits are separated by a single space.

Each line is allowed to have up to one trailing space.

There may be a single optional trailing newline.

You must use the characters for normal decimal digits (0 through 9).

The shortest code in bytes wins. Tiebreaker is earlier answer.

Body:
Jelly, <s>20</s> <s>19</s> 18 bytes

Ṛ+2\ṖÐ¿%⁵z”@ṚZGḟ”@

Try it online!

Background

Generating the numbers is straightforward in Jelly. The output is a bit more complicated.

Jelly has a built-in grid atom (G) that displays a 2D list with newlines between rows and spaces between columns. We take the 2D array of numbers (generated with each row reversed), and transpose it with fill value @. After revering the resulting array and transposing again, applying G yield the following.

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

To obtain the desired triangular shape, all we have to do is remove the fill value.

How it works

Ṛ+2\ṖÐ¿%⁵z”@ṚZGḟ”@  Main link. Argument: A (list of integers)

Ṛ                   Reverse A.
    ṖÐ¿             While there's more than one element:
 +2\                  Compute the pairwise sum.
                    Collect all intermediate results in a list.
       %⁵           Take all resulting integers modulo 10.
         z”@        Transpose with fill value '@'.
            Ṛ       Reverse the order of the rows.
             Z      Transpose.
              G     Grid.
               ḟ”@  Filter; remove the fill value.


答:
MATL, <s>32</s> <s>30</s> <s>29</s> <s>28</s> <s>27</s> <s>26</s> <s>25</s> 24 bytes

```<code>t"X@qZ"y1X9&VhDTTH&Y+10\
</code>```

1 Byte saved thanks to @Luis

Try it Online!

Modified version for all test cases

Explanation

```<code>        % Implicitly grab input
t       % Duplicate the input
"       % For each element of the input (really just a shortcut to loop numel(input) times)
  X@q   % Determine the current loop index and subtract 1
  Z"    % Create an array of blanks this size (these are the padding to the left)
  y     % Copy the current array of numbers from the stack
  1X9   % Get the pre-defined output format of %.15g from the clipboard
  &V    % Convert the input to it's character representation with single spacing
  h     % Horizontally concatenate the left padding and the numbers
  D     % Display the result (consumes the string)
  TT    % Create a two-element vector of 1's ([1 1])
  H&Y+  % Convolve [1 1] with the array (computes the pair-wise sum)
  10\   % Mod 10 the result
        % Implicitly close for loop
</code>```

Title: Sum It Up with a Digital Triangle

Body:
MATL, <s>32</s> <s>30</s> <s>29</s> <s>28</s> <s>27</s> <s>26</s> <s>25</s> 24 bytes

t"X@qZ"y1X9&VhDTTH&Y+10\

1 Byte saved thanks to @Luis

Try it Online!

Modified version for all test cases

Explanation

        % Implicitly grab input
t       % Duplicate the input
"       % For each element of the input (really just a shortcut to loop numel(input) times)
  X@q   % Determine the current loop index and subtract 1
  Z"    % Create an array of blanks this size (these are the padding to the left)
  y     % Copy the current array of numbers from the stack
  1X9   % Get the pre-defined output format of %.15g from the clipboard
  &V    % Convert the input to it's character representation with single spacing
  h     % Horizontally concatenate the left padding and the numbers
  D     % Display the result (consumes the string)
  TT    % Create a two-element vector of 1's ([1 1])
  H&Y+  % Convolve [1 1] with the array (computes the pair-wise sum)
  10\   % Mod 10 the result
        % Implicitly close for loop


答:
05AB1E, <s>20</s> <s>19</s> 17 bytes

Code:

```<code>DvNð×?T%Ððý,¦‚ø€O
</code>```

Explanation:

```<code>D                     # Duplicate the input.
 v                    # Map over it, running the following len(input) times.
  Nð×                 # Multiply the iteration number with a space.
     ?                # Pop and print without a newline.
      T%              # Take all integers modulo 10.
        Ð             # Triplicate the array.
         ðý,          # Join by spaces and print with a newline.
            ¦         # Remove the first element of the array.
             ‚        # Wrap it up, (pop a, b push [a, b]).
              ø       # Zip.
               €O     # Sum up each element.
</code>```

Uses the CP-1252 encoding. Try it online!.

Title: Sum It Up with a Digital Triangle

Body:
05AB1E, <s>20</s> <s>19</s> 17 bytes

Code:

DvNð×?T%Ððý,¦‚ø€O

Explanation:

D                     # Duplicate the input.
 v                    # Map over it, running the following len(input) times.
  Nð×                 # Multiply the iteration number with a space.
     ?                # Pop and print without a newline.
      T%              # Take all integers modulo 10.
        Ð             # Triplicate the array.
         ðý,          # Join by spaces and print with a newline.
            ¦         # Remove the first element of the array.
             ‚        # Wrap it up, (pop a, b push [a, b]).
              ø       # Zip.
               €O     # Sum up each element.

Uses the CP-1252 encoding. Try it online!.


Title: Sum It Up with a Digital Triangle

Body:
JavaScript (ES6) 147 bytes

a=>{o=0;e=(c=>console.log(' '.repeat(o++)+c.join` `));l=1;while(l){p=0,d=[],e(a),a.map(b=>{p?d.push((v+b)%10):0;p=1,v=b});d.length<2?l=0:a=d};e(d)}


答:
Python 3.5, <s>74</s> <s>72</s> 71 bytes

f=lambda L,*S:f([sum(x)%10for x in zip(L,L[1:print(*S,*L)]or 1)],'',*S)
```

Input is a list of integers (e.g. f([1,2,3,5,8])), output is to STDOUT. The %10 and the fact that map returns a map object in Python 3 is a bit annoying, meaning we can't do map(lambda*x:sum(x)%10,L,L[1:]) or similar.

The function errors out, but by then the output would have completed. Thanks to @xsot for -1 byte by finding a good place to stick the print.

Title: Sum It Up with a Digital Triangle

Body:
Python 3.5, <s>74</s> <s>72</s> 71 bytes

f=lambda L,*S:f([sum(x)%10for x in zip(L,L[1:print(*S,*L)]or 1)],'',*S)

Input is a list of integers (e.g. f([1,2,3,5,8])), output is to STDOUT. The %10 and the fact that map returns a map object in Python 3 is a bit annoying, meaning we can't do map(lambda*x:sum(x)%10,L,L[1:]) or similar.

The function errors out, but by then the output would have completed. Thanks to @xsot for -1 byte by finding a good place to stick the print.


答:
Python, 46 bytes

g=lambda n,c=0:n<1or(c%n<1)*c or g(n,c+g(n-1))
```
<p>Looking for the multiple <code>c</code> of <code>g(n-1)</code> directly. I had though before that this method would wrongly find 0 as a multiple of anything, but the <code>or</code> short-circuiting or <code>(c%n<1)*c</code> will skip <code>c==0</code> as well because 0 is Falsey.</p>
<hr />
<p><strong>50 bytes:</strong></p>
<pre class="lang-python prettyprint-override"><code>g=lambda n,i=1:n<1or(i*n%g(n-1)<1)*i*n or g(n,i+1)
</code>```

Like Dennis's solution, but as a recursive function. Having computed g(n-1), looks for the smallest multiple i*n of n that's also a multiple of g(n-1). Really slow.

Thanks to Dennis for 4 bytes by looking at multiples of n instead of g(n-1).

Title: Pseudofactorial

Body:
Python, 46 bytes

g=lambda n,c=0:n<1or(c%n<1)*c or g(n,c+g(n-1))

Looking for the multiple c of g(n-1) directly. I had though before that this method would wrongly find 0 as a multiple of anything, but the or short-circuiting or (c%n<1)*c will skip c==0 as well because 0 is Falsey.

50 bytes:

g=lambda n,i=1:n<1or(i*n%g(n-1)<1)*i*n or g(n,i+1)

Like Dennis's solution, but as a recursive function. Having computed g(n-1), looks for the smallest multiple i*n of n that's also a multiple of g(n-1). Really slow.

Thanks to Dennis for 4 bytes by looking at multiples of n instead of g(n-1).


答:
Perl 6, 17 bytes

{$_??[==] $_!!$_}
```

<p><code>[==] $_</code> does a reduce of the input (<code>$_</code>) with <code>&infix:<==></code>. <code>&infix:<==></code> is a Numeric operator so it coerces its inputs to Numeric. The rest is just the ternary operator <code>??</code> <code>!!</code>.</p>

<p>This is roughly equivalent to</p>

<pre class="lang-perl6 prettyprint-override"><code>sub ( $_ ) {
  if $_ {
    # the ｢map｣ is for clarity, it is not needed
    $_.map(*.elems).reduce(&infix:<==>)
    # ｢[OP] List｣ is actually smarter than ｢List.reduce(&infix:«OP»)｣
    # as it takes into account operator chaining, and associativity
  } else {
    $_
  }
}
</code>```

Test:

#! /usr/bin/env perl6

use v6.c;
use Test;

# put it into the lexical namespace for clarity
my &same-elems = {$_??[==] $_!!$_}

my @tests = (
  [] => [],
  [[1], [1], [2]] => True,
  [[1],] => True,
  [[1, 2, 3, 4],] => True,
  [[1, 2, 3, 4, 5], [2], [12, 314123]] => False,
  [[1, 2, 3, 4], [1]] => False,
);

plan +@tests;

for @tests -> ( :key(@input), :value($expected) ) {
  is same-elems(@input), $expected, @input.perl
}
```

<pre class="lang-none prettyprint-override"><code>1..6
ok 1 - []
ok 2 - [[1], [1], [2]]
ok 3 - [[1],]
ok 4 - [[1, 2, 3, 4],]
ok 5 - [[1, 2, 3, 4, 5], [2], [12, 314123]]
ok 6 - [[1, 2, 3, 4], [1]]
</code>```

Title: Same length sub arrays

Body:
Background:

Here's a little simple challenge. You want to be able to find out whether the arrays inside an array have the same length.

Input:

Your input should consist of exactly one array (this is the value passed to the function, not a user input). Your function takes exactly 1 parameter.  It could contain arrays or be empty. No error checking needed, assume only list is ever passed in. Assume a 1-D array such as [1] or [1,2,3,4,5] is never passed in.

Output:

Return true if all the list elements have the same length, false if they don't, and the parameter itself if the list is empty (or null if your language doesn't support multiple return types).

Some test cases:

```<code>List: [] - [] (or null/your language equivalent)
List: [[1], [1], [2]] - True
List: [[1]] - True
List: [[1, 2, 3, 4]] - True
List: [[1, 2, 3, 4, 5], [2], [12, 314123]] - False
List: [[1, 2, 3, 4], [1]] - False
</code>```

No std(in/out) input/output needed (however, it is allowed, just not required!), the function only needs to return boolean values true or false; or the parameter itself if the function is passed an empty list (or null/your language equivalent). Only one return value is returned.

Rules:

Shortest byte count wins, only function is necessary (full programs are allowed if you desire).

Body:
Perl 6, 17 bytes

{$_??[==] $_!!$_}

[==] $_ does a reduce of the input ($_) with &infix:<==>. &infix:<==> is a Numeric operator so it coerces its inputs to Numeric. The rest is just the ternary operator ?? !!.

This is roughly equivalent to

sub ( $_ ) {
  if $_ {
    # the ｢map｣ is for clarity, it is not needed
    $_.map(*.elems).reduce(&infix:<==>)
    # ｢[OP] List｣ is actually smarter than ｢List.reduce(&infix:«OP»)｣
    # as it takes into account operator chaining, and associativity
  } else {
    $_
  }
}

Test:

#! /usr/bin/env perl6

use v6.c;
use Test;

# put it into the lexical namespace for clarity
my &same-elems = {$_??[==] $_!!$_}

my @tests = (
  [] => [],
  [[1], [1], [2]] => True,
  [[1],] => True,
  [[1, 2, 3, 4],] => True,
  [[1, 2, 3, 4, 5], [2], [12, 314123]] => False,
  [[1, 2, 3, 4], [1]] => False,
);

plan +@tests;

for @tests -> ( :key(@input), :value($expected) ) {
  is same-elems(@input), $expected, @input.perl
}

1..6
ok 1 - []
ok 2 - [[1], [1], [2]]
ok 3 - [[1],]
ok 4 - [[1, 2, 3, 4],]
ok 5 - [[1, 2, 3, 4, 5], [2], [12, 314123]]
ok 6 - [[1, 2, 3, 4], [1]]


答:
Perl 6, 13 bytes

{[lcm] 1..$_}
```

<p>Anonymous code block that creates a Range from 1 to the input (inclusive), and then reduces that with <code>&infix:<lcm></code>.</p>

<h3>Example:</h3>

<pre class="lang-perl6 prettyprint-override"><code>#! /usr/bin/env perl6
use v6.c;

my &postfix:<p!> = {[lcm] 1..$_}

say 1p!; # 1
say 2p!; # 2
say 3p!; # 6
say 4p!; # 12
say 5p!; # 60
say 6p!; # 60
say 7p!; # 420

say 10000p!; # 5793339670287642968692270879...
# the result from this is 4349 digits long
</code>```

Title: Pseudofactorial

Body:
There is a rather curious number which shows up sometimes in math problems or riddles. The pseudofactorial(N) is the least (i.e. lowest) common multiple of the numbers 1 through N; in other words, it's the lowest number which has all numbers from 1 through N as factors.

For instance pseudofactorial(7) = 3 * 4 * 5 * 7, which is the same as 7! except that 2 and 6 have been removed because they are contained in other terms.

Write a program to calculate pseudofactorial(N) and as always, shortest code wins.

Here is a short list for your use. More test cases can be found in the OEIS under A003418.

Factorial:

1

2

6

24

120

720

5040

Pseudofactorial:

1

2

6

12

60

60

420

Body:
Perl 6, 13 bytes

{[lcm] 1..$_}

Anonymous code block that creates a Range from 1 to the input (inclusive), and then reduces that with &infix:<lcm>.

Example:

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

my &postfix:<p!> = {[lcm] 1..$_}

say 1p!; # 1
say 2p!; # 2
say 3p!; # 6
say 4p!; # 12
say 5p!; # 60
say 6p!; # 60
say 7p!; # 420

say 10000p!; # 5793339670287642968692270879...
# the result from this is 4349 digits long


问:
Generalized Birthday Problem
Tonight, my fiancée took me out to dinner to celebrate my birthday. While we were out, I heard Happy Birthday sung to 5 different guests (including myself), in a restaurant full of 50 people. This got me wondering - the original birthday problem (finding the probability that 2 people in a room of N people share the same birthday) is very simple and straightforward. But what about calculating the probability that at least k people out of N people share the same birthday?

In case you're wondering, the probability of at least 5 people out of 50 total people sharing the same birthday is about 1/10000.

The Challenge

Given two integers N and k, where N >= k > 0, output the probability that at least k people in a group of N people share the same birthday. To keep things simple, assume that there are always 365 possible birthdays, and that all days are equally likely.

For k = 2, this boils down to the original birthday problem, and the probability is 1 - P(365, N)/(365)**N (where P(n,k) is the number of k-length permutations formed from n elements). For larger values of k, this Wolfram MathWorld article may prove useful.

Rules

Output must be deterministic, and as accurate as possible for your chosen language. This means no Monte Carlo estimation or Poisson approximation.

N and k will be no larger than the largest representable integer in your chosen language. If your chosen language has no hard maximum on integers (aside from memory constraints), then N and k may be arbitrarily large.

Accuracy errors stemming from floating-point inaccuracies may be ignored - your solution should assume perfectly-accurate, infinite-precision floats.

Test Cases

Format: k, N -> exact fraction (float approximation)

```<code>2, 4 -> 795341/48627125 (0.016355912466550306)
2, 10 -> 2689423743942044098153/22996713557917153515625 (0.11694817771107766)
2, 23 -> 38093904702297390785243708291056390518886454060947061/75091883268515350125426207425223147563269805908203125 (0.5072972343239854)
3, 3 -> 1/133225 (7.5060987051979735e-06)
3, 15 -> 99202120236895898424238531990273/29796146005797507000413918212890625 (0.0033293607910766013)
3, 23 -> 4770369978858741874704938828021312421544898229270601/375459416342576750627131037126115737816349029541015625 (0.01270542106874784)
3, 88 -> 121972658600365952270507870814168157581992420315979376776734831989281511796047744560525362056937843069780281314799508374037334481686749665057776557164805212647907376598926392555810192414444095707428833039241/238663638085694198987526661236008945231785263891283516149752738222327030518604865144748956653519802030443538582564040039437134064787503711547079611163210009542953054552383296282869196147657930850982666015625 (0.5110651106247305)
4, 5 -> 1821/17748900625 (1.0259790386313012e-07)
4, 25 -> 2485259613640935164402771922618780423376797142403469821/10004116148447957520459906484225353834116619892120361328125 (0.0002484237064787077)
5, 50 -> 786993779912104445948839077141385547220875807924661029087862889286553262259306606691973696493529913926889614561937/7306010813549515310358093277059651246342214174497508156711617142094873581852472030624097938198246993124485015869140625 (0.00010771867165219201)
10, 11 -> 801/8393800448639761033203125 (9.542757239717371e-23)
10, 20 -> 7563066516919731020375145315161/4825745614492126958810682272575693836212158203125 (1.5672327389589693e-18)
10, 100 -> 122483733913713880468912433840827432571103991156207938550769934255186675421169322116627610793923974214844245486313555179552213623490113886544747626665059355613885669915058701717890707367972476863138223808168550175885417452745887418265215709/1018100624231385241853189999481940942382873878399046008966742039665259133127558338726075853312698838815389196105495212915667272376736512436519973194623721779480597820765897548554160854805712082157001360774761962446621765820964355953037738800048828125 (1.2030611807765361e-10)
10, 200 -> 46037609834855282194444796809612644889409465037669687935667461523743071657580101605348193810323944369492022110911489191609021322290505098856358912879677731966113966723477854912238177976801306968267513131490721538703324306724303400725590188016199359187262098021797557231190080930654308244474302621083905460764730976861073112110503993354926967673128790398832479866320227003479651999296010679699346931041199162583292649095888379961533947862695990956213767291953359129132526574405705744727693754517/378333041587022747413582050553902956219347236460887942751654696440740074897712544982385679244606727641966213694207954095750881417642309033313110718881314425431789802709136766451022222829015561216923212248085160525409958950556460005591372098706995468877542448525403291516015085653857006548005361106043070914396018461580475651719152455730181412523297836008507156692430467118523245584181582255037664477857149762078637248959905010608686740872875726844702607085395469621591502118462813086807727813720703125 (1.21685406174776e-07)
</code>```

答:
Jelly, <s>17</s> 16 bytes

```<code>ĠZL
365ṗÇ€<¬µS÷L
</code>```

Extremely inefficient. Try it online! (but keep N below 3)

How it works

```<code>365ṗÇ€<¬µS÷L  Main link. Left argument: N. Right argument: K

365ṗ          Cartesian product; generate all lists of length N that consist of
              elements of [1, ..., 365].
    Ç€        Map the helper link over all generated lists. It returns the highest
              amount of people that share a single birthday.
      <       Compare each result with K.
       ¬      Negate.
        µS÷L  Take the mean by dividing the sum by the length.

ĠZL           Helper link. Argument: A (list of integers)

Ġ             Group the indices have identical values in A.
 Z            Zip; transpose rows with columns.
  L           Take the length of the result, thus counting columns.
</code>```

Title: Generalized Birthday Problem

Body:
Jelly, <s>17</s> 16 bytes

ĠZL
365ṗÇ€<¬µS÷L

Extremely inefficient. Try it online! (but keep N below 3)

How it works

365ṗÇ€<¬µS÷L  Main link. Left argument: N. Right argument: K

365ṗ          Cartesian product; generate all lists of length N that consist of
              elements of [1, ..., 365].
    Ç€        Map the helper link over all generated lists. It returns the highest
              amount of people that share a single birthday.
      <       Compare each result with K.
       ¬      Negate.
        µS÷L  Take the mean by dividing the sum by the length.

ĠZL           Helper link. Argument: A (list of integers)

Ġ             Group the indices have identical values in A.
 Z            Zip; transpose rows with columns.
  L           Take the length of the result, thus counting columns.


答:
Julia, <s>60</s> 59 bytes

```<code>\(x,s="")=x==[]?"":s*join(x," ")"
"*(diag(x'.+x,1)%10\" "s)
</code>```

Based on @Sp3000's answer. The function \ accepts an array as input and returns a string.

Try it online!

Title: Sum It Up with a Digital Triangle

Body:
Julia, <s>60</s> 59 bytes

\(x,s="")=x==[]?"":s*join(x," ")"
"*(diag(x'.+x,1)%10\" "s)

Based on @Sp3000's answer. The function \ accepts an array as input and returns a string.

Try it online!


答:
Haskell, <s>48</s> 46 bytes

```<code>f[]=Nothing
f x|h:t<-length<$>x=Just$all(==h)t
</code>```

Wraps the result in the Maybe type and returns Nothing if the input is the empty list and Just True/Just False otherwise.

Usage example:

```<code>*Main> map f [[],[[1],[2],[3]],[[1]],[[1,2,3,4]],[[1,2,3,4,5],[2],[12,314123]],[[1,2,3,4],[1]]]
[Nothing,Just True,Just True,Just True,Just False,Just False]
</code>```

How it works:

```<code>f[]=Nothing                   -- empty input
f x                           -- otherwise
   |(h:t)<-length<$>x         -- map length function over the input and bind h
                              -- to the first element and t to rest of the list
          =     all(==h)t     -- return whether all values in t equal h
           Just$              -- wrapped in the Maybe type
</code>```

Edit: @Lynn saved two bytes. Thanks!

Title: Same length sub arrays

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

f[]=Nothing
f x|h:t<-length<$>x=Just$all(==h)t

Wraps the result in the Maybe type and returns Nothing if the input is the empty list and Just True/Just False otherwise.

Usage example:

*Main> map f [[],[[1],[2],[3]],[[1]],[[1,2,3,4]],[[1,2,3,4,5],[2],[12,314123]],[[1,2,3,4],[1]]]
[Nothing,Just True,Just True,Just True,Just False,Just False]

How it works:

f[]=Nothing                   -- empty input
f x                           -- otherwise
   |(h:t)<-length<$>x         -- map length function over the input and bind h
                              -- to the first element and t to rest of the list
          =     all(==h)t     -- return whether all values in t equal h
           Just$              -- wrapped in the Maybe type

Edit: @Lynn saved two bytes. Thanks!


答:
Perl 6, <s> 65 63 62 </s> 61 bytes

<s>{put ' 'x my$++,$_ for @_,{.rotor(2=>-1).map(*.sum%10).list}...1}
{put ' 'x my$++,$_ for @_,{@(.rotor(2=>-1).map(*.sum%10))}...1}
{put ' 'x my$++,$_ for @_,{@(map *.sum%10,.rotor(2=>-1))}...1}</s>
{put ' 'x my$++,$_ for @_,{[map *.sum%10,.rotor(2=>-1)]}...1}```

<h3>Explanation:</h3>

<pre class="lang-perl6 prettyprint-override"><code>{ # anonymous block that takes the list as input (@_)

  put # print with trailing newline

    ' ' x ( my $ )++, # pad with one more space than previous iteration
    $_                   # the list to print for this iteration
    # The ｢.Str｣ method on a List puts spaces between elements
    # which is what ｢put｣ calls on anything that isn't a Str

  for # do that for every list produced from the following

    @_, # the input list

    { # anonymous block that takes the previous list as input ($_)

      [ # turn the following from a Seq into an Array

        map
          *.sum % 10, # sum the values and modulus 10 of the following:

          # take the previous list 2 at a time, backing up one
          $_.rotor( 2 => -1 )

      ]

    }

    ... # repeatedly call that block until:

    1   # the result is only one element long
}
</code>```

Example:

my &digital-triangle-sum = {put ' 'x my$++,$_ for @_,{[map *.sum%10,.rotor(2=>-1)]}...1}

for [7,5,0,9], [0,1,0], [1,0,0,0], [9,2,4,5,3,2,2] -> \List {
   digital-triangle-sum List

   put '';
}
```

<pre class="lang-none prettyprint-override"><code>7 5 0 9
 2 5 9
  7 4
   1

0 1 0
 1 1
  2

1 0 0 0
 1 0 0
  1 0
   1

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

Title: Sum It Up with a Digital Triangle

Body:
Perl 6, <s> 65 63 62 </s> 61 bytes

<s>{put ' 'x my$++,$_ for @_,{.rotor(2=>-1).map(*.sum%10).list}...1}
{put ' 'x my$++,$_ for @_,{@(.rotor(2=>-1).map(*.sum%10))}...1}
{put ' 'x my$++,$_ for @_,{@(map *.sum%10,.rotor(2=>-1))}...1}</s>
{put ' 'x my$++,$_ for @_,{[map *.sum%10,.rotor(2=>-1)]}...1}

Explanation:

{ # anonymous block that takes the list as input (@_)

  put # print with trailing newline

    ' ' x ( my $ )++, # pad with one more space than previous iteration
    $_                   # the list to print for this iteration
    # The ｢.Str｣ method on a List puts spaces between elements
    # which is what ｢put｣ calls on anything that isn't a Str

  for # do that for every list produced from the following

    @_, # the input list

    { # anonymous block that takes the previous list as input ($_)

      [ # turn the following from a Seq into an Array

        map
          *.sum % 10, # sum the values and modulus 10 of the following:

          # take the previous list 2 at a time, backing up one
          $_.rotor( 2 => -1 )

      ]

    }

    ... # repeatedly call that block until:

    1   # the result is only one element long
}

Example:

my &digital-triangle-sum = {put ' 'x my$++,$_ for @_,{[map *.sum%10,.rotor(2=>-1)]}...1}

for [7,5,0,9], [0,1,0], [1,0,0,0], [9,2,4,5,3,2,2] -> \List {
   digital-triangle-sum List

   put '';
}

7 5 0 9
 2 5 9
  7 4
   1

0 1 0
 1 1
  2

1 0 0 0
 1 0 0
  1 0
   1

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