72 lines
2.1 KiB
C
72 lines
2.1 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
/*
|
|
* This file was generated by OpenAI and was not modified apart from this comment. The prompt was:
|
|
* consider a text file like this:
|
|
* 22-65,22-66
|
|
* 91-94,63-91
|
|
* 6-88,5-31
|
|
* 85-86,64-86
|
|
* 40-65,40-65
|
|
* 25-82,24-94
|
|
*
|
|
* write c program that:
|
|
* - reads a text file like this line by line and count how often one of the two ranges contains the other.
|
|
* - accepts the filename via command line arg
|
|
* - outputs the result using printf with a suitable string
|
|
* A range r1 contains the other r2 when the r1.lower <= r2.lower and r1.upper >= r2.upper
|
|
* the program needs to output how often that is the case in the entire file
|
|
*/
|
|
|
|
// Structure to represent a range in the file
|
|
struct range {
|
|
int lower;
|
|
int upper;
|
|
};
|
|
|
|
// Function to parse a line from the file and return the two ranges in the line
|
|
void parse_line(const char *line, struct range *range1, struct range *range2) {
|
|
// Parse the two ranges in the line
|
|
sscanf(line, "%d-%d,%d-%d", &range1->lower, &range1->upper, &range2->lower, &range2->upper);
|
|
}
|
|
|
|
int main(int argc, char *argv[]) {
|
|
// Check if a filename was provided
|
|
if (argc < 2) {
|
|
fprintf(stderr, "Error: No filename provided\n");
|
|
return 1;
|
|
}
|
|
|
|
// Open the file for reading
|
|
FILE *fp = fopen(argv[1], "r");
|
|
if (fp == NULL) {
|
|
fprintf(stderr, "Error: Unable to open file for reading\n");
|
|
return 1;
|
|
}
|
|
|
|
// Read the file line by line
|
|
char line[256];
|
|
int count = 0;
|
|
while (fgets(line, sizeof(line), fp) != NULL) {
|
|
// Parse the two ranges in the line
|
|
struct range range1, range2;
|
|
parse_line(line, &range1, &range2);
|
|
|
|
// Check if one range contains the other
|
|
if ((range1.lower <= range2.lower && range1.upper >= range2.upper) ||
|
|
(range2.lower <= range1.lower && range2.upper >= range1.upper)) {
|
|
count++;
|
|
}
|
|
}
|
|
|
|
// Close the file
|
|
fclose(fp);
|
|
|
|
// Print the result
|
|
printf("The file contains %d lines where one of the two ranges contains the other\n", count);
|
|
|
|
return 0;
|
|
}
|