- Classes
- Fall14 CS31
- Week 5 Classwork
Week 5 Classwork
Int Arrays Equal
#include <iostream>
#include <string>
using namespace std;
bool intArraysEqual(int arr1[], int arr2[], int start, int n) {
// [!] Iterate through all n items starting
// at the start index
for (int i = start; i < n; i++) {
// [!] We can return something whenever we find
// an inconsistency
if (arr1[i] != arr2[i]) {
return false;
}
}
// [!] If we get here, we know there was no
// inconsistency so...
return true;
}
int main () {
int i[] = {1, 2, 3};
int j[] = {0, 2, 3, 4, 5};
cout << intArraysEqual(i, j, 1, 2) << endl;
// Above will print out: 1
// because {2, 3} == {2, 3}
cout << intArraysEqual(i, j, 0, 2) << endl;
// Above will print out: 0
// because {1, 2} != {0, 2}
}
String Array Print
#include <iostream>
#include <string>
using namespace std;
/*
* Takes in an array of strings and some max index
* n, and prints all n strings in the array, comma
* and space separated and enclosed in brackets
*/
void stringArrayPrint (string s[], int n) {
// [!] What should be prepended?
string result = "{";
// Iterate through all n specified indexes
for (int i = 0; i < n; i++) {
// [!] Add the string, its quotes, and any
// comma-space separation
result += "\"" + s[i] + "\", ";
}
// [!] We need to fix something at the end of all this
// (hint, consider n as zero and non-zero)
if (n > 0) {
result = result.substr(0, result.length() - 2);
}
// Tack on the closing bracket
result += "}";
cout << result << endl;
}
int main () {
string s[] = {"print", "me", "NOW"};
stringArrayPrint(s, 3);
// Above will print out:
// {"print", "me", "NOW"}
stringArrayPrint(s, 0);
// Above will print out:
// {}
}
Interleave Strings
#include <iostream>
#include <string>
using namespace std;
/*
* interleaveStrings takes in an array of strings s,
* and a number of strings in that array n, and interleaves
* all characters of each string, producing a string
* as a result.
*/
string interleaveStrings (string s[], int n) {
string result;
bool charsLeft = true;
for (int i = 0; charsLeft; i++) {
charsLeft = false;
for (int j = 0; j < n; j++) {
if (i < s[j].length()) {
result += s[j][i];
charsLeft = true;
}
}
}
return result;
}
int main () {
string s[] = {"AAA", "BB", "CCCC"};
cout << interleaveStrings(s, 3) << endl;
// Above prints out:
// ABCABCACC
string w[] = {"BB", "AAA", "CCCC"};
cout << interleaveStrings(w, 3) << endl;
// Above prints out:
// BACBACACC
string t[] = {"AAA", ""};
cout << interleaveStrings(t, 2) << endl;
// Above prints out:
// AAA
}