CS106B Assignment1

Foreword

记录2022 winter的CS106B Assignment1

StackOverflow

熟悉栈溢出,观察Cycle是137 164 685 203 327 549

Only Connect

用递归方式去掉元音

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
string onlyConnectize(string phrase) {
if (phrase.length() == 0) {
return "";
} else if (!isalpha(phrase[0])) {
if (phrase.length() == 1) {
return "";
} else {
return onlyConnectize(phrase.substr(1));
}
}
phrase[0] = toUpperCase(phrase[0]);
if (phrase[0] == 'A' || phrase[0] == 'E' || phrase[0] == 'I' || phrase[0] == 'O' || phrase[0] == 'U') {
if (phrase.length() == 1) {
return "";
} else {
return onlyConnectize(phrase.substr(1));
}
}
if (phrase.length() == 1) {
string res = "";
res += phrase[0];
return res;
} else {
string res = "";
res += phrase[0];
res += onlyConnectize(phrase.substr(1));
return res;
}
}

Playing Fair

还是递归小练习,对于负数要抛出异常

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
string aSequenceOfOrder(int n) {
if (n == 0) {
return "A";
} else if (n < 0) {
error("n should be greater than or equal zero.");
return "";
} else {
return aSequenceOfOrder(n - 1) + bSequenceOfOrder(n - 1);
}
return "";
}

string bSequenceOfOrder(int n) {
if (n == 0) {
return "B";
} else if (n < 0) {
error("n should be greater than or equal zero.");
return "";
} else {
return bSequenceOfOrder(n - 1) + aSequenceOfOrder(n - 1);
}
}

Sandpiles

递归练习,模拟丢沙子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const int dx[] = {-1, 1, 0, 0};
const int dy[] = {0, 0, -1, 1};

void dropSandOn(Grid<int>& world, int row, int col) {
if (!world.inBounds(row, col)) {
return;
} else if (world[row][col] <= 2) {
world[row][col] += 1;
return;
} else {
world[row][col] = 0;
for (int i = 0; i < 4; ++i) {
int nrow = row + dx[i], ncol = col + dy[i];
if (!world.inBounds(nrow, ncol)) {
continue;
}
dropSandOn(world, nrow, ncol);
}
return;
}
}

Plotter

模拟绘图仪,熟悉Stanford的库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
void runPlotterScript(istream& input) {
PenStyle style = {1, "black"};
bool is_up = true;
double curx = 0.0, cury = 0.0;
for (string line; getline(input, line); ) {
Vector<string> opt = stringSplit(line, " ");
opt[0] = toUpperCase(opt[0]);
if (startsWith(opt[0], "PEND")) {
is_up = false;
} else if (startsWith(opt[0], "PENU")) {
is_up = true;
} else if (startsWith(opt[0], "MOVEA")) {
if (!is_up) {
drawLine(curx, cury, stringToReal(opt[1]), stringToReal(opt[2]), style);
}
curx = stringToReal(opt[1]), cury = stringToReal(opt[2]);
} else if (startsWith(opt[0], "MOVER")) {
if (!is_up) {
drawLine(curx, cury, curx + stringToReal(opt[1]), cury + stringToReal(opt[2]), style);
}
curx = curx + stringToReal(opt[1]), cury = cury + stringToReal(opt[2]);
} else if (startsWith(opt[0], "PENC")) {
style.color = opt[1];
} else {
style.width = stringToReal(opt[1]);
}
}
}

效果

丢沙子

绘图仪