What i want to do is get the average of each row of what the user inputs. I'm able to display the input, but not sure how to calculate an average of the three numbers in each row. What would be a solution? I'm new to C# so still learning.
Here's my code:
class Program
{
static void Main(string[] args)
{
int[,] number = new int[3, 5];
for (int i = 0; i < 3; i++)
{
for (int x = 0; x < 3; x++)
{
Console.WriteLine("Please enter number");
number[x, i] = int.Parse(Console.ReadLine());
}
}
for (int i = 0; i < 3; i++)
{
for (int x = 0; x < 3; x++)
{
Console.Write(number[x, i] + " ");
}
Console.WriteLine(" ");
Console.ReadLine();
}
}
}
You can do it something like this
for(int i = 0; i < 3; i++)
{
int Avg = 0;
for(int x = 0; x < 3; x++)
{
Console.Write(number[x, i] + " ");
Avg += number[x, i];
}
Avg = Avg / 3;
Console.Write("Average is" + Avg);
Console.WriteLine(" ");
Console.ReadLine();
}
I think you have to create a method like the following, that will accept a two dimensional array as input and iterate through its rows and further iteration will performed through its cols to find the sum of all elements in each rows and then it will be divided with number of cols, to get the average. Take a look into the method
public static void rowWiseAvg(int[,] inputArray)
{
int rows = inputArray.GetLength(0);
int cols = inputArray.GetLength(1);
for (int i = 0; i < rows; i++)
{
float rowAvg = 0;
for (int x = 0; x < cols; x++)
{
rowAvg += inputArray[i,x];
}
rowAvg = rowAvg / cols;
Console.Write("Average of row {0} is :{1}", i,rowAvg);
}
}
An additional note for you : When you are reading values for a multi-dimensional array, use outer loop to read values for the rows and inner loop for reading columns. in your case you are actually reads the columns first then gets values for each rows in a column. One more, use float / double to store the average
Here's a (mostly) LINQ solution:
var array = new int[,]
{
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 }
};
int count = 0;
var averages = array.Cast<int>()
.GroupBy(x => count++ / array.GetLength(1))
.Select(g => g.Average())
.ToArray();
// [2.5, 6.5, 10.5]
The simplest way is to use for loops, as described in other answers.
You can also utilize LINQ and use Enumerable.Range to make it another way:
public static class MultidimensionalIntArrayExtensions
{
// Approach 1 (using Select and Average)
public static double[] RowAverages(this int[,] arr)
{
int rows = arr.GetLength(0);
int cols = arr.GetLength(1);
return Enumerable.Range(0, rows)
.Select(row => Enumerable
.Range(0, cols)
.Select(col => arr[row, col])
.Average())
.ToArray();
}
// Approach 2 (using Aggregate)
public static double[] RowAverages(this int[,] arr)
{
int rows = arr.GetLength(0);
int cols = arr.GetLength(1);
return Enumerable.Range(0, rows)
.Select(row => Enumerable
.Range(0, cols)
.Aggregate(0.0, (avg, col) => avg + ((double)arr[row, col] / cols)))
.ToArray();
}
}
// Usage:
int[,] arr =
{
{ 1, 2, 3 },
{ 2, 3, 4 },
{ 3, 4, 5 },
{ 6, 7, 8 },
{ 1, 1, 1 }
};
double[] rowSums = arr.RowAverages(); // [2, 3, 4, 7, 1]
This code may look unreadable and non-OOP for some developers; and may seem good and laconic for others. If your belongs to the second group, use this code.
Related
Tried to googled it but with no luck.
How can I find the second maximum number in an array with the smallest complexity?
code OR idea will be much help.
I can loop through an array and look for the maximum number
after that, I have the maximum number and then loop the array again to find the second the same way.
But for sure it is not efficient.
You could sort the array and choose the item at the second index, but the following O(n) loop will be much faster.
int[] myArray = new int[] { 0, 1, 2, 3, 13, 8, 5 };
int largest = int.MinValue;
int second = int.MinValue;
foreach (int i in myArray)
{
if (i > largest)
{
second = largest;
largest = i;
}
else if (i > second)
second = i;
}
System.Console.WriteLine(second);
OR
Try this (using LINQ):
int secondHighest = (from number in test
orderby number descending
select number).Distinct().Skip(1).First()
How to get the second highest number in an array in Visual C#?
Answer in C# :
static void Main(string[] args)
{
//let us define array and vars
var arr = new int[]{ 100, -3, 95,100,95, 177,-5,-4,177,101 };
int biggest =0, secondBiggest=0;
for (int i = 0; i < arr.Length; ++i)
{
int arrItem = arr[i];
if(arrItem > biggest)
{
secondBiggest = biggest; //always store the prev value of biggest
//to second biggest...
biggest = arrItem;
}
else if (arrItem > secondBiggest && arrItem < biggest) //if in our
//iteration we will find a number that is bigger than secondBiggest and smaller than biggest
secondBiggest = arrItem;
}
Console.WriteLine($"Biggest Number:{biggest}, SecondBiggestNumber:
{secondBiggest}");
Console.ReadLine(); //make program wait
}
Output : Biggest Number:177, SecondBiggestNumber:101
public static int F(int[] array)
{
array = array.OrderByDescending(c => c).Distinct().ToArray();
switch (array.Count())
{
case 0:
return -1;
case 1:
return array[0];
}
return array[1];
}
static void Main(string[] args)
{
int[] myArray = new int[] { 0, 11, 2, 15, 16, 8, 16 ,8,15};
int Smallest = myArray.Min();
int Largest = myArray.Max();
foreach (int i in myArray)
{
if(i>Smallest && i<Largest)
{
Smallest=i;
}
}
System.Console.WriteLine(Smallest);
Console.ReadLine();
}
This will work even if you have reputation of items in an array
int[] arr = {-10, -3, -3, -6};
int h = int.MinValue, m = int.MinValue;
foreach (var t in arr)
{
if (t == h || t == m)
continue;
if (t > h)
{
m = h;
h = t;
}
else if(t > m )
{
m = t;
}
}
Console.WriteLine("High: {0} 2nd High: {1}", h, m);
//or,
m = arr.OrderByDescending(i => i).Distinct().Skip(1).First();
Console.WriteLine("High: {0} 2nd High: {1}", h, m);
/* we can use recursion */
var counter = 0;
findSecondMax = (arr)=> {
let max = Math.max(...arr);
counter++;
return counter == 1 ? findSecondMax(arr.slice(0,arr.indexOf(max)).concat(arr.slice(arr.indexOf(max)+1))) : max;
}
console.log(findSecondMax([1,5,2,3,0]))
static void Main(string[] args){
int[] arr = new int[5];
int i, j,k;
Console.WriteLine("Enter Array");
for (i = 0; i < 5; i++) {
Console.Write("element - {0} : ", i);
arr[i] = Convert.ToInt32(Console.ReadLine());
}
Console.Write("\nElements in array are: ");
j=arr[0];
k=j;
for (i = 1; i < 5; i++) {
if (j < arr[i])
{
if(j>k)
{
k=j;
}
j=arr[i];
}
}
Console.WriteLine("First Greatest element: "+ j);
Console.WriteLine("Second Greatest element: "+ k);
Console.Write("\n");
}
int max = 0;
int secondmax = 0;
int[] arr = { 2, 11, 15, 1, 7, 99, 6, 85, 4 };
for (int r = 0; r < arr.Length; r++)
{
if (max < arr[r])
{
max = arr[r];
}
}
for (int r = 0; r < arr.Length; r++)
{
if (secondmax < arr[r] && arr[r] < max)
{
secondmax = arr[r];
}
}
Console.WriteLine(max);
Console.WriteLine(secondmax);
Console.Read();
Python 36>=
def sec_max(array: list) -> int:
_max_: int = max(array)
second: int = 0
for element in array:
if second < element < _max_:
second = element
else:
continue
return second
Using below code we can find out second highest number, even array contains multiple max numbers
// int[] myArray = { 25, 25, 5, 20, 50, 23, 10 };
public static int GetSecondHighestNumberForUniqueNumbers(int[] numbers)
{
int highestNumber = 0, Seconhight = 0;
List<int> numberList = new List<int>();
for (int i = 0; i < numbers.Length; i++)
{
//For loop should move forward only for unique items
if (numberList.Contains(numbers[i]))
continue;
else
numberList.Add(numbers[i]);
//find higest number
if (highestNumber < numbers[i])
{
Seconhight = highestNumber;
highestNumber = numbers[i];
} //find second highest number
else if (Seconhight < numbers[i])
{
Seconhight = numbers[i];
}
}
It's not like that your structure is a tree...It's just a simple array, right?
The best solution is to sort the array. And depending on descending or ascending, display the second or the 2nd last element respectively.
The other alternative is to use some inbuilt methods, to get the initial max. Pop that element, and then search for the max again. Don't know C#, so can't give the direct code.
You'd want to sort the numbers, then just take the second largest. Here's a snippet without any consideration of efficiency:
var numbers = new int[] { 3, 5, 1, 5, 4 };
var result=numbers.OrderByDescending(x=>x).Distinct().Skip(1).First();
This isn't too bad:
int[] myArray = new int[] { 0, 1, 2, 3, 13, 8, 5 };
var secondMax =
myArray.Skip(2).Aggregate(
myArray.Take(2).OrderByDescending(x => x).AsEnumerable(),
(a, x) => a.Concat(new [] { x }).OrderByDescending(y => y).Take(2))
.Skip(1)
.First();
It's fairly low on complexity as it only every sorts a maximum of three elements
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int size;
Console.WriteLine("Enter the size of array");
size = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the element of array");
int[] arr = new int[size];
for (int i = 0; i < size; i++)
{
arr[i] = Convert.ToInt32(Console.ReadLine());
}
int length = arr.Length;
Program program = new Program();
program.SeconadLargestValue(arr, length);
}
private void SeconadLargestValue(int[] arr, int length)
{
int maxValue = 0;
int secondMaxValue = 0;
for (int i = 0; i < length; i++)
{
if (arr[i] > maxValue)
{
secondMaxValue = maxValue;
maxValue = arr[i];
}
else if(arr[i] > secondMaxValue)
{
secondMaxValue = arr[i];
}
}
Console.WriteLine("First Largest number :"+maxValue);
Console.WriteLine("Second Largest number :"+secondMaxValue);
Console.ReadLine();
}
}
}
My solution below.
class Program
{
static void Main(string[] args)
{
Program pg = new Program();
Console.WriteLine("*****************************Program to Find 2nd Highest and 2nd lowest from set of values.**************************");
Console.WriteLine("Please enter the comma seperated numbers : ");
string[] val = Console.ReadLine().Split(',');
int[] inval = Array.ConvertAll(val, int.Parse); // Converts Array from one type to other in single line or Following line
// val.Select(int.Parse)
Array.Sort(inval);
Console.WriteLine("2nd Highest is : {0} \n 2nd Lowest is : {1}", pg.Return2ndHighest(inval), pg.Return2ndLowest(inval));
Console.ReadLine();
}
//Method to get the 2nd lowest and 2nd highest from list of integers ex 1000,20,-10,40,100,200,400
public int Return2ndHighest(int[] values)
{
if (values.Length >= 2)
return values[values.Length - 2];
else
return values[0];
}
public int Return2ndLowest(int[] values)
{
if (values.Length > 2)
return values[1];
else
return values[0];
}
}
I am giving solution that's in JavaScript, it takes o(n/2) complexity to find the highest and second highest number.
here is the working Fiddler Link
var num=[1020215,2000,35,2,54546,456,2,2345,24,545,132,5469,25653,0,2315648978523];
var j=num.length-1;
var firstHighest=0,seoncdHighest=0;
num[0] >num[num.length-1]?(firstHighest=num[0],seoncdHighest=num[num.length-1]):(firstHighest=num[num.length-1], seoncdHighest=num[0]);
j--;
for(var i=1;i<=num.length/2;i++,j--)
{
if(num[i] < num[j] )
{
if(firstHighest < num[j]){
seoncdHighest=firstHighest;
firstHighest= num[j];
}
else if(seoncdHighest < num[j] ) {
seoncdHighest= num[j];
}
}
else {
if(firstHighest < num[i])
{
seoncdHighest=firstHighest;
firstHighest= num[i];
}
else if(seoncdHighest < num[i] ) {
seoncdHighest= num[i];
}
}
}
Sort the array and take the second to last value?
var result = (from elements in inputElements
orderby elements descending
select elements).Distinct().Skip(1).Take(1);
return result.FirstOrDefault();
namespace FindSecondLargestNumber
{
class Program
{
static void Main(string[] args)
{
int max=0;
int smax=0;
int i;
int[] a = new int[20];
Console.WriteLine("enter the size of the array");
int n = int.Parse(Console.ReadLine());
Console.WriteLine("elements");
for (i = 0; i < n; i++)
{
a[i] = int.Parse(Console.ReadLine());
}
for (i = 0; i < n; i++)
{
if ( a[i]>max)
{
smax = max;
max= a[i];
}
else if(a[i]>smax)
{
smax=a[i];
}
}
Console.WriteLine("max:" + max);
Console.WriteLine("second max:"+smax);
Console.ReadLine();
}
}
}
I am trying to randomize a sett of predetermine elements in a 2d array.
using System;
namespace array
{
public class tiles
{
static void Main(string[] args)
{
Random random = new Random();
int[,] tilearr = { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 } };
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
Console.Write(tilearr[i, j] + " ");
}
Console.WriteLine();
}
Console.ReadLine();
}
}
}
My problem is if I do something like tilearr[i, j] = random.Next(0, 8); it randomizes the array but doesn't care if there are any duplicates of the same element.
2 6 7
1 1 3
2 7 0
what I am after is more like this:
2 4 8 1 3 0
0 3 1 5 6 8
6 7 5, 2 4 7
A simple and to the point solution would be to have a list of available numbers and then go position by position and randomly select the numbers out of the list.
Like this:
var numbers = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
for(int x = 0; x < 3; ++x) {
for(int y = 0; y < 3; ++y) {
// select a random number from the list ...
int rand = random.Next(0, numbers.Count - 1);
tilearr[x, y] = numbers[rand];
// ... and remove it from the list
numbers.RemoveAt(rand);
}
}
As user Wai Ha Lee stated in the comments a shuffle will achieve what you are looking for. I would recommend the Fisher Yates Shuffle.
public static void Shuffle<T>(Random random, T[,] array)
{
int lengthRow = array.GetLength(1);
for (int i = array.Length - 1; i > 0; i--)
{
int i0 = i / lengthRow;
int i1 = i % lengthRow;
int j = random.Next(i + 1);
int j0 = j / lengthRow;
int j1 = j % lengthRow;
T temp = array[i0, i1];
array[i0, i1] = array[j0, j1];
array[j0, j1] = temp;
}
}
I retrieved this implementation from this answer.
This should be implemented in your code like this,
using System;
namespace array
{
public class tiles
{
static void Main(string[] args)
{
Random random = new Random();
int[,] tilearr = { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 } };
Shuffle<int>(random, tilearr);
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
Console.Write(tilearr[i, j] + " ");
}
Console.WriteLine();
}
Console.ReadLine();
}
}
}
Make sure to place the shuffle generic function within your class.
HERE is an example of my implementation on dotnetfiddle.net.
If you generate the array from scratch, it's easier to randomize a one dimensional array, and then load it into a 2D array.
static int[,] GenerateArray(int size)
{
Random r = new Random();
var arr = new int[size, size];
var values = Enumerable.Range(0, size * size).OrderBy(x => r.Next()).ToArray();
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
arr[i, j] = values[i * size + j];
return arr;
}
One way to Randomize would be flatten the 2d array, shuffle it and then recreate based on original dimension. If you want to use Linq/Extension methods, you could do the following
Random random = new Random();
int[,] tilearr = {{ 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 }};
var result = tilearr.OfType<int>()
.OrderBy(x=> random.Next())
.ChunkBy(tilearr.GetLength(1))
.To2DArray();
Where ChunkBy and To2DArray are defined as
public static class Extensions
{
public static IEnumerable<IEnumerable<T>> ChunkBy<T>(this IEnumerable<T> source, int chunkSize)
{
return source
.Select((x, i) => new { Index = i, Value = x })
.GroupBy(x => x.Index / chunkSize)
.Select(x => x.Select(v => v.Value));
}
public static T[,] To2DArray<T>(this IEnumerable<IEnumerable<T>> source)
{
var data = source
.Select(x => x.ToArray())
.ToArray();
var res = new T[data.Length, data.Max(x => x.Length)];
for (var i = 0; i < data.Length; ++i)
{
for (var j = 0; j < data[i].Length; ++j)
{
res[i,j] = data[i][j];
}
}
return res;
}
}
Sample Demo
I have a matrix like this
13 7 22
101 50 3
I Want to Print The smallest Number from the same.
Below is my Code:
using System;
class Class1
{ int min(int[,] arr)
{
int small = arr[0, 0];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (small > arr[i, j])
{
small = arr[i, j];
}
}
}
return small;
}
public static void Main()
{
int[,] x;
x = new int[,] { { 13, 7, 22 }, { 101, 50, 3 } };
Class1 obj = new Class1();
Console.WriteLine("Smallest Element : {0}", obj.min(x));
Console.ReadLine();
}
}
Throws Error as
{"Index was outside the bounds of the array."}
Expected output is 3
Why am getting this error? Please give me solution.
Note that you can use foreach to iterate over all the elements of a multidimensional array without having to worry about indices.
So it is simpler to write your min() method like so (note that I'm also using Math.Min() to find the lower of two values rather than writing my own if to do it):
static int min(int[,] arr)
{
int small = int.MaxValue;
foreach (int n in arr)
small = Math.Min(n, small);
return small;
}
Also note how I initialised small to be the largest possible int, in order to avoid having to access the first value of the array to initialise it.
If you wanted to use Linq to do the same thing you can just do this:
int min = array.Cast<int>().Min();
The reason that Cast<int> is needed is because a multidimensional array only implements the non-generic IEnumerable rather than the generic IEnumerable<T>. See this question for more details.
However using Linq an advanced topic if you are currently learning C#, in which case don't worry about that for now!
Try the following code, it will resolve X x X matrix
List<List<int>> matrix = new List<System.Collections.Generic.List<int>>()
{
new List<int>() {5,10,6}, new List<int>() {6,11,7}, new List<int>() {7,12,8}, new List<int>() {8,13,9}
};
To find MIN Value:
matrix.SelectMany(m => m.Select(n => n)).OrderBy(m => m).FirstOrDefault().Dump();
To find MAX Value
matrix.SelectMany(m => m.Select(n => n)).OrderByDescending(m => m).FirstOrDefault().Dump();
If you are using multi dimensional array
int[,] matrix = { { 1, 2, 3 }, { 3, 4, 5 } };
IEnumerable<int> query = matrix.OfType<int>();
query.SelectMany(m => m.Select(n => n)).OrderBy(m => m).FirstOrDefault().Dump();
Your array is 2X3 so you have specify condition for first loop is i<2
Like this
int min(int[,] arr)
{
int small = arr[0, 0];
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
if (small > arr[i, j])
{
small = arr[i, j];
}
}
}
return small;
}
I have some problems with comparison of matrix elements. Here is the code:
int coll = 0;
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
int tmp = 0;
for (int k = 0; k < 9; k++)
{
if (matrix[i, j] == matrix[i, k])
{
tmp++;
Console.WriteLine("{0},{1} coll {2},{3}-al", i, j, i, k);
}
coll += tmp;
}
}
}
The code wants to compare the elements of an array called matrix. When 2 elements in a column are the same, I'll increase the tmp value. At the end coll will be increased by the number of the collisions of the actual element of the array. The problem is that the program will find only the collisions of the element with itself. For example, for a matrix like
1234
1342
2341
2413
the 0:0 position will collide only with itself and not with 1:0. Can anyone tell me why?
Try this logic:
class Program
{
static void Main(string[] args)
{
int[,] matrix=new int[,] {
{ 1, 2, 3, 4 },
{ 1, 3, 4, 2 },
{ 2, 3, 4, 1 },
{ 2, 4, 1, 3 } };
// This returns the #of collisions in each column
Debug.WriteLine(CheckColumn(matrix, 0)); // 2
Debug.WriteLine(CheckColumn(matrix, 1)); // 1
Debug.WriteLine(CheckColumn(matrix, 2)); // 1
Debug.WriteLine(CheckColumn(matrix, 3)); // 0
}
static int CheckColumn(int[,] matrix, int column)
{
int[] data=new int[matrix.GetLength(0)];
for(int i=0; i<data.Length; i++)
{
data[i]=matrix[i, column];
}
var hist=data.GroupBy(i => i)
.OrderByDescending(g => g.Count())
.Select(g => new { Num=g.Key, Dupes=g.Count()-1 })
.Where(h=>h.Dupes>0);
return hist.Count()>0?hist.Sum(h=>h.Dupes):0;
}
}
I used code from https://stackoverflow.com/a/10335326/380384
Tried to googled it but with no luck.
How can I find the second maximum number in an array with the smallest complexity?
code OR idea will be much help.
I can loop through an array and look for the maximum number
after that, I have the maximum number and then loop the array again to find the second the same way.
But for sure it is not efficient.
You could sort the array and choose the item at the second index, but the following O(n) loop will be much faster.
int[] myArray = new int[] { 0, 1, 2, 3, 13, 8, 5 };
int largest = int.MinValue;
int second = int.MinValue;
foreach (int i in myArray)
{
if (i > largest)
{
second = largest;
largest = i;
}
else if (i > second)
second = i;
}
System.Console.WriteLine(second);
OR
Try this (using LINQ):
int secondHighest = (from number in test
orderby number descending
select number).Distinct().Skip(1).First()
How to get the second highest number in an array in Visual C#?
Answer in C# :
static void Main(string[] args)
{
//let us define array and vars
var arr = new int[]{ 100, -3, 95,100,95, 177,-5,-4,177,101 };
int biggest =0, secondBiggest=0;
for (int i = 0; i < arr.Length; ++i)
{
int arrItem = arr[i];
if(arrItem > biggest)
{
secondBiggest = biggest; //always store the prev value of biggest
//to second biggest...
biggest = arrItem;
}
else if (arrItem > secondBiggest && arrItem < biggest) //if in our
//iteration we will find a number that is bigger than secondBiggest and smaller than biggest
secondBiggest = arrItem;
}
Console.WriteLine($"Biggest Number:{biggest}, SecondBiggestNumber:
{secondBiggest}");
Console.ReadLine(); //make program wait
}
Output : Biggest Number:177, SecondBiggestNumber:101
public static int F(int[] array)
{
array = array.OrderByDescending(c => c).Distinct().ToArray();
switch (array.Count())
{
case 0:
return -1;
case 1:
return array[0];
}
return array[1];
}
static void Main(string[] args)
{
int[] myArray = new int[] { 0, 11, 2, 15, 16, 8, 16 ,8,15};
int Smallest = myArray.Min();
int Largest = myArray.Max();
foreach (int i in myArray)
{
if(i>Smallest && i<Largest)
{
Smallest=i;
}
}
System.Console.WriteLine(Smallest);
Console.ReadLine();
}
This will work even if you have reputation of items in an array
int[] arr = {-10, -3, -3, -6};
int h = int.MinValue, m = int.MinValue;
foreach (var t in arr)
{
if (t == h || t == m)
continue;
if (t > h)
{
m = h;
h = t;
}
else if(t > m )
{
m = t;
}
}
Console.WriteLine("High: {0} 2nd High: {1}", h, m);
//or,
m = arr.OrderByDescending(i => i).Distinct().Skip(1).First();
Console.WriteLine("High: {0} 2nd High: {1}", h, m);
/* we can use recursion */
var counter = 0;
findSecondMax = (arr)=> {
let max = Math.max(...arr);
counter++;
return counter == 1 ? findSecondMax(arr.slice(0,arr.indexOf(max)).concat(arr.slice(arr.indexOf(max)+1))) : max;
}
console.log(findSecondMax([1,5,2,3,0]))
static void Main(string[] args){
int[] arr = new int[5];
int i, j,k;
Console.WriteLine("Enter Array");
for (i = 0; i < 5; i++) {
Console.Write("element - {0} : ", i);
arr[i] = Convert.ToInt32(Console.ReadLine());
}
Console.Write("\nElements in array are: ");
j=arr[0];
k=j;
for (i = 1; i < 5; i++) {
if (j < arr[i])
{
if(j>k)
{
k=j;
}
j=arr[i];
}
}
Console.WriteLine("First Greatest element: "+ j);
Console.WriteLine("Second Greatest element: "+ k);
Console.Write("\n");
}
int max = 0;
int secondmax = 0;
int[] arr = { 2, 11, 15, 1, 7, 99, 6, 85, 4 };
for (int r = 0; r < arr.Length; r++)
{
if (max < arr[r])
{
max = arr[r];
}
}
for (int r = 0; r < arr.Length; r++)
{
if (secondmax < arr[r] && arr[r] < max)
{
secondmax = arr[r];
}
}
Console.WriteLine(max);
Console.WriteLine(secondmax);
Console.Read();
Python 36>=
def sec_max(array: list) -> int:
_max_: int = max(array)
second: int = 0
for element in array:
if second < element < _max_:
second = element
else:
continue
return second
Using below code we can find out second highest number, even array contains multiple max numbers
// int[] myArray = { 25, 25, 5, 20, 50, 23, 10 };
public static int GetSecondHighestNumberForUniqueNumbers(int[] numbers)
{
int highestNumber = 0, Seconhight = 0;
List<int> numberList = new List<int>();
for (int i = 0; i < numbers.Length; i++)
{
//For loop should move forward only for unique items
if (numberList.Contains(numbers[i]))
continue;
else
numberList.Add(numbers[i]);
//find higest number
if (highestNumber < numbers[i])
{
Seconhight = highestNumber;
highestNumber = numbers[i];
} //find second highest number
else if (Seconhight < numbers[i])
{
Seconhight = numbers[i];
}
}
It's not like that your structure is a tree...It's just a simple array, right?
The best solution is to sort the array. And depending on descending or ascending, display the second or the 2nd last element respectively.
The other alternative is to use some inbuilt methods, to get the initial max. Pop that element, and then search for the max again. Don't know C#, so can't give the direct code.
You'd want to sort the numbers, then just take the second largest. Here's a snippet without any consideration of efficiency:
var numbers = new int[] { 3, 5, 1, 5, 4 };
var result=numbers.OrderByDescending(x=>x).Distinct().Skip(1).First();
This isn't too bad:
int[] myArray = new int[] { 0, 1, 2, 3, 13, 8, 5 };
var secondMax =
myArray.Skip(2).Aggregate(
myArray.Take(2).OrderByDescending(x => x).AsEnumerable(),
(a, x) => a.Concat(new [] { x }).OrderByDescending(y => y).Take(2))
.Skip(1)
.First();
It's fairly low on complexity as it only every sorts a maximum of three elements
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int size;
Console.WriteLine("Enter the size of array");
size = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the element of array");
int[] arr = new int[size];
for (int i = 0; i < size; i++)
{
arr[i] = Convert.ToInt32(Console.ReadLine());
}
int length = arr.Length;
Program program = new Program();
program.SeconadLargestValue(arr, length);
}
private void SeconadLargestValue(int[] arr, int length)
{
int maxValue = 0;
int secondMaxValue = 0;
for (int i = 0; i < length; i++)
{
if (arr[i] > maxValue)
{
secondMaxValue = maxValue;
maxValue = arr[i];
}
else if(arr[i] > secondMaxValue)
{
secondMaxValue = arr[i];
}
}
Console.WriteLine("First Largest number :"+maxValue);
Console.WriteLine("Second Largest number :"+secondMaxValue);
Console.ReadLine();
}
}
}
My solution below.
class Program
{
static void Main(string[] args)
{
Program pg = new Program();
Console.WriteLine("*****************************Program to Find 2nd Highest and 2nd lowest from set of values.**************************");
Console.WriteLine("Please enter the comma seperated numbers : ");
string[] val = Console.ReadLine().Split(',');
int[] inval = Array.ConvertAll(val, int.Parse); // Converts Array from one type to other in single line or Following line
// val.Select(int.Parse)
Array.Sort(inval);
Console.WriteLine("2nd Highest is : {0} \n 2nd Lowest is : {1}", pg.Return2ndHighest(inval), pg.Return2ndLowest(inval));
Console.ReadLine();
}
//Method to get the 2nd lowest and 2nd highest from list of integers ex 1000,20,-10,40,100,200,400
public int Return2ndHighest(int[] values)
{
if (values.Length >= 2)
return values[values.Length - 2];
else
return values[0];
}
public int Return2ndLowest(int[] values)
{
if (values.Length > 2)
return values[1];
else
return values[0];
}
}
I am giving solution that's in JavaScript, it takes o(n/2) complexity to find the highest and second highest number.
here is the working Fiddler Link
var num=[1020215,2000,35,2,54546,456,2,2345,24,545,132,5469,25653,0,2315648978523];
var j=num.length-1;
var firstHighest=0,seoncdHighest=0;
num[0] >num[num.length-1]?(firstHighest=num[0],seoncdHighest=num[num.length-1]):(firstHighest=num[num.length-1], seoncdHighest=num[0]);
j--;
for(var i=1;i<=num.length/2;i++,j--)
{
if(num[i] < num[j] )
{
if(firstHighest < num[j]){
seoncdHighest=firstHighest;
firstHighest= num[j];
}
else if(seoncdHighest < num[j] ) {
seoncdHighest= num[j];
}
}
else {
if(firstHighest < num[i])
{
seoncdHighest=firstHighest;
firstHighest= num[i];
}
else if(seoncdHighest < num[i] ) {
seoncdHighest= num[i];
}
}
}
Sort the array and take the second to last value?
var result = (from elements in inputElements
orderby elements descending
select elements).Distinct().Skip(1).Take(1);
return result.FirstOrDefault();
namespace FindSecondLargestNumber
{
class Program
{
static void Main(string[] args)
{
int max=0;
int smax=0;
int i;
int[] a = new int[20];
Console.WriteLine("enter the size of the array");
int n = int.Parse(Console.ReadLine());
Console.WriteLine("elements");
for (i = 0; i < n; i++)
{
a[i] = int.Parse(Console.ReadLine());
}
for (i = 0; i < n; i++)
{
if ( a[i]>max)
{
smax = max;
max= a[i];
}
else if(a[i]>smax)
{
smax=a[i];
}
}
Console.WriteLine("max:" + max);
Console.WriteLine("second max:"+smax);
Console.ReadLine();
}
}
}