Compare commits

...

3 Commits

8 changed files with 223 additions and 63 deletions

View File

@ -88,4 +88,8 @@ parts:
- command: 'algorithm-stacks-next-greater-element'
description: 'Seminarblatt Woche 4, Aufgabe 1'
inputs:
L: [4, 2, 1, 100, 6, 3, 16]
L: [4, 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 {
clearOutput()
if len(L) == 0 {
return output()
}
S := stacks.CREATE()
S.INIT()
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])
nextElement := L[i]
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.
logging.Debug("Stack S | %v", S)
for !S.EMPTY() { // ACHTUNG: dies ist eine while-Schleife in golang
for !S.EMPTY() { // ACHTUNG: schreibe 'while' im Pseudocode, denn dies ist eine while-Schleife in golang
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 {
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)
// sonst Element auf Stack zurücklegen und Schleife abbrechen.
S.POP()
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 {
logging.Debug("Stack-Element >= nextElement ==> zurücklegen")
S.PUSH(element)
// falls top Element == next Element, vom Stack entfernen und Schleife abbrechen.
S.POP()
metrics.AddMovesCost()
break
}
@ -60,19 +60,21 @@ func NextGreaterElement(L []int) [][2]int {
logging.Debug("L[%v] auf Stack legen", i)
S.PUSH(nextElement)
logging.Debug("Stack S | %v", S)
metrics.AddMovesCost()
}
logging.Debug("Stack S | %v", S)
// was übrig bleibt hat kein größeres Element
logging.Debug("Alles übrige auf Stack hat kein nächstes größeres Element")
for !S.EMPTY() { // ACHTUNG: dies ist eine while-Schleife in golang
for !S.EMPTY() { // ACHTUNG: schreibe 'while' im Pseudocode, denn dies ist eine while-Schleife in golang
logging.Debug("Stack S | %v", S)
element := S.TOP()
S.POP()
metrics.AddMovesCost()
addToOutput(element, -1)
}
logging.Debug("Stack S | %v", S)
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) {
var name = "Binärsuchalgorithmus"
var name = "Next Greater Element"
var inputs = map[string]interface{}{
"L": input_L,
}

View File

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

View File

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

View File

@ -0,0 +1,52 @@
#!/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,26 +18,33 @@ from local.typing import *;
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class Stack(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 len(self.values) == 0;
return not self._initialised or len(self.values) == 0;
def PUSH(self, x: int):
if not self._initialised:
raise Exception('Stack not initialised!');
self.values.append(x);
def TOP(self) -> int:
if self.EMPTY():
raise Exception('Cannot pop from empty stack!')
raise Exception('Cannot read from empty stack!');
return self.values[-1];
def POP(self) -> int:
x = self.TOP()
self.values = self.values[:-1]
return x
if self.EMPTY():
raise Exception('Cannot remove from empty stack!');
self.values = self.values[:-1];
def __str__(self) -> str:
if len(self.values) == 0: