问:
Smallest palindrome divisible by the input
Given a positive integer N, output the smallest positive integer such that this number is a palindrome (i.e. is its own reverse) and is divisible by N.

The palindrome (i.e. the output) must not need a leading zero to be a palindrome, e.g. 080 is not the valid answer for 16.

The input will never be a multiple of 10, because of the previous reason.

Your program may take as much time as necessary, even if in practice it would be way too long to output the answer.

Inputs and outputs

You may take the input through STDIN, as a function argument, or anything similar.

You may print the output to STDOUT, return it from a function, or anything similar.

Inputs and outputs must be in the decimal base.

Test cases

```<code>N        Output
1        1
2        2
16       272
17       272
42       252
111      111
302      87278
1234     28382
</code>```

Scoring

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

答:
Racket 174 bytes

```<code>(let((p?(λ(m)(equal? m(string->number(list->string(reverse(string->list(number->string m)))))))))
(let loop((N n))(cond[(and(p? N)(= 0(modulo N n)))N][else(loop(add1 N))])))
</code>```

Ungolfed:

```<code>(define (f1 n)
  (let ((p? (λ (m)(equal? m
                          (string->number
                           (list->string
                            (reverse
                             (string->list
                              (number->string m)))))))))
    (let loop ((N n))
      (cond
        [(and (p? N) (= 0 (modulo N n))) N]
        [else (loop (add1 N))]
        ))))
</code>```

Testing:

```<code>(f 1)
(f 2)
(f 16)
(f 17)
(f 42)
(f 111)
(f 302)
(f 1234)
</code>```

Output:

```<code>1
2
272
272
252
111
87278
28382
</code>```

Body:
Racket 174 bytes

(let((p?(λ(m)(equal? m(string->number(list->string(reverse(string->list(number->string m)))))))))
(let loop((N n))(cond[(and(p? N)(= 0(modulo N n)))N][else(loop(add1 N))])))

Ungolfed:

(define (f1 n)
  (let ((p? (λ (m)(equal? m
                          (string->number
                           (list->string
                            (reverse
                             (string->list
                              (number->string m)))))))))
    (let loop ((N n))
      (cond
        [(and (p? N) (= 0 (modulo N n))) N]
        [else (loop (add1 N))]
        ))))

Testing:

(f 1)
(f 2)
(f 16)
(f 17)
(f 42)
(f 111)
(f 302)
(f 1234)

Output:

1
2
272
272
252
111
87278
28382


问:
Divisibility test

Task

Given two strictly positive integers n and d as input, determine whether n is evenly divisible by d, i.e., if there exists an integer q such that n = qd.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

The output should be a truthy or a falsy value; truthy if n is divisible by d, and falsy otherwise.

Your code only has to handle integers it can represent natively, as long as it works for all signed 8-bit integers. However, your algorithm has to work for arbitrarily large integers.

You may use any programming language, but note that these loopholes are forbidden by default.

This is code-golf, so the shortest valid answer – measured in bytes – wins.

Test cases

