{"title": "100 doors", "language": "Java", "task": "There are 100 doors in a row that are all initially closed. \n\nYou make 100 passes by the doors. \n\nThe first time through, visit every door and ''toggle'' the door (if the door is closed, open it; if it is open, close it). \n\nThe second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it. \n\nThe third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.\n\n\n;Task:\nAnswer the question: what state are the doors in after the last pass? Which are open, which are closed?\n\n\n'''Alternate:''' \nAs noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.\n\nOpening only those doors is an optimization that may also be expressed; \nhowever, as should be obvious, this defeats the intent of comparing implementations across programming languages.\n\n", "solution": "class HundredDoors {\n public static void main(String[] args) {\n boolean[] doors = new boolean[101];\n\n for (int i = 1; i < doors.length; i++) {\n for (int j = i; j < doors.length; j += i) {\n doors[j] = !doors[j];\n }\n }\n\n for (int i = 1; i < doors.length; i++) {\n if (doors[i]) {\n System.out.printf(\"Door %d is open.%n\", i);\n }\n }\n }\n}"} {"title": "100 prisoners", "language": "Java from Kotlin", "task": "The Problem:\n* 100 prisoners are individually numbered 1 to 100\n* A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside.\n* Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start.\n* Prisoners start outside the room\n:* They can decide some strategy before any enter the room.\n:* Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer.\n:* A prisoner can open no more than 50 drawers.\n:* A prisoner tries to find his own number.\n:* A prisoner finding his own number is then held apart from the others.\n* If '''all''' 100 prisoners find their own numbers then they will all be pardoned. If ''any'' don't then ''all'' sentences stand. \n\n\n;The task:\n# Simulate several thousand instances of the game where the prisoners randomly open drawers\n# Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of:\n:* First opening the drawer whose outside number is his prisoner number.\n:* If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum).\n\n\nShow and compare the computed probabilities of success for the two strategies, here, on this page.\n\n\n;References:\n# The unbelievable solution to the 100 prisoner puzzle standupmaths (Video).\n# [[wp:100 prisoners problem]]\n# 100 Prisoners Escape Puzzle DataGenetics.\n# Random permutation statistics#One hundred prisoners on Wikipedia.\n\n", "solution": "import java.util.Collections;\nimport java.util.List;\nimport java.util.Objects;\nimport java.util.function.Function;\nimport java.util.function.Supplier;\nimport java.util.stream.Collectors;\nimport java.util.stream.IntStream;\n\npublic class Main {\n private static boolean playOptimal(int n) {\n List secretList = IntStream.range(0, n).boxed().collect(Collectors.toList());\n Collections.shuffle(secretList);\n\n prisoner:\n for (int i = 0; i < secretList.size(); ++i) {\n int prev = i;\n for (int j = 0; j < secretList.size() / 2; ++j) {\n if (secretList.get(prev) == i) {\n continue prisoner;\n }\n prev = secretList.get(prev);\n }\n return false;\n }\n return true;\n }\n\n private static boolean playRandom(int n) {\n List secretList = IntStream.range(0, n).boxed().collect(Collectors.toList());\n Collections.shuffle(secretList);\n\n prisoner:\n for (Integer i : secretList) {\n List trialList = IntStream.range(0, n).boxed().collect(Collectors.toList());\n Collections.shuffle(trialList);\n\n for (int j = 0; j < trialList.size() / 2; ++j) {\n if (Objects.equals(trialList.get(j), i)) {\n continue prisoner;\n }\n }\n\n return false;\n }\n return true;\n }\n\n private static double exec(int n, int p, Function play) {\n int succ = 0;\n for (int i = 0; i < n; ++i) {\n if (play.apply(p)) {\n succ++;\n }\n }\n return (succ * 100.0) / n;\n }\n\n public static void main(String[] args) {\n final int n = 100_000;\n final int p = 100;\n System.out.printf(\"# of executions: %d\\n\", n);\n System.out.printf(\"Optimal play success rate: %f%%\\n\", exec(n, p, Main::playOptimal));\n System.out.printf(\"Random play success rate: %f%%\\n\", exec(n, p, Main::playRandom));\n }\n}"} {"title": "15 puzzle game", "language": "Java 8", "task": "Implement the Fifteen Puzzle Game.\n\n\nThe '''15-puzzle''' is also known as: \n:::* '''Fifteen Puzzle'''\n:::* '''Gem Puzzle'''\n:::* '''Boss Puzzle'''\n:::* '''Game of Fifteen'''\n:::* '''Mystic Square'''\n:::* '''14-15 Puzzle'''\n:::* and some others.\n\n\n;Related Tasks:\n:* 15 Puzzle Solver\n:* [[16 Puzzle Game]]\n\n", "solution": "package fifteenpuzzle;\n\nimport java.awt.*;\nimport java.awt.event.*;\nimport java.util.Random;\nimport javax.swing.*;\n\nclass FifteenPuzzle extends JPanel {\n\n private final int side = 4;\n private final int numTiles = side * side - 1;\n\n private final Random rand = new Random();\n private final int[] tiles = new int[numTiles + 1];\n private final int tileSize;\n private int blankPos;\n private final int margin;\n private final int gridSize;\n private boolean gameOver;\n\n private FifteenPuzzle() {\n final int dim = 640;\n\n margin = 80;\n tileSize = (dim - 2 * margin) / side;\n gridSize = tileSize * side;\n\n setPreferredSize(new Dimension(dim, dim + margin));\n setBackground(Color.WHITE);\n setForeground(new Color(0x6495ED)); // cornflowerblue\n setFont(new Font(\"SansSerif\", Font.BOLD, 60));\n\n gameOver = true;\n\n addMouseListener(new MouseAdapter() {\n @Override\n public void mousePressed(MouseEvent e) {\n if (gameOver) {\n newGame();\n\n } else {\n\n int ex = e.getX() - margin;\n int ey = e.getY() - margin;\n\n if (ex < 0 || ex > gridSize || ey < 0 || ey > gridSize) {\n return;\n }\n\n int c1 = ex / tileSize;\n int r1 = ey / tileSize;\n int c2 = blankPos % side;\n int r2 = blankPos / side;\n\n int clickPos = r1 * side + c1;\n\n int dir = 0;\n if (c1 == c2 && Math.abs(r1 - r2) > 0) {\n dir = (r1 - r2) > 0 ? 4 : -4;\n \n } else if (r1 == r2 && Math.abs(c1 - c2) > 0) {\n dir = (c1 - c2) > 0 ? 1 : -1;\n }\n\n if (dir != 0) {\n do {\n int newBlankPos = blankPos + dir;\n tiles[blankPos] = tiles[newBlankPos];\n blankPos = newBlankPos;\n } while (blankPos != clickPos);\n tiles[blankPos] = 0;\n }\n \n gameOver = isSolved();\n }\n repaint();\n }\n });\n\n newGame();\n }\n\n private void newGame() {\n do {\n reset();\n shuffle();\n } while (!isSolvable());\n gameOver = false;\n }\n\n private void reset() {\n for (int i = 0; i < tiles.length; i++) {\n tiles[i] = (i + 1) % tiles.length;\n }\n blankPos = tiles.length - 1;\n }\n\n private void shuffle() {\n // don't include the blank space in the shuffle, leave it\n // in the home position\n int n = numTiles;\n while (n > 1) {\n int r = rand.nextInt(n--);\n int tmp = tiles[r];\n tiles[r] = tiles[n];\n tiles[n] = tmp;\n }\n }\n\n /* Only half the permutations of the puzzle are solvable.\n\n Whenever a tile is preceded by a tile with higher value it counts\n as an inversion. In our case, with the blank space in the home\n position, the number of inversions must be even for the puzzle\n to be solvable.\n\n See also:\n www.cs.bham.ac.uk/~mdr/teaching/modules04/java2/TilesSolvability.html\n */\n private boolean isSolvable() {\n int countInversions = 0;\n for (int i = 0; i < numTiles; i++) {\n for (int j = 0; j < i; j++) {\n if (tiles[j] > tiles[i]) {\n countInversions++;\n }\n }\n }\n return countInversions % 2 == 0;\n }\n\n private boolean isSolved() {\n if (tiles[tiles.length - 1] != 0) {\n return false;\n }\n for (int i = numTiles - 1; i >= 0; i--) {\n if (tiles[i] != i + 1) {\n return false;\n }\n }\n return true;\n }\n\n private void drawGrid(Graphics2D g) {\n for (int i = 0; i < tiles.length; i++) {\n int r = i / side;\n int c = i % side;\n int x = margin + c * tileSize;\n int y = margin + r * tileSize;\n\n if (tiles[i] == 0) {\n if (gameOver) {\n g.setColor(Color.GREEN);\n drawCenteredString(g, \"\\u2713\", x, y);\n }\n continue;\n }\n\n g.setColor(getForeground());\n g.fillRoundRect(x, y, tileSize, tileSize, 25, 25);\n g.setColor(Color.blue.darker());\n g.drawRoundRect(x, y, tileSize, tileSize, 25, 25);\n g.setColor(Color.WHITE);\n\n drawCenteredString(g, String.valueOf(tiles[i]), x, y);\n }\n }\n\n private void drawStartMessage(Graphics2D g) {\n if (gameOver) {\n g.setFont(getFont().deriveFont(Font.BOLD, 18));\n g.setColor(getForeground());\n String s = \"click to start a new game\";\n int x = (getWidth() - g.getFontMetrics().stringWidth(s)) / 2;\n int y = getHeight() - margin;\n g.drawString(s, x, y);\n }\n }\n\n private void drawCenteredString(Graphics2D g, String s, int x, int y) {\n FontMetrics fm = g.getFontMetrics();\n int asc = fm.getAscent();\n int des = fm.getDescent();\n\n x = x + (tileSize - fm.stringWidth(s)) / 2;\n y = y + (asc + (tileSize - (asc + des)) / 2);\n\n g.drawString(s, x, y);\n }\n\n @Override\n public void paintComponent(Graphics gg) {\n super.paintComponent(gg);\n Graphics2D g = (Graphics2D) gg;\n g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n RenderingHints.VALUE_ANTIALIAS_ON);\n\n drawGrid(g);\n drawStartMessage(g);\n }\n\n public static void main(String[] args) {\n SwingUtilities.invokeLater(() -> {\n JFrame f = new JFrame();\n f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n f.setTitle(\"Fifteen Puzzle\");\n f.setResizable(false);\n f.add(new FifteenPuzzle(), BorderLayout.CENTER);\n f.pack();\n f.setLocationRelativeTo(null);\n f.setVisible(true);\n });\n }\n}"} {"title": "21 game", "language": "Java", "task": "'''21''' is a two player game, the game is played by choosing \na number ('''1''', '''2''', or '''3''') to be added to the ''running total''.\n\nThe game is won by the player whose chosen number causes the ''running total''\nto reach ''exactly'' '''21'''.\n\nThe ''running total'' starts at zero. \nOne player will be the computer.\n \nPlayers alternate supplying a number to be added to the ''running total''. \n\n\n;Task:\nWrite a computer program that will:\n::* do the prompting (or provide a button menu), \n::* check for errors and display appropriate error messages, \n::* do the additions (add a chosen number to the ''running total''), \n::* display the ''running total'', \n::* provide a mechanism for the player to quit/exit/halt/stop/close the program,\n::* issue a notification when there is a winner, and\n::* determine who goes first (maybe a random or user choice, or can be specified when the game begins). \n\n", "solution": "import java.util.Random;\nimport java.util.Scanner;\n\npublic class TwentyOneGame {\n\n public static void main(String[] args) {\n new TwentyOneGame().run(true, 21, new int[] {1, 2, 3});\n }\n \n public void run(boolean computerPlay, int max, int[] valid) {\n String comma = \"\";\n for ( int i = 0 ; i < valid.length ; i++ ) {\n comma += valid[i];\n if ( i < valid.length - 2 && valid.length >= 3 ) {\n comma += \", \";\n }\n if ( i == valid.length - 2 ) {\n comma += \" or \";\n }\n }\n System.out.printf(\"The %d game.%nEach player chooses to add %s to a running total.%n\" + \n \"The player whose turn it is when the total reaches %d will win the game.%n\" + \n \"Winner of the game starts the next game. Enter q to quit.%n%n\", max, comma, max);\n int cGames = 0;\n int hGames = 0;\n boolean anotherGame = true;\n try (Scanner scanner = new Scanner(System.in);) {\n while ( anotherGame ) {\n Random r = new Random();\n int round = 0;\n int total = 0;\n System.out.printf(\"Start game %d%n\", hGames + cGames + 1);\n DONE:\n while ( true ) {\n round++;\n System.out.printf(\"ROUND %d:%n%n\", round);\n for ( int play = 0 ; play < 2 ; play++ ) {\n if ( computerPlay ) {\n int guess = 0;\n // try find one equal\n for ( int test : valid ) {\n if ( total + test == max ) {\n guess = test;\n break;\n }\n }\n // try find one greater than\n if ( guess == 0 ) {\n for ( int test : valid ) {\n if ( total + test >= max ) {\n guess = test;\n break;\n }\n }\n }\n if ( guess == 0 ) {\n guess = valid[r.nextInt(valid.length)];\n }\n total += guess;\n System.out.printf(\"The computer chooses %d%n\", guess);\n System.out.printf(\"Running total is now %d%n%n\", total);\n if ( total >= max ) {\n break DONE;\n }\n }\n else {\n while ( true ) {\n System.out.printf(\"Your choice among %s: \", comma);\n String line = scanner.nextLine();\n if ( line.matches(\"^[qQ].*\") ) {\n System.out.printf(\"Computer wins %d game%s, human wins %d game%s. One game incomplete.%nQuitting.%n\", cGames, cGames == 1 ? \"\" : \"s\", hGames, hGames == 1 ? \"\" : \"s\");\n return;\n }\n try {\n int input = Integer.parseInt(line);\n boolean inputOk = false;\n for ( int test : valid ) {\n if ( input == test ) {\n inputOk = true;\n break;\n }\n }\n if ( inputOk ) {\n total += input;\n System.out.printf(\"Running total is now %d%n%n\", total);\n if ( total >= max ) {\n break DONE;\n }\n break;\n }\n else {\n System.out.printf(\"Invalid input - must be a number among %s. Try again.%n\", comma);\n }\n }\n catch (NumberFormatException e) {\n System.out.printf(\"Invalid input - must be a number among %s. Try again.%n\", comma);\n }\n }\n }\n computerPlay = !computerPlay;\n }\n }\n String win;\n if ( computerPlay ) {\n win = \"Computer wins!!\";\n cGames++;\n }\n else {\n win = \"You win and probably had help from another computer!!\";\n hGames++;\n }\n System.out.printf(\"%s%n\", win);\n System.out.printf(\"Computer wins %d game%s, human wins %d game%s%n%n\", cGames, cGames == 1 ? \"\" : \"s\", hGames, hGames == 1 ? \"\" : \"s\");\n while ( true ) {\n System.out.printf(\"Another game (y/n)? \");\n String line = scanner.nextLine();\n if ( line.matches(\"^[yY]$\") ) {\n // OK\n System.out.printf(\"%n\");\n break;\n }\n else if ( line.matches(\"^[nN]$\") ) {\n anotherGame = false;\n System.out.printf(\"Quitting.%n\");\n break;\n }\n else {\n System.out.printf(\"Invalid input - must be a y or n. Try again.%n\");\n }\n }\n }\n }\n }\n\n}\n"} {"title": "24 game", "language": "Java 7", "task": "The 24 Game tests one's mental arithmetic. \n\n\n;Task\nWrite a program that displays four digits, each from 1 --> 9 (inclusive) with repetitions allowed.\n\nThe program should prompt for the player to enter an arithmetic expression using ''just'' those, and ''all'' of those four digits, used exactly ''once'' each. The program should ''check'' then evaluate the expression. \n\nThe goal is for the player to enter an expression that (numerically) evaluates to '''24'''.\n* Only the following operators/functions are allowed: multiplication, division, addition, subtraction\n* Division should use floating point or rational arithmetic, etc, to preserve remainders.\n* Brackets are allowed, if using an infix expression evaluator.\n* Forming multiple digit numbers from the supplied digits is ''disallowed''. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).\n* The order of the digits when given does not have to be preserved.\n\n\n;Notes\n* The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.\n* The task is not for the program to generate the expression, or test whether an expression is even possible.\n\n\n;Related tasks\n* [[24 game/Solve]]\n\n\n;Reference\n* The 24 Game on h2g2.\n\n", "solution": "import java.util.*;\n\npublic class Game24 {\n static Random r = new Random();\n\n public static void main(String[] args) {\n\n int[] digits = randomDigits();\n Scanner in = new Scanner(System.in);\n\n System.out.print(\"Make 24 using these digits: \");\n System.out.println(Arrays.toString(digits));\n System.out.print(\"> \");\n\n Stack s = new Stack<>();\n long total = 0;\n for (char c : in.nextLine().toCharArray()) {\n if ('0' <= c && c <= '9') {\n int d = c - '0';\n total += (1 << (d * 5));\n s.push((float) d);\n } else if (\"+/-*\".indexOf(c) != -1) {\n s.push(applyOperator(s.pop(), s.pop(), c));\n }\n }\n if (tallyDigits(digits) != total)\n System.out.print(\"Not the same digits. \");\n else if (Math.abs(24 - s.peek()) < 0.001F)\n System.out.println(\"Correct!\");\n else\n System.out.print(\"Not correct.\");\n }\n\n static float applyOperator(float a, float b, char c) {\n switch (c) {\n case '+':\n return a + b;\n case '-':\n return b - a;\n case '*':\n return a * b;\n case '/':\n return b / a;\n default:\n return Float.NaN;\n }\n }\n\n static long tallyDigits(int[] a) {\n long total = 0;\n for (int i = 0; i < 4; i++)\n total += (1 << (a[i] * 5));\n return total;\n }\n\n static int[] randomDigits() { \n int[] result = new int[4];\n for (int i = 0; i < 4; i++)\n result[i] = r.nextInt(9) + 1;\n return result;\n }\n}"} {"title": "24 game/Solve", "language": "Java 7", "task": "Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the [[24 game]].\n\nShow examples of solutions generated by the program.\n\n\n;Related task:\n* [[Arithmetic Evaluator]]\n\n", "solution": "import java.util.*;\n\npublic class Game24Player {\n final String[] patterns = {\"nnonnoo\", \"nnonono\", \"nnnoono\", \"nnnonoo\",\n \"nnnnooo\"};\n final String ops = \"+-*/^\";\n\n String solution;\n List digits;\n\n public static void main(String[] args) {\n new Game24Player().play();\n }\n\n void play() {\n digits = getSolvableDigits();\n\n Scanner in = new Scanner(System.in);\n while (true) {\n System.out.print(\"Make 24 using these digits: \");\n System.out.println(digits);\n System.out.println(\"(Enter 'q' to quit, 's' for a solution)\");\n System.out.print(\"> \");\n\n String line = in.nextLine();\n if (line.equalsIgnoreCase(\"q\")) {\n System.out.println(\"\\nThanks for playing\");\n return;\n }\n\n if (line.equalsIgnoreCase(\"s\")) {\n System.out.println(solution);\n digits = getSolvableDigits();\n continue;\n }\n\n char[] entry = line.replaceAll(\"[^*+-/)(\\\\d]\", \"\").toCharArray();\n\n try {\n validate(entry);\n\n if (evaluate(infixToPostfix(entry))) {\n System.out.println(\"\\nCorrect! Want to try another? \");\n digits = getSolvableDigits();\n } else {\n System.out.println(\"\\nNot correct.\");\n }\n\n } catch (Exception e) {\n System.out.printf(\"%n%s Try again.%n\", e.getMessage());\n }\n }\n }\n\n void validate(char[] input) throws Exception {\n int total1 = 0, parens = 0, opsCount = 0;\n\n for (char c : input) {\n if (Character.isDigit(c))\n total1 += 1 << (c - '0') * 4;\n else if (c == '(')\n parens++;\n else if (c == ')')\n parens--;\n else if (ops.indexOf(c) != -1)\n opsCount++;\n if (parens < 0)\n throw new Exception(\"Parentheses mismatch.\");\n }\n\n if (parens != 0)\n throw new Exception(\"Parentheses mismatch.\");\n\n if (opsCount != 3)\n throw new Exception(\"Wrong number of operators.\");\n\n int total2 = 0;\n for (int d : digits)\n total2 += 1 << d * 4;\n\n if (total1 != total2)\n throw new Exception(\"Not the same digits.\");\n }\n\n boolean evaluate(char[] line) throws Exception {\n Stack s = new Stack<>();\n try {\n for (char c : line) {\n if ('0' <= c && c <= '9')\n s.push((float) c - '0');\n else\n s.push(applyOperator(s.pop(), s.pop(), c));\n }\n } catch (EmptyStackException e) {\n throw new Exception(\"Invalid entry.\");\n }\n return (Math.abs(24 - s.peek()) < 0.001F);\n }\n\n float applyOperator(float a, float b, char c) {\n switch (c) {\n case '+':\n return a + b;\n case '-':\n return b - a;\n case '*':\n return a * b;\n case '/':\n return b / a;\n default:\n return Float.NaN;\n }\n }\n\n List randomDigits() {\n Random r = new Random();\n List result = new ArrayList<>(4);\n for (int i = 0; i < 4; i++)\n result.add(r.nextInt(9) + 1);\n return result;\n }\n\n List getSolvableDigits() {\n List result;\n do {\n result = randomDigits();\n } while (!isSolvable(result));\n return result;\n }\n\n boolean isSolvable(List digits) {\n Set> dPerms = new HashSet<>(4 * 3 * 2);\n permute(digits, dPerms, 0);\n\n int total = 4 * 4 * 4;\n List> oPerms = new ArrayList<>(total);\n permuteOperators(oPerms, 4, total);\n\n StringBuilder sb = new StringBuilder(4 + 3);\n\n for (String pattern : patterns) {\n char[] patternChars = pattern.toCharArray();\n\n for (List dig : dPerms) {\n for (List opr : oPerms) {\n\n int i = 0, j = 0;\n for (char c : patternChars) {\n if (c == 'n')\n sb.append(dig.get(i++));\n else\n sb.append(ops.charAt(opr.get(j++)));\n }\n\n String candidate = sb.toString();\n try {\n if (evaluate(candidate.toCharArray())) {\n solution = postfixToInfix(candidate);\n return true;\n }\n } catch (Exception ignored) {\n }\n sb.setLength(0);\n }\n }\n }\n return false;\n }\n\n String postfixToInfix(String postfix) {\n class Expression {\n String op, ex;\n int prec = 3;\n\n Expression(String e) {\n ex = e;\n }\n\n Expression(String e1, String e2, String o) {\n ex = String.format(\"%s %s %s\", e1, o, e2);\n op = o;\n prec = ops.indexOf(o) / 2;\n }\n }\n\n Stack expr = new Stack<>();\n\n for (char c : postfix.toCharArray()) {\n int idx = ops.indexOf(c);\n if (idx != -1) {\n\n Expression r = expr.pop();\n Expression l = expr.pop();\n\n int opPrec = idx / 2;\n\n if (l.prec < opPrec)\n l.ex = '(' + l.ex + ')';\n\n if (r.prec <= opPrec)\n r.ex = '(' + r.ex + ')';\n\n expr.push(new Expression(l.ex, r.ex, \"\" + c));\n } else {\n expr.push(new Expression(\"\" + c));\n }\n }\n return expr.peek().ex;\n }\n\n char[] infixToPostfix(char[] infix) throws Exception {\n StringBuilder sb = new StringBuilder();\n Stack s = new Stack<>();\n try {\n for (char c : infix) {\n int idx = ops.indexOf(c);\n if (idx != -1) {\n if (s.isEmpty())\n s.push(idx);\n else {\n while (!s.isEmpty()) {\n int prec2 = s.peek() / 2;\n int prec1 = idx / 2;\n if (prec2 >= prec1)\n sb.append(ops.charAt(s.pop()));\n else\n break;\n }\n s.push(idx);\n }\n } else if (c == '(') {\n s.push(-2);\n } else if (c == ')') {\n while (s.peek() != -2)\n sb.append(ops.charAt(s.pop()));\n s.pop();\n } else {\n sb.append(c);\n }\n }\n while (!s.isEmpty())\n sb.append(ops.charAt(s.pop()));\n\n } catch (EmptyStackException e) {\n throw new Exception(\"Invalid entry.\");\n }\n return sb.toString().toCharArray();\n }\n\n void permute(List lst, Set> res, int k) {\n for (int i = k; i < lst.size(); i++) {\n Collections.swap(lst, i, k);\n permute(lst, res, k + 1);\n Collections.swap(lst, k, i);\n }\n if (k == lst.size())\n res.add(new ArrayList<>(lst));\n }\n\n void permuteOperators(List> res, int n, int total) {\n for (int i = 0, npow = n * n; i < total; i++)\n res.add(Arrays.asList((i / npow), (i % npow) / n, i % n));\n }\n}"} {"title": "4-rings or 4-squares puzzle", "language": "Java", "task": "Replace '''a, b, c, d, e, f,''' and\n '''g ''' with the decimal\ndigits LOW ---> HIGH\nsuch that the sum of the letters inside of each of the four large squares add up to\nthe same sum.\n\n\n +--------------+ +--------------+\n | | | |\n | a | | e |\n | | | |\n | +---+------+---+ +---+---------+\n | | | | | | | |\n | | b | | d | | f | |\n | | | | | | | |\n | | | | | | | |\n +----------+---+ +---+------+---+ |\n | c | | g |\n | | | |\n | | | |\n +--------------+ +-------------+\n\n\nShow all output here.\n\n\n:* Show all solutions for each letter being unique with\n LOW=1 HIGH=7\n:* Show all solutions for each letter being unique with\n LOW=3 HIGH=9\n:* Show only the ''number'' of solutions when each letter can be non-unique\n LOW=0 HIGH=9\n\n\n;Related task:\n* [[Solve the no connection puzzle]]\n\n", "solution": "import java.util.Arrays;\n\npublic class FourSquares {\n public static void main(String[] args) {\n fourSquare(1, 7, true, true);\n fourSquare(3, 9, true, true);\n fourSquare(0, 9, false, false);\n }\n\n private static void fourSquare(int low, int high, boolean unique, boolean print) {\n int count = 0;\n\n if (print) {\n System.out.println(\"a b c d e f g\");\n }\n for (int a = low; a <= high; ++a) {\n for (int b = low; b <= high; ++b) {\n if (notValid(unique, a, b)) continue;\n\n int fp = a + b;\n for (int c = low; c <= high; ++c) {\n if (notValid(unique, c, a, b)) continue;\n for (int d = low; d <= high; ++d) {\n if (notValid(unique, d, a, b, c)) continue;\n if (fp != b + c + d) continue;\n\n for (int e = low; e <= high; ++e) {\n if (notValid(unique, e, a, b, c, d)) continue;\n for (int f = low; f <= high; ++f) {\n if (notValid(unique, f, a, b, c, d, e)) continue;\n if (fp != d + e + f) continue;\n\n for (int g = low; g <= high; ++g) {\n if (notValid(unique, g, a, b, c, d, e, f)) continue;\n if (fp != f + g) continue;\n\n ++count;\n if (print) {\n System.out.printf(\"%d %d %d %d %d %d %d%n\", a, b, c, d, e, f, g);\n }\n }\n }\n }\n }\n }\n }\n }\n if (unique) {\n System.out.printf(\"There are %d unique solutions in [%d, %d]%n\", count, low, high);\n } else {\n System.out.printf(\"There are %d non-unique solutions in [%d, %d]%n\", count, low, high);\n }\n }\n\n private static boolean notValid(boolean unique, int needle, int... haystack) {\n return unique && Arrays.stream(haystack).anyMatch(p -> p == needle);\n }\n}"} {"title": "99 bottles of beer", "language": "Java", "task": "Display the complete lyrics for the song: '''99 Bottles of Beer on the Wall'''. \n\n\n;The beer song:\nThe lyrics follow this form:\n\n\n::: 99 bottles of beer on the wall\n::: 99 bottles of beer\n::: Take one down, pass it around\n::: 98 bottles of beer on the wall\n \n::: 98 bottles of beer on the wall\n::: 98 bottles of beer\n::: Take one down, pass it around\n::: 97 bottles of beer on the wall\n\n\n... and so on, until reaching '''0''' (zero).\n\nGrammatical support for ''1 bottle of beer'' is optional. \n\nAs with any puzzle, try to do it in as creative/concise/comical a way \nas possible (simple, obvious solutions allowed, too).\n\n\n\n\n;See also: \n* http://99-bottles-of-beer.net/\n* [[:Category:99_Bottles_of_Beer]]\n* [[:Category:Programming language families]]\n* Wikipedia 99 bottles of beer\n\n", "solution": "public class Beer {\n public static void main(String args[]) {\n song(99);\n }\n\n public static void song(int bottles) {\n if (bottles >= 0) {\n if (bottles > 1)\n System.out.println(bottles + \" bottles of beer on the wall\\n\" + bottles + \" bottles of beer\\nTake one down, pass it around\\n\" + (bottles - 1) + \" bottles of beer on the wall.\\n\");\n else if (bottles == 1)\n System.out.println(bottles + \" bottle of beer on the wall\\n\" + bottles + \" bottle of beer\\nTake one down, pass it around\\n\" + (bottles - 1) + \" bottles of beer on the wall.\\n\");\n else\n System.out.println(bottles + \" bottles of beer on the wall\\n\" + bottles + \" bottles of beer\\nBetter go to the store and buy some more!\");\n song(bottles - 1);\n }\n }\n}"} {"title": "99 bottles of beer", "language": "Java from C++", "task": "Display the complete lyrics for the song: '''99 Bottles of Beer on the Wall'''. \n\n\n;The beer song:\nThe lyrics follow this form:\n\n\n::: 99 bottles of beer on the wall\n::: 99 bottles of beer\n::: Take one down, pass it around\n::: 98 bottles of beer on the wall\n \n::: 98 bottles of beer on the wall\n::: 98 bottles of beer\n::: Take one down, pass it around\n::: 97 bottles of beer on the wall\n\n\n... and so on, until reaching '''0''' (zero).\n\nGrammatical support for ''1 bottle of beer'' is optional. \n\nAs with any puzzle, try to do it in as creative/concise/comical a way \nas possible (simple, obvious solutions allowed, too).\n\n\n\n\n;See also: \n* http://99-bottles-of-beer.net/\n* [[:Category:99_Bottles_of_Beer]]\n* [[:Category:Programming language families]]\n* Wikipedia 99 bottles of beer\n\n", "solution": "See: [[99 Bottles of Beer/Java/Object Oriented]]\n\n===GUI===\n"} {"title": "9 billion names of God the integer", "language": "Java", "task": "This task is a variation of the short story by Arthur C. Clarke.\n \n(Solvers should be aware of the consequences of completing this task.)\n\nIn detail, to specify what is meant by a \"name\":\n:The integer 1 has 1 name \"1\".\n:The integer 2 has 2 names \"1+1\", and \"2\".\n:The integer 3 has 3 names \"1+1+1\", \"2+1\", and \"3\".\n:The integer 4 has 5 names \"1+1+1+1\", \"2+1+1\", \"2+2\", \"3+1\", \"4\".\n:The integer 5 has 7 names \"1+1+1+1+1\", \"2+1+1+1\", \"2+2+1\", \"3+1+1\", \"3+2\", \"4+1\", \"5\".\n\n\n;Task\nDisplay the first 25 rows of a number triangle which begins:\n\n 1\n 1 1\n 1 1 1 \n 1 2 1 1\n 1 2 2 1 1\n 1 3 3 2 1 1\n\n\nWhere row n corresponds to integer n, and each column C in row m from left to right corresponds to the number of names beginning with C.\n\nA function G(n) should return the sum of the n-th row. \n\nDemonstrate this function by displaying: G(23), G(123), G(1234), and G(12345). \n\nOptionally note that the sum of the n-th row P(n) is the integer partition function. \n\nDemonstrate this is equivalent to G(n) by displaying: P(23), P(123), P(1234), and P(12345).\n\n\n;Extra credit\n\nIf your environment is able, plot P(n) against n for n=1\\ldots 999.\n\n;Related tasks\n* [[Partition function P]]\n\n", "solution": "Translation of [[9_billion_names_of_God_the_integer#Python|Python]] via [[9_billion_names_of_God_the_integer#D|D]]\n"} {"title": "9 billion names of God the integer", "language": "Java 8", "task": "This task is a variation of the short story by Arthur C. Clarke.\n \n(Solvers should be aware of the consequences of completing this task.)\n\nIn detail, to specify what is meant by a \"name\":\n:The integer 1 has 1 name \"1\".\n:The integer 2 has 2 names \"1+1\", and \"2\".\n:The integer 3 has 3 names \"1+1+1\", \"2+1\", and \"3\".\n:The integer 4 has 5 names \"1+1+1+1\", \"2+1+1\", \"2+2\", \"3+1\", \"4\".\n:The integer 5 has 7 names \"1+1+1+1+1\", \"2+1+1+1\", \"2+2+1\", \"3+1+1\", \"3+2\", \"4+1\", \"5\".\n\n\n;Task\nDisplay the first 25 rows of a number triangle which begins:\n\n 1\n 1 1\n 1 1 1 \n 1 2 1 1\n 1 2 2 1 1\n 1 3 3 2 1 1\n\n\nWhere row n corresponds to integer n, and each column C in row m from left to right corresponds to the number of names beginning with C.\n\nA function G(n) should return the sum of the n-th row. \n\nDemonstrate this function by displaying: G(23), G(123), G(1234), and G(12345). \n\nOptionally note that the sum of the n-th row P(n) is the integer partition function. \n\nDemonstrate this is equivalent to G(n) by displaying: P(23), P(123), P(1234), and P(12345).\n\n\n;Extra credit\n\nIf your environment is able, plot P(n) against n for n=1\\ldots 999.\n\n;Related tasks\n* [[Partition function P]]\n\n", "solution": "import java.math.BigInteger;\nimport java.util.*;\nimport static java.util.Arrays.asList;\nimport static java.util.stream.Collectors.toList;\nimport static java.util.stream.IntStream.range;\nimport static java.lang.Math.min;\n\npublic class Test {\n\n static List cumu(int n) {\n List> cache = new ArrayList<>();\n cache.add(asList(BigInteger.ONE));\n\n for (int L = cache.size(); L < n + 1; L++) {\n List r = new ArrayList<>();\n r.add(BigInteger.ZERO);\n for (int x = 1; x < L + 1; x++)\n r.add(r.get(r.size() - 1).add(cache.get(L - x).get(min(x, L - x))));\n cache.add(r);\n }\n return cache.get(n);\n }\n\n static List row(int n) {\n List r = cumu(n);\n return range(0, n).mapToObj(i -> r.get(i + 1).subtract(r.get(i)))\n .collect(toList());\n }\n\n public static void main(String[] args) {\n System.out.println(\"Rows:\");\n for (int x = 1; x < 11; x++)\n System.out.printf(\"%2d: %s%n\", x, row(x));\n\n System.out.println(\"\\nSums:\");\n for (int x : new int[]{23, 123, 1234}) {\n List c = cumu(x);\n System.out.printf(\"%s %s%n\", x, c.get(c.size() - 1));\n }\n }\n}"} {"title": "A+B", "language": "Java", "task": "'''A+B''' --- a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.\n\n\n;Task:\nGiven two integers, '''A''' and '''B'''. \n\nTheir sum needs to be calculated.\n\n\n;Input data:\nTwo integers are written in the input stream, separated by space(s):\n: (-1000 \\le A,B \\le +1000)\n\n\n;Output data:\nThe required output is one integer: the sum of '''A''' and '''B'''.\n\n\n;Example:\n::{|class=\"standard\"\n ! input \n ! output \n |-\n | 2 2 \n | 4 \n |-\n | 3 2 \n | 5 \n |}\n\n", "solution": "import java.io.*;\nimport java.util.*;\n\npublic class SumDif {\n StreamTokenizer in;\n PrintWriter out;\n\n public static void main(String[] args) throws IOException {\n new SumDif().run();\n }\n\n private int nextInt() throws IOException {\n in.nextToken();\n return (int)in.nval;\n }\n\n public void run() throws IOException {\n in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); // Standard input\n out = new PrintWriter(new OutputStreamWriter(System.out)); // Standard output\n solve();\n out.flush();\n }\n\n private void solve() throws IOException {\n out.println(nextInt() + nextInt());\n }\n}"} {"title": "ABC problem", "language": "Java 1.6+", "task": "You are given a collection of ABC blocks (maybe like the ones you had when you were a kid). \n\nThere are twenty blocks with two letters on each block. \n\nA complete alphabet is guaranteed amongst all sides of the blocks. \n\nThe sample collection of blocks: \n (B O)\n (X K)\n (D Q)\n (C P)\n (N A)\n (G T)\n (R E)\n (T G)\n (Q D)\n (F S)\n (J W)\n (H U)\n (V I)\n (A N)\n (O B)\n (E R)\n (F S)\n (L Y)\n (P C)\n (Z M)\n\n\n;Task:\nWrite a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks. \n\n\nThe rules are simple:\n::# Once a letter on a block is used that block cannot be used again\n::# The function should be case-insensitive\n::# Show the output on this page for the following 7 words in the following example\n\n\n;Example:\n >>> can_make_word(\"A\")\n True\n >>> can_make_word(\"BARK\")\n True\n >>> can_make_word(\"BOOK\")\n False\n >>> can_make_word(\"TREAT\")\n True\n >>> can_make_word(\"COMMON\")\n False\n >>> can_make_word(\"SQUAD\")\n True\n >>> can_make_word(\"CONFUSE\")\n True\n\n", "solution": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class ABC {\n\n public static void main(String[] args) {\n List blocks = Arrays.asList(\n \"BO\", \"XK\", \"DQ\", \"CP\", \"NA\",\n \"GT\", \"RE\", \"TG\", \"QD\", \"FS\",\n \"JW\", \"HU\", \"VI\", \"AN\", \"OB\",\n \"ER\", \"FS\", \"LY\", \"PC\", \"ZM\");\n\n for (String word : Arrays.asList(\"\", \"A\", \"BARK\", \"BOOK\", \"TREAT\", \"COMMON\", \"SQUAD\", \"CONFUSE\")) {\n System.out.printf(\"%s: %s%n\", word.isEmpty() ? \"\\\"\\\"\" : word, canMakeWord(word, blocks));\n }\n }\n\n public static boolean canMakeWord(String word, List blocks) {\n if (word.isEmpty())\n return true;\n\n char c = word.charAt(0);\n for (int i = 0; i < blocks.size(); i++) {\n String b = blocks.get(i);\n if (b.charAt(0) != c && b.charAt(1) != c)\n continue;\n Collections.swap(blocks, 0, i);\n if (canMakeWord(word.substring(1), blocks.subList(1, blocks.size())))\n return true;\n Collections.swap(blocks, 0, i);\n }\n\n return false;\n }\n}"} {"title": "ASCII art diagram converter", "language": "Java", "task": "Given the RFC 1035 message diagram from Section 4.1.1 (Header section format) as a string:\nhttp://www.ietf.org/rfc/rfc1035.txt\n\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | ID |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n |QR| Opcode |AA|TC|RD|RA| Z | RCODE |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | QDCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | ANCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | NSCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | ARCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n\nWhere (every column of the table is 1 bit):\n\n ID is 16 bits\n QR = Query (0) or Response (1)\n Opcode = Four bits defining kind of query:\n 0: a standard query (QUERY)\n 1: an inverse query (IQUERY)\n 2: a server status request (STATUS)\n 3-15: reserved for future use\n AA = Authoritative Answer bit\n TC = Truncation bit\n RD = Recursion Desired bit\n RA = Recursion Available bit\n Z = Reserved\n RCODE = Response code\n QC = Question Count\n ANC = Answer Count\n AUC = Authority Count\n ADC = Additional Count\n\nWrite a function, member function, class or template that accepts a similar multi-line string as input to define a data structure or something else able to decode or store a header with that specified bit structure.\n\nIf your language has macros, introspection, code generation, or powerful enough templates, then accept such string at compile-time to define the header data structure statically.\n\nSuch \"Header\" function or template should accept a table with 8, 16, 32 or 64 columns, and any number of rows. For simplicity the only allowed symbols to define the table are + - | (plus, minus, pipe), and whitespace. Lines of the input string composed just of whitespace should be ignored. Leading and trailing whitespace in the input string should be ignored, as well as before and after each table row. The box for each bit of the diagram takes four chars \"+--+\". The code should perform a little of validation of the input string, but for brevity a full validation is not required.\n\nBonus: perform a thoroughly validation of the input string.\n\n", "solution": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class AsciiArtDiagramConverter {\n\n private static final String TEST = \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n \"| ID |\\r\\n\" +\n \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n \"|QR| Opcode |AA|TC|RD|RA| Z | RCODE |\\r\\n\" +\n \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n \"| QDCOUNT |\\r\\n\" +\n \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n \"| ANCOUNT |\\r\\n\" +\n \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n \"| NSCOUNT |\\r\\n\" +\n \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\\r\\n\" +\n \"| ARCOUNT |\\r\\n\" +\n \"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\";\n\n public static void main(String[] args) {\n validate(TEST);\n display(TEST);\n Map> asciiMap = decode(TEST);\n displayMap(asciiMap);\n displayCode(asciiMap, \"78477bbf5496e12e1bf169a4\");\n }\n\n private static void displayCode(Map> asciiMap, String hex) {\n System.out.printf(\"%nTest string in hex:%n%s%n%n\", hex);\n\n String bin = new BigInteger(hex,16).toString(2);\n\n // Zero pad in front as needed\n int length = 0;\n for ( String code : asciiMap.keySet() ) {\n List pos = asciiMap.get(code);\n length += pos.get(1) - pos.get(0) + 1;\n }\n while ( length > bin.length() ) {\n bin = \"0\" + bin;\n }\n System.out.printf(\"Test string in binary:%n%s%n%n\", bin);\n\n System.out.printf(\"Name Size Bit Pattern%n\");\n System.out.printf(\"-------- ----- -----------%n\");\n for ( String code : asciiMap.keySet() ) {\n List pos = asciiMap.get(code);\n int start = pos.get(0);\n int end = pos.get(1);\n System.out.printf(\"%-8s %2d %s%n\", code, end-start+1, bin.substring(start, end+1));\n }\n\n }\n\n\n private static void display(String ascii) {\n System.out.printf(\"%nDiagram:%n%n\");\n for ( String s : TEST.split(\"\\\\r\\\\n\") ) {\n System.out.println(s);\n }\n }\n\n private static void displayMap(Map> asciiMap) {\n System.out.printf(\"%nDecode:%n%n\");\n\n\n System.out.printf(\"Name Size Start End%n\");\n System.out.printf(\"-------- ----- ----- -----%n\");\n for ( String code : asciiMap.keySet() ) {\n List pos = asciiMap.get(code);\n System.out.printf(\"%-8s %2d %2d %2d%n\", code, pos.get(1)-pos.get(0)+1, pos.get(0), pos.get(1));\n }\n\n }\n\n private static Map> decode(String ascii) {\n Map> map = new LinkedHashMap<>();\n String[] split = TEST.split(\"\\\\r\\\\n\");\n int size = split[0].indexOf(\"+\", 1) - split[0].indexOf(\"+\");\n int length = split[0].length() - 1;\n for ( int i = 1 ; i < split.length ; i += 2 ) {\n int barIndex = 1;\n String test = split[i];\n int next;\n while ( barIndex < length && (next = test.indexOf(\"|\", barIndex)) > 0 ) {\n // List is start and end of code.\n List startEnd = new ArrayList<>();\n startEnd.add((barIndex/size) + (i/2)*(length/size));\n startEnd.add(((next-1)/size) + (i/2)*(length/size));\n String code = test.substring(barIndex, next).replace(\" \", \"\");\n map.put(code, startEnd);\n // Next bar\n barIndex = next + 1;\n }\n }\n\n return map;\n }\n\n private static void validate(String ascii) {\n String[] split = TEST.split(\"\\\\r\\\\n\");\n if ( split.length % 2 != 1 ) {\n throw new RuntimeException(\"ERROR 1: Invalid number of input lines. Line count = \" + split.length);\n }\n int size = 0;\n for ( int i = 0 ; i < split.length ; i++ ) {\n String test = split[i];\n if ( i % 2 == 0 ) {\n // Start with +, an equal number of -, end with +\n if ( ! test.matches(\"^\\\\+([-]+\\\\+)+$\") ) {\n throw new RuntimeException(\"ERROR 2: Improper line format. Line = \" + test);\n }\n if ( size == 0 ) {\n int firstPlus = test.indexOf(\"+\");\n int secondPlus = test.indexOf(\"+\", 1);\n size = secondPlus - firstPlus;\n }\n if ( ((test.length()-1) % size) != 0 ) {\n throw new RuntimeException(\"ERROR 3: Improper line format. Line = \" + test);\n }\n // Equally spaced splits of +, -\n for ( int j = 0 ; j < test.length()-1 ; j += size ) {\n if ( test.charAt(j) != '+' ) {\n throw new RuntimeException(\"ERROR 4: Improper line format. Line = \" + test);\n }\n for ( int k = j+1 ; k < j + size ; k++ ) {\n if ( test.charAt(k) != '-' ) {\n throw new RuntimeException(\"ERROR 5: Improper line format. Line = \" + test);\n }\n }\n }\n }\n else {\n // Vertical bar, followed by optional spaces, followed by name, followed by optional spaces, followed by vdrtical bar\n if ( ! test.matches(\"^\\\\|(\\\\s*[A-Za-z]+\\\\s*\\\\|)+$\") ) {\n throw new RuntimeException(\"ERROR 6: Improper line format. Line = \" + test);\n }\n for ( int j = 0 ; j < test.length()-1 ; j += size ) {\n for ( int k = j+1 ; k < j + size ; k++ ) {\n // Vertical bar only at boundaries\n if ( test.charAt(k) == '|' ) {\n throw new RuntimeException(\"ERROR 7: Improper line format. Line = \" + test);\n }\n }\n }\n\n }\n }\n }\n\n}\n"} {"title": "AVL tree", "language": "Java", "task": "{{wikipedia|AVL tree}}\n\n\n\nIn computer science, an '''AVL tree''' is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; at no time do they differ by more than one because rebalancing is done ensure this is the case. Lookup, insertion, and deletion all take O(log ''n'') time in both the average and worst cases, where n is the number of nodes in the tree prior to the operation. Insertions and deletions may require the tree to be rebalanced by one or more tree rotations. Note the tree of nodes comprise a set, so duplicate node keys are not allowed.\n\nAVL trees are often compared with red-black trees because they support the same set of operations and because red-black trees also take O(log ''n'') time for the basic operations. Because AVL trees are more rigidly balanced, they are faster than red-black trees for lookup-intensive applications. Similar to red-black trees, AVL trees are height-balanced, but in general not weight-balanced nor m-balanced; that is, sibling nodes can have hugely differing numbers of descendants.\n\n\n;Task:\nImplement an AVL tree in the language of choice, and provide at least basic operations.\n\n;Related task\n[[Red_black_tree_sort]]\n\n", "solution": "public class AVLtree {\n\n private Node root;\n\n private static class Node {\n private int key;\n private int balance;\n private int height;\n private Node left;\n private Node right;\n private Node parent;\n\n Node(int key, Node parent) {\n this.key = key;\n this.parent = parent;\n }\n }\n\n public boolean insert(int key) {\n if (root == null) {\n root = new Node(key, null);\n return true;\n }\n\n Node n = root;\n while (true) {\n if (n.key == key)\n return false;\n\n Node parent = n;\n\n boolean goLeft = n.key > key;\n n = goLeft ? n.left : n.right;\n\n if (n == null) {\n if (goLeft) {\n parent.left = new Node(key, parent);\n } else {\n parent.right = new Node(key, parent);\n }\n rebalance(parent);\n break;\n }\n }\n return true;\n }\n\n private void delete(Node node) {\n if (node.left == null && node.right == null) {\n if (node.parent == null) {\n root = null;\n } else {\n Node parent = node.parent;\n if (parent.left == node) {\n parent.left = null;\n } else {\n parent.right = null;\n }\n rebalance(parent);\n }\n return;\n }\n\n if (node.left != null) {\n Node child = node.left;\n while (child.right != null) child = child.right;\n node.key = child.key;\n delete(child);\n } else {\n Node child = node.right;\n while (child.left != null) child = child.left;\n node.key = child.key;\n delete(child);\n }\n }\n\n public void delete(int delKey) {\n if (root == null)\n return;\n\n Node child = root;\n while (child != null) {\n Node node = child;\n child = delKey >= node.key ? node.right : node.left;\n if (delKey == node.key) {\n delete(node);\n return;\n }\n }\n }\n\n private void rebalance(Node n) {\n setBalance(n);\n\n if (n.balance == -2) {\n if (height(n.left.left) >= height(n.left.right))\n n = rotateRight(n);\n else\n n = rotateLeftThenRight(n);\n\n } else if (n.balance == 2) {\n if (height(n.right.right) >= height(n.right.left))\n n = rotateLeft(n);\n else\n n = rotateRightThenLeft(n);\n }\n\n if (n.parent != null) {\n rebalance(n.parent);\n } else {\n root = n;\n }\n }\n\n private Node rotateLeft(Node a) {\n\n Node b = a.right;\n b.parent = a.parent;\n\n a.right = b.left;\n\n if (a.right != null)\n a.right.parent = a;\n\n b.left = a;\n a.parent = b;\n\n if (b.parent != null) {\n if (b.parent.right == a) {\n b.parent.right = b;\n } else {\n b.parent.left = b;\n }\n }\n\n setBalance(a, b);\n\n return b;\n }\n\n private Node rotateRight(Node a) {\n\n Node b = a.left;\n b.parent = a.parent;\n\n a.left = b.right;\n\n if (a.left != null)\n a.left.parent = a;\n\n b.right = a;\n a.parent = b;\n\n if (b.parent != null) {\n if (b.parent.right == a) {\n b.parent.right = b;\n } else {\n b.parent.left = b;\n }\n }\n\n setBalance(a, b);\n\n return b;\n }\n\n private Node rotateLeftThenRight(Node n) {\n n.left = rotateLeft(n.left);\n return rotateRight(n);\n }\n\n private Node rotateRightThenLeft(Node n) {\n n.right = rotateRight(n.right);\n return rotateLeft(n);\n }\n\n private int height(Node n) {\n if (n == null)\n return -1;\n return n.height;\n }\n\n private void setBalance(Node... nodes) {\n for (Node n : nodes) {\n reheight(n);\n n.balance = height(n.right) - height(n.left);\n }\n }\n\n public void printBalance() {\n printBalance(root);\n }\n\n private void printBalance(Node n) {\n if (n != null) {\n printBalance(n.left);\n System.out.printf(\"%s \", n.balance);\n printBalance(n.right);\n }\n }\n\n private void reheight(Node node) {\n if (node != null) {\n node.height = 1 + Math.max(height(node.left), height(node.right));\n }\n }\n\n public static void main(String[] args) {\n AVLtree tree = new AVLtree();\n\n System.out.println(\"Inserting values 1 to 10\");\n for (int i = 1; i < 10; i++)\n tree.insert(i);\n\n System.out.print(\"Printing balance: \");\n tree.printBalance();\n }\n}"} {"title": "Abbreviations, automatic", "language": "Java from D", "task": "The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an\neasy way to add flexibility when specifying or using commands, sub-commands, options, etc.\n\n\n\nIt would make a list of words easier to maintain (as words are added, changed, and/or deleted) if\nthe minimum abbreviation length of that list could be automatically (programmatically) determined.\n\n\nFor this task, use the list (below) of the days-of-the-week names that are expressed in about a hundred languages (note that there is a blank line in the list).\n\nSunday Monday Tuesday Wednesday Thursday Friday Saturday\nSondag Maandag Dinsdag Woensdag Donderdag Vrydag Saterdag\nE_djele E_hene E_marte E_merkure E_enjte E_premte E_shtune\nEhud Segno Maksegno Erob Hamus Arbe Kedame\nAl_Ahad Al_Ithinin Al_Tholatha'a Al_Arbia'a Al_Kamis Al_Gomia'a Al_Sabit\nGuiragui Yergou_shapti Yerek_shapti Tchorek_shapti Hink_shapti Ourpat Shapat\ndomingu llunes martes miercoles xueves vienres sabadu\nBazar_gUnU Birinci_gUn Ckinci_gUn UcUncU_gUn DOrdUncU_gUn Bes,inci_gUn Altonco_gUn\nIgande Astelehen Astearte Asteazken Ostegun Ostiral Larunbat\nRobi_bar Shom_bar Mongal_bar Budhh_bar BRihashpati_bar Shukro_bar Shoni_bar\nNedjelja Ponedeljak Utorak Srijeda Cxetvrtak Petak Subota\nDisul Dilun Dimeurzh Dimerc'her Diriaou Digwener Disadorn\nnedelia ponedelnik vtornik sriada chetvartak petak sabota\nsing_kei_yaht sing_kei_yat sing_kei_yee sing_kei_saam sing_kei_sie sing_kei_ng sing_kei_luk\nDiumenge Dilluns Dimarts Dimecres Dijous Divendres Dissabte\nDzeenkk-eh Dzeehn_kk-ehreh Dzeehn_kk-ehreh_nah_kay_dzeeneh Tah_neesee_dzeehn_neh Deehn_ghee_dzee-neh Tl-oowey_tts-el_dehlee Dzeentt-ahzee\ndy_Sul dy_Lun dy_Meurth dy_Mergher dy_You dy_Gwener dy_Sadorn\nDimanch Lendi Madi Mekredi Jedi Vandredi Samdi\nnedjelja ponedjeljak utorak srijeda cxetvrtak petak subota\nnede^le ponde^li utery str^eda c^tvrtek patek sobota\nSondee Mondee Tiisiday Walansedee TOOsedee Feraadee Satadee\ns0ndag mandag tirsdag onsdag torsdag fredag l0rdag\nzondag maandag dinsdag woensdag donderdag vrijdag zaterdag\nDiman^co Lundo Mardo Merkredo ^Jaudo Vendredo Sabato\npUhapaev esmaspaev teisipaev kolmapaev neljapaev reede laupaev\n\nDiu_prima Diu_sequima Diu_tritima Diu_quartima Diu_quintima Diu_sextima Diu_sabbata\nsunnudagur manadagur tysdaguy mikudagur hosdagur friggjadagur leygardagur\nYek_Sham'beh Do_Sham'beh Seh_Sham'beh Cha'har_Sham'beh Panj_Sham'beh Jom'eh Sham'beh\nsunnuntai maanantai tiistai keskiviiko torsktai perjantai lauantai\ndimanche lundi mardi mercredi jeudi vendredi samedi\nSnein Moandei Tiisdei Woansdei Tonersdei Freed Sneon\nDomingo Segunda_feira Martes Mercores Joves Venres Sabado\nk'vira orshabati samshabati otkhshabati khutshabati p'arask'evi shabati\nSonntag Montag Dienstag Mittwoch Donnerstag Freitag Samstag\nKiriaki' Defte'ra Tri'ti Teta'rti Pe'mpti Paraskebi' Sa'bato\nravivaar somvaar mangalvaar budhvaar guruvaar shukravaar shanivaar\npopule po`akahi po`alua po`akolu po`aha po`alima po`aono\nYom_rishon Yom_sheni Yom_shlishi Yom_revi'i Yom_chamishi Yom_shishi Shabat\nravivara somavar mangalavar budhavara brahaspativar shukravara shanivar\nvasarnap hetfo kedd szerda csutortok pentek szombat\nSunnudagur Manudagur +ridjudagur Midvikudagar Fimmtudagur FOstudagur Laugardagur\nsundio lundio mardio merkurdio jovdio venerdio saturdio\nMinggu Senin Selasa Rabu Kamis Jumat Sabtu\nDominica Lunedi Martedi Mercuridi Jovedi Venerdi Sabbato\nDe_Domhnaigh De_Luain De_Mairt De_Ceadaoin De_ardaoin De_hAoine De_Sathairn\ndomenica lunedi martedi mercoledi giovedi venerdi sabato\nNichiyou_bi Getzuyou_bi Kayou_bi Suiyou_bi Mokuyou_bi Kin'you_bi Doyou_bi\nIl-yo-il Wol-yo-il Hwa-yo-il Su-yo-il Mok-yo-il Kum-yo-il To-yo-il\nDies_Dominica Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni\nsve-tdien pirmdien otrdien tresvdien ceturtdien piektdien sestdien\nSekmadienis Pirmadienis Antradienis Trec^iadienis Ketvirtadienis Penktadienis S^es^tadienis\nWangu Kazooba Walumbe Mukasa Kiwanuka Nnagawonye Wamunyi\nxing-_qi-_ri xing-_qi-_yi-. xing-_qi-_er xing-_qi-_san-. xing-_qi-_si xing-_qi-_wuv. xing-_qi-_liu\nJedoonee Jelune Jemayrt Jecrean Jardaim Jeheiney Jesam\nJabot Manre Juje Wonje Taije Balaire Jarere\ngeminrongo minomishi martes mierkoles misheushi bernashi mishabaro\nAhad Isnin Selasa Rabu Khamis Jumaat Sabtu\nsphndag mandag tirsdag onsdag torsdag fredag lphrdag\nlo_dimenge lo_diluns lo_dimarc lo_dimercres lo_dijous lo_divendres lo_dissabte\ndjadomingo djaluna djamars djarason djaweps djabierna djasabra\nNiedziela Poniedzial/ek Wtorek S,roda Czwartek Pia,tek Sobota\nDomingo segunda-feire terca-feire quarta-feire quinta-feire sexta-feira sabado\nDomingo Lunes martes Miercoles Jueves Viernes Sabado\nDuminica Luni Mart'i Miercuri Joi Vineri Sambata\nvoskresenie ponedelnik vtornik sreda chetverg pyatnitsa subbota\nSunday Di-luain Di-mairt Di-ciadain Di-ardaoin Di-haoine Di-sathurne\nnedjelja ponedjeljak utorak sreda cxetvrtak petak subota\nSontaha Mmantaha Labobedi Laboraro Labone Labohlano Moqebelo\nIridha- Sandhudha- Anga.haruwa-dha- Badha-dha- Brahaspa.thindha- Sikura-dha- Sena.sura-dha-\nnedel^a pondelok utorok streda s^tvrtok piatok sobota\nNedelja Ponedeljek Torek Sreda Cxetrtek Petek Sobota\ndomingo lunes martes miercoles jueves viernes sabado\nsonde mundey tude-wroko dride-wroko fode-wroko freyda Saturday\nJumapili Jumatatu Jumanne Jumatano Alhamisi Ijumaa Jumamosi\nsondag mandag tisdag onsdag torsdag fredag lordag\nLinggo Lunes Martes Miyerkoles Huwebes Biyernes Sabado\nLe-pai-jit Pai-it Pai-ji Pai-san Pai-si Pai-gO. Pai-lak\nwan-ar-tit wan-tjan wan-ang-kaan wan-phoet wan-pha-ru-hat-sa-boh-die wan-sook wan-sao\nTshipi Mosupologo Labobedi Laboraro Labone Labotlhano Matlhatso\nPazar Pazartesi Sali Car,samba Per,sembe Cuma Cumartesi\nnedilya ponedilok vivtorok sereda chetver pyatnytsya subota\nChu?_Nha.t Thu*_Hai Thu*_Ba Thu*_Tu* Thu*_Na'm Thu*_Sau Thu*_Ba?y\ndydd_Sul dyds_Llun dydd_Mawrth dyds_Mercher dydd_Iau dydd_Gwener dyds_Sadwrn\nDibeer Altine Talaata Allarba Al_xebes Aljuma Gaaw\niCawa uMvulo uLwesibini uLwesithathu uLuwesine uLwesihlanu uMgqibelo\nzuntik montik dinstik mitvokh donershtik fraytik shabes\niSonto uMsombuluko uLwesibili uLwesithathu uLwesine uLwesihlanu uMgqibelo\nDies_Dominica Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni\nBazar_gUnU Bazar_aertaesi Caers,aenbae_axs,amo Caers,aenbae_gUnU CUmae_axs,amo CUmae_gUnU CUmae_Senbae\nSun Moon Mars Mercury Jove Venus Saturn\nzondag maandag dinsdag woensdag donderdag vrijdag zaterdag\nKoseEraa GyoOraa BenEraa Kuoraa YOwaaraa FeEraa Memenaa\nSonntag Montag Dienstag Mittwoch Donnerstag Freitag Sonnabend\nDomingo Luns Terza_feira Corta_feira Xoves Venres Sabado\nDies_Solis Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Sabbatum\nxing-_qi-_tian xing-_qi-_yi-. xing-_qi-_er xing-_qi-_san-. xing-_qi-_si xing-_qi-_wuv. xing-_qi-_liu\ndjadomingu djaluna djamars djarason djaweps djabierne djasabra\nKillachau Atichau Quoyllurchau Illapachau Chaskachau Kuychichau Intichau\n\n''Caveat: The list (above) most surely contains errors (or, at the least, differences) of what the actual (or true) names for the days-of-the-week.''\n\n\nTo make this Rosetta Code task page as small as possible, if processing the complete list, read the days-of-the-week from a file (that is created from the above list).\n\n\nNotes concerning the above list of words\n::* each line has a list of days-of-the-week for a language, separated by at least one blank\n::* the words on each line happen to be in order, from Sunday --> Saturday\n::* most lines have words in mixed case and some have all manner of accented words and other characters\n::* some words were translated to the nearest character that was available to ''code page'' '''437'''\n::* the characters in the words are not restricted except that they may not have imbedded blanks\n::* for this example, the use of an underscore ('''_''') was used to indicate a blank in a word\n\n\n;Task:\n::* The list of words (days of the week) needn't be verified/validated.\n::* Write a function to find the (numeric) minimum length abbreviation for each line that would make abbreviations unique.\n::* A blank line (or a null line) should return a null string.\n::* Process and show the output for at least the first '''five''' lines of the file.\n::* Show all output here.\n\n\n", "solution": "import java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class Abbreviations {\n public static void main(String[] args) throws IOException {\n Path path = Paths.get(\"days_of_week.txt\");\n List readAllLines = Files.readAllLines(path);\n for (int i = 0; i < readAllLines.size(); i++) {\n String line = readAllLines.get(i);\n if (line.length() == 0) continue;\n\n String[] days = line.split(\" \");\n if (days.length != 7) throw new RuntimeException(\"There aren't 7 days on line \" + (i + 1));\n\n Map temp = new HashMap<>();\n for (String day : days) {\n Integer count = temp.getOrDefault(day, 0);\n temp.put(day, count + 1);\n }\n if (temp.size() < 7) {\n System.out.print(\" \u221e \");\n System.out.println(line);\n continue;\n }\n\n int len = 1;\n while (true) {\n temp.clear();\n for (String day : days) {\n String sd;\n if (len >= day.length()) {\n sd = day;\n } else {\n sd = day.substring(0, len);\n }\n Integer count = temp.getOrDefault(sd, 0);\n temp.put(sd, count + 1);\n }\n if (temp.size() == 7) {\n System.out.printf(\"%2d %s\\n\", len, line);\n break;\n }\n len++;\n }\n }\n }\n}"} {"title": "Abbreviations, easy", "language": "Java", "task": "This task is an easier (to code) variant of the Rosetta Code task: [[Abbreviations, simple]].\n\n\nFor this task, the following ''command table'' will be used:\n Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy\n COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO\n MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT\n READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT\n RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up\n\n\n\n\nNotes concerning the above ''command table'':\n::* it can be thought of as one long literal string (with blanks at end-of-lines)\n::* it may have superfluous blanks\n::* it may be in any case (lower/upper/mixed)\n::* the order of the words in the ''command table'' must be preserved as shown\n::* the user input(s) may be in any case (upper/lower/mixed)\n::* commands will be restricted to the Latin alphabet (A --> Z, a --> z)\n::* A valid abbreviation is a word that has:\n:::* at least the minimum length of the number of capital letters of the word in the ''command table''\n:::* compares equal (regardless of case) to the leading characters of the word in the ''command table''\n:::* a length not longer than the word in the ''command table''\n::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTer'''\n::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTer'''\n::::* The number of capital letters in '''ALTer''' indicates that any abbreviation for '''ALTer''' must be at least three letters\n::::* Any word longer than five characters can't be an abbreviation for '''ALTer'''\n::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''Overlay'''\n::* if there isn't any lowercase letters in the word in the ''command table'', then there isn't an abbreviation permitted\n\n\n\n;Task:\n::* The command table needn't be verified/validated.\n::* Write a function to validate if the user \"words\" (given as input) are valid (in the ''command table'').\n::* If the word is valid, then return the full uppercase version of that \"word\".\n::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters).\n::* A blank input (or a null input) should return a null string.\n::* Show all output here.\n\n\n;An example test case to be used for this task:\nFor a user string of:\n riG rePEAT copies put mo rest types fup. 6 poweRin\nthe computer program should return the string:\n RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT\n\n\n", "solution": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class AbbreviationsEasy {\n private static final Scanner input = new Scanner(System.in);\n private static final String COMMAND_TABLE\n = \" Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy\\n\" +\n \" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\\n\" +\n \" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\\n\" +\n \" Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO\\n\" +\n \" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT\\n\" +\n \" READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT\\n\" +\n \" RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up\";\n\n public static void main(String[] args) {\n String[] cmdTableArr = COMMAND_TABLE.split(\"\\\\s+\");\n Map cmd_table = new HashMap();\n\n for (String word : cmdTableArr) { //Populate words and number of caps\n cmd_table.put(word, countCaps(word));\n }\n\n System.out.print(\"Please enter your command to verify: \");\n String userInput = input.nextLine();\n String[] user_input = userInput.split(\"\\\\s+\");\n\n for (String s : user_input) {\n boolean match = false; //resets each outer loop\n for (String cmd : cmd_table.keySet()) {\n if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {\n String temp = cmd.toUpperCase();\n if (temp.startsWith(s.toUpperCase())) {\n System.out.print(temp + \" \");\n match = true;\n }\n }\n }\n if (!match) { //no match, print error msg\n System.out.print(\"*error* \");\n }\n }\n }\n\n private static int countCaps(String word) {\n int numCaps = 0;\n for (int i = 0; i < word.length(); i++) {\n if (Character.isUpperCase(word.charAt(i))) {\n numCaps++;\n }\n }\n return numCaps;\n }\n}\n"} {"title": "Abbreviations, simple", "language": "Java from C++", "task": "The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an \neasy way to add flexibility when specifying or using commands, sub-commands, options, etc.\n\n\n\nFor this task, the following ''command table'' will be used:\n add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3\n compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate\n 3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2\n forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load\n locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2\n msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3\n refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left\n 2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1\n\n\n\n\nNotes concerning the above ''command table'':\n::* it can be thought of as one long literal string (with blanks at end-of-lines)\n::* it may have superfluous blanks\n::* it may be in any case (lower/upper/mixed)\n::* the order of the words in the ''command table'' must be preserved as shown\n::* the user input(s) may be in any case (upper/lower/mixed)\n::* commands will be restricted to the Latin alphabet (A --> Z, a --> z)\n::* a command is followed by an optional number, which indicates the minimum abbreviation\n::* A valid abbreviation is a word that has:\n:::* at least the minimum length of the word's minimum number in the ''command table''\n:::* compares equal (regardless of case) to the leading characters of the word in the ''command table''\n:::* a length not longer than the word in the ''command table''\n::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTER 3'''\n::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTER 3'''\n::::* The '''3''' indicates that any abbreviation for '''ALTER''' must be at least three characters\n::::* Any word longer than five characters can't be an abbreviation for '''ALTER'''\n::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''overlay 1'''\n::* if there isn't a number after the command, then there isn't an abbreviation permitted\n\n\n\n;Task:\n::* The command table needn't be verified/validated.\n::* Write a function to validate if the user \"words\" (given as input) are valid (in the ''command table'').\n::* If the word is valid, then return the full uppercase version of that \"word\".\n::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters).\n::* A blank input (or a null input) should return a null string.\n::* Show all output here.\n\n\n;An example test case to be used for this task:\nFor a user string of:\n riG rePEAT copies put mo rest types fup. 6 poweRin\nthe computer program should return the string:\n RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT\n\n\n", "solution": "import java.util.*;\n\npublic class Abbreviations {\n public static void main(String[] args) {\n CommandList commands = new CommandList(commandTable);\n String input = \"riG rePEAT copies put mo rest types fup. 6 poweRin\";\n System.out.println(\" input: \" + input);\n System.out.println(\"output: \" + test(commands, input));\n }\n\n private static String test(CommandList commands, String input) {\n StringBuilder output = new StringBuilder();\n Scanner scanner = new Scanner(input);\n while (scanner.hasNext()) {\n String word = scanner.next();\n if (output.length() > 0)\n output.append(' ');\n Command cmd = commands.findCommand(word);\n if (cmd != null)\n output.append(cmd.cmd);\n else\n output.append(\"*error*\");\n }\n return output.toString();\n }\n\n private static String commandTable =\n \"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 \" +\n \"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate \" +\n \"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n \"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load \" +\n \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 \" +\n \"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 \" +\n \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n \"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1\";\n\n private static class Command {\n private Command(String cmd, int minLength) {\n this.cmd = cmd;\n this.minLength = minLength;\n }\n private boolean match(String str) {\n int olen = str.length();\n return olen >= minLength && olen <= cmd.length()\n && cmd.regionMatches(true, 0, str, 0, olen);\n }\n private String cmd;\n private int minLength;\n }\n\n private static Integer parseInteger(String word) {\n try {\n return Integer.valueOf(word);\n } catch (NumberFormatException ex) {\n return null;\n }\n }\n\n private static class CommandList {\n private CommandList(String table) {\n Scanner scanner = new Scanner(table);\n List words = new ArrayList<>();\n while (scanner.hasNext()) {\n String word = scanner.next();\n words.add(word.toUpperCase());\n }\n for (int i = 0, n = words.size(); i < n; ++i) {\n String word = words.get(i);\n // if there's an integer following this word, it specifies the minimum\n // length for the command, otherwise the minimum length is the length\n // of the command string\n int len = word.length();\n if (i + 1 < n) {\n Integer number = parseInteger(words.get(i + 1));\n if (number != null) {\n len = number.intValue();\n ++i;\n }\n }\n commands.add(new Command(word, len));\n }\n }\n private Command findCommand(String word) {\n for (Command command : commands) {\n if (command.match(word))\n return command;\n }\n return null;\n }\n private List commands = new ArrayList<>();\n }\n}"} {"title": "Abelian sandpile model", "language": "Java", "task": "{{wikipedia|Abelian sandpile model}}\nImplement the '''Abelian sandpile model''' also known as '''Bak-Tang-Wiesenfeld model'''. Its history, mathematical definition and properties can be found under its wikipedia article.\n\nThe task requires the creation of a 2D grid of arbitrary size on which \"piles of sand\" can be placed. Any \"pile\" that has 4 or more sand particles on it ''collapses'', resulting in '''four particles being subtracted from the pile''' and '''distributed among its neighbors.'''\n\nIt is recommended to display the output in some kind of image format, as terminal emulators are usually too small to display images larger than a few dozen characters tall. As an example of how to accomplish this, see the Bitmap/Write a PPM file task.\nExamples up to 2^30, wow!\njavascript running on web\n'''Examples:'''\n\n\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 1 0 0\n0 0 4 0 0 -> 0 1 0 1 0\n0 0 0 0 0 0 0 1 0 0\n0 0 0 0 0 0 0 0 0 0\n\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 1 0 0\n0 0 6 0 0 -> 0 1 2 1 0\n0 0 0 0 0 0 0 1 0 0\n0 0 0 0 0 0 0 0 0 0\n\n0 0 0 0 0 0 0 1 0 0\n0 0 0 0 0 0 2 1 2 0\n0 0 16 0 0 -> 1 1 0 1 1\n0 0 0 0 0 0 2 1 2 0\n0 0 0 0 0 0 0 1 0 0\n\n", "solution": "import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\n\npublic class AbelianSandpile {\n public static void main(String[] args) {\n SwingUtilities.invokeLater(new Runnable() {\n public void run() {\n Frame frame = new Frame();\n frame.setVisible(true);\n }\n });\n }\n\n private static class Frame extends JFrame {\n private Frame() {\n super(\"Abelian Sandpile Model\");\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n Container contentPane = getContentPane();\n JPanel controlPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));\n JButton start = new JButton(\"Restart Simulation\");\n start.addActionListener(e -> restartSimulation());\n JButton stop = new JButton(\"Stop Simulation\");\n stop.addActionListener(e -> stopSimulation());\n controlPanel.add(start);\n controlPanel.add(stop);\n contentPane.add(controlPanel, BorderLayout.NORTH);\n contentPane.add(canvas = new Canvas(), BorderLayout.CENTER);\n timer = new Timer(100, e -> canvas.runAndDraw());\n timer.start();\n pack();\n }\n\n private void restartSimulation() {\n timer.stop();\n canvas.initGrid();\n timer.start();\n }\n\n private void stopSimulation() {\n timer.stop();\n }\n\n private Timer timer;\n private Canvas canvas;\n }\n\n private static class Canvas extends JComponent {\n private Canvas() {\n setBorder(BorderFactory.createEtchedBorder());\n setPreferredSize(new Dimension(600, 600));\n }\n\n public void paintComponent(Graphics g) {\n int width = getWidth();\n int height = getHeight();\n g.setColor(Color.WHITE);\n g.fillRect(0, 0, width, height);\n int cellWidth = width/GRID_LENGTH;\n int cellHeight = height/GRID_LENGTH;\n for (int i = 0; i < GRID_LENGTH; ++i) {\n for (int j = 0; j < GRID_LENGTH; ++j) {\n if (grid[i][j] > 0) {\n g.setColor(COLORS[grid[i][j]]);\n g.fillRect(i * cellWidth, j * cellHeight, cellWidth, cellHeight);\n }\n }\n }\n }\n\n private void initGrid() {\n for (int i = 0; i < GRID_LENGTH; ++i) {\n for (int j = 0; j < GRID_LENGTH; ++j) {\n grid[i][j] = 0;\n }\n }\n }\n\n private void runAndDraw() {\n for (int i = 0; i < 100; ++i)\n addSand(GRID_LENGTH/2, GRID_LENGTH/2);\n repaint();\n }\n\n private void addSand(int i, int j) {\n int grains = grid[i][j];\n if (grains < 3) {\n grid[i][j]++;\n }\n else {\n grid[i][j] = grains - 3;\n if (i > 0)\n addSand(i - 1, j);\n if (i < GRID_LENGTH - 1)\n addSand(i + 1, j);\n if (j > 0)\n addSand(i, j - 1);\n if (j < GRID_LENGTH - 1)\n addSand(i, j + 1);\n }\n }\n\n private int[][] grid = new int[GRID_LENGTH][GRID_LENGTH];\n }\n\n private static final Color[] COLORS = {\n Color.WHITE,\n new Color(0x00, 0xbf, 0xff),\n new Color(0xff, 0xd7, 0x00),\n new Color(0xb0, 0x30, 0x60)\n };\n private static final int GRID_LENGTH = 300;\n}"} {"title": "Abundant odd numbers", "language": "Java", "task": "An Abundant number is a number '''n''' for which the ''sum of divisors'' '''s(n) > 2n''',\nor, equivalently, the ''sum of proper divisors'' (or aliquot sum) '''s(n) > n'''.\n\n\n;E.G.:\n'''12''' is abundant, it has the proper divisors '''1,2,3,4 & 6''' which sum to '''16''' ( > '''12''' or '''n'''); \n or alternately, has the sigma sum of '''1,2,3,4,6 & 12''' which sum to '''28''' ( > '''24''' or '''2n''').\n\n\nAbundant numbers are common, though '''even''' abundant numbers seem to be much more common than '''odd''' abundant numbers. \n\nTo make things more interesting, this task is specifically about finding ''odd abundant numbers''.\n\n\n;Task\n*Find and display here: at least the first 25 abundant odd numbers and either their proper divisor sum or sigma sum.\n*Find and display here: the one thousandth abundant odd number and either its proper divisor sum or sigma sum.\n*Find and display here: the first abundant odd number greater than one billion (109) and either its proper divisor sum or sigma sum.\n\n\n;References:\n:* OEIS:A005231: Odd abundant numbers (odd numbers n whose sum of divisors exceeds 2n)\n:* American Journal of Mathematics, Vol. 35, No. 4 (Oct., 1913), pp. 413-422 - Finiteness of the Odd Perfect and Primitive Abundant Numbers with n Distinct Prime Factors (LE Dickson)\n\n", "solution": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class AbundantOddNumbers {\n private static List list = new ArrayList<>();\n private static List result = new ArrayList<>();\n\n public static void main(String[] args) {\n System.out.println(\"First 25: \");\n abundantOdd(1,100000, 25, false);\n\n System.out.println(\"\\n\\nThousandth: \");\n abundantOdd(1,2500000, 1000, true);\n\n System.out.println(\"\\n\\nFirst over 1bn:\"); \n abundantOdd(1000000001, 2147483647, 1, false);\n }\n private static void abundantOdd(int start, int finish, int listSize, boolean printOne) {\n for (int oddNum = start; oddNum < finish; oddNum += 2) {\n list.clear();\n for (int toDivide = 1; toDivide < oddNum; toDivide+=2) {\n if (oddNum % toDivide == 0)\n list.add(toDivide);\n }\n if (sumList(list) > oddNum) {\n if(!printOne)\n System.out.printf(\"%5d <= %5d \\n\",oddNum, sumList(list) );\n result.add(oddNum);\n }\n if(printOne && result.size() >= listSize)\n System.out.printf(\"%5d <= %5d \\n\",oddNum, sumList(list) );\n\n if(result.size() >= listSize) break;\n }\n }\n private static int sumList(List list) {\n int sum = 0;\n for (int i = 0; i < list.size(); i++) {\n String temp = list.get(i).toString();\n sum += Integer.parseInt(temp);\n }\n return sum;\n }\n}\n\n"} {"title": "Accumulator factory", "language": "Java", "task": "{{requires|Mutable State}}\n\nA problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).\n\n\n;Rules:\nThe detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in ''small italic text'').\n:Before you submit an example, make sure the function\n\n:# Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).Although these exact function and parameter names need not be used\n:# Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) ''(i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)''\n:# Generates functions that return the sum of every number ever passed to them, not just the most recent. ''(This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)''\n:# Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. ''(Follow your language's conventions here.)''\n:# Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. ''(No global variables or other such things.)''\n: E.g. if after the example, you added the following code (in a made-up language) ''where the factory function is called foo'':\n:: x = foo(1); \nx(5); \nfoo(3);\nprint x(2.3);\n: It should print 8.3. ''(There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)''\n\n\n;Task:\nCreate a function that implements the described rules. \n\n\nIt need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.\n\nWhere it is not possible to hold exactly to the constraints above, describe the deviations.\n\n", "solution": "Java has no first-class functions, so an accumulator can't use the x(5) syntax. The standard syntactic workaround is to use a standard method name, like x.call(5) or x.apply(5). This is a deviation from task.\n\nOur accumulator sums with long integers as far as possible before switching to floats. This requires the use of the Number class. The code needs Java 5 to autobox primitive values 1 or 2.3 into instances of Number. The apply method is ready to implement interface UnaryOperator in Java 8.\n\n"} {"title": "Accumulator factory", "language": "Java 5 and up", "task": "{{requires|Mutable State}}\n\nA problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).\n\n\n;Rules:\nThe detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in ''small italic text'').\n:Before you submit an example, make sure the function\n\n:# Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).Although these exact function and parameter names need not be used\n:# Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) ''(i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)''\n:# Generates functions that return the sum of every number ever passed to them, not just the most recent. ''(This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)''\n:# Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. ''(Follow your language's conventions here.)''\n:# Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. ''(No global variables or other such things.)''\n: E.g. if after the example, you added the following code (in a made-up language) ''where the factory function is called foo'':\n:: x = foo(1); \nx(5); \nfoo(3);\nprint x(2.3);\n: It should print 8.3. ''(There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)''\n\n\n;Task:\nCreate a function that implements the described rules. \n\n\nIt need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.\n\nWhere it is not possible to hold exactly to the constraints above, describe the deviations.\n\n", "solution": "public class Accumulator\n //implements java.util.function.UnaryOperator // Java 8\n{\n private Number sum;\n\n public Accumulator(Number sum0) {\n\tsum = sum0;\n }\n\n public Number apply(Number n) {\n\t// Acts like sum += n, but chooses long or double.\n\t// Converts weird types (like BigInteger) to double.\n\treturn (longable(sum) && longable(n)) ?\n\t (sum = sum.longValue() + n.longValue()) :\n\t (sum = sum.doubleValue() + n.doubleValue());\n }\n\n private static boolean longable(Number n) {\n\treturn n instanceof Byte || n instanceof Short ||\n\t n instanceof Integer || n instanceof Long;\n }\n\n public static void main(String[] args) {\n\tAccumulator x = new Accumulator(1);\n\tx.apply(5);\n\tnew Accumulator(3);\n\tSystem.out.println(x.apply(2.3));\n }\n}\n"} {"title": "Accumulator factory", "language": "Java 8 and up", "task": "{{requires|Mutable State}}\n\nA problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).\n\n\n;Rules:\nThe detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in ''small italic text'').\n:Before you submit an example, make sure the function\n\n:# Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).Although these exact function and parameter names need not be used\n:# Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) ''(i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)''\n:# Generates functions that return the sum of every number ever passed to them, not just the most recent. ''(This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)''\n:# Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. ''(Follow your language's conventions here.)''\n:# Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. ''(No global variables or other such things.)''\n: E.g. if after the example, you added the following code (in a made-up language) ''where the factory function is called foo'':\n:: x = foo(1); \nx(5); \nfoo(3);\nprint x(2.3);\n: It should print 8.3. ''(There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)''\n\n\n;Task:\nCreate a function that implements the described rules. \n\n\nIt need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.\n\nWhere it is not possible to hold exactly to the constraints above, describe the deviations.\n\n", "solution": "import java.util.function.UnaryOperator;\n\npublic class AccumulatorFactory {\n\n public static UnaryOperator accumulator(Number sum0) {\n\t// Allows sum[0] = ... inside lambda.\n\tNumber[] sum = { sum0 };\n\n\t// Acts like n -> sum[0] += n, but chooses long or double.\n\t// Converts weird types (like BigInteger) to double.\n\treturn n -> (longable(sum[0]) && longable(n)) ?\n\t (sum[0] = sum[0].longValue() + n.longValue()) :\n\t (sum[0] = sum[0].doubleValue() + n.doubleValue());\n }\n\n private static boolean longable(Number n) {\n\treturn n instanceof Byte || n instanceof Short ||\n\t n instanceof Integer || n instanceof Long;\n }\n\n public static void main(String[] args) {\n\tUnaryOperator x = accumulator(1);\n\tx.apply(5);\n\taccumulator(3);\n\tSystem.out.println(x.apply(2.3));\n }\n}"} {"title": "Aliquot sequence classifications", "language": "Java", "task": "An aliquot sequence of a positive integer K is defined recursively as the first member\nbeing K and subsequent members being the sum of the [[Proper divisors]] of the previous term.\n\n:* If the terms eventually reach 0 then the series for K is said to '''terminate'''.\n\n:There are several classifications for non termination:\n:* If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called '''perfect'''.\n:* If the third term ''would'' be repeating K then the sequence repeats with period 2 and K is called '''amicable'''.\n:* If the Nth term ''would'' be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called '''sociable'''.\n:Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions...\n:* Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called '''aspiring'''.\n:* K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called '''cyclic'''.\n\n:And finally:\n:* Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called '''non-terminating'''. For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating '''16''' terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328. \n\n\n;Task:\n# Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above.\n# Use it to display the classification and sequences of the numbers one to ten inclusive.\n# Use it to show the classification and sequences of the following integers, in order:\n:: 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080.\n\nShow all output on this page.\n\n\n;Related tasks:\n* [[Abundant, deficient and perfect number classifications]]. (Classifications from only the first two members of the whole sequence).\n* [[Proper divisors]]\n* [[Amicable pairs]]\n\n", "solution": "Translation of [[Aliquot_sequence_classifications#Python|Python]] via [[Aliquot_sequence_classifications#D|D]]\n"} {"title": "Aliquot sequence classifications", "language": "Java 8", "task": "An aliquot sequence of a positive integer K is defined recursively as the first member\nbeing K and subsequent members being the sum of the [[Proper divisors]] of the previous term.\n\n:* If the terms eventually reach 0 then the series for K is said to '''terminate'''.\n\n:There are several classifications for non termination:\n:* If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called '''perfect'''.\n:* If the third term ''would'' be repeating K then the sequence repeats with period 2 and K is called '''amicable'''.\n:* If the Nth term ''would'' be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called '''sociable'''.\n:Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions...\n:* Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called '''aspiring'''.\n:* K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called '''cyclic'''.\n\n:And finally:\n:* Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called '''non-terminating'''. For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating '''16''' terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328. \n\n\n;Task:\n# Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above.\n# Use it to display the classification and sequences of the numbers one to ten inclusive.\n# Use it to show the classification and sequences of the following integers, in order:\n:: 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080.\n\nShow all output on this page.\n\n\n;Related tasks:\n* [[Abundant, deficient and perfect number classifications]]. (Classifications from only the first two members of the whole sequence).\n* [[Proper divisors]]\n* [[Amicable pairs]]\n\n", "solution": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.LongStream;\n\npublic class AliquotSequenceClassifications {\n\n private static Long properDivsSum(long n) {\n return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum();\n }\n\n static boolean aliquot(long n, int maxLen, long maxTerm) {\n List s = new ArrayList<>(maxLen);\n s.add(n);\n long newN = n;\n\n while (s.size() <= maxLen && newN < maxTerm) {\n\n newN = properDivsSum(s.get(s.size() - 1));\n\n if (s.contains(newN)) {\n\n if (s.get(0) == newN) {\n\n switch (s.size()) {\n case 1:\n return report(\"Perfect\", s);\n case 2:\n return report(\"Amicable\", s);\n default:\n return report(\"Sociable of length \" + s.size(), s);\n }\n\n } else if (s.get(s.size() - 1) == newN) {\n return report(\"Aspiring\", s);\n\n } else\n return report(\"Cyclic back to \" + newN, s);\n\n } else {\n s.add(newN);\n if (newN == 0)\n return report(\"Terminating\", s);\n }\n }\n\n return report(\"Non-terminating\", s);\n }\n\n static boolean report(String msg, List result) {\n System.out.println(msg + \": \" + result);\n return false;\n }\n\n public static void main(String[] args) {\n long[] arr = {\n 11, 12, 28, 496, 220, 1184, 12496, 1264460,\n 790, 909, 562, 1064, 1488};\n\n LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47));\n System.out.println();\n Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47));\n }\n}"} {"title": "Anagrams/Deranged anagrams", "language": "Java 8", "task": "Two or more words are said to be anagrams if they have the same characters, but in a different order. \n\nBy analogy with derangements we define a ''deranged anagram'' as two words with the same characters, but in which the same character does ''not'' appear in the same position in both words.\n\n;Task\n\nUse the word list at unixdict to find and display the longest deranged anagram. \n\n\n;Related\n* [[Permutations/Derangements]]\n* Best shuffle\n\n{{Related tasks/Word plays}}\n\n\n\n", "solution": "import java.io.File;\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n \npublic class DerangedAnagrams {\n \n public static void main(String[] args) throws IOException {\n List words = Files.readAllLines(new File(\"unixdict.txt\").toPath());\n printLongestDerangedAnagram(words);\n }\n \n private static void printLongestDerangedAnagram(List words) {\n words.sort(Comparator.comparingInt(String::length).reversed().thenComparing(String::toString));\n\n Map> map = new HashMap<>();\n for (String word : words) {\n char[] chars = word.toCharArray();\n Arrays.sort(chars);\n String key = String.valueOf(chars);\n\n List anagrams = map.computeIfAbsent(key, k -> new ArrayList<>());\n for (String anagram : anagrams) {\n if (isDeranged(word, anagram)) {\n System.out.printf(\"%s %s%n\", anagram, word);\n return;\n }\n }\n anagrams.add(word);\n }\n System.out.println(\"no result\");\n }\n\n private static boolean isDeranged(String word1, String word2) {\n for (int i = 0; i < word1.length(); i++) {\n if (word1.charAt(i) == word2.charAt(i)) {\n return false;\n }\n }\n return true;\n }\n}"} {"title": "Angle difference between two bearings", "language": "Java from C++", "task": "Finding the angle between two bearings is often confusing.[https://stackoverflow.com/questions/16180595/find-the-angle-between-two-bearings]\n\n\n;Task:\nFind the angle which is the result of the subtraction '''b2 - b1''', where '''b1''' and '''b2''' are the bearings. \n\nInput bearings are expressed in the range '''-180''' to '''+180''' degrees. \nThe result is also expressed in the range '''-180''' to '''+180''' degrees. \n\n\nCompute the angle for the following pairs:\n* 20 degrees ('''b1''') and 45 degrees ('''b2''')\n* -45 and 45\n* -85 and 90\n* -95 and 90\n* -45 and 125\n* -45 and 145\n* 29.4803 and -88.6381\n* -78.3251 and -159.036\n\n\n;Optional extra: \nAllow the input bearings to be any (finite) value. \n\n\n;Test cases:\n* -70099.74233810938 and 29840.67437876723\n* -165313.6666297357 and 33693.9894517456\n* 1174.8380510598456 and -154146.66490124757\n* 60175.77306795546 and 42213.07192354373\n\n", "solution": "public class AngleDifference {\n\n public static double getDifference(double b1, double b2) {\n double r = (b2 - b1) % 360.0;\n if (r < -180.0)\n r += 360.0;\n if (r >= 180.0)\n r -= 360.0;\n return r;\n }\n\n public static void main(String[] args) {\n System.out.println(\"Input in -180 to +180 range\");\n System.out.println(getDifference(20.0, 45.0));\n System.out.println(getDifference(-45.0, 45.0));\n System.out.println(getDifference(-85.0, 90.0));\n System.out.println(getDifference(-95.0, 90.0));\n System.out.println(getDifference(-45.0, 125.0));\n System.out.println(getDifference(-45.0, 145.0));\n System.out.println(getDifference(-45.0, 125.0));\n System.out.println(getDifference(-45.0, 145.0));\n System.out.println(getDifference(29.4803, -88.6381));\n System.out.println(getDifference(-78.3251, -159.036));\n\n System.out.println(\"Input in wider range\");\n System.out.println(getDifference(-70099.74233810938, 29840.67437876723));\n System.out.println(getDifference(-165313.6666297357, 33693.9894517456));\n System.out.println(getDifference(1174.8380510598456, -154146.66490124757));\n System.out.println(getDifference(60175.77306795546, 42213.07192354373));\n }\n}"} {"title": "Anti-primes", "language": "Java from Go", "task": "The anti-primes \n(or highly composite numbers, sequence A002182 in the OEIS) \nare the natural numbers with more factors than any smaller than itself.\n\n\n;Task:\nGenerate and show here, the first twenty anti-primes.\n\n\n;Related tasks:\n:* [[Factors of an integer]]\n:* [[Sieve of Eratosthenes]]\n\n", "solution": "public class Antiprime {\n\n static int countDivisors(int n) {\n if (n < 2) return 1;\n int count = 2; // 1 and n\n for (int i = 2; i <= n/2; ++i) {\n if (n%i == 0) ++count;\n }\n return count;\n }\n\n public static void main(String[] args) {\n int maxDiv = 0, count = 0;\n System.out.println(\"The first 20 anti-primes are:\");\n for (int n = 1; count < 20; ++n) {\n int d = countDivisors(n);\n if (d > maxDiv) {\n System.out.printf(\"%d \", n);\n maxDiv = d;\n count++;\n }\n }\n System.out.println();\n }\n}"} {"title": "Apply a digital filter (direct form II transposed)", "language": "Java from Kotlin", "task": "Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the \"direct form II transposed\" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [https://ccrma.stanford.edu/~jos/fp/Transposed_Direct_Forms.html]\n\n;Task:\n\nFilter a signal using an order 3 low-pass Butterworth filter. The coefficients for the filter are a=[1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] and b = [0.16666667, 0.5, 0.5, 0.16666667]\n\nThe signal that needs filtering is the following vector: [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677 ,0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589]\n\n;See also:\n[Wikipedia on Butterworth filters]\n\n\n", "solution": "public class DigitalFilter {\n private static double[] filter(double[] a, double[] b, double[] signal) {\n double[] result = new double[signal.length];\n for (int i = 0; i < signal.length; ++i) {\n double tmp = 0.0;\n for (int j = 0; j < b.length; ++j) {\n if (i - j < 0) continue;\n tmp += b[j] * signal[i - j];\n }\n for (int j = 1; j < a.length; ++j) {\n if (i - j < 0) continue;\n tmp -= a[j] * result[i - j];\n }\n tmp /= a[0];\n result[i] = tmp;\n }\n return result;\n }\n\n public static void main(String[] args) {\n double[] a = new double[]{1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17};\n double[] b = new double[]{0.16666667, 0.5, 0.5, 0.16666667};\n\n double[] signal = new double[]{\n -0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412,\n -0.662370894973, -1.00700480494, -0.404707073677, 0.800482325044,\n 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195,\n 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293,\n 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589\n };\n\n double[] result = filter(a, b, signal);\n for (int i = 0; i < result.length; ++i) {\n System.out.printf(\"% .8f\", result[i]);\n System.out.print((i + 1) % 5 != 0 ? \", \" : \"\\n\");\n }\n }\n}"} {"title": "Approximate equality", "language": "Java from Kotlin", "task": "Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the\ndifference in floating point calculations between different language implementations becomes significant. \n\nFor example, a difference between '''32''' bit and '''64''' bit floating point calculations may appear by \nabout the 8th significant digit in base 10 arithmetic.\n\n\n;Task:\nCreate a function which returns true if two floating point numbers are approximately equal. \n\n\nThe function should allow for differences in the magnitude of numbers, so that, for example, \n'''100000000000000.01''' may be approximately equal to '''100000000000000.011''', \neven though '''100.01''' is not approximately equal to '''100.011'''.\n\nIf the language has such a feature in its standard library, this may be used instead of a custom function.\n\nShow the function results with comparisons on the following pairs of values:\n:# 100000000000000.01, 100000000000000.011 (note: should return ''true'')\n:# 100.01, 100.011 (note: should return ''false'')\n:# 10000000000000.001 / 10000.0, 1000000000.0000001000\n:# 0.001, 0.0010000001\n:# 0.000000000000000000000101, 0.0\n:# sqrt(2) * sqrt(2), 2.0\n:# -sqrt(2) * sqrt(2), -2.0\n:# 3.14159265358979323846, 3.14159265358979324\n\nAnswers should be true for the first example and false in the second, so that just rounding the numbers to a fixed number of decimals should not be enough. Otherwise answers may vary and still be correct. See the Python code for one type of solution.\n\n\n__TOC__\n\n", "solution": "public class Approximate {\n private static boolean approxEquals(double value, double other, double epsilon) {\n return Math.abs(value - other) < epsilon;\n }\n\n private static void test(double a, double b) {\n double epsilon = 1e-18;\n System.out.printf(\"%f, %f => %s\\n\", a, b, approxEquals(a, b, epsilon));\n }\n\n public static void main(String[] args) {\n test(100000000000000.01, 100000000000000.011);\n test(100.01, 100.011);\n test(10000000000000.001 / 10000.0, 1000000000.0000001000);\n test(0.001, 0.0010000001);\n test(0.000000000000000000000101, 0.0);\n test(Math.sqrt(2.0) * Math.sqrt(2.0), 2.0);\n test(-Math.sqrt(2.0) * Math.sqrt(2.0), -2.0);\n test(3.14159265358979323846, 3.14159265358979324);\n }\n}"} {"title": "Archimedean spiral", "language": "Java 8", "task": "The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. \n\n\nAn Archimedean spiral can be described by the equation:\n\n:\\, r=a+b\\theta\n\nwith real numbers ''a'' and ''b''.\n\n\n;Task\nDraw an Archimedean spiral.\n\n", "solution": "import java.awt.*;\nimport static java.lang.Math.*;\nimport javax.swing.*;\n\npublic class ArchimedeanSpiral extends JPanel {\n\n public ArchimedeanSpiral() {\n setPreferredSize(new Dimension(640, 640));\n setBackground(Color.white);\n }\n\n void drawGrid(Graphics2D g) {\n g.setColor(new Color(0xEEEEEE));\n g.setStroke(new BasicStroke(2));\n\n double angle = toRadians(45);\n\n int w = getWidth();\n int center = w / 2;\n int margin = 10;\n int numRings = 8;\n\n int spacing = (w - 2 * margin) / (numRings * 2);\n\n for (int i = 0; i < numRings; i++) {\n int pos = margin + i * spacing;\n int size = w - (2 * margin + i * 2 * spacing);\n g.drawOval(pos, pos, size, size);\n\n double ia = i * angle;\n int x2 = center + (int) (cos(ia) * (w - 2 * margin) / 2);\n int y2 = center - (int) (sin(ia) * (w - 2 * margin) / 2);\n\n g.drawLine(center, center, x2, y2);\n }\n }\n\n void drawSpiral(Graphics2D g) {\n g.setStroke(new BasicStroke(2));\n g.setColor(Color.orange);\n\n double degrees = toRadians(0.1);\n double center = getWidth() / 2;\n double end = 360 * 2 * 10 * degrees;\n double a = 0;\n double b = 20;\n double c = 1;\n\n for (double theta = 0; theta < end; theta += degrees) {\n double r = a + b * pow(theta, 1 / c);\n double x = r * cos(theta);\n double y = r * sin(theta);\n plot(g, (int) (center + x), (int) (center - y));\n }\n }\n\n void plot(Graphics2D g, int x, int y) {\n g.drawOval(x, y, 1, 1);\n }\n\n @Override\n public void paintComponent(Graphics gg) {\n super.paintComponent(gg);\n Graphics2D g = (Graphics2D) gg;\n g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n RenderingHints.VALUE_ANTIALIAS_ON);\n\n drawGrid(g);\n drawSpiral(g);\n }\n\n public static void main(String[] args) {\n SwingUtilities.invokeLater(() -> {\n JFrame f = new JFrame();\n f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n f.setTitle(\"Archimedean Spiral\");\n f.setResizable(false);\n f.add(new ArchimedeanSpiral(), BorderLayout.CENTER);\n f.pack();\n f.setLocationRelativeTo(null);\n f.setVisible(true);\n });\n }\n}"} {"title": "Arithmetic-geometric mean", "language": "Java", "task": "{{wikipedia|Arithmetic-geometric mean}}\n\n\n;Task:\nWrite a function to compute the arithmetic-geometric mean of two numbers.\n\n\nThe arithmetic-geometric mean of two numbers can be (usefully) denoted as \\mathrm{agm}(a,g), and is equal to the limit of the sequence:\n: a_0 = a; \\qquad g_0 = g\n: a_{n+1} = \\tfrac{1}{2}(a_n + g_n); \\quad g_{n+1} = \\sqrt{a_n g_n}.\nSince the limit of a_n-g_n tends (rapidly) to zero with iterations, this is an efficient method.\n\nDemonstrate the function by calculating:\n:\\mathrm{agm}(1,1/\\sqrt{2})\n \n\n;Also see:\n* mathworld.wolfram.com/Arithmetic-Geometric Mean\n\n", "solution": "/*\n * Arithmetic-Geometric Mean of 1 & 1/sqrt(2)\n * Brendan Shaklovitz\n * 5/29/12\n */\npublic class ArithmeticGeometricMean {\n\n public static double agm(double a, double g) {\n double a1 = a;\n double g1 = g;\n while (Math.abs(a1 - g1) >= 1.0e-14) {\n double arith = (a1 + g1) / 2.0;\n double geom = Math.sqrt(a1 * g1);\n a1 = arith;\n g1 = geom;\n }\n return a1;\n }\n\n public static void main(String[] args) {\n System.out.println(agm(1.0, 1.0 / Math.sqrt(2.0)));\n }\n}"} {"title": "Arithmetic-geometric mean/Calculate Pi", "language": "Java from Kotlin", "task": "Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate \\pi.\n\nWith the same notations used in [[Arithmetic-geometric mean]], we can summarize the paper by writing:\n\n\\pi =\n\\frac{4\\; \\mathrm{agm}(1, 1/\\sqrt{2})^2}\n{1 - \\sum\\limits_{n=1}^{\\infty} 2^{n+1}(a_n^2-g_n^2)}\n\n\nThis allows you to make the approximation, for any large '''N''':\n\n\\pi \\approx\n\\frac{4\\; a_N^2}\n{1 - \\sum\\limits_{k=1}^N 2^{k+1}(a_k^2-g_k^2)}\n\n\nThe purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of \\pi.\n\n", "solution": "import java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.util.Objects;\n\npublic class Calculate_Pi {\n private static final MathContext con1024 = new MathContext(1024);\n private static final BigDecimal bigTwo = new BigDecimal(2);\n private static final BigDecimal bigFour = new BigDecimal(4);\n\n private static BigDecimal bigSqrt(BigDecimal bd, MathContext con) {\n BigDecimal x0 = BigDecimal.ZERO;\n BigDecimal x1 = BigDecimal.valueOf(Math.sqrt(bd.doubleValue()));\n while (!Objects.equals(x0, x1)) {\n x0 = x1;\n x1 = bd.divide(x0, con).add(x0).divide(bigTwo, con);\n }\n return x1;\n }\n\n public static void main(String[] args) {\n BigDecimal a = BigDecimal.ONE;\n BigDecimal g = a.divide(bigSqrt(bigTwo, con1024), con1024);\n BigDecimal t;\n BigDecimal sum = BigDecimal.ZERO;\n BigDecimal pow = bigTwo;\n while (!Objects.equals(a, g)) {\n t = a.add(g).divide(bigTwo, con1024);\n g = bigSqrt(a.multiply(g), con1024);\n a = t;\n pow = pow.multiply(bigTwo);\n sum = sum.add(a.multiply(a).subtract(g.multiply(g)).multiply(pow));\n }\n BigDecimal pi = bigFour.multiply(a.multiply(a)).divide(BigDecimal.ONE.subtract(sum), con1024);\n System.out.println(pi);\n }\n}"} {"title": "Arithmetic evaluation", "language": "Java", "task": "Create a program which parses and evaluates arithmetic expressions.\n;Requirements:\n* An abstract-syntax tree (AST) for the expression must be created from parsing the input. \n* The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) \n* The expression will be a string or list of symbols like \"(1+3)*7\". \n* The four symbols + - * / must be supported as binary operators with conventional precedence rules. \n* Precedence-control parentheses must also be supported.\n\n\n;Note:\nFor those who don't remember, mathematical precedence is as follows:\n* Parentheses\n* Multiplication/Division (left to right)\n* Addition/Subtraction (left to right)\n\n\n;C.f: \n* [[24 game Player]].\n* [[Parsing/RPN calculator algorithm]].\n* [[Parsing/RPN to infix conversion]].\n\n", "solution": "import java.util.Stack;\n\npublic class ArithmeticEvaluation {\n\n public interface Expression {\n BigRational eval();\n }\n\n public enum Parentheses {LEFT}\n\n public enum BinaryOperator {\n ADD('+', 1),\n SUB('-', 1),\n MUL('*', 2),\n DIV('/', 2);\n\n public final char symbol;\n public final int precedence;\n\n BinaryOperator(char symbol, int precedence) {\n this.symbol = symbol;\n this.precedence = precedence;\n }\n\n public BigRational eval(BigRational leftValue, BigRational rightValue) {\n switch (this) {\n case ADD:\n return leftValue.add(rightValue);\n case SUB:\n return leftValue.subtract(rightValue);\n case MUL:\n return leftValue.multiply(rightValue);\n case DIV:\n return leftValue.divide(rightValue);\n }\n throw new IllegalStateException();\n }\n\n public static BinaryOperator forSymbol(char symbol) {\n for (BinaryOperator operator : values()) {\n if (operator.symbol == symbol) {\n return operator;\n }\n }\n throw new IllegalArgumentException(String.valueOf(symbol));\n }\n }\n\n public static class Number implements Expression {\n private final BigRational number;\n\n public Number(BigRational number) {\n this.number = number;\n }\n\n @Override\n public BigRational eval() {\n return number;\n }\n\n @Override\n public String toString() {\n return number.toString();\n }\n }\n\n public static class BinaryExpression implements Expression {\n public final Expression leftOperand;\n public final BinaryOperator operator;\n public final Expression rightOperand;\n\n public BinaryExpression(Expression leftOperand, BinaryOperator operator, Expression rightOperand) {\n this.leftOperand = leftOperand;\n this.operator = operator;\n this.rightOperand = rightOperand;\n }\n\n @Override\n public BigRational eval() {\n BigRational leftValue = leftOperand.eval();\n BigRational rightValue = rightOperand.eval();\n return operator.eval(leftValue, rightValue);\n }\n\n @Override\n public String toString() {\n return \"(\" + leftOperand + \" \" + operator.symbol + \" \" + rightOperand + \")\";\n }\n }\n\n private static void createNewOperand(BinaryOperator operator, Stack operands) {\n Expression rightOperand = operands.pop();\n Expression leftOperand = operands.pop();\n operands.push(new BinaryExpression(leftOperand, operator, rightOperand));\n }\n\n public static Expression parse(String input) {\n int curIndex = 0;\n boolean afterOperand = false;\n Stack operands = new Stack<>();\n Stack operators = new Stack<>();\n while (curIndex < input.length()) {\n int startIndex = curIndex;\n char c = input.charAt(curIndex++);\n\n if (Character.isWhitespace(c))\n continue;\n\n if (afterOperand) {\n if (c == ')') {\n Object operator;\n while (!operators.isEmpty() && ((operator = operators.pop()) != Parentheses.LEFT))\n createNewOperand((BinaryOperator) operator, operands);\n continue;\n }\n afterOperand = false;\n BinaryOperator operator = BinaryOperator.forSymbol(c);\n while (!operators.isEmpty() && (operators.peek() != Parentheses.LEFT) && (((BinaryOperator) operators.peek()).precedence >= operator.precedence))\n createNewOperand((BinaryOperator) operators.pop(), operands);\n operators.push(operator);\n continue;\n }\n\n if (c == '(') {\n operators.push(Parentheses.LEFT);\n continue;\n }\n\n afterOperand = true;\n while (curIndex < input.length()) {\n c = input.charAt(curIndex);\n if (((c < '0') || (c > '9')) && (c != '.'))\n break;\n curIndex++;\n }\n operands.push(new Number(BigRational.valueOf(input.substring(startIndex, curIndex))));\n }\n\n while (!operators.isEmpty()) {\n Object operator = operators.pop();\n if (operator == Parentheses.LEFT)\n throw new IllegalArgumentException();\n createNewOperand((BinaryOperator) operator, operands);\n }\n\n Expression expression = operands.pop();\n if (!operands.isEmpty())\n throw new IllegalArgumentException();\n return expression;\n }\n\n public static void main(String[] args) {\n String[] testExpressions = {\n \"2+3\",\n \"2+3/4\",\n \"2*3-4\",\n \"2*(3+4)+5/6\",\n \"2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10\",\n \"2*-3--4+-.25\"};\n for (String testExpression : testExpressions) {\n Expression expression = parse(testExpression);\n System.out.printf(\"Input: \\\"%s\\\", AST: \\\"%s\\\", value=%s%n\", testExpression, expression, expression.eval());\n }\n }\n}"} {"title": "Array length", "language": "Java", "task": "Determine the amount of elements in an array.\n\n\nAs an example use an array holding the strings 'apple' and 'orange'.\n\n\n\n", "solution": "String[] strings = { \"apple\", \"orange\" };\nint length = strings.length;\n"} {"title": "Ascending primes", "language": "Java from C++", "task": "Generate and show all primes with strictly ascending decimal digits.\n\nAside: Try solving without peeking at existing solutions. I had a weird idea for generating\na prime sieve faster, which needless to say didn't pan out. The solution may be p(r)etty trivial\nbut generating them quickly is at least mildly interesting.\nTip: filtering all 7,027,260 primes below 123,456,789 probably won't kill you, but there is\nat least one significantly better and much faster way, needing a mere 511 odd/prime tests.\n\n\n;See also\n;* OEIS:A052015 - Primes with distinct digits in ascending order\n\n\n;Related:\n*[[Primes with digits in nondecreasing order]] (infinite series allowing duplicate digits, whereas this isn't and doesn't)\n*[[Pandigital prime]] (whereas this is the smallest, with gaps in the used digits being permitted)\n\n\n", "solution": "/*\n * Ascending primes\n *\n * Generate and show all primes with strictly ascending decimal digits.\n *\n *\n * Solution\n *\n * We only consider positive numbers in the range 1 to 123456789. We would\n * get 7027260 primes, because there are so many primes smaller than 123456789\n * (see also Wolfram Alpha).On the other hand, there are only 511 distinct\n * positive integers having their digits arranged in ascending order.\n * Therefore, it is better to start with numbers that have properly arranged\n * digits and then check if they are prime numbers.The method of generating\n * a sequence of such numbers is not indifferent.We want this sequence to be\n * monotonically increasing, because then additional sorting of results will\n * be unnecessary. It turns out that by using a queue we can easily get the\n * desired effect. Additionally, the algorithm then does not use recursion\n * (although the program probably does not have to comply with the MISRA\n * standard). The problem to be solved is the queue size, the a priori\n * assumption that 1000 is good enough, but a bit magical.\n */\n\npackage example.rossetacode.ascendingprimes;\n\nimport java.util.Arrays;\n\npublic class Program implements Runnable {\n\n public static void main(String[] args) {\n long t1 = System.nanoTime();\n new Program().run();\n long t2 = System.nanoTime();\n System.out.println(\n \"total time consumed = \" + (t2 - t1) * 1E-6 + \" milliseconds\");\n }\n\n public void run() {\n\n final int MAX_SIZE = 1000;\n final int[] queue = new int[MAX_SIZE];\n int begin = 0;\n int end = 0;\n\n for (int k = 1; k <= 9; k++) {\n queue[end++] = k;\n }\n\n while (begin < end) {\n int n = queue[begin++];\n for (int k = n % 10 + 1; k <= 9; k++) {\n queue[end++] = n * 10 + k;\n }\n }\n\n // We can use a parallel stream (and then sort the results)\n // to use multiple cores.\n //\n System.out.println(Arrays.stream(queue).filter(this::isPrime).boxed().toList());\n }\n\n private boolean isPrime(int n) {\n if (n == 2) {\n return true;\n }\n if (n == 1 || n % 2 == 0) {\n return false;\n }\n int root = (int) Math.sqrt(n);\n for (int k = 3; k <= root; k += 2) {\n if (n % k == 0) {\n return false;\n }\n }\n return true;\n }\n}"} {"title": "Associative array/Merging", "language": "Java", "task": "Define two associative arrays, where one represents the following \"base\" data:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"name\" || \"Rocket Skates\"\n|-\n| \"price\" || 12.75\n|-\n| \"color\" || \"yellow\"\n|}\n\nAnd the other represents \"update\" data:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"price\" || 15.25\n|-\n| \"color\" || \"red\"\n|-\n| \"year\" || 1974\n|}\n\nMerge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"name\" || \"Rocket Skates\"\n|-\n| \"price\" || 15.25\n|-\n| \"color\" || \"red\"\n|-\n| \"year\" || 1974\n|}\n\n", "solution": "for(Map.Entry entry : mapA.entrySet())\n System.out.printf(\"%-20s%s%n\", entry.getKey(), entry.getValue());\n\nfor(Map.Entry entry : mapB.entrySet())\n System.out.printf(\"%-20s%s%n\", entry.getKey(), entry.getValue());\n\nfor(Map.Entry entry : mapC.entrySet())\n System.out.printf(\"%-20s%s%n\", entry.getKey(), entry.getValue());\n"} {"title": "Attractive numbers", "language": "Java from C", "task": "A number is an ''attractive number'' if the number of its prime factors (whether distinct or not) is also prime.\n\n\n;Example:\nThe number '''20''', whose prime decomposition is '''2 x 2 x 5''', is an ''attractive number'' because the number of its prime factors ('''3''') is also prime.\n\n\n;Task:\nShow sequence items up to '''120'''.\n\n\n;Reference:\n:* The OEIS entry: A063989: Numbers with a prime number of prime divisors.\n\n", "solution": "public class Attractive {\n\n static boolean is_prime(int n) {\n if (n < 2) return false;\n if (n % 2 == 0) return n == 2;\n if (n % 3 == 0) return n == 3;\n int d = 5;\n while (d *d <= n) {\n if (n % d == 0) return false;\n d += 2;\n if (n % d == 0) return false;\n d += 4;\n }\n return true;\n }\n\n static int count_prime_factors(int n) {\n if (n == 1) return 0;\n if (is_prime(n)) return 1;\n int count = 0, f = 2;\n while (true) {\n if (n % f == 0) {\n count++;\n n /= f;\n if (n == 1) return count;\n if (is_prime(n)) f = n;\n }\n else if (f >= 3) f += 2;\n else f = 3;\n }\n }\n\n public static void main(String[] args) {\n final int max = 120;\n System.out.printf(\"The attractive numbers up to and including %d are:\\n\", max);\n for (int i = 1, count = 0; i <= max; ++i) {\n int n = count_prime_factors(i);\n if (is_prime(n)) {\n System.out.printf(\"%4d\", i);\n if (++count % 20 == 0) System.out.println();\n }\n }\n System.out.println();\n }\n}"} {"title": "Average loop length", "language": "Java", "task": "Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence.\n\n\n;Task:\nWrite a program or a script that estimates, for each N, the average length until the first such repetition.\n\nAlso calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one.\n\n\nThis problem comes from the end of Donald Knuth's Christmas tree lecture 2011.\n\nExample of expected output:\n\n N average analytical (error)\n=== ========= ============ =========\n 1 1.0000 1.0000 ( 0.00%)\n 2 1.4992 1.5000 ( 0.05%)\n 3 1.8784 1.8889 ( 0.56%)\n 4 2.2316 2.2188 ( 0.58%)\n 5 2.4982 2.5104 ( 0.49%)\n 6 2.7897 2.7747 ( 0.54%)\n 7 3.0153 3.0181 ( 0.09%)\n 8 3.2429 3.2450 ( 0.07%)\n 9 3.4536 3.4583 ( 0.14%)\n 10 3.6649 3.6602 ( 0.13%)\n 11 3.8091 3.8524 ( 1.12%)\n 12 3.9986 4.0361 ( 0.93%)\n 13 4.2074 4.2123 ( 0.12%)\n 14 4.3711 4.3820 ( 0.25%)\n 15 4.5275 4.5458 ( 0.40%)\n 16 4.6755 4.7043 ( 0.61%)\n 17 4.8877 4.8579 ( 0.61%)\n 18 4.9951 5.0071 ( 0.24%)\n 19 5.1312 5.1522 ( 0.41%)\n 20 5.2699 5.2936 ( 0.45%)\n\n", "solution": "import java.util.HashSet;\nimport java.util.Random;\nimport java.util.Set;\n\npublic class AverageLoopLength {\n\n private static final int N = 100000;\n\n //analytical(n) = sum_(i=1)^n (n!/(n-i)!/n**i)\n private static double analytical(int n) {\n double[] factorial = new double[n + 1];\n double[] powers = new double[n + 1];\n powers[0] = 1.0;\n factorial[0] = 1.0;\n for (int i = 1; i <= n; i++) {\n factorial[i] = factorial[i - 1] * i;\n powers[i] = powers[i - 1] * n;\n }\n double sum = 0;\n //memoized factorial and powers\n for (int i = 1; i <= n; i++) {\n sum += factorial[n] / factorial[n - i] / powers[i];\n }\n return sum;\n }\n\n private static double average(int n) {\n Random rnd = new Random();\n double sum = 0.0;\n for (int a = 0; a < N; a++) {\n int[] random = new int[n];\n for (int i = 0; i < n; i++) {\n random[i] = rnd.nextInt(n);\n }\n Set seen = new HashSet<>(n);\n int current = 0;\n int length = 0;\n while (seen.add(current)) {\n length++;\n current = random[current];\n }\n sum += length;\n }\n return sum / N;\n }\n\n public static void main(String[] args) {\n System.out.println(\" N average analytical (error)\");\n System.out.println(\"=== ========= ============ =========\");\n for (int i = 1; i <= 20; i++) {\n double avg = average(i);\n double ana = analytical(i);\n System.out.println(String.format(\"%3d %9.4f %12.4f (%6.2f%%)\", i, avg, ana, ((ana - avg) / ana * 100)));\n }\n }\n}"} {"title": "Averages/Mean angle", "language": "Java 7+", "task": "{{Related tasks/Statistical measures}}\n\n\n", "solution": "import java.util.Arrays;\n\npublic class AverageMeanAngle {\n\n public static void main(String[] args) {\n printAverageAngle(350.0, 10.0);\n printAverageAngle(90.0, 180.0, 270.0, 360.0);\n printAverageAngle(10.0, 20.0, 30.0);\n printAverageAngle(370.0);\n printAverageAngle(180.0);\n }\n\n private static void printAverageAngle(double... sample) {\n double meanAngle = getMeanAngle(sample);\n System.out.printf(\"The mean angle of %s is %s%n\", Arrays.toString(sample), meanAngle);\n }\n\n public static double getMeanAngle(double... anglesDeg) {\n double x = 0.0;\n double y = 0.0;\n\n for (double angleD : anglesDeg) {\n double angleR = Math.toRadians(angleD);\n x += Math.cos(angleR);\n y += Math.sin(angleR);\n }\n double avgR = Math.atan2(y / anglesDeg.length, x / anglesDeg.length);\n return Math.toDegrees(avgR);\n }\n}"} {"title": "Averages/Pythagorean means", "language": "Java", "task": "{{Related tasks/Statistical measures}}\n\n\n", "solution": "import java.util.Arrays;\nimport java.util.List;\n\npublic class PythagoreanMeans {\n public static double arithmeticMean(List numbers) {\n if (numbers.isEmpty()) return Double.NaN;\n double mean = 0.0;\n for (Double number : numbers) {\n mean += number;\n }\n return mean / numbers.size();\n }\n\n public static double geometricMean(List numbers) {\n if (numbers.isEmpty()) return Double.NaN;\n double mean = 1.0;\n for (Double number : numbers) {\n mean *= number;\n }\n return Math.pow(mean, 1.0 / numbers.size());\n }\n\n public static double harmonicMean(List numbers) {\n if (numbers.isEmpty() || numbers.contains(0.0)) return Double.NaN;\n double mean = 0.0;\n for (Double number : numbers) {\n mean += (1.0 / number);\n }\n return numbers.size() / mean;\n }\n\n public static void main(String[] args) {\n Double[] array = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0};\n List list = Arrays.asList(array);\n double arithmetic = arithmeticMean(list);\n double geometric = geometricMean(list);\n double harmonic = harmonicMean(list);\n System.out.format(\"A = %f G = %f H = %f%n\", arithmetic, geometric, harmonic);\n System.out.format(\"A >= G is %b, G >= H is %b%n\", (arithmetic >= geometric), (geometric >= harmonic));\n }\n}"} {"title": "Averages/Pythagorean means", "language": "Java 1.8", "task": "{{Related tasks/Statistical measures}}\n\n\n", "solution": "public static double arithmAverage(double array[]){\n if (array == null ||array.length == 0) {\n return 0.0;\n }\n else {\n return DoubleStream.of(array).average().getAsDouble();\n }\n }\n\n public static double geomAverage(double array[]){\n if (array == null ||array.length == 0) {\n return 0.0;\n }\n else {\n double aver = DoubleStream.of(array).reduce(1, (x, y) -> x * y);\n return Math.pow(aver, 1.0 / array.length);\n }\n }\n\n public static double harmAverage(double array[]){\n if (array == null ||array.length == 0) {\n return 0.0;\n }\n else {\n double aver = DoubleStream.of(array)\n // remove null values\n .filter(n -> n > 0.0)\n // generate 1/n array\n .map( n-> 1.0/n)\n // accumulating\n .reduce(0, (x, y) -> x + y);\n // just this reduce is not working- need to do in 2 steps\n // .reduce(0, (x, y) -> 1.0/x + 1.0/y);\n return array.length / aver ;\n }\n }\n "} {"title": "Averages/Root mean square", "language": "Java", "task": "Task\n\nCompute the Root mean square of the numbers 1..10.\n\n\nThe ''root mean square'' is also known by its initials RMS (or rms), and as the '''quadratic mean'''.\n\nThe RMS is calculated as the mean of the squares of the numbers, square-rooted:\n\n\n::: x_{\\mathrm{rms}} = \\sqrt {{{x_1}^2 + {x_2}^2 + \\cdots + {x_n}^2} \\over n}. \n\n\n;See also\n\n{{Related tasks/Statistical measures}}\n\n\n", "solution": "public class RootMeanSquare {\n\n public static double rootMeanSquare(double... nums) {\n double sum = 0.0;\n for (double num : nums)\n sum += num * num;\n return Math.sqrt(sum / nums.length);\n }\n\n public static void main(String[] args) {\n double[] nums = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0};\n System.out.println(\"The RMS of the numbers from 1 to 10 is \" + rootMeanSquare(nums));\n }\n}"} {"title": "Babbage problem", "language": "Java", "task": "Charles Babbage\nCharles Babbage's analytical engine.\n\nCharles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:\n{{quote\n | What is the smallest positive integer whose square ends in the digits 269,696?\n | Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.\n}}\nHe thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.\n\n\n;Task\n\nThe task is to find out if Babbage had the right answer -- and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand. \nAs Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.\n\nFor these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].\n\n\n;Motivation\n\nThe aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.\n\n", "solution": "public class Test {\n\n public static void main(String[] args) {\n\n // let n be zero\n int n = 0;\n\n // repeat the following action\n do {\n\n // increase n by 1\n n++;\n\n // while the modulo of n times n is not equal to 269696\n } while (n * n % 1000_000 != 269696);\n\n // show the result\n System.out.println(n);\n }\n}"} {"title": "Balanced brackets", "language": "Java 1.5+", "task": "'''Task''': \n* Generate a string with '''N''' opening brackets '''[''' and with '''N''' closing brackets ''']''', in some arbitrary order. \n* Determine whether the generated string is ''balanced''; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.\n\n\n\n;Examples:\n (empty) OK\n [] OK \n [][] OK \n [[][]] OK \n ][ NOT OK\n ][][ NOT OK\n []][[] NOT OK\n\n", "solution": "import java.util.ArrayDeque;\nimport java.util.Deque;\n\npublic class BalancedBrackets {\n\t\n\tpublic static boolean areSquareBracketsBalanced(String expr) {\n\t\treturn isBalanced(expr, \"\", \"\", \"[\", \"]\", false); \n\t}\n\tpublic static boolean areBracketsBalanced(String expr) {\n\t\treturn isBalanced(expr, \"\", \"\", \"{([\", \"})]\", false); \n\t}\n\tpublic static boolean areStringAndBracketsBalanced(String expr) {\n\t\treturn isBalanced(expr, \"'\\\"\", \"\\\\\\\\\", \"{([\", \"})]\", true); \n\t}\n\tpublic static boolean isBalanced(String expr, String lit, String esc, String obr, String cbr, boolean other) {\n\t\tboolean[] inLit = new boolean[lit.length()];\n\t\tDeque stack = new ArrayDeque();\n\t\tfor (int i=0; i0)\n\t\t\t\treturn v%3;\n\t\t\tv=v%3;\n\t\t\treturn (v+3)%3;\n\t\t}\n\t\t\n\t\tpublic int intValue()\n\t\t{\n\t\t\tint sum=0;\n\t\t\tString s=this.value;\n\t\t\tfor(int i=0;ib.length()?a:b;\n\t\t\tString shorter=a.length()>b.length()?b:a;\n\t\t\t\n\t\t\twhile(shorter.length()that.intValue())\n\t\t\t\treturn 1;\n\t\t\telse if(this.equals(that))\n\t\t\t\treturn 0;\n\t\t\t return -1;\n\t\t}\n\t\t\n\t\tpublic String toString()\n\t\t{\n\t\t\treturn value;\n\t\t}\n\t}\n}\n"} {"title": "Barnsley fern", "language": "Java 8", "task": "A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).\n\n\n;Task:\nCreate this fractal fern, using the following transformations:\n* f1 (chosen 1% of the time)\n xn + 1 = 0\n yn + 1 = 0.16 yn\n\n* f2 (chosen 85% of the time)\n xn + 1 = 0.85 xn + 0.04 yn\n yn + 1 = -0.04 xn + 0.85 yn + 1.6\n\n* f3 (chosen 7% of the time)\n xn + 1 = 0.2 xn - 0.26 yn\n yn + 1 = 0.23 xn + 0.22 yn + 1.6\n\n* f4 (chosen 7% of the time)\n xn + 1 = -0.15 xn + 0.28 yn\n yn + 1 = 0.26 xn + 0.24 yn + 0.44.\n\nStarting position: x = 0, y = 0\n\n", "solution": "import java.awt.*;\nimport java.awt.image.BufferedImage;\nimport javax.swing.*;\n\npublic class BarnsleyFern extends JPanel {\n\n BufferedImage img;\n\n public BarnsleyFern() {\n final int dim = 640;\n setPreferredSize(new Dimension(dim, dim));\n setBackground(Color.white);\n img = new BufferedImage(dim, dim, BufferedImage.TYPE_INT_ARGB);\n createFern(dim, dim);\n }\n\n void createFern(int w, int h) {\n double x = 0;\n double y = 0;\n\n for (int i = 0; i < 200_000; i++) {\n double tmpx, tmpy;\n double r = Math.random();\n\n if (r <= 0.01) {\n tmpx = 0;\n tmpy = 0.16 * y;\n } else if (r <= 0.08) {\n tmpx = 0.2 * x - 0.26 * y;\n tmpy = 0.23 * x + 0.22 * y + 1.6;\n } else if (r <= 0.15) {\n tmpx = -0.15 * x + 0.28 * y;\n tmpy = 0.26 * x + 0.24 * y + 0.44;\n } else {\n tmpx = 0.85 * x + 0.04 * y;\n tmpy = -0.04 * x + 0.85 * y + 1.6;\n }\n x = tmpx;\n y = tmpy;\n\n img.setRGB((int) Math.round(w / 2 + x * w / 11),\n (int) Math.round(h - y * h / 11), 0xFF32CD32);\n }\n }\n\n @Override\n public void paintComponent(Graphics gg) {\n super.paintComponent(gg);\n Graphics2D g = (Graphics2D) gg;\n g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n RenderingHints.VALUE_ANTIALIAS_ON);\n\n g.drawImage(img, 0, 0, null);\n }\n\n public static void main(String[] args) {\n SwingUtilities.invokeLater(() -> {\n JFrame f = new JFrame();\n f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n f.setTitle(\"Barnsley Fern\");\n f.setResizable(false);\n f.add(new BarnsleyFern(), BorderLayout.CENTER);\n f.pack();\n f.setLocationRelativeTo(null);\n f.setVisible(true);\n });\n }\n}"} {"title": "Base64 decode data", "language": "Java", "task": "See [[Base64 encode data]]. \n\nNow write a program that takes the output of the [[Base64 encode data]] task as input and regenerate the original file. \n\nWhen working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.\n\n", "solution": "void decodeToFile(String path, byte[] bytes) throws IOException {\n try (FileOutputStream stream = new FileOutputStream(path)) {\n byte[] decoded = Base64.getDecoder().decode(bytes);\n stream.write(decoded, 0, decoded.length);\n }\n}\n"} {"title": "Base64 decode data", "language": "Java from Kotlin", "task": "See [[Base64 encode data]]. \n\nNow write a program that takes the output of the [[Base64 encode data]] task as input and regenerate the original file. \n\nWhen working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.\n\n", "solution": "import java.nio.charset.StandardCharsets;\nimport java.util.Base64;\n\npublic class Decode {\n public static void main(String[] args) {\n String data = \"VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=\";\n Base64.Decoder decoder = Base64.getDecoder();\n byte[] decoded = decoder.decode(data);\n String decodedStr = new String(decoded, StandardCharsets.UTF_8);\n System.out.println(decodedStr);\n }\n}"} {"title": "Bell numbers", "language": "Java from Kotlin", "task": "Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly '''n''' elements. Each element of the sequence '''Bn''' is the number of partitions of a set of size '''n''' where order of the elements and order of the partitions are non-significant. E.G.: '''{a b}''' is the same as '''{b a}''' and '''{a} {b}''' is the same as '''{b} {a}'''.\n\n\n;So:\n\n:'''B0 = 1''' trivially. There is only one way to partition a set with zero elements. '''{ }'''\n\n:'''B1 = 1''' There is only one way to partition a set with one element. '''{a}'''\n\n:'''B2 = 2''' Two elements may be partitioned in two ways. '''{a} {b}, {a b}'''\n\n:'''B3 = 5''' Three elements may be partitioned in five ways '''{a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c}'''\n\n: and so on.\n\n\nA simple way to find the Bell numbers is construct a '''Bell triangle''', also known as an '''Aitken's array''' or '''Peirce triangle''', and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case.\n\n\n;Task:\n\nWrite a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the '''first 15''' and (if your language supports big Integers) '''50th''' elements of the sequence. \n\nIf you ''do'' use the Bell triangle method to generate the numbers, also show the '''first ten rows''' of the Bell triangle.\n\n\n;See also:\n\n:* '''OEIS:A000110 Bell or exponential numbers'''\n:* '''OEIS:A011971 Aitken's array'''\n\n", "solution": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class Bell {\n private static class BellTriangle {\n private List arr;\n\n BellTriangle(int n) {\n int length = n * (n + 1) / 2;\n arr = new ArrayList<>(length);\n for (int i = 0; i < length; ++i) {\n arr.add(0);\n }\n\n set(1, 0, 1);\n for (int i = 2; i <= n; ++i) {\n set(i, 0, get(i - 1, i - 2));\n for (int j = 1; j < i; ++j) {\n int value = get(i, j - 1) + get(i - 1, j - 1);\n set(i, j, value);\n }\n }\n }\n\n private int index(int row, int col) {\n if (row > 0 && col >= 0 && col < row) {\n return row * (row - 1) / 2 + col;\n } else {\n throw new IllegalArgumentException();\n }\n }\n\n public int get(int row, int col) {\n int i = index(row, col);\n return arr.get(i);\n }\n\n public void set(int row, int col, int value) {\n int i = index(row, col);\n arr.set(i, value);\n }\n }\n\n public static void main(String[] args) {\n final int rows = 15;\n BellTriangle bt = new BellTriangle(rows);\n\n System.out.println(\"First fifteen Bell numbers:\");\n for (int i = 0; i < rows; ++i) {\n System.out.printf(\"%2d: %d\\n\", i + 1, bt.get(i + 1, 0));\n }\n\n for (int i = 1; i <= 10; ++i) {\n System.out.print(bt.get(i, 0));\n for (int j = 1; j < i; ++j) {\n System.out.printf(\", %d\", bt.get(i, j));\n }\n System.out.println();\n }\n }\n}"} {"title": "Benford's law", "language": "Java", "task": "{{Wikipedia|Benford's_law}}\n\n\n'''Benford's law''', also called the '''first-digit law''', refers to the frequency distribution of digits in many (but not all) real-life sources of data. \n\nIn this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale. \n\nBenford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.\n\nThis result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.\n\nA set of numbers is said to satisfy Benford's law if the leading digit d (d \\in \\{1, \\ldots, 9\\}) occurs with probability\n\n:::: P(d) = \\log_{10}(d+1)-\\log_{10}(d) = \\log_{10}\\left(1+\\frac{1}{d}\\right)\n\nFor this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).\n\nUse the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained. \n\nYou can generate them or load them from a file; whichever is easiest. \n\nDisplay your actual vs expected distribution.\n\n\n''For extra credit:'' Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.\n\n\n;See also:\n* numberphile.com.\n* A starting page on Wolfram Mathworld is {{Wolfram|Benfords|Law}}.\n\n", "solution": "import java.math.BigInteger;\nimport java.util.Locale;\n\npublic class BenfordsLaw {\n\n private static BigInteger[] generateFibonacci(int n) {\n BigInteger[] fib = new BigInteger[n];\n fib[0] = BigInteger.ONE;\n fib[1] = BigInteger.ONE;\n for (int i = 2; i < fib.length; i++) {\n fib[i] = fib[i - 2].add(fib[i - 1]);\n }\n return fib;\n }\n\n public static void main(String[] args) {\n BigInteger[] numbers = generateFibonacci(1000);\n\n int[] firstDigits = new int[10];\n for (BigInteger number : numbers) {\n firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++;\n }\n\n for (int i = 1; i < firstDigits.length; i++) {\n System.out.printf(Locale.ROOT, \"%d %10.6f %10.6f%n\",\n i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i));\n }\n }\n}"} {"title": "Best shuffle", "language": "Java", "task": "Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. \n\nA shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative.\n\nDisplay the result as follows: \n\n original string, shuffled string, (score) \n\nThe score gives the number of positions whose character value did ''not'' change. \n\n\n;Example:\n tree, eetr, (0)\n\n\n;Test cases:\n abracadabra\n seesaw\n elk\n grrrrrr\n up\n a\n\n\n;Related tasks\n* [[Anagrams/Deranged anagrams]]\n* [[Permutations/Derangements]]\n\n\n\n", "solution": "import java.util.Random;\n\npublic class BestShuffle {\n private final static Random rand = new Random();\n\n public static void main(String[] args) {\n String[] words = {\"abracadabra\", \"seesaw\", \"grrrrrr\", \"pop\", \"up\", \"a\"};\n for (String w : words)\n System.out.println(bestShuffle(w));\n }\n\n public static String bestShuffle(final String s1) {\n char[] s2 = s1.toCharArray();\n shuffle(s2);\n for (int i = 0; i < s2.length; i++) {\n if (s2[i] != s1.charAt(i))\n continue;\n for (int j = 0; j < s2.length; j++) {\n if (s2[i] != s2[j] && s2[i] != s1.charAt(j) && s2[j] != s1.charAt(i)) {\n char tmp = s2[i];\n s2[i] = s2[j];\n s2[j] = tmp;\n break;\n }\n }\n }\n return s1 + \" \" + new String(s2) + \" (\" + count(s1, s2) + \")\";\n }\n\n public static void shuffle(char[] text) {\n for (int i = text.length - 1; i > 0; i--) {\n int r = rand.nextInt(i + 1);\n char tmp = text[i];\n text[i] = text[r];\n text[r] = tmp;\n }\n }\n\n private static int count(final String s1, final char[] s2) {\n int count = 0;\n for (int i = 0; i < s2.length; i++)\n if (s1.charAt(i) == s2[i])\n count++;\n return count;\n }\n}"} {"title": "Bin given limits", "language": "Java", "task": "You are given a list of n ascending, unique numbers which are to form limits\nfor n+1 bins which count how many of a large set of input numbers fall in the\nrange of each bin.\n\n(Assuming zero-based indexing)\n\n bin[0] counts how many inputs are < limit[0]\n bin[1] counts how many inputs are >= limit[0] and < limit[1]\n ..''\n bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1]\n bin[n] counts how many inputs are >= limit[n-1]\n\n;Task:\nThe task is to create a function that given the ascending limits and a stream/\nlist of numbers, will return the bins; together with another function that\ngiven the same list of limits and the binning will ''print the limit of each bin\ntogether with the count of items that fell in the range''.\n\nAssume the numbers to bin are too large to practically sort.\n\n;Task examples:\nPart 1: Bin using the following limits the given input data\n\n limits = [23, 37, 43, 53, 67, 83]\n data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n\nPart 2: Bin using the following limits the given input data\n\n limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,\n 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,\n 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749]\n\nShow output here, on this page.\n", "solution": "import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Bins {\n public static > int[] bins(\n List limits, Iterable data) {\n int[] result = new int[limits.size() + 1];\n for (T n : data) {\n int i = Collections.binarySearch(limits, n);\n if (i >= 0) {\n // n == limits[i]; we put it in right-side bin (i+1)\n i = i+1;\n } else {\n // n is not in limits and i is ~(insertion point)\n i = ~i;\n }\n result[i]++;\n }\n return result;\n }\n\n public static void printBins(List limits, int[] bins) {\n int n = limits.size();\n if (n == 0) {\n return;\n }\n assert n+1 == bins.length;\n System.out.printf(\" < %3s: %2d\\n\", limits.get(0), bins[0]);\n for (int i = 1; i < n; i++) {\n System.out.printf(\">= %3s and < %3s: %2d\\n\", limits.get(i-1), limits.get(i), bins[i]);\n }\n System.out.printf(\">= %3s : %2d\\n\", limits.get(n-1), bins[n]);\n }\n\n public static void main(String[] args) {\n List limits = Arrays.asList(23, 37, 43, 53, 67, 83);\n List data = Arrays.asList(\n 95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65,\n 17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19,\n 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55);\n\n System.out.println(\"Example 1:\");\n printBins(limits, bins(limits, data));\n\n limits = Arrays.asList(14, 18, 249, 312, 389,\n 392, 513, 591, 634, 720);\n data = Arrays.asList(\n 445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525,\n 570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391,\n 913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213,\n 799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n 397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981,\n 480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898,\n 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n 54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374,\n 101, 684, 727, 749);\n\n System.out.println();\n System.out.println(\"Example 2:\");\n printBins(limits, bins(limits, data));\n }\n}"} {"title": "Bioinformatics/Sequence mutation", "language": "Java", "task": "Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by:\n# Choosing a random base position in the sequence.\n# Mutate the sequence by doing one of either:\n## '''S'''wap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base)\n## '''D'''elete the chosen base at the position.\n## '''I'''nsert another base randomly chosen from A,C, G, or T into the sequence at that position.\n# Randomly generate a test DNA sequence of at least 200 bases\n# \"Pretty print\" the sequence and a count of its size, and the count of each base in the sequence\n# Mutate the sequence ten times.\n# \"Pretty print\" the sequence after all mutations, and a count of its size, and the count of each base in the sequence.\n\n;Extra credit:\n* Give more information on the individual mutations applied.\n* Allow mutations to be weighted and/or chosen.\n", "solution": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class SequenceMutation {\n public static void main(String[] args) {\n SequenceMutation sm = new SequenceMutation();\n sm.setWeight(OP_CHANGE, 3);\n String sequence = sm.generateSequence(250);\n System.out.println(\"Initial sequence:\");\n printSequence(sequence);\n int count = 10;\n for (int i = 0; i < count; ++i)\n sequence = sm.mutateSequence(sequence);\n System.out.println(\"After \" + count + \" mutations:\");\n printSequence(sequence);\n }\n\n public SequenceMutation() {\n totalWeight_ = OP_COUNT;\n Arrays.fill(operationWeight_, 1);\n }\n\n public String generateSequence(int length) {\n char[] ch = new char[length];\n for (int i = 0; i < length; ++i)\n ch[i] = getRandomBase();\n return new String(ch);\n }\n\n public void setWeight(int operation, int weight) {\n totalWeight_ -= operationWeight_[operation];\n operationWeight_[operation] = weight;\n totalWeight_ += weight;\n }\n\n public String mutateSequence(String sequence) {\n char[] ch = sequence.toCharArray();\n int pos = random_.nextInt(ch.length);\n int operation = getRandomOperation();\n if (operation == OP_CHANGE) {\n char b = getRandomBase();\n System.out.println(\"Change base at position \" + pos + \" from \"\n + ch[pos] + \" to \" + b);\n ch[pos] = b;\n } else if (operation == OP_ERASE) {\n System.out.println(\"Erase base \" + ch[pos] + \" at position \" + pos);\n char[] newCh = new char[ch.length - 1];\n System.arraycopy(ch, 0, newCh, 0, pos);\n System.arraycopy(ch, pos + 1, newCh, pos, ch.length - pos - 1);\n ch = newCh;\n } else if (operation == OP_INSERT) {\n char b = getRandomBase();\n System.out.println(\"Insert base \" + b + \" at position \" + pos);\n char[] newCh = new char[ch.length + 1];\n System.arraycopy(ch, 0, newCh, 0, pos);\n System.arraycopy(ch, pos, newCh, pos + 1, ch.length - pos);\n newCh[pos] = b;\n ch = newCh;\n }\n return new String(ch);\n }\n\n public static void printSequence(String sequence) {\n int[] count = new int[BASES.length];\n for (int i = 0, n = sequence.length(); i < n; ++i) {\n if (i % 50 == 0) {\n if (i != 0)\n System.out.println();\n System.out.printf(\"%3d: \", i);\n }\n char ch = sequence.charAt(i);\n System.out.print(ch);\n for (int j = 0; j < BASES.length; ++j) {\n if (BASES[j] == ch) {\n ++count[j];\n break;\n }\n }\n }\n System.out.println();\n System.out.println(\"Base counts:\");\n int total = 0;\n for (int j = 0; j < BASES.length; ++j) {\n total += count[j];\n System.out.print(BASES[j] + \": \" + count[j] + \", \");\n }\n System.out.println(\"Total: \" + total);\n }\n\n private char getRandomBase() {\n return BASES[random_.nextInt(BASES.length)];\n }\n\n private int getRandomOperation() {\n int n = random_.nextInt(totalWeight_), op = 0;\n for (int weight = 0; op < OP_COUNT; ++op) {\n weight += operationWeight_[op];\n if (n < weight)\n break;\n }\n return op;\n }\n\n private final Random random_ = new Random();\n private int[] operationWeight_ = new int[OP_COUNT];\n private int totalWeight_ = 0;\n\n private static final int OP_CHANGE = 0;\n private static final int OP_ERASE = 1;\n private static final int OP_INSERT = 2;\n private static final int OP_COUNT = 3;\n private static final char[] BASES = {'A', 'C', 'G', 'T'};\n}"} {"title": "Bioinformatics/base count", "language": "Java", "task": "Given this string representing ordered DNA bases:\n\nCGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\nCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\nAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\nGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\nCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\nTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\nTTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\nCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\nTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\nGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\n\n\n\n;Task:\n:* \"Pretty print\" the sequence followed by a summary of the counts of each of the bases: ('''A''', '''C''', '''G''', and '''T''') in the sequence \n:* print the total count of each base in the string.\n\n\n\n", "solution": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class orderedSequence {\n public static void main(String[] args) {\n Sequence gene = new Sequence(\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\");\n gene.runSequence();\n }\n}\n\n/** Separate class for defining behaviors */\npublic class Sequence {\n \n private final String seq;\n \n public Sequence(String sq) {\n this.seq = sq;\n }\n \n /** print the organized structure of the sequence */\n public void prettyPrint() {\n System.out.println(\"Sequence:\");\n int i = 0;\n for ( ; i < seq.length() - 50 ; i += 50) {\n System.out.printf(\"%5s : %s\\n\", i + 50, seq.substring(i, i + 50));\n }\n System.out.printf(\"%5s : %s\\n\", seq.length(), seq.substring(i));\n }\n \n /** display a base vs. frequency chart */\n public void displayCount() {\n Map counter = new HashMap<>();\n for (int i = 0 ; i < seq.length() ; ++i) {\n counter.merge(seq.charAt(i), 1, Integer::sum);\n }\n\n System.out.println(\"Base vs. Count:\");\n counter.forEach(\n key, value -> System.out.printf(\"%5s : %s\\n\", key, value));\n System.out.printf(\"%5s: %s\\n\", \"SUM\", seq.length());\n }\n \n public void runSequence() {\n this.prettyPrint();\n this.displayCount();\n }\n}\n\n"} {"title": "Bitcoin/address validation", "language": "Java", "task": "Write a program that takes a bitcoin address as argument, \nand checks whether or not this address is valid.\n\nA bitcoin address uses a base58 encoding, which uses an alphabet of the characters 0 .. 9, A ..Z, a .. z, but without the four characters:\n:::* 0 zero\n:::* O uppercase oh\n:::* I uppercase eye\n:::* l lowercase ell\n\n\nWith this encoding, a bitcoin address encodes 25 bytes:\n* the first byte is the version number, which will be zero for this task ;\n* the next twenty bytes are a [[RIPEMD-160]] digest, but you don't have to know that for this task: you can consider them a pure arbitrary data ;\n* the last four bytes are a checksum check. They are the first four bytes of a double [[SHA-256]] digest of the previous 21 bytes.\n\n\nTo check the bitcoin address, you must read the first twenty-one bytes, compute the checksum, and check that it corresponds to the last four bytes.\n\nThe program can either return a boolean value or throw an exception when not valid.\n\nYou can use a digest library for [[SHA-256]].\n\n\n;Example of a bitcoin address:\n\n 1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i\n\n\nIt doesn't belong to anyone and is part of the test suite of the bitcoin software. \nYou can change a few characters in this string and check that it'll fail the test.\n\n", "solution": "import java.math.BigInteger;\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\nimport java.util.Arrays;\n\npublic class BitcoinAddressValidator {\n\n private static final String ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\n public static boolean validateBitcoinAddress(String addr) {\n if (addr.length() < 26 || addr.length() > 35)\n return false;\n byte[] decoded = decodeBase58To25Bytes(addr);\n if (decoded == null)\n return false;\n\n byte[] hash1 = sha256(Arrays.copyOfRange(decoded, 0, 21));\n byte[] hash2 = sha256(hash1);\n\n return Arrays.equals(Arrays.copyOfRange(hash2, 0, 4), Arrays.copyOfRange(decoded, 21, 25));\n }\n\n private static byte[] decodeBase58To25Bytes(String input) {\n BigInteger num = BigInteger.ZERO;\n for (char t : input.toCharArray()) {\n int p = ALPHABET.indexOf(t);\n if (p == -1)\n return null;\n num = num.multiply(BigInteger.valueOf(58)).add(BigInteger.valueOf(p));\n }\n\n byte[] result = new byte[25];\n byte[] numBytes = num.toByteArray();\n System.arraycopy(numBytes, 0, result, result.length - numBytes.length, numBytes.length);\n return result;\n }\n\n private static byte[] sha256(byte[] data) {\n try {\n MessageDigest md = MessageDigest.getInstance(\"SHA-256\");\n md.update(data);\n return md.digest();\n } catch (NoSuchAlgorithmException e) {\n throw new IllegalStateException(e);\n }\n }\n\n public static void main(String[] args) {\n assertBitcoin(\"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i\", true);\n assertBitcoin(\"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62j\", false);\n assertBitcoin(\"1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9\", true);\n assertBitcoin(\"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62X\", false);\n assertBitcoin(\"1ANNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i\", false);\n assertBitcoin(\"1A Na15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i\", false);\n assertBitcoin(\"BZbvjr\", false);\n assertBitcoin(\"i55j\", false);\n assertBitcoin(\"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62!\", false);\n assertBitcoin(\"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62iz\", false);\n assertBitcoin(\"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62izz\", false);\n assertBitcoin(\"1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nJ9\", false);\n assertBitcoin(\"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62I\", false);\n }\n\n private static void assertBitcoin(String address, boolean expected) {\n boolean actual = validateBitcoinAddress(address);\n if (actual != expected)\n throw new AssertionError(String.format(\"Expected %s for %s, but got %s.\", expected, address, actual));\n }\n}"} {"title": "Box the compass", "language": "Java", "task": "Avast me hearties!\nThere be many a land lubber that knows naught of the pirate ways and gives direction by degree!\nThey know not how to box the compass! \n\n\n;Task description:\n# Create a function that takes a heading in degrees and returns the correct 32-point compass heading.\n# Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:\n:[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance).\n\n\n;Notes;\n* The headings and indices can be calculated from this pseudocode:\nfor i in 0..32 inclusive:\n heading = i * 11.25\n case i %3:\n if 1: heading += 5.62; break\n if 2: heading -= 5.62; break\n end\n index = ( i mod 32) + 1\n* The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..\n\n", "solution": "enum Compass {\n N, NbE, NNE, NEbN, NE, NEbE, ENE, EbN,\n E, EbS, ESE, SEbE, SE, SEbS, SSE, SbE,\n S, SbW, SSW, SWbS, SW, SWbW, WSW, WbS,\n W, WbN, WNW, NWbW, NW, NWbN, NNW, NbW;\n\n float midpoint() {\n float midpoint = (360 / 32f) * ordinal();\n return midpoint == 0 ? 360 : midpoint;\n }\n\n float[] bounds() {\n float bound = (360 / 32f) / 2f;\n float midpoint = midpoint();\n float boundA = midpoint - bound;\n float boundB = midpoint + bound;\n if (boundB > 360) boundB -= 360;\n return new float[] { boundA, boundB };\n }\n\n static Compass parse(float degrees) {\n float[] bounds;\n float[] boundsN = N.bounds();\n for (Compass value : Compass.values()) {\n bounds = value.bounds();\n if (degrees >= boundsN[0] || degrees < boundsN[1])\n return N;\n if (degrees >= bounds[0] && degrees < bounds[1])\n return value;\n }\n return null;\n }\n\n @Override\n public String toString() {\n String[] strings = new String[name().length()];\n int index = 0;\n for (char letter : name().toCharArray()) {\n switch (letter) {\n case 'N' -> strings[index] = \"north\";\n case 'E' -> strings[index] = \"east\";\n case 'S' -> strings[index] = \"south\";\n case 'W' -> strings[index] = \"west\";\n case 'b' -> strings[index] = \"by\";\n }\n index++;\n }\n String string\n = strings[0].substring(0, 1).toUpperCase() +\n strings[0].substring(1);\n switch (strings.length) {\n case 2 -> string += strings[1];\n case 3 -> {\n if (strings[1].equals(\"by\")) {\n string += \" %s %s\".formatted(strings[1], strings[2]);\n } else {\n string += \"-%s%s\".formatted(strings[1], strings[2]);\n }\n }\n case 4 -> {\n string += String.join(\" \", strings[1], strings[2], strings[3]);\n }\n }\n return string;\n }\n}\n"} {"title": "Brazilian numbers", "language": "Java", "task": "Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad ''Olimpiada Iberoamericana de Matematica'' in Fortaleza, Brazil.\n\nBrazilian numbers are defined as:\n\nThe set of positive integer numbers where each number '''N''' has at least one natural number '''B''' where '''1 < B < N-1''' where the representation of '''N''' in '''base B''' has all equal digits.\n\n\n;E.G.:\n\n:* '''1, 2 & 3''' can not be Brazilian; there is no base '''B''' that satisfies the condition '''1 < B < N-1'''.\n:* '''4''' is not Brazilian; '''4''' in '''base 2''' is '''100'''. The digits are not all the same.\n:* '''5''' is not Brazilian; '''5''' in '''base 2''' is '''101''', in '''base 3''' is '''12'''. There is no representation where the digits are the same.\n:* '''6''' is not Brazilian; '''6''' in '''base 2''' is '''110''', in '''base 3''' is '''20''', in '''base 4''' is '''12'''. There is no representation where the digits are the same.\n:* '''7''' ''is'' Brazilian; '''7''' in '''base 2''' is '''111'''. There is at least one representation where the digits are all the same.\n:* '''8''' ''is'' Brazilian; '''8''' in '''base 3''' is '''22'''. There is at least one representation where the digits are all the same.\n:* ''and so on...''\n\n\nAll even integers '''2P >= 8''' are Brazilian because '''2P = 2(P-1) + 2''', which is '''22''' in '''base P-1''' when '''P-1 > 2'''. That becomes true when '''P >= 4'''.\nMore common: for all all integers '''R''' and '''S''', where '''R > 1''' and also '''S-1 > R''', then '''R*S''' is Brazilian because '''R*S = R(S-1) + R''', which is '''RR''' in '''base S-1'''\nThe only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3. \nAll prime integers, that are brazilian, can only have the digit '''1'''. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of '''111''' to base Integer(sqrt(prime number)). Must be an odd count of '''1''' to stay odd like primes > 2\n\n;Task:\n\nWrite a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page;\n\n:* the first '''20''' Brazilian numbers;\n:* the first '''20 odd''' Brazilian numbers;\n:* the first '''20 prime''' Brazilian numbers;\n\n\n;See also:\n\n:* '''OEIS:A125134 - Brazilian numbers'''\n:* '''OEIS:A257521 - Odd Brazilian numbers'''\n:* '''OEIS:A085104 - Prime Brazilian numbers'''\n\n", "solution": "import java.math.BigInteger;\nimport java.util.List;\n\npublic class Brazilian {\n private static final List primeList = List.of(\n 2, 3, 5, 7, 9, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89,\n 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 169, 173, 179, 181,\n 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 247, 251, 257, 263, 269, 271, 277, 281,\n 283, 293, 299, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 377, 379, 383, 389,\n 397, 401, 403, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 481, 487, 491,\n 499, 503, 509, 521, 523, 533, 541, 547, 557, 559, 563, 569, 571, 577, 587, 593, 599, 601, 607,\n 611, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 689, 691, 701, 709, 719,\n 727, 733, 739, 743, 751, 757, 761, 767, 769, 773, 787, 793, 797, 809, 811, 821, 823, 827, 829,\n 839, 853, 857, 859, 863, 871, 877, 881, 883, 887, 907, 911, 919, 923, 929, 937, 941, 947, 949,\n 953, 967, 971, 977, 983, 991, 997\n );\n\n public static boolean isPrime(int n) {\n if (n < 2) {\n return false;\n }\n\n for (Integer prime : primeList) {\n if (n == prime) {\n return true;\n }\n if (n % prime == 0) {\n return false;\n }\n if (prime * prime > n) {\n return true;\n }\n }\n\n BigInteger bi = BigInteger.valueOf(n);\n return bi.isProbablePrime(10);\n }\n\n private static boolean sameDigits(int n, int b) {\n int f = n % b;\n while ((n /= b) > 0) {\n if (n % b != f) {\n return false;\n }\n }\n return true;\n }\n\n private static boolean isBrazilian(int n) {\n if (n < 7) return false;\n if (n % 2 == 0) return true;\n for (int b = 2; b < n - 1; ++b) {\n if (sameDigits(n, b)) {\n return true;\n }\n }\n return false;\n }\n\n public static void main(String[] args) {\n for (String kind : List.of(\"\", \"odd \", \"prime \")) {\n boolean quiet = false;\n int bigLim = 99_999;\n int limit = 20;\n System.out.printf(\"First %d %sBrazilian numbers:\\n\", limit, kind);\n int c = 0;\n int n = 7;\n while (c < bigLim) {\n if (isBrazilian(n)) {\n if (!quiet) System.out.printf(\"%d \", n);\n if (++c == limit) {\n System.out.println(\"\\n\");\n quiet = true;\n }\n }\n if (quiet && !\"\".equals(kind)) continue;\n switch (kind) {\n case \"\":\n n++;\n break;\n case \"odd \":\n n += 2;\n break;\n case \"prime \":\n do {\n n += 2;\n } while (!isPrime(n));\n break;\n default:\n throw new AssertionError(\"Oops\");\n }\n }\n if (\"\".equals(kind)) {\n System.out.printf(\"The %dth Brazilian number is: %d\\n\\n\", bigLim + 1, n);\n }\n }\n }\n}"} {"title": "Break OO privacy", "language": "Java", "task": "Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. \nThe intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism. \nThe intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.\n\nNote that cheating on your type system is almost universally regarded \nas unidiomatic at best, and poor programming practice at worst. \nNonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.\n", "solution": "Example example = new Example();\nMethod method = example.getClass().getDeclaredMethod(\"stringB\");\nmethod.setAccessible(true);\nString stringA = example.stringA;\nString stringB = (String) method.invoke(example);\nSystem.out.println(stringA + \" \" + stringB);\n"} {"title": "Brilliant numbers", "language": "Java from C++", "task": "'''Brilliant numbers''' are a subset of semiprime numbers. Specifically, they are numbers that are the product of exactly two prime numbers '''that both have the same number of digits when expressed in base 10'''.\n\n''Brilliant numbers are useful in cryptography and when testing prime factoring algorithms.''\n \n\n\n;E.G.\n* '''3 x 3''' (9) is a brilliant number. \n* '''2 x 7''' (14) is a brilliant number.\n* '''113 x 691''' (78083) is a brilliant number.\n* '''2 x 31''' (62) is semiprime, but is '''not''' a brilliant number (different number of digits in the two factors).\n\n\n\n;Task\n* Find and display the first 100 brilliant numbers.\n* For the orders of magnitude 1 through 6, find and show the first brilliant number greater than or equal to the order of magnitude, and, its position in the series (or the count of brilliant numbers up to that point).\n\n\n;Stretch\n* Continue for larger orders of magnitude.\n\n\n;See also\n;* Numbers Aplenty - Brilliant numbers\n;* OEIS:A078972 - Brilliant numbers: semiprimes whose prime factors have the same number of decimal digits\n", "solution": "import java.util.*;\n\npublic class BrilliantNumbers {\n public static void main(String[] args) {\n var primesByDigits = getPrimesByDigits(100000000);\n System.out.println(\"First 100 brilliant numbers:\");\n List brilliantNumbers = new ArrayList<>();\n for (var primes : primesByDigits) {\n int n = primes.size();\n for (int i = 0; i < n; ++i) {\n int prime1 = primes.get(i);\n for (int j = i; j < n; ++j) {\n int prime2 = primes.get(j);\n brilliantNumbers.add(prime1 * prime2);\n }\n }\n if (brilliantNumbers.size() >= 100)\n break;\n }\n Collections.sort(brilliantNumbers);\n for (int i = 0; i < 100; ++i) {\n char c = (i + 1) % 10 == 0 ? '\\n' : ' ';\n System.out.printf(\"%,5d%c\", brilliantNumbers.get(i), c);\n }\n System.out.println();\n long power = 10;\n long count = 0;\n for (int p = 1; p < 2 * primesByDigits.size(); ++p) {\n var primes = primesByDigits.get(p / 2);\n long position = count + 1;\n long minProduct = 0;\n int n = primes.size();\n for (int i = 0; i < n; ++i) {\n long prime1 = primes.get(i);\n var primes2 = primes.subList(i, n);\n int q = (int)((power + prime1 - 1) / prime1);\n int j = Collections.binarySearch(primes2, q);\n if (j == n)\n continue;\n if (j < 0)\n j = -(j + 1);\n long prime2 = primes2.get(j);\n long product = prime1 * prime2;\n if (minProduct == 0 || product < minProduct)\n minProduct = product;\n position += j;\n if (prime1 >= prime2)\n break;\n }\n System.out.printf(\"First brilliant number >= 10^%d is %,d at position %,d\\n\",\n p, minProduct, position);\n power *= 10;\n if (p % 2 == 1) {\n long size = primes.size();\n count += size * (size + 1) / 2;\n }\n }\n }\n\n private static List> getPrimesByDigits(int limit) {\n PrimeGenerator primeGen = new PrimeGenerator(100000, 100000);\n List> primesByDigits = new ArrayList<>();\n List primes = new ArrayList<>();\n for (int p = 10; p <= limit; ) {\n int prime = primeGen.nextPrime();\n if (prime > p) {\n primesByDigits.add(primes);\n primes = new ArrayList<>();\n p *= 10;\n }\n primes.add(prime);\n }\n return primesByDigits;\n }\n}"} {"title": "Burrows\u2013Wheeler transform", "language": "Java from Kotlin", "task": "{{Wikipedia|Burrows-Wheeler_transform}}\n\n\nThe Burrows-Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters. \n\nThis is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding. \n\nMore importantly, the transformation is reversible, without needing to store any additional data. \n\nThe BWT is thus a \"free\" method of improving the efficiency of text compression algorithms, costing only some extra computation.\n\n\nSource: Burrows-Wheeler transform\n\n", "solution": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class BWT {\n private static final String STX = \"\\u0002\";\n private static final String ETX = \"\\u0003\";\n\n private static String bwt(String s) {\n if (s.contains(STX) || s.contains(ETX)) {\n throw new IllegalArgumentException(\"String cannot contain STX or ETX\");\n }\n\n String ss = STX + s + ETX;\n List table = new ArrayList<>();\n for (int i = 0; i < ss.length(); i++) {\n String before = ss.substring(i);\n String after = ss.substring(0, i);\n table.add(before + after);\n }\n table.sort(String::compareTo);\n\n StringBuilder sb = new StringBuilder();\n for (String str : table) {\n sb.append(str.charAt(str.length() - 1));\n }\n return sb.toString();\n }\n\n private static String ibwt(String r) {\n int len = r.length();\n List table = new ArrayList<>();\n for (int i = 0; i < len; ++i) {\n table.add(\"\");\n }\n for (int j = 0; j < len; ++j) {\n for (int i = 0; i < len; ++i) {\n table.set(i, r.charAt(i) + table.get(i));\n }\n table.sort(String::compareTo);\n }\n for (String row : table) {\n if (row.endsWith(ETX)) {\n return row.substring(1, len - 1);\n }\n }\n return \"\";\n }\n\n private static String makePrintable(String s) {\n // substitute ^ for STX and | for ETX to print results\n return s.replace(STX, \"^\").replace(ETX, \"|\");\n }\n\n public static void main(String[] args) {\n List tests = List.of(\n \"banana\",\n \"appellee\",\n \"dogwood\",\n \"TO BE OR NOT TO BE OR WANT TO BE OR NOT?\",\n \"SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES\",\n \"\\u0002ABC\\u0003\"\n );\n for (String test : tests) {\n System.out.println(makePrintable(test));\n System.out.print(\" --> \");\n String t = \"\";\n try {\n t = bwt(test);\n System.out.println(makePrintable(t));\n } catch (IllegalArgumentException e) {\n System.out.println(\"ERROR: \" + e.getMessage());\n }\n String r = ibwt(t);\n System.out.printf(\" --> %s\\n\\n\", r);\n }\n }\n}"} {"title": "CSV data manipulation", "language": "Java", "task": "CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. \n\nThe CSV format is flexible but somewhat ill-defined. \n\nFor present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.\n\n\n;Task:\nRead a CSV file, change some values and save the changes back to a file.\n\nFor this task we will use the following CSV file:\n\n C1,C2,C3,C4,C5\n 1,5,9,13,17\n 2,6,10,14,18\n 3,7,11,15,19\n 4,8,12,16,20\n\nSuggestions\n\n Show how to add a column, headed 'SUM', of the sums of the rows.\n If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.\n\n\n", "solution": "import java.io.*;\nimport java.awt.Point;\nimport java.util.HashMap;\nimport java.util.Scanner;\n\npublic class CSV {\n\n private HashMap _map = new HashMap();\n private int _cols;\n private int _rows;\n\n public void open(File file) throws FileNotFoundException, IOException {\n open(file, ',');\n }\n\n public void open(File file, char delimiter)\n throws FileNotFoundException, IOException {\n Scanner scanner = new Scanner(file);\n scanner.useDelimiter(Character.toString(delimiter));\n\n clear();\n\n while(scanner.hasNextLine()) {\n String[] values = scanner.nextLine().split(Character.toString(delimiter));\n\n int col = 0;\n for ( String value: values ) {\n _map.put(new Point(col, _rows), value);\n _cols = Math.max(_cols, ++col);\n }\n _rows++;\n }\n scanner.close();\n }\n\n public void save(File file) throws IOException {\n save(file, ',');\n }\n\n public void save(File file, char delimiter) throws IOException {\n FileWriter fw = new FileWriter(file);\n BufferedWriter bw = new BufferedWriter(fw);\n\n for (int row = 0; row < _rows; row++) {\n for (int col = 0; col < _cols; col++) {\n Point key = new Point(col, row);\n if (_map.containsKey(key)) {\n bw.write(_map.get(key));\n }\n\n if ((col + 1) < _cols) {\n bw.write(delimiter);\n }\n }\n bw.newLine();\n }\n bw.flush();\n bw.close();\n }\n\n public String get(int col, int row) {\n String val = \"\";\n Point key = new Point(col, row);\n if (_map.containsKey(key)) {\n val = _map.get(key);\n }\n return val;\n }\n\n public void put(int col, int row, String value) {\n _map.put(new Point(col, row), value);\n _cols = Math.max(_cols, col+1);\n _rows = Math.max(_rows, row+1);\n }\n\n public void clear() {\n _map.clear();\n _cols = 0;\n _rows = 0;\n }\n\n public int rows() {\n return _rows;\n }\n\n public int cols() {\n return _cols;\n }\n\n public static void main(String[] args) {\n try {\n CSV csv = new CSV();\n\n csv.open(new File(\"test_in.csv\"));\n csv.put(0, 0, \"Column0\");\n csv.put(1, 1, \"100\");\n csv.put(2, 2, \"200\");\n csv.put(3, 3, \"300\");\n csv.put(4, 4, \"400\");\n csv.save(new File(\"test_out.csv\"));\n } catch (Exception e) {\n }\n }\n}"} {"title": "CSV to HTML translation", "language": "Java", "task": "Consider a simplified CSV format where all rows are separated by a newline \nand all columns are separated by commas. \n\nNo commas are allowed as field data, but the data may contain \nother characters and character sequences that would \nnormally be ''escaped'' when converted to HTML\n\n\n;Task:\nCreate a function that takes a string representation of the CSV data\nand returns a text string of an HTML table representing the CSV data. \n\nUse the following data as the CSV text to convert, and show your output.\n: Character,Speech\n: The multitude,The messiah! Show us the messiah!\n: Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!\n: The multitude,Who are you?\n: Brians mother,I'm his mother; that's who!\n: The multitude,Behold his mother! Behold his mother!\n\n\n;Extra credit:\n''Optionally'' allow special formatting for the first row of the table as if it is the tables header row \n(via preferably; CSS if you must).\n\n", "solution": "import java.io.BufferedReader;\nimport java.io.InputStreamReader;\nimport java.io.PrintStream;\n\nclass Csv2Html {\n\n\tpublic static String escapeChars(String lineIn) {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tint lineLength = lineIn.length();\n\t\tfor (int i = 0; i < lineLength; i++) {\n\t\t\tchar c = lineIn.charAt(i);\n\t\t\tswitch (c) {\n\t\t\t\tcase '\"': \n\t\t\t\t\tsb.append(\""\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase '&':\n\t\t\t\t\tsb.append(\"&\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase '\\'':\n\t\t\t\t\tsb.append(\"'\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase '<':\n\t\t\t\t\tsb.append(\"<\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase '>':\n\t\t\t\t\tsb.append(\">\");\n\t\t\t\t\tbreak;\n\t\t\t\tdefault: sb.append(c);\n\t\t\t}\n\t\t}\n\t\treturn sb.toString();\n\t}\n\n\tpublic static void tableHeader(PrintStream ps, String[] columns) {\n\t\tps.print(\"\");\n\t\tfor (int i = 0; i < columns.length; i++) {\n\t\t\tps.print(\"\");\n\t\t\tps.print(columns[i]);\n\t\t\tps.print(\"\");\n\t\t}\n\t\tps.println(\"\");\n\t}\n\t\n\tpublic static void tableRow(PrintStream ps, String[] columns) {\n\t\tps.print(\"\");\n\t\tfor (int i = 0; i < columns.length; i++) {\n\t\t\tps.print(\"\");\n\t\t\tps.print(columns[i]);\n\t\t\tps.print(\"\");\n\t\t}\n\t\tps.println(\"\");\n\t}\n\t\n\tpublic static void main(String[] args) throws Exception {\n\t\tboolean withTableHeader = (args.length != 0);\n\t\t\n\t\tInputStreamReader isr = new InputStreamReader(System.in);\n\t\tBufferedReader br = new BufferedReader(isr);\n\t\tPrintStream stdout = System.out;\n\t\t\n\t\tstdout.println(\"\");\n\t\tstdout.println(\"\");\n\t\tstdout.println(\"\");\n\t\tstdout.println(\"Csv2Html\");\n\t\tstdout.println(\"\");\n\t\tstdout.println(\"

Csv2Html

\");\n\n\t\tstdout.println(\"\");\n\t\tString stdinLine;\n\t\tboolean firstLine = true;\n\t\twhile ((stdinLine = br.readLine()) != null) {\n\t\t\tString[] columns = escapeChars(stdinLine).split(\",\");\n\t\t\tif (withTableHeader == true && firstLine == true) {\n\t\t\t\ttableHeader(stdout, columns);\n\t\t\t\tfirstLine = false;\n\t\t\t} else {\n\t\t\t\ttableRow(stdout, columns);\n\t\t\t}\n\t\t}\n\t\tstdout.println(\"
\");\n\t}\n}\n"} {"title": "Calculating the value of e", "language": "Java", "task": "Calculate the value of ''e''.\n\n\n(''e'' is also known as ''Euler's number'' and ''Napier's constant''.)\n\n\nSee details: Calculating the value of e\n\n", "solution": "BigDecimal e(BigInteger limit, int scale) {\n BigDecimal e = BigDecimal.ONE.setScale(scale, HALF_UP);\n BigDecimal n;\n BigInteger term = BigInteger.ONE;\n while (term.compareTo(limit) <= 0) {\n n = new BigDecimal(String.valueOf(factorial(term)));\n e = e.add(BigDecimal.ONE.divide(n, scale, HALF_UP));\n term = term.add(BigInteger.ONE);\n }\n return e;\n}\n\nBigInteger factorial(BigInteger value) {\n if (value.compareTo(BigInteger.ONE) > 0) {\n return value.multiply(factorial(value.subtract(BigInteger.ONE)));\n } else {\n return BigInteger.ONE;\n }\n}\n"} {"title": "Calculating the value of e", "language": "Java from Kotlin", "task": "Calculate the value of ''e''.\n\n\n(''e'' is also known as ''Euler's number'' and ''Napier's constant''.)\n\n\nSee details: Calculating the value of e\n\n", "solution": "public class CalculateE {\n public static final double EPSILON = 1.0e-15;\n\n public static void main(String[] args) {\n long fact = 1;\n double e = 2.0;\n int n = 2;\n double e0;\n do {\n e0 = e;\n fact *= n++;\n e += 1.0 / fact;\n } while (Math.abs(e - e0) >= EPSILON);\n System.out.printf(\"e = %.15f\\n\", e);\n }\n}"} {"title": "Calkin-Wilf sequence", "language": "Java", "task": "The '''Calkin-Wilf sequence''' contains every nonnegative rational number exactly once. \n\nIt can be calculated recursively as follows:\n\n {{math|a1}} = {{math|1}} \n {{math|an+1}} = {{math|1/(2an+1-an)}} for n > 1 \n\n\n;Task part 1:\n* Show on this page terms 1 through 20 of the Calkin-Wilf sequence.\n\nTo avoid floating point error, you may want to use a rational number data type.\n\n\nIt is also possible, given a non-negative rational number, to determine where it appears in the sequence without calculating the sequence. The procedure is to get the continued fraction representation of the rational and use it as the run-length encoding of the binary representation of the term number, beginning from the end of the continued fraction. \nIt only works if the number of terms in the continued fraction is odd- use either of the two equivalent representations to achieve this:\n\n {{math|[a0; a1, a2, ..., an]}} = {{math|[a0; a1, a2 ,..., an-1, 1]}} \n\n\n;Example:\nThe fraction '''9/4''' has odd continued fraction representation {{math|2; 3, 1}}, giving a binary representation of '''100011''', \nwhich means '''9/4''' appears as the '''35th''' term of the sequence.\n\n\n;Task part 2:\n* Find the position of the number '''83116''''''/''''''51639''' in the Calkin-Wilf sequence.\n\n\n;See also:\n* Wikipedia entry: Calkin-Wilf tree\n* [[Continued fraction]]\n* [[Continued fraction/Arithmetic/Construct from rational number]]\n\n", "solution": "import java.util.ArrayDeque;\nimport java.util.Deque;\n\npublic final class CalkinWilfSequence {\n\n\tpublic static void main(String[] aArgs) {\n\t\tRational term = Rational.ONE;\n\t System.out.println(\"First 20 terms of the Calkin-Wilf sequence are:\");\n\t for ( int i = 1; i <= 20; i++ ) {\n\t \tSystem.out.println(String.format(\"%2d\", i) + \": \" + term);\n\t \tterm = nextCalkinWilf(term);\n\t }\n\t System.out.println();\n\t \n\t Rational rational = new Rational(83_116, 51_639);\n\t System.out.println(\" \" + rational + \" is the \" + termIndex(rational) + \"th term of the sequence.\");\n\n\t}\n\t\n\tprivate static Rational nextCalkinWilf(Rational aTerm) {\n\t\tRational divisor = Rational.TWO.multiply(aTerm.floor()).add(Rational.ONE).subtract(aTerm);\n\t\treturn Rational.ONE.divide(divisor);\n\t}\n\t\n\tprivate static long termIndex(Rational aRational) {\n\t long result = 0;\n\t long binaryDigit = 1;\n\t long power = 0;\n\t for ( long term : continuedFraction(aRational) ) {\n\t for ( long i = 0; i < term; power++, i++ ) {\n\t result |= ( binaryDigit << power );\n\t }\n\t binaryDigit = ( binaryDigit == 0 ) ? 1 : 0;\n\t }\n\t return result;\n\t}\n\t\n\tprivate static Deque continuedFraction(Rational aRational) {\n\t long numerator = aRational.numerator();\n\t long denominator = aRational.denominator();\n\t Deque result = new ArrayDeque();\n\t \n\t while ( numerator != 1 ) {\n\t result.addLast(numerator / denominator);\n\t long copyNumerator = numerator;\n\t numerator = denominator;\n\t denominator = copyNumerator % denominator;\n\t }\n\t \n\t if ( ! result.isEmpty() && result.size() % 2 == 0 ) {\n\t \tfinal long back = result.removeLast();\n\t \tresult.addLast(back - 1);\n\t result.addLast(1L);\n\t }\n\t return result;\n\t}\n\n}\n\nfinal class Rational {\n\t\n\tpublic Rational(long aNumerator, long aDenominator) {\n \tif ( aDenominator == 0 ) {\n \t\tthrow new ArithmeticException(\"Denominator cannot be zero\");\n \t} \n \tif ( aNumerator == 0 ) {\n \t\taDenominator = 1;\n \t}\n \tif ( aDenominator < 0 ) {\n \t\tnumer = -aNumerator;\n \t\tdenom = -aDenominator;\n \t} else {\n \t\tnumer = aNumerator;\n \t\tdenom = aDenominator;\n \t} \t\n \tfinal long gcd = gcd(numer, denom);\n \tnumer = numer / gcd;\n \tdenom = denom / gcd;\n }\n\t\n\tpublic Rational add(Rational aOther) {\n \treturn new Rational(numer * aOther.denom + aOther.numer * denom, denom * aOther.denom);\n }\n\t\n\tpublic Rational subtract(Rational aOther) {\n\t\treturn new Rational(numer * aOther.denom - aOther.numer * denom, denom * aOther.denom);\n\t} \n \n public Rational multiply(Rational aOther) {\n\t\treturn new Rational(numer * aOther.numer, denom * aOther.denom);\n\t}\n \n public Rational divide(Rational aOther) {\n\t\treturn new Rational(numer * aOther.denom, denom * aOther.numer);\n\t}\n \n public Rational floor() {\n \treturn new Rational(numer / denom, 1);\n }\n \n public long numerator() {\n \treturn numer;\n }\n \n public long denominator() {\n \treturn denom;\n }\n \n @Override\n public String toString() {\n \treturn numer + \"/\" + denom;\n }\n \n public static final Rational ONE = new Rational(1, 1);\n public static final Rational TWO = new Rational(2, 1);\n \n private long gcd(long aOne, long aTwo) {\n \tif ( aTwo == 0 ) {\n \t\treturn aOne;\n \t}\n \treturn gcd(aTwo, aOne % aTwo);\n }\n \n private long numer;\n private long denom;\n \n}\n"} {"title": "Call a function", "language": "Java", "task": "Demonstrate the different syntax and semantics provided for calling a function. \n\n\nThis may include:\n:* Calling a function that requires no arguments\n:* Calling a function with a fixed number of arguments\n:* Calling a function with optional arguments\n:* Calling a function with a variable number of arguments\n:* Calling a function with named arguments\n:* Using a function in statement context\n:* Using a function in first-class context within an expression\n:* Obtaining the return value of a function\n:* Distinguishing built-in functions and user-defined functions\n:* Distinguishing subroutines and functions\n;* Stating whether arguments are passed by value or by reference\n;* Is partial application possible and how\n\n\nThis task is ''not'' about defining functions.\n\n", "solution": "int myMethod( Map params ){\n return\n ((Integer)params.get(\"x\")).intValue()\n + ((Integer)params.get(\"y\")).intValue();\n}"} {"title": "Canonicalize CIDR", "language": "Java", "task": "Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form. \n\nThat is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address.\n\n\n;Example:\nGiven '''87.70.141.1/22''', your code should output '''87.70.140.0/22'''\n\n\n;Explanation:\nAn Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 digit is given in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the network portion of the address, while the rightmost (least-significant) bits determine the host portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion.\n\nIn general, CIDR blocks stand in for the entire set of IP addresses sharing the same network component, so it's common to see access control lists that specify individual IP addresses using /32 to indicate that only the one address is included. Software accepting this notation as input often expects it to be entered in canonical form, in which the host bits are all zeroes. But network admins sometimes skip this step and just enter the address of a specific host on the subnet with the network size, resulting in a non-canonical entry.\n\nThe example address, 87.70.141.1/22, represents binary 0101011101000110100011 / 0100000001, with the / indicating the network/host division. To canonicalize, clear all the bits to the right of the / and convert back to dotted decimal: 0101011101000110100011 / 0000000000 - 87.70.140.0.\n\n\n;More examples for testing\n\n 36.18.154.103/12 - 36.16.0.0/12\n 62.62.197.11/29 - 62.62.197.8/29\n 67.137.119.181/4 - 64.0.0.0/4\n 161.214.74.21/24 - 161.214.74.0/24\n 184.232.176.184/18 - 184.232.128.0/18\n\n\n", "solution": "import java.text.MessageFormat;\nimport java.text.ParseException;\n\npublic class CanonicalizeCIDR {\n public static void main(String[] args) {\n for (String test : TESTS) {\n try {\n CIDR cidr = new CIDR(test);\n System.out.printf(\"%-18s -> %s\\n\", test, cidr.toString());\n } catch (Exception ex) {\n System.err.printf(\"Error parsing '%s': %s\\n\", test, ex.getLocalizedMessage());\n }\n }\n }\n\n private static class CIDR {\n private CIDR(int address, int maskLength) {\n this.address = address;\n this.maskLength = maskLength;\n }\n\n private CIDR(String str) throws Exception {\n Object[] args = new MessageFormat(FORMAT).parse(str);\n int address = 0;\n for (int i = 0; i < 4; ++i) {\n int a = ((Number)args[i]).intValue();\n if (a < 0 || a > 255)\n throw new Exception(\"Invalid IP address\");\n address <<= 8;\n address += a;\n }\n int maskLength = ((Number)args[4]).intValue();\n if (maskLength < 1 || maskLength > 32)\n throw new Exception(\"Invalid mask length\");\n int mask = ~((1 << (32 - maskLength)) - 1);\n this.address = address & mask;\n this.maskLength = maskLength;\n }\n\n public String toString() {\n int address = this.address;\n int d = address & 0xFF;\n address >>= 8;\n int c = address & 0xFF;\n address >>= 8;\n int b = address & 0xFF;\n address >>= 8;\n int a = address & 0xFF;\n Object[] args = { a, b, c, d, maskLength };\n return new MessageFormat(FORMAT).format(args);\n }\n\n private int address;\n private int maskLength;\n private static final String FORMAT = \"{0,number,integer}.{1,number,integer}.{2,number,integer}.{3,number,integer}/{4,number,integer}\";\n };\n\n private static final String[] TESTS = {\n \"87.70.141.1/22\",\n \"36.18.154.103/12\",\n \"62.62.197.11/29\",\n \"67.137.119.181/4\",\n \"161.214.74.21/24\",\n \"184.232.176.184/18\"\n };\n}"} {"title": "Cantor set", "language": "Java from Kotlin", "task": "Draw a Cantor set.\n\n\nSee details at this Wikipedia webpage: Cantor set\n\n", "solution": "public class App {\n private static final int WIDTH = 81;\n private static final int HEIGHT = 5;\n\n private static char[][] lines;\n static {\n lines = new char[HEIGHT][WIDTH];\n for (int i = 0; i < HEIGHT; i++) {\n for (int j = 0; j < WIDTH; j++) {\n lines[i][j] = '*';\n }\n }\n }\n\n private static void cantor(int start, int len, int index) {\n int seg = len / 3;\n if (seg == 0) return;\n for (int i = index; i < HEIGHT; i++) {\n for (int j = start + seg; j < start + seg * 2; j++) {\n lines[i][j] = ' ';\n }\n }\n cantor(start, seg, index + 1);\n cantor(start + seg * 2, seg, index + 1);\n }\n\n public static void main(String[] args) {\n cantor(0, WIDTH, 1);\n for (int i = 0; i < HEIGHT; i++) {\n for (int j = 0; j < WIDTH; j++) {\n System.out.print(lines[i][j]);\n }\n System.out.println();\n }\n }\n}\n"} {"title": "Cartesian product of two or more lists", "language": "Java Virtual Machine 1.8", "task": "Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.\n\nDemonstrate that your function/method correctly returns:\n::{1, 2} x {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}\n\nand, in contrast:\n::{3, 4} x {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}\n\nAlso demonstrate, using your function/method, that the product of an empty list with any other list is empty.\n:: {1, 2} x {} = {}\n:: {} x {1, 2} = {}\n\nFor extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.\n\nUse your n-ary Cartesian product function to show the following products:\n:: {1776, 1789} x {7, 12} x {4, 14, 23} x {0, 1}\n:: {1, 2, 3} x {30} x {500, 100}\n:: {1, 2, 3} x {} x {500, 100}\n\n\n", "solution": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class CartesianProduct {\n\n\tpublic List> product(List> lists) {\n\t\tList> product = new ArrayList<>();\n\n\t\t// We first create a list for each value of the first list\n\t\tproduct(product, new ArrayList<>(), lists);\n\n\t\treturn product;\n\t}\n\n\tprivate void product(List> result, List existingTupleToComplete, List> valuesToUse) {\n\t\tfor (V value : valuesToUse.get(0)) {\n\t\t\tList newExisting = new ArrayList<>(existingTupleToComplete);\n\t\t\tnewExisting.add(value);\n\n\t\t\t// If only one column is left\n\t\t\tif (valuesToUse.size() == 1) {\n\t\t\t\t// We create a new list with the exiting tuple for each value with the value\n\t\t\t\t// added\n\t\t\t\tresult.add(newExisting);\n\t\t\t} else {\n\t\t\t\t// If there are still several columns, we go into recursion for each value\n\t\t\t\tList> newValues = new ArrayList<>();\n\t\t\t\t// We build the next level of values\n\t\t\t\tfor (int i = 1; i < valuesToUse.size(); i++) {\n\t\t\t\t\tnewValues.add(valuesToUse.get(i));\n\t\t\t\t}\n\n\t\t\t\tproduct(result, newExisting, newValues);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tList list1 = new ArrayList<>(Arrays.asList(new Integer[] { 1776, 1789 }));\n\t\tList list2 = new ArrayList<>(Arrays.asList(new Integer[] { 7, 12 }));\n\t\tList list3 = new ArrayList<>(Arrays.asList(new Integer[] { 4, 14, 23 }));\n\t\tList list4 = new ArrayList<>(Arrays.asList(new Integer[] { 0, 1 }));\n\n\t\tList> input = new ArrayList<>();\n\t\tinput.add(list1);\n\t\tinput.add(list2);\n\t\tinput.add(list3);\n\t\tinput.add(list4);\n\n\t\tCartesianProduct cartesianProduct = new CartesianProduct<>();\n\t\tList> product = cartesianProduct.product(input);\n\t\tSystem.out.println(product);\n\t}\n}\n"} {"title": "Casting out nines", "language": "Java 8", "task": "Task (in three parts):\n\n\n;Part 1\nWrite a procedure (say \\mathit{co9}(x)) which implements Casting Out Nines as described by returning the checksum for x. Demonstrate the procedure using the examples given there, or others you may consider lucky.\n\nNote that this function does nothing more than calculate the least positive residue, modulo 9. Many of the solutions omit Part 1 for this reason. Many languages have a modulo operator, of which this is a trivial application.\n\nWith that understanding, solutions to Part 1, if given, are encouraged to follow the naive pencil-and-paper or mental arithmetic of repeated digit addition understood to be \"casting out nines\", or some approach other than just reducing modulo 9 using a built-in operator. Solutions for part 2 and 3 are not required to make use of the function presented in part 1.\n\n;Part 2\nNotwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure:\n: Consider the statement \"318682 is 101558 + 217124 and squared is 101558217124\" (see: [[Kaprekar numbers#Casting Out Nines (fast)]]).\n: note that 318682 has the same checksum as (101558 + 217124);\n: note that 101558217124 has the same checksum as (101558 + 217124) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes);\n: note that this implies that for Kaprekar numbers the checksum of k equals the checksum of k^2.\n\nDemonstrate that your procedure can be used to generate or filter a range of numbers with the property \\mathit{co9}(k) = \\mathit{co9}(k^2) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.\n\n;Part 3\nConsidering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing:\n: \\mathit{co9}(x) is the residual of x mod 9;\n: the procedure can be extended to bases other than 9.\n\nDemonstrate your algorithm by generating or filtering a range of numbers with the property k%(\\mathit{Base}-1) == (k^2)%(\\mathit{Base}-1) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.\n\n;related tasks\n* [[First perfect square in base N with N unique digits]]\n* [[Kaprekar numbers]]\n\n", "solution": "import java.util.*;\nimport java.util.stream.IntStream;\n\npublic class CastingOutNines {\n\n public static void main(String[] args) {\n System.out.println(castOut(16, 1, 255));\n System.out.println(castOut(10, 1, 99));\n System.out.println(castOut(17, 1, 288));\n }\n\n static List castOut(int base, int start, int end) {\n int[] ran = IntStream\n .range(0, base - 1)\n .filter(x -> x % (base - 1) == (x * x) % (base - 1))\n .toArray();\n\n int x = start / (base - 1);\n\n List result = new ArrayList<>();\n while (true) {\n for (int n : ran) {\n int k = (base - 1) * x + n;\n if (k < start)\n continue;\n if (k > end)\n return result;\n result.add(k);\n }\n x++;\n }\n }\n}"} {"title": "Catalan numbers/Pascal's triangle", "language": "Java from C++", "task": "Print out the first '''15''' Catalan numbers by extracting them from Pascal's triangle.\n\n\n;See:\n* Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.\n\n* Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.\n* Sequence A000108 on OEIS has a lot of information on Catalan Numbers.\n\n;Related Tasks:\n[[Pascal's triangle]]\n\n", "solution": "public class Test {\n public static void main(String[] args) {\n int N = 15;\n int[] t = new int[N + 2];\n t[1] = 1;\n\n for (int i = 1; i <= N; i++) {\n\n for (int j = i; j > 1; j--)\n t[j] = t[j] + t[j - 1];\n\n t[i + 1] = t[i];\n\n for (int j = i + 1; j > 1; j--)\n t[j] = t[j] + t[j - 1];\n\n System.out.printf(\"%d \", t[i + 1] - t[i]);\n }\n }\n}"} {"title": "Catamorphism", "language": "Java 8", "task": "''Reduce'' is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. \n\n\n;Task:\nShow how ''reduce'' (or ''foldl'' or ''foldr'' etc), work (or would be implemented) in your language.\n\n\n;See also:\n* Wikipedia article: Fold\n* Wikipedia article: Catamorphism\n\n", "solution": "import java.util.stream.Stream;\n\npublic class ReduceTask {\n\n public static void main(String[] args) {\n System.out.println(Stream.of(1, 2, 3, 4, 5).mapToInt(i -> i).sum());\n System.out.println(Stream.of(1, 2, 3, 4, 5).reduce(1, (a, b) -> a * b));\n }\n}"} {"title": "Chaocipher", "language": "Java from Kotlin", "task": "Description:\nThe Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.\n\nThe algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.\n\n\n;Task:\nCode the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.\n\n", "solution": "import java.util.Arrays;\n\npublic class Chaocipher {\n private enum Mode {\n ENCRYPT,\n DECRYPT\n }\n\n private static final String L_ALPHABET = \"HXUCZVAMDSLKPEFJRIGTWOBNYQ\";\n private static final String R_ALPHABET = \"PTLNBQDEOYSFAVZKGJRIHWXUMC\";\n\n private static int indexOf(char[] a, char c) {\n for (int i = 0; i < a.length; ++i) {\n if (a[i] == c) {\n return i;\n }\n }\n return -1;\n }\n\n private static String exec(String text, Mode mode) {\n return exec(text, mode, false);\n }\n\n private static String exec(String text, Mode mode, Boolean showSteps) {\n char[] left = L_ALPHABET.toCharArray();\n char[] right = R_ALPHABET.toCharArray();\n char[] eText = new char[text.length()];\n char[] temp = new char[26];\n\n for (int i = 0; i < text.length(); ++i) {\n if (showSteps) {\n System.out.printf(\"%s %s\\n\", new String(left), new String(right));\n }\n int index;\n if (mode == Mode.ENCRYPT) {\n index = indexOf(right, text.charAt(i));\n eText[i] = left[index];\n } else {\n index = indexOf(left, text.charAt(i));\n eText[i] = right[index];\n }\n if (i == text.length() - 1) {\n break;\n }\n\n // permute left\n\n if (26 - index >= 0) System.arraycopy(left, index, temp, 0, 26 - index);\n System.arraycopy(left, 0, temp, 26 - index, index);\n char store = temp[1];\n System.arraycopy(temp, 2, temp, 1, 12);\n temp[13] = store;\n left = Arrays.copyOf(temp, temp.length);\n\n // permute right\n\n if (26 - index >= 0) System.arraycopy(right, index, temp, 0, 26 - index);\n System.arraycopy(right, 0, temp, 26 - index, index);\n store = temp[0];\n System.arraycopy(temp, 1, temp, 0, 25);\n temp[25] = store;\n store = temp[2];\n System.arraycopy(temp, 3, temp, 2, 11);\n temp[13] = store;\n right = Arrays.copyOf(temp, temp.length);\n }\n\n return new String(eText);\n }\n\n public static void main(String[] args) {\n String plainText = \"WELLDONEISBETTERTHANWELLSAID\";\n System.out.printf(\"The original plaintext is : %s\\n\", plainText);\n System.out.println(\"\\nThe left and right alphabets after each permutation during encryption are:\");\n String cipherText = exec(plainText, Mode.ENCRYPT, true);\n System.out.printf(\"\\nThe cipher text is : %s\\n\", cipherText);\n String plainText2 = exec(cipherText, Mode.DECRYPT);\n System.out.printf(\"\\nThe recovered plaintext is : %s\\n\", plainText2);\n }\n}"} {"title": "Chaos game", "language": "Java 8", "task": "The Chaos Game is a method of generating the attractor of an iterated function system (IFS). \n\nOne of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.\n\n\n;Task\nPlay the Chaos Game using the corners of an equilateral triangle as the reference points. Add a starting point at random (preferably inside the triangle). Then add the next point halfway between the starting point and one of the reference points. This reference point is chosen at random.\n\nAfter a sufficient number of iterations, the image of a Sierpinski Triangle should emerge.\n\n\n;See also\n* The Game of Chaos\n\n", "solution": "import java.awt.*;\nimport java.awt.event.*;\nimport java.util.*;\nimport javax.swing.*;\nimport javax.swing.Timer;\n\npublic class ChaosGame extends JPanel {\n static class ColoredPoint extends Point {\n int colorIndex;\n\n ColoredPoint(int x, int y, int idx) {\n super(x, y);\n colorIndex = idx;\n }\n }\n\n Stack stack = new Stack<>();\n Point[] points = new Point[3];\n Color[] colors = {Color.red, Color.green, Color.blue};\n Random r = new Random();\n\n public ChaosGame() {\n Dimension dim = new Dimension(640, 640);\n setPreferredSize(dim);\n setBackground(Color.white);\n\n int margin = 60;\n int size = dim.width - 2 * margin;\n\n points[0] = new Point(dim.width / 2, margin);\n points[1] = new Point(margin, size);\n points[2] = new Point(margin + size, size);\n\n stack.push(new ColoredPoint(-1, -1, 0));\n\n new Timer(10, (ActionEvent e) -> {\n if (stack.size() < 50_000) {\n for (int i = 0; i < 1000; i++)\n addPoint();\n repaint();\n }\n }).start();\n }\n\n private void addPoint() {\n try {\n int colorIndex = r.nextInt(3);\n Point p1 = stack.peek();\n Point p2 = points[colorIndex];\n stack.add(halfwayPoint(p1, p2, colorIndex));\n } catch (EmptyStackException e) {\n e.printStackTrace();\n }\n }\n\n void drawPoints(Graphics2D g) {\n for (ColoredPoint p : stack) {\n g.setColor(colors[p.colorIndex]);\n g.fillOval(p.x, p.y, 1, 1);\n }\n }\n\n ColoredPoint halfwayPoint(Point a, Point b, int idx) {\n return new ColoredPoint((a.x + b.x) / 2, (a.y + b.y) / 2, idx);\n }\n\n @Override\n public void paintComponent(Graphics gg) {\n super.paintComponent(gg);\n Graphics2D g = (Graphics2D) gg;\n g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n RenderingHints.VALUE_ANTIALIAS_ON);\n\n drawPoints(g);\n }\n\n public static void main(String[] args) {\n SwingUtilities.invokeLater(() -> {\n JFrame f = new JFrame();\n f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n f.setTitle(\"Chaos Game\");\n f.setResizable(false);\n f.add(new ChaosGame(), BorderLayout.CENTER);\n f.pack();\n f.setLocationRelativeTo(null);\n f.setVisible(true);\n });\n }\n}"} {"title": "Check Machin-like formulas", "language": "Java", "task": "Machin-like formulas are useful for efficiently computing numerical approximations for \\pi\n\n\n;Task:\nVerify the following Machin-like formulas are correct by calculating the value of '''tan''' (''right hand side)'' for each equation using exact arithmetic and showing they equal '''1''':\n\n: {\\pi\\over4} = \\arctan{1\\over2} + \\arctan{1\\over3} \n: {\\pi\\over4} = 2 \\arctan{1\\over3} + \\arctan{1\\over7}\n: {\\pi\\over4} = 4 \\arctan{1\\over5} - \\arctan{1\\over239}\n: {\\pi\\over4} = 5 \\arctan{1\\over7} + 2 \\arctan{3\\over79}\n: {\\pi\\over4} = 5 \\arctan{29\\over278} + 7 \\arctan{3\\over79}\n: {\\pi\\over4} = \\arctan{1\\over2} + \\arctan{1\\over5} + \\arctan{1\\over8} \n: {\\pi\\over4} = 4 \\arctan{1\\over5} - \\arctan{1\\over70} + \\arctan{1\\over99} \n: {\\pi\\over4} = 5 \\arctan{1\\over7} + 4 \\arctan{1\\over53} + 2 \\arctan{1\\over4443}\n: {\\pi\\over4} = 6 \\arctan{1\\over8} + 2 \\arctan{1\\over57} + \\arctan{1\\over239}\n: {\\pi\\over4} = 8 \\arctan{1\\over10} - \\arctan{1\\over239} - 4 \\arctan{1\\over515}\n: {\\pi\\over4} = 12 \\arctan{1\\over18} + 8 \\arctan{1\\over57} - 5 \\arctan{1\\over239}\n: {\\pi\\over4} = 16 \\arctan{1\\over21} + 3 \\arctan{1\\over239} + 4 \\arctan{3\\over1042}\n: {\\pi\\over4} = 22 \\arctan{1\\over28} + 2 \\arctan{1\\over443} - 5 \\arctan{1\\over1393} - 10 \\arctan{1\\over11018}\n: {\\pi\\over4} = 22 \\arctan{1\\over38} + 17 \\arctan{7\\over601} + 10 \\arctan{7\\over8149}\n: {\\pi\\over4} = 44 \\arctan{1\\over57} + 7 \\arctan{1\\over239} - 12 \\arctan{1\\over682} + 24 \\arctan{1\\over12943}\n: {\\pi\\over4} = 88 \\arctan{1\\over172} + 51 \\arctan{1\\over239} + 32 \\arctan{1\\over682} + 44 \\arctan{1\\over5357} + 68 \\arctan{1\\over12943}\n\nand confirm that the following formula is ''incorrect'' by showing '''tan''' (''right hand side)'' is ''not'' '''1''':\n\n: {\\pi\\over4} = 88 \\arctan{1\\over172} + 51 \\arctan{1\\over239} + 32 \\arctan{1\\over682} + 44 \\arctan{1\\over5357} + 68 \\arctan{1\\over12944}\n\nThese identities are useful in calculating the values:\n: \\tan(a + b) = {\\tan(a) + \\tan(b) \\over 1 - \\tan(a) \\tan(b)}\n\n: \\tan\\left(\\arctan{a \\over b}\\right) = {a \\over b}\n\n: \\tan(-a) = -\\tan(a)\n\nYou can store the equations in any convenient data structure, but for extra credit parse them from human-readable text input.\n\nNote: to formally prove the formula correct, it would have to be shown that ''{-3 pi \\over 4} < right hand side < {5 pi \\over 4}'' due to ''\\tan()'' periodicity.\n\n\n", "solution": "import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class CheckMachinFormula {\n \n private static String FILE_NAME = \"MachinFormula.txt\";\n \n public static void main(String[] args) {\n try {\n runPrivate();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n private static void runPrivate() throws IOException {\n try (BufferedReader reader = new BufferedReader(new FileReader(new File(FILE_NAME)));) { \n String inLine = null;\n while ( (inLine = reader.readLine()) != null ) {\n String[] split = inLine.split(\"=\");\n System.out.println(tanLeft(split[0].trim()) + \" = \" + split[1].trim().replaceAll(\"\\\\s+\", \" \") + \" = \" + tanRight(split[1].trim()));\n }\n }\n }\n \n private static String tanLeft(String formula) {\n if ( formula.compareTo(\"pi/4\") == 0 ) {\n return \"1\";\n }\n throw new RuntimeException(\"ERROR 104: Unknown left side: \" + formula);\n }\n \n private static final Pattern ARCTAN_PATTERN = Pattern.compile(\"(-{0,1}\\\\d+)\\\\*arctan\\\\((\\\\d+)/(\\\\d+)\\\\)\");\n \n private static Fraction tanRight(String formula) {\n Matcher matcher = ARCTAN_PATTERN.matcher(formula);\n List terms = new ArrayList<>();\n while ( matcher.find() ) {\n terms.add(new Term(Integer.parseInt(matcher.group(1)), new Fraction(matcher.group(2), matcher.group(3))));\n }\n return evaluateArctan(terms);\n }\n \n private static Fraction evaluateArctan(List terms) {\n if ( terms.size() == 1 ) {\n Term term = terms.get(0);\n return evaluateArctan(term.coefficient, term.fraction);\n }\n int size = terms.size();\n List left = terms.subList(0, (size+1) / 2);\n List right = terms.subList((size+1) / 2, size);\n return arctanFormula(evaluateArctan(left), evaluateArctan(right));\n }\n \n private static Fraction evaluateArctan(int coefficient, Fraction fraction) {\n //System.out.println(\"C = \" + coefficient + \", F = \" + fraction);\n if ( coefficient == 1 ) {\n return fraction;\n }\n else if ( coefficient < 0 ) {\n return evaluateArctan(-coefficient, fraction).negate();\n }\n if ( coefficient % 2 == 0 ) {\n Fraction f = evaluateArctan(coefficient/2, fraction);\n return arctanFormula(f, f);\n }\n Fraction a = evaluateArctan(coefficient/2, fraction);\n Fraction b = evaluateArctan(coefficient - (coefficient/2), fraction);\n return arctanFormula(a, b);\n }\n \n private static Fraction arctanFormula(Fraction f1, Fraction f2) {\n return f1.add(f2).divide(Fraction.ONE.subtract(f1.multiply(f2)));\n }\n \n private static class Fraction {\n \n public static final Fraction ONE = new Fraction(\"1\", \"1\");\n \n private BigInteger numerator;\n private BigInteger denominator;\n \n public Fraction(String num, String den) {\n numerator = new BigInteger(num);\n denominator = new BigInteger(den);\n }\n\n public Fraction(BigInteger num, BigInteger den) {\n numerator = num;\n denominator = den;\n }\n\n public Fraction negate() {\n return new Fraction(numerator.negate(), denominator);\n }\n \n public Fraction add(Fraction f) {\n BigInteger gcd = denominator.gcd(f.denominator);\n BigInteger first = numerator.multiply(f.denominator.divide(gcd));\n BigInteger second = f.numerator.multiply(denominator.divide(gcd));\n return new Fraction(first.add(second), denominator.multiply(f.denominator).divide(gcd));\n }\n \n public Fraction subtract(Fraction f) {\n return add(f.negate());\n }\n \n public Fraction multiply(Fraction f) {\n BigInteger num = numerator.multiply(f.numerator);\n BigInteger den = denominator.multiply(f.denominator);\n BigInteger gcd = num.gcd(den);\n return new Fraction(num.divide(gcd), den.divide(gcd));\n }\n\n public Fraction divide(Fraction f) {\n return multiply(new Fraction(f.denominator, f.numerator));\n }\n \n @Override\n public String toString() {\n if ( denominator.compareTo(BigInteger.ONE) == 0 ) {\n return numerator.toString();\n }\n return numerator + \" / \" + denominator;\n }\n }\n \n private static class Term {\n \n private int coefficient;\n private Fraction fraction;\n \n public Term(int c, Fraction f) {\n coefficient = c;\n fraction = f;\n }\n }\n \n}\n"} {"title": "Cheryl's birthday", "language": "Java from D", "task": "Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.\n\nCheryl gave them a list of ten possible dates:\n May 15, May 16, May 19\n June 17, June 18\n July 14, July 16\n August 14, August 15, August 17\n\nCheryl then tells Albert the ''month'' of birth, and Bernard the ''day'' (of the month) of birth.\n 1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too.\n 2) Bernard: At first I don't know when Cheryl's birthday is, but I know now.\n 3) Albert: Then I also know when Cheryl's birthday is.\n\n\n;Task\nWrite a computer program to deduce, by successive elimination, Cheryl's birthday.\n\n\n;Related task:\n* [[Sum and Product Puzzle]]\n\n\n;References\n* Wikipedia article of the same name.\n* Tuple Relational Calculus\n\n", "solution": "import java.time.Month;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.stream.Collectors;\n\npublic class Main {\n private static class Birthday {\n private Month month;\n private int day;\n\n public Birthday(Month month, int day) {\n this.month = month;\n this.day = day;\n }\n\n public Month getMonth() {\n return month;\n }\n\n public int getDay() {\n return day;\n }\n\n @Override\n public String toString() {\n return month + \" \" + day;\n }\n }\n\n public static void main(String[] args) {\n List choices = List.of(\n new Birthday(Month.MAY, 15),\n new Birthday(Month.MAY, 16),\n new Birthday(Month.MAY, 19),\n new Birthday(Month.JUNE, 17),\n new Birthday(Month.JUNE, 18),\n new Birthday(Month.JULY, 14),\n new Birthday(Month.JULY, 16),\n new Birthday(Month.AUGUST, 14),\n new Birthday(Month.AUGUST, 15),\n new Birthday(Month.AUGUST, 17)\n );\n System.out.printf(\"There are %d candidates remaining.\\n\", choices.size());\n\n // The month cannot have a unique day because Albert knows the month, and knows that Bernard does not know the answer\n Set uniqueMonths = choices.stream()\n .collect(Collectors.groupingBy(Birthday::getDay))\n .values()\n .stream()\n .filter(g -> g.size() == 1)\n .flatMap(Collection::stream)\n .map(Birthday::getMonth)\n .collect(Collectors.toSet());\n List f1List = choices.stream()\n .filter(birthday -> !uniqueMonths.contains(birthday.month))\n .collect(Collectors.toList());\n System.out.printf(\"There are %d candidates remaining.\\n\", f1List.size());\n\n // Bernard now knows the answer, so the day must be unique within the remaining choices\n List f2List = f1List.stream()\n .collect(Collectors.groupingBy(Birthday::getDay))\n .values()\n .stream()\n .filter(g -> g.size() == 1)\n .flatMap(Collection::stream)\n .collect(Collectors.toList());\n System.out.printf(\"There are %d candidates remaining.\\n\", f2List.size());\n\n // Albert knows the answer too, so the month must be unique within the remaining choices\n List f3List = f2List.stream()\n .collect(Collectors.groupingBy(Birthday::getMonth))\n .values()\n .stream()\n .filter(g -> g.size() == 1)\n .flatMap(Collection::stream)\n .collect(Collectors.toList());\n System.out.printf(\"There are %d candidates remaining.\\n\", f3List.size());\n\n if (f3List.size() == 1) {\n System.out.printf(\"Cheryl's birthday is %s\\n\", f3List.get(0));\n } else {\n System.out.println(\"No unique choice found\");\n }\n }\n}"} {"title": "Chinese remainder theorem", "language": "Java", "task": "Suppose n_1, n_2, \\ldots, n_k are positive [[integer]]s that are pairwise co-prime. \n\nThen, for any given sequence of integers a_1, a_2, \\dots, a_k, there exists an integer x solving the following system of simultaneous congruences:\n\n::: \\begin{align}\n x &\\equiv a_1 \\pmod{n_1} \\\\\n x &\\equiv a_2 \\pmod{n_2} \\\\\n &{}\\ \\ \\vdots \\\\\n x &\\equiv a_k \\pmod{n_k}\n\\end{align}\n\nFurthermore, all solutions x of this system are congruent modulo the product, N=n_1n_2\\ldots n_k.\n\n\n;Task:\nWrite a program to solve a system of linear congruences by applying the Chinese Remainder Theorem. \n\nIf the system of equations cannot be solved, your program must somehow indicate this. \n\n(It may throw an exception or return a special false value.) \n\nSince there are infinitely many solutions, the program should return the unique solution s where 0 \\leq s \\leq n_1n_2\\ldots n_k.\n\n\n''Show the functionality of this program'' by printing the result such that the n's are [3,5,7] and the a's are [2,3,2].\n\n\n'''Algorithm''': The following algorithm only applies if the n_i's are pairwise co-prime. \n\nSuppose, as above, that a solution is required for the system of congruences:\n\n::: x \\equiv a_i \\pmod{n_i} \\quad\\mathrm{for}\\; i = 1, \\ldots, k\n\nAgain, to begin, the product N = n_1n_2 \\ldots n_k is defined. \n\nThen a solution x can be found as follows:\n\nFor each i, the integers n_i and N/n_i are co-prime. \n\nUsing the Extended Euclidean algorithm, we can find integers r_i and s_i such that r_i n_i + s_i N/n_i = 1. \n\nThen, one solution to the system of simultaneous congruences is:\n\n::: x = \\sum_{i=1}^k a_i s_i N/n_i\n\nand the minimal solution,\n\n::: x \\pmod{N}.\n\n", "solution": "Translation of [[Chinese_remainder_theorem#Python|Python]] via [[Chinese_remainder_theorem#D|D]]\n"} {"title": "Chinese remainder theorem", "language": "Java 8", "task": "Suppose n_1, n_2, \\ldots, n_k are positive [[integer]]s that are pairwise co-prime. \n\nThen, for any given sequence of integers a_1, a_2, \\dots, a_k, there exists an integer x solving the following system of simultaneous congruences:\n\n::: \\begin{align}\n x &\\equiv a_1 \\pmod{n_1} \\\\\n x &\\equiv a_2 \\pmod{n_2} \\\\\n &{}\\ \\ \\vdots \\\\\n x &\\equiv a_k \\pmod{n_k}\n\\end{align}\n\nFurthermore, all solutions x of this system are congruent modulo the product, N=n_1n_2\\ldots n_k.\n\n\n;Task:\nWrite a program to solve a system of linear congruences by applying the Chinese Remainder Theorem. \n\nIf the system of equations cannot be solved, your program must somehow indicate this. \n\n(It may throw an exception or return a special false value.) \n\nSince there are infinitely many solutions, the program should return the unique solution s where 0 \\leq s \\leq n_1n_2\\ldots n_k.\n\n\n''Show the functionality of this program'' by printing the result such that the n's are [3,5,7] and the a's are [2,3,2].\n\n\n'''Algorithm''': The following algorithm only applies if the n_i's are pairwise co-prime. \n\nSuppose, as above, that a solution is required for the system of congruences:\n\n::: x \\equiv a_i \\pmod{n_i} \\quad\\mathrm{for}\\; i = 1, \\ldots, k\n\nAgain, to begin, the product N = n_1n_2 \\ldots n_k is defined. \n\nThen a solution x can be found as follows:\n\nFor each i, the integers n_i and N/n_i are co-prime. \n\nUsing the Extended Euclidean algorithm, we can find integers r_i and s_i such that r_i n_i + s_i N/n_i = 1. \n\nThen, one solution to the system of simultaneous congruences is:\n\n::: x = \\sum_{i=1}^k a_i s_i N/n_i\n\nand the minimal solution,\n\n::: x \\pmod{N}.\n\n", "solution": "import static java.util.Arrays.stream;\n\npublic class ChineseRemainderTheorem {\n\n public static int chineseRemainder(int[] n, int[] a) {\n\n int prod = stream(n).reduce(1, (i, j) -> i * j);\n\n int p, sm = 0;\n for (int i = 0; i < n.length; i++) {\n p = prod / n[i];\n sm += a[i] * mulInv(p, n[i]) * p;\n }\n return sm % prod;\n }\n\n private static int mulInv(int a, int b) {\n int b0 = b;\n int x0 = 0;\n int x1 = 1;\n\n if (b == 1)\n return 1;\n\n while (a > 1) {\n int q = a / b;\n int amb = a % b;\n a = b;\n b = amb;\n int xqx = x1 - q * x0;\n x1 = x0;\n x0 = xqx;\n }\n\n if (x1 < 0)\n x1 += b0;\n\n return x1;\n }\n\n public static void main(String[] args) {\n int[] n = {3, 5, 7};\n int[] a = {2, 3, 2};\n System.out.println(chineseRemainder(n, a));\n }\n}"} {"title": "Chinese zodiac", "language": "Java", "task": "Determine the Chinese zodiac sign and related associations for a given year.\nTraditionally, the Chinese have counted years using two lists of labels, one of length 10 (the \"celestial stems\") and one of length 12 (the \"terrestrial branches\"). The labels do not really have any meaning outside their positions in the two lists; they're simply a traditional enumeration device, used much as Westerners use letters and numbers. They were historically used for months and days as well as years, and the stems are still sometimes used for school grades.\n\nYears cycle through both lists concurrently, so that both stem and branch advance each year; if we used Roman letters for the stems and numbers for the branches, consecutive years would be labeled A1, B2, C3, etc. Since the two lists are different lengths, they cycle back to their beginning at different points: after J10 we get A11, and then after B12 we get C1. The result is a repeating 60-year pattern within which each pair of names occurs only once.\n\nMapping the branches to twelve traditional animal deities results in the well-known \"Chinese zodiac\", assigning each year to a given animal. For example, Sunday, January 22, 2023 CE (in the common Gregorian calendar) began the lunisolar Year of the Rabbit.\n\nThe celestial stems do not have a one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems are each associated with one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element is assigned to yin, the other to yang.\n\nThus, the Chinese year beginning in 2023 CE is also the yin year of Water. Since 12 is an even number, the association between animals and yin/yang doesn't change; consecutive Years of the Rabbit will cycle through the five elements, but will always be yin.\n\n;Task: Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year.\n\nYou may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration).\n\n;Requisite information:\n* The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig.\n* The element cycle runs in this order: Wood, Fire, Earth, Metal, Water. \n* Each element gets two consecutive years; a yang followed by a yin.\n* The current 60-year cycle began in 1984; any multiple of 60 years from that point may be used to reckon from.\n\nThus, year 1 of a cycle is the year of the Wood Rat (yang), year 2 the Wood Ox (yin), and year 3 the Fire Tiger (yang). The year 2023 - which, as already noted, is the year of the Water Rabbit (yin) - is the 40th year of the current cycle. \n\n;Information for optional task:\n* The ten celestial stems are '''Jia ''' ''jia'', '''Yi ''' ''yi'', '''Bing ''' ''bing'', '''Ding ''' ''ding'', '''Wu ''' ''wu'', '''Ji ''' ''ji'', '''Geng ''' ''geng'', '''Xin ''' ''xin'', '''Ren ''' ''ren'', and '''Gui ''' ''gui''. With the ASCII version of Pinyin tones, the names are written \"jia3\", \"yi3\", \"bing3\", \"ding1\", \"wu4\", \"ji3\", \"geng1\", \"xin1\", \"ren2\", and \"gui3\".\n* The twelve terrestrial branches are '''Zi ''' ''zi'', '''Chou ''' ''chou'', '''Yin ''' ''yin'', '''Mao ''' ''mao'', '''Chen ''' ''chen'', '''Si ''' ''si'', '''Wu ''' ''wu'', '''Wei ''' ''wei'', '''Shen ''' ''shen'', '''You ''' ''you'', '''Xu ''' ''xu'', '''Hai ''' ''hai''. In ASCII Pinyin, those are \"zi3\", \"chou3\", \"yin2\", \"mao3\", \"chen2\", \"si4\", \"wu3\", \"wei4\", \"shen1\", \"you3\", \"xu1\", and \"hai4\".\n\nTherefore 1984 was '''Jia Zi ''' (''jia-zi'', or jia3-zi3). 2023 is '''Gui Mao ''' (''gui-mao'' or gui3-mao3).\n", "solution": "public class Zodiac {\n\n\tfinal static String animals[]={\"Rat\",\"Ox\",\"Tiger\",\"Rabbit\",\"Dragon\",\"Snake\",\"Horse\",\"Goat\",\"Monkey\",\"Rooster\",\"Dog\",\"Pig\"};\n\tfinal static String elements[]={\"Wood\",\"Fire\",\"Earth\",\"Metal\",\"Water\"};\n\tfinal static String animalChars[]={\"\u5b50\",\"\u4e11\",\"\u5bc5\",\"\u536f\",\"\u8fb0\",\"\u5df3\",\"\u5348\",\"\u672a\",\"\u7533\",\"\u9149\",\"\u620c\",\"\u4ea5\"};\n\tstatic String elementChars[][]={{\"\u7532\",\"\u4e19\",\"\u620a\",\"\u5e9a\",\"\u58ec\"},{\"\u4e59\",\"\u4e01\",\"\u5df1\",\"\u8f9b\",\"\u7678\"}};\n\n\tstatic String getYY(int year)\n\t{\n\t if(year%2==0)\n\t {\n\t return \"yang\";\n\t }\n\t else\n\t {\n\t return \"yin\";\n\t }\n\t}\n\n\tpublic static void main(String[] args)\n\t{\n\t\tint years[]={1935,1938,1968,1972,1976,1984,1985,2017};\n\t\tfor(int i=0;i {\n }\n\n public static ChurchNum zero() {\n return f -> x -> x;\n }\n\n public static ChurchNum next(ChurchNum n) {\n return f -> x -> f.apply(n.apply(f).apply(x));\n }\n\n public static ChurchNum plus(ChurchNum a) {\n return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));\n }\n\n public static ChurchNum pow(ChurchNum m) {\n return n -> m.apply(n);\n }\n\n public static ChurchNum mult(ChurchNum a) {\n return b -> f -> x -> b.apply(a.apply(f)).apply(x);\n }\n\n public static ChurchNum toChurchNum(int n) {\n if (n <= 0) {\n return zero();\n }\n return next(toChurchNum(n - 1));\n }\n\n public static int toInt(ChurchNum c) {\n AtomicInteger counter = new AtomicInteger(0);\n ChurchNum funCounter = f -> {\n counter.incrementAndGet();\n return f;\n };\n\n plus(zero()).apply(c).apply(funCounter).apply(x -> x);\n\n return counter.get();\n }\n\n public static void main(String[] args) {\n ChurchNum zero = zero();\n ChurchNum three = next(next(next(zero)));\n ChurchNum four = next(next(next(next(zero))));\n\n System.out.println(\"3+4=\" + toInt(plus(three).apply(four))); // prints 7\n System.out.println(\"4+3=\" + toInt(plus(four).apply(three))); // prints 7\n\n System.out.println(\"3*4=\" + toInt(mult(three).apply(four))); // prints 12\n System.out.println(\"4*3=\" + toInt(mult(four).apply(three))); // prints 12\n\n // exponentiation. note the reversed order!\n System.out.println(\"3^4=\" + toInt(pow(four).apply(three))); // prints 81\n System.out.println(\"4^3=\" + toInt(pow(three).apply(four))); // prints 64\n\n System.out.println(\" 8=\" + toInt(toChurchNum(8))); // prints 8\n }\n}"} {"title": "Circles of given radius through two points", "language": "Java from Kotlin", "task": "2 circles with a given radius through 2 points in 2D space.\n\nGiven two points on a plane and a radius, usually two circles of given radius can be drawn through the points. \n;Exceptions:\n# r==0.0 should be treated as never describing circles (except in the case where the points are coincident).\n# If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point.\n# If the points form a diameter then return two identical circles ''or'' return a single circle, according to which is the most natural mechanism for the implementation language.\n# If the points are too far apart then no circles can be drawn.\n\n\n;Task detail:\n* Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, ''or some indication of special cases where two, possibly equal, circles cannot be returned''.\n* Show here the output for the following inputs:\n\n p1 p2 r\n0.1234, 0.9876 0.8765, 0.2345 2.0\n0.0000, 2.0000 0.0000, 0.0000 1.0\n0.1234, 0.9876 0.1234, 0.9876 2.0\n0.1234, 0.9876 0.8765, 0.2345 0.5\n0.1234, 0.9876 0.1234, 0.9876 0.0\n\n\n\n;Related task:\n* [[Total circles area]].\n\n\n;See also:\n* Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel\n\n", "solution": "import java.util.Objects;\n\npublic class Circles {\n private static class Point {\n private final double x, y;\n\n public Point(Double x, Double y) {\n this.x = x;\n this.y = y;\n }\n\n public double distanceFrom(Point other) {\n double dx = x - other.x;\n double dy = y - other.y;\n return Math.sqrt(dx * dx + dy * dy);\n }\n\n @Override\n public boolean equals(Object other) {\n if (this == other) return true;\n if (other == null || getClass() != other.getClass()) return false;\n Point point = (Point) other;\n return x == point.x && y == point.y;\n }\n\n @Override\n public String toString() {\n return String.format(\"(%.4f, %.4f)\", x, y);\n }\n }\n\n private static Point[] findCircles(Point p1, Point p2, double r) {\n if (r < 0.0) throw new IllegalArgumentException(\"the radius can't be negative\");\n if (r == 0.0 && p1 != p2) throw new IllegalArgumentException(\"no circles can ever be drawn\");\n if (r == 0.0) return new Point[]{p1, p1};\n if (Objects.equals(p1, p2)) throw new IllegalArgumentException(\"an infinite number of circles can be drawn\");\n double distance = p1.distanceFrom(p2);\n double diameter = 2.0 * r;\n if (distance > diameter) throw new IllegalArgumentException(\"the points are too far apart to draw a circle\");\n Point center = new Point((p1.x + p2.x) / 2.0, (p1.y + p2.y) / 2.0);\n if (distance == diameter) return new Point[]{center, center};\n double mirrorDistance = Math.sqrt(r * r - distance * distance / 4.0);\n double dx = (p2.x - p1.x) * mirrorDistance / distance;\n double dy = (p2.y - p1.y) * mirrorDistance / distance;\n return new Point[]{\n new Point(center.x - dy, center.y + dx),\n new Point(center.x + dy, center.y - dx)\n };\n }\n\n public static void main(String[] args) {\n Point[] p = new Point[]{\n new Point(0.1234, 0.9876),\n new Point(0.8765, 0.2345),\n new Point(0.0000, 2.0000),\n new Point(0.0000, 0.0000)\n };\n Point[][] points = new Point[][]{\n {p[0], p[1]},\n {p[2], p[3]},\n {p[0], p[0]},\n {p[0], p[1]},\n {p[0], p[0]},\n };\n double[] radii = new double[]{2.0, 1.0, 2.0, 0.5, 0.0};\n for (int i = 0; i < radii.length; ++i) {\n Point p1 = points[i][0];\n Point p2 = points[i][1];\n double r = radii[i];\n System.out.printf(\"For points %s and %s with radius %f\\n\", p1, p2, r);\n try {\n Point[] circles = findCircles(p1, p2, r);\n Point c1 = circles[0];\n Point c2 = circles[1];\n if (Objects.equals(c1, c2)) {\n System.out.printf(\"there is just one circle with center at %s\\n\", c1);\n } else {\n System.out.printf(\"there are two circles with centers at %s and %s\\n\", c1, c2);\n }\n } catch (IllegalArgumentException ex) {\n System.out.println(ex.getMessage());\n }\n System.out.println();\n }\n }\n}"} {"title": "Cistercian numerals", "language": "Java from Kotlin", "task": "Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from '''0''' to '''9999'''.\n\n;How they work\nAll Cistercian numerals begin with a vertical line segment, which by itself represents the number '''0'''. Then, glyphs representing the digits '''1''' through '''9''' are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number:\n\n:* The '''upper-right''' quadrant represents the '''ones''' place.\n:* The '''upper-left''' quadrant represents the '''tens''' place.\n:* The '''lower-right''' quadrant represents the '''hundreds''' place.\n:* The '''lower-left''' quadrant represents the '''thousands''' place.\n\nPlease consult the following image for examples of Cistercian numerals showing each glyph: [https://upload.wikimedia.org/wikipedia/commons/6/67/Cistercian_digits_%28vertical%29.svg]\n\n;Task\n\n:* Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile).\n\n:* Use the routine to show the following Cistercian numerals:\n\n::* 0\n::* 1\n::* 20\n::* 300\n::* 4000\n::* 5555\n::* 6789\n::* And a number of your choice!\n\n;Notes\nDue to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed -- especially for text output.\n\n;See also\n\n:* '''Numberphile - The Forgotten Number System'''\n:* '''dcode.fr - Online Cistercian numeral converter'''\n", "solution": "import java.util.Arrays;\nimport java.util.List;\n\npublic class Cistercian {\n private static final int SIZE = 15;\n private final char[][] canvas = new char[SIZE][SIZE];\n\n public Cistercian(int n) {\n initN();\n draw(n);\n }\n\n public void initN() {\n for (var row : canvas) {\n Arrays.fill(row, ' ');\n row[5] = 'x';\n }\n }\n\n private void horizontal(int c1, int c2, int r) {\n for (int c = c1; c <= c2; c++) {\n canvas[r][c] = 'x';\n }\n }\n\n private void vertical(int r1, int r2, int c) {\n for (int r = r1; r <= r2; r++) {\n canvas[r][c] = 'x';\n }\n }\n\n private void diagd(int c1, int c2, int r) {\n for (int c = c1; c <= c2; c++) {\n canvas[r + c - c1][c] = 'x';\n }\n }\n\n private void diagu(int c1, int c2, int r) {\n for (int c = c1; c <= c2; c++) {\n canvas[r - c + c1][c] = 'x';\n }\n }\n\n private void draw(int v) {\n var thousands = v / 1000;\n v %= 1000;\n\n var hundreds = v / 100;\n v %= 100;\n\n var tens = v / 10;\n var ones = v % 10;\n\n drawPart(1000 * thousands);\n drawPart(100 * hundreds);\n drawPart(10 * tens);\n drawPart(ones);\n }\n\n private void drawPart(int v) {\n switch (v) {\n case 1:\n horizontal(6, 10, 0);\n break;\n case 2:\n horizontal(6, 10, 4);\n break;\n case 3:\n diagd(6, 10, 0);\n break;\n case 4:\n diagu(6, 10, 4);\n break;\n case 5:\n drawPart(1);\n drawPart(4);\n break;\n case 6:\n vertical(0, 4, 10);\n break;\n case 7:\n drawPart(1);\n drawPart(6);\n break;\n case 8:\n drawPart(2);\n drawPart(6);\n break;\n case 9:\n drawPart(1);\n drawPart(8);\n break;\n\n case 10:\n horizontal(0, 4, 0);\n break;\n case 20:\n horizontal(0, 4, 4);\n break;\n case 30:\n diagu(0, 4, 4);\n break;\n case 40:\n diagd(0, 4, 0);\n break;\n case 50:\n drawPart(10);\n drawPart(40);\n break;\n case 60:\n vertical(0, 4, 0);\n break;\n case 70:\n drawPart(10);\n drawPart(60);\n break;\n case 80:\n drawPart(20);\n drawPart(60);\n break;\n case 90:\n drawPart(10);\n drawPart(80);\n break;\n\n case 100:\n horizontal(6, 10, 14);\n break;\n case 200:\n horizontal(6, 10, 10);\n break;\n case 300:\n diagu(6, 10, 14);\n break;\n case 400:\n diagd(6, 10, 10);\n break;\n case 500:\n drawPart(100);\n drawPart(400);\n break;\n case 600:\n vertical(10, 14, 10);\n break;\n case 700:\n drawPart(100);\n drawPart(600);\n break;\n case 800:\n drawPart(200);\n drawPart(600);\n break;\n case 900:\n drawPart(100);\n drawPart(800);\n break;\n\n case 1000:\n horizontal(0, 4, 14);\n break;\n case 2000:\n horizontal(0, 4, 10);\n break;\n case 3000:\n diagd(0, 4, 10);\n break;\n case 4000:\n diagu(0, 4, 14);\n break;\n case 5000:\n drawPart(1000);\n drawPart(4000);\n break;\n case 6000:\n vertical(10, 14, 0);\n break;\n case 7000:\n drawPart(1000);\n drawPart(6000);\n break;\n case 8000:\n drawPart(2000);\n drawPart(6000);\n break;\n case 9000:\n drawPart(1000);\n drawPart(8000);\n break;\n\n }\n }\n\n @Override\n public String toString() {\n StringBuilder builder = new StringBuilder();\n for (var row : canvas) {\n builder.append(row);\n builder.append('\\n');\n }\n return builder.toString();\n }\n\n public static void main(String[] args) {\n for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) {\n System.out.printf(\"%d:\\n\", number);\n var c = new Cistercian(number);\n System.out.println(c);\n }\n }\n}"} {"title": "Closures/Value capture", "language": "Java 8+", "task": "Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index '' i '' (you may choose to start '' i '' from either '''0''' or '''1'''), when run, should return the square of the index, that is, '' i '' 2. \n\nDisplay the result of running any but the last function, to demonstrate that the function indeed remembers its value.\n\n\n;Goal:\nDemonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. \n\nIn imperative languages, one would generally use a loop with a mutable counter variable. \n\nFor each function to maintain the correct number, it has to capture the ''value'' of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.\n\nSee also: [[Multiple distinct objects]]\n", "solution": "import java.util.List;\nimport java.util.function.IntSupplier;\nimport java.util.stream.IntStream;\n\nimport static java.util.stream.Collectors.toList;\n\npublic interface ValueCapture {\n public static void main(String... arguments) {\n List closures = IntStream.rangeClosed(0, 10)\n .mapToObj(i -> () -> i * i)\n .collect(toList())\n ;\n\n IntSupplier closure = closures.get(3);\n System.out.println(closure.getAsInt()); // prints \"9\"\n }\n}"} {"title": "Colorful numbers", "language": "Java from C", "task": "A '''colorful number''' is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique.\n\n\n;E.G.\n\n24753 is a colorful number. 2, 4, 7, 5, 3, (2x4)8, (4x7)28, (7x5)35, (5x3)15, (2x4x7)56, (4x7x5)140, (7x5x3)105, (2x4x7x5)280, (4x7x5x3)420, (2x4x7x5x3)840\n\nEvery product is unique.\n\n\n2346 is '''not''' a colorful number. 2, 3, 4, '''6''', (2x3)'''6''', (3x4)12, (4x6)24, (2x3x4)48, (3x4x6)72, (2x3x4x6)144\n\nThe product '''6''' is repeated.\n\n\nSingle digit numbers '''are''' considered to be colorful. A colorful number larger than 9 cannot contain a repeated digit, the digit 0 or the digit 1. As a consequence, there is a firm upper limit for colorful numbers; no colorful number can have more than 8 digits.\n\n\n;Task\n\n* Write a routine (subroutine, function, procedure, whatever it may be called in your language) to test if a number is a colorful number or not.\n* Use that routine to find all of the colorful numbers less than 100.\n* Use that routine to find the largest possible colorful number.\n\n\n;Stretch\n\n* Find and display the count of colorful numbers in each order of magnitude.\n* Find and show the total count of '''all''' colorful numbers.\n\n\n''Colorful numbers have no real number theory application. They are more a recreational math puzzle than a useful tool.''\n\n", "solution": "public class ColorfulNumbers {\n private int count[] = new int[8];\n private boolean used[] = new boolean[10];\n private int largest = 0;\n\n public static void main(String[] args) {\n System.out.printf(\"Colorful numbers less than 100:\\n\");\n for (int n = 0, count = 0; n < 100; ++n) {\n if (isColorful(n))\n System.out.printf(\"%2d%c\", n, ++count % 10 == 0 ? '\\n' : ' ');\n }\n\n ColorfulNumbers c = new ColorfulNumbers();\n\n System.out.printf(\"\\n\\nLargest colorful number: %,d\\n\", c.largest);\n\n System.out.printf(\"\\nCount of colorful numbers by number of digits:\\n\");\n int total = 0;\n for (int d = 0; d < 8; ++d) {\n System.out.printf(\"%d %,d\\n\", d + 1, c.count[d]);\n total += c.count[d];\n }\n System.out.printf(\"\\nTotal: %,d\\n\", total);\n }\n\n private ColorfulNumbers() {\n countColorful(0, 0, 0);\n }\n\n public static boolean isColorful(int n) {\n // A colorful number cannot be greater than 98765432.\n if (n < 0 || n > 98765432)\n return false;\n int digit_count[] = new int[10];\n int digits[] = new int[8];\n int num_digits = 0;\n for (int m = n; m > 0; m /= 10) {\n int d = m % 10;\n if (n > 9 && (d == 0 || d == 1))\n return false;\n if (++digit_count[d] > 1)\n return false;\n digits[num_digits++] = d;\n }\n // Maximum number of products is (8 x 9) / 2.\n int products[] = new int[36];\n for (int i = 0, product_count = 0; i < num_digits; ++i) {\n for (int j = i, p = 1; j < num_digits; ++j) {\n p *= digits[j];\n for (int k = 0; k < product_count; ++k) {\n if (products[k] == p)\n return false;\n }\n products[product_count++] = p;\n }\n }\n return true;\n }\n\n private void countColorful(int taken, int n, int digits) {\n if (taken == 0) {\n for (int d = 0; d < 10; ++d) {\n used[d] = true;\n countColorful(d < 2 ? 9 : 1, d, 1);\n used[d] = false;\n }\n } else {\n if (isColorful(n)) {\n ++count[digits - 1];\n if (n > largest)\n largest = n;\n }\n if (taken < 9) {\n for (int d = 2; d < 10; ++d) {\n if (!used[d]) {\n used[d] = true;\n countColorful(taken + 1, n * 10 + d, digits + 1);\n used[d] = false;\n }\n }\n }\n }\n }\n}"} {"title": "Colour bars/Display", "language": "Java", "task": "Display a series of vertical color bars across the width of the display. \n\nThe color bars should either use:\n:::* the system palette, or \n:::* the sequence of colors: \n::::::* black\n::::::* red\n::::::* green\n::::::* blue\n::::::* magenta\n::::::* cyan\n::::::* yellow\n::::::* white\n\n", "solution": "import java.awt.Color;\nimport java.awt.Graphics;\n\nimport javax.swing.JFrame;\n\npublic class ColorFrame extends JFrame {\n\tpublic ColorFrame(int width, int height) {\n\t\tthis.setDefaultCloseOperation(EXIT_ON_CLOSE);\n\t\tthis.setSize(width, height);\n\t\tthis.setVisible(true);\n\t}\n\n\t@Override\n\tpublic void paint(Graphics g) {\n\t\tColor[] colors = { Color.black, Color.red, Color.green, Color.blue,\n\t\t\t\tColor.pink, Color.CYAN, Color.yellow, Color.white };\n\n\t\tfor (int i = 0; i < colors.length; i++) {\n\t\t\tg.setColor(colors[i]);\n\t\t\tg.fillRect(this.getWidth() / colors.length * i, 0, this.getWidth()\n\t\t\t\t\t/ colors.length, this.getHeight());\n\t\t}\n\t}\n\n\tpublic static void main(String args[]) {\n\t\tnew ColorFrame(200, 200);\n\t}\n}\n"} {"title": "Comma quibbling", "language": "Java", "task": "Comma quibbling is a task originally set by Eric Lippert in his blog.\n\n\n;Task:\n\nWrite a function to generate a string output which is the concatenation of input words from a list/sequence where:\n# An input of no words produces the output string of just the two brace characters \"{}\".\n# An input of just one word, e.g. [\"ABC\"], produces the output string of the word inside the two braces, e.g. \"{ABC}\".\n# An input of two words, e.g. [\"ABC\", \"DEF\"], produces the output string of the two words inside the two braces with the words separated by the string \" and \", e.g. \"{ABC and DEF}\".\n# An input of three or more words, e.g. [\"ABC\", \"DEF\", \"G\", \"H\"], produces the output string of all but the last word separated by \", \" with the last word separated by \" and \" and all within braces; e.g. \"{ABC, DEF, G and H}\".\n\n\nTest your function with the following series of inputs showing your output here on this page:\n* [] # (No input words).\n* [\"ABC\"]\n* [\"ABC\", \"DEF\"]\n* [\"ABC\", \"DEF\", \"G\", \"H\"]\n\n\nNote: Assume words are non-empty strings of uppercase characters for this task.\n\n", "solution": "public class Quibbler {\n\n\tpublic static String quibble(String[] words) {\n\t\tString qText = \"{\";\n\t\tfor(int wIndex = 0; wIndex < words.length; wIndex++) {\n\t\t\tqText += words[wIndex] + (wIndex == words.length-1 ? \"\" : \n\t\t\t\t\t\t wIndex == words.length-2 ? \" and \" :\n\t\t\t\t\t\t \", \";\n\t\t}\n\t\tqText += \"}\";\n\t\treturn qText;\n\t}\n\t\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(quibble(new String[]{}));\n\t\tSystem.out.println(quibble(new String[]{\"ABC\"}));\n\t\tSystem.out.println(quibble(new String[]{\"ABC\", \"DEF\"}));\n\t\tSystem.out.println(quibble(new String[]{\"ABC\", \"DEF\", \"G\"}));\n\t\tSystem.out.println(quibble(new String[]{\"ABC\", \"DEF\", \"G\", \"H\"}));\n\t}\n}"} {"title": "Command-line arguments", "language": "Java", "task": "{{selection|Short Circuit|Console Program Basics}} Retrieve the list of command-line arguments given to the program. For programs that only print the arguments when run directly, see [[Scripted main]].\nSee also [[Program name]].\n\nFor parsing command line arguments intelligently, see [[Parsing command-line arguments]].\n\nExample command line:\n\n myprogram -c \"alpha beta\" -h \"gamma\"\n\n", "solution": "public class Arguments {\n public static void main(String[] args) {\n System.out.println(\"There are \" + args.length + \" arguments given.\");\n for(int i = 0; i < args.length; i++) \n System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n }\n}"} {"title": "Compare a list of strings", "language": "Java", "task": "Given a list of arbitrarily many strings, show how to:\n\n* test if they are all lexically '''equal'''\n* test if every string is lexically '''less than''' the one after it ''(i.e. whether the list is in strict ascending order)''\n\n\nEach of those two tests should result in a single true or false value, which could be used as the condition of an if statement or similar. \n\nIf the input list has less than two elements, the tests should always return true.\n\nThere is ''no'' need to provide a complete program and output.\n \nAssume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name strings, and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), with as little distractions as possible.\n\nTry to write your solution in a way that does not modify the original list, but if it does then please add a note to make that clear to readers.\n\nIf you need further guidance/clarification, see [[#Perl]] and [[#Python]] for solutions that use implicit short-circuiting loops, and [[#Raku]] for a solution that gets away with simply using a built-in language feature. \n\n", "solution": "boolean isAscending(String[] strings) {\n String previous = strings[0];\n int index = 0;\n for (String string : strings) {\n if (index++ == 0)\n continue;\n if (string.compareTo(previous) < 0)\n return false;\n previous = string;\n }\n return true;\n}\n"} {"title": "Compare a list of strings", "language": "Java 8", "task": "Given a list of arbitrarily many strings, show how to:\n\n* test if they are all lexically '''equal'''\n* test if every string is lexically '''less than''' the one after it ''(i.e. whether the list is in strict ascending order)''\n\n\nEach of those two tests should result in a single true or false value, which could be used as the condition of an if statement or similar. \n\nIf the input list has less than two elements, the tests should always return true.\n\nThere is ''no'' need to provide a complete program and output.\n \nAssume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name strings, and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), with as little distractions as possible.\n\nTry to write your solution in a way that does not modify the original list, but if it does then please add a note to make that clear to readers.\n\nIf you need further guidance/clarification, see [[#Perl]] and [[#Python]] for solutions that use implicit short-circuiting loops, and [[#Raku]] for a solution that gets away with simply using a built-in language feature. \n\n", "solution": "import java.util.Arrays;\n\npublic class CompareListOfStrings {\n\n public static void main(String[] args) {\n String[][] arr = {{\"AA\", \"AA\", \"AA\", \"AA\"}, {\"AA\", \"ACB\", \"BB\", \"CC\"}};\n for (String[] a : arr) {\n System.out.println(Arrays.toString(a));\n System.out.println(Arrays.stream(a).distinct().count() < 2);\n System.out.println(Arrays.equals(Arrays.stream(a).distinct().sorted().toArray(), a));\n }\n }\n}"} {"title": "Compiler/AST interpreter", "language": "Java", "task": "The C and Python versions can be considered reference implementations.\n\n;Related Tasks\n\n* Lexical Analyzer task\n* Syntax Analyzer task\n* Code Generator task\n* Virtual Machine Interpreter task\n\n\n__TOC__\n\n", "solution": "import java.util.Scanner;\nimport java.io.File;\nimport java.util.List;\nimport java.util.ArrayList;\nimport java.util.Map;\nimport java.util.HashMap;\n\nclass Interpreter {\n\tstatic Map globals = new HashMap<>();\n\tstatic Scanner s;\n\tstatic List list = new ArrayList<>();\n\tstatic Map str_to_nodes = new HashMap<>();\n\n\tstatic class Node {\n\t\tpublic NodeType nt;\n\t\tpublic Node left, right;\n\t\tpublic String value;\n\t\t\n\t\tNode() {\n\t\t\tthis.nt = null;\n\t\t\tthis.left = null;\n\t\t\tthis.right = null;\n\t\t\tthis.value = null;\n\t\t}\n\t\tNode(NodeType node_type, Node left, Node right, String value) {\n\t\t\tthis.nt = node_type;\n\t\t\tthis.left = left;\n\t\t\tthis.right = right;\n\t\t\tthis.value = value;\n\t\t}\n\t\tpublic static Node make_node(NodeType nodetype, Node left, Node right) {\n\t\t\treturn new Node(nodetype, left, right, \"\");\n\t\t}\n\t\tpublic static Node make_node(NodeType nodetype, Node left) {\n\t\t\treturn new Node(nodetype, left, null, \"\");\n\t\t}\n\t\tpublic static Node make_leaf(NodeType nodetype, String value) {\n\t\t\treturn new Node(nodetype, null, null, value);\n\t\t}\n\t}\n\tstatic enum NodeType {\n\t\tnd_None(\";\"), nd_Ident(\"Identifier\"), nd_String(\"String\"), nd_Integer(\"Integer\"),\n\t\tnd_Sequence(\"Sequence\"), nd_If(\"If\"),\n\t\tnd_Prtc(\"Prtc\"), nd_Prts(\"Prts\"), nd_Prti(\"Prti\"), nd_While(\"While\"),\n\t\tnd_Assign(\"Assign\"), nd_Negate(\"Negate\"), nd_Not(\"Not\"), nd_Mul(\"Multiply\"), nd_Div(\"Divide\"),\n\t\tnd_Mod(\"Mod\"), nd_Add(\"Add\"),\n\t\tnd_Sub(\"Subtract\"), nd_Lss(\"Less\"), nd_Leq(\"LessEqual\"),\n\t\tnd_Gtr(\"Greater\"), nd_Geq(\"GreaterEqual\"), nd_Eql(\"Equal\"), nd_Neq(\"NotEqual\"), nd_And(\"And\"), nd_Or(\"Or\");\n\t\t\n\t\tprivate final String name;\n\t\t\n\t\tNodeType(String name) {\tthis.name = name; }\n\t\t\n\t\t@Override\n\t\tpublic String toString() { return this.name; }\n\t}\n\tstatic String str(String s) {\n\t\tString result = \"\";\n\t\tint i = 0;\n\t\ts = s.replace(\"\\\"\", \"\");\n\t\twhile (i < s.length()) {\n\t\t\tif (s.charAt(i) == '\\\\' && i + 1 < s.length()) {\n\t\t\t\tif (s.charAt(i + 1) == 'n') {\n\t\t\t\t\tresult += '\\n';\n\t\t\t\t\ti += 2;\n\t\t\t\t} else if (s.charAt(i) == '\\\\') {\n\t\t\t\t\tresult += '\\\\';\n\t\t\t\t\ti += 2;\n\t\t\t\t} \n\t\t\t} else {\n\t\t\t\tresult += s.charAt(i);\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tstatic boolean itob(int i) {\n\t\treturn i != 0;\n\t}\n\tstatic int btoi(boolean b) {\n\t\treturn b ? 1 : 0;\n\t}\n\tstatic int fetch_var(String name) {\n\t\tint result;\n\t\tif (globals.containsKey(name)) {\n\t\t\tresult = globals.get(name);\n\t\t} else {\n\t\t\tglobals.put(name, 0);\n\t\t\tresult = 0;\n\t\t}\n\t\treturn result;\t\t\n\t}\n\tstatic Integer interpret(Node n) throws Exception {\n\t\tif (n == null) {\n\t\t\treturn 0;\n\t\t}\n\t\tswitch (n.nt) {\n\t\t\tcase nd_Integer:\n\t\t\t\treturn Integer.parseInt(n.value);\n\t\t\tcase nd_Ident:\n\t\t\t\treturn fetch_var(n.value);\n\t\t\tcase nd_String:\n\t\t\t\treturn 1;//n.value;\n\t\t\tcase nd_Assign:\n\t\t\t\tglobals.put(n.left.value, interpret(n.right));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Add:\n\t\t\t\treturn interpret(n.left) + interpret(n.right);\n\t\t\tcase nd_Sub:\n\t\t\t\treturn interpret(n.left) - interpret(n.right);\n\t\t\tcase nd_Mul:\n\t\t\t\treturn interpret(n.left) * interpret(n.right);\n\t\t\tcase nd_Div:\n\t\t\t\treturn interpret(n.left) / interpret(n.right);\n\t\t\tcase nd_Mod:\n\t\t\t\treturn interpret(n.left) % interpret(n.right);\n\t\t\tcase nd_Lss:\n\t\t\t\treturn btoi(interpret(n.left) < interpret(n.right));\n\t\t\tcase nd_Leq:\n\t\t\t\treturn btoi(interpret(n.left) <= interpret(n.right));\n\t\t\tcase nd_Gtr:\n\t\t\t\treturn btoi(interpret(n.left) > interpret(n.right));\n\t\t\tcase nd_Geq:\n\t\t\t\treturn btoi(interpret(n.left) >= interpret(n.right));\n\t\t\tcase nd_Eql:\n\t\t\t\treturn btoi(interpret(n.left) == interpret(n.right));\n\t\t\tcase nd_Neq:\n\t\t\t\treturn btoi(interpret(n.left) != interpret(n.right));\n\t\t\tcase nd_And:\n\t\t\t\treturn btoi(itob(interpret(n.left)) && itob(interpret(n.right)));\n\t\t\tcase nd_Or:\n\t\t\t\treturn btoi(itob(interpret(n.left)) || itob(interpret(n.right)));\n\t\t\tcase nd_Not:\n\t\t\t\tif (interpret(n.left) == 0) {\n\t\t\t\t\treturn 1;\n\t\t\t\t} else {\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\tcase nd_Negate:\n\t\t\t\treturn -interpret(n.left);\n\t\t\tcase nd_If:\n\t\t\t\tif (interpret(n.left) != 0) {\n\t\t\t\t\tinterpret(n.right.left);\n\t\t\t\t} else {\n\t\t\t\t\tinterpret(n.right.right);\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\tcase nd_While:\n\t\t\t\twhile (interpret(n.left) != 0) {\n\t\t\t\t\tinterpret(n.right);\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prtc:\n\t\t\t\tSystem.out.printf(\"%c\", interpret(n.left));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prti:\n\t\t\t\tSystem.out.printf(\"%d\", interpret(n.left));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Prts:\n\t\t\t\tSystem.out.print(str(n.left.value));//interpret(n.left));\n\t\t\t\treturn 0;\n\t\t\tcase nd_Sequence:\n\t\t\t\tinterpret(n.left);\n\t\t\t\tinterpret(n.right);\n\t\t\t\treturn 0;\n\t\t\tdefault:\n\t\t\t\tthrow new Exception(\"Error: '\" + n.nt + \"' found, expecting operator\");\n\t\t}\n\t}\n\tstatic Node load_ast() throws Exception {\n\t\tString command, value;\n\t\tString line;\n\t\tNode left, right;\n\t\t\n\t\twhile (s.hasNext()) {\n\t\t\tline = s.nextLine();\n\t\t\tvalue = null;\n\t\t\tif (line.length() > 16) {\n\t\t\t\tcommand = line.substring(0, 15).trim();\n\t\t\t\tvalue = line.substring(15).trim();\n\t\t\t} else {\n\t\t\t\tcommand = line.trim();\n\t\t\t}\n\t\t\tif (command.equals(\";\")) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (!str_to_nodes.containsKey(command)) {\n\t\t\t\tthrow new Exception(\"Command not found: '\" + command + \"'\");\n\t\t\t}\n\t\t\tif (value != null) {\n\t\t\t\treturn Node.make_leaf(str_to_nodes.get(command), value);\n\t\t\t}\n\t\t\tleft = load_ast(); right = load_ast();\n\t\t\treturn Node.make_node(str_to_nodes.get(command), left, right);\n\t\t}\n\t\treturn null; // for the compiler, not needed\n\t}\n\tpublic static void main(String[] args) {\n\t\tNode n;\n\n\t\tstr_to_nodes.put(\";\", NodeType.nd_None);\n\t\tstr_to_nodes.put(\"Sequence\", NodeType.nd_Sequence);\n\t\tstr_to_nodes.put(\"Identifier\", NodeType.nd_Ident);\n\t\tstr_to_nodes.put(\"String\", NodeType.nd_String);\n\t\tstr_to_nodes.put(\"Integer\", NodeType.nd_Integer);\n\t\tstr_to_nodes.put(\"If\", NodeType.nd_If);\n\t\tstr_to_nodes.put(\"While\", NodeType.nd_While);\n\t\tstr_to_nodes.put(\"Prtc\", NodeType.nd_Prtc);\n\t\tstr_to_nodes.put(\"Prts\", NodeType.nd_Prts);\n\t\tstr_to_nodes.put(\"Prti\", NodeType.nd_Prti);\n\t\tstr_to_nodes.put(\"Assign\", NodeType.nd_Assign);\n\t\tstr_to_nodes.put(\"Negate\", NodeType.nd_Negate);\n\t\tstr_to_nodes.put(\"Not\", NodeType.nd_Not);\n\t\tstr_to_nodes.put(\"Multiply\", NodeType.nd_Mul);\n\t\tstr_to_nodes.put(\"Divide\", NodeType.nd_Div);\n\t\tstr_to_nodes.put(\"Mod\", NodeType.nd_Mod);\n\t\tstr_to_nodes.put(\"Add\", NodeType.nd_Add);\n\t\tstr_to_nodes.put(\"Subtract\", NodeType.nd_Sub);\n\t\tstr_to_nodes.put(\"Less\", NodeType.nd_Lss);\n\t\tstr_to_nodes.put(\"LessEqual\", NodeType.nd_Leq);\n\t\tstr_to_nodes.put(\"Greater\", NodeType.nd_Gtr);\n\t\tstr_to_nodes.put(\"GreaterEqual\", NodeType.nd_Geq);\n\t\tstr_to_nodes.put(\"Equal\", NodeType.nd_Eql);\n\t\tstr_to_nodes.put(\"NotEqual\", NodeType.nd_Neq);\n\t\tstr_to_nodes.put(\"And\", NodeType.nd_And);\n\t\tstr_to_nodes.put(\"Or\", NodeType.nd_Or);\n\t\t\n\t\tif (args.length > 0) {\n\t\t\ttry {\n\t\t\t\ts = new Scanner(new File(args[0]));\n\t\t\t\tn = load_ast();\n\t\t\t\tinterpret(n);\n\t\t\t} catch (Exception e) {\n\t\t\t\tSystem.out.println(\"Ex: \"+e.getMessage());\n\t\t\t}\n\t\t}\n\t}\n}\n\n"} {"title": "Compiler/code generator", "language": "Java from Python", "task": "The C and Python versions can be considered reference implementations.\n\n;Related Tasks\n\n* Lexical Analyzer task\n* Syntax Analyzer task\n* Virtual Machine Interpreter task\n* AST Interpreter task\n\n\n__TOC__\n\n", "solution": "package codegenerator;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class CodeGenerator {\n final static int WORDSIZE = 4;\n \n static byte[] code = {};\n \n static Map str_to_nodes = new HashMap<>();\n static List string_pool = new ArrayList<>();\n static List variables = new ArrayList<>();\n static int string_count = 0;\n static int var_count = 0;\n \n static Scanner s;\n static NodeType[] unary_ops = {\n NodeType.nd_Negate, NodeType.nd_Not\n };\n static NodeType[] operators = {\n NodeType.nd_Mul, NodeType.nd_Div, NodeType.nd_Mod, NodeType.nd_Add, NodeType.nd_Sub,\n NodeType.nd_Lss, NodeType.nd_Leq, NodeType.nd_Gtr, NodeType.nd_Geq,\n NodeType.nd_Eql, NodeType.nd_Neq, NodeType.nd_And, NodeType.nd_Or\n };\n \n static enum Mnemonic {\n NONE, FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT,\n JMP, JZ, PRTC, PRTS, PRTI, HALT\n }\n static class Node {\n public NodeType nt;\n public Node left, right;\n public String value;\n\n Node() {\n this.nt = null;\n this.left = null;\n this.right = null;\n this.value = null;\n }\n Node(NodeType node_type, Node left, Node right, String value) {\n this.nt = node_type;\n this.left = left;\n this.right = right;\n this.value = value;\n }\n public static Node make_node(NodeType nodetype, Node left, Node right) {\n return new Node(nodetype, left, right, \"\");\n }\n public static Node make_node(NodeType nodetype, Node left) {\n return new Node(nodetype, left, null, \"\");\n }\n public static Node make_leaf(NodeType nodetype, String value) {\n return new Node(nodetype, null, null, value);\n }\n }\n static enum NodeType {\n nd_None(\"\", Mnemonic.NONE), nd_Ident(\"Identifier\", Mnemonic.NONE), nd_String(\"String\", Mnemonic.NONE), nd_Integer(\"Integer\", Mnemonic.NONE), nd_Sequence(\"Sequence\", Mnemonic.NONE),\n nd_If(\"If\", Mnemonic.NONE),\n nd_Prtc(\"Prtc\", Mnemonic.NONE), nd_Prts(\"Prts\", Mnemonic.NONE), nd_Prti(\"Prti\", Mnemonic.NONE), nd_While(\"While\", Mnemonic.NONE),\n nd_Assign(\"Assign\", Mnemonic.NONE),\n nd_Negate(\"Negate\", Mnemonic.NEG), nd_Not(\"Not\", Mnemonic.NOT), nd_Mul(\"Multiply\", Mnemonic.MUL), nd_Div(\"Divide\", Mnemonic.DIV), nd_Mod(\"Mod\", Mnemonic.MOD), nd_Add(\"Add\", Mnemonic.ADD),\n nd_Sub(\"Subtract\", Mnemonic.SUB), nd_Lss(\"Less\", Mnemonic.LT), nd_Leq(\"LessEqual\", Mnemonic.LE),\n nd_Gtr(\"Greater\", Mnemonic.GT), nd_Geq(\"GreaterEqual\", Mnemonic.GE), nd_Eql(\"Equal\", Mnemonic.EQ),\n nd_Neq(\"NotEqual\", Mnemonic.NE), nd_And(\"And\", Mnemonic.AND), nd_Or(\"Or\", Mnemonic.OR);\n\n private final String name;\n private final Mnemonic m;\n\n NodeType(String name, Mnemonic m) {\n this.name = name;\n this.m = m;\n }\n Mnemonic getMnemonic() { return this.m; }\n\n @Override\n public String toString() { return this.name; }\n }\n static void appendToCode(int b) {\n code = Arrays.copyOf(code, code.length + 1);\n code[code.length - 1] = (byte) b;\n }\n static void emit_byte(Mnemonic m) {\n appendToCode(m.ordinal());\n }\n static void emit_word(int n) {\n appendToCode(n >> 24);\n appendToCode(n >> 16);\n appendToCode(n >> 8);\n appendToCode(n);\n }\n static void emit_word_at(int pos, int n) {\n code[pos] = (byte) (n >> 24);\n code[pos + 1] = (byte) (n >> 16);\n code[pos + 2] = (byte) (n >> 8);\n code[pos + 3] = (byte) n;\n }\n static int get_word(int pos) {\n int result;\n result = ((code[pos] & 0xff) << 24) + ((code[pos + 1] & 0xff) << 16) + ((code[pos + 2] & 0xff) << 8) + (code[pos + 3] & 0xff) ;\n \n return result;\n }\n static int fetch_var_offset(String name) {\n int n;\n n = variables.indexOf(name);\n if (n == -1) {\n variables.add(name);\n n = var_count++;\n }\n return n;\n }\n static int fetch_string_offset(String str) {\n int n;\n n = string_pool.indexOf(str);\n if (n == -1) {\n string_pool.add(str);\n n = string_count++;\n }\n return n;\n }\n static int hole() {\n int t = code.length;\n emit_word(0);\n return t;\n }\n static boolean arrayContains(NodeType[] a, NodeType n) {\n boolean result = false;\n for (NodeType test: a) {\n if (test.equals(n)) {\n result = true;\n break;\n }\n }\n return result;\n }\n static void code_gen(Node x) throws Exception {\n int n, p1, p2;\n if (x == null) return;\n \n switch (x.nt) {\n case nd_None: return;\n case nd_Ident:\n emit_byte(Mnemonic.FETCH);\n n = fetch_var_offset(x.value);\n emit_word(n);\n break;\n case nd_Integer:\n emit_byte(Mnemonic.PUSH);\n emit_word(Integer.parseInt(x.value));\n break;\n case nd_String:\n emit_byte(Mnemonic.PUSH);\n n = fetch_string_offset(x.value);\n emit_word(n);\n break;\n case nd_Assign:\n n = fetch_var_offset(x.left.value);\n code_gen(x.right);\n emit_byte(Mnemonic.STORE);\n emit_word(n);\n break;\n case nd_If:\n p2 = 0; // to avoid NetBeans complaining about 'not initialized'\n code_gen(x.left);\n emit_byte(Mnemonic.JZ);\n p1 = hole();\n code_gen(x.right.left);\n if (x.right.right != null) {\n emit_byte(Mnemonic.JMP);\n p2 = hole();\n }\n emit_word_at(p1, code.length - p1);\n if (x.right.right != null) {\n code_gen(x.right.right);\n emit_word_at(p2, code.length - p2);\n }\n break;\n case nd_While:\n p1 = code.length;\n code_gen(x.left);\n emit_byte(Mnemonic.JZ);\n p2 = hole();\n code_gen(x.right);\n emit_byte(Mnemonic.JMP);\n emit_word(p1 - code.length);\n emit_word_at(p2, code.length - p2);\n break;\n case nd_Sequence:\n code_gen(x.left);\n code_gen(x.right);\n break;\n case nd_Prtc:\n code_gen(x.left);\n emit_byte(Mnemonic.PRTC);\n break;\n case nd_Prti:\n code_gen(x.left);\n emit_byte(Mnemonic.PRTI);\n break;\n case nd_Prts:\n code_gen(x.left);\n emit_byte(Mnemonic.PRTS);\n break;\n default:\n if (arrayContains(operators, x.nt)) {\n code_gen(x.left);\n code_gen(x.right);\n emit_byte(x.nt.getMnemonic());\n } else if (arrayContains(unary_ops, x.nt)) {\n code_gen(x.left);\n emit_byte(x.nt.getMnemonic());\n } else {\n throw new Exception(\"Error in code generator! Found \" + x.nt + \", expecting operator.\");\n }\n }\n }\n static void list_code() throws Exception {\n int pc = 0, x;\n Mnemonic op;\n System.out.println(\"Datasize: \" + var_count + \" Strings: \" + string_count);\n for (String s: string_pool) {\n System.out.println(s);\n }\n while (pc < code.length) {\n System.out.printf(\"%4d \", pc);\n op = Mnemonic.values()[code[pc++]];\n switch (op) {\n case FETCH:\n x = get_word(pc);\n System.out.printf(\"fetch [%d]\", x);\n pc += WORDSIZE;\n break;\n case STORE:\n x = get_word(pc);\n System.out.printf(\"store [%d]\", x);\n pc += WORDSIZE;\n break;\n case PUSH:\n x = get_word(pc);\n System.out.printf(\"push %d\", x);\n pc += WORDSIZE;\n break;\n case ADD: case SUB: case MUL: case DIV: case MOD:\n case LT: case GT: case LE: case GE: case EQ: case NE:\n case AND: case OR: case NEG: case NOT:\n case PRTC: case PRTI: case PRTS: case HALT:\n System.out.print(op.toString().toLowerCase());\n break;\n case JMP:\n x = get_word(pc);\n System.out.printf(\"jmp (%d) %d\", x, pc + x);\n pc += WORDSIZE;\n break;\n case JZ:\n x = get_word(pc);\n System.out.printf(\"jz (%d) %d\", x, pc + x);\n pc += WORDSIZE;\n break;\n default:\n throw new Exception(\"Unknown opcode \" + code[pc] + \"@\" + (pc - 1));\n }\n System.out.println();\n }\n }\n static Node load_ast() throws Exception {\n String command, value;\n String line;\n Node left, right;\n\n while (s.hasNext()) {\n line = s.nextLine();\n value = null;\n if (line.length() > 16) {\n command = line.substring(0, 15).trim();\n value = line.substring(15).trim();\n } else {\n command = line.trim();\n }\n if (command.equals(\";\")) {\n return null;\n }\n if (!str_to_nodes.containsKey(command)) {\n throw new Exception(\"Command not found: '\" + command + \"'\");\n }\n if (value != null) {\n return Node.make_leaf(str_to_nodes.get(command), value);\n }\n left = load_ast(); right = load_ast();\n return Node.make_node(str_to_nodes.get(command), left, right);\n }\n return null; // for the compiler, not needed\n }\n public static void main(String[] args) {\n Node n;\n\n str_to_nodes.put(\";\", NodeType.nd_None);\n str_to_nodes.put(\"Sequence\", NodeType.nd_Sequence);\n str_to_nodes.put(\"Identifier\", NodeType.nd_Ident);\n str_to_nodes.put(\"String\", NodeType.nd_String);\n str_to_nodes.put(\"Integer\", NodeType.nd_Integer);\n str_to_nodes.put(\"If\", NodeType.nd_If);\n str_to_nodes.put(\"While\", NodeType.nd_While);\n str_to_nodes.put(\"Prtc\", NodeType.nd_Prtc);\n str_to_nodes.put(\"Prts\", NodeType.nd_Prts);\n str_to_nodes.put(\"Prti\", NodeType.nd_Prti);\n str_to_nodes.put(\"Assign\", NodeType.nd_Assign);\n str_to_nodes.put(\"Negate\", NodeType.nd_Negate);\n str_to_nodes.put(\"Not\", NodeType.nd_Not);\n str_to_nodes.put(\"Multiply\", NodeType.nd_Mul);\n str_to_nodes.put(\"Divide\", NodeType.nd_Div);\n str_to_nodes.put(\"Mod\", NodeType.nd_Mod);\n str_to_nodes.put(\"Add\", NodeType.nd_Add);\n str_to_nodes.put(\"Subtract\", NodeType.nd_Sub);\n str_to_nodes.put(\"Less\", NodeType.nd_Lss);\n str_to_nodes.put(\"LessEqual\", NodeType.nd_Leq);\n str_to_nodes.put(\"Greater\", NodeType.nd_Gtr);\n str_to_nodes.put(\"GreaterEqual\", NodeType.nd_Geq);\n str_to_nodes.put(\"Equal\", NodeType.nd_Eql);\n str_to_nodes.put(\"NotEqual\", NodeType.nd_Neq);\n str_to_nodes.put(\"And\", NodeType.nd_And);\n str_to_nodes.put(\"Or\", NodeType.nd_Or);\n\n if (args.length > 0) {\n try {\n s = new Scanner(new File(args[0]));\n n = load_ast();\n code_gen(n);\n emit_byte(Mnemonic.HALT);\n list_code();\n } catch (Exception e) {\n System.out.println(\"Ex: \"+e);//.getMessage());\n }\n }\n }\n}\n"} {"title": "Compiler/lexical analyzer", "language": "Java", "task": "The C and Python versions can be considered reference implementations.\n\n\n;Related Tasks\n* Syntax Analyzer task\n* Code Generator task\n* Virtual Machine Interpreter task\n* AST Interpreter task\n\n\n", "solution": "// Translated from python source\n\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\n\npublic class Lexer {\n private int line;\n private int pos;\n private int position;\n private char chr;\n private String s;\n \n Map keywords = new HashMap<>();\n \n static class Token {\n public TokenType tokentype;\n public String value;\n public int line;\n public int pos;\n Token(TokenType token, String value, int line, int pos) {\n this.tokentype = token; this.value = value; this.line = line; this.pos = pos;\n }\n @Override\n public String toString() {\n String result = String.format(\"%5d %5d %-15s\", this.line, this.pos, this.tokentype);\n switch (this.tokentype) {\n case Integer:\n result += String.format(\" %4s\", value);\n break;\n case Identifier:\n result += String.format(\" %s\", value);\n break;\n case String:\n result += String.format(\" \\\"%s\\\"\", value);\n break;\n }\n return result;\n }\n }\n \n static enum TokenType {\n End_of_input, Op_multiply, Op_divide, Op_mod, Op_add, Op_subtract,\n Op_negate, Op_not, Op_less, Op_lessequal, Op_greater, Op_greaterequal,\n Op_equal, Op_notequal, Op_assign, Op_and, Op_or, Keyword_if,\n Keyword_else, Keyword_while, Keyword_print, Keyword_putc, LeftParen, RightParen,\n LeftBrace, RightBrace, Semicolon, Comma, Identifier, Integer, String\n }\n \n static void error(int line, int pos, String msg) {\n if (line > 0 && pos > 0) {\n System.out.printf(\"%s in line %d, pos %d\\n\", msg, line, pos);\n } else {\n System.out.println(msg);\n }\n System.exit(1);\n }\n\n Lexer(String source) {\n this.line = 1;\n this.pos = 0;\n this.position = 0;\n this.s = source;\n this.chr = this.s.charAt(0);\n this.keywords.put(\"if\", TokenType.Keyword_if);\n this.keywords.put(\"else\", TokenType.Keyword_else);\n this.keywords.put(\"print\", TokenType.Keyword_print);\n this.keywords.put(\"putc\", TokenType.Keyword_putc);\n this.keywords.put(\"while\", TokenType.Keyword_while);\n \n }\n Token follow(char expect, TokenType ifyes, TokenType ifno, int line, int pos) {\n if (getNextChar() == expect) {\n getNextChar();\n return new Token(ifyes, \"\", line, pos);\n }\n if (ifno == TokenType.End_of_input) {\n error(line, pos, String.format(\"follow: unrecognized character: (%d) '%c'\", (int)this.chr, this.chr));\n }\n return new Token(ifno, \"\", line, pos);\n }\n Token char_lit(int line, int pos) {\n char c = getNextChar(); // skip opening quote\n int n = (int)c;\n if (c == '\\'') {\n error(line, pos, \"empty character constant\");\n } else if (c == '\\\\') {\n c = getNextChar();\n if (c == 'n') {\n n = 10;\n } else if (c == '\\\\') {\n n = '\\\\';\n } else {\n error(line, pos, String.format(\"unknown escape sequence \\\\%c\", c));\n }\n }\n if (getNextChar() != '\\'') {\n error(line, pos, \"multi-character constant\");\n }\n getNextChar();\n return new Token(TokenType.Integer, \"\" + n, line, pos);\n }\n Token string_lit(char start, int line, int pos) {\n String result = \"\";\n while (getNextChar() != start) {\n if (this.chr == '\\u0000') {\n error(line, pos, \"EOF while scanning string literal\");\n }\n if (this.chr == '\\n') {\n error(line, pos, \"EOL while scanning string literal\");\n }\n result += this.chr;\n }\n getNextChar();\n return new Token(TokenType.String, result, line, pos);\n }\n Token div_or_comment(int line, int pos) {\n if (getNextChar() != '*') {\n return new Token(TokenType.Op_divide, \"\", line, pos);\n }\n getNextChar();\n while (true) { \n if (this.chr == '\\u0000') {\n error(line, pos, \"EOF in comment\");\n } else if (this.chr == '*') {\n if (getNextChar() == '/') {\n getNextChar();\n return getToken();\n }\n } else {\n getNextChar();\n }\n }\n }\n Token identifier_or_integer(int line, int pos) {\n boolean is_number = true;\n String text = \"\";\n \n while (Character.isAlphabetic(this.chr) || Character.isDigit(this.chr) || this.chr == '_') {\n text += this.chr;\n if (!Character.isDigit(this.chr)) {\n is_number = false;\n }\n getNextChar();\n }\n \n if (text.equals(\"\")) {\n error(line, pos, String.format(\"identifer_or_integer unrecognized character: (%d) %c\", (int)this.chr, this.chr));\n }\n \n if (Character.isDigit(text.charAt(0))) {\n if (!is_number) {\n error(line, pos, String.format(\"invalid number: %s\", text));\n }\n return new Token(TokenType.Integer, text, line, pos);\n }\n \n if (this.keywords.containsKey(text)) {\n return new Token(this.keywords.get(text), \"\", line, pos);\n }\n return new Token(TokenType.Identifier, text, line, pos);\n }\n Token getToken() {\n int line, pos;\n while (Character.isWhitespace(this.chr)) {\n getNextChar();\n }\n line = this.line;\n pos = this.pos;\n \n switch (this.chr) {\n case '\\u0000': return new Token(TokenType.End_of_input, \"\", this.line, this.pos);\n case '/': return div_or_comment(line, pos);\n case '\\'': return char_lit(line, pos);\n case '<': return follow('=', TokenType.Op_lessequal, TokenType.Op_less, line, pos);\n case '>': return follow('=', TokenType.Op_greaterequal, TokenType.Op_greater, line, pos);\n case '=': return follow('=', TokenType.Op_equal, TokenType.Op_assign, line, pos);\n case '!': return follow('=', TokenType.Op_notequal, TokenType.Op_not, line, pos);\n case '&': return follow('&', TokenType.Op_and, TokenType.End_of_input, line, pos);\n case '|': return follow('|', TokenType.Op_or, TokenType.End_of_input, line, pos);\n case '\"': return string_lit(this.chr, line, pos);\n case '{': getNextChar(); return new Token(TokenType.LeftBrace, \"\", line, pos);\n case '}': getNextChar(); return new Token(TokenType.RightBrace, \"\", line, pos);\n case '(': getNextChar(); return new Token(TokenType.LeftParen, \"\", line, pos);\n case ')': getNextChar(); return new Token(TokenType.RightParen, \"\", line, pos);\n case '+': getNextChar(); return new Token(TokenType.Op_add, \"\", line, pos);\n case '-': getNextChar(); return new Token(TokenType.Op_subtract, \"\", line, pos);\n case '*': getNextChar(); return new Token(TokenType.Op_multiply, \"\", line, pos);\n case '%': getNextChar(); return new Token(TokenType.Op_mod, \"\", line, pos);\n case ';': getNextChar(); return new Token(TokenType.Semicolon, \"\", line, pos);\n case ',': getNextChar(); return new Token(TokenType.Comma, \"\", line, pos);\n \n default: return identifier_or_integer(line, pos);\n }\n }\n \n char getNextChar() {\n this.pos++;\n this.position++;\n if (this.position >= this.s.length()) {\n this.chr = '\\u0000';\n return this.chr;\n }\n this.chr = this.s.charAt(this.position);\n if (this.chr == '\\n') {\n this.line++;\n this.pos = 0;\n }\n return this.chr;\n }\n\n void printTokens() {\n Token t;\n while ((t = getToken()).tokentype != TokenType.End_of_input) {\n System.out.println(t);\n }\n System.out.println(t);\n }\n public static void main(String[] args) {\n if (args.length > 0) {\n try {\n \n File f = new File(args[0]);\n Scanner s = new Scanner(f);\n String source = \" \";\n while (s.hasNext()) {\n source += s.nextLine() + \"\\n\";\n }\n Lexer l = new Lexer(source);\n l.printTokens();\n } catch(FileNotFoundException e) {\n error(-1, -1, \"Exception: \" + e.getMessage());\n }\n } else {\n error(-1, -1, \"No args\");\n }\n }\n}\n"} {"title": "Compiler/syntax analyzer", "language": "Java from Python", "task": "The C and Python versions can be considered reference implementations.\n\n;Related Tasks\n\n* Lexical Analyzer task\n* Code Generator task\n* Virtual Machine Interpreter task\n* AST Interpreter task\n\n\n__TOC__\n\n", "solution": "import java.io.File;\nimport java.io.FileNotFoundException;\nimport java.util.Scanner;\nimport java.util.StringTokenizer;\nimport java.util.List;\nimport java.util.ArrayList;\nimport java.util.Map;\nimport java.util.HashMap;\n\nclass Parser {\n\tprivate List source;\n\tprivate Token token;\n\tprivate int position;\n\n\tstatic class Node {\n\t\tpublic NodeType nt;\n\t\tpublic Node left, right;\n\t\tpublic String value;\n\n\t\tNode() {\n\t\t\tthis.nt = null;\n\t\t\tthis.left = null;\n\t\t\tthis.right = null;\n\t\t\tthis.value = null;\n\t\t}\n\t\tNode(NodeType node_type, Node left, Node right, String value) {\n\t\t\tthis.nt = node_type;\n\t\t\tthis.left = left;\n\t\t\tthis.right = right;\n\t\t\tthis.value = value;\n\t\t}\n\t\tpublic static Node make_node(NodeType nodetype, Node left, Node right) {\n\t\t\treturn new Node(nodetype, left, right, \"\");\n\t\t}\n\t\tpublic static Node make_node(NodeType nodetype, Node left) {\n\t\t\treturn new Node(nodetype, left, null, \"\");\n\t\t}\n\t\tpublic static Node make_leaf(NodeType nodetype, String value) {\n\t\t\treturn new Node(nodetype, null, null, value);\n\t\t}\n\t}\n\n\tstatic class Token {\n\t\tpublic TokenType tokentype;\n\t\tpublic String value;\n\t\tpublic int line;\n\t\tpublic int pos;\n\n\t\tToken(TokenType token, String value, int line, int pos) {\n\t\t\tthis.tokentype = token; this.value = value; this.line = line; this.pos = pos;\n\t\t}\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn String.format(\"%5d %5d %-15s %s\", this.line, this.pos, this.tokentype, this.value);\n\t\t}\n\t}\n\n\tstatic enum TokenType {\n\t\tEnd_of_input(false, false, false, -1, NodeType.nd_None),\n\t\tOp_multiply(false, true, false, 13, NodeType.nd_Mul),\n\t\tOp_divide(false, true, false, 13, NodeType.nd_Div),\n\t\tOp_mod(false, true, false, 13, NodeType.nd_Mod),\n\t\tOp_add(false, true, false, 12, NodeType.nd_Add),\n\t\tOp_subtract(false, true, false, 12, NodeType.nd_Sub),\n\t\tOp_negate(false, false, true, 14, NodeType.nd_Negate),\n\t\tOp_not(false, false, true, 14, NodeType.nd_Not),\n\t\tOp_less(false, true, false, 10, NodeType.nd_Lss),\n\t\tOp_lessequal(false, true, false, 10, NodeType.nd_Leq),\n\t\tOp_greater(false, true, false, 10, NodeType.nd_Gtr),\n\t\tOp_greaterequal(false, true, false, 10, NodeType.nd_Geq),\n\t\tOp_equal(false, true, true, 9, NodeType.nd_Eql),\n\t\tOp_notequal(false, true, false, 9, NodeType.nd_Neq),\n\t\tOp_assign(false, false, false, -1, NodeType.nd_Assign),\n\t\tOp_and(false, true, false, 5, NodeType.nd_And),\n\t\tOp_or(false, true, false, 4, NodeType.nd_Or),\n\t\tKeyword_if(false, false, false, -1, NodeType.nd_If),\n\t\tKeyword_else(false, false, false, -1, NodeType.nd_None),\n\t\tKeyword_while(false, false, false, -1, NodeType.nd_While),\n\t\tKeyword_print(false, false, false, -1, NodeType.nd_None),\n\t\tKeyword_putc(false, false, false, -1, NodeType.nd_None),\n\t\tLeftParen(false, false, false, -1, NodeType.nd_None),\n\t\tRightParen(false, false, false, -1, NodeType.nd_None),\n\t\tLeftBrace(false, false, false, -1, NodeType.nd_None),\n\t\tRightBrace(false, false, false, -1, NodeType.nd_None),\n\t\tSemicolon(false, false, false, -1, NodeType.nd_None),\n\t\tComma(false, false, false, -1, NodeType.nd_None),\n\t\tIdentifier(false, false, false, -1, NodeType.nd_Ident),\n\t\tInteger(false, false, false, -1, NodeType.nd_Integer),\n\t\tString(false, false, false, -1, NodeType.nd_String);\n\n\t\tprivate final int precedence;\n\t\tprivate final boolean right_assoc;\n\t\tprivate final boolean is_binary;\n\t\tprivate final boolean is_unary;\n\t\tprivate final NodeType node_type;\n\n\t\tTokenType(boolean right_assoc, boolean is_binary, boolean is_unary, int precedence, NodeType node) {\n\t\t\tthis.right_assoc = right_assoc;\n\t\t\tthis.is_binary = is_binary;\n\t\t\tthis.is_unary = is_unary;\n\t\t\tthis.precedence = precedence;\n\t\t\tthis.node_type = node;\n\t\t}\n\t\tboolean isRightAssoc() { return this.right_assoc; }\n\t\tboolean isBinary() { return this.is_binary; }\n\t\tboolean isUnary() { return this.is_unary; }\n\t\tint getPrecedence() { return this.precedence; }\n\t\tNodeType getNodeType() { return this.node_type; }\n\t}\n\tstatic enum NodeType {\n\t\tnd_None(\"\"), nd_Ident(\"Identifier\"), nd_String(\"String\"), nd_Integer(\"Integer\"), nd_Sequence(\"Sequence\"), nd_If(\"If\"),\n\t\tnd_Prtc(\"Prtc\"), nd_Prts(\"Prts\"), nd_Prti(\"Prti\"), nd_While(\"While\"),\n\t\tnd_Assign(\"Assign\"), nd_Negate(\"Negate\"), nd_Not(\"Not\"), nd_Mul(\"Multiply\"), nd_Div(\"Divide\"), nd_Mod(\"Mod\"), nd_Add(\"Add\"),\n\t\tnd_Sub(\"Subtract\"), nd_Lss(\"Less\"), nd_Leq(\"LessEqual\"),\n\t\tnd_Gtr(\"Greater\"), nd_Geq(\"GreaterEqual\"), nd_Eql(\"Equal\"), nd_Neq(\"NotEqual\"), nd_And(\"And\"), nd_Or(\"Or\");\n\n\t\tprivate final String name;\n\n\t\tNodeType(String name) {\n\t\t\tthis.name = name;\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() { return this.name; }\n\t}\n\tstatic void error(int line, int pos, String msg) {\n\t\tif (line > 0 && pos > 0) {\n\t\t\tSystem.out.printf(\"%s in line %d, pos %d\\n\", msg, line, pos);\n\t\t} else {\n\t\t\tSystem.out.println(msg);\n\t\t}\n\t\tSystem.exit(1);\n\t}\n\tParser(List source) {\n\t\tthis.source = source;\n\t\tthis.token = null;\n\t\tthis.position = 0;\n\t}\n\tToken getNextToken() {\n\t\tthis.token = this.source.get(this.position++);\n\t\treturn this.token;\n\t}\n\tNode expr(int p) {\n\t\tNode result = null, node;\n\t\tTokenType op;\n\t\tint q;\n\n\t\tif (this.token.tokentype == TokenType.LeftParen) {\n\t\t\tresult = paren_expr();\n\t\t} else if (this.token.tokentype == TokenType.Op_add || this.token.tokentype == TokenType.Op_subtract) {\n\t\t\top = (this.token.tokentype == TokenType.Op_subtract) ? TokenType.Op_negate : TokenType.Op_add;\n\t\t\tgetNextToken();\n\t\t\tnode = expr(TokenType.Op_negate.getPrecedence());\n\t\t\tresult = (op == TokenType.Op_negate) ? Node.make_node(NodeType.nd_Negate, node) : node;\n\t\t} else if (this.token.tokentype == TokenType.Op_not) {\n\t\t\tgetNextToken();\n\t\t\tresult = Node.make_node(NodeType.nd_Not, expr(TokenType.Op_not.getPrecedence()));\n\t\t} else if (this.token.tokentype == TokenType.Identifier) {\n\t\t\tresult = Node.make_leaf(NodeType.nd_Ident, this.token.value);\n\t\t\tgetNextToken();\n\t\t} else if (this.token.tokentype == TokenType.Integer) {\n\t\t\tresult = Node.make_leaf(NodeType.nd_Integer, this.token.value);\n\t\t\tgetNextToken();\n\t\t} else {\n\t\t\terror(this.token.line, this.token.pos, \"Expecting a primary, found: \" + this.token.tokentype);\n\t\t}\n\n\t\twhile (this.token.tokentype.isBinary() && this.token.tokentype.getPrecedence() >= p) {\n\t\t\top = this.token.tokentype;\n\t\t\tgetNextToken();\n\t\t\tq = op.getPrecedence();\n\t\t\tif (!op.isRightAssoc()) {\n\t\t\t\tq++;\n\t\t\t}\n\t\t\tnode = expr(q);\n\t\t\tresult = Node.make_node(op.getNodeType(), result, node);\n\t\t}\n\t\treturn result;\n\t}\n\tNode paren_expr() {\n\t\texpect(\"paren_expr\", TokenType.LeftParen);\n\t\tNode node = expr(0);\n\t\texpect(\"paren_expr\", TokenType.RightParen);\n\t\treturn node;\n\t}\n\tvoid expect(String msg, TokenType s) {\n\t\tif (this.token.tokentype == s) {\n\t\t\tgetNextToken();\n\t\t\treturn;\n\t\t}\n\t\terror(this.token.line, this.token.pos, msg + \": Expecting '\" + s + \"', found: '\" + this.token.tokentype + \"'\");\n\t}\n\tNode stmt() {\n\t\tNode s, s2, t = null, e, v;\n\t\tif (this.token.tokentype == TokenType.Keyword_if) {\n\t\t\tgetNextToken();\n\t\t\te = paren_expr();\n\t\t\ts = stmt();\n\t\t\ts2 = null;\n\t\t\tif (this.token.tokentype == TokenType.Keyword_else) {\n\t\t\t\tgetNextToken();\n\t\t\t\ts2 = stmt();\n\t\t\t}\n\t\t\tt = Node.make_node(NodeType.nd_If, e, Node.make_node(NodeType.nd_If, s, s2));\n\t\t} else if (this.token.tokentype == TokenType.Keyword_putc) {\n\t\t\tgetNextToken();\n\t\t\te = paren_expr();\n\t\t\tt = Node.make_node(NodeType.nd_Prtc, e);\n\t\t\texpect(\"Putc\", TokenType.Semicolon);\n\t\t} else if (this.token.tokentype == TokenType.Keyword_print) {\n\t\t\tgetNextToken();\n\t\t\texpect(\"Print\", TokenType.LeftParen);\n\t\t\twhile (true) {\n\t\t\t\tif (this.token.tokentype == TokenType.String) {\n\t\t\t\t\te = Node.make_node(NodeType.nd_Prts, Node.make_leaf(NodeType.nd_String, this.token.value));\n\t\t\t\t\tgetNextToken();\n\t\t\t\t} else {\n\t\t\t\t\te = Node.make_node(NodeType.nd_Prti, expr(0), null);\n\t\t\t\t}\n\t\t\t\tt = Node.make_node(NodeType.nd_Sequence, t, e);\n\t\t\t\tif (this.token.tokentype != TokenType.Comma) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tgetNextToken();\n\t\t\t}\n\t\t\texpect(\"Print\", TokenType.RightParen);\n\t\t\texpect(\"Print\", TokenType.Semicolon);\n\t\t} else if (this.token.tokentype == TokenType.Semicolon) {\n\t\t\tgetNextToken();\n\t\t} else if (this.token.tokentype == TokenType.Identifier) {\n\t\t\tv = Node.make_leaf(NodeType.nd_Ident, this.token.value);\n\t\t\tgetNextToken();\n\t\t\texpect(\"assign\", TokenType.Op_assign);\n\t\t\te = expr(0);\n\t\t\tt = Node.make_node(NodeType.nd_Assign, v, e);\n\t\t\texpect(\"assign\", TokenType.Semicolon);\n\t\t} else if (this.token.tokentype == TokenType.Keyword_while) {\n\t\t\tgetNextToken();\n\t\t\te = paren_expr();\n\t\t\ts = stmt();\n\t\t\tt = Node.make_node(NodeType.nd_While, e, s);\n\t\t} else if (this.token.tokentype == TokenType.LeftBrace) {\n\t\t\tgetNextToken();\n\t\t\twhile (this.token.tokentype != TokenType.RightBrace && this.token.tokentype != TokenType.End_of_input) {\n\t\t\t\tt = Node.make_node(NodeType.nd_Sequence, t, stmt());\n\t\t\t}\n\t\t\texpect(\"LBrace\", TokenType.RightBrace);\n\t\t} else if (this.token.tokentype == TokenType.End_of_input) {\n\t\t} else {\n\t\t\terror(this.token.line, this.token.pos, \"Expecting start of statement, found: \" + this.token.tokentype);\n\t\t}\n\t\treturn t;\n\t}\n\tNode parse() {\n\t\tNode t = null;\n\t\tgetNextToken();\n\t\twhile (this.token.tokentype != TokenType.End_of_input) {\n\t\t\tt = Node.make_node(NodeType.nd_Sequence, t, stmt());\n\t\t}\n\t\treturn t;\n\t}\n\tvoid printAST(Node t) {\n\t\tint i = 0;\n\t\tif (t == null) {\n\t\t\tSystem.out.println(\";\");\n\t\t} else {\n\t\t\tSystem.out.printf(\"%-14s\", t.nt);\n\t\t\tif (t.nt == NodeType.nd_Ident || t.nt == NodeType.nd_Integer || t.nt == NodeType.nd_String) {\n\t\t\t\tSystem.out.println(\" \" + t.value);\n\t\t\t} else {\n\t\t\t\tSystem.out.println();\n\t\t\t\tprintAST(t.left);\n\t\t\t\tprintAST(t.right);\n\t\t\t}\n\t\t}\n\t}\n\tpublic static void main(String[] args) {\n\t\tif (args.length > 0) {\n\t\t\ttry {\n\t\t\t\tString value, token;\n\t\t\t\tint line, pos;\n\t\t\t\tToken t;\n\t\t\t\tboolean found;\n\t\t\t\tList list = new ArrayList<>();\n\t\t\t\tMap str_to_tokens = new HashMap<>();\n\n\t\t\t\tstr_to_tokens.put(\"End_of_input\", TokenType.End_of_input);\n\t\t\t\tstr_to_tokens.put(\"Op_multiply\", TokenType.Op_multiply);\n\t\t\t\tstr_to_tokens.put(\"Op_divide\", TokenType.Op_divide);\n\t\t\t\tstr_to_tokens.put(\"Op_mod\", TokenType.Op_mod);\n\t\t\t\tstr_to_tokens.put(\"Op_add\", TokenType.Op_add);\n\t\t\t\tstr_to_tokens.put(\"Op_subtract\", TokenType.Op_subtract);\n\t\t\t\tstr_to_tokens.put(\"Op_negate\", TokenType.Op_negate);\n\t\t\t\tstr_to_tokens.put(\"Op_not\", TokenType.Op_not);\n\t\t\t\tstr_to_tokens.put(\"Op_less\", TokenType.Op_less);\n\t\t\t\tstr_to_tokens.put(\"Op_lessequal\", TokenType.Op_lessequal);\n\t\t\t\tstr_to_tokens.put(\"Op_greater\", TokenType.Op_greater);\n\t\t\t\tstr_to_tokens.put(\"Op_greaterequal\", TokenType.Op_greaterequal);\n\t\t\t\tstr_to_tokens.put(\"Op_equal\", TokenType.Op_equal);\n\t\t\t\tstr_to_tokens.put(\"Op_notequal\", TokenType.Op_notequal);\n\t\t\t\tstr_to_tokens.put(\"Op_assign\", TokenType.Op_assign);\n\t\t\t\tstr_to_tokens.put(\"Op_and\", TokenType.Op_and);\n\t\t\t\tstr_to_tokens.put(\"Op_or\", TokenType.Op_or);\n\t\t\t\tstr_to_tokens.put(\"Keyword_if\", TokenType.Keyword_if);\n\t\t\t\tstr_to_tokens.put(\"Keyword_else\", TokenType.Keyword_else);\n\t\t\t\tstr_to_tokens.put(\"Keyword_while\", TokenType.Keyword_while);\n\t\t\t\tstr_to_tokens.put(\"Keyword_print\", TokenType.Keyword_print);\n\t\t\t\tstr_to_tokens.put(\"Keyword_putc\", TokenType.Keyword_putc);\n\t\t\t\tstr_to_tokens.put(\"LeftParen\", TokenType.LeftParen);\n\t\t\t\tstr_to_tokens.put(\"RightParen\", TokenType.RightParen);\n\t\t\t\tstr_to_tokens.put(\"LeftBrace\", TokenType.LeftBrace);\n\t\t\t\tstr_to_tokens.put(\"RightBrace\", TokenType.RightBrace);\n\t\t\t\tstr_to_tokens.put(\"Semicolon\", TokenType.Semicolon);\n\t\t\t\tstr_to_tokens.put(\"Comma\", TokenType.Comma);\n\t\t\t\tstr_to_tokens.put(\"Identifier\", TokenType.Identifier);\n\t\t\t\tstr_to_tokens.put(\"Integer\", TokenType.Integer);\n\t\t\t\tstr_to_tokens.put(\"String\", TokenType.String);\n\n\t\t\t\tScanner s = new Scanner(new File(args[0]));\n\t\t\t\tString source = \" \";\n\t\t\t\twhile (s.hasNext()) {\n\t\t\t\t\tString str = s.nextLine();\n\t\t\t\t\tStringTokenizer st = new StringTokenizer(str);\n\t\t\t\t\tline = Integer.parseInt(st.nextToken());\n\t\t\t\t\tpos = Integer.parseInt(st.nextToken());\n\t\t\t\t\ttoken = st.nextToken();\n\t\t\t\t\tvalue = \"\";\n\t\t\t\t\twhile (st.hasMoreTokens()) {\n\t\t\t\t\t\tvalue += st.nextToken() + \" \";\n\t\t\t\t\t}\n\t\t\t\t\tfound = false;\n\t\t\t\t\tif (str_to_tokens.containsKey(token)) {\n\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\tlist.add(new Token(str_to_tokens.get(token), value, line, pos));\n\t\t\t\t\t}\n\t\t\t\t\tif (found == false) {\n\t\t\t\t\t\tthrow new Exception(\"Token not found: '\" + token + \"'\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tParser p = new Parser(list);\n\t\t\t\tp.printAST(p.parse());\n\t\t\t} catch (FileNotFoundException e) {\n\t\t\t\terror(-1, -1, \"Exception: \" + e.getMessage());\n\t\t\t} catch (Exception e) {\n\t\t\t\terror(-1, -1, \"Exception: \" + e.getMessage());\n\t\t\t}\n\t\t} else {\n\t\t\terror(-1, -1, \"No args\");\n\t\t}\n\t}\n}\n"} {"title": "Conjugate transpose", "language": "Java", "task": "Suppose that a conjugate transpose of M is a matrix M^H containing the [[complex conjugate]]s of the [[matrix transposition]] of M.\n\n::: (M^H)_{ji} = \\overline{M_{ij}}\n\n\nThis means that row j, column i of the conjugate transpose equals the \ncomplex conjugate of row i, column j of the original matrix.\n\n\nIn the next list, M must also be a square matrix.\n\n* A Hermitian matrix equals its own conjugate transpose: M^H = M.\n* A multiplication with its conjugate transpose: M^HM = MM^H.\n* A iff M^HM = I_n and iff MM^H = I_n, where I_n is the identity matrix.\n\n\n\n;Task:\nGiven some matrix of complex numbers, find its conjugate transpose. \n\nAlso determine if the matrix is a:\n::* Hermitian matrix,\n::* normal matrix, or \n::* unitary matrix.\n\n\n;See also:\n* MathWorld entry: conjugate transpose\n* MathWorld entry: Hermitian matrix\n* MathWorld entry: normal matrix\n* MathWorld entry: unitary matrix\n\n", "solution": "import java.util.Arrays;\nimport java.util.List;\n\npublic final class ConjugateTranspose {\n\n\tpublic static void main(String[] aArgs) {\t\t\n\t\tComplexMatrix one = new ComplexMatrix( new Complex[][] { { new Complex(0, 4), new Complex(-1, 1) },\n\t\t\t\t\t\t\t\t\t\t\t { new Complex(1, -1), new Complex(0, 4) } } );\t\t\n\n\t\tComplexMatrix two = new ComplexMatrix(\n\t\t\tnew Complex[][] { { new Complex(1, 0), new Complex(1, 1), new Complex(0, 2) },\n\t\t\t \t\t\t { new Complex(1, -1), new Complex(5, 0), new Complex(-3, 0) },\n\t\t\t\t\t\t\t { new Complex(0, -2), new Complex(-3, 0), new Complex(0, 0) } } );\n\n\t\tfinal double term = 1.0 / Math.sqrt(2.0);\n\t\tComplexMatrix three = new ComplexMatrix( new Complex[][] { { new Complex(term, 0), new Complex(term, 0) },\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t { new Complex(0, term), new Complex(0, -term) } } );\n\t\t\n\t\tList matricies = List.of( one, two, three );\n\t\tfor ( ComplexMatrix matrix : matricies ) {\n\t\t\tSystem.out.println(\"Matrix:\");\n\t\t\tmatrix.display();\n\t\t\tSystem.out.println(\"Conjugate transpose:\");\n\t\t\tmatrix.conjugateTranspose().display();\n\t\t\tSystem.out.println(\"Hermitian: \" + matrix.isHermitian());\n\t\t\tSystem.out.println(\"Normal: \" + matrix.isNormal());\n\t\t\tSystem.out.println(\"Unitary: \" + matrix.isUnitary() + System.lineSeparator());\n\t\t}\n\t}\n\n}\n\nfinal class ComplexMatrix {\n\t\n\tpublic ComplexMatrix(Complex[][] aData) {\n\t\trowCount = aData.length;\n colCount = aData[0].length;\n data = Arrays.stream(aData).map( row -> Arrays.copyOf(row, row.length) ).toArray(Complex[][]::new);\n\t} \n\t\n\tpublic ComplexMatrix multiply(ComplexMatrix aOther) {\n if ( colCount != aOther.rowCount ) { \n \tthrow new RuntimeException(\"Incompatible matrix dimensions.\");\n } \n Complex[][] newData = new Complex[rowCount][aOther.colCount];\n Arrays.stream(newData).forEach( row -> Arrays.fill(row, new Complex(0, 0)) );\n for ( int row = 0; row < rowCount; row++ ) {\n for ( int col = 0; col < aOther.colCount; col++ ) {\n for ( int k = 0; k < colCount; k++ ) {\n newData[row][col] = newData[row][col].add(data[row][k].multiply(aOther.data[k][col]));\n }\n }\n }\n return new ComplexMatrix(newData);\n } \n\n public ComplexMatrix conjugateTranspose() {\n \tif ( rowCount != colCount ) {\n \t\tthrow new IllegalArgumentException(\"Only applicable to a square matrix\");\n \t} \t\n \tComplex[][] newData = new Complex[colCount][rowCount];\n for ( int row = 0; row < rowCount; row++ ) {\n for ( int col = 0; col < colCount; col++ ) {\n newData[col][row] = data[row][col].conjugate();\n }\n }\n return new ComplexMatrix(newData);\n }\n \n public static ComplexMatrix identity(int aSize) {\n \tComplex[][] data = new Complex[aSize][aSize];\n for ( int row = 0; row < aSize; row++ ) {\n \tfor ( int col = 0; col < aSize; col++ ) {\n \t\tdata[row][col] = ( row == col ) ? new Complex(1, 0) : new Complex(0, 0);\n \t}\n }\n return new ComplexMatrix(data);\n }\n \n public boolean equals(ComplexMatrix aOther) { \t\n if ( aOther.rowCount != rowCount || aOther.colCount != colCount ) {\n \treturn false;\n } \n for ( int row = 0; row < rowCount; row++ ) {\n for ( int col = 0; col < colCount; col++ ) {\n \tif ( data[row][col].subtract(aOther.data[row][col]).modulus() > EPSILON ) {\n \treturn false;\n }\n }\n }\n return true;\n } \n \n public void display() {\n for ( int row = 0; row < rowCount; row++ ) {\n \tSystem.out.print(\"[\");\n for ( int col = 0; col < colCount - 1; col++ ) { \n System.out.print(data[row][col] + \", \");\n }\n System.out.println(data[row][colCount - 1] + \" ]\");\n }\n }\n \n public boolean isHermitian() {\n \treturn equals(conjugateTranspose());\n }\n \n public boolean isNormal() {\n \tComplexMatrix conjugateTranspose = conjugateTranspose();\n \treturn multiply(conjugateTranspose).equals(conjugateTranspose.multiply(this));\n }\n \n public boolean isUnitary() {\n \tComplexMatrix conjugateTranspose = conjugateTranspose();\n \treturn multiply(conjugateTranspose).equals(identity(rowCount)) &&\n \t\t conjugateTranspose.multiply(this).equals(identity(rowCount));\n } \n \n private final int rowCount;\n private final int colCount;\n private final Complex[][] data;\n \n private static final double EPSILON = 0.000_000_000_001;\n\t\n}\n\nfinal class Complex {\n\t\n\tpublic Complex(double aReal, double aImag) {\n\t\treal = aReal;\n\t\timag = aImag;\n\t}\t\t\n\t\n\tpublic Complex add(Complex aOther) {\n\t\treturn new Complex(real + aOther.real, imag + aOther.imag);\n\t}\n\t\n\tpublic Complex multiply(Complex aOther) {\n\t\treturn new Complex(real * aOther.real - imag * aOther.imag, real * aOther.imag + imag * aOther.real);\n\t}\n\t\n\tpublic Complex negate() {\n\t\treturn new Complex(-real, -imag);\n\t}\n\t\n\tpublic Complex subtract(Complex aOther) {\n\t\treturn this.add(aOther.negate());\n\t}\n\t\n\tpublic Complex conjugate() {\n\t\treturn new Complex(real, -imag);\n\t}\n\t\t\n\tpublic double modulus() {\n\t\treturn Math.hypot(real, imag);\n\t}\n\t\n\tpublic boolean equals(Complex aOther) {\n\t\treturn real == aOther.real && imag == aOther.imag;\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\tString prefix = ( real < 0.0 ) ? \"\" : \" \";\n\t\tString realPart = prefix + String.format(\"%.3f\", real);\n\t\tString sign = ( imag < 0.0 ) ? \" - \" : \" + \";\n\t\treturn realPart + sign + String.format(\"%.3f\", Math.abs(imag)) + \"i\";\n\t}\n\t\n\tprivate final double real;\n\tprivate final double imag;\n\t\n}\t\n"} {"title": "Continued fraction", "language": "Java 8", "task": "A number may be represented as a continued fraction (see Mathworld for more information) as follows:\n:a_0 + \\cfrac{b_1}{a_1 + \\cfrac{b_2}{a_2 + \\cfrac{b_3}{a_3 + \\ddots}}}\n\nThe task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:\n\nFor the square root of 2, use a_0 = 1 then a_N = 2. b_N is always 1.\n\n:\\sqrt{2} = 1 + \\cfrac{1}{2 + \\cfrac{1}{2 + \\cfrac{1}{2 + \\ddots}}}\n\nFor Napier's Constant, use a_0 = 2, then a_N = N. b_1 = 1 then b_N = N-1.\n\n:e = 2 + \\cfrac{1}{1 + \\cfrac{1}{2 + \\cfrac{2}{3 + \\cfrac{3}{4 + \\ddots}}}}\n\nFor Pi, use a_0 = 3 then a_N = 6. b_N = (2N-1)^2.\n\n:\\pi = 3 + \\cfrac{1}{6 + \\cfrac{9}{6 + \\cfrac{25}{6 + \\ddots}}}\n\n\n;See also:\n:* [[Continued fraction/Arithmetic]] for tasks that do arithmetic over continued fractions.\n\n", "solution": "import static java.lang.Math.pow;\nimport java.util.*;\nimport java.util.function.Function;\n\npublic class Test {\n static double calc(Function f, int n) {\n double temp = 0;\n\n for (int ni = n; ni >= 1; ni--) {\n Integer[] p = f.apply(ni);\n temp = p[1] / (double) (p[0] + temp);\n }\n return f.apply(0)[0] + temp;\n }\n\n public static void main(String[] args) {\n List> fList = new ArrayList<>();\n fList.add(n -> new Integer[]{n > 0 ? 2 : 1, 1});\n fList.add(n -> new Integer[]{n > 0 ? n : 2, n > 1 ? (n - 1) : 1});\n fList.add(n -> new Integer[]{n > 0 ? 6 : 3, (int) pow(2 * n - 1, 2)});\n\n for (Function f : fList)\n System.out.println(calc(f, 200));\n }\n}"} {"title": "Continued fraction/Arithmetic/Construct from rational number", "language": "Java 9", "task": "To understand this task in context please see [[Continued fraction arithmetic]]\nThe purpose of this task is to write a function \\mathit{r2cf}(\\mathrm{int} N_1, \\mathrm{int} N_2), or \\mathit{r2cf}(\\mathrm{Fraction} N), which will output a continued fraction assuming:\n:N_1 is the numerator\n:N_2 is the denominator\n \nThe function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.\n\nTo achieve this it must determine: the integer part; and remainder part, of N_1 divided by N_2. It then sets N_1 to N_2 and N_2 to the determined remainder part. It then outputs the determined integer part. It does this until \\mathrm{abs}(N_2) is zero.\n\nDemonstrate the function by outputing the continued fraction for:\n: 1/2\n: 3\n: 23/8\n: 13/11\n: 22/7\n: -151/77\n\\sqrt 2 should approach [1; 2, 2, 2, 2, \\ldots] try ever closer rational approximations until boredom gets the better of you:\n: 14142,10000\n: 141421,100000\n: 1414214,1000000\n: 14142136,10000000\n\nTry :\n: 31,10\n: 314,100\n: 3142,1000\n: 31428,10000\n: 314285,100000\n: 3142857,1000000\n: 31428571,10000000\n: 314285714,100000000\n\nObserve how this rational number behaves differently to \\sqrt 2 and convince yourself that, in the same way as 3.7 may be represented as 3.70 when an extra decimal place is required, [3;7] may be represented as [3;7,\\infty] when an extra term is required.\n\n", "solution": "import java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\n\npublic class ConstructFromRationalNumber {\n private static class R2cf implements Iterator {\n private int num;\n private int den;\n\n R2cf(int num, int den) {\n this.num = num;\n this.den = den;\n }\n\n @Override\n public boolean hasNext() {\n return den != 0;\n }\n\n @Override\n public Integer next() {\n int div = num / den;\n int rem = num % den;\n num = den;\n den = rem;\n return div;\n }\n }\n\n private static void iterate(R2cf generator) {\n generator.forEachRemaining(n -> System.out.printf(\"%d \", n));\n System.out.println();\n }\n\n public static void main(String[] args) {\n List> fracs = List.of(\n Map.entry(1, 2),\n Map.entry(3, 1),\n Map.entry(23, 8),\n Map.entry(13, 11),\n Map.entry(22, 7),\n Map.entry(-151, 77)\n );\n for (Map.Entry frac : fracs) {\n System.out.printf(\"%4d / %-2d = \", frac.getKey(), frac.getValue());\n iterate(new R2cf(frac.getKey(), frac.getValue()));\n }\n\n System.out.println(\"\\nSqrt(2) ->\");\n List> root2 = List.of(\n Map.entry( 14_142, 10_000),\n Map.entry( 141_421, 100_000),\n Map.entry( 1_414_214, 1_000_000),\n Map.entry(14_142_136, 10_000_000)\n );\n for (Map.Entry frac : root2) {\n System.out.printf(\"%8d / %-8d = \", frac.getKey(), frac.getValue());\n iterate(new R2cf(frac.getKey(), frac.getValue()));\n }\n\n System.out.println(\"\\nPi ->\");\n List> pi = List.of(\n Map.entry( 31, 10),\n Map.entry( 314, 100),\n Map.entry( 3_142, 1_000),\n Map.entry( 31_428, 10_000),\n Map.entry( 314_285, 100_000),\n Map.entry( 3_142_857, 1_000_000),\n Map.entry( 31_428_571, 10_000_000),\n Map.entry(314_285_714, 100_000_000)\n );\n for (Map.Entry frac : pi) {\n System.out.printf(\"%9d / %-9d = \", frac.getKey(), frac.getValue());\n iterate(new R2cf(frac.getKey(), frac.getValue()));\n }\n }\n}"} {"title": "Convert decimal number to rational", "language": "Java", "task": "The task is to write a program to transform a decimal number into a fraction in lowest terms.\n\nIt is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333...\n\nBecause of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals:\n* 67 / 74 = 0.9(054) = 0.9054054...\n* 14 / 27 = 0.(518) = 0.518518...\n\nAcceptable output:\n\n* 0.9054054 - 4527027 / 5000000\n* 0.518518 - 259259 / 500000\n\nFinite decimals are of course no problem:\n\n* 0.75 - 3 / 4 \n\n", "solution": "double fractionToDecimal(String string) {\n int indexOf = string.indexOf(' ');\n int integer = 0;\n int numerator, denominator;\n if (indexOf != -1) {\n integer = Integer.parseInt(string.substring(0, indexOf));\n string = string.substring(indexOf + 1);\n }\n indexOf = string.indexOf('/');\n numerator = Integer.parseInt(string.substring(0, indexOf));\n denominator = Integer.parseInt(string.substring(indexOf + 1));\n return integer + ((double) numerator / denominator);\n}\n\nString decimalToFraction(double value) {\n String string = String.valueOf(value);\n string = string.substring(string.indexOf('.') + 1);\n int numerator = Integer.parseInt(string);\n int denominator = (int) Math.pow(10, string.length());\n int gcf = gcf(numerator, denominator);\n if (gcf != 0) {\n numerator /= gcf;\n denominator /= gcf;\n }\n int integer = (int) value;\n if (integer != 0)\n return \"%d %d/%d\".formatted(integer, numerator, denominator);\n return \"%d/%d\".formatted(numerator, denominator);\n}\n\nint gcf(int valueA, int valueB) {\n if (valueB == 0) return valueA;\n else return gcf(valueB, valueA % valueB);\n}\n"} {"title": "Convert seconds to compound duration", "language": "Java", "task": "Write a function or program which:\n* takes a positive integer representing a duration in seconds as input (e.g., 100), and\n* returns a string which shows the same duration decomposed into:\n:::* weeks,\n:::* days, \n:::* hours, \n:::* minutes, and \n:::* seconds.\n\nThis is detailed below (e.g., \"2 hr, 59 sec\").\n\n\nDemonstrate that it passes the following three test-cases:\n\n'''''Test Cases'''''\n\n:::::{| class=\"wikitable\"\n|-\n! input number\n! output string\n|-\n| 7259\n| 2 hr, 59 sec\n|-\n| 86400\n| 1 d\n|-\n| 6000000\n| 9 wk, 6 d, 10 hr, 40 min\n|}\n\n'''''Details'''''\n\nThe following five units should be used:\n:::::{| class=\"wikitable\"\n|-\n! unit\n! suffix used in output\n! conversion\n|-\n| week\n| wk\n| 1 week = 7 days\n|-\n| day\n| d\n| 1 day = 24 hours\n|-\n| hour\n| hr\n| 1 hour = 60 minutes\n|-\n| minute\n| min\n| 1 minute = 60 seconds\n|-\n| second\n| sec\n| \n|}\n\nHowever, '''only''' include quantities with non-zero values in the output (e.g., return \"1 d\" and not \"0 wk, 1 d, 0 hr, 0 min, 0 sec\").\n\nGive larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)\n\nMimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).\n\n\n", "solution": "String duration(int seconds) {\n StringBuilder string = new StringBuilder();\n if (seconds >= 604_800 /* 1 wk */) {\n string.append(\"%,d wk\".formatted(seconds / 604_800));\n seconds %= 604_800;\n }\n if (seconds >= 86_400 /* 1 d */) {\n if (!string.isEmpty()) string.append(\", \");\n string.append(\"%d d\".formatted(seconds / 86_400));\n seconds %= 86_400;\n }\n if (seconds >= 3600 /* 1 hr */) {\n if (!string.isEmpty()) string.append(\", \");\n string.append(\"%d hr\".formatted(seconds / 3600));\n seconds %= 3600;\n }\n if (seconds >= 60 /* 1 min */) {\n if (!string.isEmpty()) string.append(\", \");\n string.append(\"%d min\".formatted(seconds / 60));\n seconds %= 60;\n }\n if (seconds > 0) {\n if (!string.isEmpty()) string.append(\", \");\n string.append(\"%d sec\".formatted(seconds));\n }\n return string.toString();\n}\n"} {"title": "Copy stdin to stdout", "language": "Java", "task": "Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.\n\n", "solution": "import java.util.Scanner;\n\npublic class CopyStdinToStdout {\n\n public static void main(String[] args) {\n try (Scanner scanner = new Scanner(System.in);) {\n String s;\n while ( (s = scanner.nextLine()).compareTo(\"\") != 0 ) {\n System.out.println(s);\n }\n }\n }\n\n}\n"} {"title": "Count the coins", "language": "Java 1.5+", "task": "There are four types of common coins in US currency: \n:::# quarters (25 cents)\n:::# dimes (10 cents)\n:::# nickels (5 cents), and \n:::# pennies (1 cent) \n\n\nThere are six ways to make change for 15 cents:\n:::# A dime and a nickel \n:::# A dime and 5 pennies\n:::# 3 nickels\n:::# 2 nickels and 5 pennies\n:::# A nickel and 10 pennies\n:::# 15 pennies\n\n\n;Task:\nHow many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).\n\n\n;Optional:\nLess common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000? \n\n(Note: the answer is larger than 232).\n\n\n;References:\n* an algorithm from the book ''Structure and Interpretation of Computer Programs''.\n* an article in the algorithmist.\n* Change-making problem on Wikipedia.\n\n", "solution": "import java.util.Arrays;\nimport java.math.BigInteger;\n\nclass CountTheCoins {\n private static BigInteger countChanges(int amount, int[] coins){\n final int n = coins.length;\n int cycle = 0;\n for (int c : coins)\n if (c <= amount && c >= cycle)\n cycle = c + 1;\n cycle *= n;\n BigInteger[] table = new BigInteger[cycle];\n Arrays.fill(table, 0, n, BigInteger.ONE);\n Arrays.fill(table, n, cycle, BigInteger.ZERO);\n\n int pos = n;\n for (int s = 1; s <= amount; s++) {\n for (int i = 0; i < n; i++) {\n if (i == 0 && pos >= cycle)\n pos = 0;\n if (coins[i] <= s) {\n final int q = pos - (coins[i] * n);\n table[pos] = (q >= 0) ? table[q] : table[q + cycle];\n }\n if (i != 0)\n table[pos] = table[pos].add(table[pos - 1]);\n pos++;\n }\n }\n\n return table[pos - 1];\n }\n\n public static void main(String[] args) {\n final int[][] coinsUsEu = {{100, 50, 25, 10, 5, 1},\n {200, 100, 50, 20, 10, 5, 2, 1}};\n\n for (int[] coins : coinsUsEu) {\n System.out.println(countChanges( 100,\n Arrays.copyOfRange(coins, 2, coins.length)));\n System.out.println(countChanges( 100000, coins));\n System.out.println(countChanges( 1000000, coins));\n System.out.println(countChanges(10000000, coins) + \"\\n\");\n }\n }\n}"} {"title": "Create an HTML table", "language": "Java", "task": "Create an HTML table. \n* The table body should have at least three rows of three columns.\n* Each of these three columns should be labelled \"X\", \"Y\", and \"Z\". \n* An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. \n* The rows of the \"X\", \"Y\", and \"Z\" columns should be filled with random or sequential integers having 4 digits or less. \n* The numbers should be aligned in the same fashion for all columns.\n\n", "solution": "String generateHTMLTable() {\n StringBuilder string = new StringBuilder();\n string.append(\"\");\n string.append(System.lineSeparator());\n string.append(\"\".indent(2));\n string.append(\"\".indent(4));\n string.append(\"\".indent(4));\n string.append(\"\".indent(4));\n string.append(\"\".indent(4));\n string.append(\"\".indent(2));\n Random random = new Random();\n int number;\n for (int countA = 0; countA < 10; countA++) {\n string.append(\"\".indent(2));\n string.append(\"\".formatted(countA).indent(4));\n for (int countB = 0; countB < 3; countB++) {\n number = random.nextInt(1, 9999);\n string.append(\"\".formatted(number).indent(4));\n }\n string.append(\"\".indent(2));\n }\n string.append(\"
XYZ
%d%,d
\");\n return string.toString();\n}\n"} {"title": "Create an HTML table", "language": "Java 1.5+", "task": "Create an HTML table. \n* The table body should have at least three rows of three columns.\n* Each of these three columns should be labelled \"X\", \"Y\", and \"Z\". \n* An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. \n* The rows of the \"X\", \"Y\", and \"Z\" columns should be filled with random or sequential integers having 4 digits or less. \n* The numbers should be aligned in the same fashion for all columns.\n\n", "solution": "public class HTML {\n\n\tpublic static String array2HTML(Object[][] array){\n\t\tStringBuilder html = new StringBuilder(\n\t\t\t\t\"\");\n\t\tfor(Object elem:array[0]){\n\t\t\thtml.append(\"\");\n\t\t}\n\t\tfor(int i = 1; i < array.length; i++){\n\t\t\tObject[] row = array[i];\n\t\t\thtml.append(\"\");\n\t\t\tfor(Object elem:row){\n\t\t\t\thtml.append(\"\");\n\t\t\t}\n\t\t\thtml.append(\"\");\n\t\t}\n\t\thtml.append(\"
\" + elem.toString() + \"
\" + elem.toString() + \"
\");\n\t\treturn html.toString();\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tObject[][] ints = {{\"\",\"X\",\"Y\",\"Z\"},{1,1,2,3},{2,4,5,6},{3,7,8,9},{4,10,11,12}};\n\t\tSystem.out.println(array2HTML(ints));\n\t}\n}"} {"title": "Cullen and Woodall numbers", "language": "Java", "task": "A Cullen number is a number of the form '''n x 2n + 1''' where '''n''' is a natural number.\n\nA Woodall number is very similar. It is a number of the form '''n x 2n - 1''' where '''n''' is a natural number.\n\nSo for each '''n''' the associated Cullen number and Woodall number differ by 2.\n\n''Woodall numbers are sometimes referred to as Riesel numbers or Cullen numbers of the second kind.''\n\n\n'''Cullen primes''' are Cullen numbers that are prime. Similarly, '''Woodall primes''' are Woodall numbers that are prime.\n\nIt is common to list the Cullen and Woodall primes by the value of '''n''' rather than the full evaluated expression. They tend to get very large very quickly. For example, the third Cullen prime, '''n''' == 4713, has 1423 digits when evaluated.\n\n\n;Task\n\n* Write procedures to find Cullen numbers and Woodall numbers. \n\n* Use those procedures to find and show here, on this page the first 20 of each.\n\n\n;Stretch\n\n* Find and show the first '''5''' '''Cullen primes''' in terms of '''n'''.\n\n* Find and show the first '''12''' '''Woodall primes''' in terms of '''n'''.\n\n\n;See also\n\n* OEIS:A002064 - Cullen numbers: a(n) = n*2^n + 1\n\n* OEIS:A003261 - Woodall (or Riesel) numbers: n*2^n - 1\n\n* OEIS:A005849 - Indices of prime Cullen numbers: numbers k such that k*2^k + 1 is prime\n\n* OEIS:A002234 - Numbers k such that the Woodall number k*2^k - 1 is prime\n\n\n", "solution": "import java.math.BigInteger;\n\npublic final class CullenAndWoodhall {\n\n\tpublic static void main(String[] aArgs) {\n\t\tnumberSequence(20, NumberType.Cullen);\n\t\t\n\t\tnumberSequence(20, NumberType.Woodhall);\n\t\t\n\t\tprimeSequence(5, NumberType.Cullen);\n\t\t\n\t\tprimeSequence(12, NumberType.Woodhall);\n\t}\n\n\tprivate enum NumberType { Cullen, Woodhall }\n\t\n\tprivate static void numberSequence(int aCount, NumberType aNumberType) {\n\t\tSystem.out.println();\n\t\tSystem.out.println(\"The first \" + aCount + \" \" + aNumberType + \" numbers are:\");\n\t\tnumberInitialise();\n\t\tfor ( int index = 1; index <= aCount; index++ ) {\n\t\t\tSystem.out.print(nextNumber(aNumberType) + \" \");\n\t\t}\t\n\t\tSystem.out.println();\t\n\t}\n\t\n\tprivate static void primeSequence(int aCount, NumberType aNumberType) {\n\t\tSystem.out.println();\n\t\tSystem.out.println(\"The indexes of the first \" + aCount + \" \" + aNumberType + \" primes are:\");\n\t\tprimeInitialise();\n\t\t\n\t\twhile ( count < aCount ) {\t\t\t\n\t\t\tif ( nextNumber(aNumberType).isProbablePrime(CERTAINTY) ) {\n\t\t\t\tSystem.out.print(primeIndex + \" \");\n\t\t\t\tcount += 1;\n\t\t\t}\n\t\t\t\n\t\t\tprimeIndex += 1; \n\t\t}\n\t\tSystem.out.println();\n\t}\n\t\n\tprivate static BigInteger nextNumber(NumberType aNumberType) {\n\t\tnumber = number.add(BigInteger.ONE);\n\t\tpower = power.shiftLeft(1);\n\t\treturn switch ( aNumberType ) {\n\t\t\tcase Cullen -> number.multiply(power).add(BigInteger.ONE);\n\t\t\tcase Woodhall -> number.multiply(power).subtract(BigInteger.ONE);\n\t\t};\n\t}\n\t\n\tprivate static void numberInitialise() {\n\t\tnumber = BigInteger.ZERO;\n\t\tpower = BigInteger.ONE;\t\t\n\t}\n\t\n\tprivate static void primeInitialise() {\t\n\t\tcount = 0;\n\t\tprimeIndex = 1;\n\t\tnumberInitialise();\n\t}\n\t\n\tprivate static BigInteger number;\n\tprivate static BigInteger power;\n\tprivate static int count;\n\tprivate static int primeIndex;\n\t\n\tprivate static final int CERTAINTY = 20;\n\t\n}\n"} {"title": "Currency", "language": "Java", "task": "Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents. \n\n\n;Note:\nThe '''IEEE 754''' binary floating point representations of numbers like '''2.86''' and '''.0765''' are not exact.\n\nFor this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate. \n \nUse the values:\n::* 4000000000000000 hamburgers at $5.50 each (four quadrillion burgers)\n::* 2 milkshakes at $2.86 each, and \n::* a tax rate of 7.65%. \n\n\n(That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naive task solutions using 64 bit floating point types.) \n\nCompute and output (show results on this page):\n::* the total price before tax\n::* the tax\n::* the total with tax \n\n\nThe tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax. \n\nThe output must show dollars and cents with a decimal point. \n \nThe three results displayed should be:\n::* 22000000000000005.72\n::* 1683000000000000.44 \n::* 23683000000000006.16 \n\n\nDollar signs and thousands separators are optional.\n\n", "solution": "import java.math.*;\nimport java.util.*;\n\npublic class Currency {\n final static String taxrate = \"7.65\";\n\n enum MenuItem {\n\n Hamburger(\"5.50\"), Milkshake(\"2.86\");\n\n private MenuItem(String p) {\n price = new BigDecimal(p);\n }\n\n public final BigDecimal price;\n }\n\n public static void main(String[] args) {\n Locale.setDefault(Locale.ENGLISH);\n\n MathContext mc = MathContext.DECIMAL128;\n\n Map order = new HashMap<>();\n order.put(MenuItem.Hamburger, new BigDecimal(\"4000000000000000\"));\n order.put(MenuItem.Milkshake, new BigDecimal(\"2\"));\n\n BigDecimal subtotal = BigDecimal.ZERO;\n for (MenuItem it : order.keySet())\n subtotal = subtotal.add(it.price.multiply(order.get(it), mc));\n\n BigDecimal tax = new BigDecimal(taxrate, mc);\n tax = tax.divide(new BigDecimal(\"100\"), mc);\n tax = subtotal.multiply(tax, mc);\n\n System.out.printf(\"Subtotal: %20.2f%n\", subtotal);\n System.out.printf(\" Tax: %20.2f%n\", tax);\n System.out.printf(\" Total: %20.2f%n\", subtotal.add(tax));\n }\n}"} {"title": "Currying", "language": "Java", "task": "{{Wikipedia|Currying}}\n\n\n;Task:\nCreate a simple demonstrative example of Currying in a specific language. \n\nAdd any historic details as to how the feature made its way into the language.\n\n\n\n", "solution": "public class Currier {\n public interface CurriableFunctor {\n RET evaluate(ARG1 arg1, ARG2 arg2);\n }\n \n public interface CurriedFunctor {\n RET evaluate(ARG2 arg);\n }\n \n final CurriableFunctor functor;\n \n public Currier(CurriableFunctor fn) { functor = fn; }\n \n public CurriedFunctor curry(final ARG1 arg1) {\n return new CurriedFunctor() {\n public RET evaluate(ARG2 arg2) {\n return functor.evaluate(arg1, arg2);\n }\n };\n }\n \n public static void main(String[] args) {\n Currier.CurriableFunctor add\n = new Currier.CurriableFunctor() {\n public Integer evaluate(Integer arg1, Integer arg2) {\n return new Integer(arg1.intValue() + arg2.intValue());\n }\n };\n \n Currier currier\n = new Currier(add);\n \n Currier.CurriedFunctor add5\n = currier.curry(new Integer(5));\n \n System.out.println(add5.evaluate(new Integer(2)));\n }\n }"} {"title": "Cut a rectangle", "language": "Java 7", "task": "A given rectangle is made from ''m'' x ''n'' squares. If ''m'' and ''n'' are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180deg). All such paths for 2 x 2 and 4 x 3 rectangles are shown below.\n\n[[file:rect-cut.svg]]\n\nWrite a program that calculates the number of different ways to cut an ''m'' x ''n'' rectangle. Optionally, show each of the cuts.\n\nPossibly related task: [[Maze generation]] for depth-first search.\n\n", "solution": "import java.util.*;\n\npublic class CutRectangle {\n\n private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};\n\n public static void main(String[] args) {\n cutRectangle(2, 2);\n cutRectangle(4, 3);\n }\n\n static void cutRectangle(int w, int h) {\n if (w % 2 == 1 && h % 2 == 1)\n return;\n\n int[][] grid = new int[h][w];\n Stack stack = new Stack<>();\n\n int half = (w * h) / 2;\n long bits = (long) Math.pow(2, half) - 1;\n\n for (; bits > 0; bits -= 2) {\n\n for (int i = 0; i < half; i++) {\n int r = i / w;\n int c = i % w;\n grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n }\n\n stack.push(0);\n grid[0][0] = 2;\n int count = 1;\n while (!stack.empty()) {\n\n int pos = stack.pop();\n int r = pos / w;\n int c = pos % w;\n\n for (int[] dir : dirs) {\n\n int nextR = r + dir[0];\n int nextC = c + dir[1];\n\n if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n\n if (grid[nextR][nextC] == 1) {\n stack.push(nextR * w + nextC);\n grid[nextR][nextC] = 2;\n count++;\n }\n }\n }\n }\n if (count == half) {\n printResult(grid);\n }\n }\n }\n\n static void printResult(int[][] arr) {\n for (int[] a : arr)\n System.out.println(Arrays.toString(a));\n System.out.println();\n }\n}"} {"title": "Cyclotomic polynomial", "language": "Java", "task": "The nth Cyclotomic polynomial, for any positive integer n, is the unique irreducible polynomial of largest degree with integer coefficients that is a divisor of x^n - 1, and is not a divisor of x^k - 1 for any k < n.\n\n\n;Task:\n* Find and print the first 30 cyclotomic polynomials.\n* Find and print the order of the first 10 cyclotomic polynomials that have n or -n as a coefficient.\n\n\n;See also\n* Wikipedia article, Cyclotomic polynomial, showing ways to calculate them.\n* The sequence A013594 with the smallest order of cyclotomic polynomial containing n or -n as a coefficient.\n\n", "solution": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.TreeMap;\n\npublic class CyclotomicPolynomial {\n\n @SuppressWarnings(\"unused\")\n private static int divisions = 0;\n private static int algorithm = 2;\n \n public static void main(String[] args) throws Exception {\n System.out.println(\"Task 1: cyclotomic polynomials for n <= 30:\");\n for ( int i = 1 ; i <= 30 ; i++ ) {\n Polynomial p = cyclotomicPolynomial(i);\n System.out.printf(\"CP[%d] = %s%n\", i, p);\n }\n System.out.println(\"Task 2: Smallest cyclotomic polynomial with n or -n as a coefficient:\");\n int n = 0;\n for ( int i = 1 ; i <= 10 ; i++ ) {\n while ( true ) {\n n++;\n Polynomial cyclo = cyclotomicPolynomial(n);\n if ( cyclo.hasCoefficientAbs(i) ) {\n System.out.printf(\"CP[%d] has coefficient with magnitude = %d%n\", n, i);\n n--;\n break;\n }\n }\n }\n }\n\n private static final Map COMPUTED = new HashMap<>();\n \n private static Polynomial cyclotomicPolynomial(int n) {\n if ( COMPUTED.containsKey(n) ) {\n return COMPUTED.get(n);\n }\n \n //System.out.println(\"COMPUTE: n = \" + n);\n \n if ( n == 1 ) {\n // Polynomial: x - 1\n Polynomial p = new Polynomial(1, 1, -1, 0);\n COMPUTED.put(1, p);\n return p;\n }\n\n Map factors = getFactors(n);\n \n if ( factors.containsKey(n) ) {\n // n prime\n List termList = new ArrayList<>();\n for ( int index = 0 ; index < n ; index++ ) {\n termList.add(new Term(1, index));\n }\n \n Polynomial cyclo = new Polynomial(termList);\n COMPUTED.put(n, cyclo);\n return cyclo;\n }\n else if ( factors.size() == 2 && factors.containsKey(2) && factors.get(2) == 1 && factors.containsKey(n/2) && factors.get(n/2) == 1 ) {\n // n = 2p\n int prime = n/2;\n List termList = new ArrayList<>();\n int coeff = -1;\n for ( int index = 0 ; index < prime ; index++ ) {\n coeff *= -1;\n termList.add(new Term(coeff, index));\n }\n\n Polynomial cyclo = new Polynomial(termList);\n COMPUTED.put(n, cyclo);\n return cyclo;\n }\n else if ( factors.size() == 1 && factors.containsKey(2) ) {\n // n = 2^h\n int h = factors.get(2);\n List termList = new ArrayList<>();\n termList.add(new Term(1, (int) Math.pow(2, h-1)));\n termList.add(new Term(1, 0));\n Polynomial cyclo = new Polynomial(termList);\n COMPUTED.put(n, cyclo);\n return cyclo;\n }\n else if ( factors.size() == 1 && ! factors.containsKey(n) ) {\n // n = p^k\n int p = 0;\n for ( int prime : factors.keySet() ) {\n p = prime;\n }\n int k = factors.get(p);\n List termList = new ArrayList<>();\n for ( int index = 0 ; index < p ; index++ ) {\n termList.add(new Term(1, index * (int) Math.pow(p, k-1)));\n }\n\n Polynomial cyclo = new Polynomial(termList);\n COMPUTED.put(n, cyclo);\n return cyclo;\n }\n else if ( factors.size() == 2 && factors.containsKey(2) ) {\n // n = 2^h * p^k\n int p = 0;\n for ( int prime : factors.keySet() ) {\n if ( prime != 2 ) {\n p = prime;\n }\n }\n List termList = new ArrayList<>();\n int coeff = -1;\n int twoExp = (int) Math.pow(2, factors.get(2)-1);\n int k = factors.get(p);\n for ( int index = 0 ; index < p ; index++ ) {\n coeff *= -1;\n termList.add(new Term(coeff, index * twoExp * (int) Math.pow(p, k-1)));\n }\n\n Polynomial cyclo = new Polynomial(termList);\n COMPUTED.put(n, cyclo);\n return cyclo; \n }\n else if ( factors.containsKey(2) && ((n/2) % 2 == 1) && (n/2) > 1 ) {\n // CP(2m)[x] = CP(-m)[x], n odd integer > 1\n Polynomial cycloDiv2 = cyclotomicPolynomial(n/2);\n List termList = new ArrayList<>();\n for ( Term term : cycloDiv2.polynomialTerms ) {\n termList.add(term.exponent % 2 == 0 ? term : term.negate());\n }\n Polynomial cyclo = new Polynomial(termList);\n COMPUTED.put(n, cyclo);\n return cyclo; \n }\n \n // General Case\n \n if ( algorithm == 0 ) {\n // Slow - uses basic definition.\n List divisors = getDivisors(n);\n // Polynomial: ( x^n - 1 )\n Polynomial cyclo = new Polynomial(1, n, -1, 0);\n for ( int i : divisors ) {\n Polynomial p = cyclotomicPolynomial(i);\n cyclo = cyclo.divide(p);\n }\n \n COMPUTED.put(n, cyclo); \n return cyclo;\n }\n else if ( algorithm == 1 ) {\n // Faster. Remove Max divisor (and all divisors of max divisor) - only one divide for all divisors of Max Divisor\n List divisors = getDivisors(n);\n int maxDivisor = Integer.MIN_VALUE;\n for ( int div : divisors ) {\n maxDivisor = Math.max(maxDivisor, div);\n }\n List divisorsExceptMax = new ArrayList();\n for ( int div : divisors ) {\n if ( maxDivisor % div != 0 ) {\n divisorsExceptMax.add(div);\n }\n }\n\n // Polynomial: ( x^n - 1 ) / ( x^m - 1 ), where m is the max divisor\n Polynomial cyclo = new Polynomial(1, n, -1, 0).divide(new Polynomial(1, maxDivisor, -1, 0));\n for ( int i : divisorsExceptMax ) {\n Polynomial p = cyclotomicPolynomial(i);\n cyclo = cyclo.divide(p);\n }\n\n COMPUTED.put(n, cyclo);\n\n return cyclo;\n }\n else if ( algorithm == 2 ) {\n // Fastest\n // Let p ; q be primes such that p does not divide n, and q q divides n.\n // Then CP(np)[x] = CP(n)[x^p] / CP(n)[x]\n int m = 1;\n Polynomial cyclo = cyclotomicPolynomial(m);\n List primes = new ArrayList<>(factors.keySet());\n Collections.sort(primes);\n for ( int prime : primes ) {\n // CP(m)[x]\n Polynomial cycloM = cyclo;\n // Compute CP(m)[x^p].\n List termList = new ArrayList<>();\n for ( Term t : cycloM.polynomialTerms ) {\n termList.add(new Term(t.coefficient, t.exponent * prime));\n }\n cyclo = new Polynomial(termList).divide(cycloM);\n m = m * prime;\n }\n // Now, m is the largest square free divisor of n\n int s = n / m;\n // Compute CP(n)[x] = CP(m)[x^s]\n List termList = new ArrayList<>();\n for ( Term t : cyclo.polynomialTerms ) {\n termList.add(new Term(t.coefficient, t.exponent * s));\n }\n cyclo = new Polynomial(termList);\n COMPUTED.put(n, cyclo);\n\n return cyclo;\n }\n else {\n throw new RuntimeException(\"ERROR 103: Invalid algorithm.\");\n }\n }\n \n private static final List getDivisors(int number) {\n List divisors = new ArrayList();\n long sqrt = (long) Math.sqrt(number);\n for ( int i = 1 ; i <= sqrt ; i++ ) {\n if ( number % i == 0 ) {\n divisors.add(i);\n int div = number / i;\n if ( div != i && div != number ) {\n divisors.add(div);\n }\n }\n }\n return divisors;\n }\n\n private static final Map> allFactors = new TreeMap>();\n static {\n Map factors = new TreeMap();\n factors.put(2, 1);\n allFactors.put(2, factors);\n }\n\n public static Integer MAX_ALL_FACTORS = 100000;\n\n public static final Map getFactors(Integer number) {\n if ( allFactors.containsKey(number) ) {\n return allFactors.get(number);\n }\n Map factors = new TreeMap();\n if ( number % 2 == 0 ) {\n Map factorsdDivTwo = getFactors(number/2);\n factors.putAll(factorsdDivTwo);\n factors.merge(2, 1, (v1, v2) -> v1 + v2);\n if ( number < MAX_ALL_FACTORS ) \n allFactors.put(number, factors);\n return factors;\n }\n boolean prime = true;\n long sqrt = (long) Math.sqrt(number);\n for ( int i = 3 ; i <= sqrt ; i += 2 ) {\n if ( number % i == 0 ) {\n prime = false;\n factors.putAll(getFactors(number/i));\n factors.merge(i, 1, (v1, v2) -> v1 + v2);\n if ( number < MAX_ALL_FACTORS ) \n allFactors.put(number, factors);\n return factors;\n }\n }\n if ( prime ) {\n factors.put(number, 1);\n if ( number < MAX_ALL_FACTORS ) \n allFactors.put(number, factors);\n }\n return factors;\n }\n \n private static final class Polynomial {\n\n private List polynomialTerms;\n \n // Format - coeff, exp, coeff, exp, (repeating in pairs) . . .\n public Polynomial(int ... values) {\n if ( values.length % 2 != 0 ) {\n throw new IllegalArgumentException(\"ERROR 102: Polynomial constructor. Length must be even. Length = \" + values.length);\n }\n polynomialTerms = new ArrayList<>();\n for ( int i = 0 ; i < values.length ; i += 2 ) {\n Term t = new Term(values[i], values[i+1]);\n polynomialTerms.add(t);\n }\n Collections.sort(polynomialTerms, new TermSorter());\n }\n \n public Polynomial() {\n // zero\n polynomialTerms = new ArrayList<>();\n polynomialTerms.add(new Term(0,0));\n }\n \n private boolean hasCoefficientAbs(int coeff) {\n for ( Term term : polynomialTerms ) {\n if ( Math.abs(term.coefficient) == coeff ) {\n return true;\n }\n }\n return false;\n }\n \n private Polynomial(List termList) {\n if ( termList.size() == 0 ) {\n // zero\n termList.add(new Term(0,0));\n }\n else {\n // Remove zero terms if needed\n for ( int i = 0 ; i < termList.size() ; i++ ) {\n if ( termList.get(i).coefficient == 0 ) {\n termList.remove(i);\n }\n }\n }\n if ( termList.size() == 0 ) {\n // zero\n termList.add(new Term(0,0));\n }\n polynomialTerms = termList;\n Collections.sort(polynomialTerms, new TermSorter());\n }\n \n public Polynomial divide(Polynomial v) {\n //long start = System.currentTimeMillis();\n divisions++;\n Polynomial q = new Polynomial();\n Polynomial r = this;\n long lcv = v.leadingCoefficient();\n long dv = v.degree();\n while ( r.degree() >= v.degree() ) {\n long lcr = r.leadingCoefficient();\n long s = lcr / lcv; // Integer division\n Term term = new Term(s, r.degree() - dv);\n q = q.add(term);\n r = r.add(v.multiply(term.negate()));\n }\n //long end = System.currentTimeMillis();\n //System.out.printf(\"Divide: Elapsed = %d, Degree 1 = %d, Degree 2 = %d%n\", (end-start), this.degree(), v.degree());\n return q;\n }\n\n public Polynomial add(Polynomial polynomial) {\n List termList = new ArrayList<>();\n int thisCount = polynomialTerms.size();\n int polyCount = polynomial.polynomialTerms.size();\n while ( thisCount > 0 || polyCount > 0 ) {\n Term thisTerm = thisCount == 0 ? null : polynomialTerms.get(thisCount-1);\n Term polyTerm = polyCount == 0 ? null : polynomial.polynomialTerms.get(polyCount-1);\n if ( thisTerm == null ) {\n termList.add(polyTerm.clone());\n polyCount--;\n }\n else if (polyTerm == null ) {\n termList.add(thisTerm.clone());\n thisCount--;\n }\n else if ( thisTerm.degree() == polyTerm.degree() ) {\n Term t = thisTerm.add(polyTerm);\n if ( t.coefficient != 0 ) {\n termList.add(t);\n }\n thisCount--;\n polyCount--;\n }\n else if ( thisTerm.degree() < polyTerm.degree() ) {\n termList.add(thisTerm.clone());\n thisCount--;\n }\n else {\n termList.add(polyTerm.clone());\n polyCount--;\n }\n }\n return new Polynomial(termList);\n }\n\n public Polynomial add(Term term) {\n List termList = new ArrayList<>();\n boolean added = false;\n for ( int index = 0 ; index < polynomialTerms.size() ; index++ ) {\n Term currentTerm = polynomialTerms.get(index);\n if ( currentTerm.exponent == term.exponent ) {\n added = true;\n if ( currentTerm.coefficient + term.coefficient != 0 ) {\n termList.add(currentTerm.add(term));\n }\n }\n else {\n termList.add(currentTerm.clone());\n }\n }\n if ( ! added ) {\n termList.add(term.clone());\n }\n return new Polynomial(termList);\n }\n\n public Polynomial multiply(Term term) {\n List termList = new ArrayList<>();\n for ( int index = 0 ; index < polynomialTerms.size() ; index++ ) {\n Term currentTerm = polynomialTerms.get(index);\n termList.add(currentTerm.clone().multiply(term));\n }\n return new Polynomial(termList);\n }\n\n public Polynomial clone() {\n List clone = new ArrayList<>();\n for ( Term t : polynomialTerms ) {\n clone.add(new Term(t.coefficient, t.exponent));\n }\n return new Polynomial(clone);\n }\n\n public long leadingCoefficient() {\n// long coefficient = 0;\n// long degree = Integer.MIN_VALUE;\n// for ( Term t : polynomialTerms ) {\n// if ( t.degree() > degree ) {\n// coefficient = t.coefficient;\n// degree = t.degree();\n// }\n// }\n return polynomialTerms.get(0).coefficient;\n }\n\n public long degree() {\n// long degree = Integer.MIN_VALUE;\n// for ( Term t : polynomialTerms ) {\n// if ( t.degree() > degree ) {\n// degree = t.degree();\n// }\n// }\n return polynomialTerms.get(0).exponent;\n }\n \n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n boolean first = true;\n for ( Term term : polynomialTerms ) {\n if ( first ) {\n sb.append(term);\n first = false;\n }\n else {\n sb.append(\" \");\n if ( term.coefficient > 0 ) {\n sb.append(\"+ \");\n sb.append(term);\n }\n else {\n sb.append(\"- \");\n sb.append(term.negate());\n }\n }\n }\n return sb.toString();\n }\n }\n \n private static final class TermSorter implements Comparator {\n @Override\n public int compare(Term o1, Term o2) {\n return (int) (o2.exponent - o1.exponent);\n } \n }\n \n // Note: Cyclotomic Polynomials have small coefficients. Not appropriate for general polynomial usage.\n private static final class Term {\n long coefficient;\n long exponent;\n \n public Term(long c, long e) {\n coefficient = c;\n exponent = e;\n }\n \n public Term clone() {\n return new Term(coefficient, exponent);\n }\n \n public Term multiply(Term term) {\n return new Term(coefficient * term.coefficient, exponent + term.exponent);\n }\n \n public Term add(Term term) {\n if ( exponent != term.exponent ) {\n throw new RuntimeException(\"ERROR 102: Exponents not equal.\");\n }\n return new Term(coefficient + term.coefficient, exponent);\n }\n\n public Term negate() {\n return new Term(-coefficient, exponent);\n }\n \n public long degree() {\n return exponent;\n }\n \n @Override\n public String toString() {\n if ( coefficient == 0 ) {\n return \"0\";\n }\n if ( exponent == 0 ) {\n return \"\" + coefficient;\n }\n if ( coefficient == 1 ) {\n if ( exponent == 1 ) {\n return \"x\";\n }\n else {\n return \"x^\" + exponent;\n }\n }\n if ( exponent == 1 ) {\n return coefficient + \"x\";\n }\n return coefficient + \"x^\" + exponent;\n }\n }\n\n}\n"} {"title": "Damm algorithm", "language": "Java from Kotlin", "task": "The '''Damm''' algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. \n\n\nThe algorithm is named after H. Michael Damm.\n\n\n;Task:\nVerify the checksum, stored as last digit of an input.\n\n\n\n", "solution": "public class DammAlgorithm {\n private static final int[][] table = {\n {0, 3, 1, 7, 5, 9, 8, 6, 4, 2},\n {7, 0, 9, 2, 1, 5, 4, 8, 6, 3},\n {4, 2, 0, 6, 8, 7, 1, 3, 5, 9},\n {1, 7, 5, 0, 9, 8, 3, 4, 2, 6},\n {6, 1, 2, 3, 0, 4, 5, 9, 7, 8},\n {3, 6, 7, 4, 2, 0, 9, 5, 8, 1},\n {5, 8, 6, 9, 7, 2, 0, 1, 3, 4},\n {8, 9, 4, 5, 3, 6, 2, 0, 1, 7},\n {9, 4, 3, 8, 6, 1, 7, 2, 0, 5},\n {2, 5, 8, 1, 4, 3, 6, 7, 9, 0},\n };\n\n private static boolean damm(String s) {\n int interim = 0;\n for (char c : s.toCharArray()) interim = table[interim][c - '0'];\n return interim == 0;\n }\n\n public static void main(String[] args) {\n int[] numbers = {5724, 5727, 112946, 112949};\n for (Integer number : numbers) {\n boolean isValid = damm(number.toString());\n if (isValid) {\n System.out.printf(\"%6d is valid\\n\", number);\n } else {\n System.out.printf(\"%6d is invalid\\n\", number);\n }\n }\n }\n}"} {"title": "De Bruijn sequences", "language": "Java from C++", "task": "{{DISPLAYTITLE:de Bruijn sequences}}\nThe sequences are named after the Dutch mathematician Nicolaas Govert de Bruijn.\n\n\nA note on Dutch capitalization: Nicolaas' last name is '''de Bruijn''', the '''de''' isn't normally capitalized\nunless it's the first word in a sentence. Rosetta Code (more or less by default or by fiat) requires the first word in the task name to be\ncapitalized.\n\n\nIn combinatorial mathematics, a '''de Bruijn sequence''' of order ''n'' on\na size-''k'' alphabet (computer science) ''A'' is a cyclic sequence in which every\npossible length-''n'' string (computer science, formal theory) on ''A'' occurs\nexactly once as a contiguous substring.\n\n\nSuch a sequence is denoted by ''B''(''k'', ''n'') and has\nlength ''k''''n'', which is also the number of distinct substrings of\nlength ''n'' on ''A''; \nde Bruijn sequences are therefore optimally short.\n\n\nThere are:\n (k!)k(n-1) / kn\ndistinct de Bruijn sequences ''B''(''k'', ''n''). \n\n\n;Task:\nFor this Rosetta Code task, a '''de Bruijn''' sequence is to be generated that can be used to shorten a brute-force attack on\na PIN-like code lock that does not have an \"enter\"\nkey and accepts the last ''n'' digits entered.\n\n\nNote: automated teller machines (ATMs) used to work like\nthis, but their software has been updated to not allow a brute-force attack.\n\n\n;Example:\nA digital door lock with a 4-digit code would\nhave ''B'' (10, 4) solutions, with a length of '''10,000''' (digits).\n\nTherefore, only at most '''10,000 + 3''' (as the solutions are cyclic or ''wrap-around'') presses are needed to\nopen the lock.\n\nTrying all 4-digit codes separately would require '''4 x 10,000''' or '''40,000''' presses.\n\n\n;Task requirements:\n:* Generate a de Bruijn sequence for a 4-digit (decimal) PIN code.\n:::* Show the length of the generated de Bruijn sequence.\n:::* (There are many possible de Bruijn sequences that solve this task, one solution is shown on the ''discussion'' page).\n:::* Show the first and last '''130''' digits of the de Bruijn sequence.\n:* Verify that all four-digit (decimal) '''1,000''' PIN codes are contained within the de Bruijn sequence.\n:::* 0000, 0001, 0002, 0003, ... 9996, 9997, 9998, 9999 (note the leading zeros).\n:* Reverse the de Bruijn sequence.\n:* Again, perform the (above) verification test.\n:* Replace the 4,444th digit with a period (.) in the original de Bruijn sequence.\n:::* Perform the verification test (again). There should be four PIN codes missing.\n\n\n(The last requirement is to ensure that the verification tests performs correctly. The verification processes should list\nany and all missing PIN codes.)\n\nShow all output here, on this page.\n\n\n\n;References:\n:* Wikipedia entry: de Bruijn sequence.\n:* MathWorld entry: de Bruijn sequence.\n:* An OEIS entry: A166315 lexicographically earliest binary de Bruijn sequences, B(2,n) --- Not B(10,4), but possibly relevant.\n\n", "solution": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.function.BiConsumer;\n\npublic class DeBruijn {\n public interface Recursable {\n void apply(T t, U u, Recursable r);\n }\n\n public static BiConsumer recurse(Recursable f) {\n return (t, u) -> f.apply(t, u, f);\n }\n\n private static String deBruijn(int k, int n) {\n byte[] a = new byte[k * n];\n Arrays.fill(a, (byte) 0);\n\n List seq = new ArrayList<>();\n\n BiConsumer db = recurse((t, p, f) -> {\n if (t > n) {\n if (n % p == 0) {\n for (int i = 1; i < p + 1; ++i) {\n seq.add(a[i]);\n }\n }\n } else {\n a[t] = a[t - p];\n f.apply(t + 1, p, f);\n int j = a[t - p] + 1;\n while (j < k) {\n a[t] = (byte) (j & 0xFF);\n f.apply(t + 1, t, f);\n j++;\n }\n }\n });\n db.accept(1, 1);\n\n StringBuilder sb = new StringBuilder();\n for (Byte i : seq) {\n sb.append(\"0123456789\".charAt(i));\n }\n\n sb.append(sb.subSequence(0, n - 1));\n return sb.toString();\n }\n\n private static boolean allDigits(String s) {\n for (int i = 0; i < s.length(); ++i) {\n char c = s.charAt(i);\n if (!Character.isDigit(c)) {\n return false;\n }\n }\n return true;\n }\n\n private static void validate(String db) {\n int le = db.length();\n int[] found = new int[10_000];\n Arrays.fill(found, 0);\n List errs = new ArrayList<>();\n\n // Check all strings of 4 consecutive digits within 'db'\n // to see if all 10,000 combinations occur without duplication.\n for (int i = 0; i < le - 3; ++i) {\n String s = db.substring(i, i + 4);\n if (allDigits(s)) {\n int n = Integer.parseInt(s);\n found[n]++;\n }\n }\n\n for (int i = 0; i < 10_000; ++i) {\n if (found[i] == 0) {\n errs.add(String.format(\" PIN number %d is missing\", i));\n } else if (found[i] > 1) {\n errs.add(String.format(\" PIN number %d occurs %d times\", i, found[i]));\n }\n }\n\n if (errs.isEmpty()) {\n System.out.println(\" No errors found\");\n } else {\n String pl = (errs.size() == 1) ? \"\" : \"s\";\n System.out.printf(\" %d error%s found:\\n\", errs.size(), pl);\n errs.forEach(System.out::println);\n }\n }\n\n public static void main(String[] args) {\n String db = deBruijn(10, 4);\n\n System.out.printf(\"The length of the de Bruijn sequence is %d\\n\\n\", db.length());\n System.out.printf(\"The first 130 digits of the de Bruijn sequence are: %s\\n\\n\", db.substring(0, 130));\n System.out.printf(\"The last 130 digits of the de Bruijn sequence are: %s\\n\\n\", db.substring(db.length() - 130));\n\n System.out.println(\"Validating the de Bruijn sequence:\");\n validate(db);\n\n StringBuilder sb = new StringBuilder(db);\n String rdb = sb.reverse().toString();\n System.out.println();\n System.out.println(\"Validating the de Bruijn sequence:\");\n validate(rdb);\n\n sb = new StringBuilder(db);\n sb.setCharAt(4443, '.');\n System.out.println();\n System.out.println(\"Validating the overlaid de Bruijn sequence:\");\n validate(sb.toString());\n }\n}"} {"title": "Deepcopy", "language": "Java", "task": "Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. \n\nThis is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects.\n\nIf this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure.\n\n\nThe task should show:\n\n* Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles.\n\n* Any limitations of the method.\n\n* That the structure and its copy are different.\n\n* Suitable links to external documentation for common libraries.\n\n", "solution": "import java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutputStream;\nimport java.io.Serializable;\n\npublic class DeepCopy {\n\n public static void main(String[] args) {\n Person p1 = new Person(\"Clark\", \"Kent\", new Address(\"1 World Center\", \"Metropolis\", \"NY\", \"010101\"));\n Person p2 = p1;\n \n System.out.printf(\"Demonstrate shallow copy. Both are the same object.%n\");\n System.out.printf(\"Person p1 = %s%n\", p1);\n System.out.printf(\"Person p2 = %s%n\", p2);\n System.out.printf(\"Set city on person 2. City on both objects is changed.%n\");\n p2.getAddress().setCity(\"New York\");\n System.out.printf(\"Person p1 = %s%n\", p1);\n System.out.printf(\"Person p2 = %s%n\", p2);\n \n p1 = new Person(\"Clark\", \"Kent\", new Address(\"1 World Center\", \"Metropolis\", \"NY\", \"010101\"));\n p2 = new Person(p1);\n System.out.printf(\"%nDemonstrate copy constructor. Object p2 is a deep copy of p1.%n\");\n System.out.printf(\"Person p1 = %s%n\", p1);\n System.out.printf(\"Person p2 = %s%n\", p2);\n System.out.printf(\"Set city on person 2. City on objects is different.%n\");\n p2.getAddress().setCity(\"New York\");\n System.out.printf(\"Person p1 = %s%n\", p1);\n System.out.printf(\"Person p2 = %s%n\", p2);\n\n p2 = (Person) deepCopy(p1);\n System.out.printf(\"%nDemonstrate serialization. Object p2 is a deep copy of p1.%n\");\n System.out.printf(\"Person p1 = %s%n\", p1);\n System.out.printf(\"Person p2 = %s%n\", p2);\n System.out.printf(\"Set city on person 2. City on objects is different.%n\");\n p2.getAddress().setCity(\"New York\");\n System.out.printf(\"Person p1 = %s%n\", p1);\n System.out.printf(\"Person p2 = %s%n\", p2);\n \n p2 = (Person) p1.clone();\n System.out.printf(\"%nDemonstrate cloning. Object p2 is a deep copy of p1.%n\");\n System.out.printf(\"Person p1 = %s%n\", p1);\n System.out.printf(\"Person p2 = %s%n\", p2);\n System.out.printf(\"Set city on person 2. City on objects is different.%n\");\n p2.getAddress().setCity(\"New York\");\n System.out.printf(\"Person p1 = %s%n\", p1);\n System.out.printf(\"Person p2 = %s%n\", p2);\n }\n\n /**\n * Makes a deep copy of any Java object that is passed.\n */\n private static Object deepCopy(Object object) {\n try {\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream();\n ObjectOutputStream outputStrm = new ObjectOutputStream(outputStream);\n outputStrm.writeObject(object);\n ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());\n ObjectInputStream objInputStream = new ObjectInputStream(inputStream);\n return objInputStream.readObject();\n }\n catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n }\n \n public static class Address implements Serializable, Cloneable {\n\n private static final long serialVersionUID = -7073778041809445593L;\n\n private String street;\n private String city;\n private String state;\n private String postalCode;\n public String getStreet() {\n return street;\n }\n public String getCity() {\n return city;\n }\n public void setCity(String city) {\n this.city = city;\n }\n public String getState() {\n return state;\n }\n public String getPostalCode() {\n return postalCode;\n }\n \n @Override\n public String toString() {\n return \"[street=\" + street + \", city=\" + city + \", state=\" + state + \", code=\" + postalCode + \"]\";\n }\n \n public Address(String s, String c, String st, String p) {\n street = s;\n city = c;\n state = st;\n postalCode = p;\n }\n \n // Copy constructor\n public Address(Address add) {\n street = add.street;\n city = add.city;\n state = add.state;\n postalCode = add.postalCode;\n }\n \n // Support Cloneable\n @Override\n public Object clone() {\n return new Address(this);\n }\n \n }\n \n public static class Person implements Serializable, Cloneable {\n private static final long serialVersionUID = -521810583786595050L;\n private String firstName;\n private String lastName;\n private Address address;\n public String getFirstName() {\n return firstName;\n }\n public String getLastName() {\n return lastName;\n }\n public Address getAddress() {\n return address;\n }\n\n @Override\n public String toString() {\n return \"[first name=\" + firstName + \", last name=\" + lastName + \", address=\" + address + \"]\";\n }\n\n public Person(String fn, String ln, Address add) {\n firstName = fn;\n lastName = ln;\n address = add;\n }\n \n // Copy Constructor\n public Person(Person person) {\n firstName = person.firstName;\n lastName = person.lastName;\n address = new Address(person.address); // Invoke copy constructor of mutable sub-objects.\n }\n \n // Support Cloneable\n @Override\n public Object clone() {\n return new Person(this);\n }\n }\n}\n"} {"title": "Deming's funnel", "language": "Java", "task": "W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of \"rules\" to try to improve performance. In each case the experiment begins with the funnel positioned directly over the target.\n\n* '''Rule 1''': The funnel remains directly above the target.\n* '''Rule 2''': Adjust the funnel position by shifting the target to compensate after each drop. E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position.\n* '''Rule 3''': As rule 2, but first move the funnel back over the target, before making the adjustment. E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target.\n* '''Rule 4''': The funnel is moved directly over the last place a marble landed.\n\nApply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys. '''Output''': calculate the mean and standard-deviations of the resulting x and y values for each rule. \n\nNote that rules 2, 3, and 4 give successively worse results. Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples.\n\n'''Stretch goal 1''': Generate fresh pseudorandom data. The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed.\n\n'''Stretch goal 2''': Show scatter plots of all four results.\n\n\n;Further information:\n* Further explanation and interpretation\n* Video demonstration of the funnel experiment at the Mayo Clinic.\n\n", "solution": "Translation of [[Deming's_Funnel#Python|Python]] via [[Deming's_Funnel#D|D]]\n"} {"title": "Deming's funnel", "language": "Java 8", "task": "W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of \"rules\" to try to improve performance. In each case the experiment begins with the funnel positioned directly over the target.\n\n* '''Rule 1''': The funnel remains directly above the target.\n* '''Rule 2''': Adjust the funnel position by shifting the target to compensate after each drop. E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position.\n* '''Rule 3''': As rule 2, but first move the funnel back over the target, before making the adjustment. E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target.\n* '''Rule 4''': The funnel is moved directly over the last place a marble landed.\n\nApply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys. '''Output''': calculate the mean and standard-deviations of the resulting x and y values for each rule. \n\nNote that rules 2, 3, and 4 give successively worse results. Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples.\n\n'''Stretch goal 1''': Generate fresh pseudorandom data. The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed.\n\n'''Stretch goal 2''': Show scatter plots of all four results.\n\n\n;Further information:\n* Further explanation and interpretation\n* Video demonstration of the funnel experiment at the Mayo Clinic.\n\n", "solution": "import static java.lang.Math.*;\nimport java.util.Arrays;\nimport java.util.function.BiFunction;\n\npublic class DemingsFunnel {\n\n public static void main(String[] args) {\n double[] dxs = {\n -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,\n 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,\n -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,\n 0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,\n -0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,\n -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,\n 0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,\n -0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,\n 0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,\n -1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,\n 0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,\n 0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,\n 0.443, -0.521, -0.799, 0.087};\n\n double[] dys = {\n 0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,\n 0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,\n 0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,\n 0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,\n -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,\n 0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,\n 0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,\n 1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,\n -0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,\n 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,\n -0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,\n 1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,\n -0.947, -1.424, -0.542, -1.032};\n\n experiment(\"Rule 1:\", dxs, dys, (z, dz) -> 0.0);\n experiment(\"Rule 2:\", dxs, dys, (z, dz) -> -dz);\n experiment(\"Rule 3:\", dxs, dys, (z, dz) -> -(z + dz));\n experiment(\"Rule 4:\", dxs, dys, (z, dz) -> z + dz);\n }\n\n static void experiment(String label, double[] dxs, double[] dys,\n BiFunction rule) {\n\n double[] resx = funnel(dxs, rule);\n double[] resy = funnel(dys, rule);\n System.out.println(label);\n System.out.printf(\"Mean x, y: %.4f, %.4f%n\", mean(resx), mean(resy));\n System.out.printf(\"Std dev x, y: %.4f, %.4f%n\", stdDev(resx), stdDev(resy));\n System.out.println();\n }\n\n static double[] funnel(double[] input, BiFunction rule) {\n double x = 0;\n double[] result = new double[input.length];\n\n for (int i = 0; i < input.length; i++) {\n double rx = x + input[i];\n x = rule.apply(x, input[i]);\n result[i] = rx;\n }\n return result;\n }\n\n static double mean(double[] xs) {\n return Arrays.stream(xs).sum() / xs.length;\n }\n\n static double stdDev(double[] xs) {\n double m = mean(xs);\n return sqrt(Arrays.stream(xs).map(x -> pow((x - m), 2)).sum() / xs.length);\n }\n}"} {"title": "Department numbers", "language": "Java from Kotlin", "task": "There is a highly organized city that has decided to assign a number to each of their departments:\n::* police department\n::* sanitation department\n::* fire department \n\n\nEach department can have a number between '''1''' and '''7''' (inclusive).\n\nThe three department numbers are to be unique (different from each other) and must add up to '''12'''.\n\nThe Chief of the Police doesn't like odd numbers and wants to have an even number for his department.\n\n\n;Task:\nWrite a computer program which outputs all valid combinations.\n\n\nPossible output (for the 1st and 14th solutions):\n \n --police-- --sanitation-- --fire-- \n 2 3 7 \n 6 5 1\n\n", "solution": "public class DepartmentNumbers {\n public static void main(String[] args) {\n System.out.println(\"Police Sanitation Fire\");\n System.out.println(\"------ ---------- ----\");\n int count = 0;\n for (int i = 2; i <= 6; i += 2) {\n for (int j = 1; j <= 7; ++j) {\n if (j == i) continue;\n for (int k = 1; k <= 7; ++k) {\n if (k == i || k == j) continue;\n if (i + j + k != 12) continue;\n System.out.printf(\" %d %d %d\\n\", i, j, k);\n count++;\n }\n }\n }\n System.out.printf(\"\\n%d valid combinations\", count);\n }\n}"} {"title": "Detect division by zero", "language": "Java", "task": "Write a function to detect a ''divide by zero error'' without checking if the denominator is zero.\n\n", "solution": "public static boolean except(double numer, double denom){\n\ttry{\n\t\tint dummy = (int)numer / (int)denom;//ArithmeticException is only thrown from integer math\n\t\treturn false;\n\t}catch(ArithmeticException e){return true;}\n}"} {"title": "Determinant and permanent", "language": "Java", "task": "permanent of the matrix.\n\nThe determinant is given by\n:: \\det(A) = \\sum_\\sigma\\sgn(\\sigma)\\prod_{i=1}^n M_{i,\\sigma_i}\nwhile the permanent is given by\n:: \\operatorname{perm}(A)=\\sum_\\sigma\\prod_{i=1}^n M_{i,\\sigma_i}\nIn both cases the sum is over the permutations \\sigma of the permutations of 1, 2, ..., ''n''. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.)\n\nMore efficient algorithms for the determinant are known: [[LU decomposition]], see for example [[wp:LU decomposition#Computing the determinant]]. Efficient methods for calculating the permanent are not known.\n\n\n;Related task:\n* [[Permutations by swapping]]\n\n", "solution": "import java.util.Scanner;\n\npublic class MatrixArithmetic {\n\tpublic static double[][] minor(double[][] a, int x, int y){\n\t\tint length = a.length-1;\n\t\tdouble[][] result = new double[length][length];\n\t\tfor(int i=0;i=x && j=y){\n\t\t\t\tresult[i][j] = a[i][j+1];\n\t\t\t}else{ //i>x && j>y\n\t\t\t\tresult[i][j] = a[i+1][j+1];\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tpublic static double det(double[][] a){\n\t\tif(a.length == 1){\n\t\t\treturn a[0][0];\n\t\t}else{\n\t\t\tint sign = 1;\n\t\t\tdouble sum = 0;\n\t\t\tfor(int i=0;i charMap = new HashMap<>(); \n char dup = 0;\n int index = 0;\n int pos1 = -1;\n int pos2 = -1;\n for ( char key : input.toCharArray() ) {\n index++;\n if ( charMap.containsKey(key) ) {\n dup = key;\n pos1 = charMap.get(key);\n pos2 = index;\n break;\n }\n charMap.put(key, index);\n }\n String unique = dup == 0 ? \"yes\" : \"no\";\n String diff = dup == 0 ? \"\" : \"'\" + dup + \"'\";\n String hex = dup == 0 ? \"\" : Integer.toHexString(dup).toUpperCase();\n String position = dup == 0 ? \"\" : pos1 + \" \" + pos2;\n System.out.printf(\"%-40s %-6d %-10s %-8s %-3s %-5s%n\", input, input.length(), unique, diff, hex, position);\n }\n\n}\n"} {"title": "Determine if a string is collapsible", "language": "Java", "task": "Determine if a character string is ''collapsible''.\n\nAnd if so, collapse the string (by removing ''immediately repeated'' characters).\n\n\n\nIf a character string has ''immediately repeated'' character(s), the repeated characters are to be\ndeleted (removed), but not the primary (1st) character(s).\n\n\nAn ''immediately repeated'' character is any character that is immediately followed by an\nidentical character (or characters). Another word choice could've been ''duplicated character'', but that\nmight have ruled out (to some readers) triplicated characters *** or more.\n\n\n{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) '''PL/I''' BIF: '''collapse'''.}\n\n\n;Examples:\nIn the following character string:\n\n\n The better the 4-wheel drive, the further you'll be from help when ya get stuck! \n\n\nOnly the 2nd '''t''', '''e''', and '''l''' are repeated characters, indicated\nby underscores (above), even though they (those characters) appear elsewhere in the character string.\n\n\n\nSo, after ''collapsing'' the string, the result would be:\n\n The beter the 4-whel drive, the further you'l be from help when ya get stuck! \n\n\n\n\nAnother example:\nIn the following character string:\n\n headmistressship \n\n\nThe \"collapsed\" string would be:\n\n headmistreship \n\n\n\n;Task:\nWrite a subroutine/function/procedure/routine*** to\nlocate ''repeated'' characters and ''collapse'' (delete) them from the character\nstring. The character string can be processed from either direction.\n\n\nShow all output here, on this page:\n:* the original string and its length\n:* the resultant string and its length\n:* the above strings should be \"bracketed\" with '''<<<''' and '''>>>''' (to delineate blanks)\n;* <<<<<>>>>>\n\n\n\n\nUse (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except\nthe 1st string:\n\n string\n number\n ++\n 1 |+-----------------------------------------------------------------------+ <###### a null string (length zero)\n 2 |\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln |\n 3 |..1111111111111111111111111111111111111111111111111111111111111117777888|\n 4 |I never give 'em hell, I just tell the truth, and they think it's hell. |\n 5 | --- Harry S Truman | <###### has many repeated blanks\n +------------------------------------------------------------------------+\n\n\n", "solution": "// Title: Determine if a string is collapsible\n\npublic class StringCollapsible {\n\n public static void main(String[] args) {\n for ( String s : new String[] {\n \"\", \n \"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \", \n \"..1111111111111111111111111111111111111111111111111111111111111117777888\", \n \"I never give 'em hell, I just tell the truth, and they think it's hell. \", \n \" --- Harry S Truman \",\n \"122333444455555666666777777788888888999999999\",\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n \"headmistressship\"}) {\n String result = collapse(s);\n System.out.printf(\"old: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n\", s.length(), s, result.length(), result);\n }\n }\n \n private static String collapse(String in) {\n StringBuilder sb = new StringBuilder();\n for ( int i = 0 ; i < in.length() ; i++ ) {\n if ( i == 0 || in.charAt(i-1) != in.charAt(i) ) {\n sb.append(in.charAt(i));\n }\n }\n return sb.toString();\n }\n\n}\n"} {"title": "Determine if a string is squeezable", "language": "Java", "task": "Determine if a character string is ''squeezable''.\n\nAnd if so, squeeze the string (by removing any number of\na ''specified'' ''immediately repeated'' character).\n\n\nThis task is very similar to the task '''Determine if a character string is collapsible''' except\nthat only a specified character is ''squeezed'' instead of any character that is ''immediately repeated''.\n\n\nIf a character string has a specified ''immediately repeated'' character(s), the repeated characters are to be\ndeleted (removed), but not the primary (1st) character(s).\n\n\nA specified ''immediately repeated'' character is any specified character that is immediately \nfollowed by an identical character (or characters). Another word choice could've been ''duplicated\ncharacter'', but that might have ruled out (to some readers) triplicated characters *** or more.\n\n\n{This Rosetta Code task was inspired by a newly introduced (as of around\nNovember 2019) '''PL/I''' BIF: '''squeeze'''.}\n\n\n;Examples:\nIn the following character string with a specified ''immediately repeated'' character of '''e''':\n\n\n The better the 4-wheel drive, the further you'll be from help when ya get stuck! \n\n\nOnly the 2nd '''e''' is an specified repeated character, indicated by an underscore\n(above), even though they (the characters) appear elsewhere in the character string.\n\n\n\nSo, after ''squeezing'' the string, the result would be:\n\n The better the 4-whel drive, the further you'll be from help when ya get stuck! \n\n\n\n\nAnother example:\nIn the following character string, using a specified immediately repeated character '''s''':\n\n headmistressship \n\n\nThe \"squeezed\" string would be:\n\n headmistreship \n\n\n\n;Task:\nWrite a subroutine/function/procedure/routine*** to locate a ''specified immediately repeated'' character\nand ''squeeze'' (delete) them from the character string. The\ncharacter string can be processed from either direction.\n\n\nShow all output here, on this page:\n:* the specified repeated character (to be searched for and possibly ''squeezed''):\n:* the original string and its length\n:* the resultant string and its length\n:* the above strings should be \"bracketed\" with '''<<<''' and '''>>>''' (to delineate blanks)\n;* <<<<<>>>>>\n\n\n\nUse (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except\nthe 1st string:\n\n immediately\n string repeated\n number character\n ( | a blank, a minus, a seven, a period)\n ++\n 1 |+-----------------------------------------------------------------------+ ' ' <###### a null string (length zero)\n 2 |\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln | '-'\n 3 |..1111111111111111111111111111111111111111111111111111111111111117777888| '7'\n 4 |I never give 'em hell, I just tell the truth, and they think it's hell. | '.'\n 5 | --- Harry S Truman | (below) <###### has many repeated blanks\n +------------------------------------------------------------------------+ |\n |\n |\n For the 5th string (Truman's signature line), use each of these specified immediately repeated characters:\n * a blank\n * a minus\n * a lowercase '''r'''\n\n\nNote: there should be seven results shown, one each for the 1st four strings, and three results for\nthe 5th string.\n\n\n", "solution": "// Title: Determine if a string is squeezable\n\npublic class StringSqueezable {\n\n public static void main(String[] args) {\n String[] testStrings = new String[] {\n \"\", \n \"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \", \n \"..1111111111111111111111111111111111111111111111111111111111111117777888\", \n \"I never give 'em hell, I just tell the truth, and they think it's hell. \", \n \" --- Harry S Truman \",\n \"122333444455555666666777777788888888999999999\",\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n \"headmistressship\"};\n\n String[] testChar = new String[] {\n \" \", \n \"-\", \n \"7\", \n \".\", \n \" -r\",\n \"5\",\n \"e\",\n \"s\"};\n for ( int testNum = 0 ; testNum < testStrings.length ; testNum++ ) {\n String s = testStrings[testNum];\n for ( char c : testChar[testNum].toCharArray() ) {\n String result = squeeze(s, c);\n System.out.printf(\"use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n\", c, s.length(), s, result.length(), result);\n }\n }\n }\n \n private static String squeeze(String in, char include) {\n StringBuilder sb = new StringBuilder();\n for ( int i = 0 ; i < in.length() ; i++ ) {\n if ( i == 0 || in.charAt(i-1) != in.charAt(i) || (in.charAt(i-1) == in.charAt(i) && in.charAt(i) != include)) {\n sb.append(in.charAt(i));\n }\n }\n return sb.toString();\n }\n\n}\n"} {"title": "Determine if two triangles overlap", "language": "Java 8", "task": "Determining if two triangles in the same plane overlap is an important topic in collision detection.\n\n\n;Task:\nDetermine which of these pairs of triangles overlap in 2D:\n\n:::* (0,0),(5,0),(0,5) and (0,0),(5,0),(0,6)\n:::* (0,0),(0,5),(5,0) and (0,0),(0,5),(5,0)\n:::* (0,0),(5,0),(0,5) and (-10,0),(-5,0),(-1,6)\n:::* (0,0),(5,0),(2.5,5) and (0,4),(2.5,-1),(5,4)\n:::* (0,0),(1,1),(0,2) and (2,1),(3,0),(3,2)\n:::* (0,0),(1,1),(0,2) and (2,1),(3,-2),(3,4)\n\n\nOptionally, see what the result is when only a single corner is in contact (there is no definitive correct answer):\n:::* (0,0),(1,0),(0,1) and (1,0),(2,0),(1,1)\n\n", "solution": "import java.util.function.BiFunction;\n\npublic class TriangleOverlap {\n private static class Pair {\n double first;\n double second;\n\n Pair(double first, double second) {\n this.first = first;\n this.second = second;\n }\n\n @Override\n public String toString() {\n return String.format(\"(%s, %s)\", first, second);\n }\n }\n\n private static class Triangle {\n Pair p1, p2, p3;\n\n Triangle(Pair p1, Pair p2, Pair p3) {\n this.p1 = p1;\n this.p2 = p2;\n this.p3 = p3;\n }\n\n @Override\n public String toString() {\n return String.format(\"Triangle: %s, %s, %s\", p1, p2, p3);\n }\n }\n\n private static double det2D(Triangle t) {\n Pair p1 = t.p1;\n Pair p2 = t.p2;\n Pair p3 = t.p3;\n return p1.first * (p2.second - p3.second)\n + p2.first * (p3.second - p1.second)\n + p3.first * (p1.second - p2.second);\n }\n\n private static void checkTriWinding(Triangle t, boolean allowReversed) {\n double detTri = det2D(t);\n if (detTri < 0.0) {\n if (allowReversed) {\n Pair a = t.p3;\n t.p3 = t.p2;\n t.p2 = a;\n } else throw new RuntimeException(\"Triangle has wrong winding direction\");\n }\n }\n\n private static boolean boundaryCollideChk(Triangle t, double eps) {\n return det2D(t) < eps;\n }\n\n private static boolean boundaryDoesntCollideChk(Triangle t, double eps) {\n return det2D(t) <= eps;\n }\n\n private static boolean triTri2D(Triangle t1, Triangle t2) {\n return triTri2D(t1, t2, 0.0, false, true);\n }\n\n private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed) {\n return triTri2D(t1, t2, eps, allowedReversed, true);\n }\n\n private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed, boolean onBoundary) {\n // Triangles must be expressed anti-clockwise\n checkTriWinding(t1, allowedReversed);\n checkTriWinding(t2, allowedReversed);\n // 'onBoundary' determines whether points on boundary are considered as colliding or not\n BiFunction chkEdge = onBoundary ? TriangleOverlap::boundaryCollideChk : TriangleOverlap::boundaryDoesntCollideChk;\n Pair[] lp1 = new Pair[]{t1.p1, t1.p2, t1.p3};\n Pair[] lp2 = new Pair[]{t2.p1, t2.p2, t2.p3};\n\n // for each edge E of t1\n for (int i = 0; i < 3; ++i) {\n int j = (i + 1) % 3;\n // Check all points of t2 lay on the external side of edge E.\n // If they do, the triangles do not overlap.\n if (chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[0]), eps) &&\n chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[1]), eps) &&\n chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[2]), eps)) return false;\n }\n\n // for each edge E of t2\n for (int i = 0; i < 3; ++i) {\n int j = (i + 1) % 3;\n // Check all points of t1 lay on the external side of edge E.\n // If they do, the triangles do not overlap.\n if (chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[0]), eps) &&\n chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[1]), eps) &&\n chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[2]), eps)) return false;\n }\n\n // The triangles overlap\n return true;\n }\n\n public static void main(String[] args) {\n Triangle t1 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 5.0));\n Triangle t2 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 6.0));\n System.out.printf(\"%s and\\n%s\\n\", t1, t2);\n if (triTri2D(t1, t2)) {\n System.out.println(\"overlap\");\n } else {\n System.out.println(\"do not overlap\");\n }\n\n // need to allow reversed for this pair to avoid exception\n t1 = new Triangle(new Pair(0.0, 0.0), new Pair(0.0, 5.0), new Pair(5.0, 0.0));\n t2 = t1;\n System.out.printf(\"\\n%s and\\n%s\\n\", t1, t2);\n if (triTri2D(t1, t2, 0.0, true)) {\n System.out.println(\"overlap (reversed)\");\n } else {\n System.out.println(\"do not overlap\");\n }\n\n t1 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 5.0));\n t2 = new Triangle(new Pair(-10.0, 0.0), new Pair(-5.0, 0.0), new Pair(-1.0, 6.0));\n System.out.printf(\"\\n%s and\\n%s\\n\", t1, t2);\n if (triTri2D(t1, t2)) {\n System.out.println(\"overlap\");\n } else {\n System.out.println(\"do not overlap\");\n }\n\n t1.p3 = new Pair(2.5, 5.0);\n t2 = new Triangle(new Pair(0.0, 4.0), new Pair(2.5, -1.0), new Pair(5.0, 4.0));\n System.out.printf(\"\\n%s and\\n%s\\n\", t1, t2);\n if (triTri2D(t1, t2)) {\n System.out.println(\"overlap\");\n } else {\n System.out.println(\"do not overlap\");\n }\n\n t1 = new Triangle(new Pair(0.0, 0.0), new Pair(1.0, 1.0), new Pair(0.0, 2.0));\n t2 = new Triangle(new Pair(2.0, 1.0), new Pair(3.0, 0.0), new Pair(3.0, 2.0));\n System.out.printf(\"\\n%s and\\n%s\\n\", t1, t2);\n if (triTri2D(t1, t2)) {\n System.out.println(\"overlap\");\n } else {\n System.out.println(\"do not overlap\");\n }\n\n t2 = new Triangle(new Pair(2.0, 1.0), new Pair(3.0, -2.0), new Pair(3.0, 4.0));\n System.out.printf(\"\\n%s and\\n%s\\n\", t1, t2);\n if (triTri2D(t1, t2)) {\n System.out.println(\"overlap\");\n } else {\n System.out.println(\"do not overlap\");\n }\n\n t1 = new Triangle(new Pair(0.0, 0.0), new Pair(1.0, 0.0), new Pair(0.0, 1.0));\n t2 = new Triangle(new Pair(1.0, 0.0), new Pair(2.0, 0.0), new Pair(1.0, 1.1));\n System.out.printf(\"\\n%s and\\n%s\\n\", t1, t2);\n System.out.println(\"which have only a single corner in contact, if boundary points collide\");\n if (triTri2D(t1, t2)) {\n System.out.println(\"overlap\");\n } else {\n System.out.println(\"do not overlap\");\n }\n\n System.out.printf(\"\\n%s and\\n%s\\n\", t1, t2);\n System.out.println(\"which have only a single corner in contact, if boundary points do not collide\");\n if (triTri2D(t1, t2, 0.0, false, false)) {\n System.out.println(\"overlap\");\n } else {\n System.out.println(\"do not overlap\");\n }\n }\n}"} {"title": "Dice game probabilities", "language": "Java", "task": "Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.\n\nThey roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player?\n\nLater the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player?\n\nThis task was adapted from the Project Euler Problem n.205:\nhttps://projecteuler.net/problem=205\n\n", "solution": "import java.util.Random;\n\npublic class Dice{\n\tprivate static int roll(int nDice, int nSides){\n\t\tint sum = 0;\n\t\tRandom rand = new Random();\n\t\tfor(int i = 0; i < nDice; i++){\n\t\t\tsum += rand.nextInt(nSides) + 1;\n\t\t}\n\t\treturn sum;\n\t}\n\t\n\tprivate static int diceGame(int p1Dice, int p1Sides, int p2Dice, int p2Sides, int rolls){\n\t\tint p1Wins = 0;\n\t\tfor(int i = 0; i < rolls; i++){\n\t\t\tint p1Roll = roll(p1Dice, p1Sides);\n\t\t\tint p2Roll = roll(p2Dice, p2Sides);\n\t\t\tif(p1Roll > p2Roll) p1Wins++;\n\t\t}\n\t\treturn p1Wins;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tint p1Dice = 9; int p1Sides = 4;\n\t\tint p2Dice = 6; int p2Sides = 6;\n\t\tint rolls = 10000;\n\t\tint p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t\t\n\t\tSystem.out.println();\n\t\t\n\t\tp1Dice = 5; p1Sides = 10;\n\t\tp2Dice = 6; p2Sides = 7;\n\t\trolls = 10000;\n\t\tp1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t\t\n\t\tSystem.out.println();\n\t\t\n\t\tp1Dice = 9; p1Sides = 4;\n\t\tp2Dice = 6; p2Sides = 6;\n\t\trolls = 1000000;\n\t\tp1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t\t\n\t\tSystem.out.println();\n\t\t\n\t\tp1Dice = 5; p1Sides = 10;\n\t\tp2Dice = 6; p2Sides = 7;\n\t\trolls = 1000000;\n\t\tp1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);\n\t\tSystem.out.println(rolls + \" rolls, p1 = \" + p1Dice + \"d\" + p1Sides + \", p2 = \" + p2Dice + \"d\" + p2Sides);\n\t\tSystem.out.println(\"p1 wins \" + (100.0 * p1Wins / rolls) + \"% of the time\");\n\t}\n}"} {"title": "Digital root", "language": "Java", "task": "The digital root, X, of a number, n, is calculated:\n: find X as the sum of the digits of n\n: find a new X by summing the digits of X, repeating until X has only one digit.\n\nThe additive persistence is the number of summations required to obtain the single digit. \n\nThe task is to calculate the additive persistence and the digital root of a number, e.g.:\n:627615 has additive persistence 2 and digital root of 9;\n:39390 has additive persistence 2 and digital root of 6;\n:588225 has additive persistence 2 and digital root of 3;\n:393900588225 has additive persistence 2 and digital root of 9;\n\nThe digital root may be calculated in bases other than 10.\n\n\n;See:\n* [[Casting out nines]] for this wiki's use of this procedure.\n* [[Digital root/Multiplicative digital root]]\n* [[Sum digits of an integer]]\n* Digital root sequence on OEIS\n* Additive persistence sequence on OEIS\n* [[Iterated digits squaring]]\n\n", "solution": "import java.math.BigInteger;\n\nclass DigitalRoot\n{\n public static int[] calcDigitalRoot(String number, int base)\n {\n BigInteger bi = new BigInteger(number, base);\n int additivePersistence = 0;\n if (bi.signum() < 0)\n bi = bi.negate();\n BigInteger biBase = BigInteger.valueOf(base);\n while (bi.compareTo(biBase) >= 0)\n {\n number = bi.toString(base);\n bi = BigInteger.ZERO;\n for (int i = 0; i < number.length(); i++)\n bi = bi.add(new BigInteger(number.substring(i, i + 1), base));\n additivePersistence++;\n }\n return new int[] { additivePersistence, bi.intValue() };\n }\n\n public static void main(String[] args)\n {\n for (String arg : args)\n {\n int[] results = calcDigitalRoot(arg, 10);\n System.out.println(arg + \" has additive persistence \" + results[0] + \" and digital root of \" + results[1]);\n }\n }\n}"} {"title": "Disarium numbers", "language": "Java", "task": "A '''Disarium number''' is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.\n\n\n;E.G.\n\n'''135''' is a '''Disarium number''':\n\n 11 + 32 + 53 == 1 + 9 + 125 == 135\n\nThere are a finite number of '''Disarium numbers'''.\n\n\n;Task\n\n* Find and display the first 18 '''Disarium numbers'''.\n\n\n;Stretch\n\n* Find and display all 20 '''Disarium numbers'''.\n\n\n;See also\n\n;* Geeks for Geeks - Disarium numbers\n;* OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...)\n;* Related task: Narcissistic decimal number\n;* Related task: Own digits power sum ''Which seems to be the same task as Narcissistic decimal number...''\n\n", "solution": "import java.lang.Math;\n\npublic class DisariumNumbers {\n public static boolean is_disarium(int num) {\n int n = num;\n int len = Integer.toString(n).length();\n int sum = 0;\n int i = 1;\n while (n > 0) {\n sum += Math.pow(n % 10, len - i + 1);\n n /= 10;\n i ++;\n }\n return sum == num;\n }\n\n public static void main(String[] args) {\n int i = 0;\n int count = 0;\n while (count <= 18) {\n if (is_disarium(i)) {\n System.out.printf(\"%d \", i);\n count++;\n }\n i++;\n }\n System.out.printf(\"%s\", \"\\n\");\n }\n}\n"} {"title": "Display a linear combination", "language": "Java from Kotlin", "task": "Display a finite linear combination in an infinite vector basis (e_1, e_2,\\ldots).\n\nWrite a function that, when given a finite list of scalars (\\alpha^1,\\alpha^2,\\ldots), creates a string representing the linear combination \\sum_i\\alpha^i e_i in an explicit format often used in mathematics, that is:\n\n:\\alpha^{i_1}e_{i_1}\\pm|\\alpha^{i_2}|e_{i_2}\\pm|\\alpha^{i_3}|e_{i_3}\\pm\\ldots\n\nwhere \\alpha^{i_k}\\neq 0\n\nThe output must comply to the following rules:\n* don't show null terms, unless the whole combination is null. \n::::::: '''e(1)''' is fine, '''e(1) + 0*e(3)''' or '''e(1) + 0''' is wrong.\n* don't show scalars when they are equal to one or minus one. \n::::::: '''e(3)''' is fine, '''1*e(3)''' is wrong.\n* don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction. \n::::::: '''e(4) - e(5)''' is fine, '''e(4) + -e(5)''' is wrong.\n\n\nShow here output for the following lists of scalars:\n\n 1) 1, 2, 3\n 2) 0, 1, 2, 3\n 3) 1, 0, 3, 4\n 4) 1, 2, 0\n 5) 0, 0, 0\n 6) 0\n 7) 1, 1, 1\n 8) -1, -1, -1\n 9) -1, -2, 0, -3\n10) -1\n\n\n", "solution": "import java.util.Arrays;\n\npublic class LinearCombination {\n private static String linearCombo(int[] c) {\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < c.length; ++i) {\n if (c[i] == 0) continue;\n String op;\n if (c[i] < 0 && sb.length() == 0) {\n op = \"-\";\n } else if (c[i] < 0) {\n op = \" - \";\n } else if (c[i] > 0 && sb.length() == 0) {\n op = \"\";\n } else {\n op = \" + \";\n }\n int av = Math.abs(c[i]);\n String coeff = av == 1 ? \"\" : \"\" + av + \"*\";\n sb.append(op).append(coeff).append(\"e(\").append(i + 1).append(')');\n }\n if (sb.length() == 0) {\n return \"0\";\n }\n return sb.toString();\n }\n\n public static void main(String[] args) {\n int[][] combos = new int[][]{\n new int[]{1, 2, 3},\n new int[]{0, 1, 2, 3},\n new int[]{1, 0, 3, 4},\n new int[]{1, 2, 0},\n new int[]{0, 0, 0},\n new int[]{0},\n new int[]{1, 1, 1},\n new int[]{-1, -1, -1},\n new int[]{-1, -2, 0, -3},\n new int[]{-1},\n };\n for (int[] c : combos) {\n System.out.printf(\"%-15s -> %s\\n\", Arrays.toString(c), linearCombo(c));\n }\n }\n}"} {"title": "Distance and Bearing", "language": "Java", "task": "It is very important in aviation to have knowledge of the nearby airports at any time in flight. \n;Task:\nDetermine the distance and bearing from an Airplane to the 20 nearest Airports whenever requested.\nUse the non-commercial data from openflights.org airports.dat as reference.\n\n\nA request comes from an airplane at position ( latitude, longitude ): ( '''51.514669, 2.198581''' ).\n\n\nYour report should contain the following information from table airports.dat (column shown in brackets):\n\nName(2), Country(4), ICAO(6), Distance and Bearing calculated from Latitude(7) and Longitude(8). \n\n\nDistance is measured in nautical miles (NM). Resolution is 0.1 NM.\n\nBearing is measured in degrees (deg). 0deg = 360deg = north then clockwise 90deg = east, 180deg = south, 270deg = west. Resolution is 1deg.\n \n\n;See:\n:* openflights.org/data: Airport, airline and route data\n:* Movable Type Scripts: Calculate distance, bearing and more between Latitude/Longitude points\n\n", "solution": "// The Airport class holds each airport object\npackage distanceAndBearing;\npublic class Airport {\n\tprivate String airport;\n\tprivate String country;\n\tprivate String icao;\n\tprivate double lat;\n\tprivate double lon;\n\tpublic String getAirportName() {\treturn this.airport;\t}\n\tpublic void setAirportName(String airport) {\tthis.airport = airport; }\n\tpublic String getCountry() {\treturn this.country;\t}\n\tpublic void setCountry(String country) {\tthis.country = country;\t}\n\tpublic String getIcao() { return this.icao; }\n\tpublic void setIcao(String icao) { this.icao = icao;\t}\n\tpublic double getLat() {\treturn this.lat; }\n\tpublic void setLat(double lat) {\tthis.lat = lat;\t}\n\tpublic double getLon() {\treturn this.lon; }\n\tpublic void setLon(double lon) {\tthis.lon = lon;\t}\n\t@Override\n\tpublic String toString() {return \"Airport: \" + getAirportName() + \": ICAO: \" + getIcao();}\n}\n\n// The DistanceAndBearing class does all the work.\npackage distanceAndBearing;\nimport java.io.File;\nimport java.text.DecimalFormat;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Scanner;\nimport java.util.stream.Collectors;\npublic class DistanceAndBearing {\n\tprivate final double earthRadius = 6371;\n\tprivate File datFile;\n\tprivate List airports;\n\tpublic DistanceAndBearing() { this.airports = new ArrayList(); }\n\tpublic boolean readFile(String filename) {\n\t\tthis.datFile = new File(filename);\n\t\ttry {\n\t\t\tScanner fileScanner = new Scanner(datFile);\n\t\t\tString line;\n\t\t\twhile (fileScanner.hasNextLine()) {\n\t\t\t\tline = fileScanner.nextLine();\n\t\t\t\tline = line.replace(\", \", \"; \"); // There are some commas in airport names in the dat\n\t\t\t\t\t\t\t\t\t\t\t\t\t// file\n\t\t\t\tline = line.replace(\",\\\",\\\"\", \"\\\",\\\"\"); // There are some airport names that\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// end in a comma in the dat file\n\t\t\t\tString[] parts = line.split(\",\");\n\t\t\t\tAirport airport = new Airport();\n\t\t\t\tairport.setAirportName(parts[1].replace(\"\\\"\", \"\")); // Remove the double quotes from the string\n\t\t\t\tairport.setCountry(parts[3].replace(\"\\\"\", \"\")); // Remove the double quotes from the string\n\t\t\t\tairport.setIcao(parts[5].replace(\"\\\"\", \"\")); // Remove the double quotes from the string\n\t\t\t\tairport.setLat(Double.valueOf(parts[6]));\n\t\t\t\tairport.setLon(Double.valueOf(parts[7]));\n\t\t\t\tthis.airports.add(airport);\n\t\t\t}\n\t\t\tfileScanner.close();\n\t\t\treturn true; // Return true if the read was successful\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\treturn false; // Return false if the read was not successful\n\t\t}}\n\tpublic double[] calculate(double lat1, double lon1, double lat2, double lon2) {\n\t\tdouble[] results = new double[2];\n\t\tdouble dLat = Math.toRadians(lat2 - lat1);\n\t\tdouble dLon = Math.toRadians(lon2 - lon1);\n\t\tdouble rlat1 = Math.toRadians(lat1);\n\t\tdouble rlat2 = Math.toRadians(lat2);\n\t\tdouble a = Math.pow(Math.sin(dLat / 2), 2)\n\t\t\t\t+ Math.pow(Math.sin(dLon / 2), 2) * Math.cos(rlat1) * Math.cos(rlat2);\n\t\tdouble c = 2 * Math.asin(Math.sqrt(a));\n\t\tdouble distance = earthRadius * c;\n\t\tDecimalFormat df = new DecimalFormat(\"#0.00\");\n\t\tdistance = Double.valueOf(df.format(distance));\n\t\tresults[0] = distance;\n\t\tdouble X = Math.cos(rlat2) * Math.sin(dLon);\n\t\tdouble Y = Math.cos(rlat1) * Math.sin(rlat2) - Math.sin(rlat1) * Math.cos(rlat2) * Math.cos(dLon);\n\t\tdouble heading = Math.atan2(X, Y);\n\t\theading = Math.toDegrees(heading);\n\t\tresults[1] = heading;\n\t\treturn results;\n\t}\n\tpublic Airport searchByName(final String name) {\n\t\tAirport airport = new Airport();\n\t\tList results = this.airports.stream().filter(ap -> ap.getAirportName().contains(name))\n\t\t\t\t.collect(Collectors.toList());\n\t\tairport = results.get(0);\n\t\treturn airport;\n\t}\n\tpublic List findClosestAirports(double lat, double lon) {\n\t\t// TODO Auto-generated method stub\n\t\tMap airportDistances = new HashMap<>();\n\t\tMap airportHeading = new HashMap<>();\n\t\tList closestAirports = new ArrayList();\n\t\t// This loop finds the distance and heading for every airport and saves them\n\t\t// into two separate Maps\n\t\tfor (Airport ap : this.airports) {\n\t\t\tdouble[] result = calculate(lat, lon, ap.getLat(), ap.getLon());\n\t\t\tairportDistances.put(result[0], ap);\n\t\t\tairportHeading.put(result[1], ap);\n\t\t}\n\t\t// Get the keyset from the distance map and sort it.\n\t\tArrayList distances = new ArrayList<>(airportDistances.keySet());\n\t\tCollections.sort(distances);\n\t\t// Get the first 20 airports by finding the value in the distance map for\n\t\t// each distance in the sorted Arraylist. Then get the airport name, and\n\t\t// use that to search for the airport in the airports List.\n\t\t// Save that into a new List\n\t\tfor (int i = 0; i < 20; i++) { closestAirports.add(searchByName((airportDistances.get(distances.get(i)).getAirportName())));}\n\t\t// Find the distance and heading for each of the top 20 airports.\n\t\tMap distanceMap = new HashMap<>();\n\t\tfor (Double d : airportDistances.keySet()) {\tdistanceMap.put(airportDistances.get(d).getAirportName(), d);}\n\t\tMap headingMap = new HashMap<>();\n\t\tfor (Double d : airportHeading.keySet()) { \n double d2 = d;\n if(d2<0){d2+=360'}\n headingMap.put(airportHeading.get(d).getAirportName(), d2); }\n\n\t\t// Print the results.\n\t\tSystem.out.printf(\"%-4s %-40s %-25s %-6s %12s %15s\\n\", \"Num\", \"Airport\", \"Country\", \"ICAO\", \"Distance\", \"Bearing\");\n\t\tSystem.out.println(\"-----------------------------------------------------------------------------------------------------------\");\n\t\tint i = 0;\n\t\tfor (Airport a : closestAirports) {\n\t\t\tSystem.out.printf(\"%-4s %-40s %-25s %-6s %12.1f %15.0f\\n\", ++i, a.getAirportName(), a.getCountry(), a.getIcao(), distanceMap.get(a.getAirportName())*0.5399568, headingMap.get(a.getAirportName()));\n\t\t}\n\t\treturn closestAirports;\n\t}\n}\n"} {"title": "Diversity prediction theorem", "language": "Java from Kotlin", "task": "The ''wisdom of the crowd'' is the collective opinion of a group of individuals rather than that of a single expert.\n\nWisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other. \n\nThus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.\n\n\nScott E. Page introduced the diversity prediction theorem: \n: ''The squared error of the collective prediction equals the average squared error minus the predictive diversity''. \n\n\nTherefore, when the diversity in a group is large, the error of the crowd is small.\n\n\n;Definitions:\n::* Average Individual Error: Average of the individual squared errors\n::* Collective Error: Squared error of the collective prediction\n::* Prediction Diversity: Average squared distance from the individual predictions to the collective prediction\n::* Diversity Prediction Theorem: ''Given a crowd of predictive models'', then\n:::::: Collective Error = Average Individual Error - Prediction Diversity\n\n;Task:\nFor a given true value and a number of number of estimates (from a crowd), show (here on this page):\n:::* the true value and the crowd estimates\n:::* the average error\n:::* the crowd error\n:::* the prediction diversity\n\n\nUse (at least) these two examples:\n:::* a true value of '''49''' with crowd estimates of: ''' 48 47 51'''\n:::* a true value of '''49''' with crowd estimates of: ''' 48 47 51 42'''\n\n\n\n;Also see:\n:* Wikipedia entry: Wisdom of the crowd\n:* University of Michigan: PDF paper (exists on a web archive, the ''Wayback Machine'').\n\n", "solution": "import java.util.Arrays;\n\npublic class DiversityPredictionTheorem {\n private static double square(double d) {\n return d * d;\n }\n\n private static double averageSquareDiff(double d, double[] predictions) {\n return Arrays.stream(predictions)\n .map(it -> square(it - d))\n .average()\n .orElseThrow();\n }\n\n private static String diversityTheorem(double truth, double[] predictions) {\n double average = Arrays.stream(predictions)\n .average()\n .orElseThrow();\n return String.format(\"average-error : %6.3f%n\", averageSquareDiff(truth, predictions))\n + String.format(\"crowd-error : %6.3f%n\", square(truth - average))\n + String.format(\"diversity : %6.3f%n\", averageSquareDiff(average, predictions));\n }\n\n public static void main(String[] args) {\n System.out.println(diversityTheorem(49.0, new double[]{48.0, 47.0, 51.0}));\n System.out.println(diversityTheorem(49.0, new double[]{48.0, 47.0, 51.0, 42.0}));\n }\n}"} {"title": "Doomsday rule", "language": "Java", "task": " About the task\nJohn Conway (1937-2020), was a mathematician who also invented several mathematically\noriented computer pastimes, such as the famous Game of Life cellular automaton program.\nDr. Conway invented a simple algorithm for finding the day of the week, given any date.\nThe algorithm was based on calculating the distance of a given date from certain\n\"anchor days\" which follow a pattern for the day of the week upon which they fall.\n\n; Algorithm\nThe formula is calculated assuming that Sunday is 0, Monday 1, and so forth with Saturday 7, and\n\n doomsday = (Tuesday(or 2) + 5(y mod 4) + 4(y mod 100) + 6(y mod 400)) % 7\n\nwhich, for 2021, is 0 (Sunday).\n\nTo calculate the day of the week, we then count days from a close doomsday,\nwith these as charted here by month, then add the doomsday for the year,\nthen get the remainder after dividing by 7. This should give us the number\ncorresponding to the day of the week for that date.\n\n Month\t Doomsday Dates for Month\n --------------------------------------------\n January (common years) 3, 10, 17, 24, 31\n January (leap years) 4, 11, 18, 25\n February (common years) 7, 14, 21, 28\n February (leap years) 1, 8, 15, 22, 29\n March 7, 14, 21, 28\n April 4, 11, 18, 25\n May 2, 9, 16, 23, 30\n June 6, 13, 20, 27\n July 4, 11, 18, 25\n August 1, 8, 15, 22, 29\n September 5, 12, 19, 26\n October 3, 10, 17, 24, 31\n November 7, 14, 21, 28\n December 5, 12, 19, 26\n\n; Task\n\nGiven the following dates:\n\n* 1800-01-06 (January 6, 1800)\n* 1875-03-29 (March 29, 1875)\n* 1915-12-07 (December 7, 1915)\n* 1970-12-23 (December 23, 1970)\n* 2043-05-14 (May 14, 2043)\n* 2077-02-12 (February 12, 2077)\n* 2101-04-02 (April 2, 2101)\n\n\nUse Conway's Doomsday rule to calculate the day of the week for each date.\n\n\n; see also\n* Doomsday rule\n* Tomorrow is the Day After Doomsday (p.28)\n\n\n\n\n", "solution": "class Doom {\n public static void main(String[] args) {\n final Date[] dates = {\n new Date(1800,1,6),\n new Date(1875,3,29),\n new Date(1915,12,7),\n new Date(1970,12,23),\n new Date(2043,5,14),\n new Date(2077,2,12),\n new Date(2101,4,2)\n };\n \n for (Date d : dates)\n System.out.println(\n String.format(\"%s: %s\", d.format(), d.weekday()));\n }\n}\n\nclass Date {\n private int year, month, day;\n \n private static final int[] leapdoom = {4,1,7,4,2,6,4,1,5,3,7,5};\n private static final int[] normdoom = {3,7,7,4,2,6,4,1,5,3,7,5};\n public static final String[] weekdays = {\n \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n \"Thursday\", \"Friday\", \"Saturday\"\n };\n \n public Date(int year, int month, int day) {\n this.year = year;\n this.month = month;\n this.day = day;\n }\n \n public boolean isLeapYear() {\n return year%4 == 0 && (year%100 != 0 || year%400 == 0);\n }\n \n public String format() {\n return String.format(\"%02d/%02d/%04d\", month, day, year);\n }\n \n public String weekday() {\n final int c = year/100;\n final int r = year%100;\n final int s = r/12;\n final int t = r%12;\n \n final int c_anchor = (5 * (c%4) + 2) % 7;\n final int doom = (s + t + t/4 + c_anchor) % 7;\n final int anchor = \n isLeapYear() ? leapdoom[month-1] : normdoom[month-1];\n \n return weekdays[(doom + day - anchor + 7) % 7];\n }\n}"} {"title": "Dot product", "language": "Java", "task": "Create a function/use an in-built function, to compute the '''dot product''', also known as the '''scalar product''' of two vectors. \n\nIf possible, make the vectors of arbitrary length.\n\n\nAs an example, compute the dot product of the vectors:\n:::: [1, 3, -5] and \n:::: [4, -2, -1] \n\nIf implementing the dot product of two vectors directly:\n:::* each vector must be the same length\n:::* multiply corresponding terms from each vector\n:::* sum the products (to produce the answer)\n\n\n;Related task:\n* [[Vector products]]\n\n", "solution": "public class DotProduct {\n\t\n\tpublic static void main(String[] args) {\n\t\tdouble[] a = {1, 3, -5};\n\t\tdouble[] b = {4, -2, -1};\n\t\t\n\t\tSystem.out.println(dotProd(a,b));\n\t}\n\t\n\tpublic static double dotProd(double[] a, double[] b){\n\t\tif(a.length != b.length){\n\t\t\tthrow new IllegalArgumentException(\"The dimensions have to be equal!\");\n\t\t}\n\t\tdouble sum = 0;\n\t\tfor(int i = 0; i < a.length; i++){\n\t\t\tsum += a[i] * b[i];\n\t\t}\n\t\treturn sum;\n\t}\n}"} {"title": "Draw a clock", "language": "Java 8", "task": "Draw a clock. \n\n\nMore specific:\n# Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting \"one thousand and one\", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be ''drawn''; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK.\n# The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock.\n# A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task.\n# A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language.\n\n\n;Key points\n* animate simple object\n* timed event \n* polling system resources \n* code clarity\n\n", "solution": "import java.awt.*;\nimport java.awt.event.*;\nimport static java.lang.Math.*;\nimport java.time.LocalTime;\nimport javax.swing.*;\n\nclass Clock extends JPanel {\n\n final float degrees06 = (float) (PI / 30);\n final float degrees30 = degrees06 * 5;\n final float degrees90 = degrees30 * 3;\n\n final int size = 590;\n final int spacing = 40;\n final int diameter = size - 2 * spacing;\n final int cx = diameter / 2 + spacing;\n final int cy = diameter / 2 + spacing;\n\n public Clock() {\n setPreferredSize(new Dimension(size, size));\n setBackground(Color.white);\n\n new Timer(1000, (ActionEvent e) -> {\n repaint();\n }).start();\n }\n\n @Override\n public void paintComponent(Graphics gg) {\n super.paintComponent(gg);\n Graphics2D g = (Graphics2D) gg;\n g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n RenderingHints.VALUE_ANTIALIAS_ON);\n\n drawFace(g);\n\n final LocalTime time = LocalTime.now();\n int hour = time.getHour();\n int minute = time.getMinute();\n int second = time.getSecond();\n\n float angle = degrees90 - (degrees06 * second);\n drawHand(g, angle, diameter / 2 - 30, Color.red);\n\n float minsecs = (minute + second / 60.0F);\n angle = degrees90 - (degrees06 * minsecs);\n drawHand(g, angle, diameter / 3 + 10, Color.black);\n\n float hourmins = (hour + minsecs / 60.0F);\n angle = degrees90 - (degrees30 * hourmins);\n drawHand(g, angle, diameter / 4 + 10, Color.black);\n }\n\n private void drawFace(Graphics2D g) {\n g.setStroke(new BasicStroke(2));\n g.setColor(Color.white);\n g.fillOval(spacing, spacing, diameter, diameter);\n g.setColor(Color.black);\n g.drawOval(spacing, spacing, diameter, diameter);\n }\n\n private void drawHand(Graphics2D g, float angle, int radius, Color color) {\n int x = cx + (int) (radius * cos(angle));\n int y = cy - (int) (radius * sin(angle));\n g.setColor(color);\n g.drawLine(cx, cy, x, y);\n }\n\n public static void main(String[] args) {\n SwingUtilities.invokeLater(() -> {\n JFrame f = new JFrame();\n f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n f.setTitle(\"Clock\");\n f.setResizable(false);\n f.add(new Clock(), BorderLayout.CENTER);\n f.pack();\n f.setLocationRelativeTo(null);\n f.setVisible(true);\n });\n }\n}"} {"title": "Draw a rotating cube", "language": "Java", "task": "Task\nDraw a rotating cube. \n\nIt should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional.\n\n\n;Related tasks\n* Draw a cuboid\n* write language name in 3D ASCII\n\n", "solution": "import java.awt.*;\nimport java.awt.event.ActionEvent;\nimport static java.lang.Math.*;\nimport javax.swing.*;\n\npublic class RotatingCube extends JPanel {\n double[][] nodes = {{-1, -1, -1}, {-1, -1, 1}, {-1, 1, -1}, {-1, 1, 1},\n {1, -1, -1}, {1, -1, 1}, {1, 1, -1}, {1, 1, 1}};\n\n int[][] edges = {{0, 1}, {1, 3}, {3, 2}, {2, 0}, {4, 5}, {5, 7}, {7, 6},\n {6, 4}, {0, 4}, {1, 5}, {2, 6}, {3, 7}};\n\n public RotatingCube() {\n setPreferredSize(new Dimension(640, 640));\n setBackground(Color.white);\n\n scale(100);\n rotateCube(PI / 4, atan(sqrt(2)));\n\n new Timer(17, (ActionEvent e) -> {\n rotateCube(PI / 180, 0);\n repaint();\n }).start();\n }\n\n final void scale(double s) {\n for (double[] node : nodes) {\n node[0] *= s;\n node[1] *= s;\n node[2] *= s;\n }\n }\n\n final void rotateCube(double angleX, double angleY) {\n double sinX = sin(angleX);\n double cosX = cos(angleX);\n\n double sinY = sin(angleY);\n double cosY = cos(angleY);\n\n for (double[] node : nodes) {\n double x = node[0];\n double y = node[1];\n double z = node[2];\n\n node[0] = x * cosX - z * sinX;\n node[2] = z * cosX + x * sinX;\n\n z = node[2];\n\n node[1] = y * cosY - z * sinY;\n node[2] = z * cosY + y * sinY;\n }\n }\n\n void drawCube(Graphics2D g) {\n g.translate(getWidth() / 2, getHeight() / 2);\n\n for (int[] edge : edges) {\n double[] xy1 = nodes[edge[0]];\n double[] xy2 = nodes[edge[1]];\n g.drawLine((int) round(xy1[0]), (int) round(xy1[1]),\n (int) round(xy2[0]), (int) round(xy2[1]));\n }\n\n for (double[] node : nodes) \n g.fillOval((int) round(node[0]) - 4, (int) round(node[1]) - 4, 8, 8); \n }\n\n @Override\n public void paintComponent(Graphics gg) {\n super.paintComponent(gg);\n Graphics2D g = (Graphics2D) gg;\n g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n RenderingHints.VALUE_ANTIALIAS_ON);\n\n drawCube(g);\n }\n\n public static void main(String[] args) {\n SwingUtilities.invokeLater(() -> {\n JFrame f = new JFrame();\n f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n f.setTitle(\"Rotating Cube\");\n f.setResizable(false);\n f.add(new RotatingCube(), BorderLayout.CENTER);\n f.pack();\n f.setLocationRelativeTo(null);\n f.setVisible(true);\n });\n }\n}"} {"title": "Draw a sphere", "language": "Java from C", "task": "{{requires|Graphics}}\n\n\n;Task:\nDraw a sphere. \n\nThe sphere can be represented graphically, or in ASCII art, depending on the language capabilities. \n\nEither static or rotational projection is acceptable for this task.\n\n\n;Related tasks:\n* draw a cuboid\n* draw a rotating cube\n* write language name in 3D ASCII\n* draw a Deathstar\n\n", "solution": "public class Sphere{\n static char[] shades = {'.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@'};\n\n static double[] light = { 30, 30, -50 };\n private static void normalize(double[] v){\n double len = Math.sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n v[0] /= len; v[1] /= len; v[2] /= len;\n }\n\n private static double dot(double[] x, double[] y){\n double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n return d < 0 ? -d : 0;\n }\n\n public static void drawSphere(double R, double k, double ambient){\n double[] vec = new double[3];\n for(int i = (int)Math.floor(-R); i <= (int)Math.ceil(R); i++){\n double x = i + .5;\n for(int j = (int)Math.floor(-2 * R); j <= (int)Math.ceil(2 * R); j++){\n double y = j / 2. + .5;\n if(x * x + y * y <= R * R) {\n vec[0] = x;\n vec[1] = y;\n vec[2] = Math.sqrt(R * R - x * x - y * y);\n normalize(vec);\n double b = Math.pow(dot(light, vec), k) + ambient;\n int intensity = (b <= 0) ?\n shades.length - 2 :\n (int)Math.max((1 - b) * (shades.length - 1), 0);\n System.out.print(shades[intensity]);\n } else\n System.out.print(' ');\n }\n System.out.println();\n }\n }\n\n public static void main(String[] args){\n normalize(light);\n drawSphere(20, 4, .1);\n drawSphere(10, 2, .4);\n }\n}"} {"title": "Dutch national flag problem", "language": "Java", "task": "The Dutch national flag is composed of three coloured bands in the order:\n::* red (top)\n::* then white, and\n::* lastly blue (at the bottom). \n\n\nThe problem posed by Edsger Dijkstra is:\n:Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag.\nWhen the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ...\n\n\n;Task\n# Generate a randomized order of balls ''ensuring that they are not in the order of the Dutch national flag''.\n# Sort the balls in a way idiomatic to your language.\n# Check the sorted balls ''are'' in the order of the Dutch national flag.\n\n\n;C.f.:\n* Dutch national flag problem\n* Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)\n\n", "solution": "import java.util.Arrays;\nimport java.util.Random;\n\npublic class DutchNationalFlag {\n enum DutchColors {\n RED, WHITE, BLUE\n }\n\n public static void main(String[] args){\n DutchColors[] balls = new DutchColors[12];\n DutchColors[] values = DutchColors.values();\n Random rand = new Random();\n\n for (int i = 0; i < balls.length; i++)\n balls[i]=values[rand.nextInt(values.length)];\n System.out.println(\"Before: \" + Arrays.toString(balls));\n\n Arrays.sort(balls);\n System.out.println(\"After: \" + Arrays.toString(balls));\n\n boolean sorted = true;\n for (int i = 1; i < balls.length; i++ ){\n if (balls[i-1].compareTo(balls[i]) > 0){\n sorted=false;\n break;\n }\n }\n System.out.println(\"Correctly sorted: \" + sorted);\n }\n}"} {"title": "EKG sequence convergence", "language": "Java", "task": "The sequence is from the natural numbers and is defined by:\n* a(1) = 1; \n* a(2) = Start = 2;\n* for n > 2, a(n) shares at least one prime factor with a(n-1) and is the ''smallest'' such natural number ''not already used''.\n\nThe sequence is called the EKG sequence (after its visual similarity to an electrocardiogram when graphed).\n\nVariants of the sequence can be generated starting 1, N where N is any natural number larger than one. For the purposes of this task let us call: \n* The sequence described above , starting 1, 2, ... the EKG(2) sequence;\n* the sequence starting 1, 3, ... the EKG(3) sequence; \n* ... the sequence starting 1, N, ... the EKG(N) sequence.\n\n\n;Convergence\nIf an algorithm that keeps track of the minimum amount of numbers and their corresponding prime factors used to generate the next term is used, then this may be known as the generators essential '''state'''. Two EKG generators with differing starts can converge to produce the same sequence after initial differences.\nEKG(N1) and EKG(N2) are said to to have converged at and after generation a(c) if state_of(EKG(N1).a(c)) == state_of(EKG(N2).a(c)).\n\n\n;Task:\n# Calculate and show here the first 10 members of EKG(2).\n# Calculate and show here the first 10 members of EKG(5).\n# Calculate and show here the first 10 members of EKG(7).\n# Calculate and show here the first 10 members of EKG(9).\n# Calculate and show here the first 10 members of EKG(10).\n# Calculate and show here at which term EKG(5) and EKG(7) converge ('''stretch goal''').\n\n;Related Tasks:\n# [[Greatest common divisor]]\n# [[Sieve of Eratosthenes]]\n\n;Reference:\n* The EKG Sequence and the Tree of Numbers. (Video).\n\n", "solution": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class EKGSequenceConvergence {\n\n public static void main(String[] args) {\n System.out.println(\"Calculate and show here the first 10 members of EKG[2], EKG[5], EKG[7], EKG[9] and EKG[10].\");\n for ( int i : new int[] {2, 5, 7, 9, 10} ) {\n System.out.printf(\"EKG[%d] = %s%n\", i, ekg(i, 10));\n }\n System.out.println(\"Calculate and show here at which term EKG[5] and EKG[7] converge.\");\n List ekg5 = ekg(5, 100);\n List ekg7 = ekg(7, 100);\n for ( int i = 1 ; i < ekg5.size() ; i++ ) {\n if ( ekg5.get(i) == ekg7.get(i) && sameSeq(ekg5, ekg7, i)) {\n System.out.printf(\"EKG[%d](%d) = EKG[%d](%d) = %d, and are identical from this term on%n\", 5, i+1, 7, i+1, ekg5.get(i));\n break;\n }\n }\n }\n \n // Same last element, and all elements in sequence are identical\n private static boolean sameSeq(List seq1, List seq2, int n) {\n List list1 = new ArrayList<>(seq1.subList(0, n));\n Collections.sort(list1);\n List list2 = new ArrayList<>(seq2.subList(0, n));\n Collections.sort(list2);\n for ( int i = 0 ; i < n ; i++ ) {\n if ( list1.get(i) != list2.get(i) ) {\n return false;\n }\n }\n return true;\n }\n \n // Without HashMap to identify seen terms, need to examine list.\n // Calculating 3000 terms in this manner takes 10 seconds\n // With HashMap to identify the seen terms, calculating 3000 terms takes .1 sec.\n private static List ekg(int two, int maxN) {\n List result = new ArrayList<>();\n result.add(1);\n result.add(two);\n Map seen = new HashMap<>();\n seen.put(1, 1);\n seen.put(two, 1);\n int minUnseen = two == 2 ? 3 : 2;\n int prev = two;\n for ( int n = 3 ; n <= maxN ; n++ ) {\n int test = minUnseen - 1;\n while ( true ) {\n test++;\n if ( ! seen.containsKey(test) && gcd(test, prev) > 1 ) {\n \n result.add(test);\n seen.put(test, n);\n prev = test;\n if ( minUnseen == test ) {\n do {\n minUnseen++;\n } while ( seen.containsKey(minUnseen) );\n }\n break;\n }\n }\n }\n return result;\n }\n\n private static final int gcd(int a, int b) {\n if ( b == 0 ) {\n return a;\n }\n return gcd(b, a%b);\n }\n \n}\n"} {"title": "Earliest difference between prime gaps", "language": "Java", "task": "When calculating prime numbers > 2, the difference between adjacent primes is always an even number. This difference, also referred to as the gap, varies in an random pattern; at least, no pattern has ever been discovered, and it is strongly conjectured that no pattern exists. However, it is also conjectured that between some two adjacent primes will be a gap corresponding to every positive even integer.\n\n\n\n{|class=\"wikitable\"\n!gap!!minimalstartingprime!!endingprime\n|-\n|2||3||5\n|-\n|4||7||11\n|-\n|6||23||29\n|-\n|8||89||97\n|-\n|10||139||149\n|-\n|12||199||211\n|-\n|14||113||127\n|-\n|16||1831||1847\n|-\n|18||523||541\n|-\n|20||887||907\n|-\n|22||1129||1151\n|-\n|24||1669||1693\n|-\n|26||2477||2503\n|-\n|28||2971||2999\n|-\n|30||4297||4327\n|}\n\nThis task involves locating the minimal primes corresponding to those gaps.\n\nThough every gap value exists, they don't seem to come in any particular order. For example, this table shows the gaps and minimum starting value primes for 2 through 30:\n\n\nFor the purposes of this task, considering only primes greater than 2, consider prime gaps that differ by exactly two to be adjacent.\n\n\n\n;Task\n\nFor each order of magnitude '''m''' from '''101''' through '''106''':\n\n* Find the first two sets of minimum adjacent prime gaps where the absolute value of the difference between the prime gap start values is greater than '''m'''.\n\n\n;E.G.\n\nFor an '''m''' of '''101'''; \n\nThe start value of gap 2 is 3, the start value of gap 4 is 7, the difference is 7 - 3 or 4. 4 < '''101''' so keep going.\n\nThe start value of gap 4 is 7, the start value of gap 6 is 23, the difference is 23 - 7, or 16. 16 > '''101''' so this the earliest adjacent gap difference > '''101'''.\n\n\n;Stretch goal\n\n* Do the same for '''107''' and '''108''' (and higher?) orders of magnitude\n\nNote: the earliest value found for each order of magnitude may not be unique, in fact, ''is'' not unique; also, with the gaps in ascending order, the minimal starting values are not strictly ascending.\n\n", "solution": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class PrimeGaps {\n private Map gapStarts = new HashMap<>();\n private int lastPrime;\n private PrimeGenerator primeGenerator = new PrimeGenerator(1000, 500000);\n\n public static void main(String[] args) {\n final int limit = 100000000;\n PrimeGaps pg = new PrimeGaps();\n for (int pm = 10, gap1 = 2;;) {\n int start1 = pg.findGapStart(gap1);\n int gap2 = gap1 + 2;\n int start2 = pg.findGapStart(gap2);\n int diff = start2 > start1 ? start2 - start1 : start1 - start2;\n if (diff > pm) {\n System.out.printf(\n \"Earliest difference > %,d between adjacent prime gap starting primes:\\n\"\n + \"Gap %,d starts at %,d, gap %,d starts at %,d, difference is %,d.\\n\\n\",\n pm, gap1, start1, gap2, start2, diff);\n if (pm == limit)\n break;\n pm *= 10;\n } else {\n gap1 = gap2;\n }\n }\n }\n\n private int findGapStart(int gap) {\n Integer start = gapStarts.get(gap);\n if (start != null)\n return start;\n for (;;) {\n int prev = lastPrime;\n lastPrime = primeGenerator.nextPrime();\n int diff = lastPrime - prev;\n gapStarts.putIfAbsent(diff, prev);\n if (diff == gap)\n return prev;\n }\n }\n}"} {"title": "Eban numbers", "language": "Java from Kotlin", "task": "Definition:\nAn '''eban''' number is a number that has no letter '''e''' in it when the number is spelled in English.\n\nOr more literally, spelled numbers that contain the letter '''e''' are banned.\n\n\nThe American version of spelling numbers will be used here (as opposed to the British).\n\n'''2,000,000,000''' is two billion, ''not'' two milliard.\n\n\nOnly numbers less than '''one sextillion''' ('''1021''') will be considered in/for this task.\n\nThis will allow optimizations to be used.\n\n\n\n;Task:\n:::* show all eban numbers <= '''1,000''' (in a horizontal format), and a count\n:::* show all eban numbers between '''1,000''' and '''4,000''' (inclusive), and a count\n:::* show a count of all eban numbers up and including '''10,000'''\n:::* show a count of all eban numbers up and including '''100,000'''\n:::* show a count of all eban numbers up and including '''1,000,000'''\n:::* show a count of all eban numbers up and including '''10,000,000'''\n:::* show all output here.\n\n\n;See also:\n:* The MathWorld entry: eban numbers.\n:* The OEIS entry: A6933, eban numbers.\n:* [[Number names]].\n\n", "solution": "import java.util.List;\n\npublic class Main {\n private static class Range {\n int start;\n int end;\n boolean print;\n\n public Range(int s, int e, boolean p) {\n start = s;\n end = e;\n print = p;\n }\n }\n\n public static void main(String[] args) {\n List rgs = List.of(\n new Range(2, 1000, true),\n new Range(1000, 4000, true),\n new Range(2, 10_000, false),\n new Range(2, 100_000, false),\n new Range(2, 1_000_000, false),\n new Range(2, 10_000_000, false),\n new Range(2, 100_000_000, false),\n new Range(2, 1_000_000_000, false)\n );\n for (Range rg : rgs) {\n if (rg.start == 2) {\n System.out.printf(\"eban numbers up to and including %d\\n\", rg.end);\n } else {\n System.out.printf(\"eban numbers between %d and %d\\n\", rg.start, rg.end);\n }\n int count = 0;\n for (int i = rg.start; i <= rg.end; ++i) {\n int b = i / 1_000_000_000;\n int r = i % 1_000_000_000;\n int m = r / 1_000_000;\n r = i % 1_000_000;\n int t = r / 1_000;\n r %= 1_000;\n if (m >= 30 && m <= 66) m %= 10;\n if (t >= 30 && t <= 66) t %= 10;\n if (r >= 30 && r <= 66) r %= 10;\n if (b == 0 || b == 2 || b == 4 || b == 6) {\n if (m == 0 || m == 2 || m == 4 || m == 6) {\n if (t == 0 || t == 2 || t == 4 || t == 6) {\n if (r == 0 || r == 2 || r == 4 || r == 6) {\n if (rg.print) System.out.printf(\"%d \", i);\n count++;\n }\n }\n }\n }\n }\n if (rg.print) {\n System.out.println();\n }\n System.out.printf(\"count = %d\\n\\n\", count);\n }\n }\n}"} {"title": "Eertree", "language": "Java from D", "task": "An '''eertree''' is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. \n\nThe data structure has commonalities to both ''tries'' and ''suffix trees''.\n See links below. \n\n\n;Task:\nConstruct an eertree for the string \"eertree\", then output all sub-palindromes by traversing the tree.\n\n\n;See also:\n* Wikipedia entry: trie.\n* Wikipedia entry: suffix tree \n* Cornell University Library, Computer Science, Data Structures and Algorithms ---> EERTREE: An Efficient Data Structure for Processing Palindromes in Strings.\n\n", "solution": "import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class Eertree {\n public static void main(String[] args) {\n List tree = eertree(\"eertree\");\n List result = subPalindromes(tree);\n System.out.println(result);\n }\n\n private static class Node {\n int length;\n Map edges = new HashMap<>();\n int suffix;\n\n public Node(int length) {\n this.length = length;\n }\n\n public Node(int length, Map edges, int suffix) {\n this.length = length;\n this.edges = edges != null ? edges : new HashMap<>();\n this.suffix = suffix;\n }\n }\n\n private static final int EVEN_ROOT = 0;\n private static final int ODD_ROOT = 1;\n\n private static List eertree(String s) {\n List tree = new ArrayList<>();\n tree.add(new Node(0, null, ODD_ROOT));\n tree.add(new Node(-1, null, ODD_ROOT));\n int suffix = ODD_ROOT;\n int n, k;\n for (int i = 0; i < s.length(); ++i) {\n char c = s.charAt(i);\n for (n = suffix; ; n = tree.get(n).suffix) {\n k = tree.get(n).length;\n int b = i - k - 1;\n if (b >= 0 && s.charAt(b) == c) {\n break;\n }\n }\n if (tree.get(n).edges.containsKey(c)) {\n suffix = tree.get(n).edges.get(c);\n continue;\n }\n suffix = tree.size();\n tree.add(new Node(k + 2));\n tree.get(n).edges.put(c, suffix);\n if (tree.get(suffix).length == 1) {\n tree.get(suffix).suffix = 0;\n continue;\n }\n while (true) {\n n = tree.get(n).suffix;\n int b = i - tree.get(n).length - 1;\n if (b >= 0 && s.charAt(b) == c) {\n break;\n }\n }\n tree.get(suffix).suffix = tree.get(n).edges.get(c);\n }\n return tree;\n }\n\n private static List subPalindromes(List tree) {\n List s = new ArrayList<>();\n subPalindromes_children(0, \"\", tree, s);\n for (Map.Entry cm : tree.get(1).edges.entrySet()) {\n String ct = String.valueOf(cm.getKey());\n s.add(ct);\n subPalindromes_children(cm.getValue(), ct, tree, s);\n }\n return s;\n }\n\n // nested methods are a pain, even if lambdas make that possible for Java\n private static void subPalindromes_children(final int n, final String p, final List tree, List s) {\n for (Map.Entry cm : tree.get(n).edges.entrySet()) {\n Character c = cm.getKey();\n Integer m = cm.getValue();\n String pl = c + p + c;\n s.add(pl);\n subPalindromes_children(m, pl, tree, s);\n }\n }\n}"} {"title": "Egyptian division", "language": "Java", "task": "Egyptian division is a method of dividing integers using addition and \ndoubling that is similar to the algorithm of [[Ethiopian multiplication]]\n\n'''Algorithm:'''\n\nGiven two numbers where the '''dividend''' is to be divided by the '''divisor''':\n\n# Start the construction of a table of two columns: '''powers_of_2''', and '''doublings'''; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column.\n# Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order.\n# Continue with successive i'th rows of 2^i and 2^i * divisor.\n# Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend.\n# We now assemble two separate sums that both start as zero, called here '''answer''' and '''accumulator'''\n# Consider each row of the table, in the ''reverse'' order of its construction.\n# If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer.\n# When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend).\n\n\n'''Example: 580 / 34'''\n\n''' Table creation: '''\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n|-\n| 1\n| 34\n|-\n| 2\n| 68\n|-\n| 4\n| 136\n|-\n| 8\n| 272\n|-\n| 16\n| 544\n|}\n\n''' Initialization of sums: '''\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| 16\n| 544\n|\n\n|\n\n|-\n|\n|\n| 0\n| 0\n|}\n\n''' Considering table rows, bottom-up: '''\n\nWhen a row is considered it is shown crossed out if it is not accumulated, or '''bold''' if the row causes summations.\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n| 16\n| 544\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n| 16\n| 544\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n| 16\n| 544\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n| 16\n| 544\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| '''1'''\n| '''34'''\n| 17\n| 578\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n;Answer:\nSo 580 divided by 34 using the Egyptian method is '''17''' remainder (578 - 580) or '''2'''.\n\n\n;Task:\nThe task is to create a function that does Egyptian division. The function should\nclosely follow the description above in using a list/array of powers of two, and\nanother of doublings.\n\n* Functions should be clear interpretations of the algorithm.\n* Use the function to divide 580 by 34 and show the answer '''here, on this page'''.\n\n\n;Related tasks:\n:* Egyptian fractions\n\n\n;References:\n:* Egyptian Number System\n\n", "solution": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class EgyptianDivision {\n\n /**\n * Runs the method and divides 580 by 34\n *\n * @param args not used\n */\n public static void main(String[] args) {\n\n divide(580, 34);\n\n }\n\n /**\n * Divides dividend by divisor using the Egyptian Division-Algorithm and prints the\n * result to the console\n *\n * @param dividend\n * @param divisor\n */\n public static void divide(int dividend, int divisor) {\n\n List powersOf2 = new ArrayList<>();\n List doublings = new ArrayList<>();\n\n //populate the powersof2- and doublings-columns\n int line = 0;\n while ((Math.pow(2, line) * divisor) <= dividend) { //<- could also be done with a for-loop\n int powerOf2 = (int) Math.pow(2, line);\n powersOf2.add(powerOf2);\n doublings.add(powerOf2 * divisor);\n line++;\n }\n\n int answer = 0;\n int accumulator = 0;\n\n //Consider the rows in reverse order of their construction (from back to front of the List<>s)\n for (int i = powersOf2.size() - 1; i >= 0; i--) {\n if (accumulator + doublings.get(i) <= dividend) {\n accumulator += doublings.get(i);\n answer += powersOf2.get(i);\n }\n }\n\n System.out.println(String.format(\"%d, remainder %d\", answer, dividend - accumulator));\n }\n}\n\n"} {"title": "Elementary cellular automaton", "language": "Java 8", "task": "An '''cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits.\n\nThe rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101.\n\n\n;Task:\nCreate a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice.\n\nThe space state should ''wrap'': this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally.\n\nThis task is basically a generalization of [[one-dimensional cellular automata]].\n\n\n;See also\n* Cellular automata (natureofcode.com)\n\n", "solution": "import java.awt.*;\nimport java.awt.event.ActionEvent;\nimport javax.swing.*;\nimport javax.swing.Timer;\n\npublic class WolframCA extends JPanel {\n final int[] ruleSet = {30, 45, 50, 57, 62, 70, 73, 75, 86, 89, 90, 99,\n 101, 105, 109, 110, 124, 129, 133, 135, 137, 139, 141, 164,170, 232};\n byte[][] cells;\n int rule = 0;\n\n public WolframCA() {\n Dimension dim = new Dimension(900, 450);\n setPreferredSize(dim);\n setBackground(Color.white);\n setFont(new Font(\"SansSerif\", Font.BOLD, 28));\n\n cells = new byte[dim.height][dim.width];\n cells[0][dim.width / 2] = 1;\n\n new Timer(5000, (ActionEvent e) -> {\n rule++;\n if (rule == ruleSet.length)\n rule = 0;\n repaint();\n }).start();\n }\n\n private byte rules(int lhs, int mid, int rhs) {\n int idx = (lhs << 2 | mid << 1 | rhs);\n return (byte) (ruleSet[rule] >> idx & 1);\n }\n\n void drawCa(Graphics2D g) {\n g.setColor(Color.black);\n for (int r = 0; r < cells.length - 1; r++) {\n for (int c = 1; c < cells[r].length - 1; c++) {\n byte lhs = cells[r][c - 1];\n byte mid = cells[r][c];\n byte rhs = cells[r][c + 1];\n cells[r + 1][c] = rules(lhs, mid, rhs); // next generation\n if (cells[r][c] == 1) {\n g.fillRect(c, r, 1, 1);\n }\n }\n }\n }\n\n void drawLegend(Graphics2D g) {\n String s = String.valueOf(ruleSet[rule]);\n int sw = g.getFontMetrics().stringWidth(s);\n\n g.setColor(Color.white);\n g.fillRect(16, 5, 55, 30);\n\n g.setColor(Color.darkGray);\n g.drawString(s, 16 + (55 - sw) / 2, 30);\n }\n\n @Override\n public void paintComponent(Graphics gg) {\n super.paintComponent(gg);\n Graphics2D g = (Graphics2D) gg;\n g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n RenderingHints.VALUE_ANTIALIAS_ON);\n\n drawCa(g);\n drawLegend(g);\n }\n\n public static void main(String[] args) {\n SwingUtilities.invokeLater(() -> {\n JFrame f = new JFrame();\n f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n f.setTitle(\"Wolfram CA\");\n f.setResizable(false);\n f.add(new WolframCA(), BorderLayout.CENTER);\n f.pack();\n f.setLocationRelativeTo(null);\n f.setVisible(true);\n });\n }\n}"} {"title": "Elliptic curve arithmetic", "language": "Java from D", "task": "digital signatures. \n\nThe purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the elliptic curve DSA protocol. \n\nIn a nutshell, an elliptic curve is a bi-dimensional curve defined by the following relation between the '''x''' and '''y''' coordinates of any point on the curve:\n\n:::: y^2 = x^3 + a x + b\n\n'''a''' and '''b''' are arbitrary parameters that define the specific curve which is used. \n\nFor this particular task, we'll use the following parameters:\n\n:::: a=0, b=7 \n\nThe most interesting thing about elliptic curves is the fact that it is possible to define a group structure on it. \n\nTo do so we define an internal composition rule with an additive notation '''+''', such that for any three distinct points '''P''', '''Q''' and '''R''' on the curve, whenever these points are aligned, we have:\n\n:::: P + Q + R = 0 \n\nHere '''0''' (zero) is the ''infinity point'', for which the '''x''' and '''y''' values are not defined. It's basically the same kind of point which defines the horizon in projective geometry. \n\nWe'll also assume here that this infinity point is unique and defines the neutral element of the addition.\n\nThis was not the definition of the addition, but only its desired property. For a more accurate definition, we proceed as such:\n\nGiven any three aligned points '''P''', '''Q''' and '''R''', we define the sum '''S = P + Q''' as the point (possibly the infinity point) such that '''S''', '''R''' and the infinity point are aligned.\n\nConsidering the symmetry of the curve around the x-axis, it's easy to convince oneself that two points '''S''' and '''R''' can be aligned with the infinity point if and only if '''S''' and '''R''' are symmetric of one another towards the x-axis (because in that case there is no other candidate than the infinity point to complete the alignment triplet).\n\n'''S''' is thus defined as the symmetric of '''R''' towards the '''x''' axis.\n\nThe task consists in defining the addition which, for any two points of the curve, returns the sum of these two points. You will pick two random points on the curve, compute their sum and show that the symmetric of the sum is aligned with the two initial points. \n\nYou will use the '''a''' and '''b''' parameters of secp256k1, i.e. respectively zero and seven.\n\n''Hint'': You might need to define a \"doubling\" function, that returns '''P+P''' for any given point '''P'''.\n\n''Extra credit'': define the full elliptic curve arithmetic (still not modular, though) by defining a \"multiply\" function that returns, \nfor any point '''P''' and integer '''n''', the point '''P + P + ... + P''' ('''n''' times).\n\n", "solution": "import static java.lang.Math.*;\nimport java.util.Locale;\n\npublic class Test {\n\n public static void main(String[] args) {\n Pt a = Pt.fromY(1);\n Pt b = Pt.fromY(2);\n System.out.printf(\"a = %s%n\", a);\n System.out.printf(\"b = %s%n\", b);\n Pt c = a.plus(b);\n System.out.printf(\"c = a + b = %s%n\", c);\n Pt d = c.neg();\n System.out.printf(\"d = -c = %s%n\", d);\n System.out.printf(\"c + d = %s%n\", c.plus(d));\n System.out.printf(\"a + b + d = %s%n\", a.plus(b).plus(d));\n System.out.printf(\"a * 12345 = %s%n\", a.mult(12345));\n }\n}\n\nclass Pt {\n final static int bCoeff = 7;\n\n double x, y;\n\n Pt(double x, double y) {\n this.x = x;\n this.y = y;\n }\n\n static Pt zero() {\n return new Pt(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);\n }\n\n boolean isZero() {\n return this.x > 1e20 || this.x < -1e20;\n }\n\n static Pt fromY(double y) {\n return new Pt(cbrt(pow(y, 2) - bCoeff), y);\n }\n\n Pt dbl() {\n if (isZero())\n return this;\n double L = (3 * this.x * this.x) / (2 * this.y);\n double x2 = pow(L, 2) - 2 * this.x;\n return new Pt(x2, L * (this.x - x2) - this.y);\n }\n\n Pt neg() {\n return new Pt(this.x, -this.y);\n }\n\n Pt plus(Pt q) {\n if (this.x == q.x && this.y == q.y)\n return dbl();\n\n if (isZero())\n return q;\n\n if (q.isZero())\n return this;\n\n double L = (q.y - this.y) / (q.x - this.x);\n double xx = pow(L, 2) - this.x - q.x;\n return new Pt(xx, L * (this.x - xx) - this.y);\n }\n\n Pt mult(int n) {\n Pt r = Pt.zero();\n Pt p = this;\n for (int i = 1; i <= n; i <<= 1) {\n if ((i & n) != 0)\n r = r.plus(p);\n p = p.dbl();\n }\n return r;\n }\n\n @Override\n public String toString() {\n if (isZero())\n return \"Zero\";\n return String.format(Locale.US, \"(%.3f,%.3f)\", this.x, this.y);\n }\n}"} {"title": "Empty directory", "language": "Java 7+", "task": "Starting with a path to some directory, determine whether the directory is empty.\n\nAn empty directory contains no files nor subdirectories. \nWith [[Unix]] or [[Windows]] systems, every directory contains an entry for \".\" and almost every directory contains \"..\" (except for a root directory); an empty directory contains no other entries.\n\n", "solution": "import java.nio.file.Paths;\n//... other class code here\npublic static boolean isEmptyDir(String dirName){\n return Paths.get(dirName).toFile().listFiles().length == 0;\n}"} {"title": "Empty string", "language": "Java", "task": "Languages may have features for dealing specifically with empty strings \n(those containing no characters).\n\n\n;Task:\n::* Demonstrate how to assign an empty string to a variable.\n::* Demonstrate how to check that a string is empty.\n::* Demonstrate how to check that a string is not empty.\n\n\n\n", "solution": "String s = \"\";\nif(s != null && s.isEmpty()){//optionally, instead of \"s.isEmpty()\": \"s.length() == 0\" or \"s.equals(\"\")\"\n System.out.println(\"s is empty\");\n}else{\n System.out.println(\"s is not empty\");\n}"} {"title": "Entropy/Narcissist", "language": "Java", "task": "Write a computer program that computes and shows its own [[entropy]].\n\n\n;Related Tasks: \n:* [[Fibonacci_word]]\n:* [[Entropy]]\n\n", "solution": "import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class EntropyNarcissist {\n\n private static final String FILE_NAME = \"src/EntropyNarcissist.java\";\n \n public static void main(String[] args) {\n System.out.printf(\"Entropy of file \\\"%s\\\" = %.12f.%n\", FILE_NAME, getEntropy(FILE_NAME));\n }\n \n private static double getEntropy(String fileName) {\n Map characterCount = new HashMap<>();\n int length = 0;\n\n try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));) { \n int c = 0;\n while ( (c = reader.read()) != -1 ) {\n characterCount.merge((char) c, 1, (v1, v2) -> v1 + v2);\n length++;\n }\n }\n catch ( IOException e ) {\n throw new RuntimeException(e);\n }\n \n double entropy = 0;\n for ( char key : characterCount.keySet() ) {\n double fraction = (double) characterCount.get(key) / length;\n entropy -= fraction * Math.log(fraction);\n }\n\n return entropy / Math.log(2);\n }\n\n}\n"} {"title": "Equilibrium index", "language": "Java 1.5+", "task": "An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. \n\n\nFor example, in a sequence A:\n\n::::: A_0 = -7\n::::: A_1 = 1\n::::: A_2 = 5\n::::: A_3 = 2\n::::: A_4 = -4\n::::: A_5 = 3\n::::: A_6 = 0\n\n3 is an equilibrium index, because:\n\n::::: A_0 + A_1 + A_2 = A_4 + A_5 + A_6\n\n6 is also an equilibrium index, because:\n\n::::: A_0 + A_1 + A_2 + A_3 + A_4 + A_5 = 0\n\n(sum of zero elements is zero) \n\n7 is not an equilibrium index, because it is not a valid index of sequence A.\n\n\n;Task;\nWrite a function that, given a sequence, returns its equilibrium indices (if any).\n\nAssume that the sequence may be very long.\n\n", "solution": "public class Equlibrium {\n\tpublic static void main(String[] args) {\n\t\tint[] sequence = {-7, 1, 5, 2, -4, 3, 0};\n\t\tequlibrium_indices(sequence);\n\t}\n\n\tpublic static void equlibrium_indices(int[] sequence){\n\t\t//find total sum\n\t\tint totalSum = 0;\n\t\tfor (int n : sequence) {\n\t\t\ttotalSum += n;\n\t\t}\n\t\t//compare running sum to remaining sum to find equlibrium indices\n\t\tint runningSum = 0;\n\t\tfor (int i = 0; i < sequence.length; i++) {\n\t\t\tint n = sequence[i];\n\t\t\tif (totalSum - runningSum - n == runningSum) {\n\t\t\t\tSystem.out.println(i);\n\t\t\t}\n\t\t\trunningSum += n;\n\t\t}\n\t}\n}\n"} {"title": "Erd\u00f6s-Selfridge categorization of primes", "language": "Java", "task": "A prime p is in category 1 if the prime factors of p+1 are 2 and or 3. p is in category 2 if all the prime factors of p+1 are in category 1. p is in category g if all the prime factors of p+1 are in categories 1 to g-1.\n\nThe task is first to display the first 200 primes allocated to their category, then assign the first million primes to their category, displaying the smallest prime, the largest prime, and the count of primes allocated to each category.\n\n", "solution": "import java.util.*;\n\npublic class ErdosSelfridge {\n private int[] primes;\n private int[] category;\n\n public static void main(String[] args) {\n ErdosSelfridge es = new ErdosSelfridge(1000000);\n\n System.out.println(\"First 200 primes:\");\n for (var e : es.getPrimesByCategory(200).entrySet()) {\n int category = e.getKey();\n List primes = e.getValue();\n System.out.printf(\"Category %d:\\n\", category);\n for (int i = 0, n = primes.size(); i != n; ++i)\n System.out.printf(\"%4d%c\", primes.get(i), (i + 1) % 15 == 0 ? '\\n' : ' ');\n System.out.printf(\"\\n\\n\");\n }\n\n System.out.println(\"First 1,000,000 primes:\");\n for (var e : es.getPrimesByCategory(1000000).entrySet()) {\n int category = e.getKey();\n List primes = e.getValue();\n System.out.printf(\"Category %2d: first = %7d last = %8d count = %d\\n\", category,\n primes.get(0), primes.get(primes.size() - 1), primes.size());\n }\n }\n\n private ErdosSelfridge(int limit) {\n PrimeGenerator primeGen = new PrimeGenerator(100000, 200000);\n List primeList = new ArrayList<>();\n for (int i = 0; i < limit; ++i)\n primeList.add(primeGen.nextPrime());\n primes = new int[primeList.size()];\n for (int i = 0; i < primes.length; ++i)\n primes[i] = primeList.get(i);\n category = new int[primes.length];\n }\n\n private Map> getPrimesByCategory(int limit) {\n Map> result = new TreeMap<>();\n for (int i = 0; i < limit; ++i) {\n var p = result.computeIfAbsent(getCategory(i), k -> new ArrayList());\n p.add(primes[i]);\n }\n return result;\n }\n\n private int getCategory(int index) {\n if (category[index] != 0)\n return category[index];\n int maxCategory = 0;\n int n = primes[index] + 1;\n for (int i = 0; n > 1; ++i) {\n int p = primes[i];\n if (p * p > n)\n break;\n int count = 0;\n for (; n % p == 0; ++count)\n n /= p;\n if (count != 0) {\n int category = (p <= 3) ? 1 : 1 + getCategory(i);\n maxCategory = Math.max(maxCategory, category);\n }\n }\n if (n > 1) {\n int category = (n <= 3) ? 1 : 1 + getCategory(getIndex(n));\n maxCategory = Math.max(maxCategory, category);\n }\n category[index] = maxCategory;\n return maxCategory;\n }\n\n private int getIndex(int prime) {\n return Arrays.binarySearch(primes, prime);\n }\n}"} {"title": "Erd\u0151s-Nicolas numbers", "language": "Java", "task": "Definition\nAn perfect but is equal to the sum of its first '''k''' divisors (arranged in ascending order and including one) for some value of '''k''' greater than one.\n\n;Examples\n24 is an Erdos-Nicolas number because the sum of its first 6 divisors (1, 2, 3, 4, 6 and 8) is equal to 24 and it is not perfect because 12 is also a divisor.\n\n6 is not an Erdos-Nicolas number because it is perfect (1 + 2 + 3 = 6).\n\n48 is not an Erdos-Nicolas number because its divisors are: 1, 2, 3, 4, 6, 8, 12, 16, 24 and 48. The first seven of these add up to 36, but the first eight add up to 52 which is more than 48.\n\n;Task\n\nFind and show here the first 8 Erdos-Nicolas numbers and the number of divisors needed (i.e. the value of 'k') to satisfy the definition.\n\n;Stretch\nDo the same for any further Erdos-Nicolas numbers which you have the patience for.\n\n;Note\nAs all known Erdos-Nicolas numbers are even you may assume this to be generally true in order to quicken up the search. However, it is not obvious (to me at least) why this should necessarily be the case.\n\n;Reference\n* OEIS:A194472 - Erdos-Nicolas numbers\n\n", "solution": "import java.util.Arrays;\n\npublic final class ErdosNicolasNumbers {\n\n\tpublic static void main(String[] aArgs) {\n\t\tfinal int limit = 100_000_000;\n\t\t\n\t int[] divisorSum = new int[limit + 1];\n\t int[] divisorCount = new int[limit + 1];\n\t Arrays.fill(divisorSum, 1);\n\t Arrays.fill(divisorCount, 1);\n\t \n\t for ( int index = 2; index <= limit / 2; index++ ) {\n\t for ( int number = 2 * index; number <= limit; number += index ) {\n\t if ( divisorSum[number] == number ) {\n\t System.out.println(String.format(\"%8d\", number) + \" equals the sum of its first \"\n\t \t + String.format(\"%3d\", divisorCount[number]) + \" divisors\");\n\t }\n\t \n\t divisorSum[number] += index;\n\t divisorCount[number]++;\n\t }\n\t }\n\t}\n\n}\n"} {"title": "Esthetic numbers", "language": "Java from Kotlin", "task": "An '''esthetic number''' is a positive integer where every adjacent digit differs from its neighbour by 1.\n\n\n;E.G.\n\n:* '''12''' is an esthetic number. One and two differ by 1.\n\n:* '''5654''' is an esthetic number. Each digit is exactly 1 away from its neighbour.\n\n:* '''890''' is '''not''' an esthetic number. Nine and zero differ by 9.\n\n\nThese examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers ''are'' included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros.\n\nEsthetic numbers are also sometimes referred to as stepping numbers.\n\n\n;Task\n\n:* Write a routine (function, procedure, whatever) to find esthetic numbers in a given base.\n\n:* Use that routine to find esthetic numbers in bases '''2''' through '''16''' and display, here on this page, the esthectic numbers from index '''(base x 4)''' through index '''(base x 6)''', inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.)\n\n:* Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1000''' and '''9999'''.\n\n:* Stretch: Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1.0e8''' and '''1.3e8'''.\n\n\n;Related task:\n* numbers with equal rises and falls\n\n\n;See also:\n:;*OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1\n:;*Numbers Aplenty - Esthetic numbers\n:;*Geeks for Geeks - Stepping numbers\n\n", "solution": "import java.util.ArrayList;\nimport java.util.stream.IntStream;\nimport java.util.stream.LongStream;\n\npublic class EstheticNumbers {\n interface RecTriConsumer {\n void accept(RecTriConsumer f, A a, B b, C c);\n }\n\n private static boolean isEsthetic(long n, long b) {\n if (n == 0) {\n return false;\n }\n var i = n % b;\n var n2 = n / b;\n while (n2 > 0) {\n var j = n2 % b;\n if (Math.abs(i - j) != 1) {\n return false;\n }\n n2 /= b;\n i = j;\n }\n return true;\n }\n\n private static void listEsths(long n, long n2, long m, long m2, int perLine, boolean all) {\n var esths = new ArrayList();\n var dfs = new RecTriConsumer() {\n public void accept(Long n, Long m, Long i) {\n accept(this, n, m, i);\n }\n\n @Override\n public void accept(RecTriConsumer f, Long n, Long m, Long i) {\n if (n <= i && i <= m) {\n esths.add(i);\n }\n if (i == 0 || i > m) {\n return;\n }\n var d = i % 10;\n var i1 = i * 10 + d - 1;\n var i2 = i1 + 2;\n if (d == 0) {\n f.accept(f, n, m, i2);\n } else if (d == 9) {\n f.accept(f, n, m, i1);\n } else {\n f.accept(f, n, m, i1);\n f.accept(f, n, m, i2);\n }\n }\n };\n\n LongStream.range(0, 10).forEach(i -> dfs.accept(n2, m2, i));\n\n var le = esths.size();\n System.out.printf(\"Base 10: %d esthetic numbers between %d and %d:%n\", le, n, m);\n if (all) {\n for (int i = 0; i < esths.size(); i++) {\n System.out.printf(\"%d \", esths.get(i));\n if ((i + 1) % perLine == 0) {\n System.out.println();\n }\n }\n } else {\n for (int i = 0; i < perLine; i++) {\n System.out.printf(\"%d \", esths.get(i));\n }\n System.out.println();\n System.out.println(\"............\");\n for (int i = le - perLine; i < le; i++) {\n System.out.printf(\"%d \", esths.get(i));\n }\n }\n System.out.println();\n System.out.println();\n }\n\n public static void main(String[] args) {\n IntStream.rangeClosed(2, 16).forEach(b -> {\n System.out.printf(\"Base %d: %dth to %dth esthetic numbers:%n\", b, 4 * b, 6 * b);\n var n = 1L;\n var c = 0L;\n while (c < 6 * b) {\n if (isEsthetic(n, b)) {\n c++;\n if (c >= 4 * b) {\n System.out.printf(\"%s \", Long.toString(n, b));\n }\n }\n n++;\n }\n System.out.println();\n });\n System.out.println();\n\n // the following all use the obvious range limitations for the numbers in question\n listEsths(1000, 1010, 9999, 9898, 16, true);\n listEsths((long) 1e8, 101_010_101, 13 * (long) 1e7, 123_456_789, 9, true);\n listEsths((long) 1e11, 101_010_101_010L, 13 * (long) 1e10, 123_456_789_898L, 7, false);\n listEsths((long) 1e14, 101_010_101_010_101L, 13 * (long) 1e13, 123_456_789_898_989L, 5, false);\n listEsths((long) 1e17, 101_010_101_010_101_010L, 13 * (long) 1e16, 123_456_789_898_989_898L, 4, false);\n }\n}"} {"title": "Euclid-Mullin sequence", "language": "Java", "task": "Definition\nThe Euclid-Mullin sequence is an infinite sequence of distinct prime numbers, in which each element is the least prime factor of one plus the product of all earlier elements. \n\nThe first element is usually assumed to be 2. So the second element is : (2) + 1 = 3 and the third element is : (2 x 3) + 1 = 7 as this is prime.\n\nAlthough intermingled with smaller elements, the sequence can produce very large elements quite quickly and only the first 51 have been computed at the time of writing.\n\n;Task\nCompute and show here the first '''16''' elements of the sequence or, if your language does not support arbitrary precision arithmetic, as many as you can.\n\n;Stretch goal\nCompute the next '''11''' elements of the sequence.\n\n;Reference\nOEIS sequence A000945\n\n", "solution": "import java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.BitSet;\nimport java.util.List;\nimport java.util.concurrent.ThreadLocalRandom;\n\npublic class EulerMullinSequence {\n\n\tpublic static void main(String[] aArgs) {\n\t\tprimes = listPrimesUpTo(1_000_000);\n\t\t\n\t\tSystem.out.println(\"The first 27 terms of the Euler-Mullin sequence:\");\n\t\tSystem.out.println(2);\n\t\tfor ( int i = 1; i < 27; i++ ) {\n\t\t\tSystem.out.println(nextEulerMullin());\n\t\t}\n\n\t}\n\t\n\tprivate static BigInteger nextEulerMullin() {\n\t\tBigInteger smallestPrime = smallestPrimeFactor(product.add(BigInteger.ONE));\n\t\tproduct = product.multiply(smallestPrime);\n\t\t\n\t\treturn smallestPrime;\n\t}\n\t\n\tprivate static BigInteger smallestPrimeFactor(BigInteger aNumber) {\n\t\tif ( aNumber.isProbablePrime(probabilityLevel) ) {\n\t\t\treturn aNumber;\n\t\t}\n\t\t\n\t\tfor ( BigInteger prime : primes ) {\n\t\t\tif ( aNumber.mod(prime).signum() == 0 ) {\n\t\t\t\treturn prime;\n\t\t\t}\n \t\t}\n\t\t\n\t\tBigInteger factor = pollardsRho(aNumber);\n\t\treturn smallestPrimeFactor(factor);\n\t}\n\t\n\tprivate static BigInteger pollardsRho(BigInteger aN) {\n\t\tif ( aN.equals(BigInteger.ONE) ) {\n\t\t\treturn BigInteger.ONE;\n\t\t}\n\t\t\n\t\tif ( aN.mod(BigInteger.TWO).signum() == 0 ) {\n\t\t\treturn BigInteger.TWO;\n\t\t}\n\t\t\n\t\tfinal BigInteger core = new BigInteger(aN.bitLength(), random);\n\t\tBigInteger x = new BigInteger(aN.bitLength(), random);\n\t\tBigInteger xx = x;\n\t\tBigInteger divisor = null;\t\t\n\t\t\n\t\tdo {\n\t\t\tx = x.multiply(x).mod(aN).add(core).mod(aN);\n\t\t\txx = xx.multiply(xx).mod(aN).add(core).mod(aN);\n\t\t\txx = xx.multiply(xx).mod(aN).add(core).mod(aN);\n\t\t\tdivisor = x.subtract(xx).gcd(aN);\n\t\t} while ( divisor.equals(BigInteger.ONE) );\n\t\t\n\t\treturn divisor;\n\t}\t\n\t\n\tprivate static List listPrimesUpTo(int aLimit) {\n\t\tBitSet sieve = new BitSet(aLimit + 1);\n\t\tsieve.set(2, aLimit + 1);\n\t\t\n\t\tfinal int squareRoot = (int) Math.sqrt(aLimit);\n\t\tfor ( int i = 2; i <= squareRoot; i = sieve.nextSetBit(i + 1) ) {\n\t\t\tfor ( int j = i * i; j <= aLimit; j = j + i ) {\n\t\t\t\tsieve.clear(j);\n\t\t\t}\n\t\t}\n\t\t\n\t\tList result = new ArrayList(sieve.cardinality());\n\t\tfor ( int i = 2; i >= 0; i = sieve.nextSetBit(i + 1) ) {\n\t\t\tresult.add(BigInteger.valueOf(i));\n\t\t}\n\t\t\n\t\treturn result;\n\t}\n\t\n\tprivate static List primes;\n\tprivate static BigInteger product = BigInteger.TWO;\n\tprivate static ThreadLocalRandom random = ThreadLocalRandom.current();\n\t\n\tprivate static final int probabilityLevel = 20;\n\n}\n"} {"title": "Euler's identity", "language": "Java", "task": "{{Wikipedia|Euler's_identity}}\n\n\nIn mathematics, ''Euler's identity'' is the equality:\n\n ei\\pi + 1 = 0\n\nwhere\n\n e is Euler's number, the base of natural logarithms,\n ''i'' is the imaginary unit, which satisfies ''i''2 = -1, and\n \\pi is pi, the ratio of the circumference of a circle to its diameter.\n\nEuler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:\n\n The number 0.\n The number 1.\n The number \\pi (\\pi = 3.14159+),\n The number e (e = 2.71828+), which occurs widely in mathematical analysis.\n The number ''i'', the imaginary unit of the complex numbers.\n\n;Task\nShow in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation. \n\nMost languages are limited to IEEE 754 floating point calculations so will have some error in the calculation. \n\nIf that is the case, or there is some other limitation, show \nthat ei\\pi + 1 is ''approximately'' equal to zero and \nshow the amount of error in the calculation.\n\nIf your language is capable of symbolic calculations, show \nthat ei\\pi + 1 is ''exactly'' equal to zero for bonus kudos points.\n\n", "solution": "public class EulerIdentity {\n\n public static void main(String[] args) {\n System.out.println(\"e ^ (i*Pi) + 1 = \" + (new Complex(0, Math.PI).exp()).add(new Complex(1, 0)));\n }\n\n public static class Complex {\n\n private double x, y;\n \n public Complex(double re, double im) {\n x = re;\n y = im;\n }\n \n public Complex exp() {\n double exp = Math.exp(x);\n return new Complex(exp * Math.cos(y), exp * Math.sin(y));\n }\n \n public Complex add(Complex a) {\n return new Complex(x + a.x, y + a.y);\n }\n \n @Override\n public String toString() {\n return x + \" + \" + y + \"i\";\n }\n }\n}\n"} {"title": "Euler's sum of powers conjecture", "language": "Java from ALGOL 68", "task": "There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.\n\nThis conjecture is called Euler's sum of powers conjecture and can be stated as such:\n\n:At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk.\n\nIn 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.\n\nThe task consists in writing a program to search for an integer solution of x_0^5 + x_1^5 + x_2^5 + x_3^5 = y^5 where all x_i and y are distinct integers between 0 and 250 (exclusive). Show an answer here.\n\nRelated tasks are:\n* [[Pythagorean quadruples]]. \n* [[Pythagorean triples]].\n\n\n\n", "solution": "public class eulerSopConjecture\n{\n\n static final int MAX_NUMBER = 250;\n\n public static void main( String[] args )\n {\n boolean found = false;\n long[] fifth = new long[ MAX_NUMBER ];\n\n for( int i = 1; i <= MAX_NUMBER; i ++ )\n {\n long i2 = i * i;\n fifth[ i - 1 ] = i2 * i2 * i;\n } // for i\n\n for( int a = 0; a < MAX_NUMBER && ! found ; a ++ )\n {\n for( int b = a; b < MAX_NUMBER && ! found ; b ++ )\n {\n for( int c = b; c < MAX_NUMBER && ! found ; c ++ )\n {\n for( int d = c; d < MAX_NUMBER && ! found ; d ++ )\n {\n long sum = fifth[a] + fifth[b] + fifth[c] + fifth[d];\n int e = java.util.Arrays.binarySearch( fifth, sum );\n found = ( e >= 0 );\n if( found )\n {\n // the value at e is a fifth power\n System.out.print( (a+1) + \"^5 + \"\n + (b+1) + \"^5 + \"\n + (c+1) + \"^5 + \"\n + (d+1) + \"^5 = \"\n + (e+1) + \"^5\"\n );\n } // if found;;\n } // for d\n } // for c\n } // for b\n } // for a\n } // main\n\n} // eulerSopConjecture"} {"title": "Even or odd", "language": "Java", "task": "Test whether an integer is even or odd.\n\nThere is more than one way to solve this task:\n\n* Use the even and odd predicates, if the language provides them.\n* Check the least significant digit. With binary integers, ''i iff ''i'' is even, or equals 1 iff ''i'' is odd.\n* Divide ''i'' by 2. The remainder equals 0 iff ''i'' is even. The remainder equals +1 or -1 iff ''i'' is odd.\n* Use modular congruences:\n** ''i'' 0 (mod 2) iff ''i'' is even.\n** ''i'' 1 (mod 2) iff ''i'' is odd.\n\n", "solution": "public static boolean isEven(BigInteger i){\n return i.mod(BigInteger.valueOf(2)).equals(BigInteger.ZERO);\n}"} {"title": "Evolutionary algorithm", "language": "Java 1.5+", "task": "Starting with:\n* The target string: \"METHINKS IT IS LIKE A WEASEL\".\n* An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent).\n* A fitness function that computes the 'closeness' of its argument to the target string.\n* A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated.\n* While the parent is not yet the target:\n:* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.\n:* Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others.\n:* repeat until the parent converges, (hopefully), to the target.\n\n\n;See also:\n* Wikipedia entry: Weasel algorithm.\n* Wikipedia entry: Evolutionary algorithm.\n\n\nNote: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions\n\nA cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically,\n* While the parent is not yet the target:\n:* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.\n\nNote that some of the the solutions given retain characters in the mutated string that are ''correct'' in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of \"converges\"\n\n (:* repeat until the parent converges, (hopefully), to the target.\n\nStrictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by ''not'' being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent!\n\nAs illustration of this error, the code for 8th has the following remark.\n\n Create a new string based on the TOS, '''changing randomly any characters which\n don't already match the target''':\n\n''NOTE:'' this has been changed, the 8th version is completely random now\n\nClearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters!\n\nTo ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.\n\n", "solution": "import java.util.Random;\n\npublic class EvoAlgo {\n static final String target = \"METHINKS IT IS LIKE A WEASEL\";\n static final char[] possibilities = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ \".toCharArray();\n static int C = 100; //number of spawn per generation\n static double minMutateRate = 0.09;\n static int perfectFitness = target.length();\n private static String parent;\n static Random rand = new Random();\n\n private static int fitness(String trial){\n int retVal = 0;\n for(int i = 0;i < trial.length(); i++){\n if (trial.charAt(i) == target.charAt(i)) retVal++;\n }\n return retVal;\n }\n\n private static double newMutateRate(){\n return (((double)perfectFitness - fitness(parent)) / perfectFitness * (1 - minMutateRate));\n }\n\n private static String mutate(String parent, double rate){\n String retVal = \"\";\n for(int i = 0;i < parent.length(); i++){\n retVal += (rand.nextDouble() <= rate) ?\n possibilities[rand.nextInt(possibilities.length)]:\n parent.charAt(i);\n }\n return retVal;\n }\n \n public static void main(String[] args){\n parent = mutate(target, 1);\n int iter = 0;\n while(!target.equals(parent)){\n double rate = newMutateRate();\n iter++;\n if(iter % 100 == 0){\n System.out.println(iter +\": \"+parent+ \", fitness: \"+fitness(parent)+\", rate: \"+rate);\n }\n String bestSpawn = null;\n int bestFit = 0;\n for(int i = 0; i < C; i++){\n String spawn = mutate(parent, rate);\n int fitness = fitness(spawn);\n if(fitness > bestFit){\n bestSpawn = spawn;\n bestFit = fitness;\n }\n }\n parent = bestFit > fitness(parent) ? bestSpawn : parent;\n }\n System.out.println(parent+\", \"+iter);\n }\n\n}"} {"title": "Executable library", "language": "Java", "task": "The general idea behind an executable library is to create a library \nthat when used as a library does one thing; \nbut has the ability to be run directly via command line. \nThus the API comes with a CLI in the very same source code file.\n\n'''Task detail'''\n\n* Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the [[Hailstone sequence]] for that number.\n\n* The library, when executed directly should satisfy the remaining requirements of the [[Hailstone sequence]] task:\n:: 2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1\n:: 3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.\n\n* Create a second executable to calculate the following:\n** Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 <= n < 100,000.\n\n* Explain any extra setup/run steps needed to complete the task.\n\n'''Notes:''' \n* It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed ''not'' to be present in the runtime environment.\n* Interpreters are present in the runtime environment.\n\n", "solution": "import java.util.ArrayList;\nimport java.util.List;\n\n// task 1\npublic class HailstoneSequence {\n\n public static void main(String[] args) {\n // task 2\n int n = 27;\n List sequence27 = hailstoneSequence(n);\n System.out.printf(\"Hailstone sequence for %d has a length of %d:%nhailstone(%d) = %s%n\", n, sequence27.size(), n, sequence27);\n \n // task 3\n int maxN = 0;\n int maxLength = 0;\n for ( int i = 1 ; i < 100_000 ; i++ ) {\n int seqLength = hailstoneSequence(i).size();\n if ( seqLength > maxLength ) {\n maxLength = seqLength;\n maxN = i;\n }\n }\n System.out.printf(\"Longest hailstone sequence less than 100,000: hailstone(%d).length() = %d\", maxN, maxLength);\n }\n \n public static List hailstoneSequence(long n) {\n if ( n <= 0 ) {\n throw new IllegalArgumentException(\"Must be grater than or equal to zero.\");\n }\n List sequence = new ArrayList<>();\n sequence.add(n);\n while ( n > 1 ) {\n if ( (n & 1) == 0 ) {\n n /= 2;\n }\n else {\n n = 3 * n + 1;\n }\n sequence.add(n);\n }\n return sequence;\n }\n \n}\n"} {"title": "Execute Brain****", "language": "Java", "task": "Brainf***}}\nRCBF is a set of [[Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. \n\nBelow are links to each of the versions of RCBF.\n\nAn implementation need only properly implement the following instructions:\n{| class=\"wikitable\"\n!Command\n!Description\n|-\n| style=\"text-align:center\"| > || Move the pointer to the right\n|-\n| style=\"text-align:center\"| < || Move the pointer to the left\n|-\n| style=\"text-align:center\"| + || Increment the memory cell under the pointer\n|-\n| style=\"text-align:center\"| - || Decrement the memory cell under the pointer\n|-\n| style=\"text-align:center\"| . || Output the character signified by the cell at the pointer\n|-\n| style=\"text-align:center\"| , || Input a character and store it in the cell at the pointer\n|-\n| style=\"text-align:center\"| [ || Jump past the matching ] if the cell under the pointer is 0\n|-\n| style=\"text-align:center\"| ] || Jump back to the matching [ if the cell under the pointer is nonzero\n|}\nAny cell size is allowed, EOF (End-O-File) support is optional, as is whether you have bounded or unbounded memory.\n\n", "solution": "import java.io.IOException;\n\npublic class Interpreter {\n\n public final static int MEMORY_SIZE = 65536;\n\n private final char[] memory = new char[MEMORY_SIZE];\n private int dp;\n private int ip;\n private int border;\n\n private void reset() {\n\n for (int i = 0; i < MEMORY_SIZE; i++) {\n memory[i] = 0;\n }\n ip = 0;\n dp = 0;\n }\n\n private void load(String program) {\n\n if (program.length() > MEMORY_SIZE - 2) {\n throw new RuntimeException(\"Not enough memory.\");\n }\n\n reset();\n\n for (; dp < program.length(); dp++) {\n memory[dp] = program.charAt(dp);\n }\n\n // memory[border] = 0 marks the end of instructions. dp (data pointer) cannot move lower than the\n // border into the program area.\n border = dp;\n\n dp += 1;\n }\n\n public void execute(String program) {\n\n load(program);\n char instruction = memory[ip];\n\n while (instruction != 0) {\n\n switch (instruction) {\n case '>':\n dp++;\n if (dp == MEMORY_SIZE) {\n throw new RuntimeException(\"Out of memory.\");\n }\n break;\n case '<':\n dp--;\n if (dp == border) {\n throw new RuntimeException(\"Invalid data pointer.\");\n }\n break;\n case '+':\n memory[dp]++;\n break;\n case '-':\n memory[dp]--;\n break;\n case '.':\n System.out.print(memory[dp]);\n break;\n case ',':\n try {\n // Only works for one byte characters.\n memory[dp] = (char) System.in.read();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n break;\n case '[':\n if (memory[dp] == 0) {\n skipLoop();\n }\n break;\n case ']':\n if (memory[dp] != 0) {\n loop();\n }\n break;\n default:\n throw new RuntimeException(\"Unknown instruction.\");\n }\n\n instruction = memory[++ip];\n }\n }\n\n private void skipLoop() {\n\n int loopCount = 0;\n\n while (memory[ip] != 0) {\n if (memory[ip] == '[') {\n loopCount++;\n } else if (memory[ip] == ']') {\n loopCount--;\n if (loopCount == 0) {\n return;\n }\n }\n ip++;\n }\n\n if (memory[ip] == 0) {\n throw new RuntimeException(\"Unable to find a matching ']'.\");\n }\n }\n\n private void loop() {\n\n int loopCount = 0;\n\n while (ip >= 0) {\n if (memory[ip] == ']') {\n loopCount++;\n } else if (memory[ip] == '[') {\n loopCount--;\n if (loopCount == 0) {\n return;\n }\n }\n ip--;\n }\n\n if (ip == -1) {\n throw new RuntimeException(\"Unable to find a matching '['.\");\n }\n }\n\n public static void main(String[] args) {\n\n Interpreter interpreter = new Interpreter();\n interpreter.execute(\">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+.\");\n }\n}"} {"title": "Execute Computer/Zero", "language": "Java 8", "task": "Computer/zero Assembly}}\n\n;Task:\nCreate a [[Computer/zero Assembly emulator. You may consider this webpage as a reference implementation. Output the results of the sample programs \"2+2\" and \"7*8\" found there.\n\n:* The virtual machine \"bytecode\" needs to be able to modify itself (or at least act as though it can) while the virtual machine is running, to be consistent with the reference implementation.\n:* For output, it is sufficient to have the implementation of the STP opcode return the accumulator to your actual language, and then use your standard printing routines to output it.\n\n;Bonus Points: Run all 5 sample programs at the aforementioned website and output their results.\n\n\n\n", "solution": "import static java.lang.Math.floorMod;\nimport static java.lang.Math.min;\nimport static java.util.stream.Collectors.toMap;\n\nimport java.util.AbstractMap.SimpleEntry;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport java.util.stream.Stream;\n\npublic class ComputerZero {\n\n private static final int MEM = 32;\n\n private static final int NOP = 0;\n private static final int LDA = 1;\n private static final int STA = 2;\n private static final int ADD = 3;\n private static final int SUB = 4;\n private static final int BRZ = 5;\n private static final int JMP = 6;\n private static final int STP = 7;\n\n private static final Map OPCODES = Stream.of(\n new SimpleEntry<>(\"NOP\", NOP),\n new SimpleEntry<>(\"LDA\", LDA),\n new SimpleEntry<>(\"STA\", STA),\n new SimpleEntry<>(\"ADD\", ADD),\n new SimpleEntry<>(\"SUB\", SUB),\n new SimpleEntry<>(\"BRZ\", BRZ),\n new SimpleEntry<>(\"JMP\", JMP),\n new SimpleEntry<>(\"STP\", STP))\n .collect(toMap(SimpleEntry::getKey, SimpleEntry::getValue));\n\n private static final Pattern RE_INSTRUCTION = Pattern.compile(\n \"\\\\s*\" +\n \"(?:(?