/
ch-2.cpp
128 lines (104 loc) · 2.5 KB
/
ch-2.cpp
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
/*
Challenge 242
Task 2: Flip Matrix
Submitted by: Mohammad S Anwar
You are given n x n binary matrix.
Write a script to flip the given matrix as below.
1 1 0
0 1 1
0 0 1
a) Reverse each row
0 1 1
1 1 0
1 0 0
b) Invert each member
1 0 0
0 0 1
0 1 1
Example 1
Input: @matrix = ([1, 1, 0], [1, 0, 1], [0, 0, 0])
Output: ([1, 0, 0], [0, 1, 0], [1, 1, 1])
Example 2
Input: @matrix = ([1, 1, 0, 0], [1, 0, 0, 1], [0, 1, 1, 1], [1, 0, 1, 0])
Output: ([1, 1, 0, 0], [0, 1, 1, 0], [0, 0, 0, 1], [1, 0, 1, 0])
*/
#include <algorithm>
#include <iostream>
#include <regex>
#include <string>
#include <vector>
using namespace std;
vector<string> regex_split(const string& s, const regex& sep_regex = regex{ "\\s+" }) {
sregex_token_iterator iter(s.begin(), s.end(), sep_regex, -1);
sregex_token_iterator end;
return { iter, end };
}
vector<int> parse_list(const string& text) {
vector<int> result;
auto nums = regex_split(text, regex{ "[\\[\\](),; \\t]+" });
for (auto& num : nums) {
if (!num.empty()) {
int n = stoi(num);
result.push_back(n);
}
}
return result;
}
vector<vector<int>> parse_matrix(const string& text) {
vector<vector<int>> matrix;
auto rows_text = regex_split(text, regex("\\],"));
for (auto& row_text : rows_text) {
auto row = parse_list(row_text);
matrix.push_back(row);
}
return matrix;
}
void process_matrix(vector<vector<int>>& matrix) {
for (auto& row : matrix) {
// a) Reverse each row
reverse(row.begin(), row.end());
// b) Invert each member
for (auto& n : row)
n = 1 - n;
}
}
void print_list(const vector<int>& arr) {
cout << "[";
string sep = "";
for (auto& n : arr) {
cout << sep << n;
sep = ", ";
}
cout << "]";
}
void print_matrix(vector<vector<int>>& matrix) {
cout << "(";
string sep = "";
for (auto& row : matrix) {
cout << sep;
print_list(row);
sep = ", ";
}
cout << ")";
}
int main(int argc, char* argv[]) {
if (argc != 2) {
cerr << "Usage: ch-2 '([a, b, c], [d, e, f], [g, h, i])'" << endl;
exit(EXIT_FAILURE);
}
auto matrix = parse_matrix(argv[1]);
process_matrix(matrix);
print_matrix(matrix);
#if 0
free_matrix(matrix);
utarray_free(matrix);
#endif
}
#if 0
void free_matrix(UT_array* matrix) {
for (UT_array** p = NULL; (p = utarray_next(matrix, p)) != NULL; ) {
utarray_free(*p);
*p = NULL;
}
}
#endif