Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the average value of an array - Swift [duplicate]

Tags:

arrays

swift

I'm having a problem where I don't know how to find the average value of an array. Here are my questions:

  1. How do I add up all the numbers within my array?
  2. How do I find how many indexes are in my array?
  3. How do I take this information and gather the average value from my array?

While all of these may seem simple and fairly elementary, I am unsure on how to do this. Any help?

like image 898
bwc Avatar asked Apr 30 '17 06:04

bwc


1 Answers

For example purposes, I will define my array as intArray with the values of [10, 15, 5, 7, 13] creating our final array as:

var intArray = [10, 15, 5, 7, 13]

Now let's answer each of the questions in order:

  1. How do I add up all the numbers within my array?

In order to add up all the numbers within your array, you'll need to utilize the reduce() function that is integrated within arrays. It will look something like this:

intArray.reduce(0, +)

This line will take your array, intArray in this case, and reduce it starting at index number 0 and adding all the following consecutive numbers. However, in our case, we need to assign this value to a variable in order to utilize it later in the averaging function. This is what that looks like:

let sumArray = intArray.reduce(0, +)
  1. How do I find how many indexes are in my array?

In our case, we need the total amount of indexes to figure out what to divide by in order to get our final average. That is done by utilizing the count() property of arrays. That will look like this:

intArray.count

So now that we have the total index count, we can figure out our answer to the next question.

  1. How do I take this information and gather the average value from my array?

We can take the information from question 1 and question 2 and combine it together to get our average value of the array. It will look something like this:

let avgArrayValue = sumArray / intArray.count

Altogether the code will look like this:

let sumArray = intArray.reduce(0, +)

let avgArrayValue = sumArray / intArray.count
like image 120
bwc Avatar answered Nov 04 '22 01:11

bwc