From 5e8cc7cf8b4cc5260c6d16c7453f4b4a0646465e Mon Sep 17 00:00:00 2001 From: Util Date: Sun, 3 Mar 2024 16:58:54 -0600 Subject: Add TWC 258 solutions by Bruce Gray, in Raku, Perl, and Java. --- challenge-258/bruce-gray/java/ch-2.java | 41 +++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 challenge-258/bruce-gray/java/ch-2.java (limited to 'challenge-258/bruce-gray/java/ch-2.java') diff --git a/challenge-258/bruce-gray/java/ch-2.java b/challenge-258/bruce-gray/java/ch-2.java new file mode 100644 index 0000000000..f7f9036d89 --- /dev/null +++ b/challenge-258/bruce-gray/java/ch-2.java @@ -0,0 +1,41 @@ +// java java/ch-2.java +import java.util.List; +import java.util.stream.IntStream; +import java.util.stream.Collectors; +public class ch_2 { + + + static int task2 ( Integer k, List ns ) { + Integer[] ints = ns.toArray(new Integer[0]); + + return IntStream.range(0, ints.length) + .filter(i -> Integer.bitCount(i) == k) + .mapToObj(i -> ints[i]) + .collect(Collectors.summingInt(Integer::intValue)); + } + + + + // Test harness + static int test_number = 1; + static void plan ( Integer count ) { System.out.printf("1..%d\n", count); } + static boolean is ( Integer got, Integer expected, String desc ) { + boolean ret = got == expected; + System.out.printf("%s %d - %s\n", (ret ? "ok" : "not ok"), test_number++, desc); + return ret; + } + public static void main(String[] args) { + record Testcase ( Integer expected, Integer in_k, List in_nums ) {} + + List tst = List.of( + new Testcase( 17, 1, List.of(2, 5, 9, 11, 3) ), + new Testcase( 11, 2, List.of(2, 5, 9, 11, 3) ), + new Testcase( 2, 0, List.of(2, 5, 9, 11, 3) ) + ); + plan(tst.size()); + for (Testcase t : tst) { + is( task2(t.in_k, t.in_nums), t.expected, "k=" + t.in_k); + } + + } +} -- cgit