-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3.r
More file actions
44 lines (31 loc) · 1.04 KB
/
3.r
File metadata and controls
44 lines (31 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#
# Complete the 'diagonalDifference' function below.
#
# The function is expected to return an INTEGER.
# The function accepts 2D_INTEGER_ARRAY arr as parameter.
#
diagonalDifference <- function(arr) {
arr <- as.matrix(arr);
lsum <- 0;
rsum <- 0;
arrlength <- nrow(arr);
for (i in 1:arrlength) {
indextwo <- arrlength + 1 - i; # THIS IS 1 indexed not 0 indexed so its is + 1 here!!!
lsum <- lsum + as.numeric(arr[i,i]);
rsum <- rsum + as.numeric(arr[i, indextwo]);
}
return (abs(lsum - rsum));
}
stdin <- file('stdin')
open(stdin)
fptr <- file(Sys.getenv("OUTPUT_PATH"))
open(fptr, open = "w")
n <- as.integer(trimws(readLines(stdin, n = 1, warn = FALSE), which = "both"))
arr <- readLines(stdin, n = n, warn = FALSE)
arr <- unlist(lapply(trimws(arr, which = "right"), function(x) strsplit(x, " ")[[1]]))
arr <- as.integer(arr)
arr <- matrix(arr, nrow = n, ncol = n, byrow = TRUE)
result <- diagonalDifference(arr)
writeLines(as.character(result), con = fptr)
close(stdin)
close(fptr)