int iterationMax = 1;
double actualMax = 0;
int A = 3;
List<double> tmp = new List<double> { 400, 0, -300, 400, 600 ,300, 400,
1200, 900, 400, 1200, 1500};
List<double> listMax = new List<double>();
for (int i = 0; i < tmp.Count; i++)
{
if (iterationMax < A) // A == 3
{
if (tmp[i] > actualMax)
{
actualMax = tmp[i];
}
iterationMax++;
}
else
{
listMax.Add(actualMax);
actualMax = 0;
iterationMax = 1;
}
}
Console.WriteLine("\nMaxs: ");
foreach (double max in listMax)
{
Console.Write(max + ", ");
}
List tmp holds = { 400,0,-300|400,600,300|400,1200,900|400,1200,1500},
Produce 400, 600, 1200, 1200,
Should be 400, 600, 1200, 1500. I don't know how to enter else statement to add 1500 to list.
I just want to get max from every 3 elements.
When one needs to perform manipulations on collection it is many times nicer to use Linq.
Use GroupBy in the index/3 and as it is an int each 3 following items will have a different key. Then for each group select the maximum value:
var items = new int[] { 400, 0, -300, 400, 600, 300, 400, 1200, 900 };
var results = items.Select((item, index) => new { item, index })
.GroupBy(item => item.index / 3)
.Select(group => group.Max(item => item.item));
//400, 600, 1200
A quick fix for your code would be:
var A = 3;
int iterationMax = 0;
double actualMax = 0;
List<double> tmp = new List<double> {400,0,-300,400,600,300,400,1200,900,400,1200,1500};
List<double> listMax = new List<double>();
for (int i = 0; i < tmp.Count; i++)
{
if (iterationMax < A) // A == 3
{
if (tmp[i] > actualMax)
{
actualMax = tmp[i];
}
iterationMax++;
}
if (iterationMax == A)
{
listMax.Add(actualMax);
actualMax = 0;
iterationMax = 0;
}
}
Console.WriteLine("\nMaxs: ");
foreach (double max in listMax)
{
Console.Write(max + ", ");
}
As others have said, start iterationMax from 0 and turn that else into an if (iterationMax == A).
Setting iterationMax to 0 in initialization and under else should solve your issue.
Currently your if structure will only check the first two out of three elements. Since 1500 is element #3, it will not be checked.
The problem is, when iterationMax reaches 3, you don't do anything with the value in temp, that loop is lost.
for (int i = 0; i < tmp.Count; i++)
{
if (tmp[i] > actualMax)
{
actualMax = tmp[i];
}
iterationMax++;
if (iterationMax > A)
{
listMax.Add(actualMax);
actualMax = 0;
iterationMax = 1;
}
}
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 have a problem with numbers distribution to perfectly fit given container. My numbers are:
int[] number = {50, 40, 30, 30, 25, 25};
I want to find a best combo which will be nearest to 100, and when no more options available start another container of 100. Simple solution like sorting and adding from max to min won't work, because:
int[] firstContainer = { 50, 40 }; //10 unused
int[] secontContainer = { 30, 30, 25 }; //15 unused
int[] thirdContainer = { 25 }; //75 unused
The result what I'm looking for is:
int[] firstContainer = { 50, 25, 25 }; //0 unused
int[] secontContainer = { 40, 30, 30 }; //0 unused
Is there any kind soul willing to help me solve the problem?
Here is one solution - it can be optimized and improved, but now you have a starting point. Starting point is to create all combinations of your initial array and then get the sum
static void Main(string[] args)
{
int[] number = { 50, 40, 30, 30, 25, 25 };
foreach (var kvp in Exercise(number, 100))
{
Console.WriteLine("Solution " + kvp.Key);
foreach (var sol in kvp.Value)
{
Console.Write(sol + " ");
}
Console.WriteLine();
}
}
private static Dictionary<int, List<int>> Exercise(int[] number, int sum)
{
Dictionary<int, List<int>> results = new Dictionary<int, List<int>>();
int counter = 0;
var numberOfCombinations = Math.Pow(2, number.Count());
for (int i = 0; i < numberOfCombinations; i++)
{
//convert an int to binary and pad it with 0, so I will get an array which is the same size of the input[] array. ie for example 00000, then 00001, .... 11111
var temp = Convert.ToString(i, 2).PadLeft(number.Count(), '0').ToArray();
List<int> positions = new List<int>();
int total = 0;
for (int k = 0; k < temp.Length; k++)
{
if (temp[k] == '1')
{
total += number[k];
positions.Add(number[k]);
}
}
if (total == sum)
{
results.Add(counter, positions);
counter++;
}
}
return results;
}
My solution is based on generating random and feasible answers, at the end we can find best answer :
static void Main(string[] args)
{
int[] number = { 50, 40, 30, 30, 25, 25 };
int bound = 100;
var numbers = new List<dynamic>();
Random rnd = new Random();
var ans_collection = new List<List<List<int>>>();
//number of random answers , best answer depends on i so you can't be sure this algorithm always finds optimal answer choose i big enough...
for (int i = 0; i < 100; i++)
{
for (int j = 0; j < number.Length; j++)
{
numbers.Add(new { num = number[j], seen = false });
}
var ans = new List<List<int>>();
var container = new List<int>();
var distSum = 0;
//while loop generates a distribution
while (numbers.Where(x => !x.seen).Count() > 0)
{
var chosen = numbers.OrderBy(x => rnd.NextDouble()).Where(x => !x.seen && distSum + x.num <= bound).FirstOrDefault();
if (numbers.Where(x => !x.seen && distSum + x.num <= bound).Count() > 0)
{
container.Add(chosen.num);
distSum += chosen.num;
numbers.Add(new { num = chosen.num, seen = true });
numbers.Remove(chosen);
if (numbers.Where(x => !x.seen && distSum + x.num <= bound).Count() == 0)
{
ans.Add(new List<int>(container));
container = new List<int>();
distSum = 0;
}
}
else
{
ans.Add(new List<int>(container));
container = new List<int>();
distSum = 0;
}
}
ans_collection.Add(new List<List<int>>(ans));
}
//find best answer based on sum of *unused* amounts
var min = ans_collection.Min(ans => ans.Sum(dis => (bound - dis.Sum())));
var best = ans_collection.Where(ans => ans.Sum(dis => (bound - dis.Sum())) == min).FirstOrDefault();
best.ForEach(x => Console.WriteLine(string.Join(",", x.Select(Y => Y.ToString()))));
}
Here is my code:
int Temp = 200;
List<int> PrimeBuilders = new List<int>();
PrimeBuilders.Add(200);
PrimeBuilders.Add(300);
PrimeBuilders.Add(400);
PrimeBuilders.Add(500);
PrimeBuilders.Add(200);
PrimeBuilders.Add(600);
PrimeBuilders.Add(400);
foreach(int A in PrimeBuilders)
{
}
How can I go through the list and output the index that does not contain the number assigned to Temp?
If you need indexed you probably should go with for instead of foreach:
for(int i = 0; i < PrimeBuilders.Count; i++)
{
if(PrimeBuilders[i] != Temp)
Console.WriteLine(i.ToString());
}
Bonus: LINQ one-liner:
Console.WriteLine(String.Join(Environment.NewLine, PrimeBuilders.Select((x, i) => new { x, i }).Where(x => x.x != Temp).Select(x => x.i)));
What you need is:
int Temp = 200;
var PrimeBuilders = new List<int> {200, 300, 400, 500, 200, 600, 400};
for (int i = 0; i < PrimeBuilders.Count; i++)
{
Console.WriteLine("Current index: " + i);
if (PrimeBuilders[i] != Temp)
{
Console.WriteLine("Match found at index: " + i);
}
}
Firstly, you can initialize your list with 1 line.
Secondly, if you need an index, then foreach will not give you that. You need a for loop, as shown above.
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'm a rookie in C# and I'm trying to learn that language.
Can you guys give me a tip how I can compare an array with a value picking the lowest from it?
like:
Double[] w = { 1000, 2000, 3000, 4000, 5000 };
double min = double.MaxValue;
double max = double.MinValue;
foreach (double value in w)
{
if (value < min)
min = value;
if (value > max)
max = value;
}
Console.WriteLine(" min:", min);
gives me the lowest value of w, how can I compare now?
If I have:
int p = 1001 + 2000; // 3001
how can I compare now with the list of the array and find out that the (3000) value is the nearest value to my "Searchvalue"?
You can do this with some simple mathematics and there are different approaches.
LINQ
Double searchValue = ...;
Double nearest = w.Select(p => new { Value = p, Difference = Math.Abs(p - searchValue) })
.OrderBy(p => p.Difference)
.First().Value;
Manually
Double[] w = { 1000, 2000, 3000, 4000, 5000 };
Double searchValue = 3001;
Double currentNearest = w[0];
Double currentDifference = Math.Abs(currentNearest - searchValue);
for (int i = 1; i < w.Length; i++)
{
Double diff = Math.Abs(w[i] - searchValue);
if (diff < currentDifference)
{
currentDifference = diff;
currentNearest = w[i];
}
}
Double[] w = { 1000, 2000, 3000, 4000, 5000 };
var minimumValueFromArray = w.Min();
produces
1000, as expected, cause we execute Enumerable.Min.
The same is for Enumerable.Max, to figure out the max value:
Double[] w = { 1000, 2000, 3000, 4000, 5000 };
var maximumValueFromArray = w.Max();
Considering that you're comparing with the double.MinValue and double.MaxValue, I would assume that you want just pick the smallest and biggest value from array.
If this is not what you're searching for, please clarify.
based on your code, you can achieve this in a very easy way
Double[] w = { 1000, 2000, 3000, 4000, 5000 }; // it has to be sorted
double search = 3001;
double lowerClosest = 0;
double upperClosest = 0;
for (int i = 1; i < w.Length; i++)
{
if (w[i] > search)
{
upperClosest = w[i];
break; // interrupts your foreach
}
}
for (int i = w.Length-1; i >=0; i--)
{
if (w[i] <= search)
{
lowerClosest = w[i];
break; // interrupts your foreach
}
}
Console.WriteLine(" lowerClosest:{0}", lowerClosest);
Console.WriteLine(" upperClosest:{0}", upperClosest);
if (upperClosest - search > search - lowerClosest)
Console.WriteLine(" Closest:{0}", lowerClosest);
else
Console.WriteLine(" Closest:{0}", upperClosest);
Console.ReadLine();
depending on the position of your search value this will be less than O(n)
Performance wise custom code will be more use full.
List<int> results;
int targetNumber = 0;
int nearestValue=0;
if (results.Any(ab => ab == targetNumber ))
{
nearestValue= results.FirstOrDefault<int>(i => i == targetNumber );
}
else
{
int greaterThanTarget = 0;
int lessThanTarget = 0;
if (results.Any(ab => ab > targetNumber ))
{
greaterThanTarget = results.Where<int>(i => i > targetNumber ).Min();
}
if (results.Any(ab => ab < targetNumber ))
{
lessThanTarget = results.Where<int>(i => i < targetNumber ).Max();
}
if (lessThanTarget == 0 )
{
nearestValue= greaterThanTarget;
}
else if (greaterThanTarget == 0)
{
nearestValue= lessThanTarget;
}
else if (targetNumber - lessThanTarget < greaterThanTarget - targetNumber )
{
nearestValue= lessThanTarget;
}
else
{
nearestValue= greaterThanTarget;
}
}