Skip to content

Instantly share code, notes, and snippets.

@logicchains
Last active August 29, 2015 13:57
Show Gist options
  • Save logicchains/9362593 to your computer and use it in GitHub Desktop.
Save logicchains/9362593 to your computer and use it in GitHub Desktop.
/* 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 characters, which are represented in memory as integers that are < 256. Each input character therefore maps to a unique position in the array.*/
int occurrenceCounts[256];
char* joinInputStrings(int c, 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 characters.*/
}
char *bigNewString = (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;
}
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.*/
}
for (i = 0; i < strlen(inputString); ++i){ /*Iterate over the input string.*/
occurrenceCounts[inputString[i]]++; /*Increment the count of the index in the array that's equal to the ASCII value of the input character. */
}
int majorityValueFound = 0;
int nOverTwo = strlen(inputString)/2;
for (i = 0; i < 256; ++i){
if (occurrenceCounts[i] > nOverTwo){
printf("The symbol in S that occurs more than n/2 times is %c.\n", i);
majorityValueFound = 1;
}
}
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