How to count with hash

This is a discussion on How to count with hash within the C Programming forums, part of the General Programming Boards category; So i have a string, lets say "I love dogs. I love cats. I love turtles." in this file. I ...

  1. #1
    Registered User
    Join Date
    Oct 2008
    Posts
    91

    How to count with hash

    So i have a string, lets say "I love dogs. I love cats. I love turtles." in this file. I pass the file through and I want to count the amount of each word that pops up so the output would be like

    I = 3
    Love = 3
    dogs = 1
    cats = 1
    turtles = 1

    I was wondering if someone lead me into the right direction. I'm really new to hash.

  2. #2
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,167
    First of all, this can really be done without hashes. It will just be slower (you'll need to compare whole strings, which is O(n)).

    One way to do it with hashing, assuming you already figured out how to get the words one by one -
    Maintain a map of hashes to counts, and a set of strings encountered.

    For each word, hash the word, and try to find the hash in the map. If it doesn't exist (meaning it's the first time you encountered the word). Add it to the map, set count to 0, and insert the string into the set.

    If it exists, just increment the count.

    At the end, iterate through the set, calculate the hash for each word, and get the count from the map.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can you help me about tolower() in file
    By nctar in forum C Programming
    Replies: 7
    Last Post: 05-12-2010, 10:04 AM
  2. bintree and count (withouth using template)?
    By cubimongoloid in forum C++ Programming
    Replies: 7
    Last Post: 05-24-2009, 06:22 AM
  3. Group Project Help/Volunteer
    By DarkDot in forum C++ Programming
    Replies: 3
    Last Post: 04-24-2007, 11:36 PM
  4. input question
    By piyush_v in forum C Programming
    Replies: 9
    Last Post: 04-12-2007, 07:09 AM
  5. Program Crashing
    By Pressure in forum C Programming
    Replies: 3
    Last Post: 04-18-2005, 10:28 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21