title: You have a n day streak!

text:
# Question
Title: You have a n day streak!
Write a program that keeps track of the number of consecutive days it has been run.

The day resets at midnight (the local time of the computer on which the program is run).

If there is a day that the program is not run, the counter is reset to zero.

Every time the program is run, the counter should go up by one day if it is the first time the program is run that day. This means that the first time the program is run, it should say, "You have a 1 day streak!"

The output of the program is in the form: `You have a [streak_length] day streak!`

You are allowed to store data externally or modify the source code––your choice.

This is , so shortest code in bytes wins!

# Answer
> 5 votes
# Bash, ~~92~~, ~~90~~, 82 bytes

**Golfed**

```
grep `date -d-1day -I` h||>h
date -I>>h
echo You have a `uniq h|wc -l` day streak!

```

**EDITS**

* Truncate file, instead of removing it, -8 bytes;
* Replaced *-daystart* with *! -newermt* to save 2 bytes.

**How It Works !**

Each time you launch it will append a line with the current date to the file *h*, e.g:

```
2017-02-03
2017-02-04
2017-02-05
2017-02-05

```

It will then use `uniq` to filter out duplicates (i.e. multiple launches, within the same day), and count the lines to get the *streak* length.

```
uniq h|wc -l

```

To reset a *streak*, it will grep for 'yesterday' in *h*, and truncate it if not found.

```
grep `date -d-1day -I` h||>h

```

# Answer
> 5 votes
# Bash, 102 bytes

```
find ! -newerat 0-1day -delete
touch -a a
echo You have a $((1+(`stat -c %X-%Y a`)/86400)) day streak!

```

**Warning, do *not* run in any folder you care about. It deletes any file not accessed in the last day in the working directory.**

Uses a file `a` to store data, using the accessed/modified timestamps.

# Answer
> 2 votes
# Goruby, 85 Bytes

Run with the interpreter flag `-rdate`.

```
c,t=0,Dae.y
op t.ts,?w
dw{c+=1;t=t.p;Fil.f t.ts}
s"You have a #{c} day streak!"

```

It works by storing a new file for each day on which it's invoked, then counts the number of consecutive files backwards to obtain the length of the streak. It doesn't ever delete files, so it will, eventually, after a very, very, very, very, very long time, fill your hard drive, a handful of bytes at a time.

Here's an ungolfed version of it:

```
streak, current_date = 0, Date.today
open(current_date.to_s, 'w')
while File.file?(current_date.to_s)
    streak += 1
    current_date = current_date.prev_day;
end
puts "You have a #{streak} day streak!"

```

# Answer
> 1 votes
# Bash + coreutils, ~~120~~ 97 bytes

```
read d n<f;c=`date -d0 +%s`;echo $c $[c>d?c>d+86399?n=1:++n:n]>f;echo You have a $n day streak!

```

The bash line above has 95 bytes in it.

There's a second file called f that just contains a single character:

```
0

```

(The program writes to f.)

So I think the total number of bytes should be scored as 97 (95 bytes for the contents of the bash file, 1 byte for the contents of the external file, and 1 byte because 1 file other than the program is used). This is based on Counting bytes for multi-file programs.

Note: Thanks to @orlp for pointing out that an earlier answer to this that I posted was nonsense; I had misread the problem completely. (It was posted as a different answer, which I've deleted.)

# Answer
> 1 votes
**Python 3, 213 bytes**

```
import time
t=time.time()
try:
 r=open("a").read().split(":")
 open("a","w").write((str(int(r[0])+1)+":"+t)if(t>float(r[1])+86400)and(t<float(r[1])+172800)else("1:"+str(t)))
except:open("a","w").write("1:"+str(t))

```

# Answer
> 0 votes
# PowerShell, 95 bytes

```
(date -f 'd')>>z
gc z|gu|%{$c=(1,++$c)[($d=date $_)-eq$n]
$n=$d+1D}
"You have a $c day streak!"

```

Try it online!

### Explanation

I start by writing the current date (in short date format) out to a file (named `z`). `>>` works as usual; appends, but creates if it doesn't exist.

Next, I read the contents of the file line by line with `Get-Content` (`gc`), pipe through `Get-Unique` (`gu`) since there could be multiple entries from the same date, then pipe through `ForEach-Object` (`%`).

In the loop, I create a 2 element array with the value `0` in the first element, and the current value of `$c` (`+1`) in the second element. Using `++$c` allows me to avoid wrapping something like `$c+1` in parentheses.

Then I index into the two element array with a boolean comparison, which will get coalesced to `0` for `$false` or `1` for `$true`. Within the comparison, I'm assigning to `$d` a `[datetime]` object created from the date read from the current line in the file. That object gets compared to `$n`, which on the first run hasn't been assigned yet, so it will never match, and `$c` will be initialized to `1`, since the value of the indexing is being assigned to `$c`.

Next, `$n` is populated with the next expected date, by adding `1` to the current datetime object. The key here is that `1D` means it's a `[decimal]` literal. For some reason when you add integer numbers to a `[datetime]`, it's interpreted as ticks, but when you add floating point numbers, they are interpreted as days. So this populates `$n` for the next iteration.

The effect is that the counter gets reset every time the current date doesn't match the "next" date (which is the previous date plus 1 day).

Finally the message is output.

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


title: Kolmogorov Complexity Meta Golfer

text:
# Question
Title: Kolmogorov Complexity Meta Golfer
* Mike Bufardeci (Pyth) - 175 bytes
* Leo (Retina) - 175 bytes
* devRicher (Lua) - 182 bytes
* Peter Taylor (CJam) - Waiting for clarification
* Lyth (C++11) - Waiting for clarification

---

**Edit: Several changes made, should not affect any already submitted answers.**

**Edit #2: Very few people are taking advantage of the 1024 byte limit. The point of this challenge is to output code golf answers, not things like the example at the bottom of this post.**

**Edit #3: Here is the paragraph to test against: `WASHINGTON - These are chaotic and anxious days inside the National Security Council, the traditional center of management for a president's dealings with an uncertain world.` I will test the submissions myself later.**

At PPCG, we pride ourselves in writing programs to solve problems. However, it's very time consuming to write the programs to solve problems. Instead we should write programs to write programs to solve problems!

In this case, the problem is Kolmogorov Complexity. You must write a program that golfs a program, that outputs piece of text.

Main program -\> Generated program -\> Text

You do not necessarily need to golf the main program. Your score is the length of the generated program.

---

You will not know the final text when writing the main program. Therefore, you will not be able to write the generated program by hand. The main program should take a string input and create the generated program, which correctly outputs the text.

---

On February 12th, the first paragraph of the headline of the New York Times will be used for scoring. I will post the article at 10 AM ESThttps://www.nytimes.com/

---

* You may use any language for the main program and generated program. They do not have to be the same.
* The final text will never contain these characters: `", ', \n, \r`.
* The main program is limited to 1024 bytes (not characters). The generated program has no byte limit, as long as it outputs the text.
* Compression algorithms built in to your language are not allowed (both ways), unless you code it from scratch. This includes any type of text compression libraries, and base conversion. This does not include Regexes.
* Standard loopholes apply.

---

Example: (JavaScript)
```
f=(g)=>{console.log("console.log('" + g + "')")}

```

# Answer
# Retina, worst case (3+original length) bytes

*EDIT: added support for newlines, in order to try this code in actual kolmogorov complexity challenges. Behaviour on strings without newlines remains unchanged.*

Retina is great at substituting substrings, so that's what we're going to do!

This program looks for repeated sequences of characters and replaces them every time with a single character not appearing in the full string. The generated program then starts with the "compressed" string and applies all substitutions in reverse.

This code adds 3 bytes of boilerplate (a newline at the beginning, and a `\`` towards the end to suppress a trailing newline), so in the worst case (when there are no repeated sequences worth substituting) we have a length of 3 bytes more than the starting string. On average, this will shave a few bytes from the original length, not much but still a compression.

Here's the code with some comments:

First, we use a trick with transliteration ranges to change newlines into , which is how newlines are printed in a Retina program

```
T`µ¶·`µ-·

```

then we start the main loop, duplicating the first line

```
{`^.+
$&¶$&

```

we only substitute when the sequence is repeated enough times (depending on its length)

```
^.*?((......+).*?\2|(.....?).*?\3.*?\3|(...).*?\4.*?\4.*?\4|(..).*?\5.*?\5.*?\5.*?\5.*?\5).*
"$2$3$4$5
^"(.+)|^.*
$+

```

to find a character not in the string, we append a list of candidates to the string, using `"` as separator, and then remove duplicates

```
^(.*)¶(.*)
$2" 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!#%&\'()*+,-./:;?@\^_`{|}~¶$2¶$1
D`(?<=^.*).
^.*"(.)?.*¶(.+)
$2¶$1

```

here the actual substitution in the text happens

```
+`^(.*)(.+)(.*¶(.)¶\2(¶|$))
$1$4$3

```

in case we couldn't find a repeated sequence or an unused character, we restore the string to the original state (which makes us break from the loop)

```
}`(.*)¶(¶.*|.*¶)(¶|$)
$1$3

```

at the end, we add the 3 bytes of boilerplate

```
^
¶
\-1=`.*¶
\`$&

```

Try it online!

In the linked example, the 292 bytes paragraph gets compressed to a 286 bytes Retina code.

NOTE: the substitutions made are not optimal, we just make every time the first suitable substitution we find; I don't know if an algorithm finding the optimal substitutions could run in a reasonable amount of time.
> 3 votes

# Answer
# Pyth, worst case `length(input) + 1` bytes

```
=kNJ++kzkV92Iq/zC+32N0 aYC+32N))V.:z7I>/JN2=J+++\::JNK.)Y+\\K++kNk))V.:z6I>/JN2=J+++\::JN=K.)Y+\\K++kNk))V.:z5I>/JN2=J+++\::JN=K.)Y+\\K++kNk))V.:z4I>/JN3=J+++\::JN=K.)Y+\\K++kNk))V.:z3I>/JN4=J+++\::JN=K.)Y+\\K++kNk))V.:z2I>/JN7=J+++\::JN=K.)Y+\\K++kNk))?qeJkPJJ

```

Test Suite Available Online
Generated Programs from Test Suite

## Explanation

This program no longer abuses the fact that the article will be the first paragraph of a NY Times article and is now a general compressor of short strings. There are still some assumptions being made here, specifically that not all characters will appear in the text and that the text is at least seven characters long.

The high level explanation is that the program searches thorough the text for progressively shorter repeated strings, then replaces each repeated with a character not present in the text. Each string length has its own break even point where making a substitution is actually shorter than leaving the text alone. For strings of length 7 only 2 occurrences are needed but for strings of length 3 the break even point is 4 occurrences.

### Main Program

The main program mostly consists of six loops: one each for strings of length seven down through strings of length 2. Each loop goes over all substrings of the input with that length, counts how often they appear in the article and determines if a replacement should be made. If a replacement is made then the string is wrapped with a replacement method to obtain the original string.

This breakdown is itself broken down into several parts for readability. This first part is setting up for the main loops.

```
=kNJ++kzkV95Iq/zC+32N0 aYC+32N))
  N                               N is initialized to " (the double quote character)
=kN                               assign " to k
       z                          z is initialized to the input
    ++kzk                         wrap z with double quotes
   J                              and assign that to J (J automatically assigns on first use)
          92     +32      +32     32-126 is the "printable" character range
          92     +32      +32     | causes issues so we stop before it (code point 124)
         V92                   )  for each printable character:
              /zC+32N              count occurrences of it in the input
            Iq       0        )    if there are 0 occurrences:
                       aYC+32N      append that character to list Y (Y is initialized to an empty list)

```

The six main loops are nearly identical. I will breakdown a general loop for the sake of simplicity.

```
V.:z5I>/JN2=J+++\::JN=K.)Y+\\K++kNk))
   z                                   z is the input
 .:z5                                  get each substring of a certain length (here 5)
V                                   )  for each string:
       /JN                              count how many times it appears in the input
     I>   2                        )    if count > break even point: (here 2)
                       .)Y               pop a character off Y (unused characters list)
                     =K                  assign it to K (K automatically assigns the first time but must be manually assigned after that)
                  :JN K                  regex replacement:
                   J                      in the input
                    N                     replace current string
                      K                   with popped character
               +\:                       prepend : (the colon character)
              +           +\\K           append \ and popped character
             +                ++kNk      append current string wrapped in double quotes
           =J                            and assign to variable J

```

This last section only saves one byte on the generated program but also ensures that the worst case is as long as our trivial answer.

```
?qeJkPJJ
    k     k is still set to " (the double quote character)
   J  JJ  J is the string to be returned
?qeJk     if the last character of J is ":
     PJ    return J without the last character
          else:
       J   return J

```

### Generated Program

If no substitutions are made the generated program will be in this format:

```
"(input)

```

This will have a length of `length(input) + 1` bytes. This is the worst case, and I fear it may also be the average case. One paragraph does not have a lot of repeated strings, especially because professional writers try to vary their words.

If one substitution is made then the generated program will be in this format:

```
:"(input with replacements)"\(unused character)"(replacement string)

```

In Pyth, this is the format for replacement with regular expressions. Instances of the unused character in the input are replaced with the replacement string.

This adds a static 6 characters to the string, but in the worst case we are hitting the break even point mentioned earlier.

Here is the format for a generated program with two replacements:

```
::"(input with replacements)"\(char 1)"(str 1)"\(char 2)"(str 2)

```

As replacements stack up we simply add another colon to the front and add the substring and replacement character to the end.

I have not determined what the size reduction is in the best case. If anyone can determine the size of the generated program in the best case please let me know.
> 3 votes

# Answer
## CJam, Burrows-Wheeler transform and run-length encoding

I think it's stupid to ban builtins for base-conversion as "compression", but I've implemented my own, as well as implementing run-length encoding and decoding manually rather than using the builtin.

```
q
e# Reduce range, add start-of-message marker
[0\:i_:e<(:If-+
e# Burrows-Wheeler transform
_,({_(+}*]$Wf=
e# RLE without e`, decrementing each runlength for compactness
0\{_2$={;\)}0?\}%\;2/
e# Pair [runlength-1 ch] to a single int
_1f=:e>):Paf{.*1b}
e# Base-convert to the minimal possible base
_:e>):B;W%{\B*+}*
e# Base-convert to base 256
[{256md\}h;]W%
e# Format as a string literal with as few special cases as possible
:c'"\'"/"\\\""*'"
e# Decoder base-converts to base 256, then base B, unpairs, run-length decodes, and
e# inverse Burrows-Wheeler transforms
":i{\256*+}*{"B"md"P"mda\)*\}h;]e_:A,Ma*_,{A\.+$}*0=(;"I"cf+"

```
* `I` is the increment which must be added to each decoded value
* `P` is the base used to combine run-length with char
* `B` is the base used to convert the whole thing
> 3 votes

# Answer
## CJam, range reduction and base conversion

I think it's stupid to ban builtins for base-conversion as "compression", but I've implemented my own.

```
q
e# Reduce range by offsetting towards 0 as far as possible
:i_:e<:If-
e# Base-convert to the minimal possible base
_:e>):B;W%{\B*+}*
e# Base-convert to base 256
[{256md\}h;]W%
e# Format as a string literal with as few special cases as possible
:c'"\'"/"\\\""*'"
e# Decoder base-converts to base 256 and then base B, adding the offset
":i{\256*+}*{"B"md"I"c+\}h;"

```

The text is too small to benefit greatly from techniques which require a lot of decoding, but if we can subtract 32 from each byte and base-convert then we get an asymptotic improvement of at least 2.4%, and with luck the input source will be pure ASCII and we get an asymptotic improvement of about 18.7%. With an overhead of about 26 bytes we stand a decent chance of getting compression.

If the output is allowed to have a trailing NUL byte, one byte can be saved by removing that final `;`.
> 2 votes

# Answer
# Pyth, `length(input) + 1` bytes

```
+Nz

```

Online interpreter available here.

This will return a generated program of the form `"(input)`. Put another way, the main program prepends a double quote to the input text.

## Main Program Explanation

```
+      Concatenate
 N     " (the variable N defaults to a double quote mark)
  z    and the input

```

## Generated Program Explanation

```
"                start of a string
 (input)         the input text
        (eof)    strings are closed automatically at the end of file

```

This is the shortest of the "input length plus a constant" answers. I'm posting this mostly to set a bar for the non-trivial answers. It's unclear if a non-trivial answer can exist within the rules as they are currently worded, but I am setting this bar nonetheless.
> 1 votes

# Answer
# C++11, arithmetic coding, overhead \>= 382 bytes

Compression algorithm is shamelessly copied from Simple byte-aligned binary arithmetic coder by Fabian 'ryg' Giesen

```
#include <iostream>
using std::cout;
void pu(char c){c=='\r'?cout.write(")OMG\" \"\\r\" R\"OMG(",17):cout.put(c);}

int main() {
    uint32_t lo{0},hi{~0u},x,i,prob{256};
    char ch;

    cout<<R"!*(#include <iostream>
void operator ""_p(const char* q,size_t z){uint32_t d{0},l{0},h{~0u},p{256},x,t;size_t r{0},i;for(i=4;i-->0;)d=(d<<8)|q[r++];while(r<=z){char y{0};for(i=8;i-->0;){x=l+((uint64_t(h-l)*p)>>9);t=(d<=x);t?(h=x):(l=x+1);while((l^h)<(1u<<24)){d=(d<<8)|q[r++];l<<=8;h=(h<<8)|0xff;}p+=t?((512-p)>>5):-(p>>5);y+=y+t;}std::cout.put(y);}}int main(){R"OMG()!*";

    while (std::cin.get(ch)) {
        for (size_t b=8; b-->0;) {
            int bit{ch&(1<<b)};
            x = lo+((uint64_t(hi-lo)*prob)>>9);
            bit ? (hi=x) : (lo=x+1);
            while ((lo^hi)<(1u<<24)) {pu(lo>>24);lo<<=8;hi=(hi<<8)|0xff;}
            prob += bit?((512-prob)>>5):-(prob>>5);
        }
    }
    for (i=4;i-->0;) {pu(lo>>24);lo<<=8;}
    cout<<")OMG\"_p;return 0;}";

    return 0;
}

```

## Explanation

1. Main program reads the input and uses BinShiftModel to generate an encoded bitstream.
2. The bitstream is then included into a C++11 user-defined raw literal in the output program.
3. The literal is being processed by the user-defined function, `operator ""_p(const char* string, size_t size)`, printing out the decoded stream.

Some extra care was necessary due to all newline values being converted to `\n`.

## Improvement

The code does not look for different compression paths (there were, but some optimal value was chosen instead).

It is possible to improve the compression ratio, either by limiting input to 7 bits (did not do that because "em-dash" in the sample became corrupted) or by storing MSB from all input bytes first, which will likely be roughly same for 1/4 of the text.

Either way, algorithm overhead is huge on small texts.

## Usage

`g++ -std=c++11 -o golf golf.cpp && ./golf < sample.txt > degolf.cpp && g++ -std=c++11 -o degolf degolf.cpp && ./degolf`
> 1 votes

# Answer
## Lua

```
print('print"'..io.read()..'"')

```

Try it here.

Will always be `string length + 7` bytes long.

## C#

```
using System;
namespace H {
    class K {
        static string P;
        static void Main(string text)
        {
            P = text;
            Console.WriteLine("()=>{Console.WriteLine(H.K.P);}");
        }
    }
}

```

Works if the program itself is added as a dependency where you run the resulting output program. If you would to run the resulting code in a `OutputText.exe`, you will have to add `OutputCodeThatOutputsText.exe` as a dependency.

Resulting code is always `()=>{Console.WriteLine(H.K.P)}`.
> 0 votes

---
Tags: restricted-source, code-generation, metagolf
---


title: Fill the holes in letters

text:
# Question
Title: Fill the holes in letters
Sometimes when I'm bored, I take some text and fill the "holes" in the letters. But isn't filling the holes the most boring thing you can do? I think we should automate it, so we could use our time better.

Standard rules apply.

# Input

A string containing sequence of alphanumeric characters (a-z, A-Z, 0-9) and spaces.

# Output

Image containing string rendered and holes on it filled. You can use any human readable font as long as it still requires filling the holes. You can either save image to file `i.png` (in png format) or just display the image.

Image properties:

* Black text
* White or transparent background
* Padding:
    + The dimensions of the image can be maximum two times the dimensions of the text
    + Padding should be same color as background, either white or transparent

# Example

Input: `Example text`

Output:

# Answer
> 18 votes
## Bash, 135 bytes

```
convert +antialias -pointsize 99 label:$1 -fill red -draw 'color 0,0 floodfill' -fill black -opaque white -fill white -opaque red i.png

```

Uses ImageMagick (`convert`).

Sample output:

```
convert
  +antialias                              # disable antialiasing
  -pointsize 99                           # annoyingly necessary (see below)
  label:$1                                # draw input text
  -fill red -draw 'color 0,0 floodfill'   # flood fill from (0,0) with red
  -fill black -opaque white               # replace all white with black
  -fill white -opaque red                 # replace all red with white
  i.png

```

Disabling antialiasing is required because otherwise antialiased interior parts of the letters wouldn't flood fill. Setting the font to a large size is also required because some fonts have "gaps" in letters that should have "holes" in them at small font sizes (in my tests, the `a` wasn't filled at the default small font size).

# Answer
> 8 votes
## Mathematica, 83 bytes

```
ImageSubtract[s=Binarize@Rasterize@Style[#,FontSize->99],DeleteBorderComponents@s]&

```

An unnamed function that takes a string as input and returns an image object. The idea is to use `DeleteBorderComponents` to keep *only* the holes and then subtract those from the original image.

# Answer
> 5 votes
# SmileBASIC, 38 bytes

```
??INPUT S$GPUTCHR.,2,S$,2,2,8GPAINT.,0

```

Draws black\* text on the black background, then uses the built in "paint bucket" function to fill everything outside the text with white.
\*(actually I used `00000008`, which looks identical to transparent, but is treated as a different color)

# Answer
> 2 votes
Eats away at the text a bit, but there's also a canvas-based solution:

## JS, 610 bytes

```
function o(a,b){return a[b]+a[b+1]+a[b+2]}x=prompt();l=x.length;c=document.createElement("canvas");document.body.appendChild(c);h=33;w=18*l;c.height=h;c.width=w;n=255;m=764;t=c.getContext("2d");t.fillStyle="white";t.fillRect(0,0,w,h);t.fillStyle="red";t.fillRect(0,2,w,h);t.font="900 30px Courier";t.fillStyle="black";t.fillText(x,0,25);d=t.getImageData(0,0,w,h);f=0;q=d.data.length;for(i=0;i<20;i++){for(j=0;j<q;j+=4){f=d.data;if(o(f,j)>0&&(o(f,j-w*4)>m||o(f,j+w*4)>m||o(f,j-4)>m||o(f,j+4)>m)){f[j]=n;f[j+1]=n;f[j+2]=n}}}for(k=0;k<q;k+=4){f=d.data;if(f[k+1]<1){f[k]=0;f[k+1]=0;f[k+2]=0}}t.putImageData(d,0,0)

```

# Answer
> 2 votes
## Postscript 273

\[was originally posted to the related challenge, but I never implemented the counting.\]

Renders each character normally, to get the correct spacing to advance, then takes all the curves which describe the glyph and fills each one. Normally the interior and exterior curves are described with different orientations, so a fill will leave the interior empty, regardless of whether it's using the non-zero winding rule or even-odd rule. Filling separately, it all gets filled.

```
/Courier 9 selectfont
9 9 moveto{( ) dup 0 4 3 roll put currentpoint 3 2 roll
dup show currentpoint 3 2 roll 5 3 roll moveto
true charpath[[{/moveto
cvx}{/lineto cvx}{/curveto cvx}{/closepath cvx]cvx[}pathforall
pop]]{exec currentpoint fill moveto}forall pop moveto}forall

```

Indented:

```
/Courier 9 selectfont
9 9 moveto
{
    ( ) dup 0 4 3 roll put
    currentpoint 3 2 roll
    dup show
    currentpoint 3 2 roll
    5 3 roll moveto
    true charpath
    [ [{/moveto cvx}{/lineto cvx}{/curveto cvx}{/closepath cvx]cvx[}
       pathforall pop] ]
    { exec currentpoint fill moveto } forall
    pop moveto
} forall

```

Usage. String object is expected to be on the stack when the program starts. Extra scaling just to make it visible.

```
$ gs -c '7 7 scale(Example Text)' -f courier.ps

```

---
Tags: code-golf, graphical-output, image-processing
---


title: Shifty Eyes Shifting I's

text:
# Question
Title: Shifty Eyes Shifting I's
Shifty-eyes ASCII guys like to shift ASCII `Ii`'s:

```
>_> <_< >_< <_>

```

Given a string of shifty-guys, spaced apart or separate lines, shift the `Ii`'s side to side, left the wall and right the skies:

```
Ii

```

The shortest shifter wins the prize.

# Say What?

Write a program or function that takes in a string of an arbitrary list of these four ASCII emoticons, either space or newline separated (with an optional trailing newline):

```
>_>
<_<
>_<
<_>

```

> For example, the input might be
>
> ```
> >_> >_> <_>
>
> ```
>
> or
>
> ```
> >_>
> >_>
> <_>
>
> ```
>
> (The method you support is up to you.)

Each emoticon performs a different action on the `I` and `i` characters, which always start like this:

```
Ii

```
* `>_>` shifts `I` to the right by one, if possible, and then shifts `i` to the right by one.
* `<_<` shifts `I` to the left by one, if possible, and then shifts `i` to the left by one, if possible.
* `>_<` shifts `I` to the right by one, if possible, and then shifts `i` to the left by one, if possible.
* `<_>` shifts `I` to the left by one, if possible, and then shifts `i` to the right by one.

`I` cannot be shifted left if it is at the left edge of the line (as it is initially), and cannot be shifted right if `i` is directly to its right (as it is initially).

`i` cannot be shifted left if `I` is directly to its left (as it is initially), but can always be shifted right.

Note that with these rules, `I` will always remain to the left of `i`, and `I` is attempted to be shifted before `i` for all emoticons.

Your program or function needs to print or return a string of the final `Ii` line after applying all the shifts in the order given, using spaces () or periods (`.`) for empty space. Trailing spaces or periods and a single trailing newline are optionally allowed in the output. Don't mix spaces and periods.

> For example, the input
>
> ```
> >_>
> >_>
> <_>
>
> ```
>
> has output
>
> ```
> I...i
>
> ```
>
> because the shifts apply like
>
> ```
> start  |Ii
> >_>    |I.i
> >_>    |.I.i
> <_>    |I...i
>
> ```

**The shortest code in bytes wins.** Tiebreaker is higher voted answer.

# Test Cases

```
#[id number]
[space separated input]
[output]

```

Using `.` for clarity.

```
#0
[empty string]
Ii

#1
>_>
I.i

#2
<_<
Ii

#3
>_<
Ii

#4
<_>
I.i

#5
>_> >_>
.I.i

#6
>_> <_<
Ii

#7
>_> >_<
.Ii

#8
>_> <_>
I..i

#9
<_< >_>
I.i

#10
<_< <_<
Ii

#11
<_< >_<
Ii

#12
<_< <_>
I.i

#13
>_< >_>
I.i

#14
>_< <_<
Ii

#15
>_< >_<
Ii

#16
>_< <_>
I.i

#17
<_> >_>
.I.i

#18
<_> <_<
Ii

#19
<_> >_<
.Ii

#20
<_> <_>
I..i

#21
>_> >_> <_>
I...i

#22
<_> >_> >_> >_> <_> <_<
.I...i

#23
<_> >_> >_> >_> <_> <_< >_< <_< >_<
..Ii

#24
>_> >_< >_> >_> >_> >_> >_> >_> <_> <_> <_<
...I.....i

```

# Answer
> 3 votes
## CJam, 33 bytes

```
0Xq2%{'=-_3$+[2$W]-,*@+}/S*'i+'It

```

Uses the same algorithm as my Python answer, except with 0-indexing. Essentially:

* Only look at the arrows in the input, converting `<` to -1 and `>` to 1
* Only apply an update if it doesn't move us to position -1 and doesn't move us to the position of the other char
* Since the arrows alternate between applying to `I` and applying to `i`, we alternate which position we update after each arrow

Thanks to @MartinBüttner for golfing the output step, taking off 5 bytes.

Try it online | Test suite

```
0X                 Initialise the two positions a = 0, b = 1
q2%                Read input and take every second char, leaving just the arrows

{ ... }/           For each arrow in the input...
  '=-              Subtract '=, leaving -1 for '< and 1 for '>
  _3$+             Duplicate and add a. Stack looks like [a b diff a+diff]
  [2$W]-           Perform setwise subtraction, [a+diff] - [b -1]
                   The result is empty list if a+diff is either b or -1, else [a+diff]
  ,                Length, yielding 0 or 1 respectively
                   0 means we don't want to update the char, 1 means we do
  *                Multiply diff by this result
  @+               Add to a. Stack now looks like [b a'] where a' is a updated

                   After the above loop, the stack ends with [(I position) (i position)]

S*                 Create (i position) many spaces
'i+                Stick an 'i at the end - this is the right place due to 0-indexing
'It                Set (I position) to 'I

```

# Answer
> 20 votes
# Perl, ~~59~~ ~~56~~ 54 bytes

Includes +1 for `-p`

Run with the input on STDIN, e.g. `perl -p shifty.pl <<< ">_> <_< >_< <_>"`

`shifty.pl`:

```
s%^|<|(>)%y/iI/Ii/or$_=Ii;$1?s/i |i$/ i/:s/ i/i /%reg

```

## Explanation

The control string alternates instructions for `i` and `I` and the rule is the same for both of them if you formulate them as:

* `<` Move left if there is a space to the left
* `>` Move right if there is a space or end of string to the right

So I'm going to swap `i` and `I` in the target string at each step so I only need to apply the rule to one letter ever. This is the `y/iI/Ii/`

I will walk the control string looking for `<` and `>` using a substitution which is usually the shortest way in perl to process something character by character. To avoid having to write `$var =~` I want the control string in the perl default variable `$_`. And I also want an easy way to distinguish `<` from `>`. All this can be accomplished using

```
s%<|(>)%  code using $1 to distinguish < from > %eg

```

The target string I also want to manipulate using substitutions and for the same reason I want that in `$_` too. `$_` being two things at once seems impossible.

However I can have my cake and eat it too because the `$_` inside the body of a substitution does not have to remain the same as the `$_` being substituded. Once perl started substituting a string this string will not change even if you change the variable the string originally came from. So you can do something like:

```
s%<|(>)% change $_ here without disturbing the running substitution %eg

```

I want to replace the original `$_` by the initial `"Ii"` only the very first time the substitution body gets executed (otherwise I keep resetting the target string). This replacement however also has to happen for an empty control string, so even for the empty control string the body needs to be executed at least once. To make sure the substition runs an extra time at the start of the control string (even for empty control strings) I change the substitution to:

```
s%^|<|(>)% change $_ here without disturbing the running substitution %eg

```

I will run the `y/iI/Ii/` as the first thing inside the substitution code. While `$_` is still the control string this won't yet contain any `Ii`, so if the transliteration indicates nothing was changed that is my trigger initialize `$_`:

```
y/iI/Ii/or$_=Ii

```

Now I can implement the actual moving of the letters. Since I start with a swap all moves should be done on `i`, not `I`. If `$1` is set move `i` to the right:

```
s/i |i$/ i/

```

If `$1` is not set move `i` to the left

```
s/ i/i /

```

Notice that at the start of the control string when I match `^` `$1` will not be set, so it tries to move `i` to the left on the initial string `Ii`. This won't work because there is no space there, so the intial string remains undisturbed (this is why I put the `()` around `>` instead of `<`)

Only one problem remains: at the end of the outer substitution `$_` is set to result of the outer substitution regardless of what you did to `$_` inside the substitution body. So the target string with the proper placement of `i` and `I` gets lost. In older perls this would be a fatal flaw. More recent perls however have the `r` modifier which means "make a copy of the original string, do your substitution on that and return the resulting string (instead of number of matches)". When I use that here the result is that the modified command string gets discarded while the original `$_` is not disturbed by perl and left after the substitution. However the disturbing **I** do on `$_` is still done after perl left `$_` alone. So at the end `$_` will be the proper target string.

The `-p` option makes sure the original string is in `$_` and also prints the final `$_`.

# Answer
> 10 votes
## LittleLua \- 178 Bytes

```
r()l=sw(I)o=1 D='.'f q=1,#l do i l[q]:s(1,1)=='>'t i z+1~=o t z=z+1 e else i z-1>0 t z=z-1 e e i l[q]:s(3)=='>'t o=o+1 else i o-1~=z t o=o-1 e e e p(D:r(z).."I"..D:r(o-z-1)..'i')

```

Straight forward implementation.

Ungolfed:

```
r()                             --call for input
l=sw(I)                         --Split input by spaces
o=1                             --Hold i position (z holds I position)
D='.'                           --Redundant character
f q=1,#l do                     --Foreach table entry
    i l[q]:s(1,1)=='>' t        --If the first eye points right
        i z+1~=o t z=z+1 e      --Verify no collision and move the I
    else
        i z-1>0 t z=z-1 e       --If it points left.. .same...
    e                           --yatta yatta...
    i l[q]:s(3)=='>' t
        o=o+1
    else
        i o-1~=z t o=o-1 e
    e
e
p(D:r(z).."I"..D:r(o-z-1)..'i')--String repeats to print correct characters.

```

**What is LittleLua?**

LittleLua is a work in progress to try to level the playing fields between my language of choice for these challenges and esoteric languages that often have extremely powerful built-ins.

LittleLua is a Lua 5.3.6 interpreter with an additional module (LittleLua.Lua), as well as function and module names shrunk. These changes will expand over the next day or two, until I'm happy, but as it stands several of the largest changes between LittleLua and a the standard Lua interpreter are:

**Functions and modules are shrunk:**

```
io.read() -> r() (Value stored in built in variable "I")
string -> s
string.sub -> s.s or stringvalue:s
etc.

```

**Built in variables**

LittleLua has several built in variables to shrink some tasks:

```
z=0
o=10
h1="Hello, World!"
h2="Hello, World"
h3="hello, world"
h4=hello, world!"
etc.

```

**Built in Functions**

Currently a depressingly small list, but here it is:

```
d(N) -> Prints NxN identity matrix
sw(str) -> Splits string at spaces and returns table of results
sc(str) -> Splits string at commas and returns table of results
sd(str) -> Removes white space from a string (not including tabs)
ss(str,n) -> Swap N characters from beginning and end of string
sr(str,n) -> Swap N characters from beginning and end of string retaining order
sd(str) -> Split string into array of characters
co(ta) -> Concatenate table with no delimiter
co(ta, delim) -> Concatenate table with delimiter: delim

```

# Answer
> 8 votes
# Retina, ~~101~~ 86

```
$
¶Ii
(`^¶

s`^>(.*)I( )?
$1$2I
s`^<(.*?)( )?I
$1I$2
s`^_>(.*)i
$1 i
s`^_<(.*?) ?i
$1i

```

Try it online

Saved 15 bytes thanks to daavko!

Takes input separated by newlines and outputs with the eyes separated by spaces.

### Explanation:

I will explain stage by stage as usual. All of these stages are in Retina's Replace mode. That means the first line is a regular expression and the second line is a replacement string.

```
$
¶Ii

```

Add the initial `Ii` to the end of the input.

```
(`^¶

```

The backtick separates the stage from the options. The option character `(` indicates that this stage is the start of a loop of stages to be executed repeatedly in order until a full cycle is completed without changing the input. Since this open parenthesis is never closed, all of the remaining stages are a part of this loop.

The actual stage is very simple, if the first character of the string is a newline then delete it. This is just to help make handling the empty input easier, otherwise it'd be golfier to add it on to the two last stages.

```
s`^>(.*)I( )?
$1$2I

```

Here, the option `s` causes the Regex metacharacter `.` to match newlines. This stage causes a leading `>` to match the `I` followed by an optional space. Then it replaces that match with the stuff after the `>`, followed by the optional space (so the empty string if the space couldn't be matched), and then the `I`.

```
s`^<(.*?)( )?I
$1I$2

```

This stage is very similar to the previous one, only the optional space is before the `I`, and the order and eye are reversed.

```
s`^_>(.*)i
$1 i

```

The handling of `i` is actually often simpler, because we don't have to worry about optionally adding or removing as `i` can always move right. For the `i` cases we match away the underscore as well as the greater/less than sign, but otherwise do similar logic. This one adds a space before the `i`.

```
s`^_<(.*?) ?i
$1i

```

Again similar to the above, but it deletes the character before the `i` if that character is a space, otherwise it only removes the emoticon.

# Answer
> 6 votes
# Javascript (ES6) 176 171 168 155 148 147 142 141 bytes

```
//v8 - I was sure saving off math was saving a byte, thanks ETF
_=>_.split` `.map(m=>(I=m<'='?I-1||0:Math.min(i-1,I+1))+(i=m[2]=='<'?Math.max(I+1,i-1):i+1),i=1,I=0)&&'.'.repeat(I)+'I'+'.'.repeat(--i-I)+'i'

//v7 - not checking first char when I can check whole string - changed how I create end string (stolen from edc65)
_=>_.split` `.map(m=>(I=m<'='?I-1||0:M.min(i-1,I+1))+(i=m[2]=='<'?M.max(I+1,i-1):i+1),i=1,I=0,M=Math)&&'.'.repeat(I)+'I'+'.'.repeat(--i-I)+'i'

//v6 - one more byte
_=>_.split` `.map(m=>(I=m[0]=='<'?M(0,I-1):Math.min(i-1,I+1))+(i=m[2]=='<'?M(I+1,i-1):i+1),i=1,I=0,M=Math.max)+((a=Array(i))[I]='I')&&a.join`.`+'i'

//v5 - not filling array with '.', just joining with . later
_=>_.split` `.map(m=>(I=m[0]=='<'?M(0,I-1):Math.min(i-1,I+1))+(i=m[2]=='<'?M(I+1,i-1):i+1),i=1,I=0,M=Math.max)&&((a=Array(i))[I]='I')&&a.join`.`+'i'

//v4 - realized I didn't need to split >_> on _, just use the 0th and 2nd index
_=>_.split` `.map(m=>(I=m[0]=='<'?M(0,I-1):Math.min(i-1,I+1))+(i=m[2]=='<'?M(I+1,i-1):i+1),i=1,I=0,M=Math.max)&&((a=Array(i).fill`.`)[I]='I')&&a.join``+'i'

//v3 - saving Math to a var (thanks @Verzio)
_=>_.split` `.map(m=>(I=(m=m.split`_`)[0]=='<'?M(0,I-1):Math.min(i-1,I+1))+(i=m[1]=='<'?M(I+1,i-1):i+1),i=1,I=0,M=Math.max)&&((a=Array(i).fill`.`)[I]='I')&&a.join``+'i'

//v2 - as a single expression! (thanks @Downgoat)
_=>_.split` `.map(m=>(I=(m=m.split`_`)[0]=='<'?Math.max(0,I-1):Math.min(i-1,I+1))+(i=m[1]=='<'?Math.max(I+1,i-1):i+1),i=1,I=0)&&((a=Array(i).fill`.`)[I]='I')&&a.join``+'i'

//version 1
_=>{I=0;i=1;_.split` `.map(m=>(I=(m=m.split`_`)[0]=='<'?Math.max(0,I-1):Math.min(i-1,I+1))+(i=m[1]=='<'?Math.max(I+1,i-1):i+1));(a=Array(i).fill`.`)[I]='I';return a.join``+'i'}

```

Usage

```
f=_=>_.split` `.map(m=>(I=m<'='?I-1||0:Math.min(i-1,I+1))+(i=m[2]=='<'?Math.max(I+1,i-1):i+1),i=1,I=0)&&'.'.repeat(I)+'I'+'.'.repeat(--i-I)+'i'

f(">_> >_< >_> >_> >_> >_> >_> >_> <_> <_> <_<")
//"...I.....i"

```

Degolfed (v6, v7 isn't much different)

```
//my solution has changed slightly, but not significantly enough to redo the below

_=>                   //take an input
  _.split` `          //split to each command <_<
   .map(              //do something for each command (each command being called m)
     m=>
       (I=            //set I to.... 'I will be the index of the letter I'
         m[0]=='<'?   //is the first char of the command '<'?
           Math.max(0,I-1)   //yes => move I to the left (but don't move past 0)
           :
           Math.min(i-1,I+1)  //no => move I to the right one, but keep it one less than i
       )

       +              //also we need to mess with i
       (i=
        m[2]=='<'?    //is the 3rd char of the command '<'?
          Math.max(I+1,i-1)  //yes => move i to the left, but keep it one right of I
          :
          i+1         //move i to the right (no bounds on how far right i can go)
       )

       ,i=1,I=0       //set I to 0 and i to 1 initially
     )
   +                  //this just lets us chain commands into one expression, not really adding
   (
    (a=Array(i))[I]='I') //create an array of length i (will be one shorter than we really need)
                         //set element I to 'I'

   &&                    //last chained command, we know the array creation will be true
                         //so javascript will just output the next thing as the return for the function
   a.join`.`+'i'         //join the array with '.' (into a string) and append i
                         //i will always be the last element

```

# Answer
> 6 votes
# MATL, ~~56~~ ~~55~~ ~~50~~ ~~49~~ 47 bytes

```
1Hj3\q4ZC"w@1)+lhX>yqhX<w@3)+yQhX>]tZ"105b(73b(

```

**Try it online!**

```
1           % push 1: initial position of 'I'
H           % push 2: initial position of 'i'
j           % take input as a string
4\q         % modulo 3 and subtract 1: this gives -1 for '<', 1 for '>'
4Zc         % arrange blocks of length 4 as columns of 2D array. This pads last
            % block with a zero (because the separating space won't be there).
            % Only first and third and last rows will be used
"           % for each column
  w         %   swap: move position of 'I' to top of stack
  @1)       %   first number (+/-1) of current column: tells where the 'I' moves
  +         %   add
  lhX>      %   max with 1: 'I' cannot move left past position 1
  y         %   duplicate position of 'i'
  qhX<      %   max with that number minus 1: 'I' cannot collide with 'i'
  w         %   swap: move position of 'i' to top of stack
  @3)       %   last number (+/-1) of current column: tells where the 'i' moves
  +         %   add
  y         %   duplicate position of 'I'
  QhX>      %   max with that number plus 1: 'i' cannot collide with 'I'
]           % end for each
t           % duplicate position of 'I'. This is the output string length
Z"          % string with that many spaces
105b(       % set 'i' at its computed position in that string
73b(        % set 'I' at its computed position in that string

```

# Answer
> 6 votes
## Python, ~~142~~ ~~141~~ ~~134~~ ~~122~~ 121 bytes

Saved 19 bytes thanks to xnor.

```
def f(l,I=0,i=1):
    for a,_,b in l.split():I-=[I>0,-(i!=I+1)][a>'='];i-=[i!=I+1,-1][b>'=']
    return'.'*I+'I'+'.'*(i+~I)+'i'

```

Example:

```
>>> assert f('<_> >_> >_> >_> <_> <_<') == '.I...i'
>>>

```

Explanation:

```
def f(l, I=0, i=1):
    for a, _, b in l.split():
        I-= -(i!=I+1) if a == '>' else I > 0
        i-= -1 if b == '>' else i!=I+1

    return '.'*I + 'I' + '.'*(i-I-1) + 'i'

```

# Answer
> 6 votes
# GNU sed, 81 bytes

(including +1 for `-r` flag)

```
#!/bin/sed -rf
s!<!s/ I/I /;!g
s!>!s/I / I/;!g
s!_(.{9})!\L\1!g
s!i !i!g
s/.*/echo Ii|sed '&'/e

```

This creates a new sed program from the input (which you can see by removing the last line), and applies it to the start state `Ii`.

## Explanation

* The first two lines convert `<` and `>` to 'substitute' commands that shift `I` left and right respectively.
* Then we change the one following `_` to work on `i` rather than `I`
* `i` is not bounded by any right-hand edge, so don't add or consume space following it
* Finally, apply the created command to the input `Ii`. `s///e` always uses `/bin/sh` as its shell, so I couldn't shorten this to `sed '&'<<<Ii` as I wanted (that's a Bash redirection syntax).

## Test results

```
$ for i in '' '>_>' '<_<' '>_<' '<_>' '>_> >_>' '>_> <_<' '>_> >_<' '>_> <_>' '<_< >_>' '<_< <_<' '<_< >_<' '<_< <_>' '>_< >_>' '>_< <_<' '>_< >_<' '>_< <_>' '<_> >_>' '<_> <_<' '<_> >_<' '<_> <_>' '>_> >_> <_>' '<_> >_> >_> >_> <_> <_<' '<_> >_> >_> >_> <_> <_< >_< <_< >_<' '>_> >_< >_> >_> >_> >_> >_> >_> <_> <_> <_<'
> do printf '%s => ' "$i"; ./74719.sed <<<"$i" | tr \  .; done | cat -n
     1   => Ii
     2  >_> => I.i
     3  <_< => Ii
     4  >_< => Ii
     5  <_> => I.i
     6  >_> >_> => .I.i
     7  >_> <_< => Ii
     8  >_> >_< => .Ii
     9  >_> <_> => I..i
    10  <_< >_> => I.i
    11  <_< <_< => Ii
    12  <_< >_< => Ii
    13  <_< <_> => I.i
    14  >_< >_> => I.i
    15  >_< <_< => Ii
    16  >_< >_< => Ii
    17  >_< <_> => I.i
    18  <_> >_> => .I.i
    19  <_> <_< => Ii
    20  <_> >_< => .Ii
    21  <_> <_> => I..i
    22  >_> >_> <_> => I...i
    23  <_> >_> >_> >_> <_> <_< => .I...i
    24  <_> >_> >_> >_> <_> <_< >_< <_< >_< => ..Ii
    25  >_> >_< >_> >_> >_> >_> >_> >_> <_> <_> <_< => ...I.....i

```

# Answer
> 5 votes
# Retina, ~~91~~ 86 bytes

I probably didn't take the best approach, so it can probably be golfed more. And no, I did not copy FryAmTheEggman (I know they're really similar in our approaches). I didn't even see his answer until after I posted mine.

```
$
¶Ii
(`^¶

sr`^<_(.*)( |)I
$1I$2
s`^>_(.*)I( ?)
$1$2I
sr`^<(.*) ?i
$1i
s`^>(.*)i
$1 i

```

**Try it online**

# Answer
> 4 votes
## Javascript (ES6) 166 bytes

Using Charlie Wynn's answer, I managed to save 10 bytes by defining Math.max as M and calling M each time his script uses

```
_=>{I=0;i=1;_.split` `.map(m=>(I=(m=m.split`_`)[0]=='<'?M=Math.max;M(0,I-1):M(i-1,I+1))+(i=m[1]=='<'?M(I+1,i-1):i+1));(a=Array(i).fill`.`)[I]='I';return a.join``+'i'}

```

(I didn't write this golf, Charlie Wynn did here. I merely modified it to make it shorter)

# Answer
> 3 votes
# JavaScript (ES6), 115 ~~118~~

**Edit:** 3 bytes saved thx CharlieWynn

```
a=>a.split` `.map(x=>x[x>'='?q&&(--q,++p):p&&(--p,++q),2]>'='?++q:q&&--q,p=q=0)&&'.'.repeat(p)+`I${'.'.repeat(q)}i`

```

`p` is the number of spaces before `I`; `q` is the number of spaces between `I` and `i`. Neither can be negative.

**Less golfed**

```
a=>(
  a.split(' ').map( x=> (
    x>'='?q&&(--q,++p):p&&(--p,++q), // try to move I based on 1st char of x
    x[2]>'='?++q:q&&--q // try to move i based on 3rd char of x
  )
  , p=q=0), // starting values of p and q
  '.'.repeat(p)+'I' + '.'.repeat(q) +'i' // return value
)

```

**Test**

```
f=a=>a.split` `.map(x=>x[x>'='?q&&(--q,++p):p&&(--p,++q),2]>'='?++q:q&&--q,p=q=0)&&'.'.repeat(p)+`I${'.'.repeat(q)}i`

console.log=x=>O.textContent+=x+'\n'

;[['','Ii'],
['>_>','I.i'],
['<_<','Ii'],
['>_<','Ii'],
['<_>','I.i'],
['>_> >_>','.I.i'],
['>_> <_<','Ii'],
['>_> >_<','.Ii'],
['>_> <_>','I..i'],
['<_< >_>','I.i'],
['<_< <_<','Ii'],
['<_< >_<','Ii'],
['<_< <_>','I.i'],
['>_< >_>','I.i'],
['>_< <_<','Ii'],
['>_< >_<','Ii'],
['>_< <_>','I.i'],
['<_> >_>','.I.i'],
['<_> <_<','Ii'],
['<_> >_<','.Ii'],
['<_> <_>','I..i'],
['>_> >_> <_>','I...i'],
['<_> >_> >_> >_> <_> <_<','.I...i'],
['<_> >_> >_> >_> <_> <_< >_< <_< >_<','..Ii'],
['>_> >_< >_> >_> >_> >_> >_> >_> <_> <_> <_<','...I.....i']]
.forEach(t=>{
  var i=t[0],k=t[1],r=f(i)
  console.log(i +' -> '+r + (r==k?' OK':' KO (exp '+k+')'))
})
```

```
<pre id=O></pre>
```

# Answer
> 3 votes
# Retina, ~~61~~ 58 bytes

*3 bytes saved thanks to @FryAmTheEggman.*

```
^
Ii
(`( ?)I(.*i) <|I( ?)(.*i) >
$3I$1$2$4
 ?i_<
i
i_>
 i

```

Explanation comes a bit later.

Try it online!

Modified code with batch test.

# Answer
> 2 votes
## Python 2, ~~96~~ 92 bytes

```
f=lambda s,I=1,i=2:s and f(s[2:],i,I+cmp(s,'=')*(0<I+cmp(s,'=')!=i))or'%*c'*2%(I,73,i-I,105)

```

Pretty shifty-looking solution for a shifty challenge. Input like `f('>_> <_>')`, output like `'I i'`.

Verification program (assuming `tests` is the multiline test case string):

```
for test in zip(*[iter(tests.replace("[empty string]", "").splitlines())]*4):
    assert f(test[1]) == test[2].replace('.',' ')

```

The program reads each arrow one at a time, starting with `I=1, i=2` and using 1-based indices. The variable names are a tad misleading since they swap roles - after every char, `I` becomes `i` and `i` becomes `I` updated. A char is only updated if it would move to neither the position of the other char nor position 0.

For example, for `>_> <_> >_<` we do:

```
Char     I (= i from previous iteration)        i
-----------------------------------------------------------------------------------------
         1                                      2
>        2                                      1+1 = 2 would overlap, so remain 1
>        1                                      2+1 = 3
<        3                                      1-1 = 0 is too low, so remain 1
>        1                                      3+1 = 4
>        4                                      1+1 = 2
<        2                                      4-1 = 3

```

This gives `' Ii'` as desired.

# Answer
> 0 votes
## Lua, 104 bytes

```
s='Ii'for v in(...):gmatch'%S_?'do
s=s:gsub(('>i$ i< ii>_I  I<_ II '):match(v..'(..)(%P+)'))end
print(s)

```

Usage:

```
$ lua shifter.lua "<_> >_> >_> >_> <_> <_<"
 I   i

```

# Answer
> 0 votes
## Javascript (ES5), ~~153~~ 125 bytes

takes an input by setting a variable `a` before running

```
I=i=0;for(b of a.split(" "))b[0]==">"?i!=I&&I++:I>0&&I--,b[2]==">"?i++:I!=i&&i--;r=Array(i).fill(".");r[I]="I";r.join("")+"i"

```

Somewhat ungolfed:

```
I=i=0;
for(b of a.split(" "))
   b[0]==">"
       ? i!=I && I++
       : I>0 && I--,
   b[2]==">"
       ? i++
       : I!=i && i--
;
r=Array(i).fill(".");
r[I]="I";
r.join("")+"i"

```

# Answer
> 0 votes
## Mathematica, 125 bytes

```
Fold[StringReplace,"Ii",StringCases[#,"<_"|">_"|">"|"<"]/.{"<_"->".I"->"I.",">_"->"I."->".I","<"->".i"->"i",">"->"i"->".i"}]&

```

Pure function with first argument `#`. The idea is that each `<_`, `>_`, `<`, and `>` in the input corresponds to a string replacement rule. `"<_"|">_"|">"|"<"` is a string pattern that matches any of those four expressions. `StringCases[#,"<_"|">_"|">"|"<"]` will find all such matches. Then we replace (`/.`) each `"<_"` with the string replacement rule `".I"->"I."`, each `">_"` with the rule `"I."->".I"`, and so forth. Then I want to sequentially apply each replacement rule to the string `"Ii"`, but `StringReplace` will only look for matches in the parts of the string which have not been replaced, so we left `Fold` the function `StringReplace` over the list of replacement rules with starting value `"Ii"`.

Perhaps it would be clearer with an example (here `%` refers to the previous cell's output):

---
Tags: code-golf, string, ascii-art
---


title: Tell me I'm pretty!

text:
# Question
Title: Tell me I'm pretty!
I only very recently discovered code golf and just found this part of the Stackexchange network, and naturally after looking at so many clever answers, I feel inferior. Inner me knows I'll get better over time, but inner me is also vain and needs validation.

At the same time, I don't take kindly to pandering, so you'd **better** not write me a program that looks like it took 15 seconds. You have to *mean* it.

# Goal:

Print the phrase "you're pretty!" or write a function that returns that string. All letters can be upper-case or lower-case, but the punctuation and the spacing must be the same.

# How to mean it:

If you're sensitive and can sympathize with all the emotions associated with feeling like a noobie, you should aim to make your program look like it does something entirely different and innocuous. I like to be surprised :) You may achieve this by not using any of the alphabetical characters in "you're pretty".

Winner is decided by shortest byte count. -5 bytes for each positive or neutral adjective you extend the phrase by, i.e. "you're pretty and effulgent and green", up to a possible 20 byte reduction.

# Answer
# Jelly, ~~29~~ 28 - 20 = ~~9~~ 8 points

```
“+vẇSȮv¿⁷“ñż“ÞỌ“Ḋ;“ʠK»j“ and

```

Try it online!

The bonus turns out to be just *marginally* worth it for Jelly: `“+vẇSȮv¿⁷»` (the compressed representation of `you're pretty`) is 10 bytes. (Now with another byte saved per @ConorOBrien; I'd forgotten that as the final `and` is uncompressed, it wouldn't need a trailing delimeter.)

## Explanation

```
“+vẇSȮv¿⁷“ñż“ÞỌ“Ḋ;“ʠK»j“ and
“+vẇSȮv¿⁷“ñż“ÞỌ“Ḋ;“ʠK»        ["you're pretty"," airy"," agile"," calm"," brave"]
                      j       join with
                       “ and  " and"

```

This is pretty much just a case of using Jelly's built-in string compression. Picking adjectives that come near the start of the alphabet makes it slightly shorter than it would be otherwise.

Incidentally, this program would be quite a bit shorter if Jelly's dictionary were more complete. It has plenty of obscure words in, but for some reason is missing `and` (likely because it's only three letters long and thus doesn't gain much from the compression, but it'd benefit from being included in the dictionary for when it's used as part of a longer string, because `“¡ÞṄɱ»` is longer than just writing out the word would be).
> 3 votes

# Answer
# Japt, 10 bytes

```
`YŒ'œ pÎ5y

```

Japt uses the shoco library for string compresstion. Backticks are used to decompress strings.

Try it online!
> 2 votes

---
Tags: code-golf
---


title: Is today a real weekday?

text:
# Question
Title: Is today a real weekday?
Feb. 6 was a real weekday. Because it lies in the 6th week of the year. So a real weekday is a day with a a day number that equals the week number.

But not all country have the same counting of weeks. in Germany a week starts with Monday and ends on Saturday in the US they start on Sunday.

Write a program that checks a given date (the format your program likes the best) and a weekstart ('S' or 'M') whether it is a real weekday.

Too simplify things a bit we assume January 1st is always a real weekday because it is in the first week. In Germany it is the last day of week 52)

Some examples of real weekday for a start on Monday:

```
 2017-01-01
 2017-02-07
 2017-04-17

```

Some examples of real weekday for a start on Sunday:

```
2017-01-01
2017-02-06
2017-04-16

```

Example:

```
2017-04-16 S Output: YES
20170416M Output: 0

```

How you enter the Date does not matter, as long as it is human readable. The start day can be given by M or S or 1 or 0. the Output is a printed boolean Yes, not or Y,N or 0,1

Shortest code wins!

Its my first question I put on this forum, so I'd be happy to hear some comments.

# Answer
# MATLAB, 53 bytes

```
d=datetime(input(''));week(d-(input('')=='M'))==d.Day

```

This answer accepts the first input as a string `'2017-02-06'` and the second input as a string (either `'S'` or `'M'`).

It constructs a `datetime` object from the first input and saves it in `d`. We then compute the week number (but first we subtract 1 day from the date if the second input is an `'M'` since `week` uses Sundays by default) and then we compare this week number to the day of the `datetime` object to yield a boolean.
> 0 votes

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


title: Output a sound of a certain frequency

text:
# Question
Title: Output a sound of a certain frequency
This is a rather simple challenge, but I couldn't find any question that was really similar to it. The challenge is to take a frequency in using STDIN or an equivalent, and then output a tone that matches that frequency, in Hz, for 5 seconds. For example

```
Input: 400
Output: (a tone of 400 Hz with a duration of 5 seconds)

```

## Rules

* Input must be taken in through STDIN, or your language's equivalent
* The answer must be a full program
* Builtins may be used
* The frequency will be anywhere from 50 - 5000 Hz
* The output must be played for 5 seconds
* The output must be in the form of a sine wave

## Test cases

Input: `440`

Output:

Input: `200`

Output:

Input: `4000`

Output:

---

* This is not about finding the language with the shortest solution for this (there are some where the empty program does the trick) - this is about finding the shortest solution in *every* language. Therefore, no answer will be marked as accepted.
* Unlike our usual rules, feel free to use a language (or language version) even if it's newer than this challenge. Languages specifically written to submit a 0-byte answer to this challenge are fair game but not particularly interesting.

Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language.

Also note that languages *do* have to fullfil our usual criteria for programming languages.

---

## Catalogue

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

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

```
## Language Name, N bytes

```

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

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

```

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

```
## Perl, 43 + 2 (-p flag) = 45 bytes

```

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

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

```

```
<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 63967; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 39060; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "//api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "//api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(42), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>
```

# Answer
> 12 votes
# QBasic, ~~18 bytes~~ (disqualified)

Like @pabouk mentioned, this uses the PC speaker, so it plays a *square* wave, not a sine wave like the problem asks. (This requirement was added to the problem *after* this answer was posted, hence the votes.) I'll leave it here for posterity anyway.

---

```
INPUT F
SOUND F,91

```

Play a sound at the inputted frequency for 91 ticks, which is equal to 5 seconds.

# Answer
> 11 votes
# Python2, 40 bytes

```
from winsound import*
Beep(input(),5000)

```

Only works on Windows.

# Answer
> 9 votes
## Mathematica, 42 bytes

Well if we can use built-ins...

```
Input[]
EmitSound@Play[Sin[2t%Pi],{t,0,5}]

```

Thanks to the requirement for a full program, this was the first time I got to use my recently discovered golfing tip of using `%` (result of last evaluation) to save two bytes.

Mathematica also has a built-in `Sound` which takes a pitch and a duration as arguments, but unfortunately the pitch has to be given as a musical note. Specifying your own sound wave via `Play` seems to be the only way to work with a frequency.

# Answer
> 7 votes
## MATLAB, 36 bytes

```
sound(sin(pi*input('')*(0:8^-4:10)))

```

Thanks to flawr for saving two bytes.

# Answer
> 6 votes
# C#, 80 bytes

```
class P{static void Main(string[]a){System.Console.Beep(int.Parse(a[0]),5000);}}

```

# Answer
> 6 votes
## PowerShell, 32 bytes

```
[console]::beep((read-host),5kb)

```

# Answer
> 4 votes
# FakeASM, 12 bytes

```
RDA
BEEP 5e3

```

Works with the Windows reference implementation (download). It calls Windows' `Beep` function, which is a sine wave on modern platforms.

# Answer
> 4 votes
# Bash + X11, ~~27~~ 20 bytes

```
xset b 9 $1 5;echo

```

This contains an unprintable, so here's a hexdump:

```
0000000: 7873 6574 2062 2039 2024 3120 353b 6563  xset b 9 $1 5;ec
0000010: 686f 2007                                ho .

```

This takes the frequency as a command-line argument and plays the appropriate beep at a volume of 9% (since no volume was specified).

(Note: I was unable to test this due to some issues with my computer, but I'm 99% sure it works.)

# Answer
> 4 votes
# Bash + Linux utils, 95

```
bc -l<<<"obase=16;for(;t<5;t+=1/8000){a=s($1*t*6.3);scale=0;a*30/1+99;scale=9}"|xxd -p -r|aplay

```

This is a true sine wave. No beeps. Input frequency entered via the command-line:

```
./hz.sh 440

```

# Answer
> 3 votes
## VB.net, 90 bytes, 74 bytes

```
Module m
Sub Main(a() as String)
Console.Beep(a(0),5000)
End Sub
End Module

```

Thanks to Sehnsucht

```
Module m
Sub Main()
Console.Beep(My.Application.CommandLineArgs.First,5000)
End Sub
End Module

```

This is my first post so if I did any thing wrong please let me know

# Answer
> 3 votes
## JavaScript, 114 bytes

```
p=prompt();c=new AudioContext;with(c.createOscillator()){frequency.value=p;connect(c.destination);start();stop(5)}

```

Requires a somewhat cutting-edge browser, enter the frequency in the prompt. JSFiddle

# Answer
> 3 votes
# Processing, ~~148~~ ~~114~~ 106 bytes

```
import processing.sound.*;
Engine.start().sinePlay(int(loadStrings("s")[0]),1,0,0,0);delay(5000);exit();

```

(For some reason Processing requires both using the import statement and the new line, otherwise it does not recognize the library.)

I still haven't figured out how to pass arguments into Processing, though I know it's possible, so this code requires having a file called "s" in the sketch folder which has the frequency value. If I can figure out how to pass in arguments I could replace file loading with `args[0]`.

# Answer
> 2 votes
# Turbo/Borland/Free/GNU Pascal, 95 bytes

Due to issues with the delay function on modern computers (well, anything faster than 200Mhz) trying to run Turbo / Borland pascal, this might not wait 5 seconds, even with a patched CRT library

```
Program a;Uses crt;Var i,k:Integer;BEGIN Val(ParamStr(1),i,k);Sound(i);Delay(5000);NoSound;END.

```

The String to Integer conversion can be done shorter (77 bytes) on FreePascal, and modern derivates, as they have the `StrToInt` function:

```
Program a;Uses crt;BEGIN Sound(StrToInt(ParamStr(1)));Delay(5000);NoSound;END.

```

# Answer
> 2 votes
## Perl, 27 bytes

Basically a Perl version of the Python answer (also only works on Windows), if we're allowing modules.

```
use Audio::Beep;beep<>,5000

```

# Answer
> 2 votes
# Vitsy + X11, 20 bytes

```
"5 "WX" 9 b tesx",7O

```

A translation of my bash answer. Does not work in the online interpreter (obviously).

Takes input as any non-numeric character followed by the frequency (so for an input of 440 Hz you could do "a440").

## Explanation

```
"5 "WX" 9 b tesx",7O
"5 "                   Push " 5"
    WX                 Reads input and removes the first character (which is used to force string context)
      " 9 b tesx"      Push "xset b 9 "
                 ,     Pop everything and execute as a shell command.
                  7O   Output bell char.

```

# Answer
> 1 votes
# C with WinAPI, 82 bytes

```
#include<windows.h>
#include<stdio.h>
main(){int x;scanf("%i",&x);Beep(x,5000);}

```

Uses the WinAPI Beep() function.

# Answer
> 1 votes
# Hassium, 38 Bytes

```
func main()Console.beep(input(), 5000)

```

# Answer
> 0 votes
## Shadertoy GLSL Sound Shader, 86

```
#define F 440.0
vec2 mainSound(float t){return vec2(sin(6.3*F*t)*(t<5.0?1.0:0.0));}

```

"Input" is given via `#define`. Outputs a sinewave with approximate frequency of `F`Hz. Rounded 2\*Pi to 6.3, instead of "default" 6.2831, but sounds pretty much the same.

Sadly there isn't much to golf here.

# Answer
> 0 votes
# Jolf, 4 bytes, noncompeting

This language addition came after the challenge.

```
Αc5j
Αc     create a beep
  5     five seconds long
   j    with the input as a frequency

```

The default wave is a sine wave.

# Answer
> 0 votes
# SmileBASIC, 84 bytes

```
INPUT F
N=LOG(F/440,POW(2,1/12))+57BGMPLAY FORMAT$("@D%D@255T12N%D",(N-(N<<0))*63,N)

```

Converts from Hz to half steps, and plays the a certain note with the a detune value to produce the frequency.

---
Tags: code-golf, audio
---


title: Draw the Ingress glyphs

text:
# Question
Title: Draw the Ingress glyphs
In the ~~location-based AR mobile game~~ way of life Ingress the player can hack things called portals in order to get items. (If you are interested in Ingress, you can ping me in chat for more info. Trust me, it's better than Pokémon. If you end up downloading it, remember to choose the Resistance.)

A way to increase hack output significantly is the *glyph hacking* minigame, in which the player has to draw glyphs on a hexagonal grid.

In total, there are about 115 glyphs with about 130 names that are actually used in the game.

## Glyphs

For the purposes of this challenge we will number each point of the grid like so:

Here is the list of all the glyphs for the purposes of this challenge. The list is a JSON object, containing each glyph as a list of edges.

```
{
"ABANDON": [[1, 6], [3, 4], [4, 8], [6, 10], [8, 10]],
"ACCEPT": [[3, 7], [3, 8], [7, 8]],
"ADVANCE": [[0, 9], [4, 9]],
"AFTER": [[1, 2], [1, 6], [2, 7], [6, 10], [7, 10]],
"AGAIN": [[4, 9], [6, 7], [6, 10], [8, 9], [8, 10]],
"ALL": [[0, 1], [0, 5], [1, 2], [2, 3], [3, 4], [4, 5]],
"ANSWER": [[6, 7], [6, 9], [7, 10]],
"ATTACK": [[0, 6], [0, 9], [2, 6], [4, 9]],
"AVOID": [[0, 5], [0, 6], [1, 6], [1, 7]],
"BALANCE": [[0, 10], [2, 3], [2, 7], [3, 4], [4, 8], [7, 10], [8, 10]],
"BARRIER": [[0, 10], [2, 7], [7, 10]],
"BEFORE": [[4, 5], [4, 8], [5, 9], [8, 10], [9, 10]],
"BEGIN": [[0, 8], [3, 7], [3, 8]],
"BODY": [[6, 9], [6, 10], [9, 10]],
"BREATHE": [[1, 6], [5, 9], [6, 10], [9, 10]],
"CAPTURE": [[1, 7], [3, 4], [4, 8], [7, 10], [8, 10]],
"CHANGE": [[3, 7], [3, 10], [8, 10]],
"CHAOS": [[0, 1], [0, 5], [1, 6], [3, 8], [4, 5], [6, 10], [8, 10]],
"CIVILIZATION": [[1, 6], [5, 9], [6, 7], [7, 8], [8, 9]],
"CLEAR": [[0, 10], [3, 10]],
"CLEAR ALL": [[0, 1], [0, 5], [0, 10], [1, 2], [2, 3], [3, 4], [3, 10], [4, 5]],
"COMPLEX": [[6, 9], [8, 10], [9, 10]],
"CONFLICT": [[2, 6], [4, 9], [6, 7], [7, 8], [8, 9]],
"CONTEMPLATE": [[0, 1], [1, 2], [2, 3], [3, 8], [6, 10], [8, 9], [9, 10]],
"COURAGE": [[4, 9], [7, 8], [8, 9]],
"CREATE": [[1, 6], [4, 8], [6, 10], [8, 10]],
"DANGER": [[0, 9], [3, 10], [9, 10]],
"DATA": [[0, 6], [3, 8], [6, 10], [8, 10]],
"DEFEND": [[1, 7], [3, 7], [3, 8], [5, 8]],
"DESTINY": [[3, 8], [6, 7], [6, 10], [7, 8], [9, 10]],
"DESTROY": [[2, 7], [5, 9], [7, 10], [9, 10]],
"DETERIORATE": [[4, 8], [8, 10], [9, 10]],
"DIE": [[2, 7], [4, 8], [7, 10], [8, 10]],
"DIFFICULT": [[1, 6], [6, 7], [7, 10], [8, 10]],
"DISCOVER": [[1, 2], [2, 3], [3, 4]],
"DISTANCE": [[0, 5], [4, 5]],
"EASY": [[3, 8], [6, 10], [8, 10]],
"END": [[0, 1], [0, 10], [1, 7], [3, 7], [3, 10]],
"ENLIGHTENED": [[0, 1], [0, 9], [1, 2], [2, 3], [6, 9], [6, 10], [9, 10]],
"ENLIGHTENMENT": [[0, 1], [0, 9], [1, 2], [2, 3], [6, 9], [6, 10], [9, 10]],
"EQUAL": [[6, 7], [6, 9], [8, 9]],
"ESCAPE": [[0, 1], [1, 6], [6, 9], [8, 9]],
"EVOLUTION": [[0, 10], [8, 9], [9, 10]],
"FAILURE": [[0, 10], [6, 7], [6, 10]],
"FEAR": [[1, 7], [6, 7], [6, 9]],
"FOLLOW": [[0, 6], [1, 2], [1, 6]],
"FORGET": [[4, 8]],
"FUTURE": [[1, 6], [2, 7], [6, 7]],
"GAIN": [[5, 8]],
"GROW": [[4, 9], [8, 9]],
"HARM": [[0, 6], [0, 9], [2, 7], [6, 10], [7, 10], [9, 10]],
"HARMONY": [[0, 6], [0, 9], [3, 7], [3, 8], [6, 10], [7, 10], [8, 10], [9, 10]],
"HAVE": [[3, 8], [7, 10], [8, 10]],
"HELP": [[5, 9], [7, 8], [8, 10], [9, 10]],
"HIDE": [[1, 6], [1, 7], [6, 9], [7, 8]],
"HUMAN": [[3, 7], [3, 8], [6, 7], [6, 9], [8, 9]],
"IDEA": [[1, 2], [1, 6], [2, 7], [4, 5], [4, 8], [5, 9], [7, 10], [9, 10]],
"IGNORE": [[2, 7]],
"IMPERFECT": [[6, 8], [6, 10], [8, 9], [8, 10], [9, 10]],
"IMPROVE": [[1, 6], [6, 10], [7, 10]],
"IMPURE": [[3, 10], [8, 9], [8, 10], [9, 10]],
"INSIDE": [[6, 7], [6, 9]],
"INTELLIGENCE": [[1, 6], [4, 8], [6, 10], [8, 9], [9, 10]],
"INTERRUPT": [[0, 10], [3, 10], [4, 5], [4, 8], [5, 9], [8, 10], [9, 10]],
"JOURNEY": [[1, 6], [2, 3], [3, 4], [4, 5], [5, 9], [6, 10], [9, 10]],
"KNOWLEDGE": [[3, 6], [3, 9], [6, 10], [9, 10]],
"LEAD": [[0, 5], [3, 8], [4, 5], [4, 8]],
"LEGACY": [[0, 1], [0, 5], [1, 6], [2, 7], [4, 8], [5, 9], [6, 7], [8, 9]],
"LESS": [[6, 10], [9, 10]],
"LIBERATE": [[0, 1], [1, 6], [4, 9], [6, 10], [9, 10]],
"LIE": [[6, 7], [6, 10], [7, 10], [8, 9], [9, 10]],
"LOSE": [[1, 7]],
"MESSAGE": [[1, 7], [4, 9], [7, 10], [9, 10]],
"MIND": [[3, 8], [3, 10], [8, 9], [9, 10]],
"MORE": [[7, 10], [8, 10]],
"MYSTERY": [[0, 6], [0, 9], [5, 9], [6, 9], [8, 9]],
"N'ZEER": [[0, 6], [0, 9], [0, 10], [3, 10], [6, 10], [9, 10]],
"NATURE": [[2, 7], [4, 8], [6, 7], [6, 9], [8, 9]],
"NEW": [[2, 7], [6, 7]],
"NO": [[6, 7], [6, 9]],
"NOT": [[6, 7], [6, 9]],
"NOURISH": [[3, 4], [3, 10], [4, 8], [8, 10]],
"NOW": [[6, 7], [7, 8], [8, 9]],
"OLD": [[5, 9], [8, 9]],
"OPEN": [[3, 7], [3, 8], [7, 8]],
"OPEN ALL": [[0, 1], [0, 5], [1, 2], [2, 3], [3, 4], [3, 7], [3, 8], [4, 5], [7, 8]],
"OUTSIDE": [[0, 5], [4, 5]],
"PAST": [[4, 8], [5, 9], [8, 9]],
"PATH": [[0, 10], [4, 8], [8, 10]],
"PEACE": [[0, 6], [0, 9], [3, 7], [3, 8], [6, 10], [7, 10], [8, 10], [9, 10]],
"PERFECTION": [[0, 10], [2, 3], [2, 7], [3, 4], [4, 8], [7, 10], [8, 10]],
"PERSPECTIVE": [[0, 6], [0, 9], [2, 7], [4, 8], [6, 10], [7, 10], [8, 10], [9, 10]],
"PORTAL": [[1, 2], [1, 6], [2, 7], [4, 5], [4, 8], [5, 9], [6, 9], [7, 8]],
"POTENTIAL": [[0, 10], [1, 2], [2, 7], [7, 10]],
"PRESENT": [[6, 7], [7, 8], [8, 9]],
"PURE": [[0, 10], [6, 7], [6, 10], [7, 10]],
"PURSUE": [[0, 6], [0, 9], [5, 9]],
"QUESTION": [[0, 6], [6, 9], [8, 9]],
"REACT": [[2, 7], [6, 9], [7, 10], [9, 10]],
"REBEL": [[1, 2], [1, 6], [5, 8], [6, 10], [8, 10]],
"RECHARGE": [[0, 5], [0, 10], [5, 9], [9, 10]],
"REPAIR": [[0, 5], [0, 10], [5, 9], [9, 10]],
"REPEAT": [[4, 9], [6, 7], [6, 10], [8, 9], [8, 10]],
"RESISTANCE": [[0, 9], [0, 10], [3, 8], [3, 10], [6, 9]],
"RESTRAINT": [[2, 3], [2, 7], [5, 9], [7, 10], [9, 10]],
"RETREAT": [[0, 6], [2, 6]],
"SAFETY": [[2, 6], [4, 9], [6, 9]],
"SAVE": [[1, 7], [7, 10], [8, 10]],
"SEARCH": [[6, 9], [6, 10], [7, 8], [8, 9]],
"SEE": [[0, 9]],
"SEPARATE": [[2, 7], [5, 9], [6, 7], [6, 10], [8, 9], [8, 10]],
"SHAPER": [[0, 6], [0, 9], [2, 7], [4, 8], [6, 7], [8, 9]],
"SIMPLE": [[7, 8]],
"SOUL": [[3, 7], [3, 10], [6, 7], [6, 10]],
"STABILITY": [[2, 7], [4, 8], [7, 8]],
"STAY": [[2, 7], [4, 8], [7, 8]],
"STRONG": [[6, 7], [6, 9], [7, 8], [8, 9]],
"STRUGGLE": [[0, 9], [0, 10], [3, 8], [3, 10], [6, 9]],
"SUCCESS": [[0, 10], [8, 9], [9, 10]],
"TECHNOLOGY": [[1, 6], [2, 7], [6, 10], [7, 10], [8, 9], [8, 10], [9, 10]],
"THOUGHT": [[1, 2], [1, 6], [2, 7], [4, 5], [4, 8], [5, 9], [7, 10], [9, 10]],
"TOGETHER": [[4, 8], [6, 9], [6, 10], [8, 10], [9, 10]],
"TRUTH": [[6, 7], [6, 10], [7, 10], [8, 9], [8, 10], [9, 10]],
"UNBOUNDED": [[0, 1], [0, 5], [1, 7], [2, 3], [3, 4], [4, 5], [6, 9], [6, 10], [7, 8], [8, 9]],
"US": [[3, 6], [6, 9]],
"USE": [[1, 7], [7, 10]],
"WANT": [[3, 7], [3, 8], [4, 8]],
"WAR": [[0, 6], [0, 9], [2, 6], [4, 9]],
"WEAK": [[5, 9], [6, 7], [6, 9]],
"XM": [[6, 7], [6, 9], [7, 10], [8, 9], [8, 10]],
"YOU": [[0, 7], [0, 8], [7, 8]],
"YOUR": [[0, 7], [0, 8], [7, 8]]
}

```

Some glyphs have multiple names (e.g. `NO, NOT, INSIDE`); you must support them all.

**Disclaimer:** I couldn't find a good list of all of the glyphs, so I combined multiple sources and finally ended up drawing all of them in a hacked-together JS application to get the list of them. I may be missing some and there may be a couple of aliases not used in the game; I hope I didn't misdraw some of the glyphs, though.

**Edit the next morning when it's not 4am:** I already noticed VICTORY is missing. Oh well, it's left for the best golfer then.

## Challenge

Your task is to create a program or function that takes in a name of a glyph, and outputs the glyph as an image.

The image must contain the grid points and the lines connecting the points in question.

This is , so the shortest answer in bytes wins. Standard rules apply.

### I/O

You will take as input, in a format of your choice, a name of a glyph exactly as found in the keys of the above JSON object. Any other input is undefined behavior.

You will output an image in any common format with the glyph rendered to the grid.

### Grid proportions

These proportions must be accurate to five pixels (to allow for rounding etc.)

* The outer points (0-5) must form a regular hexagon.
* The center point (10) must be in the center of the hexagon.
* The intermediate points (6-9) must be halfway between the center point and the corresponding outer points.
* The grid must be oriented like the original.
* The height of the outer hexagon must be at least 100 pixels.

### Other rules

* The background **must** be either transparent or filled with a solid color.
* The lines and points **must** be clearly distinct from the background and each other; they cannot be of the same solid color.
    + For example, solid blue lines and solid pink points is fine.
    + Solid black lines and white points with black borders is fine.
    + Red and white striped lines and footballs as points is fine.
    + Solid green lines and solid green points is **not** fine.
* The radius of the points **must** be larger than the width of the lines.
* You **may** draw the lines in front of or behind the points.
* You **may** include any amount of padding (in the background color) in the image.
* You **may** combine consecutive lines into one line, since it doesn't affect the outcome.

## Examples

The colors and object widths in these images are just examples that somewhat resemble the appearance of the game.

### UNBOUNDED

### PEACE

### RESISTANCE

# Answer
# Mathematica, 228 + 184 + 365 + 13 = 790 bytes

```
Graphics@{v=255#+##&~Fold~BinaryReadList@#~IntegerDigits~#2&;p=#~Partition~2&;c=p["c"~v~25-12][[#+1]]&;Array[Disk@*c,11,0],Red,Line[c/@<|Thread["a"~v~2293->First/@p@SplitBy["b"~v~12,#>10&]]|>@Mod[1##&@@ToCharacterCode@#,2293]]}&

```

The above 228-byte command defines an unnamed function that takes as input one of the glyph names above, and returns an image. For example, here is the output for `"UNBOUNDED"`:

The command reads three binary files—`"a"`, `"b"`, and `"c"`—which have 184, 365, and 13 bytes, respectively. An easier-to-read version:

```
1  Graphics@{
2    v = 255#+##&~Fold~BinaryReadList@#~IntegerDigits~#2 &;
3    p = #~Partition~2 &;
4    c = p["c"~v~25-12][[#+1]] &;
5    Array[Disk@*c, 11, 0], Red,
6    Line[c /@
7      <| Thread[ "a"~v~2293 -> First/@p@SplitBy["b"~v~12, #>10&] ] |>
8        @ Mod[1##& @@ ToCharacterCode@#, 2293]]
9  } &

```

Line 2 defines a handmade uncompression function: it reads in a stream of bytes from the file `#`, converts it into a base-256 integer, and then expands that integer into its list of digits in base `#2`. Lines 3 and 4 define a function (using the third binary file) that converts an integer from 0 to 10 into the coordinates of the corresponding grid point; all these coordinates were chosen to be integers between –12 and 12, which makes compression convenient (though not so convenient that I saw it for my initial submission).

Line 5 draws the grid points (in default color black), then switches to the color red for the lines. Line 7 creates an association (using the first two binary files) that converts certain input integers between 0 and 2292 into a list of grid-point integers such as `{2, 3, 4, 5, 0, 1, 7, 8, 9, 6, 10}`, which represents a path joining point 2 to 3 to 4 to ... to 10. (This is an "Eulerian path", one that visits each edge exactly once; all the glyphs in the table have an Eulerian path, so this representation is shorter than listing the set of edges explicitly.) The command after the `->` on line 7 creates this list of Eulerian paths, by reading in a base-12 integer using `v` and then splitting it at every occurrence of the digit 11.

Finally, line 8 hashes the input string by converting all its letters to their ASCII codes and taking their product modulo 2293 (the smallest modulus for which the answers are all distinct). That integer is fed into the association in the line above, resulting in the appropriate Eulerian path, and line 6 draws the resulting path over the grid points.

Hex dumps of files "a", "b", and "c", in that order:

```
09d5f27cd2246e0cb06aa243b442d761ac3a5604439f1767a202c4d3fc4fc1b24ce59acfc65a05235cc46354af8820d6733001e1f25ea01479cee027d62e8b1be10891c693ed5887942ca461c461d458a7676bfcd866a70263ad1833b3e836895ce121153c451ad327086e2bd30d6bad7097a9e71c2fc67c2c57716e5ada6907d99f42702dfb8b88c6d26799aa01f42fb89394e00b0752825f2740903276e20ec405473f309cc978aea187da24749d0a44319cd7322dd542

02d9ebf5fc94183ce50f0fc84e88a27bd21a3b3665d54949608c75c86c4507eed3072e02657822bfb83dbca8a708e07d1382c2b6c3c8fcddc88fa7244281a918b3a8aa823048d4a7e070a336c1e5ab83ec4950fc1960f34c6b89c541c9401607882418cac7f79f4edb164b775ecbb97947470016cadea4d06f93a958713b8c23d11be3c9ce8a2824a458d151ac3cafc6d7bb1557e55868434bd5c0da4bd71e66a3f7711018ae5e7f2941a949a85b6e65aebcc2fe43a89cb0479fa9474fe5102cfbf7da8a455f46ac5409dfdc79970ed8dbfc6b84df78c9c19df4d16bda298dca445ad510bf32e14ca5c91ce58e7521492f6e79e05624ab4a4c02c66c22ef670a06d5c5a3dfdf8ccc8c40c353f3aecf17bbb5cb911baefa3ce80e41551376838c166153a1038d83e171077a3f260ccd70358917eeceb5722b58ad6900a40b5b1512b292fb7a7e0d2cbe2bac2a48a4e343e8f2a338808ec9957c64778aba412bec47bcabb2a2789f01c2d5fdd993

254c40dac61bb215386b7361a8

```
> 9 votes

---
Tags: code-golf, kolmogorov-complexity, graphical-output
---


title: Jordan Decomposition

text:
# Question
Title: Jordan Decomposition
**Important note**: Because this challenge only applies to square matrices, any time I use the term "matrix", it is assumed that I am referring to a square matrix. I am leaving off the "square" description for brevity's sake.

## Background

Many matrix-related operations, such as computing the determinant, solving a linear system, or extending scalar-valued functions to matrices are made easier by using a diagonal matrix (one whose elements that are not on the main diagonal are 0) that is similar to the original matrix (meaning, for the input matrix `A` and the diagonal matrix `D`, there exists some invertible matrix `P` such that `D = P^(-1) * A * P`; also, `D` and `A` share some important properties, like eigenvalues, determinant, and trace). For matrices with distinct eigenvalues (the roots to the matrix's characteristic polynomial, given by solving `det(A-λI) = 0` for `λ`, where `I` is the identity matrix with the same dimensions as `A`), diagonalization is simple: `D` is a matrix with the eigenvalues on the main diagonal, and `P` is a matrix formed from eigenvectors corresponding to those eigenvalues (in the same order). This process is called eigendecomposition.

However, matrices with repeated eigenvalues cannot be diagonalized in this manner. Luckily, the Jordan normal form of any matrix can be computed rather easily, and is not much harder to work with than a regular diagonal matrix. It also has the nice property that, if the eigenvalues are unique, then Jordan decomposition is identical to eigendecomposition.

## Jordan decomposition explained

For a square matrix `A` whose eigenvalues all have a geometric multiplicity of 1, the process of Jordan decomposition can be described as such:

1. Let `λ = {λ_1, λ_2, ... λ_n}` be the list of eigenvalues of `A`, with multiplicity, with repeated eigenvalues appearing consecutively.
2. Create a diagonal matrix `J` whose elements are the elements of `λ`, in the same order.
3. For each eigenvalue with multiplicity greater than 1, place a `1` to the right of each of the repetitions of the eigenvalue in the main diagonal of `J`, except the last.

The resulting matrix `J` is a Jordan normal form of `A` (there can be multiple Jordan normal forms for a given matrix, depending on the order of the eigenvalues).

### A worked example

Let `A` be the following matrix:

The eigenvalues of `A`, with multiplicity, are `λ = {1, 2, 4, 4}`. By putting these into a diagonal matrix, we get this result:

Next, we place `1`s to the right of all but one of each of the repeated eigenvalues. Since `4` is the only repeated eigenvalue, we place a single `1` next to the first 4:

This is a Jordan normal form of `A` (a single matrix can potentially have several valid Jordan normal forms, but I'm glossing over that detail for the purpose of explanation).

## The task

Given a square matrix `A` as input, output a valid Jordan normal form of `A`.

* The input and output may be in any reasonable format (2D array/list/whatever, list/array/whatever of column or row vectors, a builtin matrix data type, etc.).
* The elements and eigenvalues of `A` will always be integers in the range `[-200, 200]`.
* For the sake of simplicity, all of the eigenvalues will have a geometric multiplicity of 1 (and thus the above process holds).
* `A` will at most be a 10x10 matrix and at least a 2x2 matrix.
* Builtins that compute eigenvalues and/or eigenvectors or perform eigendecomposition, Jordan decomposition, or any other kind of decomposition/diagonalization are not allowed. Matrix arithmetic, matrix inversion, and other matrix builtins are allowed.

## Test cases

```
[[1, 0], [0, 1]] -> [[1, 1], [0, 1]]
[[3, 0], [0, 3]] -> [[1, 1], [0, 1]]
[[4, 2, 2], [1, 2, 2],[0, 3, 3]] -> [[6, 0, 0], [0, 3, 0], [0, 0, 0]]
[[42, 48, 40, 64, 64], [41, 47, 31, 58, 42], [-55, -47, -27, -74, -46], [-46, -58, -46, -70, -68], [30, 20, 12, 34, 18]] -> [[10, 0, 0, 0, 0], [0, -18, 0, 0, 0], [0, 0, 6, 1, 0], [0, 0, 0, 6, 1], [0, 0, 0, 0, 6]]

```

# Answer
> 3 votes
# Mathematica, ~~140~~ ~~139~~ 105 bytes

```
Total[DiagonalMatrix@@@{{#},{1-Sign[Differences@#^2],1}}]&@(x/.Solve[#~CharacteristicPolynomial~x==0,x])&

```

I just found the builtin `DiagonalMatrix` which allows for an easy way to place the 0s and 1s along the superdiagonal.

## Usage

# Answer
> 2 votes
## Sage, 79 bytes

```
lambda A:block_diagonal_matrix([jordan_block(*r)for r in A.charpoly().roots()])

```

Try it online

Since nobody else is posting solutions, I might as well go ahead and post one.

`A.charpoly.roots()` computes the roots (and algebraic multiplicities) of the characteristic polynomial of `A` (aka the eigenvalues and multiplicities). `jordan_block` constructs a Jordan block from the given root and multiplicity. `block_diagonal_matrix` forms a matrix with the Jordan blocks on the diagonal, which is exactly the definition of a Jordan normal form.

# Answer
> 2 votes
# , ~~78~~ 71 bytes

```
1(#\.|."_1#{."1],.2=/\,&_)@>@{[:p.@>[:-&.>/ .(+//.@(*/)&.>)],&.>[:-@=#\

```

Try it online!

The two challenging portions of this task, getting the eigenvalues and performing the diagonalization, ending up both taking about the same number of bytes. These were disallowed by the rules but in case any are curious, J has builtins for QR decomposition (`128!:0`) as well as LAPACK addons which could be used to find eigenvalues.

## Explanation (Outdated)

There are two major portions to this verb: finding the eigenvalues and performing the diagonalization. First, in order to find the eigenvalues, the roots of the characteristic polynomial for the input matrix will have to be found. Using the same input matrix from the example,

```
   ] m =: _4 ]\ 5 4 2 1 0 1 _1 _1 _1 _1 3 0 1  1 _1 2
 5  4  2  1
 0  1 _1 _1
_1 _1  3  0
 1  1 _1  2

```

The characteristic polynomial for a matrix *M* can be found using |*M* \- *λI*| = 0 where *I* is the identity matrix with the same dimensions as *M*. The expression *M* \- *λI* can be modeled in J by boxing each element in *M* with a -1 if it is on the diagonal else otherwise a 0. Each box represents a polynomial in coefficient form.

```
   (],&.>[:-@=#\) m
┌────┬────┬────┬────┐
│5 _1│4 0 │2 0 │1 0 │
├────┼────┼────┼────┤
│0 0 │1 _1│_1 0│_1 0│
├────┼────┼────┼────┤
│_1 0│_1 0│3 _1│0 0 │
├────┼────┼────┼────┤
│1 0 │1 0 │_1 0│2 _1│
└────┴────┴────┴────┘

```

The determinant in J is `-/ .*` however, that operates on numbers, not boxed polynomials. Instead of multiplication, the polynomial product is needed which can be found using convolution (`[:+//.*/`). Folded subtraction is still used, and both these verbs need to operate within boxes so under (`&.`) unbox (`>`) is used.

```
   ([:-&.>/ .(+//.@(*/)&.>)],&.>[:-@=#\) m0
┌───────────────┐
│32 _64 42 _11 1│
└───────────────┘

```

These are the coefficients of the characteristic polynomial. The roots can be found using `p.` which converts the representation of a polynomial between coefficients and roots form.

```
   ([:p.@>[:-&.>/ .(+//.@(*/)&.>)],&.>[:-@=#\) m0
┌─┬───────┐
│1│4 4 2 1│
└─┴───────┘

```

The roots are `[4, 4, 2, 1]` and those are the eigenvalues of *M*.

Second, the diagonalization must be performed. Each continuous pair of values is tested for equality.

```
   (2=/\]) 4 4 2 1
1 0 0

```

A zero is appended and those values are columinized together with the eigenvalues.

```
   (],.0,~2=/\]) 4 4 2 1
4 1
4 0
2 0
1 0

```

Then each row is padded to the same length as the number of eigenvalues to form a square matrix.

```
   (#{."1],.0,~2=/\]) 4 4 2 1
4 1 0 0
4 0 0 0
2 0 0 0
1 0 0 0

```

Finally each row is shifted right with values falling off at the right and zeros being pushed in on the left. The first row is shifted zero times, the second once, the third twice, and so on.

```
   (-@i.@#|.!.0"_1#{."1],.0,~2=/\]) 4 4 2 1
4 1 0 0
0 4 0 0
0 0 2 0
0 0 0 1

```

The output is the Jordan decomposition of *M*.

# Answer
> 1 votes
# Octave, 60 bytes

```
@(a)diag(1-sign(diff(v=round(roots(poly(a)))).^2),1)+diag(v)

```

Try it online!

A port of my Mathematica solution.

# Answer
> 1 votes
# MATL, 29 bytes, non-competing

```
1$Yn1$ZQYotdUZS~0hXdF1hYSwXd+

```

Try it online!

This is my first MATL submission so there are bound to be improvements. I spent a while learning it and only at the end did I remember that this might not have worked using the MATL from May 7, 2016. Sure enough, I checked out the penultimate commit to that day and it did not run.

I would have liked to use `diag` but it seems MATL only supports the single argument version. The second argument would be needed to place values along the superdiagonal (or any other diagonal for different problems).

---
Tags: code-golf, math, linear-algebra, matrix
---