Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Swift – Given an Int like 30 how to take ranged numbers by 7?

Let’s suppose I have an Int like 30, how can i take ranged numbers by 7 and put them into a list of pairs in Swift?

For example in this case it would be [(1, 7), (8, 14), (15, 21), (22, 28), (29, 30)] where the last couple is 29-30.

I found a code in Kotlin that may do that but I don’t know how could it be in Swift since I don’t know Kotlin. I post it in case it is helpful.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

val myInt = 28
val list = (1..ceil(myInt/7.0).toInt()).mapIndexed { index, i ->
    7*index + 1 to (7*index + 7).coerceAtMost(myInt)
}

print(list)

Update:

I tried this code so far:

var days = 30
var daysInt: [Int] = []
var index = 0
      
        for i in 1...days {
                
                 if index <= days {
                    if i == 1 {
                        index += 1
                        daysInt.append(index)
                        index += 6
                        daysInt.append(index)
                    } else {
                        index += 1
                        daysInt.append(index)
                        index += 6
                        daysInt.append(index)
                    }
                }
            }

And the output is:

  • 0 : 1
    • 1 : 7
    • 2 : 8
    • 3 : 14
    • 4 : 15
    • 5 : 21
    • 6 : 22
    • 7 : 28
    • 8 : 29
    • 9 : 35

All fine but the 35 should be 30.

I’m sure there is a better way.

>Solution :

The Kotlin code

(1..myInt step 7).map { it to min(it + 6, myInt) }

which was suggested in a comment can almost literally be translated to Swift.

With stride() you can create the sequence 1, 8, 15, …, 29, and with map() you can map each value to a tuple:

let days = 30
let list = stride(from: 1, to: days, by: 7).map { ($0, min($0+6, days)) }
print(list)
// [(1, 7), (8, 14), (15, 21), (22, 28), (29, 30)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading