title: Has my milk expired?

text:
# Question
Title: Has my milk expired?
*Aww, man, this expiry date doesn't write the months with letters! I can't tell if it's expiring on March 10th or October 3rd... Wait, no, never mind, the year says 2012. **(alley-oops half-used brick of cheese into the trash can like a pro)***

So let's suppose for a moment that you're too busy to try to reason out when this jar of marinara is supposed to expire. You just want the Cliff Notes version: how likely is it that it's past due? Let's write some code!

You know that the manufacturers print the date as an ordered triple of integers, in one of three formats:

```
YEAR  MONTH DAY
MONTH DAY   YEAR
DAY   MONTH YEAR

```

And you know that some dates can only be interpreted in one or two ways, not all three: the 55 in `55-11-5` has to be a year, meaning this particular box of Twinkies expired November 5th, 1955. The year is sometimes given in four digits and not two, which can rule out some options. When it's two digits, though, 50..99 means 1950..1999 and 0..49 means 2000..2049.

Your job is to write a program or function that takes an array of integers which is a valid date in at least one of the interpretations above, and outputs a percent chance it is still good. The percent chance is simply the percentage of valid interpretations of the date that are **on or later** than today's date.

The array of integers will be your language's `[Int]` type of length three if it is an argument to a function, and given as either dash-, slash-, or space-separated (you get to pick) integers if used as input on STDIN to a full program.\*

"Today's date" can be today's actual date, as obtained through a date function, or the date given in an extra argument to function or extra paramater in STDIN. It may be in Unix epoch seconds, another year-month-day triple entered in one of the three ways above, or another more convenient fashion.

Let's have some examples! The expiry date input will be in the dash-separated style, and assume for the examples below that today's date is July 5th, 2006.

* `14-12-14` \- Both valid interpretations for this (DMY and YMD) are equivalent, December 14, 2014. The output is **100** because this product is definitely still good.
* `8-2-2006` \- The last number is a year, for sure, since it has four digits. This could be either February 8th (expired) or August 2nd (still good). The output is **50**.
* `6-7-5` \- This could be anything! The "July 5th, 2006" interpretation is still good (for one day only), but the remaining two are both in 2005 and should be tossed as quickly as possible. The output is **33**.
* `6-5-7` \- Here, two out of three interpretations are safe. You can round your decimal up or down, so **66** or **67** are both okay.
* `12-31-99` \- Okay, this one is unambiguously from the turn of the century (years from 50 to 99 are 19XX, and 31 can't possibly be a month). A big fat **0**, and you really should clean out your fridge more often.

You can safely assume that any input which does not meet the standards above is not privy to the output rules above.

No web requests or standard loopholes. Date handling libraries are allowed. This is code golf: may the shortest program win.

* If you are using brainfuck or some similarly datatype-handicapped language, you can assume the ASCII values of the first three characters in input are the integers for the date. This excludes the four-digit year logic, sure, but I think we would be too astounded by seeing a solution to this in Brainfuck to slight you for it.

# Answer
# k4 ~~(90)~~ ~~(88)~~ ~~(87)~~ (82)

```
{100*(+/~d<x)%3-+/^d:{"D"$"."/:$|z,y,x+(x<100)*100*19+x<50}.'y@/:3 3#.:'$21020101}

```

Invoke with `x` of `.z.D` (a builtin) for comparison to today, or a date literal of your choice otherwise:

```
  f:{100*(+/~d<x)%3-+/^d:{"D"$"."/:$|z,y,x+(x<100)*100*19+x<50}.'y@/:3 3#.:'$21020101}
  .z.D f'(14 12 14;8 2 2006;6 7 5;6 5 7;12 31 99)
100 0 0 0 0f
  2006.07.05 f'(14 12 14;8 2 2006;6 7 5;6 5 7;12 31 99)
100 50 33.33333 66.66667 0

```

This is basically a port of @Alex-l's Python solution, with a few miscellaneous golfing tricks added:

* The rearrangement instructions are encoded in a string to save a couple characters.
* The conditional logic (ab)uses truth-as-integer (but in a different way from the Python solution).
* The validity test is slightly different--k4/q will happily parse any string into any datatype; it simply returns a null if it can't make sense of it. Thus, I return a list of dates from the inner function, which may or may not be null.
* The final result comes from checking how many of the possible date interpretations are null vs. how many are less than the comparison date; it's important here that the null date is considered less than any other date.
> 5 votes

# Answer
## Ruby, 115 characters

```
f=->a,t{[a,a.rotate(~s=r=0),a.reverse].map{|x,*y|(t>Time.gm(x<100?x+2e3-100*x/=50:x,*y)||r+=100
s+=1)rescue p}
r/s}

```

This defines a function `f` that takes two arguments: an array containing the input, and "today's" date.

Examples:

```
f[[14,12,14], Time.new]
100
f[[8,2,2006], Time.new]
0
f[[8,2,2006], Time.new(2006, 7, 5)]
50
f[[6,7,5], Time.new(2006, 7, 5)]
33

```
> 15 votes

# Answer
# Python 2.7 - 172

I use the datetime module for validity and comparison of dates. If `date` can't make a valid datetime out of the input, it raises `ValueError`. This way `s` is the sum of the non-expired dates and `t` is the total number of valid dates. I'm taking advantage of the fact that `True == 1` for the purposes of addition and indexing in Python. I also save a character by using 25\*(76,80) instead of (1900,2000).

Note the lines in the second level of indentation use a tab character, not 2 spaces.

```
def f(e,c,s=0,t=3):
 for Y,M,D in(0,1,2),(2,0,1),(2,1,0):
  y=e[Y]
  try:s+=date(y+25*[[76,80][y<50],0][y>99],e[M],e[D])>=c
  except:t-=1
 return 100*s/t

```

Add this to the end to test:

```
examples = [[14,12,14],[8,2,2006],[6,7,5],[6,5,7],[12,31,99]]
for e in examples:
 print f(e, date(2006,7,5))

```
> 13 votes

# Answer
## PowerShell, ~~183~~ ~~173~~ 168

```
[int](100*(($d=@(($a,$b,$c=$args[0]),($c,$a,$b),($c,$b,$a)|%{$_[0]+=1900*($_[0]-le99)+100*($_[0]-le49)
.{date($_-join'-')}2>$x}|sort -u))-ge(date)+'-1').Count/$d.Count)

```
* Input as `int[]` via parameter, e.g.

```
  PS> ./milk.ps1 5,6,7

```
* Error messages are silenced via `try`/`catch`, as long as I don't know whether output on stderr is allowed or not.
* Using `+"-1"` on the date, which gets interpreted as `.AddDays(-1)` to shift the current date by one day, so that we can compare to yesterday (instead of just today). This solves the problem that we get a date with 0:00 as time but need to compare with a date with time from today.
* Heavily inlined by now
* Using a new trick for silencing errors that's quite a bit shorter
> 10 votes

# Answer
## R, 269

I was expecting this to be easy in R, but the single-digit years were a pretty big curveball. I feel like this could be much better than it is.

`lubridate` is a package from CRAN, you might need to install it with `install.packages("lubridate")`.

```
require(lubridate)
f = function(d){
d=sapply(d,function(l)if(nchar(l)==1)sprintf("%02d",l)else l)
d=paste0(d,collapse="-")
t=ymd(Sys.Date())
s=na.omit(c(ymd(d),mdy(d),dmy(d)))
s=lapply(s,function(d){
if(year(d)>2049){year(d)=year(d)-100;d}
else d})
sum(s>t)/length(s)}

```

Usage: `f(c(d1,d2,d3))` where `c(d1,d2,d3)` is a vector of integers.

e.g. `f(c(6,10,14))` returns `0.3333333`.

The `lubridate` package has a series of wrapper functions for parsing dates in different orders. I use these to see which formats produce valid dates, throw out the invalid ones, and then see which ones haven't occurred yet.
> 6 votes

# Answer
## Mathematica, ~~163~~ ~~153~~ 164 bytes

(*edit:* fixed dates outside the 1950 - 2049 range)

```
f=100.Count[#,x_/;x<1]/Length@#&[DateDifference[#,Date[]]&/@Cases[{If[#<100,Mod[#+50,100]+1950,#],##2}&@@@{{##},{#3,#2,#},{#3,#,#2}}&@@#,d_/;DateList@d~Take~3==d]]&

```

This defines a function which you can call like

```
f[{6,7,5}]

```

Currently, the percentage isn't rounded (waiting for the OP to clarify).

Here is a slightly lengthy explanation that should be understandable without any Mathematica knowledge (note that `&` makes everything left of it an anonymous function whose parameters are referred to as `#`, `#2`, `#3`...):

```
{{##},{#3,#2,#},{#3,#,#2}}&

```

This defines a function, which turns 3 parameters `a,b,c` into 3 lists `{{a,b,c},{c,b,a},{c,a,b}`. Note that `##` is just a sequence of all parameters.

```
{{##},{#3,#2,#},{#3,#,#2}}&@@#

```

Applied to the expiry date, this gives a list of `{y,m,d}` for each of the three possible permutations.

```
{If[#<100,Mod[#+50,100]+1950,#],##2}&

```

This is an anonymous function that takes three parameters `a,b,c` and returns a list of the three, where the first has been converted to a year as per the given rules: numbers between `50` and `99` (modulo `100`) are turned into a 20th century year, numbers between `0` and `49` (modulo `100`) are turned into a 21st century year, all others are left along. Here, `##2` is a sequence of parameters starting with the second one, i.e. `b,c`.

```
{If[#<100,Mod[#+50,100]+1950,#],##2}&@@@{{##},{#3,#2,#},{#3,#,#2}}&@@#

```

Applied to each of the three previous results, this just canonicalises the year formats. Let's call this `canonicalDates` to shorten the following expression:

```
Cases[canonicalDates,d_/;DateList@d~Take~3==d]

```

This filters out invalid interpretations. `DateList@d` makes a full `{y,m,d,h,m,s}` representation out of various date formats. It will interpret lists in the same order, but the catch is that you *can* pass it things like `{8,2,2006}` in which case it will calculate `8 years + 2 months + 2006 days`. So we check that the first three elements of the returned list are identical to the input (which can only happen if the month and day in the appropriate ranges).

To shorten the following lines, I'll refer to the result of that expression as `validDates` from now on:

```
DateDifference[#,Date[]]&

```

Another anonymous function which takes a date and returns the difference in days to today (obtained from `Date[]`).

```
DateDifference[#,Date[]]&/@validDates

```

Map that onto the valid date interpretations.

```
100.Count[#,x_/;x<1]/Length@#&

```

Yet another anonymous function which, given a list (`#`), returns the percentage of non-positive numbers in that list. The `.` is not a multiplication but just the decimal digit, to avoid rational numbers as the result (you'd get things like `100/3` instead of `33.333` \- I don't actually know if that's a problem).

```
100.Count[#,x_/;x<1]/Length@#&[DateDifference[#,Date[]]&/@validDates]

```

Applied to the list of date differences, this gives us the fraction of interpretations which are not yet expired.
> 6 votes

# Answer
# JavaScript (E6) 159 ~~164 172~~

**Edit** Thanks to nderscore for the hints and for pushing me to think again. Reorganized D avoiding parameters and cutting some chars.

**Edit 2** Another trick by nderscore, 2 functions merged into 1. Then two parenthesis removed merging comma separated expressions into one. Readability near 0. Sidenote: Not rounding could save another 2 chars (|0).

```
F=(a,t)=>t?100*(3-((i=F([y,m,d]=a))<t)-((j=F([m,d,y]=a))<t)-((k=F([d,m]=a))<t))/(3-!i-!j-!k)|0:(q=new Date(y<50?y+2e3:y,--m,d)).getMonth()==m&q.getDate()==d&&q

```

**Test** In FireFox console

```
;[[14,12,14],[8,2,2006],[6,7,5],[6,5,7],[12,31,99]]
.map(x=>x + ' ' + F(x, new Date(2006,6,5)))

```

Output:

```
["14,12,14 100", "8,2,2006 50", "6,7,5 33", "6,5,7 66", "12,31,99 0"]

```

**Ungolfed**

NB D function tries to create a Date with given year, month, day but returns false if the created date is not what was intented (!= day or month)

```
F=(d,t)=>
(
  D=(y,m,d)=>(
    q=new Date(y<50?y+2000:y, --m, d), // decr m as javascript (like java) counts months starting at 0
    q.getMonth() == m & q.getDate() == d && q
  ),
  [a,b,c] = d,
  x=D(...d), // three ways of express the date ...
  y=D(c,a,b),
  z=D(c,b,a),
  100 * (3-(x<t)-(y<t)-(z<t)) / (3-!x-!y-!z) | 0
)

```
> 4 votes

# Answer
# C# in LINQPad - 446 408 272 Bytes

**Third Edit:** Thanks to Le Canard fou for pointing out that DateTime.Today is correct, not DateTime.Now. **Second Edit:** Thanks VisualMelon for this clever solution!

```
void g(int[]d){var p=".";int a=d[2],b=d[1],e=d[0],y=a+(a<100?a>49?1900:2000:0),q=0,s=0;DateTime c;Action<string>z=x=>{if(DateTime.TryParse(x,out c)){s++;if(c>=DateTime.Today)q+=100;}};z(e+p+b+p+y);z(b+p+e+p+y);z(a+p+b+p+(e<100?e>49?1900+e:2000+e:e));(q/(s>0?s:1)).Dump();}

```

**Edit:** Thanks to podiluska and edc65 for helping me shorting the code! I also noticed that my solution wasn't correct if the year input was 4 bytes long, therefore I included the fix for that problem. The score for this solution is **408 Bytes.**

Even though I'm not beating any of the previous answers, I still wanted to share my C# solution. Any help/suggestions are appreciated! ;)

```
void g(int[]d){var q=new List<DateTime>();var p=".";int s=0,a=d[2],b=d[1],e=d[0],y=0;var c=new DateTime();y=(a<100)?(a>49)?1900+a:2000+a:a;if(DateTime.TryParse(e+p+b+p+y,out c)){q.Add(c);s++;}if(DateTime.TryParse(b+p+e+p+y,out c)){q.Add(c);s++;}y=(e<100)?(e>49)?1900+e:2000+e:e;if(DateTime.TryParse(a+p+b+p+y,out c)){q.Add(c);s++;}q=q.Where(i=>i>=DateTime.Now).ToList();if(s==0){s=1;}(q.Count*100/s).Dump();}

```

Formatted and ungolfed version:

```
void g(int[] d)
    {
        var q = new List<DateTime>();
        var p = ".";
        int s = 0, a = d[2],b = d[1],e = d[0], y=0;
        var c = new DateTime();
        y = (a < 100) ?((a > 49) ? 1900 + a : 2000 + a) : a;

        if (DateTime.TryParse(e + p + b + p + y, out c))
        {
            q.Add(c);
            s++;
        }
        if (DateTime.TryParse(b + p + e + p + y, out c))
        {
            q.Add(c);
            s++;
        }
        y = (e < 100) ? ((e > 49) ? 1900 + e : 2000 + e) : e;

        if (DateTime.TryParse(a + p + b + p + y, out c))
        {
            q.Add(c);
            s++;
        }
        q = q.Where(i => i >= DateTime.Now).ToList();
        if (s == 0)
        {
            s = 1;
        }
        (q.Count*100/s).Dump();
    }

```

I tried to make a solution where the "DateTime.TryParse"-Part isn't repeated as in this solution, but it was 21 bytes longer.

**Solution without repeating "DateTime.TryParse" : 467 Bytes**

```
void g(int[]d){var q=new List<DateTime>();int s=0;int a=d[2];int b=d[1];int e=d[0];int y=0;if(a<100){if(a>49){y=1900+a;}else{y=2000+a;}}if(z(e,b,y,q)){s++;}if(z(b,e,y,q)){s++;}if(e<100){if(e>49){y=1900+e;}else{y=2000+e;}}if(z(a,b,y,q)){s++;}q=q.Where(i=>i>=DateTime.Now).ToList();if(s==0){s=1;}(q.Count*100/s).Dump();}bool z(int a,int b,int d,List<DateTime> q){var c=new DateTime();var p=".";if(DateTime.TryParse(a+p+b+p+d,out c)){q.Add(c);return true;}return false;}

```

Ungolfed version:

```
private void g(int[] d)
    {
        var q = new List<DateTime>();
        int s = 0;
        int a = d[2];
        int b = d[1];
        int e = d[0];
        int y = 0;
        if (a < 100)
        {
            if (a > 49)
            {
                y = 1900 + a;
            }
            else
            {
                y = 2000 + a;
            }
        }
        if (z(e, b, y, q))
        {
            s++;
        }
        if (z(b, e, y, q))
        {
            s++;
        }
        if (e < 100)
        {
            if (e > 49)
            {
                y = 1900 + e;
            }
            else
            {
                y = 2000 + e;
            }
        }
        if (z(a, b, y, q))
        {
            s++;
        }
        q = q.Where(i => i >= DateTime.Now).ToList();
        if (s == 0)
        {
            s = 1;
        }
        (q.Count*100/s).Dump();
    }

    private bool z(int a, int b, int d, List<DateTime> q)
    {
        var c = new DateTime();
        string p = ".";
        if (DateTime.TryParse(a + p + b + p + d, out c))
        {
            q.Add(c);
            return true;
        }
        return false;
    }

```
> 4 votes

# Answer
## Haskell, 171 165 characters

```
l=length
r y|y<100=(y+50)`mod`100+1950|y>0=y
q d m y z|d<32&&m<13&&d*m>0=(r y,m,d):z|1<3=z
v(a,b,c)=q c b a$q b a c$q a b c[]
t%d=(l$filter(>t)(v d))*100`div`l(v d)

```

The function's name is `%`. Run with the test date as an tuple in canonical (y,m,d) order with actual year, and the carton stamp as a tuple of three numbers:

```
λ: (2006,6,5)%(14,12,14)
100

λ: (2006,6,5)%(8,2,2006)
50

λ: (2006,6,5)%(6,7,5)
33

λ: (2006,6,5)%(6,5,7)
66

λ: (2006,6,5)%(12,31,99)
0

λ: (2006,6,5)%(0,1,7)
0

```
> 3 votes

# Answer
# Erlang, 146

```
f([A,B,C]=U,N)->F=[T||T<-[{(Y+50)rem 100+1950,M,D}||[Y,M,D]<-[U,[C,A,B],[C,B,A]]],calendar:valid_date(T)],100*length([1||T<-F,T>=N])div length(F).

```

Test function would be:

```
t() ->
    0 = f([12,31,99],{2006,6,5}),
    66 = f([6,5,7],{2006,6,5}),
    33 = f([6,7,5],{2006,6,5}),
    100 = f([14,12,14],{2006,6,5}),
    50 = f([8,2,2006],{2006,6,5}),
    100 = f([29,2,2],{2006,6,5}).

```

**Ungolfed**

```
f([A,B,C]=U,Today)->
    Perms = [U,[C,A,B],[C,B,A]],
    WithYears = [{(Y+50) rem 100+1950,M,D} || [Y,M,D] <- Perms],
    ValidDates = [T || T <- WithYears, calendar:valid_date(T)],
    100*length([1 || T <- ValidDates, T >= Today]) div length(ValidDates).

```

This solution relies on list comprehensions. It borrows the modulo trick for the year from the Haskell solution. It also uses `calendar:valid_date/1` to handle impossible dates because of the number of days in a given month (e.g. "29-2-2" can only be in YMD format). Also, Today is in Erlang's `date()` format (a YMD tuple).
> 2 votes

# Answer
## APL (85)

This uses some of Dyalog APL 14's new functions, but no external libraries. For a change, it works on TryAPL.

```
{100×(+/÷⍴)⍺≤{(3/100)⊥⍵+(99≥⊃⍵)×3↑1900+100×50>⊃⍵}¨Z/⍨{∧/12 31≥1↓⍵}¨Z←(⊂⌽⍵),(⊂2⌽⍵),⊂⍵}

```

This is a function that takes the 3-element array as its right side () argument, and the date to check against as its left side () argument, as an integer of `YYYYMMDD` format. I.e., the date `2014-07-09` is represented as the number `20140709`.

Test:

```
      20060705 {100×(+/÷⍴)⍺≤{(3/100)⊥⍵+(99≥⊃⍵)×3↑1900+100×50>⊃⍵}¨Z/⍨{∧/12 31≥1↓⍵}¨Z←(⊂⌽⍵),(⊂2⌽⍵),⊂⍵} 14 12 14
100
      20060705 {100×(+/÷⍴)⍺≤{(3/100)⊥⍵+(99≥⊃⍵)×3↑1900+100×50>⊃⍵}¨Z/⍨{∧/12 31≥1↓⍵}¨Z←(⊂⌽⍵),(⊂2⌽⍵),⊂⍵} 8 2 2006
50
      20060705 {100×(+/÷⍴)⍺≤{(3/100)⊥⍵+(99≥⊃⍵)×3↑1900+100×50>⊃⍵}¨Z/⍨{∧/12 31≥1↓⍵}¨Z←(⊂⌽⍵),(⊂2⌽⍵),⊂⍵} 6 7 5
33.3333
      20060705 {100×(+/÷⍴)⍺≤{(3/100)⊥⍵+(99≥⊃⍵)×3↑1900+100×50>⊃⍵}¨Z/⍨{∧/12 31≥1↓⍵}¨Z←(⊂⌽⍵),(⊂2⌽⍵),⊂⍵} 12 31 99
0

```

Explanation:

* `Z←(⊂⌽⍵),(⊂2⌽⍵),⊂⍵`: turn the given date into Y-M-D format by flipping `(⊂⌽⍵)`, rotating it to the left by 2 `(⊂2⌽⍵)`, or just doing nothing `⊂⍵`. At least one of these is now a proper date in Y-M-D format, maybe more than one if the date is ambiguous.
* `{∧/12 31≥1↓⍵}¨Z`: test if each date is valid: the year (first element) is dropped, and then the month must be no higher than 12 and the day must be no higher than 31.
* `Z/⍨`: filter the valid dates from `Z`.
* `{`...: for each valid date:
    + `⍵+(99≥⊃⍵)×3↑1900+100×50>⊃⍵`: if the year is not higher than 99, add 1900, then 100 if the year is lower than 50.
    + `(3/100)⊥`: decode it as if it were a set of base-100 numbers. (The year is higher than 100, but this doesn't matter as it's the first element.) This gives a number for each valid date in the same format as the left argument.
* `⍺≤`: for each date, see if it is not smaller than . This will give a binary vector where 1 means `OK` and 0 means `spoiled`.
* `100×(+/÷⍴)`: divide the sum of the binary vector by its length and multiply by 100.
> 2 votes

# Answer
## **Java: 349 Characters (3 w/o spaces)**

```
int e(int[]n,Date t){int a=n[0],b=n[1],c=n[2];Date[]d=new Date[3];if(b<13&&c<32)d[0]=new Date((a<50?100:(a>100?-1900:0))+a,b-1,c);if(b<13&&a<32)d[1]=new Date((c<50?100:(c>100?-1900:0))+c,b-1,a);if(a<13&&b<32)d[2]=new Date((c<50?100:(c>100?-1900:0))+c,a-1,b);int v=0,g=0;for(int i=0;i<3;i++)if(d[i]!=null){if(!d[i].before(t))g++;v++;}return 100*g/v;}

```

Here is a containing class that can be used to test it, including a (slightly) degolfed version of the method:

```
import java.util.*;
class i{

   int e(int[]n,Date t){
      int a=n[0],b=n[1],c=n[2];
      Date[]d=new Date[3];
      if(b<13&&c<32)d[0]=new Date((a<50?100:(a>100?-1900:0))+a,b-1,c);
      if(b<13&&a<32)d[1]=new Date((c<50?100:(c>100?-1900:0))+c,b-1,a);
      if(a<13&&b<32)d[2]=new Date((c<50?100:(c>100?-1900:0))+c,a-1,b);
      int v=0,g=0;
      for(int i=0;i<3;i++)
         if(d[i]!=null){
            if(!d[i].before(t))
               g++;
            v++;
         }
      return 100*g/v;}

   public static void main(String[] args){
      int[]i=new int[3];
      for(int k=0;k<3;k++)
         i[k] = Integer.parseInt(args[k]);
      int j = new i().e(i,new Date());
      System.out.println(j+"%");
   }
}

```

This is my first round of code golf, and I think I figured out why I don't usually see very many Java golfers.
> 0 votes

# Answer
# C# 287 bytes

```
namespace System{class E{static float a,o,l;void M(int[]i){int d=i[0],m=i[1],y=i[2],t;if(l<3)try{if(l==1){t=y;y=d;d=t;}if(l++==0){t=d;d=m;m=t;}if(y<100&&(y+=1900)<1950)y+=100;o+=new DateTime(y,m,d)>=DateTime.Today?1:0;a++;if(l<3)i[9]=9;}catch{M(i);throw;}Console.Write(o/a);}}}

```

First time golfing, looking for advices. Notably, removing bytes due to namespace.

Abusing the fact that only a function is required, not an actual program. Also, the function always results in an uncaught exception.

**Ungolfed**

```
namespace System {
    class E {
        static float a, o, l;
        void M(int[] i) {
            int d = i[0], m = i[1], y = i[2], t;
            if (l < 3)
                try {
                    if (l == 1) {
                        t = y; y = d; d = t;
                    }
                    if (l++ == 0) {
                        t = d; d = m; m = t;
                    }
                    if (y < 100 && (y += 1900) < 1950)
                        y += 100;
                    o += new DateTime(y, m, d) >= DateTime.Today ? 1 : 0; // # not expired
                    a++; // # valid dates
                    if (l < 3)
                        i[9] = 9; // throw new Exception()
                }
                catch {
                    M(i);
                    throw; // fail after the first Console.Write()
                }
            Console.Write(o / a);
        }
    }
}

```
> 0 votes

# Answer
## *Mathematica*, 118

Using m.buettner's code as a starting point I have a few improvements:

```
⌊100Mean@UnitStep@Cases[DateDifference@{If[#<100,Mod[#+50,100]+1950,#],##2}&@@@{#,RotateRight@#,Reverse@#},_Integer]⌋&

```
> 0 votes

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


title: Palindromic prime

text:
# Question
Title: Palindromic prime
I'm solving task, where:

## Input:

A number as an integer.

## Output:

The closest greater palindromic prime as an integer.

I would appreciate *hints* how to make my solution shorter. Or directions if change of approach would be beneficial.

```
golf=lambda l,r=range:next(x for x in r(10**6)if(x==int(`x`[::-1]))&all(x%d for d in r(2,x))and x>l)

```

palindromic:

```
x==int(`x`[::-1])

```

prime:

```
all(x%d for d in r(2,x))

```

# Answer
Now, for some really big improvements. Your original program was 97 characters:

```
n=lambda l,r=range:next(x for x in r(10**6)if(x==int(`x`[::-1]))&all(x%d for d in r(2,x))and x>l)

```

With the improvements below, you could get to 90 characters:

```
n=lambda l,r=range:min(x for x in r(l+1,10**6)if(`x`==`x`[::-1])&all(x%d for d in r(2,x)))

```

With a trick to eliminate the parentheses around the palindrome checking statement, you can get to 87:

```
n=lambda l,r=range:min(x for x in r(l+1,10**4)if`x`==`x`[::-1]*all(x%d for d in r(2,x)))

```

However, I have a solution in 80 characters. To get it, focus on changing the big picture, not the individual components. Rethink your most basic choices in getting to this point. Why a lambda? Why a min of a filtered range? There may be a better way.

---

Using `int()` in the palindrome comparison is a lot of characters - can you see a shorter way to turn

```
x

```

and

```
`x`[::-1]

```

into the same type?

Also, that `and x>l` bit at the end is a lot of characters. Is there a way we could shorten it? Eliminate the need for it by changing something else?

Is `next` the right function for the job? Remember, this is code golf, runtime is irrelevant.

The prime checking function looks spot on, though.

Also, and this is merely aesthetic, I don't like aliasing functions, the way you are doing with range, when it doesn't save any characters, as in this case.
> 7 votes

---
Tags: code-golf, tips, primes, python, palindrome
---


# Question
Title: One Bad Ternary Operator Deserves Another
Today's Daily WTF quotes the following line of code...

```
FailSafe==0?'No technical alarms':((FailSafe&1)!=0&&(FailSafe&2)!=0&&(FailSafe&4)!=0&&(FailSafe&8)!=0?'Detection zones staying in a given state; Bad visibility;
Initialization; Bad configuration':((FailSafe&1)!=0&&(FailSafe&2)!=0&&(FailSafe&4)!=0?'Detection zones staying in a given state; Bad visibility; Initialization':
((FailSafe&1)!=0&&(FailSafe&2)!=0&&(FailSafe&8)!=0?'Detection zones staying in a given state; Bad visibility; Bad configuration':((FailSafe&1)!=0&&(FailSafe&4)!=0&&
(FailSafe&8)!=0?'Detection zones staying in a given state; Initialization; Bad configuration':((FailSafe&2)!=0&&(FailSafe&4)!=0&&(FailSafe&8)!=0?'Bad visibility;
Initialization; Bad configuration':((FailSafe&1)!=0&&(FailSafe&2)!=0?'Detection zones staying in a given state; Bad visibility':((FailSafe&1)!=0&&(FailSafe&4)!=0?'Detection
zones staying in a given state; Initialization':((FailSafe&1)!=0&&(FailSafe&8)!=0?'Detection zones staying in a given state; Bad configuration':((FailSafe&2)!=0&&
(FailSafe&4)!=0?'Bad visibility; Initialization':((FailSafe&2)!=0&&(FailSafe&8)!=0?'Bad visibility; Bad configuration':((FailSafe&4)!=0&&(FailSafe&8)!=0?'Initialization; Bad
configuration':((FailSafe&1)!=0?'Detection zones staying in a given state':((FailSafe&2)!=0?'Bad visibility':((FailSafe&4)!=0?'Initialization':((FailSafe&8)!=0?'Bad
configuration':'Unknown')))))))))))))))

```

Write some code that takes an integer value named FailSafe and returns the same string that the above code would produce from the same integer value.

* The challenge is to rewrite that line, so "boilerplate" code is free, including any code that loads an integer value and outputs the string. Only the code that performs the above transformation from an integer to a string counts.
* You may use a different name to "FailSafe" if you wish, as long as your chosen identifier has the same golf score.
* No calling external resources to perform the lookup.
* Normal code-golf rules apply.

# Answer
### Ruby, 210 characters

Similar to @Jan Dvorak's solution but a bit more functional and a bit shorter.

```
f=FailSafe
e=[f&1,f&2,f&4,f&8,1-f].zip(["Detection zones staying in a given state","Bad visibility","Initialization","Bad configuration","No technical alarms"]).map{|a,b|a>0&&b}-[!0]
e[0]||="Unknown"
e.join"; "

```
> 5 votes

# Answer
### GolfScript, 167 characters

```
FailSafe.15&["Unknown"][""]"Bad configuration
Initialization
Bad visibility
Detection zones staying in a given state"
n/{`{n+1$+}+%}/1>+=n%"; "*"No technical alarms"if

```

The code assumes the value in variable `FailSafe` and pushes the result on the stack (i.e. output the string if run as standalone program). You can test the code online.

The code basically generates an array of all 16 possible outcomes, selects the error message depending on the four lowest bits of `FailSafe`. The outermost `if` then handles the zero case.
> 5 votes

# Answer
## Rebol/Red: 208 chars

I'm not as interested in golfing this as in agreeing that nested ternary operators are annoying...and mentioning this is actually a nice instance for Rebol/Red's CASE. It's related to SWITCH and really helps flatten things like this out:

```
f: FailSafe
append case [
    0 < f and 1 ["Detection zones staying in a given state"]
    1 < f and 2 ["Bad visibility"]
    3 < f and 4 ["Initialization"]
    7 < f and 8 ["Bad configuration"]
    f > 0 ["Unknown"]
    true ["No technical alarms"]
] "; "

```

There's a variant called CASE/ALL that will actually run all the conditions, but the default just stops after the first true one.

I'll "golf" it a little to 208:

> x: func\[y\]\[y \< (f: FailSafe) and ++ y\]append case\[x 0\["Detection zones staying in a given state"\]x 1\["Bad visibility"\]x 3\["Initialization"\]y 7\["Bad configuration"\]f \> 0\["Unknown"\]1\["No technical alarms"\]\]"; "
> 4 votes

# Answer
## APL (172)

```
2↓⊃,/'; '∘,¨{⍵=0:⊂'No technical alarms'⋄0=16|⍵:⊂'Unknown'⋄'Detection zones staying in a given state' 'Bad visibility' 'Initialization' 'Bad configuration'/⍨⌽⍵⊤⍨4/2}FailSafe

```

Explanation:

* `{`...`}FailSafe`: generate the strings
    + `⍵=0:⊂'No technical alarms'`: the `0` case
    + `0=16|⍵:⊂'Unknown'`: the `Unknown` case (FailSafe is not 0 but the first four bits are)
    + `'Detection zones staying in a given state' 'Bad visibility' 'Initialization' 'Bad configuration'/⍨⌽⍵⊤⍨4/2`: get the lowest 4 bits in the argument (`⍵⊤⍨4/2`), reverse (), and select the strings for the bits that are on (`/⍨`).
* `'; '∘,¨`: add `'; '` to the front of each returned string,
* `⊃,/`: join all the strings together,
* `2↓`: and remove the first two characters (because there's an extra `'; '` at the front.)
> 4 votes

# Answer
## Ruby, 183 characters

```
[(f=FailSafe)<1?"No technical alarms":f&15<1?:Unknown:["Detection zones staying in a given state"*f[0],"Bad visibility"*f[1],"Initialization"*f[2],"Bad configuration"*f[3]]-[""]]*"; "

```

Yet another Ruby solution, but a bit shorter than the others. This is a single expression that uses the constant `FailSafe` (in Ruby, all uppercase identifiers are constants) to create the output string.
> 3 votes

# Answer
# Ruby, 213 characters

```
f=failSafe
e=f&1>0?["Detection zones staying in a given state"]:[]
e+=["Bad visibility"]if f&2>1
e+=["Initialization"]if f&4>3
e+=["Bad configuration"]if f&8>7
e[0]||=f>0?"Unknown":"No technical alarms"
e.join"; "

```

This will work just fine wrapped in a function body (`def transform failSafe; ...; end`). It can also be used as a single expression (wrap in parentheses because a semicolon/newline has the lowest priority) or as a sequence of statements with the last expression (`e.join"; "`) used within an expression.
> 2 votes

# Answer
## JavaScript, ~~197~~195 characters

```
FailSafe?['Detection zones staying in a given state','Bad visibility','Initialization','Bad configuration'].filter(function(_,i){return FailSafe&1<<i}).join('; ')||'Unknown':'No technical alarms'

```

formatted:

```
FailSafe
  ? [ 'Detection zones staying in a given state',
      'Bad visibility',
      'Initialization',
      'Bad configuration'
    ].filter(function(_, i) {
      return FailSafe & 1<<i;
    }).join('; ') || 'Unknown'
  : 'No technical alarms';

```

Could be further reduced by using ES6 or Coffeescript function expressions.
> 2 votes

# Answer
# VBScript, 204 234 232 characters

(edit: improved score by 2 by using array() instead of split(). 232 now.)

```
f=failsafe:for b=0to 3:s=s&split(",; Detection zones staying in a given state,; Bad visibility,,; Initialization,,,,; Bad configuration",",")(f and 2^b):next:array("No technical alarms","Unknown",mid(s,3))(2+(f=0)+(len(s)=0))

```

(edit: forgot the "unknown" part. 234 chars now.)

f=failsafe:for b=0to 3:s=s&split(",; Detection zones staying in a given state,; Bad visibility,,; Initialization,,,,; Bad configuration",",")(f and 2^b):next:split("No technical alarms,Unknown,"&mid(s,3),",")(2+(f=0)+(len(s)=0))

(original, 230)

for b=0to 3:s=s&split(",; Detection zones staying in a given state,; Bad visibility,,; Initialization,,,,; Bad configuration",",")(FailSafe and 2^b):next:array(mid(s,3),"No technical alarms")(-(len(s)=0))

Of course, this is just part of a script. to test it, try something like this:

```
FailSafe=cint(inputbox("Please enter Failsafe as an integer"))
f=failsafe:for b=0to 3:s=s&split(",; Detection zones staying in a given state,; Bad visibility,,; Initialization,,,,; Bad configuration",",")(f and 2^b):next
msgbox array("No technical alarms","Unknown",mid(s,3))(2+(f=0)+(len(s)=0))

```
> 1 votes

# Answer
## Smalltalk, 243 characters

```
FailSave>15ifTrue:'Unknown'ifFalse:[((((1to:4)select:[:b|FailSafe isBitSet:b])collect:[:b|#('Detection zones staying in a given state' 'Bad visibility' 'Initialization' 'Bad configuration')at:b])asStringWith:'; ')ifEmpty:'No technical alarms']

```

formatted for readability:

```
FailSafe > 15
    ifTrue:'Unknown'
    ifFalse:[
        ((((1 to:4)
            select:[:b | FailSafe isBitSet:b ])
                collect:[:b|
                    #( 'Detection zones staying in a given state'
                       'Bad visibility'
                       'Initialization'
                       'Bad configuration') at:b ]
                    ) asStringWith:'; ')
                        ifEmpty:'No technical alarms']

```

Thanks to Bergi, for pointing to the bug in the first version.

This brings up an idea: if I map the FailSafe value into a 6-bit mask, (mapping 0 -\> 16 and greater-than-15 -\> 32), I can get rid of the final tests. The mapping to the 6bit mask m can be done with:

`m := {16},(1 to: 15) at:FailSafe+1 ifAbsent:32.`

that is, m will be 16 for a zero FailSafe, and 32 for out-of-bounds values. Then select and collect strings as above. This gives the new code:

```
m := {16},(1 to:15) at:FailSafe+1 ifAbsent:32.
(((1 to:6) select:[:b | m isBitSet:b ])
        collect:[:b|
            #( 'Detection zones staying in a given state'
               'Bad visibility'
               'Initialization'
               'Bad configuration'
               'No technical alarms'
               'Unknown') at:b ]
               ) joinWithAll:'; '

```

(I also replaced asStringWith: by joinWithAll:, which is an alias).

Although this seems to be a nice idea, this has the same character count - sigh. Maybe some other programming language with denser operator names scores better here!

I could save a few chars by not using a temporary variable for m, but recompute it in the loop and by not using a literal array for the string vector, to get a count slighty below 240 chars.

Finally, the mask m could also be computed by `m:={32},(1 to: 16) at:(FailSafe+1 min:17)`, which might be shorter in APL. Then exchange the last two strings in the vector.

PS: The first version assumes FailSafe is non-negative, like some other solutions here do. The second can deal with anything, even nil or other non-numbers.
> 1 votes

# Answer
## CoffeeScript, 161 160 221 chars

```
F = FailSafe;F<16 and (F and [0..3].filter((i)->(1<<i)&F).map((i)->(['Detection zones staying in a given state','Bad visibility','Initialization','Bad configuration'])[i]).join('; ') or 'No technical alarms') or 'Unknown'

```
> 0 votes

# Answer
**VB.net**

```
Function StateText(f As FailFlag) As String
  If f=0 Then Return "No Technical Alarm"
  Dim t=""
  If f.HasFlag(f1) Then t &= "Detection zones staying in a given state; "
  If f.HasFlag(f2) Then t &= "Bad visibility; "
  If f.HasFlag(f4) Then t &= "Initialization; "
  If f.HasFlag(f8) Then t &= "Bad configuration; "
  Return If( t<>"", t.TrimEnd("; "),"Unknown")
End Function

<Flags>
Enum FailFlag
  f1 = 1
  f2 = 2
  f4 = 4
  f8 = 8
End Enum

```

Edit: Better Entry

```
Function StateText(f As FailFlag) As String
  If f = 0 Then Return "No Technical Alarm"
  Dim t = String.Join("; ",
            From e In [Enum].GetValues(GetType(FailFlag))
            Where f.HasFlag(e)
            Select [Enum].GetName(GetType(FailFlag), e).Replace("_", " "))
  Return If( t<>"", t,"Unknown")
End Function

<Flags>
Enum FailFlag
  Detection_zones_staying_in_a_given_state = 1
  Bad_visibility = 2
  Initialization = 4
  Bad_configuration = 8
End Enum

```
> 0 votes

# Answer
## Perl, 208 197 Characters

```
$f=$FailSafe;%m=(1,'Detection zones staying in a given state',2,'Bad visibility',4,'Initialization',8,'Bad configuration');($f?join'; ',@m{map{$f&$_?$_:()}1,2,4,8}:'No technical alarms')||'Unknown'

```

With boilerplate code to make it work:

```
#!/usr/bin/env perl
$FailSafe=17;
print failmsg() . "\n";

sub failmsg {
$f=$FailSafe;%m=(1,'Detection zones staying in a given state',2,'Bad visibility',4,'Initialization',8,'Bad configuration');($f?join'; ',@m{map{$f&$_?$_:()}1,2,4,8}:'No technical alarms')||'Unknown'
}

```
> 0 votes

# Answer
**Java 275 characters** (not counting **unnecessary** white space)

```
    String s = "";
    int b = 1;
    for (String m : new String[]{"Detection zones staying in a given state; ","Bad visibility; ", "Initialization; ", "Bad configuration; "}) {
        if ((FailSafe & b) != 0) s = s + m;
        b <<= 1;
    }
    return (s.length() == 0) ? (FailSafe == 0) ? "No technical alarms" : "Unknown" : s.substring(0, s.length() - 2);

```
> 0 votes

---
Tags: code-golf
---


title: Create an autocorrect program

text:
# Question
Title: Create an autocorrect program
People sometimes make spelling eorrors. A lto. Your challenge is to write a program that can take a string with certain spelling errors, such as the switching of I and E, and correct those mistakes. This has to be able to make changes to any combination of characters in any string, and fix the spelling errors. This is a , the winner will be chosen in three days. If I need to clarify any additional details, please do say, and I will add it to my challenge. Good luck!

# Rules

* You may read correctly-spelled words from a file.
* You will read the string from standard input.
* You need only correct basic spelling errors.
* It's ok if your program makes a *few* errors.

# Answer
for a real "good" correction, we need to know the set of words which are "reasonable". In a program editor, this depends on the word before the cursor. This may be either a class or variable name, or the name of the function to be called (some syntax awareness required here). In a general text editor, this would be a list of words from a dictionary.

In the following code, I assume that the list of "good" words is found in "candidates", in Smalltalk this would be one of:

```
Smalltalk allClasses collect:[:cls | cls name]

```

for class names, or

```
Smalltalk allClasses collectAll:[:cls | cls methodDictionary keys] as:Set

```

for the names of all methods.

Of course, in a real world corrector, this would take into account the current scope to restrict the set of possible candidates.

The code then selects the best candidate by its editing distance, which is the distance between two strings based on the weighted number of insert, delete and replace operations required to change one string onto another. All Smalltalks provide a "spellAgainst:" method in their String class, which is based on levenshtein or a similar algorithm.

```
"the following is of course very Smalltalk dialect specific,
 as the GUI frameworks are slightly different.
 It assumes there is an editor object, which represents the code edit
 window."

candidates := <one of the above>.
wordToFix := editor wordBeforeCursor.

best := candidates detectMax:[:each | each spellAgainst: wordToFix].

editor selectWordBeforeCursor.
editor replaceSelectionBy:best.

```

PS: one of the coolest features of Smalltalk is that the IDE is part of your program and vice versa (they are the same), so you can actually add the above code fragment to your editor's keyPress method and have it work immediately!
> 3 votes

# Answer
# Python

This uses Levenshtein distance, but doesn't account for non-alpha characters and case. Corrects single misspelled words. Enter a string on stdin, output on stdout, and have a newline separated list of words in a file called words.txt in the same directory.

## Code

```
# Open list of correcly-spelled words.
wordFile = open("words.txt")
threshold = 8
listOfWords = input().split()
index = 0

def lev(a, b):
    if min(len(a), len(b)) == 0:
        return max(len(a), len(b))
    else:
        return min(lev(a[:-1], b) + 1, lev(a, b[:-1]) + 1,
            lev(a[:-1], b[:-1]) + int(not a[-1] == b[-1]))

for x in listOfWords:
    replacement = (x, threshold + 1)

    for word in wordFile:
        x = x.lower()
        word = word[:-1].lower()

        if x == word:
            replacement = (x, 0)
            break # Some words may actually be spelled correctly!

        d = lev(x, word)
        if (d < threshold) and (replacement[1] > d):
            replacement = (word, d)

    listOfWords[index] = replacement[0]
    index += 1
    wordFile.seek(0)

print(*listOfWords)

```

# Bugfix

All words are corrected now.
> 2 votes

---
Tags: popularity-contest, natural-language
---


# Question
Title: Optimal Minesweeper on the Largest Board
**Overview:** Your challenge is to write a program that will play minesweeper optimally, giving the best move in any position. Moreover, you must do this on the largest board possible.

**Game details:** Minesweeper is a one player game, played on a rectangular board. At the beginning of the game, a specified number of mines are randomly distributed over the board, at most one to a cell. Each possible placement of the mines is equally likely. The mines' positions are hidden from the player.

On each of the player's turns, he or she chooses a square on the board to reveal. If the square contains a mine, the player loses the game. Otherwise, the number of mines in Moore neighborhood of the chosen square (orthogonally or diagonally adjacent) is revealed to the player.

The player repeats this until either a mine is revealed, or the number of unrevealed squares is equal to the number of mines. If the latter occurs, the player wins.

**Program specification:** Your program must take as input a board position, which should specify the locations and values of the revealed and unrevealed squares, as well as the number of mines on the board. It must return at least one move which has a maximal likelihood of winning if followed by optimal play. Returning more moves is allowed, as long as they all have the same, maximal, win rate.

In addition, the program must return the maximal number of possibilities that can be won under optimal play and the total number of possibilities for this revealed board state. From these values, the exact probability of winning under optimal play is known.

**Examples:**

Input (in any format you prefer):

```
4 mines
____
____
____
____

```

Output:

```
Best moves are [(0, 1), (0, 2), (1, 0), (1, 3), (2, 0), (2, 3), (3, 1), (3, 2)].
961 wins out of 1820 possibilities.

```

Input:

```
5 mines
_____
_1___
_3___
_____

```

Output:

```
Best moves are [(0, 2)].
285 wins out of 360 possibilities.

```

**Challenge specification:** Your challenge is to run your program on the initial position of a board of one of the following types:

* n x n board, n mines.
* n x n+1 board, n mines.
* n x n+1 board, n+1 mines.

Your program must find an optimal move on your machine at least as fast as the reference implementation solves the 4x5 board, 5 mines case on your machine. That case takes 6 minutes on my computer, for reference.

To run that instance of the reference implementation with timing, run `python3 Minesweeper-challenge.py <<< "(4,5), 5, '____________________'"`

The program that correctly identifies the optimal moves and exact number of possibilities that can be won with perfect play, on the initial position of the largest board of the above type, tiebreaker most mines, in the given time limit, wins the contest.

I will select a winner in two weeks, on July 24th.

Since writing a program like this is a big task, I will be awarding a bounty of 150 reputation, starting tomorrow and ending on the 18th.

Edit/bump: Well, that was a waste of 250 rep.

# Answer
> 4 votes
# Python, 4x5 board, 5 mines.

This is the reference implementation, I just thought I'd put it here to help give people ideas.

This implementation uses dynamic programming to prevent duplication of work, exploits mirror symmetries, and maintains a fist of all possible boards with a given revealed square status to check for guaranteed safe squares.

```
# Minesweeper solver
# Class just contains partially revealed boards that all look the same
# from the outside

# This is a branch, that uses strings.

# Boards have every cell revealed.
# Revealed is partially revealed. Boards must match revealed on every
# cell that is revealed.

# Meanings:
# '0'-'8': Safe square with that # of surrounding mines
# '*'    : Mine
# '_'    : Unrevealed
import copy
import itertools
import time
import pickle
import random
import math
import cProfile
import sys

class Position:
    def __init__(self, dimensions, revealed, boards):
        self.dim_r,self.dim_c=dimensions
        self.rev=revealed
        self.boards=boards
        assert len(revealed)==self.dim_r*self.dim_c

    def click(self,loc):
        # Takes a location, returns all possible revealed positions, with boards
        # split up accordingly
        try:
            assert self.rev[loc]=='_'
        except AssertionError:
            print(self,loc,self.rev)
            assert self.rev[loc]=='_'
        # Create all possible new boards, split up by revealed item.
        board_dict={}
        for board in self.boards:
            clicked_cell=board[loc]
            if clicked_cell in board_dict:
                board_dict[clicked_cell].append(board)
            else:
                board_dict[clicked_cell]=[board]
        new_positions=[]
        for rev_cell in board_dict.keys():
            # Make the new board without copying
            new_rev=''.join([self.rev[:loc],rev_cell,self.rev[loc+1:]])
                new_pos=Position((self.dim_r,self.dim_c),new_rev,board_dict[rev_cell])
            new_positions.append(new_pos)
        return new_positions

    def someBestClick(self):
        click_list=[]
        # Set of boards is all we know when outputting, may be smaller than
        # complete set
        # If we've clicked on a bomb, no way to win, no best click.
        if '*' in self.rev:
            return 0,[]
        unrevealed = [loc for loc in range(len(self.rev)) if self.rev[loc]=='_']
        # If there is only 1 possible board, you're done. The click list is every
        # unrevealed square on the board without a bomb under it.
        if len(self.boards)==1:
            return 1,[loc for loc in unrevealed if self.boards[0][loc]!='*']

        # If there is an unrevaled locaiton on the board that is bomb free in
        # every sub-board, use it.
        for loc in unrevealed:
            if all(board[loc]!='*' for board in self.boards):
                return sum(pos.memoBestClick()[0] for pos in self.click(loc)),[loc]

        # The broadest test - try everywhere.
        click_list=[]
        most_wins=0
        for loc in unrevealed:
            wins=sum(pos.memoBestClick()[0] for pos in self.click(loc) if pos.rev[loc]!='*')
            if wins>=most_wins:
                if wins>most_wins:
                    click_list=[]
                    most_wins=wins
                click_list.append(loc)
        return most_wins,click_list

    def memoBestClick(self):
        global memo
        global memo_counter
        memo_counter +=1
        if not self.rev in memo:
            # These lines check for mirror images of the board being in the memo table

            vert_reversed_memo_str=                                         \
            ''.join([self.rev[y*self.dim_c:(y+1)*self.dim_c]
                     for y in range(self.dim_r)][::-1])

            if vert_reversed_memo_str in memo:
                vert_reversed_output=memo[vert_reversed_memo_str]
                return vert_reversed_output[0],                             \
                        [(self.dim_r-1-loc//self.dim_c)*self.dim_c+loc%self.dim_c
                         for loc in vert_reversed_output[1]]

            horiz_reversed_memo_str=                                        \
            ''.join(self.rev[y*self.dim_c:(y+1)*self.dim_c][::-1]
                    for y in range(self.dim_r))

            if horiz_reversed_memo_str in memo:
                horiz_reversed_output=memo[horiz_reversed_memo_str]
                return horiz_reversed_output[0],                            \
                        [(loc//self.dim_c)*self.dim_c+
            both_reversed_memo_str=self.rev[::-1]
            if both_reversed_memo_str in memo:
                both_reversed_output=memo[both_reversed_memo_str]
                return both_reversed_output[0],                             \
                        [len(self.rev)-1-loc
                         for loc in both_reversed_output[1]]

            global restart_counter
            global restart_memo

            if len(self.rev)-self.rev.count('_') <= restart_max:
                restart_memo[self.rev]=self.someBestClick()
                memo[self.rev]=restart_memo[self.rev]
                return restart_memo[self.rev]
            # Needed because of memory issues
            if len(memo)>5*10**6:
                memo=copy.deepcopy(restart_memo)
                restart_counter+=1
            memo[self.rev]=self.someBestClick()
        return memo[self.rev]

def makeBlankPosition(dimensions,mines):
    dim_r,dim_c=dimensions
    # Makes all locations on the board
    all_loc=itertools.product(range(dim_c),range(dim_r))
    # Makes all possible distributions of mines
    all_mine_layouts=itertools.combinations(all_loc,mines)
    boards=[]
    for mine_layout in all_mine_layouts:
        boards.append(makeBoardFromMines(dimensions,mine_layout))
    return Position(dimensions, '_'*dim_c*dim_r, boards)

def makeBoardFromMines(dimensions,mine_layout):
    dim_r,dim_c=dimensions
    def mineNum(loc):
        if (loc%dim_c,loc//dim_c) in mine_layout:
            return '*'
        return str(sum(((loc%dim_c+dif[0],loc//dim_c+dif[1]) in mine_layout) for dif in
                   [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]))
    return ''.join(map(mineNum,(loc for loc in range(dim_r*dim_c))))

def makePosition(dimensions,mines,revealed):
    blank_pos=makeBlankPosition(dimensions,mines)
    boards_subset=[]
    for board in blank_pos.boards:
        if all(revealed[cell_num]==board[cell_num] or revealed[cell_num]=='_' for cell_num in range(len(board))):
            boards_subset.append(board)
    return Position(dimensions, revealed, boards_subset)

def winRate(dimensions,mines,revealed):
    pos=makePosition(dimensions,mines,revealed)
    global memo
    memo={}
    wins=pos.memoBestClick()
    return wins[0],len(pos.boards),wins[1],memo

global memo_counter
memo_counter=0
global restart_counter
restart_counter=0
global restart_memo
restart_memo={}
global restart_max
restart_max=6
dimensions, mines, revealed = eval(input())
start_time=time.clock()
wins, total_boards, moves, memo = winRate(dimensions, mines, revealed)
move_points=[(move//dimensions[1],move%dimensions[1]) for move in moves]
print("""Best moves are %s.\n%i wins out of %i boards. Ratio of %f. %i
positions searched.\n%f seconds taken."""%(move_points, wins, total_boards,
wins/total_boards, len(memo),time.clock()-start_time))

```

---
Tags: code-challenge, game, fastest-code, minesweeper
---


title: Calculate the most digits of pi

text:
# Question
Title: Calculate the most digits of pi
There are a lot of challenges on this site regarding pi, but none that challenge you to calculate as many digits of pi as possible.

As you all may know, pi in its decimal form goes on for infinity, so calculating it in its entirety is near to impossible. However, I challenge you to write a program in your language of choice that can calculate as many digits of pi as possible, and ***include an explanation with your code.*** The winner will be decided by popularity contest.

The only restriction is that your program cannot connect to the internet. The point is not to have your program search the internet for the most digits of pi.

So in summary, the goal is to write a program that computes as many digits of pi as possible (in decimal, so 3.14159....). Your program cannot simply connect to the internet and lookup digits, it needs to calculate it.

**Note here that the goal here is to calculate as many digits as possible, but that is not the winning criteria. The winner will be based on popularity (number of upvotes).** Remember, we're here to learn just as much as to have fun.

Winner will be decided on July 16 at 10 AM eastern time.

And please, don't be this guy. Let's have fun.

# Answer
# C

The following is my favourite implementation of a pi calculation program:

```
#define _ F-->00 || F-OO--;
long F=00,OO=00;
main(){F_OO();printf("%1.3f\n", 4.*-F/OO/OO);}F_OO()
{
            _-_-_-_
       _-_-_-_-_-_-_-_-_
    _-_-_-_-_-_-_-_-_-_-_-_
  _-_-_-_-_-_-_-_-_-_-_-_-_-_
 _-_-_-_-_-_-_-_-_-_-_-_-_-_-_
 _-_-_-_-_-_-_-_-_-_-_-_-_-_-_
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
 _-_-_-_-_-_-_-_-_-_-_-_-_-_-_
 _-_-_-_-_-_-_-_-_-_-_-_-_-_-_
  _-_-_-_-_-_-_-_-_-_-_-_-_-_
    _-_-_-_-_-_-_-_-_-_-_-_
       _-_-_-_-_-_-_-_-_
            _-_-_-_
}

```

Found here with the following explanation:

> Pi -- A unique program layout and the most unusual method of calculating pi I have ever seen. The source code is a circle and the program works by calculating its own area and diameter, and then doing a division to approximate pi!! Very bizzare.

I haven't tried this, but I guess you can make the circle larger to calculate more digits of pi.
> 15 votes

# Answer
## Mathematica

I'm definitely going for the simplicity/golf award here with 5 characters:

```
π~N~n

```

Just defined `n` to be the number of digits you want.

I did a quick test to figure out how many digits that allows me to calculate within a week. I ran this for `n` from 100 000 to 10 000 000 in steps of 100 000 and measured the time. The plot looks *very* much linear (apart from a few outliers, because I used my machine during the test), so I got a least squares fit for a linear function, solved it for `n` and plugged in `t = 60*60*24*7`. On my 3 year-old laptop, I'd get about **4.5 * 1011** digits, which is 450 billion. Realistically it might be a bit less, as I can't predict whether the algorithm used by Mathematica will at some point slow down, e.g. due to memory or cache constraints.
> 8 votes

# Answer
## C - 13 million digits

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

#define DIGITS 13000000

int main() {
  uint64_t d=0,h=1e9;
  uint32_t b,c=30*((DIGITS+25)/9),e=0,g;
  uint32_t* f=(uint32_t*)malloc(4*c);
  while(b=c-=30){
    while(--b){
      d=d*b+h*(e?f[b]:2);
      f[b]=d%(g=2*b-1);
      d/=g;
    }
    printf(e?"%09d":"%d.",e+d/h);
    e=d%h;
  }
  free(f);
  return 0;
}

```

Using only standard libraries, compiled with `gcc -O2`. The formula used is the following:

This can be derived directly from the Leibniz Series, as can be seen elsewhere. Standard long division is used, in base *1000000000* rather than base *10*, storing the remainders for each division in an array.

The algorithm is quadratic: *10000* digits takes ~0.35s, *100000* takes ~35s, etc (*10* times as many takes *100* times as long). I estimate that all *13000000* will take approximately 6d 20h 18m, give or take, using a constant 170MB of memory.
> 6 votes

# Answer
## C# - 412 394 chars, 3000 digits, 7 seconds

I wrote this program myself, except for the square root function. It calculates π using the Chudnovsky formula and uses the .Net BigInteger class for fixed-point math.

```
using B=System.Numerics.BigInteger;class M{static void Main(){B f=B.Pow(10,3000);B z=0;for(int k=0;k<220;k++)z+=f*F(6*k)*(13591409+545140134*new B(k))/(F(3*k)*B.Pow(F(k),3)*B.Pow(-640320,3*k));System.Console.WriteLine(f*f/(12*z*f/S(B.Pow(640320,3)*f*f)));}static B F(B N){return(N.Sign>0)?N*F(N-1):1;}static B S(B N){if(0==N)return 0;B o=(N>>1)+1;for(B a=o+N/o>>1;a>1)o=a;return o;}}

```

With some extra white space:

```
using B=System.Numerics.BigInteger;
class M{
static void Main(){
B f=B.Pow(10,3000);
B z=0;
for(int k=0;k<220;k++)
z+=f*F(6*k)*(13591409+545140134*new B(k))/(F(3*k)*B.Pow(F(k),3)*B.Pow(-640320,3*k));
System.Console.WriteLine(f*f/(12*z*f/S(B.Pow(640320,3)*f*f)));
}
static B F(B N){return(N.Sign>0)?N*F(N-1):1;}
static B S(B N){if(0==N)return 0;B o=(N>>1)+1;for(B a=o+N/o>>1;a>1)o=a;return o;}}

```

The Main function calculates Pi, and the other 2 functions are (respectively) Factorial and Square Root. The number of digits (3000) can be changed in the Main function, just be sure to change the number of Chudnovsky terms (220) to match, otherwise some digits will be incorrect.
It takes about 7 seconds to run on my computer right now.
> 3 votes

---
Tags: popularity-contest, pi
---


title: Find the unique number

text:
# Question
Title: Find the unique number
I have read a question similar to this. I found it interesting, and difficult so I rephrased the question as a code golf. (that question is closed )

Challenge:

> In 1 million and 1 numbers, all the numbers having the duplicate except only one number . Write a program that can find this unique number.

Input form:

> a text file containing 1000001 integer seperated by space. The numbers are shuffled

Output form:

> a single number

Note: Using standard library functions to compare values is not allowed the (in case you intend to use something as `strcmp()` in c or anything similar in other languages) a simple algorithm that can achieve the job.

This is code golf, so the shortest code win. All languages are allowed. ( I prefer c/c x86 assembly if possible because i have no experience in any other language) add some explanation to your source code if possible.

Good luck.

# Answer
## Golfscript, 6 characters

```
~]{^}*

```

This simply XORs all numbers: assuming the input file consists of the numbers `a b b c c d d ...` in any order, this calculates `a^b^b^c^c^d^d^...` (XOR is commutative/associative, so the order of numbers doesn't matter). Since `x^x == 0`, this effectively leaves only the number that hasn't been duplicated.

Run it like this: `golfscript unique.gs < inputfile`
> 11 votes

# Answer
# Pyth, 10 characters

Note: Does not fail even if there are more than 2 copies of duplicated numbers.

```
JPw)'ocJNJ

```

Explanation:

```
JPw)    J=input.split()
'oJNJ   print first element of J sorted by count of element in J.

```
> 2 votes

---
Tags: code-golf
---


# Question
Title: Optimize paper folding to mitigate inkblots
Dark black ink has splattered all over your white sheet of printer paper! The obvious solution is to fold the paper so black and white parts meet and both become grey as the ink diffuses. Then unfold and refold until your paper is all equally grey.

Finding the best way to make these folds is your task in this coding challenge. This Pastebin contains four different sized grids of ones and zeros. Each grid represents a piece of ink splattered paper that you must turn grey. Zeros are paper and ones are ink.

In these grids, only horizontal and vertical folds along the spaces between lines and columns are valid. When a fold is made the pairs of overlapping values are averaged. Folds are done one at a time and always unfolded. Folds only change the ink distribution, not the size of the paper.

Rn denotes folding the left edge of the grid to the right, starting after the nth column. Dn denotes folding the top edge of the grid downward fold, starting after the nth row. (n is 1-indexed)

## Example

Given this grid

```
0 1 1 1
0 0 0 0
0 0 0 0

```

a D1 fold means "fold the entire top row down then unfold".

```
0 0.5 0.5 0.5
0 0.5 0.5 0.5
0   0   0   0

```

Then an R2 will produce

```
0.25 0.5 0.5 0.25
0.25 0.5 0.5 0.25
   0   0   0    0

```

and another R2 will not change anything.

## Goal

Your goal is to write an algorithm that finds the best ink-spreading folding sequence for each of the four grids using **exactly 8 folds** each time. The folds may be any combination of Rs or Ds.

**Scoring**

The score of your submission is the sum of your scores for each grid. A grid's score is the sum of the absolute differences between each of its values and its average (its sum divided by its area). Lower scores are better. A score of 0 is perfect, but is probably impossible in only 8 folds.

You must report your four 8-step folding sequences with your code in your answer. This is so we can verify your algorithm really works.

Please put them in this form:

```
20*20R1D2R3D4R5D6R7D8
40*20R1D2R3D4R5D6R7D8
40*40R1D2R3D4R5D6R7D8
20*80R1D2R3D4R5D6R7D8

```

Here is a Python script that will calculate your scores given your folding sequences.

Naturally you should not copy someone else's sequence submission. Sequences for each grid only belong to the person who first created them.

# Clarifications

* Ideally your algorithm will work well on any grid, though you can tailor it to these specific ones.
* You must submit your code with your sequence. To win you need the smallest-scoring set of 8-step folding sequences that has not already been posted, and also an algorithm that stands up to public scrutiny. Explain your code, don't obfuscate it.
* The grid should never contain negative numbers.
* Standard loopholes apply.

# Answer
# Python

Exhaustively tries different combinations of folds for the first few folds, then does the rest of the folds using a greedy approach.

The exhaustive approach is bounded within a reasonable range of folds in the center, such that it won't take forever, while not ignoring too many possible folds to yield a good minimum.

Ran using pypy on my macbook air.

Answers:

```
20*20D9R15R6D11R10R9D10R11
40*20D6D13D9R19R21R20D11D10
40*40D21R21R11D19R23R20D23D15
20*80D33D47D40R10D39D41R9R11

```

Outputs:

```
Exhaustive folds levels: 3
Percentage pruned from sides from exhaustive folds: 0.2
Time taken: 4.016076s
Score: 7.91125
20*20D9R15R6D11R10R9D10R11

Exhaustive folds levels: 3
Percentage pruned from sides from exhaustive folds: 0.2
Time taken: 28.529278s
Score: 16.34375
40*20D6D13D9R19R21R20D11D10

Exhaustive folds levels: 3
Percentage pruned from sides from exhaustive folds: 0.25
Time taken: 98.430465s
Score: 42.13
40*40D21R21R11D19R23R20D23D15

Exhaustive folds levels: 3
Percentage pruned from sides from exhaustive folds: 0.25
Time taken: 234.873787s
Score: 32.30875
20*80D33D47D40R10D39D41R9R11

```

Total Score: 7.91125 + 16.34375 + 42.13 + 32.30875 = 98.69375

Code:

```
import time, math
from collections import deque

numberOfFolds = 8 # Total number of folds

startTime = time.clock()

exec "grid = ("+"""
1 1 1 0 1 1 0 0 1 0 0 1 0 1 1 0 1 0 1 1
1 1 0 0 0 1 0 1 1 0 0 0 1 0 1 1 1 0 1 1
0 1 0 0 0 1 0 1 0 1 1 1 1 0 1 0 1 0 1 0
0 0 0 1 0 1 0 0 0 0 1 1 1 0 1 1 0 0 0 1
0 1 0 1 1 0 0 0 0 0 1 0 1 1 1 0 1 0 1 0
1 0 1 1 0 1 1 1 1 1 1 0 0 1 0 1 0 1 0 1
0 1 1 1 0 0 0 1 1 0 1 0 1 1 0 0 0 0 0 0
0 0 0 0 0 0 1 1 1 1 1 0 0 0 1 1 0 0 0 0
1 1 1 0 1 0 0 1 0 1 1 1 1 1 1 0 0 0 0 1
1 1 0 0 0 1 1 1 0 1 0 1 0 0 1 1 0 0 1 0
0 1 1 0 0 0 1 1 0 1 1 1 0 1 1 1 0 1 0 1
0 1 1 1 1 0 0 1 1 0 1 0 1 1 1 1 0 1 1 0
0 0 0 1 0 0 0 1 0 1 0 0 1 0 0 0 1 0 0 1
0 0 1 1 1 1 1 1 0 0 1 1 0 0 1 1 0 0 1 1
1 1 1 1 0 1 1 0 0 0 0 1 1 1 0 0 0 0 0 1
1 0 0 1 0 0 0 0 1 0 0 1 1 0 0 0 0 0 0 0
0 1 1 1 0 0 1 1 0 0 1 1 1 1 0 1 1 0 0 1
0 0 1 0 1 1 1 1 0 1 1 0 1 0 1 0 0 1 1 0
0 1 1 0 1 0 0 1 0 0 1 1 1 1 1 0 1 1 0 0
0 0 1 0 1 1 1 0 0 1 0 0 0 1 0 1 1 1 1 1
""".replace(" ",",").replace("\n","],[")[2:-2]+")"

def getAverage(grid):
    count = total = 0
    for j in grid:
        for i in j:
            count += 1
            total += i
    return total/float(count)

def getScore(grid, average):
    score = 0
    for j in grid:
        for i in j:
            score += abs(average-i)
    return score

def downFoldedGrid(grid, row, width, height, copy=True):
    if copy: grid = [r[:] for r in grid]
    foldRange = min(row, height-row)
    for j in xrange(foldRange):
        rowRef1 = grid[row+j]
        rowRef2 = grid[row-1-j]
        for i in xrange(width):
            rowRef1[i] = rowRef2[i] = (rowRef1[i] + rowRef2[i]) * .5
    return grid

def downFoldedScore(grid, score, average, row, width, height):
    foldRange = min(row, height-row)
    average2  = 2*average
    for j in xrange(foldRange):
        rowRef1 = grid[row+j]
        rowRef2 = grid[row-1-j]
        a = b = c = 0
        for i in xrange(width):
            a = rowRef1[i]
            b = rowRef2[i]
            c = a+b
            score += abs(average2-c) - abs(average-a) - abs(average-b)
    return score

def rightFoldedGrid(grid, column, width, height, copy=True):
    if copy: grid = [r[:] for r in grid]
    foldRange = min(column, width-column)
    for j in xrange(height):
        rowRef = grid[j]
        for i in xrange(foldRange):
            a = column+i
            b = column-1-i
            rowRef[a] = rowRef[b] = (rowRef[a] + rowRef[b]) * .5
    return grid

def rightFoldedScore(grid, score, average, column, width, height):
    foldRange = min(column, width-column)
    average2 = 2*average
    for j in xrange(height):
        rowRef = grid[j]
        a = b = c = 0
        for i in xrange(foldRange):
            a = rowRef[column+i]
            b = rowRef[column-1-i]
            c = a+b
            score += abs(average2-c) - abs(average-a) - abs(average-b)
    return score

def bestFoldsGreedy(grid, average, maxFolds, width, height):
    score  = getScore(grid, average)
    folds  = []
    append = folds.append
    for z in xrange(maxFolds):
        bestFold      = 0
        bestFoldScore = score
        bestFoldGrid  = grid
        for i in xrange(1, width): #Try all right folds
            foldScore = rightFoldedScore(grid, score, average, i, width, height)
            if foldScore < bestFoldScore:
                bestFold      = i
                bestFoldScore = foldScore
        for i in xrange(1, height): #Try all down folds
            foldScore = downFoldedScore(grid, score, average, i, width, height)
            if foldScore < bestFoldScore:
                bestFold      = -i
                bestFoldScore = foldScore
        if bestFold:
            append(bestFold)
            score = bestFoldScore
            if bestFold > 0: rightFoldedGrid(grid, bestFold, width, height, False)
            else:            downFoldedGrid(grid, -bestFold, width, height, False)
    return score, folds

# Get the height and width
height  = len(grid)
width   = len(grid[0])

# Transpose the grid if height > width for better locality of reference
transposed = False
if height > width:
    grid = [[grid[i][j] for i in range(height)] for j in range(width)]
    transposed = True
    height, width = width, height

# The exhaustive grids and folds attempted
exhaustiveGridsAndFolds = deque([(grid,[])])
popleft = exhaustiveGridsAndFolds.popleft
append  = exhaustiveGridsAndFolds.append

# Set the bounds to exhaustively test for
exhaustiveLevels   = 3
prunePadding       = [0.2, 0.25][width*height > 1000]
leftBound          = int(max(width*prunePadding, 1))
rightBound         = int(width*(1.0-prunePadding))
topBound           = int(max(height*prunePadding, 1))
bottomBound        = int(height*(1.0-prunePadding))

# Populate the exhaustive grids and folds
while 1:
    grid, folds = popleft()
    if len(folds) == exhaustiveLevels:
        append((grid, folds))
        break
    for i in xrange(leftBound, rightBound):
        if i not in folds:
            append((rightFoldedGrid(grid, i, width, height), folds+[i]))
    for i in xrange(topBound, bottomBound):
        if -i not in folds:
            append((downFoldedGrid(grid, i, width, height), folds+[-i]))

# Test all the exhaustive grids and folds greedily
average             = getAverage(grid)
bestFinalScore      = getScore(grid, average)
bestFinalFolds      = []
numberOfGreedyFolds = numberOfFolds-exhaustiveLevels
while exhaustiveGridsAndFolds:
    grid, exhaustiveFolds = popleft()
    finalScore, greedyFolds = bestFoldsGreedy(grid, average, numberOfGreedyFolds, width, height)
    if finalScore <= bestFinalScore:
        bestFinalScore = finalScore
        bestFinalFolds = exhaustiveFolds + greedyFolds

# Repeat the last fold till the total number of folds if needed
if len(bestFinalFolds) < numberOfFolds:
    bestFinalFolds += [bestFinalFolds[-1]]*(numberOfFolds-len(bestFinalFolds))

# Print the best result
foldsString = ""
down  = "D"
right = "R"
if transposed:
    down,  right  = right,  down
    width, height = height, width
for fold in bestFinalFolds:
    if   fold > 0: foldsString += right+str(fold)
    elif fold < 0: foldsString += down+str(-fold)
print "Exhaustive folds levels: " + str(exhaustiveLevels)
print "Percentage pruned from sides from exhaustive folds: " + str(prunePadding)
print "Time taken: " + str(time.clock()-startTime) + "s"
print "Score: " + str(bestFinalScore)
print str(width) + "*" + str(height) + foldsString

```
> 8 votes

# Answer
# C, 16.344 (4 minutes 33 seconds)

### Best moves found so far: D6,D13,R19,D9,D11,R21,D10,R20

Uses a mixture of Monte Carlo and hill climbing. Could be made to run much faster, I'm sure.

```
#include <stdio.h>
#include <stdlib.h>

/*

Best result so far: 16.344
D6,D13,R19,D9,D11,R21,D10,R20

real    4m33.027s
user    4m12.787s
sys 0m1.334s

*/

#define GRID_WIDTH   40
#define GRID_HEIGHT  20
#define GRID_SIZE    (GRID_WIDTH * GRID_HEIGHT)
#define NUM_FOLDS    8
#define MAX_VALUE    (1 << NUM_FOLDS)
#define TARGET_VALUE (MAX_VALUE / 2)

double score_grid(short *g) {
  int i, sum;
  for (i=sum=0; i<GRID_SIZE; i++) sum += abs(*g++ - TARGET_VALUE);
  return sum * 1.0 / MAX_VALUE;
}

void h_fold(short *g, int fold_row) {
  int x, y0, y1;
  if (fold_row<1 || fold_row>=GRID_HEIGHT) return;
  y1 = fold_row * GRID_WIDTH;
  y0 = y1 - GRID_WIDTH;
  while (y0>=0 && y1<GRID_SIZE) {
    for (x=0; x<GRID_WIDTH; x++) {
      g[y0+x] = g[y1+x] = (g[y0+x] + g[y1+x]) >> 1;
    }
    y0 -= GRID_WIDTH;
    y1 += GRID_WIDTH;
  }
}

void v_fold(short *g, int fold_col) {
  int y, x0, x1;
  if (fold_col<1 || fold_col>=GRID_WIDTH) return;
  x1 = fold_col;
  x0 = x1 - 1;
  while (x0>=0 && x1<GRID_WIDTH) {
    for (y=0; y<GRID_SIZE; y+=GRID_WIDTH) {
      g[y+x0] = g[y+x1] = (g[y+x0] + g[y+x1]) >> 1;
    }
    x0--;
    x1++;
  }
}

void print_grid(short *g) {
  int i=0, checksum=0;
  while (i<GRID_SIZE) {
    checksum += *g;
    printf("%3X",*g++);
    if ((++i) % GRID_WIDTH == 0) putchar('\n');
  }
  if (checksum != GRID_SIZE * TARGET_VALUE) printf("Bad total: %d\n",checksum);
}

void init_grid(short *g) {
  int i;
  static short *start_grid=0, *sg;
  if (!start_grid) {
    char *src = "11010110100011100000001000110001001101010111000100100100000101100000101111000010"
                "10110011111011111101101011111001000010101010110111000101000001011111101000011001"
                "10000111111001111011100101101001101100001110001101001011010011011110101000011100"
                "00110010100010100010110101001100110001100100111010000110100110001000110000111101"
                "01000001110000101000110101011011101010111110101010110000001011010010000011101000"
                "11111011111100100100100010111010111111000101011110000100111111111000110101101101"
                "00110100010111101111000011011010000110001001101010010101110010110111101001011111"
                "10110001101100001110010100110100010011011110100110000100100111101101000010011001"
                "00011100110100111101000000001000010100001101001011000101101001000100111100011010"
                "00010110001110011111100011101111011100111001110011111011010010000100101111101001";
    start_grid = malloc(GRID_SIZE * sizeof(short));
    for (i=0; i<GRID_SIZE; i++) start_grid[i] = (src[i]&1)<<NUM_FOLDS;
  }
  sg = start_grid;
  for (i=0; i<GRID_SIZE; i++) *g++ = *sg++;
}

double evaluate(int *moves) {
  short *grid;
  double score;
  int i, f;
  grid = malloc(GRID_SIZE * sizeof(short));
  init_grid(grid);
  for (i=0; i<NUM_FOLDS; i++) {
    f = moves[i];
    if (f>0) v_fold(grid,f);
    else h_fold(grid,-f);
  }
  score = score_grid(grid);
  free(grid);
  return score;
}

double optimize_folding(int *moves, double score) {
  int opt_cycle, i, which_fold, new_move, f1, f2, t;
  double s;

  for (opt_cycle=0; opt_cycle<1000; opt_cycle++) {
    for (i=0; i<NUM_FOLDS; i++) {
      which_fold = random() % NUM_FOLDS;
      do {
        if (random()&1) new_move = random() % (GRID_WIDTH-1) + 1;
        else new_move = -(random() % (GRID_HEIGHT-1) + 1);
      } while (moves[which_fold]==new_move);
      t = moves[which_fold];
      moves[which_fold] = new_move;
      s = evaluate(moves);
      if (s>score) moves[which_fold] = t;
      else score = s;
    }
    for (i=0; i<NUM_FOLDS; i++) {
      f1 = random() % NUM_FOLDS;
      do {
        f2 = random() % NUM_FOLDS;
      } while (f2==f1);
      t = moves[f1];
      moves[f1] = moves[f2];
      moves[f2] = t;
      s = evaluate(moves);
      if (s>score) {
        t = moves[f1];
        moves[f1] = moves[f2];
        moves[f2] = t;
      }
      else score = s;
    }
  }

  return score;
}

void show_moves(int *moves) {
  int i, m;
  for (i=0; i<NUM_FOLDS; i++) {
    m = moves[i];
    printf("%c%d%c",(m>0)?'R':'D',abs(m),((i+1)%NUM_FOLDS)?',':'\n');
  }
}

int main() {
  int i, j, moves[NUM_FOLDS], save_moves[NUM_FOLDS];
  double score, best_score = 1.0E+99;

  srandomdev();
  for (i=0; i<400; i++) {
    for (j=0; j<NUM_FOLDS; j++) {
            if (random()&1) moves[j] = random() % (GRID_WIDTH-1) + 1;
            else moves[j] = -(random() % (GRID_HEIGHT-1) + 1);
        }
        score = optimize_folding(moves, 1.0E+99);
        if (score<best_score) {
            best_score = score;
            for (j=0; j<NUM_FOLDS; j++) save_moves[j]=moves[j];
        }
    }
  printf("%.3lf\n",best_score);
  show_moves(save_moves);
  return 0;
}

```
> 5 votes

---
Tags: code-challenge
---


title: Brainfuck Sorting

text:
# Question
Title: Brainfuck Sorting
Write a program in brainfuck that accepts input of 4 ASCII characters as numbers (from 32 to 126) and outputs the numbers or ASCII equivalent sorted in ascending order.

Requirements: Your program should prompt the user for 4 characters that will be sorted by their ASCII value. All the inputs will be distinct. Any sorting algorithm can be used. Every cell is one byte, and the shortest code wins. If there is a tie, the code that uses the least memory cells wins.

Example input:

```
(i"G

```

Example output:

```
"(Gi

```

Helpful links: How to compare 2 numbers with brainfuck

If you have any questions please ask them in the comments.

I tried to write a program that solves this problem. It works, but it's so inefficient and lenghty (500+) that I don't want to post it here. If you bothered to go through the pain I did, you'll get a +1 from me.

# Answer
# 33 code bytes, 2n+3=11 n+4=8 memory cells

Edited: I can improve memory usage by keeping the count in only one cell.

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

```

EOF is 0, 8 bit wrapping memory (0+256=0)

## How it works

* Read all numbers
* Decrement each number, keep count of how many times you do this.
* When something hits zero, print the count
* Repeat until count rolls over.

## Details

Memory: 0(start padding),\[input\],...,count,0(padding),0 (more padding)

```
> (start padding)
,[>,] read input
+ count=1
[ while count !=0
    <[-<] decrement all inputs
    >[>] go to an input that was just decremented to zero, or padding
    > point to next input or more padding
    [ if not padding
         <- change the 0 to 255 so it doesn't stop the next decrement pass
         [>]<. point to and print count
         >> point to more padding
    ]
    <<+ increment count
]

```

## The old way

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

```

Memory plan:

```
0(padding),[input,count],[input,count],...,[0,0](dummy input & count)

```

Commented code:

```
> get some elbow room
,[->+>,] read each number & do an initial count/decrement pass so count is not 0
< point at last count
[ while count !=0 (didn't roll over)
    [+<-<] decrement each number and increment each count
    > point at first input
    [>>] go to the first 0-ed input (probably the dummy input)
    > point at count or dummy count
    [ if not the dummy count
        . print it
        [>]> go to the dummy count (no other inputs will be 0 because they are all unique)
    ]
    << point at last count
]

```
> 20 votes

# Answer
# 94 bytes code, 2n+5 = 13 bytes memory

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

```

EOF is zero.

Example:

```
$ echo -n '(i"G'|beef sort.bf ;echo
"(Gi

```
> 6 votes

# Answer
# 90 63 bytes code, 769 513 bytes memory

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

```

This works much like the old way, but doesn't initialize memory with numbers. Instead, it keeps track of which location it is checking and prints that number.

# The old way

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

```

EOF is 0, 255+1 = 0

## How it works

Step 1: Prep the memory to look like: 0,0,0,\[1,0,0\],\[2,0,0\],...,\[255,0,0\],0

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

```

Step 2: Read the input and increment memory at (3+input\*3+2). Reading space (32) results in 0,0,0,\[1,0,0\],...,\[32,0,1\],...

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

```

Step 3: Read through the memory and output any number that has a non-zero value two cells to the right of it. Stop after 255. This prints out the characters in ascending order.

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

```
> 6 votes

---
Tags: code-golf, brainfuck
---


# Question
Title: Reduce html to n characters while keeping the formatting
Almost every language has a built-in function that can split a string at a given position. However, as soon as you have html tags in the string, the built-in function will not work properly.

Your task is to write a program or function which splits a string at the nth character but does not count characters of html tags and will output a valid html. The program must keep the formatting. Spaces outside the html tags may be counted or not counted, as you wish, but must be preserved. You can, however, exchange multiple consecutive spaces into a single space.

Input:

1. the string
2. the position to split at (0-based)

These can be taken as program or function arguments or can be read from the standard input.

Output: The split string which can be returned or written to the standard output.

The input will be valid html, it won't contain any entities (such as ` `). Tags that are opened after the character limit should be omitted from the output (see the last example).

Example:

Input: `<i>test</i>`, 3
Output: `<i>tes</i>`

Input: `<strong><i>more</i> <span style="color: red">complicated</span></strong>`, 7
Output: `<strong><i>more</i> <span style="color: red">co</span></strong>`

Input: `no html`, 2
Output: `no`

Input: `<b>no</b> <i>html root</i>`, 5
Output: `<b>no</b> <i>ht</i>`

Input: `<b>no img</b><img src="test.png" />more text`, 6
Output: `<b>no img</b>`

You can use any language and the standard library of the given language. This is code golf, shortest program wins. Have fun!

# Answer
> 2 votes
**This answer is no longer valid with the latest rule.**

# Javascript (*ES6*) 94 91

```
f=(s,l)=>s.split(/(<[^>]+>)/).map(x=>x[0]=='<'?x:[l-->0?y:''for(y of x)].join('')).join('')

```

```
f('<strong><i>more</i> <span style="color: red">complicated</span></strong>', 7);
// '<strong><i>more</i> <span style="color: red">co</span></strong>'

```

Ungolfed:

```
f=(s,l)=>
    s.split(/(<[^>]+>)/). // split string s by <*>, capture group is spliced into the array
    map(x=> // map function to every item in the array
        x[0]=='<'? // if first character is a <
            x // don't modify the string
        : // else
            [ // array comprehension
                for(y of x) // for every character y in x
                    l-->0? // if l > 0 (and decrement l)
                        y // character y
                    : // else
                        '' // empty string
            ].join('') // join characters in array
        ).
    join('') // join all strings in array

```

# Answer
> 2 votes
# Rebol - 252 chars

```
c: complement charset"<>"f: func[s n][t: e: 0 to-string collect[parse s[any[(m: 0)copy w[["</"some c">"](-- t)|["<"some c"/>"]|["<"some c">"](++ t)| any c(m: 1)](if e = 0[if m = 1[w: copy/part w n n: n - length? w]keep w]if all[n <= 0 t = 0][e: 1])]]]]

```

Ungolfed with comments:

```
c: complement charset "<>"

f: func [s n] [
    t: e: 0             ;; tag level (nesting) & end output flag
    to-string collect [
        parse s [
            any [
                (m: 0)                            ;; tag mode
                copy w [
                      ["</" some c ">" ] (-- t)   ;; close tag
                    | ["<"  some c "/>"]          ;; self-closing / void elements
                    | ["<"  some c ">" ] (++ t)   ;; open tag
                    | any c (m: 1)                ;; text mode
                ] (
                    ;; flag not set so can still output
                    if e = 0 [
                        ;; in text mode - so trim text
                        if m = 1 [
                            w: copy/part w n
                            n: n - length? w
                        ]
                        keep w
                    ]

                    ; if all trimmed and returned to flat tag level then end future output
                    if all [n <= 0  t = 0] [e: 1]
                )
            ]
        ]
    ]
]

```

Examples in Rebol console:

```
>> f "<i>test</i>" 3
== "<i>tes</i>"

>> f {<strong><i>more</i> <span style="color: red">complicated</span></strong>} 7
== {<strong><i>more</i> <span style="color: red">co</span></strong>}

>> f {no html} 2
== "no"

>> f {<b>no</b> <i>html root</i>} 5
== "<b>no</b> <i>ht</i>"

>> f {<b>no img</b><img src="test.png" />more text} 6
== "<b>no img</b>"

>> f {<i>a</i><b></b>} 1
== "<i>a</i>"

>> f {<strong><i>even</i> <span style="color: red">more <b>difficult</b></span></strong>} 14
== {<strong><i>even</i> <span style="color: red">more <b>diff</b></span></strong>}

>> f {<strong><i>even</i> <span style="color: red">more <b>difficult</b></span></strong>} 3
== {<strong><i>eve</i><span style="color: red"><b></b></span></strong>}

```

# Answer
> 0 votes
**(IE) JS - 135**

`function f(t,n){b=document.body;b.innerHTML=t;r=b.createTextRange();r.moveStart("character",n);r.select();r.execCommand('cut');return b.innerHTML}`

Now I feel dirty. But need to start removing all those chars...

```
function f(t,n)
{b=document.body;b.innerHTML=t;r=b.createTextRange();r.collapse();r.moveEnd("character",n);
r.select();return r.htmlText}

```

Disclaimer:

* run in IE console

# Answer
> 0 votes
Ruby... Very unrubylike with loops

```
def split(str,n)

  i = current = 0
  return_str = ""

  while i < n
    if str[current] == "<"
      while str[current] != ">"
        return_str.concat str[current]
        current += 1
      end
      return_str.concat str[current]
      current += 1
    else
      return_str.concat str[current]
      i += 1
      current += 1
    end
  end

  while current < str.length
    if str[current] == "<"
      while str[current] != ">"
        return_str.concat str[current]
        current += 1
      end
      return_str.concat str[current]
      current += 1
    end
    current += 1
  end

  return_str + str[current..-1]
end

```

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


# Question
Title: Solve this math problem in smallest amount of code
Here I found a cool math problem. I thought you could write some golfed code to compute all answers between x and x.(there is an infinite amount).

Problem: Once upon a time, and old lady went to sell her vast quantity of eggs at the local market. When asked how many she had, she replied:

Son, I can't count past 100 but I know that:

* If you divide the number of eggs by 2 OR 3 OR 4 OR 5 OR 6 OR 7 OR 8 OR 9 OR 10, there will be one egg left.
* If you divide the number of eggs by 11 there will be NO EGGS left!

How many eggs did the old lady have?

i answered the question on that thread with:

```
    public static void main(String... args)
    {
        for (int i = 0; i < 1000000000; i++)
        {
            boolean a = true;
            for (int x = 2; x < 11; x++)
            {
                if (i % x != 1) a = false;
            }
            if (i % 11 != 0) a = false;
            if (a) System.out.println(i);
        }
    }

```

Catch:
If some sharp eyed person noticed, you could start at 25201 and keep adding 27720 to get to the next one. You can NOT use this machanic to answer the question. So dont post something like this:

```
public class test {
public static void main(String... args) {
    long l=25201;
    while(true){
        System.out.println(l);
        l+=27720;
    }
}
}

```

# Answer
> 1 votes
# R, 37 chars

```
n=121;while(!all(n%%2:10==1))n=n+11;n

```

**Edit**: if the question was: "Found all possible answers between x and y" then it's **65** characters as a function:

```
f=function(x,y)(x:y)[!rowSums(outer(x:y,2:10,`%%`)!=1)&!x:y%%11]

```

Example:

```
> f(1,1e5)
[1] 25201 52921 80641

```

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


title: Draw with your CPU

text:
# Question
Title: Draw with your CPU
I have come across an article where students used network traffic to draw their university on the country's IPv6 graph. \[image\]

**Your goal** is simple to tell, but hard to implement. *Draw* the text MAIL (as it is one of the few words that can be read on a 1D graph) on the CPU graph.

It should look something like this:

# Elaborating a bit more on what qualifies:

* The code does not need to be cross-platform (so you won't need unknown APIs to deal with).
* You may capture it in any general CPU usage utility that you have.
* The graph looks a bit worse on a different machine: I trust you this time.
* The base CPU usage % must be continuous, so if you generate a random wave and highlight something that looks like the word MAIL, it's obviously cheating.
* You may choose the maximum load to use, but it has to be substantial enough to clearly see it.
* You must follow the linearity of the example. (For M it looks like this: base %, then sudden increase to the specified max, fall gradually to a lower %, rise back to max and sudden drop to the base % again.)
* If it's unreadable, voters will notice after all.

Standard loopholes apply. Post the images too!

# Answer
## Python, 143

```
from time import*
while 1:
 sleep((ord('00012345654321000~~~D:6300036:D~~~000~~~000DDDD~~~~~'[int(time())%52])-48)*0.001);x=10**5
 while x:x-=1

```

Each character of the string corresponds to one second of activity, from the ASCII character `0` (max load) through to `~` (very light load). The program runs on a time-synchronised loop, so you can run multiple instances for nicer results.

I used Python 2.7.6 on OS X with an Intel Core i7, but it should work on other computers with a bit of tweaking (adjust the `0.001`). The screenshot below was taken with significant background activity.

**Update -** I was able to produce a clearer graph with `time()/10` and a lower update frequency:

And finally, here's a more golfed version (**123 bytes**) and its result:

```
from time import*
while 1:
 sleep((ord('002464200~~A5005A~~00~~00DDD~~'[int(time()/2)%30])-48)*0.001);x=10**5
 while x:x-=1

```
> 123 votes

# Answer
# Python, ~~358~~ ~~281~~ ~~268~~ ~~221~~ 194 bytes

Monochrome is *so* last year. This uses multiple processes and syscalls to achieve **two color** CPU graphs!

```
import os,time
A='%-99o'%int('t12q2lxqkap48euoej9429cstbnazl63ubyryteo49u',36)
for i in'0123456':
 t=os.fork()
 while t<1:T=int(time.time())%50;(time.sleep,(id,os.urandom)[i<A[T+49]])[i<A[T]](1)

```

Output from Activity Monitor (OS X 10.9):

>

Output from MenuMeters:

>

All outputs were generated with an update speed of 1s. No significant background tasks were running, though this output quite easily beats out any single-threaded CPU task.

This code assumes you have 8 cores. It should be pretty easy to modify for fewer/more. It is *portable* to Linux/UNIX systems (though it has only been tested on OS X), and should produce the same two-color output for any CPU monitor that can distinguish User from System CPU time.

Essentially, this works by forking off seven processes, each of which will choose to spend 1 second sleeping, spinning in usermode, or spinning the kernel. Spinning in kernel mode is achieved by requesting large globs of data from `/dev/urandom`, which forces the driver backing `/dev/urandom` to spend a lot of "system" CPU cycles.

EDITED \[07/21\]: Shortened significantly by using `fork()` instead of `multiprocessing.Process` (`/dev/urandom` only works on \*NIX systems anyway so this doesn't reduce portability). Note however that the program now spawns *background* tasks; you may have to `killall Python` (or similar) to get rid of the CPU-eaters.

---

I couldn't resist implementing a few more letters. I got 16 letters, plus a few symbols:

The complete alphabet is "ACDFHILMNOPTUVWY", with symbols ".\_~/\\". There are probably lots more characters that can be represented.

Entirely ungolfed code for the extra letters:

```
from time import*
from multiprocessing import*

chars6 = {
'A': ('123456654321',
      '000123321000'),
'C': ('344556666666',
      '321110000000'),
'D': ('666666655443',
      '000000011123'),
'F': ('66666666666666',
      '00002222244444'),
'H': ('666664444466666',
      '000002222200000'),
'I': ('66666',
      '00000'),
'L': ('666662222222',
      '000000000000'),
'M': ('6665544334455666',
      '0004321001234000'),
'N': ('66665544336666',
      '00003322110000'),
'O': ('3445556666555443',
      '3221110000111223'),
'P': ('666666666555',
      '000003333444'),
'T': ('777776666677777',
      '444440000044444'),
'U': ('6666322236666',
      '4211000001124'),
'V': ('66654322345666',
      '33321000012333'),
'W': ('66542466424566',
      '43210133101234'),
'Y': ('66665433456666',
      '44333000033344'),
'_': ('1111111111',
      '0000000000'),
' ': ('000',
      '000'),
'.': ('12221',
      '10001'),
'~': ('44445544334444',
      '11223322112233'),
'/': ('2234566',
      '0012344'),
'\\': ('6654322',
       '4432100'),
}

s = 'ANCHOVY '
A = '000'.join(chars6[t][0] for t in s)
B = '000'.join(chars6[t][1] for t in s)

t=time()
f=open('/dev/urandom')
def F(n):
 while 1:T=int(time()-t)%len(A);[sleep,[].count,lambda x:f.read(4**9)][(n<int(A[T]))+(n<int(B[T]))](1)
for i in range(7):Process(target=F,args=(i,)).start()
F(7)

```
> 261 votes

# Answer
# C (Intel Core Duo + OS X/Darwin), 248 bytes

```
#include <unistd.h>
#include <mach/mach_time.h>
#define M mach_absolute_time()
main(){char*s="JJJIHGFGHIJJJ@BDFHJJJHFDB@JJJJ@JJJJBBBBBBB";uint64_t i,t,y=1;for(;*s;s++){
for(i=40;i;i--){for(t=M+(*s&15)*9090909;t>M;)y*=7;usleep((11-(*s&15))*9091);}}}

```

This code is about as portable as the Great Pyramid of Cheops. Sorry about that. The values returned from `mach_absolute_time()` are hardware-dependent, but on my machine the value increments about once per nanosecond.

Here's the result:

There are two graphs because the processor has two cores. I set the maximum CPU load to about 90% because the process is liable to switch between cores whenever I call `usleep()`. With a 100% load, the process is chained to one core and the results are illegible (see this, for example)
> 135 votes

# Answer
## Ruby, 150 characters

```
a=(0..15).map{|i|[0.9-3*i*=0.02,i]}
[9,*a[0,11],*(z=a.reverse)[5,11],11,*z,*a,2,11,6,*[0.2]*9].map{|x,y|c=Time.now
1until Time.now-c>x/3
sleep y||x%3}

```

This isn't all that short so far, but in my opinion the output's rather nice, so I figured I'd post this anyway. As with most other solutions, you may have to pin the Ruby process to a certain core by prefixing it with `taskset -c $core`.

The code is a simple combination of spinning/sleeping for a certain amount of time, which *should* make it somewhat portable. Smooth gradients are created by varying the ratio of spin/sleep time.

Lowering the CPU sampling frequency makes the edges look a bit better:

By adding a few more letters to the alphabet (`AILMNUVW` are somewhat recognizable), we can also write some other words:

These pictures were generated with the following code:

```
def gradient num_samples, direction, base = 0.3, increment = 0.02, scale = 1
    range = [*0..num_samples]

    samples = case direction
        when :up then range.reverse
        when :down then range
        when :updown then range.reverse + range
        when :downup then range + range.reverse
    end

    samples.map{|i|
        i *= increment
        [base - scale * i, i]
    }
end

# letters are defined as a series of pairs of (spin-time, sleep-time)
# with the time in seconds
THIN_A = gradient(15, :updown, 0.2, 0.2/15)
A = gradient(15, :updown)
I = 2,0
L = 1.5,0, [[0.1,0.2]]*9
M = 2,0, gradient(9, :downup), 2,0
N = 1,0, gradient(9, :down), 2,0
U = 1,0, gradient(9, :downup, 0.1, 0.03, 0.1), 1,0
V = 0.5,0, gradient(12, :downup, 0.25, 0.02), 0.5,0
W = 0.5,0, [gradient(12, :downup, 0.25, 0.02)]*2, 0.5,0

[A,I,L,M,N,U,V,W].map{|i|
    # add 2 second pause after each letter
    i + [0,2]
}.flatten.each_slice(2){|x,y|
    # spin, then sleep
    c = Time.now
    1 until Time.now-c > x
    sleep y
}

```

Words that can be written with the implemented letters can be found with

```
grep -E '^[aijlmnuvw]+$' /usr/share/dict/words

```
> 105 votes

# Answer
## Python, on Intel Pentium 4 3.0Ghz, 180 166 145 141 138 bytes

Call with `taskset -c 0 python cpu_graph_drawer.py`.

`taskset` is needed to restrict the process to use only one CPU/core (hyperthreading in my case.)

```
from time import*;c=clock
a=[(3,.8),(3,5),(4,5),(1.3,5),(1.3,0)]
a.extend([(.1,.2)]*10)
for x,y in a:
    t=c()
    while c()-t<x:pass
    sleep(y)

```

Result isn't that great.
> 48 votes

# Answer
# Java 8, 482 characters

Every character in the String means number of threads, that will be utilized. Image taken on Intel Core i3 (2 cores / 4 threads).

```
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Mail{
public static void main(String[] args) throws InterruptedException{
Thread.sleep(15000);
for(char c:"123432234321000012343210000444000044441111111".toCharArray()){
ExecutorService executorService = Executors.newScheduledThreadPool(4);
for(int i=1;i<c-48;i++)executorService.execute(()->{while(!Thread.interrupted());});
Thread.sleep(1500);
executorService.shutdownNow();
}}}

```

**Edit**: more golfed version (322 chars), same functionality:

```
import java.util.concurrent.*;
class M{
public static void main(String[]a)throws Exception{
for(int c:"123432234321000012343210000444000044441111111".toCharArray()){
ExecutorService s=Executors.newFixedThreadPool(4);
while(c>48){c--;s.execute(()->{while(!Thread.interrupted());});}
Thread.sleep(1500);
s.shutdownNow();
}}}

```
> 46 votes

# Answer
# C, 78 bytes

You never said we couldn't accept user input, sooo..

```
#include <unistd.h>
int main(){int x=0;for(;x<1<<26;++x);read(0,&x,1);main();}

```

This program reads from standard in and every time it reads a character it executes a gratuitous CPU wasting for loop, then calls main again. You control the amount of CPU time it uses by spamming the enter key at different speeds.

I ran this on an intel i3 4130T, which is a reasonably new processor. But your mileage may vary, if it's using more or less CPU time than is practical for you to observe, try playing with the shift amount in the delay loop.

My program is awesome because it:

* is mostly cross platform, it should work with very little fiddling on any \*nix
* defeats the question
* great endgame play

After a few tries I produced a graph that looked like this:
> 23 votes

---
Tags: code-golf
---