A triangle number is given by

\[t_n = \frac{1}{2}n(n+1)\]

We want to determine if a number is triangular.

I have a helperfunction for that:

source("helpers.R")

It looks like this:

is_triangle
## function(x) {
##   if (x < 1) return(FALSE)
##   s <- sqrt(8 * x + 1)
##   s == floor(s)
## }

We can also represent a number as a combination of letters. Or rather the other way around.

Take each letter, give it the value of its position in the alphabet. Add all values togehter:

ABC -> 1, 2, 3 -> 1 + 2 + 3 =6

Let us also write a function for that:

lettervalue <- function(chars){
  chars <- toupper(chars)
  t <- unlist(strsplit(chars,""))
  sum(match(t, LETTERS))
}

We now get a list of words. How many of these, converted to a sum with the function above, is a triangle number?

wordlist <- scan("solutions/0042_words.txt", what=character(), sep=",", quiet=TRUE)

Neither the is_triangle nor lettervalues functions are vectorised, so I have to map:

library(purrr)

answer <- map_int(wordlist, lettervalue) |> 
  map_lgl(is_triangle) |> 
  sum()