Docsity

Section Handout - Programming Paradigms - 18, Exercises of Programming Paradigms

Toggle sidebar
bg1
CS107 Handout 18
Spring 2008 April 25, 2008
Section Handout
Problem 1: The sparsestringarray
A sparsestringarray is an array-like data structure that provides constant time access to its
elements, and constant time insertion and deletion. It layers array semantics over an
ordered collection of C strings, with the understanding that most of the strings are empty.
The sparsestringarray is different from C arrays and other array-like data structures,
because it’s aggressively miserly in its use of memory. Each empty string requires just one
bit of storage, which is less than 3% of the memory cost incurred by the allocation of a full
char *. The implementation is slower than true C arrays and our vector from Assignment
3, but it’s a wise choice when memory is at a premium and an overwhelmingly large
fraction of the strings being stored are the empty string.
Our sparsestringarray is backed by an array of groups, where each group is responsible
for managing a contiguous subset of array indices. The programmer specifies not only the
logical length of the sparsestringarray, but also the group size. If the logical length of the
full sparsestringarray is, for instance, established as 50,000, and the group size is
established to be 100, then group 0 would manage indices 0 through 99, group 1 would
manage indices 100 through 199, group 2 would manage indices 200 through 299, and so
forth. All search, insert, and delete operations are passed on to the appropriate group.
typedef struct {
group *groups; // dynamically allocated array of structs, defined below
int numGroups; // number of groups
int arrayLength; // logical length of the full sparsestringarray
int groupSize; // number of strings managed by each group
} sparsestringarray;
Each group contains a bitmap, which is an array of bools whose length is equal to the group
size, and a C vector (yes, Assignment 3’s vector) to store nonempty, dynamically allocated
C strings. Search for a particular element amounts to search within a particular group at
index i. If bitmap[i] is false, then the string at the ith position is understood to be the
empty string. If instead bitmap[i] is true, then the group needs to find the corresponding
string in the C vector.
typedef struct {
bool *bitmap; // set to be of size 'groupSize'
vector strings; // vector of dynamically allocated, nonempty C strings
} group;
Each true in a group’s bitmap corresponds to some char * (addressing a dynamically
allocated C string) in the same group’s vector. The true at the lowest index in the bitmap
corresponds to the 0th entry in the vector; the true at the second lowest index in the bitmap
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26

Partial preview of the text

Download Section Handout - Programming Paradigms - 18 and more Exercises Programming Paradigms in PDF only on Docsity!

CS107 Handout 18 Spring 2008 April 25, 2008

Section Handout

Problem 1: The sparsestringarray

A sparsestringarray is an array-like data structure that provides constant time access to its

elements, and constant time insertion and deletion. It layers array semantics over an

ordered collection of C strings, with the understanding that most of the strings are empty.

The sparsestringarray is different from C arrays and other array-like data structures,

because it’s aggressively miserly in its use of memory. Each empty string requires just one

bit of storage, which is less than 3% of the memory cost incurred by the allocation of a full

char *. The implementation is slower than true C arrays and our vector from Assignment

3, but it’s a wise choice when memory is at a premium and an overwhelmingly large

fraction of the strings being stored are the empty string.

Our sparsestringarray is backed by an array of groups, where each group is responsible

for managing a contiguous subset of array indices. The programmer specifies not only the

logical length of the sparsestringarray , but also the group size. If the logical length of the

full sparsestringarray is, for instance, established as 50,000, and the group size is

established to be 100, then group 0 would manage indices 0 through 99, group 1 would

manage indices 100 through 199, group 2 would manage indices 200 through 299, and so

forth. All search, insert, and delete operations are passed on to the appropriate group.

