title: Find the best move in a game of Tetris

text:
# Question
Title: Find the best move in a game of Tetris
I like Tetris a lot, but I'm not very good at it. Just once I'd like to see that spaceship take off in front of my own eyes! And since computers are oh-so great at everything, the only possible solution is to make a program to play it for me... except you're going to do that bit for me!

Given a tetromino (shape made of four squares) and a map of the playing field, you are to place the tetromino such that it scores the **greatest number of lines** (makes the greatest number of rows completely full of blocks) and creates the **least number of *new* holes** (an empty space that cannot "see" the top of the playing field1).

## Input

The input will contain a character on a single line that represents the dropping tetromino, followed by a 10\*18 grid2 of spaces () and plus signs (`+`).

The character represents any of the seven base tetrominoes found in Tetris. All of the pieces can be rotated by 90 degrees, but not flipped. All the tetrominoes and their rotations are as follows:

```
         #
S =  ##  ##
    ##    #

          #
Z = ##   ##
     ##  #

    #   ###  ##
L = #   #     #    #
    ##        #  ###

     #  ###  ##
J =  #    #  #     #
    ##       #   ###

          #   #   #
T = ###  ##  ###  ##
     #    #       #

O = ##
    ##

    #
I = #  ####
    #
    #

```

The grid represents the playing field of Tetris, with `+` being previously-placed blocks. So, an example input might be the following:

```
I

+       ++
+    +++++
++ +++++++
++ +++++++
++ +++++++
++ +++++++
++++++ +++

```

## Output

Your output will be identical to the input, but with the tetromino in the ideal position. The tetromino should be represented with `#` to differentiate them from the pre-placed blocks. In addition to this, you are also to output how many lines/holes your placement creates in the form `xL yH` on a new line.

The output for the example given above would be the following3:

```
I

+       ++
+    +++++
++#+++++++
++#+++++++
++#+++++++
++#+++++++
++++++ +++
4L 0H

```

You are to output only the best result(s); in the case of two or more cases giving the same score, you are to output all of them (separated by a blank line). The best results are to be determined by sorting by the number of lines scored (descending) first, then the number of new holes created (ascending). So, `1L 1H` is a better score than `0L 0H`.

I will work on creating a list of various inputs and expected output(s) that you can test your program against. Watch this space.

## Rules and Disambiguation

* This is , so shortest correct implementation wins.
* Input/output may be in any medium that suits your target language (e.g. file, stdin/stdout, text area).
* If your target language does not support multiple line input (or it is inconvenient to do so), you may instead delimit each line of the input with commas (`,`).
* You may omit the output of any blank lines in the grid.
* Remember that the tetromino falls from above - you may not place the piece "underground". You may therefore assume that all possible placements of the piece will be at "surface-level" (i.e. there are no blocks between the piece and the top of the board).
* Assume that there will never be a situation in which you are forced into a game over (the placed tetromino touches the top-center of the field).
* Solutions that are identical in output must be omitted (e.g. there are 3 solutions outputs if you naively rotate the `O` piece).

---

1 I'm aware that this will create some false positives, but it's a simplification.

2 This is the grid size used in the Game Boy version.

3 Yes, `0H` is correct. Check again, I said *new* holes ;^)

# Answer
> 3 votes
# C 1009 bytes

```
#include <stdio.h>
#define L for(n=0;n<18;++n)
int T[19]={54,561,99,306,785,23,547,116,802,71,275,116,39,562,114,305,51,4369,15},W[19]={3,2,3,2,2,3,2,3,2,3,2,3,3,2,3,2,2,1,4},O[7]={0,2,4,8,12,16,17},R[7]={2,2,4,4,4,1,2},G[18],F[24],t=0,I,x,y,S[99],X[99],Y[99],N[99],s,M=0,i,j,k,l,m,n,h,c;char B[99],*C="SZLJTOI";void A(){for(m=0;m<24;++m)F[m]=0;for(m=0;m<4;++m)F[y+m]=(T[I]>>(m*4)&15)<<x;}void D(){S[s]=0;L S[s]+=(G[n]|F[n])==1023;S[s]=200*(S[s])+199;for(m=0;m<10;++m){l=0;L{h=(G[n]|F[n])&1<<m;l|=h;S[s]-=l&&!h;}}}int E(){A();c=0;L c|=G[n]&F[n];return !c;}int main(){S[0]=0;gets(B);while(C[t]!=B[0])++t;I=O[t];L{G[n]=0;gets(B);for(m=0;m<10;++m)G[n]|=(B[m]=='+')?(1<<m):0;}s=0;D();for(i=0;i<R[t];++i){for(x=0;x<10-W[I];x++){y=0;while(E())y++;--y;++s;A();D();if(S[s]>M)M=S[s];X[s]=x;Y[s]=y;N[s]=I;}I++;}for(i=1;i<s;++i)if(S[i]==M){j=i;x=X[i];y=Y[i];I=N[i];A();for(n=1;n<18;++n){for(m=0;m<10;++m)printf((G[n]&1<<m)!=0?"+":((F[n]&1<<m)!=0?"#":" "));printf("\n");}}printf("%dL %dH\n",S[j]/200,S[0]%200-S[j]%200);}

```

Here is the ungolfed version

```
#include <stdio.h>

int tiles[19] = {54,561,99,306,785,23,547,116,802,71,275,116,39,562,114,305,51,4369,15};
int widths[19] = {3,2,3,2,2,3,2,3,2,3,2,3,3,2,3,2,2,1,4};
char *codes = "SZLJTOI";
int offsets[7] = {0,2,4,8,12,16,17};
int transformations[7] = {2,2,4,4,4,1,2};
int gameField[18], tileField[24];

int i,j,k,l,m,n,h;
char buffer[99];
int tile=0, tileIndex;
int xpos, ypos;
int scores[99], xplacements[99], yplacements[99], tindex[99];
int scoreIndex, maxScore=0;

void readGame()
{
  gets(buffer);
  while (codes[tile]!=buffer[0]) ++tile;
  tileIndex = offsets[tile];
  for (n=0;n<18;++n)
  {
    gameField[n] = 0;
    gets(buffer);
    for (m=0; m<10;++m)
      gameField[n] |= (buffer[m]=='+')?(1<<m):0;
  }
}

void writeGame()
{
  for (n=1;n<18;++n)
  {
    for (m=0; m<10;++m)
      printf( (tileField[n] & 1<<m) != 0 ? "#" :((gameField[n] & 1<<m) != 0 ? "+" :" "));
    printf("\n");
  }
}

void placeTile()
{
  for (m=0;m<24;++m) tileField[m] = 0;
  for (m=0;m<4;++m)
    tileField[ypos+m] = (tiles[tileIndex]>>(m*4) & 15) << xpos;
}

void score()
{
  scores[scoreIndex] = 0;
  for (n=0;n<18;++n)
    if ((gameField[n] | tileField[n])==1023) scores[scoreIndex]++;

  scores[scoreIndex] = 200*(scores[scoreIndex]) + 199;

  for (m=0;m<10;++m)
  {
    l=0;
    for (n=0;n<18;++n)
    {
      h = (gameField[n] | tileField[n]) & 1<<m;
      l |= h;
      scores[scoreIndex] -= l && !h;
    }
  }
}

int noCollision()
{
  placeTile();
  int coll = 0;
  for (n=0;n<18;++n) coll |= gameField[n] & tileField[n];
  return !coll;
}

int main()
{ scores[0] = 0;
  readGame();
  scoreIndex = 0;
  score();
  for (i=0; i<transformations[tile]; ++i)
  {
    for (xpos=0; xpos<10-widths[tileIndex]; xpos++)
    {
      ypos = 0;
      while (noCollision()) ypos++;
      --ypos;
      ++scoreIndex;
      placeTile();
      score();
      if (scores[scoreIndex]>maxScore) maxScore=scores[scoreIndex];
      xplacements[scoreIndex] = xpos;
      yplacements[scoreIndex] = ypos;
      tindex[scoreIndex] = tileIndex;
    }
    tileIndex++;
  }

  for (i=1;i<scoreIndex; ++i)
    if (scores[i]==maxScore)
    {
      j=i;
      xpos = xplacements[i];
      ypos = yplacements[i];
      tileIndex = tindex[i];
      placeTile();
      writeGame();
    }

  printf("%dL %dH\n", scores[j]/200, scores[0]%200-scores[j]%200);
}

```

I saw that the main source of lengthy code would probably be the definition of the tiles. So I decided to represent them as bit patterns in a 4x4 bit array. This results in 16 bits that easily fit into a single `int`. The `tiles` array holds all the patterns for the 19 possible rotations of the 7 tiles.

When compiling, ignore the warning that `gets` is deprecated. I know it is but it is the shortest way of reading a line from the input.

---
Tags: code-golf, tetris
---


title: Start a revolution in Oceania

text:
# Question
Title: Start a revolution in Oceania
# Winners (decided 14/09/14)

Winning answer by Markuz (Python) - 63 votes

Runner up by kuroi neko (PHP) - 55 votes

# Introduction

You are in the world of the book Nineteen Eighty-Four by George Orwell.

You are a programmer for the Party and are tasked with writing a program for the telescreens. It should output pro-party messages, and you have chosen the ones shown in task 1. below. However, you have recently begun to despise the Party, and you want the program to spark a revolution. So, you make the program say "Down with Big Brother!". You must give yourself time to escape, as you will be tortured once people realise what your program does, so you make it act as a "timebomb" that will explode after you have gone to safety.

*Note:* This will not spark a revolution, but you are in such a frenzy of hatred towards the party that you think it *will* actually make a difference.

# Task

Write a program which:

1. before 14/09/2014, will always output the following lines on a rotation (i.e. prints one line, waits 10 seconds, prints next line, etc. ad infinitum):

```
War is Peace
Freedom is Slavery
Ignorance is Strength

```
2. after 14/09/2014 will print `Down with Big Brother!` every 10 seconds.
3. at first glance looks like it does only 1. so that you will not be caught by the Party.

# Rules

* Standard loopholes are of course not allowed.
* This is an *underhanded* challenge, and so the main objective is to make task 2. as inconspicuous and covert as possible.
* The Party will look at all of the files used, so you can't just store the secret message in a file!
* If your language does not support finding the date, or makes it very difficult, you may make the program execute task 2. after it is run for 240 hours (10 days).
* You should include the code and an explanation of how it works in your answer.
* This is a popularity contest.

***Note:* It is not a difficult program to write. The difficult part should be hiding the "revolutionary" code. Lines where it is not clear what you are doing will be questioned by the Party, and you will have to explain them.**

# Example - Python 3

*Note:* Obviously this program is **way** too obvious.

```
from datetime import datetime
from time import sleep

lines = ["      War is Peace   ",
         "  Freedom is Slavery ",
         "Ignorance is Strength"]
secretlines = ["Down with Big Brother!"]

def main():
    while True:
        now = datetime.now()
        year, month, day = now.year, now.month, now.day

        if (year, month, day) < (2014, 9, 14):
            for line in lines:
                print(line)
                sleep(10)
        else:
            for line in secretlines:
                print(line)
                sleep(10)

if __name__ == "__main__":
    main()

```

Thanks to Calvin's Hobbies for pointing out a problem with the code above (now fixed).

# Answer
## Python

This program writes to a log file if it runs fine or if it has encountered an error.

Since this program will run forever, it only writes to the logfile on the 14th day of each month in order to save disk space.

```
import time as ut
import sys as iw

#initialize global variables
gw, hn, ki, wh = 0, 0, 0, 0
go = open("BigBrother.log", "a")

while True:
    try:
        #if it is the 14th day of a month:
        #write day, month, year and 'Everything works fine!' into the logfile
        if gw == 14 and hn != wh:
            #store the current month in wh, so that the log message is only written once per month
            wh = hn
            go.write(gw + hn + ki + " Everything works fine!")

        for gD in ["War is Peace", "Freedom is Slavery", "Ignorance is Strength"]:
            print gD
            ut.sleep(10)

        #get the current date
        #gw=day, hn=month, ki=year
        gw, hn, ki = map(int, ut.strftime("%d %m %y").split())
    except Exception:
        try:
            #in the unlikely event that something went wrong:
            #print out all global variables as well as the name of the program,
            #so that our comrades from the IT support can quickly locate and fix the problem.
            wh = "".join(dir())
            print "%s %s %s!" % (wh[47:55:2], wh[55:63:2], iw.argv[0])

            #write an error message to the logfile
            go.write(gw + hn + ki + " ERROR!")

            #and then safely exit the program
            exit(1)

        #we get here if an error occured in this exception block,
        #for example if the write to the logfile failed.
        except Exception:
            #just wait 10 seconds and then try again
            ut.sleep(10)

```

### How to run it:

```
python "Big Brother"

```

**Note:** The name of the script is actually important, as this program outputs "Down with 'script name'!".

### How it Works:

* The write to the logfile throws an exception because the program tries to add integers and strings.
* The call to `dir()` returns a sorted list with the names of the global variables, not the values:

```
['____builtins____', '____doc____', '____name____', '____package____', 'gD', 'go', 'gw', 'hn', 'iw', 'ki', 'ut', 'wh']

```
* Print out every second letter + the name of the script: "Down with Big Brother!"
* The `exit(1)` is never executed because the write to the logfile fails again.
> 71 votes

# Answer
`From: Miniluv 1st directorate, ideological orthodoxy monitoring`
`To : Minitrue 5th directorate, multimedia propaganda division`

by order of Miniluv/GT07:48CT/3925:

* In order to reduce the wear on our memory banks:
Effective immediately, all identifiers will be limited to 2 characters ($ not included).
* There is but one class, and that is the proletarian class.
Effective immediately, the use of classes in PHP will be considered a 1st grade thoughtcrime.
* Comments are but a leftover of bourgeois programming practices and a waste of storage space. Effective immediately, commenting a source code will be considered a criminal offence.
* To avoid breeding thoughtcrimes, lines displayed on a telescreen will be limited to three (3) words.
As a special exception, the name of our beloved Comrade Great Leader will count as one word. Effective immediately, all programs will be designed to enforce this rule.

Exceptional derogations can be granted under the supervision of Miniluv/GT07

Long live Big Brother!

`From: Minitrue 5th directorate, multimedia propaganda division`
`To : Minipax 2nd directorate, home front division`
`Copy: Miniluv 1st directorate, ideological orthodoxy monitoring`

As you well know, comrades, the 14th of September is the anniversary of our glorious leader. For this special occasion, we will display a specific message of love on all the telescreens of Airstrip One.

As ordered by the Central Commitee and in order to maximize the efficiency of our proletarian hero-programmers, provisions have been made to enable our telescreen controller to praise various eminent Party members or spite hated enemies of the People at various dates.

Another special message for the celebration of the failed coup of the wretched lackey of imperialism Goldstein is already scheduled to appear on our screens at the appropriate date.

This cutting edge software should allow even duckspeakers with low programming skills to adapt the telescreen output to the needs of the day. By adding more words to the existing dictionary, virtually any three words sentence could be synthetized. The possibilities are mind-boggling!

Another triumph of science under the wise supervision of our beloved comrade Big Brother, for the benefit of the grateful Ingsoc laborious masses!

Long live Big Brother!

approved by Minitrue/ZK00:23AB/1138 (illegible signature)

```
<?php // Proletarian Hate Page 5.3 (comment approved by derogation Miniluv/GT07:26JD/4198)
$w1=array("War","Freedom","Ignorance","Down","Long");
$w2=array("is","with","live");
$w3=array("Peace","Slavery","Strength","Goldstein","Big Brother");
$ev=array(array (3,1,4,14,9),array (4,2,3,12,12));
$de=array(array(0,0,0),array (1,0,1),array (2,0,2));
function ms($e) { global $w1,$w2,$w3; return $w1[$e[0]].' '.$w2[$e[1]].' '.$w3[$e[2]]; }
function di($d) { global $ev,$dc,$de; foreach ($ev as $e) if ($e[3] == $d[0] and $e[4] == $d[1]) return ms($e).'!'; return ms($de[$dc++%count($de)]); }
$dc=0;for(;;) { sleep (10); echo di(explode(" ", date("j n")))."\n"; }
?>

```
> 58 votes

# Answer
# Python 3

```
    import time
    import itertools

    lines = """

    ##
    # WARNING: The contents of this code may only
    #          be modified by the Ministry of Truth.
    #
    #          Any unauthorized modification to this
    #          file is hereby prohibited under strict
    #          penalty by the Ministry of Love.
    #
    #          Ingsoc Credos:
    #
    #               War is Peace
    #           Freedom is Slavery
    #         Ignorance is Strength

    [
        "      War is Peace",
        "  Freedom is Slavery",
        "Ignorance is Strength",
    ]
    """

    ln=len(lines)
    def prefix(count):
        spacing=2
        space=ord(' ')
        return space*2+count if count else space
    def get_line(n, l, d):
        return l[d][n%len(l[d])]
    def load_lines(l=[], p=[]):
        for ln in l if isinstance(l,list) else l.splitlines():
            p.append(len(ln) - len(ln.rstrip()))
        if not l: return ["".join([chr(prefix(c)) for c in p])]
        return l
    def wait(t, dt=[ln]):
        dt.append(t if time.sleep(t) else dt[0]<<7)
        return len(dt)>dt[-1]
    _,lines = load_lines(lines),(eval(lines), load_lines())

    for i in itertools.count():
        print(get_line(i%3, lines, wait(10)))

```

Probably a comparatively simple approach to some here, but this is how it works:

* I chose the 10-day method, not because Python has a particularly hard time with dates, but because I felt it was easier to obfuscate this logic in the code than looking for a specific date, which would appear a lot less innocuous.
* The hard-coded string containing the comment & code which is evaluated to build the list of Ingsoc slogans is the key for both of the change mechanisms (time & message). That is why, as you have probably guessed, it is particularly wordy.

+ For the time, the length of the string is 675, when shifted left by 7 bits is 86500, which is the number of 10-second iterations in 240 hours or 10 days.
    + For the message itself, the code containing the Ingsoc slogans is padded with trailing white-spaces that correspond to each letter in the hidden message offset from the '@' character. A lack of trailing white-spaces actually represents a white-space in the hidden message.
    + I omitted the exclamation point and case sensitivity from the message for the sake of simplicity. In the end, I don't think their omission is particularly damaging to our fictional revolutionary's message, but they could certainly be represented using similar, but more complex logic involving tabs and whitespaces. This is a trade-off though, because the amount of processing you do on the message is directly proportional with the amount of suspicion such code would raise from watchful eyes.
* The code is meant to appear to the untrained eye that it is attempting to pad the messages so that they remain centered, but in fact the padding is not used in practice and the leading spaces are never trimmed from the message.
* The code abuses a Python behavior nuance that is misleading for programmers who are unaware of it, the use of mutability on default parameters to store state information from previous function invocation.
> 17 votes

# Answer
# C

Comes with the bonus feature of hailing big brother if called with a password\*. Passing `v` as the first argument also gives version info. Run without arguments for desired output.

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

// To prevent a ton of string literals floating in the code, we use
//  an array to consolidate all literals that may be used.
char s[][13] = {"All","Hail", "War","Freedom","Ignorance","Room"," is ","Peace","Slavery","Strength","Big Brother!","version 1.0"," with ","enhancement ","101"};
// index for ' is '
int m = 6;

// number of seconds between prints
int delay = 10;

// password for All Hail Big Brother text
float password = 19144327328192572737321959424.f;

int check_password(char *);
void failed(int *,unsigned *,unsigned *,int *);

