首页 > 解决方案 > 根据 int 确定应该有多少行/列

问题描述

这是挑战:

/**
 * Determines how many rows and columns your garden will
 * need to be closest to a square given a number of seeds.
 *
 * @param {number} seedCount - The number of seeds in your
 * seed packet.
 * @return {array} - [rows, columns] needed for your grid
 * layout (for example [4, 5] represents a 4 row x 5 column
 * grid)
*/
function grid(seedCount) {

  // Solution here

}

这不是编码作业,它是那些编码网站之一,我知道为什么,但这个问题真的让我很难过,我可能只是想多了,但我想知道解决方案......

编辑:第一个解决方案(不起作用)

function grid(seedCount) {
    /* Enter your solution here! */
    var num1 = Math.sqrt(seedCount)
    num1 = Math.round(num1)

    while(seedCount % num1 != 0){
        num1++

    }

    num2 = seedCount / num1
    var Arr = [num1,num2]
    return Arr 
}

标签: javascript

解决方案


首先,让我们考虑这个问题的约束:

  • 花园必须能够每平方容纳 1 颗种子。
  • 花园应该足够小,以减少浪费的空间。
  • 花园应尽可能靠近完美的广场。

由此,我们得到3个基本概念:

  • Number of seeds ≤ length × width
  • |length × width - seedCount|0尽可能接近
  • |length - width|0尽可能接近

摆脱我们的第三个约束,我们可以通过取我们拥有的种子数量的平方根并找到下一个最大整数来确定我们的长度:

const length = Math.ceil(Math.sqrt(seedCount))

一旦我们有了长度,我们可以通过将种子数除以长度来找到宽度。然而,由于这可以给我们一个非整数(表明我们不能完美除法),找到下一个最大的整数应该给我们宽度:

const width = Math.ceil(seedCount / length)

现在我们有了维度,我们所要做的就是将它们组装成一个数组并返回它们!

const gridCount = seedCount =>
{
    const length = Math.ceil(Math.sqrt(seedCount))
    const width = Math.ceil(seedCount / length)
    return [length, width]
}

推荐阅读