|
| 1 | +package easy; |
| 2 | + |
| 3 | +import static java.lang.Math.pow; |
| 4 | + |
| 5 | +import java.util.Arrays; |
| 6 | + |
| 7 | +/** |
| 8 | + * Have the function ArrayAdditionI(arr) take the array of numbers stored in arr |
| 9 | + * and return the string true if any combination of numbers in the array |
| 10 | + * (excluding the largest number) can be added up to equal the largest number in the array, |
| 11 | + * otherwise return the string false. |
| 12 | + * --- |
| 13 | + * For example: if arr contains [4, 6, 23, 10, 1, 3] the output |
| 14 | + * should return true because 4 + 6 + 10 + 3 = 23. |
| 15 | + * --- |
| 16 | + * The array will not be empty, will not contain all the same elements, |
| 17 | + * and may contain negative numbers. |
| 18 | + */ |
| 19 | +public class ArrayAdditionOne { |
| 20 | + |
| 21 | + /** |
| 22 | + * Left pad the string with zeroes, |
| 23 | + * e.g. padLeft("fade", 8) -> "0000fade" |
| 24 | + * |
| 25 | + * @param str string to be padded |
| 26 | + * @param len new fixed length after applying the padding |
| 27 | + * @return padded string (e.g. 000000xxx) |
| 28 | + */ |
| 29 | + private static String padLeft(String str, int len) { |
| 30 | + return String.format("%" + len + "s", str).replace(" ", "0"); |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * Array Addition I function. |
| 35 | + * |
| 36 | + * @param arr input array of integers |
| 37 | + * @return "true" if any combination can be added up to equal the largest number in the array |
| 38 | + */ |
| 39 | + private static String arrayAdditionOne(int[] arr) { |
| 40 | + Arrays.sort(arr); |
| 41 | + int largest = arr[arr.length - 1]; |
| 42 | + int oneChar = "1".charAt(0); |
| 43 | + |
| 44 | + for (int i = 0; i < pow(2, arr.length); i++) { |
| 45 | + String bin = Integer.toBinaryString(i); |
| 46 | + String combo = padLeft(bin, arr.length - 1); |
| 47 | + int sum = 0; |
| 48 | + for (int j = 0; j < combo.length(); j++) { |
| 49 | + if (combo.charAt(j) == oneChar) { |
| 50 | + sum += arr[j]; |
| 51 | + } |
| 52 | + if (sum == largest) { |
| 53 | + return "true"; |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + return "false"; |
| 59 | + } |
| 60 | + |
| 61 | + /** |
| 62 | + * Entry point. |
| 63 | + * |
| 64 | + * @param args command line arguments |
| 65 | + */ |
| 66 | + public static void main(String[] args) { |
| 67 | + var result1 = arrayAdditionOne(new int[]{4, 6, 23, 10, 1, 3}); |
| 68 | + System.out.println(result1); |
| 69 | + var result2 = arrayAdditionOne(new int[]{2, 6, 18}); |
| 70 | + System.out.println(result2); |
| 71 | + } |
| 72 | + |
| 73 | +} |
0 commit comments