Skip to content

Commit

Permalink
Resizable array wrapper
Browse files Browse the repository at this point in the history
  • Loading branch information
BalaM314 committed May 23, 2024
1 parent 575355a commit b5e17aa
Showing 1 changed file with 64 additions and 0 deletions.
64 changes: 64 additions & 0 deletions programs/vecinteger.sc
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
CLASS VecInteger
PRIVATE array: ARRAY OF INTEGER
PRIVATE arrayLength: INTEGER
PRIVATE length: INTEGER
PRIVATE loadFactor: REAL
PUBLIC PROCEDURE NEW(Length: INTEGER)
length <- Length
arrayLength <- Length
IF arrayLength <= 0 THEN
arrayLength <- 1
ENDIF
DECLARE arr: ARRAY[0:arrayLength - 1] OF INTEGER
array <- arr
loadFactor <- 0.7
ENDPROCEDURE
PUBLIC FUNCTION length() RETURNS INTEGER
RETURN length
ENDFUNCTION
PUBLIC FUNCTION get(i: INTEGER) RETURNS INTEGER
IF i < 0 OR i >= length THEN
DECLARE array: ARRAY[0:length - 1] OF INTEGER
//Array index out of bounds
OUTPUT array[i]
ENDIF
RETURN array[i]
ENDFUNCTION
PUBLIC PROCEDURE set(i: INTEGER, val: INTEGER)
IF i < 0 OR i >= length THEN
DECLARE array: ARRAY[0:length - 1] OF INTEGER
//Array index out of bounds
OUTPUT array[i]
ENDIF
array[i] <- val
ENDPROCEDURE
PUBLIC PROCEDURE push(val: INTEGER)
CALL increaseLength(length + 1)
CALL set(length - 1, val)
ENDPROCEDURE
PUBLIC PROCEDURE increaseLength(cap: INTEGER)
IF cap > length THEN
IF cap > arrayLength THEN
CALL resizeBackingArray(INT(cap / loadFactor))
ENDIF
length <- cap
ENDIF
ENDPROCEDURE
PRIVATE PROCEDURE resizeBackingArray(Length: INTEGER)
IF length < Length THEN
DECLARE newArr: ARRAY[0:Length - 1] OF INTEGER
FOR i <- 1 TO length - 1
newArr[i] <- array[i]
NEXT i
array <- newArr
arrayLength <- Length
ENDIF
ENDPROCEDURE
ENDCLASS

DECLARE x: VecInteger
x <- NEW VecInteger(0)
FOR i <- 1 TO 100
CALL x.push(i)
OUTPUT x.length()
NEXT i

0 comments on commit b5e17aa

Please sign in to comment.