maverick maverick - 3 months ago 7
C# Question

why do I get an index of -1 for c# array?

I get the following result for the code I added right after the output:

Initializing
2.4

Searching
Index: 55504605
Time: 0.0374
Index: 21891944
Time: 0.0178
Index: 56663763
Time: 0.0425
Index: 37441319
Time: 0.0261
Index: -1
Time: 0.0676
Index: 9344095
Time: 0.0062

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var sw = new Stopwatch();
int[] big = new int[100000000];
Console.WriteLine("Initializing");
sw.Start();
var r = new Random(0);
for (int i=0; i < big.Length; ++i)
{
big[i] = r.Next(big.Length);
}
sw.Stop();
Console.WriteLine(sw.Elapsed.ToString("s\\.f"));
Console.WriteLine();

Console.WriteLine("Searching");
for (int i=0; i<6; ++i)
{
int searchFor = r.Next(big.Length);
sw.Reset();
sw.Start();
int index = Array.IndexOf(big, searchFor);
sw.Stop();
Console.WriteLine("Index: {0}", index);
Console.WriteLine("Time: {0:s\\.ffff}", sw.Elapsed);
}
Console.Read();
}
}
}


I do not understand why I get an index of -1 for the 5th iteration. Isn't the code returning the location of the match within the array? Isn't array numbered from 0 to 100,000,000?

Answer

Isn't array numbered from 0 to 100,000,000?

No. You initialize an array of 100000000 items with 100000000 random numbers.

int[] big = new int[100000000];
for (int i=0; i < big.Length; ++i)
{
    big[i] = r.Next(big.Length);
}

You then try to find the index of six random numbers:

for (int i=0; i<6; ++i)
{
    int searchFor = r.Next(big.Length);
    int index = Array.IndexOf(big, searchFor);

However, there's no guarantee that the big array contains all numbers between 0 and 100000000. Random.Next() can return duplicate values, meaning some other numbers from that range are missing.

So there is a chance that r.Next(big.Length) in the second loop returns a number that isn't in the array, hence the return value of -1.

If you actually want to shuffle the numbers from 0-99999999, then instead generate a list containing those numbers, and shuffle it.