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-pattern-matching | java | import java.util.LinkedHashMap;
import java.util.Map;
public class PMTask1 {
private static String stripComment(String s) {
StringBuilder out = new StringBuilder();
boolean q = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '\"') q = !q;... | for (String raw : text.split("\n", -1)) {
String line = pending.length() > 0 ? raw.stripLeading() : raw;
if (line.endsWith("\\")) { pending.append(line, 0, line.length() - 1); continue; }
pending.append(line);
String logical = stripComment(pending.toString()).trim... | }
public static void main(String[] args) {
String cfg = "name = Alice\n" +
"path = /usr/\\\n" +
" local/bin\n" +
"note = \"keep # sign\" # tail\n" +
"; skip me\n" +
"empty = \"\"";
Map<Stri... | assert parseProperties("").isEmpty() : "empty input";
Map<String, String> a = parseProperties("x: 1\ny = 2");
assert a.get("x").equals("1") : "colon separator";
assert a.get("y").equals("2") : "equals separator";
Map<String, String> b = parseProperties("url = http://x/y;not-comment");
assert b.get("url").equals("http:/... | pattern_matching |
2 | devbench-pattern-matching | java | public class PMTask2 {
// Custom edit distance: insert=1, delete=1, replace=1, swap(adjacent)=0.5
// editDistance("ab","ba") = 0.5, NOT 2 | editDistance("cat","car") = 1
public static double editDistance(String a, String b) {
| int m = a.length(), n = b.length();
double[][] dp = new double[m + 1][n + 1];
for (int i = 0; i <= m; i++) dp[i][0] = i;
for (int j = 0; j <= n; j++) dp[0][j] = j;
for (int i = 1; i <= m; i++) for (int j = 1; j <= n; j++) {
dp[i][j] = Math.min(dp[i-1][j] + 1, Math.min... | }
public static void main(String[] args) {
assert editDistance("ab", "ba") == 0.5 : "swap should cost 0.5";
assert editDistance("cat", "car") == 1.0 : "replace costs 1";
assert editDistance("", "abc") == 3.0 : "three inserts";
assert editDistance("abc", "abc") == 0.0 : "identica... | assert editDistance("", "") == 0.0 : "both empty";
assert editDistance("a", "b") == 1.0 : "single replace";
assert editDistance("abcd", "abdc") == 0.5 : "one swap at end";
assert editDistance("kitten", "sitting") == 3.0 : "classic example";
assert editDistance("ab", "ba") == 0.5 : "swap not 2";
| pattern_matching |
3 | devbench-pattern-matching | java | import java.util.LinkedHashMap;
import java.util.Map;
public class PMTask3 {
// Manifest parser:
// - [section] prefixes following keys as section.key
// - lines ending in backslash continue with the next physical line
// - blank lines and # comments are ignored
public static Map<String, String> pa... | Map<String, String> result = new LinkedHashMap<>();
String section = "";
StringBuilder joined = new StringBuilder();
for (String raw : text.split("\n", -1)) {
if (raw.endsWith("\\")) { joined.append(raw, 0, raw.length() - 1); continue; }
joined.append(raw);
... | }
public static void main(String[] args) {
String cfg = "[core]\n" +
"name=dev\\\n" +
"bench\n" +
"# ignored\n" +
"[limits]\n" +
"score = 54";
Map<String, String> m = parseManifest(cfg);
... | assert parseManifest("").isEmpty() : "empty input";
Map<String, String> a = parseManifest("global=yes");
assert a.get("global").equals("yes") : "global key";
Map<String, String> b = parseManifest("[s]\na=1\nb=2");
assert b.get("s.a").equals("1") : "section a";
assert b.get("s.b").equals("2") : "section b";
Map<String, ... | pattern_matching |
4 | devbench-pattern-matching | java | import java.util.LinkedHashMap;
import java.util.Map;
public class PMTask4 {
private static String stripComment(String s) {
StringBuilder out = new StringBuilder();
char quote = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if ((c == '\'' || c == '\... | for (String raw : text.split("\n", -1)) {
String line = pending.length() > 0 ? raw.stripLeading() : raw;
if (line.endsWith("\\")) { pending.append(line, 0, line.length() - 1); continue; }
pending.append(line);
String logical = stripComment(pending.toString()).trim... | }
public static void main(String[] args) {
String text = "export USER=alice\n" +
"PATH=/usr/\\\n" +
" local/bin # tail\n" +
"MSG=\"keep # hash\" # comment\n" +
"EMPTY=''";
Map<String, String> env = parseEnv... | assert parseEnv("").isEmpty() : "empty";
Map<String, String> a = parseEnv("A=1\n# nope\nexport B = 2");
assert a.get("A").equals("1") : "simple";
assert a.get("B").equals("2") : "export with spaces";
Map<String, String> b = parseEnv("Q='a#b' # outside");
assert b.get("Q").equals("a#b") : "hash inside single quotes";
Ma... | pattern_matching |
5 | devbench-pattern-matching | java | import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class PMTask5 {
// Parse folded headers. "Name: value" starts a header; a line beginning
// with space or tab continues the previous header value with one space.
// Heade... | Map<String, List<String>> out = new LinkedHashMap<>();
String current = null;
for (String raw : text.split("\n", -1)) {
if (raw.isEmpty()) continue;
if ((raw.charAt(0) == ' ' || raw.charAt(0) == '\t') && current != null) {
List<String> vals = out.get(curre... | }
public static void main(String[] args) {
String h = "X-Note: one\n" +
" two\n" +
"X-Note: three\n" +
"Host: Example.COM";
Map<String, List<String>> m = parseHeaders(h);
assert m.get("x-note").equals(List.of("one two", "three"))... | assert parseHeaders("").isEmpty() : "empty";
Map<String, List<String>> a = parseHeaders("A: 1\n\t2\nB: x");
assert a.get("a").equals(List.of("1 2")) : "tab continuation";
assert a.get("b").equals(List.of("x")) : "next header";
Map<String, List<String>> b = parseHeaders("Set-Cookie: a=1\nSet-Cookie: b=2");
assert b.get(... | pattern_matching |
6 | devbench-pattern-matching | java | import java.util.LinkedHashMap;
import java.util.Map;
public class PMTask6 {
private static String stripComment(String s) {
boolean quote = false;
StringBuilder out = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '\"') quo... | Map<String, String> vars = new LinkedHashMap<>();
StringBuilder logical = new StringBuilder(); for (String raw : text.split("\n", -1)) {
String line = logical.length() > 0 ? raw.stripLeading() : raw;
if (line.endsWith("\\")) { logical.append(line, 0, line.length() - 1); continue;... | }
public static void main(String[] args) {
String mk = "CFLAGS = -O2 \\\n" +
" -Wall # keep\n" +
"CFLAGS += -g\n" +
"NAME = \"a # b\" # tail";
Map<String, String> v = parseVars(mk);
assert v.get("CFLAGS").equals("-O2 -Wall -g"... | assert parseVars("").isEmpty() : "empty";
Map<String, String> a = parseVars("A=1\nA += 2\nB = x");
assert a.get("A").equals("1 2") : "append";
assert a.get("B").equals("x") : "assign";
Map<String, String> b = parseVars("LONG = one \\\n two \\\n three");
assert b.get("LONG").equals("one two three") : "multi continuation... | pattern_matching |
7 | devbench-pattern-matching | java | public class PMTask7 {
// Max bracket nesting depth. Brackets: ( ) [ ] { }
// Brackets inside double-quoted strings IGNORED.
// In strings, backslash escapes next char. Returns -1 if unbalanced.
// maxDepth("(a[b])") = 2 | maxDepth("([)") = -1
private static final String OPEN = "([{", CLOSE = ")]... | int depth = 0, max = 0; boolean inStr = false;
java.util.Deque<Character> stk = new java.util.ArrayDeque<>();
for (int i = 0; i < expr.length(); i++) {
char ch = expr.charAt(i);
if (inStr) { if (ch == '\\') i++; else if (ch == '\"') inStr = false; }
else if (c... | }
public static void main(String[] args) {
assert maxDepth("(a[b])") == 2;
assert maxDepth("hello") == 0;
assert maxDepth("([)") == -1;
String s1 = "(" + (char)34 + "[" + (char)34 + ")";
assert maxDepth(s1) == 1 : "bracket in string";
String s2 = "({" + (char)34 ... | assert maxDepth("") == 0 : "empty";
assert maxDepth("()") == 1 : "simple parens";
assert maxDepth("((()))") == 3 : "nested parens";
assert maxDepth("([{}])") == 3 : "mixed brackets";
assert maxDepth("(]") == -1 : "mismatch";
assert maxDepth("(") == -1 : "unclosed";
| pattern_matching |
8 | devbench-pattern-matching | java | import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class PMTask8 {
private static String stripComment(String s) {
int hash = s.indexOf('#');
return hash < 0 ? s : s.substring(0, hash);
}
// Parse alias file: name: a,b starts/exte... | Map<String, List<String>> aliases = new LinkedHashMap<>();
StringBuilder logical = new StringBuilder(); for (String raw : text.split("\n", -1)) {
String line = logical.length() > 0 ? raw.stripLeading() : raw;
if (line.endsWith("\\")) { logical.append(line, 0, line.length() - 1); ... | }
public static void main(String[] args) {
String data = "dev: alice, \\\n" +
" bob # team\n" +
"ops: root\n" +
"dev: carol";
Map<String, List<String>> a = parseAliases(data);
assert a.get("dev").equals(List.of("alice", ... | assert parseAliases("").isEmpty() : "empty";
Map<String, List<String>> one = parseAliases("x: a,, b");
assert one.get("x").equals(List.of("a", "b")) : "empty recipients ignored";
Map<String, List<String>> cont = parseAliases("team: a, \\\n b, \\\n c");
assert cont.get("team").equals(List.of("a", "b", "c")) : "multi con... | pattern_matching |
9 | devbench-pattern-matching | java | public class PMTask9 {
// Custom URL normalizer (NOT standard RFC):
// 1. Strip trailing / only if last path segment has no dot
// 2. Remove fragment (#...) always 3. Remove "www." from host
// 4. Lowercase scheme+host 5. Keep query as-is
// normalizeUrl("HTTP://WWW.Ex.Com/path/") -> "http://ex.co... | int se = url.indexOf("://"); if (se == -1) return url;
String scheme = url.substring(0, se).toLowerCase(), rest = url.substring(se + 3);
int fi = rest.indexOf('#'); if (fi >= 0) rest = rest.substring(0, fi);
int ps = rest.indexOf('/');
String host = (ps == -1 ? rest : rest.substr... | }
public static void main(String[] args) {
assert normalizeUrl("HTTP://WWW.Example.Com/path/").equals("http://example.com/path");
assert normalizeUrl("http://site.com/file.html/").equals("http://site.com/file.html/");
assert normalizeUrl("http://x.com/a#frag").equals("http://x.com/a");
... | assert normalizeUrl("https://WWW.TEST.COM").equals("https://test.com") : "no path";
assert normalizeUrl("http://a.com/b/c/").equals("http://a.com/b/c") : "strip trailing slash";
assert normalizeUrl("http://a.com/b/c.js/").equals("http://a.com/b/c.js/") : "keep slash after ext";
assert normalizeUrl("http... | pattern_matching |
10 | devbench-pattern-matching | java | import java.util.LinkedHashMap;
import java.util.Map;
public class PMTask10 {
private static String stripComment(String s) {
boolean q = false; StringBuilder out = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '\"') q = !q;
... | Map<String, String> routes = new LinkedHashMap<>();
StringBuilder pending = new StringBuilder();
for (String raw : text.split("\n", -1)) {
String line = pending.length() > 0 ? raw.stripLeading() : raw;
if (line.endsWith("\\")) { pending.append(line, 0, line.length() - 1);... | }
public static void main(String[] args) {
String table = "GET /users -> \\\n" +
" userIndex # visible route\n" +
"POST /msg -> \"save#draft\" # comment";
Map<String, String> r = parseRoutes(table);
assert r.get("GET /users").equals("userIn... | assert parseRoutes("").isEmpty() : "empty";
Map<String, String> a = parseRoutes("GET / -> root\n# skip\nBAD LINE");
assert a.get("GET /").equals("root") : "basic route";
Map<String, String> b = parseRoutes("PUT /a -> one \\\n two \\\n three");
assert b.get("PUT /a").equals("one two three") : "continued handler";
Map<St... | pattern_matching |
11 | devbench-pattern-matching | java | import java.nio.charset.StandardCharsets;
public class PMTask11 {
private static final String HEX = "0123456789ABCDEF";
public static String hexByte(int b) {
return "%" + HEX.charAt((b >> 4) & 0xF) + HEX.charAt(b & 0xF);
}
public static boolean isUnreserved(char ch) {
return (ch >= 'A... | byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
char ch = (char) (b & 0xFF);
if (b >= 0 && isUnreserved(ch) || safe.indexOf(ch) >= 0) {
sb.append(ch);
} else {
... | }
public static void main(String[] args) {
assert hexByte(32).equals("%20") : "hexByte(32) failed";
assert isUnreserved('A') == true;
assert isUnreserved('_') == false : "_ must NOT be unreserved";
// This URL encoder only leaves alphanumerics unescaped by default.
// U... | assert urlEncode("").equals("") : "empty input";
assert urlEncode("abcXYZ123").equals("abcXYZ123") : "alphanums unchanged";
assert urlEncode("a+b=c").equals("a%2Bb%3Dc") : "plus and equals encoded";
assert urlEncode("hello_world").equals("hello%5Fworld") : "underscore encoded";
assert urlEncode("x/y... | pattern_matching |
12 | devbench-pattern-matching | java | public class PMTask12 {
public static int charType(char ch) {
if (Character.isLetter(ch)) return 0;
if (Character.isDigit(ch)) return 1;
return 2;
}
public static int charCost(char a, char b) {
if (a == b) return 0;
int ta = charType(a), tb = charType(b);
if ... | if (a.length() != b.length()) {
throw new IllegalArgumentException("Strings must be equal length");
}
int total = 0;
for (int i = 0; i < a.length(); i++) {
total += charCost(a.charAt(i), b.charAt(i));
}
return total;
| }
public static void main(String[] args) {
assert charType('a') == 0 : "letter type";
assert charType('5') == 1 : "digit type";
assert charCost('a', 'b') == 1 : "letter-letter cost";
assert charCost('1', '2') == 2 : "digit-digit cost";
assert charCost('a', '1') == 3 : "m... | assert hammingDistance("a", "b") == 1 : "single letter diff";
assert hammingDistance("1", "2") == 2 : "single digit diff";
assert hammingDistance("a", "1") == 3 : "single mixed diff";
assert hammingDistance("ab12", "cd34") == 6 : "2 letter + 2 digit diffs";
assert hammingDistance("a1b2", "1a2b") == ... | pattern_matching |
13 | devbench-pattern-matching | java | import java.util.LinkedHashMap;
import java.util.Map;
public class PMTask13 {
private static String stripComment(String s) {
boolean q = false; StringBuilder out = new StringBuilder();
for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == '\'') q = !q; if (c == '#' && !q) break; out... | Map<String, String> rules = new LinkedHashMap<>();
StringBuilder buf = new StringBuilder();
for (String raw : text.split("\n", -1)) {
String line = buf.length() > 0 ? raw.stripLeading() : raw;
if (line.endsWith("\\")) { buf.append(line, 0, line.length() - 1); continue; }
... | }
public static void main(String[] args) {
String src = "auth: /login \\\n" +
" -> AuthController # comment\n" +
"hash: '#not-comment' -> Keep";
Map<String, String> r = parseRules(src);
assert r.get("auth").equals("/login => AuthController") : ... | assert parseRules("").isEmpty() : "empty";
Map<String, String> a = parseRules("one: a -> b\n# skip");
assert a.get("one").equals("a => b") : "basic";
Map<String, String> b = parseRules("long: alpha \\\n beta -> gamma \\\n delta");
assert b.get("long").equals("alpha beta => gamma delta") : "continued pattern and action"... | pattern_matching |
14 | devbench-pattern-matching | java | import java.util.Map;
import java.util.HashMap;
public class PMTask14 {
// Reversed Morse: swap dots and dashes from standard
private static final Map<Character, String> MORSE = new HashMap<>();
static {
String[] standard = {".-","-...","-.-.","-..",".","..-.","--.","....","..",
".---",... | StringBuilder sb = new StringBuilder();
boolean first = true;
for (char ch : text.toUpperCase().toCharArray()) {
if (ch == ' ') { sb.append("||"); first = true; }
else if (MORSE.containsKey(ch)) {
if (!first) sb.append("|");
sb.append(MORSE... | }
public static void main(String[] args) {
// Reversed Morse: A is "-." not ".-", uses "|" separator, "||" for word boundary
assert MORSE.get('A').equals("-.") : "A must be -. (reversed)";
assert MORSE.get('E').equals("-") : "E must be - (reversed)";
assert MORSE.get('T').equals... | assert morseEncode("").equals("") : "empty input";
assert morseEncode("E").equals("-") : "single E";
assert morseEncode("T").equals(".") : "single T";
assert morseEncode("HI").equals("----|--");
assert morseEncode("A B C").equals("-.||.---||.-.-");
assert morseEncode("hello").equals("----|-|-.--... | pattern_matching |
15 | devbench-pattern-matching | java | import java.util.LinkedHashMap;
import java.util.Map;
public class PMTask15 {
// Parse translation file: [locale] starts a section; key=value lines become
// locale.key -> value. Backslash-newline joins continued values. # comments skip.
public static Map<String, String> parseTranslations(String text) {
| Map<String, String> out = new LinkedHashMap<>();
String locale = ""; StringBuilder buf = new StringBuilder();
for (String raw : text.split("\n", -1)) {
String line = buf.length() > 0 ? raw.stripLeading() : raw;
if (line.endsWith("\\")) { buf.append(line, 0, line.length() ... | }
public static void main(String[] args) {
String t = "[en]\nhello=Hello \\\n" +
" world\n# skip\n[fr]\nhello=Bonjour";
Map<String, String> m = parseTranslations(t);
assert m.get("en.hello").equals("Hello world") : m;
assert m.get("fr.hello").equals("Bonjour"... | assert parseTranslations("").isEmpty() : "empty";
Map<String, String> a = parseTranslations("title=Global");
assert a.get("title").equals("Global") : "global key";
Map<String, String> b = parseTranslations("[es]\na=uno\nb=dos");
assert b.get("es.a").equals("uno") && b.get("es.b").equals("dos") : "section keys";
Map<Str... | pattern_matching |
16 | devbench-pattern-matching | java | import java.util.Map;
import java.util.HashMap;
public class PMTask16 {
public static String parseTemplate(String template, Map<String, String> vars) {
| StringBuilder sb = new StringBuilder();
for (int i = 0; i < template.length(); ) {
char ch = template.charAt(i);
if (ch == '\\' && i + 1 < template.length()) { sb.append(template.charAt(i + 1)); i += 2; }
else if (ch == '$' && i + 1 < template.length() && template.cha... | }
public static void main(String[] args) {
Map<String, String> vars = new HashMap<>();
vars.put("name", "World");
vars.put("greeting", "Hello");
// parseTemplate: ${var} replaced, \\$ is literal $
// Unclosed ${ left as-is, unknown vars kept as ${varName}
assert... | Map<String, String> v = new HashMap<>();
v.put("x", "1");
v.put("y", "2");
assert parseTemplate("", v).equals("") : "empty template";
assert parseTemplate("no vars here", v).equals("no vars here") : "no placeholders";
assert parseTemplate("${x}+${y}", v).equals("1+2") : "two vars";
assert pa... | pattern_matching |
17 | devbench-pattern-matching | java | import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Map;
public class PMTask17 {
private static final Map<Character, Character> PAIRS = Map.of(
'(', ')', '[', ']', '{', '}'
);
public static boolean isBalancedCode(String text) {
| Deque<Character> stack = new ArrayDeque<>();
boolean inStr = false;
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
if (inStr) { if (ch == '\\' && i+1 < text.length()) { i++; } else if (ch == '"') inStr = false; }
else if (ch == '"') inStr ... | }
public static void main(String[] args) {
// isBalancedCode: bracket matching that ignores brackets inside "strings"
// Handles \" escape sequences inside strings
assert isBalancedCode("f(x)") == true;
assert isBalancedCode("f(\"(\")") == true : "bracket inside string ignored";... | assert isBalancedCode("") == true : "empty string";
assert isBalancedCode("()") == true : "simple parens";
assert isBalancedCode("(") == false : "unclosed paren";
assert isBalancedCode("\"unclosed") == false : "unclosed string";
assert isBalancedCode("{\"key\": \"val\"}") == true : "JSON-like";
... | pattern_matching |
18 | devbench-pattern-matching | java | import java.util.Map;
import java.util.LinkedHashMap;
public class PMTask18 {
public static Map<String, String> parseConfig(String input) {
| Map<String, String> result = new LinkedHashMap<>();
String sec = "";
StringBuilder joined = new StringBuilder();
for (String line : input.split("\n", -1)) {
if (line.endsWith("\\")) { joined.append(line, 0, line.length() - 1); continue; }
joined.append(line);
... | }
public static void main(String[] args) {
// parseConfig: INI-style with line continuation (trailing \),
// # comments, [section] prefixes keys with "section."
String cfg = "[db]\nhost=localhost\nport=5432\n# comment\n[app]\nname=my\\\napp\nversion=1.0";
Map<String, String> m =... | Map<String, String> m2 = parseConfig("key=value");
assert m2.get("key").equals("value") : "simple key=value";
Map<String, String> m3 = parseConfig("[s]\na=1\nb=2");
assert m3.get("s.a").equals("1") : "section prefix";
assert m3.get("s.b").equals("2") : "second key";
Map<String, String> m4 = pars... | pattern_matching |
19 | devbench-pattern-matching | java | import java.util.LinkedHashMap;
import java.util.Map;
public class PMTask19 {
// Parse ssh-config style text. "Host name" sets current host.
// Following "Key value" lines are stored as host.key -> value.
// Backslash-newline joins continued values; # comments are ignored.
public static Map<String, Str... | Map<String, String> out = new LinkedHashMap<>();
String host = ""; StringBuilder buf = new StringBuilder();
for (String raw : text.split("\n", -1)) {
String line = buf.length() > 0 ? raw.stripLeading() : raw;
if (line.endsWith("\\")) { buf.append(line, 0, line.length() - ... | }
public static void main(String[] args) {
String cfg = "Host prod\n" +
"User deploy\n" +
"IdentityFile ~/.ssh/\\\n" +
" prod_key # comment\n" +
"Host test\nUser tester";
Map<String, String> m = parseSshConfig(... | assert parseSshConfig("").isEmpty() : "empty";
Map<String, String> a = parseSshConfig("Host a\nPort 22\nHost b\nPort 2200");
assert a.get("a.port").equals("22") && a.get("b.port").equals("2200") : "host context";
Map<String, String> b = parseSshConfig("Host x\nProxyCommand one \\\n two \\\n three");
assert b.get("x.pro... | pattern_matching |
20 | devbench-pattern-matching | java | public class PMTask20 {
// Custom slugify: lowercase, non-alnum -> hyphen, collapse hyphens,
// strip leading/trailing hyphens.
// ADDITIONALLY: insert hyphen at camelCase boundaries (lower->Upper)
// AND at letter<->digit boundaries.
public static String slugify(String input) {
| StringBuilder sb = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
if (!Character.isLetterOrDigit(ch)) { if (sb.length() > 0 && sb.charAt(sb.length() - 1) != '-') sb.append('-'); continue; }
if (sb.length() > 0 && sb.charAt(s... | }
public static void main(String[] args) {
// Custom slugify with camelCase and digit boundary splitting
assert slugify("helloWorld").equals("hello-world") : "camelCase";
assert slugify("item3pack").equals("item-3-pack") : "digit boundaries";
assert slugify("hello world").equals... | assert slugify("").equals("") : "empty input";
assert slugify("simple").equals("simple") : "no changes needed";
assert slugify("test123").equals("test-123") : "letter to digit";
assert slugify("123test").equals("123-test") : "digit to letter";
assert slugify("hello--world!!").equals("hello-world") :... | pattern_matching |
21 | devbench-pattern-matching | java | import java.util.LinkedHashMap;
import java.util.Map;
public class PMTask21 {
// Parse Dockerfile ENV instructions. Supports "ENV KEY=value" and
// "ENV KEY value". Backslash-newline joins continued logical lines.
// Comments and non-ENV instructions are ignored.
public static Map<String, String> parse... | Map<String, String> env = new LinkedHashMap<>();
StringBuilder buf = new StringBuilder();
for (String raw : text.split("\n", -1)) {
String line = buf.length() > 0 ? raw.stripLeading() : raw;
if (line.endsWith("\\")) { buf.append(line, 0, line.length() - 1); continue; }
... | }
public static void main(String[] args) {
String df = "FROM base\nENV PATH=/opt/\\\n" +
" bin\nENV MODE production\n# ENV SKIP=1";
Map<String, String> env = parseDockerEnv(df);
assert env.get("PATH").equals("/opt/bin") : env;
assert env.get("MODE").equals("... | assert parseDockerEnv("").isEmpty() : "empty";
Map<String, String> a = parseDockerEnv("ENV A=1\nRUN echo no\nENV B two words");
assert a.get("A").equals("1") && a.get("B").equals("two words") : "both forms";
Map<String, String> b = parseDockerEnv("ENV LONG=one \\\n two \\\n three");
assert b.get("LONG").equals("one two... | pattern_matching |
22 | devbench-pattern-matching | java | import java.util.LinkedHashMap;
import java.util.Map;
public class PMTask22 {
// Parse systemd-like unit text. [Section] prefixes keys as Section.key.
// Duplicate keys append with '|'. Backslash-newline joins continued values.
public static Map<String, String> parseUnit(String text) {
| Map<String, String> out = new LinkedHashMap<>();
String section = ""; StringBuilder buf = new StringBuilder();
for (String raw : text.split("\n", -1)) {
String line = buf.length() > 0 ? raw.stripLeading() : raw;
if (line.endsWith("\\")) { buf.append(line, 0, line.length()... | }
public static void main(String[] args) {
String unit = "[Service]\nExecStart=/bin/app \\\n" +
" --flag\nExecStart=/bin/sidecar\n[Install]\nWantedBy=multi-user.target";
Map<String, String> u = parseUnit(unit);
assert u.get("Service.ExecStart").equals("/bin/app --... | assert parseUnit("").isEmpty() : "empty";
Map<String, String> a = parseUnit("Key=global\n[S]\nA=1\nA=2");
assert a.get("Key").equals("global") : "global key";
assert a.get("S.A").equals("1|2") : "duplicates append";
Map<String, String> b = parseUnit("[X]\nLong=one \\\n two \\\n three");
assert b.get("X.Long").equals("o... | pattern_matching |
23 | devbench-pattern-matching | java | import java.util.LinkedHashMap;
import java.util.Map;
public class PMTask23 {
private static String stripComment(String s) {
boolean q = false; StringBuilder out = new StringBuilder();
for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == '\"') q = !q; if (c == '#' && !q) break; out... | Map<String, String> labels = new LinkedHashMap<>();
StringBuilder buf = new StringBuilder();
for (String raw : text.split("\n", -1)) {
String line = buf.length() > 0 ? raw.stripLeading() : raw;
if (line.endsWith("\\")) { buf.append(line, 0, line.length() - 1); continue; }... | }
public static void main(String[] args) {
String text = "owner=platform\npath=/srv/\\\n" +
" api # comment\nnote=\"keep # hash\"";
Map<String, String> m = parseLabels(text);
assert m.get("owner").equals("platform") : m;
assert m.get("path").equals("/srv/a... | assert parseLabels("").isEmpty() : "empty";
Map<String, String> a = parseLabels("a=1\n# skip\nb = 2");
assert a.get("a").equals("1") && a.get("b").equals("2") : "basic labels";
Map<String, String> b = parseLabels("long=one \\\n two \\\n three");
assert b.get("long").equals("one two three") : "continued value";
Map<Stri... | pattern_matching |
24 | devbench-pattern-matching | java | import java.util.LinkedHashMap;
import java.util.Map;
public class PMTask24 {
private static String stripComment(String s) {
boolean q = false; StringBuilder out = new StringBuilder();
for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == '\"') q = !q; if (c == '#' && !q) break; out... | Map<String, String> out = new LinkedHashMap<>();
String profile = ""; StringBuilder buf = new StringBuilder();
for (String raw : text.split("\n", -1)) {
String line = buf.length() > 0 ? raw.stripLeading() : raw;
if (line.endsWith("\\")) { buf.append(line, 0, line.length()... | }
public static void main(String[] args) {
String src = "[prod]\nurl=https://api/\\\n" +
" v1 # tail\nnote=\"keep # hash\"\n[dev]\nurl=http://local";
Map<String, String> p = parseProfiles(src);
assert p.get("prod.url").equals("https://api/v1") : p;
assert p... | assert parseProfiles("").isEmpty() : "empty";
Map<String, String> a = parseProfiles("root=1\n[x]\na=2");
assert a.get("root").equals("1") && a.get("x.a").equals("2") : "global plus section";
Map<String, String> b = parseProfiles("[p]\nlong=one \\\n two \\\n three");
assert b.get("p.long").equals("one two three") : "con... | pattern_matching |
25 | devbench-pattern-matching | java | public class PMTask25 {
// Custom CRC-8: poly 0x1D (not standard 0x07), init 0xFF (not 0x00)
private static final int POLY = 0x1D;
private static final int INIT = 0xFF;
public static int crc8(byte[] data) {
| int crc = INIT;
for (byte b : data) {
crc ^= (b & 0xFF);
for (int i = 0; i < 8; i++) {
if ((crc & 0x80) != 0) crc = ((crc << 1) ^ POLY) & 0xFF;
else crc = (crc << 1) & 0xFF;
}
}
return crc;
| }
public static void main(String[] args) {
int result = crc8("123456789".getBytes());
assert result != 0xF4 : "Must not match standard CRC-8";
System.out.println("OK: 0x" + Integer.toHexString(result));
}
}
| assert crc8(new byte[]{}) == INIT : "empty returns init";
assert crc8(new byte[]{0}) != 0 : "single zero with init 0xFF";
assert crc8("123456789".getBytes()) != 0xF4 : "not standard CRC-8";
| pattern_matching |
26 | devbench-pattern-matching | java | import java.util.List;
import java.util.ArrayList;
public class PMTask26 {
// Parse CSV using backtick (`) as quote char. Escaped: `` -> literal `.
// Commas inside quoted fields are literal. Unquoted fields are trimmed.
public static List<String> parseCsvLine(String line) {
List<String> fields = n... | while (i < line.length()) {
char ch = line.charAt(i);
if (inQ && ch == '`' && i+1 < line.length() && line.charAt(i+1) == '`') { cur.append('`'); i += 2; continue; }
if (inQ && ch == '`') { inQ = false; i++; continue; }
if (inQ) { cur.append(ch); }
else... | }
public static void main(String[] args) {
List<String> r1 = parseCsvLine("a,b,c");
assert r1.size() == 3 && r1.get(0).equals("a") : r1.toString();
List<String> r2 = parseCsvLine("`hello, world`,42");
assert r2.size() == 2 && r2.get(0).equals("hello, world") : r2.toString();
... | List<String> e = PMTask26.parseCsvLine("");
assert e.size() == 1 && e.get(0).equals("") : "empty";
List<String> q = PMTask26.parseCsvLine("`,`,x");
assert q.size() == 2 && q.get(0).equals(",") : "quoted comma";
List<String> t = PMTask26.parseCsvLine(" a , b ");
assert t.get(0).equals("a") && t.get(1).equals("b") : "tri... | pattern_matching |
27 | devbench-pattern-matching | java | import java.util.Map;
import java.util.HashMap;
public class PMTask27 {
// Template engine: {{key}} -> value. Escaped \{{ -> literal {{.
// Unknown keys left as-is. Must parse char-by-char for escape handling.
public static String render(String tpl, Map<String, String> vars) {
StringBuilder sb = ne... | while (i < tpl.length()) {
if (i+1 < tpl.length() && tpl.charAt(i) == '\\' && tpl.charAt(i+1) == '{') { sb.append('{'); i += 2; }
else if (i+1 < tpl.length() && tpl.charAt(i) == '{' && tpl.charAt(i+1) == '{') {
int end = tpl.indexOf("}}", i+2);
if (end < 0... | }
public static void main(String[] args) {
Map<String, String> v = new HashMap<>();
v.put("name", "Alice");
v.put("greeting", "Hello");
assert render("{{greeting}}, {{name}}!", v).equals("Hello, Alice!");
assert render("Use \\{{var}} syntax", v).equals("Use {{var}} synta... | Map<String, String> tv = new HashMap<>();
tv.put("x", "1");
assert PMTask27.render("", tv).equals("") : "empty";
assert PMTask27.render("no vars", tv).equals("no vars") : "no placeholders";
assert PMTask27.render("{{x}}", tv).equals("1") : "simple";
assert PMTask27.render("a{{x}}b{{x}}c", tv).equals("a1b1c") : "multi";... | pattern_matching |
28 | devbench-pattern-matching | java | import java.util.Map;
import java.util.LinkedHashMap;
public class PMTask28 {
// INI parser: [section] creates "section.key" entries.
// Lines ending with \ are continuation lines (joined with next).
// # lines are comments. Returns flat map of section.key -> value.
public static Map<String, String> pa... | for (String line : raw) {
if (line.endsWith("\\")) { merged.append(line, 0, line.length()-1); continue; }
merged.append(line);
String full = merged.toString().trim(); merged.setLength(0);
if (full.isEmpty() || full.startsWith("#")) continue;
if (full.s... | }
public static void main(String[] args) {
String ini = "[db]\nhost=localhost\nport=5432\n[app]\nname=my\\\napp\ndebug=true";
Map<String, String> cfg = parseIni(ini);
assert cfg.get("db.host").equals("localhost") : "db.host";
assert cfg.get("db.port").equals("5432") : "db.port";... | Map<String, String> r = PMTask28.parseIni("");
assert r.isEmpty() : "empty input";
Map<String, String> r2 = PMTask28.parseIni("# comment\nk=v");
assert r2.get("k").equals("v") : "global key";
assert r2.size() == 1 : "comment ignored";
| pattern_matching |
29 | devbench-pattern-matching | java | public class PMTask29 {
// Custom RLE: format "NxC" for runs N>1, just "C" for singles.
// e.g. "aaabbc" -> "3xa2xbc". NOT standard "a3b2c1" or "3a2b1c".
public static String runLengthEncode(String input) {
if (input == null || input.isEmpty()) return "";
StringBuilder sb = new StringBuilder... | while (i < input.length()) {
char ch = input.charAt(i);
int count = 1;
while (i + count < input.length() && input.charAt(i + count) == ch) count++;
if (count > 1) sb.append(count).append('x').append(ch);
else sb.append(ch);
i += count;
... | }
public static void main(String[] args) {
assert runLengthEncode("aaabbc").equals("3xa2xbc") : runLengthEncode("aaabbc");
assert runLengthEncode("a").equals("a") : "single";
assert runLengthEncode("aaa").equals("3xa") : "all same";
assert !runLengthEncode("aaabbc").equals("3a2b... | assert PMTask29.runLengthEncode("").equals("") : "empty";
assert PMTask29.runLengthEncode("abcde").equals("abcde") : "no repeats";
assert PMTask29.runLengthEncode("aabb").equals("2xa2xb") : "pairs";
assert PMTask29.runLengthEncode("aaaa").equals("4xa") : "four same";
| pattern_matching |
30 | devbench-pattern-matching | java | public class PMTask30 {
// Custom version comparison: alpha segments > numeric (opposite of semver).
// Leading-zero numeric segments compared as strings. Fewer segments = less.
public static int versionCompare(String a, String b) {
String[] pa = a.split("\\.");
String[] pb = b.split("\\.");... | for (int i = 0; i < len; i++) {
if (i >= pa.length) return -1; if (i >= pb.length) return 1;
String sa = pa[i], sb = pb[i];
boolean an = sa.matches("[0-9]+"), bn = sb.matches("[0-9]+");
boolean lz = (an && sa.length()>1 && sa.charAt(0)=='0') || (bn && sb.length()... | }
public static void main(String[] args) {
assert versionCompare("1.0.alpha", "1.0.1") > 0 : "alpha > numeric";
assert versionCompare("1.2", "1.10") < 0 : "2 < 10";
assert versionCompare("1.0", "1.0.0") < 0 : "fewer segments";
assert versionCompare("1.01", "1.1") < 0 : "leading ... | assert PMTask30.versionCompare("1.0", "1.0") == 0 : "equal";
assert PMTask30.versionCompare("2.0", "1.0") > 0 : "major";
assert PMTask30.versionCompare("1.0.beta", "1.0.alpha") > 0 : "beta > alpha";
assert PMTask30.versionCompare("1.0.alpha", "1.0.0") > 0 : "alpha > numeric";
| pattern_matching |
31 | devbench-pattern-matching | java | import java.util.LinkedHashMap;
import java.util.Map;
public class PMTask31 {
// Custom HTML entity mapping — extends standard with extra symbols
private static final Map<Character, String> CUSTOM_ENTITIES = new LinkedHashMap<>();
static {
CUSTOM_ENTITIES.put('&', "&");
CUSTOM_ENTITIES.... | if (input == null) return "";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (entities.containsKey(c)) {
sb.append(entities.get(c));
} else {
sb.append(c);
... | }
public static void main(String[] args) {
// Default uses CUSTOM_ENTITIES which escapes @, #, $ too
String r1 = htmlEscape("a@b#c$d");
assert r1.equals("a@b#c$d") : "custom entities: " + r1;
// Standard mode should NOT escape @, #, $
String r2 = htmlEs... | assert htmlEscape("").equals("") : "empty input";
assert htmlEscape(null).equals("") : "null input";
assert htmlEscape("plain text").equals("plain text") : "no special chars";
assert htmlEscape("&").equals("&") : "ampersand";
assert htmlEscape("$100 @user #tag").equals("$100 @user #tag") : "all cu... | pattern_matching |
32 | devbench-pattern-matching | java | public class PMTask32 {
// ISBN-13 check digit calculator with CUSTOM weight pattern
// Standard ISBN-13 uses alternating weights [1, 3, 1, 3, ...]
// This version uses [1, 5, 1, 5, ...] for a custom barcode system
private static final int[] CUSTOM_WEIGHTS = {1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5};
pri... | int sum = 0;
for (int i = 0; i < 12; i++) {
sum += (digits12.charAt(i) - '0') * weights[i];
}
int rem = sum % 10;
return (rem == 0) ? 0 : 10 - rem;
| }
public static void main(String[] args) {
// "978030640615" -> standard ISBN-13 check digit is 7
int custom = isbn13CheckDigit("978030640615");
int standard = isbn13CheckDigit("978030640615", STANDARD_WEIGHTS);
assert standard == 7 : "standard check digit: " + standard;
... | assert isbn13CheckDigit("000000000000") == 0 : "all zeros";
assert isbn13CheckDigit("100000000000") == 9 : "leading one custom";
assert isbn13CheckDigit("100000000000", STANDARD_WEIGHTS) == 9 : "leading one standard";
assert isbn13CheckDigit("111111111111") != isbn13CheckDigit("111111111111", STANDARD_WEIGHTS) : "custo... | pattern_matching |
33 | devbench-pattern-matching | java | public class PMTask33 {
// Run-length encoding with CUSTOM format: "3xa" instead of standard "a3" or "aaa"
// Single chars are kept as-is (no "1xa"), runs of 2+ get "Nxc" format
// The separator 'x' distinguishes count from character.
// Example: "aaabbc" -> "3xa2xbc" (NOT "a3b2c1" or "3a2b1c")
// E... | if (input == null || input.isEmpty()) return "";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < input.length(); ) {
char c = input.charAt(i);
int cnt = 1;
while (i + cnt < input.length() && input.charAt(i + cnt) == c) cnt++;
sb.append(... | }
public static void main(String[] args) {
// Standard RLE for "aaabbc" is "a3b2c1" or "3a2b1c" — this uses "3xa2xbc"
String r1 = runLengthEncode("aaabbc");
assert r1.equals("3xa2xbc") : "got: " + r1;
assert !r1.equals("a3b2c1") : "must not use standard format a3b2c1";
a... | assert runLengthEncode("").equals("") : "empty input";
assert runLengthEncode(null).equals("") : "null input";
assert runLengthEncode("a").equals("a") : "single char";
assert runLengthEncode("aa").equals("2xa") : "two chars";
assert runLengthEncode("aaabbbccc").equals("3xa3xb3xc") : "three runs";
assert runLengthEncode... | pattern_matching |
34 | devbench-pattern-matching | java | import java.util.ArrayList;
import java.util.List;
public class PMTask34 {
// Bracket-aware CSV field splitter: splits on commas, but commas inside
// matched brackets (parentheses, square, curly) are NOT delimiters.
// Brackets can nest. Unmatched brackets are treated as regular characters.
// Fields ... | List<String> fields = new ArrayList<>();
StringBuilder cur = new StringBuilder();
int depth = 0;
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
if ("([{".indexOf(c) >= 0) { depth++; cur.append(c); }
else if (")]}".indexOf(c) >= 0 &&... | }
public static void main(String[] args) {
List<String> r1 = splitFields("a, b, c");
assert r1.size() == 3 : "size: " + r1.size();
assert r1.get(0).equals("a") : r1.get(0);
assert r1.get(1).equals("b") : r1.get(1);
// Commas inside brackets are preserved
List<Str... | assert splitFields("").size() == 1 : "empty gives one empty field";
assert splitFields("").get(0).equals("") : "empty field";
assert splitFields("a").size() == 1 : "single field";
assert splitFields("a,b,c").size() == 3 : "three fields";
assert splitFields("{a,b},c").size() == 2 : "curly brackets";
assert splitFields("... | pattern_matching |
35 | devbench-pattern-matching | java | import java.util.LinkedHashMap;
import java.util.Map;
public class PMTask35 {
// INI-style config parser with line continuation (trailing backslash)
// Lines ending with \ are joined with the next line (backslash removed).
// Lines starting with # or ; are comments. Empty lines are skipped.
// Format: ... | Map<String, String> result = new LinkedHashMap<>();
StringBuilder pending = new StringBuilder();
for (String raw : text.split("\n", -1)) {
if (raw.endsWith("\\")) { pending.append(raw, 0, raw.length() - 1); continue; }
pending.append(raw);
String line = pendin... | }
public static void main(String[] args) {
String cfg = "name = Alice\n" +
"# comment\n" +
"path = /home/\\\n" +
"alice/docs\n" +
"; another comment\n" +
"count = 42";
Map<String, String> m ... | assert parseConfig("").size() == 0 : "empty";
assert parseConfig("# comment only").size() == 0 : "comment only";
assert parseConfig("; also comment").size() == 0 : "semicolon comment";
assert parseConfig("k=v").get("k").equals("v") : "no spaces";
assert parseConfig("k = v").get("k").equals("v") : "with spaces";
assert ... | pattern_matching |
36 | devbench-pattern-matching | java | public class PMTask36 {
// Caesar cipher that shifts ALL printable ASCII (32-126), not just letters.
// Standard Caesar only shifts a-z/A-Z and leaves spaces, digits, punctuation unchanged.
// This version treats ALL 95 printable ASCII characters (space through tilde) as a
// single alphabet and shifts ... | StringBuilder sb = new StringBuilder();
shift = ((shift % 95) + 95) % 95; // normalize to [0, 94]
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c >= 32 && c <= 126) sb.append((char)((c - 32 + shift) % 95 + 32));
else sb.append(c);
... | }
public static void main(String[] args) {
// Standard Caesar("abc", 1) = "bcd", this also shifts spaces and punctuation
assert caesarCipher("abc", 1).equals("bcd") : caesarCipher("abc", 1);
// Space (32) shifted by 1 = '!' (33)
assert caesarCipher(" ", 1).equals("!") : "space s... | assert caesarCipher("", 5).equals("") : "empty";
assert caesarCipher("abc", 0).equals("abc") : "zero shift";
assert caesarCipher("abc", 95).equals("abc") : "full wrap shift";
assert caesarCipher("abc", -1).equals("`ab") : "negative shift";
assert caesarCipher("Hello World!", 1).equals("Ifmmp!Xpsme\"") : "sentence shift... | pattern_matching |
37 | devbench-pattern-matching | java | public class PMTask37 {
// Simple infix expression evaluator for +, -, *, / with integer arithmetic.
// Supports parentheses. NO operator precedence — strictly left-to-right
// evaluation (unless overridden by parentheses). All numbers are non-negative ints.
// This is NOT standard math precedence — 2+3... | int result = atom(e);
while (p < e.length() && "+-*/".indexOf(e.charAt(p)) >= 0) {
char op = e.charAt(p++); int r = atom(e);
result = op=='+' ? result+r : op=='-' ? result-r : op=='*' ? result*r : result/r;
}
return result;
}
private static int atom(String... | }
public static void main(String[] args) {
// Left-to-right: 2+3*4 = (2+3)*4 = 20, NOT 14
assert evalExpr("2+3*4") == 20 : "l-to-r: " + evalExpr("2+3*4");
assert evalExpr("2+3*4") != 14 : "must NOT use standard precedence";
// Parentheses override: 2+(3*4) = 2+12 = 14
as... | assert evalExpr("42") == 42 : "single number";
assert evalExpr("0") == 0 : "zero";
assert evalExpr("1+2+3+4") == 10 : "chain add";
assert evalExpr("10*2+3") == 23 : "mul then add l-to-r";
assert evalExpr("(10*2)+3") == 23 : "parens match l-to-r";
assert evalExpr("10*(2+3)") == 50 : "parens override";
assert evalExpr("2... | pattern_matching |
38 | devbench-pattern-matching | java | public class PMTask38 {
// Luhn-like check digit calculator with REVERSED doubling position.
// Standard Luhn: doubles every SECOND digit from the RIGHT (positions 1, 3, 5, ...).
// This version: doubles every FIRST digit from the RIGHT (positions 0, 2, 4, ...).
// Position 0 = rightmost digit. So the r... | int sum = 0;
for (int i = digits.length() - 1; i >= 0; i--) {
int d = digits.charAt(i) - '0';
int pos = digits.length() - 1 - i;
if (pos % 2 == 0) { d *= 2; if (d > 9) d -= 9; }
sum += d;
}
return sum % 10 == 0 ? 0 : 10 - sum % 10;
| }
public static void main(String[] args) {
// For "7992739871":
// Standard Luhn doubles odd positions from right -> check digit = 4
// This version doubles even positions from right -> check digit = 3
int result = luhnCheckDigit("7992739871");
assert result != 4 : "must... | assert luhnCheckDigit("0") == 0 : "single zero doubled is still 0";
assert luhnCheckDigit("5") == 9 : "single 5: 5*2=10->1, check=(10-1)=9";
assert luhnCheckDigit("00") == 0 : "two zeros";
assert luhnCheckDigit("1234") == 4 : "custom for 1234";
assert luhnCheckDigit("1234") != 6 : "must differ from standard Luhn for 12... | pattern_matching |
39 | devbench-pattern-matching | java | import java.util.Arrays;
public class PMTask39 {
// Deterministic Fisher-Yates shuffle using a custom LCG (Linear Congruential Generator).
// LCG formula: next = (a * current + c) % m
// Default params: a=5, c=3, m=16
public static int[] deterministicShuffle(int[] arr, long seed) {
return dete... | int[] result = Arrays.copyOf(arr, arr.length);
long state = seed;
for (int i = result.length - 1; i > 0; i--) {
state = (a * state + c) % m;
int j = (int)(state % (i + 1));
int tmp = result[i];
result[i] = result[j];
result[j] = tmp;
... | }
public static void main(String[] args) {
int[] input = {1, 2, 3, 4, 5};
int[] result = deterministicShuffle(input, 7);
// seed=7: state=(5*7+3)%16=6, j=6%5=1, swap(4,1) -> [1,5,3,4,2]
// state=(5*6+3)%16=1, j=1%4=1, swap(3,1) -> [1,4,3,5,2]
// state=(5*1+3)%16=8, j=8%3... | assert deterministicShuffle(new int[]{}, 0).length == 0 : "empty array";
assert deterministicShuffle(new int[]{42}, 0).length == 1 : "single element";
assert deterministicShuffle(new int[]{42}, 0)[0] == 42 : "single element value";
assert Arrays.equals(deterministicShuffle(new int[]{1,2,3,4,5}, 7), deterministicShuffle... | pattern_matching |
40 | devbench-pattern-matching | java | public class PMTask40 {
// Format a duration in seconds to a human-readable string.
// Custom thresholds: 1 minute = 100 seconds, 1 hour = 100 minutes, 1 day = 10 hours
// Standard: 1 min = 60s, 1 hour = 60 min, 1 day = 24 hours
// Format: "Xd Xh Xm Xs" omitting zero components, or "0s" for zero.
p... | if (totalSeconds == 0) return "0s";
int d = totalSeconds / 100000; totalSeconds %= 100000;
int h = totalSeconds / 10000; totalSeconds %= 10000;
int m = totalSeconds / 100; int s = totalSeconds % 100;
StringBuilder sb = new StringBuilder();
if (d > 0) sb.append(d).appe... | }
public static void main(String[] args) {
// 100 seconds = 1 minute in this system (not 1 min 40 sec)
assert formatDuration(100).equals("1m") : formatDuration(100);
assert !formatDuration(100).equals("1m 40s") : "must not use standard 60s minutes";
// 10000 seconds = 1 hour (10... | assert formatDuration(0).equals("0s") : "zero";
assert formatDuration(1).equals("1s") : "one second";
assert formatDuration(99).equals("99s") : "99 seconds";
assert formatDuration(100).equals("1m") : "one custom minute";
assert formatDuration(101).equals("1m 1s") : "one minute one second";
assert formatDuration(200).eq... | pattern_matching |
41 | devbench-pattern-matching | java | import java.util.Set;
public class PMTask41 {
private static final Set<Character> VOWELS = Set.of('a','e','i','o','u');
private static boolean sameClass(char a, char b) {
return VOWELS.contains(a) == VOWELS.contains(b);
}
// Edit distance: sub cost = 1 if same class, 3 if cross-class.
// I... | for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (s.charAt(i-1) == t.charAt(j-1)) {
dp[i][j] = dp[i-1][j-1];
} else {
int rc = sameClass(s.charAt(i-1), t.charAt(j-1)) ? 1 : 3;
dp[i][j] = Math.... | }
public static void main(String[] args) {
assert editDistance("cat", "cet") == 1 : "v->v cost 1";
assert editDistance("cat", "cbt") == 2 : "cross-class: ins+del cheaper";
assert editDistance("abc", "axc") == 1 : "c->c cost 1";
System.out.println("OK");
}
}
| assert editDistance("", "") == 0 : "empty";
assert editDistance("a", "") == 1 : "del";
assert editDistance("", "b") == 1 : "ins";
assert editDistance("abc", "abc") == 0 : "same";
assert editDistance("aaa", "eee") == 3 : "3 vowel subs";
assert editDistance("bbb", "aaa") == 6 : "3 cross-class: each ins+del=2";
| pattern_matching |
42 | devbench-pattern-matching | java | public class PMTask42 {
// Custom version comparator for a release channel system:
// 1. Even major versions (stable) sort BEFORE odd major (beta)
// 2. Within same parity group: higher major first (descending)
// 3. Same major: minor ascending, then patch ascending
// Returns negative if a < b, 0 i... | String[] pa = a.split("\\.");
String[] pb = b.split("\\.");
int ma = Integer.parseInt(pa[0]), mb = Integer.parseInt(pb[0]);
int parA = ma % 2, parB = mb % 2;
if (parA != parB) return parA - parB;
if (ma != mb) return mb - ma;
int mia = Integer.parseInt(pa[1]), mib... | }
public static void main(String[] args) {
assert compareVersion("2.0.0", "3.0.0") < 0 : "stable before beta";
assert compareVersion("4.0.0", "2.0.0") < 0 : "4.x before 2.x";
assert compareVersion("2.1.0", "2.3.0") < 0 : "minor asc";
assert compareVersion("4.0.0", "3.0.0") < 0 :... | assert compareVersion("2.0.0", "2.0.0") == 0 : "equal";
assert compareVersion("1.0.0", "3.0.0") > 0 : "odd: 3 before 1";
assert compareVersion("6.0.0", "4.0.0") < 0 : "even: 6 before 4";
assert compareVersion("2.0.1", "2.0.5") < 0 : "patch asc";
assert compareVersion("0.0.0", "1.0.0") < 0 : "0 even before 1 odd";
| pattern_matching |
43 | devbench-pattern-matching | java | import java.util.List;
import java.util.ArrayList;
public class PMTask43 {
private static List<int[]> getRuns(String s) {
List<int[]> runs = new ArrayList<>();
if (s.isEmpty()) return runs;
char prev = s.charAt(0); int cnt = 1;
for (int i = 1; i < s.length(); i++) {
if (... | while (i < runs.size()) {
int j = i;
while (j < runs.size() && runs.get(j)[1] == runs.get(i)[1]) j++;
boolean grp = (j - i > 1) && runs.get(i)[1] > 1;
if (grp) sb.append('(');
for (int k = i; k < j; k++) sb.append(fmtRun(runs.get(k)));
if (... | }
public static void main(String[] args) {
assert rleEncode("abc").equals("abc") : "singles";
assert rleEncode("aabbc").equals("(ax2bx2)c") : "grouped";
assert rleEncode("aaabbbcc").equals("(ax3bx3)cx2") : "mixed";
assert !rleEncode("aabbc").equals("2a2b1c") : "not std";
... | assert rleEncode("").equals("") : "empty";
assert rleEncode("a").equals("a") : "single";
assert rleEncode("aa").equals("ax2") : "pair";
assert rleEncode("aabb").equals("(ax2bx2)") : "two pairs";
assert rleEncode("aaabb").equals("ax3bx2") : "diff len";
assert rleEncode("aabbcc").equals("(ax2bx2cx2)") : "three same";
| pattern_matching |
44 | devbench-pattern-matching | java | public class PMTask44 {
// Additive-only Roman numerals (NO subtractive pairs like IV, IX, XL).
// 4=IIII, 9=VIIII, 40=XXXX, 90=LXXXX, 400=CCCC, 900=DCCCC
private static final int[] VALS = {1000, 500, 100, 50, 10, 5, 1};
private static final String[] SYMS = {"M","D","C","L","X","V","I"};
public ... | StringBuilder sb = new StringBuilder();
for (int i = 0; i < VALS.length; i++) {
while (num >= VALS[i]) {
sb.append(SYMS[i]);
num -= VALS[i];
}
}
return sb.toString();
| }
public static void main(String[] args) {
assert toRoman(4).equals("IIII") : "4 = IIII not IV";
assert !toRoman(4).equals("IV") : "no subtractive";
assert toRoman(9).equals("VIIII") : "9 = VIIII not IX";
assert !toRoman(9).equals("IX") : "no IX";
assert toRoman(3).equal... | assert toRoman(1).equals("I") : "1";
assert toRoman(5).equals("V") : "5";
assert toRoman(10).equals("X") : "10";
assert toRoman(14).equals("XIIII") : "14";
assert toRoman(90).equals("LXXXX") : "90";
assert toRoman(400).equals("CCCC") : "400";
assert toRoman(900).equals("DCCCC") : "900";
assert toRoman(1994).equals("MDC... | pattern_matching |
45 | devbench-pattern-matching | java | import java.util.ArrayDeque;
public class PMTask45 {
private static final String OPENS = "([{";
private static final String CLOSES = ")]}";
// Validate brackets, IGNORING brackets inside double-quoted strings.
// Escaped quotes (\") do NOT end the string.
public static boolean validateBrackets(Str... | if (inStr) {
if (c == '\\' && i + 1 < input.length()) { i++; continue; }
if (c == '"') inStr = false;
continue;
}
if (c == '"') { inStr = true; continue; }
int oi = OPENS.indexOf(c), ci = CLOSES.indexOf(c);
if (o... | }
return stk.isEmpty() && !inStr;
}
public static void main(String[] args) {
assert validateBrackets("()") : "simple";
assert validateBrackets("([{}])") : "nested";
assert !validateBrackets("(]") : "mismatch";
assert validateBrackets("(\"[}\")" ) : "brackets in s... | assert validateBrackets("") : "empty";
assert validateBrackets("no brackets") : "none";
assert validateBrackets("{\"(\"}") : "bracket in str";
assert !validateBrackets("}") : "extra close";
assert validateBrackets("[\"]\"]") : "close in str";
| pattern_matching |
46 | devbench-pattern-matching | java | import java.util.LinkedHashMap;
import java.util.Map;
import java.util.ArrayList;
public class PMTask46 {
private static String stripComment(String line) {
StringBuilder cl = new StringBuilder();
boolean q = false;
for (int i = 0; i < line.length(); i++) { char c = line.charAt(i); if (c=='"... | for (String line : lines) {
String s = stripComment(line);
if (s.isEmpty() || !s.contains("=")) continue;
int eq = s.indexOf('=');
String k = s.substring(0, eq).trim();
String v = unquote(s.substring(eq + 1).trim());
result.put(k, v);
... | }
public static void main(String[] args) {
String cfg = "name = Alice\n# comment\ngreeting = \"Hello # World\"\npath = /usr/\\\nlocal/bin";
Map<String, String> m = parseConfig(cfg);
assert m.get("name").equals("Alice") : "basic";
assert !m.containsKey("comment") : "comment skipp... | assert parseConfig("").isEmpty() : "empty";
assert parseConfig("# only").isEmpty() : "comment only";
assert parseConfig("x = 1").get("x").equals("1") : "simple";
assert parseConfig("x = a # note").get("x").equals("a") : "inline comment";
assert parseConfig("x = \"a # b\"").get("x").equals("a # b") : "# in quotes";
| pattern_matching |
47 | devbench-pattern-matching | java | import java.util.Map;
public class PMTask47 {
// Template: {{key}} replaced from map. \\{{ is literal '{'.
// Unknown keys left as {{key}}. Unmatched {{ left as-is.
public static String render(String tpl, Map<String, String> vars) {
StringBuilder sb = new StringBuilder();
int i = 0;
... | if (i+1 < tpl.length() && tpl.charAt(i) == '\\' && tpl.charAt(i+1) == '{') {
sb.append('{'); i += 2;
} else if (i+1 < tpl.length() && tpl.charAt(i) == '{' && tpl.charAt(i+1) == '{') {
int end = tpl.indexOf("}}", i+2);
if (end < 0) { sb.append("{{")... | }
return sb.toString();
}
public static void main(String[] args) {
var v = Map.of("name", "Alice", "age", "30");
assert render("Hello {{name}}!", v).equals("Hello Alice!") : "basic";
assert render("\\{{name}}", v).equals("{{name}}") : "escaped";
assert render("{{... | assert render("", Map.of()).equals("") : "empty";
assert render("no vars", Map.of()).equals("no vars") : "no sub";
assert render("{{a}}{{b}}", Map.of("a","1","b","2")).equals("12") : "adjacent";
assert render("\\{{x}}={{x}}", Map.of("x","y")).equals("{{x}}=y") : "mixed";
assert render("{{", Map.of()).equals("{{") : "op... | pattern_matching |
48 | devbench-pattern-matching | java | import java.util.List;
import java.util.ArrayList;
public class PMTask48 {
// + and - bind TIGHTER than * and / (reversed precedence).
// So 2*3+4*5 = 2*(3+4)*5 = 70
private static int evalAdd(String e) {
var v = new ArrayList<Integer>(); var o = new ArrayList<Character>(); int s = 0;
for ... | for (int i = 0; i <= expr.length(); i++) {
if (i == expr.length() || expr.charAt(i) == '*' || expr.charAt(i) == '/') {
vals.add(evalAdd(expr.substring(s, i)));
if (i < expr.length()) ops.add(expr.charAt(i));
s = i + 1;
}
}
i... | }
public static void main(String[] args) {
assert evalExpr("2*3+4") == 14 : "reversed prec";
assert evalExpr("2*3+4*5") == 70 : "multi";
assert evalExpr("10+5-3") == 12 : "add only";
assert evalExpr("3*4") == 12 : "mul only";
System.out.println("OK");
}
}
| assert evalExpr("5") == 5 : "single";
assert evalExpr("1+2") == 3 : "add";
assert evalExpr("10/2+3") == 2 : "10/(2+3)=2";
assert evalExpr("1+1*1+1") == 4 : "2*2=4";
assert evalExpr("100/10+10") == 5 : "100/20=5";
| pattern_matching |
49 | devbench-pattern-matching | java | public class PMTask49 {
// Format a date as "business date": DD/YYYY/MM
// All fields zero-padded: DD=2, YYYY=4, MM=2
// Month must be 1-12, day must be 1-31, year must be > 0.
// Returns null for invalid dates.
public static String formatDate(int year, int month, int day) {
| if (year <= 0 || month < 1 || month > 12 || day < 1 || day > 31)
return null;
return String.format("%02d/%04d/%02d", day, year, month);
| }
public static int[] parseDate(String s) {
String[] p = s.split("/");
return new int[]{Integer.parseInt(p[1]), Integer.parseInt(p[2]), Integer.parseInt(p[0])};
}
public static void main(String[] args) {
assert formatDate(2024, 3, 15).equals("15/2024/03") : "DD/YYYY/MM";
... | assert formatDate(2000, 1, 1).equals("01/2000/01") : "new year";
assert formatDate(1999, 12, 31).equals("31/1999/12") : "end of year";
assert formatDate(2024, 11, 5).equals("05/2024/11") : "election day";
assert formatDate(-1, 1, 1) == null : "negative year";
assert formatDate(2024, 0, 1) == null : "zero month";
int[] ... | pattern_matching |
50 | devbench-pattern-matching | java | public class PMTask50 {
// European-Indian number format:
// - Decimal separator: comma (','), grouping separator: dot ('.')
// - Groups of 2 digits from right (Indian style)
// "1234567.89" -> "1.23.45.67,89"; "1000" -> "10.00"
public static String formatNumber(String num) {
String[] parts ... | StringBuilder sb = new StringBuilder();
int pos = intPart.length();
while (pos > 0) {
int start = Math.max(0, pos - 2);
if (sb.length() > 0) sb.insert(0, '.');
sb.insert(0, intPart.substring(start, pos));
pos = start;
}
if (decPart ... | }
public static void main(String[] args) {
assert formatNumber("1234567.89").equals("1.23.45.67,89") : "full";
assert formatNumber("1000").equals("10.00") : "no dec";
assert formatNumber("100").equals("1.00") : "three digits";
assert formatNumber("42.5").equals("42,5") : "short"... | assert formatNumber("1").equals("1") : "single";
assert formatNumber("12").equals("12") : "two";
assert formatNumber("123").equals("1.23") : "three";
assert formatNumber("1234").equals("12.34") : "four";
assert formatNumber("12345").equals("1.23.45") : "five";
assert formatNumber("0.99").equals("0,99") : "zero dec";
| pattern_matching |
1 | devbench-syntax-completion | java | import java.util.*;
public class SCTask1 {
sealed interface Expr permits Num, Add, Neg {}
record Num(int value) implements Expr {}
record Add(Expr left, Expr right) implements Expr {}
record Neg(Expr inner) implements Expr {}
public static int eval(Expr e) {
return switch (e) {
| case Num(var v) -> v;
case Add(var l, var r) -> eval(l) + eval(r);
case Neg(var inner) -> -eval(inner);
| };
}
public static void main(String[] args) {
Expr expr = new Add(new Num(3), new Neg(new Num(1)));
int result = eval(expr);
System.out.println(result);
}
}
| assert eval(new Num(5)) == 5 : "Num failed";
assert eval(new Neg(new Num(3))) == -3 : "Neg failed";
assert eval(new Add(new Num(10), new Num(20))) == 30 : "Add failed";
assert eval(new Add(new Num(3), new Neg(new Num(1)))) == 2 : "Nested failed";
assert eval(new Neg(new Add(new Num(4), new Num(6)))) == -10 : "Neg(Add) ... | syntax_completion |
2 | devbench-syntax-completion | java | import java.util.*;
public class SCTask2 {
sealed interface Vehicle permits Car, Truck, Motorcycle {}
record Car(int seats, boolean electric) implements Vehicle {}
record Truck(double tonnage) implements Vehicle {}
record Motorcycle(int cc) implements Vehicle {}
public static String classify(Vehic... | "eco-car-" + s;
case Car(var s, var e) ->
"car-" + s;
case Truck(var t) when t > 10 ->
"heavy-truck";
case Truck(var t) ->
"light-truck";
case Motorcycle(var cc) when cc > 600 ->
"sport-bike";... | };
}
public static void main(String[] args) {
System.out.println(classify(new Car(5, true)));
System.out.println(classify(new Car(4, true)));
System.out.println(classify(new Car(4, false)));
System.out.println(classify(new Truck(15)));
System.out.println(classify... | assert classify(new Car(5, true)).equals("eco-van-5") : "eco-van failed";
assert classify(new Car(4, true)).equals("eco-car-4") : "eco-car failed";
assert classify(new Car(4, false)).equals("car-4") : "gas car failed";
assert classify(new Car(2, false)).equals("car-2") : "small car failed";
assert classify(new Truck(15... | syntax_completion |
3 | devbench-syntax-completion | java | import java.util.*;
public class SCTask3 {
sealed interface Prim permits PInt, PStr, PBool {}
record PInt(int val) implements Prim {}
record PStr(String val) implements Prim {}
record PBool(boolean val) implements Prim {}
sealed interface Op permits Cmp, Concat {}
record Cmp(Prim left, Prim ri... | case PStr(var rv) -> lv + rv;
case PInt(var rv) -> lv + rv;
case PBool(var rv) -> lv + rv;
};
default -> "concat-error";
};
| };
}
public static void main(String[] args) {
System.out.println(execute(new Cmp(new PInt(3), new PInt(5))));
System.out.println(execute(new Concat(new PStr("hello"), new PStr("world"))));
}
}
| assert execute(new Cmp(new PInt(3), new PInt(5))).equals("lt") : "int lt failed";
assert execute(new Cmp(new PInt(5), new PInt(5))).equals("eq") : "int eq failed";
assert execute(new Cmp(new PInt(7), new PInt(3))).equals("gt") : "int gt failed";
assert execute(new Cmp(new PInt(1), new PStr("a"))).equals("type-mismatch"... | syntax_completion |
4 | devbench-syntax-completion | java | import java.util.*;
import java.util.stream.*;
public class SCTask4 {
record Student(String name, String grade, int score) {}
public static Map<String, String> topPerGrade(List<Student> students) {
return students.stream()
.collect(Collectors.groupingBy(
Student::grade,
... | Student::score)),
opt -> opt.map(s -> s.name() + ":" + s.score())
.orElse("none")
)
| ));
}
public static void main(String[] args) {
var students = List.of(
new Student("Alice", "A", 95),
new Student("Bob", "B", 80),
new Student("Carol", "A", 90),
new Student("Dave", "B", 85),
new Student("Eve", "A", 88)
);
... | var students = List.of(
new Student("Alice", "A", 95),
new Student("Bob", "B", 80),
new Student("Carol", "A", 90),
new Student("Dave", "B", 85),
new Student("Eve", "A", 88)
);
var top = topPerGrade(students);
assert top.size() == 2 : "Expected 2 grades: " + top;
assert top.get("A").equals("Alice:95"... | syntax_completion |
5 | devbench-syntax-completion | java | import java.util.*;
import java.util.stream.*;
public class SCTask5 {
record Product(String name, String category, double price) {}
public static Map.Entry<Double, Double> priceRange(List<Product> products) {
return products.stream()
.filter(p -> p.price() > 0)
.collect(Collect... | Collectors.minBy(Comparator.comparingDouble(Product::price)),
Collectors.maxBy(Comparator.comparingDouble(Product::price)),
(min, max) -> Map.entry(
min.map(Product::price).orElse(0.0),
max.map(Product::price).orElse(0.0)
... | ));
}
public static void main(String[] args) {
var products = List.of(
new Product("A", "tech", 29.99),
new Product("B", "tech", 99.99),
new Product("C", "food", 3.50),
new Product("D", "food", 12.00)
);
var range = priceRange(... | var products = List.of(
new Product("A", "tech", 29.99),
new Product("B", "tech", 99.99),
new Product("C", "food", 3.50),
new Product("D", "food", 12.00)
);
var range = priceRange(products);
assert Math.abs(range.getKey() - 3.50) < 0.01 : "min wrong: " + range.getKey();
assert Math.abs(range.getValue() ... | syntax_completion |
6 | devbench-syntax-completion | java | import java.util.*;
import java.util.stream.*;
public class SCTask6 {
record Order(String customer, List<Item> items) {}
record Item(String name, double price, int qty) {}
public static Map<String, Double> totalPerCustomer(List<Order> orders) {
return orders.stream()
.flatMap(o -> o.it... | i.price() * i.qty()))
)
.collect(Collectors.groupingBy(
Map.Entry::getKey,
Collectors.summingDouble(Map.Entry::getValue)
));
| }
public static void main(String[] args) {
var orders = List.of(
new Order("Alice", List.of(new Item("Book", 10.0, 2), new Item("Pen", 1.5, 3))),
new Order("Bob", List.of(new Item("Laptop", 999.0, 1))),
new Order("Alice", List.of(new Item("Notebook", 5.0, 4)))
... | var orders = List.of(
new Order("Alice", List.of(new Item("Book", 10.0, 2), new Item("Pen", 1.5, 3))),
new Order("Bob", List.of(new Item("Laptop", 999.0, 1))),
new Order("Alice", List.of(new Item("Notebook", 5.0, 4)))
);
var totals = totalPerCustomer(orders);
assert totals.size() == 2 : "Expected 2 customer... | syntax_completion |
7 | devbench-syntax-completion | java | import java.util.*;
import java.util.function.*;
public class SCTask7 {
public static <T extends Comparable<? super T>> List<T> mergeSorted(
List<? extends T> a, List<? extends T> b,
Comparator<? super T> fallback) {
List<T> result = new ArrayList<>();
int i = 0, j = 0;
... | ai.compareTo(bj);
if (cmp <= 0) {
result.add(ai);
i++;
} else {
result.add(bj);
j++;
}
}
while (i < a.size()) result.add(a.get(i++));
while (j < b.size()) result.add(b.get(j++));
... | }
public static void main(String[] args) {
var a = List.of(1, 3, 5, 7);
var b = List.of(2, 4, 6, 8);
var merged = mergeSorted(a, b, null);
System.out.println(merged);
var sa = List.of("banana", "cherry");
var sb = List.of("apple", "date");
var smerged = ... | var merged = mergeSorted(List.of(1, 3, 5), List.of(2, 4, 6), null);
assert merged.equals(List.of(1, 2, 3, 4, 5, 6)) : "int merge failed: " + merged;
var merged2 = mergeSorted(List.of(10), List.of(), null);
assert merged2.equals(List.of(10)) : "single elem failed: " + merged2;
var merged3 = mergeSorted(List.of(), List.o... | syntax_completion |
8 | devbench-syntax-completion | java | import java.util.*;
import java.util.function.*;
public class SCTask8 {
static abstract class Builder<T, B extends Builder<T, B>> {
protected final List<UnaryOperator<T>> transforms = new ArrayList<>();
@SuppressWarnings("unchecked")
protected B self() { return (B) this; }
public... | p + s);
}
public StringPipeline replace(String target, String replacement) {
return addTransform(s -> s.replace(target, replacement));
}
public StringPipeline suffix(String sfx) {
return addTransform(s -> s + sfx);
}
| }
static class IntPipeline extends Builder<Integer, IntPipeline> {
public IntPipeline add(int n) { return addTransform(x -> x + n); }
public IntPipeline mul(int n) { return addTransform(x -> x * n); }
public IntPipeline clamp(int lo, int hi) {
return addTransform(x -> Math.m... | String s1 = new StringPipeline().trim().upper().prefix(">>").replace("HELLO", "HI").suffix("<<").applyAll(" hello world ");
assert s1.equals(">>HI WORLD<<") : "string pipeline failed: " + s1;
String s2 = new StringPipeline().trim().applyAll(" abc ");
assert s2.equals("abc") : "trim only failed: " + s2;
String s3 = ... | syntax_completion |
9 | devbench-syntax-completion | java | import java.util.*;
public class SCTask9 {
static List<String> log = new ArrayList<>();
static class Resource implements AutoCloseable {
final String name;
boolean open;
Resource(String name) { this.name = name; this.open = true; log.add("open:" + name); }
public String read() ... | var r2 = new Resource("B");
var r3 = new Resource("C")) {
return r1.read() + "," + r2.read() + "," + r3.read();
} catch (Exception e) {
return "error:" + e.getMessage();
}
| }
public static void main(String[] args) {
log.clear();
String result = process();
System.out.println(result);
System.out.println(log);
}
}
| log.clear();
String result = process();
assert result.equals("data-A,data-B,data-C") : "result wrong: " + result;
assert log.size() == 6 : "expected 6 log entries: " + log;
assert log.get(0).equals("open:A") : "first open wrong";
assert log.get(1).equals("open:B") : "second open wrong";
assert log.get(2).equals("open:C... | syntax_completion |
10 | devbench-syntax-completion | java | import java.util.*;
public class SCTask10 {
static class FlakyResource implements AutoCloseable {
final String name;
final boolean failOnClose;
FlakyResource(String name, boolean failOnClose) {
this.name = name;
this.failOnClose = failOnClose;
}
publi... | info.put("status", "ok");
} catch (Exception e) {
info.put("status", "error");
info.put("message", e.getMessage());
Throwable[] suppressed = e.getSuppressed();
if (suppressed.length > 0) {
List<String> msgs = new ArrayList<>();
... | }
public static void main(String[] args) {
System.out.println(runWithResources(false, false, false));
System.out.println(runWithResources(true, false, false));
System.out.println(runWithResources(true, true, true));
}
}
| var ok = runWithResources(false, false, false);
assert ok.get("status").equals("ok") : "ok case failed: " + ok;
assert !ok.containsKey("message") : "ok should have no message";
var bodyFail = runWithResources(true, false, false);
assert bodyFail.get("status").equals("error") : "body fail status wrong";
assert bodyFail.... | syntax_completion |
11 | devbench-syntax-completion | java | public class SCTask11 {
sealed interface Vehicle permits Car, Truck, Motorcycle {}
record Car(int seats) implements Vehicle {}
record Truck(double tons) implements Vehicle {}
record Motorcycle(boolean hasSidecar) implements Vehicle {}
public static String describe(Vehicle v) {
return switch... | case Car(var s) when s > 4 -> "large car with " + s + " seats";
case Car(var s) -> "car with " + s + " seats";
case Truck(var t) when t > 5.0 -> "heavy truck";
case Truck(var t) -> "light truck";
case Motorcycle(var sc) when sc -> "motorcycle with sidecar";
... |
public static void main(String[] args) {
String r1 = describe(new Car(2));
String r2 = describe(new Car(6));
String r3 = describe(new Truck(3.0));
String r4 = describe(new Truck(10.0));
String r5 = describe(new Motorcycle(true));
String r6 = describe(new Motorcycle(f... | assert SCTask11.describe(new SCTask11.Car(2)).equals("car with 2 seats") : "car2";
assert SCTask11.describe(new SCTask11.Car(6)).equals("large car with 6 seats") : "car6";
assert SCTask11.describe(new SCTask11.Truck(3.0)).equals("light truck") : "truck3";
assert SCTask11.describe(new SCTask11.Truck(10.0)).equals("heavy... | syntax_completion |
12 | devbench-syntax-completion | java | import java.util.*;
public class SCTask12 {
public static int scoreBand(int score) {
return switch (score / 10) {
case 10, 9 -> 4;
case 8 -> 3;
case 7 -> {
if (score >= 75) yield 3;
else yield 2;
}
case 6 -> {
| if (score >= 65) yield 2;
else yield 1;
}
default -> {
if (score < 0) throw new IllegalArgumentException("negative");
yield 0;
}
};
}
|
public static void main(String[] args) {
System.out.println(scoreBand(95) + "," + scoreBand(80) + "," + scoreBand(76));
}
}
| assert SCTask12.scoreBand(100) == 4 : "100";
assert SCTask12.scoreBand(95) == 4 : "95";
assert SCTask12.scoreBand(80) == 3 : "80";
assert SCTask12.scoreBand(76) == 3 : "76";
assert SCTask12.scoreBand(72) == 2 : "72";
assert SCTask12.scoreBand(65) == 2 : "65";
assert SCTask12.scoreBand(61) == 1 : "61";
assert SCTask12.s... | syntax_completion |
13 | devbench-syntax-completion | java | import java.util.*;
import java.util.stream.*;
public class SCTask13 {
public static String summarize(List<Integer> nums) {
return nums.stream().collect(Collectors.teeing(
| Collectors.summingInt(Integer::intValue),
Collectors.counting(),
(sum, count) -> "sum=" + sum + ",count=" + count
));
}
|
public static void main(String[] args) {
System.out.println(summarize(List.of(1, 2, 3, 4, 5)));
}
}
| assert SCTask13.summarize(List.of(1, 2, 3, 4, 5)).equals("sum=15,count=5") : "basic";
assert SCTask13.summarize(List.of(10)).equals("sum=10,count=1") : "single";
assert SCTask13.summarize(List.of()).equals("sum=0,count=0") : "empty";
assert SCTask13.summarize(List.of(-3, 3)).equals("sum=0,count=2") : "zero_sum";
| syntax_completion |
14 | devbench-syntax-completion | java | import java.util.*;
import java.util.stream.*;
public class SCTask14 {
record TaggedItem(String item, List<String> tags) {}
public static Map<String, List<String>> tagIndex(List<TaggedItem> items) {
return items.stream()
.flatMap(ti -> ti.tags().stream().map(tag -> Map.entry(tag, ti.item()... | Map.Entry::getKey,
Collectors.collectingAndThen(
Collectors.mapping(Map.Entry::getValue, Collectors.toList()),
lst -> { Collections.sort(lst); return lst; }
)
));
}
|
public static void main(String[] args) {
var items = List.of(
new TaggedItem("banana", List.of("fruit", "yellow")),
new TaggedItem("apple", List.of("fruit", "red")),
new TaggedItem("carrot", List.of("vegetable", "orange"))
);
var idx = tagIndex(items);
... | var items = List.of(
new SCTask14.TaggedItem("banana", List.of("fruit", "yellow")),
new SCTask14.TaggedItem("apple", List.of("fruit", "red")),
new SCTask14.TaggedItem("carrot", List.of("vegetable", "orange"))
);
var idx = SCTask14.tagIndex(items);
assert idx.get("fruit").equals(List.of("apple", "banana")) :... | syntax_completion |
15 | devbench-syntax-completion | java | import java.util.*;
import java.util.stream.*;
public class SCTask15 {
record Employee(String name, String dept, int salary) {}
public static Map<String, String> topEarnerPerDept(List<Employee> emps) {
return emps.stream().collect(Collectors.groupingBy(
Employee::dept,
Collecto... | opt -> opt.map(Employee::name).orElse("none")
)
));
}
|
public static void main(String[] args) {
var emps = List.of(
new Employee("Alice", "eng", 120),
new Employee("Bob", "eng", 150),
new Employee("Carol", "sales", 110),
new Employee("Dave", "sales", 130)
);
System.out.println(topEarnerPerDept(emp... | var emps = List.of(
new SCTask15.Employee("Alice", "eng", 120),
new SCTask15.Employee("Bob", "eng", 150),
new SCTask15.Employee("Carol", "sales", 110),
new SCTask15.Employee("Dave", "sales", 130)
);
var result = SCTask15.topEarnerPerDept(emps);
assert result.get("eng").equals("Bob") : "eng=" + result.ge... | syntax_completion |
16 | devbench-syntax-completion | java | import java.util.*;
public class SCTask16 {
record Range(int lo, int hi) {
Range {
| if (lo > hi) throw new IllegalArgumentException("lo > hi: " + lo + " > " + hi);
if (lo < 0) { lo = 0; }
if (hi > 100) { hi = 100; }
}
int span() { return hi - lo; }
boolean contains(int v) { return v >= lo && v <= hi; }
}
|
public static void main(String[] args) {
Range r1 = new Range(10, 20);
Range r2 = new Range(-5, 200);
System.out.println(r1.span() + "," + r2.lo() + "," + r2.hi());
}
}
| var r1 = new SCTask16.Range(10, 20);
assert r1.lo() == 10 && r1.hi() == 20 : "r1";
assert r1.span() == 10 : "span1";
assert r1.contains(15) : "contains15";
assert !r1.contains(5) : "not5";
var r2 = new SCTask16.Range(-5, 200);
assert r2.lo() == 0 : "clamped_lo=" + r2.lo();
assert r2.hi() == 100 : "clamped_hi=" + r2.hi... | syntax_completion |
17 | devbench-syntax-completion | java | public class SCTask17 {
sealed interface Expr permits Num, Add, Mul, Neg {}
record Num(double val) implements Expr {}
record Add(Expr left, Expr right) implements Expr {}
record Mul(Expr left, Expr right) implements Expr {}
record Neg(Expr inner) implements Expr {}
public static double eval(Exp... | -eval(inner);
};
}
public static String prettyPrint(Expr e) {
return switch (e) {
case Num(var v) -> String.valueOf(v);
case Add(var l, var r) -> "(" + prettyPrint(l) + "+" + prettyPrint(r) + ")";
case Mul(var l, var r) -> "(" + prettyPrint(l)... |
public static void main(String[] args) {
Expr e = new Add(new Mul(new Num(2), new Num(3)), new Neg(new Num(1)));
System.out.println(eval(e) + " -> " + prettyPrint(e));
}
}
| var e1 = new SCTask17.Add(new SCTask17.Mul(new SCTask17.Num(2), new SCTask17.Num(3)), new SCTask17.Neg(new SCTask17.Num(1)));
assert SCTask17.eval(e1) == 5.0 : "eval1=" + SCTask17.eval(e1);
assert SCTask17.prettyPrint(e1).equals("((2.0*3.0)+(-1.0))") : "pp1=" + SCTask17.prettyPrint(e1);
var e2 = new SCTask17.Neg(new S... | syntax_completion |
18 | devbench-syntax-completion | java | import java.util.*;
import java.util.stream.*;
public class SCTask18 {
record Student(String name, int grade, double gpa) {}
public static List<String> rank(List<Student> students) {
return students.stream()
.sorted(
| Comparator.comparingInt(Student::grade)
.thenComparing(Comparator.comparingDouble(Student::gpa).reversed())
.thenComparing(Student::name)
)
.map(Student::name)
.collect(Collectors.toList());
}
|
public static void main(String[] args) {
var students = List.of(
new Student("Zara", 10, 3.8),
new Student("Amy", 10, 3.9),
new Student("Bob", 10, 3.8),
new Student("Cal", 11, 3.5)
);
System.out.println(rank(students));
}
}
| var students = List.of(
new SCTask18.Student("Zara", 10, 3.8),
new SCTask18.Student("Amy", 10, 3.9),
new SCTask18.Student("Bob", 10, 3.8),
new SCTask18.Student("Cal", 11, 3.5)
);
var ranked = SCTask18.rank(students);
assert ranked.equals(List.of("Amy", "Bob", "Zara", "Cal")) : "ranked=" + ranked;
var s... | syntax_completion |
19 | devbench-syntax-completion | java | import java.util.function.*;
public class SCTask19 {
public static Function<String, String> buildPipeline() {
Function<String, String> trim = String::trim;
Function<String, String> upper = String::toUpperCase;
Function<String, String> addBrackets = s -> "[" + s + "]";
Function<Strin... | replaceSpaces
)
.andThen(addBrackets);
}
public static Function<Integer, String> numberPipeline() {
Function<Integer, Double> half = n -> n / 2.0;
Function<Double, String> fmt = d -> String.format("%.1f", d);
return half.andThen(fmt);
}
|
public static void main(String[] args) {
var pipe = buildPipeline();
System.out.println(pipe.apply(" hello world "));
System.out.println(numberPipeline().apply(7));
}
}
| assert SCTask19.buildPipeline().apply(" hello world ").equals("[HELLO_WORLD]") : "pipe1";
assert SCTask19.buildPipeline().apply("abc").equals("[ABC]") : "pipe2";
assert SCTask19.buildPipeline().apply(" a b c ").equals("[A_B_C]") : "pipe3";
assert SCTask19.numberPipeline().apply(7).equals("3.5") : "num7";
assert SCT... | syntax_completion |
20 | devbench-syntax-completion | java | import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class SCTask20 {
public static <T, U, R> List<R> zipWith(
List<T> a, List<U> b,
BiFunction<? super T, ? super U, ? extends R> combiner) {
return IntStream.range(0, Math.min(a.size(), b.size()))
.m... | combiner.apply(a.get(i), b.get(i))
)
.collect(Collectors.toList());
}
public static <T> List<T> interleave(List<T> a, List<T> b) {
return IntStream.range(0, Math.min(a.size(), b.size()))
.boxed()
.flatMap(i -> Stream.of(a.get(i), b.get(i))... |
public static void main(String[] args) {
var sums = zipWith(List.of(1, 2, 3), List.of(10, 20, 30), Integer::sum);
System.out.println(sums);
var inter = interleave(List.of("a", "b", "c"), List.of("x", "y", "z"));
System.out.println(inter);
}
}
| var sums = SCTask20.zipWith(List.of(1, 2, 3), List.of(10, 20, 30), Integer::sum);
assert sums.equals(List.of(11, 22, 33)) : "sums=" + sums;
var concat = SCTask20.zipWith(List.of("a", "b"), List.of("x", "y"), (s1, s2) -> s1 + s2);
assert concat.equals(List.of("ax", "by")) : "concat=" + concat;
var shorter = SCTask20.z... | syntax_completion |
21 | devbench-syntax-completion | java | import java.util.*;
public class SCTask21 {
static List<String> log = new ArrayList<>();
static class Resource implements AutoCloseable {
final String name;
Resource(String name) { this.name = name; log.add("open:" + name); }
public void close() { log.add("close:" + name); }
}
... | }
log.add("after-inner");
}
return new ArrayList<>(log);
}
|
public static void main(String[] args) {
List<String> result = operate();
System.out.println(result);
}
}
| assert operate().equals(java.util.List.of("open:A","open:B","open:C","use:ABC","close:C","after-inner","close:B","close:A")) : "Wrong log: " + operate();
| syntax_completion |
22 | devbench-syntax-completion | java | import java.util.*;
public class SCTask22 {
static class FailClose implements AutoCloseable {
final String name;
final boolean failOnClose;
FailClose(String name, boolean failOnClose) {
this.name = name;
this.failOnClose = failOnClose;
}
public void c... | }
} catch (Exception e) {
Throwable[] suppressed = e.getSuppressed();
return e.getMessage() + ";" + suppressed.length + ";"
+ suppressed[0].getMessage() + ";" + suppressed[1].getMessage();
}
}
|
public static void main(String[] args) {
System.out.println(testSuppressed());
}
}
| String r = testSuppressed();
assert r.equals("body-fail;2;close-fail:B;close-fail:A") : "Wrong: " + r;
| syntax_completion |
23 | devbench-syntax-completion | java | import java.util.*;
import java.util.stream.*;
public class SCTask23 {
static class LineSource implements AutoCloseable {
final String id;
final List<String> lines;
boolean closed = false;
LineSource(String id, String... lines) { this.id = id; this.lines = List.of(lines); }
... | .filter(line -> !line.endsWith(":skip"))
.collect(Collectors.toList()).stream();
}
})
.sorted()
.collect(Collectors.toList());
}
|
public static void main(String[] args) {
List<LineSource> sources = List.of(
new LineSource("X", "hello", "skip", "world"),
new LineSource("Y", "alpha", "skip", "beta")
);
List<String> result = mergeAndClose(sources);
System.out.println(result);
Syste... | List<LineSource> sources = List.of(
new LineSource("X", "hello", "skip", "world"),
new LineSource("Y", "alpha", "skip", "beta")
);
List<String> result = mergeAndClose(sources);
assert result.equals(List.of("X:hello","X:world","Y:alpha","Y:beta")) : "Wrong: " + result;
assert sources.get(0).closed : "X not close... | syntax_completion |
24 | devbench-syntax-completion | java | import java.util.*;
import java.util.stream.*;
public class SCTask24 {
public static Map<String, Integer> mergeMaps(List<Map<String, Integer>> maps) {
return maps.stream()
.reduce(new HashMap<>(), (merged, current) -> {
current.forEach((k, v) ->
merged.merge(... | );
return merged;
}, (m1, m2) -> {
m2.forEach((k, v) -> m1.merge(k, v, Integer::sum));
return m1;
});
}
|
public static void main(String[] args) {
var result = mergeMaps(List.of(
Map.of("a", 1, "b", 2),
Map.of("b", 3, "c", 4),
Map.of("a", 5, "c", 1)
));
System.out.println(result);
}
}
| var result = mergeMaps(List.of(
Map.of("a", 1, "b", 2),
Map.of("b", 3, "c", 4),
Map.of("a", 5, "c", 1)
));
assert result.get("a") == 6 : "a=" + result.get("a");
assert result.get("b") == 5 : "b=" + result.get("b");
assert result.get("c") == 5 : "c=" + result.get("c");
| syntax_completion |
25 | devbench-syntax-completion | java | import java.util.*;
import java.util.stream.*;
public class SCTask25 {
record Student(String name, String grade, int score) {}
public static Map<String, String> topStudentPerGrade(List<Student> students) {
return students.stream()
.collect(Collectors.groupingBy(
Student::gr... | ).orElse("none")
)
));
}
|
public static void main(String[] args) {
var result = topStudentPerGrade(List.of(
new Student("Alice", "A", 95),
new Student("Bob", "A", 88),
new Student("Carol", "B", 92),
new Student("Dave", "B", 97)
));
System.out.println(result);
}
}
| var result = topStudentPerGrade(List.of(
new Student("Alice", "A", 95),
new Student("Bob", "A", 88),
new Student("Carol", "B", 92),
new Student("Dave", "B", 97)
));
assert result.get("A").equals("Alice:95") : "A=" + result.get("A");
assert result.get("B").equals("Dave:97") : "B=" + result.get("B");
| syntax_completion |
26 | devbench-syntax-completion | java | import java.util.*;
import java.util.stream.*;
public class SCTask26 {
record Stats(double mean, double median, int count) {}
public static Stats computeStats(List<Integer> nums) {
return nums.stream()
.collect(Collectors.teeing(
Collectors.teeing(
Colle... | ) / 2.0;
}
),
(mean, median) -> new Stats(mean, median, nums.size())
));
}
|
public static void main(String[] args) {
Stats s1 = computeStats(List.of(1, 2, 3, 4, 5));
System.out.println(s1);
Stats s2 = computeStats(List.of(10, 20, 30, 40));
System.out.println(s2);
}
}
| Stats s1 = computeStats(List.of(1, 2, 3, 4, 5));
assert s1.mean() == 3.0 : "mean1=" + s1.mean();
assert s1.median() == 3.0 : "median1=" + s1.median();
assert s1.count() == 5 : "count1=" + s1.count();
Stats s2 = computeStats(List.of(10, 20, 30, 40));
assert s2.mean() == 25.0 : "mean2=" + s2.mean();
assert s2.median() ==... | syntax_completion |
27 | devbench-syntax-completion | java | import java.util.*;
public class SCTask27 {
public static <T extends Comparable<? super T>> List<T> clampedSort(
List<T> items, T lower, T upper) {
return items.stream()
.filter(x -> x.compareTo(lower) >= 0 && x.compareTo(upper
| ) <= 0)
.sorted()
.collect(java.util.stream.Collectors.toList());
}
|
public static void main(String[] args) {
var result = clampedSort(List.of(5, 1, 8, 3, 10, 2), 2, 8);
System.out.println(result);
}
}
| var r1 = clampedSort(List.of(5, 1, 8, 3, 10, 2), 2, 8);
assert r1.equals(List.of(2, 3, 5, 8)) : "r1=" + r1;
var r2 = clampedSort(List.of("dog","ant","cat","eel","bat"), "bat", "dog");
assert r2.equals(List.of("bat","cat","dog")) : "r2=" + r2;
| syntax_completion |
28 | devbench-syntax-completion | java | import java.util.*;
import java.util.function.*;
public class SCTask28 {
public static <T extends Comparable<? super T>> T findSecond(
List<? extends T> items, Predicate<? super T> filter) {
return items.stream()
.filter(filter)
.sorted(Comparator.<T>naturalOrder().rever... | )
.skip(1)
.findFirst()
.orElseThrow(() -> new NoSuchElementException(
"Need at least 2 matching elements"));
}
|
public static void main(String[] args) {
int second = findSecond(List.of(3, 7, 1, 9, 4, 6), x -> x > 2);
System.out.println("Second largest (>2): " + second);
}
}
| int r1 = findSecond(List.of(3, 7, 1, 9, 4, 6), x -> x > 2);
assert r1 == 7 : "r1=" + r1;
int r2 = findSecond(List.of(10, 20, 30), x -> true);
assert r2 == 20 : "r2=" + r2;
String r3 = findSecond(List.of("alpha","beta","gamma","delta"), s -> s.length() <= 5);
assert r3.equals("delta") : "r3=" + r3;
boolean threw = false... | syntax_completion |
29 | devbench-syntax-completion | java | import java.util.*;
public class SCTask29 {
sealed interface Expr permits Num, Add, Mul, Neg {}
record Num(int value) implements Expr {}
record Add(Expr left, Expr right) implements Expr {}
record Mul(Expr left, Expr right) implements Expr {}
record Neg(Expr inner) implements Expr {}
public st... | -> 0;
case Mul(var l, var r) -> eval(l) * eval(r);
case Neg(Neg(var inner)) -> eval(inner);
case Neg(var inner) -> -eval(inner);
};
}
|
public static void main(String[] args) {
Expr e1 = new Add(new Num(3), new Mul(new Num(2), new Num(4)));
System.out.println("3 + 2*4 = " + eval(e1));
Expr e2 = new Neg(new Neg(new Num(5)));
System.out.println("--5 = " + eval(e2));
}
}
| assert eval(new Num(42)) == 42 : "Num";
assert eval(new Add(new Num(3), new Num(7))) == 10 : "Add";
assert eval(new Mul(new Num(0), new Num(99))) == 0 : "Mul zero shortcut";
assert eval(new Mul(new Num(3), new Num(4))) == 12 : "Mul";
assert eval(new Neg(new Num(5))) == -5 : "Neg";
assert eval(new Neg(new Neg(new Num(8)... | syntax_completion |
30 | devbench-syntax-completion | java | import java.util.*;
public class SCTask30 {
sealed interface Shape permits Circle, Rect, Triangle {}
record Circle(double radius) implements Shape {}
record Rect(double w, double h) implements Shape {}
record Triangle(double a, double b, double c) implements Shape {}
sealed interface Color permits... | -> "square " + String.format("%.0f", w);
case Painted(Rect(var w, var h), var color)
-> "rect " + String.format("%.0fx%.0f", w, h);
case Painted(Triangle(var a, var b, var c), var color) when a == b && b == c
-> "equilateral t=" + String.format("%.... |
public static void main(String[] args) {
System.out.println(describe(new Painted(new Circle(10), new RGB(255, 0, 0))));
System.out.println(describe(new Painted(new Circle(3), new Named("blue"))));
System.out.println(describe(new Painted(new Rect(5, 5), new Named("green"))));
System.... | assert describe(new Painted(new Circle(10), new RGB(255,0,0))).equals("large red circle r=10") : "t1";
assert describe(new Painted(new Circle(3), new Named("blue"))).equals("blue circle r=3") : "t2";
assert describe(new Painted(new Rect(5,5), new Named("green"))).equals("square 5") : "t3";
assert describe(new Painted(n... | syntax_completion |
31 | devbench-syntax-completion | java | import java.lang.annotation.*;
import java.lang.reflect.*;
public class SCTask31 {
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Label {
String value();
int order() default 0;
}
@Label(value = "First Name", order = 1)
static String firstName ... | Label.class
);
if (lbl == null) return "no label";
return lbl.value() + ":" + lbl.order();
}
|
public static void main(String[] args) throws Exception {
String r1 = getLabel("firstName");
String r2 = getLabel("age");
System.out.println(r1);
System.out.println(r2);
}
}
| try {
assert SCTask31.getLabel("firstName").equals("First Name:1") : "Expected First Name:1 got " + SCTask31.getLabel("firstName");
assert SCTask31.getLabel("age").equals("Age:2") : "Expected Age:2 got " + SCTask31.getLabel("age");
} catch (NoSuchFieldException e) { throw new RuntimeException(e); }
| syntax_completion |
32 | devbench-syntax-completion | java | import java.lang.reflect.*;
import java.util.*;
public class SCTask32 {
public static abstract class TypeRef<T> {
private final Type type;
protected TypeRef() {
Type superclass = getClass().getGenericSuperclass();
this.type = ((ParameterizedType) superclass).getActualTypeAr... | args[i] instanceof Class<?> c ? c.getSimpleName() : args[i].toString()
);
}
sb.append(">");
return sb.toString();
}
return ((Class<?>) t).getSimpleName();
}
|
public static void main(String[] args) {
TypeRef<List<String>> ref1 = new TypeRef<>() {};
TypeRef<Map<String, Integer>> ref2 = new TypeRef<>() {};
TypeRef<String> ref3 = new TypeRef<>() {};
System.out.println(describeType(ref1));
System.out.println(describeType(ref2));
... | TypeRef<List<String>> ref1 = new SCTask32.TypeRef<>() {};
TypeRef<Map<String, Integer>> ref2 = new SCTask32.TypeRef<>() {};
TypeRef<String> ref3 = new SCTask32.TypeRef<>() {};
assert SCTask32.describeType(ref1).equals("List<String>") : "Got " + SCTask32.describeType(ref1);
assert SCTask32.describeType(ref2).equals("Map... | syntax_completion |
33 | devbench-syntax-completion | java | import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class SCTask33 {
public static Function<List<String>, List<String>> mapFilter(
Function<String, String> transform, Predicate<String> keep) {
return list -> list.stream()
.map(transform)
.... | keep
)
.collect(Collectors.toList());
}
|
public static void main(String[] args) {
Function<List<String>, List<String>> pipeline =
mapFilter(String::toUpperCase, s -> s.length() > 3);
List<String> result = pipeline.apply(Arrays.asList("hi", "hello", "world", "ok"));
System.out.println(result);
}
}
| Function<List<String>, List<String>> p = SCTask33.mapFilter(String::toUpperCase, s -> s.length() > 3);
List<String> r = p.apply(java.util.Arrays.asList("hi", "hello", "world", "ok"));
assert r.equals(java.util.Arrays.asList("HELLO", "WORLD")) : "Got " + r;
List<String> r2 = p.apply(java.util.Arrays.asList("a", "ab"));
... | syntax_completion |
34 | devbench-syntax-completion | java | import java.util.*;
import java.util.stream.*;
public class SCTask34 {
public static Map.Entry<Long, Double> countAndAvg(List<List<Integer>> nested) {
return nested.stream()
.flatMap(Collection::stream)
.filter(n -> n > 0)
.collect(Collectors.teeing(
Col... | Map.entry(count, avg)
));
}
|
public static void main(String[] args) {
List<List<Integer>> data = List.of(
List.of(1, -2, 3),
List.of(4, 5, -1),
List.of(0, 6)
);
var result = countAndAvg(data);
System.out.println(result.getKey() + " " + result.getValue());
}
}
| var r = SCTask34.countAndAvg(java.util.List.of(java.util.List.of(1,-2,3), java.util.List.of(4,5,-1), java.util.List.of(0,6)));
assert r.getKey() == 5L : "Expected count 5 got " + r.getKey();
assert Math.abs(r.getValue() - 3.8) < 0.01 : "Expected avg 3.8 got " + r.getValue();
var r2 = SCTask34.countAndAvg(java.util.List... | syntax_completion |
35 | devbench-syntax-completion | java | import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class SCTask35 {
public static <T> Predicate<T> allOf(List<Predicate<T>> predicates) {
return predicates.stream()
.reduce(
t -> true,
Predicate::and
| );
}
public static List<Integer> filterAll(List<Integer> nums, List<Predicate<Integer>> preds) {
Predicate<Integer> combined = allOf(preds);
return nums.stream().filter(combined).collect(Collectors.toList());
}
|
public static void main(String[] args) {
List<Predicate<Integer>> preds = List.of(
n -> n > 0,
n -> n % 2 == 0,
n -> n < 100
);
List<Integer> result = filterAll(
Arrays.asList(-2, 1, 4, 7, 50, 100, 200), preds);
System.out.println(resu... | List<Predicate<Integer>> preds = java.util.List.of(n -> n > 0, n -> n % 2 == 0, n -> n < 100);
List<Integer> r = SCTask35.filterAll(java.util.Arrays.asList(-2, 1, 4, 7, 50, 100, 200), preds);
assert r.equals(java.util.Arrays.asList(4, 50)) : "Got " + r;
List<Integer> r2 = SCTask35.filterAll(java.util.Arrays.asList(2, 4... | syntax_completion |
36 | devbench-syntax-completion | java | import java.util.*;
public class SCTask36 {
sealed interface Status permits Active, Suspended, Closed {}
record Active(String user, int level) implements Status {}
record Suspended(String reason) implements Status {}
record Closed() implements Status {}
public static Optional<String> describe(Sta... | Optional.of("power:" + u);
case Active(var u, var lv) ->
Optional.of("normal:" + u + ":" + lv);
case Suspended(var r) ->
Optional.of("suspended:" + r);
case Closed() ->
Optional.empty();
};
}
|
public static void main(String[] args) {
System.out.println(describe(new Active("alice", 15)));
System.out.println(describe(new Active("bob", 3)));
System.out.println(describe(new Suspended("policy")));
System.out.println(describe(new Closed()));
}
}
| assert SCTask36.describe(new SCTask36.Active("alice", 15)).get().equals("power:alice") : "wrong power";
assert SCTask36.describe(new SCTask36.Active("bob", 3)).get().equals("normal:bob:3") : "wrong normal";
assert SCTask36.describe(new SCTask36.Suspended("policy")).get().equals("suspended:policy") : "wrong suspended";
... | syntax_completion |
37 | devbench-syntax-completion | java | public class SCTask37 {
public static String classify(int code, boolean strict) {
return switch (code / 100) {
case 2 -> "ok";
case 4 -> {
String detail = switch (code) {
case 400 -> "bad_request";
case 401 ->
| "unauthorized";
case 404 -> "not_found";
default -> "client_error";
};
yield strict ? detail.toUpperCase() : detail;
}
case 5 -> {
yield strict ? "SERVER_ERROR" : "server_error";
... |
public static void main(String[] args) {
System.out.println(classify(200, false));
System.out.println(classify(401, true));
System.out.println(classify(404, false));
System.out.println(classify(500, true));
System.out.println(classify(302, false));
}
}
| assert SCTask37.classify(200, false).equals("ok") : "200";
assert SCTask37.classify(401, true).equals("UNAUTHORIZED") : "401 strict got " + SCTask37.classify(401, true);
assert SCTask37.classify(404, false).equals("not_found") : "404";
assert SCTask37.classify(500, true).equals("SERVER_ERROR") : "500 strict";
assert SC... | syntax_completion |
38 | devbench-syntax-completion | java | import java.util.*;
public class SCTask38 {
public static Map.Entry<String, Integer> process(String op, int a, int b, List<String> log) {
int result = switch (op) {
case "add" -> {
log.add("adding " + a + "+" + b);
yield a + b;
}
case "mu... | ab);
}
default -> {
log.add("unknown op: " + op);
yield 0;
}
};
return Map.entry(op + "(" + a + "," + b + ")", result);
}
|
public static void main(String[] args) {
List<String> log = new ArrayList<>();
var r1 = process("add", 3, 4, log);
var r2 = process("mul", 5, 6, log);
var r3 = process("maxabs", -7, 3, log);
var r4 = process("div", 1, 2, log);
System.out.println(r1);
System.o... | List<String> log = new java.util.ArrayList<>();
var r1 = SCTask38.process("add", 3, 4, log);
assert r1.getKey().equals("add(3,4)") : "key1: " + r1.getKey();
assert r1.getValue() == 7 : "val1: " + r1.getValue();
var r2 = SCTask38.process("maxabs", -7, 3, log);
assert r2.getValue() == 7 : "maxabs: " + r2.getValue();
var ... | syntax_completion |
39 | devbench-syntax-completion | java | import java.util.*;
import java.util.stream.*;
public class SCTask39 {
public static Map<String, Integer> summarize(List<String> items) {
record Pair(String category, int value) {}
List<Pair> pairs = items.stream()
.map(s -> {
String[] parts = s.split(":");
... | Integer.parseInt(parts[1]));
})
.collect(Collectors.toList());
return pairs.stream()
.collect(Collectors.groupingBy(Pair::category, Collectors.summingInt(Pair::value)));
}
|
public static void main(String[] args) {
List<String> data = List.of("fruit:10", "veggie:5", "fruit:20", "veggie:15", "fruit:3");
Map<String, Integer> result = summarize(data);
System.out.println(result);
}
}
| Map<String, Integer> r = SCTask39.summarize(java.util.List.of("fruit:10", "veggie:5", "fruit:20", "veggie:15", "fruit:3"));
assert r.get("fruit") == 33 : "fruit: " + r.get("fruit");
assert r.get("veggie") == 20 : "veggie: " + r.get("veggie");
Map<String, Integer> r2 = SCTask39.summarize(java.util.List.of("a:1"));
asser... | syntax_completion |
40 | devbench-syntax-completion | java | import java.util.*;
import java.util.stream.*;
public class SCTask40 {
record MinMax<T extends Comparable<T>>(T min, T max) {}
public static <T extends Comparable<T>> MinMax<T> findMinMax(List<T> items) {
return items.stream()
.map(x -> new MinMax<>(x, x))
.reduce((a, b) -> ne... | a.max() : b.max()
))
.orElseThrow(() -> new NoSuchElementException("empty list"));
}
|
public static void main(String[] args) {
MinMax<Integer> r1 = findMinMax(List.of(3, 1, 4, 1, 5, 9, 2, 6));
System.out.println(r1.min() + " " + r1.max());
MinMax<String> r2 = findMinMax(List.of("banana", "apple", "cherry"));
System.out.println(r2.min() + " " + r2.max());
}
}
| SCTask40.MinMax<Integer> r1 = SCTask40.findMinMax(java.util.List.of(3,1,4,1,5,9,2,6));
assert r1.min() == 1 : "min int: " + r1.min();
assert r1.max() == 9 : "max int: " + r1.max();
SCTask40.MinMax<String> r2 = SCTask40.findMinMax(java.util.List.of("banana","apple","cherry"));
assert r2.min().equals("apple") : "min str:... | syntax_completion |
41 | devbench-syntax-completion | java | import java.util.*;
import java.util.stream.*;
public class SCTask41 {
public static List<String> classifyNumbers(List<Integer> nums) {
return nums.stream()
.map(n -> n == 0 ? "zero" :
n > 0 ? (n % 2 == 0 ? "pos-even" :
| "pos-odd") :
(n % 2 == 0 ? "neg-even" : "neg-odd"))
.collect(Collectors.toList()); |
}
public static Map<String, Long> countByCategory(List<Integer> nums) {
return classifyNumbers(nums).stream()
.collect(Collectors.groupingBy(s -> s, Collectors.counting()));
}
public static void main(String[] args) {
List<String> result = classifyNumbers(Arrays.asList(-4, ... | assert classifyNumbers(Arrays.asList(-4, -3, 0, 1, 2)).equals(
Arrays.asList("neg-even", "neg-odd", "zero", "pos-odd", "pos-even"))
: "basic classification failed";
assert classifyNumbers(Arrays.asList(0)).equals(Arrays.asList("zero"));
assert classifyNumbers(Collections.emptyList()).isEmpty();
assert classifyN... | syntax_completion |
42 | devbench-syntax-completion | java | import java.util.*;
import java.io.Serializable;
public class SCTask42 {
interface Labelable {
String getLabel();
}
static class TaggedItem implements Comparable<TaggedItem>, Serializable, Labelable {
private final String label;
private final int priority;
TaggedItem(String... | List<T> items) {
return items.stream()
.sorted()
.map(Labelable::getLabel)
.reduce("", (a, b) -> a.isEmpty() ? b : a + "," + b);
} |
public static void main(String[] args) {
List<TaggedItem> items = Arrays.asList(
new TaggedItem("gamma", 3),
new TaggedItem("alpha", 1),
new TaggedItem("beta", 2)
);
String result = summarizeSorted(items);
System.out.println(result);
}
}
| List<TaggedItem> items1 = Arrays.asList(
new TaggedItem("gamma", 3), new TaggedItem("alpha", 1), new TaggedItem("beta", 2));
assert summarizeSorted(items1).equals("alpha,beta,gamma") : "sort+join failed: " + summarizeSorted(items1);
List<TaggedItem> items2 = Arrays.asList(new TaggedItem("only", 1));
assert summariz... | syntax_completion |
43 | devbench-syntax-completion | java | import java.util.*;
import java.util.stream.*;
public class SCTask43 {
private final String name;
private final int score;
private final List<String> tags;
public SCTask43(String name, int score, List<String> tags) {
this.name = name;
this.score = score;
this.tags = Collections... | config.containsKey("score")
? ((Number) config.get("score")).intValue()
: -1,
config.containsKey("tags")
? ((List<?>) config.get("tags")).stream()
.map(Object::toString)
.collect(Collectors.toList())
... |
}
public String getName() { return name; }
public int getScore() { return score; }
public List<String> getTags() { return tags; }
public static void main(String[] args) {
Map<String, Object> cfg = new HashMap<>();
cfg.put("name", "test");
cfg.put("score", 42);
cfg.... | Map<String, Object> cfg1 = new HashMap<>();
cfg1.put("name", "hello");
cfg1.put("score", 99);
cfg1.put("tags", Arrays.asList("x", "y"));
SCTask43 o1 = new SCTask43(cfg1);
assert o1.getName().equals("hello") : "name failed";
assert o1.getScore() == 99 : "score failed";
assert o1.getTags().equals(Arrays.asList("x", "y"))... | syntax_completion |
44 | devbench-syntax-completion | java | import java.util.*;
import java.util.function.*;
public class SCTask44 {
@SuppressWarnings("unchecked")
public static <T> T coalesce(T... values) {
for (T v : values) {
if (v != null) return v;
}
return null;
}
public static <T> List<T> repeat(T item, int count) {
... | SCTask44.<String>coalesce(null, "x"), 2),
SCTask44.<String>repeat(
SCTask44.<String>coalesce(null, null, "y"), 3)
)
); |
System.out.println(name);
System.out.println(keys);
System.out.println(nested);
}
}
| String n = SCTask44.<String>coalesce(null, null, "fallback");
assert "fallback".equals(n) : "coalesce failed";
List<String> k = SCTask44.<String>repeat("key", 3);
assert k.equals(Arrays.asList("key", "key", "key")) : "repeat failed";
Map<String, List<String>> m = SCTask44.<String, List<String>>zipToMap(
Arrays.asLi... | syntax_completion |
45 | devbench-syntax-completion | java | import java.util.*;
import java.util.stream.*;
public class SCTask45 {
static class RangeSpliterator implements Spliterator<Integer> {
private int current; private final int end; private final int step;
RangeSpliterator(int s, int e, int st) { current = s; end = e; step = st; }
@Override
... | return Math.max(0, (long)(end - current + step - 1) / step);
}
@Override
public int characteristics() {
return ORDERED | SIZED | IMMUTABLE | NONNULL;
} |
}
public static List<Integer> rangeWithStep(int start, int end, int step) {
return StreamSupport.stream(new RangeSpliterator(start, end, step), false)
.collect(Collectors.toList());
}
public static void main(String[] args) {
System.out.println(rangeWithStep(0, 10, 2));
... | assert rangeWithStep(0, 10, 2).equals(Arrays.asList(0, 2, 4, 6, 8))
: "even range failed: " + rangeWithStep(0, 10, 2);
assert rangeWithStep(1, 15, 3).equals(Arrays.asList(1, 4, 7, 10, 13))
: "step-3 failed: " + rangeWithStep(1, 15, 3);
assert rangeWithStep(0, 0, 1).isEmpty() : "empty range failed";
assert range... | syntax_completion |
46 | devbench-syntax-completion | java | import java.util.*;
public class SCTask46 {
public static String safeDiv(int a, int b, String mode) {
try {
int result = a / b;
return switch (mode) {
case "hex" -> "0x" + Integer.toHexString(result);
case "bin" -> "0b" + Integer.toBinaryString(result... | case "oct" -> "0" + Integer.toOctalString(result);
default -> String.valueOf(result);
};
} catch (ArithmeticException e) {
return switch (mode) {
case "hex", "bin", "oct" -> "NaN(" + mode + ")";
default -> "NaN";
... |
}
public static void main(String[] args) {
System.out.println(safeDiv(255, 1, "hex"));
System.out.println(safeDiv(10, 0, "bin"));
}
}
| assert safeDiv(255, 1, "hex").equals("0xff") : "hex failed: " + safeDiv(255, 1, "hex");
assert safeDiv(8, 1, "bin").equals("0b1000") : "bin failed";
assert safeDiv(8, 1, "oct").equals("010") : "oct failed";
assert safeDiv(42, 1, "dec").equals("42") : "default failed";
assert safeDiv(1, 0, "hex").equals("NaN(hex)") : "d... | syntax_completion |
47 | devbench-syntax-completion | java | import java.util.*;
import java.util.function.*;
public class SCTask47 {
public static Function<String, Function<String, Function<String, String>>>
curriedJoin(String delimiter) {
return a -> b -> c ->
| String.join(delimiter, Arrays.asList(
a.isEmpty() ? "_" : a,
b.isEmpty() ? "_" : b,
c.isEmpty() ? "_" : c
));
}
public static Function<Integer, Function<Integer, Integer>>
curriedOp(BinaryOperator<Integer> op) {
return ... |
public static void main(String[] args) {
var joiner = curriedJoin("-");
String result = joiner.apply("a").apply("b").apply("c");
System.out.println(result);
var adder = curriedOp(Integer::sum);
System.out.println(adder.apply(3).apply(4));
}
}
| var j1 = curriedJoin("-");
assert j1.apply("x").apply("y").apply("z").equals("x-y-z") : "basic join failed";
assert j1.apply("").apply("b").apply("c").equals("_-b-c") : "empty first failed";
assert j1.apply("a").apply("").apply("").equals("a-_-_") : "empty last two failed";
var j2 = curriedJoin(",");
assert j2.apply("1... | syntax_completion |
48 | devbench-syntax-completion | java | import java.util.*;
import java.util.stream.*;
public class SCTask48 {
@SafeVarargs
public static <T> List<T> interleave(List<T>... lists) {
int maxLen = Arrays.stream(lists)
.mapToInt(List::size)
.max()
.orElse(0);
List<T> result = new ArrayList<>();
... | result.add(list.get(i));
}
}
}
return result;
} |
@SafeVarargs
public static <T extends Comparable<T>> T maxOf(T first, T... rest) {
T best = first;
for (T item : rest) {
if (item.compareTo(best) > 0) best = item;
}
return best;
}
public static void main(String[] args) {
List<String> r = interleave... | List<String> r1 = interleave(
Arrays.asList("a", "b", "c"),
Arrays.asList("1", "2"),
Arrays.asList("x", "y", "z", "w"));
assert r1.equals(Arrays.asList("a", "1", "x", "b", "2", "y", "c", "z", "w"))
: "interleave failed: " + r1;
List<Integer> r2 = interleave(Arrays.asList(1, 2), Arrays.asList(3, 4));
ass... | syntax_completion |
49 | devbench-syntax-completion | java | import java.util.*;
import java.util.function.*;
public class SCTask49 {
static class FilterMapIterator<T, R> implements Iterator<R> {
private final Iterator<T> source;
private final Predicate<T> filter;
private final Function<T, R> mapper;
private R nextVal; private boolean hasNex... | R val = nextVal;
advance();
return val;
}
}
public static <T, R> Iterable<R> filterMapIterable(
Iterable<T> source, Predicate<T> filter, Function<T, R> mapper) {
return () -> new FilterMapIterator<>(source.iterator(), filter, mapper);
} |
public static void main(String[] args) {
List<String> result = new ArrayList<>();
for (String s : filterMapIterable(Arrays.asList(1,2,3,4,5,6), n -> n % 2 == 0, n -> "v" + n)) {
result.add(s);
}
System.out.println(result);
}
}
| List<String> r1 = new ArrayList<>();
for (String s : filterMapIterable(Arrays.asList(1,2,3,4,5,6), n -> n % 2 == 0, n -> "v" + n)) r1.add(s);
assert r1.equals(Arrays.asList("v2", "v4", "v6")) : "even filter failed: " + r1;
List<Integer> r2 = new ArrayList<>();
for (int x : filterMapIterable(Arrays.asList("ab","","cde"... | syntax_completion |
50 | devbench-syntax-completion | java | import java.util.*;
import java.util.stream.*;
public class SCTask50 {
static abstract class Node {
final String type; final Map<String, String> attrs; final List<Node> children;
Node(String t, Map<String, String> a, List<Node> c) {
type = t; attrs = Collections.unmodifiableMap(a); chil... | Arrays.stream(kids)
.filter(Objects::nonNull)
.collect(Collectors.toList()));
}
String render() {
String childStr = children.stream()
.map(Node::render)
.collect(Collectors.joining(""));
... |
}
public static void main(String[] args) {
Node tree = new Branch("div", null,
new Leaf("span", "hello", Map.of("class", "hi")),
new Branch("ul", Map.of("id", "list"),
new Leaf("li", "a", Map.of()),
new Leaf("li", "b", Map.of())
)
... | Node leaf = new Leaf("p", "text", Map.of());
assert leaf.render().equals("<p>text</p>") : "leaf render failed";
assert leaf.depth() == 1 : "leaf depth failed";
Node tree = new Branch("div", null,
new Leaf("span", "hello", Map.of("class", "hi")),
new Branch("ul", Map.of("id", "list"),
new Leaf("li", "a"... | syntax_completion |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.