repl.it
@SofhinWong1/

Room Assign

C

No description

fork
loading
Files
  • main.c
  • sa
main.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <stdio.h>
#include <string.h>

#define BLOCK_COUNT     4
#define ROOMS_PER_BLOCK 2

/* Define room structure */
struct room {
	char block[3];
	int room_number;
	int room_size;
	int occupied;
};

/* Create global variable rooms, which is an array of struct room */
struct room rooms[BLOCK_COUNT * ROOMS_PER_BLOCK];

void
print_rooms(void)
{
	printf("| Block | Room | Size | Occupied |\n");
	printf("|-------|------|------|----------|\n");

	for (struct room *r = rooms, *end = rooms + BLOCK_COUNT * ROOMS_PER_BLOCK; r < end; ++r) {
		printf("| %5s | %4d | %4d | %8d |\n", r->block, r->room_number, r->room_size, r->occupied);
	}
}

int
main(void)
{
	/* Initialize rooms */
	const char *blocks[BLOCK_COUNT] = {"A1", "A3", "A4", "B4"};
	for (int i = 0; i < BLOCK_COUNT; ++i) {
		for (int j = 0; j < ROOMS_PER_BLOCK; ++j) {
			struct room *r = rooms + i * ROOMS_PER_BLOCK + j;
			strcpy(r->block, blocks[i]);
			r->room_number = j + 1;
			r->room_size = i % 4 + 1;
			r->occupied = 0;
		}
	}

	print_rooms();

	/* Ask user to choose block and auto assign a room for them */
	while (1) {
		printf("Enter block or \"quit\": ");
		char b[100];
		scanf("%s", b);

		if (strcmp(b, "quit") == 0) {
			break;
		}

		/* Search for available room */
		int found = 0;
		for (int i = 0; i < BLOCK_COUNT * ROOMS_PER_BLOCK; ++i) {
			if (
				strcmp(rooms[i].block, b) == 0 /* Found block */
				&& rooms[i].occupied < rooms[i].room_size /* Has empty space */
			) {
				rooms[i].occupied += 1;
				printf("Assign to room %s-%d\n", rooms[i].block, rooms[i].room_number);
				found = 1;
				break;
			}
		}

		if (!found) {
			printf("Sorry, no empty room\n");
		}
	}

	/* Print all rooms */
	print_rooms();

	return 0;
}
Fetching token
?