Главная страница
Top.Mail.Ru    Яндекс.Метрика
Текущий архив: 2005.09.11;
Скачать: CL | DM;

Вниз

Выбор наибольшего числа!   Найти похожие ветки 

 
Витёк   (2005-08-12 02:34) [0]

Подскажите пожалуйста, как мне например из 10 чисел выбрать наибольшее! Вот из двух я могу выбрать тут проще простого, а как из 10! Пожалуйста помогите!


 
Andy BitOff ©   (2005-08-12 02:36) [1]

Что значит выбрать? Откуда?
Если на бумаге написано, просто посмотри какое больше.


 
KilkennyCat ©   (2005-08-12 02:44) [2]

пузырьком.

и не жадничай :)


 
KilkennyCat ©   (2005-08-12 02:48) [3]

а давайте поглючим, кто самый заумный код сравнения 10 чисел напишет?


 
SoftX   (2005-08-12 03:21) [4]

Procedure XXX;
var a:array of integer;
var i:integer;
var maxnumber:integer;
begin
Setlength(a,10);
randomize;
for i:=0 to High(a) do
a[i]:=Trunc(Random(MaxInt));

maxnumber:=a[0];
for i:=1 to High(a) do
if a[i]>maxnumber then maxnumber:=a[i];

ShowMessage("Max number="+IntToStr(maxnumber));
end;


 
KilkennyCat ©   (2005-08-12 03:29) [5]

предлагаю такой:

var
 s : TStringList;
 label oshibka;

 function check(const ss : string) : boolean;
 var
    i : integer;
 begin
    for i := 1 to length(ss) do begin
      result := ss[i] in ["0".."9"];
      if not result then exit;
    end;
 end;

begin
 s := TStringList.Create;
 if not check(edit1.text) then goto oshibka;
 s.add(Edit1.Text);
 if not check(edit2.text) then goto oshibka;
 s.add(Edit2.Text);
 if not check(edit3.text) then goto oshibka;
 s.add(Edit3.Text);
 if not check(edit4.text) then goto oshibka;
 s.add(Edit4.Text);
 if not check(edit5.text) then goto oshibka;
 s.add(Edit5.Text);
 if not check(edit6.text) then goto oshibka;
 s.add(Edit6.Text);
 if not check(edit7.text) then goto oshibka;
 s.add(Edit7.Text);
 if not check(edit8.text) then goto oshibka;
 s.add(Edit8.Text);
 if not check(edit9.text) then goto oshibka;
 s.add(Edit9.Text);
 if not check(edit10.text) then goto oshibka;
 s.add(Edit10.Text);
 s.sort;
 showmessage ("наибольшее число: " + s.strings[9] + " не обращайте внимание на последующее сообщение об ошибке");
 oshibka : showmessage("Вы где-то что-то не то ввели. Попробуйте еще раз");
 edit1.text := "";
 edit2.text := "";
 edit3.text := "";
 edit4.text := "";
 edit5.text := "";
 edit6.text := "";
 edit7.text := "";
 edit8.text := "";
 edit9.text := "";
 edit10.text := "";
 s.free;
end;


 
Andy BitOff ©   (2005-08-12 03:33) [6]

KilkennyCat ©   (12.08.05 03:29) [5]

Ну тут ты перестарался, надо было check функцией не оформлять, а прописать явно в каждом условии. Вот тогда...


 
Lamer@fools.ua ©   (2005-08-12 08:25) [7]

>>SoftX   (12.08.05 03:21) [4]

>if a[i]>maxnumber then maxnumber:=a[i];

Автор, вроде как, наибольшее просил, а не наименьшее.

>>KilkennyCat ©   (12.08.05 03:29) [5]

2 > 10
?


 
БарЛог ©   (2005-08-12 08:27) [8]

Переводим в двоичную систему. Идем от старшего бита и сравниваем на равно/не равно. При первом неравенстве то число, где 1, больше.

Код писАть лень =)

ЗЫ Систему счисления можно и не двоичную =) тада алгоритм чуток изменить придется.


 
begin...end ©   (2005-08-12 08:34) [9]

> Lamer@fools.ua ©   (12.08.05 08:25) [7]

> Автор, вроде как, наибольшее просил, а не наименьшее.

Там, вроде как, наибольшее и находится.


 
tttyu ©   (2005-08-12 08:48) [10]

for Ct1:=0 to 9 do begin
if ChkValue<WArray[ct1] then break else
begin
ChkError:=ChkError+1;
min1:=ChkValue;
end;
end;
if chkerror=10 then begin
ShowMessage(Inttostr(min1));
break;
end;
 end;
Ограничение на 9-просто так


 
TUser ©   (2005-08-12 08:51) [11]

> а давайте поглючим, кто самый заумный код сравнения 10 чисел напишет?

Вот поиск 10-го (по порядку) числа из 10. Время - логарифмическое. Не тестировал, но принцип понятен.

var A: array [0..9] of integer;

function Find10: integer;

function F (S, E: byte): integer;
var i, j, m: integer;
begin
  if S = E then
    result:=S
    else begin
      i:=S; j:=E;
      repeat
        m:=(i + j) shr 1;
        m:=A[m];
        while A[i] < m do inc (i);
        while A[j] > m do dec (j);
        if i < j then begin
          m:=A[i]; A[i]:=A[j]; A[j]:=m;
          end;
      until i >= j;
      result:=F (i,E);
    end;
end;

begin
 result:=F (0,9);
end;


 
Gero ©   (2005-08-12 08:58) [12]


if (a1 > a2) and (a1 > a3) and (a1 > a4) and (a1 > a5) and (a1 > a6) and (a1 > a7) and (a1 > a8) and (a1 > a9) and (a1 > a10) then
Result := a1
else if (a2 > a1) and (a2 > a3) and (a2 > a4) and (a2 > a5) and (a2 > a6) and (a2 > a7) and (a2 > a8) and (a2 > a9) and (a2 > a20) then
Result := a2
else if (a3 > a1) and (a3 > a2) and (a3 > a4) and (a3 > a5) and (a3 > a6) and (a3 > a7) and (a3 > a8) and (a3 > a9) and (a3 > a30) then
Result := a3
else if (a4 > a1) and (a4 > a2) and (a4 > a3) and (a4 > a5) and (a4 > a6) and (a4 > a7) and (a4 > a8) and (a4 > a9) and (a4 > a40) then
Result := a4
else if (a5 > a1) and (a5 > a2) and (a5 > a3) and (a5 > a4) and (a5 > a6) and (a5 > a7) and (a5 > a8) and (a5 > a9) and (a5 > a50) then
Result := a5
else if (a6 > a1) and (a6 > a2) and (a6 > a3) and (a6 > a4) and (a6 > a5) and (a6 > a7) and (a6 > a8) and (a6 > a9) and (a6 > a60) then
Result := a6
else if (a7 > a1) and (a7 > a2) and (a7 > a3) and (a7 > a4) and (a7 > a5) and (a7 > a6) and (a7 > a8) and (a7 > a9) and (a7 > a70) then
Result := a7
else if (a8 > a1) and (a8 > a2) and (a8 > a3) and (a8 > a4) and (a8 > a5) and (a8 > a6) and (a8 > a7) and (a8 > a9) and (a8 > a80) then
Result := a8
else if (a9 > a1) and (a9 > a2) and (a9 > a3) and (a9 > a4) and (a9 > a5) and (a9 > a6) and (a9 > a7) and (a9 > a8) and (a9 > a90) then
Result := a9
else if (a10 > a1) and (a10 > a2) and (a10 > a3) and (a10 > a4) and (a10 > a5) and (a10 > a6) and (a10 > a7) and (a10 > a8) and (a10 > a9) then
Result := a10
else
Result := ERROR;


 
tttyu ©   (2005-08-12 10:49) [13]


> Gero

Стильно!


 
Lamer@fools.ua ©   (2005-08-12 10:50) [14]

>>begin...end ©   (12.08.05 08:34) [9]

А, ну да. Это я ступил.


 
Igorek ©   (2005-08-12 10:52) [15]

Если массив 10 чисел отсортирован, то берем соотв. первое или последнее.


 
ocean ©   (2005-08-12 11:49) [16]

unit Math;
var iArray[1..10] : Array of Integer;
...
Result := MaxIntValue(iArray);

> а давайте поглючим, кто самый заумный код сравнения 10 чисел напишет?
{ А вдруг там 2 одинаковых максимальных числа? }
... (в лом)


 
ocean ©   (2005-08-12 11:50) [17]

пардон, заболтался:
uses unit Math;


 
Думкин ©   (2005-08-12 11:55) [18]


> [17] ocean ©   (12.08.05 11:50)

Колбасит, Михалыч? (с)


 
KilkennyCat ©   (2005-08-12 11:55) [19]


> [12] Gero ©   (12.08.05 08:58)


Блеск!
:)


 
Antonn ©   (2005-08-12 12:00) [20]

Разрешите добавить свои 10 копеек:)

function MaxIsTenChisel(_i1,_i2,_i3,_i4,_i5,_i6,_i7,_i8,_i9,_i10:real):real;
var _massiv:array[0..9] of real; _max_tmp:real; i:integer;
begin
_massiv[0]:=_i1;_massiv[1]:=_i2;
_massiv[2]:=_i3;_massiv[3]:=_i4;
_massiv[4]:=_i5;_massiv[5]:=_i6;
_massiv[6]:=_i7;_massiv[7]:=_i8;
_massiv[8]:=_i9;_massiv[9]:=_i10;
_max_tmp:=_massiv[0];
for i:=0 to 9 do
if _massiv[i]> _max_tmp then _max_tmp:=_massiv[i];
result:=_max_tmp;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
label1.caption:=floattostr(MaxIsTenChisel(10,20,30,40,45,60,80,10,20,80.2));
end;


 
KilkennyCat ©   (2005-08-12 12:27) [21]

интересно, можно ли применить строковые Soundные функции?


 
guav ©   (2005-08-13 00:42) [22]

http://kladovka.net.ru/index.cgi?pid=list&rid=213


 
Витёк   (2005-08-13 02:11) [23]

Огромное спасибо всем!!! Вы мне очень ПОМОГЛИ!!!!!!!!!!!


 
Труп Васи Доброго ©   (2005-08-13 10:50) [24]

Смотри примеры из стандартной поставки Дельфей, там есть три алгоритма сортировки массива, выбирай на вкус.


 
SergP.   (2005-08-13 11:55) [25]


> Gero ©   (12.08.05 08:58) [12]
>
> if (a1 > a2) and (a1 > a3) and (a1 > a4) and (a1 > a5) and
> (a1 > a6) and (a1 > a7) and (a1 > a8) and (a1 > a9) and
> (a1 > a10) then
> Result := a1
> else if (a2 > a1) and (a2 > a3) and (a2 > a4) and (a2 >
> a5) and (a2 > a6) and (a2 > a7) and (a2 > a8) and (a2 >
> a9) and (a2 > a20) then
> Result := a2
> else if (a3 > a1) and (a3 > a2) and (a3 > a4) and (a3 >
> a5) and (a3 > a6) and (a3 > a7) and (a3 > a8) and (a3 >
> a9) and (a3 > a30) then
> Result := a3
> else if (a4 > a1) and (a4 > a2) and (a4 > a3) and (a4 >
> a5) and (a4 > a6) and (a4 > a7) and (a4 > a8) and (a4 >
> a9) and (a4 > a40) then
> Result := a4
> else if (a5 > a1) and (a5 > a2) and (a5 > a3) and (a5 >
> a4) and (a5 > a6) and (a5 > a7) and (a5 > a8) and (a5 >
> a9) and (a5 > a50) then
> Result := a5
> else if (a6 > a1) and (a6 > a2) and (a6 > a3) and (a6 >
> a4) and (a6 > a5) and (a6 > a7) and (a6 > a8) and (a6 >
> a9) and (a6 > a60) then
> Result := a6
> else if (a7 > a1) and (a7 > a2) and (a7 > a3) and (a7 >
> a4) and (a7 > a5) and (a7 > a6) and (a7 > a8) and (a7 >
> a9) and (a7 > a70) then
> Result := a7
> else if (a8 > a1) and (a8 > a2) and (a8 > a3) and (a8 >
> a4) and (a8 > a5) and (a8 > a6) and (a8 > a7) and (a8 >
> a9) and (a8 > a80) then
> Result := a8
> else if (a9 > a1) and (a9 > a2) and (a9 > a3) and (a9 >
> a4) and (a9 > a5) and (a9 > a6) and (a9 > a7) and (a9 >
> a8) and (a9 > a90) then
> Result := a9
> else if (a10 > a1) and (a10 > a2) and (a10 > a3) and (a10
> > a4) and (a10 > a5) and (a10 > a6) and (a10 > a7) and (a10
> > a8) and (a10 > a9) then
> Result := a10
> else
> Result := ERROR;


Попытался оптимизировать. :-)))

if (a1 > a2) and (a1 > a3) and (a1 > a4) and (a1 > a5) and
(a1 > a6) and (a1 > a7) and (a1 > a8) and (a1 > a9) and
(a1 > a10) then
Result := a1
else if (a2 > a3) and (a2 > a4) and (a2 > a5) and (a2 > a6) and (a2 > a7) and (a2 > a8) and (a2 >
a9) and (a2 > a10) then
Result := a2
else if (a3 > a4) and (a3 > a5) and (a3 > a6) and (a3 > a7) and (a3 > a8) and (a3 > a9) and (a3 > a10) then
Result := a3
else if (a4 > a5) and (a4 > a6) and (a4 > a7) and (a4 > a8) and (a4 > a9) and (a4 > a10) then
Result := a4
else if (a5 > a6) and (a5 > a7) and (a5 > a8) and (a5 >
a9) and (a5 > a10) then
Result := a5
else if(a6 > a7) and (a6 > a8) and (a6 >  a9) and (a6 > a10) then
Result := a6
else if (a7 > a8) and (a7 > a9) and (a7 > a70) then
Result := a7
else if (a8 > a9) and (a8 > a10) then
Result := a8
else if (a9 > a10) then
Result := a9
else Result := a10;


 
TStas ©   (2005-08-13 12:23) [26]

А я бы их в TList поместил, точнее указатели на них и сортировал его. Врядли самому удастся придумать лучший способ сортировки, чем у TList"а.


 
GuAV ©   (2005-08-13 13:46) [27]


> Попытался оптимизировать. :-)))

Самый оптимальный код у меня. см. ссылку 22


 
Lamer@fools.ua ©   (2005-08-13 17:29) [28]

>>GuAV ©   (13.08.05 13:46) [27]

>Самый оптимальный код у меня

По какому критерию?

По критерию минимизации предпринятых усилий для реализации у меня самый оптимальный:
Math.MaxValue() либо Math.MaxIntValue().


 
TUser ©   (2005-08-13 17:56) [29]

> По какому критерию?

Очевидно, что по требованиям данной ветки.


 
Lamer@fools.ua ©   (2005-08-13 18:20) [30]

>>TUser ©   (13.08.05 17:56) [29]

Кому очевидно?


 
TUser ©   (2005-08-13 18:28) [31]

> Кому очевидно?

А вы этот код смотрели?


 
NikotiN ©   (2005-08-13 19:59) [32]

max(max(...),max(...))
глупо и просто.


 
Lamer@fools.ua ©   (2005-08-13 23:47) [33]

>>TUser ©   (13.08.05 18:28) [31]

Смотрел.


 
jack128 ©   (2005-08-14 00:30) [34]

NikotiN ©   (13.08.05 19:59) [32]
max(max(...),max(...))


Точно!!

function ExecAndWait(const ExeName, Params: string; out ExitCode: Cardinal; Timeout: Cardinal = MaxInt): boolean;
var
 p: PChar;
 sui: TStartupInfo;
 pi: TProcessInformation;
begin
 ZeroMemory(@sui, SizeOf(sui));
 sui.cb := SizeOf(sui);
 if ExeName = "" then
   P := nil
 else
   P := PChar(ExeName);
 Win32Check(CreateProcess(p, PChar(Params), nil, nil, False, 0, nil,
   nil, sui, pi));
 try
   CloseHandle(pi.hThread);
   Result := WaitForSingleObject(pi.hProcess, Timeout) = WAIT_OBJECT_0;
   if Result then
     Win32Check(GetExitCodeProcess(pi.hProcess, ExitCode));
 finally
   CloseHandle(pi.hProcess);
 end;
end;


function FindMax(Arr: array of Integer): Integer;
   const
     ProgramText =
   "  function Max(i, j: Integer): Integer;"#13#10+
   "  begin"#13#10+
   "    if i > j then"#13#10+
   "      Result := i"#13#10+
   "    else"#13#10+
   "      Result := j;"#13#10+
   "  end;"#13#10+
   ""#13#10+
   "begin"#13#10+
   "  Halt(%s)"#13#10+
   "end.";
 function StrMax(const s1, s2: string): string;
 begin
   Result := "Max(" + s1 + ", " + s2 + ")";
 end;
var
 s: string;
 f: TextFile;
 i: Integer;
 flag: boolean;
begin
 s := IntToStr(Arr[Low(Arr)]);
 for i := low(Arr) + 1 to high(Arr) do
   s := StrMax(s, IntToStr(Arr[i]));
 AssignFile(f, ExtractFilePath(ParamStr(0)) + "calc.dpr");
 ReWrite(f);
 try
   Write(f, Format(ProgramText, [s]));
 finally
   CloseFile(f);
 end;
 flag := ExecAndWait("", "dcc32.exe "" + ExtractFilePath(ParamStr(0)) + "calc.dpr"", Cardinal(Result));
 if flag  then
   flag := ExecAndWait(ExtractFilePath(ParamStr(0)) + "calc.exe", "", Cardinal(Result));
 if not flag then
   raise Exception.Create("Не могу найти ответ.  Очень сложная задача :-(");
end;


 
guav ©   (2005-08-15 15:54) [35]

Lamer@fools.ua ©   (13.08.05 17:29) [28]

> По какому критерию?

Минимум зависимостей.
IMHO, самый быстрый алгоритм (из предложенных).



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

Текущий архив: 2005.09.11;
Скачать: CL | DM;

Наверх




Память: 0.57 MB
Время: 0.03 c
1-1124370115
Aleksandr.
2005-08-18 17:01
2005.09.11
Почему Excel не понимает формат даты?


3-1122795559
Девушка
2005-07-31 11:39
2005.09.11
IBX - добавление записи, вызов генератора


2-1123456671
TIGOS
2005-08-08 03:17
2005.09.11
Дурацкий вопрос. По-поводу конвертирования текст -> в Real


14-1124259182
REA
2005-08-17 10:13
2005.09.11
1C защита


3-1122743231
Andy Nortsov
2005-07-30 21:07
2005.09.11
проблемы работы с excel через ado