toyakp.blogg.se

Arraylist in kotlin
Arraylist in kotlin





arraylist in kotlin

However, the error message is different this time: “ Kotlin: Val cannot be reassigned.” Next, let’s test the += operator: val myList = listOf("Tom Hanks", "Brad Pitt")Īs we’ve expected, the code doesn’t compile either. If we compile the code above, the compiler complains: “Kotlin: Unresolved reference: add.” This is expected, as the List interface doesn’t have the add() method. But let’s create a test to verify if it’s true: var myList = listOf("Tom Hanks", "Brad Pitt") Since List is read-only, we can’t add an element to it. Implement fun asteroidCollision(asteroids: IntArray): IntArray else if (Math.abs(prev) > Math.Finally, let’s look at the List type in Kotlin.

  • If there are no collisions, decrement the stack curIndex.
  • Only decrement when curIndex is at the end of the stack.

    arraylist in kotlin

  • Given a collision with one AST with a larger value, remove the smaller AST.
  • If the curIndex is not at the end of the stack after removing ASTs, continue to check for right-most collisions by decrementing curIndex.
  • Given a collision with ASTs with equal value, remove both ASTs.
  • A collision occurs when prev is positive and cur is negative.
  • Using the current cur and previous prev values, check whether a collision will occur.
  • Start curIndex at the top of the stack and check the stack until curIndex is at the second element of the stack, thus checking for all possible AST collisions.
  • Build ArrayList used as a stack and add the AST values to the stack.
  • However, I'm looking to improve speed and memory performance. The solution performs as expected in terms of achieving the correct results. The 5 and 10 never collide.Ĭreate a stack using an ArrayList to compare asteroid (AST) direction, values, and remove ASTs.

    arraylist in kotlin

    Smaller ASTs explode (are deleted), the same size both explode, and same direction ASTs do nothingĮxplanation: The 10 and -5 collide resulting in 10.Negative numbers move left, positive numbers move right.Is this a performant strategy to implement a stack in Kotlin to compare and delete values? ExpectĬreate a stack in order to compare an array of asteroids (ASTs) and handle collisions (deletions), returning the final array of ASTs after collisions.







    Arraylist in kotlin