Skip to content

Instantly share code, notes, and snippets.

@dgodfrey206
Last active March 26, 2022 16:41
Show Gist options
  • Save dgodfrey206/f76f4a7c6baaf0d0dfd0 to your computer and use it in GitHub Desktop.
Save dgodfrey206/f76f4a7c6baaf0d0dfd0 to your computer and use it in GitHub Desktop.
HackerRank
#include <string>
#include <iostream>
#include <initializer_list>
enum struct Color {
red,blue,orange,purple,green,black,yellow,invalid=-1
};
Color FromStringToColor(std::string const& str) {
return ((str == "red") ? Color::red :
(str == "blue") ? Color::blue :
(str == "orange") ? Color::orange :
(str == "purple") ? Color::purple :
(str == "green") ? Color::green :
(str == "black") ? Color::black :
(str == "yellow") ? Color::yellow : Color::invalid);
}
struct ColorNode {
std::string color;
ColorNode* next = nullptr;
};
ColorNode** TailOf(ColorNode** n)
{
while (n[0]) n = &n[0]->next;
return n;
}
void Push(ColorNode*& n, std::string value)
{
*TailOf(&n) = new ColorNode{value};
}
void Push(ColorNode*& n, std::initializer_list<std::string> v)
{
ColorNode** tail = TailOf(&n);
for (auto& c : v)
{
*tail = new ColorNode{c};
tail = &(*tail)->next;
}
}
ColorNode* PrioritizeColors(ColorNode* a, ColorNode* b) {
ColorNode* temp = nullptr;
while (a && b) {
Color colorA = FromStringToColor(a->color);
Color colorB = FromStringToColor(b->color);
if (colorA == Color::invalid || colorB == Color::invalid) {
return temp;
}
if (colorA == colorB) {
Push(temp, { a->color, b->color });
a = a->next;
b = b->next;
} else if (colorA < colorB) {
Push(temp, a->color);
a = a->next;
} else {
Push(temp, b->color);
b = b->next;
}
}
while (b) {
Push(temp, b->color);
b = b->next;
}
while (a) {
Push(temp, a->color);
a = a->next;
}
return temp;
}
int main() {
ColorNode* a = nullptr, *b = nullptr;
Push(a, {"red", "red", "orange", "green", "black"});
Push(b, {"red", "blue", "purple", "green", "yellow"});
ColorNode* c = PrioritizeColors(a, b);
while (c) {
std::cout << c->color << " ";
c = c->next;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment