3.8 KiB
id | title | date | author | layout | guid | permalink | categories | tags | ||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
207 | The Buridan’s donkey paradox | 2015-09-20T10:34:36+00:00 | pesceWanda | post | http://francescomecca.eu/?p=207 | /index.php/archives/207 |
|
|
The Buridan’s donkey is an illustration of a paradox regarding the philosophy of moral determinism and free will.
The paradox shows an hypothetical situation in which a donkey searching for food is caught in the middle of two equally appealing stacks of hay located at the same distance from the donkey. Because the donkey has no real reason to choose one over the other he dies of starvation.
I have decided to write a cli program that chooses for me when I can’t make up my mind.
The program is written in C++ and when invoked along with two or more arguments it puts them in a vector and then changes the order randomly.
{% highlight c %} #include #include #include #include #include #include <sys/poll.h> using namespace std;
struct pollfd stdin_poll = { .fd = fileno (stdin), .events = POLLIN };
void read_from_piped_input (vector& lst) { string x; while (getline (cin, x)) { lst.push_back (x); } }
void read_from_arguments (const int& argc, char* argv[], vector& lst) { if (argc == 1) { cout << "Usage: asino [string] [string] ..." << endl; exit; } for (vector::size_type i = 1; i < argc; ++i) { lst.push_back (argv[i]); } }
int main (int argc, char* argv[]) { vector lst; int poll_ret = poll (&stdin_poll, 1, 0); if (poll_ret > 0) { read_from_piped_input (lst); } else { read_from_arguments (argc, argv, lst); }
random_device rd;
mt19937 m(rd());
shuffle (lst.begin (), lst.end (), m);
int i = 1;
for (vector<string>::iterator it = lst.begin (); it != lst.end (); ++it) {
cout << i++ << ". " << *it << endl;
}
} {% endhighlight %}
I have used the Mersenne Twister PRNG just to give it a try.
One of the challenges was to read from stdin instead of arguments when the program is piped after another program in the shell:
{% highlight sh %} ls /media/my_movies/ | buridan {% endhighlight %}So I have used poll() that checks for a specified amount of time if the selected device (/dev/stdin in my case) can perform I/O operations; in my code:
{% highlight bash %} poll (&stdin_poll, 1, 0) {% endhighlight %}
I selected the POLLIN as event so poll() only checks if there is data to read, 1 as the number of items in the fds array, 0 milliseconds of timeout because when the program is invoked /dev/stdin may already contain input.
The program should be compiled this way:
{% highlight bash %} g++ -std=c++11 ./program.cpp -o output {% endhighlight %}
You are free to reuse this little piece of code as you wish.
EDIT: 02-04-2016 The original idea for the Buridan's donkey came from my mentor Simone Basso who wrote the original one in haskell.
Francesco Mecca