typedef struct { group *groups; // dynamically allocated array of structs, defined below int numGroups; // number of groups int arrayLength; // logical length of the full sparsestringarray int groupSize; // number of strings managed by each group } sparsestringarray;

Each group contains a bitmap, which is an array of bool s whose length is equal to the group

size, and a C vector (yes, Assignment 3’s vector ) to store nonempty, dynamically allocated

C strings. Search for a particular element amounts to search within a particular group at

index i. If bitmap[i] is false , then the string at the i th^ position is understood to be the

empty string. If instead bitmap[i] is true , then the group needs to find the corresponding

string in the C vector.

typedef struct { bool *bitmap; // set to be of size 'groupSize' vector strings; // vector of dynamically allocated, nonempty C strings } group;

Each true in a group’s bitmap corresponds to some char * (addressing a dynamically

allocated C string) in the same group’s vector. The true at the lowest index in the bitmap

corresponds to the 0th^ entry in the vector ; the true at the second lowest index in the bitmap

corresponds to the 1st^ entry in the vector , and so forth; the total number of true s should be

equal to the logical length of the accompanying vector. (In practice, the bool array would

be compressed to use just one bit of memory for each Boolean value, but for our purposes

we won’t implement that optimization, since it requires advanced C directives not covered

in CS107.)

Here are the prototypes of the four functions you’ll be implementing:

void SSANew (sparsestringarray *ssa, int arrayLength, int groupSize); bool SSAInsert (sparsestringarray *ssa, int index, const char *str); void SSAMap (sparsestringarray *ssa, SSAMapFunction mapfn, void *auxData); void SSADispose (sparsestringarray *ssa);

Of course, the sparsestringarray gives the illusion that all strings, both empty and nonempty,

are stored in an array-like manner. You know as the implementer the internal representation

is such that only nonempty strings are really stored. Your job is to implement these four

functions in a way that’s consistent with the description outlined on the previous page. Here’s

a test program that illustrates how a client can interact with a sparsestringarray.

static void CountEmptyPrintNonEmpty(int index, const char *str, void auxData) { if (strcmp(str, "") != 0) { printf("Oooo! Nonempty string at index %d: "%s"\n", index, str); } else { ((int *)auxData)++; } }

int main(int argc, char **argv) { sparsestringarray ssa; SparseStringArrayNew(&ssa, 70000, 35); SparseStringArrayInsert(&ssa, 33001, "need"); SparseStringArrayInsert(&ssa, 58291, "more"); SparseStringArrayInsert(&ssa, 33000, "Eye"); SparseStringArrayInsert(&ssa, 33000, "I"); SparseStringArrayInsert(&ssa, 67899, "cowbell"); int numEmptyStrings = 0; SparseStringArrayMap(&ssa, CountEmptyPrintNonEmpty, &numEmptyStrings); printf("%d of the strings were empty strings.\n", numEmptyStrings); SparseStringArrayDispose(&ssa); return 0; }

Here’s the output of that test program:

Oooo! Nonempty string at index 33000: "I" Oooo! Nonempty string at index 33001: "need" Oooo! Nonempty string at index 58291: "more" Oooo! Nonempty string at index 67899: "cowbell" 69996 of the strings were empty strings.

Y e^ l l o w

P i n k

G r e e n

R e^ d

NULL P u^ r^ p^ l e

c) Finally, implement the SSAMap routine, which applies the specified mapping function to

every single index/string pair held by the specified sparsestringarray. Note that the

mapping function is called on behalf of all strings, empty and nonempty. The specified

auxiliary data is channeled through as the third argument to every single call.

  • Function: SSAMap

  • Applies the specified mapping routine to every single index/string pair
  • (along with the specified auxiliary data). Note that the mapping routine
  • is called on behalf of all strings, both empty and nonempty. / typedef void (SSAMapFunction)(int index, const char *str, void *auxData) void SSAMap(sparsestringarray *ssa, SSAMapFunction mapfn, void *auxData);

Problem 2: Serializing Lists of Packed Character Nodes

Write a function serializeList to convert a linked list to a single stream of null-delimited

characters arrays.

The linked list consists of a series of

variably sized nodes, where each node

packs the address of the next node and all

of the characters of a C string all into one

contiguous block.

Notice that each node stores a four-byte pointer,

followed by the individual characters of the string,

followed by the null character (represented as a shaded

box). Each of these four-byte pointers stores the address

of the next node in the list, unless there is no next node, in

which case the four-byte pointer is equal to NULL.

serializeList synthesizes a dynamically allocated serialization of such a list. The

serialization starts off with a sizeof(int)- byte figure storing the number of C strings. The

serialization then continues with each of the C strings laid down side by side, one after

another in their original order. The individual strings are separated by the null characters,

and the final string in the character array is null-terminated as well. If handling the above

list, serializeList would build and return the base address of the int storing the 5 :

serializeList takes a const void * and constructs the corresponding serialization. Your

implementation:

  • should be implemented iteratively in one single pass over the list.
  • should create a serialization using the exact number of bytes needed.

5 R e d Y e^ l l o w P i n k G r e e n P u^ r^ p^ l e

list

  • should not free the nodes of the original list.
  • should be written in straight C, using no C++ whatsoever.
  • should return the base address of the entire figure, expressed as an **int ***.
  • should properly handle the empty list.
  • needn't perform any error checking of any sort.

Relevant function prototypes:

  • *strlen(const char str)

The strlen function returns the number of bytes in str , not including the

terminating null character.

  • **strcpy(char destination, const char source);

The strcpy function copies string source to destination , including the

terminating null character, stopping after the null character has been copied.

int *serializeList(const void *list);

Problem 3: The multitable

The multitable allows a client to associate keys (of any type) with one or more values (of

any type). It operates somewhat like the C++ map class, except that it’s written in C and it

allows multiple values to be bound to a single key.

The multitable shouldn’t re-implement the hashset and the vector , but instead should be

layered on top of them. A single key’s collection of values should be stored in a C vector ,

and each key/ vector - of-values pair will be stored in a C hashset. The pair itself is a

manually managed chunk of memory, the size being determined by the size of the key and

the size of a vector.

I’ve designed the multitable struct for you, but you’ll be implementing three functions to

demonstrate your understanding of all the low-level C functions we’ve been studying.

Here’s the reduced .h file outlining the signatures of those three functions.

typedef int (*MultiTableHashFunction)(const void keyAddr, int numBuckets); typedef int (MultiTableCompareFunction)(const void *keyAddr1, const void keyAddr2); typedef void (MultiTableMapFunction)(void *keyAddr, void *valueAddr, void *auxData); typedef struct { hashset mappings; int keySize; int valueSize; } multitable;

keySize bytes sizeof(vector)^ bytes^ bytes

to see if it already exists (so duplicate values are allowed). And be sure to handle the

situation where the key is being inserted for the very first time (in which case you’re also

introducing a new key/ vector pair.)

  • Function: MultiTableEnter

  • Enters the specified key/value pair into the multitable.
  • Duplicate values are permitted, so there's no need to search
  • existing vectors for a match. You must handle the case where
  • the key is being inserted for the very first time.
  • Understand that the patterns for each key and value are replicated
  • behind the scenes (using memcpy/memmove/VectorAppend as needed). */

void MultiTableEnter(multitable *mt, const void *keyAddr, const void *valueAddr);

c) Finally, implement the MultiTableMap routine. MultiTableMap applies the specified

mapping function to each key/value pair. You’ll certainly need to use HashSetMap to

reach all key/value pairs, but you may iterate over all value vector s using

VectorLength , VectorNth , and a for loop. You will need to write a helper function

and define a helper struct in order to get this to work. (Note that the

MultiTableMapFunction and the HashSetMapFunction are incompatible types.)

  • Function: MultiTableMap

  • Applies the specified MultiTableMapFunction to each key/value pair
  • stored inside the specified multitable. The auxData parameter
  • is ultimately channeled in as the third parameter to every single
  • invocation of the MultiTableMapFunction. Just to be clear, a
  • multitable with seven keys, where each key is associated with
  • three different values, would prompt MultiTableMap to invoke the
  • specified MultiTableMapFunction twenty-one times. */

typedef void (*MultiTableMapFunction)(const void *keyAddr, void *valueAddr, void *auxData);

void MultiTableMap(multitable *mt, MultiTableMapFunction map, void *auxData);

Problem 4: Acting As multitable Client Code

Every post office in America has one: a multitable mapping zip codes to US cities.

Some zip codes (like 08077, I just happen to know) identify multiple cities

(Cinnaminson, NJ; Riverton, NJ; and Palmyra, NJ—small towns don’t need their own

zip code), so a multitable makes sense. This multitable sets aside exactly six bytes

