Program that creates random numbers from 1 to n, without repeating, and stores them in array of size n

Viewed 67

Well, I've been coding this program that has the objective to create random numbers, and then store them in an array (linhas[n]), but I don't want them to repeat. I started by doing a for loop (int i = 0; i < n; i++) and inside it I wrote that a variable a (int a) was equal to a random number generated from the random function (r). Then I compared if a already existed in the array, using bool b = Array.Exists(linhas, elements => elements == a);, then wrote that if b was true it would decrease the i value by one, to repeat the same i loop, doing linhas[i] = a if b was false. Then it would write the elements of the array. The problem that I'm getting is that when I open the program and write the value of n the program just doesn't do nothing, just a black screen. I already checked and if I put the value of n = 1, the program generates just one number, number 1. But if I put n = 2 it just stops. If anyone understood what I said here and could help me, please just throw some tips!

The code here:

static void Main(string[] args)
{
    int n;
    Console.Write("Escreva o número de linhas a aparecer: ");
    n = Convert.ToInt32(Console.ReadLine());
    int[] linhas = new int[n];
    var r = new Random();
    for (int i = 0; i < n; i++) 
    {
        int a = r.Next(1, n);
        bool b = Array.Exists(linhas, elements => elements == a);
        if (b == true)
        {
            i--;
        }
        else
        {
            linhas[i] = a;
        }
    }
    Console.WriteLine("");
    for (int i = 0; i < n; i++)
    {
        Console.WriteLine(linhas[i]);
    }
    Console.Read();
}
1 Answers

Random range is not valid. Your fault is r.Next(1, n) mean is [1;n). I fixed that r.Next(1, n+1). Hope this helps. Bye!

using System;
using System.Linq;
class MyClass
{

    static void Main(string[] args)
    {
        int n;
        Console.Write("Escreva o número de linhas a aparecer: ");
        n = Convert.ToInt32(Console.ReadLine());
        int[] linhas = new int[n];
        var r = new Random();
        for (int i = 0; i < n;)
        {
            int a = r.Next(1, n + 1);
            #region Using LINQ
            //if (linhas.Contains(a))
            //{
            //    continue;
            //}
            #endregion
            #region Using Array Exists
            bool b = Array.Exists(linhas, elements => elements == a);
            if (b == true)
            {
                continue;
            }
            #endregion
            else
            {
                linhas[i] = a;
                i++;
            }
        }
        Console.WriteLine("");
        for (int i = 0; i < n; i++)
        {
            Console.WriteLine(linhas[i]);
        }
    }
}
Related