Skip to content

Instantly share code, notes, and snippets.

@mizuhara
Created October 27, 2015 13:15
Show Gist options
  • Save mizuhara/08a2bed33e3f8a405214 to your computer and use it in GitHub Desktop.
Save mizuhara/08a2bed33e3f8a405214 to your computer and use it in GitHub Desktop.
#include <vector>
#include <string>
#include <numeric>
#include <iostream>
#include <algorithm>
constexpr size_t CHAIR_COUNTS = 8;
constexpr size_t OCCUPIED_STATE = 3;
void wait(std::vector<int>& chairs, size_t customer)
{
for(size_t i = 0; i < chairs.size(); ++i)
{
chairs[i] = std::max(0, chairs[i] - 1);
}
const size_t vacant_chairs = std::count_if(chairs.begin(), chairs.end(), [&](int chair) { return chair == 0; });
if(vacant_chairs < customer)
{
wait(chairs, customer);
}
}
size_t chair_to_sit(const std::vector<int>& chairs, size_t customer)
{
for(size_t i = 0; i < CHAIR_COUNTS; ++i)
{
std::vector<size_t> indeces;
for(size_t j = i; j < i + customer; ++j)
{
indeces.push_back(j % CHAIR_COUNTS);
}
const auto found = std::all_of(indeces.begin(), indeces.end(), [&](int idx) { return chairs[idx] == 0; });
if(found)
{
return i;
}
}
return CHAIR_COUNTS;
}
void sit(std::vector<int>& chairs, size_t customer)
{
size_t from = chair_to_sit(chairs, customer);
while(0 < customer)
{
if(CHAIR_COUNTS <= from)
{
from = 0;
}
chairs[from] = OCCUPIED_STATE;
++from;
--customer;
}
}
std::string to_bit_string(const std::vector<int>& chairs)
{
return std::accumulate(
chairs.begin(), chairs.end(), std::string {},
[&](const std::string& s, int chair) { return s + (chair == 0 ? "0" : "1"); });
}
std::string solve(const std::string& customers)
{
std::vector<int> chairs(CHAIR_COUNTS, 0);
for(size_t i = 0; i < customers.size(); ++i)
{
const auto n = customers[i] - '0';
wait(chairs, n);
sit(chairs, n);
}
return to_bit_string(chairs);
}
void test(const std::string& input, const std::string& expected)
{
const auto actual = solve(input);
std::cout << ( actual == expected ? "OK" : "***NG***" ) << std::endl;
}
void test_all()
{
test("3316", "11111110");
test("3342153", "11111111");
test("8", "11111111");
test("232624", "11110110");
test("1", "10000000");
test("224673432", "11111000");
test("123464334", "11111110");
test("44372332", "11111111");
test("2344", "11111111");
test("6448476233", "11111100");
test("4345174644", "11111111");
test("77743", "11111110");
test("2136524281", "10000000");
test("344373", "11100000");
test("434226", "11111111");
test("7433223", "11111110");
test("2246534", "11110111");
test("634", "11111110");
test("2222", "11111100");
test("2442343238", "11111111");
test("7243344", "11111111");
test("26147234", "10111111");
test("34424", "10011111");
test("6334", "11011111");
test("3828342", "11011110");
test("4431", "11110000");
test("2843212125", "11111111");
test("333336482", "11000000");
test("374", "11110000");
test("4382333", "11100111");
}
int main()
{
test_all();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment