Search

mercredi 8 février 2017

Array length

Context

Note: in this post, arrays will be implemented according to our previous definition.
Array length can be computed by counting its number of elements. To do so, we need to split the array between counted elements and not counted ones. And counting an element means move it from one array to another.
To have clean code, we can additionally move back all our elements at the initial position.

Initial state

  • Memory: 0, Array, 0, 0, 0
  • Cursor: first cell
  • Input: any

Process

  • Move to last item (can be done by >[>]<, move to first item on second cell, move to next until it's null, move back to last non-null cell)
  • While last item is not null
    • Move last item to next cell
    • Increment count (2 cells after the end of array)
    • Go back to last item of first array
  • Optional : move all array items back to their original position and same for result

Code 

>[>]< go to last item
[ 
  [->+<] move to right 
  >[>]>+ go to counter and increment 
  <<[<]< go to new last item
] 
>>[[-<+>]>] move back all items 
>[-<+>]< move result back

Code (minified)

>[>]<[[->+<]>[>]>+<<[<]<]>>[[-<+>]>]>[-<+>]

Final state

  • Memory: 0, Array, 0, Array length
  • Cursor: on array length
  • Input: any
  • Output: unchanged

Aucun commentaire:

Enregistrer un commentaire