equivalent number to find exact match between two sets - c#

I am writing a program where I have a set of number 123456789 and words ABCDEFGHI. Now if a user enters any number its equivalent letter should show up in the result. Can someone guide me on how to approach this question.
For EX: user entry of 1352 should result in ACEB

Welcome here, your question is too 'easy' to become a question. And at lease you should show up what you have done.
But I will give you a shot.
I have wrote simple method for solve your question.
Sandbox to run this online
//Your code goes here
Console.WriteLine("Hello, world!");
//predifine your sets
var inputSet = new List<char> {'1','2','3','4','5','6','7','8','9','0'};
var outputSet = new List<char>{'A','B','C','D','E','F','G','H','I','J'};
//lets parse
Console.WriteLine(new string("1352".Select(x=>outputSet[inputSet.IndexOf(x)]).ToArray()));
Console.WriteLine(new string("199466856".Select(x=>outputSet[inputSet.IndexOf(x)]).ToArray()));
Console.WriteLine(new string("111222333444".Select(x=>outputSet[inputSet.IndexOf(x)]).ToArray()));
Result:
Hello, world!
ACEB
AIIDFFHEF
AAABBBCCCDDD
Edit:
Explain how it works.
"1352".Select(x) To select chars one by one in the string and store in x.
inputSet.IndexOf(x) To find position of x in inputSet
outputSet[int] To get value by given position from found position in inputSet recenly
new string(char array) Instantiate a new string by given char array.

Related

How can I make an automatic blank box out of a text?

I am new to C# and trying to figure out how I could do this.
So, what I am trying to do right now is to make a textbox out of text like this.
If I have a sentence saying "Hello World. I have a problem. Can you help me?", I want to randomly pick one word and let the user fill it in. Could you please help me how to randomize the pick and make a textbox?
Thanks in advance for your help! :)
PS. I posted a pic for better understanding
Example picture of what I want to do
Here is a way to get a random word of a sentence ...
You might split the sentence (tb.Text) into a string [] of words by using string.Split(' '). Then get a random number between '0' and .Length of your words.
Then pick the random substring.
// split the string into substrings seperated by a blank ' ' ...
var strArrWords = tb.Text.Split(' ');
// get the number of words ...
var numWords = strArrWords.Length;
// get a random number between '0' and numWords-1
Random rnd = new Random();
var number = rnd.Next(0, numWords - 1);
// finally get your random word ...
var word = tb.Text.Split(' ')[number];
or the same in 2 lines ...
Random rnd = new Random();
var word = tb.Text.Split(' ')[rnd.Next(0, tb.Text.Split(' ').Length - 1)];
To visualize this, you can maybee open another textbox displaying your word, the user can edit it. Then you replace the word in the other box, depends ...
I hope that helps :-)

How to get delete and added string in between two strings

In my requirement i have two strings (Dynamically) i want to compare two strings and strike off the deleted/modified string and also highlight the newly added string. one string is my old string and one string is new string, some times both are same based on user input. i tried but i cant get output. please help me. below is my tried code in c#
Ex: string s1 = "Hello dear Alice and dear Bob.";string s2 = " Hello Alice and dear Bob Have a nice day.";
Need Output: Hello dear Alice and dear Bob Have a nice day.
Dear is strike off and Have a nice day is highlight. pLEASE help me friends
My code:
if(String.Equals(my_NString,my_String,StringComparison.OrdinalIgnoreCase))
{
sb.AppendLine("<div><p style='text-align:justify;'>"+my_NString+" </p></div>");
sb.AppendLine("<br/>");
}
else
{
sb.AppendLine("<p style='text-align:justify;border:3px;border-color:#FF0000;padding:1em;color:red;'>"+my_NString+" </p>");
sb.AppendLine("<br/>");
}
}
This is not so easy. There's no one way to compare strings like that. There are different strategies and each have their up and downs. This is a very complicated task. Your best shot is to use an existing implementation of difference and variation algorithm, like this:
https://github.com/kpdecker/jsdiff (sorry, it's js)
PS: Editted:
Example really depends on what library/engine you'd like to use. The one that I'm most familiar with (and used most often) would look like this:
class Difference {
public static void Main(string[] args) {
diff_match_patch match = new diff_match_patch();
List<Diff> diff = match.diff_main("Hello World.", "Goodbye World.");
for (int i = 0; i < diff.Count; i++) Console.WriteLine(diff[i]);
}
}
The result would be:
[(-1, "Hell"), (1, "G"), (0, "o"), (1, "odbye"), (0, " World.")]
You could also use match.diff_cleanupSemantic(diff); before displaying, and then the result would be:
[(-1, "Hello"), (1, "Goodbye"), (0, " World.")]
So basically use diff_cleanupSemantic to change level of differences from 'letter-level' to 'word-level'.

