Finding Triangles
This Quora post answered the question: “How many triangles with integer-length sides have a perimeter of 40?” So, I wrote the following R code to obtain the answer, 33, plus the lengths of the triangles' sides. Notice how to define an empty list and how to make it “grow” to a data frame.
find_xyz <- function(s = 40)
{re <- vector(mode = "list") # an empty list
the_counter <- 0
m <- ceiling(s / 3)
for(x in 1:m)
for(y in x:s)
for(z in y:s) {
chk_sum <- sum(c(x, y, z)) == s
chk_triangle <- (x + y) > z
if(all(chk_sum, chk_triangle)) {
the_counter <- the_counter + 1
re[[the_counter]] <- c(x, y, z)
}
}
df <- do.call('rbind', re)
return(list(the_counter, df))
}
find_xyz(40)
## [[1]]
## [1] 33
##
## [[2]]
## [,1] [,2] [,3]
## [1,] 2 19 19
## [2,] 3 18 19
## [3,] 4 17 19
## [4,] 4 18 18
## [5,] 5 16 19
## [6,] 5 17 18
## [7,] 6 15 19
## [8,] 6 16 18
## [9,] 6 17 17
## [10,] 7 14 19
## [11,] 7 15 18
## [12,] 7 16 17
## [13,] 8 13 19
## [14,] 8 14 18
## [15,] 8 15 17
## [16,] 8 16 16
## [17,] 9 12 19
## [18,] 9 13 18
## [19,] 9 14 17
## [20,] 9 15 16
## [21,] 10 11 19
## [22,] 10 12 18
## [23,] 10 13 17
## [24,] 10 14 16
## [25,] 10 15 15
## [26,] 11 11 18
## [27,] 11 12 17
## [28,] 11 13 16
## [29,] 11 14 15
## [30,] 12 12 16
## [31,] 12 13 15
## [32,] 12 14 14
## [33,] 13 13 14