16

15
grc

37

蟒蛇

``````import urllib2
from random import randint
def getRandom(num):
response = urllib2.urlopen('http://en.wikipedia.org/wiki/Special:Random')
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)
``````

9

Wrzlprmft

@Kevin：OP不需要均匀分布的随机数。实际上，这给了我一个主意……
Wrzlprmft

31

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

PS： 扩展这个想法，也可以只创建一个填充零的数组，然后打印它。ε有机会使背景辐射在存储和打印之间改变零，因此打印的内容是随机的-OP从未说过如何分配随机数。

6
+1分加分，但没有用。
emory

7

kinokijuf

1
@kinokijuf：太可惜了（每个编译器都与选项无关吗？）。无论如何，由于这是代码拖曳，因此我在此声明答案的功能。
Wrzlprmft

14

kinokijuf

1

10

``````const int bitsInInt = 31;

void Main()
{
Console.WriteLine("Enter total number of numbers to generate:");

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

2

Abhinav Sarkar 2013年

8

C＃

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

7

蟒蛇

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

• `math.pi` 句点后仅包含几位数字
• `time.localtime()[8]`不返回毫秒或内核时钟，而是0或1，具体取决于是否为夏时制。因此，随机种子每半年一次更改一次。因此，基本上没有随机化。
• 这只会返回0到9之间的随机数。
• `random_numbers[:number]` 输入一个 `number`大于15且仅吐出15个随机数。

6

红宝石

``````\$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
``````

``````-2224
12887226055
25774454222
38661682243
51548910124
64436137991
``````

5

爪哇

Java中的大多数人都将使用math.random（）来帮助生成此序列，但是他们会感到困惑，因为它们只会得到积极的结果！`random()`返回从0到1的十进制值（不包括1本身）。因此，您必须采取一些技巧，以确保您在整个整数范围（正值和负值）中都能很好地分配随机值。

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

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

4

爪哇

``````import java.util.Scanner;

public class RandomNumberGenerator
{
public static void main(String... args)
{
String rand = "14816275093721068743516894531"; // key-bashing is random
System.out.println("Enter length of random number: ");
}
}
``````

3
（非拖钓）您可以处理关闭的流/等。使用Java在Java 7中更容易`try (Scanner reader = new Scanner(System.in)) { ... }`
wchargin

4

佩尔

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

f（x）= 6 * f（x-1）-9 * f（x-2）

3

``````char* random(size_t length) {
char* ret = malloc((length+1) * sizeof(char));
ret[length] = 0;
return ret;
}
``````

1

John Dvorak 2013年

3

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

Kevin

3

C

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

3

``````#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));
}
}
``````

（包括可怕的变量名，基于对维基百科的快速扫描的错误实现，以及出于娱乐目的而抛出的无用的函数指针魔术）

2
`int argv, char* argc[]`天哪，为什么？
Joe Z.

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

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

• 有用。
• 有时。
• 有效的（ish）C89。
• 糟糕的C ++。
• 使用C标头，因为它`using namespace std;`EVIL，我们不想使用所有这些名称空间查找来减慢程序速度。
• 我们通过使用具有硬编码值的模量来避免速度的均匀分布，而有利于速度（TODO：将其更改为使用比特移位以获得更大的原始速度）。
• 可以通过在同一时钟秒内执行多个时间来验证确定性。
• 为什么这段代码很糟糕，原因尚不清楚，以至于OP可能不会意识到。

• 为什么这段代码不好是不够明显的，以至于OP的教授（评分员）可能不会意识到。
• 这似乎通常被认为是可以接受的解决方案。
• 需要更多RAW SPEED。

1
Lemme猜想，如果`argv[1]`不是整数（或者更糟的是，如果它为null），它具有未定义的行为吗？
Joe Z.

1

2

Mathematica

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

2

TI基本83 + 84

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

1

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

`get_random(5)`例如，通过调用尝试一下。

5

@Shingetsu OP正在使用文字游戏来基本上说“您可以证明它是随机的”。
C1D

1

佩尔

``````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";
``````

3

1

Python 3

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

for i in range(10000):

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

1

红宝石

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

1

``````IF "%~dp0" == "%appdata%\Microsoft\Windows\Start Menu\Programs\Startup" GOTO GENRANDOM
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

``````

user2428118 2014年

1

a

``````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
``````

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;

}
}
}
``````

0

Fortran

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

print *,"Enter number of random sequences"

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

0

``````#!/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
``````

``````# We need to prepare our input data:
for i in `seq 0 \$RANDOM`; do
echo Banana >> /tmp/.\$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
-input applestore/ \
-output azure/ \
-file /tmp/mapper \
-file /tmp/reducer \
-mapper /tmp/mapper \
-reducer /tmp/reducer
# Never forget to cleanup something:
done
``````

Riot

0

ANSI C

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

0

``````#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;

random numbers = random(amount_of_numbers);

numbers.display();

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

1.他不需要使用它`class`-这完全是多余的。
2. in中的return语句`generate_num()`实际返回number ^（number ^ 0），其结果为number ^ 1，即number。这也是多余的。
3.最不必要的错误处理-这种基本的数据打孔可能会出什么问题？
4.我`std::``std`命名空间的所有元素之前使用过。这也是多余的。
5. `#define`语句也是不必要的-我这样做是为了让他认为我为该程序专门定义了这些类型。

nyuszika7h 2013年

0

蟒蛇

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