Für Vorlesungen, bitte die Webseite verwenden. https://flavigny.de/lecture
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

57 satır
1.4KB

  1. collatz <- function(raw_x, max_iter) {
  2. stopifnot("Length of x must be 1" = length(raw_x) == 1)
  3. x <- as.integer(raw_x)
  4. stopifnot("Cannot interprete x as integer" = !is.na(x))
  5. sequ <- c(x)
  6. len <- NA
  7. for (n in (1:(max_iter-1))) {
  8. if (x == 1) {
  9. len <- n
  10. break
  11. } else if (x %% 2 == 0) {
  12. x <- x / 2
  13. } else {
  14. x <- 3*x+1
  15. }
  16. sequ <- c(sequ, x)
  17. }
  18. return(list(seq=sequ, len=len))
  19. }
  20. str(collatz(1, 1e4))
  21. ## List of 2
  22. ## $ seq: int 1
  23. ## $ len: int 1
  24. str(collatz(2, 1e4))
  25. ## List of 2
  26. ## $ seq: int [1:2] 2 1
  27. ## $ len: int 2
  28. str(collatz(3, 1e4))
  29. ## List of 2
  30. ## $ seq: int [1:8] 3 10 5 16 8 4 2 1
  31. ## $ len: int 8
  32. str(collatz(3, 5))
  33. ## List of 2
  34. ## $ seq: int [1:5] 3 10 5 16 8
  35. str(collatz("4", 1e4))
  36. ## List of 2
  37. ## $ seq: int [1:3] 4 2 1
  38. ## $ len: int 3
  39. str(collatz("four", 1e4))
  40. ## Warning in collatz("four", 10000): NAs introduced by coercion
  41. ## Error in collatz("four", 10000): Cannot interprete x as integer
  42. str(collatz(1:5, 1e4))
  43. ## Error in collatz(1:5, 10000): Length of x must be 1
  44. str(collatz(5.0, 1e4))
  45. ## List of 2
  46. ## $ seq: int [1:6] 5 16 8 4 2 1
  47. ## $ len: int 6
  48. str(collatz(5.1, 1e4))
  49. ## List of 2
  50. ## $ seq: int [1:6] 5 16 8 4 2 1
  51. ## $ len: int 6
  52. str(collatz(5.9, 1e4))
  53. ## List of 2
  54. ## $ seq: int [1:6] 5 16 8 4 2 1
  55. ## $ len: int 6