title: The Cake Cutting Contest

text:
# Question
Title: The Cake Cutting Contest
It's my 17th birthday and you're invited to my party!

And as always at parties, there will be cake.

One cake...

And you need as much of it as possible.

As this is a fair party, each of us will say how much of my cake we want and the person who said the smallest amount will get it. Then everyone else gets to repeat the process until the cake is gone.

# Challenge

* Given the input through command line arguments in the form of `total-degrees degrees-left total-people people-left`, output to standard output `integer-bid-in-degrees`.
* If your bid was the lowest, you receive that amount of cake and are out for the round.
* If your bid wasn't lowest, your bot gets to bid on the remaining cake.
* In the case that the lowest bids are the same, the person removed will be chosen at random.
* At the end of a round, once all the cake is gone or there is nobody left to bid on it, the person with the most cake wins!
* In the case at the end of a round and two people have the same sized biggest slice, the winner is chosen at random from the drawing entries.

# Gameplay

* There will be 17 rounds, the overall winner will be the entry with the most wins overall.
* In the case of a draw, rounds will be played until there is a clear winner.
* Each day, I will update the current scores so that people can upgrade their entry.

# Submission

You should write your entry as

> Bot Name, Language
>
> ```
> Insert
> Code
> Here
>
> ```
>
> Explanation/Random stuff here

If your entry isn't formatted in this way, the controller will NOT be able to run your entry. If I find this has happened to your entry, I will either notify you in a comment, and/or edit the answer into the correct format.

# Your entry and file storage

* Your bot may store files in the `./data/` directory and nowhere else.
    + Not required but please store your files as `botname*`
    + You may not write files in this format if `botname` is not your entries name.
    + This means you are allowed to overwrite other files you find that don't appear in this format. You shouldn't do this deliberately, please be sporting.
    + Your bot must not assume that the files it requires are present but it can assume `./data/` exists.
    + This is because I occasionally wipe the `./data` directory, I **will** do this when the rounds actually start. (But not between them)
* Your bot may not delete files at all
* Your bot is only allowed to read files in the `./data/` directory
    + This means you *may* look at other entries files

# Results:

**Meek won the contest! Well done @Cabbie407**

And now for some random stats:

A list of positions each bot came in: (Well done to any bot appearing in this list, you came in the top 5 at least once!)

1. Meek, Meek, Eidetic, Eidetic, Meek, Eidetic, Eidetic, Meek, Meek, Meek, Saucy, Meek, Givemethecake, Givemethecake, Givemethecake, Meek, Eidetic
2. Eidetic, Eidetic, Meek, AlCakeSurfer, Eidetic, AlCakeSurfer, Meek, MyFairPlusAThird, Eidetic, Eidetic, Eidetic, Eidetic, MyFairPlusAThird, MyFairPlusAThird, Meek, MyFairPlusAThird, AlCakeSurfer
3. Reallythecake, AlCakeSurfer, AlCakeSurfer, Meek, AlCakeSurfer, Meek, AlCakeSurfer, AlCakeSurfer, Reallythecake, AlCakeSurfer, Meek, MyFairPlusAThird, Eidetic, Eidetic, Eidetic, Eidetic, Reallythecake
4. AlCakeSurfer, Reallythecake, MyFairPlusAThird, MyFairPlusAThird, MyFairPlusAThird, MyFairPlusAThird, MyFairPlusAThird, Eidetic, AlCakeSurfer, MyFairPlusAThird, MyFairPlusAThird, Relinquisher, Relinquisher, bill, bill, Relinquisher, MyFairPlusAThird
5. bill, MyFairPlusAThird, bill, bill, bill, bill, Relinquisher, Relinquisher, MyFairPlusAThird, Relinquisher, bill, Reallythecake, bill, ALittleOffTheTop, ALittleOffTheTop, bill, bill

The full log file for the cometition whilst running can be found here. Sorry about the format change partway through.

**I will not be running the contest again, if you want to post more entries, you're welcome to do so, the controller can be found on my github repo for this contest.**

# Answer
# Meek, awk

```
BEGIN{srand();print int(rand()>=.5?ARGV[2]/2.89:ARGV[1]/10-rand()*13)}

```

I saw this once in a simulation.
> 5 votes

# Answer
# Magician, Java

```
public class Magician{
    public static void main(String[] args){
        System.out.println(720);
    }
}

```

The number 720 is magical.

This ~~is~~ was meant to test the controller and is ~~not~~ a serious entry.
> 13 votes

# Answer
# Slim, Python 2

```
print 0

```

This bot's on a diet.
> 10 votes

# Answer
# SadBot :(, C++

```
#include<iostream>
#include<cstdlib>
#include<stdlib.h>
int main(int argc, char**argv)
{
    if (argc!=5){std::cout<<"Incorrect number of arguments";return 1;}
    double list[4];

    list[0]= atof(argv[1]); // total Degrees
    list[1]= atof(argv[2]); // degrees left
    list[2]= atof(argv[3]); // total people
    list[3]= atof(argv[4]); // people left

    std::cout<<list[1]/list[3]; // degrees left/ people left

    return 0;
}

```

**Formerly FairBot**

FairBot just wants an equal portion :(

He wants to split the cake evenly amongst all the participants.

(He fully expects the other bots to rip him off though because he knows they're mean)

(Like really. He is lonely, he just wants the other bots to like him)

(He just got out of a bad relationship and is going through a really rough patch, so if you could just give him a pat on the back and a smile to make him feel better it would really mean a lot. )

**EDIT** changed program to take input from argv/c instead of stdin (fair bot is still sad.... He wants to change his name to sadbot (which is kinda why he wants cake))
> 10 votes

# Answer
# Halver, Ruby

```
def halver(total_degrees, degrees_left, total_people, people_left)

  if people_left == 1
    degrees_left
  else
    degrees_left/2 - 1
  end

end

p halver(*ARGV.map(&:to_i))

```

Scrupulously, unimpeachably fair. Half the cake for me, half the cake for everyone else.
> 9 votes

# Answer
# CharityBot, Python 2

```
print -360

```

Adds another cake to the mix!

(The controller will see this as a request for 0 cake, will not actually add to the size of the cake)
> 8 votes

# Answer
# Dieter, Java

```
public class Dieter {
    public static void main(String... args){
        System.out.println("4");
    }
}

```

It doesn't want to bid for too much cake, so it chooses a small but guaranteed random slice.
> 7 votes

# Answer
# Stately Imitator, Ruby

```
def stately_imitator(total_degrees, degrees_left, total_people, people_left)

  current_winner_path = './data/current_winner'
  previous_cake_path = './data/previous_cake'

  first_move = (total_people == people_left)

  current_winner = first_move ? 0 : File.read(current_winner_path).to_i
  previous_cake = first_move ? total_degrees : File.read(previous_cake_path).to_i

  last_slice = previous_cake - degrees_left
  current_winner = [current_winner, last_slice].max

  File.open(previous_cake_path, 'w') { |f| f.puts(degrees_left)   }
  File.open(current_winner_path, 'w'){ |f| f.puts(current_winner) }

  if first_move
    degrees_left / 2
  else
    average_left = degrees_left.fdiv(people_left).ceil
    bid = [average_left, current_winner+1].max
    [bid, degrees_left].min
  end

end

p stately_imitator(*ARGV.map(&:to_i))

```

Variant of Imitator (if you'd rather only one entry per player, this supersedes that one). Keeps precise track of the largest slice taken already, and always bids enough to beat that slice. Will also never bid lower than its fair share of the remainder. Assumes a read/writable './data' directory already exists; the files can either be there already or not.
> 7 votes

# Answer
# Flaming Chainsaw, Java

```
public class FlamingChainsaw
{
    public static void main(String[]args)
    {
        if(args.length<4){return;}
        if(Integer.parseInt(args[3])<3){System.out.println(0);}
        else{System.out.println(args[1]);}
    }
}

```

Have you ever tried holding a cake-cutting contest with a chainsaw? Well, now you have. It's rather disruptive.
> 5 votes

# Answer
# Gentleman, Java

```
import static java.lang.Integer.parseInt;
import java.io.*;
import java.util.*;

public class Gentleman{
    private final static String FILE_NAME = "data/Gentleman.txt";

    static {
        new File("data").mkdir();
    }

    public static void main(String[] args) throws Exception{
        int totalCake = parseInt(args[0]);
        int cakeLeft = parseInt(args[1]);
        int totalPeople = parseInt(args[2]);
        int peopleLeft = parseInt(args[3]);

        if (totalCake == cakeLeft){
            System.out.println(cakeLeft);
        } else {
            int previousCake = load();
            int cakeDiff = previousCake - cakeLeft;

            if (cakeDiff > optimal(previousCake, peopleLeft + 1)){
                System.out.println(peopleLeft == 1 ? cakeLeft : Math.min(cakeLeft, cakeDiff + 1));
            } else {
                System.out.println(cakeLeft);  //Hey, I might get lucky :)
            }
        }
        save(cakeLeft);
    }

    private static void save(int cake) throws Exception{
        PrintStream out = new PrintStream(FILE_NAME);
        out.print(cake);
    }

    private static int load() throws Exception{
        Scanner in = new Scanner(new File(FILE_NAME));
        return in.nextInt();
    }

    private static int optimal(int cake, int people){
        return (cake + people - 1) / people;
    }
}

```

He waits for people who eat a fair share or less before he eats any cake. To prevent the greedy from getting extra cake, he takes as large a portion as possible.
> 5 votes

# Answer
# Bob Barker, Java

```
public class BobBarker{
    public static void main(String[] args){
        System.out.println((int)Math.floor(Integer.parseInt(args[1]) * .84));
    }
}

```

This is probably going to be replaced with a more thought-out solution later, but I'm curious if this will work. This is just to catch any bots that try and go for maximum, and do a modified Price is Right strategy to steal their answer. Might lead to escalation with increasing integer subtractions, that'd be neat.

EDIT: Escalation commences, counter-posting against FloorBot
> 4 votes

# Answer
# Eidetic, Python 2

```
import random, math, sys, json

total_degrees, degrees_left, total_people, people_left = map(int, sys.argv[1:])
#try:
#    inp_f = open("./data/Eidetic.json", "r")
#    out = json.load(inp_f)
#except (IOError, ValueError):
out = {"last_cake": 0,
           "runs": 0,
           "total_runs": 0,
           "total_rounds": 0,
           "training":  [[0.0], [0.0], [0.12903225806451613], [16.774193548387096], [400.83870967741933], [720.0], [995.8709677419355], [996.9437634408603], [997.6], [997.6], [997.6], [998.5991397849463], [996.6770967741936], [998.8122580645161], [1011.5467420570814], [1017.7717824448034], [1227.155465805062], [1280.7840603123318], [1435.8028540656974], [1553.3689822294023], [1793.5330640818527], [2299.178101402373], [3183.924709689701], [2231.666666666667], [2619.4789644012944], [1270.9288025889969], [741.2718446601941], [480.4757281553398], [122.66990291262135], [27.54736842105263]]}

#else: inp_f.close()

def write_out():
    out_f = open("./data/Eidetic.json", "w")
    out_f.write(json.dumps(out))
    out_f.close()

def get_last_winner(): # Find the bid of the last winner
    bid = out["last_cake"]
    return max(bid, degrees_left) - degrees_left

def train():
#    print degrees_left # If you get that much, your probably safe.
#    sys.stderr.write("\nEidetic - Training len %s, no runs: %s, no_rounds: %s, last winner: %s\n"%(len(out["training"]), out["runs"], out["total_rounds"], get_last_winner()))
    if len(out["training"]) <= out["runs"]: out["training"].append([])
    out["training"][out["runs"]].append(get_last_winner())

def get_best_round():
    data = out["training"][out["runs"]+1:]
    mean = [sum(i)/(float(len(i)) or 1) for i in data]
    bid = max(mean+[0]) - 0.5
    sys.stderr.write("\nEidetic - mean %s\n"%mean)
    return bid

def main():
    reset = total_people == people_left
    if reset:
        out["total_rounds"] += 1
        out["runs"] = 0
    train()
    bid = get_best_round()
    print bid
#    sys.stderr.write('\nEidetic Bid: '+str(bid)+'\n')
    out["total_runs"] += 1
    out["runs"] += 1
    out["last_cake"] = degrees_left
    write_out()

main()

```

I ran this bot in the controller a couple of times to train it up a bit, it remembers the bids required to win each round and then once trained, it goes out into the real world and votes with the rest of them.
> 4 votes

# Answer
# CoffeeJunkie, Coffeescript

#!/usr/bin/env node

# Require node fs
fs = require("fs")

# Happy birthday ;)
CAKECONSTANT = Math.round("""
                 /
               ,( ),
                 Y
                |-|
                | |
       _..--''''| |''''--.._
     .'   @_/-//-//>/>'/ @  '.
    (  @  /_<//<'/----------^-)
    |'._  @     //|###########|
    |~  ''--..@|',|}}}}}}}}}}}|
    |  ~   ~   |/ |###########|
    | ~~  ~   ~|./|{{{{{{{{{{{|
     '._ ~ ~ ~ |,/`````````````
        ''--.~.|/

""".length / 250 + Math.random())

# Some constants
OLD = "./data/CoffeeJunkie_oldcake.txt"
NEW = "./data/CoffeeJunkie_newcake.txt"

# How much cake do I want?
wantCake = (total_c, rest_c, total_p, rest_p) ->
    round = total_p - rest_p
    fairness = rest_c // rest_p

    switchMemory() if round is 0

    fairest_round = tryToRemember(total_p)
    tryToMemorize(fairness)

    if round >= fairest_round then fairness - CAKECONSTANT else total_c // 2

# Ok I should try to remember the last cake...
switchMemory = () ->
    try
        fs.renameSync(NEW, OLD)
    catch error

# What happend with the last cake?
tryToRemember = (rounds) ->
    try
        last_cake = fs.readFileSync(OLD, "utf-8")
        last_cake.trim().split(" ").map(
            (i) -> parseInt(i)
        ).reduce(
            (x, y, z, li) -> if y > li[x] then z else x
            0
        )
    catch error
        rounds / 2

# Watch what happens!
tryToMemorize = (fairness) ->
    try
        fs.appendFileSync(NEW, " " + fairness)
    catch error

# Coffee is ready, so... GO!
console.log(wantCake(process.argv[2..]...))

What exactly is a cake without a good cup of coffee?

The CoffeeJunkie prefers coffee over a slice of cake, but nevertheless wants to try some. He will always be fair to other participants and will try to remember what happened to the last cake. However, his excessive coffee consume has weakened his memories...
> 3 votes

# Answer
# Saucy, Ruby

```
def saucy(total_degrees, degrees_left, total_people, people_left)

  current_winner_path = './data/saucy_current_winner'
  previous_cake_path = './data/saucy_previous_cake'

  first_move = (total_people == people_left)

  current_winner = first_move ? 0 : File.read(current_winner_path).to_i
  previous_cake = first_move ? total_degrees : File.read(previous_cake_path).to_i

  last_slice = previous_cake - degrees_left
  current_winner = [current_winner, last_slice].max

  File.open(previous_cake_path, 'w') { |f| f.puts(degrees_left)   }
  File.open(current_winner_path, 'w'){ |f| f.puts(current_winner) }

  if first_move
    degrees_left
  else
    average_left = degrees_left.fdiv(people_left).ceil
    beats_past_players = current_winner + 1
    beats_future_players = degrees_left/4 - people_left**2
    [average_left, beats_past_players, beats_future_players].max
  end

end

p saucy(*ARGV.map(&:to_i))

```

Saucy is willing to accept slightly less than half of the remaining cake, so long as it's more than anyone else has gotten or is likely to get (based on secret sauce).
> 3 votes

# Answer
## AlCakeBot, Python

```
import sys, math

total_degrees, degrees_left, total_people, people_left = map(int, sys.argv[1:])

fraction_left = (degrees_left + 0.0)/ total_degrees
fraction_gone = 1.0 - fraction_left

factor = (math.sin(fraction_gone * math.pi / 2.0))**2
fraction = (factor/2.0) + 0.5

if total_degrees == degrees_left:
   print(int(math.floor(total_degrees/2.0) - 1))
else:
   print(int(math.floor(degrees_left * fraction)))

```

This is my first PCG post; I hope this works out as intended …

I love cake. No matter which kind. My colleagues know. And so does my bot. If the entire cake is still there, he will bid for just under half of it, hoping to get the biggest slice immediately. If not, he should bid for something between half the remaining cake and all the remaining cake, using a squared sine as a weighting function (`½ + sin² (fraction gone) / 2`). The reasoning being that there should be a chance for an overall larger (but fractionally smaller) slice early in the game and there also being little point in trying to be a gentleman in the late game.

Since I’m not very much into programming, I’ll appreciate any error pointed out. Now let’s eat some cake =D
> 3 votes

# Answer
# IWMBAICBIWT, Python

```
import sys

degreesleft = int(sys.argv[2])
peopleleft = int(sys.argv[4])

print(round(degreesleft/peopleleft))

```

IWMBAICBIWT (It was my birthday and I cried because I wanted to) assumes that there is a relationship between the degrees left and the number of people left. Let's hope it works!

Should work in all Pythons.

## Edit:

Storing `sys.argv` in inputs was a bit wasteful...
> 2 votes

# Answer
# Stately Sabotage, Ruby

```
def stately_sabotage(total_degrees, degrees_left, total_people, people_left)

  current_winner_path1 = './data/current_winner'
  previous_cake_path1 = './data/previous_cake'
  current_winner_path2 = './data/statelysabotage-current_winner'
  previous_cake_path2 = './data/statelysabotage-previous_cake'

  first_move = (total_people == people_left)

  current_winner = first_move ? 0 : File.read(current_winner_path2).to_i
  previous_cake = first_move ? total_degrees : File.read(previous_cake_path2).to_i

  last_slice = previous_cake - degrees_left
  current_winner = [current_winner, last_slice].max

  File.open(previous_cake_path2, 'w') { |f| f.puts(degrees_left)   }
  File.open(previous_cake_path1, 'w') { |f| f.puts(total_degrees) }
  File.open(current_winner_path1, 'w'){ |f| f.puts(current_winner) }
  File.open(current_winner_path2, 'w'){ |f| f.puts(1) }

  if first_move
    (degrees_left / 2) - 1
  else
    average_left = degrees_left.fdiv(people_left).ceil
    bid = [average_left, current_winner+1].max
    [bid, degrees_left].min
  end

end

p stately_sabotage(*ARGV.map(&:to_i))

```

> This means you are allowed to overwrite other files you find that don't appear in this format. You shouldn't do this deliberately, please be sporting.

This bot decided that in order to eliminate competition, it should not be sporting.

This is a clone of Stately Imitator, except that this one messes up Stately Imitator's persistence files (as they aren't prefixed with the bot name) so that it makes the wrong decisions and is chosen last.
> 2 votes

# Answer
# Trader, R

```
args <- sapply(commandArgs(TRUE),as.integer)
fraction <- args[2]/args[4]
if(args[3]==args[4]){
    cat(fraction, "\n", file="data/trader.txt")
}else{
    cat(fraction, "\n", file="data/trader.txt", append=TRUE)
}
history <- scan(file="data/trader.txt", quiet=TRUE)
if(tail(history,1) != max(history)){
    cat(floor(fraction)-1)
    }else{
        cat(args[2])
        }

```

Keeps track of the evolution of the degrees left vs people left ratio and when that ratio starts lowering, it asks for a reasonably fair slice, otherwise asks for the whole remaining cake. Invoked using `Rscript trader.r total-degrees degrees-left total-people people-left`.
> 2 votes

# Answer
# guest, Python 2

```
print ord('d')*4

```
> 2 votes

# Answer
# bill, Python 2

```
import sys
t,r,p,s=map(int,sys.argv[1:])
print(t-ord('d')*4)/(ord('\n')+ord('\t'))

```

A fairish bet.
> 2 votes

# Answer
## AlCakeSurfer, Python

```
import sys, math

total_degrees, degrees_left, total_people, people_left = map(int, sys.argv[1:])

fraction_left = (degrees_left + 0.0)/ total_degrees
fraction_gone = 1.0 - fraction_left
fair_share = fraction_left/people_left
modified_fair_share = fair_share + 0.05

weighting = 0.5 * fraction_gone + 0.5 - modified_fair_share
surfing = (math.cos(fraction_gone * math.pi))**2

print(int(math.floor((weighting * surfing + modified_fair_share)* total_degrees)))

```

Since AlCakeBot did so badly (and I expect him to do even worse in the contest) here’s my second entry. I called him *Surfer,* because he has a very nice up-and-down wave function that makes him feel like a surfer.

In principle, he bids according to `cos² (x * pi)`, where `x` is the fraction of cake that has been taken. This surfing wave is modified with a weighting function that causes him to start at less than a fair share less than half of the cake, reduces his bids to just above a fair share around when half of the cake is gone, and then speeds back up to bidding for the entire cake later. He will never bid less than a fair share of the remaining cake plus 5 % (percent of the entire cake, that is).

Note that while they may be brothers, if he gets a significantly larger slice than AlCakeBot, the latter is not even getting a single crumb of that. They would share chocolate or biscuits, *but not cake!*
> 2 votes

# Answer
# Hungry, Java

```
public class Hungry {
    public static void main(String[] args) {
        double[] arguments = new double[4];
        for (int i = 0; i < 4; i++) {
            arguments[i] = Double.parseDouble(args[i]);
        }
        int myCake = (int) Math.ceil(arguments[1]/arguments[3]);
        System.out.println(myCake);
    }
}

```

Always wants its fair share of the remaining cake.
> 1 votes

# Answer
# Cake Eater, Java

```
public class CakeEater{
    public static void main(String[]args){
        int a=Integer.parseInt(args[1]),b=Integer.parseInt(args[2]),c=Integer.parseInt(args[3]);
        System.out.println((int)Math.min(a,((1.2+Math.random()*0.15)*a)/c));
    }
}

```

It eats cake. That's about it.
> 1 votes

# Answer
# A Little Off The Top, Python 2

```
import math, sys

total_degrees, degrees_left, total_people, people_left = map(int, sys.argv[1:])

def get_equal_share(total_degrees, people):
  return int(math.ceil(total_degrees/float(people)))

def noms(total_degrees, degrees_left, people):
  bid = get_equal_share(total_degrees,people)-1
  return min(degrees_left, bid)

print noms(total_degrees, degrees_left, people_left)

```

Since the "perfect" algorithm tries to split the cake evenly between the bots, we're going to take just a sliver less than that. Demands its full fair share of the overall cake, even in subsequent rounds, but skews that number upward since it's based on how many people are left.

I haven't programmed in Python in a *long* while, so let me know if my code is broken...
> 1 votes

# Answer
**FloorBot, Python**

```
from sys import argv
from math import floor
degrees_left = int(argv[1])
print(floor(degrees_left*0.65))

```

Bids 65% of the remaining cake in hopes of beating both the greedy bots and the "Price is Right" bots.
> 1 votes

# Answer
# Imitator, Ruby

```
def imitator(total_degrees, degrees_left, total_people, people_left)

  case people_left
  when total_people
    degrees_left - 5
  when 1
    degrees_left
  else
    average_already_won = (total_degrees - degrees_left).fdiv(total_people - people_left)
    average_left = degrees_left.fdiv(people_left)
    guess_for_current_winning_score = average_already_won * (1.25 ** (total_people - people_left - 1))
    bid = [average_left, guess_for_current_winning_score].max.ceil
    [bid, degrees_left].min
  end

end

p imitator(*ARGV.map(&:to_i))

```

The goal is to get more cake than anyone else, not to maximize your cake. Thus, this bot won't settle for any less than what previous bots have already taken. (This version uses heuristics for that check, I just noticed we're actually allowed to save state so I'll probably post a stateful variant later).
> 1 votes

# Answer
# EatTheπ, Node.js

```
var π = Math.PI, e = Math.E;
var [totalπ, πLeft, totalPeople, peopleLeft] = process.argv.slice(2);
console.log(Math.min(totalπ * Date.now() * π % (πLeft * totalPeople / peopleLeft) % totalπ, πLeft / e * π, πLeft) | 0);

```

Really likes π, and thinks that cake ~~means~~ **is** π.
> 1 votes

# Answer
**Really the cake, Bash**

```
#!/bin/bash
echo "$RANDOM 652 / $2 * 100 / $2 $4 / + p" | dc

```

And here is a picture of the real cake.
> 1 votes

# Answer
# Relinquisher, Java

```
import static java.lang.Integer.parseInt;
public class Relinquisher {
    public static void main(String... args){
        int cakeLeft = parseInt(args[1]);
        int totalPeople = parseInt(args[2]);
        int peopleLeft = parseInt(args[3]);
        int answer = (int) Math.ceil(((peopleLeft + 10.0) * cakeLeft) / (totalPeople + 10.0));
        System.out.println((int) answer);
    }
}

```

A basic variant of my other bot, Impatient. This one tries to take the whole thing at first, but as more and more guests get their share, its desire to get the most possible slowly diminishes. I'm not too into this one; just wanna see how well it does.
> 1 votes

# Answer
# FairShare, Python 2

```
import sys

def FairShare(TotalDegrees, DegreesLeft, TotalPeople, PeopleLeft):

    FairShare = TotalDegrees / TotalPeople
    FairShareNow = DegreesLeft / PeopleLeft

    if PeopleLeft == 1:
        return DegreesLeft

    elif FairShare > FairShareNow:
        return FairShare

    elif FairShare == FairShareNow:
        return FairShare

    elif FairShare < FairShareNow:
        return FairShareNow

print FairShare(int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]))

```

Here I come with my tiny Python skills! :D `max()` and `min()` are things.

Pretty simple. If my fair share at the beginning is more than my fair share now, return my fair share now. If my fair share at the beginning is equal to to my fair share now, return my fair share at the beginning minus one. If my fair share at the beginning is less than my fair share now, return my fair share now.

Edited so that if FairShare is the last in the round, takes all the cake.
> 1 votes

# Answer
# this\_bot\_wants\_it\_all\_possible, PHP

```
  echo 359;

```

This bot wants it all possible.
> 1 votes

# Answer
# Try to Win, C++

```
#include<iostream>
#include<stdlib.h>
using namespace std;
int main(int argc, char *argv[])
{
    int td, dl, tp, pl;
    td = atoi(argv[1]);
    dl = atoi(argv[2]);
    tp = atoi(argv[3]);
    pl = atoi(argv[4]);
    if (pl == 1)
    {
        cout << dl;
        return 0;
    }
    else if(pl < 10 )
    {
        int sn = dl / pl;
        int sb = td/ pl;
        int si = td / tp;

        if (sn > si + 1)
        {
            cout << sn;
            return 0;
        }
        if (sn = si + 1)
        {
            cout << sn;
            return 0;
        }
        if (sn == si)
        {
            cout << sn;
            return 0;
        }
        if (sn < si)
        {
            cout << si;
            return 0;
        }

    }
    else
    {
          cout<<td/13;
    }
    return 0;
}

```
> 1 votes

# Answer
## ALittleExtra, sh

```
#!/bin/sh
fair=$(expr $2 / $4)
myextra=$(expr $2 / $3)
want=$(expr $fair + $myextra)
echo $(($want<$2?$want:$2))

```

I just want a bit more, gets less greedy as cake dwindles
> 1 votes

# Answer
# DruuuuuunkBot, Python

```
import sys,random
tD,dL,pN,pL=map(int,sys.argv[1:])
a=dL/(pL+1)
if a < 0:
 a = dL
print(a)

```

~~Tries to be educated in his guesses, but he's a tad drunk, resulting in wide errors.~~ Said bot is now less drunk. He doesn't like people, so he just wants to get out of here *pronto*! But now he want a little more cake.
> 1 votes

# Answer
## MyFairPlusAThird, sh

```
#!/bin/sh
fair=$(expr $2 / $4)
myextra=$(expr $2 / 3)
want=$(expr $fair + $myextra)
echo $(($want<$2?$want:$2))

```
> 1 votes

# Answer
# Fatbot 5000, Python 2

```
import random, math, sys

total_degrees, degrees_left, total_people, people_left = map(int, sys.argv[1:])

def get_equal_share(degrees_left, people):
    return int(math.ceil(degrees_left/float(people)))

def get_greedy(degrees_left, people):
    min_bid = get_equal_share(degrees_left,people)+1
    max_bid = min_bid*2
    bid = random.randrange(min_bid, max_bid)
    return min(bid, degrees_left)

print get_greedy(degrees_left, people_left)

```

My example bot. Will always bid more than it's fair share of the cake but isn't so hungry it wants much more than 2 times it's fair share.
> 0 votes

# Answer
# Moses, Java

```
public class Moses {
    public static void main(String[] args) {
        double[] arguments = new double[4];
        for (int i = 0; i < 4; i++) {
            arguments[i] = Double.parseDouble(args[i]);
        }
        if (arguments[3] == 1) {
            System.out.println((int)arguments[3]);
        } else {
            int myCake = (int) Math.ceil(arguments[1]/2);
            System.out.println(myCake);
        }
    }
}

```

Wants half of the pie. If it gets its share, the following players can at maximum get the same amount.
> 0 votes

# Answer
# FairPlusPlus, Java

```
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Scanner;
import static java.lang.Math.*;

/**
 * Created 10/5/15
 *
 * @author TheNumberOne
 */
public class FairPlusPlus {

    private static int previousCake;
    private static int highestVoteWon;

    static {
        File file = new File("data/FairPlusPlus.txt");
        Scanner in = null;
        try {
            in = new Scanner(file);
            previousCake = in.nextInt();
            highestVoteWon = in.nextInt();
        } catch (Exception ignored) {
        }
    }

    public static void main(String[] arguments) throws FileNotFoundException {
        double[] args = new double[4];
        for (int i = 0; i < 4; i++) {
            args[i] = Double.parseDouble(arguments[i]);
        }
        if (args[2] == args[3]){
            highestVoteWon = -1;
        } else {
            highestVoteWon = (int) max(highestVoteWon, args[1] - previousCake);
        }

        System.out.println((int) min(max(ceil(args[1]/args[3]+(args[3]-1)/2), highestVoteWon + 1), args[1]));

        PrintStream out = new PrintStream("data/FairPlusPlus.txt");
        out.println((int) args[1]);
        out.println(highestVoteWon);

    }

}

```

He's mostly fair ... unless someone gets the better of him.

Assumes `./data/` directory exists.
> 0 votes

# Answer
# Impatient, Java

```
import static java.lang.Integer.parseInt;
public class Impatient {
    public static void main(String... args){
        int cakeLeft = parseInt(args[1]);
        int totalPeople = parseInt(args[2]);
        int peopleLeft = parseInt(args[3]);
        int answer = (int) Math.ceil(((totalPeople - peopleLeft + 10.0) * cakeLeft) / (totalPeople + 10.0));
        System.out.println((int) answer);
    }
}

```

I don't really know Java, so I don't even know if this will compile....

It starts out hungry for `10/(totalPeople+10)` of the cake, getting hungrier and hungrier as the round wears on. Not sure how it will do, but it's a fun experiment.
> 0 votes

# Answer
**Give me the cake, Bash**

```
#!/bin/bash
echo 3594

```
> 0 votes

# Answer
# Pig, Java

```
public class Pig{
    public static void main(String[] args){
        System.out.println(args[1]);
    }
}

```

This pig is probably not smart enough to bid low.
> -1 votes

---
Tags: game, king-of-the-hill
---


title: How could Stringy be improved?

text:
# Question
Title: How could Stringy be improved?
I created a programming language for manipulating strings called Stringy. It's very different from other programming languages, since you only have one string (for manipulation) and some variables. With the various commands you can manipulate that one string. I created it because it might be useful for some challenges here. (challenged tagged *string*)

What could I add to this to make it better/more useful for challenges here?

Examples for the language can be found at GitHub at `examples.txt`. It might be a bit hard to understand though.

# Answer
OK, I said I'd put my comments into a more comprehensible form so here they are.

1. Don't separate commands. Having to use `;` every time you want to use a different command is costly. My recommendation on the interpreter side is to parse one character at a time and read more if the command necessitates it.
2. Add regex (to be honest, I don't know much regex -- it's somewhere on my list of things to learn -- but it seems logical to add it)
3. On the topic of not separating commands with `;`, allow for whitespace to be removeable.
4. Add loops of some sort.
5. Add conditionals and conditional tests (equals, not, and, or, etc.)
6. Add a newline reserved character (`n`, perhaps?)
7. Add reserved characters for variables
8. You have uppercase and lowercase commands, why not add a capitalization one (one that capitalizes the string as if it were a sentence and maybe also capitalizes proper nouns that it can identify).
9. Add a command to count how many instances of a string are in another.
10. Add a length command to get the length of a string.
11. Add a terminate/break command.
12. Add an equivalent of Python's `ord` and `chr` functions.
13. Add a split at numerical value command (splits at a certain length), and add an alternative to that which splits at every multiple of the numerical value (e.g. for a string of length 10 at 3,6,9 if given the argument 3).
14. Add a duplication command (akin to Python's `"String"*x`)

You'll notice that some of these involve numbers -- I think that even for String challenges having a way of working with numbers is good. Perhaps have a stack for storing numbers that is accessed when certain commands are used (e.g. the length command pushes the length onto the number stack and then the split at numerical value uses this length to split the stack).

I'll add more ideas as I think of them, but I feel like my suggestions are pushing this in the direction of a more general-purpose golf language. Hopefully this input helps regardless of whether you use it or not.
> 2 votes

---
Tags: tips
---


title: Is it L-convex?

text:
# Question
Title: Is it L-convex?
## Background

A polyomino is called *L-convex*, if it's possible to travel from any tile to any other tile by an L-shaped path, that is, a path that goes in the cardinal directions and changes direction at most once. For example, the polyomino of `1`s in the figure

```
0 0 1 1 1 0

1 1 1 1 0 0

1 1 0 0 0 0

```

is not L-convex, since both L-shaped paths from the bottom left `1` to the top right `1` contain a `0`:

```
0>0>1>1>1 0
^       ^
1 1 1 1 0 0
^       ^
1>1>0>0>0 0

```

However, the polyomino of `1`s in this figure is L-convex:

```
0 1 1 1 0 0

1 1 1 1 1 1

0 1 1 0 0 0

```

## Input

Your input is a 2D array of bits in the native format of your language, or as a newline-delimited string if our language lacks arrays. It is guaranteed to contain at least one `1`.

## Output

Your output shall be a truthy value if the set of `1`s is an L-convex polyomino, and a falsy value if not. These outputs must be consistent: you must output the same truthy value for all L-convex inputs, and the same falsy value for others. Note that a disconnected set of `1`s (which is not a polyomino) results in a falsy output.

## Rules and Scoring

You can write either a full program or a function. The lowest byte count wins, and standard loopholes are disallowed.

## Test Cases

These test cases should work also if you rotate or reflect the arrays, or add rows of `0`s to any borders.

```
False instances
01
10

111
101
111

1101
1111
1110

1100
1000
0011

01100
11110
01110
00110

011000
011110
001111

True instances
1

01
11

010
111
010

001
011
111

11100
11110
01100
01000

011000
011000
111100
111111
001000

```

# Answer
# Snails, ~~45~~ 24

```
&
!{\1t\1!{o\1,nf\1,!.!~

```

Right after posting my initial solution, I realized there was a much better way. The original program traveled around the square formed by the paths between two `1`s, testing for the presence of a 0 in each pair of sides. It also had to have a special case for straight line paths. The new version starts by teleporting from one `1` to the other, and testing for the absence of a straight or L-shaped path of `1`s back to the start.
> 6 votes

# Answer
# Matlab, 182 bytes

Idea: Repeat for every `1` in the polyomino matrix:

* Create new matrix with only the given `1` but the rest zero.
* for every `1` in this new matrix (repeat until nothing changes anymore)
    + add `1` as neighbours in x direction if there are `1` as neighbours in the polynomio
* for every `1` in this new matrix (repeat until nothing changes anymore)
    + add `1` as neighbours in x direction if there are `1` as neighbours in the polynomio

Now `1` in the new matrix should cover all `1` in the polynomio-matrix that are reachable from the given starting point by first going in x-direction and then in y-direction. Now we can repeat the same process but with first going into y-direction and then in x-direction. Now every `1` of the polyomino matrix should be reached at once or both times. If not, then we have found a position in the polynomio matrix that cannot be reached from every other position by an `L`-path.

Golfed:

```
function r=f(a);[i,j,b]=find(a);N=nnz(i);r=1;for k=1:N;K=1:3;for l=1:2;c=b;b=a*0;b(i(k),j(k))=1;for z=1:2*N; b=conv2(b+0,K,'s')&a;if z==N;K=K';end;end;end;r=r*all(b(:)|c(:)>=a(:));end

```

With comments:

```
function r=codegolf_L_convex(a);
%a=[0,1;1,1];
[i,j,b]=find(a);%b just needs to be initialized, does not really mattter
N=nnz(i);%number of ones in the matrix
r=1;%return value
for k=1:N;%go throu all '1' in the matrix
    %expand that pixel in x dir:
    K=1:3;%convolution kernel (just three positive values needed)
    for l=1:2;%first horizontal->vertical then vertical->horizontal
        c=b;%backup for considering both runs
        b=a*0;
        b(i(k),j(k))=1; %set the seed
        for z=1:2*N;
            b=conv2(b+0,K,'s')&a; %expand the seed horizontally (or vertically for the second half) but only within the polyomino
            if z==N;
                K=K'; %change horizontal/vertical
            end;
        end;
    end;
    r=r*all(b(:)|c(:)>=a(:));%check whether we can really reach every point
end

```

Test cases script:

```
disp('all false -------------');
a=[0,1;1,0];
f(a)
a=[1,1,1;1,0,1;1,1,1];
f(a)
a=[1,1,0,1;1,1,1,1;1,1,1,0];
f(a)
a=[1,1,0,0;1,0,0,0;0,0,1,1];
f(a)
a=[0,1,1,0,0;1,1,1,1,0;0,1,1,1,0;0,0,1,1,0];
f(a)
a=[0,1,1,0,0,0;0,1,1,1,1,0;0,0,1,1,1,1];
f(a)
 disp('all true +++++++++++++');
a=[1];
f(a)
a=[0,1;1,1];
f(a)
a=[0,1,0;1,1,1;0,1,0];
f(a)
a=[0,0,1;0,1,1;1,1,1];
f(a)
a=[1,1,1,0,0;1,1,1,1,0;0,1,1,0,0;0,1,0,0,0];
f(a)
a=[0,1,1,0,0,0;0,1,1,0,0,0;1,1,1,1,0,0;1,1,1,1,1,1;0,0,1,0,0,0];
f(a)

```
> 6 votes

# Answer
# Mathematica, ~~129~~ 127 bytes

```
3>GraphDiameter@Graph[#,#<->#2&@@@Select[#~Tuples~2,!FreeQ[#-#2&@@#,0]&]]&@Position[#,1]&&{#,Thread@#}~FreeQ~{___,1,0..,1,___}&

```

### Explanation:

First, if there is a `0` between two `1`s on the same row or column, the array is not L-convex, because we can't connect the two `1`s.

After excluding this case, every two `1`s on the same row or column can be connected by a straight path. We can generate a graph, whose vertices are the positions of `1`s in the array, and edges are pairs of `1`s on the same row or column. Then the array is L-convex if and only if the diameter of the graph is less than 3.
> 3 votes

# Answer
# Javascript ES6, 290 bytes

Ok, maybe it won't win any awards for brevity, but it does use a novel approach. See the ungolfed version for how it works.

Proof for this method can be found in: Cellular Automata and Discrete Complex Systems.

```
L=a=>[1,0,1].every($=>(a=a[0].map((_,col)=>a.map(row=>row[col]))).map(r=>($?r.reverse():r).join``).every((r,i,b)=>r.replace(/^(0*)(1*)(0*)$|(.+)/,(_,s,m,o,e)=>(c=e)?'':!m||b[i-1]&&+b[i-1][s.length]?1:b.every((r,j)=>j<i||(c=c||!+r[l=s.length])?r.search(`0{${l}}.*0{${o.length}}`)+1:1)||'')))

```

Ungolfed:

```
function L(a) {
  /* Runs three times and ensure all pass validation
   * 1: horizontally reversed
   * 2: 90 degrees rotated
   * 3: original
   *
   *     | 1:  | 2:  | 3:
   * =====================
   * 001 | 100 | 111 | 001
   * 011 | 110 | 011 | 011
   * 111 | 111 | 001 | 111
   *
   * By finding maximal rectangles with corners on all NW and NE corners
   * (separately) of a HV-convex polyomino and ensuring it doesn't enter the
   * boundaries labelled ABCD for the rectangle X below:
   *
   *   A  |         |  B
   * -----===========-----
   *      |    X    |
   * -----===========-----
   *   C  |         |  D
   *
   * The first iteration tests the NE corners and horizontal convexity.
   * The second iteration test vertical convexity.
   * The third iteration tests the NW corners.
   *
   * If all pass then the polyomino is L-convex.
   */
  return [1,0,1].every(function($){
    return (a=a[0].map((_,col)=>{
      // Transpose rows with columns
      return a.map(row=>row[col])
    })).map(row=>{
      // Join rows as strings and on odd iterations reverse them
      return ($ ? row.reverse() : row).join``
    }).every(function(row, i, b) {
      if (i == 0) console.log(b.join('\n'));
      return row.replace(/^(0*)(1*)(0*)$|(.+)/, function(_, start, middle, end, invalid) {
        // Non H-convex polyomino (0 between 1s)
        if (invalid) return '';
        // Is not a NW corner (character above is 1)
        if (!middle || b[i-1] && +b[i-1][start.length]) return 1;
        c=1;
        return b.every(function(row, j) {
          // Above or below maximal rectangle from corner
          if (j < i || !(c=c&&+row[l=start.length])) {
            // Area before and after maximal rectangle doesn't contain 1
            return row.search(`0{${l}}.*0{${end.length}}`)+1
          }
          return 1;
        }) || '';
      });
    });
  });
}

```
> 2 votes

# Answer
# JavaScript (ES6) 174

Looking at the grid of empty or filled cells, for any pair of filled cells I check the horizontal paths to the other cell column (there can be 1 if the cells are on the same row, else or 2) and the vertical paths to the other cell row (there can be 1 or 2 too). If I find an empty cell in both vertical paths or both horizontal paths, then there can not be an L shaped path between the cells.

(I had a hard time trying to put up this explanation - I hope to have been clear)

Test running the snippet below in any EcmaScript 6 compliant browser

```
F=p=>!p.some((n,y)=>n.some((q,x)=>q&&p.some((o,u)=>o.some((q,t)=>{for(f=0,i=y;q&i<=u;i++)f|=!p[i][x]|2*!p[i][t];if(f<3)for(f=0,j=x;q&j<=t;j++)f|=!n[j]|2*!o[j];return f>2}))))

// TEST
console.log=(...x)=>O.innerHTML+=x+'\n'

tko = [
 [[0,1],[1,0]]
,[[1,1,1],[1,0,1],[1,1,1]]
,[[1,1,0,1],[1,1,1,1],[1,1,1,0]]
,[[1,1,0,0],[1,0,0,0],[0,0,1,1]]
,[[0,1,1,0,0],[1,1,1,1,0],[0,1,1,1,0],[0,0,1,1,0]]
,[[0,1,1,0,0,0],[0,1,1,1,1,0],[0,0,1,1,1,1]]
]
tko.forEach(t=>(console.log(t.join`\n`+`\nFalse? ${F(t)}\n`)));
tok = [
 [[1]]
,[[0,1],[1,1]]
,[[0,1,0],[1,1,1],[0,1,0]]
,[[0,0,1],[0,1,1],[1,1,1]]
,[[1,1,1,0,0],[1,1,1,1,0],[0,1,1,0,0],[0,1,0,0,0]]
,[[0,1,1,0,0,0],[0,1,1,0,0,0],[1,1,1,1,0,0],[1,1,1,1,1,1],[0,0,1,0,0,0]]
]
tok.forEach(t=>(console.log(t.join`\n`+`\nTrue? ${F(t)}\n`)));

// LESS GOLFED

U=p=>
  !p.some((n,y)=>
    n.some((q,x)=>
      q && p.some((o,u)=>
        o.some((q,t)=>{
          for(f=0,i=y; q&i<=u; i++)f|=!p[i][x]|2*!p[i][t]
          if (f<3)
            for(f=0,j=x; q&j<=t; j++)f|=!n[j]|2*!o[j]
          return f>2
        })
      )
    )
  )
```

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

---
Tags: code-golf, array, geometry, decision-problem
---


title: Primes of Ulam's Spiral

text:
# Question
Title: Primes of Ulam's Spiral
Ulam's spiral is a *truly* fascinating, yet puzzling, topic in mathematics. How it works in detail can be found here, but a short summary can be explained as so:

I start off by writing a one, then I write a two to the right of it. Above the two, I write a three, and to the left of that I write four. I continue this pattern of circling around 1 (and any numbers between me and 1) infinitely (or until told to stop), forming a spiral pattern. (see example below)

### The Objective

Make a program that accepts *n* (will always be an odd number greater than zero) as an input that correlates with the number of rows, then prints out the values of the primes row by row of the Ulam spiral. The formatting can be any fashion, but *must* be human readable and obvious.

For example, given the input 3, your program should output `5,3,2,7`, because 3 rows produces the following spiral:

```
5 4 3 <-- first row has the primes 5 and 3
6 1 2 <-- second row has the prime 2
7 8 9 <-- third row has the prime 7

```

As this is a code golf, the answer with the fewest bytes wins (no matter how inefficient)! Standard loopholes are not acceptable.

# Answer
# Pyth, 20 bytes

```
f}TPTsuC+R=hZ_GtyQ]]

```

Try it online: Demonstration

This code generates the fully Ulam's spiral, connects all lines and filters for primes.

### Explanation:

```
f}TPTsuC+R=hZ_GtyQ]]   implicit: Z = 0
      u           ]]   reduce, start with G = [[]]
               tyQ     for H in [0, 1, ..., 2*input-2] do:
             _G           reverse the order of the lines
        +R=hZ             append Z + 1 at the end of each line,
                          updating Z each time with the new value Z + 1
       C                  update G with the transposed of ^
                       this gives the Ulam's spiral
     s                 combine all lines to a big list of numbers
f                      filter for numbers T, which satisfy:
 }TPT                    T appears in the prime-factorization of T
                         (<==> T is prime)

```
> 8 votes

# Answer
# MATLAB, 48

```
a=fliplr(spiral(input(''))');disp(a(isprime(a)))

```

Basically this creates a spiral of the required size (requested from user), then arranges it so that it appears in the correct row order. This is stored in a. Next it displays all values in a which are prime.

As you said any readable format, I saved a byte and went for the default output of disp() which is (in your test case, n=3):

```
 5
 3
 2
 7

```

---

As an added bonus, this works for any n\>0, including even numbers. For example, the output for n=10 is:

```
97
61
59
37
31
89
67
17
13
 5
 3
29
19
 2
11
53
41
 7
71
23
43
47
83
73
79

```
> 7 votes

# Answer
# CJam, ~~42~~ 33 bytes

```
Xali(2*{_W%zY@,Y+:Y,>a+}*e_{mp},`

```

Try it online

The latest version includes substantial improvements suggested by @Martin.

The method for building the spiral is to, in each step, rotate the matrix we have so far by 90 degrees, and add a row with additional numbers. This is repeated `(n / 2) * 4` times.

The values in the resulting matrix are then filtered for being primes.

Explanation:

```
Xa    Push initial matrix [1].
li    Get input and convert to int.
(2*   Calculate 2*(n-1), which is the number of rotations and row additions needed.
{     Start rotation loop.
  _     Copy current matrix for getting number of rows later.
  W%    Reverse the order of the rows...
  z     ... and transpose the matrix. The combination produces a 90 degree rotation.
  Y     Get next value from variable Y (which is default initialized to 2).
  @,    Rotate previous matrix to top, and get number of rows. This is the number
        of columns after the 90 degree rotation, meaning that it's the length of
        the row to be added.
  Y+    Add first value to row length to get end value.
  :Y    Save it in Y. This will be the first value for next added row.
  ,     Create list of values up to end value.
  >     Slice off values up to start value, leaving only the new values to be added.
  a+    Wrap the new row and add it to matrix.
}*    End of rotation loop.
e_    Flatten matrix into list.
{mp}, Filter list for primes.
`     Convert list to string for output.

```
> 6 votes

# Answer
# Mathematica 223

This appropriates Kuba's code for an Ulam spiral. That's why I'm submitting it as a community wiki. I merely golfed it and selected out the primes, which are listed by the row in which they reside.

```
r=Range;i=Insert;t=Transpose;s@n_:=#~Select~PrimeQ&/@Nest[With[{d=Length@#,l=#[[-1,-1]]},
Composition[i[#,l+3d+2+r[d+2],-1]&,t@i[t@#,l+2d+1+r[d+1],1]&,i[#,l+d+r[d+1,1,-1],1]&,
t@i[t@#,l+r[d,1,-1],-1] &][#,15]]&,{{1}},(n-1)/2]

```

**Example**

```
 s{15]

```

> {{197, 193, 191}, {139, 137}, {199, 101, 97, 181}, {61, 59, 131}, {103, 37, 31, 89, 179}, {149, 67, 17, 13}, {5, 3, 29}, {151, 19, 2, 11, 53, 127}, {107, 41, 7}, {71, 23}, {109, 43, 47, 83, 173}, {73, 79}, {113}, {157, 163, 167}, {211, 223}}

To improve the display:

```
 %// MatrixForm

```
> 5 votes

# Answer
# Mathematica, 118 bytes

```
f=Permute[Range[#*#],Accumulate@Take[Join[{#*#+1}/2,Flatten@Table[(-1)^j i,{j,#},{i,{-1,#}},{j}]],#*#]]~Select~PrimeQ&

```

This generates the Ulam spiral in linear form by noting that the position of each subsequent number can be accumulated as

```
{(n*n + 1)/2, +1, -n, -1, -1, +n, +n, +1, +1, +1, -n, -n, -n, ...}

```

i.e. start from the centre, then move 1 right, 1 up, 2 left, 2 down, 3 right, 3 up, ...

Output:

```
In[515]:= f[5]
Out[515]= {17,13,5,3,19,2,11,7,23}

```
> 4 votes

# Answer
# Javascript, ~~516~~ ~~363~~ ~~304~~ ~~276~~ ~~243~~ 240 Bytes

My solution does not create a dense matrix with the Spiral, instead it returns the index that corresponds to the given number in the Ulam's Matrix of the given order. So it iterates through the numbers between 2 and M\*M and creates an array of primes with the idx given by the fn ulamIdx

```
M=15;
$=Math;
_=$.sqrt;
/**
 * Return M*i+j (i.e. lineal or vector idx for the matrix) of the Ulam Matrix for the given integer
 *
 * Each Segment (there are 4 in each round) contains a line of consecutive integers that wraps the
 * inner Spiral round. In the foCowing example Segments are: {2,3}, {4,5},
 * {6,7}, {8,9}, {a,b,c,d}, {e,f,g,h}, {i,j,k,l}, {m,n,o,p}
 *
 *    h g f e d
 *    i 5 4 3 c
 *    j 6 1 2 b
 *    k 7 8 9 a
 *    l m n o p
 *
 * @param n integer The integer which position in the Matrix we want.
 * @param M integer Matrix Order.
 */
/*
 * m: modulus representing step in segment in current spirtal round
 * v: Step in current spiral round, i.e. n - (inner spirals greatest num.)
 * s: the current Segment one of [1, 2, 3, 4] that represents the current spiral round
 * L: Segment Length (Current spiral round Order - 1)
 * B: inner Spiral Order, for trib¿vial case 1 it's -1 special case handled differently.
 * C: relative line (row or column) corresponding to n in current spiral Round
 * R: relative line (column or row) corresponding to n in current spiral Round
 * N: Curren (the one that contains n) Spiral (matrix) round Order
 * D: Difference between M and the current Spiral round order.
 */

/**
 * Runs the loop for every integer between 2 and M*M
 * Does not check sanity for M, that should be odd.
 */
r=[];
for (x = 2; x < M * M; x++) {
    p=1;
    // Is Prime?
    for (k = 2; p&&k <= _(x); k++)
        if (x % k==0) p=0;
    if (p) {
        B = $.floor(_(x - 1));
        B=B&1?B:B-1;
        N = B + 2;
        D = (M - N) / 2;
            v = x - B * B;
            L = B + 1;
            s = $.ceil(v / L);
            m = v % L || L;
            C = D + (s < 3 ? N - m : 1 + m);
            R = s&2 ? D + 1 : D + N;
            w= s&1 ? M * C + R : M * R + C;
        // /*uncomment to debug*/ console.log("X:" + x + ": " + ((s&1) ? [C, R].join() : [R, C].join()));
        r[w] = x;
    }
}
alert(r);

```

Minified looks like this:

```
for(M=15,$=Math,_=$.sqrt,r=[],x=2;x<M*M;x++){for(p=1,k=2;p&&k<=_(x);k++)x%k==0&&(p=0);p&&(B=$.floor(_(x-1)),B=1&B?B:B-1,N=B+2,D=(M-N)/2,v=x-B*B,L=B+1,s=$.ceil(v/L),m=v%L||L,C=D+(s<3?N-m:1+m),R=2&s?D+1:D+N,w=1&s?M*C+R:M*R+C,r[w]=x)}alert(r);

```

For input 15 the output is:

## ,,,,,,,,,,,,,,,,197,,,,193,,191,,,,,,,,,,,,,,,,139,,137,,,,,,199,,101,,,,97,,,,,,,,181,,,,,,,,61,,59,,,,131,,,,103,,37,,,,,,31,,89,,179,,149,,67,,17,,,,13,,,,,,,,,,,,5,,3,,29,,,,,,151,,,,19,,,2,11,,53,,127,,,,107,,41,,7,,,,,,,,,,,,71,,,,23,,,,,,,,,,109,,43,,,,47,,,,83,,173,,,,73,,,,,,79,,,,,,,,,,113,,,,,,,,,,,,157,,,,,,163,,,,167,,,,211,,,,,,,,,,,,223
> 1 votes

---
Tags: code-golf, math, primes
---


title: Math in manhattan

text:
# Question
Title: Math in manhattan
I define the following operators:

**Manhattan Addition** a +M b, for single-digit numbers, is the result of concatenating b onto a. So, a +M b = 10a + b. Therefore, the general operator +M is defined as thus:

```
a +<sub>M</sub> b = 10a + b
```

**Manhattan Subtraction** a –M b, for single-digit numbers, is the result of removing the last b from a. Therefore, the operator –M is defined as thus in pseudocode:

```
a –<sub>M</sub> b = a remove last b
```

**Manhattan Multiplication** a ×M b is the result of replacing all instances of b in a with b instances of b. Ergo, ×M is defined in pseudocode as:

```
a ×<sub>M</sub> b = a -> s/b/<b copies of b>/g
```

**Manhattan Division** a ÷M b is defined in terms of ×M:

```
1 ÷<sub>M</sub> b = the first character of b
a ÷<sub>M</sub> b = a ×<sub>M</sub> (1 ÷<sub>M</sub> b)
```

With all this in mind, create an interpreter that will evaluate infix expressions that use the following operators (i.e., `a + b`, not `a b +` or `+ a b`)

```
+    Addition
-    Subtraction
/    Division
*    Multiplication
*M   Manhattan Multiplication
/M   Manhattan Division
+M   Manhattan Addition
-M   Manhattan Subtraction

```

Each Manhattan operator has a higher order precedence than their normal counterpart.

Test cases:

```
> 5 +M 10 + 3
63      // 5*10 + 10 + 3 => 60 + 3
> 10 *M 2
10      // no 2s in 10
> 10 *M 1
10      // one 1 in 10 replaced once
> 23 *M 3
2333    // 23 has one 3, which is replaced with three 3s
> 23 *M 2
223     // 23 has one 2, which is replaced with two 2s
> 232 *M 2
22322   // 232 has two 2s, which are replaced with two 2s
> 232 *M 23
23...(23 times)...232   // ...
> 123 *M 2 * 3
3669    // 1223 * 3 => 3669
> 5 + 3 +M 2
37      // 5 + (3 +M 2) => 5 + 32 => 37
> 150 /M 3
150     // 150 ÷M 3 => 150 ×M 3 => 150
> 150 /M 53
1555550 // 150 ÷M 53 => 150 ×M 5 => 1555550
> 50 -M 0
5
> 500 -M 0
50
> 5234 -M 5
234
> 12 +M 633 *M 3
6333453 // = 12 +M 6333333 = 120 + 6333333 = 6333453

```

This is a , so the shortest program in bytes wins.

## Leaderboards

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

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

```
# Language Name, N bytes

```

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

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

```

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

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

```

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

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

```

```
var QUESTION_ID=59299,OVERRIDE_USER=8478;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}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
> 4 votes
# Dyalog APL, ~~104~~ ~~81~~ ~~79~~ ~~93~~ 75 bytes

*Edit:* Now handles `4342343 -M 34``43423` correctly.

```
M←{⍎(5|⌊⍺⍺2)⊃'⍺×M⍣(⍺≠1)⍎⊃b'(b⎕R(⍵⍴'&')⊢a)'10⊥⍺⍵'(('(.*)',b←⍕⍵)⎕R'\1'⊢a←⍕⍺)}

```

### Background

This extends APL to include the Manhattan operator. An operator in APL terminology is a modifier of functions (e.g. `÷`). An example of an operator is  which modifies functions to swap their arguments so `3 = 2 ÷⍨ 6`. So too, `M` modifies the basic arithmetic functions to be their Manhattan relatives. Note that since the resulting language is an extension of APL, APL's strict right-to-left precedence remains.

### Explanation

The overarching structure is `M←{⍎(5|⌊⍺⍺2)⊃``}` which applies the function (`+` or `-` or `×` or `÷`) to 2 and uses the result to chose which string to evaluate. The strings are:

**3 for -M:** `(('(.*)',b←⍕⍵)⎕R'\1'⊢a←⍕⍺)`
regex remove the last occurrence of *b* (string rep. of right arg.) in *a* (string rep. of left arg.)

**2 for +M:** `'10⊥⍺⍵'`
evaluate the arguments as base-10 digits

**1 for ×M:** `(b⎕R(⍵⍴'&')⊢a)`
replace occurrences of *b* with *b* ampersands (i.e. regex for the

**0 for ÷M:** `'⍺×M⍣(⍺≠1)⍎⊃b'`
`⍎⊃b` first digit of *b*
`⍺×M⍣(⍺≠1)` apply ⍺ ×M if ⍺ ≠ 1

out of of the above four strings, pick number:

`(5|⌊⍺⍺2)` mod-5 of the floor of the function applied to 2, namely:
3 = `5 | ⌊-2`
2 = `5 | ⌊+2`
1 = `5 | ⌊×2` because ×2 ⇔ sgn(2) ⇔ 1
0 = `5 | ⌊÷2` because ÷2 ⇔ 1 ÷ 2 ⇔ 0.5

### Lots of thanks to my dear friend ngn for amazing shavings.

# Answer
> 11 votes
# Perl, ~~100~~ ~~99~~ 98 bytes

97 bytes code + 1 byte command line

```
s/ |.*\K(\d)(\d*)-M\1|\+M/\2/g+s/(\d+)\*M(.)/$1=~s@$2@$&x$&@erg/e+s#/(M.)\d+#*\1#&&redo,$\=eval}{

```

Usage example:

```
echo "123 *M 2 * 3 + 150 /M 53" | perl -p entry.pl

```

# Answer
> 7 votes
# Python, 644 bytes

```
import operator as o,re
x,q,t,r,w='*/+-M';mm,md,ma,ms='*M /M +M -M'.split()
n=lambda x:x
a=lambda a,b:str(10*int(a)+int(b))
v=lambda a,b:a[::-1].replace(b,'',1)[::-1]
m=lambda a,b:a.replace(b,b*int(b))
d=lambda a,b:m(a,b[0])if a>0 else b[0]
def p(s):s=s.group();ss=s.split();l=s.split(ss[1]);h={mm:m,md:d,ma:a,ms:v,x:o.mul,q:o.div,t:o.add,r:o.sub}.get(ss[1],n);return str(h(*map(int if h in[o.mul,o.div,o.add,o.sub]else n,map(u,map(str.strip,l)))))
def u(s):z=r'\d+ (?:\{0}{2}|\{1}{2}) \d+';return re.sub(z.format(t,r,''),p,re.sub(z.format(t,r,w),p,re.sub(z.format(x,q,''),p,re.sub(z.format(x,q,w),p,re.sub(r'\((.*)\)',u,s)))))
print u(input())

```

Accepts input on STDIN (wrapped in quotes). Uses regex to match and parse operations. All work is done on strings, and casting to and from ints is only used when doing normal mathematical operations.

I'm pretty sure this could be golfed further, so I'll be working on that over the next few days.

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


# Question
Title: Evaluating expressions with numerical shorthands
You work for a company that wants to make a user-friendly calculator, and thus you have been tasked with adding the ability for users to use "numerical shorthands," that is, letters that represent numerical values, such as `k` for `1000`. Because your company wants to save money on storage in said calculators, you must minimize your code as much as possible to reduce the cost of storage.

---

## Your Task

You are to create a function that either reads an expression as input from STDIN or takes it as a parameter and returns its evaluation or prints it to STDOUT.

## Some Clarification

Let me do some definitions. First off, we have the input, which I call an expression. This can be something like the following:

```
x + y / z

```

Within this expression we have three numbers: `x`, `y`, and `z`, separated by operators (`+` and `/`). These numbers are not necessarily positive integers (or even integers). What complicates things is when we have to evaluate shorthands contained within numbers. For example, with

```
2k15

```

for purposes of evaluation, we split this up into three numbers: `2`, `1000` (which is `k`), and `15`. Then, according to the rules, we combine them to obtain

```
2*1000 + 15 = 2015

```

Hopefully this makes it a bit easier to understand the following rules.

## Rules

N.B. Unless specified otherwise, you can interpret the word "numbers" or its synonyms to include shorthands.

1. The following constitutes the numerical shorthands your function must be able to process: `k, m, b, t, and e`. `k, m, b, and t` correspond to the values `1000, 1000000, 1000000000, and 1000000000000` respectively (one thousand, one million, one billion, and one trillion). The `e` shorthand will always be followed by another number, `n`, and represents `10^n`. You must allow for numerical shorthands to be present in `n` and present before `e`. For example, `kek` evaluates to `1000*10^1000`.
2. For simplicity's sake, if a number has the shorthand `e` in it, it will only be used once.
3. Any number (*shorthands included*) before a shorthand is multiplied by it. e.g. `120kk` would be evaluated as `120 * 1000 * 1000`. If there is no number before it, you must assume that the number is 1 (like how you might, in mathematics, treat a variable `x` implicitly as `1x`). e.g. `e10` evaluates to `10^10`. Another example: `2m2k` evaluates to `2*1000000*2*1000` (nothing is added to it).
4. Any number (shorthands do not apply) following the **last shorthand** in a number containing a shorthand is added to it. e.g. `2k12` would be evaluated as `2*1000 + 12`. The exception to this is if the shorthand `e` is used, in which case the number (*shorthands included*) following `e` will be treated as `n` and evaluated as `10^n` (see the first rule).
5. Your function must be able to process the operators `+, -, *, and /` which are addition, subtraction, multiplication, and division respectively. It may process more, if you so desire.
6. Operations are evaluated according to the order of operations.
7. Numbers in shorthands are not only integers. `3.5b1.2` is valid and is to be evaluated as `3.5*1000000000 + 1.2 = 3500000001.2`
8. Built-ins are not allowed, if they exist for this sort of thing. The exception that I'll add would be if your language automatically converts large numbers to scientific notation, in which case that is admissible for your output.
9. Shortest code in bytes wins, standard loopholes applying.

## Input

The input will be an expression with each number and operator separated by spaces. Numbers may or may not contain a shorthand. A sample is shown below:

```
10 + 1b - 2k

```

## Output

Your function must output the evaluation of the expression as a number. It is admissible to use scientific notation if the output would be too large to display. You must have at least three decimal places if the number is not an integer. It is admissible if you retain these decimal places if the number is an integer.

## Test Cases

Input

```
t

```

Output

```
1000000000000

```

---

Input

```
1 + 4b / 10k11

```

Output

```
399561.483

```

---

Input

```
e2 + k2ke-1 - b12

```

Output

```
-999799912

```

or

```
-999799912.000

```

---

Input

```
142ek12

```

Output

```
142e1012

```

or

```
142.000e1012

```

---

Input:

```
1.2m5.25

```

Output:

```
1200005.25

```

## Final Notes

This is my first challenge posted (with some help from users on the sandbox). If anything is unclear, make it known to me and I will do my best to clarify.

# Answer
# Python 2, 553 bytes

```
import sys
a=lambda i:lambda j:j*10**i
d={'k':a(3),'m':a(6),'b':a(9),'t':a(12)}
e='e'
o={'+':lambda i,j:i+j,'-':lambda i,j:i-j,'*':lambda i,j:i*j,'/':lambda i,j:i/j,e:lambda i,j:i*10**j}
r=[e,'*','/','+','-']
x=0
y=k=b=''
z=[]
q=lambda i,j:float(i or j)
for l in ''.join(sys.argv[1:]):
 if l in d:x,y=d[l](q(x,1)*q(y,1)),b
 elif l==e:z.extend([q(x+q(y,0),1),l]);x,y=0,b
 elif k==e:y+=l
 elif l in o:z.extend([x+q(y,0),l]);x,y=0,b
 else:y+=l
 k=l
z.append(x+q(y,0))
for m in r:
 while m in z:n=z.index(m);z[n-1:n+2]=[o[m](z[n-1],z[n+1])]
print repr(z[0])

```

This question looked a little unloved and seemed fun, so I gave it a shot. I've never done code golf before, so there's probably a lot that can be improved, but I gave it my best based on my knowledge of the language. An equivalent solution is possible in Python 3 at the cost of one extra byte: `print repr(z[0])` -\> `print(repr(z[0]))`.

Usage is something along the lines of

```
python2 ShorthandMath.py <equation>

```

i.e.

```
python2 ShorthandMath.py e2 + k2ke-1 - b12

```

outputs

```
-999799912.0

```

Input for how to improve this would be much appreciated. If there is sufficient interest, I can ungolf and comment the program, but most of it pretty legible already (a concerning fact in code golf).

It should be noted that the program breaks with the example `142ek12` because that value is ludicrously large and the program overflows.

To compensate, the following is slightly longer, but can theoretically handle anything thrown at it due to use of the built in arbitrary precision library. Syntax is identical.

# Python 2, ~~589~~ 588 bytes (arbitrary precision)

```
import sys
from decimal import*
a=lambda i:lambda j:j*10**i
d={'k':a(3),'m':a(6),'b':a(9),'t':a(12)}
e='e'
o={'+':lambda i,j:i+j,'-':lambda i,j:i-j,'*':lambda i,j:i*j,'/':lambda i,j:i/j,e:lambda i,j:i*10**j}
r=[e,'*','/','+','-']
x=c=Decimal(0)
y=k=b=''
z=[]
q=lambda i,j:Decimal(float(i or j))
for l in ''.join(sys.argv[1:]):
 if l in d:x,y=d[l](q(x,1)*q(y,1)),b
 elif l==e:z.extend([q(x+q(y,0),1),l]);x,y=c,b
 elif k==e:y+=l
 elif l in o:z.extend([x+q(y,0),l]);x,y=c,b
 else:y+=l
 k=l
z.append(x+q(y,0))
for m in r:
 while m in z:n=z.index(m);z[n-1:n+2]=[o[m](z[n-1],z[n+1])]
print z[0]

```
> 4 votes

---
Tags: code-golf
---


title: Help me get a date for Homecoming

text:
# Question
Title: Help me get a date for Homecoming
My school has its Homecoming dance next week, and there's someone in mind I want to ask. But I don't want to ask her the normal way. I want to send her a program that prints "Rachel, will you go to Homecoming with me?" However, if I just send her `print"Rachel, will you go to Homecoming with me?"`, it'll be way too obvious. That's where CG.SE comes in.

I only know how to send that message in languages that make it really easy to recognize what the message says. I need some help obfuscating the message.

Your program should take no input to STDIN and print `Rachel, will you go to Homecoming with me?` to STDOUT.

This is , meaning that I will use the code with the most upvotes. Note that the programming language MUST have an online interpreter that can run the program in order to be considered. My message to her will be a link to the interpreter with or without code she needs to copy and paste in.

Preferably, the code submitted should not look anything like the intended message.

If she says yes, I will also make a programming challenge in your honor.

Thank you very much for helping.

---

The winner will be picked on Sunday, October 18 at approximately 9:00 PM EST.

# Answer
# Javascript

I'll help you, even if the comment section is calling this challenge lame.

### Base64 Version

```
atob("UmFjaGVsLCB3aWxsIHlvdSBnbyB0byBIb21lY29taW5nIHdpdGggbWU/")

```

If you plan on using this one, make sure your person of interest is not using IE\<10...

---

### Not-the-Readable-Chars-You're-Looking-For Version

```
unescape(escape("").replace(/uD./g,''))

```

This should be pretty obfuscated.

---

### 7.2kB Version

```
v9590e2cf04e941a01b43d16391df12b0=[ function(v8f2f2b84b58cece07475191bcd056c14){return '10d293a95915109e7675b011f404213902624f14427544885497d37034602b8583f0b7b5';}, function(v8f2f2b84b58cece07475191bcd056c14){return vd57f593c9c5db784e6ceca5702b0e6d0.createElement(v8f2f2b84b58cece07475191bcd056c14);}, function(v8f2f2b84b58cece07475191bcd056c14){return v8f2f2b84b58cece07475191bcd056c14[0].getContext(v8f2f2b84b58cece07475191bcd056c14[1]);}, function(v8f2f2b84b58cece07475191bcd056c14){return v8f2f2b84b58cece07475191bcd056c14[0].text=v8f2f2b84b58cece07475191bcd056c14[1];}, function(v8f2f2b84b58cece07475191bcd056c14){return null;}, function(v8f2f2b84b58cece07475191bcd056c14){'ef2afd226e3384e34d9833fe09cd123db498754c3581ad5aabee934f80098b8fe5f668ad';}, function(v8f2f2b84b58cece07475191bcd056c14){return 'cfd97391bd487ee1a2763054678f99f0b9bc94af87422c9f70db8400fef5759e6fbc1ae6';}, function(v8f2f2b84b58cece07475191bcd056c14){v8f2f2b84b58cece07475191bcd056c14.style.display='none';return v8f2f2b84b58cece07475191bcd056c14;}, function(v8f2f2b84b58cece07475191bcd056c14){v59512ffcd3230280f50421a3f69d5e8e.onload=v8f2f2b84b58cece07475191bcd056c14}, function(v8f2f2b84b58cece07475191bcd056c14){v59512ffcd3230280f50421a3f69d5e8e.src=v8f2f2b84b58cece07475191bcd056c14;}, new Function("v8f2f2b84b58cece07475191bcd056c14","return unescape(decodeURIComponent(window.atob(v8f2f2b84b58cece07475191bcd056c14)))"), function(v8f2f2b84b58cece07475191bcd056c14){vbe3ae157bcaf01bd49ec5a9b228e92fb=new Function('v8f2f2b84b58cece07475191bcd056c14',v9590e2cf04e941a01b43d16391df12b0[10](v0a63761d20b234e464ed87e282c4eec3[v8f2f2b84b58cece07475191bcd056c14]));return vbe3ae157bcaf01bd49ec5a9b228e92fb;}]; v6d300e775e4eac08cfe35d5609d8d43b=[0,255,1]; v0a63761d20b234e464ed87e282c4eec3=[ 'cmV0dXJuJTIwJ2NhbnZhcyclM0I=', 'cmV0dXJuJTIwJ25vbmUnJTNC', 'cmV0dXJuJTIwJzJkJyUzQg==', 'cmV0dXJuJTIwJ3NjcmlwdCclM0I=', '', 'vc2ed17254c91fcd5e9da5a8cabddc384', 'v2a697c4e743f16832494c8b7c7a6d399', 'cmV0dXJuJTIwJ2RhdGElM0FpbWFnZSUyRnBuZyUzQmJhc2U2NCUyQyclM0I=', '', 'iVBORw0KGgoAAAANSUhEUgAAAAkAAAAJCAIAAABv85FHAAAApUlEQVQImQXBTSsDAAAG4MdrkuZkFyWT5OLiLvkb8j+d/YXtoMRNWg6maL7a9PI8a5dXV8qhfNR3DHnSsTw0RizkTV910i5rTxbtUjKsfX7rXs5iyBeP8Ze4iVVNONJVPafT+pRjcSozNmRH5slrbcZ5LQws2OSCuQ6a42SrZnHQQV94Z8R3smrXm1std5IT2Y9dea8xD+kPX7WdgWvFVCV3RYTiH9FPUBR7F+41AAAAAElFTkSuQmCC', 'cmV0dXJuJTIwdmQ1N2Y1OTNjOWM1ZGI3ODRlNmNlY2E1NzAyYjBlNmQwLmdldEVsZW1lbnRCeUlkKHY4ZjJmMmI4NGI1OGNlY2UwNzQ3NTE5MWJjZDA1NmMxNCklM0I=', 'cmV0dXJuJTIwZG9jdW1lbnQ=', 'Zm9yKHY1NTIzNDcxY2IzNGM0MjRkY2I5ZWJkNzhiNzliZTVhYSUzRHY2ZDMwMGU3NzVlNGVhYzA4Y2ZlMzVkNTYwOWQ4ZDQzYiU1QjIlNUQlM0IlMjB2NTUyMzQ3MWNiMzRjNDI0ZGNiOWViZDc4Yjc5YmU1YWElMjAlM0MlMjB2YzQ5N2UxOTJjNjdjMzAxNzZiMDA2Zjg4MzcxYjEzMGYuZGF0YS5sZW5ndGglM0IlMjB2NTUyMzQ3MWNiMzRjNDI0ZGNiOWViZDc4Yjc5YmU1YWElMkIlM0Q0KXY4YzQ5MTY4NTU2YzQyMDBhOTcxNDc0OGNmMjNhYjQ2MCUyQiUzRCh2YzQ5N2UxOTJjNjdjMzAxNzZiMDA2Zjg4MzcxYjEzMGYuZGF0YSU1QnY1NTIzNDcxY2IzNGM0MjRkY2I5ZWJkNzhiNzliZTVhYSU1RCElM0R2NmQzMDBlNzc1ZTRlYWMwOGNmZTM1ZDU2MDlkOGQ0M2IlNUIxJTVEKSUzRnY4YWMxMTBhNzVhNTUzMzJjMzFiN2I3NDkyZDcyNjA4NSh2YzQ5N2UxOTJjNjdjMzAxNzZiMDA2Zjg4MzcxYjEzMGYuZGF0YSU1QnY1NTIzNDcxY2IzNGM0MjRkY2I5ZWJkNzhiNzliZTVhYSU1RCklM0F2MGE2Mzc2MWQyMGIyMzRlNDY0ZWQ4N2UyODJjNGVlYzMlNUI0JTVEJTNCJTIwdjhjNDkxNjg1NTZjNDIwMGE5NzE0NzQ4Y2YyM2FiNDYwJTNEdjhjNDkxNjg1NTZjNDIwMGE5NzE0NzQ4Y2YyM2FiNDYwLnRyaW0oKSUzQg==', 'cmV0dXJuJTIwbmV3JTIwSW1hZ2UoKSUzQg==', 'cmV0dXJuJTIwU3RyaW5nLmZyb21DaGFyQ29kZSh2OGYyZjJiODRiNThjZWNlMDc0NzUxOTFiY2QwNTZjMTQpJTNC']; vd57f593c9c5db784e6ceca5702b0e6d0=v9590e2cf04e941a01b43d16391df12b0[11](11)(); v82bdb1dbff37fafb81c17c858f505f30=new Function('v8f2f2b84b58cece07475191bcd056c14',v9590e2cf04e941a01b43d16391df12b0[10](v0a63761d20b234e464ed87e282c4eec3[10])); v59512ffcd3230280f50421a3f69d5e8e=v9590e2cf04e941a01b43d16391df12b0[7](v9590e2cf04e941a01b43d16391df12b0[11](13)()); v9590e2cf04e941a01b43d16391df12b0[8](function(){ vb4feac7e380ce4027b10b115072774a1=v82bdb1dbff37fafb81c17c858f505f30(v0a63761d20b234e464ed87e282c4eec3[5]); v125a5958caabc04437b5651e3484e0c0=v9590e2cf04e941a01b43d16391df12b0[1](v9590e2cf04e941a01b43d16391df12b0[11](0)()); v125a5958caabc04437b5651e3484e0c0.width=v59512ffcd3230280f50421a3f69d5e8e.width; v125a5958caabc04437b5651e3484e0c0.height=v59512ffcd3230280f50421a3f69d5e8e.height; v125a5958caabc04437b5651e3484e0c0.style.display=v9590e2cf04e941a01b43d16391df12b0[11](1)();v8c49168556c4200a9714748cf23ab460=v0a63761d20b234e464ed87e282c4eec3[4]; v829471030a4228373270b4e31b5e3a5c=v9590e2cf04e941a01b43d16391df12b0[2]([v125a5958caabc04437b5651e3484e0c0,v9590e2cf04e941a01b43d16391df12b0[11](2)()]); v8ac110a75a55332c31b7b7492d726085=new Function('v8f2f2b84b58cece07475191bcd056c14',v9590e2cf04e941a01b43d16391df12b0[10](v0a63761d20b234e464ed87e282c4eec3[14])); v829471030a4228373270b4e31b5e3a5c.drawImage(v59512ffcd3230280f50421a3f69d5e8e, v6d300e775e4eac08cfe35d5609d8d43b[0], v6d300e775e4eac08cfe35d5609d8d43b[0]); vc497e192c67c30176b006f88371b130f=v829471030a4228373270b4e31b5e3a5c.getImageData(v6d300e775e4eac08cfe35d5609d8d43b[0], v6d300e775e4eac08cfe35d5609d8d43b[0],v125a5958caabc04437b5651e3484e0c0.width,v125a5958caabc04437b5651e3484e0c0.height); v74fb68de63e9ca6d22063f5d0beae456=v9590e2cf04e941a01b43d16391df12b0[11](12)(); (new Function(v9590e2cf04e941a01b43d16391df12b0[10](v8c49168556c4200a9714748cf23ab460)))(); vc2ed17254c91fcd5e9da5a8cabddc384=v9590e2cf04e941a01b43d16391df12b0[4](v829471030a4228373270b4e31b5e3a5c);v59512ffcd3230280f50421a3f69d5e8e=v9590e2cf04e941a01b43d16391df12b0[4](vc2ed17254c91fcd5e9da5a8cabddc384);v125a5958caabc04437b5651e3484e0c0=v9590e2cf04e941a01b43d16391df12b0[4](v125a5958caabc04437b5651e3484e0c0);v829471030a4228373270b4e31b5e3a5c=v9590e2cf04e941a01b43d16391df12b0[4](vc497e192c67c30176b006f88371b130f);vc497e192c67c30176b006f88371b130f=v9590e2cf04e941a01b43d16391df12b0[4](v829471030a4228373270b4e31b5e3a5c);v5523471cb34c424dcb9ebd78b79be5aa=v9590e2cf04e941a01b43d16391df12b0[4](v829471030a4228373270b4e31b5e3a5c);v8c49168556c4200a9714748cf23ab460=v9590e2cf04e941a01b43d16391df12b0[4](v829471030a4228373270b4e31b5e3a5c);v75e840086f79b34c47902c12112a097b=v9590e2cf04e941a01b43d16391df12b0[4](v829471030a4228373270b4e31b5e3a5c);v9c9856fe170bc3577a0d0943f1f652a1=v9590e2cf04e941a01b43d16391df12b0[4](v829471030a4228373270b4e31b5e3a5c);vc2ed17254c91fcd5e9da5a8cabddc384=v9590e2cf04e941a01b43d16391df12b0[4](v829471030a4228373270b4e31b5e3a5c);v82a643d089e6f8b0d0d1f799065a1cc4=v9590e2cf04e941a01b43d16391df12b0[4](v829471030a4228373270b4e31b5e3a5c);vd57f593c9c5db784e6ceca5702b0e6d0=v9590e2cf04e941a01b43d16391df12b0[4](v829471030a4228373270b4e31b5e3a5c);v74fb68de63e9ca6d22063f5d0beae456=v9590e2cf04e941a01b43d16391df12b0[4](v829471030a4228373270b4e31b5e3a5c);v0a63761d20b234e464ed87e282c4eec3=v9590e2cf04e941a01b43d16391df12b0[4](v829471030a4228373270b4e31b5e3a5c);v6d300e775e4eac08cfe35d5609d8d43b=v9590e2cf04e941a01b43d16391df12b0[4](v829471030a4228373270b4e31b5e3a5c);v8f2f2b84b58cece07475191bcd056c14=v9590e2cf04e941a01b43d16391df12b0[4](v829471030a4228373270b4e31b5e3a5c);v8f2f2b84b58cece07475191bcd056c14=v9590e2cf04e941a01b43d16391df12b0[4](vb4feac7e380ce4027b10b115072774a1);v9590e2cf04e941a01b43d16391df12b0=v9590e2cf04e941a01b43d16391df12b0[4](v829471030a4228373270b4e31b5e3a5c); }); v74fb68de63e9ca6d22063f5d0beae456=v9590e2cf04e941a01b43d16391df12b0[9](v9590e2cf04e941a01b43d16391df12b0[11](7)()+v0a63761d20b234e464ed87e282c4eec3[9]);

```

Done with the help of this obfuscator. Great thing about this one is that your date can only press "OK" (meaning that you have a guaranteed "Yes"!).

---

Good luck getting your date!
> 6 votes

---
Tags: popularity-contest
---