![]() |
| ||
|
|
Новости |
Поиск |
FAQ |
Статьи |
Книги |
Новости VCL
| | Форумы ЧАТ |
Орешник |
|
| |||
| |||
« предыдущая ветвь | форум | следующая ветвь »
Оптимизация кода [D7, XP]
--------- © (2006-10-26 23:40:00)Люди помогите!!!!! Как мне это лучше сделать, чтоб машина не гнала бесу..тормозит по чёрному!!!!
вот код:
procedure TForm1.rasbr;
var
c_e: array [0..15] of Integer;
x, xx: Integer;
zxc: Boolean;
begin
for xx := 0 to 15 do
begin
zxc := False;
Randomize;
x := Random(15);
repeat
if xx=0 then
begin
c_e[xx] := x;
zxc := True;
end;
if xx=1 then
if c_e[0]<>x then
begin
c_e[xx] := x;
zxc := True;
Beep;
end else
begin
Randomize;
x := Random(15);
zxc := False;
end;
if xx=2 then
if (c_e[0]<>x)and(c_e[1]<>x) then
begin
c_e[xx] := x;
zxc := True;
Beep;
end else
begin
Randomize;
x := Random(15);
zxc := False;
end;
if xx=3 then
if (c_e[0]<>x)and(c_e[1]<>x)and(c_e[2]<>x) then
begin
c_e[xx] := x;
zxc := True;
Beep;
end else
begin
Randomize;
x := Random(15);
zxc := False;
end;
if xx=4 then
if (c_e[0]<>x)and(c_e[1]<>x)and(c_e[2]<>x)and(c_e[3]<>x) then
begin
c_e[xx] := x;
zxc := True;
Beep;
end else
begin
Randomize;
x := Random(15);
zxc := False;
end;
if xx=5 then
if (c_e[0]<>x)and(c_e[1]<>x)and(c_e[2]<>x)and(c_e[3]<>x)
and(c_e[4]<>x) then
begin
c_e[xx] := x;
zxc := True;
Beep;
end else
begin
Randomize;
x := Random(15);
zxc := False;
end;
if xx=6 then
if (c_e[0]<>x)and(c_e[1]<>x)and(c_e[2]<>x)and(c_e[3]<>x)
and(c_e[4]<>x)and(c_e[5]<>x) then
begin
c_e[xx] := x;
zxc := True;
Beep;
end else
begin
Randomize;
x := Random(15);
zxc := False;
end;
if xx=7 then
if (c_e[0]<>x)and(c_e[1]<>x)and(c_e[2]<>x)and(c_e[3]<>x)
and(c_e[4]<>x)and(c_e[5]<>x)and(c_e[6]<>x) then
begin
c_e[xx] := x;
zxc := True;
Beep;
end else
begin
Randomize;
x := Random(15);
zxc := False;
end;
if xx=8 then
if (c_e[0]<>x)and(c_e[1]<>x)and(c_e[2]<>x)and(c_e[3]<>x)
and(c_e[4]<>x)and(c_e[5]<>x)and(c_e[6]<>x)and(c_e[7]<>x) then
begin
c_e[xx] := x;
zxc := True;
Beep;
end else
begin
Randomize;
x := Random(15);
zxc := False;
end;
if xx=9 then
if (c_e[0]<>x)and(c_e[1]<>x)and(c_e[2]<>x)and(c_e[3]<>x)
and(c_e[4]<>x)and(c_e[5]<>x)and(c_e[6]<>x)and(c_e[7]<>x)
and(c_e[8]<>x) then
begin
c_e[xx] := x;
zxc := True;
Beep;
end else
begin
Randomize;
x := Random(15);
zxc := False;
end;
if xx=10 then
if (c_e[0]<>x)and(c_e[1]<>x)and(c_e[2]<>x)and(c_e[3]<>x)
and(c_e[4]<>x)and(c_e[5]<>x)and(c_e[6]<>x)and(c_e[7]<>x)
and(c_e[8]<>x)and(c_e[9]<>x) then
begin
c_e[xx] := x;
zxc := True;
Beep;
end else
begin
Randomize;
x := Random(15);
zxc := False;
end;
if xx=11 then
if (c_e[0]<>x)and(c_e[1]<>x)and(c_e[2]<>x)and(c_e[3]<>x)
and(c_e[4]<>x)and(c_e[5]<>x)and(c_e[6]<>x)and(c_e[7]<>x)
and(c_e[8]<>x)and(c_e[9]<>x)and(c_e[10]<>x) then
begin
c_e[xx] := x;
zxc := True;
Beep;
end else
begin
Randomize;
x := Random(15);
zxc := False;
end;
if xx=12 then
if (c_e[0]<>x)and(c_e[1]<>x)and(c_e[2]<>x)and(c_e[3]<>x)
and(c_e[4]<>x)and(c_e[5]<>x)and(c_e[6]<>x)and(c_e[7]<>x)
and(c_e[8]<>x)and(c_e[9]<>x)and(c_e[10]<>x)and(c_e[11]<>x) then
begin
c_e[xx] := x;
zxc := True;
Beep;
end else
begin
Randomize;
x := Random(15);
zxc := False;
end;
if xx=13 then
if (c_e[0]<>x)and(c_e[1]<>x)and(c_e[2]<>x)and(c_e[3]<>x)
and(c_e[4]<>x)and(c_e[5]<>x)and(c_e[6]<>x)and(c_e[7]<>x)
and(c_e[8]<>x)and(c_e[9]<>x)and(c_e[10]<>x)and(c_e[11]<>x)
and(c_e[12]<>x) then
begin
c_e[xx] := x;
zxc := True;
Beep;
end else
begin
Randomize;
x := Random(15);
zxc := False;
end;
if xx=14 then
if (c_e[0]<>x)and(c_e[1]<>x)and(c_e[2]<>x)and(c_e[3]<>x)
and(c_e[4]<>x)and(c_e[5]<>x)and(c_e[6]<>x)and(c_e[7]<>x)
and(c_e[8]<>x)and(c_e[9]<>x)and(c_e[10]<>x)and(c_e[11]<>x)
and(c_e[12]<>x)and(c_e[13]<>x) then
begin
c_e[xx] := x;
zxc := True;
Beep;
end else
begin
Randomize;
x := Random(15);
zxc := False;
end;
if xx=15 then
if (c_e[0]<>x)and(c_e[1]<>x)and(c_e[2]<>x)and(c_e[3]<>x)
and(c_e[4]<>x)and(c_e[5]<>x)and(c_e[6]<>x)and(c_e[7]<>x)
and(c_e[8]<>x)and(c_e[9]<>x)and(c_e[10]<>x)and(c_e[11]<>x)
and(c_e[12]<>x)and(c_e[13]<>x)and(c_e[14]<>x) then
begin
c_e[xx] := x;
zxc := True;
Beep;
end else
begin
Randomize;
x := Random(15);
zxc := False;
end;
until zxc = True;
end;
end;
Gydvin (2006-10-27 19:29:00) [1]Ну я тож попробую свой вариант выкинуть, как-то делал.
Сколько угодно цифр (edit1)
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Edit1: TEdit;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
function prov(var r: array of integer; num, i: integer): boolean; /// i?iaa?ea ia iiaoi?
var
x, a: integer;
begin
result := false;
for x := 0 to i - 1 do
if r[x] = num then begin
result := true;
exit;
end;
end;
var
r: array of integer;
x, i, a: integer;
begin
try
i := Strtoint(edit1.Text) + 1;
except
Showmessage('Error integer');
end;
setlength(r, i);
randomize;
/// generate
for x := 0 to i - 1 do begin
a := random(i);
while (prov(r, a, x)) do a := random(i);
r[x] := a;
end;
///write
memo1.Clear;
for x := 0 to i - 1 do memo1.Lines.Add(inttostr(r[x]))
end;
end.
DevilDevil (2006-10-27 16:32:00) [2]
... if not c_b[X] then ...
DevilDevil (2006-10-27 16:30:00) [3]предлагаю не самый быстрый, но вполне понятный и компактный способ:
const
COUNT = 16;
procedure TForm1.rasbr;
var
c_e: array [0..COUNT-1] of Integer;
c_b: array [0..COUNT-1] of boolean;
X, i : integer;
begin
Randomize;
ZeroMemory(c_b, COUNT);
for i := 0 to COUNT-1 do
repeat
X := random(COUNT);
if not c_b then
begin
c_e[i] := X;
c_b[X] := true;
break;
end;
until false;
end;
ASoft (2006-10-27 13:23:00) [4]фактор псевдо-случайности
первый раз слышу... ;)
Krants (2006-10-27 13:06:00) [5]Я понял!, проблема даже не в коде, это все из-за процедуры Beep!!! поменяй динамик, должно помочь! Серьезно!
Loginov Dmitry (2006-10-27 12:53:00) [6]> кто-нить скажет, для чего у автора сабжа в приведенном листинге
> постоянно вызывается Randomize?
Это чтоб исключить фактор псевдо-случайности, который обычно проявляется при использовании Random %))
Megabyte (2006-10-27 12:12:00) [7]<offtop>В орешник код будет отправлен?</offtop>
ASoft (2006-10-27 07:55:00) [8]кто-нить скажет, для чего у автора сабжа в приведенном листинге постоянно вызывается Randomize? Кажись, достаточно в onCreate один раз ето вызвать.... Или я чего-то не знаю, касаемо этого?
Don Nikola (2006-10-27 06:26:00) [9]>мне нужно сгенерировать 16 чисел в разброс так, чтоб они не повторялись
Имею вопрос не очень по теме, но сходной тематики.
Есть код вида:
---
add ax,45 //числа колдунские
rol ax,1 //числа колдунские
xor ax,2927 //числа колдунские
---
Так вот, такой код выдает последовательность из 65536 неповторяющихся значений, то есть перебирает все возможные варианты, причем выглядит результат весьма рендомно. Правильных колдунских чисел не очень много, но хватает.
Собственно вопрос: как найти эти числа для 32бит? Для 8/16 это не проблема, немного оптимизированный брутфорс и все находится. Что это вообще за метод рендома, может он давно известен?
------------ (2006-10-27 00:32:00) [10]спасибо всё пашет!!!!!!!!!!!1 :):):):)
DrPass (2006-10-27 00:28:00) [11]Удалено модератором
Ketmar (2006-10-27 00:26:00) [12]>[16] DrPass(c) 27-Oct-2006, 00:10
>У этого кода еще вторая функция есть - ускорить приход
>Антихриста
тс-с-с! это тайна!
>[18] ProgRAMmer Dimonych(c) 27-Oct-2006, 00:12
>Вообще, чего-то у меня с идеями туговато...
отчего же "туговато"? очень верный подход. часто зовётся "задача о перемешивании колоды карт". решается в том числе и таким путём. так что если сам придумал -- радуйся. %-)
------------ (2006-10-27 00:20:00) [13]Удалено модератором
DrPass (2006-10-27 00:20:00) [14]Удалено модератором
Gero (2006-10-27 00:18:00) [15]А вобще парень без комплексов. Я бы такой код постеснялся кому-то показывать.
------------ (2006-10-27 00:16:00) [16]ProgRAMmer Dimonych вариант...
DrPass (2006-10-27 00:16:00) [17]
> ------------ (27.10.06 00:03) [9]
Это понятно... Но какова задумка, блин...
Ладно, не мучайся
randomize;
for i:= 0 to 15 do c_e[i]:= -1; //функцией fillchar пугать тебя не будем
k:= 0;
for i:= 0 to 15 do
begin
j:= random(16) + 1;//сколько - не особо важно, лишь бы случайно
repeat
if k = 15 then k:= 0 else k:= k + 1;
if c_e[k] = -1 then j:= j - 1;
until j = 0;
c_e[k]:= i;
end;
Anatoly Podgoretsky (2006-10-27 00:13:00) [18]И 2^64 за остальное.
ProgRAMmer Dimonych (2006-10-27 00:12:00) [19]Вообще, чего-то у меня с идеями туговато...
Вариант такой: заполняем массив числами, равными номерам элементов, т.е.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
В цикле...
Дальше начинаем случайно выбирать элемент и менять его местами со случайно выбранным другим.
Пока лучше ничего в голову не пришло :(
Gero (2006-10-27 00:12:00) [20]Жесть!