Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Created April 5, 2016 02:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save primaryobjects/d202bc8c5f4582d77d919fb9d2089f81 to your computer and use it in GitHub Desktop.
Save primaryobjects/d202bc8c5f4582d77d919fb9d2089f81 to your computer and use it in GitHub Desktop.
[2016-04-04] Challenge #261 [Easy] verifying 3x3 magic squares
#
# [2016-04-04] Challenge #261 [Easy] verifying 3x3 magic squares
# https://www.reddit.com/r/dailyprogrammer/comments/4dccix/20160404_challenge_261_easy_verifying_3x3_magic/
# Demo at http://www.r-fiddle.org/#/fiddle?id=AgVxiDgU&version=1
#
# Kory Becker 4/4/2016
# http://primaryobjects.com
#
magicSquare <- function(input) {
# Determine the sum of a magic square row, column, diagonal.
n <- sqrt(length(input))
(n * (n ^ 2 + 1)) / 2
}
diagSums <- function(grid) {
# Verify diagonals.
y1 <- 1
y2 <- nrow(grid)
a <- c()
b <- c()
for (x in seq(ncol(grid))) {
# Top-left diagonal.
a <- c(a, grid[y1, x])
# Bottom-left diagonal.
b <- c(b, grid[y2, x])
y1 <- y1 + 1
y2 <- y2 - 1
if (y1 > nrow(grid))
break
}
c(sum(a), sum(b))
}
isMagicSquare <- function(input) {
sum <- magicSquare(input)
grid <- t(as.data.frame(split(input, ceiling(seq_along(input) / sqrt(length(input))))))
# Verify rows, columns, diagonals.
(length(which(rowSums(grid) == sum)) == nrow(grid) &&
length(which(colSums(grid) == sum)) == ncol(grid) &&
length(which(diagSums(grid) == sum)) == 2)
}
isMagicSquare(c(8, 1, 6, 3, 5, 7, 4, 9, 2))
isMagicSquare(c(2, 7, 6, 9, 5, 1, 4, 3, 8))
isMagicSquare(c(3, 5, 7, 8, 1, 6, 4, 9, 2))
isMagicSquare(c(8, 1, 6, 7, 5, 3, 4, 9, 2))
isMagicSquare(c(16,2,3,13,5,11,10,8,9,7,6,12,4,14,15,1))
isMagicSquare(1:16)
isMagicSquare(c(1,2,62,61,60,59,7,8,9,10,54,53,52,51,15,16,48,47,19,20,21,22,42,41,40,39,27,28,29,30,34,33,32,31,35,36,37,38,26,25,24,23,43,44,45,46,18,17,49,50,14,13,12,11,55,56,57,58,6,5,4,3,63,64))
> isMagicSquare(c(8, 1, 6, 3, 5, 7, 4, 9, 2))
[1] TRUE
> isMagicSquare(c(2, 7, 6, 9, 5, 1, 4, 3, 8))
[1] TRUE
> isMagicSquare(c(3, 5, 7, 8, 1, 6, 4, 9, 2))
[1] FALSE
> isMagicSquare(c(8, 1, 6, 7, 5, 3, 4, 9, 2))
[1] FALSE
> isMagicSquare(c(16,2,3,13,5,11,10,8,9,7,6,12,4,14,15,1))
[1] TRUE
> isMagicSquare(1:16)
[1] FALSE
> isMagicSquare(c(1,2,62,61,60,59,7,8,9,10,54,53,52,51,15,16,48,47,19,20,21,22,42,41,40,39,27,28,29,30,34,33,32,31,35,36,37,38,26,25,24,23,43,44,45,46 .... [TRUNCATED]
[1] TRUE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment