# Question
Title: Convert short month names to their longer counterparts [Ended]
**This challenge has ended!** Congratulations **Flonk**!

I was sure I would get a good grade, but after turning in Flonk's my work, my professor did not believe it was mine and also could not understand why it was so complicated... I failed *and* my mom grounded me from Facebook and Minecraft for a month. I don't understand. :(

Thanks for all your submissions! Some great answers here. The official winner is **Flonk** with a score of **64**. The top 5 are:

1. Flonk, 64 (Haskell, with efficient maths!)
2. DigitalTrauma, 40 (The cloud, the future is now)
3. primo, 38 (Python, and my personal favorite - and very professional much!)
4. Sylwester, 20 (Racket, although Janember is stretching it!)
5. ilmale, 16 (A *highly* optimized algorithm in Lua)

Original challenge below.

---

Please help me, it's very urgent!!! :(

I need to convert shortened versions of month names to their longer representations (e.g "Dec" -\> "December"), case-insensitive. Right now I'm using Java; the month's name is a String and I would rather not convert it to a Date object first. Any language will do, though.

Is there an easy way to do this?? Go easy please I am a newbie to programming!

---

This is a **code trolling** popularity contest (the best kind there is!). The answer with the most upvotes on Apr 8, 2014 wins.

# Answer
> 74 votes
It's really simple with a little polynomial interpolation!

First, I looked at the list of short month names

```
["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"]

```

and checked the sum of their characters ASCII values

```
[313,301,320,323,327,333,331,317,328,326,339,300]

```

then subtracted 300 from those to get a grasp of what I'm dealing with here, and prepared an Array that contains all the longer versions of the months' names.

```
[13,1,20,23,27,33,31,17,28,26,39,0]
mons = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

```

I guess you can see what's going on now - all I need is a function getIndex that maps 13 to 0, 1 to 1, 20 to 2, and so on, so I can simply do

```
getMonthName shortname = mons !! (getIndex shortname)

```

Luckily, Wolfram|Alpha can do this for me! The numbers get a bit large, but Haskell can handle that with grace. We just need to make sure to round the results, because floating-point-arithmetic is a little imprecise! So there you go, fast, elegant, and idiomatic Haskell:

```
import Data.Char

getIndex x = round $ 11 -
    (220797068189915461*x)/11644212222720 +
    (184127469431441671621*x^2)/6982771136140800 -
    (8800438195450444577647153*x^3)/1013060436431307264000 +
    (2826703553741192361967823*x^4)/2026120872862614528000 -
    (269098602165195540339443*x^5)/2026120872862614528000 +
    (13744405529566098359*x^6)/1692665725031424000 -
    (13060656886070844161*x^7)/39727860252208128000 +
    (5939638907108115199*x^8)/675373624287538176000 -
    (303426664924585177*x^9)/2026120872862614528000 +
    (2983240583426137*x^10)/2026120872862614528000 -
    (12901227927103*x^11)/2026120872862614528000

mons = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
getMonthName = (mons!!).getIndex.subtract 300.fromIntegral.sum.fmap (ord.toLower)

```

Run it simply like this:

```
λ> getMonthName "DeC"
"December"

λ> getMonthName "jan"
"January"

```

# Answer
> 46 votes
# Bash + GNU tools + "the cloud"

Google has the answer to everything, and *I'm feeling lucky*:

```
wget -qU Mozilla -O- "http://www.google.com/search?q=$1+month&btnI" | grep -Eo "<title>[[:alpha:]]+" | cut -d\> -f2

```

In use:

```
$ ./longmonth.sh jan
January
$ ./longmonth.sh feb
February
$

```

# Answer
> 43 votes
## Python

Because this function is very important, it will probably be used a lot, so you should try to make it as fast as possible. Other posters have recommended using a hashmap look-up... don't do this! Hashmaps are *really slow* compared to arrays. You just need to convert each abbreviation to a number. There's a standard hashing technique that can be used for this:

```
index = reduce(int.__mul__, (ord(c) for c in abbr))

```

This is almost guaranteed to be unique, and lots of professional tools use this.

Now you need to create a look-up function:

```
def month_abbr_to_name(abbr):
  months = ["Unknown"] * 2000000

  months[679932]  = "December"
  months[692860]  = "Febuary"
  months[783315]  = "August"
  months[789580]  = "January"
  months[829920]  = "April"
  months[851466]  = "March"
  months[903749]  = "May"
  months[907236]  = "October"
  months[935064]  = "July"
  months[938896]  = "September"
  months[952380]  = "June"
  months[1021644] = "November"

  index = reduce(int.__mul__, (ord(c) for c in abbr))

  month_name = months[index]

  if month_name == "Unknown":
    raise ValueError("Invalid month abbreviation!")

  return month_name

```

And use it like this:

`print month_abbr_to_name("Dec")``December`

HTH!

---

**Trolling**

> \- This code is horrendously slow. Although array access is indeed faster than hashmaps, this doesn't apply if the array is thousands of times larger than the necessary hashmap would be.
> \- This incredibly large array is created again, and again, every time the function is called. To waste a little more space, each value is initialized with "Unknown".
> \- The hashing function is meant to be obscure to someone unfamilar with Python. I add that it is "used in lots of professional tools" to discourage investigation.
> \- The hashing function is unique enough to distiquish between the twelve months correctly, but will not catch many common typos, such as swapped characters.
> \- Just about any string longer than 3 chars will crash on array index out of bounds.
> \- "Febuary" is misspelled.
> \- "This function is very important." Minor ego-rub for the OP.

# Answer
> 25 votes
# Racket

I go for a KISS solution. I've test it with OP's use case "Dec" with all caps to check if the correct result is returned. It passed with flying colors.

```
(define (long-month short-month)
  (define end "ember")
  (string-titlecase
   (string-append short-month end)))

;; Test OP's use case
(long-month "DEC") ;;==> "December"

```

Obviously the trolling here is that it only works for a few cases so it's useless :-)

# Answer
> 22 votes
# LUA

My solution will work in your locale language, your professor will be happy

```
input = ...
found = false
input = string.lower(input)

i = 12
while i > 0 do
   abb = os.date("%b")
   if string.lower(abb) == input then
      print(os.date("%B"))
      return
   end
   os.execute('sleep 28d')
   i = i - 1
end
print('not found')

```

Test

```
lua 25207.lua aPr
April

```

> Check the abbreviation of the current month, if correct return the long string otherwise try again.. ONE MONTH LATER

# Answer
> 13 votes
# Perl

```
use re 'eval';$_=lc<>;
s/b/br/;s/an|br/$&uary/;s/(?<!u)ar/arch/;s/r$/ril/;s/p$/pt/;s/t|v|c$/$&ember/;
s/ju(.)/$&.$1=~tr\/nl\/ey\/r/e;s/(?<=g)/ust/;s/ctem/cto/;
print ucfirst;

```

---

> \- Regex hell. I hope regex doesn't count as "trolling by obscure language".
> \- Extremely fragile. You'd have a hard time adding a support for Bugsember.
> \- Unreadable. Pattern inside pattern makes it even more so.
> \- Compression of June and July into a single statement doesn't actually compress anything.
> \- random usage of lookbehind for `g`, while others repeat the pattern in the substitution.
> \- `use re 'eval'` is actually not needed; it's only used when a variable pattern is wanted. Also, use of `eval` to "gain" a little "compression".

# Answer
> 10 votes
# Bash + coreutils + paq8hp12

The answer that is currently upvoted the most has to access the internet for every query. In addition to being very inefficient, this also means that your script will fail if there's no internet.

It's better to store the necessary information on your hard disk. Of course, you could store just the data needed for this very script, but that would require different data for different tasks. It is much better to store all data you could possibly need in a single multi-purpose file.

```
# This script is supposed to output only the wanted information, so we'll have to close
# STDERR and make sure accidental keyboard presses don't show any characters on the screen.

exec 2>&-
stty -echo

# Unfortunately, Bash doesn't have goto labels. Without them, it's impossible to use if
# statements, so we'll implement them.

goto()
{
    exec bash <(egrep -A 1000 "^: $1" $0) $BASH_ARGV
}

# We'll need enwik8, a magic file containing all the important Wikipedia data. EVERYTHING
# can be found on Wikipedia, so this file contains all the information any script could
# possibly need.

ls | grep -q enwik8 && goto alreadydownloaded

# Too bad.

wget http://mattmahoney.net/dc/enwik8.zip
unzip enwik8.zip

# ZIP is a very wasteful format and hard disk space is expensive. It is best to compress
# the file using a more efficient algorithm.

wget http://mattmahoney.net/dc/paq8hp12any_src.zip
unzip paq8hp12any_src.zip

# Make the compression program executable and compress the magic Wikipedia file.

chmod +x paq8hp12_l64
./paq8hp12_l64 enwik8.paq8 enwik8

: alreadydownloaded

# Extract the enwik8 file from the paq archive.

./paq8hp12_l64 enwik8.paq8 enwik8

# Now we use a simple POSIX Basic Regular Expression to find the required information in
# the file.

cat enwik8 | egrep -io "[0-9].[a-z]?[a-z]?[a-z]?[a-z]?[a-z]?[a-z]?[a-z]?[a-z]?[a-z]?[a-z]?[a-z]?[a-z]?[a-z]?[a-z]?[a-z]?.[0-9]" | sort | uniq -c | sort -n | tac | egrep -o "$1[a-z]*" | sort | uniq -c | sort -n | tac | head -n 1 | cut -d ' ' -f 7

# We're done.

```

# Trolling

* > Closes STDERR, so we won't be able to debug the script if it fails.
* > Disables input echoing, which persists after the script has finished. If executed from a terminal, you have to execute **stty echo** to get your terminal usable again. If not executed from a terminal, this could crash the script.
* > Requires implementing **goto** first. As if that wasn't bad enough on its own, the **goto** function won't work if the script's filename contains spaces.
* > We won't download the archive if a file containing the string *enwik8* exists in the current directory. This *might* work.
* > Downloading a 100 MB file (even if compressed to 36 MB) is obviously overkill for this task. Plus, *enwik8* contains the first 100 MB of a 4+ GB Wikipedia dump, so for a specific task, it's unlikely to contain any useful information.
* > Compressing the file with paq8hp12 shrinks it to 16 MB, but compression and decompression both take one hour. It actually will do both the first time this script is run.
* > The script doesn't delete the zipped or raw version of *enwik8*, so shrinking it to 16 MB consumed even more hard disk space.
* > The compression utility will only work on 64-bit processors.
* > It leaves all the files that have been downloaded or extracted in the current directory.
* > It doesn't explain the most tricky part of the script, which is the regex-pipe monster. It basically extracts all strings between 4 and 19 bytes that have a leading and trailing digit, sorts those strings by number of occurrences, filters the strings containing the short month name, sorts again by number of occurrences and displays the most frequent.
* > Even if the above *was* a good idea, **cat** is unneeded at the beginning, **egrep** is rather slow for this task, the regex will return *a lot* of false positives (everything could be done with one regex), the first **sort | uniq -c | sort -n | tac** accomplishes absolutely nothing, it uses **sort | tac** instead of **sort -r** and **cut** won't work reliably since the number of spaces at the beginning is variable.
* > The regex is an *Extended* POSIX Regular Expression, so googling the BRE syntax won't help at all.
* > Returns **Nov** instead of **November** and **6** instead of **August**.

# Answer
> 10 votes
# Java

You said your current code's in Java, so I thought I'd make things easy for you.

```
// The standard library's there, so you should use it
import static java.util.Calendar.*;

public class MonthConverter {

  private static int shortNameToNumber(String shortName) {
    int i;
    switch (shortName) {
      case "jan": i = 1;
      case "feb": i = 2;
      case "mar": i = 3;
      case "apr": i = 4;
      case "may": i = 5;
      case "jun": i = 6;
      case "jul": i = 7;
      case "aug": i = 8;
      case "sep": i = 9;
      case "oct": i = 10;
      case "nov": i = 11;
      case "dec": i = 12;
      default: i = 0;
    }
    return i;
  }

  private static String numberToLongName(int month) {
    switch (month) {
      case JANUARY: return "January";
      case FEBRUARY: return "February";
      case MARCH: return "March";
      case APRIL: return "April";
      case MAY: return "May";
      case JUNE: return "June";
      case JULY: return "July";
      case AUGUST: return "August";
      case SEPTEMBER: return "September";
      case OCTOBER: return "October";
      case NOVEMBER: return "November";
      case DECEMBER: return "December";
      default: return "Unknown";
    }
  }

  public static String fullName(String shortName) {
    return numberToLongName(shortNameToNumber(shortName));
  }

  public static void main(String[] args) {
    // Always test your code
    System.out.println("jan is: " + fullName("jan"));
    assert fullName("jan").equals("January");
  }
}

```

> The Calendar class has a fun little gotcha where months are numbered starting at 0 - so `JANUARY == 0`. However, this clearly can't affect our code, as we test it, right? Notice that there's an unintended switch fallthrough in shortNameToNumber, which means every month ends up being 0. Handily, `JANUARY == 0`, so our test passes.

# Answer
> 9 votes
# Python + SQLite

Many of the answers so far make the mistake of hard-coding the month names. But, you never know when some Pope or President is going to make us switch to another calendar, and then tons of date parsing/formatting code will instantly become worthless! (Or, more commonly, when you need to internationalize your program.)

What you need is a database.

```
CREATE TABLE tblShortMonthNames (
   MonthAbbr CHAR(3) PRIMARY KEY NOT NULL COLLATE NOCASE,
   MonthID   INTEGER NOT NULL
);

CREATE TABLE tblFullMonthNames (
   MonthID   INTEGER PRIMARY KEY,
   MonthName VARCHAR(9) NOT NULL
);

INSERT INTO tblFullMonthNames VALUES (1, 'January');
INSERT INTO tblFullMonthNames VALUES (2, 'February');
INSERT INTO tblFullMonthNames VALUES (3, 'March');
INSERT INTO tblFullMonthNames VALUES (4, 'April');
INSERT INTO tblFullMonthNames VALUES (5, 'May');
INSERT INTO tblFullMonthNames VALUES (6, 'June');
INSERT INTO tblFullMonthNames VALUES (7, 'July');
INSERT INTO tblFullMonthNames VALUES (8, 'August');
INSERT INTO tblFullMonthNames VALUES (9, 'September');
INSERT INTO tblFullMonthNames VALUES (10, 'October');
INSERT INTO tblFullMonthNames VALUES (11, 'November');
INSERT INTO tblFullMonthNames VALUES (12, 'December');

INSERT INTO tblShortMonthNames
   SELECT SUBSTR(MonthName, 1, 3), MonthID FROM tblFullMonthNames;

```

Then, just write a simple program to query it.

```
import sqlite3
import sys

QUERY = """SELECT tblFullMonthNames.MonthName
FROM tblShortMonthNames INNER JOIN tblFullMonthNames USING (MonthID)
WHERE tblShortMonthNames.MonthAbbr = ?"""

with sqlite3.connect('months.db') as db:
    for abbr in sys.argv[1:]:
        row = db.execute(QUERY, [abbr]).fetchone()
        if row:
            print(row[0])
        else:
            print(abbr + ' is not a valid month name.')

```

# Answer
> 5 votes
# SH & a friend (date)

The function:

```
longmonth() {
    date +%B -d"$1 1"
}

```

Testing it:

```
$ echo $LANG
de_DE.utf8
$ for i in jan feb mar apr may jun jul aug sep oct nov dec ; do longmonth $i ; done
Januar
Februar
März
April
Mai
Juni
Juli
August
September
Oktober
November
Dezember
$ LANG=C
$ for i in jan feb mar apr may jun jul aug sep oct nov dec ; do longmonth $i ; done
January
February
March
April
May
June
July
August
September
October
November
December

```

It is short... but calculate it's "evil per character" ratio... mwhuaaahahahaaa...

# Answer
> 4 votes
# perl

How about some good ol' brute force?

```
$|++;

use List::Util qw(reduce);

sub hash {
    my $t=9;
    (reduce { $a*$b*log(++$t+$a) } map { ord() } split//, shift)%54321098
}

my @m = (qw( january february march april may june
             july august september october november december ) );
my %targets = map { hash($m[$_]) => 1 } (0..$#m);

chomp(my $in = lc <>);

print ucfirst $in;

my $r;
if(!$targets{hash($in)}) {
  $r = "a";
  ++$r until $targets{hash($in.$r)};
}
print "$r\n";

```

Why this is awesome:

* brute force is always the manliest way to do it.
* for your convenience, prints the partial answer as soon as it knows it (I bet you didn't know that "Feb" is short for something starting with "Feb..."???)
* custom hashing function for maximal security.
* use of perl's built-in operator overloading (increment on strings) makes this code as fast as native C code. Look at all those zeroes, showing just how fast it runs!

```
ski@anito:/tmp$ for m in mar apr may jun jul  ; do echo $m | time -f "%U user" perl brute.pl ; done
March
0.00 user
April
0.00 user
May
0.00 user
June
0.00 user
July
0.00 user

```
* The algorithm is intuitively obvious, and I leave a proof as an exercise to the reader, but just to make sure it works in all cases, let's check August, one of the -ber months, and one of the -uaries to make sure we didn't miss anything:

```
ski@anito:/tmp$ for m in aug jan oct ; do echo $m | perl brute.pl  ; done
August
January
October

```

Trollage:

Leaving aside the coding practices that would make Damian Conway die on sight, this code is intermittently wrong, and intermittently extremely slow. "Feb" runs about 6 orders of magnitude - one million times - slower than "may", "jun", or "jul". Feboapic, Sepibnd, Novgpej, and Decabjuj are not months (although they are fun to try to pronounce).

```
    ski@anito:/tmp$ for m in jan feb mar apr may jun jul aug sep oct nov dec ; do echo $m | time -f "%U user" perl  brute.pl  ; done
    January
    3.14 user
    Feboapic
    62.77 user
    March
    0.00 user
    April
    0.00 user
    May
    0.00 user
    June
    0.00 user
    July
    0.00 user
    August
    0.10 user
    Sepibnd
    1.33 user
    October
    2.22 user
    Novgpej
    1.11 user
    Decabjuj
    4.27 user

```

PS - I had some code that has an even greater spread of runtimes, but it boringly outputs the correct answer in all cases, which is much less fun.

# Answer
> 3 votes
# JavaScript - Optimized Node cluster with Branches, Leaves, and string barrels.

```
// fullMon - Converts month key names to full names using a highly optimized tree for fast traversal.
function fullMon(key) {

    // Initialize the full month string
    var fullMonth = "";

    // Make sure the key is capitalized.
    key = key.substr(0,1).toUpperCase() + key.substr(1).toLowerCase();

    // Set the current node to the tree root.
    var current = fullMon.tree;

    // Traverse the characters in key until we can go no further.
    for (var i = 0; i < key.length; i++) {
        var c = key.charAt(i)
        fullMonth += c
        if (typeof current[c] === "undefined") return key // no full month for this key
        current = current[c]
    }

    // The remaining leaves are the characters in the full month.
    while (current !== null) {
        for (c in current) fullMonth += c
        current=current[c]
    }
    return fullMonth
}

// fullMon.treeBuilder - Builds a character node tree of full month names.
fullMon.treeBuilder = function() {
    // Set a barrel of month keys.
    var barrel = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

    // Root node for letter tree.
    var tree = {};

    // Loop through all month keys.
    for (var i = 0; i < barrel.length; i++) {

        // Get the next month key and do a barrel roll by
        // splitting into an array of single character strings.
        var monKey = barrel[i].split("");

        // Set the current branch to the tree root.
        var branch = tree;

        // Climb branches in the tree by looping through
        // month key characters and doing leaf wipes.
        for (var c = 0; c < monKey.length; c++) {

            // The next character is the next leaf of the branch.
            var leaf = monKey[c];

            // Wipe this leaf on the branch if it doesn't already exist.
            if (typeof branch[leaf] === "undefined") {
                // If the leaf is the last character then it's not sticky should be set to null.
                branch[leaf] = (c === (monKey.length-1)) ? null : {};
            }

            // Switch to the next branch.
            branch = branch[leaf];
        }
    }
    return tree;
}

fullMon.tree = fullMon.treeBuilder();

fullMon.demo = function () {
    // Demonstrates keys that are not found "none" and found keys.
    var short = ["none","jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"];
    for (var i = 0; i < short.length; i++) {
        console.log(fullMon(short[i]));
    }
    // Shows the optimized tree for fast lookups.
    console.log(JSON.stringify(fullMon.tree));
}

fullMon.demo();

```

# Answer
> 3 votes
## Java, Google and Probability

I am disappointed that so many of the solutions here "reinvent the wheel" when the answer is easily available on the internet.

Here is my program's output:

```
The short version of jan is january
The short version of feb is february
The short version of mar is margin
The short version of apr is april
The short version of may is mayinhistory
The short version of jun is june
The short version of jul is july
The short version of aug is august
The short version of sep is september
The short version of oct is october
The short version of nov is november
The short version of dec is december

```

Not perfect, but good enough to send to QA. I was able to achieve these results by leveraging the power of crowdsourcing:

```
public static String expandMonthName(String shortMonthName) {
    try {
        // First, we ask Google for the answer

        String query = "https://www.google.com/search?q="
                + "what+month+is+" + shortMonthName;
        String response = curl(query);

        // now sift through the results for likely answers.
        // The best way to parse HTML is regex.

        List<String> possibleMonths = new ArrayList<>();
        Pattern pattern = Pattern.compile(shortMonthName + "[A-Za-z]+");
        Matcher matcher = pattern.matcher(response);
        while (matcher.find())
            possibleMonths.add(matcher.group(0));

        // And finally, choose the likeliest answer using
        // the ineluctable laws of probability

        return possibleMonths.get(new Random().nextInt(possibleMonths.size()));

    } catch (Exception e) { return "August";}   // well, we tried.
}

```

> If it's not clear, expandMonthName("jan") returns a randomly selected word beginning with "jan" from the Google result for "what month is jan". Unless you're behind a proxy, in which case it returns "August."

# Answer
> 2 votes
# Bash + binutils

I tried hard to do the obvious by converting the input to a date object, but failed miserably. Finally I resorted to brute-force approach.

```
while read -e line; do
  [[ "${line,,}" == "${1,,}"* ]] && o=$line && break
done < <(strings /bin/date)
o=${o:=$1}
o=${o,,}
echo ${o^}

```

Test runs:

```
$ bash getmonth.sh jan
January
$ bash getmonth.sh may
May
$ bash getmonth.sh DEC
December

```

# Answer
> 2 votes
I understand that checking months' names is very hard, and it requires lots of computation and logic thinking. Here's an optimized version of the Buzz-Strahlemann algorythm for checking months' names.

# PHP

```
$month = "Jan"; //Change this to search for a different month, noob :)
$time = time(); //This loads an extended time library
$ivefoundthismonthnowexit = false;
while (!$ivefoundthismonthnowexit) {
    $checkThis = date('F', $time); //"F" stands for "Find it"
    if (substr($checkThis, 1, 4) == $month) $ivefondthismonthnowexit = true; //You can also replace it with ($checkThis, 0, 3)
    //since PHP understands if you are counting from 0 or 1!
    $time++;
}

```

**Trolls:**

* This answer;
* Doesn't handle timezones and will output a warning message;
* Doesn't accept month as an input, but you need to hardcode it;
* Even when you hardcode it, it's case-sensitive;
* What this code tries to do is to get the current month, get the first three letters, and check if it matches with `$month`. If it does not match, it increments the timestamp by 1 and then retries. This ends up to be **EXTREMELY SLOW**;
* This code outputs nothing (except the warning, of course);
* Comments are very misleading: `time()` does not load an extended time library, but gets the current timestamp; `substr($checkThis,1,4)` skips the first letter of the month and gets the following 4 (`arch` for `March`, e.g.); The correct form is the one in the comments;
* Even when a match is found, the code won't exit the loop: in fact, the variable that gets set to `true` is different.

# Answer
> 2 votes
# Batch

What you're asking for is non-trivial. However I have found the perfect solution for you! How this works is by downloading a highly intricate list of the English language to your hard-disk. The input is then checked against the downloaded list and the final name of the month is given! Genius!

Now, this method has many pros over other methods, some being:

* You can have any abbreviation of the word! E.g. `Jan` or `Janu` for January!
* "You never know when some Pope or President is going to make us switch to another calendar, and then tons of date parsing/formatting code will instantly become worthless!" This is never a problem with our method!
* The user is sent confirmation prompts, better safe than sorry!

## The Code:

```
@ECHO OFF
setlocal EnableDelayedExpansion
REM Remove this at the end ^^^
REM First off, we have to get the user's input
set /p abbreviatedUserInput= Please input your abbreviated form of the month:
REM echo out confirmation message. Without this, the thing won't work
SET /P variableThatIsUsedForConfirmation= Are you sure you want to look for %abbreviatedUserInput% (Y/N)?
REM if the user said no, send him elsewhere
if /i {%variableThatIsUsedForConfirmation%}=={n} (goto :hell)
REM to keep things clean, we clear the screen!
cls
ECHO Prepare for launch!
REM make sure the user reads what we wrote, we spent time on this and the user must understand that...
REM BTW this pings an incorrect ip address and waits 3000 millisex for the output
ping 1.1.1.1 -n 1 -w 3000 > nul
REM to keep things clean, we clear the screen!
cls
REM We must inform the user that something is going on, otherwise they might get bored and quit the app
ECHO LOA-DING!
REM Now, how this works is by utilizing the dictionary.. I believe we all know what that is. First of all, let's get a dictionary!
powershell -Command "(New-Object Net.WebClient).DownloadFile('http://www.mieliestronk.com/corncob_caps.txt', 'dic.txt')"
REM to keep things clean, we clear the screen!
cls
REM The user probably already got bored, let's inform them that we're still working...
ECHO STILL WORKING...
REM wait what?!! The dictionary is all caps!! Lets fix that...
REM Lets loop through the file like so:

for /F "tokens=*" %%A in (dic.txt) do (
    SET "line=%%A"
    REM replace ALL the letters!!
    SET "line=!line:A=a!"
    SET "line=!line:B=b!"
    SET "line=!line:C=c!"
    SET "line=!line:D=d!"
    SET "line=!line:E=e!"
    SET "line=!line:F=f!"
    SET "line=!line:G=g!"
    SET "line=!line:H=h!"
    SET "line=!line:I=i!"
    SET "line=!line:J=j!"
    SET "line=!line:K=k!"
    SET "line=!line:L=l!"
    SET "line=!line:M=m!"
    SET "line=!line:N=n!"
    SET "line=!line:O=o!"
    SET "line=!line:P=p!"
    SET "line=!line:Q=q!"
    SET "line=!line:R=r!"
    SET "line=!line:S=s!"
    SET "line=!line:T=t!"
    SET "line=!line:U=u!"
    SET "line=!line:V=v!"
    SET "line=!line:W=w!"
    SET "line=!line:X=x!"
    SET "line=!line:Y=y!"
    SET "line=!line:Z=z!"
    ECHO !line! >> dic-tmp.txt
)

REM to keep things clean, we clear the screen!
cls
REM The user probably already got bored, let's inform them that we're still working...
:lookup
ECHO WOW! THAT TOOK LONG! ALMOST THERE...
REM Alright, now we need to find the correct date in the dictionary, we might need the users help in this...
REM Lets loop through ALL the lines again
set match=seriously?
for /F "tokens=*" %%a in (dic-tmp.txt) do (
    SET "line=%%a"
    REM to keep things clean, we clear the screen!
    cls
    REM replace the user input with some other stuff...
    SET "test=!line:%abbreviatedUserInput%=lol!"
    REM if the original line does not equal the test variable, then we have a match!
    IF NOT !line!==!test! (
        REM ask the user if the match is correct..
        set /P variableThatIsUsedForConfirmation= "Did you mean !line!? (Y/N): "
        REM if the user entered "y"
        IF /i {!variableThatIsUsedForConfirmation!}=={y} (
            REM set the variable "match" to the current line and goto the matchFound section...
            set match=!line!
            goto :matchFound
        )
    )
)
:matchFound
REM to keep things clean, we clear the screen!
cls
REM give the user their match
Echo Here's your month's full name: %match%
PAUSE
:hell
ECHO screw you!

```

## Trollz

> \- Batch... \- Downloading a list of words, because we can't type out the months manually... \- Not using switch case hack \- VERY SLOW \- converting the text file to lowercase and saving it in another file \- run it a second time without deleting the text files created and it will be even slower \- Something ticks the script off while converting the dic.txt file to lowercase, this sets echo back on \- This spoiler thing has messed up formatting by the way...

# Answer
> 2 votes
# ! #/bash

```
! #/bash

# Make the MONTH variable equal to the $1 variable
MONTH="$1"

# Run grep passing the $MONTH variable and the -i flag
# Then use the << operator followed by a list of months
grep -i "$MONTH" << January
March
May
July
August
0ctober
December
April
June
September
November
February
January

```

To make your program respond faster, I have put the months with 31 days earlier in the list. Statistically speaking, given an even distribution of dates, you are more likely to be in one of those months.

I documented each line to impress your boss.

Save this in a file called `lookup_month_script.bash` and copy-paste the following line to test it:

```
bash $PWD/lookup_month_script.bash "0ct"

```

Good luck with your project!

---

> \- Doesn't work for January, despite it being listed *twice*. (We are actually using `January` as the delimiter for the start and end of the heredoc.)
> \- Also doesn't work for October. Nobody can see why.
> \- If the input happens to be empty, returns all 11 months.
> \- If the script is copy-pasted, the June response will be 42 characters in length.
> Minor:
> \- The shebang is somewhat incorrect, but no warning is given.
> \- Comments that are comments which say what the line below them is saying.
> \- Even if the program did respond sooner for the earlier entries, it still wouldn't complete any faster.

# Answer
> 1 votes
# JavaScript - 209

It does say not to convert to a Date, which is not what's happening here, I'm simply using Date to generate the extension of the short name.

```
function m(s){c=s.charAt(0).toUpperCase()+s.substr(1).toLowerCase();a="ember,ember,ober,tember,ust,y,e,,il,ch,uary,uary".split(",");b=[];for(i=12;i--;)b[(""+new Date(1,i,1)).slice(4,7)]=11-i;return c+a[b[c]];}

```

Tests Input/Output:

```
jan: January
feb: Febuary
mar: March
apr: April
may: May
Jun: June
JUL: July
AuG: August
sEp: September
OCT: October
nov: November
dec: December

```

# Answer
> 1 votes
**Java 696 including test input**

```
public class DateConverter {
    String months[] =
    {
        "January", "February","March","April","May","June","July",
        "August","September","October","November","December"
    };
    DateConverter(){}
    String LongMonth(String shortMonth)
    {
        String m = "Invalid";
        for(int i=0;i<months.length;i++)
        {
            if(months[i].toLowerCase().contains(shortMonth.toLowerCase()))
            {
                m=months[i];
                break;
            }
        }
        return m;
    }

    public static void main(String[] args) {

        String input[] = {"jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"};
        for(int i=0; i<input.length; i++)
        {
            System.out.println((new DateConverter()).LongMonth(input[i]));
        }
    }
}

```

# Answer
> 1 votes
The programming language "Brainf\*ck" is a perfect tool for this! It might not be exactly what you were looking for, sure, but it gets the job done flawlessly!

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

This is the debug part of the code used when looping more than once

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

It takes a dummy argument due to the nature of my interpreter
If you're using some other intepreter I can rewrite the code for you

>>>>>>>>>>>>>>>>>>>>>>>,<+<<<<<<<<<<<<<<<<<<<<<<<<->-]>>>>>>>>>>>>>>>>>
[<<<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>>-]<<<<<<<<<<<<<<<<<<[>[-]+<-]>[<+

This is the normal part of the code, used when starting the programme the first time

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

Here we take three arguments and assign them to variables; This is the three-letter
abbreviation of the month

>>>>>>>>>>>>>>,<,<,

Now we check if the abbreviation is good; note that it will fail if it doesn't begin
with a capital letter and isn't followed by two lowercase letters
In general it will print an error message and wait for you to input a letter
(or just hit enter) before it exits

<<<[-]>>>>>[<<<<<+<<<<<<<+>>>>>>>>>>>>-]<<<<<<<<<<<<[>>>>>>>>>>>>+<<<<<<<
<<<<<-]>>>>>>>----------------------------------------------------------------->[-]
<[<<<+>>>-]->[<<<<<<<+>+<<+>>>>>>>>-]<<<<<<<<[>>>>>>>>+<<
<<<<<<-]>>[>>[<+<<<+>>>>-]<<<<[>>>>+<<<<-]+>>>[<<->>>-<<<<->>>[-]]<<<[>>[-]+<<-]>>-]>>
[>>>+<<<[-]]<<<[-]<->>>>>>>[<<<<<<<->>>>>>>-]<<<<<<<[>
>>>>>>+<<<<<<<-]>>>>>>>[>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<->>>>>>>>>[-]]<<<<<<<<-]
<[>[-]+<-]>[<+>>+++++++++++[>++++++>++++++++++>+++<<<-
]>+++.>++++..---.+++.>.[-]<[-]<[-]<++++++++++.[-]>>>>>>>>>>>>>>>,,<<<<<<<<<<<<<<<<<-<-
>>-]>>>>>>>>>>>>>>>>>>>>>>[<<<<<<<<<<<<<<<<<<<<<<<+>>>
>>>>>>>>>>>>>>>>>>>>-]<<<<<<<<<<<<<<<<<<<<<<<[>[-]+<-]>[<+>>>>>>>>>[-]>>>>[<<<<+
<<<<<<<+>>>>>>>>>>>-]<<<<<<<<<<<[>>>>>>>>>>>+<<<<<<<<<<<-]>>
>>>>>-------------------------------->[-
]+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<[<<<+>>>-]>
[<<<<<<<+>+<<+>>>>>>>>
-]<<<<<<<<[>>>>>>>>+<<<<<<<<-]>>[>>[<+<<<+>>>>-]<<<<[>>>>+<<<<-]+>>>[<<->>>-<<<<->>>[-]]
<<<[>>[-]+<<-]>>-]<[>>>>>>-<<<<<<[-]]>>>[-]>>>>[-]>>
>[<<<+<<<<<<<<+>>>>>>>>>>>-]<<<<<<<<<<<[>>>>>>>>>>>+<<<<<<<<<<<-]>>>>>>>>---------------
----------------->[-]+++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<[<<<<+>>>>-]>[<<<<<<<<+>+
<<+>>>>>>>>>-]<<<<<<<<<[>>>>>>>>>+<<<<<<<<<-]>>[>>[<+<<
<+>>>>-]<<<<[>>>>+<<<<-]+>>>[<<->>>-<<<<->>>[-]]<<<[>>[-]+<<-]>>-]>>[>>>>-<<<<[-]]<<<[-
]>>>>>>[<<<<<<<+>>>>>>>-]<<<<<<<[>>>>>>>-<<<<<<<[-]]>
>>>>>>>[<<<<<<<<+>+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]<[>>>>>>>[-]-<<<<<<<[-]]->>>>>>>
[<<<<<<<->>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]>>>>>>>[>>>>
>>>>>>+<<<<<<<<<<<<<<<<<<<->>>>>>>>>[-]]<<<<<<<<-]<[>[-]+<-]>[<+>>+++++++++++
[>++++++>++++++++++>+++<<<-]>+++.>++++..---.+++.>.[-]<[-]<[-]<+
+++++++++.[-]>>>>>>>>>>>>>>>,,<<<<<<<<<<<<<<<<<-<->>-]>>>>>>>>>>>>>>>>>>
[<<<<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>>>-]<<<<<<<<<<<<<<<<<<<[>[-]+<
-]>[<+>>>>>>>>>[-]>>>[<<<+<<<<<<<+>>>>>>>>>>-]<<<<<<<<<<[>>>>>>>>>>+<<<<<<<<<<-]>>>>>>>-
------------------------------->[-]+++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++<[<<<+>>>-]>[<<<<<<<+>+<<+>>>>>>>>-]
<<<<<<<<[>>>>>>>>+<<<<<<<<-]>>[>>[<+<<<+>>>>-]<<<<[>>>>+
<<<<-]+>>>[<<->>>-<<<<->>>[-]]<<<[>>[-]+<<-]>>-]<[>>>>>>-<<<<<<[-]]>>>[-]>>>>[-]>>[<<+
<<<<<<<<+>>>>>>>>>>-]<<<<<<<<<<[>>>>>>>>>>+<<<<<<<<<<-
]>>>>>>>>-------------------------------->[-
]++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
<[<<<
<+>>>>-]>[<<<<<<<<+>+<<+>>>>>>>>>-]<<<<<<<<<[>>>>>>>>>+<<<<<<<<<-]>>[>>[<+<<<+>>>>-]
<<<<[>>>>+<<<<-]+>>>[<<->>>-<<<<->>>[-]]<<<[>>[-]+<<-]>>
-]>>[>>>>-<<<<[-]]<<<[-]>>>>>>[<<<<<<<+>>>>>>>-]<<<<<<<[>>>>>>>-<<<<<<<[-]]>>>>>>>>
[<<<<<<<<+>+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]<[>>>>>>>[-
]-<<<<<<<[-]]->>>>>>>[<<<<<<<->>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]>>>>>>>[>>>>>>>>>>>+
<<<<<<<<<<<<<<<<<<<<->>>>>>>>>[-]]<<<<<<<<-]<[>[-]+<-]>[
<+>>+++++++++++[>++++++>++++++++++>+++<<<-]>+++.>++++..---.+++.>.[-]<[-]<[-]<++++++++++.
[-]>>>>>>>>>>>>>>>,,<<<<<<<<<<<<<<<<<-<->>-]>>>>>>>>
>>>>>>>>>>>[<<<<<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>>>>-]<<<<<<<<<<<<<<<<<<<<[>[-]+<-]>[<+

This part of the code handles special exceptions to the pattern

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

This part of the code handles the regular pattern

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

Here the programme checks if you want to insert another abbreviation or are done with the programme

>-]>>>>>>>>>>>>>>>[<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>-]<<<<<<<<<<<<<<<<[>[-]+<-]>
[<+>>+++++++++++++++[>+++++>++++++++>++>+++++++>++++>+
+++++<<<<<<-]>--.>-----.>++.<+.>>-.-------.<<.>.>.<<--------..>>>+++.<<.>>>+.--.
<<<+++++++++++++++.<<+++++.>>>----.>>[-]<[-]<[-]<[-]<[-]<[-]
<++++++++++.[-]>>>>>>>>>>>>>>>>>>>>>>>,<<<<<<<<<<,<<<<<<[-]>>>>>>[<<<<<<+
<<<<<<<+>>>>>>>>>>>>>-]<<<<<<<<<<<<<[>>>>>>>>>>>>>+<<<<<<<<<<<<<-]>
>>>>>>>[-]++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
<[<<<<<<+>>>>>>-]->[<<<<<<<-<+>>>>>>>>-]<<<<<<<<[>>>
>>>>>+<<<<<<<<-]>[>>>>>>+<<<<<<[-]]>>>>>>[>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<->>>>>>>>>
[-]]<<<<<<<<-]<[>[-]+<-]>[<+>>>>>>>>>[-]>>>>>>[<<<<<
<+<<<<<<<+>>>>>>>>>>>>>-]<<<<<<<<<<<<<[>>>>>>>>>>>>>+<<<<<<<<<<<<<-]>>>>>>>>[-
]+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++<[<<<<<<+>>>>>>-]->[<<<<<<<-<+>>>>>>>>-]<<<<<<<<[>>>>>>>>+
<<<<<<<<-]>[>>>>>>+<<<<<<[-]]<->>>>>>>[<<<<<<<->>>>>>>
-]<<<<<<<[>>>>>>>+<<<<<<<-]>>>>>>>[>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<<<-
>>>>>>>>>[-]]<<<<<<<<-]<[>[-]+<-]>[<+-<->>-]>>>>>>>>>>>>>>>>
>>>>>>>>>[<<<<<<<<<<<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>>>>>>>>>>-]
<<<<<<<<<<<<<<<<<<<<<<<<<<[>[-]+<-]>[<+>>+++++++++++[>++++++>++++++++++>+++
<<<-]>+++.>++++..---.+++.>.[-]<[-]<[-]<++++++++++.[-]<<<->>-]<<]

```

I'm sure your teacher will be proud when you show him this!

---

**Trolling**

> The programme is, first of all, quite badly written. I've made some loops that cause random error prints and general non-workingness for lack of a better word. It takes a bit of cleanup to get decently working code (primarily in the first two paragraphs of it) which is anyhow useless as it gives long names as "abbreviation + 'uary'" (January, Febuary, Maruary etc.) The programme also includes redundant code for "January" (defined as an exception and coded separately). First answer on Stackexchange, so I hope this meets criteria

# Answer
> 1 votes
# Julia

You're going to want to use the power of multiple dispatch here. First we'll define a type of each month. Then we can write simple function definitions for each month type that give the desired answer. This will allows you to use the convenient form of `nicename(Jan)` without having to bother with those annoying quotation marks. Plus we can define a convenience function to accept strings and converting them to types, reuse all the work we already did to provide a totally new interface.

```
abstract Month
abstract Jan <: Month
abstract Feb <: Month
abstract Mar <: Month
abstract Apr <: Month
abstract May <: Month
abstract Jun <: Month
abstract Jul <: Month
abstract Aug <: Month
abstract Sep <: Month
abstract Oct <: Month
abstract Nov <: Month
abstract Dec <: Month
nicename(::Type{Jan})="January"
nicename(::Type{Feb})="February"
nicename(::Type{Mar})="March"
nicename(::Type{Apr})="April"
nicename(::Type{May})="May"
nicename(::Type{Jun})="June"
nicename(::Type{Jul})="July"
nicename(::Type{Aug})="August"
nicename(::Type{Sep})="September"
nicename(::Type{Oct})="October"
nicename(::Type{Nov})="Novermber"
nicename(::Type{Dec})="December"

