#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
/*
This program demonstrates how to find the 3 products with the lowest cost
from a list of product–price pairs, rewritten in C.
We use:
- arrays instead of std::vector
- qsort instead of partial_sort
- helper functions for clarity
- detailed comments explaining each step
*/
// A simple struct to hold product data
typedef struct {
char name[10]; // product name, e.g., "p1"
int price; // price in dollars
} Product;
// Generate random products with prices between 1 and 20
void generateProducts(Product *products, int total_products) {
/*
We use rand() seeded with time(NULL).
Each product gets a name "pX" and a random price.
*/
for (int i = 0; i < total_products; i++) {
sprintf(products[i].name, "p%d", i + 1);
products[i].price = (rand() % 20) + 1; // random price 1–20
}
}
// Print all products
void printProducts(const Product *products, int total_products) {
printf("All products:\n");
for (int i = 0; i < total_products; i++) {
printf(" %-3s $%d\n", products[i].name, products[i].price);
}
printf("\n");
}
// Comparison function for qsort (ascending by price)
int compareByPrice(const void *a, const void *b) {
const Product *pa = (const Product *)a;
const Product *pb = (const Product *)b;
return pa->price - pb->price;
}
// Find the 3 cheapest products
void findThreeCheapest(const Product *products, Product *out_three, int total_products) {
/*
In C, we cannot partially sort easily like in C++.
Instead, we copy the array and fully sort it using qsort.
Sorting 10 items is trivial in cost.
After sorting, the first 3 items are the cheapest.
*/
Product temp[total_products];
memcpy(temp, products, sizeof(temp));
qsort(temp, total_products, sizeof(Product), compareByPrice);
// Copy the first 3 cheapest products
for (int i = 0; i < 3; i++) {
out_three[i] = temp[i];
}
}
int main() {
srand((unsigned)time(NULL)); // seed RNG
const int total_products = 10;
Product products[total_products];
Product cheapest[3];
// Generate random products
generateProducts(products, total_products);
// Display all products
printProducts(products, total_products);
// Find the 3 cheapest
findThreeCheapest(products, cheapest, total_products);
// Display the result
printf("Three cheapest products:\n");
for (int i = 0; i < 3; i++) {
printf(" %-3s $%d\n", cheapest[i].name, cheapest[i].price);
}
return 0;
}
/*
run:
All products:
p1 $16
p2 $10
p3 $19
p4 $16
p5 $20
p6 $7
p7 $2
p8 $6
p9 $9
p10 $5
Three cheapest products:
p7 $2
p10 $5
p8 $6
*/