I'm trying to do the following exercise in Swift:
Create the function obtenerFrecuencias
that allows you to calculate the frequencies of a set of answers, numbers between 0 and 9, which are stored in an array of Int.
Example:
let respuestas = [0,0,1,1,2,1,2,3,5,1,2,2,2,6]
let frec = obtenerFrecuencias(respuestas: respuestas)
print("Frecuencias: \(frec)")
Frecuencias: [2, 4, 5, 1, 0, 1, 1, 0, 0, 0]
I know the solution is the following:
func obtenerFrecuencias(respuestas: [Int]) -> [Int] {
var frecuencias = Array(repeating: 0, count: 10)
for puntuacion in respuestas {
frecuencias[puntuacion] += 1
}
return frecuencias
}
But I do not understand the way in which the for-in loop works, it should act on the indexes (in this case called punctuation) of the array, so that for answers [0] would return 0, responses [1] = 0, response [2] = 1 ... but the execution of frequencies [punctuation] + = 1 does not I would get what I wanted ...
It seems that it is not fixed in the index but in the associated value, I explain:
For each punctuation with value 'i' in the initial array, add 1 to the value of the index 'i' in the resulting array and so on until you complete the first array.
So if you get the desired but I do not know if there is another explanation, or if it is possible to implement it in this way ...
I've been reviewing the Swift documentation and searched the web but I can not find anything about it.
I hope you explained well, thanks in advance.