I have a word, for example:
qwerty
I want to add a dot between each char, but also take into consideration all possible cases.
For example, output should be:
qwerty
qwert.y
qwer.ty
qwer.t.y
qwe.rty
qwe.rt.y
qwe.r.ty
qwe.r.t.y
qw.erty
qw.ert.y
qw.er.ty
qw.er.t.y
qw.e.rty
qw.e.rt.y
qw.e.r.ty
qw.e.r.t.y
q.werty
q.wert.y
q.wer.ty
q.wer.t.y
q.we.rty
q.we.rt.y
q.we.r.ty
q.we.r.t.y
q.w.erty
q.w.ert.y
q.w.er.ty
q.w.er.t.y
q.w.e.rty
q.w.e.rt.y
q.w.e.r.ty
q.w.e.r.t.y
I have so far this code:
private void button12_Click(object sender, EventArgs e)
{
int maxPossibilities = Convert.ToInt32(Math.Pow(2.0, txtInput.Text.Length));
List<string> allPossibilities = new List<string>();
for (int i = 0; i < maxPossibilities; i++)
{
string result = "";
string added = Convert.ToString(i, 2).PadLeft(txtInput.Text.Length - 1);
for (int j = 0; j < txtInput.Text.Length; j++)
{
result += txtInput.Text[j] + ((j < txtInput.Text.Length - 1) && (added[j].Equals('1')) ? "." : "");
}
allPossibilities.Add(result);
}
}
I am getting the following output:
qwerty
qwert.y
qwer.ty
qwer.t.y
qwe.rty
qwe.rt.y
qwe.r.ty
qwe.r.t.y
qw.erty
qw.ert.y
qw.er.ty
qw.er.t.y
qw.e.rty
qw.e.rt.y
qw.e.r.ty
qw.e.r.t.y
q.werty
q.wert.y
q.wer.ty
q.wer.t.y
q.we.rty
q.we.rt.y
q.we.r.ty
q.we.r.t.y
q.w.erty
q.w.ert.y
q.w.er.ty
q.w.er.t.y
q.w.e.rty
q.w.e.rt.y
q.w.e.r.ty
q.w.e.r.t.y
q.werty
q.werty
q.wert.y
q.wert.y
q.wer.ty
q.wer.ty
q.wer.t.y
q.wer.t.y
q.we.rty
q.we.rty
q.we.rt.y
q.we.rt.y
q.we.r.ty
q.we.r.ty
q.we.r.t.y
q.we.r.t.y
q.w.erty
q.w.erty
q.w.ert.y
q.w.ert.y
q.w.er.ty
q.w.er.ty
q.w.er.t.y
q.w.er.t.y
q.w.e.rty
q.w.e.rty
q.w.e.rt.y
q.w.e.rt.y
q.w.e.r.ty
q.w.e.r.ty
q.w.e.r.t.y
q.w.e.r.t.y
There are some duplicates in the output, but shouldn't be. Any help is appreciated.
Here is a slight variation on your algorithm that looks at the bits of i to determine which positions should get dots:
string input = "qwerty";
int maxPossibilities = Convert.ToInt32(Math.Pow(2.0, input.Length));
List<string> allPossibilities = new List<string>();
for(int i = 0; i < maxPossibilities; ++i)
{
string result = "";
for(int j = 0; j < input.Length; j++)
{
result += input[j];
if((i & (1 << j)) != 0) { result += "."; }
}
allPossibilities.Add(result);
System.Console.WriteLine(result);
}
If you're just looking to not add the item to the list if it's already there then, try this:
Change
allPossibilities.Add(result);
To
if (!allPossibilities.Contains(result)) { allPossibilities.Add(result); }
try this code, I know it's a little bit too much, but it's structured and I use bitmask for putting dot between characters.
static void Main(string[] args)
{
Do("qwerty");
}
public static void Do(string text)
{
int i = 1;
Text output = new Text();
output.Add(new Dot(i));
i = i * 2;
foreach(char c in text)
{
output.Add(new textChar(c));
output.Add(new Dot(i));
i = i * 2;
}
int possibilites = output.Possibilites;
for (i = 0; i < possibilites; i++)
{
Console.WriteLine(output.ToString(i));
}
}
public class Text
{
public List<character> characters = new List<character>();
public void Add(character c)
{
characters.Add(c);
}
public int Possibilites
{
get
{
return Convert.ToInt32(Math.Pow(2, characters.Count(C => C is Dot)));
}
}
public string ToString(int i)
{
string output = "";
foreach (character c in characters)
{
if (c is textChar)
{
output += c.c;
}
else if (c is Dot)
{
if ((i & ((Dot)c).index) != 0)
output += c.c;
}
}
return output;
}
}
public class character
{
public char c { set; get; }
}
public class textChar : character
{
public textChar(char c)
{
this.c = c;
}
}
public class Dot : character
{
public int index;
public Dot(int i)
{
index = i;
c = '.';
}
}
Another solution which works.
Here the positions of the dots get saved as a matrix in the binarycount List as booleans. They define where the dots will be.
static void Main(string[] args)
{
Console.WriteLine(String.Join(Environment.NewLine, printPossibilities("qwerty")));
}
private static List<string> printPossibilities(string str)
{
List<string> allPossibilities = new List<string>();
List<bool> binarycount = new List<bool>();
for (int i = 0; i < str.Length - 1; i++) {
binarycount.Add(false);
}
bool hasNext = true;
while(hasNext)
{
string temp = str;
for (int i = binarycount.Count - 1; i >= 0; i--)
{
if (binarycount[i])
temp = temp.Insert(i+1, ".");
}
allPossibilities.Add(temp);
hasNext = false;
for (int i = binarycount.Count - 1; i >= 0; i--)
{
if (binarycount[i]) {
binarycount[i] = false;
} else {
binarycount[i] = true;
hasNext = true;
break;
}
}
}
return allPossibilities;
}
output:
qwerty
qwert.y
qwer.ty
qwer.t.y
qwe.rty
qwe.rt.y
qwe.r.ty
qwe.r.t.y
qw.erty
qw.ert.y
qw.er.ty
qw.er.t.y
qw.e.rty
qw.e.rt.y
qw.e.r.ty
qw.e.r.t.y
q.werty
q.wert.y
q.wer.ty
q.wer.t.y
q.we.rty
q.we.rt.y
q.we.r.ty
q.we.r.t.y
q.w.erty
q.w.ert.y
q.w.er.ty
q.w.er.t.y
q.w.e.rty
q.w.e.rt.y
q.w.e.r.ty
q.w.e.r.t.y
Related
This is the code I'll try. But I got wrong output. Replace * in string by character in c#. Example p**gra* replace * by rom the output will be program.
namespace Uncensor
{
class Program
{
// "*h*s *s v*ry *tr*ng*", "Tiiesae" ➜ "This is very strange"
static string uncensor(string str,string s)
{
string s1 = "";
int i, j;
if (str.Contains("*"))
{
for (i = 0; i < str.Length; i++)
{
if (str[i] == '*')
{
for (j = 0; j < s.Length; j++)
{
s1 = str.Replace(str[i], s[j]);
}
}
}
return s1;
}
else
{
return str;
}
}
static void Main(string[] args)
{
Console.WriteLine("Enter string:");
string str = Console.ReadLine();
Console.WriteLine("Enter string to be replaced by * :");
string s = Console.ReadLine();
string original_text= uncensor(str, s);
Console.WriteLine(original_text);
Console.Read();
}
}
}
This is easy with linq:
string a = "*h*s *s v*ry *tr*ng*";
string b = "Tiiesae";
int index = 0;
string c = new string(a.Select(x => x == '*' ? b[index++] : x).ToArray());
public string solve(string str, string s)
{
int index = 0;
for(int i = 0; i < str.Length; ++i)
{
if(str[i] == '*') {
str[i] = s[index];
++index;
}
return str;
}
Give two strings of equal size. Determine whether each character in the first string can be uniquely replaced by a character in the second string so that the two strings are equal. Display also the corresponding character pairs between the two strings. The code works well now.
Example 1:
For input data:
aab
ttd
The console will display:
True
a => t
b => d
Example 2:
For input data:
tab
ttd
The console will display:
False
In the second example the answer is false because there is no unique correspondence for the character 'a': both 't' and 'd' correspond to it.
This is my code:
using System;
namespace problemeJM
{
class Program
{
static void Main(string[] args)
{
string firstPhrase = Convert.ToString(Console.ReadLine());
string secondPhrase = Convert.ToString(Console.ReadLine());
string aux1 = string.Empty, aux2 = string.Empty;
bool x = true;
for (int i = 0; i < firstPhrase.Length; i++)
{
if (!aux1.Contains(firstPhrase[i]))
{
aux1 += firstPhrase[i];
}
}
for (int i = 0; i < secondPhrase.Length; i++)
{
if (!aux2.Contains(secondPhrase[i]))
{
aux2 += secondPhrase[i];
}
}
if (aux1.Length != aux2.Length)
{
Console.WriteLine("False");
}
else
{
for (int i = 0; i < firstPhrase.Length - 2; i++)
{
for (int j = 1; j < secondPhrase.Length - 1; j++)
{
if (firstPhrase[i] == firstPhrase[j] && secondPhrase[i] == secondPhrase[j])
{
x = true;
}
else if (firstPhrase[i] != firstPhrase[j] && secondPhrase[i] != secondPhrase[j])
{
x = true;
}
else if (firstPhrase[i] == firstPhrase[j] && secondPhrase[i] != secondPhrase[j])
{
x = false;
break;
}
else if (firstPhrase[i] != firstPhrase[j] && secondPhrase[i] == secondPhrase[j])
{
x = false;
break;
}
}
}
Console.WriteLine(x);
aux1 = string.Empty;
aux2 = string.Empty;
if (x == true)
{
for (int i = 0; i < firstPhrase.Length; i++)
{
if (!aux1.Contains(firstPhrase[i]))
{
aux1 += firstPhrase[i];
}
}
for (int i = 0; i < secondPhrase.Length; i++)
{
if (!aux2.Contains(secondPhrase[i]))
{
aux2 += secondPhrase[i];
}
}
for (int i = 0; i <= aux1.Length - 1; i++)
{
for (int j = 1; j <= aux2.Length; j++)
{
if (aux1[i] == aux1[j] && aux2[i] == aux2[j])
{
Console.WriteLine(aux1[i] + " => " + aux2[i]);
break;
}
else if (aux1[i] != aux1[j] && aux2[i] != aux2[j])
{
Console.WriteLine(aux1[i] + " => " + aux2[i]);
break;
}
}
}
}
}
}
}
}
I think you should use a Dictionary<char, char> as commented. But you need to check if there's a unique mapping in both string, so from s1 to s2 and from s2 to s1:
static bool UniqueMapping(string s1, string s2)
{
int length = Math.Min(s1.Length, s2.Length);
var dict = new Dictionary<char, char>(length);
for (int i = 0; i < length; i++)
{
char c1 = s1[i];
char c2 = s2[i];
bool contained = dict.TryGetValue(c1, out char c);
if (contained && c2 != c)
{
return false;
}
dict[c1] = c2;
}
return true;
}
Here are your samples. Note that i use UniqueMapping twice(if true after 1st):
static void Main(string[] args)
{
var items = new List<string[]> { new[]{ "aab", "ttd" }, new[] { "tab", "ttd" }, new[] { "ala bala portocala", "cuc dcuc efghficuc" }, new[] { "ala bala portocala", "cuc dcuc efghijcuc" } };
foreach (string[] item in items)
{
bool result = UniqueMapping(item[0], item[1]);
if(result) result = UniqueMapping(item[1], item[0]);
Console.WriteLine($"Word 1 <{item[0]}> Word 2 <{item[1]}> UniqueMapping? {result}");
}
}
.NET Fiddle: https://dotnetfiddle.net/4DtIyH
So I am creating a hangman-type game in C# and I want the user's input to be recognized as a variable. So I am trying to use this variable(user input) and see if it is found in the word chosen. However, there is no .Contain function that works with "char" variables. Is there any way to make this work? (The part in asterisks is the portion I want to add this code to)
using System;
namespace Hangman
{
class WordChoice
{
static void Main(string[] args)
{
Random rand = new Random();
int numword = rand.Next(2);
string word = "";
char[] ltrlist = { ' ' };
char ltrchce = ' ';
int strlength = 0;
**void ltrcheck()
{
if
{
Console.WriteLine("Great you got a letter");
}
}**
if (numword == 1)
{
word = "Shrek";
strlength = word.Length;
ltrlist = new char[strlength];
for (int a = 0; a < strlength; a++)
{
ltrlist[a] = word[a];
}
}
if (numword == 2)
{
word = "Venom";
strlength = word.Length;
ltrlist = new char[strlength];
for (int a = 0; a < strlength; a++)
{
ltrlist[a] = word[a];
}
}
if (numword == 3)
{
word = "Avengers";
strlength = word.Length;
ltrlist = new char[strlength];
for (int a = 0; a < strlength; a++)
{
ltrlist[a] = word[a];
}
}
if (numword == 4)
{
word = "Inception";
strlength = word.Length;
ltrlist = new char[strlength];
for (int a = 0; a < strlength; a++)
{
ltrlist[a] = word[a];
}
}
if (numword == 5)
{
word = "Batman";
strlength = word.Length;
ltrlist = new char[strlength];
for (int a = 0; a < strlength; a++)
{
ltrlist[a] = word[a];
}
}
string undscr = "";
for (int i = 0; i < strlength; i++)
{
undscr = undscr + " _";
}
Console.WriteLine(undscr);
Console.WriteLine("");
Console.WriteLine("Pick a letter");
string ltrchcestr = Console.ReadLine();
ltrchce = Convert.ToChar(ltrchcestr);
ltrcheck();
}
}
}
You can do a function like this
static bool Contains(IEnumerable < char > items, char letter)
=> return items?.Any(c => c == letter) == true;
or just create a typeExtension, for Project wide use:
public static class CharExtensions {
public static bool Contains(this IEnumerable<char> items, char letter ){
return items?.Any(c => c == letter) == true;
}
}
this test will now work:
var chars = new []{'a','b','c'};
Console.WriteLine(chars.Contains('m'));
Console.WriteLine(chars.Contains('b'));
I'm a math student with little to no experience programming, but I wrote this to act like a brute force algorithm. It seems to run fine except that it runs all the password combinations out to 3 characters for passwords as short as 2. Also I'm sure there's a way to refactor the for and if statements as well. Any help would be appreciated, thanks.
I've already been testing to see if some of the if statements aren't executing, and it looks like the statements with "console.writeln(Is this executing)" aren't executing but I'm not really sure.
public Form1()
{
InitializeComponent();
}
static char[] Match ={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j' ,'k','l','m','n','o','p',
'q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','C','L','M','N','O','P',
'Q','R','S','T','U','V','X','Y','Z','!','?',' ','*','-','+'};
private string[] tempPass;
private void button1_Click(object sender, EventArgs e)
{
string tempPass1 = "lm";
string result = String.Empty;
int passLength = 1;
int maxLength = 17;
tempPass = new string[passLength];
for (int i = 0; i < Match.Length; i++)
{
if (tempPass1 != result)
{
tempPass[0] = Match[i].ToString();
result = String.Concat(tempPass);
if (passLength > 1)
{
for (int j = 0; j < Match.Length; j++)
{
if (tempPass1 != result)
{
tempPass[1] = Match[j].ToString();
result = String.Concat(tempPass);
if (passLength > 2)
{
for (int k = 0; k < Match.Length; k++)
{
if (tempPass1 != result)
{
tempPass[2] = Match[k].ToString();
result = String.Concat(tempPass);
if (tempPass[0] == "+" && tempPass[1] == "+" && tempPass[2] == "+" && tempPass1 != result)
{
Console.WriteLine("This will execute?");
passLength++;
tempPass = new string[passLength];
k = 0;
j = 0;
i = 0;
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is big gay: " + result);
break;
}
}
}
}
if (tempPass[0] == "+" && tempPass[1] == "+" && tempPass1 != result)
{
Console.WriteLine("Did this execute?");
passLength++;
tempPass = new string[passLength];
j = 0;
i = 0;
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is bigger gay: " + result);
break;
}
}
}
}
//tempPass[1] = "World!";
//Console.WriteLine(result);
if (tempPass[tempPass.Length - 1] == "+" && tempPass1 != result)
{
passLength++;
tempPass = new string[passLength];
Console.WriteLine(tempPass.Length + " " + result + " " + "Success");
Console.WriteLine(i);
i = 0; /**update
j = 0;
k = 0;
l = 0;
m = 0;*/
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is biggest gay: " + result);
}
}
}
}
Play with this; modified from my answer here. It'll show you all the 2 and 3 length combinations. Clicking the button will start/stop the generation process. You need a button, label, and a timer:
public partial class Form1 : Form
{
private Revision rev;
public Form1()
{
InitializeComponent();
rev = new Revision("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!? *-+", "00");
label1.Text = rev.CurrentRevision;
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = !timer1.Enabled;
}
private void timer1_Tick(object sender, EventArgs e)
{
rev.NextRevision();
if (rev.CurrentRevision.Length == 4)
{
timer1.Stop();
MessageBox.Show("Sequence Complete");
// make it start back at the beginning?
rev = new Revision("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!? *-+", "00");
label1.Text = rev.CurrentRevision;
}
else
{
label1.Text = rev.CurrentRevision;
}
}
}
public class Revision
{
private string chars;
private char[] values;
private System.Text.StringBuilder curRevision;
public Revision()
{
this.DefaultRevision();
}
public Revision(string validChars)
{
if (validChars.Length > 0)
{
chars = validChars;
values = validChars.ToCharArray();
curRevision = new System.Text.StringBuilder(values[0]);
}
else
{
this.DefaultRevision();
}
}
public Revision(string validChars, string startingRevision)
: this(validChars)
{
curRevision = new System.Text.StringBuilder(startingRevision.ToUpper());
int i = 0;
for (i = 0; i <= curRevision.Length - 1; i++)
{
if (Array.IndexOf(values, curRevision[i]) == -1)
{
curRevision = new System.Text.StringBuilder(values[0]);
break;
}
}
}
private void DefaultRevision()
{
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
values = chars.ToCharArray();
curRevision = new System.Text.StringBuilder(values[0]);
}
public string ValidChars
{
get { return chars; }
}
public string CurrentRevision
{
get { return curRevision.ToString(); }
}
public string NextRevision(int numRevisions = 1)
{
bool forward = (numRevisions > 0);
numRevisions = Math.Abs(numRevisions);
int i = 0;
for (i = 1; i <= numRevisions; i++)
{
if (forward)
{
this.Increment();
}
else
{
this.Decrement();
}
}
return this.CurrentRevision;
}
private void Increment()
{
char curChar = curRevision[curRevision.Length - 1];
int index = Array.IndexOf(values, curChar);
if (index < (chars.Length - 1))
{
index = index + 1;
curRevision[curRevision.Length - 1] = values[index];
}
else
{
curRevision[curRevision.Length - 1] = values[0];
int i = 0;
int startPosition = curRevision.Length - 2;
for (i = startPosition; i >= 0; i += -1)
{
curChar = curRevision[i];
index = Array.IndexOf(values, curChar);
if (index < (values.Length - 1))
{
index = index + 1;
curRevision[i] = values[index];
return;
}
else
{
curRevision[i] = values[0];
}
}
curRevision.Insert(0, values[0]);
}
}
private void Decrement()
{
char curChar = curRevision[curRevision.Length - 1];
int index = Array.IndexOf(values, curChar);
if (index > 0)
{
index = index - 1;
curRevision[curRevision.Length - 1] = values[index];
}
else
{
curRevision[curRevision.Length - 1] = values[values.Length - 1];
int i = 0;
int startPosition = curRevision.Length - 2;
for (i = startPosition; i >= 0; i += -1)
{
curChar = curRevision[i];
index = Array.IndexOf(values, curChar);
if (index > 0)
{
index = index - 1;
curRevision[i] = values[index];
return;
}
else
{
curRevision[i] = values[values.Length - 1];
}
}
curRevision.Remove(0, 1);
if (curRevision.Length == 0)
{
curRevision.Insert(0, values[0]);
}
}
}
}
I am currently trying to make a random password generator.
My code works fine if I only pick one type of symbols.
What's the best way to make my code to word for more than one type?
Also what parameters would you add to make the password more secured?
I am thinking of adding an if loop to check if there are more than two same letters, symbols or numbers in a row.
That's how my interface looks like:
and that is my code:
public partial class Form1 : Form
{
// Max number of identical characters in a row
const int Maximum_Identical = 2;
// lower case chars
const string lower_chars = "abcdefghijklmnopqrstuvwxyz";
// capital chars
const string capital_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// numbers
const string numbers = "0123456789";
// symbols
const string symbols = #"!#$%&*#\";
// password lenght
int lenght;
private void button1_Click(object sender, EventArgs e)
{
//use stringbuilder so I can add more chars later
StringBuilder password = new StringBuilder();
//take max lenght from numericUpDown
lenght = Convert.ToInt32(numericUpDown1.Value);
// random instance so I can use Next and don't get loops
Random rdm = new Random();
if (small_letters__Box.Checked)
{
//add a random small character to pass untill it reaches the selected lenght
while (lenght-- > 0 )
{
password.Append(lower_chars[rdm.Next(lower_chars.Length)]);
}
}
if (capital_letters__Box.Checked)
{
//add a random capital character to pass untill it reaches the selected lenght
while (lenght-- > 0)
{
password.Append(capital_chars[rdm.Next(capital_chars.Length)]);
}
}
if (numbers_Box.Checked)
{
//add a random character to pass untill it reaches the selected lenght
while (lenght-- > 0)
{
password.Append(numbers[rdm.Next(numbers.Length)]);
}
}
if (symbols_Box.Checked)
{
//add a random character to pass untill it reaches the selected lenght
while (lenght-- > 0)
{
password.Append(symbols[rdm.Next(symbols.Length)]);
}
}
textBox1.Text = password.ToString();
}
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
}
}
Your password generation has 2 steps.
Determine the character set
Create a password randomly from the character set of length n
Function 1 creates the character set:
// Make sure you have using System.Linq;
private List<char> GetCharacterSet()
{
IEnumerable<char> returnSet = new char[]{};
if (small_letters__Box.Checked)
{
returnSet = returnSet.Append(lower_chars);
}
if (capital_letters__Box.Checked)
{
returnSet = returnSet.Append(capital_chars);
}
if (numbers_Box.Checked)
{
returnSet = returnSet.Append(numbers);
}
if (symbols_Box.Checked)
{
returnSet = returnSet.Append(symbols);
}
return returnSet.ToList();
}
Function 2 creates a password of given length from your character set
private string GetPassword(int length, List<char> characterSet)
{
if(characterSet.Count < 1)
{
throw new ArgumentException("characterSet contains no items!");
}
if(length < 1)
{
return "";
}
Random rdm = new Random();
StringBuilder password = new StringBuilder();
for(int i = 0; i < length; i++){
int charIndex = rdm.Next(0, characterSet.Count)
password.Append(characterSet[charIndex]);
}
return password.ToString();
}
Then simply rig your button click event handler to call these functions and display the resulting password.
below code is my already written code which I wrote more than a couple of years ago and I still use it in my many of my projects where needed, it covers all you are in need of
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading;
public static class ArrayExtentions
{
public static object[] Shuffle(this object[] array)
{
var alreadySwaped = new HashSet<Tuple<int, int>>();
var rndLoopCount = RandomUtils.GetRandom(Convert.ToInt32(array.Length / 4), Convert.ToInt32((array.Length / 2) + 1));
for (var i = 0; i <= rndLoopCount; i++)
{
int rndIndex1 = 0, rndIndex2 = 0;
do
{
rndIndex1 = RandomUtils.GetRandom(0, array.Length);
rndIndex2 = RandomUtils.GetRandom(0, array.Length);
} while (alreadySwaped.Contains(new Tuple<int, int>(rndIndex1, rndIndex2)));
alreadySwaped.Add(new Tuple<int, int>(rndIndex1, rndIndex2));
var swappingItem = array[rndIndex1];
array[rndIndex1] = array[rndIndex2];
array[rndIndex2] = swappingItem;
}
return array;
}
}
public class RandomUtils
{
private static readonly ThreadLocal<Random> RndLocal = new ThreadLocal<Random>(() => new Random(GetUniqueSeed()));
private static int GetUniqueSeed()
{
long next, current;
var guid = Guid.NewGuid().ToByteArray();
var seed = BitConverter.ToInt64(guid, 0);
do
{
current = Interlocked.Read(ref seed);
next = current * BitConverter.ToInt64(guid, 3);
} while (Interlocked.CompareExchange(ref seed, next, current) != current);
return (int)next ^ Environment.TickCount;
}
public static int GetRandom(int min, int max)
{
Contract.Assert(max >= min);
return RndLocal.Value.Next(min, max);
}
public static int GetRandom(int max)
{
return RndLocal.Value.Next(max);
}
public static double GetRandom()
{
return RndLocal.Value.NextDouble();
}
}
public class StringUtility
{
private const string UpperAlpha = "ABCDEFGHIJKLMNOPQRSTUWXYZ";
private const string LowerAlpha = "abcdefghijklmnopqrstuwxyz";
private const string Numbers = "0123456789";
private const string SpecialChars = "~!##$%^&*()_-+=.?";
private static string CreateSourceString(bool includeLowerCase, bool includeUpperCase, bool includenumbers, bool includeSpChars)
{
Contract.Assert(includeLowerCase || includeUpperCase || includenumbers || includeSpChars);
var sb = new StringBuilder();
if (includeLowerCase) sb.Append(LowerAlpha);
if (includeUpperCase) sb.Append(UpperAlpha);
if (includenumbers) sb.Append(Numbers);
if (includeSpChars) sb.Append(SpecialChars);
return sb.ToString();
}
private static string GenerateString(string sourceString, int length = 6)
{
var rndString = Shuffle(sourceString);
var builder = new StringBuilder();
for (var i = 0; i < length; i++)
builder.Append(rndString[RandomUtils.GetRandom(0, rndString.Length)]);
return builder.ToString();
}
public static string GenerateRandomString(int length = 6,
bool includenumbers = false,
bool includeSpChars = false)
{
var sourceStr = CreateSourceString(true, true, includenumbers, includeSpChars);
return GenerateString(sourceStr, length);
}
public static string GenerateRandomString(int minLength,
int maxLength,
bool includenumbers = false,
bool includeSpChars = false)
{
if (maxLength < minLength) maxLength = minLength;
var len = RandomUtils.GetRandom(minLength, maxLength + 1);
return GenerateRandomString(len, includenumbers, includeSpChars);
}
public static string Shuffle(string str)
{
var alreadySwaped = new HashSet<Tuple<int, int>>();
var rndLoopCount = RandomUtils.GetRandom(Convert.ToInt32(str.Length / 4), Convert.ToInt32((str.Length / 2) + 1));
var strArray = str.ToArray();
for (var i = 0; i <= rndLoopCount; i++)
{
int rndIndex1 = 0, rndIndex2 = 0;
do
{
rndIndex1 = RandomUtils.GetRandom(0, str.Length);
rndIndex2 = RandomUtils.GetRandom(0, str.Length);
} while (alreadySwaped.Contains(new Tuple<int, int>(rndIndex1, rndIndex2)));
alreadySwaped.Add(new Tuple<int, int>(rndIndex1, rndIndex2));
var swappingChar = strArray[rndIndex1];
strArray[rndIndex1] = strArray[rndIndex2];
strArray[rndIndex2] = swappingChar;
}
return new string(strArray);
}
public static string GeneratePassword(PasswordComplexity complexityLevel)
{
switch (complexityLevel)
{
case PasswordComplexity.Simple: return GenerateSimplePassword();
case PasswordComplexity.Medium: return GenerateMediumPassword();
case PasswordComplexity.Strong: return GenerateStrongPassword();
case PasswordComplexity.Stronger: return GenerateStrongerPassword();
}
return null;
}
private static string GenerateSimplePassword()
{
return GenerateRandomString(6, 9);
}
private static string GenerateMediumPassword()
{
var passLen = RandomUtils.GetRandom(6, 10);
var numCount = RandomUtils.GetRandom(1, 3);
var alphaStr = GenerateRandomString(passLen - numCount);
var numStr = GenerateString(Numbers, numCount);
var pass = alphaStr + numStr;
return Shuffle(pass);
}
private static string GenerateStrongPassword()
{
var lowerCharCount = RandomUtils.GetRandom(2, 5);
var upperCharCount = RandomUtils.GetRandom(2, 5);
var numCount = RandomUtils.GetRandom(2, 4);
var spCharCount = RandomUtils.GetRandom(2, 4);
var lowerAlphaStr = GenerateString(LowerAlpha, lowerCharCount);
var upperAlphaStr = GenerateString(UpperAlpha, upperCharCount);
var spCharStr = GenerateString(SpecialChars, spCharCount);
var numStr = GenerateString(Numbers, numCount);
var pass = lowerAlphaStr + upperAlphaStr + spCharStr + numStr;
return Shuffle(pass);
}
private static string GenerateStrongerPassword()
{
var lowerCharCount = RandomUtils.GetRandom(5, 12);
var upperCharCount = RandomUtils.GetRandom(4, 8);
var numCount = RandomUtils.GetRandom(4, 6);
var spCharCount = RandomUtils.GetRandom(4, 6);
var lowerAlphaStr = GenerateString(LowerAlpha, lowerCharCount);
var upperAlphaStr = GenerateString(UpperAlpha, upperCharCount);
var spCharStr = GenerateString(SpecialChars, spCharCount);
var numStr = GenerateString(Numbers, numCount);
var pass = lowerAlphaStr + upperAlphaStr + spCharStr + numStr;
return Shuffle(Shuffle(pass));
}
public enum PasswordComplexity
{
Simple, Medium, Strong, Stronger
}
}
I write this code for you. You can just copy and use it. All of my code is just a method that you can pass appropriate arguments and it gives you back a completely randomized password. I test it several times before answering your question, It works well.
private string GeneratePassword(bool useCapitalLetters, bool useSmallLetters, bool useNumbers, bool useSymbols, int passLenght)
{
Random random = new Random();
StringBuilder password = new StringBuilder(string.Empty);
//This for loop is for selecting password chars in order
for (int i = 0;;)
{
if (useCapitalLetters)
{
password.Append((char)random.Next(65, 91)); //Capital letters
++i; if (i >= passLenght) break;
}
if (useSmallLetters)
{
password.Append((char)random.Next(97, 122)); //Small letters
++i; if (i >= passLenght) break;
}
if (useNumbers)
{
password.Append((char)random.Next(48, 57)); //Number letters
++i; if (i >= passLenght) break;
}
if (useSymbols)
{
password.Append((char)random.Next(35, 38)); //Symbol letters
++i; if (i >= passLenght) break;
}
}
//This for loop is for disordering password characters
for (int i = 0; i < password.Length; ++i)
{
int randomIndex1 = random.Next(password.Length);
int randomIndex2 = random.Next(password.Length);
char temp = password[randomIndex1];
password[randomIndex1] = password[randomIndex2];
password[randomIndex2] = temp;
}
return password.ToString();
}
an answer with complete randomize char and using the max repeat of char, i have added a shuffle string function:
const int Maximum_Identical = 2; // Max number of identical characters in a row
const string lower_chars = "abcdefghijklmnopqrstuvwxyz"; // lower case chars
const string capital_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //capital chars
const string numbers = "0123456789"; //numbers
const string symbols = #"!#$%&*#\"; //symbols
int lenght = 6; //
bool lowercase = true, capital=true, num=true, sym=true;
List<char[]> PasswordSet = new List<char[]>();
List<char[]> charSet = new List<char[]>();
List<int[]> countSet = new List<int[]>();
if (lowercase) charSet.Add(lower_chars.ToArray());
if (capital) charSet.Add(capital_chars.ToArray());
if (num) charSet.Add(numbers.ToArray());
if (sym) charSet.Add(symbols.ToArray());
foreach(var c in charSet)
countSet.Add(new int[c.Length]);
Random rdm = new Random();
//we create alist with each type with a length char (max repeat char included)
for(int i = 0; i < charSet.Count;i++)
{
var lng = 1;
var p0 = "";
while (true)
{
var ind = rdm.Next(0, charSet[i].Length);
if (countSet[i][ind] < Maximum_Identical )
{
countSet[i][ind] += 1;
lng++;
p0 += charSet[i][ind];
}
if (lng == lenght) break;
}
PasswordSet.Add(p0.ToArray());
}
//generate a password with the desired length with at less one char in desired type,
//and we choose randomly in desired type to complete the length of password
var password = "";
for(int i = 0; i < lenght; i++)
{
char p;
if (i < PasswordSet.Count)
{
int id;
do
{
id = rdm.Next(0, PasswordSet[i].Length);
p = PasswordSet[i][id];
} while (p == '\0');
password += p;
PasswordSet[i][id] = '\0';
}
else
{
int id0;
int id1;
do
{
id0 = rdm.Next(0, PasswordSet.Count);
id1 = rdm.Next(0, PasswordSet[id0].Length);
p = PasswordSet[id0][id1];
} while (p == '\0');
password += p;
PasswordSet[id0][id1] = '\0';
}
}
//you could shuffle the final password
password = Shuffle.StringMixer(password);
shuffle string function:
static class Shuffle
{
static System.Random rnd = new System.Random();
static void Fisher_Yates(int[] array)
{
int arraysize = array.Length;
int random;
int temp;
for (int i = 0; i < arraysize; i++)
{
random = i + (int)(rnd.NextDouble() * (arraysize - i));
temp = array[random];
array[random] = array[i];
array[i] = temp;
}
}
public static string StringMixer(string s)
{
string output = "";
int arraysize = s.Length;
int[] randomArray = new int[arraysize];
for (int i = 0; i < arraysize; i++)
{
randomArray[i] = i;
}
Fisher_Yates(randomArray);
for (int i = 0; i < arraysize; i++)
{
output += s[randomArray[i]];
}
return output;
}
}
There you go :
string[] charList =
{
"abcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"0123456789",
"#\"!#$%&*#\\"
};
int desiredPasswordLength = 12;
var randomNumberGenerator = new Random();
string generatedPassword = "";
for (int i = randomNumberGenerator.Next() % 4; desiredPasswordLength > 0; i = (i+1) % 4)
{
var takeRandomChars = randomNumberGenerator.Next() % 3;
for (int j = 0; j < takeRandomChars; j++)
{
var randomChar = randomNumberGenerator.Next() % charList[i].Length;
char selectedChar = charList[i][randomChar % charList[i].Length];
generatedPassword = string.Join("", generatedPassword, selectedChar);
}
desiredPasswordLength -= takeRandomChars;
}
Console.WriteLine("Generated password: {0}",generatedPassword);
private static string GeneratorPassword(UInt16 length = 8)
{
const string chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
Random rnd = new Random();
System.Threading.Thread.Sleep(2);
for (int i = 0; i < length; i++)
{
int index = 0;
if (i % 3 == 0)
{
index = rnd.Next(0, 10);
}
else if (i % 3 == 1)
{
index = rnd.Next(10, 36);
}
else
{
index = rnd.Next(36, 62);
}
sb.Insert(rnd.Next(0, sb.Length), chars[index].ToString());
}
return sb.ToString();
}
static void Main(string[] args)
{
for (int j= 0; j < 100; j++)
{
Console.WriteLine( GeneratorPassword());
}
Console.ReadLine();
}