Главная страница
    Top.Mail.Ru    Яндекс.Метрика
Форум: "Начинающим";
Текущий архив: 2006.11.12;
Скачать: [xml.tar.bz2];

Вниз

Оптимизация кода   Найти похожие ветки 

 
---------   (2006-10-26 23:40) [0]

Люди помогите!!!!! Как мне это лучше сделать, чтоб машина не гнала бесу..тормозит по чёрному!!!!

вот код:

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;


 
Ketmar ©   (2006-10-26 23:48) [1]

лучше всего или провести ритуал посвящения машины Сатане (тогда машина не будет бесов бояться), или не вызывать бесов без достаточного опыта в саммонинге.


 
Anatoly Podgoretsky ©   (2006-10-26 23:51) [2]

Много буков, что бы разбираться, а какая часть тормозит, померь и скажи нам, тогда поможем.

Кстати ты слышал, что Паскаль (Дельфи) поддерживают оператор CASE?


 
DrPass ©   (2006-10-26 23:51) [3]

На самом деле такой код мог родиться только в черном разуме адепта, прошедшего как минимум третий круг инициации. Я даже у себя за столом, в нескольких тысяч км от сервера "Мастером", ощущаю исходящее от него Зло


 
DrPass ©   (2006-10-26 23:52) [4]


> Мастером

= Мастеров. Руки дрожат и плохо слушаются


 
Anatoly Podgoretsky ©   (2006-10-26 23:53) [5]

Не это черный сотона или ССЗБ или что еще хуже, даже называть не хочется.


 
------------   (2006-10-26 23:55) [6]

1ое число есть а дальше он так думать начинает


 
Anatoly Podgoretsky ©   (2006-10-26 23:57) [7]

Обязательно дождись второго.


 
Kolan ©   (2006-10-27 00:00) [8]

> Как мне это лучше сделать

Выделить все и удалить.


 
------------   (2006-10-27 00:03) [9]

2го просто не дождёшся..мне нужно сгенерировать 16 чисел в разброс так, чтоб они не повторялись


 
Ketmar ©   (2006-10-27 00:04) [10]

а-а-а! я осилил код! кто догадался, для чего он? без анализа? интуитивно? нет, в цитатник, однозначно. только жаль, что всего 16 чисел надо. лучше бы 256. или 1024.


 
Ketmar ©   (2006-10-27 00:05) [11]

тьфу. автор разрушил всю интригу... %-(((


 
ProgRAMmer Dimonych ©   (2006-10-27 00:06) [12]

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

Я бы эту проверку в отдельную функцию вынес:

function IsAllFalse(Count,x:Integer):Boolean;
var
i:Integer;
begin
Result:=True;
for i:=0 to Count-1 do
 if c_e[i]=x then
  Result:=False;
end;


 
Ketmar ©   (2006-10-27 00:06) [13]

ах, да. +1 за трудолюбивость. -16384 за сам код.


 
Ketmar ©   (2006-10-27 00:07) [14]

>[12] ProgRAMmer Dimonych(c) 27-Oct-2006, 00:06
>Я бы эту проверку в отдельную функцию вынес:
нафига?


 
ProgRAMmer Dimonych ©   (2006-10-27 00:08) [15]

> [14]
Действительно... (С) Староконь


 
DrPass ©   (2006-10-27 00:10) [16]


> Ketmar ©   (27.10.06 00:04) [10]

У этого кода еще вторая функция есть - ускорить приход Антихриста


 
Gero ©   (2006-10-27 00:12) [17]

Жесть!


 
ProgRAMmer Dimonych ©   (2006-10-27 00:12) [18]

Вообще, чего-то у меня с идеями туговато...

Вариант такой: заполняем массив числами, равными номерам элементов, т.е.

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

В цикле...

Дальше начинаем случайно выбирать элемент и менять его местами со случайно выбранным другим.

Пока лучше ничего в голову не пришло :(


 
Anatoly Podgoretsky ©   (2006-10-27 00:13) [19]

И 2^64 за остальное.


 
DrPass ©   (2006-10-27 00:16) [20]


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


 
------------   (2006-10-27 00:16) [21]

ProgRAMmer Dimonych  вариант...


 
Gero ©   (2006-10-27 00:18) [22]

А вобще парень без комплексов. Я бы такой код постеснялся кому-то показывать.


 
DrPass ©   (2006-10-27 00:20) [23]

Удалено модератором


 
------------   (2006-10-27 00:20) [24]

Удалено модератором


 
Ketmar ©   (2006-10-27 00:26) [25]

>[16] DrPass(c) 27-Oct-2006, 00:10
>У этого кода еще вторая функция есть - ускорить приход
>Антихриста
тс-с-с! это тайна!

>[18] ProgRAMmer Dimonych(c) 27-Oct-2006, 00:12
>Вообще, чего-то у меня с идеями туговато...
отчего же "туговато"? очень верный подход. часто зовётся "задача о перемешивании колоды карт". решается в том числе и таким путём. так что если сам придумал -- радуйся. %-)


 
DrPass ©   (2006-10-27 00:28) [26]

Удалено модератором


 
------------   (2006-10-27 00:32) [27]

спасибо всё пашет!!!!!!!!!!!1    :):):):)


 
Don Nikola ©   (2006-10-27 06:26) [28]

