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

    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
                      • K Karl Sanford

                        An example is not a specification... the spec says:

                        Quote:

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

                        Which says nothing about removing spaces (which Chris has already mentioned in a few replies on the thread), therefore, all spaces are left alone. Examples are guidance, specifications are rules... I followed the rules*. *I do agree that 'technically', once you remove the first occurance of "dog", cat is NOT at the begining of the string, and should actually result in " cat monkey dog horse ". Though in looking at the guidance, since cat is removed, I assumed that spaces should be ignored and left alone. Although if you really wanted to get convoluted, and have the EXACT match of a single leading space, that would fundamentally change the given specification... hence my design choice. Taking an occams razor approach, is it more likely that the spec is wrong and we should have a convoluted solution to have a single leading space? Or more likely that it was a typo and Chris ment to have two leading spaces?

                        Be The Noise

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

                        I read it as, "if you want to trim whitespace, then supply them as a 'string to be removed'".

                        1 Reply Last reply
                        0
                        • L Lost User

                          It thought it was both alive and dead until you had a look in the box at which point it became alive or dead. A bit late but still; Erwin Schrödinger has sent us a Christmas present. The kids are going to be delighted or distraught on Christmas Day.

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

                          I Offline
                          I Offline
                          IAbstract
                          wrote on last edited by
                          #143

                          You would be correct. Until you look in the box - the cat is neither dead nor alive. Quantum theory can be crudely demonstrated with this example. Anyway ...back to the topic...

                          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

                            B Offline
                            B Offline
                            brian oslick
                            wrote on last edited by
                            #144

                            Chris Maunder... without having to think too much (and thus stress my feeble brain)

                            include 'win32a.inc'
                            format PE console 4.0
                            entry start
                            ;*********************************************
                            section '.data' data readable writeable

                            _s db '%s',13,0

                            i_string db 'dog cat monkey dog horse dog'
                            o_string db 21 dup(0)

                            ;*********************************************
                            section '.text' code readable executable
                            ;*********************************************
                            start: ;fasm_dogcat.fasm

                            mov ebx,3
                            xor ecx,ecx
                            above:
                            mov eax,dword[i_string+ebx+ecx*4]
                            mov dword[o_string+ecx*4],eax
                            inc ecx
                            cmp ecx,5
                            jnz above
                            mov ax,word[i_string+ebx+ecx*4]
                            mov word[o_string+ecx*4],ax

                            cinvoke printf,_s,o_string

                            ; >"C:\_sys\temp\shell.exe"
                            ;$20,'cat monkey dog horse',$20,0
                            ; >Exit code: 0
                            ;*********************************************
                            invoke ExitProcess,0
                            ;***********************************************
                            section '.idata' data import readable writeable
                            library kernel32,'kernel32.dll',\
                            user32,'user32.dll',\
                            msvcrt,'msvcrt.dll'
                            include 'api\kernel32.inc'
                            include 'api\user32.inc'
                            import msvcrt,\
                            printf,'printf'
                            ;***********************************************

                            brianO

                            C 1 Reply Last reply
                            0
                            • B brian oslick

                              Chris Maunder... without having to think too much (and thus stress my feeble brain)

                              include 'win32a.inc'
                              format PE console 4.0
                              entry start
                              ;*********************************************
                              section '.data' data readable writeable

                              _s db '%s',13,0

                              i_string db 'dog cat monkey dog horse dog'
                              o_string db 21 dup(0)

                              ;*********************************************
                              section '.text' code readable executable
                              ;*********************************************
                              start: ;fasm_dogcat.fasm

                              mov ebx,3
                              xor ecx,ecx
                              above:
                              mov eax,dword[i_string+ebx+ecx*4]
                              mov dword[o_string+ecx*4],eax
                              inc ecx
                              cmp ecx,5
                              jnz above
                              mov ax,word[i_string+ebx+ecx*4]
                              mov word[o_string+ecx*4],ax

                              cinvoke printf,_s,o_string

                              ; >"C:\_sys\temp\shell.exe"
                              ;$20,'cat monkey dog horse',$20,0
                              ; >Exit code: 0
                              ;*********************************************
                              invoke ExitProcess,0
                              ;***********************************************
                              section '.idata' data import readable writeable
                              library kernel32,'kernel32.dll',\
                              user32,'user32.dll',\
                              msvcrt,'msvcrt.dll'
                              include 'api\kernel32.inc'
                              include 'api\user32.inc'
                              import msvcrt,\
                              printf,'printf'
                              ;***********************************************

                              brianO

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

                              You get serious Man Points for that. :beer:

                              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

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

                                Here is my kick at the cat … er, dog … er, dog and cat. This c# solution is generic enough to handle any number of search words (when using parameters). Note the use of a space as a search word.

                                using System;
                                using System.Text;

                                namespace ConsoleApplication1 {
                                class Program {
                                static void Main( string[] args ) {

                                     string phrase = "dog cat monkey dog horse dog";
                                     string\[\] words = { " ", "dog", "cat" };    // Note: added space.
                                     StringBuilder sb1 = new StringBuilder();  // Leading spaces.
                                     StringBuilder sb2 = new StringBuilder();  // Trailing spaces.
                                     bool found;
                                
                                     // Trim start.
                                     do {
                                        found = false;
                                        foreach ( string w in words ) {
                                           if ( phrase.StartsWith( w ) ) {
                                              found = true;
                                              phrase = phrase.Substring( w.Length );
                                              if ( string.IsNullOrWhiteSpace( w ) ) sb1.Append( w );
                                           }
                                        }
                                     } while ( phrase.Length > 0 && found );
                                
                                     // Trim end.
                                     do {
                                        found = false;
                                        foreach ( string w in words ) {
                                           if ( phrase.EndsWith( w ) ) {
                                              found = true;
                                              phrase = phrase.Substring( 0, phrase.Length - w.Length );
                                              if ( string.IsNullOrWhiteSpace( w ) ) sb2.Append( w );
                                           }
                                        }
                                     } while ( phrase.Length > 0 && found );
                                
                                     Console.WriteLine( "\[" + sb1.ToString() + phrase + sb2.ToString() + "\]" );
                                  }
                                

                                }
                                }

                                P 1 Reply Last reply
                                0
                                • L Lost User

                                  Here is my kick at the cat … er, dog … er, dog and cat. This c# solution is generic enough to handle any number of search words (when using parameters). Note the use of a space as a search word.

                                  using System;
                                  using System.Text;

                                  namespace ConsoleApplication1 {
                                  class Program {
                                  static void Main( string[] args ) {

                                       string phrase = "dog cat monkey dog horse dog";
                                       string\[\] words = { " ", "dog", "cat" };    // Note: added space.
                                       StringBuilder sb1 = new StringBuilder();  // Leading spaces.
                                       StringBuilder sb2 = new StringBuilder();  // Trailing spaces.
                                       bool found;
                                  
                                       // Trim start.
                                       do {
                                          found = false;
                                          foreach ( string w in words ) {
                                             if ( phrase.StartsWith( w ) ) {
                                                found = true;
                                                phrase = phrase.Substring( w.Length );
                                                if ( string.IsNullOrWhiteSpace( w ) ) sb1.Append( w );
                                             }
                                          }
                                       } while ( phrase.Length > 0 && found );
                                  
                                       // Trim end.
                                       do {
                                          found = false;
                                          foreach ( string w in words ) {
                                             if ( phrase.EndsWith( w ) ) {
                                                found = true;
                                                phrase = phrase.Substring( 0, phrase.Length - w.Length );
                                                if ( string.IsNullOrWhiteSpace( w ) ) sb2.Append( w );
                                             }
                                          }
                                       } while ( phrase.Length > 0 && found );
                                  
                                       Console.WriteLine( "\[" + sb1.ToString() + phrase + sb2.ToString() + "\]" );
                                    }
                                  

                                  }
                                  }

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

                                  But then you haven't removed the whitespace as specified by the parameters.

                                  L 1 Reply Last reply
                                  0
                                  • L Lost User

                                    I am pretty sure the cat is both dead and alive, until viewed by a perceiver. That is the paradox of that thought experiment.

                                    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.

                                    U Offline
                                    U Offline
                                    User 4520523
                                    wrote on last edited by
                                    #148

                                    The paradox is that the cat can't be alive and dead at the same time. The thought experiment was designed to pick holes in the Coppenhagen interpretation of quantum mechanics. He never believed that an unseen cat could be both dead & alive at the same time.

                                    L 1 Reply Last reply
                                    0
                                    • U User 4520523

                                      The paradox is that the cat can't be alive and dead at the same time. The thought experiment was designed to pick holes in the Coppenhagen interpretation of quantum mechanics. He never believed that an unseen cat could be both dead & alive at the same time.

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

                                      Member 4523790 wrote:

                                      The paradox is that the cat can't be alive and dead at the same time.

                                      By no definition (of paradox) is that a paradox. Thats like saying my computer can't be on and off at the same time is a paradox. If I could somehow claim my computer is both on and off then that is a paradox. A paradox is something that holds true yet contradicts. "The only certainty is there is no certainty" is a pardoxial (word?) statement because even if it is true then there exists a certainty, thus making it not true. The paradox is that both truths (the cat is dead and the cat is alive) are true until you open the box.

                                      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.

                                      U 1 Reply Last reply
                                      0
                                      • P PIEBALDconsult

                                        But then you haven't removed the whitespace as specified by the parameters.

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

                                        :confused: As per Chris: "The specs say nothing of trimming whitespace ..." (8:07 4 Jan '12)

                                        P 1 Reply Last reply
                                        0
                                        • L Lost User

                                          Member 4523790 wrote:

                                          The paradox is that the cat can't be alive and dead at the same time.

                                          By no definition (of paradox) is that a paradox. Thats like saying my computer can't be on and off at the same time is a paradox. If I could somehow claim my computer is both on and off then that is a paradox. A paradox is something that holds true yet contradicts. "The only certainty is there is no certainty" is a pardoxial (word?) statement because even if it is true then there exists a certainty, thus making it not true. The paradox is that both truths (the cat is dead and the cat is alive) are true until you open the box.

                                          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.

                                          U Offline
                                          U Offline
                                          User 4520523
                                          wrote on last edited by
                                          #151

                                          I'll go by the wikipedia definition of paradox: a paradox is a logical statement or group of statements that lead to a contradiction or a situation which (if true) defies logic or reason it defies logic that the cat can be both alive and dead. If you read http://en.wikipedia.org/wiki/Schrödinger's\_cat (scroll to The thought experiment) you'll see that Schrödinger thought it was a "ridiculous case". Albert Einstein wrote: "Nobody really doubts that the presence or absence of the cat is something independent of the act of observation" Niels Bohr (one of the main scientists associated with the Copenhagen interpretation) "never had in mind the observer-induced collapse of the wave function, so that Schrödinger's Cat did not pose any riddle to him. The cat would be either dead or alive long before the box is opened by a conscious observer.[6] Analysis of an actual experiment found that measurement alone (for example by a Geiger counter) is sufficient to collapse a quantum wave function before there is any conscious observation of the measurement" So basically nobody involved thinks the cat is both alive and dead, I don't know why so many people don't get it. Everything is "an observer", there is no special flag in the universe on humans, cats, geiger counters etc.

                                          L 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