title: Constructible n-gons

text:
# Question
Title: Constructible n-gons
A constructible \\$n\\$-gon is a regular polygon with n sides that you can construct with only a compass and an unmarked ruler.

As stated by Gauss, the only \\$n\\$ for which a \\$n\\$-gon is constructible is a product of any number of distinct Fermat primes and a power of \\$2\\$ (ie. \\$n = 2^k \times p\_1 \times p\_2 \times ...\\$ with \\$k\\$ being an integer and every \\$p\_i\\$ some distinct Fermat prime).

A Fermat prime is a prime which can be expressed as \\$2^{2^n}+1\\$ with \\$n\\$ a positive integer. The only known Fermat primes are for \\$n = 0, 1, 2, 3 \text{ and } 4\\$

# The challenge

Given an integer \\$n\>2\\$, say if the \\$n\\$-gon is constructible or not.

# Specification

Your program or function should take an integer or a string representing said integer (either in unary, binary, decimal or any other base) and return or print a truthy or falsy value.

This is code-golf, so shortest answer wins, standard loopholes apply.

Relevant OEIS

# Examples

```
3 -> True
9 -> False
17 -> True
1024 -> True
65537 -> True
67109888 -> True
67109889 -> False

```

# Answer
# Jelly, ~~7~~ 5 bytes

*Thanks to Sp3000 for saving 2 bytes.*

```
ÆṪBSỊ

```

Uses the following classification:

> These are also the numbers for which phi(n) is a power of 2.

Where *phi* is Euler's totient function.

```
ÆṪ        # Compute φ(n).
  B       # Convert to binary.
   S      # Sum bits.
    Ị     # Check whether it's less than or equal to 1. This can only be the
          # case if the binary representation was of the form [1 0 0 ... 0], i.e.
          e# a power of 2.

```

Try it online!

Alternatively (credits to xnor):

```
ÆṪ’BP
ÆṪ        # Compute φ(n).
  ’       # Decrement.
   B      # Convert to binary.
    P     # Product. This is 1 iff all bits in the binary representation are
          # 1, which means that φ(n) is a power of 2.

```

A direct port of my Mathematica answer is two bytes longer:

```
ÆṪ        # Compute φ(n).
  µ       # Start a new monadic chain, to apply to φ(n).
   ÆṪ     # Compute φ(φ(n)).
      H   # Compute φ(n)/2.
     =    # Check for equality.

```
> 8 votes

# Answer
## Mathematica, 24 bytes

```
e=EulerPhi
e@e@#==e@#/2&

```

Uses the following classification from OEIS:

> Computable as numbers such that cototient-of-totient equals the totient-of-totient.

The totient `φ(x)` of an integer `x` is the number of positive integers below `x` that are coprime to `x`. The cototient is the number of positive integers that aren't, i.e. `x-φ(x)`. If the totient is equal to the cototient, that means that the totient of `φ(x) == x/2`.

The more straightforward classification

> These are also the numbers for which phi(n) is a power of 2.

ends up being a byte longer:

```
IntegerQ@Log2@EulerPhi@#&

```
> 3 votes

# Answer
## Retina, ~~51~~ 50 bytes

```
0+$

+`^(.*)(?=(.{16}|.{8}|....|..?)$)0*\1$
$1
^1$

```

Input is in binary. The first two lines divide by a power of two, the next two divide by all known Fermat primes (if in fact the number is a product of Fermat primes). Edit: Saved 1 byte thanks to @Martin Ender♦.
> 3 votes

# Answer
## JavaScript (ES7), 61 bytes

```
n=>[...Array(5)].map((_,i)=>n%(i=2**2**i+1)?0:n/=i)&&!(n&n-1)

```
> 2 votes

# Answer
# Actually, 6 bytes

This answer is based on xnor's algorithm in Martin Ender's Jelly answer. Golfing suggestions welcome. Try it online!

```
▒D├♂≈π

```

**How it works**

```
         Implicit input n.
▒        totient(n)
 D       Decrement.
  ├      Convert to binary (as string).
   ♂≈    Convert each char into an int.
     π   Take the product of those binary digits.
         If the result is 1,
           then bin(totient(n) - 1) is a string of 1s, and totient(n) is power of two.

```
> 1 votes

# Answer
## Batch, 97 bytes

```
@set/pn=
@for /l %%a in (4,-1,0)do @set/a"p=1<<(1<<%%a),n/=p*!(n%%-~p)+1"
@cmd/cset/a"!(n-1&n)"

```

Input is on stdin in decimal. This is actually 1 byte shorter than calculating the powers of powers of 2 iteratively. I saved 1 byte by using @xnor's power of 2 check.
> 0 votes

---
Tags: code-golf, math, number-theory
---


title: Are you a Fanatic?

text:
# Question
Title: Are you a Fanatic?
Write a function or program that awards you SE badges. If an input "Q" is given it means you have asked a question. If no input is given it means you have only visited the site.\*

Badges it must support:

* Run script 30 days in a row: "Enthusiast"
* Run script 100 days in a row: "Fanatic"
* Input "Q" first time: "Student"
* Input "Q" on 5 separate days: "Curious"
* Input "Q" on 30 separate days: "Inquisitive"
* Input "Q" on 100 separate days: "Socratic"

**Input:**

* You may choose an arbitrary input value for the times you ask questions (I've used "Q" as an example).
* You may choose an arbitrary input value, or have none at all, for the times you only visit the site.
* If a third type of input is given, say "R", then the counters and list of badges shall be reset. This is to ensure that the program can be reused.

Note, you may visit the site many times each day, and ask several questions on the same day. As with the real badges, days are counted in UTC.

You can only have one of each of the badges.

The source code can be altered, but remember the reset functionality. The score will be the size of the script before it's executed the first time.

**Output:**

Every time you run the script it should output/print a list of badges you have. The output format is optional, but it must use the proper badge names, i.e. you can't enumerate the badges.

The output should be an empty string, `0`, `false` or something similar if you don't have any badges. The program can't crash, enter an infinite loop or something similar.

---

This is code golf, so the shortest code before running the script the first time. As always, the score is counted in bytes.

You may use an external file to store information, but both the name of the file, and the size of the file before the code is executed the first time will count toward the score.

# Answer
I guess I'll start.

# **JAVA: 572 bytes**

```
public class a {static Map<Integer,String>o=new HashMap<Integer,String>();static Map<Integer,String>p=new HashMap<Integer,String>();public static void main(String[] args){Scanner d= new Scanner(System.in);b();int e=0,v=0;while(true){char y=d.nextLine().toCharArray()[0];if(y=='Q'){e++;v++;}else if(y == 'R'){e=0;v=0;b();}else{v++;}System.out.println(o.get(v)+p.get(e));o.remove(v);p.remove(e);}}public static void b(){o.clear();p.clear();o.put(30,"Enthusiast");o.put(100, "fanatic");p.put(1, "student");p.put(5, "Curious");p.put(30,"Inquisitive");p.put(100, "Socratic");}}

```

Input:
"R" to reset
"Q" if you asked a question
" " if you visited.
\[Enter\] to log your day.

Output: The badges that you earned that day.
> 4 votes

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


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

```
 . . . . . . . .
. . . . # . . .
 . # . . . # . .
. . . # . . . .
 . . . . . # . .
. . . . . . . .

```

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

```
 . . . . . . . .
. . # # # # . .
 . # # # # # . .
. . # # # # # .
 . . # # # # . .
. . . . . . . .

```

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

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

```
. . . . . . . .         . . . . . . . .
 . # . . . . . .         . # # # # . . .
. . . . . # . .         . . # # # # . .
 . . # . . . . .         . . # # # . . .
. . . . . . . .         . . . . . . . .

```

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

**Too hard? Try Part I!**

## Rules

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

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

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

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

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

This is , so the shortest valid answer – measured in *bytes* – wins.

## Test Cases

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

```
#    #

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

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

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

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

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

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

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

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

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

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

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

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

```

# Answer
> 6 votes
# Pyth, ~~82~~ 71 bytes

```
~~L,hbebMqH@S+GH1KhMyJs.e,Lkfq\#@bTUb.zA,ySm-FdJySsMJj.es.eXW&&gKkgG-kYgH+kYZ\.\#b.z~~
MqH@S[hGHeG)1j.es.eXW&&ghMJs.e,Lkfq\#@bTUb.zkgSm-FdJ-kYgSsMJ+kYZ\.\#b.z

```

Try it online!

### Explanation

* Let A be the point with the lowest y-coordinate and B the point with the highest y-coordinate.
* Let C be the point with the lowest (x-value minus y-value) and D the point with the highest.
* Let E be the point with the lowest (x-value plus y-value) and F the point with the highest.

Then it is equivalent to finding the coordinates which the y-coordinate is between A and B, the x-value minus y-value is between C and D, and the x-value plus y-value is between E and F.

# Answer
> 5 votes
## Haskell, ~~256 254~~ 243 bytes

```
import Data.List
f=z(\l->(,).(,))[0..]l)[0..]
q l=m(m(\e->min(snd e).(".#"!!).fromEnum.and.z($)(m(\x y->y>=minimum x&&y<=maximum x).transpose.m b.filter((==)'#'.snd).concat$l)$b e))l
b=(m uncurry[const,(-),(+)]<*>).pure.fst
z=zipWith
m=map
q.f

```

Thanks @Damien for golfing `f`!

Input is taken as list of list of chars, output is provided the same way.

Soo this was a beast to write. It's based on LeakyNun's idea using a maximum and minimum based filtering on the coordinates of the items.

I'm really surprised by the fact that `m=map` actually saves bytes since it seems so costly.

---

Explanation:

Here's a slightly less butchered version (emphasis on *slightly*):

```
import Data.List
f=zipWith(\y l->zipWith(\x e->((y,x),e))[0..]l)[0..]
p=map(\x y->y>=minimum x&&y<=maximum x).transpose.map b.filter((==)'#'.snd).concat
q l=map(map(\e->min(snd e).(".#"!!).fromEnum.and.zipWith($)(p$l)$b e))l
b=(map uncurry[const,(-),(+)]<*>).pure.fst

```
* `f` is a function which assigns each char an index `(y-index, x-index)` while preserving the original structure of the list.
* `b`: Given an item of the indexed list, `b` computes `[y-index, y - x, y + x]`.
* `p`: Given the indexed field, return 3 functions `Int -> Bool`, the first of which is the check of the y-index, the second of the difference and the third of the sum. `min(snd e)` takes care of the spaces (a space is smaller than both). This function is inlined in the golfed code.
* `q` given the indexed field, change all necessary `.` to `#` by checking if that specific field return `True` to every test function.

The final solution is then the composition of `q` and `f`.

# Answer
> 5 votes
# Jelly, ~~45~~ ~~3513~~ ~~42~~ 41 bytes

```
Ṁ€»\
ṚÇṚ«Çṁ"
ŒDṙZL$ÇṙL’$ŒḌ«Ç
ṚÇṚ«Ç
n⁶aÇo⁶

```

This is a list of links; the last one has to be called on the input to produce the output.

I/O is in form of string arrays, where `.` indicates empty and `@` indicates filled.

Try it online! or verify all test cases.

### Background

Let's consider the following example.

```
. . . . . . . .
 . @ . . . . . .
. . . . . @ . .
 . . @ . . . . .

```

By drawing a pair or parallel lines – the closest pair that encloses all filled positions – in each of the three directions, we can determine the hexagonal bounding box.

In the implementation, we replace all characters between those two lines with `@`, and everything outside these lines with `.`, with the possible exception of diagonals that only contains spaces).

For the horizontal axis, this gives

```
................
@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@

```

for the falling diagonal axis, it gives

```
..@@@@@@@......
...@@@@@@@......
....@@@@@@@.....
 ....@@@@@@@....

```

and for the raising diagonal axis, it gives

```
....@@@@@@@@@...
...@@@@@@@@@....
..@@@@@@@@@....
.@@@@@@@@@.... .

```

By taking the character-wise minimum of all three, since `.` \< `@`, we get

```
...............
...@@@@@@@......
....@@@@@@@....
 ....@@@@@.... .

```

All that's left to do is restoring the spaces.

### How it works

```
n⁶aÇo⁶           Main link. Argument: A (array of strings)

n⁶               Not-equal space; yield 0 for spaces, 1 otherwise.
  aÇ             Take the logical AND with the result the 4th helper link.
                 This will replace 1's (corresponding to non-space characters) with
                 the corresponding character that result from calling the link.
    o⁶           Logical OR with space; replaces the 0's with spaces.

```

```
ṚÇṚ«Ç            4th helper link. Argument: A

Ṛ                Reverse the order of the strings in A.
 Ç               Call the 3rd helper link.
  Ṛ              Reverse the order of the strings in the resulting array.
    Ç            Call the 3rd helper link with argument A (unmodified).
   «             Take the character-wise minimum of both results.

```

```
ŒDṙZL$ÇṙL’$ŒḌ«Ç  3rd helper link. Argument: L (array of strings)

ŒD               Yield all falling diagonals of L. This is a reversible operation,
                 so it begins with the main diagonal.
   ZL$           Yield the length of the transpose (number of columns).
  ṙ              Shift the array of diagonals that many units to the left.
                 This puts the diagonals in their natural order.
      Ç          Call the helper link on the result.
        L’$      Yield the decremented length (number of columns) of L.
       ṙ         Shift the result that many units to the left.
                 This puts the changed diagonals in their original order.
           ŒḌ    Undiagonal; reconstruct the string array.
              Ç  Call the 2nd helper link with argument L (unmodified).
             «   Take the character-wise minimum of both results.

```

```
ṚÇṚ«Çṁ"          2nd helper link. Argument: M (array)

Ṛ                Reverse the rows of M.
 Ç               Call the 1st helper link on the result.
  Ṛ              Reverse the rows of the result.
    Ç            Call the 1nd helper link with argument M (unmodified).
   «             Take the minimum of both results.
     ṁ"          Mold zipwith; repeat each character in the result to the left
                 as many times as needed to fill the corresponding row of M.

```

```
Ṁ€»\             1st helper link. Argument: N (array)

Ṁ€               Take the maximum of each row of N.
  »\             Take the cumulative maxima of the resulting characters.

```

# Answer
> 4 votes
# Python 3, ~~380~~ ~~378~~ ~~348~~ 346 bytes

Note that the indentation is with tabs, not spaces.

### Golfed version:

```
def s(i):
    L=i.splitlines();E=enumerate;A=lambda x,y:(y,x+y,x-y);N=(2**64,)*3;X=(-2**64,)*3
    for y,l in E(L):
        for x,c in E(l):
            if c=='#':p=A(x,y);X=tuple(map(max,X,p));N=tuple(map(min,N,p))
    R=''
    for y,l in E(L):
        for x,c in E(l):
            if c!='.':R+=c
            else:p=A(x,y);f=all(N[j]<=p[j]<=X[j]for j in range(0,3));R+='.#'[f]
        R+='\n'
    return R

```

Test it on Ideone

### Explanation (for ungolfed version below):

All processing is done without any conversion, space characters are simply skipped.
Function `axes_pos` calculates 3-tuple of imaginary "3D" coordinates, they are accumulated into (element wise) minimum and maximum 3-tuples (`bmin`, `bmax`) for all `#` characters.

Coordinates are calculated in `def axes_pos(x, y): return y, x + y, lc - y + x`;
where X counts from 0 to right, and Y counts from 0 to bottom (from first line to last).
First imaginary coordinate is basically Y, because it's obvious why. Its axe is orthogonal to green bounds (in the OP's pictures)
Second is orthogonal to red bounds, and third is orthogonal to blue bounds.

In the second pass, replacement is done for all `.` characters which "3D" coordinates fall into `bmin`..`bmax` range, element wise — this is checked in this expression `all(bmin[j] <= p[j] <= bmax[j] for j in range(0, 3))`.

### Ungolfed version with tests, also on Ideone:

```
def solve(i):
    ls = i.splitlines()
    lc = len(ls)

    def axes_pos(x, y):
        return y, x + y, lc - y + x

    I = 2 ** 64
    bmin = (I, I, I)
    bmax = (0, 0, 0)

    for y, line in enumerate(ls):
        for x, char in enumerate(line):
            if char != '#': continue
            p = axes_pos(x, y)
            bmax = tuple(map(max, bmax, p))
            bmin = tuple(map(min, bmin, p))

    result = ''
    for y, line in enumerate(ls):
        for x, char in enumerate(line):
            if char != '.':
                result += char
            else:
                p = axes_pos(x, y)
                f = all(bmin[j] <= p[j] <= bmax[j] for j in range(0, 3))
                result += '#' if f else char
        result += '\n'

    return result

def run_test(a, b):
    result = solve(a)
    if result != b:
        raise AssertionError('\n' + result + '\n\nshould be equal to\n\n' + b)

def run_tests():
    run_test(
        "#\n",

        "#\n")

    run_test(
        " . . \n"
        "# . #\n"
        " . . \n",

        " . . \n"
        "# # #\n"
        " . . \n")

    run_test(
        " . # \n"
        ". . .\n"
        " # . \n",

        " . # \n"
        ". # .\n"
        " # . \n")

    run_test(
        " # . \n"
        ". . .\n"
        " . # \n",

        " # . \n"
        ". # .\n"
        " . # \n")

    run_test(
        " # . \n"
        "# . .\n"
        " . # \n",

        " # . \n"
        "# # .\n"
        " # # \n")

    run_test(
        " . # \n"
        "# . .\n"
        " . # \n",

        " # # \n"
        "# # #\n"
        " # # \n")

    run_test(
        ". . . . . . . . \n"
        " . . # . # . . .\n"
        ". . . . . . . . \n"
        " . . . # . . . .\n",

        ". . . . . . . . \n"
        " . . # # # . . .\n"
        ". . . # # . . . \n"
        " . . . # . . . .\n")

    run_test(
        ". . . . . . . . \n"
        " . . # . . . # .\n"
        ". . . . . . . . \n"
        " . . . # . . . .\n",

        ". . . . . . . . \n"
        " . . # # # # # .\n"
        ". . . # # # # . \n"
        " . . . # # # . .\n")

    run_test(
        ". . . . . . . . \n"
        " . # . . . . . .\n"
        ". . . . . # . . \n"
        " . . . . . . . .\n",

        ". . . . . . . . \n"
        " . # # # # . . .\n"
        ". . # # # # . . \n"
        " . . . . . . . .\n")

    run_test(
        ". . . . . . . . \n"
        " . # . . . . . .\n"
        ". . . . . # . . \n"
        " . . # . . . . .\n",

        ". . . . . . . . \n"
        " . # # # # . . .\n"
        ". . # # # # . . \n"
        " . . # # # . . .\n")

    run_test(
        ". . . . # . . . \n"
        " . # . . . # . .\n"
        ". . . # . . . . \n"
        " . . . . . # . .\n",

        ". . # # # # . . \n"
        " . # # # # # . .\n"
        ". . # # # # # . \n"
        " . . # # # # . .\n")

if __name__ == '__main__':
    run_tests()

```
Update 1:

Removed unnecessary `-1` for third imaginary coordinate, because it doesn't change anything

Update 2,3:

Partially implemented improvements suggested by `Leaky Nun` \+ my own too.

# Answer
> 2 votes
# Python, ~~237~~ 230 bytes

**7 bytes thanks to Dennis.**

```
def f(a):i=range(len(a[0]));j=range(len(a));b,c,d=map(sorted,zip(*[[x,x+y,x-y]for y in i for x in j if"?"<a[x][y]]));return[[[a[x][y],"#"][(a[x][y]>" ")*(b[0]<=x<=b[-1])*(c[0]<=x+y<=c[-1])*(d[0]<=x-y<=d[-1])]for y in i]for x in j]

```

Port of my answer in Pyth.

Takes array of lines as input, outputs 2D array of characters.

# Answer
> 2 votes
# Perl, ~~128~~ 126 bytes

Includes +6 for `-0F\n`

Run with input on STDIN. Use `1` for filled, `0` for empty. Lines do not have to be padded with spaces at the end:

```
perl -M5.010 hexafill.pl
 0 0 0 0 0 0 0 0
0 0 1 1 1 1 0 0
 0 1 1 1 1 1 0 0
0 0 1 1 1 1 1 0
 0 0 1 1 1 1 0 0
0 0 0 0 0 0 0 0
^D

```

`hexafill.pl`

```
#!/usr/bin/perl -0F\n
$-=map{s%$=%$=^!map{/$/;grep{pos=$`;$=?$_|="!"x$`.1:!/\b.*\G./}${--$@}}@F-$-+pos,$-+pos,$-%eeg;--$-;$=||say}@F while$=--

```

Uses cube coordinates. Determine maximum and minimum during the `$= == 1` loop and fills coordinates between these bounds during the `$= == 0` loop. The first 58 loops are pointless and are only there to fill `$-` with the number of lines

# Answer
> 1 votes
# TSQL, 768 bytes

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

**Golfed:**

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

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

```

**Ungolfed:**

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

```

**Fiddle ungolfed**

# Answer
> 1 votes
# GNU Octave, ~~212~~, 196 bytes

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

golfed:

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

```

ungolfed:

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

```

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

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

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

```

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

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

```

---
Tags: code-golf, ascii-art, grid, hexagonal-grid
---


title: “HHeelllloo,, EEaarrtthh!!”

text:
# Question
Title: “HHeelllloo,, EEaarrtthh!!”
Much like this challenge, write a program or function that takes no input and prints or returns the string

```
Hello, Earth!

```

with an optional trailing newline.

The catch is that your program must be an even number of characters long, and each two character chunk of your program must consist of identical characters.

For example, a valid program might look like

```
AAbb==11++♥♥

[[--  2222]]

```

because every two character chunk (`AA`, `bb`, `==`, `11`, etc.) is made of two identical characters (even the newlines).

A program such as

```
AAbB==11++♥♥

[[--  2222]]

```

would not be valid because the `bB` chunk is not made of identical characters.

The only exception to the rule is that `\r\n` should be treated a single, generic "newline" character since replacing it with `\r\r\n\n` wouldn't work or make sense for some languages and systems.

**The shortest code in bytes wins**. The example is 30 bytes long (not 15, not 13).

# Answer
> 6 votes
# Lenguage, 1354616599400377002855073561913010716386821416114463012 bytes

It's 1354616599400377002855073561913010716386821416114463012 zeroes:

```
0000000000000000000000000000000000000000000000000000000000000000000000000000000000...00000000

```

---

It's this BF program:

```
-[------->+<]>-.-[->+++++<]>++.+++++++..+++.[->+++++<]>+.------------.++[->++<]>+.+[------>+<]>.--[--->+<]>---.++.------------.--[--->+<]>-.

```

Converted into binary:

```
001110001001001001001001001010000011111010001100001110001010000000000000000011111010000000100000000000000000000000100100000000000100110001010000000000000000011111010000100001001001001001001001001001001001001100000000110001010000000011111010000100000110001001001001001001010000011111010100001001110001001001010000011111010001001001100000000100001001001001001001001001001001001001100001001110001001001010000011111010001100

```

Converted into a decimal number:

```
1354616599400377002855073561913010716386821416114463012

```

With that many zeroes. Hooray for lenguage!