```<code> n,  d    output

 1,  1    truthy
 2,  1    truthy
 6,  3    truthy
17, 17    truthy
22,  2    truthy
 1,  2    falsy
 2,  3    falsy
 2,  4    falsy
 3,  9    falsy
15, 16    falsy
</code>```

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 + 3 (-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>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
Elixir, 14 bytes

```<code>&rem(&1,&2)==0
</code>```

Anonymous function defined using the capture operator.

Full program with test cases (yes, the . in the function call is mandatory!):

```<code>s=&rem(&1,&2)==0
# test cases
IO.puts s.(1,1) # true
IO.puts s.(2,1) # true
IO.puts s.(6,3) # true
IO.puts s.(17,17)   # true
IO.puts s.(22,2)    # true
IO.puts s.(1,2) # false
IO.puts s.(2,3) # false
IO.puts s.(2,4) # false
IO.puts s.(3,9) # false
IO.puts s.(15,16)   # false
</code>```

Try it online on ElixirPlayground !

ContentLicense: CC BY-SA 3.0

Title: Divisibility test

Body:
Elixir, 14 bytes

&rem(&1,&2)==0

Anonymous function defined using the capture operator.

Full program with test cases (yes, the . in the function call is mandatory!):

s=&rem(&1,&2)==0
# test cases
IO.puts s.(1,1) # true
IO.puts s.(2,1) # true
IO.puts s.(6,3) # true
IO.puts s.(17,17)   # true
IO.puts s.(22,2)    # true
IO.puts s.(1,2) # false
IO.puts s.(2,3) # false
IO.puts s.(2,4) # false
IO.puts s.(3,9) # false
IO.puts s.(15,16)   # false

Try it online on ElixirPlayground !


问:
Is it an Odd Word?

Challenge

Given a single word as input, determine if the word is odd or even.

Odd and Even words

Assume the general rules:

```<code>odd + odd = even
even + odd = odd
odd + even = odd
even + even = even
</code>```

In the alphabet, the odd letters are:

```<code>aeiou
</code>```

And the even letters are:

```<code>bcdfghjklmnpqrstvwxyz
</code>```

The same applies to capital letters (AEIOU are odd and BCDFGHJKLMNPQRSTVWXYZ are even).

You then 'add' each of the letters in the word together. For example, the word cats is equivalent to:

```<code>even + odd + even + even
</code>```

Which simplifies to:

```<code>odd + even
</code>```

Which simplifies further to:

```<code>odd
</code>```

So the word cats is odd.

Examples

```<code>Input:  trees
Output: even
</code>```

```<code>Input:  brush
Output: odd
</code>```

```<code>Input:  CAts
Output: odd
</code>```

```<code>Input:  Savoie
Output: even
</code>```

```<code>Input:  rhythm
Output: even
</code>```

Rules

All input will be a single word which will only contain alphabetical characters.

If the word is odd, output a truthy value. If the word is even, output a falsey value.

Winning

The shortest code in bytes wins.

答:
Ruby, 30 bytes

```<code>->w{w.count('aeiouAEIOU')%2>0}
</code>```

Returns true for an odd word and false for an even word. The existing Ruby solution returns 0 for even words, which is a truthy value in Ruby.

Title: Is it an Odd Word?

Body:
Ruby, 30 bytes

->w{w.count('aeiouAEIOU')%2>0}

Returns true for an odd word and false for an even word. The existing Ruby solution returns 0 for even words, which is a truthy value in Ruby.


问:
Appease Your Google Overlords: Draw the "G" Logo
Write a program or function that takes in a positive integer N, and outputs an N×N pixel image of Google's "G" logo according to this* construction:

For example, if N is 400, a 400×400 pixel logo should be output, with correct dimensions and colors:

It should look accurate regardless of how large or small N is. e.g. here is N = 13:

Your code should not need to connect to the internet. For example, scaling an externally hosted svg is not allowed. (Scaling an svg encoded in your code would be fine though.)

Anti-aliasing may be used or not. It's up to you.

Notice that the horizontal bar of the "G" does not extend all the way to the right edge of the image. The circle curves normally inward on the right edge before it is cut off.

The shortest code in bytes wins.

* The construction of the logo has been simplified for this challenge. The correct construction can be seen here and here.

答:
JavaScript (ES7), <s>285</s> <s>258</s> <s>254</s> <s>252</s> 251 bytes

Prompts for the width of the logo (up to 999) and draws it in a canvas, pixel per pixel.

Edit: The initial version was converting Cartesian coordinates (x,y) to Polar coordinates (r,a), but we don't really need the angle. It's simpler (and significantly shorter) to just do comparisons between x and y to find out in which quarter we are.

Edit: Saved 1 byte thanks to ETHproductions.

JS, <s>251</s> <s>224</s> <s>220</s> <s>218</s> 217 bytes

for(w=x=y=prompt(c=c.getContext`2d`)/2;r=(x*x+y*y)**.5,q=(x<y)+2*(x<-y),c.fillStyle='#'+'4285F434A853EA4335FBBC05FFF'.substr(x>0&r<w&y*y<w*w/25?0:r<w*.6|r>w|!q&y<0?24:q*6,6),x-->-w||y-->-(x=w);)c.fillRect(x+w,y+w,1,1)
```

<h3>HTML, 34 bytes</h3>

<pre class="lang-html prettyprint-override"><code><canvas id=c width=999 height=999>
</code>```

ES6 version: <s>258</s> <s>231</s> <s>227</s> <s>225</s> 224 + 34 = 258 bytes

Recommended maximum width for the snippet: 190.

for(w=x=y=prompt(c=c.getContext`2d`)/2;r=Math.pow(x*x+y*y,.5),q=(x<y)+2*(x<-y),c.fillStyle='#'+'4285F434A853EA4335FBBC05FFF'.substr(x>0&r<w&y*y<w*w/25?0:r<w*.6|r>w|!q&y<0?24:q*6,6),x-->-w||y-->-(x=w);)c.fillRect(x+w,y+w,1,1)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id=c width=999 height=999></code>```

Body:
JavaScript (ES7), <s>285</s> <s>258</s> <s>254</s> <s>252</s> 251 bytes

Prompts for the width of the logo (up to 999) and draws it in a canvas, pixel per pixel.

Edit: The initial version was converting Cartesian coordinates (x,y) to Polar coordinates (r,a), but we don't really need the angle. It's simpler (and significantly shorter) to just do comparisons between x and y to find out in which quarter we are.

Edit: Saved 1 byte thanks to ETHproductions.

JS, <s>251</s> <s>224</s> <s>220</s> <s>218</s> 217 bytes

for(w=x=y=prompt(c=c.getContext`2d`)/2;r=(x*x+y*y)**.5,q=(x<y)+2*(x<-y),c.fillStyle='#'+'4285F434A853EA4335FBBC05FFF'.substr(x>0&r<w&y*y<w*w/25?0:r<w*.6|r>w|!q&y<0?24:q*6,6),x-->-w||y-->-(x=w);)c.fillRect(x+w,y+w,1,1)

HTML, 34 bytes

<canvas id=c width=999 height=999>

ES6 version: <s>258</s> <s>231</s> <s>227</s> <s>225</s> 224 + 34 = 258 bytes

Recommended maximum width for the snippet: 190.

for(w=x=y=prompt(c=c.getContext`2d`)/2;r=Math.pow(x*x+y*y,.5),q=(x<y)+2*(x<-y),c.fillStyle='#'+'4285F434A853EA4335FBBC05FFF'.substr(x>0&r<w&y*y<w*w/25?0:r<w*.6|r>w|!q&y<0?24:q*6,6),x-->-w||y-->-(x=w);)c.fillRect(x+w,y+w,1,1)

<canvas id=c width=999 height=999>


问:
Draw an asterisk triangle
Inspired by a task for Programming 101, here's a challenge that hopefully isn't too easy (or a duplicate).

Input:

A positive integer n >= 1.

Output:

n lines of asterisks, where every new line has one asterisk more than the line before, and starting with one asterisk in the first line.

Test case (n=5):

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

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

答:
Prolog, <s>60 58</s> 56 bytes

```<code>g(N):-N<=0,put(*),g(N-1);!.
f(N):-N<=0,f(N-1),g(N),nl;!.
</code>```

I'm not that familiar with Prolog, but I just gave it a shot.
I'm sure it can be a lot shorter.

Put the code into a file, then load that file into swipl and run f(25). (or some other number).

EDIT: quotes can be left out in put statement

EDIT 2: changing =:= to <= saves 2 bytes. I tried inverting it, but that'd make it wait for a return for some reason.

ContentLicense: CC BY-SA 4.0

Title: Draw an asterisk triangle

Body:
Prolog, <s>60 58</s> 56 bytes

g(N):-N<=0,put(*),g(N-1);!.
f(N):-N<=0,f(N-1),g(N),nl;!.

I'm not that familiar with Prolog, but I just gave it a shot.
I'm sure it can be a lot shorter.

Put the code into a file, then load that file into swipl and run f(25). (or some other number).

EDIT: quotes can be left out in put statement

EDIT 2: changing =:= to <= saves 2 bytes. I tried inverting it, but that'd make it wait for a return for some reason.


问:
List of first n prime numbers most efficiently and in shortest code
Rules are simple:

First n primes (not primes below n), should be printed to standard output separated by newlines (primes should be generated within the code)

primes cannot be generated by an inbuilt function or through a library, i.e. use of a inbuilt or library function such as, prime = get_nth_prime(n), is_a_prime(number), or factorlist = list_all_factors(number) won't be very creative.

Scoring - Say, we define Score = f([number of chars in the code]), O(f(n)) being the complexity of your algorithm where n is the number of primes it finds. So for example, if you have a 300 char code with O(n^2) complexity, score is 300^2 = 90000, for 300 chars with O(n*ln(n)), score becomes 300*5.7 = 1711.13 (let's assume all logs to be natural logs for simplicity)

Use any existing programming language, lowest score wins

Edit: Problem has been changed from finding 'first 1000000 primes' to 'first n primes' because of a confusion about what 'n' in O(f(n)) is, n is the number of primes you find (finding primes is the problem here and so complexity of the problem depends on the number of primes found)

Note: to clarify some confusions on complexity, if 'n' is the number of primes you find and 'N' is the nth prime found, complexity in terms of n is and N are not equivalent i.e. O(f(n)) != O(f(N)) as , f(N) != constant * f(n) and N != constant * n, because we know that nth prime function is not linear, I though since we were finding 'n' primes complexity should be easily expressible in terms of 'n'.

As pointed out by Kibbee, you can visit this site to verify your solutions (here, is the old google docs list)

Please Include these in your solution -

what complexity your program has (include basic analysis if not trivial)

character length of code

the final calculated score

This is my first CodeGolf Question so, if there is a mistake or loophole in above rules please do point them out.

答:
Python 3, <s>117</s> 106 bytes

This solution is slightly trivial, as it outputs 0 where a number is not prime, but I'll post it anyway:

```<code>r=range
for i in[2]+[i*(not 0 in[i%j for j in r(3,int(i**0.5)+1,2)])for i in r(3,int(input()),2)]:print(i)
</code>```

Also, I'm not sure how to work out the complexity of an algorithm. Please don't downvote because of this. Instead, be nice and comment how I could work it out. Also, tell me how I could shorten this.

Body:
Python 3, <s>117</s> 106 bytes

This solution is slightly trivial, as it outputs 0 where a number is not prime, but I'll post it anyway:

r=range
for i in[2]+[i*(not 0 in[i%j for j in r(3,int(i**0.5)+1,2)])for i in r(3,int(input()),2)]:print(i)

Also, I'm not sure how to work out the complexity of an algorithm. Please don't downvote because of this. Instead, be nice and comment how I could work it out. Also, tell me how I could shorten this.


答:
Python 2, <s>378</s> 373 bytes

I really wanted to do this using turtle. I had to dust off my knowledge of Geometry for this, calculating angles and lengths not provided in the challenge description.

Edit: removed up(), since doing so removes the little sliver of white between green and blue and makes the inner circle look better. This slows down the program even more.

Edit: replaced 9*n with 2*n to make faster. I determined that it would still create a smooth circle.

from turtle import*
n=input()
C=circle
F=fill
K=color
q=90
w="white"
t=n*.3
lt(45)
def P(c,x,A):K(c);F(1);fd(x);lt(q);C(x,A,2*n);F(0);goto(0,0);rt(q)
for c in"#EA4335","#FBBC05","#34A853":P(c,n/2,q)
P(w,t,360)
K("#4285F4")
F(1)
fd(n/2)
lt(q)
a=11.537
C(n/2,45+a,2*n)
seth(0)
bk(.489*n)
rt(q)
fd(n/5)
lt(q)
fd(t)
F(0)
bk(t)
K(w)
F(1)
fd(.283*n)
lt(94-2*a)
C(t,a-45,2*n)
F(0)
```

Notes:

The trinkets use Python 3, so the input must be cast to int.

The trinkets go really slow for large n if you remove speed(0), which I added only for speed.

The slowness of the code is mostly due to the third parameter of circle growing O(n), since it determines how many sides the inscribed polygon for drawing the circle has.

Try it online

Ungolfed: Try it online

Fun fact: Trinket is an anagram of Tkinter, Python's GUI package and the foundation for turtle.

Title: Appease Your Google Overlords: Draw the "G" Logo

Body:
Write a program or function that takes in a positive integer N, and outputs an N×N pixel image of Google's "G" logo according to this* construction:

For example, if N is 400, a 400×400 pixel logo should be output, with correct dimensions and colors:

It should look accurate regardless of how large or small N is. e.g. here is N = 13:

Your code should not need to connect to the internet. For example, scaling an externally hosted svg is not allowed. (Scaling an svg encoded in your code would be fine though.)

Anti-aliasing may be used or not. It's up to you.

Notice that the horizontal bar of the "G" does not extend all the way to the right edge of the image. The circle curves normally inward on the right edge before it is cut off.

The shortest code in bytes wins.

* The construction of the logo has been simplified for this challenge. The correct construction can be seen here and here.

Body:
Python 2, <s>378</s> 373 bytes

I really wanted to do this using turtle. I had to dust off my knowledge of Geometry for this, calculating angles and lengths not provided in the challenge description.

Edit: removed up(), since doing so removes the little sliver of white between green and blue and makes the inner circle look better. This slows down the program even more.

Edit: replaced 9*n with 2*n to make faster. I determined that it would still create a smooth circle.

from turtle import*
n=input()
C=circle
F=fill
K=color
q=90
w="white"
t=n*.3
lt(45)
def P(c,x,A):K(c);F(1);fd(x);lt(q);C(x,A,2*n);F(0);goto(0,0);rt(q)
for c in"#EA4335","#FBBC05","#34A853":P(c,n/2,q)
P(w,t,360)
K("#4285F4")
F(1)
fd(n/2)
lt(q)
a=11.537
C(n/2,45+a,2*n)
seth(0)
bk(.489*n)
rt(q)
fd(n/5)
lt(q)
fd(t)
F(0)
bk(t)
K(w)
F(1)
fd(.283*n)
lt(94-2*a)
C(t,a-45,2*n)
F(0)

Notes:

The trinkets use Python 3, so the input must be cast to int.

The trinkets go really slow for large n if you remove speed(0), which I added only for speed.

The slowness of the code is mostly due to the third parameter of circle growing O(n), since it determines how many sides the inscribed polygon for drawing the circle has.

Try it online

Ungolfed: Try it online

Fun fact: Trinket is an anagram of Tkinter, Python's GUI package and the foundation for turtle.


Body:
MATLAB, <s>189</s> 184 bytes

[X,Y]=meshgrid(-5:10/(input("")-1):5);[A,R]=cart2pol(-X,Y);I=round(A*2/pi+3);I(R<3)=1;I(X>0&Y.^2<1)=5;I(R>5)=1;image(I)
colormap([1,1,1;[234,67,53;251,188,5;52,168,83;66,133,244]/255])

ungolfed

[X,Y]=meshgrid(-5:10/(input("")-1):5);    % coordinates in 10th of image width
[A,R]=cart2pol(-X,Y);                     % angle and radius
I=round(A*2/pi+3); % map [0-45,45-135,135-225,225-315,315-360] to [1,2,3,4,5]
I(R<3)=1;                                 % clear inner pixels
I(X>0&Y.^2<1)=5;                          % draw horizontal line
I(R>5)=1;                                 % clear outer pixels
image(I)
colormap([1,1,1;[234,67,53;251,188,5;52,168,83;66,133,244]/255])


答:
Elixir, 45 bytes

```<code>&rem(length(Regex.scan(~r/[aeiou]/i,&1)),2)>0
</code>```

Anonymous function defined using the capture operator. If the number of vowels is odd, the specified word is odd, so the function returns true.

Full program with test cases:

```<code>s=&rem(length(Regex.scan(~r/[aeiou]/i,&1)),2)>0
# test cases
IO.puts s.("trees") # false
IO.puts s.("brush") # true
IO.puts s.("CAts")  # true
IO.puts s.("Savoie")    # false
IO.puts s.("rhythm")    # false
</code>```

Try it online on ElixirPlayground !

Title: Is it an Odd Word?

Body:
Challenge

Given a single word as input, determine if the word is odd or even.

Odd and Even words

Assume the general rules:

```<code>odd + odd = even
even + odd = odd
odd + even = odd
even + even = even
</code>```

In the alphabet, the odd letters are:

```<code>aeiou
</code>```

And the even letters are:

```<code>bcdfghjklmnpqrstvwxyz
</code>```

The same applies to capital letters (AEIOU are odd and BCDFGHJKLMNPQRSTVWXYZ are even).

You then 'add' each of the letters in the word together. For example, the word cats is equivalent to:

```<code>even + odd + even + even
</code>```

Which simplifies to:

```<code>odd + even
</code>```

Which simplifies further to:

```<code>odd
</code>```

So the word cats is odd.

Examples

```<code>Input:  trees
Output: even
</code>```

```<code>Input:  brush
Output: odd
</code>```

```<code>Input:  CAts
Output: odd
</code>```

```<code>Input:  Savoie
Output: even
</code>```

```<code>Input:  rhythm
Output: even
</code>```

Rules

All input will be a single word which will only contain alphabetical characters.

If the word is odd, output a truthy value. If the word is even, output a falsey value.

Winning

The shortest code in bytes wins.

Body:
Elixir, 45 bytes

&rem(length(Regex.scan(~r/[aeiou]/i,&1)),2)>0

Anonymous function defined using the capture operator. If the number of vowels is odd, the specified word is odd, so the function returns true.

Full program with test cases:

s=&rem(length(Regex.scan(~r/[aeiou]/i,&1)),2)>0
# test cases
IO.puts s.("trees") # false
IO.puts s.("brush") # true
IO.puts s.("CAts")  # true
IO.puts s.("Savoie")    # false
IO.puts s.("rhythm")    # false

Try it online on ElixirPlayground !


问:
Run Length Decoding
Write the shortest code in the language of your choice to perform run length decoding of the given string.

The string will be supplied as input on stdin in the form

```<code>CNCNCNCNCNCNCNCN
</code>```

where each C could be any printable ASCII character and each N is a digit 1 to 9 (inclusive).

Sample input:

```<code>:144,1'1
</code>```

Corresponding output:

```<code>:4444,'
</code>```

答:
><> - 36 Bytes

```<code>i:01-=?; l2=?v
v?=*68:ro:r-1<
>~~d0.
</code>```

This solution can be run without using the input flag or preloading the stack, although both of those methods could cut down on bytes. If there is any interest, I can describe how it works to anyone who is curious.

Try it here!

Title: Run Length Decoding

Body:
><> - 36 Bytes

i:01-=?; l2=?v
v?=*68:ro:r-1<
>~~d0.

This solution can be run without using the input flag or preloading the stack, although both of those methods could cut down on bytes. If there is any interest, I can describe how it works to anyone who is curious.

Try it here!


问:
Ordering words to fit in a given string
Given a string of letters and a set of words, output an ordering of the words so
that they can be found in the string by dropping letters that are not needed.
Words may occur more than once in the word set. The input string and all words
will consist of 1 to 1000 lower case letters each. The letters to be dropped may occur inside words or between words.

Your program or function can accept the letter string and words as lists, a string, or from STDIN, and must output all words in a correct order as a list
or string output. If there is more than one correct solution, only output one of
them. If there is no possible correct solution, output an empty list or an empty
string.

Examples:

```<code>dogcatfrog cat frog dog
-> dog cat frog

xxcatfixsxhingonxgrapexxxfishingcxat cat grape catfish fishing
-> catfish grape fishing cat

dababbabadbaccbcbaaacdacdbdd aa bb cc dd ba ba ba ab ac da db dc
-> da ab ba ba ba cc bb aa ac dc db dd

flea antelope
->
(no solution)
</code>```

This is code golf. Lowest number of bytes wins.

Edit: Explained that extra characters can be inside words.

答:
Groovy (44 Bytes)

I can't believe nobody else used regexes for this...

```<code>{a,b->a.findAll(/${b.join('|')}/).join(" ")}
</code>```

Explanation

/${b.join('|')}/ - Create a regex to find any of the words in a string.

.findAll(...) - Find and collect all occurrences in the string into an array.

.join(" ") - Join the array together with spaces.

Basically, if there aren't any occurrences, the array is empty and returns an empty string implicitly. If it does find occurrences, it returns an array object with the occurrences then flattens it into a string.

Title: Ordering words to fit in a given string

Body:
Groovy (44 Bytes)

I can't believe nobody else used regexes for this...

{a,b->a.findAll(/${b.join('|')}/).join(" ")}

Explanation

/${b.join('|')}/ - Create a regex to find any of the words in a string.

.findAll(...) - Find and collect all occurrences in the string into an array.

.join(" ") - Join the array together with spaces.

Basically, if there aren't any occurrences, the array is empty and returns an empty string implicitly. If it does find occurrences, it returns an array object with the occurrences then flattens it into a string.


问:
Add two numbers
Input: Two integers. Preferably decimal integers, but other forms of numbers can be used. These can be given to the code in standard input, as arguments to the program or function, or as a list.

Output: Their sum. Use the same format for output integers as input integers. For example, the input 5 16 would lead to the output 21.

Restrictions: No standard loopholes please. This is code-golf, answer in lowest amount of bytes wins.

Notes: This should be fairly trivial, however I'm interested to see how it can be implemented. The answer can be a complete program or a function, but please identify which one it is.

Test cases:

```<code>1 2 -> 3
14 15 -> 29
7 9 -> 16
-1 8 -> 7
8 -9 -> -1
-8 -9 -> -17
</code>```

Or as CSV:

```<code>a,b,c
1,2,3
14,15,29
7,9,16
-1,8,7
8,-9,-1
-8,-9,-17
</code>```

Leaderboard

var QUESTION_ID=84260,OVERRIDE_USER=8478;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

```

答:
Y, 5 bytes

```<code>{α+β}
</code>```

Anonymous function returning the sum of it first and second argument.

Title: Add two numbers

Body:
Y, 5 bytes

{α+β}

Anonymous function returning the sum of it first and second argument.


问:
Draw an ASCII chess board!
Here is a simple challenge for you: You must produce this ASCII representation of a chess board. White is represented by uppercase characters, and black is represented by lowercase. Empty tiles are represented by a .. Here is the full board:

```<code>rnbqkbnr
pppppppp
........
........
........
........
PPPPPPPP
RNBQKBNR
</code>```

Since this is a kolmogorov-complexity question, you may not take any input and you must output this board by any default method, for example, saving a file, printing to STDOUT or returning from a function. You may optionally produce one trailing newline. Standard loopholes apply, and the shortest program in bytes!

However, remember this is equally as much a competition between submissions in the same language. While it's unlikely that a languages like Java could beat a language like perl, or a golfing language like pyth or cjam, having the shortest Java answer is still really impressive! To help you track the shortest answer in each language, you may use this leaderboard, which will show the shortest submission by language and overall.

Leaderboards

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 leaderboard snippet:

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

var QUESTION_ID=95745,OVERRIDE_USER=31716;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

```

答:
Microscript II, 56 bytes

```<code>"rnbqkbnr\npppppppp"P"........"PPPP"PPPPPPPP\nRNBQKBNR"
</code>```

Title: Draw an ASCII chess board!

Body:
Microscript II, 56 bytes

"rnbqkbnr\npppppppp"P"........"PPPP"PPPPPPPP\nRNBQKBNR"


问:
Make an error quine!
Your challenge: write a "program", for a language of your choice, that causes the compiler/interpreter/runtime to produce error output when compiling/running your program which is identical to your program's source code.

Rules:

Your program may be specific to a particular version or implementation of your language's compiler/interpreter/runtime environment. If so, please specify the particulars.

Only standard compiler/interpreter/runtime options are permitted. You cannot pass some weird flag to your compiler to get a specific result.

The program does not need to be syntactically or semantically valid, but I may give a bounty to the best syntactically valid submission.

The program must not produce any output of its own (e.g. by calling a print or output function). All output generated upon attempting to compile/run the program must originate from the compiler/interpreter/runtime.

The complete output of the compiler/interpreter/runtime must be exactly identical to your program source code.

The compiler/interpreter/runtime must generate at least one error message when invoked with your program.

This is a popularity contest. Most creative answer, as determined by upvotes, wins. If you can give a good case for using a standard loophole, you may do so.

答:
TrumpScript - Making PPCG Great Again (TrumpScript)

When trying to run this language on a windows PC, the output is always:

```<code>Make sure the currently-running OS is not Windows, because we're not PC
</code>```

So when running this program:

```<code>Make sure the currently-running OS is not Windows, because we're not PC
</code>```

It won't even parse it because the OS check fails, and you get the error message. Examples can be given for Mac as well if anyone wants them haha. God I've wanted to use this in PPCG for awhile now, good that I finally get to.

Full list of errors that can be triggered using environmental specifics:

https://github.com/samshadwell/TrumpScript/blob/master/src/trumpscript/utils.py

Bonus Answer: ArnoldC (ArnoldC)

ArnoldC requires root declaration of IT'S SHOWTIME, meaning main(), so:

```<code>WHAT THE FUCK DID I DO WRONG
</code>```

Results in the only error message in ArnoldC...

```<code>WHAT THE FUCK DID I DO WRONG
</code>```

Which, is actually... hilarious. You have to run it non-verbose though w/o stack traces.

Title: Make an error quine!

Body:
TrumpScript - Making PPCG Great Again (TrumpScript)

When trying to run this language on a windows PC, the output is always:

Make sure the currently-running OS is not Windows, because we're not PC

So when running this program:

Make sure the currently-running OS is not Windows, because we're not PC

It won't even parse it because the OS check fails, and you get the error message. Examples can be given for Mac as well if anyone wants them haha. God I've wanted to use this in PPCG for awhile now, good that I finally get to.

Full list of errors that can be triggered using environmental specifics:

https://github.com/samshadwell/TrumpScript/blob/master/src/trumpscript/utils.py

Bonus Answer: ArnoldC (ArnoldC)

ArnoldC requires root declaration of IT'S SHOWTIME, meaning main(), so:

WHAT THE FUCK DID I DO WRONG

Results in the only error message in ArnoldC...

WHAT THE FUCK DID I DO WRONG

Which, is actually... hilarious. You have to run it non-verbose though w/o stack traces.


答:
PHP + GD, <s>529</s> 449 bytes

This takes a query string parameter n and outputs a PNG version of the logo of the specified size.

```<code><?php $n=$_GET['n'];$h=$n/2;$c='imagecolorallocate';$a='imagefilledarc';$i=imagecreatetruecolor($n,$n);$m=[$c($i,66,133,244),$c($i,52,168,83),$c($i,251,188,5),$c($i,234,67,53),$c($i,255,255,255)];imagefill($i,0,0,$m[4]);$j=-11.6;foreach([45,135,225,315]as$k=>$e){$a($i,$h,$h,$n,$n,$j,$e,$m[$k],0);$j=$e;}$a($i,$h,$h,$n*.6,$n*.6,0,0,$m[4],0);imagefilledrectangle($i,$h,$h-$n*.1,$h+$h*.98,$h+$h*.2,$m[0]);header('Content-Type:image/png');imagepng($i);
</code>```

Ungolfed:

```<code><?php

$n = $_GET['n'];$h=$n/2;
$c = 'imagecolorallocate';$a='imagefilledarc';
$i = imagecreatetruecolor($n,$n);

// Create array of colors
$m=[$c($i,66,133,244),$c($i,52,168,83),$c($i,251,188,5),$c($i,234,67,53),$c($i,255,255,255)];

// Fill background with white
imagefill($i, 0, 0, $m[4]);

// Create four arcs
$j=-11.6;
foreach([45,135,225,315]as$k=>$e){
    $a($i, $h, $h, $n, $n, $j, $e, $m[$k], 0);$j=$e;
}

// Hollow out the center and fill with white
$a($i, $h, $h, $n*.6,$n*.6,0,0,$m[4],0);

// create the horizontal bar
imagefilledrectangle($i,$h,$h-$n*.1,$h+$h*.98,$h+$h*.2,$m[0]);

// Output
header('Content-Type: image/png');
imagepng($i);
</code>```

N=13:

N=200:

Body:
PHP + GD, <s>529</s> 449 bytes

This takes a query string parameter n and outputs a PNG version of the logo of the specified size.

<?php $n=$_GET['n'];$h=$n/2;$c='imagecolorallocate';$a='imagefilledarc';$i=imagecreatetruecolor($n,$n);$m=[$c($i,66,133,244),$c($i,52,168,83),$c($i,251,188,5),$c($i,234,67,53),$c($i,255,255,255)];imagefill($i,0,0,$m[4]);$j=-11.6;foreach([45,135,225,315]as$k=>$e){$a($i,$h,$h,$n,$n,$j,$e,$m[$k],0);$j=$e;}$a($i,$h,$h,$n*.6,$n*.6,0,0,$m[4],0);imagefilledrectangle($i,$h,$h-$n*.1,$h+$h*.98,$h+$h*.2,$m[0]);header('Content-Type:image/png');imagepng($i);

Ungolfed:

<?php

$n = $_GET['n'];$h=$n/2;
$c = 'imagecolorallocate';$a='imagefilledarc';
$i = imagecreatetruecolor($n,$n);

// Create array of colors
$m=[$c($i,66,133,244),$c($i,52,168,83),$c($i,251,188,5),$c($i,234,67,53),$c($i,255,255,255)];

// Fill background with white
imagefill($i, 0, 0, $m[4]);

// Create four arcs
$j=-11.6;
foreach([45,135,225,315]as$k=>$e){
    $a($i, $h, $h, $n, $n, $j, $e, $m[$k], 0);$j=$e;
}

// Hollow out the center and fill with white
$a($i, $h, $h, $n*.6,$n*.6,0,0,$m[4],0);

// create the horizontal bar
imagefilledrectangle($i,$h,$h-$n*.1,$h+$h*.98,$h+$h*.2,$m[0]);

// Output
header('Content-Type: image/png');
imagepng($i);

N=13:

N=200:


问:
Fill in the grid randomly
Given positive integer n < 10, create a 2 dimensional matrix where each location is filled with its x and y index (starting from the top left).

For example:

Input: 2

```<code>00 10
10 11
</code>```

Input: 3

```<code>00 10 20
01 11 21
02 12 22
</code>```

Once the grid is created, randomly fill each index. This can be with an 'x' or any other way to denote a spot has been filled.

You determine which location to fill by randomly generating indices to fill the matrix. You can only fill n^2 times so you cannot fill as many times as you want until the matrix is completely filled. At the end the matrix must be filled so you must do some work to make sure that you check the random numbers that you use to fill to make sure that spot is not already filled.

Refresh or print after each fill in order to show the progression of the filling iterations.

Example for filling:

Input: 2

```<code>00 10
01 11
</code>```

00 is randomly chosen:

```<code>XX 10
01 11
</code>```

01 is randomly chosen:

```<code>XX 10
XX 11
</code>```

00 is randomly chosen, but since it's already been chosen a re-roll chooses 10:

```<code>XX XX
XX 11
</code>```

11 is randomly chosen:

```<code>XX XX
XX XX
</code>```

Do not print out the random numbers as visually I should be able to see which index was selected. By this I mean do not print "11 is randomly chosen:". It is here for exploratory sake.

Since this is code-golf The shortest code wins.

Have fun and happy golfing!

答:
05AB1E, 29 bytes

```<code><ÝDâJU[X¹ä»,XÐÙg#Jþ2ô.R„  :)U
</code>```

Try it online!

Space chosen as the char for the removed numbers (as it looks nice), but it could be replaced with any char without affecting byte-count.

Explanation

```<code>                                # implicit input n
<ÝDâ                            # cartesian product of [0..n-1] and [0..n-1]
    JU                          # join pairs and store in X
      [     XÐÙg#               # loop until there's only spaces left in X
       X¹ä                      # split X into n pieces
          »,                    # join rows by space and columns by newlines and print
                 Jþ             # join X to string and remove all non-digits
                   2ô.R         # split in pieces of 2 and pick a pair at random
                       „  :)    # replace this pair with 2 spaces
                            U   # and store in X
</code>```

Title: Fill in the grid randomly

Body:
05AB1E, 29 bytes

<ÝDâJU[X¹ä»,XÐÙg#Jþ2ô.R„  :)U

Try it online!

Space chosen as the char for the removed numbers (as it looks nice), but it could be replaced with any char without affecting byte-count.

Explanation

                                # implicit input n
<ÝDâ                            # cartesian product of [0..n-1] and [0..n-1]
    JU                          # join pairs and store in X
      [     XÐÙg#               # loop until there's only spaces left in X
       X¹ä                      # split X into n pieces
          »,                    # join rows by space and columns by newlines and print
                 Jþ             # join X to string and remove all non-digits
                   2ô.R         # split in pieces of 2 and pick a pair at random
                       „  :)    # replace this pair with 2 spaces
                            U   # and store in X


答:
AWK, <s>96</s> 86 bytes

Subtitle: Look Mom! Only adding and some bookkeeping!

File fsoe3.awk:

```<code>{for(n=2;l<$1;){if(n in L)p=L[n]
else{print p=n;l++}
for(N=p+n++;N in L;)N+=p
L[N]=p}}
</code>```

Run:

```<code>$ awk -f fsoe3.awk <<< 5
2
3
5
7
11
$ awk -f fsoe3.awk <<< 1000 | wc -l
1000
</code>```

BASH, 133 bytes

File x.bash:

```<code>a=2
while((l<$1));do if((b[a]))
then((c=b[a]));else((c=a,l++));echo $a;fi;((d=a+c))
while((b[d]));do((d+=c));done
((b[d]=c,a++));done
</code>```

Run:

```<code>$ bash x.bash 5
2
3
5
7
11
$ bash x.bash 1000 | wc -l
1000
</code>```

Primes get calculated by letting the already found primes jump on the "tape of positive integers". Basically it is a serialised Sieve Of Eratosthenes.

```<code>from time import time as t

L = {}
n = 2
l = 0

t0=t()

while l<1000000:

        if n in L:
                P = L[n]
        else:
                P = n
                l += 1
                print t()-t0

        m = n+P
        while m in L:
                m += P
        L[m] = P

        n += 1
</code>```

...is the same algorithm in Python and prints out the time when the l-th prime was found instead of the prime itself.

The output plotted with gnuplot yields the following:

The jumps probably have something to do with file i/o delays due to writing buffered data to disk...

Using much larger numbers of primes to find, will bring additional system dependent delays into the game, e.g. the array representing the "tape of positive integers" grows continuously and sooner or later will make every computer cry for more RAM (or later swap).

...so getting an idea of the complexity by looking at the experimental data does not really help a lot... :-(

Now counting the additions needed to find n primes:

```<code>cells = {}
current = 2
found = 0

additons = 0

while found < 10000000:

        if current in cells:
                candidate = cells[current]
                del cells[current] # the seen part is irrelevant
        else:
                candidate = current
                found += 1 ; additons += 1
                print additons

        destination = current + candidate ; additons += 1
        while destination in cells:
                destination += candidate ; additons += 1
        cells[destination] = candidate

        current += 1 ; additons += 1
</code>```

Title: List of first n prime numbers most efficiently and in shortest code

Body:
Rules are simple:

First n primes (not primes below n), should be printed to standard output separated by newlines (primes should be generated within the code)

primes cannot be generated by an inbuilt function or through a library, i.e. use of a inbuilt or library function such as, prime = get_nth_prime(n), is_a_prime(number), or factorlist = list_all_factors(number) won't be very creative.

Scoring - Say, we define Score = f([number of chars in the code]), O(f(n)) being the complexity of your algorithm where n is the number of primes it finds. So for example, if you have a 300 char code with O(n^2) complexity, score is 300^2 = 90000, for 300 chars with O(n*ln(n)), score becomes 300*5.7 = 1711.13 (let's assume all logs to be natural logs for simplicity)

Use any existing programming language, lowest score wins

Edit: Problem has been changed from finding 'first 1000000 primes' to 'first n primes' because of a confusion about what 'n' in O(f(n)) is, n is the number of primes you find (finding primes is the problem here and so complexity of the problem depends on the number of primes found)

Note: to clarify some confusions on complexity, if 'n' is the number of primes you find and 'N' is the nth prime found, complexity in terms of n is and N are not equivalent i.e. O(f(n)) != O(f(N)) as , f(N) != constant * f(n) and N != constant * n, because we know that nth prime function is not linear, I though since we were finding 'n' primes complexity should be easily expressible in terms of 'n'.

As pointed out by Kibbee, you can visit this site to verify your solutions (here, is the old google docs list)

Please Include these in your solution -

what complexity your program has (include basic analysis if not trivial)

character length of code

the final calculated score

This is my first CodeGolf Question so, if there is a mistake or loophole in above rules please do point them out.

Body:
AWK, <s>96</s> 86 bytes

Subtitle: Look Mom! Only adding and some bookkeeping!

File fsoe3.awk:

{for(n=2;l<$1;){if(n in L)p=L[n]
else{print p=n;l++}
for(N=p+n++;N in L;)N+=p
L[N]=p}}

Run:

$ awk -f fsoe3.awk <<< 5
2
3
5
7
11
$ awk -f fsoe3.awk <<< 1000 | wc -l
1000

BASH, 133 bytes

File x.bash:

a=2
while((l<$1));do if((b[a]))
then((c=b[a]));else((c=a,l++));echo $a;fi;((d=a+c))
while((b[d]));do((d+=c));done
((b[d]=c,a++));done

Run:

$ bash x.bash 5
2
3
5
7
11
$ bash x.bash 1000 | wc -l
1000

Primes get calculated by letting the already found primes jump on the "tape of positive integers". Basically it is a serialised Sieve Of Eratosthenes.

from time import time as t

L = {}
n = 2
l = 0

t0=t()

while l<1000000:

        if n in L:
                P = L[n]
        else:
                P = n
                l += 1
                print t()-t0

        m = n+P
        while m in L:
                m += P
        L[m] = P

        n += 1

...is the same algorithm in Python and prints out the time when the l-th prime was found instead of the prime itself.

The output plotted with gnuplot yields the following:

The jumps probably have something to do with file i/o delays due to writing buffered data to disk...

Using much larger numbers of primes to find, will bring additional system dependent delays into the game, e.g. the array representing the "tape of positive integers" grows continuously and sooner or later will make every computer cry for more RAM (or later swap).

...so getting an idea of the complexity by looking at the experimental data does not really help a lot... :-(

Now counting the additions needed to find n primes:

cells = {}
current = 2
found = 0

additons = 0

while found < 10000000:

        if current in cells:
                candidate = cells[current]
                del cells[current] # the seen part is irrelevant
        else:
                candidate = current
                found += 1 ; additons += 1
                print additons

        destination = current + candidate ; additons += 1
        while destination in cells:
                destination += candidate ; additons += 1
        cells[destination] = candidate

        current += 1 ; additons += 1


答:
Groovy (202 Bytes)

```<code>{a->b=new String[a][a];while(b.flatten().flatten().contains(null)){b[(int)(Math.random()*a)][(int)(Math.random()*a)]="XX";b.eachWithIndex{e,i->e.eachWithIndex{f,j->print f?"XX ":"${i}${j} "}println()}}}
</code>```

That specific output format really messed up my byte count, but meh.

Try it out: https://groovyconsole.appspot.com/edit/5171951567896576
(+9 bytes for a prettier print)

Ungolfed:

```<code>y={a->
    b=new String[a][a];
    while(b.flatten().flatten().contains(null)) {
        b[(int)(Math.random()*a)][(int)(Math.random()*a)]="XX";
        b.eachWithIndex{
            e,i->
            e.eachWithIndex{
                f,j->
                print f ? "XX ": "${i}${j} "
            }
            println()
        }
    }
}
y(4)
</code>```

Output Example:

```<code>00 01 02 XX
10 11 12 13
20 21 22 23
30 31 32 33
00 01 02 XX
XX 11 12 13
20 21 22 23
30 31 32 33
XX 01 02 XX
XX 11 12 13
20 21 22 23
30 31 32 33
XX 01 XX XX
XX 11 12 13
20 21 22 23
30 31 32 33
XX 01 XX XX
XX 11 12 XX
20 21 22 23
30 31 32 33
XX 01 XX XX
XX 11 12 XX
XX 21 22 23
30 31 32 33
XX 01 XX XX
XX 11 XX XX
XX 21 22 23
30 31 32 33
XX 01 XX XX
XX XX XX XX
XX 21 22 23
30 31 32 33
XX XX XX XX
XX XX XX XX
XX 21 22 23
30 31 32 33
XX XX XX XX
XX XX XX XX
XX 21 22 23
30 31 32 33
XX XX XX XX
XX XX XX XX
XX 21 22 23
XX 31 32 33
XX XX XX XX
XX XX XX XX
XX 21 22 23
XX 31 32 33
XX XX XX XX
XX XX XX XX
XX 21 22 23
XX 31 32 33
XX XX XX XX
XX XX XX XX
XX 21 22 23
XX 31 32 33
XX XX XX XX
XX XX XX XX
XX 21 22 23
XX 31 32 33
XX XX XX XX
XX XX XX XX
XX 21 22 23
XX 31 32 33
XX XX XX XX
XX XX XX XX
XX 21 22 23
XX 31 32 33
XX XX XX XX
XX XX XX XX
XX 21 22 23
XX 31 32 33
XX XX XX XX
XX XX XX XX
XX 21 22 XX
XX 31 32 33
XX XX XX XX
XX XX XX XX
XX 21 22 XX
XX 31 32 33
XX XX XX XX
XX XX XX XX
XX 21 22 XX
XX 31 32 33
XX XX XX XX
XX XX XX XX
XX 21 22 XX
XX 31 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX 31 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX 31 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX 31 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX 31 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX 31 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX 31 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX 31 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX 31 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX 31 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX 31 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX 31 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX XX XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX XX XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX XX XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX XX XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX XX XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX XX XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX XX XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX XX XX
XX XX XX XX
XX XX XX XX
XX XX XX XX
XX XX XX XX
</code>```

Title: Fill in the grid randomly

Body:
Given positive integer n < 10, create a 2 dimensional matrix where each location is filled with its x and y index (starting from the top left).

For example:

Input: 2

```<code>00 10
10 11
</code>```

Input: 3

```<code>00 10 20
01 11 21
02 12 22
</code>```

Once the grid is created, randomly fill each index. This can be with an 'x' or any other way to denote a spot has been filled.

You determine which location to fill by randomly generating indices to fill the matrix. You can only fill n^2 times so you cannot fill as many times as you want until the matrix is completely filled. At the end the matrix must be filled so you must do some work to make sure that you check the random numbers that you use to fill to make sure that spot is not already filled.

Refresh or print after each fill in order to show the progression of the filling iterations.

Example for filling:

Input: 2

```<code>00 10
01 11
</code>```

00 is randomly chosen:

```<code>XX 10
01 11
</code>```

01 is randomly chosen:

```<code>XX 10
XX 11
</code>```

00 is randomly chosen, but since it's already been chosen a re-roll chooses 10:

```<code>XX XX
XX 11
</code>```

11 is randomly chosen:

```<code>XX XX
XX XX
</code>```

Do not print out the random numbers as visually I should be able to see which index was selected. By this I mean do not print "11 is randomly chosen:". It is here for exploratory sake.

Since this is code-golf The shortest code wins.

Have fun and happy golfing!

Body:
Groovy (202 Bytes)

{a->b=new String[a][a];while(b.flatten().flatten().contains(null)){b[(int)(Math.random()*a)][(int)(Math.random()*a)]="XX";b.eachWithIndex{e,i->e.eachWithIndex{f,j->print f?"XX ":"${i}${j} "}println()}}}

That specific output format really messed up my byte count, but meh.

Try it out: https://groovyconsole.appspot.com/edit/5171951567896576
(+9 bytes for a prettier print)

Ungolfed:

y={a->
    b=new String[a][a];
    while(b.flatten().flatten().contains(null)) {
        b[(int)(Math.random()*a)][(int)(Math.random()*a)]="XX";
        b.eachWithIndex{
            e,i->
            e.eachWithIndex{
                f,j->
                print f ? "XX ": "${i}${j} "
            }
            println()
        }
    }
}
y(4)

Output Example:

00 01 02 XX
10 11 12 13
20 21 22 23
30 31 32 33
00 01 02 XX
XX 11 12 13
20 21 22 23
30 31 32 33
XX 01 02 XX
XX 11 12 13
20 21 22 23
30 31 32 33
XX 01 XX XX
XX 11 12 13
20 21 22 23
30 31 32 33
XX 01 XX XX
XX 11 12 XX
20 21 22 23
30 31 32 33
XX 01 XX XX
XX 11 12 XX
XX 21 22 23
30 31 32 33
XX 01 XX XX
XX 11 XX XX
XX 21 22 23
30 31 32 33
XX 01 XX XX
XX XX XX XX
XX 21 22 23
30 31 32 33
XX XX XX XX
XX XX XX XX
XX 21 22 23
30 31 32 33
XX XX XX XX
XX XX XX XX
XX 21 22 23
30 31 32 33
XX XX XX XX
XX XX XX XX
XX 21 22 23
XX 31 32 33
XX XX XX XX
XX XX XX XX
XX 21 22 23
XX 31 32 33
XX XX XX XX
XX XX XX XX
XX 21 22 23
XX 31 32 33
XX XX XX XX
XX XX XX XX
XX 21 22 23
XX 31 32 33
XX XX XX XX
XX XX XX XX
XX 21 22 23
XX 31 32 33
XX XX XX XX
XX XX XX XX
XX 21 22 23
XX 31 32 33
XX XX XX XX
XX XX XX XX
XX 21 22 23
XX 31 32 33
XX XX XX XX
XX XX XX XX
XX 21 22 23
XX 31 32 33
XX XX XX XX
XX XX XX XX
XX 21 22 XX
XX 31 32 33
XX XX XX XX
XX XX XX XX
XX 21 22 XX
XX 31 32 33
XX XX XX XX
XX XX XX XX
XX 21 22 XX
XX 31 32 33
XX XX XX XX
XX XX XX XX
XX 21 22 XX
XX 31 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX 31 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX 31 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX 31 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX 31 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX 31 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX 31 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX 31 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX 31 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX 31 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX 31 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX 31 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX 32 XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX XX XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX XX XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX XX XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX XX XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX XX XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX XX XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX XX XX
XX XX XX XX
XX XX XX XX
XX XX 22 XX
XX XX XX XX
XX XX XX XX
XX XX XX XX
XX XX XX XX
XX XX XX XX


答:
Pip, <s>41</s> <s>40</s> <s>38</s> 36 bytes

35 bytes of code, +1 for the -S flag.

```<code>Pm:J_MM ZCGa{ST:mmR:asX2}M$ALmSK{r}
</code>```

Takes input from cmdline argument. Replaces with space (any other character is possible for +1 byte). Outputs successive iterations separated by a single newline (which is legal but can make it a bit hard to read). Try it online!

<s>All kinds of dirty tricks in this one.</s> Shorter version has fewer dirty tricks. :^( Explanation:

```<code>Pm:J_MM ZCGa{ST:mmR:asX2}M$ALmSK{r}
                                     -S flag means nested lists are delimited first
                                       by newlines then by spaces when stringified/printed
           a                         1st cmdline arg
         CG                          Coordinate Grid, a list of lists of coord pairs
        Z                            Zip (transposes so it's x,y instead of row,col)
   J_                                Function that takes a list and joins all items
     MM                              MapMap: map this function to each sublist
                                       This joins a coord pair [1;0] into a string "10"
 Pm:                                 Assign the result to m and print it

                          $ALm       Fold m on Append List: appends all sublists of m
                                       together, making a single list of coord pairs
                              SK     Sort with the following function as key:
                                {r}  Return a random number
                                     We now have a randomly-ordered list of all the
                                       coord pairs from m

            {           }M           Map this function to that list:
             ST:m                    Convert m to string in-place
                 mR:                 Replace (in-place)...
                    a                  the argument (a coord pair)...
                     sX2               ... with two spaces
                                     The map operation returns a list of strings, one for
                                       each step of the process, which are autoprinted
                                       (separated by newlines)
</code>```

Title: Fill in the grid randomly

Body:
Pip, <s>41</s> <s>40</s> <s>38</s> 36 bytes

35 bytes of code, +1 for the -S flag.

Pm:J_MM ZCGa{ST:mmR:asX2}M$ALmSK{r}

Takes input from cmdline argument. Replaces with space (any other character is possible for +1 byte). Outputs successive iterations separated by a single newline (which is legal but can make it a bit hard to read). Try it online!

<s>All kinds of dirty tricks in this one.</s> Shorter version has fewer dirty tricks. :^( Explanation:

Pm:J_MM ZCGa{ST:mmR:asX2}M$ALmSK{r}
                                     -S flag means nested lists are delimited first
                                       by newlines then by spaces when stringified/printed
           a                         1st cmdline arg
         CG                          Coordinate Grid, a list of lists of coord pairs
        Z                            Zip (transposes so it's x,y instead of row,col)
   J_                                Function that takes a list and joins all items
     MM                              MapMap: map this function to each sublist
                                       This joins a coord pair [1;0] into a string "10"
 Pm:                                 Assign the result to m and print it

                          $ALm       Fold m on Append List: appends all sublists of m
                                       together, making a single list of coord pairs
                              SK     Sort with the following function as key:
                                {r}  Return a random number
                                     We now have a randomly-ordered list of all the
                                       coord pairs from m

            {           }M           Map this function to that list:
             ST:m                    Convert m to string in-place
                 mR:                 Replace (in-place)...
                    a                  the argument (a coord pair)...
                     sX2               ... with two spaces
                                     The map operation returns a list of strings, one for
                                       each step of the process, which are autoprinted
                                       (separated by newlines)


答:
Ada

```<code>test.adb:1:01: compilation unit expected
</code>```

Really just make an ada file, toss it at the start as above and compile with gcc filename.adb -c.

Title: Make an error quine!

Body:
Your challenge: write a "program", for a language of your choice, that causes the compiler/interpreter/runtime to produce error output when compiling/running your program which is identical to your program's source code.

Rules:

Your program may be specific to a particular version or implementation of your language's compiler/interpreter/runtime environment. If so, please specify the particulars.

Only standard compiler/interpreter/runtime options are permitted. You cannot pass some weird flag to your compiler to get a specific result.

The program does not need to be syntactically or semantically valid, but I may give a bounty to the best syntactically valid submission.

The program must not produce any output of its own (e.g. by calling a print or output function). All output generated upon attempting to compile/run the program must originate from the compiler/interpreter/runtime.

The complete output of the compiler/interpreter/runtime must be exactly identical to your program source code.

The compiler/interpreter/runtime must generate at least one error message when invoked with your program.

This is a popularity contest. Most creative answer, as determined by upvotes, wins. If you can give a good case for using a standard loophole, you may do so.

Body:
Ada

test.adb:1:01: compilation unit expected

Really just make an ada file, toss it at the start as above and compile with gcc filename.adb -c.


答:
Ruby, 50 bytes

```<code>->n{a=n;while(s=a.to_s;s!=s.reverse)do a+=n;end;a}
</code>```

It's horrible, I know.

Title: Smallest palindrome divisible by the input

Body:
Given a positive integer N, output the smallest positive integer such that this number is a palindrome (i.e. is its own reverse) and is divisible by N.

The palindrome (i.e. the output) must not need a leading zero to be a palindrome, e.g. 080 is not the valid answer for 16.

The input will never be a multiple of 10, because of the previous reason.

Your program may take as much time as necessary, even if in practice it would be way too long to output the answer.

Inputs and outputs

You may take the input through STDIN, as a function argument, or anything similar.

You may print the output to STDOUT, return it from a function, or anything similar.

Inputs and outputs must be in the decimal base.

Test cases

```<code>N        Output
1        1
2        2
16       272
17       272
42       252
111      111
302      87278
1234     28382
</code>```

Scoring

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

Body:
Ruby, 50 bytes

->n{a=n;while(s=a.to_s;s!=s.reverse)do a+=n;end;a}

It's horrible, I know.


答:
JavaScript, 40 bytes

```<code>f=v=>v&&v[0].repeat(v[1])+f(v.slice(2))
</code>```

Recursive.  Expand first 2 characters and call self with remainder of string.

Title: Run Length Decoding

Body:
Write the shortest code in the language of your choice to perform run length decoding of the given string.

The string will be supplied as input on stdin in the form

```<code>CNCNCNCNCNCNCNCN
</code>```

where each C could be any printable ASCII character and each N is a digit 1 to 9 (inclusive).

Sample input:

```<code>:144,1'1
</code>```

Corresponding output:

```<code>:4444,'
</code>```

Body:
JavaScript, 40 bytes

f=v=>v&&v[0].repeat(v[1])+f(v.slice(2))

Recursive.  Expand first 2 characters and call self with remainder of string.


答:
AWK, 229 bytes

```<code>func p(a){for(k=1;k<=m;k++){if(k==a)gsub("[0-9]","X",M[k])
printf"%s",M[k]}}{n=$1;m=n*n
k=1
for(i=0;i<n;i++)for(j=0;j<n;j++){s=k%n==0?k==m?"\n\n":"\n":" "
M[k++]=i j s}p()
for(;z<m;z++){do{y=int(rand()*m+1)}while(M[y]~"X")p(y)}}
</code>```

I added a few bytes to give the output a space between each matrix.

Note: to make it more 'random' between runs, a call to srand() could be added for 7 additional bytes.

Usage and output after storing above code in FILE:

```<code>    awk -f FILE <<< 2

00 01
10 11

XX 01
10 11

XX XX
10 11

XX XX
10 XX

XX XX
XX XX
</code>```

Title: Fill in the grid randomly

Body:
AWK, 229 bytes

func p(a){for(k=1;k<=m;k++){if(k==a)gsub("[0-9]","X",M[k])
printf"%s",M[k]}}{n=$1;m=n*n
k=1
for(i=0;i<n;i++)for(j=0;j<n;j++){s=k%n==0?k==m?"\n\n":"\n":" "
M[k++]=i j s}p()
for(;z<m;z++){do{y=int(rand()*m+1)}while(M[y]~"X")p(y)}}

I added a few bytes to give the output a space between each matrix.

Note: to make it more 'random' between runs, a call to srand() could be added for 7 additional bytes.

Usage and output after storing above code in FILE:

    awk -f FILE <<< 2

00 01
10 11

XX 01
10 11

XX XX
10 11

XX XX
10 XX

XX XX
XX XX


答:
PHP, 172 Bytes

```<code>for(;$x<$s=($a=$argv[1])*$a;)$r[]=$x%$a.($x++/$a^0);echo($c=chunk_split)(join(" ",$r),$a*3);for(;$q<$s;){if($r[$z=rand(0,$s-1)]<X)++$q&$r[$z]=XX;echo$c(join(" ",$r),$a*3);}
</code>```

Breakdown

```<code>for(;$x<$s=($a=$argv[1])*$a;)$r[]=$x%$a.($x++/$a^0); #make the array
echo($c=chunk_split)(join(" ",$r),$a*3); # Output array
for(;$q<$s;)
{
  if($r[$z=rand(0,$s-1)]<X)++$q&$r[$z]=XX; #fill position if it is not XX and raise increment
  echo$c(join(" ",$r),$a*3); #Output array
}
</code>```

Title: Fill in the grid randomly

Body:
PHP, 172 Bytes

for(;$x<$s=($a=$argv[1])*$a;)$r[]=$x%$a.($x++/$a^0);echo($c=chunk_split)(join(" ",$r),$a*3);for(;$q<$s;){if($r[$z=rand(0,$s-1)]<X)++$q&$r[$z]=XX;echo$c(join(" ",$r),$a*3);}

Breakdown

for(;$x<$s=($a=$argv[1])*$a;)$r[]=$x%$a.($x++/$a^0); #make the array
echo($c=chunk_split)(join(" ",$r),$a*3); # Output array
for(;$q<$s;)
{
  if($r[$z=rand(0,$s-1)]<X)++$q&$r[$z]=XX; #fill position if it is not XX and raise increment
  echo$c(join(" ",$r),$a*3); #Output array
}


Title: Fill in the grid randomly

Body:
R, <s>84</s> <s>81</s> 74 bytes

Now uses one-indexing rather than zero-indexing. Got rid of 7 bytes thanks to @Billywob.

N=scan()
m=outer(1:N,1:N,paste0)
for(i in sample(N^2)){m[i]="XX";print(m)}

Example output for N=3

     [,1] [,2] [,3]
[1,] "11" "12" "XX"
[2,] "21" "22" "23"
[3,] "31" "32" "33"
     [,1] [,2] [,3]
[1,] "11" "12" "XX"
[2,] "21" "22" "23"
[3,] "31" "XX" "33"
     [,1] [,2] [,3]
[1,] "11" "12" "XX"
[2,] "XX" "22" "23"
[3,] "31" "XX" "33"
     [,1] [,2] [,3]
[1,] "11" "XX" "XX"
[2,] "XX" "22" "23"
[3,] "31" "XX" "33"
     [,1] [,2] [,3]
[1,] "XX" "XX" "XX"
[2,] "XX" "22" "23"
[3,] "31" "XX" "33"
     [,1] [,2] [,3]
[1,] "XX" "XX" "XX"
[2,] "XX" "22" "23"
[3,] "XX" "XX" "33"
     [,1] [,2] [,3]
[1,] "XX" "XX" "XX"
[2,] "XX" "XX" "23"
[3,] "XX" "XX" "33"
     [,1] [,2] [,3]
[1,] "XX" "XX" "XX"
[2,] "XX" "XX" "XX"
[3,] "XX" "XX" "33"
     [,1] [,2] [,3]
[1,] "XX" "XX" "XX"
[2,] "XX" "XX" "XX"
[3,] "XX" "XX" "XX"


问:
Division of not so little numbers
Write a program or function that takes in positive integers a, b and c, and prints or returns a/b to c decimal places, using the operations +-*/% [add, subtract, multiply, divide, modulate] on the positive integers: you can use all that your language allows, but not on floating point numbers. The range of a,b,c would be the range allowed for unsigned integers in your language.
The number result will be truncated to the last digit to print (so no round).

This means that if your language does not have an integer type (only float), you can participate by using these float numbers as positive integers only.
The clue of this exercise it would be to write the function that find the
digits in a float point division, using only the operation +-*/%  on
[unsigned] integers.

Examples

print(1,2,1) would print 0.5

print(1,2,2) would print 0.50

print(13,7,27) would print 1.857142857142857142857142857

print(2,3,1) would print 0.6

print(4,5,7) would print 0.8000000

print(4,5,1) would print 0.8

print(9999,23,1) would print 434.7

print(12345613,2321,89) would print if your Language has 32 bit unsigned 5319.09220163722533390779836277466609220163722533390779836277466609220163722533390779836277466

The shortest code in bytes wins. I'm sorry if this appear not clear... I don't know languages too, not remember words well...
It is better to have one link to Ideone.com or some other place for easily try the answer especially for to test some input different from proposed.

答:
Pyth - <s>21</s> <s>19</s> <s>18</s> <s>16</s> 14 bytes

Will be looking over the input format, that can prolly save a bunch.

```<code>j\.c`/*E^TQE]_
</code>```

Test Suite. (P.S. the 27 one doesn't finish online, so I did 10 instead).

Title: Division of not so little numbers

Body:
Pyth - <s>21</s> <s>19</s> <s>18</s> <s>16</s> 14 bytes

Will be looking over the input format, that can prolly save a bunch.

j\.c`/*E^TQE]_

Test Suite. (P.S. the 27 one doesn't finish online, so I did 10 instead).


答:
Haskell, 87 bytes

```<code>(a#b)c|s<-show$div(a*10^c)b,l<-length s-c,(h,t)<-splitAt l s=['0'|l<1]++h++['.'|c>0]++t
</code>```

Usage example: (13#7)27 -> "1.857142857142857142857142857".

23 bytes to handle the c==0 case and using a leading zero instead of things like .5.

How it works: multiply a with 10^c, divide by b, turn into a string, split where the . must be inserted, join both parts with a . in-between and fix the edge cases.

Title: Division of not so little numbers

Body:
Write a program or function that takes in positive integers a, b and c, and prints or returns a/b to c decimal places, using the operations +-*/% [add, subtract, multiply, divide, modulate] on the positive integers: you can use all that your language allows, but not on floating point numbers. The range of a,b,c would be the range allowed for unsigned integers in your language.
The number result will be truncated to the last digit to print (so no round).

This means that if your language does not have an integer type (only float), you can participate by using these float numbers as positive integers only.
The clue of this exercise it would be to write the function that find the
digits in a float point division, using only the operation +-*/%  on
[unsigned] integers.

Examples

print(1,2,1) would print 0.5

print(1,2,2) would print 0.50

print(13,7,27) would print 1.857142857142857142857142857

print(2,3,1) would print 0.6

print(4,5,7) would print 0.8000000

print(4,5,1) would print 0.8

print(9999,23,1) would print 434.7

print(12345613,2321,89) would print if your Language has 32 bit unsigned 5319.09220163722533390779836277466609220163722533390779836277466609220163722533390779836277466

The shortest code in bytes wins. I'm sorry if this appear not clear... I don't know languages too, not remember words well...
It is better to have one link to Ideone.com or some other place for easily try the answer especially for to test some input different from proposed.

Body:
Haskell, 87 bytes

(a#b)c|s<-show$div(a*10^c)b,l<-length s-c,(h,t)<-splitAt l s=['0'|l<1]++h++['.'|c>0]++t

Usage example: (13#7)27 -> "1.857142857142857142857142857".

23 bytes to handle the c==0 case and using a leading zero instead of things like .5.

How it works: multiply a with 10^c, divide by b, turn into a string, split where the . must be inserted, join both parts with a . in-between and fix the edge cases.


答:
PHP, 187 Bytes

works with strings for the numerator which can be int values greater then PHP_INT_MAX

```<code>list(,$n,$d,$c)=$argv;$a=str_split($n);while($a){$n.=array_shift($a);if($n>=$d||$r)$n-=$d*$r[]=$n/$d^0;}if(!$r)$r[]=0;if($c)$r[]=".";while($c--){$n*=10;$n-=$d*$r[]=$n/$d^0;}echo join($r);
</code>```

I have no other chance then 13/7 is shorten to 1.8571428571429 and I reach so not the test case with 27 decimal places

This way 36 Bytes is not allowed

```<code><?=bcdiv(($z=$argv)[1],$z[2],$z[3]);
</code>```

Title: Division of not so little numbers

Body:
PHP, 187 Bytes

works with strings for the numerator which can be int values greater then PHP_INT_MAX

list(,$n,$d,$c)=$argv;$a=str_split($n);while($a){$n.=array_shift($a);if($n>=$d||$r)$n-=$d*$r[]=$n/$d^0;}if(!$r)$r[]=0;if($c)$r[]=".";while($c--){$n*=10;$n-=$d*$r[]=$n/$d^0;}echo join($r);

I have no other chance then 13/7 is shorten to 1.8571428571429 and I reach so not the test case with 27 decimal places

This way 36 Bytes is not allowed

<?=bcdiv(($z=$argv)[1],$z[2],$z[3]);


答:
FreeMarker+HTML/CSS, 46 + 468 = 514 bytes

HTML:

```<code><div><div></div><div></div><span></span></div>
</code>```

CSS:

```<code>div div,div span{position:absolute}div{width:10px;height:10px;box-sizing:border-box;transform-origin:top left;position:relative;transform:scale(${n*.1})}div div{border:2px solid;border-radius:9px;border-color:transparent #4285f4 transparent transparent;transform:rotate(33.4630409671deg);transform-origin:center}div div+div{border-color:#ea4335 transparent #34a853 #fbbc05;transform:none}div span{display:block;top:4px;bottom:4px;left:5px;right:.1px;background:#4285f4}
</code>```

Assuming the FreeMarker processor is executed with a variable n set, representing input.

Explanation of magic numbers:

Everything is based on a 10x10px wrapper, then scaled by n/10.

Distance to right of blue horizontal box [px]: 5 - sqrt(5^2 - 1^2) = 0.10102051443 (Pythagoras)

Rotation of blue arc [deg]: 45 - arcSin(1/5) = 33.4630409671 (Sine)

Ungolfed JSFiddle

Body:
Write a program or function that takes in a positive integer N, and outputs an N×N pixel image of Google's "G" logo according to this* construction:

For example, if N is 400, a 400×400 pixel logo should be output, with correct dimensions and colors:

It should look accurate regardless of how large or small N is. e.g. here is N = 13:

Your code should not need to connect to the internet. For example, scaling an externally hosted svg is not allowed. (Scaling an svg encoded in your code would be fine though.)

Anti-aliasing may be used or not. It's up to you.

Notice that the horizontal bar of the "G" does not extend all the way to the right edge of the image. The circle curves normally inward on the right edge before it is cut off.

The shortest code in bytes wins.

* The construction of the logo has been simplified for this challenge. The correct construction can be seen here and here.

Body:
FreeMarker+HTML/CSS, 46 + 468 = 514 bytes

HTML:

<div><div></div><div></div><span></span></div>

CSS:

div div,div span{position:absolute}div{width:10px;height:10px;box-sizing:border-box;transform-origin:top left;position:relative;transform:scale(${n*.1})}div div{border:2px solid;border-radius:9px;border-color:transparent #4285f4 transparent transparent;transform:rotate(33.4630409671deg);transform-origin:center}div div+div{border-color:#ea4335 transparent #34a853 #fbbc05;transform:none}div span{display:block;top:4px;bottom:4px;left:5px;right:.1px;background:#4285f4}

Assuming the FreeMarker processor is executed with a variable n set, representing input.

Explanation of magic numbers:

Everything is based on a 10x10px wrapper, then scaled by n/10.

Distance to right of blue horizontal box [px]: 5 - sqrt(5^2 - 1^2) = 0.10102051443 (Pythagoras)

Rotation of blue arc [deg]: 45 - arcSin(1/5) = 33.4630409671 (Sine)

Ungolfed JSFiddle


答:
<s>JS/</s>CSS/HTML(+JS), <s>40</s> 0 + <s>701</s> <s>644</s> <s>617</s> 593 + <s>173</s> <s>90</s> <s>97 121 = <s>914</s> <s>774</s> <s>754</s> 730</s> 714 bytes

*{position:absolute}a,h{height:100%;background:#4285F4}a,g{width:100%;border-radius:100%}h{width:30%;height:20%;top:40%}b,c,d,e,f{width:50%;height:50%}b,d,f,h{left:50%}e,f{top:50%}c{border-radius:100% 0 0;background:linear-gradient(45deg,#FBBC05 50%,#EA4335 50%)}d{border-radius:0 100% 0 0;background:linear-gradient(-45deg,transparent 50%,#EA4335 50%)}e{border-radius:0 0 0 100%;background:linear-gradient(-45deg,#34A853 50%,#FBBC05 50%)}f{border-radius:0 0 100%;background:linear-gradient(45deg,#34A853 50%,#4285F4 50%)}b,g{height:40%;background:#FFF}g{width:60%;height:60%;top:20%;left:20%}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input oninput=with(o.style)height=width=value+"px"><o id=o><a></a><b></b><c></c><d></d><e></e><f></f><g></g><h></h></o></code>```

Uses linear gradients rather than transforms. Edit: Saved 140 bytes thanks to @darrylyeo. Saved 20 bytes by using an extra element instead of a gradient. Saved 24 bytes thanks to @DBS. Saved 16 bytes thanks to @Hedi. From back to front, the various layers are:

a The blue circle

b A white rectangle to obscure the part above the bar

c The red/yellow top left quarter

d The red octant top right

e The yellow/green bottom left quarter

f The green/blue bottom right quarter

g The inner white circle

h The horizontal blue bar

JavaScript (ES6) (+SVG), 293 bytes, invalid

document.write(`<svg id=o width=${prompt()} viewbox=0,0,50,50>`);m=`39,11`;`#EA433511,11
#FBBC0511,39
#34A85339,39
#4285F445,25L25,25`.replace(/(.{7})(.{5})(.*)/g,(_,s,t,u)=>m=document.write(`<path stroke=${s} d=M${m}A20,20,0,0,0,${t+u} fill=none stroke-width=10 stroke-linejoin=round />`)||t)```

Sadly the round line join isn't quite the requested effect, but it's pretty close.

Body:
<s>JS/</s>CSS/HTML(+JS), <s>40</s> 0 + <s>701</s> <s>644</s> <s>617</s> 593 + <s>173</s> <s>90</s> <s>97 121 = <s>914</s> <s>774</s> <s>754</s> 730</s> 714 bytes

*{position:absolute}a,h{height:100%;background:#4285F4}a,g{width:100%;border-radius:100%}h{width:30%;height:20%;top:40%}b,c,d,e,f{width:50%;height:50%}b,d,f,h{left:50%}e,f{top:50%}c{border-radius:100% 0 0;background:linear-gradient(45deg,#FBBC05 50%,#EA4335 50%)}d{border-radius:0 100% 0 0;background:linear-gradient(-45deg,transparent 50%,#EA4335 50%)}e{border-radius:0 0 0 100%;background:linear-gradient(-45deg,#34A853 50%,#FBBC05 50%)}f{border-radius:0 0 100%;background:linear-gradient(45deg,#34A853 50%,#4285F4 50%)}b,g{height:40%;background:#FFF}g{width:60%;height:60%;top:20%;left:20%}

<input oninput=with(o.style)height=width=value+"px"><o id=o><a></a><b></b><c></c><d></d><e></e><f></f><g></g><h></h></o>

Uses linear gradients rather than transforms. Edit: Saved 140 bytes thanks to @darrylyeo. Saved 20 bytes by using an extra element instead of a gradient. Saved 24 bytes thanks to @DBS. Saved 16 bytes thanks to @Hedi. From back to front, the various layers are:

a The blue circle

b A white rectangle to obscure the part above the bar

c The red/yellow top left quarter

d The red octant top right

e The yellow/green bottom left quarter

f The green/blue bottom right quarter

g The inner white circle

h The horizontal blue bar

JavaScript (ES6) (+SVG), 293 bytes, invalid

document.write(`<svg id=o width=${prompt()} viewbox=0,0,50,50>`);m=`39,11`;`#EA433511,11
#FBBC0511,39
#34A85339,39
#4285F445,25L25,25`.replace(/(.{7})(.{5})(.*)/g,(_,s,t,u)=>m=document.write(`<path stroke=${s} d=M${m}A20,20,0,0,0,${t+u} fill=none stroke-width=10 stroke-linejoin=round />`)||t)

Sadly the round line join isn't quite the requested effect, but it's pretty close.


答:
BBC BASIC, 177 bytes

Download interpreter at http://www.bbcbasic.co.uk/bbcwin/download.html

```<code>I.n
V.19;16,234,67,53,275;64272;1468;531;16,43060;83,787;16,34114;7668;n;n;
F.t=1TO8.256S.1/n
a=t*PI/4y=n*SIN(a)x=n*COS(a)V.18;t-1>>1,25,85,x*.6;y*.6;25,85,x;y;
N.PLOT101,0,-n/5
</code>```

BBC BASIC uses 2 units=1 pixel, so we plot a G of radius n units (=n/2 pixels) at centre n,n.

The idea is to plot a series of radial lines, changing colour as appropriate. It was found that there were small gaps between the lines due to truncation of the numbers when converted to pixels, so thin triangles are actually plotted instead.

Once the sweep of lines is completed, the cursor is at the top right corner of the blue area. A single coordinate for the diagonally opposite corner is given to draw a rectangle in order to complete the shape.

Ungolfed

```<code>INPUTn
REM reprogram pallette
VDU19;16,&EA,&43,&35,275;16,&FB,&BC,5,531;16,&34,&A8,&53,787;16,&42,&85,&F4
ORIGINn,n               :REM move origin to position n,n on screen.
FORt=1TO8.256STEP1/n    :REM from 1/8 turn to 8.56 turns in small steps
  GCOL0,t-1>>1          :REM set the colours, 0=red, 1=yellow, 2=green, 3=blue
  a=t*PI/4              :REM convert angle from 1/8 turns into radians
  y=n*SIN(a)            :REM find position of outer end of ray
  x=n*COS(a)            :REM plot to coordinates of inner and outer ends of ray
  PLOT85,x*.6,y*.6      :REM PLOT85 actually draws a triangle between the specified point
  PLOT85,x,y            :REM and the last two points visited.
NEXT
PLOT101,0,-n/5          :REM once all is over, cursor is at top right corner of blue rectangle. Draw a rectangle to the bottom left corner as specified.
</code>```

Body:
BBC BASIC, 177 bytes

Download interpreter at http://www.bbcbasic.co.uk/bbcwin/download.html

I.n
V.19;16,234,67,53,275;64272;1468;531;16,43060;83,787;16,34114;7668;n;n;
F.t=1TO8.256S.1/n
a=t*PI/4y=n*SIN(a)x=n*COS(a)V.18;t-1>>1,25,85,x*.6;y*.6;25,85,x;y;
N.PLOT101,0,-n/5

BBC BASIC uses 2 units=1 pixel, so we plot a G of radius n units (=n/2 pixels) at centre n,n.

The idea is to plot a series of radial lines, changing colour as appropriate. It was found that there were small gaps between the lines due to truncation of the numbers when converted to pixels, so thin triangles are actually plotted instead.

Once the sweep of lines is completed, the cursor is at the top right corner of the blue area. A single coordinate for the diagonally opposite corner is given to draw a rectangle in order to complete the shape.

Ungolfed

INPUTn
REM reprogram pallette
VDU19;16,&EA,&43,&35,275;16,&FB,&BC,5,531;16,&34,&A8,&53,787;16,&42,&85,&F4
ORIGINn,n               :REM move origin to position n,n on screen.
FORt=1TO8.256STEP1/n    :REM from 1/8 turn to 8.56 turns in small steps
  GCOL0,t-1>>1          :REM set the colours, 0=red, 1=yellow, 2=green, 3=blue
  a=t*PI/4              :REM convert angle from 1/8 turns into radians
  y=n*SIN(a)            :REM find position of outer end of ray
  x=n*COS(a)            :REM plot to coordinates of inner and outer ends of ray
  PLOT85,x*.6,y*.6      :REM PLOT85 actually draws a triangle between the specified point
  PLOT85,x,y            :REM and the last two points visited.
NEXT
PLOT101,0,-n/5          :REM once all is over, cursor is at top right corner of blue rectangle. Draw a rectangle to the bottom left corner as specified.


答:
Perl, 55 bytes

Includes +3 for -p

Give a and b on one line on STDIN, c on the next

```<code>division.pl
1 26
38
^D
</code>```

division.pl:

```<code>#!/usr/bin/perl -p
eval'$\.=($_/$&|0)."."x!$\;$_=$_%$&.0;'x(/ .*/+<>)}{
</code>```

the $_/$& is a bit arguable. I Actually want an integer division there but perl doesn't have that without loading special modules. So it's temporarily a non-integer which I then immediately truncate (using |0) so I end up with the integer an integer division would give. It could be rewritten as ($_-$_%$&)/$& in order to not even temporarily have a non-integer value (it would internally still be a float though)

Title: Division of not so little numbers

Body:
Perl, 55 bytes

Includes +3 for -p

Give a and b on one line on STDIN, c on the next

division.pl
1 26
38
^D

division.pl:

#!/usr/bin/perl -p
eval'$\.=($_/$&|0)."."x!$\;$_=$_%$&.0;'x(/ .*/+<>)}{

the $_/$& is a bit arguable. I Actually want an integer division there but perl doesn't have that without loading special modules. So it's temporarily a non-integer which I then immediately truncate (using |0) so I end up with the integer an integer division would give. It could be rewritten as ($_-$_%$&)/$& in order to not even temporarily have a non-integer value (it would internally still be a float though)


答:
Python 2, 190 bytes

from random import *
R=range(input())
G=[(x,y)for x in R for y in R]
def f():print"\n".join(" ".join(["XX","%d%d"%(x,y)][(x,y) in G]for x in R)for y in R)
f()
while G:G.remove(choice(G));f()
```

Title: Fill in the grid randomly

Body:
Given positive integer n < 10, create a 2 dimensional matrix where each location is filled with its x and y index (starting from the top left).

For example:

Input: 2

```<code>00 10
10 11
</code>```

Input: 3

```<code>00 10 20
01 11 21
02 12 22
</code>```

Once the grid is created, randomly fill each index. This can be with an 'x' or any other way to denote a spot has been filled.

You determine which location to fill by randomly generating indices to fill the matrix. You can only fill n^2 times so you cannot fill as many times as you want until the matrix is completely filled. At the end the matrix must be filled so you must do some work to make sure that you check the random numbers that you use to fill to make sure that spot is not already filled.

Refresh or print after each fill in order to show the progression of the filling iterations.

Example for filling:

Input: 2

```<code>00 10
01 11
</code>```

00 is randomly chosen:

```<code>XX 10
01 11
</code>```

01 is randomly chosen:

```<code>XX 10
XX 11
</code>```

00 is randomly chosen, but since it's already been chosen a re-roll chooses 10:

```<code>XX XX
XX 11
</code>```

11 is randomly chosen:

```<code>XX XX
XX XX
</code>```

Do not print out the random numbers as visually I should be able to see which index was selected. By this I mean do not print "11 is randomly chosen:". It is here for exploratory sake.

Since this is code-golf The shortest code wins.

Have fun and happy golfing!


答:
RProgN, 55 Bytes

```<code>S y = '' x = y L ¿ y pop y pop \ rep x . 'x' = y L } x
</code>```

Explained

```<code>S y =               # Convert the input to a backwards stack, assign it to y.
'' x =              # Assign a blank string to x
y L                 # Push the length of y
¿                   # While the top of the stack is truthy, popping.
    y pop           # Push the top value of y to the stack.
    y pop           # Twice.
    \               # Swap them around, so we get C 1 instead of 1 C
    rep             # Repeat the string. (C 1 times in the above example)
    x . 'x' =       # Append it to the back of x, and re-assign it. We use the back because we're starting at the END of the string.
    y L             # Push the length of y for the next itteration of the loop.
}                   #
x                   # Push x, and implicitly print it.
</code>```

Try it Online!

Title: Run Length Decoding

Body:
RProgN, 55 Bytes

S y = '' x = y L ¿ y pop y pop \ rep x . 'x' = y L } x

Explained

S y =               # Convert the input to a backwards stack, assign it to y.
'' x =              # Assign a blank string to x
y L                 # Push the length of y
¿                   # While the top of the stack is truthy, popping.
    y pop           # Push the top value of y to the stack.
    y pop           # Twice.
    \               # Swap them around, so we get C 1 instead of 1 C
    rep             # Repeat the string. (C 1 times in the above example)
    x . 'x' =       # Append it to the back of x, and re-assign it. We use the back because we're starting at the END of the string.
    y L             # Push the length of y for the next itteration of the loop.
}                   #
x                   # Push x, and implicitly print it.

Try it Online!


答:
JavaScript (ES6), <s> 64 </s> <s>62</s> 59 bytes

Saved 2 bytes thanks to ETHproductions.

The included division always results in an integer.

f=(a,b,n,s)=>~n?f((q=(a-a%b)/b,a%b*10),b,n-1,s?s+q:q+'.'):s

console.log(f(13,7,27))```

Title: Division of not so little numbers


问:
Square, diamond, square, diamond

Task

Given a non-empty string of lowercase ASCII letters a-z, take its first character, and:

Surround it with a square of copies of the second character,

Surround that with a diamond of copies of the third character,

Surround that with a square of copies of the fourth character…

…alternating between square and diamond borders until the end of the string. Empty space between the borders should be represented by ASCII spaces ().

To add a square border, draw a square exactly around the entire current “working array”:

```<code>                                               sssssssssss
                                t              s    t    s
                               t t             s   t t   s
                              t   t            s  t   t  s
                             t aaa t           s t aaa t s
                            t  aca  t    =>    st  aca  ts
                             t aaa t           s t aaa t s
                              t   t            s  t   t  s
                               t t             s   t t   s
                                t              s    t    s
                                               sssssssssss
</code>```

To add a diamond border, draw a centered diamond shape that touches the outermost square diagonally, but not orthogonally:

```<code>                                                     s
                                                    s s
                                                   s   s
                                                  s     s
                                                 s       s
                                                s         s
                                               s           s
                    wwwwwwwwwww               s wwwwwwwwwww s
                    w    o    w              s  w    o    w  s
                    w   o o   w             s   w   o o   w   s
                    w  o   o  w            s    w  o   o  w    s
                    w o eee o w           s     w o eee o w     s
                    wo  eme  ow    =>    s      wo  eme  ow      s
                    w o eee o w           s     w o eee o w     s
                    w  o   o  w            s    w  o   o  w    s
                    w   o o   w             s   w   o o   w   s
                    w    o    w              s  w    o    w  s
                    wwwwwwwwwww               s wwwwwwwwwww s
                                               s           s
                                                s         s
                                                 s       s
                                                  s     s
                                                   s   s
                                                    s s
                                                     s
</code>```

Your program must output the final array.

Each line may contain any amount of trailing spaces.

You may output a list of strings representing lines, or a single newline-separated string with an optional trailing newline.

Leading/trailing blank lines are disallowed.

Leading columns of spaces are also disallowed.

This is code-golf. The shortest code in bytes wins.

Test cases

The above examples are expected outputs for cat, cats, meow, and meows, in reading order. Some other cases worth handling:

For the input a, your program should output:

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

For the input ab, your program should output:

```<code>bbb
bab
bbb
</code>```

For the input codegolf, your program should output:

```<code>fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
f                            l                            f
f                           l l                           f
f                          l   l                          f
f                         l     l                         f
f                        l       l                        f
f                       l         l                       f
f                      l           l                      f
f                     l             l                     f
f                    l               l                    f
f                   l                 l                   f
f                  l                   l                  f
f                 l                     l                 f
f                l                       l                f
f               l                         l               f
f              l                           l              f
f             l ooooooooooooooooooooooooooo l             f
f            l  o            g            o  l            f
f           l   o           g g           o   l           f
f          l    o          g   g          o    l          f
f         l     o         g     g         o     l         f
f        l      o        g       g        o      l        f
f       l       o       g         g       o       l       f
f      l        o      g           g      o        l      f
f     l         o     g eeeeeeeeeee g     o         l     f
f    l          o    g  e    d    e  g    o          l    f
f   l           o   g   e   d d   e   g   o           l   f
f  l            o  g    e  d   d  e    g  o            l  f
f l             o g     e d ooo d e     g o             l f
fl              og      ed  oco  de      go              lf
f l             o g     e d ooo d e     g o             l f
f  l            o  g    e  d   d  e    g  o            l  f
f   l           o   g   e   d d   e   g   o           l   f
f    l          o    g  e    d    e  g    o          l    f
f     l         o     g eeeeeeeeeee g     o         l     f
f      l        o      g           g      o        l      f
f       l       o       g         g       o       l       f
f        l      o        g       g        o      l        f
f         l     o         g     g         o     l         f
f          l    o          g   g          o    l          f
f           l   o           g g           o   l           f
f            l  o            g            o  l            f
f             l ooooooooooooooooooooooooooo l             f
f              l                           l              f
f               l                         l               f
f                l                       l                f
f                 l                     l                 f
f                  l                   l                  f
f                   l                 l                   f
f                    l               l                    f
f                     l             l                     f
f                      l           l                      f
f                       l         l                       f
f                        l       l                        f
f                         l     l                         f
f                          l   l                          f
f                           l l                           f
f                            l                            f
fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
</code>```

Reference implementation

I wrote some Julia code that your program’s output should match (at least visually). Try it online!

答:
JavaScript (ES6), <s>294</s> <s>288</s> <s>287</s> <s>284</s> <s>256</s> <s>246</s> <s>240</s> <s>238</s> 220 bytes

My first golf on this site. Pass input string to function f, e.g. f('codegolf')

f=s=>{N=n=>(2<<n/2+.5)-3-n%2
D=N(l=s.length)
for(a=[],i=S=D*2+1;i--;)a[i]=a[S+~i]=Array(S).fill` `
for(;l--;)for(o=n=N(l+1),I=0;I<=n;I++,o-=~l&1)a[y=D+I][x=D+o]=a[x][y]=a[y][D-o]=a[x][D-I]=s[l]
return a.map(r=>r.join``)}```

-6 bytes thanks to @Sunny Pun: Remove parentheses when passing template strings.

-2 bytes thanks to @ETHproductions: Change S-i-1 to S+~i, l%2||o-- to o-=~l&1.

-18 bytes per suggestions of @Sunny Pun, @edc65: Remove prompt() and console.log() in favor of function format, don't .join() final array of strings

Title: Square, diamond, square, diamond

Body:
JavaScript (ES6), <s>294</s> <s>288</s> <s>287</s> <s>284</s> <s>256</s> <s>246</s> <s>240</s> <s>238</s> 220 bytes

My first golf on this site. Pass input string to function f, e.g. f('codegolf')

f=s=>{N=n=>(2<<n/2+.5)-3-n%2
D=N(l=s.length)
for(a=[],i=S=D*2+1;i--;)a[i]=a[S+~i]=Array(S).fill` `
for(;l--;)for(o=n=N(l+1),I=0;I<=n;I++,o-=~l&1)a[y=D+I][x=D+o]=a[x][y]=a[y][D-o]=a[x][D-I]=s[l]
return a.map(r=>r.join``)}

-6 bytes thanks to @Sunny Pun: Remove parentheses when passing template strings.

-2 bytes thanks to @ETHproductions: Change S-i-1 to S+~i, l%2||o-- to o-=~l&1.

-18 bytes per suggestions of @Sunny Pun, @edc65: Remove prompt() and console.log() in favor of function format, don't .join() final array of strings