随机数发生器及其简单应用

Practice makes perfect!

随机数产生原理:经典的随机数产生方法为是线性同余法,即Linear Congruence Generator (LCG),由Lehmer于1951年提出。
同余:对于两个整数A,B,如果它们同时除以一个自然数M的余数相同,就说A,B对于模M同余,A \equiv B\ mod \ M

LCG 算法:

X_{n+1} = (aX_{n} + c) \ mod \ m 

X为随机序列,模除因子,a乘子(0 < a < m),c为增量,或偏移量(0 < c < m),X_0称为初始种子。

如果m,a,c取值合适,序列最大周期将达到m。这种情况下,序列中所有可能的整数都在某点固定出现。当c=0时候,LCG就变换成了乘法同余发生器,multiplicative congruential generator (MCG),c≠0时叫做混合同余发生器,mixed congruential generator,MCG.

具体实现参见:wiki 随机数产生原理

ANSI C标准规定rand()返回一个整数值,RAND_MAX通常不是很大。ANSI C标准要求RAND_MAX最大32767.

汇编语言实现猜随机数游戏:

;THis project decides to play the number game with computer !!! 
stack segment   stack
    dw  256 dup(0)
stack ends
    
data segment
data ends

code segment
    assume cs:code, ds:data
    
start:
    mov cx, 0 
    call random         ;get the random number 
    mov ax, bx
    mov bl, 10          ;convert Heximal to Decimal
    div bl
    mov ch, al 
j0: 
    mov ah, 01          ;receive data from keyboard
    int 21h
    mov bh, al
    sub bh, 30h
    mov ah, 01
    int 21h
    mov bl, al
    sub bl, 30h
    cmp bx, cx
    je  j1
    ja  j2
    jb  j3
j2:                     ;the input data is bigger than ranmdom number
    mov dl, 62
    mov ah, 2
    int 21h
    mov dl, 13
    int 21h
    mov dl, 10
    int 21h 
    jmp j0
j3:                     ;the input data is smaller than random number
    mov dl, 60
    mov ah, 2
    int 21h
    mov dl, 13
    int 21h
    mov dl, 10
    int 21h
    jmp j0
j1:                     ;the input data is equal to random data
    mov dl, 61
    mov ah, 2               
    int 21h 
    mov dl, 13
    int 21h
    mov dl, 10
    int 21h    
    mov ax, 4c00h
    int 21h
random proc near        ;the random subprocess
    push cx
    push dx
    push ax
    sti                 ;Set Interrupt
    mov ah, 0
    int 1ah
    mov ax, dx
    and ah, 3
    mov dl, 101         ;generate 0~100 random number
    div dl
    mov bl, ah
    pop ax
    pop dx
    pop cx
    ret
random endp
    code ends
end start

C++实现猜随机数游戏:

#include
#include
#include
#define random(a, b) (rand()%(b - a + 1) + a) //generate the random number in [a, b]

using namespace std;

int main()
{
	srand((unsigned)time(NULL));
	int rand_num = 0;
	int temp;
	rand_num = random(1, 100);
	cout << "Guess what number my brain has generated :" <> temp;
	do
	{
		if (rand_num < temp)
		{
			cout << "	Your answer is too large " << endl;
		}
		else if (rand_num > temp)
		{
			cout << "	Your answer is too small " << endl;
		}
		else
		{
			cout << "good game, well done !" << endl;
		}
		cin >> temp;
	} while (rand_num != temp);
	cout << "good game, well done !" << endl;
	return 0;
}

 

你可能感兴趣的:(C++,数据结构与算法分析-C++描述,随机数,汇编,C,猜数字)