Guest User

Untitled

a guest
Nov 16th, 2018
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. /*
  2. Stack of plates: Imagine a literal stack of plates. If the stack gets too high, it might topple.
  3. Therefore, in real life, we would likely start a new stack when the previous stack exceeds some threshold.
  4. Implement a data structure SetOfStacks that mimics this. SetOfStacks should be composed of several stacks and
  5. should create a new stack once the previous one exceeds capacity.
  6.  
  7. SetOfStacks.push() and SetfStacks.pop() should behave identically to a single stack
  8. That is pop should return the same valeues as it would if there were just a single stack.
  9. */
  10.  
  11.  
  12. class SetOfStacks<T> {
  13. threshold: number
  14. stacks: MyStack<T>[]
  15. stackSizes: number[]
  16. constructor(threshold: number) {
  17. this.threshold = threshold
  18. this.stacks = []
  19. this.stackSizes = []
  20. }
  21. push(num: T) {
  22. let stack = null
  23. let stackIndex = 0
  24. while (!stack && stackIndex < this.stacks.length) {
  25. if (this.stackSizes[stackIndex] < this.threshold) {
  26. stack = this.stacks[stackIndex]
  27. } else {
  28. ++stackIndex
  29. }
  30. }
  31.  
  32. if (!stack) {
  33. this.pushStack()
  34. stack = this.peakStack()
  35. }
  36.  
  37. stack.push(num)
  38. ++this.stackSizes[stackIndex]
  39. }
  40. pop() {
  41. const stack = this.peakStack()
  42. const item = stack.pop()
  43. --this.stackSizes[this.stacks.length - 1]
  44. if (stack.isEmpty()) {
  45. this.popStack()
  46. }
  47. return item
  48. }
  49. pushStack(){
  50. this.stacks.push(new MyStack())
  51. this.stackSizes.push(0)
  52. }
  53. popStack() {
  54. console.log('popping stack')
  55. this.stacks.pop()
  56. this.stackSizes.pop()
  57. }
  58. peakStack() {
  59. return this.stacks[this.stacks.length - 1]
  60. }
  61. isEmpty() {
  62. return this.stacks.length === 0
  63. }
  64. }
  65.  
  66. let newstackset = new SetOfStacks(2)
  67. newstackset.push(2)
  68. newstackset.push(1)
  69. newstackset.push(1)
  70. newstackset.push(3)
  71. newstackset.push(0)
  72.  
  73.  
  74. while (!newstackset.isEmpty()) {
  75. for (let i = 0; i < newstackset.stacks.length; ++i) {
  76. console.log('stack size at ',i, newstackset.stackSizes[i])
  77. }
  78.  
  79. console.log(newstackset.pop().data)
  80. }
Add Comment
Please, Sign In to add comment