Skip to content

Instantly share code, notes, and snippets.

@bjulius
Created February 13, 2024 08:33
Show Gist options
  • Save bjulius/b6c8adc5e5324a6dd728b3f38b4391ef to your computer and use it in GitHub Desktop.
Save bjulius/b6c8adc5e5324a6dd728b3f38b4391ef to your computer and use it in GitHub Desktop.
Excel BI Challenge 390 - Brian Julius Hybrid Power Query/R Solution
data <- dataset$Digits
find_n_digit_numbers_optimized <- function(n) {
start <- 10^(n-1)
end <- 10^n - 1
valid_numbers <- numeric(0)
for (num in start:end) {
digit_sum <- sum(as.numeric(unlist(strsplit(as.character(num), ""))))
if (digit_sum == n) {
valid_numbers <- c(valid_numbers, num)
}
}
return(valid_numbers)
}
results_list <- lapply(unique(data), function(n) {
valid_numbers <- find_n_digit_numbers_optimized(n)
if (length(valid_numbers) > 0) {
return(data.frame(digits = rep(n, length(valid_numbers)), number = valid_numbers))
} else {
return(NULL) # Return NULL for cases where no numbers are found
}
})
results_list <- Filter(NROW, results_list)
if (length(results_list) > 0) {
results_df <- do.call(rbind, results_list)
} else {
results_df <- data.frame(digits = integer(), number = integer())
}
results_df
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment