//code with problem (maybe)
numberArray = NameNumEquv;
listStringArray = NamesArray;
string[] sortedArray = new string[NamesArray.Length];
for (int arrayItemCounter = 0; arrayItemCounter < NamesArray.Length; arrayItemCounter++)
{
compareArrayCount = 1;
initialArrayCount = 0;
while (compareArrayCount < numberArray.Length)
{
for (int doubleArrayLength = 0; doubleArrayLength < numberArray[compareArrayCount].Length; doubleArrayLength++)
{
if (numberArray[initialArrayCount][doubleArrayLength] < numberArray[compareArrayCount][doubleArrayLength])
{
initialArrayCount = compareArrayCount;
break;
}
}
compareArrayCount = compareArrayCount + 1;
}
sortedArray[arrayItemCounter] = listStringArray[initialArrayCount];
List<string> tempArrayValues = new List<string>();
List<int[]> tempNumArrayValues = new List<int[]>();
for (int tempArrayCount = 0; tempArrayCount < listStringArray.Length; tempArrayCount++)
{
if (tempArrayCount != initialArrayCount)
{
tempArrayValues.Add(listStringArray[tempArrayCount]);
tempNumArrayValues.Add(numberArray[tempArrayCount]);
}
}
listStringArray = tempArrayValues.ToArray();
numberArray = tempNumArrayValues.ToArray();
tempArrayValues.Clear();
tempNumArrayValues.Clear();
}
//till here
foreach (string nums in sortedArray)
{
Console.WriteLine(nums);
}
}
public static int[] AlphaNumericConversion(string stringValue, int arrayLength)
{
string Alphabets = "abcdefghijklmnopqrstuvwxyz";
char[] alphabetArray = Alphabets.ToCharArray();
string lowerCaseConv = stringValue.ToLower();
char[] stringArray = lowerCaseConv.ToCharArray();
int[] numericalConvertedArray = new int[arrayLength];
for (int valueArrayCount = 0; valueArrayCount < numericalConvertedArray.Length; valueArrayCount++)
{
numericalConvertedArray[valueArrayCount] = 0;
}
for (int letterCounter= 0;letterCounter < stringArray.Length;letterCounter++)
{
for (int alphabetCounter = 0; alphabetCounter < Alphabets.Length; alphabetCounter++)
{
if (stringArray[letterCounter] == alphabetArray[alphabetCounter])
numericalConvertedArray[letterCounter] = alphabetCounter + 1;
}
}
return numericalConvertedArray;
}
}
}
I want to arrange strings in ascending order. It is arranging the single letter strings(a, b, c,d, e.....) in reverse alphabetical order as in Z-A and string containing 2 or more letters randomly such as "Aayush", "Ayush", "Aayusha", "Ayusha" to "Aayusha","Ayusha","Aayush","Ayush". What is wrong with the code. Don't suggest to simply use List.Sort() because I want to write it in algorithmic manner. I'm trying to understand how it works rather than using Sort().
Related
In the inputs first row, there are two numbers the first one is the amount of rows N and the second one is a limit K. I have to find the first and last element's indexes of the longest continuous subarray which's elements are greater than K.
(There are lots of inputs with different numbers, but they have the same base.)
The example input is:
7 20
18
23
44
32
9
30
26
So the N is 7 and K is 20, in this case there are 2 continuous subarrays which would be correct: [23, 44, 32] and [30, 26], but I only need the longer ones indexes.
Therefore the output is:
1 3
I have split the first row, so i have the N and K, I have added the remaining rows in an array H[ ]. Now I just have to find the longest continuous subarray and get the first and last element's indexes.
static void Main(string[] args)
{
string[] fRow = Console.ReadLine().Split(' ');
int N = int.Parse(fRow[0]);
int K = int.Parse(fRow[1]);
int[] H = new int[N];
for (int i = 0; i < N; i++)
{
H[i] = int.Parse(Console.ReadLine());
}
}
And I'm stuck here, if someone could help me I would greatly appreciate their assistance.
Sounds like homework, but an interesting challenge none the less. Here's one way of doing it.
static void Main(string[] args)
{
string[] fRow = Console.ReadLine().Split(' ');
int N = int.Parse(fRow[0]);
int K = int.Parse(fRow[1]);
int[] H = new int[N];
for (int i = 0; i < N; i++)
{
H[i] = int.Parse(Console.ReadLine());
}
int greatesRangeStartIndex = -1;
int greatestRangeEndIndex = -1;
int greatestIndexSpan = 0;
for (int i = 0; i < N; i++)
{
// Find the first array item that meets the criteria.
if (H[i] > K)
{
var rangeStartIndex = i;
// Continue spinning through the array while we still meet the criteria.
do
{
i++;
} while (i < N && H[i] > K);
var rangeEndIndex = i - 1;
// Determine the width of our current range and check if its our largest one.
// If the range is the biggest so far, store that as the current largest range.
var indexSpan = rangeEndIndex - rangeStartIndex + 1;
if (indexSpan > greatestIndexSpan)
{
greatesRangeStartIndex = rangeStartIndex;
greatestRangeEndIndex = rangeEndIndex;
greatestIndexSpan = indexSpan;
}
}
}
// Report out the results.
// Not part of the requirements, but will remove false reporting of the criteria being in index position 1.
if (greatesRangeStartIndex == -1 && greatestRangeEndIndex == -1)
{
Console.WriteLine($"No values in the array were greater than {K}.");
}
else
{
Console.WriteLine($"{greatesRangeStartIndex} {greatestRangeEndIndex}");
}
}
You could do something like this (could be improved a lot with LINQ, but i suppose this is an introduction exercise of some sorts, so i'll stick to this):
static void Main(string[] args)
{
string[] fRow = Console.ReadLine().Split(' ');
int N = int.Parse(fRow[0]);
int K = int.Parse(fRow[1]);
int[] H = new int[N];
int firstIndex = 0;
int lastIndex = 0;
int subarraySize = 0;
int firstIndexTemp = 0;
int lastIndexTemp = 0;
int subarraySizeTemp = 0;
bool arrayContinues = false;
for (int i = 0; i < N; i++)
{
//Read the newest index
H[i] = int.Parse(Console.ReadLine());
/*If arrrayContinues is true, and the current value is higher than the threshold K,
this means this is the continuation of a subarray. For now, the current value is the last index value
*/
if (H[i] > K && arrayContinues)
{
subarraySizeTemp++;
lastIndexTemp = i;
}
/*If arrrayContinues is false, but the current value is higher than the threshold K,
this means this is the first index of a new subarray
*/
else if (H[i] > K)
{
subarraySizeTemp = 1;
firstIndexTemp = i;
arrayContinues = true;
}
/*If we reach this statement, the current value is smaller than K,
* so the array streak stopped (or was already stopped by a previous smaller value)
*/
else
{
arrayContinues = false;
}
/* We're only interested in the largest subarray,
* so let's override the previous largest array only when the current one is larger.
*/
if(subarraySizeTemp > subarraySize)
{
subarraySize = subarraySizeTemp;
firstIndex = firstIndexTemp;
lastIndex = lastIndexTemp;
}
}
/*Let's print our result!*/
Console.WriteLine($"{firstIndex} {lastIndex}");
}
Other answers work out but you can use something simpler like this;
private static void Main()
{
var input = Console.ReadLine().Split(' ');
var n = int.Parse(input[0]);
var k = int.Parse(input[1]);
var startingIndex = 0;
var endingIndex = 0;
var temporaryIndex = 0;
var items = new int[n];
for (var i = 0; i < n; i++)
{
var value = int.Parse(Console.ReadLine());
items[i] = value;
if (value < k)
{
temporaryIndex = i;
continue;
}
var currentSize = i - temporaryIndex;
var currentBiggestSize = endingIndex - startingIndex;
if (currentSize > currentBiggestSize)
{
startingIndex = temporaryIndex + 1;
endingIndex = i;
}
}
Console.WriteLine($"Biggest Subset's Start and Ending Indexes: {startingIndex} {endingIndex}");
Console.ReadLine();
}
Another Option:
static void Main(string[] args)
{
Example(new string[] { "7","20"},new string[] { "18", "23", "44", "32", "9", "30", "26"});
}
static void Example(string[] arr,string[] values)
{
int N = int.Parse(arr[0]);
int K = int.Parse(arr[1]);
int counter = 0;
int most_succesfull_index_yet = 0;
int most_succesfull_length_yet = 0;
for (int i = 1; i < N; i++)
{
if (int.Parse(values[i]) > K)
{
counter++;
}
else
{
if (counter > most_succesfull_length_yet)
{
most_succesfull_length_yet = counter;
most_succesfull_index_yet = i - counter;
}
counter = 0;
}
}
// For last index
if (counter > most_succesfull_length_yet)
{
most_succesfull_length_yet = counter;
most_succesfull_index_yet = N - counter;
}
var bestStart = most_succesfull_index_yet;
var bestEnd = most_succesfull_index_yet + most_succesfull_length_yet -1;
Console.WriteLine(bestStart + "," + bestEnd);
Console.ReadLine();
}
Another solution, keeping indexes of the longest match, and displaying the max length, indexes, and rows values at the end.
static void Main(string[] args)
{
var data = #"7 20
18
23
44
32
9
30
26";
var rows = data.Split("\r\n");
var frow = rows[0].Split(" ");
int N = int.Parse(frow[0]);
int K = int.Parse(frow[1]);
int max = 0, currentmax = 0;
int i = 1;
int[] indexes = null;
while(i < rows.Length)
{
if (int.Parse(rows[i]) > K)
{
currentmax++;
}
else
{
if (currentmax > max)
{
max = currentmax;
indexes = new int[max];
indexes[--currentmax] = i;
do
{
indexes[--currentmax] = indexes[currentmax + 1] - 1;
} while (currentmax > 0);
currentmax = 0;
}
}
i++;
}
if (indexes != null) {
Console.WriteLine($"{max} occured on indexes {string.Join(",", indexes)} with values {string.Join(",", indexes.Select(i => rows[i]).ToList())}");
}
}
string[] fRow = Console.ReadLine().Split(' ');
int N = int.Parse(fRow[0]);
int K = int.Parse(fRow[1]);
bool isChain = false;
int currentFirstIndex = -1;
int maxFirstIndex = -1;
int currentLastIndex = -1;
int maxLastIndex = -1;
int currentLength = 0;
int maxLength = 0;
int[] H = new int[N];
for (int i = 0; i < N; i++)
{
H[i] = int.Parse(Console.ReadLine());
if(H[i] > K)
{
if (isChain)
{
currentLastIndex = i;
}
else
{
currentFirstIndex = i;
isChain = true;
}
currentLength++;
}
else
{
if (maxLength < currentLength)
{
maxLength = currentLength;
maxFirstIndex = currentFirstIndex;
maxLastIndex = currentLastIndex;
}
currentLength = 0;
isChain = false;
}
}
Console.WriteLine("first: " + maxFirstIndex + " last: " + maxLastIndex);
This could be one of the way
static void Main(string[] args)
{
var firstLineInput = Console.ReadLine().Split(" ");
var numberOfInput = Int64.Parse(firstLineInput[0]);
var value = Int64.Parse(firstLineInput[1]);
var startIndex = -1; //No value greater than value
var endIndex = -1;
var maxLength = 0;
var maxStartIndex = -1;
var maxEndIndex = -1;
for (int i = 0; i < numberOfInput ; i++)
{
var input = Int64.Parse(Console.ReadLine());
if (input > value && startIndex == -1)
{
startIndex = i;
endIndex = i;
if(maxLength == 0)
{
maxLength = 1;
maxStartIndex = startIndex;
maxEndIndex = endIndex;
}
}
else if(input > value && startIndex != -1)
{
endIndex = i;
}
else if(input < value)
{
startIndex = -1;
endIndex = -1;
}
if (maxLength < (endIndex - startIndex))
{
maxLength = endIndex - startIndex;
maxStartIndex = startIndex;
maxEndIndex = endIndex;
}
}
Console.WriteLine($"{maxStartIndex} {maxEndIndex}");
}
i want to store each row in a different array. below is the code i tried.
but it doesn't not work, it only splits the last line and store values in "valueperline" array
first 11 rows are source text. file and screen shot of console
using System;
using System.Collections.Generic;
using System.IO;
namespace BBS_optimize
{
class Program
{
static void Main()
{
int i = 0; int j = 0; int k =0; string[] valueperline = new string[0]; string[] lines = new string [0];
lines = File.ReadAllLines("Table1.txt");
for (i = 0; i < lines.Length; i++)
{
Console.WriteLine(lines[i]);
}
for (j = 0; j<lines.Length; j++)
{ valueperline = lines[j].Split('\t');
}
for (k = 0; k < 44; k++)
{ Console.WriteLine(valueperline[k]);
}
}
}
}
Use array:
string[,] ParseFromFile (string fileName)
{
// Assume that your table have 10 cols and 100 rows
string[,] result = new string[10,100];
string str = File.ReadAllText (fileName);
// Split each line to arrays
string[] yourStringArray = str.Split(new[]{'\r', '\n'},StringSplitOptions.RemoveEmptyEntries);
for (int i == 0; i < yourStringArray; i++)
{
string[] row = yourStringArray[i].Split(new[]{" "},StringSplitOptions.RemoveEmptyEntries);
result[i] = row;
}
return result;
}
Use List:
List<List<string>> ParseFromFile (string fileName)
{
// Your list
List<List<string>> result = new List<List<string>>();
string str = File.ReadAllText (fileName);
// Split each line to arrays
string[] yourStringArray = str.Split(new[]{'\r', '\n'},StringSplitOptions.RemoveEmptyEntries);
for (int i == 0; i < yourStringArray; i++)
{
List<string> row = yourStringArray[i].Split(new[]{" "},StringSplitOptions.RemoveEmptyEntries).ToList();
result.Add(row);
}
return result;
}
below is a solution:
static void Main(string[] args)
{
List<List<string>> lst = new List<List<string>>();
string[] lines = new string[0];
lines = File.ReadAllLines("tableX.txt");
for (int i = 0; i < lines.Length; i++)
{
Console.WriteLine(lines[i]);
}
for (int j = 0; j < lines.Length; j++)
{
var line = lines[j].Split(' ').ToList();
lst.Add(line);
}
foreach (var item in lst)
{
for (int k = 0; k < item.Count; k++)
{
Console.WriteLine(item[k]);
}
}
}
I have a problem retrieving values in the order that I want
I wrote a simple code to demonstrate :
List<string> st1 = new List<string>() {"st11","st12"};
List<string> st2 = new List<string>() {"st21","st22"};
ArrayList stringArrayList = new ArrayList();
stringArrayList.Add(st1);
stringArrayList.Add(st2);
string[] n1 = new string[10];
int i = 0;
foreach (List<string> item in stringArrayList)
{
foreach (var item2 in item)
{
n1[i] = item2;
i++;
}
}
in this code the output will be : st11,st12 st21,s22
i want it to get values like this : st11,st21 st12,st22
i want the information stored in this order "st11,st21 st12,st22" into n1
If the lenght of the list are the same you can make something like this:
int j = 0;
int lengthToLoop = st1.length;
for(int i = 0; i < lengthToLoop; i++)
{
n1[j++] = st1[i];
n1[j++] = st2[i];
}
If the length are not equal you can calculate the minimum, copy the minimum length of element from each and then copy the remaining.
Here's an implementation that will do what you're looking for, and will also handle jagged arrays.
List<string> st1 = new List<string>() { "st11", "st12" };
List<string> st2 = new List<string>() { "st21", "st22", };
ArrayList stringArrayList = new ArrayList();
stringArrayList.Add(st1);
stringArrayList.Add(st2);
//this will protect us against differing max indexes if the 2D array is jagged.
int maxIndex = 0;
int totalElements = 0;
foreach (List<string> currentList in stringArrayList)
{
if (currentList.Count > maxIndex)
{
maxIndex = currentList.Count;
}
totalElements += currentList.Count;
}
string[] n1 = new string[totalElements];
int i = 0;
for (int j = 0; j < maxIndex; j++)
{
for (int k = 0; k < stringArrayList.Count; k++)
{
List<string> currentStringArray = (List<string>)stringArrayList[k];
if (j < currentStringArray.Count)
{
n1[i] = currentStringArray[j];
i++;
}
}
}
You have to reverse the two loops, making the outer loop the inner loop.
Use a for loop instead of a foreach loop for the outer loop using the length of the string arrays as the delimiter.
Also: Don't use ArrayList, but a real typed list.
List<string> st1 = new List<string>() { "st11", "st12" };
List<string> st2 = new List<string>() { "st21", "st22" };
List<List<string>> stringArrayList = new List<List<string>>();
stringArrayList.Add(st1);
stringArrayList.Add(st2);
// Get length of first string array
int firstArrayLength = stringArrayList[0].Count;
string[] n1 = new string[10];
int i = 0;
// For each position in the arrays from 0 to firstArrayLength -1 do
for (int arrayPosition = 0; arrayPosition < firstArrayLength; arrayPosition++)
{
// For each of the string array
foreach (var stringArray in stringArrayList)
{
// Get the item from the stringArray at position arrayPosition
n1[i] = stringArray[arrayPosition];
i++;
}
}
First, check the max list length, and then take item at index (0,1,3... till max) from every list. Don't forget to check if the index exist. In addition, you can set the exact size of n1 because it is the sum of all list count. You don't need to have a separated line for i++ in this case.
List<string> st1 = new List<string> { "st11", "st12" };
List<string> st2 = new List<string> { "st21", "st22" };
List<List<string>> stringArrayList = new List<List<string>> {st1, st2};
int maxCount = stringArrayList.Max(x => x.Count);
int totalItems = 0;
stringArrayList.ForEach(x=> totalItems+= x.Count);
string[] n1 = new string[totalItems];
int i = 0;
for (int index = 0; index < maxCount; index++)
{
foreach (var list in stringArrayList)
{
if (list.Count > index)
{
n1[i++] = list[index];
}
}
}
I have an array which can hold 10 elements:
string[] Ar = new string[10];
But it has only 5 items added to it. I need to insert The string value "NULL" to the rest of the empty slots in the array and thus making the array 'full' with string elements (that, being my objective).
This is what I've attempted as of now:
int entityCount = 5;
if (entityCount < 10)
{
for (int i = entityCount; i < 10; i++)
{
Ar[i] = "NULL";
}
}
And thus, when printed should output the values:
A, B, C, D, E, NULL, NULL, NULL, NULL, NULL
But this does not seem to do the trick, Still prints out ONLY the 5 items and not the 5 new strings.
I am not from C# background but I think this is what you want:
string[] Ar = new string[10];
for (int i = 0; i < 10; i++)
{
if(String.IsNullOrEmpty(Ar[i]))
{
Ar[i]="NULL";
}
}
for (int i = 0; i < 10; i++)
{
Console.WriteLine(Ar[i]);
}
You can read about String.IsNullOrEmpty(Ar[i]) here.
static void Main(string[] args)
{
int arraySize = 10;
string[] Ar = new string[arraySize];
Ar[0] = "A";
Ar[1] = "B";
Ar[2] = "C";
Ar[3] = "D";
for (int i = 0; i < arraySize; i++)
{
if (Ar[i]==null)
{
Ar[i] = "NULL";
}
}
for (int i = 0; i < Ar.Length; i++)
{
Console.Write(Ar[i]+" ");
}
}
}
this works fine.
int entityCount = 5;
string[] Ar = new string[10];
Ar[0] = "A";
Ar[1] = "B";
Ar[2] = "C";
Ar[3] = "D";
Ar[4] = "E";
if(entityCount < 10) {
for(int i = entityCount; i < 10; i++) {
Ar[i] = "NULL";
}
}
foreach(string s in Ar) {
Console.WriteLine(s);
}
using System;
using System.Linq;
class Program
{
private static void Main(string[] args)
{
string[] Ar = new string[10];
var item = from f in Ar
select string.IsNullOrWhiteSpace(f) ? "NULL" : f;
foreach (var i in item)
{
Console.WriteLine(i);
}
Console.ReadLine();
}
}
Here item is iterator in string of array replace all with null if not contains value
string multiplayer = new string[5];
foreach (var item in multiplayers)
{
if (item == null) { Console.WriteLine("Empty"); }
Console.WriteLine(item);
}
remember string of array is not nullable here
I need a C# function that takes 2 strings as an input and return an array of all possible combinations of strings.
private string[] FunctionName(string string1, string string2)
{
//code
}
The strings input will be in the following format:
string1: basement
string2: a*fa
Now what I need is all combinations of possible strings using the characters in String2 (ignoring the * symbols), and keeping them in the same character position like this:
baaement, baaefent, baaefena, basefent, basemena, etc.
EDIT:
This is not homework. I need this function for a piece of a program I am doing.
The following is the code I have so far but it has some bugs.
static List<string> combinations = new List<string>();
static void Main(string[] args)
{
//include trimming of input string
string FoundRes = "incoming";
string AltRes = "*2*45*78";
List<int> loc = new List<int>();
string word = "";
for (int i = 0; i < AltRes.Length; i++)
{
if (AltRes[i] != '*')
{
loc.Add(i);
word += AltRes[i];
}
}
generate(word);
string[] aaa = InsertSymbol(FoundRes, loc.ToArray(), AltRes, combinations);
Console.WriteLine("input string: " + FoundRes);
Console.WriteLine("Substitute string: " + AltRes);
Console.WriteLine("============Output============");
for (int j = 0; j < aaa.Length; j++)
{
Console.WriteLine(aaa[j]);
}
Console.ReadKey();
}//
private static void generate(string word)
{
// Add this word to combination results set
if (!combinations.Contains(word))
combinations.Add(word);
// If the word has only one character, break the recursion
if (word.Length == 1)
{
if (!combinations.Contains(word))
combinations.Add(word);
return;
}
// Go through every position of the word
for (int i = 0; i < word.Length; i++)
{
// Remove the character at the current position
// call this method with the String
generate(word.Substring(0, i) + word.Substring(i + 1));
}
}//
private static string[] InsertSymbol(string orig, int[] loc, string alternative, List<string> Chars)
{
List<string> CombinationsList = new List<string>();
string temp = "";
for (int i = 0; i < Chars.Count; i++)
{
temp = orig;
for (int j = 0; j < Chars[i].Length; j++)
{
string token = Chars[i];
if (alternative.IndexOf(token[j]) == loc[j])
{
temp = temp.Remove(loc[j], 1);
temp = temp.Insert(loc[j], token[j].ToString());
// int pos = sourceSubst.IndexOf(token[j]);
// sourceSubst = sourceSubst.Remove(pos, 1);
// sourceSubst = sourceSubst.Insert(pos, ".");
}
else
{
temp = temp.Remove(alternative.IndexOf(token[j]), 1);
temp = temp.Insert(alternative.IndexOf(token[j]), token[j].ToString());
}
}
CombinationsList.Add(temp);
}
return CombinationsList.ToArray();
}//
It does sound like homework. As a suggestion, I would ignore the first parameter and focus on getting all possible permutations of the second string. What's turned off, what's turned on, etc. From that list, you can easily come up with a method of swapping out characters of the first string.
On that note, I'm in the uncomfortable position of having a function ready to go but not wanting to post it because of the homework implication. I'd sure love for somebody to review it, though! And technically, there's two functions involved because I just happened to already have a generic function to generate subsets lying around.
Edit: OP says it isn't homework, so here is what I came up with. It has been refactored a bit since the claim of two functions, and I'm more than open to criticism.
using System;
using System.Collections.Generic;
using System.Text;
class Program
{
static void Main()
{
string original = "phenomenal";
string pattern = "*xo**q*t**";
string[] replacements = StringUtility.GetReplacementStrings(original, pattern, true);
foreach (string replacement in replacements)
Console.WriteLine(replacement);
Console.Read();
}
public static class StringUtility
{
public static string[] GetReplacementStrings(string original, string pattern, bool includeOriginal)
{
// pattern and original might not be same length
int maxIndex = Math.Max(original.Length, pattern.Length);
List<int> positions = GetPatternPositions(pattern, maxIndex, '*');
List<int[]> subsets = ArrayUtility.CreateSubsets(positions.ToArray());
List<string> replacements = GenerateReplacements(original, pattern, subsets);
if (includeOriginal)
replacements.Insert(0, original);
return replacements.ToArray();
}
private static List<string> GenerateReplacements(string original, string pattern, List<int[]> subsets)
{
List<string> replacements = new List<string>();
char[] temp = new char[original.Length];
foreach (int[] subset in subsets)
{
original.CopyTo(0, temp, 0, original.Length);
foreach (int index in subset)
{
temp[index] = pattern[index];
}
replacements.Add(new string(temp));
}
return replacements;
}
private static List<int> GetPatternPositions(string pattern, int maxIndex, char excludeCharacter)
{
List<int> positions = new List<int>();
for (int i = 0; i < maxIndex; i++)
{
if (pattern[i] != excludeCharacter)
positions.Add(i);
}
return positions;
}
}
public static class ArrayUtility
{
public static List<T[]> CreateSubsets<T>(T[] originalArray)
{
List<T[]> subsets = new List<T[]>();
for (int i = 0; i < originalArray.Length; i++)
{
int subsetCount = subsets.Count;
subsets.Add(new T[] { originalArray[i] });
for (int j = 0; j < subsetCount; j++)
{
T[] newSubset = new T[subsets[j].Length + 1];
subsets[j].CopyTo(newSubset, 0);
newSubset[newSubset.Length - 1] = originalArray[i];
subsets.Add(newSubset);
}
}
return subsets;
}
}
}
since it's hopw work I'd only suggest some way to solve the problem rather than writing the code.
if you loop the second parameter every time you hit a letter you'll have to options either use the letter from the first argument or the letter from the second. collect all these optins together with the index. keep a list of the parts from the first argument that will never change. iterate thorugh those two lists to created all the possible permutations
Decimal to Binary converted code is stolon copied from here.
static void Main()
{
string string1 = "basement";
string string2 = "**a*f**a";
string[] result = GetCombinations(string1, string2);
foreach (var item in result)
{
Console.WriteLine(item);
}
}
private static string[] GetCombinations(string string1, string string2)
{
var list = new List<List<char>> { new List<char>(), new List<char>() };
var cl = new List<char>();
List<string> result = new List<string>();
for (int i = 0; i < string1.Length; i++)
{
if (string2[i] == '*')
{
cl.Add(string1[i]);
}
else
{
list[0].Add(string1[i]);
list[1].Add(string2[i]);
}
}
int l = list[0].Count;
for (int i = 0; i < (Int64)Math.Pow(2.0,l); i++)
{
string s = ToBinary(i, l);
string ss = "";
int x = 0;
int y = 0;
for (int I = 0; I < string1.Length; I++)
{
if (string2[I] == '*')
{
ss += cl[x].ToString();
x++;
}
else
{
ss += (list[int.Parse(s[y].ToString())][y]);
y++;
}
}
result.Add(ss);
}
return result.ToArray<string>();
}
public static string ToBinary(Int64 Decimal, int width)
{
Int64 BinaryHolder;
char[] BinaryArray;
string BinaryResult = "";
while (Decimal > 0)
{
BinaryHolder = Decimal % 2;
BinaryResult += BinaryHolder;
Decimal = Decimal / 2;
}
BinaryArray = BinaryResult.ToCharArray();
Array.Reverse(BinaryArray);
BinaryResult = new string(BinaryArray);
var d = width - BinaryResult.Length;
if (d != 0) for (int i = 0; i < d; i++) BinaryResult = "0" + BinaryResult;
return BinaryResult;
}
which password cracker do you want to program? :)
how about
if string2 contains '*'
foreach(char ch in string1)
replace first * with ch,
execute FunctionName
else
print string2