Compare commits

..

No commits in common. "0f1b426f9475ab46761457ba81de1be0f7109b9a" and "5c13f8d4cdcccf7c79106cf6f8266d7e42e5863f" have entirely different histories.

8 changed files with 57 additions and 217 deletions

View File

@ -88,8 +88,4 @@ parts:
- command: 'algorithm-stacks-next-greater-element' - command: 'algorithm-stacks-next-greater-element'
description: 'Seminarblatt Woche 4, Aufgabe 1' description: 'Seminarblatt Woche 4, Aufgabe 1'
inputs: inputs:
L: [4, 6, 3, 16] L: [4, 2, 1, 100, 6, 3, 16]
- command: 'algorithm-stacks-next-greater-element'
description: 'Seminarblatt Woche 4, Aufgabe 1 mit anderen Daten'
inputs:
L: [20, 10, 10, 2, 1, 5, 30, 3, 16]

View File

@ -27,32 +27,32 @@ Outputs: Liste von Paaren von Elementen und ihrem nächsten größeren Element
*/ */
func NextGreaterElement(L []int) [][2]int { func NextGreaterElement(L []int) [][2]int {
clearOutput() clearOutput()
if len(L) == 0 {
return output()
}
S := stacks.CREATE() S := stacks.CREATE()
S.INIT()
for i := 0; i < len(L); i++ { for i := 0; i < len(L); i++ {
logging.Debug("Stack S | %v", S)
logging.Debug("Nächstes List-Element L[%v] = %v betrachten", i, L[i]) logging.Debug("Nächstes List-Element L[%v] = %v betrachten", i, L[i])
nextElement := L[i] nextElement := L[i]
logging.Debug("Alle top Elemente vom Stack, die < nextElement sind, mit L[i] paaren") logging.Debug("Alle top Elemente vom Stack, die < nextElement sind, mit L[i] paaren")
// Führe aus, bis top Element >= nextElement oder Stack leer ist. // Führe aus, bis top Element >= nextElement oder Stack leer ist.
for !S.EMPTY() { // ACHTUNG: schreibe 'while' im Pseudocode, denn dies ist eine while-Schleife in golang // Führe aus, bis top Element >= nextElement oder Stack leer ist.
logging.Debug("Stack S | %v", S)
for !S.EMPTY() { // ACHTUNG: dies ist eine while-Schleife in golang
element := S.TOP() element := S.TOP()
S.POP()
metrics.AddMovesCost()
logging.Debug("Stack S | %v; (popped) Top-Element = %v", S, element)
// falls element < next Element, zum Output hinzufügen
if element < nextElement { if element < nextElement {
logging.Debug("Stack S | %v; top Element > nextElement; ==> pop und Paar zum Output hinzufügen", S)
// falls top Element < next Element, zum Output hinzufügen und vom Stack
addToOutput(element, nextElement) addToOutput(element, nextElement)
S.POP() // sonst Element auf Stack zurücklegen und Schleife abbrechen.
metrics.AddMovesCost()
logging.Debug("Stack S | %v", S)
} else if element > nextElement {
// falls top Element > next Element, auf Stack lassen und Schleife abbrechen.
break
} else { } else {
// falls top Element == next Element, vom Stack entfernen und Schleife abbrechen. logging.Debug("Stack-Element >= nextElement ==> zurücklegen")
S.POP() S.PUSH(element)
metrics.AddMovesCost() metrics.AddMovesCost()
break break
} }
@ -60,21 +60,19 @@ func NextGreaterElement(L []int) [][2]int {
logging.Debug("L[%v] auf Stack legen", i) logging.Debug("L[%v] auf Stack legen", i)
S.PUSH(nextElement) S.PUSH(nextElement)
logging.Debug("Stack S | %v", S)
metrics.AddMovesCost() metrics.AddMovesCost()
} }
logging.Debug("Stack S | %v", S)
// was übrig bleibt hat kein größeres Element // was übrig bleibt hat kein größeres Element
logging.Debug("Alles übrige auf Stack hat kein nächstes größeres Element") logging.Debug("Alles übrige auf Stack hat kein nächstes größeres Element")
for !S.EMPTY() { // ACHTUNG: schreibe 'while' im Pseudocode, denn dies ist eine while-Schleife in golang for !S.EMPTY() { // ACHTUNG: dies ist eine while-Schleife in golang
logging.Debug("Stack S | %v", S) logging.Debug("Stack S | %v", S)
element := S.TOP() element := S.TOP()
S.POP() S.POP()
metrics.AddMovesCost() metrics.AddMovesCost()
addToOutput(element, -1) addToOutput(element, -1)
} }
logging.Debug("Stack S | %v", S) logging.Debug("Stack S | %v", S)
return output() return output()

View File

@ -34,7 +34,7 @@ func postChecks(L []int, pairs [][2]int, _ ...interface{}) error {
* ---------------------------------------------------------------- */ * ---------------------------------------------------------------- */
func FancyNextGreaterElement(input_L []int) ([][2]int, error) { func FancyNextGreaterElement(input_L []int) ([][2]int, error) {
var name = "Next Greater Element" var name = "Binärsuchalgorithmus"
var inputs = map[string]interface{}{ var inputs = map[string]interface{}{
"L": input_L, "L": input_L,
} }

View File

@ -1,81 +0,0 @@
package queues
/* ---------------------------------------------------------------- *
* IMPORTS
* ---------------------------------------------------------------- */
import (
"fmt"
"strings"
)
/* ---------------------------------------------------------------- *
* GLOBAL VARIABLES/CONSTANTS
* ---------------------------------------------------------------- */
//
/* ---------------------------------------------------------------- *
* TYPE
* ---------------------------------------------------------------- */
type QueueInt struct {
values *[]int
}
/* ---------------------------------------------------------------- *
* METHODS stacks
* ---------------------------------------------------------------- */
func CREATE() QueueInt {
return QueueInt{}
}
func (S *QueueInt) INIT() {
S.values = &[]int{}
}
func (S QueueInt) Length() int {
if S.values == nil {
return 0
}
return len(*S.values)
}
func (S QueueInt) String() string {
if S.EMPTY() {
return "-"
}
values := []string{}
n := S.Length()
for i := n - 1; i >= 0; i-- {
value := (*S.values)[i]
values = append(values, fmt.Sprintf("%v", value))
}
return fmt.Sprintf(strings.Join(values, " -> "))
}
func (S QueueInt) EMPTY() bool {
return S.Length() == 0
}
func (S *QueueInt) ENQUEUE(x int) {
if S.values == nil {
panic("Queue not initialised!")
}
*S.values = append(*S.values, x)
}
func (S *QueueInt) FRONT() int {
if S.EMPTY() {
panic("Cannot read from empty queue!")
}
return (*S.values)[0]
}
func (S *QueueInt) DEQUEUE() {
if S.EMPTY() {
panic("Cannot remove from empty queue!")
}
*S.values = (*S.values)[1:]
}

View File

@ -20,7 +20,7 @@ import (
* ---------------------------------------------------------------- */ * ---------------------------------------------------------------- */
type StackInt struct { type StackInt struct {
values *[]int values []int
} }
/* ---------------------------------------------------------------- * /* ---------------------------------------------------------------- *
@ -28,54 +28,45 @@ type StackInt struct {
* ---------------------------------------------------------------- */ * ---------------------------------------------------------------- */
func CREATE() StackInt { func CREATE() StackInt {
return StackInt{} return StackInt{
values: []int{},
}
} }
func (S *StackInt) INIT() { func (S *StackInt) INIT() StackInt {
S.values = &[]int{} return StackInt{
} values: []int{},
func (S StackInt) Length() int {
if S.values == nil {
return 0
} }
return len(*S.values)
}
func (S StackInt) String() string {
if S.EMPTY() {
return "-"
}
values := []string{}
for _, value := range *S.values {
values = append(values, fmt.Sprintf("%v", value))
}
return fmt.Sprintf(strings.Join(values, ", "))
} }
func (S StackInt) EMPTY() bool { func (S StackInt) EMPTY() bool {
return S.Length() == 0 return len(S.values) == 0
} }
func (S *StackInt) PUSH(x int) { func (S *StackInt) PUSH(x int) {
if S.values == nil { S.values = append(S.values, x)
panic("Stack not initialised!")
}
*S.values = append(*S.values, x)
} }
func (S *StackInt) TOP() int { func (S *StackInt) TOP() int {
if S.EMPTY() { if S.EMPTY() {
panic("Cannot read from empty stack!") panic("Cannot pop from empty stack!")
} }
n := S.Length() return S.values[len(S.values)-1]
return (*S.values)[n-1]
} }
func (S *StackInt) POP() { func (S *StackInt) POP() int {
if S.EMPTY() { x := S.TOP()
panic("Cannot remove from empty stack!") S.values = S.values[:(len(S.values) - 1)]
} return x
n := S.Length() }
*S.values = (*S.values)[:(n - 1)]
func (S StackInt) String() string {
if len(S.values) == 0 {
return "-"
}
values := []string{}
for _, value := range S.values {
values = append(values, fmt.Sprintf("%v", value))
}
return fmt.Sprintf(strings.Join(values, ", "))
} }

View File

@ -46,7 +46,6 @@ def NextGreaterElement(L: List[int]) -> List[Tuple[int,int]]:
S.INIT(); S.INIT();
for i in range(len(L)): for i in range(len(L)):
logDebug('Stack S | {S}'.format(S=S));
logDebug('Nächstes List-Element L[{i}] = {el} betrachten'.format(i=i, el=L[i])); logDebug('Nächstes List-Element L[{i}] = {el} betrachten'.format(i=i, el=L[i]));
nextElement = L[i]; nextElement = L[i];
@ -55,29 +54,25 @@ def NextGreaterElement(L: List[int]) -> List[Tuple[int,int]]:
logDebug('Stack S | {S}'.format(S=S)); logDebug('Stack S | {S}'.format(S=S));
while not S.EMPTY(): while not S.EMPTY():
element = S.TOP(); element = S.TOP();
S.POP();
AddMovesCost();
logDebug('Stack S | {S}; (popped) Top-Element = {el}'.format(S=S, el=element))
# falls element < next Element, zum Output hinzufügen # falls element < next Element, zum Output hinzufügen
if element < nextElement: if element < nextElement:
logDebug('Stack S | {S}; top Element > nextElement; ==> pop und Paar zum Output hinzufügen'.format(S=S))
addToOutput(element, nextElement); addToOutput(element, nextElement);
S.POP(); # sonst Element auf Stack zurücklegen und Schleife abbrechen.
AddMovesCost();
logDebug('Stack S | {S}'.format(S=S));
# falls top Element > next Element, auf Stack lassen und Schleife abbrechen.
elif element > nextElement:
break
# falls top Element == next Element, vom Stack entfernen und Schleife abbrechen.
else: else:
S.POP() logDebug('Stack element >= nextElement ==> zurücklegen')
AddMovesCost() S.PUSH(element);
break AddMovesCost();
break;
logDebug('Stack S | {S}'.format(S=S)); logDebug('Stack S | {S}'.format(S=S));
logDebug('L[{i}] auf Stack legen'.format(i=i)); logDebug('L[{i}] auf Stack legen'.format(i=i));
S.PUSH(nextElement); S.PUSH(nextElement);
logDebug('Stack S | {S}'.format(S=S));
AddMovesCost(); AddMovesCost();
logDebug('Stack S | {S}'.format(S=S));
# was übrig bleibt hat kein größeres Element # was übrig bleibt hat kein größeres Element
logDebug('Alles übrige auf Stack hat kein nächstes größeres Element') logDebug('Alles übrige auf Stack hat kein nächstes größeres Element')
while not S.EMPTY(): while not S.EMPTY():

View File

@ -1,52 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# IMPORTS
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
from local.typing import *;
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# GLOBAL VARIABLES/CONSTANTS
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# CLASS Queue
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class Queue(object):
_initialised: bool;
values: List[int];
def __init__(self):
self._initialised = False;
def INIT(self):
self.values = [];
self._initialised = True;
def EMPTY(self) -> bool:
return not self._initialised or len(self.values) == 0;
def ENQUEUE(self, x: int):
if not self._initialised:
raise Exception('Queue not initialised!')
self.values.append(x);
def FRONT(self) -> int:
if self.EMPTY():
raise Exception('Cannot read from empty queue!')
return self.values[0];
def DEQUEUE(self) -> int:
if self.EMPTY():
raise Exception('Cannot remove from empty queue!')
self.values = self.values[1:];
def __str__(self) -> str:
if len(self.values) == 0:
return '-';
return ', '.join([str(x) for x in self.values]);

View File

@ -18,33 +18,26 @@ from local.typing import *;
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class Stack(object): class Stack(object):
_initialised: bool;
values: List[int]; values: List[int];
def __init__(self):
self._initialised = False;
def INIT(self): def INIT(self):
self.values = []; self.values = [];
self._initialised = True;
def EMPTY(self) -> bool: def EMPTY(self) -> bool:
return not self._initialised or len(self.values) == 0; return len(self.values) == 0;
def PUSH(self, x: int): def PUSH(self, x: int):
if not self._initialised:
raise Exception('Stack not initialised!');
self.values.append(x); self.values.append(x);
def TOP(self) -> int: def TOP(self) -> int:
if self.EMPTY(): if self.EMPTY():
raise Exception('Cannot read from empty stack!'); raise Exception('Cannot pop from empty stack!')
return self.values[-1]; return self.values[-1];
def POP(self) -> int: def POP(self) -> int:
if self.EMPTY(): x = self.TOP()
raise Exception('Cannot remove from empty stack!'); self.values = self.values[:-1]
self.values = self.values[:-1]; return x
def __str__(self) -> str: def __str__(self) -> str:
if len(self.values) == 0: if len(self.values) == 0: