In: Computer Science
C#
To write a program using a stack and a program using a queue.
Code a class encapsulating a queue of foods using a circular array. A food has the following attributes: name, the number of calories per serving and the number of servings per container. Limit your queue to 20 food items. In addition to writing the enqueue, dequeue, and peek methods, you will write two more methods: a method that returns the average calories per serving of all the foods in the queue; a method that returns the food items with the highest total calories (ie: number of calories per serving * servings per container). Write a program to test your queue with all these methods
import java.util.* ;
class Solution
{
static class FoodItem
{
String name;
int calories;
int serving;
FoodItem link;
}
static class Queue
{
FoodItem front, rear;
}
static void enQueue(Queue q, String name, int calories, int
serving)
{
FoodItem temp = new FoodItem();
temp.name= name;
temp.calories=calories;
temp.serving= serving;
if (q .front == null)
q .front = temp;
else
q .rear .link = temp;
q .rear = temp;
q .rear .link = q .front;
}
static int deQueue(Queue q)
{
if (q .front == null)
{
System.out.printf ("Queue is
empty");
return Integer.MIN_VALUE;
}
int value;
if (q .front == q .rear)
{
value = q .front .data;
q .front = null;
q .rear = null;
}
else
{
FoodItem temp = q .front;
value = temp .data;
q .front = q .front .link;
q .rear .link= q .front;
}
return value ;
}
static void averageCalories( Queue q)
{
int n=0;
int sumCalories=0;
FoodItem temp = q .front;
System.out.printf("\nAverage calories is : ");
while (temp .link != q .front)
{ n++;
sumCalories= sumCalories +
temp.calories;
temp = temp .link;
}
int averageCalories = sumCalories/n;
System.out.printf("%d", averageCalories);
}
static void highestCalories( Queue q)
{
int HighestCalories=0;
String name;
FoodItem temp = q .front;
System.out.printf("\nFood with highest calories is:
");
while (temp .link != q .front)
{
int n=
temp.calories*temp.servings;
if(n>HighestCalories)
{
HighestCalories=n;
name= temp.name;
}
temp = temp .link;
}
System.out.printf(name);
}
/* Driver of the program */
public static void main(String args[])
{
Queue q = new Queue();
q .front = q .rear = null;
int noOfFoodItems;
Scanner input = new Scanner(System.in);
System.out.println("enter no of food items: ")
noOfFoodItems = input.nextInt();
if(noOfFoodItems<=20)
{
for(int i=0;i<noOfFoodItems;i++)
{
String name = input.nextString();
int calories =input.nextInt();
int serving = input.nextInt();
enQueue(q, name,calories,serving);
}
}
averageCalories(q);
highestCalories(q);
}
}