Topic: | Data Structures (Arrays) |
---|---|
Author: | Peter Bui <pbui@cse.nd.edu> |
Date: | August 31, 2009 |
int mInts[128];
char mString[MAX_STRLEN];
const char *mStrings[NSTRINGS] = { "Aww", "Herro", "Prz" };
C string is just an array of chars.
Arrays best when you know how many elements are needed ahead of time.
Input:
In hoc signo vinces. E pluribus unum.
Output:
h E
Naive Solution: O(N2)
# For each letter in String, check if letter appears
# more than once
for C in String:
i = 0
for CC in String:
if C.lower() == CC.lower(): i += 1
if i >= 1: break
if i == 1:
return C
Binning Solution: O(N)
char letter_count[NLETTERS];
char *sptr;
for(sptr = s; *sptr != 0; sptr++)
if (isalpha(*sptr))
letter_count[tolower(*sptr) - 'a']++;
for(sptr = s; *sptr != 0; sptr++)
if (isalpha(*sptr))
if (letter_count[tolower(*sptr) - 'a'] == 1)
return *sptr;
Complete binning example.
Arrays best when you have a fixed and bounded size set.
Input:
5 4 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3
Allocate Matrix
int **mMatrix;
mMatrix = malloc(sizeof(int*) * mRows);
for (r = 0; r < mRows; r++)
mMatrix[r] = malloc(sizeof(int) * mColumns);
// Remember to free!
Complete matrix example.