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

答:
Ruby, <s>64</s> 55 + 1 (p flag) = 56 bytes

Input is a line of STDIN piped in without trailing newline.

a=[]
gsub(/(.)\1*/){a<<$&}
a.sample[-1]*=rand 3
$_=a*''
```

Title: Randomly Misspell a Word


答:
Pip, <s>38</s> 27 bytes

```<code>a@:`(.)\1*`YRR#aa@y@0X:RR3a
</code>```

This was fun--got to use Pip's regex and mutable string capabilities, which I hadn't pulled out in a while. Takes input via command-line argument.

Explanation:

```<code>a@:`(.)\1*`                  Split a into runs of identical chars using regex match
           YRR#a             Yank randrange(len(a)) into y (randomly choosing one such run)
                a@y@0        Take the first character of that run
                     X:RR3   Modify in place, string-multiplying by randrange(3):
                               If RR3 is 0, character is deleted
                               If RR3 is 1, no change
                               If RR3 is 2, character is duplicated
                          a  Output the modified a
</code>```

Try it online!

ContentLicense: CC BY-SA 3.0

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:
Pip, <s>38</s> 27 bytes

a@:`(.)\1*`YRR#aa@y@0X:RR3a

This was fun--got to use Pip's regex and mutable string capabilities, which I hadn't pulled out in a while. Takes input via command-line argument.

Explanation:

a@:`(.)\1*`                  Split a into runs of identical chars using regex match
           YRR#a             Yank randrange(len(a)) into y (randomly choosing one such run)
                a@y@0        Take the first character of that run
                     X:RR3   Modify in place, string-multiplying by randrange(3):
                               If RR3 is 0, character is deleted
                               If RR3 is 1, no change
                               If RR3 is 2, character is duplicated
                          a  Output the modified a

Try it online!


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

答:
Pyth - 7 bytes

Very simple, save as o.txt.

```<code>.wk)l"1
</code>```

(btw to change filename, replace the paren for the .w with a string, like: .wk"file.pyth"l"1

Body:
Pyth - 7 bytes

Very simple, save as o.txt.

.wk)l"1

(btw to change filename, replace the paren for the .w with a string, like: .wk"file.pyth"l"1


答:
V, 15 bytes

```<code>:e z
jñ:wñck0
</code>```

Or, this readable version:

```<code>:e <C-r>z
j<C-a>ñ:wñck0
</code>```

This will not work on the online interpreter, since it disallows file access.

Here is a hexdump:

```<code>00000000: 3a65 2012 7a0a 6a01 f13a 77f1 636b 30    :e .z.j..:w.ck
</code>```

Explanation:

```<code>:e                   "Edit the following file:
   <C-r>z            "Insert the full path to the source file
j                    "Move down a line
 <C-a>               "And increment the first number on this line
      ñ:wñ           "Save this file. Surrounding it with 'ñ' is a fun little hack that allows this to appear on the same line
          ck         "Change this line and the line above us
            0        "To '0' (or whatever number we're on)
</code>```

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:
V, 15 bytes

:e z
jñ:wñck0

Or, this readable version:

:e <C-r>z
j<C-a>ñ:wñck0

This will not work on the online interpreter, since it disallows file access.

Here is a hexdump:

00000000: 3a65 2012 7a0a 6a01 f13a 77f1 636b 30    :e .z.j..:w.ck

Explanation:

:e                   "Edit the following file:
   <C-r>z            "Insert the full path to the source file
j                    "Move down a line
 <C-a>               "And increment the first number on this line
      ñ:wñ           "Save this file. Surrounding it with 'ñ' is a fun little hack that allows this to appear on the same line
          ck         "Change this line and the line above us
            0        "To '0' (or whatever number we're on)


答:
PowerShell, 69/60 57

Further golfed and regex corrected based on feedback from TimmyD and Matt

```<code>($a=1);$a++;(gc($b=$PSCommandPath))-replace"\d+",$a|sc $b
</code>```

69 for completely path and filename agnostic

```<code>($a=1)|oh;$a++;$b=$PSCommandPath;((gc $b)-replace"\d",$a)|Out-File $b
</code>```

60 bytes if I can specify a fixed filename

```<code>($a=1)|oh;$a++;(gc .\a.ps1)-replace"\d",$a)|Out-File .\a.ps1
</code>```

Explanation:

Sets $a to 1, returns it. Then it increments the variable, finds its own invocation path, brings that into memory and uses regex to replace digits with the value in $a, then writes to disk.

Body:
PowerShell, 69/60 57

Further golfed and regex corrected based on feedback from TimmyD and Matt

($a=1);$a++;(gc($b=$PSCommandPath))-replace"\d+",$a|sc $b

69 for completely path and filename agnostic

($a=1)|oh;$a++;$b=$PSCommandPath;((gc $b)-replace"\d",$a)|Out-File $b

60 bytes if I can specify a fixed filename

($a=1)|oh;$a++;(gc .\a.ps1)-replace"\d",$a)|Out-File .\a.ps1

Explanation:

Sets $a to 1, returns it. Then it increments the variable, finds its own invocation path, brings that into memory and uses regex to replace digits with the value in $a, then writes to disk.


答:
C#, 124 bytes

```<code>namespace System.IO{class C{static void Main(){Console.Write(File.ReadAllLines("p").Length);File.AppendAllText("p","\n");}}}
</code>```

Usage: Source file needs to be called p. If using Visual Studio, make sure the Build Action is set to Compile (not default for non-cs files). Also, under project properties ensure the the Output Path is the current directory (ie- empty text box) (again not a default setting).

How it works: It opens the source file and outputs the line count. Then it appends an empty line to the source file.

Pretty print version:

```<code>namespace System.IO // Put in System.IO namespace so no usings needed.
{
    class C
    {
        static void Main()
        {
            Console.Write(File.ReadAllLines("p").Length); // Write line count/run count
            File.AppendAllText("p","\n"); // Increment line count/run count
        }
    }
}
</code>```

Body:
C#, 124 bytes

namespace System.IO{class C{static void Main(){Console.Write(File.ReadAllLines("p").Length);File.AppendAllText("p","\n");}}}

Usage: Source file needs to be called p. If using Visual Studio, make sure the Build Action is set to Compile (not default for non-cs files). Also, under project properties ensure the the Output Path is the current directory (ie- empty text box) (again not a default setting).

How it works: It opens the source file and outputs the line count. Then it appends an empty line to the source file.

Pretty print version:

namespace System.IO // Put in System.IO namespace so no usings needed.
{
    class C
    {
        static void Main()
        {
            Console.Write(File.ReadAllLines("p").Length); // Write line count/run count
            File.AppendAllText("p","\n"); // Increment line count/run count
        }
    }
}


答:
QBasic (QB64), 47 bytes

```<code>OPEN"C:\p.bas"FOR APPEND AS 1:?LOF(1)\2-22:?#1,
</code>```

Adjust the path and filename as desired. Note: you must create the file C:\p.bas with an external text-editor (I used Notepad++) and make sure it does not contain a trailing newline. The QB64 editor adds one when you save the file, which throws off the math and the bytecount. (I assume actual QBasic would do the same, not to mention the auto-formatting.)

Here's an ungolfed version (which does expect a trailing newline):

```<code>OPEN "C:\p.bas" FOR APPEND AS 1
PRINT LOF(1) \ 2 - 32
PRINT #1,
</code>```

How it works

The program opens its own code file in APPEND mode. It then uses LOF to get the length of the current version in bytes. To begin with, this is 47, so we calculate LOF(1)\2-22 (where \ is integer division) and print the resulting 1.

Finally, we want to write some no-op to the end of the file. The shortest way to do this turns out to be writing nothing, with a trailing newline automatically added. Since this is Windows (or DOS), the newline is \r\n, adding two bytes and necessitating the division by 2 earlier in the code.

(Always CLOSE your files when you're done with them, kids. Unless you're golfing.)

Body:
QBasic (QB64), 47 bytes

OPEN"C:\p.bas"FOR APPEND AS 1:?LOF(1)\2-22:?#1,

Adjust the path and filename as desired. Note: you must create the file C:\p.bas with an external text-editor (I used Notepad++) and make sure it does not contain a trailing newline. The QB64 editor adds one when you save the file, which throws off the math and the bytecount. (I assume actual QBasic would do the same, not to mention the auto-formatting.)

Here's an ungolfed version (which does expect a trailing newline):

OPEN "C:\p.bas" FOR APPEND AS 1
PRINT LOF(1) \ 2 - 32
PRINT #1,

How it works

The program opens its own code file in APPEND mode. It then uses LOF to get the length of the current version in bytes. To begin with, this is 47, so we calculate LOF(1)\2-22 (where \ is integer division) and print the resulting 1.

Finally, we want to write some no-op to the end of the file. The shortest way to do this turns out to be writing nothing, with a trailing newline automatically added. Since this is Windows (or DOS), the newline is \r\n, adding two bytes and necessitating the division by 2 earlier in the code.

(Always CLOSE your files when you're done with them, kids. Unless you're golfing.)


答:
Ruby, 37 bytes

```<code>#!ruby -n
gsub(/./){eval"$.=$./2*2#$&2"}
p$./2
</code>```

The shebang counts as 1 byte. This program uses xnor's creative approach. We avoid the need to initialise an accumulator variable by using $.. As it has a value of 1 after the input is read, we have to clear the LSB before applying each operator. This also requires changing &-2 to /2*2 for the correct precedence.

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:
Ruby, 37 bytes

#!ruby -n
gsub(/./){eval"$.=$./2*2#$&2"}
p$./2

The shebang counts as 1 byte. This program uses xnor's creative approach. We avoid the need to initialise an accumulator variable by using $.. As it has a value of 1 after the input is read, we have to clear the LSB before applying each operator. This also requires changing &-2 to /2*2 for the correct precedence.


答:
Python 2, 31 bytes

```<code>open(*'aa').write('+1');print 1
</code>```

Simply appends +1 to the source file upon execution. This program assumes that the source file is named as a. It can be easily modified to work with an arbitrary filename at 38 bytes as follows:

```<code>open(__file__,'a').write('+1');print 1
</code>```

Additionally, a 37 bytes alternative exists though it isn't valid due to the 'no temporary files' rule:

```<code>f=open(*'aa')
print>>f
print f.tell()
</code>```

This program appends a newline to the file a which is assumed not to exist before the first execution of the program. Then, the program prints the file size of a which is simply f.tell() since the file object is now pointing to the end of the file after appending.

Body:
Python 2, 31 bytes

open(*'aa').write('+1');print 1

Simply appends +1 to the source file upon execution. This program assumes that the source file is named as a. It can be easily modified to work with an arbitrary filename at 38 bytes as follows:

open(__file__,'a').write('+1');print 1

Additionally, a 37 bytes alternative exists though it isn't valid due to the 'no temporary files' rule:

f=open(*'aa')
print>>f
print f.tell()

This program appends a newline to the file a which is assumed not to exist before the first execution of the program. Then, the program prints the file size of a which is simply f.tell() since the file object is now pointing to the end of the file after appending.


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

yields 125 lights on.

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

答:
Actually, <s>24</s> 23 bytes

This is a port of Luis Mendo's MATL answer. Golfing suggestions welcome. Try it online!

Edit: One byte thanks to Leaky Nun.

```<code>O⌠4P@%ïⁿ⌡Mσ;╗╔⌠╜c2@%⌡MΣ
</code>```

Ungolfing:

```<code>O        ord(c) of the input string (implicit input)
⌠...⌡M   Start a function, and map over the list of ord(). Call the variable i.
  4P@%     i mod 11 (the 4-th prime).
  ïⁿ       1i to the power of (i%11).

