53.4k views
13 votes
Write a function in Java to implement the following logic:

We want to make a row of bricks that is goal inches long. We have a number of small bricks (1 inch each) and big bricks (5 inches each). Return true if it is possible to make the goal by choosing from the given bricks.

User Kevin Nash
by
3.5k points

1 Answer

14 votes

Answer:

Step-by-step explanation:

The following Java code basically divides the goal size by 5 and rounds the answer to the lowest whole number. Then multiplies that answer by 5 and goes adding 1 until the exact goal size is met. If the value is passed then that means that using the current brick sizes it is not possible to make the goal. Otherwise, it will print out that it is possible.

import java.io.*;

import java.util.Scanner;

public class Main{

public static void main(String args[]) throws IOException {

String answer = "No, it is not possible";

Scanner in = new Scanner(System.in);

System.out.println("Enter goal size: ");

float goalSize = in.nextFloat();

float currentSize = (float) Math.floor(goalSize / 5);

currentSize = currentSize * 5;

while (true) {

if (currentSize < goalSize) {

currentSize += 1;

} else if(currentSize == goalSize) {

answer = "Yes, it is possible";

break;

} else {

break;

}

}

System.out.println(answer);

}

User Alex Saunin
by
3.6k points