This simulates ascii sand falling in a grid. Sand is a '.', spaces are just empty space, and '#' is a rock. Rocks don't fall dumbo.
I saw this as an [Easy] challenge on reddit, but all the solutions people were posting used various algorithm libraries and stuff. w/e
sand code:
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
void tick(vector<vector<char>> grid);
void drawgrid(vector<vector<char>> grid);
void setgrid(unsigned int a[]);
void tick(vector<vector<char>> grid)
{
bool movement = false;
for(int i = grid.size() - 1; i >= 0; i--)
{
for(int j = grid[i].size() - 1; j >= 0; j--)
{
if(i < grid.size() -1)
{
if(grid[i+1][j] == ' ' && grid[i][j] == '.')
{
grid[i][j] = ' ';
grid[i+1][j] = '.';
movement = true;
}
}
}
}
if(movement)
{
drawgrid(grid);
}
}
void drawgrid(vector<vector<char>> grid)
{
for(int i = 0; i < grid.size(); i++)
{
for(int j = 0; j < grid[i].size(); j++)
{
cout << grid[i][j];
}
cout << endl;
}
time_t start = time(NULL);
while(true)
{
time_t now = time(NULL);
if(now == start + 1)
{
break;
}
}
for(int i = 0; i < grid[1].size(); i++)
{
cout << "-";
}
cout << endl;
tick(grid);
}
void setgrid(unsigned int a[])
{
srand(time(NULL));
vector<vector<char>> grid (a[0]);
for(int i = 0; i < a[0]; i++)
{
for(int j = 0; j < a[1]; j++)
{
int random = rand();
if(random % 10 == 0)
{
grid[i].push_back('.');
}else if(random % 21 == 0)
{
grid[i].push_back('#');
}else
{
grid[i].push_back(' ');
}
}
}
drawgrid(grid);
}
int main()
{
while(true)
{
unsigned int gridsize[] = {0,0};
string getsize;
try
{
cout << "Enter grid dimensions, x (space) y : ";
if(getline(cin, getsize))
{
for(int i = 0; i <= 1; i++)
{
string temp;
temp = (i == 0) ? getsize.substr(0, getsize.find(' ')) : getsize;
(converttoint(temp) != -1) ? gridsize[i] = converttoint(temp) : throw 0;
getsize.erase(0, getsize.find(' '));
}
cout << "calling setgrid with " << gridsize[0] << "," << gridsize[1] << endl;
setgrid(gridsize);
cout << endl << "--End--" << endl;
break;
}
throw 0;
}
catch(int a)
{
switch(a)
{
case 0:
cout << "input must be a number!" << endl;
cin.clear();
cin.sync();
break;
case 1:
cout << "grid sizes greater than 20 not allowed" << endl;
break;
}
}
}
cin.clear();
cin.sync();
cin.get();
return 0;
}
This isn't really anything special, but I like how it all works and how the errors are handled (actually I took out grid boundaries for now, that's why catch case 1 is redundant right now). If you're wondering what the mystery function converttoint does, it's something I made and put in my own personal header. It's just this:
so useful code:
int converttoint(string a)
{
stringstream ss;
ss << a;
int b;
if(ss >> b)
{
return b;
}else
{
return -1;
}
}
Last edited by Fear; Mar 31, 2014 at 08:46 AM.