C#: Create Ints in a loop with names from a table array - c#

Alright, so I was trying to do a part of my program which just tallies all the numbers in a number (i'm good at translating polish mathematical arguments to english) and I wanted to implement a loop in which new variables are created, and those variables have names from a table array.
Here's the snippet of my code:
Random rand = new Random();
int[] a = { rand.Next(100,999), rand.Next(100, 999), rand.Next(100, 999), rand.Next(100, 999) }; // random numbers
int j = -1;
string[] inty = { "k", "l", "m", "n" }; // the array from which i want to extract variable names
for (int i = 0;i<=a.Length;i++) // loop
{
j++;
int inty[j] = new int(); // create a new int, where the name of the int is some letter from that array
Console.WriteLine(a[j]);
}
Console.ReadKey();
So that int that's supposed to be created in the loop should have a name from the next letters in that string array (inty). Does anyone have an idea on how to do this (or replace the code in another way)?
Sincerely,
some random dude on the internet.

You can use a Dictionary for this:
Random rand = new Random();
int[] a = { rand.Next(100,999), rand.Next(100, 999), rand.Next(100, 999), rand.Next(100, 999) }; // random numbers
string[] inty = { "k", "l", "m", "n" };
var variables = new Dictionary<string, int>();
for (int i = 0; i<a.Length; i++)
{
variables.Add(inty[i], a[i]);
Console.WriteLine(variables[inty[i]]);
}
//example using a variable
Console.WriteLine($"k: {variables["k"]}");
Console.ReadKey();
or:
Random rand = new Random();
int[] a = { rand.Next(100,999), rand.Next(100, 999), rand.Next(100, 999), rand.Next(100, 999) }; // random numbers
string[] inty = { "k", "l", "m", "n" };
var variables = new Dictionary<string, int>();
foreach (var item in a.Zip(inty, (i, n) => (i, n)))
{
variables.Add(item.i, item.n);
}
//example using a variable
Console.WriteLine($"k: {variables["k"]}");
Console.ReadKey();
Remember C# is strongly-typed. Variables must be declared to the compiler. If you want an identifier to be available as a variable in the IDE, it must be declared that way. Otherwise, you just use the name as data held in some other type.

If I understand your question... you may use the modulus function and a hashset maybe
HashSet<string> names = new HashSet<strings>();
for (int i = 0;i<=a.Length;i++)
{
j = j++ % 3; // Will give 0,1,2,0,1,2,0,1,2... or use ranbd.Next(0,4)
string forName = inty[j]; // Restricted to 0,1,2
string newName = $"{forName}{a[j]}";
if (! names.Contains(newName)
{
names.Add(newName);
Console.WriteLine("Name: {newName}");
}
else
{
Console.WriteLine("Ups!: {newName} already used!");
}
}

Related

Create various from Wordlist

I want to create a password list.
So far, it works but my list contains only words like D?t1g3+T%J.
Now I want to create words with more sense.
I have a List with words like Banana, Desk and so on.
How is it possible to change randomly the spelling, add numbers and special characters?
For example:
"Banana" -> "baNana123"
Well, I have just come up with this.
string foo = "banana";
List<string> chars = new List<string>();
Random rnd = new Random();
string newPassword = "";
for (int i = 0; i < foo.Length; i++)
{
chars.Add(foo[i].ToString());
}
foreach (var boo in chars)
{
var randomNum = rnd.Next(0, 2);
Debug.WriteLine(randomNum);
if (randomNum == 0)
{
newPassword = newPassword + boo.ToUpper();
}
else
{
newPassword = newPassword + boo.ToLower();
}
}
Debug.WriteLine(newPassword);
What it does: 1)strips the string, in my case "banana" into individual characters
2) for every character program generates randomly 1, or 0. Base on that I just simply convert to lower, or upper case.
All you have to do is to feed the algorithm with strings. And to the adding numbers at the end you can do something like this I quess.
int howMany = rnd.Next(1, 20); //1 to 19 numbers, you can set that manually
for (int i = 0; i < howMany; i++)
{
newPassword = newPassword + rnd.Next(0, 10);
}
Debug.WriteLine(newPassword);
Outcome last run for me: BanANA6469242684

Checking to see the char equivalent of my int value

Okay i might not have explained it to the best of my ability but i'm a beginner and i would like to make a piece of code that does this :
you have a string and you need to find each vowel in it and multiply each vowel's position in the string by its position in the alphabet and add all the sums together
example : steve: has 2 vowels the first e's position is 3 and its position in the alphabet is 5. and the second's position in the alphabet and the string is 5
so the sum is 5*3 + 5*5 = 40
this is what i did . idk what to do now or how to approach it
var vowels = new char[] {'a', 'e', 'i', 'o', 'u', 'y', 'A','E','I', 'O', 'U','Y'};
var chars = new List<char>();
List<int> indexes = new List<int>();
Console.WriteLine("Write something : ");
var input = Console.ReadLine();
int index;
foreach (var vowel in vowels)
{
if (input.Contains(vowel))
{
index = input.IndexOf(vowel);
indexes.Add(index + 1);
chars.Add(vowel);
}
}
Consider this approach:
using System;
using System.Linq;
using System.Collections.Generic;
namespace Whatever
{
class Program
{
static void Main(string[] args)
{
var vowels = new Dictionary<string, int>(5, StringComparer.OrdinalIgnoreCase) { { "a", 1 }, { "e", 5 }, { "i", 9 }, { "o", 15 }, { "u", 21 } };
Console.WriteLine("Write something : ");
var input = Console.ReadLine();
var sum = input.Select((value, index) => new { value, index })
.Sum(x =>
{
vowels.TryGetValue(x.value.ToString(), out var multiplier);
return (x.index + 1) * multiplier;
});
Console.ReadLine();
}
}
}
The Select projects the original string as an anonymous type with the char and its index included.
The Sum checks if the string is a vowel - and if it is it multiplies the position (index + 1) by the position in the alphabet (from vowels).
vowels is case insensitive so that "A" and "a" are treated the same.
If the compiler complains about the out var then use:
int multiplier = 0;
vowels.TryGetValue(x.value.ToString(), out multiplier);
return (x.index + 1) * multiplier;
instead.
i figured it out right here
for (int i = 0; i < indexes.Count; i++)
{
sumofone += indexes[i] * (char.ToUpper(chars[i]) - 64);
}
You can do this (Reference is from here):
var vowels = new char[] { 'a', 'e', 'i', 'o', 'u' };
Console.WriteLine("Write something : ");
var input = Console.ReadLine().ToLower();
int total = 0;
for (int temp = 1; temp <= input.Length; temp++)
{
if (vowels.Contains(input[temp - 1]))
{
total += temp * (char.ToUpper(input[temp -1]) - 64);
}
}
Console.WriteLine("The length is " + total);

Change the array values order by changing the index

I'm trying to change the elements of an array randomly, by changing the indexes.
My code so far is the following:
public static string[] Shuffle(string[] wordArray)
{
int swapIndex = 0;
string temp;
Random random = new Random();
for (int i = 0; i < wordArray.Length; i++)
{
System.Console.WriteLine("random " + random.Next(0, wordArray.Length));
swapIndex = (int)(random.Next(0, wordArray.Length));
temp = wordArray[i];
wordArray[i] = wordArray[swapIndex];
wordArray[swapIndex] = temp;
}
return wordArray;
}
And the function that calls that method is the following:
static string[] words1 = new string[] { "1", "2", "3" };
static string[] days = new string[] { "M", "T", "W", "Th", "F", "S", "Su" };
public static void playListCreation()
{
for (int j = 0; j < days.Length; j++)
{
var result = Shuffle(words1);
foreach (var i in result)
{
System.Console.WriteLine(i + " ");
}
System.Console.WriteLine("/n");
}
}
The problem with the code is that every time Im getting the same number in the swapIndex value. I always get:
random 2
random 2
random 0
In all the iterations. And I don't know what I'm doing wrong.
Any ideas? thanks in advance.
Addition
Now the solution is good. But not perfect. As I have random values, I can get two results that are the same.
for example:
Monday:
song 1
song 2
song 3
Tuesday:
song 2
song 1
song 3
Wednesday:
song 1
song 2
song 3
And so on...
And the list from
Monday
and
Wednesday
in this case is the same. I need to control that, but as you can see on the code, once I get the list from one day, I just print it. I thought about putting it on an array or Tuples and check if that tuple exists, but I think its too complicated. How can I solve this situation? Thanks!!
You need to declare and initialize the Random only once. You are declaring it inside the Shuffle method and calling it in a loop. This means that your Randomobject is getting initialized with the same seed every time, so obviously it will generate the same sequence of "random" numbers.
private static Random random = new Random();
public static string[] Shuffle(string[] wordArray)
{
int swapIndex = 0;
string temp;
for (int i = 0; i < wordArray.Length; i++)
{
System.Console.WriteLine("random " + random.Next(0, wordArray.Length));
swapIndex = (int)(random.Next(0, wordArray.Length));
temp = wordArray[i];
wordArray[i] = wordArray[swapIndex];
wordArray[swapIndex] = temp;
}
return wordArray;
}
Also, stop-cran had a valid point - the Console.WriteLine gets a different random number then the swapIndex variable.
If you want to print out the value of the swapIndex variable, do it like this:
swapIndex = (int)(random.Next(0, wordArray.Length));
System.Console.WriteLine("random {0}", swapIndex);

Best way to randomize two identical arrays without overlap?

Suppose we have two identical arrays {"A", "B", "C", "D", "E", "F"}. Is there a quick way to randomize the order of each that ensures when the two are lined up, the same letters are never at the same indices? (Obviously we can just generate a new index if it will cause a match but I'm wondering if there's a way that produces less repetition).
This works, and I think it is fairly easy to understand.
var source = new [] { "A", "B", "C", "D", "E", "F" };
var output1 = (string[])null;
var output2 = (string[])null;
var rnd = new Random();
Action shuffle = () =>
{
output1 = source.OrderBy(x => rnd.Next()).ToArray();
output2 = source.OrderBy(x => rnd.Next()).ToArray();
};
shuffle();
while (output1.Zip(output2, (o1, o2) => new { o1, o2 })
.Where(x => x.o1 == x.o2)
.Any())
{
shuffle();
}
You could do it in two steps with O(n) complexity.
[Step 1]
Shuffle just one array in a way that every letter changes its original position, something like this:
var rnd = new Random(0);
var x = new char[] { 'A', 'B', 'C', 'D', 'E', 'F' };
for(int i = 0; i < x.Length; i++)
{
var j0 = (i == x[i] - 'A')? i + 1: i;
var j = rnd.Next(j0, x.Length);
// x[i] ⟷ x[j]
var t = x[i]; x[i] = x[j]; x[j] = t;
}
It ensures that the first and the second arrays are different in every position.
[Step 2]
Use Fisher–Yates shuffle for both arrays synchronously:
var y = new char[] { 'A', 'B', 'C', 'D', 'E', 'F' };
for(int i = 0; i < x.Length; i++)
{
var j = rnd.Next(i, x.Length);
// x[i] ⟷ x[j]; y[i] ⟷ y[j]
var
t = x[i]; x[i] = x[j]; x[j] = t;
t = y[i]; y[i] = y[j]; y[j] = t;
}
It ensures randomization of both, keeping difference at every position.
My best advice would be to make your own randomizer method that takes 2 arguments: array to be shuffled and array that its not allowed to match.
Here is a quick example of a class that has 2 string arrays that it will be shuffling by calling (objectName).Shuffle();
public class ArrayShuffler {
public String[] arr1;
public String[] arr2;
public ArrayShuffler() {
arr1 = new String[] { "A", "B", "C", "D", "E", "F" };
arr2 = new String[] { "A", "B", "C", "D", "E", "F" };
}
public void Shuffle() {
shuffleArr(arr1);
shuffleArr(arr2, arr1);
}
/// <summary>
/// Can shuffle array, maching against a second array to prevent dublicates in same intex spot.
/// </summary>
/// <param name="arr">Array to be shuffled</param>
/// <param name="validate">Array to mach against</param>
private void shuffleArr(String[] arr, String[] validate = null) {
Random r = new Random();
int indx = 0;
while(indx < arr.Length){
int rIndx = r.Next(indx, arr.Length);
string tmp = arr[indx];
if(validate != null) { //Will only be performed if you specify an array to be matched against.
if(arr[rIndx] != validate[indx]) {
arr[indx] = arr[rIndx];
arr[rIndx] = tmp;
indx++;
}
else if(indx == arr.Length - 1) {
shuffleArr(arr, validate);
}
}
else { //Default operation
arr[indx] = arr[rIndx];
arr[rIndx] = tmp;
indx++;
}
}
}
}
Assuming you're trying to minimize the quantity of unnecessary re-rolls, and that it's the two results that must not match one another (permitting an output character at a particular index to match the character in the input at that index), I think I've got a solution for you.
The gist of it is that we build the resulting strings on-the-fly keeping track of which characters have not been picked in each list and temporarily removing the one we picked first for a particular index from the candidates we select from for the second one. I don't think this method has any bias to it, but I'm admittedly not an expert in that regard.
public void Shuffle(int seed)
{
char[] orig = { 'A', 'B', 'C', 'D', 'E', 'F' };
List<char> buffer1 = new List<char>();
List<char> buffer2 = new List<char>();
// Keep track of which indexes haven't yet been used in each buffer.
List<int> availableIndexes1 = new List<int>(orig.Length);
List<int> availableIndexes2 = new List<int>(orig.Length);
for (int i = 0; i < orig.Length; i++)
{
availableIndexes1.Add(i);
availableIndexes2.Add(i);
}
Random rand = new Random(seed);
// Treat the last 2 specially. See after the loop for details.
for (int i = 0; i < orig.Length - 2; i++)
{
// Choose an arbitrary available index for the first buffer.
int rand1 = rand.Next(availableIndexes1.Count);
int index1 = availableIndexes1[rand1];
// Temporarily remove that index from the available indices for the second buffer.
// We'll add it back in after if we removed it (note that it's not guaranteed to be there).
bool removed = availableIndexes2.Remove(index1);
int rand2 = rand.Next(availableIndexes2.Count);
int index2 = availableIndexes2[rand2];
if (removed)
{
availableIndexes2.Add(index1);
}
// Add the characters we selected at the corresponding indices to their respective buffers.
buffer1.Add(orig[index1]);
buffer2.Add(orig[index2]);
// Remove the indices we used from the pool.
availableIndexes1.RemoveAt(rand1);
availableIndexes2.RemoveAt(rand2);
}
// At this point, we have 2 characters remaining to add to each buffer. We have to be careful!
// If we didn't do anything special, then we'd end up with the last characters matching.
// So instead, we just flip up to a fixed number of coins to figure out the swaps that we need to do.
int secondToLastIndex1Desired = rand.Next(2);
int secondToLastIndex2Desired = rand.Next(2);
// If the "desired" (i.e., randomly chosen) orders for the last two items in each buffer would clash...
if (availableIndexes1[secondToLastIndex1Desired] == availableIndexes1[secondToLastIndex2Desired] ||
availableIndexes1[(secondToLastIndex1Desired + 1) % 2] == availableIndexes2[(secondToLastIndex2Desired + 1) % 2])
{
// ...then swap the relative order of the last two elements in one of the two buffers.
// The buffer whose elements we swap is also chosen at random.
if (rand.Next(2) == 0)
{
secondToLastIndex1Desired = (secondToLastIndex1Desired + 1) % 2;
}
else
{
secondToLastIndex2Desired = (secondToLastIndex2Desired + 1) % 2;
}
}
else if (rand.Next(2) == 0)
{
// Swap the last two elements in half of all cases where there's no clash to remove an affinity
// that the last element has for the last index of the output, and an affinity that the first
// element has for the second-to-last index of the output.
int t = secondToLastIndex1Desired;
secondToLastIndex1Desired = secondToLastIndex2Desired;
secondToLastIndex2Desired = t;
}
buffer1.Add(orig[availableIndexes1[secondToLastIndex1Desired]]);
buffer1.Add(orig[availableIndexes1[(secondToLastIndex1Desired + 1) % 2]]);
buffer2.Add(orig[availableIndexes2[secondToLastIndex2Desired]]);
buffer2.Add(orig[availableIndexes2[(secondToLastIndex2Desired + 1) % 2]]);
Console.WriteLine(new string(buffer1.ToArray()));
Console.WriteLine(new string(buffer2.ToArray()));
}
Note that if this were used for particularly long arrays, then the data moving from List<T>.Remove / List<T>.RemoveAt and the linear searching done by the former may not scale well.

generate 200 numbers with an operator c#

I need to generate in a loop 200 numbers and signs that will create something like this:
1+1 or 20*1252
Is there a way to do this?
I am new to c#. Can someone help?
Random randonNum = new Random();
for (int i = 0; i < 200; i++)
{
int nums = randonNum.Next(0, 500);
//dont know how to continue
}
You seem to know how to generate a random number, so generating two random numbers shouldn't prove any problem. It looks like you're having trouble generating a random "sign", called operators.
You can do so by creating an array containing the possible choices, generating a random index for that array and retrieving that element through the array's indexer as explained in Access random item in list:
var operators = new[] { "+", "-", "/", "*" };
int operatorIndex = randomNum.Next(operators.Length);
var selectedOperator = operators[operatorIndex];
What about using Random for all three factors? Random can be used to find an operator from a list or array too for example.
You could use something like this (where operators is an array of string objects):
string[] operators = new string[] { "+", "-", "*" };
string oper = operators[randonNum.Next(operators.Length)];
Take a look at this working example:
// this list will contain the results
List<string> list = new List<string>();
// create an array of allowed operators
string[] operators = new string[] { "+", "-", "*" };
Random randonNum = new Random();
for (int i = 0; i < 200; i++)
{
// pick two numbers
int num1 = randonNum.Next(0, 500);
int num2 = randonNum.Next(0, 500);
// pick an operator from the array
string oper = operators[randonNum.Next(operators.Length)];
// add it to the list
list.Add(string.Format("{0}{1}{2}", num1, oper, num2));
}
Something like this
string[] operands = new[] {"+", "-", "*", "/"};
Random random = new Random();
List<string> results = new List<string>();
for (int i = 0; i < 200; i++)
{
int firstNum = random.Next(0, 500);
int secondNum = random.Next(0, 500);
string operand = operands[random.Next(0, 3)];
results.Add(string.Format("{0}{1}{2}", firstNum, operand, secondNum));
}

Categories

Resources