snippetcsharpMinor
Generate String Combinations
Viewed 0 times
generatestringcombinations
Problem
I have created an algorithm that can generate all possible combinations of a string given its length, and character set (it uses a custom numeral system to do this). How could I improve its performance and readability?
using System;
using System.Text;
public class Program
{
public static void Main(string[] args)
{
Bruteforce brute = new Bruteforce(9, new Range(0, Helpers.Chars.Length - 1));
brute.PrintResults();
Console.ReadKey(true);
}
}
public class Bruteforce
{
private int _Length;
private Range _Range;
public int Length
{
get
{
return _Length;
}
}
public Range Range
{
get
{
return _Range;
}
}
public Bruteforce(int length, Range range)
{
_Length = length;
_Range = range;
}
public Bruteforce(int length, int min, int max)
{
_Length = length;
_Range = new Range(min, max);
}
public void PrintResults()
{
int num = this.Range.Max;
int[] arr = new int[this.Length];
for (int c = 0; c this.Range.Max)
{
for (int i = 1; i this.Range.Max)
{
arr[i - 1] = this.Range.Min;
arr[i]++;
}
}
}
int num2 = arr[0];
for (int i = 1; i = 0)
{
builder.Append(Helpers.Chars[arr[i]]);
}
else
{
throw new Exception();
}
}
return builder.ToString();
}
}
public class Range
{
private int _Max, _Min;
public int Max
{
get
{
return _Max;
}
}
public int Min
{
get
{
return _Min;
}
}
public Range(int min, int max)
{
_Max = max;
_Min = min;
}
}Solution
string.Join(string, IEnumerable)Your method
ArrayToString can be replaced with a single line :public static string ArrayToString(int[] arr)
{
return string.Join("", arr.Select(x => Chars[x]));
}Your method
PrintArray is never used but I assume it's just there for testing purpose.Code style
Auto properties
You can use auto-properties to avoid explicitly creating a backing field for your variables :
private int _Length;
public int Length
{
get
{
return _Length;
}
}Can be simplified to a single property :
public int Length { get; }You can do the same for all of your properties.
Redundant
this qualifierYou don't have to write
this. everywhere e.g this.Range.Max as there are no variables with the same names there, the compiler will guess that you are referring to the container class.Code Snippets
public static string ArrayToString(int[] arr)
{
return string.Join("", arr.Select(x => Chars[x]));
}private int _Length;
public int Length
{
get
{
return _Length;
}
}public int Length { get; }Context
StackExchange Code Review Q#151295, answer score: 4
Revisions (0)
No revisions yet.