How to sort numbers - c#

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.

Related

Best way to search/filter (potentially several billion) combinations of items from multiple lists or arrays

I'm trying to write a program to optimize equipment configurations for a game. The problem is as follows:
There are six different equipment slots for a character to place an item. This is represented by 6 lists of individual items for each slot in the code containing all of the equipment owned by the player altogether.
The program will calculate the total stats of the character for each possible combination of equipment (1 from each list). These calculated stats can be filtered by specific stat min/max values and then also sorted by a specific stat to pinpoint a certain target set of stats for their character.
The program should be able to perform these queries without running out of memory or taking hours, and of course, the main problem is sifting through several billion possible combinations.
I'm not sure what the name of any supporting data structures or search algorithms to accomplish this would be called (in order to do more research towards a solution). I have come up with the following idea but I'm not sure if i'm on the right track or if someone can point me in a more effective direction.
The idea i'm pursuing is to use recursion, where each list (for each possible equipment slot) is set into a tree structure, with each progressive list acting as a child of the last. E.G.:
Weapons List
|
-----Armor List
|
------Helm List... etc
Each layer of the tree would keep a dictionary of every child path it can take containing the IDs of 1 item from each list and progressively calculating the stats given to the character (simple addition of stats from weapon + armor + helm as it traverses the tree and so on...)
When any stat with a min/max filter being applied hits it's boundary for that stat (namely, if the stat goes over the maximum before it reaches the bottom layer of the tree, it eliminates that "path" from the dictionary thus removing that entire leg of possible results from being traversed).
The main goal here is to reduce the possible tree paths to be traversed by the search algorithm and remove as many invalid results before the tree needs to calculate them to make the search as fast as possible and avoid any wasteful cycles. This seems pretty straightforward when removing items based on a "maximum" filter since when adding each item's stats progressively we can quickly tell when a stat has crossed it's expected maximum -- however when it comes to stopping paths based on a minimum total stat, I can't wrap my head around how to predict and remove these paths that won't end up above the minimum by the sixth item.
To simplify the idea, think of it like this:
I have 3 arrays of numbers
[X][0][1][2]
[0] 5 3 2
[1] 1 0 8
[2] 3 2 7
[3] 2 1 0
I want to find all combinations from the 3 arrays (sums) that are minimum of 9 and maximum of 11 total.
Each array must select at least but no more than 1 item and the sum of those selected values is what is being searched. This would need to be able to scale up to search 6+ arrays of 40+ values each essentially. Is the above approach on the right track or what is the best way to go about this (mainly using c#)
You should be able to filter out a lot of items by using a lower and upper bound for each slot:
var minimum = slots.Sum(slot => slot.Minimum);
var maximum = slots.Sum(slot => slot.Maximum);
foreach (var slot in slots)
{
var maxAvailable = maximum - slot.Maximum;
var minAvailable = minimum - slot.Minimum;
var filtered = slot.Items
// If we choose the strongest item in all the other slots and it's still below the minimum
.Where(item => item.Value + maxAvailable >= request.MinimumValue)
// If we choose the weakest item in all the other slots and its still above the maximum
.Where(item => item.Value + minAvailable <= request.MaximumValue);
}
After doing this, you can guarantee that all your combinations will be above the requested minimum, however some combinations may also be above the requested maximum, so combine this with the logic you have so far and I think you should get pretty optimal performance.

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

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

given a random set of boxes and a set of spaces, how can you find the optimal combination?

I have kind of an interesting assignment and I'm not sure where to begin.
Imagine you have a set of spaces (all same size) and a set of boxes (variable integer size, 1 or 2 or 3 units of volume). Each space can hold 4 units of volume. Given a random set of boxes, what would be the optimal combination(s) that would leave the most open space (i.e. pack in the densest).
I don't expect anyone to write my code for me, but i could really use some advice on where to start for such a problem. Can anyone help?
I tried listing all the permutations and then choosing the ones with the most "open space" but it was computationally very expensive. I'm using C# if that makes a difference.
the code is kind of longwinded so here is the pseudo code
int [] boxes = new int[20] // I will be given an array of length 20 representing 20 boxes.
// the values of the boxes[] array will be random integers of either 1, 2 or 3
foreach (var v in boxes[]){boxes[v] = random(1 or 2 or 3)
//now i take the set of boxes and come up with all the permutations with a permutation function
int [,] permutearray = new int[20!,20] // each row is the index of a permutation, with the y value as the size.
//permutearray will be a set of numbers representing a possible combination of boxes like
{{1,3,2,2,1,2,3,4 ...},{3,1,2,3,2,1,1, ...}...}
//now check each row to see how many spaces it would take to contain the boxes in that order
// do this using another function i call "fitcheck" on each row/column of permutearray
//fitcheck reports an array of numbers which represent the permutation index
int [] solutions = new [max_solutions]
solutions = fitcheck(permutearray)

c# indexer for list of list

hi all
i want to make an indexer to list of list to get items like this myopj[i,j] .
my data structure is like this :
list<list<doubl>>
i try code like this but it not work
public double this[int r, int c]
{
set
{
if (this.list1.Count == 0 )
{
this.list1[r].Add(value);
}
else
this.list1[r][c]=value;
}
}
when i watch it the program don't enter the 'if' and it end the watch .
please is there anyone can help
and thank for all .
You should be checking the count, not the capacity. Capacity is the number of elements the list can have, the Count is the actual number of items in your list.
So, given a list that is not null, the capacity should NEVER be zero, but the count could be.
It seems rather strange that your value is either a list<T> or a T.
Without more information, I suggest you implement this using a single, long list of T.
You will then translate myList<T>[i,j] to the underlying list<T>[ i * numRows + j].
Sprinkle validations as required.
If you really, really must use lists of lists figure out if you want to end up with a rectangular matrix (i.e. the list at row i has the same number of elements as the list at row j), or a staggered array (where each list has an independent number of elements).
If you're in the first case, consider creating and filling the row lists automatically, with the appropriate number of elements( use default<T> to initialize them)
Update:
Then, if what you really need is a rectangular matrix then use a list.
It will have numRows * numColumns elements.
Imagine that, instead of putting one row under the other to make a matrix, you put the elements of a row one after the other.
So, if you have:
11 12 13
21 22 23
31 32 33
in a list form they will be
11 12 13 21 22 23 31 32 33
There is a simple conversion between the X and Y (or i and j) coordinates in the first form and the index in the list in the second form.
Why are you checking the capacity? It will likely never be zero. Did you mean to check the Count?
You want the length property, and not Capactiy.
Use:
if (this.list1.Count < r )
Your algorithm doesn't really make much sense, you might want to describe what you are trying to accomplish. It looks like you are trying to make it grow if its not large enough, but the logic in the two seperate paths(if else) doesn't align.

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.

Categories