tags:

views:

100

answers:

4

I need some help in code to be able to handle the following logic.

The program gets many input in Integers 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

+1  A: 

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.

Robin Day
+1  A: 

Logic:

  1. Sort in descending order
  2. Select top 4 element
  3. Assign value as per your requirement in A,B,C,D
Brij
+1  A: 

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.

Jørn Schou-Rode
+1  A: 

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.

Sagekilla