id stringclasses 50
values | testsource stringclasses 6
values | language stringclasses 6
values | prefix stringlengths 16 3.39k | golden_completion stringlengths 23 3.14k | suffix stringlengths 0 2.68k | assertions stringlengths 0 2.72k | category stringclasses 6
values |
|---|---|---|---|---|---|---|---|
1 | devbench-code2NL-NL2code | java | import java.util.*;
public class C2NTask1 {
public static void sortByLength(List<String> words) {
Collections.sort(words, Comparator.comparingInt(String::length));
}
| public static String describeSortByLength() {
return "Sorts the list of strings in place by length using Collections.sort, " +
"which guarantees a stable sort so that strings of equal length retain " +
"their original relative order. Mutates the input list rather than " +
... |
public static void main(String[] args) {
List<String> w = new ArrayList<>(Arrays.asList("bb", "a", "cc", "dd"));
sortByLength(w);
assert w.get(0).equals("a") : "first should be shortest";
assert w.get(1).equals("bb") : "stable order among length-2";
String doc = describeSor... | String d1 = C2NTask1.describeSortByLength().toLowerCase();
assert d1.contains("stable") : "must mention stable sort guarantee";
assert d1.contains("in place") || d1.contains("mutate") || d1.contains("mutates") : "must mention in-place mutation";
assert d1.contains("relative") || d1.contains("original order") || d1.cont... | code2NL_NL2code |
2 | devbench-code2NL-NL2code | java | import java.util.*;
public class C2NTask2 {
public static List<Integer> middleSlice(List<Integer> list) {
int size = list.size();
if (size < 2) return list.subList(0, size);
int from = size / 4;
int to = size - size / 4;
return list.subList(from, to);
}
| public static String describeMiddleSlice() {
return "Returns a live view of the middle portion of the list via List.subList. " +
"The returned list is backed by the original list, so structural " +
"modifications to the returned view (such as set or remove) are " +
... |
public static void main(String[] args) {
List<Integer> data = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8));
List<Integer> mid = middleSlice(data);
assert mid.size() == 4 : "middle of 8 should be 4 elements";
assert mid.get(0) == 3 : "should start at index 2";
Stri... | String d2 = C2NTask2.describeMiddleSlice().toLowerCase();
assert d2.contains("live view") || d2.contains("backed by") || d2.contains("view") : "must mention live view/backed semantics";
assert d2.contains("original") || d2.contains("backing") : "must reference original/backing list";
assert d2.contains("reflected") || ... | code2NL_NL2code |
3 | devbench-code2NL-NL2code | java | import java.util.*;
public class C2NTask3 {
public static void mergeInventory(Map<String, Integer> inventory, String item, int delta) {
inventory.merge(item, delta, (oldVal, newVal) -> {
int result = oldVal + newVal;
return result <= 0 ? null : result;
});
}
| public static String describeMergeInventory() {
return "Merges a quantity delta into the inventory map using Map.merge. " +
"If the item is absent, inserts it with the delta value. If present, " +
"adds delta to the existing quantity. When the resulting sum is zero " +
... |
public static void main(String[] args) {
Map<String, Integer> inv = new HashMap<>();
mergeInventory(inv, "apple", 5);
assert inv.get("apple") == 5;
mergeInventory(inv, "apple", 3);
assert inv.get("apple") == 8;
mergeInventory(inv, "apple", -8);
assert !inv.co... | String d3 = C2NTask3.describeMergeInventory().toLowerCase();
assert d3.contains("null") : "must mention null return from remapping function";
assert d3.contains("remove") || d3.contains("deleted") || d3.contains("drops") : "must state that null causes removal";
assert d3.contains("absent") || d3.contains("not present")... | code2NL_NL2code |
4 | devbench-code2NL-NL2code | java | import java.util.*;
import java.util.stream.*;
public class C2NTask4 {
public static int sumOfSquares(List<Integer> nums) {
return nums.stream().reduce(0, (acc, x) -> acc + x * x);
}
| public static String describeSumOfSquares() {
return "Computes the sum of squares using Stream.reduce with identity " +
"element 0. The identity value must be a true identity for the " +
"accumulator (i.e., 0 + x*x == x*x), which is required for " +
"correctness ... |
public static void main(String[] args) {
assert sumOfSquares(Arrays.asList(1, 2, 3)) == 14;
assert sumOfSquares(Collections.emptyList()) == 0;
String doc = describeSumOfSquares();
assert doc != null && doc.length() > 10;
System.out.println("Task 4 visible tests passed");
... | String d4 = C2NTask4.describeSumOfSquares().toLowerCase();
assert d4.contains("identity") : "must mention identity element concept";
assert d4.contains("parallel") || d4.contains("correctness") : "must mention parallel stream correctness requirement";
assert d4.contains("empty") : "must describe empty stream behavior";... | code2NL_NL2code |
5 | devbench-code2NL-NL2code | java | import java.util.*;
public class C2NTask5 {
public static List<String> createSyncList(String... items) {
List<String> base = new ArrayList<>(Arrays.asList(items));
return Collections.synchronizedList(base);
}
public static int safeCount(List<String> syncList) {
synchronized (syncL... | public static String describeSafeCount() {
return "Counts non-null, non-empty strings in a synchronized list. " +
"Must be called with explicit synchronization on the list object " +
"because Collections.synchronizedList does not protect iteration — " +
"iterator... |
public static void main(String[] args) {
List<String> sl = createSyncList("hello", "", null, "world");
assert safeCount(sl) == 2;
String doc = describeSafeCount();
assert doc != null && doc.length() > 10;
System.out.println("Task 5 visible tests passed");
}
}
| String d5 = C2NTask5.describeSafeCount().toLowerCase();
assert d5.contains("synchroniz") : "must mention synchronization requirement";
assert d5.contains("iterator") || d5.contains("iteration") || d5.contains("traversal") : "must mention iterator/iteration is not auto-protected";
assert d5.contains("concurrentmodificat... | code2NL_NL2code |
6 | devbench-code2NL-NL2code | java | import java.util.*;
public class C2NTask6 {
private static int callCount = 0;
public static String resolveConfig(String override) {
callCount = 0;
return Optional.ofNullable(override)
.orElseGet(() -> {
callCount++;
... | public static String describeResolveConfig() {
return "Returns the override value if non-null, otherwise lazily computes " +
"a default via Optional.orElseGet. The supplier lambda is only " +
"invoked when the Optional is empty, unlike Optional.orElse which " +
"... |
public static void main(String[] args) {
assert resolveConfig("custom").equals("custom");
assert getCallCount() == 0 : "supplier should not be called";
assert resolveConfig(null).equals("default_value");
assert getCallCount() == 1 : "supplier should be called once";
String ... | String d6 = C2NTask6.describeResolveConfig().toLowerCase();
assert d6.contains("lazy") || d6.contains("lazily") : "must mention lazy evaluation";
assert d6.contains("orelseget") || d6.contains("or_else_get") : "must name the orElseGet method";
assert d6.contains("orelse") && (d6.contains("eager") || d6.contains("always... | code2NL_NL2code |
7 | devbench-code2NL-NL2code | java | public class C2NTask7 {
public static boolean fastEquals(String a, String b) {
return a.intern() == b.intern();
}
public static String canonicalize(String s) {
return s.intern();
}
| public static String describeFastEquals() {
return "Compares two strings by reference identity (==) after interning " +
"both via String.intern(). intern() returns the canonical instance " +
"from the JVM string pool, guaranteeing that two strings with the " +
"s... |
public static void main(String[] args) {
String a = new String("hello");
String b = new String("hello");
assert !(a == b) : "new String creates distinct objects";
assert fastEquals(a, b) : "intern makes them reference-equal";
assert canonicalize(a) == canonicalize(b);
... | String d7 = C2NTask7.describeFastEquals().toLowerCase();
assert d7.contains("intern") : "must mention String.intern()";
assert d7.contains("pool") || d7.contains("canonical") : "must mention string pool or canonical reference";
assert d7.contains("reference") || d7.contains("identity") : "must explain reference/identit... | code2NL_NL2code |
8 | devbench-code2NL-NL2code | java | import java.util.*;
public class C2NTask8 {
// Returns a new list containing the elements of the input list
// sorted in ascending natural order. The original input list
// must NOT be modified. Returns an empty list if input is empty.
public static <T extends Comparable<T>> List<T> sortedCopy(List<T>... | List<T> copy = new ArrayList<>(input);
Collections.sort(copy);
return copy;
}
|
public static void main(String[] args) {
List<Integer> orig = new ArrayList<>(Arrays.asList(3, 1, 2));
List<Integer> sorted = sortedCopy(orig);
assert sorted.equals(Arrays.asList(1, 2, 3));
assert orig.equals(Arrays.asList(3, 1, 2)) : "original must be unchanged";
assert sor... | List<String> orig8 = new ArrayList<>(java.util.Arrays.asList("c", "a", "b"));
List<String> sorted8 = C2NTask8.sortedCopy(orig8);
assert sorted8.equals(java.util.Arrays.asList("a", "b", "c")) : "must be sorted";
assert orig8.equals(java.util.Arrays.asList("c", "a", "b")) : "original must be unmodified";
assert sorted8 !... | code2NL_NL2code |
9 | devbench-code2NL-NL2code | java | import java.util.concurrent.atomic.AtomicInteger;
public class C2NTask9 {
private static final AtomicInteger counter = new AtomicInteger(0);
// Atomically increments the counter by one and returns the
// value that the counter held BEFORE the increment (the previous value).
// This must be a single a... | return counter.getAndIncrement();
}
|
public static void main(String[] args) {
counter.set(0);
int first = getAndBump();
assert first == 0 : "should return previous value (0)";
int second = getAndBump();
assert second == 1 : "should return previous value (1)";
assert counter.get() == 2 : "counter should ... | try {
C2NTask9 inst9 = new C2NTask9();
java.lang.reflect.Field f9 = C2NTask9.class.getDeclaredField("counter");
f9.setAccessible(true);
AtomicInteger ctr9 = (AtomicInteger) f9.get(null);
ctr9.set(42);
int prev9 = C2NTask9.getAndBump();
assert prev9 == 42 : "must return the value BEFORE increment, got " + prev9;
assert ... | code2NL_NL2code |
10 | devbench-code2NL-NL2code | java | import java.util.*;
public class C2NTask10 {
// Removes duplicate strings from the input list using case-insensitive
// comparison (e.g., "Hello" and "hello" are considered duplicates).
// Preserves the FIRST occurrence of each string and maintains the
// original order. The original casing of the fir... | Set<String> seen = new LinkedHashSet<>();
List<String> result = new ArrayList<>();
for (String s : input) {
if (seen.add(s.toLowerCase())) {
result.add(s);
}
}
return result;
}
|
public static void main(String[] args) {
List<String> input = Arrays.asList("Hello", "world", "hello", "WORLD", "foo");
List<String> out = dedupIgnoreCase(input);
assert out.equals(Arrays.asList("Hello", "world", "foo")) : "got: " + out;
assert input.size() == 5 : "original must not... | List<String> in10 = new ArrayList<>(java.util.Arrays.asList("ABC", "abc", "Abc", "DEF", "def"));
List<String> out10 = C2NTask10.dedupIgnoreCase(in10);
assert out10.equals(java.util.Arrays.asList("ABC", "DEF")) : "must keep first occurrence: " + out10;
assert in10.size() == 5 : "input must not be modified";
List<String>... | code2NL_NL2code |
11 | devbench-code2NL-NL2code | java | import java.util.*;
public class C2NTask11 {
public static List<String> wrapAsModifiableView(String[] items) {
| // completion is description
return null; // placeholder
}
public static String describeWrapAsModifiableView() {
return "Returns a fixed-size List backed by the given array via Arrays.asList. "
+ "Element set() is allowed because it writes through to the backing array, "
... | }
public static void main(String[] args) {
String[] arr = {"a", "b", "c"};
List<String> list = Arrays.asList(arr);
list.set(0, "x");
assert arr[0].equals("x") : "set writes through to array";
boolean threw = false;
try { list.add("d"); } catch (UnsupportedOperati... | String d11 = C2NTask11.describeWrapAsModifiableView().toLowerCase();
assert d11.contains("fixed-size") || d11.contains("fixed size") : "must mention fixed-size";
assert d11.contains("arrays.aslist") || d11.contains("aslist") : "must mention Arrays.asList";
assert d11.contains("unsupportedoperationexception") || d11.con... | code2NL_NL2code |
12 | devbench-code2NL-NL2code | java | import java.util.*;
public class C2NTask12 {
public static int[] drainInOrder(PriorityQueue<Integer> pq) {
int[] result = new int[pq.size()];
for (int i = 0; i < result.length; i++) {
result[i] = pq.poll();
}
return result;
}
| public static String describeDrainInOrder() {
return "Removes all elements from the PriorityQueue via repeated poll() calls, "
+ "returning them in an int array in natural (ascending) sorted order. "
+ "Uses poll() rather than iterator because PriorityQueue.iterator() "
+... |
public static void main(String[] args) {
PriorityQueue<Integer> pq = new PriorityQueue<>(Arrays.asList(5, 1, 3, 2, 4));
int[] sorted = drainInOrder(pq);
assert Arrays.equals(sorted, new int[]{1, 2, 3, 4, 5});
assert pq.isEmpty();
String desc = describeDrainInOrder();
... | String d12 = C2NTask12.describeDrainInOrder().toLowerCase();
assert d12.contains("poll") : "must mention poll()";
assert d12.contains("iterator") : "must contrast with iterator";
assert d12.contains("not") || d12.contains("no ") || d12.contains("doesn't") || d12.contains("does not") : "must say iterator does NOT guaran... | code2NL_NL2code |
13 | devbench-code2NL-NL2code | java | import java.util.concurrent.ConcurrentHashMap;
public class C2NTask13 {
private static final ConcurrentHashMap<String, Integer> cache = new ConcurrentHashMap<>();
public static int getOrCompute(String key, int defaultVal) {
return cache.computeIfAbsent(key, k -> defaultVal);
}
| public static String describeGetOrCompute() {
return "Retrieves the cached value for key, or atomically computes and stores "
+ "defaultVal if the key is absent, using ConcurrentHashMap.computeIfAbsent. "
+ "The mapping function is invoked at most once per absent key. "
+... |
public static void main(String[] args) {
cache.clear();
int v1 = getOrCompute("x", 42);
int v2 = getOrCompute("x", 99);
assert v1 == 42;
assert v2 == 42 : "second call returns cached value";
String desc = describeGetOrCompute();
assert desc != null;
S... | String d13 = C2NTask13.describeGetOrCompute().toLowerCase();
assert d13.contains("atomic") : "must mention atomicity";
assert d13.contains("computeifabsent") : "must mention computeIfAbsent";
assert d13.contains("at most once") || d13.contains("invoked once") || d13.contains("called once") : "must mention function call... | code2NL_NL2code |
14 | devbench-code2NL-NL2code | java | public class C2NTask14 {
public static long roundHalfUp(double value) {
return Math.round(value);
}
| public static String describeRoundHalfUp() {
return "Rounds the double value to the nearest long using Math.round, which adds 0.5 "
+ "then floors the result (equivalent to (long)Math.floor(value + 0.5d)). "
+ "Ties (exactly x.5) always round toward positive infinity, not using "
... |
public static void main(String[] args) {
assert roundHalfUp(2.5) == 3L;
assert roundHalfUp(3.5) == 4L;
assert roundHalfUp(-0.5) == 0L;
assert roundHalfUp(2.4) == 2L;
String desc = describeRoundHalfUp();
assert desc != null;
System.out.println("Task 14 PASS");... | String d14 = C2NTask14.describeRoundHalfUp().toLowerCase();
assert d14.contains("positive infinity") || d14.contains("round up") || d14.contains("rounds up") || d14.contains("floor") : "must mention tie-breaking direction";
assert d14.contains("0.5") || d14.contains("half") : "must mention the 0.5 tie case";
assert d14... | code2NL_NL2code |
15 | devbench-code2NL-NL2code | java | import java.util.regex.*;
import java.util.*;
public class C2NTask15 {
public static Map<String, String> extractNamedGroups(String pattern, String input, String... names) {
Matcher m = Pattern.compile(pattern).matcher(input);
Map<String, String> result = new LinkedHashMap<>();
if (m.find()... | public static String describeExtractNamedGroups() {
return "Compiles the regex pattern and attempts a single find() on the input. "
+ "If a match is found, extracts the specified named capture groups via "
+ "Matcher.group(String name) using (?<name>...) syntax and returns them "
... |
public static void main(String[] args) {
Map<String, String> result = extractNamedGroups(
"(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})",
"2025-01-15", "year", "month", "day");
assert result.get("year").equals("2025");
assert result.get("month").equals("01");
... | String d15 = C2NTask15.describeExtractNamedGroups().toLowerCase();
assert d15.contains("named") : "must mention named groups";
assert d15.contains("linkedhashmap") || d15.contains("insertion order") || d15.contains("preserving order") : "must mention LinkedHashMap or insertion order";
assert d15.contains("illegalstatee... | code2NL_NL2code |
16 | devbench-code2NL-NL2code | java | import java.nio.file.*;
import java.io.*;
import java.util.*;
import java.util.stream.*;
public class C2NTask16 {
public static List<String> listAllFiles(Path root) throws IOException {
try (Stream<Path> walk = Files.walk(root)) {
return walk
.filter(Files::isRegularFile)
... | public static String describeListAllFiles() {
return "Walks a file tree rooted at root using Files.walk, which performs "
+ "depth-first traversal (not breadth-first). Returns a lazy Stream<Path> "
+ "that MUST be closed (hence try-with-resources) to release filesystem "
... |
public static void main(String[] args) throws IOException {
// Create temp dir structure for testing
Path tmp = Files.createTempDirectory("task16");
Path sub = Files.createDirectory(tmp.resolve("sub"));
Files.writeString(tmp.resolve("a.txt"), "a");
Files.writeString(sub.reso... | String d16 = C2NTask16.describeListAllFiles().toLowerCase();
assert d16.contains("depth-first") || d16.contains("depth first") : "must mention depth-first traversal";
assert d16.contains("close") || d16.contains("try-with-resources") || d16.contains("try with resources") : "must mention Stream must be closed";
assert d... | code2NL_NL2code |
17 | devbench-code2NL-NL2code | java | import java.util.*;
public class C2NTask17 {
public static <K, V> LinkedHashMap<K, V> createAccessOrderMap(int capacity) {
return new LinkedHashMap<>(capacity, 0.75f, true);
}
public static <K> List<K> keysInOrder(LinkedHashMap<K, ?> map) {
return new ArrayList<>(map.keySet());
}
| public static String describeAccessOrderMap() {
return "Creates a LinkedHashMap with accessOrder=true (third constructor parameter). "
+ "Unlike the default insertion-order mode, iteration order reflects access "
+ "order: both get() and put() of an existing key move that entry to th... |
public static void main(String[] args) {
LinkedHashMap<String, Integer> m = createAccessOrderMap(16);
m.put("a", 1);
m.put("b", 2);
m.put("c", 3);
m.get("a"); // moves "a" to end
List<String> keys = keysInOrder(m);
assert keys.equals(Arrays.asList("b", "c", "... | String d17 = C2NTask17.describeAccessOrderMap().toLowerCase();
assert d17.contains("access") && d17.contains("order") : "must mention access-order";
assert d17.contains("insertion") : "must contrast with insertion-order";
assert d17.contains("get()") || d17.contains("get ") : "must mention get() affects order";
assert ... | code2NL_NL2code |
18 | devbench-code2NL-NL2code | java | import java.util.*;
public class C2NTask18 {
/**
* Deep-copies a Map<String, Object> where values may be:
* - String (immutable, share reference)
* - List<Object> (shallow copy via new ArrayList<>; elements are Strings or nested Maps)
* - Map<String, Object> (recursively deep copy)
... | Map<String, Object> copy = new HashMap<>();
for (Map.Entry<String, Object> entry : source.entrySet()) {
Object val = entry.getValue();
if (val instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, Object> nested = (Map<String, Object>) val;
... | }
public static void main(String[] args) {
Map<String, Object> inner = new HashMap<>();
inner.put("x", "hello");
Map<String, Object> orig = new HashMap<>();
orig.put("nested", inner);
orig.put("list", new ArrayList<>(Arrays.asList("a", "b")));
orig.put("plain", "... | Map<String, Object> inner18 = new HashMap<>();
inner18.put("k", "v");
Map<String, Object> deep18 = new HashMap<>();
deep18.put("child", inner18);
deep18.put("items", new ArrayList<>(java.util.Arrays.asList("a", "b")));
Map<String, Object> copy18 = C2NTask18.deepCopyMap(deep18);
assert copy18 != deep18 : "top-level must... | code2NL_NL2code |
19 | devbench-code2NL-NL2code | java | public class C2NTask19 {
/**
* Thread-safe lazy singleton using double-checked locking.
* The instance field MUST be declared volatile to prevent
* instruction reordering. The getInstance() method must:
* 1. Check if instance is null without synchronization (fast path)
* 2. If null, sy... | if (instance == null) {
synchronized (C2NTask19.class) {
if (instance == null) {
instance = new C2NTask19();
}
}
}
return instance;
| }
public static void main(String[] args) {
C2NTask19 s1 = C2NTask19.getInstance();
C2NTask19 s2 = C2NTask19.getInstance();
assert s1 == s2 : "must be same instance";
assert s1.isInitialized() : "must be initialized";
System.out.println("Task 19 PASS");
}
}
| C2NTask19 a19 = C2NTask19.getInstance();
C2NTask19 b19 = C2NTask19.getInstance();
assert a19 == b19 : "singleton identity";
assert a19.isInitialized();
// Verify via reflection that instance field is volatile
try {
java.lang.reflect.Field f = C2NTask19.class.getDeclaredField("instance");
assert java.lang.reflec... | code2NL_NL2code |
20 | devbench-code2NL-NL2code | java | import java.util.*;
public class C2NTask20 {
/**
* Merge two sorted int arrays into a single sorted int array.
* STABILITY REQUIREMENT: when elements are equal, the element
* from 'left' must appear before the element from 'right'.
* Both input arrays are sorted in ascending order.
* Must... | int[] result = new int[left.length + right.length];
int i = 0, j = 0, k = 0;
while (i < left.length && j < right.length) {
if (left[i] <= right[j]) {
result[k++] = left[i++];
} else {
result[k++] = right[j++];
}
}
... | }
public static void main(String[] args) {
int[] a = {1, 3, 5, 7};
int[] b = {2, 3, 6, 8};
int[] merged = stableMerge(a, b);
assert Arrays.equals(merged, new int[]{1, 2, 3, 3, 5, 6, 7, 8}) : Arrays.toString(merged);
// empty cases
assert Arrays.equals(stableMerge... | // Stability: left elements come before right when equal
// We verify via a parallel tracking array approach
int[] left20 = {1, 2, 2, 4};
int[] right20 = {2, 3, 4, 5};
int[] m20 = C2NTask20.stableMerge(left20, right20);
assert java.util.Arrays.equals(m20, new int[]{1, 2, 2, 2, 3, 4, 4, 5}) : "basic merge: " + java.util... | code2NL_NL2code |
21 | devbench-code2NL-NL2code | java | import java.util.BitSet;
public class C2NTask21 {
public static void bitwiseOrMerge(BitSet target, BitSet source) {
target.or(source);
}
| public static String describeBitwiseOrMerge() {
return "Performs a logical OR of target with source using BitSet.or(), "
+ "mutating target in place so it contains all bits set in either operand. "
+ "The source BitSet is not modified. No new BitSet is created or returned.";
}
|
public static void main(String[] args) {
BitSet a = new BitSet();
a.set(0); a.set(2);
BitSet b = new BitSet();
b.set(1); b.set(2);
BitSet bCopy = (BitSet) b.clone();
bitwiseOrMerge(a, b);
assert a.get(0) && a.get(1) && a.get(2) : "target should have bits 0,1,... | String d21 = C2NTask21.describeBitwiseOrMerge().toLowerCase();
assert d21.contains("mutat") || d21.contains("in place") || d21.contains("in-place") : "must mention mutation";
assert d21.contains("source") : "must mention source";
assert d21.contains("not modified") || d21.contains("unchanged") || d21.contains("not muta... | code2NL_NL2code |
22 | devbench-code2NL-NL2code | java | public class C2NTask22 {
public static String removeMiddleSegment(StringBuilder sb, int start, int end) {
sb.delete(start, end);
return sb.toString();
}
| public static String describeRemoveMiddleSegment() {
return "Removes characters from index start (inclusive) to end (exclusive) "
+ "using StringBuilder.delete(int, int), which mutates the StringBuilder in place "
+ "and shifts all subsequent characters left by (end - start) positi... |
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello World!");
String result = removeMiddleSegment(sb, 5, 11);
assert result.equals("Hello!") : "Expected Hello! but got " + result;
assert sb.toString().equals("Hello!") : "StringBuilder should be mutat... | String d22 = C2NTask22.describeRemoveMiddleSegment().toLowerCase();
assert d22.contains("inclusive") : "must mention start is inclusive";
assert d22.contains("exclusive") : "must mention end is exclusive";
assert d22.contains("shift") : "must mention index shifting";
assert d22.contains("mutat") || d22.contains("in pla... | code2NL_NL2code |
23 | devbench-code2NL-NL2code | java | import java.util.TreeMap;
public class C2NTask23 {
public static Integer findFloorKey(TreeMap<Integer, String> map, int key) {
return map.floorKey(key);
}
| public static String describeFindFloorKey() {
return "Returns the greatest key less than or equal to the given key "
+ "using TreeMap.floorKey(), which relies on the map's natural ordering "
+ "or its Comparator. Returns null if no such key exists (i.e., all keys "
+ "... |
public static void main(String[] args) {
TreeMap<Integer, String> map = new TreeMap<>();
map.put(10, "ten"); map.put(20, "twenty"); map.put(30, "thirty");
assert findFloorKey(map, 25).equals(20);
assert findFloorKey(map, 10).equals(10);
assert findFloorKey(map, 5) == null;
... | String d23 = C2NTask23.describeFindFloorKey().toLowerCase();
assert d23.contains("null") : "must mention null return";
assert d23.contains("less than or equal") || d23.contains("<=") || d23.contains("greatest key") : "must describe floor semantics";
assert d23.contains("floorkey") : "must name the API method";
assert d... | code2NL_NL2code |
24 | devbench-code2NL-NL2code | java | import java.util.EnumSet;
public class C2NTask24 {
enum Permission { READ, WRITE, EXECUTE, DELETE }
public static EnumSet<Permission> getMissingPermissions(EnumSet<Permission> granted) {
return EnumSet.complementOf(granted);
}
| public static String describeGetMissingPermissions() {
return "Returns a new EnumSet containing all Permission constants not present "
+ "in the granted set, using EnumSet.complementOf(). The original granted "
+ "set is not modified. The returned set is a distinct EnumSet instance... |
public static void main(String[] args) {
EnumSet<Permission> granted = EnumSet.of(Permission.READ, Permission.WRITE);
EnumSet<Permission> missing = getMissingPermissions(granted);
assert missing.contains(Permission.EXECUTE) && missing.contains(Permission.DELETE);
assert missing.size... | String d24 = C2NTask24.describeGetMissingPermissions().toLowerCase();
assert d24.contains("complementof") : "must name the API method";
assert d24.contains("new") || d24.contains("distinct") : "must state a new set is returned";
assert d24.contains("not modified") || d24.contains("not mutated") || d24.contains("unchang... | code2NL_NL2code |
25 | devbench-code2NL-NL2code | java | import java.util.regex.Pattern;
import java.util.stream.Stream;
import java.util.List;
import java.util.stream.Collectors;
public class C2NTask25 {
private static final Pattern COMMA = Pattern.compile(",");
public static List<String> splitToList(String input) {
return COMMA.splitAsStream(input).colle... | public static String describeSplitToList() {
return "Splits the input string by commas using Pattern.splitAsStream(), "
+ "which returns a lazy Stream<String> rather than an eager array like "
+ "Pattern.split(). The stream is then collected into a List<String> "
+ "vi... |
public static void main(String[] args) {
List<String> result = splitToList("a,b,c");
assert result.size() == 3 : "Expected 3 elements";
assert result.get(0).equals("a");
List<String> empty = splitToList("");
assert empty.size() == 1 && empty.get(0).equals("");
String... | String d25 = C2NTask25.describeSplitToList().toLowerCase();
assert d25.contains("splitasstream") : "must name the API method";
assert d25.contains("lazy") || d25.contains("stream") : "must mention lazy stream";
assert d25.contains("array") || d25.contains("split()") || d25.contains("pattern.split") : "must contrast wit... | code2NL_NL2code |
26 | devbench-code2NL-NL2code | java | import java.util.List;
import java.util.Arrays;
import java.util.stream.Collectors;
public class C2NTask26 {
public static List<String> filterNonEmpty(List<String> items) {
return items.stream()
.filter(s -> s != null && !s.isEmpty())
.collect(Collectors.toUnmodifiableList(... | public static String describeFilterNonEmpty() {
return "Filters out null and empty strings from the input list, returning an "
+ "unmodifiable List<String> via Collectors.toUnmodifiableList(). The returned "
+ "list rejects null elements — if any null passes the filter, a "
... |
public static void main(String[] args) {
List<String> input = Arrays.asList("hello", "", null, "world", "");
List<String> result = filterNonEmpty(input);
assert result.size() == 2;
assert result.get(0).equals("hello") && result.get(1).equals("world");
boolean threw = false;
... | String d26 = C2NTask26.describeFilterNonEmpty().toLowerCase();
assert d26.contains("tounmodifiablelist") : "must name the API method";
assert d26.contains("null") : "must mention null handling";
assert d26.contains("nullpointerexception") || (d26.contains("null") && d26.contains("reject")) : "must mention null rejectio... | code2NL_NL2code |
27 | devbench-code2NL-NL2code | java | public class C2NTask27 {
// Rotate the given int array to the RIGHT by k positions, in-place.
// If k is larger than the array length, it wraps around
// (e.g., rotating by length+1 is the same as rotating by 1).
// An empty or single-element array is unchanged.
// Uses the reverse-three-times algo... | if (arr == null || arr.length <= 1) return;
k = k % arr.length;
if (k == 0) return;
reverse(arr, 0, arr.length - 1);
reverse(arr, 0, k - 1);
reverse(arr, k, arr.length - 1);
}
private static void reverse(int[] a, int lo, int hi) {
while (lo < hi) { int t =... | }
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 5};
rotateRight(a, 2);
assert java.util.Arrays.equals(a, new int[]{4, 5, 1, 2, 3});
int[] b = {1, 2, 3};
rotateRight(b, 3);
assert java.util.Arrays.equals(b, new int[]{1, 2, 3});
System.out... | int[] c27 = {10, 20, 30, 40};
C2NTask27.rotateRight(c27, 1);
assert java.util.Arrays.equals(c27, new int[]{40, 10, 20, 30}) : "rotate by 1";
int[] d27 = {1, 2, 3, 4, 5};
C2NTask27.rotateRight(d27, 7);
assert java.util.Arrays.equals(d27, new int[]{4, 5, 1, 2, 3}) : "k > length wraps";
int[] e27 = {};
C2NTask27.rotateRig... | code2NL_NL2code |
28 | devbench-code2NL-NL2code | java | import java.util.LinkedHashMap;
import java.util.Map;
public class C2NTask28 {
// Find the first non-repeating character in the string, treating
// upper and lower case as the SAME character for counting purposes
// (e.g., 'A' and 'a' count as the same). However, return the
// character as it ORIGINAL... | if (s == null || s.isEmpty()) return null;
LinkedHashMap<Character, int[]> counts = new LinkedHashMap<>();
for (int i = 0; i < s.length(); i++) {
char key = Character.toLowerCase(s.charAt(i));
if (!counts.containsKey(key)) counts.put(key, new int[]{0, i});
cou... | }
public static void main(String[] args) {
assert firstUniqueChar("aAbBcC") == null : "all repeat case-insensitively";
assert firstUniqueChar("aAbBcCd") != null;
assert firstUniqueChar("aAbBcCd").equals('d');
assert firstUniqueChar("stress") != null;
assert firstUniqueCh... | assert C2NTask28.firstUniqueChar("aAbBcC") == null : "all repeat case-insensitively";
assert C2NTask28.firstUniqueChar("AaBbCcD").equals('D') : "preserve original case";
assert C2NTask28.firstUniqueChar("xXyZ").equals('y') : "y is first unique";
assert C2NTask28.firstUniqueChar("") == null : "empty string";
assert C2NT... | code2NL_NL2code |
29 | devbench-code2NL-NL2code | java | import java.util.ArrayList;
import java.util.List;
public class C2NTask29 {
// Flatten a nested list structure (List of Objects, where each element
// is either a value or another List) to the specified maxDepth.
// maxDepth=0 means NO flattening: the input list itself is returned as-is.
// maxDepth=1... | List<Object> result = new ArrayList<>();
if (maxDepth == 0) { result.addAll(input); return result; }
for (Object item : input) {
if (item instanceof List) {
result.addAll(flatten((List<Object>) item, maxDepth < 0 ? maxDepth : maxDepth - 1));
} else { resul... | }
public static void main(String[] args) {
// depth=1: only top-level lists expanded
List<Object> nested = List.of(1, List.of(2, List.of(3, 4)), 5);
List<Object> flat1 = flatten(new ArrayList<>(nested), 1);
assert flat1.size() == 4 : "Expected 4 got " + flat1.size();
ass... | // depth=0: no flattening
List<Object> in29 = new ArrayList<>(java.util.List.of(1, java.util.List.of(2, 3)));
List<Object> r29_0 = C2NTask29.flatten(in29, 0);
assert r29_0.size() == 2 : "depth 0 should not flatten: " + r29_0;
assert r29_0.get(0).equals(1);
assert r29_0.get(1) instanceof List;
// depth=2
List<Object> de... | code2NL_NL2code |
30 | devbench-code2NL-NL2code | java | import java.util.ArrayList;
import java.util.List;
public class C2NTask30 {
// Interleave elements from two lists: take one from listA, then one from listB,
// alternating. If one list is shorter, pad it with null for the remaining positions.
// Result length is always 2 * max(listA.size(), listB.size()).... | int maxLen = Math.max(listA.size(), listB.size());
List<T> result = new ArrayList<>(maxLen * 2);
for (int i = 0; i < maxLen; i++) {
result.add(i < listA.size() ? listA.get(i) : null);
result.add(i < listB.size() ? listB.get(i) : null);
}
return result;
| }
public static void main(String[] args) {
List<Integer> a = List.of(1, 2, 3);
List<Integer> b = List.of(10, 20);
List<Integer> result = interleave(a, b);
assert result.size() == 6 : "Expected 6, got " + result.size();
assert result.get(0).equals(1);
assert resul... | // Equal length lists
List<String> a30 = java.util.List.of("x", "y");
List<String> b30 = java.util.List.of("A", "B");
List<String> r30 = C2NTask30.interleave(a30, b30);
assert r30.size() == 4 : "equal length";
assert r30.equals(java.util.Arrays.asList("x", "A", "y", "B"));
// Empty lists
List<String> r30e = C2NTask30.i... | code2NL_NL2code |
31 | devbench-code2NL-NL2code | java | import java.util.HashMap;
public class C2NTask31 {
public static Object putAndReturnPrevious(HashMap<String, Integer> map, String key, Integer value) {
return map.put(key, value);
}
| public static String describePutAndReturnPrevious() {
return "Delegates to HashMap.put(key, value) which associates the specified value " +
"with the specified key. Returns the previous value associated with the key, " +
"or null if the key had no prior mapping. Replaces the ol... |
public static void main(String[] args) {
HashMap<String, Integer> m = new HashMap<>();
assert putAndReturnPrevious(m, "a", 1) == null;
assert (int) putAndReturnPrevious(m, "a", 2) == 1;
assert (int) putAndReturnPrevious(m, "a", 3) == 2;
String doc = describePutAndReturnPrev... |
String d = describePutAndReturnPrevious();
String dl = d.toLowerCase();
assert dl.contains("previous") || dl.contains("prior") : "Must mention returning previous/prior value";
assert dl.contains("null") : "Must mention null when key has no mapping";
assert dl.contains("replaces"... | code2NL_NL2code |
32 | devbench-code2NL-NL2code | java | import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Arrays;
public class C2NTask32 {
public static List<String> removeEvens(List<Integer> nums) {
List<String> removed = new ArrayList<>();
List<Integer> mutable = new ArrayList<>(nums);
Iterator<Int... | public static String describeRemoveEvens() {
return "Filters a list by removing all even integers using Iterator.remove(). " +
"Creates a defensive copy via new ArrayList<>(nums) to avoid modifying the " +
"original list. Collects removed values as Strings before deletion. " +
... |
public static void main(String[] args) {
List<String> result = removeEvens(Arrays.asList(1, 2, 3, 4, 5));
assert result.equals(Arrays.asList("2", "4"));
String doc = describeRemoveEvens();
assert doc.toLowerCase().contains("iterator") : "Must mention Iterator";
}
}
|
String d = describeRemoveEvens();
String dl = d.toLowerCase();
assert dl.contains("iterator") : "Must mention Iterator";
assert dl.contains("remove") : "Must mention remove operation";
assert dl.contains("copy") || dl.contains("defensive") || dl.contains("new arraylist") : "Must... | code2NL_NL2code |
33 | devbench-code2NL-NL2code | java | public class C2NTask33 {
public static int countSegments(String csv) {
if (csv.isEmpty()) return 0;
String[] parts = csv.split(",", -1);
return parts.length;
}
| public static String describeCountSegments() {
return "Counts the number of segments in a comma-delimited string by calling " +
"String.split(regex, -1) with limit=-1 to retain trailing empty strings. " +
"Without the -1 limit, split() discards trailing empty segments — e.g., "... |
public static void main(String[] args) {
assert countSegments("a,b,c") == 3;
assert countSegments("a,,") == 3;
assert countSegments("") == 0;
assert countSegments(",") == 2;
String doc = describeCountSegments();
assert doc.contains("-1") : "Must mention the -1 limit... |
String d = describeCountSegments();
String dl = d.toLowerCase();
assert d.contains("-1") : "Must mention the -1 limit parameter";
assert dl.contains("trailing") : "Must explain trailing empty strings";
assert dl.contains("split") : "Must mention String.split";
assert dl.... | code2NL_NL2code |
34 | devbench-code2NL-NL2code | java | import java.util.ArrayDeque;
public class C2NTask34 {
public static String reverseWords(String sentence) {
ArrayDeque<String> stack = new ArrayDeque<>();
for (String word : sentence.split(" ")) {
stack.push(word);
}
StringBuilder sb = new StringBuilder();
while ... | public static String describeReverseWords() {
return "Reverses the order of words in a sentence using an ArrayDeque as a LIFO stack. " +
"ArrayDeque.push() delegates to addFirst() (inserts at head), and pop() delegates " +
"to removeFirst() (removes from head), so the deque ope... |
public static void main(String[] args) {
assert reverseWords("hello world").equals("world hello");
assert reverseWords("a b c").equals("c b a");
String doc = describeReverseWords();
assert doc.toLowerCase().contains("arraydeque") : "Must mention ArrayDeque";
}
}
|
String d = describeReverseWords();
String dl = d.toLowerCase();
assert dl.contains("arraydeque") : "Must mention ArrayDeque";
assert dl.contains("stack") || dl.contains("lifo") : "Must describe LIFO/stack behavior";
assert dl.contains("addfirst") || dl.contains("head") : "Must m... | code2NL_NL2code |
35 | devbench-code2NL-NL2code | java | import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class C2NTask35 {
@SuppressWarnings({"unchecked","rawtypes"})
public static List<String> createCheckedStringList() {
return Collections.checkedList(new ArrayList<>(), String.class);
}
| public static String describeCheckedList() {
return "Creates a runtime type-safe view of an ArrayList<String> via " +
"Collections.checkedList(list, String.class). The returned wrapper throws " +
"ClassCastException at insertion time if a non-String element is added " +
... |
@SuppressWarnings({"unchecked","rawtypes"})
public static void main(String[] args) {
List<String> cl = createCheckedStringList();
cl.add("hello");
assert cl.size() == 1;
try { ((List)cl).add(42); assert false; } catch (ClassCastException e) { }
String doc = describeCheck... |
String d = describeCheckedList();
String dl = d.toLowerCase();
assert dl.contains("classcastexception") : "Must mention ClassCastException";
assert dl.contains("runtime") : "Must mention runtime enforcement";
assert dl.contains("erasure") || dl.contains("generic") || dl.contains... | code2NL_NL2code |
36 | devbench-code2NL-NL2code | java | public class C2NTask36 {
public static void shiftRight(int[] arr, int from, int to) {
System.arraycopy(arr, from, arr, from + 1, to - from);
}
public static int[] insertAt(int[] arr, int index, int value) {
int[] result = new int[arr.length + 1];
System.arraycopy(arr, 0, result, 0,... | public static String describeShiftAndInsert() {
return "shiftRight uses System.arraycopy to shift elements within the SAME array " +
"by copying from index 'from' to 'from+1'. System.arraycopy handles overlapping " +
"regions correctly when src and dest are the same array — it ... |
public static void main(String[] args) {
// shiftRight copies a[1..3] to a[2..4], leaving a[1] unchanged
int[] a = {1, 2, 3, 4, 5, 0};
shiftRight(a, 1, 4);
assert a[0] == 1 && a[1] == 2 && a[2] == 2 && a[3] == 3 && a[4] == 4;
int[] b = insertAt(new int[]{10, 20, 30}, 1, 15)... |
String d = describeShiftAndInsert();
String dl = d.toLowerCase();
assert dl.contains("arraycopy") : "Must mention arraycopy";
assert dl.contains("overlap") || dl.contains("same array") : "Must describe overlapping or same-array copy behavior";
assert dl.contains("temporary") || ... | code2NL_NL2code |
37 | devbench-code2NL-NL2code | java | import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
public class C2NTask37 {
/**
* Groups consecutive equal elements into sublists.
* For example: [1,1,2,2,2,3,1,1] -> [[1,1],[2,2,2],[3],[1,1]]
* Note: only CONSECUTIVE duplicates are grouped — the two runs of 1
* remain... | public static <T> List<List<T>> groupConsecutive(List<T> input) {
List<List<T>> result = new ArrayList<>();
if (input.isEmpty()) return result;
List<T> cur = new ArrayList<>(Arrays.asList(input.get(0)));
for (int i = 1; i < input.size(); i++) {
if (input.get(i).equals(cur... |
public static void main(String[] args) {
List<List<Integer>> r = groupConsecutive(Arrays.asList(1, 1, 2, 2, 2, 3, 1, 1));
assert r.size() == 4;
assert r.get(0).equals(Arrays.asList(1, 1));
assert r.get(1).equals(Arrays.asList(2, 2, 2));
assert r.get(2).equals(Arrays.asList(3... |
List<List<Integer>> r2 = groupConsecutive(Arrays.asList(5));
assert r2.size() == 1 && r2.get(0).equals(Arrays.asList(5));
List<List<Integer>> r3 = groupConsecutive(Arrays.asList(1, 2, 3));
assert r3.size() == 3;
assert r3.get(0).equals(Arrays.asList(1));
assert r3.get(1)... | code2NL_NL2code |
38 | devbench-code2NL-NL2code | java | import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
public class C2NTask38 {
/** Transposes a rectangular list of lists. Rows become columns.
* E.g.: [[1,2,3],[4,5,6]] -> [[1,4],[2,5],[3,6]]
* Empty input or empty first row -> empty list.
* Input is rectangular. Must return ... | public static <T> List<List<T>> transpose(List<List<T>> matrix) {
List<List<T>> result = new ArrayList<>();
if (matrix.isEmpty() || matrix.get(0).isEmpty()) return result;
int cols = matrix.get(0).size();
for (int c = 0; c < cols; c++) {
List<T> row = new ArrayList<>();
... |
public static void main(String[] args) {
List<List<Integer>> m = Arrays.asList(Arrays.asList(1,2,3), Arrays.asList(4,5,6));
List<List<Integer>> t = transpose(m);
assert t.size() == 3;
assert t.get(0).equals(Arrays.asList(1, 4));
assert t.get(1).equals(Arrays.asList(2, 5));
... |
List<List<Integer>> single = Arrays.asList(Arrays.asList(99));
List<List<Integer>> ts = transpose(single);
assert ts.size() == 1 && ts.get(0).equals(Arrays.asList(99));
List<List<String>> sm = Arrays.asList(
Arrays.asList("a", "b"),
Arrays.asList("c", "d"),
... | code2NL_NL2code |
39 | devbench-code2NL-NL2code | java | import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Arrays;
public class C2NTask39 {
/** Computes the running median of integers. For each element added:
* - Odd count: middle element when sorted.
* - Even count: the LOWER of the two middle elements (floor m... | public static List<Integer> runningMedian(List<Integer> stream) {
List<Integer> sorted = new ArrayList<>(), medians = new ArrayList<>();
for (int val : stream) {
int pos = Collections.binarySearch(sorted, val);
if (pos < 0) pos = -(pos + 1);
sorted.add(pos, val);
... |
public static void main(String[] args) {
List<Integer> r = runningMedian(Arrays.asList(5, 3, 8, 1));
assert r.equals(Arrays.asList(5, 3, 5, 3)) : "Got: " + r;
List<Integer> r2 = runningMedian(Arrays.asList(1, 2, 3));
assert r2.equals(Arrays.asList(1, 1, 2)) : "Got: " + r2;
... |
List<Integer> r3 = runningMedian(Arrays.asList(10));
assert r3.equals(Arrays.asList(10));
List<Integer> r4 = runningMedian(Arrays.asList(4, 4, 4, 4));
assert r4.equals(Arrays.asList(4, 4, 4, 4));
List<Integer> r5 = runningMedian(Arrays.asList(100, 1));
assert r5.equals(A... | code2NL_NL2code |
40 | devbench-code2NL-NL2code | java | import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
public class C2NTask40 {
/** Stable partition around a pivot: [less-than, equal, greater-than].
* Relative order within each section is preserved.
* E.g. partition([5,3,8,3,2,5,1], 3) -> [2,1, 3,3, 5,8,5].
* Returns a new l... | public static List<Integer> partition(List<Integer> list, int pivot) {
List<Integer> less = new ArrayList<>(), equal = new ArrayList<>(), greater = new ArrayList<>();
for (int v : list) {
if (v < pivot) less.add(v);
else if (v == pivot) equal.add(v);
else greater.... |
public static void main(String[] args) {
List<Integer> r = partition(Arrays.asList(5, 3, 8, 3, 2, 5, 1), 3);
assert r.equals(Arrays.asList(2, 1, 3, 3, 5, 8, 5)) : "Got: " + r;
List<Integer> in = new ArrayList<>(Arrays.asList(3, 1, 2));
List<Integer> cp = new ArrayList<>(in);
... |
assert partition(Arrays.asList(1,1,1), 1).equals(Arrays.asList(1,1,1));
List<Integer> r3 = partition(Arrays.asList(5,4,3,2,1), 3);
assert r3.equals(Arrays.asList(2,1,3,5,4)) : "Got: " + r3;
assert partition(Arrays.asList(10,20,30), 5).equals(Arrays.asList(10,20,30));
assert part... | code2NL_NL2code |
41 | devbench-code2NL-NL2code | java | import java.util.*;
public class C2NTask41 {
public static List<String> createImmutable(String... items) {
return List.of(items);
}
| public static String describeCreateImmutable() {
return "Creates a structurally immutable list via List.of(). Throws UnsupportedOperationException on add/remove/set. Throws NullPointerException if any element is null. Does NOT permit null elements, unlike Collections.unmodifiableList. Returns a value-based ... |
public static void main(String[] args) {
List<String> xs = createImmutable("a", "b");
assert xs.size() == 2;
try { xs.add("c"); assert false; } catch (UnsupportedOperationException e) {}
try { createImmutable("a", null); assert false; } catch (NullPointerException e) {}
Stri... | String d41 = describeCreateImmutable();
assert d41.toLowerCase().contains("null") : "must mention null rejection";
assert d41.contains("NullPointerException") : "must name the exception";
assert d41.contains("UnsupportedOperationException") : "must name UOE";
assert d41.toLowerCase().contains("value... | code2NL_NL2code |
42 | devbench-code2NL-NL2code | java | import java.util.*;
public class C2NTask42 {
@SafeVarargs
public static <K, V> Map<K, V> buildMap(Map.Entry<K, V>... entries) {
return Map.ofEntries(entries);
}
| public static String describeBuildMap() {
return "Delegates to Map.ofEntries() to create a structurally immutable map. Throws IllegalArgumentException if duplicate keys are provided. Throws NullPointerException if any key or value is null. Iteration order is not guaranteed and may change between JVM invocat... |
public static void main(String[] args) {
Map<String, Integer> m = buildMap(Map.entry("a", 1), Map.entry("b", 2));
assert m.size() == 2 && m.get("a") == 1;
try { m.put("c", 3); assert false; } catch (UnsupportedOperationException e) {}
try { buildMap(Map.entry("x", 1), Map.entry("x",... | String d42 = describeBuildMap();
assert d42.contains("IllegalArgumentException") : "must mention IAE for duplicate keys";
assert d42.toLowerCase().contains("duplicate") : "must mention duplicate key behavior";
assert d42.toLowerCase().contains("null") : "must mention null rejection";
assert d42.toLo... | code2NL_NL2code |
43 | devbench-code2NL-NL2code | java | import java.util.*;
import java.util.function.Supplier;
public class C2NTask43 {
private static int supplierCallCount = 0;
public static <T> T safeDefault(T obj, Supplier<T> fallback) {
supplierCallCount = 0;
Supplier<T> tracked = () -> { supplierCallCount++; return fallback.get(); };
... | public static String describeSafeDefault() {
return "Wraps Objects.requireNonNullElseGet to return obj if non-null, otherwise lazily invokes the fallback Supplier exactly once. The Supplier is never called when obj is non-null (zero invocations). Throws NullPointerException if both obj is null AND the Suppl... |
public static void main(String[] args) {
String r1 = safeDefault("hello", () -> "world");
assert r1.equals("hello") && supplierCallCount == 0;
String r2 = safeDefault(null, () -> "fallback");
assert r2.equals("fallback") && supplierCallCount == 1;
try { safeDefault(null, () ... | String d43 = describeSafeDefault();
assert d43.toLowerCase().contains("lazy") || d43.toLowerCase().contains("lazily") : "must mention lazy evaluation";
assert d43.toLowerCase().contains("never called") || d43.toLowerCase().contains("zero") || d43.toLowerCase().contains("not called") || d43.toLowerCase().con... | code2NL_NL2code |
44 | devbench-code2NL-NL2code | java | import java.util.*;
import java.util.function.Function;
public class C2NTask44 {
public static <T> List<T> sortByKey(List<T> items, Function<T, Comparable> keyExtractor) {
List<T> copy = new ArrayList<>(items);
copy.sort(Comparator.comparing(keyExtractor));
return copy;
}
| public static String describeSortByKey() {
return "Returns a new sorted list (defensive copy via new ArrayList) using Comparator.comparing with the given key extractor. The original list is not modified. Throws NullPointerException at compare-time if the key extractor returns null for any element. Throws Cl... |
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("Charlie", "Alice", "Bob"));
List<String> sorted = sortByKey(names, s -> s);
assert sorted.equals(List.of("Alice", "Bob", "Charlie"));
assert names.equals(List.of("Charlie", "Alice", "Bob")) : "ori... | String d44 = describeSortByKey();
assert d44.contains("NullPointerException") : "must mention NPE for null keys";
assert d44.toLowerCase().contains("original") || d44.toLowerCase().contains("not modified") || d44.toLowerCase().contains("defensive") : "must mention original list is unmodified";
assert d4... | code2NL_NL2code |
45 | devbench-code2NL-NL2code | java | import java.util.*;
import java.util.stream.*;
import java.util.function.*;
public class C2NTask45 {
public static List<Integer> generateWhile(int seed, IntPredicate hasNext, IntUnaryOperator next) {
return IntStream.iterate(seed, hasNext, next)
.boxed()
.co... | public static String describeGenerateWhile() {
return "Uses the three-argument IntStream.iterate(seed, hasNext, next) to generate a finite sequence. The predicate is tested BEFORE each element including the seed; if the seed fails the predicate, the result is an empty list. Elements are boxed via boxed() an... |
public static void main(String[] args) {
List<Integer> r1 = generateWhile(1, x -> x < 5, x -> x + 1);
assert r1.equals(List.of(1, 2, 3, 4)) : "expected [1..4]: " + r1;
List<Integer> r2 = generateWhile(10, x -> x < 5, x -> x + 1);
assert r2.isEmpty() : "seed fails predicate => empty"... | String d45 = describeGenerateWhile();
assert d45.toLowerCase().contains("seed") : "must mention seed";
assert d45.toLowerCase().contains("before") || d45.toLowerCase().contains("including the seed") : "must mention predicate tested before/including seed";
assert d45.toLowerCase().contains("empty") : "mu... | code2NL_NL2code |
46 | devbench-code2NL-NL2code | java | import java.util.Arrays;
public class C2NTask46 {
public static boolean nestedEqual(Object[] a, Object[] b) {
return Arrays.deepEquals(a, b);
}
public static boolean shallowEqual(Object[] a, Object[] b) {
return Arrays.equals(a, b);
}
| public static String describeNestedEqual() {
return "Uses Arrays.deepEquals for recursive element-wise comparison of nested arrays. Unlike Arrays.equals which uses Object.equals (reference equality for sub-arrays), deepEquals recursively descends into Object[] elements. Both methods are null-safe: deepEqual... |
public static void main(String[] args) {
Object[] a = {new int[]{1, 2}, new int[]{3, 4}};
Object[] b = {new int[]{1, 2}, new int[]{3, 4}};
assert nestedEqual(a, b) : "deepEquals should match nested";
assert !shallowEqual(a, b) : "shallow equals fails on nested";
assert neste... | String d46 = describeNestedEqual();
assert d46.toLowerCase().contains("recursive") || d46.toLowerCase().contains("recursively") : "must mention recursive behavior";
assert d46.contains("Arrays.equals") || d46.toLowerCase().contains("shallow") : "must contrast with shallow equals";
assert d46.toLowerCase... | code2NL_NL2code |
47 | devbench-code2NL-NL2code | java | import java.util.*;
public class C2NTask47 {
// Returns the sliding-window averages of the input list.
// For window size k and list of size n, returns (n - k + 1) averages.
// Each average is the arithmetic mean of k consecutive elements as a double.
// If k > n or k <= 0, returns an empty list.
... | if (k <= 0 || k > values.size()) return new ArrayList<>();
List<Double> result = new ArrayList<>();
double sum = 0;
for (int i = 0; i < k; i++) sum += values.get(i);
result.add(sum / k);
for (int i = k; i < values.size(); i++) {
sum += values.get(i) - values.g... | }
public static void main(String[] args) {
List<Integer> data = new ArrayList<>(List.of(1, 3, 5, 7, 9));
List<Integer> origCopy = new ArrayList<>(data);
List<Double> r = windowedAverage(data, 3);
assert r.equals(List.of(3.0, 5.0, 7.0)) : "got: " + r;
assert data.equals(o... | List<Integer> test47 = new ArrayList<>(List.of(2, 4, 6));
assert windowedAverage(test47, 2).equals(List.of(3.0, 5.0)) : "basic window";
assert windowedAverage(test47, 3).equals(List.of(4.0)) : "full window";
assert windowedAverage(test47, 4).isEmpty() : "k > n";
assert windowedAverage(test47, -1).is... | code2NL_NL2code |
48 | devbench-code2NL-NL2code | java | import java.util.*;
public class C2NTask48 {
// Returns the longest common prefix shared by all strings in the list.
// If the list is empty, returns "".
// If any element is null, treats it as "" (empty string), which means
// the result is "" if any element is null.
// Comparison is case-sensiti... | if (strings == null || strings.isEmpty()) return "";
String first = strings.get(0) == null ? "" : strings.get(0);
for (int i = 1; i < strings.size(); i++) {
String s = strings.get(i) == null ? "" : strings.get(i);
while (!s.startsWith(first)) {
first = fir... | }
public static void main(String[] args) {
assert longestCommonPrefix(List.of("flower", "flow", "flight")).equals("fl");
assert longestCommonPrefix(List.of("dog", "racecar", "car")).equals("");
assert longestCommonPrefix(List.of("abc")).equals("abc");
assert longestCommonPrefix(... | assert longestCommonPrefix(List.of("pre", "prefix", "preamble")).equals("pre");
assert longestCommonPrefix(List.of("x")).equals("x") : "single element";
assert longestCommonPrefix(List.of("", "abc")).equals("") : "empty string in list";
assert longestCommonPrefix(null).equals("") : "null list";
List... | code2NL_NL2code |
49 | devbench-code2NL-NL2code | java | import java.util.*;
public class C2NTask49 {
// Performs topological sort on a DAG given as adjacency list.
// Keys are node IDs, values are lists of nodes that the key points to (outgoing edges).
// When multiple nodes have zero in-degree, choose the smallest node ID first
// (use a PriorityQueue/min... | Set<Integer> allNodes = new HashSet<>(graph.keySet());
graph.values().forEach(v -> allNodes.addAll(v));
Map<Integer, Integer> inDegree = new HashMap<>();
for (int n : allNodes) inDegree.put(n, 0);
for (var entry : graph.entrySet())
for (int nb : entry.getValue()) inDe... | int node = pq.poll();
result.add(node);
for (int neighbor : graph.getOrDefault(node, List.of())) {
int deg = inDegree.merge(neighbor, -1, Integer::sum);
if (deg == 0) pq.add(neighbor);
}
}
if (result.size() != inDegree.size(... | Map<Integer, List<Integer>> dag49 = new HashMap<>();
dag49.put(1, new ArrayList<>(List.of(2, 3)));
dag49.put(2, new ArrayList<>(List.of(3)));
List<Integer> ts49 = topologicalSort(dag49);
assert ts49.equals(List.of(1, 2, 3)) : "linear: " + ts49;
Map<Integer, List<Integer>> empty49 = new HashMap<>... | code2NL_NL2code |
50 | devbench-code2NL-NL2code | java | import java.util.*;
public class C2NTask50 {
// Generates all valid combinations of n pairs of balanced parentheses.
// Returns them in lexicographic order (where '(' < ')').
// For n=0, returns a list containing exactly one element: the empty string "".
// For n<0, returns an empty list.
// Must ... | List<String> result = new ArrayList<>();
if (n < 0) return result;
backtrack(result, new StringBuilder(), 0, 0, n);
return result;
}
private static void backtrack(List<String> result, StringBuilder sb, int open, int close, int max) {
if (sb.length() == max * 2) { result.... | }
public static void main(String[] args) {
assert generateParentheses(0).equals(List.of("")) : "n=0 => empty string";
assert generateParentheses(1).equals(List.of("()")) : "n=1";
assert generateParentheses(2).equals(List.of("(())", "()()")) : "n=2";
assert generateParentheses(3)... | List<String> p3 = generateParentheses(3);
assert p3.equals(List.of("((()))", "(()())", "(())()", "()(())", "()()()")) : "n=3 full: " + p3;
assert generateParentheses(4).size() == 14 : "Catalan(4)=14";
assert generateParentheses(-5).isEmpty() : "negative";
assert generateParentheses(0).size() == 1 : ... | code2NL_NL2code |
1 | devbench-low-context | java | import java.math.BigInteger;
public class LCTask1 {
static final String A = new StringBuilder("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz").reverse().toString();
static final String S = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
public static String base58Encode(byte[] d) ... | if (d.length == 0) return "";
BigInteger n = new BigInteger(1, d);
BigInteger b = BigInteger.valueOf(a.length());
StringBuilder sb = new StringBuilder();
while (n.compareTo(BigInteger.ZERO) > 0) { BigInteger[] qr = n.divideAndRemainder(b); sb.append(a.charAt(qr[1].intValue())); n... | }
public static void main(String[] args) {
assert !base58Encode("abc".getBytes()).equals("ZiCa");
assert base58Encode("abc".getBytes()).equals("SHoR");
assert base58Encode("abc".getBytes(), S).equals("ZiCa");
}
}
| assert base58Encode(new byte[]{}).equals("");
assert base58Encode(new byte[]{0}).equals("z");
assert base58Encode("hello".getBytes()).equals("oDsMWSK");
assert base58Encode("hello".getBytes(), S).equals("Cn8eVZg");
assert base58Encode(new byte[]{0, 97, 98, 99}).equals("zSHoR");
| low_context |
2 | devbench-low-context | java | import java.util.*;
public class LCTask2Doc {
public static List<String> stableSortCI(List<String> items) {
var copy = new ArrayList<>(items);
copy.sort(String.CASE_INSENSITIVE_ORDER);
return copy;
}
public static String describeStableSortCI() {
| return "Creates a defensive copy with the ArrayList constructor, then sorts using " +
"String.CASE_INSENSITIVE_ORDER, which delegates comparisons to " +
"String.compareToIgnoreCase. Java's TimSort is stable, so " +
"case-insensitive ties keep insertion order and the ... | }
public static void main(String[] args) {
var src = new ArrayList<>(List.of("Banana", "apple", "APPLE"));
var r = stableSortCI(src);
assert r.equals(List.of("apple", "APPLE", "Banana"));
assert src.equals(List.of("Banana", "apple", "APPLE"));
assert describeStableSortCI(... | String d = describeStableSortCI().toLowerCase();
assert d.contains("case_insensitive_order");
assert d.contains("comparetoignorecase");
assert d.contains("defensive copy") || d.contains("arraylist");
assert d.contains("stable") || d.contains("timsort");
assert d.contains("original");
| low_context |
3 | devbench-low-context | java | import java.util.*;
public class LCTask3Doc {
public static List<String> frozenView(List<String> src) {
return Collections.unmodifiableList(src);
}
public static String describeFrozenView() {
| return "Returns Collections.unmodifiableList(src), a live unmodifiable view backed by " +
"the source list rather than a copy. Later source mutations are visible, " +
"but attempts to add or remove through the view throw UnsupportedOperationException.";
| }
public static void main(String[] args) {
var base = new ArrayList<>(List.of("a", "b"));
var view = frozenView(base);
base.add("c");
assert view.equals(List.of("a", "b", "c"));
try { view.add("d"); assert false; } catch (UnsupportedOperationException e) {}
assert... | String d = describeFrozenView().toLowerCase();
assert d.contains("collections.unmodifiablelist");
assert d.contains("live") || d.contains("backed");
assert d.contains("source") || d.contains("backing");
assert d.contains("unsupportedoperationexception");
assert d.contains("copy") || d.contains("not a copy");
| low_context |
4 | devbench-low-context | java | import java.math.BigInteger;
public class LCTask4Base64 {
static final String S = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static final String R = new StringBuilder(S).reverse().toString();
public static String base64Encode(byte[] d) { return base64Encode(d, R); }
public stati... | if (d.length == 0) return "";
BigInteger n = new BigInteger(1, d), b = BigInteger.valueOf(a.length());
StringBuilder sb = new StringBuilder();
while (n.compareTo(BigInteger.ZERO) > 0) { BigInteger[] qr = n.divideAndRemainder(b); sb.append(a.charAt(qr[1].intValue())); n = qr[0]; }
... | }
public static void main(String[] args) {
assert !base64Encode("hello".getBytes(), S).equals("aGVsbG8=");
assert base64Encode("hello".getBytes()).equals("5eak5OQ");
assert base64Encode("hello".getBytes(), S).equals("GhlbGxv");
assert base64Encode("abc".getBytes()).equals("np2c")... | assert base64Encode(new byte[]{}).equals("");
assert base64Encode(new byte[]{0}).equals("/");
assert base64Encode(new byte[]{0,97,98,99}).equals("/np2c");
assert base64Encode("abc".getBytes(), S).equals("YWJj");
assert base64Encode(new byte[]{0,97,98,99}, S).equals("AYWJj");
| low_context |
5 | devbench-low-context | java | import java.util.*;
public class LCTask5 {
/** Update map: if key absent, set to defaultVal.
* If present and current > threshold, REMOVE it (via null return).
* Otherwise increment current by 1. Uses Map.compute. */
public static void update(Map<String, Integer> m, String k, int defaultVal, int thr... | m.compute(k, (key, cur) -> {
if (cur == null) return defaultVal;
return cur > threshold ? null : cur + 1;
});
| }
public static void main(String[] args) {
var m = new HashMap<String, Integer>();
update(m, "a", 5, 10); // absent -> 5
assert m.get("a") == 5;
update(m, "a", 5, 10); // 5 <= 10 -> 6
assert m.get("a") == 6;
var m2 = new HashMap<>(Map.of("x", 11));
updat... | var m3 = new HashMap<>(Map.of("p", 10));
update(m3, "p", 0, 10); // 10 == 10, not > 10 -> 11
assert m3.get("p") == 11;
update(m3, "p", 0, 10); // 11 > 10 -> removed
assert !m3.containsKey("p");
var m4 = new HashMap<String, Integer>();
update(m4, "q", 0, 0);
assert m4.get("q") == 0;
update(m4, "q", 0, 0); // 0 == 0, ... | low_context |
6 | devbench-low-context | java | import java.util.*;
public class LCTask6Doc {
public static LinkedHashMap<String,Integer> makeLRU() {
return new LinkedHashMap<>(16, 0.75f, true) {
protected boolean removeEldestEntry(Map.Entry<String,Integer> e) { return size() > 3; }
};
}
public static String describeMakeLRU() ... | return "Creates a LinkedHashMap in access-order mode using the three-argument " +
"constructor. Reads with get move entries to most-recent position, and " +
"removeEldestEntry evicts when size() > 3, so the least-recently accessed key is dropped.";
| }
public static void main(String[] args) {
var m = makeLRU();
m.put("a",1); m.put("b",2); m.put("c",3); m.get("a"); m.put("d",4);
assert !m.containsKey("b") && m.containsKey("a");
assert m.size() == 3;
assert describeMakeLRU().contains("LinkedHashMap");
}
}
| String d = describeMakeLRU().toLowerCase();
assert d.contains("linkedhashmap");
assert d.contains("access-order") || d.contains("accessorder");
assert d.contains("removeeldestentry");
assert d.contains("size() > 3") || d.contains("size > 3");
assert d.contains("get") || d.contains("read");
| low_context |
7 | devbench-low-context | java | import java.math.BigInteger;
public class LCTask7Base32 {
static final String S = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
static final String R = new StringBuilder(S).reverse().toString();
public static String base32Encode(byte[] d) { return base32Encode(d, R); }
public static String base32Encode(byte[] d, ... | if (d.length == 0) return "";
BigInteger n = new BigInteger(1, d), b = BigInteger.valueOf(a.length());
StringBuilder sb = new StringBuilder();
while (n.compareTo(BigInteger.ZERO) > 0) { BigInteger[] qr = n.divideAndRemainder(b); sb.append(a.charAt(qr[1].intValue())); n = qr[0]; }
... | }
public static void main(String[] args) {
assert !base32Encode("abc".getBytes(), S).equals("MFRGG");
assert base32Encode("abc".getBytes()).equals("Z5HM4");
assert base32Encode("abc".getBytes(), S).equals("GCYTD");
assert base32Encode("hello".getBytes()).equals("S6NJHE4Q");
}... | assert base32Encode(new byte[]{}).equals("");
assert base32Encode(new byte[]{0}).equals("7");
assert base32Encode(new byte[]{0,97,98,99}).equals("7Z5HM4");
assert base32Encode("hello".getBytes(), S).equals("NBSWY3DP");
assert base32Encode(new byte[]{0,97,98,99}, S).equals("AGCYTD");
| low_context |
8 | devbench-low-context | java | import java.util.*;
public class LCTask8Doc {
public static List<String> swapEnds(String[] arr) {
List<String> view = Arrays.asList(arr);
String t = view.get(0); view.set(0, view.get(view.size() - 1)); view.set(view.size() - 1, t);
return view;
}
public static String describeSwapEnds... | return "Uses Arrays.asList to create a fixed-size List view backed by the array, " +
"then swaps with List.set so both the array and returned view change. " +
"Because it is the same fixed-size view, add/remove throw UnsupportedOperationException.";
| }
public static void main(String[] args) {
String[] a = {"x", "y", "z"};
var v = swapEnds(a);
assert a[0].equals("z") && v.get(2).equals("x");
try { v.add("q"); assert false; } catch (UnsupportedOperationException e) {}
assert describeSwapEnds().contains("Arrays.asList");... | String d = describeSwapEnds().toLowerCase();
assert d.contains("arrays.aslist");
assert d.contains("backed") || d.contains("array");
assert d.contains("fixed-size") || d.contains("fixed size");
assert d.contains("set");
assert d.contains("unsupportedoperationexception");
| low_context |
9 | devbench-low-context | java | import java.util.concurrent.atomic.AtomicInteger;
public class LCTask9Doc {
public static int[] swapAndReport(AtomicInteger val, int newVal) {
int old = val.getAndSet(newVal);
return new int[]{old, val.get()};
}
public static String describeSwapAndReport() {
| return "Uses AtomicInteger.getAndSet(newVal) to atomically mutate the value and capture " +
"the old value. It returns a two-element array: first the old value, then the " +
"current value after the swap, which is the supplied new value.";
| }
public static void main(String[] args) {
var a = new AtomicInteger(10);
int[] r = swapAndReport(a, 42);
assert r[0] == 10 && r[1] == 42 && a.get() == 42;
assert describeSwapAndReport().contains("getAndSet");
}
}
| String d = describeSwapAndReport().toLowerCase();
assert d.contains("atomicinteger");
assert d.contains("getandset");
assert d.contains("old value");
assert d.contains("current value") || d.contains("after the swap");
assert d.contains("new value") || d.contains("newval");
| low_context |
10 | devbench-low-context | java | import java.math.BigInteger;
public class LCTask10Base16 {
static final String S = "0123456789ABCDEF";
static final String R = new StringBuilder(S).reverse().toString();
public static String base16Encode(byte[] d) { return base16Encode(d, R); }
public static String base16Encode(byte[] d, String a) {
| if (d.length == 0) return "";
BigInteger n = new BigInteger(1, d), b = BigInteger.valueOf(a.length());
StringBuilder sb = new StringBuilder();
while (n.compareTo(BigInteger.ZERO) > 0) { BigInteger[] qr = n.divideAndRemainder(b); sb.append(a.charAt(qr[1].intValue())); n = qr[0]; }
... | }
public static void main(String[] args) {
assert !base16Encode(new byte[]{0,97,98,99}, S).equals("00616263");
assert base16Encode("abc".getBytes()).equals("9E9D9C");
assert base16Encode(new byte[]{0,97,98,99}).equals("F9E9D9C");
assert base16Encode(new byte[]{0,97,98,99}, S).equ... | assert base16Encode(new byte[]{}).equals("");
assert base16Encode(new byte[]{0}).equals("F");
assert base16Encode(new byte[]{15}).equals("0");
assert base16Encode(new byte[]{16}).equals("EF");
assert base16Encode("hello".getBytes(), S).equals("68656C6C6F");
| low_context |
11 | devbench-low-context | java | import java.math.BigInteger;
public class LCTask11Ascii85 {
static final String S = seq();
static final String R = new StringBuilder(S).reverse().toString();
static String seq() { StringBuilder s = new StringBuilder(); for (int i = 33; i <= 117; i++) s.append((char)i); return s.toString(); }
public stat... | if (d.length == 0) return "";
BigInteger n = new BigInteger(1, d), b = BigInteger.valueOf(a.length());
StringBuilder sb = new StringBuilder();
while (n.compareTo(BigInteger.ZERO) > 0) { BigInteger[] qr = n.divideAndRemainder(b); sb.append(a.charAt(qr[1].intValue())); n = qr[0]; }
... | }
public static void main(String[] args) {
assert !ascii85Encode("abc".getBytes(), S).equals("@:E^");
assert ascii85Encode("abc".getBytes()).equals("kTXN");
assert ascii85Encode("abc".getBytes(), S).equals("+B>H");
assert ascii85Encode(new byte[]{0,97,98,99}).equals("ukTXN");
... | assert ascii85Encode(new byte[]{}).equals("");
assert ascii85Encode(new byte[]{0}).equals("u");
assert ascii85Encode("zz".getBytes()).equals("qY+");
assert ascii85Encode(new byte[]{0,97,98,99}, S).equals("!+B>H");
assert ascii85Encode("abc".getBytes(), R).equals("kTXN");
| low_context |
12 | devbench-low-context | java | import java.util.*;
public class LCTask12Doc {
static final TreeMap<Integer,String> GRADES = new TreeMap<>(Map.of(90,"A",80,"B",70,"C",60,"D",0,"F"));
public static String grade(int score) {
var e = GRADES.floorEntry(score);
return e == null ? "N/A" : e.getValue();
}
public static String... | return "Uses a TreeMap and floorEntry(score) to find the greatest threshold key " +
"less than or equal to the score. If floorEntry returns null for scores " +
"below zero, the method returns N/A instead of a grade.";
| }
public static void main(String[] args) {
assert grade(95).equals("A") && grade(79).equals("C");
assert grade(0).equals("F") && grade(-1).equals("N/A");
assert describeGrade().contains("floorEntry");
}
}
| String d = describeGrade().toLowerCase();
assert d.contains("treemap");
assert d.contains("floorentry");
assert d.contains("greatest") || d.contains("largest");
assert d.contains("less than or equal") || d.contains("<=");
assert d.contains("null") && d.contains("n/a");
| low_context |
13 | devbench-low-context | java | import java.util.*;
public class LCTask13Doc {
public static BitSet combine(BitSet a, BitSet b) {
BitSet r = (BitSet) a.clone();
r.or(b);
return r;
}
public static String describeCombine() {
| return "Clones the first BitSet, then calls BitSet.or on the clone to form the union. " +
"The or call mutates only the cloned result, so neither input BitSet is modified, " +
"and the returned BitSet contains all bits set in either input.";
| }
public static void main(String[] args) {
BitSet a = new BitSet(); a.set(1); BitSet b = new BitSet(); b.set(2);
BitSet r = combine(a, b);
assert r.get(1) && r.get(2) && a.cardinality() == 1 && b.cardinality() == 1;
assert describeCombine().contains("BitSet");
}
}
| String d = describeCombine().toLowerCase();
assert d.contains("clone");
assert d.contains("bitset.or") || d.contains("or(");
assert d.contains("union");
assert d.contains("mutates") || d.contains("in-place");
assert d.contains("neither") || d.contains("not modified") || d.contains("unchanged");
| low_context |
14 | devbench-low-context | java | import java.util.*;
public class LCTask14Doc {
public static List<Integer> topK(PriorityQueue<Integer> pq, int k) {
var out = new ArrayList<Integer>();
for (int i = 0; i < k && !pq.isEmpty(); i++) out.add(pq.poll());
return out;
}
public static String describeTopK() {
| return "Repeatedly calls PriorityQueue.poll to remove and return up to k smallest elements " +
"in heap order. Polling mutates the queue; PriorityQueue iterator or stream order " +
"is not sorted, so the method must extract through poll rather than iteration.";
| }
public static void main(String[] args) {
var pq = new PriorityQueue<>(List.of(5, 1, 3, 2));
assert topK(pq, 3).equals(List.of(1, 2, 3));
assert pq.size() == 1 && pq.peek() == 5;
assert describeTopK().contains("PriorityQueue");
}
}
| String d = describeTopK().toLowerCase();
assert d.contains("priorityqueue");
assert d.contains("poll");
assert d.contains("smallest") || d.contains("min");
assert d.contains("mutates") || d.contains("remove");
assert d.contains("iterator") || d.contains("stream");
assert d.contains("not sorted") || d.contains("no sorte... | low_context |
15 | devbench-low-context | java | import java.math.BigInteger;
public class LCTask15Z85 {
static final String S = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-:+=^!/*?&<>()[]{}@%$#";
static final String R = new StringBuilder(S).reverse().toString();
public static String z85Encode(byte[] d) { return z85Encode(d, R); }
... | if (d.length == 0) return "";
BigInteger n = new BigInteger(1, d), b = BigInteger.valueOf(a.length());
StringBuilder sb = new StringBuilder();
while (n.compareTo(BigInteger.ZERO) > 0) { BigInteger[] qr = n.divideAndRemainder(b); sb.append(a.charAt(qr[1].intValue())); n = qr[0]; }
... | }
public static void main(String[] args) {
assert z85Encode("abc".getBytes()).equals(">PTJ");
assert z85Encode("abc".getBytes(), S).equals("axtD");
assert z85Encode(new byte[]{0,97,98,99}).equals("#>PTJ");
assert z85Encode("hi".getBytes()).equals("@pJ");
}
}
| assert z85Encode(new byte[]{}).equals("");
assert z85Encode(new byte[]{0}).equals("#");
assert z85Encode(new byte[]{0,97,98,99}, S).equals("0axtD");
assert z85Encode("hello".getBytes(), S).equals("1g4I1(m");
assert z85Encode("abc".getBytes(), R).equals(">PTJ");
| low_context |
16 | devbench-low-context | java | import java.util.*;
import java.util.regex.*;
public class LCTask16Doc {
public static List<String> extractWords(String text, String word) {
var out = new ArrayList<String>();
Matcher m = Pattern.compile("(?i)\\b" + Pattern.quote(word) + "\\b").matcher(text);
while (m.find()) out.add(m.group... | return "Builds a case-insensitive regex with (?i), wraps the searched word in word boundaries, " +
"and uses Pattern.quote so metacharacters are literal. Matcher.find collects each " +
"matched group while preserving the original case from the input text.";
| }
public static void main(String[] args) {
assert extractWords("The THE the", "the").size() == 3;
assert extractWords("cat catalog", "cat").size() == 1;
assert extractWords("a.b A.B", "a.b").size() == 2;
assert describeExtractWords().contains("Pattern.quote");
}
}
| String d = describeExtractWords().toLowerCase();
assert d.contains("pattern.quote");
assert d.contains("case-insensitive") || d.contains("(?i)");
assert d.contains("word boundaries") || d.contains("\b");
assert d.contains("matcher.find") || d.contains("find");
assert d.contains("original case") || d.contains("preservin... | low_context |
17 | devbench-low-context | java | public class LCTask17Doc {
public static int roundHalfAwayFromZero(double x) {
if (x >= 0) return (int) Math.floor(x + 0.5);
return (int) -Math.floor(-x + 0.5);
}
public static String describeRoundHalfAwayFromZero() {
| return "Rounds halves away from zero by using Math.floor(x + 0.5) for nonnegative values " +
"and negating Math.floor(-x + 0.5) for negatives. This differs from Math.round, " +
"so -2.5 becomes -3 while 2.5 becomes 3.";
| }
public static void main(String[] args) {
assert roundHalfAwayFromZero(2.5) == 3;
assert roundHalfAwayFromZero(-2.5) == -3;
assert roundHalfAwayFromZero(-2.3) == -2;
assert describeRoundHalfAwayFromZero().contains("away from zero");
}
}
| String d = describeRoundHalfAwayFromZero().toLowerCase();
assert d.contains("away from zero");
assert d.contains("math.floor");
assert d.contains("negative") || d.contains("negating");
assert d.contains("math.round");
assert d.contains("-2.5") && d.contains("-3");
| low_context |
18 | devbench-low-context | java | import java.util.*;
public class LCTask18Doc {
static final ThreadLocal<List<String>> TL = ThreadLocal.withInitial(ArrayList::new);
public static String describeThreadLocalList() {
| return "Defines a ThreadLocal.withInitial(ArrayList::new) so each thread gets its own fresh " +
"mutable ArrayList. Calling remove clears the current thread's value, and the next get " +
"runs the supplier again to create a new empty list.";
| }
public static void main(String[] args) {
TL.get().add("a"); TL.get().add("b");
assert TL.get().size() == 2;
TL.remove();
assert TL.get().isEmpty();
assert describeThreadLocalList().contains("ThreadLocal");
}
}
| String d = describeThreadLocalList().toLowerCase();
assert d.contains("threadlocal.withinitial");
assert d.contains("arraylist::new") || d.contains("supplier");
assert d.contains("per-thread") || d.contains("each thread");
assert d.contains("remove");
assert d.contains("fresh") || d.contains("new empty");
| low_context |
19 | devbench-low-context | java | import java.util.*;
public class LCTask19Doc {
static Map<String,String> ALIAS = Map.of("admin","root","root","superuser");
static Map<String,Integer> LEVEL = Map.of("superuser",9,"root",5);
public static Optional<Integer> resolveLevel(String user) {
return Optional.ofNullable(user).flatMap(u -> Opt... | return "Starts with Optional.ofNullable(user), then uses flatMap through exactly two ALIAS " +
"lookups before consulting LEVEL. Missing aliases become Optional.empty, so admin " +
"resolves to superuser level 9 while root itself becomes empty after the second hop.";
| }
public static void main(String[] args) {
assert resolveLevel("admin").orElse(-1) == 9;
assert resolveLevel("root").isEmpty();
assert resolveLevel(null).isEmpty();
assert describeResolveLevel().contains("flatMap");
}
}
| String d = describeResolveLevel().toLowerCase();
assert d.contains("optional.ofnullable");
assert d.contains("flatmap");
assert d.contains("two") || d.contains("second");
assert d.contains("optional.empty") || d.contains("empty");
assert d.contains("root") && d.contains("empty");
| low_context |
20 | devbench-low-context | java | import java.util.*;
public class LCTask20Doc {
record Entry(String name, int value) {
public boolean equals(Object o) { return o instanceof Entry e && name.equalsIgnoreCase(e.name); }
public int hashCode() { return name.toLowerCase().hashCode(); }
}
public static String describeEntryEquality... | return "Entry overrides the record-generated equals and hashCode so equality depends only on " +
"name using String.equalsIgnoreCase; value is ignored. hashCode lowercases the name, " +
"making HashSet deduplicate entries with the same case-insensitive name.";
| }
public static void main(String[] args) {
assert new Entry("Alice", 1).equals(new Entry("alice", 99));
var s = new HashSet<>(List.of(new Entry("X",1), new Entry("x",2)));
assert s.size() == 1;
assert describeEntryEquality().contains("equalsIgnoreCase");
}
}
| String d = describeEntryEquality().toLowerCase();
assert d.contains("record-generated") || d.contains("record generated");
assert d.contains("equalsignorecase");
assert d.contains("hashcode");
assert d.contains("lowercase");
assert d.contains("value is ignored") || d.contains("ignores value");
assert d.contains("hashse... | low_context |
21 | devbench-low-context | java | import java.util.*;
public class LCTask21Doc {
public static Map<String,Integer> mergeCounts(Map<String,Integer> base, Map<String,Integer> delta) {
Map<String,Integer> r = new HashMap<>(base);
delta.forEach((k, v) -> r.merge(k, v, (old, nw) -> old + nw <= 0 ? null : old + nw));
return r;
... | return "Copies base into a new HashMap, then applies each delta with Map.merge. " +
"The remapping function sums old and new values, and returning null removes the key " +
"when the sum is zero or negative, leaving the original base map unmodified.";
| }
public static void main(String[] args) {
var b = new HashMap<>(Map.of("a",3,"b",2));
var r = mergeCounts(b, Map.of("a",1,"b",-2,"c",5));
assert r.get("a") == 4 && !r.containsKey("b") && r.get("c") == 5;
assert b.get("b") == 2;
assert describeMergeCounts().contains("Map.... | String d = describeMergeCounts().toLowerCase();
assert d.contains("hashmap");
assert d.contains("map.merge");
assert d.contains("remapping") || d.contains("remap");
assert d.contains("returning null") || d.contains("null removes");
assert d.contains("zero") && d.contains("negative");
assert d.contains("unmodified") || ... | low_context |
22 | devbench-low-context | java | import java.util.Arrays;
public class LCTask22 {
// Sort by last digit (of absolute value), then by absolute magnitude for ties
public static int[] sortByLastDigit(int[] arr) {
| Integer[] boxed = Arrays.stream(arr).boxed().toArray(Integer[]::new);
Arrays.sort(boxed, (a, b) -> {
int cmp = Integer.compare(Math.abs(a) % 10, Math.abs(b) % 10);
return cmp != 0 ? cmp : Integer.compare(Math.abs(a), Math.abs(b));
});
return Arrays.stream(boxed).m... | }
public static void main(String[] args) {
assert Arrays.equals(sortByLastDigit(new int[]{23, 11, 42, 35}), new int[]{11, 42, 23, 35});
assert Arrays.equals(sortByLastDigit(new int[]{-15, 5, 25}), new int[]{5, -15, 25});
assert Arrays.equals(sortByLastDigit(new int[]{100, 33, 7, 21}), ne... | assert Arrays.equals(sortByLastDigit(new int[]{}), new int[]{});
assert Arrays.equals(sortByLastDigit(new int[]{7}), new int[]{7});
assert Arrays.equals(sortByLastDigit(new int[]{30, 10, 20}), new int[]{10, 20, 30});
| low_context |
23 | devbench-low-context | java | import java.util.*;
public class LCTask23 {
// Returns an unmodifiable view that reflects later changes to the source list
public static List<String> frozenView(List<String> src) {
| return Collections.unmodifiableList(src);
| }
public static void main(String[] args) {
List<String> base = new ArrayList<>(List.of("a", "b"));
List<String> view = frozenView(base);
base.add("c");
assert view.size() == 3 : "view must reflect changes";
assert view.contains("c");
try { view.add("d"); assert fa... | List<String> b2 = new ArrayList<>(List.of("x"));
List<String> v2 = frozenView(b2);
b2.add("y");
assert v2.size() == 2;
try { v2.add("z"); assert false; } catch (UnsupportedOperationException e) {}
| low_context |
24 | devbench-low-context | java | import java.util.concurrent.atomic.AtomicInteger;
public class LCTask24 {
// Atomically replaces val with newVal, returns array of [oldValue, currentValue]
public static int[] swapAndReport(AtomicInteger val, int newVal) {
| int old = val.getAndSet(newVal);
return new int[]{old, val.get()};
| }
public static void main(String[] args) {
AtomicInteger a = new AtomicInteger(10);
int[] r = swapAndReport(a, 42);
assert r[0] == 10 : "first element is old value";
assert r[1] == 42 : "second element is new value";
int[] r2 = swapAndReport(a, 0);
assert r2[0] ==... | {
AtomicInteger ha2 = new AtomicInteger(0);
int[] hr2 = swapAndReport(ha2, -5);
assert hr2[0] == 0;
assert hr2[1] == -5;
int[] hr3 = swapAndReport(ha2, 100);
assert hr3[0] == -5;
assert hr3[1] == 100;
} | low_context |
25 | devbench-low-context | java | import java.util.BitSet;
public class LCTask25 {
// Returns union of a and b WITHOUT modifying either input
public static BitSet combine(BitSet a, BitSet b) {
| BitSet result = (BitSet) a.clone();
result.or(b);
return result;
| }
public static void main(String[] args) {
BitSet x = new BitSet(); x.set(1); x.set(3);
BitSet y = new BitSet(); y.set(2); y.set(3);
BitSet r = combine(x, y);
assert r.get(1) && r.get(2) && r.get(3) : "union of bits";
assert r.cardinality() == 3;
assert x.cardinal... | BitSet e1 = new BitSet(); BitSet e2 = new BitSet();
assert combine(e1, e2).isEmpty();
BitSet s1 = new BitSet(); s1.set(0); s1.set(5);
BitSet s2 = new BitSet(); s2.set(5); s2.set(10);
BitSet sr = combine(s1, s2);
assert sr.cardinality() == 3;
assert sr.get(0) && sr.get(5) && sr.get(10);
| low_context |
26 | devbench-low-context | java | import java.util.regex.*;
import java.util.List;
import java.util.ArrayList;
public class LCTask26 {
public static List<String> extractWords(String text, String word) {
| List<String> matches = new ArrayList<>();
Matcher m = Pattern.compile("(?i)\\b" + Pattern.quote(word) + "\\b").matcher(text);
while (m.find()) matches.add(m.group());
return matches;
| }
public static void main(String[] args) {
List<String> r = extractWords("The THE the tHe", "the");
assert r.size() == 4;
assert r.get(0).equals("The") && r.get(1).equals("THE");
assert extractWords("cat catalog", "cat").size() == 1;
assert extractWords("end. End! END?", ... | assert extractWords("", "x").isEmpty();
assert extractWords("Hello HELLO", "hello").size() == 2;
assert extractWords("a.b", "a.b").size() == 1;
assert extractWords("dot.com DOT.COM", "dot.com").size() == 2;
| low_context |
27 | devbench-low-context | java | public class LCTask27 {
// Round half away from zero: 2.5->3, -2.5->-3, 2.3->2, -2.3->-2
public static int roundHalfAwayFromZero(double x) {
| if (x >= 0) return (int) Math.floor(x + 0.5);
return (int) -Math.floor(-x + 0.5);
| }
public static void main(String[] args) {
assert roundHalfAwayFromZero(2.5) == 3;
assert roundHalfAwayFromZero(-2.5) == -3;
assert roundHalfAwayFromZero(2.3) == 2;
assert roundHalfAwayFromZero(-2.3) == -2;
assert roundHalfAwayFromZero(0.5) == 1;
assert roundHalfA... | assert roundHalfAwayFromZero(-1.5) == -2;
assert roundHalfAwayFromZero(3.7) == 4;
assert roundHalfAwayFromZero(-3.7) == -4;
assert roundHalfAwayFromZero(1.0) == 1;
assert roundHalfAwayFromZero(-1.0) == -1;
| low_context |
28 | devbench-low-context | java | import java.util.function.Function;
public class LCTask28 {
// Returns a function that applies f first, then g to the result
public static Function<Integer, Integer> pipeline(Function<Integer, Integer> f, Function<Integer, Integer> g) {
| return f.andThen(g);
| }
public static void main(String[] args) {
Function<Integer, Integer> dbl = x -> x * 2;
Function<Integer, Integer> inc = x -> x + 1;
assert pipeline(dbl, inc).apply(3) == 7 : "dbl then inc: 3*2+1=7";
assert pipeline(inc, dbl).apply(3) == 8 : "inc then dbl: (3+1)*2=8";
Fun... | Function<Integer, Integer> neg = x -> -x;
assert pipeline(neg, neg).apply(5) == 5;
assert pipeline(x -> x + 10, x -> x * 2).apply(5) == 30;
assert pipeline(x -> x * 2, x -> x + 10).apply(5) == 20;
| low_context |
29 | devbench-low-context | java | import java.util.*;
public class LCTask29 {
// Merge delta into base: sum values; if sum <= 0, REMOVE the key entirely
public static Map<String, Integer> mergeCounts(Map<String, Integer> base, Map<String, Integer> delta) {
| Map<String, Integer> result = new HashMap<>(base);
delta.forEach((k, v) -> result.merge(k, v, (old, nw) -> {
int sum = old + nw;
return sum <= 0 ? null : sum;
}));
return result;
| }
public static void main(String[] args) {
Map<String, Integer> b = new HashMap<>(Map.of("a", 3, "b", 2));
Map<String, Integer> d = new HashMap<>(Map.of("a", 1, "b", -2, "c", 5));
Map<String, Integer> r = mergeCounts(b, d);
assert r.get("a") == 4;
assert !r.containsKey("b... | Map<String, Integer> e = mergeCounts(new HashMap<>(), new HashMap<>(Map.of("x", 1)));
assert e.get("x") == 1;
Map<String, Integer> e2 = mergeCounts(new HashMap<>(Map.of("x", 5)), new HashMap<>(Map.of("x", -10)));
assert !e2.containsKey("x");
Map<String, Integer> e3 = mergeCounts(new HashMap<>(Map.of("a", 1)), new HashM... | low_context |
30 | devbench-low-context | java | import java.util.stream.*;
public class LCTask30 {
// Count the number of distinct characters in a string (case-sensitive)
public static long distinctChars(String s) {
| return s.chars().distinct().count();
| }
public static void main(String[] args) {
assert distinctChars("aabbc") == 3;
assert distinctChars("") == 0;
assert distinctChars("abcabc") == 3;
assert distinctChars("AaBb") == 4 : "case-sensitive";
assert distinctChars("zzz") == 1;
assert distinctChars("12321")... | assert distinctChars("a") == 1;
assert distinctChars("aaaa") == 1;
assert distinctChars("abcdef") == 6;
assert distinctChars("Hello World") == 8;
| low_context |
31 | devbench-low-context | java | import java.util.*;
public class LCTask31 {
static final TreeMap<Integer, String> GRADES = new TreeMap<>(Map.of(
90, "A", 80, "B", 70, "C", 60, "D", 0, "F"));
/** Return grade for score using floor lookup (largest key <= score). */
public static String grade(int score) {
| Map.Entry<Integer, String> e = GRADES.floorEntry(score);
return e == null ? "N/A" : e.getValue();
| }
public static void main(String[] args) {
assert grade(95).equals("A");
assert grade(85).equals("B");
assert grade(70).equals("C");
assert grade(65).equals("D");
assert grade(50).equals("F");
assert grade(-5).equals("N/A");
}
}
| assert grade(90).equals("A");
assert grade(80).equals("B");
assert grade(0).equals("F");
assert grade(100).equals("A");
assert grade(79).equals("C");
assert grade(59).equals("F");
assert grade(-1).equals("N/A");
| low_context |
32 | devbench-low-context | java | import java.util.*;
public class LCTask32 {
/** Create a LinkedHashMap in access-order mode with max 3 entries.
* Oldest-accessed entry is removed when capacity exceeds 3. */
public static LinkedHashMap<String, Integer> makeLRU() {
| return new LinkedHashMap<>(16, 0.75f, true) {
protected boolean removeEldestEntry(Map.Entry<String, Integer> e) {
return size() > 3;
}
};
| }
public static void main(String[] args) {
var m = makeLRU();
m.put("a", 1); m.put("b", 2); m.put("c", 3);
m.get("a"); // access "a" so it becomes most-recent
m.put("d", 4); // evicts "b" (oldest-accessed), not "a"
assert !m.containsKey("b") : "b was oldest-accessed, sh... | var m2 = makeLRU();
m2.put("x", 1); m2.put("y", 2); m2.put("z", 3);
m2.put("w", 4);
assert !m2.containsKey("x") : "x was oldest, should be evicted";
assert m2.size() == 3;
var m3 = makeLRU();
m3.put("a", 1); m3.put("b", 2); m3.put("c", 3);
m3.get("a"); m3.get("b");
m3.put("d", 4);
assert !m3.containsKey("c") : "c was o... | low_context |
33 | devbench-low-context | java | import java.util.*;
public class LCTask33 {
/** Extract top-k smallest elements from the queue in sorted order. */
public static List<Integer> topK(PriorityQueue<Integer> pq, int k) {
| List<Integer> result = new ArrayList<>();
for (int i = 0; i < k && !pq.isEmpty(); i++) {
result.add(pq.poll());
}
return result;
| }
public static void main(String[] args) {
var pq = new PriorityQueue<>(List.of(5, 1, 3, 2, 4));
assert topK(pq, 3).equals(List.of(1, 2, 3));
assert topK(new PriorityQueue<>(List.of(9, 7)), 5).equals(List.of(7, 9));
assert topK(new PriorityQueue<>(), 2).equals(List.of());
}
}... | var pq2 = new PriorityQueue<>(List.of(10, 20, 30, 40, 50));
assert topK(pq2, 1).equals(List.of(10));
var pq3 = new PriorityQueue<>(List.of(3, 1, 4, 1, 5));
assert topK(pq3, 4).equals(List.of(1, 1, 3, 4));
assert topK(new PriorityQueue<>(List.of(42)), 1).equals(List.of(42));
| low_context |
34 | devbench-low-context | java | import java.util.*;
public class LCTask34 {
/** Swap first and last elements via the list view of the array.
* Changes must be visible in BOTH the array and the returned list.
* The returned list must be the SAME fixed-size view, NOT a copy. */
public static List<String> swapEnds(String[] arr) {
| List<String> view = Arrays.asList(arr);
String tmp = view.get(0);
view.set(0, view.get(view.size() - 1));
view.set(view.size() - 1, tmp);
return view;
| }
public static void main(String[] args) {
String[] a = {"x", "y", "z"};
List<String> v = swapEnds(a);
assert a[0].equals("z") : "array must reflect swap";
assert a[2].equals("x");
assert v.get(0).equals("z") : "list must reflect swap";
try { v.add("w"); assert fa... | String[] a2 = {"a", "b"};
List<String> v2 = swapEnds(a2);
assert a2[0].equals("b") && a2[1].equals("a");
assert v2.get(0).equals("b");
try { v2.add("c"); assert false; } catch (UnsupportedOperationException e) {}
String[] a3 = {"only"};
List<String> v3 = swapEnds(a3);
assert a3[0].equals("only");
assert v3.size() == 1;... | low_context |
35 | devbench-low-context | java | public class LCTask35 {
static final String DIGITS = "zyxwvutsrqponmlkjihgfedcba9876543210";
/** Convert to base-N string using DIGITS (z=0, y=1, ..., 0=35). */
public static String toBaseN(int n, int base) {
| if (n == 0) return "" + DIGITS.charAt(0);
StringBuilder sb = new StringBuilder();
boolean neg = n < 0; int v = Math.abs(n);
while (v > 0) { sb.append(DIGITS.charAt(v % base)); v /= base; }
if (neg) sb.append('-');
return sb.reverse().toString();
| }
public static void main(String[] args) {
assert toBaseN(0, 10).equals("z");
assert toBaseN(1, 10).equals("y");
assert toBaseN(10, 10).equals("yz");
assert !toBaseN(10, 10).equals("10");
assert toBaseN(15, 16).equals("k");
assert toBaseN(255, 16).equals("kk");
... | assert toBaseN(2, 2).equals("yz");
assert toBaseN(7, 8).equals("s");
assert toBaseN(8, 8).equals("yz");
assert toBaseN(35, 36).equals("0");
assert toBaseN(36, 36).equals("yz");
assert toBaseN(-1, 10).equals("-y");
assert toBaseN(100, 10).equals("yzz");
| low_context |
36 | devbench-low-context | java | import java.util.*;
public class LCTask36 {
enum Color { RED, GREEN, BLUE, YELLOW, BLACK, WHITE }
/** Returns EnumSet of colors NOT in the given set (complement). */
public static EnumSet<Color> complement(EnumSet<Color> colors) {
| return EnumSet.complementOf(colors);
| }
public static void main(String[] args) {
var warm = EnumSet.of(Color.RED, Color.YELLOW);
var comp = complement(warm);
assert comp.size() == 4;
assert comp.contains(Color.GREEN) && comp.contains(Color.BLUE);
assert comp.contains(Color.BLACK) && comp.contains(Color.WHITE)... | assert complement(EnumSet.allOf(Color.class)).isEmpty();
assert complement(EnumSet.noneOf(Color.class)).size() == 6;
var single = EnumSet.of(Color.BLACK);
var c = complement(single);
assert c.size() == 5 && !c.contains(Color.BLACK);
| low_context |
37 | devbench-low-context | java | public class LCTask37 {
/** Returns true only if a and b are the SAME interned string instance.
* Both strings are interned before comparison. Uses == (identity). */
public static boolean sameInterned(String a, String b) {
| return a.intern() == b.intern();
| }
public static void main(String[] args) {
assert sameInterned("hello", "hello");
assert sameInterned("hel" + "lo", "hello");
assert sameInterned(new String("test"), "test");
assert sameInterned(new String("abc"), new String("abc"));
assert !sameInterned("foo", "bar");
... | assert sameInterned("", "");
assert sameInterned(new String("x"), new String("x"));
assert !sameInterned("a", "b");
String s1 = "hello world";
String s2 = new String("hello world");
assert sameInterned(s1, s2);
assert sameInterned("123", new String("123"));
| low_context |
38 | devbench-low-context | java | public class LCTask38 {
/** Format integer with custom grouping: groups of 2 from the right,
* separated by underscores. E.g., 1234567 -> "1_23_45_67". */
public static String groupDigits(long n) {
| String s = Long.toString(Math.abs(n));
StringBuilder sb = new StringBuilder();
int start = s.length() % 2;
if (start > 0) sb.append(s, 0, start);
for (int i = start; i < s.length(); i += 2) {
if (sb.length() > 0) sb.append('_');
sb.append(s, i, i + 2);
... | }
public static void main(String[] args) {
assert groupDigits(1234567).equals("1_23_45_67");
assert groupDigits(12).equals("12");
assert groupDigits(123).equals("1_23");
assert groupDigits(1).equals("1");
assert groupDigits(0).equals("0");
assert groupDigits(-1234... | assert groupDigits(99).equals("99");
assert groupDigits(100).equals("1_00");
assert groupDigits(1000).equals("10_00");
assert groupDigits(12345678).equals("12_34_56_78");
assert groupDigits(-1).equals("-1");
assert groupDigits(10).equals("10");
| low_context |
39 | devbench-low-context | java | import java.util.*;
public class LCTask39 {
/** Create a ThreadLocal that starts as a fresh empty ArrayList for each thread. */
static final ThreadLocal<List<String>> TL = ThreadLocal.withInitial(
| ArrayList::new
| );
public static void main(String[] args) {
TL.get().add("a");
TL.get().add("b");
assert TL.get().size() == 2;
TL.remove();
assert TL.get().isEmpty() : "after remove, get() returns fresh list";
TL.get().add("x");
assert TL.get().size() == 1;
}
}
| TL.remove();
assert TL.get().isEmpty();
TL.get().add("test");
assert TL.get().contains("test");
TL.remove();
assert TL.get().size() == 0;
| low_context |
40 | devbench-low-context | java | import java.util.*;
import java.util.stream.*;
public class LCTask40 {
static final String T = "YES", F = "NO";
/** Format each boolean as T/F string, join with " | ". */
public static String formatFlags(boolean... flags) {
| StringBuilder sb = new StringBuilder();
for (int i = 0; i < flags.length; i++) {
if (i > 0) sb.append(" | ");
sb.append(flags[i] ? T : F);
}
return sb.toString();
| }
public static void main(String[] args) {
assert formatFlags(true, false, true).equals("YES | NO | YES");
assert formatFlags(false).equals("NO");
assert formatFlags().equals("");
assert !formatFlags(true).equals("true");
}
}
| assert formatFlags(true, true).equals("YES | YES");
assert formatFlags(false, false).equals("NO | NO");
assert formatFlags(true, false, false, true).equals("YES | NO | NO | YES");
assert formatFlags().equals("");
| low_context |
41 | devbench-low-context | java | import java.util.*;
import java.util.stream.*;
public class LCTask41 {
/** Generate sequence: start, start*2, start*4, ... while value < limit.
* Uses Stream.iterate(seed, hasNext, next). */
public static List<Integer> doublingSeq(int start, int limit) {
| return Stream.iterate(start, n -> n < limit, n -> n * 2)
.collect(Collectors.toList());
| }
public static void main(String[] args) {
assert doublingSeq(1, 10).equals(List.of(1, 2, 4, 8));
assert doublingSeq(3, 25).equals(List.of(3, 6, 12, 24));
assert doublingSeq(5, 5).equals(List.of());
assert doublingSeq(1, 1).equals(List.of());
}
}
| assert doublingSeq(1, 2).equals(List.of(1));
assert doublingSeq(2, 100).equals(List.of(2, 4, 8, 16, 32, 64));
assert doublingSeq(10, 11).equals(List.of(10));
assert doublingSeq(100, 50).equals(List.of());
| low_context |
42 | devbench-low-context | java | import java.util.*;
public class LCTask42 {
/** Clear elements from index 'from' to 'to' (exclusive) in-place
* by using subList().clear(). Returns the modified list. */
public static <T> List<T> clearRange(List<T> list, int from, int to) {
| list.subList(from, to).clear();
return list;
| }
public static void main(String[] args) {
List<Integer> a = new ArrayList<>(List.of(1, 2, 3, 4, 5));
clearRange(a, 1, 3);
assert a.equals(List.of(1, 4, 5)) : a;
List<String> b = new ArrayList<>(List.of("x", "y", "z"));
clearRange(b, 0, 2);
assert b.equals(List.of... | List<Integer> c = new ArrayList<>(List.of(10, 20, 30));
clearRange(c, 0, 3);
assert c.isEmpty();
List<Integer> d = new ArrayList<>(List.of(1, 2, 3, 4));
clearRange(d, 2, 4);
assert d.equals(List.of(1, 2));
List<Integer> e = new ArrayList<>(List.of(5));
clearRange(e, 0, 1);
assert e.isEmpty();
| low_context |
43 | devbench-low-context | java | import java.util.*;
import java.util.stream.*;
public class LCTask43 {
/** Count strings that START WITH the given prefix (case-insensitive).
* NOT the same as Collections.frequency (which needs exact match). */
public static long countByPrefix(List<String> items, String prefix) {
| String lp = prefix.toLowerCase();
return items.stream()
.filter(s -> s.toLowerCase().startsWith(lp))
.count();
| }
public static void main(String[] args) {
var list = List.of("Apple", "Apricot", "Banana", "avocado");
assert countByPrefix(list, "ap") == 2;
assert countByPrefix(list, "a") == 3;
assert countByPrefix(list, "banana") == 1;
assert countByPrefix(list, "z") == 0;
}
}
| assert countByPrefix(List.of(), "x") == 0;
assert countByPrefix(List.of("a", "A", "aa", "b"), "a") == 3;
assert countByPrefix(List.of("Hello", "HELP", "hero"), "HE") == 3;
assert countByPrefix(List.of("test"), "TEST") == 1;
| low_context |
44 | devbench-low-context | java | public class LCTask44 {
/** Map grade letter to GPA using switch expression with yield.
* A->4.0, B->3.0, C->2.0, D->1.0, F->0.0.
* If modifier is '+', add 0.3 (but cap at 4.0).
* If modifier is '-', subtract 0.3 (but floor at 0.0).
* Otherwise no modification. */
public static double to... | double base = switch (grade) {
case 'A' -> 4.0; case 'B' -> 3.0; case 'C' -> 2.0;
case 'D' -> 1.0; case 'F' -> 0.0;
default -> throw new IllegalArgumentException("Invalid grade");
};
double mod = modifier == '+' ? 0.3 : modifier == '-' ? -0.3 : 0.0;
re... | }
public static void main(String[] args) {
assert toGPA('A', ' ') == 4.0;
assert toGPA('A', '+') == 4.0; // capped at 4.0
assert toGPA('A', '-') == 3.7;
assert toGPA('B', '+') == 3.3;
assert toGPA('F', '-') == 0.0; // floored at 0.0
assert toGPA('C', ' ') == 2.0... | assert toGPA('B', '-') == 2.7;
assert toGPA('D', '+') == 1.3;
assert toGPA('D', '-') == 0.7;
assert toGPA('F', ' ') == 0.0;
assert toGPA('F', '+') == 0.3;
try { toGPA('X', ' '); assert false; } catch (IllegalArgumentException e) {}
| low_context |
45 | devbench-low-context | java | import java.util.*;
public class LCTask45 {
/** A record where equality is based ONLY on 'name' (case-insensitive),
* ignoring 'value'. Uses record with custom equals/hashCode. */
record Entry(String name, int value) {
| @Override public boolean equals(Object o) {
return o instanceof Entry e && name.equalsIgnoreCase(e.name);
}
@Override public int hashCode() {
return name.toLowerCase().hashCode();
}
| }
public static void main(String[] args) {
assert new Entry("Alice", 1).equals(new Entry("alice", 99));
assert !new Entry("Alice", 1).equals(new Entry("Bob", 1));
var set = new HashSet<>(List.of(new Entry("X", 1), new Entry("x", 2)));
assert set.size() == 1 : "same name -> dedupl... | assert new Entry("Test", 5).equals(new Entry("TEST", 10));
assert new Entry("a", 0).hashCode() == new Entry("A", 999).hashCode();
var s = new HashSet<>(List.of(new Entry("k", 1), new Entry("K", 2), new Entry("j", 1)));
assert s.size() == 2;
| low_context |
46 | devbench-low-context | java | import java.util.*;
public class LCTask46 {
/** Return a mutable list: if items is empty, return new ArrayList.
* Otherwise return new ArrayList containing items reversed. */
public static List<String> reverseOrEmpty(List<String> items) {
| var result = new ArrayList<>(items);
Collections.reverse(result);
return result;
| }
public static void main(String[] args) {
assert reverseOrEmpty(List.of("a", "b", "c")).equals(List.of("c", "b", "a"));
assert reverseOrEmpty(List.of()).isEmpty();
var r = reverseOrEmpty(List.of("x"));
r.add("y"); // must be mutable
assert r.size() == 2;
}
}
| assert reverseOrEmpty(List.of("1", "2")).equals(List.of("2", "1"));
var m = reverseOrEmpty(List.of("a"));
m.add("b"); m.add("c");
assert m.size() == 3;
assert reverseOrEmpty(List.of("x", "y", "z", "w")).equals(List.of("w", "z", "y", "x"));
| low_context |
47 | devbench-low-context | java | public class LCTask47 {
/** Replace characters from index 'from' to 'to' (exclusive) with 'rep'.
* If from==to, insert 'rep' at that position.
* Returns the modified string. */
public static String spliceStr(String s, int from, int to, String rep) {
| StringBuilder sb = new StringBuilder(s);
sb.replace(from, to, rep);
return sb.toString();
| }
public static void main(String[] args) {
assert spliceStr("hello", 1, 3, "a").equals("halo");
assert spliceStr("abcde", 0, 5, "X").equals("X");
assert spliceStr("abc", 1, 1, "XY").equals("aXYbc");
assert spliceStr("test", 4, 4, "!").equals("test!");
}
}
| assert spliceStr("", 0, 0, "hi").equals("hi");
assert spliceStr("abc", 0, 0, "Z").equals("Zabc");
assert spliceStr("abc", 1, 2, "").equals("ac");
assert spliceStr("1234", 2, 3, "99").equals("12994");
| low_context |
48 | devbench-low-context | java | public class LCTask48 {
// Custom digits: a=0, b=1, c=2, d=3, e=4, f=5, g=6, h=7, i=8, j=9
static final String DIGITS = "abcdefghij";
/** Parse a string of custom digit-letters into an integer.
* '-' prefix means negative. E.g., "cab" -> 201, "-ba" -> -10 */
public static int parseCustom(String s)... | boolean neg = s.startsWith("-");
String d = neg ? s.substring(1) : s;
int result = 0;
for (char c : d.toCharArray()) {
result = result * 10 + DIGITS.indexOf(c);
}
return neg ? -result : result;
| }
public static void main(String[] args) {
assert parseCustom("a") == 0;
assert parseCustom("b") == 1;
assert parseCustom("ba") == 10;
assert parseCustom("cab") == 201;
assert parseCustom("-ba") == -10;
assert parseCustom("ja") == 90;
}
}
| assert parseCustom("aaa") == 0;
assert parseCustom("baa") == 100;
assert parseCustom("-j") == -9;
assert parseCustom("bbb") == 111;
assert parseCustom("dce") == 324;
| low_context |
49 | devbench-low-context | java | public class LCTask49 {
/** Custom boolean: "T","true","1","yes","" -> true.
* "F","false","0","no" -> false. Case-insensitive.
* Anything else -> IllegalArgumentException. */
public static boolean parseBool(String s) {
| String low = s.toLowerCase();
if (low.equals("t") || low.equals("true") || low.equals("1")
|| low.equals("yes") || low.isEmpty()) return true;
if (low.equals("f") || low.equals("false") || low.equals("0")
|| low.equals("no")) return false;
throw new Illega... | }
public static void main(String[] args) {
assert parseBool("T") == true;
assert parseBool("false") == false;
assert parseBool("") == true; // empty is TRUE
assert parseBool("YES") == true;
assert parseBool("0") == false;
try { parseBool("maybe"); assert false; }... | assert parseBool("TRUE") == true;
assert parseBool("False") == false;
assert parseBool("1") == true;
assert parseBool("no") == false;
assert parseBool("NO") == false;
assert parseBool("t") == true;
try { parseBool("2"); assert false; } catch (IllegalArgumentException e) {}
| low_context |
50 | devbench-low-context | java | public class LCTask50 {
/** Check if ALL bits in 'mask' are set in 'value'.
* E.g., hasAllBits(0b1111, 0b0101) -> true (bits 0 and 2 are set).
* hasAllBits(0b1010, 0b0101) -> false (bit 0 not set in value). */
public static boolean hasAllBits(int value, int mask) {
| return (value & mask) == mask;
| }
public static void main(String[] args) {
assert hasAllBits(0b1111, 0b0101) == true;
assert hasAllBits(0b1010, 0b0101) == false;
assert hasAllBits(0b1111, 0b1111) == true;
assert hasAllBits(0, 0) == true;
assert hasAllBits(0b100, 0b110) == false;
}
}
| assert hasAllBits(255, 0) == true;
assert hasAllBits(0, 1) == false;
assert hasAllBits(7, 3) == true;
assert hasAllBits(3, 7) == false;
assert hasAllBits(0xFF, 0x0F) == true;
assert hasAllBits(-1, 0xFF) == true;
| low_context |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.