#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAXZONES 5 // Define…
- User
#include <stdio.h> #include <stdlib.h> #include <string.h>
#define MAX_ZONES 5 // Define the maximum number of zones #define STACK_SIZE 50 // Define the maximum stack size for supplies
typedef struct { int id; // Zone ID int priority; // Priority of the zone (lower number means higher priority) int people; // Number of people to rescue int zoneSupplies; // Supplies specific to the zone } Zone;
typedef struct { int supplies[STACK_SIZE]; // Array to store the supplies int top; // Top index of the stack } Stack;
typedef struct Node { int time; // Time of the rescue char name[20]; // Name of the rescued person struct Node *left, *right; // Pointers for left and right children in BST } RescuedPerson;
// Function prototypes void initStack(Stack *s); int isStackEmpty(Stack *s); int canAddSupplies(Stack *s, int quantity); void addSupplies(Stack *s, int quantity); void useSupplies(Stack *s, int quantity); void addZone(Zone zones[], int *zoneCount); void heapifyDown(Zone zones[], int size); void rescue(Stack *s, Zone zones[], int *zoneCount, RescuedPerson *root); RescuedPerson insertBST(RescuedPerson *root, int time, char name[]); void displayRescued(RescuedPerson *root); void inOrder(RescuedPerson *root);
void initStack(Stack *s) { s->top = -1; } // Initialize the stack
int isStackEmpty(Stack *s) { return s->top == -1; } // Check if stack is empty
int canAddSupplies(Stack *s, int quantity) { return s->top + quantity < STACK_SIZE; } // Check if supplies can be added
// Add multiple supplies to the stack void addSupplies(Stack *s, int quantity) { if (canAddSupplies(s, quantity)) { s->top += quantity; // Directly adjust the top pointer to add supplies } else { printf("Cannot add %d more supplies, stack overflow.\n", quantity); } }
// Use (pop) multiple supplies from the stack void useSupplies(Stack *s, int quantity) { for (int i = 0; i < quantity; i++) { if (!isStackEmpty(s)) { s->top--; } else { printf("Ran out of supplies unexpectedly.\n"); return; } } }
// Add a zone with heap property maintenance void addZone(Zone zones[], int *zoneCount) { if (*zoneCount >= MAX_ZONES) { printf("Cannot add more zones.\n"); return; } int id, priority, people, zoneSupplies; printf("Enter Zone ID, Priority (1-5), People, and Zone Specific Supplies: "); scanf("%d %d %d %d", &id, &priority, &people, &zoneSupplies); Zone newZone = {id, priority, people, zoneSupplies}; int i = (*zoneCount)++; while (i > 0 && zones[(i-1)/2].priority > priority) { zones[i] = zones[(i-1)/2]; // Bubble up i = (i-1)/2; } zones[i] = newZone; // Insert new zone }
// Maintain heap by sinking down an element void heapifyDown(Zone zones[], int size) { int i = 0; while (2 * i + 1 < size) { int leftChild = 2 * i + 1; int rightChild = 2 * i + 2; int smallest = leftChild;
if (rightChild < size && zones[rightChild].priority < zones[leftChild].priority) { smallest = rightChild; } if (zones[i].priority <= zones[smallest].priority) break; Zone temp = zones[i]; zones[i] = zones[smallest]; zones[smallest] = temp; i = smallest; // Move down the heap }}
// Perform the rescue operation void rescue(Stack *s, Zone zones[], int *zoneCount, RescuedPerson **root) { if (*zoneCount == 0) { printf("No zones available for rescue.\n"); return; }
Zone *topZone = &zones[0]; printf("Rescuing in Zone %d with priority %d.\n", topZone->id, topZone->priority); int requiredSupplies = topZone->people - topZone->zoneSupplies; if (requiredSupplies > 0 && s->top + 1 < requiredSupplies) { printf("Not enough supplies for rescue in this zone.\n"); return; } if (requiredSupplies > 0) { useSupplies(s, requiredSupplies); } for (int i = 0; i < topZone->people; i++) { char name[20]; int time; printf("Enter name and time of rescue for person %d: ", i + 1); scanf("%s %d", name, &time); *root = insertBST(*root, time, name); } zones[0] = zones[--(*zoneCount)]; heapifyDown(zones, *zoneCount);}
// Insert rescued person into a binary search tree RescuedPerson* insertBST(RescuedPerson root, int time, char name[]) { if (root == NULL) { RescuedPerson newNode = (RescuedPerson*)malloc(sizeof(RescuedPerson)); newNode->time = time; strcpy(newNode->name, name); newNode->left = newNode->right = NULL; return newNode; } if (time < root->time) root->left = insertBST(root->left, time, name); else root->right = insertBST(root->right, time, name); return root; }
// Display all rescued people void displayRescued(RescuedPerson *root) { if (root == NULL) { printf("No rescued people.\n"); return; } printf("Rescued people:\n"); inOrder(root); }
// In-order traversal of the binary search tree void inOrder(RescuedPerson *root) { if (root) { inOrder(root->left); printf("Name: %s, Time: %d\n", root->name, root->time); inOrder(root->right); } }
int main() { Zone zones[MAX_ZONES]; int zoneCount = 0; Stack supplyStack; initStack(&supplyStack); RescuedPerson *rescuedRoot = NULL;
int choice; do { printf("\nMenu:\n"); printf("1. Add Zone\n2. Add Supply to Rescuers\n3. Perform Rescue\n4. Display Rescued People\n5. Exit\n"); printf("Enter your choice: "); scanf("%d", &choice); switch (choice) { case 1: addZone(zones, &zoneCount); break; case 2: { int supply; printf("Enter the number of supplies to add: "); scanf("%d", &supply); addSupplies(&supplyStack, supply); break; } case 3: rescue(&supplyStack, zones, &zoneCount, &rescuedRoot); break; case 4: displayRescued(rescuedRoot); break; case 5: printf("Exiting...\n"); break; default: printf("Invalid choice. Try again.\n"); } } while (choice != 5); return 0;}
for th given code if we are already sorting in add_zone function ,why are we using heapify down function to sort again
- Assistant
In the provided code, the heap structure is being used to manage the priority of rescue zones during the rescue operation. Here’s a clear explanation of why both the initial sorting and later restructuring with
heapifyDowntake place:-
Initial Sorting using Heap Insertion (
addZonefunction):- When a new zone is added using the
addZonefunction, the new zone is inserted at the end of the heap array. - The heap property is maintained by "bubbling up" the zone to ensure that each parent node has a higher priority (lower priority number) than its child nodes. This ensures that the most critical zone (with the highest priority) is always on top.
- This ensures that when a new zone is added, it is placed correctly within the heap based on priority.
- When a new zone is added using the
-
Re-sort or Rearrange using
heapifyDownduring Rescue Operation:- After rescuing people from the top-priority zone, the zone is removed from the heap. To do this, the last zone in the heap is moved to the root position (index 0) to fill the gap.
- However, this disrupts the heap property because the new root may not be the highest priority. Thus,
heapifyDownis used to restore the heap order by comparing the new root with its children and moving it down the tree until the heap property is restored. - This is necessary after each rescue operation to ensure that the next zone with the highest priority is at the top of the heap for the subsequent rescue.
In summary, the use of a heap is a classic way to efficiently manage a dynamic list of zones with priorities. The
addZonefunction makes sure the newly added zone is correctly placed according to its priority, whileheapifyDownensures the priority order is restored after removing the top zone. This two-step approach allows for efficient insertion and deletion in the heap structure. -
- User
PROBLEM STATEMENT-1 (for odd number SRNs): Create and display a list of 3 patient appointments using the React framework. Each appointment should include the patient's name, reason for appointment, appointment date, and status (e.g., scheduled, completed). When a user clicks a button, the status of the selected appointment should change to "completed", and the total number of completed appointments should be recalculated and displayed. Use a style object variable for custom styling, like how you would in JavaScript. Ensure that the appointment details are read from an array of objects OBJECTIVE The objective of this exercise is to test the student on the front end framework React JS. It evaluates the student’s knowledge React Js components, ReactJS props and state, ReactJS Lists and Keys, React JS events PREREQUISITE In order to complete this exercise, the student needs to understand the fundamentals of HTML,CSS, and JavaScript
AUG
DEC 2024 Unit 3
SAMPLE1: Here's a visual representation of what the webpage will look like: Explanation: Sample UI Design Picture Patient Appointments Description:
- Header: "Patient Appointments" is prominently displayed at the top, centered.
- Appointment Cards: o Each card includes: ▪ Patient Name: Large, bold text. ▪ Reason: Description of the appointment reason. ▪ Date: The date of the appointment. ▪ Status: Current status of the appointment (Scheduled/Completed). ▪ Button: A button to mark the appointment as completed, only visible if the appointment is scheduled.
o Completed appointments have the name crossed out and in gray color. 3. Total Completed Appointments: Displays the total number of completed appointments at the bottom, centered and bold. SAMPLE SCREENSHOT OF OUTPUT (Just for your reference)
AUG
DEC 2024 Unit 3
PROGRAM
SCREENSHOT OF YOUR OUTPUT
- Assistant
To create the described application using the React framework, you'll first need to set up a simple React app if you haven't already. You can use Create React App to bootstrap your application. Once you have your project set up, you can start implementing the components and functionality as specified. Here's a detailed implementation:
Steps to Implement the Solution:
-
Setup a React Project:
If you haven't already set up a React project, you can do so using Create React App with the following command:
npx create-react-app patient-appointmentsNavigate to your project directory:
cd patient-appointments -
Modify the App Component:
Open the
src/App.jsfile and replace its content with the following code:
import React, { useState } from 'react'; const App = () => { const [appointments, setAppointments] = useState([ { id: 1, name: 'John Doe', reason: 'Dental Checkup', date: '2023-11-01', status: 'Scheduled' }, { id: 2, name: 'Jane Smith', reason: 'Eye Exam', date: '2023-11-02', status: 'Scheduled' }, { id: 3, name: 'Bob Johnson', reason: 'Physical Therapy', date: '2023-11-03', status: 'Scheduled' } ]); // Function to mark appointment as completed const markAsCompleted = (id) => { setAppointments(appointments.map(app => app.id === id ? { ...app, status: 'Completed' } : app )); }; // Calculate the total number of completed appointments const completedCount = appointments.filter(app => app.status === 'Completed').length; // Custom styles const styles = { container: { marginTop: '20px', textAlign: 'center' }, header: { fontSize: '24px', fontWeight: 'bold' }, card: { border: '1px solid #ccc', padding: '10px', margin: '10px', borderRadius: '5px' }, cardCompleted: { border: '1px solid #ccc', padding: '10px', margin: '10px', borderRadius: '5px', textDecoration: 'line-through', color: 'gray' }, button: { padding: '5px 10px', marginTop: '10px', cursor: 'pointer' }, footer: { marginTop: '20px', fontSize: '18px', fontWeight: 'bold' } }; return ( <div style={styles.container}> <div style={styles.header}>Patient Appointments</div> {appointments.map(appointment => ( <div key={appointment.id} style={appointment.status === 'Completed' ? styles.cardCompleted : styles.card}> <div style={{ fontWeight: 'bold', fontSize: '20px' }}>{appointment.name}</div> <div>Reason: {appointment.reason}</div> <div>Date: {appointment.date}</div> <div>Status: {appointment.status}</div> {appointment.status === 'Scheduled' && ( <button style={styles.button} onClick={() => markAsCompleted(appointment.id)}>Mark as Completed</button> )} </div> ))} <div style={styles.footer}>Total Completed Appointments: {completedCount}</div> </div> ); }; export default App;Code Explanation:
-
State Management:
- We use the
useStatehook to manage the list of appointments. Initially, the appointments are set with a status of "Scheduled".
- We use the
-
Mark as Completed Functionality:
- The
markAsCompletedfunction updates the status of an appointment to "Completed". It uses thesetAppointmentsfunction to update the specific appointment based on itsid.
- The
-
Styling:
- The
stylesobject contains custom styles for various parts of the component. This is akin to using inline styles in JavaScript.
- The
-
Rendering:
- We map over the
appointmentsarray to render each appointment. Completed appointments are styled differently (crossed out and gray). - A button to mark an appointment as completed is shown only if the appointment is still scheduled.
- We map over the
-
Total Count:
- The total number of completed appointments is calculated using the
filtermethod and displayed at the bottom.
- The total number of completed appointments is calculated using the
Running the App:
-
Start the React development server with:
npm start -
Visit
http://localhost:3000in your browser to see the application in action.
This setup will give you a functional React application for managing and displaying patient appointments as specified in the problem statement.
-
- User
how do i design the website using html?
- Assistant
Designing a simple website using HTML involves structuring the content properly with HTML elements and enhancing the design with CSS for styles. Below is a basic implementation of the patient appointments as previously described using HTML and CSS:
HTML Structure
Let's start by creating a basic HTML file:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Patient Appointments</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="container"> <h1>Patient Appointments</h1> <div class="appointment-card"> <h2>John Doe</h2> <p>Reason: Dental Checkup</p> <p>Date: 2023-11-01</p> <p>Status: <span class="status scheduled">Scheduled</span></p> <button class="complete-btn">Mark as Completed</button> </div> <div class="appointment-card"> <h2>Jane Smith</h2> <p>Reason: Eye Exam</p> <p>Date: 2023-11-02</p> <p>Status: <span class="status scheduled">Scheduled</span></p> <button class="complete-btn">Mark as Completed</button> </div> <div class="appointment-card"> <h2>Bob Johnson</h2> <p>Reason: Physical Therapy</p> <p>Date: 2023-11-03</p> <p>Status: <span class="status scheduled">Scheduled</span></p> <button class="complete-btn">Mark as Completed</button> </div> <div class="footer"> Total Completed Appointments: <span id="completed-count">0</span> </div> </div> <script src="script.js"></script> </body> </html>CSS for Styling
Now, add the styling file
styles.cssto enhance the presentation of the HTML content:body { font-family: Arial, sans-serif; margin: 0; padding: 0; box-sizing: border-box; display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #f4f4f4; } .container { width: 80%; max-width: 600px; text-align: center; } h1 { font-size: 2em; margin-bottom: 20px; } .appointment-card { background: white; padding: 20px; margin: 10px 0; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); } h2 { font-size: 1.5em; margin-bottom: 10px; color: black; } p { margin: 5px 0; } .status.scheduled { color: green; } .status.completed { color: gray; text-decoration: line-through; } .complete-btn { margin-top: 10px; padding: 10px 20px; border: none; background-color: #007BFF; color: white; border-radius: 5px; cursor: pointer; } .complete-btn:hover { background-color: #0056b3; } .footer { margin-top: 20px; font-size: 1.2em; font-weight: bold; }JavaScript to Handle Interactivity
To enable dynamic interaction, such as marking appointments as completed and updating the count, add a
script.jsfile:document.addEventListener("DOMContentLoaded", function() { const completeButtons = document.querySelectorAll('.complete-btn'); const completedCount = document.getElementById('completed-count'); let completedAppointments = 0; completeButtons.forEach(button => { button.addEventListener('click', function() { const card = button.parentElement; const statusElement = card.querySelector('.status'); if (statusElement.textContent === 'Scheduled') { statusElement.textContent = 'Completed'; statusElement.classList.remove('scheduled'); statusElement.classList.add('completed'); completedAppointments += 1; completedCount.textContent = completedAppointments; button.style.display = 'none'; } }); }); });Explanation
-
HTML Structure: Defines the layout with placeholders for patient data. Includes a button to mark each appointment as completed.
-
CSS Styling: Adds aesthetic styles, such as card borders, button colors, and text formatting.
-
JavaScript Interactivity: Facilitates dynamic updates to the appointment status and count of completed appointments.
This setup will give you a simple, interactive static HTML webpage exemplifying the functionality described in your problem. While basic, it showcases essential front-end development practices such as HTML structure, CSS styling, and JavaScript interactivity.
-
- User
how do i use it on react
- Assistant
To incorporate the HTML and CSS design into a React application while maintaining the functionality, you can follow these steps. React allows you to create components, manage state, and handle events, which will help in making the patient appointments interactive. Below, I will guide you through converting the static HTML and CSS setup into a React component:
Step 1: Set Up Your React Project
If you haven’t set up a React project yet, use Create React App to create one:
npx create-react-app patient-appointments cd patient-appointmentsStep 2: Building the React Component
Open
src/App.jsand implement the functionality using React:import React, { useState } from 'react'; import './App.css'; // Assume you're using App.css for styles const App = () => { const [appointments, setAppointments] = useState([ { id: 1, name: 'John Doe', reason: 'Dental Checkup', date: '2023-11-01', status: 'Scheduled' }, { id: 2, name: 'Jane Smith', reason: 'Eye Exam', date: '2023-11-02', status: 'Scheduled' }, { id: 3, name: 'Bob Johnson', reason: 'Physical Therapy', date: '2023-11-03', status: 'Scheduled' } ]); // Function to mark an appointment as completed const markAsCompleted = (id) => { setAppointments(appointments.map(appointment => appointment.id === id ? { ...appointment, status: 'Completed' } : appointment )); }; // Calculate completed appointments count const completedCount = appointments.filter(appointment => appointment.status === 'Completed').length; return ( <div className="container"> <h1>Patient Appointments</h1> {appointments.map(appointment => ( <div key={appointment.id} className={`appointment-card ${appointment.status.toLowerCase()}`}> <h2>{appointment.name}</h2> <p>Reason: {appointment.reason}</p> <p>Date: {appointment.date}</p> <p>Status: <span className={`status ${appointment.status.toLowerCase()}`}>{appointment.status}</span></p> {appointment.status === 'Scheduled' && ( <button onClick={() => markAsCompleted(appointment.id)}>Mark as Completed</button> )} </div> ))} <div className="footer"> Total Completed Appointments: {completedCount} </div> </div> ); }; export default App;Step 3: Styling with CSS
Create or modify
src/App.cssto include your styles:.container { text-align: center; width: 80%; max-width: 600px; margin: 0 auto; } h1 { font-size: 2em; margin-bottom: 20px; } .appointment-card { background: white; padding: 20px; margin: 10px 0; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); position: relative; } .appointment-card.completed { color: gray; text-decoration: line-through; } h2 { font-size: 1.5em; margin-bottom: 10px; color: black; } p { margin: 5px 0; } .status { font-weight: bold; } button { margin-top: 10px; padding: 10px 20px; border: none; background-color: #007BFF; color: white; border-radius: 5px; cursor: pointer; } button:hover { background-color: #0056b3; } .footer { margin-top: 20px; font-size: 1.2em; font-weight: bold; }Explanation
-
Component Logic: The
Appcomponent usesuseStateto manage the state of appointments. Each appointment can be marked as completed, updating its status in the component's state. -
Dynamic Styles: Class names and styles are conditionally applied based on the appointment's status to differentiate completed appointments.
-
Event Handling: When the "Mark as Completed" button is clicked, the corresponding appointment is updated.
Step 4: Run Your Project
In your terminal, navigate to your project directory and run:
npm startThis will open a new browser window with the rendered React application. Here, you can interact with the patient appointments, changing their status and seeing the totals update in real time.
By following these steps, you transform a static HTML/CSS setup into a dynamic React application, leveraging state and event handling to create an interactive user experience.
-