Created
March 7, 2014 07:28
-
-
Save logicchains/9406966 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* After compiling it, eg. with "gcc -Wall -ansi DetermineMajorityValue.c -o DetermineMajorityValue -O3", run with: | |
* "DetermineMajorityValue someInputStringIWantToCheck", where that someInputString is the sequence S. | |
*/ | |
#include <stdlib.h> | |
#include <stdio.h> | |
#include <string.h> | |
/*Defining an array in which the number of each symbol encountered is stored. | |
The input is assumed to consist solely of ASCII unsigned characters, which are represented in memory as integers that are < 256. Each input unsigned character therefore maps to a unique position in the array.*/ | |
int occurrenceCounts[256]; | |
unsigned char* joinInputStrings(int c, unsigned char **argv){ /*Make the strings passed in via argv into a single string, not multiple strings separated by spaces.*/ | |
int i; | |
int totalStringLength = 0; | |
for (i = 1; i < c; ++i){ | |
totalStringLength += strlen(argv[i]); /*Calculate the total number of input unsigned characters.*/ | |
} | |
unsigned char *bigNewString = (unsigned char*)malloc(totalStringLength); /*Allocate a new array in which to store the input string.*/ | |
int curStringPos = 0; | |
for (i = 1; i < c; ++i){ | |
strcpy(bigNewString + curStringPos, argv[i]); /*Add each string in argv into the new array.*/ | |
curStringPos += strlen(argv[i]); | |
} | |
return bigNewString; | |
} | |
int main(int c, char **argv){ | |
if(c < 2){ | |
printf("Error: no input string provided.\n"); | |
return 1; | |
} | |
unsigned char *inputString = joinInputStrings(c, argv); /*Convert the input into one long string.*/ | |
int i; | |
for (i = 0; i < 256; ++i){ | |
occurrenceCounts[i] = 0; /*Zero all the counts in the array.*/ | |
} | |
int nOverTwo = strlen(inputString)/2; | |
int majorityValueFound = 0; | |
for (i = 0; i < nOverTwo; ++i){ | |
occurrenceCounts[inputString[i]]++; | |
} | |
for (; i < strlen(inputString); ++i){ | |
occurrenceCounts[inputString[i]]++; | |
if (occurrenceCounts[inputString[i]] > nOverTwo){ | |
printf("The symbol in S that occurs more than n/2 times is %c.\n", inputString[i]); | |
majorityValueFound = 1; | |
break; | |
} | |
} | |
if (majorityValueFound == 0){ | |
printf("No symbol found that occurs more than n/2 times.\n"); | |
} | |
free(inputString); | |
return 0; | |
} | |
/* Copyright Jonathan Barnard, 2014.*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment