Skip to content

Instantly share code, notes, and snippets.

@DanielDe
Created December 1, 2012 22:07
Show Gist options
  • Save DanielDe/4185491 to your computer and use it in GitHub Desktop.
Save DanielDe/4185491 to your computer and use it in GitHub Desktop.
Week 9 Lab Exercise Solutions
#include <iostream>
#include <vector>
using namespace std;
void remove(vector<int>&, int);
void print(const vector<int>&);
int main() {
vector<int> v;
v.push_back(3);
v.push_back(1);
v.push_back(4);
v.push_back(1);
v.push_back(5);
v.push_back(9);
cout << "Before: ";
print(v);
cout << endl << "Remove element at index: ";
int index = 0;
cin >> index;
remove(v, index);
cout << "After: ";
print(v);
cout << endl;
return 0;
}
void remove(vector<int> & v, int index) {
int temp = 0;
for (int i = index; i < v.size() - 1; ++i) {
temp = v.at(i);
v.at(i) = v.at(i + 1);
v.at(i + 1) = temp;
}
v.pop_back();
}
void print(const vector<int> & v) {
for (int i = 0; i < v.size(); ++i)
cout << v.at(i) << " ";
}
#include <iostream>
#include <vector>
using namespace std;
void print_freq(vector<int> & v) {
for (int i = 0; i < v.size(); ++i)
cout << i + 1 << ": " << v[i] << endl;
}
int main() {
vector<int> freq(10, 0);
int next = 0;
while (cin >> next) {
freq.at(next - 1) = freq.at(next - 1) + 1;
}
print_freq(freq);
return 0;
}
#include <iostream>
#include <vector>
using namespace std;
void print_board(const vector< vector<char> > &);
int main() {
vector< vector<char> > outer;
vector<char> inner(8, '-');
for (int i = 0; i < 8; ++i)
outer.push_back(inner);
// initialize starting chess positions
outer.at(0).at(0) = 'R';
outer.at(0).at(1) = 'H';
outer.at(0).at(2) = 'B';
outer.at(0).at(3) = 'Q';
outer.at(0).at(4) = 'K';
outer.at(0).at(5) = 'B';
outer.at(0).at(6) = 'H';
outer.at(0).at(7) = 'R';
outer.at(7).at(0) = 'R';
outer.at(7).at(1) = 'H';
outer.at(7).at(2) = 'B';
outer.at(7).at(3) = 'Q';
outer.at(7).at(4) = 'K';
outer.at(7).at(5) = 'B';
outer.at(7).at(6) = 'H';
outer.at(7).at(7) = 'R';
for (int i = 0; i < 8; ++i) {
outer.at(1).at(i) = 'P';
outer.at(6).at(i) = 'P';
}
// run the game infinitely, ctrl-c to stop
int x1, y1, x2, y2;
while (true) {
print_board(outer);
cout << "Move piece from location: ";
cin >> x1 >> y1;
cout << "To location: ";
cin >> x2 >> y2;
outer.at(outer.size() - y2 - 1).at(x2) = outer.at(outer.size() - y1 - 1).at(x1);
outer.at(outer.size() - y1 - 1).at(x1) = '-';
}
return 0;
}
void print_board(const vector< vector<char> > & board) {
for (int i = 0; i < board.size(); ++i) {
for (int j = 0; j < board.at(i).size(); ++j) {
cout << board.at(i).at(j) << " ";
}
cout << endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment