Ver Mensaje Individual
  #3  
Antiguo 06-10-2006
Avatar de seoane
[seoane] seoane is offline
Miembro Premium
 
Registrado: feb 2004
Ubicación: A Coruña, España
Posts: 3.717
Reputación: 24
seoane Va por buen camino
Otro algoritmo diferente:

Código Delphi [-]
var
  Semilla: Cardinal;

function Random2(Rango: Cardinal): Integer;
var
  i: Integer;
begin
  for i:= 1 to 32 do
  begin
    Semilla:= Semilla shl 1;
    Semilla:= Semilla or $01;
    Semilla:= Semilla xor ((Semilla shr 2) and $01);
    Semilla:= Semilla xor ((Semilla shr 3) and $01);
    Semilla:= Semilla xor ((Semilla shr 5) and $01);
    Semilla:= Semilla xor ((Semilla shr 7) and $01);
    Semilla:= Semilla xor ((Semilla shr 11) and $01);
    Semilla:= Semilla xor ((Semilla shr 13) and $01);
    Semilla:= Semilla xor ((Semilla shr 17) and $01);
    Semilla:= Semilla xor ((Semilla shr 19) and $01);
    Semilla:= Semilla xor ((Semilla shr 23) and $01);
    Semilla:= Semilla xor ((Semilla shr 29) and $01);
    Semilla:= Semilla xor ((Semilla shr 31) and $01);
  end;
  Result:= Semilla mod Rango;
end;

Se utiliza igual que el Random de toda la vida, y en este caso también hay que acordarse de darle un valor inicial a la semilla. Aquí un ejemplo de como usarlo, y una prueba de que tal funciona:

Código Delphi [-]
var
  i,j,k: integer;
  Str: string;
  X: array[0..255] of Integer;
begin
  FillChar(X, Sizeof(X), 0);
  // Le damos un valor a la semilla
  Semilla:= GetTickCount;
  // Generamos cien mil numeros aletorios
  for i:= 1 to 100000 do
    inc(X[Random2(256)]);
  j:= MAXINT;
  k:= 0;
  // Mostramos de veces que aperece cada numero
  for i:= 0 to 255 do
  begin
    if j > X[i] then j:= X[i];
    if k < X[i] then k:= X[i];
    if i mod 10 = 0then
      Str:= Str + #13;
    Str:= Str +  IntToStr(X[i]) + ',';
  end;
  Str:= Str + #13#13 +
    'El valor mas bajo es: ' + IntToStr(j) + #13 +
    'El valor mas alto es: ' + IntToStr(k);
  // Si funciona bien deben mostrarse valores
  // cercanos para todos los numeros.
  ShowMessage(Str);
end;

Otra forma de generar números "aleatorios" es utilizar un algoritmo de encriptación, donde cada numero es el anterior encriptado. Utilizando un buen algoritmo, AES, MD5, Serpent, etc ... la secuencia sera tan difícil de descifrar, como lo sera romper el algoritmo.
Responder Con Cita