关于自动填充功能与完美的数字

问题描述 投票:-1回答:2

我必须制作一个模拟唱歌锦标赛的节目。我完成了这个问题(差不多)但是我需要一个更实际的功能,可以在阵列中填充1000到20个人。

我试图做一个无限循环,直到成功,但它需要很多时间,所以我删除它,我试图随机填写(0,1001-(到目前为止的投票数))但不幸的是大多数选票是前两个,然后都会有零。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp0
{
    class Program
    {
        static void Main(string[] args)
        {

            int[] A = new int[20];
            Random rnd = new Random();
            int jmo3 = 0;
            for (int i = 0; i < A.Length; i++)
            {
                if (i == A.Length - 1) 
                    A[i] = 1000 - jmo3; // so it can fill the last spot with the rest of the votes
                else
                {
                    A[i] = rnd.Next(0, 1001 - jmo3);
                    jmo3 += A[i];
                }
            }
        }
    }
}

我需要数字是正常的,第20个人获胜的机会与第1个相同:)

c#
2个回答
0
投票

对于A中所有条目之间需要1000票的情况

int[] A = new int[20];
Random rnd = new Random();

// repeat for 1000 votes
for (int i = 0; i < 1000; i++)
{
    // select a random singer (by his index)
    int index = rnd.Next(0, A.Length);
    // add one vote for this singer
    A[index]++;
}

对于你想继续投票的情况,直到A中的一个条目是1000

int[] A = new int[20];
Random rnd = new Random();
int index;

// repeat
do
{
    // select a random singer (by his index)
    index = rnd.Next(0, A.Length);
    // add one vote for this singer
    A[index]++;
}
// until one singer has 1000 votes
while(A[index] < 1000)

或者你的意思是完全不同的其他东西?


0
投票

我不理解不以OOP主体开头的C#类。

如果定义了Contest类来处理所有投票机制等问题,那么这个问题会更有意义。

有一个名为Votes的数组,其中包含每个参与者拥有的总票数。要为某人投票,请增加数组中的值。这样做了1000次,你在参与者中分配了1000张选票。

public class Contest
{
    static readonly Random rng = new Random();

    public Contest(int n_participants)
    {
        this.Votes = new int[n_participants];
    }
    public int Participants => Votes.Length;
    public int[] Votes { get; }
    public int TotalVotes => Votes.Sum();

    public void VoteFor(int index)
    {
        this.Votes[index] += 1;
    }

    public void VoteRandom()
    {
        int index = rng.Next(0, Votes.Length);
        VoteFor(index);
    }
}

static class Program
{
    static void Main(string[] args)
    {
        // Singing contest with 20 participants.
        var singing_contest = new Contest(20);
        // Gather 1000 random votes
        for (int i = 0; i < 1000; i++)
        {
            singing_contest.VoteRandom();
        }

        // Tally up the votes
        for (int i = 0; i < singing_contest.Participants; i++)
        {
            Console.WriteLine($"Participant# : {i+1}, Votes = {singing_contest.Votes[i]}");
        }
        Console.WriteLine($"Total Votes = {singing_contest.TotalVotes}");

        Console.WriteLine("Press [Enter] to exit.");
        Console.ReadLine();
    }
}

scr

© www.soinside.com 2019 - 2024. All rights reserved.