#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>


FILE *NAME;

const long int density = 7;
const long int columns = 60;
const long int rows = 60;
float countdensity = 0;

int pocet = 0;
long int random ;

long int rand100;
long int costs [columns];
int matrix [rows][columns];



int RANGE_MIN_C = 1;
int RANGE_MAX_C = 5;
int RANGE_MIN = 0;
int RANGE_MAX = 100;



int main ( int argc, char* argv[] ){

	char *OutputFile;
	int i,j;


	srand( (unsigned)time( NULL ) );
	rand();

//******* vygenerovani vektoru cen *******
	for (j = 0; j<columns; j++) {

			 rand100 = (((double) rand() / 
                         (double) RAND_MAX) * RANGE_MAX_C + RANGE_MIN_C);
		 costs [j] = rand100; 
	}

	
	
//******* vygenerovani binarni matice *******
	for (i = 0; i<rows; i++) {
		for (j = 0; j<columns; j++){
			matrix[i][j] = 0;
		}
	}


	for (i = 0; i<rows; i++) {
		for (j = 0; j<columns; j++){
//			printf (" i je %d, j je %d. \n",i,j);
		
			rand100 = (((double) rand() / 
                        (double) RAND_MAX) * RANGE_MAX + RANGE_MIN);
			
			if ( rand100 < density ) matrix[i][j] = 1;
			else matrix[i][j] = 0;
		}
	}

//*******zajisteni, aby se jednalo opravdu o binarni matici
	for (i = 0; i<rows; i++) {
		for (j = 0; j<columns; j++){
		if ( matrix[i][j] != 0 && matrix[i][j]!= 1 ) matrix[i][j] = 0;
		}
	}



/*
	printf ( "%d %d\n",columns,rows);
	for (j = 0; j<columns; j++) {
		printf ( "%d ",costs[j]);
	}
	printf ( "\n");
	for (i = 0; i<rows; i++) {
		for (j = 0; j<columns; j++){
			printf ("%d ",matrix[i][j]);
		}
		printf ( "\n");
	}
	printf ( "\n");*/
	
//******* uprava radku tak, aby matice mela vzdy reseni *******	

for (i = 0; i<rows; i++) {
		pocet = 0;
		for (j = 0; j<columns; j++){
			 if (matrix[i][j] == 1) pocet = 1;	
		}
		if ( pocet == 0) {
			
			int random = (((double) rand() / 
                           (double) RAND_MAX) * columns );
			matrix [i][random] = 1;

		}
	}



//******* spocteni procentualni hustoty matice *******	
	float pom = 0;
	for (i = 0; i<rows; i++) {
		for (j = 0; j<columns; j++){
		if ( matrix[i][j]==1) pom ++;
		}
	}
	countdensity = pom/(((float)rows * (float)columns)/100);
	printf("pocet jednicek je je %f .",pom);
	printf("hustota je %f .",countdensity);


//******* vypsani matice do souboru *******	

	if ( argc == 2 ) OutputFile = argv[2];
      else OutputFile = "matice.dat";
	if ( (NAME=fopen ( OutputFile,"wt"))==NULL){   
	printf("Cannot open output file %s \n");
	exit(0);
    }



	NAME=fopen ( OutputFile,"at");
	fprintf (NAME, "%d %d\n",columns,rows);
	for (j = 0; j<columns; j++) {
		fprintf (NAME, "%d ",costs[j]);
	}
	fprintf (NAME, "\n");
	for (i = 0; i<rows; i++) {
		for (j = 0; j<columns; j++){
			fprintf (NAME, "%d ",matrix[i][j]);
		}
		fprintf (NAME, "\n");
	}
	fprintf (NAME, "\n");
	fclose(NAME);

	return 0;

}