how to generate random characters in various text boxes [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have tried variations of code for this, but some of the characters are repeating in the text boxes.
I want seven different characters in seven text boxes.
See picture for reference.... thank you in advance

Random rnd = new Random();
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sevenRandomChars = chars.OrderBy(_ => rnd.Next()).Take(7).ToList();

The simplest way is:
// The 26 letters, A...Z, in a char[] array
char[] letters = Enumerable.Range(0, 26).Select(x => (char)('A' + x)).ToArray();
Take all the 26 upper case letters
// http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
public static void Shuffle<T>(IList<T> list, Random r)
{
for (int i = list.Count - 1; i > 0; i--)
{
int j = r.Next(0, i + 1);
// Do the swap
T temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
// This is the method that does the shuffling
Shuffle(letters, new Random());
Shuffle them with the Fisher-Yates algorithm,
and take the first 7 elements of the shuffled letters array letters[0]...letters[6]. In this way you are gauranteed that the letters are unique, and that each letter has the same chance of being used.
An even easier way to do it:
// The 26 letters, A...Z, in a List<char>!
List<char> letters = Enumerable.Range(0, 26).Select(x => (char)('A' + x)).ToList();
Random r = new Random();
// The letters you "select"
char[] usedLetters = new char[7];
for (int i = 0; i < usedLetters.Length; i++)
{
int j = r.Next(0, letters.Count);
usedLetters[i] = letters[j];
// When you select a letter, you remove it!
letters.RemoveAt(i);
}
When you select a letter, you remove it. In this way any one letter can be used 0...1 times.

Related

script to mask a string in C#? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have a code where if i pass a inputdata as "sail" my code will generate a masked output such as "aisl" or "isal". where the output will be jumbled format of input. I want to have a output which should not generate the output with the same exact letters in the input.Below is my current code and please help me with this
string InputData = "123456";
string MaskedData = InputData;
if (MaskedData.Length > 0)
{
// The technique used to mask the data is to replace numbers with random numbers and letters with letters
//char[] chars = new char[InputData.Length];
char[] chars = new char[InputData.Length];
Random rand = new Random(DateTime.Now.Millisecond);
int index = 0;
while (InputData.Length > 0)
{
// Get a random number between 0 and the length of the word.
int next = rand.Next(0, InputData.Length - 1);
// Take the character from the random position and add to our char array.
//chars[index] = InputData[next];
chars[index] = InputData[next];
// Remove the character from the word.
InputData = InputData.Substring(0, next) + InputData.Substring(next + 1);
++index;
}
MaskedData = new String(chars);
}
In this page in dotnetperls.com there is an algorithm that randomizes an array of strings. With a few changes you can use it to randomize a string, using the fact that a string is also an array of chars. Here you have:
static class RandomCharArrayTool
{
static Random _random = new Random();
public static string RandomizeChars(string theString)
{
var arr = theString.ToCharArray();
List<KeyValuePair<int, char>> list = new List<KeyValuePair<int, char>>();
// Add all strings from array
// Add new random int each time
foreach (char s in arr)
{
list.Add(new KeyValuePair<int, char>(_random.Next(), s));
}
// Sort the list by the random number
var sorted = from item in list
orderby item.Key
select item;
// Allocate new string array
char[] result = new char[arr.Length];
// Copy values to array
int index = 0;
foreach (KeyValuePair<int, char> pair in sorted)
{
result[index] = pair.Value;
index++;
}
// Return string generated from copied array
return new string(result);
}
}
You use it like this:
RandomCharArrayTool.RandomizeChars("sail");
Please try with the below code snippet.
Mehtod 1:
string word = "123456";
string temp = word;
string result = string.Empty;
Random rand = new Random();
for (int a = 0; a < word.Length; a++)
{
//multiplied by a number to get a better result, it was less likely for the last index to be picked
int temp1 = rand.Next(0, (temp.Length - 1) * 3);
result += temp[temp1 % temp.Length];
temp = temp.Remove(temp1 % temp.Length, 1);
}
string str = result;
Method2:
var rnd = new Random();
string InputData = "123456";
string MaskedData = new string(InputData.OrderBy(r => rnd.Next()).ToArray());
You have several different approaches, however the easiest may be to implement a SecureString or a Hash. One of those two would encrypt your data quite easily. Under the notion the mask is to hide said contents.
// SecureString
var secure = new SecureString();
foreach(var character in textbox.Text.ToCharArray())
secure.AppendChar(character);
Once your string is placed on memory, it would be encrypted on memory. That is a rough implementation, but documentation will help you refine the approach to your needs.
// Hash (BCrypt for simplicity)
private const int factor = 12;
var hashed = BCrypter.HashPassword(textbox.Text, BCrypter.GenerateSalt(factor));
Another approach would simply be randomization, similar to a word shuffle. Like the other answers have demonstrated.

Range of a string program [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This is a program to get all the letters in a string in a specified range (in this case characters 3 through 7 of the word 'kangaroo').
Why am i getting an error at line arr[i] = x[start+i];?
I am not using Substring because my instructor wants us to figure out how to do it without it as an exercise.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MethodsPractice2
{
class Program
{
static char[] GetRangeOfCharacters(string word, int start, int end)
{
string x = word;
char[] arr = new char[end - start];
for (int i = 0; i < end; i++)
{
arr[i] = x[start + i];
}
return arr;
}
private static void Main(string[] args)
{
char[] endResult;
string word = "kangaroo";
int start = 3;
int end = 7;
endResult = GetRangeOfCharacters(word, start, end);
Console.WriteLine(endResult);
}
}
}
I'll explain the error you are getting,
You have said that you wish to start at character 3, and fill arr which is has 4 entries, with the characters that start at (3) + i
i can be any number less than 7.. 3 + 6 = 9; and Kangaroo has 8 letters in it... therefore you for loop at the minimum needs to go to
i < (end - start)
The other error could could get is i >= 4 in which case it would be trying to access arr[4] which is also out of range
0123456789
kangaroo
garo## /// what arr would be - # = error
garoo# // where i would get you - # = error
If you're looking for the easiest way to print part of the string, the easiest way, as mentioned in the comments, is with the String.Substring method.. To get characters #3-7 of the word kangaroo, you could use:
String.Substring(2,5);
The 2 is the starting index (it's 0-based, so 2 is the third character), and 5 is the length.
If you need the array of characters (as your return type indicates), you could try using the String.ToCharArray method, which functions the same way:
x.ToCharArray(2,5)
Because you take too many characters in the loop:
static char[] GetRangeOfCharacters(string word, int start, int end)
{
string x = word;
char[] arr = new char[end - start];
for (int i = 0; i < end; i++) // <--- here!!!
{
arr[i] = x[start + i];
}
return arr;
}
Correct would be
for (int i = 0; i < end - start; i++)
I would use this instead (skipped invalid argument check):
static char[] GetRangeOfCharacters(string word, int start, int end)
{
return word.Skip(start).Take(end - start).ToArray();
// or more efficient: word.Substring(start, end - start).ToCharArray();
}
end is 7 so you are looping from 0 to 7 and so going at subscripts 3 to 10
so
for (int i = 0; i < end; i++)
should be
for (int i = 0; i < (end - start); i++)
or perhaps even clearer
for (int i = 0; i < arr.Length; i++)
You're overflowing your array, arr[] by 1. Quanity (end-start) gives you one less than the size of your range.
You need to use quantity (end-start+1) to size your target array.
arr is an array with 4 slots (7 - 3).
But the code:
for (int i = 0; i < end; i++)
will loop 7 times (because end == 7), trying to write to a new position of arr on every iteration.
Q: How can you store 7 distinct values to an array with only 4 slots?
A: You can't!
(Your for-loop needs different constraints).
Well end is 7, start is 3. 3 + 6 is 9. Kangaroo is only of length 8 so you're gonna get an index out of range exception (looping while i < end, and adding i to start to get the index). As others have suggested you should use substring instead of your current method.
string subString;
if (end - start < 0)
subString = null; // error!
else
subString = myWord.SubString(start, end - start);
Might also want to check that start and end are both less than myWord.Length

C# random letter generator with specified ratio of consonants:vowels

I need to create code to scatter 50 random letters into the console (It's a "Snake" game); that part, I didn't have a problem with. I used this code to generate the letters (the "scatter them around the console" part I'm handling once I know how to fix the problem)
Random rand = new Random();
int number = rand.Next(0, 26);
char letter = (char)('a' + number);
It generates random letters just fine, but the instructions for the problem specify the ratio of consonants to vowels must be 4:1, and I have no idea how to make that part happen.
Create a pair of static strings:
String consonants = "BCDFGHJKLMNPQRSTVWXYZ";
String vowels = "AEIOU";
Generate a random number between 1..5 (or 0..4). If the number is 1 (0), pick a random character from the vowels list. Otherwise pick a random character from the consonants list.
Alternately, if you need exactly the ratio of 4:1, use a for-loop in place of the first random number generator, to wit:
for ( i = 0; i < 50; i++ )
{
if ( i % 5 == 0 )
// select a vowel at random
else
// select a consonant at random
}
EDIT: Complete solution. I'm writing my fifty characters to an array then printing them to the console. You can pass theChar to your output method.
public void RandomChars()
{
Random random = new Random();
String consonants = "BCDFGHJKLMNPQRSTVWXYZ";
String vowels = "AEIOU";
StringBuilder result = new StringBuilder();
for (int i = 0; i < 50; i++)
{
char theChar;
if (i % 5 == 0)
{
theChar = vowels[random.Next(vowels.Length)];
}
else
{
theChar = consonants[random.Next(consonants.Length)];
}
result.Append(theChar);
}
Console.WriteLine(result.ToString());
}

Insert random amount of dots to string with minimum different places?

I want to insert a random amount of dots (from 1 to 7) on random parts of a string without breaking the layout.
This is my current code:
Random rand = new Random();
string[] words = iTemplate.Text.Split(' ');
string result = string.Empty;
for (int i = 0; i < words.Count(); i++)
{
string word = words[i];
if (rand.Next(i, words.Count()) == i)
{
for (int dots = rand.Next(1, 7); dots > 0; dots--)
word += ".";
}
result += word + " ";
}
Is there a more efficient or nice LINQ option to it ?
Right now, since its random, there may be cases of no dots showing up. I have narrowed it by using if (rand.Next(i, words.Count()) == i) which seems to work but still some results only show 1 to 3 places having dots inserted.
How could I guarantee that the dots are inserted a minimum of 4 different places during the process ?
Sample data/result as per comment request:
string template = "Hi, this is a template with several words on it and I want to place random dots on 4 different random places every time I run the function";
Result 1:
string result = "Hi, this... is a template with several.. words on it and. I want to place random dots on 4 different random...... places every time I run the function";
Result 2:
string result = "Hi, this is a template. with several... words on it and I want to..... place random dots on 4 different random. places every time I run the function";
Result 3:
string result = "Hi, this. is a template with... several words on it and I want to place random.. dots on 4 different random....... places every time I run the.. function";
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Program
{
static void Main(string[] args)
{
Random rand = new Random();
string[] words = "Now is the time for all good men to come to the aid of their countrymen".Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (words.Length > 0)
{
// Generate a list of integers from 0 to words.Length - 1
List<int> addIndices = Enumerable.Range(0, words.Length).ToList();
// Shuffle those indices
Shuffle(addIndices, rand);
// Pick the number of words that will have dots added
int addCount = rand.Next(4, Math.Max(4, words.Length));
// Truncate the array so that it only contains the first addCount items
addIndices.RemoveRange(addCount, addIndices.Count - addCount);
StringBuilder result = new StringBuilder();
for (int i = 0; i < words.Length; i++)
{
result.Append(words[i]);
if (addIndices.Contains(i)) // If the random indices list contains this index, add dots
result.Append('.', rand.Next(1, 7));
result.Append(' ');
}
Console.WriteLine(result.ToString());
}
}
private static void Shuffle<T>(IList<T> array, Random rand)
{
// Kneuth-shuffle
for (int i = array.Count - 1; i > 0; i--)
{
// Pick random element to swap.
int j = rand.Next(i + 1); // 0 <= j <= i
// Swap.
T tmp = array[j];
array[j] = array[i];
array[i] = tmp;
}
}
}
This will ensure that you add dots to at least 4 words, as well as not adding a trailing space to your final string.
Random rand = new Random();
string[] words = iTemplate.Text.Split(' ');
// Insert dots onto at least 4 words
int numInserts = rand.Next(4, words.Count());
// Used later to store which indexes have already been used
Dictionary<int, bool> usedIndexes = new Dictionary<int, bool>();
for (int i = 0; i < numInserts; i++)
{
int idx = rand.Next(1, words.Count());
// Don't process the same word twice
while (usedIndexes.ContainsKey(idx))
{
idx = rand.Next(1, words.Count());
}
// Mark this index as used
usedIndexes.Add(idx, true);
// Append the dots
words[idx] = words[idx] + new String('.', rand.Next(1, 7));
}
// String.Join will put the separator between each word,
// without the trailing " "
string result = String.Join(" ", words);
Console.WriteLine(result);
This code assumes that you do in fact have at least 4 words in iTemplate.Text. If there's a chance that you won't, you should add some additional validation logic.
Well, if you need at least 4 different places, you need at least four dots. You do it in two parts - first choose the 4 words that get a dot at the end (that is, choose a word at random, add a dot to it, and make sure you don't choose it again), then choose 3 words at random, with repetitions, and add dots to them.
Just for fun and as terse as I can make it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var random = new Random();
var iTemplate = "Hi, this is a template with several words on it and I want to place random dots on 4 different random places every time I run the function";
var result = iTemplate;
while (new Regex("\\. ").Matches(result).Count < 4)
result = result.TrimEnd()
.Split(' ')
.Aggregate(
string.Empty,
(current, word) =>
current + (word + (((word.EndsWith(".") || (random.Next(1, 100) % 10) != 0)) ? "" : new string('.', random.Next(1, 7))) + " ")
);
Console.WriteLine(result);
Console.Read();
}
}
}

Linear Search Problem [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
My program has no compile errors but the output is incorrect. Example input:
size of array: 5
input numbers: 5 4 3 2 1
//sorted: 1 2 3 4 5
search: 1
output: number 1 found at index 4
the output should be number 1 found at index 0 since the numbers were sorted already. How will I change it to this.
int[] nums = new int[100];
int SizeNum;
bool isNum = false;
private void ExeButton_Click(object sender, EventArgs e)
{
int i, loc, key;
Boolean found = false;
string SizeString = SizeTextBox.Text;
isNum = Int32.TryParse(SizeString, out SizeNum);
string[] numsInString = EntNum.Text.Split(' '); //split values in textbox
for (int j = 0; j < numsInString.Length; j++)
{
nums[j] = int.Parse(numsInString[j]);
}
if (SizeNum == numsInString.Length)
{
Array.Sort(numsInString);
key = int.Parse(SearchTextBox.Text);
ResultText.AppendText("Sorted: ");
for (i = 0; i < SizeNum; i++)
ResultText.AppendText(" " + numsInString[i]);
ResultText.AppendText("\n\n");
{
for (loc = 0; loc < SizeNum; loc++)
{
if (nums[loc] == key)
{
found = true;
break;
}
}
if (found == true)
ResultText.AppendText("Number " + key + " Found At Index [" + loc + "]\n\n");
else
ResultText.AppendText("Number " + key + " Not Found!\n\n");
}
}
}
You're sorting numsInString but then searching nums. nums is being populated before the search, so you're seeing the results of searching the unsorted numbers.
Once you've parsed numsInStrings into nums, you should be working with the latter array only. Make sure that's the one you're sorting and searching through.
In other words, once you replace the current sort call with
Array.Sort(nums);
your code will be fine.
Updated:
You actually need another fix. Right now, you're initializing nums to be an array of size 100. By default, each element will be 0. So even though you put numbers in the first five elements, when you sort the array, you end up with 95 0's, followed by 1 2 3 4 5.
You should delay initializing nums until you've seen how big numsInString is:
string[] numsInString = EntNum.Text.Split(' '); //split values in textbox
nums = new int[numsInString.Length];
for (int j = 0; j < numsInString.Length; j++)
{
nums[j] = int.Parse(numsInString[j]);
}
Now when you sort nums, you'll see only the numbers you entered.
you are sorting the numsInString array, but still searching into the nums array.
for (loc = 0; loc < SizeNum; loc++)
{
if (numsInString[loc] == key)
{
found = true;
break;
}
}
You're parsing numsInString then you're sorting it. (I suspect the sort won't do what you want, either.)
I think you really want to be sorting nums instead:
Array.Sort(nums);
Having said that, there are simpler ways of achieving the end result - such as using IndexOf to find the index of a value in an array.
It's also rather unclear why you've got braces here:
for (i = 0; i < SizeNum; i++)
ResultText.AppendText(" " + numsInString[i]);
ResultText.AppendText("\n\n");
{
...
}
That makes it look like you've got a loop with a body, but it's actually equivalent to:
for (i = 0; i < SizeNum; i++)
{
ResultText.AppendText(" " + numsInString[i]);
}
ResultText.AppendText("\n\n");
{
...
}
... the braces serve no purpose here, and merely harm readability.

Categories