问:
Highlight the Bounding Box, Part II: Hexagonal Grid
You're given a hexagonal grid of the characters . and #, like this:

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

Your task is to fill the entire axis-aligned bounding box of the # with further #:

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

The axis-aligned bounding box is the smallest convex hexagonal shape which contains all the #. Note that in the case of the hexagonal grid, there are three axes to consider (W/E, SW/NE, NW/SE):

Here is another example to show that in some cases, one or more sides will contain only one #:

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

You can either view these as hexagons with degenerate sides, or you can draw the bounding box around them, like I have done above, in which case they are still hexagons:

Too hard? Try Part I!

Rules

You may use any two distinct non-space printable ASCII characters (0x21 to 0x7E, inclusive), in place of # and .. I'll continue referring to them as # and . for the remainder of the specification though.

Input and output may either be a single linefeed-separated string or a list of strings (one for each line), but the format has to be consistent.

You may assume that the input contains at least one # and all lines are the same length. Note that there are two different "kinds" of lines (starting with a space or a non-space) - you may not assume that the input always starts with the same type. You may assume that the bounding box always fits inside the grid you are given.

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

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

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

Test Cases

Each test case has input and output next to each other.

```<code>#    #

 . .      . .
# . #    # # #
 . .      . .

 . #      . #
. . .    . # .
 # .      # .

 # .      # .
. . .    . # .
 . #      . #

 # .      # .
# . .    # # .
 . #      # #

 . #      # #
# . .    # # #
 . #      # #

. . #    . # #
 . .      # #
# . .    # # .

# . .    # # .
 . .      # #
. . #    . # #

. . . . . . . .         . . . . . . . .
 . . # . # . . .         . . # # # . . .
. . . . . . . .         . . . # # . . .
 . . . # . . . .         . . . # . . . .

. . . . . . . .         . . . . . . . .
 . . # . . . # .         . . # # # # # .
. . . . . . . .         . . . # # # # .
 . . . # . . . .         . . . # # # . .

. . . . . . . .         . . . . . . . .
 . # . . . . . .         . # # # # . . .
. . . . . # . .         . . # # # # . .
 . . . . . . . .         . . . . . . . .

. . . . . . . .         . . . . . . . .
 . # . . . . . .         . # # # # . . .
. . . . . # . .         . . # # # # . .
 . . # . . . . .         . . # # # . . .

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

答:
TSQL, 768 bytes

I wrote a query to solve this - which I found quite difficult. It is not able to compete with all the excellent shorter answer. But wanted to post it anyway for those interested. Sorry about the length of the answer - hoping codegolf is also about different approachs.

Golfed:

```<code>DECLARE @ varchar(max)=
'
. . . . # . . .
 . # . . . # . .
. . . # . . . .
 . . . . . # . .
. . . . . . . .
'

;WITH c as(SELECT cast(0as varchar(max))a,x=0,y=1,z=0UNION ALL SELECT SUBSTRING(@,z,1),IIF(SUBSTRING(@,z,1)=CHAR(10),1,x+1),IIF(SUBSTRING(@,z,1)=CHAR(10),y+1,y),z+1FROM c WHERE LEN(@)>z)SELECT @=stuff(@,z-1,1,'#')FROM c b WHERE((exists(SELECT*FROM c WHERE b.y=y and'#'=a)or exists(SELECT*FROM c WHERE b.y<y and'#'=a)and exists(SELECT*FROM c WHERE b.y>y and'#'=a))and a='.')and(exists(SELECT*FROM c WHERE b.x<=x-ABS(y-b.y)and'#'=a)or exists(SELECT*FROM c WHERE b.x<=x+y-b.y and a='#'and b.y<y)and exists(SELECT*FROM c WHERE b.x<=x+b.y-y and a='#'and b.y>y))and(exists(SELECT*FROM c WHERE b.x>=x+ABS(y-b.y)and'#'=a)or exists(SELECT*FROM c WHERE b.x>=x-y+b.y and b.y<y and'#'=a)and exists(SELECT*FROM c WHERE b.x>=x-b.y+y and a='#'and b.y>y))OPTION(MAXRECURSION 0)PRINT @
</code>```

Ungolfed:

```<code>DECLARE @ varchar(max)=
'
. . . . # . . .
 . # . . . # . .
. . . # . . . .
 . . . . . # . .
. . . . . . . .
'
;WITH c as
(
  SELECT
    cast(0as varchar(max))a,x=0,y=1,z=0
  UNION ALL
  SELECT
    SUBSTRING(@,z,1),IIF(SUBSTRING(@,z,1)=CHAR(10),1,x+1),
    IIF(SUBSTRING(@,z,1)=CHAR(10),y+1,y),
    z+1
  FROM c
  WHERE LEN(@)>z
)
SELECT @=stuff(@,z-1,1,'#')FROM c b
WHERE((exists(SELECT*FROM c WHERE b.y=y and'#'=a)
or exists(SELECT*FROM c WHERE b.y<y and'#'=a)
and exists(SELECT*FROM c WHERE b.y>y and'#'=a)
)and a='.')
and
(exists(SELECT*FROM c WHERE b.x<=x-ABS(y-b.y)and'#'=a)
or exists(SELECT*FROM c WHERE b.x<=x+y-b.y and a='#'and b.y<y)
and exists(SELECT*FROM c WHERE b.x<=x+b.y-y and a='#'and b.y>y))
and(exists(SELECT*FROM c WHERE b.x>=x+ABS(y-b.y)and'#'=a)
or exists(SELECT*FROM c WHERE b.x>=x-y+b.y and b.y<y and'#'=a)
and exists(SELECT*FROM c WHERE b.x>=x-b.y+y and a='#'and b.y>y))
OPTION(MAXRECURSION 0)
PRINT @
</code>```

Fiddle ungolfed

Body:
TSQL, 768 bytes

I wrote a query to solve this - which I found quite difficult. It is not able to compete with all the excellent shorter answer. But wanted to post it anyway for those interested. Sorry about the length of the answer - hoping codegolf is also about different approachs.

Golfed:

DECLARE @ varchar(max)=
'
. . . . # . . .
 . # . . . # . .
. . . # . . . .
 . . . . . # . .
. . . . . . . .
'

;WITH c as(SELECT cast(0as varchar(max))a,x=0,y=1,z=0UNION ALL SELECT SUBSTRING(@,z,1),IIF(SUBSTRING(@,z,1)=CHAR(10),1,x+1),IIF(SUBSTRING(@,z,1)=CHAR(10),y+1,y),z+1FROM c WHERE LEN(@)>z)SELECT @=stuff(@,z-1,1,'#')FROM c b WHERE((exists(SELECT*FROM c WHERE b.y=y and'#'=a)or exists(SELECT*FROM c WHERE b.y<y and'#'=a)and exists(SELECT*FROM c WHERE b.y>y and'#'=a))and a='.')and(exists(SELECT*FROM c WHERE b.x<=x-ABS(y-b.y)and'#'=a)or exists(SELECT*FROM c WHERE b.x<=x+y-b.y and a='#'and b.y<y)and exists(SELECT*FROM c WHERE b.x<=x+b.y-y and a='#'and b.y>y))and(exists(SELECT*FROM c WHERE b.x>=x+ABS(y-b.y)and'#'=a)or exists(SELECT*FROM c WHERE b.x>=x-y+b.y and b.y<y and'#'=a)and exists(SELECT*FROM c WHERE b.x>=x-b.y+y and a='#'and b.y>y))OPTION(MAXRECURSION 0)PRINT @

Ungolfed:

DECLARE @ varchar(max)=
'
. . . . # . . .
 . # . . . # . .
. . . # . . . .
 . . . . . # . .
. . . . . . . .
'
;WITH c as
(
  SELECT
    cast(0as varchar(max))a,x=0,y=1,z=0
  UNION ALL
  SELECT
    SUBSTRING(@,z,1),IIF(SUBSTRING(@,z,1)=CHAR(10),1,x+1),
    IIF(SUBSTRING(@,z,1)=CHAR(10),y+1,y),
    z+1
  FROM c
  WHERE LEN(@)>z
)
SELECT @=stuff(@,z-1,1,'#')FROM c b
WHERE((exists(SELECT*FROM c WHERE b.y=y and'#'=a)
or exists(SELECT*FROM c WHERE b.y<y and'#'=a)
and exists(SELECT*FROM c WHERE b.y>y and'#'=a)
)and a='.')
and
(exists(SELECT*FROM c WHERE b.x<=x-ABS(y-b.y)and'#'=a)
or exists(SELECT*FROM c WHERE b.x<=x+y-b.y and a='#'and b.y<y)
and exists(SELECT*FROM c WHERE b.x<=x+b.y-y and a='#'and b.y>y))
and(exists(SELECT*FROM c WHERE b.x>=x+ABS(y-b.y)and'#'=a)
or exists(SELECT*FROM c WHERE b.x>=x-y+b.y and b.y<y and'#'=a)
and exists(SELECT*FROM c WHERE b.x>=x-b.y+y and a='#'and b.y>y))
OPTION(MAXRECURSION 0)
PRINT @

Fiddle ungolfed


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

答:
PowerShell v3+, 24 bytes

```<code>($args[0]-12)/111-in1..7
</code>```

Uses the same "multiple of 111 plus 12" trick as some other answers, but goes the other direction. Takes input $args[0], subtracts 12, divides by 111, and checks whether that's -in the range 1..7. Outputs a Boolean true/false value. Requires v3+ for the -in operator.

Test Cases

```<code>PS C:\Tools\Scripts\golfing> 123,234,345,456,567,678,789|%{.\easy-as-one-two-three.ps1 $_}
True
True
True
True
True
True
True

PS C:\Tools\Scripts\golfing> 1,2,3,12,122,124,132,321,457,777,890,900,1011,1230,1234|%{.\easy-as-one-two-three.ps1 $_}
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
</code>```

ContentLicense: CC BY-SA 3.0

Title: As Easy as One-Two-Three

Body:
PowerShell v3+, 24 bytes

($args[0]-12)/111-in1..7

Uses the same "multiple of 111 plus 12" trick as some other answers, but goes the other direction. Takes input $args[0], subtracts 12, divides by 111, and checks whether that's -in the range 1..7. Outputs a Boolean true/false value. Requires v3+ for the -in operator.

Test Cases

PS C:\Tools\Scripts\golfing> 123,234,345,456,567,678,789|%{.\easy-as-one-two-three.ps1 $_}
True
True
True
True
True
True
True

PS C:\Tools\Scripts\golfing> 1,2,3,12,122,124,132,321,457,777,890,900,1011,1230,1234|%{.\easy-as-one-two-three.ps1 $_}
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False


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

答:
Retina, 744 bytes

Sorry folks, no Hexagony this time...

Byte count assumes ISO 8859-1 encoding.

```<code>.+¶
$.'$*_¶$&
^_¶
¶
((^_|\2_)*)_\1{5}_+
$2_
^_*
$.&$*×_$&$&$.&$*×
M!&m`(?<=(?=×*(_)+)\A.*)(?<-1>.)+(?(1)!)|^.*$
O$`(_)|.(?=.*$)
$1
G-2`
T`d`À-É
m`\A(\D*)(?(_)\D*¶.|(.)\D*¶\2)((.)(?<=(?<4>_)\D+)?((?<=(?<1>\1.)\4\D*)|(?<=(?<1>\D*)\4(?<=\1)\D*)|(?<=\1(.(.)*¶\D*))((?<=(?<1>\D*)\4(?>(?<-7>.)*)¶.*\6)|(?<=(?<1>\D*)(?=\4)(?>(?<-7>.)+)¶.*\6))|(?<=(×)*¶.*)((?<=(?<1>\1.(?>(?<-9>¶.*)*))^\4\D*)|(?<=(?<1>\D*)\4(?>(?<-9>¶.*)*)(?<=\1)^\D*)|(?<=(?<1>\1\b.*(?(9)!)(?<-9>¶.*)*)\4×*¶\D*)|(?<=(?<1>\D*\b)\4.*(?(9)!)(?<-9>¶.*)*(?<=\1.)\b\D*))|(?<=(?<1>\1.(?>(?<-11>.)*)¶.*)\4(.)*¶\D*)|(?<=(?<1>\1(?>(?<-12>.)*)¶.*)\4(.)*¶\D*)|(?<=(?<1>\1.(?>(?<-13>.)*¶\D*))\4(\w)*\W+.+)|(?<=(?<1>.*)\4(?>(?<-14>.)*¶\D*)(?<=\1.)(\w)*\W+.+))(?<=\1(\D*).+)(?<!\1\15.*(?<-1>.)+))*\Z
</code>```

Expects the target string on the first line and the hexagon on the second line of the input. Prints 0 or 1 accordingly.

Try it online! (The first line enables a test suite, where each line is a test case, using ¦ for separation instead of a linefeed.)

The proper way to solve this challenge is with a regex of course. ;) And if it wasn't for the fact that this challenge also involves the unfolding procedure of the hexagon, this answer would actually consist of nothing but a single ~600-byte long regex.

This isn't quite optimally golfed yet, but I'm quite happy with the result (my first working version, after removing named groups and other stuff required for sanity, was around 1000 bytes). I think I could save about 10 bytes by swapping the order of the string and the hexagon but it would require a complete rewrite of the regex at the end, which I'm not feeling up to right now. There's also a 2-byte saving by omitting the G stage, but it slows down the solution considerably, so I'll wait with making that change until I'm sure I've golfed this as well as I can.

Explanation

The main part of this solution makes extensive use of balancing groups, so I recommend reading up on them, if you want to understand how this works in detail (I won't blame you if you don't...).

The first part of the solution (i.e. everything except the last two lines) is a modified version of my answer to Unfolding the Hexagony source code. It constructs the hexagon, while leaving the target string untouched (and it actually constructs the hexagon before the target string). I've made some changes to the previous code to save bytes:

The background character is × instead of a space so that it doesn't conflict with potential spaces in the input.

The no-op/wildcard character is _ instead ., so that grid cells can be reliably identified as word characters.

I don't insert any spaces or indentation after the hexagon is first constructed. That gives me a slanted hexagon, but that is actually much more convenient to work with and the adjacency rules are fairly simple.

Here is an example. For the following test case:

```<code>ja
abcdefghij
</code>```

We get:

```<code>××abc
×defg
hij__
____×
___××
ja
</code>```

Compare this with the usual layout of the hexagon:

```<code>  a b c
 d e f g
h i j _ _
 _ _ _ _
  _ _ _
</code>```

We can see that the neighbours are now all of the usual 8 Moore-neighbours, except the north-west and south-east neighbours. So we need to check horizontal, vertical and south-west/north-east adjacency (well and then there are the wrapping edges). Using this more compact layout also has the bonus that we'll be able to use those ×× at the end to determine the size of the hexagon on the fly when we need it.

After this form has been constructed, we make one more change to the entire string:

```<code>T`d`À-É
</code>```

This replaces the digits with the extended ASCII letters

```<code>ÀÁÂÃÄÅÆÇÈÉ
</code>```

Since they are replaced both in the hexagon and in the target string this won't affect whether the string is matched or not. Also, since they are letters \w and \b still identify them as hexagon cells. The benefit of doing this substitution is that we can now use \D in the upcoming regex to match any character (specifically, linefeeds as well as non-linefeed characters). We can't use the s option to accomplish that, because we'll need . to match non-linefeed characters in several places.

Now the last bit: determining whether any path matches our given string. This is done with a single monstrous regex. You might ask yourself why?!?! Well, this is fundamentally a backtracking problem: you start somewhere and attempt a path as long as it matches the string, and once it doesn't you backtrack and try a different neighbour from the last character that worked. The one thing that you get for free when working with regex is backtracking. That's literally the only thing the regex engine does. So if we just find a way to describe a valid path (which is tricky enough for this kind of problem, but definitely possible with balancing groups), then the regex engine will sort out finding that path among all possible ones for us. It would certainly be possible to implement the search manually with multiple stages (and I've done so in the past), but I doubt it would be shorter in this particular case.

One issue with implementing this with a regex is that we can't arbitrarily weave the regex engine's cursor back and forth through the string during backtracking (which we'd need since the path might go up or down). So instead, we keep track of our own "cursor" in a capturing group and update that at every step (we can move to the position of the cursor temporarily with a lookaround). This also enables us to store all past positions which we'll use to check that we haven't visited the current position before.

So let's get to it. Here is a slightly saner version of the regex, with named groups, indentation, less random order of neighbours and some comments:

```<code>\A
# Store initial cursor position in <pos>
(?<pos>\D*)
(?(_)
  # If we start on a wildcard, just skip to the first character of the target.
  \D*¶.
|
  # Otherwise, make sure that the target starts with this character.
  (?<first>.)\D*¶\k<first>
)
(?:
  # Match 0 or more subsequent characters by moving the cursor along the path.
  # First, we store the character to be matched in <next>.
  (?<next>.)
  # Now we optionally push an underscore on top (if one exists in the string).
  # Depending on whether this done or not (both of which are attempted by
  # the engine's backtracking), either the exact character, or an underscore
  # will respond to the match. So when we now use the backreference \k<next>
  # further down, it will automatically handle wildcards correctly.
  (?<=(?<next>_)\D+)?
  # This alternation now simply covers all 6 possible neighbours as well as
  # all 6 possible wrapped edges.
  # Each option needs to go into a separate lookbehind, because otherwise
  # the engine would not backtrack through all possible neighbours once it
  # has found a valid one (lookarounds are atomic).
  # In any case, if the new character is found in the given direction, <pos>
  # will have been updated with the new cursor position.
  (?:
    # Try moving east.
    (?<=(?<pos>\k<pos>.)\k<next>\D*)
  |
    # Try moving west.
    (?<=(?<pos>\D*)\k<next>(?<=\k<pos>)\D*)
  |
    # Store the horizontal position of the cursor in <x> and remember where
    # it is (because we'll need this for the next two options).
    (?<=\k<pos>(?<skip>.(?<x>.)*¶\D*))
    (?:
      # Try moving north.
      (?<=(?<pos>\D*)\k<next>(?>(?<-x>.)*)¶.*\k<skip>)
    |
      # Try moving north-east.
      (?<=(?<pos>\D*)(?=\k<next>)(?>(?<-x>.)+)¶.*\k<skip>)
    )
  |
    # Try moving south.
    (?<=(?<pos>\k<pos>.(?>(?<-x>.)*)¶.*)\k<next>(?<x>.)*¶\D*)
  |
    # Try moving south-east.
    (?<=(?<pos>\k<pos>(?>(?<-x>.)*)¶.*)\k<next>(?<x>.)*¶\D*)
  |
    # Store the number of '×' at the end in <w>, which is one less than the
    # the side-length of the hexagon. This happens to be the number of lines
    # we need to skip when wrapping around certain edges.
    (?<=(?<w>×)*¶.*)
    (?:
      # Try wrapping around the east edge.
      (?<=(?<pos>\k<pos>.(?>(?<-w>¶.*)*))^\k<next>\D*)
    |
      # Try wrapping around the west edge.
      (?<=(?<pos>\D*)\k<next>(?>(?<-w>¶.*)*)(?<=\k<pos>)^\D*)
    |
      # Try wrapping around the south-east edge.
      (?<=(?<pos>\k<pos>\b.*(?(w)!)(?<-w>¶.*)*)\k<next>×*¶\D*)
    |
      # Try wrapping around the north-west edge.
      (?<=(?<pos>\D*\b)\k<next>.*(?(w)!)(?<-w>¶.*)*(?<=\k<pos>.)\b\D*)
    )
  |
    # Try wrapping around the south edge.
    (?<=(?<pos>\k<pos>.(?>(?<-x>.)*¶\D*))\k<next>(?<x>\w)*\W+.+)
  |
    # Try wrapping around the north edge.
    (?<=(?<pos>.*)\k<next>(?>(?<-x>.)*¶\D*)(?<=\k<pos>.)(?<x>\w)*\W+.+)
  )
  # Copy the current cursor position into <current>.
  (?<=\k<pos>(?<current>\D*).+)
  # Make sure that no matter how many strings we pop from our stack of previous
  # cursor positions, none are equal to the current one (to ensure that we use
  # each cell at most once).
  (?<!\k<pos>\k<current>.*(?<-pos>.)+)
)*
# Finally make sure that we've reached the end of the string, so that we've
# successfully matched all characters in the target string.
\Z
</code>```

I hope that the general idea is roughly clear from this. As an example for how one of those movements along the path works, let's look at the bit that moves the cursor south:

```<code>(?<=(?<pos>\k<pos>.(?>(?<-x>.)*)¶.*)\k<next>(?<x>.)*¶\D*)
</code>```

Remember that lookbehinds should be read from right to left (or bottom to top), because that's the order they are executed in:

```<code>(?<=
  (?<pos>
    \k<pos>       # Check that this is the old cursor position.
    .             # Match the character directly on top of the new one.
    (?>(?<-x>.)*) # Match the same amount of characters as before.
    ¶.*           # Skip to the next line (the line, the old cursor is on).
  )               # We will store everything left of here as the new
                  # cursor position.
  \k<next>        # ...up to a match of our current target character.
  (?<x>.)*        # Count how many characters there are...
  ¶\D*            # Skip to the end of some line (this will be the line below
                  # the current cursor, which the regex engine's backtracking
                  # will determine for us).
)
</code>```

Note that it's not necessary to put an anchor in front of the \k<pos> to ensure that this actually reaches the beginning of the string. <pos> always starts with an amount of × that can't be found anywhere else, so this acts as an implicit anchor already.

I don't want to bloat this post more than necessary, so I won't go into the other 11 cases in detail, but in principle they all work similarly. We check that <next> can be found in some specific (admissible) direction from the old cursor position with the help of balancing groups, and then we store the string up to that match as the new cursor position in <pos>.

Title: HexaRegex: A Tribute to Martin Ender

Body:
Retina, 744 bytes

Sorry folks, no Hexagony this time...

Byte count assumes ISO 8859-1 encoding.

.+¶
$.'$*_¶$&
^_¶
¶
((^_|\2_)*)_\1{5}_+
$2_
^_*
$.&$*×_$&$&$.&$*×
M!&m`(?<=(?=×*(_)+)\A.*)(?<-1>.)+(?(1)!)|^.*$
O$`(_)|.(?=.*$)
$1
G-2`
T`d`À-É
m`\A(\D*)(?(_)\D*¶.|(.)\D*¶\2)((.)(?<=(?<4>_)\D+)?((?<=(?<1>\1.)\4\D*)|(?<=(?<1>\D*)\4(?<=\1)\D*)|(?<=\1(.(.)*¶\D*))((?<=(?<1>\D*)\4(?>(?<-7>.)*)¶.*\6)|(?<=(?<1>\D*)(?=\4)(?>(?<-7>.)+)¶.*\6))|(?<=(×)*¶.*)((?<=(?<1>\1.(?>(?<-9>¶.*)*))^\4\D*)|(?<=(?<1>\D*)\4(?>(?<-9>¶.*)*)(?<=\1)^\D*)|(?<=(?<1>\1\b.*(?(9)!)(?<-9>¶.*)*)\4×*¶\D*)|(?<=(?<1>\D*\b)\4.*(?(9)!)(?<-9>¶.*)*(?<=\1.)\b\D*))|(?<=(?<1>\1.(?>(?<-11>.)*)¶.*)\4(.)*¶\D*)|(?<=(?<1>\1(?>(?<-12>.)*)¶.*)\4(.)*¶\D*)|(?<=(?<1>\1.(?>(?<-13>.)*¶\D*))\4(\w)*\W+.+)|(?<=(?<1>.*)\4(?>(?<-14>.)*¶\D*)(?<=\1.)(\w)*\W+.+))(?<=\1(\D*).+)(?<!\1\15.*(?<-1>.)+))*\Z

Expects the target string on the first line and the hexagon on the second line of the input. Prints 0 or 1 accordingly.

<a href="http://retina.tryitonline.net/#code=JShTYMKmCi4rwrYKJC4nJCpfwrYkJgpeX8K2CsK2CigoXl98XDJfKSopX1wxezV9XysKJDJfCl5fKgokLiYkKsOXXyQmJCYkLiYkKsOXCk0hJm1gKD88PSg_PcOXKihfKSspXEEuKikoPzwtMT4uKSsoPygxKSEpfF4uKiQKTyRgKF8pfC4oPz0uKiQpCiQxCkctMmAKVGBkYMOALcOJCm1gXEEoXEQqKSg_KF8pXEQqwrYufCguKVxEKsK2XDIpKCguKSg_PD0oPzw0Pl8pXEQrKT8oKD88PSg_PDE-XDEuKVw0XEQqKXwoPzw9KD88MT5cRCopXDQoPzw9XDEpXEQqKXwoPzw9XDEoLiguKSrCtlxEKikpKCg_PD0oPzwxPlxEKilcNCg_Pig_PC03Pi4pKinCti4qXDYpfCg_PD0oPzwxPlxEKikoPz1cNCkoPz4oPzwtNz4uKSspwrYuKlw2KSl8KD88PSjDlykqwrYuKikoKD88PSg_PDE-XDEuKD8-KD88LTk-wrYuKikqKSleXDRcRCopfCg_PD0oPzwxPlxEKilcNCg_Pig_PC05PsK2LiopKikoPzw9XDEpXlxEKil8KD88PSg_PDE-XDFcYi4qKD8oOSkhKSg_PC05PsK2LiopKilcNMOXKsK2XEQqKXwoPzw9KD88MT5cRCpcYilcNC4qKD8oOSkhKSg_PC05PsK2LiopKig_PD1cMS4pXGJcRCopKXwoPzw9KD88MT5cMS4oPz4oPzwtMTE-LikqKcK2LiopXDQoLikqwrZcRCopfCg_PD0oPzwxPlwxKD8-KD88LTEyPi4pKinCti4qKVw0KC4pKsK2XEQqKXwoPzw9KD88MT5cMS4oPz4oPzwtMTM-LikqwrZcRCopKVw0KFx3KSpcVysuKyl8KD88PSg_PDE-LiopXDQoPz4oPzwtMTQ-LikqwrZcRCopKD88PVwxLikoXHcpKlxXKy4rKSkoPzw9XDEoXEQqKS4rKSg_PCFcMVwxNS4qKD88LTE-LikrKSkqXFo&input=YcKmYQphwqZhYgpiwqZhYgpiYcKmYWIKYWJhwqZhYgomwqZhYgojNy5KIcKmYWIKYWFhYWFhwqZhYgpiZ2puZXRhwqZhYgpjZWJ0bWFhwqZhYgpkZmFiY2fCpmFiY2RlZmcKR0NiQWVGRMKmQWJDRGVGRwphYWFiYWJiwqZhYWFhYmJiCmFsccKmYWJjZGVmZ2hpamtsbW5vcHFycwphcW5taWVkaMKmYWJjZGVmZ2hpamtsbW5vcHFycwphZGhjZ2tvcmJlZmppbW5xbHBzwqZhYmNkZWZnaGlqa2xtbm9wcXJzCjEyMzQxMzQ1MTIzMjQ1wqYxMTEyMjIzMzM0NDQ1NQpoJWHCpmFiY2RlZmdoCmEpKEAjLipiwqZhYmNkZWZnaGlqa2xtCmEpKEAjLippwqZhYmNkZWZnaGlqa2xtCmphwqZhYmNkZWZnaGlqCmtnZmVpYcKmYWJjZGVmZ2hpamtsbW5vCm1tbW1taWVhwqZhYmNkZWZnaGlqa2xtbm8KbW1tbW1sYWXCpmFiY2RlZmdoaWprbG1ubwpqYcKmYWJjZGVmZ2hpamtsbW5vCmVpamZiYWRobW5va2djc3JxbMKmYWJjZGVmZ2hpamtsbW5vcHFycwpiwqZhCiXCpmEKX8KmYQphYcKmYQphX8KmYQpfIzdKISrCpmFiCiM3Sl8hKsKmYWIKYWFhYWFhYcKmYWIKYWFhYWJhYWHCpmFiCjEyMzQ1NsKmYWIKYmZnZWRhY8KmYWJjZGVmZwpnZWNhZmRiwqZhYmNkZWZnCkdDYmFlRkTCpmFiY2RlZmcKYWFhYWFiYsKmYWFhYWJiYgphcXJjZ2bCpmFiY2RlZmdoaWprbG1ub3BxcnMKYWRobGNna25iZWlmam3CpmFiY2RlZmdoaWprbG1ub3BxcnMKamHCpmFiY2RlZmdoaWprbG1ub3BxcnMKYSkoQCMuKibCpmFiY2RlZmdoaWprbG0KYSkoQGJmZWlqa8KmYWJjZGVmZ2hpamtsbW5vCmtnZmVpY8KmYWJjZGVmZ2hpamtsbW5vCm1tbW1tbWllYcKmYWJjZGVmZ2hpamtsbW5vCmFhwqZhCmFhYcKmYQphYWFhwqZhCnJmwqZhYmNkZWZnaGlqa2xtbm9wcXJz" rel="noreferrer">Try it online! (The first line enables a test suite, where each line is a test case, using ¦ for separation instead of a linefeed.)

The proper way to solve this challenge is with a regex of course. ;) And if it wasn't for the fact that this challenge also involves the unfolding procedure of the hexagon, this answer would actually consist of nothing but a single ~600-byte long regex.

This isn't quite optimally golfed yet, but I'm quite happy with the result (my first working version, after removing named groups and other stuff required for sanity, was around 1000 bytes). I think I could save about 10 bytes by swapping the order of the string and the hexagon but it would require a complete rewrite of the regex at the end, which I'm not feeling up to right now. There's also a 2-byte saving by omitting the G stage, but it slows down the solution considerably, so I'll wait with making that change until I'm sure I've golfed this as well as I can.

Explanation

The main part of this solution makes extensive use of balancing groups, so I recommend reading up on them, if you want to understand how this works in detail (I won't blame you if you don't...).

The first part of the solution (i.e. everything except the last two lines) is a modified version of my answer to Unfolding the Hexagony source code. It constructs the hexagon, while leaving the target string untouched (and it actually constructs the hexagon before the target string). I've made some changes to the previous code to save bytes:

The background character is × instead of a space so that it doesn't conflict with potential spaces in the input.

The no-op/wildcard character is _ instead ., so that grid cells can be reliably identified as word characters.

I don't insert any spaces or indentation after the hexagon is first constructed. That gives me a slanted hexagon, but that is actually much more convenient to work with and the adjacency rules are fairly simple.

Here is an example. For the following test case:

ja
abcdefghij

We get:

××abc
×defg
hij__
____×
___××
ja

Compare this with the usual layout of the hexagon:

  a b c
 d e f g
h i j _ _
 _ _ _ _
  _ _ _

We can see that the neighbours are now all of the usual 8 Moore-neighbours, except the north-west and south-east neighbours. So we need to check horizontal, vertical and south-west/north-east adjacency (well and then there are the wrapping edges). Using this more compact layout also has the bonus that we'll be able to use those ×× at the end to determine the size of the hexagon on the fly when we need it.

After this form has been constructed, we make one more change to the entire string:

T`d`À-É

This replaces the digits with the extended ASCII letters

ÀÁÂÃÄÅÆÇÈÉ

Since they are replaced both in the hexagon and in the target string this won't affect whether the string is matched or not. Also, since they are letters \w and \b still identify them as hexagon cells. The benefit of doing this substitution is that we can now use \D in the upcoming regex to match any character (specifically, linefeeds as well as non-linefeed characters). We can't use the s option to accomplish that, because we'll need . to match non-linefeed characters in several places.

Now the last bit: determining whether any path matches our given string. This is done with a single monstrous regex. You might ask yourself why?!?! Well, this is fundamentally a backtracking problem: you start somewhere and attempt a path as long as it matches the string, and once it doesn't you backtrack and try a different neighbour from the last character that worked. The one thing that you get for free when working with regex is backtracking. That's literally the only thing the regex engine does. So if we just find a way to describe a valid path (which is tricky enough for this kind of problem, but definitely possible with balancing groups), then the regex engine will sort out finding that path among all possible ones for us. It would certainly be possible to implement the search manually with multiple stages (and I've done so in the past), but I doubt it would be shorter in this particular case.

One issue with implementing this with a regex is that we can't arbitrarily weave the regex engine's cursor back and forth through the string during backtracking (which we'd need since the path might go up or down). So instead, we keep track of our own "cursor" in a capturing group and update that at every step (we can move to the position of the cursor temporarily with a lookaround). This also enables us to store all past positions which we'll use to check that we haven't visited the current position before.

So let's get to it. Here is a slightly saner version of the regex, with named groups, indentation, less random order of neighbours and some comments:

\A
# Store initial cursor position in <pos>
(?<pos>\D*)
(?(_)
  # If we start on a wildcard, just skip to the first character of the target.
  \D*¶.
|
  # Otherwise, make sure that the target starts with this character.
  (?<first>.)\D*¶\k<first>
)
(?:
  # Match 0 or more subsequent characters by moving the cursor along the path.
  # First, we store the character to be matched in <next>.
  (?<next>.)
  # Now we optionally push an underscore on top (if one exists in the string).
  # Depending on whether this done or not (both of which are attempted by
  # the engine's backtracking), either the exact character, or an underscore
  # will respond to the match. So when we now use the backreference \k<next>
  # further down, it will automatically handle wildcards correctly.
  (?<=(?<next>_)\D+)?
  # This alternation now simply covers all 6 possible neighbours as well as
  # all 6 possible wrapped edges.
  # Each option needs to go into a separate lookbehind, because otherwise
  # the engine would not backtrack through all possible neighbours once it
  # has found a valid one (lookarounds are atomic).
  # In any case, if the new character is found in the given direction, <pos>
  # will have been updated with the new cursor position.
  (?:
    # Try moving east.
    (?<=(?<pos>\k<pos>.)\k<next>\D*)
  |
    # Try moving west.
    (?<=(?<pos>\D*)\k<next>(?<=\k<pos>)\D*)
  |
    # Store the horizontal position of the cursor in <x> and remember where
    # it is (because we'll need this for the next two options).
    (?<=\k<pos>(?<skip>.(?<x>.)*¶\D*))
    (?:
      # Try moving north.
      (?<=(?<pos>\D*)\k<next>(?>(?<-x>.)*)¶.*\k<skip>)
    |
      # Try moving north-east.
      (?<=(?<pos>\D*)(?=\k<next>)(?>(?<-x>.)+)¶.*\k<skip>)
    )
  |
    # Try moving south.
    (?<=(?<pos>\k<pos>.(?>(?<-x>.)*)¶.*)\k<next>(?<x>.)*¶\D*)
  |
    # Try moving south-east.
    (?<=(?<pos>\k<pos>(?>(?<-x>.)*)¶.*)\k<next>(?<x>.)*¶\D*)
  |
    # Store the number of '×' at the end in <w>, which is one less than the
    # the side-length of the hexagon. This happens to be the number of lines
    # we need to skip when wrapping around certain edges.
    (?<=(?<w>×)*¶.*)
    (?:
      # Try wrapping around the east edge.
      (?<=(?<pos>\k<pos>.(?>(?<-w>¶.*)*))^\k<next>\D*)
    |
      # Try wrapping around the west edge.
      (?<=(?<pos>\D*)\k<next>(?>(?<-w>¶.*)*)(?<=\k<pos>)^\D*)
    |
      # Try wrapping around the south-east edge.
      (?<=(?<pos>\k<pos>\b.*(?(w)!)(?<-w>¶.*)*)\k<next>×*¶\D*)
    |
      # Try wrapping around the north-west edge.
      (?<=(?<pos>\D*\b)\k<next>.*(?(w)!)(?<-w>¶.*)*(?<=\k<pos>.)\b\D*)
    )
  |
    # Try wrapping around the south edge.
    (?<=(?<pos>\k<pos>.(?>(?<-x>.)*¶\D*))\k<next>(?<x>\w)*\W+.+)
  |
    # Try wrapping around the north edge.
    (?<=(?<pos>.*)\k<next>(?>(?<-x>.)*¶\D*)(?<=\k<pos>.)(?<x>\w)*\W+.+)
  )
  # Copy the current cursor position into <current>.
  (?<=\k<pos>(?<current>\D*).+)
  # Make sure that no matter how many strings we pop from our stack of previous
  # cursor positions, none are equal to the current one (to ensure that we use
  # each cell at most once).
  (?<!\k<pos>\k<current>.*(?<-pos>.)+)
)*
# Finally make sure that we've reached the end of the string, so that we've
# successfully matched all characters in the target string.
\Z

I hope that the general idea is roughly clear from this. As an example for how one of those movements along the path works, let's look at the bit that moves the cursor south:

(?<=(?<pos>\k<pos>.(?>(?<-x>.)*)¶.*)\k<next>(?<x>.)*¶\D*)

Remember that lookbehinds should be read from right to left (or bottom to top), because that's the order they are executed in:

(?<=
  (?<pos>
    \k<pos>       # Check that this is the old cursor position.
    .             # Match the character directly on top of the new one.
    (?>(?<-x>.)*) # Match the same amount of characters as before.
    ¶.*           # Skip to the next line (the line, the old cursor is on).
  )               # We will store everything left of here as the new
                  # cursor position.
  \k<next>        # ...up to a match of our current target character.
  (?<x>.)*        # Count how many characters there are...
  ¶\D*            # Skip to the end of some line (this will be the line below
                  # the current cursor, which the regex engine's backtracking
                  # will determine for us).
)

Note that it's not necessary to put an anchor in front of the \k<pos> to ensure that this actually reaches the beginning of the string. <pos> always starts with an amount of × that can't be found anywhere else, so this acts as an implicit anchor already.

I don't want to bloat this post more than necessary, so I won't go into the other 11 cases in detail, but in principle they all work similarly. We check that <next> can be found in some specific (admissible) direction from the old cursor position with the help of balancing groups, and then we store the string up to that match as the new cursor position in <pos>.


问:
Highlight the Bounding Box, Part I: Cartesian Grid
You're given a rectangular grid of the characters . and #, like this:

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

Your task is to fill the entire axis-aligned bounding box of the # with further #:

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

The axis-aligned bounding box is the smallest rectangle which contains all the #.

Want more? Try Part II!

Rules

You may use any two distinct printable ASCII characters (0x20 to 0x7E, inclusive), in place of # and .. I'll continue referring to them as # and . for the remainder of the specification though.

Input and output may either be a single linefeed-separated string or a list of strings (one for each line), but the format has to be consistent.

You may assume that the input contains at least one # and all lines are the same length.

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

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

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

Test Cases

Each test case has input and output next to each other.

```<code>#    #

...    ...
#..    #..
...    ...

...    ...
#..    ###
..#    ###

.#.    ###
#..    ###
..#    ###

.....    .....
.#.#.    .###.
.....    .....

...    ...
.#.    .#.
...    .#.
.#.    .#.
...    ...

..........    ..........
..........    ..........
....#.....    ....#.....
..........    ..........

..........    ..........
..........    ..........
....#.....    ...##.....
...#......    ...##.....

..........    ..........
..#.......    ..###.....
....#.....    ..###.....
...#......    ..###.....

..........    ..........
..#.......    ..######..
....#..#..    ..######..
...#......    ..######..

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

答:
Pyth, 50 bytes

```<code>L}hbebjuXGhHX@GhHeH\#*yhMJs.e,Lkfq\#@bTUb.zySeMJ.z
</code>```

Try it online!

Body:
Pyth, 50 bytes

L}hbebjuXGhHX@GhHeH\#*yhMJs.e,Lkfq\#@bTUb.zySeMJ.z

Try it online!


问:
The Final Number

Challenge

Write a program that takes an array of 4 integers (which represents a sequence of numbers generated by a certain algorithm)  and returns the next integer that would follow.

We will only be using simple addition, subtraction, multiplication and division algorithms with a constant (i.e non-variable) variation.

For division we will use the floor integer values: 133/4 = 33 and 33/4 = 8

You can assume that there will always be one single valid return value

Test cases

[14,24,34,44] should return 54 (addition Algorithm)

[105,45,-15,-75] should return -135 (subtraction algorithm)

[5,25,125,625] should return 3125 (multiplicative algorithm)

[256,64,16,4] should return 1 (division algorithm)

General rules

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

Standard loopholes are forbidden

答:
Javascript (ES6), <s> 44 </s> <s> 42 </s> 44 bytes (fixed)

```<code>(a,b,c,d)=>a-b+d-c?d/(a<b?a/b:a/b|0)|0:d+c-b
</code>```

Saved 2 bytes, following IsmaelMiguel's advice.

Fixed version for [2,1,0,0] and [1,0,0,0] as suggested by edc65

30 bytes version

For the record, my first attempt was <s>32</s> 30 bytes but was lacking floor() support for the division. It also fails for special cases such as [2,1,0,0] and [1,0,0,0].

```<code>(a,b,c,d)=>c-2*b+a?d*c/b:d+c-b
</code>```

Demo

var f =
(a,b,c,d)=>a-b+d-c?d/(a<b?a/b:a/b|0)|0:d+c-b

var test = [
  [ 14, 24, 34, 44 ],     // should return 54 (addition Algorithm)
  [ 105, 45, -15, -75 ],  // should return -135 (subtraction algorithm)
  [ 5, 25, 125, 625 ],    // should return 3125 (multiplicative algorithm)
  [ 256, 64, 16, 4 ],     // should return 1 (division algorithm)
  [ 260, 65, 16, 4 ],     // should return 1 (division algorithm with floor())
  [ 2, 1, 0, 0 ],         // should return 0 (special case of division algorithm)
  [ 1, 0, 0, 0 ]          // should return 0 (special case of division algorithm)
];

test.forEach(l => console.log('[' + l.join`, `+ '] => ' + f(...l)));```

Title: The Final Number

Body:
Javascript (ES6), <s> 44 </s> <s> 42 </s> 44 bytes (fixed)

(a,b,c,d)=>a-b+d-c?d/(a<b?a/b:a/b|0)|0:d+c-b

Saved 2 bytes, following IsmaelMiguel's advice.

Fixed version for [2,1,0,0] and [1,0,0,0] as suggested by edc65

30 bytes version

For the record, my first attempt was <s>32</s> 30 bytes but was lacking floor() support for the division. It also fails for special cases such as [2,1,0,0] and [1,0,0,0].

(a,b,c,d)=>c-2*b+a?d*c/b:d+c-b

Demo

var f =
(a,b,c,d)=>a-b+d-c?d/(a<b?a/b:a/b|0)|0:d+c-b

var test = [
  [ 14, 24, 34, 44 ],     // should return 54 (addition Algorithm)
  [ 105, 45, -15, -75 ],  // should return -135 (subtraction algorithm)
  [ 5, 25, 125, 625 ],    // should return 3125 (multiplicative algorithm)
  [ 256, 64, 16, 4 ],     // should return 1 (division algorithm)
  [ 260, 65, 16, 4 ],     // should return 1 (division algorithm with floor())
  [ 2, 1, 0, 0 ],         // should return 0 (special case of division algorithm)
  [ 1, 0, 0, 0 ]          // should return 0 (special case of division algorithm)
];

test.forEach(l => console.log('[' + l.join`, `+ '] => ' + f(...l)));


问:
Incrementing Numbers, Over Multiple Sessions
Good Evening Golf Agents,

Your mission is on behalf of notorious entertainment giant Eviltronic Arts. As part of their nefarious plan for world enslavement and entertainment, they must sell as many copies of SimStation V as possible. This means that the software must mysteriously stop working, after starting it a few times.

Your goal is to write a program that counts the amount of times it has been run. The program must do nothing other then write the integer to stdout. The first time it is run, it should return "1". The next "2" and so on. The program must be able to at least reach the number "14", but there is no required upper limit.

However, your program must not write any new files. Accessing itself, or the registry, or even the internet is absolutely OK. But some of our users are suspicious of new files, and will merely overwrite them! The nerve! Defeating the limitations on software they legitimately purchased!

The program can not assume a stable interpreter or shell - the program must still work if the entire interpreter nay shell nay computer is restarted between running.

As it must be as undetectable as possible, the shortest source code will win.

Good luck agents. The entertainment industry is counting on you.

答:
GNU sed, 13 + 1(n flag) = 14 bytes

$=;$eecho>>s
```

<p><strong>Run:</strong> sed -nf s s</p>

<p>The assumption is that the source filename is called <code>s</code>. A trailing newline is needed after the code, which was counted in the bytes total. Explanation:</p>

<pre class="lang-sed prettyprint-override"><code>$=           # print the number of lines of the input file
$eecho>>s    # a shell echo call that appends an empty line to the source file 's'
</code>```

Body:
GNU sed, 13 + 1(n flag) = 14 bytes

$=;$eecho>>s

Run: sed -nf s s

The assumption is that the source filename is called s. A trailing newline is needed after the code, which was counted in the bytes total. Explanation:

$=           # print the number of lines of the input file
$eecho>>s    # a shell echo call that appends an empty line to the source file 's'


答:
Brachylog, <s>37</s> <s>33</s> 27 bytes

```<code>b:[E]cL,?:Iz{:+a|:*a|:/a}Lt
</code>```

Try it online! or verify all test cases.

Saved 10 bytes thanks to @LeakyNun.

Explanation

```<code>Input = [A:B:C:D]

b:[E]cL,     L = [B:C:D:E]
?:Iz         Create the list [[B:I]:[C:I]:[D:I]:[E:I]]
{            Either…
    :+a          Sum all couples of that list
|            or…
    :*a          Multiply all couples of that list
|            or…
    :/a          Integer divide all couples of that list
}L          The result is L
t           Output is the last element of L
</code>```

As LeakyNun pointed out, we don't need the subtraction case because I can be any integer.

Title: The Final Number

Body:
Challenge

Write a program that takes an array of 4 integers (which represents a sequence of numbers generated by a certain algorithm)  and returns the next integer that would follow.

We will only be using simple addition, subtraction, multiplication and division algorithms with a constant (i.e non-variable) variation.

For division we will use the floor integer values: 133/4 = 33 and 33/4 = 8

You can assume that there will always be one single valid return value

Test cases

[14,24,34,44] should return 54 (addition Algorithm)

[105,45,-15,-75] should return -135 (subtraction algorithm)

[5,25,125,625] should return 3125 (multiplicative algorithm)

[256,64,16,4] should return 1 (division algorithm)

General rules

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

Standard loopholes are forbidden

Body:
Brachylog, <s>37</s> <s>33</s> 27 bytes

b:[E]cL,?:Iz{:+a|:*a|:/a}Lt

Try it online! or verify all test cases.

Saved 10 bytes thanks to @LeakyNun.

Explanation

Input = [A:B:C:D]

b:[E]cL,     L = [B:C:D:E]
?:Iz         Create the list [[B:I]:[C:I]:[D:I]:[E:I]]
{            Either…
    :+a          Sum all couples of that list
|            or…
    :*a          Multiply all couples of that list
|            or…
    :/a          Integer divide all couples of that list
}L          The result is L
t           Output is the last element of L

As LeakyNun pointed out, we don't need the subtraction case because I can be any integer.


答:
Python 2, 40 bytes

lambda(a,b,c,d):[d+c-b,d*c/b][c-2*b+a>0]
```

<p>It's literally the JS answer ported into Python (thanks @LeakyNun!). My previous approach was ridiculously long, but here it is:</p>

<h2>Python 2, <s>169</s> 166 bytes</h2>

<p>The second and third levels are a raw tab and a raw tab plus a space, respectively, which plays <em>really</em> badly with Markdown, so the tabs have been replaced by 2 spaces.</p>

<pre class="lang-py prettyprint-override"><code>x=input()
q='%d%s%d'
for i in range(max(x)):
 for o in'+-*/':
  a=1
  for e,n in zip(x,x[1:]):
   try:1/(eval(q%(e,o,i))==n)
   except:a=0
  if a:print eval(q%(x[-1],o,i))
</code>```

Pretty simple; tries every constant and operator it thinks could be the constant, then if the constant/operator combination works for every element in the list (using a try/except pair to avoid ZeroDivisionErrors), it prints the result for the last element in the list.

I'm sure there's a better method here, this is the naive method.

Title: The Final Number

Body:
Python 2, 40 bytes

lambda(a,b,c,d):[d+c-b,d*c/b][c-2*b+a>0]

It's literally the JS answer ported into Python (thanks @LeakyNun!). My previous approach was ridiculously long, but here it is:

Python 2, <s>169</s> 166 bytes

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

x=input()
q='%d%s%d'
for i in range(max(x)):
 for o in'+-*/':
  a=1
  for e,n in zip(x,x[1:]):
   try:1/(eval(q%(e,o,i))==n)
   except:a=0
  if a:print eval(q%(x[-1],o,i))

Pretty simple; tries every constant and operator it thinks could be the constant, then if the constant/operator combination works for every element in the list (using a try/except pair to avoid ZeroDivisionErrors), it prints the result for the last element in the list.

I'm sure there's a better method here, this is the naive method.


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

答:
chopped off one character:

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

then remove the curly braces:

```<code>while(1) echo chr(2+45*rand(1,2));
</code>```

another trick, with the same length:

```<code>while(1) echo chr(rand()%2*45+47);
</code>```

OwnerDisplayName: Judy

ContentLicense: CC BY-SA 4.0

Body:
chopped off one character:

while(1) { echo chr(2 + 45 * rand(1,2)); }

then remove the curly braces:

while(1) echo chr(2+45*rand(1,2));

another trick, with the same length:

while(1) echo chr(rand()%2*45+47);

OwnerDisplayName: Karoly Horvath


答:
TSQL, 55 bytes

This script is trying adding and subtraction in the same check, then it tries to multiply, if that fails, it must be division.

```<code>DECLARE
@1 INT=6561,
@2 INT=729,
@3 INT=81,
@  INT=9

PRINT IIF(@2-@1=@-@3,@*2-@3,IIF(@1*@2=@3,@*@1,sqrt(@)))
</code>```

Fiddle

Title: The Final Number

Body:
TSQL, 55 bytes

This script is trying adding and subtraction in the same check, then it tries to multiply, if that fails, it must be division.

DECLARE
@1 INT=6561,
@2 INT=729,
@3 INT=81,
@  INT=9

PRINT IIF(@2-@1=@-@3,@*2-@3,IIF(@1*@2=@3,@*@1,sqrt(@)))

Fiddle


答:
Haskell, 65 bytes

f l@[a,b,c,d]|[a,b..d]==l=d+b-a|z<-b+0^b=div(d*b)$a-mod(max b a)z
```

Title: The Final Number


答:
GNU Octave, <s>212</s>, 196 bytes

Maybe not really a golfer's favourite choice language, but that's what makes the challenge, isn't it? Assuming m is taken as a char matrix: 178 bytes stand alone and 196 if stuffed into a function.

golfed:

```<code>function k=f(m)[a,b]=size(m);[y,x]=ndgrid(1:a,1:b);t={y,y+x,x-y};k=m;s=x>0;for j=1:3l{j}=unique(sort(vec(t{j}.*(m==['#']))))([2,end]);s&=(l{j}(1)<=t{j})&(l{j}(2)>=t{j});endk(s&mod(x+y,2))=['#']end
</code>```

ungolfed:

```<code>function k=f(m)
[a,b]=size(m);[y,x]=ndgrid(1:a,1:b);t={y,y+x,x-y};k=m;s=x>0;
for j=1:3
  l{j}=unique(sort(vec(t{j}.*(m==['#']))))([2,end]);
  s&=(l{j}(1)<=t{j})&(l{j}(2)>=t{j});
end
k(s&mod(x+y,2))=['#']
end
</code>```

Explanation : we build a coordinate system, 3 axes - orthogonal to the hexagons sides, find max and min of each coordinate, then build a logical mask starting with 1 everywhere and logically and:ing each coordinate max and min constraint, finally re-setting each remaining "true" position to "#" char.

If you want to test it, you can just create m matrix like this:

```<code>m = [' . . . . . . . .. . . . # . . .  . # . . . # . .. . . # . . . .  . . . . . # . .. . . . . . . . ']; m = reshape(m,[numel(m)/6,6])';
</code>```

and then call the f(m) and compare with m by building a matrix with both of them in:

```<code>['     before           after      ';m,ones(6,1)*'|',f(m)]
</code>```

Title: Highlight the Bounding Box, Part II: Hexagonal Grid

Body:
You're given a hexagonal grid of the characters . and #, like this:

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

Your task is to fill the entire axis-aligned bounding box of the # with further #:

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

The axis-aligned bounding box is the smallest convex hexagonal shape which contains all the #. Note that in the case of the hexagonal grid, there are three axes to consider (W/E, SW/NE, NW/SE):

Here is another example to show that in some cases, one or more sides will contain only one #:

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

You can either view these as hexagons with degenerate sides, or you can draw the bounding box around them, like I have done above, in which case they are still hexagons:

Too hard? Try Part I!

Rules

You may use any two distinct non-space printable ASCII characters (0x21 to 0x7E, inclusive), in place of # and .. I'll continue referring to them as # and . for the remainder of the specification though.

Input and output may either be a single linefeed-separated string or a list of strings (one for each line), but the format has to be consistent.

You may assume that the input contains at least one # and all lines are the same length. Note that there are two different "kinds" of lines (starting with a space or a non-space) - you may not assume that the input always starts with the same type. You may assume that the bounding box always fits inside the grid you are given.

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

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

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

Test Cases

Each test case has input and output next to each other.

```<code>#    #

 . .      . .
# . #    # # #
 . .      . .

 . #      . #
. . .    . # .
 # .      # .

 # .      # .
. . .    . # .
 . #      . #

 # .      # .
# . .    # # .
 . #      # #

 . #      # #
# . .    # # #
 . #      # #

. . #    . # #
 . .      # #
# . .    # # .

# . .    # # .
 . .      # #
. . #    . # #

. . . . . . . .         . . . . . . . .
 . . # . # . . .         . . # # # . . .
. . . . . . . .         . . . # # . . .
 . . . # . . . .         . . . # . . . .

. . . . . . . .         . . . . . . . .
 . . # . . . # .         . . # # # # # .
. . . . . . . .         . . . # # # # .
 . . . # . . . .         . . . # # # . .

. . . . . . . .         . . . . . . . .
 . # . . . . . .         . # # # # . . .
. . . . . # . .         . . # # # # . .
 . . . . . . . .         . . . . . . . .

. . . . . . . .         . . . . . . . .
 . # . . . . . .         . # # # # . . .
. . . . . # . .         . . # # # # . .
 . . # . . . . .         . . # # # . . .

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

Body:
GNU Octave, <s>212</s>, 196 bytes

Maybe not really a golfer's favourite choice language, but that's what makes the challenge, isn't it? Assuming m is taken as a char matrix: 178 bytes stand alone and 196 if stuffed into a function.

golfed:

function k=f(m)[a,b]=size(m);[y,x]=ndgrid(1:a,1:b);t={y,y+x,x-y};k=m;s=x>0;for j=1:3l{j}=unique(sort(vec(t{j}.*(m==['#']))))([2,end]);s&=(l{j}(1)<=t{j})&(l{j}(2)>=t{j});endk(s&mod(x+y,2))=['#']end

ungolfed:

function k=f(m)
[a,b]=size(m);[y,x]=ndgrid(1:a,1:b);t={y,y+x,x-y};k=m;s=x>0;
for j=1:3
  l{j}=unique(sort(vec(t{j}.*(m==['#']))))([2,end]);
  s&=(l{j}(1)<=t{j})&(l{j}(2)>=t{j});
end
k(s&mod(x+y,2))=['#']
end

Explanation : we build a coordinate system, 3 axes - orthogonal to the hexagons sides, find max and min of each coordinate, then build a logical mask starting with 1 everywhere and logically and:ing each coordinate max and min constraint, finally re-setting each remaining "true" position to "#" char.

If you want to test it, you can just create m matrix like this:

m = [' . . . . . . . .. . . . # . . .  . # . . . # . .. . . # . . . .  . . . . . # . .. . . . . . . . ']; m = reshape(m,[numel(m)/6,6])';

and then call the f(m) and compare with m by building a matrix with both of them in:

['     before           after      ';m,ones(6,1)*'|',f(m)]


答:
05AB1E, <s>18</s> <s>16</s> 18 bytes

```<code>D¥¬QPi`+s-ë`r/s\*î
</code>```

Explanation

```<code>D                   # duplicate
 ¥                  # delta's
  ¬Q                # compare first delta to the other deltas
    P               # product (1 if all deltas are equal, otherwise 0)
     i              # if 1 (we're dealing with addition or subtraction)
      `+s-          # add the difference between the elements to the last element
          ë         # else (we're dealing with multiplication or division)
           `r/      # divide the 2nd element by the 1st
              s\*   # multiply with the 4th element
                 î  # round up
</code>```

Try it online!

Title: The Final Number

Body:
05AB1E, <s>18</s> <s>16</s> 18 bytes

D¥¬QPi`+s-ë`r/s\*î

Explanation

D                   # duplicate
 ¥                  # delta's
  ¬Q                # compare first delta to the other deltas
    P               # product (1 if all deltas are equal, otherwise 0)
     i              # if 1 (we're dealing with addition or subtraction)
      `+s-          # add the difference between the elements to the last element
          ë         # else (we're dealing with multiplication or division)
           `r/      # divide the 2nd element by the 1st
              s\*   # multiply with the 4th element
                 î  # round up

Try it online!


问:
If a program terminates and there is no one to see it, does it halt?
It's time to face the truth: We will not be here forever, but at least we can write a program that will outlive the human race even if it struggles till the end of time.

Your task is to write a program that has a expected running time greater than the remaining time till the end of the universe.

You may assume that:

The universe will die from entropy in 101000 years.

Your computer:

Will outlive the universe, because it is made of Unobtainium.

Has infinite memory/stack/recursion limit.

Its processor has limited speed.

You must show that your program terminates (sorry, no infinite loops) and calculate its expected running time.

The standard loopholes apply.

This is a code golf challenge, so the shortest code satisfying the criteria wins.

EDIT:

Unfortunately, it was found (30min later) that the improbability field of Unobtainium interferes with the internal clock of the computer, rendering it useless. So time based programs halt immediately. (Who would leave a program that just waits as its living legacy, anyway?).

The computer processor is similar to the Intel i7-4578U, so one way to measure the running time is to run your program in a similar computer with a smaller input (I hope) and extrapolate its running time.

Podium

#
Chars
Language
Upvotes
Author

1
5
CJam
20
Dennis

2
5
J
5
algorithmshark

3
7
GolfScript
30
Peter Taylor

4
9
Python
39
xnor

5
10
Matlab
5
SchighSchagh

* Upvotes on 31/08

答:
R, 45 bytes

```<code>(f=function(x)if(x)f(x-1)+f(x-1)else 0)(9999)
</code>```

It's an old thread but I see no R answer, and we can't be having that!

The runtime for me was about 1s when x was 20, suggesting a runtime of 2^9979 seconds.

If you replace the zero with a one, then the output would be 2^x, but as it stands the output is zero whatever x was (avoids overflow problems).

Body:
R, 45 bytes

(f=function(x)if(x)f(x-1)+f(x-1)else 0)(9999)

It's an old thread but I see no R answer, and we can't be having that!

The runtime for me was about 1s when x was 20, suggesting a runtime of 2^9979 seconds.

If you replace the zero with a one, then the output would be 2^x, but as it stands the output is zero whatever x was (avoids overflow problems).


问:
Lucas Vs. The Garage Door Remote

Disclaimer

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

The Background

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

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

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

Part One

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

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

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

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

Part Two

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

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

So, if closed:

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

1 sec: 25% open

2 sec: 50% open

3 sec: 75% open

4 sec: 100% open, door stops

And therefore, if open:

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

1 sec: 75% open

2 sec: 50% open

3 sec: 25% open

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

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

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

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

Output

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

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

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

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

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

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

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

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

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

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

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

Best of luck!

答:
C, <s>420</s> <s>433</s> <s>424</s> 374 bytes

```<code>#define F(X,x) X=x==1?X+1:x==2?X-1:X;X=X<0?0:X>4?4:X;x=X==0?0:X==4?3:x
#define G(x) x=x==1?3:x==2?0:x==3?2:x+1
#define H(X,x) X*25,x==0||x==3?"stopped":x==1?"opening":"closing"
c,i,l,r,L,R,x[60];main(){while(i<60)printf("%d",x[i++]=random()%3);while(c<60){if(x[c]==1)G(l);else if(x[c]==2)G(r);printf("\n%d: (L:%d%% %s, R:%d%% %s)",x[c++],H(L,l),H(R,r));F(L,l);F(R,r);}}
</code>```

Doesn't seed the random generator but does use random for a better distribution.
There must be a better way to golf this logic though...

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

Older version 1:

```<code>c,i,l,r,L,R,x[60];main(){while(i<60)printf("%d",x[i++]=random()%3);while(c<60){if(x[c]==1)l=l==1?3:l==2?0:l==3?2:l+1;else if(x[c]==2)r=r==1?3:r==2?0:r==3?2:r+1;printf("\n%d: (L:%d%% %s, R:%d%% %s)",x[c++],L*25,l==0||l==3?"stopped":l==1?"opening":"closing",R*25,r==0||r==3?"stopped":r==1?"opening":"closing");L=l==1?L+1:l==2?L-1:L;R=r==1?R+1:r==2?R-1:R;L=L<0?0:L>4?4:L;R=R<0?0:R>4?4:R;l=L==0?0:L==4?3:l;r=R==0?0:R==4?3:r;}}
</code>```

Older version 2:

```<code>c,i,l,r,L,R,x[60];g(){while(i<60)printf("%d",x[i++]=random()%3);}main(){g();while(c<60){if(x[c]==1)l=l==1?3:l==2?0:l==3?2:l+1;else if(x[c]==2)r=r==1?3:r==2?0:r==3?2:r+1;printf("%d: (L:%d%% %s, R:%d%% %s)\n",x[c++],L*25,l==0||l==3?"stopped":l==1?"opening":"closing",R*25,r==0||r==3?"stopped":r==1?"opening":"closing");L=l==1?L+1:l==2?L-1:L;R=r==1?R+1:r==2?R-1:R;L=L<0?0:L>4?4:L;R=R<0?0:R>4?4:R;l=L==0?0:L==4?3:l;r=R==0?0:R==4?3:r;}}
</code>```

Title: Lucas Vs. The Garage Door Remote

Body:
C, <s>420</s> <s>433</s> <s>424</s> 374 bytes

#define F(X,x) X=x==1?X+1:x==2?X-1:X;X=X<0?0:X>4?4:X;x=X==0?0:X==4?3:x
#define G(x) x=x==1?3:x==2?0:x==3?2:x+1
#define H(X,x) X*25,x==0||x==3?"stopped":x==1?"opening":"closing"
c,i,l,r,L,R,x[60];main(){while(i<60)printf("%d",x[i++]=random()%3);while(c<60){if(x[c]==1)G(l);else if(x[c]==2)G(r);printf("\n%d: (L:%d%% %s, R:%d%% %s)",x[c++],H(L,l),H(R,r));F(L,l);F(R,r);}}

Doesn't seed the random generator but does use random for a better distribution.
There must be a better way to golf this logic though...

110121100121212100112200222111200020111100022122202112202211002
1: (L:0% opening, R:0% stopped)
1: (L:25% stopped, R:0% stopped)
0: (L:25% stopped, R:0% stopped)
1: (L:25% closing, R:0% stopped)
2: (L:0% stopped, R:0% opening)
1: (L:0% opening, R:25% opening)
1: (L:25% stopped, R:50% opening)
0: (L:25% stopped, R:75% opening)
0: (L:25% stopped, R:100% stopped)
1: (L:25% closing, R:100% stopped)
2: (L:0% stopped, R:100% closing)
1: (L:0% opening, R:75% closing)
2: (L:25% opening, R:50% stopped)
1: (L:50% stopped, R:50% stopped)
2: (L:50% stopped, R:50% opening)
1: (L:50% closing, R:75% opening)
0: (L:25% closing, R:100% stopped)
0: (L:0% stopped, R:100% stopped)
1: (L:0% opening, R:100% stopped)
1: (L:25% stopped, R:100% stopped)
2: (L:25% stopped, R:100% closing)
2: (L:25% stopped, R:75% stopped)
0: (L:25% stopped, R:75% stopped)
0: (L:25% stopped, R:75% stopped)
2: (L:25% stopped, R:75% opening)
2: (L:25% stopped, R:100% closing)
2: (L:25% stopped, R:75% stopped)
1: (L:25% closing, R:75% stopped)
1: (L:0% opening, R:75% stopped)
1: (L:25% stopped, R:75% stopped)
2: (L:25% stopped, R:75% opening)
0: (L:25% stopped, R:100% stopped)
0: (L:25% stopped, R:100% stopped)
0: (L:25% stopped, R:100% stopped)
2: (L:25% stopped, R:100% closing)
0: (L:25% stopped, R:75% closing)
1: (L:25% closing, R:50% closing)
1: (L:0% opening, R:25% closing)
1: (L:25% stopped, R:0% stopped)
1: (L:25% closing, R:0% stopped)
0: (L:0% stopped, R:0% stopped)
0: (L:0% stopped, R:0% stopped)
0: (L:0% stopped, R:0% stopped)
2: (L:0% stopped, R:0% opening)
2: (L:0% stopped, R:25% stopped)
1: (L:0% opening, R:25% stopped)
2: (L:25% opening, R:25% closing)
2: (L:50% opening, R:0% opening)
2: (L:75% opening, R:25% stopped)
0: (L:100% stopped, R:25% stopped)
2: (L:100% stopped, R:25% closing)
1: (L:100% closing, R:0% stopped)
1: (L:75% stopped, R:0% stopped)
2: (L:75% stopped, R:0% opening)
2: (L:75% stopped, R:25% stopped)
0: (L:75% stopped, R:25% stopped)
2: (L:75% stopped, R:25% closing)
2: (L:75% stopped, R:0% opening)
1: (L:75% opening, R:25% opening)
1: (L:100% closing, R:50% opening)

Older version 1:

c,i,l,r,L,R,x[60];main(){while(i<60)printf("%d",x[i++]=random()%3);while(c<60){if(x[c]==1)l=l==1?3:l==2?0:l==3?2:l+1;else if(x[c]==2)r=r==1?3:r==2?0:r==3?2:r+1;printf("\n%d: (L:%d%% %s, R:%d%% %s)",x[c++],L*25,l==0||l==3?"stopped":l==1?"opening":"closing",R*25,r==0||r==3?"stopped":r==1?"opening":"closing");L=l==1?L+1:l==2?L-1:L;R=r==1?R+1:r==2?R-1:R;L=L<0?0:L>4?4:L;R=R<0?0:R>4?4:R;l=L==0?0:L==4?3:l;r=R==0?0:R==4?3:r;}}

Older version 2:

c,i,l,r,L,R,x[60];g(){while(i<60)printf("%d",x[i++]=random()%3);}main(){g();while(c<60){if(x[c]==1)l=l==1?3:l==2?0:l==3?2:l+1;else if(x[c]==2)r=r==1?3:r==2?0:r==3?2:r+1;printf("%d: (L:%d%% %s, R:%d%% %s)\n",x[c++],L*25,l==0||l==3?"stopped":l==1?"opening":"closing",R*25,r==0||r==3?"stopped":r==1?"opening":"closing");L=l==1?L+1:l==2?L-1:L;R=r==1?R+1:r==2?R-1:R;L=L<0?0:L>4?4:L;R=R<0?0:R>4?4:R;l=L==0?0:L==4?3:l;r=R==0?0:R==4?3:r;}}


答:
C#, 63 bytes

```<code>int f(int[]x)=>2*x[1]-x[0]==x[2]?x[3]+x[1]-x[0]:x[3]*x[1]/x[0];
</code>```

Checks whether the difference between the first and second element is the same as the difference between the second and third element. If so, it does addition/subtraction, otherwise it does multiplication/division.

Title: The Final Number

Body:
C#, 63 bytes

int f(int[]x)=>2*x[1]-x[0]==x[2]?x[3]+x[1]-x[0]:x[3]*x[1]/x[0];

Checks whether the difference between the first and second element is the same as the difference between the second and third element. If so, it does addition/subtraction, otherwise it does multiplication/division.


答:
Not much better. Needs php 5.5+ for the array dereferencing feature.</p>

```<code>while(1) { echo ['/', '\\'][rand(0, 1)]; }
</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:
Not much better. Needs php 5.5+ for the array dereferencing feature.

