Skip to content

Instantly share code, notes, and snippets.

@drbh
Created November 7, 2018 03:56
Show Gist options
  • Select an option

  • Save drbh/86b7579ae6523fe25d30fbcb66c5e526 to your computer and use it in GitHub Desktop.

Select an option

Save drbh/86b7579ae6523fe25d30fbcb66c5e526 to your computer and use it in GitHub Desktop.
Determine if a word or phrase is an isogram. An isogram (also known as a "nonpattern word") is a word or phrase without a repeating letter, however spaces and hyphens are allowed to appear multiple times. Examples of isograms: lumberjacks background downstream six-year-old The word isograms, however, is not an isogram, because the s repeats.
#include "isogram.h"
#include "string.h"
#include "ctype.h"
// simple Key/Value struct
struct Map {
int Key;
int Value;
};
bool is_isogram(const char phrase[])
{
// check if the input is NULL
if (phrase == 0) return false;
// we need to get the size of our string
int word_len = strlen(phrase);
// we need to make it a char and not a const char
char temp[word_len + 1];
strcpy(temp, phrase);
// we also loop though and make everything lowercase
for(int i = 0; temp[i]; i++){
temp[i] = tolower(temp[i]);
}
// we inialize a freq map
struct Map freqMapArray[word_len];
// add all values to map list in int form (no need to deal with chars)
for(int i = 0; temp[i] != '\0'; i++) {
struct Map freq;
const char character = temp[i];
freq.Key = character - '\x00';
freq.Value = 0;
freqMapArray[i] = freq;
}
// we could be smarter and check the values as we add them to our freq
// lookup Map Array - but for simplicty we build them, then
// loop over our map
for (int i = 0; i < word_len; ++i)
{
// pull the vars out as that we saved above
struct Map b = freqMapArray[i];
// loop over map for each var
for (int i = 0; i < word_len; ++i)
{
// pull the values out of the list
struct Map c = freqMapArray[i];
if (b.Key == c.Key)
{
switch(b.Key) {
case 32: // whitespaces
break;
case 45: // -
break;
default : // all others we add to the value
b.Value += 1;
}
}
// if we've seen more than one - return false
if (b.Value > 1 ){
return false;
}
}
}
// if we got through all the code above -
// we havent seen any chars more than once
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment