安定な結婚の問題 stable marriage problem
改訂新版 C言語による標準アルゴリズム事典をSwiftでコーディング
アルゴリズム
安定な結婚の問題 stable marriage problem
実行
Command Line
コード
import Foundation /// 入力 /// - parameter メッセージ /// - returns 入力文字列 func input(msg:String = "") -> String { print(msg, separator: "", terminator: "") let indata = FileHandle.standardInput; let rawdata = indata.availableData; let str = NSString(data: rawdata, encoding: String.Encoding.utf8.rawValue); let length = str?.length let result = str?.substring(with: NSRange(location: 0,length: length! - 1)) return result! } func marriage() { let N = 3 var boy = [Int](repeating: 0, count: N + 1) var position = [Int](repeating: 0, count: N + 1) var rank = Array<[Int]>(repeating: [Int](repeating: 0, count: N + 1), count: N + 1) var girl = Array<[Int]>(repeating: [Int](repeating: 0, count: N + 1), count: N + 1) for g in 1...N { print("女性\(g)好み入力") for r in 1...N { let b = Int(input(msg: "\(r)位入力:"))! rank[g][b] = r } boy[g] = 0 rank[g][0] = N + 1 } for b in 1...N { print("男性\(b)好み入力") for r in 1...N { girl[b][r] = Int(input(msg: "\(r)位入力:"))! } position[b] = 0 } for b in 1...N { var s = b while s != 0 { position[s] = position[s] + 1 let g = girl[s][position[s]] if rank[g][s] < rank[g][boy[g]] { let t = boy[g] boy[g] = s s = t } } } for g in 1...N { print("女 \(g) - 男 \(boy[g])") } } marriage()