title: Cross Language Troll

text:
# Question
Title: Cross Language Troll
**The Setup**
Jim the student who attempts to use Stack Overflow to do his homework has asked how to get his program to say "Hello World" in under 100 lines of code, you decide mere mortal trolling is not enough...

**The Challenge**
You need to provide Jim with a program less than 100 lines long that outputs a satisfactory answer in another language. Bonus points for additional languages.

**The Rules**
1. Max 100 lines of code
2. 10 points for successfully outputting the answer in another language
3. +1 point for every additional language answer is provided for
4. Honorable mentions will be given to the most creative, most evil, and most unorthodox answers
5. Challenge ends 23:59pm GMT 3/14/2014 (results provided a few hours post challenge)

The winner is Michael who converted between six languages first

I also will give an honorable mention for cleverness to McMillin for using one command that works in several languages

I also give an honorable mention to Comintern... I don't actually know if brownies is a language, but I think we can agree it was unorthodox.

I don't think any of the answers qualifies as evil, but for the sake of it everyone who used brainfuckery will be considered recipients.

# Answer
> 10 votes
## JavaScript to C to PHP to JavaScript to Brainfuck to HQ9+

```
atob("bWFpbigpe3B1dHMoImVjaG8gXCJjb25zb2xlLmxvZygnKysrKysrWz4rKysrKysrKysrKys8LV0+LicpO1wiOyIpO30=")

```

This outputs :

```
main(){puts("echo \"console.log('++++++[>++++++++++++<-]>.');\";");}

```

Which outputs :

```
echo "console.log('++++++[>++++++++++++<-]>.');";

```

Which outputs :

```
console.log('++++++[>++++++++++++<-]>.');

```

Which outputs :

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

```

Which outputs :

```
H

```

Which outputs :

```
Hello World!

```

# Answer
> 17 votes
## Bash

```
echo Bonjour tout le monde

```

Outputs "Hello World" in a language called French.

# Answer
> 5 votes
## C# -\> Chef -\> German\Brownies

```
using System;
using System.Text;

namespace Greetings
{
    class Program
    {
        static string[] ingredients = {" vegetable oil "," eggs "," boiling water "," vanilla "," cocoa powder "," flour "," sugar "," baking soda "," salt "};
        static string[] measures = {" tablespoons"," dashes"," heaped tablespoons",""," pinches"};
        static int[] amounts = {154,32,157,127,110,145,164,141,154};
        static int[] units = {0,3,0,1,2,2,2,4,4};
        static int[] steps = {4,7,0,8,2,1,3,5,0,6};

        static void Main(string[] args)
        {
            StringBuilder sb = new StringBuilder("Fudge Brownies.\n\nThis recipe makes an absurd amount of brownies for one person.\n");
            sb.Append("\nPre-heat oven to 175 degrees Celsius.\n\nIngredients.\n");

            for (int i = 0; i < ingredients.Length; i++)
            {
                sb.Append(amounts[i]);
                sb.Append(measures[units[i]]);
                sb.Append(ingredients[i]);
                sb.Append("\n");
            }

            sb.Append("\nMethod.\n");

            for (int i = 0; i < steps.Length; i++)
            {
                sb.Append("Put");
                sb.Append(ingredients[steps[i]]);
                sb.Append("into the mixing bowl.\n");
            }

            sb.Append("Liquefy contents of the mixing bowl.\nPour contents of the mixing bowl into the baking dish.\n");
            sb.Append("\nCooking time: time 40 minutes.\n\nServes 1.");
            Console.WriteLine(sb);
        }
    }
}

```

The C# code above outputs the Chef code below (which is also a pretty tasty brownie recipe).

```
Fudge Brownies.

This recipe makes an absurd amount of brownies for one person.

Pre-heat oven to 175 degrees Celsius.

Ingredients.
154 tablespoons vegetable oil
32 eggs
157 tablespoons boiling water
127 dashes vanilla
110 heaped tablespoons cocoa powder
145 heaped tablespoons flour
164 heaped tablespoons sugar
141 pinches baking soda
154 pinches salt

Method.
Put cocoa powder into the mixing bowl.
Put baking soda into the mixing bowl.
Put vegetable oil into the mixing bowl.
Put salt into the mixing bowl.
Put boiling water into the mixing bowl.
Put eggs into the mixing bowl.
Put vanilla into the mixing bowl.
Put flour into the mixing bowl.
Put vegetable oil into the mixing bowl.
Put sugar into the mixing bowl.
Liquefy contents of the mixing bowl.
Pour contents of the mixing bowl into the baking dish.

Cooking time: time 40 minutes.

Serves 1.

```

The hardest part was doing the unit conversions on the recipe, and it really does make an absurd amount of brownies, even for a whole bunch of people. When run through a Chef interpreter, it outputs:

```
Hallo Welt

```

Or, "Hello World" in German. I'm not sure if "brownies" technically constitutes a language. If it does, it probably isn't Turing complete.

# Answer
> 2 votes
# Fortran 95 to Batch back to Fortran 95

```
open(unit=11,file="FOO.BAT")
write(11,"(A)") "@ECHO OFF"
write(11,"(A)") 'ECHO print*, "Hello World!"; end > BAR.F95'
call SYSTEM("FOO.BAT")
call SYSTEM("gfortran BAR.F95 -o BAR.EXE")
call SYSTEM("BAR.EXE")
end

```

This code produces a file named FOO.BAT, and then executes it automatically. This .BAT file will generate another file named BAR.F95, which is a Fortran code. This code is automatically compiled and executed, finally producing the phrase "Hello World!"

# Answer
> 1 votes
# C++/JavaScript/Python 3

A oneliner:

```
int main(){puts("alert(\"print(\\\"Hello World!\\\")\")");}

```

Output is a program in JavaScript that outputs the basic Hello World program in Python 3.

# Answer
> 1 votes
**Perl/Ruby/Python(2)/Fortran/SML**

```
print "Hello World";

```

---
Tags: code-challenge
---


title: ASCII Art Generator

text:
# Question
Title: ASCII Art Generator
Your goal is to write a program / script which "converts" real images into ascii art.

**General:**
Your program will get a path to a image file over stdin or as parameter (whatever you prefer). The format will be jpeg.
It should "convert" it to ascii art and save it to the harddrive.
The image will be in grayscale. You don't have to check if the input file exists or the file is a valid image.
You can use any utf-8 character in your outputfile.

**Rules:**

* You must be able to recognize the output image.
* Your program must recognize the path on `stdin` or parameters
* The content of the original image must be read from the drive (you get only the path to the file)
* No user interaction (except giving the parameters at startup) allowed
* Must terminate without any error message
* The output must be written to the harddrive (output name is up to you)
* Only turing complete languages allowed.
* If you require any special language version for your program you have to add it to your answer. Otherwise the newest stable version will be used (e.g. python = python 3.3)

**Bonus points:**

* -10 Points for every additional image format your program can convert (please write down which formats can be recognized)
* -25 Points if your program can change the output size (width / height parameters at startup in characters)
* -100 Points if you don't use any Image Processing libraries (e.g. PIL, ImageMagic, GD...)
* -50 Points if your program source looks like ascii art itself ;)

**Formula to calculate your points:**

`points = floor(programSize (in Bytes) * avgRuntimeOnTestInput (in seconds) - BonusPoints)`

**How your program will be tested:**
All programs will run on a new virtual machine running Debian x64 (current version) with 512MB memory, 2x3,4Ghz CPU.
The time will be calculated on an average of three pictures per format with different size and content (every program will be use the same files).
Please write your programcall into your answer so i can check it (and if required the needed compile parameters).
Example program call (with bonus parameters):
`python ascii.py -file /home/chill0r/test/MyPicture.jpeg -width 1000 -height 750 -out /home/chill0r/test/MyPictureAscii.txt`
I'll check the answers every few days and post a 'low score' (*high score* doesn't really fit on code golf...). (Meaning you don't have to calculate your points on your own)

# Answer
> 11 votes
# Mathematica

`asciiPhoto[image_,rastersize_:125,shades_:3]` scans the image according to the raster size (default=125), quantizes it into up to 7 shades (3 by default), then replaces the shading with ASCII characters of varying darkness. Hints about relative darkness found here. The characters are stored in `shades`; for some reason, 2 of them disappeared in the cut and paste to SE.

```
asciiPhoto[image_,rastersize_:125,shades_:3]:=
Module[{chars,gray},
chars={{},{"M"," "},{"","/"," "},{"P","o","/"," "},{"W","o","/",""," "},
{"","b","o","/",""," "},{"","M","b","o","/",""," "},};
gray=ImageData[ColorQuantize[Rasterize[image,RasterSize->rastersize+1,
ImageSize->rastersize],shades]];
GraphicsGrid[gray/.Thread[Union@Flatten[gray,1]->chars[[shades]]],ImageSize->500]]

```

## Examples

Render the merganser with a raster size of 35 in 4 shades; compare it to a raster size of 85 with 5 shades.

```
{asciiPhoto[merganzer, 35, 4], asciiPhoto[merganzer, 85, 5]}

```

---

---

Raster size of 125 in 2 shades; same raster size with 7 shades.

```
{asciiPhoto[merganzer, 125, 2], asciiPhoto[merganzer, 125, 7]}

```

---

Let's not forget Greta.

---
Tags: ascii-art, code-challenge
---


title: Could you please tell me the time?

text:
# Question
Title: Could you please tell me the time?
You know that your language's clock/time API's are broken and they are not reliable at all.

So you are not allowed to use any built-in API to access system time/date.

But you also know that your language's ability to perform date math, and retaining a date/time value in a variable are correct.

Write a program that prints the current date/time without calling any date/time/clock API's. For example `DateTime.Now`, `GetDate()` and similar functions are not allowed.

The answer with most upvotes wins.

In case of a tie, the answer with more precision wins (that is, accurate up to seconds, then milliseconds, then microseconds, and so on).

# Answer
# Java

Almost all of the current solutions assume that local/remote computer is not lying about a current time (would you believe T-600 as well?) .
Key point in time calculation is trusting a **pure nature**.
This Android app asks user to take photo of the sky and it's predicting current time with outstanding precision:

```
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
   if (resultCode == RESULT_OK)
   {
      Uri selectedImageUri = data.getData();
      this.imageView.setImageURI(selectedImageUri);

      TimeGuesser guesser = new TimeGuesser(this);
      String result = guesser.guessTimeFromImage(selectedImageUri);
      this.textView.setText(result);
   }
}

public class TimeGuesser {

    private Context context;
    public TimeGuesser(Context context)
    {
        super();
        this.context = context;
    }

    public String guessTimeFromImage(Uri uri) {
        Bitmap bitmap = null;
        try {
            bitmap = MediaStore.Images.Media.getBitmap(this.context.getContentResolver(), uri);
        } catch (IOException e) {
            return "There is no sky. Everyone's going to die";
        }

        float brightness = getBrightness(bitmap);

        if (brightness < 90.0)
        {
            return "It's sooo late";
        } else {
            return "It's sooo early";
        }
    }

    private float getBrightness(Bitmap bitmap)
    {
        float R, G, B;
        R = G = B = 0.0f;
        int pixelColor;
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int size = width * height;

        for (int x = 0; x < width; ++x) {
            for (int y = 0; y < height; ++y) {
                pixelColor = bitmap.getPixel(x, y);
                R += Color.red(pixelColor);
                G += Color.green(pixelColor);
                B += Color.blue(pixelColor);
            }
        }

        R /= size;
        G /= size;
        B /= size;

        float brightness =  (0.2126f*R ) + (0.7152f*G) + (0.0722f*B);
        return brightness;
    }
}

```

## Results:

---
> 122 votes

# Answer
# Ruby

Let's be honest: time only changes when something is posted on stackoverflow.com ;)

The script extracts the time of the "XYs ago" label in the topmost question.

```
require 'net/http'
source = Net::HTTP.get('stackoverflow.com', '/')

puts source.match(/span title=\"(.*)\" class=\"relativetime/)[1]

```

Output:

```
2014-03-10 18:40:05Z

```
> 64 votes

# Answer
## Bash

Like this? (requires `wget` and `grep`)

```
wget -qO- 'http://www.wolframalpha.com/input/?i=current+time'|grep ' am \| pm '

```

The output I got a few minutes ago:

```
                    Why am I seeing this message?
  context.jsonArray.popups.pod_0200.push( {"stringified": "6:08:38 pm GMT\/BST  |  Monday, March 10, 2014","mInput": "","mOutput": "", "popLinks": {} });

```

Or this? (requires `wget` and `eog`)

```
wget http://c.xkcd.com/redirect/comic/now
eog ./now
rm ./now

```

Output I get now: (Image by xkcd)

world map with timezone http://c.xkcd.com/redirect/comic/now
> 30 votes

# Answer
# sh/coreutils

```
touch . && stat . -c %z

```

Outputs the date in somewhat nonstandard format:
`YYYY-MM-DD hh:mm:ss.nanoseconds +timezone`
Although I guess it might depend on the locale.
> 29 votes

# Answer
## PHP

Exploit the fact that `uniqid()` returns an ID based on the time.

```
$u=hexdec(substr(uniqid(),0,8));

$y=floor($u/31536000);
$u-=$y*31536000;
$y+=1970;

$d=floor($u/86400);
$u-=$d*86400;

$h=floor($u/3600);
$u-=$h*3600;

$m=floor($u/60);

$s=$u-$m*60;

echo 'Year='.$y.' Days='.$d.' Hours='.$h.' Minutes='.$m.' Seconds='.$s;

```

During my test, it returned : `Year=2014 Days=79 Hours=18 Minutes=9 Seconds=49`.
I don't know if I can use `date` to format correctly, so I converted it manually.
> 25 votes

# Answer
**Bash**

Just to be always absolutely precise and correct:

```
echo "Now"

```

or motivating:

```
echo "Now, do something useful today"

```
> 24 votes

# Answer
# DNS

Do we only mistrust our own machine? If so, does this count?

```
ssh $othermachine date

```

If that doesn't count, extracting time from DNS update definitely does:

```
dig stackexchange.com | grep WHEN

```
> 23 votes

# Answer
# curl - accurate to whatever your ping rate is

```
curl -s time.nist.gov:13

```
> 20 votes

# Answer
# Python

You sure you don't know what time is it?!? Here's a reminder:

```
print "It's Adventure Time!"

```
> 14 votes

# Answer
# Python 2

So, the clock is correct but the time API is hosed, right? Why not check a raw filesystem timestamp. Instead of creating a test file, we just use our own access timestamp since the script *has* to be read to run (even if it's been compiled). Accurate to the second.\*

```
import os
h, m = divmod(os.stat('t.py').st_atime % 86400, 3600)
print h+1, m // 60, m % 60

```

This should be saved and run as `t.py`. Alternately, get the script name at runtime with `inspect.getfile(inspect.currentframe())`

Note * Occasionally accurate to the *previous* second.
> 13 votes

# Answer
## Ruby

HTTP, but just using response meta-data.

```
require 'uri'
require 'net/http'

def get_now
  uri = URI.parse("http://google.com")
  http = Net::HTTP.new(uri.host, uri.port)
  request = Net::HTTP::Get.new(uri.request_uri)
  rsp = http.request(request)
  rsp['date']
end

```
> 10 votes

# Answer
# ps

Can't `ps` tell the time? It can!

```
sleep 1&  ps -o lstart -p $!

```

The process is started in the background and `ps` tells the time the process started. Since the process started in the background, the start time of the process is *pretty much* the same time as now.

Moreover, the advantage is that the time is obtained in the local time zone. And you don't need a internet connection either!
> 9 votes

# Answer
## vba

because I shouldn't.

```
Public Function DateTime() As String
Dim myNTPsvr As String
Dim dattime As String
Dim oHTTP As Object

myNTPsvr = "time.windows.com"
Set oHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
oHTTP.Open "GET", "http://" & myNTPsvr & "/", False
oHTTP.Send

DateTime = oHTTP.GetResponseHeader("Date")

Set oHTTP = Nothing
End Function

```

use `?DateTime` to use, or if you put it into Excel, then `=DateTime()` will work as a formula.
The date/time is returned in GMT - I leave it as an exercise in futility to convert it from a string to local time
> 7 votes

# Answer
# Bash + `last` \+ `head` \+ `cut`

Precise to the second. `last` uses the log file `/var/log/wtmp`

```
$ last -RF reboot | head -n1 | cut -c50-73
Tue Mar 11 09:38:53 2014
$

```

EDIT: Added `head` to limit to only one line.

EDIT: This works on Linux Mint 13 Cinnamon 64-bit but it seems that this is depends on your distro. `sysvinit-utils` (which provides `last`) version is `2.88dsf-13.10ubuntu11.1` `last` reads from `/var/log/wtmp` (in my case) so the results depend on that log file. See comments below.

EDIT: Apparently this depends on the system uptime so you can see the proof here https://i.stack.imgur.com/rVS5B.jpg
> 6 votes

# Answer
## Python

Getting nanosecond precision would be tricky unless the returned time was based on when the program finishes running, not when it starts. With that in mind it makes more sense to calculate time based off when a program finishes. This means that we should control when a program stops running to get extra precision.

```
import subprocess

def what_day_is_it(): return int(subprocess.check_output(["date", "+%dd"]))[:-2];

current_day = next_day = what_day_is_it # It's a bash call,
while not current_day - next_day:
  next_day = what_day_is_it()
print "It's midnight."
print "Probably."

```

Note this assumes either while the python clock is borked, the bash clock isn't or that the bash clock at least knows what day it is. If not, we can instead use this:

```
def what_year_is_it(): return int(subprocess.check_output(["date", "+%yy"]))[:-2];

```

Might be slightly slower, though. I haven't tested it.
> 5 votes

# Answer
# BrainFuck

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

```

Output:

```
5PM

```

I think it displays the time in Denver at the time of writing. The explanation for the algorithm here by this Alan Jackson video.
> 5 votes

# Answer
# Ruby

```
`date`

```

Doesn't use the language's clock/time API.
> 5 votes

# Answer
I liked the "reading from a time server" idea. Improved its formatting though, and added some cities for fun.

# PHP

```
$page = file_get_contents("http://www.timeapi.org/utc/now");
echo "In London: ".date("H:i:s - jS F, Y", strtotime($page))."<br>";
echo "In Rome: ".date("H:i:s - jS F, Y", strtotime($page)+3600)."<br>";
echo "In Athens: ".date("H:i:s - jS F, Y", strtotime($page)+7200)."<br>";

```
> 4 votes

# Answer
# Bash

```
echo "It's eight o'clock."

```

With thanks to The Goon Show. (Also, it's right twice a day!)
> 4 votes

# Answer
## C/WinAPI

This makes the assumption that my own API calls to query the clock are broken, but the system itself can work with the time correctly.

```
// NO ERROR CHECKING - that's left as an exercise for the reader
TCHAR tmpfilename[MAX_PATH];
TCHAR tmpfilepath[MAX_PATH];

// get some information to create a temporary file
DWORD dwRes = GetTempPath(MAX_PATH, tmpfilepath);
UINT uiRes  = GetTempFileName(tmpfilepath, TEXT("golftime"), 0, tmpfilename);

// create the file
HANDLE hTempFile = CreateFile(tmpfilename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

// read the creation time of the file. accuracy is to, uhm... 10ms on NTFS?
FILETIME created;
GetFileTime(hTempFile, &created, NULL, NULL);

// convert the filetime to a system time (in UTC)
SYSTEMTIME systime;
FileTimeToSystemTime(&created, &systime);

std::cout << "Time is " <<
    systime.wHour << ":" << systime.wMinute << ":" << systime.wSecond << "." << systime.wMilliseconds << "\n";

// close the file and delete
CloseHandle(hTempFile);
DeleteFile(tmpfilename);

```

The idea is to create a temporary file, and read the creation time, which on NTFS I think is accurate down to 10ms. Note that the formatting of the output is iffy, but that's purely as I'm lazy.

Output on my machine just now: `Time is 10:39:45.790`
> 4 votes

# Answer
### Batch

```
@echo off
echo.>>%0
for /f "tokens=2,3 skip=4" %%a in ('dir /TW %0') do echo %%a %%b & goto :EOF

```

Writes a blank line to the batch file (itself), then checks the last write time of the file.

```
H:\uprof>GetTime.bat
09:28 AM

H:\uprof>GetTime.bat
09:29 AM

```
> 4 votes

# Answer
**HTML, CSS & Javascript/jQuery**

Ok, so I know this isn't technically a program, and probably falls outside of the criteria, but in only a few hours time, this will be the most accurate clock in the world!

CSS

```
@font-face {
    font-family:"DSDIGI";
    src:url("http://fontsforweb.com/public/fonts/1091/DSDIGI.eot") format("eot"),
    url("http://fontsforweb.com/public/fonts/1091/DSDIGI.ttf") format("truetype");
    font-weight:normal;
    font-style:normal;
}
#backer {
    background-image: url('http://i.imgur.com/w3W5TPd.jpg');
    width: 450px;
    height: 354px;
    color: red;
    font-family: 'DSDIGI';
}
#backer p {
    width: 100%;
    display: block;
    line-height: 325px;
    font-size: 60px;
}

```

HTML

```
<div id="backer">
    <p>
        BEER<span id="fade">:</span>30
    </p>
</div>

```

jQuery

```
function start() {
    $('#fade').fadeOut(function() {
        $('#fade').fadeIn();
    });
    setTimeout(start, 1000);
}
start();

```

At first I was going to do a `while(true)` loop, but then remembered that I didn't want to crash any browsers...

Here is a fiddle of it in action: http://jsfiddle.net/E7Egu/
> 3 votes

# Answer
## Emacs Lisp

The google thing has been done but not in emacs!

```
(url-retrieve "http://www.google.com/search?q=time" (lambda(l)
        (search-forward-regexp "[0-9]?[0-9]:[0-9][0-9][ap]m")
        (print (buffer-substring (point) (1+ (search-backward ">"))))))

```
> 3 votes

# Answer
node.js / Javascript

```
var fs = require('fs'),
    util = require('util');

var date = null, time = null;

fs.readFile('/sys/class/rtc/rtc0/date', 'UTF-8', function(err, d) {
    date = d.trim();
    if(time)
        done();
})

fs.readFile('/sys/class/rtc/rtc0/time', 'UTF-8', function(err, t) {
    time = t.trim();
    if(date)
        done();
});

function done() {
    console.log(util.format('%sT%sZ', date, time));
}

```
> 2 votes

# Answer
# JavaScript

```
new Date(performance.timing.navigationStart+performance.now())+''

```

Since clock/time API is broken, I use Performance API to get the time. Then `Date` is only used to parse it to string.
> 1 votes

# Answer
# PHP:

```
 $n=PHP_SHLIB_SUFFIX=='dll'?strtotime(str_replace(PHP_EOL,' ',`date /t&time /t`).' GMT'):`date +%s`;

```

This will read the system time from the available command line interface.

The backtick operator is used to do just that: run a command.

Another way would be:

```
$_SERVER['REQUEST_TIME'];

```

Which contains the **current** time at which the script was called.
> 1 votes

# Answer
## Bash

```
export PS1="(\t) $PS1"

```

Skirts the rules a little bit, but it never calls a time function. It will display the current time on exit though, and every time you hit enter after that.
> 1 votes

# Answer
**C#**

This super-exact method will work - provided you'll run the program at 0:00:00,0000

```
using System;
using System.Threading;

namespace ConsoleApplication1 {
  class Program {
    private static volatile int s_Hour;
    private static volatile int s_Minute;
    private static volatile int s_Second;
    private static volatile int s_Millisecond;

    class Looper {
      public int Length { get; set; }
      public Action Update { get; set; }
    }

    static void Loop(object args) {
      var looper = (Looper)args;
      while (true) {
        Thread.Sleep(looper.Length);
        looper.Update.Invoke();
      }
    }

    static void Main(string[] args) {
      var starter = new ParameterizedThreadStart(Loop);
      new Thread(starter).Start(new Looper { Length = 100, Update = () => { s_Millisecond = (s_Millisecond + 100) % 1000; } });
      new Thread(starter).Start(new Looper { Length = 1000, Update = () => { s_Second = (s_Second + 1) % 60; } });
      new Thread(starter).Start(new Looper { Length = 60 * 1000, Update = () => { s_Minute = (s_Minute + 1) % 60; } });
      new Thread(starter).Start(new Looper { Length = 60 * 60 * 1000, Update = () => { s_Hour++; } });

      Console.Out.WriteLine(@"Press e to exit, enter to write current time...");
      while (true) {
        string input = Console.In.ReadLine();
        if (input == "e") {
          Environment.Exit(0);
          return;
        }
        Console.Out.WriteLine("{0:00}:{1:00}:{2:00},{3}", s_Hour, s_Minute, s_Second, s_Millisecond);
      }
    }
  }
}

```
> 1 votes

# Answer
Linux, most shells, on hardware with an RTC:

```
echo `cat /sys/class/rtc/rtc0/{date,time} | tr "\n" " "`

```
> 1 votes

# Answer
## Java

We all know Java Date/Time API is unusable and broken. So here's a fix that does not (at least directly) use any of the existing API. It even supports leap seconds! :) The output is in UTC.

```
import java.lang.reflect.Field;
import java.net.HttpCookie;
import java.util.*;

public class FixedTimeAPI4Java {

    private static final List<Integer> MONTHS_WITH_30_DAYS = Arrays.asList(4, 6, 9, 11);
    private static final List<Integer> YEARS_WITH_LEAP_SECOND_IN_DECEMBER = Arrays.asList(1972, 1973, 1974, 1975, 1976, 1977, 1978, 1979, 1987, 1989, 1990, 1995, 1998, 2005, 2008);
    private static final List<Integer> YEARS_WITH_LEAP_SECOND_IN_JUNE =  Arrays.asList(1972, 1981, 1982, 1983, 1985, 1992, 1993, 1994, 1997, 2012);

    /**
    * Returns the UTC time, at the time of method invocation, with millisecond
    * precision, in format <code>yyyy-MM-dd HH:mm:ss.SSS</code>.
    */
    public String getTime() throws Exception {

        // The cookie is only used for accessing current system time
        HttpCookie cookie = new HttpCookie("Offline", "Cookie");
        Field created = HttpCookie.class.getDeclaredField("whenCreated");
        created.setAccessible(true);

        long millisecondsSinceEpoch = created.getLong(cookie);
        long fullSecondsSinceEpoch = millisecondsSinceEpoch / 1000L;

        int year = 1970, month = 1, dayOfMonth = 1, hour = 0, minute = 0, second = 0,
            millisecond = (int)(millisecondsSinceEpoch - (fullSecondsSinceEpoch * 1000L));

        ticks:
        for (;; year++) {
            for (month = 1; month <= 12; month++) {
                for (dayOfMonth = 1; dayOfMonth <= daysInMonth(month, year); dayOfMonth++) {
                    for (hour = 0; hour < 24; hour++) {
                        for (minute = 0; minute < 60; minute++) {
                            for (second = 0; second < secondsInMinute(minute, hour, dayOfMonth, month, year); second++, fullSecondsSinceEpoch--) {
                                if (fullSecondsSinceEpoch == 0) {
                                    break ticks;
                                }
                            }
                        }
                    }
                }
            }
        }
        return String.format("%04d-%02d-%02d %02d:%02d:%02d.%03d", year, month,
            dayOfMonth, hour, minute, second, millisecond);
    }

    /**
     * Returns the seconds in the given minute of the given hour/day/month/year,
     * taking into account leap seconds that can be added to the last minute of
     * June or December.
     */
    private static int secondsInMinute(int minute, int hour, int day, int month, int year) {
        return (minute == 59 && hour == 23 && ((day == 30 && month == 6) || (day == 31 && month == 12)))
                ? 60 + leapSecondsInMonth( month, year)
                : 60;
    }

    /**
     * Returns the number of days in the given month of the given year.
     */
    private static int daysInMonth(int month, int year) {
        return month == 2 ? isLeapYear(year) ? 29 : 28
                : MONTHS_WITH_30_DAYS.contains(month) ? 30
                    : 31;
    }

    /**
     * Returns whether the given year is a leap year or not.
     * A leap year is every 4th year, but not if the year is divisible by 100, unless if it's divisible by 400.
     */
    private static boolean isLeapYear(int year) {
        return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? true : false;
    }

    /**
     * Returns the number of leap seconds that were added to UTC time at the end of the given month and year.
     * Leap seconds are added (by the decison of International Earth Rotation Service / Paris Observatory)
     * in order to keep UTC within 0.9 seconds of international atomic time (TAI).
     * <p>TODO: implement parser for updated list at http://www.ietf.org/timezones/data/leap-seconds.list :)
     */
    private static int leapSecondsInMonth(int month, int year) {
        return (year < 1972 || year > 2012) ? 0
                : (month == 6 && YEARS_WITH_LEAP_SECOND_IN_JUNE.contains(year)) ? 1
                    : (month == 12 && YEARS_WITH_LEAP_SECOND_IN_DECEMBER.contains(year)) ? 1
                        : 0;
    }

    public final static void main(String[] args) throws Exception {
        System.out.println(new FixedTimeAPI4Java().getTime());
    }
}

```
> 1 votes

# Answer
# HTML

Pure HTML, no Javascript or anything. Less is more.

```
<title>Time</title>
<iframe src="http://wwp.greenwichmeantime.com/time/scripts/clock-8/runner.php"></iframe>

```

jsFiddle
> 1 votes

# Answer
**Python** *in a linux xterm*

```
import os
n=os.stat('/dev/ptmx')[7]
n,s=divmod(n,60)
n,m=divmod(n,60)
n,h=divmod(n,24)
y,d=divmod(n,365)
print "It is {}:{}:{} GMT on the {}th day of {}".format(
    h,m,s,d-(y/4-1),y+1970)

```

`/dev/ptmx/` has its timestamp updated every time the xterm is written to, which includes the command invocation.
> 1 votes

# Answer
## CPython

gettime.py:

```
import struct
import gettime

if __name__ == '__main__':
    print struct.unpack('i', open('gettime.pyc').read()[4:8])[0], 'seconds after Unix epoch'

```

The self-import statement compiles it to a `.pyc` file, which contains the timestamp as the second 4-byte word.

Doesn't work multiple times in a row unless you change the .py file or delete the .pyc file.
> 0 votes

# Answer
## Groovy

```
def latLong = "http://www.ipligence.com/geolocation".toURL().text =~ /GLatLng\(([^)]*)/
def lat= latLong[0][1].tokenize(",")[0].trim()
def lng = latLong[0][1].tokenize(",")[1].trim()
def xml = "http://www.earthtools.org/timezone/${lat}/${lng}".toURL().text
println new XmlSlurper().parseText(xml).localtime

```

Get latitude and longitude by IP address, then make a Http request to a time server via the latitude and longitude.
> 0 votes

# Answer
## Wolfram Language

```
WolframAlpha["now", {{"Result", 1}, "Plaintext"}]

> 11:15:35 pm MSK  |  Monday, March 10, 2014

```
> -2 votes

---
Tags: popularity-contest
---


title: Minesweeper Solver

text:
# Question
Title: Minesweeper Solver
We already generated Minesweeper fields, but someone really has to sweep those generated mines before PCG blows up!

Your task is to write a Minesweeper Solver that is compatible with a slightly modified version of the accepted solution of “Working Minesweeper” (actions are separated by spaces to allow for larger fields).

**Input:** A Minesweeper field, fields separated by spaces. The first line denotes the total number of mines.

* `x`: Untouched
* `!`: Flag
* Digit: Number of mines around that field

Example:

```
10
0 0 1 x x x x x
0 0 2 x x x x x
0 0 2 ! x x x x
0 0 1 2 x x x x
0 0 0 1 x x x x
1 1 0 2 x x x x
x 1 0 2 x x x x
1 1 0 1 x x x x

```

**Output:** Your next step in the format `action row column` (starting at zero)

Valid Actions:

* `0`: Open it
* `1`: Place a flag

Example:

```
0 1 2

```

**Rules:**

* You write a complete program that takes a single field as input (either STDIN or command line arguments) and outputs a single action (STDOUT). Therefore, you cannot save states, except for `!`.
* Your choice must follow the best odds for survival. (i.e. if there is a 100% safe move, take it)
* This is ; the shortest solution (in UTF-8 bytes) wins

**Tests:**

These tests serve the purpose of testing for common clear situations; your program must work for every test field.

In:

```
4
x x x x
1 2 x x
0 1 2 x
0 0 1 x

```

Out (any of these):

```
1 1 2
0 0 2
0 1 3

```

In:

```
2
x x x
1 ! x
1 1 x

```

Out (any of these):

```
0 0 0
0 0 1
0 1 2
0 2 2
1 0 2

```

In:

```
10
x x x x x x x x
1 3 3 x x x x x
0 1 ! 3 3 4 x x
0 2 3 ! 2 3 x x
0 1 ! 2 2 ! x x

```

Out (any of these):

```
1 1 5
1 0 2

```

In:

```
2
x x x
2 3 1
! 1 0

```

Out (any of these):

```
0 0 1
1 0 0
1 0 2

```

# Answer
> 18 votes
## Mathematica

Still not golfed. Needs some more work on I/O formats.

```
t = {{0, 0, 1, x, x, x, x, x}, {0, 0, 2, x, x, x, x, x}, {0, 0, 2, F, x, x, x, x},
     {0, 0, 1, 2, x, x, x, x}, {0, 0, 0, 1, x, x, x, x}, {1, 1, 0, 2, x, x, x, x},
     {x, 1, 0, 2, x, x, x, x}, {1, 1, 0, 1, x, x, x, x}};
(*Sqrt[2] is  1.5*)
c = Sequence; p = Position;
nums = p[t, _?NumberQ];
fx = Nearest[p[t, x]];
flagMinus[flag_] := If[Norm[# - flag] < 1.5, t[[c @@ #]]--] & /@ nums
flagMinus /@ p[t, F];
g@x_List := Tr[q[#] & /@ x]
eqs = MapIndexed[t[[c @@ (nums[[#2]][[1]])]] == g[#1] &, (fx[#, {8, 1.5}] & /@nums)];
vars = Union@Cases[eqs, _q, 4];
s = Solve[Join[eqs, Thread[0 <= vars < 2]], vars, Integers];
res = (Transpose@s)[[All, All, 2]];
i = 1; plays = Select[{i++, #[[1]], Equal @@ #} & /@ res, #[[3]] &];
Flatten /@ ({#[[2]] /. 1 -> F, List @@ vars[[#[[1]]]] - 1} & /@ plays)

(*
{{0, 0, 3}, {F, 1, 3}, {F, 2, 4}, {0, 3, 4}, {0, 4, 4},
 {F, 5, 4}, {F, 6, 0}, {F, 6, 4}, {0, 7, 4}}
*)

```

**Edit: Bonus Track**

I made up an interactive playground that calculates bomb probabilities by calculating all possible solutions for a given configuration:

Instructions for testing it without Mathematica installed:

1. Download http://pastebin.com/asLC47BW and save it as \*.CDF
2. Dowload the free CDF environment from Wolfram Research at https://www.wolfram.com/cdf-player/ (not a small file)

The slider changes the board dimensions. This is just a sketchy program, not fully tested, please report any bugs. I haven't implemented a "total number of available bombs on board" feature. It's assumed infinite.

---
Tags: code-golf, game, minesweeper
---


# Question
Title: What do you see in an inkspot? Rorschach generation'
So I'd like you to attempt to generate Rorschach images like the below image:

Here is a link to further inspiration.

This is a popularity contest, but I will say that colours are likely to be more popular than black and white, as well as textures.

Rorschach images are created by folding paper with ink on so one criteria is symmetry.

ASCII art is valid, but will be subject to the same criteria as above.

# Answer
# Fortran 95

This code is kind of big, but it produces a nice(ish) ASCii result:

```
program Rorschach
implicit none

integer :: i, j, k, l, N, seed
integer, dimension (24) :: i_zero, j_zero
real :: aux
integer, dimension (17,12) :: matrix_I = 0
character, dimension (17,12) :: matrix_C

! random seed according to system clock
call SYSTEM_CLOCK(count=k)
call RANDOM_SEED(size=N)
allocate(seed(N))
seed=k+37*(/ (i - 1, i = 1, n) /)
call RANDOM_SEED(PUT=seed)

! generating 7 random points
do i=1,7
  call RANDOM_NUMBER(aux)
  i_zero(i) = 15 * aux + 2 ! range = 2-16
  call RANDOM_NUMBER(aux)
  j_zero(i) = 11 * aux + 2 ! range = 2-12
enddo

! generating 7 large spots of ink
do i=1,7
  matrix_I(i_zero(i),j_zero(i)) = 3 ! central points have ink value 3
  do k=-1,1
    do l=-1,1
      if (.NOT.((k==0) .AND. (l==0))) then ! immediate neighbours...
        if ( (((i_zero(i)+k)<=17).OR.((i_zero(i)+k)>0)) .AND. (((j_zero(i)+l)<=12).OR.((j_zero(i)+l)>0)) ) then ! ... that are inside the designed area ...
            if (matrix_I(i_zero(i)+k,j_zero(i)+l) < 2) matrix_I(i_zero(i)+k,j_zero(i)+l) = 2 ! ... and that do not have ink value larger than 2 will be attributed as 2
        endif
      endif
    enddo
  enddo
enddo

! generating N little sparkles of ink
call RANDOM_NUMBER(aux)
N = int(11 * aux) + 20 ! N = 20-30

i = 0
do while (i <= N)
  call RANDOM_NUMBER(aux)
  i_zero(i) = 16 * aux + 1 ! range = 1-17
  call RANDOM_NUMBER(aux)
  j_zero(i) = 11 * aux + 1 ! range = 1-12
  if (matrix_I(i_zero(i),j_zero(i)) < 1) then ! if the selected point already has more ink than 1, then cycle the loop
    matrix_I(i_zero(i),j_zero(i)) = 1
    else
      cycle
  endif
  i = i + 1
enddo

! converting matrix of integers into matrix of characters
do i=1,17
  do j=1,12
    select case(matrix_I(i,j))
      case(0)
      matrix_C(i,j) = " "
      case(1)
      matrix_C(i,j) = "."
      case(2)
      matrix_C(i,j) = "+"
      case(3)
      matrix_C(i,j) = "@"
    end select
  enddo
enddo

! printing it on the screen + its reflection
do i=1,17
  do j=1,12
    write(*,"(A1)",advance="NO") matrix_C(i,j)
  enddo
  do j=12,2,-1
    write(*,"(A1)",advance="NO") matrix_C(i,j)
  enddo
  write(*,"(A1)") matrix_C(i,1)
enddo

end program Rorschach

```

The code is fully commented, but the basic idea is that it generates a matrix with values between 0 and 3, representing the amount of ink in that spot. There are 7 large spots of ink (a spot with a value 3 surrounded by values 2) and a lot of little "sparkles" (value 1). This matrix is then converted into a character matrix, using the following conversion:

```
0 =
1 = .
2 = +
3 = @

```

Here is a result:

```
 +++      .  .      +++
 +@++++   .  .   ++++@+
 ++++@+.        .+@++++
   .+++   ++++   +++.
          +@@+
. .   . +++@@+++ .   . .
.       +@++++@+       .
     ++++++  ++++++
     +@+        +@+
.    ++++      ++++    .
   .  +@+      +@+  .
  .  .+++.    .+++.  .
 . .   .        .   . .
    .    .    .    .
   .   ..      ..   .
 .                    .

```
> 11 votes

# Answer
## Python

Not quite the best or smoothest, but here's a python solution:

```
from PIL import Image
import random
import sys

imgsize = (int(sys.argv[1]), int(sys.argv[2]))
color = (0, 0, 0)
img = Image.new("RGB", imgsize, "white")

for j in range(0,int(sys.argv[3])):
    start = (random.randrange(0, imgsize[0]/2), random.randrange(0, imgsize[1]))
    point = start
    img.putpixel(point, color)

    blotsize = random.randrange(0, int(sys.argv[4]))
    for i in range(blotsize):
        directions = [(point[0], point[1]+1), (point[0], point[1]-1), (point[0]+1, point[1]), (point[0]-1, point[1])]
        toremove = []
        for direction in directions:
            if direction[0]>=(imgsize[0]/2) or direction[1]>=imgsize[1] or direction[0]<0 or direction[1]<0:
                toremove.append(direction)
        for d in toremove:
            directions.remove(d)
        point = random.choice(directions)
        img.putpixel(point, color)

cropped = img.crop((0, 0, imgsize[0]/2, imgsize[1]))
img = img.transpose(Image.FLIP_LEFT_RIGHT)
img.paste(cropped, (0, 0, imgsize[0]/2, imgsize[1]))

img.save("blot.png")

```

It just makes a "wandering path" for a blot, and makes several of those.

An example usage:

```
py inkblot.py width height blots blotsize
py inkblot.py 512 512 20 10000

```

And some example images:
> 12 votes

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


title: Calculate a tip

text:
# Question
Title: Calculate a tip
You and a friend walk into a bar. The bartender treats you well, so you decide to tip him. So you pull out your trusty pocket computer and write a quick program to calculate a tip for you since it has no built in calculator. But wait! Your operator keys are broken! Your task is to calculate a 20% tip for any given input amount. The test inputs will be in the form of xx.xx e.g. 20.96. Here are the rules:

* No use of the following in mathematical form operators: `+ - * / %` (Thanks Wally West)
* No use of built in percent functions or APIs
* No accessing the network
* No use of `eval` or similar
* No Windows Calculator (yes people have answered with it before)
* No built in tip functions (Not that any language would have one)

Output should be rounded up to two decimal places.

Score is based on length in bytes.

**-20%** if your program can accept any tip amount. Input for amount will be given in the form of xx e.g. 35 not 0.35

# Answer
> 17 votes
## Javascript 81

**EDIT** : The result is now a real rounding, not truncated.

Do not use **ANY** math here, just string manipulation and bitwise operators.
All the `+` char are string concatenation, or *string to float* conversion.
Works for any xx.xx input and outputs in (x)x.xx format

```
s='00'+(prompt().replace('.','')<<1);(+s.replace(/(.*)(...)/,'$1.$2')).toFixed(2)

```

Trick explained : 20% is divided by 10 and multiplied by 2.

* Make a division by 10 by *moving* the dot to the left (string manipulation)
* Multiply each part by 2 by *moving* bits to the left (bitwise operation)

# Answer
> 6 votes
# J (9 characters)

A short answer in J:

```
^.(^.2)^~ 32

```

# Answer
> 4 votes
# Pure bash, 50 43 chars

Pretty sure this'll be beat, but here's a start:

```
a=$[10#${1/.}<<1]
echo ${a%???}.${a: -3:2}

```

As per the comments:

* `/` is not a division operator here, it is part of a pattern substitution parameter expansion
* `%` is not a modulo operator here, it is part of a parameter expansion
* `-` is not a subtraction operator here, it is a negation, which was allowed as per the comments

Output:

```
$ ./20pct.sh 0.96
.19
$ ./20pct.sh 20.96
4.19
$ ./20pct.sh 1020.96
204.19
$

```

# Answer
> 4 votes
# APL (9 characters, new code with 7 characters, fixed with 13 characters)

Compute 20% of the given amount.

```
{⍟⍵*⍨*.2} 32

```

In APL `*` is the exponential operator.

Try it online.

But why use a function for that? See this new version:

```
⍟(*.2)* 32

```

Try it online.

Please, before downvoting, the `*` is not forbidden as a KEY and it doesn't mean multiplication here.

OK, here is the version rounding to 2 decimals (Dyalog APL):

```
⎕PP←2⋄⍟(*.2)* 32.01

```

# Answer
> 4 votes
## Python 98\*0.8=78.4

```
d=`len('X'*int("{}{:>02}".format(*(raw_input()+".0").split('.')))*2)`;print'%s.%s'%(d[:-3],d[-3:])

```

## Python 74 (without bonus)

```
d=len('X'*int(raw_input().replace('.',''))*2);print'%s.%s'%(d[:-3],d[-3:])

```

**Note**

* `+` is used for string concatenation
* `*` used to create copies of string

**Ungolfed**

```
def tip():
    amount = raw_input()
    #Add an extra decimal point so that we can accept integer
    #amount
    amount += ".0"
    #Split the integer and decimal part
    whole, frac = amount.split('.')
    #Multiply amount by 100 :-)
    amount = "{}{:>02}".format(whole, frac)
    #Create amount copies of a character
    st = 'X'*amount
    #Double it
    st *= 2
    #Calculate the Length
    d = len(st)
    #Display the result as 3 decimal fraction
    print'%s.%s'%(d[:-3],d[-3:])

```

**Note**

In spirit of the question, I believe the following solution though follows all rules of the question is an abuse

## Python 41

```
print __import__("operator")(input(),0.2)

```

**Finally**

If you insist that the mathematical symbols are forbidden, her is a 90 character solution

## Python 90 (without any mathematical symbol)

```
print' '.join(str(int(raw_input().replace(".",""))<<1)).replace(' ','.',1).replace(' ','')

```

# Answer
> 4 votes
# **R, 30 27 36 34**

*Updated to round to 2 decimal places*

*Saved 2 characters thanks to plannapus*

Creates a vector from 0 to x and takes the 2nd element.

```
a=function(x)round(seq(0,x,l=6)[2],2)

```

Example:

```
> a(20.36)
[1] 4.07

```

## Further explanation:

```
seq(0,x,len=6)

```

creates a vector of length 6 from 0 to the input value x, with the values in between equally spaced.

```
> seq(0,5,len=6)
[1] 0 1 2 3 4 5

```

The first value is then 0%, the second 20%, third 40%, etc.

# Answer
> 3 votes
# dc + sed + pipes (44 characters)

My third answer (one APL, one J, and now one with the old and venerable dc).

```
dc -e 5o?p|sed -e 's/\(.\)$/.\1/'|dc -e 5i?p

```

It will ask for an INTEGER input and compute 20% with a tricky way. Input is converted to base 5 (easy to do with many other tools but wait...); a dot is appended before the last digit with sed (unfortunately, dc can't handle strings very well), and THEN, dc converts back from base 5 on a float number (not all tools can do that).

# Answer
> 2 votes
# Mathematica, 19

```
Log[(E^.2)^Input[]]

```

No use of the mathematical operators of `+`, `-`, `*`, `/`, or `%`. Uses properties of logarithms to calculate the answer; when you simplify the expression, you get `.2*Input[]`

With the bonus (**30 * 0.8 = 24**):

```
Log[((E^.01)^Input[])^Input[]]

```

Input the percentage first, then the amount.

When you simplify the expression, you get `Input[]*Input[]*.01`.

Thanks to ברוכאל for help with shortening the code.

# Answer
> 2 votes
## Python, 88

This is no where near short, but this demonstrate how a normal mental division by five should be done. This assumes that the input must be of the form xx.xx

```
import math
a,b=raw_input().split('.')
print'%.2f'%math.ldexp(float(a[0]+'.'+a[1]+b),1)

```

Or for input of any length, an addition of 3 characters is required.

```
import math
a,b=raw_input().split('.')
print'%.2f'%math.ldexp(float(a[:-1]+'.'+a[-1]+b),1)

```

Explanation: We take the input as string, then move the decimal point one place forward (dividing by 10). We then cast it to a float, and use the `ldexp` function to multiply it by 2.

Note that in this answer, the `+` are string concatenation operators, and the `%` are used to format `print`.

If you insist on not using any of these characters, here is a 159 character solution:

```
import math
a,b=raw_input().split('.')
l=[a[0]]
l.append('.')
l.append(a[1])
l.append(b)
c=str(math.ldexp(float(''.join(l)),1))
print ''.join([c[0:2],c[2:4]])

```

# Answer
> 2 votes
# dc + sed -- 45 * 0.8 = 36

(Inspired by the answer by ברוכאל)

* Handles any tip amount (integer or float)

Example runs (input is accepted via STDIN):

```
$ dc -e 5o?.0+p|sed 's/\(.\)\./.\1/'|dc -e 5i?p
42
8.400
$ dc -e 5o?.0+p|sed 's/\(.\)\./.\1/'|dc -e 5i?p
20.96
4.1920

```

# Answer
> 1 votes
# TI-89 Basic - 39 * 0.8 = 31.2

```
Input y:Input x:Disp ln(((e^y)^.01)^x))

```

Works by inputting the two numbers, then using the logarithm properties to compute `x * y / 100`.

If I can assume input from placement in global variables `x` and `y`, then this is much shorter, for a score of **17 * 0.8 = 13.6**:

```
ln(((e^y)^.01)^x)

```

Without bonus (**12**):

```
ln((e^.2)^x)

```

But if it needs to be wrapped in a function, then this works (**38** chars, for **30.4**):

```
:f(x,y):Func:ln(((e^y)^.01)^x):EndFunc

```

# Answer
> 1 votes
# JavaScript (ES6) (Regex) 142

Regex is great and it can do many things. It can even do maths!

```
a=('x'.repeat(prompt().replace('.', ''))+'xxxx').match(/^((x*)\2{99}(x{0,99}))\1{4}x{0,4}$/);c=a[3].length;alert(a[2].length+'.'+(c<10?'0'+c:c))

```

---

Readable version:

```
function tip(m) {
    var s = 'x'.repeat(m.replace('.', '')) + 'xxxx';
    var a = s.match(/^((x*)\2{99}(x{0,99}))\1{4}x{0,4}$/);
    var c = a[3].length;
    if (c < 10) c = '0' + c;
    return a[2].length + '.' + c;
}

```

The `tip()` function expects String argument, rather than Number.

All instances of `*`, `/`, `+` are not related to math operations.

* `+` is string concatenation in all instances it is used.
* `*` is part of RegExp syntax
* `/` is the delimiter of RegExp literal

The input **must** use `.` as decimal point, and there **must** be 2 digits after decimal point.

# Stack Snippet

```
<button onclick = "a=('x'.repeat(prompt().replace('.', ''))+'xxxx').match(/^((x*)\2{99}(x{0,99}))\1{4}x{0,4}$/);c=a[3].length;alert(a[2].length+'.'+(c<10?'0'+c:c))">Try it out</button>
```

# Answer
> 1 votes
## Perl, 50 60 bytes

```
$_=<>;s|\.||;$_<<=1;$_="00$_";m|\d{3}$|;printf'%.2f',"$`.$&"

```

The input is expected at STDIN. It must contain the decimal separator with two decimal digits. The output is written to STDOUT.

**Update:** The step `$_<<=1` removes leading zeroes. Therefore `m|\d{3}$|` would not match for bills \< 1. Therefore ten bytes `$_="00$` were added, Now even `0.00` works.

Examples:

* Input: `20.96`, output: `4.19`
* Input: `12.34`, output: `2.47`

**Ungolfed version:**

```
$_=<>;
s|\.||; # multiply by 100
$_ <<= 1; # multiply by 2
$_="00$_";
m|\d{3}$|; # divide by 1000
printf '%.2f'," $`.$&"

```

First the number is read from STDIN. Then the decimal dot is removed, that is multiplied with 100. Then the amount is doubled by a shifting operator. Then the decimal dot is reinserted and the result is printed and rounded to two decimal digits.

**50 bytes, if bill ≥ 1:**

If `x.xx` is greater or equal than `1.00`, then 10 bytes can be removed:

```
$_=<>;s|\.||;$_<<=1;m|\d{3}$|;printf'%.2f',"$`.$&"

```

# Answer
> 1 votes
# Python, 81 80 89 characters

```
a,b=map(str,raw_input().split('.'));c=str(int(a+b)<<1).zfill(4);print c[:-3]+'.'+c[-3:-1]

```

Explanation

```
x = raw_input()       # say 20.96
a , b = x.split('.')  # a = 20 , b = 96
c = a + b             # c = '2096'      # string concatenation , multiplying by 100
d = int(c)<<1         # multiply by 2 by bitshift left , c = 4096
e = str(d).zfill(4)   # zfill pads 0's making the string
                      # atleast 4 chars which is required
                      # for decimal notation next

#     divide by 1000 (4) + . (4.) + fraction rounded to 2 decimals (4.09)
print        e[:-3]      +   '.'  +              e[-3:-1]

```

Technically, this is cheating as it truncates to two decimals rather than rounding it but I can argue that it rounds down(Better for you, less tip).

# Answer
> 1 votes
# PHP 107 \*.8 = 85.6

can't really run for code-golf with PHP, but at least I can operate on strings. accepts both numbers as command-line arguments.

```
<? @$r=strrev;unset($argv[0]);echo$r(substr_replace($r(str_replace('.','',array_product($argv)))),'.',2,0);

```

had to reverse it twice since I can't use -2 :(

# Answer
> 1 votes
# JavaScript 251 (forced restriction: no +, -, \*, ? or % in any manner)

While I know this won't win, I figured I'd try to get brownie points through taking a very strict approach and not even think about using the restricted operators in any shape or form... as a result, I came up with this beauty...

```
A=(x,y)=>{for(;x;)b=x^y,x=(a=x&y)<<1,y=b;return y};D=(x,y,i=x,j=0)=>{for(;i>=y;)i=A(i,A(~y,1)),j=A(j,1);return j};alert(parseFloat((x="00".concat(String(D(prompt().replace(".",""),5)))).substr(0,A(x.length,y=A(~2,1))).concat(".").concat(x.substr(y))))

```

I used bitwise operations to create the Add function `A`, and then started chaining up from there:

The integer division function `D` used a series of Negated Addition (subtraction in the form of `A(x,A(~y,1)` over a loop; the rest is string manipulation and concatenation so as to avoid using `+` concatenation operators...

The number must be provided in decimal form with two decimal places for this to work...

# Answer
> 0 votes
## Haskell 32 Chars -20% = 25.6 Chars

```
t y x=log $(^x)$(**0.01)$ exp y

```

Abuses the fact that exponents become multiplication in logarithms.

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


# Question
Title: Input text from one file, output it to another
The challenge:

> Input text from one file and output it to another. Solution should be a complete, working function.

Note: This is a question. Please do not take the question and/or answers seriously. More information here.

# Answer
> 38 votes
# C

The whole point of having multiple programming languages, is that you need to use the right tool for the job.
In this case, we want to copy bytes from one file to another.
While we could use something fancy like bash or ruby, or fall to the power of ASM, we need something quick, good with bits and fast.
The obvious choice is C.
The SIMPLEST way of doing it would be like so:

```
#include <stdio.h>
#define THEORY FILE
#define AND *
#define PRACTICE myfile1
#define SOLUTIONS myfile2
#define ARE fopen
#define IMPORTANT "r"
#define BAD "w"
#define LOL fclose
#define PLEASE fgetc
#define HELP fputc
#define ME return
#define NEVER for
#define SURRENDER !=
#define VERY filename1
#define NOT filename2
#define _ 1

int copyFile(char* filename1, char* filename2)
{
  THEORY AND PRACTICE = ARE (VERY, IMPORTANT);
  THEORY AND SOLUTIONS = ARE (NOT, BAD);
  NEVER (;_;)
  {
    HELP(PLEASE(PRACTICE),SOLUTIONS);
  }
  ME _SURRENDER_;
}

```

This is evil because it will read garbage on things like cygwin, is completely chinese for a beginner, will scare him when he realizes it's a call for help and, obviously, because C.

# Answer
> 26 votes
## sh

I like the simplicity of this one.

```
echo File1.txt > File2.txt

```

Really only works properly if `File1.txt` contains "File1.text"...

# Answer
> 8 votes
# AutoHotKey

```
WinActivate, file1.txt
SendInput ^a^c
WinActivate, file2.txt
SendInput ^a^v^s

```

You must first open the files in notepad or some other text editor that makes the window names start with the file names. Then it copies the contents of file1 to the clipboard (literally, using `ctrl`+`c`), and pastes it into file2, overwriting anything currently in it, and saves.

Solves the problem, but in a very inconvenient and pretty useless fashion. It would probably by easier to just copy and paste manually.

# Answer
> 6 votes
As everyone knows, perl is very good for manipulating files. This code will copy the contents of one file to another, and will do so with extra redundancy for good measure.

```
#Good perl programs always start thusly
use strict;
use warnings;

my $input_file  = 'File1.txt';
my $output_file = 'File2.txt';
open(my $in, '<', $input_file) or die "Couldn't open $input_file $!";

my $full_line = "";
while (my $line = <$in>) {
    #Get each letter one at a time for safety,
    foreach my $letter (split //, $line) {
        #You could and should add validity checks here
        $full_line .= $letter;

        #Get rid of output file if it exists!  You are replacing it with
        # new content so it's just wasting space.
        unlink $output_file if (-e $output_file);

        #Write data to new file
        open(my $out, '>', $output_file) or die "Couldn't open $output_file $!";
        print {$out} $full_line;
        close($out);
    }
}

```

To be safe, test this out on a small file at first. Once you are convinced of its correctness you can put it into production for use on very large files without worry.

# Answer
> 6 votes
**C#**

In order to achieve this, you must make sure to do several things:

1. Read string from file
2. Download Microsoft File IO and String Extension for Visual Studio
3. Remove viruses from string ("sanitize")
4. Write file to path
5. Delete and reload cache

Here's the code:

```
static void CopyTextFile(string path1, string path2)
    {
        try
        {
            FileStream fs = new FileStream(path1, FileMode.OpenOrCreate); //open the FTP connection to file
            byte[] file = new byte[fs.Length];
            fs.Read(file, 0, file.Length);
            string makeFileSafe = Encoding.UTF32.GetString(file);

            using (var cli = new WebClient())
            {
                cli.DownloadData(new Uri("Microsoft .NET File IO and String Extension Package")); //get MS package
            }

            fs.Dispose();

            File.Create(path2);
            StreamReader read = new StreamReader(path2);
            read.Dispose(); //create and read file for good luck

            var sb = new StringBuilder();
            foreach (char c in path1.ToCharArray())
            {
                sb.Append(c);
            }

            string virusFreeString = sb.ToString(); //remove viruses from string

            File.WriteAllText(path2, virusFreeString);
            File.Delete(path1);
            File.WriteAllText(path1, virusFreeString); //refresh cache
        }
        catch
        {
            //Don't worry, exceptions can be safely ignored
        }
    }

```

# Answer
> 6 votes
In four simple steps:

1. Print the file. You can use the `lpr` command for this.
2. Mail the printouts to a scanning service. (You will need postage for this).
3. The scanning service will scan the printouts and do OCR for you.
4. Download to the appropriate file location.

# Answer
> 4 votes
# Java

A lot of people find it useful to attempt to use regular expressions or to evaluate strings in order to copy them from one file to another, however that method of programming is sloppy. First we use Java because the OOP allows more transparency in our code, and secondly we use an interactive interface to receive the data from the first file and write it to the second.

```
import java.util.*;
import java.io.*;

public class WritingFiles{

 public static void main(String []args){
    File tJIAgeOhbWbVYdo = new File("File1.txt");
    Scanner jLLPsdluuuXYKWO = new Scanner(tJIAgeOhbWbVYdo);
    while(jLLPsdluuuXYKWO.hasNext())
    {
        MyCSHomework.fzPouRoBCHjsMrR();
        jLLPsdluuuXYKWO.next();
    }
 }
}

class MyCSHomework{
    Scanner jsvLfexmmYeqdUB = new Scanner(System.in);
    Writer kJPlXlLZvJdjAOs = new BufferedWriter(new OutputStreamWriter( new  FileOutputStream("File2.txt"), "utf-8"));
    String quhJAyWHGEFQLGW = "plea";
   String LHpkhqOtkEAxrlN = "f the file";
   String SLGXUfzgLtaJcZe = "e nex";
   String HKSaPJlOlUCKLun = "se";
   String VWUNvlwAWvghVpR = " ";
   String cBFJgwxycJiIrby = "input th";
   String ukRIWQrTPfqAbYd = "t word o";
   String  CMGlDwZOdgWZNTN =   quhJAyWHGEFQLGW+HKSaPJlOlUCKLun+VWUNvlwAWvghVpR+cBFJgwxycJiIrby+SLGXUfzgLtaJcZe+ukRIWQrTPfqAbYd+LHpkhqOtkEAxrlN;
    public static void fzPouRoBCHjsMrR(){
        System.out.println(CMGlDwZOdgWZNTN);
        kJPlXlLZvJdjAOs.write(jsvLfexmmYeqdUB.next());
    }

}

```

---

In theory (I haven't tested it) this makes the user manually input the content of the first file (word by word) and then writes it to the second file. This response is a play on the ambiguity of the question as to what it means by "input text from one file," and the crazy variable names (generated randomly) were just for some extra fun.

# Answer
> 3 votes
## sh

Like @Shingetsu pointed out, one has to use the right tool for the right job. Copying the content from one file to another is an old problem, and the best tool for such file-management tasks is using the shell.

One shell command that every programmer has to familiarise themself with is the common `tac` command, used to **tac**k the content of files together, one after another. As a special case of this, when only one file is passed in it is simply spit out as-is again. We then simply redirect the output to the appropriate file:

```
tac inputfile.txt >outputfile.txt

```

Simple and to-the-point, no tricks!

# Answer
> 2 votes
# Perl

Antivirus included.

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

print "Copy the text of the file here: (warning: I can't copy files with newlines):\n";
my $content = <STDIN>;

print "\n\nPlease wait, removing viruses...";
my @array = split(//,"$content");
my @tarray;

foreach my $item (@array)
{
    if ($item ne "V" && $item ne "I" && $item ne "R" && $item ne "U" && $item ne "S")
    {
        push(@tarray, $item);
    }

}

print "\n\nNow copy this into the target file:\n";

foreach my $item (@tarray){ print "$item"};

```

# Answer
> 2 votes
# Windows Batch

(because you gotta have this supposedly "dead" language ;-)

```
@echo off
setlocal enabledelayedexpansion
for %%I in ('type %1') do set this=!this!%%I
echo !this!>%2 2>nul

```

You simply call this as `copy.bat file1.txt file2.txt` (or whatever files you want)

If only it would keep line breaks...

# Answer
> 2 votes
# Linq

Efficiency is not important, correctness is. Writing in a functional style results in more clear and less error-prone code. If performance does turn out to be a problem, the last ToArray() line can be omitted. It's better to be lazy anyway.

```
public void CopyFile(string input, string output)
{
    Enumerable
        .Range(0, File.ReadAllBytes(input).Length)
        .Select(i => new { i = i, b = File.ReadAllBytes(input)[i] })
        .Select(ib => {
            using (var f = File.Open(output, ib.i == 0 ? FileMode.Create : FileMode.Append))
                f.Write(new byte[] { ib.b }, 0, 1);
            return ib; })
        .ToArray();
}

```

# Answer
> 2 votes
**Smalltalk**

There is a library yet ported to several Smalltalk dialects (Visualworks, Gemstone Squeak/Pharo, ...) named Xtreams that makes this task more than easy.

FileStream would be as simple as `'foo' asFilename reading` and `'bar' asFilename writing` for example in Visualworks, but are dialect specific.
For this reason I demonstrate the algorithm with dialect neutral internal Streams instead.
A good idea could be to process each byte code in increasing order:

```
| input |
input := 'Hello world' asByteArray reading.
^((ByteArray new writing)
    write: ((0 to: 255) inject: ByteArray new reading into: [:outputSoFar :code |
        | nextOutput |
        nextOutput := ByteArray new writing.
        ((input += 0; selecting: [:c | c <= code]) ending: code inclusive: true) slicing do: [:subStream |
            | positionable |
            positionable := subStream positioning.
            nextOutput write: (outputSoFar limiting: (positionable ending: code) rest size).
            nextOutput write: (positionable += 0; selecting: [:c | c = code])].
        nextOutput conclusion reading]);
    conclusion) asString

```

Of course, it is also possible to process in random order, but i'm afraid that it makes the code a bit too compact:

```
| input output |
input := 'Hello world' asByteArray reading.
output := ByteArray new writing.
(0 to: 255) asArray shuffled do: [:code |
        output += 0.
        (input += 0; ending: code inclusive: true) slicing do: [:subStream |
            | positionable |
            positionable := subStream positioning.
            output ++ (positionable += 0; rejecting: [:c | c = code]) rest size.
            output write: (positionable += 0; selecting: [:c | c = code])]].
^output conclusion asString

```

**EDIT**

Ah stupid me, I didn't saw the log2 solution:

```
| input output |
input := 'Hello world' asByteArray reading.
(output := ByteArray new writing) write: (input collecting: [:e | 0]).
output := (0 to: 7) asArray shuffled inject: output into: [:outputSoFar :bit |
        (ByteArray new writing)
            write:
                (((input += 0; collecting: [:e | e >> bit bitAnd: 1]) interleaving: outputSoFar conclusion reading)
                    transforming: [ :in :out | out put: in get << bit + in get]);
            yourself].
^output conclusion asString

```

# Answer
> 1 votes
# C++

This is somewhat based on Shingetsu's answer, but I couldn't resist. It is fully functioning, but no student would submit it to their teacher (I hope). If they are willing to analyze the code, they will be able to solve their problem:

```
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#define SOLVE ifs
#define IT >>
#define YOURSELF ofs

ifstream& operator IT(ifstream& ifs, ofstream& ofs) {
  string s;
  SOLVE IT s;
  YOURSELF << s;
  return ifs;
}

void output(ofstream& ofs, ifstream& ifs) {
  while (ifs) {
    SOLVE IT YOURSELF;
    ofs << ' ';
  }
}

int main() try {

  ofstream ofs("out.txt");
  ifstream ifs("in.txt");

  output(ofs, ifs);

  return 0;
}
catch (exception& e) {
  cerr << "Error: " << e.what() << endl;
  return 1;
}
catch (...) {
  cerr << "Unknown error.\n";
  return 2;
}

```

# Answer
> 1 votes
## **BASH**

*on terminal #1 with the IP, 192.168.1.2*

```
nc -l 8080 | gpg -d > mydocument.docx

```

*on terminal #2 with the IP, 192.168.1.3*

```
gpg -c mydocument.docx | nc 192.168.1.2 8080

```

This will encrypt and send `mydocument.docx`, using `nc` and `gpg`, over to terminal #1 You will have to type the password on terminal #2, then on terminal #1

# Answer
> 1 votes
## Python

Inputs text from file1.txt and outputs it to file2.txt

It's complete and "working". No one said anything about writing the input as it is. All input characters appear in the output. "getchar" is the trolling part.

```
from random import choice as getchar

f1 = open("file1.txt")
s1 = []
for line in f1:
    for char in line:
        s1.append(str(char))
s2 = ''
while len(s1) > 0:
    x = getchar(s1)
    s2 += x
    s1.remove(x)
f2 = open("file2.txt" , 'w')
f2.write(s2)

```

# Answer
> 1 votes
# Mathematica, 44 characters

Implementation

```
f = (BinaryWrite[#2, BinaryReadList@#]; Close@#2) &

```

Execution

```
f["one file", "another"]

```

Check

```
check = Import[StringJoin["!diff \"", #, "\" \"", #2, "\" 2>&1"], "Text"] &;
check["one file", "another"]

```

>

# Answer
> 1 votes
**DELPHI / PASCAL** ( copy from f1.txt to f2.txt )

```
program t;

{$APPTYPE CONSOLE}

uses
  classes;

var a : TStringlist;
begin
   a:=TStringlist.Create;
   a.LoadFromFile('e:\f1.txt');
   a.SaveToFile('e:\f2.txt');
   a.Free;
end.

```

# Answer
> 1 votes
# MASM

I'm certainly not an assembly expert, but below is my little snippet:

```
include \masm32\include\masm32rt.inc

.code

start:
call main
inkey
exit

main proc
LOCAL hFile :DWORD
LOCAL bwrt  :DWORD
LOCAL cloc  :DWORD
LOCAL flen  :DWORD
LOCAL hMem  :DWORD

.if rv(exist,"out.txt") != 0
  test fdelete("out.txt"), eax
.endif

mov hFile, fopen("source.txt")
mov flen, fsize(hFile)
mov hMem, alloc(flen)
mov bwrt, fread(hFile,hMem,flen)
fclose hFile

invoke StripLF,hMem

mov hFile, fcreate("out.txt")
mov bwrt, fwrite(hFile,hMem,flen)
fclose hFile

free hMem

ret

main endp
end start

```

# Answer
> 1 votes
**PHP**

```
function copyFile($input, $output)
{
    return file_put_contents($output, file_get_contents($input));
}

```

# Answer
> 1 votes
# C++

Did you notice the "complete, working function" bit? Anyway, here is my answer:

```
#include <stdlib.h>
int main(void)
{
  system("echo < input > dest");
}

```

# Answer
> 1 votes
## Lua

```
io.read()

```

Run with an input file containing `text from one file and output it to another. Solution should be a complete, working function.`.

# Answer
> 1 votes
# #!/bin/sh

```
contents=`< $1` ; echo "$contents" > $2

```

Looks reasonable, but rather inefficient if the file is large.

Works fine on ASCII files except when the input file contains `-n`, `-e` or `-E`. (Because these are interpreted as arguments by `echo`.)

Does not produce the correct output for all (most) binary files.

(Using `printf "%s" "$contents" > output` under `/bin/bash` works a little better, but that still drops NULL bytes.)

Oh and of course it doesn't work for filenames\_containing\_spaces. But such files are illegal under UNIX%20policy anyway.

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


title: Fake error message

text:
# Question
Title: Fake error message
Write a program that prints out the syntax error message of the compiler or interpreter. The error message should be misleading so that code maintainers will take days to find out that the error was faked, that means, you should obfuscate (and hide your intention). Also, the error must be as exact as possible, and should reference to the code correctly.

For complied languages, assume your code maintainer will do `compile program.p && ./program` on the command line to compile AND run the program, that means, he cannot distinguish if the output comes from the compiler or the program itself. Also, assume your code maintainer will turn on syntax error messages.

For reference, here is an example I made: https://gist.github.com/359604

The `DATA` section encodes the string of error message, and the hash `%abcdef` is the decode table. The error printed references to the backslashes, which makes a code maintainer will try to count the backslashes.

Entries will be graded by:

* Code has an deceptively obvious intention `/6`
* Code reproduces error correctly `/16` (your point starts with 16, and divide by the corresponding factors for each inaccuracies)
    + Correct capitalization: 4
    + Correct line number and column number: 4
    + Correct wording: 2 for each incorrect words
* The line number referenced misleads the code maintainer `/3`

For example,

```
./pythontest1.py: line 7: syntax error near token `('
./pythontest1.py: line 7: `   x=input("Enter a number:") #Number input'

```

gets 8 (16 / 2) on correctness for missing "unexpected" before "token", a normal Python interpreter displays

```
./pythontest1.py: line 7: syntax error near unexpected token `('
./pythontest1.py: line 7: `   x=input("Enter a number:") #Number input'

```

If your "code reproduces error correctly" point is under 1, your entry disqualifies.

In case of a tie, I will put up additional grading factors.

# Answer
## Python

```
import sys,traceback
try:
  f=open(sys.argv[0])
  print eval(f.readline())
except Exception, e:
  traceback.print_exc(0)

```

This is a program that should take a filename on the command line, evaluate the first line in it, and print the result. It has 2 bugs. The major bug is that it should use `sys.argv[1]`, not `sys.argv[0]`, so it ends up evaluating the program itself, not the contents of the file named by the first argument. The second bug is that the argument to `print_exc` makes it print only the deepest frame on the stack, hiding the fact that the error took place inside the `eval`. As a result, you get an error like this:

```
$ python fake_error.py twelve
Traceback (most recent call last):
  File "<string>", line 1
     import sys,traceback
          ^
 SyntaxError: invalid syntax

```

This looks very much like the first line of the program has a syntax error. It's not quite right as the file is `<string>`, not `fake_error.py`, but otherwise it is indistinguishable from the case where, for example, you spell `import` wrong.

Both errors are somewhat "underhanded" in that they could be accidental.
> 36 votes

# Answer
Reminds me a practical joke.

```
$ ls -l
$ cat readme.txt
cat: readme.txt: No such file or directory
$ echo 'cat: readme.txt: No such file or directory' >readme.txt
$ ls -l
total 8
-rw-r--r--  1 florian  staff  43 Mar 16 09:52 readme.txt
$ cat readme.txt
cat: readme.txt: No such file or directory
$

```
> 10 votes

# Answer
## BrainF\***

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

```

I can't find the particular compiler I used before, but I assure you that that is the exact error message.
> 9 votes

# Answer
**Java**

```
throw new Error();

```

I didn't know if you meant actually throwing an unhandled exception (as in that example), or simulating an error message. If that is the case, this should work:

**C**

```
printf("FATAL ERROR #0xBAD\nProgram execution stopped\n\nIn line 123, character 321, of file 'buggy.c'");

```

(this assumes that `stdio.h` is #included)
> 1 votes

# Answer
## Game Maker Language

```
show_error("Error: Undefined variable a##Line 1, character 4, of event Create in obj_controller",0)

```
> 0 votes

# Answer
# **ACTIONSCRIPT 3**

```
trace("TypeError: Error #1009: Cannot access a property or method of a null object reference.");

```
> 0 votes

---
Tags: code-challenge, error-message
---


# Question
Title: Minimal keystrokes needed to type a given text
We all know that programmers tend to be lazy. In order to maximize your free time, you decide to write a program that outputs a minimal number of keystrokes for text fed into it.

**Input**: Text that has to be converted into keystrokes. You may decide on how to input the text (STDIN / reading from a file provided in the arguments)

**Output**: The necessary actions in the following format:

* They must be numbered
* `H`it: Pressing a key and immediately releasing it
* `P`ress: Pressing a key and not releasing it (this will never be optimal when the key is `R`eleased as the next keystroke)
* `R`elease: Releasing a `P`ressed key

**Example**:

Input:

```
Hello!

```

Output:

A naive solution would be:

```
1 P Shift
2 H h
3 R Shift
4 H e
5 H l
6 H l
7 H o
8 P Shift
9 H 1
10 R Shift

```

This would be more efficient:

```
1 P Shift
2 H h
3 H 1
4 R Shift
5 H Left
6 H e
7 H l
8 H l
9 H o

```

**Environment:**

* The editor uses a monospaced font
* Text is soft wrapped at 80 characters
* Arrow up and Arrow down preserve the column, even if there are shorter lines in between
* The clipboard is assumed to be empty
* Num lock is assumed to be enabled
* Caps lock is assumed to be disabled
* Caps lock only works for the letters (i.e. no Shift Lock)

*Hotkeys / Shortcuts*:

* `Home`: Jump to the beginning of the current line
* `End`: Jump to the end of the current line
* `Ctrl`+`A`: Mark everything
* `Ctrl`+`C`: Copy
* `Ctrl`+`X`: Cut
* `Ctrl`+`V`: Paste
* `Shift`+Cursor moving: Marking
* `Ctrl`+`F`: Opens a search dialog.
    + Stupid text matching, no Regular Expressions
    + Case sensitive
    + Searches wrap around
    + Single line text input for the search
    + The input is prefilled with the current selection, unless there is a newline in between, the complete input is selected
    + Copying / Pasting works as usual
    + Pressing `Enter` performs the search, selecting the first match after the current cursor position
* `F3`: Repeat last search
* `Ctrl`+`H`: Opens a replace dialog
    + Stupid text matching, no Regular Expressions
    + Case sensitive
    + Replace All, with wrap around
    + Single line text inputs
    + The search input is prefilled with the current selection, unless there is a newline in between, the complete input is selected
    + The replace input is empty
    + Copying / Pasting works as usual
    + `Tab` jumps to the replace input
    + Pressing `Enter` performs the replace all. The cursor is placed after the last replacement

**Rules**:

* Solutions must be a complete program that compiles / parses and executes without any further modification
* The keyboard displayed above is the keyboard to use
    + It is not required to handle characters that cannot be typed with it
* Every key must be released at the end
* The cursor does not need to be at the end of file at the end

**Scoring**:

Your score is sum the amount of actions needed to type the following texts. The winner is the solution with the lowest score. Using my naive solution I get `1371 + 833 + 2006 = 4210`. Beat it! I will pick a winner in two weeks.

1 My naive solution

```
number = 1

H = (char) -> console.log "#{number++} H #{char}"
P = (char) -> console.log "#{number++} P #{char}"
R = (char) -> console.log "#{number++} R #{char}"

strokes = (text) ->
    shiftActive = no

    for char in text
        if /^[a-z]$/.test char
            if shiftActive
                R "Shift"
                shiftActive = no

            H char
        else if /^[A-Z]$/.test char
            unless shiftActive
                P "Shift"
                shiftActive = yes

            H char.toLowerCase()
        else
            table =
                '~': '`'
                '!': 1
                '@': 2
                '#': 3
                '$': 4
                '%': 5
                '^': 6
                '&': 7
                '*': 8
                '(': 9
                ')': 0
                '_': '-'
                '+': '='
                '|': '\\'
                '<': ','
                '>': '.'
                '?': '/'
                ':': ';'
                '"': "'"
                '{': '['
                '}': ']'

            if table[char]?
                unless shiftActive
                    P "Shift"
                    shiftActive = yes

                H table[char]
            else
                H switch char
                    when " " then "Space"
                    when "\n" then "Enter"
                    when "\t" then "Tab"
                    else
                        if shiftActive
                            R "Shift"
                            shiftActive = no

                        char
    R "Shift" if shiftActive

input = ""

process.stdin.on 'data', (chunk) -> input += chunk
process.stdin.on 'end', -> strokes input

```

2 Easy repetition

```
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG
HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII
JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ
KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK
LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM

```

3 More complex repetition

```
We're no strangers to love
You know the rules and so do I
A full commitment's what I'm thinking of
You wouldn't get this from any other guy
I just wanna tell you how I'm feeling
Gotta make you understand

Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you

We've known each other for so long
Your heart's been aching but
You're too shy to say it
Inside we both know what's been going on
We know the game and we're gonna play it
And if you ask me how I'm feeling
Don't tell me you're too blind to see

Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you

Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you

(Ooh, give you up)
(Ooh, give you up)
(Ooh)
Never gonna give, never gonna give
(Give you up)
(Ooh)
Never gonna give, never gonna give
(Give you up)

We've know each other for so long
Your heart's been aching but
You're too shy to say it
Inside we both know what's been going on
We know the game and we're gonna play it

I just wanna tell you how I'm feeling
Gotta make you understand

Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you

Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you

Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you

```

---

You can use the replay program written by me to test your solutions (Note: It does not support Searching / Replacing yet, everything else should work).

# Answer
# Haskell 1309 + 457 + 1618=3384

Finally, an answer (score greatly improved once I realised there's tabs in your first test-had to edit question to see those). Compile with `ghc`, supply input on stdin. Example:

```
$ ghc keyboard.hs && echo hello|./keyboard
1 H h
2 H e
3 H l
4 H l
5 H o
6 H Enter

```

I tried the obvious stuff like Dijkstra but it was way too slow, even after reducing the branching to the only useful moves, which are: output the next key, or copy from the start of the line (Shift+Home, Ctrl+C, End), or paste.

So, this approach uses a fixed-length clipboard, copies when a line prefix is about to become 'useful', and keeps using that prefix as long as it would be pasteable on more lines than the prefixes of lines it reaches next. When it can't use the clipboard, it falls back on the naive solution, so it's guaranteed to beat it once the length chosen is more than the cost of a copy.

The minimum score is achieved when the prefix length is chosen to fit "Never gonna ". There are ways to improve on this, but I've had enough of reading Rick Astley.

```
import Data.List (isPrefixOf,isInfixOf)
import Control.Monad (foldM)
plen=12
softlines text=sl 0 [] text
  where
    sl n [] [] = []
    sl n acc [] = [(n,reverse acc)]
    sl n acc (x:xs)
      |x=='\n'||length acc==79=(n,reverse (x:acc)):(sl (n+1) [] xs)
      |otherwise=sl n (x:acc) xs
pasteable (a,b) (c,d)=(c>a && b`isInfixOf`d)
                      || (c==a && b`isInfixOf`(drop (length b) d))
findprefixes l=filter (\(a,b,c)->c/=[])
               $ map (\(a,b)->(a, b, map fst $ filter (pasteable (a,b)) l))
               $ filter (\(a,b)->length b==plen && last b/='\n')
               $ map (\(a,b)->(a, take plen b)) l
mergePrefixes [] = []
mergePrefixes (p:ps) = mergePrefixes' p ps
 where mergePrefixes' p [] = [p]
       mergePrefixes' (a,x,b) ((c,y,d):qs) =
         if length (filter (>=c) b) >= length d then
           mergePrefixes' (a,x,b) qs
         else
           (a, x, (filter (<c) b)):(mergePrefixes' (c,y,d) qs)
uc = ("~!@#$%^&*()_+<>?:{}|\""++['A'..'Z'])
lc = ("`1234567890-=,./;[]\\'"++['a'..'z'])
down c = case [[lo]|(lo,hi)<-zip lc uc,c==hi] of []->error [c];p->head p
applyPrefixToLine prefix [] s=return s
applyPrefixToLine [] line s=emit line s
applyPrefixToLine prefix line@(ch:rest) s=
 if prefix`isPrefixOf`line then
   do { s<-emitPaste s; applyPrefixToLine prefix (drop (length prefix) line) s}
 else
   do { s<-emitch s ch; applyPrefixToLine prefix rest s}
type Keystroke = (Char, [Char])
key action k (n, shift) = do
  putStrLn ((show n)++" "++[action]++" "++k)
  if k=="Shift" then return (n+1, (not shift))
  else return (n+1, shift)
emitch (m, shift) ch=
  case ch of
    '\t'->key 'H' "Tab" (m,shift)
    '\n'->key 'H' "Enter" (m,shift)
    ' '->key 'H' "Space" (m,shift)
    _->
      if shift && ch`elem`lc then
        do { key 'R' "Shift" (m, True); key 'H' [ch] (m+1, False) }
      else if not shift && ch`elem`uc then
             do { key 'P' "Shift" (m, False); key 'H' (down ch) (m+1, True) }
           else if ch`elem`lc
                then key 'H' [ch] (m, shift)
                else key 'H' (down ch) (m, shift)
emit line s = foldM emitch s line
emitPaste s = do
  s<-key 'P'"Ctrl" s
  s<-key 'H' "v" s
  key 'R' "Ctrl" s
emitCopy s = do
  s<-key 'H' "Home" s
  s<-key 'P'"Ctrl" s
  s<-key 'H' "c" s
  s<-key 'R' "Ctrl" s
  s<-key 'R' "Shift" s
  key 'H' "End" s
applyPrefix pf ((a,b):xs) p@((c,y,d):ps) s=
  if (c==a) then
    do
      s@(n, shift) <- emit y s
      s <- if shift then return s else key 'P' "Shift" s
      s <- emitCopy s
      s <- applyPrefixToLine y (drop (length y) b) s
      applyPrefix y xs ps s
  else
    do
      s<-applyPrefixToLine pf b s
      applyPrefix pf xs p s
applyPrefix "" ((a,b):xs) [] s=
  do
    s <- emit b s
    applyPrefix "" xs [] s
applyPrefix pf ((a,b):xs) [] s=
  do
    s<-applyPrefixToLine pf b s
    applyPrefix pf xs [] s
applyPrefix _ [] _ s=return s

main=do
  input <- getContents
  let lines = softlines input
  let prefixes = mergePrefixes (findprefixes lines)
  (n,shift) <- applyPrefix "" lines prefixes (1, False)
  if shift then
    key 'R' "Shift" (n, shift)
  else
    return(n,shift)

```
> 12 votes

---
Tags: code-challenge, optimization, keyboard
---


title: Calculate practical numbers

text:
# Question
Title: Calculate practical numbers
### Definition

A positive integer `n` is a practical number (OEIS sequence A005153) iff all smaller positive integers can be represented as sums of distinct divisors of `n`.

For example, `18` is a practical number: its divisors are 1, 2, 3, 6, 9, and 18, and the other positive integers smaller than 18 can be formed as follows:

```
 4 = 1 + 3          5 = 2 + 3           7 = 1 + 6
 8 = 2 + 6          10 = 1 + 9         11 = 2 + 9
12 = 3 + 9 = 1 + 2 + 9 = 1 + 2 + 3 + 6
13 = 1 + 3 + 9      14 = 2 + 3 + 9      15 = 6 + 9
16 = 1 + 6 + 9      17 = 2 + 6 + 9

```

But `14` is not a practical number: its divisors are 1, 2, 7, and 14, and there's no subset of these which adds to 4, 5, 6, 11, 12, or 13.

### Challenge

Write a program, function, or verb which takes as input a positive integer `x` and either returns or prints the xth practical number, indexed from 1 for consistency with OEIS. Your code must be sufficiently efficient that it can handle inputs up to 250000 in less than two minutes on a reasonable desktop computer. (NB my reference implementation in Java manages 250000 in less than 0.5 seconds, and my reference implementation in Python manages it in 12 seconds).

### Test cases

```
Input        Expected output
1            1
8            18
1000         6500
250000       2764000
1000000      12214770
3000000      39258256

```

# Answer
# J (99 chars)

```
f=:3 :0
'n c'=.0 1
while.c<y do.
'p e'=.__ q:n=.n+2
c=.c+*/(}.p)<:}:1+*/\(<:p^e+1)%<:p
end.
n+n=0
)

```

Since the problem statement asks for a "program, function *or verb*", someone had to make a J submission. J people will notice I didn't really golf (!) or optimize this. Like the other entries, I used Stewart's theorem, mentioned at the OEIS link, to test whether each even number is practical or not.

I don't have ready access to a "reasonable desktop computer" with J installed. On my six year old netbook `f 250000` computes in 120.6 seconds, which is not quite under two minutes, but presumably on any slightly more reasonable computer this finishes in time.
> 5 votes

# Answer
# Mathematica, ~~126~~ 121 chars

Thanks to belisarius.

Using the formula on wikipedia.

```
f=(i=j=1;While[j<#,If[And@@Thread[#[[;;,1]]<2+Most@DivisorSum[FoldList[#Power@@#2&,1,#],#&]&@FactorInteger@++i],j++]];i)&

```

Examples:

```
f[1]

```

> 1

```
f[8]

```

> 18

```
f[250000]

```

> 2764000

It took 70s to compute `f[250000]` on my computer.
> 6 votes

# Answer
# Haskell - 329

```
s 1=[]
s n=p:(s$div n p)where d=dropWhile((/=0).mod n)[2..ceiling$sqrt$fromIntegral n];p=if null d then n else head d
u=foldr(\v l@((n,c):q)->if v==n then(n,c+1):q else(v,1):l)[(0,1)]
i z=(z<2)||(head w==2)&&(and$zipWith(\(n,_)p->n-1<=p)(tail n)$scanl1(*)$map(\(n,c)->(n*n^c-1)`div`(n-1))n)where w=s z;n=u w
f=((filter i[0..])!!)

```

Examples:

```
> f 1
1
> f 13
32
> f 1000
6500

```

Here's a small testing suite (prepend to the above):

```
import Data.Time.Clock
import System.IO

test x = do
    start <- getCurrentTime
    putStr $ (show x) ++ " -> " ++ (show $ f x)
    finish <- getCurrentTime
    putStrLn $ " [" ++ (show $ diffUTCTime finish start) ++ "]"

main = do
    hSetBuffering stdout NoBuffering
    mapM_ test [1, 8, 1000, 250000, 1000000, 3000000]

```

Test results after being compiled with `ghc -O3`:

```
1 -> 1 [0.000071s]
8 -> 18 [0.000047s]
1000 -> 6500 [0.010045s]
250000 -> 2764000 [29.084049s]
1000000 -> 12214770 [201.374324s]
3000000 -> 39258256 [986.885397s]

```
> 3 votes

# Answer
# Javascript, ~~306 307~~ 282B

```
function y(r){for(n=r-1,k=1;n;k++)if(p=[],e=[],c=0,P=s=1,!((x=k)%2|1==x)){while(x>1){for(f=x,j=2;j<=Math.sqrt(f);j++)if(f%j==0){f=j;break}f!=p[c-1]?(p.push(f),e.push(2),c++):e[c-1]++,x/=f}for(i=0;c>i;i++){if(p[i]>P+1){s=0;break}P*=(Math.pow(p[i],e[i])-1)/(p[i]-1)}s&&n--}return k-1}

```

250k in approx. 6s on my laptop.

Commented un-golfed code: http://jsfiddle.net/82xb9/3/ now with better sigma-testing and a better if condition (thank you comments)

Pre-edit versions: http://jsfiddle.net/82xb9/ http://jsfiddle.net/82xb9/1/
> 2 votes

---
Tags: code-golf, sequence, number-theory
---