---
Tags: code-golf, string, kolmogorov-complexity, source-layout, hello-world
---


title: Stringsplode the String!

text:
# Question
Title: Stringsplode the String!
The challenge is relatively simple, but will hopefully lead to some wonderfully creative answers. The task is to take a string as an input (via command line, function parameter etc.) and output/return a stringsploded version of it.

A stringsploded version of a string is its first letter followed by its first 2 letters, followed by its first 3 letters,... until you finally output the complete word.

You are guaranteed that the input will consist of printable ASCII characters and that the input will all be on one line (no new line characters).

Here are examples to clarify what stringsplosions are:

```
Input                 Output
==================================================================
"Code"       ---->   "CCoCodCode"
"name"       ---->   "nnanamname"
"harambe"    ---->   "hhaharharaharamharambharambe"
"sp aces?"   ---->   "sspsp sp asp acsp acesp acessp aces?"
"1234"       ---->   "1121231234"
"ss"         ---->   "sss"

```

This is code golf so shortest code wins + up votes for interesting uses of your respective language.

Good luck!

# Answer
# gs2, 1 byte

# `x`

* `gs2` takes input from STDIN, and pushes it to the stack as a string.
* `x` is the **prefixes** built-in, returning a list of all prefixes of the argument, in ascending-length order.
* The resulting list of strings is implicitly printed one-by-one, without a delimiter, when the program terminates.
> 20 votes

# Answer
## Jelly, 2 bytes

```
;\

```

Acculumate over concatenation gives all prefixes, which Jelly outputs to STDOUT without a delimiter. Try it online!
> 13 votes

# Answer
## Retina, 4 bytes

```
.
$`

```

Expects the input to be terminated with a Windows-style `\r\n` newline (which seems fitting for a .NET-based programming language...).

This can be tested on Regex Storm (which uses `\r\n` newlines). Click the "Context" tab for the result.

This is essentially the same as Jordan's Ruby answer: it replaces each character in the input (including the `\r` but not the `\n`) with all the characters that came before it.
> 8 votes

# Answer
## Java 7, ~~81~~ 78 bytes

```
String g(String a){for(int i=a.length();i>0;)a=a.substring(0,--i)+a;return a;}

```

Straightforward method. Repeatedly prepends the shrinking prefix until it's done.

As a bonus, it should work for non-ASCII as well.

Sample:

```
Input:  ( ͡° ͜ʖ ͡°)
Output: (( ( ͡( ͡°( ͡° ( ͡° ͜( ͡° ͜ʖ( ͡° ͜ʖ ( ͡° ͜ʖ ͡( ͡° ͜ʖ ͡°( ͡° ͜ʖ ͡°)

```
> 8 votes

# Answer
# Jelly, ~~5 4~~ 2 bytes

-2 bytes thanks to @Dennis

```
ḣJ

```

Test it at **TryItOnline**
Or all test cases, also at **TryItOnline**

How?

```
ḣJ - Main link takes one argument, e.g. "Code"
 J    - range(length(input)), e.g. [1,2,3,4]
ḣ    - head, x[:y] (implicit vectorization), e.g. "CCoCodCode"

```
> 7 votes

# Answer
# Brachylog, ~~11~~ 5 bytes

```
:@[fc

```

Try it online!

### Explanation

```
:@[f           Find all prefixes of the input
    c          Concatenate

```
> 5 votes

# Answer
# MATL, ~~9~~ ~~8~~ 6 bytes

*2 bytes saved thanks to @Luis*

```
t&+Rf)

```

**Try it Online!**

**Explanation**

```
t       % Implicitly grab the input and duplicate
&+      % Broadcast and create a 2D matrix with all values > 0
R       % Grab the upper triangular portion (sets the lower triangular values to 0)
f       % Get the linear index for each value > 0
)       % Index into the original string (uses modular indexing)
        % Implicitly display the result

```
> 5 votes

# Answer
# 05AB1E, 3 bytes

```
.pJ

```

**Explanation**

```
.p   # get list of prefixes of input
  J  # join as string

```

Try it online!
> 5 votes

# Answer
# Ruby, 13 + 1 = 14 bytes

+1 byte for `-p` flag. Expects input on STDIN. Requires Windows-style line endings (`\r\n`).

```
gsub(/./){$`}

```

See it on eval.in (a few extra bytes since eval.in doesn't support command line flags): https://eval.in/637093
> 5 votes

# Answer
## Javascript (ES6), ~~28~~ 26 bytes

Recursively appends the shortened strings to the left of the final result:

```
f=s=>s&&f(s.slice(0,-1))+s

```

### Examples

```
var
f=s=>s&&f(s.slice(0,-1))+s

console.log(f("Code"));     //  -->   "CCoCodCode"
console.log(f("name"));     //  -->   "nnanamname"
console.log(f("harambe"));  //  -->   "hhaharharaharamharambharambe"
console.log(f("sp aces?")); //  -->   "sspsp sp asp acsp acesp acessp aces?"
console.log(f("1234"));     //  -->   "1121231234"
```
> 5 votes

# Answer
## JavaScript (ES6), 25 bytes

```
s=>s.replace(/./g,'$`$&')

```
> 4 votes

# Answer
## Haskell, ~~34 29 28~~ 26 bytes

```
reverse=<<scanl(flip(:))[]

```
> 3 votes

# Answer
# Perl, 10 bytes

Includes +1 for `-p`

Run with the input on STDIN:

```
splode.pl <<< "Hello"

```

`splode.pl`

```
#!/usr/bin/perl -p
s/./$`/sg

```

This depends on the input being terminated by a newline. This 11 byte version does not need a final newline:

```
#!/usr/bin/perl -lp
s/.?/$`/g

```
> 3 votes

# Answer
## CJam, 8 bytes

Here's 4 separate ways to get 8 bytes

```
l_,),\f<
l{1$\+}*
l{+_}*co
Ll{+_}/;

```

Credits to @MartinEnder for the last one. Online interpreter.

* `l_,),\f<` creates the range `[0 .. len(s)+1]` then uses `f<` to slice for each number, producing all prefixes.
* `l{1$\+}*` is a fold that duplicates the previous prefix and adds a char to it as it goes.
* `l{+_}*co` is a bit weird - `l{+_}*` is also a fold but it produces the wrong prefixes, skipping the first and doubling the last (e.g. `abcd` -\> `ab/abc/abcd/abcd`, slashes for clarity). We then use `c` to turn the last string into just its first character and output it with `o`, to get the first prefix.
* `Ll{+_}/;` is a for-each loop that also duplicates the previous prefix and adds a char to it as it goes. We have an extra copy of the original string once the loop is over, which we pop with `;`.
> 3 votes

# Answer
# Python, ~~34~~ 28 bytes

Here's my rough attempt with a recursive solution:

```
f=lambda s:s and f(s[:-1])+s

```

Ungolfed:

```
def f(s):
    if s: return f(s[:-1]) + s
    return ''

```

Try it here!

Thanks to @Dennis for -6 bytes.
> 2 votes

# Answer
# C, 49 bytes

```
i;f(char*n){for(i=0;i++<strlen(n);)write(1,n,i);}

```

Try on Ideone
> 2 votes

# Answer
# C#, ~~91~~ ~~87~~ ~~84~~ 83 bytes

```
void c(string n){var b="";for(int i=0;i<n.Length;)System.Console.Write(b+=n[i++]);}

```

Ungolfed:

```
void c(string n)
{
    var b = "";
    for (int i = 0; i < n.Length ; )
    {
        System.Console.Write(b+=n[i++]);
    }
}

```

Thank you Kevin Cruijssen.
> 2 votes

# Answer
## Jellyfish, 5 bytes

```
P,\}I

```

Try it online!

### Explanation

```
    I  # Read input.
  \}   # Get all prefixes.
 ,     # Flatten.
P      # Print.

```
> 2 votes

# Answer
# , 8 bytes

```
òÄ$xhòíî

```

Try it online!
> 2 votes

# Answer
# sed 41

```
h;:;G;s,.\n,\n,;h;s,\n.*,,;/./b;x;s,\n,,g

```
> 2 votes

# Answer
# Sesos, 4 bytes

```
0000000: 8073ec 09                                         .s..

```

Try it online! Check *Debug* to see the generated SBIN code.

### Sesos assembly

The binary file above has been generated by assembling the following SASM code.

```
    jmp, rwd 1, jnz
    fwd 1
    jmp, put, fwd 1, jnz
jnz

```
> 2 votes

# Answer
# R, ~~60~~ 49 bytes

Not going to win any golf, but hopefully no shorter R answer is possible

```
cat(substring(s<-readline(),1,1:nchar(s)),sep="")

```

~~`paste0(substring(s<-readLines(,1),1,1:nchar(s)),collapse="")`~~

Thanks @MickyT
> 2 votes

# Answer
# CJam, 11 bytes

```
q{(L\+:Lo}h

```

Explanation:

```
q                   get input
 {       }h         do while
  (L                get 1st character and variable L (initialized with "")
    \+              swap and concatenate them
      :Lo           store result in L and print it

```

Try it online
> 2 votes

# Answer
# Dyalog APL, 3 bytes

```
∊,\

```

flatten the

`,\` cumulative concatenation

TryAPL online!
> 2 votes

# Answer
# Pyth, 3 bytes

```
s._

```

Explanation:

```
s   (s)um together
 ._ all prefixes

```
> 2 votes

# Answer
# Python 3, 47 bytes

Thanks to @deustice

```
lambda s:''.join(s[:i]for i in range(len(s)+1))

```

**Ideone it!**
> 1 votes

# Answer
# Retina, 24 bytes

Well, I got destroyed by Martin, but here was my solution.

```
1m+`(.*).$
$1$.1$*¶$0
¶

```

**Try it online**
> 1 votes

# Answer
## PowerShell v2+, 43 bytes

```
param($n)-join(1..$n.length|%{$n[0..--$_]})

```

Takes input `$n`, loops from `1` to `$n.length`, each iteration slicing `$n` from `0` up to one less than the current number -- done because `.length` is 1-indexed, while array slicing is 0-indexed. Each iteration places characters on the pipeline, those are encapsulated in parens and `-join`ed together into one string. Output is implicit.

```
PS C:\Tools\Scripts\golfing> .\stringsplode-the-string.ps1 'PPCG'
PPPPPCPPCG

```

---

Alternatively, using Jordan's Ruby submission as a basis, you can get to the following for **22 bytes**

```
$input-replace'.','$`'

```

This feels kinda cheaty, though, since you'd have to explicitly insert a newline into the string that you're piping in, or otherwise do a `Get-Content` or something out of a file that pulls the newlines with it. Valid, but not really common.

```
PS C:\Tools\Scripts\golfing> 'PPCG
' | .\stringsplode-the-string.ps1 $_
PPPPPCPPCG

```
> 1 votes

# Answer
# C ~~71~~ 67 Bytes

```
k;f(v){char*m,*n=v;while(*n++)for(k=0,m=v;k<n-v;k++)putchar(*m++);}

```
> 1 votes

# Answer
## Pyke, 5 bytes

```
FKoh<

```

Try it here!

```
      - o = 0
FK    - for i in input:
  oh  -   1+o++
    < -  input[:^]
      - "".join(^)

```
> 1 votes

# Answer
# Gema, 16 characters

```
?=@append{s;?}$s

```

Sample run:

```
bash-4.3$ echo -n 'sp aces?' | gema '?=@append{s;?}$s'
sspsp sp asp acsp acesp acessp aces?

```
> 1 votes

# Answer
## GNU sed, 30 bytes

```
:;G;h;s/.\n.*//;/./t;g;s/\n//g

```

**Run:**

```
echo -n "name" | sed -f stringsplode.sed

```
> 1 votes

# Answer
# Perl 6,  ~~23~~  16 bytes

```
{S:g/.?/{$/.prematch}/}  # <-- the Perl 5 entry as a Perl 6 lambda
{[R~] m:ex/^.*/}
{[~] m:ex/^.*?/}

```

# Explanation:

```
# bare block lambda with implicit parameter ｢$_｣
{
  # list reduce using string concatenation operator
  [~]

  # the input implicitly matched against
  m

  # in all possible ways
  :exhaustive

  /
    ^   # must match from the beginning
    .   # any character
    *?  # any number of times non-greedily
  /
}

```

The `m:ex/^.*?/` part produces a list of Match values `(｢｣,｢C｣,｢Co｣,｢Cod｣,｢Code｣)`.

The other option `m:ex/^.*/` produces the Match values in exactly the opposite order, so they have to be combined in reverse using the `R` meta operator.
> 1 votes

# Answer
# Lua, 58

```
u=''for s in io.read():gmatch('.')do u=u..s io.write(u)end

```

*Saved 5 Bytes thanks to manatwork*

I love using lua's gmatch and gsub for golfing.

Simply takes io.read(), gmatch's it for any single character, iterating through the entire string. it assigns the variable st, which slowly builds the entire string as lua iterates, and at every iteration, writes the contents of st.
> 1 votes

# Answer
## Go, 90 bytes

```
package main;import."fmt";func main(){s:="";Scan(&s);for i:=0;i<=len(s);i++{Print(s[:i])}}

```
> 0 votes

# Answer
# BASH (grep + sed + tr) 36

```
grep -o .|sed ':;p;N;$!b'|tr -d '\n'

```
> 0 votes

# Answer
# PHP , 52 Bytes

```
for(;$i<strlen($t=$argv[1]);)echo substr($t,0,++$i);

```
> 0 votes

# Answer
# PHP, ~~39~~ ~~37~~ 35 bytes

```
while($c=$argv[1][$i++])echo$s.=$c;

```

works for all examples. String should not countain the `0` character.

# PHP, ~~50~~ ~~40~~ 38 bytes

```
while(''<$c=$argv[1][$i++])echo$s.=$c;

```
> 0 votes

# Answer
# Racket 81 bytes

```
(λ(s)(apply string-append(for/list((i(+ 1(string-length s))))(substring s 0 i))))

```

More readable form:

```
(define(f s)
  (apply
   string-append
   (for/list
       ((i(+ 1(string-length s))))
     (substring s 0 i))))

```

Testing:

```
(f "Code")
"CCoCodCode"

```
> 0 votes

# Answer
# Haskell (lambdabot), 10 bytes

```
join.inits

```

Sample:

```
(join.inits) "Code"
"CCoCodCode"

```
> 0 votes

# Answer
# MATL, 8 bytes

```
"GX@:)v!

```

This uses a different approach from @Suever's answer.

Try it online!

### Explanation

```
        % Implicit input: string
"       % For each. This repeats as many times as chars in the input string
  G     %   Push input again
  X@    %   Push iteration index, k (varies from 1 to input length)
  :)    %   Get k first chars from input
  v!    %   Concatenate all stack contents horizontally
        % Implicit end
        % Implicit display

```
> 0 votes

# Answer
# Japt, 5 bytes

```
Uå+ q

```

Test it online!

### How it works

```
       // Implicit: U = input string
Uå+    // Cumulative-reduce the input by addition.
       // This returns an array of all prefixes.
    q  // Join with the empty string.
       // Implicit: output last expression

```
> 0 votes

# Answer
# Java 7, 74 bytes

```
String h(String a){int l=a.length();return l>1?h(a.substring(0,l-1))+a:a;}

```

or

```
String j(String a){return a.isEmpty()?a:j(a.substring(0,a.length()-1))+a;}

```

Recursive version of Geobits answer.
> 0 votes

---
Tags: code-golf, string
---


title: HexaGolf: Rotatagons

text:
# Question
Title: HexaGolf: Rotatagons
***See also: Wordagons***

## Challenge

Given a hexagon and a number `n` as input, output the same hexagon rotated `n` times.

## Hexagon

The hexagon will be a string like so:

```
  a b c
 d d e e
f f o g g
 h h i i
  j k l

```

The hexagon will always be regular and will only ever contain the printable ASCII characters:

```
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

```

## Rotation

To find how much to rotate the hexagon by, multiply `n` by 60 degrees to get the angle of rotation. For example, using the above hexagon, if `n` is 2, we multiply that by 60 to get 120 degrees. Then, we rotate the hexagon by 120 degrees:

```
  j h f
 k h f d
l i o d a
 i g e b
  g e c

```

Note that each side has moved *two* sides clockwise.

If `n` is positive, you should rotate the hexagon clockwise. If `n` is negative, you should rotate the hexagon anticlockwise.

`n` will always be an integer in the range -6 to 6 inclusive.

## Examples

Input:

```
  . u .
 .  |  .
l - + - r
 .  |  .
  . d .

```

`n` = 3

```
  . d .
 .  |  .
r - + - l
 .  |  .
  . u .

```

---

Input:

```
  - - -
 /     \
<       >
 \     /
  - - -

```

`n` = -1

Output:

```
  - \ >
 -     /
-       -
 /     -
  < \ -

```

---

Input:

```
   h e x a
  g o n s a
 n d t r i a
n g l e s m a
 k e m e s a
  d l y m a
   d d e r

```

`n` = 6

Output:

```
   h e x a
  g o n s a
 n d t r i a
n g l e s m a
 k e m e s a
  d l y m a
   d d e r

```

## Winning

The shortest program in bytes wins.

# Answer
# Perl, ~~120~~ ~~119~~ ~~113~~ ~~107~~ ~~104~~ 102 bytes

Includes +6 for `-0pXi`

Run with the hexagon on STDIN (padded with spaces so all lines have the same length) and the number of rotations after -i.

```
perl -0pXi1 rotagon.pl
  a b c
 d d e e
f f o g g
 h h i i
  j k l
^D

```

`rotagon.pl`

```
s!(.)!$X=(3*($w=y/
//*2)/4+($-="@-"/$w)-"@+"%$w)/2*--$w+2*$--.25;/^\C{$X}(.)/;$1!eg while$^I--%6

```

Finally got the rotation matrix to be shorter than the old double loop
> 1 votes

# Answer
# Python 2, ~~160~~ ~~158~~ ~~156~~ ~~148~~ 124 bytes

***Prepare to be amazed!*** The resulting text is drawn on a canvas... by a `Turtle`! :D

```
from turtle import*
h,n=input()
up()
rt(n*60)
l=0
for c in h:
 write(c);fd(9);l-=1
 if" ">c:fd(9*l);rt(90);fd(15);lt(90);l=0

```

**Try it online** \- Supports decimal rotations as well!

---

If you would prefer the turtle to be shaped like one, you can add the line `t.shape("turtle")`.

View the revision history to see past versions.

**Aliases used**:

`up()` \- `penup()`

`rt()` \- `right()`

`lt()` \- `left()`

`fd()` \- `forward()`

`bk()` \- `backward()`

*Thanks to Sherlock9 for the suggestions!*
> 14 votes

# Answer
# Python 2.7, 151 bytes

```
h,n=input()
s=1-len(h)
e=enumerate
exec n%6*"h=[''.join(c>' 'and h[y-x-3*s/2>>1][x*2+y*6+s>>2]or c for x,c in e(l))for y,l in e(h)];"
print'\n'.join(h)

```

Example:

```
% python2.7 hexarot.py <<<'[["   h e x a   ","  g o n s a  "," n d t r i a ","n g l e s m a", " k e m e s a ","  d l y m a  ","   d d e r   "],-1]'
   a a a a
  x s i m a
 e n r s s a
h o t e e m r
 g d l m y e
  n g e l d
   n k d d

```
> 6 votes

# Answer
## JavaScript (ES6), ~~130~~ 127 bytes

```
f=(s,n)=>n%6?f(s.split`
`.map((s,i,a)=>s.replace(/./g,(c,j)=>(a[(i+z-j)/2+z]||c)[(i+j-z)/2+i]||c,z=a.length>>1)).join`
`,n-1):s

```

Originally based on my answer to Rotate a diamond tiling although I might now be able to rewrite that answer along the lines of this answer.
> 1 votes

---
Tags: code-golf, ascii-art, hexagonal-grid
---


# Question
Title: Sample win/loss data generator based on certain criteria
Lets say we have this existing data:

```
Total - 10
Won   -  7
Lost  -  3
Longest Winning Streak - 5
Longest Losing Streak - 2

```

Now you need to write a function which generates an array of random boolean values (`true` representing a win and `false` representing a loss) which fulfills the above criteria.

So, in this case the output can be any of the following:

```
0011011111
1111101100
1010011111
..........

```

### Rules:

* Solution must be function which takes in `Won, Lost, Longest Winning Streak and Longest Losing Streak` and returns a boolean array or string formed of a boolean array like (`110011001010`). It can also display output instead of returning the generated data.
* You can safely assume there are no ties/draws/no-results.
* This is code-golf so shortest code wins.
* Input format can be in any form (Standard Input/Command-Line,etc.). And the real *input format* should be - `<Won> <Lost> <LWS> <LLS>` where `<..>` are place-holders or they can be separate parameters for the function.. whatever you deem best for your code. The parameter `Total` is unnecessary. So you needn't use it.
* As far as random is concerned, you can see that in the example, there are three (and more) possible outputs. Just output any one at random.
* If you have any other question, ask in the comments below.

## Important - Not any answer as of now is correct.

I provide another example (this one's real data) which is possible but not working with the codes in the current answers:

```
Total - 171
Won   - 111
Lost  -  60
Longest Winning Streak - 10
Longest Losing Streak  - 4

```

Real Data:

```
1110110100111111010000101111111100110001100110111101101011111011011011011111111110110001111011010001101011100101111101001011011110101101001100001111101010110001111110111111

```

Another possible output (Basically the same, just the third and fourth digits are interchanged):

```
1101110100111111010000101111111100110001100110111101101011111011011011011111111110110001111011010001101011100101111101001011011110101101001100001111101010110001111110111111

```

# Answer
> 1 votes
# JavaScript ES6, ~~83 70~~ 63 bytes

```
(b,c,d,e)=>'1'[r='repeat'](d)+'0'[r](e)+'1'[r](b-d)+'0'[r](c-e)

```

Try it online

# Answer
> 1 votes
# Python3 - 239 238 bytes

```
W,L,O,S=map(int,input().split())
from itertools import*
P=lambda A,B:len(max(A.split(str(B)),key=len))
for C in product("01",repeat=W+L):
 C="".join(C)
 if P(C,0)==O and P(C,1)==S and W==C.count("1")and L==C.count("0"):
  print(C)
  break

```

Well, this is way too long, but it works. **Very slow**. Takes the inputs from STDIN as whitespace separated in the same order as OP does.

## Testcases

```
Input: 7 3 5 2
Output: 0011011111

Input: 15 10 15 5
Output: 0000011111111111111100000

```

# Answer
> 0 votes
# Pyth - 33 bytes

```
J_E.W|n/H1hQnJmeShMd.gekrH8mO2sQY

```

Try it online here.

Rejection testing, very slow.

# Answer
> 0 votes
# Java 7, ~~319~~ 317 bytes

```
import java.util.*String c(int a,int b,int c,int d){String r="",w="",l="";List z=new ArrayList();int i,q=a+b-c-d;for(i=;i++<c;w+=1);for(i=0;i++<d;l+=0);for(;a---c>0;z.add(1));for(;b---d>0;z.add(0));Collections.shuffle(z);for(i=0;i<q;r+=z.get(i++));return new StringBuilder(r).insert(new Random().nextInt(q),w+l)+"";}

```

NOTE: The winning streak and losing streak will always be right after one-another, everything else, including their positions in the resulting string, is random.

**Ungolfed & test cases:**

Try it here.

```
import java.util.*;
class M{
  static String c(int a, int b, int c, int d){
    String r = "",
           w = "",
           l = "";
    List z = new ArrayList();
    int i,
        q = a+b-c-d;
    for(i = 0; i++ < c; w += 1);
    for(i = 0; i++ < d; l += 0);
    for( ; a-- - c > 0; z.add(1));
    for( ; b-- - d > 0; z.add(0));
    Collections.shuffle(z);
    for(i = 0; i < q; r += z.get(i++));
    return new StringBuilder(r).insert(new Random().nextInt(q), w+l)+"";
  }

  public static void main(String[] a){
    System.out.println(c(7, 3, 5, 2));
    System.out.println(c(171, 111, 10, 4));
  }
}

```

**Possible output:**

```
1111100011
100100010110111111110011011100101111011010110011011101111010010010101111101111000010010000110100010111001100100110010011101100111111111111110110110101011100111111111100001011111000111011111010010001010001100111110011111011011011101010101011101011011101101001001100100101100111111101

```

# Answer
> 0 votes
## R - (I don't know how to calculate bytes)

```
 a <- read.csv("a.csv")
 b <- seq(1,1, seq.length = a$3)
 a$1 <- a$1-a$3
 c <- seq(0,0, seq.length = a$4)
 a$2 <- a$2 - a$4
 append(b,c)
 d <- a$1 + a$2
 while(d >= 0){append(b,c(1,0)); d <- d-2}
 d

```

where `a.csv` is a file with the four inputs separated by commas. This program will output a long string of `1`'s (for the win streak), and then a long string of `0`'s for the loss streak, and finally a long string of `0,1` for the rest of the games.

---
Tags: code-golf, random, generation
---


title: Conjugate a Turkish verb

text:
# Question
Title: Conjugate a Turkish verb
# Input

* *verb*, a string that matches the regular expression `([a-pr-vyzıöüçğş]*[aeıioöuü][bcçdfgğhj-nprsştvyz]+|([a-pr-vyzıöüçğş]*[aeıioöuü]){2})(mak|mek)`
* *plural*, a truthy or falsy value
* *person*, an integer having value either 1, 2, or 3
* *tense*, an integer having value either 1, 2, or 3

# Output

The conjugated form of the Turkish verb *verb*, in *person*st/nd/rd person, plural if *plural* is `TRUE` and singular if it is not, in

* If *tense* is 1, the simple present;
* If *tense* is 2, the continuing present;
* If *tense* is 3, the future.

# Rules

Turkish verbs are conjugated in three elements, which are in order:

* The *stem*, formed by removing `mak` or `mek` from the end of the infinitive;
* The *sign of the tense*, which is:

+ For the simple present:

    > - *-r* if the stem ends in a vowel;
    >     - *-ir* according to **vowel harmony rules** (see below) if the stem contains more than one syllable (i.e. vowel), or is from one of the following irregular verbs: *almak, bilmek, bulmak, durmak, gelmek, görmek, kalmak, olmak, ölmek, sanmak, vermek, varmak, vurmak*;
    >     - *-er* according to **vowel harmony rules** if the stem contains one syllable and is not listed in the irregular verbs above.
    + For the continuing present, *-iyor*, where the *i* changes according to **vowel harmony rules**. Stems that end in a vowel drop this vowel before adding this suffix, whereupon the suffix harmonizes with the next-to-last vowel in the word (guaranteed to exist by the regular expression).
    + For the future:
    > - *-ecek* according to **vowel harmony rules** if the stem ends in a consonant;
    >     - *-yecek* according to **vowel harmony rules** if the stem ends in a vowel.
* The *personal suffix* to indicate the performer of the action, in all cases according to **vowel harmony rules**:

```
    |Singular|Plural|
|---|--------|------|
|1st|    -im |   -iz|
|2nd|   -sin |-siniz|
|3rd| (none) |  -ler|

```

The final *k* of the future tense becomes *ğ* before *-im* and *-iz*, so for example `(almak, TRUE, 1, 3)` would yield `alacağız`.

# Vowel harmony rules

Turkish vowels are divided into two groups: back (`a ı o u`) and front (`e i ö ü`) by where in the mouth they are pronounced. The suffixes of a word change vowels according to the vowels of the root.

All suffixes listed above that have *i* as a vowel instead use:

* if the last vowel before the suffix is `ı` or `a` (both these vowels are back and unrounded);
* *-i* if the last vowel before the suffix is `i` or `e` (both these vowels are front and unrounded; note here Turkish's distinction between dotted and dotless I);
* *-u* if the last vowel before the suffix is `u` or `o` (both these vowels are back and rounded); or
* if the last vowel before the suffix is `ü` or `ö` (both these vowels are front and rounded).

Take careful note of the present continuous suffix *-iyor*. The `i` harmonizes, but the `o` does not change. The personal suffixes will thus harmonize with the `o`.

All the suffixes listed above that have *e* as a vowel instead use:

* *-e* if the last vowel before the suffix is a front vowel; or
* *-a* if the last vowel before the suffix is a back vowel.

# Irregular verbs

The verbs *gitmek*, *tatmak*, *ditmek*, *gütmek*, and *etmek* change the final `t` to a `d` before any endings that begin with a vowel (which includes all the endings in this challenge). Any verb that ends in *-etmek* likewise changes the `t` to a `d`, and appends *-er* for the simple present (though this is not so for the other verbs).

# Test cases

```
gütmek, FALSE, 1, 2 -> güdüyorum
almak, TRUE, 3, 3 -> alacaklar
boğmak, TRUE, 2, 1 -> boğarsınız
ölmek, FALSE, 3, 1 -> ölür
boyamak, TRUE, 1, 2 -> boyuyoruz
affetmek, FALSE, 2, 1 -> affedersin
söylemek, TRUE, 3, 1 -> söylerler
söylemek, FALSE, 3, 2 -> söylüyor
söylemek, FALSE, 1, 3 -> söyleyeceğim

```

# Answer
> 4 votes
## Javascript (ES6), ~~466~~ ~~456~~ ~~451~~ 446 bytes

```
(v,p,w,t)=>(R=g=>g.exec(s),T=r=>s=s.slice(0,-1)+r,Z=s=>s.replace(/\d/g,c=>l=['ıuiü'[(n='aıoueiöü'.search(l))>>1],'ae'[n>>2]][c]),(s=v.slice(k=l=0,-3)).replace(/[aıoueiöü]/g,c=>(L=l,l=c,k++)),(R(/^(gi|ta|di|gü)t$/)||(R(/et$/)&&(k=1)))&&T`d`,((E=R(/[aıoueiöü]$/))&&t==2?(l=L,T``):s)+Z([(E?'':k<2&!R(/^((k?a|bi|bu|ge|o|ö)l)|dur|gör|san|v[aeu]r$/))+'r','0yor',(E?'y1c1':'1c1')+'ğkk'[--w]][t-1])+Z('0m|0z|s0n|s0n0z||l1r'.split`|`[w+w+p],t-2||(l='o')))

```

### Ungofled and commented

```
// Parameters:
//   - 'v' = verb
//   - 'p' = plural flag
//   - 'w' = person
//   - 't' = tense
(v, p, w, t) => (
  // R() - Helper function to execute a regular expression on the stem.
  R = g => g.exec(s),

  // T() - Helper function to replace the last character of the stem with 'r'.
  T = r => s = s.slice(0, -1) + r,

  // Z() - Function that applies vowel harmony to the string 's', assuming
  //       '0' = 'i' and '1' = 'e' and using the last encountered vowel 'l'.
  Z = s => s.replace(
    /\d/g,
    c => l = [
      'ıuiü' [(n = 'aıoueiöü'.search(l)) >> 1],
      'ae' [n >> 2]
    ][c]
  ),

  // Computes:
  //   - 's' = stem
  //   - 'k' = number of vowels in stem
  //   - 'l' = last vowel in stem
  //   - 'L' = penultimate vowel in stem
  (s = v.slice(k = l = 0, -3)).replace(/[aıoueiöü]/g, c => (L = l, l = c, k++)),

  // Applies ending 't' => 'd' for irregular verbs and those ending in -et(mek).
  (R(/^(gi|ta|di|gü)t$/) || (R(/et$/) && (k = 1))) && T `d`,

  // Computes 'E' = truthy value if the stem ends in a vowel.
  // If 'E' is truthy and the tense is the continuing present, drops this vowel.
  ((E = R(/[aıoueiöü]$/)) && t == 2 ? (l = L, T ``) : s) +

  // Appends sign of tense with vowel harmony.
  Z([
    // t = 1: simple present -> either '-er', '-ir' or '-r'
    (E ? '' : k < 2 & !R(/^((k?a|bi|bu|ge|o|ö)l)|dur|gör|san|v[aeu]r$/) + 'r',

    // t = 2: continuing present -> always '-iyor'
    '0yor',

    // t = 3: future -> either '-yecek', '-ecek', '-yeceğ' or '-eceğ'
    (E ? 'y1c1' : '1c1') + 'ğkk' [--w]
  ][t - 1]) +

  // Appends personal suffix with vowel harmony,
  // forcing last vowel to 'o' for continuing present.
  Z(
    '0m|0z|s0n|s0n0z||l1r'.split `|` [w + w + p],
    t - 2 || (l = 'o')
  )
)

```

### Test cases

```
let f =
(v,p,w,t)=>(R=g=>g.exec(s),T=r=>s=s.slice(0,-1)+r,Z=s=>s.replace(/\d/g,c=>l=['ıuiü'[(n='aıoueiöü'.search(l))>>1],'ae'[n>>2]][c]),(s=v.slice(k=l=0,-3)).replace(/[aıoueiöü]/g,c=>(L=l,l=c,k++)),(R(/^(gi|ta|di|gü)t$/)||(R(/et$/)&&(k=1)))&&T`d`,((E=R(/[aıoueiöü]$/))&&t==2?(l=L,T``):s)+Z([(E?'':k<2&!R(/^((k?a|bi|bu|ge|o|ö)l)|dur|gör|san|v[aeu]r$/))+'r','0yor',(E?'y1c1':'1c1')+'ğkk'[--w]][t-1])+Z('0m|0z|s0n|s0n0z||l1r'.split`|`[w+w+p],t-2||(l='o')))

console.log(f("gütmek", false, 1, 2));    // -> güdüyorum
console.log(f("almak", true, 3, 3));      // -> alacaklar
console.log(f("boğmak", true, 2, 1));     // -> boğarsınız
console.log(f("ölmek", false, 3, 1));     // -> ölür
console.log(f("boyamak", true, 1, 2));    // -> boyuyoruz
console.log(f("affetmek", false, 2, 1));  // -> affedersin
console.log(f("söylemek", true, 3, 1));   // -> söylerler
console.log(f("söylemek", false, 3, 2));  // -> söylüyor
console.log(f("söylemek", false, 1, 3));  // -> söyleyeceğim
```

# Answer
> 4 votes
# sed, 583 bytes

```
sed -E 's/^((bul|dur|k?al|ol|san|v[au]r)ma|(bil|gel|gör|öl|ver)me)k( . .) 1/\2\3Ir\4/;s/etmek( . .) 1/edEr\1/;s/etmek /ed /;s/^((ta)tma|([dg]i|gü)tme)k /\2\3d /;s/m[ae]k / /;s/([aıoueiöüEI])/V\1/g;s/(V.)( . .) 1/\1r\2/;s/(V.+V.+)( . .) 1/\1VIr\2/;s/( . .) 1/VEr\1/;s/(V.)?( . .) 2/VIyVor\2/;s/(V.)( . . 3)/\1y\2/;s/( . .) 3/VEcVEk\1/;s/k( . 1)/ğ\1/;s/ 0 1/VIm/;s/ 1 1/VIz/;s/ 0 2/sVIn/;s/ 1 2/sVInVIz/;s/ 0 3//;s/ 1 3/lVEr/;:l
s/([ıa][^V]*V)I/\1ı/;s/([ie][^V]*V)I/\1i/;s/([uo][^V]*V)I/\1u/;s/([üö][^V]*V)I/\1ü/;s/([aıou][^V]*V)E/\1a/;s/(V[^aEI][^V]*V)E/\1e/;t l
s/V//g'

```

Like my answer to the closely-related Dactylic Hexameter question, this is really just translating the rules as given into regular expressions.

### Usage:

Takes input in the form:

```
word [01] [123] [123]

```

So the test cases are:

```
printf 'gütmek 0 1 2
almak 1 3 3
boğmak 1 2 1
ölmek 0 3 1
boyamak 1 1 2
affetmek 0 2 1
söylemek 1 3 1
söylemek 0 3 2
söylemek 0 1 3' | sed -E '<...>';

```

### Breakdown:

```
sed -E "
# special cases for simple present tense
 s/^((bul|dur|k?al|ol|san|v[au]r)ma|(bil|gel|gör|öl|ver)me)k( . .) 1/\2\3Ir\4/;

# stemming
# always uses -er rule if simple present
 s/etmek( . .) 1/edEr\1/;
 s/etmek /ed /;
 s/^((ta)tma|([dg]i|gü)tme)k /\2\3d /;
 s/m[ae]k / /;

# mark vowels for easier expressions later
 s/([aıoueiöüEI])/V\1/g;

# simple present
 s/(V.)( . .) 1/\1r\2/;
 s/(V.+V.+)( . .) 1/\1VIr\2/;
 s/( . .) 1/VEr\1/;

# continuing present
 s/(V.)?( . .) 2/VIyVor\2/;

# future
 s/(V.)( . . 3)/\1y\2/;
 s/( . .) 3/VEcVEk\1/;

# personal suffix
 s/k( . 1)/ğ\1/;
 s/ 0 1/VIm/;
 s/ 1 1/VIz/;
 s/ 0 2/sVIn/;
 s/ 1 2/sVInVIz/;
 s/ 0 3//;
 s/ 1 3/lVEr/;

# vowel harmony
 :l
 s/([ıa][^V]*V)I/\1ı/;
 s/([ie][^V]*V)I/\1i/;
 s/([uo][^V]*V)I/\1u/;
 s/([üö][^V]*V)I/\1ü/;

 s/([aıou][^V]*V)E/\1a/;
 s/(V[^aEI][^V]*V)E/\1e/;
# keep looping until all vowels are known
 t l

# unmark vowels
 s/V//g
"

```

### Results for test cases:

```
güdüyorum
alacaklar
boğarsınız
ölür
boyuyoruz
affedersin
söylerler
söylüyor
söyleyeceğim

```

---
Tags: code-golf, string, natural-language
---


title: "Cut and Paste Sorting"

text:
# Question
Title: "Cut and Paste Sorting"
**The Challenge**

Given a string containing a random sequence of unique characters A to Z (all upper case, no duplicates), determine the cut-and-paste" sort and output the sort sequence to a specific format (detailed below).

**Definition of Cut-And-Paste Sort, by Example**

Example string: `AKJCFEGHDBI`

This string contains 11 characters, of which `A`, `C`, `E`, `G`, `H`, and `I` form the longest "lengthy sequence" from left to right that is in alphabetic order. So we base the cut-and-paste around these key letters.

If there is more than one "lengthy sequence" of equal length, the code will always favor the lengthy sequence with the biggest "stretch" across the entire string.

In the case of a slightly different string than our original example, `AKGHJCFDEBI`, there are three lengthy sequences of `ACDE`, `AGHJ`, and `AGHI`, but the code will favor the sequence with the greatest stretch, which in this case is `AGHI` because the distance between `A` and `I` is greatest amongst the three as opposed to the `A` to `E` in the first sequence and the `A` to `J` in the second sequence. If there happens to be more than one lengthy sequence with the same stretch length, the first lengthy sequence in alphabetic order will be chosen, just to make it easy.

The cut-and-paste sort is simply a case of plucking the appropriate letters not within the key letters and placing them back in their respective positions in alphabetic order.

Then the sort from our original example would occur as follows:

```
Step 1: AKJCFEGHDBI
Step 2: ABKJCFEGHDI (B gets cut and takes 8 steps to the left and gets pasted after A)
Step 3: ABKJCDFEGHI (D gets cut and takes 4 steps to the left and gets pasted after C)
Step 4: ABKJCDEFGHI (F gets cut and takes 1 step to the right and gets pasted after E)
Step 5: ABKCDEFGHIJ (J gets cut and takes 7 steps to the right and gets pasted after I)
Step 6: ABCDEFGHIJK (K gets cut and takes 8 steps to the right and gets pasted after J)

```

To make it easier for the purpose of this challenge we can rewrite this sort as:

`B<<<<<<<<D<<<<F>J>>>>>>>K>>>>>>>>`

where each letter represents the letter being cut, followed by a series of left or right arrows, represented by the `<` and `>` characters. When the arrows end, it is implied that the letter is pasted.

Bear in mind that the number of letters being cut at any one time can be more than one, so long as the letters are sequential. So if there is a string that can have two or more letters cut at any one time, the code should favor using the larger rather than perform two or more individual cut-and-pastes as this will provide a more efficient cut-paste sort.

For example:

```
AKGHJCFDEBI
Lengthy sequences: ACDE AGHJ AGHI; AGHI is chosen (longest stretch)
Step 1: AKGHJCFDEBI
Step 2: ABKGHJCFDEI (B<<<<<<<<)
Step 3: ABCKGHJFDEI (C<<<<)
Step 4: ABCDEKGHJFI (DE<<<<<)
        Note two or more letters can be moved as long as they are side-by-side
Step 5: ABCDEFKGHJI (F<<<<)
Step 6: ABCDEFKGHIJ (J>)
Step 7: ABCDEFGHIJK (K>>>>)

End result: B<<<<<<<<C<<<<DE<<<<<F<<<<J>K>>>>

```

**Code Behavior**

The code must take an alphabetic upper case string with unique letters (Please assume that this string will always be upper case and with all unique letters, i.e. no dupliates), and perform a cut-paste sort according to the above rules and provide a formatted string simliar to `B<<<<<<<<C<<<<DE<<<<<F<<<<J>K>>>>` providing the method of cutting and pasting respective letters to achieve a string in alphabetic order.

**Test Cases**

`AKJCFEGHDBI` Result: `B<<<<<<<<D<<<<F>J>>>>>>>K>>>>>>>>`

`AKGHJCFDEBI` Result: `B<<<<<<<<C<<<<DE<<<<<F<<<<J>K>>>>`

`BDEFHGI` Result: `H>`

`ABC` Result: (already sorted)

`CBA` Result: `B>C>>`

**Rules**

1. Code Golf: Shortest code wins...
2. Code must be in the form of a piece of STDIN/STDOUT code, or a function taking the input string as a parameter and returning the output string
3. Code must be suported by a working version of the code or verified execution of test cases.
4. In the event that there are two or more with the same character count, the winner will be chosen by the most upvotes.
5. No silly loopholes

# Answer
# PHP, 859 bytes

not the shortest code (yet?), but for shorter output.
Added line breaks for a little reading convenience.

```
function s($u,$a=''){$r=[];for($i=$k=0;$i<strlen($u);$i++)if($u[$i]>substr($a,-1))$r=array_merge($r,s(substr($u,$i+1),$a.$u[$i]));return$r?:[chr(59-strlen($a)).$a];}$w=s($a=$argv[1]);sort($w);$r=preg_split('#_+#',preg_replace("#[$w[0]]#",'_$0_',$a),-1,1);$v=substr;$x=strlen;
for($i=count($r);$i--;)if(!strpos($w[0],$q=&$r[$i]))for($o=0;++$o<$x($q);)if($q[$o-1]>$c=$q[$p=$o]){for(;++$p<$x($q) & $q[$p]>$c & $q[$p]<$q[$o-1];)$c.=$q[$p];echo$c;for(;$q[$o-1]>$v($c,-1);echo'<')$q[--$p]=$q[--$o];$q=$v($q,0,$o).$c.$v($q,$p);$o-=2;}
for(;$n<count($r);$n=count($r),$r=str_split(join($r),1))for($i=-1;++$i<count($r);)if(!strpos($w[0],$r[$i])){$s=array_splice($r,$i,1);for($e=0,$k=$i;$v($s[0],-1)<$r[--$k][0];)$e-=$x($r[$k]);for(;++$k<count($r) & $s[0][0]>$v($r[$k],-1);)$e+=$x($r[$k]);if($e)echo$s[0].str_repeat('><'[$e<0],abs($e));array_splice($r,$k,0,$s);$i-=$k>$i;}

```

**examples**

```
INPUT           KEY     OUTPUT                      RESULT
AKJCFEGHDBI     ACEGHI  B<J<JK>>>>>>>>F>BD<<<<B<    ABCDEFGHIJK
AKGHJCFDEBI     ACDEI   GHJ<GHJK>>>>>F>>>B<<<K>     BCDEFGHJIK
BDEFHGI         BDEFGI  H>                          BDEFGHI
ABC             ABC     _empty_                     ABC
CBA             A       B<BC>                       ABC
PHCODER         CDER    H<HP>O>>P>>>                CHDEOPR
XTREMGOD        EGO     T<R<<RTX>>>>>M>D<<<<        DEGMORTX        (I love it)

```

Yup. It fails for `PHCODER`. It´s buggy, but it´s nice.
btw: The shortest possible output for that is `O<P>>HOP>>>` (for example).
> 1 votes

---
Tags: code-golf, sorting
---


title: Send a cosmic call

text:
# Question
Title: Send a cosmic call
The cosmic call is a message sent into space in 1999 and 2003. It's made of 23 127\*127px monochrome bitmap images, as detailed here.

Your mission is to write a program that displays the entire 127\*2921px message, either as a text (made of zeros, ones and line breaks) or as an image (drawn on screen or saved on disk). There will be two categories of winners: one for text output and one for image output.

All the tricks are permitted, except common loopholes.

It is allowed to output the 23 pages separately.

It is allowed to write up to 23 programs (like, one for each page) and sum their size to determine your score.

It is allowed to use up to 23 binary files alongside your program(s). Their weight is counted in your score.

The shortest code (in byte) wins.

At 1 bit per pixel, the image contains 127\*127\*23/8 = 46370 bytes + 7 bits of data. (warning: it's not allowed to output an extra zero if you store pixel values into 46371 bytes)

Trailing newline/space is allowed for the text output.

Visual output can not contain any black pixel besides the black pixels of the cosmic call. It can be drawn in one column (ordered correctly), or split in 23 images, or animated (like a gif), also ordered correctly.

Attachment: the text output, and the image output to reproduce:

# Answer
> 18 votes
# GIF, 27386 bytes

Here are the pages of the original transmission sliced into individual GIF frames, it turned out not to be as small as 1 PNG of all of them :(

# Answer
> 7 votes
# HTML, 16012b

I compressed the image in PNG8, opened it in a text editor, appended

`<svg onload="document.body.innerHTML='<img src=#>'">`

at the end, and voilà:

Demo: http://xem.github.io/miniCosmicCall/

---

NB: appending just `<img src=#>` works too but it lets a lot of garbage visible, so I prefer not to.

---

PS: for the fun, I also put the entire message in a single, executable tweet (you can copy-paste it in a browser console and the image appears):

https://twitter.com/MaximeEuziere/status/742440423994580992

# Answer
> 6 votes
# Python 2.7 - ~~10971~~ 8077 bytes

**update:**

* LZMA actually for some reason doesn't work for me, so I went back to Deflate.
* I found an online tool to compress the PNG even further (they say they use lossy compression, but the array remains unchanged)
* I golfed the `__main__.py` script a bit more...
* I found I was omitting a step (extracting the data files from zip archive)
* Added DL link (see bottom)

Most compression algorithms look at data as a 1 dimensional array, and therefore cannot capture the repeating 2 dimensional characters displayed in the cosmic call (IMO also makes it harder for aliens to understand too :P).

First, I selected each character as a 7\*5 array and made a list of all unique characters (101 if I recall). Then I iterated over the image, and when a character was found, the position and index of that character (in the character list) were recorded.

Those positions could be represented with a single int, however with over 2K chars found, and positions ranging from 0-370966 (divmod form) require up to 3 bytes each. I collected the character positions in order however, so I instead converted absolute position to offset position, making most of the numbers less than 1 byte. I encoded this list in utf-8 to account for the few numbers that were greater than 1 byte

After recording and removing all the matched characters, I saved the png with maximum compression. I then packaged the python reconstruction script (reverse same process), the png, the chatacter template, and the character position list all into a zip file to take advantage of the fact that python can take a folder or zip file as an argument, and it will begin execution at any file in the top level named `__main__.py`. I played around with 7z a bit to get the best compression, which turned out to be LZMA with a 1M dict and 32bit words.

here's the decoder script (golfed but with comments still)

```
import sys,zipfile as z
z.ZipFile(sys.argv[0]).extractall() #extract data files from zip to cwd
from numpy import*
o=open  #next line overwrites open, which I need
from PIL.Image import*
from scipy.ndimage import*
a=imread('p')[:,:,0]/255 #read image file
a[:2414,0]=0 #draw vertical borders
a[2541:,0]=0
a[2412:,-1]=0
a[:2287,-1]=0
for x in range(0,2921,127):a[[x,x+126],:]=0 #draw horizontal borders
with o('c','rb') as f:t=f.read();C=[int(i)for c in t for i in'{0:08b}'.format(ord(c))] #read character template file and convert to list of bytes
C=array(C[:-1]).reshape([101,7,5]) #re-slice (extra 0 appended to make even number of bytes) and re-shape
with o('l','rb') as f:L=array([ord(x)for x in f.read().decode('utf_8')]).reshape([2158,2]) #read decode and reshape positional list
p=0 #relative position accumulator
for e in L:p+=e[0];x,y=p%127,p/127;a[y:y+7,x:x+5]=C[e[1]] #divmod for x,y position and paste character template onto array at position
i=fromarray(a*255)
i.show()

```
link to download for the zip file...

# Answer
> 3 votes
# ~~Gzip~~ `bzip2` in the shell, ~~20914~~ 18965 bytes

Make the output data file with the text output provided in the question, `bzip2` it and rename the file to `s`. This then allows:

```
bzcat s

```

to do the job. So it adds up to 18958 bytes of data and a 7 byte command.

# Answer
> 3 votes
# Bash + WebP binary, 11 + 15330 = 15341 bytes

As the rules state this:

> Your mission is to write a program that displays the entire 127\*2921px message … or as an image (drawn on screen **or saved on disk**).
>
> **It is allowed to use up to 23 binary files alongside your program(s).** Their weight is counted in your score.

and

> All the tricks are permitted, except common loopholes.

…I could not resist to post something stupidly simple.

The program is in bash and it outputs the image by saving it on disk.
It uses 1 binary file, which also happens to be image file (yeah WebP is an image format), therefore the program can do as little as… make a copy of that file.

So, the code (11 bytes):

```
cp b a.webp

```

Assuming the companion binary is named "b", the code writes the image file to disk with correct extension ("a.webp").

I see little reason to upload the binary, because it's trivially created by running

```
cwebp -z 9 <downloaded input file> b

```

it produces the file with 15330 bytes. If anyone wants, I can upload it somewhere.

NB: `-z` option in `cwebp` activates lossless compression mode. `9` is the compression strength (max).

# Answer
> 2 votes
# Pyth, 46381 bytes

For obvious reasons it cannot be posted here.

```
jc.BC"<too long>"127

```

Sample.

Pastebin of hexdump of program.

# Answer
> 2 votes
## Python 3, 64513 bytes

Use only ASCII !

http://pastebin.com/PMLb4Xti

Old version, 64529 bytes: http://pastebin.com/nteYkUtM

---
Tags: code-golf, kolmogorov-complexity, compression
---


title: A cube of text ݀

text:
# Question
Title: A cube of text ݀
Last time you made a square of text, but now, can you make a **cube** of text?

## The Challenge

Given a string, output the string in the form of a cube.

You can assume the string will always have 2 chars or more, and will only have printable ascii characters.

## How to Make a Text Cube

## Test Cases

```
Input:
Test

Output:
   Test
  e  ss
 s  e e
tseT  T
s  e e
e  ss
Test

Input:
Hello, world!

Output:
            Hello, world!
           e           dd
          l           l l
         l           r  r
        o           o   o
       ,           w    w

     w           ,      ,
    o           o       o
   r           l        l
  l           l         l
 d           e          e
!dlrow ,olleH           H
d           e          e
l           l         l
r           l        l
o           o       o
w           ,      ,

,           w    w
o           o   o
l           r  r
l           l l
e           dd
Hello, world!

Input:
Hi

Output:
 Hi
iHH
Hi

```

## Reference Implementation in Python

```
text = raw_input("Enter a string: ")

print " " * (len(text) - 1) + text

spaces = len(text) - 2
_spaces = spaces

for i in range(1, len(text) - 2 + 1):
    print " " * spaces + text[i] + " " * _spaces + text[(i + 1) * -1] + " " * (_spaces - spaces) + text[(i + 1) * -1]
    spaces -= 1

print text[::-1] + " " * _spaces + text[0]

spaces = _spaces - 1

for i in range(1, len(text) - 2 + 1):
    print text[(i + 1) * -1] + " " * _spaces + text[i] + " " * spaces + text[i]
    spaces -= 1

print text

```

## Rules

* This is , so shortest answer in bytes wins! Tiebreaker is most upvoted.
* Standard loopholes are disallowed.
* Trailing newline and trailing spaces are allowed.

## Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

```
/* Configuration */

var QUESTION_ID = 92410; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 48934; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://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 "https://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,]*[^\s,]),.*?(\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,
      });

  });

  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;
    if (/<a/.test(lang)) lang = jQuery(lang).text();

    languages[lang] = languages[lang] || {lang: a.language, 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 > b.lang) return 1;
    if (a.lang < b.lang) 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);
  }

}
```

```
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;
}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<div id="language-list">
  <h2>Winners by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><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>
```

# Answer
# Pyth, 78 bytes

```
AtBtlQJ_SH
+*dGQVJs[*Nd@Q-GN*dHK@QN*d-HNK;
++_Q*dHhQVJs[@QN*dH@Q-GN*dtN@Q-GN;

```

With trailing newline. Inspired by Joshua de Haan's Python 3 answer.

Try it online here!
> 2 votes

# Answer
# Python 2, ~~228~~ ~~223~~ ~~221~~ ~~203~~ ~~199~~ ~~195~~ 189

```
t=input()
x=" "
l=len(t)-1
q=l-1
f=range(q,0,-1)
print x*l+t
for i in f:print x*i+t[l-i]+x*q+t[i]+x*(q-i)+t[i]
print t[::-1]+x*q+t[0]
for i in f:print t[i]+x*q+t[l-i]+x*(i-1)+t[l-i]
print t

```

# Python 3, ~~192~~ ~~188~~ 182

```
t=input()
x=" "
l=len(t)-1
q=l-1
p=print
f=range(q,0,-1)
p(x*l+t)
for i in f:p(x*i+t[l-i]+x*q+t[i]+x*(q-i)+t[i])
p(t[::-1]+x*q+t[0])
for i in f:p(t[i]+x*q+t[l-i]+x*(i-1)+t[l-i])
p(t)

```
> 4 votes

# Answer
# Ruby, ~~148~~ 144 bytes

+1 byte from the `n` flag. Shows newlines instead of semicolons for readability (same functionality).

```
S=" "
X=S*s=$_.size-2
puts X+S+I=$_,(r=1..s).map{|i|c=I[~i];S*(s-i+1)+I[i]+X+c+S*~-i+c},I.reverse+X+I[0],r.map{|i|c=I[i];I[~i]+X+c+S*(s-i)+c},I

```

Run like so. Input is a line of STDIN, with no trailing newline, so it likely needs to be piped from file.

```
ruby -ne 'S=" ";X=S*s=$_.size-2;puts X+S+I=$_,(r=1..s).map{|i|c=I[~i];S*(s-i+1)+I[i]+X+c+S*~-i+c},I.reverse+X+I[0],r.map{|i|c=I[i];I[~i]+X+c+S*(s-i)+c},I'

```
> 3 votes

# Answer
# x86 (IA-32) machine code, 126 bytes

Hexdump:

```
60 8b f9 57 33 c0 f2 ae 5e 2b fe 4f 87 fa 8d 1c
12 8b c3 48 f6 e3 c6 04 07 00 48 c6 04 07 20 75
f9 8b ea 4d 53 8d 04 2a 50 53 8b c5 f6 e3 8d 44
68 01 50 53 2b c2 8b c8 50 4b 53 55 53 03 c5 50
f7 d3 53 50 53 95 f6 e2 6b c0 04 50 43 53 51 6a
01 4a 52 6a 01 50 6a ff 51 b0 0a 6a 0b 8b dc 59
8b 6c cb fc 88 04 2f 03 2c cb 89 6c cb fc 83 f9
0a 75 01 ac e2 ea 4a 79 e0 83 c4 58 61 c3

```

This is a bit long, so to explain it I'll give C code first:

```
void doit(const char* s, char out[])
{
    int n = strlen(s);
    int w = 2 * n;
    int h = w - 1;
    int m = n - 1;

    memset(out, ' ', h * w);
    out[h * w] = 0;

    int offset1 = n + m;
    int offset2 = w * m + 2 * m + 1; // 2 * n * n - 1
    int offset3 = offset2 - n; // 2 * n * n - n - 1
    int offset4 = 4 * n * m; // 4 * n * n - 4 * n

    int offsets[] = {
        offset3, -1,
        offset4, 1,
        m, 1,
        offset3, 1 - w,
        offset4, -w,
        offset2 - 1, -w,
        offset2 - 1, w - 1,
        m, w - 1,
        offset3, w,
        offset2, w,
        offset1, w,
    };

    do
    {
        char c = *s++;
        for (int i = 0; i < 11; ++i)
        {
            if (i == 9)
                c = '\n';
            int offset = offsets[i * 2];
            assert(offset > 0 && offset < w * h);
            out[offset] = c;
            offsets[i * 2] += offsets[i * 2 + 1];
        }
    } while (--n);
}

```

Here `n` is the length of the input string.

The dimensions of the output area are `2n` (width) by `2n-1` (height). First, it fills everything with spaces (and adds a terminating null byte). Then, it travels along 11 straight lines in the output area, and fills them with text:

* 2 lines are filled with end-of-line bytes (=10)
* 9 lines are filled with the consecutive bytes of the input string

Each line is represented by two numbers, a start offset and a stride. I stuffed them both into the array `offsets`, to make access "easy".

The interesting part is filling the array. There is little importance for the order of the entries in the array; I tried to rearrange them to minimize the number of register conflicts. In addition, quadratic formulas have some freedom in choosing the way of calculation; I tried to minimize the number of subtractions (because additions can be implemented by the flexible `LEA` instruction).

Assembly source:

```
    pushad;

    ; // Calculate the length of the input string
    mov edi, ecx;
    push edi;
    xor eax, eax;
    repne scasb;
    pop esi; // esi = input string
    sub edi, esi;
    dec edi;

    ; // Calculate the size of the output area
    xchg edi, edx;  // edx = n
                    // edi = output string
    lea ebx, [edx + edx]; // ebx = w
    mov eax, ebx;
    dec eax; // eax = h
    mul bl; // eax = w * h

    ; // Fill the output string with spaces and zero terminate it
    mov byte ptr [edi + eax], 0;
myfill:
    dec eax;
    mov byte ptr [edi + eax], ' ';
    jnz myfill;

    mov ebp, edx;
    dec ebp; // ebp = m

    ; // Fill the array of offsets
    push ebx; // w
    lea eax, [edx + ebp];
    push eax; // offset1
    push ebx; // w
    mov eax, ebp;
    mul bl;
    lea eax, [eax + 2 * ebp + 1];
    push eax; // offset2
    push ebx; // w
    sub eax, edx;
    mov ecx, eax; // ecx = offset3
    push eax; // offset3
    dec ebx;
    push ebx; // w - 1
    push ebp; // m
    push ebx; // w - 1
    add eax, ebp;
    push eax; // offset2 - 1
    not ebx;
    push ebx; // -w
    push eax; // offset2 - 1
    push ebx; // -w
    xchg eax, ebp; // eax = m
    mul dl;
    imul eax, eax, 4;
    push eax; // offset4
    inc ebx;
    push ebx; // 1 - w
    push ecx; // offset3
    push 1;
    dec edx; // edx = n - 1
    push edx;
    push 1;
    push eax;
    push -1;
    push ecx;

    ; // Use the array of offsets to write stuff to output
myout:
    mov al, '\n';
    push 11;
    mov ebx, esp;
    pop ecx;
myloop:
    mov ebp, [ebx + ecx * 8 - 4];
    mov [edi + ebp], al;
    add ebp, [ebx + ecx * 8];
    mov [ebx + ecx * 8 - 4], ebp;
    cmp ecx, 10;
    jne skip_read;
    lodsb;
skip_read:
    loop myloop;
    dec edx;
    jns myout;

    add esp, 11 * 8;

    popad;
    ret;

```

I used byte multiplications here, limiting the length of the input string to 127. This avoids clobbering the register `edx` \- the product is calculated in `ax` instead.

A minor glitch: when filling the array, the length of the string gets decreased by 1. So I adjusted the loop exit condition:

```
    jns myout

```

It counts down to -1.
> 3 votes

# Answer
## Javascript, ~~225~~ 198 bytes

Saved 27 bytes thanks to @Neil

```
f=(s,l=s.length-2,d=' ',r='repeat',t=d[r](l))=>[d+t+s,...a=[...Array(l)].map((_,i)=>d[r](l-i)+s[i+1]+t+(p=s[l-i])+d[r](i)+p),[...s].reverse().join``+t+s[0],...a.map(v=>v.trim()).reverse(),s].join`
`

```
* \[...\] instead of .concat
* \[...\]+map instead of *for* loop
* only one statement by moving variables as function parameters
* better initialization for *l* and *t*

**Original answer:**

```
f=s=>{l=s.length,d=' ',r='repeat',a=[],t=d[r](l-2)+s;for(i=1;i++<l-1;)a.push(d[r](l-i)+s[i-1]+d[r](l-2)+(p=s[l-i])+d[r](i-2)+p);console.log(d+[t].concat(a,[...t].reverse().join``+s[0],a.map(v=>v.trim()).reverse(),s).join`
`)}

```
> 1 votes

# Answer
# Java 7, 283 bytes

```
void a(String s){int h=s.length(),n=h*2-1,t=n-h,u=n-1;char[][]c=new char[n][n];for(int i=0;i<h;i++){c[0][t+i]=c[i][t-i]=c[t][t-i]=c[t+i][t]=c[t+i][u-i]=c[t-i][t+i]=c[t-i][u]=c[u][i]=c[u-i][0]=s.charAt(i);}for(int y=0;y<n;y++){System.out.println(new String(c[y]).replace('\0',' '));}}

```

**Try it here!**

**Ungolfed:**

```
void a(String s) {
    int length=s.length(),
        n=length*2-1,
        mid=n-length,
        doubleMid=n-1;
    char[][]c=new char[n][n];
    for(int i=0;i<length;i++) {
        c[0][mid+i]=
        c[i][mid-i]=
        c[mid][mid-i]=
        c[mid+i][mid]=
        c[mid+i][doubleMid-i]=
        c[mid-i][mid+i]=
        c[mid-i][doubleMid]=
        c[doubleMid][i]=
        c[doubleMid-i][0]=s.charAt(i);
    }
    for(int y=0;y<n;y++){
        System.out.println(new String(c[y]).replace('\0',' '));
    }
}

```
> 0 votes

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


title: The Extreme Voters

text:
# Question
Title: The Extreme Voters
## Challenge

Output the person on PPCG who has cast the most upvotes and the person who has cast the most downvotes.

## Voters

You should only look at the people who have cast more than 1000 votes in total.

To find the person who upvotes the most, you should the find the person with the highest `upvotes/total votes` value. Similarly, the person who downvotes the most has the highest `downvotes/total votes` value.

## Rules

Your output should be the two users' id (the number found in the URL of the user's page). You must put the upvoter first.

In the case of a tie, you must choose the user whose id is the lowest.

The Stack Exchange API is allowed, but entries in T-SQL using the Stack Exchange Data Explorer are disallowed.

## Winning

The shortest code in bytes wins.

# Answer
> 4 votes
# Java, 1106 bytes

```
import java.io.*;import java.util.regex.*;()->{String u="",y="",z="",s,t;float h=0,a,l=0,d;int i=-1,k=-1;Matcher m;Pattern p=null;while(i<=k){try(BufferedReader g=new BufferedReader(new InputStreamReader(new java.net.URL("https://codegolf.stackexchange.com/users"+(k==-1?"?tab=NewUsers&sort=creationdate":"/"+i+"/?tab=topactivity")).openStream()));){while((s=g.readLine())!=null){Integer v=0;if(k==-1&s.contains("users/")&!s.contains("profile-me")){m=p.compile("(?<=users/)(\\d+)").matcher(s);if(m.find()){k=v.parseInt(m.group());break;}}if(s.contains("User")){m=p.compile("(?<=User )(.*)(?= - P)").matcher(s);if(m.find())u=m.group();}if(s.contains("Cast")){m=p.compile("(?<=\\>\\().*(?=\\)\\<)").matcher(s);if(m.find()&&(v=v.parseInt(m.group().replace(",","")))>1000){while(1>0){s=g.readLine();m=p.compile("(\\d*,?\\d+)(?=\\<.*\\>)").matcher(s);if(m.find()){if((t=g.readLine()).contains("up")&&(a=0f+v.parseInt(m.group().replace(",",""))/v)>h){y=""+u;h=a;}if(t.contains("down")){if((d=0f+v.parseInt(m.group().replace(",",""))/v)>l){z=""+u;l=d;}break;}}}}}}}catch(Exception e){}}System.out.print(y+"\n"+z);}

```

As a full class:

```
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.regex.*;

public class C {
    public static void main(String[] args) throws Exception {
        String u="", y="", z="", s, t;
        float h = 0, a, l = 0, d;
        int i = -1, k = -1;
        Matcher m;
        Pattern p = null;
        while (i < k) {
            // System.out.println(i);
            try (BufferedReader br = new BufferedReader(new InputStreamReader(new URL("https://codegolf.stackexchange.com/users" + (k == -1 ? "?tab=NewUsers&sort=creationdate" : "/" + i + "/?tab=topactivity")).openStream()));) {
                while ((s = br.readLine()) != null) {
                    Integer v = 0;
                    if (k == -1 && s.contains("users/") && !s.contains("profile-me")) {
                        m = p.compile("(?<=users/)(\\d+)").matcher(s);
                        if (m.find()) {
                            k = v.parseInt(m.group());
                            break;
                        }
                    }
                    if (s.contains("User")) {
                        m = p.compile("(?<=User )(.*)(?= - P)").matcher(s);
                        if (m.find())
                            u = m.group();
                    }
                    if (s.contains("Cast")) {
                        m = p.compile("(?<=\\>\\().*(?=\\)\\<)").matcher(s);
                        if (m.find() && (v = v.parseInt(m.group().replace(",",""))) > 1000) {
                            while (true) {
                                s = br.readLine();
                                m = p.compile("(\\d*,?\\d+)(?=\\<.*\\>)").matcher(s);
                                if (m.find()) {
                                    if ((t = br.readLine()).contains("up") && (a = 0f + v.parseInt(m.group().replace(",",""))/v)>h) {
                                        y = ""+u;
                                        h = a;
                                    }
                                    if (t.contains("down")) {
                                        if ((d=0f + v.parseInt(m.group().replace(",",""))/v)>l) {
                                            z = ""+u;
                                            l = d;
                                        }
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {}
        }
        System.out.print(y+"\n"+z);
    }
}

```

One word: Damn.

I mean, I've always wanted to do a challenge like this, but boy was it a doozy.

I didn't use the Stack Exchange API (don't know what it is, where to access it, or how to use it :P), so I basically had to do everything on my own; having the program crawl through each of the nearly 60,000 PPCG users' profile pages for the right data, looking up the HTML scripts and accounting for how the vote totals were laid out differently for different users1, and debugging (which was, perhaps unsurprisingly, a *huge* pain). And let me just say, this code could probably use some *serious* optimization. It takes well over two hours for the program to finish running on my machine, though most of the time is probably used opening the connections to the sites.

So here's a quick rundown of how it works:

1. Create `String` variables to hold the upvotingest and downvotingest users on PPCG.
2. Figure out the total number of active (and deleted/nonexistent) user accounts there are on the site. The program visits https://codegolf.stackexchange.com/users?tab=NewUsers&sort=creationdate and looks for the first user on the page, who happens to be the most recent addition to the community, and as such has the highest ID number. This ID number is set to be the total number of iterations for the loop.
3. Start at ID 1 and visit https://codegolf.stackexchange.com/users/#, where the pound symbol represents the ID. Parse the HTML code (with regex͠,̰ nőͣ l͇̪e̐̃s̸͖̚͜͝s̡͍̲̫̋ͯ) and collect the user's username, vote total, upvote total, and downvote total.
4. Check to see if the upvotes to total votes ratio is larger than the current largest ratio, and set the current ratio to the new ratio if necessary. Do the same for the downvotes to total votes ratio, and also set the upvotingest and downvotingest user names when needed.
5. Do steps 3 and 4 another (near) 60,000 times, incrementing the ID each time. (This takes care of the event when there is a tie.) If the user doesn't exist, either nothing matches or an Exception is thrown, and move on.
6. Print the upvotingest and downvotingest users.

Yes, there are quite a few places where I can shave off a few bytes (especially on the strings where I use the `contains` method), but I'll save that for later... maybe.

If you decide to run this program, be prepared to wait a couple hours for it to finish execution.

Here's a screenshot of the output:

In case it's difficult to read, at the bottom it says...

```
gnat
Peter Taylor

```

...and the total time it took for the program to finish: a whopping two hours, forty-eight minutes, and twenty-three seconds!

---

1 The instance on which this occurred had to do with how recently the user voted. If the user voted at least once within the past week or month, two(?) additional stats showing how many times they voted over the past week or month appear on their activity page.

---
Tags: code-golf, internet
---