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.180 tracks/r/exercises/luhn/example.R
trackler-2.2.1.179 tracks/r/exercises/luhn/example.R
trackler-2.2.1.178 tracks/r/exercises/luhn/example.R
trackler-2.2.1.177 tracks/r/exercises/luhn/example.R
trackler-2.2.1.176 tracks/r/exercises/luhn/example.R
trackler-2.2.1.175 tracks/r/exercises/luhn/example.R
trackler-2.2.1.174 tracks/r/exercises/luhn/example.R
trackler-2.2.1.173 tracks/r/exercises/luhn/example.R
trackler-2.2.1.172 tracks/r/exercises/luhn/example.R
trackler-2.2.1.171 tracks/r/exercises/luhn/example.R
trackler-2.2.1.170 tracks/r/exercises/luhn/example.R
trackler-2.2.1.169 tracks/r/exercises/luhn/example.R
trackler-2.2.1.167 tracks/r/exercises/luhn/example.R
trackler-2.2.1.166 tracks/r/exercises/luhn/example.R
trackler-2.2.1.165 tracks/r/exercises/luhn/example.R
trackler-2.2.1.164 tracks/r/exercises/luhn/example.R
trackler-2.2.1.163 tracks/r/exercises/luhn/example.R
trackler-2.2.1.162 tracks/r/exercises/luhn/example.R
trackler-2.2.1.161 tracks/r/exercises/luhn/example.R
trackler-2.2.1.160 tracks/r/exercises/luhn/example.R