Preface
This lab is going to be a little more abstract and follow up on the lecture ideas on invariants specifically. This will be the main focus of today’s lab.
The main flow would be to hopefully get you to recognise invariants of existing loops, then come up with invariants on your own before writing your own code.
Spot The Invariant
For each of the parts, look at the code snippet below, and try to think about what invariant we might use to try to reason about the correctness of the program. Recall that this means:
- Coming up with properties that do not change throughout the iteration.
- See that it holds true before any iterations.
- See that it holds true between all iterations.
- See that it holds true after the last iteration.
Remember, the statement has to intuitively help you show progress and reason about the behaviour of the program. Yes this is quite abstract and there are no hard and fast rules (we will use this as an informal problem solving tool).
Part 1:
Program goal: Find maximum value of the entire int array arr of length len.
int max_so_far = arr[0];
for(size_t idx = 1; idx < len; ++idx){
max_so_far = (max_so_far > arr[idx]) ? max_so_far : arr[idx];
}
// by this point in the code
// max_so_far should have the maximum possible value of the arrayPart 2:
Program goal: Given a string str, return a heap-allocated string that is a copy of str with the first word removed. The heap-allocated string can be as large as the original string.
A word is defined as a contiguous sequence of non-space characters. The string may start with spaces and end with spaces.
If there is no word, return a copy of the string, including when it is empty.
Return nullptr if allocation fails.
Note: You should probably think about having 3 separate invariants for the 3 loops.
Example Input:
The quick brown fox jumps over the lazy dog.
Respective Output:
quick brown fox jumps over the lazy dog.
Note exactly 3 characters were deleted, and everything else was maintained and left as-is.
char *remove_first_word(char const *str){
size_t len = strlen(str);
char *output = calloc(len + 1, sizeof(char));
if(output == nullptr){
return nullptr;
}
char const *p = str;
char *q = output;
while(*p && *p == ' '){
*q++ = *p++;
}
while(*p && *p != ' '){
p++;
}
while(*p){
*q++ = *p++;
}
return output;
}Hint
Your statement needs to talk about both
pandq.
Part 3:
Program goal: Given a null-terminated string str that comprises numerical characters and whitespace, return a heap-allocated array that corresponds to all the elements within the array.
For example, the string:
123 456 1 0 21
should be parsed into an array of size 5 with elements {123, 456, 1, 0, 21}.
#include <ctype.h>
#include <stdlib.h>
char const *next_non_space(char const *s){
while(*s && isspace(*s)){
++s;
}
return s;
}
int *into_arr(char const *str, size_t *n){
size_t num_integers = 0;
for(char const *p = str; *p; ++p){
num_integers += (isdigit(*p) && !isdigit(*(p + 1)));
}
*n = num_integers;
if(*n == 0){
return nullptr;
}
int *arr = calloc(num_integers, sizeof(int));
char const *start = next_non_space(str);
char *end;
for(size_t idx = 0; idx < num_integers; ++idx){
arr[idx] = strtol(start, &end, 10);
start = next_non_space(end);
}
return arr;
}Set the size_t pointed at by n to the number of elements in the array.
Try to spot the invariants here. Importantly, how is start being maintained to make sure our program is correct?
Part 4:
Program goal: Given two sorted integer arrays left, right each of integers. Merge them into an array of size so that the resulting array is also sorted.
You are guaranteed that output has capacity for at least integers and does not overlap either input array. The value is representable as a size_t.
void merge(int left[], int right[], int output[], size_t n){
size_t output_idx = 0;
size_t left_idx = 0, right_idx = 0;
while(output_idx < 2 * n){
if(left_idx < n && right_idx < n){
// What are we guaranteed at this point?
if(left[left_idx] <= right[right_idx]){
output[output_idx++] = left[left_idx++];
} else {
output[output_idx++] = right[right_idx++];
}
} else if(left_idx == n){
// What are we guaranteed at this point?
output[output_idx++] = right[right_idx++];
} else {
// What are we guaranteed at this point?
output[output_idx++] = left[left_idx++];
}
// Point A
}
}Hint
Think about how this relates the elements from
leftandrightvs the elements inoutput.
Problem Solving (with Invariants)
Get the Lab 9 code through Entainer and the cs1010 helper.
Work in problem-solving-1/, problem-solving-2/, and problem-solving-3/ respectively.
Implement each function in student.c; its declaration is in student.h.
main.c handles input and output.
Run make and then ./main inside the activity directory.
The starters compile, but their placeholder results are not solutions.
Each input line may contain at most 4095 characters.
Last week we wrote simple loops to loop over simpler ideas. This week we will start trying to write loop for more involved things.
Here’s the recommended flow:
- Plan before you write. Try to figure out how to make the loop progress towards the solution. This will most likely come in the form of an invariant.
- Decide based on that information, what you should iterate on, what should the termination condition, what should be in the loop body.
Problem Solving Practice 1
Task: You are given an array of integers. Output the index such that all the elements of are all the elements of . Both partitions must be nonempty: .
Return any valid index, or if none exists, including when .
Implement long partition_index(int const arr[], size_t n).
Enter the array elements on one line (at most 256 integers); an empty line represents an empty array.
The program prints the returned index.
Problem Solving Practice 2
Task: Given a string str. Count and return the number of words in the string. A word is defined as a contiguous sequence of non-space characters. The string may start with spaces and end with spaces.
Example:
The quick brown fox jumps over the lazy dog.
Output: 9
Implement size_t count_words(char const *str).
Enter one line; the program prints the returned count.
Here, a space means the character ' '.
Problem Solving Practice 3
Task: Given a mutable string str and a nonempty string needle,
repeatedly delete the leftmost occurrence of needle from str.
After each deletion, restart the search from the beginning of str,
until no more occurrences remain.
Modify str in place, shifting the remaining characters, including the null terminator,
to close each gap.
You may assume that needle does not overlap str.
Implement void remove_occurrences(char *str, char const *needle).
Enter str and then needle on separate lines; the program prints the modified string.
Example 1:
str: "ababa"
needle: "aba"
Result 1:
str: "ba"
Example 2:
str: "abababa"
needle: "aba"
Result 2:
str: "b"