I wrote logic for "Wordle" game but iI think it's too heavy and not very readable. Is
Is there any way to improve it? Simple wordle game with conditions: 1) Green colour - "G" if string1 and string2 indices values are equal. 2) Yellow colour - "Y" if string2 indices value appears in string1. 3) else statement Grey colour - "." 4) Every letter from string1 used for colour only once.
Simple wordle game with conditions:
1) Green colour - "G" if string1 and string2 indices values are equal.
2) Yellow colour - "Y" if string2 indices value appears in string1.
3) else statement Grey colour - "."
4) Every letter from string1 used for colour only once.
My code:
let mstr1 = readLine()!
let mstr2 = readLine()!
var string1 = mstr1.compactMap { $0.asciiValue }
var string2 = mstr2.compactMap { $0.asciiValue }
var dict: Dictionary<UInt8, Int> = [:]
for element in Set(string1) {
dict[element] = string1.filter { $0 == element }.count
}
var answer = Array(repeatElement(".", count: string1.count))
for i in 0 ..< string1.count {
if string1[i] == string2[i] {
answer[i] = "G"
dict[string1[i]]! -= 1
}
}
for i in 0 ..< string1.count {
if dict[string2[i]] != nil && answer[i] != "G"{
if dict[string2[i]]! > 0 {
dict[string2[i]]! -= 1
answer[i] = "Y"
}
}
if dict.values.filter { $0 > 0 }.count <= 0 {
break
}
}
print(answer.joined())
Input:
ABBEY
ALGAE
Output:
G...Y