I have an array starting from 1 to 100 and I have to print element if the number is divisible by 4 it should print the letter "A" and if the number is divisible by 5 it should print the letter "B" and if it is divisible by both then "AB" I want to make a scalable solution if in future I want to add number divisible by 8 should print "C" and divisible by 4 & 8 should print "AC", by 5&8 should print "BC" and if all three then "ABC"
desired output:
1
2
3
A
B
6
7
C
9
B
11
AB
13
14
...
I wrote this
for number in 1...100 {
if number.isMultiple(of: 4) && !number.isMultiple(of: 5){
print("A"
} else if !number.isMultiple(of: 4) && number.isMultiple(of: 5){
print("B")
} else if number.isMultiple(of: 4) && number.isMultiple(of: 5){
print("AB")
} else {
print(number)
}
}
Please provide a scalable solution to keep adding If-else is not a good option.
2
Answers
Here it is, instead of using if-else, you can just add up whenever you need
Result::
if you just want [Any] type then just
You were pretty close but you don’t need the else conditions. Just add the character to the string if it matches another condition:
Using a dictionary to store the characters:
Note that dictionary is an unordered collection. If you need the characters to be sorted you would need to sort the dictionary by its values before iterating its key value pairs: