【问题标题】:Minimum number of digit changes to get two arrays to have the same value. Please solve in R programming使两个数组具有相同值的最小位数更改。请在 R 编程中解决
【发布时间】:2020-12-24 09:54:22
【问题描述】:

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

这是挑战:

不允许对数字重新排序 例如,考虑两个数组: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)

【问题讨论】:

    标签: r arrays comparison


    【解决方案1】:
    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
    

    【讨论】:

    • 出现以下错误并且没有输出 str_split(a[i], "") 中的错误:找不到函数“str_split”调用:minimumMoves -> unlist 执行停止
    • library(stringr)
    • 以下一个测试用例已通过,但其余测试用例未通过 1 2468 1 8642
    • 0 16,不是吗?
    • 哦,函数的最后一行使用sum(rlt)
    猜你喜欢
    • 2019-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 2020-08-22
    • 2016-06-07
    • 1970-01-01
    相关资源
    最近更新 更多