Hello folks,
I have a task that I cannot solve, maybe you guys can help me out .
To explain it I'll start with an example.
1234=46
2222=8
These equations are false, but if you add plusses between the digits you can make them be true, like this:
12+34=46
2+2+2+2=8
You need to build a function that gets 2 numbers (the left side and the right side of the equation), puts the plusses in right places between the digits of the left number, and then returns the equation in it's true form.
It is important to notice that there can be a random number of plusses.
That's it, have any idea?
I tried to write it, but the code was too long and complicated. Not to mention it didn't work. So I thought that there is an easier way for sure, maybe a trick that I don't know. Basicaly, I tried to get all the possible positions of plusses between the digits, then check if the sum matches the right number. The problem is that I have no idea how to get the collection of all of these positions.
Here is a little console program that I think will do what you are wanting... like the others, I believe you should actually write some attempts, or at least show what you attempted, as then we can feel better about helping you out... however, I also believe you can study the code below and still learn from it, and perhaps improve on it as you gather some understanding.
Good luck!
Code:
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine(Test("12345", 15));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
WaitForUser();
}
static string Test(string source, int answer)
{
// add placeholder for every possible + position
for (int i = 1; i < source.Length; i += 2)
source = source.Insert(i, " ");
for (int i = 1; i < source.Length; i += 2)
{
int j = i;
while (j < source.Length)
{
source = source.Remove(j, 1);
source = source.Insert(j, "+");
string formula = source.Replace(" ", "");
if (answer == GetAnswerForForumla(formula))
return formula;
j += 2;
}
source = source.Replace("+", " ");
}
return "unresolved";
}
static int GetAnswerForForumla(string formula)
{
int answer = 0;
string[] parts = formula.Split('+');
foreach (string part in parts)
{
int partValue = 0;
if (Int32.TryParse(part, out partValue))
answer += partValue;
}
return answer;
}
static void WaitForUser()
{
Console.WriteLine("");
Console.WriteLine("Press any key to close application...");
while (!Console.KeyAvailable) ;
}
}
Last edited by fcronin; May 19th, 2011 at 03:30 PM.
Sorry I wasn't around for so long, but I still don't have a full solution to this exercise.
fcronin, thank you, your post helped me very much. But your solution doesn't check all the options, for example if the left number is 12345 and the right one is 240 (1+234+5) your solution won't find the answer, although it exists.
I will try to fix it and if I will, I'll post it here.
Bookmarks