Answer to Question #325227 in C++ for Anji

Question #325227

monica has cooked n dishes and collected the data on the level of satisfaction for all the dishes from a guest. the guest returns an array, where the ith element of the array is the liking level of the ith dish. also, the time taken to cook the ith dish is i. like-to-time coefficient of a dish is calculated by multiplying the time taken to cook food with its liking level, i.e., input 2[i]. totally like-to-time coefficient is calculated by summing up all individual coefficients of dishes. you want the total like-to-time coefficient to be maximum. you can also remove some dishes, in which case, a new coefficient is calculated using the left dishes. find the maximum sum of all possible like-to-time coefficients.​program done by using functions.


1
Expert's answer
2022-04-07T04:05:05-0400
#include <iostream>
using namespace std;


const int N=100;


// Read array of liking levels
// return size of the array
int read_liking(int liking[]) {
    int n;
    cout << "Enter number of foods: ";
    cin >> n;
    if (n > N) n = N;


    for (int i=0; i<n; i++) {
        cout << "Enter liking level of " << i+1 << "th food: ";
        cin >> liking[i];
    }
    return n;
}


// Calculate total like-to-time coefficient
// Skip k-th element
int total_like_to_time(int liking[], int n, int k=-1) {
    int total = 0;
    for (int i=0; i<n; i++) {
        if (i != k) {
            total += i*liking[i];
        }
    }
    return total;
}


// Remove k-th element from liking array
void remove(int liking[], int& n, int k) {
    n--;
    for (int i=k; i<n; i++) {
        liking[i] = liking[i+1];
    }
}


// Calculate maximum of total like-to-time coefficient
int max_like_to_time(int liking[], int& n) {
    int max_like = total_like_to_time(liking, n);
    int max_k = -1;


    for (int i=0; i<n; i++) {
        int like_to_time = total_like_to_time(liking, n, i);
        if (like_to_time > max_like)  {
            max_like = like_to_time;
            max_k = i;
        }
    }


    if (max_k >=0) {
        remove(liking, n, max_k);
        return max_like_to_time(liking, n);
    }
    return max_like;
}


int main() {
    int liking[N];
    int n;

    n = read_liking(liking);
    int max_like = max_like_to_time(liking, n);
    cout << "Maximum sum of like-to-time coefficents is " << max_like << endl;


    return 0;


}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS