随机数组排序 [英] Random Array Sort

查看:82
本文介绍了随机数组排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好朋友

我有一堂课

Hello friends

I have one class

public class PollOptions:Polls
    {
        #region [ Constructors ]
        public PollOptions()
        {
        }
        #endregion

        #region [ Properties ]

        public Guid PollOptionsGuid { get; set; }
        public int AnswerNumber { get; set; }
        public string AnswerText { get; set; }
        public int Votes { get; set; }

        #endregion

        
    }



我在另一个类中有一个方法,该方法返回Array of PollOptions类.
例如



I have one method in another class which returns Array of PollOptions class.
For example

PollOptions[] options = obj.GetPollOptions(poll.PollGuid);



options数组按AnswerNumber值的排序顺序.我想以随机顺序排列此数组.

例如.目前的顺序是
1个Ans1
2 Ans2
3 Ans3
我想将其设为随机排序顺序,例如

3 Ans3
1个Ans1
2 Ans2

任何顺序都可以,但每次都应该是随机的.

谢谢
Imrankhan



options array is in sort order by AnswerNumber value. I want to arrange this array in random order.

For example. Currently it is in order like as
1 Ans1
2 Ans2
3 Ans3
And I want to make it random sort order such as

3 Ans3
1 Ans1
2 Ans2

In any order but should be random every time.

Thanks
Imrankhan

推荐答案

我从Google找到了代码.

I found code from google.

public PollOptions[] GetRandomOptions(PollOptions[] options)
    {
        int newIndex;
        PollOptions temp;
        for (int i = 0; i < options.Length; i++)
        {
            newIndex = new Random().Next(options.Length);
            temp = options[i];
            options[i] = options[newIndex];
            options[newIndex] = temp;
        }
        return options;
    }


所以您想要随机化和排列.您是否考虑过使用随机对象? (实际上,有一种更好的随机方法,但它有一定的局限性(仅返回0到255),但至少它是内置在框架中的.无论如何,您要采用的一般方法是到

0)获得从0到数组的随机数.长度-1

1)检索数组A中该索引处的项目

2)从数组A中删除该项目

3)将项目添加到数组B

4)如果数组A不为空,请返回步骤0

5)如果数组A *为空,则将数组B完全复制回数组A

我把它留给您,以便实际提出实际的代码.

顺便说一句,如果您要成为一名程序员,您将必须学习如何自己提出这类东西-认真地讲-这是非常基础的东西.
So you want to randomize and array. Did you consider using the Random object? (Actually, there''s a better random method but it''s kind of limited (only returns 0 to 255), but at least it''s built into the framework. In any case, the general approach you want to take is to

0) get a random number from 0 to array.Length - 1

1) retrieve the item at that index in array A

2) Remove the item from Array A

3) Add the item to array B

4) If array A isn''t empty, go back to step 0

5) If array A *is empty, copy array B back to array A in its entirety

I leave it to you to actually come up with the actual code.

BTW, if you''re going to be a programmer, you''re going to have to learn how to come up with this kind of stuff on your own - seriously - this is pretty basic stuff.


这篇关于随机数组排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