Created
October 29, 2018 06:27
-
-
Save yanhsiah/95ac88820bdbe87bfeda501e0c87401b to your computer and use it in GitHub Desktop.
Rearrange balls
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
vector<string> rearrange(vector<int>& baskets); | |
// [ 2 , 1 , 4 , 5 , 3 , empty_basket ] | |
vector<int> baskets = {2,1,4,5,3,0}; | |
vector<string> commands = rearrange(baskets); | |
for (string command : commands) { | |
cout << command << endl; | |
} | |
/* | |
move 2 to [5] | |
move 1 to [0] | |
move 2 to [1] | |
move 4 to [5] | |
move 3 to [2] | |
move 5 to [4] | |
move 4 to [3] | |
*/ | |
vector<string> rearrange(vector<int>& baskets) { | |
vector<string> commands; | |
int i = 0, last = (int)baskets.size() - 1, empty = last, done = 0; | |
while (done < (int)baskets.size() - 1) { | |
// 1. if empty is at the last, find any ball in a wrong basket and move it to empty (swap it with the empty) | |
// 2. if empty is not the last, move the correct ball (empty+1) to the current empty basket (swap it with the empty) | |
if ((empty == last && baskets[i] != i + 1) || | |
(empty != last && baskets[i] == empty + 1)) { | |
// swap brackets[i], brackets[empty] | |
commands.push_back("move " + to_string(baskets[i]) + " to [" + to_string(empty) + "]"); | |
baskets[empty] = baskets[i]; | |
baskets[i] = 0; | |
// check if empty is filled correctly | |
if (baskets[empty] == empty + 1) { | |
done++; | |
} | |
empty = i; | |
} | |
i = (i + 1) % (int)baskets.size(); | |
} | |
return commands; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment