-
Notifications
You must be signed in to change notification settings - Fork 3
Solution for the Collatz Challenge #3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: challenge0001_The_3n+1_problem
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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()! | ||
| } | ||
|
|
||
| //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) | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nice solution, I think you could simplify the
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I also find more readable
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Good point, looks easier on the eyes without that
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 |
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Lovely
maxElementI didn't know it. 🌟There was a problem hiding this comment.
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