>мне нужно сгенерировать 16 чисел в разброс так, чтоб они не повторялись

Имею вопрос не очень по теме, но сходной тематики.
Есть код вида:
---
add ax,45 //числа колдунские
rol ax,1 //числа колдунские
xor ax,2927 //числа колдунские
---
Так вот, такой код выдает последовательность из 65536 неповторяющихся значений, то есть перебирает все возможные варианты, причем выглядит результат весьма рендомно. Правильных колдунских чисел не очень много, но хватает.
Собственно вопрос: как найти эти числа для 32бит? Для 8/16 это не проблема, немного оптимизированный брутфорс и все находится. Что это вообще за метод рендома, может он давно известен?


 
ASoft   (2006-10-27 07:55) [29]

кто-нить скажет, для чего у автора сабжа в приведенном листинге постоянно вызывается Randomize? Кажись, достаточно в onCreate один раз ето вызвать.... Или я чего-то не знаю, касаемо этого?


 
Megabyte ©   (2006-10-27 12:12) [30]

<offtop>В орешник код будет отправлен?</offtop>


 
Loginov Dmitry ©   (2006-10-27 12:53) [31]

> кто-нить скажет, для чего у автора сабжа в приведенном листинге
> постоянно вызывается Randomize?


Это чтоб исключить фактор псевдо-случайности, который обычно проявляется при использовании Random %))


 
Krants   (2006-10-27 13:06) [32]

Я понял!, проблема даже не в коде, это все из-за процедуры Beep!!! поменяй динамик, должно помочь! Серьезно!


 
ASoft   (2006-10-27 13:23) [33]

фактор псевдо-случайности
первый раз слышу... ;)


 
DevilDevil ©   (2006-10-27 16:30) [34]

предлагаю не самый быстрый, но вполне понятный и компактный способ:

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;


 
DevilDevil ©   (2006-10-27 16:32) [35]

... if not c_b[X] then ...


 
Gydvin ©   (2006-10-27 19:29) [36]

Ну я тож попробую свой вариант выкинуть, как-то делал.

Сколько угодно цифр (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.



Страницы: 1 вся ветка

Форум: "Начинающим";
Текущий архив: 2006.11.12;
Скачать: [xml.tar.bz2];

Наверх





Память: 0.57 MB
Время: 0.037 c
11-1138000587
Barloggg
2006-01-23 10:16
2006.11.12
История. MMTimer!!!


15-1161153013
LaidBack
2006-10-18 10:30
2006.11.12
Можно застрелиться...


2-1161187684
Благодарный слушатель
2006-10-18 20:08
2006.11.12
Помогите работать с TImage


2-1161715996
TStas
2006-10-24 22:53
2006.11.12
Как программно сделать файл ReadOnly?


4-1151225686
Экспериментатор
2006-06-25 12:54
2006.11.12
Перезапуск оболочки explorer.exe





Afrikaans Albanian Arabic Armenian Azerbaijani Basque Belarusian Bulgarian Catalan Chinese (Simplified) Chinese (Traditional) Croatian Czech Danish Dutch English Estonian Filipino Finnish French
Galician Georgian German Greek Haitian Creole Hebrew Hindi Hungarian Icelandic Indonesian Irish Italian Japanese Korean Latvian Lithuanian Macedonian Malay Maltese Norwegian
Persian Polish Portuguese Romanian Russian Serbian Slovak Slovenian Spanish Swahili Swedish Thai Turkish Ukrainian Urdu Vietnamese Welsh Yiddish Bengali Bosnian
Cebuano Esperanto Gujarati Hausa Hmong Igbo Javanese Kannada Khmer Lao Latin Maori Marathi Mongolian Nepali Punjabi Somali Tamil Telugu Yoruba
Zulu
Английский Французский Немецкий Итальянский Португальский Русский Испанский