答:
PHP, 5106 + 297 + 161 = 5564

encoder

$t=str_replace("=","",base64_encode((gzdeflate($_GET["e"]))));$c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";$e=["AT","TA","CG","GC"];$n="";foreach(str_split($t)as$b){$p=str_pad(base_convert(strpos($c,$b),10,4),3,"0",STR_PAD_LEFT);$n.=$e[$p[0]].$e[$p[1]].$e[$p[2]];}echo $n;
```

<p>decoder</p>

<pre class="lang-php prettyprint-override"><code>$e=["AT"=>0,"TA"=>1,"CG"=>2,"GC"=>3];$a=str_split(strtr($_GET["d"],$e),3);$o="";foreach($a as $v)$o.=$c[base_convert($v,4,10)];echo gzinflate(base64_decode($o));
</code>```

Title: DNA Encode a String

Body:
Challenge

You must write an encoder (and a separate decoder) which takes a string as input and outputs the string encoded in the style of a strand of DNA.

DNA

DNA is made up of four types of nucleotide:

Adenine (A)

Thymine (T)

Cytosine (C)

Guanine (G)

Adenine and thymine pair up together to make AT or TA. Similarly, cytosine and guanine pair up together to make CG or GC.

Let's call these pairs units. This means that your encoded string is only allowed to contain the four units AT, TA, CG and GC.

This means that:

```<code>ATTAGACG
</code>```

Would be invalid because it contains the unit GA, which is impossible.

Similarly,

```<code>TAGCGCCGATA
</code>```

Is invalid because the final A does not have a thymine to pair up with.

Example

You must encode the following example text and use its encoded length as part of your score:

I have a friend who's an artist and has sometimes taken a view which I don't agree with very well. He'll hold up a flower and say "look how beautiful it is," and I'll agree. Then he says "I as an artist can see how beautiful this is but you as a scientist take this all apart and it becomes a dull thing," and I think that he's kind of nutty. First of all, the beauty that he sees is available to other people and to me too, I believe. Although I may not be quite as refined aesthetically as he is ... I can appreciate the beauty of a flower. At the same time, I see much more about the flower than he sees. I could imagine the cells in there, the complicated actions inside, which also have a beauty. I mean it's not just beauty at this dimension, at one centimeter; there's also beauty at smaller dimensions, the inner structure, also the processes. The fact that the colors in the flower evolved in order to attract insects to pollinate it is interesting; it means that insects can see the color. It adds a question: does this aesthetic sense also exist in the lower forms? Why is it aesthetic? All kinds of interesting questions which the science knowledge only adds to the excitement, the mystery and the awe of a flower. It only adds. I don't understand how it subtracts.

Bounty

If you answer this challenge in the language DNA#, I will offer a 100 to 200 rep bounty.

Rules

Your encoder and decoder programs must work for any string supplied. Therefore, your encoder must produce a genuine encoding and your decoder should not simply hardcode the example text.

You must support all printable ASCII characters:

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

If you can support more characters, that is acceptable.

Scoring

Your score is how long in characters (not units) the encoded version of the above text plus the length in bytes of your decoder and your encoder.

Winning

The program with the lowest score wins.

Body:
PHP, 5106 + 297 + 161 = 5564

encoder

$t=str_replace("=","",base64_encode((gzdeflate($_GET["e"]))));$c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";$e=["AT","TA","CG","GC"];$n="";foreach(str_split($t)as$b){$p=str_pad(base_convert(strpos($c,$b),10,4),3,"0",STR_PAD_LEFT);$n.=$e[$p[0]].$e[$p[1]].$e[$p[2]];}echo $n;

decoder

$e=["AT"=>0,"TA"=>1,"CG"=>2,"GC"=>3];$a=str_split(strtr($_GET["d"],$e),3);$o="";foreach($a as $v)$o.=$c[base_convert($v,4,10)];echo gzinflate(base64_decode($o));


问:
10 PRINT CHR$(205.5+RND(1)); : GOTO 10 in PHP (or anything else, for that matter)
Just had a 'spirited' conversation with a co-worker about the succinctness of the following BASIC statement:

```<code>10 PRINT CHR$(205.5+RND(1)); : GOTO 10
</code>```

It's the title of this book, and will simply print a sequence of / and \ characters, alternating between the two randomly, resulting in a pattern similar to this:

(Image borrowed from http://www.flickr.com/photos/rndmcnlly/5058442151/sizes/o/in/photostream/)

Being of a PHP proclivity, we wondered what the most compact way of writing the same thing in PHP would be, and came up with this:

```<code>while(1) { echo chr(47 + 45 * rand(0,1)); }
</code>```

chr(47) is a / character, and chr(92) is a \. So the statement echo chr(47 + 45 * rand(0,1)); will randomly alternate between the two, ad nauseam.

In a language of your choosing, write the shortest program or function to output an infinite random sequence of \ and / characters, where each character has an equal probability of being chosen.

答:
print has a return value of 1, so if you use that you can just wrap the whole expression in the while:

while(print chr(47 + 45 * rand(0,1));

You can probably golf it further too.

OwnerDisplayName: Judy

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
Quixels - Quantum Pixels

Introduction

A quixel is a quantum pixel. Similar to a classical pixel, it is represented with 3 integer values (Red, Green, Blue). However, quixels are in a super position of these 3 states instead of a combination. This super position only lasts until the quixel is observed at which point it collapses to one of three classical pixels; RGB(255,0,0), RGB(0,255,0) and RGB(0,0,255).

Specification

Representation

Each quixel is represented as an array of 3 integers between 0 and 255, r, g and b respectively.

Super Positions

Each quixel is in a super position between the Red, Blue and Green states represented by R, G and B respectively.

Observation

When each quixel is observed it collapses into one of the three states. The probability of each classical state is R = (r + 1) / (r + g + b +3), G = (g + 1) / (r + g + b + 3) and B = (b + 1) / (r + g + b + 3). This way each classical state always as a non-zero probability of showing up.

Input

The function or program should take a image of quixels. How it does this is flexible. A filename, using a multi-dimensional array, etc are all acceptable.

Output

The function or program should produce an image of classical pixels. The data structure for this produced image is also flexible. Note that all of the pixels should be one of these three: RGB(255,0,0), RGB(0,255,0) and RGB(0,0,255)

The output should not be deterministic; these are quantum pixels! The same input should result in different outputs.

If your language has no way of generating a random number, you can take random bytes as input

Scoring

This is code-golf so fewest bytes win.

Images

Mona Lisa by Leonardo da Vinci

Starry Night by Vincent van Gogh

Persistence of Memory by Salvador Dali

Teddy Roosevelt VS. Bigfoot by SharpWriter

答:
C#, <s>366</s> 243 bytes

Huge thanks to @TheLethalCoder for golfing this!

var r=new Random();c=>{double t=c.R+c.G+c.B+3,x=(c.R+1)/t,d=r.NextDouble();return d<=x?Color.Red:d<=x+(c.G+1)/t?Color.Lime:Color.Blue;};b=>{for(int x=0,y;x<b.Width;x++)for(y=0;y<b.Height;y++)b.SetPixel(x,y,g(b.GetPixel(x,y)));return b;};
```

<p>Basic idea:</p>

<pre class="lang-c# prettyprint-override"><code>using System;
using System.Drawing;
static Random r = new Random();

static Image f(Bitmap a) {
    for (int x = 0; x < a.Width; x++) {
        for (int y = 0; y < a.Height; y++) {
            a.SetPixel(x, y, g(a.GetPixel(x, y)));
        }
    }
    return a;
}

static Color g(Color c) {
    int a = c.R;
    int g = c.G;
    double t = a + g + c.B + 3;
    var x = (a + 1) / t;
    var y = x + (g + 1) / t;
    var d = r.NextDouble();
    return d <= x ? Color.Red : d <= y ? Color.Lime : Color.Blue;
}
</code>```

Examples:

Mona Lisa

Starry Night

Persistence of Memory

Teddy Roosevelt VS. Bigfoot

Here's an updated imgur album with a few more examples, to show that this is nondeterministic.

Title: Quixels - Quantum Pixels

Body:
C#, <s>366</s> 243 bytes

Huge thanks to @TheLethalCoder for golfing this!

var r=new Random();c=>{double t=c.R+c.G+c.B+3,x=(c.R+1)/t,d=r.NextDouble();return d<=x?Color.Red:d<=x+(c.G+1)/t?Color.Lime:Color.Blue;};b=>{for(int x=0,y;x<b.Width;x++)for(y=0;y<b.Height;y++)b.SetPixel(x,y,g(b.GetPixel(x,y)));return b;};

Basic idea:

using System;
using System.Drawing;
static Random r = new Random();

static Image f(Bitmap a) {
    for (int x = 0; x < a.Width; x++) {
        for (int y = 0; y < a.Height; y++) {
            a.SetPixel(x, y, g(a.GetPixel(x, y)));
        }
    }
    return a;
}

static Color g(Color c) {
    int a = c.R;
    int g = c.G;
    double t = a + g + c.B + 3;
    var x = (a + 1) / t;
    var y = x + (g + 1) / t;
    var d = r.NextDouble();
    return d <= x ? Color.Red : d <= y ? Color.Lime : Color.Blue;
}

Examples:

Mona Lisa

Starry Night

Persistence of Memory

Teddy Roosevelt VS. Bigfoot

Here's an updated imgur album with a few more examples, to show that this is nondeterministic.


答:
Python 2, <s>172</s> <s>166</s> 162 bytes

The second and third indent levels are a raw tab and a raw tab plus a space, respectively; this plays really badly with Markdown, so the tabs have been replaced by two spaces.

from random import*
i=input()
E=enumerate
for a,y in E(i):
 for b,x in E(y):
  t=sum(x)+3.;n=random()
  for j,u in E(x):
   n-=-~u/t
   if n<0:i[a][b]=j;break
print i
```

<p>Uses a similar input/output format to Adám's APL answer. Input is a 2D array of RGB tuples; output is a 2D array of <code>0</code>, <code>1</code>, or <code>2</code>, representing red, green, and blue respectively. For example:</p>

```$ echo "[[(181,61,34),(39,184,160),(255,0,0)],[(84,7,27),(123,97,5),(12,24,88)]]" | python quixel.py
[[2, 2, 0], [0, 0, 0]]
```

<p>Below is my older Python 3 answer using PIL.</p>

<h2>Python 3 + PIL, <s>271</s> <s>250</s> <s>245</s> 243 bytes</h2>

<pre class="lang-py prettyprint-override"><code>import random as a,PIL.Image as q
i=q.open(input())
w,h=i.size
for k in range(w*h):
 m=k//h,k%h;c=i.getpixel(m);t=sum(c)+3;n=a.random()
 for j,u in enumerate(c):
  n-=-~u/t
  if n<0:z=[0]*3;z[j]=255;i.putpixel(m,tuple(z));break
i.save('o.png')
</code>```

Iterates over every pixel and applies the quixel function to it. Takes the filename as input and saves its output in o.png.

Here are some results:

```<code>$ echo mona-lisa.jpg | python quixel.py
</code>```

```<code>$ echo starry-night.jpg | python quixel.py
</code>```

```<code>$ echo persistence-of-memory.jpg | python quixel.py
</code>```

```<code>$ echo roosevelt-vs-bigfoot.jpg | python quixel.py
</code>```

Title: Quixels - Quantum Pixels

Body:
Introduction

A quixel is a quantum pixel. Similar to a classical pixel, it is represented with 3 integer values (Red, Green, Blue). However, quixels are in a super position of these 3 states instead of a combination. This super position only lasts until the quixel is observed at which point it collapses to one of three classical pixels; RGB(255,0,0), RGB(0,255,0) and RGB(0,0,255).

Specification

Representation

Each quixel is represented as an array of 3 integers between 0 and 255, r, g and b respectively.

Super Positions

Each quixel is in a super position between the Red, Blue and Green states represented by R, G and B respectively.

Observation

When each quixel is observed it collapses into one of the three states. The probability of each classical state is R = (r + 1) / (r + g + b +3), G = (g + 1) / (r + g + b + 3) and B = (b + 1) / (r + g + b + 3). This way each classical state always as a non-zero probability of showing up.

Input

The function or program should take a image of quixels. How it does this is flexible. A filename, using a multi-dimensional array, etc are all acceptable.

Output

The function or program should produce an image of classical pixels. The data structure for this produced image is also flexible. Note that all of the pixels should be one of these three: RGB(255,0,0), RGB(0,255,0) and RGB(0,0,255)

The output should not be deterministic; these are quantum pixels! The same input should result in different outputs.

If your language has no way of generating a random number, you can take random bytes as input

Scoring

This is code-golf so fewest bytes win.

Images

Mona Lisa by Leonardo da Vinci

Starry Night by Vincent van Gogh

Persistence of Memory by Salvador Dali

Teddy Roosevelt VS. Bigfoot by SharpWriter

Body:
Python 2, <s>172</s> <s>166</s> 162 bytes

The second and third indent levels are a raw tab and a raw tab plus a space, respectively; this plays really badly with Markdown, so the tabs have been replaced by two spaces.

from random import*
i=input()
E=enumerate
for a,y in E(i):
 for b,x in E(y):
  t=sum(x)+3.;n=random()
  for j,u in E(x):
   n-=-~u/t
   if n<0:i[a][b]=j;break
print i

Uses a similar input/output format to Adám's APL answer. Input is a 2D array of RGB tuples; output is a 2D array of 0, 1, or 2, representing red, green, and blue respectively. For example:

$ echo "[[(181,61,34),(39,184,160),(255,0,0)],[(84,7,27),(123,97,5),(12,24,88)]]" | python quixel.py
[[2, 2, 0], [0, 0, 0]]

Below is my older Python 3 answer using PIL.

Python 3 + PIL, <s>271</s> <s>250</s> <s>245</s> 243 bytes

import random as a,PIL.Image as q
i=q.open(input())
w,h=i.size
for k in range(w*h):
 m=k//h,k%h;c=i.getpixel(m);t=sum(c)+3;n=a.random()
 for j,u in enumerate(c):
  n-=-~u/t
  if n<0:z=[0]*3;z[j]=255;i.putpixel(m,tuple(z));break
i.save('o.png')

Iterates over every pixel and applies the quixel function to it. Takes the filename as input and saves its output in o.png.

Here are some results:

$ echo mona-lisa.jpg | python quixel.py

$ echo starry-night.jpg | python quixel.py

$ echo persistence-of-memory.jpg | python quixel.py

$ echo roosevelt-vs-bigfoot.jpg | python quixel.py


答:
Dyalog APL, <s>23</s> <s>21</s> 19 bytes

Takes table of (R, G, B) triplets.

Inspired by miles' algorithm

Returns table of indices into {(255, 0, 0), (0, 255, 0), (0, 0, 255)}. Horribly wasteful.

(?∘≢⊃⊢)¨(⊂⍳3)/¨⍨1+⊢
```
<p><code>(</code><br>
 <code>?∘≢</code> random index<br>
 <code>⊃</code> selects<br>
 <code>⊢</code> from<br>
<code>)¨</code> each of</p>
<p><code>(</code><br>
 <code>⊂</code> the entire<br>
 <code>⍳3</code> first three indices<br>
<code>)/¨⍨</code> replicated by each of</p>
<p><code>1+⊢</code> the incremented triplets</p>
<p>TryAPL!</p>
<hr />
<h3>Old version</h3>
<p>Returns table of 0-based indices into {(255, 0, 0), (0, 255, 0), (0, 0, 255)}</p>
<pre class="lang-apl prettyprint-override"><code>{+/(?0)≥+\(1+⍵)÷3++/⍵}¨
</code>```

{...}¨ for each quixel in the table, find the:

 +/ the sum of (i.e. count of truths of)

 (?0)≥ a random 0 < number < 1 being greater than or equal to

 +\ the cumulative sum of

 (1+⍵)÷ the incremented RGB values divided by

 3+ three plus

 +/⍵ the sum of the quixel

Note: Dyalog APL lets you chose between the Lehmer linear congruential generator, the Mersenne Twister, and the Operating System's RNG¹ ².

For example, the image:

┌──────────┬──────────┬───────────┬───────────┬─────────┐
│52 241 198│148 111 45│197 165 180│9 137 120  │46 62 75 │
├──────────┼──────────┼───────────┼───────────┼─────────┤
│81 218 104│0 0 255   │0 255 0    │181 202 116│122 89 76│
├──────────┼──────────┼───────────┼───────────┼─────────┤
│181 61 34 │84 7 27   │233 220 249│39 184 160 │255 0 0  │
└──────────┴──────────┴───────────┴───────────┴─────────┘
```
<p>can give</p>
<pre class="lang-apl prettyprint-override"><code>┌─┬─┬─┬─┬─┐
│1│0│2│2│1│
├─┼─┼─┼─┼─┤
│2│2│1│1│2│
├─┼─┼─┼─┼─┤
│0│2│1│2│0│
└─┴─┴─┴─┴─┘
</code>```

Notice how the three "pure" quixels collapsed to their respective colors.

TryAPL online!

Title: Quixels - Quantum Pixels

Body:
Dyalog APL, <s>23</s> <s>21</s> 19 bytes

Takes table of (R, G, B) triplets.

Inspired by miles' algorithm

Returns table of indices into {(255, 0, 0), (0, 255, 0), (0, 0, 255)}. Horribly wasteful.

(?∘≢⊃⊢)¨(⊂⍳3)/¨⍨1+⊢

(

 ?∘≢ random index

 ⊃ selects

 ⊢ from

)¨ each of

(

 ⊂ the entire

 ⍳3 first three indices

)/¨⍨ replicated by each of

1+⊢ the incremented triplets

TryAPL!

Old version

Returns table of 0-based indices into {(255, 0, 0), (0, 255, 0), (0, 0, 255)}

{+/(?0)≥+\(1+⍵)÷3++/⍵}¨

{...}¨ for each quixel in the table, find the:

 +/ the sum of (i.e. count of truths of)

 (?0)≥ a random 0 < number < 1 being greater than or equal to

 +\ the cumulative sum of

 (1+⍵)÷ the incremented RGB values divided by

 3+ three plus

 +/⍵ the sum of the quixel

Note: Dyalog APL lets you chose between the Lehmer linear congruential generator, the Mersenne Twister, and the Operating System's RNG¹ ².

For example, the image:

┌──────────┬──────────┬───────────┬───────────┬─────────┐
│52 241 198│148 111 45│197 165 180│9 137 120  │46 62 75 │
├──────────┼──────────┼───────────┼───────────┼─────────┤
│81 218 104│0 0 255   │0 255 0    │181 202 116│122 89 76│
├──────────┼──────────┼───────────┼───────────┼─────────┤
│181 61 34 │84 7 27   │233 220 249│39 184 160 │255 0 0  │
└──────────┴──────────┴───────────┴───────────┴─────────┘

can give

┌─┬─┬─┬─┬─┐
│1│0│2│2│1│
├─┼─┼─┼─┼─┤
│2│2│1│1│2│
├─┼─┼─┼─┼─┤
│0│2│1│2│0│
└─┴─┴─┴─┴─┘

Notice how the three "pure" quixels collapsed to their respective colors.

TryAPL online!


答:
Mathematica, 53 bytes

```<code>RandomChoice[255#+1->IdentityMatrix@3]&~ImageApply~#&
</code>```

Anonymous function. Takes a Mathematica Image as input and returns an Image as output. Note that the input image must have an RGB color space.

Title: Quixels - Quantum Pixels

Body:
Mathematica, 53 bytes

RandomChoice[255#+1->IdentityMatrix@3]&~ImageApply~#&

Anonymous function. Takes a Mathematica Image as input and returns an Image as output. Note that the input image must have an RGB color space.


问:
Stock Exchange KoTH
The stock market is all about the speed of knowledge. Unlike previous challenges, the current stock price is not random: it is determined by those playing the game.  If you can identify an under-priced stock before anybody else, then you've written yourself a money-making program.

Price refers to the how much people are trading the stock for, while Value refers to the amount the stock is worth at the end of the game.

Each player starts with 1000 of each stock, and 0 relative net worth.  Each stock has a secret value, and your score at the end of the game is (stockValue for each ownedStock) + netWorth.  Your net worth can be negative.  In an N-player game, there are N stocks.

Steps:

The game follows the following steps:

You are given the secret value of a single stock.

You make an offer to sell X of Y stock for $Z

All players are given the offers, and each may choose one to accept

All players are informed of accepted offers

Go back to step 2

Each of the steps are given in detail below:

void secretValue(int stockType, int value):

The value you learn is not revealed to any other player.

The value is between 0 and 1000

Low values are more like to occur than high values (squared uniform distribution)

Offer makeOffer(List<Stock> currentStock)

You can return null to make no offer.

Offer acceptOffer(List<Offer> offers)

You can return null to accept none of them

If there are no available offers, this will not be called

If you accept, your net worth goes down by $Z (can go negative) and receive X of Y stock.  The opposite occurs with the seller.

If you accept an offer, the exchange will occur immediately, and the offer will be removed so additional players cannot accept it.

void acceptedOffers(List<Offer> offers)

Includes your accepted offers as well

Static variables or writing to files is not allowed.  (No persistent data from game to game)  Non-serious contenders are allowed.

Interfaces:

```<code>public final class Stock {
    public Stock(int stockType, int amount);
    public int getType();
    public int getAmount();
    public Stock minus(Stock other);
    public Stock plus(Stock other);
    public Stock minus(int amount);
    public Stock plus(int amount);
    public Stock setAmount(int amount);
}
public class Offer {
    public Offer(Stock offer, int payment);
    public Stock getOffer();
    public int getPayment();
}
</code>```

Non-Java submissions:

All calls consist of two lines: The first line is the function being called: SecretValue, MakeOffer, AcceptOffer, AcceptedOffers, SetRandom, and the second line containing the actual data.

Stocks are formatted with a : delimiter: stockType:stockAmount.

Offers are formatted with a @ delimiter: offer@price

Lists are formatted with a ; delimiter

SecretValue is formatted with a : delimiter: stockType:value

RandomSeed is used to make your submission deterministic.  If your submission uses randomness, please use the integer value passed as the seed!

All function calls need a response.  If the response is null or void, return an empty string.

Please include a command.txt that gives the command line arguments to run your submission

Scoring

Games consisting of 1000 turns will be run multiple times.  Players will be scored according to the ELO system, and paired with players of similar skill levels.  The player with the highest final ELO score wins!  (I've modified the system so that each game, ELO scores are updated for each player pairing)

The controller includes an autodownloader, so please start your submission with a header: Name, Language.  If your submission is not in Java, each code block should start with the name of the file.  (excluding the command file, which should be the first block in your post)

Running

There are 2 ways to run this project:

Download the source code, compile and run.  You can find the source on Github.  Run git clone --recursive https://github.com/nathanmerrill/StockExchange.git

Download the JAR executable.  Submissions should be placed in your current working directory in the /submissions folder.  You can download just the JAR, just the submissions, or both

Pass in run to run the project (default option), or pass in download to download all submissions so far from this question.

Scoreboard

```<code>1.  1308.1220497323848  Cheater
2.  1242.0333695640356  InsideTrader
3.  1158.3662658295411  UncleScrooge
4.  1113.8344000358493  BlackMarket
5.  1051.8370015258993  DartMonkey
6.  983.0545446731494   WarGamer
7.  939.457423938002    Spammer
8.  901.4372529538886   DumbBot
9.  859.0519326039137   ShutUpAndTakeMyMoney
10. 852.9448222849587   VincentKasuga
11. 718.2112067329083   Profiteer
</code>```

答:
InsideTrader, Java

InsideTrader just looked around and saw that everybody was trying to be creative. But he did something creative: do what is expected.

This bot buys when it's "worth it" because it "borrowed" some "internal documents" to "guide" "investing decisions".

To-Do and how it works in the code. ;)

The "code"

```<code>import java.util.List;

import com.ppcg.stockexchange.*;

public class InsideTrader extends Player {
    public String coverStory = "I can tell the good companies from the bad ones.";
    private String theTruth = "I'm cheating. (but so is everyone else)";
    private String ambitions = "Learn to \"follow the market\"";  // don't steal this idea
    private int secretStock = -1;
    private int secretStockValue = -1;

    private int appraiseOffer(Offer offer) {
        /* get how much the offer is worth, 0 if it's not the secret stock */
        if (offer.getOffer().getType() != secretStock ||offer.getOffer().getAmount() == 0) {
            return 0;
        }
        return (offer.getPayment()/offer.getOffer().getAmount())  // price per stock...
                - secretStockValue  // minus value of stock.
                ;
    }
    public Offer acceptOffer(List<Offer> offers) {
        Offer bestOffer = null;
        int bestOfferValue = -1;
        for (Offer offer :
                offers) {
            int value = appraiseOffer(offer);
            if (value > bestOfferValue && value > 0) {
                bestOfferValue = value;
                bestOffer = offer;
            }
        }
        return bestOffer;
    }

    public Offer makeOffer(List<Stock> currentStock) {
        return new Offer(new Stock(0,1), Integer.MAX_VALUE);
    }

    public void secretValue(int stockType, int value) {
        secretStock = stockType;
        secretStockValue = value;
    }

    public void acceptedOffers(List<Offer> acceptedOffers) {

    }
}
</code>```

Title: Stock Exchange KoTH

Body:
InsideTrader, Java

InsideTrader just looked around and saw that everybody was trying to be creative. But he did something creative: do what is expected.

This bot buys when it's "worth it" because it "borrowed" some "internal documents" to "guide" "investing decisions".

To-Do and how it works in the code. ;)

The "code"

import java.util.List;

import com.ppcg.stockexchange.*;

public class InsideTrader extends Player {
    public String coverStory = "I can tell the good companies from the bad ones.";
    private String theTruth = "I'm cheating. (but so is everyone else)";
    private String ambitions = "Learn to \"follow the market\"";  // don't steal this idea
    private int secretStock = -1;
    private int secretStockValue = -1;

    private int appraiseOffer(Offer offer) {
        /* get how much the offer is worth, 0 if it's not the secret stock */
        if (offer.getOffer().getType() != secretStock ||offer.getOffer().getAmount() == 0) {
            return 0;
        }
        return (offer.getPayment()/offer.getOffer().getAmount())  // price per stock...
                - secretStockValue  // minus value of stock.
                ;
    }
    public Offer acceptOffer(List<Offer> offers) {
        Offer bestOffer = null;
        int bestOfferValue = -1;
        for (Offer offer :
                offers) {
            int value = appraiseOffer(offer);
            if (value > bestOfferValue && value > 0) {
                bestOfferValue = value;
                bestOffer = offer;
            }
        }
        return bestOffer;
    }

    public Offer makeOffer(List<Stock> currentStock) {
        return new Offer(new Stock(0,1), Integer.MAX_VALUE);
    }

    public void secretValue(int stockType, int value) {
        secretStock = stockType;
        secretStockValue = value;
    }

    public void acceptedOffers(List<Offer> acceptedOffers) {

    }
}


问:
The Squiggly Sequence

All credits to Adnan for coming up with this challenge.

My last challenge, before I go on break.

Task

Given positive integer n, if n is odd, repeat / that many times; if n is even, repeat \ that many times.

(Seriously, the testcases would be much clearer than this description, so just look at the testcases.)

Specs

Any reasonable input/output format.

Standard loopholes apply.

Testcases

```<code>n output
1 /
2 \\
3 ///
4 \\\\
5 /////
6 \\\\\\
</code>```

答:
Javascript, 22 bytes

```<code>n=>"\\/"[n%2].repeat(n)
</code>```

Defines an anonymous function.

If only * repeated strings in Javascript. sighs

Title: The Squiggly Sequence

Body:
Javascript, 22 bytes

n=>"\\/"[n%2].repeat(n)

Defines an anonymous function.

If only * repeated strings in Javascript. sighs


答:
Ruby, 15 bytes

```<code>->n{'\/'[n%2]*n}
</code>```

See it on eval.in: https://eval.in/632030

Title: The Squiggly Sequence

Body:
All credits to Adnan for coming up with this challenge.

My last challenge, before I go on break.

Task

Given positive integer n, if n is odd, repeat / that many times; if n is even, repeat \ that many times.

(Seriously, the testcases would be much clearer than this description, so just look at the testcases.)

Specs

Any reasonable input/output format.

Standard loopholes apply.

Testcases

```<code>n output
1 /
2 \\
3 ///
4 \\\\
5 /////
6 \\\\\\
</code>```

Body:
Ruby, 15 bytes

->n{'\/'[n%2]*n}

See it on eval.in: https://eval.in/632030


答:
C, 40 bytes

i;f(n){for(i=n;i--;)putchar(n%2?47:92);}
```

Try it on Ideone

Title: The Squiggly Sequence

Body:
C, 40 bytes

i;f(n){for(i=n;i--;)putchar(n%2?47:92);}

Try it on Ideone


答:
J, 10 bytes

```<code>#'\/'{~2|]
</code>```

This is a six-train verb, consisting of:

```<code># ('\/' {~ 2 | ])
</code>```

This is a hook between # and ('\/' {~ 2 | ]); a hook (f g) y expands to y f (g y), so this expands to y # (... y), which, for single-characters, yields a list of y characters.

The second part is a 5-train, consisting of:

```<code>'\/' {~ 2 | ]
</code>```

This evaluates to two forks:

```<code>'\/' {~ (2 | ])
</code>```

The inner fork, 2 | ], is modulus two. The outer fork, therefore, is:

```<code>'\/' {~ mod2
</code>```

Which takes ({~) the mod2 index (mod2) from the string /.

Then, using the hook from above:

```<code>y # (apt char)
</code>```

This yields what we want, and we are done.

Title: The Squiggly Sequence

Body:
J, 10 bytes

#'\/'{~2|]

This is a six-train verb, consisting of:

# ('\/' {~ 2 | ])

This is a hook between # and ('\/' {~ 2 | ]); a hook (f g) y expands to y f (g y), so this expands to y # (... y), which, for single-characters, yields a list of y characters.

The second part is a 5-train, consisting of:

'\/' {~ 2 | ]

This evaluates to two forks:

'\/' {~ (2 | ])

The inner fork, 2 | ], is modulus two. The outer fork, therefore, is:

'\/' {~ mod2

Which takes ({~) the mod2 index (mod2) from the string /.

Then, using the hook from above:

y # (apt char)

This yields what we want, and we are done.


问:
Calculate the correlation coefficient
Given a series of numbers for events X and Y, calculate Pearson's correlation coefficient. The probability of each event is equal, so expected values can be calculated by simply summing each series and dividing by the number of trials.

Input

```<code>1   6.86
2   5.92
3   6.08
4   8.34
5   8.7
6   8.16
7   8.22
8   7.68
9   12.04
10  8.6
11  10.96
</code>```

Output

```<code>0.769
</code>```

Shortest code wins. Input can be by stdin or arg. Output will be by stdout.

Edit: Builtin functions should not be allowed (ie calculated expected value, variance, deviation, etc) to allow more diversity in solutions. However, feel free to demonstrate a language that is well suited for the task using builtins (for exhibition).

Based on David's idea for input for Mathematica (86 char using builtin mean)

```<code>m=Mean;x=d[[All,1]];y=d[[All,2]];(m@(x*y)-m@x*m@y)/Sqrt[(m@(x^2)-m@x^2)(m@(y^2)-m@y^2)]

m = Mean;
x = d[[All,1]];
y = d[[All,2]];
(m@(x*y) - m@x*m@y)/((m@(x^2) - m@x^2)(m@(y^2) - m@y^2))^.5
</code>```

Skirting by using our own mean (101 char)

```<code>m=Total[#]/Length[#]&;x=d[[All,1]];y=d[[All,2]];(m@(x*y)-m@x*m@y)/((m@(x^2)-m@x^2)(m@(y^2)-m@y^2))^.5

m = Total[#]/Length[#]&;
x = d[[All,1]];
y = d[[All,2]];
(m@(x*y)-m@x*m@y)/((m@(x^2)-m@x^2)(m@(y^2)-m@y^2))^.5
</code>```

Title: Calculate the correlation coefficient

Body:
APL 57

Using the dot product approach:

a←1 2 3 4 5 6 7 8 9 10 11

b←6.86 5.92 6.08 8.34 8.7 8.16 8.22 7.68 12.04 8.6 10.96

(a+.×b)÷((+/(a←a-(+/a)÷⍴a)*2)*.5)×(+/(b←b-(+/b)÷⍴b)*2)*.5

0.7690904406


答:
Python, 20 bytes

lambda n:'\/'[n%2]*n
```

Title: The Squiggly Sequence

Body:
Python, 20 bytes

lambda n:'\/'[n%2]*n


答:
Pyth, 5 bytes

```<code>*@"\/
</code>```

Test suite.

Modular-indexing into the string \/ and then repeat.

Title: The Squiggly Sequence

Body:
Pyth, 5 bytes

*@"\/

Test suite.

Modular-indexing into the string \/ and then repeat.


答:
Jelly, 5 bytes

```<code>ị⁾/\x
</code>```

Try it online! or Verify all testcases.

```<code>ị⁾/\x

ị⁾/\    modular-indexing into the string "/\"
    x   repeat
</code>```

Title: The Squiggly Sequence

Body:
Jelly, 5 bytes

ị⁾/\x

Try it online! or Verify all testcases.

ị⁾/\x

ị⁾/\    modular-indexing into the string "/\"
    x   repeat


答:
Perl, 20 bytes

Includes +1 for -p

Run with input on STDIN:

```<code>squigly.pl <<< 6
</code>```

squigly.pl

```<code>#!/usr/bin/perl -p
$_=$_%2x$_;y;01;\\/
</code>```

Title: The Squiggly Sequence

Body:
Perl, 20 bytes

Includes +1 for -p

Run with input on STDIN:

squigly.pl <<< 6

squigly.pl

#!/usr/bin/perl -p
$_=$_%2x$_;y;01;\\/


答:
S.I.L.O.S, 55 bytes

```<code>readIO
c=i
c%2
c*45
c-92
c|
lbla
printChar c
i-1
if i a
</code>```

Try it online!

Port of this answer in C.

Title: The Squiggly Sequence

Body:
S.I.L.O.S, 55 bytes

readIO
c=i
c%2
c*45
c-92
c|
lbla
printChar c
i-1
if i a

Try it online!

Port of this answer in C.


答:
Fourier, 27 bytes

```<code>92~SI~N%2{1}{47~S}N(Sai^~i)
</code>```

Try it online!

Title: The Squiggly Sequence

Body:
Fourier, 27 bytes

92~SI~N%2{1}{47~S}N(Sai^~i)

Try it online!


答:
DartMonkey, Java

(non-competing: It won't win and I already have another answer)

Dart monkey likes throwing things... and there's a big pile of pointy sticks next to him. He sees some paper on the wall. Bam! Bam! Bam! In no time at all, Dart Monkey's thrown 80 darts! Half the darts are red, and the other half are blue, and there's random numbers on them! Dart monkey sees a computer... dart monkey types in the numbers. Dart monkey likes numbers. Dart monkey makes some money from his darts...

In all seriousness, DartMonkey initializes an integer array that has a length that is twice the number of stocks. He stores one number for the amount of stock he wants to buy/sell, and one number for the price of the stock. He then alternates selling stock from the array, and accepting offers according to the array. If he has no stock from the array, he won't offer anything, and if he has no offers given to him from the array, he won't accept anything.

This answer was inspired by @TheNumberOne, who mentioned dart monkeys in the chat

```<code>import com.ppcg.stockexchange.Offer;
import com.ppcg.stockexchange.Player;
import com.ppcg.stockexchange.Stock;

import java.util.List;
import java.util.Random;

public class DartMonkey extends Player {
    private int basePrice = 100;
    private int numStocks;
    private int[] dartBoard;
    private boolean first = true;

    @Override
    public Offer acceptOffer(List<Offer> offers) {
        for(Offer offer : offers) {
            Stock stock = offer.getOffer();
            int type = stock.getType();
            int amount = stock.getAmount();
            int price = offer.getPayment();
            if(this.dartBoard[type] < 0 && amount <= -this.dartBoard[type] && price <= this.dartBoard[type + this.numStocks]) {
                this.dartBoard[type] = 0;
                return offer;
            }
        }
        return null;
    }

    @Override
    public Offer makeOffer(List<Stock> stocks) {
        if(this.first) {
            this.first = false;
            this.numStocks = stocks.size();
            this.dartBoard = new int[this.numStocks * 2];
            Random random = this.getRandom();
            for (int i = 0; i < 20; i++) {
                int index = random.nextInt(this.dartBoard.length / 2);
                this.dartBoard[index] = random.nextInt(1001);
                this.dartBoard[this.numStocks + index] = random.nextInt(1001);
            }

            for (int i = 0; i < 20; i++) {
                int index = random.nextInt(this.dartBoard.length / 2);
                this.dartBoard[index] = -random.nextInt(1001);
                this.dartBoard[this.numStocks + index] = random.nextInt(1001);
            }
        }

        for (Stock stock : stocks) {
            int type = stock.getType();
            if(this.dartBoard[type] > 0) {
                Offer offer = new Offer(stock.setAmount(this.dartBoard[type]), this.basePrice + this.dartBoard[type + this.numStocks]);
                this.dartBoard[type] = 0;
                this.dartBoard[type + this.numStocks] = 0;
                return offer;
            }
        }

        return null;
    }

}
</code>```

Title: Stock Exchange KoTH

Body:
The stock market is all about the speed of knowledge. Unlike previous challenges, the current stock price is not random: it is determined by those playing the game.  If you can identify an under-priced stock before anybody else, then you've written yourself a money-making program.

Price refers to the how much people are trading the stock for, while Value refers to the amount the stock is worth at the end of the game.

Each player starts with 1000 of each stock, and 0 relative net worth.  Each stock has a secret value, and your score at the end of the game is (stockValue for each ownedStock) + netWorth.  Your net worth can be negative.  In an N-player game, there are N stocks.

Steps:

The game follows the following steps:

You are given the secret value of a single stock.

You make an offer to sell X of Y stock for $Z

All players are given the offers, and each may choose one to accept

All players are informed of accepted offers

Go back to step 2

Each of the steps are given in detail below:

void secretValue(int stockType, int value):

The value you learn is not revealed to any other player.

The value is between 0 and 1000

Low values are more like to occur than high values (squared uniform distribution)

Offer makeOffer(List<Stock> currentStock)

You can return null to make no offer.

Offer acceptOffer(List<Offer> offers)

You can return null to accept none of them

If there are no available offers, this will not be called

If you accept, your net worth goes down by $Z (can go negative) and receive X of Y stock.  The opposite occurs with the seller.

If you accept an offer, the exchange will occur immediately, and the offer will be removed so additional players cannot accept it.

void acceptedOffers(List<Offer> offers)

Includes your accepted offers as well

Static variables or writing to files is not allowed.  (No persistent data from game to game)  Non-serious contenders are allowed.

Interfaces:

```<code>public final class Stock {
    public Stock(int stockType, int amount);
    public int getType();
    public int getAmount();
    public Stock minus(Stock other);
    public Stock plus(Stock other);
    public Stock minus(int amount);
    public Stock plus(int amount);
    public Stock setAmount(int amount);
}
public class Offer {
    public Offer(Stock offer, int payment);
    public Stock getOffer();
    public int getPayment();
}
</code>```

Non-Java submissions:

All calls consist of two lines: The first line is the function being called: SecretValue, MakeOffer, AcceptOffer, AcceptedOffers, SetRandom, and the second line containing the actual data.

Stocks are formatted with a : delimiter: stockType:stockAmount.

Offers are formatted with a @ delimiter: offer@price

Lists are formatted with a ; delimiter

SecretValue is formatted with a : delimiter: stockType:value

RandomSeed is used to make your submission deterministic.  If your submission uses randomness, please use the integer value passed as the seed!

All function calls need a response.  If the response is null or void, return an empty string.

Please include a command.txt that gives the command line arguments to run your submission

Scoring

Games consisting of 1000 turns will be run multiple times.  Players will be scored according to the ELO system, and paired with players of similar skill levels.  The player with the highest final ELO score wins!  (I've modified the system so that each game, ELO scores are updated for each player pairing)

The controller includes an autodownloader, so please start your submission with a header: Name, Language.  If your submission is not in Java, each code block should start with the name of the file.  (excluding the command file, which should be the first block in your post)

Running

There are 2 ways to run this project:

Download the source code, compile and run.  You can find the source on Github.  Run git clone --recursive https://github.com/nathanmerrill/StockExchange.git

Download the JAR executable.  Submissions should be placed in your current working directory in the /submissions folder.  You can download just the JAR, just the submissions, or both

Pass in run to run the project (default option), or pass in download to download all submissions so far from this question.

Scoreboard

```<code>1.  1308.1220497323848  Cheater
2.  1242.0333695640356  InsideTrader
3.  1158.3662658295411  UncleScrooge
4.  1113.8344000358493  BlackMarket
5.  1051.8370015258993  DartMonkey
6.  983.0545446731494   WarGamer
7.  939.457423938002    Spammer
8.  901.4372529538886   DumbBot
9.  859.0519326039137   ShutUpAndTakeMyMoney
10. 852.9448222849587   VincentKasuga
11. 718.2112067329083   Profiteer
</code>```

Body:
DartMonkey, Java

(non-competing: It won't win and I already have another answer)

Dart monkey likes throwing things... and there's a big pile of pointy sticks next to him. He sees some paper on the wall. Bam! Bam! Bam! In no time at all, Dart Monkey's thrown 80 darts! Half the darts are red, and the other half are blue, and there's random numbers on them! Dart monkey sees a computer... dart monkey types in the numbers. Dart monkey likes numbers. Dart monkey makes some money from his darts...

In all seriousness, DartMonkey initializes an integer array that has a length that is twice the number of stocks. He stores one number for the amount of stock he wants to buy/sell, and one number for the price of the stock. He then alternates selling stock from the array, and accepting offers according to the array. If he has no stock from the array, he won't offer anything, and if he has no offers given to him from the array, he won't accept anything.

This answer was inspired by @TheNumberOne, who mentioned dart monkeys in the chat

import com.ppcg.stockexchange.Offer;
import com.ppcg.stockexchange.Player;
import com.ppcg.stockexchange.Stock;

import java.util.List;
import java.util.Random;

public class DartMonkey extends Player {
    private int basePrice = 100;
    private int numStocks;
    private int[] dartBoard;
    private boolean first = true;

    @Override
    public Offer acceptOffer(List<Offer> offers) {
        for(Offer offer : offers) {
            Stock stock = offer.getOffer();
            int type = stock.getType();
            int amount = stock.getAmount();
            int price = offer.getPayment();
            if(this.dartBoard[type] < 0 && amount <= -this.dartBoard[type] && price <= this.dartBoard[type + this.numStocks]) {
                this.dartBoard[type] = 0;
                return offer;
            }
        }
        return null;
    }

    @Override
    public Offer makeOffer(List<Stock> stocks) {
        if(this.first) {
            this.first = false;
            this.numStocks = stocks.size();
            this.dartBoard = new int[this.numStocks * 2];
            Random random = this.getRandom();
            for (int i = 0; i < 20; i++) {
                int index = random.nextInt(this.dartBoard.length / 2);
                this.dartBoard[index] = random.nextInt(1001);
                this.dartBoard[this.numStocks + index] = random.nextInt(1001);
            }

            for (int i = 0; i < 20; i++) {
                int index = random.nextInt(this.dartBoard.length / 2);
                this.dartBoard[index] = -random.nextInt(1001);
                this.dartBoard[this.numStocks + index] = random.nextInt(1001);
            }
        }

        for (Stock stock : stocks) {
            int type = stock.getType();
            if(this.dartBoard[type] > 0) {
                Offer offer = new Offer(stock.setAmount(this.dartBoard[type]), this.basePrice + this.dartBoard[type + this.numStocks]);
                this.dartBoard[type] = 0;
                this.dartBoard[type + this.numStocks] = 0;
                return offer;
            }
        }

        return null;
    }

}


答:
Dyalog APL, 11 bytes

Requires ⎕IO←0 which is default on many systems.

⊢⍴'\/'⊃⍨2|⊢
```

⊢ the argument

⍴ reshapes (repeats)

'\/'⊃⍨ the string "/" selected by

2|⊢ the division remainder when the argument is divided by two

TryAPL online!

Title: The Squiggly Sequence

Body:
Dyalog APL, 11 bytes

Requires ⎕IO←0 which is default on many systems.

⊢⍴'\/'⊃⍨2|⊢

⊢ the argument

⍴ reshapes (repeats)

'\/'⊃⍨ the string "/" selected by

2|⊢ the division remainder when the argument is divided by two

TryAPL online!


答:
Haskell, 32 bytes

```<code>f n=replicate n$"\\/"!!(mod n 2)
</code>```

Title: The Squiggly Sequence

Body:
Haskell, 32 bytes

f n=replicate n$"\\/"!!(mod n 2)


问:
Four weights to produce integer scale differences from 0 through 40 pounds
Just-in-time edit: I decided to reveal part of the answer and highlight a single aspect of the challenge.

Show how 4 weights, of 1, 3,  9, and 27 lbs. can be used to produce "weight differences" from 0 to 40 lbs.

You have a two - pan balance scale.

We define the difference in pan weights as the total weight placed on the left pan minus the total weight on the right pan.

The difference in pan weights for the empty scale is 0 lbs.

You have 4 rocks, a,b,c, and d, weighing 1, 3, 9 and 27 lbs respectively

Show how you can produce all integer weight differences from 0 to 40 lbs.

Simpler example:

Problem: With weights of 1 and 3 lbs. show how you can generate all weight differences from 0 to 4 lbs.

Output: for a=1, b=3;

For the 4 weight, 40 pound version, your output should consist of
a table with columns displaying the weight difference, the symbolic amounts in each pan, and the absolute weights in each pan.

You may format the table in a way congenial to the language you are coding in.

Scoring: Shortest code wins

Bonus: 50% of your score if the same code can present the results for the case where 3, 4, and 5 weights are used (for 13, 40, and 121 lbs.)

Body:
Python <s>124</s> 107 bytes * 50% = 53.5

f=lambda i,e=1:i and[e]*(i%3>1)+f(-~i/3,e*3)or[]
for i in range(3**4/2+1):r=f(-i),f(i);print i,map(sum,r),r

For different numbers of stones, replace the 4 in range(3**4/2+1) with any positive integer.

Sample output:

0 [0, 0] ([], [])
1 [1, 0] ([1], [])
2 [3, 1] ([3], [1])
3 [3, 0] ([3], [])
4 [4, 0] ([1, 3], [])
5 [9, 4] ([9], [1, 3])
6 [9, 3] ([9], [3])
7 [10, 3] ([1, 9], [3])
8 [9, 1] ([9], [1])
9 [9, 0] ([9], [])
10 [10, 0] ([1, 9], [])
11 [12, 1] ([3, 9], [1])
12 [12, 0] ([3, 9], [])
13 [13, 0] ([1, 3, 9], [])
14 [27, 13] ([27], [1, 3, 9])
15 [27, 12] ([27], [3, 9])
16 [28, 12] ([1, 27], [3, 9])
17 [27, 10] ([27], [1, 9])
18 [27, 9] ([27], [9])
19 [28, 9] ([1, 27], [9])
20 [30, 10] ([3, 27], [1, 9])
21 [30, 9] ([3, 27], [9])
22 [31, 9] ([1, 3, 27], [9])
23 [27, 4] ([27], [1, 3])
24 [27, 3] ([27], [3])
25 [28, 3] ([1, 27], [3])
26 [27, 1] ([27], [1])
27 [27, 0] ([27], [])
28 [28, 0] ([1, 27], [])
29 [30, 1] ([3, 27], [1])
30 [30, 0] ([3, 27], [])
31 [31, 0] ([1, 3, 27], [])
32 [36, 4] ([9, 27], [1, 3])
33 [36, 3] ([9, 27], [3])
34 [37, 3] ([1, 9, 27], [3])
35 [36, 1] ([9, 27], [1])
36 [36, 0] ([9, 27], [])
37 [37, 0] ([1, 9, 27], [])
38 [39, 1] ([3, 9, 27], [1])
39 [39, 0] ([3, 9, 27], [])
40 [40, 0] ([1, 3, 9, 27], [])

The basic operating principle, is that the problem is analog to converting a number into ternary. In Python, this is a one liner:

f=lambda i:i and i%3+f(i/3)*10

Of course, we're working in a slightly different base. Instead of the values 0, 1, 2 we use -1, 0, 1. This means when i%3 == 2, this should really be -1 (calculated by (i+1)%3-1 or -~i%3-1), and the value of the i sent to the next iteration needs to be adjusted accordingly.

More specifically, if d=(i+1)%3-1, then the value of i sent to the next iteration should be (i-d)/3. However, this calculaion can be simplified greatly using integer division, to just (i+1)//3. Rationale: if d == 0, then i was already a multiple of 3, and adding one won't change the integer quotient. If d == 1, then we should be subtracting 1 to make i a multiple of 3, but if we add 1 instead, it will now be 2 (mod 3), which won't change the integer quotient either. If however d == -1, then we do in fact need to add 1 to reach the next multiple of 3. Therefore, by using integer division, all three cases can be simplified to adding 1.

One thing that makes this problem interesting is that the negative and positive values need to be separated into different baskets. I decided the best way to accomplish this is to only collect the positive values, and then call the function again with -i, which will obviously have its stones reversed. This also allows me to save the -~i%3 calculation entirely, since I know what its value will be.


答:
Haskell, 25 bytes

f n=cycle"\\/"!!n<$[1..n]
```

-1 byte thanks to Damien with cycle.

Title: The Squiggly Sequence

Body:
Haskell, 25 bytes

f n=cycle"\\/"!!n<$[1..n]

-1 byte thanks to Damien with cycle.


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

答:
dc, <s>85</s> <s>78</s> 76 bytes

[pq]sq?ddsI[dddZ0sR[1-dsD10r^rdsN10%*lR+sRlN10/lDd0<@]ds@xlR++=q+lIrlLx]dsLx
```

<p><strong>Run:</strong></p>

<pre class="lang-sh prettyprint-override"><code>dc -f program.dc <<< "16"
</code>```

Output:

272
```

<p><strong>Previously submitted code and explanation:</strong></p>

<pre class="lang-dc prettyprint-override"><code>    # loads register 'q' with an exit function
[pq]sq
    # register '@' contains an iterative function to reverse a number (312 to 213),
#by calculating one coefficient at a time of the new base 10 polynomial
[1-dsD10r^rdsN10%*lR+sRlN10/lDd0<@]s@
    # register 'L' implements the logic. It iteratively compares the current value
#with the generated reversed one, exiting if equal, otherwise increments the value
#by N and repeats.
[dddZ0sRl@xlR++=q+lIrlLx]sL
    # the "main". It reads the input, then calls the solver function from 'L'.
?ddsIlLx
</code>```

Body:
dc, <s>85</s> <s>78</s> 76 bytes

[pq]sq?ddsI[dddZ0sR[1-dsD10r^rdsN10%*lR+sRlN10/lDd0<@]ds@xlR++=q+lIrlLx]dsLx

Run:

dc -f program.dc <<< "16"

Output:

272

Previously submitted code and explanation:

    # loads register 'q' with an exit function
[pq]sq
    # register '@' contains an iterative function to reverse a number (312 to 213),
#by calculating one coefficient at a time of the new base 10 polynomial
[1-dsD10r^rdsN10%*lR+sRlN10/lDd0<@]s@
    # register 'L' implements the logic. It iteratively compares the current value
#with the generated reversed one, exiting if equal, otherwise increments the value
#by N and repeats.
[dddZ0sRl@xlR++=q+lIrlLx]sL
    # the "main". It reads the input, then calls the solver function from 'L'.
?ddsIlLx


答:
05AB1E/2sable, <s>15</s> <s>11</s> <s>9</s> 8 bytes

```<code>DÈ„/\sè×
</code>```

-2 bytes thanks to Leaky Nun

-1 byte thanks to Emigna

Try it online! in 05AB1E

or in 2sable

Title: The Squiggly Sequence

Body:
All credits to Adnan for coming up with this challenge.

My last challenge, before I go on break.

Task

Given positive integer n, if n is odd, repeat / that many times; if n is even, repeat \ that many times.

(Seriously, the testcases would be much clearer than this description, so just look at the testcases.)

Specs

Any reasonable input/output format.

Standard loopholes apply.

Testcases

```<code>n output
1 /
2 \\
3 ///
4 \\\\
5 /////
6 \\\\\\
</code>```

Body:
05AB1E/2sable, <s>15</s> <s>11</s> <s>9</s> 8 bytes

DÈ„/\sè×

-2 bytes thanks to Leaky Nun

-1 byte thanks to Emigna

Try it online! in 05AB1E

or in 2sable


问:
Lucas Vs. The Garage Door Remote

Disclaimer

While I know there is this particular related question, my question uses two garage doors, a randomizing component, and I'm also basing this on real life events, seeing my son accidentally lowered one of said garage doors whilst I was walking out of the garage last week... Nothing like a blow to the head to get the creative juices flowing! ;)

The Background

Lucas (my 15 month old son) likes to play with the garage remote. There are two buttons on this remote, one for the left garage door, and one for the right garage door. Both buttons work in the same manner; press once to get the door to start opening, press again to stop, press again to start closing, press again to stop again, and so on.

Lucas loves this remote, he'll randomly press one of the buttons, or both, or none at all. If both are pressed, no signal is sent, but a press of one button will send out a signal.

So, the code-golf challenge is divided on two parts:

Part One

Generate a 60 character long string representing Lucas random button presses over a minute. "Random" in this case means "with an equal chance of each input at each tick". The characters are as follows:

0: Lucas has either pressed no button, or has pressed both buttons. Either way, no signal has been sent.

1: The button for the left garage door has been pressed by Lucas

2: The button for the right garage door has been pressed by Lucas

Part Two

Using the string generated in Part One, simulate the opening and closing of the two-car garage using the numbers as triggers for opening, stopping and closing these doors.

My garage doors are pretty quick (see Disclaimer above as to why).  Once you press the button it takes four seconds to be fully open or closed.

So, if closed:

0 sec: 0% open (closed); when button is pressed, door starts opening

1 sec: 25% open

2 sec: 50% open

3 sec: 75% open

4 sec: 100% open, door stops

And therefore, if open:

0 sec: 100% open; when button is pressed, door starts closing

1 sec: 75% open

2 sec: 50% open

3 sec: 25% open

4 sec: 0% open (closed), door stops

If a particular door is in motion, a signal to that same door will stop it. The next signal sent to that same door after that will send it moving in the opposite direction. If a door is stopped when it has previously been in motion and is now fully open or fully closed when the "stop" signal is received, the door will register as "stopped" in the fully-open or fully-closed state, ready to move in the opposite direction when it receives a new signal.

With this simulation, both garage doors will be initially in the closed position. So, let's look at a 10 second list of commands and see what happens if Lucas was to perform them on the remote:

```<code>2120221120
2: (L:0% stopped, R:0% opening)
1: (L:0% opening, R:25% opening)
2: (L:25% opening, R:50% stopped)
0: (L:50% opening, R:50% stopped)
2: (L:75% opening, R:50% closing)
2: (L:100% stopped, R:25% stopped)
1: (L:100% closing, R:25% stopped)
1: (L:75% stopped, R:25% stopped)
2: (L:75% stopped, R:25% opening)
0: (L:75% stopped, R:50% opening)
</code>```

Output

The first part of the output requires the display of the 60 character long string of random "0", "1" and "2" characters generated from Part One. eg.
212022112021202211202120221120212022112021202211202120221120

Below this string, is the processing of these "signals" according to the rules mentioned above of how the garage doors will behave with each respective character (on a second by second basis). You should end up with 60 lines as a result below the initial display string.

Each of these processed lines will be in the form of:
N: (L:X% XXXXXXX, R:Y% YYYYYYY) where:

N is the nth character from the respective random string, which will be in the form of a 0, 1, or 2.

X% is the percentage of openness of the left door (there is no zero padding)

XXXXXXX is the status of the left door. If the door is not in motion (i.e. not opening or closing) the status "stopped" is enforced, meaning it has been stopped in motion (only possible at 25%, 50% or 75%) or stopped when fully open (100%) or fully closed (0%). Otherwise, the door will either be "opening" or "closing".

Y% is the percentage of openness of the right door (there is no zero padding)

YYYYYYY is the status of the right door. If the door is not in motion (i.e. not opening or closing) the status "stopped" is enforced, meaning it has been stopped in motion (only possible at 25%, 50% or 75%) or stopped when fully open (100%) or fully closed (0%). Otherwise, the door will either be "opening" or "closing".

Example shown below using 10 "signals" and 10 processed lines

```<code>2120221120
2: (L:0% stopped, R:0% opening)
1: (L:0% opening, R:25% opening)
2: (L:25% opening, R:50% stopped)
0: (L:50% opening, R:50% stopped)
2: (L:75% opening, R:50% closing)
2: (L:100% stopped, R:25% stopped)
1: (L:100% closing, R:25% stopped)
1: (L:75% stopped, R:25% stopped)
2: (L:75% stopped, R:25% opening)
0: (L:75% stopped, R:50% opening)
</code>```

This is code-golf, so the shortest code will be the clear winner. I've made this a little easy by using phrases like "opening", "stopped" and "closing", which are all seven letters... so you may want to work that into your strategy.

Best of luck!

答:
Ruby, <s>263</s> <s>261</s> <s>260</s> 254 bytes

How did JavaScript's answer get so short??? It overtook mine while I was away and still is winning currently...

```<code>s=(1..60).map{rand 3}
puts s*''
D=1,2
d=[25]*3;a=[0]*3;m=[p]*3
s.map{|i|D.map{|j|m[j]&&a[j]+=d[j];(0..100)===a[j]+d[j]||i!=j&&(d[j]*=-1;m[j]=p)}
(m[i]^=1)||d[i]*=-1
puts"#{i}: (L%s, R%s)"%D.map{|j|":#{a[j]}% #{%w"stopped opening closing"[m[j]?d[j]:0]}"}}
</code>```

Title: Lucas Vs. The Garage Door Remote

Body:
Ruby, <s>263</s> <s>261</s> <s>260</s> 254 bytes

How did JavaScript's answer get so short??? It overtook mine while I was away and still is winning currently...

s=(1..60).map{rand 3}
puts s*''
D=1,2
d=[25]*3;a=[0]*3;m=[p]*3
s.map{|i|D.map{|j|m[j]&&a[j]+=d[j];(0..100)===a[j]+d[j]||i!=j&&(d[j]*=-1;m[j]=p)}
(m[i]^=1)||d[i]*=-1
puts"#{i}: (L%s, R%s)"%D.map{|j|":#{a[j]}% #{%w"stopped opening closing"[m[j]?d[j]:0]}"}}


答:
Retina, 21

```<code>.+
$*/
T`/`\\`^(..)+$
</code>```

Try it online (First line added to allow multiple testcases to be run).

Title: The Squiggly Sequence

Body:
Retina, 21

.+
$*/
T`/`\\`^(..)+$

Try it online (First line added to allow multiple testcases to be run).


问:
Invert png image
Create program or function that takes file name as an argument or reads it from standard input, and completes the following task:

Read image from a png file (name given as argument).

Reverse colors in that image, so that for example dark green (0, 75, 30) would become (255, 180, 225) (because 255-0=255, 255-75=180 and 255-30=225). You should not change alpha channel value.

Output that image to a file called a.png (in png format), or show it in GUI window.

This is code-golf. Standard loopholes apply.

答:
C + stb_image + stb_image_write, 175 162 bytes (or +72=247 234)

My first submission on this site ever.

```<code>#include"stb_image.h"
#include"stb_image_write.h"
x,y,c,i;f(char*d){d=stbi_load(d,&x,&y,&c,i=0);for(;i<x*y*c;i++)d[i]=255-d[i];stbi_write_png("a.png",x,y,c,d,0);}
</code>```

Could probably shave off a few bytes. Needs stb_* implementation to either be in a separate library, or at the start of this file with:

```<code>#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_WRITE_IMPLEMENTATION
</code>```

I didn't include it in the count because it's essentially part of the library (esp. if it's compiled separately). +72 bytes to add that if required, however.

Update 1:

Realized only a function (as opposed to an entire program) is acceptable, shaving off 15 bytes. The old implementation (which is an entire program), for reference:

```<code>x,y,i;main(int c,char**d){*d=stbi_load(d[1],&x,&y,&c,0);for(;i<x*y*c;i++)i[*d]=255-i[*d];stbi_write_png("a.png",x,y,c,*d,0);}
</code>```

Title: Invert png image

Body:
C + stb_image + stb_image_write, 175 162 bytes (or +72=247 234)

My first submission on this site ever.

#include"stb_image.h"
#include"stb_image_write.h"
x,y,c,i;f(char*d){d=stbi_load(d,&x,&y,&c,i=0);for(;i<x*y*c;i++)d[i]=255-d[i];stbi_write_png("a.png",x,y,c,d,0);}

Could probably shave off a few bytes. Needs stb_* implementation to either be in a separate library, or at the start of this file with:

#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_WRITE_IMPLEMENTATION

I didn't include it in the count because it's essentially part of the library (esp. if it's compiled separately). +72 bytes to add that if required, however.

Update 1:

Realized only a function (as opposed to an entire program) is acceptable, shaving off 15 bytes. The old implementation (which is an entire program), for reference:

x,y,i;main(int c,char**d){*d=stbi_load(d[1],&x,&y,&c,0);for(;i<x*y*c;i++)i[*d]=255-i[*d];stbi_write_png("a.png",x,y,c,*d,0);}


问:
Sylvester's sequence
Sylvester's sequence, OEIS A000058, is an integer sequence defined as follows:

Each member is the product of all previous members plus one.  The first member of the sequence is 2.

Task

Create a program to calculate the nth term of Sylvester's Sequence.  Standard input, output and loopholes apply.

Standard sequence rules apply.

This is code-golf, so the goal is to minimize the size of your source code as measured in bytes.

Test Cases

You may use either zero or one indexing. (Here I use zero indexing)

```<code>>>0
2
>>1
3
>>2
7
>>3
43
>>4
1807
</code>```

答:
Oasis, 4 bytes

Probably my last language from the golfing family! <s>Non-competing, since the language postdates the challenge.</s>

Code:

```<code>²->2
</code>```

Alternative solution thanks to Zwei:

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

Expanded version:

```<code>a(n) = ²->
a(0) = 2
</code>```

Explanation:

```<code>²    # Stack is empty, so calculate a(n - 1) ** 2.
 -   # Subtract, arity 2, so use a(n - 1).
  >  # Increment by 1.
</code>```

Uses the CP-1252 encoding. Try it online!

Title: Sylvester's sequence

Body:
Oasis, 4 bytes

Probably my last language from the golfing family! <s>Non-competing, since the language postdates the challenge.</s>

Code:

²->2

Alternative solution thanks to Zwei:

<*>2

Expanded version:

a(n) = ²->
a(0) = 2

Explanation:

²    # Stack is empty, so calculate a(n - 1) ** 2.
 -   # Subtract, arity 2, so use a(n - 1).
  >  # Increment by 1.

Uses the CP-1252 encoding. Try it online!


Title: The Squiggly Sequence

Body:
Perl 6, 16 bytes

{<\ />[$_%2]x$_}

Usage:

for 1..6 {
  say $_, {<\ />[$_%2]x$_}( $_ )
}

1/
2\\
3///
4\\\\
5/////
6\\\\\\


答:
Mathematica, <s>34</s> <s>32</s> 28 bytes

```<code>If[OddQ@#,"/","\\"]~Table~#&
</code>```

Anonymous function. Takes an integer as input and returns a list of characters as output.

Title: The Squiggly Sequence

Body:
Mathematica, <s>34</s> <s>32</s> 28 bytes

If[OddQ@#,"/","\\"]~Table~#&

Anonymous function. Takes an integer as input and returns a list of characters as output.


答:
Perl

This one looks funny for me :

```<code>perl -pe '$_="~"ge$_?"/":"\\"' </dev/urandom
</code>```

(Sorry to be out of subject here. I know this is not PHP)

Title: 10 PRINT CHR$(205.5+RND(1)); : GOTO 10 in PHP (or anything else, for that matter)

Body:
Just had a 'spirited' conversation with a co-worker about the succinctness of the following BASIC statement:

```<code>10 PRINT CHR$(205.5+RND(1)); : GOTO 10
</code>```

It's the title of this book, and will simply print a sequence of / and \ characters, alternating between the two randomly, resulting in a pattern similar to this:

(Image borrowed from http://www.flickr.com/photos/rndmcnlly/5058442151/sizes/o/in/photostream/)

Being of a PHP proclivity, we wondered what the most compact way of writing the same thing in PHP would be, and came up with this:

```<code>while(1) { echo chr(47 + 45 * rand(0,1)); }
</code>```

chr(47) is a / character, and chr(92) is a \. So the statement echo chr(47 + 45 * rand(0,1)); will randomly alternate between the two, ad nauseam.

In a language of your choosing, write the shortest program or function to output an infinite random sequence of \ and / characters, where each character has an equal probability of being chosen.

Body:
Perl

This one looks funny for me :

perl -pe '$_="~"ge$_?"/":"\\"' </dev/urandom

(Sorry to be out of subject here. I know this is not PHP)


问:
Can you beat the British Intelligence? (Nonogram Solver)
It is time to embark on a perilous quest to defeat the British Intelligence. The aim of this challenge is to write the shortest code that will solve a Nonogram.

What is a Nonogram?

The rules are simple.
  You have a grid of squares, which must be either filled in black or left blank. Beside each row of the grid are listed the lengths of the runs of black squares on that row. Above each column are listed the lengths of the runs of black squares in that column. Your aim is to find all black squares. In this puzzle type, the numbers are a form of discrete tomography that measures how many unbroken lines of filled-in squares there are in any given row or column. For example, a clue of "4 8 3" would mean there are sets of four, eight, and three filled squares, in that order, with at least one blank square between successive groups.
   [1][2]

So the solution to the above Nonogram would be:

Implementation Details

You can chose to represent the Nonogram however you would like and take it as an input in whatever way you deem fit for your language. Same goes for output. The aim of this challenge is to literally just get the job done; if you can solve the nonogram with whatever output your program gives, that is valid. One caveat is you can't use an online solver :)

This problem is very algorithmically challenging (np-complete) in that there is no completely efficient solution to it and as such, you won't be penalized for not being able to solve larger ones, although your answer will be heavily rewarded if it is able to handle big cases (see bonus). As a benchmark, my solution works for up to roughly 25x25 within 5-10 seconds. To allow for flexibility amongst different languages, solutions that take less than 5 mins for a 25x25 nonogram are good enough.

You may assume a puzzle in always a square NxN nonogram.

You can use this online nonogram puzzle maker to test your solutions.

Scoring

You are, of course, free to use any language you want and since this is code golf, the entries will be sorted in the order: accuracy -> length of code -> speed. However, don't be discouraged by code golfing languages, answers in all languages that show attempts at golfing in an interesting way will be upvoted!

Bonus

I actually learnt about Nonograms from a cryptographic Christmas card released by the British Intelligence here. The first part was basically a massive 25x25 Nonogram. If your solution is able to solve this, you will get kudos :)

To make your life easier in terms of data entry, I have provided how I represented the data for this specific puzzle for your free use. The first 25 lines are the row clues, followed by a '-' separator line, followed by 25 lines of the col clues, followed by a '#' separator line, and then a representation of the grid with the square clues filled in.

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

And here is a slightly different version for your convenience; a comma separated tuple (row, col) where each element is list of lists.

```<code>([[7, 3, 1, 1, 7],
  [1, 1, 2, 2, 1, 1],
  [1, 3, 1, 3, 1, 1, 3, 1],
  [1, 3, 1, 1, 6, 1, 3, 1],
  [1, 3, 1, 5, 2, 1, 3, 1],
  [1, 1, 2, 1, 1],
  [7, 1, 1, 1, 1, 1, 7],
  [3, 3],
  [1, 2, 3, 1, 1, 3, 1, 1, 2],
  [1, 1, 3, 2, 1, 1],
  [4, 1, 4, 2, 1, 2],
  [1, 1, 1, 1, 1, 4, 1, 3],
  [2, 1, 1, 1, 2, 5],
  [3, 2, 2, 6, 3, 1],
  [1, 9, 1, 1, 2, 1],
  [2, 1, 2, 2, 3, 1],
  [3, 1, 1, 1, 1, 5, 1],
  [1, 2, 2, 5],
  [7, 1, 2, 1, 1, 1, 3],
  [1, 1, 2, 1, 2, 2, 1],
  [1, 3, 1, 4, 5, 1],
  [1, 3, 1, 3, 10, 2],
  [1, 3, 1, 1, 6, 6],
  [1, 1, 2, 1, 1, 2],
  [7, 2, 1, 2, 5]],
 [[7, 2, 1, 1, 7],
  [1, 1, 2, 2, 1, 1],
  [1, 3, 1, 3, 1, 3, 1, 3, 1],
  [1, 3, 1, 1, 5, 1, 3, 1],
  [1, 3, 1, 1, 4, 1, 3, 1],
  [1, 1, 1, 2, 1, 1],
  [7, 1, 1, 1, 1, 1, 7],
  [1, 1, 3],
  [2, 1, 2, 1, 8, 2, 1],
  [2, 2, 1, 2, 1, 1, 1, 2],
  [1, 7, 3, 2, 1],
  [1, 2, 3, 1, 1, 1, 1, 1],
  [4, 1, 1, 2, 6],
  [3, 3, 1, 1, 1, 3, 1],
  [1, 2, 5, 2, 2],
  [2, 2, 1, 1, 1, 1, 1, 2, 1],
  [1, 3, 3, 2, 1, 8, 1],
  [6, 2, 1],
  [7, 1, 4, 1, 1, 3],
  [1, 1, 1, 1, 4],
  [1, 3, 1, 3, 7, 1],
  [1, 3, 1, 1, 1, 2, 1, 1, 4],
  [1, 3, 1, 4, 3, 3],
  [1, 1, 2, 2, 2, 6, 1],
  [7, 1, 3, 2, 1, 1]])
</code>```

答:
Pyth, <s>91</s> <s>72</s> 71 bytes

```<code>D:GHdRq@@QdG.nCf.)TrH8V^,01^hQ2=TcNhQ=Y1VhQ=*Y*:H@TH1:H@CTH2)IYjbmjkdTb
</code>```

A program that takes input of a list of the form [size, [horizontal clues], [vertical clues]] where each clue is a list of integers (empty clues are the empty list, []), and prints every solution, newline separated, in the form of a binary grid where 1 is shaded and 0 is unshaded.

This is a brute force, so is roughly O(2^n^2). It starts taking a very long time for larger puzzles, but will solve any arbritrary size given sufficient time.

Try it online

How it works

The program generates every possible layout by taking the repeated Cartesian product of [0, 1] with a length equal to size^2. This is then split into chunks, giving a list for each horizontal line. Each line is run-length encoded, filtered by the presence of 1 and flattened, leaving the clue for that line. This is then checked against the input. The above process is repeated for the transpose of the chunks, checking the vertical lines. If there is a hit, each chunk is concatenated, and the concatenated chunks are joined on newlines and implicitly printed, with a trailing newline.

```<code>D:GHdRq@@QdG.nCf.)TrH8V^,01^hQ2=TcNhQ=Y1VhQ=*Y*:H@TH1:H@CTH2)IYjbmjkdTb  Program. Input: Q
                            hQ                                           Q[0], size
                           ^  2                                          Square
                        ,01                                              [0, 1]
                       ^                                                 Cartesian product
                      V                                     )            For N in the Cartesian product:
                                 cNhQ                                    Split N into Q[0] chunks
                               =T                                        Assign that to T
                                     =Y1                                 Y=1
                                        VhQ                              For H in range [0, Q[0]-1]:
D:GHd                                                                     def :(G, H, d)
                   rH8                                                     Run-length-encode(H)
               f.)T                                                        Filter by presence of 1 in character part
            .nC                                                            Transpose and flatten, giving the clue
       @@QdG                                                               Q[d][G], the relevant input clue
     Rq                                                                    Return clue==input clue
                                               :H@TH1                     :(H, T, 1)
                                                     :H@CTH2              :(H, transpose(T), 2)
                                           =*Y*                           Y=Y*product of above two
                                                             IY           If Y:
                                                                 mjkdT     Conacatenate each element of T
                                                               jb          Join on newlines
                                                                      b    Add a newline and implicitly print
</code>```

Thanks to @Pietu1998 for some tips

Body:
Pyth, <s>91</s> <s>72</s> 71 bytes

D:GHdRq@@QdG.nCf.)TrH8V^,01^hQ2=TcNhQ=Y1VhQ=*Y*:H@TH1:H@CTH2)IYjbmjkdTb

A program that takes input of a list of the form [size, [horizontal clues], [vertical clues]] where each clue is a list of integers (empty clues are the empty list, []), and prints every solution, newline separated, in the form of a binary grid where 1 is shaded and 0 is unshaded.

This is a brute force, so is roughly O(2^n^2). It starts taking a very long time for larger puzzles, but will solve any arbritrary size given sufficient time.

Try it online

How it works

The program generates every possible layout by taking the repeated Cartesian product of [0, 1] with a length equal to size^2. This is then split into chunks, giving a list for each horizontal line. Each line is run-length encoded, filtered by the presence of 1 and flattened, leaving the clue for that line. This is then checked against the input. The above process is repeated for the transpose of the chunks, checking the vertical lines. If there is a hit, each chunk is concatenated, and the concatenated chunks are joined on newlines and implicitly printed, with a trailing newline.

D:GHdRq@@QdG.nCf.)TrH8V^,01^hQ2=TcNhQ=Y1VhQ=*Y*:H@TH1:H@CTH2)IYjbmjkdTb  Program. Input: Q
                            hQ                                           Q[0], size
                           ^  2                                          Square
                        ,01                                              [0, 1]
                       ^                                                 Cartesian product
                      V                                     )            For N in the Cartesian product:
                                 cNhQ                                    Split N into Q[0] chunks
                               =T                                        Assign that to T
                                     =Y1                                 Y=1
                                        VhQ                              For H in range [0, Q[0]-1]:
D:GHd                                                                     def :(G, H, d)
                   rH8                                                     Run-length-encode(H)
               f.)T                                                        Filter by presence of 1 in character part
            .nC                                                            Transpose and flatten, giving the clue
       @@QdG                                                               Q[d][G], the relevant input clue
     Rq                                                                    Return clue==input clue
                                               :H@TH1                     :(H, T, 1)
                                                     :H@CTH2              :(H, transpose(T), 2)
                                           =*Y*                           Y=Y*product of above two
                                                             IY           If Y:
                                                                 mjkdT     Conacatenate each element of T
                                                               jb          Join on newlines
                                                                      b    Add a newline and implicitly print

Thanks to @Pietu1998 for some tips


问:
Hofstadter H-sequence

Definition

\$a(0) = 0\$

\$a(n) = n-a(a(a(n-1)))\$ for integer \$n > 0\$

Task

Given non-negative integer \$n\$, output \$a(n)\$.

Testcases

```<code>n     a(n)
0     0
1     1
2     1
3     2
4     3
5     4
6     4
7     5
8     5
9     6
10    7
11    7
12    8
13    9
14    10
15    10
16    11
17    12
18    13
19    13
20    14
10000 6823
</code>```

References

WolframMathWorld

OEIS A005374

答:
Oasis, 6 bytes

Code:

```<code>nbaa-0
</code>```

Expanded version:

```<code>a(n) = nbaa-
a(0) = 0
</code>```

Code:

```<code>n      # Push n
 b     # Calculate a(n - 1)
  a    # Calculate a(a(n - 1))
   a   # Calculate a(a(a(n - 1)))
    -  # Subtract a(a(a(n - 1))) from n
</code>```

Try it online!

Title: Hofstadter H-sequence

Body:
Oasis, 6 bytes

Code:

nbaa-0

Expanded version:

a(n) = nbaa-
a(0) = 0

Code:

n      # Push n
 b     # Calculate a(n - 1)
  a    # Calculate a(a(n - 1))
   a   # Calculate a(a(a(n - 1)))
    -  # Subtract a(a(a(n - 1))) from n

Try it online!


问:
Draw the Union Jack

Preface

There are many "draw x flag" challenges, and upon searching it turns out there are no challenges to draw the union Jack! I feel like this would be a harder flag to draw but it should still be possible.

Challenge

Draw the Union Jack. It can be outputted to a file in any freely available graphics file format or drawn onto the screen.

Code Golf rules apply, shortest code in bytes wins.

Standard loopholes apply.

No builtins for flag drawing allowed.

Dimensions shall be as below. Minimum size 600x300 pixels (or units if your language supports only scalable graphics.) Maximum error 1 pixel.

Colours shall be red, white and blue as defined by your language or its documentation, or #CC0000, #FFFFFF and #003399 per Wikipedia page.

答:
Logo, <s>260</s> 239 bytes

(XLogo Interpreter)

I used the Java-based XLogo interpreter since it was one of the few Logo implementations I could find which supports setting the output window size.

The XLogo editor normally saves files as procedures which are meant to be called.  This program is written to be pasted into the immediate window instead.  This saves about 9 bytes.

```<code>window setscreensize[600 300]setsc 4 lt atan 2 repeat 2[repeat 2[setpc 7 setpw 60 fd 400 setpw 20 lt 90 fd 10 lt 90 setpc 1 fd 400 lt 90 fd 10 rt 90]lt asin .8]home wrap setpw 100 setpc 7 repeat 2[repeat 2[fd 600 lt 90]setpw 60 setpc 1] ht
</code>```

Since exact colors weren't required, I regolfed this to use built-in color numbers which saved several bytes.  If you want to see a version with exact RGB colors, check the revisions.  I also substituted a trigonometric calculation with a shorter equivalent.

Ungolfed with commentary

The only real trickery here is changing colors for the second pass of a loop, and taking advantage of the wrap feature which allows us to draw the horizontal stripes with very little effort.  Since the flag height and width are both factors of 600, we can go forward 600 for either vertical or horizontal stripes and end up back at the center again.  This avoids having separate cases for each, even if it does draw the vertical bar twice as often.  We're saving code space, not clock-cycles.

```<code>to UnionJack
  #Initialize the screen
  window  #Allow the turtle to overshoot the boundary without reappearing on the opposite side
  setscreensize[600 300]
  setsc 4  #blue background

  lt atan 2 #Turn left, preparing to draw first diagonal
  repeat 2 [ #Draw 2 sets of main diagonal bars
    repeat 2 [ #Each main bar is made of 2 spokes
      setpc 7 setpw 60 #Use a wide white pen
      fd 400 #Draw past the corner of the window
      setpw 20 #Make the pen narrow
      lt 90 fd 10 lt 90 #Do a 10px U-turn
      setpc 1 #Switch to a red pen
      fd 400 #Draw back to the center.
      lt 90 fd 10 rt 90 #Do a 10 px S curve back to center, ready to draw the opposite spoke
    ] #Finish spoke
    lt asin .8 #Turn for the next bar.
  ] #Finish bar
  home #Return to a sane heading
  wrap #Makes the turtle wrap to the opposite side if it overshoots the boundary
  setpw 100 setpc 7 #Wide white pen
  repeat 2 [ #Draw 2 crosses
    repeat 2 [ #Each cross has 2 stripes
      fd 600 #Overshoot the boundary so that we end up where we started at the center, leaving a stripe behind
      lt 90 #Rotate to draw the next stripe
    ] #Finish the stripe
    setpw 60 setpc 1 #Change to a narrow red pen
  ] #Finish cross
  ht #Hide the turtle
end
</code>```

Title: Draw the Union Jack

Body:
Logo, <s>260</s> 239 bytes

(XLogo Interpreter)

I used the Java-based XLogo interpreter since it was one of the few Logo implementations I could find which supports setting the output window size.

The XLogo editor normally saves files as procedures which are meant to be called.  This program is written to be pasted into the immediate window instead.  This saves about 9 bytes.

window setscreensize[600 300]setsc 4 lt atan 2 repeat 2[repeat 2[setpc 7 setpw 60 fd 400 setpw 20 lt 90 fd 10 lt 90 setpc 1 fd 400 lt 90 fd 10 rt 90]lt asin .8]home wrap setpw 100 setpc 7 repeat 2[repeat 2[fd 600 lt 90]setpw 60 setpc 1] ht

Since exact colors weren't required, I regolfed this to use built-in color numbers which saved several bytes.  If you want to see a version with exact RGB colors, check the revisions.  I also substituted a trigonometric calculation with a shorter equivalent.

Ungolfed with commentary

The only real trickery here is changing colors for the second pass of a loop, and taking advantage of the wrap feature which allows us to draw the horizontal stripes with very little effort.  Since the flag height and width are both factors of 600, we can go forward 600 for either vertical or horizontal stripes and end up back at the center again.  This avoids having separate cases for each, even if it does draw the vertical bar twice as often.  We're saving code space, not clock-cycles.

to UnionJack
  #Initialize the screen
  window  #Allow the turtle to overshoot the boundary without reappearing on the opposite side
  setscreensize[600 300]
  setsc 4  #blue background

  lt atan 2 #Turn left, preparing to draw first diagonal
  repeat 2 [ #Draw 2 sets of main diagonal bars
    repeat 2 [ #Each main bar is made of 2 spokes
      setpc 7 setpw 60 #Use a wide white pen
      fd 400 #Draw past the corner of the window
      setpw 20 #Make the pen narrow
      lt 90 fd 10 lt 90 #Do a 10px U-turn
      setpc 1 #Switch to a red pen
      fd 400 #Draw back to the center.
      lt 90 fd 10 rt 90 #Do a 10 px S curve back to center, ready to draw the opposite spoke
    ] #Finish spoke
    lt asin .8 #Turn for the next bar.
  ] #Finish bar
  home #Return to a sane heading
  wrap #Makes the turtle wrap to the opposite side if it overshoots the boundary
  setpw 100 setpc 7 #Wide white pen
  repeat 2 [ #Draw 2 crosses
    repeat 2 [ #Each cross has 2 stripes
      fd 600 #Overshoot the boundary so that we end up where we started at the center, leaving a stripe behind
      lt 90 #Rotate to draw the next stripe
    ] #Finish the stripe
    setpw 60 setpc 1 #Change to a narrow red pen
  ] #Finish cross
  ht #Hide the turtle
end


答:
J, <s>20</s> <s>18</s> 17 bytes

```<code>(>:({~?@#)@##\)"1
</code>```

The image is input as an array with dimensions h x w x 3 representing the RGB values as integers in the range 0 - 255. The output is a table with dimensions h x w where 1 is an rgb value of (255, 0, 0), 2 is (0, 255, 0), and 3 is (0, 0, 255).

Explanation

The ()"1 represents that this  verb is to be applied to each array of rank 1 in the input, meaning that it will apply to each pixel.

```<code>>:({~?@#)@##\  Input: array [R G B]
>:             Increment each, gets [R+1, G+1, B+1]
           #\  Gets the length of each prefix of [R G B], forms [1 2 3]
          #    Make a new array with R+1 copies of 1, G+1 copies of 2,
               and B+1 copies of 3
  (     )@     Operate on that array
       #         Get the length of the array of copies, will be R+G+B+3
     ?@          Generate a random integer in the range [0, R+G+B+3)
   {~            Select the value at that index from the array of copies and return
</code>```

Title: Quixels - Quantum Pixels

Body:
Introduction

A quixel is a quantum pixel. Similar to a classical pixel, it is represented with 3 integer values (Red, Green, Blue). However, quixels are in a super position of these 3 states instead of a combination. This super position only lasts until the quixel is observed at which point it collapses to one of three classical pixels; RGB(255,0,0), RGB(0,255,0) and RGB(0,0,255).

Specification

Representation

Each quixel is represented as an array of 3 integers between 0 and 255, r, g and b respectively.

Super Positions

Each quixel is in a super position between the Red, Blue and Green states represented by R, G and B respectively.

Observation

When each quixel is observed it collapses into one of the three states. The probability of each classical state is R = (r + 1) / (r + g + b +3), G = (g + 1) / (r + g + b + 3) and B = (b + 1) / (r + g + b + 3). This way each classical state always as a non-zero probability of showing up.

Input

The function or program should take a image of quixels. How it does this is flexible. A filename, using a multi-dimensional array, etc are all acceptable.

Output

The function or program should produce an image of classical pixels. The data structure for this produced image is also flexible. Note that all of the pixels should be one of these three: RGB(255,0,0), RGB(0,255,0) and RGB(0,0,255)

The output should not be deterministic; these are quantum pixels! The same input should result in different outputs.

If your language has no way of generating a random number, you can take random bytes as input

Scoring

This is code-golf so fewest bytes win.

Images

Mona Lisa by Leonardo da Vinci

Starry Night by Vincent van Gogh

Persistence of Memory by Salvador Dali

Teddy Roosevelt VS. Bigfoot by SharpWriter

Body:
J, <s>20</s> <s>18</s> 17 bytes

(>:({~?@#)@##\)"1

The image is input as an array with dimensions h x w x 3 representing the RGB values as integers in the range 0 - 255. The output is a table with dimensions h x w where 1 is an rgb value of (255, 0, 0), 2 is (0, 255, 0), and 3 is (0, 0, 255).

Explanation

The ()"1 represents that this  verb is to be applied to each array of rank 1 in the input, meaning that it will apply to each pixel.

>:({~?@#)@##\  Input: array [R G B]
>:             Increment each, gets [R+1, G+1, B+1]
           #\  Gets the length of each prefix of [R G B], forms [1 2 3]
          #    Make a new array with R+1 copies of 1, G+1 copies of 2,
               and B+1 copies of 3
  (     )@     Operate on that array
       #         Get the length of the array of copies, will be R+G+B+3
     ?@          Generate a random integer in the range [0, R+G+B+3)
   {~            Select the value at that index from the array of copies and return


答:
Pip, 8 bytes

```<code>"\/"@aXa
</code>```

Straightforward. Uses modular indexing to select the character and string repetition to multiply it. Try it online!

This question presents an interesting comparison between Pip, Pyth, and Jelly, the latter two each having scored 5 bytes. All three languages have implicit output, with single-char operators for modular indexing and string repetition, and no requirement to escape backslashes in strings. There are two key differences, though:

Under certain circumstances, Pyth and Jelly need only one delimiter to define a string;

Pyth and Jelly have syntax such that the input doesn't need to be explicitly represented in the code (though for very different reasons, as Maltysen explained to me).

Neither one of these features is likely to show up in Pip1 (I don't like the aesthetics of unbalanced delimiters, and point-free syntax or implicit operands seem like they would be too alien to my infix expression parser), but I'm okay with playing third fiddle. Even though "readability" is extremely relative when golfing, I'd argue that those three extra bytes make the Pip program a lot easier to understand at a glance--and in my book, that's a worthwhile tradeoff.

1 Although, single-character strings in Pip use a single ' delimiter, inspired by CJam and by quoting in Lisp.

Title: The Squiggly Sequence

Body:
Pip, 8 bytes

"\/"@aXa

Straightforward. Uses modular indexing to select the character and string repetition to multiply it. Try it online!

This question presents an interesting comparison between Pip, Pyth, and Jelly, the latter two each having scored 5 bytes. All three languages have implicit output, with single-char operators for modular indexing and string repetition, and no requirement to escape backslashes in strings. There are two key differences, though:

Under certain circumstances, Pyth and Jelly need only one delimiter to define a string;

Pyth and Jelly have syntax such that the input doesn't need to be explicitly represented in the code (though for very different reasons, as Maltysen explained to me).

Neither one of these features is likely to show up in Pip1 (I don't like the aesthetics of unbalanced delimiters, and point-free syntax or implicit operands seem like they would be too alien to my infix expression parser), but I'm okay with playing third fiddle. Even though "readability" is extremely relative when golfing, I'd argue that those three extra bytes make the Pip program a lot easier to understand at a glance--and in my book, that's a worthwhile tradeoff.

1 Although, single-character strings in Pip use a single ' delimiter, inspired by CJam and by quoting in Lisp.


Title: The Squiggly Sequence

Body:
Julia, 20 bytes

!x="$("/\\"[x%2])"^x


答:
RETURN, 21 bytes

```<code>[$2÷%'/'\2øø4ø2␂{␋},]
</code>```

Try it here.

Anonymous lambda. Usage:

```<code>5[$2÷%'/'\2øø4ø2␂{␋},]!
</code>```

Explanation

```<code>[                    ]  [lambda]%
 $2÷%                   [copy input and mod 2]%
     '/'\2øø            [choose either / or \ depending on input mod 2]%
            4ø          [get input again]%
              2␂{      [copy the /\ char and the input into a new stack]%
                  ␋},   [repeat the stack by the input and output the stack]%
</code>```

Title: The Squiggly Sequence

Body:
RETURN, 21 bytes

[$2÷%'/'\2øø4ø2␂{␋},]

Try it here.

Anonymous lambda. Usage:

5[$2÷%'/'\2øø4ø2␂{␋},]!

Explanation

[                    ]  [lambda]%
 $2÷%                   [copy input and mod 2]%
     '/'\2øø            [choose either / or \ depending on input mod 2]%
            4ø          [get input again]%
              2␂{      [copy the /\ char and the input into a new stack]%
                  ␋},   [repeat the stack by the input and output the stack]%


问:
Output "Fit" numbers

"Fit Numbers"

Sam has a "brilliant" idea for compression! Can you help?

Here is a rundown of Sam's compression scheme. First take in a base 10 representation of any natural number strictly smaller than 2^16, and write it as a binary string without any leading zeros.

```
1 -> 1
9 -> 1001
15 ->1111
13 ->1101
16 -> 10000
17 -> 10001
65535 -> 111111111111111
```

Now replace any group of one or more zeros with a single zero. This is because the number has gotten leaner. Your binary string now will look like this.

```
1 -> 1 -> 1
9 -> 1001 -> 101
15 ->1111 -> 1111
13 ->1101 -> 1101
16 -> 10000 -> 10
17 -> 10001 -> 101
65535 -> 111111111111111 -> 111111111111111
```

Now you convert the binary string back to a base 10 representation, and output it in any acceptable format. Here are your test cases. The first integer represents an input, and the last integer represents an output. Note that some numbers do not change, and thus can be called "fit"

```
1 -> 1 -> 1 -> 1
9 -> 1001 -> 101 -> 5
15 ->1111 -> 1111 -> 15
13 ->1101 -> 1101 -> 13
16 -> 10000 -> 10 -> 2
17 -> 10001 -> 101 -> 5
65535 -> 1111111111111111 -> 1111111111111111 -> 65535
65000 -> 1111110111101000 -> 11111101111010 -> 16250
```

You may use any language, but please note that Sam hates standard loopholes. This is code golf so the code can be as short as possible to make room for the "compressed" numbers".

Note:This is NOT an acceptable compression scheme. Using this will promptly get you fired.

Citation-Needed: I do not take credit for this concept. This comes from @Conor O' Brien's blog here see this OEIS of fit numbers. https://oeis.org/A090078

答:
Oasis, 25 bytes (non-competing)

```<code>n2÷an»»n»4÷xx-p>*nn2÷x-+0
</code>```

Try it online!

I have not failed my master. \o/

There are many missing features which must be built. For example, there is no conditionals, so the formula I am using would be f(n/2)*[1+(n%4>0)] + n%2.

Actually, there is no modulo either, so n%2 is implemented as n-(n/2*2) where / is integer division.

I did not mention n%4, because there is no > either. The > in the code means +1. So, n%4>0 is built from is_prime(((n+2)%4)+2) where the modulo is generated as above.

Title: Output "Fit" numbers

Body:
Oasis, 25 bytes (non-competing)

n2÷an»»n»4÷xx-p>*nn2÷x-+0

Try it online!

I have not failed my master. \o/

There are many missing features which must be built. For example, there is no conditionals, so the formula I am using would be f(n/2)*[1+(n%4>0)] + n%2.

Actually, there is no modulo either, so n%2 is implemented as n-(n/2*2) where / is integer division.

I did not mention n%4, because there is no > either. The > in the code means +1. So, n%4>0 is built from is_prime(((n+2)%4)+2) where the modulo is generated as above.