title: Input number; Output line number

text:
# Question
Title: Input number; Output line number
# Code Golf

*Totally real* backstory: I'm a contractor working on a website www.**Sky.Net** and one of our tasks it to create some self-aware program or something, I don't know I wasn't really listening to the boss. Anyways in an effort to make our code more self-aware we need *IT* to be able to know what code is on each line-number.

---

# Challenge

Create a program or function that takes an input `n` and returns the code of said program or function on line `n`.

---

# Rules

➊ Your program or function must be at least 4 lines long. Each line must be unique.

➋ You may assume the input will always be a positive integer greater than or equal to 1 and less than or equal to the number of lines in your program/function.

➌ The first line in your program/function is line 1, not line 0.

➍ You can not access the file that your program is on. (If someone has to ask "Isn't this technically breaking rule #4"; it probably is)

➎ Lines can-not be empty *(this includes a space if spaces don't do anything in your language)*

➏ Lines can-not be //comments (/\* of any \<!--style)

---

This is a -like challenge
This is , so the submission with the fewest bytes wins!

# Answer
> 16 votes
# Vim, 7 bytes

```
1
2
3
4

```

Try it online!

As far as I can tell, this complies with all of the rules. In vim by default, the empty program prints out all of the input. Since

```
<N><CR>

```

Is a noop, nothing changes the input text, and since each input matches the desired output, this same approach works with any number of lines.

# Answer
> 9 votes
# Ruby, ~~71~~ ~~70~~ 66 bytes

Try it online!

```
->n{
k=["}", "k[-n]%%k.inspect", "k=%s", "->n{"]
k[-n]%k.inspect
}

```

**"Cheating" Mode: 7+1 = 8 bytes**

Requires the `-p` flag for +1 byte. Literally a copy of the V answer. Prints the number that is inputted; the entire program is effectively just no-ops.

```
1
2
3
4

```

# Answer
> 7 votes
## Haskell, ~~69~~ 59 bytes

```
(lines(s++show
 s)
 !!)
s="\n(lines(s++show\n s)\n !!)\ns="

```

Based on the standard Haskell quine. The first expression (spread over the first three lines) is an unnamed function that picks the nth line from the quinified string `s` (`s++show s`). +2 bytes for making indexing 1-based (imho an unnecessary rule).

For a Try it online! version I have to name the function which adds 4 bytes.

# Answer
> 5 votes
# PowerShell, ~~184~~ 172 bytes

```
$v=0,
'$v=0,',
"'`$v=0',",(($q='"{0}`$v=0{0},",(($q={0}{1}{0})-f([char]39),$q)')-f([char]39),$q),
(($z='(($z={0}{1}{0})-f([char]39),$z;$v[$args]')-f([char]39),$z);$v[$args]

```

Try it online!

## Explanation

Starts by creating an array `$v` on the first line. On that same line, the first (`0`th) element is set to `0`, and a comma `,` continues its definition.

The next line sets the next element (`1`) of the array to a string representing the content of the first line of the script, so that `$v[1]` returns the first line.

The 3rd line first sets the 3rd element of the array (index `2`) to a string representing the 2nd line of the script, then on the same line sets the 4th element (index `3`) using a quine snippet that uses the format operator (`-f`) to replace certain instances of single quotes (`[char]39`) and the format template string, into itself, to reproduce the entirety of the 3rd line.

Line 4 basically does the same thing, but also ends the creation of the array and then indexes into it using the supplied argument.

# Answer
> 4 votes
# Python 2, 104 73 67 bytes

Thanks to Jonathan Allan for saving 6 bytes!

```
s=\
['print s[input()]or s', 's=\\', 0, 'exec s[', '0]']
exec s[
0]

```

**Edit:** Same byte count, but I like this solution better

Try it online!

Python version of Value Ink's Ruby answer.

Older answer (67 bytes):

```
1
s=\
['print s[-input()]or s', 0, 's=\\', 1]
print s[-input()]or s

```

# Answer
> 2 votes
## CJam, ~~19~~ ~~18~~ 17 bytes

```
1
{'_'~]ri(=}
_
~

```

Try it online!

Based on the standard CJam-quine. The `{...}_~` runs the `...` with the block itself on the stack (and in this case, also `1` below that). Then we do:

```
'_'~  e# Push the third and fourth line.
]     e# Wrap all four lines in a list.
ri    e# Read input and convert to integer.
(=    e# Use as index into the lines.

```

# Answer
> 1 votes
# PHP, 261 bytes

```
<?php function f($l){
$a="aWYoJGw9PTEpJG09Ijw/cGhwIGZ1bmN0aW9uIGYoXCRsKXsiO2lmKCRsPT0yKSRtPSJcJGE9XCIkYVwiOyI7aWYoJGw9PTMpJG09IlwkYj1cIiR";
$b="iXCI7IjtpZigkbD09NCkkbT0iZXZhbChiYXNlNjRfZGVjb2RlKFwkYS5cJGIpKTt9Pz4iO2VjaG8gJG07";
eval(base64_decode($a.$b));}?>

```

Try it online !!

The encoded string is:

```
if($l==1)$m="<?php function f(\$l){";
if($l==2)$m="\$a=\"$a\";
if($l==3)$m="\$b=\"$b\";
if($l==4)$m="eval(base64_decode(\$a.\$b));}?>";
echo $m;

```

# Answer
> 0 votes
# Perl, 52 bytes

```
$_=q{print+(split/
/,"\$_=q{$_};
eval")[<>-1]};
eval

```

This is a simple variation on the classic quine

```
$_=q{print"\$_=q{$_};eval"};eval

```

The "payload" is `split` on newlines and the correct line is selected by indexing into the resulting list.

# Perl, ~~49~~ 48 bytes (non-competing)

```
#!/usr/bin/perl -d:A
sub DB'DB{
print${"_<$0"}[<>]}
1

```

38 bytes for the code (excluding the shebang but including `-d:A`) plus 10 bytes for the filename, which must be `Devel/A.pm`. The `Devel` directory must be in `@INC`.

Technically, this violates Rule #4 because `-d:A` causes the file to be parsed twice, so it's a non-competing solution.

It uses a debugger hook to access the lines of the file, which perl stores in the `@{"_<$filename"}` array at compile time.

---
Tags: code-golf, quine
---


title: Can you barcode code in a bar?

text:
# Question
Title: Can you barcode code in a bar?
Welcome to the piNapple bar, Melbourne. All of the finest code golfers are here, with their laptops, sampling cocktails and programming increasingly badly.

I feel a special need to reemphasise the last point. Increasingly badly. Alcohol can do funny things to programming logic.

So - a few of the Golfers were attempting some nested quines in increasingly exotic languages. Somebody had hit the forth order in INTERCAL. Then the flow of alcohol stopped. He drunkedly, accidentally deleted the barcode reading algorithms from a completely different computer... that wasn't even connected to any network! (Kids - don't INTERCAL. For the sake of you. For the sake of your family.)

Normally, this wouldn't be a big issue. But, some golfer had designed the system years ago, and none of the barcodes were standard. Assuming 1's are lines, and 0's are space, they all start with 101 and finish with 1001. Everything in the middle is 7-bit ASCII encoded.

The barkeep does have a big fancy barcode reader that will return a string of arbitrary length (though less then 300 bits) of 1's and 0's, via STDIN, argument or file depending on your program. And it might come forward, or backwards depending on which way the bottle is being held. Your program must return the string from the middle of the barcode, via STOUT or file.

Unfortunately, he didn't spend as much on his storage, so the program with the shortest source will be chosen, and win free drinks and drunken programming tutorials from the other golfers.

Good luck!

# Answer
### GolfScript, 30 characters

```
.-1%]$1=3>7/);{{1&}%2base}%""+

```

Input is provided on STDIN. Example:

```
> 1011000001100001010000111001
ABC

> 1001110000101000011000001101
ABC

```
> 9 votes

# Answer
## J - 35 bytes

```
_7(a.{~#.)\_4}.3}.|.^:([:-.2{])"."0

```

Explanation coming later :).
> 1 votes

# Answer
# Pyth, 21

```
smCid2c:?zv@z2_z3_4 7

```

Explanation:

```
        ?zv@z2_z           Input if 3rd character of input is 1, else reversed input.
       :        3_4        Slice out the middle portion, ASCII of the above string.
      c             7      Chop into 7 character chunks.
 mCid2                     Convert each chunk from binary to integer, then to a character.
s                          Sum up the characters into a string and print.

```

Note that while the question is older than the language, the existence of the question did not influence the design of the language in any way, because I haven't seen the question before today.

Still rules are rules, so I'm making it CW.
> 0 votes

# Answer
## AWK, 116 bytes

```
/101$/{r=1}{L=split($0,a,"")
n=r?L-2:3
N=r?-1:1
while(d<L-7){c=0
for(k=0;k<7;k++){c*=2;c+=a[n+=N];d++}printf"%c",c}}

```

I know this question hasn't seen a lot of love, but I was curious about seeing and `AWK` solution. This isn't all that clever, but it seems to work and I don't see any obvious areas to golf. I originally reversed the string when needed, but that added more bytes than just tweaking the increment logic to move backwards.
> 0 votes

---
Tags: code-golf
---


title: Minesweeper Wars

text:
# Question
Title: Minesweeper Wars
We've had problems to generate minesweeper games.
We've had problems to solve these minesweeper games.
Now...

**It's time to battle other people on a minesweeper game!**

Your program must be run in Java. Essentially, each player can do an action every turn.

1. You may move to any space touching yours including corners. The board does not wrap around.
2. You may place a mine in the spot you currently occupy, and then to any space touching yours including corners.
3. You may place a mine on any space adjacent to yours including corners.
4. You may defuse a mine on any space adjacent to yours including corners. This turn is wasted if you defuse an empty spot. (This turn does nothing if you try to defuse a spot with someone on it, but that doesn't need to be explicitly stated because there won't be a living bot on a mine...)
5. You may do nothing.

You must make your bot in a class that extends the class `MineBot`. MineBot looks like this:

```
public abstract class MineBot {
    private int x, y;

    public abstract int changeMines(int[][] field);

    public abstract int[] proceed(int[][] field);

    public final int getX() {
        return x;
    }

    public final void setX(int x) {
        this.x = x;
    }

    public final  int getY() {
        return y;
    }

    public final void setY(int y) {
        this.y = y;
    }
}

```

(You must keep the final methods as they are for your submission to be valid)

`MineBot#changeMines(int[][])` is asked first. The result is a single `int`, representing whether or not you would like to perform an action involving a mine. This could be placing a mine, or defusing a mine. `0` means no, `1` means defuse, and `2` means place a mine. (`2` or anything not `0` or `1`)

Then, `MineBot#proceed(int[][])` is executed. The following things happen in the following ordering:

1. First, bots that are defusing mines make their move. All spots that were targeted by defusers are now safe to move onto.
2. Next, bots that are placing mines make their move. Bots may not place a bomb on a spot that was just defused.
3. Finally, all other bots move. Spaces do not have a limit on bot count, so all bots that try to move are guaranteed to move.

Then, after the configurations have been updated, all bots occupying a spot with a mine on it will be eliminated (including those who stayed put and got a mine placed under them), and it will keep iterating.

On each iteration, the number of points increases. When a bot is eliminated, the number of points on the current iteration becomes its score.

During each test run, all `n` bots will be placed on an `n+10` by `n+10` board. On each run, the score for each bot will be recorded. The total score is the sum over `n` test runs. The winner will be constantly updated, so after there are at least 3 submissions or it has passed March 14th (Pi Day), I will accept an answer, but this can change at any time!

# Input/Output Format

## Input

The array given is an `int[][]`. The rightmost four bits (`k & 15`) represent how many mines are adjacent to that square (including corners). The fifth bit from the right (`(k & 16) >> 4`) is `1` if there is a bot there and `0` if there are none. Remember, the board doesn't wrap around.

## Output

By "output" I actually mean what the functions return. Again, your bot's code will have two functions: `int changeMines(int[][])`, and `int[] proceed(int[][])`. Here's a detailed explanation for both of these:

`int changeMines(int[][])` returns a single integer representing what type of move you want to perform next. Namely, return `0` if you want to move your location or idle, `1` if you want to defuse a mine, and `2` if you want to place a mine.

`int[] proceed(int[][])` returns an array of length `1` or `2`, depending on whether or not you want to stay idle. Let's say that the return value of this method is named `int[] i`. Then, `i[0]` represents what type of move you want to make according to the list at the top of the question. `i[1]` represents which on which space you want to perform the action, where applicable. This is not checked when you remain idle because it does not apply. Follow this table:

```
1: top-left
2: top
3: top-right
4: right
5: bottom-right
6: bottom
7: bottom-left
8: left

```

(You can only act within a 3x3 square centered on yourself.)

The game code can be found at my GitHub repo here. After downloading the code, it should be a valid eclipse project (run with Eclipse Neon.2). The source code is in `/tree/master/MinesweeperKOTH/src`. Change the source code in `src/game/Game.java` so that `String[] botnames` contains the name of all of the bots. I will be updating this every so often to save you some typing. Bots go in `/src/programmed_bots`, and must extend `bot.MineBot`. Your bot must not throw any exceptions, or it will die with score 0 (no invalid arguments will be given to your bot).

# Rules

* No using reflection of any sort!
* No using `Runtime` to invoke processes on the system!
* No reading the source file of anything using your bot!
* You may read other people's programs, obviously. You may also specifically target a specific AI, but please do so in a respectful manner, also leading to my next point...
* You may not attempt to invoke an instance of another bot and run its AI
* Standard Loopholes Apply

Happy KOTH-ing!

**Note**: This question now exists on the sandbox to get more suggestions.

# Answer
> 0 votes
# TestBot

This submission is to help you determine what a valid submission might look like!

```
import bot.MineBot;

public class TestBot extends MineBot {
    public int changeMines(int[][] field) {
        return 2;
    }

    public int[] proceed(int[][] field) {
        return new int[] { 2, (int) (Math.random() * 8) };
    }
}

```

This bot just does a random-walk, placing mines as it goes. Usually backs onto its own track and commits suicide.

---
Tags: king-of-the-hill, java, minesweeper
---


# Question
Title: Build a NAND gate using multiple NAND gates
A question that had popped up in my head once - how many NAND gates would it take to build a larger, "meta-NAND" gate?

Your task is to build a black-box circuit that takes two input wires `A` and `B` and returns one output wire that satisfies `A NAND B`, subject to the following restrictions:

* You must use at least two `NAND` gates in this construction (and no gates other than `NAND`).
* You may not have null configurations of gates - that is, systems of gates that are equivalent to a gateless wire. (For example, two `NOT` gates in series are a null configuration.)
* You cannot have any stray wires (discarded values or constants).

Fewest gates wins.

# Answer
> 7 votes
# 4 gates

(A NAND B) AND-using-NAND (A NAND B)

```
A---NAND        _
 \ /    \      / \
  X      NAND-<   NAND-->
 / \    /      \_/
B---NAND

```

# Answer
> 12 votes
Three gates. Compute (((A nand A) nand B) nand B). Unlike the four-gate solution above in which three of the four gates compute A nand B, two of them simultaneously, and substituting one of the simultaneous outputs for the other would yield two consecutive inverters, the three-gate solution uses the three gates to compute different functions: "not A", "A or not B", and "A nand B". Only the last gate computes the desired function.

# Answer
> 7 votes
# 3 gates

```
   /-----------\
A-<             \
   \-----\       \
          \       NAND--
           NAND--/
B-<NAND---/

```

---
Tags: logic-gates, atomic-code-golf
---


title: Visualize the Euclidean algorithm

text:
# Question
Title: Visualize the Euclidean algorithm
The Euclidean algorithm is a widely known algorithm for calculating the greatest common divisor (GCD) of two positive integers.

# The algorithm

For the purpose of this challenge, the algorithm is described as below:

1. Display the two input as adjacent lines of a certain character
e.g. an input of `3,4` can be represented by the adjacent lines `000` and `0000`
2. Turn the first `length(short_line)` characters in the longer line into another character, say `-`
now it looks like `000` and `---0`
3. Eliminate the first `length(short_line)` characters in the longer line.
now `000`, `0`
4. Repeat step 2 and 3 until the two have equal length, using the shorter and longer lines after each iteration, e.g.
`000`,`0`
`-00`,`0`
`00`,`0`
`-0`,`0`
`0`,`0`
5. You can choose whether to stop here or continue the iteration and turn one of the lines into an empty line.

Each of these steps should be separated by an interval between 0.3s and 1.5s.

# The challenge

Write a program that, given two natural numbers as input, creates an output that looks exactly the same as the output of the algorithm above. You can use other non-whitespace printable ASCII characters than `0` and `-`, but be consistent and use only two characters. You can also use alternative algorithms provided the output, including the timing, is exactly the same as would be produced by the algorithm above.

# Examples

This is an example with input `24,35`, which are coprimes so their GCD is 1.

This is an example with input `16,42`, which have the GCD 2.

# Rules

---

**Clarifications**

* The lines that represent the numbers need to stay in their original order, i.e. the first and second lines of the first displayed "frame" need to be the first and second lines respectively, in all subsequent frames.
* After the algorithm ends, no additional *visible* entity should appear. However, this also means that it is okay to blank the lines, if you make sure that the last "frame" is displayed for at least the same amount of time as did all other frames before blanking out.

# Answer
# Jelly, 29 bytes

```
VY“ñc‘ỌœS.⁸
1ẋÇµ+M¦ṚÇt€2Çµ⁻/¿

```

Try it online!

This defines a function `2Ŀ` (not a full program; the TIO link contains a footer that converts a function into a program) that takes a list of two elements as input, and displays the output on the screen (one of our legal I/O methods, and one that is kind-of necessary for this challenge because it talks about the appearance on screen). This assumes that the program is run in a terminal that complies with the ANSI standard (I used `gnome-terminal` but most will work), and that the terminal is initially empty (which seems like the most sensible default); note that Try it online! does *not* conform to these assumptions, and thus the output is distorted there (I ran the program locally to verify that it animates as expected). I use `1` where the question uses `0`, and `2` in place of `-`.

## Explanation

**Helper function** `1Ŀ` (given a list of two lists of digits, outputs them on the first and second lines of the screen, then waits 0.5 seconds; returns its input)

```
VY“ñc‘ỌœS.⁸
V                   Convert each list of digits to an integer
 Y                  Separate these integers by newlines
  “ñc‘              {Output that; then restart with} the list [27, 99]
      Ọ             Convert codepoints to characters (i.e. "\x1bc"
       œS.          Wait (œS) 0.5 (.) seconds
          ⁸         {Output that; then return} the initial argument

```

The string "\x1bc", when sent to an ANSI-compatible terminal, is interpreted as a control code to reset the terminal; this clears the screen and moves the cursor to the top left corner (thus resetting the terminal ready for the next output).

The helper function is named `1Ŀ` (Jelly autogenerates names of this form for functions, and in fact there's no other way to name them), but it can be referred to simply as `Ç` from the main program (because the language has shorthand for functions with numbers nearby).

**Main function** `2Ŀ` (implements the task requested in the question)

```
1ẋÇµ+M¦ṚÇt€2Çµ⁻/¿
1ẋ                  Convert input to unary
  Ç                 Call helper function (producing one animation frame)
   µ         µ  ¿   While
              ⁻/      the elements differ:
     M¦               Change the largest element
    +  Ṛ                by adding corresponding elements of the other element
        Ç             Call helper function (producing one animation frame)
         t€2          Delete all 2s from each side of each element
            Ç         Call helper function (producing one animation frame)

```
> 3 votes

# Answer
## JavaScript (ES6), ~~128~~ 124 bytes

```
t=0
f=
(a,b,o,c,d)=>setInterval(e=>{e=[b,d,a,c];o.data=`-0
-0`.replace(/./g,c=>c.repeat(e.pop()));c|d?c=d=0:a>b?a-=c=b:b-=d=a},1e3)
```

```
<form><input id=a><input id=b><button onclick=clearTimeout(t),t=f(+a.value,+b.value,o.firstChild)>Go!</button><pre id=o>
```
> 6 votes

# Answer
# Python 2, ~~152~~ 146 bytes

```
import time
s,o='-0'
a,b=input()
while a*b:
 d,e=o*a,o*b
 if a>b:a=a-b;d=s*b+o*a
 elif b>a:b=b-a;e=s*a+o*b
 else:a=0
 print d+'\n'+e;time.sleep(1)

```

Try it online!

---

Takes two comma-separated integers as input
> 3 votes

# Answer
# Javascript (ES6), ~~215 194~~ ... ~~135 129~~ 127 bytes

```
a=>b=>F=(c=0)=>alert('-'[d='repeat'](e=c&a>b&&b)+'0'[d](a-=e)+`
`+'-'[d](f=c&a<b&&a)+'0'[d](b-=f))|a-b|c&&setTimeout(F,1e3,1-c)

```

# Usage

This takes input in a variation on currying. To use it, fist assign the function to a variable (for example `G`), then call it like this:

```
G(5)(6)()

```

# Explanation

Somewhat recursive function that calls itself after 1 second as long as the algorithm hasn't finished. It keeps track of a third variable `c` that determines whether `a` and `b` should be changed (if `c` is `1`, it's time for change).

First, the function writes something to the console. If `c` is `0`, it writes two strings of zeroes with a newline inbetween. Since `c` is initialised to `0`, we can take advantage of this, and set up global variables `f` and `g` that hold some strings we need often (like `0` and `repeat`).

Otherwise, it builds up a string with zeroes and minuses. All such strings consist of two parts: first some (call this amount `A`) minuses, then some (call this amount `B`) zeroes, then a newline, then some (call this amount `D`) minuses and lastly some (call this amount `E`) zeroes.

If the first input is smaller than the second input, we need to remove zeroes from the second input, so `A` is zero, `B` equals the first input, `D` equals the first input and `E` equals the second input minus the first input. If the first input is not smaller than the second input, the reverse applies (`A` is the second input, `B` is the first input minus the second input etc.).

With these new values for the input and a switched variable `c`, the function is scheduled to be called again in `1e3` milliseconds, which equals one second.

# Notes

* Uses `alert` for output
* Uses `0` and `-`, just like in the examples
* Delay between steps is 1000 ms (1 second)
* After the first step, the function will (due to the nature of JavaScript) return some number which is to be ignored
* The version on TIO outputs everything at once, pasting the code in the browser console will properly take the delays into account

# Try it online

Try it here!
> 2 votes

# Answer
# Python 2, ~~208~~ ~~204~~ 194 bytes

-4 with thanks to @math\_junkie for the sneaky trick with `time.sleep`

-10 with thanks to @busukxuan for clarifying the "clear screen" rule.

```
def z(a,b,y='-',w=1):
 import time;c,d,n,s='0'*a,'0'*b,'\n',time.sleep
 if w:print c+n+d;s(1)
 if b>a:d=y*a+d[a:]
 else:c=y*b+c[b:]
 print c+n+d;s(1)
 if c!=d:z(len(c),len(d),('','-')[y!='-'],0)

```

Try it online!

Pretty sure this could be more golfed. It pains me to duplicate the `print` and the `for` loop to create the pause but I can't find a way round it at the moment.

**Notes**

* The pause now uses a hint from @math\_junkie
* Doesn't fully work on TIO as it stores the output and dumps it out when the program finishes. Works fine in the console though.
> 2 votes

# Answer
# perl, ~~161~~ 149 bytes

...without indentations and newlines:

```
($a,$b)=map 0 x$_,@ARGV;
sub p{say"\n$a\n$b";sleep 1}p;
while($a ne$b){
  ($A,$B)=$b lt$a?(\$a,\$b):(\$b,\$a);
  map$$A=~s/0/-/,1..length$$B;
  p;
  $$A=~s/-//g;
  p
}

```

Put it into a file gcd.pl and run like this:

```
perl -M5.010 gcd.pl 16 42

```
> 1 votes

# Answer
# GNU Sed (with `e`xec extension), 88

Score includes +3 for `-zrf` options to `sed`.

```
p
:
x
esleep 1
g
ta
:a
s/o+//p
t
s/^((O+)(O+)\n\2\b|(O+)\n\4\B)/\L\2\U\3\4\n\2\L\4\U/p
t

```

Input is given as two newline separated unary integers, using the upper case `O` as digits.

For example, the 16, 42 example may be run as:

```
printf "%0*d\n%0*d\n" 16 0 42 0 | tr 0 O | sed -znrf euclidvis.sed

```

As per the latest comments, I am not clearing the screen between iterations.
> 1 votes

# Answer
# , ~~47~~ 44 bytes

```
Àé0á
Àé0Hqwmmjlhmmkl@wqòHî@w
gs`mlhv0r-gsÓ-ò

```

Try it online!

The header and footer on TIO just modify `gs` to copy the current two lines to the bottom of the screen, and then delete the first two at the end. This visualizes the operation for TIO, but if you ran it in V (without the header and footer), it would just wait a second between each operation.

```
Àé0                     " Print (Arg1) zeroes
   á                    " Newline
Àé0                     " Print (Arg2) zeroes
   H                    " Go home
    qwmmjlhmmkl@wq      " Store a recursive macro in w that finds the shorter line
                  ò     " recursively
                   Hî@w " find the longest line
gs                      " wait a second
  `mlhv0r-              " replace the zeroes of the long line with -
          gs            " wait a second
            Ó-          " delete all -
              ò         " end recursion

```
> 0 votes

---
Tags: code-golf, math, ascii-art, number, animation
---


title: Write self-validating code

text:
# Question
Title: Write self-validating code
Write code that takes a string as input, and outputs a truthy or falsey value depending on whether or not the string follows these rules:

If you stack each character on top of each other, convert to binary and sums each column, then all the sums should be identical. You may assume the input string contains only printable ASCII-characters (code points 32 - 126).

As an example:

The input `O5vy_+~` should return a truthy value, since its binary representation is:

```
1001111  | O
0110101  | 5
1110110  | v
1111001  | y
1011111  | _
0101011  | +
1111110  | ~
-------
5555555  <- Sum of bits in each column. Should give a truthy value.

```

The input `PPCG` should return a falsey value, since its binary representation is:

```
1010000  | P
1010000  | P
1000011  | C
1000111  | G
-------
4020122  <- Should give a falsey value

```

---

The twist is: **Your code should return a truthy value if it's used as input to your function / program.** I.e. the code must adhere to the same rules as above (your code can contain characters that are not ASCII 32-126).

Your program/function only needs to handle printable ASCII as input. If your code contains something else, 8 bit, 16 bit encoding, Unicode, a custom made character set (or something else), then the binary representation of it should adhere to the same rules, but your code doesn't need to handle it as input.

This is , so standard rules apply.

# Answer
## JavaScript (ES6), ~~123~~ ~~122~~ ~~120~~ 110 bytes

```
S=>[...S].map(S=>R.map((_GSSSSSSVWWW,V)=>R[V]-=S.charCodeAt()>>V&1),R=[_=3^3,_,_,_,_,_,_])&&!R.some(S=>S^R[_])

```

Below is a hexdump with bit sums.

```
Addr. | Dump                                            | #6 #5 #4 #3 #2 #1 #0
------+-------------------------------------------------+---------------------
00-0F | 53 3D 3E 5B 2E 2E 2E 53 5D 2E 6D 61 70 28 53 3D |  8 11  9 11  9  9  9
10-1F | 3E 52 2E 6D 61 70 28 28 5F 47 53 53 53 53 53 53 | 20 18 19 17 14 20 19
20-2F | 56 57 57 57 2C 56 29 3D 3E 52 5B 56 5D 2D 3D 53 | 30 24 32 25 26 30 29
30-3F | 2E 63 68 61 72 43 6F 64 65 41 74 28 29 3E 3E 56 | 41 37 37 32 34 38 36
40-4F | 26 31 29 2C 52 3D 5B 5F 3D 33 5E 33 2C 5F 2C 5F | 47 47 48 43 44 47 46
50-5F | 2C 5F 2C 5F 2C 5F 2C 5F 5D 29 26 26 21 52 2E 73 | 54 57 55 54 56 56 54
60-6D | 6F 6D 65 28 53 3D 3E 53 5E 52 5B 5F 5D 29       | 64 64 64 64 64 64 64

```

### Demo

```
let f =

S=>[...S].map(S=>R.map((_GSSSSSSVWWW,V)=>R[V]-=S.charCodeAt()>>V&1),R=[_=3^3,_,_,_,_,_,_])&&!R.some(S=>S^R[_])

console.log(f("O5vy_+~"))
console.log(f("Hello World!"))
console.log(f(`S=>[...S].map(S=>R.map((_GSSSSSSVWWW,V)=>R[V]-=S.charCodeAt()>>V&1),R=[_=3^3,_,_,_,_,_,_])&&!R.some(S=>S^R[_])`))
```
> 10 votes

# Answer
# MATL, ~~10~~ 9 bytes

```
BXs&=?I&]

```

Input is a string enclosed with single quotes (if the input contains single qoutes, escape them by duplicating).

Output is `3` as truthy and nothing (empty output) as falsy.

Try it online!

The code in binary is as follows:

```
B     1 0 0 0 0 1 0
X     1 0 1 1 0 0 0
s     1 1 1 0 0 1 1
&     0 1 0 0 1 1 0
=     0 1 1 1 1 0 1
?     0 1 1 1 1 1 1
I     1 0 0 1 0 0 1
&     0 1 0 0 1 1 0
]     1 0 1 1 1 0 1

Sum   5 5 5 5 5 5 5

```

### Explanation

```
B      % Input string (implicit). Convert each char to its ASCII code, and
       % then to binary. This gives a binary matrix, with each char of the
       % input corresponding to a row
Xs     % Sum of each column. Gives a row vector
&=     % All pairwise equality comparisons
?      % If all are true
  I    %    Push 3
  &    %    Specify that the next function, namely implicit display, will
       %    take one input, instead of the whole stack which is the default
]      % End
       % Display (implicit)

```
> 10 votes

# Answer
# Jelly, ~~11~~ 10 bytes

```
OBUSE&889.

```

**Try It Online!** Or see tests and self-input (the code is all printable ASCII, which have the same values in Jelly's code page, as seen below).

```
Char -> Hex -> Decimal -> Binary
O       0x4F   79         0b1001111
B       0x42   66         0b1000010
U       0x55   85         0b1010101
S       0x53   83         0b1010011
E       0x45   69         0b1000101
&       0x26   38         0b0100110
8       0x38   56         0b0111000
8       0x38   56         0b0111000
9       0x39   57         0b0111001
.       0x2E   46         0b0101110
                            -------
                            5555555

```

### How?

```
OBUSE&889. - Main link: string
O          - cast to ordinals
 B         - convert to binary
  U        - upend (reverses each to prepare for vectorised sum)
   S       - sum (vectorises)
    E      - all equal? (yields 1 if all bit-sums are equal and 0 if not)
      889. - 889.0
     &     - bitwise and (1 & 889.0 is 1; and 0 & 889.0 is 0)

```
> 8 votes

# Answer
# Jelly, ~~11~~ 10 bytes

```
OBUSE$*8?8

```

Uses no no-ops or comments.

Try it online!

### Binary breakdown

```
O  1 0 0 1 1 1 1
B  1 0 0 0 0 1 0
U  1 0 1 0 1 0 1
S  1 0 1 0 0 1 1
E  1 0 0 0 1 0 1
$  0 1 0 0 1 0 0
*  0 1 0 1 0 1 0
8  0 1 1 1 0 0 0
?  0 1 1 1 1 1 1
8  0 1 1 1 0 0 0
————————————————
∑  5 5 5 5 5 5 5

```

### How it works

```
OBUSE$*8?8  Main link. Argument: s (string)

O           Ordinal; map all characters in s to their code points.
 B          Binary; convert each code point to base 2.
  U         Upend; reverse each binary array to right-align the digits.
       8?   If 8 is non-zero (it is):
   SE$          Sum the corresponding digits and test the the sums for equality.
            Else (never happens):
      *  8      Raise all binary digits to the eighth power.

```
> 6 votes

# Answer
# Mathematica, 88 bytes

```
Total@IntegerDigits[ToCharacterCode@#,2,7]~MatchQ~{"?";a_ ..}&

```

Contains many unprintable characters between the quotes. Has 49 of each bit.

Here's the hexdump:

```
0000-0010:  54 6f 74 61-6c 40 49 6e-74 65 67 65-72 44 69 67  Total@In tegerDig
0000-0020:  69 74 73 5b-54 6f 43 68-61 72 61 63-74 65 72 43  its[ToCh aracterC
0000-0030:  6f 64 65 40-23 2c 32 2c-37 5d 7e 4d-61 74 63 68  ode@#,2, 7]~Match
0000-0040:  51 7e 7b 22-3f 1f 1f 1f-1f 1f 1f 1f-1f 1f 1f 1f  Q~{"?... ........
0000-0050:  1f 1f 1f 1f-1f 1a 1a 1a-1a 18 18 18-18 18 10 22  ........ ......."
0000-0058:  3b 61 5f 20-2e 2e 7d 26                          ;a_...}&

```
> 4 votes

# Answer
# Octave, ~~53~~ 52 bytes

Making a complete rewrite helped me golf the code 5 bytes, but I had to add more no-ops, making it a net-save of only 1 byte.

```
@(_)~diff(sum(de2bi(+_)))%RRPPPVVVW?????????________

```

I can't add a TIO-link, since none of the online interpreters have implemented the communication toolbox necessary for `de2bi`. Changing it to `dec2bin` instead would cost 4 bytes (2 for working code, and two no-ops).

I found no way to avoid any of the 27 no-ops. All function names and parentheses are between either below 64, or higher than 96, meaning all "necessary" characters have a 1 in the 6th position (from the right, 2^5). I had a solution with only 23 no-ops, but the code itself was longer. The actual code is 25 bytes, and has the following column sum when counting the bits of the binary equivalent:

```
15   22    6   15   10    9   13

```

There are 22 bits in the 6th position from the right (2^5), and only 6 bits in the 4th position from the right (2^3). That means, we have to add *at least* 16 bytes, to get the 6 up to 22. Now, the comment character `%` adds a bit to the 6th position, increasing it to 23. All printable ASCII-characters needs at least one of the two top bits to be `1`. Therefore, adding 17 bytes will give us at least 27 bits in each of the two "top spots" (2^6 and 2^5). Now, we have 27 bits in the top two spots, and 22 in the rest. In order to get to an equilibrium, we have to add 10 bytes, to get to an even 32 bits in each position.

**An explanation of the new code (52 bytes):**

```
@(_)~diff(sum(de2bi(+_)))
@(_)      % An anonymous function that take a variable _ as input
          % We use underscore, instead of a character, since it has the
          % most suitable binary represetation
              de2bi(+_)    % Convert the input string to a binary matrix
          sum(de2bi(+_))   % Take the sum of each column
     diff(sum(de2bi(+_)))  % And calculate the difference between each sum
    ~diff(sum(de2bi(+_)))  % Negate the result, meaning 0 becomes true,
                           % and everything else becomes false

```

A vector containing only 1s (true) is evaluated to true in Octave, and a vector containing at least one zero is evaluated to false in Octave.

**An explanation of the old code (53 bytes):**

```
@(_)!((_=sum(de2bi(+_)))-_(1))%RRRFVVVVVVVVV_____????

@(_)      % An anonymous function that take a variable _ as input
          % We use underscore, instead of a character, since it has the
          % most suitable binary represetation
    !     % Negate the result, meaning 0 becomes true, and everything else becomes false
        de2bi(+_)         % Convert the input string to a binary matrix
    sum(de2bi(+_))        % Take the sum of each column
 (_=sum(de2bi(+_)))       % Assign the result to a new variable, also called _
                          % It's not a problem that we use the same variable name, due
                          % to the order of evaluation
((_=sum(de2bi(+_)))-_(1)) % Subtract the first element of the new variable _
                          % If all elements of the new variable _ are identical, then this
                          % should give us a vector containing only zeros,
                          % otherwise, at least one element should be non-zero
!((_=sum(de2bi(+_)))-_(1))  % And finally, we negate this.

```

A vector containing only 1s (true) is evaluated to true in Octave, and a vector containing *at least* one zero is evaluated to false in Octave.
> 4 votes

# Answer
## JavaScript (ES6), ~~139~~ ~~111~~ 107 bytes

```
f=
S=>![...""+1E6].some((____________ABQWWWWWWWWW,P)=>P*=R^(R^=R,[...S].map(Q=>R+=Q.charCodeAt()>>P&1),R),R=0)
```

```
<textarea oninput=o.textContent=f(this.value) style=width:100% rows=10>S=>![...""+1E6].some((____________ABQWWWWWWWWW,P)=>P*=R^(R^=R,[...S].map(Q=>R+=Q.charCodeAt()>>P&1),R),R=0)</textarea><div id=o>true
```

Contains ~~81~~ ~~63~~ 61 of each bit.
> 3 votes

# Answer
# Scala, 149 bytes

```
_.map(C=>("0"*7++(BigInt(C)toString 2))takeRight 7 map(_-48)).transpose.map(_.sum).toSet.size==1//______________________________

```

### Usage:

```
val f:(String=>Any)=_.map(C=>("0"*7++(BigInt(C)toString 2))takeRight 7 map(_-48)).transpose.map(_.sum).toSet.size==1//______________________________
println(f("string here")

```

### Hexdump:

```
00000000  5f 2e 6d 61 70 28 43 3d  3e 28 22 30 22 2a 37 2b  |_.map(C=>("0"*7+|
00000010  2b 28 42 69 67 49 6e 74  28 43 29 74 6f 53 74 72  |+(BigInt(C)toStr|
00000020  69 6e 67 20 32 29 29 74  61 6b 65 52 69 67 68 74  |ing 2))takeRight|
00000030  20 37 20 6d 61 70 28 5f  2d 34 38 29 29 2e 74 72  | 7 map(_-48)).tr|
00000040  61 6e 73 70 6f 73 65 2e  6d 61 70 28 5f 2e 73 75  |anspose.map(_.su|
00000050  6d 29 2e 74 6f 53 65 74  2e 73 69 7a 65 3d 3d 31  |m).toSet.size==1|
00000060  2f 2f 5f 5f 5f 5f 5f 5f  5f 5f 5f 5f 5f 5f 5f 5f  |//______________|
00000070  5f 5f 5f 5f 5f 5f 5f 5f  5f 5f 5f 5f 5f 5f 5f 5f  |________________|
00000080  1f 1f 1f 1f 1e 1e 1e 1e  16 16 16 16 16 12 12 10  |................|
00000090  10 10 10 10 10                                    |.....|

```

### Ungolfed:

```
string =>
  string.map(char =>
    (
      "0" * 7 ++ BigInt(char).toString(2)
    ).takeRight(7).map(n=>n-48)
  ).transpose
  .map(bits=>bits.sum)
  .toSet
  .size == 1
  //______________________________

```

### Explanation:

```
string =>                      //create an anonymous function with a parameter string
  string.map(char =>           //map each char in the string to
    (
      "0" * 7                  //a string of 7 zeroes
      ++                       //concatenated with
      BigInt(char).toString(2) //the ascii value as a binary string
    ).takeRight(7)             //the last 7 items from this sequence
    .map(n=>n-48)              //where each digit is mapped to its numerical value
  ).transpose                  //transpose, so the colums become rows and vice-versa
  .map(bits=>bits.sum)         //maps the bits in each column to their sum
  .toSet                       //and convert the sequence of sums to a set
  .size == 1                   //which has 1 element of the sums are the same
  //______________________________

```
> 2 votes

# Answer
# , 45 bytes

```
[:(*/@:={.)[:+/2 #.inv 3 u:]NB.____UUUUUUUUDD

```

Try it online! Includes test cases for most submissions submitted, along with the source code.
> 1 votes

# Answer
# Haskell, 118 bytes

```
_R _S=mod _S 2:_R(div _S 2)
_Z _S|_V:_W<-take 7.foldl1(zipWith(+))$_R.fromEnum<$>_S=all(==_V)_W
--________

```

Try it online! Usage: `_Z "some string"` returns either `True` or `False`.

There are some unprintable chars in the comment on the last line, so here is a string of the program using escaped chars:

```
"_R _S=mod _S 2:_R(div _S 2)\n_Z _S|_V:_W<-take 7.foldl1(zipWith(+))$_R.fromEnum<$>_S=all(==_V)_W\n--___\US\US\US\ETB\DC3\DC3\DC3\DC3\DC3\DC3\DC2\DC2_____"

```

Each bit occurs 68 times.

---

The shortest code I came up with was 82 bytes:

```
b n=mod n 2:b(div n 2)
(all=<<(==).head).take 7.foldl1(zipWith(+)).map(b.fromEnum)

```

However the sums of the bits for this code are `[33,28,41,48,20,79,46]`, so `79 - 20 = 59` no-ops plus 2 bytes for starting a comment would additionally be needed, totalling in 143 bytes.

While rearranging the program I found that using upper case letters as variable names helps to level the sums because they don't have the bit in the 6th position set. Because Haskell does not allow variable names to start with an upper case letter they need to be prepended with `_`, which also does not set the 6th bit.

In doing so I ended up with the above solution which has 97 bytes before adding the no-ops and the bist sum to `[50,47,56,56,48,68,60]`, so `(68 - 47) = 21`, so only 21 bytes need to be added in the comment.
> 1 votes

# Answer
# PHP, ~~95~~ ~~93~~ 91 bytes

I am so happy that PHP function names are case insensitive!

```
FOR(ZZSSSSQ__*;$W=ORD($argn[$T++]);)FOR($V=7;$V--;)$R[$V]+=$W>>$V&1;PRINT MIN($R)==MAX($R);

```

where the `*` must be replaced with ASCII 151 (0x97). (PHP would complain about any control character in the code - apart from `\r` and `\n`, but I need something with bit 4 set, so I added 128.)

+1 byte for pure printable ASCII: Use `_7` instead.

Run with `echo '<input>' | php -nR '<code>'` or test it online. Output is `1` for truthy, empty for falsy.
> 1 votes

# Answer
# Python 2, 117 bytes

All "spaces" are tabs to reduce number of 0x20 bits.

```
def Y(S):
    O=map(sorted,zip(*['{:07b}'.format(ord(W))for   W   in  S]))
    return  O[1:]==O[:-1]#V_____________

```

Contains 66 of each bit. (There is no `'%07b'` as explained in this issue.)

Hex dump:

```
00000000: 64 65 66 09 59 28 53 29 3a 0a 09 4f 3d 6d 61 70  def.Y(S):..O=map
00000010: 28 73 6f 72 74 65 64 2c 7a 69 70 28 2a 5b 27 7b  (sorted,zip(*['{
00000020: 3a 30 37 62 7d 27 2e 66 6f 72 6d 61 74 28 6f 72  :07b}'.format(or
00000030: 64 28 57 29 29 66 6f 72 09 57 09 69 6e 09 53 5d  d(W))for.W.in.S]
00000040: 29 29 0a 09 72 65 74 75 72 6e 09 4f 5b 31 3a 5d  ))..return.O[1:]
00000050: 3d 3d 4f 5b 3a 2d 31 5d 23 56 5f 5f 5f 5f 5f 5f  ==O[:-1]#V______
00000060: 5f 5f 5f 5f 5f 5f 5f 16 16 16 16 16 16 16 16 16  _______.........
00000070: 16 16 14 14 10                                   .....

```
> 0 votes

---
Tags: code-golf, restricted-source, binary
---


title: Motorcycle gear checker!

text:
# Question
Title: Motorcycle gear checker!
Some of you may be familiar with the way that a motorcycle shifts. But for those who don't, It looks like this

6

5

4

3

2

N

1

Now I want to know what gear I am in after performing a few up and down shifts. The program should work from neutral.

Sample input:

```
V^^

```

Sample output:

```
2

```

As you can see I downshifted once from N to 1 and upshifted twice to 2nd gear.

This is a code golf. Shortest answer in bytes wins.

Note: The input can be any 2 characters. Can be U and D for up and down or whatever you want **it has to be a string**. You cannot shift beyond 1st or 6th gear. If you are in 6th and upshift again it will stay in 6th. Good luck!

# Answer
## JavaScript (ES6), ~~49~~ ~~48~~ ~~47~~ 46 bytes

Expects:

* `1` for down
* `7` for up

```
f=([c,...s],g=2)=>c?f(s,g-c&7||g):'1N'[--g]||g

```

### Formatted and commented

```
f = (                   // f is a recursive function which takes:
  [c,                   // - c = next character in input string
      ...s],            // - s = remaining characters
  g = 2                 // - g = current gear, with default = neutral = 2
) =>                    //
  c ?                   // if there's still a character to process:
    f(                  //   do a recursive call with:
      s,                //     - the remaining characters
      g - c & 7 ||      //     - the updated gear if it is valid
      g                 //       or the previous gear if not
    )                   //
  :                     // else:
    '1N'[--g] ||        //   decrement g and output '1' for g = 0, 'N' for g = 1,
    g                   //   or simply the corresponding digit for other values

```

Gears are mapped as follows:

```
g MOD 8 = 0 1 2 3 4 5 6 7
          ---------------
gear    = X 1 N 2 3 4 5 6       (where 'X' is an invalid state)

```

Which allows us to easily check the validity of the current gear with:

```
(g & 7) != 0

```

### Demo

```
f=([c,...s],g=2)=>c?f(s,g-c&7||g):'1N'[--g]||g

console.log(f(''))
console.log(f('1'))
console.log(f('11'))
console.log(f('17777'))
console.log(f('1777777771'))
```
> 15 votes

# Answer
# 05AB1E, ~~22~~ 20 bytes

```
Îvy<+®‚Z5‚W}6LÀ'N¸ìè

```

Try it online!

**Explanation**

```
Î                      # push 0 (accumulator) and input
 v         }           # for each in input
  y<+                  # decrement current element and add to accumulator
     ®‚Z               # take maximum of current value and -1
        5‚W            # take minimum of current value and 5
            6L         # push the range [1 ... 6]
              À        # rotate left
               'N¸ì    # prepend the letter "N" producing the list [N, 2, 3, 4, 5, 6, 1]
                   è   # index into this list with the value produced by the loop

```
> 7 votes

# Answer
# MATL, ~~32~~ ~~28~~ 23 bytes

*5 bytes saved thanks to @Luis*

```
'234561N'j!Uq[aA]&Ys0))

```

This solution uses `'2'` for up-shift and `'0'` for down-shift.

Try it at **MATL Online**

**Explanation**

```
'234561N'   % Push the string literal to the stack
j           % Grab the input as a string
!U          % Convert the input to a numeric array based on the characters.
q           % Subtract 1 to turn '2' into 1 and '0' into -1
[aA]        % Push the array [-1 5] to the stack
&Ys         % Compute the cumulative sum using the array [-1, 5] as
            % the upper and lower limits at each point
0)          % Get the last value from the cumulative sum
)           % Use this to index into the initial string literal.
            % Implicitly display the result

```
> 6 votes

# Answer
# Java 7, ~~106~~ ~~105~~ 103 bytes

```
char c(String s){int r=1;for(int c:s.toCharArray())r+=c<99?1:-1;return"1N23456".charAt(r<0?0:r>6?6:r);}

```

**Explanation:**

```
char c(String s){                // Method with String input and character return-type
  int r = 1;                     // Result-index (0-indexed and starting at 1)
  for(int c : s.toCharArray()){  // Loop over all characters in the input String
    r += c < 99 ?                //  If the current character is '^':
           1                     //   Raise the result-index by 1
         :                       //  If it is 'v' instead:
           -1;                   //   Decrease the result-index by 1
  }
  return "1N23456".charAt(       // Return the character based on the return-index:
           r < 0 ?               //  If the result-index is below 0
                  0              //   Use 0 instead
                 : r > 6 ?       //  Else-if the result-index is above 6
                          6      //   Use 6 instead
                         :       //  Else
                          r);    //   Use the result-index
}

```

**Test code:**

Try it here.

```
class M{
  static char c(String s){int r=1;for(int c:s.toCharArray())r+=c<99?1:-1;return"1N23456".charAt(r<0?0:r>6?6:r);}

  public static void main(String[] a){
    System.out.println(c("v^^"));
    System.out.println(c("^^^^^^^^"));
    System.out.println(c("vvvv^^^vvvv"));
    System.out.println(c("^v^v^v^v"));
  }
}

```

**Output:**

```
2
6
1
N

```
> 6 votes

# Answer
# , ~~20~~, 15 bytes

```
:sil!î¬61énÀxVp

```

Try it online!

Input is a string of `h` (up) and `l` (down) characters.

*Thanks to @nmjcman for saving 5 bytes and teaching me about a vim feature I never knew about!*

If we could assume the input never goes out of bounds, it would simply be 9 bytes:

```
¬61énÀxVp

```

But unfortunately that isn't allowed.

Explanation:

```
:sil!           " If the cursor goes out of bounds, ignore it and continue
     î          " Run the following keystrokes as V code, rather than vimscript:
      ¬61       "   Insert the string "654321". This will leave the cursor on the '1'
         én     "   Insert an 'n'
           À    "   Run the first arg as V code. This will move left and right a bunch of times
            x   "   Delete whatever character we ended up on
             V  "   Select this whole line,
              p "   And replace it with the character we just deleted

```
> 6 votes

# Answer
# Haskell, ~~59~~ ~~53~~ 51 Bytes

```
("1N23456"!!).foldl(\l c->max 0$min 6$l+read[c]-1)1

```

Uses `0` for down and `2` for up. Usage example:

```
(("1N23456"!!).foldl(\l c->max 0$min 6$l+read[c]-1)1) "0002"

```

Thanks to @xnor for taking off 6 bytes! Also, turns out I don't need a function name or parentheses so that's another 2 bytes.
> 5 votes

# Answer
# JavaScript (ES6), ~~48~~ 58 bytes

```
s=>"1N23456"[[1,...s].reduce((a,b)=>a?a<6?+b?a+1:a-1:6:0)]

```

# Usage

Assign it to a function, and then call it. Input is a string containing a `1` for an upshift, and a `0` for a downshift.

```
f=s=>"1N23456"[[1,...s].reduce((a,b)=>a?a<6?+b?++a:a--:6:0)]
f("011")
-> "2"
f("0")
-> "1"
f("01")
-> "N"

```
> 4 votes

# Answer
# PHP 7.1, 71 bytes

```
for(;$c=$argv[1][$i++];))$g=max(-1,min($g+=$c<=>X,5));echo N234561[$g];

```

shifts `$g` from -1 to 5, uses negative string offset for first gear.
Run with `-nr`, provide shifting string as command line argument.
> 4 votes

# Answer
# Jelly, ~~17~~ 14 bytes

```
1;r2ị$¥/CỊ¡o”N

```

Uses `6` for up and`0` for down.

Try it online!

### How it works

```
1;r2ị$¥/CỊ¡o”N  Main link. Argument: s (string of 6's and 0's)

1;              Prepend a 1 (integer) to the string/character array s.
       /        Reduce the result by the following dyadic link.
                Let's call the arguments x and y.
      ¥           Create a dyadic chain of 2 links:
  r                 Construct the range [x, ..., y] (increasing or decreasing).
                    y will be a character, but 'r' casts both argument to int.
                    This is intended for use with floats, but it works just as well
                    when the argument is a digit.
     $              Create a monadic chain of two links:
   2ị                 Take the second element of the constructed range.
                  When y = 6 > x, this gives x + 1.
                  When y = 0 < x, this gives x - 1.
                  When y = x, the range is a singleton array, so this gives x.
          ¡     Conditional application:
         Ị        If the previous result is insignificant (0 or 1):
        C           Subtract it from 1.
                This swaps 0 and 1 without affecting the other potential outcomes.
           o”N  Logical OR with 'N', replacing 0 with that character.

```
> 4 votes

# Answer
## Ruby, 58 bytes

```
->s{a=1;s.chars{|b|a-=[a<=>0,a<=>6][b<=>?v]};"1N23456"[a]}

```

Expected input is 'v' for a downshift and '^' for upshift
> 2 votes

# Answer
# Rebol, 96 93 bytes

```
f: func[s][g: next"1N23456"parse s[any["D"(g: back g)|"U"(unless tail? x: next g[g: x])]]g/1]

```

Ungolfed:

```
f: func [s] [
    g: next "1N23456"
    parse s [
        any [
              "D" (g: back g)
            | "U" (unless tail? x: next g [g: x])
        ]
    ]
    g/1
]

```

Example usage (in Rebol console):

```
>> print f "DUU"
2

>> print f "DDDUU"
2

>> print f "UUUUUUUUU"
6

>> print f "UUUUUUUUUD"
5

```
> 2 votes

# Answer
# Processing JS (modified) 121 bytes

```
var g="1N23456",a="",c=0; for(var i=0;i<a.length;i++){if(a[i]==="d"&&c>0){c--;}else if(c<6&&a[i]==="u"){c++;}}println(g[c]);

```

Ungolfed

```
var g=[1,"N",2,3,4,5,6],a="",c=0;
for(var i=0;i<a.length;i++)
{if(a[i]==="d"&&c>0)
{
    c--;

}else if(c<6&&a[i]==="u")
{
    c++;

}

}
println(g[c]);

```

Try it online!

I went with PJs since I know it well. The only problem is the version I use is *very* strictly typed. I can't leave out brackets and lots of other tricks. It is pretty simple. The input should go into the variable `a` and it takes lowercase `u d`. The program loops until it hits the end of the string and every iteration it checks to see if it is a u or a d. If it is and it won't try and "shift" past where you can it shifts. At the end I print the results!
> 2 votes

# Answer
# k, 25 bytes

```
"1N23456"@{6&0|x+y-92}/1,

```

It takes input as a string, and uses `[` for downshift, and `]` for upshift, because they're conveniently situated.

```
"1N23456"@                / the numbers 0 to 6 are used for the gears,
                          / this turns them into the correct number/letter
                       1, / prepend 1 because this is our initial gear
          {          }/   / fold the function through the list
                          / x is before, y is the next character
                 y-92     / subtract 92, which is between "[" and "]"
                          / "[" becomes -1 and "]" becomes 1
               x+         / add it to what we had before
           6&0|           / use max and min to set boundaries 6 and 0

```

Examples:

```
 shift:"1N23456"@{6&0|x+y-92}/1,
 shift"[]]"
"2"
 shift"]]]]]]]]"
"6"
 shift"[[[[]]][[[["
"1"
 shift"[][][][]"
"N"
 shift"[[[[[[[[]"
"N"
 shift"]]]]]]]]["
"5"

```
> 2 votes

# Answer
## GNU sed, ~~89~~ 87 + 1(r flag) = 88 bytes

Because sed has no integer types or arithmetic operations, the solution is arrived at by using regular expressions only.

```
s:$:65432Nx1:
:
/6x/!s:^U(.*)(.)x:\1x\2:
s:^D(.*)x(.):\1\2x:
t
s:U|D::
t
s:.*(.)x.*:\1:

```

It works by sliding the pointer `x` based on each input shift, left (for `U`p) or right (for `D`own), along a non-wrapping tape that contains only the cells `65432N1`. The answer at the end is the value in the cell left of the pointer.

**Example run:** or **Try it online!**

```
sed -rf gear.sed <<< "UUUUUUD"
5

```

**Explanation:**

```
s:$:65432Nx1:              # assign initial tape and pointer
:                          # start loop
/6x/!s:^U(.*)(.)x:\1x\2:   # if shift 'U', slide `x` to left, but not past the edge
s:^D(.*)x(.):\1\2x:        # if shift 'D', slide `x` to right, -||-
t                          # repeat
s:U|D::                    # if a shift couldn't be applied, delete it "manually",
t                          # and jump to the start of the loop again
s:.*(.)x.*:\1:             # print value left of pointer `x` (answer)

```
> 2 votes

# Answer
# GNU sed, ~~76~~ 73 bytes

Includes +1 for `-r`

```
s/$/1/
:
/1{6}/!s/^U(.*)/\11/
s/^D(.*)1/\1/
t
s/U|D//
t
s/^1$/N/
s/^$/1/

```

Output is in unary except neutral, which is still `N` (see this consensus).

Try it online!

This basically counts up and down in unary then converts 1 to N and 0 to 1.

```
s/$/1/               # add 1 to the end (the starting value)
:                    # loop start
/1{6}/!s/^U(.*)/\11/ # If the string starts with 'U' and doesn't have 6 ones, increment
s/^D(.*)1/\1/        # If the string starts with 'D' decrement (but not past 0)
t                    # if something changed loop back
s/U|D//              # if the U or D couldn't be applied, remove it.
t                    # if something changed loop back
s/^1$/N/             # replace 1 with N
s/^$/1/              # if "0", replace with 1

```
> 2 votes

# Answer
# \>\<\>, 35 bytes

An enthusiastic piece of code that encourages you to drive above the speed limit.

Accepts any two inputs whose code modulo 3 are 0 and 2, for example `0` and `2`.
For extra fishiness, I recommend the use of `<` and `>`.

```
1i:0(?;3%1-+:0(?0:6)?6:1go!
1N23456

```

Explanation :

```
1i:0(?;3%1-+:0(?0:6)?6:1go!
1                             # initial position
 i                            # read the next char
  :0(?;                       # copies it, test copy against 0, if lower stops (EOF detection)
       3%1-                   # map the char to -1 or 1
           +                  # add it to the position
            :0(?0             # if the new position is lower than 0, set to 0
                 :6)?6        # if the new position is greater than 6, set to 6
                      :1go    # output a character from line 1 at the position
                          !   # loops and skip the position initialisation

```

You can try it here !
> 2 votes

# Answer
# CJam, ~~24~~ 22 bytes

```
"1N23456"1q{~0e>6e<}/=

```

Uses `(` for down and `)` for up.

Try it online!

**Explanation**

```
"1N23456"               e# Push the string containing all gears
         1              e# Push 1, the initial index
          q             e# Push the input
           {            e# For each character in the input
            ~           e#   Eval that character. ( is decrement and ) is increment.
             0e>        e#   Take the maximum of (0, index)
                6e<     e#   Take the minimum of (6, index)
                   }/   e# (end of block)
                     =  e# Take that index of the string

```
> 1 votes

# Answer
# SpecBAS - 102

```
1 g=2: INPUT s$
2 FOR i=1 TO LEN s$
3 g+=(s$(i)="^" AND g<7)-(s$(i)="v" AND g>1)
4 NEXT i
5  ?"1N23456"(g)

```

Moves the index of the string depending on input and prints the relevant character.
> 1 votes

# Answer
# Pyth, 32 bytes

```
J1VQ=JhtS[06+J-qNbqNd;?qJ1\N?JJ1

```

Uses space and newline for down and up.

Explanation

```
J1VQ=JhtS[06+J-qNbqNd;?qJ1\N?JJ1
J1                                 Initialize J to 1
  VQ                 ;             For each character in the input
            +J-qNbqNd              Increment or decrement J
      htS[06                       Get the middle sorted value of [0,6,J]
    =J                             Assign it to J
                      ?qJ1\N?JJ1   Change 1 to 'N' and 0 to 1

```

There's almost certainly a better way to do the incrementing and the output.
> 1 votes

# Answer
## Batch, 144 bytes

```
@set/ps=
@set g=1
:l
@if %g% neq %s:~,1% set/ag+=%s:~,1%/3-1
@set s=%s:~1%
@if not "%s%"=="" goto l
@if %g%==1 (echo N)else cmd/cset/ag+!g

```

Takes input on STDIN, using `0` to go to a lower gear and `6` to go to a higher gear. These numbers were chosen to make it easy to ignore the current gear. Finally if the gear is `1` then `N` is printed otherwise `0` is converted to `1` and the gear is printed.
> 1 votes

# Answer
# Javascript ES6 nonstrict, ~~136~~ 120 chars

## 136 chars for `V^`

```
with({get x(){return Math.max(0,Math.min(y,6))},set x(v){y=v}})f=s=>eval(s.replace(/(V)|./g,(m,v)=>`x${"-+"[+!v]}=1,`,y=1)+'"1N"[x]||x')

```

```
with({get x(){return Math.max(0,Math.min(y,6))},set x(v){y=v}})
f=s=>eval(s.replace(/(V)|./g,(m,v)=>`x${"-+"[+!v]}=1,`,y=1)+'"1N"[x]||x')
console.log(f("V^^"))
```

## 120 chars for `-+`

```
with({get x(){return Math.max(0,Math.min(y,6))},set x(v){y=v}})f=s=>eval(s.replace(/./g,m=>`x${m}=1,`,y=1)+'"1N"[x]||x')

```

```
with({get x(){return Math.max(0,Math.min(y,6))},set x(v){y=v}})
f=s=>eval(s.replace(/./g,m=>`x${m}=1,`,y=1)+'"1N"[x]||x')
console.log(f("-++"))
```
> 0 votes

# Answer
# Retina, 65 bytes

```
^
1 N23456
+(` (.)?(\w*6)u
$1 $2
)`(.)? (\w*6)d
 $1$2
.* (.).*
$1

```

Uses `u` and `d` for up and down.

Try it online!

**Explanation**

This program works by keeping `1N23456` behind the sequence of instructions. It keeps track of the current gear by having a space behind it. Then it takes one instruction at a time until there's no more.

```
^
1 N23456

```

Start by putting `1 N23456` before the input. The space before `N` indicates that `N` is the current gear.

```
+(` (.)?(\w*6)u
$1 $2
)`(.)? (\w*6)d
 $1$2

```

These are two replacement stages, grouped together, and run until they stop changing the string:

```
 (.)?(\w*6)u
$1 $2

```

The first one handles shifting the gear up. It will look for any number of gears after the space, followed by a `6`, then followed by `u` (`u` indicates the instruction to gear shift up). If there were characters before the 6, it swaps the space with the character immediately after it, deletes the `u`, and leaves the rest of the string intact. Since the `6` is mandatory in the match, it will only swap the space with any character before the `6`. It will never swap with the `6`.

```
(.)? (\w*6)d
 $1$2

```

The second stage handles gear shifting down, and works similarly. It looks optionally for a character before the space, then some other gears after ending in `6`, followed by `d`. It swaps the space with the character before it, deletes the `d`, and leaves the rest intact. If the space was at the start of the string, there was no match for a character before the space, so no swap occurs.

```
.* (.).*
$1

```

After neither of the above replacements can be done anymore, all gear shifts have been completed. The line is cleared of everything except the gear immediately after the space. This is the final gear.
> 0 votes

# Answer
# Python 3, ~~67~~ 63 bytes

```
k=1
for i in input():k+=[k<6,-(k>0)][i<'1']
print('1N23456'[k])

```

Pretty straightforward solution.

-4 bytes thanks to @ovs!
> 0 votes

# Answer
# Powershell, ~~112~~ ~~87~~ 85 bytes

`$i=1;switch([char[]]$args[0]){'^'{if(5-gt$i){$i++}}'v'{if(1-le$i){$i--}}}'1N2345'[$i]`

ungolfed

```
$i=1;                                # index which gear we are in
switch([char[]]$args[0]){            # loop over all elements using a switch
  '^'{if(5-gt$i){$i++}}             # if there is a ^ and we are not in sixth yet, shift up
  'v'{if(1-le$i){$i--}}             # if there is a v and we are not in first, shift down
}
'1N2345'[$i]                         # print the output

```

saved 25 bytes by reading the powershell codegolf tips

saved 2 bytes by flipping the gt/le operators
> 0 votes

# Answer
**Perl 6, 144 bytes**

```
my enum C <1 N 2 3 4 5 6>;my $n=prompt("");my $p=1;for split("",$n) ->$l {$l eq "u" && $p < 6 ?? ++$p !! 0;$l eq"d"&&$p>0 ?? --$p!!0};say C($p);

```

Works as it should, i believe. Improvements are welcome. First time using Perl for anything, but i loved the thought of the language, so i had to try.
> 0 votes

# Answer
# Clojure, 74 bytes

```
#((vec "1N23456")(reduce(fn[c s](max 0(min 6((if(= s \^)inc dec)c))))1 %))

```

Folds over the shift string, maintaining an index as the accumulator. Each iteration it either increases or decreases the index, then clamps it to the range 0-6. Finally, a string holding the gears is indexed and returned.

Returns a Clojure character representing the current gear. Gear 1 is returned as `\1`, and gear 'N' is returned as `\N`.

Pre-golfed explanation. Follow the numbers, since it doesn't read well top-down.

```
; Expects ^ for shift-up, and V (or anything else) for shift down
; Returns a character representing the current gear
(defn shift [shift-str]
  ((vec "1N23456") ; 4. Then index the gear list with the calculated index, and return
   (reduce (fn [current-gear s] ; 1. Fold over the shift symbols
             (max 0 (min 6 ; 3. Clamp it to the range 0-6 so we don't overflow
                      ((if (= s \^) inc dec) ; 2. If the shift is up, increase, else decrease
                       current-gear))))
           1
           shift-str)))

```
> 0 votes

---
Tags: code-golf
---


title: Day of the week of the next Feb 29th

text:
# Question
Title: Day of the week of the next Feb 29th
Write a function which takes a date and returns the day of the week of the next February 29th after that date.

* The input is a string in the ISO Extended format: YYYY-MM-DD (e.g. May 27th, 2010 would be "2010-05-27").
* The output is a string which is the name of the day of the week (e.g. "Monday"). Capitalization doesn't matter, but do give the full name in English.
* If the given date is February 29th, then return the day of the week of the *next* Feburary 29th.
* Use the calculations for the Proleptic Gregorian Calendar (so, it uses the Gregorian leap year calculations for it's entire length). Don't worry about the Julian Calendar or when the switch from Julian to Gregorian occurred. Just assume Gregorian for everything.
* The function should work for at least the range of "0001-01-01" - "2100-01-01".
* Feel free to use whatever standard libraries your language of choice provides, but do not use 3rd party libraries unless you want to include that code as part of your solution.
* Shortest code (fewest characters) wins.

**Examples:**

* `func("0001-01-01")` -\> `"Sunday"`
* `func("1899-12-03")` -\> `"Monday"`
* `func("1970-01-01")` -\> `"Tuesday"`
* `func("1999-07-06")` -\> `"Tuesday"`
* `func("2003-05-22")` -\> `"Sunday"`
* `func("2011-02-17")` -\> `"Wednesday"`
* `func("2100-01-01")` -\> `"Friday"`

(and no, you don't have to name the function `func`)

**Hints:**

* Remember that years ending in 00 which aren't divisable by 400 aren't leap years.
* January 1st, 0001 is a Monday.

# Answer
> 7 votes
## Windows PowerShell, 65

Fairly straightforward.

```
filter f{for($d=date $_;($d+='1').day*$d.month-58){}$d.dayofweek}

```

As usual, we can shave off two bytes if we are willing to wait a long time till completion:

```
filter f{for($d=date $_;($d+=9).day*$d.month-58){}$d.dayofweek}

```

Test:

```
> '0001-01-01','1899-12-03','1970-01-01','1999-07-06','2003-05-22','2011-02-17','2100-01-01'|f
Sunday
Monday
Tuesday
Tuesday
Sunday
Wednesday
Friday

```

History:

* 2011-02-18 00:06 (65) First attempt.

# Answer
> 5 votes
## Ruby 1.9, 85 characters

```
f=->a{require"date";d=Date.parse(a,0,0)+1;d+=1until d.day*d.month==58;d.strftime"%A"}

```

Straightforward solution. Call the function with `f[args]`.

* Edit: (87 -\> 97) Fixed the `0001-01-01` testcase.
* Edit 2: (97 -\> 91) Date.parse allows specifying the date of the calendar reform as well.
* Edit 3: (91 -\> 87) Use a lambda instead of a function. Thanks Dogbert!
* Edit 4: (87 -\> 85) Remove unnecessary spaces. Thanks again, Dogbert!

# Answer
> 3 votes
## T-SQL ~~166~~ 185 Characters

```
CREATE PROCEDURE f29 (@d DATETIME) AS
DECLARE @i int
SET @i=YEAR(DATEADD(M,-2,@d)+3)
SET @i=@i+(4-@i%4)
IF @i%100=0 AND @i%400<>0 SET @i=@i+4
SELECT DATENAME(W,CAST(@i AS CHAR)+'-2-29')

```

I was already messing with T-SQL date functions, so I figured why not...

Original solution was incorrect...

Here's what I *actually* have to do to get that strategy to work:

```
CREATE PROCEDURE f29 (@d DATE) AS
DECLARE @i int
SET @i = YEAR(@d)
BEGIN TRY
SET @i=YEAR(DATEADD(D, 3, DATEADD(M,-2,@d)))
END TRY
BEGIN CATCH
END CATCH
SET @i=@i+(4-@i%4)
IF @i%100=0 AND @i%400<>0 SET @i=@i+4
SELECT DATENAME(W,CAST(@i AS CHAR)+'-2-29')

```

# Answer
> 3 votes
**C#, 176**

```
Func<String,String>f=(d)=>{DateTime n;for(n=DateTime.Parse(d).AddDays(307);!(DateTime.IsLeapYear(n.Year));n=n.AddYears(1)){}return new DateTime(n.Year,2,29).ToString("dddd");};

```

# Answer
> 3 votes
# Bash, 96 bytes

Thanks Peter... Highly golfed version, 96 bytes:

```
i=1;until [ `date -d"$1 $i days" +%m-%d` = "02-29" ];do((i++));done
date -d "${1} ${i} days" +%A

```

Old version, 229 bytes

```
#!/bin/bash
from=$1
i=1
while [ "$isFeb" = "" ] || [ "$is29" = "" ]
do
isFeb=`date -d "${from} ${i} days" | grep Feb`
is29=`date -d "${from} ${i} days" +%Y-%m-%d | grep "\-29"`
((i++))
done
((i--))
date -d "${from} ${i} days" +%A

```

**SAMPLE I/O**

```
:~/aman>./29Feb.sh 0001-01-01
Sunday
:~/aman>./29Feb.sh 1899-12-03
Monday
:~/aman>./29Feb.sh 1970-01-01
Tuesday

```

# Answer
> 2 votes
### Perl, no date library: 160 159 155

```
sub f{($y,$m)=split/-/,@_[0],2;$y++if($m>'02-28');$y=($y+3)%400>>2;$y+=$y&&!($y%25);@r=(Tues,Wednes,Thurs,Fri,Satur,Sun,Mon);@r[(5*$y-($y/25&3))%7]."day";}

```

The real benefit of these date libraries is pushing off the length of the names of the days to someone else.

On the other hand, I think this is the only solution so far which works regardless of locale.

# Answer
> 2 votes
# DATE and some BASHy glue (90)

The function:

```
f(){ while :;do $(date -d$1+1day +'set - %F %A 1%m%d');(($3==10229))&&break;done;echo $2;}

```

Testing:

```
$ for x in 0001-01-01 1899-12-03 1970-01-01 1999-07-06 2003-05-22 2011-02-17 2100-01-01 ; do f $x ; done
Sunday
Monday
Tuesday
Tuesday
Sunday
Wednesday
Friday

```

# Answer
> 1 votes
# D: 175 Characters

```
S f(S)(S s){auto d=Date.fromISOExtString(s)+days(1);while(d.month!=Month.feb||d.day!=29)d+=days(1);return["Sun","Mon","Tues","Wednes","Thurs","Fri","Sat"][d.dayOfWeek]~"day";}

```

More Legibly:

```
S f(S)(S s)
{
    auto d = Date.fromISOExtString(s) + days(1);

    while(d.month != Month.feb || d.day != 29)
        d += days(1);

    return ["Sun", "Mon", "Tues", "Wednes", "Thurs", "Fri", "Sat"][d.dayOfWeek] ~ "day";
}

```

It's very easy to write in D, but it's definitely not going to win any code golfing contests. Still, outside of code golfing, I'd much rather have it easy to write and understand but long than have it terse but hard to write and understand.

# Answer
> 1 votes
## Java 8 - 252 chars

Golfed:

```
import java.time.*;
import java.time.format.*;
public class S{public static void main(String[] a){LocalDate d=LocalDate.parse(a[0]).plusDays(1);while(d.getMonthValue()!=2||d.getDayOfMonth()!=29){d=d.plusDays(1);}System.out.println(d.getDayOfWeek());}}

```

Ungolfed:

```
import java.time.*;
import java.time.format.*;
public class S {
    public static void main(String[] a) {
        LocalDate d = LocalDate.parse(a[0]).plusDays(1);

        while(d.getMonthValue()!=2 || d.getDayOfMonth()!=29) {
            d = d.plusDays(1);
        }
        System.out.println(d.getDayOfWeek());
    }
}

```

# Answer
> 1 votes
# Rebol - 78

```
f: func[d][system/locale/days/(until[d: d + 1 d/day * d/month = 58]d/weekday)]

```

Ungolfed:

```
f: func [d] [
    system/locale/days/(
        until [
            d: d + 1
            d/day * d/month = 58
        ]
        d/weekday
    )
]

```

Example usage (in Rebol console):

```
>> f 0001-01-01
== "Sunday"

>> f 2100-01-01
== "Friday"

```

# Answer
> 1 votes
# PHP, 104 bytes

```
function f($s){for($y=$s-(substr($s,5)<"02-29");!date(L,$t=strtotime(++$y."-2-1")););return date(l,$t);}

```

**breakdown**

```
for($y=$s-;                 // "-" casts the string to int; decrement year if ...
    (substr($s,5)<"02-29")  // ... date is before feb 29
    !date(L,                        // loop while incremented $y is no leap year
        $t=strtotime(++$y."-2-1")   // $t=feb 01 in that year (same weekday, but shorter)
    );
);
return date(l,$t);          // return weekday name of that timestamp

```

`date(L)`: `1` for leap year, `0` else
`date(l)`: full textual representation of the day of the week

# Answer
> 0 votes
# GNU coreutils, 71 bytes

```
f(){
seq -f "$1 %gday" 2921|date -f- +'%m%d%A'|sed 's/0229//;t;d;:;q'
}

```

Linear search of the next 8 years (worst case, given 2096-02-29). Sed finds and outputs the first line that matches 29th of February.

I was surprised to find that `t;d;:;q` was shorter than testing to see whether the digits remained (`/[01]/d;q`), despite being twice as many commands.

### Tests

I added an extra line of tests for difficult corner cases:

```
for i in 0001-01-01.Sunday 1899-12-03.Monday \
    1970-01-01.Tuesday     1999-07-06.Tuesday \
    2003-05-22.Sunday      2011-02-17.Wednesday 2100-01-01.Friday \
    2000-02-28.Tuesday     2000-02-29.Sunday    2000-03-01.Sunday   2096-02-29.Friday
do
    printf "%s => %s (expected %s)\n" ${i%.*} $(f ${i%.*}) ${i#*.}
done

```

---
Tags: code-golf, date
---


# Question
Title: Build a digital clock in Conway's Game of Life
Your task is to build a Game of Life simulation representing a digital clock, which satisfies the following properties:

1. The clock displays the hours and minutes in decimal (e.g. `12:00`, `3:59`, `7:24`) with a different state for each of the 1,440 minutes of the day — either the hours will go from 0 to 23 or from 1 to 12 with a PM indicator.
2. The pattern is periodic, and the state loops around without any outside interaction.
3. The minutes update at regular intervals — from one change of minute to the next takes the same number of generations.
4. An anonymous bystander is able to tell at a glance that the display is supposed to be a digital clock. In particular, this entails:

* The digits are visible and clearly distinguishable. You must be able to tell with certainty at a glance what time is being displayed.
    * The digits update in place. Each new number appears in the same place as the previous number, and there is little to no movement of the bounding boxes of the digits. (In particular, a digit does not contain 10 different digits in different places that get uncovered every time the digits change.)
    * The digits appear next to each other, without an excessive amount of space between them.

---

Your program will be scored on the following things, in order (with lower criteria acting as tiebreakers for higher criteria):

* Bounding box size — the rectangular box with the smallest area that completely contains the given solution wins.
* Fastest execution — the fewest generations to advance one minute wins.
* Initial live cell count — smaller count wins.
* First to post — earlier post wins.

# Answer
# 11,520 generations per clock count / 10,016 x 6,796 box / 244,596 pop count

There you go... Was fun.

Well, the design is certainly not optimal. Neither from the bounding box standpoint (those 7-segment digits are *huge*), nor from the initial population count (there are some useless stuff, and some stuff that could certainly be made simpler), and the execution speed - well... I'm not sure.

But, hey, it's beautiful. Look:

**Run it!**

Get the design from this gist. Copy the whole file text to the clipboard.

**New**: here is a version with both AM and PM indicators for the demanding.

Go to the online JavaScript Conway life simulator. Click *import*, paste the design text. You should see the design. Then, go to *settings* and set the *generation step* to 512, or something around those lines, or you'll have to wait forever to see the clock display updating.

Click *run*, wait a bit and be amazed!

Direct link to in-browser version.

Note that the only algorithm that makes this huge design useable is hashlife. But with this, you can achieve the whole clock wraparound in seconds. With other algorithms, it is impractical to even see the hour changing.

**How it works**

It uses p30 technology. Just basic things, gliders and lightweight spaceships. Basically, the design goes top-down:

* At the very top, there's the clock. It is a 11520 period clock. Note that you need about 10.000 generations to ensure the display is updated appropriately, but the design should still be stable with a clock of smaller period (about 5.000 or so - the clock needs to be multiple of 60).
* Then, there is the clock distribution stage. The clock glider is copied in a balanced tree, so at the end, there are 32 gliders arriving at the exact same moment to the counters stage.
* The counter stage is made using a RS latch for each state, and for each digit (we're counting in decimal). So there is 10 states for the right digit of the minutes, 6 states for the left digit of the minuts, and 12 states for the hours (both digits of the hours are merged here). For each of these groups, the counter behaves like a shift register.
* After the counting stage, there are the lookup tables. They convert the state pulses to display segments ON/OFF actions.
* Then, the display itself. The segments are simply made with multiple strings of LWSS. Each segment has it own latch to maintain its state. I could have made a simple logical-OR of the digit states to know wether a segment must be ON or OFF, and get rid of these latches, but there would be glitches for non-changing segments, when the digits are changing (because of signal delays). And there would be long streams of gliders coming from the lookup table to the digit segments. So it wouldn't be as nice-looking. And it needed to be. Yes.

Anyway, there is actually nothing extraordinary in this design. There are no amazing reactions that have been discovered in this process, and no really clever combinations that nobody thought of before. Just bits taken here and there and put together (and I'm not even sure I did it the "right" way - I was actually completely new to this). It required a lot of patience, however. Making all those gliders coming up at the right time in the right position was head-scratching.

**Possible optimizations:**

* Instead of copying and distributing the same root clock to the *n* counter cells, I could have just put the same clock block *n* times (once for each counter cell). This would actually be much simpler. But then I wouldn't be able to adjust it as easily by changing the clock at a single point... And I have an electronics background, and in a real circuit, that would be horribly wrong.
* Each segment has it own RS latch. This requires the lookup tables to output both R and S pulses. If we had a latch that would just toggle its state from a common input pulse, we could make the lookup tables half as big. There is such a latch for the PM dot, but it is huge, and I'm unable to come up with something more practical.
* Make the display smaller. But that wouldn't be as nice-looking. And it needed to be. Yes.
> 1163 votes

---
Tags: code-challenge, cellular-automata, game-of-life
---


# Question
Title: Simulate the Wireworld cellular automaton
Wireworld is a cellular automaton that was designed to be resemble electrons flowing through wires. Its simple mechanics allow the construction of digital circuits. It has even permitted the construction of an entire computer.

Your mission is to create the shortest Wireworld implementation in your language of choice.

Each cell in the grid has one out of four states. The four states are "blank," "copper," "electron head," or "electron tail."

* A blank cell will always remain a blank cell
* An electron head will always become an electron tail
* An electron tail will always become copper
* A copper cell will become an electron head iff exactly one or two out of its eight neighbors are electron heads, otherwise it will remain copper

This competition will have a similar style to the Shortest Game of Life competition, but with a few changes.

* The grid must be at least 40 by 40 cells
* The edges of the grid must NOT wrap around (not a torus). Treat cells outside of the field as being constantly "blank."
* It must be possible for the users to enter their own starting configuration.
* Staring at blank screens is not fun. The program must visually display the simulation as it is running.

This is code golf, fewest bytes wins.

# Answer
## APL, Dyalog (131)

```
{h t c←1↓⍵∘=¨F←' htc'⋄⎕SM∘←1 1,⍨⊂N←F[1+⊃+/H h(t∨c≠H←c∧S↑1 1↓1 2∊⍨⊃+/+/K∘.⊖(K←2-⍳3)∘.⌽⊂¯1⌽¯1⊖h↑⍨2+S←25 79)×¨⍳3]⋄∇N⊣⎕DL÷4}↑{79↑⍞}¨⍳25

```

The output is displayed in the `⎕SM` window. The simulation runs endlessly. The grid is 79x25 because that's the default size of the `⎕SM` window. The electron head is `h`, tail is `t`, copper is `c`. The program reads the starting configuration from the keyboard as 25 lines.

Explanation:

* `↑{79↑⍞}¨⍳25`: read the 79x25 grid
* `h t c←1↓⍵∘=¨F←' htc'`: get three matrices, one with the heads, one with the tails and one with the copper. Also set F to the string `' htc'`.
* `⎕SM∘←1 1,⍨⊂N←F[1+⊃+/`...`×¨⍳3]`: The "..." part is a vector of length three, where the elements are matrices showing the new heads, tails, and copper respectively. The heads are multiplied by 1, the tails by 2, and the copper by 3, then we sum these matrices together and add one, giving a matrix of indices into `F`. `N` becomes the new state, in the same format as the input, and it is shown on the `⎕SM` screen starting from the top-left corner.
* `¯1⌽¯1⊖h↑⍨2+S←25 79`: Add a border of blanks to `h` by growing it by two rows and columns, then rotating it one right and one down.
* `⊃+/+/K∘.⊖(K←2-⍳3)∘.⌽⊂`: Rotate the matrix in all eight directions and then sum the resulting matrices together, giving the amount of neighbours that are heads on each position.
* `1 2∊⍨`: Set only those positions to 1 which have 1 or 2 neighbours.
* `S↑1 1↓`: Remove the border we added earlier.
* `H←c∧`: The new heads are all those copper cells that have 1 or 2 head neighbours.
* `t∨c≠H`: The new copper cells are all old tails, and all old copper cells that have not become heads.
* `H h(`...`)`: The new heads are `H` as calculated above, the new tails are the old heads, and the new copper cells are as calculated above.
* `∇N⊣⎕DL÷4`: Wait 1/4th of a second, then run the function again on `N`.
> 7 votes

# Answer
## ALPACA, 82 chars

ALPACA is a language specifically designed for cellular automatons.

o is nothing; c is conductor; e is electron; t is electron tail.

```
state o " ";
state c "c" to e when 1 e or 2 e;
state e "e" to t;
state t "t" to c.

```
> 7 votes

# Answer
## GolfScript (125 120 105 100 chars)

```
n%{.,,{1${.0=,:w[1,*]\+2*>3<}:^~`{zip^''+.4=5%'`X '@{+}*(7&1>'iX'>+=}+w,%}%"\033[H\033[J"@n*+puts 6.?.?}do

```

Note that I'm counting the `\033` as one character each, because they can be replaced by a literal `ESC` character. This uses ANSI control codes, so relies on a compatible tty. Also note that frames are printed starting with the input grid.

There is some overlap with Generate a grid of sums, which also uses the Moore neighbourhood.

Encoding: blank space =\> ; electron head =\> `i`; electron tail =\> ```; copper =\> `X`.

The pause between iterations is the time required to calculate 46656<sup>46656</sup>. Changing `6.?.?` to another expression allows you to control the speed; the next slowest for the same character count is `7.?.?`, which is *much* slower (the output is 22 times as big, and it's not a linear complexity calculation).

For a test case, I've been using

```
`iXXXXXXXXX
X   X
   XXX
X   X
i`XX XXXXXX

```

from the Rosetta Code Wireworld challenge.
> 4 votes

# Answer
## Python (~~243~~ 214)

Tried to make a cross between usability and characters. The grid is 40x40. Input is given on stdin. An electron head is `h`, electron tail is `t`, copper is `c`, anything else is blank.

```
import os
f=raw_input()
while 1:f=''.join('h'if(i=='c')&(0<sum(1 for i in[-1,1,-39,-40,-41,39,40,41]if f[e+i:e+i+1]=='h')<3)else't'if i=='h'else'c'if i=='t'else f[e]for e,i in enumerate(f));os.system('cls');print f

```

The while loop (line 3) uncompressed (will not work if placed in code):

```
while 1:
 for e,i in enumerate(f):
  if(i=='c')&(0<sum(1 for i in[-1,1,-39,-40,-41,39,40,41]if f[e+i:e+i+1]=='h')<3):f[e]='h'
  elif i=='h':f[e]='t'
  elif i=='t':f[e]='c'
  else:f[e]=f[e]  #redundant, but Python needs this to run
 os.system('cls') #cls is shorter than clear, so I used that
 print f

```
> 3 votes

# Answer
# Python 371 341 chars

Yeah, it's not that short, but it has an interactive gui!

```
import matplotlib.pylab as l,scipy.ndimage as i
r=round
w=l.zeros((40,40),int)-1
p=l.matshow(w,vmax=2)
c=p.figure.canvas
def h(e):
 try:w[r(e.ydata),r(e.xdata)]=[0,2,-1][e.button-1]
 except:x=i.convolve(w==2,l.ones((3,3)),int,'constant');w[:]=w/2+((w==0)&(x>0)&(x<3))*2
 p.set_data(w);c.draw()
c.mpl_connect('button_press_event',h)
l.show()

```

Instructions:

Click with left mouse button to place wire

Click with right mouse button to clear

Click with middle mouse button to place electron head

Click outside the axes to step the automaton
> 3 votes

# Answer
# C, 355 347 300 294 chars

Edit: realized I don't need `feof()`

Edit: Saved 47 chars! Removed the Sleep, got rid of almost all braces, combined a lot of operations.

Edit: Last one today, since I broke 300 chars. Changed `printf` to `puts`, found a cute little optimization with the first comparison.

C does not lend itself well to this sort of problem, but hey, golfing it is fun. This is a pretty brute-force implementation, but I wanted to see how far I could golf it up.

Input is a text file named `i`. It contains a representation of the starting state, with `*` for copper, `+` for electron head, `-` for electron tail, spaces for empty cells. I'm using the XOR gate from the wiki page for testing.

```
   ****-+**
  +        ******
   -*******      *
                ****
                *  *****
                ****
   ********      *
  +        ******
   -****+-*

```

---

```
char*p,t[42][42],s[42][42];
main(i,r,c,n,j)
{
  for(p=fopen("i","r");fgets(s[i++]+1,40,p););

  for(;;getch(),memcpy(s,t,1764))
    for(j=1;j<41;puts(s[j++]+1))
      for(i=1;i<41;)
      {
        p=t[j]+i;
        r=s[j][i++];
        *p=r==43?45:r;
        if(r==45)
          *p=42;
        if(r==42)
          for(r=-1,n=0;r<2;++r,*p=n&&n<3?43:42)
            for(c=-2;c<1;)
              n+=s[j+r][i+c++]==43;
      }
}

```
> 2 votes

# Answer
## Python, 234 218 chars

```
import time
I=input
C=I()
H=I()
T=I()
R=range(40)
while 1:
 for y in R:print''.join(' CHT'[(C+H+2*T).count(x+y*1j)]for x in R)
 H,T=[c for c in C if 0<sum(1 for h in H if abs(c-h)<2)<3and c not in H+T],H;time.sleep(.1)

```

You input the board as three list of complex numbers representing the coordinates of the cells of copper (which must include the heads and tails lists), heads, and tails. Here's an example:

```
[3+2j+x for x in range(8)] + [3+4j+x for x in range(8)] + [11+3j+x for x in range(6)] + [2+3j]
[3+2j]
[2+3j]

```

Note that we `eval` the input, so you can use arbitrarily complex expressions for lists of complex numbers.
> 1 votes

# Answer
## QBasic, 309 bytes

**Warning:** the golfed version is not user-friendly: it has a weird input method, runs as an infinite loop, and doesn't have any delay (thus, runs too fast on some systems). Only run it if you know how to terminate a program in your QBasic environment. The ungolfed version is recommended (see below).

```
INPUT w,h
SCREEN 9
FOR y=1TO h
FOR x=1TO w
PSET(x,y),VAL(INPUT$(1))
NEXT
NEXT
DO
FOR y=1TO h
FOR x=1TO w
SCREEN,,0
c=POINT(x,y)
d=c
IF c=7THEN d=1
IF c=1THEN d=6
IF c=6THEN
n=0
FOR v=y-1TO y+1
FOR u=x-1TO x+1
n=n-(POINT(u,v)=7)
NEXT
NEXT
d=7+(n=0OR n>2)
END IF
SCREEN,,1,0
PSET(x,y),d
NEXT
NEXT
PCOPY 1,0
LOOP

```

To run, specify at the input prompt your configuration's width `w` and height `h`.<sup>1</sup> Then type `w*h` single-digit codes for the cells (moving left to right, then top to bottom), with

* `0` = empty
* `6` = wire
* `7` = signal head
* `1` = signal tail

Once you have entered all of the cells, the simulation will begin (and continue forever, until you kill the program).

### Ungolfed

A more user-friendly version. To modify the layout, modify the `DATA` statements at the end.

The code takes advantage of the `POINT` function, which reads the color value of a pixel from the screen. This means we don't have to store the cells separately as an array. To make sure that all cells update simultaneously, we perform the updates on a second "page." We can toggle the active page using a version of the `SCREEN` statement, and copy one page's contents to another using the `PCOPY` statement.

```
SCREEN 9

EMPTY = 0 ' Black
HEAD = 7  ' Light gray
TAIL = 1  ' Blue
WIRE = 6  ' Brown/orange

' First two data values are the width and height
READ w, h
' The rest are the initial configuration, row by row
' Read them and plot the appropriately colored pixels
FOR y = 1 TO h
  FOR x = 1 TO w
    READ state$
    IF state$ = "" THEN value = EMPTY
    IF state$ = "H" THEN value = HEAD
    IF state$ = "T" THEN value = TAIL
    IF state$ = "W" THEN value = WIRE
    PSET (x, y), value
  NEXT x
NEXT y

' Loop the simulation until user presses a key
DO UNTIL INKEY$ <> ""
  ' Store current time for delay purposes
  t# = TIMER

  FOR y = 1 TO h
    FOR x = 1 TO w
      ' Active page = display page = 0
      SCREEN , , 0
      ' Get the color value of the pixel at x,y
      oldVal = POINT(x, y)
      IF oldVal = EMPTY THEN
        newVal = EMPTY
      ELSEIF oldVal = HEAD THEN
        newVal = TAIL
      ELSEIF oldVal = TAIL THEN
        newVal = WIRE
      ELSEIF oldVal = WIRE THEN
        neighbors = 0
        FOR ny = y - 1 TO y + 1
          FOR nx = x - 1 TO x + 1
            IF POINT(nx, ny) = HEAD THEN neighbors = neighbors + 1
          NEXT nx
        NEXT ny
        IF neighbors = 1 OR neighbors = 2 THEN
          newVal = HEAD
        ELSE
          newVal = WIRE
        END IF
      END IF
      ' Active page = 1, display page = 0
      SCREEN , , 1, 0
      ' Plot the new value on page 1
      PSET (x, y), newVal
    NEXT x
  NEXT y

  ' Copy page 1 to page 0
  PCOPY 1, 0

  ' Delay
  WHILE TIMER >= t# AND t# + 0.2 > TIMER
  WEND
LOOP

DATA 8,5
DATA T,H,W,W,W,W,W,W
DATA W, , , ,W, , ,
DATA  , , ,W,W,W, ,
DATA W, , , ,W, , ,
DATA H,T,W,W, ,W,W,W

```

1 The maximum values for width and height depend on which screen mode is used. In `SCREEN 9`, width can be up to 638 and height up to 348. `SCREEN 7` has a smaller resolution (max configuration size 318 by 198), but the pixels are bigger and thus easier to see (on DOS QBasic or the DOSBox emulator--unfortunately QB64 just gives a smaller window).

### Example run

Ungolfed version on archive.org, with screen mode 7:
> 1 votes

---
Tags: code-golf, cellular-automata
---