Recursive method in pharo produces #SubscriptOutOfBounds:8
Asked Answered
K

1

1

I created a class in Pharo known as BinarySearchTreean i implemented a method called BinarySearchTree>>PreOrder and BinarySearchTree>>index

Preorder: myArray index: position

(myArray at: position) ~= -1 
ifTrue: [ 
       Transcript show: (myArray at: position).
        self Preorder: myArray index: (position * 2).
        self Preorder: myArray index: (position * 2) + 1.
    ].

I then provided this array #(90 60 95 50) with index 1 to make a PreOrder search in my binary tree which i implemented using arrays but it does not work. Please help...

Krawczyk answered 7/10, 2017 at 11:31 Comment(0)
O
1

#at: will signal SubscriptOutOfBounds when the index is < 0 or greater than the size of the array (Smalltalk collections are 1-based, i.e. the first index is 1, not 0). 8 is clearly larger than 4 (the size of myArray).

The check at the start will never evaluate to False as your array has no entry -1, and hence the conditional block will be evaluated every time.

I can't really say where your problem lies as you've excluded all the code that is actually of interest. If you add that I can tell you more.

Orphism answered 7/10, 2017 at 14:16 Comment(2)
I think all the necessary code to get the error is here. If you call PreOrder: array index: 1, since it duplicates position on every call and calls the same method again, it's just a matter of (short) time to call with a position exceeding the size.Scrambler
Well, yes... but you have to make lots of assumptions. It's probably simpler for OP to post the missing code than for us to iterate over all permutations of possibilities (e.g. start value of position, that wondrous condition at the beginning etc.).Orphism

© 2022 - 2024 — McMap. All rights reserved.