Read input with different datatypes and space seperation

I'm trying to figure out how to write code to let the user input three values (string, int, int) in one line with space to separate the values.
I thought of doing it with String.Split Method but that only works if all the values have the same datatype.
How can I do it with different datatypes?
For example:
The user might want to input
Hello 23 54
I'm using console application C#
Well the first problem is that you need to decide whether the text the user enters itself can contain spaces. For example, is the following allowed?
Hello World, it's me 08 15
In that case, String.Split will not really be helpful.
What I'd try is using a regular expression. The following may serve as a starting point:
Match m = Regex.Match(input, #"^(?<text>.+) (?<num1>(\+|\-)?\d+) (?<num2>(\+|\-)?\d+)$");
if (m.Success)
{
string stringValue = m.Groups["text"].Value;
int num1 = Convert.ToInt32(m.Groups["num1"].Value);
int num2 = Convert.ToInt32(m.Groups["num2"].Value);
}
BTW: The following part of your question makes me frown:
I thought of doing it with String.Split Method but that only works if all the values have the same datatype.
A string is always just a string. Whether it contains a text, your email-address or your bank account balance. It is always just a series of characters. The notion that the string contains a number is just your interpretation!
So from a program's point of view, the string you gave is a series of characters. And for splitting that it doesn't matter at all what the real semantics of the content are.
That's why the splitting part is separate from the conversion part. You need to tell your application that that the first part is a string, the second and third parts however are supposed to be numbers. That's what you need type conversions for.
You are confusing things. A string is either null, empty or contains a sequence of characters. It never contains other data types. However, it might contain parts that could be interpreted as numbers, dates, colors etc... (but they are still strings). "123" is not an int! It is a string containing a number.
In order to extract these pieces you need to do two things:
Split the string into several string parts.
Convert string parts that are supposed to represent whole numbers into a the int type (=System.Int32).
string input = "Abc 123 456"
string[] parts = input.Split(); //Whitespaces are assumed as separators by default.
if (parts.Count == 3) {
Console.WriteLine("The text is \"{0}\"", parts[0]);
int n1;
if (Int32.TryParse(parts[1], out n1)) {
Console.WriteLine("The 1st number is {0}", n1);
} else {
Console.WriteLine("The second part is supposed to be a whole number.");
}
int n2;
if (Int32.TryParse(parts[2], out n2)) {
Console.WriteLine("The 2nd number is {0}", n2);
} else {
Console.WriteLine("The third part is supposed to be a whole number.");
}
} else {
Console.WriteLine("You must enter three parts separated by a space.");
}
What you have to do is get "Hello 23 54" in a string variable. Split by " " and treat them.
string value = "Hello 23 54";
var listValues = value.Split(' ').ToList();
After that you have to parse each item from listValues to your related types.
Hope it helps. ;)

grouping adjacent similar substrings

I am writing a program in which I want to group the adjacent substrings, e.g ABCABCBC can be compressed as 2ABC1BC or 1ABCA2BC.
Among all the possible options I want to find the resultant string with the minimum length.
Here is code what i have written so far but not doing job. Kindly help me in this regard.
using System;
using System.Collections.Generic;
using System.Linq;
namespace EightPrgram
{
class Program
{
static void Main(string[] args)
{
string input;
Console.WriteLine("Please enter the set of operations: ");
input = Console.ReadLine();
char[] array = input.ToCharArray();
List<string> list = new List<string>();
string temp = "";
string firstTemp = "";
foreach (var x in array)
{
if (temp.Contains(x))
{
firstTemp = temp;
if (list.Contains(firstTemp))
{
list.Add(firstTemp);
}
temp = "";
list.Add(firstTemp);
}
else
{
temp += x;
}
}
/*foreach (var item in list)
{
Console.WriteLine(item);
}*/
Console.ReadLine();
}
}
}
You can do this with recursion. I cannot give you a C# solution, since I do not have a C# compiler here, but the general idea together with a python solution should do the trick, too.
So you have an input string ABCABCBC. And you want to transform this into an advanced variant of run length encoding (let's called it advanced RLE).
My idea consists of a general first idea onto which I then apply recursion:
The overall target is to find the shortest representation of the string using advanced RLE, let's create a function shortest_repr(string).
You can divide the string into a prefix and a suffix and then check if the prefix can be found at the beginning of the suffix. For your input example this would be:
(A, BCABCBC)
(AB, CABCBC)
(ABC, ABCBC)
(ABCA, BCBC)
...
This input can be put into a function shorten_prefix, which checks how often the suffix starts with the prefix (e.g. for the prefix ABC and the suffix ABCBC, the prefix is only one time at the beginning of the suffix, making a total of 2 ABC following each other. So, we can compact this prefix / suffix combination to the output (2ABC, BC).
This function shorten_prefix will be used on each of the above tuples in a loop.
After using the function shorten_prefix one time, there still is a suffix for most of the string combinations. E.g. in the output (2ABC, BC), there still is the string BC as suffix. So, need to find the shortest representation for this remaining suffix. Wooo, we still have a function for this called shortest_repr, so let's just call this onto the remaining suffix.
This image displays how this recursion works (I only expanded one of the node after the 3rd level, but in fact all of the orange circles would go through recursion):
We start at the top with a call of shortest_repr to the string ABABB (I selected a shorter sample for the image). Then, we split this string at all possible split positions and get a list of prefix / suffix pairs in the second row. On each of the elements of this list we first call the prefix/suffix optimization (shorten_prefix) and retrieve a shortened prefix/suffix combination, which already has the run-length numbers in the prefix (third row). Now, on each of the suffix, we call our recursion function shortest_repr.
I did not display the upward-direction of the recursion. When a suffix is the empty string, we pass an empty string into shortest_repr. Of course, the shortest representation of the empty string is the empty string, so we can return the empty string immediately.
When the result of the call to shortest_repr was received inside our loop, we just select the shortest string inside the loop and return this.
This is some quickly hacked code that does the trick:
def shorten_beginning(beginning, ending):
count = 1
while ending.startswith(beginning):
count += 1
ending = ending[len(beginning):]
return str(count) + beginning, ending
def find_shortest_repr(string):
possible_variants = []
if not string:
return ''
for i in range(1, len(string) + 1):
beginning = string[:i]
ending = string[i:]
shortened, new_ending = shorten_beginning(beginning, ending)
shortest_ending = find_shortest_repr(new_ending)
possible_variants.append(shortened + shortest_ending)
return min([(len(x), x) for x in possible_variants])[1]
print(find_shortest_repr('ABCABCBC'))
print(find_shortest_repr('ABCABCABCABCBC'))
print(find_shortest_repr('ABCABCBCBCBCBCBC'))
Open issues
I think this approach has the same problem as the recursive levenshtein distance calculation. It calculates the same suffices multiple times. So, it would be a nice exercise to try to implement this with dynamic programming.
If this is not a school assignment or performance critical part of the code, RegEx might be enough:
string input = "ABCABCBC";
var re = new Regex(#"(.+)\1+|(.+)", RegexOptions.Compiled); // RegexOptions.Compiled is optional if you use it more than once
string output = re.Replace(input,
m => (m.Length / m.Result("$1$2").Length) + m.Result("$1$2")); // "2ABC1BC" (case sensitive by default)

getting numbers from a textbox that has letters and numbers

I am trying to make a console based modding application for a PS3 game.
one of the commands goes like
"kills value"
the value being a number the user defines, How would i only get the "value" of the textbox so it sets the users "kills" to what they defined.
Would it be good to get the value then send it to a label were. After a bit of coding would set the players "kills" to what they defined?
Using regular expressions would make everything easier.
using System.Text.RegularExpressions;
var input = "kills 67"; // Just an example!
var kill_str = Regex.Match(input, #"\d+").Value;
int kills = Int32.Parse(kill_str); // Now we have the number specified by our user
// Now, do whatever you want with the collected data
info_label.text = string.format("You specified {0} kills to be added within the hack.", kills);
var input = "kills value"
var value = input.Split(new char[] {' '})[1];

Categories

Resources