How to rearrange a slice into a zig-zag pattern (a < b > c < d > e < f > g) in Swift

3 Answers

0 votes
// This program rearranges an array into a zig-zag pattern, where the elements 
// alternate between being smaller and larger than their neighbors

// a < b > c < d > e < f > g...
// 3 < 5 > 1 < 9 > 6 < 7 > 2 < 4

func rearrangeIntoZigZag(_ arr: inout [Int]) {
    guard arr.count > 1 else { return }

    for i in 0..<(arr.count - 1) {
        let shouldSwap =
            (i.isMultiple(of: 2) && arr[i] > arr[i + 1]) ||
            (!i.isMultiple(of: 2) && arr[i] < arr[i + 1])

        if shouldSwap {
            arr.swapAt(i, i + 1)
        }
    }
}

var arr = [3, 5, 1, 7, 9, 6, 4, 2]

rearrangeIntoZigZag(&arr)

print(arr)


/*
run:

[3, 5, 1, 9, 6, 7, 2, 4]

*/

 



answered Oct 8 by avibootz
0 votes
// This program rearranges an array into a zig-zag pattern, where the elements 
// alternate between being smaller and larger than their neighbors

// a < b > c < d > e < f > g...
// 3 < 5 > 1 < 9 > 6 < 7 > 2 < 4

func rearrangeIntoZigZag(_ arr: inout [Int]) {
    guard arr.count > 1 else { return }

    for i in 0..<(arr.count - 1) {
        if i.isMultiple(of: 2) {
            // Expect arr[i] < arr[i + 1]
            if arr[i] > arr[i + 1] {
                arr.swapAt(i, i + 1)
            }
        } else {
            // Expect arr[i] > arr[i + 1]
            if arr[i] < arr[i + 1] {
                arr.swapAt(i, i + 1)
            }
        }
    }
}

var arr = [3, 5, 1, 7, 9, 6, 4, 2]

rearrangeIntoZigZag(&arr)

print(arr)


/*
run:

[3, 5, 1, 9, 6, 7, 2, 4]

*/

 



answered Oct 8 by avibootz
0 votes
// This program rearranges an array into a zig-zag pattern, where the elements 
// alternate between being smaller and larger than their neighbors

// a < b > c < d > e < f > g...
// 3 < 5 > 1 < 9 > 6 < 7 > 2 < 4

extension Array where Element: Comparable {
    mutating func zigZag() {
        guard count > 1 else { return }

        for i in 0..<(count - 1) {
            let shouldSwap =
                (i.isMultiple(of: 2) && self[i] > self[i + 1]) ||
                (!i.isMultiple(of: 2) && self[i] < self[i + 1])

            if shouldSwap {
                swapAt(i, i + 1)
            }
        }
    }
}

var arr = [3, 5, 1, 7, 9, 6, 4, 2]
arr.zigZag()

print(arr)



/*
run:

[3, 5, 1, 9, 6, 7, 2, 4]

*/

 



answered Oct 8 by avibootz

Related questions

...