C# - How to find a difference between lowest and highest numbers - c#

I have a List that contains multiple numbers like this:
1.75
1.25
2.03
1.44
What I want to do, is to find a difference between lowest and highest number. In this case it would be 1.25 and 2.03, which would make 0.78.
How should I do it?

The steps are quite simple:
Find the largest number in the list
Find the smallest number in the list
The result you need = [Result of 1] - [Result of 2]
To implement this you can use LINQ:
// Intialize your list (or use the existing one)
var list = new List<decimal>{ 1.75m, 1.25m, 2.03m, 1.44m};
// The result is maximum of the list minus minimum of the list
var result = list.Max() - list.Min();
// Print or use the result
Console.WriteLine(result); // prints the result 0.78

first determine the maximum and the minimum number and then substract the min from the max.

There are a few different ways you can do it, but first a few questions:
Is the list sorted? If it is, then it's really simple.
If it's not sorted, then you may iterate through the list, an have two variables "min" and "max", and in the end just find the difference.
Are you given the list? If not and you are the one adding values to the list, then you can keep track of the added values, and assign them appropriately to your "min" and "max" variables.
You can use LINQ

Related

how to find elements present in all three lists (most eficiently)

I use C# and I have three List<int> (say of equal size n and of distinct elements). My goal is to find elements present in all three. So I could iterate through first one and check if item is in the other two. That would be O(n^2). I could sort the other two lists first and then check for item in them using binary search. That would be O(nlogn) (without sorting).
Or I could construct two dictionaries Dictionary<int, byte>, where the key would be my list's item and then checking for an item would be O(1) and the total O(n). But how about the price of constructing dictionary? Can anyone tell how much does that cost?
Also perhaps there is even more efficient algorithm?
Using a HashSet is fairly simple, and I think it will be your best bet for performance.
HashSet<T> hset = new HashSet<T>(list1);
hset.IntersectWith(list2);
hset.IntersectWith(list3);
return hset.ToList(); // skip the ToList() if you don't explicitly need a List
You could use only one Dictionary<int, byte> where value of byte could be 1 or 2. For first list you just do the insert with value equal to 1, and for second list you do TryGetValue and based on result do either insert or update with value equal to 2. For third list you check if value is 2.

Group By variable ceiling value with catch-all maximum using LINQ To NHibernate

I'd like to construct a LINQ GroupBy statement according to the following decimal categories: 0-50, 50-100, 100-250, 250-above. I found Group by variable integer range using Linq which discusses how to use a variable range, but that query has a finite upper bound. My query needs to be able to handle everything over 250 as one group. I tried using decimal.maxValue as my upper bound, but the query couldn't handle it, I suppose because the value is larger than what NHibernate can handle. Ideally, I'd like to do this without specifying a max value so the query is independent of the database.
Edit: I'm pretty sure I can do this by using a array of floor values and following the pattern in the link. But I'm curious if there is a kind of catch-all group-by construct.
Edit:
You changed your OP to state that you could use a floor function, but you wanted to find out about a default grouping.
Mathematically a floor function is equivalent. In the case of ceiling, the lower bound for the data they used is presumably 0. In the case of floor, the logical upper bound is positive infinity (effectively it ends up being the highest value the DB supports, since integers don't support the concept of infinity). It gets you where you want to go.
If you want something that might be more applicable to other situations, you could try something like this:
items.GroupBy(item =>
(
floors.FirstOrDefault(floor => floor <= item)
?? "Default"
)
.ToString()
);
It probably wouldn't work in Linq to NHibernate, as I don't think this would map well to SQL. Instead you could import the whole set into memory first (.ToList()), and then add your grouping as a Linq to Objects query.
It doesn't make a lot of sense to use it in this situation, but it might in the case of non-number-line groupings:
var groups = new HashSet<string>
{
"Orange",
"Green",
"Mauve",
};
items.GroupBy(item =>
groups.Contains(item.Color)
? item.Color
: "Default"
);
Before Edit:
You could simply reverse the logic and you'll automatically include everything below a certain value.
var floors = new[] { 250, 100, 50, 0 };
var groupings = items.GroupBy(item => floors.First(floor => floor <= item));
How it works:
Take an item 270.
The first item in the list would be the first bucket it falls under. This is because 250 <= 270.
Take an item 99.
The third item in the list would be the first bucket it falls under. 250 is not less than 99. 100 is not less than 99. But 50 is less than 99.
An item 50 would fall into the third bucket.
It is less than 250 and 100, but equal to 50.
Doesn't quite match the description in your question:
Your group description is a bit broken. You'd have to bucketize them separately for this algorithm to work. There would be a 0-50 bucket, 51-100 bucket, etc. Or a 0-49 bucket, a 50-99 bucket, etc.
A 0-50 bucket, and a 50-100 bucket couldn't exist together.

How to sort numbers

I need some help to be able to handle the following logic. The program gets many integers input like 10,16,3,17,21,29,6.
Logic to be done:
Scenario 1:
First select the biggest 4 numbers of input which is 16,17,21,29. Now assign the values to A,B,C and D:
A = smallest in the selected 4
B = biggest in the selected 4
C =
second smallest in the selected 4
D = third smallest in the selected
4
Result to be Displayed:
A = 16
B = 29
C = 17
D = 21
Scenario: 2
If the user gives 3 inputs like 3,6,10 assign only to A,B,C and should ignore D
Result to be Displayed:
A = 3
B = 10
C = 6
Assuming that you have your input values in an array, you can sort it using the static Array.Sort() method and then pick the top/bottom ones by indexing (eg. values[value.Length - 1] gets the highest value). Do make sure to do some bounds checking to avoid runtime exceptions, and to solve "scenario 2" of the assignment correctly.
If you want something more modern, you could also use some LINQ magic to get the top 4 items:
values = values.OrderByDescending(i => i).Take(4).ToArray();
The four highest values are now in highOnes for you to print in whatever order you please. Once again, make sure to do some bounds checking - there might be less than four numbers in the array.
I would take the input and store them into a List. I would then sort this list.
Once sorted you can then pull out the numbers as required.
Logic:
Sort in descending order
Select top 4 element
Assign value as per your requirement in A,B,C,D
Sounds like this could be an assignment so I'll give you these tips:
If you have all these numbers in an array, you can try partially sorting the array. Write a simple bubble sort, and have it sort the largest numbers to the front. But instead of sorting the whole array, make it stop after it brings the 4 largest elements to the front of the array.
That way, your first element will be your largest, and so forth. From there, you can do the rest of the things you need easily.
Hope that helped.

C# algorithm - listing all permutations of number

This is sort of a follow up to a question I posted earlier (C# algorithm - find least number of objects necessary), but a bit different.
Given I have the following code:
var max = 80;
var list = new[]{10,20,30,40,50, 60);
I want to generate a array containing all the possible combinations I can use those numbers in the list to get to that max number.
The array would contain, {40, 40}, {50, 30}, {40,30, 10} etc...
You'll want to iterate over all the numbers in descending order. Then recursively add each next descending number in the sequence. Each time the sum matches, note that combo, pop out, and move on. When your tentative sum takes you over the max variable, pop out of the function to the next function in the stack. If the max still hasn't been reached, successively add the next number down in the sequence. In this way you will cover ever possible sequence, with no duplicates (unless there are duplicates in the given set, in which case you would want that duplicate). It will be not too much code actually.
The naive approach is to simply generate every combination of numbers possible, and see if they add up to the target number.
Needless to say, this has hideous time complexity. But it does the job for small lists.
EDIT: Actually, if you're allowing repeated numbers, this doesn't work. An alternative algorithm (which allows repeats, but not any negatives) is to basically keep adding up the highest number in the list, and then backtrack if you go over the target.

combination question

i have an array like below
int[] array = new array[n];// n may be 2,3,4
example for N = 4
int[] array = new array[4];
array[0] = 2;
array[1] = 4;
array[2] = 6;
array[3] = 8;
how i calculate all unrepeated combination of this array without using linq may be within?
2,4,6,8
2,4,8,6
2,8,6,4
2,6,4,6
8,6,4,2
2,4,6,8
.......
.......
.......
Here's a pretty flexible C# implementation using iterators.
Well, given that you are looking for all unrepeated combinations, that means there will be N! such combinations... (so, in your case, N! = 4! = 24 such combinations).
As I'm in the middle of posting this, dommer has pointed out a good implementation.
Just be warned that it's is going to get really slow for large values of N (since there are N! permutations).
Think about the two possible states of the world to see if that sheds any light.
1) There are no dupes in my array(i.e. each number in the array is unique). In this case, how many possible permutations are there?
2) There is one single dupe in the array. So, of the number of permutations that you calculated in part one, how many are just duplicates
Hmmm, lets take a three element array for simplicity
1,3,5 has how many permutations?
1,3,5
1,5,3
3,1,5
3,5,1
5,1,3
5,3,1
So six permutations
Now what happens if we change the list to say 1,5,5?
We get
1,5,5
5,1,5
5,5,1
My question to you would be, how can you express this via factorials?
Perhaps try writing out all the permutations with a four element array and see if the light bulb goes off?

Categories