Skip to content

Instantly share code, notes, and snippets.

@lsem
Created March 30, 2024 21:54
Show Gist options
  • Save lsem/a7a391da20389fdc5ae6efe5ca8b9f6b to your computer and use it in GitHub Desktop.
Save lsem/a7a391da20389fdc5ae6efe5ca8b9f6b to your computer and use it in GitHub Desktop.
user_friendly_hash.cpp
#include <algorithm>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
using namespace std;
unsigned long long shash(const string& s) {
const unsigned long long P = 131;
const unsigned long long M = 1000000007;
const long long N = s.size();
unsigned long long h = 0;
unsigned long long p = 1;
for (size_t i = 0; i < s.size(); ++i) {
const char c = s[N - i - 1];
h = (h + (c * p)) % M;
p = (p * P) % M;
}
return h % M;
}
unsigned long long shash_minus_1(const string& s) {
const unsigned long long P = 131;
const unsigned long long M = 1000000007;
const long long N = s.size();
unsigned long long h = 0;
unsigned long long p = 1;
for (size_t i = 0; i < s.size(); ++i) {
const char c = s[N - i - 1];
h = (h + (c * p)) % M;
p = (p * P) % M;
}
return h % M;
}
long long remainder(long long a, long long b)
{
return a - (a / b) * b;
}
vector<int> authEvents(vector<vector<string>> events) {
vector<int> results;
unsigned long long current_password_hash = 0;
unsigned long long current_nice_hash = 0;
for (auto& event : events) {
auto& cmd = event[0];
if (cmd == "setPassword") {
current_password_hash = shash(event[1]);
current_nice_hash = remainder(shash(event[1] + "X") - 'X', 1000000007);
// std::cout << "new hash: " << current_password_hash << "\n";
// std::cout << "new nice hash: " << current_nice_hash << "\n";
} else if (cmd == "authorize") {
auto h = std::stoi(event[1]);
std::cout << "authorize " << h << "\n";
if (h == current_password_hash) {
results.push_back(1);
} else {
bool found = false;
for (size_t i = 0; i <= 255; ++i) {
if ((h - i) == current_nice_hash) {
found = true;
break;
}
}
if (found) {
results.push_back(1);
} else {
results.push_back(0);
}
}
}
}
return results;
}
int main() {
vector<vector<string>> events = {
{"setPassword", "cAr1"},
{"authorize", "223691457"},
{"authorize", "303580761"},
{"authorize", "100"},
{"setPassword", "d"},
{"authorize", "100"},
{"authorize", "101"},
};
for (auto a : authEvents(events)) {
cout << a << "\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment