Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,15 @@ Output the maximum cycle length found in the range defined by the input values i

func challenge_0001(i: Int, _ j: Int) -> Int {

<#Write here your solution#>
func collatzCycles(n: Int) -> Int {
if n == 1 { return 1 }
return n%2==0 ? 1 + collatzCycles(n/2) : 1 + collatzCycles(3*n+1)
}

return (i...j).map(collatzCycles).maxElement()!
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lovely maxElement I didn't know it. 🌟

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not extremely fond of that ! at the end, but its quite handy

}

//assert(challenge_0001(1, 10) == 20)
//assert(challenge_0001(100, 200) == 125)
//assert(challenge_0001(201, 210) == 89)
//assert(challenge_0001(900, 1000) == 174)
assert(challenge_0001(1, 10) == 20)
assert(challenge_0001(100, 200) == 125)
assert(challenge_0001(201, 210) == 89)
assert(challenge_0001(900, 1000) == 174)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice solution, I think you could simplify the collatzCycles function removing the else clausure because the if always results in a return.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I also find more readable n/2 than n>>1 The compilers are clever enough these days to apply this type of optimisations.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point, looks easier on the eyes without that else

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was just having fun here 😄 (But I'm not entirely sure if that division is optimized btw, I recall some time ago confirming that * 0.5 was faster than / 2.0 for Floats)