nicename(s::String)=nicename(eval(symbol(ucfirst(s))))

nicename(Jan)
nicename("jan")

```

# Answer
> 1 votes
# Java

Dear Computer Scientist Apprentice,

This is quite a difficult task, and I have solved only partially: I guess this is for your thesis work or some research purpose.

Up to now I have only beta version with some minor bugs: sometimes it gives the wrong results, but I'm sure your professor will accept your effort.

file Month.java:

```
/**
 * This bean keep track of a month-code (e.g. Apr) and month-name (e.g. April)
 * pair.
 */
public class Month{
    String month_name;
    String month_code;
    public void Month(monthName,monthCode){
        setMonthName(monthName);
        setMonthCode(monthCode);
    }
    public String getMonthName(){
        return this.monthName;
    }
    public void setMonthName(String monthName){
        this.monthName=monthName;
    }
    public String getMonthCode(){
        return this.monthCode;
    }
    public void setMonthCode(String monthCode){
        this.monthCode=monthCode;
    }

```

file Era.java:

```
/**
 * This bean keep contains every couple of month-code,month-name in a year.
 */
public class Era{
    List <Month>months;
    public void Era(){
        months.add(new Month("Jan","January"));
        months.add(new Month("Feb","Febrary"));
        months.add(new Month("Apr","March"));
        months.add(new Month("May","May"));
        months.add(new Month("June","June"));
        months.add(new Month("Jul","July"));
        months.add(new Month("Aug","August"));
        months.add(new Month("Sep","September"));
        months.add(new Month("Oct","October"));
        months.add(new Month("Nov","Novemeber"));
        months.add(new Month("Dec","December"));
   }
   public String getMonthByCode(String monthName){

       return String.format("[%s]",months.get(new Random().nextInt((11) + 1) + 0));
   }
   public static void main(String ... argv){
        String monthCode="jan";
       System.out.println(String.format("%s: %s",monthCode, new Era().getMonthByCode(monthCode));
   }

```

To run it execute:

```
javac Month.java
javac Era.java
java Era jan

```

output:

```
jan: [January]

```

Remember to set your `%JAVAPATH%` to the path where your `Java` compiler is installed!

> It just return a random month. Actually I didn't even test it. I guess some imports are missing.

# Answer
> 1 votes
Since the OP is using Java, I'll give a Java solution. The idea is simple:

1. Create a `Map` from long name to short name.
2. Generate a random String, map it to the short name.
3. Use `String.equalsIgnoreCase` to check whether the short name is same as the input short name ignoring cases. If so, success, exit.
4. Otherwise go to Step 2.

Here is the source:

```
import java.util.*;

public class Short2Long {
    static final Map<String, String> long2Short = new HashMap<String, String>();
    static {
        long2Short.put("Janurary", "jan");
        long2Short.put("February", "feb");
        long2Short.put("March", "mar");
        long2Short.put("April", "apr");
        long2Short.put("May", "may");
        long2Short.put("June", "jun");
        long2Short.put("July", "jul");
        long2Short.put("August", "aug");
        long2Short.put("September", "sep");
        long2Short.put("October", "oct");
        long2Short.put("November", "nov");
        long2Short.put("December", "dec");
    }

    static Random rand = new Random();

    static String genString() {
        int len = rand.nextInt(9-3) + 3;
        StringBuffer res = new StringBuffer(len);
        res.append((char)('A' + rand.nextInt(26)));
        for (int i = 1; i < len; i ++) {
            res.append((char)('a' + rand.nextInt(26)));
        }
        return res.toString();
    }

    public static void main(String[] args) {
        String s = args[0];
        while (true) {
            String l = genString();
            if (s.equalsIgnoreCase(long2Short.get(l))) {
                System.out.println(s + " -> " + l);
                break;
            }
        }
    }
}

```

---

**Trolling**

> The program needs a fast CPU and your patient. When you learn multi-threading and have a multi-core cpu, you can try make it faster.

# Answer
> 1 votes
Thank you for posting this thought provoking and original question. Those of us that post answers on Stack Overflow enjoy the opportunity to help posters, as the purpose of this website is to catalogue all such questions to make the need for text books and self-motivated learning obsolete. Do not be alarmed by your lack of understanding of this particular question, as it is a common type of question asked because of its hidden trick required to solve it effectively. Instructors will commonly ask this question to determine not only your depth of understanding of the language, but also whether you where aware of this common programmer pitfall: character encoding. You will understand more completely after you thoroughly read through the following link, as I know you will: link.
I am sure by now that your professor has described in great detail the importance of code reuse, so as you have read the character encoding link that I provided, you are absolutely coming to the understanding that you will have to make a generic enough class that can handle any language, even if the original question didn't specifically specify this requirement (you may also want to learn about requirement specification, which will help you understand requirements, read through this link: link.
You where very intelligent in suggesting not use the provided Date object, as using the code in the default languages will not allow you to show your true understanding of the language to your professor.
To help you through this difficult question, I have written a Groovy application that will solve you problem, and will undoubtably make more sense than that cryptic java. Don't be alarmed at the use of Groovy for this answer, as Groovy also runs on the JVM just like Java code, so you can easily drop this code into your java class with only a few modifications. I have attached a link to help you through this process, but I wouldn't worry about it until the morning, as it should only take a second (here is the link for later: link. So, just copy the code for now, as I will show plenty of test cases of the code working appropriately, so that you can feel confident in your submission. I definitely understand that you are very very busy eager student, with plenty of obligations on your plate. You are probably aware that contributors here work full time, and are well compensated.

```
//Definetely leave the comments in so your instructor
//can see how well you document your code!

//see how easy it is to specify other languages!
//the users of your software will probably have an IDE just
//like yours, so they can easily come into the source
//code and edit these to their liking, That's Code Reuse!
def EnglishNames ="""January
February
March
April
May
June
July
August
October
November
December
"""

//change this to use other encodings, as discussed above
final String encodingToUseSoThatOurCodeIsSuperRobust = "UTF-8"

//it is a good idea to number your lists for clarity,
//just in case you need more
def list1 = []
def list2 = []

//specifying the method name like this will help make it
//easy to add more languages, another method for another
//language

//this is called a 'Closure', which is pretty much identical
//to that cool new Java thing called the 'Lambda', so if you
//wanted to turn this into Java code, it would be soo easy!
EnglishNames.eachLine() {
    //You probably remember you instructor telling you
    //never to do this String 1 == String 2
    //So to get around that, we will convert the String
    //to bytes, Easy huh!
    list1.add(it.getBytes(encodingToUseSoThatOurCodeIsSuperRobust))
}

//change this to run a different test, the IDE no doubt makes
//it very easy to do this!
//See the very very descriptive variable name for readability?
def iAmLookingForThisCountriesLongNameWithThisShortName = "Dec"
def theFoundAnswerInTheListIs

//this is the real important part as you can easily see
for(BigInteger index = 0; index < list1.size(); index ++){
    for(BigInteger indeX = 0; indeX < list1[index].size(); indeX ++){
        list2[index] = [list1[index][0],list1[index][1],list1[index][2]]
    }
}

boolean foundTheAnswerSoDontDoAnymore = false

//now we just find the correct answer in the list!
for(BigInteger index = 0; index < list1.size(); index ++){
    for(BigInteger indeX = 0; indeX < list1[index].size(); indeX ++){
        //see how readable the following code is!
        if((list2.get(index)) == iAmLookingForThisCountriesLongNameWithThisShortName.getBytes(encodingToUseSoThatOurCodeIsSuperRobust)){
            //see how we can now use the == so we can compare the two strings!
            if(!(new Boolean(foundTheAnswerSoDontDoAnymore))){
                println new String(list1[index], encodingToUseSoThatOurCodeIsSuperRobust)
                foundTheAnswerSoDontDoAnymore = true
            }
        }
    }
}

```

Sorry that I didn't leave anything for you to do here, I got carried away answering your thought provoking question. So just copy and paste this response. As you can see from the following runs of the code, here is what it can do:

```
input: Dec, output: December
input: Jan, output: January
input: Feb, output: February

```

# Answer
> 0 votes
# Python 2.75

```
def getMonthName(short):
    from time import time, gmtime, strftime
    time = time()
    while not (lambda t:strftime("%B",t).upper().startswith(short.upper()))(gmtime(time)): time += 1
    return strftime("%B",gmtime(time))

```

True beauty is in simplicity, which means low memory requirements. Forget those pesky dictionaries and paragraphs of code. This function is so good, it will match short month names using any case. Observe.

```
>>> getMonthName("Apr")
'April'
>>> getMonthName("apr")
'April'
>>> getMonthName("APR")
'April'

```

BONUS:

You can use more than the first 3 characters (e.g. "sept", "febr", etc.)

> This will loop through every second from the time you run this code, checking for match at the beginning of the name, so it will take forever to run if the expected result is not your current month. Also numerous style errors.

# Answer
> 0 votes
in **c#**

```
 var Dictonery = "january,febuary,March,April,May,June,July,August,September,October,November,December";
                     var input = "jan";
                     var outpt= Regex.Match(Dictonery , input + "[a-z]*",
RegexOptions.IgnoreCase).Value;

```

# Answer
> 0 votes
Here's a little program that does what you requested.

> Or actually, 13 of them.

I've written it in C++ because that's what *I* use at the moment, but it converts pretty easily to Java. Being a dedicated student, I'm sure you can work that bit out yourself.

```
#include <iostream>
#include <fstream>
#include <cstdlib>

int main()
{
   std::string months[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };

   for(int i = 0; i <= 12; ++i)
   {
       std::string filename = months[i] + ".cpp";
       std::ofstream myfile;
       myfile.open( filename.c_str() );
       myfile << "#include <iostream>\n\nint main()\n{\n\tstd::cout << \"" << months[i] << "\" << std::endl;\n return " << i << ";\n}";
       myfile.close();

       std::string compile = "g++ " + months[i] + ".cpp -o " +  months[i].substr(0, 3);
       system( compile.c_str() );
   }

   system("Dec");

   return 0;
}

```

> Oh and I may have overlooked a little offset error in the loop.

I decided to be nice and use `std::string`s instead of `char*`s. I'm sure I would have confused you with syntax like `char*[]` and I would definitely have forgotten to call `delete`, or done something stupid like call `delete` instead of `delete[]`.

# Answer
> 0 votes
**C**

Some kind of generic transformation of abbreviations to full words, just adjust `data` array...

```
#include <stdio.h>
#include <string.h>
#include <stdint.h>

const char* getLong(char *shrt) {
    size_t position;
    size_t found = 0;
    static int32_t data[19];

    data[000] = 0x756e614a;
    data[001] = 0x46797261;
    data[002] = 0x75726265;
    data[003] = 0x4d797261;
    data[004] = 0x68637261;
    data[005] = 0x69727041;
    data[006] = 0x79614d6c;
    data[007] = 0x656e754a;
    data[010] = 0x796c754a;
    data[011] = 0x75677541;
    data[012] = 0x65537473;
    data[013] = 0x6d657470;
    data[014] = 0x4f726562;
    data[015] = 0x626f7463;
    data[016] = 0x6f4e7265;
    data[017] = 0x626d6576;
    data[020] = 0x65447265;
    data[021] = 0x626d6563;
    data[022] = 0x00597265;

    for (position = 0; position < strlen(shrt); position++) {
        shrt[position] = position < 1 ? (shrt[position] >= 97 ?
        shrt[position] - 97 + 65 : shrt[position]) : (
        shrt[position] <= 90 ? shrt[position] - 90 + 122 : shrt[position]);
    }

    for (position = 0; position < strlen(((char*)data)); position++) {
        if (((char*)data)[position] == shrt[found]) {
            found++;
            if (found == strlen(shrt)) {
                found = position;
                position -= strlen(shrt);
                for (;((char*)data)[found] > 90; found++);
                ((char*)data)[found] = 0;
                return &(((char*)data)[position + 1]);
            }
        } else {
            found = data[0] - data[1] - 0x2EF4EEE9;
        }
    }
    return "not a month";
}

int main(int argc, char *argv[]) {
    if (argc != 2) return 1;
    printf("%s is %s\n", argv[1], getLong(argv[1]));
    return 0;
}

```

# Answer
> 0 votes
# PHP

```
$month = strtolower($month);
if($month = 'jan') {
return 'January';
}
if($month = 'feb') {
return 'February';
}
if($month = 'mar') {
return 'March';
}
if($month = 'apr') {
return 'April';
}
if($month = 'may') {
return 'May';
}
if($month = 'jun') {
return 'June';
}
if($month = 'jul') {
return 'July';
}
if($month = 'aug') {
return 'August';
}
if($month = 'sep') {
return 'September';
}
if($month = 'oct') {
return 'October';
}
if($month = 'nov') {
return 'November';
}
if($month = 'dec') {
return 'December';
}

```

---
Tags: popularity-contest, code-trolling
---


# Question
Title: Determine if a number is prime without using arithmetic
Write a program which determines if a given number is prime.

The catch: No digits or arithmetical operators. This means:

1. No digits from `0` to `9`, anywhere in the program, and whatever the meaning
2. No using any built-in operators for addition (and incrementing), subtraction (and decrementing), multiplication, division, exponentiation, or modulus, anywhere in the program
3. This includes symbols like `+` and functions like `num.add()`
4. All other operations are permitted
5. You may define your own functions for the forbidden operations
6. You may use symbols like `-` when they mean things other than the forbidden operations

Shortest code wins - any language permitted.

# Example solution

An ungolfed solution in Java can be found here.

# Answer
# PHP, 117 characters

This one is based on regular expressions. If a string containing *$n* characters can be split into chunks of equal length, then *$n* must be composite.

(Assumes *$n* is a positive integer.)

```
function p($n){$u=true;$s=str_repeat('x',$n);return($s!='x'&&!preg_match('/^(xx{'.$u.',})\\'.$u.'{'.$u.',}$/U',$s));}

```

### Output:

```
for ($i=1; $i<=100; $i++) if (p($i)) echo "$i ";

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

```
> 25 votes

# Answer
## Sage, 18

Looks like this is allowed.

```
input()in Primes()

```

`3` gives `True`, `4` gives `False`
> 15 votes

# Answer
# PERL ~~53~~ ~~54~~ ~~52~~ 48

```
('a'x($_=pop))=~/^a?$|^(?<a>aa+?)\g{a}+$/||print

```

Thanks to reddit: http://www.reddit.com/r/programming/comments/crmhe/regular\_expression\_to\_check\_for\_prime\_numbers\_1111/
> 10 votes

# Answer
# J - 7 char

Trivial.

```
(p:~=~)

```

This verb is in the form of a hook. Applied to an argument `y`, it will evaluate as follows. (Feel free to check for yourself: Hook, Reflex/Passive, Equals, Primes.)

```
(p:~=~) y          NB. (F G) y  becomes  y F (G y)   (Hook)
y p:~ (=~ y)       NB. x F~ y   becomes  y F x       (Passive)
(=~ y) p: y        NB. F~ y     becomes  y F y       (Reflex)
(y = y) p: y       NB. anything is equal to itself, so y=y becomes 1
1 p: y             NB. 1 p: y tests for primality of y

```

Usage:

```
   (p:~=~) 5
1
   (p:~=~) 6
0
   (p:~=~) 8675309
1
   NB. test every element of a list
   (p:~=~)every 1627 5231 7610 6311 4549 6990 4220 9028 4066 3496
1 1 0 1 1 0 0 0 0 0

```
> 7 votes

# Answer
## Python 3, 85

```
(lambda i:not any(' '*i==(' '*u)*v for u in range(i)for v in range(i)))(int(input()))

```

Where `*` is not a multiplication operator but a string multiple self-concatenation operator.
> 5 votes

# Answer
# Ruby, 30

```
require'prime';f=->n{n.prime?}

```

Declares a function that returns whether its argument is prime.

Alternative version (same length):

```
require'prime';f=proc &:prime?

```

Obviously bending the rules, but you never said built-in prime functions aren't allowed.
> 4 votes

# Answer
# PHP - 208

```
<?php
function i($n){if($n==strlen(" "))return!!"";foreach(range(strlen("  "),$n) as$_){if($_!=$n){$a=array_fill(!!"",$n,"");while(count($a)>=$_)array_splice($a,!!"",$_);if(!count($a))return!!"";}}return!"";}

```

Type juggling in PHP is fun!
> 3 votes

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


title: Kolmogorov-mania

text:
# Question
Title: Kolmogorov-mania
The Kolmogorov complexity of a string s is defined as the length of the *shortest program* P that outputs s. If the length of P is shorter than the length of s, then s is said to be *compressible*, otherwise s is *incompressible*. Most strings are incompressible ...

Write the shortest program that outputs this string (without spaces and without newlines):

```
d9 a6 b6 33 56 a7 95 4b 29 b0 ac 7f 2a aa 6d 19 b8 4b 4c f8 b6 2a ac 95
a1 4b 4e a5 9d b3 e7 c9 4c 49 59 ec 94 b3 aa 6c 93 8f 11 5a 4d 39 75 82
ec ea 24 cc d3 2d c3 93 38 4e b7 a6 0d d2 b5 37 23 54 ad 1b 79 aa 6e 49
55 52 94 5a a7 3a 6a e9 e4 52 cd 2d 79 ad c6 12 b5 99 5b b4 76 51 17 4e
94 f3 9a a2 e7 15 6a 55 14 4d 4e 4a a3 5c 2f ab 63 cc b5 a6 a4 92 96 8a
2e c3 d8 88 9b 8c a9 16 f5 33 22 5b a2 e2 cc 1b 27 d4 e8 db 17 a4 39 85
ca aa 5b 4f 36 24 d3 c6 f6 94 ad d7 0f 71 24 e1 b1 c5 ef 65 35 6c 8d d7
1a 87 1e 25 df 5d c0 13 b2 6f 5a 57 28 98 bd 41 66 04 ed a2 52 c9 ac 83
b3 6c 56 7e d1 c6 cc 53 4a 62 c5 59 a9 b2 d4 af 22 a5 a9 f4 b2 99 23 32
f8 fb ae 48 6a 8a 9a b5 46 7a 36 59 9f 92 d3 25 b5 19 bd 8a 4a 49 62 a5
e4 59 fb e5 ba a2 35 dd a9 36 1d a9 c9 69 89 77 6a b2 34 2d 1d 22 61 c5
c2 66 1c e2 76 74 52 a5 d9 84 b9 8a a6 b5 14 ec 29 58 b2 bc 96 16 16 48
f5 c5 bd 2f 32 1b 3d 4f 4b 2e b2 6b 9a d9 32 a4 4b 5c bc 92 b7 b3 26 39
fa 42 2d 64 ed 1a 79 49 4c a3 b7 85 b2 a6 e2 8c d9 55 90 e1 a8 87 4b 60
a6 e1 ba c4 bb ec 32 39 76 90 a6 b4 c6 65 79 61 91 aa 3d 54 b7 18 3d 15
4b 06 db 30 8a 4d 4a a1 35 75 5d 3b d9 98 ac 55 5b 10 dd b3 e2 cc f1 5e
b3 2b 53 90 b6 ee 2b ac 8f 88 8d 95 5a 75 df 59 2d 1c 5a 4c e8 f4 ea 48
b9 56 de a0 92 91 a9 15 4c 55 d5 e9 3a 76 8e 04 ba e7 b2 aa e9 ab 2a d6
23 33 45 3d c4 e9 52 e3 6a 47 50 ba af e4 e5 91 a3 14 63 95 26 b3 8b 4c
bc aa 5a 92 7a ab ad a6 db 53 2e 97 06 6d ba 3a 66 49 4d 95 d7 65 c2 aa
c3 1a 92 93 3f ca c2 6c 2b 37 55 13 c9 88 4a 5c 62 6b a6 ae cc de 72 94

```

The output should look like:

```
d9a6b63356a7954b29b0ac7f2aaa6d19b84b4cf8b62aac95a14b4e...7294

```

Note: no user input is allowed, nor web access, nor libraries (except the one required for printing the output).

**Edit I:** the sequence seems random ... but it turns out to be highly compressible handling a *little bit* of prime numbers ...

**Edit II:** Well done! I'll review the answers in the next hours, then assign the bounty. This is my idea on how it could be solved:

1. If you try to compress the data you don't go far away ...
2. In internet you can find the (well-known?) On-Line Encyclopedia of Integer Sequences (OEIS) ;
3. trying the first hexadecimal digits `d9, a6, b6, 33, ...` (or their decimal representation) give no result;
4. but if you convert the numbers to binary (`1,1,0,1,1,0,0,1,1,0,1,0,0,1,1,0`) and searching them on OEIS, you get this result.
5. As noted by Claudiu, I also gave a *little* hint in the question (Edit I above) ... :-)

**The winner is**: Peter Taylor (GolfScript, 50), with a special mention for Claudiu (Python, 92), the first who "solved" it.

# Answer
> 11 votes
## GolfScript (50 bytes)

```
$ wc -c codegolf24909.min.gs
50 codegolf24909.min.gs
$ md5sum codegolf24909.min.gs
ce652060039fba071d17333a1199fd72  codegolf24909.min.gs
$ time golfscript.rb codegolf24909.min.gs
d9a6b63356a7954b29b0ac7f2aaa6d19b84b4cf8b62aac95a14b4ea59db3e7c94c4959ec94b3aa6c938f115a4d397582ecea24ccd32dc393384eb7a60dd2b5372354ad1b79aa6e495552945aa73a6ae9e452cd2d79adc612b5995bb47651174e94f39aa2e7156a55144d4e4aa35c2fab63ccb5a6a492968a2ec3d8889b8ca916f533225ba2e2cc1b27d4e8db17a43985caaa5b4f3624d3c6f694add70f7124e1b1c5ef65356c8dd71a871e25df5dc013b26f5a572898bd416604eda252c9ac83b36c567ed1c6cc534a62c559a9b2d4af22a5a9f4b2992332f8fbae486a8a9ab5467a36599f92d325b519bd8a4a4962a5e459fbe5baa235dda9361da9c96989776ab2342d1d2261c5c2661ce2767452a5d984b98aa6b514ec2958b2bc96161648f5c5bd2f321b3d4f4b2eb26b9ad932a44b5cbc92b7b32639fa422d64ed1a79494ca3b785b2a6e28cd95590e1a8874b60a6e1bac4bbec32397690a6b4c665796191aa3d54b7183d154b06db308a4d4aa135755d3bd998ac555b10ddb3e2ccf15eb32b5390b6ee2bac8f888d955a75df592d1c5a4ce8f4ea48b956dea09291a9154c55d5e93a768e04bae7b2aae9ab2ad62333453dc4e952e36a4750baafe4e591a314639526b38b4cbcaa5a927aabada6db532e97066dba3a66494d95d765c2aac31a92933fcac26c2b375513c9884a5c626ba6aeccde7294

real    365m11.938s
user    364m45.620s
sys     0m6.520s

```

Since everyone else is now revealing their code, I will also pre-empt OP's request to unobfuscate:

```
38200,{:x,{)x\%!},,2=},4/{3\{2&!!1$++}/.57>39*+}%+

```

### Overview dissection

* Compute primes smaller than N with N=38200: this gives the first 4032 primes: `38200,{:x,{)x\%!},,2=},`
* We want one bit per prime, with a hex conversion, so split them into groups of 4: `4/`
* For each group, map each prime `p` to `p&2 != 0`, and do a base-2 to base-16 conversion: `{3\{2&!!1$++}/.57>39*+}%` (this is where the interesting tricks are)
* We now have an array of ASCII values, plus the empty string from stdin; concatenate them to get a single string for output: `+`

### More detailed dissection of the base conversion

Given a stack holding an empty string and a list of primes, we need to do two conversions:

1. Convert each prime to a bit indicating whether it's equal to 2 or 3 (mod 4)
2. Convert the bits into hex digits

There are lots of equally long ways to do 1; e.g.

```
{4%1>}%
{4%2/}%
{2/1&}%
{2/2%}%
{2&!!}%

```

or even

```
{2&}% followed by a 2/ after the base conversion

```

For 2, the obvious approach is

```
2base 16base{'0123456789abcdef'=}%+

```

But base is a long word, and since 16 = 24 we can easily save a few chars with

```
4/{2base'0123456789abcdef'=}%+

```

Now the most obvious waste is the 18 chars devoted to that string. We just want a function from digit to ASCII code. We want to map `0` to `'0' = 48`, ..., `9` to `'9' = 57`, `10` to `'a' = 97`, ... `15` to `'f' = 102`.

```
4/{2base.9>39*+48+}%+

```

But now throw into the mix a ban on `base`. We need to implement it ourselves. The obvious implementation (in this direction, the easy one) is that `k base` is a fold `{\k*+}*`. The slightly longer alternative is a straightforward iteration, which needs a base case: `0\{\k*+}/`. Base 2 is slightly special: `1$++` is equivalent to `\2*+` for the same length, and I've taken that approach.

Both of those are longer than the 5-char `2base`, but since we're now iterating over the values we can pull in part 1 to have a single loop. We replace

```
{2&!!}%4/{2base.9>39*+48+}%+

```

with

```
4/{{2&!!1$++}*.9>39*+48+}%+

```

for a nice 1-char saving, or

```
4/{0\{2&!!1$++}/.9>39*+48+}%+

```

for a 1-char loss.

But although that 1-char loss looks like a step backwards, consider what happens to that 0. It's multiplied by 16 and added to the base-conversion output. And the final thing we do is to add a multiple of 16 to the output. So we can combine the two as

```
4/{3\{2&!!1$++}/.57>39*+}%+

```

Joint shortest and the bonus cleverness makes it more interesting.

# Answer
> 32 votes
# Python, 92 characters

Here it is ladies and gentlemen, the code itself!

```
>>> code = "R=range;print hex(int(''.join(`i/2%2`for i in R(38198)if all(i%x for x in R(2,i))),2))[2:-1]"
>>> len(code)
92
>>> exec code
d9a6b63356a7954b29b0ac7f2aaa6d19b84b4cf8b62aac95a14b4ea59db3e7c94c4959ec94b3aa6c938f115a4d397582ecea24ccd32dc393384eb7a60dd2b5372354ad1b79aa6e495552945aa73a6ae9e452cd2d79adc612b5995bb47651174e94f39aa2e7156a55144d4e4aa35c2fab63ccb5a6a492968a2ec3d8889b8ca916f533225ba2e2cc1b27d4e8db17a43985caaa5b4f3624d3c6f694add70f7124e1b1c5ef65356c8dd71a871e25df5dc013b26f5a572898bd416604eda252c9ac83b36c567ed1c6cc534a62c559a9b2d4af22a5a9f4b2992332f8fbae486a8a9ab5467a36599f92d325b519bd8a4a4962a5e459fbe5baa235dda9361da9c96989776ab2342d1d2261c5c2661ce2767452a5d984b98aa6b514ec2958b2bc96161648f5c5bd2f321b3d4f4b2eb26b9ad932a44b5cbc92b7b32639fa422d64ed1a79494ca3b785b2a6e28cd95590e1a8874b60a6e1bac4bbec32397690a6b4c665796191aa3d54b7183d154b06db308a4d4aa135755d3bd998ac555b10ddb3e2ccf15eb32b5390b6ee2bac8f888d955a75df592d1c5a4ce8f4ea48b956dea09291a9154c55d5e93a768e04bae7b2aae9ab2ad62333453dc4e952e36a4750baafe4e591a314639526b38b4cbcaa5a927aabada6db532e97066dba3a66494d95d765c2aac31a92933fcac26c2b375513c9884a5c626ba6aeccde7294
>>> import hashlib; hashlib.sha256(code).hexdigest()
'60fa293bbe895f752dfe208b7b9e56cae4b0c8e4cdf7c5cf82bf7bab60af3db6'

```

Marzio left a clever hint by saying that "it turns out to be highly compressible handling a *little bit* of prime numbers". I was sure the "little bit" wasn't italicized by accident, so I converted the hex string to bits and tried to find patterns. I thought that at first he was representing all the primes as bits and concatenating them together, but that didn't work out. Then maybe taking only a few digits, or dropping all the zeroes in the bit string - still no. Maybe it's a bitstring of the least-significant-bit of the first few primes? Not quite. But eventually I found the one that worked - it's a bitstring of the second-least-significant bit from the first however-many primes.

So, my code does just that: generate just enough primes, take the second bit of each (`i/2%2`), concatenate them as a binary string, then convert it to base-10 (`int(..., 2)`) and then to base-16 (`hex(...)`).

# Answer
> 9 votes
# C, ~~136~~ ~~116~~ ~~109~~ 103 characters

OK then, here's my effort:

```
i;p;q;main(n){for(;n++,q<4032;){for(i=1;++i<n&&n%i;);if(i==n)p+=p+(n&2)/2,p=++q&3?p:printf("%x",p)*0;}}

MD5 hash = f638552ef987ca302d1b6ecbf0b50e66

```

# Answer
> 9 votes
# Haskell, 105

SHA1 hash: `a24bb0f4f8538c911eee59dfc2d459194ccb969c`

Output:

```
d9a6b63356a7954b29b0ac7f2aaa6d19b84b4cf8b62aac95a14b4ea59db3e7c94c4959ec94b3aa6c938f115a4d397582ecea24ccd32dc393384eb7a60dd2b5372354ad1b79aa6e495552945aa73a6ae9e452cd2d79adc612b5995bb47651174e94f39aa2e7156a55144d4e4aa35c2fab63ccb5a6a492968a2ec3d8889b8ca916f533225ba2e2cc1b27d4e8db17a43985caaa5b4f3624d3c6f694add70f7124e1b1c5ef65356c8dd71a871e25df5dc013b26f5a572898bd416604eda252c9ac83b36c567ed1c6cc534a62c559a9b2d4af22a5a9f4b2992332f8fbae486a8a9ab5467a36599f92d325b519bd8a4a4962a5e459fbe5baa235dda9361da9c96989776ab2342d1d2261c5c2661ce2767452a5d984b98aa6b514ec2958b2bc96161648f5c5bd2f321b3d4f4b2eb26b9ad932a44b5cbc92b7b32639fa422d64ed1a79494ca3b785b2a6e28cd95590e1a8874b60a6e1bac4bbec32397690a6b4c665796191aa3d54b7183d154b06db308a4d4aa135755d3bd998ac555b10ddb3e2ccf15eb32b5390b6ee2bac8f888d955a75df592d1c5a4ce8f4ea48b956dea09291a9154c55d5e93a768e04bae7b2aae9ab2ad62333453dc4e952e36a4750baafe4e591a314639526b38b4cbcaa5a927aabada6db532e97066dba3a66494d95d765c2aac31a92933fcac26c2b375513c9884a5c626ba6aeccde7294

```

Edit: Code:

```
import Numeric;f(x:z)s=f[y|y<-z,0/=mod y x]$s*2+quot(mod x 4)2;f[]s=s;main=putStr$showHex(f[2..38198]0)""

```

I missed the rule about not using any library functions except for printing (putStr). I would assume that mathematical operators, while they're technically functions, are allowed.

# Answer
> 7 votes
## JS, 764

if we consider this string as base64, we can have a smaller version using the un-base-64-ed version:

```
btoa("wÖºo÷ç¦»÷ÛÖôiÎßÙ¦éÝ}oÎáÇüoiÏyk^áæ¹õÖ÷{·=áÎ=ç×÷÷i®÷×^ZáÝýï6yÇÛw}swßÎo¶ºÑ×voûÛ~xiÝ[ïÖéî=çv÷Zk½Úé§½{vqÝïÖsvo}å¶øï®u×¾÷÷õ¦¶{½yé®y×áîk~\Ùöëwoºkv÷¯Ùç7wÏ<õ¿kÝz÷Ûn[kg¶qÍ[Û·x{Ç[×¶¸ßß9q¦å¾ß¸ww:¯xi×{ÑþõÛµoW9yþ¹ßñ×{Õ¯;Õí¹uþ]sMwonå®{ÛÏ|mÞ5ë8yÖ¶çg=iÏ7o~ç®ÞwW:qÎwá®¶s}kÖöwÛf¹k×øoo}Û}öÇÛiî<é¯õ¦ùã®Úß®}õÿvw}¹o}mßá®=ëf¹{}}·¹m¦¶ß]kÝúÕÖ½sÞ½óÞûé¦ößÕÝ¶ëW9snºÕÇ¶ï®øçf¹wß8oßk¦ù×ÛÞ|ofÜ÷z×®<9mÝßm[ÝÞá½onõ§}ßf¸á¾\mÏvo¶÷Ûý}®6ÙÞ¸yÝZïÞ=áÆ·o¿9ofº{owÞy÷GµkÏ;á¾´k§µm§8m·ßmýï¯tk¦øs®¹ïÞµ÷VÝÞxo½|ÝÝyá½:u½ôñ®á¦µßùåÝÛwß|iÎyå½tuÖ÷{g^^o}çto§Ù¶ñÿ<ñßyå®ùuþ}ÙÝ\å®{Çøy®<oÞzuæ´÷oukÝyáÎyw½Ý®úñí8m§»of{ÖÙ§zÛ}÷ãÝs½çg·é®;çFÚi÷¸{uk}xëyÛ¦÷ñ¾mÆå¯ví¦iÖºu¾wÙï{Ó®mÚë®=áßyw¾¹sfs}Z÷owÝ÷snÙ½ûçwsß<á®\ënk¦qÇ^ïox")

```

But I think that the author wants us to find the logic behind this non-random string instead.

# Answer
> 4 votes
## Mathetmatica - 56

The mystery is already solved, so just implementing the idea

```
⌊.5Prime@Range@4032⌋~Mod~2~FromDigits~2~IntegerString~16

```

# Answer
> 3 votes
# J - 46 char

Don't mind me, just logging the J golf here for posterity. Wasn't clever enough to figure out the trick.

```
4[1!:2&4'0123456789abcdef'{~#.2|<.-:p:i.1007 4

```

Explained:

* `p:i.1007 4` \- Create a 1007-row, 4-column matrix of the integers from 0, then take the prime numbers corresponding to those integers. Yes, `p:` is a J builtin. Yes, we're four primes short.
* `2|<.-:` \- Halve each number (`-:`), floor it (`<.`), and take that modulo 2 (`2|`). This is the same as taking the next-to-lease significant bit.
* `#.` \- Convert each row of the result from base 2 into an integer. This gives us 1007 numbers from 0 to 15 inclusive.
* `'0123456789abcdef'{~#.` \- Take each row of this matrix of bits as the binary for a number, and use that number to select from the list of hex digits. This converts every four bits into the hex.
* `1!:2&4` \- The J interpreter has a problem with outputting strings longer than 256 chars, so we have to send this data directly to stdout. You win some, you lose some.
* `4[` \- Finally, discard the result from `1!:2` and instead output the missing 4 from the output. We do this because it's shorter than including those last four primes and returning an empty result here.

# Answer
> 0 votes
# JS, 503

Following @xem idea:

```
s='Ù¦¶3V§K)°¬*ªm¸KLø¶*¬¡KN¥³çÉLIYì³ªlZM9uìê$ÌÓ-Ã8N·¦\nÒµ7#TyªnIURZ§:jéäRÍ-yÆµ[´vQNó¢çjUMNJ£\/«cÌµ¦¤.ÃØ©õ3"[¢âÌ'+"'"+'ÔèÛ¤9Êª[O6$ÓÆö×q$á±Åïe5l×%ß]À²oZW(½Afí¢RÉ¬³lV~ÑÆÌSJbÅY©²Ô¯"¥©ô²#2øû®HjµFz6YÓ%µ½JIb¥äYûåº\n5Ý©6©Éiwj²4-"aÅÂfâvtR¥Ù¹¦µì)X²¼HõÅ½/2=OK.²kÙ2¤K\¼·³&9úB-díyIL£·²¦âÙUá¨K`¦áºÄ»ì29v¦´Æeyaª=T·=KÛ0MJ¡5u];Ù¬U[Ý³âÌñ^³+S¶î+¬ZußY-ZLèôêH¹VÞ ©LUÕé:vºç²ªé«*Ö#3E=ÄéRãjGPº¯äå£c&³L¼ªZz«¦ÛS.mº:fIM×eÂªÃ?ÊÂl+7UÉJ\bk¦®ÌÞr'
r=''
for(var i=0;i<s.length;i++) r+=s.charCodeAt(i).toString(16);
console.log(r)

```

# Answer
> 0 votes
# Mathematica, 55

```
Prime~Array~4031~BitAnd~2~FromDigits~2~IntegerString~16

```

Tested on Mathematica 8. This makes use of two observations:

* Mathematica's `FromDigits` doesn't actually check the range of the digits given, so if you apply it to a list of the form `{2,0,2,2,0,...}` you just get twice the result as if applying to `{1,0,1,1,0,...}`. But that's exactly the form generated by `BitAnd`ing the primes with 2.
* The last bit of the number whose hexadecimal representation we want happens to be zero (as evidenced by the string ending in an even digit), so it is just two times the number you'd get with one prime less. But a factor of two is exactly what we get from using the previous observation, so everything perfectly fits together.

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


title: The Tic-tac-toe Games

text:
# Question
Title: The Tic-tac-toe Games
Create a deterministic program to play nd tic-tac-toe with the other contestants.

Your program should work when `n` (width) and `d` (dimension number) are in these ranges:

```
n∈[3,∞)∩ℕ  ie a natural number greater than 2
d∈[2,∞)∩ℕ  ie a natural number greater than 1

```

`n = 3; d = 2` (32 ie 3 by 3):

```
[][][]
[][][]
[][][]

```

`n = 3; d = 3` (33 ie 3 by 3 by 3):

```
[][][]
[][][]
[][][]

[][][]
[][][]
[][][]

[][][]
[][][]
[][][]

```

`n = 6; d = 2` (62 ie 6 by 6):

```
[][][][][][]
[][][][][][]
[][][][][][]
[][][][][][]
[][][][][][]
[][][][][][]

```

And so on.

**Input:**

Input will be to STDIN. The first line of input will be two numbers, `n` and `d` in the form `n,d`.

After this will be a line consisting of coordinates specifying the moves that have been done. Coordinates will be listed in the form: `1,1;2,2;3,3`. The upper left corner is the origin ( 0,0 for 2D). In the general case, this list will be like `1,2,...,1,4;4,0,...,6,0;...` where the first number represents left-right-ness, the second up-down-ness, the third through the 3rd dimension, etc. Note that the first coordinate is `X`s first turn, the second is `O`s first turn, ....

Should this be the first move, the input will a number followed by 1 blank line.

For consistency, the input will always end with a newline. Sample Input (\n is newline):

```
10,10\n0,0,0,0,0,0,0,0,0,0;0,2,3,4,5,6,7,8,9,0;0,1,2,3,4,5,6,7,8,9\n

```

For first move:

```
10,10\n\n

```

where `\n` is the newline character.

**Output:**

Output the move you wish to make in the same format as the input (a comma-separated list). An invalid move (ie one that has already been taken) will result in a loss for the game.

Note: You can use a random number generator, as long as you seed it with a value such that each run would be identical given the same conditions. In other words, the program must be deterministic.

Note: only valid moves are allowed.

**Winning Games** (If you've played enough multi-dimensional tic tac toe, this is the same.)

In order for there to be a win, one player must have all the adjacent squares along a line. That is, that player must have `n` moves on a line to be a winner.

Adjacent:

* each tile is a point; for example (0,0,0,0,0) is a point in `d=5`
* adjacent tiles are tiles such they are both points on the same unit d-cube. In other words, the Chebyshev distance between the tiles is 1.
* in other words, if a point `p` is adjacent to a point `q`, then every coordinate in `p`s corresponding coordinate in `q` differs from it by no more than one. Additionally, at least on coordinate pair differs by exactly one.

Lines:

* Lines are defined by vectors and a tile. A line is each tile hit by the equation: `p<sub>0</sub> + t`<`some vector with the same number of coordinates as p<sub>0</sub>`>``

**Simulation and Winning Conditions:**

* State in your answer if it is ready for grading. That is, clearly indicate whether or not your answer is done.
* If your answer is marked as done, it will not be graded until at least 24 hours after the last edit to the code.
* Programs must work offline. If a program is found to be cheating, it will automatically receive a score of `-1`, and will not be scored further. (How would anyone end up with their programs cheating?)
* If your program produces invalid output, it is immediately counted as a loss for the game
* If you program fails to produce output after 1 minute it is immediately counted as a loss for the game. If necessary, optimize for speed. I don't want to have to wait an hour to test a program off of another.
* Each program will be run against the other programs twice for each `n` in the range `[3,6]` and each `d` in the range `[2,5]`, once as `X` and once as `O`. This is one round.
* For each game a program wins, it gets `+3` to its score. If the program tied (1 win and 1 loss in a single round or ties for both games), then it gets `+1`. If the program lost, then it gets `+0` (ie no change).
* The program with the highest score wins. Should there be a tie, then the program with the least number of lost games (out of the tied contestants) wins.

Note: Depending on the number of answers, I may need help running the tests.

*Good luck! And may the simulations run ever in your favor!*

# Answer
# Python 3

```
import random as rand
import re

def generateMoves(width, dim):
    l = [0] * dim
    while existsNotX(l, width - 1):
        yield l[:]
        for i in range(dim):
            if l[i] < width - 1:
                l[i] += 1
                break
            else:
                l[i] = 0
    yield l

def existsNotX(l, x):
    for i in l:
        if i != x:
            return True
    return False

input_s = input()
dims, moves = None, None
#this is to allow input as a single paste, instead of ENTER inputting.
try:
    dims, moves = input_s.splitlines()
except ValueError:
    dims = input_s
    moves = input()

rand.seed(moves + dims)

dims = eval(dims) #change into tuple

moves = moves.split(';')
if len(moves[0]):
    moves = [eval(m) for m in moves] #change into tuples

output =[x for x in generateMoves(dims[0], dims[1]) if x not in moves]
print(re.sub('[^\\d,]', '', str(output[rand.randint(0, len(output))])))

```

This is simply a random ai. It randomly selects a move out of the moves that are still available.
> 2 votes

# Answer
# Python 2.7

This is a work-in-progress submission which I'm providing to give a skeleton/inspiration to other answerers. It works by listing every possible winning line, then applying some heuristic to score that line according to how valuable it is. Currently, the heuristic is blank (super-secret workings). I have also added win and clash error handling.

### Notes on the problem

How many winning lines are there? Consider the 1-dimensional case; there are 2 vertices, 1 edge, and 1 line. In 2 dimensions, we have 4 vertices joined by 2 lines, and 4 edges joined by 2\*n lines. In 3 dimensions, we have 8 vertices joined by 4 lines, 12 edges joined by 6\*n lines, and 6 faces joined by `3*n^2` lines.

In general, let us call a vertex a 0-facet, an edge a 1-facet, etc. Then let `N(i)` denote the number of i-facets, `d` the number of dimensions, and `n` the side length. Then the number of winning lines is `0.5*sum(N(i)*n^i,i=0..d-1)`.

Per wikipedia, `N(i)=2^(d-i)*d!/(i!*(n-1)!)`, so the final formula is:

`sum(2^(d-i-1) n^i d! / (i! * (n-i)!),i=0..d-1)`

which wolfram|alpha doesn't like very much. This gets very large pretty quickly, so I don't expect my program to have manageable runtime for d\>8.

Some results (sorry about the formatting:

```
d\n 0   1    2      3      4       5        6        7         8         9
0   1   1    1      1      1       1        1        1         1         1
1   2   4    6      8      10      12       14       16        18        20
2   4   11   26     47     74      107      146      191       242       299
3   8   40   120    272    520     888      1400     2080      2952      4040
4   16  117  492    1437   3372    6837     12492    21117     33612     50997
5   32  364  2016   7448   21280   51012    107744   206896    368928    620060
6   64  1093 8128   37969  131776  372709   908608   1979713   3951424   7352101
7   128 3280 32640  192032 807040  2687088  7548800  18640960  41611392  85656080
8   256 9834 130809 966714 4907769 19200234 62070009 173533434 432891129 985263594

```

### I/O

At the moment, the input needs to be input as: `tictactoe.py <ret> n,d <ret> move;move <ret>` \- note the multiple lines and no final `;`.

The output looks like `(x_1,x_2,x_3...)`, for instance:

`tictactoe.py <ret> 6,5 <ret> <ret>` =\> `0, 0, 0, 0, 0`

`tictactoe.py <ret> 6,5 <ret> 0,0,0,0,0;0,0,0,0,5 <ret>` =\> `0, 0, 0, 5, 0`

```
# Notes on terminology:
#
# - A hypercube is the region [0,n]^d
# - An i-facet is an i-dimensional facet of a hypercube,
#   which is to say, a 0-facet is a vertex, a 1-facet an
#   edge, a 2-facet a face, and so on.
# - Any tuple {0,n}^i is a vertex of an i-hypercube
#   which is why I've used vertex to describe such
#   tuples
# - A winning line is a set of n coordinates which joins
#   two opposite i-facets
# - i-facets are opposite if they differ in every co-
#   ordinate which defines them
#
# Test Data:
#

import numpy
import itertools

def removeDuplicates(seq):
    noDupes = []
    [noDupes.append(i) for i in seq if not noDupes.count(i)]
    return noDupes

def listPairedVertices (i,n):
    """
    listPairedVertices returns a list L of elements of {0,n}^i which has the
    property that for every l in L, there does not exist l' such that
    l+l' = {n}^i.
    """

    vertices = numpy.array([[b*(n-1)  for b in a] for a in [
        list(map(int,list(numpy.binary_repr(x,i)))) for x in range(2**i)
    ]])
    result = []
    while len(vertices)>1:
        for j in range(len(vertices)):
            if numpy.all(vertices[j] + vertices[0] == [n-1]*i):
                result.append(vertices[0])
                vertices=numpy.delete(vertices,[0,j],axis=0)
                break
    return result

def listSequences (d,l):
    """
    listSequences returns the subset of {0,1}^d having precisely n 1s.
    """
    return numpy.array([
        r for r in itertools.product([0,1],repeat=d) if sum(r)==l
    ])

def listPaddedConstants (s,n):
    """
    listPaddedConstants takes a sequence in {0,1}^d and returns a number in
    {0..n}^sum(s) padded by s
    """
    result = numpy.zeros([n**sum(s),len(s)],dtype=numpy.int)
    for i,x in enumerate([list(z) for z in
        itertools.product(range(n),repeat=sum(s))]):
        for j in range(len(s)):
            if s[j]: result[i][j] = x.pop()
    return result

def listWinningVectorsForDimension(d,i,n):
    """
    List the winning lines joining opposite i-facets of the hypercube.

    An i-facet is defined by taking a vertex v and a sequence s, then forming
    a co-ordinate C by padding v with zeroes in the positions indicated by s.
    If we consider s = s_0.e_0 + s_1+e_1... where the e_j are the canonical
    basis for R^d, then the formula of the i-facet is
        C+x_0.s_0.e_0+x_1.s_1.e_1...
    for all vectors x = (x_0,x_1...) in R^n

    We know that winning lines only start at integral positions, and that the
    value of a will only be needed when s_j is nonempty, so the start point S
    of a winning line is in fact determined by:
     + vertex v in {0,n}^(d-i), padded by s
     + a in R^i, padded by the complement of s, s'

    Having performed the following operations, the co-ordinates of the winning
    lines are abs(S-k*s') for k in [0..n-1]
    """
    vertices = listPairedVertices(d-i,n)
    sequences = listSequences(d,i)
    result = []
    for s in sequences:
        for v in vertices:
            C = [0]*d
            j = 0
            for index in range(d):
                if s[index]: C[index] = 0
                else:
                    C[index] = v[j]
                    j+=1
            result += [
                [numpy.absolute(S-k*(numpy.absolute(s-1))) for k in range(n)]
                    for S in [C+a for a in listPaddedConstants(s,n)]
            ]
    return result

def AllWinningLines (d,n):
    """
    has the structure [[x_1,x_2,x_3],[y_1,y_2,y_3]] where each l_k is a
    length-d co-ordinate
    """
    result = []
    for i in range(d):
        result += listWinningVectorsForDimension(d,i,n)
    return result

def movesAlreadyMade ():
    """
    Returns a list of co-ordinates of moves already made read from STDIN
    """
    parameters = raw_input()
    moves = raw_input()
    parameters = list(map(int,parameters.split(',')))
    moves = [map(int,a.split(',')) for a in moves.split(';')] \
        if moves != '' else []
    return {'n':parameters[0], 'd':parameters[1], 'moves':moves}

def scoreLine (moves, line, scores, n):
    """
    Gives each line a score based on whatever logic I choose
    """
    myMoves          = moves[0::2]
    theirMoves       = moves[1::2]
    if len(moves)%2: myMoves, theirMoves = theirMoves, myMoves

    lineHasMyMove    = 0
    lineHasTheirMove = 0
    score            = 0

    for coord in line:
        if coord.tolist() in myMoves:
            lineHasMyMove += 1
            if coord.tolist() in theirMoves: raise Exception('Move clash')
        elif coord.tolist() in theirMoves: lineHasTheirMove += 1

    if lineHasMyMove == len(line):
        raise Exception('I have won')
    elif lineHasTheirMove == len(line):
        raise Exception('They have won')
    elif lineHasMyMove and lineHasTheirMove:
        pass
    elif lineHasTheirMove == len(line)-1:
        score = n**lineHasTheirMove
    else:
        score = n**lineHasMyMove

    for coord in line:
        if coord.tolist() not in moves:
            scores[tuple(coord)]+=score

def main():
    """
    Throw it all together
    """
    data      = movesAlreadyMade()
    dimension = data['d']
    length    = data['n']
    lines     = AllWinningLines(dimension, length)
    scores    = numpy.zeros([length]*dimension, dtype=numpy.int)

    try: [scoreLine(data['moves'], line, scores, length) for line in lines]
    except Exception as E:
            print 'ERROR: ' + E.args[0]
            return
    print ','.join(map(
        str,numpy.unravel_index(numpy.argmax(scores),scores.shape)
        ))

if __name__ == "__main__": main()

```

Edit: for I/O, added logic. I believe this is now ready to mark

Note that this comment was initially a placeholder which I deleted and undeleted.
> 2 votes

# Answer
# Python 2

```
import re
import itertools

input_s = raw_input()
dims, moves = None, None
#this is to allow input as a single paste, instead of ENTER inputting.
try:
    dims, moves = input_s.splitlines()
except ValueError:
    dims = input_s
    moves = raw_input()

dims = eval(dims) #change into tuple

moves = moves.split(';')
if len(moves[0]):
    moves = [eval(m) for m in moves] #change into tuples

allSpaces = [x for x in itertools.product(range(dims[0]), repeat=dims[1])]
move = None
for space in allSpaces:
    if space not in moves:
        move = space
        break
print(re.sub('[^\\d,]', '', str(move)))

```

Most of the code is exactly the same as Quincunx's random AI. Instead of randomly selecting a move, it picks the first available move lexicographically (i.e. (0,0,...0), then (0,0,...1), then (0,0,...2), etc.).

This is a pretty rubbish strategy, but it almost always beats playing at random.
> 1 votes

---
Tags: tic-tac-toe, king-of-the-hill
---


# Question
Title: Shortest code to generate 2D coordinates
I'm looking for the shortest code to generate the following sequences:

```
Sequence A
i | y x
0 | 0 0
1 | 0 1
2 | 1 0
3 | 1 1

```

The best I have is `x = i % 2, y = i / 2`, there is probably no beating that. Those are coordinates of corners of a box in 2D, but they are not in a good order for drawing. To draw a box as line loop, one needs those coordinates:

```
Sequence B
i | y x
0 | 0 0
1 | 0 1
2 | 1 1
3 | 1 0

```

So far, I have `x = (i ^ i / 2) % 2, y = i / 2`. There is likely space for improvement there. Finally, how to generate directions towards the box edges (where the order does not matter, but `i` still must be 0 to 3):

```
Sequence C
i |  y  x
? |  0 -1
? |  0  1
? | -1  0
? |  1  0

```

So far I have rather ugly `x = (1 | -(i % 2)) * (i / 2), y = (1 | -(i % 2)) * (1 - i / 2)`.

Shortest code in any programming language wins (I actually plan to use these). The best solution will be used in a **closed-source** project, **no attribution** can be paid other than source code comment, so post only if you're ok with it. Submit solutions to any of the above sequences. Don't bother writing code that generates all of them, think of it like competition with three categories (and tree possible winners).

# Answer
> 3 votes
Short sequence C (20 characters):

```
x=1==i^-!i,y=i%3-!!i

```

This generates a permutation of the original sequence (as I said, the order does not matter):

```
x -1  1  0  0
y  0  0  1 -1

```

Short sequence B (14 characters):

```
x=i>>~-i,y=i/2

```

So how about that? I'd say it is not possible to do better than that. Anyone to prove me wrong?

And yes, this answer is free. Use it as you want, sell it, no attribution needed.

**EDIT**:

Shorter sequence C (17 characters):

```
x=~-i%2,y=~-~-i%2

```

This generates a permutation of the original sequence (as I said, the order does not matter):

```
x -1  0  1  0
y  0 -1  0  1

```

Some other interesting solutions to short sequences:

```
was solving for {0, 0, 1, 1} in 1D {4 x 1 x 1} domain
solution: '1 < i': score 3
solution: 'i > 1': score 3
solution: 'i / 2': score 3

was solving for {0, 1, 0, 1} in 1D {4 x 1 x 1} domain
solution: '1 & i': score 3
solution: 'i & 1': score 3
solution: 'i % 2': score 3

was solving for {0, 1, 1, 0} in 1D {4 x 1 x 1} domain
solution: 'i >> ~-i': score 6
solution: '!!(i % 3)': score 7
solution: 'i >> ~(-i)': score 8

was solving for {-1, 1, 0, 0} in 1D {4 x 1 x 1} domain
solution: '!~-i - !i': score 7
solution: '!~-i + -!i': score 8
solution: '!~-i | -!i': score 8

was solving for {1, -1, 0, 0} in 1D {4 x 1 x 1} domain
solution: '!i - !~-i': score 7
solution: '!i - !(~-i)': score 9
solution: '-!(~-i) + !i': score 10

was solving for {1, 0, 0, -1} in 1D {4 x 1 x 1} domain
solution: '-~(~i / 2)': score 8
solution: '-~(-i >> 1)': score 9
solution: '-(~-i >> 1)': score 9

was solving for {-1, 0, 0, 1} in 1D {4 x 1 x 1} domain
solution: '~-i >> 1': score 6
solution: '~(~i / 2)': score 7
solution: '~-i >> !!i': score 8

was solving for {0, 1, -1, 0} in 1D {4 x 1 x 1} domain
solution: '~(~i % 3)': score 7
solution: '~(~i % ~2)': score 8
solution: '~(~i % -3)': score 8

was solving for {0, -1, 1, 0} in 1D {4 x 1 x 1} domain
solution: '-~(~i % 3)': score 8
solution: '-~(~i % ~2)': score 9
solution: '-~(~i % -3)': score 9

```

---
Tags: code-golf, sequence
---