Algorithmen und Programmierung II
Übungsblatt 7 - Musterlösung
Aufgabe 1
class DVListe {
final Element anker = new Element();
void einfuegenNach(Element e, int wert) {
Element neu = new Element(wert, e, e.nachf);
e.nachf.vorg = neu;
e.nachf = neu;
}
void loeschen(Element e) {
if (e == anker) return;
e.vorg.nachf = e.nachf;
e.nachf.vorg = e.vorg;
}
}
class Element {
int wert;
Element vorg, nachf;
Element(int wert, Element vorg, Element nachf) {
this.wert = wert;
this.vorg = vorg;
this.nachf = nachf;
}
Element() {
vorg = this;
nachf = this;
}
}
Aufgabe 2
static void replace(char[] text, char[] a, char[] b) {
outer: for (int i = 0; i <= text.length-a.length; i++) {
for (int j = 0; j < a.length; j++) {
if (text[i+j] != a[j])
continue outer;
}
for (int j = 0; j < b.length; j++)
text[i+j] = b[j];
int diff = a.length - b.length;
if (diff > 0) {
for (int j = i+a.length; j < text.length; j++)
text[j-diff] = text[j];
for (int j = text.length-diff; j < text.length; j++)
text[j] = ' ';
}
return;
}
}
Aufgabe 3
static char[] matrixCode(char[] text, int width, boolean encode) {
char[] matrix = new char[text.length];
int col = 0;
int row = 0;
int inc = 1;
int c = 0;
while (c < text.length) {
if (encode) matrix[c++] = text[row*width + col];
else matrix[row*width + col] = text[c++];
row += inc;
if (row*width + col >= text.length || row < 0) { inc = -inc;
col++;
row += inc;
if (row*width + col >= text.length)
row--;
}
}
return matrix;
}
Gesuchter Text (Spaltenanzahl 11):
Deciphering
is, in my opinion, one of the most fascinating of arts, and I fear I
have wasted upon it more time than it deserves. (Charles Babbage)