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

答:
UncleScrooge, Java

```<code>import java.util.List;
import com.ppcg.stockexchange.*;

public class UncleScrooge extends Player {
    public Offer acceptOffer(List<Offer> offers) {
        Offer offer;
        try {
            offer = offers.get(0);
        } catch (Exception ex) {
            return null;
        }
        if (offer.getPayment() < 100)
            return offer;
        else
            return null;
    }
    public Offer makeOffer(List<Stock> currentStock){
        if (this.getRandom().nextDouble() < 0.6)
            return new Offer(currentStock.get(secretStockType).setAmount(1), Integer.MAX_VALUE);
        else
            return null;
    }
    public void secretValue(int stockType, int value) {
        super.secretValue(stockType, value);
    }
    public void acceptedOffers(List<Offer> acceptedOffers) { }
}
</code>```

Sell stock at a really high price, and only buy if the price is less than 100.

Title: Stock Exchange KoTH

Body:
UncleScrooge, Java

import java.util.List;
import com.ppcg.stockexchange.*;

public class UncleScrooge extends Player {
    public Offer acceptOffer(List<Offer> offers) {
        Offer offer;
        try {
            offer = offers.get(0);
        } catch (Exception ex) {
            return null;
        }
        if (offer.getPayment() < 100)
            return offer;
        else
            return null;
    }
    public Offer makeOffer(List<Stock> currentStock){
        if (this.getRandom().nextDouble() < 0.6)
            return new Offer(currentStock.get(secretStockType).setAmount(1), Integer.MAX_VALUE);
        else
            return null;
    }
    public void secretValue(int stockType, int value) {
        super.secretValue(stockType, value);
    }
    public void acceptedOffers(List<Offer> acceptedOffers) { }
}

Sell stock at a really high price, and only buy if the price is less than 100.


问:
Climbing binomial tree to find the option value

Background:

In finance, the binomial options pricing model (BOPM) is the simplest technique used for option pricing. The mathematics behind the model is relatively easy to understand and (at least in their basic form) it is not difficult to implement. This model was first proposed by Cox, Ross, and Rubinstein in 1979. Quoting Wikipedia:

The binomial pricing model traces the evolution of the option's key underlying variables in discrete-time. This is done by means of a binomial lattice (tree), for a number of time steps between the valuation and expiration dates. Each node in the lattice represents a possible price of the underlying at a given point in time.

Valuation is performed iteratively, starting at each of the final nodes (those that may be reached at the time of expiration), and then working backwards through the tree towards the first node (valuation date). The value computed at each stage is the value of the option at that point in time.

For this challenge's sake, we will create a simple model to predict potential future prices of the option(s) by creating a lattice or a tree as shown below (a picture is worth a thousand words):

where S is the option price today, p is the probability of a price rise, and t is the period of time or number of steps.

Challenge:

The challenge is to write either a program or a function which take S, p (in percent), and t as the inputs and give the binomial tree as the output. The output of the program or the function must follow the format above, but the boxes and the arrow lines are optional. For example, if the program take inputs S = 100, p = 10%, and t = 3, then its output may be in the following simple form:

```<code>                        133.1
                121
        110             108.9
100              99
         90              89.1
                 81
                         72.9
</code>```

General rules:

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

Don't let esolangs discourage you from posting an answer with regular languages. Enjoy this challenge by providing an answer as short as possible with your programming language. If you post a clever answer and a clear explanation, your answer will be appreciated (hence the upvotes) regardless of the programming language you use.

Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/ method with the proper parameters, full programs, etc. The choice is yours.

Using a binomial tree built-in is forbidden.

If possible, your program can properly handle a large number of steps. If not, that will just be fine.

References:

Binomial options pricing model

Binomial tree option calculator

答:
Dyalog APL, <s>60</s> 56 bytes

Needs ⎕IO←0 which is default on many systems. Prompts for S then t then p.

⍉{⍵⌽⍨-⌽⍳≢⍵}↑{⍵\⍨0 1⍴⍨2×≢⍵}¨⍕¨¨⎕{⍵,⊂∪∊(⊃⌽⍵)∘.×1+⍺,-⍺}⍣⎕⊢⎕
```
<p>Over 50% of the code is to get the right display form.</p>
<p>TryAPL online! (<code>]Box off</code> for proper display – the default on installed systems – emulated here using <code>⍕</code>.)</p>
<p>Example run:</p>
<pre class="lang-apl prettyprint-override"><code>                133.1
           121
      110       108.9
 100       99
      90        89.1
           81
                72.9
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Dyalog APL, <s>60</s> 56 bytes

Needs ⎕IO←0 which is default on many systems. Prompts for S then t then p.

⍉{⍵⌽⍨-⌽⍳≢⍵}↑{⍵\⍨0 1⍴⍨2×≢⍵}¨⍕¨¨⎕{⍵,⊂∪∊(⊃⌽⍵)∘.×1+⍺,-⍺}⍣⎕⊢⎕

Over 50% of the code is to get the right display form.

TryAPL online! (]Box off for proper display – the default on installed systems – emulated here using ⍕.)

Example run:

                133.1
           121
      110       108.9
 100       99
      90        89.1
           81
                72.9


答:
Spammer, Java

```<code>import java.util.List;
import java.util.ArrayList;
import com.ppcg.stockexchange.*;

public class Spammer extends Player {
    private boolean panic = false;

    public Offer acceptOffer(List<Offer> offers) {
        for (Offer offer : offers) {
            if (this.panic || offer.getPayment() < 20)
                return offer;
        }
        return null;
    }
    public Offer makeOffer(List<Stock> currentStock) {
        if (currentStock.size() > 1) { // Don't sell all the stock
            this.panic = false;
            return new Offer(currentStock.get(secretStockType).setAmount(1), 1);
        }
        this.panic = true; // BUY
        return null;
    }
}
</code>```

Spam the market with really cheap stock, and only buy stock when the price is lesser than 20. When the stock count fall to 1, it will try to buy anything.

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:
Spammer, Java

import java.util.List;
import java.util.ArrayList;
import com.ppcg.stockexchange.*;

public class Spammer extends Player {
    private boolean panic = false;

    public Offer acceptOffer(List<Offer> offers) {
        for (Offer offer : offers) {
            if (this.panic || offer.getPayment() < 20)
                return offer;
        }
        return null;
    }
    public Offer makeOffer(List<Stock> currentStock) {
        if (currentStock.size() > 1) { // Don't sell all the stock
            this.panic = false;
            return new Offer(currentStock.get(secretStockType).setAmount(1), 1);
        }
        this.panic = true; // BUY
        return null;
    }
}

Spam the market with really cheap stock, and only buy stock when the price is lesser than 20. When the stock count fall to 1, it will try to buy anything.


问:
Write a program that outputs the number of times it has been run
In a programming language of your choice, write a full program that, when run, prints a positive integer N and then modifies its own source file such that the next time it is run it will print N+1.

For example, this (ungolfed) Python 3 program satisfies this behavior:

N = 1
print(N)
with open(__file__, 'r+') as f:
    N = int(f.readline()[4:]) + 1
    code = 'N = ' + str(N) + '\n' + f.read()
    f.seek(0)
    f.write(code)
```
<p>Right away it declares and prints N, then it opens itself and rewrites its first line so the declared value of N is incremented. Then it copies the rest of its code verbatim and writes the new code to the same file, resulting in a program that will print N+1 when run again.</p>
<p>If the file were named <code>incr.py</code>, running it on the command line would look something like this:</p>
```C:\somepath> python incr.py
1
C:\somepath> python incr.py
2
C:\somepath> python incr.py
3
C:\somepath> python incr.py
4
```
<p>At this point, <code>incr.py</code> would read:</p>
<pre class="lang-python prettyprint-override"><code>N = 5
print(N)
with open(__file__, 'r+') as f:
    N = int(f.readline()[4:]) + 1
    code = 'N = ' + str(N) + '\n' + f.read()
    f.seek(0)
    f.write(code)
</code>```

Your program should behave essentially the same as this Python example, though of course your program structure may be very different, even changing as N increases. (You don't need to define N as a plain integer on the first line, for example.)

Give the program that prints 1 in your answer. Programs for all higher N can then be inferred. The shortest 1-printing program in bytes wins.

Notes

The output should be the sole number N in decimal (or your language's most natural base), followed optionally by a trailing newline.

Your program must actually rewrite its own source code file, not simply output its modified source like a quine.

The file name and/or path of the source file may be hardcoded into your program (e.g. 'incr.py' could have replaced __file__ in the Python example) but the program's behavior should not depend on them. If the file is moved or renamed it should be easy enough to rewrite the program accordingly.

The source file's name and path should not change during execution.

Temporary files may be made (to copy code to or whatever) but they should be removed before the main program ends. Specifically, the only side effects of running your program should be:

Printing N to stdout.

Changing the source file so it will print N+1 when next run.

答:
Batch, <s>70</s> 55 bytes

```<code>@cmd/cset/a-1>>%0
@call:l
@echo %n:~1%
:l
@set/an=0
</code>```

Ensure that the file does not end in a newline. Use the full file name to invoke the file (e.g. incr.bat). Works by appending -1 (cmd/cset/a does not output a trailing newline) to the end of the file on each run (including the first!) so that n is the negation of the desired result, then just strips off the leading minus sign when printing n.

Edit: Saved 8 bytes by removing an exit/b which had no visible effect. Saved 7 bytes by switching from @echo off to @ prefixes on each line.

Body:
Batch, <s>70</s> 55 bytes

@cmd/cset/a-1>>%0
@call:l
@echo %n:~1%
:l
@set/an=0

Ensure that the file does not end in a newline. Use the full file name to invoke the file (e.g. incr.bat). Works by appending -1 (cmd/cset/a does not output a trailing newline) to the end of the file on each run (including the first!) so that n is the negation of the desired result, then just strips off the leading minus sign when printing n.

Edit: Saved 8 bytes by removing an exit/b which had no visible effect. Saved 7 bytes by switching from @echo off to @ prefixes on each line.


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

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

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

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

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

The shortest code in bytes wins.

答:
Fish (><>), 14 bytes

With input from the command line/initial stack.

```<code>l3=?!;$:@---0=l1==n;
</code>```

Explanation:

```<code>$:@              Swaps top two values on stack then duplicates topmost one, then swaps top three values
   ---             Each '-' subtracts the second most value on the stack from the topmost and pushes their result
      0=l1=          Checks if topmost value is 0, pushes 1 if true and 0 if false, then checks if length of stack is 1 (pushes 1 is true, 0 if false)
         =n;           Does the logical && of the top two truthy/falsy values pushed in previous step and outputs the result.
</code>```

Try it here

Title: As Easy as One-Two-Three

Body:
Fish (><>), 14 bytes

With input from the command line/initial stack.

l3=?!;$:@---0=l1==n;

Explanation:

$:@              Swaps top two values on stack then duplicates topmost one, then swaps top three values
   ---             Each '-' subtracts the second most value on the stack from the topmost and pushes their result
      0=l1=          Checks if topmost value is 0, pushes 1 if true and 0 if false, then checks if length of stack is 1 (pushes 1 is true, 0 if false)
         =n;           Does the logical && of the top two truthy/falsy values pushed in previous step and outputs the result.

Try it here


答:
PHP, <s>32</s> 34 bytes

```<code><?=(800>$x=$argv[1]-12?:1)>$x%111;
</code>```

Run like this:

```<code>echo '<?=(800>$x=$argv[1]-12?:1)>$x%111;' | php -- 124
</code>```

Updates:

I made a little mistake where 12 was considered valid.

Title: As Easy as One-Two-Three

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

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

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

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

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

The shortest code in bytes wins.

Body:
PHP, <s>32</s> 34 bytes

<?=(800>$x=$argv[1]-12?:1)>$x%111;

Run like this:

echo '<?=(800>$x=$argv[1]-12?:1)>$x%111;' | php -- 124

Updates:

I made a little mistake where 12 was considered valid.


Title: As Easy as One-Two-Three

Body:
Batch, 49 bytes

@for /l %%a in (123,111,789)do @if %%a==%1 echo 1


问:
DNA Encode a String

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.

答:
Pyth, 5152 + 21 + 23 = 5196 bytes

Encoder

```<code>sm@c4s_B"ATCG"djC.ZQ4
</code>```

Try it here

Decoder

```<code>.ZCimxc4s_B"ATCG"dcQ2 4
</code>```

Try it here (Input too long to link, put output of first in quotes in the input box)

Compresses the input and converts it from base 256 into an integer. Then converts into a sequence of base 4 numbers and chooses from ['AT', 'CG', 'GC', 'TA']

Title: DNA Encode a String

Body:
Pyth, 5152 + 21 + 23 = 5196 bytes

Encoder

sm@c4s_B"ATCG"djC.ZQ4

<a href="http://pyth.herokuapp.com/?code=sm%40c4s_B%22ATCG%22djC.ZQ4&input=%22%22%22I+have+a+friend+who%27s+an+artist+and+has+sometimes+taken+a+view+which+I+don%27t+agree+with+very+well.+He%27ll+hold+up+a+flower+and+say+%22look+how+beautiful+it+is%2C%22+and+I%27ll+agree.+Then+he+says+%22I+as+an+artist+can+see+how+beautiful+this+is+but+you+as+a+scientist+take+this+all+apart+and+it+becomes+a+dull+thing%2C%22+and+I+think+that+he%27s+kind+of+nutty.+First+of+all%2C+the+beauty+that+he+sees+is+available+to+other+people+and+to+me+too%2C+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%2C+I+see+much+more+about+the+flower+than+he+sees.+I+could+imagine+the+cells+in+there%2C+the+complicated+actions+inside%2C+which+also+have+a+beauty.+I+mean+it%27s+not+just+beauty+at+this+dimension%2C+at+one+centimeter%3B+there%27s+also+beauty+at+smaller+dimensions%2C+the+inner+structure%2C+also+the+processes.+The+fact+that+the+colors+in+the+flower+evolved+in+order+to+attract+insects+to+pollinate+it+is+interesting%3B+it+means+that+insects+can+see+the+color.+It+adds+a+question%3A+does+this+aesthetic+sense+also+exist+in+the+lower+forms%3F+Why+is+it+aesthetic%3F+All+kinds+of+interesting+questions+which+the+science+knowledge+only+adds+to+the+excitement%2C+the+mystery+and+the+awe+of+a+flower.+It+only+adds.+I+don%27t+understand+how+it+subtracts.%22%22%22&debug=0" rel="nofollow noreferrer">Try it here

Decoder

.ZCimxc4s_B"ATCG"dcQ2 4

Try it here (Input too long to link, put output of first in quotes in the input box)

Compresses the input and converts it from base 256 into an integer. Then converts into a sequence of base 4 numbers and chooses from ['AT', 'CG', 'GC', 'TA']


问:
Randomly Misspell a Word
Inspired by this CR question (please don't kill me for browsing CR)

Spec

The probabilities of misspelling a word are:

1/3 of the time don't change the output

1/3 of the time remove a random character

1/3 of the time duplicate a random character

The chance for removing/duplicating a given character in the input should be the same for all chars.

If two consecutive characters are the same (case-sensitive), the probability of one of them being modified should be the same as if they are one character. I.e. the outputs for AA (which are AA or A or AAA) should all have the same probability.

The input will only contain of letters for simplicity.

Examples

First line is input, following lines are all possible misspellings. Each line should have the same probability of being output, the input is excluded in the examples but it should still have a 1/3 probability of output.

```<code>foo

fo
oo
ffoo
fooo
</code>```

```<code>PPCG

PPC
PPG
PCG
PPPCG
PPCCG
PPCGG
</code>```

答:
JavaScript (ES6), 107

w=>(r=x=>Math.random()*x|0,a=w.match(/(.)\1*/g),a[p=r(a.length)]=[b=a[p],b+b[0],b.slice(1)][r(3)],a.join``)
```
<p><em>Less golfed</em></p>
<pre class="lang-js prettyprint-override"><code>w=>(
  a = w.match(/(.)\1*/g),
  r = x => Math.random()*x | 0,
  p = r(a.length),
  b = a[p],
  a[p] = [b, b+b[0], b.slice(1)][r(3)],
  a.join``
)
</code>```

Test

f=w=>(r=x=>Math.random()*x|0,a=w.match(/(.)\1*/g),a[p=r(a.length)]=[b=a[p],b+b[0],b.slice(1)][r(3)],a.join``)

function update() {
  O.innerHTML = Array(99)
  .fill(I.value)
  .map(x=>(
    r=f(x),
    r==x?r:r.length<x.length?''+r+'':''+r+''

    )
  ).join` `
}

update()```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#O { width:90%; overflow: auto; white-space: pre-wrap}</code>```

<input id=I oninput='update()' value='trolley'>
```</code>```

Title: Randomly Misspell a Word

Body:
JavaScript (ES6), 107

w=>(r=x=>Math.random()*x|0,a=w.match(/(.)\1*/g),a[p=r(a.length)]=[b=a[p],b+b[0],b.slice(1)][r(3)],a.join``)

Less golfed

w=>(
  a = w.match(/(.)\1*/g),
  r = x => Math.random()*x | 0,
  p = r(a.length),
  b = a[p],
  a[p] = [b, b+b[0], b.slice(1)][r(3)],
  a.join``
)

Test

f=w=>(r=x=>Math.random()*x|0,a=w.match(/(.)\1*/g),a[p=r(a.length)]=[b=a[p],b+b[0],b.slice(1)][r(3)],a.join``)

function update() {
  O.innerHTML = Array(99)
  .fill(I.value)
  .map(x=>(
    r=f(x),
    r==x?r:r.length<x.length?'<b>'+r+'</b>':'<i>'+r+'</i>'

    )
  ).join` `
}

update()

#O { width:90%; overflow: auto; white-space: pre-wrap}

<input id=I oninput='update()' value='trolley'><pre id=O></pre>


答:
Python 3, 15324 + 122 + 211 = 15657 bytes

This is a very wasteful method which converts each character to a three digit number and, for each of those three digits, assigns it a two unit code.

Encoder, 122 bytes

u='AAAATTTCCGTTTTAAAGGCATCGTCGCGGTAGCAGCGCC'
o=''
for i in o.join("%03d"%ord(i)for i in input()):o+=u[int(i)::10]
print(o)
```

<p><em>See the encoded version of the example text <strong>here</strong></em></p>

<h2>Decoder, 211 bytes</h2>

<pre class="lang-py prettyprint-override"><code>u=['ATAT','ATTA','ATCG','ATGC','TATA','TACG','TAGC','CGCG','CGGC','GCGC']
l=input()
I=u.index
s=''
for j in[l[i:i+12]for i in range(0,len(l),12)]:s+=chr(int(str(I(j[:4]))+str(I(j[4:8]))+str(I(j[-4:]))))
print(s)
</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:
Python 3, 15324 + 122 + 211 = 15657 bytes

This is a very wasteful method which converts each character to a three digit number and, for each of those three digits, assigns it a two unit code.

Encoder, 122 bytes

u='AAAATTTCCGTTTTAAAGGCATCGTCGCGGTAGCAGCGCC'
o=''
for i in o.join("%03d"%ord(i)for i in input()):o+=u[int(i)::10]
print(o)

See the encoded version of the example text here

Decoder, 211 bytes

u=['ATAT','ATTA','ATCG','ATGC','TATA','TACG','TAGC','CGCG','CGGC','GCGC']
l=input()
I=u.index
s=''
for j in[l[i:i+12]for i in range(0,len(l),12)]:s+=chr(int(str(I(j[:4]))+str(I(j[4:8]))+str(I(j[-4:]))))
print(s)


答:
Java 7, <s>189</s> <s>180</s> 178 bytes

```<code>import java.util.*;String c(String i){Random r=new Random();int x=r.nextInt(2),j=r.nextInt(i.length());return x<1?i:i.substring(0,j-(x%2^1))+(x<2?i.charAt(j):"")+i.substring(j);}
</code>```

Ungolfed & test cases:

Try it here.

```<code>import java.util.*;
class M{
  static String c(String i){
    Random r = new Random();
    int x = r.nextInt(2),
        j = r.nextInt(i.length());
    return x < 1
            ? i
            : i.substring(0, j - (x%2 ^ 1)) + (x<2?i.charAt(j):"") + i.substring(j);
  }

  public static void main(String[] a){
    for(int i = 0; i < 5; i++){
      System.out.println(c("foo"));
    }
    System.out.println();
    for(int i = 0; i < 5; i++){
      System.out.println(c("PPCG"));
    }
  }
}
</code>```

Possible output:

```<code>foo
fooo
foo
foo
ffoo

PPCCG
PPCG
PPCCG
PPPCG
PPCG
</code>```

Title: Randomly Misspell a Word

Body:
Inspired by this CR question (please don't kill me for browsing CR)

Spec

The probabilities of misspelling a word are:

1/3 of the time don't change the output

1/3 of the time remove a random character

1/3 of the time duplicate a random character

The chance for removing/duplicating a given character in the input should be the same for all chars.

If two consecutive characters are the same (case-sensitive), the probability of one of them being modified should be the same as if they are one character. I.e. the outputs for AA (which are AA or A or AAA) should all have the same probability.

The input will only contain of letters for simplicity.

Examples

First line is input, following lines are all possible misspellings. Each line should have the same probability of being output, the input is excluded in the examples but it should still have a 1/3 probability of output.

```<code>foo

fo
oo
ffoo
fooo
</code>```

```<code>PPCG

PPC
PPG
PCG
PPPCG
PPCCG
PPCGG
</code>```

Body:
Java 7, <s>189</s> <s>180</s> 178 bytes

import java.util.*;String c(String i){Random r=new Random();int x=r.nextInt(2),j=r.nextInt(i.length());return x<1?i:i.substring(0,j-(x%2^1))+(x<2?i.charAt(j):"")+i.substring(j);}

Ungolfed & test cases:

Try it here.

import java.util.*;
class M{
  static String c(String i){
    Random r = new Random();
    int x = r.nextInt(2),
        j = r.nextInt(i.length());
    return x < 1
            ? i
            : i.substring(0, j - (x%2 ^ 1)) + (x<2?i.charAt(j):"") + i.substring(j);
  }

  public static void main(String[] a){
    for(int i = 0; i < 5; i++){
      System.out.println(c("foo"));
    }
    System.out.println();
    for(int i = 0; i < 5; i++){
      System.out.println(c("PPCG"));
    }
  }
}

Possible output:

foo
fooo
foo
foo
ffoo

PPCCG
PPCG
PPCCG
PPPCG
PPCG


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

ContentLicense: CC BY-SA 4.0

Title: Sylvester's sequence

Body:
dc, 34 bytes

0sg[[d1-*1+Lgx]Sg1-d0<f]dsfx2Lgx++

This pops the argument from top of stack, and pushes the result to stack, as normal for dc.

Annotated full program

#!/usr/bin/dc

# accept input
?

# initialise the bottom of the g-stack
0sg
# Add n iterations of recurrence formula
[[d1-*1+Lgx]Sg1-d0<f]dsfx
# Prime the 0th value
2
# Execute all of the g-stack
Lgx
# Last instruction left a zero on the stack
+
# Special case: if input is 0, f left a -1 behind.  This is a correction
# for wrongly doing 2->3 in that case
+

# print output
p

It works by using the recurrence relation described in OEIS: a[n+1] = a[n]² - a[n] + 1, starting with a[0]==2.  Equivalently, a[n+1] = a[n](a[n]-1) + 1, written in dc as d1-*1+.

We push n copies of the program d1-*1+ to the stack g, prime the main stack with the initial value 2, and set off.  There's a correction for n=0, because we always push at least one instance of the recurrence.  Handily, we can fix that, because function f leaves -1 on the stack in that case, and 0 otherwise.

Test output:

0: 2
1: 3
2: 7
3: 43
4: 1807
5: 3263443
6: 10650056950807
7: 113423713055421844361000443
8: 12864938683278671740537145998360961546653259485195807
9: 165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443
10: 27392450308603031423410234291674686281194364367580914627947367941608692026226993634332118404582438634929548737283992369758487974306317730580753883429460344956410077034761330476016739454649828385541500213920807
11: 750346333909286311464218348364293017384724140073732363176684391768374238237200233203724274839819736227493060107386942069521875902258281351952761393460726027774387698896086030486687796275661950199835484418384103096899499524666007073298797852932127876923983340497448231960048833094195425231846478785035602339261149953564729371337917773386670133413581537490788020231265093210310224397095644371148893261284201611453610443
12: 563019620811106188735345793029131127645126456201508328395934709948713369875017428398616526515350801978901280848429236023780360625686785326318172135941491985234945009397938528773976977887356630327917721419666751591559883455828027643329740930320548089836575156581070880066847294722353255119648341271402723167206816552066010592134725124376810874159292118224274440907862996344067325025151751506647339684959479438354192989470470488621172745980086435801519575581664038703641801974453354864238123148678312993828328158261237284571445163949954735321181426755485563860804935755099928085508785637606452207007984638610604113718738727804169240213041488645142155664706600019329809186121988322464207409749450811638629159492106903853533242008723387118397794980575878357156285111258733862431522178328441469980110808406224908967784943255608168545045807
13: 316991093418281796980738587324498503465985663563441351614965595710659626509023026378810664917769979749230375616949095839488230630774365784766585678394020150307543448990686716629735821013846949520218610883960194258122308878890968113466913053158083723070515602776324450012006168592325685889943262781933132780014500164781142497008320197365141855119010118077705678576368755229432787283587491897170937657553086679827144799087397199129432233281774986701578182361474362882421927116451702868297347253630717771757957438615228337552613006602138504913204731416596016919892552584014059657038635241014722034375088903021315484876024289828564177721518967548558336213757430766087730295001595138792039193609746512786881659903942227205537012891959828532940594409566163694454653037016800027294499421291400492041597627904670868358757293568071192353450861046220903121264904877170553117406388566305811088048722332066039563082830094354238880920553702156022717609505663704069061610519598560624334935881397512984533454362321248854729174814176943381209734396537109715522733592519084452225492188715705481658124794599731527140827530319488791822858978924780015280035310521766457660381662363459675166288099343838361130665940967928850877954452552005403436587169730515877297387774041696625714088910160966686976352250237188765370786055553236020704945964404004577531357576565107610684603955726197582253686411381871520005412537060114403951740688011605681233186481569161991920354077827812176666950510226500521720520469387009627382085749910481677989034236154462513159644551504513525508614268492165297534777956118363272320828495465015734808069866823697938666550506233479919235237378935603448169915183235443
14: 100483353306517857188816511171973264968130481955993490961776578914384855009465596512878627978186320098524674810822809215084298821790532480217571435837318997038501027166944291436298311859998927368878478765662052261013905379683606908563327049366289350227874801320137528476359434996625155321924896471487253609774383161294073700386567438895729619959183688827019175395384990049660760826706275656247200320644562229907983316938796200727194177710641698165578469600709422183645673081099011178658794923207340118316226811044120124994280172667435132674250477913878334229469634774955766654959747171269329356217729819952093850230832136940392143299736102334976183356619572749168857678782222255344301700168226608019630704240193738779198063738629831841413772846575231497629810592678428725195220732911880790353530776313807267315574488856933933931968726196972550157616749777588888821303729634383570842953721086839502335017753789603211887639264756326943906234925564059713122739441052488376985825209930025027331642643833862623818612641648534007690784009230583997364206027891426162271405399576520661523570494921380174573570295575834537952976231451138917903119690734728050868143651943079046629073247009723903287946523072583428647088990713577505274669321894108556505593299658881909461644436220683735665670039545950199079805499092674406353548516096407916275052371510047476698658893306349068133879014809524920709542592832744670134019181012820484031829100985336532444887396195766078330294774788615792775829183741076029977456631131003360810557200089618493958319779112283680033864350359591347851857639767660909655544622503481811302270128415655545885368248621757558781407774929247336942808205264958129961178967782261436710020914320953492879039247990865098954170193648898076402861312803632817456574773061811978648089614340109760702469211985641224691799075765885167117855362986656144090527289697873066081524676142089795828969028242126025160985084779781007974719610529121366009147473928798323429514961662955075830495059188425232901129844306717176754536658533793214326255403412914373598713551532524170357661947859352181097102731800860434424406585016086605044703266455861041380556886689319004123095655013285849524741495205262970148746426581276319938997140587845485798731493239638046736464142096404810367841352036464369335995230683471276720095626585363049720580305501778636182605592068492151793190258602236893550140479021220581841241476297575889705144565984983772835663470728331437295945770147420128139970898197153180098987682528952187399111614545313650329728193759220800741639763444502297436225484681500013482802572032911312979385547883726365017125898034265710900263014307543995711388447583272341504352098242603013317289071851486202200363353430637400418445403028209289752937101610106546407815385279051077386957963745649023423516876644029840971378691516442745761797057396994687382618710236478541855961623090443801434726418529440871490091117324165342131670988126442133481305788646667033011070351616554711007362680081909808994105138595194669575127185645557552945017168697977343707144183186705714691228418618276386168995938283316172058534438295911377445943568762495111242585896098376432273844229629284777619272064792008892485171141118486114024760197688360378085790695965894817048250719620713759873671293320363983916413298621510321025850259140267373664767105414000002388170807
15: [encoded data, 6671 characters]
16: (13341 digits)
17: (26681 digits)
18: (53361 digits)
19: (106721 digits)
20: (213441 digits)
21: (426881 digits)
22: (853761 digits)
23: (1707522 digits)
24: (3415043 digits)
25: (6830085 digits)
26: (13660169 digits)
27: (27320338 digits)
28: (54640675 digits)
29: (109281349 digits)

As you can see, these numbers grow quite rapidly; the computation time also increases in the same proportion as the result length. It took me half a minute to compute a(23), and several hours for a(29).


答:
JavaScript (browser) (ES6), 84 bytes

```<code>s=document.querySelector('script');f=_=>eval(s.innerHTML);n=0;s.innerHTML+='n++;n;';
</code>```

Run by calling f(). Note that this is reset on page load.

I assume that modifying the

Title: Write a program that outputs the number of times it has been run

Body:
In a programming language of your choice, write a full program that, when run, prints a positive integer N and then modifies its own source file such that the next time it is run it will print N+1.

For example, this (ungolfed) Python 3 program satisfies this behavior:

N = 1
print(N)
with open(__file__, 'r+') as f:
    N = int(f.readline()[4:]) + 1
    code = 'N = ' + str(N) + '\n' + f.read()
    f.seek(0)
    f.write(code)
```
<p>Right away it declares and prints N, then it opens itself and rewrites its first line so the declared value of N is incremented. Then it copies the rest of its code verbatim and writes the new code to the same file, resulting in a program that will print N+1 when run again.</p>
<p>If the file were named <code>incr.py</code>, running it on the command line would look something like this:</p>
```C:\somepath> python incr.py
1
C:\somepath> python incr.py
2
C:\somepath> python incr.py
3
C:\somepath> python incr.py
4
```
<p>At this point, <code>incr.py</code> would read:</p>
<pre class="lang-python prettyprint-override"><code>N = 5
print(N)
with open(__file__, 'r+') as f:
    N = int(f.readline()[4:]) + 1
    code = 'N = ' + str(N) + '\n' + f.read()
    f.seek(0)
    f.write(code)
</code>```

Your program should behave essentially the same as this Python example, though of course your program structure may be very different, even changing as N increases. (You don't need to define N as a plain integer on the first line, for example.)

Give the program that prints 1 in your answer. Programs for all higher N can then be inferred. The shortest 1-printing program in bytes wins.

Notes

The output should be the sole number N in decimal (or your language's most natural base), followed optionally by a trailing newline.

Your program must actually rewrite its own source code file, not simply output its modified source like a quine.

The file name and/or path of the source file may be hardcoded into your program (e.g. 'incr.py' could have replaced __file__ in the Python example) but the program's behavior should not depend on them. If the file is moved or renamed it should be easy enough to rewrite the program accordingly.

The source file's name and path should not change during execution.

Temporary files may be made (to copy code to or whatever) but they should be removed before the main program ends. Specifically, the only side effects of running your program should be:

Printing N to stdout.

Changing the source file so it will print N+1 when next run.

Body:
JavaScript (browser) (ES6), 84 bytes

s=document.querySelector('script');f=_=>eval(s.innerHTML);n=0;s.innerHTML+='n++;n;';

Run by calling f(). Note that this is reset on page load.

I assume that modifying the <script> tag counts as rewriting the source code.


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

答:
I guess you can use recursion.

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

I guess you can use recursion.

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

```<code>...
</code>```

OwnerDisplayName: Judy

Body:
I guess you can use recursion.

function slashes() {echo chr(47 + 45 * rand(0,1)); slashes();}

I guess you can use recursion.

function slashes() {echo chr(47 + 45 * rand(0,1)); slashes();}

...

OwnerDisplayName: Neal


答:
PHP, 75 bytes

This uses a modified version of Jörg Hülsermann's answer.

```<code>eval(preg_replace('~.~','$s=($s\0(2-ord("\0")%11%3))|0;',$argv[1]));echo$s;
</code>```

It heavily relies on string substitution, using a simple regular expression (~.~).

The variable $s is re-assigned with the new value for each character. At the end, it outputs the result.

Note: This is meant to be executed using the -r flag.

Try it here:

if('\0' == "\0")
{
 $argv = Array($s = 0, prompt());
 function preg_replace($pattern, $replacement, $subject)
 {
  $regexp = new RegExp($pattern.replace(new RegExp('~', 'g'), ''), 'g');
  return $subject.replace($regexp, $replacement.split('\0').join('$&'));
 }

 function printf($string)
 {
  console.log($string);
 }

 function ord($chr)
 {
  return $chr.charCodeAt(0);
 }
}
else
{
    if(!isset($argv))
    {
        $argv = array('', '++*+');
    }
}

eval(preg_replace('~.~','$s=($s\0(2-ord("\0")%11%3))|0;',$argv[1]));printf($s);```

