0

I understand how to create a random number generator in C # that is not what I'm trying to do. What I'm trying to do is to create a program that will pull numbers from an existing list of numbers output those numbers and add it to a total.

var numbers = new List<int>();
numbers.Add(50);
numbers.Add(100);
numbers.Add(150);

For example the numbers within this list. When the person running the program inputs R it will output one of these 3 numbers, Let's say it outputs 50 the total output would be 50, then the user can run it again, and let's say it outputs 150 at that time. the total would go up to 200.

Roman Patutin
  • 2,171
  • 4
  • 23
  • 27
  • 1
    so the total is cumulative between runs? then you're going to need to store that data somewhere - perhaps in a file next to the app, or perhaps in a database, or perhaps in a clustered cloud container on multiple redundant data-centres (hey, we don't know your scale here!); also; does returning 50 remove it from the pool? if so, that information also needs storage – Marc Gravell Oct 07 '20 at 06:38
  • 3
    And what did you try so far? I guess you have at least some verbal decription of the steps you have to do, right? So where specifically are you stuck? Can you re-use a number? – MakePeaceGreatAgain Oct 07 '20 at 06:40

2 Answers2

1

Here a solution in case you just need to add them for one run of the APP:
If you need to store the values for other runs in the future let me know & I will edit my answer. (In this case you will need a database or a external text file to store the data)

List<int> PossibleNumbers = new List<int>()
    {
        10,
        50,
        23,
        45,
        100
    };
    Random rnd = new Random();
    List<int> randomNumbers = new List<int>();
    public int GetRandomFromList()
    {
        return PossibleNumbers[rnd.Next(0, PossibleNumbers.Count)];
    }

    public int NewSum()
    {
        //Get number
        var random = GetRandomFromList();
        randomNumbers.Add(random);
        //Add numbers
        int sum = 0;
        foreach (var number in randomNumbers)
        {
            sum += number;
        }

        return sum;
    }
Adrian Efford
  • 473
  • 3
  • 8
1

If you simply want random numbers from a list you should see @Adrian Efford answer. If you want non repeating numbers from a list you can shuffle the list;

public static void Shuffle<T>(this IList<T> list, Random rnd)
{
    for(var i=list.Count; i > 0; i--)
        list.Swap(0, rnd.Next(0, i));
}

public static void Swap<T>(this IList<T> list, int i, int j)
{
    var temp = list[i];
    list[i] = list[j];
    list[j] = temp;
}

And use like

Shuffle(MyList, rnd);
MyList.Take(10).Sum();

You could further extend the solution by adding a parameter to the shuffle method that stops shuffling after N items.

JonasH
  • 28,608
  • 2
  • 10
  • 23