Close Enough Computations

From programming_contest
Jump to navigation Jump to search

Introduction

This problem asks you to determine whether or not a given set of grams of fat, carbohydrates, and protein could yield the listed total calories if normal rounding is assumed. The number of calories per gram of fat, carbohydrate, and protein is given.

Algorithm

All of the above inputs are integers, but we will need to treat them as floats since we are interested in how rounding floats to integers affects the final total calories. The simplest approach is to calculate the maximum and minimum possible total calories that could result from round-off error, and then check whether or not the given total calories lies within this range. To do this we will convert the integers given in the problem to integers, find the minimum and maximum float values that could round to their original values, calculating the total calories for these two endpoints (floats), and then round via normal rounding. Both algorithm and implementation are simple. One possible solution is displayed below.

Solution - Java

import java.util.Scanner;
public class CloseEnoughComputations {
	Scanner in = new Scanner(System.in);
	float fat_CalsPerGram = 9f;
	float car_CalsPerGram = 4f;
	float pro_CalsPerGram = 4f;
	float pos = 0.499f;
	float neg = -0.5f;
	void start() {
		while (true) {
			int cals_total = in.nextInt();
			float fat_grams = in.nextFloat();
			float car_grams = in.nextFloat();
			float pro_grams = in.nextFloat();
			if (cals_total==0 && fat_grams==0 && car_grams==0 && pro_grams==0) return;
			int cals_max = Math.round(
					(fat_grams + pos) * fat_CalsPerGram
					+ (car_grams + pos) * car_CalsPerGram
					+ (pro_grams + pos) * pro_CalsPerGram);
			int cals_min = Math.round(
					(fat_grams + neg) * fat_CalsPerGram
					+ (car_grams + neg) * car_CalsPerGram
					+ (pro_grams + neg) * pro_CalsPerGram);
			if (cals_total <= cals_max && cals_total >= cals_min) {
				System.out.println("yes");
			}
			else {
				System.out.println("no");
			}
		}
	}
	public static void main(String[] args) {
		new CloseEnoughComputations().start();
	}
}