Как найти два наибольших элемента массива

Помогите. Задача описана в первых комментариях кода.
Никак не могу понять, как найти два максимальных элемента массива и их индекс.
Например, массив у нас пусть будет {10, -2, 3, 9, 7, 6, 2, -10, 9, 10}
Нужно чтобы показало элементы A[0] = 10 и A[9] = 10.

И ещё, поясните почему рандом постоянно генерирует одни и те же значения при компиляции.

// Задача: заполнить массив из 10 элементов случайными числами 
// в интервале [-10..10] и найти в нем 
// два максимальных элемента и их номера. 
#include <iostream>
#include <cstdlib>
using namespace std; 

// Функция, возвращает случайное число в заданном диапазоне [a,b].
int random (int min, int max)
{
    max++;
    return abs(rand()%(max-min))+min;
}


int main()
{
    const int N = 10;
    int A[N], i, element, first_max_element, second_max_element, random_number_is, iMAX1, iMAX2;
    
    cout<<"Enter 5 elements of array.nn";
    
    // Заполняем массив рандомными числами.
    for(i =0; i<N; i++)
    {
        random_number_is = random(-10,10);
        A[i] = {random_number_is};
        cout<<"Random A["<<i<<"]: "<< random_number_is<<"n";       
    }
    
    // Вычисляем первый максимальный элемент массива.
    first_max_element = A[0];
    iMAX1 = 0;
    for(i=0; i<N; i++)
    {
        if(A[i] > first_max_element)
        {
            first_max_element = A[i];
            iMAX1 = i;      
        }   
    }

    // Вычисляем второй максимальный элемент массива.
    second_max_element = A[0];
    iMAX2 = 0;
    for(i=0; i<N; i++)
    {
        if(A[i] > second_max_element && iMAX1 != iMAX2)
        {
            second_max_element = A[i];
            iMAX2 = i;      
        }
    }
    
    cout<<"nFirst max element of array is: "<<"A["<<iMAX1<<"]: "<<first_max_element;
    cout<<"nSecond max element of array is: "<<"A["<<iMAX2<<"]: "<<second_max_element;
}

At first glance, I’d suggest:

function choseBig(myArray) {
  return myArray.sort((a, b) => b - a).slice(0, 2);
}

console.log(choseBig([1, 2, 3, 4, 5, 9]));

To extend the above a little, for example offering the user the option to specify whether the returned values should be the highest numbers, or the lowest numbers, and how many they wish returned, I’d offer the following:

function choseBig(myArray, opts) {
  // 'max':      Boolean,
  //             true:  returns the highest numbers,
  //             false: returns the lowest numbers
  // 'howMany':  Number,
  //             specifies how many numbers to return:
  var settings = {
      'max': true,
      'howMany': 2
    };

  // ensuring we have an Object, otherwise
  // Object.keys( opts ) returns an error:
  opts = opts || {};

  // retrieving the keys of the opts Object, and
  // uses Array.prototype.forEach() to iterate over
  // those keys; 'o' (in the anonymous function) is
  // the array element (the property-name/key) from
  // the array Object keys over which we're iterating:
  Object.keys(opts).forEach(function(o) {

    // updating the settings Object to the new values
    // (if any is specified) to those set in the user-
    // supplied opts Object:
    settings[o] = opts[o];
  });

  // here we first sort the Array, using a numeric sort;
  // using ES2015 Arrow functions. 'a' and 'b' are supplied
  // by Array.prototype.sort() and refer to the current ('a')
  // and next ('b') array-elements. If b - a is less than zero
  // b is moved to a lower index; if a - b is less than zero
  // a is moved to a lower index.
  // Here we use a ternary operator based on whether settings.max
  // is true; if it is true we sort to move the larger number to
  // the lower index; otherwise we sort to move the smaller number
  // to the lower index.
  // Then we slice the resulting array to return the numbers from
  // the 0 index (the first number) to the settings.howMany number
  // (the required length of the array).
  // this is then returned to the calling context.
  return myArray.sort((a, b) => settings.max === true ? b - a : a - b).slice(0, settings.howMany);
}

console.log(choseBig([1, 2, 3, 4, 5, 9], {
  // here we specify to select the largest numbers:
  'max': true,
  // we specify we want the 'top' three numbers:
  'howMany': 3
}));

JS Fiddle demo.

References:

  • Array.prototype.forEach.
  • Array.prototype.slice().
  • Array.prototype.sort().
  • Conditional (Ternary) Operator: statement ? ifTrue : ifFalse
    • How do you use the ? : (conditional) operator in JavaScript?.
  • Object.keys().

John_Pa9JIbHuK

Добрый самаритянин

1107 / 622 / 139

Регистрация: 31.03.2009

Сообщений: 2,567

21.06.2009, 14:16

2

Лучший ответ Сообщение было отмечено Floopy2k как решение

Решение

5)

Pascal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
var
s,s1:string;
a,i,k:integer;
begin
writeln('Ââåäèòå ñòðîêè,ïåðâàÿ ñòðîêà áîëüøå 2-é');
readln(s,s1);
a:=length(s);
For i:=1 to a do
if pos(s[i],s1)>0 then
inc(k);
If k>0 then
writeln('Äà') else
writeln('Íåò');
end.

Добавлено через 4 минуты 5 секунд
6)

Pascal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
var
s,s1:string;
a,i,k:integer;
begin
writeln('Ââåäèòå ñòðîêè,ïåðâàÿ ñòðîêà áîëüøå 2-é');
readln(s,s1);
a:=length(s);
For i:=1 to a do
if pos(s1[i],s)>0 then
inc(k);
If k=a then
writeln('Äà') else
writeln('Íåò');
end.

Добавлено через 1 минуту 24 секунды
7)

Pascal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var
s:string;
a:array [1..100] of integer;
i,count,max:integer;
begin
readln(s);
for i:=1 to length(s) do
begin
if s[i]=' ' then inc(count);
if (s[i]<>' ') and (count>0) then
begin
a[i]:=count;
count:=0;
end;
end;
max:=0;
For i:=1 to 100 do
begin
if a[i]>max then max:=a[i];
end;
writeln('наибольшее количество идущих подряд пробелов ',max);
end.

Добавлено через 5 минут 48 секунд
4)

Pascal
1
2
3
4
5
6
7
8
9
10
var
s:string;
a,i:integer;
begin
readln(s);
a:=length(s);
For i:=a downto 1 do
if (s[i]=' ') and (s[i]=s[i-1]) then delete(s,i,1);
writeln(s);
end.

Добавлено через 22 минуты 1 секунду
9)

Pascal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
var
s,s1,s3:string;
a,i,x,y:integer;
begin
readln(s);
a:=length(s);
For i:=1 to a do
begin
x:=pos(' ',s);
if x>0 then
begin
s1:=copy(s,1,x-1);
delete(s,1,x);
if length(s1)>y then
begin
y:=length(s1);
s3:=s1;
end;
end;
end;
if x=0 then
begin
s1:=copy(s,1,length(s));
if length(s1)>y then s3:=s;
writeln('Слово = ',s3);
end;
end.



2



Форум JScourse

Загрузка…

const
    n = 10; { ×èñëî ýëåìåГ*òîâ Г¬Г*Г±Г±ГЁГўГ* }
var
    arr: array[1..n] of integer;
    i, max1, max2, temp: integer;
begin
    { Г‡Г*ïîëГ*ГїГҐГ¬ Г¬Г*Г±Г±ГЁГў ñëó÷Г*Г©Г*ûìè ýëåìåГ*ГІГ*ìè ГЁ âûâîäèì ГҐГЈГ® Г*Г* ГЅГЄГ°Г*Г* }
    Randomize;
    Write('ÑãåГ*åðèðîâГ*Г*Г*ûé Г¬Г*Г±Г±ГЁГў:');
    for i := 1 to n do begin
        arr[i] := random(100);
        Write(' ', arr[i]);
    end;
    WriteLn;
    
    { Äëÿ Г*Г*Г·Г*Г«Г* ïðåäïîëîæèì, Г·ГІГ® ïåðâûå ýëåìåГ*ГІГ» Г¬Г*Г±Г±ГЁГўГ* ÿâëÿþòñÿ Г¬Г*ГЄГ±ГЁГ¬Г*ëüГ*ûìè }
    { (ÏðåäïîëîãГ*ГҐГІГ±Гї, Г·ГІГ® Гў Г¬Г*Г±Г±ГЁГўГҐ ГҐГ±ГІГј õîòÿ ГЎГ» äâГ* ýëåìåГ*ГІГ*) }
    max1 := arr[1];
    max2 := arr[2];
    { ГЏГіГ±ГІГј áîëüøèé ГЁГ§ Г*ГЁГµ áóäåò Гў max1, Г* ìåГ*ГјГёГЁГ© Гў max2 }
    if max1 < max2 then begin
        temp := max1;
        max1 := max2;
        max2 := temp;
    end;
    
    { ÏðîñìГ*òðèâГ*ГҐГ¬ îñòГ*ГўГёГЁГҐГ±Гї ýëåìåГ*ГІГ» }
    for i := 3 to n do begin
        { Åñëè ñëåäóþùèé ýëåìåГ*ГІ áîëüøå, Г·ГҐГ¬ ìèГ*ГЁГ¬Г*ëüГ*ûé ГЁГ§ óæå Г§Г*ïîìГ*ГҐГ*Г*ûõ, Г§Г*ïîìèГ*Г*ГҐГ¬ ГҐГЈГ® }
        if arr[i] > max2 then max2 := arr[i];
        { Óäîñòîâåðÿåìñÿ, Г·ГІГ® áîëüøèé ГЇГ® ïðåæГ*åìó Гў max1 }
        if max1 < max2 then begin
            temp := max1;
            max1 := max2;
            max2 := temp;
        end;
    end;
    
    WriteLn('ГЊГ*ГЄГ±ГЁГ¬Г*ëüГ*ûé ýëåìåГ*ГІ - ', max1);
    WriteLn('Ñëåäóþùèé Г§Г* Г*ГЁГ¬ - ', max2);
end.

Понравилась статья? Поделить с друзьями:
  • Как найти особенности своего лица
  • Как найти угол наклона прямоугольного треугольника
  • Как найти груз тк кит
  • Нашел деньги как найти владельца
  • Гта вай сити как найти машины