Помогите. Задача описана в первых комментариях кода.
Никак не могу понять, как найти два максимальных элемента массива и их индекс.
Например, массив у нас пусть будет {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 |
|||||||||||||||||||
Решение5)
Добавлено через 4 минуты 5 секунд
Добавлено через 1 минуту 24 секунды
Добавлено через 5 минут 48 секунд
Добавлено через 22 минуты 1 секунду
2 |
Загрузка…
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.