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. Friday Programming Quiz [modified]

Friday Programming Quiz [modified]

Scheduled Pinned Locked Moved The Lounge
javascriptdebugginghelpquestion
24 Posts 12 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.
  • R Rama Krishna Vavilala

    David Stone wrote:

    list1.Intersect(list2).ToString();

    I wonder whether that will work?


    Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -Brian Kernighan

    D Offline
    D Offline
    David Stone
    wrote on last edited by
    #11

    So do I, honestly. :-D Anybody with VS and the May LINQ CTP installed want to try it out?

    Once you wanted revolution
    Now you're the institution
    How's it feel to be the man?

    1 Reply Last reply
    0
    • R Rama Krishna Vavilala

      While you are waiting for a build that crashes or may be not. Here is a simple programming problem (not question). The objective is to write the following function:

      string GetIntersection(string csvString1, string csvString2) {

      }

      csvString1 and csvString2 both contain comma separated list of unique values. The values can be in any order and they don't contain commas. The objective is to return a new CSV string which contains value from both the lists. e.g. csvString1: cat,rat,dog,lion csvString2: lion,elephant,mouse,tiger,rat,dog output: lion,rat,dog The coolest implementation of the function I have seen, so far, happens to be in JavaScript. Feel free to use any library functions. -- modified at 15:18 Friday 27th October, 2006


      Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -Brian Kernighan

      J Offline
      J Offline
      Judah Gabriel Himango
      wrote on last edited by
      #12

      I thought about a couple solutions. Most of the options are either compact and poor performance, or verbose and high performance. Here's one compact solution:

      string GetIntersection(string csvString1, string csvString2)
      {
      foreach (string str in csvString2.Split(','))
      if (!csvString1.Contains("," + str + ",") && !csvString1.EndsWith(str))
      csvString1 += "," + str;

       return csvString1;
      

      }

      Of course, I'd never write code like that as it's hugely inefficient due to the excessive string concatenation. You could make a more efficient version with a StringBuilder, char array, or List of strings, but they'd be more verbose. :)

      Tech, life, family, faith: Give me a visit. I'm currently blogging about: God-as-Judge, God-as-Forgiver The apostle Paul, modernly speaking: Epistles of Paul Judah Himango

      1 Reply Last reply
      0
      • L Lost User

        Here is my answer in C#. I couldnt find List<>.Intersect() anywhere on MSDN public string GetIntersection(string csvString1, string csvString2) { string[] stringAry1 = csvString1.Split(new char[] { ',' }); List stringList = new List(); foreach (string str in stringAry1) { if (csvString2.Contains(str)) { stringList.Add(str); } } return String.Join(",", stringList.ToArray()); } sorry about the formatting. My browser is Opera

        J Offline
        J Offline
        jesarg
        wrote on last edited by
        #13

        Your code will return false positives if csvString1 has element "hi" and csvString2 has element "hide".

        L 1 Reply Last reply
        0
        • L Lost User

          Here is my answer in C#. I couldnt find List<>.Intersect() anywhere on MSDN public string GetIntersection(string csvString1, string csvString2) { string[] stringAry1 = csvString1.Split(new char[] { ',' }); List stringList = new List(); foreach (string str in stringAry1) { if (csvString2.Contains(str)) { stringList.Add(str); } } return String.Join(",", stringList.ToArray()); } sorry about the formatting. My browser is Opera

          D Offline
          D Offline
          David Stone
          wrote on last edited by
          #14

          J.Doli wrote:

          I couldnt find List<>.Intersect() anywhere on MSDN

          It's not there yet. You only get List<T>.Intersect() if you install the LINQ CTPs.

          Oh geez... the forum keeps spinning... you'll take care o f it i'm sure, c'ause ... yeah, i neede this. *cough* anyway good job finding the bug.
          -Shog9 on...a Firefox bug.

          1 Reply Last reply
          0
          • J jesarg

            Your code will return false positives if csvString1 has element "hi" and csvString2 has element "hide".

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

            thanks for pointing that out. Here is my next try. public string GetIntersection(string csvString1, string csvString2) { List stringList = new List(csvString2.Split(new char[] { ',' })); List results = new List(); foreach (string str in csvString1.Split(new char[] { ',' })) { if (stringList.Contains(str)) { results.Add(str); } } return String.Join(",", results.ToArray()); } I dont like it that much, i just keep thinking that there is a better way.

            1 Reply Last reply
            0
            • R Rama Krishna Vavilala

              David Stone wrote:

              list1.Intersect(list2).ToString();

              I wonder whether that will work?


              Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -Brian Kernighan

              D Offline
              D Offline
              David Stone
              wrote on last edited by
              #16

              It won't. Also, my string splitting is wrong. I've modified it with the correct answer.

              Oh geez... the forum keeps spinning... you'll take care o f it i'm sure, c'ause ... yeah, i neede this. *cough* anyway good job finding the bug.
              -Shog9 on...a Firefox bug.

              1 Reply Last reply
              0
              • R Rama Krishna Vavilala

                While you are waiting for a build that crashes or may be not. Here is a simple programming problem (not question). The objective is to write the following function:

                string GetIntersection(string csvString1, string csvString2) {

                }

                csvString1 and csvString2 both contain comma separated list of unique values. The values can be in any order and they don't contain commas. The objective is to return a new CSV string which contains value from both the lists. e.g. csvString1: cat,rat,dog,lion csvString2: lion,elephant,mouse,tiger,rat,dog output: lion,rat,dog The coolest implementation of the function I have seen, so far, happens to be in JavaScript. Feel free to use any library functions. -- modified at 15:18 Friday 27th October, 2006


                Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -Brian Kernighan

                E Offline
                E Offline
                Ennis Ray Lynch Jr
                wrote on last edited by
                #17

                Sue me, I am lazy and uncreative right now. StringBuilder sb = new StringBuilder(); Hashtable table = new Hashtable(); string[] splitList = csvString1.Split(new char[]{','}); foreach(string s in splitList){ table[s] = s; } splitList = csvString2.Split(new char[]{','}); foreach(string s in splitList){ table[s] = s; } foreach(string s in table.Values){ sb.Append(s); } return sb.ToString();


                On two occasions I have been asked [by members of Parliament], 'Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out?' I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question. - Charles Babbage

                1 Reply Last reply
                0
                • D David Stone

                  Um. Yeah. That's too much. ;P


                  Mandrake, do you realize that in addition to fluoridating water, why, there are studies underway to fluoridate salt, flour, fruit juices, soup, sugar, milk, ice cream. Ice cream, Mandrake. Children's ice cream.

                  M Offline
                  M Offline
                  Matt Gerrans
                  wrote on last edited by
                  #18

                  Yeah. You need to get a smaller monitor. Your team will thank you. BTW: "but at least it works" is a commonly used rationale (or excuse) for code that usually doesn't work very well at all. Remember, good code is about readability too. If it wasn't for that, we wouldn't keep source code after it was compiled once. Code is for people, not computers. All computers care about is the machine instructions.

                  Matt Gerrans

                  1 Reply Last reply
                  0
                  • R Rama Krishna Vavilala

                    While you are waiting for a build that crashes or may be not. Here is a simple programming problem (not question). The objective is to write the following function:

                    string GetIntersection(string csvString1, string csvString2) {

                    }

                    csvString1 and csvString2 both contain comma separated list of unique values. The values can be in any order and they don't contain commas. The objective is to return a new CSV string which contains value from both the lists. e.g. csvString1: cat,rat,dog,lion csvString2: lion,elephant,mouse,tiger,rat,dog output: lion,rat,dog The coolest implementation of the function I have seen, so far, happens to be in JavaScript. Feel free to use any library functions. -- modified at 15:18 Friday 27th October, 2006


                    Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -Brian Kernighan

                    J Offline
                    J Offline
                    Joe Woodbury
                    wrote on last edited by
                    #19

                    For the heck of it I threw together a C++ version. Note that the CMTrieIntT class is one of my own implementations of a trie and is extremely fast. (I have a case insensitive version that could also be used.)

                    int GetString(LPCTSTR& pStr)
                    {
                    	while (*pStr == ',')
                    		pStr++;
                    
                    	int len = 0;
                    
                    	while (pStr[len] && pStr[len] != ',')
                    		len++;
                    
                    	return len;
                    }
                    
                    CString GetIntersection(LPCTSTR pStr1, LPCTSTR pStr2)
                    {
                    	CMTrieIntT trie;
                    
                    	for ( ; ; )
                    	{
                    		int len = GetString(pStr1);
                    		if (len == 0)
                    			break;
                    
                    		trie.Add(pStr1, 0, len);
                    
                    		pStr1 += len;
                    	}
                    
                    	CString rval;
                    
                    	for ( ; ; )
                    	{
                    		int len = GetString(pStr2);
                    		if (len == 0)
                    			break;
                    
                    		if (trie.KeyExists(pStr2, len))
                    		{
                    			if (rval.GetLength() > 0)
                    				rval += ',';
                    
                    			rval.Append(pStr2, len);
                    		}
                    
                    		pStr2 += len;
                    	}
                    
                    	return rval;
                    }
                    

                    Anyone who thinks he has a better idea of what's good for people than people do is a swine. - P.J. O'Rourke

                    1 Reply Last reply
                    0
                    • R Rama Krishna Vavilala

                      While you are waiting for a build that crashes or may be not. Here is a simple programming problem (not question). The objective is to write the following function:

                      string GetIntersection(string csvString1, string csvString2) {

                      }

                      csvString1 and csvString2 both contain comma separated list of unique values. The values can be in any order and they don't contain commas. The objective is to return a new CSV string which contains value from both the lists. e.g. csvString1: cat,rat,dog,lion csvString2: lion,elephant,mouse,tiger,rat,dog output: lion,rat,dog The coolest implementation of the function I have seen, so far, happens to be in JavaScript. Feel free to use any library functions. -- modified at 15:18 Friday 27th October, 2006


                      Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -Brian Kernighan

                      H Offline
                      H Offline
                      Henrik Husted
                      wrote on last edited by
                      #20

                      my $l1 = "cat,rat,dog,lion"; my $l2 = "lion,elephant,mouse,tiger,rat,dog"; my (%h1,%h2); foreach(split ",", $l1) { $h1{$_}=$_;} foreach(split ",", $l2) { $h2{$_}=$_;} foreach( sort keys %h1 ) { if( $h2{$_} ) { print "$h1{$_}\n"; } }

                      1 Reply Last reply
                      0
                      • D David Stone

                        LINQ: (Note: Completely untested. I haven't set up Visual Studio on my new laptop yet. ;P Should work though.)

                        string GetCsvIntersection(string csv1, string csv2)
                        {
                        var list1 = new List<String>(Regex.Split(csv1, ","));
                        var list2 = new List<String>(Regex.Split(csv2, ","));

                        var result = new StringBuilder();
                        foreach (string item in list1.Intersect(list2))
                        {
                            result.AppendFormat("{0},", item);
                        }
                        
                        return result.Remove(result.Length - 1, 1).ToString();
                        

                        }


                        Last modified: 2hrs 8mins after originally posted -- Yeah. Okay. LINQ still isn't as cool as Javascript

                        Oh geez... the forum keeps spinning... you'll take care o f it i'm sure, c'ause ... yeah, i neede this. *cough* anyway good job finding the bug. -Shog9 on...a Firefox bug.

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

                        Why use Regex.Split instead of just csv1.Split(',') ? Marc

                        Thyme In The Country

                        People are just notoriously impossible. --DavidCrow
                        There's NO excuse for not commenting your code. -- John Simmons / outlaw programmer
                        People who say that they will refactor their code later to make it "good" don't understand refactoring, nor the art and craft of programming. -- Josh Smith

                        D 1 Reply Last reply
                        0
                        • M Marc Clifton

                          Why use Regex.Split instead of just csv1.Split(',') ? Marc

                          Thyme In The Country

                          People are just notoriously impossible. --DavidCrow
                          There's NO excuse for not commenting your code. -- John Simmons / outlaw programmer
                          People who say that they will refactor their code later to make it "good" don't understand refactoring, nor the art and craft of programming. -- Josh Smith

                          D Offline
                          D Offline
                          David Stone
                          wrote on last edited by
                          #22

                          Because Regex.Split takes a String. String.Split needs a char array. And so I didn't want to construct a whole char[]. ;P There's no other good reason.


                          Mandrake, do you realize that in addition to fluoridating water, why, there are studies underway to fluoridate salt, flour, fruit juices, soup, sugar, milk, ice cream. Ice cream, Mandrake. Children's ice cream.

                          M 1 Reply Last reply
                          0
                          • D David Stone

                            Because Regex.Split takes a String. String.Split needs a char array. And so I didn't want to construct a whole char[]. ;P There's no other good reason.


                            Mandrake, do you realize that in addition to fluoridating water, why, there are studies underway to fluoridate salt, flour, fruit juices, soup, sugar, milk, ice cream. Ice cream, Mandrake. Children's ice cream.

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

                            David Stone wrote:

                            String.Split needs a char array.

                            Obviously, the documentation and Intellisense does not match the implementation, as:

                                        string foo="a,b,c";
                                        string\[\] foo2=foo.Split(',');
                            

                            Compiles fine. Unless there's some implicit conversion to char[]? I use the above syntax all the time! :~ Marc

                            Thyme In The Country

                            People are just notoriously impossible. --DavidCrow
                            There's NO excuse for not commenting your code. -- John Simmons / outlaw programmer
                            People who say that they will refactor their code later to make it "good" don't understand refactoring, nor the art and craft of programming. -- Josh Smith

                            D 1 Reply Last reply
                            0
                            • M Marc Clifton

                              David Stone wrote:

                              String.Split needs a char array.

                              Obviously, the documentation and Intellisense does not match the implementation, as:

                                          string foo="a,b,c";
                                          string\[\] foo2=foo.Split(',');
                              

                              Compiles fine. Unless there's some implicit conversion to char[]? I use the above syntax all the time! :~ Marc

                              Thyme In The Country

                              People are just notoriously impossible. --DavidCrow
                              There's NO excuse for not commenting your code. -- John Simmons / outlaw programmer
                              People who say that they will refactor their code later to make it "good" don't understand refactoring, nor the art and craft of programming. -- Josh Smith

                              D Offline
                              D Offline
                              David Stone
                              wrote on last edited by
                              #24

                              Weird. Huh. Then there's really no reason (here) to use Regex.Split. Go figure.

                              Oh geez... the forum keeps spinning... you'll take care o f it i'm sure, c'ause ... yeah, i neede this. *cough* anyway good job finding the bug.
                              -Shog9 on...a Firefox bug.

                              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