Minimum value in 2 arrays - c#

I have 2 arrays, first array holds all the values for resource_wastage and 2nd array holds all the value for power_consumed. To implement a fuzzy logic I need to check of both resource wastage and power consumption are low at the same time then my output would be the array index, if one of them is low and second is not then I should move on to the next value in the array.
Eg:
for(int i=0, i<n; i++)
if(res_was[0] is low in all res_was[i=0 to n] && [pow_con[0] is low in all pow_con[i=0 to n])
{
print i;
break;
}
else continue with next value in arrays;
Please help how to I implement this, I mean check if the values in both arrays are low simultaneously.

You can use something like this. Arrays have special method for Min search.
var resMin = res_was.Min();
var powMin = pow_con.Min();
for(int i = 0; i < n; i++)
{
if(res_was[i] == resMin && pow_con[i] == powMin)
{
Console.writeLine(i);
break;
}
}
May be you will need use more complex Min method. You can read about all of them in MSDN.

Also try this;
find the minvalue and minvalue position then compare if equal proceed your process...
int _ires_wasminValue = Enumerable.Range(0, res_was.Length).Min(i => res_was[i]);
int _imin_res_was_pos = Array.IndexOf(res_was, _ires_wasminValue);
int _ipow_cons_minValue = Enumerable.Range(0, res_was.Length).Min(i => res_was[i]);
int _imin_pow_cons_pos = Array.IndexOf(res_was, _ires_wasminValue);
if (_imin_pow_cons_pos==_imin_res_was_pos)
{
Console.writeLine(_imin_pow_cons_pos);
}

Related

Is there a way to compare every array value with eachother effectively?

So Ive been trying to compare given double values in an array with eachother to return the smallest one, but the way I do it does not seem to work consistently and very efficient. Im feeling lost.
public static double FindSmallestNum(double[] arr)
{
double max = 0;
for (int x=0;x<arr.Length-1;x++){
if ( arr[x]>= arr[x+1]){
if (max >= arr[x+1]){
max = arr[x+1];
}
}
else if (max >=arr[x]){
max = arr[x];
}
else {
max = arr[x];
}
}
return max;
}
If you are willing to use System.Linq (which it appears that you are, given the accepted answer), then you may as well just go straight to the Min() method:
public static double FindSmallestNum(double[] arr)
{
return arr.Min();
}
Although, given that it's a simple one-line method call, it's not clear that a helper method is really all that helpful in this case.
Problems with your code
In your sample code, it appears that the problem is that you set max = 0; (why do you call it max instead of min?) and then start doing comparisons to see if max is larger than items in the array. This can be problematic, since all positive numbers will be larger than max, so they will never be considered.
To fix this, first let's rename that variable to min, so we remember what we're doing, and then set it to the first value in the array. This way we know we're dealing with a number in our array, and all comparisons will be valid.
Next, we don't need to compare each item with the next item - that comparison is not relevant to finding the smallest of all the items. We only need to compare each item to the current value of min (and do the necessary reassignment if we find a lower number).
This would reduce the code to something like:
public static double FindSmallestNum(double[] input)
{
if (input == null) throw new ArgumentNullException(nameof(input));
if (input.Length == 0)
throw new InvalidOperationException("array contains no elements");
// Start with the first number
double smallest = input[0];
// Now compare the rest of the items with 'smallest'
for (int index = 1; index < input.Length; index++)
{
if (input[index] < smallest) smallest = input[index];
}
return smallest;
}
Your code can further be optimized. you can see the below logic. Complexity of this code is O(N)
static void GetSmallest(int[] arr)
{
int first, arr_size = arr.Length;
first = int.MaxValue;
for (int i = 0; i < arr_size; i++)
{
if (arr[i] < first)
{
first = arr[i];
}
}
}
You can use the below code also.
int[] arr = new int[5] { 1, 2, 3, 4, 5 };
int min = arr.Min();
Just use Linq:
var min = arr.OrderBy(v => v).FirstOrDefault();
min will be the smallest number in your array.

Quickest way to find position of item less than or equal to double in sorted list C#

I am exploring the fastest way to iterate through three sorted lists to find the position of the first item which is equal to or less than a double value. The lists contains two columns of doubles.
I have the two following working examples attached below, these are encompassed by a bigger while loop (which also modifies the currentPressure list changing the [0] value) value. But, considering the amount of rows (500,000+) being parsed by the bigger while loop, the code below is too slow (one iteration of the three while loops takes >20 ms).
"allPressures" contains all rows while currentPressure is modified by the remaining code. The while loops are used to align the time from the Flow, Rpm and Position lists to the Time in the pressure list.
In other words I am trying to find the quickest way to determine the x of
for instance
FlowList[x].Time =< currentPressure[0].Time
Any suggestions are greatly appreciated!
Examples:
for (int i = 0; i < allPressures.Count; i++)
{
if (FlowList[i].Time >= currentPressure[0].Time)
{
fl = i;
break;
}
}
for (int i = 0; i < allPressures.Count; i++)
{
if (RpmList[i].Time >= currentPressure[0].Time)
{
rp = i;
break;
}
}
for (int i = 0; i < allPressures.Count; i++)
{
if (PositionList[i].Time >= currentPressure[0].Time)
{
bp = i;
break;
}
}
Using while loop:
while (FlowList[fl].Time < currentPressure[0].Time)
{
fl++;
}
while (RpmList[rp].Time < currentPressure[0].Time)
{
rp++;
}
while (PositionList[bp].Time < currentPressure[0].Time)
{
bp++;
}
The problem is that your are doing a linear search. This means that in the worst case scenario your are iterating over all the elements in your lists. This gives you a computational complexity of O(3*n) where n is the length of your lists and 3 is the number of lists you are searching.
Since your lists are sorted you can use the much faster binary search which has a complexity of O(log(n)) and in your case O(3*log(n)).
Luckily you don't have to implement it yourself, because .NET offers the helper method List.BinarySearch(). You will need the one that takes a custom comparer, because you want to compare PressureData objects.
Since you are looking for the index of the closest value that's less than your search value, you'll have to use a little trick: when BinarySearch() doesn't find a matching value it returns the index of the next element that is larger than the search value. From this it's easy to find the previous element that is smaller than the search value.
Here is an extension method the implements this:
public static int FindMaxIndex<T>(
this List<T> sortedList, T inclusiveUpperBound, IComparer<T> comparer = null)
{
var index = sortedList.BinarySearch(inclusiveUpperBound, comparer);
// The max value was found in the list. Just return its index.
if (index >= 0)
return index;
// The max value was not found and "~index" is the index of the
// next value greater than the search value.
index = ~index;
// There are values in the list less than the search value.
// Return the index of the closest one.
if (index > 0)
return index - 1;
// All values in the list are greater than the search value.
return -1;
}
Test it at https://dotnetfiddle.net/kLZsM5
Use this method with a comparer that understands PressureData objects:
var pdc = Comparer<PressureData>.Create((x, y) => x.Time.CompareTo(y.Time));
var fl = FlowList.FindMaxIndex(currentPressure[0], pdc);
Here is a working example: https://dotnetfiddle.net/Dmgzsv

Selection sort with strings

Okay, I've been using this code to do a selection sort on integers:
public void selectSort(int [] arr)
{
//pos_min is short for position of min
int pos_min,temp;
for (int i=0; i < arr.Length-1; i++)
{
pos_min = i; //set pos_min to the current index of array
for (int j=i+1; j < arr.Length; j++)
{
if (arr[j] < arr[pos_min])
{
//pos_min will keep track of the index that min is in, this is needed when a swap happens
pos_min = j;
}
}
//if pos_min no longer equals i than a smaller value must have been found, so a swap must occur
if (pos_min != i)
{
temp = arr[i];
arr[i] = arr[pos_min];
arr[pos_min] = temp;
}
}
}
but now I want to run the same algorithm on a string list instead.
How could that be accomplished? It feels really awkward and like you would need additional loops to compare multiple chars of different strings..?
I tried a lot, but I couldn't come up with anything useful. :/
Note:
I know, selection sort isn't very efficient. This is for learning purposes only. I'm not looking for alternative algorithms or classes that are already part of C#. ;)
IComparable is an interface that gives us a function called CompareTo, which is a comparison operator. This operator works for all types which implement the IComparable interface, which includes both integers and strings.
// Forall types A where A is a subtype of IComparable
public void selectSort<A>(A[] arr)
where A : IComparable
{
//pos_min is short for position of min
int pos_min;
A temp;
for (int i=0; i < arr.Length-1; i++)
{
pos_min = i; //set pos_min to the current index of array
for (int j=i+1; j < arr.Length; j++)
{
// We now use 'CompareTo' instead of '<'
if (arr[j].CompareTo(arr[pos_min]) < 0)
{
//pos_min will keep track of the index that min is in, this is needed when a swap happens
pos_min = j;
}
}
//if pos_min no longer equals i than a smaller value must have been found, so a swap must occur
if (pos_min != i)
{
temp = arr[i];
arr[i] = arr[pos_min];
arr[pos_min] = temp;
}
}
}
The System.String class has a static int Compare(string, string) method that returns a negative number if the first string is smaller than the second, zero if they are equal, and a positive integer if the first is larger.
By "smaller" I mean that it comes before the other in the lexical order and by larger that it comes after the other in lexical order.
Therefore you can compare String.Compare(arr[j], arr[pos_min]) < 0 instead of just arr[j] < arr[pos_min] for integers.
I am writing the code in python 3.6
First import sys module for use of various features in our syntax.
import sys
Consider an array of string data type items.
A = ['Chuck', 'Ana', 'Charlie', 'Josh']
for i in range(0, len(A)):
min_val = i
for j in range(i+1, len(A)):
if A[min_val] > A[j]:
min_val = j
Swapping the indexed and minimum value here.
(A[min_val], A[i]) = (A[i], A[min_val])
print("Sorted Array is :")
for i in range(len(A)):
print("%s" % A[i])
This works perfectly fine for an array of string datatype and sorts out the input data in an alphabetical way out.
As in the input 'Charlie' and 'Chuck' are being compared according to their alphabetical preference till the 3rd place and arranged accordingly.
The output of this program on python console is
Sorted Array is :
Ana
Charlie
Chuck
Josh

Interview function with time complexity

I had an interview question to write a program in C# that Outputs odd number of occurrences in an array.
Example: [2, 2, 3, 3, 3] => [3] (Considering the array is sorted)
My solution was:
public list<int> OddOccurance(list<int> InputList)
{
list<int> output = new list<int>();
for(int i=0; i<InputList.length; i++)
{
int Count = 0;
for(int j=1; j<(InputList.length-1); j++)
{
if(InputList[i] == InputList[j])
{
Count++;
}
}
if(Count % 2 != 0)
{
output.add(InputList[i]);
}
}
return output.distinct();
}
I am thinking the answer is correct only but the interviewer had asked me like different ways of how I can make the solution much faster.
Can anyone please tell me the time complexity of the above solution please.
If there is a way to make the above solution much faster then what can be the time complexity of that solution.
Your solution is O(n^2) - if you don't know why - evaluate sum:
This is an equation which describes the running time of your algorithm. You can solve it in linear time easily - just increment i instead of inner loop over all values in array.
for (int i=0; i<InputList.Length; ++i)
{
int currentValue = InputList[i];
int j=i+1;
int count = 1;
while (InputList[j] == currentValue && j<InputList.Length)
{
count++;
i++;
j++;
}
if (count % 2 == 0)
..
}
If array is not sorted - use dictionary (hash table - Dictionary in C#) - value is a dictionary key, count is a dictionary value. (that will give you Contains key check in O(1)) Another way to get linear time if implemented properly.
The root problem of your solution is seen on this line:
return output.Distinct();
The very fact that you are doing a Distinct means that you may be adding more entries than you should.
So how can you optimize it? Observe that since the array is sorted, the only place where you can find a number that's the same as the one you're looking at is next to it, or next to another number that's equal to your current number. In other words, your numbers go in "runs".
This observation lets you go from two nested loops and an O(N2) solution to a single loop and an O(N) solution. Simply walk the array, and check lengths of each "run": when you see a new number, store its index. If you come across a new number, see if the length of the "run" is odd, and start a new run:
int start = 0;
int pos = 1;
while (pos < InputList.Length) {
if (InputList[pos] != InputList[start]) {
if ((pos-start) % 2 == 1) {
output.Add(InputList[start]);
}
start = pos;
}
pos++;
}
// Process the last run
if ((InputList.Length-start) % 2 == 1) {
output.Add(InputList[start]);
}
Demo.

How to filter an array to remove wrong values (like noise)?

I have a measurement array of 1024 values. But in this array are some values wrong like noise/peaks. The array is normally like sinus so all values should be in a good line.
How can i create a filter to the array to remove these peaks and noise?
I heard something of an algorithm that compares always three values and creates the mean-value of it but I can't find an example of this.
The wrong values are "peaks" which are bigger than the value before so it is perhaps easier if i just compare the value with the value before for a given "Offset"?
But how to do this?
public int FilterArray(double[] Values, double Offset, out double[] Results)
{
int ArrLength = Values.Length;
Results = new double[ArrLength];
for (int i = 0; i < ArrLength; i++)
Values[i] = 0;
try
{
for (int i = 0; i < ArrLength; i++)
{
if (Values[i+1] + Offset) > (Values[i]
{
// here someting is needed
}
else
{
// nothing to do if next value is ok
}
}
}
return 0;
}
Thanks for all help
I suggest to use a List instead of an Array. If you need an Array to process your data you can use the ToArray() Method but removing/filtering items from a List is way more easy than resizing Arrays.
It seems you heard about Median Filter (due to phrase that compares always three values phrase). It works good when you have to remove rare peaks.
Example: for data point triplet [3, 100, 7] algorithm finds that median (not mean!) value of this triplet is 7, and (100) data point is replaced by (7) value.
public int FilterArray(List<double> Values, double Offset, out double[] Results)
{
foreach(double value in new List<double>(Values))
{
// some logic
Values.Remove(value);
}
return 0; //??
}

Categories