this post was submitted on 04 Aug 2023
5 points (100.0% liked)

C Programming Language

993 readers
1 users here now

Welcome to the C community!

C is quirky, flawed, and an enormous success.
... When I read commentary about suggestions for where C should go, I often think back and give thanks that it wasn't developed under the advice of a worldwide crowd.
... The only way to learn a new programming language is by writing programs in it.

ยฉ Dennis Ritchie

๐ŸŒ https://en.cppreference.com/w/c

founded 1 year ago
MODERATORS
 

Hi guys, I'm writing a program using the pbm "P1" format to create a random bitmap. The '1' char represents a black pixel and the '0' char represents a white pixel. All that has to be done to use this format is to basically "draw" the image in a file using this system. I just want to make a char matrix and randomly put black pixels until I hit a maximum percentage of black pixels which I don't want to exceed. Then I print that matrix to a file.

What I don't understand is that even if I decrease the value of PERCENTAGE, recompile, and execute the program, there is no noticeable difference, in fact I suspect it's the same image, although I can't be sure.

#include
#include

#define WIDTH 400 #define HEIGHT 250 #define TOTAL_PIXELS (WIDTH * HEIGHT) #define PERCENTAGE 0.01 #define BLACK_PIXEL '1' #define WHITE_PIXEL '0'

` int randomBrackets(int n){ return rand()/((RAND_MAX/n) + 1); }

int main(){
	
	char pbm_matrix[WIDTH][HEIGHT];
	for(int i = 0; i < HEIGHT; i++){
		for(int j = 0; j < WIDTH; j++){
			pbm_matrix[i][j] = WHITE_PIXEL;
		}
	}
	int total_black_pixels = 0;
	while((double)(total_black_pixels/TOTAL_PIXELS) < PERCENTAGE){
		int x = randomBrackets(WIDTH);
		int y = randomBrackets(HEIGHT);
		pbm_matrix[x][y] = BLACK_PIXEL;
		total_black_pixels++;
	}

	FILE* img_ref = fopen("bitmap1.pbm", "w");
	fprintf(img_ref, "P1 %d %d\n", WIDTH, HEIGHT); 
	for(int i = 0; i < HEIGHT; i++){
		for(int j = 0; j < WIDTH; j++){
			fputc(pbm_matrix[i][j], img_ref);
		}
		fputc('\n', img_ref);
	}
	fclose(img_ref);
	return 0;
}`

This to open the image file netpbm is needed, and maybe libnetpbm (I don't know, everything is preinstalled on Linux Mint). I'm using the exercise in Rouben Rostamian's book as reference.

EDIT: I'm sorry for the very poor formatting at the top of the code, I can't seem to get the macros to look good

top 1 comments
sorted by: hot top controversial new old
[โ€“] [email protected] 2 points 1 year ago

You may need to seed the random number generator in order for it to actually behave randomly between program execution. Add the following in the main function:

srand(time(NULL));

For reference: https://www.tutorialspoint.com/c_standard_library/c_function_srand.htm