I am pretty new to coding and I'm trying my best, but after hours and hours of research i still cant figure this out. I'm trying to make these two separate arrays the same with the minimum number of moves. I can only ++ or -- one number at a time.
This is the challenge:
No reordering of the digits is allowed For example, consider two arrays: Andrea's [123, 543] and Maria's [321, 279]. For the first digit, Andrea can increment the 1 twice to achieve 3. The 2's are equal already. Finally, she decrements her 3 twice to equal 1. It took 4 moves to reach her goal. For the second integer, she decrements 5 three times, increments 4 three times and 3 six times. It took 12 moves to convert the second array element. In total, it took 16 moves to convert both values comprising the complete array.
# Complete the 'minimumMoves' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER_ARRAY a
# 2. INTEGER_ARRAY m
#
minimumMoves <- function(a, m) {
# Write your code here
}
stdin <- file('stdin')
open(stdin)
fptr <- file(Sys.getenv("OUTPUT_PATH"))
open(fptr, open = "w")
aCount <- as.integer(trimws(readLines(stdin, n = 1, warn = FALSE), which = "both"))
a <- readLines(stdin, n = aCount, warn = FALSE)
a <- trimws(a, which = "both")
a <- as.integer(a)
mCount <- as.integer(trimws(readLines(stdin, n = 1, warn = FALSE), which = "both"))
m <- readLines(stdin, n = mCount, warn = FALSE)
m <- trimws(m, which = "both")
m <- as.integer(m)
`enter code here`result <- minimumMoves(a, m)
`enter code here`writeLines(as.character(result), con = fptr)
enter code here
close(stdin)
close(fptr)
library(stringr)
minimumMoves <- function(a, m) {
n = length(a)
rlt = numeric(n)
for (i in 1:n) {
x = as.numeric(unlist(str_split(a[i], "")))
y = as.numeric(unlist(str_split(m[i], "")))
rlt[i] = sum(abs(x - y))
}
sum(rlt)
}
a = c(123,543)
m = c(321,279)
minimumMoves(a, m)
# [1] 16