Getting index is outside bounds of the array - c#

Could someone explain why do I get this out of bounds?
Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace testing
{
class Program
{
static void Main(string[] args)
{
var n = int.Parse(Console.ReadLine());
double[] numbers = new double[] { };
for(int i = 0; i < n; i++)
{
var input = double.Parse(Console.ReadLine());
numbers[i] = input;
}
Console.WriteLine(numbers);
}
}
}

You haven't set the array size
double[] numbers = new double[n]

An array is fixed in length upon initialization. Yours has size 0.
double[] numbers = new double[] { }; // { } is the same as 'initialize with 0 elements or no content'
You need to use a List instead of an Array.
List<double> numbers = new List<double>();
for(int i = 0; i < n; i++)
{
var input = double.Parse(Console.ReadLine());
numbers.Add(input);
}

Related

How to store instances of an integer in an array in a separate variable in C#?

Goal
A C# program that picks a random number from 1 to 6 and stores it
Question
Which way to store: the entire sequence or an array of 6 elements with increments to the n-1 index for every hit of n?
Code
using System;
namespace DiceProbabilityCalc
{
class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
int[] instanceCount = new int[1000];
for (int i = 0; i < 999; i++)
{
int num = rnd.Next(1, 7);
}
}
}
}
Thanks to #PeterSmith and #Martheen for solving the question in the comments: The array instanceCount can be used to store the number of instances instead of the entire sequence. This is the resulting code.
using System;
namespace DiceProbabilityCalc
{
class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
int[] instanceCount = new int[6];
for (int i = 0; i < 999; i++)
{
int num = rnd.Next(1, 7);
instanceCount[num - 1]++;
}
for (int j = 0; j < instanceCount.Length; j++)
{
Console.WriteLine(instanceCount[j]);
}
}
}
}

VB.net C# number and letter generator

I been having issues creating a number and letter generator, it should look like this: 9WJLNN8MNDVJCFLQJ4W93YH6ZM:ZWN6QV9ZXG9YCMWAXXWP492DS9
26 letters and numbers randomly colon and same thing after colon, but I keep getting errors but heres my code from what I got so far
Right now I cant even get the numbers and letters together to make it work, im just so confused on what to do. If anyone can help me out that would be amazing. I've been working on this for a few days now.
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Xml;
namespace Testing23891721983712983981
{
class Program
{
static void Main(string[] args)
{
{
Random rand = new Random();
int[] numbers = new int[4];
for (int i = 0; i < 4; i++)
{
numbers[i] = rand.Next(1000, 10000);
}
string prefix = string.Join("-", numbers);
for (int i = 0; i < 100; i++)
{
int threeDigits = rand.Next(100, 1000);
RandomGenerator generator = new RandomGenerator();
string str = generator.RandomString(26, false);
Console.WriteLine(threeDigits, str);
Console.ReadKey();
}
}
}
public class RandomGenerator
{
// Generate a random number between two numbers
public int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
// Generate a random string with a given size
public string RandomString(int size, bool lowerCase)
{
StringBuilder builder = new StringBuilder();
Random random = new Random();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
if (lowerCase)
return builder.ToString().ToLower();
return builder.ToString();
}
// Generate a random password
public string RandomPassword()
{
StringBuilder builder = new StringBuilder();
builder.Append(RandomString(4, true));
builder.Append(RandomNumber(1000, 9999));
builder.Append(RandomString(2, false));
return builder.ToString();
}
}
}
}
use Guid class to generate random numbers with string and then use substring on it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
{
Random rand = new Random();
int[] numbers = new int[4];
for (int i = 0; i < 4; i++)
{
numbers[i] = rand.Next(1000, 10000);
}
string prefix = string.Join("-", numbers);
string strguid = "";
for (int i = 0; i < 2; i++)
{
Guid guid = Guid.NewGuid();
if (strguid != "")
{
strguid = strguid + ":" + guid.ToString().Replace("-", "").Substring(0, 26).ToUpper();
}
else
{
strguid = guid.ToString().Replace("-", "").Substring(0, 26).ToUpper();
}
}
Console.WriteLine(strguid);
Console.ReadKey();
}
}
}
}

How can I pair the contents of this array without repeating itself?

I am trying to make a Secret Santa code, so that upon running the program, it will take all names from the array and pair them.
I've tried numerous ways of doing this but it just ends up repeating an entry already in the output. fOr example:
Fred and Sarah
Yusef and Kyle
Sarah and Fred
Sarah has come up twice which is not good.
Here's the starting code, of course I first randomise the array, but have no clue what to do after that.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp27
{
class Program
{
static void Main(string[] args)
{
Random random = new Random();
String[] students = {"Fred","Mary","Yusef","Kyle","Sophie", "Lydia", "Max", "Donald","Yasmin","Archie"};
string[] shuffleStudents = students.OrderBy(x => random.Next()).ToArray();
}
}
}
Any ideas, can anyone help?
I have also tried this which I thought would work but it returns an error of the index being out of bounds of array
static void Main(string[] args)
{
Random random = new Random();
String[] students = { "Fred", "Mary", "Yusef", "Kyle", "Sophie", "Lydia", "Max", "Donald", "Yasmin", "Archie" };
int count = 0;
for (int i = 0; i < 5; i++)
{
string[] shuffleStudents = students.OrderBy(x => random.Next()).ToArray();
Console.Write("{0} and {1}", shuffleStudents[count], shuffleStudents[count+1]);
for (int j = 0; j < 5; j++)
{
count++;
}
}
Console.Read();
}
}
}
You can try to shuffle them, then print the result. Here's the code I did:
using System;
using System.Linq;
namespace _05_01_19_5am
{
class Program
{
public static void Main()
{
Random random = new Random();
String[] students = { "Fred", "Mary", "Yusef", "Kyle", "Sophie", "Lydia", "Max", "Donald", "Yasmin", "Archie" };
var shuffleThem = students.OrderBy(s => Guid.NewGuid()).ToArray();
for (int i = 0; i < 5; i++)
{
Console.WriteLine(shuffleThem[i] + " + " + shuffleThem[i+5]);
}
}
}
}
Fiddled around a bit more and found the solution.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp27
{
class Program
{
static void Main(string[] args)
{
Random random = new Random();
string[] students = { "Fred", "Mary", "Yusef", "Kyle", "Sophie", "Lydia", "Max", "Donald", "Yasmin", "Archie"};
string[] shuffleStudents = students.OrderBy(x => random.Next()).ToArray();
Console.WriteLine("Your pairs for Secret Santa has been completed!");
int count = 0;
for (int j = 0; j < 5; j++)
{
Console.Write("{0} and {1} \n", shuffleStudents[count], shuffleStudents[count+1]);
for (int i = 0; i < 2; i++)
{
count++;
}
}
Console.Read();
}
}
}

How to generate the numeric value which is not exist in given numeric array?

I have this method to generate new numeric value but it takes a long time to complete the function.
How to generate random number in fast approch?
public int GeneratenewID(int[] OptionId)
{
Random ran = new Random();
int SearchId = ran.Next(1, OptionId.Length*2);
if (!OptionId.Contains(SearchId))
{
return SearchId;
}
else
{
return GeneratenewID(OptionId);
}
}
this is going to work for sure so try:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
int [] OptionId=new int[]
{
0, 1,4,7,3,1,37,9
};
Program p = new Program();
int a= p. GeneratenewID(OptionId);
}
public int GeneratenewID(int[] OptionId)
{
Random ran = new Random(1);
int number = 0;
for (int j = 0; j < OptionId.Length ; j++)
{
number = ran.Next(OptionId.Length);
if (!OptionId.Contains(number))
break;
else
j--;
}
return number;
}
}
}

While cycle and inputs

I have code like this, how can i add 4 more inputs? (5 in total) and program would return the square of them(num*num, dont know how i should be in english, maybe correct?) Thank you very much for your time!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication9
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter number to get square");
int num = Convert.ToInt16(Console.ReadLine());
int ruut = num * num;
while (num!=1000)
{
Console.WriteLine(ruut);
break;
}
Console.ReadLine();
}
}
}
`
use a for loop and an array. Here's an example in the simplest code possible:
int[] num = new int[5];
for(int i = 0; i < 5; i++)
{
num[i] = Convert.ToInt16(Console.ReadLine());
}
for(int i = 0; i < 5; i++)
{
Console.WriteLine(num[i] * num[i]);
}

Categories

Resources