DevPinoy.org
A Filipino Developers Community
   

Another Programming Quiz!

rated by 0 users
This post has 40 Replies | 2 Followers

Top 10 Contributor
Posts 1,999
Points 41,320
keithrull Posted: 12-14-2006 5:38 PM

Jokiz won our last book giveaway! now its time for another programming quiz!

Problem:
Given a sentence or phrase, count the number of words that exist in a phrase.
Each word is delimited by a space and words that are wrapped in quotes ("") is considered 1 word

Oh, No using of built in String methods(e.g String.Split, String.Join, String.ToCharArray and etc.)

Below are test inputs that you should consider when writing the application

The phrase: [ this is a long text consist of different words. ] has 9 words
The phrase: [ "this is a long text consist of different words." ] has 1 words
The phrase: [ this "is a long" text consist "of different words. ] has 7 words
The phrase: [ "this is a long text consist of different words. ] has 9 words
The phrase: [ this is a long text consist of different words." ] has 9 words
The phrase: [ ""this is a long text consist of different words. ] has 9 words
The phrase: [ this is a long text consist of different words."" ] has 9 words
The phrase: [ this is a long text"" consist of different words. ] has 9 words
The phrase: [ this is a long text "" consist of different words. ] has 9 words
The phrase: [ this is a long text  consist of different words. ] has 9 words
The phrase: [ this is a     long text     consist of different words. ] has 9 words
The phrase: [  ] has 0 words

prize: A TDD Book + C# Book(or Java)

*note: the best solution will win the prize | Deadline for submissions is December 18, 2006

devpinoy sig

Top 10 Contributor
Posts 1,009
Points 23,550
what if the quotes only contain spaces? like

this is a long "     " text

does that count as 5 words or 6?

http://devpinoy.org/blogs/cruizer
Naglalayong buksan at palayain ang kamalayan ng Pinoy .NET developer
  • | Post Points: 20
Top 10 Contributor
Posts 1,009
Points 23,550
here's my solution (badly needs refactoring!!!)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
  public class WordCount
  {
    public bool StartOfNewWord(char prev, char next)
    {
      if ((prev == ' ') && (next != ' '))
        return true;
      else return false;
    }
    public bool ForbiddenWord(string word)
    {
      const string doubleQuotesOnly = "\"\"";
      const string lonelyQuote = "\"";
      return ((word == doubleQuotesOnly) || (word == lonelyQuote) ||
 (word == String.Empty) || OnlySpacesIn(word));
    }
    public bool OnlySpacesIn(string word)
    {
      bool allSpaces = true;
      string strippedWord = RemoveInitialQuoteFrom(word);
      for (int i = 0; i < strippedWord.Length; i++)
        if (strippedWord[ i ] != ' ')
        {
          allSpaces = false;
          break;
        }
      return allSpaces;
    }
    public string RemoveInitialQuoteFrom(string word)
    {
      string newWord = String.Empty;
      for (int i = 0; i < word.Length; i++)
        if (word[ i ] != '"') newWord += word[ i ];
      return newWord;
    }
    public bool HasOnlyOneQuote(string word)
    {
      int quoteCount = 0;
      for (int i = 0; i < word.Length; i++)
      {
        if (word[ i ] == '"
') quoteCount++;
      }
      return (quoteCount == 1);
    }
    public int CountWordsIn(string message)
    {
      char prev = ' ';
      int numWords = 0;
      bool inQuote = false;
      string currentWord = String.Empty;

      for (int i = 0; i < message.Length; i++)
      {
        char current = message[ i ];
        if (inQuote)
        {
          currentWord += current;
          if (current == '"')
          {
            inQuote = !inQuote;
          }
        }
        else if (StartOfNewWord(prev, current))
        {
          if (!ForbiddenWord(currentWord)) numWords++;
          currentWord = String.Empty;
          currentWord += current;
          if (current == '"
')
          {
            inQuote = !inQuote;
          }
        }
        else
        {
          if (current != ' ') currentWord += current;
        }
        prev = current;
      }
      if (!ForbiddenWord(currentWord) && HasOnlyOneQuote(currentWord))
      {
        numWords += CountWordsIn(RemoveInitialQuoteFrom(currentWord));
      }
      else if (!ForbiddenWord(currentWord)) numWords++;
      return numWords;
    }
  }

main entry point is the int CountWordsIn(string message) method...
http://devpinoy.org/blogs/cruizer
Naglalayong buksan at palayain ang kamalayan ng Pinoy .NET developer
  • | Post Points: 5
Top 10 Contributor
Posts 1,999
Points 41,320

cruizer:
what if the quotes only contain spaces? like

this is a long "     " text

does that count as 5 words or 6?

according to the instruction it should be considered a word so the correct answere is 6

devpinoy sig

  • | Post Points: 20
Top 10 Contributor
Posts 1,009
Points 23,550
ngek! ganon ba? lemme modify my solution then...
http://devpinoy.org/blogs/cruizer
Naglalayong buksan at palayain ang kamalayan ng Pinoy .NET developer
  • | Post Points: 5
Top 10 Contributor
Posts 1,009
Points 23,550
my modified solution to conform to Keith's "user story:"

  public class WordCount
  {
    public bool StartOfNewWord(char prev, char next)
    {
      if (IsASpace(prev) && !IsASpace(next))
        return true;
      else return false;
    }
    public bool ForbiddenWord(string word)
    {
      const string doubleQuotesOnly = "\"\"";
      const string lonelyQuote = "\"";
      return ((word == doubleQuotesOnly) || (word == lonelyQuote) ||
       (word == String.Empty));
    }
    public bool ForbiddenWord(StringBuilder word)
    {
      return ForbiddenWord(word.ToString());
    }
    public string RemoveInitialQuoteFrom(string word)
    {
      string newWord = String.Empty;
      for (int index = 0; index < word.Length; index++)
        if (!IsAQuote(word[index])) newWord += word[index];
      return newWord;
    }
    public string RemoveInitialQuoteFrom(StringBuilder word)
    {
      return RemoveInitialQuoteFrom(word.ToString());
    }
    public bool HasOnlyOneQuote(string word)
    {
      int quoteCount = 0;
      for (int index = 0; index < word.Length; index++)
      {
        if (IsAQuote(word[index])) quoteCount++;
      }
      return (quoteCount == 1);
    }
    public bool HasOnlyOneQuote(StringBuilder word)
    {
      return HasOnlyOneQuote(word.ToString());
    }
    public int CountWordsIn(string message)
    {
      char prev = ' ';
      int numWords = 0;
      bool inQuote = false;
      StringBuilder currentWord = new StringBuilder();

      for (int index = 0; index < message.Length; index++)
      {
        char current = message[index];
        if (inQuote)
        {
          currentWord.Append(current);
        }
        else if (StartOfNewWord(prev, current))
        {
          if (!ForbiddenWord(currentWord)) numWords++;
          currentWord = new StringBuilder();
          currentWord.Append(current);
        }
        else
        {
          if (!IsASpace(current))
            currentWord.Append(current);
        }
        if (IsAQuote(current))
        {
          inQuote = !inQuote;
        }
        prev = current;
      }
      if (HasOnlyOneQuote(currentWord))
      {
        numWords += CountWordsIn(RemoveInitialQuoteFrom(currentWord));
      }
      else if (!ForbiddenWord(currentWord)) numWords++;
      return numWords;
    }
    private bool IsAQuote(char c)
    {
      return (c == '"');
    }
    private bool IsASpace(char c)
    {
      return (c == ' ');
    }
  }

(edited for a bit of refactoring and removed line numbers)
http://devpinoy.org/blogs/cruizer
Naglalayong buksan at palayain ang kamalayan ng Pinoy .NET developer
  • | Post Points: 35
Top 10 Contributor
Posts 461
Points 6,950

Ahh suko na ko sa C# nakaklito masyado, here's mine.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Public Class clsWords

Public Function Count(ByVal strSentence As String) As Integer
Dim chrArray As Char() = strSentence
Dim intCntr As Integer
Dim blnDoubleQuoteEncountred As Boolean
Dim intStringCount As Integer

For intCntr = 0 To chrArray.Length - 1

If chrArray(intCntr) = """" Then
If blnDoubleQuoteEncountred Then
blnDoubleQuoteEncountred = False
intStringCount += 1
Else
blnDoubleQuoteEncountred = True
End If

ElseIf chrArray(intCntr) = " " And blnDoubleQuoteEncountred = False Then
If intCntr > 0 Then If chrArray(intCntr - 1) <> " " Then intStringCount += 1
End If

Next

Return intStringCount
End Function

End Class

...Think 64 Bit
  • | Post Points: 5
Top 25 Contributor
Posts 96
Points 1,370
cruizer:
my modified solution to conform to Keith's "user story:"

  public class WordCount
  {
    public bool StartOfNewWord(char prev, char next)
    {
      if (IsASpace(prev) && !IsASpace(next))
        return true;
      else return false;
    }
    public bool ForbiddenWord(string word)
    {
      const string doubleQuotesOnly = "\"\"";
      const string lonelyQuote = "\"";
      return ((word == doubleQuotesOnly) || (word == lonelyQuote) ||
       (word == String.Empty));
    }
    public bool ForbiddenWord(StringBuilder word)
    {
      return ForbiddenWord(word.ToString());
    }
    public string RemoveInitialQuoteFrom(string word)
    {
      string newWord = String.Empty;
      for (int index = 0; index < word.Length; index++)
        if (!IsAQuote(word[index])) newWord += word[index];
      return newWord;
    }
    public string RemoveInitialQuoteFrom(StringBuilder word)
    {
      return RemoveInitialQuoteFrom(word.ToString());
    }
    public bool HasOnlyOneQuote(string word)
    {
      int quoteCount = 0;
      for (int index = 0; index < word.Length; index++)
      {
        if (IsAQuote(word[index])) quoteCount++;
      }
      return (quoteCount == 1);
    }
    public bool HasOnlyOneQuote(StringBuilder word)
    {
      return HasOnlyOneQuote(word.ToString());
    }
    public int CountWordsIn(string message)
    {
      char prev = ' ';
      int numWords = 0;
      bool inQuote = false;
      StringBuilder currentWord = new StringBuilder();

      for (int index = 0; index < message.Length; index++)
      {
        char current = message[index];
        if (inQuote)
        {
          currentWord.Append(current);
        }
        else if (StartOfNewWord(prev, current))
        {
          if (!ForbiddenWord(currentWord)) numWords++;
          currentWord = new StringBuilder();
          currentWord.Append(current);
        }
        else
        {
          if (!IsASpace(current))
            currentWord.Append(current);
        }
        if (IsAQuote(current))
        {
          inQuote = !inQuote;
        }
        prev = current;
      }
      if (HasOnlyOneQuote(currentWord))
      {
        numWords += CountWordsIn(RemoveInitialQuoteFrom(currentWord));
      }
      else if (!ForbiddenWord(currentWord)) numWords++;
      return numWords;
    }
    private bool IsAQuote(char c)
    {
      return (c == '"');
    }
    private bool IsASpace(char c)
    {
      return (c == ' ');
    }
  }

(edited for a bit of refactoring and removed line numbers)

this is neat... i'll submit my code later :D

When will be the deadline for this one?
  • | Post Points: 5
Top 25 Contributor
Posts 96
Points 1,370

using System.Text;

public class WordCount
{
    private int _index;
    private bool IsValidWord(string word)
    {
        return word.Length > 0 && word != "\"\"" && word != "\" " && word != "\"";
    }

    private string GetWord(string message, int start)
    {
        StringBuilder word = new StringBuilder();
        int sIndex = -1;
        string sWord = "";
        int qIndex = -1;
        int i = start;
       
        while (i < message.Length && message[ i ] == ' ') i++;
        if (i >= message.Length) return "";

        word.Append(message[ i ]);
        int j = i + 1;

        if (word.ToString() == "\"")
        {
            while (j < message.Length)
            {
                word.Append(message[j]);
                if (sIndex == -1 && (message[j] == ' ' || j == message.Length - 1))
                {
                    sIndex = j;
                    sWord = word.ToString();
                }
                else if (message[j] == '"' && (j == message.Length - 1 || message[j+1] == ' '))
                {
                    qIndex = j;
                    break;
                }
                j++;
            }
            if (qIndex != -1)
            {
                _index = qIndex;
            }
            else if (sIndex != -1)
            {
                _index = sIndex;
                word = new StringBuilder(sWord);    //word.Replace(word.ToString(), sWord); // word.Replace might be illegal
            }
            else
            {
                _index = message.Length - 1;
            }
        }
        else
        {
            while (j < message.Length && message[j] != ' ')
            {
                word.Append(message[j]);
                j++;
            }
            _index = --j;
        }
        string wordString = word.ToString();
        return word.ToString();

    }

    public int CountWords(string message)
    {
        string word;
        int wordCount = 0;
        for (_index = 0; _index < message.Length; _index++)
        {
            word = GetWord(message, _index);
            if (IsValidWord(word))
                wordCount++;
        }
        return wordCount;
    }
}

  • | Post Points: 5
Top 10 Contributor
Posts 1,105
Points 18,350
 hmmm,  i'll contact roy osherove for some regex rules, :p
  • | Post Points: 20
Top 10 Contributor
Posts 835
Points 10,775
Here's mine. I hope its correct.
lea esi, buffer
invoke lstrlen, esi
cmp eax, 0
jz _nothing
mov ecx, eax
xor edi, edi
_counter:
dec ecx
jz _finished
lodsb
cmp al, ' '
je _validate_space
jmp _not_space

_validate_space:
inc edi
cmp edi, 1
je _found_space
jmp _counter

_not_space:
xor edi, edi
cmp al, '"'
je _found_quote
jmp _counter

_found_space:
inc ebx
jmp _counter

_found_quote:
dec ecx
jz _finished
lodsb
cmp al, '"'
jne _found_quote
jmp _counter

_nothing:
invoke MessageBox, hWin, addr nothing, addr caption, MB_OK
jmp _breakout

_finished:
add ebx, 1
invoke dwtoa, ebx, addr result
invoke szMultiCat, 3,  addr message_complete, addr message_start, addr result, addr message_end
invoke MessageBox, hWin, addr message_complete, addr caption, MB_OK

_breakout:
invoke lstrcpy, addr message_complete, addr blank

  • | Post Points: 20
Top 10 Contributor
Posts 1,009
Points 23,550
ambangis, assembly pa! Yes
http://devpinoy.org/blogs/cruizer
Naglalayong buksan at palayain ang kamalayan ng Pinoy .NET developer
  • | Post Points: 20
Top 10 Contributor
Posts 527
Points 8,685
Oops, I'm a little late Stick out tongue
Anyways, I'm just cheering you guys in the background.

-chris
Chris Vega This posting is provided "AS IS" with no warranties, and confers no rights My Weblog|Visit MSDN Community
  • | Post Points: 35
Top 10 Contributor
Posts 835
Points 10,775
Welcome back Chris! :)

  • | Post Points: 20
Top 10 Contributor
Posts 1,105
Points 18,350
wb boss, na-miss ka namin, matagal na walang nag-aangas dito eh,  Stick out tongue
  • | Post Points: 50
Page 1 of 3 (41 items) 1 2 3 Next > | RSS

Copyright DevPinoy 2005-2008