|
CS256 - Fundamentals of Structured Programming
|
Displaying ./code/functions/curses-rnd.c
#include <stdio.h>
#include <curses.h>
#include <stdlib.h>
#include <time.h>
#include <sys/types.h>
#include <unistd.h>
#define NUMS 100
/**
* Returns a random integer between 'a' and 'b' (inclusive)
*/
int R(int a, int b)
{
int diff = (a < b? b-a : a-b)+1;
int min = a < b? a : b;
return min + (rand()%diff);
}
void print_index(int i)
{
char buf[5];
sprintf(buf, "%d", i);
int y = LINES-3;
for(int p = 0; buf[p] != '\0'; p++) {
mvaddch(y, i, buf[p]);
y++;
}
}
void line(int col, int n)
{
int y = LINES-5;
for(int i=0; i < n; i++) {
attron(COLOR_PAIR((col%6)+1));
mvaddch(y, col, ' ');
y--;
}
}
int main(void)
{
initscr();
start_color();
init_pair(1, COLOR_BLACK, COLOR_RED);
init_pair(2, COLOR_BLACK, COLOR_GREEN);
init_pair(3, COLOR_BLACK, COLOR_BLUE);
init_pair(4, COLOR_BLACK, COLOR_YELLOW);
init_pair(5, COLOR_BLACK, COLOR_CYAN);
init_pair(6, COLOR_BLACK, COLOR_MAGENTA);
int n[NUMS];
srand(time(0)+getpid());
for(int i=0; i < NUMS; i++) n[i] = 0;
for(int i=0; i < 1000; i++) {
int idx = R(0,(NUMS-1)/2) + R(0,(NUMS-1)/2);
n[idx]++;
}
for(int i=0; i < NUMS; i++) {
print_index(i);
line(i, n[i]);
attrset(A_NORMAL);
}
mvprintw(LINES-1,0,"Press any key to quit.");
refresh();
getch();
endwin();
return 0;
}
|