Coffee inTime
Coffee inTime

Reputation: 230

How can I make function code cleaner and optimize?

func getRepeats(_ string: String, _ k: Int = 1) {
    var length = string.count

    if (k > length / 2) {
        return
    }
    sleep(2)
    for i in stride(from: 0, to: length - k, by: k) {
        var part_1 = Array(string)[i..<length] 
        var part_2 = Array(part_1)[0..<k]

        var part_3 = Array(string)[i..<length]
        var part_4 = Array(part_3)[k..<k*2]
        print(part_2, part_4)
    }

    getRepeats(string, k+1)

}

getRepeats("abcabc")

The function displays the subsequences of the string.

Instead of this:

var part_1 = Array(string)[i..<length] 
var part_2 = Array(part_1)[0..<k]

I would like it:

part_1 = Array(string)[i..<length][0..<k]

But this does not work, here is the error: Fatal error: ArraySlice index is out of range (before startIndex)

Perhaps tell me something else useful, thanks in advance!

Upvotes: 1

Views: 55

Answers (1)

rmaddy
rmaddy

Reputation: 318955

The two lines:

let part_1 = Array(string)[i..<length]
let part_2 = Array(part_1)[0..<k]

Can be combined into one as:

let part_2 = Array(string)[i..<length][i..<(k+i)]

The expression Array(string)[i..<length] returns an ArraySlice. The important thing to remember is that the indices of the slice do not necessarily start at 0. They start at whatever index you used to access the slice. In this case, i.

So your second access with [0..<k] needs to be shifted to start with i. This gives [i..<(k+i)].

Upvotes: 4

Related Questions