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 0 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

    M Offline
    M Offline
    Michael Bergman
    wrote on last edited by
    #91

    Can I used delegates? If so, I will delegate this to one of my co-workers. That should do it!

    m.bergman

    For Bruce Schneier, quanta only have one state : afraid.

    To succeed in the world it is not enough to be stupid, you must also be well-mannered. -- Voltaire

    Honesty is the best policy, but insanity is a better defense. -- Steve Landesberg

    1 Reply Last reply
    0
    • K Karl Sanford

      Here's my stab at a solution in C#: [Edit: Chris updated the guidance, and I changed the method accordingly.]

      public static string CPtrimmer(string input, string[] trims, StringComparison compare = StringComparison.InvariantCultureIgnoreCase)
      {
      String Input = input;

      foreach (var trimWord in trims)
      {
          if (Input.StartsWith(trimWord, compare))
              Input = Input.Remove(Input.IndexOf(trimWord, compare), trimWord.Length);
          if (Input.EndsWith(trimWord, compare))
              Input = Input.Remove(Input.LastIndexOf(trimWord, compare), trimWord.Length);
      }
      
      if (Input != input)
          return CPtrimmer(Input, trims);
      else
          return Input;
      

      }

      [modified] Given the exchange below, I am including the usage of this method as well (console C#):

      static void Main(string[] args)
      {
      String input = "dog cat monkey dog horse dog";
      String[] trims = new String[] { "dog", "cat" };

      String result = CPtrimmer(input, trims);
      // After CPtrimmer has returned, the result is " cat monkey dog horse "
      

      }

      Be The Noise

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

      This will not remove all of the strings. You will only remove the first instances of them if the string starts with it or ends with it. If your collection is {"dog", "cat"} But your string is "cat dog monkey" you will remove cat but not dog.

      Computers have been intelligent for a long time now. It just so happens that the program writers are about as effective as a room full of monkeys trying to crank out a copy of Hamlet.

      K 1 Reply Last reply
      0
      • L Lost User

        Norm .net wrote:

        2. Language Dependent

        Nothing stated you could not use a specific language. In fact part of the point it seemed was it can be done so many different ways with different languages...

        Computers have been intelligent for a long time now. It just so happens that the program writers are about as effective as a room full of monkeys trying to crank out a copy of Hamlet.

        N Offline
        N Offline
        NormDroid
        wrote on last edited by
        #93

        Internationalization (Uk, German etc.)

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

        1 Reply Last reply
        0
        • H hairy_hats

          Collin Jasnoch wrote:

          perceiver

          Which is defined as what? The cat is inside the box, observing its own state, so no external observer is needed to collapse the waveform.

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

          It is defined as the one holding the experiment. The cat is the experiment and therefore can not be the observer. Any experiement needs observation externally or it is not sound.

          Computers have been intelligent for a long time now. It just so happens that the program writers are about as effective as a room full of monkeys trying to crank out a copy of Hamlet.

          H 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

            N Offline
            N Offline
            NormDroid
            wrote on last edited by
            #95

            Can be done in RegEx albeit terse, I've just been experimenting I do believe somebody with day-to-day contact with reg ex will achieve this.

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

            L 1 Reply Last reply
            0
            • N NormDroid

              Can be done in RegEx albeit terse, I've just been experimenting I do believe somebody with day-to-day contact with reg ex will achieve this.

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

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

              http://www.codeproject.com/Lounge.aspx?msg=4118816#xx4118816xx[^]

              Computers have been intelligent for a long time now. It just so happens that the program writers are about as effective as a room full of monkeys trying to crank out a copy of Hamlet.

              1 Reply Last reply
              0
              • L Lost User

                This will not remove all of the strings. You will only remove the first instances of them if the string starts with it or ends with it. If your collection is {"dog", "cat"} But your string is "cat dog monkey" you will remove cat but not dog.

                Computers have been intelligent for a long time now. It just so happens that the program writers are about as effective as a room full of monkeys trying to crank out a copy of Hamlet.

                K Offline
                K Offline
                Karl Sanford
                wrote on last edited by
                #97

                Umm, no, it would remove both cat and dog. Just ran your example using my code, and it returned " monkey"... maybe you should try the same... [hint] The solution is recursive [/hint]

                Be The Noise

                L 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

                  S Offline
                  S Offline
                  Sentenryu
                  wrote on last edited by
                  #98

                  why no one used Regex? ok, this code is far from optimum, but i had no time to do it better :(

                  using System;
                  using System.Text.RegularExpressions;

                  namespace chalenge
                  {
                  class Program
                  {
                  public static void Main(string[] args)
                  {
                  string input = "dog cat dog monkey dog horse dog";
                  string[] removes = { "dog", "cat" };
                  bool hasMore = false;
                  do{
                  hasMore = false;
                  for(int i =0; i < removes.Length; i++){

                  				while (Regex.IsMatch(input, @"^\\s\*" + removes\[i\] + @"\\s\*.\*")){
                  					input = Regex.Replace(input, @"(?^\\s\*)" + removes\[i\] + @"(?\\s\*.\*)", "${w1}${w2}");
                  				}
                  				
                  				while (Regex.IsMatch(input, @".\*\\s\*" + removes\[i\] + @"\\s\*$")){
                  					input = Regex.Replace(input, @"(?.\*\\s\*)" + removes\[i\] + @"(?\\s\*$)", "${w1}${w2}");
                  				}
                  				
                  				foreach(var item in removes){
                  					if(Regex.IsMatch(input, @"^\\s\*" + item + @"\\s\*.\*") || Regex.IsMatch(input, @".\*\\s\*" + removes\[i\] + @"\\s\*$")){
                  						hasMore = true;
                  						break;
                  					}
                  				}
                  				
                  			}
                  		}while(hasMore);
                  		Console.Write(input);
                  		Console.ReadKey();
                  	}
                  }
                  

                  }

                  (sorry by the english, i'm brasilian...)

                  M 1 Reply Last reply
                  0
                  • P PIEBALDconsult

                    ChrisElston wrote:

                    'each of two.

                    That is "both", not "either". Don't use a word for two meanings when there is already a word for the other. You want to ride a see-saw -- you may sit at either end.

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

                    Yeah cos there are no other words with different meanings. You don't have to like it but they are both valid definitions. There were trees down either side of the road.

                    Every man can tell how many goats or sheep he possesses, but not how many friends.

                    P 1 Reply Last reply
                    0
                    • L Lost User

                      It is defined as the one holding the experiment. The cat is the experiment and therefore can not be the observer. Any experiement needs observation externally or it is not sound.

                      Computers have been intelligent for a long time now. It just so happens that the program writers are about as effective as a room full of monkeys trying to crank out a copy of Hamlet.

                      H Offline
                      H Offline
                      hairy_hats
                      wrote on last edited by
                      #100

                      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 1 Reply Last reply
                      0
                      • K Karl Sanford

                        Umm, no, it would remove both cat and dog. Just ran your example using my code, and it returned " monkey"... maybe you should try the same... [hint] The solution is recursive [/hint]

                        Be The Noise

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

                        Yes if you call it recursively you will remove it. That was not clear in your OP though...

                        Computers have been intelligent for a long time now. It just so happens that the program writers are about as effective as a room full of monkeys trying to crank out a copy of Hamlet.

                        K 1 Reply Last reply
                        0
                        • J jesarg

                          I'll be the first to put up the recursive solution in C#.

                          private string TrimCatDog(string input)
                          {
                          if (input.StartsWith(" ") || input.EndsWith(" "))
                          return TrimCatDog(input.Trim());
                          if (input.StartsWith("cat") || input.StartsWith("dog"))
                          return TrimCatDog(input.Substring(3));
                          if (input.EndsWith("cat") || input.EndsWith("dog"))
                          return TrimCatDog(input.Substring(0, input.Length - 3));
                          return input;
                          }

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

                          The specs say nothing of trimming whitespace, and the hardcoding of "dog" and "cat" means the solution can't be reused.

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

                          J 1 Reply Last reply
                          0
                          • L Lost User

                            Yeah cos there are no other words with different meanings. You don't have to like it but they are both valid definitions. There were trees down either side of the road.

                            Every man can tell how many goats or sheep he possesses, but not how many friends.

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

                            ChrisElston wrote:

                            There were trees down either side of the road.

                            That makes no sense -- which side? The other side I hope.

                            1 Reply Last reply
                            0
                            • N Nagy Vilmos

                              Marc Clifton wrote:

                              Do we need detail specs? Hell NO!!!

                              I was about to invite you into my esteemed LinkIn network, but I'm not sure after reading that. :laugh:


                              Panic, Chaos, Destruction. My work here is done. Drink. Get drunk. Fall over - P O'H OK, I will win to day or my name isn't Ethel Crudacre! - DD Ethel Crudacre I cannot live by bread alone. Bacon and ketchup are needed as well. - Trollslayer Have a bit more patience with newbies. Of course some of them act dumb - they're often *students*, for heaven's sake - Terry Pratchett

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

                              Nagy Vilmos wrote:

                              I was about to invite you into my esteemed LinkIn network, but I'm not sure after reading that.

                              Specs are like the uncertainty principle. The more you spec something, the more inaccurate you will be in some other area. ;) Marc

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

                              1 Reply Last reply
                              0
                              • A Andy Brummer

                                If spaces aren't counted as special characters the output should be " cat monkey dog horse " because cat isn't at the end after removing dog.

                                Curvature of the Mind now with 3D

                                X Offline
                                X Offline
                                Xiangyang Liu
                                wrote on last edited by
                                #105

                                As philosophers would say: "That depends on how you define the concept of END". :-D

                                My Younger Son & His "PET"

                                1 Reply Last reply
                                0
                                • L Lost User

                                  Yes if you call it recursively you will remove it. That was not clear in your OP though...

                                  Computers have been intelligent for a long time now. It just so happens that the program writers are about as effective as a room full of monkeys trying to crank out a copy of Hamlet.

                                  K Offline
                                  K Offline
                                  Karl Sanford
                                  wrote on last edited by
                                  #106

                                  Again, no... the method itself is recursive, no need to call it recursively. Look at the last few lines of the method:

                                  if (Input != input)
                                  return CPtrimmer(Input, trims);
                                  else
                                  return Input;

                                  What this means is that if the mothod changed the original string in any way, it will call itself again to see if there is anything else to be removed. Otherwise, if nothing changed, then the method will return the result up the call stack.

                                  Be The Noise

                                  L 1 Reply Last reply
                                  0
                                  • K Karl Sanford

                                    Here's my stab at a solution in C#: [Edit: Chris updated the guidance, and I changed the method accordingly.]

                                    public static string CPtrimmer(string input, string[] trims, StringComparison compare = StringComparison.InvariantCultureIgnoreCase)
                                    {
                                    String Input = input;

                                    foreach (var trimWord in trims)
                                    {
                                        if (Input.StartsWith(trimWord, compare))
                                            Input = Input.Remove(Input.IndexOf(trimWord, compare), trimWord.Length);
                                        if (Input.EndsWith(trimWord, compare))
                                            Input = Input.Remove(Input.LastIndexOf(trimWord, compare), trimWord.Length);
                                    }
                                    
                                    if (Input != input)
                                        return CPtrimmer(Input, trims);
                                    else
                                        return Input;
                                    

                                    }

                                    [modified] Given the exchange below, I am including the usage of this method as well (console C#):

                                    static void Main(string[] args)
                                    {
                                    String input = "dog cat monkey dog horse dog";
                                    String[] trims = new String[] { "dog", "cat" };

                                    String result = CPtrimmer(input, trims);
                                    // After CPtrimmer has returned, the result is " cat monkey dog horse "
                                    

                                    }

                                    Be The Noise

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

                                    You're algorithm results in: "  monkey dog horse " (two leading spaces) rather than: " monkey dog horse " It's really odd how every solution that I've seen somehow fails to take this into account (as well as the fact that after the first trim, there will be a leading or trailing space in the result.) Are we that bad at reading specs, meeting simple requirements, and testing our code? :sigh: Marc

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

                                    K 2 Replies Last reply
                                    0
                                    • S Sentenryu

                                      why no one used Regex? ok, this code is far from optimum, but i had no time to do it better :(

                                      using System;
                                      using System.Text.RegularExpressions;

                                      namespace chalenge
                                      {
                                      class Program
                                      {
                                      public static void Main(string[] args)
                                      {
                                      string input = "dog cat dog monkey dog horse dog";
                                      string[] removes = { "dog", "cat" };
                                      bool hasMore = false;
                                      do{
                                      hasMore = false;
                                      for(int i =0; i < removes.Length; i++){

                                      				while (Regex.IsMatch(input, @"^\\s\*" + removes\[i\] + @"\\s\*.\*")){
                                      					input = Regex.Replace(input, @"(?^\\s\*)" + removes\[i\] + @"(?\\s\*.\*)", "${w1}${w2}");
                                      				}
                                      				
                                      				while (Regex.IsMatch(input, @".\*\\s\*" + removes\[i\] + @"\\s\*$")){
                                      					input = Regex.Replace(input, @"(?.\*\\s\*)" + removes\[i\] + @"(?\\s\*$)", "${w1}${w2}");
                                      				}
                                      				
                                      				foreach(var item in removes){
                                      					if(Regex.IsMatch(input, @"^\\s\*" + item + @"\\s\*.\*") || Regex.IsMatch(input, @".\*\\s\*" + removes\[i\] + @"\\s\*$")){
                                      						hasMore = true;
                                      						break;
                                      					}
                                      				}
                                      				
                                      			}
                                      		}while(hasMore);
                                      		Console.Write(input);
                                      		Console.ReadKey();
                                      	}
                                      }
                                      

                                      }

                                      (sorry by the english, i'm brasilian...)

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

                                      Results in too many leading spaces. The output should have one leading and one trailing space. Marc

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

                                      S 1 Reply Last reply
                                      0
                                      • A Alberto Bar Noy

                                        Chris barely posted and already there is a design review, rejects from marketing, the devs want to shoot the PM. The PM is whistling nastily (Nagy you dog ... cat... horse... dog) and the mischievous ones reach for the assembler books. What we miss here is QA and we can start a death-march :laugh: EDIT-------------------------- I forgot legal as well. Legal department share its thoughts here with the assistance of the tech writers ;P

                                        Alberto Bar-Noy --------------- “The city’s central computer told you? R2D2, you know better than to trust a strange computer!” (C3PO)

                                        B Offline
                                        B Offline
                                        BillWoodruff
                                        wrote on last edited by
                                        #109

                                        I think what you have described is what is known as "Agile" programming methodology. best, Bill

                                        "It is the mark of an educated mind to be able to entertain a thought without accepting it." Aristotle

                                        1 Reply Last reply
                                        0
                                        • M Marc Clifton

                                          Results in too many leading spaces. The output should have one leading and one trailing space. Marc

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

                                          S Offline
                                          S Offline
                                          Sentenryu
                                          wrote on last edited by
                                          #110

                                          this results in too many spaces because of the input string "dog cat dog monkey dog horse dog", the original are "dog cat monkey dog horse dog", i thought it was to preserve all spaces, so "dog cat dog " would result into 3 spaces, and " dog" would result in 1 space, am i wrong?

                                          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