Skip to content

Instantly share code, notes, and snippets.

@jamescurran
Created February 15, 2025 16:46
Show Gist options
  • Select an option

  • Save jamescurran/808ce1d3f0ee1e79db742d121a16b5f2 to your computer and use it in GitHub Desktop.

Select an option

Save jamescurran/808ce1d3f0ee1e79db742d121a16b5f2 to your computer and use it in GitHub Desktop.
Daily Challenge #JS-98: Find the Second Largest Number in an Array (in C#)
/*
Find the Second Largest Number in an Array
The Challenge
Difficulty: Medium
Topic: Array Manipulation
Description
Write a JavaScript function that takes an array of numbers
and returns the second largest number in the array.
If the array has less than two distinct numbers, return null.
*/
void Main()
{
int[] array = new int[] { 1, 3, 5, 7, 9, 1, 2, 11, 3, 11, 4, 8, 7, 6, 5 };
// int[] array = new int[] { 2, 2, 2,2,2,2,};
(int? Max, int? Snd) tuple = (null, null);
array.Aggregate(tuple,
(t, n) => (n == t.Max.GetValueOrDefault()) ? t // deal with repeated highest
: (n > t.Max.GetValueOrDefault()) ? (n, t.Max) // new highest
: (n > t.Snd.GetValueOrDefault()) ? (t.Max, n) // new 2nd highest
: t)
.Snd.Dump();
/* The more explicit version
array.Aggregate(tuple, (t, n) =>
{
if (n > t.Max.GetValueOrDefault())
return (n, t.Max);
if (n > t.Snd.GetValueOrDefault())
return (t.Max, n);
return t;
}).Snd.Dump();
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment