異性体の問題 counting isomers

改訂新版 C言語による標準アルゴリズム事典をSwiftでコーディング

アルゴリズム

異性体の問題 counting isomers

実行

Playground※但し時間がかかります。Command Lineが現実的です。

コード

let C = 17
let L = 2558
var size = [Int](repeating: 0, count: L)
var length = [Int](repeating: 0, count: L)
var count = [Int](repeating: 0, count: C + 1)

func isomer() -> Bool {
    var n = 0
    var len = 0
    
    for i in 0..<L {
        len = length[i] + 1
        if len > C / 2 {
            break
        }
        let si = size[i] + 1
        if si + len > C {
            continue
        }
        for j in 0...i {
            let sj = si + size[j]
            if sj + len > C {
                continue
            }
            for k in 0...j {
                let sk = sj + size[k]
                if sk + len > C {
                    continue
                }
                n = n + 1
                if n >= L {
                    return false
                }
                size[n] = sk
                length[n] = len
            }
        }
    }
    if len <= C / 2 {
        return false
    }
    for i in 0...n {
        let si = size[i]
        for j in 0...i {
            if length[i] != length[j] {
                continue
            }
            let sj = si + size[j]
            if sj > C {
                continue
            }
            count[sj] = count[sj] + 1
            for k in 0...j {
                let sk = sj + size[k] + 1
                if sk > C {
                    continue
                }
                for h in 0...k {
                    let sh = sk + size[h]
                    if sh <= C {
                        count[sh] = count[sh] + 1
                    }
                }
            }
        }
    }
    for i in 1...C {
        print("炭素原子が \(i) 個のものは \(count[i]) 種類")
    }
    return true
}

print(isomer())

Algorithm,Swift

Posted by shi-n