code.club

標題: 猜數字AABB的小遊戲 [打印本頁]

作者: swift    時間: 2016-8-7 18:09
標題: 猜數字AABB的小遊戲
本帖最後由 swift 於 2016-9-25 15:19 編輯

var str = "1234"

//這個函數會將字串變成字元陣列
func stringtToCharacterArray(theString:String) -> [Character] {
    var characterArray:[Character] = []
    for i in theString.characters {
        characterArray.append(i)
    }
    return characterArray
}

var theCh = stringtToCharacterArray(theString: str) //將字元陣列賦值給 theCh


// 判斷這字元陣列有無重複的字元
var isDouble = false

for k in 0..<4 {
   
    for j in k+1..<4 {
        if theCh[k] == theCh[j] {
            isDouble = true
            break
        }
    }
}

if isDouble == true {
    print("CH is not ok")
} else {
    print ("CH is ok")
}


// 判斷所猜的數字符合幾A幾B

func guess( num1:[Character],  num2:[Character]) -> String {
    var a:Int = 0
    var b:Int = 0
    var tempNum = num2
    for k in 0..<4 {
        if num1[k] == tempNum[k] {
            tempNum[k] = "x"
            a += 1
        }
    }
   
    for k in 0..<4 {
        for j in 0..<4 {
            if num1[k] == tempNum[j] {
                b += 1
            }
        }
    }
    if a == 4 && b == 0 {
        return "Bingo, you win!"
    } else {
        
        return "\(a)A \(b)B"
    }
}
var tnum1:[Character] = ["2","4","6","8"]
var tnum2:[Character] = ["2","4","8","6"]

var result = guess(num1:tnum1, num2:tnum2)





歡迎光臨 code.club (https://code.club/) Powered by Discuz! X3.2