while(1) { echo ['/', '\\'][rand(0, 1)]; }

OwnerDisplayName: rambo coder


问:
Where are Champernowne's zeroes?
Consider the infinite string of all nonnegative decimal integers concatenated together in order (akin to Champernowne's constant):

```<code>0123456789101112131415161718192021222324252627282930...979899100101102103...
</code>```

Write a program or function that takes in a nonnegative integer that indexes (0-based) into this infinite string. Output a truthy value if the digit indexed is 0, otherwise output a falsy value if the digit is 1-9.

The shortest code in bytes wins.

The first 25 truthy-producing inputs are:

```<code>0
11
31
51
71
91
111
131
151
171
191
192
194
197
200
203
206
209
212
215
218
222
252
282
312
</code>```

Kudos if your program is memory effecient, but this is not a requirement.

答:
Octave, <s>41</s> 29 bytes

Credit to Dennis, whose Julia answer made me realize I wasn't treating input 0 correctly.

```<code>@(n)sprintf('%i',0:n)(n+1)<49
</code>```

This is an anonymous function.

Try at Ideone.

Explanation

For input n, this generates the Champernowne digits corresponding to the first n+1 numbers starting at 0 (which is more than enough). sprintf is used for this so that no blank spaces appear. The result is true if the n+1-th  digit (1-based) is zero, that is, if its ASCII code is less than 49.

Title: Where are Champernowne's zeroes?

Body:
Octave, <s>41</s> 29 bytes

Credit to Dennis, whose Julia answer made me realize I wasn't treating input 0 correctly.

@(n)sprintf('%i',0:n)(n+1)<49

This is an anonymous function.

Try at Ideone.

Explanation

For input n, this generates the Champernowne digits corresponding to the first n+1 numbers starting at 0 (which is more than enough). sprintf is used for this so that no blank spaces appear. The result is true if the n+1-th  digit (1-based) is zero, that is, if its ASCII code is less than 49.


问:
This isn't rocket science
Write a program or function that takes in a single-line string. You can assume it only contains printable ASCII. Print or return a string of an ASCII art rocket such as

```<code>  |
 /_\
 |E|
 |a|
 |r|
 |t|
 |h|
 |_|
/___\
 VvV
</code>```

with the input string written from top to bottom on the fuselage. In this case the input was Earth. The height of the rocket (including flames) is always the length of the string plus five.

Each line in the output may have up to two trailing spaces and there may be a single optional trailing newline. The shortest code in bytes wins.

More Examples:

```<code>[empty string]

  |
 /_\
 |_|
/___\
 VvV

a

  |
 /_\
 |a|
 |_|
/___\
 VvV

|0

  |
 /_\
 |||
 |0|
 |_|
/___\
 VvV

\/\

  |
 /_\
 |\|
 |/|
 |\|
 |_|
/___\
 VvV

 _ _ [note trailing space]

  |
 /_\
 | |
 |_|
 | |
 |_|
 | |
 |_|
/___\
 VvV

    [4 spaces]

  |
 /_\
 | |
 | |
 | |
 | |
 |_|
/___\
 VvV

SPACEY

  |
 /_\
 |S|
 |P|
 |A|
 |C|
 |E|
 |Y|
 |_|
/___\
 VvV
</code>```

Leaderboard

var QUESTION_ID=91182,OVERRIDE_USER=26997;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Dart, <s>110</s> 106 bytes

r(var s){s=s+'_';var o='  |\n /_\\\n',i=0;while(i<s.length)o=o+' |'+s[i++]+'|\n';return o+'/___\\\n VvV';}
```

Try it out

EDIT: Saved 4 bytes, thanks!

Title: This isn't rocket science

Body:
Dart, <s>110</s> 106 bytes

r(var s){s=s+'_';var o='  |\n /_\\\n',i=0;while(i<s.length)o=o+' |'+s[i++]+'|\n';return o+'/___\\\n VvV';}

Try it out

EDIT: Saved 4 bytes, thanks!


问:
Look-and-say sequence: roman numerals edition

Challenge description

We've had a few challenges involving the Look-and-say sequence. Quick reminder:

The sequence starts with 1,

Subsequent terms of this sequence are generated by enumerating each group of repeating digits in the previous term,

So the first few terms are:

```<code>1        "one"
11       "one one" (we look at the previous term)
21       "two ones"
1211     "one two, one one"
111221   "one one, one two, two ones"
312211   "three ones, two twos, one one"
</code>```

Now let's do the same thing, but use Roman Numerals instead. We start with I and follow the same rules (we apply the digit-counting rule to characters instead, so we read IVX as one one, one five, one ten instead of one four, one ten or some other way):

```<code>I           "one"
II          "one one"
III         "two ones" = "II" + "I"
IIII        "three ones" = "III" + "I"
IVI         "four ones" = "IV" + "I"
IIIVII      "one one, one five, one one"
IIIIIVIII   "three ones, one five, two ones" = ("III" + "I") + ("I" + "V") + ("II" + "I")
</code>```

Given a positive integer N, either:

Output first N numerals of this sequence (any reasonable separator is fine, as well as ["I", "II", "III", ...]

Output Nth term of this sequence (it may be 0-indexed).

Remember to make your code as short as possible, since this is a code-golf challenge!

EDIT: I believe that there is always one standard/preferred way of expressing integers as roman numerals, (like 95 -> XCV instead of VC). Couple of Roman numeral converters I found online corroborate my opinion. If in doubt, use an online converter, as listing all the possible edge-cases and specific rules of writing Roman numerals is not the point of this challenge.

EDIT2: @PeterTaylor and @GregMartin pointed out that only numbers less or equal to 5 appear in the sequence, so you don't have to worry about the ambiguity of Roman numerals (numbers 1 - 8 are I, II, III, IV, V, VI, VII, and VIII)

答:
Python 3, 195 bytes

There's a lot of bytes wasted on the roman numerals, so there's likely some golfing to be done there.

Thanks to @El'endiaStarman, @Sherlock9 and @Shooqie

import re
def f(x,r=""):
 for v,i in(5,"V"),(4,"IV"),(1,"I"):a,x=divmod(x,v);r+=i*a
 return r
s="I"
for i in[0]*int(input()):print(s);s=re.sub(r'(.)\1*',lambda m:f(len(m.group()))+m.group()[0],s)
```

Ideone it!

Body:
Python 3, 195 bytes

There's a lot of bytes wasted on the roman numerals, so there's likely some golfing to be done there.

Thanks to @El'endiaStarman, @Sherlock9 and @Shooqie

import re
def f(x,r=""):
 for v,i in(5,"V"),(4,"IV"),(1,"I"):a,x=divmod(x,v);r+=i*a
 return r
s="I"
for i in[0]*int(input()):print(s);s=re.sub(r'(.)\1*',lambda m:f(len(m.group()))+m.group()[0],s)

Ideone it!


答:
C 61 Bytes

```<code>f(char*v){puts(v[3]==0&v[0]+1==v[1]&v[1]+1==v[2]?"T":"F");}
g(v){puts(v<790&v%111==12?"T":"F");}
main(c, v)char**v;{
    f(v[1]);
    g(atoi(v[1]));
}
</code>```

61 Bytes only includes the function. f(...)
36 Bytes using the trick from Geobits in g(...)

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:
C 61 Bytes

f(char*v){puts(v[3]==0&v[0]+1==v[1]&v[1]+1==v[2]?"T":"F");}
g(v){puts(v<790&v%111==12?"T":"F");}
main(c, v)char**v;{
    f(v[1]);
    g(atoi(v[1]));
}

61 Bytes only includes the function. f(...)
36 Bytes using the trick from Geobits in g(...)


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

答:
Python 2, 12770 + 204 + 271 = 13245

Encoder:

```<code>from itertools import*
D=[''.join(p)for p in permutations('AT TA CG GC'.split())]
e=lambda x:''.join('AT'+D[c-32]if c<56else'TA'+D[c-56]if c<80else'CG'+D[c-80]if c<104else'GC'+D[c-104]for c in map(ord,x))
</code>```

Decoder:

```<code>from itertools import*
D=[''.join(p)for p in permutations('AT TA CG GC'.split())]
n=D.index
d=lambda x:''.join(chr(n(c[2:])+32)if'AT'==c[:2]else chr(n(c[2:])+56)if'TA'==c[:2]else chr(n(c[2:])+80)if'CG'==c[:2]else chr(n(c[2:])+104)for c in map(''.join,zip(*[iter(x)]*10)))
</code>```

Every character is encoded to a 10-character (5 unit) string, with the first unit indicating what quarter of the printable character string it belongs to, and the last four indicating what character in that quarter is represented.

Try it here.

Title: DNA Encode a String

Body:
Python 2, 12770 + 204 + 271 = 13245

Encoder:

from itertools import*
D=[''.join(p)for p in permutations('AT TA CG GC'.split())]
e=lambda x:''.join('AT'+D[c-32]if c<56else'TA'+D[c-56]if c<80else'CG'+D[c-80]if c<104else'GC'+D[c-104]for c in map(ord,x))

Decoder:

from itertools import*
D=[''.join(p)for p in permutations('AT TA CG GC'.split())]
n=D.index
d=lambda x:''.join(chr(n(c[2:])+32)if'AT'==c[:2]else chr(n(c[2:])+56)if'TA'==c[:2]else chr(n(c[2:])+80)if'CG'==c[:2]else chr(n(c[2:])+104)for c in map(''.join,zip(*[iter(x)]*10)))

Every character is encoded to a 10-character (5 unit) string, with the first unit indicating what quarter of the printable character string it belongs to, and the last four indicating what character in that quarter is represented.

Try it here.


答:
GNU Octave : 74 bytes

golfed:

```<code>function r=g(a)t=conv(a-'0',[1,-1],'valid')==1;r=(sum(t)==2).*prod(t);end;
</code>```

ungolfed:

```<code>function r=golf_123(a)
  t=conv(a-'0',[1,-1],'valid')==1;
  r=(sum(t)==2).*prod(t);
endfunction
</code>```

Explanation: Treat the string as an integer vector, any two consecutive digits will then have derivative given the finite difference filter [1,-1] equal to 1 at each valid convolution output. The prod command calculates product, so it will short circuit to 0 if at least one entry is 0. The sum(t)==2 disqualifies any run of increasing digits longer or shorter than 3.

Title: As Easy as One-Two-Three

Body:
GNU Octave : 74 bytes

golfed:

function r=g(a)t=conv(a-'0',[1,-1],'valid')==1;r=(sum(t)==2).*prod(t);end;

ungolfed:

function r=golf_123(a)
  t=conv(a-'0',[1,-1],'valid')==1;
  r=(sum(t)==2).*prod(t);
endfunction

Explanation: Treat the string as an integer vector, any two consecutive digits will then have derivative given the finite difference filter [1,-1] equal to 1 at each valid convolution output. The prod command calculates product, so it will short circuit to 0 if at least one entry is 0. The sum(t)==2 disqualifies any run of increasing digits longer or shorter than 3.


答:
Rust / cargo-script, 283 bytes

Oneliner:

```<code>use std::fs::File;use std::io::Write;fn main(){let c=     0; let mut v = vec![];::std::io::Read::read_to_end(&mut File::open("w").unwrap(),&mut v);let mut q=&mut File::create("w").unwrap();q.write(&v[..53]);q.write(format!("{:6}",c+1).as_bytes());q.write(&v[59..]);println!("{}",c);}
</code>```

Save as w and run with cargo-script:

```<code>$ cargo-script script w
   Compiling w v0.1.0 (file:///home/vi/.cargo/script-cache/file-w-b4d6541706fabb11)
    (warnings skipped...)
    Finished release [optimized] target(s) in 1.47 secs
0
$ cargo-script script w
    (compilation output skipped)
1
$ cargo-script script w
...
2
$ cargo-script script w 2> /dev/null
3
$ cargo-script script w 2> /dev/null
4
$ cargo-script script w 2> /dev/null
5
$ cargo-script script w 2> /dev/null
6
$ cargo-script script w 2> /dev/null
7
$ cargo-script script w 2> /dev/null
8
$ cargo-script script w 2> /dev/null
9
$ cargo-script script w 2> /dev/null
10
$ cargo-script script w 2> /dev/null
11
</code>```

Don't iterate too fast or it'll get stuck.

Partially ungolfed:

```<code>use std::fs::File;use std::io::Write;fn main(){let c=     0;
    let mut v = vec![];
    ::std::io::Read::read_to_end(&mut File::open("w").unwrap(),&mut v);
    let mut q = &mut File::create("w").unwrap();
    q.write(&v[..53]);
    q.write(format!("{:6}",c+1).as_bytes());
    q.write(&v[59..]);
    println!("{}", c);
}
</code>```

Will break after 99999;

Title: Incrementing Numbers, Over Multiple Sessions

Body:
Good Evening Golf Agents,

Your mission is on behalf of notorious entertainment giant Eviltronic Arts. As part of their nefarious plan for world enslavement and entertainment, they must sell as many copies of SimStation V as possible. This means that the software must mysteriously stop working, after starting it a few times.

Your goal is to write a program that counts the amount of times it has been run. The program must do nothing other then write the integer to stdout. The first time it is run, it should return "1". The next "2" and so on. The program must be able to at least reach the number "14", but there is no required upper limit.

However, your program must not write any new files. Accessing itself, or the registry, or even the internet is absolutely OK. But some of our users are suspicious of new files, and will merely overwrite them! The nerve! Defeating the limitations on software they legitimately purchased!

The program can not assume a stable interpreter or shell - the program must still work if the entire interpreter nay shell nay computer is restarted between running.

As it must be as undetectable as possible, the shortest source code will win.

Good luck agents. The entertainment industry is counting on you.

Body:
Rust / cargo-script, 283 bytes

Oneliner:

use std::fs::File;use std::io::Write;fn main(){let c=     0; let mut v = vec![];::std::io::Read::read_to_end(&mut File::open("w").unwrap(),&mut v);let mut q=&mut File::create("w").unwrap();q.write(&v[..53]);q.write(format!("{:6}",c+1).as_bytes());q.write(&v[59..]);println!("{}",c);}

Save as w and run with cargo-script:

$ cargo-script script w
   Compiling w v0.1.0 (file:///home/vi/.cargo/script-cache/file-w-b4d6541706fabb11)
    (warnings skipped...)
    Finished release [optimized] target(s) in 1.47 secs
0
$ cargo-script script w
    (compilation output skipped)
1
$ cargo-script script w
...
2
$ cargo-script script w 2> /dev/null
3
$ cargo-script script w 2> /dev/null
4
$ cargo-script script w 2> /dev/null
5
$ cargo-script script w 2> /dev/null
6
$ cargo-script script w 2> /dev/null
7
$ cargo-script script w 2> /dev/null
8
$ cargo-script script w 2> /dev/null
9
$ cargo-script script w 2> /dev/null
10
$ cargo-script script w 2> /dev/null
11

Don't iterate too fast or it'll get stuck.

Partially ungolfed:

use std::fs::File;use std::io::Write;fn main(){let c=     0;
    let mut v = vec![];
    ::std::io::Read::read_to_end(&mut File::open("w").unwrap(),&mut v);
    let mut q = &mut File::create("w").unwrap();
    q.write(&v[..53]);
    q.write(format!("{:6}",c+1).as_bytes());
    q.write(&v[59..]);
    println!("{}", c);
}

Will break after 99999;