so I've tried my way, which has not worked and seemed to have way too many control statements, which got somewhat confusing. The question is pretty self evident.
How do you implement three stacks using a single array?
I know the answer has been answered in Java, but I couldn't find anything in Javascript.
For now, a potential solution that has fixed amount of space for each stack would be fine. I know that a solution that would be more flexible in space allocation would also be more complex.
Thank you for your help :)
EDIT: This is my code
function ThreeInOne() {
this.stack = [];
this.firstStackBeginning;
this.firstStackEnd;
this.secondStackBeginning;
this.secondStackEnd;
this.thirdStackBeginning;
this.thirdStackEnd;
this.addAtStack = function(stackIndex, value) {
if (this.stack.length === 0) {
this.stack.push(value);
if (stackIndex = 1) {
this.firstStackBeginning = 0;
this.firstStackEnd = 0;
} else if (stackIndex = 2) {
this.secondStackBeginning = 0;
this.secondStackEnd = 0;
} else if (stackIndex = 3) {
this.thirdStackBeginning = 0;
this.thirdStackEnd = 0;
} else if (stackIndex > 3) {
console.log("There are only 3 stacks available to add to")
}
} else if (this.stack.length > 0) {
if (stackIndex == 1) {
if (this.secondStackBeginning == 0) {
this.stack.unshift(value);
this.secondStackBeginning++;
this.secondStackEnd++;
this.firstStackBeginning = 0;
this.firstStackEnd = 0;
}
if (this.secondStackBeginning && this.secondStackBeginning !== 0) {
this.stack.splice(this.secondStackBeginning-1, 0, value);
this.firstStackEnd++;
}
} else if (stackIndex == 2) {
if (this.thirdStackBeginning==0) {
this.stack.unshift(value);
this.thirdStackBeginning++;
this.thirdStackEnd++;
this.secondStackBeginning = 0;
this.secondStackEnd = 0;
} else if (this.thirdStackBeginning != 0) {
this.stack.splice(this.thirdStackBeginning-1, 0, value);
this.secondStackEnd = this.thirdStackBeginning-1;
this.thirdStackBeginning++;
this.thirdStackEnd++;
}
} else if (stackIndex == 3) {
if (this.firstStackEnd && !this.secondStackEnd && !this.thirdStackBeginning) {
this.thirdStackBeginning = this.firstStackEnd+1;
this.stack.push(value);
} else if (this.seconStackEnd )
}
}
}
}
It's not finished, but the idea was to keep pointers of the beginning and end of each stack and update them accordingly. I think the point is to not use another data structure (other than that one array) or else I would just create an array with three internal arrays and update them accordingly. So the idea is that for example if we start with array = [4, 5, 1, 2, 0, 3, 6], this array is actually composed of three stacks, one = [ 4, 5 ), two = [ 1, 2), and three = [0, 3, 6). The idea is that if I want to add x to stack two, then I'll end up with the array = [4, 5, 1, 2, x, 0, 3, 6]
I hope this makes it more clear!
let stacks = [[ ], [ ], [ ]]and get three stacks in a single array. Maybe not in the spirit of the question, but evidence that the question is not at all "self evident".