使两个数组具有相同值的最少数字更改次数。请用R编程解决

Minimum number of digit changes to get two arrays to have the same value. Please solve in R programming

我对编码还很陌生,我正在尽我最大的努力,但经过数小时的研究,我仍然无法弄清楚这一点。我试图用最少的移动次数使这两个独立的数组相同。我一次只能 ++ 或 -- 一个数字。

这是挑战:

不允许对数字重新排序 例如,考虑两个数组:Andrea 的 [123, 543] 和 Maria 的 [321, 279]。对于第一个数字,Andrea 可以将 1 递增两次以获得 3。2 已经相等。最后,她将 3 递减两次等于 1。完成她的目标需要 4 步。对于第二个整数,她将 5 递减 3 次,将 4 递增 3 次,将 3 递增 6 次。转换第二个数组元素用了 12 步。总共需要 16 次移动才能转换构成完整数组的两个值。

# 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