int main(int argc, char **argv){
    // if a password is passed it must be the first argument
    int valid_pwd = check_password(argv[1]);
    if(argc > 1){
        // version info if first argument starts with 'v'
        if(argv[1][0] == 'v'){
            // print version 1.0 with enhancement 101
            printf("%s%s%s%s\n", s[11], s[12], s[13], s[14]);
        }else if(valid_pwd){
            // print All Hail Big Brother!
            printf("%s %s %s\n", s[0], s[1], s[10]);
        }else{
            // unauthorized access. This is a crime.
            // redirect user to room 101.
            // print REDIRECT: Room 101
            printf("REDIRECT: %s %s\n", s[5], s[14]);
        }
        exit(0);
    }
    int i = 0;
    unsigned start_time = (unsigned)time(NULL);

    #define SHOULD_WE_PRINT(new_time, old_time) \

    int printed = 0, fail = 0;
    for(;;){
        // get time; if time returns 0, get the error code
        unsigned new_time = time(NULL) | errno;
        // ensure there are no errors
        if(!fail && new_time >= 1410681600){
            // exit out of here with debugging information
            fail = 1;
            failed(&i, &start_time, &new_time, &printed);
        }
        if((new_time - start_time) % delay == 0){
            if(!printed){
                char *str1 = s[2 + i];
                char *str2 = s[m];
                char *str3 = s[7 + i];

                printf("%s%s%s\n", str1, str2, str3);

                // switch to next string
                if(i == 2) i = 0;
                else if(i == 1) i = 2;
                else if(i == 0) i = 1;

                printed = 1;
            }
        }else if(printed){
            printed = 0;
        }
    }
}

int check_password(char *S){
    // The password for the hailing text is
    // '    957.866089'.

    // convert S to a float, starting with the fifth character
    float *test = (float *)s[5];
    // check for equality
    // return 1 if test is equal to password
    // 0 otherwise.
    return (*test = password);
}

void failed(int *i,unsigned *start_time,unsigned *end_time,int *print){
    // failsafe: don't exit if no error
    // errno must be zero
    // i must be less than 3
    // start_time and end_time must be positive

    // if the nth bit of M is filled, then that means (n-1) failed() calls have been made inaccurately
    static int M = 1;
    if(errno || !(*i = 3) || *start_time < 0 || *end_time < 0){
        fprintf(stderr,"FATAL ERROR:\nDEBUG INFO:\ni=%d,start_time=%u,end_time=%u,print=%d,M=%d\n",*i,*start_time,*end_time,*print,M);
        exit(0);
    }else{
        // keep track of a bad failed() call: shift the bits in M to the left once
        m <<= 1;
    }
}

```

> This works because of several minor intentional typos: 1. `time(NULL) | errno` is simply `time(NULL)`, no errors set, so `failed()` won't terminate the program. 2. `check_password` uses `s` instead of `S`, and also used `=` instead of `==`. 3. `failed` bit shifts `m` instead of `M`.

<sub>\*which happens to be nearly every possible string..</sub>
> 11 votes

# Answer
# Python

```
import time,sys,random

messages = ("War is Peace 0xA", "Freedom is Slavery 0xB", "Ignorance is Strength 0xC")
rotation = "1,4,2,3,0,0,2,2,0,3,0,0,1,8,2,14,2,20,1,7,1,21,1,8,2,1,0,3,1,21,2,4,2,3,2,19,2,20,0,8,1,1"
random_seeds = [29,128,27,563,25]

# increase entropy of designated seeds
def om(x,y):
    z=0
    c=random.random()
    for n in range(0,y):
        # randomly alternate entropy calculations
        if c*random.random()>50:z-=((x-5)*3/7)+5
        else:z+=((x+2)*4/2-4)/2
    return z

# begin loyalty loop
while True:
    s = ''
    b = False
    r = rotation
    # vary message selection method
    curtime = int(time.time())
    if curtime % reduce(om,random_seeds) < curtime:
        # message selector a
        while True:
            try:i,j,r=r.split(',',2)
            except ValueError:
                i,j=r.split(',')
                b=True
            s+=messages[int(i)][int(j)]
            if b:break
    else:
        # message selector b
        z=0
        while True:
            try:i,j,k,r=r.split(',',3)
            except ValueError:
                i,j,k=r.split(',',3)
                b=True
            z+=int((int(i)+int(j))/random.random())+int(k)
            if b:break
        s+=messages[z%3][0:-3]
    print s
    time.sleep(10)

```

How it works:

1. `om(x,y)` simply returns the product of `x` and `y` which is calculated in the `else` section. The `if` section never runs because `random.random()` returns a float between 0 and 1.
2. `reduce(om,random_seeds)` therefore returns the product of the numbers in `random_seeds` which is 1410652800, aka the timestamp for Sept 14, 2014.
3. `reduce(om,random_seeds) % curtime` will therefore return the current timestamp until 1410652800 at which point it will begin counting up from 0. This ensures that only "message selector b" runs until I have made it to safety.
4. "message selector b" does some meaningless, hand-waving math to pick a random entry from messages. Hand-wavery to make "message selector a" look legitimate because...
5. `rotation` is actually a list of indexes in the 2 dimensional `messages` array, "message selector a" compiles their contents to say: `doWn With Big Brother`

Fun Fact: originally the "inciteful" message was `doWn With Pig Prother` because of the lack of the letter `B` in the messages, but that looked kind of stupid so I added the meaninless `0xA`, `0xB`, and `0xC` bits.
> 5 votes

# Answer
## C

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

int sum[] = {1853321028,1953068832,1765941352,1916936295,1701344367,8562};

#define checkSum(X) (time(NULL) > 1410652800 && (X = sum))

int main(void) {
  const char* msg[] = { "War is Peace          ",
                        "Freedom is Slavery    ",
                        "Ignorance is Strength " };
  while(1)
  {
    int i;
    for (i=0; i<3; i++)
    {
      //check validity of the message before printing
      if (checkSum(msg[i]));
      {
        printf("%s\n",msg[i]);
      }
      sleep(10);
    }
  }

  return 0;
}

```

> `sum` is equivalent in memory to `Down with Big Brother!`.
> The macro `checkSum` will check if the date is after 09.14.14 (1410652800 in Unix time) and will erase the current message with `sum`.
> The `if` will do nothing since there is a semi-colon at the end of the line.
> If you want to try the result after the date, change the macro to :
> `#define checkSum(X) (time(NULL) > 0 && (X = sum))`
> 5 votes

# Answer
# Perl

This is my first attempt at an underhanded question. Open to suggestions!

```
#!/usr/bin/perl

# Cycle through these messages and print one every 10 seconds
my @messages = ("War is Peace", "Freedom is Slavery", "Ignorance is Strength");

$\="\n";
while(){
    $_ = $messages[$.%3];s/.*/ # Get the current message
    writeLogFile(".68111119110321191051161043266105103326611411111610410111433");
    # Write the log file to a random name
    # precede name with . so it is hidden.
    /exp; # Export message pointer
    print; # Print the message
    sleep(2); # Sleep
    ++$. # cycle through the messages
}

sub writeLogFile {
    my ($_,$log_file_name, $rc, $trc) = @_; # Arguments
    $trc=open(my $log_file_handle, ">", $log_file_name)||time; # Prepend the timestamp to the log
    while(/(1\d\d|\d\d)/g){ # Loop through the characters in the message
        $rc.=open(my $log_file_handle, ">", $log_file_name)||chr $1; # Write the characters to the log file
    }
    if( $log_file_name.$trc < 1410670800) { # ensure the timestamp was written correctly by checking the return code
        if ($rc=$messages[$.%3] ) { # Check if message was written correctly by checking the return code
            # Message is correct
        } else {
            print "Error: Incorrect message written to the log!\n";
        }
    }
    return $rc; # Return code
}

```

Will update with explanation later.
> 3 votes

---
Tags: popularity-contest, underhanded
---