简体   繁体   中英

How find minimum value with System.Collections.Queue in C#

I have some problem with it. I need to find min and max values and swap them. This is my code, help me, pls, if u can. Thanks.

Queue myQueue = new Queue();
Random rnd = new Random();
for (var k = 0; k <= 5; k++) myQueue.Enqueue(rnd.Next(0, 10));
foreach (var d in myQueue) Console.Write("{0} ", d);
var min = (int)myQueue.Peek(); var max = 0;
var minInd = 0; var maxInd = 0;
for (var c = 0; c < myQueue.Count; c++)
{
   if ((int)myQueue.Peek() < min)
   {
       min = (int)myQueue.Peek();
       minInd = c;
   }
   if ((int)myQueue.Peek() > max)
   {
       max = (int)myQueue.Peek();
       maxInd = c;
   }
   foreach (var f in myQueue) Console.Write(" {0}", f);
}

First of all, you are using the wrong class. Queue is for a list of stuff that need to be processed in order they arrive, not for working with sets of data. I edited your code to use a List<> , did some general cleanup, and added the swapping code:

List<int> list = new List<int>();
Random rnd = new Random();
for (var k = 0; k <= 5; k++)
    list.Add(rnd.Next(0, 10));

int min = 0;
int max = 0;

for (var i = 0; i < list.Count; i++)
{
    if (list[i] < min)
        min = i;
    if (list[i] > max)
        max = i;
}

Console.Write("Before: ");
foreach (var item in list)
    Console.Write("{0}", item);

var tmp = list[min];
list[min] = list[max];
list[max] = tmp;

Console.Write("\nAfter: ");
var queue = new Queue(list);
foreach (var item in queue)
    Console.Write("{0}", item);
Console.ReadLine();

As mentioned in another answer, there's no reason to use a queue here, also everything could be made much much easier.

var randomList = Enumerable.Range(0,5).ToList();
var min = randomList.Min();
var max = randomList.Max();
var minIndex = randomList.IndexOf(min);
var maxIndex = randomList.IndexOf(max);
randomList[minIndex] = max;
randomList[maxIndex] = min;

As you can see things don't have to be hard :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM