# Question
Title: Most efficient table storage for determining recurrence
The goal of this challenge is to implement a storage and retrieval pattern that will most quickly determine if a set of recurrence definitions fall within a date range.

Consider the schema: `Event -|--has one or many--<- Schedules`

Schedule is a record defining a recurrence, e.g. (these are just samples)

* Monthly, every month
* Monthly, first Wednesday of every month
* Monthly, Monday and Tuesday of every 3rd month from start date
* Monthly, Monday and Tuesday of every May, June and July
* Weekly, every Tuesday through Saturday
* Weekly, Monday every 3rd week from start date

The types of supported schedules should be (definitive list):

**Pattern**

1. Daily
2. Weekly, every \[X\] weeks on \[set of 1-7 days\]
3. Monthly, every \[Xth\] day of every \[Y\] months
4. Monthly, every \[1st-4th-last\] \[weekday\] of every \[Y\] months
5. Yearly, on \[month\] \[day of month\] every \[X\] years
6. Yearly, on \[1st-4th-last\] \[weekday\] of \[month\]
7. Monthly, every \[Xth\] day of \[set of months\]
8. Monthly, every \[1st-4th-last\] \[weekday\] of \[set of months\]

**End date** (Start is always a single date)

1. No end date (for simplicity, you could omit this since we can use year 2999)
2. A single date
3. A number of \[X\] occurences

To win, the answer must define:

1. Table schema
2. SQL query or function (any RBDMS) to test a date range against the entire table

Determination of winner:

1. test data: 10,000 events will be created randomly; 20 special test cases will be added as well
2. test case: 100 random date ranges (min:1 max:32 days), 5 fixed date ranges (min:1 max:32 days)
3. test execution: Test will be repeated 3 times
4. proof of correctness: All answers must be correct 6: speed: Quickest execution wins

Example test case:

```
---------
Schedules
---------
Event A: Weekly, Every Monday starting 1 Jan 2015
Event A: Monthly, Every [31st] day of every [1] month starting 1 Jan 2015
  (e.g. Event A is a backup schedule)
Event B: Monthly, Every [1st] day of every [1] month starting 1 Jan 2015
Event C: Yearly, Every [10th] day of every [3] months starting 1 Jan 2015
  (e.g. quarterly summary report)
Event D: Weekly, Every [Tue,Wed,Fri] starting 1 Jan 2015
Event E: Weekly, Every [Tue,Wed,Fri] starting 1 Jan 2015 ending 3 July 2015
(assume no end dates unless stated)

-----
Query
-----
What events occur between 1 July 2015 and 31 July 2015 (inclusive)

---------------
Expected Result
---------------
(shown in date order)
01 July: Event B
01 July: Event E
03 July: Event E  << last occurrence due to end date
06 July: Event A
10 July: Event C
13 July: Event A
20 July: Event A
27 July: Event A
31 July: Event A
(a lot of event D's every Tue/Wed/Fri in July)

```

# Answer
# T-SQL

Given that the speed of the query is the most important part of the challenge, I have created a table that is an expansion of the events so that each event has all of it's occurrence dates stored. The query is then just a simple `WHERE DATE BETWEEN` query and will perform extremely quickly.

This of course is built towards the query speed and not for the maintenance of the data. Building and populating the table will take a fair amount of time depending on the amount of dates that the events cover.

The parsing of the records assume the the Days and Months are all abbreviated

## View

A simple view to give a list of numbers up to 1e8

```
CREATE View [dbo].[Tally] as
WITH
    E1(N) AS (select 1 from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))dt(n)),
    E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
    E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
    E8(N) AS (SELECT 1 FROM E4 a, E4 b), --10E+4 or 100,000,000 rows max
    cteTally(N) AS
    (
        SELECT  ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
    )
SELECT N FROM cteTally;
GO

```

## Functions

A couple of inline table functions to parse and expand the Event input records.

```
CREATE FUNCTION ParseEvent (@InputString VARCHAR(1000)) RETURNS TABLE AS RETURN
    -- Parse rest of the components
    SELECT
        EventName,
        ScheduleType,
        StartDate,
        EndDate,
        CASE WHEN ScheduleType = 'Weekly' THEN
            SUBSTRING(Remainder,7,CHARINDEX(' weeks ',Remainder)-7)
        END WeeklyX,
        CASE WHEN ScheduleType = 'Weekly' THEN
            SUBSTRING(Remainder,CHARINDEX(' on ',Remainder)+4,999)
        END WeeklyDays,
        CASE WHEN ScheduleType = 'Monthly' and Remainder like '% day of %' THEN
            SUBSTRING(Remainder,7,CHARINDEX(' day ',Remainder)-7)
        END MonthlyDayOfMonth,
        CASE WHEN ScheduleType = 'Monthly' and Remainder like '% of every %' THEN
            REPLACE(SUBSTRING(Remainder,CHARINDEX(' of every',Remainder)+10,999),' months','')
        END MonthlyX, -- Y
        CASE WHEN ScheduleType = 'Monthly' and Remainder not like '% of every %' THEN
            SUBSTRING(Remainder,CHARINDEX(' of ',Remainder)+4,999)
        END MonthlyMonths,
        CASE WHEN ScheduleType = 'Yearly' THEN
            CASE WHEN Remainder like '% every %' THEN
                SUBSTRING(Remainder,4,CHARINDEX(' ',Remainder,4)-4) -- length 3 ?
            ELSE
                SUBSTRING(Remainder,CHARINDEX(' of ',Remainder)+4,999) -- Right(Remainder,3) ?
            END
        END YearlyMonth,
        CASE WHEN ScheduleType = 'Yearly' and Remainder like '% every %' THEN
            SUBSTRING(Remainder,CHARINDEX(' ',Remainder,4)+1,CHARINDEX(' ',Remainder,CHARINDEX(' ',Remainder,4)+1)-CHARINDEX(' ',Remainder,4)-1) -- Can we assume 3 ??
        END YearlyDayOfMonth,
        CASE WHEN ScheduleType = 'Yearly' and Remainder like '% every %' THEN
            REPLACE(SUBSTRING(Remainder,CHARINDEX(' every ',Remainder)+7,9999),' years','')
        END YearlyX,
        CASE WHEN (ScheduleType = 'Yearly' and Remainder like '% of %') OR
            (ScheduleType = 'Monthly' and remainder not like '% day %') THEN
            SUBSTRING(Remainder,CHARINDEX(' ',Remainder)+1,CHARINDEX(' of ',Remainder)-CHARINDEX(' ',Remainder)-1)
        END WeekDayOccurance
        FROM
        -- Get the start and end dates
        (SELECT
            EventName,
            ScheduleType,
            CAST(SUBSTRING(Remainder, CHARINDEX('Starting',Remainder)+9, IIF(CHARINDEX('Ending',Remainder)=0,999,CHARINDEX('Ending',Remainder) - (CHARINDEX('Starting',Remainder) + 9))) AS DATE)  StartDate,
            CAST(IIF(CHARINDEX('Ending',Remainder)=0,'31 Dec 2999',SUBSTRING(Remainder, CHARINDEX('Ending',Remainder) + 7, 999)) AS DATE) EndDate,
            RTRIM(STUFF(Remainder,CHARINDEX('Starting',Remainder),999,'')) Remainder
        FROM
            -- Get the schedule type
            (SELECT EventName,
                LTRIM(LEFT(Remainder, CHARINDEX(',',Remainder)-1)) ScheduleType,
                LTRIM(STUFF(Remainder, 1, CHARINDEX(',',Remainder), '')) Remainder
            FROM
                -- Get the event name
                ( SELECT
                    LEFT(@InputString, CHARINDEX(':',@InputString)-1) EventName,
                    STUFF(@InputString, 1, CHARINDEX(':',REPLACE(@InputString,'Daily ','Daily, ')), '') Remainder
                ) EventName
            ) ScheduleType
        ) StartEndDate
;
GO

CREATE FUNCTION ExpandEvent (
        @EventName VARCHAR(100),
        @ScheduleType VARCHAR(20),
        @StartDate DATE,
        @EndDate DATE,
        @WeeklyX VARCHAR(10),
        @WeeklyDays VARCHAR(50),
        @MonthlyDayOfMonth VARCHAR(10),
        @MonthlyX VARCHAR(10),
        @MonthlyMonths VARCHAR(50),
        @YearlyMonth VARCHAR(50),
        @YearlyDayOfMonth VARCHAR(10),
        @YearlyX VARCHAR(10),
        @WeekDayOccurance VARCHAR(50)
    ) RETURNS TABLE RETURN
WITH AllDays AS (
    SELECT *
    FROM (
        SELECT
            DENSE_RANK() OVER (ORDER BY DATEPART(year,D)) - 1 YearCount
            ,DENSE_RANK() OVER (ORDER BY DATEPART(year,D), DATEPART(month,D)) - 1 MonthCount
            ,DENSE_RANK() OVER (ORDER BY DATEPART(year,D), DATEPART(week,D)) - 1 WeekCount
            ,CASE DATEPART(month,D)
                WHEN 1 THEN 'Jan'
                WHEN 2 THEN 'Feb'
                WHEN 3 THEN 'Mar'
                WHEN 4 THEN 'Apr'
                WHEN 5 THEN 'May'
                WHEN 6 THEN 'Jun'
                WHEN 7 THEN 'Jul'
                WHEN 8 THEN 'Aug'
                WHEN 9 THEN 'Sep'
                WHEN 10 THEN 'Oct'
                WHEN 11 THEN 'Nov'
                WHEN 12 THEN 'Dec'
            END MonthAbrev
            ,DATEPART(day,D) MonthDay
            ,CASE DATEPART(weekday,D)
                WHEN 1 THEN 'Sun'
                WHEN 2 THEN 'Mon'
                WHEN 3 THEN 'Tue'
                WHEN 4 THEN 'Wed'
                WHEN 5 THEN 'Thu'
                WHEN 6 THEN 'Fri'
                ELSE 'Sat'
            END DayOfWeek
            ,DENSE_RANK() OVER (PARTITION BY DATEPART(year,D),DATEPART(month,D),DATEPART(weekday,D) ORDER BY D) DayWeekMonthOccurance
            ,COUNT(*) OVER (PARTITION BY DATEPART(year,D),DATEPART(month,D),DATEPART(weekday,D)) DayWeekMonthMax
            ,D
        FROM (
            SELECT DATEADD(day,t.N,@StartDate) D
            FROM (SELECT TOP(DATEDIFF(day,@StartDate,@EndDate) + 1) N - 1 N FROM Tally) T
            ) Days
        ) AllDays
    )
SELECT @EventName E, D FROM AllDays
WHERE (@ScheduleType = 'Daily')
    OR (WeekCount % @WeeklyX = 0 and @weeklyDays like '%'+DayofWeek+'%' and @ScheduleType = 'Weekly')
    OR (MonthDay = SUBSTRING(@MonthlyDayOfMonth,1,LEN(@MonthlyDayOfMonth)-2) and MonthCount % @MonthlyX = 0 and @ScheduleType = 'Monthly' and @MonthlyDayOfMonth IS NOT NULL and @MonthlyX IS NOT NULL)
    OR (MonthDay = SUBSTRING(@MonthlyDayOfMonth,1,LEN(@MonthlyDayOfMonth)-2) and @MonthlyMonths like '%'+MonthAbrev+'%' and @ScheduleType = 'Monthly' and @MonthlyDayOfMonth IS NOT NULL and @MonthlyMonths IS NOT NULL
    OR (DayWeekMonthOccurance = CASE WHEN @WeekDayOccurance like 'last %' THEN DayWeekMonthMax ELSE LEFT(@WeekDayOccurance,1) END and DayOfWeek = RIGHT(@WeekDayOccurance,3) and MonthCount % @MonthlyX = 0 and @ScheduleType = 'Monthly' and @WeekDayOccurance IS NOT NULL and @MonthlyX IS NOT NULL)
    OR (DayWeekMonthOccurance = CASE WHEN @WeekDayOccurance like 'last %' THEN DayWeekMonthMax ELSE LEFT(@WeekDayOccurance,1) END and DayOfWeek = RIGHT(@WeekDayOccurance,3) and @MonthlyMonths like '%'+MonthAbrev+'%' and @ScheduleType = 'Monthly' and @WeekDayOccurance IS NOT NULL and @MonthlyMonths IS NOT NULL)
    OR (@YearlyMonth like '%'+MonthAbrev+'%' and MonthDay = @YearlyDayOfMonth and YearCount % @YearlyX = 0 and @ScheduleType = 'Yearly' and @YearlyMonth IS NOT NULL and @YearlyDayOfMonth IS NOT NULL and @YearlyX IS NOT NULL)
    OR (DayWeekMonthOccurance = CASE WHEN @WeekDayOccurance like 'last %' THEN DayWeekMonthMax ELSE LEFT(@WeekDayOccurance,1) END and DayOfWeek = RIGHT(@WeekDayOccurance,3) and @YearlyMonth like '%'+MonthAbrev+'%' and @ScheduleType = 'Yearly' and @WeekDayOccurance IS NOT NULL and @YearlyMonth IS NOT NULL)
;
GO

```

## Table

The search table for the event dates

```
CREATE TABLE SearchEvents (
    ID BIGINT IDENTITY (1,1) NOT NULL PRIMARY KEY,
    EventName VARCHAR(100) NOT NULL,
    EventDate DATE NOT NULL
    );

```

## Table Population

An example of populating the SearchEvents table. This example shows each of the Event patterns that are acceptable and will likely error if that format is deviated from. Note the Months and Days are abbreviated. The ending date is not required and will default to 31 Dec 2999. But I would suggest that it is set.

```
INSERT INTO SearchEvents
SELECT Ex.E, Ex.D
FROM (VALUES
    ('Event A: Daily, Starting 3 Jun 2010 Ending 5 Dec 2020')
    ,('Event B: Weekly,  every 2 weeks on Mon,Tue Starting 3 Jun 2010 Ending 5 Dec 2020')
    ,('Event C: Monthly, every 2nd day of every 2 months Starting 3 Jun 2010 Ending 5 Dec 2020')
    ,('Event D: Monthly, every 3rd day of Jun,Jul,Dec,Jan Starting 3 Jun 2010 Ending 5 Dec 2020')
    ,('Event E: Monthly, every 2nd Tue of every 3 months Starting 3 Jun 2010 Ending 5 Dec 2020')
    ,('Event F: Monthly, every last Wed of Jun,Nov Starting 3 Jun 2010 Ending 5 Dec 2020')
    ,('Event B: Yearly, on Jun 10 every 1 years Starting 3 Jun 2010 Ending 5 Dec 2020')
    ,('Event H: Yearly, on 3rd Wed of Jun Starting 3 Jun 2010 Ending 5 Dec 2020')
)A(S) CROSS APPLY (SELECT * FROM parseEvent(S)) P
    CROSS APPLY (SELECT * FROM ExpandEvent(
        EventName,
        ScheduleType,
        StartDate,
        EndDate,
        WeeklyX,
        WeeklyDays,
        MonthlyDayOfMonth,
        MonthlyX,
        MonthlyMonths,
        YearlyMonth,
        YearlyDayOfMonth,
        YearlyX,
        WeekDayOccurance
    )) Ex

```

## Indexing

The important part, indexing of the date field

```
CREATE INDEX SE_EventDate_IDX ON SearchEvents(EventDate) INCLUDE (EventName);
GO

```

## Query

An example query

```
SELECT EventName, EventDate
FROM SearchEvents
WHERE EventDate BETWEEN CAST('1 Jan 2015' AS DATE) AND CAST('31 Dec 2015' AS DATE)
ORDER BY EventDate

```

This executed with the following stats on my machine. 1 years worth of events from ten years of data.

```
SQL Server parse and compile time:
   CPU time = 0 ms, elapsed time = 1 ms.

(435 row(s) affected)
Table 'SearchEvents'. Scan count 1, logical reads 5, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

 SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 98 ms.
SQL Server parse and compile time:
   CPU time = 0 ms, elapsed time = 0 ms.

 SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 0 ms.

```
> 1 votes

---
Tags: code-challenge, date, data-structures
---


title: Pronouncing Hex

text:
# Question
Title: Pronouncing Hex
# Pronouncing Hex

For those of you uninitiated with the show Silicon Valley, this challenge is inspired by an exchange that goes like this (YouTube):

```
Kid -
  Here it is: Bit… soup. It’s like alphabet soup, BUT… it’s ones and zeros
  instead of letters.
Erlich Bachman -
  {silence}
Kid -
  ‘Cause it’s binary? You know, binary’s just ones and zeroes.
Erlich Bachman -
  Yeah, I know what binary is. Jesus Christ, I memorized the hexadecimal
  times tables when I was fourteen writing machine code. Okay? Ask me
  what nine times F is. It’s fleventy-five. I don’t need you to tell me what binary is.

```

It should be noted that technically, `0x9 * 0xF = 0x87`, not 'fleventy-five', but this brings up an important question - how would you actually pronounce hex in conversation? It's not like `oh ex eff eff` flows off the tongue easily, so what should we do? Here's a handy pronunciation chart we will follow.

```
A = ay       A0 = atta-
B = bee      B0 = bibbity-
C = cee      C0 = city-
D = dee      D0 = dickety-
E = ee       E0 = ebbity-
F = eff      F0 = fleventy-

```

We can split a 4-length hex number into two groups of two, and determine the pronunciation from the table above, as well as common English pronunciation for numbers. So, for the example `0xFFAB`, we would get `Fleventy-eff bitey atta-bee`.

If a number is included, such as `0xF5AB`, you would print `Fleventy-five bitey atta-bee`. Also, if a number starts one of the groups, you should use it's "tens" pronunciation. For example, `0x5FAA` would become `Fifty-eff bitey atta-ay`. In the case where you have something like `0x1FAC`, this would be `Effteen bitey atta-cee`. But, if this rule were to be used for `0x1AF4`, `a-teen` could be confused for `eighteen`, so you must prepend a Y. So, the correct output would be `Yayteen bitey fleventy-four`

In the case of `0xD0F4`, instead of doing `Dickety-zero bitey fleventy-four`, we would ignore the zero and print `Dickety-bitey fleventy-four`.

Hyphens should only appear within the groups of two, i.e. bitey should not be connected to either group with a hyphen unless the first group is only one word! So `0x04F4` would be `four-bitey fleventy-four`, but `0x44F4` would be `forty-four bitey fleventy-four`. As *trichoplax* said, bitey should only be hyphened when following a round number.

For a comprehensive look at how this will work, check out the example I/O below.

# Objective

Create a *program or function* that will take a hexadecimal string as **input or a function argument** and produce it's pronunciation. The output must have proper capitalization. You may assume that the length of this number will always be 4.

# Example I/O

```
"0xFFFF" -> "Fleventy-eff bitey fleventy-eff"
"0x0000" -> "Zero"
"0x0010" -> "Ten"
"0x0100" -> "One-bitey zero"
"0x1110" -> "Eleven-bitey ten"
"0xBEEF" -> "Bibbity-ee bitey ebbity-eff"
"0x9999" -> "Ninety-nine bitey ninety-nine"
"0xA1B2" -> "Atta-one bitey bibbity-two"
"0x3C4F" -> "Thirty-cee bitey forty-eff"
"0x17AB" -> "Seventeen-bitey atta-bee"
"0x1AFB" -> "Yayteen-bitey fleventy-bee"
"0xAAAA" -> "Atta-ay bitey atta-ay"

```

---

This is , so least number of bytes wins.

# Answer
# Pyth - 312 293 286 251 bytes

Time to start reducing the data, more coming.

Holy biggest Pyth program I've ever written! There is still huge compression possible with the data, both algortihimically and base conversion, but just wanted to put this up.

```
Kcs@LGjC"qNjÆÉý(7läQ«I?sfçÂØ^Ðûü»   u$ÐÃoó}QÛã´Hf®?Nâ²-YÜZÔ7ÂþæX#\"åØ"26\q=+K>K11J.e?+?bnb\|@K+16k"ty"-kTbc"  twen | for | | | | | atta bibbi ci dicke ebbi fleven"d.srj"bitey "m?++@Kd?k<d18"teen"\-<d32+j\-@V,JKfT.Dd16\ ?Gh=G.DQ256tG4\-

```

I interpret input as hex literal through Q which it automatically detect with the `0x`. Then I divmod it 256 into the bytes, and remove the first byte if its zero, then map it through two arrays, one for `0-1F` and then `20-F0`. The second one gets a divmod through the first array also. The first option gets a hypen at the end, and the second get a hyphen at the middle and a space at the end. Join by `"bitey "`, capitalize with range, and strip hyphens with `.s` and we're good.

The base compression part is also interesting because I first started out with basic 128 -\> 256 conversion. But now, what I am doing is using `"q"` as the separator instead of space. Thus I can now consider the string as a base 26 string with `xLG`, improving compression tremendously.

Try it here online.

Test suite.
> 9 votes

# Answer
## Java - 856 bytes

Not short but at least the second answer ;)

It's a method called `String p(String n)` which will do the job:

```
String p(String n){String[]b={"","ten","twen","thir","for","fif","six","seven","eigh","nine",
"atta","bibbi","ci","dicke","ebbi","fleven"};String[]s={"zero","one","two","three","four",
"five","six","seven","eight","nine","ay","bee","cee","dee","ee","eff"};String[]t={"ten",
"eleven","twelve","thir","four","fif","six","seven","eigh","nine","yay","bee","cee","dee",
"ee","eff"};int w=Byte.valueOf(n.substring(2,3),16);int x=Byte.valueOf(n.substring(3,4),16);
int y=Byte.valueOf(n.substring(4,5),16);int z=Byte.valueOf(n.substring(5,6),16);String r=(w==
1?t[x]+(x>2?"teen":""):((w==0?"":b[w]+(w>1&&w!=10?"ty":"")+"-")+(w==0&&x==0?"":s[x])))+((w==0
&&x>0||w==1&&x<3||w>0&&x==0)?"-":w==0&&x==0?"":" ")+(w>0||x>0?"bitey ":"")+(y==1?t[z]+(z>2?
"teen":""):((y==0?"":b[y]+(y>1&&y!=10?"ty":"")+"-")+(y>1&&z!=0||y==0?s[z]:"")));return (char)
(r.charAt(0)-32)+r.substring(1);}

```
> 5 votes

# Answer
## Javascript - 577 719 bytes

```
function h(e){for(e=e.match(/.{1,2}/g),r="",i=1;i<e.length;i++)j=parseInt("0x"+e[i]),0!=j?r+=c(parseInt("0x"+e[i]))+"bitey ":i>1?r+="zero-bitey":0;return r=""==r?"Zero":r[0].toUpperCase()+r.substr(1,r.length-7),null!==r[r.length-1].match(/[-\s]$/g)?r=r.substr(0,r.length-1):0,r}function c(e){return d=["zero","one","two","three","four","five","six","seven","eight","nine","ay","bee","cee","dee","ee","eff","ten","eleven","twelve","thir","four","fif","six","seven","eigh","nine","yay","bee","cee","dee","ee","eff"],p=["twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety","atta","bibbity","city","dickety","ebbity","fleventy"],1>e?"":e>31?p[Math.floor(e/16)-2]+"-"+d[e%16]+" ":17>e?d[e]+"-":d[e]+"teen-"}

```

I'm sure there are improvements to be made. Added bonus, it parses arbitrary length hex strings.

EDIT: Whoops, it doesn't work right when there are leading zeros. Hm.

EDIT 2: Fixed, I think. JSFiddle
> 4 votes

---
Tags: code-golf, hexadecimal
---


title: Knockout probabilities

text:
# Question
Title: Knockout probabilities
Knockout is a basketball game where players take turns shooting. It is played as a sequence of two-player contests, each of which has the possibility of "knocking out" one of those players.

Suppose the players are `A B C D` and their chances of shooting and making a basket are `0.1 0.2 0.3 0.4` respectively, independently of the other player in the contest. The two players at the front of the line, `A` and `B`, "fight." Since `A` goes first, he is the *defender*, in danger of being eliminated, and `B` is the *attacker*, and not in danger of immediate elimination. `A` shoots first. If `A` makes it, `A` has successfully defended, and goes to the back of the line. The line would change to `B C D A`. If `A` doesn't make it, then `B` shoots. If `B` makes it, then `A` is out and `B` goes to the back of the line, so the line becomes `C D B`. If neither `A` nor `B` makes it, the process repeats, with `A` shooting again, until either `A` or `B` makes a basket.

Suppose the line changed to `B C D A` (`A` had successfully defended). Now, `B` and `C` "fight," with `B` being the defender, and `C` being the attacker. This process repeats until only one person is left over. That person is the winner.

Your task is to calculate the probabilities of each person winning given the chance that they will make a basket.

**Input**:

A list of numbers, such as `0.1 0.2` or `0.5 0.5 0.5 0.5`, where the *n*th number is the chance that the *n*th player will make a basket. You can take this input in any format you like, including as the parameters to a function.

**Output**:

A list of numbers, where the *n*th number is the chance that the *n*th player will win the game. Your numbers must be accurate to at least two decimal places at least 90% of the time. This means that you can use a simulation-based approach. However, if your code is not simulation based (it is *guaranteed* to return a correct answer to at least 6 decimal places) then take away 30% from your score.

Example between `0.5 0.5`: Call the players `A` and `B`. Let `p` be the probability of A winning. `A` has a `2/3` chance of successfully defending (since there's a `1/2` chance that `A` scores, a `1/4` chance that `A` misses and `B` scores, and a `1/4` chance that both miss and the process repeats). If `A` fails to defend, he is knocked out and `B` wins. If `A` defends, then the line becomes `B A`. Since the situation is symmetric, the probability of `A` winning is `(1 - p)`. We get:

`p = 2/3 * (1 - p) + 1/3 * 0`. Solving, we get `p = 2/5`. The output should be `2/5 3/5` or `0.4 0.6`.

I'm not good enough with probability to do more complex examples.

If you need more test cases, here are a few:

```
0.1 0.2 0.3 0.4 --> 0.01 0.12 0.25 0.62
0.99 0.99 --> 0.5 0.5 (it's not exact, but if you round to two decimal places, you get 0.5 and 0.5)

```

# Answer
## CJam (84 80 chars * 0.7 = 56)

```
{_,({_,,{_2$m<(;(+Q0\)\++m>\}%)_(+.{X2$-*_@+/}1\{1$*\1$-}%)1\-f/.f*:.+}{,da}?}:Q

```

Online demo. This is a recursive function which takes an array of doubles and returns an array of doubles. The online demo includes a tiny amount of scaffolding to execute the function and format the output for display.

### Dissection

The basic principle is that if there are `n > 1` players left, one of them must be the next one to be knocked out. Moreover, the order of the queue after that happens depends only on the initial order of the queue and on who gets knocked out. So we can make `n` recursive calls, calculate the winning probabilities for each player in each case, and then we just need to weight appropriately and add.

I'll label the input probabilities as `[p_0 p_1 ... p_{n-1}]`. Let `f(a,b)` denote the probability that `a` fails to defend against `b`. In any given round, the probability that `a` defends successfully is `p_a`, the probability that `b` knocks `a` out is `(1-p_a)*p_b`, and the probability that it goes to another round is `(1-p_a)*(1-p_b)`. We can either do an explicit sum of a geometric progression or we can argue that the two geometric progressions are proportional to each other to reason that `f(a,b) = (1-p_a)*p_b / (p_a + (1-p_a)*p_b)`.

Then we can step up a level to full rounds of the line. The probability that the first player is knocked out on is `f(0,1)`; the probability that the second player is knocked out is `(1-f(0,1)) * f(1,2)`; the third player is `(1-f(0,1)) * (1-f(1,2)) * f(2,3)`; etc until the last one is knocked out with probability `\prod_i (1-f(i,i+1)) * f(n-1,0)`. The same argument about geometric progressions allows us to use these probabilities as weights, with normalisation by a factor of `1 / \prod_i f(i, i+1 mod n)`.

```
{                   e# Define a recursive function Q
  _,({              e# If we have more than one person left in the line...
    _,,{            e#   Map each i from 0 to n-1...
      _2$m<         e#     Rotate a copy of the probabilities left i times to get [p_i p_{i+1} ... p_{n-1} p_0 ... p_{i-1}]
      (;(+          e#     i fails to defend, leaving the line as [p_{i+2} ... p_{n-1} p_0 ... p_{i-1} p_{i+1}]
      Q             e#     Recursive call
      0\)\++        e#     Insert 0 for the probability of i winning and fix up the order
      m>\           e#     Rotate right i times and push under the list of probabilities
    }%
    )               e#   Stack: [probs if 0 knocked out, probs if 1 knocked out, ...] [p_0 p_1 ...]
    _(+.{           e#   Duplicate probs, rotate 1, and pointwise map block which calculates f(a,b)
      X2$-*_@+/     e#     f(a,b) = (1-p_a)*p_b / (p_a + (1-p_a)*p_b)  TODO is the d necessary?
    }
    1\{1$*\1$-}%    e#   Lift over the list of f(a,b) a cumulative product to get the weights  TODO is the d necessary?
    )1\-f/          e#   Normalise the weights
    .f*             e#   Pointwise map a multiplication of the probabilities for each case with the corresponding weight
    :.+             e#   Add the weights across the cases
  }{,da}?           e# ...else only one left, so return [1.0]
}:Q

```
> 4 votes

---
Tags: code-golf, probability-theory, markov-chain
---


# Question
Title: Calculate probability of getting half as many heads as coin tosses.
Write a program that, given a small positive even integer from standard input, calculates the probability that flipping that many coins will result in half as many heads.

For example, given 2 coins the possible outcomes are:

```
HH HT TH TT

```

where H and T are heads and tails. There are 2 outcomes (`HT` and `TH`) that are half as many heads as the number of coins. There are a total of 4 outcomes, so the probability is 2/4 = 0.5.

This is simpler than it looks.

Test cases:

```
2 -> 0.5
4 -> 0.375
6 -> 0.3125
8 -> 0.2734375

```

# Answer
> 3 votes
## J, 22 ~~19~~ (killer approach)

I got down to this while golfing my Haskell answer.

```
%/@:>:@i.&.(".@stdin)_

```

(same I/O as my other J answer)

# Answer
> 3 votes
# Pari/GP - 32 30 34 chars

```
print(binomial(n=input(),n\2)/2^n)

```

# Answer
> 3 votes
**Python 53 Characters**

```
i=r=1.;exec"r*=(2*i-1)/i/2;i+=1;"*(input()/2);print r

```

# Answer
> 3 votes
## Haskell, 39 ~~43~~ ~~46~~

```
main=do x<-readLn;print$foldr1(/)[1..x]

```

Demonstration:

```
$ runhaskell coins.hs <<<2
0.5
$ runhaskell coins.hs <<<4
0.375
$ runhaskell coins.hs <<<6
0.3125
$ runhaskell coins.hs <<<8
0.2734375

```

# Answer
> 3 votes
## Excel, 25

Not quite according to spec, though :)

Name a cell `n` and then type the following into another cell:

```
=COMBIN(n,n/2)/POWER(2,n)

```

# Answer
> 2 votes
## Golfscript - 30 chars

Limitation - only works for inputs less than 63

```
'0.'\~..),1>\2//{{*}*}%~\/5@?*

```

test cases

```
$ echo 2 | ruby golfscript.rb binom.gs
0.50
$ echo 4 | ruby golfscript.rb binom.gs
0.3750
$ echo 6 | ruby golfscript.rb binom.gs
0.312500
$ echo 8 | ruby golfscript.rb binom.gs
0.27343750

```

Analysis

`'0.'` GS doesn't do floating point, so we'll fake it by writing an integer after this
`\~` Pull the input to the top of the stack and convert to an integer
`..` Make 2 copies of the input
`),1>`Create a list from 1..n
`\2//`Split the list into 1..n/2 and n/2+1..n
`{{*}*}%`Multiply the elements of the two sublists giving (n/2)! and n!/(n/2)!
`~`Extract those two numbers onto the stack
`\`Swap the two numbers around
`/`Divide
`5@?*`Multiply by 5\**n. This is the cause of the limitation given above

# Answer
> 2 votes
## J, 25 (natural approach)

```
((!~-:)%2&^)&.(".@stdin)_

```

Sample use:

```
$ echo -n 2 | jconsole coins.ijs
0.5
$ echo -n 4 | jconsole coins.ijs
0.375
$ echo -n 6 | jconsole coins.ijs
0.3125
$ echo -n 8 | jconsole coins.ijs
0.273438

```

It's all self-explanatory, but for a rough split of responsibilities:

* `!~ -:` could be thought of as *binomial(x,x/2)*
* `% 2&^` is "divided by *2^x*"
* `&. (". @ stdin) _` for I/O

# Answer
> 2 votes
## GNU Octave - 36 Characters

```
disp(binopdf((n=input(""))/2,n,.5));

```

# Answer
> 2 votes
## Ruby, 39 characters

```
p 1/(1..gets.to_i).inject{|a,b|1.0*b/a}

```

# Answer
> 2 votes
# TI-BASIC, 10

This will take more than ten bytes of calculator memory because there is a program header, but there are only ten bytes of code.

```
binompdf(Ans,.5,.5Ans

//Equivalently:

2^~AnsAns nCr (.5Ans

```

This takes input in the form `[number]:[program name]`; adding an Input command uses three more bytes. `~` is the unary minus token.

# Answer
> 1 votes
# Ruby - 50 57 54 chars

```
p (1..(n=gets.to_i)/2).reduce(1.0){|r,i|r*(n+1-i)/i/4}

```

# Answer
> 1 votes
## J, 20

```
f=:(]!~[:<.2%~])%2^]

```

examples:

```
f 2
0.5
f 4
0.375
f 6
0.3125
f 8
0.273438

```

# Answer
> 1 votes
**APL 21 15 chars**

```
((N÷2)!N)÷2*N←⎕

```

For where it doesn't render right

```
((N{ColonBar}2)!N){ColonBar}2*N{LeftArrow}{Quad}

```

Where everything in {} are APL specific symbols like here.

# Answer
> 1 votes
# Windows PowerShell, 45

```
($p=1)..($n="$input"/2)|%{$p*=(1+$n/$_)/4}
$p

```

Meh.

# Answer
> 1 votes
# MATLAB, 29

```
n=input('');binopdf(n/2,n,.5)

```

# Answer
> 0 votes
## PostScript, 77

```
([)(%stdin)(r)file token{2 idiv}if def
1
1 1[{[exch div 1 add 4 div mul}for
=

```

# Answer
> 0 votes
## Mathematica, 19

```
f=2^-# #!/(#/2)!^2&

```

# Answer
> 0 votes
# Javascript, 86 bytes

```
a=prompt(f=function(n){return n?n*f(n-1):1});alert(f(a)/(f(a/2)*f(a/2)*Math.pow(2,a)))

```

# Answer
> 0 votes
# Python 3, 99

This is a naive approach, I suppose, and fR0DDY's solution is much cooler, but at least I am able to solve it.

**Try it here**

```
from itertools import*
n=int(input())
print(sum(n/2==i.count("H")for i in product(*["HT"]*n))/2**n)

```

# Python 2, 103

```
from itertools import*
n=int(raw_input())
print sum(n/2==i.count("H")for i in product(*["HT"]*n))/2.**n

```

# Answer
> 0 votes
# Objective-C:

## 152 148 bytes for just the function.

Class methods, headers, and UI are not included within the code.

Input: an `int` value determinining the number of coins.

Output: a `float` value determining the probability.

```
-(float)calcPWithCoins:(int)x {int i=0;int j=0;for (int c=x;c<1;c+-){i=i*c;} for(int d=x/2;d<1;d+-){j=j*d;} return (((float)i/(float)j)/powf(2,x));}

```

## Ungolfed:

```
-(float)calcPWithCoints:(int)x
{
    int i = 0;
    int j = 0;
    for (int c = x; c < 1; c+-) {
         i = i * c;
    }
    // Calculate the value of x! (Factorial of x)

    for (int d = x / 2; d < 1; d+-)
         j = j * d;
    }
    // Calculate (x/2)! (Factorial of x divided by 2)

    return (((float)i / (float)j) / powf(2, x));
    /* Divides i! by (i/2)!, then divides that result (known as the nCr) by 2^x.
    This is all floating-point and precise. If I didn't have casts in there,
    It would be Integer division and, therefore, wouldn't have any decimal
    precision. */
}

```

This is based off of the Microsoft Excel answer. In C and Objective-C, the challenge is in hard-coding the algorithms.

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


title: Golf Practice: Pyth

text:
# Question
Title: Golf Practice: Pyth
This is a challenge about the the tricks and optimizations that can be used when golfing in Pyth. Pyth golfers may recognize many of the tricks involved. However, unfamiliar approaches and constructs may be involved, so take a look at the Pyth Tips as well as the Pyth Character Reference if you get stuck. Solutions may be tested here.

**Goal:** There are 8 problems, each with a Pyth snippet for you to optimize. Your goal is to create something equivalent but shorter. The reference solutions total 80 bytes. Your goal is to beat that by as much as possible.

The winner will go to the submission that solves all 8 problems with the smallest total number of bytes. Tiebreaker is earlier post.

**Answering:** Please spoiler your entire answer, except for your total score. It is intended that you do not look at other people's answers before submitting your own.

Each submission should answer every problem and give the corresponding byte count, but feel free to use the reference implementation if you cannot improve it.

**Details:** If the question calls for a certain value or output, `q` equality is desired, so `1` and `!0` are equivalent. If the question calls for testing whether a condition is true, the output must be truthy if the condition is true and falsy if the condition is false, but is unconstrained beyond that. You may not swap true for false and false for true. If the question calls for something to be printed, nothing else may be printed except a trailing newline.

All answers must be valid for the most recent Pyth commit as of this question's posting.

**Problem 1:** Given a set in Q, output a list containing the elements of Q in any order.

```
; 3 bytes
f1Q

```

**Problem 2:** Output the list `[1, 1, 0, 0, 1, 1, 0]`.

```
; 9 bytes
[J1JZZJJZ

```

**Problem 3:** Given a positive integer in Q, test whether all of Q's digits are positive (not zero).

```
; 7 bytes
!f!TjQT

```

**Problem 4:** Given a string in z, test whether z contains any quotation marks - `"` or `'`.

```
; 9 bytes
|}\'z}\"z

```

**Problem 5:** Map Q=1 to 'Win', Q=0 to 'Tie' and Q=-1 to 'Lose'.

```
; 20 bytes
@["Tie""Win""Lose")Q

```

**Problem 6:** Print `0123456789`.

```
; 6 bytes
sm`dUT

```

**Problem 7:** Given a string in z, count the number of inversions.

(Indexes `i` and `j` form an inversion if `i < j` but `z[i] > z[j]`).

```
; 17 bytes
ssmm>@zd@zkrdlzUz

```

**Problem 8:** Given a list in z, count the number of repeated adjacent elements.

```
; 9 bytes
lfqFT.:z2

```

# Answer
> 3 votes
This post is for the accumulation of the best solutions across all answers. Please edit in the solution and the answerer who first found that solution if there any improvements.

# 48 bytes

> 1. `SQ` \- 2 bytes, first posted by @orlp
> 2. `jC\f2` \- 5 bytes, first posted by @Maltysen
> 3. `-0`Q` \- 4 bytes, first posted by @Jakube
> 4. `@z`N` \- 4 bytes, mixture of @xnor and @Jakube, but not in any answers yet.
> (I didn't see it when writing the question, either)
> 5. `@c3"LoseTieWin"hQ` \- 17 bytes, first posted by @orlp
> 6. `pMT` \- 3 bytes, first posted by @Jakube
> 7. `s>M.cz2` \- 7 bytes, first posted by @orlp
> 8. `sqVtzz` \- 6 bytes, first posted by @Maltysen

# Answer
> 9 votes
# 52 bytes

> **Problem 1: 2 bytes**
>
> ```
>     SQ
> ```
>
> **Problem 2: 5 bytes**
> ```
>     jC\f2
> ```
>
> **Problem 3: 4 bytes**
> ```
>     -0`Q
> ```
> **Problem 4: 6 bytes**
> ```
>     @z+N\'
> ```
> **Problem 5: 17 bytes**
> ```
>     %3>"LTWoiisene"hQ
> ```
> or
> ```
>     @c3"LoseTieWin"hQ
> ```
> **Problem 6: 3 bytes**
> ```
>     pMT
> ```
> **Problem 7: 9 bytes**
> ```
>     s>R_d.cz2
> ```
> **Problem 8: 6 bytes**
> ```
>     sqVztz
> ```
> Combining @xnor's solution for problem 4 with mine (both 6 bytes) gives a nice 4 bytes solution. So 48 bytes are possible.

# Answer
> 7 votes
# 54 bytes

> **Task 1, 2 bytes**: `SQ`
> **Task 2, 6 bytes**: `j102 2`
> **Task 3, 5 bytes**: `*FjQT`
> **Task 4, 6 bytes**: `@z"'\"`
> **Task 5, 17 bytes**: `@c3"LoseTieWin"hQ`
> **Task 6, 4 bytes**: `jkUT`
> **Task 7, 7 bytes**: `s>M.cz2`
> **Task 8, 7 bytes**: `sqM.:z2`

# Answer
> 3 votes
# 58 bytes

> **Task 1, 2 bytes**: `SQ`
> **Task 2, 5 bytes**: `jC\f2`
> **Task 3, 6 bytes**: `!}`Z`Q`
> **Task 4, 8 bytes**: `|}\'z}Nz`
> **Task 5, 18 bytes**: `@c"Tie\nWin\nLose"bQ`
> **Task 6, 4 bytes**: `jkUT`
> **Task 7, 9 bytes**: `lf>FT.cz2`
> **Task 8, 6 bytes**: `sqVtzz`

# Answer
> 2 votes
## 57 bytes

> 1. (2) `SQ` Sort.
> 2. (5) `jC\f2` Convert `f` to ASCII val then base 2.
> 3. (5) `/`Q`0` Count `'0'` in the number string.
> 4. (5) `@z`\'` Takes the set intersection of the string with `"'"`.
> 5. (18) `@c"Tie Win Lose"dQ` Makes the list with split. I didn't get slicing to work.
> 6. (4) `jkUT` Join `range(10)`. Apparently converts to a string automatically.
> 7. (9) `sm>d_d.:z`Counts substrings that are greater than their reverse.
> 8. (9) `l@C,zz.:z` Length of intersection of sublists of the list and pairs of elements in the list. Same length as reference solution.

---
Tags: code-golf, pyth
---


# Question
Title: Draw the combinations that add up to 100
You have a box with a single digit number in each corner:

```
1|2
---
3|4

```

If we concatenate the digits along rows left to right, we get 12 and 34. If we concatenate the digits along columns top to bottom, we get 13 and 24. If we add all of these numbers, we get 12+34+13+24 = 83.

### Challenge

Write a program to print all such boxes where the sum calculated as above is equal to 100.

Assuming each corner contains a single digit number between 1 and 9, there are 9 combinations: 1157, 1247, 1337, 1427, 1517, 2138, 2228, 2318, and 3119. (Note that there are 25 combinations if we include 0, but we're not for this challenge.)

Note that the example 1234 doesn't work since 12+34+13+24 does not equal 100.

### Input

None

### Output

Answer boxes in the following format:

```
A|B
---
C|D

```

Output should be printed to STDOUT or closest alternative.

### Rules

* AB + CD + AC + BD = 100
* Each corner will contain the positive integers 1-9 only.
* 0 is excluded.
* Numbers can be used more than once.
* You need to draw the boxes, as above. (`A|B\n---\nC|D\n`)
* You need to output all valid answers.
* An additional trailing newline is fine.
* , so shortest code in bytes wins.
* Standard loopholes and T&C's apply.

This is my first submission so please do let me know if I need to clarify anything.

# Answer
> 8 votes
# Pyth, 42 38 34 bytes

```
V^ST4IqC\ds*VNsM^,T1 2Xj\|N3"
---

```

The trailing newline in the code is important. The main reason I'm competitive is because I use the vector dot product of `[1, 1, 5, 7]` and `[20, 11, 11, 2]` and compare it to 100.

# Answer
> 6 votes
# Ruby, 71

As hardcoding is not disallowed (and in any case it is difficult to draw a line) here's a partial hardcoded answer.

```
1.upto(3){|i|1.upto(7-i*2){|j|print i,?|,j,'
---
',8-j-2*i,?|,i+6,'
'}}

```

Explanation

The formula for a solution is as follows:

```
A*20+(B+C)*11+D*2=100

```

By modular arithmetic arguments, we see that A and D must differ by a constant amount, such that `(A*20+D*2)%11` is constant. In fact D=A+6. The `i` loop iterates through the three possible values of A.

The value of B can be anything from 1 to `7-i*2` and the total of B and C must be `14-A-D`. Thus we obtain the following expressions, which are printed. Ruby allows literal newlines in strings enclosed in `''`

```
   i     |    j
------------------
8-j-2*i  |   i+6

```

# Answer
> 4 votes
## Java, ~~202~~ ~~200~~ 198

Trying for the first time :D

EDIT: saved 2 bytes with slightly smaller calculation found in an other comment.

```
class C{public static void main(String[]c){for(int i=0;++i<5;)for(int j=0;++j<7;)for(int k=0;++k<10;)for(int l=0;++l<10;)if(20*i+11*(j+k)+2*l==100)System.out.printf("%s|%s%n---%n%s|%s%n",i,j,k,l);}}

```

# Answer
> 4 votes
## Batch - 187 bytes

Brute force.

```
@!! 2>nul||cmd/q/v/c%0&&exit/b
set y=for /l &set z= in (1,1,9)do
%y%%%a%z%%y%%%b%z%%y%%%c%z%%y%%%d%z%set/aa=%%a%%b+%%c%%d+%%a%%c+%%b%%d&if !a!==100 echo %%a^|%%b&echo ---&echo %%c^|%%d

```

Un-golfed it's *slightly* less disgusting:

```
@echo off
setLocal enableDelayedExpansion
for /l %%a in (1,1,9) do (
    for /l %%b in (1,1,9) do (
        for /l %%c in (1,1,9) do (
            for /l %%d in (1,1,9) do (
                set/aa=%%a%%b+%%c%%d+%%a%%c+%%b%%d
                if !a!==100 (
                    echo %%a^|%%b
                    echo ---
                    echo %%c^|%%d
                )
            )
        )
    )
)

```

# Answer
> 3 votes
# CJam, 40 bytes

```
A4m*{[KBBY].*:+56=},{:)2/'|f*"
---
"*N}/

```

The approach for finding the combinations is different from @Optimizer's, but the code for printing them is identical.

Try it online in the CJam interpreter.

### How it works

```
A4m*     e# Push all vectors of length 4 with coordinates in [0 ... 9].
         e# We'd normally use [0 ... 8] here, but "9 4m*" is 1 byte longer and
         e# "A4m*" doesn't produce any false positives.

{        e# Filter the vectors:
[KBBY].* e#   Multiply the elements of the vector by 20, 11, 11 and 2.
:+       e#   Add all four products.
56=      e#   Check if the sum is 56. 56 is used instead of 100 since all elements
         e#   of the vector will be incremented and 56 + 20 + 11 + 11 + 2 == 100.
},       e# Keep only vectors for which = pushed a truthy value.

{        e# For each vector:
:)       e#   Increment each coordinate.
2/       e#   Split into pair.
'|f*     e#   Join each pair, delimiting by '|'.
"
---
"*       e#   Join the two pairs, delimiting by "\n---\n".
N        e#   Push "\n".
}/       e#

```

# Answer
> 3 votes
# Haskell, ~~125~~ 121 bytes

```
s=show
f=putStr$unlines[s a++'|':s b++"\n---\n"++s c++'|':s d|[a,b,c,d]<-mapM id$"abcd">>[[1..9]],20*a+11*(b+c)+2*d==100]

```

Usage:

```
*Main> f
1|1
---
5|7
1|2
---
4|7
1|3
---
3|7
1|4
---
2|7
1|5
---
1|7
2|1
---
3|8
2|2
---
2|8
2|3
---
1|8
3|1
---
1|9

```

`>>` in `"abcd">>[[1..9]]` makes a list with 4 (length of 1st parameter) copies of the second element, i.e. `[[1..9],[1..9],[1..9],[1..9]]`. `mapM id` makes a list of all combinations thereof, i.e `[0,0,0,0]` to `[9,9,9,9]`. Keep those that sum up `100` and build a string with the box of it. Print all boxes.

Thanks @Mauris for 1 byte and making me review my post to find 3 more.

# Answer
> 3 votes
# Haskell, 107 131 bytes

```
s=show
r=[1..9]
v=putStr$unlines[s a++"|"++s b++"\n---\n"++s c++"|"++s d++"\n"|a<-r,b<-r,c<-r,d<-r,(2*a+b+c)*10+b+2*d+c==100]

```

The second version of my first Haskell program ever!

This time with display as per requirements, shamelessly stolen adapted from nimi's (well I did some research but it seems there aren't so may efficient ways to display characters in Haskell so that putStr$unlines is hard to avoid).

And...apart from the factorisation of the formula at the end, it's still readable =)

# Answer
> 2 votes
# CJam, ~~43~~ 42 bytes

```
A,1>4m*{2/_z+Afb:+100=},{2/'|f*"
---
"*N}/

```

Explanation to follow.. by today EOD

Try it online here

# Answer
> 2 votes
# Python 2, ~~145~~ 129 Bytes

I'm currently toying with a few different methods of calculating which should be shorter than what is outlined, but I will post what I have now.

```
i=int
for k in range(1000,9999):
 a,b,c,d=`k`
 if i(a+b)+i(c+d)+i(a+c)+i(b+d)==100and not'0'in`k`:print a+'|'+b+'\n---\n'+c+'|'+d

```

# Answer
> 1 votes
# Python 3, 159

Quick and dirty.

```
N='123456789'
D='%s|%s\n'
O=D+'---\n'+D
I=int
[print(O%(a,b,c,d)if I(a+b)+I(c+d)+I(a+c)+I(b+d)==100 else'',end='')for a in N for b in N for c in N for d in N]

```

# Answer
> 1 votes
# Java, 450

My first (ungolfed) attempt looked like this:

```
class B{
  public static void main(String[]a){
    for(int i=1;i<10;i++)
      for(int j=1;j<10;j++)
        for(int k=1;k<10;k++)
          for(int l=1;l<10;l++)
            if(Integer.parseInt(i+""+j)+Integer.parseInt(k+""+l)+Integer.parseInt(i+""+k)+Integer.parseInt(j+""+l)==100){
              System.out.println(i+"|"+j);
              System.out.println("---");
              System.out.println(k+"|"+l+"\n");
            }
  }
}

```

# Answer
> 1 votes
# R, 165 bytes

```
e=expand.grid(d<-1:9,d,d,d)
a=apply
o=a(e[a(e,1,function(x)20*x[1]+11*(x[2]+x[3])+2*x[4]==100),],1,function(x)cat(x[1],"|",x[2],"\n---\n",x[3],"|",x[4],"\n",sep=""))

```

This would have been significantly shorter had I chosen to hard-code the output in some way. Like a few other solutions, this takes advantage of the identity 20 *x*1 \+ 11 (*x*2 \+ *x*3) + 2 *x*4 = 100.

Ungolfed + explanation:

```
# Create a matrix where each row is a combination of the digits 1-9
e <- expand.grid(1:9, 1:9, 1:9, 1:9)

# Filter the rows of the matrix using the aforementioned identity
e <- e[apply(e, 1, function(x) 20*x[1] + 11*(x[2]+x[3]) + 2*x[4] == 100), ]

# Print each row formatted into boxes
o <- apply(e, 1, function(x) cat(x[1], "|", x[2], "\n---\n", x[3], "|", x[4], sep = ""))

```

You may be wondering why the last statement is an assignment. As it turns out, the `cat` function, which concatenates and prints, returns a value of `NULL`. When you call `cat` from within a function like `apply`, the output will be followed by `NULL`, which is undesirable. There are two ways around this: assign it to a variable or wrap it in `invisible`. Here I've opted for the former since it's significantly shorter.

You can try it online.

# Answer
> 1 votes
## PowerShell , 98

adapted steveverrill's formula

```
:\>cat printbox.ps1

1..9|%{for($j=1;$j-lt10;$j++){if(($k=(8-$j-2*$_))-gt0){"{0}|{1}`n---`n{2}|{3}"-f$_,$j,$k,
($_+6)}}}

:\>powershell -f printbox.ps1
1|1
---
5|7
1|2
---
4|7
1|3
---
3|7
1|4
---
2|7
1|5
---
1|7
2|1
---
3|8
2|2
---
2|8
2|3
---
1|8
3|1
---
1|9

```

---
Tags: code-golf
---


title: VSEPR Strikes Back! [Revamped Again]

text:
# Question
Title: VSEPR Strikes Back! [Revamped Again]
(Note: I know that the VSEPR method fails sometimes, and that there are exceptional molecules. The challenge is about the molecules which conform.)

Most people who have taken an introductory chemistry course know about molecules, and (probably) the VSEPR theory of chemical bonding. Basically, the theory predicts the shape of a molecule given three main properties:

* `A`: The central atom. You may assume this is the first element appearing in the chemical formula; for example, in CH4, you may assume the central atom is C.
* `X`: The number of atoms bonded to the central atom A.
* `E`: The number of "lone electron pairs" on the central atom. For the purposes of this challenge, the number of outer electrons A has is given by the last digit of the element's column number on the periodic table.

+ If A is bonded to an element X in column 17 of the periodic table, there will be a mutual sharing of electrons, so that A effectively has one additional electron for each atom of X attached to it. (This does not apply for elements such as O or S in column 16.)

Each bond requires two of these electrons. Leftover electrons not used in bonding with other atoms are found in pairs of two, called lone pairs. So E is the number of electrons not used in bonding by the central atom A divided by 2. (It may be assumed that input will always lead to A having an even number of electrons.)

For example, a molecule which has 1 lone pair and 3 atoms bonded to the main atom is AX3E1, which is the trigonal pyramidal configuration. (There is always only 1 central atom, so A never has a subscript.)

## The Challenge

Your job is, given a string representing a covalent chemical compound, to output the shape of that molecule. "*But wait!*", exclaim the exasperated programmers, "*you can't expect us to input all of the molecular data for every element!*" Of course we can, but as that wouldn't be fun, we'll only consider the compounds formed by the following 7 elements:

```
Carbon    C
Sulfur    S
Oxygen    O
Nitrogen  N
Chlorine  Cl
Bromine   Br
Fluorine  F

```

The input is any molecule composed of the above 7, such as `CO2` or `SF4`, that is in the form `AXN`, where A and X are each one of the above seven element symbols, X is not `C` or `N`, and N is a number between 2 and 6 inclusive.

The output should be the name of the geometric shape of the molecule, for example "linear".

The following (don't get scared, I swear they're less than they seem!) is a list of all possible configurations along with their AXE number and a drawing of how they look (adapted from Wikipedia's nifty table):

## Test Cases

> CO2: CO2 -\> linear
> OF2: OF2 -\> bent
> CCl2: CCl2 -\> bent
> BrF3: BrF3 -\> T-shaped
> SF4: SF4 -\> seesaw

Notes:
\- We won't consider compounds in which the first element has a subscript other than 1, such as C2H4.
\- Standard loopholes apply.
\- This is a code golf, so the shortest answer wins (obviously)

# Answer
# Ruby, 250

```
s=gets
e=7-"FBOSN C".index(s[0])/2+(s[1]==?l?3:0)
x=s.reverse!.to_i
e+="Frl".index(s[2])?x:0
t="trigonal "
puts [["linear",b="bent",b],[t+"planar",t+p="pyramidal","T-shaped"],["tetr"+h="ahedral","seesaw"],[t+"bi"+p,"square "+p],["oct"+h]][x-2][e/2-x]

```

Note that with the rules as they are, AX2E3 and AX4E2 are not possible with the given elements, so they are not supported. All test cases passed.

**with comments**

```
s=gets                                     #get input with newline attached
e=7-"FBOSN C".index(s[0])/2+(s[1]==?l?3:0) #calculate the number of electrons (not lone pairs) from A. Note the addition required to differentiate C and Cl.
x=s.reverse!.to_i                          #reverse the input string so the number is at the beginning (after the newline) and evaluate the string as a number to get X.
e+="Frl".index(s[2])?x:0                   #if the character after the number is in "Frl" we have a halogen so increment number of electrons accordingly.
t="trigonal "                              #as "trigonal " goes at the beginning of the string, we cannot define it on the fly, it is defined as a constant here.
                                           #array of outputs below. note the subscripts at the end: x-2 to put it in the range 0..4 and e/2-x to convert e into the actual number of lone pairs.
puts [["linear",b="bent",b],[t+"planar",t+p="pyramidal","T-shaped"],["tetr"+h="ahedral","seesaw"],[t+"bi"+p,"square "+p],["oct"+h]][x-2][e/2-x]

```
> 1 votes

---
Tags: code-golf, chemistry
---


title: Alphabet Between Encryption

text:
# Question
Title: Alphabet Between Encryption
You must write a program that encrypts an input into a string of characters.

For every character `i` in the input up to the second to last character, take the `i` and `i+1` characters and encode them by writing the letters of the alphabet, in order, that range in the same direction between those chosen characters.

For example: if the original string were `bo` then it would be encoded as `cdefghijklmn`, but if the string were `boa` then `bo` is encoded as `cdefghijklmn` and `oa` is encoded as `nmlkjihgfedcb` with the final encrypted string being `cdefghijklmnnmlkjihgfedcb`.

If the original string contain zero letters between two chosen characters, such as the string `ab` then you should encrypt it as `aRb` with `R` standing for what direction in the alphabet to go in determining the original characters. The encrypted string `aRb` represents `ab` but the encrypted string `aLb` represents `ba` (`R` = right, `L` = left).

If two chosen characters in the original string are the same, such as the string `tt`, then you should encrypt it as `tZt` with `Z` standing for zero letters in between.

**Examples:**

Input: `att` Output: `bcdefghijklmnopqrstZt`

Input: `brep` Output: `cdefghijklmnopqqponmlkjihgffghijklmno`

Input: `Optimizer` Output: `oRpqrssrqponmlkjjkllkjjklmnopqrstuvwxyyxwvutsrqponmlkjihgffghijklmnopq`

**Rules:**

* You can write a program or a function.
* Your input may contain uppercase letters, so you need to put them all to lowercase before encrypting.
* You can ignore non-alphabet characters.
* One character length strings are undefined.
* Shortest code in bytes wins!

# Answer
> 3 votes
# Pyth, 38 bytes

```
M|strFGjHGsm?>Fd_g_d\Lgd?qFd\Z\R.:rzZ2

```

Demonstration.

```
M|strFGjHGsm?>Fd_g_d\Lgd?qFd\Z\R.:rzZ2
                                          Implicit: z = input(), Z = 0
                                          g is a function of a 2 letter string
                                          and an insert letter.
M                                         def g(G, H): return
    rFG                                   Take the string range between the
                                          letters in G.
   t                                      Remove the first letter to get just
                                          the letters in between.
  s                                       Concatenate.
 |                                        Logical or (if nothing in between)
       jHG                                H.join(G)
                                  rzZ     Convert input to lowercase.
                                .:   2    Take 2 letter substrings.
           m                              Map d over the substrings
            ?>Fd                          If the first character of `d`
                                          is greater than the second,
                 _g_\L                    g(d[::-1], 'L')[::-1]
                      gd                  else, g(d,
                        ?qFd              if the letters of d are the same,
                            \Z            'Z'
                              \R          else 'R')
          s                               Concatenate and print.

```

# Answer
> 3 votes
# C - 161 Bytes - GCC

```
#define y(x) putchar(x)
main(_,z){for(_=getchar();-~(z=getchar());_=z)for(_==z?y(_),y(90),y(z):-~_==z?y(_++),y(82),y(z):_==-~z?y(_),y(76),y(z):_;_<z;y(_),_++);}

```

Will update when I get it shorter

# Answer
> 2 votes
# JavaScript ES6, 253 bytes

```
(d,y=`abcdefghijklmnopqrstuvwxyz`)=>[...`${d}`.toLowerCase()].map((l,i,a,m=a[i-1],c=s=>y.search(s),d=(s,e)=>y.slice(c(s),c(e)).slice(1),j=c(m),k=c(l))=>m?l==m?l+'Z'+l:j+1==k?m+'R'+l:k+1==j?l+'L'+m:j>k?[...d(l,m)].reverse().join``:k>j?d(m,l):0:'').join``

```

Just by glancing you can see all the places where this can be golfed. I can probably chop off 100 bytes.

Ungolfed:

```
(d,y=`abcdefghijklmnopqrstuvwxyz`)=>
[...`${d}`.toLowerCase()].map((l,i,a, m=a[i-1],
 c=s=>y.search(s),
 d=(s,e)=>y.slice(c(s),c(e)).slice(1))
   =>m?
     l==m?         l+'Z'+l:
     c(m)+1==c(l)? m+'R'+l:
     c(l)+1==c(m)? l+'L'+m:
     c(m)>c(l)?    [...d(l,m)].reverse().join``:
     c(l)>c(m)?    d(m,l):  0:
'').join``

```

You can clearly see where this can be golfed in the `?:` sequence.

---

ES5 Snippet:

```
function t(d) {
    var y = 'abcdefghijklmnopqrstuvwxyz';
    return (d+'').toLowerCase().split('').map(function (l,i,a) {
        var m = a[i - 1],
            c = function (s) {
                return y.search(s)
            },
            d = function (s,e) {
                return y.slice( c(s), c(e) ).slice(1);
            };
       return m ?
              l == m           ? l + 'Z' + l :
              c(m) + 1 == c(l) ? m + 'R' + l :
              c(l) + 1 == c(m) ? l + 'L' + m :
              c(m) > c(l)      ? d(l,m).split('').reverse().join('') :
              c(l) > c(m)      ? d(m,l)                              :
              0 : ''
    }).join('');
}

// Demo
document.getElementById('go').onclick=function(){
  document.getElementById('output').innerHTML = t(document.getElementById('input').value)
};
```

```
<div style="padding-left:5px;padding-right:5px;"><h2 style="font-family:sans-serif">Encoding Snippet</h2><div><div  style="background-color:#EFEFEF;border-radius:4px;padding:10px;"><input placeholder="Text here..." id="input"><button id='go'>Encode!</button></div><br><div style="background-color:#EFEFEF;border-radius:4px;padding:10px;"><span style="font-family:sans-serif;">Output:</span><br><pre id="output" style="background-color:#DEDEDE;padding:1em;border-radius:2px;overflow-x:auto;"></pre></div></div></div>
```

# Answer
> 1 votes
# Python ~~343~~ 334 bytes

```
import sys,re,string
j=''.join
a=string.ascii_lowercase
for l in sys.stdin:
 s,L=re.sub('[^a-z]','',l.lower()).strip(),[]
 for i,c in enumerate(s[:-1]):o=s[i+1:i+2]or c;b,d=a.index(c),a.index(o);L.extend(j(e[1])for e in[(c==o,[c,'Z',c]),(c<o,(a[b+1:d],[c,'R',o])[b+1==d]),(c>o,(a[d+1:b][::-1],[c,'L',o])[b-1==d])]if e[0])
 print(j(L))

```

Code on ideone.

First golf ever. Any suggestions would be great.

# Answer
> 1 votes
# K5, 77 bytes

*ouch*

```
,/{$[(p:d>0)&3>d:1+x-y;"LZR"@d;`c$$[p;1_y+!x-y;|1_x+!y-x]]}':{(x;x+32)@x<97}'

```

Explanation coming after more golfing.

# Answer
> 1 votes
## Haskell, 168 bytes

```
import Data.Char
s=succ
b#a|a==b=[a,'Z',b]|s a==b=[a,'R',b]|a==s b=[a,'L',b]|a>b=reverse$a#b|a<b=[s a..pred b]
e=concat.(tail>>=zipWith(#)).map toLower.filter isLetter

```

running:

```
λ: e "att"
"bcdefghijklmnopqrstZt"
λ: e "brep"
"cdefghijklmnopqqponmlkjihgffghijklmno"
λ: e "Optimizer"
"oRpqrssrqponmlkjjkllkjjklmnopqrstuvwxyyxwvutsrqponmlkjihgffghijklmnopq"
λ: e "aabbcfcBBAa"
"aZaaRbbZbbRcdeedcLbbZbbLaaZa"

```

# Answer
> 0 votes
# Haskell, 185 bytes

```
import Data.Char
s=succ
p=pred
f(a:b:c)|b==s a=q 'R'|a==s b=q 'L'|a==b=q 'Z'|a<b=[s a..p b]++n|a>b=[p a,p$p a..s b]++n where q m=a:m:b:n;n=f(b:c)
f _=[]
g x=f[toLower e|e<-x,isLetter e]

```

Usage: `g "brep"` -\> `"cdefghijklmnopqqponmlkjihgffghijklmno"`.

How it works: `g` throws away all non-letters and converts the letters to lower case and calls `f` to do the encryption. Depending on the first two characters `f` inserts `R`, `L` or `Z` or builds the sequence in-between and and appends the result of a recursive call of itself with the tail of the input.

---
Tags: code-golf
---


# Question
Title: Merging a dict compression referencing the original list into 1 line
# Background

A question wanted to solve a problem in a way that made it unreasonably complex: https://stackoverflow.com/a/31551257/29347

The problem in the original question is:

> Take a list of (key, value) and produce a dict such that {key: sum(value)}

# My Problem

I want to use dict compression with `list.count` or `str.count` but constructing the iterable, iterating and referencing it in one motion has me stumped.

```
a = [("a",1), ("b",3), ("a",5)]

# b = "abbbaaaaa"
b = "".join(b[0] * b[1] for b in a)

# dict_a = {'a': 6, 'b': 3}
dict_a = {e[0]: b.count(e) for e in b}

```

# Goal

Remove the need for the variable b thus merging the two lines whilst staying true to the solution.

# Answer
> 1 votes
```
dict_a = {t[0] : sum(tp[1] for tp in a if tp[0] == t[0]) for t in a}

```

Horribly slow, but hey it's a one liner!

---
Tags: python
---


title: Deep thought: Levenshtein distance

text:
# Question
Title: Deep thought: Levenshtein distance
So, ~~blatantly plagiarizing from~~ inspired by this challenge and its sequel, I thought I'd add another.

The text to match:

> What do you get when you multiply six by nine

The result your function/program/etc. should print or return:

> 42

An online calculator for Levenshtein distance can be found here: http://planetcalc.com/1721/

**Comments are disallowed.**

# Answer
> 7 votes
# GolfScript, 2

```
What 42 you get when you multiply six by nine

```

All words except `do` are undefined tokens, so they do nothing.

Try it online in Web GolfScript.

# Answer
> 3 votes
# TI-BASIC, 3

Replaces the first character with length(, which is a single TI-BASIC token.

```
length("t do you get when you multiply six by nine

```

# Answer
> 2 votes
# Ruby, 10

```
p"What do you get when you multiply six by nine".sum/99

```

In the spirit of the challenge. Following the letter I think the best you can do is

```
p 42||"What do you get when you multiply six by nine"

```

but that program would still work if you changed the string.

# Answer
> 1 votes
# Pyth, 4

```
42 "What do you get when you multiply six by nine

```

That's not a comment, it's a string that doesn't get printed.

# Answer
> 1 votes
# CJam, 3

```
"hat do you get when you multiply six by ni",

```

`,` pushes the string's length.

Try it online in the CJam interpreter.

# Answer
> 0 votes
## CMD, 9

```
echo 42||What do you get when you multiply six by nine

```

Code after `||` inline will only run if the previous command generates an error.

---
Tags: code-challenge
---


title: Probability to clear the board or win

text:
# Question
Title: Probability to clear the board or win
In the game Hearthstone there is a playing board containing friendly and enemy minions, and two heroes - yours and the enemy's.

To generalize and simplify, we will assume it's your turn, the opponent has 0-7 minions with given health values on the board, and is at *H* life points. We will ignore our side of the board entirely.

Now we will cast a supercharged version of Arcane Missiles. This ability shoots a random enemy (uniformly selected from all alive minions and the hero) for 1 damage, repeated *A* times. Note that if a target dies (reduced to 0 health), it can not be hit again.

Given *H*, *A* and a list *L* containing the health values of the minions, output the probability as a percentage accurate to 2 digits after the decimal point that *either or both* the hero dies, or every minion dies (clearing the board).

Some examples logically derived:

```
H: 30, A: 2, L: [1, 1]

We have no chance of killing our opponent here. To clear the board, both shots
must hit a minion. The first shot has a 2/3 chance of hitting a minion, then
that minion dies. The second shot has a 1/2 chance. The probability of clearing
the board or killing our opponent is thus 2/6 = 33.33%.

H: 2, A: 3, L: [9, 3, 4, 1, 9]

We have no chance of clearing the board here. 2/3 shots must hit the hero. However,
if any of the shots hit the 1 health minion, it dies, increasing the odds for
future shots.

4/6 the first shot hits a health minion. The next two shots must hit the hero,
for a total probability of 4/6 * 1/6 * 1/6.

1/6 the first shot hits the 1 health minion and it dies. The next two shots must
hit the hero, for a total probability of 1/6 * 1/5 * 1/5.

1/6 the first shot hits the hero. Then there are three options again:

    1/6 the second shot hits the hero.
    4/6 the second shot hits a healthy minion. The last shot must hit 1/6.
    1/6 the second shot hits the 1 health minion. The last shot must hit 1/5.

This last option gives a probability of 1/6 * (1/6 + 4/6 * 1/6 + 1/(5*6)). The
total probability is the chance of any of these scenarios happening, or:

    4/6 * 1/6 * 1/6 + 1/(6*5*5) + 1/6 * (1/6 + 4/6 * 1/6 + 1/(5*6)) = 7.70%

```

As you can see, it gets complicated quickly... Good luck!

---

Your score is the number of bytes of code of your answer. If your code computes a probability exactly rather than simulating boards, halve your score. Lowest score wins.

# Answer
# Pyth, (67 bytes) / 2 = 33.5

```
L_,*lbJ*FeCbsm*hd/JedbM?&hHstH?GymgtG-XdKH_1_!dlH,01,TT*100cFghQstQ

```

This qualifies for the bonus even though I had to manually implement arbitrary precision rationals.

(I wish Pyth5 was already a thing).

Input from STDIN in the format `A, H, L`

Demonstration.

Corrected to output percentage. Percentage is as acurate as possible, due to use of integer math until the last step.

At the high level, the first segment, `L_,*lbJ*FeCbsm*hd/Jedb`, is a helper function which takes a list of rationals in the form of 2 element lists, and outputs their average as an (unreduced) rational.

The second segment, `M?&hHstH?GymgtG-XdKH_1_!dlH,01,TT`, recusively calculates the probability of victory.

The third segment, `cFghQstQ` formats the input to fit the function and performs the final division.

On the second example case, the final unreduced 2-tuple is too long to fit on the screen:

```
[83158592487544376524800000000000000000000, 1079462498636393349120000000000000000000000]

```

Fortunately, Pyth does have arbitrary precision integers.
> 3 votes

# Answer
# Ruby, Score: 328/2 = 164

Here is a ruby solution that calculates the answer exactly (and then truncates the answer as specified), using the power of recursion. You run it in irb with the `g` function:

```
require 'rational'
def c(h, a, l)
  l=l.reject { |m| m == 0 }
  return 1.to_r if l.empty? ||h==0
  return 0.to_r if a==0
  a-=1
  n=[c(h-1, a, l), *((0..l.length-1).map { |i| nl = l.dup;nl[i]-=1;c(h, a, nl)})]
  n.inject(:+)/n.length
end
def g(h, a, l)
  puts "%.2f%%" % (c(h.to_r, a.to_r, l.map(&:to_r)) * 100)
end

```

Example output:

```
> g 30, 2, [1,1]
33.33%
> g 2, 3, [9,3,4,1,9]
7.70%

```
> 2 votes

---
Tags: code-golf, probability-theory, card-games
---


title: Word with greatest repeat of letters

text:
# Question
Title: Word with greatest repeat of letters
Recently there was a question on Stack Overflow where the OP was trying to write a function to find the word in a string that has the most repeated letters. It is of course not hard to write one up in seconds, and I wrote one in Javascript as short as I can for fun. But I'm not an expert in code golfing, so I wonder how much shorter can this simple program be!

---

## Challenge

Write a program or function that takes in a string of words and return or print the word with the most repeating single letters.

Rules:

* Choose the word with the greatest number of repeating *single* letters (see examples below)
* If no word has repeating letters, return -1.
* If two words have the same maximum number of repeating letters, choose the one closer to the start of the string.
* The shortest submission in bytes wins.

## Input

Take as input a string consisting of one or more space-delimited words. Input can be from STDIN (or closest alternative), command line parameters, or function arguments.

## Output

Print the output to STDOUT to return it.

## Examples

Consider the string `aaabbb cccc`. This contains two words: `aaabbb` and `cccc`. The word `aaabbb` has 3 `a`'s and 3 `b`'s, and `cccc` has 4 `c`'s. So the maximum number of repeated letters in `aaabbb` is 3 and the maximum in `cccc` is 4. We want to choose the word with the maximum number of repeated single letters, so the output for `aaabbb cccc` should be `cccc`.

Other test cases:

```
Today, is the greatest day ever!  --> greatest
This is a great day               --> -1
aaabbb cccc                       --> cccc

```

# Answer
# C - GCC - ~~159~~ ~~145~~ 135 Bytes

```
x=0,w=0,i,j,c;main(int _,char**z){while(--_)for(j=i=0;_[z][i];j=++i,x=c>x?w=_,c:x)for(c=0;j--;)c+=z[_][i]==z[_][j];puts(x?z[w]:"-1");}

```

Will update when I can truncate it a bit

How to compile: gcc -w cg.c

How to run: ./a.out word1 word2 aass ddaaa ssdddd

Output: ssdddd

No-Output/No-match: -1

First off, I cheated a bit, by taking in the words as program arguments, but getting GCC to parse the words and give me a word count for free was too much reward to pass up.

### How does it work?

We have 3 nested loops. The first incrementing through each word, the next two are mimicking a bubble sort to compare values. The first letter is never compared with itself, and each subsequent letter is compared to each previous letter. Whenever a word has more same letters than a previous word, the word is stored in x, and the count of how many same letters is also stored.

### GCC Abuse

We use implicit global auto int delcarations for our integers. We allow argv to be an int instead of a char (currently a char, this is a TODO). We make use of default functions such as puts and getchar. We also make use of the comma operator to overload our trinary (conditional) operator.

### Want 2 less bytes?

Replace "-1" with \*z and name the file -1

### Program unobfuscated and untested:

```
int main(int argc, char * argv[])
{
    int word = 0           // Current most repeat letters word
    int count = 0;        // Current most repeat letters
    int i, j, increment; // Counter variables

    while(--argc != 0) // While we have words from program parameters
    {
        for(j = i = 0; argv[argc][i] != '\0'; j = ++i) // Iterate through each letter until end of word
        {
            for(increment = 0; j > 0; j--) // Iterative backwards through each letter
            {
                if(argv[argc][i] == argv[argc][j])
                {
                    increment++;
                }
            }
            if(increment > count) // New greatest lettered word
            {
                word = argc;
                count = increment;
            }
        }
    }

    if(word == 0)
    {
        puts("-1");
    }
    else
    {
        puts(argv[word]);
    }

    return 0;
}

```
> 7 votes

# Answer
# Pyth, 14 bytes

```
eoeS/LNN+czd_1

```

Demonstration. Test harness.

```
eoeS/LNN+czd_1
                  Implicit: z = input(), d = ' '
         czd      chop z on delimeter d.
        +   _1    Add an -1 to the end of the list.
 o                Order the list by
  eS              the maximum of
    /LN           the occurence count in the word
       N          of letters in the word.
                  (If we are mapping over -1, this will give -1/-1 = 1)
                  Since Python's sort is stable, this will leave -1 at the end if
                  all words have maximum repetition count 1.
e                 Take the final element of the resulting list and print it.

```
> 4 votes

# Answer
# K, 35 bytes (missing -1 requirement, just noticed, but time to sleep)

```
{1#w[>{|/{#:&:x=y}[x]'x}'w:" "\:x]}

```

### how it works:

1 take

```
1#

```

of the words indexed by

```
w[

```

the indices to put in ascending order

```
>

```

the maximum

```
|/

```

count where

```
#:&:

```

string = char

```
x=y

```

for each char in word

```
'x

```

for each word where `w` (words) are

```
'w:

```

the string split by spaces

```
\:x

```

Obviously I sacrificed a bit of precision for expressiveness and legibility in the English explanation. I hope it was interesting.
> 3 votes

# Answer
# Haskell, 100 bytes

```
import Data.List
f=g.last.sort.map((,)=<<last.sort.map length.group.sort).words
g(1,_)="-1"
g(_,w)=w

```

Usage example: `f "Today, is the greatest day ever!"` -\> `"greatest"`

How it works:

```
                                                words  -- split input at spaces into list of words
          map(                                 )       -- for each word
              (,)=<<                                   -- build a pair, where the second element is the word itself
                                                       -- and the first element is made by
                                           sort        -- sort the letters
                                      group            -- group equal letters
                            map length                 -- take length of each group
                        sort                           -- sort the lengths
                    last                               -- take the last
                                                       -- now we have a list of (l,w) pairs where l is how often the most frequent letter occurs for word w
     sort                                              -- sort the list
 last                                                  -- take last element
g                                                      -- call g which checks the "-1" case

```

## Haskell, ~~79~~ 77 bytes (untested)

```
import Data.List
last.sortOn(last.sort.map length.group.sort).words.(++" -1")

```

This uses `sortOn` from `Data.List` v4.8.0.0, which I don't have installed, so I cannot test it.
> 2 votes

# Answer
# Python 2, ~~97~~ 77 Bytes

Fairly straightforward solution, just maps the input (surrounded by quotes) to a tuple containing the word and the number of repeated characters. Gets the maximum, and prints out the word if the most repeated letter is repeated at all, otherwise it prints -1.

I saved 20(!) bytes by rearranging the order of input so that I didn't need a key for finding the max.

```
j=max((max(map(x.count,x)),x)for x in input().split())
print[-1,j[1]][j[0]>1]

```
> 2 votes

# Answer
# CJam, 25 bytes

```
lS/{_$e`$W=0=(\}%2/$W=~W?

```

Try it online

Explanation:

```
lS/   Get input and split at spaces.
{     Start of loop over all words.
  _     Copy, need to keep original word.
  $     Sort letters.
  e`    RLE.
  $     Sort RLE result. Sort is increasing by count.
  W=    Get last count/letter pair, which corresponds to largest count.
  0=    Extract count from pair.
  (     Decrement count, so that it has a falsy value when the count is 1.
  \     Swap count and word, so that we can sort the pairs by count.
}%    End of loop over words.
2/    Split list into pairs, which are the count/word pairs.
$     Sort the pairs.
W=    Get last one, which is the largest count.
~     Unwrap the pair.
W?    Output word if count is truthy, -1 otherwise.

```
> 2 votes

# Answer
# SWI-Prolog, ~~158~~ ~~154~~ 149 bytes

```
a(A,R):-split_string(A," ","",B),findall(X:Z,(member(Z,B),string_codes(Z,D),length(D,L),sort(D,E),length(E,M),X is M-L,X<0),S),sort(S,[_:R|_]);R= -1.

```

Example: `a("Today, is the greatest day ever!",R).` outputs `R = "greatest" .`.
> 1 votes

# Answer
# JavaScript, ~~86~~ ~~111~~ 108 bytes

```
s=>(l=(x=s.split` `,r=x.map(l=>(/(.)\1+/.exec(l)||[''])[0].length),x)[r.indexOf(k=Math.max(...r))],k<2?-1:l)

```

Definitely golf-able, the whole -1 thing added about 20 bytes.
> 1 votes

# Answer
# R, 107 bytes

```
w=scan(,"");l=sapply(w,function(x)max(table(strsplit(x,"")[[1]])));cat(ifelse(max(l)>1,w[which.max(l)],-1))

```

This reads from STDIN and prints to STDOUT.

Ungolfed + explanation:

```
# Read a string and split it into a vector on spaces
w <- scan(, "")

# Get the maximum number of letter repeats in each element of w
l <- sapply(w, function(x) max(table(strsplit(x, "")[[1]])))

# If the largest number in l is 1, print -1, otherwise get the word
cat(ifelse(max(l) > 1, w[which.max(l)], -1)

```
> 1 votes

# Answer
# C# 166 Bytes

```
string a(string i){var z=i.Split(' ');int g=1,c=0;var m="-1";foreach(var w in z)foreach(var l in w.Distinct()){c=w.Where(x=>x==l).Count();if(c>g){g=c;m=w;}}return m;}

```

Straightforward coding. Nothing Special in here.

C# sucks for code golfing :-/
> 1 votes

# Answer
# JavaScript (*ES7?*), 99

Using array comprehension, that is implemented in Firefox but no more included in EcmaScript 6.

Test using the snippet below (Firefox only)

```
f=s=>s.split(' ').map(w=>[for(c of(l=[m=0],w))(n=l[c]=-~l[c])>m?m=n:0]&&m>x&&(x=m,v=w),x=1,v=-1)&&v

// TEST
out=x=>O.innerHTML+=x+'\n';

test=x=>out(x+' -> '+f(x))

;["aaabbb cccc","This is a great day","Today, is the greatest  day ever a!"]
.forEach(t=>test(t));
```

```
<pre id=O></pre>
Try:<input id=I><button onclick='test(I.value),I.value=""'>-></button>
```

**Ungolfed** And more compatible

```
function f(s)
{
  v = -1;
  x = 1;
  s.split(' ')
  .forEach(function(w){
    l=[];
    m=0;
    w.split('').forEach(function(c){
      n=l[c]=-~l[c];
      if (n>m) m=n;
    })
    if (m>x) x=m,v=w;
  })
  return v;
}

// TEST
out=function(x) { O.innerHTML+=x+'\n' }

test=function(x) { out(x+' -> '+f(x)) }

;["aaabbb cccc","This is a great day","Today, is the greatest  day ever a!"]
.forEach(function(t) { test(t)} );
```

```
<pre id=O></pre>
Try:<input id=I><button onclick='test(I.value),I.value=""'>-></button>
```
> 1 votes

# Answer
## C (167)

```
double m,k,n=k=2,*O,V[256];char*f(char*c,char*s){return*c?((*O=!((n+=!(*c*=*c!=32))>1.1/modf(*(O=V+*c),&m))*m+1/n+1)>k)?f(c+!!(k=*O),c):f(c+1,s):s?!*s?s+1:f(c,s-1):0;}

```

TRY IT

**HOW DOES THIS WORK?**

* the function is inner recursive one inside another recursive function, the insider function retrieves the beginning of a string where an inclusive character is returned by first function.
* maximum number is given by hashing characters over an ascii table.
> 1 votes

# Answer
# Pure Bash (no external commands) 129 bytes

This is quite long, but still compares favourably with some of the other longer entries.

```
m=1
w=-1
for b;{
declare -A a
for((i=0;i<${#b};i++));{
c=${b:$i:1}
let a[$c]++
d=${a[$c]}
((d>m))&&w=$b&&m=$d
}
unset a
}
echo $w

```

I'm not entirely happy with some of the constucts, having to use that inner for loop is annoying. Any suggestions?
> 1 votes

# Answer
# Python, 58

```
max('-1',*input().split(),key=lambda w:len(w)-len(set(w)))

```
> 1 votes

# Answer
# Q (44 bytes)

```
{w l?0|/l:{max(#:)'[(=)x]}'[w:" "vs"-1 ",x]}

```

### ungolfed

```
{
    words:" " vs "-1 ",x;
    counts:{max count each group x} each words;
    : words counts ? max counts;
}

```
> 1 votes

# Answer
**Haskell 96 Bytes**

---

```
r o=(last.sort.map length$(group.sort)o,o)
w p=n$maximum(map(r)(words p))
n (1,_)="-1"
n (_,w)=w

```

\`\`\`

---

`r` is a function that takes a word and return a tuple `(n,w)` where `n` is the number of occurrence of the most occurring char in the word `w`. For instance let `x="norep", y="dnredundant"`, then `r x=(1,norep), r y=(3,ndredundant)`

`w` is a function that takes a string containing a number of space-separated words and:

1. Split the list on space `words p`
2. foreach word create a list of `(n,w)`
3. take the tuple that has the greatest `n` (occurrence counter)
4. If it has n equals to 1 simply return the string `-1`, the word itself (stored in the second component of the tuple) otherwise.

For instance take `p="Today, is the greatest day ever!"`

1. produces `["Today,","is","the","greatest","day","ever!"]`
2. `[(1,"Today,"),(1,"is"),(1,"the"),(2,"greatest"),(1,"day"),(2,"ever!")]`
3. (2,"greatest")
4. 2 != 1 then `greatest` is the solution!
> 1 votes

---
Tags: code-golf, word
---


title: Build an Authenticating SMTP Client

text:
# Question
Title: Build an Authenticating SMTP Client
The basic parts of SMTP can be implemented in surprising little code. I was able to build an example SMTP client that works with Gmail and Amazon SES in about 320 characters using PHP.

Your task is to implement an SMTP client that can send UTF-8 email from at least 2 major providers listed here:

* Gmail
* Yahoo!
* Live/Hotmail
* Postmark
* Amazon SES

Keep in mind that most require SSL support. Some SMTP services (like Amazon) require different SMTP Auth and From addresses. Your function can take input for the actual data transmitted. After all, it woudn't make sense to hard-code anything into the transport layer.

* SMTP User
* SMTP Password
* SMTP Host
* SMTP Port
* DATA (message)
* From email
* To email

Sample DATA (message)

```
Subject: =?UTF-8?B?VGVzdCBFbWFpbA==?=\r\n
To: <him@gmail.com>\r\n
From: <you@gmail.com>\r\n
MIME-Version: 1.0\r\n
Content-Type: text/html; charset=utf-8\r\n
Content-Transfer-Encoding: base64\r\n\r\n
PGgxPlRlc3QgRW1haWw8L2gxPjxwPkhlbGxvIFRoZXJlITwvcD4=\r\n.

```

### In Summary

1. Build an SMTP client that can send email through at least two of the services above.
2. Accepts the seven inputs needed to form a valid SMTP Auth request (above). (Might only need six inputs if you combine the "From" and "SMTP User" inputs).
3. Use as few characters as posible.

# Answer
# Python 3 864 bytes

Extremely quick and dirty. Works with AWS SES and Yahoo!. Could not get it to work with Postmark (requires STARTTLS) or Gmail (requires further authentication outside of the SMTP connection).

```
import socket,ssl
from base64 import*
N=b'\x00'
U='utf-8'
E=lambda s:s.encode(U)
D=lambda b:b.decode(U)
B=lambda s:D(b64encode(E(s)))
A=lambda f,t,j,b:E('\r\n'.join(['DATA','Subject: =?UTF-8?B?{}?=','To: <{}>','From: <{}>','MIME-Version: 1.0','Content-Type: text/html; charset=utf-8','Content-Transfer-Encoding: base64',B(b),'','.','']).format(B(j),t,f,b))
X=lambda s,e:s.startswith(e)
def S(h,u,p,t,f,j,b):
    c,F,W=ssl.wrap_socket(socket.create_connection((h,465))),lambda m:E(m if'amazonaws'in h else'<'+m+'>'),lambda m:c.write(m+b'\r\n')
    def R(d,o=[]):
        x,y=c.read(),str(d)
        if not(X(x,E(y))or filter(lambda i:X(i,X(x,E(y))),o)):raise RuntimeError(y+' '+repr(x))
    R(220);W(b'EHLO x');R(250);W(b'AUTH PLAIN '+b64encode(N+E(u)+N+E(p)));R(235);W(b'MAIL FROM: '+F(f));R(250);W(b'RCPT TO: '+F(t));R(250);W(A(f,t,j,b));R(250,(354,));W(b'QUIT')

```

Invoke like `S(hostname, username, password, to, from_, subject, body)`

Expect bugs and changes (kind of got bored so it feels slightly half-baked).
> 2 votes

# Answer
C# .NET, assuming all the proper namespaces have been imported and not counting newlines/whitespace as characters. Also, displays no output as it's used as a library function.

```
bool sm(string h, string u, string p, string r, string m) {
    try {
        SmtpClient smtp = new SmtpClient();
        smtp.Port = 587;
        smtp.Host = h;
        smtp.Credentials = new NetworkCredential(u, p);
        smtp.UseSsl = true;
        smtp.Send(u, r, "", m);
        return true;
    } catch {
        return false;
    }
}

```

In its compressed form, the way I would code it, it'd look like this:

```
bool sm(string h, string u, string p, string r, string m) { try { SmtpClient smtp = new SmtpClient(); smtp.Port = 587; smtp.Host = h; smtp.Credentials = new NetworkCredential(u, p); smtp.UseSsl = true; smtp.Send(u, r, "", m); return true; } catch { return false; } }

```

Call it cheating, because of using .NET, but 266 characters. Works with major providers that allow SMTP with STARTTLS authentication on port 587. I use this for my Gmail all the time, works with Windows Live Hotmail too. Can be used either client-side OR server-side, and requires .NET 2.0 or newer (so it's compatible with pretty much every Windows machine).
> -3 votes

---
Tags: code-golf
---


title: 2048 Bot Challenge

text:
# Question
Title: 2048 Bot Challenge
We have been cloning 2048, analyzing 2048, but why haven't we played it yet? Write a 555 byte javascript snippet to play 2048 automatically, the best score after an hour will count (see scoring below).

# Setup:

Goto 2048 and run:

```
 a = new GameManager(4, KeyboardInputManager, HTMLActuator, LocalStorageManager);

```

`a` is the object to control the game.

# Rules:

After setup you may run 555 bytes of javascript from the console to control the game. The source code of the game can be found here (including comments).

* It may only do things which are possible for the user:
    + `a.move(n)` to trigger a key action in any of the 4 directions.
        - 0: up, 1: right, 2: down, 3: left
    + `a.restart()` to restart the game. Restarting is allowed in the middle of the game.
* Information about the state of the game can be found in `a.grid.cells`. This information is read-only
* Hooking into any of the functions is allowed, altering their behaviour in any way is not (or changing any other data)
* Moving is allowed only once every 250ms

# Example

Just a very simple example to start from. Without comments and enters **181 bytes**.

```
//bind into new tile function and change m(ove) variable when a tile was moved
b = a.addRandomTile.bind(a);
m = !1;
a.addRandomTile = function() { m = !0; b(); };
//number of move fails
mfs = 0;
setInterval(function() {
  //set global moved tracking variable to false
  m = !1;
  a.move(Math.floor(4 * Math.random()));
  m || mfs++;
  //restart after 10 moves failed
  10 < mfs && (mfs = 0, a.restart());
}, 250);

```

# Scoring and results

I will be running the snippets for one hour straight and the best score will count. Indeed there is a chance that `randombot` above will win that way, but 1 hour should be enough to beat it:

* **King** `Bottomstacker VII`: **9912**
* *Queen* `Bottomstacker V`: **9216**
* *Prince* `Bottomstacker II`: **7520**
* *Lord* `Bottom and Right`: **6308**
* *Peasant* `Randombot`: **1413**
* ~~`Bottomstacker IV`: **12320**~~ *Disqualified for making two moves in one interval (within 250ms)*

# FAQ

* Why is this challenge not language agnostic through the terminal?
    + For the simple reason that it is more fun like this. Watching a game play itself graphically is simply a lot more mesmerizing than seeing a console spit out numbers. Even knowing no javascript you should be able to join into this challenge as it isn't about language features primarily (just use this tool to minimize the code)

# Answer
> 4 votes
I can't code javascript, so I stole your answer.

```
//bind into new tile function and change m(ove) variable when a tile was moved
b = a.addRandomTile.bind(a);
m = !1;
a.addRandomTile = function() { m = !0; b(); };
//number of move fails
mfs = 0;
c=1;
setInterval(function() {
  //set global moved tracking variable to false
  m = !1;
  a.move(c)
  c++
  if (c>3) {c=1}
  m || mfs++;
  //restart after 10 moves failed
  10 < mfs && (mfs = 0, a.restart());
}, 250);

```

It uses the strategy I also use.

EDIT: Nice, it just beat your score after about 5 minutes on my machine :D

EDIT: Forgot to move down twice instead of just once, this is the code you should use:

```
a = new GameManager(4, KeyboardInputManager, HTMLActuator, LocalStorageManager);
//bind into new tile function and change m(ove) variable when a tile was moved
b = a.addRandomTile.bind(a);
m = !1;
a.addRandomTile = function() { m = !0; b(); };
//number of move fails
mfs = 0;
c=1;
setInterval(function() {
  //set global moved tracking variable to false
  m = !1;
  if (c<=3) {n=c}
  else {n=2}
  a.move(n)
  c++

  if (c>4) {c=1}
  m || mfs++;
  //restart after 10 moves failed
  10 < mfs && (mfs = 0, a.restart());
}, 250);

```

Also, there's a bug in it that it restarts when it's not needed, but I'm not sure how to fix this. EDIT: It currently has a highscore of 3116 (after 3 minutes). I think it's safe to say this algoritm is better than just doing random moves.

EDIT Newer version:

```
a = new GameManager(4, KeyboardInputManager, HTMLActuator, LocalStorageManager);
//bind into new tile function and change m(ove) variable when a tile was moved
b = a.addRandomTile.bind(a);
m = !1;
a.addRandomTile = function() { m = !0; mfs=0; b(); };
//number of move fails
mfs = 0;
c=1;
setInterval(function() {
  //set global moved tracking variable to false
  m = !1;
  if (c<=3) {n=c}
  else {n=2}
  a.move(n)
  c++
  if (c>4) {c=1}
  m || mfs++;
  //up after 5 moves
  5 < mfs && (a.move(0));
  //restart after 10 moves failed
  10 < mfs && (mfs = 0, a.restart());
}, 250);

```

EDIT: Another new version, this one moves down directly after moving up.

```
a = new GameManager(4, KeyboardInputManager, HTMLActuator, LocalStorageManager);
//bind into new tile function and change m(ove) variable when a tile was moved
b = a.addRandomTile.bind(a);
m = !1;
a.addRandomTile = function() { m = !0; mfs=0; b(); };
//number of move fails
mfs = 0;
c=1;
setInterval(function() {
  //set global moved tracking variable to false
  m = !1;
  if (c<=3) {n=c}
  else {n=2}
  a.move(n)
  c++
  if (c>4) {c=1}
  m || mfs++;
  //up after 5 moves
  5 < mfs && (a.move(0), c=4);
  //restart after 10 moves failed
  10 < mfs && (mfs = 0, a.restart());
}, 250);

```

EDIT: Update: it just broke my personal record with a pretty crazy score of 12596.

EDIT: Hey, I'm bottomstacker :D Also:

```
b=a.addRandomTile.bind(a);m=!1;a.addRandomTile=function(){m=!0;mfs=0;b()};mfs=0;c=1;setInterval(function(){m=!1;n=3>=c?c:2;a.move(n);c++;4<c&&(c=1);m||mfs++;5<mfs&&(a.move(0),c=4);10<mfs&&(mfs=0,a.restart())},250);

```

(Not actually a change, just compressed.)

5th time's a charm? Not sure. Anyways:

```
//bind into new tile function and change m(ove) variable when a tile was moved
b = a.addRandomTile.bind(a);
m = !1;
a.addRandomTile = function() { m = !0; mfs=0; b(); };
//number of move fails
mfs = 0;
c=1;
setInterval(function() {
  //set global moved tracking variable to false
  m = !1;
  if (c<=3) {n=c}
  else {n=2}
  a.move(n)
  c++
  if (c>4) {c=1}
  if (c==0) {c=4}
  m || mfs++;
  //up after 5 moves
  5 < mfs && (c=0);
  //restart after 10 moves failed
  10 < mfs && (mfs = 0, a.restart());
}, 250);

```

and:

```
b=a.addRandomTile.bind(a);m=!1;a.addRandomTile=function(){m=!0;mfs=0;b()};mfs=0;c=1;setInterval(function(){m=!1;n=3>=c?c:2;a.move(n);c++;4<c&&(c=1);0==c&&(c=4);m||mfs++;5<mfs&&(c=0);10<mfs&&(mfs=0,a.restart())},250);

```

Another new version:

```
a = new GameManager(4, KeyboardInputManager, HTMLActuator, LocalStorageManager);
//bind into new tile function and change m(ove) variable when a tile was moved
b = a.addRandomTile.bind(a);
m = !1;
a.addRandomTile = function() { m = !0; mfs=0; b(); };
//number of move fails
mfs = 0;
c=1;
setInterval(function() {
  //set global moved tracking variable to false
  m = !1;
  if (c<=3) {n=c}
  else {n=2}
  a.move(n)
  c++
  if (c>4) {c=1}
  if (c==0) {c=4}
  m || mfs++;
  //up after 5 moves
  5 < mfs && (c=0);
  //Found this in the source, as the criteria for a gameover. Might as well reset then ;)
  if (!a.movesAvailable()) {
      a.restart()
  }

}, 250);

```

and:

```
a=new GameManager(4,KeyboardInputManager,HTMLActuator,LocalStorageManager);b=a.addRandomTile.bind(a);m=!1;a.addRandomTile=function(){m=!0;mfs=0;b()};mfs=0;c=1;setInterval(function(){m=!1;n=3>=c?c:2;a.move(n);c++;4<c&&(c=1);0==c&&(c=4);m||mfs++;5<mfs&&(c=0);a.movesAvailable()||a.restart()},250);

```

(I hope it's not too much of a problem that this continues behind the gameover screen? I think you could add an `a.over=0` somewhere that gets executed often. I'll figure it out someday.)

EDIT (again): I dropped the standard gameover way and reverted to the old way of doing things. I'm now testing out an addition that'll always merge if there are 2 tiles of 16 or more together:

```
a = new GameManager(4, KeyboardInputManager, HTMLActuator, LocalStorageManager);
b = a.addRandomTile.bind(a);
m = !1;
a.addRandomTile = function() {
  m = !0;
  mfs = 0;
  b();
};
mfs = 0;
c = 1;
setInterval(function() {
  m = !1;
  l = 8;
  for (x = 0;x < 4;x++) {
    for (y = 0;y < 4;y++) {
      t1 = a.grid.cellContent({x:x, y:y});
      t2 = a.grid.cellContent({x:x, y:y + 1});
      t3 = a.grid.cellContent({x:x + 1, y:y + 1});
      if (t1 & t2) {
        if (t1.value == t2.value) {
          if (t1.value > l) {
            l = t1.value;
            c = 2;
          }
        }
        if (t1 & t3) {
          if (t1.value == t2.value) {
            if (t1.value > l) {
              l = t1.value;
            }
          }
        }
      }
    }
  }
  if (c <= 3) {
    n = c;
  } else {
    n = 2;
  }
  a.move(n);
  c++;
  if (c > 4) {
    c = 1;
  }
  if (c == 0) {
    c = 4;
  }
  m || mfs++;
  5 < mfs && (c = 0);
  10 < mfs && (mfs = 0, a.restart());
}, 250);

```

# Answer
> 3 votes
# Right and Down bot: 345 bytes

Short version

```
b=a.addRandomTile.bind(a);m=!1;t=250;d=!0;a.addRandomTile=function(){m=!0;b();d&&setTimeout(c,t)};c=function(){d=!1;a.move(2);setTimeout(function(){m=!1;d=!0;a.move(1);m||setTimeout(function(){a.move(0);m?a.grid.cells[3][0]&&a.grid.cells[3][3]&&setTimeout(function(){a.move(1)},t):setTimeout(function(){a.move(3);m||a.restart()},t)},t)},t)};c();

```

Long version

```
a = new GameManager(4, KeyboardInputManager, HTMLActuator, LocalStorageManager);
b = a.addRandomTile.bind(a);
m = !1;
t = 250;
d = !0;
a.addRandomTile = function() {
  m = !0;
  b();
  d && setTimeout(c, t);
};
c = function() {
  d = !1;
  a.move(2);
  setTimeout(function() {
    m = !1;
    d = !0;
    a.move(1);
    m || setTimeout(function() {
      a.move(0);
      m ? a.grid.cells[3][0] && a.grid.cells[3][3] && setTimeout(function() {
        a.move(1);
      }, t) : setTimeout(function() {
        a.move(3);
        m || a.restart();
      }, t);
    }, t);
  }, t);
};
c();

```

# In words

Move down, then right, if you can't move, move up (or if you can't, move left), if both the top right and bottom right corner is filled, move right otherwise start over.

# Current highscore

My own best score was 7668, but that was run at far greater speed than `t=250` (and thus indirectly longer than an hour).

# Answer
> 3 votes
Somehow I ran across this older contest this morning, and since I love 2048, I love AI, and JS is one of the few languages I currently know well, I figured I'd give it a shot.

# GreedyBot (~~607~~ 536 bytes)

Short version:

```
C=function(x,y){return a.grid.cellContent({x:x,y:y})},h=[[1,3,2,0],[2,1,3,0]],V='value',A='addRandomTile';a=new GameManager(4,KeyboardInputManager,HTMLActuator,LocalStorageManager);b=a[A].bind(a);m=!1;f=d=X=Y=0;a[A]=function(){m=!0;f=0;b()};setInterval(function(){m=!1;for(var c=X=Y=0;4>c;c++)for(var e=0;4>e;e++)if(u=C(c,e),!!u){for(q=e+1;4>q;){v=C(c,q);if(!!v){u[V]==v[V]&&(Y+=u[V]);break}q++}for(q=c+1;4>q;){v=C(q,e);if(!!v){u[V]==v[V]&&(X+=u[V]);break}q++}}f<4&&a.move(h[X>Y+4?0:1][f]);m&&(f=0);m||f++;15<f&&(f=0,a.restart())},250);

```

Long version (outdated):

```
a = new GameManager(4, KeyboardInputManager, HTMLActuator,    LocalStorageManager);
b = a.addRandomTile.bind(a);
m = !1;
f = d = X = Y = 0;
a.addRandomTile = function() { m = !0; f = 0; b(); };
setInterval(function() {
    m = !1;
    X = Y = 0;

    for(var x=0;x<4;x++) {
        for(var y=0;y<4;y++) {
            u = a.grid.cellContent({x:x, y:y});
            if(u==null){continue;}
            q = y+1;
            while(q < 4) {
                v = a.grid.cellContent({x:x,y:q});
                if(v!=null){
                    if(u.value==v.value){
                        Y+=u.value;
                    }
                    break;
                }
                q++;
            }
            q = x+1;
            while(q < 4) {
                v = a.grid.cellContent({x:q,y:y});
                if(v!=null){
                    if(u.value==v.value){
                        X+=u.value;
                    }
                    break;
                }
                q++;
            }
        }
    }

    if(X>=Y){
        if(f==0)
            a.move(1);
        else if(f==1)
            a.move(3);
        else if(f==2)
            a.move(2);
        else if(f==3)
            a.move(0);
    } else {
        if(f==0)
            a.move(2);
        else if(f==1)
            a.move(0);
        else if(f==2)
            a.move(1);
        else if(f==3)
            a.move(3);
    }
    if(m)f=0;
    m || f++;
    if(15 < f) f=0,a.restart();
}, 250);

```

The longer version was not golfed at all (other than shrinking variable names), so it could be shortened quite a bit while still being readable. The shorter version was created using Closure Compiler (thanks for the link!), which ended up at 650. With some custom modifications on my part, I was able to shave off another ~~43~~ 114 bits.

Basically, it searches for through the grid for possible moves, and whenever it finds one, adds its value to either the horizontal or vertical total. After searching through every possible move, it determines which direction it should move, based on if the H or V total is higher, and the directions it has already tried. Right and Down are the first choices.

Looking back at this, I realize now that if either total is non-zero, the first attempt at sliding the tiles in that direction is guaranteed to succeed. Perhaps I could simplify the move-deciding section towards the end based on this.

I left this program running for an hour and ended up with a high score of `6080`. However, in one of the trial runs (pre-minification), it managed a high score of `6492`, only 128 behind my personal best of `6620`. Its logic could be greatly improved by having it move left-down occasionally, as the numbers tend to pile up like this:

```
 2  4  8 16
 4  8 16 32
 8 16 32 64
16 32 64 128

```

(**EDIT:** I left it running a while longer, and it managed some `7532` points. Darn, my program is smarter than me....)

One more interesting tidbit: in one of my glitched attempts at creating something useable, somehow it ended up so that anytime *any* two tiles were in the same row or column, they were combined. This led to interesting developments as the random 2s or 4s would repeatedly combine with the highest tile, doubling it every time. One time, it somehow managed to score over 11,000 in 15 seconds before I shut it off.... XD

Any suggestions for improvement are very welcome!

# Answer
> 1 votes
# Windshield Wipers: 454 bytes

Simply goes Right, Up, Left, Up... repeating (just like the wipers on a car) unless it gets jammed. If it gets jammed, it will attempt to turn off the wipers and turn them back on. Highest score I got in an hour was 12,156 -- However, most of the scores are somewhere between 3k - 7k.

It will output the score into the console after every attempt.

```
var move = !1;
var bad = 0;
var c = 0;
var b = a.addRandomTile.bind(a);
a.addRandomTile = function() {
    b();
    move=!0;
    bad=0;
}
setInterval(function() {
    if (!move) bad++;
    if (c>3) c=0;
    move = !1;
    if (c==3) {a.move(0);c++;}
    if (c==2) {a.move(3);c++;}
    if (c==1) {a.move(0);c++;}
    if (c==0) {a.move(1);c++;}
    if (bad>10) {a.move(2);}
    if (!a.movesAvailable()) {console.log("Score: "+a.score);a.restart();}
}, 250);

```

# Answer
> 0 votes
# UpAndLeftBot

As title suggests, moves up & left by stealing David Mulder's work & swapping some numbers (I don't know jack about Javascript, so best I can do is this).

```
a = new GameManager(4, KeyboardInputManager, HTMLActuator, LocalStorageManager);
b = a.addRandomTile.bind(a);
m = !1;
t = 250;
d = !0;
a.addRandomTile = function() {
  m = !0;
  b();
  d && setTimeout(c, t);
};
c = function() {
  d = !1;
  a.move(0); // a.move(2)
  setTimeout(function() {
    m = !1;
    d = !0;
    a.move(3); // a.move(1)
    m || setTimeout(function() {
      a.move(2);  //a.move(0)
      m ? a.grid.cells[3][0] && a.grid.cells[3][3] && setTimeout(function() {
        a.move(3); // a.move(1)
      }, t) : setTimeout(function() {
        a.move(1);  // a.move(3)
        m || a.restart();
      }, t);
    }, t);
  }, t);
};
c();

```

---
Tags: code-challenge, game, javascript, ai-player, sliding-puzzle
---