Or try on: http://sandbox.onlinephpfunctions.com/code/7d2adc2a500268c011222d8d953d9b837f2312aa

Differences:

Instead of echo$s, I'm using sprintf($s).
Both perform the same action on numbers. Since this is just for testing, it is fine.

In case there's no passed argument, it will run as if you passed ++*+ as the first argument, which should show 5.

Title: Simple integer operation calculator

Body:
Implement a simple integer operation scriptable calculator.

Concept

The accumulator starts at 0 and has operations performed on it. At the end of the program output the value of the accumulator.

Operations:

+ adds 1 to the accumulator

- subtracts 1 from the accumulator

* multiplies the accumulator by 2

/ divides the accumulator by 2

Sample script

The input ++**--/ should give the output 3.

Example implementation

```<code>def calc(s)
    i = 0
    s.chars.each do |o|
        case o
            when '+'
                i += 1
            when '-'
                i -= 1
            when '*'
                i *= 2
            when '/'
                i /= 2
        end
    end
    return i
end
</code>```

Rules

This is code-golf, so lowest answer in bytes wins, but is not selected.

Creative implementations are encouraged.

Standard loopholes are prohibited.

You get the program via stdin or arguments, and you can output the answer via return value or stdout.

Have fun.

Division truncates down because it is integer division.

The program -/ returns -1.

Test cases

```<code>*///*-*+-+
-1
/*+/*+++/*///*/+-+//*+-+-/----*-*-+++*+**+/*--///+*-/+//*//-+++--++/-**--/+--/*-/+*//*+-*-*/*+*+/+*-
-17
+++-+--/-*/---++/-+*-//+/++-*--+*+/*/*/++--++-+//++--*/***-*+++--+-*//-*/+*/+-*++**+--*/*//-*--**-/-*+**-/*-**/*+*-*/--+/+/+//-+*/---///+**////-*//+-+-/+--/**///*+//+++/+*++**++//**+**+-*/+/*/*++-/+**+--+*++++/-*-/*+--/++*/-++/-**++++/-/+/--*/-/+---**//*///-//*+-*----+//--/-/+*/-+++-+*-*+*+-/-//*-//+/*-+//+/+/*-/-/+//+**/-****/-**-//+/+-+/*-+*++*/-/++*/-//*--+*--/-+-+/+/**/-***+/-/++-++*+*-+*+*-+-//+/-++*+/*//*-+/+*/-+/-/*/-/-+*+**/*//*+/+---+*+++*+/+-**/-+-/+*---/-*+/-++*//*/-+-*+--**/-////*/--/*--//-**/*++*+/*+/-+/--**/*-+*+/+-*+*+--*///+-++/+//+*/-+/**--//*/+++/*+*////+-*-//--*+/*/-+**/*//+*+-//+--+*-+/-**-*/+//*+---*+//*/+**/*--/--+/*-*+*++--*+//+*+-++--+-*-*-+--**+/+*-/+*+-/---+-*+-+-/++/+*///*/*-+-*//-+-++/++/*/-++/**--+-////-//+/*//+**/*+-+/+/+///*+*///*-/+/*/-//-*-**//-/-+--+/-*--+-++**++//*--/*++--*-/-///-+/+//--+*//-**-/*-*/+*/-*-*//--++*//-*/++//+/-++-+-*/*-+++**-/-*++++**+-+++-+-***-+//+-/**-+/*+****-*+++*/-*-/***/-/*+/*****++*+/-/-**-+-*-*-++**/*+-/*-+*++-/+/-++*-/*-****-*
18773342
</code>```

Body:
PHP, 75 bytes

This uses a modified version of Jörg Hülsermann's answer.

eval(preg_replace('~.~','$s=($s\0(2-ord("\0")%11%3))|0;',$argv[1]));echo$s;

It heavily relies on string substitution, using a simple regular expression (~.~).

The variable $s is re-assigned with the new value for each character. At the end, it outputs the result.

Note: This is meant to be executed using the -r flag.

Try it here:

if('\0' == "\0")
{
 $argv = Array($s = 0, prompt());
 function preg_replace($pattern, $replacement, $subject)
 {
  $regexp = new RegExp($pattern.replace(new RegExp('~', 'g'), ''), 'g');
  return $subject.replace($regexp, $replacement.split('\0').join('$&'));
 }

 function printf($string)
 {
  console.log($string);
 }

 function ord($chr)
 {
  return $chr.charCodeAt(0);
 }
}
else
{
    if(!isset($argv))
    {
        $argv = array('', '++*+');
    }
}

eval(preg_replace('~.~','$s=($s\0(2-ord("\0")%11%3))|0;',$argv[1]));printf($s);

Or try on: http://sandbox.onlinephpfunctions.com/code/7d2adc2a500268c011222d8d953d9b837f2312aa

Differences:

Instead of echo$s, I'm using sprintf($s).
Both perform the same action on numbers. Since this is just for testing, it is fine.

In case there's no passed argument, it will run as if you passed ++*+ as the first argument, which should show 5.


答:
PHP, 31 bytes

```<code><?=($n=$_GET[n])-12==$n[0]*111;
</code>```

Check if first digit of (number minus 12) is multiple of 111

Title: As Easy as One-Two-Three

Body:
PHP, 31 bytes

<?=($n=$_GET[n])-12==$n[0]*111;

Check if first digit of (number minus 12) is multiple of 111


问:
The Letter A without A
Your task is to display the letter "A" alone, without anything else, except any form of trailing newlines if you cannot avoid them, doing so in a program and/or snippet. Code that returns (instead of printing) is allowed.

Both the lowercase and uppercase versions of the letter "A" are acceptable (that is, unicode U+0061 or unicode U+0041. Other character encodings that aren't Unicode are allowed, but either way, the resulting output of your code must be the latin letter "A", and not any lookalikes or homoglyphs)

You must not use any of the below characters in your code, regardless of the character encoding that you pick:

"A", whether uppercase or lowercase.

"U", whether lowercase or uppercase.

X, whether uppercase or lowercase.

+

&

#

0

1

4

5

6

7

9

Cheating, loopholes, etc, are not allowed.

Since this is code-golf, the shortest solution, in bytes, that follows all the rules, is the winner.

Validity Checker

This Stack Snippet checks to make sure your code doesn't use the restricted characters. It might not work properly for some character encodings.

var t = prompt("Input your code.");

if (/[AaUuXx+&#0145679]/.test(t)) {
  alert("Contains a disallowed character!");
} else {
  alert("No disallowed characters");
}```
</div>
</div>
</p>

<p><em>This Stack Snippet that makes sure you don't have a disallowed character is also available on JSFiddle.</em></p>

<h3>Leaderboard</h3>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var QUESTION_ID=90349,OVERRIDE_USER=58717;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;</code>```

body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td>Link</td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td>Link</td></tr></tbody> </table></code>```

答:
R, 12 bytes

I was losing it until I realized I can use 2 and 3.

```<code> LETTERS[3-2]
</code>```

Title: The Letter A without A

Body:
R, 12 bytes

I was losing it until I realized I can use 2 and 3.

 LETTERS[3-2]


答:
3d, 61 bytes

```<code>>:&&#a&×∕$#a∕#a%.--v
  v--.%a#$∕a#&%×&a#—'F!,;
v —'F!;
>'T!;
</code>```

Will output:

```<code>T
</code>```

if input is a three consecutive increasing digits,

```<code>F
</code>```

if not.

Explanation:

```<code>:&&  push imput and duplicate twice
#a&× push 0xa (10), duplicate it, multiply top two of the stack: get 100
∕    floor divide top two elements of the stack (we get the first digit)
$    invert top two elements
#a∕  floor divide by 10 (get rid of last digit)
#a%  modulo 10 (get middle digit)
.-   push 1 and difference
-    difference (hence we get 0 if two initial digits have a difference of 1)
—    is top of stack null?
if not:
'F!  print 'F'
,;   pops the stack and exits
if yes:
#a&× get 100
%    modulo (get rid of first digit)
&    duplicate
#a∕  floor divide by 10 (get middle digit)
$    invert
#a%  modulo 10 (get last digit)
.- push 1 and difference
-  difference
— is top of stack null?
yes:
'T!; print 'T' and exit
not:
'F!; print F and exit
</code>```

Phew, this really ain't golfy.

Title: As Easy as One-Two-Three

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

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

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

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

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

The shortest code in bytes wins.

Body:
3d, 61 bytes

>:&&#a&×∕$#a∕#a%.--v
  v--.%a#$∕a#&%×&a#—'F!,;
v —'F!;
>'T!;

Will output:

T

if input is a three consecutive increasing digits,

F

if not.

Explanation:

:&&  push imput and duplicate twice
#a&× push 0xa (10), duplicate it, multiply top two of the stack: get 100
∕    floor divide top two elements of the stack (we get the first digit)
$    invert top two elements
#a∕  floor divide by 10 (get rid of last digit)
#a%  modulo 10 (get middle digit)
.-   push 1 and difference
-    difference (hence we get 0 if two initial digits have a difference of 1)
—    is top of stack null?
if not:
'F!  print 'F'
,;   pops the stack and exits
if yes:
#a&× get 100
%    modulo (get rid of first digit)
&    duplicate
#a∕  floor divide by 10 (get middle digit)
$    invert
#a%  modulo 10 (get last digit)
.- push 1 and difference
-  difference
— is top of stack null?
yes:
'T!; print 'T' and exit
not:
'F!; print F and exit

Phew, this really ain't golfy.


答:
R, 45 bytes

```<code>f=function(){body(f)[[3]]<<-body(f)[[3]]+1;1}
</code>```

Not sure if a function counts as a "full program" but calling f() will return 1,2,... within the same R session. It also satisfies the self-modifying criterion.

It is necessary to use the double-harpoon operator <<- or else f will just make a local copy of itself and modify that instead. <<- forces that to happen at the top level.

Body:
R, 45 bytes

f=function(){body(f)[[3]]<<-body(f)[[3]]+1;1}

Not sure if a function counts as a "full program" but calling f() will return 1,2,... within the same R session. It also satisfies the self-modifying criterion.

It is necessary to use the double-harpoon operator <<- or else f will just make a local copy of itself and modify that instead. <<- forces that to happen at the top level.


问:
HexaRegex: A Tribute to Martin Ender
Martin Ender recently hit 100K, and has come up with some pretty awesome languages.  We're going to have a bit of fun with one of them, Hexagony (and a bit of regex for Retina)

As a brief overview, you need to write a program that inputs a Hexagony grid and determines if there is a path on that grid that matches a string of text

Generating

Hexagony generates hexagons from a string of text using the following steps:

Calculate the minimum hexagon size (take the length of the string and round up to the nearest hex number)

Wrapping the text into a hexagon of the above size

Filling the remaining locations with ..

For example, the string of text abcdefghijklm requires a hexagon of side-length 3, and therefore becomes:

```<code>   a b c
  d e f g
 h i j k l
  m . . .
   . . .
</code>```

Now, notice that there are 6 possible directions you can travel in a hexagon.  For example, in the above hexagon, e is adjacent to abfjid.

Wrapping

Furthermore, in Hexagony, hexagons wrap:

```<code>   . . . .          . a . .          . . f .          . a . .
  a b c d e        . . b . .        . . g . .        . b . . f
 . . . . . .      g . . c . .      . . h . . a      . c . . g .
. . . . . . .    . h . . d . .    . . u . . b .    . d . . h . .
 f g h i j k      . i . . e .      . j . . c .      e . . i . .
  . . . . .        . j . . f        k . . d .        . . j . .
   . . . .          . k . .          . . e .          . k . .
</code>```

If you look at the 2nd and 4th example, notice how a and k are in the same spots, despite the fact that you are wrapping in different directions.  Due to this fact, these spots are only adjacent to 5 other locations.

To make this clearer:

```<code>   a b c d
  e f g h i
 j k l m n o
p q r s t u v
 w x y z A B
  C D E F G
   H I J K
</code>```

Edges wrap to their opposite neighbor (b->I and G->j).

Top/bottom corners wrap to the opposite center corner and up/down (d->K,p and H->a,v).

Center corners wrap to both the top and bottom corners (v->a,H)

Paths

A path to be a sequence of adjacent locations without returning to the same location.

```<code>   a b c
  d e f g
 h i f k l
  m . . .
   . . .
</code>```

In the above hexagon, aefkgm is a valid path.  However, abfd is not a valid path (f and d aren't adjacent), and abea isn't valid (returns to the a location).

We can use these paths to match text (like regex).  An alpha-numeric character matches itself (and only itself), and a . matches any character.  For example, the path aej..lgm would match aej..lgm, aejAAlgm, aeja.lgm, or aej^%gm.

Input/Output

Your program should take two strings (in any order). The first string will be nonempty, and consist of only alphanumeric characters [a-zA-Z0-9]. This will represent the hexagon you are operating on.  The second string will consist of printable characters.

You need to return a truthy value iff there is a path in the hexagon that matches the string of text given, otherwise a falsy value.

Test cases

Truthy:

```<code>"a","a"
"ab","a"
"ab","b"
"ab","ba"
"ab","aba"
"ab","&"
"ab","#7.J!"
"ab","aaaaaa"
"ab","bgjneta"
"ab","cebtmaa"
"abcdefg","dfabcg"
"AbCDeFG","GCbAeFD"
"aaaabbb","aaababb"
"abcdefghijklmnopqrs","alq"
"abcdefghijklmnopqrs","aqnmiedh"
"abcdefghijklmnopqrs","adhcgkorbefjimnqlps"
"11122233344455","12341345123245"
"abcdefgh","h%a"
"abcdefghijklm","a)(@#.*b"
"abcdefghijklm","a)(@#.*i"
"abcdefghij","ja"
"abcdefghijklmno","kgfeia"
"abcdefghijklmno","mmmmmiea"
"abcdefghijklmno","mmmmmlae"
"abcdefghijklmno","ja"
"abcdefghijklmnopqrs","eijfbadhmnokgcsrql"
</code>```

Falsy:

```<code>"a","b"
"a","%"
"a","."
"a","aa"
"a","a."
"ab","#7.J!*"
"ab","aaaaaaa"
"ab","aaaabaaa"
"ab","123456"
"abcdefg","bfgedac"
"abcdefg","gecafdb"
"abcdefg","GCbaeFD"
"aaaabbb","aaaaabb"
"abcdefghijklmnopqrs","aqrcgf"
"abcdefghijklmnopqrs","adhlcgknbeifjm"
"abcdefghijklmnopqrs","ja"
"abcdefghijklm","a)(@#.*&"
"abcdefghijklmno","a)(@bfeijk"
"abcdefghijklmno","kgfeic"
"abcdefghijklmno","mmmmmmiea"
</code>```

This is a code-golf, so make your answers as short as possible in your favorite language.

答:
Javascript (ES6), <s>511</s> <s>500</s> 496 bytes

```<code>(H,N)=>{C=(x,y)=>(c[x]=c[x]||[])[y]=y;S=d=>(C(x,y=x+d),C(y,x),C(s-x,s-y),C(s-y,s-x));r=(x,p,v)=>{p<N.length?(v[x]=1,c[x].map(n=>!v[n]&&(H[n]==N[p]||H[n]=='.')&&r(n,p+1,v.slice()))):K=1};for(e=x=K=0;(s=3*e*++e)<(l=H.length)-1;);H+='.'.repeat(s+1-l);for(a=[],b=[],c=[[]],w=e;w<e*2;){a[w-e]=x;b[e*2-w-1]=s-x;for(p=w;p--;x++){w-e||S(s-e+1);w<e*2-1&&(S(w),S(w+1));p&&S(1)}a[w]=x-1;b[e*3-++w]=s-x+1}a.map((v,i)=>S(b[i]-(x=v)));[N[0],'.'].map(y=>{for(x=-1;(x=H.indexOf(y,x+1))>-1;r(x,1,[]));});return K}
</code>```

Ungolfed and commented

```<code>// Entry point
//   H = haystack (the string the hexagon is filled with)
//   N = needle (the substring we're looking for)
(H, N) => {
  // C(x, y) - Helper function to save a connection between two locations.
  //   x = source location
  //   y = target location
  C = (x, y) => (c[x] = c[x] || [])[y] = y;

  // S(d) - Helper function to save reciprocal connections between two locations
  //        and their symmetric counterparts.
  //   d = distance between source location (x) and target location
  S = d => (C(x, y = x + d), C(y, x), C(s - x, s - y), C(s - y, s - x));

  // r(x, p, v) - Recursive path search.
  //   x = current location in hexagon
  //   p = current position in needle
  //   v = array of visited locations
  r = (x, p, v) => {
    p < N.length ?
      (v[x] = 1, c[x].map(n => !v[n] && (H[n] == N[p] || H[n] == '.') &&
      r(n, p + 1, v.slice())))
    :
      K = 1
  };

  // Compute e = the minimum required edge width of the hexagon to store the haystack.
  // Also initialize:
  //   x = current location in hexagon
  //   l = length of haystack
  //   s = size of hexagon (number of locations - 1)
  //   K = fail/success flag
  for(e = x = K = 0; (s = 3 * e * ++e) < (l = H.length) - 1;);

  // Pad haystack with '.'
  H += '.'.repeat(s + 1 - l);

  // Build connections c[] between locations, using:
  //   x = current location
  //   w = width of current row
  //   p = position in current row
  // Also initialize:
  //   a[] = list of locations on top left and top right edges
  //   b[] = list of locations on bottom left and bottom right edges
  for(a = [], b = [], c = [[]], w = e; w < e * 2;) {
    a[w - e] = x;
    b[e * 2 - w - 1] = s - x;

    for(p = w; p--; x++) {
      // connection between top and bottom edges
      w - e || S(s - e + 1);
      // connections between current location and locations below it
      w < e * 2 - 1 && (S(w), S(w + 1));
      // connection between current location and next location
      p && S(1)
    }
    a[w] = x - 1;
    b[e * 3 - ++w] = s - x + 1
  }

  // Save connections between top left/right edges and bottom left/right edges.
  a.map((v, i) => S(b[i] - (x = v)));

  // Look for either the first character of the needle or a '.' in the haystack,
  // and use it as the starting point for the recursive search. All candidate
  // locations are tried out.
  [N[0], '.'].map(y => {
    for(x = -1; (x = H.indexOf(y, x + 1)) > -1; r(x, 1, []));
  });

  // Return fail/success flag.
  return K
}
</code>```

Test cases

The snippet below will walk through all truthy and falsy test cases.

let f =
(H,N)=>{C=(x,y)=>(c[x]=c[x]||[])[y]=y;S=d=>(C(x,y=x+d),C(y,x),C(s-x,s-y),C(s-y,s-x));r=(x,p,v)=>{p<N.length?(v[x]=1,c[x].map(n=>!v[n]&&(H[n]==N[p]||H[n]=='.')&&r(n,p+1,v.slice()))):K=1};for(e=x=K=0;(s=3*e*++e)<(l=H.length)-1;);H+='.'.repeat(s+1-l);for(a=[],b=[],c=[[]],w=e;w<e*2;){a[w-e]=x;b[e*2-w-1]=s-x;for(p=w;p--;x++){w-e||S(s-e+1);w<e*2-1&&(S(w),S(w+1));p&&S(1)}a[w]=x-1;b[e*3-++w]=s-x+1}a.map((v,i)=>S(b[i]-(x=v)));[N[0],'.'].map(y=>{for(x=-1;(x=H.indexOf(y,x+1))>-1;r(x,1,[]));});return K}

let truthy = [
  ["a","a"],
  ["ab","a"],
  ["ab","b"],
  ["ab","ba"],
  ["ab","aba"],
  ["ab","&"],
  ["ab","#7.J!"],
  ["ab","aaaaaa"],
  ["ab","bgjneta"],
  ["ab","cebtmaa"],
  ["abcdefg","dfabcg"],
  ["AbCDeFG","GCbAeFD"],
  ["aaaabbb","aaababb"],
  ["abcdefghijklmnopqrs","alq"],
  ["abcdefghijklmnopqrs","aqnmiedh"],
  ["abcdefghijklmnopqrs","adhcgkorbefjimnqlps"],
  ["11122233344455","12341345123245"],
  ["abcdefgh","h%a"],
  ["abcdefghijklm","a)(@#.*b"],
  ["abcdefghijklm","a)(@#.*i"],
  ["abcdefghij","ja"],
  ["abcdefghijklmno","kgfeia"],
  ["abcdefghijklmno","mmmmmiea"],
  ["abcdefghijklmno","mmmmmlae"],
  ["abcdefghijklmno","ja"],
  ["abcdefghijklmnopqrs","eijfbadhmnokgcsrql"]
];

let falsy = [
  ["a","b"],
  ["a","%"],
  ["a","."],
  ["a","aa"],
  ["a","a."],
  ["ab","#7.J!*"],
  ["ab","aaaaaaa"],
  ["ab","aaaabaaa"],
  ["ab","123456"],
  ["abcdefg","bfgedac"],
  ["abcdefg","gecafdb"],
  ["abcdefg","GCbaeFD"],
  ["aaaabbb","aaaaabb"],
  ["abcdefghijklmnopqrs","aqrcgf"],
  ["abcdefghijklmnopqrs","adhlcgknbeifjm"],
  ["abcdefghijklmnopqrs","ja"],
  ["abcdefghijklm","a)(@#.*&"],
  ["abcdefghijklmno","a)(@bfeijk"],
  ["abcdefghijklmno","kgfeic"],
  ["abcdefghijklmno","mmmmmmiea"]
];

console.log(
  'Testing truthy test cases:',
  truthy.every(v => f(v[0], v[1])) ? 'passed' : 'failed'
);
console.log(
  'Testing falsy test cases:',
  falsy.every(v => !f(v[0], v[1])) ? 'passed' : 'failed'
);```

Title: HexaRegex: A Tribute to Martin Ender

Body:
Javascript (ES6), <s>511</s> <s>500</s> 496 bytes

(H,N)=>{C=(x,y)=>(c[x]=c[x]||[])[y]=y;S=d=>(C(x,y=x+d),C(y,x),C(s-x,s-y),C(s-y,s-x));r=(x,p,v)=>{p<N.length?(v[x]=1,c[x].map(n=>!v[n]&&(H[n]==N[p]||H[n]=='.')&&r(n,p+1,v.slice()))):K=1};for(e=x=K=0;(s=3*e*++e)<(l=H.length)-1;);H+='.'.repeat(s+1-l);for(a=[],b=[],c=[[]],w=e;w<e*2;){a[w-e]=x;b[e*2-w-1]=s-x;for(p=w;p--;x++){w-e||S(s-e+1);w<e*2-1&&(S(w),S(w+1));p&&S(1)}a[w]=x-1;b[e*3-++w]=s-x+1}a.map((v,i)=>S(b[i]-(x=v)));[N[0],'.'].map(y=>{for(x=-1;(x=H.indexOf(y,x+1))>-1;r(x,1,[]));});return K}

Ungolfed and commented

// Entry point
//   H = haystack (the string the hexagon is filled with)
//   N = needle (the substring we're looking for)
(H, N) => {
  // C(x, y) - Helper function to save a connection between two locations.
  //   x = source location
  //   y = target location
  C = (x, y) => (c[x] = c[x] || [])[y] = y;

  // S(d) - Helper function to save reciprocal connections between two locations
  //        and their symmetric counterparts.
  //   d = distance between source location (x) and target location
  S = d => (C(x, y = x + d), C(y, x), C(s - x, s - y), C(s - y, s - x));

  // r(x, p, v) - Recursive path search.
  //   x = current location in hexagon
  //   p = current position in needle
  //   v = array of visited locations
  r = (x, p, v) => {
    p < N.length ?
      (v[x] = 1, c[x].map(n => !v[n] && (H[n] == N[p] || H[n] == '.') &&
      r(n, p + 1, v.slice())))
    :
      K = 1
  };

  // Compute e = the minimum required edge width of the hexagon to store the haystack.
  // Also initialize:
  //   x = current location in hexagon
  //   l = length of haystack
  //   s = size of hexagon (number of locations - 1)
  //   K = fail/success flag
  for(e = x = K = 0; (s = 3 * e * ++e) < (l = H.length) - 1;);

  // Pad haystack with '.'
  H += '.'.repeat(s + 1 - l);

  // Build connections c[] between locations, using:
  //   x = current location
  //   w = width of current row
  //   p = position in current row
  // Also initialize:
  //   a[] = list of locations on top left and top right edges
  //   b[] = list of locations on bottom left and bottom right edges
  for(a = [], b = [], c = [[]], w = e; w < e * 2;) {
    a[w - e] = x;
    b[e * 2 - w - 1] = s - x;

    for(p = w; p--; x++) {
      // connection between top and bottom edges
      w - e || S(s - e + 1);
      // connections between current location and locations below it
      w < e * 2 - 1 && (S(w), S(w + 1));
      // connection between current location and next location
      p && S(1)
    }
    a[w] = x - 1;
    b[e * 3 - ++w] = s - x + 1
  }

  // Save connections between top left/right edges and bottom left/right edges.
  a.map((v, i) => S(b[i] - (x = v)));

  // Look for either the first character of the needle or a '.' in the haystack,
  // and use it as the starting point for the recursive search. All candidate
  // locations are tried out.
  [N[0], '.'].map(y => {
    for(x = -1; (x = H.indexOf(y, x + 1)) > -1; r(x, 1, []));
  });

  // Return fail/success flag.
  return K
}

Test cases

The snippet below will walk through all truthy and falsy test cases.

let f =
(H,N)=>{C=(x,y)=>(c[x]=c[x]||[])[y]=y;S=d=>(C(x,y=x+d),C(y,x),C(s-x,s-y),C(s-y,s-x));r=(x,p,v)=>{p<N.length?(v[x]=1,c[x].map(n=>!v[n]&&(H[n]==N[p]||H[n]=='.')&&r(n,p+1,v.slice()))):K=1};for(e=x=K=0;(s=3*e*++e)<(l=H.length)-1;);H+='.'.repeat(s+1-l);for(a=[],b=[],c=[[]],w=e;w<e*2;){a[w-e]=x;b[e*2-w-1]=s-x;for(p=w;p--;x++){w-e||S(s-e+1);w<e*2-1&&(S(w),S(w+1));p&&S(1)}a[w]=x-1;b[e*3-++w]=s-x+1}a.map((v,i)=>S(b[i]-(x=v)));[N[0],'.'].map(y=>{for(x=-1;(x=H.indexOf(y,x+1))>-1;r(x,1,[]));});return K}

let truthy = [
  ["a","a"],
  ["ab","a"],
  ["ab","b"],
  ["ab","ba"],
  ["ab","aba"],
  ["ab","&"],
  ["ab","#7.J!"],
  ["ab","aaaaaa"],
  ["ab","bgjneta"],
  ["ab","cebtmaa"],
  ["abcdefg","dfabcg"],
  ["AbCDeFG","GCbAeFD"],
  ["aaaabbb","aaababb"],
  ["abcdefghijklmnopqrs","alq"],
  ["abcdefghijklmnopqrs","aqnmiedh"],
  ["abcdefghijklmnopqrs","adhcgkorbefjimnqlps"],
  ["11122233344455","12341345123245"],
  ["abcdefgh","h%a"],
  ["abcdefghijklm","a)(@#.*b"],
  ["abcdefghijklm","a)(@#.*i"],
  ["abcdefghij","ja"],
  ["abcdefghijklmno","kgfeia"],
  ["abcdefghijklmno","mmmmmiea"],
  ["abcdefghijklmno","mmmmmlae"],
  ["abcdefghijklmno","ja"],
  ["abcdefghijklmnopqrs","eijfbadhmnokgcsrql"]
];

let falsy = [
  ["a","b"],
  ["a","%"],
  ["a","."],
  ["a","aa"],
  ["a","a."],
  ["ab","#7.J!*"],
  ["ab","aaaaaaa"],
  ["ab","aaaabaaa"],
  ["ab","123456"],
  ["abcdefg","bfgedac"],
  ["abcdefg","gecafdb"],
  ["abcdefg","GCbaeFD"],
  ["aaaabbb","aaaaabb"],
  ["abcdefghijklmnopqrs","aqrcgf"],
  ["abcdefghijklmnopqrs","adhlcgknbeifjm"],
  ["abcdefghijklmnopqrs","ja"],
  ["abcdefghijklm","a)(@#.*&"],
  ["abcdefghijklmno","a)(@bfeijk"],
  ["abcdefghijklmno","kgfeic"],
  ["abcdefghijklmno","mmmmmmiea"]
];

console.log(
  'Testing truthy test cases:',
  truthy.every(v => f(v[0], v[1])) ? 'passed' : 'failed'
);
console.log(
  'Testing falsy test cases:',
  falsy.every(v => !f(v[0], v[1])) ? 'passed' : 'failed'
);


问:
How many lights are on?
You are little speck on a Cartesian plane. Pondering your existence, you decide to roam around your plane and touch things. You notice that every coordinate pair you visit has a light switch. To entertain yourself, you decide to toggle every switch that you come across.

The Challenge: Create a program that will take an input of random length, using only the characters v,^,<, and >. These characters correspond to movements.

< moves you one unit to the left

^ moves you one unit up

> moves you one unit to the right

v moves you one unit down

Using this randomly generated input, calculate how many switches will be left in the ON position, assuming you start at (0,0), all lights begin in the OFF state, and you don't turn on any lights until you make your first move. (Meaning, if you start at (0,0), and move up 1 unit to (0,1), there will now be 1 light on). If you come across a switch that is on the ON position, it will be turned OFF.

Test cases:

```<code>v>v<^^<v<<^<^><<>^^>>><v>vv^v>v^><><<^>><<<vvv^vvv>v>>v><vv^^<<>vv^^>v^<>>^^<^^>^^v<^>^<vvv^v^v><^<<v<<>><<>v>>^><^>^^<>>>>vv>^<<^<<><vvv<v^>>vvv>v^>>><<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><^>^^^vv^^v<>vv<>>^><<^v>^v^>>v>^v^<<^^^vv<<vvv>^vv^v<<<v^^<<><vv<>>^^vv>^^^vv>><><v>v<^v^>>>vv^><>><v<^v<>^><v<^^^^>><^<>v>^v<^vv>v>v<^<>v>v>^<vv>v<^>vvv<v^<vv<vv<>v>^><v^v<>>>>>v>><^v<>v>^v><v^v^vv<>^<vvv^>><v^<vvv^^<^vvv^v^<>><v>v^^v<><>v^^^v<<<^><v<<<>><<vv<<><vvv^v>>v^v<v^>>><<v<>^v><>vv<<v>v^vv>v^v<^<vv<><><^v>^<vv>v^^>>^^^><vv<><^>>>^<v^<<^^>^>vv^><v<vvv>^^>>>^><<vv>vv>^<>>^^><^v><<>^<<<v^>^
</code>```

yields 1408 lights on.

To generate input, you may use the following Python script:

import random
length = random.randint(15, 10000)
walk = ''
chars = ['v', '<', '>', '^']
for i in range(length):
    walk += random.choice(chars)
print(walk)
```

Standard code-golf scoring, winner is the smallest number of bytes.

答:
APL (Dyalog Unicode), <s>21</s> 20 bytesSBCS

+/≠/×⊢⌸+\0j1*'^<v'⍳⎕
```

Try it online!

uses ⎕io←1

⎕ input

'^<v'⍳ find the index of each input char among '^<v', i.e. ^ becomes 1, < 2, v 3, and anything else 4

0j1* i to the power (the imaginary constant)

+\ partials sums

⊢⌸ matrix in which each row is the list of occurrences (indices) of a unique partial sum; padded with 0s to make it rectangular

× signum - all indices become 1s, the padding remains 0s

≠/ sum mod 2 for each row

+/ sum

Title: How many lights are on?


答:
The goto operator was added to PHP from version 5.3.0 so you could use the same method as you would in BASIC:

```<code>a: echo chr(47 + 45 * rand(0,1)); goto a;
</code>```

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:
The goto operator was added to PHP from version 5.3.0 so you could use the same method as you would in BASIC:

a: echo chr(47 + 45 * rand(0,1)); goto a;

OwnerDisplayName: MichaelRushton


答:
PowerShell <s>55</s> <s>53</s> 31 Bytes

"$(gc($p='.\1.ps1'))+1"|sc $p;1
```
<p>Read in the file then just add +1 to the end of the file. Powershell will evaluate that as addition so for the fifth pass the file would have <code>....;1+1+1+1+1</code> which evaluates to five!</p>
<p>Old version using saved integer in a variable.</p>
<pre class="lang-ps prettyprint-override"><code>($a=1);$a++;(gc .\1.ps1)-replace'=\d+',"=$a"|sc .\1.ps1
</code>```

Since we can hardcode a name it saves spaces over the script determining its own name. Printer the current value of $a. Increase $a by one. Using regex, replace the digits that follow an equal sign with the now updated value. Then write back to the original file.

If I change the way I locate the first number I can get down to 53. Using a newline I change my regex to look for numbers at the end of a line. This is why I have to a semicolon to the last line to get that omitted.

$a=1
($a++);(gc .\1.ps1)-replace'\d+$',$a|sc .\1.ps1;
```

Body:
PowerShell <s>55</s> <s>53</s> 31 Bytes

"$(gc($p='.\1.ps1'))+1"|sc $p;1

Read in the file then just add +1 to the end of the file. Powershell will evaluate that as addition so for the fifth pass the file would have ....;1+1+1+1+1 which evaluates to five!

Old version using saved integer in a variable.

($a=1);$a++;(gc .\1.ps1)-replace'=\d+',"=$a"|sc .\1.ps1

Since we can hardcode a name it saves spaces over the script determining its own name. Printer the current value of $a. Increase $a by one. Using regex, replace the digits that follow an equal sign with the now updated value. Then write back to the original file.

If I change the way I locate the first number I can get down to 53. Using a newline I change my regex to look for numbers at the end of a line. This is why I have to a semicolon to the last line to get that omitted.

$a=1
($a++);(gc .\1.ps1)-replace'\d+$',$a|sc .\1.ps1;