public
Created

Sudoku solver in C++11

  • Download Gist
sudoku_solver.cpp
C++
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 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
#include <iterator>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <iostream>
#include <cassert>
#include <memory>
#include <future>
#include <chrono>
 
using namespace std;
 
template<typename T>
struct maybe {
bool valid;
static unsigned created, destroyed;
union {
shared_ptr<T> value;
};
 
maybe() : valid(false) {}
 
maybe(T *_v) : valid(true), value(_v) {}
maybe(const shared_ptr<T>& _v) : valid(true), value(_v) {
++created;
}
 
maybe(const maybe& other) : valid(other.valid),
value(other.value) { ++created; }
operator T& () {
if (valid) return *value;
assert(false);
}
 
~maybe() {
if (valid) {
value.reset();
++destroyed;
}
}
 
bool is_valid() {
return valid;
}
};
 
template<typename T> unsigned maybe<T>::created = 0;
template<typename T> unsigned maybe<T>::destroyed = 0;
 
template<typename E1, typename E2>
auto cross(const vector<E1>& a, const vector<E2>& b) ->
vector<decltype(a[0]+b[0])> {
vector<decltype(a[0]+b[0])> output;
for (auto _a : a) {
for (auto _b : b) {
output.push_back(_a+_b);
}
}
return output;
}
 
vector<string> operator"" _vec(char const* str, size_t N) {
vector<string> output;
for_each(str, str+N, [=, &output] (char c) {
output.push_back(string(1, c));
});
return output;
}
 
vector<string> digits =
{"1", "2", "3", "4", "5", "6", "7", "8", "9"};
 
vector<string> rows =
{"A", "B", "C", "D", "E", "F", "G", "H", "I"};
 
vector<string> cols = digits;
 
vector<string> squares = cross(rows, cols);
vector<vector<string>> unitlist;
 
map<string, vector<vector<string>>> units;
 
map<string, set<string>> peers;
 
typedef map<string, string> value_t;
 
maybe<value_t> eliminate(maybe<value_t> _values, string s, string d);
 
maybe<value_t> assign(maybe<value_t> _values, string s, string d) {
value_t& values = _values;
 
size_t pos = values[s].find(d);
assert(pos != string::npos);
 
string temp = values[s];
temp.replace(pos, 1, "");
string other_values = temp;
 
for (auto const &d2 : other_values) {
if (eliminate(_values, s, string(1, d2)).is_valid() == false)
return maybe<value_t>();
}
 
return _values;
}
 
maybe<value_t> eliminate(maybe<value_t> _values, string s, string d) {
value_t& values = _values;
size_t pos = values[s].find(d);
if (pos == string::npos)
return _values;
 
values[s].replace(pos, 1, "");
 
if (values[s].length() == 0)
return maybe<value_t>();
else if (values[s].length() == 1) {
string d2 = values[s];
for (auto const &s2 : peers[s]) {
if (eliminate(_values, s2, d2).is_valid() == false)
return maybe<value_t>();
}
}
 
for (auto const &u : units[s]) {
vector<string> dplaces;
for (auto const &_s : u) {
if (values[_s].find(d) != string::npos)
dplaces.push_back(_s);
}
if (dplaces.size() == 0)
return maybe<value_t>();
if (dplaces.size() == 1)
if (assign(_values, dplaces[0], d).is_valid() == false)
return maybe<value_t>();
}
 
return _values;
}
 
void display(maybe<value_t> values);
 
maybe<value_t> grid_values(string grid) {
vector<string> chars;
for (auto c : grid) {
if ((string(".0").find(c) != string::npos) ||
(find(digits.begin(), digits.end(), string(1, c)) != digits.end()))
chars.push_back(string(1, c));
}
 
assert(chars.size() == 81);
 
maybe<value_t> output(make_shared<value_t>());
value_t& temp = output;
for (unsigned i=0; i<81; ++i)
temp[squares[i]] = chars[i];
 
return output;
}
 
maybe<value_t> parse_grid(string grid) {
maybe<value_t> _values(make_shared<value_t>());
value_t& values = _values;
 
for (auto s : squares)
values[s] = string("123456789");
 
maybe<value_t> _g = grid_values(grid);
value_t& g = _g;
for (auto _i : g) {
auto s = _i.first, d = _i.second;
if ((string("123456789").find(d) != string::npos) &&
(assign(_values, s, d).is_valid() == false))
return maybe<value_t>();
}
return _values;
}
 
std::string center(const std::string & str, int width) {
int len = (int) str.size();
int marg, left;
 
if (len >= width) return str;
 
marg = width - len;
left = marg / 2 + (marg & width & 1);
 
return std::string(left, ' ') + str + std::string(marg - left, ' ');
}
 
void check(maybe<value_t> _values) {
value_t& values = _values;
for (auto u1 : unitlist) {
string unitvals("");
for (auto u2 : u1) {
unitvals += values[u2];
}
sort(unitvals.begin(), unitvals.end());
assert (unitvals == "123456789");
}
}
 
void display(maybe<value_t> values) {
unsigned width = 3;
if (values.is_valid() == false) {
cout << "Invalid grid\n";
return;
}
value_t& _values = values;
for (auto s : squares)
if (_values[s].length() > width) width = _values[s].length();
string line = string(width*3, '-') + "+" + string(width*3, '-') + "+" + string(width*3, '-');
 
for (auto r : rows) {
for (auto c : cols) {
cout << center(_values[r+c], width) + string((c=="3" || c=="6")?"|":"");
}
cout << "\n";
if (r=="C" || r=="F") cout << line << "\n";
}
}
 
maybe<value_t> search(maybe<value_t> _values) {
if (_values.is_valid() == false)
return maybe<value_t>();
 
value_t& values = _values;
value_t temp;
 
copy_if(values.begin(), values.end(),
inserter(temp, temp.begin()),
[=, &values] (value_t::value_type v) -> bool {
return v.second.length() > 1;
});
if (temp.empty())
return _values;
 
auto min_s = min_element(temp.begin(), temp.end(),
[=, &values] (value_t::value_type v1,
value_t::value_type v2) -> bool {
return v1.second.length() < v2.second.length();
});
 
string s = min_s->first;
 
for (auto const &d : values[s]) {
maybe<value_t> v_copy(make_shared<value_t>(values));
maybe<value_t> retval = search(assign(v_copy, s, string(1, d)));
if (retval.is_valid()) return retval;
}
return maybe<value_t>();
}
 
int main(int argc, char* argv[])
{
assert (argc == 2);
 
for (auto _c : cols) {
vector<string> c = {_c};
unitlist.push_back(cross(rows, c));
}
 
for (auto _r : rows) {
vector<string> r = {_r};
unitlist.push_back(cross(r, cols));
}
 
for (vector<string> rs : {"ABC"_vec, "DEF"_vec, "GHI"_vec}) {
for (vector<string> cs : {"123"_vec, "456"_vec, "789"_vec}) {
unitlist.push_back(cross(rs, cs));
}
}
 
for (string s : squares) {
for (vector<string> u : unitlist) {
if (find(u.begin(), u.end(), s) != u.end())
units[s].push_back(u);
}
}
 
for (auto s : squares) {
vector<string> temp =
accumulate(units[s].begin(), units[s].end(), vector<string>(),
[=](const vector<string>& a1, const vector<string>& a2) ->
vector<string> {
vector<string> ret;
for (auto e : a1) ret.push_back(e);
for (auto e : a2) ret.push_back(e);
return ret;
});
 
set<string>& output = peers[s];
copy_if(temp.begin(), temp.end(), inserter(output, output.end()),
[=] (string t) { return !(t == s); });
}
string grid(argv[1]);
 
auto start = chrono::high_resolution_clock::now();
maybe<value_t> ans = search(parse_grid(grid));
auto end = chrono::high_resolution_clock::now();
auto elapsed = chrono::duration_cast<chrono::microseconds>(end-start).count();
cout << elapsed << " us\n";
display(ans);
 
check(ans);
return 0;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.