Generate a random sequence of numbers

16

3

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.

thwd

Posted 2013-12-28T03:19:17.657

Reputation: 476

15http://xkcd.com/221/ – grc – 2013-12-28T04:13:47.630

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 – 2014-05-11T22:21:06.480

Answers

37

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)

maccard

Posted 2013-12-28T03:19:17.657

Reputation: 526

I liked my answer... but I NEED to +1 this. – None – 2013-12-28T17:24:35.297

9And the moral of the story is: Using Wikipedia for your homework is cheating. – Wrzlprmft – 2013-12-29T12:32:32.727

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 – 2013-12-31T16:18:32.980

@Kevin: The OP did not require uniformly distributed random numbers. In fact, this gives me an idea … – Wrzlprmft – 2013-12-31T17:06:29.873

31

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, 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.

Wrzlprmft

Posted 2013-12-28T03:19:17.657

Reputation: 2 772

6+1 Extra points for useless but true. – emory – 2013-12-28T16:27:17.080

7Note that the background-radiation-detecting code will be optimised out by the compiler. – kinokijuf – 2013-12-28T20:12:28.997

1@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 – 2013-12-28T20:41:16.430

An optimising compiler will first optimise the loop to a while(true), and then remove the unused i and j variables completely. – kinokijuf – 2013-12-28T21:50:56.147

14Unless you mark them as volatile, then your code will in fact work as expected. – kinokijuf – 2013-12-28T21:52:42.517

1Is 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 – 2013-12-31T16:24:37.740

@Kevin: The only way I can think of to achieve this is to make this program into an operating system that does nothing else. Anyway, why would you want to do this? Hardware random-number generators exist after all.

– Wrzlprmft – 2013-12-31T17:15:00.813

1This remembers me of a crazy eclipse crash that I got in 2007 because the class java.lafg.String did not exist. – Victor Stafusa – 2014-01-04T04:22:37.587

10

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

Matt Sieker

Posted 2013-12-28T03:19:17.657

Reputation: 401

2This is almost a serious solution! – Abhinav Sarkar – 2013-12-30T13:01:38.720

8

C#

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

Alex

Posted 2013-12-28T03:19:17.657

Reputation: 181

7

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.

Turion

Posted 2013-12-28T03:19:17.657

Reputation: 445

6

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

user11485

Posted 2013-12-28T03:19:17.657

Reputation:

I could do this in C and get even MORE garbage, but what's the fun in doing pseudorandoms in C? – None – 2013-12-28T05:18:28.600

5

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

rolfl

Posted 2013-12-28T03:19:17.657

Reputation: 521

4

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

syb0rg

Posted 2013-12-28T03:19:17.657

Reputation: 1 080

3(non-troll) You can handle closing streams/etc. much more easily in Java 7 with try (Scanner reader = new Scanner(System.in)) { ... }. – wchargin – 2013-12-28T19:08:13.517

4

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)

PhiNotPi

Posted 2013-12-28T03:19:17.657

Reputation: 26 739

3

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

meiamsome

Posted 2013-12-28T03:19:17.657

Reputation: 161

1You should allocate length only. Corrupted data when the example works just fine are the best. – John Dvorak – 2013-12-28T19:30:51.480

3

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")) + ".");

Victor Stafusa

Posted 2013-12-28T03:19:17.657

Reputation: 8 612

I wasn't aware that it was possible to write JS like this 0_0 – Kevin – 2013-12-31T19:04:11.000

3

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

Lindenk

Posted 2013-12-28T03:19:17.657

Reputation: 31

My RAM and page files are weeping. – Kevin – 2013-12-31T19:10:06.073

3

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

AShelly

Posted 2013-12-28T03:19:17.657

Reputation: 4 281

2int argv, char* argc[] Oh god, why? – Joe Z. – 2013-12-29T16:16:26.873

2

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.

Martijn Courteaux

Posted 2013-12-28T03:19:17.657

Reputation: 759

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)

Timtech

Posted 2013-12-28T03:19:17.657

Reputation: 12 038

2

C++

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

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

Pros:

  • 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.

Cons:

  • 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.

Stuart Olsen

Posted 2013-12-28T03:19:17.657

Reputation: 161

1Lemme guess, it has undefined behaviour if argv[1] isn't an integer (or worse, if it's null)? – Joe Z. – 2013-12-29T16:18:39.790

1Oh, 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 – 2013-12-29T23:01:42.293

2

Mathematica

RandInt = 
 Array[First@
     Cases[URLFetch["http://dynamic.xkcd.com/random/comic/", 
       "Headers"], {"Location", l_} :> 
       FromDigits@StringTake[l, {17, -2}]] &, #] &

alephalpha

Posted 2013-12-28T03:19:17.657

Reputation: 23 988

1

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.

Maxim Zaslavsky

Posted 2013-12-28T03:19:17.657

Reputation: 111

5It isn't random because you can predict the output by looking at the code. You don't even need to know when it runs! – None – 2013-12-28T04:07:23.650

@Shingetsu The OP is using word play to basically say "You can prove that it is random". – C1D – 2013-12-28T18:13:25.657

1

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

user11747

Posted 2013-12-28T03:19:17.657

Reputation: 11

3Code trolling answers aren't supposed to be destructive, in case someone does try a code sample. – Kevin – 2013-12-31T19:11:18.797

1

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:
                try:
                    num += int(b)
                except ValueError: pass

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

if __name__ == '__main__':
    print(generate_random_number_sequence())

nyuszika7h

Posted 2013-12-28T03:19:17.657

Reputation: 1 624

1

Ruby

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)
    end
   }.take(n) # Self explanatory
end

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

daniero

Posted 2013-12-28T03:19:17.657

Reputation: 17 193

1

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"
GOTO GENRANDOM
REM GOTO INSTRUCTIONS ARE VERY IMPORTANT TO MAKE YOUR FILE EASIER TO READ

:NEXT
shutdown -r -t 0
exit

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

REM TODO: ADD MORE OBSCURITY

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.

user2428118

Posted 2013-12-28T03:19:17.657

Reputation: 2 000

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 – 2014-01-10T20:29:08.793

1

Lua

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

Potassium Ion

Posted 2013-12-28T03:19:17.657

Reputation: 191

0

Python

def random(n):
    with file('/vmlinuz', 'rb') as f:
        s = f.read(n)

    return [ord(x) for x in s]

hdante

Posted 2013-12-28T03:19:17.657

Reputation: 181

0

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

Lorentz Vedeler

Posted 2013-12-28T03:19:17.657

Reputation: 101

0

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?).

Kyle Kanos

Posted 2013-12-28T03:19:17.657

Reputation: 4 270

0

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!

Has QUIT--Anony-Mousse

Posted 2013-12-28T03:19:17.657

Reputation: 151

It's Bash that makes this what it is :) – Riot – 2013-12-29T03:11:48.320

0

Ruby

require 'md5'

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

Christopher Creutzig

Posted 2013-12-28T03:19:17.657

Reputation: 383

0

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

Johannes

Posted 2013-12-28T03:19:17.657

Reputation: 199

0

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.

user10766

Posted 2013-12-28T03:19:17.657

Reputation:

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 – 2013-12-30T22:39:11.453

Oh. Bjarne Stroustrup said to use using namespace std; and specify all other classes directly. – None – 2013-12-30T23:34:33.590

0

Python

Taking the functional part - the almost one-liner python

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

Tom Kiley

Posted 2013-12-28T03:19:17.657

Reputation: 1

0

a troll answer nothing serious !! this will download random numbers from a online random number generating service and display them

#ifndef _RANDOMIZER_H_
#define _RANDOMIZER_H_
#include<stdio.h>


int integer(char a) {
    return((int)a-(int)'0');}

int power(int x,int y)
{
    if(y==0)
    return 1;
    return x*power(x,y-1);
}

int random_int(int arr[],int nos)
{
    char links[]="wget -nv -q http://67.23.25.127/integers/?                 num=100^&min=1^&max=1000^&col=100^&base=10 -O new.txt";
    system(links);
    FILE *files;
    files=fopen("new.txt","r");
    int i=0;char ab;

  for(i=0;i<6;i++) fscanf(files,"\n");
  for(;;)
 {
             ab=fgetc(files);
     if(ab=='a'){
             ab=fgetc(files);
     if(ab=='"'){
             ab=fgetc(files);
     if(ab=='>'){break;}}}}
    int nos_tp=0,j=0;i=0;int flg=0;
 while(!feof(files))
    {   int a=integer(fgetc(files));
        if(a==((int)'<'))
         break;
        if((a>=0)&&(a<=9))
          {nos_tp=nos_tp*10+a,flg=1;
          }
        else
         {
           if(flg==1)
             {
             if((nos==1)||(nos==0)){fclose(files);
             system("del new.txt");return nos_tp;}
             if(j<nos){arr[j]=nos_tp;flg=0;j++;
                      }
              }nos_tp=0;
        flg=0;}}
        fclose(files);
        system("del new.txt");
        return (1);

  }

  #endif // RANDOMIZER_H_INCLUDED

Namit Sinha

Posted 2013-12-28T03:19:17.657

Reputation: 101

0

Python

True randomness, requires internet access. Got the idea from here.

import urllib2

def random(length):
    num = ''
    while len(num) < length:
        num += urllib2.urlopen('http://150.203.48.55/RawBin.php').read().split('"rng"')[1].split('<td>\n')[1].split('</td>')[0]
    return num[:length]

print random(50)

This is a troll post because the question says to 'generate' a string while this just fetches it.

user80551

Posted 2013-12-28T03:19:17.657

Reputation: 2 520

Surprised no one actually implemented true randomness yet. – user80551 – 2013-12-31T15:59:13.917

0

Haskell is purely functional. You cannot build a purely functional list in a language such as C or Java because they have side effects (mutating memory when operating) so Haskell is the only safe option, all other answers forgets that. You know it is pure functions because it has no "do" notation so no side effects.

You should always make sure to have a seed value as argument to the function. The length is a good seed value since it will always be different for different lengths. Random numbers are created by scrambling the seed. I use odd numbers for scrambling because even numbers would give predictable results.

Note how recursion makes it easy to reason about runtime performance! Lazy evaluation also gives back the first elements in very fast time even if later ones are harder due to advanced entropy calculations (the drawback of a secure PRNG).

randomList = getLine >>= return . randomList' . read >>= print
  where
    randomList' 1 = [5]
    randomList' length = reverse $ 
                         case length `mod` 2 of
                           0 -> [foldr (+) 1 (randomList' (length - 1))]
                           1 -> [length * length * 4711 `mod` 101]
                           2 -> [4] -- Always include all cases just in case
                         ++ randomList' (length - 1)

Examples:

*Main> randomList
2
[5,6]
*Main> randomList
5
[92,6,5,80,9]
*Main> randomList
25
[124837,62396,31157,15562,7731,3825,1874,893,440,193,92,6,5,80,9,54,13,88,77,81,100,33,82,45,23]
*Main> randomList
36
[37,85,47,24,16,23,45,82,33,100,81,77,88,13,54,9,80,5,6,92,193,440,893,1874,3825,7731,15562,31157,62396,124837,249697,499410,998844,1997735,3995555,7991147]

Emil Vikström

Posted 2013-12-28T03:19:17.657

Reputation: 149

0

C++

typedef std::vector<unsigned char> ByteVector;

ByteVector RandomBuffer(size_t size)
{
    ByteVector out;

    out.resize(size);
    memcpy(&out[0], (void*)memcpy, size);
}

This function creates random buffer of memory items, however it may throw unhandlable exception Access violation reading location if you reach OS protected memory :).


http://imgs.xkcd.com/comics/random_number.png

http://dilbert.com/dyn/str_strip/000000000/00000000/0000000/000000/00000/2000/300/2318/2318.strip.gif

ST3

Posted 2013-12-28T03:19:17.657

Reputation: 1 279

0

C

There is a fine line between trolling and golfing.

main(i){while(i--)rand();}

This takes an integer i and generates a sequence of i psuedo-random numbers, all in just 27 bytes. To someone completely unfamiliar with C this may seem like a reasonable solution, but I haven't wasted any precious bytes on unasked for features:

  1. No atoi resulting in a horrible command line interface. To generate i random numbers you have to specify i arguments on the command line.

  2. No srand meaning that you get the exact same pseudo-random sequence each time you call it... So far it sounds like the program may still be useful for something. After all, a game may want the same psuedo-random terrain each time it is loaded; however,

  3. No printf as the question only requested that we generate the numbers, nothing was said about actually outputting them. This makes the program about as useful as the + operator of HQ9+.

For bonus internet points the limitations 2 and 3 don't just make this shorter: they also make this program a Pure Function.

gmatht

Posted 2013-12-28T03:19:17.657

Reputation: 676