σ        Push a list of cumulative sums of the new list of complex numbers.
           This is a list of the coordinate visited.
;╗       Duplicate coord_list, and push to register 0.
╔        uniquify(coord_list)

⌠...⌡M   Map over the uniquified list. Call the variable j.
  ╜c       Push coord_list.count(j)
  2@%      Push count mod 2

Σ        Return the sum of this last list.
</code>```

Title: How many lights are on?

Body:
Actually, <s>24</s> 23 bytes

This is a port of Luis Mendo's MATL answer. Golfing suggestions welcome. Try it online!

Edit: One byte thanks to Leaky Nun.

O⌠4P@%ïⁿ⌡Mσ;╗╔⌠╜c2@%⌡MΣ

Ungolfing:

O        ord(c) of the input string (implicit input)
⌠...⌡M   Start a function, and map over the list of ord(). Call the variable i.
  4P@%     i mod 11 (the 4-th prime).
  ïⁿ       1i to the power of (i%11).

σ        Push a list of cumulative sums of the new list of complex numbers.
           This is a list of the coordinate visited.
;╗       Duplicate coord_list, and push to register 0.
╔        uniquify(coord_list)

⌠...⌡M   Map over the uniquified list. Call the variable j.
  ╜c       Push coord_list.count(j)
  2@%      Push count mod 2

Σ        Return the sum of this last list.

ContentLicense: CC BY-SA 4.0


问:
Implement glob Matcher
Implement a function of pattern and string to be matched, return true if the pattern matches the WHOLE string, otherwise false.

Our glob pattern syntax is:

? matches any one character

+ matches one or more characters

* matches zero or more characters

\ escapes

Rules:

No eval, no converting into regular expression, no calling a system glob function.

I/O are not required: you can just write a function

Shortest wins

Examples:

```<code>glob('abc', 'abc') => true
glob('abc', 'abcdef') => false IMPORTANT!
glob('a??', 'aww') => true
glob('a*b', 'ab') => true
glob('a*b', 'agwijgwbgioeb') => true
glob('a*?', 'a') => false
glob('?*', 'def') => true
glob('5+', '5ggggg') => true
glob('+', '') => false
glob('a\*b', 'a*b') => true
</code>```

Here is a tip to get started: http://en.wikipedia.org/wiki/Backtracking

答:
golfscript

```<code>{{;;}2$+}:x;{x if}:a;{x\if}:o;{1$1$}:b;{(@(@={\m}a}:r;{b(63={\({\m}a}a{b(43={\({\b m{'+'\+m}o}a}a{b(42={b m{\({\'*'\+m}a}o}a{b(92={r}a{b 0=0=\0=0=*{r}o}o}o}o}o}:m;{[0]+\[0]+m}:glob;
</code>```

it's built out of functions that consume two arguments from the stack, s and p, and produce a single boolean return value. there's a bit of mucking around to make that compatible with the lazy and and lazy or operators. i really doubt this approach is anywhere near optimal, or even in the right direction.

there's also a few entertainingly stupid moments, such as popping a '*' off the pattern, consuming the '*' in a comparison, only to realise that the subsequent branch doesn't match. in order to go down the other branch, we need the pattern with the '*' on the front, but we've consumed that original pattern when we popped the '*', and we consumed the '*', so to get ourselves the pattern again we load a shiny new string constant '*', and prepend it in place. it gets even uglier because for some reason the character matching needs to be done with ascii values, but prepending back onto the string needs strings.

less golfed golfscript

```<code>{[0]+}:terminate_string;
{{;;}2$+if}:_and;
{{;;}2$+\if}:_or;
{1$1$}:branch;
{(@(@={\match}_and}:match_literal;
{0=0=\0=0=*}:match_terminator;
{(92={match_literal}_and}:match_escape;
{(63={\({\match}_and}_and}:match_wildcard;
{(43={\({\branch match{'+'\+match}_or}_and}_and}:match_wildcard_plus;
{(42={branch match{\({\'*'\+match}_and}_or}_and}:match_wildcard_star;
{branch match_wildcard{branch match_wildcard_plus{branch match_wildcard_star{branch match_escape{branch match_terminator{match_literal}_or}_or}_or}_or}_or}:match;
{terminate_string\terminate_string match}:glob;
</code>```

tests

```<code>{2$2$glob = "test passed: " "test FAILED: " if print \ print ' ; ' print print "\n" print}:test_case;

'abc' 'abc' 1 test_case
'abc' 'abcdef' 0 test_case
'a??' 'aww' 1 test_case
'a*b' 'ab' 1 test_case
'a*b' 'agwijgwbgioeb' 1 test_case
'a*?' 'a' 0 test_case
'?*' 'def' 1 test_case
'5+' '5ggggg' 1 test_case
'+' '' 0 test_case
</code>```

ContentLicense: CC BY-SA 2.5

Title: Implement glob Matcher

Body:
golfscript

{{;;}2$+}:x;{x if}:a;{x\if}:o;{1$1$}:b;{(@(@={\m}a}:r;{b(63={\({\m}a}a{b(43={\({\b m{'+'\+m}o}a}a{b(42={b m{\({\'*'\+m}a}o}a{b(92={r}a{b 0=0=\0=0=*{r}o}o}o}o}o}:m;{[0]+\[0]+m}:glob;

it's built out of functions that consume two arguments from the stack, s and p, and produce a single boolean return value. there's a bit of mucking around to make that compatible with the lazy and and lazy or operators. i really doubt this approach is anywhere near optimal, or even in the right direction.

there's also a few entertainingly stupid moments, such as popping a '*' off the pattern, consuming the '*' in a comparison, only to realise that the subsequent branch doesn't match. in order to go down the other branch, we need the pattern with the '*' on the front, but we've consumed that original pattern when we popped the '*', and we consumed the '*', so to get ourselves the pattern again we load a shiny new string constant '*', and prepend it in place. it gets even uglier because for some reason the character matching needs to be done with ascii values, but prepending back onto the string needs strings.

less golfed golfscript

{[0]+}:terminate_string;
{{;;}2$+if}:_and;
{{;;}2$+\if}:_or;
{1$1$}:branch;
{(@(@={\match}_and}:match_literal;
{0=0=\0=0=*}:match_terminator;
{(92={match_literal}_and}:match_escape;
{(63={\({\match}_and}_and}:match_wildcard;
{(43={\({\branch match{'+'\+match}_or}_and}_and}:match_wildcard_plus;
{(42={branch match{\({\'*'\+match}_and}_or}_and}:match_wildcard_star;
{branch match_wildcard{branch match_wildcard_plus{branch match_wildcard_star{branch match_escape{branch match_terminator{match_literal}_or}_or}_or}_or}_or}:match;
{terminate_string\terminate_string match}:glob;

tests

{2$2$glob = "test passed: " "test FAILED: " if print \ print ' ; ' print print "\n" print}:test_case;

'abc' 'abc' 1 test_case
'abc' 'abcdef' 0 test_case
'a??' 'aww' 1 test_case
'a*b' 'ab' 1 test_case
'a*b' 'agwijgwbgioeb' 1 test_case
'a*?' 'a' 0 test_case
'?*' 'def' 1 test_case
'5+' '5ggggg' 1 test_case
'+' '' 0 test_case


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

答:
APL 198 * 50% = 99

```<code>z←W n
l←⍉(n⍴3)⊤w←0,⍳+/b←3*0,⍳n-1
r←(⍴l)⍴0
:while 0≠+/+/l>1
    r←r+l>1
    l←((l≤1)×l)+1⌽l>1
:end
a←' ',⌽⎕av[97+⍳n]
c←(⍴l)⍴⍳n
b←0,⌽b
z←l≠r
l←z×l
r←z×r
l←1+l×c
r←1+r×c
z←w,'{',a[l],'}','{',a[r],'}','{',b[l],'}','{',b[r],'}'
</code>```

As we are effectively working in base three the arithmetic is fairly trivial and is complete by the end of the while loop where the arrays l and r are the contents of the left and right scale pans respectively in base three. This takes about 80 characters. The rest is formatting the output which I am sure can be improved.

To run simply type W followed by the number of weights you want to use. Below is a sample output for n=3:

```<code> W 3
 0 {   }{   }{ 0 0 0 }{ 0 0 0 }
 1 {  a}{   }{ 0 0 1 }{ 0 0 0 }
 2 { b }{  a}{ 0 3 0 }{ 0 0 1 }
 3 { b }{   }{ 0 3 0 }{ 0 0 0 }
 4 { ba}{   }{ 0 3 1 }{ 0 0 0 }
 5 {c  }{ ba}{ 9 0 0 }{ 0 3 1 }
 6 {c  }{ b }{ 9 0 0 }{ 0 3 0 }
 7 {c a}{ b }{ 9 0 1 }{ 0 3 0 }
 8 {c  }{  a}{ 9 0 0 }{ 0 0 1 }
 9 {c  }{   }{ 9 0 0 }{ 0 0 0 }
10 {c a}{   }{ 9 0 1 }{ 0 0 0 }
11 {cb }{  a}{ 9 3 0 }{ 0 0 1 }
12 {cb }{   }{ 9 3 0 }{ 0 0 0 }
13 {cba}{   }{ 9 3 1 }{ 0 0 0 }
</code>```

Body:
APL 198 * 50% = 99

z←W n
l←⍉(n⍴3)⊤w←0,⍳+/b←3*0,⍳n-1
r←(⍴l)⍴0
:while 0≠+/+/l>1
    r←r+l>1
    l←((l≤1)×l)+1⌽l>1
:end
a←' ',⌽⎕av[97+⍳n]
c←(⍴l)⍴⍳n
b←0,⌽b
z←l≠r
l←z×l
r←z×r
l←1+l×c
r←1+r×c
z←w,'{',a[l],'}','{',a[r],'}','{',b[l],'}','{',b[r],'}'

As we are effectively working in base three the arithmetic is fairly trivial and is complete by the end of the while loop where the arrays l and r are the contents of the left and right scale pans respectively in base three. This takes about 80 characters. The rest is formatting the output which I am sure can be improved.

To run simply type W followed by the number of weights you want to use. Below is a sample output for n=3:

 W 3
 0 {   }{   }{ 0 0 0 }{ 0 0 0 }
 1 {  a}{   }{ 0 0 1 }{ 0 0 0 }
 2 { b }{  a}{ 0 3 0 }{ 0 0 1 }
 3 { b }{   }{ 0 3 0 }{ 0 0 0 }
 4 { ba}{   }{ 0 3 1 }{ 0 0 0 }
 5 {c  }{ ba}{ 9 0 0 }{ 0 3 1 }
 6 {c  }{ b }{ 9 0 0 }{ 0 3 0 }
 7 {c a}{ b }{ 9 0 1 }{ 0 3 0 }
 8 {c  }{  a}{ 9 0 0 }{ 0 0 1 }
 9 {c  }{   }{ 9 0 0 }{ 0 0 0 }
10 {c a}{   }{ 9 0 1 }{ 0 0 0 }
11 {cb }{  a}{ 9 3 0 }{ 0 0 1 }
12 {cb }{   }{ 9 3 0 }{ 0 0 0 }
13 {cba}{   }{ 9 3 1 }{ 0 0 0 }


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

答:
Jelly, 6 bytes

```<code>DI⁼1,1
</code>```

Try it online! or verify all test cases.

How it works

```<code>DI⁼1,1  Main link. Argument: n (integer)

D       Decimal; convert n to base 10.
 I      Increments; compute the differences of all pairs of adjacent digits.
   1,1  Yield [1, 1].
  ⁼     Test the results to both sides for equality.
</code>```

Title: As Easy as One-Two-Three

Body:
Jelly, 6 bytes

DI⁼1,1

Try it online! or verify all test cases.

How it works

DI⁼1,1  Main link. Argument: n (integer)

D       Decimal; convert n to base 10.
 I      Increments; compute the differences of all pairs of adjacent digits.
   1,1  Yield [1, 1].
  ⁼     Test the results to both sides for equality.


答:
MATL, 8 bytes

```<code>d1=tn2=*
</code>```

Try it online!

This will print 1 1 for a truthy input, and an array with a 0 in it for a falsy value, since that is falsy in MATL.

Explanation:

```<code>d           % Calculate the difference between consecutive digits
 1=         % Push an array of which elements equal one
   t        % Duplicate this array
    n       % Push the length of this array
     2=     % Push a one if the length is 2, and a zero otherwise
            % Now, if we have a truthy input, the stack looks like:
            %   [1 1]
            %   1
            % And if we have a falsy input, the stack looks something like this:
            %   [1 0]
            %   1
            % Or this:
            %   [1 1]
            %   0
       *    % Multiply the top two elements
</code>```

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:
MATL, 8 bytes

d1=tn2=*

Try it online!

This will print 1 1 for a truthy input, and an array with a 0 in it for a falsy value, since that is falsy in MATL.

Explanation:

d           % Calculate the difference between consecutive digits
 1=         % Push an array of which elements equal one
   t        % Duplicate this array
    n       % Push the length of this array
     2=     % Push a one if the length is 2, and a zero otherwise
            % Now, if we have a truthy input, the stack looks like:
            %   [1 1]
            %   1
            % And if we have a falsy input, the stack looks something like this:
            %   [1 0]
            %   1
            % Or this:
            %   [1 1]
            %   0
       *    % Multiply the top two elements


答:
Brachylog, 9 bytes

```<code>h:2j:12+?
</code>```

Try it online! or Verify all test-cases.

Credits to Dennis for the algorithm.

In English, "(prove that) the Input's first digit, concatenated to itself twice, add 12, is still the Input."

Title: As Easy as One-Two-Three

Body:
Brachylog, 9 bytes

h:2j:12+?

Try it online! or Verify all test-cases.

Credits to Dennis for the algorithm.

In English, "(prove that) the Input's first digit, concatenated to itself twice, add 12, is still the Input."


答:
CJam, <s>13</s> 9 bytes

```<code>A,s3ewqe=
</code>```

Try it online!

Explanation

```<code>A,s        e# Push "0123456789".
   3ew     e# Split it into contiguous length-3 chunks: ["012" "123" "234" ... "789"].
      q    e# Push the input.
       e=  e# Count the number of times the input appears in the array.
</code>```

Title: As Easy as One-Two-Three

Body:
CJam, <s>13</s> 9 bytes

A,s3ewqe=

Try it online!

Explanation

A,s        e# Push "0123456789".
   3ew     e# Split it into contiguous length-3 chunks: ["012" "123" "234" ... "789"].
      q    e# Push the input.
       e=  e# Count the number of times the input appears in the array.


答:
Python 2, 25 bytes

lambda n:`n-12`==`n`[0]*3
```

Test it on Ideone.

Title: As Easy as One-Two-Three

Body:
Python 2, 25 bytes

lambda n:`n-12`==`n`[0]*3

Test it on Ideone.


答:
Java 7, 46 bytes

```<code>boolean f(int a){return a>12&a<790&a%111==12;}
</code>```

After trying several things with Leaky Nun in chat, this seems to be the shortest. Sometimes you just have to do things the straightforward way :/

Explanation:

```<code>boolean f(int a){
    return a>12         Is it more than 12? (stupid edge case)
           &
           a<790        Is it in range the other way?
           &
           a%111==12;   Is it 12 more than a multiple of 111?
}
</code>```

Title: As Easy as One-Two-Three

Body:
Java 7, 46 bytes

boolean f(int a){return a>12&a<790&a%111==12;}

After trying several things with Leaky Nun in chat, this seems to be the shortest. Sometimes you just have to do things the straightforward way :/

Explanation:

boolean f(int a){
    return a>12         Is it more than 12? (stupid edge case)
           &
           a<790        Is it in range the other way?
           &
           a%111==12;   Is it 12 more than a multiple of 111?
}


答:
Excel - 104 bytes

```<code>=IF(LEN(N)<3,"Falsy",IF(AND(LEN(N)=3,MID(N,2,1)-MID(N,1,1)=1,MID(N,3,1)-MID(N,2,1)=1),"Truthy","Falsy"))
</code>```

Explanation:

The syntax for the IF formula in Excel is:

```<code>IF( condition, [value_if_true], [value_if_false] )
</code>```

If the length of input N, where it's a name of the reference cell, is less than 3, then it will return Falsy. Else, if the length of input N is 3 and both of the difference of second digit and first digit and the difference of third digit and second digit are equal to 1, then it will return Truthy.

Title: As Easy as One-Two-Three

Body:
Excel - 104 bytes

=IF(LEN(N)<3,"Falsy",IF(AND(LEN(N)=3,MID(N,2,1)-MID(N,1,1)=1,MID(N,3,1)-MID(N,2,1)=1),"Truthy","Falsy"))

Explanation:

The syntax for the IF formula in Excel is:

IF( condition, [value_if_true], [value_if_false] )

If the length of input N, where it's a name of the reference cell, is less than 3, then it will return Falsy. Else, if the length of input N is 3 and both of the difference of second digit and first digit and the difference of third digit and second digit are equal to 1, then it will return Truthy.


答:
Python, 24 bytes

lambda n:n%111==12<n<900
```

Just a lot of condition chaining.

Title: As Easy as One-Two-Three

Body:
Python, 24 bytes

lambda n:n%111==12<n<900

Just a lot of condition chaining.


Title: As Easy as One-Two-Three

Body:
Brain-Flak, 99 bytes

([{}]({})<>)<>([{}]{}<>)(({})<([{}]{})((){[()](<{}>)}{})>)([{}]{})((){[()](<{}>)}{})<>{{{}}<>{}}<>

Try it online!

This is 98 bytes of code +1 for the -a flag.

This prints 1 for truthy, and either 0 or nothing (which is equivalent to 0) for falsy


问:
Russian Roulette
Write a program which plays Russian Roulette!

If the program is started,

there should be a 5 in 6 chance of it ending normally after printing "I survived!"

there should be a 1 in 6 chance of the program crashing. (segmentation fault, etc.)

No input, and no other outputs are allowed.

The randomness must be fair: it must have a uniform probability distribution. This means an uninitialized variable (or a RNG without seed) MOD 6 will not be sufficient.

If the solution works with only one dedicated operating system / platform, you will receive a 6 byte penalty to the score.

Shortest code wins, not sooner than 10 days after first valid answer.

答:
Python (56), Haskell (77)

This crashes with an IndexError when the generated number is 1:

```
from random import*
print['I survived!'][1/randint(1,7)]
```

The Haskell solution has the same idea:

```
import System.Random
main=putStrLn.(["I survived!"]!!).div 1=<<randomRIO(1,6)
```

Title: Russian Roulette

Body:
Python (56), Haskell (77)

This crashes with an IndexError when the generated number is 1:

from random import*
print['I survived!'][1/randint(1,7)]

The Haskell solution has the same idea:

import System.Random
main=putStrLn.(["I survived!"]!!).div 1=<<randomRIO(1,6)


答:
Python, 24 bytes

range(123,790,111).count
```
<p>An anonymous function that outputs 0 or 1. It creates the list <code>[123, 234, 345, 456, 567, 678, 789]</code> and counts how many times the input appears.</p>
<pre class="lang-python prettyprint-override"><code>f=range(123,790,111).count

f(123)
=> 1
f(258)
=> 0
</code>```

Title: As Easy as One-Two-Three

Body:
Python, 24 bytes

range(123,790,111).count

An anonymous function that outputs 0 or 1. It creates the list [123, 234, 345, 456, 567, 678, 789] and counts how many times the input appears.

f=range(123,790,111).count

f(123)
=> 1
f(258)
=> 0


答:
Haskell, 22 bytes

(`elem`[123,234..789])
```

An anonymous function. Generates the evenly-spaced list [123, 234, 345, 456, 567, 678, 789] and checks if the input is an element.

Title: As Easy as One-Two-Three

Body:
Haskell, 22 bytes

(`elem`[123,234..789])

An anonymous function. Generates the evenly-spaced list [123, 234, 345, 456, 567, 678, 789] and checks if the input is an element.


答:
Pyth, 8 Bytes

```<code>qi>3SeQT
</code>```

Try online!

Explanation:

```<code>q       Q  Is the input equal to:
  <3S       The last three digits of the range from 1 to
     eQ      The last digit of the input
 i     T      Concatenated together into an integer
</code>```

Title: As Easy as One-Two-Three

Body:
Pyth, 8 Bytes

qi>3SeQT

Try online!

Explanation:

q       Q  Is the input equal to:
  <3S       The last three digits of the range from 1 to
     eQ      The last digit of the input
 i     T      Concatenated together into an integer


Title: As Easy as One-Two-Three

Body:
Ruby -nl, <s>32</s> <s>30</s> 25 bytes

p"123456789"[$_]&.size==3

Attempt This Online!


Title: As Easy as One-Two-Three

Body:
Brain-Flak 76 + 3 = 79 bytes

This answer is a golf of this answer.  I don't actually know quite how my answer works but DJMcMayhem gives a good explanation in his original answer and my answer is a modification of his.

([]<>)<>({}[({})]<>)<>(({}[({})()()()()()]<>{}{}<(())>)){{}{}(((<{}>)))}{}{}

It is run with the -a ascii flag adding 3 bytes.

Explanation (of sorts)

Starting with the original working solution:

([]<>)<>({}[({})]<>)<>({}[({})]<>)({}{}[()()])({}<({}[()()()])>)(({}{}<(())>)){{}{}(((<{}>)))}{}{}

I run this through a simple golfing algorithm I wrote and get:

([]<>)<>({}[({})]<>)<>(({}[({})]<>{}[()()]<({}[()()()])>{}<(())>)){{}{}(((<{}>)))}{}{}

From here I see the section <({}[()()()])>{} this essentially multiplies by one which makes it equal to {}[()()()] reduce the whole code to:

([]<>)<>({}[({})]<>)<>(({}[({})]<>{}[()()]{}[()()()]<(())>)){{}{}(((<{}>)))}{}{}

Lastly negatives can be combined:

([]<>)<>({}[({})]<>)<>(({}[({})()()()()()]<>{}{}<(())>)){{}{}(((<{}>)))}{}{}


答:
Brainfuck, 43 bytes

```<code>,>,>,>,[>>]<[[-<-<->>]<+[>>]<++[>>->]<+<]>.
</code>```

Bah, I'm no good at this. Outputs \x01 if the output is one of the strings 123, 234, …, 789; outputs \x00 otherwise.

(I beat Java 7, though…)

Try it online!

Title: As Easy as One-Two-Three

Body:
Brainfuck, 43 bytes

,>,>,>,[>>]<[[-<-<->>]<+[>>]<++[>>->]<+<]>.

Bah, I'm no good at this. Outputs \x01 if the output is one of the strings 123, 234, …, 789; outputs \x00 otherwise.

(I beat Java 7, though…)

Try it online!


答:
Perl 6, <s> 35 29 24 21 </s> 19 bytes

<s>{.chars==3&&'0123456789'.index: $_}
{$_ (elem) (123,*+111...789)}
{$_∈(123,*+111...789)}
*∈(123,*+111...789)</s>
*∈(123,234...789)```

<h2>Explanation:</h2>

<pre class="lang-perl6 prettyprint-override"><code># Whatever lambda ( the parameter is ｢*｣ )
*

∈ # is it an element of:

# this sequence
(
  123,
  234,

  # deduce rest of sequence
  ...

  # stop when you generate this value
  789
)
</code>```

Usage:

my &code = *∈(123,234...789);

say code 123; # True
say code 472; # False

say (  *∈(123,234...789)  )( 789 ); # True
```

Title: As Easy as One-Two-Three

Body:
Perl 6, <s> 35 29 24 21 </s> 19 bytes

<s>{.chars==3&&'0123456789'.index: $_}
{$_ (elem) (123,*+111...789)}
{$_∈(123,*+111...789)}
*∈(123,*+111...789)</s>
*∈(123,234...789)

Explanation:

# Whatever lambda ( the parameter is ｢*｣ )
*

∈ # is it an element of:

# this sequence
(
  123,
  234,

  # deduce rest of sequence
  ...

  # stop when you generate this value
  789
)

Usage:

my &code = *∈(123,234...789);

say code 123; # True
say code 472; # False

say (  *∈(123,234...789)  )( 789 ); # True


答:
Retina, 26

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

Outputs 1 for truthy and 0 for falsey.

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

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:
Retina, 26

.
$*:
^(:+ ):\1::\1$

Outputs 1 for truthy and 0 for falsey.

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


问:
First-n Fibonacci sequence elements
There is a well known question here that asks for a short (least characters) fibonacci sequence generator.

I would like to know if someone can generate the first N elements only, of the fibonacci sequence, in very short space.   I am trying to do it in python, but I'm interested in any short answer, in any language.  Function F(N) generates the first N elements of the sequence, either returns them as the return of the function or prints them.

Interestingly it seems that the code-golf answers start with 1 1 2, instead of 0 1 1 2. Is that a convention in code-golf or programming-in-general?  (Wikipedia says the fibonacci sequence starts with zero.).

Python Sample (First 5 Elements):

```<code>def f(i,j,n):
    if n>0:
        print i;
        f(j,i+j,n-1)
f(1,1,5)
</code>```

答:
Haskell (26)

Surprisingly, this is only one character longer than the J solution.

```
f=(`take`s)
s=0:scanl(+)1s
```

I shave off a few characters by:

Using take as a binary operator;

Using scanl instead of the verbose zipWith.

Title: First-n Fibonacci sequence elements

Body:
Haskell (26)

Surprisingly, this is only one character longer than the J solution.

f=(`take`s)
s=0:scanl(+)1s

I shave off a few characters by:

Using take as a binary operator;

Using scanl instead of the verbose zipWith.


答:
bash (+ wc + id), 16 bytes

```<code>wc -l<$0;id>>$0

</code>```

Counts its lines, then appends a line of garbage to itself.

Needs a trailing newline.

Crashes on line 2 with a syntax error, which thankfully prints to STDERR and exits.

After three invocations, the script looks like this for me:

```<code>wc -l<$0;id>>$0
uid=1000(lynn) gid=1000(lynn) groups=1000(lynn),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),113(lpadmin),128(sambashare)
uid=1000(lynn) gid=1000(lynn) groups=1000(lynn),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),113(lpadmin),128(sambashare)
uid=1000(lynn) gid=1000(lynn) groups=1000(lynn),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),113(lpadmin),128(sambashare)

</code>```

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:
bash (+ wc + id), 16 bytes

wc -l<$0;id>>$0

Counts its lines, then appends a line of garbage to itself.

Needs a trailing newline.

Crashes on line 2 with a syntax error, which thankfully prints to STDERR and exits.

After three invocations, the script looks like this for me:

wc -l<$0;id>>$0
uid=1000(lynn) gid=1000(lynn) groups=1000(lynn),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),113(lpadmin),128(sambashare)
uid=1000(lynn) gid=1000(lynn) groups=1000(lynn),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),113(lpadmin),128(sambashare)
uid=1000(lynn) gid=1000(lynn) groups=1000(lynn),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),113(lpadmin),128(sambashare)


答:
Javascript (Node.js), 92 bytes

```<code>s=require('fs')
f=s.readFileSync(l=__filename)
console.log(f.length-91)
s.writeFile(l,f+';')
</code>```

Prints out the length of the file minus 91, and adds a semicolon (which is ignored by the interpreter) to the final line of the file each time it is run

Body:
Javascript (Node.js), 92 bytes

s=require('fs')
f=s.readFileSync(l=__filename)
console.log(f.length-91)
s.writeFile(l,f+';')

Prints out the length of the file minus 91, and adds a semicolon (which is ignored by the interpreter) to the final line of the file each time it is run


答:
Excel - 62 57 35 31 bytes

Based on Anastasiya-Romanova's answer, but returning Excel's TRUE/FALSE values.

```<code>=AND(LEN(N)=3,MID(N,2,1)-MID(N,1,1)=1,MID(N,3,1)-MID(N,2,1)=1)
</code>```

Further, we can get to

```<code>=AND(LEN(N)=3,MID(N,2,1)-LEFT(N)=1,RIGHT(N)-MID(N,2,1)=1)
</code>```

since both RIGHT and LEFT return a single character by default.

And, inspired by some of the Python solutions:

```<code>=AND(LEN(N)=3,MOD(N,111)=12,N<>900)
</code>```

Thanks to Neil for 4 more bytes...

```<code>=AND(N>99,MOD(N,111)=12,N<900)
</code>```

Title: As Easy as One-Two-Three

Body:
Excel - 62 57 35 31 bytes

Based on Anastasiya-Romanova's answer, but returning Excel's TRUE/FALSE values.

=AND(LEN(N)=3,MID(N,2,1)-MID(N,1,1)=1,MID(N,3,1)-MID(N,2,1)=1)

Further, we can get to

=AND(LEN(N)=3,MID(N,2,1)-LEFT(N)=1,RIGHT(N)-MID(N,2,1)=1)

since both RIGHT and LEFT return a single character by default.

And, inspired by some of the Python solutions:

=AND(LEN(N)=3,MOD(N,111)=12,N<>900)

Thanks to Neil for 4 more bytes...

=AND(N>99,MOD(N,111)=12,N<900)


答:
Brainfuck, 32 bytes

```<code>+>,+>,>,-[-<-<->>],[<]<[<]<[<]<.
</code>```

Try it online!

Credits to Lynn for the core of the algorithm.

Title: As Easy as One-Two-Three

Body:
Brainfuck, 32 bytes

+>,+>,>,-[-<-<->>],[<]<[<]<[<]<.

Try it online!

Credits to Lynn for the core of the algorithm.


答:
PHP, 38 bytes

There are so many ways in PHP to do that ... this one´s the shortest I could find:

```<code><?=stat(n)[7]-37;fputs(fopen(n,a),1);#
</code>```

print file size (initially 38) -37, append a character (1 in this case) to the comment at the end.

save with file name n, call with php n

make sure that the file contains no trailing newline

fclose is called implicitly when the script finishes.

if you pick another filename, replace 37 with the new file size -1.

if filename gets longer than 5 characters (including eventual quotation marks), use $n=filename for the first occurence, $n for the second.

if filename gets longer than 7 characters, use __FILE__ instead of the literal file name.

Body:
PHP, 38 bytes

There are so many ways in PHP to do that ... this one´s the shortest I could find:

<?=stat(n)[7]-37;fputs(fopen(n,a),1);#

print file size (initially 38) -37, append a character (1 in this case) to the comment at the end.

save with file name n, call with php n

make sure that the file contains no trailing newline

fclose is called implicitly when the script finishes.

if you pick another filename, replace 37 with the new file size -1.

if filename gets longer than 5 characters (including eventual quotation marks), use $n=filename for the first occurence, $n for the second.

if filename gets longer than 7 characters, use __FILE__ instead of the literal file name.


答:
05AB1E, 5 bytes

```<code>¥XX‚Q
</code>```

Explanation

```<code>¥      # deltas
    Q  # are equal to
 XX‚   # [1,1]
</code>```

Try it online

Title: As Easy as One-Two-Three

Body:
05AB1E, 5 bytes

¥XX‚Q

Explanation

¥      # deltas
    Q  # are equal to
 XX‚   # [1,1]

Try it online


答:
Dyalog APL, 21 bytes

Define f as the following:

(⎕FX⊢2-⍨⍴)'⍝',⍨⎕NR'f'
```
<p><code>⎕NR'f'</code> the <strong>N</strong>ested <strong>R</strong>epresentation of <code>f</code>; on the first run, this is {<code>f</code>, <code>(⎕FX⊢2-⍨⍴)'⍝',⍨⎕NR'f'</code>}</p>
<p><code>'⍝',⍨</code> append a comment symbol, giving {<code>f</code>, <code>(⎕FX⊢2-⍨⍴)'⍝',⍨⎕NR'f'</code>, <code>⍝</code>}</p>
<p><code>(</code>...<code>)</code> apply the following function:</p>
<p> <code>⎕FX</code> <strong>F</strong>i<strong>x</strong> definition of <code>f</code></p>
<p> <code>⊢</code> then</p>
<p> <code>2-⍨</code> subtract two from</p>
<p> <code>⍴</code> the length of the argument (3 on the first run)</p>
<p>Example run:</p>
<pre class="lang-apl prettyprint-override"><code>      f
1
      f
2
      f
3
</code>```

Body:
Dyalog APL, 21 bytes

Define f as the following:

(⎕FX⊢2-⍨⍴)'⍝',⍨⎕NR'f'

⎕NR'f' the Nested Representation of f; on the first run, this is {f, (⎕FX⊢2-⍨⍴)'⍝',⍨⎕NR'f'}

'⍝',⍨ append a comment symbol, giving {f, (⎕FX⊢2-⍨⍴)'⍝',⍨⎕NR'f', ⍝}

(...) apply the following function:

 ⎕FX Fix definition of f

 ⊢ then

 2-⍨ subtract two from

 ⍴ the length of the argument (3 on the first run)

Example run:

      f
1
      f
2
      f
3


答:
Dyalog APL, 10 bytes

Takes string argument.

1 1≡¯2-/⍎¨
```

1 1≡ Is {1, 1} identical to

¯2-/ the reversed pair-wise difference of

⍎¨ each character taken as a number?

TryAPL online! (⍎ has been emulated with e for security reasons.)

Title: As Easy as One-Two-Three

Body:
Dyalog APL, 10 bytes

Takes string argument.

1 1≡¯2-/⍎¨

1 1≡ Is {1, 1} identical to

¯2-/ the reversed pair-wise difference of

⍎¨ each character taken as a number?

TryAPL online! (⍎ has been emulated with e for security reasons.)


答:
Perl, 18 bytes

Includes +1 for -p

Run with the input on STDIN

```<code>123.pl <<< 123
</code>```

123.pl:

```<code>#!/usr/bin/perl -p
$_=$_=/./.2==$_-$&x3
</code>```

Title: As Easy as One-Two-Three

Body:
Perl, 18 bytes

Includes +1 for -p

Run with the input on STDIN

123.pl <<< 123

123.pl:

#!/usr/bin/perl -p
$_=$_=/./.2==$_-$&x3


问:
Implement a Truth-Machine
A truth-machine (credits goes to this guy for coming up with it) is a very simple program designed to demonstrate the I/O and control flow of a language. Here's what a truth-machine does:

Gets a number (either 0 or 1) from STDIN.

If that number is 0, print out 0 and terminate.

If that number is 1, print out 1 forever.

Challenge

Write a truth-machine as described above in your language of choice. The truth-machine must be a full program that follows these rules:

take input from STDIN or an acceptable alternative

If your language cannot take input from STDIN, it may take input from a hardcoded variable or suitable equivalent in the program

must output to STDOUT or an acceptable alternative

If your language is incapable of outputting the characters 0 or 1, byte or unary I/O is acceptable.

when the input is 1, it must continually print 1s and only stop if the program is killed or runs out of memory

the output must only be either a 0 followed by either one or no newline or space, or infinite 1s with each 1 followed by either one or no newline or space. No other output can be generated, except constant output of your language's interpreter that cannot be suppressed (such as a greeting, ANSI color codes or indentation). Your usage of newlines or spaces must be consistent: for example, if you choose to output 1 with a newline after it all 1s must have a newline after them.

if and only if your language cannot possibly terminate on an input of 0 it is acceptable for the code to enter an infinite loop in which nothing is outputted.

Since this is a catalog, languages created after this challenge are allowed to compete. Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. Other than that, all the standard rules of code-golf must be obeyed. Submissions in most languages will be scored in bytes in an appropriate preexisting encoding (usually UTF-8).

Catalog

The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```<code>## Language Name, N bytes
</code>```

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

```<code>## Ruby, <s>104</s> <s>101</s> 96 bytes
</code>```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

```<code>## Perl, 43 + 2 (-p flag) = 45 bytes
</code>```

You can also make the language name a link which will then show up in the snippet:

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
dc, <s>13</s> 12 bytes

?[pd1=@]ds@x
```

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

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

Adding to the diversity of languages used, I present a dc solution that works as follows:

?              # reads the input and pushes it on top of the stack
[pd1=@]ds@x    # stores the macro command [pd1=@] into register '@' and executes it
   p           # prints the value on top of the stack
   d           # makes a duplicate that is pushed on top
   1=@         # pushes 1, pops two numbers and if they are equal, the macro from
               #register '@' is executed (again), thus making an infinite cycle
```

Title: Implement a Truth-Machine

Body:
dc, <s>13</s> 12 bytes

?[pd1=@]ds@x

Run:

dc -f truth_machine.dc <<< "1"

Adding to the diversity of languages used, I present a dc solution that works as follows:

?              # reads the input and pushes it on top of the stack
[pd1=@]ds@x    # stores the macro command [pd1=@] into register '@' and executes it
   p           # prints the value on top of the stack
   d           # makes a duplicate that is pushed on top
   1=@         # pushes 1, pops two numbers and if they are equal, the macro from
               #register '@' is executed (again), thus making an infinite cycle


问:
Shortest power set implementation

Problem definition

Print out the powerset of a given set. For example:

```<code>[1, 2, 3] => [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
</code>```

Each element is to be printed on a separate line, so the above example would be printed as:

```<code>[]
[1]
[2]
...
[1, 2, 3]
</code>```

Example code (in D, python example here):

```<code>import std.stdio;

string[][] powerset(string[] set) {
    if (set.length == 1) {
        return [set, []];
    }

    string[][] ret;
    foreach (item; powerset(set[1 .. $])) {
        ret ~= set[0]~item;
        ret ~= item;
    }

    return ret;
}

void main(string[] argv) {
    foreach (set; powerset(argv[1 .. $]))
        writeln(set);
}
</code>```

Input

Elements will be passed as arguments. For example, the example provided above would be passed to a program called powerset as:

```<code>powerset 1 2 3
</code>```

Arguments will be alphanumeric.

Rules

No libraries besides io

Output does not have to be ordered

Powerset does not have to be stored, only printed

Elements in the set must be delimited (e.g. 1,2,3, [1,2,3] and ['1','2','3'] are acceptable, but 123 is not

Trailing delimiters are fine (e.g. 1,2,3, == 1,2,3)

Best is determined based on number of bytes

The best solution will be decided no less than 10 days after the first submission.

答:
Haskell (96)

```
import Control.Monad
import System.Environment
main=getArgs>>=mapM print.filterM(\_->[False ..])
```

If importing Control.Monad isn't allowed, this becomes 100 characters:

```
import System.Environment
main=getArgs>>=mapM print.p
p z=case z of{[]->[[]];x:y->p y++map(x:)(p y)}
```

Title: Shortest power set implementation

Body:
Haskell (96)

import Control.Monad
import System.Environment
main=getArgs>>=mapM print.filterM(\_->[False ..])

If importing Control.Monad isn't allowed, this becomes 100 characters:

import System.Environment
main=getArgs>>=mapM print.p
p z=case z of{[]->[[]];x:y->p y++map(x:)(p y)}


答:
JavaScript ES6, 26 bytes

n=>1>(n-12)%111&n>99&n<790

This takes advantage of the fact that I'm using bit-wise logic operators on what are essentially booleans (which are bit-based!)

Thanks to Titus for saving 2.

Title: As Easy as One-Two-Three


答:
Perl (+shell), 30 bytes

self.pl:

```<code>#!/usr/bin/perl
print 1;`$^X -pi -es/1/1+1/ $0`
</code>```

Works as shown, but replace ^X by the literal control byte for the claimed score. This does lead to a warning on recent perl versions though.

Because the filename is passed through the shell it should not contain any special characters.

A pure perl version weights in at 32 bytes (or 33 if you add a -X option to suppress the -i warning)

```<code>#!/usr/bin/perl -pi
INIT{print 1;@ARGV=$0}s/1/1+1/
</code>```

If you don't mind calling with perl -M5.010 in both version 2 more bytes can be removed by using say instead of print

Body:
Perl (+shell), 30 bytes

self.pl:

#!/usr/bin/perl
print 1;`$^X -pi -es/1/1+1/ $0`

Works as shown, but replace ^X by the literal control byte for the claimed score. This does lead to a warning on recent perl versions though.

Because the filename is passed through the shell it should not contain any special characters.

A pure perl version weights in at 32 bytes (or 33 if you add a -X option to suppress the -i warning)

#!/usr/bin/perl -pi
INIT{print 1;@ARGV=$0}s/1/1+1/

If you don't mind calling with perl -M5.010 in both version 2 more bytes can be removed by using say instead of print


答:
R, <s>30</s> 22 bytes

```<code>scan()%in%(12+1:7*111)
</code>```

Not particularly exciting; check if input is in the sequence given by 12 + 111k, where k is each of 1 to 7. Note that : precedes * so the multiplication happens after the sequence is generated.

Title: As Easy as One-Two-Three

Body:
R, <s>30</s> 22 bytes

scan()%in%(12+1:7*111)

Not particularly exciting; check if input is in the sequence given by 12 + 111k, where k is each of 1 to 7. Note that : precedes * so the multiplication happens after the sequence is generated.


答:
CJam (21 bytes)

```<code>re`_,mr_2$=3mr(a.+te~
</code>```

Online demo

Dissection

```<code>r     e# Read a line of input from stdin
e`    e# Run-length encode it
_,mr  e# Select a random index in the RLE array
_     e# Hang on to a copy of that index
2$=   e# Copy the [run-length char] pair from that index
3mr(  e# Select a uniformly random integer from {-1, 0, 1}
a.+   e# Add it to the run-length
t     e# Replace the pair at that index
e~    e# Run-length decode
</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:
CJam (21 bytes)

re`_,mr_2$=3mr(a.+te~

Online demo

Dissection

r     e# Read a line of input from stdin
e`    e# Run-length encode it
_,mr  e# Select a random index in the RLE array
_     e# Hang on to a copy of that index
2$=   e# Copy the [run-length char] pair from that index
3mr(  e# Select a uniformly random integer from {-1, 0, 1}
a.+   e# Add it to the run-length
t     e# Replace the pair at that index
e~    e# Run-length decode


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:
Java 7, 73 bytes

int c(char[]i){int r=0;for(int c:i)r=c<43?r*2:c<46?r+44-c:r>>1;return r;}

Shamelessly stolen from @Scepheo's amazing C# answer and implemented in Java 7.

Ungolfed & test cases:

Try it here.

class M{
  static int c(char[] i){
    int r = 0;
    for(int c : i) {
      r = c < 43
           ? r * 2
           : c < 46
              ? r+44 - c
              : r >> 1;
    }
    return r;
  }

  public static void main(String[] a){
    System.out.println(c("*///*-*+-+".toCharArray()));
    System.out.println(c("/*+/*+++/*///*/+-+//*+-+-/----*-*-+++*+**+/*--///+*-/+//*//-+++--++/-**--/+--/*-/+*//*+-*-*/*+*+/+*-".toCharArray()));
    System.out.println(c("+++-+--/-*/---++/-+*-//+/++-*--+*+/*/*/++--++-+//++--*/***-*+++--+-*//-*/+*/+-*++**+--*/*//-*--**-/-*+**-/*-**/*+*-*/--+/+/+//-+*/---///+**////-*//+-+-/+--/**///*+//+++/+*++**++//**+**+-*/+/*/*++-/+**+--+*++++/-*-/*+--/++*/-++/-**++++/-/+/--*/-/+---**//*///-//*+-*----+//--/-/+*/-+++-+*-*+*+-/-//*-//+/*-+//+/+/*-/-/+//+**/-****/-**-//+/+-+/*-+*++*/-/++*/-//*--+*--/-+-+/+/**/-***+/-/++-++*+*-+*+*-+-//+/-++*+/*//*-+/+*/-+/-/*/-/-+*+**/*//*+/+---+*+++*+/+-**/-+-/+*---/-*+/-++*//*/-+-*+--**/-////*/--/*--//-**/*++*+/*+/-+/--**/*-+*+/+-*+*+--*///+-++/+//+*/-+/**--//*/+++/*+*////+-*-//--*+/*/-+**/*//+*+-//+--+*-+/-**-*/+//*+---*+//*/+**/*--/--+/*-*+*++--*+//+*+-++--+-*-*-+--**+/+*-/+*+-/---+-*+-+-/++/+*///*/*-+-*//-+-++/++/*/-++/**--+-////-//+/*//+**/*+-+/+/+///*+*///*-/+/*/-//-*-**//-/-+--+/-*--+-++**++//*--/*++--*-/-///-+/+//--+*//-**-/*-*/+*/-*-*//--++*//-*/++//+/-++-+-*/*-+++**-/-*++++**+-+++-+-***-+//+-/**-+/*+****-*+++*/-*-/***/-/*+/*****++*+/-/-**-+-*-*-++**/*+-/*-+*++-/+/-++*-/*-****-*".toCharArray()));
  }
}

Output:

-1
-17
18773342


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:
Brain-Flak, 118 + 3 = 121 bytes

([][()()()]<>)<>({}[({})()]<>)<>({}[{}()]<>)<>(<{{}}>)<>([]){{}{(<{}>)<>({}())<>}{}([])}<>{(<{}>)<>({}[()])<>}<>({}())

Try it online!

ASCII version: take code-points as input, output \x00 for falsey or \x01 for truthy.


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

Body:
Python, <s>168</s> 167 bytes

q=lambda s,p,t:'\n'.join(''.join('%e'%(s*(1+p)**(c-(r+c-t)//2)*(1-p)**((r+c-t)//2))if(t-c<=r<=t+c)&(r%2^(c+~t%2)%2)else' '*12for c in range(t+1))for r in range(2*t+1))

Test case with anonymous function above assigned to f would be print(f(100,0.1,3)), yielding:

                                    1.331000e+02
                        1.210000e+02
            1.100000e+02            1.089000e+02
1.000000e+02            9.900000e+01
            9.000000e+01            8.910000e+01
                        8.100000e+01
                                    7.290000e+01

Extending the same to t=4 would be print(f(100,0.1,3)), yielding:

                                                1.464100e+02
                                    1.331000e+02
                        1.210000e+02            1.197900e+02
            1.100000e+02            1.089000e+02
1.000000e+02            9.900000e+01            9.801000e+01
            9.000000e+01            8.910000e+01
                        8.100000e+01            8.019000e+01
                                    7.290000e+01
                                                6.561000e+01

For the avoidance of scientific notation while keeping at least 3 significant figures we can use the following 211 byte code instead:

lambda s,p,t:'\n'.join(''.join('%12s'%(v and(10**5>v>.0001and'%f'%v or'%e'%v)or'')for v in[(t-c<=r<=t+c)&(r%2^(c+~t%2)%2)and s*(1+p)**(c-(r+c-t)//2)*(1-p)**((r+c-t)//2)for c in range(t+1)])for r in range(2*t+1))

Test case, print(f(100,0.1,3)) yields:

                                      133.100000
                          121.000000
              110.000000              108.900000
  100.000000               99.000000
               90.000000               89.100000
                           81.000000
                                       72.900000

then when numbers get too big or small, for example print(f(9876.000123,0.99,6)):

                                                                        6.133375e+05
                                                            3.082098e+05
                                                1.548793e+05             3082.098178
                                    77828.796693             1548.793054
                        39109.948087              778.287967               15.487931
            19653.240245              391.099481                7.782880
 9876.000123              196.532402                3.910995                0.077829
               98.760001                1.965324                0.039110
                            0.987600                0.019653                0.000391
                                        0.009876                0.000197
                                                9.876000e-05            1.965324e-06
                                                            9.876000e-07
                                                                        9.876000e-09


答:
Brain-Flak, 114 bytes

```<code>([((()()()){}){}]{})(((()()()){}())<>)<>{({}<(({}[(((((()()()){}()){}){}){}){}]())){(<{}>)<>({}[()])<>}{}>[()])}<>
</code>```

Try it online!

Correct version (in the spirit of the question): takes the integer as input, output 0 for falsey and 1 for truthy.

This is not stack clean.

Algorithm

Let the input be n.

The output is truthy iff (n-123)(n-234)(n-345)(n-456)(n-567)(n-678)(n-789)=0.

I computed those seven numbers by first subtracting 12 and then subtract 111 7 times, and then computed the logical double-NOT of those seven numbers and added them up.

For truthy results, the sum is 6; for falsey results, the sum is 7.

Then, I subtract the sum from 7 and output the answer.

Title: As Easy as One-Two-Three

Body:
Brain-Flak, 114 bytes

([((()()()){}){}]{})(((()()()){}())<>)<>{({}<(({}[(((((()()()){}()){}){}){}){}]())){(<{}>)<>({}[()])<>}{}>[()])}<>

Try it online!

Correct version (in the spirit of the question): takes the integer as input, output 0 for falsey and 1 for truthy.

This is not stack clean.

Algorithm

Let the input be n.

The output is truthy iff (n-123)(n-234)(n-345)(n-456)(n-567)(n-678)(n-789)=0.

I computed those seven numbers by first subtracting 12 and then subtract 111 7 times, and then computed the logical double-NOT of those seven numbers and added them up.

For truthy results, the sum is 6; for falsey results, the sum is 7.

Then, I subtract the sum from 7 and output the answer.


问:
We're no strangers to code golf, you know the rules, and so do I
Write the shortest program that prints the entire lyrics of "Never Gonna Give You Up" by Rick Astley.

Rules:

Must output the lyrics exactly as they appear in the above pastebin*. Here's the raw dump: http://pastebin.com/raw/wwvdjvEj

Cannot rely on any external resources - all lyrics must be generated by / embedded in code.

No use of existing compression algorithms (e.g. gzip / bzip2) unless you include the full algorithm in your code.

Use any language, shortest code wins.

Update, 1st June 2012:

For solutions containing non-ASCII text, the size of your solution will be counted in bytes, based on UTF-8 encoding. If you use codepoints that cannot be encoded in UTF-8, your solution will not be judged as valid.

Update, 7th June 2012:

Thank you all for your awesome solutions! I'll be accepting the shortest answer tomorrow afternoon. Right now, Peter Taylor's GolfScript answer is winning, so get cracking on some improvements if you want to beat him! :)

*There is a typo in the Pastebin (line 46, "know" should be "known").  You may either replicate it or not at your discretion.

答:
Perl, <s>584</s> <s>578</s> <s>577</s> <s>576</s> <s>575</s> <s>571</s> <s>564</s> <s>554</s> <s>553</s> 540

This solution follows the same basic approach as most of the others: given an initial string, perform repeated substitutions of repeated portions of the text.

The substitution rules are specified by a single character, preferably one not occurring in the output text, so a rule of length L and occurring N times will save approximately N*L-N-L-1 (N*L is the original length of all occurrences, but the substitution character occurs N times, and the literal text itself has length L, and the rules are split by a separating character.)  If the substitution characters are explicitly specified, then the savings is reduced to N*L-N-L-2.  Given that most languages can compute a character with chr() or similarly short code, the first approach tends to be superior.

There are some drawbacks to computing the substitution character, the most significant being the need for a continuous range of ASCII characters.  The output uses mostly lowercase letters, but there are enough uppercase letters and punctuation to require either replacing a character with itself, remapping a few characters in a fixup stage afterwards, or ordering the rules such that replacements with problematic characters occur earlier.  Using a language that replaces using regexes also means that there are gotchas for characters that have special meaning within a regex: . + * \ ?

My original approach had 63 bytes in the decoder and 521 in the rules.  I spent a lot of time optimizing the rules, which can be tricky particularly with the short rules as they can overlap.  I got the decoding down to 55 bytes and the rules down to 485 by cheating the formula a little bit.  Normally, a 2-character rule that occurs 3 times or a 3-character rule that occurs twice would not actually save any length, but there is a loophole - which also allows for making up words that aren't part of the output ;-).

I do make use of control characters in this solution, so the solution is provided here base64-encoded.

```<code>cz09AhpuCnRyYQ8QcxIHbG8OGRwVBHJ1bGVzDRRzB2QHSQFBE3VsbCBjb21taXQIbnQXcxFoYXQs
FWluaxtvZhkRC2xkbhd0BWV0FWlzE3JvbQ1ueR8FdXkuJ0EUaWYYDXNrIAgtRG9uF3QgHiAIGBp0
bwdibGkUdAoDKysBKSkoKCcuKys9OyRjPWNociQ9LS0sczpbJGNdOigiCldlZWVlICBnb3RvIG1l
b3cHc291bmQgYXZlbmdlciB3IHQgZgwgEmhpDiciPX4vLj9cRC9nLHNwbGl0CjAsJyB5CzABWQsw
F3IEMGkPIDAga24JMG5uYSAwdGVsbDAgBmgQMCAwFhggdXAwZQ5yBW8dMHQXcyBiA24gMGF5IGl0
ATABTiIwAShPb2gwAQECFw4cbiBlYWNoHxNvciBzB2xvDxlyIGhlYXIjYWNoG2J1dBkadG8KaHkS
CiRJbnNpZGURBGIGaBwRaGEjZ28bb24BAhwVBGdhCA0Ud2UaZ28dcGwkMCYpJWcWLCBuImcWAShH
ISkwJiwFISkwbWFrZRggMAElZyElbGV0GCBkCW4lcnVuDXILFGEUZGVzEHQYJSpjcnklc2F5BW9v
ZGJ5ZSUeDSBsaWUNFGh1cnQYMCBJF20wIGgJLBMDbGkPATABSSBqdXN0EWEdHhgtRwZ0YSAqdQwQ
c3RhDCsnKVskPV06ZWd3aGlsZSQ9O3ByaW50
</code>```

And here it is as a slightly more readable (but less executable) version.

```<code>s==^B^Zn
tra^O^Ps^R^Glo^N^Y^\^U^Drules^M^Ts^Gd^GI^AA^Sull commit^Hnt^Ws^Qhat,^Uink^[of^Y^Q^Kldn^Wt^Eet^Uis^Srom^Mny^_^Euy.'A^Tif^X^Msk ^H-Don^Wt ^^ ^H^X^Zto^Gbli^Tt
^C++^A))(('.++=;$c=chr$=--,s:[$c]:("
Weeee  goto meow^Gsound avenger w t f^L ^Rhi^N'"=~/.?\D/g,split
0,' y^K0^AY^K0^Wr^D0i^O 0 kn^I0nna 0tell0 ^Fh^P0 0^V^X up0e^Nr^Eo^]0t^Ws b^Cn 0ay it^A0^AN"0^A(Ooh0^A^A^B^W^N^\n each^_^Sor s^Glo^O^Yr hear#ach^[but^Y^Zto
hy^R
$Inside^Q^Db^Fh^\^Qha#go^[on^A^B^\^U^Dga^H^M^Twe^Zgo^]pl$0&)%g^V, n"g^V^A(G!)0&,^E!)0make^X 0^A%g!%let^X d^In%run^Mr^K^Ta^Tdes^Pt^X%*cry%say^Eoodbye%^^^M lie^M^Thurt^X0 I^Wm0 h^I,^S^Cli^O^A0^AI just^Qa^]^^^X-G^Fta *u^L^Psta^L+')[$=]:egwhile$=;print
</code>```

However, I suspect this still isn't the minimum, as Ed H. points out that the php decoding is the shortest at 44 bytes and I have seen room for improvement in the rules he is using.  I do have a 52-byte decoder in Perl but I was unable to use it for this solution as I needed to run through the range in reverse.

Body:
Perl, <s>584</s> <s>578</s> <s>577</s> <s>576</s> <s>575</s> <s>571</s> <s>564</s> <s>554</s> <s>553</s> 540

This solution follows the same basic approach as most of the others: given an initial string, perform repeated substitutions of repeated portions of the text.

The substitution rules are specified by a single character, preferably one not occurring in the output text, so a rule of length L and occurring N times will save approximately N*L-N-L-1 (N*L is the original length of all occurrences, but the substitution character occurs N times, and the literal text itself has length L, and the rules are split by a separating character.)  If the substitution characters are explicitly specified, then the savings is reduced to N*L-N-L-2.  Given that most languages can compute a character with chr() or similarly short code, the first approach tends to be superior.

There are some drawbacks to computing the substitution character, the most significant being the need for a continuous range of ASCII characters.  The output uses mostly lowercase letters, but there are enough uppercase letters and punctuation to require either replacing a character with itself, remapping a few characters in a fixup stage afterwards, or ordering the rules such that replacements with problematic characters occur earlier.  Using a language that replaces using regexes also means that there are gotchas for characters that have special meaning within a regex: . + * \ ?

My original approach had 63 bytes in the decoder and 521 in the rules.  I spent a lot of time optimizing the rules, which can be tricky particularly with the short rules as they can overlap.  I got the decoding down to 55 bytes and the rules down to 485 by cheating the formula a little bit.  Normally, a 2-character rule that occurs 3 times or a 3-character rule that occurs twice would not actually save any length, but there is a loophole - which also allows for making up words that aren't part of the output ;-).

I do make use of control characters in this solution, so the solution is provided here base64-encoded.

cz09AhpuCnRyYQ8QcxIHbG8OGRwVBHJ1bGVzDRRzB2QHSQFBE3VsbCBjb21taXQIbnQXcxFoYXQs
FWluaxtvZhkRC2xkbhd0BWV0FWlzE3JvbQ1ueR8FdXkuJ0EUaWYYDXNrIAgtRG9uF3QgHiAIGBp0
bwdibGkUdAoDKysBKSkoKCcuKys9OyRjPWNociQ9LS0sczpbJGNdOigiCldlZWVlICBnb3RvIG1l
b3cHc291bmQgYXZlbmdlciB3IHQgZgwgEmhpDiciPX4vLj9cRC9nLHNwbGl0CjAsJyB5CzABWQsw
F3IEMGkPIDAga24JMG5uYSAwdGVsbDAgBmgQMCAwFhggdXAwZQ5yBW8dMHQXcyBiA24gMGF5IGl0
ATABTiIwAShPb2gwAQECFw4cbiBlYWNoHxNvciBzB2xvDxlyIGhlYXIjYWNoG2J1dBkadG8KaHkS
CiRJbnNpZGURBGIGaBwRaGEjZ28bb24BAhwVBGdhCA0Ud2UaZ28dcGwkMCYpJWcWLCBuImcWAShH
ISkwJiwFISkwbWFrZRggMAElZyElbGV0GCBkCW4lcnVuDXILFGEUZGVzEHQYJSpjcnklc2F5BW9v
ZGJ5ZSUeDSBsaWUNFGh1cnQYMCBJF20wIGgJLBMDbGkPATABSSBqdXN0EWEdHhgtRwZ0YSAqdQwQ
c3RhDCsnKVskPV06ZWd3aGlsZSQ9O3ByaW50

And here it is as a slightly more readable (but less executable) version.

s==^B^Zn
tra^O^Ps^R^Glo^N^Y^\^U^Drules^M^Ts^Gd^GI^AA^Sull commit^Hnt^Ws^Qhat,^Uink^[of^Y^Q^Kldn^Wt^Eet^Uis^Srom^Mny^_^Euy.'A^Tif^X^Msk ^H-Don^Wt ^^ ^H^X^Zto^Gbli^Tt
^C++^A))(('.++=;$c=chr$=--,s:[$c]:("
Weeee  goto meow^Gsound avenger w t f^L ^Rhi^N'"=~/.?\D/g,split
0,' y^K0^AY^K0^Wr^D0i^O 0 kn^I0nna 0tell0 ^Fh^P0 0^V^X up0e^Nr^Eo^]0t^Ws b^Cn 0ay it^A0^AN"0^A(Ooh0^A^A^B^W^N^\n each^_^Sor s^Glo^O^Yr hear#ach^[but^Y^Zto
hy^R
$Inside^Q^Db^Fh^\^Qha#go^[on^A^B^\^U^Dga^H^M^Twe^Zgo^]pl$0&)%g^V, n"g^V^A(G!)0&,^E!)0make^X 0^A%g!%let^X d^In%run^Mr^K^Ta^Tdes^Pt^X%*cry%say^Eoodbye%^^^M lie^M^Thurt^X0 I^Wm0 h^I,^S^Cli^O^A0^AI just^Qa^]^^^X-G^Fta *u^L^Psta^L+')[$=]:egwhile$=;print

However, I suspect this still isn't the minimum, as Ed H. points out that the php decoding is the shortest at 44 bytes and I have seen room for improvement in the rules he is using.  I do have a 52-byte decoder in Perl but I was unable to use it for this solution as I needed to run through the range in reverse.


答:
Pyke, 9 bytes

```<code>~ut{3Qlq&
</code>```

Try it here!

```<code>~ut{      -  input in "123456789"
        & - ^ and V
    3Qlq  -  len(input) == 3
</code>```

Or 5 bytes if allowed sequence input

```<code>$1D]q
</code>```

Try it here!

```<code>$     - delta(input)
 1D]q - ^ == [1,1]
</code>```

Title: As Easy as One-Two-Three

Body:
Pyke, 9 bytes

~ut{3Qlq&

Try it here!

~ut{      -  input in "123456789"
        & - ^ and V
    3Qlq  -  len(input) == 3

Or 5 bytes if allowed sequence input

$1D]q

Try it here!

$     - delta(input)
 1D]q - ^ == [1,1]


答:
PHP, 35 bytes

```<code><?=($n=$argv[1]-99)<790&$n%111==24;
</code>```

exploiting that the modulo of a negative number is never positive in PHP

Title: As Easy as One-Two-Three

Body:
PHP, 35 bytes

<?=($n=$argv[1]-99)<790&$n%111==24;

exploiting that the modulo of a negative number is never positive in PHP