[SOLVED] C programming help

Hello everyone,
Hopefully this is the appropiate spot to post this, I need help with a C programming HW problem. I need to create a program that that finds how many repeated characters in a string. For example the word "missing" has 2 repeating characters and the word "hisssss" has 1 repeating character. In my code posted below, the word "missing" returns 4 repeated characters so I assume my approach was wrong. I also have another similar problem that I need to do, but if i can figure this one out, I can do the next one. If anyone can point me in the right direction I'll greatly appreciate it.
Thanks.
Also, I need to use the function prototype I used in the code.
#include <stdio.h>
#include <string.h>
#define MAX 64
int repeat(char *ptr) {
int length, i, j, count = 0;
char comp[MAX];
length = strlen(ptr);
for (i = 0; i < length; i++)
for (j = 0; j < length; j++) {
if (i != j && ptr[i] == ptr[j])
count++;
} //for
return count;
} //repeat
int main () {
char word[MAX];
char character = ' ';
int total;
printf("word: ");
scanf("%s", word);
total = repeat(word);
printf ("repeated letters: %d", total);
} //main
Last edited by NYFinest (2011-07-08 02:35:10)

tavianator wrote:
listdata wrote:True, but I like my approach better because: (1) it works for arbitrarily dense sets of symbols, and (2) does not needlessly waste space. The advantage of your approach is that you use almost no CPU cycles to calculate the UUID. So for very large input strings, it will be very, very fast (although at the cost of more memory use depending on set density). I was just noting how your approach used more memory, which is not an insignificant point.
1) What do you mean by dense?
2) Both use O(1) space, mine just happens to use slightly more.  For unicode characters obviously my way would be a huge waste, but you could use a hash table or trie or something to keep the space proportional to the number of distinct characters found.
Also, the first U in UUID stands for "universal," which is certainly not true of any of the hashing methods listed here.  UID would make sense though.
This discussion is getting a little too hairy for me, so just to clear up any misunderstandings, here's my (slightly modified) full solution:
* Return unique number for a given character, based on the history buffer. If
* not found in the history, then add the character to the history and return
* its index.
int get_idx(char *history, char *c) {
int i;
for (i = 0; i < MAX; i++) {
if (history[i] == *c)
return i;
if (history[i] == '\0') {
history[i] = *c;
return i;
* History buffer is full, which should never happen as long as both the
* string where *c comes from and the buffer is both MAX big.
assert(0);
* Only use 1 for-loop, and only call get_idx() once per iteration. Drawback:
* get_idx() modifies the history[] array!
int count_reps(char *str) {
int i, idx, reps;
char history[MAX] = {'\0'};
int rep_chars[MAX] = {0};
for (i = 0, reps = 0; str[i] != '\0'; i++) {
idx = get_idx(history, &str[i]);
rep_chars[idx]++;
if (rep_chars[idx] == 2)
reps++;
return reps;
The get_idx() function used to just return 1 or -1 depending on whether the character was found in the hash already, but now it just modifies the history buffer to cut down on the logic. It's still far less impressive than Cdh's solution, though...
Regarding point (1): My approach requires another copy of the string; it's difference from your approach is that it always only requires the same memory space as the original string. Your approach's memory use grows with the number of symbols/characters in the string type's set. That's what I meant by "arbitrary density"...
Point (2): As you can probably see now, my solution can be very slow and certainly is not O(n)...

Similar Messages

  • My speaker is not working properly in 4s if i use headphone its working now my volume increase decrease button is also not working properly how can i solve it pl help me my warranty finished

    my speaker is not working properly in 4s if i use headphone its working now my volume increase decrease button is also not working properly how can i solve it pl help me my warranty finished

    Hello. I sent my WRT1900AC V1 to Linksys four days ago (Monday) via UPS with a RMA. Linksys paid the shipping and everything. The router is still in route, and it should arrive to their offices tomorrow. Once they receive the WRT1900 AC V1, they are going to send me an EA8500 as a replacement. But I have been reading the comments about the EA8500 here in the forum and it seems to have the same problems. I guess the firmware is extremely flawed in both routers (maybe it is almost the same code?). Anyway, I will try the EA8500 and I hope it works. I bought a temporary router from Walmart and I paid $35 for it. It is a Belink N600 DB. I can't believe that a $35 router is working a lot, lot, lot better than my previous $250 WRT1900AC router. Unbelievable. If the EA8500 doesn't work, I'm going to try and get my money back from Linksys, or contact The Consumerist or someone to get my money back and get a Nighthawk instead.

  • TS3899 In my iPad 2 with IO6 today I can not send emails from my gmail account, they go to the outbox directly...why? How can i solve this problem? ..I restarted the IPad but the problem was not solved. Please help.

    In my iPad 2 with IO6 today I can not send emails from my gmail account, they go to the outbox directly...why? How can i solve this problem? ..I restarted the IPad but the problem was not solved. Please help.

    Greetings,
    Questions:
    1. What version of the Mac OS are you running (Apple > About this Mac)?
    2. What version of the iOS are you running (Settings > About)?
    3. Do you use MobileMe/ iCloud or another server based sync solution like Google or Yahoo?
    4. Do other changes to synced information like Address Book content sync successfully back and forth?
    Based on your description it sounds like you have a 1 way sync issue.  Events sync fine between the iOS devices and fine from the computer to the iOS devices but not from the iOS devices to the computer.
    Try:
    Backup your computer and iOS devices before doing anything else:
    http://support.apple.com/kb/HT1427
    http://support.apple.com/kb/ht1766
    Ensure all the devices in use are fully up to date: Apple > Software Update / Settings > General > Software Update
    Make separate backups of critical data:
    Backup your computer Addressbook: http://docs.info.apple.com/article.html?path=AddressBook/4.0/en/ad961.html
    Backup your computer iCal: http://support.apple.com/kb/HT2966
    Reset syncing on your Mac: http://support.apple.com/kb/TS1627
    Reply back if that does not resolve your issue.
    Hope that helps.

  • When i open itunes its normal and then out of nowhere it says "itunes has stopped working" and i have to click 'close program'. help?

    when i open itunes its normal and then out of nowhere it says "itunes has stopped working" and i have to click 'close program'. help?

    Having the same issue here....a quick fix is to just minimize the window, and immediately maximize it.  It will now fit the screen.  Trouble is, after you close it, you'll have to do it again when you re-start itunes.  The good news is it takes all of about 2 seconds.  Apple should fix this.  Should.

  • Programming help - how to get the read-only state of PDF file is windows explorer preview is ON?

    Programming help - how to get the read-only state of PDF file is windows explorer preview is ON?
    I'm developing an application where a file is need to be saved as pdf. But, if there is already a pdf file with same name in the specified directory, I wish to overwrite it. And in the overwrite case, read-only files should not be overwritten. If the duplicate(old) file is opened in windows (Win7) explorer preview, it is write protected. So, it should not be overwritten. I tried to get the '
    FILE_ATTRIBUTE_READONLY' using MS API 'GetFileAttributes', but it didn't succeed. How Adobe marks the file as read-only for preview? Do I need to check some other attribute of the file?
    Thanks!

    Divya - I have done it in the past following these documents. Please read it and try it it will work.
    Please read it in the following order since both are a continuation documents for the same purpose (it also contains how to change colors of row dynamically but I didnt do that part I just did the read_only part as your requirement) 
    http://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/f0625002-596c-2b10-46af-91cb31b71393
    http://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/d0155eb5-b6ce-2b10-3195-d9704982d69b?quicklink=index&overridelayout=true
    thanks!
    Jason PV

  • Freely Programmed help in Pop Up Window

    Hi,
      Is it possible to display the data of freely programmed help in the pop up window.
    Thanks
    Raghavendra

    Hi Thomas,
       I agree that by using Freely Programmed help the data will be displayed in a seperate window. I want to display the data in a window( of type Pop Up) because i am displaying table control with 3 fields on clicking f4 and it has 2 buttons Ok and Cancel. But if there are 50 entries the user needs to scroll down to click on Ok. If the window is of type pop up Ok button will be embedded in the window instead of on view.
    Thanks
    Raghavendra

  • Freely programmed help in ALV

       HI:ALL
          How to achieve  Freely programmed help in ALV?

    Hi,
    On APPLY buttton action, write the below code
    *Fire the event to indicate that data selection is done
    wd_comp_controller->fire_vh_data_selected_evt( ).
    wd_comp_controller->value_help_listener->close_window( ).
    *Raise Event
       cl_fpm_factory=>get_instance( )->raise_event_by_id( EXPORTING   iv_event_id   = '<custom event name>').
    And in PROCESS_EVENT of your webdynpro component(where Freely Programmed search help is implemented) write the code as per your requirement to set the values back to the table.
    CASE IO_EVENT->MV_EVENT_ID.
              WHEN '<CUSTOM EVENT NAME>'.
                        write code as per your requirement.
    ENDCASE.
    Thanks
    KH

  • N95 Maps Program Help and Suggestions Anybody??

    N95 Maps Program Help and Suggestions Anybody??
    havnt updated to firmware v12 yet
    Why can't I search my Address or Current Location and then save this as HOME or say my Start_Point_01?
    I have managed to save my HOME as a PEOPLE LOCATION and my friends address etc and worked out
    how to plan a route etc, BUT Maps GPS POSITION thinks I live 20 miles away??
    I dont seem to be able to simply set my HOME or Current Location myself,
    I have seen some Satelite activity but insists I live 20 miles away :/ how do I fix this,
    it's realy annoying. any handy tips people??
    cant upgrade firmware as need phone plugged into wall socket
    at webcafe, will have to wait for firmware :/
    N95-1 (8GB-MicroSD),LCG-Audio,Fring,Nimbuzz,Skype,Youtube,iPlayer,Garmin4-GPS.Googlemaps,SkyFire,ZoneTag,Gravity, Sennheiser CX-400-IIs,500-IIs,TR-120 Wireless,HD215'S.AudioTechnica ATX-M50's.BT B-Tube BT Speaker.

    The least problems you'll have with miniDV cameras. About any miniDV camera will connect to a Mac via Firewire. HDD cameras are an open invitation to trouble, especially as you speak of older computers.
    There are well-featured models out there now for 2-300 bucks. But watch out for cameras that connect to the computer via a dock. I had two Sony with these @#$% docking stations .... both docks broke and rendered the cameras useless for capturing. replacing the dock was nearly the price of a new cam.

  • I'm using firefox 6.0.2 It's making problem with Bangla font ONLY on FACEBOOK others bangli website FORNT SIZE are OK. On the FACEBOOK it shows Bangla font in a very / Too small! I change font SIZE in firefox setting but i can't solve. Pls HELP me

    I'm using firefox 6.0.2 It's making problem with Bangla font ONLY on FACEBOOK others bangli website FORNT SIZE are OK. On the FACEBOOK it shows Bangla font in a very / Too small! I change font SIZE in firefox setting but i can't solve. Pls HELP me ..

    Reset the page zoom on pages that cause problems: <b>View > Zoom > Reset</b> (Ctrl+0 (zero); Cmd+0 on Mac)
    *http://kb.mozillazine.org/Zoom_text_of_web_pages
    You can use an extension to set a default font size and page zoom on web pages.
    *Default FullZoom Level: https://addons.mozilla.org/firefox/addon/default-fullzoom-level/
    *NoSquint: https://addons.mozilla.org/firefox/addon/nosquint/

  • What Is Wrong With My Program Help

    This Is The Assignment I Have To Do:
    Write a Java program that prints a table with a list of at least 5 students together with their grades earned (lab points, bonus points, and the total) in the format below.
    == Student Points ==
    Name Lab Bonus Total
    Joe 43 7 50
    William 50 8 58
    Mary Sue 39 10 49
    The requirements for the program are as follows:
    1.     Name the project StudentGrades.
    2.     Print the border on the top as illustrated (using the slash and backslash characters).
    3.     Use tab characters to get your columns aligned and you must use the + operator both for addition and string concatenation.
    4.     Make up your own student names and points -- the ones shown are just for illustration purposes. You need 5 names.
    This Is What I Have So Far:
    * Darron Jones
    * 4th Period
    * ID 2497430
    *I recieved help from the internet and the book
    *StudentGrades
      public class StudentGrades
         public static void main (String[] args )
    System.out.println("///////////////////\\\\\\\\\\\\\\\\\\");
    System.out.println("==          Student Points          ==");
    System.out.println("\\\\\\\\\\\\\\\\\\\///////////////////");
    System.out.println("                                      ");
    System.out.println("Name            Lab     Bonus   Total");
    System.out.println("----            ---     -----   -----");
    System.out.println("Dill             43      7       50");
    System.out.println("Josh             50      8       58");
    System.out.println("Rebbeca          39      10      49");When I Compile It Keeps Having An Error Thats Saying: "Illegal Escape Character" Whats Wrong With The Program Help Please

    This will work exactly as you want it to be....hope u like it
         public static void main(String[] args)
              // TODO Auto-generated method stub
              System.out.print("///////////////////");
              System.out.print("\\\\\\\\\\\\\\\\\\\\\\\\");
              System.out.println("\\\\\\\\\\\\\\");
              System.out.println("== Student Points ==");
              System.out.print("\\\\\\\\\\\\\\");
              System.out.print("\\\\\\\\\\\\");
              System.out.print("\\\\\\\\\\\\");
              System.out.print("///////////////////");
              System.out.println(" ");
              System.out.println("Name Lab Bonus Total");
              System.out.println("---- --- ----- -----");
              System.out.println("Dill 43 7 50");
              System.out.println("Josh 50 8 58");
              System.out.println("Rebbeca 39 10 49");
         }

  • HT3964 I am getting the error message "No AirPort card installed" Restarting my iMac desktop does not solve this (Apple help says I need to reset the SMC this way, but nothing changes. Can somebody advise, please?

    I am getting the error message "No AirPort card installed" Restarting my iMac desktop does not solve this (Apple help says I need to reset the SMC this way, but nothing changes). Can somebody advise, please?

    Thanks for the flag J.K. - they contaced me and solved my problem.  On this account (which I created just to ask this question), I log in with my email rather than my user name (mtalldud). On the account that I was having trouble with, they told me to use my user ID instead of my email to log in and it worked. This is a bit confusing and seems a bit inconsistent but at least I don't need this temporary account any more to get into this community and find answers!

  • Freely Programed Help for select-option field

    Hi,
    how can i set freely programmed help for select option field, i mean while adding selection field what are the parameters that are important for freely programmed help.
    i have implemented iwd_value_help in one component comp1 and declared the usage of comp1 in comp2 where i actually defined the usage of select-option component.
    i used parameter   i_value_help_type = if_wd_value_help_handler=>co_prefix_appldev while adding selection field, however when i presss F4 icon, the following message is coming
    View WD_VALUE_HELP does not exist within the component WDR_SELECT_OPTIONS
    Please suggest where i am doing wrong??
    Edited by: kranthi kumar on Dec 29, 2010 6:19 PM

    >
    kranthi kumar wrote:
    > Hi,
    >
    > how can i set freely programmed help for select option field, i mean while adding selection field what are the parameters that are important for freely programmed help.
    >
    > i have implemented iwd_value_help in one component comp1 and declared the usage of comp1 in comp2 where i actually defined the usage of select-option component.
    >
    > i used parameter   i_value_help_type = if_wd_value_help_handler=>co_prefix_appldev while adding selection field, however when i presss F4 icon, the following message is coming
    >
    > View WD_VALUE_HELP does not exist within the component WDR_SELECT_OPTIONS
    >
    > Please suggest where i am doing wrong??
    >
    > Edited by: kranthi kumar on Dec 29, 2010 6:19 PM
    Hi Kranthi,
    Please help me to understand your design.
    Why would you like to create a Freely programmed value help for select-option?. why not use wdr_select_option directly ?

  • Why i cant open the ae after i download ~then pop up something like ae error, crash in program~help~pls

    why i cant open the ae after i download ~then pop up something like ae error, crash in program~help~pls

  • I recently updated my iPhone to version 7.0.4. After that my facebook app crashes much often and the problem of freezing is also increased. How to solve that? Help!!

    Most recently, I updated my iOS version to 7.0.4. After that, my facebook app often gets crashed and even though I re-install it, the problem persists. And also, the phone freezes much often. I am really afraid that my device is damaged or engulfed with bugs. How can I solve this? Help please!!

    Time to update to iOS 7.0.6.

  • My Apple ID is still disabled. How to fix it? I tried the steps given but just cant be solved. Please help.

    My Apple ID is still disabled. How to fix it? I tried the steps given but just cant be solved. Please help. i use right keyword but cant open apple id my

    Goldboyvidar wrote:
    how i can open my apple id?? 
    As the article states, you need to reset your password.
    how i can talk to apple center and i am deaf cant call them and them have not email???
    You can contact Apple Support online here
    or
    by phone: Apple Support Numbers

Maybe you are looking for

  • Crawl log error in sharepoint 2013 for search services

    Dear Support, please find below mention crawl log error in sharepoint 2013 for search services. 8,597 The server is unavailable and could not be accessed. The server is probably disconnected from the network.  423 This item could not be crawled becau

  • Is there any kind of application for keeping Precedence?

    I act as a Speaker of the Hous for a Mock session of Congress, is there any kind of application that will he me keep track of precedence throughout the session?

  • How do I disable tearaway tabs?

    I just upgraded to firefox 4.0 and had forgotten about the tearaway tabs feature (because I had installed an extension that disables it in 3.X that didn't port into 4.0). I've seen a large number of people talk about having a way to turn it off since

  • When is the Free Tablet with purchase of a G3 offer expire?

    I'm up for my upgrade soon and keep looking for good deals. I saw this one and wanted to know if my upgrade date is still good for this awesome offer!

  • Updating - Never but always Publishing?!

    Hi, Can someone please tell me if it is actually a fault in iWeb, that the 'update' feature as such, just doesn't work? In the help it says that when you 'publish', it will update only the files you have changed since your last publish. I find that a