|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
public class RekursionSol extends MiniJava { public static void AusgabeMitSchleife(int n) { for (int i = 1; i <= n; i++) { System.out.print(i + ", "); } System.out.println("\nFertig"); } public static void AMR(int i, int n) { // Abbruch? if (i > n) { // System.out.println("\nFertig"); // oder hier return; } // Ausgabe System.out.print(i + ", "); // Rekursiver Aufruf AMR(i + 1, n); } public static void AusgabeMitRekursion(int n) { // Hilfsprozedur: AMR(1, n); System.out.println("\nFertig"); // oder oben } public static void AMT(int i, int n) { // Abbruch? if (i > n) { System.out.println(); return; } // Ausgabe EingerueckteAusgabe(i); // Rekursiver Aufruf AMT(i + 1, n); // Nochmal Ausgabe EingerueckteAusgabe(i); } public static void AusgabeTiefeRekursiv(int n) { // Hilfsprozedur: AMT(1, n); } public static void main(String[] args) { int n = 10; // n = 0; while (n < 1 || n > 10) { n = readInt("Bitte n (1 <= n <= 10) eingeben:"); } System.out.println("\nAusgabeMitSchleife:"); AusgabeMitSchleife(n); System.out.println("\nAusgabeMitRekursion:"); AusgabeMitRekursion(n); System.out.println("\nAusgabeTiefe:"); AusgabeTiefe(n); System.out.println("\nAusgabeTiefeRekursiv:"); AusgabeTiefeRekursiv(n); } // Gibt die Zahl mit Einrueckung aus. public static void EingerueckteAusgabe(int n) { for (int j = 1; j <= n; j++) { System.out.print(" "); } System.out.println(n + ""); } // Simuliert die mittels Rekursion zu erreichende Ausgabe. public static void AusgabeTiefe(int n) { // Hin for (int i = 1; i <= n; i++) { EingerueckteAusgabe(i); } System.out.println(); // Zurueck for (int i = n; i >= 1; i--) { EingerueckteAusgabe(i); } System.out.println(); } } |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
public class Pi { // Kompakt public static double piRec(long n) { if (0 == n) { return 4.0; } else { // +/-4 == (4-8*(n%2)) return (4 - 8 * (n % 2)) / (2 * n + 1.0) + piRec(n - 1); } } // Alternative public static double piSwitchRec(long n) { if (0 == n % 2) return piPosRec(n); else return piNegRec(n); } public static double piPosRec(long n) { if (0 == n) return 4.0; else return 4.0 / (2 * n + 1) + piNegRec(n - 1); } public static double piNegRec(long n) { if (0 == n) return 4.0; // shouldn't happen else return -4.0 / (2 * n + 1) + piPosRec(n - 1); } // Iterative Loesung public static double piIt(long n) { double pi = 0.0; double f = 4.0; for (long i = n; i >= 0; i--) { pi += f / (2 * i + 1); f = -f; } return pi; } public static void main(String[] args) { System.out.println(piRec(1000)); System.out.println(piSwitchRec(1000)); System.out.println(piIt(1000)); } } |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
public class Wurzel { // Iterative Version public static double heronIt(double a, double epsilon) { double x = a; while (Math.abs(x * x - a) > epsilon) { x = (x + a / x) / 2.0; } return x; } // Hilfsfunktion fuer rekursive Loesung private static double heronRecHelper(double x, double a, double epsilon) { if (Math.abs(x * x - a) >= epsilon) { return heronRecHelper((x + a / x) / 2.0, a, epsilon); } return x; } // Rekursive Variante public static double heronRec(double a, double epsilon) { return heronRecHelper(a, a, epsilon); } // Kleines Testprogramm public static void main(String[] args) { System.out.println(heronIt(2.0, 0.0001)); System.out.println(heronRec(2.0, 0.0001)); } } |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
@SuppressWarnings("serial") public class MazeSolution extends Maze { static int[][] maze; static int goalX, goalY; public static void main(String[] args) { int width = 20; int height = 20; goalX = width - 1; goalY = height - 2; maze = generateMaze(width, height); walk(1, 0, 1); } public static boolean wall(int x, int y) { return maze[x][y] == WALL; } public static void walk(int x, int y, int direction) { maze[x][y] = PLAYER; draw(maze); maze[x][y] = OLD_PATH_DONE; if (x == goalX && y == goalY) { return; } if (x == 1 && y == 0 && direction != 1) { System.out.println("There is no way out :("); return; } // Do we have a wall on the right hand side? if (direction == 0 && wall(x - 1, y) || direction == 1 && wall(x, y + 1) || direction == 2 && wall(x + 1, y) || direction == 3 && wall(x, y - 1)) { // Is there an obstacle directly in front of us? if (direction == 0 && wall(x, y + 1) || direction == 1 && wall(x + 1, y) || direction == 2 && wall(x, y - 1) || direction == 3 && wall(x - 1, y)) { System.out.println("There is an obstacle, turning to " + ((direction + 1) % 4)); // We can turn counterclockwise, having the obstacle on our // right-hand side. walk(x, y, ((direction + 1) % 4)); } else { // We walk straigt on switch (direction) { case 0: walk(x, y + 1, direction); break; case 1: walk(x + 1, y, direction); break; case 2: walk(x, y - 1, direction); break; case 3: default: walk(x - 1, y, direction); } } } else { // There is no wall on the right side, so we walk to the right side // and turn until we have a wall on the right side switch (direction) { case 0: walk(x - 1, y, (direction + 3) % 4); break; case 1: walk(x, y + 1, (direction + 3) % 4); break; case 2: walk(x + 1, y, (direction + 3) % 4); break; case 3: default: walk(x, y - 1, (direction + 3) % 4); } } } } |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 |
import java.awt.*; import java.util.Random; import javax.swing.JFrame; import javax.swing.JPanel; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.*; import java.io.File; @SuppressWarnings("serial") public class Maze extends JPanel { public static final int FREE = 0; public static final int WALL = 1; public static final int PLAYER = 2; public static final int OLD_PATH_ACTIVE = 3; public static final int OLD_PATH_DONE = 4; public static final int PENGUIN = 5; private class Field extends JPanel { Point p; int x, y; public Field(int x, int y) { this.x = x; this.y = y; p = getLocation(); } public void paint(Graphics g) { super.paint(g); if (spielFeld[x][y] == WALL) { GradientPaint gradient = new GradientPaint(10, 50, Color.GRAY, getWidth(), 0, Color.DARK_GRAY); ((Graphics2D) g).setPaint(gradient); } else { GradientPaint gradient = new GradientPaint(0, 50, Color.WHITE, getWidth(), 0, Color.GRAY); ((Graphics2D) g).setPaint(gradient); } g.fillRect(p.getLocation().x, p.getLocation().y, getWidth() * 2, getHeight()); switch (spielFeld[x][y]) { case PLAYER: paintSymbol(g, Color.RED); break; case OLD_PATH_ACTIVE: paintSymbol(g, Color.BLUE); break; case OLD_PATH_DONE: paintSymbol(g, Color.GRAY); break; case PENGUIN: drawPeng(g); break; default: break; } } private void paintSymbol(Graphics g, Color c) { GradientPaint gradient = new GradientPaint(15, 0, c, getWidth(), 0, Color.LIGHT_GRAY); ((Graphics2D) g).setPaint(gradient); ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.fillOval((int) (getWidth() * 0.3), (int) (getHeight() * 0.3), (int) (getWidth() * 0.5), (int) (getHeight() * 0.5)); } private void drawPeng(Graphics g) { if (peng == null) { paintSymbol(g, Color.YELLOW); return; } ((Graphics2D) g).drawImage(peng, 0, 0, getWidth(), getHeight(), 0, 0, peng.getWidth(null), peng.getHeight(null), null); } } private int[][] spielFeld; private static Maze myMaze; private JPanel fieldPanel = new JPanel(); private JFrame myFrame; public Maze() { File f = new File("tux.png"); if (f.exists() && !f.isDirectory()) { peng = Toolkit.getDefaultToolkit().getImage(f.getAbsolutePath()); } /* Intentionally left blank */ } private Maze(int[][] feld) { this(); spielFeld = new int[feld.length][feld[0].length]; Field[][] field = new Field[spielFeld.length][spielFeld[0].length]; for (int y = 0; y < spielFeld[0].length; y++) { for (int x = 0; x < spielFeld.length; x++) { field[x][y] = new Field(x, y); fieldPanel.add(field[x][y]); spielFeld[x][y] = feld[x][y]; } } myFrame = new JFrame("A-Maze-Ing"); fieldPanel.setLayout(new GridLayout(spielFeld[0].length, spielFeld.length)); myFrame.getContentPane().add(fieldPanel); myFrame.setSize(IWH * 10, IWH * 10 * (spielFeld[0].length) / (spielFeld.length)); myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); myFrame.addComponentListener(new ComponentHandler()); myFrame.addKeyListener(new KeyHandler()); myFrame.setVisible(true); update(feld); } private void update(int[][] feld) { for (int x = 0; x < spielFeld.length; x++) for (int y = 0; y < spielFeld[0].length; y++) spielFeld[x][y] = feld[x][y]; fieldPanel.repaint(); } public static void draw(int[][] maze) { if (myMaze == null) { myMaze = new Maze(maze); } while (myMaze.pause) { try { Thread.sleep(50); } catch (InterruptedException ie) { } } myMaze.update(maze); try { Thread.sleep(wannaSleep); } catch (InterruptedException ie) { /* Intentionally left blank */ } } private class ComponentHandler extends ComponentAdapter { @Override public void componentResized(ComponentEvent e) { repaint(); } } private class KeyHandler extends KeyAdapter { @Override public void keyPressed(KeyEvent ke) { switch (ke.getKeyCode()) { case KeyEvent.VK_ESCAPE: myMaze.myFrame.dispose(); System.exit(0); break; case KeyEvent.VK_PLUS: wannaSleep -= 50; wannaSleep = wannaSleep < 0 ? 0 : wannaSleep; System.out.println("delay=" + wannaSleep); break; case KeyEvent.VK_MINUS: wannaSleep += 50; System.out.println("delay=" + wannaSleep); break; case KeyEvent.VK_B: System.out.println("break"); pause = true; break; case KeyEvent.VK_C: System.out.println("continue"); pause = false; break; default: break; } } } private Image peng; private static long wannaSleep = 100; private static final int IWH = 40; private boolean pause = false; public static int[][] generateMaze(int width, int height) { return generateMaze(width, height, false, false); } public static int[][] generatePenguinMaze(int width, int height) { return generateMaze(width, height, true, false); } public static int[][] generateStandardMaze(int width, int height) { return generateMaze(width, height, false, true); } public static int[][] generateStandardPenguinMaze(int width, int height) { return generateMaze(width, height, true, true); } private static int[][] generateMaze(int width, int height, boolean penguins, boolean standard) { width = Math.max(width, 3); height = Math.max(height, 3); int[][] maze = new int[width][height]; // Borders: // if(!penguins){ for (int i = 0; i < width; i++) { maze[i][0] = WALL; maze[i][height - 1] = WALL; } for (int i = 0; i < height; i++) { maze[0][i] = WALL; maze[width - 1][i] = WALL; } // } // Random obstacles: Random random = new Random(); if (standard) { random.setSeed(0); } for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { if (random.nextInt(4) == 0) { maze[x][y] = WALL; } } } if (penguins) { // Random penguins: for (int y = 1; y < height - 1; y++) { for (int x = 1; x < width - 1; x++) { if (random.nextInt(16) == 0) { maze[x][y] = PENGUIN; // if(WALL != maze[x][y]) } } } } if (!penguins) { // Exit maze[width - 1][height - 2] = FREE; maze[width - 2][height - 2] = FREE; } // Entrance maze[1][0] = FREE; maze[1][1] = FREE; return maze; } } |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
@SuppressWarnings("serial") public class FindPingu extends Maze { static int[][] maze; public static void main(String[] args) { int width = MiniJava.read("Breite des Labyrinths?"); int height = MiniJava.read("H枚he des Labyrinths?");; maze = generateStandardPenguinMaze(width, height); int maxDistance = MiniJava.read("Wie weit trauen Sie sich maximal weg vom Startpunkt?"); if(width < 3 || height < 3 || maxDistance < 1) { MiniJava.write("Fehlerhafte Eingabe!"); return; } int penguins = walk(1, 0, maxDistance); System.out.println("Gerettete Pinguine: " + penguins); } /** * Testet, ob sich eine Wand an den gegebenen Koordinaten befindet */ public static boolean wall(int x, int y) { return maze[x][y] == WALL; } /** * Testet, ob sich an den gegebenen Koordinaten keine Wand befindet; die Koordinaten * k枚nnen au脽erhalb des Labyrinths liegen. */ public static boolean noWall(int x, int y) { if (x < 0 || y < 0 || x >= maze.length || y >= maze[0].length) return false; return maze[x][y] != WALL; } public static int walk(int x, int y, int maxDistance) { if(maxDistance < 0) return 0; // Sind wir in Begriff, aus dem Labyrinth zu laufen? if (x < 0 || y < 0 || x >= maze.length || y >= maze[0].length) return 0; // Sind wir in Begriff, uns auf ein wandfreies Feld zu wagen? if (noWall(x - 1, y - 1) && noWall(x - 1, y) && noWall(x - 1, y + 1) && noWall(x, y - 1) && noWall(x, y) && noWall(x, y + 1) && noWall(x + 1, y - 1) && noWall(x + 1, y) && noWall(x + 1, y + 1)) return 0; // Sind wir in Begriff, in eine Wand oder auf Feld zu laufen, auf dem wir schon waren? if (maze[x][y] == WALL || maze[x][y] == OLD_PATH_ACTIVE || maze[x][y] == OLD_PATH_DONE) { return 0; } // Wir betreten das Feld maze[x][y] = PLAYER; draw(maze); maze[x][y] = OLD_PATH_ACTIVE; int penguins = maze[x][y] == PENGUIN ? 1 : 0; penguins += walk(x + 1, y, maxDistance - 1); // An diesem Punkt sind wir aus der Rekursion zur眉ckgekommen. Wir betreten das Feld // daher erneut. maze[x][y] = PLAYER; draw(maze); maze[x][y] = OLD_PATH_ACTIVE; penguins += walk(x, y + 1, maxDistance - 1); // An diesem Punkt sind wir aus der Rekursion zur眉ckgekommen. Wir betreten das Feld // daher erneut. maze[x][y] = PLAYER; draw(maze); maze[x][y] = OLD_PATH_ACTIVE; penguins += walk(x - 1, y, maxDistance - 1); // An diesem Punkt sind wir aus der Rekursion zur眉ckgekommen. Wir betreten das Feld // daher erneut. maze[x][y] = PLAYER; draw(maze); maze[x][y] = OLD_PATH_ACTIVE; penguins += walk(x, y - 1, maxDistance - 1); // An diesem Punkt sind wir aus der Rekursion zur眉ckgekommen. Wir betreten das Feld // daher erneut. maze[x][y] = PLAYER; draw(maze); // Such in alle Richtungen abgeschlossen; mit diesem Feld sind wir fertig! maze[x][y] = OLD_PATH_DONE; return penguins; } } |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 |
public class Ponynome extends MiniJava { public static int[] quadraticFormula(double[] coefficients) { if (coefficients.length != 3) return new int[0]; double root = coefficients[1] * coefficients[1] - 4 * coefficients[0] * coefficients[2]; int[] result; if (root == 0) { result = new int[1]; result[0] = (int) Math.round((-coefficients[1] + Math.sqrt(root)) / (2 * coefficients[0])); } else if (root > 0) { result = new int[2]; result[0] = (int) Math.round((-coefficients[1] + Math.sqrt(root)) / (2 * coefficients[0])); result[1] = (int) Math.round((-coefficients[1] - Math.sqrt(root)) / (2 * coefficients[0])); } else { result = new int[0]; } return result; } public static double[] hornerSchema(double[] coefficients, int x0) { if (coefficients.length != 4) return new double[0]; double[] result = new double[3]; result[0] = coefficients[0]; result[1] = result[0] * x0 + coefficients[1]; result[2] = result[1] * x0 + coefficients[2]; return result; } public static double calculateY(double[] coefficients, int x) { if (coefficients.length != 4) return 0; return coefficients[0] * x * x * x + coefficients[1] * x * x + coefficients[2] * x + coefficients[3]; } public static int[] findIntervalRecursive(double[] coefficients, int a, int b, int faktor) { if (coefficients.length != 4) return new int[0]; double valueA = calculateY(coefficients, a); double valueB = calculateY(coefficients, b); // wenn das resultat der Multiplkation negativ ist --> unterschiedliche // Vorzeichen if (valueA * valueB <= 0) { int[] result = new int[2]; result[0] = a; result[0] = b; return result; } return findIntervalRecursive(coefficients, a * faktor, b * faktor, faktor); } public static int findRootRecursive(double[] coefficients, int a, int b) { int m = (a + b) / 2; if (m == a) throw new IllegalArgumentException("Uebergebenes Polynom ist falsch..."); double valueA = calculateY(coefficients, a); double valueB = calculateY(coefficients, b); double valueM = calculateY(coefficients, m); if (Math.abs(valueM) < 0.00001) return m; else if (valueA == 0) return a; else if (valueB == 0) return b; if (valueA * valueM < 0) { return findRootRecursive(coefficients, a, m); } return findRootRecursive(coefficients, m, b); } public static String quadraticSolutionsToString(int[] roots) { String output = ""; if (roots.length == 1) output += "\n" + "x1/2 = " + roots[0]; else for (int i = 1; i <= roots.length; i++) output += "\n" + "x" + i + " = " + roots[i - 1]; return output; } public static void main(String[] args) { double[] coeffs = new double[4]; coeffs[0] = readDouble("Bitte geben Sie den Koeffizient von x^3 ein: "); coeffs[1] = readDouble("Bitte geben Sie den Koeffizient von x^2 ein: "); coeffs[2] = readDouble("Bitte geben Sie den Koeffizient von x^1 ein: "); coeffs[3] = readDouble("Bitte geben Sie den Koeffizient von x^0 ein: "); // Wir unterscheiden nach Grad des Polynoms if (coeffs[0] == 0.0 && coeffs[1] == 0.0) { // Suchen von Nullstellen einer linearen Funktion double solution = -coeffs[3] / coeffs[2]; write("Es gibt eine L枚sung x = " + solution + "."); } else if (coeffs[0] == 0.0) { // Suchen von Nullstellen einer quadratischen Funktion double[] parabola = new double[3]; for (int i = 0; i < parabola.length; i++) { parabola[i] = coeffs[i + 1]; } int[] roots = quadraticFormula(parabola); String output = "Es gibt insgesamt " + roots.length + " L枚sungen.\n"; output += quadraticSolutionsToString(roots); write(output); } else { // Suchen von Nullstellen einer Funktion dritten Grades int[] intervall = findIntervalRecursive(coeffs, -2, 2, 10); int x2 = findRootRecursive(coeffs, intervall[0], intervall[1]); double[] reducedPonynom = hornerSchema(coeffs, x2); int[] roots = quadraticFormula(reducedPonynom); int solutions = 1 + roots.length; String output = "Es gibt insgesamt " + solutions + " L枚sungen.\n"; output += quadraticSolutionsToString(roots); output += "\nx2 = " + x2; write(output); } } } |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 |
public class BaseBlase extends MiniJava { public static int[] rev(int[] array) { int[] result = new int[array.length]; for (int i = 0; i < result.length; i++) { result[i] = array[result.length - 1 - i]; } return result; } public static char digitToChar(int digit) { if (digit >= 10) return (char) ('A' + digit - 10); else return (char) ('0' + digit); } public static String toString(int[] array) { StringBuilder sB = new StringBuilder(); for (int i = 0; i < array.length; i++) { int nextDigit = array[array.length - 1 - i]; sB.append(digitToChar(nextDigit)); } return sB.toString(); } public static int[] mulDigit(int[] a, int digit, int shift, int base) { // System.out.print(toString(a) + " * 10^" + shift + " * " + digit + " = "); // Keine langen 0er erzeugen if (digit == 0) return new int[] {0}; // L盲nge des Ergebnis-Arrays berechnen int carry = 0; for (int i = 0; i < a.length; i++) { int digitSum = a[i] * digit + carry; carry = digitSum / base; } // Multiplikation durchf眉hren int diff = carry > 0 ? 1 : 0; carry = 0; int[] result = new int[a.length + diff + shift]; for (int i = 0; i < a.length + diff; i++) { int digitSum = at(a, i) * digit + carry; carry = digitSum / base; result[i + shift] = digitSum % base; } // System.out.println(toString(result)); return result; } public static int columnsLatex(int[] a, int[] b) { // Eine Zeile in Latex muss (maximal) die beiden Zahlen, ein + und das // *-Zeichen enthalten. return a.length + b.length + 2; } /** * Eine Zeile der Latex-Tabelle ausgeben * * @param leading Zeichen in der ersten Spalte * @param number Die Zahl der Zeile * @param columns Gesamtzahl an Spalten in der Latex-Tabelle */ public static void printLineLatex(char leading, int[] number, int columns) { System.out.print(leading + "&"); for (int j = 0; j < columns - number.length - 2; j++) { System.out.print("&"); } for (int j = number.length - 1; j >= 0; j--) { System.out.print("& "); System.out.print(digitToChar(number[j])); } System.out.println("\\\\"); } public static int[] mul(int[] a, int[] b, int base) { int[][] lines = new int[b.length][]; // Wir multiplizieren Zeile f眉r Zeile... for (int i = 0; i < b.length; i++) { lines[i] = mulDigit(a, at(b, i), i, base); printLineLatex('+', lines[i], columnsLatex(a, b)); // System.out.println("Lines[" + i + "] = " + toString(lines[i])); } // ... und addieren die Ergebnisse auf int[] result = lines[0]; for (int i = 1; i < lines.length; i++) { result = add(result, lines[i], base); } return result; } public static int[] add(int[] a, int[] b, int base) { // System.out.print(toString(a) + " + " + toString(b) + " = "); // Zun盲chst berechnen wir die L盲nge des Ergebnis-Arrays. int length = Math.max(a.length, b.length); int carry = 0; for (int i = 0; i < length; i++) { int digitSum = at(a, i) + at(b, i) + carry; carry = digitSum / base; } // Dann f眉hren wir die eigentliche Addition durch. int[] result = new int[length + carry]; carry = 0; for (int i = 0; i < result.length; i++) { int digitSum = at(a, i) + at(b, i) + carry; carry = digitSum / base; result[i] = digitSum % base; } // System.out.println(toString(result)); return result; } public static int at(int[] a, int i) { if (i >= a.length) return 0; else return a[i]; } public static int[] readNumber() { String input = readString("Bitte geben Sie eine Zahl ein."); int[] number = new int[input.length()]; for (int i = 0; i < number.length; i++) { char next = input.charAt(input.length() - 1 - i); if (next >= 'A' && next <= 'Z') number[i] = next - 'A' + 10; else if (next >= '0' && next <= '9') number[i] = next - '0'; else number[i] = -1; } return number; } public static boolean testNumber(int[] number, int base) { for (int i = 0; i < number.length; i++) { if (number[i] < 0 || number[i] >= base) return false; } return true; } public static void main(String[] args) { // int[] a = rev(new int[] { 1, 2, 3, 9, 8 }); // int[] a = rev(new int[] { 11, 15, 13, 1, 5, 9, 9, 1, 3, 14, 15, 1, 2, 3 }); // int[] a = rev(new int[] { 8, 8, 5 }); // int[] b = rev(new int[]{ 1, 8, 9 }); // int[] b = rev(new int[]{ 12, 14, 6, 7, 8, 11, 10, 9, 10, 11, 12 }); // int[] a = rev(new int[] {1, 0, 1, 1}); // int[] b = rev(new int[] {1, 1, 1, 0, 0, 0}); // int[] r = add(a, b, 16); int base = read("Bitte geben Sie die Basis zwischen 2 und 35 ein."); if (base < 2 || base > 35) { write("Ne, mit dieser Basis machen wir hier nicht weiter."); return; } int[] a = readNumber(); if (!testNumber(a, base)) { write("Diese Nummber ist fehlerhaft!"); return; } int[] b = readNumber(); if (!testNumber(a, base)) { write("脛h ne, so geht das nicht!"); return; } // Die Anzahl an 'c's muss der Anzahl Spalten entsprechen. int columns = columnsLatex(a, b); System.out.print("\\begin{tabular}{"); for (int i = 0; i < columns; i++) { System.out.print('c'); } System.out.println("}"); // Ausgabe der Kopfzeile System.out.print("&"); for (int i = a.length - 1; i >= 0; i--) { System.out.print(digitToChar(a[i])); System.out.print(" & "); } System.out.print(" $\\ast$ "); for (int i = b.length - 1; i >= 0; i--) { System.out.print(" & "); System.out.print(digitToChar(b[i])); } System.out.println("\\\\"); System.out.println("\\hline"); // Berechnung des Ergebnisses int[] result = mul(a, b, base); // Ergebniszeile in Latex System.out.println("\\hline"); printLineLatex('=', result, columns); System.out.println("\\end{tabular}"); String resultString = toString(result); write("Result: " + resultString); } } |