john doe john doe -4 years ago 83
Swift Question

Creating a Scale Between 0 and 1 Even when Higher numbers are passed in

I want to write an algorithm which allows me to rescale numbers to between 0 and 1. This means if I pass 25, 100, 500 then it should generate a new scale and represent those numbers on a scale of 0 to 1.

Here is what I have which is incorrect and does not make sense.

height: item.height/item.height * 20


SOLUTION: I think I found a simpler approach

let maxItem = self.items.max { $0.height < $1.height }

for item in self.items {

print(item.height/(maxItem?.height)!)

Answer Source

Pass in the numbers in an array.

Loop through the numbers and find the max.

Map the array of integers to an array of floats, each one being the value from the source array, divided by the max.

Try to write that code. If you have trouble, update your question with your attempt and tell us what's going wrong.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download