Gray Code

«  ML Reading Ch04 - Training Models
My Thoughts - Software Engineer Task Estimation  »

The reflected binary code (RBC), also known just as reflected binary (RB) or Gray code after Frank Gray, is an ordering of the binary numeral system such that two successive values differ in only one bit (binary digit).

Decimal Binary Gray Gray Decimal
0 0000 0000 0
1 0001 0001 1
2 0010 0011 3
4 0100 0110 6
5 0101 0111 7
6 0110 0101 5
7 0111 0100 4
8 1000 1100 12
9 1001 1101 13
10 1010 1111 15
11 1011 1110 14
12 1100 1010 10
13 1101 1011 11
14 1110 1001 9
15 1111 1000 8

Swift

// 1st way
func grayCode(_ n: Int) -> [Int] {
    var res = [Int]()
    res.append(0)

    for i in 1...n {
        let size = res.count
        let mask = 1<<(i-1)
        for j in stride(from: size-1, through: 0, by: -1) {
            res.append(mask | res[j])
        }
    }

    return res
}

// 2nd way
func grayCode(_ n: Int) -> [Int] {
    var res = [Int]()
    let len = 1<<
    for i in 0..<len {
        let num = i ^ (i >> 1)
        res.append(num)
    }
    return res
}

Reference

Published on 03 Jul 2021 Find me on Facebook, Twitter!

«  ML Reading Ch04 - Training Models
My Thoughts - Software Engineer Task Estimation  »

Comments

    Join the discussion for this article at here . Our comments is using Github Issues. All of posted comments will display at this page instantly.