0

How do I archive this result using a simple mathematical formula.

I have an initial offset = 100, and initial count = 0, that i want to increase the offset based on count value. I tried using the below code but it doesn't function correctly.

Example

  1. When count is 0 to 3, then offset should be 100.
  2. When count is 4 to 6, then offset should be 200.
  3. When count is 7 to 9, then offset should be 300.
  4. When count is 10 to 12, then offset should be 400.

Attempt

func getHeight(count: Int) ->CGFloat {
     var index = 0
     for i in 0..<count{
         if(i % 2  != 0){
             index += 1
         }
     }
    return CGFloat(100 * index)
    //return CGFloat(count + 3 / 9 * 100)
}

Testing

print("0 to 3 = \(self.getHeight(count: 0)), expected = 100")
print("0 to 3 = \(self.getHeight(count: 2)), expected = 100")
print("4 to 6 = \(self.getHeight(count: 4)), expected = 200")
print("7 to 9 = \(self.getHeight(count: 7)), expected = 300")
print("10 to 12 = \(self.getHeight(count: 12)), expected = 400")

Results

0 to 3 = 0.0, expected = 100
0 to 3 = 100.0, expected = 100
4 to 6 = 200.0, expected = 200
7 to 9 = 300.0, expected = 300
10 to 12 = 600.0, expected = 400
Peter
  • 1,860
  • 2
  • 18
  • 47
  • 2
    switch case with range value should work: https://stackoverflow.com/questions/52665744/switch-case-with-range – Larme Sep 22 '21 at 08:46

1 Answers1

0

Formula with integer division:

let cnt = count != 0 ? count : 1
result = 100 * ((cnt + 2) / 3)
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
MBo
  • 77,366
  • 5
  • 53
  • 86