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

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();
}
}
}

Related

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 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;
}
}
}

Getting index is outside bounds of the array

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);
}

How do I keep my program generating a new random number untill it finds one that has not been used before?

Okay, the title might be kind of misleading, but I couldn't really come up with a better explanation for my problem. I'm trying to create a program that takes an array of first names and an array of last names, and puts these together in an array of full names. Problem here is that I'm trying to make sure that the same name doesn't occur twice, so that if a combination of firstname[randomindex] and lastname[randomindex] is already in the full names array, it will reroll the random number used for index untill it finds a combination that has not been used. So far I'm kinda stuck at this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _100randompersons
{
class Fyldefylde
{
private string[] firstnames;
private string[] lastnames;
private string[] fullnames;
private Random random;
public Fyldefylde()
{
firstnames = new string[10] { "Kim", "Allan", "Frank", "Lone", "Line", "Anne", "Per", "Bo", "Grethe", "Mette" };
lastnames = new string[10] { "Pedersen", "Nielsen", "Hansen", "Larsen", "Nygaard", "Harboe", "Bendix", "Højris", "Pilgaard", "Nyager" };
fullnames = new string[100];
random = new Random();
}
public string[] getFirstNames()
{
return firstnames;
}
public string[] getLastNames()
{
return lastnames;
}
public string[] getFullNames()
{
return fullnames;
}
public int getRandomIndex(int min, int max)
{
int randomnumber = random.Next(min, max);
return randomnumber;
}
public void fillFullNames()
{
for(int i = 0; i < fullnames.Length; i++)
{
getRandomIndex(0, 10);
while(fullnames.Contains(firstnames[getRandomIndex(0,10)] + " " + lastnames[getRandomIndex(0,10)]))
{
fullnames[i] = firstnames[getRandomIndex(0, 10)] + " " + lastnames[getRandomIndex(0, 10)];
}
}
}
}
}
Thanks in advance! :)
It looks like you just want to make all combinations of full names, so why not do that?
for (int i = 0; i < firstnames.Length; i++)
{
for (int j = 0; j < lastnames.Length; j++)
{
fullnames[i*lastnames.Length + j] = firstnames[i] + " " + lastnames[j];
}
}
Then if you want your names in a random order, run a method to randomize the order of names
If you want the names in a random order then you could always do something like the following
string[] firstnames = new string[10] { "Kim", "Allan", "Frank", "Lone", "Line", "Anne", "Per", "Bo", "Grethe", "Mette" };
string[] lastnames = new string[10] { "Pedersen", "Nielsen", "Hansen", "Larsen", "Nygaard", "Harboe", "Bendix", "Højris", "Pilgaard", "Nyager" };
string[] fullnames = new string[100];
List<int> indices = new List<int>();
for (int i = 0; i < firstnames.Length * lastnames.Length; i++)
{
indices.Add(i);
}
Random random = new Random();
for (int i = 0; i < firstnames.Length; i++)
{
for (int j = 0; j < lastnames.Length; j++)
{
int randomIndex = random.Next(indices.Count() - 1);
fullnames[indices[randomIndex]] = firstnames[i] + " " + lastnames[j];
indices.RemoveAt(randomIndex);
}
}
You could use a simple HashSet to make sure that values are unique:
public void fillFullNames()
{
HashSet<string> newFullNames = new HashSet<string>();
while (newFullNames.Count != fullnames.Length) {
newFullNames.Add(firstnames[getRandomIndex(0, 10)] + " " + lastnames[getRandomIndex(0, 10)]);
}
fullnames = newFullNames.ToArray();
}
Your best bet is to generate a prototype version of fullname which represents every possible combination, then shuffle that if you want randomised output:
Random rnd = new Random();
string[] random_full_name = fullname.OrderBy(x => rnd.Next()).ToArray();
You then read this new array out consecutively to achieve your random sample with no duplciates.

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