Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

In this task, you are allowed make an useful program to do anything you can write within 100 characters. You are allowed to use less characters, but not more.

Rules, just to protect from standard loopholes that are no longer funny:

  1. Your program cannot access the internet, unless it really has to. For example, the program which shows the most upvoted question on this website may use the Internet to check this question. However, it's not allowed to browse the Internet in order to find its real source and run it.

  2. Your program cannot be an interpreter for the language it was written in. However, Brainfuck interpreter in non-Brainfuck language would be fine.

  3. Your program cannot execute external programs that does exactly what your program does. For example, you cannot run vim, and claim that your program is vim implementation.

  4. Your program cannot be dangerous for the computer it's being ran on and other computers. You aren't allowed to write program like rmdir / (the example here intentionally doesn't work, don't fix it), and claim it's an useful program to remove all files on the computer.

  5. Your program may be as slow as you want, and use as much resources as you want, as long you can prove it does what it meant to do.

  6. You aren't allowed to make language specifically for this task. However, you are allowed to make interpreter for your invented language in some other programming language.

share|improve this question

closed as too broad by Doorknob, Peter Taylor, xfix, TheDoctor, Mhmd Mar 23 at 18:59

There are either too many possible answers, or good answers would be too long for this format. Please add details to narrow the answer set or to isolate an issue that can be answered in a few paragraphs.If this question can be reworded to fit the rules in the help center, please edit the question.

    
Can I post more than one answer for this contest? –  TrungDQ Mar 23 at 11:12
    
@TrungDQ: Sure. –  xfix Mar 23 at 11:19
1  
This has got to be one of the best questions to date ;) –  Timtech Mar 23 at 15:21
13  
This is way too open-ended, even for a site like this one, even for a popularity contest. Literally any answer is valid, there's no frame of reference whatsoever for comparing them. –  Aaronaught Mar 23 at 15:53
3  
This question is cannibalizing code-golf. Interesting 100 character ideas should be able to be rephrased into great code-gold questions. I'd encourage the answerers to spend a few extra minutes to turn their answers into new questions. –  gnibbler Mar 27 at 20:35

11 Answers 11

up vote 25 down vote accepted

C - 47 bytes

The following program outputs every document ever written in human history, along with every document that will ever be written and loads of interesting texts that no human will ever come up with (along with a "little bit" of garbage in between). Just give it some time. Moreover, every time you run it, it will output different texts first! If that's not useful! (And all of that within half the character limit!)

main(){srand(time(0));while(1)putchar(rand());}

If you don't care about it outputting something else each time, you only need 41 bytes!

main(){srand(0);while(1)putchar(rand());}

Not quite C99 conform, but it compiles smoothly with gcc.exe (GCC) 4.7.0 20111220.

The rules state

Your program may be as slow as you want, and use as much resources as you want, as long you can prove it does what it meant to do.

No problem.

Some things, this program will output:

  • a solution to every Millennium Problem
  • tomorrow's newspaper articles
  • the complete works of Shakespeare's (of course)
  • your darkest secret
  • all the other answers to this question

Not really, because (as ace correctly mentioned in the comment), rand() is only a pseudo-random generator, that will wrap around at some point - probably way too early to produce a lot of meaningful texts. But I doubt that getting data from a true (hardware) random number generator is remotely possible within 100 characters. I'll leave this here for the fun of it, though.

As Dennis notes, the randomness of the the algorithm, could be somewhat improved (within the character limit), by using rand()^rand()>>16 instead of rand().

share|improve this answer
8  
Not necessarily. rand() is only pseudorandom - it may not produce any useful text before it loops around. –  ace Mar 23 at 15:25
1  
@Dennis luckily that is still within the rules of this question! :) –  Martin Büttner Mar 23 at 16:33
1  
@m.buettner: With GLIBC's rand(), there's a simple algebraic relation between bytes of your program's output: Viewing the output as an array x, you have x[i] == (x[i - 3] + x[i - 31] + c[i]) % 256, where c[i] is 0 with probability 0.75 and 1 with probability 0.25. This pretty much means that it can't generate any of the things you mentioned. –  Dennis Mar 23 at 17:04
1  
@m.buettner: It won't make the PRNG much better, but you can remove the linearity using rand()^rand()>>16 instead of plain rand(). If you're looking for ways to save on bytes, remove int and %256. –  Dennis Mar 23 at 18:59
1  

BBC BASIC, 84 chars

MODE 6:INPUT T,A,B,A$,B$:FOR X=0 TO 1279:A=A+EVAL(A$):B=B+EVAL(B$):DRAW X,A+500:NEXT

Plots the solutions to first and second order differential equations.

Takes as user input:

Title (does nothing)
Start value for A (plotted value)
Start value for B (not plotted)
Expression for dA/dX
Expression for dB/dX

Inspired by a differential equation solving software called Polymath which I used when studying to be a chemical engineer. We would input different equations for reactants and products and see how the whole reaction system changed over time. A very simple software (not much more complex than this) but much more convenient for this purpose than Excel. Unfortunately I cannot do a complete clone of Polymath in 100 chars.

enter image description here

share|improve this answer

Mathematica 76

This program constructs an applet that displays information regarding various properties for any of 240 countries. It opens with information about the adult population of Afghanistan. The user may change the country and property settings through drop-down lists.

Mathematica interoperates smoothly with WolframAlpha.
For this reason I believe the submission meets requirement #1 of the challenge: "Your program cannot access the internet, unless it really has to".

This rather modest applet simply makes use of existing functionality in the Mathematica language. A short video provides some additional information about the applet.

d = CountryData; Manipulate[WolframAlpha[p <> " " <> c], {p, d["Properties"]}, {c, d[]}]

alpha


Below is a list of the first 20 (of 223) properties related to countries. With a additional programming one can obtain additional information regarding countries and analyze this information in Mathematica.

CountryData["Properties"][[;; 20]]

{"AdultPopulation", "AgriculturalProducts", "AgriculturalValueAdded", "Airports", "AlternateNames", "AlternateStandardNames", "AMRadioStations", "AnnualBirths", "AnnualDeaths", "AnnualHIVAIDSDeaths", "ArableLandArea", "ArableLandFraction", "Area", "BirthRateFraction", "BorderingCountries", "BordersLengths", "BoundaryLength", "CallingCode", "CapitalCity", "CapitalLocation"}

share|improve this answer
    
I don't see how your program "has to" access the internet. The data you present doesn't change that frequently you would need to rely on an outside source. –  shiona Mar 23 at 14:11
1  
Whether the source is inside or outside is open to debate. I was considering the request for information on WolframAlpha (which the code does make) to be a case of (necessary) "access to the internet", even though the code directly consults a Wolfram data server and does not require the use of a browser like FireFox. It does require that one have a network or WIFI connection –  David Carraher Mar 23 at 14:40
1  
-1 if I could - this simply munges a data structure from a pre-existing service. –  l0b0 Mar 23 at 16:47
    
@l0b0 I suppose you could see it that way. Or you might say that it exploits the functionality of the language. After all, WolframAlpha was designed from the ground up to interoperate closely with Mathematica. –  David Carraher Mar 23 at 17:07
1  
"The information in WolframAlpha is an integral part of Mathematica and the Wolfram Language" is a rather alarming state of affairs. That must make it the least stable programming language in existence. –  Peter Taylor Mar 23 at 18:16

bash, 100 bytes

head -c${1--1} /dev/zero |
openssl enc -aes-128-ctr -pass file:/dev/random 2>/dev/null |
tail -c+17

This script prints a cryptographically secure stream of bytes. It takes an optional argument specifying the number of bytes it should print. By default, the output will be infinite.

Useful in cases where reading from /dev/urandom is just too darn slow.

Benchmark

$ time head -c 1G /dev/urandom > /dev/null
Real    59.75
User    0.03
Sys     59.68
$ time random 1G > /dev/null
Real    0.68
User    0.64
Sys     0.86

This script generates up to 1.5 GiB per second on my i7-3770.

In contrast, reading from /dev/urandom manages to generate barely 1 GiB per minute.

How it works

  • head -c${1--1} /dev/zero outputs the specified amount of zero bytes. If no amount is specified, ${1--1} equals -1 and head outputs an infinite amount.

  • openssl enc -aes-128-ctr -pass file:/dev/random uses AES-128 in counter mode to encrypt the zero bytes, reading the password from /dev/random.

  • tail -c+17 gets rid of the output's 16-byte header.

share|improve this answer
    
Note that this stream can be distinguished from a "real" random stream by looking at the first 2^68 output bytes (a real random stream should have duplicated blocks there, this one won't). –  Paŭlo Ebermann Mar 23 at 16:40
    
@PaŭloEbermann: You're obviously right. Then again, it would take over 6,000 years to generate that many bytes on my machine... –  Dennis Mar 23 at 16:48

JavaScript: 97

p=function(x){i=2;while(i*i<=x){if(x%i==0)return 0;i++}return 1},y=1;while(1){p(y)&&alert(y);y++}

With 3 characters to spare: it will alert every prime number in existence, very useful for cryptography-applications.

Ungolfed:

var isPrime = function(x){
    var i = 2;
    while(i * i <= x){
        if(x % i == 0) return false;
        i++;
    }
    return true;
}, y = 1;

while(true){
    if(isPrime(y)) alert(y);
    y++;
}
share|improve this answer
    
Is it limited to 32 or 64 bits numbers? –  A.L Mar 24 at 11:29
    
@n.1 I don't know if or what the spec says about numerical limits, but the algorithm should work for all positive numbers. It depends on the implementation, I guess. –  Kninnug Mar 24 at 11:33
2  
...very useful for cryptography-applications - I had to +1 just for the mental image of some poor soul clicking through alert after alert, waiting for the numbers to become anywhere near big enough to be useful for cryptography. –  BenM Mar 25 at 23:25
    
And I believe Javascript represents all its numbers in 64-bit floating point format. For this particular purpose, the exponent is useless, so you're effectively restricted to the mantissa. From my interpretation of Wikipedia‌​, you'll have a 52-bit mantissa, and an effective maximum of 9,007,199,254,740,992 (after that point, it starts skipping over odd numbers, so it becomes useless for storing prime numbers). –  BenM Mar 25 at 23:45
    
@DatEpicCoderGuyWhoPrograms: Can you please stop spamming for syntax highlighting? –  Kyle Kanos Jul 14 at 14:04

C - 99 characters

i;main(int c,char**a){for(a+=2;1+(c=getchar());)putchar(c+(**(a-1)-69?1:-1)**(*a+i++%strlen(*a)));}

This program allows encryption and decryption of any kind of data.

Usage

First... compile it!

gcc crypto.c crypto

If you want to encrypt the contents of mypreciousdata.txt with the key mysecretkey, and store the result in myprotecteddata.txt:

cat mypreciousdata.txt | ./crypto E mysecretkey > myprotecteddata.txt

Now, if you want to retrieve the decoded contents of myprotecteddata.txt:

cat myprotecteddata.txt | ./crypto D mysecretkey > mypreciousdata.txt

The longer the key, the safer!

Explanation

Please find the expanded and commented code below:

int main(int argc, char** argv)
{   
    // retrieve the first argument passed to the program (action)
    char action = argv[1][0];

    // retrieve the second argument passed to the program (key)
    char* key = argv[2];

    // initialize character position in the key
    int i = 0;

    // initialize the current input character
    char c = 0;

    // loop until we reach the end of input
    while (c != -1){
        // get a character from stdin
        c = getchar();
        if (action == 'E'){
            // encode the current character
            putchar(c + key[i]);
        } else{
            // decode the current character
            putchar(c - key[i]);
        }
        // increment the position in the key, without overflow
        i = (i + 1) % strlen(key);
    }
}
share|improve this answer
    
This is a variant of the Vigenère cipher adapted for a alphabet of the size of your char type (usually 256). –  Paŭlo Ebermann Mar 23 at 16:47

GolfScript

I managed to squeeze this into exactly 100 characters!

{{}/]{97-}%}:b~:|;"etaoinshrdlcumwfgypbvkjxqz"b:f,:&,{:x[|{&x-+&%f?}%{+}*\]}%$0=1=:x|{&x-+&%97+}%''+

It takes input of ROT-n encrypted text and outputs the text decoded. (Taken from here.) For example, when given the input pmttwxmwxtmwnxzwoziuuqvoxchhtmakwlmowtnabiksmfkpivom, the output is 8hellopeopleofprogrammingpuzzlescodegolfstackexchange.

share|improve this answer

JavaScript

To generate a unique id in javascript
Math.random().toString(30).slice(2);

Produces something like : 'h9d2f4aniimma7h1d3pbffi0foi8d3mf'

strings of 30-32 alpha-numeric characters

Math.random().toString(36).slice(2)

Produces something like : 'uq2sze67hsacq5mi'

Strings of length 14-16 .

share|improve this answer

Javascript

Solve any equation (well, not all, but should work with common functions...)

r=s=>{for(x=e=a=1e-7;a;x-=e*a/(eval(s.replace(/x/g,x+e))-a))a=eval(s.replace(/x/g,x));return x}

Without ES6 (105 chars):

function r(s){for(x=e=a=1e-7;a;x-=e*a/(eval(s.replace(/x/g,x+e))-a))a=eval(s.replace(/x/g,x));return x}

Just give the left side of the equation assuming that the right side is zero.

Example :

  • r("x*x-9") returns 3
  • r("Math.sin(x)-1") returns 1.5707963394347828 (pi/2)
  • r("Math.pow(2,x)-512") returns 9

Warning : can diverge on some functions (or if there is no solution) and freeze your browser tab, or return NaN.

share|improve this answer

C++ 57

#include<iostream>
#include<conio.h>
int main(){std::cout<<getch();}  

This program takes a character input and outputs its ASCII value.

share|improve this answer
2  
The Brainfuck$ code is a lot shorter - ,: –  Timtech Mar 23 at 15:19
2  
@Timtech I don't know brainfuck$ –  Mukul Kumar Mar 23 at 15:24
1  
esolangs.org/wiki/Brainfuck$ –  Timtech Mar 23 at 15:38

Fortran - 85 bytes

l=0;read(*,*)n;do while(n>0);i=mod(n,10);l=l+i;n=n/10;enddo;print*,"digit sum=",l;end

Reads in a number and prints out the sum of the digits. Useful for Project Euler problems.

share|improve this answer
    
How does this help for project Euler problems? –  Paŭlo Ebermann Mar 23 at 22:03
    
@PaŭloEbermann: Perhaps I should have added "some" before Project Euler. I know for sure Problems 16, 20 & 119 use digit sums, not sure about others, but many of their problems do not need this one. –  Kyle Kanos Mar 24 at 0:02

protected by Doorknob Mar 24 at 22:21

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.