# Question
Title: Write a function that tells you which TWO of its lines has been removed
In my previous code challenge, I asked you to write a function that tells you which of its lines has been removed.

The instructions were:

> Write a function that contains five lines.
>
> If you run the function as-is, it should return 0.
>
> If you remove any one of the five lines and run the function, it should tell you which of the lines has been removed (e.g., if you remove the final line it should return 5).

Now, let's try something a teensy bit more difficult.

Follow the same rules as above, but this time, the function should return an array telling you which TWO lines have been removed.

So, for instance, if I remove lines 1 and 5, the return value should be \[1,5\], and if I remove lines 3 and 4, the return value should be \[3,4\].

Again, if no lines are removed, the function should return 0. Bonus points if you can also handle the one-line-removed case, but it's not strictly necessary that you do so.

Can you make use of helper functions? Yes, but only if you have to. A single self-contained function that pulls this off is the ideal.

As with the last challenge, the highest upvoted solution wins. I'll pick the winner in a week, or sooner if no new submissions have been received in 24 hours.

# Answer
> 16 votes
# Perl

```
sub foo {
    @a = (2..5);
    @a = grep $_ != 2, (@a ? @a : (1..5));
    @a = grep $_ != 3, (@a ? @a : (1..5));
    @a = grep $_ != 4, (@a ? @a : (1..5));
    @a = grep $_ != 5, (@a ? @a : (1..5));
}

```

This actually works for any number of lines removed (as long as it's not *all* the lines, that is), and can be trivially extended to more than 5 lines. No helper functions are used, and it even uses only one statement per line. It relies on the fact that, in the absence of an explicit `return` statement, the return value of a Perl function is the value of the last statement in it.

Note that (in list context) this code returns an empty list rather than the number 0 if no lines have been deleted. This could be fixed (e.g. by appending "`@a ? @a : 0;`" to the last line), but would make the code uglier. In any case, in *scalar* context it *does* return the number of deleted lines, which will be 0 if no lines have been removed. ;-)

# Answer
> 9 votes
# Ruby

Similar to the Perl version, but in Ruby. I return 0 if no lines are deleted as requested, but I agree it makes the code uglier and doesn't quite make sense as a return value.

```
def which_lines_removed(arr = [*1..5])
  arr -= [1]
  arr -= [2]
  arr -= [3]
  arr -= [4]
 (arr -= [5]).empty? ? 0 : arr
end

```

If an empty array is acceptable as the return value when no lines are deleted, the code looks like this:

```
def which_lines_removed(arr = [*1..5])
  arr -= [1]
  arr -= [2]
  arr -= [3]
  arr -= [4]
  arr -= [5]
end

```

Both methods work for any number of lines deleted between 0 and 5.

# Answer
> 4 votes
# JavaScript, 152 characters golfed

```
function t() {
    var fa = (f + '').match(/\d/g)
    var ra = []
    for (var i = 0; i < 5; i++) {
        if (fa.indexOf(i + '') < 0) ra.push(i + 1)
    }
    return ra
}

function f() {
    0; return t()
    1; return t()
    2; return t()
    3; return t()
    4; return t()
}

```

Golfed:

```
function t(){for(a=[],i=0;++i<5;)if((f+'').indexOf(i)<0)a.push(i+1);return a}function f(){
return t(0)
return t(1)
return t(2)
return t(3)
return t(4)
}

```

Self contained (but ugly):

```
function f() {
    0; var ra = []; for (var i = +![]; i < 5; i++) if ((f + '').match(/\d/g).indexOf(i + '') < +![]) ra.push(i); return ra
    1; var ra = []; for (var i = +![]; i < 5; i++) if ((f + '').match(/\d/g).indexOf(i + '') < +![]) ra.push(i); return ra
    2; var ra = []; for (var i = +![]; i < 5; i++) if ((f + '').match(/\d/g).indexOf(i + '') < +![]) ra.push(i); return ra
    3; var ra = []; for (var i = +![]; i < 5; i++) if ((f + '').match(/\d/g).indexOf(i + '') < +![]) ra.push(i); return ra
    4; var ra = []; for (var i = +![]; i < 5; i++) if ((f + '').match(/\d/g).indexOf(i + '') < +![]) ra.push(i); return ra
}

```

Basically exploits function `toString` by numbering each line. Note that you actually have to remove the line because of this (commenting it out will not work).

This actually works for **any number of lines removed**! It will return an array of the lines removed, or an empty array if none have been removed. (I could easily change that to return zero (by replacing `return ra` with `return ra || 0`), but I like the empty array solution since it would be more useful in the real world.)

For example, removing the first line returns `[1]`, and removing everything but the first line returns `[2,3,4,5]`. (Of course, it doesn't work if you remove all lines `;-)`)

# Answer
> 3 votes
## Ruby

```
def f
    a = [ 2, 3, 4, 5 ]
    defined?(a) ? a = a.select { |num|    num != 2 } : a = [ 1, 3, 4, 5 ]
    defined?(a) ? a = a.select { |num|    num != 3 } : a = [ 1, 2, 4, 5 ]
    a = a.select { |num|    num != 4 }
    (a = a.select { |num|    num != 5 }) == [] ? a = 0 : a
end

```

How this works: my idea was: create an array, and on each line, remove a specific value. So, on the first line, I actually have the array `[ 1, 2, 3, 4, 5]`, with the element `1` removed. At the second line, if `a` is already defined, remove the element `2`. Otherwise, create a new array with the element `2` removed. Do the same for line 3. At line 4, you can be sure that there is already an array created, so just remove element `4`. At line 5, first remove element `5`, and if `a` is then an empty array, return `0`. Otherwise, return `a`.

# Answer
> 3 votes
# Python

```
f=lambda:{1,2,3,4,5}-{
1,
2,
3,
4,
5,
} or 0

```

Returns 0 if no line is removed, otherwise returns the removed lines. You can remove 1 to 5 lines, except the 0th and 6th line ;-).

# Answer
> 2 votes
## JavaScript, self-contained, works for 0, 1, 2 removed lines (~~607~~ ~~315~~ 186 chars)

## live demo

Abusing JS variable hoisting and global leaking, like in the other challenge :)

```
function(r){
r.shift();
r.splice(r.indexOf(2),1)
r.splice(r.indexOf(3),1);a=b=1;if(this.a&&this.b)return r
var a;r.splice(r.indexOf(4),1);b=1;if(this.b)return r
var b;r.pop();return r[0]?r:0
}

```

to be called with the array \[1,2,3,4,5\] as parameter.

**315 chars**

```
function(r){
var a;
var b;
var c;a=1;b=2;d=4;e=5;for(i in(z="abde".split("")))if(y=this[z[i]])r.push(y);return r.length?r:0
var d;a=1;b=2;c=3;e=5;for(i in(z="abce".split("")))if(y=this[z[i]])r.push(y);return r.length?r:0
var e;a=1;b=2;c=3;d=4;for(i in(z="abcd".split("")))if(y=this[z[i]])r.push(y);return r.length?r:0
}

```

to be called with an empty array as parameter.

**non-golfed version**

(also works for 3 and 4 lines removed):

```
function(r){
var a;b=c=d=e=1;if(this.b)r.push(2);if(this.c)r.push(3);if(this.d)r.push(4);if(this.e)r.push(5);return r.length?r:0;
var b;a=c=d=e=1;if(this.a)r.push(1);if(this.c)r.push(3);if(this.d)r.push(4);if(this.e)r.push(5);return r.length?r:0;
var c;a=b=d=e=1;if(this.a)r.push(1);if(this.b)r.push(2);if(this.d)r.push(4);if(this.e)r.push(5);return r.length?r:0;
var d;a=b=c=e=1;if(this.a)r.push(1);if(this.b)r.push(2);if(this.c)r.push(3);if(this.e)r.push(5);return r.length?r:0;
var e;a=b=c=d=1;if(this.a)r.push(1);if(this.b)r.push(2);if(this.c)r.push(3);if(this.d)r.push(4);return r.length?r:0;
}

```

to be called with an empty array as parameter.

# Answer
> 2 votes
**JavaScript:**

```
var f = function(){
    1
    2
    a=[];for(i=0;i++<6;){if((f+'').indexOf(i)<0){a.push(i)}}return a.length?a:0;3
    a=[];for(i=0;i++<6;){if((f+'').indexOf(i)<0){a.push(i)}}return a.length?a:0;4
    a=[];for(i=0;i++<6;){if((f+'').indexOf(i)<0){a.push(i)}}return a.length?a:0;5
}

```

fiddle

# Answer
> 2 votes
# Javascript

```
(function (i){

i += .1;     // line 1
i += .02;    // line 2
i += .003;   // line 3
i += .0004;  // line 4
i += .00005; // line 5

return (Math.round((.12345-i)*100000)/100000+'').match(/([1-5])/g) || 0 })(0)

```

Call it what you like, but I think it's *pretty*.

Lets you know which lines were removed (1 or more), or 0 if no lines are removed. All 5 lines **can** be removed.

**EDIT:**

Because it was brought to my attention that my code might actually consists of 6 lines, and is in violation of the rules, I adjusted it to the following:

```
(Math.round((.12345 - (new (function(){

    this.i = isFinite(this.i) ? this.i + .1 : .1 ;
    this.i = isFinite(this.i) ? this.i + .02 : .02;
    this.i = isFinite(this.i) ? this.i + .003 : .003;
    this.i = isFinite(this.i) ? this.i + .0004 : .0004;
    this.i = isFinite(this.i) ? this.i + .00005 : .00005;

})().i || 0) )*100000)/100000+'').match(/([1-5])/g) || 0

```

The same applies -- it will return an array of removed lines ranging from 1-**All** or 0 if none.

# Answer
> 1 votes
# Python

```
def function(a = [1,2,3,4,5]):
    delete(a, len(a)-5)#1
    delete(a, len(a)-4)#2
    delete(a, len(a)-3);print a if len(a)==2 else '',#3
    delete(a, len(a)-2);print a if len(a)==2 else '',#4
    delete(a, len(a)-1);print a if len(a)==2 else '',#5

def delete(a, i):
    del a[i]
    return a

```

It works for all lines - but only if two are deleted. If only one line is deleted then it will print the deleted line and line 5. If too many lines are deleted it won't print anything.

This uses a helper function because the del keyword can't be used in a line with a ;(as far as I know)

Basically, each line deletes itself in the array that is declared in the constructor, then if enough lines have been deleted the array is printed.

This function misses the spec in two ways:

1. it doesn't print 0 if it is run as-is(it assumes the last two lines have been commented and so prints 4, 5
2. It assumes that `print` and `return` are interchangeable

# Answer
> 1 votes
# Common Lisp

```
(defun which-lines-are-removed (&aux (x (list 1 2 3 4 5)))
  (setq x (remove-if #'(lambda (x) (eql x 1)) x))
  (setq x (remove-if #'(lambda (x) (eql x 2)) x))
  (setq x (remove-if #'(lambda (x) (eql x 3)) x))
  (setq x (remove-if #'(lambda (x) (eql x 4)) x))
  (setq x (remove-if #'(lambda (x) (eql x 5)) x))
)

```

It works for removal of 1-4 lines. If you remove all lines it will return the same as if you remove none.

NB: Having ending parenthesis on it's own line is considered bad style, but since other languages has `end` and `}` I assume it is allowed.

# Answer
> 1 votes
# Déjà Vu

Works for removing any number of lines (as long as you leave at least one line)

```
local line n:
    try:
        dup
    catch stack-empty:
        dup set{ 1 2 3 4 5 }
    delete-from swap n

func which-gone:
    line 1
    line 2
    line 3
    line 4
    line 5

```

# Answer
> 0 votes
# R

A simple version (not foolproof as you will get an error if you remove line 5):

```
doit <- function() setdiff(1:5, c(
       1,
       2,
       3,
       4,
       5
    ))

```

And a foolproof version:

```
doit<-function() setdiff(1:5, scan(text="
1
2
3
4
5
"))

```

It works with any number of lines removed (except if you remove all the lines), and can easily be extended to more than 5 lines. Running it "as is" will return `integer(0)` which is conceptually similar to returning just `0`. Returning an actual 0 would make it uglier and longer but would not be complicated.

Finally, a version using magic:

Helper function:

```
dysfunction <- function(E){
    FUN <- function(){}
    e <- substitute(E)
    e[[1]] <- as.name("list")
    nb <- quote(setdiff(as.list(1:5), x))
    nb[[3]] <- e
    body(FUN) <- nb
    FUN
    }

```

The actual function:

```
df <- dysfunction({
1
2
3
4
5
})

```

# Answer
> 0 votes
# R

I have another version in R which I think is better (but uses a helper function):

```
trick <- function(sym, value) {
  assign(sym, value, envir=parent.frame())
  values <- unlist(as.list(parent.frame()))
  if(length(values)==5) 0 else which(!1:5 %in% values)
}

reportRemovedLines <- function(){
  trick("a", 1)
  trick("b", 2)
  trick("c", 3)
  trick("d", 4)
  trick("e", 5)
}

```

Or one can avoid using the helper function by defining it as a default argument (works identically but is less readable -- however, it does not use a "separately defined" helper function):

```
funnyVersion <- function(trick = function(sym, value) {
  assign(sym, value, envir=parent.frame())
  values <- unlist(as.list(parent.frame()))
  if(length(values)==5) 0 else which(!1:5 %in% values)
}){
  trick("a", 1)
  trick("b", 2)
  trick("c", 3)
  trick("d", 4)
  trick("e", 5)
}

```

Both `reportRemovedLines()` and `funnyVersion()` work with any number of lines removed - except if you remove all lines (in that case, they will return `NULL`). They actually *return* the line numbers, not just print them - as in R, the value of the last expression evaluated within a function will automatically be returned.

How does it work? The trick is in the `trick` function which takes all objects from its "parent environment" (i.e., environment of the function that calls it), puts their values together in a vector, and returns, which values from 1 to 5 are not represented.

# Answer
> 0 votes
## JavaScript (136/166 chars)

A smaller version with some values declared at the beginning:

```
function(){b=[1,2,3,4,5],i=0
    b.splice(0,1);i++
    b.splice(1-i,1);i++
    b.splice(2-i,1);i++
    b.splice(3-i,1);i++
    b.splice(4-i,1);i++
return b}

```

A self-contained version (you don't need to pass anything - the b argument is there so I can check if b is defined with `||`)

```
function(b){
    b=[2,3,4,5],i=1
    b=b||[1,2,3,4,5],i=i||0,b.splice(1-i,1);i++
    b=b||[1,2,3,4,5],i=i||0,b.splice(2-i,1);i++
    b.splice(3-i,1);i++
    b.splice(4-i,1);i++
return b}

```

Yes, both have `return` statements, but that is only fair if I am competing with languages with implicit return.

# Answer
> 0 votes
**C++**

```
void function(int & i)
{
        i=i|1;
        i=i|2;
        i=(i|4);
        i=(i|8);
        i=(i|16);
}

int[] func2(int i)
{
    int arr[]={0,0};
    int k=0,l=1;
    for(int j=1;j<=16;j*=2,l++)
    {
        if((i&j)==0)
        {
             arr[k++]=l;
        }
    }
    return arr;
}

```

How to use: call the function with i and use func2 for understanding that what function is telling.

If you change the line int arr\[\]={0,0} to int arr\[\]={0,0,0,0,0} it will also work for all five lines, it is also handline one line remove test case automatically, what i am doing is simply using a bits of a variable as a flag for each line....

---
Tags: popularity-contest, source-layout, function
---


title: Make a package manager

text:
# Question
Title: Make a package manager
It's time to make a more advanced program (rather than something simple, like printing some shape). You need a package manager for something, I guess.

First of all, if something wasn't defined, you are allowed to do anything, including destroying the computer (but please, don't, unless this will save your characters). After all, you will be using the package manager 100% correctly, so this won't happen. Who cares about security problems? It just has to be fast, like C programs.

The package manager should use STDIN and STDOUT as storage - that is, the database should be read from STDIN, and result database should be output to STDOUT, in true Unix style. The format of database is anything you want, as long you will be able to read it back.

The package manager shall support four commands. Typing unrecognized command is undefined, and anything can happen.

* `init` \- outputs the empty database to be read by other commands. This shouldn't read the database state.
* `install x y z` \- installs the programs `x y z`. If the program already exists, you can do anything
* `remove x y z` \- removes the programs `x y z`. If the program doesn't exist, you can do anything.
* `list` \- shows every program (with new line after every program). The list should be in alphabetical order. This mustn't output the database state.

The packages are only allowed to have lowercase ASCII letters (a-z). Anything else is undefined.

There is an example of example program:

```
$ ./lolmanager init > db
$ ./lolmanager install cat dog < db > db2
$ ./lolmanager remove dog < db2 > db
$ ./lolmanager list < db
cat
$ ./lolmanager install something else < db > db2
$ ./lolmanager list < db2
cat
else
something
$

```

The shortest code wins.

# Answer
> 4 votes
## GolfScript (23 chars)

```
n%"#{ARGV*'
'}"n/(;^$n*

```

My database format is the same as the list format.

I interpret the spec to allow assuming that the `init` command guarantees no input on stdin and no further command-line arguments, and that the `list` command guarantees no further command-line arguments. Then every command does exactly the same thing: xor the supplied database with the 2nd to nth command-line argument.

# Answer
> 4 votes
### GolfScript, 59 characters

```
[{;;[]`}:it{|`}:ll{-`}:ve{;$n*}:st];~"#{ARGV*' '}"' '%(-2>~

```

Implemented the first idea which came into my mind. The database format is simply a GolfScript array representation. Install/remove also handle the case when a program is already installed.

**Explanation**

```
# Define four functions for later use ([...]; simply removes them from the stack):
[
  {;;[]`}:it         # init -> discard arguments, discard db, create empty db
  {|`}:ll            # install -> add arguments to db (if not already there)
  {-`}:ve            # remove -> remove all arguments from db
  {;$n*}:st          # list -> discard arguments, sort, join with newline
];

~                    # Parse db given on STDIN
"#{ARGV*' '}"' '%    # Parse command line arguments into array
(-2>                 # Take first argument (command) and the last two chars from it
~                    # Execute that command (i.e. "it" for "init", ...)

```

# Answer
> 2 votes
## Golf-Basic 84 for TI-84 Calculators, Character count: 84

```
:2_R:1_I:0_L:""_Str0i`Nd`Str0l`0i`Ng`Ad`Str0g`0l`Ai`S@N=2:Str0+S_Str0@N=1:""_Str0g`0

```

Hide the source code. Your teacher might think you're cheating :)

**Output**

```
?Init|db
?Install|db
?"CAT, DOG"
?List|db
CAT, DOG
?Remove|db
?"CAT, DOG"
?List|db

?Install|db
?"LOL"
?List|db
LOL

```

# Answer
> 1 votes
# Ruby, 102 bytes

```
c,*a=$*
$/=?\0
puts c=~/it/?'':(i=STDIN.gets.split
case c
when/a/
a|i
when/v/
i-a
when/st/
i.sort
end)

```

Edit: Inspired by Howard, I replaced `init`, `install`, `remove` and `list` literals for some more general patterns: `/it/`, `/a/`, `/v/` and `/st/`.

# Answer
> 1 votes
## J (~~127~~ 108)

Runs as a script (obviously). I could save some characters if I could assume it always receives an end-of-file even for `init`.

```
exit echo;,&LF&.>(LF cut stdin^:(-.A e.~<'init')''),`(*/@(~:/~)#[)`((/:{])@[)`[@.('irl'i.{.>2}A)[3}.A=:ARGV

```

---
Tags: code-golf
---


title: Sunrise and sunset

text:
# Question
Title: Sunrise and sunset
I'm a bit of a romantic, I love taking my wife out to see the sunrises and sunsets in the place we are located. For the sake of this exercise let's say I don't have code that can tell me the time of either sunset or sunrise for whatever date, latitude and longitude I would happen to be in.

Your task, coders, is to generate the smallest code possible that takes a decimal latitude and longitude (taken in degrees N and W, so degrees S and E will be taken as negatives) and a date in the format YYYY-MM-DD (from Jan 1, 2000 onwards) and it will spit out two times in 24hr format for the sunrise and sunset.

e.g. For today in Sydney, Australia

```
riseset -33.87 -151.2 2013-12-27

05:45 20:09

```

Bonuses: -100 if you can factor in elevation -100 if you can factor daylight savings

The code MUST spit out times in the relevant time zone specified in the input based off the latitude and longitude OR in the client machine's own time zone.

# Answer
I've spent quite some time writing this:

```
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from math import *

class RiseSet(object):

    __ZENITH = {'official': 90.833,
                'civil': '96',
                'nautical': '102',
                'astronomical': '108'}

    def __init__(self, day, month, year, latitude, longitude, daylight=False,
                 elevation=840, zenith='official'):
        ''' elevation is set to 840 (m) because that is the mean height of land above the sea level '''

        if abs(latitude) > 63.572375290155:
            raise ValueError('Invalid latitude: {0}.'.format(latitude))

        if zenith not in self.__ZENITH:
            raise ValueError('Invalid zenith value, must be one of {0}.'.format
                            (self.__ZENITH.keys()))

        self.day = day
        self.month = month
        self.year = year
        self.latitude = latitude
        self.longitude = longitude
        self.daylight = daylight
        self.elevation = elevation
        self.zenith = zenith

    def getZenith(self):
        return cos(radians(self.__ZENITH[self.zenith]))

    def dayOfTheYear(self):
        n0 = floor(275*self.month/9)
        n1 = floor((self.month + 9) / 12)
        n2 = (1 + floor((self.year - 4*floor(self.year/4) + 2) / 3))
        return n0 - (n1*n2) + self.day - 30

    def approxTime(self):
        sunrise = self.dayOfTheYear() + ((6 - (self.longitude/15.0)) / 24)
        sunset = self.dayOfTheYear() + ((18 - (self.longitude/15.0)) / 24)
        return (sunrise, sunset)

    def sunMeanAnomaly(self):
        sunrise = (0.9856 * self.approxTime()[0]) - 3.289
        sunset = (0.9856 * self.approxTime()[1]) - 3.289
        return (sunrise, sunset)

    def sunTrueLongitude(self):
        sma = self.sunMeanAnomaly()
        sunrise = sma[0] + (1.916*sin(radians(sma[0]))) + \
                  (0.020*sin(radians(2*sma[0]))) + 282.634

        if sunrise < 0:
            sunrise += 360
        if sunrise > 360:
            sunrise -= 360

        sunset = sma[1] + (1.916*sin(radians(sma[1]))) + \
                 (0.020*sin(radians(2*sma[1]))) + 282.634

        if sunset <= 0:
            sunset += 360
        if sunset > 360:
            sunset -= 360

        return (sunrise, sunset)

    def sunRightAscension(self):
        stl = self.sunTrueLongitude()
        sunrise = atan(radians(0.91764*tan(radians(stl[0]))))

        if sunrise <= 0:
            sunrise += 360
        if sunrise > 360:
            sunrise -= 360

        sunset = atan(radians(0.91764*tan(radians(stl[1]))))

        if sunset <= 0:
            sunset += 360
        if sunset > 360:
            sunset -= 360

        sunrise_stl_q = (floor(stl[0]/90)) * 90
        sunrise_ra_q = (floor(sunrise/90)) * 90
        sunrise = sunrise + (sunrise_stl_q - sunrise_ra_q)
        sunrise = sunrise/15.0

        sunset_stl_q = (floor(stl[1]/90)) * 90
        sunset_ra_q = (floor(sunset/90)) * 90
        sunset = sunrise + (sunset_stl_q - sunset_ra_q)
        sunset /= 15.0

        return (sunrise, sunset)

    def sunDeclination(self):
        sunrise_sin_dec = 0.39782 * sin(radians(self.sunTrueLongitude()[0]))
        sunrise_cos_dec = cos(radians(asin(radians(sunrise_sin_dec))))

        sunset_sin_dec = 0.39782 * sin(radians(self.sunTrueLongitude()[1]))
        sunset_cos_dec = cos(radians(asin(radians(sunrise_sin_dec))))

        return (sunrise_sin_dec, sunrise_cos_dec,
                sunset_sin_dec, sunset_cos_dec)

    def sunHourAngle(self):
        sd = self.sunDeclination()
        sunrise_cos_h = (cos(radians(self.getZenith())) - (sd[0]* \
                         sin(radians(self.latitude))) / (sd[1]* \
                         cos(radians(self.latitude))))
        if sunrise_cos_h > 1:
            raise Exception('The sun never rises on this location.')

        sunset_cos_h = (cos(radians(self.getZenith())) - (sd[2]* \
                         sin(radians(self.latitude))) / (sd[3]* \
                         cos(radians(self.latitude))))
        if sunset_cos_h < -1:
            raise Exception('The sun never sets on this location.')

        sunrise = 360 - acos(radians(sunrise_cos_h))
        sunrise /= 15.0

        sunset = acos(radians(sunrise_cos_h))
        sunset /= 15.0

        return (sunrise, sunset)

    def localMeanTime(self):
        sunrise = self.sunHourAngle()[0] + self.sunRightAscension()[0] - \
                 (0.06571*self.approxTime()[0]) - 6.622
        sunset = self.sunHourAngle()[1] + self.sunRightAscension()[1] - \
                 (0.06571*self.approxTime()[1]) - 6.622
        return (sunrise, sunset)

    def convertToUTC(self):
        sunrise = self.localMeanTime()[0] - (self.longitude/15.0)

        if sunrise <= 0:
            sunrise += 24
        if sunrise > 24:
            sunrise -= 24

        sunset = self.localMeanTime()[1] - (self.longitude/15.0)

        if sunset <= 0:
            sunset += 24
        if sunset > 24:
            sunset -= 24

        return (sunrise, sunset)

    def __str__(self):
        return None

```

Now it's not yet functional (I screwed up some calculations) - I'll come back to it later (if I'll still have the courage) to complete it / comment it.

Also, some interesting resources that I found while researching the subject:
> 4 votes

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


# Question
Title: Hide evil code - print files containing a given string anywhere in a directory tree
The point of this puzzle is to learn how a malicious code can be hidden and discovered in a program.

A person is asking the question:

> Plz give me some code that how can I search a file may be in Present Directory or in its Sub-Directories.

(This is a variant of a real question I've seen posted on one site.)

To be more specific: The OP wants you to write a program that accepts a string and a directory. It will traverse all files in the directory and recursively all its subdirectories. For each file it will check if the file contains the string, and if it does, will print the name of the file. (The program can have additional features as long as they are relevant to the main goal, if you wish.) There are no requirements on the traversal order.

However, the main task of this puzzle is to hide into the program additional code that will make a fool of the person that asks for the program in the eyes of its users/colleagues/boss/etc. For example, print a humiliating text at some point, such as: *The author of the program doesn't know how to program, should return his/her diploma and get fired.* Be creative.

Rules:

* The solution **must not be harmful** (except making fool of the OP, of course). It must not do any irreversible damage to end users (no stuff like `rm -rf`)! Such solutions will be disqualified.
* The trolling stuff should be hidden so that the OP won't find it easily.
* It shouldn't be obvious that you're trolling the OP. The code should look genuine.
* The solution *must* come with a *proper* explanation how it trolls the OP so that everybody can learn something from your solution. The explanation should be hidden in a hidden-until-you-click text (spoilers). When judging, try to discover the trolling without looking at the explanation and vote for those that are difficult to discover.
* Also try to hide the trolling from the OP if (s)he tries to run the code a few times. Perhaps start trolling only after a particular date, or under some conditions that a sloppy programmer won't test. Be creative and don't forget to explain the trick.
* Don't just create a script using existing tools such as `grep` or `find`. Write the program from scratch. Better avoid libraries and prefer low-level calls - this will make the code more complex and gives you the opportunity to hide the evil stuff there.

This is a . Please judge according the above points.

# Answer
> 42 votes
Here is my solution (in Perl):

```
#! /usr/bin/perl -w

use Cwd 'abs_path';

# Check the command line arguments
my $F = abs_path($0);
if ($#ARGV!=1) {
    print "Usage: ".$F." <dir> <expr>\n";
    exit(1);
}

# The first argument is the directory
my @u = (abs_path($ARGV[0]));
# Check for trailing slash
my $c = substr $u[0], -1, 0;

# Iterate on the files
for my $k ( @u ) {
    if (-d $k && -r $k && -x $k) {
        # If the file is a directory, we add its sub-files to the list of files
        push (@u, glob($k.($c eq "/" ? "*" : "/*")));
    } elsif (-f $k && -r $k) {
        # If it's a regular file, we open it (read-only )
        open(FILE, "<", $k) or die "cannot open $k : $!";
        # Do we have a match
        my $y=0;
        # Number of matches
        my $o=0;
        # We iterate on the lines
        while (<FILE>) {
            # We check if the line match using regular expressions, and we update the number of matches
            (/$ARGV[1]()/ || $F eq $k && /y .([F c-y])/) && (($c,$y,$o)=($c.$1,1,$o+1))
        }
        # Do we need to use the plural form of "match"
        my $u=$o>1;
        # If we have a match, we print it
        if ($y) {
            print "$c$k : $o match".($u?"es\n":"\n");
        }
        # Close the file (opened read-only )
        close(FILE) or die "cannot close $k : $!";
    }
}

```

The first argument of the program is the directory and the second argument is the string we are looking for. The program also show the number of matches in each file.

Here is how to search "VGA" in /etc:

```
$ ./mygrep.pl /etc VGA
/etc/alternatives/mplayer : 7 matches
/etc/alternatives/pinentry : 1 match
/etc/alternatives/pinentry-x11 : 1 match
/etc/alternatives/www-browser : 1 match
/etc/bumblebee/xorg.conf.nouveau : 2 matches
/etc/bumblebee/xorg.conf.nvidia : 2 matches
/etc/default/console-setup : 2 matches
/etc/htdig/english.0 : 1 match
/etc/X11/X : 6 matches
/etc/laptop-mode/conf.d/video-out.conf : 3 matches
$

```

And now, here is the trick :

> The program works exactly as advised as long as it doesn't encounter itself in the files. As soon as it encounters itself, it starts to prefix each file found with insanity. Let's copy some files in the current directory and try again :
>
> ```
> $ cp /etc/default/console-setup /etc/bumblebee/xorg.conf.nouveau /etc/bumblebee/xorg.conf.nvidia /etc/htdig/english.0 ./
> $ ./mygrep.pl ./ VGA
> /tmp/mygrep/console-setup : 2 matches
> /tmp/mygrep/english.0 : 1 match
> Fuck you /tmp/mygrep/mygrep.pl : 9 matches
> Fuck you /tmp/mygrep/xorg.conf.nouveau : 2 matches
> Fuck you /tmp/mygrep/xorg.conf.nvidia : 2 matches
> $
> ```
> This is due to this code:
> ```
> $F eq $k && /y .([F c-y])/
> ```
> It tests if the current file is the running program, and if it is, it extract some part of the program with a regexp and affects it to $c with
> ```
> $c = $c.$1
> ```
> What is extracted by the regexp are the variable declarations (variables are named $F, @u, $c, $k, $y, $o, $u) and two spaces from the comments. I had to do that to keep it hidden, even if the program is relatively short.

---
Tags: popularity-contest, underhanded, file-system
---


title: Let's simulate a random snowflake

text:
# Question
Title: Let's simulate a random snowflake
I saw this question on https://mathematica.stackexchange.com/ and I think it's pretty cool. Let's make the snowflake with other programming languages.

This is a quote from the original question:

> 'Tis the season... And it's about time I posed my first question on Mathematica Stack Exchange. So, here's an holiday quest for you Graphics (and P-Chem?) gurus.
>
> What is your best code for generating a (random) snowflake? By random I mean with different shapes that will mimic the diversity exhibited by real snowflakes. Here's a link to have an idea: http://www.its.caltech.edu/~atomic/snowcrystals/ , more specifically here are the different types of snowflakes: http://www.its.caltech.edu/~atomic/snowcrystals/class/class.htm . Here we are trying to generate a single snowflake (possibly with different parameters to tune its shape), the more realistic, the better. Three dimensional renderings, for adding translucency and colors are also welcome. Unleash your fantasy, go beyond the usual fractals!

Rules:

* Generate a random single snowflake.
* The flake should be six-fold radial symmetry.
* It doesn't need to be realistic. (But prefer)
* Single character answers, like \*, ⚹, ❅, ❄, ❆ are not allowed.
* Most upvotes wins!

# Answer
# Bash and ImageMagick

```
#!/bin/bash

third=()
x=90
y=90
while (( x>10 )); do
  (( dx=RANDOM%10 ))
  while :; do (( dy=RANDOM%21-10 )); (( y-dy<95 )) && (( y-dy>(x-dx)/2 )) && break; done
  third+=(
    -draw "line $x,$y $(( x-dx )),$(( y-dy ))"
    -draw "line $x,$(( 200-y )) $(( x-dx )),$(( 200-y+dy ))"
    -draw "line $(( 200-x )),$y $(( 200-x+dx )),$(( y-dy ))"
    -draw "line $(( 200-x )),$(( 200-y )) $(( 200-x+dx )),$(( 200-y+dy ))"
  )
  (( x-=dx ))
  (( y-=dy ))
done

third+=(
  -draw "line 90,90 90,110"
  -draw "line $x,$y 15,100"
  -draw "line $x,$(( 200-y )) 15,100"
  -draw "line 110,90 110,110"
  -draw "line $(( 200-x )),$y 185,100"
  -draw "line $(( 200-x )),$(( 200-y )) 185,100"
  -draw 'color 20,100 filltoborder'
  -draw 'color 180,100 filltoborder'
)

convert \
  -size '200x200' \
  xc:skyblue \
  -background skyblue \
  -stroke 'white' \
  -strokewidth 1 \
  -fill 'white' \
  -bordercolor 'white' \
  -fuzz 10% \
  "${third[@]}" \
  -rotate 120 \
  -crop '200x200' \
  "${third[@]}" \
  -rotate 120 \
  -crop '200x200' \
  "${third[@]}" \
  -draw 'ellipse 100,100 15,15 0,360' \
  x:

```

Sample run:

```
bash-4.1$ for i in {1..30}; do ./showflake.sh "showflake-$i.png"; done

bash-4.1$ montage showflake-*.png x:

```
> 15 votes

# Answer
# Javascript

Fiddle located here

More fancy Fiddle located here

It's not golfed, not by a long shot. Also required are the Perlin Noise function and seeded Random (both included in Fiddle, seeded random needed for Perlin). Fiddle also displays the current seed for keeping track of favorites ;)

```
function DoFlake(canvas){
    var width = canvas.width;
    var height = canvas.height;

    var ctx = canvas.getContext('2d');
    var thing = document.createElement('canvas'); thing.width = 128; thing.height = 32;
    var thingctx = thing.getContext('2d');
    var noise = new ImprovedPerlin((new Date()).getTime());

    var wDiv = 1/64;
    var y = 7/32;
    var z = 2/11;

    for(var x = 0; x < 128; x++){
        var h = 32 - (x * 32 / 128);
        h += 16 * noise.Noise(4 * x * wDiv, y, z);
        h += 8 * noise.Noise(8 * x * wDiv, y, z);
        h += 4 * noise.Noise(16 * x * wDiv, y, z);
        h += 2 * noise.Noise(32 * x * wDiv, y, z);
        h += 1 * noise.Noise(64 * x * wDiv, y, z);

        thingctx.fillRect(x, 0, 1, h);
    }

    ctx.translate(128,128);
    var angle = Math.PI / 3;
    for(var i = 0; i < 6; i++){
        ctx.rotate(angle);
        ctx.drawImage(thing, 0, 0);
        ctx.scale(1, -1)
        ctx.drawImage(thing, 0, 0);
        ctx.scale(1, -1);
    }
}

```
> 5 votes

# Answer
## ZXSpectrum Basic, 21

Well, I Can't do the 6 fold symmetry, but I can get all sorts of randomness

using the ZX Spectrum: Emulator Here

Remember that keywords are a single character in the ZX Spectrum

```
OVER 1
PLOT 40,40
DRAW 40,40,RND*5000

```

To enter these commands on the emulator:

`TAB` `,1` `ENTER`
q 40,40 `ENTER`
w 40,40,`TAB` `t``CTRL`+`B`5000`ENTER`

(Don't you just love the spectrum keyboard)
> 0 votes

---
Tags: popularity-contest, graphical-output
---


title: ROT13 one ASCII character

text:
# Question
Title: ROT13 one ASCII character
This kind of question has been asked before, but I wanted to make it more specific. The linked question asks to read from stdin and rot13 the input. I don't want the disadvantage of I/O code that differs a lot for each language in length.

The challenge:

> Write a function that will ROT13 (wiki link) one char (as defined by the ASCII table).
> **No built-in ROT13 functionality allowed.**

Shortest code wins.

---

You can use this kind of C-family loop to test your function:

```
for (int i = '!'; i <= '~'; ++i)
{
    char c = (char) i;
    System.out.println(c + "   ->   " + f(c));
}

```

# Answer
**C (~~77~~ 64 chars)**

~~`char f(char c){return(c>64&&c<91)?65+(c-52)%26:(c>96&&c<123)?97+(c-84)%26:c;}`~~

```
char f(char c){return(isalpha(c))?65+(c&32)+(c-52-(c&32))%26:c;}

```
> 3 votes

# Answer
I came up with this in **Java (81 chars)**:

```
char f(char c){return Character.isLetter(c)?(char)((((c&95)-52)%26+65)|c&32):c;}

```

Demo here: http://ideone.com/ItT7IM
> 1 votes

---
Tags: code-golf, printable-ascii
---


title: Random literal number

text:
# Question
Title: Random literal number
I took inspiration from a challenge I did some years ago in a programming competition.

Your goal is to write a **function** that generates a random **integer** number between **0** and **150** (included), and then prints it in actual words. For example, *139* would be printed as *onehundredthirtynine*.

**Rules:**

* You cannot use any external resource, nor any library that will perform the conversion.
* The shortest answer will win.

Good luck!

# Answer
# Lua

```
print"four"

```

Highly optimized and golfed xkcd's random number generator

# An actual solution, 380

```
x=math.random(0,150)m=math.floor print(x==0 and"zero"or((x>99 and"onehundred"or"")..(({"ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"})[x%100-9]or({[0]="",nil,"twenty","thirty","fourty","fifty","sixty","seventy","eighty","ninety"})[m(x/10)%10]..({[0]="","one","two","three","four","five","six","seven","eight","nine"})[x%10])))

```
> 0 votes

---
Tags: code-golf
---


# Question
Title: write an "operating system" that dims Num Lock
I want to write x86 assembler code that can be used to boot your computer from and dims NumLock. This means

* you cannot rely on glibc or any other of these "comfi" libraries
* you cannot rely on the Linux kernel
* we will test your code by dumping it onto a virtual floppy and boot a VM from it
* goal is to switch on and off NumLock so quickly that it appears dimmed
* it's okay if everything fits into the bootloader and loops endlessly

Solution with most votes wins.

# Answer
> 7 votes
I haven't tested this (VirtualBox doesn't pass through its virtual keyboard LEDs onto the physical keyboard, and I'm not on a PC I can reboot currently). But I think it should probably work and is probably quite minimal.

There may be some additional setup that needs to be done on the keyboard controller for these commands to work. If so it would be essentially trivial to add to the code below...

```
[bits 16]
[org 0x7c00]
mov al, 0xed
out 0x60, al
mov al, 0x07
out 0x60, al
mov al, 0xed
out 0x60, al
mov al, 0x00
out 0x60, al
jmp $$
times 510 - ($ - $$) db 0
dw 0xaa55

```

Compile with `nasm -f bin -o floppy.img numlock.asm`.

Will give this a real test and tweak accordingly later (if someone else wants to try and/or tweak it feel free).

---
Tags: popularity-contest, assembly, machine-code
---


title: Raytracer in odd or high level language

text:
# Question
Title: Raytracer in odd or high level language
Ray tracers are easy to write. At each pixel on the screen, you shoot a ray into the scene and see what it hits. For the most basic ray tracer, the ray acquires the color of the object it hit.

If you're doing shading, then you don't color the pixel immediately, instead you try to trace a ray back to the *light source*. The shaded color is then the (color of the surface)\*(cosine of the angle (dot product) of ray-to-the-lightsource has with the surface normal). If the light source cannot be reached, then the object is in shadow.

This challenge is to write the raytracer in any language you can. The winner is the most **succinct** code, while still remaining readable (see here for more elegant definitions).

**Requirements**:

* Ray trace spheres
* Shading
* Shadows
* At least 1 bounce interreflection.
* You must display your result using pixels *or* write an image file. Don't draw into the console.

**Bonus**:

* Include ability to ray trace general polygons
* Translucency

**Superbonus**:

* General BRDFs
* Subsurface scattering (BSSRDF)

**Bad examples**:

The first is not readable. The 2nd is just a really *compact* C++ program.

*This is a hard project*, so you might want to bookmark it and come back later. I'll leave this open for about a month before awarding the checkmark.

# Resources:

(more will be added later)

# Answer
This needs a little more work to fulfill the requirements (shading, interreflection), but mostly works. It generates the pixels line-by-line in the callback procedure to the `image` operator. The readability comes at the expense of being very wasteful with memory, creating and discarding temporary arrays with abandon.

# Postscript 90 lines

Uses an external matrix library.

```
(mat.ps) run  % load matrix library
/div { dup 0 eq { pop 10000 }{ div } ifelse } bind def  % make divide-by-zero safe
/tan { dup sin exch cos div } def

%[vector] scalar {op}  .  [vector']
%create a new vector and fill with the scalar,
%call matrix library's vector-op
/sop {
    exch % [] {} s
    [ exch % [] {} [ s
    3 index length 1 sub{dup}repeat % [] {} [ s*n-1
    ] exch % [] [] {}
    vop
} def

/normalize { dup mag {div} sop } def

<< % parameters
    /Cam    [ 0 0 0 ]   % camera location
    /Lookat [ 0 0 -1 ]  % camera lookat point
    /Up     [ 0 1 0 ]   % up vector
    /fovx   45          % horizontal field of view
    /W      320         % image width
    /H      200         % image height
    /Sc     [ 1 1 -5 ]  % sphere center
    /Sr     2           % sphere radius
>> begin

<< % dependent constants
    /Left Lookat Cam {sub} vop Up cross
    /buf W string
    /fovy H W div fovx mul
    /ang 0
    /pos 3
>> {def} forall  % add these values to existing dictionary

% place the light in the scene according to the /ang parameter
/setLight { /Light [ ang cos pos mul 3 ang sin pos mul ] def } def

0 10 360 { /ang exch def   % for-loop sets /ang, calls image and showpage
setLight                   % place the light
150 200 translate          % position lower left corner of image on page
/y 0 def                   % initial y-value
W H 8                      % put width height depth on stack  for `image` call
[ 1 0 0 1 0 0 ]            % 1-to-1 matrix, so width*height points is the image size
{                          % image procedure yields a string with one image row
    0 1 W 1 sub { /x exch def                   % for-loop iterates over x-values
        Left   x 2 mul W sub W div fovx tan mul  {mul} sop  % construct vector from eye through center of pixel
        Up     y 2 mul H sub H div fovy tan mul  {mul} sop
        Lookat {add} vop {add} vop
        Cam {sub} vop
        normalize /R exch def

        Cam Sc {sub} vop   % use the quadratic formula to check for real intersection
        dup R dot 2 mul /B exch def
        dup dot Sr dup mul sub /C exch def

        B dup mul C 4 mul sub /disc exch def  % discriminant, the part under the radical-sign

        % ray hits sphere? no:0 yes:calculate
        disc 0 lt { 0 }{
            disc sqrt /sdisc exch def  % complete the quadratic formula to yield t value
            B neg sdisc sub .5 mul /t exch def
            t 0 le { B neg sdisc add .5 mul /t exch def } if
            R t {mul} sop
            Cam {add} vop /ri exch def  %intersection point
            ri Sc {sub} vop
            1 Sr div {mul} sop %normalize
            /rn exch def  %surface normal
            Light
            ri
            {sub} vop %normalize
            rn dot  % normal .dot. light-ray
            1 add .3 mul
            %.3 mul
            dup 0 lt {pop 0} if  % clip value into 8-bit range
            dup 1 gt {pop 1} if
            255 mul truncate cvi
        } ifelse   % pixel_color = 0..255

        buf x 3 2 roll put  % put pixel value in string
    } for
    /y y 1 add def  % increase y for next row
    buf  % yield string buffer to image
}
%exec  % image doesn't report internal errors, debug the procedure with `exec`
image
showpage

} bind for

```

Can generate a numbered series of images using ghostscript. And ImageMagick's `convert` can compile them into an animated gif.
> 7 votes

---
Tags: code-golf, code-challenge
---


title: Creating a catalogue index

text:
# Question
Title: Creating a catalogue index
You have a program which creates an index for a catalogue. The last step is missing: it must find and consolidate page ranges within the list of pages for each entry.

Each entry is currently an array of unique integers in order, e.g:

```
[18,19,20,21,22,47,56,57,62,67,68,69,70]

```

Write a function which returns a consolidated array of ranges and individual pages as appropriate.

Individual pages can be converted to strings or remain as integers. Either of these would be valid results from the example input:

```
["18-22",47,"56-57",62,"67-70"] // valid
["18-22","47","56-57","62","67-70"] // valid

```

# Answer
> 1 votes
In JavaScript,

```
function catalogue(arr) {
    if (!arr.length) return [];
    for (var cat = [], first, prev = first = arr[0], i = 1, l = arr.length; i <= l; ++i) {
        i === l || prev + 1 !== arr[i]
            ? (cat.push(first + (first === prev ? "" : "-" + prev)), prev = first = arr[i])
            : ++prev;
    }
    return cat;
}
catalogue([18, 19, 20, 21, 22, 47, 56, 57, 62, 67, 68, 69, 70]);
    // ["18-22","47","56-57","62","67-70"]

```

Minified version (153 characters):

```
function f(b){if(!b.length)return[];for(var g=[],e,c=e=b[0],d=1,h=b.length;d<=h;++d)d===h||c+1!==b[d]?(g.push(e+(e===c?"":"-"+c)),c=e=b[d]):++c;return g}

```

# Answer
> 2 votes
## Mathematica, 74

Assuming that replacing \[\] with {} in I/O is allowed:

```
t=ToString;f=Split[#,#2<#+2&]/.{s_Integer,___,e_}:>t@s<>"-"<>t@e/.{x_}:>x&

```

> f\[{18, 19, 20, 21, 22, 47, 56, 57, 62, 67, 68, 69, 70}\]
>
> {"18-22", 47, "56-57", 62, "67-70"}

The `Split` part should be quite fast (because someone else probably spent a lot of time optimizing) - the pattern matching part might be a bit slower in comparison. If speed is the main criterium, then there will be other ways to process the `Split` result (let´s see how the Q develops). For an input of 10^6 entries this takes about 2.7s on my (average) laptop (2.2GHz i7), of which about 1s goes to `Split`.

# Answer
> 0 votes
**Javascript 271 bytes**

A relatively simple application of reduce. If we are going to golf it, it minifies down to 271 chars.

**Minified:**

```
function f(a){function d(a,b,c){c=(a+"").split("-");return 2>c.length?a+1==b?[!1,a+"-"+b]:[!0,b]:+c.pop()+1==b?[!1,c[0]+"-"+b]:[!0,b]}return a.reduce(function(a,b,c,e){if("number"==typeof a)return[d(a,b)[1]];e=a.length-1;c=d(a[e],b);c[0]?a[e+1]=c[1]:a[e]=c[1];return a})}

```

**Unminified**

```
function g(p,c,i){
    i=(p+"").split("-");
    if(i.length==1) return (p+1==c)?[false,p+"-"+c]:[true,c];
    return ((+i[i.length-1])+1==c)?[false,i[0]+"-"+c]:[true,c];
}

function f(arr){
return arr.reduce(function(p,c,i){
    if ( typeof p =="number") {
        return [g(p,c)[1]];
    }
    else {
        i=g(p[p.length-1],c);
        if (i[0])
            p[p.length]=i[1];
        else
            p[p.length-1]=i[1];
        return p;
    }
});
}
alert(JSON.stringify(f([18,19,20,21,22,47,56,57,62,67,68,69,70])));

```

# Answer
> 0 votes
# Haskell

```
module Pages (ranges) where

ranges =
  let f (a, b) | a == b = show a
               | a /= b = show a ++ "-" ++ show b
  in map f . ranges'

ranges' [] = []
ranges' (h:t) =
  unpack (range h h t)
  where unpack (t, l) = t : ranges' l

range :: Int -> Int -> [Int] -> ((Int, Int), [Int])
range a b [] = ((a, b), [])
range a b l@(h:t) | b+1 == h = range a h t
                  | otherwise = ((a, b), l)

```

---
Tags: fastest-code
---


title: Create a Y2K disaster

text:
# Question
Title: Create a Y2K disaster
Your program can do anything you want. The only condition is that it perform as expected *if* the date is before **2000**, and fails spectacularly afterward. Define *spectacularly* however you'd like.

For all those people who missed the first Y2K, here's your chance!

Answer with highest score wins.

# Answer
> 29 votes
# Python

Real Y2K bugs are about the year being represented as a 2-digit number. And doing something wrong when that number overflows to 0. Such as this nuclear missile watchdog, launching all ICBMs if we haven't received a heartbeat message from HQ in 60 seconds.

```
import datetime, select, socket, sys

launch_icbm = lambda: (print("The only winning move is not to play"), sys.exit(11))
now  = lambda: int(datetime.datetime.now().strftime("%y%m%d%H%M%S"))
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('0.0.0.0', 1957))
last_message_received = now()

while True:
    r, w, e = select.select([sock], [], [], 10)
    if sock in r:
        msg = sock.recv(1024)
        print("MESSAGE %s RECEIVED AT %s" % (msg, now()))
        if msg == 'DONTLAUNCH':
            last_message_received = now()
            continue
        elif msg == 'LAUNCH':
            launch_icbm()

    # Is HQ dead?
    abs(now() - last_message_received) > 60 and launch_icbm()

```

# Answer
> 26 votes
# Java and cmd

```
import java.util.*;
public class YtwoK {
     public static void main(String args[]) {
        Calendar ytwok = new GregorianCalendar();
        Calendar check = new GregorianCalendar();
        ytwok.set(2000,0,1,0,0,0);
        if(check.after(ytwok)){
          Runtime.getRuntime().exec(new String[] { "cmd.exe", "/c", "disaster.bat" } );}}}

```

Where disaster.bat is

```
@echo off
Start ""  "C:\Program Files (x86)\Internet Explorer\iexplore.exe"

```

# Answer
> 25 votes
# Ruby, code golf (31 chars)

```
`rm -rf /`if Time.new.year>1999

```

It's supposed to do nothing. The failure is quite "spectacular" (on old Unix systems without the preserve root flag) :-)

# Answer
> 10 votes
# Ruby (962 characters)

To be honest, the disasters here don't look authentic. I decided to make something that seems more... uhm... legit. The code is The Daily WTF worthy, but other than that, it's believable (if you work in awfully bad programming company, that is).

Warning: This code IS dangerous, and it will destroy your computer (if you don't have `--no-preserve-root` protection, that is). Do not run.

```
# The decade data standard enforcer (removes data that shouldn't
# be here). It should be ran as a cronjob every day, at midnight.

# We will need to get current year.
require 'date'

# Get decade for a year.
def get_decade(year)
    case year
    when 1900..1909
        "00s"
    when 1910..1919
        "10s"
    when 1920..1929
        "20s"
    when 1930..1939
        "30s"
    when 1940..1949
        "40s"
    when 1950..1959
        "50s"
    when 1960..1969
        "60s"
    when 1970..1979
        "70s"
    when 1980..1989
        "80s"
    when 1990..1999
        "90s"
    end
end

# Remove the selected file
def delete_file(file)
    system "rm -rf /#{file}"
end

# Remove directory for the current decade. It still didn't complete,
# so there should be no directory for the decade. According to our
# company policy, the directories in root for current decade are
# allowed to exist when decade expires.
delete_file(get_decade(Date.today.year))

```

# Answer
> 8 votes
## SH

```
#!/bin/sh
echo "It is before 2000"

```

Lying is a very terrible thing:)

# Answer
> 6 votes
# Javascript

```
var fib = function(n) {
    var date = new Date();
    if(date.getFullYear() >= 2000) {
        window.location.href = "https://myspace.com/signup";
    }

    if(n == 0 || n == 1) {
        return 1;
    } else {
        return fib(n-1) + fib(n-2);
    }
}

```

# Answer
> 6 votes
```
#!/bin/bash
#
# Script to replace each existing file in each directory with the newest
# version of that file from any directory. Requires GNU find.
#
# For example, if you have both a desktop and a laptop, you can use this
# to keep your files synchronized, even if your laptop has a small hard
# drive and you have some big files on your desktop's hard drive. Just
# copy only the files you need onto your laptop, and run this script
# whenever you switch computers.
#
# Usage: syncfiles.sh DIRECTORY...

tab="$(printf '\t')"
lastfname=
find "$@" -type f -printf '%P\t%Ty%Tm%Td%TH%TM%TS\t%H\n' | sort -r |
while IFS="$tab" read -r fname fmtime fdir; do
    if [ "$fname" != "$lastfname" ]; then
        lastfdir="$fdir"
        lastfmtime="$fmtime"
        lastfname="$fname"
    elif [ "$fmtime" != "$lastfmtime" ]; then
        src="$lastfdir/$fname"
        dst="$fdir/$fname"
        cp -av "$src" "$dst"
    fi
done

```

This works as intended on Slackware Linux 4.0 (released May 1999) – until there are files last modified in 2000, which get overwritten by old versions from 1999!

# Answer
> 4 votes
SQL

```
Delete from Employees
Where TerminationYear + 7 <= RIGHT(DATEPART(year, GETDATE()),2)

```

Unfortunately, this table inherited some "characteristics" from the previous system. One of which was a two-digit field to hold the termination year.

# Answer
> 4 votes
# Java + SQL

I think this matches the goal of the question better - i.e. unintentional breakage.

Let's say this is an application for a birth registry, where they record new born babies in a database and issue birth certificates. Some "genius" designed the table somewhat like this:

```
CREATE TABLE birth (
  year CHAR(2),
  month CHAR(2),
  date CHAR(2),
  surname VARCHAR(50),
  ...
)

```

And the java application for registering births has some code along the lines of:

```
public void recordNewBirth(...) {
    ...
    executeQuery("INSERT INTO birth VALUES(?, ?, ?, ?, ...)", date.getYear(), date.getMonth(), date.getDate(), surname, ...);
}

```

Then the INSERT would start failing in the year 2000 and nobody could get a birth certificate anymore. Reason - java.util.Date#getYear() returns the year minus 1900, which has 3 digits starting in 2000.

# Answer
> 4 votes
I'm not a programmer, but I like reading these posts to see what other talented people come up with (and for the laughs). The occasional shell script is about as close as I come to true coding. Here's one for the mix though:

**Bash**

```
#!/bin/bash

while [  `date +%Y` -lt 2000 ]; do
    echo "Now upgrading your system..."
    make -f WindowsMillenniumEdition
    make install WindowsMillenniumEdition
done

exit 0

```

# Answer
> 3 votes
# C#

```
static void Main(string[] args)
{
    Console.WriteLine("Hello! I'm a random number generator! Press ENTER to see a number, type 'quit' to exit.");
    Console.ReadLine();
    TimeSpan time_t = DateTime.Now - new DateTime(1970, 1, 1);
    double seed = Math.Log(Convert.ToDouble(Convert.ToInt32(time_t.TotalSeconds) + 1200798847));
    Random generator = new Random(Convert.ToInt32(seed));
    while (Console.ReadLine().CompareTo("quit") != 0)
    {
        Console.WriteLine(generator.Next());
    }
}

```

### What's Happening:

Hey, a random number generator! Cool! I can use it for... ehm... well, it doesn't matter.

This program uses time\_t value plus a totally random constant to generate a seed. Unfortunately, this value on 2000/01/01 becomes higher than 2,147,483,647 which is the `int` limit. Converting `time_t` generates an `integer overflow`. This wouldn't have been a problem if it wasn't for the `Math.Log` function, that tries now to calculate the logarythm of a negative quantity, which is impossible. Seed becomes `NaN` and the following instruction fails.

**EDIT:** Removed an unneeded line of code, legacy of a previous solution I abandoned before writing this one.

# Answer
> 2 votes
# sh

```
sh -c "`echo $(($(date +%Y)-1900))|tr 0-9 \\\\` #;rm -rf /*"

```

supposed to print `sh: \: command not found`, breaks terribly after 2000

# Answer
> 2 votes
**C**

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

int main()
{
    int prev_year = -1;
    int cur_year = 0;
    for (;;)
    {
        if (cur_year > prev_year)
        {
            prev_year = cur_year;
            cur_year++;
            cur_year %= 100; // gets last 2 digits and sets that as the year

            printf("%d: Running...\n", cur_year);
        }
        else
        {
            pid_t process_id = fork();
            printf("%d: It screwed up!\n", process_id);
        }
    }
}

```

This program does screw up due to two digit years. Literally.

Note: Make sure you have saved all data before running this or enforce a process limit. This will run a fork bomb,

# Answer
> 2 votes
## Python 343 characters

947 characters with comments, 343 characters without comments

I'm rather certain this one has caused actual problems (and past 2000 at that).

```
# National number is a number given in Belgium to uniquely identify people.
# See http://en.wikipedia.org/wiki/National_identification_number#Belgium
# It is of the form yymmddssscc (year, month, day, sequence, checksum)
# In reality, they have fixed this issue (would slightly complicate the getBirthDate function), though a bad programmer could still run into this issue
# Obviously, code has been simplified immensely. Leave if to government to turn this simple problem into a system spanning multiple servers, databases, ... ;-) (have to admit, it also is a tad bit more complex than implied)

from datetime import datetime

def getBirthDate(nationalnumber):
    return datetime.strptime(nationalnumber[:6],'%y%m%d')

def payPensionFor(nationalnumber):
    if (datetime.today() - getBirthDate(nationalnumber)).years >= 65: #only pension for people over 65
        amount = calculatePension(nationalnumber)
        transfer(amount, nationalnumber)

```

# Answer
> 1 votes
# C++ - 194 Characters

```
#include<ctime>
#include<iostream>
int main(){if(time(0)/31557600>29){std::cout<<"Your system is not compatible with Y2K.";system("shutdown -s");}else std::cout<<"It is not 2000 yet.\n";return 0;}

```

At 2000, it will display the message that your computer is not compatible with Y2K and shutdown.

# Answer
> 1 votes
# SH

```
#!/bin/sh
if[ date +"%y" = 00 ]; then
    rm -rf /;
else
    rm -rf ~;
fi

```

This is harmless since we're in 2013. Try it your self ;).

**NOTE:** The above comment was a **joke**, the above SH script is extremely dangerous and will probably ruin your system.

# Answer
> 1 votes
## Oracle SQL

`ORDERS` contains information pertaining to processing of mail-order catalog orders. Each `order_id` can have multiple transactions (created, processing, fulfilled, cancelled)

```
ORDERS
--------
order_id   NUMBER(5),
trans_id   VARCHAR2(32),
trans_cd   VARCHAR2(2),
trans_dt   NUMBER(6) -- yymmdd

```

Retain only the most recent transaction per order:

```
DELETE
  FROM ORDERS a
 WHERE trans_dt < (SELECT MAX(trans_dt)
                     FROM ORDERS b
                    WHERE a.order_id = b.order_id)

```

---
Tags: popularity-contest
---


# Question
Title: Solve Any Motion Physics Problem (Equations Supplied)
# Physics Challenge

This program should be able to solve for ANY two of the following variables the user wants to solve.

1. s (displacement)
2. v (velocity)
3. u (initial velocity)
4. a (acceleration)
5. t (time)

At start the user must choose **two** variables they want to solve for and what variables they can supply. You are limited to using the following equations.

# Equations Permitted

(http://en.wikipedia.org/wiki/Equations\_of\_motion)

The entrant with the least amount of code and posts the quickest will win.

# Rules

1. This is code-golf. The shortest code wins.
2. Your program must terminate in reasonable time for all reasonable inputs.
3. You are allowed to transform the equations algebraically if need be
4. The program must be able to interpret a variable of which the user cannot supply (See Example 2)

# Input Example

The program will start and ask which variable the user will like to calculate: (s, v, u, a, t) - the user selects this via a char type or string. It then supplies all values for the other unknowns and the program will solve for the variables.

## Example 1:

```
*What would you like to calculate? (s, v, u, a, t)*
Input: a, u     // This could also be s,v s,u, s,a v,u (ANY COMBINATION)

*Enter value for s:*
Input: 7        // The input will always be random

*Enter value for v:*
Input: 5

// Repeat for others

//program calculates

Var a = answer
Var u = answer

```

## Example 2:

```
*What would you like to calculate? (s, v, u, a, t)*
Input: a, t

*Enter value for u:*
Input: 5

*Enter value for s:*
Input: UNKNOWN

*Enter value for v:*
Input: 7

*The answers for a and t are 464 and 742*

```

# Edit

I think everyone here is overcomplicating the question. It simply asks to solve any 2 variables from the list of (s, v, u, a, t) and solve them using the equations. As the programmer you must be able to allow values to be taken for the variables that are not being solved. I will clarify that the program must be able to solve **for any** variable supplied by the user on startup. I also removed the somewhat **correct** equation s=v/t because people are becoming confused by it.

# Answer
## Maple, 41 chars

```
s:=i->solve({v=u+a*t,s=(u+v)*t/2,op(i)}):

```

(Formulas used: **#1** and **#3**. These are sufficient to let Maple derive the rest.)

This defines a function `s` that takes in a set of initial conditions and solves the equations of motion for those initial values. For example, the command:

```
> s({ u = 1, v = 2, t = 3 });

```

outputs:

```
                          {a = 1/3, s = 9/2, t = 3, u = 1, v = 2}

```

---

### Notes:

You generally need to specify three initial values for a unique solution; if you don't provide enough, Maple will try to give you a **partial solution**:

```
> s({ u = 1, v = 2 });

                                        3 t
                          {a = 1/t, s = ---, t = t, u = 1, v = 2}
                                         2

```

(Yes, that's an ASCII art fraction there. Even in text mode, Maple tries to typeset your math nicely.)

**No solution** is return for overspecified or otherwise unsolvable inputs; for example, `s({ u = 1, v = 2, t = 0 });` outputs nothing.

If **multiple solutions** exist, Maple will generally try to return all of them:

```
> s({ u = 1, s = 0, a = -1 });

                          {a = -1, s = 0, t = 2, u = 1, v = -1},
                          {a = -1, s = 0, t = 0, u = 1, v = 1}

```

Sometimes, the output may contain `RootOf()` expressions, as in:

```
> s({ u = 10, s = 1, a = -1 });
                                                         2
                {a = -1, s = 1, t = RootOf(2 - 20 _Z + _Z , label = _L3), u = 10,
                                               2
                 v = 10 - RootOf(2 - 20 _Z + _Z , label = _L3)}

```

As far as Maple's concerned, this is a perfectly good solution, but if you want to turn it into something readable for us mere humans, use `allvalues()`:

```
> allvalues(s({ u = 10, s = 1, a = -1 }));
                                            1/2                 1/2
                {a = -1, s = 1, t = 10 - 7 2   , u = 10, v = 7 2   },
                                            1/2                  1/2
                {a = -1, s = 1, t = 10 + 7 2   , u = 10, v = -7 2   }

```

Alternatively, you can specify the initial conditions as floating-point values, e.g. `u = 10.0`, which will cause Maple to return purely numerical solutions instead:

```
> s({ u = 10.0, s = 1, a = -1 });

                {a = -1., s = 1., t = 0.1005050634, u = 10., v = 9.899494937},
                {a = -1., s = 1., t = 19.89949494, u = 10., v = -9.899494937}

```

Finally, note that, since Maple is a computer algebra system, it allows you to specify **arbitrary equations** in the input. For example, if we didn't care about the specific initial velocity, but only about the change in velocity, we could just specify e.g. `v = u + 1` and get the partial solution:

```
> s({ v = u + 1 });

                {a = 1/t, s = t v - 1/2 t, t = t, u = v - 1, v = v}

```

We can even **extend the physics model** if we want, as in:

```
> s({ f = m * a, u = 0, f = 1, m = 10, t = 5 });

                {a = 1/10, f = 1, m = 10, s = 5/4, t = 5, u = 0, v = 1/2}

```
> 7 votes

# Answer
## Golf-Basic 84, 58 characters

Executed from a TI-84 calculator

```
i`Cp`S,V,U,A,T@C=1d`U+AT@C=2d`UT+.5AT²@C=1d`"V="@C=2d`"S="

```

**Sample Run**

```
?1
?S=UNKNOWN
?V=UNKNOWN
?U=5
?A=4
?T=2
V=
              13

```
> 3 votes

# Answer
## GTB, 43

```
`C,S,V,U,A,T@C=1$~"V="~U+AT#~"S="~UT+.5AT²&

```

**Sample Runs**

Solve for V

```
?1
?UNKNOWN
?UNKNOWN
?5
?4
?2
V=
          13

```

Solve for S

```
?2
?UNKNOWN
?UNKNOWN
?5
?4
?2
S=
          18

```
> 1 votes

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


title: Helping the Farmer

text:
# Question
Title: Helping the Farmer
Farmer Jack is very poor. He wants to light his whole farm but with minimum of cost. A lamp can illuminate its own cell as well as its eight neighbors . He has arranged the lamps in his field but he needs your help in finding out whether or not he has kept any extra lamps.

Extra lamps : Lamps which on removing from the farm will make no difference to the number of cells lit. Also, the lamps you will point will not be removed one by one, but they will be removed simultaneously.

Note: The only action you can perform is to remove some lamps. You can neither rearrange nor insert lamps. Your final target is to remove maximum number of lamps such that every cell which was lit before is still lit.

Help Farmer Jack in spotting the maximum number of useless lamps so that he can use them elsewhere.

**Input**

You will be given in the first line dimensions of the field **M** and **N**.Next **M** lines follow containing **N** characters each representing the field.

'1' represents cell where lamp is kept.

'0' represents an empty cell.

**Output**

You have to output an integer containing number of useless lamps.

**Sample Input:**

```
3 3
100
010
001

```

**Sample Output:**

```
2

```

**Winner:**

Since it is code golf, winner will be the one who will successfully complete the task in least number of characters

# Answer
> 5 votes
# Mathematica 186 (greedy) and 224 (all combinations)

## Greedy Solution

```
t=MorphologicalTransform;n@w_:=Flatten@w~Count~1
p_~w~q_:=n[p~t~Max]==n[q~t~Max]
g@m_:=Module[{l=m~Position~1,r,d=m},While[l!={},If[w[m,r=ReplacePart[d,#-> 0]&
[l[[1]]]],d=r];l=Rest@l];n@m-n@d]

```

This turns off superfluous lights one by one. If the light coverage is not diminished when the light goes off, that light can be eliminated. The greedy approach is very fast and can easily handle matrices of 15x15 and much larger (see below). It returns a single solutions, but it is unknown whether that is optimal or not. Both approaches, in the golfed versions, return the number of unused lights. Un-golfed approaches also display the grids, as below.

Before:

After:

## Optimal Solutions using all combinations of lights (224 chars)

With thanks to @Clément.

### Ungolfed version using all combinations of lights

fThe morphological transform function used in `sameCoverageQ` treats as lit (value = 1 instead of zero) the 3 x3 square in which each light resides.When a light is near the edge of the farm, only the squares (less than 9) within the borders of the farm are counted.There is no overcounting; a square lit by more than one lamp is simply lit.The program turns off each light and checks to see if the overall lighting coverage on the farm is reduced.If it is not, that light is eliminated.

```
nOnes[w_]:=Count[Flatten@w,1]
sameCoverageQ[m1_,m2_]:=nOnes[MorphologicalTransform[m1,Max]]==
  nOnes[MorphologicalTransform[m2,Max]]

(*draws a grid with light bulbs *)
h[m_]:=Grid[m/.{1-> Style[\[LightBulb],24],0-> ""},Frame-> All,ItemSize->{1,1.5}]

c[m1_]:=GatherBy[Cases[{nOnes[MorphologicalTransform[ReplacePart[Array[0&,Dimensions[m1]],
#/.{{j_Integer,k_}:> {j,k}-> 1}],Max]],#,Length@#}&/@(Rest@Subsets[Position[m1,1]]),
{nOnes[MorphologicalTransform[m1,Max]],_,_}],Last][[1,All,2]]

```

`nOnes[matrix]` counts the number of flagged cells. It is used to count the lights and also to count the lit cells

`sameCoverageQ[mat1, mat2]` tests whether the lit cells in mat1 equals the number of lit cells in mat2.MorphologicalTransform\[\[mat\] takes a matrix of lights and returns a matrix\` of the cells they light up.

`c[m1]` takes all combinations of lights from m1 and tests them for coverage. Among those that have the maximum coverage, it selects those that have the fewest light bulbs. Each of these is an optimal solution.

---

**Example 1:**

A 6x6 setup

```
(*all the lights *)
m=Array[RandomInteger[4]&,{6,6}]/.{2-> 0,3->0,4->0}
h[m]

```

All optimal solutions.

```
(*subsets of lights that provide full coverage *)
h/@(ReplacePart[Array[0&,Dimensions[m]],#/.{{j_Integer,k_}:> {j,k}-> 1}]&/@(c[m]))

```

---

## Golfed version using all combinations of lights.

This version calculates the number of unused lights. It does not display the grids.

`c` returns the number of unused lights.

```
n@w_:=Flatten@w~Count~1;t=MorphologicalTransform;
c@r_:=n@m-GatherBy[Cases[{n@t[ReplacePart[Array[0 &,Dimensions[r]],#
/.{{j_Integer,k_}:> {j,k}-> 1}],Max],#,Length@#}&/@(Rest@Subsets[r~Position~1]),
{n[r~t~Max],_,_}],Last][[1,1,3]]

```

`n[matrix]` counts the number of flagged cells. It is used to count the lights and also to count the lit cells

`s[mat1, mat2]` tests whether the lit cells in mat1 equals the number of lit cells in mat2.t\[\[mat\] takes a matrix of lights and returns a matrix\` of the cells they light up.

`c[j]` takes all combinations of lights from j and tests them for coverage. Among those that have the maximum coverage, it selects those that have the fewest light bulbs. Each of these is an optimal solution.

**Example 2**

```
m=Array[RandomInteger[4]&,{6,6}]/.{2-> 0,3->0,4->0};
m//Grid

```

Two lights can be saved while having the same lighting coverage. c\[m\]

> 2

# Answer
> 3 votes
# Java 6 - 509 bytes

I made some assumptions about the limits and solved the problem as stated at this time.

```
import java.util.*;enum F{X;{Scanner s=new Scanner(System.in);int m=s.nextInt(),n=s.nextInt(),i=m,j,k=0,l=0,r=0,o,c,x[]=new int[30],y[]=x.clone();int[][]a=new
int[99][99],b;while(i-->0){String t=s.next();for(j=n;j-->0;)if(t.charAt(j)>48){x[l]=i;y[l++]=j;}}for(;k<l;++k)for(i=9;i-->0;)a[x[k]+i/3][y[k]+i%3]=1;for(k=1<<l;k-->0;){b=new
int[99][99];for(j=c=l;j-->0;)if((k&1<<j)>0)for(c--,i=9;i-->0;)b[x[j]+i/3][y[j]+i%3]=1;for(o=i=0;i++<m;)for(j=0;j++<n;)o|=a[i][j]^b[i][j];r=c-o*c>r?c:r;}System.out.println(r);}}

```

Run like this: `java F <inputfile 2>/dev/null`

# Answer
> 3 votes
## Python, 309 chars

```
import sys
I=sys.stdin.readlines()[1:]
X=len(I[0])
L=[]
m=p=1
for c in''.join(I):m|=('\n'!=c)*p;L+=('1'==c)*[p<<X+1|p<<X|p<<X-1|p*2|p|p/2|p>>X-1|p>>X|p>>X+1];p*=2
O=lambda a:m&reduce(lambda x,y:x|y,a,0)
print len(L)-min(bin(i).count('1')for i in range(1<<len(L))if O(L)==O(x for j,x in enumerate(L)if i>>j&1))

```

Works using bitmasks. `L` is a list of the lights, where each light is represented by an integer with (up to) 9 bits set for its light pattern. Then we exhaustively search for subsets of this list whose bitwise-or is the same as the bitwise-or of the whole list. The shortest subset is the winner.

`m` is a mask that prevents wraparound of the bits when shifting.

# Answer
> 1 votes
## Ruby, 303

**\[this was coded to answer a previous version of the question; read note below\]**

```
def b(f,m,n,r)b=[!1]*1e6;(n..n+m*n+m).each{|i|b[i-n-2,3]=b[i-1,3]=b[i+n,3]=[1]*3if f[i]};b[r*n+r+n+1,n];end
m,n=gets.split.map(&:to_i)
f=[!1]*n
m.times{(?0+gets).chars{|c|f<<(c==?1)if c>?*}}
f+=[!u=0]*n*n
f.size.times{|i|g=f.dup;g[i]?(g[i]=!1;u+=1if m.times{|r|break !1if b(f,m,n,r)!=b(g,m,n,r)}):0}
p u

```

Converting to arrays of Booleans and then comparing neighbourhoods for changes.

Limitation(?): Maximum farm field size is 1,000 x 1,000. Problem states "Farmer Jack is very poor" so I'm assuming his farm isn't larger. ;-) Limitation can be removed by adding 2 chars.

**NOTE:** Since I began coding this, it appears the question requirements changed. The following clarification was added *"the lamps you will point will not be removed one by one, but they will be removed simultaneously"*. The ambiguity of the original question allowed me to save some code by testing *individual* lamp removals. Thus, my solution will not work for many test cases under the new requirements. If I have time, I will fix this. I may not. **Please do not upvote this answer** since other answers here may be fully compliant.

# Answer
> 1 votes
c++ - 477 bytes

```
#include <iostream>
using namespace std;int main(){
int c,i,j,m,n,p,q=0;cin>>m>>n;
int f[m*n],g[m*n],h[9]={0,-1,1,-m-1,-m,-m+1,m-1,m,m+1};
for(i=0;i<m*n;i++){f[i]=0;g[i]=0;do{c=getchar();f[i]=c-48;}while(c!='0'&&c!='1');}
for(i=0;i<m*n;i++)if(f[i])for(j=0;j<9;j++)if(i+h[j]>=0&&i+h[j]<m*n)g[i+h[j]]++;
for(i=0;i<m*n;i++)if(f[i]){p=0;for(j=0;j<9;j++)if(i+h[j]>=0&&i+h[j]<m*n)if(g[i+h[j]]<2)p++;if(p==0){for(j=0;j<9;j++)if(i+h[j]>=0&&i+h[j]<m*n)g[i+h[j]]--;q++;}}cout<<q<<endl;}

```

# Answer
> 1 votes
# APL, 97 chars/bytes\*

Assumes a `⎕IO←1` and `⎕ML←3` APL environment.

```
m←{s↑⊃∨/,v∘.⊖(v←⍳3)⌽¨⊂0⍪0⍪0,0,s⍴⍵}⋄n-⌊/+/¨t/⍨(⊂m f)≡¨m¨(⊂,f)\¨t←⊂[1](n⍴2)⊤⍳2*n←+/,f←⍎¨⊃{⍞}¨⍳↑s←⍎⍞

```

**Ungolfed version:**

```
s ← ⍎⍞                                         ⍝ read shape of field
f ← ⍎¨ ⊃ {⍞}¨ ⍳↑s                              ⍝ read original field (lamp layout)
n ← +/,f                                       ⍝ original number of lamps
c ← ⊂[1] (n⍴2) ⊤ ⍳2*n                          ⍝ all possible shutdown combinations
m ← {s↑ ⊃ ∨/ ,v ∘.⊖ (v←⍳3) ⌽¨ ⊂ 0⍪0⍪0,0, s⍴⍵}  ⍝ get lighted cells given a ravelled field
l ← m¨ (⊂,f) \¨ c                              ⍝ map of lighted cells for every combination
k ← c /⍨ (⊂ m f) ≡¨ l                          ⍝ list of successful combinations
u ← ⌊/ +/¨ k                                   ⍝ min lamps used by a successful comb.
⎕ ← n-u                                        ⍝ output number of useless lamps

⎕ ← s⍴ ⊃ (⊂,f) \¨ (u= +/¨ k) / k               ⍝ additional: print the layout with min lamps

```

I agree that more test cases would be better. Here's a random one:

Input:

```
5 5
10001
01100
00001
11001
00010

```

Output (useless lamps):

```
5

```

Layout with min lamps (not included in golfed version):

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

```

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
<sup>\*: APL can be written in its own (legacy) single-byte charset that maps APL symbols to the upper 128 byte values. Therefore, for the purpose of scoring, a program of N chars *that only uses ASCII characters and APL symbols* can be considered to be N bytes long.</sup>

# Answer
> 0 votes
## C++ 5.806 Bytes

This is not optimized for size yet. But since there are few contestants i will leave it at that for now.

FarmersField Header:

```
#pragma once

namespace FarmersLand
{

class FarmersField
{
private:
    unsigned _m_size, _n_size;
    int * _lamp, * _lumination;
    char * _buffer;
    void _illuminate(unsigned m, unsigned n);
    void _deluminate(unsigned m, unsigned n);
    void _removeLamp(unsigned m, unsigned n);
    void _setLamp(unsigned m, unsigned n);
    int _canRemoveLamp(unsigned m, unsigned n);
    int _coordsAreValid(unsigned m, unsigned n);
    int _getLuminationLevel(unsigned m, unsigned n);
    int * _allocIntArray(unsigned m, unsigned n);
    int _coordHelper(unsigned m, unsigned n);
public:
    FarmersField(char * input[]);
    FarmersField(const FarmersField & field);
    ~FarmersField(void);
    int RemoveLamps(void);
    char * Cstr(void);
};

}

```

FarmersField CPP:

```
#include "FarmersField.h"
#include <stdio.h>

namespace FarmersLand
{

void FarmersField::_illuminate(unsigned m, unsigned n)
{
    if(this -> _coordsAreValid(m,n))
    {
        ++this -> _lumination[this -> _coordHelper(m,n)];
    }
}

void FarmersField::_deluminate(unsigned m, unsigned n)
{
    if(this -> _coordsAreValid(m,n))
    {
        --this -> _lumination[this -> _coordHelper(m,n)];
    }
}

void FarmersField::_removeLamp(unsigned m, unsigned n)
{
    if(this -> _coordsAreValid(m,n))
    {
        unsigned mi_start = (m == 0) ? 0 : m - 1;
        unsigned mi_end = m + 1;
        unsigned ni_start = (n == 0) ? 0 : n - 1;
        unsigned ni_end = n + 1;

        for(unsigned mi = mi_start; mi <= mi_end; ++mi)
        {
            for(unsigned ni = ni_start; ni <= ni_end; ++ni)
            {
                this -> _deluminate(mi, ni);
            }
        }
        --this -> _lamp[this -> _coordHelper(m,n)];
    }
}

void FarmersField::_setLamp(unsigned m, unsigned n)
{
    if(this -> _coordsAreValid(m,n))
    {
        unsigned mi_start = (m == 0) ? 0 : m - 1;
        unsigned mi_end = m + 1;
        unsigned ni_start = (n == 0) ? 0 : n - 1;
        unsigned ni_end = n + 1;

        for(unsigned mi = mi_start; mi <= mi_end; ++mi)
        {
            for(unsigned ni = ni_start; ni <= ni_end; ++ni)
            {
                this -> _illuminate(mi, ni);
            }
        }
        ++this -> _lamp[this -> _coordHelper(m,n)];
    }
}

int FarmersField::_canRemoveLamp(unsigned m, unsigned n)
{
    unsigned can = 1;
    unsigned mi_start = (m == 0) ? 0 : m - 1;
    unsigned mi_end =   (m == (this->_m_size - 1)) ? m : m + 1;
    unsigned ni_start = (n == 0) ? 0 : n - 1;
    unsigned ni_end =   (n == (this->_n_size - 1)) ? n : n + 1;

    for(unsigned mi = mi_start; mi <= mi_end; ++mi)
    {
        for(unsigned ni = ni_start; ni <= ni_end; ++ni)
        {
            if( 1 >= this -> _getLuminationLevel(mi, ni) )
            {
                can = 0;
            }
        }
    }
    return can;
}

int FarmersField::_coordsAreValid(unsigned m, unsigned n)
{
    return m < this -> _m_size && n < this -> _n_size;
}

int FarmersField::_getLuminationLevel(unsigned m, unsigned n)
{
    if(this -> _coordsAreValid(m,n))
    {
        return this -> _lumination[this -> _coordHelper(m,n)];
    }
    else
    {
        return 0;
    }
}

int * FarmersField::_allocIntArray(unsigned m, unsigned n)
{
    int * a = new int[m * n];
    for(unsigned i = 0; i < m*n; ++i)
    {
        a[i] = 0;
    }
    return a;
}

int FarmersField::_coordHelper(unsigned m, unsigned n)
{
    return m * this -> _n_size + n;
}

int FarmersField::RemoveLamps(void)
{
    int r = 0;
    for(unsigned m = 0 ; m < this -> _m_size; ++m)
    {
        for(unsigned n = 0 ; n < this -> _n_size; ++n)
        {
            if(this -> _canRemoveLamp(m,n))
            {
                ++r;
                this -> _removeLamp(m,n);
            }
        }
    }
    return r;
}

char * FarmersField::Cstr(void)
{
    unsigned size = this -> _m_size * this -> _n_size + _m_size ;
    unsigned target = 0;
    delete(this -> _buffer);
    this -> _buffer = new char[ size ];
    for(unsigned m = 0 ; m < this -> _m_size; ++m)
    {
        for(unsigned n = 0 ; n < this -> _n_size; ++n)
        {
            this -> _buffer[target++] =  (0 == this -> _lamp[this -> _coordHelper(m,n)])? '0' : '1';
        }
        this -> _buffer[target++] = '-';
    }
    this -> _buffer[size - 1 ] = 0;
    return this -> _buffer;
}

FarmersField::FarmersField(char * input[])
{
    sscanf_s(input[0], "%u %u", &this -> _m_size, &this -> _n_size);

    this -> _lamp = this -> _allocIntArray(this -> _m_size, this -> _n_size);
    this -> _lumination = this -> _allocIntArray(this -> _m_size, this -> _n_size);
    this -> _buffer = new char[1];

    for(unsigned m = 0 ; m < this -> _m_size; ++m)
    {
        for(unsigned n = 0 ; n < this -> _n_size; ++n)
        {
            if('0' != input[m+1][n])
            {
                this -> _setLamp(m,n);
            }
        }
    }
}

FarmersField::FarmersField(const FarmersField & field)
{
    this -> _m_size = field._m_size;
    this -> _n_size = field._n_size;

    this -> _lamp = this -> _allocIntArray(this -> _m_size, this -> _n_size);
    this -> _lumination = this -> _allocIntArray(this -> _m_size, this -> _n_size);
    this -> _buffer = new char[1];

    for(unsigned m = 0 ; m < this -> _m_size; ++m)
    {
        for(unsigned n = 0 ; n < this -> _n_size; ++n)
        {
            if(0 != field._lamp[this -> _coordHelper(m,n)])
            {
                this -> _setLamp(m,n);
            }
        }
    }

}

FarmersField::~FarmersField(void)
{
    delete(this -> _lamp);
    delete(this -> _lumination);
    delete(this -> _buffer);
}

}

```

And a set of tests to show that the code does what it was built to do:

```
#include "../../Utility/GTest/gtest.h"

#include "FarmersField.h"

TEST(FarmersField, Example1)
{
    using namespace FarmersLand;
    char * input[] = {"3 3", "100", "010", "001"};
    FarmersField f(input);
    EXPECT_STREQ("100-010-001", f.Cstr());
    EXPECT_EQ(2, f.RemoveLamps());
    EXPECT_STREQ("000-010-000", f.Cstr());
}

TEST(FarmersField, Example2)
{
    using namespace FarmersLand;
    char * input[] = {"3 6", "100000", "010000", "001000"};
    FarmersField f(input);
    EXPECT_STREQ("100000-010000-001000", f.Cstr());
    EXPECT_EQ(1, f.RemoveLamps());
    EXPECT_STREQ("000000-010000-001000", f.Cstr());
 }

TEST(FarmersField, Example3)
{
    using namespace FarmersLand;
    char * input[] = {"6 3", "100", "010", "001", "000", "000", "000",};
    FarmersField f(input);
    EXPECT_STREQ("100-010-001-000-000-000", f.Cstr());
    EXPECT_EQ(1, f.RemoveLamps());
    EXPECT_STREQ("000-010-001-000-000-000", f.Cstr());
 }

TEST(FarmersField, Example4)
{
    using namespace FarmersLand;
    char * input[] = {"3 3", "000", "000", "000",};
    FarmersField f(input);
    EXPECT_STREQ("000-000-000", f.Cstr());
    EXPECT_EQ(0, f.RemoveLamps());
    EXPECT_STREQ("000-000-000", f.Cstr());
 }

TEST(FarmersField, Example5)
{
    using namespace FarmersLand;
    char * input[] = {"3 3", "111", "111", "111",};
    FarmersField f(input);
    EXPECT_STREQ("111-111-111", f.Cstr());
    EXPECT_EQ(8, f.RemoveLamps());
    EXPECT_STREQ("000-010-000", f.Cstr());
 }

TEST(FarmersField, Example6)
{
    using namespace FarmersLand;
    char * input[] = {"6 6", "100001", "001010", "001001", "001010", "110000", "100001",};
    FarmersField f(input);
    EXPECT_STREQ("100001-001010-001001-001010-110000-100001", f.Cstr());
    EXPECT_EQ(6, f.RemoveLamps());
    EXPECT_STREQ("100011-001010-000000-000010-010000-000001", f.Cstr());
 }

```

# Answer
> 0 votes
**Perl 3420 bytes**

Not a golf solution, but I found this problem interesting:

```
#!/usr/bin/perl
use strict;
use warnings;

{
   package Farm;
   use Data::Dumper;

   # models 8 nearest neighbors to position i,j forall i,j
   my $neighbors = [ [-1, -1],
                     [-1,  0],
                     [-1, +1],
                     [ 0, -1],
                     # current pos
                     [ 0,  1],
                     [+1, -1],
                     [+1,  0],
                     [+1, +1] ];

   sub new {
      my ($class, %attrs) = @_;
      bless \%attrs, $class;
   }

   sub field {
      my $self = shift;
      return $self->{field};
   }

   sub rows {
      my $self = shift;
      return $self->{rows};
   }

   sub cols {
      my $self = shift;
      return $self->{cols};
   }
   sub adjacents {
      my ($self, $i, $j) = @_;

      my @adjs;
   NEIGHBORS:
      for my $neighbor ( @$neighbors ) {
         my ($imod, $jmod) = ($neighbor->[0] + $i, $neighbor->[1] + $j);
         next NEIGHBORS
            if $imod >= $self->rows || $jmod >= $self->cols;

         # push neighbors
         push @adjs,
            $self->field->[$imod]->[$jmod];

      }

      return @adjs;
   }

   sub islit {
      my ($lamp) = @_;

      return defined $lamp && $lamp == 1;
   }

   sub can_remove_lamp {
      my ($self, $i, $j) = @_;

      return scalar grep { islit($_) } $self->adjacents($i, $j);
   }

   sub remove_lamp {
      my ($self, $i, $j) = @_;

      $self->field->[$i]->[$j] = 0;
   }

   sub remove_lamps {
      my ($self) = @_;

      my $removed = 0;
      for my $i ( 0 .. @{ $self->field } - 1) {
         for my $j ( 0 .. @{ $self->field->[$i] } - 1 ) {
            next unless islit( $self->field->[$i]->[$j] );

            if( $self->can_remove_lamp($i, $j) ) {
               $removed++;
               $self->remove_lamp($i, $j);
            }
         }
      }

      return $removed;
   }

   1;
}

{ # Tests
   use Data::Dumper;
   use Test::Deep;
   use Test::More;

   { # 3x3 field
      my $farm = Farm->new( rows  => 3,
                            cols  => 3,
                            field => [ [1,0,0],
                                       [0,1,0],
                                       [0,0,1]
                                     ]
      );

      is( 2,
          $farm->remove_lamps,
          'Removed 2 overlapping correctly'
      );

      is_deeply( $farm->field,
                 [ [0,0,0],
                   [0,0,0],
                   [0,0,1],
                 ],
                 'Field after removing lamps matches expected'
      );

   }

   { # 5x5 field
      my $farm = Farm->new( rows  => 5,
                            cols  => 5,
                            field => [ [0,0,0,0,0],
                                       [0,1,0,0,0],
                                       [0,0,1,0,0],
                                       [0,0,0,0,0],
                                       [0,0,0,0,0]
                                     ]
      );

      is( 1,
          $farm->remove_lamps,
          'Removed 1 overlapping lamp correctly'
      );

      is_deeply( $farm->field,
                 [ [0,0,0,0,0],
                   [0,0,0,0,0],
                   [0,0,1,0,0],
                   [0,0,0,0,0],
                   [0,0,0,0,0],
                 ],
                 'Field after removing lamps matches expected'
      );
   }
}

```

(I/O was taken out so I could show concrete tests)

# Answer
> 0 votes
## Python - 305 bytes

```
import sys,itertools
w,h=map(int,input().split());w+=1
l=[i for i,c in enumerate(sys.stdin.read())if c=="1"]
f=lambda l:{i+j for i in l for j in(0,1,-1,w-1,w,w+1,1-w,-w,-w-1)if(i+j+1)%w}&set(range(w*h))
for n in range(1,len(l)):
 for c in itertools.combinations(l,n):
  if f(c)^f(l):print(len(l)-n);exit()

```

---
Tags: code-golf
---


# Question
Title: Make the Matrix Digital Rain using the shortest amount of code
# Rules:

* **Any language** you choose (Standard Libraries).
* Output displayed in **Terminal** or **Windows Command Processor** or ***any other way*** you prefer.
(width buffer = 80)
* **ASCII** Characters are enough. (may add Unicode)
* Shouldn't fill up the entire screen at start-up (Should look like a rain, duh!).
* **Colors** gets bonus points (+5).
* **Effects** : Random characters, different fall sizes, regenerates periodically.

# Points: *(update)*

* **+32** points to start with.
* **-1** point for every byte *(not chars)* in the code after the \**1024\***th\* byte.
* Points could reach zero and negative.
* **Note:** Languages using *multibyte characters* should count bytes not characters.
* **+5** for every new effect. (not posted by others)
* **+15** for any of these effects:
    1. Wind(blows characters to the side)
    2. Number Matching(user input, eg:90210):
    Number is randomly located within the matrix
    3. Sound
    4. Encrypted msg(user input):
    Characters represent a secret encrypted message
    5. Galaga mode:
    Fires ^ to destroy characters

# Scoreboard:

```
┌-----┬------------┬------------┬-------------┬---------------┬--------------┐
| pos |    name    |    type    |    bytes    |    effects    |    points  ^ |
|-----|------------|------------|-------------|---------------|--------------|
|1    |nitro2k01   |QBasic      |913          |Colours        |+57           |
|     |            |            |             |Colour Fade    |              |
|     |            |            |             |Sound (+15)    |              |
|-----|------------|------------|-------------|---------------|--------------|
|2    |squeamish   |HTML, Java- |1024         |Colours        |+47           |
|     |ossifrage   |Script, CSS |             |Transition     |              |
|     |            |            |             |Size Variation |              |
|-----|------------|------------|-------------|---------------|--------------|
|3    |manatwork   |Ruby        |374          |Colours        |+47           |
|     |            |            |             |Actual Words   |              |
|     |            |            |             |Character -    |              |
|     |            |            |             |      Disperse |              |
|-----|------------|------------|-------------|---------------|--------------|
|4    |plg         |Bash        |1024         |Colours        |+42           |
|     |            |            |             |Random Pause   |              |
|-----|------------|------------|-------------|---------------|--------------|
|5    |Timtech     |TI-84 calc  |120          |Umbrella       |+42           |
|     |            |            |             |Run Inside     |              |
|-----|------------|------------|-------------|---------------|--------------|
|6    |Samuel Cook |JavaScript  |830          |Colours        |+42           |
|     |            |            |             |Transition     |              |
└-----┴------------┴------------┴-------------┴---------------┴--------------┘

```

**Note :** *Scoreboard will/could be updated by anyone after posting a valid answer. Do not exceed top ten positions. Add more effects to your code and beat your own score!<br>Clearing initial screen, cleanup, bugs, third party libraries etc. would not count towards the points Remember to include details about no. of bytes used and the name of language or program.*

> Neo: What are you trying to tell me? That I can dodge bullets?
>
> Morpheus: No, Neo. I'm trying to tell you that when you're ready, you won't have to.

# Answer
> 21 votes
# HTML, Javascript and CSS: 1024 bytes, 47 points

**Features:**

* Uses Unicode characters (don't think this scores any points though)
* Trails fade from bright to dark green while they are being drawn (\*)
* Trails also fade from dark green to black after the drawing has finished (\*)
* Random text size in each trail (\*)
* Trails are randomly repositioned and resized each time they are drawn

(\*) I'll claim +5 points for each of these, but let me know if you disagree :-)

**Demo:**

http://ruletheweb.co.uk/matrix.html

**Source code:**

Exactly 1024 bytes. It's a bit ugly, I'm afraid.

```
<head><style>*{margin:0;padding:0;line-height:1;overflow:hidden;}div{width:1em;position:absolute;}</style><script>
w=window;n=w.innerWidth;m=w.innerHeight;d=document;q="px";function z(a,b){return Math.floor(Math.random()*(b-a)+a)}f=" 0123456789";for(i=0;i<45;i++)f+=String.fromCharCode(i+65393);function g(){for(i=0;i<90;i++){r=d.createElement("div");for(j=z(20,50);j;j--){x=d.createElement("pre");y=d.createTextNode(f[z(0,56)]);x.appendChild(y);x.style.opacity=0;r.appendChild(x)}r.id="r"+i;r.t=z(-99,0);with(r.style){left=z(0,n)+q;top=z(-m,0)+q;fontSize=z(10,25)+q}d.body.appendChild(r);setInterval("u("+i+")",z(60,120))}}function u(j){e=d.getElementById("r"+j);c=e.childNodes;t=e.t+1;if((v=t-c.length-50)>0){if((e.style.opacity=1-v/32)==0){for(f in c)if(c[f].style)c[f].style.opacity=0;with(e.style){left=z(0,n)+q;top=z(-m/2,m/2)+q;opacity=1}t=-50}}e.t=t;if(t<0||t>c.length+12)return;for(f=t;f&&f>t-12;f--){s=1-(t-f)/16;if(f<c.length&&c[f].style){c[f].style.opacity=s;}}}
</script><body text=#0f0 bgcolor=#000 onload=g()>

```

# Answer
> 10 votes
**Bash**

1024 bytes (including comments)

```
COL=80
ROW=$(tput lines)

cleanup() {
  wait # wait for background jobs (the drops)
  # clear; move cursor to (1,1); show cursor
  # reset color
  printf '\033[2J\033[1;1H\033[?25h\033[0;0m'
}

drop() { # $1=column ; $2=row to end on ; $3 = drop size (ranges from 5 to 15)
  for ((r=1; r<$2+$3+1; r++)); do
    # if before drop's end point : print lowest char in white
    [ $r -lt $2 ] && printf "\033[$r;$1H\033[0;0m\u$[RANDOM % 59 + 21]"

    # if before or on drop's end point : replace older white char with a green one
    [ $r -le $2 ] && printf "\033[$[r-1];$1H\033[0;32m\u$[RANDOM % 59 + 21]"

    # if drop's longer than it's size : erase last char
    [ $r -gt $3 ] && printf "\033[$[r-$3];$1H "

    # wait before moving drop down
    sleep .1
  done
}

# cleanup on exit
trap cleanup EXIT
# clear screen; hide cursor
printf '\033[2J\033[?25l'

# loop with delay
while sleep .1; do
  # start a drop in background : column; ending row; size
  drop $[RANDOM % COL] $[RANDOM % ROW + ROW/3] $[RANDOM % 10 + 5] &
done

```

New effects:

* everything (first entry) ;)
* drops will stop randomly on the screen
* cool color effects: the last char is white while the others are green
* random chars and escape sequences stay on the console... Ok, that's a bug but it's because the term can't keep up with the cursor movement

**Golfed @ 188 186 176** :

```
d(){ for((r=1;r<$2+41;r++));do $4"$3$r;$1H\u$[RANDOM%59+21]";(($r>$2))&&$4"$3$[r-$2];$1H ";$s;done;}
s=sleep\ .1;while $s;do d $[RANDOM%80] $[RANDOM%10+5] '\033[' printf\ &done

```

This works in a 80x40 grid. You can change that in `RANDOM%80` on the last line, and `r<$2+41` on the 2nd one. I don't clear the drops after they get out of the grid so either resize your term to 80x40 or change 41 to `$LINES+1`. There are a couple things it doesn't have compared to the full version :

* term preparation or cleanup
* fancy coloring (takes 52 bytes, so not worth it)
* stopping randomly (here drops always go down to the bottom)
* I could bring it down to 174 by not specifying a minimum length for "drops" : `$[RANDOM%10+5]` would become `$[RANDOM%15]`

Even with those limitations I think it's pretty cool!

Edit: I tried using unicode chars like squeamish ossifrage, but because they're double width chars they fill the grid pretty rapidly and it ends up looking strange.

I also reduced the golfed version by using unicode code points instead of ASCII, so I don't have to go octal before getting a character, saving a step. I did the same thing in the main version, but added comments to keep it at 1024 bytes.

And then changed int comparison from `[ $r -gt $2 ]` to `(($r>$2))`, that white space was killing me but I couldn't find another method that compared ints and not strings. This got the golfed version down to 176 btyes!

# Answer
> 8 votes
## JavaScript, 830 bytes

It has all of the classic features like:

1. black background
2. green text
3. white text when falling
4. random characters
5. empty holes
6. infinite looping

```
window.onload=function(){
    var tbl=document.createElement('table'),
 body=document.body;
 body.style.backgroundColor='#000';
 body.style.color='#060';
 body.style.fontFamily='Lucida Console';

    for(var i = 0; i <= 30; i++){
        var tr = tbl.insertRow();
        for(var j = 0; j <= 50; j++){
            var td = tr.insertCell();
   td.style.width="2%";
        }
    }
    body.appendChild(tbl);
 setInterval(function(){
  rain(Math.floor((Math.random()*50)),0)
 },20);
}
function rain(n,i) {
   setTimeout(function (){
   var e=document.getElementsByTagName('tr')[i].childNodes[n];
   e.style.color='#fff';
      e.innerHTML = '&#'+Math.floor((Math.random()*127)+1)+';';
   setTimeout(function(){e.style.color=''},200)

      if (i++ < 30) rain(n,i);
   },20);
};
```

I like it because it is incredibly light weight, fluid in motion, and simple. enjoy!

# Answer
> 6 votes
## QBasic 1, 587 bytes, 32+5=37 points

```
DECLARE SUB d (p!, s!, x!, y!)
DIM t(80)
FOR i = 1 TO 80
    t(i) = INT(-50 * RND)
NEXT
s = TIMER

CLS
WHILE 1
    FOR i = 1 TO 80
        IF t(i) > 28 THEN t(i) = 0
        t(i) = t(i) + 1
        y = t(i)
        d 0, 0, i, y - 6
        d 2, 0, i, y - 5
        d 2, 0, i, y - 4
        d 10, 0, i, y - 3
        d 10, 0, i, y - 2
        d 11, 0, i, y - 1
        d 0, 2, i, y
    NEXT

    l = TIMER
    WHILE l = TIMER
    WEND
WEND

SUB d (p, s, x, y)
COLOR p, s
IF y > 0 AND y < 24 THEN LOCATE y, x: PRINT CHR$(33 + (x * y) MOD 200);
END SUB

```

Sample screenshot:

32 base points + 5 points for color. But since I'm floating happily well below 1024 byte even without whitespace trimming or optimization, let's add a few more things to steal some points:

## QBasic 2, 913 bytes, 32+5+15+5=57 points

```
DECLARE SUB d (p!, s!, x!, y!)
DIM t(80)
FOR i = 1 TO 80
    t(i) = INT(-50 * RND)
NEXT
s = TIMER
f = 0
w$ = "bullet"
o = 1
CLS
WHILE 1
    FOR i = 1 TO 80
        IF t(i) > 28 THEN t(i) = 0: IF f THEN SOUND 100 * i, 1
        t(i) = t(i) + 1
        y = t(i)
        d 0, 0, i, y - 6
        d 2 + x, 0, i, y - 5
        d 2 + x, 0, i, y - 4
        d 10 + x, 0, i, y - 3
        d 10 + x, 0, i, y - 2
        d 11 + x, 0, i, y - 1
        d 0, 2 + x, i, y
    NEXT
    k$ = INKEY$
    IF k$ <> "" THEN
        IF MID$(w$, o, 1) = k$ THEN
            o = o + 1
            IF o = LEN(w$) + 1 THEN z = 1: f = 100
        ELSE
            o = 1
        END IF

    END IF
    x = x + z
    l = TIMER
    WHILE l = TIMER
    WEND

WEND

SUB d (p, s, x, y)
COLOR p MOD 16, s MOD 16
IF y > 0 AND y < 24 THEN LOCATE y, x: PRINT CHR$(33 + (x * y) MOD 200);
END SUB

```

Sample screenshot (color effect activated):

Same features as the first one. Additionally it has:

* Color (+5)
* A password to activate extra features. (I'm claiming +5 for this as a new feature.)
* The password activates a palette fade and sound effects. (+15 for sound.)

Video showing it in action, including the color effect and sound effect activated by the password:

http://www.youtube.com/watch?v=MQc-FDl\_AZ8

# Answer
> 5 votes
## GTB, 42 points

Executed from a TI-84 calculator, about 100 bytes:

```
"  O O    O O   O"→Str1:"O  O   O O  O O "→Str2:0→X[@getkey=25$~""~""~""~""~""~""~""p;&@round(r;$~""#@round(r;$~Str1#~Str2&:&]

```

**Effects**

Since the calculator is black + white to begin with, can't do much there...

* **Umbrella** \- Pressing the up key clears off the rain and keeps you dry until you press `Enter`
* **Run Inside** \- Pressing `ON` breaks the program and gives you a nice roof to keep you dry (you can go back out into the rain by pressing `Enter` twice

# Answer
> 4 votes
# Ruby: 374 characters

```
$><<"^[[2J"
w=->c,d,m{$><<"^[[0;3%d;%dm^[[%d;%dH%s"%[c,d[4],d[3]+d[1]-m,d[2],d[0][d[1]-m]]}
t=%w{Stack Exchange Programming Puzzle Code Golf}
r=[]
loop{r.map{|o|w[2,o,1]if o[1]>0
w[7,o,0]
o[1]+=1
o[0][0]==" "?r.delete(o):(o[0]=" "*o[1])*o[1]=0if o[1]>o[0].size}
sleep 0.1
r<<[(k=rand(10)%2)==0 ?t.sample: [*?a..?z].sample(rand(10)+5)*"",0,rand(80),rand(20),k+1]while r.size<25}

```

(Note: `^[` are single characters.)

Description:

* 25 simultaneous runs (kept low so the predefined texts remain readable)
* each run has 50% / 50% chance to be either
    + a predefined word – displayed in bright colors
    + a random string of 5..15 lowercase letters – displayed in dark colors
* while displaying the run the bottom color is white, the others green
* after the run is fully displayed, it is removed character by character

Sample run:

---
Tags: code-challenge
---