This preview shows page 1. Sign up to view the full content.
Unformatted text preview: e, 0, NULL);
return csv;
}
/* Function: CSVSetNth
* Usage: CSVSetNth(csv, 22, &val);
* * Sets the given value at the index, replacing any previous
* value. The new value is copied from the memory pointed to
* by valueAddr. !Valid indexes are [0, maxIndex]; an error
* is raised if index is out of bounds.
*/
void CSVSetNth(CSparseVector *csv, int index, void *valueAddr) Problem 3: Numbers and bits
a) The CS106 RandomInteger function returns a value randomly chosen from the range
[low, high]. It is implemented on top of the C stdlib function r and that returns an
unsigned int in the range [0, RAND_MAX]. R AND_MAX is equal to U INT_MAX , i.e. the
largest representable unsigned int. RandomInteger is designed to map the result from
rand onto the desired range. The code is shown below.
int RandomInteger(int low, int high)
{
double d = rand() / ((double) RAND_MAX + 1); // map onto [0, 1)
int k = (int) (d * (high  low + 1));
// scale/truncate
return (low + k);
// translate
} The first line maps the rand result onto the range [0, 1) as a double. Would this code
work equally well using float instead of double? Explain why or why not.
The above function has been used by thousands of students for over 15 years. Imagine
my surprise when a student recently showed me that it did not work correctly for very –4–
large ranges. Trace the operation of RandomInteger(0, INT_MAX). What is returned?
Describe how to change the code to make...
View Full
Document
 Winter '08
 Cain,G

Click to edit the document details