我在swift编写一个简单的爱情计算器。它的工作方式是需要两个人的名字并将字母数量加在一起。然后它找到共同的字母数量,从总数中减去它,并将该数字除以总数以获得机会百分比。例如:
第2人:Jane
Charles + Jane =共11封信
我的问题是找到共同字母的最佳方式是什么?
我对swift很新,但之前我曾与目标C合作过。这是我的代码:
//
// ViewController.swift
// Love Calculator
//
// Created by Caden Farley on 8/18/15.
// Copyright (c) 2015 Caden Farley. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var total = 0
@IBOutlet var person1: UITextField!
@IBOutlet var person2: UITextField!
@IBOutlet var resultText: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func buttonPressed () {
self.view.endEditing(true)
let string1 = person1.text
let string2 = person2.text
total = count(string1) + count(string1)
resultText.text = "\(total)"
}
}
答案 0 :(得分:1)
这个问题有重复,它们很有用,但它们都使用了Foundation方法。
这是使用Set
在纯Swift 2.0中查找两个单词的常用字母的简单方法:
let person1 = "Charles"
let person2 = "Jane"
let p1Set = Set(person1.lowercaseString.characters)
let p2Set = Set(person2.lowercaseString.characters)
let common = Array(p1Set.intersect(p2Set)).map({ String($0) })
print(common.count) // 2
for letter in common {
print(letter) // "e", "a"
}
仅在Swift 1.2中略有不同:
let person1 = "Charles"
let person2 = "Jane"
let p1Set = Set(person1.lowercaseString)
let p2Set = Set(person2.lowercaseString)
let common = Array(p1Set.intersect(p2Set)).map({ String($0) })
println(common.count) // 2
for letter in common {
println(letter) // "e", "a"
}
当然,使用Set
意味着它只计算唯一字母,而不是出现次数。
为此,您必须使用类似NSCountedSet
的内容(但已经有关于SO的示例)。
答案 1 :(得分:0)
func compatability(a: String, _ b: String) -> Int {
let (aC, bC) = (a.lowercaseString.characters, b.lowercaseString.characters)
let matches = { (col: String.CharacterView, set: Set<Character>) in
col.reduce(0) { (sum, c) in set.contains(c) ? sum + 1 : sum }
}
let tot = aC.count + bC.count
let com = matches(aC, Set(bC)) + matches(bC, Set(aC))
return (tot - com) * 100 / tot
}
compatability("Charles", "Jane") // 63