Home > Back-end >  suffix array Index out of bounds
suffix array Index out of bounds

Time:05-20

I have an array , when I suffix array and want to select element , I get error: Index out of bounds. But when I prefix array and select element, It's sucess.

How should I do that I can select after suffix array?

Here is code:

let array = [1,2,3,4,5,6,7,8,9,10]
let suffixArray = array.suffix(5)//[6,7,8,9,10]
let prefixArray = array.prefix(5)//[1,2,3,4,5]
print(suffixArray[2])//Index out of bounds
print(prefixArray[2])//sucess print "3"

CodePudding user response:

The problem you are having is that with .suffix the array does not start with 0. So if you wanted to print the 3rd number in the suffix array, you would have to call print(suffixArray[7].

If you read the description for the return value here. It reads:

A subsequence terminating at the end of the collection with at most maxLength elements.

And if you read the description to subsequence:

A collection representing a contiguous subrange of this collection’s elements. The subsequence shares indices with the original collection.

Full example for playground:

let array = [1,2,3,4,5,6,7,8,9,10]
let suffixArray = array.suffix(5) // [6,7,8,9,10]
let prefixArray = array.prefix(5) // [1,2,3,4,5]
var newSuffixArray: [Int] = []
for i in suffixArray {
    newSuffixArray.append(i)
}

print(suffixArray[7]) // 8
print(newSuffixArray[2]) // 8
print(prefixArray[2]) // 3

CodePudding user response:

Both prefix and suffix return an ArraySlice rather than another Array.

Here's an excerpt from the ArraySlice documentation:

Unlike Array and ContiguousArray, the starting index for an ArraySlice instance isn’t always zero. Slices maintain the same indices of the larger array for the same elements, so the starting index of a slice depends on how it was created, letting you perform index-based operations on either a full array or a slice. Sharing indices between collections and their subsequences is an important part of the design of Swift’s collection algorithms.

You can see that by looking into the indices property of prefixArray and suffixArray.

Generally you are encouraged to use methods of accessing elements that collections provide instead of assuming values of indices.

  • Related