C# building permutations with wildcards using recursion [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
So I'm having a mind melt.
The problem I'm having is that I need to be able to do the following:
I have an input that defines how many wildcards I can use UP TO, in this example we say 2.
I have a string, ABCDEFGH.
I need to create an array of all the different ways those 2 wildcards can feature in the string so that I can feed it into an SQL query.
By hand we can do.
_BCDEFGH
A_CDEFGH
AB_DEFGH
ABC_EFGH
ABCD_FGH
ABCDE_GH
ABCDEF_H
ABCDEFG_
And using our limit of 2.
__CDEFGH
_B_DEFGH
_BC_EFGH
_BCD_FGH
_BCDE_GH
_BCDEF_H
_BCDEFG_
A__DEFGH
A_C_EFGH
A_CD_FGH
A_CDE_GH
A_CDEF_H
A_CDEFG_
AB__EFGH
AB_D_FGH
and so on...
For compatability with SQL I need to use the wildcard character as an underscore_.
Can someone help me understand how to structure my loops? Bare in mind that limit of wildcards isn't always 2, it is a variable.
This isn't a question of Regex or matching, I need to be able to create these variations of a string.

you get something like this
List<String> permutations(String original, int numberOfWildcards) {
//add 1 more wildcard to each posible position in the original string
List<String> perm = new List<String>();
for (int i = 0; i < original.Length; ++i)
{
if (original[i] != '_')
perm.Add(original.Substring(0, i) + "_" + original.Substring(i + 1, original.Length));
}
if ( numberOfWildcards == 1)
{
return perm;
}
//now if we need to search deeper we recusively do this for each substring
List<String> permWithMoreWildmark = new List<String>();
foreach (var str in perm)
{
permWithMoreWildmark.AddRange(permutations(str,numberOfWildcards-1));
}
return permWithMoreWildmark;
}
the trick is to try to solve the problem for 1 deep first and then try to figure out the recursion

Related

C# for loop and encryption [closed]

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 6 years ago.
Improve this question
I'm Kind of new to C# but since i have learned other programming languages before, learning it is going pretty well, However I am stuck on this one part, I am trying to "port" my old python application that takes a string or the users input and encrypts it. the python code is below, My problem is doing everything after and including the for loop. How might i go about searching for each letter in the Character string.
CHARACTER= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890-=+_)(*&^%$##!?><|:;}{]["
translated = ''
for uniqueKey in message:
if uniqueKey in CHARACTER:
num = CHARACTER.find(uniqueKey)
if mode == "encrypt":
num += key
elif mode == "decrypt":
num -= key
if num >= len(CHARACTER):
num -= len(CHARACTER)
elif num < 0:
num += len(CHARACTER)
translated = translated + CHARACTER[num]
else:
translated = translated + uniqueKey
I think the function you are looking for is IndexOf(). This is the equivalent of your find call above:
foreach (var uniqueKey in message)
{
var num = CHARACTER.IndexOf(uniqueKey);
if (num >= 0)
{
...
}
}

Store split values from user response 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 6 years ago.
Improve this question
I'm trying to create a grade calculator but I'm completely unsure how to compile the code to do so.
So far I've got the ability to split a user's response, but now I need to know how to take those splits and use them as separate values in order to create an average. I'm completely clueless how to achieve this and I've been searching for 2 days now on the internet with no luck.
Console.WriteLine ("User response seperated by commas goes here.");
string response = Console.ReadLine ();
Char delimiter = ',';
string[] splitResponses = response.Split (delimiter);
I need to know how to take those splits and use them as separate
values in order to create an average.
Not sure what you mean by take those splits and use them as separate
values, result is an array you could elements using index like splitResponseses[0]
To calculate the average you need to convert them to ints (or respective types), and calculate average.
string[] splitResponses = response.Split (delimiter); // Split string
int sum=0;
foreach(string s in splitResponses)
{
var valueInt = int.Parse(s); // convert string to an int.
sum+= valueInt;
}
double average = (double)sum/splitResponses.Length;
Another simple solution using Linq extensions.
int[] splitResponses = response.Split (delimiter) // Split string
.Select(int.Parse) // Convert To int value;
.ToArray();
Now you could calculate average using
splitResponses.Average(); // Average
splitResponses.Sum(); // Sum

Need to find whether a given key present withing the range of key available and return corresponding index value [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have large data of iteration count corresponding time started in second.
Based on any input second need to identify to which particular iteration count that input second belong to using C#.
Available Data:
string----int
iter_1----00
iter_2----06
iter_3----08
iter_5----20
.
iter_n----n
Desired output
03(input)-iter_1(output),
12(input)-iter_3(output)......
input can be as big as 1000 and code need obtain the desired out put based on input sec as many time 1000-10000times.
I am sure this can be possible done using List/Dictionary. I am not sure about Execution Time. Any DataStructure is fine.
I have used LIST and used linear search to solve this. Since the data which used to fill the list is sorted. i didn't use sorted list . Didn't find any notable time performance issue on using the list for 1500 item and did a linear search for 30000 time.
class Program
{
//Class to store iteration value and time
class test
{
public String Cycle;
public int Time;
};
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
doc.Load("test.xml");
List<test> Check = new List<test>();
foreach (XmlNode node in doc.DocumentElement.ChildNodes)
{
// Deatils to fill the list are obtained via XML , which is already sorted.
int totsec = (int)TimeSpan.Parse(node.Attributes["ElapsedTime"].Value).TotalSeconds;
Check.Add(new test() { Cycle = node.Name, Time = totsec });
}
// to Find the iteration , Do linear search via Find Function
int inputtocheck = 130;
int index = Check.IndexOf(Check.Find(item => item.Time >= inputtocheck ));
Console.WriteLine(Check[index].Cycle);
}
}

sum digits from a very long number [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Assume I let user input number : 1298743257884834...(long as user need)
Let program tell how many digit are they ?
then give result by SUM them = ?
By using LINQ
string input = // get input from console, textbox, ...
int inputLength = input.Length; // get number of digits, although you don't need it here
int sum = input.Sum(c => int.Parse(c.ToString())); // summarize
Hint: use the BigInteger structure found in System.Numerics.
First of all you can know the number of digits in this way:
string digits = TextBox1.Text;
long digitsnumber = digits.Length;
Then to sum each number, you need to loop in your string like an array of char, in this way, and cast the car value to an integer with the GetNumericValue method of System.Char:
int sum = 0;
foreach (var c in digits)
{
if (Char.IsNumber(c))
{
sum += (int)Char.GetNumericValue(c);
}
}
Sum will be your result.

Unique Permutations of a list(why won't this work)? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I was looking for a way to get all unique permutations of a List by groups of 3. I found a lot of source code to download and complex algorithms.
I finally just came up with my own code that seems to work. Could someone please tell me why the following is not a good idea. I'm assuming there must be something I am overlooking due to all the complex solutions I found and mine seems too simple.
var combinations = from a in Samples
from b in Samples
from c in Samples
where (string)a.sample != (string)b.sample
&& (string)a.sample != (string)c.sample
&& (string)b.sample != (string)c.sample
select new Rank
{
sample = a.sample,
sampleb = b.sample,
samplec = c.sample
};
foreach (var combo in combinations)
{
string[] aut = { combo.sample, combo.sampleb, combo.samplec };
Array.Sort(aut);
combo.sample = aut[0];
combo.sampleb = aut[1];
combo.samplec = aut[2];
l.Add(combo);
}
noDupes = from n in l
group n by new { n.sample, n.sampleb, n.samplec } into g
select new Rank
{
sample = g.Key.sample,
sampleb = g.Key.sampleb,
samplec = g.Key.samplec
};
You're adding all, then removing duplicates. You don't need to, see this (my) answer on permutations: https://stackoverflow.com/a/9315076/360211
Applying to your scenario, you have a 3 digit number (maxDigits = 3) where base = Samples.Count()
If your code already works, then the advantages of this approach are only performance related.

Categories

Resources