Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. The Lounge
  3. Coding Challenge

Coding Challenge

Scheduled Pinned Locked Moved The Lounge
c++architecturehelp
165 Posts 47 Posters 1 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • C Chris Maunder

    Back in the Days of Yore we had a couple of small coding challenges such as the Lean and Mean comp. I was thinking that there are a ton of small, well defined problems that can be tackled a zillion ways in a zillion languages and that it would be cool to see what you guys can come up with. I'd like to start the ball rolling with the following simple task: Problem: Given a string of text, trim from each end of the text each all occurrences of a given set of strings Sample input: Input string: "dog cat monkey dog horse dog" Strings that need to be trimmed from each end: { "dog", "cat" } Final output should be: " monkey dog horse" Final output should be " cat monkey dog horse " [Edit: My final sample output was incorrect, so to be fair I'll accept either answer] It's up to you whether you worry about case sensitivity. Let's see who can provide the smallest, neatest most elegant, most unique and/or fastest code. For those who feel like jumping on the "No Programming questions" bandwagon, please re-read the lounge guidelines. The point of this is to have fun, not to solve each other's programming issues.

    cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

    S Offline
    S Offline
    Slacker007
    wrote on last edited by
    #122

    my $trimWord = "dog";
    my $string = "dog cat monkey dog horse dog";

    $string =~ s/^($trimWord)+|($trimWord)+$//g;

    print $string;

    Just along for the ride. "the meat from that butcher is just the dogs danglies, absolutely amazing cuts of beef." - DaveAuld (2011)
    "No, that is just the earthly manifestation of the Great God Retardon." - Nagy Vilmos (2011) "It is the celestial scrotum of good luck!" - Nagy Vilmos (2011)

    1 Reply Last reply
    0
    • N NormDroid

      Shit my eyes are bleeding :)

      Software Kinetics Wear a hard hat it's under construction
      Metro RSS

      S Offline
      S Offline
      Slacker007
      wrote on last edited by
      #123

      You shat your eyes or your eyes are bleeding? :laugh: :-D :thumbsup:

      Just along for the ride. "the meat from that butcher is just the dogs danglies, absolutely amazing cuts of beef." - DaveAuld (2011)
      "No, that is just the earthly manifestation of the Great God Retardon." - Nagy Vilmos (2011) "It is the celestial scrotum of good luck!" - Nagy Vilmos (2011)

      1 Reply Last reply
      0
      • C Chris Maunder

        Back in the Days of Yore we had a couple of small coding challenges such as the Lean and Mean comp. I was thinking that there are a ton of small, well defined problems that can be tackled a zillion ways in a zillion languages and that it would be cool to see what you guys can come up with. I'd like to start the ball rolling with the following simple task: Problem: Given a string of text, trim from each end of the text each all occurrences of a given set of strings Sample input: Input string: "dog cat monkey dog horse dog" Strings that need to be trimmed from each end: { "dog", "cat" } Final output should be: " monkey dog horse" Final output should be " cat monkey dog horse " [Edit: My final sample output was incorrect, so to be fair I'll accept either answer] It's up to you whether you worry about case sensitivity. Let's see who can provide the smallest, neatest most elegant, most unique and/or fastest code. For those who feel like jumping on the "No Programming questions" bandwagon, please re-read the lounge guidelines. The point of this is to have fun, not to solve each other's programming issues.

        cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

        C Offline
        C Offline
        CPallini
        wrote on last edited by
        #124

        The function:

        -- function
        require("lpeg")
        d = lpeg.P"dog" + lpeg.P"cat"
        g = d^0 * lpeg.C((1-d)^1 * (d^0 * (1-d))^0) * d^0
        function trm(s) return lpeg.match(g, s) or "" end

        the test:

        -- test
        t = {
        "dog cat monkey dog horse dog",
        "dogcatmonkeycatcatcat",
        "dog",
        "doghorsedogdog dog",
        "monkey",
        "catcatdogcathorse sheep dog cat pig horse sheepcatmonkeydogcat"
        }

        for i,v in ipairs(t) do
        print ("'" .. v .. "'" .. " -> " .. "'" .. trm(v) .. "'")
        end

        the output:

        'dog cat monkey dog horse dog' -> ' cat monkey dog horse '
        'dogcatmonkeycatcatcat' -> 'monkey'
        'dog' -> ''
        'doghorsedogdog dog' -> 'horsedogdog '
        'monkey' -> 'monkey'
        'catcatdogcathorse sheep dog cat pig horse sheepcatmonkeydogcat' -> 'horse sheep dog cat pig horse sheepcatmonkey'

        If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
        This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
        [My articles]

        1 Reply Last reply
        0
        • OriginalGriffO OriginalGriff

          I have discovered a truly marvellous solution of this, which the margin of this website is too narrow to contain.

          Ideological Purity is no substitute for being able to stick your thumb down a pipe to stop the water

          L Offline
          L Offline
          Lost User
          wrote on last edited by
          #125

          I bet that's the last programming challenge you try!

          MVVM# - See how I did MVVM my way ___________________________________________ Man, you're a god. - walterhevedeich 26/05/2011 .\\axxx (That's an 'M')

          1 Reply Last reply
          0
          • C Chris Maunder

            Back in the Days of Yore we had a couple of small coding challenges such as the Lean and Mean comp. I was thinking that there are a ton of small, well defined problems that can be tackled a zillion ways in a zillion languages and that it would be cool to see what you guys can come up with. I'd like to start the ball rolling with the following simple task: Problem: Given a string of text, trim from each end of the text each all occurrences of a given set of strings Sample input: Input string: "dog cat monkey dog horse dog" Strings that need to be trimmed from each end: { "dog", "cat" } Final output should be: " monkey dog horse" Final output should be " cat monkey dog horse " [Edit: My final sample output was incorrect, so to be fair I'll accept either answer] It's up to you whether you worry about case sensitivity. Let's see who can provide the smallest, neatest most elegant, most unique and/or fastest code. For those who feel like jumping on the "No Programming questions" bandwagon, please re-read the lounge guidelines. The point of this is to have fun, not to solve each other's programming issues.

            cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

            L Offline
            L Offline
            Lost User
            wrote on last edited by
            #126

            Chris Maunder wrote:

            Given a string of text, trim from each end of the text each all occurrences of a given set of strings

            Assuming (from your sample) you only want to remove a single item from each end (hence the leading 'cat' remains), then the below would seem to provide the requisite output and I feel earn bonus points for its simplicity, elegance and the fact that it's the first opportunity I've had to do c# for nearly a year!

            private string CodingChallenge(string source, string[] removals)
            {
            string delimiter = " ";
            bool leftDone = false;
            bool rightDone = false;

                    foreach (string s in removals)
                    {
                        if (!leftDone && source.Substring(0, s.Length) == s && source.Substring(s.Length, 1) == delimiter)
                        {
                            source = source.Substring(s.Length);
                            leftDone = true;
                        }
            
                        if (!rightDone && source.Substring(source.Length - s.Length) == s && source.Substring(source.Length - s.Length - 1, 1) == delimiter)
                        {
                            source = source.Substring(0, source.Length - s.Length);
                            rightDone = true;
                        }
                    }
            
                    return source;
                }
            

            MVVM# - See how I did MVVM my way ___________________________________________ Man, you're a god. - walterhevedeich 26/05/2011 .\\axxx (That's an 'M')

            1 Reply Last reply
            0
            • C Chris Maunder

              Back in the Days of Yore we had a couple of small coding challenges such as the Lean and Mean comp. I was thinking that there are a ton of small, well defined problems that can be tackled a zillion ways in a zillion languages and that it would be cool to see what you guys can come up with. I'd like to start the ball rolling with the following simple task: Problem: Given a string of text, trim from each end of the text each all occurrences of a given set of strings Sample input: Input string: "dog cat monkey dog horse dog" Strings that need to be trimmed from each end: { "dog", "cat" } Final output should be: " monkey dog horse" Final output should be " cat monkey dog horse " [Edit: My final sample output was incorrect, so to be fair I'll accept either answer] It's up to you whether you worry about case sensitivity. Let's see who can provide the smallest, neatest most elegant, most unique and/or fastest code. For those who feel like jumping on the "No Programming questions" bandwagon, please re-read the lounge guidelines. The point of this is to have fun, not to solve each other's programming issues.

              cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

              E Offline
              E Offline
              ErnestoNet
              wrote on last edited by
              #127

              Need to check this with other strings, debug some more, improve comments and string handling in main(), etc. But still....here it goes:

              #include "stdafx.h"

              const wchar_t whitechar = ' ';
              const bool IncludeWhiteSpace = true;
              const wchar_t* wordstoremove[] = {L"dog", L"cat"};

              const wchar_t* strtoparse = L"dog cat monkey dog horse dog"; //Len 28
              int ltoparse;
              const int numwords = 2;

              int wordlen[numwords];

              //Positions in the original string to rip
              int pos_orig_from;
              int pos_orig_to;

              //Len of left and right copies
              int left_len;
              int right_len;

              //Gets hoy many bytes per char
              void ProcessLeft(wchar_t* strresult)
              {
              bool bContinue = true;

              pos\_orig\_from = left\_len = 0;
              
              while (bContinue)
              {
              	//Check for whitespaces. If there are, copy them
              	if (strtoparse\[pos\_orig\_from\] == whitechar)
              	{
              		pos\_orig\_from ++;
              		if (IncludeWhiteSpace)
              		{
              			strresult\[left\_len\] = whitechar;
              			left\_len ++;
              		}
              	}
              	else
              	{
              		bContinue = false;
              		for (int i = 0; i < numwords; i++)
              		{
              			//Compare strings
              			wchar\_t\* strcompare = (wchar\_t\*)strtoparse + pos\_orig\_from;
              			if (wcsncmp(strcompare, wordstoremove\[i\], wordlen\[i\]) == 0)
              			{
              				pos\_orig\_from += wordlen\[i\];
              				bContinue = true;
              				break;
              			}
              		}
              	}
              }
              

              }
              void ProcessRight(wchar_t* strresult)
              {
              bool bContinue = true;

              pos\_orig\_to = right\_len = ltoparse - 1;
              
              while (bContinue)
              {
              	//Check for whitespaces. If there are, copy them
              	if (strtoparse\[pos\_orig\_to\] == whitechar && IncludeWhiteSpace)
              	{
              		pos\_orig\_to -= 1;
              		if (IncludeWhiteSpace)
              		{
              			strresult\[right\_len\] = whitechar;
              			right\_len -= 1;
              		}
              	}
              	else
              	{
              		bContinue = false;
              		for (int i = 0; i < numwords; i++)
              		{
              			//Compare strings
              			//To check right, start from end and substract string to compare len
              			wchar\_t\* strcompare = (wchar\_t\*)strtoparse + pos\_orig\_to - wordlen\[i\] + 1;
              			if (wcsncmp(strcompare, wordstoremove\[i\], wordlen\[i\]) == 0)
              			{
              				pos\_orig\_to -= wordlen\[i\];
              				bContinue = true;
              				break;
              			}
              		}
              	}
              }
              

              }

              int _tmain(int argc, _TCHAR* argv[])
              {

              //Load len of words to avoid rechecking
              for (int i=0; i
              
              1 Reply Last reply
              0
              • M Marc Clifton

                Dang, what are we, a bunch of whiners? It's a PROGRAMMING CHALLENGE! START YOUR CODING ENGINES!!! Do we need detail specs? Hell NO!!! There's probably a regex solution, but that's gross. Here's something I whipped together in about 15 minutes (took a bit of debugging, a few nuances to it) that I hope readable and somewhat reusable:

                using System;
                using System.Collections.Generic;
                using System.Linq;
                using System.Text;
                namespace Stripper
                {
                public enum StringPoint
                {
                None,
                Start,
                End,
                }
                public static class StringHelpersExtensions
                {
                public static string RightOf(this String src, string s)
                {
                string ret = src;
                int idx = src.IndexOf(s);
                if (idx != -1)
                {
                ret = src.Substring(s.Length);
                }
                return ret;
                }
                public static string LeftOfRightmostOf(this String src, string s)
                {
                string ret = src;
                int idx = src.LastIndexOf(s);
                if (idx != -1)
                {
                ret = src.Substring(0, idx);
                }
                return ret;
                }
                public static bool StartsOrEndsWith(this String src, string[] items, out string match, out StringPoint whichEnd)
                {
                bool ret = false;
                whichEnd = StringPoint.None;
                match = String.Empty;
                foreach (string item in items)
                {
                if (src.StartsWith(item))
                {
                match = item;
                whichEnd = StringPoint.Start;
                ret = true;
                break;
                }
                if (src.EndsWith(item))
                {
                match = item;
                whichEnd = StringPoint.End;
                ret = true;
                break;
                }
                }
                return ret;
                }
                }
                class Program
                {
                static void Main(string[] args)
                {
                string input = "dog cat monkey dog horse dog";
                string[] stripOf = { "dog", "cat" };
                string desiredOutput = " monkey dog horse ";
                string result = Stripper(input, stripOf);
                if (result == desiredOutput)
                {
                Console.WriteLine("Success");
                }
                else
                {
                Console.WriteLine("Fail! '" + result + "'");
                }
                }
                static string Stripper(string input, string[] stripOf)
                {
                string ret = input;
                string match;
                StringPoint whichEnd;
                string test = ret.Trim();
                string leftPad = String.Empty;
                string rightPad = String.Empty;
                while (test.StartsOrEndsWith(stripOf, out match, out whichEnd))
                {
                switch (whichEnd)
                {
                case StringPoint.Start:
                // The result always preserves the leading space separating the token, so add it back in.
                leftPad = " ";
                ret = leftPad + test.RightOf(match).Trim() + rightPad;
                break;
                case StringPoint.End:
                // The result always preserves

                P Offline
                P Offline
                Pete OHanlon
                wrote on last edited by
                #128

                Your former client base is showing mate - calling a method Stripper.

                Forgive your enemies - it messes with their heads

                "Mind bleach! Send me mind bleach!" - Nagy Vilmos

                My blog | My articles | MoXAML PowerToys | Mole 2010 - debugging made easier - my favourite utility

                M 1 Reply Last reply
                0
                • C Chris Maunder

                  Back in the Days of Yore we had a couple of small coding challenges such as the Lean and Mean comp. I was thinking that there are a ton of small, well defined problems that can be tackled a zillion ways in a zillion languages and that it would be cool to see what you guys can come up with. I'd like to start the ball rolling with the following simple task: Problem: Given a string of text, trim from each end of the text each all occurrences of a given set of strings Sample input: Input string: "dog cat monkey dog horse dog" Strings that need to be trimmed from each end: { "dog", "cat" } Final output should be: " monkey dog horse" Final output should be " cat monkey dog horse " [Edit: My final sample output was incorrect, so to be fair I'll accept either answer] It's up to you whether you worry about case sensitivity. Let's see who can provide the smallest, neatest most elegant, most unique and/or fastest code. For those who feel like jumping on the "No Programming questions" bandwagon, please re-read the lounge guidelines. The point of this is to have fun, not to solve each other's programming issues.

                  cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                  A Offline
                  A Offline
                  AnthonyN1974
                  wrote on last edited by
                  #129

                  I was fed up, so here it is in c#

                  using System;
                  using System.Collections.Generic;
                  using System.Linq;
                  using System.Text;

                  namespace CodeChallenge
                  {
                  class Program
                  {
                  private static List<string> wordsToRemove = new List<string>() { "dog", "cat" };

                  static void Main(string\[\] args)
                  {
                    string text = "dog cat monkey dog horse dog";
                  
                    string\[\] words = text.Split(' ');
                    string\[\] output;
                    int start = 0;
                    int end = 0;
                  
                    // test the start
                    if (wordsToRemove.Contains(words\[0\]) && words.Length > 0)
                      start = 1;
                  
                    // test the end
                    if (wordsToRemove.Contains(words\[words.Length - 1\]) && words.Length != start)
                      end = (words.Length - 1) - start;
                    else
                      end = words.Length - start;
                  
                    //build
                    output = new string\[end\];
                    Array.Copy(words, start, output, 0, end);
                  
                    //output
                    Console.WriteLine(string.Join(" ",output));
                  }
                  

                  }
                  }

                  1 Reply Last reply
                  0
                  • C Chris Maunder

                    Back in the Days of Yore we had a couple of small coding challenges such as the Lean and Mean comp. I was thinking that there are a ton of small, well defined problems that can be tackled a zillion ways in a zillion languages and that it would be cool to see what you guys can come up with. I'd like to start the ball rolling with the following simple task: Problem: Given a string of text, trim from each end of the text each all occurrences of a given set of strings Sample input: Input string: "dog cat monkey dog horse dog" Strings that need to be trimmed from each end: { "dog", "cat" } Final output should be: " monkey dog horse" Final output should be " cat monkey dog horse " [Edit: My final sample output was incorrect, so to be fair I'll accept either answer] It's up to you whether you worry about case sensitivity. Let's see who can provide the smallest, neatest most elegant, most unique and/or fastest code. For those who feel like jumping on the "No Programming questions" bandwagon, please re-read the lounge guidelines. The point of this is to have fun, not to solve each other's programming issues.

                    cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                    M Offline
                    M Offline
                    mrchief_2000
                    wrote on last edited by
                    #130

                    Probably not the most efficient, but in C#, this works:

                    using System.Text.RegularExpressions;

                    var source = "dog cat dog horses monkeys dog";
                    var stringsToTrim = new[] { "dog", "cat" };
                    var trimmedString = Regex.Replace(source, string.Format("^({0})|({0})$", string.Join("|", stringsToTrim )), "");
                    Console.WriteLine(trimmedString);

                    Live demo: http://rextester.com/GTLWO64640[^] Making above shorter:

                    using System.Text.RegularExpressions;

                    Console.WriteLine(Regex.Replace("dog cat dog horses monkeys dog", string.Format("^({0})|({0})$", string.Join("|", "dog", "cat")), ""));

                    1 Reply Last reply
                    0
                    • C Chris Maunder

                      Back in the Days of Yore we had a couple of small coding challenges such as the Lean and Mean comp. I was thinking that there are a ton of small, well defined problems that can be tackled a zillion ways in a zillion languages and that it would be cool to see what you guys can come up with. I'd like to start the ball rolling with the following simple task: Problem: Given a string of text, trim from each end of the text each all occurrences of a given set of strings Sample input: Input string: "dog cat monkey dog horse dog" Strings that need to be trimmed from each end: { "dog", "cat" } Final output should be: " monkey dog horse" Final output should be " cat monkey dog horse " [Edit: My final sample output was incorrect, so to be fair I'll accept either answer] It's up to you whether you worry about case sensitivity. Let's see who can provide the smallest, neatest most elegant, most unique and/or fastest code. For those who feel like jumping on the "No Programming questions" bandwagon, please re-read the lounge guidelines. The point of this is to have fun, not to solve each other's programming issues.

                      cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                      C Offline
                      C Offline
                      Clumpco
                      wrote on last edited by
                      #131

                      Here's a solution in APL V←'dog cat monkey dog horse dog' Q←'dog' V←(((V≠Q)⍳1)-⎕IO)↓V V←(⎕IO-(Q≠⌽V)⍳1)↓V Q←'cat' V←(((V≠Q)⍳1)-⎕IO)↓V V←(⎕IO-(Q≠⌽V)⍳1)↓V No doubt a true APL programmer could do it in one line.

                      1 Reply Last reply
                      0
                      • C Chris Maunder

                        Quote:

                        There's probably a regex solution

                        result = Regex.Replace("dog cat monkey dog horse dog", "^(dog|cat)*(.*?)((dog|cat)*)$", "$2",
                        RegexOptions.IgnoreCase | RegexOptions.SingleLine);

                        cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                        M Offline
                        M Offline
                        Marc Clifton
                        wrote on last edited by
                        #132

                        Chris Maunder wrote:

                        result = Regex.Replace

                        That's sweet. And amazingly simple. Marc

                        My Blog
                        An Agile walk on the wild side with Relationship Oriented Programming

                        1 Reply Last reply
                        0
                        • P Pete OHanlon

                          Your former client base is showing mate - calling a method Stripper.

                          Forgive your enemies - it messes with their heads

                          "Mind bleach! Send me mind bleach!" - Nagy Vilmos

                          My blog | My articles | MoXAML PowerToys | Mole 2010 - debugging made easier - my favourite utility

                          M Offline
                          M Offline
                          Marc Clifton
                          wrote on last edited by
                          #133

                          Pete O'Hanlon wrote:

                          Your former client base is showing mate - calling a method Stripper.

                          I am scarred for life! ;P Marc

                          My Blog
                          An Agile walk on the wild side with Relationship Oriented Programming

                          1 Reply Last reply
                          0
                          • H hairy_hats

                            Quantum collapse occurs due to quantum interactions with something else ("observation"). There is no need for that interaction to be conscious or human, it just means that one quantum system is disturbed through interaction with something else - such as a cat. :)

                            D Offline
                            D Offline
                            DariusLegion
                            wrote on last edited by
                            #134

                            What the hell is the matter with you guys...? :sigh:

                            1 Reply Last reply
                            0
                            • C Chris Maunder

                              Won't work if you have "dog dog text". It will only remove the first "dog"

                              cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                              J Offline
                              J Offline
                              jsc42
                              wrote on last edited by
                              #135

                              5th Jan: But you said there was nothing in the spec about whitespace, so only removing the first dog is permissible. FWIW: Here is my solution in JavaScript (not the fastest, but still quite short a) Only removing the first dog (if there are multiple dogs)

                              alert(/^(dog|cat)*(.*?)(dog|cat)*$/.exec("dog cat monkey dog horse dog")[2])

                              b) Allowing removal of packs of dogs and cats optionally separated by whitespace chars:

                              alert(/^(\s*(dog|cat))*(.*?)((dog|cat)\s*)*$/.exec("dog cat monkey dog horse dog")[3])

                              6th Jan: Modified Clarifications in other responses suggest that whitespace is to be preserved and is not significant when looking for leading / trailing texts and that a general solution is required rather than looking only for dogs and cats bracketing "dog cat monkey dog horse dog". So, today's JavaScript version is ...

                              function strim(str, texts)
                              {
                              return str.replace(
                              new RegExp(
                              '^((\\s*)(' + // $2 = leading whitespace
                              texts.join('|') +
                              '))*(.*?)((' + // $4 = middle portion
                              texts.join('|') +
                              ')(\\s*)?)*$', // $7 = trailing whitespace
                              'ig'
                              ),
                              '$2$4$7'
                              );
                              }

                              alert(strim('dog cat monkey dog horse dog', [ 'dog', 'cat' ]));
                              alert(strim('dog dog text', [ 'dog', 'cat' ]));

                              To see the spaces, change the alerts to

                              alert(strim('dog cat monkey dog horse dog', [ 'dog', 'cat' ]).replace(/ /g, '~')); // ~~monkey~dog~horse~
                              alert(strim('dog dog text', [ 'dog', 'cat' ]).replace(/ /g, '~')); // ~~text

                              Note: This will not work if the texts for testing at the start and end include any special RegExp chars, e.g.

                              . * + ? {
                              or }.

                              1 Reply Last reply
                              0
                              • C Chris Maunder

                                Back in the Days of Yore we had a couple of small coding challenges such as the Lean and Mean comp. I was thinking that there are a ton of small, well defined problems that can be tackled a zillion ways in a zillion languages and that it would be cool to see what you guys can come up with. I'd like to start the ball rolling with the following simple task: Problem: Given a string of text, trim from each end of the text each all occurrences of a given set of strings Sample input: Input string: "dog cat monkey dog horse dog" Strings that need to be trimmed from each end: { "dog", "cat" } Final output should be: " monkey dog horse" Final output should be " cat monkey dog horse " [Edit: My final sample output was incorrect, so to be fair I'll accept either answer] It's up to you whether you worry about case sensitivity. Let's see who can provide the smallest, neatest most elegant, most unique and/or fastest code. For those who feel like jumping on the "No Programming questions" bandwagon, please re-read the lounge guidelines. The point of this is to have fun, not to solve each other's programming issues.

                                cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                                K Offline
                                K Offline
                                klasbj
                                wrote on last edited by
                                #136

                                Hi, I have gotten the CodeProject newsletters for several years and used the site, but this it the first time I have posted, but this topic was so fun I just had to! :) I found the task was not clear on one topic, namely which resulting string should be the answer if several are possible? It can happen if the matches at the beginning and end overlap, if my assumption that the patterns you remove can not overlap is correct? Anyway, I solved it with the assumption that what is wanted is the shortest possible resulting string, why else would you trim a string :laugh:

                                #include <cstdio>
                                #include <vector>

                                #include "ahocorasick.h"

                                using namespace std;
                                using namespace ac;

                                // arbitraty length limits
                                #define MAX_TEXT 1000000
                                #define MAX_PATTERN 1000000

                                struct interval {
                                int begin,end;

                                interval(int b, int e) : begin(b), end(e) { }
                                
                                // reverse the interval given the total length is n
                                interval reverse(int n) const {
                                    return interval(n - end, n - begin);
                                }
                                

                                };

                                interval trim(int len, vector<interval> & intervals);

                                int main() {
                                char * patternbuf;
                                char ** patterns;
                                char text[MAX_TEXT];
                                int npatterns;

                                scanf("%d", &npatterns); getchar();
                                patterns = new char\*\[npatterns\];
                                patternbuf = new char\[npatterns \* MAX\_PATTERN\];
                                for (int i = 0; i < npatterns; ++i) {
                                    patterns\[i\] = &patternbuf\[i\*MAX\_PATTERN\];
                                    gets(patterns\[i\]);  // is dangerous and should not be used!
                                }
                                gets(text);
                                
                                // match the patterns to find all the possible places to trim the string
                                aho\_corasick matcher(npatterns, patterns);
                                vector<int> \* matches = matcher.get\_matches(text);
                                
                                // build a list of intervals of the matches
                                vector<interval> intervals;
                                for (int i = 0; i < npatterns; ++i) {
                                    int len = matcher.get\_pattern\_size(i);
                                    for (vector<int>::iterator it = matches\[i\].begin();
                                            it != matches\[i\].end(); ++it)
                                        intervals.push\_back(interval(\*it, \*it+len));
                                }
                                
                                // trim the string as much as possible, i.e. find the shortest interval of
                                // the original string that can result from trimming
                                interval result = trim(strlen(text), intervals);
                                
                                // print the result
                                text\[result.end\] = '\\0';
                                printf("\\"%s\\"\\n", &text\[result.begin\]);
                                
                                
                                // clean up
                                delete \[\] patternbuf;
                                delete \[\] patterns;
                                
                                return 0;
                                

                                }

                                1 Reply Last reply
                                0
                                • C Chris Maunder

                                  Back in the Days of Yore we had a couple of small coding challenges such as the Lean and Mean comp. I was thinking that there are a ton of small, well defined problems that can be tackled a zillion ways in a zillion languages and that it would be cool to see what you guys can come up with. I'd like to start the ball rolling with the following simple task: Problem: Given a string of text, trim from each end of the text each all occurrences of a given set of strings Sample input: Input string: "dog cat monkey dog horse dog" Strings that need to be trimmed from each end: { "dog", "cat" } Final output should be: " monkey dog horse" Final output should be " cat monkey dog horse " [Edit: My final sample output was incorrect, so to be fair I'll accept either answer] It's up to you whether you worry about case sensitivity. Let's see who can provide the smallest, neatest most elegant, most unique and/or fastest code. For those who feel like jumping on the "No Programming questions" bandwagon, please re-read the lounge guidelines. The point of this is to have fun, not to solve each other's programming issues.

                                  cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                                  D Offline
                                  D Offline
                                  darkDercane
                                  wrote on last edited by
                                  #137

                                  where i can send my solution?? :P

                                  1 Reply Last reply
                                  0
                                  • C Chris Maunder

                                    Back in the Days of Yore we had a couple of small coding challenges such as the Lean and Mean comp. I was thinking that there are a ton of small, well defined problems that can be tackled a zillion ways in a zillion languages and that it would be cool to see what you guys can come up with. I'd like to start the ball rolling with the following simple task: Problem: Given a string of text, trim from each end of the text each all occurrences of a given set of strings Sample input: Input string: "dog cat monkey dog horse dog" Strings that need to be trimmed from each end: { "dog", "cat" } Final output should be: " monkey dog horse" Final output should be " cat monkey dog horse " [Edit: My final sample output was incorrect, so to be fair I'll accept either answer] It's up to you whether you worry about case sensitivity. Let's see who can provide the smallest, neatest most elegant, most unique and/or fastest code. For those who feel like jumping on the "No Programming questions" bandwagon, please re-read the lounge guidelines. The point of this is to have fun, not to solve each other's programming issues.

                                    cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                                    R Offline
                                    R Offline
                                    Rizean
                                    wrote on last edited by
                                    #138

                                    I'm sorry but this is not a challenge. If you want a real challenge go to ProjectEuler.com. There you will find over 350 easy to difficult challenges. I have learned a ton from the site and have only completed 45 problems so far. Wish I had more time to work the problems. Regards

                                    C 1 Reply Last reply
                                    0
                                    • R Rizean

                                      I'm sorry but this is not a challenge. If you want a real challenge go to ProjectEuler.com. There you will find over 350 easy to difficult challenges. I have learned a ton from the site and have only completed 45 problems so far. Wish I had more time to work the problems. Regards

                                      C Offline
                                      C Offline
                                      Chris Maunder
                                      wrote on last edited by
                                      #139

                                      I'm sorry but I think you missed the point of this entire thread. Alternatively you could post your own challenge. I'd love to see everyone else throwing their challenges into the ring.

                                      cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                                      1 Reply Last reply
                                      0
                                      • C Chris Maunder

                                        Back in the Days of Yore we had a couple of small coding challenges such as the Lean and Mean comp. I was thinking that there are a ton of small, well defined problems that can be tackled a zillion ways in a zillion languages and that it would be cool to see what you guys can come up with. I'd like to start the ball rolling with the following simple task: Problem: Given a string of text, trim from each end of the text each all occurrences of a given set of strings Sample input: Input string: "dog cat monkey dog horse dog" Strings that need to be trimmed from each end: { "dog", "cat" } Final output should be: " monkey dog horse" Final output should be " cat monkey dog horse " [Edit: My final sample output was incorrect, so to be fair I'll accept either answer] It's up to you whether you worry about case sensitivity. Let's see who can provide the smallest, neatest most elegant, most unique and/or fastest code. For those who feel like jumping on the "No Programming questions" bandwagon, please re-read the lounge guidelines. The point of this is to have fun, not to solve each other's programming issues.

                                        cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                                        U Offline
                                        U Offline
                                        User 7888059
                                        wrote on last edited by
                                        #140

                                        Hmm, i read here since more than one, year but never posted something, but this sounds not to difficult. euphoria 4.0.x include std/text.e include std/console.e puts(1,trim("dog cat monkey dog horse dog","dogcat",0)&"\n") any_key() this should produce your final output Andreas

                                        1 Reply Last reply
                                        0
                                        • C Chris Maunder

                                          Back in the Days of Yore we had a couple of small coding challenges such as the Lean and Mean comp. I was thinking that there are a ton of small, well defined problems that can be tackled a zillion ways in a zillion languages and that it would be cool to see what you guys can come up with. I'd like to start the ball rolling with the following simple task: Problem: Given a string of text, trim from each end of the text each all occurrences of a given set of strings Sample input: Input string: "dog cat monkey dog horse dog" Strings that need to be trimmed from each end: { "dog", "cat" } Final output should be: " monkey dog horse" Final output should be " cat monkey dog horse " [Edit: My final sample output was incorrect, so to be fair I'll accept either answer] It's up to you whether you worry about case sensitivity. Let's see who can provide the smallest, neatest most elegant, most unique and/or fastest code. For those who feel like jumping on the "No Programming questions" bandwagon, please re-read the lounge guidelines. The point of this is to have fun, not to solve each other's programming issues.

                                          cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                                          P Offline
                                          P Offline
                                          PIEBALDconsult
                                          wrote on last edited by
                                          #141

                                          OK, this is simpler than what I was concocting yesterday and it's not fully tested, but it works with your sample strings. I started by writing a simple Spell Check Tree class (in C# it's much simpler than it was with C back in college):

                                          namespace PIEBALD.Types
                                          {
                                          public sealed class SpellCheckTree
                                          {
                                          public enum SearchState
                                          {
                                          NotFound = -1
                                          ,
                                          Inconclusive = 0
                                          ,
                                          Found = 1
                                          }

                                          private sealed class TreeNode : System.Collections.Generic.Dictionary<char,TreeNode> {}
                                          
                                          private readonly TreeNode tree ;
                                          
                                          private TreeNode current ;
                                          
                                          public SpellCheckTree
                                          (
                                          )
                                          {
                                            this.current = this.tree = new TreeNode() ;
                                          
                                            return ;
                                          }
                                          
                                          public void
                                          Reset
                                          (
                                          )
                                          {
                                            this.current = this.tree ;
                                          
                                            return ;
                                          }
                                          
                                          public void
                                          Add
                                          (
                                            System.Collections.Generic.IEnumerable<char> String
                                          )
                                          {
                                            TreeNode temp = this.tree ;
                                          
                                            foreach ( char c in String )
                                            {
                                              if ( !temp.ContainsKey ( c ) )
                                              {
                                                temp \[ c \] = new TreeNode() ;
                                              }                                        
                                                                                       
                                              temp = temp \[ c \] ;    
                                            }
                                          
                                            temp \[ System.Char.MaxValue \] = new TreeNode() ;
                                          
                                            return ;
                                          }
                                          
                                          public SearchState
                                          Find
                                          (
                                            char C
                                          )
                                          {
                                            SearchState result = SearchState.Inconclusive ;
                                          
                                            if ( !this.current.ContainsKey ( C ) )
                                            {
                                              result = SearchState.NotFound ;
                                            }
                                            else
                                            {
                                              this.current = this.current \[ C \] ;
                                          
                                              if ( this.current.ContainsKey ( System.Char.MaxValue ) )
                                              {
                                                result = SearchState.Found ;
                                              }
                                            }
                                          
                                            return ( result ) ;
                                          }
                                          

                                          }
                                          }

                                          Then I wrote a Trim method to use it:

                                          namespace PIEBALD.Lib
                                          {
                                          using System.Linq ; /* Laziness/expedience */

                                          public enum TrimFrom
                                          {
                                          Left = 1
                                          ,
                                          Right = 2
                                          ,
                                          Both = 3
                                          }

                                          namespace LibExt.Trim
                                          {
                                          public static partial class LibExt
                                          {
                                          public static string
                                          Trim
                                          (
                                          this string Subject
                                          ,
                                          TrimFrom TrimFrom
                                          ,
                                          params string[] Strings
                                          )
                                          {
                                          System.Text.StringBuilder result = new System.Text.StringBuilder ( Subject ) ;
                                          in

                                          1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups