Skip to content

Instantly share code, notes, and snippets.

@dillmo
Created April 4, 2014 14:39
Show Gist options
  • Save dillmo/9976038 to your computer and use it in GitHub Desktop.
Save dillmo/9976038 to your computer and use it in GitHub Desktop.
Solution to the Dwarves and Coins problem
/* Dwarves and Coins Solution by Dillon Morse
* ------------------------------------------
* Several (M) dwarves have found a goblin's chest with N gold coins and have
* to divide them. Due to ancient rules governing the allocation of loot to
* pirates in order of seniority, the oldest dwarf should get one coin more
* than the next oldest dwarf, and so on, so that the youngest dwarf gets M-1
* fewer coins than the oldest dwarf. Additionally, no dwarf has to pitch in
* any coins (ie no negative coins to any dwarfs)
*
* Help the dwarves to divide the coins in this way, or tell them that this is
* impossible.
*
* Input
* -----
* You are given an integer N (3 <= N <= 1000) for number of coins and an integer
* M (3 <= M <= N) for number of dwarves, space-separated.
*
* Output
* ------
* If it is impossible to divide the coins in the way that dwarves want, print
* -1 (minus one). Otherwise, print the numbers of coins that each dwarf will
* receive, from oldest to youngest. Separate the numbers with spaces.
*/
#include <iostream>
#include <vector>
using namespace std;
int main() {
int dwarves, coins, i, total, run;
vector<int> result;
cout << "Input:\n";
cin >> coins >> dwarves;
run = 0;
do {
run += 1;
total = 0;
for( i = dwarves + run - 2; i >= run - 1; i-- ) {
total += i;
}
} while( total < coins );
if( total == coins ) {
for( i = dwarves + run - 2; i >= run - 1; i-- ) {
result.push_back( i );
}
}
else result.push_back( -1 );
cout << "\nOutput:\n";
for( i = 0; i < result.size(); i++ ) {
cout << result[i] << " ";
}
cout << '\n';
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment