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.159 tracks/r/exercises/luhn/example.R
trackler-2.2.1.158 tracks/r/exercises/luhn/example.R
trackler-2.2.1.157 tracks/r/exercises/luhn/example.R
trackler-2.2.1.156 tracks/r/exercises/luhn/example.R
trackler-2.2.1.155 tracks/r/exercises/luhn/example.R
trackler-2.2.1.154 tracks/r/exercises/luhn/example.R
trackler-2.2.1.153 tracks/r/exercises/luhn/example.R
trackler-2.2.1.152 tracks/r/exercises/luhn/example.R
trackler-2.2.1.151 tracks/r/exercises/luhn/example.R
trackler-2.2.1.150 tracks/r/exercises/luhn/example.R
trackler-2.2.1.149 tracks/r/exercises/luhn/example.R
trackler-2.2.1.148 tracks/r/exercises/luhn/example.R
trackler-2.2.1.147 tracks/r/exercises/luhn/example.R
trackler-2.2.1.146 tracks/r/exercises/luhn/example.R
trackler-2.2.1.145 tracks/r/exercises/luhn/example.R
trackler-2.2.1.144 tracks/r/exercises/luhn/example.R
trackler-2.2.1.143 tracks/r/exercises/luhn/example.R
trackler-2.2.1.142 tracks/r/exercises/luhn/example.R
trackler-2.2.1.141 tracks/r/exercises/luhn/example.R
trackler-2.2.1.140 tracks/r/exercises/luhn/example.R