title: Print Triangle Wave of Numbers

text:
# Question
Title: Print Triangle Wave of Numbers
Given the amplitude and period for a wave, print the wave. See sample output for more details. The total number of wave forms equals the period, and the height of each wave equals the amplitude. Amplitude and Period are less than 10. You can ignore the trailing spaces but not the leading spaces.

```
Sample Input
3 2

Sample Output
  3           3
 232         232
12321 12321 12321 12321
       232         232
        3           3

```

# Answer
# Dyalog APL, ~~43~~ 40 bytes

~~`{⍉⊃⍪/⍺⍴⊂(⌽⍪⊢)(n,1-n←2×⍵)↑↑b⍴¨⍕¨b←a,1↓⌽a←⍳⍵}`~~

`{⍉⊃⍪/⍺⍴⊂(⌽⍪⊢)n(1-n←2×⍵)↑↑⍴∘⍕¨⍨a,1↓⌽a←⍳⍵}` (Thanks, Moris Zucca)

This is a dyadic function with the amplitude as the right argument () and the period as the left argument (). A program that reads user input would take the same number of characters.

Drawing some inspiration from Martin Büttner's CJam answer:

```
{⍉⊃⍪/⍺⍴⊂(⌽⍪⊢)n(1-n←2×⍵)↑↑⍴∘⍕¨⍨a,1↓⌽a←⍳⍵}
                                   a←⍳⍵ ⍝ numbers 1 2 3, call them "a"
                                  ⌽     ⍝ reverse them: 3 2 1
                                1↓      ⍝ drop one: 2 1
                              a,        ⍝ prepend "a": 1 2 3 2 1
                         ⍴∘⍕¨⍨          ⍝ format a[i] and repeat it a[i] times:
                                        ⍝     (,'1') '22' '333' '22' (,'1')
                        ↑               ⍝ mix, i.e. obtain a character matrix:
                                        ⍝    ┌───┐
                                        ⍝    │1  │
                                        ⍝    │22 │
                                        ⍝    │333│
                                        ⍝    │22 │
                                        ⍝    │1  │
                                        ⍝    └───┘
             n(1-n←2×⍵)↑                ⍝ take a 2×⍵ by 1-2×⍵ matrix
                                        ⍝ (negative length extends backwards):
                                        ⍝    ┌─────┐
                                        ⍝    │  1  │
                                        ⍝    │  22 │
                                        ⍝    │  333│
                                        ⍝    │  22 │
                                        ⍝    │  1  │
                                        ⍝    │     │
                                        ⍝    └─────┘
        (⌽⍪⊢)                           ⍝ the reverse of it, vertically joined with it
                                        ⍝    ┌─────┐
                                        ⍝    │  1  │
                                        ⍝    │ 22  │
                                        ⍝    │333  │
                                        ⍝    │ 22  │
                                        ⍝    │  1  │
                                        ⍝    │     │
                                        ⍝    │  1  │
                                        ⍝    │  22 │
                                        ⍝    │  333│
                                        ⍝    │  22 │
                                        ⍝    │  1  │
                                        ⍝    │     │
                                        ⍝    └─────┘
     ⍺⍴⊂                                ⍝ take ⍺ copies
  ⊃⍪/                                   ⍝ join them vertically
 ⍉                                      ⍝ transpose

```
> 5 votes

# Answer
## Python - 135 chars

```
A,F=map(int,raw_input().split());R=range
for y in R(-A+1,A):print"".join((" %s"%x)[-x<s*y<1]for s in(1,-1)for x in R(1,A)+R(A,-1,-1))*F

```

This version with a leading space is 132 chars

```
A,F=map(int,raw_input().split());R=range
for y in R(-A+1,A):print"".join((" %s"%x)[-x<s*y<1]for s in(1,-1)for x in R(A)+R(A,0,-1))*F

```

It also can be considerably shorter if not required to read from stdin or even if the input is comma separated

For comma separated input, the first line becomes

```
A,F=input();R=range

```
> 4 votes

# Answer
## APL (77)

```
,/{×⍎⍵:⍵⋄' '}¨¨⊃∘↑∘⍕¨¨K⍴⊂(⊖M),⍨M←(2⍴N+N-1)↑(0 1↓M),⍨⌽M←(⌽⊖/¨M)×≥/¨M←⍳2⍴⊃N K←⎕

```
> 4 votes

# Answer
## J, 87 characters

As a program:

```
b=:]\@(]#~' '~:])(":@:>:@i.@-)
,.~^:(<:Y)(,.|.)@(' ',.~((<:({."1|."1)b),.b),' '$~2<:])X
        Y                                              X

```

---

runs like this:

```
,.~^:(<:2)(,.|.)@(' ',.~((<:({."1|."1)b),.b),' '$~2#<:) 3
  3           3
 232         232
12321 12321 12321 12321
       232         232
        3           3
,.~^:(<:4)(,.|.)@(' ',.~((<:({."1|."1)b),.b),' '$~2#<:) 2
 2       2       2       2       2       2       2       2
121 121 121 121 121 121 121 121 121 121 121 121 121 121 121 121
     2       2       2       2       2       2       2       2

```

It's 5 more characters if we need it as a function F:

```
3 F 2
  3           3
 232         232
12321 12321 12321 12321
       232         232
        3           3

```
> 3 votes

# Answer
## Haskell (~~226~~ ~~225~~ ~~222~~ ~~220~~ 214)

My try in Haskell:

```
import List
n!k|n>k=p:n!(k+1)++[p]|0<1=[p]where p=(n-1)?" "++k?show k++(n-k)?" ">>=id
f[n,k]=k?(n!1++(2*n-1)?' ':map reverse(n!1)++[(2*n-1)?' '])>>=id
main=interact$unlines.transpose.f.map read.words
(?)=replicate

```

Sorry guys, `(€)` is optimized away, it takes three bytes for one € as opposed to ! which only takes one byte each.
Here is a "beta Version", that doesn't satisfies the spec:

```
import List

-- Creates a single wave of numbers. k should be equal to 1
-- and is used for internal stuff,
wave n k|n==k=[peek]
        |otherwise = peek:wave n(k+1)++[peek] where
  peek=replicate(n-1)" "++replicate k(show k)++replicate(n-k)" ">>=id

-- Creates a full wave
-- k: number of waves, n: size of waves
fullWave[n,k]=unlines.transpose.concat.replicate k$wave n 1++map reverse(wave n 1)

main=interact$fullWave.map read.words

```
> 2 votes

# Answer
# CJam, 45 bytes

CJam is a lot younger than this challenge, so this answer is not eligible for the green checkmark (which should btw be updated to marinus's APL answer). This was still a fun little exercise though.

```
r~:I2*,{)IS*I@I\-z-_a*+I~)>I(S*+}%_Wf%+r~*zN*

```

Test it here.

The idea is to generate half a period *vertically*, like so:

```
  1
 22
333
 22
  1

```

(Plus the next empty row which SE swallows). This then duplicated, each row is reversed, and the second half of the period is appended. Then the entire thing is repeated by the number of periods, and ultimately the grid is transposed to orientate the wave along the horizontal.
> 1 votes

# Answer
# Canvas, 24 bytes

```
Ｈ（¹）＊！∔｝─Ｌ╷ ×；＋ ∔：↔∔⤢╶×↔

```

Try it here!
> 1 votes

---
Tags: code-golf, ascii-art
---


title: Rotate an ASCII art image

text:
# Question
Title: Rotate an ASCII art image
Out of all of the ASCII characters, it is easy to tell that some of them form groups that are rotations of the same basic character. For example, `V > ^ <`. This allows the possibility to construct ASCII art that can be rotated by multiples of 90 degrees and still remain ASCII art.

# The Challenge

Your goal is to golf a program that accepts ASCII art and the number of degrees to rotate it from STDIN, and prints the rotated ASCII art to STDOUT.

On the first line of input, your program will receive a number N. This number represents the width and height of the ASCII art.

You will then receive N more lines of exactly N characters each (the newline is not counted in this number). The size of the art will always be a square, although it may have padding in the form of spaces to make it a square.

You will then receive one more number on a final line: 90, 180, or 270. This represents how many degrees clockwise the picture should be rotated.

Note: The inputted image will only contain characters that can be rotated by the correct amount. If the input does not match these requirements exactly, no specific behavior is required.

As output, your program should print exactly N lines of N characters, with newlines after each line. The image should be rotated so that each character in the original has been replaced by a rotated version and has been moved to the correct place in the image.

## Examples (not very beautiful ASCII art)

Input

```
5
<- ||
|  |V
+->+
   |O
<--+
90

```

Output

```
^ +-^
| | |
| V
+-+--
 O <-

```

(Rotations by 90 and 270 won't look very good because the characters are not squares)

Input

```
6
+ /\ +
| \ \|
(  \/|
 \   )
I \ /
:) V $
180

```

Output

```
$ ^ (:
 / \ I
(   \
|/\  )
|\ \ |
+ \/ +

```

## Required Supported Characters

For all rotations (90, 180, and 270), the program should be able to rotate:

* Spaces, `+`, `@`, `X` and `O` which never change
* `V` `>` `<` `^`
* `|` `-` and `\` `/` (rotated by 180 they stay the same)

For 180 degree rotation, these additional characters must be supported

* `I` `N` `Z` `%` `:` `0` `=` `S` `~` `$` `#` which stay the same
* `P` `d`, `(` `)`, `[` `]`, `{` `}`, `M` `W`, and `9` `6`

# Answer
> 4 votes
## GolfScript, ~~79~~ ~~75~~ ~~73~~ 67 chars

```
n%(;)~90/{-1%zip{{.'V<^>P(d)[{]}M9W6/\/\|-|'4/\+{.}%n+.@?)=}%}%}*n*

```

Looks like my and Peter Taylor's solutions are experiencing a certain amount of convergence. Anyway, looks like I'm still a few chars ahead for now. :-) Thanks (and +1) to both Peter and copy for ideas that I've shamelessly stolen.

This code completely ignores the size given on the first line, since it's redundant information. It should even handle inputs with non-square dimensions, but it very much depends on all the input lines being padded to the same length. Trying to rotate the characters `P`, `d`, `(`, `)`, `[`, `]`, `{`, `}`, `M`, `W`, `9`, or `6` by 90 or 270 degrees may produce unexpected output; all other characters that are not explicitly remapped are retained unchanged.

Ps. Here's my original 79-char solution:

```
n%(;)~90/:z{-1%zip}*n*z'V<^>/|-\V>^<'{:c;{{.c?~.c=@if}%}*}:s~2z='P([{M96W}])d's

```

# Answer
> 5 votes
## C, 336 chars

I'm sure there's room for improvement.

```
char*a="<^>V|-|-/\\/\\ppdd(())[[]]{{}}MMWW9966",*p,*q;
n,x,y,r;
z(c){
    return(q=strchr(a,c))?a[(q-a&-4)+(q-a+r&3)]:c;
}
#define A(r)(r&3^3?1-r%4:0)*
f(r){
    return A(r)x+A(~-r)y+(r&2)/2*~-n;
}
main(){
    scanf("%d\n",&n);
    p=q=malloc(n*n+1);
    for(y=n;y--;q+=n)gets(q);
    scanf("%d",&r);
    for(r/=90;++y<n;puts(""))for(x=0;x<n;x++)putchar(z(p[f(r)+n*f(r+1)],r));
}

```

# Answer
> 4 votes
## Golfscript (80 79 78 77 76 chars)

```
n%(;)~90/{zip{-1%{'V<^>V|-|/\/''Pd()[]{}MW96'{.4*}%4/128,+{.}%+.@?)=}%}%}*n*

```

NB Entering the "undefined behaviour" permitted by invalid input can produce somewhat curious output, because of placeholder characters (outside ASCII) used for certain characters whose rotation by 90 degrees is not defined. For example, `(` would be mapped to code point 160, which in ISO-8859-1 and Unicode is a non-breaking space.

# Answer
> 4 votes
## javascript (181 chars)

```
a=prompt(f="V<^>V|-|/\\/P(d)P([{]}[}M9W6M9").split(n="\n");c=a.pop()/90;for(
b=a[0];c--;a=d.split(n))for(e=d=n;e<b*b;++e%b||(d+=n))d+=f[f.indexOf(g=a[b-e
%b][e/b|0])+1||a]||g;alert(d)

```

Requires every line to be padded to the given length.

# Answer
> 0 votes
# Canvas, 7 bytes

```
╶╶90┤÷↷

```

Try it here!

~~basically cheating~~

---
Tags: code-golf, ascii-art
---


title: Rectangular pseudo-fractal

text:
# Question
Title: Rectangular pseudo-fractal
### Goal

The program's goal is to draw an ASCII art rectangle repeatedly doubled in size, alternating horizontally and vertically. Each time the rectangle doubles in size, the extra area is represented by a different character and the previous areas remain unchanged. The two smallest sections contain one character each and may be in any corner.

The program accepts a single integer as input, defining the number of sections the full rectangle contains.

No other external resources or inputs are allowed.

### Sample input and output

```
10

ABDDFFFFHHHHHHHHJJJJJJJJJJJJJJJJ
CCDDFFFFHHHHHHHHJJJJJJJJJJJJJJJJ
EEEEFFFFHHHHHHHHJJJJJJJJJJJJJJJJ
EEEEFFFFHHHHHHHHJJJJJJJJJJJJJJJJ
GGGGGGGGHHHHHHHHJJJJJJJJJJJJJJJJ
GGGGGGGGHHHHHHHHJJJJJJJJJJJJJJJJ
GGGGGGGGHHHHHHHHJJJJJJJJJJJJJJJJ
GGGGGGGGHHHHHHHHJJJJJJJJJJJJJJJJ
IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ
IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ
IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ
IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ
IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ
IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ
IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ
IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ

```

### Selection criteria

The shortest code in a week wins the points.

# Answer
# APL, 25 chars/bytes\*

```
{⍉⍣⍵⊃{a,⍺⍴⍨⍴a←⍉⍪⍵}/⌽⍵↑⎕A}

```

**Exploded view**

```
{                   ⍵↑⎕A}   ⍝ take the first ⍵ letters
    ⊃{           }/⌽        ⍝ fold over them, using the first one as initial accum. value
            a←⍉⍪⍵           ⍝    ensure the accum. is a table, transpose it and call it 'a'
        ⍺⍴⍨⍴                ⍝    make a table as large as 'a' filled with the next letter
      a,                    ⍝    append it to the right of 'a' and loop as new accumulator
 ⍉⍣⍵                        ⍝ transpose the result as many times as the original ⍵ number

```

**Examples**

```
      {⍉⍣⍵⊃{a,⍺⍴⍨⍴a←⍉⍪⍵}/⌽⍵↑⎕A}¨⍳8
A AB  AB  ABDD  ABDD  ABDDFFFF  ABDDFFFF  ABDDFFFFHHHHHHHH
      CC  CCDD  CCDD  CCDDFFFF  CCDDFFFF  CCDDFFFFHHHHHHHH
                EEEE  EEEEFFFF  EEEEFFFF  EEEEFFFFHHHHHHHH
                EEEE  EEEEFFFF  EEEEFFFF  EEEEFFFFHHHHHHHH
                                GGGGGGGG  GGGGGGGGHHHHHHHH
                                GGGGGGGG  GGGGGGGGHHHHHHHH
                                GGGGGGGG  GGGGGGGGHHHHHHHH
                                GGGGGGGG  GGGGGGGGHHHHHHHH

```

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
<sup>\*: APL can be written in its own (legacy) single-byte charset that maps APL symbols to the upper 128 byte values. Therefore, for the purpose of scoring, a program of N chars *that only uses ASCII characters and APL symbols* can be considered to be N bytes long.</sup>
> 10 votes

# Answer
### GolfScript, 30 characters

```
~(,[0`]{{[49+]1$,*+}+%zip}@/n*

```

Example (run online):

```
> 7
01335555
22335555
44445555
44445555
66666666
66666666
66666666
66666666

```
> 9 votes

# Answer
## Python 2.7 - 85 ~~103~~

This uses the `zip(*s)` syntax to continually transpose the list. **Big thanks to Daniel for his tip that shaved 12 characters!** Then shaved a few more by using numbers instead of letters.

```
s=[]
for i in range(input()):x=1<<i/2;s=zip(*s+[chr(65+i)*x]*x)
for i in s:print''.join(i)

```

Also, this uses `1<<x` rather than `2**x` as bit shift has lower(?) precedence. Observe:

```
>>> 1<<(2*3)
64
>>> 1<<2*3
64
>>> 2**2*3
12
>>> 2**(2*3)
64

```

And some output:

```
10
01335555777777779999999999999999
22335555777777779999999999999999
44445555777777779999999999999999
44445555777777779999999999999999
66666666777777779999999999999999
66666666777777779999999999999999
66666666777777779999999999999999
66666666777777779999999999999999
88888888888888889999999999999999
88888888888888889999999999999999
88888888888888889999999999999999
88888888888888889999999999999999
88888888888888889999999999999999
88888888888888889999999999999999
88888888888888889999999999999999
88888888888888889999999999999999

```
> 7 votes

# Answer
## Ruby, 88

Reads N from standard input.

```
s=[?A]
66.upto(64+gets.to_i){|i|x=i.chr*y=s.size;i%2<1?s.map!{|r|r+x}:s+=[x*2]*y}
puts s

```

Example Usage for N=8:

```
echo 8 | rectangular-pseudo-fractal.rb

```

Output:

```
ABDDFFFFHHHHHHHH
CCDDFFFFHHHHHHHH
EEEEFFFFHHHHHHHH
EEEEFFFFHHHHHHHH
GGGGGGGGHHHHHHHH
GGGGGGGGHHHHHHHH
GGGGGGGGHHHHHHHH
GGGGGGGGHHHHHHHH

```

N=10

```
echo 10 | rectangular-pseudo-fractal.rb

```

Output:

```
ABDDFFFFHHHHHHHHJJJJJJJJJJJJJJJJ
CCDDFFFFHHHHHHHHJJJJJJJJJJJJJJJJ
EEEEFFFFHHHHHHHHJJJJJJJJJJJJJJJJ
EEEEFFFFHHHHHHHHJJJJJJJJJJJJJJJJ
GGGGGGGGHHHHHHHHJJJJJJJJJJJJJJJJ
GGGGGGGGHHHHHHHHJJJJJJJJJJJJJJJJ
GGGGGGGGHHHHHHHHJJJJJJJJJJJJJJJJ
GGGGGGGGHHHHHHHHJJJJJJJJJJJJJJJJ
IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ
IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ
IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ
IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ
IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ
IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ
IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ
IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ

```
> 5 votes

# Answer
**J, 57 43**

```
(,`,.@.(=/@$@[)$${&a.@(66+2&^.@#@,)^:)1$'A'

```

Examples:

```
5 (,`,.@.(=/@$@[)$${&a.@(66+2&^.@#@,)^:)1$'A'
ABDDFFFF
CCDDFFFF
EEEEFFFF
EEEEFFFF

7 (,`,.@.(=/@$@[)$${&a.@(66+2&^.@#@,)^:)1$'A'
ABDDFFFFHHHHHHHH
CCDDFFFFHHHHHHHH
EEEEFFFFHHHHHHHH
EEEEFFFFHHHHHHHH
GGGGGGGGHHHHHHHH
GGGGGGGGHHHHHHHH
GGGGGGGGHHHHHHHH
GGGGGGGGHHHHHHHH

```
> 4 votes

# Answer
**MATLAB, 86 Characters**

My shortest try in MATLAB, pimped by @flawr (twice!):

```
function M=f(n)
M='';
if n
M=cat(mod(n,2)+1,f(n-1),64+n*ones(2.^fix(n/2-[.5,1])));
end

```

Example output:

```
>> disp(f(7))
ACEEGGGG
BCEEGGGG
DDEEGGGG
DDEEGGGG
FFFFGGGG
FFFFGGGG
FFFFGGGG
FFFFGGGG

```
> 4 votes

# Answer
## C#, 239 185 182 180 bytes

C# has nothing on the less verbose languages.

```
using C=System.Console;
class P{
    static void Main(string[]a){
        for(int x,i,n=int.Parse(a[0]);n-->0;C.CursorTop=0)
            for(i=1<<n,x=1<<n/2+n%2;i-->0;)
                C.Write((char)(n+33)+(i%x<1?"\n":""));
    }
}

```

Output, characters chosen for prettiness:

```
!"$$&&&&((((((((****************
##$$&&&&((((((((****************
%%%%&&&&((((((((****************
%%%%&&&&((((((((****************
''''''''((((((((****************
''''''''((((((((****************
''''''''((((((((****************
''''''''((((((((****************
))))))))))))))))****************
))))))))))))))))****************
))))))))))))))))****************
))))))))))))))))****************
))))))))))))))))****************
))))))))))))))))****************
))))))))))))))))****************
))))))))))))))))****************

```
> 3 votes

# Answer
# q \[73 chars\]

```
{"c"$64+{n:x 0;m:x 1;if[2>n;m:(),m];(o;$[n-2*n div 2;,';,][m;(#m;#m 0)#o:n+1])}/[x-1;(1;1)]1}

```

### example

```
10
"ABDDFFFFHHHHHHHHJJJJJJJJJJJJJJJJ"
"CCDDFFFFHHHHHHHHJJJJJJJJJJJJJJJJ"
"EEEEFFFFHHHHHHHHJJJJJJJJJJJJJJJJ"
"EEEEFFFFHHHHHHHHJJJJJJJJJJJJJJJJ"
"GGGGGGGGHHHHHHHHJJJJJJJJJJJJJJJJ"
"GGGGGGGGHHHHHHHHJJJJJJJJJJJJJJJJ"
"GGGGGGGGHHHHHHHHJJJJJJJJJJJJJJJJ"
"GGGGGGGGHHHHHHHHJJJJJJJJJJJJJJJJ"
"IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ"
"IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ"
"IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ"
"IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ"
"IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ"
"IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ"
"IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ"
"IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ"

3
"AB"
"CC"

6
"ABDDFFFF"
"CCDDFFFF"
"EEEEFFFF"
"EEEEFFFF"

```
> 3 votes

# Answer
# Sclipting, 59 characters

```
❶塊갠分감⓶左貶終辦감標가⓺貶⓹開上❶❶貶雙是不⒉갠乘⒉終가①上뀀❷②갠分小是增終❸⓷另要감右⓶갠加⓶終丟字⓶終丟겠終

```

(This program could be quite a bit shorter if I had instructions for base-2 logarithm, but I don’t, so I do it manually with a loop.)

## Annotated code

`n` is the input.

```
❶ | n n

f = i => (1 << (i/2)) - 1;
塊갠分감⓶左貶終 | n n f

w = f(n);
辦 | n w f

d = 1;
감 | n w f d

s = "";
標 | n w f d M [s]

for (y in [0..f(n-1)])
가⓺貶⓹開上 | w d M [s] y

    if ((y & (y-1)) == 0) d *= 2;
    ❶❶貶雙是不⒉갠乘⒉終 | w d M [s] y

    for (x in [0..w])
    가①上 | w d M [s] y x

        c = 64; // '@'
        뀀 | w d M [s] y x c

        if (x < d/2) c++;
        ❷②갠分小是增終 | w d M [s] y x c

        a = x | y;
        ❸⓷另 | w d M [s] y c a

        while (a > 0) { a >>= 1; c += 2; }
        要감右⓶갠加⓶終丟 | w d M [s] y c

        s += (char) c;
        字⓶ | w d M [s] y
    終丟 | w d M [s]

    s += "\n"
    겠 | w d M [s]
終

```

## Output

For `n` = 6:

```
ABDDFFFF
CCDDFFFF
EEEEFFFF
EEEEFFFF

```

Of course you can change `뀀` (`@`) to any other base character, e.g. with  (space) and `n` = 7:

```
!"$$&&&&
##$$&&&&
%%%%&&&&
%%%%&&&&
''''''''
''''''''
''''''''
''''''''

```

The highest number that doesn’t make the program longer is  (= 255), which gives us (`n` = 8 this time):

```
Āāăăąąąąćććććććć
ĂĂăăąąąąćććććććć
ĄĄĄĄąąąąćććććććć
ĄĄĄĄąąąąćććććććć
ĆĆĆĆĆĆĆĆćććććććć
ĆĆĆĆĆĆĆĆćććććććć
ĆĆĆĆĆĆĆĆćććććććć
ĆĆĆĆĆĆĆĆćććććććć

```

If we make the program 1 character longer, e.g. use `냟및` (= `\u4DFF`) and `n` = 9, we get:

```
一丁七七丅丅丅丅万万万万万万万万
丂丂七七丅丅丅丅万万万万万万万万
丄丄丄丄丅丅丅丅万万万万万万万万
丄丄丄丄丅丅丅丅万万万万万万万万
丆丆丆丆丆丆丆丆万万万万万万万万
丆丆丆丆丆丆丆丆万万万万万万万万
丆丆丆丆丆丆丆丆万万万万万万万万
丆丆丆丆丆丆丆丆万万万万万万万万
丈丈丈丈丈丈丈丈丈丈丈丈丈丈丈丈
丈丈丈丈丈丈丈丈丈丈丈丈丈丈丈丈
丈丈丈丈丈丈丈丈丈丈丈丈丈丈丈丈
丈丈丈丈丈丈丈丈丈丈丈丈丈丈丈丈
丈丈丈丈丈丈丈丈丈丈丈丈丈丈丈丈
丈丈丈丈丈丈丈丈丈丈丈丈丈丈丈丈
丈丈丈丈丈丈丈丈丈丈丈丈丈丈丈丈
丈丈丈丈丈丈丈丈丈丈丈丈丈丈丈丈

```
> 3 votes

# Answer
# PERL, 122 chars

```
$N=<>;$x=$r=1;do{$_=chr$a+++65;$s=$x;$o=$_ x$s;$o.=$_++x$s,$s*=2while$N+65>ord++$_;print"$o\n"x$r;$r=$x;$x*=2}while++$a<$N

```

with added whitespace:

```
$N=<>;
$x=$r=1;
do{
    $_=chr$a+++65;
    $s=$x;
    $o=$_ x$s;
    $o.=$_++x$s,$s*=2
        while $N+65>ord++$_;
    print "$o\n"x$r;
    $r=$x;
    $x*=2
} while++$a<$N

```

Output:

```
$ echo 8 | perl pseudo-fractal.pl
ABDDFFFFHHHHHHHH
CCDDFFFFHHHHHHHH
EEEEFFFFHHHHHHHH
EEEEFFFFHHHHHHHH
GGGGGGGGHHHHHHHH
GGGGGGGGHHHHHHHH
GGGGGGGGHHHHHHHH
GGGGGGGGHHHHHHHH

```
> 2 votes

# Answer
# PERL,  94  81 chars

```
$N=$_;$_=$:=A;$h=1;++$i%2?s/$/$:x$h/gem:($_.=($/.$:x2x$h)x$h,$h*=2)while++$:,--$N

```

It constructs the fractal iteratively letter by letter, adding new rows and columns and rows and columns... Uses simple string operations to do that. Note that I am abusing standard variable instead of letter one to allow for syntax sugar (like omitting spaces - `$:x2` etc.)

With added whitespace and comments:

```
$N=$_;
$_=$:=A;                    # $: is current letter
$h=1;

++$i%2?
s/$/$:x$h/gem:              # every odd run - add "columns"
($_.=($/.$:x2x$h)x$h,$h*=2) # every even run - add "rows"
while++$:,--$N              # iterate over letters

```

Some output:

```
$ echo 8 | perl -p pseudo-fractal.fill.pl.5a5
ABDDFFFFHHHHHHHH
CCDDFFFFHHHHHHHH
EEEEFFFFHHHHHHHH
EEEEFFFFHHHHHHHH
GGGGGGGGHHHHHHHH
GGGGGGGGHHHHHHHH
GGGGGGGGHHHHHHHH
GGGGGGGGHHHHHHHH

```
> 1 votes

# Answer
# Sclipting, 45 characters

```
가⓶貶上倘감雙⓶壹長⓸講增字⓶復⓷是標⓷各①合終并不⓶梴❸⓶疊合終不뀐標뀐并終終⓶丟各겠終

```

This solution works completely differently from the other Sclipting solution. It’s much more boring, but it’s shorter...

## Annotated

```
for i in [0..n-1]
가⓶貶上
    if (i != 0)
    倘
        i &= 1
        감雙
        e = list[0].Length
        ⓶壹長
        c = ((char) (c[0] + 1)).Repeat(e)
        ⓸講增字⓶復
        if (i)
        ⓷是
            concatenate c onto every element of list
            標⓷各①合終并
        else
        不
            concatenate c.Repeat(list.Length) onto list
            ⓶梴❸⓶疊合
        終
    else (i.e., i == 0)
    不
        c = "A"
        뀐
        list = ["A"]
        標뀐并
    終
終
concatenate "\n" to every element in list
⓶丟各겠終

```
> 1 votes

# Answer
### Delphi 348 || 449 with indent

### Without indent

```
var inp,j,i,x: integer;s:string;L:TStringlist;begin L:=TStringList.Create;readln(s);inp:=StrToIntDef(s,4);if inp<4then inp:=4;s:='';l.Add('AB');for I:=2to inp-1do begin j:=Length(L[0]);if i mod 2=0then for x:=0to L.Count-1do L.Add(s.PadLeft(j,Chr(65+i)))else for x:=0to L.Count-1do L[x]:=L[x]+s.PadLeft(j,Chr(65+i));end;Write(L.GetText);readln;end.

```

### With indent

```
var
  inp,j,i,x: integer;
  s:string;
  L:TStringlist;
begin
  L:=TStringList.Create;
  readln(s);
  inp:=StrToIntDef(s,4);
  if inp<4then inp:=4;
  s:='';
  l.Add('AB');

  for I:=2to inp-1do
  begin
    j:=Length(L[0]);
    if i mod 2=0then
      for x:=0to L.Count-1do L.Add(s.PadLeft(j,Chr(65+i)))
    else
      for x:=0to L.Count-1do
        L[x]:=L[x]+s.PadLeft(j,Chr(65+i));
  end;
  Write(L.GetText);
  readln;
end.

```
> 1 votes

# Answer
# CJam, 30 (23) bytes

CJam is a few months younger than this challenge so it's not eligible for the green checkmark.

```
l~(Sa1${{_,I'!+*+}%z}fI\{z}*N*

```

Test it here.

The OP clarified in a comment that any set of unique printable characters is allowed, so I'm just taking the printable ASCII characters from the start (with a space in the corner, `!` next and so on).

If the orientation may change between even and odd inputs (which I don't think, but that's what the GolfScript submission does), I can do it in 25 bytes:

```
S]l~({{_,I'!+*+}%z}fIN*

```

The idea is really simple: start with a grid containing a space, and then N-1 times transpose it and double all lines with the next character.

For the long version, at the end I also transpose again N-1 times in order to guarantee a consistent orientation.
> 1 votes

# Answer
# Canvas, 22 bytes

```
A；╷｛┐⤢ｌ；Ｌ┘¹Ｚｊ＠┘┘＊＋｝╶［⤢

```

Try it here!
> 0 votes

---
Tags: code-golf, ascii-art
---


# Question
Title: Arithmetic mean of prime Fibonacci Numbers up to the x Fibonacci Number
You should have heard about the **Fibonacci Numbers**, often called the Fibonacci Sequence. In this sequence the first two terms are 0 and 1, and every number after the first two is the sum of the two preceding ones. In other words, `F(n) = F(n-1) + F(n-2)`.

Here are the first 20 Fibonacci numbers:

```
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181

```

---

## Task:

Given an integer `x`, compute the arithmetic mean (the average) of the prime Fibonacci Numbers up to the `x` number of the Fibonacci Sequence.

## Rules:

* the Fibonacci sequence starts with 0 and 1 for this challenge
* `3 < x < 40`, because higher values of `x` might cause some huge execution time or overflows and smaller values have no output
* 1 is ***NOT*** prime, since it only has 1 divisor
* the arithmetic mean should include decimals, if it's the case, or should be displayed as an exact fraction
* you are only allowed to take `x` as input and the code needed to take the input does not count (e.g: if you need something like `x = input()`, you should not take it into consideration when counting the bytes)

---

## Examples:

**Ex. 1:** For `x=10`, the output is `5.75`, because the 10th Fibonacci number is `55` and the prime Fibonacci numbers up to `55` are `2, 3, 5, 13`, their average being `5.75`

Following the explanation from example 1, other examples are:

**Ex. 2:** For `x=15`, the output is `57.5`

**Ex. 3:** For `x=20`, the output is `277.428571428571`, or any other close approximation. In this case `277.4286`, for instance, is an accepted value

**Ex. 4:** For `x=11`, the output is `22.4`

**Ex. 5:** For `x=30`, the output is `60536.4444444444`, or any other close approximation, such as `60536.444`

---

## Leaderboard:

```
var QUESTION_ID=112025,OVERRIDE_USER=59487;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="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});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;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>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;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

---

To change the leader, submit a shorter valid solution. Your code should be as short as possible, since this is , so the shortest answer in bytes wins. Good luck!

# Answer
# Actually, 10 bytes

Code:

```
R♂F;Mr♂P∩æ

```

Explanation:

```
R            # On the input, create the range [1 .. input].
 ♂F          # Map the nth Fibonacci command over it.
   ;M        # Duplicate and get the maximum of the list.
     r       # Create the range [0 .. maximum - 1].
      ♂P     # Map the nth prime operator over each element (zero-indexed).
        ∩    # Intersection of both.
         æ   # Get the mean and implicitly display.

```

Uses the **CP-437** encoding. Try it online!
> 5 votes

# Answer
# Python 2, 71 bytes

```
s=2.;a=b=c=1
exec"p=2**a%a==2;c+=p;s+=a*p;a,b=b,a+b;"*input()
print s/c

```

Try it online!

Python doesn't have useful arithmetic built-ins for this, so we do things by hand. The code iterates through Fibonacci numbers via `a,b=b,a+b` starting from `a=b=1`.

The Fermat primality test with base 2 is used to identify primes as `a` where `2^a == 2 (mod a)`. Though this only checks for probable primes, none of the false positives are within the first 40 Fibonacci numbers.

The current sum `s` and count `c` of primes are updated each time a prime is encountered, and their ratio (the mean) is printed at the end. Because the prime check misses `a=2` and it's guaranteed to be in the input range, the sum starts at 2 and the count starts at 1 to compensate.
> 12 votes

# Answer
# Jelly, 11 bytes

```
ÆḞ€ÆPÐfµS÷L

```

Try it online!

### How it works

```
ÆḞ€ÆPÐfµS÷L  Main link. Argument: n (integer)

ÆḞ€          Map the Fibonacci atom over [1, ..., n].
   ÆPÐf      Filter by primality.
       µ     Begin a new chain. Argument: A (array of Fibonacci primes)
        S    Yield the sum of A.
          L  Yield the length of A.
         ÷   Compute the quotient.

```
> 8 votes

# Answer
# Mathematica, 38 bytes

```
Mean@Select[Fibonacci@Range@#,PrimeQ]&

(* or *)

Mean@Select[Fibonacci~Array~#,PrimeQ]&

```

**Explanation**

```
Mean@Select[Fibonacci@Range@#,PrimeQ]&
                                     &  (* For input # *)
                      Range@#           (* List {1, 2, 3, ... #} *)
            Fibonacci@                  (* Find the corresponding fibonacci numbers *)
     Select[                 ,PrimeQ]   (* Select the prime terms *)
Mean@                                   (* Take the Mean *)

```
> 7 votes

# Answer
# Perl 6, 51 bytes

```
{sum($/=[grep *.is-prime,(0,1,*+*...*)[0..$_]])/$/}

```

Try it

## Expanded:

```
{
  sum(
    $/ = [                # store as an Array in $/

      grep
        *.is-prime,       # find the primes
        (
          0, 1, *+* ... * # Fibonacci sequence
        )[ 0 .. $_ ]      # grab the indicated values in the sequence

    ]
  )

  /

  $/   # use the Array as a number (elems)
}

```
> 6 votes

# Answer
# MATL, 16 bytes

```
lOi:"yy+]vtZp)Ym

```

Try it online!

### Explanation

```
lO     % Push 1, then 0. This way the generated numbers with indices 1, 2, 3, ...
       % will be 1, 1, 2, ... as required
i      % Input n
:"     % Do the following n times
  yy   %   Duplicate top two numbers
  +    %   Add
]      % End
v      % Concatenate all numbers into a column vector
t      % Duplicate
Zp     % Vector of logical values: true for prime numbers, false otherwise
)      % Apply that vector as an index. This keeps only prime numbers
Ym     % Mean. Implicitly display

```
> 5 votes

# Answer
# Octave, ~~75~~ 71 bytes

```
@(n)mean((t=fix(((1+(s=5^.5)).^(x=1:n)-(1-s).^x)/s./2.^x))(isprime(t)))

```

Anonymous function that uses Binet's formula. Input and output are in the form of function arguments.

Try it online!
> 4 votes

# Answer
# Maxima, 49 bytes

```
f(n):=mean(sublist(makelist(fib(x),x,n),primep));

```
> 4 votes

# Answer
# Prolog (SWI), ~~269~~ ~~264~~ ~~254~~ 218 bytes

* Thanks to *Fatalize* for saving 37 bytes!
* Thanks to *Emigna* for saving 9 bytes!

I'm fairly certain that I could golf some more bytes down.

```
X/X:-X<3.
N/R:-A is N-1,B is N-2,A/C,B/D,R is C+D.
2^0^0.
C^S^E:-G is C-1,G/M,G^Q^R,(p(M)->S=M+Q,E is R+1;S=Q,E is R).
a(X,S):-X^R^Q,S is R/Q.
p(N):-N*(N-1).
p(2).
p(3).
N*2:-N mod 2=\=0.
N*C:-N mod C=\=0,D is C-1,N*D.

```

Run it as **`a(15, R).`** for **x = 15**, **R** is the output variable.

Try it online!

---

A more readable version:

```
fibonacci(1, 1) :- !.
fibonacci(2, 2) :- !.

fibonacci(N, R) :-
  N0 is N - 1,
  N1 is N - 2,
  fibonacci(N0, R1),
  fibonacci(N1, R2),
  R is R1 + R2.

listed(2, 0, 0) :- !.

listed(C, S, Successes) :-
  C0 is C - 1,
  fibonacci(C0, Result),
  listed(C0, S0, S1),
  (
    is_prime(Result)
    ->
      S = Result + S0, Successes is S1 + 1
    ; S = S0, Successes is S1
  ).

f(X, S) :-
  listed(X, R, Q),
  S is R / Q.

is_prime(Num) :- is_prime(Num, Num - 1).

is_prime(2).
is_prime(3).

is_prime(Num, 2) :- Num mod 2 =\= 0, !.

is_prime(Num, C) :-
  Num mod C =\= 0,
  C0 is C - 1,
  is_prime(Num, C0).

```
> 4 votes

# Answer
# Röda, ~~98~~ ~~94~~ 93 bytes

```
f n{z=0;i=1;j=1;s=0;seq 2,n-1|{|_|c=i+j;i=j;j=c;seq 2,c-1|{z+=1;s+=c}if[c%p>0]()for p}_[s/z]}

```

It's a function that returns the result as a floating point number.

Ungolfed version:

```
function f(n) {
    i = 1
    j = 1
    sum = 0
    num = 0
    seq(2, n-1) | for _ do
        /* calculate next fibonacci number: */
        c = i+j
        i = j
        j = c
        /* if it's prime: */
        {
            num += 1
            sum += c
        /* primality test: */
        } if [c%p > 0]() for p in [seq(2, c-1)]
    done
    return sum/num
}

```
> 3 votes

# Answer
# 05AB1E, 13 bytes

```
!ÅF¹£DpÏDOsg/

```

Try it online! or as a Test suite

**Explanation**

```
!ÅF             # get a list of fibonacci numbers up to fac(input)
   ¹£           # take the first input elements of that list
     D          # duplicate
      p         # isprime on the copy
       Ï        # keep the fibonacci numbers which are true in the isprime list
        D       # duplicate the list of fibonacci primes
         O      # sum the list
          s     # swap the other copy to the top of the stack
           g    # get its length
            /   # divide sum by length

```
> 3 votes

# Answer
# Pyke, 11 bytes

```
S.b#_P)'sl/

```

Try it online!
> 2 votes

# Answer
# dc, 129 bytes

```
?sa0sb1sd0ss0sz[[lF1+sF]sqlelG!=q]si[ls+sslz1+sz]sw[lddlb+dsdrsbdsG2se0sF[lGdle%0=ile1+dse<p]dspxlF0=wla1-dsa1<c]dscxEkls1-lz1-/p

```

A Fibonacci number generator and primality checker all in one. Nice.

Try it online!
> 2 votes

# Answer
# Japt `-x`, ~~14~~ 12 bytes

```
ò!gM fj Ë/Fl

```

Try it
> 2 votes

# Answer
# Husk, 6 bytes

```
Afṗ↑İf

```

Try it online! Outputs the mean as an exact rational number.

### Explanation

```
Afṗ↑İf  (Let X denote the argument.)
A       Take the arithmetic mean of
   ↑      the first X values of
    İf     the infinite list of Fibonacci numbers,
 fṗ      filtered for primality.

```
> 2 votes

# Answer
# perl, 91 bytes

```
$b=1;map{($a,$b)=($b,$a+$b),$p=("x"x$b)!~/^(.|(..+)\2+)$/,$s+=$b*$p,$c+=$p}2..$x;print$s/$c

```

Cuold have been 8 bytes shorter if the modulo pseudoprime test worked as well in perl as in the python answer:

```
$b=1;$s=2;map{($a,$b)=($b,$a+$b),$p=2**$b%$b==2,$s+=$b*$p,$c+=$p}2..$x;print$s/++$c

```

...but this gives wrong answer for input \> 16 in perl.
> 1 votes

# Answer
# Axiom, 104 bytes

```
g(n)==(y:=x:=r:=0;repeat(x>n=>break;j:=fibonacci(x);x:=x+1;if prime?(j)then(r:=r+j;y:=y+1));y=0=>-1;r/y)

```

ungolfed, test code and results

```
f(n)==
  y:=x:=r:=0
  repeat
     x>n=>break
     j:=fibonacci(x)
     x:=x+1
     if prime?(j) then(r:=r+j;y:=y+1)
  y=0=>-1
  r/y

(3) -> [[i,g(i)::Float] for i in [1,2,3,10,15,20,11,30,50]]
   Compiling function g with type PositiveInteger -> Fraction Integer
   (3)
   [[1.0,- 1.0], [2.0,- 1.0], [3.0,2.0], [10.0,5.75], [15.0,57.5],
    [20.0,277.4285714285 7142857], [11.0,22.4], [30.0,60536.4444444444 44444],
    [50.0,309568576.1818181818 2]]

```

i try to duplicate the matematica, octave etc languages entry, if one not count the mean() function, to implement it would be here **62 bytes** so good too

```
mean(a:List Float):Any==
    i:=1; s:=0.0
    repeat
       if~index?(i,a)then break
       s:=s+a.i
       i:=i+1
    i=1=>[]
    s/(i-1)

--62 bytes
f(x:NNI):Any==mean(select(prime?,[fibonacci(i)for i in 1..x]))

```
> 1 votes

# Answer
# JavaScript ES6, ~~137~~ ~~136~~ ~~118~~ 113 bytes

```
m=

n=>(a=[],(f=x=>a[x]=x<2?x:f(--x)+f(--x))(n),eval((a=a.filter(x=>eval("for(y=x;x%--y;);y==1"))).join`+`)/a.length)

console.log(m(10))
console.log(m(15))
console.log(m(20))
console.log(m(11))
console.log(m(30))
```

---

## History

### 118 bytes

```
n=>(a=[0,1,1],(f=x=>a[--x]=a[x]||f(x)+f(--x))(n),eval((a=a.filter(x=>eval("for(y=x;x%--y;);y==1"))).join`+`)/a.length)

```

### 136 bytes

```
n=>(a=[0,1,1],(f=x=>a[--x]=a[x]||f(x)+f(--x))(n),eval((a=a.filter(x=>x>1&&!Array(x).fill().some((i,j)=>j>1&&!(x%j)))).join`+`)/a.length)

```

### 137 bytes

```
n=>(a=[0,1,1],(f=x=>a[--x]=a[x]||f(x)+f(--x))(n),eval((a=a.filter(x=>{d=x;while(--d>1)if(!(x%d))return 0;return x>1})).join`+`)/a.length)

```
> 1 votes

# Answer
# Jelly, 7 bytes

```
ÆḞ€ẒƇÆm

```

Try it online!

The newest version of Jelly really helps with this. This is essentially identical to Dennis' answer but uses the newer features, so go upvote his answer.

## How it works

```
ÆḞ€ẒƇÆm - Main link. Takes n on the left
ÆḞ€     - i'th Fibonacci number for each i in [1, 2, .., n]
    Ƈ   - Comb; Keep those for which the following is true:
   Ẓ    -   Is prime?
     Æm - Take the arithmetic mean

```
> 0 votes

# Answer
# Whispers v3, 71 bytes

```
> Input
> fₙ
>> 2ᶠ1
>> L’
>> Select∧ 4 3
>> mean(5)
>> Output 6

```

Unfortunately, no TIO as this relies on v3 features, and v3 isn't on TIO. However, you can tell it by downloading and running the interpreter in the linked GitHub repo

## How it works

```
> Input
Here, we "define" line 1 to hold our input integer, n

> fₙ
On line 2, we store an infinite list of Fibonacci numbers

>> 2ᶠ1
We then use the ᶠ dyad to take the ᶠirst n elements from the infinite list

>> L’
This line is a "functional operator line". It is passed a value on the Left and returns the ’ (prime) operator result on that value

>> Select∧ 4 3
We now take the list of Fibonacci numbers and Select those which return true when run through line 4

>> mean(5)
>> Output 6
Finally, we take the mean of the resulting list, before outputting it

```
> 0 votes

---
Tags: code-golf, math, sequence, arithmetic, fibonacci
---


title: The Last Monday

text:
# Question
Title: The Last Monday
Monday, October 31st, is Halloween. And it got me thinking -- I wonder what other months have the last day of the month *also* be a Monday?

### Input

* A positive integer in any convenient format representing a year, `10000 > y > 0`.
* The input can be padded with zeros (e.g., `0025` for year `25`) if required.

### Output

* A list of the months of that year where the last day of the month is a Monday.
* This can be as month names (e.g., `January, March, October`), or shortnames (`Jan, Mar, Oct`), or numbers (`1, 3, 10`), as separate lines or a list or delimited, etc., just so long as it's unambiguous to the reader.
* The output format must be consistent:
    + For all years input (meaning, you can't output month names for some inputs, and month numbers for other inputs)
    + As well as consistent per output (meaning, you can't output `1` for `January` in the same output as `Jul` for `July`)
    + Basically, pick one format and stick to it.

### Rules

* Assume the Gregorian calendar for input/output, even down to `y = 1`.
* Leap years must be properly accounted for (as a reminder: every year divisible by 4, except not years divisible by 100, unless also divisible by 400 -- 1700, 1800, 1900 all weren't leap years, but 2000 was).
* You may use any built-ins or other date calculation tools you like.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

### Examples

```
   1 --> Apr, Dec
 297 --> May
1776 --> Sep
2000 --> Jan, Jul
2016 --> Feb, Oct
3385 --> Jan, Feb, Oct

```

---

### Leaderboard

```
var QUESTION_ID=97585,OVERRIDE_USER=42963;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="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});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;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>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;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
> 2 votes
# Dyalog APL with dfns's cal, Version 15.0: 22; Version 16.0: 19 bytes

The cal function comes with a default install, just enter `)copy dfns`.

### Version 15.0: `∊⎕{⍵/⍨2=≢⍎⊢⌿cal⍺⍵}¨⍳12`

enlist (flatten)

`⎕{`... numeric input as left argument to the following anonymous function, taking each of the right side values as right argument in turn

`⍵/⍨` the argument if (gives an empty list if not)

`2=` two (namely Sunday and Monday) is equal to

the tally of

the numbers in

`⊢⌿` the bottom-most row of

`cal` the calendar for

`⍺⍵` year left-argument, month right-argument, the latter being

`⍳12` 1 to 12

### Version 16.0: `⍸2=⎕{≢⍎⊢⌿cal⍺⍵}¨⍳12`

the indices where

`2=` two equals (namely Sunday and Monday)

`⎕{`... numeric input as left argument to the following anonymous function, taking each of the right side values as right argument in turn

the tally of

the numbers in

`⊢⌿` the bottom-most row of

`cal` the calendar for

`⍺⍵` year left-argument, month right-argument, the latter being

`⍳12` 1 to 12

# Answer
> 18 votes
# JavaScript (Firefox 30+), ~~112~~ ~~109~~ ~~103~~ 95 bytes

Look ma, no built-ins!

```
y=>[for(m of(i=0,y%4|y%400*!(y%100)&&6)+"63153042641")if((i++,y+(y>>2)-(y/100|0)*3/4|0)%7==m)i]

```

Here's a 107-byte ES6 version:

```
y=>[...(y%4|y%400*!(y%100)&&6)+"63153042641"].map((m,i)=>(y+(y>>2)-(y/100|0)*3/4|0)%7-m?0:i+1).filter(x=>x)

```

And here's my previous attempt, ~~123~~ 113 bytes of ES6:

```
y=>[(l=y%4|y%400*!(y%100))?[7]:[1,7],[4,12],[9],[3,6],[8,11],[5],l?[1,2,10]:[2,10]][(y+(y>>2)-(y/100|0)*3/4|0)%7]

```

## Explanation

The day of the week of a particular year is calculated like so:

```
y+(y>>2)-(y/100|0)*3/4|0)%7

```

In other words:

* Take `y`.
* Add the number of 4th years before `y` (`y>>2`).
* Subtract the number of 100th years before `y` (`y/100|0`).
* Add back in the number of 400th years before `y`; this is 1/4 of `y/100|0`, so we use `*3/4|0`.

Then we modulo the result by 7. If we let `0` mean Sunday, `1` mean Monday, etc., the result corresponds to the day of the week of December 31st of that year. Therefore, for December, we want to check if the result is `1`. This gives us the last char in the string.

The last day of November is 31 days before the last day of December. This means that for the last day of November to be a Monday, Dec 31 needs to be a `(1 + 31) % 7 = 4` = Thursday.

This procedure is repeated until we get back to March (a `3`). Whether or not there is a leap day, the last day of February is 31 days before the last day of March, so we can calculate that too (it's `(3 + 31) % 7 = 6`). The tricky part is finding the correct value for January:

* If it is a leap year, the last day of January is 29 days before the last day of Feb, resulting in `(6 + 29) % 7 = 0`.
* Otherwise, it is 28 days before the last day of Feb, resulting in `(6 + 28) % 7 = 6`.

We can calculate whether or not it is a leap year with the following snippet:

```
!(y%400)|y%100*!(y%4)

```

This gives `0` if `y` is not a leap year, and a positive integer otherwise. This leads us to

```
!(y%400)|y%100*!(y%4)?0:6

```

for calculating the day for January. However, we can do better by reversing the conditions:

```
y%4|y%400*!(y%100)?6:0

```

Since the falsy result is always 0 anyway, we can reduce it to

```
y%4|y%400*!(y%100)&&6

```

saving one more precious byte.

Putting it all together, we loop through each char in the string, checking if each is equal to the day of the week of Dec 31st. We keep the indexes of the ones that match, returning this array in the end. And that is how you do leap year calculations without built-ins.

# Answer
> 11 votes
## JavaScript (Firefox 30-57), ~~67~~ ~~65~~ ~~64~~ ~~63~~ 61 bytes

```
y=>[for(_ of(m='')+1e11)if(new Date(y+400,++m).getDay()==2)m]

```

Saved ~~2~~ ~~4~~ 6 bytes thanks to @ETHproductions. ~~Saved another byte by outputting the months in reverse order.~~

# Answer
> 9 votes
# MySQL, ~~183~~ ~~134~~ ~~129~~ 106 bytes

```
SET @y=2016;SELECT help_topic_id AS m FROM mysql.help_topic HAVING m BETWEEN 1 AND 12 AND 2=DAYOFWEEK(LAST_DAY(CONCAT(@y,-m,-1)))

```

Replace `2016` with the desired year. Run.

Rev. 2: Used the `help_topics` table in the default installation instead of creating a temporary table.

Rev.3: Adopted aross´s `-` trick and noticed I can also omit the quotes for `"-1"`.
However, `-1` is required in MySQL: I need a full date.

Rev.4: Restriction `m BETWEEN 1 AND 12` could be done as `m>0 AND m<13` (-6), but is not needed at all - invalid values will be ignored; warnings will be counted but not listed.

# Answer
> 5 votes
## Batch, ~~160~~ 152 bytes

```
@set/ay=%1,m=0,j=6*!(!(y%%4)*(y%%100)+(y%%400)),y=(y*5/4-y/100*3/4)%%7
@for %%d in (%j% 6 3 1 5 3 0 4 2 6 4 1)do @set/am+=1&if %%d==%y% call echo %%m%%

```

Port of @ETHproduction's answer. With month abbreviations for ~~197~~ 189 bytes:

```
@set/ay=%1,j=6*!(!(y%%4)*(y%%100)+(y%%400)),y=(y*5/4-y/100*3/4)%%7
@for %%m in (Jan.%j% Feb.6 Mar.3 Apr.1 May.5 Jun.3 Jul.0 Aug.4 Sep.2 Oct.6 Nov.4 Dec.1)do @if %%~xm==.%y% call echo %%~nm

```

# Answer
> 5 votes
# Perl+cal, 46 bytes

```
say`cal $_ $ARGV[0]`=~/\n.{5}\n/&&$_ for 1..12

```

Example:

```
$ perl -E 'say`cal $_ $ARGV[0]`=~/\n.{5}\n/&&$_ for 1..12' 2016

2

10

$

```

# Answer
> 5 votes
# Perl, 64 bytes

Includes +1 for `-n`

Give input on STDIN:

```
perl -M5.010 mon.pl <<< 2016

```

`mon.pl`:

```
#!/usr/bin/perl -n
map$b.=$/.gmtime$_.e4,-7e6..3e7;say$b=~/on (\S+ )\S.* $_.* 1 /g

```

# Answer
> 5 votes
# Mathematica, ~~62~~ 57 bytes

```
DayName@DayRange[{#},{#+1},"EndOfMonth"]~Position~Monday&

```

Anonymous function. Takes a number as input and returns a list of single-element lists of numbers as output. I'm honestly not sure myself how it works anymore.

# Answer
> 4 votes
# J, ~~48~~ ~~34~~ 33 bytes

```
[:I.(2=7|_2#@".@,@{.])&>@calendar

```

Saved 15 bytes with help from @Adám.

Uses the calendar builtin to generate an array of strings representing the months, then parses each string to determine the whether the last Monday is the last day of the month. It outputs each month as the month number of each. That is, `Jan = 0`, `Feb = 1`, ..., `Dec = 11`.

The output of `calendar` is

```
   _3 ]\ calendar 2016
┌─────────────────────┬─────────────────────┬─────────────────────┐
│         Jan         │         Feb         │         Mar         │
│ Su Mo Tu We Th Fr Sa│ Su Mo Tu We Th Fr Sa│ Su Mo Tu We Th Fr Sa│
│                 1  2│     1  2  3  4  5  6│        1  2  3  4  5│
│  3  4  5  6  7  8  9│  7  8  9 10 11 12 13│  6  7  8  9 10 11 12│
│ 10 11 12 13 14 15 16│ 14 15 16 17 18 19 20│ 13 14 15 16 17 18 19│
│ 17 18 19 20 21 22 23│ 21 22 23 24 25 26 27│ 20 21 22 23 24 25 26│
│ 24 25 26 27 28 29 30│ 28 29               │ 27 28 29 30 31      │
│ 31                  │                     │                     │
├─────────────────────┼─────────────────────┼─────────────────────┤
│         Apr         │         May         │         Jun         │
│ Su Mo Tu We Th Fr Sa│ Su Mo Tu We Th Fr Sa│ Su Mo Tu We Th Fr Sa│
│                 1  2│  1  2  3  4  5  6  7│           1  2  3  4│
│  3  4  5  6  7  8  9│  8  9 10 11 12 13 14│  5  6  7  8  9 10 11│
│ 10 11 12 13 14 15 16│ 15 16 17 18 19 20 21│ 12 13 14 15 16 17 18│
│ 17 18 19 20 21 22 23│ 22 23 24 25 26 27 28│ 19 20 21 22 23 24 25│
│ 24 25 26 27 28 29 30│ 29 30 31            │ 26 27 28 29 30      │
│                     │                     │                     │
├─────────────────────┼─────────────────────┼─────────────────────┤
│         Jul         │         Aug         │         Sep         │
│ Su Mo Tu We Th Fr Sa│ Su Mo Tu We Th Fr Sa│ Su Mo Tu We Th Fr Sa│
│                 1  2│     1  2  3  4  5  6│              1  2  3│
│  3  4  5  6  7  8  9│  7  8  9 10 11 12 13│  4  5  6  7  8  9 10│
│ 10 11 12 13 14 15 16│ 14 15 16 17 18 19 20│ 11 12 13 14 15 16 17│
│ 17 18 19 20 21 22 23│ 21 22 23 24 25 26 27│ 18 19 20 21 22 23 24│
│ 24 25 26 27 28 29 30│ 28 29 30 31         │ 25 26 27 28 29 30   │
│ 31                  │                     │                     │
├─────────────────────┼─────────────────────┼─────────────────────┤
│         Oct         │         Nov         │         Dec         │
│ Su Mo Tu We Th Fr Sa│ Su Mo Tu We Th Fr Sa│ Su Mo Tu We Th Fr Sa│
│                    1│        1  2  3  4  5│              1  2  3│
│  2  3  4  5  6  7  8│  6  7  8  9 10 11 12│  4  5  6  7  8  9 10│
│  9 10 11 12 13 14 15│ 13 14 15 16 17 18 19│ 11 12 13 14 15 16 17│
│ 16 17 18 19 20 21 22│ 20 21 22 23 24 25 26│ 18 19 20 21 22 23 24│
│ 23 24 25 26 27 28 29│ 27 28 29 30         │ 25 26 27 28 29 30 31│
│ 30 31               │                     │                     │
└─────────────────────┴─────────────────────┴─────────────────────┘

```

## Usage

```
   f =: [:I.(2=7|_2#@".@,@{.])&>@calendar
   f 1
3 11
   f 297
4
   f 1776
8
   f 2000
0 6
   f 2016
1 9
   f 3385
0 1 9

```

## Explanation

```
[:I.(2=7|_2#@".@,@{.])&>@calendar  Input: year Y
                         calendar  Get 12 boxes each containing a month
    (                )&>@          Operate on each box
                    ]                Identity, get the box
         _2       {.                 Take the last two strings
                ,@                   Flatten it
             ".@                     Parse it into an array of integers
           #@                        Get the length
       7|                            Take it modulo 7
     2=                              Test if it equals 2 - it will either
                                     have two days or 9 days in the last
                                     two lines if the end is on a Monday
[:I.                               Return the indices containing a true value

```

# Answer
> 4 votes
# Java 7 ,~~186 182~~ 172 bytes

*Thanks to kevin for saving 4 bytes*
*Thanks to @cliffroot for saving 10 bytes*

```
int[]f(int n){int c=n-1,x=c*365+c/4+c/400-c/100,k=0,b[]={3,(n%4<1&n%100>0)|n%400<1?1:0,3,2,3,2,3,3,2,3,2,3},a[]=new int[12];for(int i:b)a[k++]=(x+=i+28)%7==1?1:0;return a;}

```

# ungolfed

```
int[] f(int n) {
 int c=n-1,x=c*365+(c/4)+(c/400)-(c/100),k=0,
   b[] = {3,(n % 4 < 1 & n % 100 > 0) | n % 400 < 1 ? 1 : 0
                                     ,3,2,3,2,3,3,2,3,2,3},a = new int[ 12 ];

 if ( (n % 4 < 1 & n % 100 > 1) | n % 400 < 1 )
     b[ 1 ] = -1;
 for (int i : b)
    a[ k++ ] = (x += i + 28) % 7 == 1 ? 1 : 0;

return a;
     }

```

This version is provide by @cliffroot(**168 bytes**)

```
 static int[] f(int n) {
 int b = 13561787 | ( (n%4 < 1 & n%100 > 0) | n%400 < 1 ? 1 << 20 : 0 ),
           x = --n*365 + n/4 + n/400 - n/100,a[]=new int[12],k=0;
    while (k < 12)
    a[k++] = (x += (b >> 24 - k*2&3 ) + 28) % 7 == 1 ? 1 : 0;
  return a;   }
    }

```

# output sample

```
1 1 0 0 0 0 0 0 0 1 0 0(for input 3385)

```

# Answer
> 4 votes
# C, 119 bytes

```
t=1248700335,m;main(y){for(scanf("%d",&y),t+=y&3||y%25<1&&y&15;m++,(6+y+y/4-y/100+y/400+t)%7||printf("%d,",m),t;t/=7);}

```

This uses a table that contains the offset of the weekdays of the last day of every month for a leap year, encoded in a signed 32-bit word using base 7. If it is not a leap year we add 1 to the offset of January (as you can see `y&3||y%25<1&&y&15` is used to check for years without leap days). Then we simply loop through every month and check if its last day is a Monday. Quite simple actually, no ugly hacks or tricks. Here it is slightly ungolfed:

```
t=1248700335,m;
main(y){
  for(
    scanf("%d",&y),t+=y&3||y%25<1&&y&15;
    m++,(6+y+y/4-y/100+y/400+t)%7||printf("%d,",m),t;
    t/=7
  );
}

```

I might revisit this to rewrite it as a function to save a few characters. The `printf` also takes up a little too much space...

# Answer
> 3 votes
# Python 2, 122 bytes

Ugh. Math with dates isn't as simple as I'd like.

```
from datetime import*
lambda y:[m+1for m in range(12)if(date(y,12,31)if m>10else(date(y,m+2,1)-timedelta(1))).weekday()<1]

```

**Try it online**

**Same length:**

```
from datetime import*
lambda y:[m-1for m in range(2,14)if(date(y,12,31)if m>12else(date(y,m,1)-timedelta(1))).weekday()<1]

```

# Answer
> 3 votes
## PHP, 109 180 159 bytes

```
for($z=$argv[1];$m++<12;)if(date(N,strtotime(sprintf("%04d-$m-",$z).cal_days_in_month(0,$m,$z)))<2)echo"$m,";

```
* Outputs the provided year, not all of them (... always read the question)
* Ignored notices (thanks Titus)
* Change `while` to `for` as it's now a single year (again, thanks Titus)

### Old 2

```
$z=0;while($z++<9999){$o=[];$m=0;while($m++<12)if(date("N",strtotime(sprintf("%04d-$m-","$z").cal_days_in_month(0,$m,$z)))<2)$o[]=$m;echo count($o)>0?"$z:".implode(",",$o)."
":"";}

```

Supports all years from dot to 10000, also got rid of an undefined var warning I wasn't aware of on one PC. Yes it's longer than the old version, but it's more robust.

### Old 1

```
while($z++<9999){$o=[];$m=0;while($m++<12)if(date("N",strtotime("$z-$m-".cal_days_in_month(0,$m,$z)))<2)$o[]=$m;echo count($o)>0?"$z:".implode(",",$o)."
":"";}

```

If running on Windows or a 32bit system there will be the dreaded 2038 bug, but on a 64bit linux system it's fine.

I did attempt to use `date("t"...` which is meant to represent the last date of the given month, but the results didn't match those previously mentioned in this thread.

# Answer
> 3 votes
# MATL, 21 bytes

```
12:"G@QhO6(YO9XO77=?@

```

Months are displayed as numbers.

Try it online! Or verify all test cases.

### Explanation

This uses date conversion builtin functions. For the given year it tests which months' last day is Monday.

Instead of explicitly specifying the last day of month `k` (which may be 28, 29, 30 or 31), we specify the `0`-th day of month `k+1`, which is equivalent and does not depend on month or year.

```
12:      % Push [1 2 ... 12] (months)
"        % For each month k
  G      %   Push input
  @Q     %   Push k+1
  h      %   Concatenate
  O6(    %   Postpend four zeros. For example, for input 2016 and month k=1
         %   (first iteration) this gives [2016 2 0 0 0 0] (year, month, day,
         %   hour, min, sec). The 0-th day of month k+1 is the same as the
         %   last day of month k.
  YO     %   Convert the above 6-element date vector to date number
  9XO    %   Convert date number to date string with output format 9, which
         %   is weekday as a capital letter
  77=    %   Is it an 'M'?
  ?      %   If so
    @    %     Push current month (will be implicitly displayed)

```

# Answer
> 3 votes
# Bash + GNU utilities, 56 bytes

```
seq -f1month-1day$1-%g-1 12|date -f- +%B%u|sed -n s/1//p

```

Appears to require `date` version 8.25. The 8.23 version in Ideone doesn't cut it.

# Answer
> 3 votes
# Excel, 537 bytes

Because – you know – Excel!

Takes input year in A1. Returns hexadecimal list of months; 1=January, C= December. Since each month is a single digit, no separator is needed.

```
=IF(2=WEEKDAY(EOMONTH(DATE(A1,1,1),0)),1,"")&IF(2=WEEKDAY(EOMONTH(DATE(A1,2,1),0)),2,"")&IF(2=WEEKDAY(EOMONTH(DATE(A1,3,1),0)),3,"")&IF(2=WEEKDAY(EOMONTH(DATE(A1,4,1),0)),4,"")&IF(2=WEEKDAY(EOMONTH(DATE(A1,5,1),0)),5,"")&IF(2=WEEKDAY(EOMONTH(DATE(A1,6,1),0)),6,"")&IF(2=WEEKDAY(EOMONTH(DATE(A1,7,1),0)),7,"")&IF(2=WEEKDAY(EOMONTH(DATE(A1,8,1),0)),8,"")&IF(2=WEEKDAY(EOMONTH(DATE(A1,9,1),0)),9,"")&IF(2=WEEKDAY(EOMONTH(DATE(A1,10,1),0)),"A","")&IF(2=WEEKDAY(EOMONTH(DATE(A1,11,1),0)),"B","")&IF(2=WEEKDAY(EOMONTH(DATE(A1,12,1),0)),"C","")

```

Example: A1 contains 2016. B1 contains the above formula, and displays as `2A`, meaning February and October.

# Answer
> 3 votes
# Excel, ~~428~~ ~~97~~ 96 bytes

Input in A1. Output un-separated Hexadecimal values (January = 0, December = B)

```
=IF(2=WEEKDAY(DATE(A1+2000,1,31)),0,"")&CHOOSE(WEEKDAY(DATE(A1+2000,3,0)),4,19,6,"3B",8,25,"7A")

```

Added 10 bytes ("+2000") to allow handling of pre-1990 dates.

Saved 11 bytes thanks to @Engineer Toast.

---

First attempt (428 bytes), borrowing heavily from @Adám's solution.

```
=IF(2=WEEKDAY(DATE(A1,1,31)),1,"")&IF(2=WEEKDAY(EOMONTH(DATE(A1,2,1),0)),2,"")&IF(2=WEEKDAY(DATE(A1,3,31)),3,"")&IF(2=WEEKDAY(DATE(A1,4,30)),4,"")&IF(2=WEEKDAY(DATE(A1,5,31)),5,"")&IF(2=WEEKDAY(DATE(A1,6,30)),6,"")&IF(2=WEEKDAY(DATE(A1,7,31)),7,"")&IF(2=WEEKDAY(DATE(A1,8,31)),8,"")&IF(2=WEEKDAY(DATE(A1,9,30)),9,"")&IF(2=WEEKDAY(DATE(A1,10,31)),"A","")&IF(2=WEEKDAY(DATE(A1,11,30)),"B","")&IF(2=WEEKDAY(DATE(A1,12,31)),"C","")

```

# Answer
> 3 votes
# PHP, ~~96~~ ~~95~~ ~~76~~ ~~71~~ ~~69~~ ~~64~~ 61 bytes

Note: year numbers must be padded to 4 chars, like `0070`.

```
for(;13+$i-=1;)date(N,mktime(0,0,0,1-$i,0,$argn))-1||print$i;

```

Run like this:

```
echo 3385 | php -nR 'for(;13+$i-=1;)date(N,mktime(0,0,0,1-$i,0,$argn))-1||print$i;';echo
> -1-2-10

```

# Explanation

Iterates from -1 to -12. Create date using mktime, day `0` (the last day of the previous month) and month `2..13`. Format the date as **day number**, and if the result is 1, print the current number. The negative sign `-` is used as the delimiter.

# The Millenium Bug Strikes Again!

Note that with this version, the range `0..100` is interpreted as `1970..2069`. This is no problem for the range `0..69`, as weeks have a pattern that repeats every 400 years (146097 days, exactly 20871 weeks), but for the range `70..99`, 1900 is added to the year number, which is not a multiple of 400. To fix that problem JUST for 30 year numbers in a range of 10k, the simplest way is to add 400 to the year number to prevent the 2-digit interpretation (**+4 bytes**):

```
for(;13+$i-=1;)date(N,mktime(0,0,0,1-$i,0,$argn+400))-1||print$i;

```

# Tweaks

* Saved a byte by using `!~-$i` to compare `$i` with `1` (`-1` binary negated is `0`, logically negated is `true`; every other number is `false`), so parentheses aren't needed
* Saved 19 bytes by using `last day ofYYYY-m` notation to create the date
* Saved 5 bytes by using `date` and `strtotime` instead of `date_create`
* Saved 2 bytes by counting from negative numbers, using the negative sign as output delimiter (negative month numbers don't exist) and also as delim in the `YYYY-m` part of the date
* Saved 5 bytes by using `mktime` instead of `strtotime`. Reverted to using day `0` (`mktime` also supports month 13, so `0-13`==`31-12`)
* Saved 3 bytes by using `-R` to make `$argn` available

# Answer
> 3 votes
# C, 214 bytes

```
main(int a,char *b[]){for(int x,y,d,m=12;m;m--){y=atoi(b[1]);x=m-1;d=x==1?(y%4==0?(y%100==0?(y%400==0?29:28):29):28):(x==3||x==5||x==10?30:31);if((d+=m<3?y--:y-2,23*m/9+d+4+y/4-y/100+y/400)%7==1)printf("%d\n",m);}}

```

# Compile

```
gcc -std=c99 -o foo foo.c

```

# Ungolfed

With credits to the relevant gurus.

*Michael Keith* and *Tom Craver* for C Program to find day of week given date.

*Collin Biedenkapp* for Q&A: How do I figure out what the last day of the month is?

```
/* credit to Collin Biedenkapp */
short _get_max_day(short x, int z) {
    if(x == 0 || x == 2 || x == 4 || x == 6 || x == 7 || x == 9 || x == 11)
        return 31;
    else if(x == 3 || x == 5 || x == 8 || x == 10)
        return 30;
    else {
        if(z % 4 == 0) {
            if(z % 100 == 0) {
                if(z % 400 == 0)
                    return 29;
                return 28;
            }
            return 29;
        }
        return 28;
    }
}

main(int argc,char *argv[]) {
 for(int y,d,m=12;m;m--) {
  y=atoi(argv[1]);
  d=_get_max_day(m-1,y);
  /* credit to Michael Keith and Tom Craver */
  if ((d+=m<3?y--:y-2,23*m/9+d+4+y/4-y/100+y/400)%7 == 1)
    printf("%d\n",m);
 }
}

```

# Answer
> 3 votes
# PHP, 92 Bytes

```
for($d=new DateTime("$argv[1]-1-1");$i++<12;)$d->modify("1month")->format(w)!=2?:print"$i,";

```

check 12 times 1 month after first day of a year is a tuesday. If it is then is the day before the last day in the month is a monday.

# Answer
> 2 votes
# Bash+cal, 58 bytes

```
$ cat t.sh
for A in {1..12};do cal $A $1|grep -qx .....&&echo $A;done
$ bash t.sh 2016
2
10
$

```

# Answer
> 2 votes
## Ruby, 54 + 6 = 60 bytes

```
λ cat monday.rb
p (1..12).select{|m|Date.new($*[0].to_i,m,-1).monday?}
λ ruby -rdate monday.rb 2016
[2, 10]

```

6 bytes for `-rdate` on the command line to get the Date class from the standard library.

Explanation: pretty straightforward thanks to the Ruby stdlib's great `Date` class. Not only does it have methods like `monday?`, `tuesday?`, etc, the constructor will take negative numbers for any field past year to mean 'count this field backwards from the end of the period represented by the previous field'. `$*` is shorthand for `ARGV`, so `$*[0]` is a quick way to get the first command line argument.

# Answer
> 2 votes
# Python 2, 94 bytes

```
from datetime import*
lambda y:[m for m in range(1,13)if date(y+(m>11),m%12+1,1).weekday()==1]

```

**repl.it**

An unnamed function, takes an integer year, outputs a list of the month numbers `[1-12]`.

I also tried to beat the byte count with arithmetic without success (110 bytes). :

```
lambda y:map(lambda x,v:(23*((x+2)%13or 1)/9+y-2*(0<x<11)+(x>10)+v/4-v/100+v/400)%7==4,range(12),[y-1]+[y]*11)

```

An unnamed function which returns a list of boolean values representing if the months \[Jan-Dec\] end in a Monday

# Answer
> 2 votes
# Java 7, ~~200~~ 249 bytes

```
import java.util.*;String c(int y){String r="";GregorianCalendar c=new GregorianCalendar();c.setGregorianChange(new Date(1L<<63));c.set(1,y);c.set(2,0);for(int i=0;i++<12;c.add(2,1)){c.set(5,c.getActualMaximum(5));if(c.get(7)==2)r+=i+" ";}return r;}

```

In Java, `GregorianCalendar` is a mix between a Gregorian and Julian calendar. Because of this, year `1` gave incorrect results. Changing `Calendar c=Calendar.getInstance();` to `GregorianCalendar c=new GregorianCalendar();c.setGregorianChange(new Date(1L<<63));` fixes this by forcing a use of the Gregorian calendar only. Thanks to *@JonSkeet* on stackoverflow.com for explaining this to me.

**Ungolfed & test code:**

Try it here.

```
import java.util.*;
class M{
  static String c(int year){
    String r = "";
    GregorianCalendar calendar = new GregorianCalendar();
    calendar.setGregorianChange(new Date(Long.MIN_VALUE));
    calendar.set(Calendar.YEAR, year);
    calendar.set(Calendar.MONTH, 0);
    for(int i = 0; i++ < 12; calendar.add(Calendar.MONTH, 1)){
      calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
      if(calendar.get(Calendar.DAY_OF_WEEK) == 2){
        r += i+" ";
      }
    }
    return r;
  }

  public static void main(String[] a){
    System.out.println(c(1));
    System.out.println(c(297));
    System.out.println(c(1776));
    System.out.println(c(2000));
    System.out.println(c(2016));
    System.out.println(c(3385));
  }
}

```

**Output:**

```
4 12
5
9
1 7
2 10
1 2 10

```

# Answer
> 2 votes
# R, ~~106~~ ~~99~~ ~~95~~ ~~83~~ ~~78~~ ~~77~~ 74 bytes

```
g=function(x)which(format(seq(as.Date(paste0(x,-2,-1)),,'m',12)-1,"%u")<2)

```

The sequence of last days of each month is given by `seq(as.Date(paste0(x,-2,-1)),,'m',12)-1`:

* `paste0` coerces -2 and -1 to characters. If the `x` was 2016 for instance, `paste0(x,-2,-1)` gives `"2016-2-1"` which is then converted to the 1st of February 2016 by `as.Date`.
* `seq` applied to a POSIXct or a Date object is `seq(from, to , by, length.out)`: here `to` is not given, `by` is given as `'m'` which is matched to `'month'` thanks to partial matching, and `length.out` is of course 12.
* The resulting sequence is the first day of the 12 months starting with February of the year in question. `-1` gives us then the last day of the 12 months starting with January of the year in question.

Test cases:

```
> g(1)
[1]  4 12
> g(25)
[1] 3 6
> g(297)
[1] 5
> g(2000)
[1] 1 7
> g(2016)
[1]  2 10
> g(3385)
[1]  1  2 10
> g(9999)
[1] 5

```

**Old version at 95 bytes, outputting the month names instead of just their numbers:**

```
g=function(x)format(S<-seq(as.Date(sprintf("%04i-02-01",x)),,'m',12)-1,"%B")[format(S,"%u")==1]

```

# Answer
> 2 votes
# ~~C#6~~ C#, ~~171~~ ~~167~~ 135 bytes

```
using System;
void d(int n){for(int i=0;++i<13;)if((int)new DateTime(n,i,DateTime.DaysInMonth(n,i)).DayOfWeek==1)Console.Write(i+" ");}

```

*-32 bytes thanks to Shebang*

Print months as numbers; with space delimited; with trailing space. Now this answer also works for earlier versions of C#.

---

Old, 167 bytes

```
using System;using System.Linq;
c(int n)=>string.Join(",",Enumerable.Range(1,12).Where(i=>new DateTime(n,i,DateTime.DaysInMonth(n,i)).DayOfWeek==(DayOfWeek)1));

```

*-4 bytes thanks to TimmyD*

Output months are numbers in return string, comma delimited

Ungolfed

```
string c(int n)=>
    string.Join(",",                                        // Join them with commas
        Enumerable.Range(1,12)                              // For 1-12 inclusive
        .Where(                                             // Select only
            i=>new DateTime(n,i,DateTime.DaysInMonth(n,i)   // Get last day of that year-month
            ).DayOfWeek                                     // Get its day of week
            ==(DayOfWeek)1                              // Is Monday
        )
    )
;

```

# Answer
> 2 votes
# Japt, 24 bytes

```
Do1 £Ov"Ð400+U"+X e ¥2©X

```

**Test it online!** Outputs an array of numbers, with `false` in place of months that don't end in a Monday.

There was a bug in the interpreter that didn't allow me to use `Ð` in the function body `£`. After the bug fix and another feature addition, this is 18 bytes in the current commit:

```
Do1@Ð400+UX e ¥2©X

```

# Answer
> 1 votes
# Java, ~~143~~ 129 bytes

This uses the new time API of Java 8.

```
y->{String s="";for(int m=0;++m<13;)if(java.time.YearMonth.of(y,m).atEndOfMonth().getDayOfWeek().ordinal()==0)s+=m+" ";return s;}

```

## Output

Note that each line has an extra space at the end.

```
4 12
5
9
1 7
2 10
1 2 10

```

## Ungolfed and testing

```
import java.time.*;
import java.util.function.*;

public class Main {
    public static void main (String[] args) {
        IntFunction<String> func = year -> {
          String result = "";
          for (int month=1; month <= 12; month++) {
            if (YearMonth.of(year, month).atEndOfMonth().getDayOfWeek().ordinal() == 0) {
              result += month + " ";
            }
          }
          return result;
        };
        System.out.println(func.apply(1));
        System.out.println(func.apply(297));
        System.out.println(func.apply(1776));
        System.out.println(func.apply(2000));
        System.out.println(func.apply(2016));
        System.out.println(func.apply(3385));
    }
}

```

## Shaves

1. 143 to 129 bytes: use `DayOfWeek::ordinal` to compare with a numerical constant instead of the enum constant.
Thanks @TimmyD for the general idea if not the exact solution! ;-)

# Answer
> 1 votes
# GNU awk, 80 bytes

```
{for(;m<13;a=mktime($0" "++m" 1 9 0 0")){if(strftime("%w",a-8e4)~1){print m-1}}}

```

Example

```
$ gawk '{for(;m<13;a=mktime($0" "++m" 1 9 0 0")){if(strftime("%w",a-8e4)~1){print m-1}}}' <<<2016
2
10
$

```

# Answer
> 1 votes
# PHP, 109 bytes

```
$y=$argv[1];for($i;++$i<13;)echo(date('N',strtotime($y."-$i-".date('t',strtotime("$y-$i-1"))))==1?"$i ":'');

```

The code produces a notice due to `for($i;` but the question mentions nothing about avoiding errors.

---

Outputs months numbers separated by a space.

```
   1 --> 1 12
 297 --> 5
1776 --> 9
2000 --> 1 7
2016 --> 2 10
3385 --> 1 2 10

```

---

Works in PHP 5.2.16 and onward at http://sandbox.onlinephpfunctions.com/

# Answer
> 1 votes
# JavaScript, 65 bytes

```
v=>[...""+1e11].map((x,i)=>new Date(v+400,++i).getDay()==2?i:"")

```

Stealing the `""+1e11` trick from the other JavaScript answer.

Returns \["", 2, "", "", "", "", "", "", "", 10, "", ""\] for 2016, indicating that Feb and Oct end on a Monday.

Edited: Years 0-99 are parsed as 1900-1999 in JS. Adding 400 causes them to be parsed as 400-499, which are equivalent calendar years.

# Answer
> 1 votes
**C, ~~175~~ 217 bytes**

```
#define R return
#define L(i) for(;i-->0;)
u(y,m){R m-1?30+((2773>>m)&1):28+(y%4==0&&y%100||y%400==0);}s(y,m,g){g+=4;L(m)g+=u(y,m),g%=7;L(y)g+=1+u(y,1),g%=7;R g;}w(y,m,r){m=12;L(m)s(y,m,u(y,m))||(r|=1<<(m+1));R r;}

```

Code for to find the last day for febrary taken from K&R2; try http://ideone.com/XtuhGj the function for debug is w

```
z(y,m,r){m=12;L(m)s(y,m,13)-4||(r|=1<<(m+1));R r;}

/*
// ritorna il numero dei giorni di anno=y mese=m con mese in 0..11
// m==1 significa febbraio   y%4?0:y%100?1:!(y%400) non funziona
u(y,m){R m-1?30+((2773>>m)&1):28+(y%4==0&&y%100||y%400==0);}

// argomenti anno:y[0..0xFFFFFFF]  mese:m[0..11]  giorno:g[1..u(y,m)]
// ritorna il numero del giorno[0..6]
s(y,m,g)
{g+=4; // correzione per il giorno di partenza anno mese giorno = 0,1,1
 L(m)g+=  u(y,m),g%=7; // m:0..m-1  somma mod 7 i giorni del mese dell'anno y
 L(y)g+=1+u(y,1),g%=7; // y:0..y-1  somma mod 7 gli anni da 0..y-1
                       // g+=1+u(y,1) poiche' (365-28)%7=1 e 1 e' febbraio
 R g;
}

// argomenti anno:y[0..0xFFFFFFF], m=0 r=0
// calcola tutti gli ultimi giorni del mese dell'anno y che cadono di lunedi'
// e mette tali mesi come bit, dal bit 1 al bit 12 [il bit 0 sempre 0] in r
w(y,m,r){m=12;L(m)s(y,m,u(y,m))||(r|=1<<(m+1));R r;}

// argomenti anno:y[0..0xFFFFFFF], m=0 r=0
//ritorna in r il numero dei mesi che ha giorno 13 di venerdi[==4]
// e mette tali mesi come bit, dal bit 1 al bit 12 [il bit 0 sempre 0] in r
z(y,m,r){m=12;L(m)s(y,m,13)-4||(r|=1<<(m+1));R r;}
*/

#define P printf
#define W while
#define M main
#define F for
#define U unsigned
#define N int
#define B break
#define I if
#define J(a,b)  if(a)goto b
#define G goto
#define P printf
#define D double
#define C unsigned char
#define A getchar()
#define O putchar
#define Y malloc
#define Z free
#define S sizeof
#define T struct
#define E else
#define Q static
#define X continue
M()
{N y,m,g,r,arr[]={1,297,1776,2000,2016,3385}, arr1[]={2016,1,1997,1337,123456789};
 C*mese[]={"gen","feb","mar","apr","mag","giu","lug","ago","set","ott","nov","dic"};
 C*giorno[]={"Lun","Mar","Mer","Gio","Ven","Sab","Dom"};
 P("Inserisci Anno mese giorno>");r=scanf("%d %d %d", &y, &m, &g);
 P("Inseriti> %d %d %d r=%d\n", y, m, g, r);
 I(r!=3||m>12||m<=0||g>u(y,m-1))R 0;
 r=s(y,m-1,g);// 12-> 11 -> 0..10
 P("Risultato=%d giorno=%s\n", r, giorno[r]);
 r=w(y,0,0);P(" r=%d ", r);P("\n");
 F(m=0;m<6;++m)
        {P("N anno=%d -->",arr[m]);
         r=w(arr[m],0,0); // ritorna in r i mesi tramite i suoi bit...
         F(y=1;y<13;++y) I(r&(1<<y))P("%s ",mese[y-1]);
         P("\n");
        }
 F(m=0;m<4;++m)
        {P("N anno=%d -->",arr1[m]);
         r=z(arr1[m],0,0); // ritorna in r i mesi tramite i suoi bit...
         F(y=1;y<13;++y) I(r&(1<<y))P("%s ",mese[y-1]);
         P("\n");
        }

}

```

# Answer
> 1 votes
# PowerShell Core, ~~73~~ 65 bytes

```
param($a)1..12|?{"$_/1/$a"|get-date|% *hs 1|% *ys -1|? d*k -eq 1}

```

This requires the regional settings to use the `en-US` date format.

## Explanations

Assumes the year is a `string` with padded zeros:

```
param($a)                     # Declares an input variable
1..12                         # Creates a range for each month
 |?                           # Filters each month
  {"$_/1/$a"                  # Creates a date for the first of the month Month/Day/Year
   |get-date
   |% *hs 1                   # *hs calls AddMonths
   |% *ys -1                  # *hs calls AddDays, -1 goes to the last day of the previous month
   |? d*k -eq 1}              # d*k calls DayOfWeek, 1 is the int value for the DayOfWeek.Monday

```

Thanks to *mazzy* for the idea of piping parameters into `get-date`!

Try it online!

# Answer
> 0 votes
# Japt, 13 bytes

Outputs an array of all months, where `0`s are months that don't end in Mondays and all other integers are the 1-based indices of the months.

```
CõÈ*=1¶ÐUXJ e

```

Try it

If run in a locale where Monday is the first day of the week, with 0-based indexing, we could save 2 bytes with:

```
CõÈ*!ÐUXJ e

```

Or push the loose output format a little further by returning an array of Booleans with:

```
Cõ@!ÐUXJ e

```

## Explanation

```
CõÈ*=1¶ÐUXJ e      :Implicit input of integer U
C                  :12
 õ                 :Range [1,C]
  È                :Map each X
   *=              :  Multiply by and reassign
     1¶            :  Test 1 for equality with
       Ð           :  Create date object using
        U          :    U for the year
         X         :    X for the 0-based month ([0,11]=[Jan,Dec] but [1,12]=[Feb,Jan])
          J        :    -1 for the date, wrapping us back to the last day of the previous month
            e      :  0-based index of the day of the week (0=Sunday)

```

# Answer
> 0 votes
# CJam, 62 bytes

```
E,(;qiaf+{[~_2$3<_!-2*@@- 4/_25/_4/\W*](23*9/+:+7%4=}%ee::*0-`

```

Try it online!

Uses an algorithm adapted from Mike Keith. The program calculates the weekday of the first day of the next month, then checks if that day is a Tuesday. Output is a string representation of an array of month indices, e.g. `[2 10]`.

If output can be in the form of a binary array with 0 meaning false and 1 meaning true for each of the 12 months, you can get away with 55 bytes.

# Answer
> 0 votes
# T-SQL, 92 bytes

Input parameter needs to be padded with zeros if the year is before 1000

```
SELECT number+1FROM spt_values
WHERE number<12and
datepart(w,eomonth(@,number))=2and'P'=type

```

**Try it online**

# Answer
> 0 votes
# Java (JDK), ~~141~~ 136 bytes

```
y->{for(int i=0;++i<13)if(java.time.LocalDate.of(y,i,1).plusMonths(1).minusDays(1).getDayOfWeek().getValue()<2)System.out.println(i);};

```

Try it online!

To get the last day of each month I get the first day of the next month and substract 1 day. Java date function `getDayOfWeek()` returns the day of the week (Monday=1)

141 -\> 136 : small improvements (thanks to @ceilingcat)

# Answer
> 0 votes
# Groovy, 83 bytes

```
f={y->(1..12).findAll{sprintf('%ta',(java.time.YearMonth.of(y,it)+1<<1)-1)=='Mon'}}

```

Try it online!

The return format is a List of 1-based months.

(Doesn't currently work in TIO since it is using the `YearMonth.plus(long months)` method, which was added in Groovy 2.5.0. TIO currently uses Groovy 2.4.8).

`sprintf('%ta',value)` returns the 3-letter month name.

`YearMonth.of(y,it)+1` returns the `YearMonth` after the given month; `YearMonth<<1` returns the `LocalDate` of the first of the month. Subtracting 1 from this returns the last day of the previous month. This is all just a convoluted way of returning `YearMonth.of(y,it).atEndOfMonth()` in 4 fewer characters.

# Answer
> 0 votes
# Groovy, 57 bytes

```
f={y->(1..12).findAll{"${new Date(y+100,it,0)}"[0]=='M'}}

```

Try it online!

The return format is a `List<Integer>` of 0-based months.

This uses the legacy `Date(int year, int month, int date)` constructor that takes a year (minus 1900), the 0-based month, and the day of month.

The legacy `Date` class uses the Julian calendar prior to 1583. However, the day-of-week is on a 400 year cycle, so I added 2000 (400\*5) to the date. Since 1900 has to be subtracted from the input date, I'm actually passing in the three-character number 100 (2000-1900) for the year.

In order to get the last day of the month, I'm passing in months 1-12 (February through the following year's January, since `Date` uses 0-based months) and day-of-month 0 (the day before the first of that month). This gets me the last day of January - December of the given year.

Finally, the string representation of `Date` is in "Sun Nov 01 00:00:00 CDT 2020" format. I'm converting the date to a `GString` using string interpolation, and then comparing the first character of that string to "M" for "Monday".

---
Tags: code-golf, date
---


title: UTF-8 Reduce Ascii art

text:
# Question
Title: UTF-8 Reduce Ascii art
This challenge is a *cut'n paste* from Enlarge ASCII art, but *reversed*, using *PetSCII* based *half-block* chars:

```
string=" ▝▘▀▗▐▚▜▖▞▌▛▄▟▙█"

```

There, *PetSCII* is emulated by using UTF-8 characters, you may found between *`U+2580 UPPER HALF BLOCK`* and *`U+259F QUADRANT UPPER RIGHT AND LOWER LEFT AND LOWER RIGHT`*.

So the goal is to reduce by `1/2` submited .

You have to group 2 char from 2 lines to obtain one 2x2 pattern for one character:

```
|XX|         |X |         |X |         |  |
|XX| -> '█'  |XX| -> '▙'  | X| -> '▚'  | X| -> '▗'  and so on...

```

Some samples: From

```
 OOOOOO  OOOOOO  OOOOOO  OOOOOOO      OOOOOO   OOOOOO  OO      OOOOOOO
OO      OO    OO OO   OO OO          OO       OO    OO OO      OO
OO      OO    OO OO   OO OOOOO       OO   OOO OO    OO OO      OOOOO
OO      OO    OO OO   OO OO          OO    OO OO    OO OO      OO
 OOOOOO  OOOOOO  OOOOOO  OOOOOOO      OOOOOO   OOOOOO  OOOOOOO OO

```

you have to render:

```
▟▀▀▘▟▀▀▙▐▛▀▙▐▛▀▀  ▗▛▀▀ ▟▀▀▙▐▌  ▐▛▀▀
█   █  █▐▌ █▐▛▀   ▐▌ ▜▌█  █▐▌  ▐▛▀
▝▀▀▘▝▀▀▘▝▀▀▘▝▀▀▀   ▀▀▀ ▝▀▀▘▝▀▀▀▝▘

```

And from:

```
  OOOOOO  OOOOOO  OOOOOO  OOOOOOO      OOOOOO   OOOOOO  OO      OOOOOOO
 OO      OO    OO OO   OO OO          OO       OO    OO OO      OO
 OO      OO    OO OO   OO OOOOO       OO   OOO OO    OO OO      OOOOO
 OO      OO    OO OO   OO OO          OO    OO OO    OO OO      OO
  OOOOOO  OOOOOO  OOOOOO  OOOOOOO      OOOOOO   OOOOOO  OOOOOOO OO

```

Where 1st column hold spaces you may render:

```
▗▛▀▀▗▛▀▜▖█▀▜▖█▀▀▘  ▟▀▀▘▗▛▀▜▖█   █▀▀▘
▐▌  ▐▌ ▐▌█ ▐▌█▀▘   █ ▝█▐▌ ▐▌█   █▀▘
 ▀▀▀ ▀▀▀ ▀▀▀ ▀▀▀▘  ▝▀▀▘ ▀▀▀ ▀▀▀▘▀

```

Piping:

```
wget -O - https://codegolf.stackexchange.com/q/19123/9424 |
    sed -ne '/<pre><code>/,/<\/code><\/pre>/{//{/\//q};s/<pre><code>//;p}'
   ('l2v2l6v2'+  'e1l1v3l2'+
 'v3e1v7e1v7e1v7e1l2v6e1l4v5'+
'e1l6v4e1l8v3e1l7l3v2e1l9l3v1')
 .replace(/[lve]\d/g,function
   (c){return Array(-~c[1]).
      join({l:' ',v:'Love'
         ,e:'\n'}[c[0
             ]])})

```

must give:

```
▗▟█████▙▟█████▄
▜█████████████▛▘
 ▝▀███▙▛█████▀
    ▝▀▜██▀▘

```

Other samples on my terminal:

## With standard rules:

* Input ASCII from STDIN or file, without special chars, tabulations or UTF-8.
* Each submited chars have to be represented, only whitespaces have to stay *empty*.
* This is too, so the lowest score win. Score is computed as:
    + `+1` by chars, to be counted **in chars, not in bytes!!** Ie: `s=' ▝▘▀▗▐▚▜▖▞▌▛▄▟▙█'` count for **20** chars, not **52** !!
    + `-10` for explanation;
    + `+20` for use of external font tool or library.

# Answer
## GolfScript (90 chars)

```
n/.,1&[""]*+.{,}%$-1=.1&+{1$,-´' '*+}+%2/{zip 2/{~+0\{32=!1$++}/" ▗▝▐▖▄▞▟▘▚▀▜▌▙▛█"3/=}%n}%

```

A lot of this goes to handling ragged arrays. Nasty test case:

```
xx
xxx
xxx
xx
x

```

contains a 3 different 2x2 grids with only one of the 4 cells containing any character at all.

To make things worse, the `zip` transposition to chop the columns into pairs gives the same output for `["xx" "xxx"]zip` and `["xxx" "xx"]zip`. I therefore begin by padding out to ensure that all lines are the same even length, and that there are an even number of lines.

Note that this program assumes that the interpreter will treat " ▗▖▄▝▐▞▟▘▚▌▙▀▜▛█" as a string of length 48, even though as per instructions in the question I'm counting it as 16 chars plus delimiters.

I've tested this to the best of my ability, but I can't find a monospace font which actually renders those characters correctly.
> 4 votes

# Answer
# APL (Dyalog Extended), 38 - 10 = 28 chars

```
' ▗▖▄▝▐▞▟▘▚▌▙▀▜▛█'[{2⊥∊⍵}⌺(2 2⍴2)≠⎕⍪0]

```

Try it online!

-10 bytes for an explanation? Count me in!

-14 bytes from Adám.

Takes input as a list of lines from STDIN.

## Explanation

```
' ▗▖▄▝▐▞▟▘▚▌▙▀▜▛█'[{2⊥∊⍵}⌺(2 2⍴2)⊢↑{2|≢⍵:⍵,0⋄⍵}' '≠⎕]
                                                   ⎕  take input
                                               ' '≠   convert spaces to 0, 1 otherwise
                                   {2|≢⍵:⍵,0⋄⍵}       if there are an odd number of rows, append a 0 to each column
                                  ⊢↑                  convert to matrix, apply the following:
                          ⌺(2 2⍴2)                    cut the matrix into 2x2 pieces, apply the following to them:
                    {2⊥∊⍵}                            enlist, decode from base 2
' ▗▖▄▝▐▞▟▘▚▌▙▀▜▛█'[                                 ] index those numbers into the box drawing characters

```
> 3 votes

# Answer
# C++ (gcc), ~~257 ... 254~~ 248 - 32 - 10 = 212 chars

```
#include<bits/stdc++.h>
namespace std{int f(){string a,b;for(int i:{1,3}){getline(cin,a={});b.resize(max(a.size()/2,b.size()));for(int j=a.size();j--;)b[j/2]+=(a[j]>32)<<i-j%2;}for(int i:b)cout.write(" ▝▘▀▗▐▚▜▖▞▌▛▄▟▙█"+i*3,3);cout<<endl;cin&&f();}}

```

Try it online!

Explained:

```
#include<bits/stdc++.h> // Evil hack to include all STL headers

namespace std {         // Shorter than using namespace std;

int f() {               // int is one byte shorter than void
  string a, b;          // a will hold one input line, b will hold one reduced line

  for (int i: {1, 3}) {                           // Do two iterations:
    getline(cin, a = {});                         // Read an input line, make sure it is empty first
    b.resize(max(a.size() / 2, b.size()));        // Resize b such that it is max of both inputs divided by 2
    for (int j = a.size(); j--;)                  // Loop over all characters in the input line backwards (order doesn't matter here)
      b[j/2] += (a[j] > 32) << i - j % 2;         // Set the bits in b depending on the presence of non-whitespace in a
  }

  for (int i: b)                                  // For each character in b:
    cout.write("⠀▝▘▀▗▐▚▜▖▞▌▛▄▟▙█" + 3 * i, 3);    // Write the corresponding multibyte character

  cout << endl;                                   // Write a newline and annoy people with an unnecessary flush

  cin && f();                                     // If we didn't reach the end of the input yet:
                                                  // Tail recurse to the start of the function
}

}

```

Thanks to Razetime for fixing the wrong space character. I also found an issue if the input is an odd number of lines, which required three extra characters to fix. Thanks to ceilingcat for shaving off 9 bytes.
> 3 votes

# Answer
# Perl 6, 159 chars (192 bytes)

```
(|lines.map(*~' '),'')».comb(/../).rotor(2).map:{my@d='  'xx.max(*.elems);say [~] map {"█▛▜▀▙▌▚▘▟▞▐▝▄▖▗ ".comb[:2(.trans([' ',/./]=>~⑩))]},[Z~] .map:{|$_,|@d}}

```

Try it online!
> 2 votes

# Answer
## Bash (~~203~~, 197 chars)

```
#!/bin/bash
r=" ▝▘▀▗▐▚▜▖▞▌▛▄▟▙█" IFS=;while read -r m;do read -r n o;for((l=${#m}>${#n}?${#m}:${#n},i=0; i<l; i+=2)){
printf -ve %-2s "${n:i:2}" "${m:i:2}";e=${e//[^ ]/1};o+=${r:2#${e// /0}:1};};echo "$o";done

```

or

```
r=" ▝▘▀▗▐▚▜▖▞▌▛▄▟▙█" IFS=
while read -r m; do
    read -r n o
    for ((l=${#m}>${#n}?${#m}:${#n},i=0; i<l; i+=2)) {
        printf -ve %-2s "${n:i:2}" "${m:i:2}"
        e=${e//[^ ]/1}
        o+=${r:2#${e// /0}:1}
    }
    echo "$o"
done

```
> 1 votes

# Answer
## Perl (192 chars)

```
#!/usr/bin/perl -CS
use utf8;my$r=" ▘▝▀▖▌▞▛▗▚▐▜▄▙▟█";while($v=<>){$w=<>;foreach my$i(0..length($v)/2){($x=substr($v,$i*2,2).substr($w,$i*2,2))=~s/\S/1/g;$x=~s/ /0/g;print substr($r,ord pack("b8",$x),1)}print"\n"}

```

or

```
#!/usr/bin/perl -CS
use utf8;
my $r = " ▘▝▀▖▌▞▛▗▚▐▜▄▙▟█";
while ( $v = <> ) {
    $w = <>;
    foreach my $i ( 0 .. length($v) / 2 ) {
        ( $x = substr( $v, $i * 2, 2 ) . substr( $w, $i * 2, 2 ) ) =~ s/\S/1/g;
        $x =~ s/ /0/g;
        print substr( $r, ord pack( "b8", $x ), 1 );
    }
    print "\n";
}

```
> 1 votes

---
Tags: code-golf, ascii-art
---