for the zip code keys, since all zip codes can be stored as static, null-terminated

character arrays. But the city names can be arbitrary long, so it’s best to store those as

pointers to dynamically allocated character arrays (also null-terminated, of course).

The multitable that’s relevant to us would be initialized like this (the details of

ZipCodeHash and ZipCodeCompare are irrelevant—just assume they do the right thing):

multitable zipCodeDatabase; MultiTableNew(&zipCodeDatabase, 6 * sizeof(char), sizeof(char *), 100000, ZipCodeHash, ZipCodeCompare);

ListRecordsInRange is designed to map over such a multitable and print all records

whose zip code lies in the specified range. Your job is to complete the

implementation for the InRangePrint mapping function, which reinterprets all of the

void * parameters to be the true types they really are, and then prints the record if

and only if the zip code of the entry is greater than or equal to the low endpoint and

less than or equal to the high endpoint. If the entry falls out of range, then

InRangePrint prints absolutely nothing. I’ve taken care of the variable declarations

and the conditional print, but you should fill the space with the code that properly

initializes the four local variables I declare for you. If you get that right, then the

strcmp and printf calls do what needs to be done.

void ListRecordsInRange(multitable *zipCodes, char *low, char *high) { char *endpoints[] = {low, high}; MultiTableMap(zipCodes, InRangePrint, endpoints); } static void InRangePrint(void *keyAddr, void *valueAddr, void *auxData) { char *zipcode; char *city; char *low; char *high;

if ((strcmp(zipcode, low) >= 0) && (strcmp(zipcode, high) <= 0) printf("%5s: %s\n", zipcode, city); }

include code that properly initializes

the four local variables to be what they

need to be so that the range check and

the printf statement work properly.

c) typedef void (*SSAMapFunction)(int index, const char *str, void *auxData) void SSAMap(sparsestringarray *ssa, SSAMapFunction mapfn, void *auxData) { int index = 0; for (int i = 0; i < ssa->numGroups; i++) { group *grp = &ssa->groups[i]; int groupSize = ssa->groupSize; if (i == ssa->numGroups - 1 && ssa->arrayLength % ssa->groupSize > 0) groupSize = ssa->arrayLength % ssa->groupSize; int indexOfNonEmptyString = 0; for (int j = 0; j < groupSize; j++) { const char *str = ""; if (grp->bitmap[j]) { str = *(char **) VectorNth(&grp->strings, indexOfNonEmptyString); indexOfNonEmptyString++; } mapfn(index, str, auxData); index++; } } }

Solution 2: Serializing Lists of Packed Character Nodes

int *serializeList(const void *list) { int *serialization = malloc(sizeof(int)); int serializationLength = sizeof(int); const void **curr = (const void **) list; int numNodes = 0;

while (curr != NULL) { const char *str = (const char *)(curr + 1); serialization = realloc(serialization, serializationLength + strlen(str) + 1); strcpy((char *) serialization + serializationLength, str); serializationLength += strlen(str) + 1; curr = (const void **) *curr; numNodes++; } *serialization = numNodes; return serialization; }

Solution 3: The C multitable

a)

typedef struct { hashset mappings; int keySize; int valueSize; } multitable; void MultiTableNew(multitable *mt, int keySizeInBytes, int valueSizeInBytes, int numBuckets, MultiTableHashFunction hash, MultiTableCompareFunction compare) { mt->keySize = keySizeInBytes; mt->valueSize = valueSizeInBytes; HashSetNew(&mt->mappings, keySizeInBytes + sizeof(vector), numBuckets, hash, compare, NULL); }

b)

void MultiTableEnter(multitable *mt, const void *keyAddr, const void *valueAddr) { char buffer[mt->keySize + sizeof(vector)]; vector *values; void *found = HashSetLookup(&mt->mappings, keyAddr); if (found == NULL) { memcpy(buffer, keyAddr, mt->keySize); values = (vector *)(buffer + mt->keySize); VectorNew(values, mt->valueSize, NULL, 0); VectorAppend(values, valueAddr); HashSetEnter(&mt->mappings, buffer); } else { values = (vector *)((char *) found + mt->keySize); VectorAppend(values, valueAddr); } }

c)

typedef struct { MultiTableMapFunction map; void *auxData; int keySize; } maphelper;

CS107 Handout 20 Spring 2008 April 28, 2008

Section Handout

Problem 1: The Incredibles (given on a midterm a few years ago)

Consider the following struct definition:

typedef struct { int violet; char *dash[2]; char superboy[4]; } superhero; static superhero **pixar(superhero *syndrome); static superhero *theincredibles(short frozone, superhero elastigirl) { frozone += elastigirl.superboy[frozone]; ((superhero *)((superhero *) elastigirl.dash[0])->dash)->violet = 400; return *pixar(&elastigirl) + 10; }

Generate code for the entire theincredibles function. Be clear about what assembly

code corresponds to what line.

Problem 2: New Zoo Revue (given on a midterm several years ago)

You are to generate code for the following nonsense code. Don't be concerned about

optimizing your instructions or conserving registers. We don't ask that you draw the

activation records, but it can only help you get the correct answer if you do. Be clear

about what assembly code corresponds to each line of C.

struct human { int doug; short emmyjo[2]; }; struct other { char *freddie; struct human charlie; struct human *henrietta; }; static struct human **AskingQuestions(struct human *heroes); static struct human **BeingCalm(short *conformity, struct other gooddeeds) { conformity[conformity] = 0; gooddeeds += ((struct human *) (gooddeeds->henrietta[0].emmyjo))->doug; return AskingQuestions((struct human *) &gooddeeds); }

Generate code for the entire BeingCalm function.

line 1 line 2 line 3

(over)

The assembly code generated by the compilation of AskingQuestions is given below.

Provide a C-code implementation of AskingQuestions , given the constraint that all

local variables must be of type struct human and/or struct human * , and the only

typecast allowed is (struct other *).

SP = SP – 12;

R1 =.2 M[SP + 8];

M[SP + 4] = R1;

R2 = M[SP + 16];

BNE R2, 0, PC + 16;

R3 = M[SP];

R4 = R3 + 8;

M[SP] = R4;

RV = SP + 12;

SP = SP + 12;

RET;

Problem 2: New Zoo Revue (given on a midterm several years ago)

You are to generate code for the following nonsense code. Don't be concerned about

optimizing your instructions or conserving registers. We don't ask that you draw the

activation records, but it can only help you get the correct answer if you do. Be clear

about what assembly code corresponds to each line of C.

struct human { int doug; short emmyjo[2]; }; struct other { char *freddie; struct human charlie; struct human *henrietta; }; static struct human **AskingQuestions(struct human *heroes); static struct human **BeingCalm(short *conformity, struct other gooddeeds) { conformity[conformity] = 0; gooddeeds += ((struct human *) (gooddeeds->henrietta[0].emmyjo))->doug; return AskingQuestions((struct human *) &gooddeeds); }

  • Generate code for the entire BeingCalm function.

// line 1 R1 = M[SP + 4]; // load conformity R2 =.2 M[R1]; // load *conformity R2 = R2 * 2; // manually compute offset from base address R3 = R1 + R2; // manually compute address M[R3] =.2 0; // and write a short 0 there.. // line 2 R1 = M[SP + 8]; // load gooddeeds, remember it R2 = M[R1 + 12]; // load henrietta[0] field R3 = M[R2 + 4]; // load doug field of human struct at emmyjo R4 = R3 * 16; // pointer math on struct other *: quantum is 16 bytes R5 = R1 + R4; // compute new value for gooddeeds M[SP + 8] = R5; // flush back to stack // line 3 R1 = SP + 8; // remember &gooddeeds SP = SP – 4; // make space for param M[SP] = R1; CALL SP = SP + 4; // clean up space RET; // leave RV alone, return

line 1 line 2 line 3

  • The assembly code generated by the compilation of AskingQuestions is given below.

Provide a C-code implementation of AskingQuestions , given the constraint that all

local variables must be of type struct human and/or struct human * , and the only

typecast allowed is (struct other *).

SP = SP – 12;

R1 =.2 M[SP + 8];

M[SP + 4] = R1;

R2 = M[SP + 16];

BNE R2, 0, PC + 16; // potentially jumps to instruction loading RV R3 = M[SP]; R4 = R3 + 8; M[SP] = R4; RV = SP + 12; SP = SP + 12; RET;

Answer

static struct human **AskingQuestions(struct human *heroes) { struct human manners; struct human *remainingCalm; manners.doug = manners.emmyjo[0]; if (heroes == NULL) remainingCalm++; return &remainingCalm + 3; }

The struct human is 8 bytes, and pointers are 4 bytes. The SP = SP – 12 line makes

it clear that there are either two or three local variables—one pointer and one

direct structure, or three pointers. The .2 implies that a short resides at byte

offset 8, so that further requires that the first variable be of type struct human , and

therefore the second variable is a pointer.

char *boy; } couple; vector generateAllCouples(vector *boys, vector *girls) { vector couples; VectorNew(&couples, sizeof(couple), CoupleFree, 0);

Problem 3: packPackets

You’re to write code that traverses a linked list of custom nodes and builds a

dynamically allocated array of bytes large enough to store the meaningful data held by

the linked list. Each node stores one or more packets of raw information, where each

packet is preceded by a two-byte short stating the length (in bytes) of the packet that

follows it. The end of the packet sequence is marked by a two-byte zero, and the four

bytes after that store the address of the next node in the list (or NULL , if the node is the

last in the list). The following node contains three packets of length 20, 10, and 30 bytes,

in that order. The number of bytes making up the entire node is 72.

You’re to write a function called packPackets that, given the address of the first node in

such a list, builds a dynamically allocated byte array where all packets in the linked list

are replicated verbatim, one after another, in the same order they appear in the list. So,

given the following list:

your packPackets function would return the address of the first byte of this dynamically

allocated figure:

Here are some constraints I’m imposing on your implementation.

  • The address passed to packPackets is the address of the first short storing the

number of bytes making up the first packet in the first node.

4 0 NULL

  • Each node alternates between shorts and packets. A two-byte zero marks the end

of the packet sequence in any given node. Every node ends with a four-byte

pointer identifying the location of the next node in the list.

  • You should implement this function iteratively, and your algorithm should

accomplish everything in exactly one traversal. This requires you to call realloc

for each packet you encounter during your one traversal. [Tip: When NULL is

passed as the first argument to realloc , realloc just calls malloc on your behalf.]

This artificial constraint is being imposed so that I can test your understanding of

realloc.

  • For simplicity, you may assume the list contains at least one node, and that each

node contains at least one packet.

  • You needn’t worry about any alignment restrictions at all.
  • You shouldn’t free or modify the original list in any way.

/**

  • Function: packPackets

  • Builds a contiguous array version of the packet list structure according
  • to the explanations provided on the prior page. The parameter passed
  • is of type short *, because the first meaningful piece of information
  • stored in the list is a two-byte short. The return value is of type
  • void *, because the implementation has no type information about the
  • packet data. */

void *packPackets(short *list) {