find the min value in int array with C# - c#

how can i find the min value in int arry with c#

With LINQ:
int min = theArray.Min();
note that this will error if there aren't any elements; check the .Length first (or alternatively, project to int?, but that adds overhead).
If you don't have LINQ available, then perhaps:
public static int Min(int[] arr) {
switch (arr.Length) {
case 0: throw new InvalidOperationException();
case 1: return arr[0];
case 2: return Math.Min(arr[0], arr[1]);
default:
int min = arr[0];
for (int i = 1; i < arr.Length; i++) {
if (arr[i] < min) min = arr[i];
}
return min;
}
}

I wrote bellow to compare what i said by #Marc Gravell, the way I told is a little faster in my PC, and the linq one is slowest way, Also if you change the position of functions (in code) you will always gain a better performance with a version with if
static void Main(string[] args)
{
Dictionary<string, List<long>> dic = new Dictionary<string, List<long>>();
dic["First"] = new List<long>();
dic["Second"] = new List<long>();
dic["Third"] = new List<long>();
for (int i = 0; i < 500; i++)
{
int[] array = GetRandomArray();
Stopwatch stopWacth = new Stopwatch();
stopWacth.Restart();
int n1 = FindMin(array);
stopWacth.Stop();
long firstTicks = stopWacth.ElapsedTicks;
dic["First"].Add(firstTicks);
stopWacth.Restart();
int n2 = AnotherFindMin(array);
stopWacth.Stop();
long secondTick = stopWacth.ElapsedTicks;
dic["Second"].Add(secondTick);
stopWacth.Restart();
int n3 = array.Min();
stopWacth.Stop();
long thirdTick = stopWacth.ElapsedTicks;
dic["Third"].Add(thirdTick);
Console.WriteLine("first tick : {0}, second tick {1}, third tick {2} ", firstTicks, secondTick, thirdTick);
}
Console.WriteLine("first tick : {0}, second tick {1}, third tick {2} ", dic["First"].Average(), dic["Second"].Average(), dic["Third"].Average());
Console.ReadLine();
}
public static int[] GetRandomArray()
{
int[] retVal = new int[1000000];
Random r = new Random();
for (int i = 0; i < 1000000; i++)
{
retVal[i] = r.Next(1000000000);
}
return retVal;
}
public static int FindMin(int[] arr)
{
switch (arr.Length)
{
case 0: throw new InvalidOperationException();
case 1: return arr[0];
case 2: return Math.Min(arr[0], arr[1]);
default:
int min = arr[0];
for (int i = 1; i < arr.Length; i++)
{
if (arr[i] < min) min = arr[i];
}
return min;
}
}
public static int AnotherFindMin(int[] arr)
{
if (arr.Length > 0)
{
int min = arr[0];
for (int i = 1; i < arr.Length; i++)
{
if (arr[i] < min) min = arr[i];
}
return min;
}
else
{
throw new InvalidOperationException();
}
}
}
// revised test by Marc (see comments discussion)
static class Test {
static void Main(string[] args)
{
Dictionary<string, List<long>> dic = new Dictionary<string, List<long>>();
dic["First"] = new List<long>();
dic["Second"] = new List<long>();
dic["Third"] = new List<long>();
const int OUTER_LOOP = 500, INNER_LOOP = 500000;
for (int arrSize = 1; arrSize <= 3; arrSize++)
{
for (int i = 0; i < OUTER_LOOP; i++)
{
int[] array = GetRandomArray(arrSize);
Stopwatch stopWacth = Stopwatch.StartNew();
for (int j = 0; j < INNER_LOOP; j++)
{
int n1 = FindMin(array);
}
stopWacth.Stop();
long firstTicks = stopWacth.ElapsedTicks;
dic["First"].Add(firstTicks);
stopWacth = Stopwatch.StartNew();
for (int j = 0; j < INNER_LOOP; j++)
{
int n2 = AnotherFindMin(array);
}
stopWacth.Stop();
long secondTick = stopWacth.ElapsedTicks;
dic["Second"].Add(secondTick);
stopWacth = Stopwatch.StartNew();
for (int j = 0; j < INNER_LOOP; j++)
{
int n3 = array.Min();
}
stopWacth.Stop();
long thirdTick = stopWacth.ElapsedTicks;
dic["Third"].Add(thirdTick);
//Console.WriteLine("{3}: switch : {0}, 0-check {1}, Enumerable.Min {2} ", firstTicks, secondTick, thirdTick, arrSize);
}
Console.WriteLine("{3}: switch : {0}, 0-check {1}, Enumerable.Min {2} ", dic["First"].Average(), dic["Second"].Average(), dic["Third"].Average(), arrSize);
}
Console.WriteLine("Done");
Console.ReadLine();
}
public static int[] GetRandomArray(int size)
{
int[] retVal = new int[size];
Random r = new Random();
for (int i = 0; i < retVal.Length; i++)
{
retVal[i] = r.Next(1000000000);
}
return retVal;
}
public static int FindMin(int[] arr)
{
switch (arr.Length)
{
case 0: throw new InvalidOperationException();
case 1: return arr[0];
case 2: return arr[0] < arr[1] ? arr[0] : arr[1];
default:
int min = arr[0];
for (int i = 1; i < arr.Length; i++)
{
if (arr[i] < min) min = arr[i];
}
return min;
}
}
public static int AnotherFindMin(int[] arr)
{
if (arr.Length > 0)
{
int min = arr[0];
for (int i = 1; i < arr.Length; i++)
{
if (arr[i] < min) min = arr[i];
}
return min;
}
else
{
throw new InvalidOperationException();
}
}
}

Related

Multiplication matrix on vector

I need to multiply the matrix on the vector and print the result. There are classes of integer vector and integer matrix. When outputting, displays only the first element. Can you tell me what the error is? Below I show the overloading of the * operator that I made, the method for displaying the matrix and exactly how I display it. Here is an example
public class VectorInt//class VectorInt
{
protected int[] IntArray;
protected uint size;
protected int codeError;
protected static uint num_vec;
public VectorInt()
{
codeError = 1;
size = 1;
IntArray = new int[size];
IntArray[0] = 0;
num_vec++;
}
public VectorInt(uint n)//конструктор з одним параметром
{
codeError = 1;
size = n;
IntArray = new int[size];
for (int i = 0; i < n; i++)
{
IntArray[i] = 0;
}
num_vec++;
}
public VectorInt(uint n, int b)
{
codeError = 1;
size = n;
IntArray = new int[size];
for (int i = 0; i < n; i++)
{
IntArray[i] = b;
}
num_vec++;
}
~VectorInt()
{
num_vec--;
Console.WriteLine("Dipsosed");
}
public void Input()
{
Console.WriteLine("\nSize of vector: ");
size = uint.Parse(Console.ReadLine());
IntArray = new int[size];
for (int i = 0; i < size; i++)
{
Console.WriteLine("Element {0}: ", i);
Console.WriteLine(" v [ {0} ] = {1} ", i, IntArray[i] = int.Parse(Console.ReadLine()));
}
}
public void Output()
{
Console.WriteLine("\nMatrix");
for (int i = 0; i < n; i++)//n-amount of rows
{
for (int j = 0; j < m; j++)//m-amount of columns
{
Console.Write(" m [ {0}{1} ] = {2} ", i, j, IntArray[i, j]);
}
Console.WriteLine();
}
}
public uint Size
{
get
{
return (uint)IntArray.Length;
}
}
public int[] NewIntArray
{
get => IntArray;
}
////////////////////////////////////////////////////////
public class MatrixInt//class MatrixInt
{
protected int[,] IntArray;
protected int n, m;
protected int codeError;
protected static int num_m;
public MatrixInt()
{
n = 1; m = 1;
IntArray = new int[n, m];
IntArray[0, 0] = 0;
num_m++;
}
public MatrixInt(int r, int c)
{
n = r; m = c;
IntArray = new int[n, m];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
IntArray[i, j] = 0;
}
num_m++;
}
public MatrixInt(int r, int c, int b)
{
n = r; m = c;
IntArray = new int[n, m];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
IntArray[i, j] = b;
}
num_m++;
}
~MatrixInt()
{
num_m--;
Console.WriteLine("Disposed");
}
public void Input()
{
Console.WriteLine("Number of rows: ");
n = int.Parse(Console.ReadLine());
Console.WriteLine("Number of columns: ");
m = int.Parse(Console.ReadLine());
IntArray = new int[n, m];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
Console.WriteLine("Element {0}{1}: ", i, j);
Console.WriteLine(" m [ {0}{1} ] = {2} ", i, j, IntArray[i, j] = int.Parse(Console.ReadLine()));
}
}
}
public void Output()
{
Console.WriteLine("\nMatrix");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
Console.Write(" m [ {0}{1} ] = {2} ", i, j, IntArray[i, j]);
}
Console.WriteLine();
}
}
public int Rows
{
get
{
return n;
}
}
public int Columns
{
get
{
return m;
}
}
/////////////////////////////////////////////////////////////
public static MatrixInt operator *(MatrixInt obj, VectorInt obj1)
{
MatrixInt obj3 = new MatrixInt();
if (obj.Columns != obj1.NewIntArray.Length)
{
throw new Exception("Error!");
}
obj3.IntArray = new int[obj.Rows, 1];
for (int i = 0; i < obj.Rows; i++)
{
obj3.IntArray[i, 0] = 0;
for (int j = 0; j < obj.Columns; j++)
{
obj3.IntArray[i, 0] += obj.IntArray[i, j] * obj1.NewIntArray[j];
//Console.WriteLine(" m [ {0}{1} ] = {2} ", i, j, obj3.IntArray[i, 0]);
}
}
return obj3;
}
////////////////////////////////////////////////////////
MatrixInt obj = new MatrixInt();
VectorInt obj1 = new VectorInt();
obj.Input();
obj.Output();
obj1.Input();
obj1.Output();
obj *= obj1;
obj.Output();

How to turn a recursive algorithm into a parallel processing recursive algorithm

I'm doing my homework for Algorithms and I stumbled into a problem. I was not able to transform a recursive algorithm to parallel process recursive algorithm.
This is the given equation I was given:
Equation
This is my code for this equation without parallel processing:
class Program
{
static void Main(string[] args)
{
List<int> p = new List<int> { 1, 2, 3, 4};
Console.WriteLine(F(4, 4, p));
}
public static int F(int k, int n, List<int> p)
{
List<int> maxList = new List<int>();
int ats = 0;
if (n == 0) { return 0; }
else if (k == 1)
{
ats = 0;
for (int i = 0; i < n; i++)
{
ats += p[i];
}
return ats;
}
else
{
for (int i = 0; i < n; i++)
{
ats = 0;
for (int j = i; j < n; j++)
{
ats += p[j];
}
int funkcija = F(k - 1, n - 1, p);
if (ats > funkcija)
{
maxList.Add(ats);
}
else
{
maxList.Add(funkcija);
}
}
}
ats = maxList.Min();
return ats;
}
}
I need to make this code to process parallel.
I tried changing for cycles into
I tried like this
public static int FPara(int k, int n, List<int> p)
{
List<int> maxList = new List<int>();
int ats = 0;
if (n == 0) { return 0; }
else if (k == 1)
{
ats = 0;
for (int i = 0; i < n; i++)
{
ats += p[i];
}
return ats;
}
else
{
Parallel.For(0, n - 1, i =>
{
ats = 0;
for (int j = i; j < n; j++)
{
ats += p[j];
}
int funkcija = F(k - 1, n - 1, p);
if (ats > funkcija)
{
maxList.Add(ats);
}
else
{
maxList.Add(funkcija);
}
});
}
ats = maxList.Min();
return ats;
}
however, it doesn't work.

calling merge sort c#

I wrote a merge sort program, but I have problems calling It from another class. I need help. For some reason after I enter the size and the max number a get a black screen in the output. I believe that the solution is pretty easy, but I can't find the solution by myself
This is the class where It sorts the numbers
class MergeSort
{
public int[] Sort(int[] unsortedSequence)
{
int[] left;
int[] right;
int[] result = new int[unsortedSequence.Length];
if (unsortedSequence.Length <= 1)
return unsortedSequence;
int midPoint = unsortedSequence.Length / 2;
left = new int[midPoint];
if (unsortedSequence.Length % 2 == 0)
right = new int[midPoint];
else
right = new int[midPoint + 1];
for (int i = 0; i < midPoint; i++)
left[i] = unsortedSequence[i];
int x = 0;
for (int i = midPoint; i < unsortedSequence.Length; i++)
{
right[x] = unsortedSequence[i];
x++;
}
left = Sort(left);
right = Sort(right);
result = merge(left, right);
return result;
}
public static int[] merge(int[] left, int[] right)
{
int resultLength = right.Length + left.Length;
int[] result = new int[resultLength];
int indexLeft = 0, indexRight = 0, indexResult = 0;
while (indexLeft < left.Length || indexRight < right.Length)
{
if (indexLeft < left.Length && indexRight < right.Length)
{
if (left[indexLeft] <= right[indexRight])
{
result[indexResult] = left[indexLeft];
indexLeft++;
indexResult++;
}
else
{
result[indexResult] = right[indexRight];
indexRight++;
indexResult++;
}
}
else if (indexLeft < left.Length)
{
result[indexResult] = left[indexLeft];
indexLeft++;
indexResult++;
}
else if (indexRight < right.Length)
{
result[indexResult] = right[indexRight];
indexRight++;
indexResult++;
}
}
return result;
}
}
And this is the class where I'm trying to call the mergesort
class Program
{
static void Main(string[] args)
{
Console.Write("How Many Random Numbers Would you like to Generate : ");
int n = Convert.ToInt32(Console.ReadLine());
Console.Write("What is the Maximum Random Number Would you like to Generate : ");
int max = Convert.ToInt32(Console.ReadLine());
Console.Clear();
int[] unsortedSequence = generateRandomSequence(n, max);
MergeSort mergeSortEngine = new MergeSort();
int[] mergeSortedArray = mergeSortEngine.Sort(unsortedSequence);
Console.Write("Output for Merge Sort: \n\n");
OutputSequence(mergeSortedArray);
Console.WriteLine("\n\nPress Any Key to Continue...");
Console.ReadKey();
Console.Clear();
Because you didn't provide them, I wrote the missing generateRandomSequence() and OutputSequence methods in order to test your code and I can't reproduce your issue. Perhaps you should compare these to your own:
static int[] generateRandomSequence(int count, int max)
{
Random rn = new Random();
int[] seq = new int[count];
for (int i = 0; i < count; ++i)
{
seq[i] = rn.Next(0, max + 1);
}
return seq;
}
static void OutputSequence(int[] array)
{
for (int i = 0; i < array.Length; ++i)
{
if (i > 0)
{
Console.Write(", ");
}
Console.Write(array[i]);
}
Console.WriteLine();
}
Output from your code using the above methods:
It looks like you missing generateRandomSequence(n, max);
It might be like
public static int[] generateRandomSequence(int n, int max)
{
var rnd = new Random();
int[] seq = new int[n];
for (int ctr = 0; ctr < n; ctr++)
{
seq[ctr] = rnd.Next(1, max + 1);
}
return seq;
}
Then, in Program/Test class after Console.Write("Output for Merge Sort: \n\n"); you can iterate with foreach loop to display the sorted array.
foreach (var item in mergeSortedArray)
{
Console.WriteLine("{0}", item);
}
//OutputSequence(mergeSortedArray);

Index Of Longest Run C#

I am trying to solve this question:
Write a function that finds the zero-based index of the longest run in a string. A run is a consecutive sequence of the same character. If there is more than one run with the same length, return the index of the first one.
For example, IndexOfLongestRun("abbcccddddcccbba") should return 6 as the longest run is dddd and it first appears on index 6.
Following what i have done:
private static int IndexOfLongestRun(string str)
{
char[] array1 = str.ToCharArray();
//Array.Sort(array1);
Comparer comparer = new Comparer();
int counter =1;
int maxCount = 0;
int idenxOf = 0;
for (int i =0; i<array1.Length-1 ; i++)
{
if (comparer.Compare(array1[i],array1[i+1]) == 0)
{
counter++;
}
else {
if(maxCount < counter)
{
maxCount = counter;
idenxOf = i - counter + 1;
}
counter = 1;
}
}
return idenxOf ;
}
}
public class Comparer : IComparer<char>
{
public int Compare(char firstChar, char nextChar)
{
return firstChar.CompareTo(nextChar);
}
}
The problem is that when i get to the last index for example "abbccaaaaaaaaaa"
which is a in this case, and when i=14 (taking this string as example) and when i<array1.Length-1 statment is false, the for loop jumps directrly to return indexOf; and return the wrong index, I am trying to find out how to push the forloop to continue the implementation so idenxOf could be changed to the right index. Any help please?
You could check whether a new best score is achieved for each iteration when current == previous. Minimally slower, but it allows you to write shorter code by omitting an extra check after the loop:
int IndexOfLongestRun(string input)
{
int bestIndex = 0, bestScore = 0, currIndex = 0;
for (var i = 0; i < input.Length; ++i)
{
if (input[i] == input[currIndex])
{
if (bestScore < i - currIndex)
{
bestIndex = currIndex;
bestScore = i - currIndex;
}
}
else
{
currIndex = i;
}
}
return bestIndex;
}
Promote the loop variable i to method scope and repeat the conditional block if (maxCount < counter) { ... } right after the loop exit. Thus, it executes one more time after the loop completes
private static int IndexOfLongestRun(string str)
{
char[] array1 = str.ToCharArray();
//Array.Sort(array1);
Comparer comparer = new Comparer();
int counter = 1;
int maxCount = 0;
int idenxOf = 0;
int i;
for (i = 0; i < array1.Length - 1; i++)
{
if (comparer.Compare(array1[i], array1[i + 1]) == 0)
{
counter++;
}
else
{
if (maxCount < counter)
{
maxCount = counter;
idenxOf = i - counter + 1;
}
counter = 1;
}
}
if (maxCount < counter)
{
maxCount = counter;
idenxOf = i - counter + 1;
}
return idenxOf;
}
As usual late, but joining the party. A natural classic algorithm:
static int IndexOfLongestRun(string input)
{
int longestRunStart = -1, longestRunLength = 0;
for (int i = 0; i < input.Length; )
{
var runValue = input[i];
int runStart = i;
while (++i < input.Length && input[i] == runValue) { }
int runLength = i - runStart;
if (longestRunLength < runLength)
{
longestRunStart = runStart;
longestRunLength = runLength;
}
}
return longestRunStart;
}
At the end you have both longest run index and length.
public static int IndexOfLongestRun(string str)
{
var longestRunCount = 1;
var longestRunIndex = 0;
var isNew = false;
var dic = new Dictionary<int, int>();
for (var i = 0; i < str.Length - 1; i++)
{
if (str[i] == str[i + 1])
{
if (isNew) longestRunIndex = i;
longestRunCount++;
isNew = false;
}
else
{
isNew = true;
dic.Add(longestRunIndex, longestRunCount);
longestRunIndex = 0;
longestRunCount = 1;
}
}
return dic.OrderByDescending(x => x.Value).First().Key;
}
This will return -1 if the string is empty and you have the flexibility of returning the index and the count depending on your specification.
string myStr = "aaaabbbbccccccccccccdeeeeeeeee";
var longestIndexStart = -1;
var longestCount = 0;
var currentCount = 1;
var currentIndexStart = 0;
for (var idx = 1; idx < myStr.Length; idx++)
{
if (myStr[idx] == myStr[currentIndexStart])
currentCount++;
else
{
if (currentCount > longestCount)
{
longestIndexStart = currentIndexStart;
longestCount = currentCount;
}
currentIndexStart = idx;
currentCount = 1;
}
}
return longestIndexStart;
The accepted answer from Kvam works great for small strings, but as the length approaches 100,000 characters (and perhaps this isn't needed), its efficiency wains.
public static int IndexOfLongestRun(string str)
{
Dictionary<string, int> letterCount = new Dictionary<string, int>();
for (int i = 0; i < str.Length; i++)
{
string c = str.Substring(i, 1);
if (letterCount.ContainsKey(c))
letterCount[c]++;
else
letterCount.Add(c, 1);
}
return letterCount.Values.Max();
}
This solution is twice as fast as Kvam's with large strings. There are, perhaps, other optimizations.

Find the average. largest, smallest number and mode of a int array

Hi I am trying to make a program where the user can enter up to 25 numbers and then it tells the user the average, smallest and largest number and the mode of the numbers entered but I am not sure on how to do this.
Any Guidance would be appreciated
here is what I have so far
static void Main(string[] args)
{
Console.WriteLine("enter the amount of numbers you would like to use of: ");
int arraylength = Int32.Parse(Console.ReadLine());
int[] AverageArray = new int[25];
//filling the array with user input
for (int i = 0; i < AverageArray.Length; i++)
{
Console.Write("enter the numbers you wish to find the average for: ");
AverageArray[i] = Int32.Parse(Console.ReadLine());
}
//printing out the array
Console.WriteLine("here is the average: ");
for (int i = 0; i < AverageArray.Length; i++)
{
Console.WriteLine(AverageArray[i]);
}
Console.WriteLine(FindAverage(AverageArray));
}
public static double FindAverage(int[] averageNumbers)
{
int arraySum = 0;
for (int i = 0; i < averageNumbers.Length; i++)
arraySum += averageNumbers[i];
return arraySum / averageNumbers.Length;
}
public static double LargestNumber(int[] Nums, int Count)
{
}
public static double SmallestNumber(int[] Nums, int Count)
{
}
public static double Mode(int[] Nums, int Count)
{
}
}
var smallest = AverageArray.Min();
var largest = AverageArray.Max();
var mode = AverageArray.GroupBy(v => v)
.OrderByDescending(g => g.Count())
.First()
.Key;
If you don't know how to use linq
/*Assign Initial Value*/
int highestNum = numberArray[0];
int lowestNum = numberArray[0];
int sum = 0;
foreach (int item in numberArray)
{
/*Get The Highest Number*/
if (item > highestNum)
{
highestNum = item;
}
/*Get The Lowest Number*/
if (item < highestNum)
{
lowestNum = item;
}
//get the sum
sum = item + sum;
}
//display the Highest Num
Console.WriteLine(highestNum);
//display the Lowest Num
Console.WriteLine(lowestNum);
//Display The Average up to 2 decimal Places
Console.WriteLine((sum/numberArray.Length).ToString("0.00"));
public static double LargestNumber(int[] Nums, int Count)
{
double max = Nums[0];
for (int i = 1; i < Count; i++)
if (Nums[i] > max) max = Nums[i];
return min;
}
public static double SmallestNumber(int[] Nums, int Count)
{
double min = Nums[0];
for (int i = 1; i < Count; i++)
if (Nums[i] < min) min = Nums[i];
return min;
}
public static double Mode(int[] Nums, int Count)
{
double mode = Nums[0];
int maxCount = 1;
for (int i = 0; i < Count; i++)
{
int val = Nums[i];
int count = 1;
for (int j = i+1; j < Count; j++)
{
if (Nums[j] == val)
count++;
}
if (count > maxCount)
{
mode = val;
maxCount = count;
}
}
return mode;
}

Categories