Created
May 19, 2011 11:06
-
-
Save arian/980538 to your computer and use it in GitHub Desktop.
Camel and Bananas Puzzle
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
/* | |
puzzle description: | |
There is a desert, one camel and 3000 bananas. | |
The camel has to transport as many bananas 1 km (1000 m). | |
However each meter, the camel eats one banana. | |
Also the camel can only carry 1000 bananas at the same time | |
What is the maximum number of bananas the camel can bring to the other side | |
*/ | |
#include <cstdlib> | |
#include <iostream> | |
#include <math.h> | |
using namespace std; | |
int bananas = 3000, | |
distance = 1000, | |
bpm = 1, | |
carry = 1000; | |
int x[1000]; | |
/* | |
* | |
*/ | |
int main(int argc, char** argv) { | |
x[0] = bananas; | |
for (int i = 0; i < 999; i++){ | |
int times = ceil((x[i] + 0.0) / carry); | |
x[i + 1] = x[i] - (times * 2 - 1); | |
} | |
cout << x[999]; | |
return 0; | |
} |
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
%% puzzle description | |
% | |
% There is a desert, one camel and 3000 bananas. | |
% | |
% The camel has to transport as many bananas 1 km (1000 m). | |
% However each meter, the camel eats one banana. | |
% Also the camel can only carry 1000 bananas at the same time | |
% | |
% What is the maximum number of bananas the camel can bring to the other side? | |
% | |
%% Solve this! | |
bananas = 3000; % number of bananas | |
distance = 1000; % total distance | |
bpm = 1; % bananas per meter | |
carry = 1000; % how many bananas the camel can carry at the time | |
step = 1; % the step size | |
x = zeros(1, distance / step); | |
x(1) = bananas; % put all bananas at x(0) | |
l = length(x); | |
for i = 1:l | |
times = ceil(x(i) / carry); | |
x(i + 1) = x(i) - (times * 2 - 1) * step; | |
end | |
%% Output | |
% display result in the console | |
x(length(x)) % I was told it should be 533, it is 532 though… | |
% plot | |
plot(x); | |
ylabel('Number of bananas'); | |
xlabel('Position (m)') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment