Codewar-011 How Much?

↘锁芯ラ 提交于 2020-01-08 16:06:47

【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>

I always thought that my old friend John was rather richer than he looked, but I never knew exactly how much money he actually had. One day (as I was plying him with questions) he said: "Imagine I have between m and n Zloty (or did he say Quetzal? I can't remember!)

If I were to buy 9 cars costing c each, I'd only have 1 Zlotty (or was it Meticals?) left.

And if I were to buy 7 boats at b each, I'd only have 2 Ringglets (or was it Zlotty?) left.

Could you tell me in each possible case:

  1. how much money f he could possibly have
  2. the cost c of a car
  3. the cost b of a boat?

So, I will have a better idea about his fortune. Note that if m-n is big enough, you might have a lot of possible answers.

Each answer will be given as ["M: f", "B: b", "C: c"] and all the answers as [ ["M: f", "B: b", "C: c"] ... ]. M stands for "Money", B for boats, C for cars.

m and n are positive or null integers with m <= n or m >= n, m and n inclusive.

Examples:

howmuch(1, 100) => [["M: 37", "B: 5", "C: 4"], ["M: 100", "B: 14", "C: 11"]]
howmuch(1000, 1100) => [["M: 1045", "B: 149", "C: 116"]]
howmuch(10000, 9950) => [["M: 9991", "B: 1427", "C: 1110"]]
howmuch(0, 200) => [["M: 37", "B: 5", "C: 4"], ["M: 100", "B: 14", "C: 11"], ["M: 163", "B: 23", "C: 18"]]

Explanation of howmuch(1, 100):

In the first answer his possible fortune is 37 so if he buys 7 boats each worth 5 it remains 37 - 7 * 5 = 2, if he buys 9 cars worth 4 each it remains 37 - 9 * 4 = 1. The same with f = 100: 100 - 7 * 14 = 2 and 100 - 9 * 11 = 1.

package codewars;

public class Carboat {

	public static String howmuch(int m, int n) {
		StringBuilder sb = new StringBuilder();
		sb.append("[");

		if (m > n) {
			int temp = m;
			m = n;
			n = temp;
		}
		for (int i = m; i <= n; i++) {
			if (i % 9 == 1 && i % 7 == 2) {
				sb.append(String.format("[M: %d B: %d C: %d]", i, i / 7, i / 9));
			}
		}
		sb.append("]");
		return sb.toString();
	}

}
package codewars;
import static org.junit.Assert.*;
import org.junit.Test;


public class CarboatTest {

	@Test
	public void BasicTests() {
		assertEquals("[[M: 37 B: 5 C: 4][M: 100 B: 14 C: 11]]", 
				Carboat.howmuch(1, 100));
		assertEquals("[]", 
				Carboat.howmuch(2950, 2950));
	}
	
}

https://www.codewars.com/kata/55b4d87a3766d9873a0000d4/train/java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!