Sha256: 58f8b14668e206173023e37834f4a909821bfda3d1880419a1f299bab1efff6e

Contents?: true

Size: 875 Bytes

Versions: 219

Compression:

Stored size: 875 Bytes

Contents

library(magrittr)

# Determine whether the number is valid.
is_valid <- function(input) {

  # Strip spaces, check length & check for invalid characters
  input_vector <- gsub(pattern = " ", replacement = "", input) %>% 
                    strsplit("") %>% 
                    unlist()
  if (length(input_vector) < 2 || any(grepl("[^[:digit:]]", input_vector))) {
    return(FALSE)
  }

  # Convert to numeric
  num_vector <- as.numeric(input_vector)

  # Double every second digit starting from the right
  num_vector <- rev(num_vector)
  num_vector[seq(2, length(num_vector), 2)] <- 
    num_vector[seq(2, length(num_vector), 2)] * 2

  # Subtract 9 if > 9 (can apply to all since no
  # digit can be greater than 9 before doubling)
  num_vector <- ifelse(num_vector > 9, num_vector - 9, num_vector)

  # Check checksum is divisible by 10
  sum(num_vector) %% 10 == 0

}

Version data entries

219 entries across 219 versions & 1 rubygems

Version Path
trackler-2.2.1.139 tracks/r/exercises/luhn/example.R
trackler-2.2.1.138 tracks/r/exercises/luhn/example.R
trackler-2.2.1.137 tracks/r/exercises/luhn/example.R
trackler-2.2.1.136 tracks/r/exercises/luhn/example.R
trackler-2.2.1.135 tracks/r/exercises/luhn/example.R
trackler-2.2.1.134 tracks/r/exercises/luhn/example.R
trackler-2.2.1.133 tracks/r/exercises/luhn/example.R
trackler-2.2.1.132 tracks/r/exercises/luhn/example.R
trackler-2.2.1.131 tracks/r/exercises/luhn/example.R
trackler-2.2.1.130 tracks/r/exercises/luhn/example.R
trackler-2.2.1.129 tracks/r/exercises/luhn/example.R
trackler-2.2.1.128 tracks/r/exercises/luhn/example.R
trackler-2.2.1.127 tracks/r/exercises/luhn/example.R
trackler-2.2.1.126 tracks/r/exercises/luhn/example.R
trackler-2.2.1.125 tracks/r/exercises/luhn/example.R
trackler-2.2.1.124 tracks/r/exercises/luhn/example.R
trackler-2.2.1.123 tracks/r/exercises/luhn/example.R
trackler-2.2.1.122 tracks/r/exercises/luhn/example.R
trackler-2.2.1.121 tracks/r/exercises/luhn/example.R
trackler-2.2.1.120 tracks/r/exercises/luhn/example.R