need help with building a function
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 14 of 14

Thread: need help with building a function

  1. #1
    Join Date
    May 2011
    Posts
    7

    Question need help with building a function

    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?

  2. #2
    Arjay's Avatar
    Arjay is online now Moderator / MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    10,958

    Re: need help with building a function

    Generally, for homework questions, it's always a good idea to post the code that you have (even if it doesn't yet work right).

  3. #3
    Join Date
    May 2011
    Posts
    7

    Re: need help with building a function

    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.

  4. #4
    Join Date
    May 2011
    Location
    Nazareth
    Posts
    5

    Re: need help with building a function

    c or c#

  5. #5
    Join Date
    May 2011
    Location
    Nazareth
    Posts
    5

    Re: need help with building a function

    public int result (string x)
    {
    //string x = "1234";
    string num1, num2;
    int n1, n2, res;

    num1=(x.Remove(2,2));
    num2=(x.Remove(0, 2));
    n1=int.Parse(num1);
    n2=int.Parse(num2);
    res = n1 + n2;
    return res;
    }

  6. #6
    Join Date
    May 2011
    Posts
    7

    Re: need help with building a function

    I write on c#.
    Remove is an interesting function, but it doesn't solve the task.

  7. #7
    Join Date
    May 2011
    Location
    Nazareth
    Posts
    5

    Re: need help with building a function

    what is the task exactly > my function work to me very well .!!!??!!?

  8. #8
    Join Date
    May 2011
    Posts
    7

    Re: need help with building a function

    Read the first post.

  9. #9
    Arjay's Avatar
    Arjay is online now Moderator / MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    10,958

    Re: need help with building a function

    Quote Originally Posted by anter View Post
    Read the first post.
    Read my first reply.

    If you want help with homework, you have to post the code you have written.

  10. #10
    Join Date
    May 2011
    Location
    Washington State
    Posts
    220

    Re: need help with building a function

    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.

  11. #11
    Join Date
    May 2011
    Posts
    7

    Re: need help with building a function

    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.

  12. #12
    Join Date
    May 2011
    Posts
    7

    Re: need help with building a function

    Well I gave it a try and with my version i finds more options, but it still gets lost with bigger numbers such as (123456789=252 - 123+45+67+8+9=252).
    Here is my code:
    Code:
    static void Main(string[] args)
            {
                int n, Right;
                string Left;
                Console.WriteLine("Enter the left number of the expression.");
                n = int.Parse(Console.ReadLine());
                Left = n.ToString();
                Console.WriteLine("Enter the right number of the expression.");
                Right = int.Parse(Console.ReadLine());
                string extra = "";
                bool found = false;
                for (int i = 0; i < Left.Length; i++)
                {
                    extra = Left.Remove(i);
                    string lleft = Left.Remove(0, extra.Length);
                    if (Test(lleft, Right, extra))
                        found = true;
                }
                if (!found)
                    Console.WriteLine("unresolved");
                WaitForUser();
            }
    
            static bool Test(string source, int answer, string extra)
            {
                bool found = false;
                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(" ", "");
                        {
                            found = true;
                            if (!extra.Equals(""))
                                Console.WriteLine(extra + "+" + formula);
                            else
                                Console.WriteLine(formula);
                        }
    
                        j += 2;
                    }
    
                    source = source.Replace("+", " ");
                }
                if (found)
                    return true;
                return false;
    
            }
    
            static int GetAnswerForForumla(string formula, string extra)
            {
                int answer = 0;
                string[] parts = formula.Split('+');
    
                foreach (string part in parts)
                {
                    int partValue = 0;
                    if (Int32.TryParse(part, out partValue))
                    {
                        answer += partValue;
                    }
                }
                if(!extra.Equals(""))
                answer += Int32.Parse(extra);
    
                return answer;
            }
    
            static void WaitForUser()
            {
                Console.WriteLine("");
                Console.WriteLine("Press any key to close application...");
                while (!Console.KeyAvailable) ;
            }
    Definetily, the algorithm for this needs another approach...
    Any ideas?
    Last edited by anter; June 7th, 2011 at 10:11 AM.

  13. #13
    Join Date
    May 2011
    Location
    Washington State
    Posts
    220

    Re: need help with building a function

    Well, that is an interesting logic assignment... I may tinker with it a bit when I have time... but given another few minutes to think it over, it occurred to me I wasn't doing you any favors by having you stick with string manipulation rather than getting all of your possible values and working with those.

    I will let you work on the overall logic from this point... this should give you a list of all the values you could possibly combine to get an answer, working with the values should be a better approach than tweaking strings the whole time as I first did...

    Code:
                List<int> values = new List<int>();
    
                for (int i = 0; i < source.Length; i++)
                    for (int j = 1; j < ((source.Length - i) + 1); j++)
                        if (source.Substring(i,j).Length < source.Length)   // dont want to bother with the whole string + nothing
                            values.Add(int.Parse(source.Substring(i, j)));
    So... find a way to test adding these values together until you hit the right combo.

    Good luck!

  14. #14
    Join Date
    May 2011
    Posts
    7

    Re: need help with building a function

    I didn't find a way to write a solution to this task using List, however I managed to find another way using binary numbers. I don't know if this is the most elegant solution, but I think it works fine .
    I found all binary numbers in range from 0 to the biggest number with same number of digits as the number of possible + positions. Then I used every "1" digit in the list of the binary numbers as + and its position in the number as a position for the +.

    For example:
    the left number in the equation is: 12345
    one of the binary numbers in the list: 1101
    so the formula will look like this: 1+2+34+5

    here is the code:

    Code:
    static void Main(string[] args)
            {
                int n, Right;
                string Left;
                Console.WriteLine("Enter the left number of the expression.");
                n = int.Parse(Console.ReadLine());
                Left = n.ToString();
                Console.WriteLine("Enter the right number of the expression.");
                Right = int.Parse(Console.ReadLine());
                Plusses(Left, Right);
                WaitForUser();
            }
            static void Plusses(string Left, int Right)
            {
                bool found = false;
    
                //Checks if the left side of the equation is equal to the right side.
                if (Right == int.Parse(Left))
                {
                    Console.WriteLine("The answer(s) is: {0}", Left); 
                    found = true;
                }
    
                //this is how I find the biggest binary number
                char[] CV = new char[Left.Length-1];
                for (int i = 0; i < Left.Length-1; i++)
                    CV[i] = '1';
                int BiggestNumber = int.Parse(new string(CV));
    
                //placeholders for every possible + position
                for (int i = 1; i < Left.Length; i += 2) 
                    Left = Left.Insert(i, " ");
    
                string Binary = "";
                bool big = false;
    
                for (int i = 1; !big; i++)
                {
                    Binary = ToBinary(i);
                    while (Binary.Length < CV.Length)
                        Binary = "0" + Binary;
    
                    int z = 1;
                    for (int j = 0; j < Binary.Length; j++)
                    {
                        if (Binary[j].Equals('1'))
                        {
                            Left = Left.Remove(z, 1);
                            Left = Left.Insert(z, "+");
                        }
                        z += 2;
                    }
    
                    string formula = Left.Replace(" ", "");
                    if (Right == GetAnswerForForumla(formula))
                    {
                        Console.WriteLine("The answer(s) is: {0}", formula);
                        found = true;
                    }
    
                    Left = Left.Replace("+", " ");
    
                    if (!(BiggestNumber > int.Parse(ToBinary(i))))
                        big = true;
                }
                if (!found)
                    Console.WriteLine("unresolved");
            }
            //function that converts decimal numbers to binary numbers
            static string ToBinary(int Decimal)
            {
                int 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);
                return BinaryResult;
            }
            static int GetAnswerForForumla(string formula)
            {
                int answer = 0;
    
                string[] parts = formula.Split('+');
    
                //I added these 3 rows to prevent from zeros messing the output.
                for (int i = 0; i < parts.Length; i++)
                    if (parts[i][0].Equals('0') && parts[i].Length > 1)
                        return answer + 1;
    
                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) ;
            }

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center