Another answer in this long list, but I think it’s worth it, because it provides some benefits that most (or all?) other answers don’t:
- The method below loops only once through the collection, therefore the order is O(N).
- The method finds ALL indices of the maximum values.
- The method can be used to find the indices of any comparison:
min
,max
,equals
,not equals
, etc. - The method can look into objects via a LINQ selector.
Method:
///-------------------------------------------------------------------
/// <summary>
/// Get the indices of all values that meet the condition that is defined by the comparer.
/// </summary>
/// <typeparam name="TSource">The type of the values in the source collection.</typeparam>
/// <typeparam name="TCompare">The type of the values that are compared.</typeparam>
/// <param name="i_collection">The collection of values that is analysed.</param>
/// <param name="i_selector">The selector to retrieve the compare-values from the source-values.</param>
/// <param name="i_comparer">The comparer that is used to compare the values of the collection.</param>
/// <returns>The indices of all values that meet the condition that is defined by the comparer.</returns>
/// Create <see cref="IComparer{T}"/> from comparison function:
/// Comparer{T}.Create ( comparison )
/// Comparison examples:
/// - max: (a, b) => a.CompareTo (b)
/// - min: (a, b) => -(a.CompareTo (b))
/// - == x: (a, b) => a == 4 ? 0 : -1
/// - != x: (a, b) => a != 4 ? 0 : -1
///-------------------------------------------------------------------
public static IEnumerable<int> GetIndices<TSource, TCompare> (this IEnumerable<TSource> i_collection,
Func<TSource, TCompare> i_selector,
IComparer<TCompare> i_comparer)
{
if (i_collection == null)
throw new ArgumentNullException (nameof (i_collection));
if (!i_collection.Any ())
return new int[0];
int index = 0;
var indices = new List<int> ();
TCompare reference = i_selector (i_collection.First ());
foreach (var value in i_collection)
{
var compare = i_selector (value);
int result = i_comparer.Compare (compare, reference);
if (result > 0)
{
reference = compare;
indices.Clear ();
indices.Add (index);
}
else if (result == 0)
indices.Add (index);
index++;
}
return indices;
}
If you don’t need the selector, then change the method to
public static IEnumerable<int> GetIndices<TCompare> (this IEnumerable<TCompare> i_collection,
IComparer<TCompare> i_comparer)
and remove all occurences of i_selector
.
Proof of concept:
//########## test #1: int array ##########
int[] test = { 1, 5, 4, 9, 2, 7, 4, 6, 5, 9, 4 };
// get indices of maximum:
var indices = test.GetIndices (t => t, Comparer<int>.Create ((a, b) => a.CompareTo (b)));
// indices: { 3, 9 }
// get indices of all '4':
indices = test.GetIndices (t => t, Comparer<int>.Create ((a, b) => a == 4 ? 0 : -1));
// indices: { 2, 6, 10 }
// get indices of all except '4':
indices = test.GetIndices (t => t, Comparer<int>.Create ((a, b) => a != 4 ? 0 : -1));
// indices: { 0, 1, 3, 4, 5, 7, 8, 9 }
// get indices of all '15':
indices = test.GetIndices (t => t, Comparer<int>.Create ((a, b) => a == 15 ? 0 : -1));
// indices: { }
//########## test #2: named tuple array ##########
var datas = new (object anything, double score)[]
{
(999, 0.1),
(new object (), 0.42),
("hello", 0.3),
(new Exception (), 0.16),
("abcde", 0.42)
};
// get indices of highest score:
indices = datas.GetIndices (data => data.score, Comparer<double>.Create ((a, b) => a.CompareTo (b)));
// indices: { 1, 4 }
Enjoy!
2 / 2 / 0 Регистрация: 07.04.2016 Сообщений: 34 |
|
1 |
|
Найти минимальный и максимальный элемент массива30.04.2016, 15:28. Показов 60439. Ответов 5
Как найти максимальный и минимальный элемент ,создав массив чисел. А главное как расписать в си шарпе?
0 |
Dark Byte 30 / 47 / 19 Регистрация: 23.10.2014 Сообщений: 1,001 |
||||
30.04.2016, 15:33 |
2 |
|||
0 |
sergeevdokimov 2 / 2 / 0 Регистрация: 07.04.2016 Сообщений: 34 |
||||
30.04.2016, 16:30 [ТС] |
3 |
|||
Программа написана, но почему-то не работает правильно. В чём проблема?
1 |
10 / 10 / 15 Регистрация: 29.11.2015 Сообщений: 43 |
|
30.04.2016, 17:23 |
4 |
зачем в цикле нахождения max в условии стоит «a[i] < 5» ?
0 |
2 / 2 / 0 Регистрация: 07.04.2016 Сообщений: 34 |
|
30.04.2016, 18:05 [ТС] |
5 |
даже если поставлю «n» заместь «5», всё равно не правильно работаёт!
0 |
Dragon6 5 / 5 / 4 Регистрация: 10.02.2011 Сообщений: 48 |
||||||||
01.05.2016, 00:20 |
6 |
|||||||
Там не должно быть такого условия («a[i] < что-либо»), ведь что делает цикл нахождения max (да и min, в принципе, тоже):
ну или:
На личное усмотрение
1 |
I want to find the biggest element of an array.
Code
static int FindBiggestElementInAnArray(int[] nums)
{
int aaa = 0;
for (int n = 0; n < nums.Length; n++)
{
for (int a = 0; a < nums.Length; a++)
{
if (nums[n] >= nums[a])
{
aaa++;
if (a == nums.Length - 1 && aaa == nums.Length)
{
return n;
}
}
}
aaa = 0;
}
return 0;
}
static void Main(string[] args)
{
int[] numbers = { 1, 3, 5, 3, 2, 7, 5, 9, 3, 34, 5 };
Console.Write(FindBiggestElementInAnArray(numbers));
}
I get 9
, but I expect to get 34
.
How do I resolve this issue?
Нахождение максимального элемента массива
Из этой небольшой заметки вы узнаете, как найти максимальный элемент массива с помощью языка c#
Вообще данную задачу можно решить множеством различных способов, так например, для нахождения максимального элемента массива мы можем использовать обычную сортировку, например, воспользуемся статическим методом Sort класса Array:
Код:
int [] ar = {67,34,3,8,35,23};
Array.Sort(ar);
int maxValue = ar[ar.Length-1];
//Результат: 67
Либо та же сортировка, но только в результате максимальный элемент будет самым первым, например:
Код:
int [] ar = { -1, -5, 0, 108, 34, 35, 21 };
int maxValue = ar.OrderByDescending(x => x).First();
//Результат: 108
Также в языке c# существует очень простой и компактный способ, который позволяет быстро найти максимальный элемент в массиве, для этого всего лишь нужно воспользоваться методом расширения Max, например:
Код:
int [] ar = {67,34,3,8,35,23};
int maxValue = ar.Max<int>();
//Результат: 67
Для многомерного массива:
Код:
int [,] numbers = {{270, 3, 62, 91, 2, 178},{22, 32, 65, 69, 8, 6}};
int maxValue = numbers.Cast<int>().Max();
//Результат: 270
Для jagged массива:
Код:
int [][] numbers = { new int [] {177,130,50,7,9},
new int [] {37,41,6,94},
new int [] {112,22,77,55}};
int maxValue = numbers.SelectMany(y => y).Max();
//Результат: 177
Читайте также:
- Как изменить данные в файле манифест
- C# Как переименовать файл?
- Mysql метод ExecuteScalar
В этом посте будет обсуждаться, как найти минимальное и максимальное число из массива в C#.
1. Использование Linq
Простое решение для поиска минимального и максимального значения в последовательности значений — использование Enumerable.Min
а также Enumerable.Max
методы из System.Linq
пространство имен.
using System; using System.Linq; public class Example { public static void Main() { int[] arr = { 8, 3, 5, —1, 2 }; Console.WriteLine(«Minimum number is « + arr.Min()); Console.WriteLine(«Maximum number is « + arr.Max()); } } |
Скачать Выполнить код
результат:
Minimum number is -1
Maximum number is 8
2. Использование Array.Sort()
Метод
Другой вероятный, но менее рекомендуемый способ найти минимум/максимум массива — отсортировать массив в порядке возрастания. Тогда первый и последний элементы отсортированного массива будут минимальным и максимальным элементом соответственно.
using System; public class Example { public static void Main() { int[] arr = { 8, 3, 5, —1, 2 }; Array.Sort(arr); if (arr.Length > 0) { Console.WriteLine(«Minimum number is « + arr[0]); Console.WriteLine(«Maximum number is « + arr[arr.Length — 1]); } } } |
Скачать Выполнить код
результат:
Minimum number is -1
Maximum number is 8
3. Использование пользовательской процедуры
Наконец, мы можем написать собственную процедуру для нахождения минимального и максимального числа массива. Идея состоит в том, чтобы пройтись по массиву и отслеживать минимальное или максимальное значение, найденное на данный момент. Вот как будет выглядеть код:
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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
using System; public class Example { public static int findMin(int[] arr) { if (arr.Length == 0) { throw new Exception(«Array is empty»); } int min = int.MaxValue; foreach (var i in arr) { if (i < min) { min= i; } } return min; } public static int findMax(int[] arr) { if (arr.Length == 0) { throw new Exception(«Array is empty»); } int max = int.MinValue; foreach (var i in arr) { if (i > max) { max = i; } } return max; } public static void Main() { int[] arr = { 8, 3, 5, —1, 2 }; Console.WriteLine(«Minimum number is « + findMin(arr)); Console.WriteLine(«Maximum number is « + findMax(arr)); } } |
Скачать Выполнить код
результат:
Minimum number is -1
Maximum number is 8
Вот и все, что касается нахождения минимального и максимального числа из массива в C#.
Спасибо за чтение.
Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.
Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования