How to randomize the word that been get on the textfile - c#

I want to ask if how can I randomize a word that I've get from the textfile data I made.
I already have the word actually from the textfile and stored into an array of character.
Here's what I have so far
I created a method called Shuffle
void Shuffle(string[] chArr)
{
//Shuffle
for (int i = 0; i < chArr.Length; i++)
{
string tmp = chArr[i].ToString();
int r = Random.Range(i, chArr.Length);
chArr[i] = chArr[r];
chArr[r] = tmp;
}
Debug.Log(chArr);
}
and use it like this
string temp = textArray[rowsToReadFrom[0]];
temp = System.Text.RegularExpressions.Regex.Replace(temp, #"\s", "");
char[] chArr = temp.ToCharArray();
string s = chArr.ToString();
string[] ss = new string[] { s };
Shuffle(ss);
foreach (char c in chArr)
{
testObject clone = Instantiate(prefab.gameObject).GetComponent<testObject>();
clone.transform.SetParent(container);
charObjects.Add(clone.Init(c));
//Debug.Log(c);
}
It still doesn't randomize that word I get from the textfile data.
EDITTED
So far here's what I did
string temp = textArray[rowsToReadFrom[0]];
temp = System.Text.RegularExpressions.Regex.Replace(temp, #"\s", "");
char[] chArr = temp.ToCharArray();
string charResult = "";
for(int i = 0; i < chArr.Length; i++)
{
int ran = Random.Range(0, chArr.Length);
charResult += chArr[ran];
}
Debug.Log(charResult);
foreach (char c in charResult)
{
testObject clone = Instantiate(prefab.gameObject).GetComponent<testObject>();
clone.transform.SetParent(container);
charObjects.Add(clone.Init(c));
//Debug.Log(c);
}
But instead of giving me for example the word "Abandon" it would give me sometimes a randomize word "aaaabn" could someone help me out why?

I will be using Fisher–Yates_shuffle
public static string Shuffle(string str)
{
System.Random random = new System.Random();
var array = str.ToCharArray();
for (int i = 0; i < array.Length; i++)
{
int j = random.Next(i, array.Length);
char temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return String.Join("", array);
}
and to use it simply do
var f = "hello";
Console.WriteLine(Shuffle(f));

Your code is just getting random letters from that word but does not exclude duplicate. What you want instead is randomize the array of chars and convert it back to a string
System.Random rnd = new System.Random();
Char[] randomCharArray = chArr.OrderBy(x => rnd.Next()).ToArray();
string charResult = randomCharArray.ToString();
Unity has its own implementation of Random so be sure you use System.Random

it's most easier if you use a list (let call it initial list), (it may have some performance overheat do to shifts on remove, but i'm wonder if using a linked list would solve that...
Here what you can do if you do as i said:
Fill the list, with your words, or char, or any data which you want to randomize
Create another list or array to store randomized data in (result)
create a while loop, and check while, your initial list Has Item (count > 0)
use Random, and performe rand.Next(0, initialList.Count)
take the item within the index of random number and append it to the result list, (or replace free slot if you are using array)
List<string> initial = new List<string>();
initial.AddRange(data);
Random rand = new Random();
List<string> result = new List<string>();
while (initial.Count > 0) // LINQ: initial.Any()
{
int index = rand.Next(0, initial.Count);
result.Add(initial[index]);
initial.RemoveAt(index);
}
return result;

Related

How to add pattern to random? [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 3 years ago.
Improve this question
How to add like number or character pattern to my random keygen?
and is it hard becuse im new to coding :) Thx for Help!
it took me alot of time to get to this and been stuck here for 1 and half day and can't find way to add patterns to this
Like This :
D4B6C5604E26-4F1198-44C1
EA3705694B8A-478E83-2D01
D3B8E2DE7BFC-49CF95-68E6
A6CD996B352A-48B89A-8C69
After - 4 Numbers and After second - 3 Numbers
static void Main(string[] args)
{
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var stringChars = new char[12];
var stringChars4 = new char[6];
var stringChars7 = new char[4];
var random = new Random();
for (int i = 0; i < stringChars.Length; i++)
{
stringChars[i] = chars[random.Next(chars.Length)];
}
for (int i = 0; i < stringChars4.Length; i++)
{
stringChars4[i] = chars[random.Next(chars.Length)];
}
for (int i = 0; i < stringChars7.Length; i++)
{
stringChars7[i] = chars[random.Next(chars.Length)];
}
var finalString = new String(stringChars);
var finalString4 = new String(stringChars4);
var finalString7 = new String(stringChars7);
var chars2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var stringChars2 = new char[12];
var stringChars5 = new char[6];
var stringChars8 = new char[4];
var randoms = new Random();
for (int i = 0; i < stringChars.Length; i++)
{
stringChars2[i] = chars2[random.Next(chars.Length)];
}
for (int i = 0; i < stringChars5.Length; i++)
{
stringChars5[i] = chars2[random.Next(chars.Length)];
}
for (int i = 0; i < stringChars8.Length; i++)
{
stringChars8[i] = chars2[random.Next(chars.Length)];
}
var finalString2 = new String(stringChars2);
var finalString8 = new String(stringChars8);
var finalString5 = new String(stringChars5);
var chars3 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var stringChars3 = new char[12];
var stringChars6 = new char[6];
var stringChars9 = new char[4];
var randomss = new Random();
for (int i = 0; i < stringChars3.Length; i++)
{
stringChars3[i] = chars3[random.Next(chars3.Length)];
}
for (int i = 0; i < stringChars6.Length; i++)
{
stringChars6[i] = chars3[random.Next(chars3.Length)];
}
for (int i = 0; i < stringChars9.Length; i++)
{
stringChars9[i] = chars3[random.Next(chars3.Length)];
}
var finalString3 = new String(stringChars3);
var finalString6 = new String(stringChars6);
var finalString9 = new String(stringChars9);
Console.WriteLine("Keys:");
Console.WriteLine();
Console.ReadKey();
Console.WriteLine(finalString + "-" + finalString4 + "-" + finalString7);
Console.WriteLine();
Console.ReadKey();
Console.WriteLine(finalString2 + "-" + finalString5 + "-" + finalString8);
Console.WriteLine();
Console.ReadKey();
Console.WriteLine(finalString3 + "-" + finalString6 + "-" + finalString9);
Console.WriteLine();
Console.ReadKey();
}
Assuming you are looking for "get string of random characters (from given set of characters) that formatted to given specification like 'xxx-xx-xxxx!xxx' where 'x' is random character".
Regex.Replace is a nice way to construct such string - it let you run arbitrary code to construct replacement - so replacing every 'x' with randomly selected character will produce result you seem to be looking for:
var r = new Random();
// convert string to array of strings for individual characters as Replace wants strings
var charsAsStrings = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
.Select(x=>x.ToString()).ToArray();
var result = Regex.Replace("xxx-xxx", "x",
m => charsAsStrings[r.Next(charsAsStrings.Length)]));
Notes:
make sure to read Random number generator only generating one random number to properly instantiate Random.
random numbers/strings are not unique. Presumably you will store them in some sort of list/database and re-generate the once that are not unique
using similarly-looking symbols like 'O' and '0' (or 'I', 'l','1') in strings that may need to be read by humans is not the best idea.
Create a function for the code generation, it makes the main method more readable.
private static readonly Random _random = new Random();
private static string CreateCode()
{
var bytes = new byte[11];
_random.NextBytes(bytes);
string s = BitConverter.ToString(bytes).Replace("-", "");
string result = new StringBuilder(s)
.Insert(18, '-')
.Insert(12, '-')
.ToString();
return result;
}
static void Main(string[] args)
{
const int N = 3;
var codes = new string[N];
for (int i = 0; i < N; i++) {
codes[i] = CreateCode();
Console.WriteLine(codes[i]);
}
}
I use the Random.NextBytes method to generate random bytes. We need 11 of them, because one byte is represented by 2 hex positions.
Your codes are in hexadecimal format, i,e, they contain only the letters A - F and digits. This solution uses the BitConverter to format a byte array as hexadecimal string. It produces strings like ""BD-EB-1F-0C-9B-9E-0C-F5-6E-2E-46". Therefore it is necessary to remove the "-" first.
Then I convert the string into a StringBuilder. The latter one has a Insert method that we can use to insert dashes at the required places. I insert the second one first, so that the index of the other one is not shifted.
You could also simply call Console.WriteLine(CreateCode()); three times and not create the codes array. But if you want to do other things with the codes, like saving them to a file or copy them to the cilpboard, it's better to store them somewhere.

Randomize string in C#

I am trying to randomize string elements, but my code is repeating strings. Can someone explain what is wrong with my code?
string[] words = Console.ReadLine().Split();
//input = "Welcome and have fun learning programming"
Random number = new Random();
for (int i = 0; i < words.Length; i++)
{
int currRandomNumber = number.Next(0, words.Length);
words[i] = words[currRandomNumber];
}
Console.WriteLine(string.Join(' ', words));
//output = "have learning learning learning learning programming"
I am facing problems with the words repeating, and it is not randomized? If you don't understand what I mean, see the comments which I added in the code. Any help will be appreciated!
The words are repeating because you are doing this:
words[i] = words[currRandomNumber];
The line means "copy the word at index currRandomNumber to the index i". As long as i and currRandomNumber are different, you are guaranteed to have a duplicate word.
What you meant to do was probably to swap the words at currRandomNumber and i:
var temp = words[i];
words[i] = words[currRandomNumber];
words[currRandomNumber] = temp;
// in C# 7, you could swap two values very easily by:
// (words[currRandomNumber], words[i]) = (words[i], words[currRandomNumber]);
Alternatively, you could use a Fisher Yates shuffling algorithm, which makes sure that each permutation have equal chances of occurring:
static void Shuffle<T>(T[] array)
{
int n = array.Length;
for (int i = 0; i < n; i++)
{
int r = i + _random.Next(n - i);
T t = array[r];
array[r] = array[i];
array[i] = t;
}
}
// Shuffle(words);
Alternatively, you can put each of the words into a new list in a random order:
List<string> words = Console.ReadLine().Split().ToList();
//input = "Welcome and have fun learning programming"
Random number = new Random();
var newwords = new List<string> ();
while (words.Count > 0)
{
int currRandomNumber = number.Next(0, words.Count);
newwords.Add( words[currRandomNumber]);
words.RemoveAt(currRandomNumber);
}
Console.WriteLine(string.Join(' ', newwords));

Convert Ienumerable<int> to array and add to list C#

I have a simple code:
List<int[]> list = new List<int[]>();
for (int i = 0; i < x; i++)
{
var vec = vector.Skip(index).Take(width);
var v = vec.ToArray();
list.Add(v);
index = index + width;
}
string toDisplay = string.Join(Environment.NewLine, list);
MessageBox.Show(toDisplay);
This is vector:
int[] vector = new int[length];
Random z = new Random();
for (int i = 0; i < length; i++)
{
vector[i] = z.Next(-100, 100);
}
What I want to do is to slice my vector on smaller vectors and add them to list of int. Using my code I only get System.Int32[] in MessageBox. I know that maybe my code it's not the right way. I barely know C#.
How can I do this in other way?
Apparently you mean to slice the initial array into smaller chunks and display them in a single line. This can be done using Linq as follows.
var StringToDisplay
= String.Join(Environment.NewLine, list.Select(iList => String.Join(",", iList)));
List<int[]> list is a list of arrays, not numbers. Calling ToString() on an array uses Object.ToString() which returns the object's (array's) type.
If you want to display a list of pages, you should change your string construction code to work with the inner arrays. One option is to use LINQ :
var lines=from page in list
select string.Join(",", page);
string toDisplay = string.Join(Environment.NewLine, lines);
It's better to use StringBuilder though, to avoid generating a lot of temporary strings:
var builder=new StringBuilder();
foreach(var page in list)
{
builder.AppendLine(string.Join(",", page));
}
string toDisplay = builder.ToString();
If you want a list of numbers change the list type to List. You can also simplify the code by using AddRange, eg :
List<int> list = new List<int>();
for (int i = 0; i < x; i++)
{
var vec = vector.Skip(index).Take(width);
list.AddRange(vec);
index = index + width;
}
string toDisplay = string.Join(Environment.NewLine, lines);

Array.Copy and accessing string array with variable

I've tried several things and just cannot seem to get this. I have 10 MotorReply strings that I then split into array elements. Then I want to copy those elements to another array so I can loop through again but whatever I try, I can't access the BayReplyArray by using the incrementing i variable, i.e. BayReplyArray[i]
Declarations:
string[] MotorReplyArray = new string[30];
string[] BayReplyArray1 = new string[30];
string[] BayReplyArray2 = new string[30];
string[] BayReplyArray3 = new string[30];
up to 10
int j = 0;
for (int i = 1; i < 11; i++)
{
// here we take the Motor? reply string for each bay and split the parameters into individual string arrays
char[] delimiters = new char[] { '\r', ':' };
MotorReplyArray = MotorReply[i].Split(delimiters);
foreach (string line in MotorReplyArray)
{
// trim whitespace from ends
MotorReplyArray[j] = line.Trim();
j++;
}
Array.Copy(MotorReplyArray, BayReplyArray[i], j);
Array.Clear(MotorReplyArray, 0, j);
j = 0;
}
I can't access the BayReplyArray by using the incrementing i variable, i.e. BayReplyArray[i]
You seem to think that if i is 1 then BayReplyArray[i] is the same as BayReplyArray1, which is not the case. You can easily enough change to a jagged array:
string[] MotorReplyArray = new string[30];
string[][] BayReplyArray = new string[][10];
now BayReplyArray[i] is a string array and you can use Array.Copy on it.

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.

Categories