Sur*_*fel 1 javascript arrays algorithm
如何从给定数组生成增量值数组
这个想法是创建一种菱形形状,一旦到达阵列的中间,阵列的尺寸就开始减小。换句话说,最长的数组将是包含数组中间值的数组或 (array.length/2 + 1)
如果元素不足以完成后半部分的数组,只需将其替换为“E”以指示空白,就像第二个示例一样。
example 1
var array = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p']
//the longest array in length is containing 'i' which is the value at
array.length/2 + 1
var output = [
['a'],
['b','c'],
['d','e','f'],
['g','h','i','j'],
['k','l','m'],
['n','o'],
['p']
]
example 2
var array = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t']
enter code here
//the longest array in length is containing 'k' which is the value at array.length/2 + 1
var output = [
['a'],
['b','c'],
['d','e','f'],
['g','h','i','j'],
['k','l','m','n','o'],
['p','q','r','s'],
['t','E','E'],
['E','E'],
['E]
]
Run Code Online (Sandbox Code Playgroud)
这是我尝试过的代码:
const values = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
const halfLen = values.length/2 + 1;
var topArr = [];
for(let i = 0; i < values.length; i ++) {
if(i <= halfLen) {
topArr.push(values[i])
}
}
console.log(topArr)
var filTopArr = [];
for(let i = 0; i <= topArr.length; i ++) {
let prevIndex = i - 1;
if(i === 0) {
filTopArr.push(topArr[i])
} else if(i === 1) {
filTopArr.push(topArr.slice(i, i + i + 1))
} else {
filTopArr.push(topArr.slice(i, i + i ))
}
}
console.log(filTopArr)
Run Code Online (Sandbox Code Playgroud)
我的想法是将数组分成两个不同的数组,其中顶部部分的大小将增加,第二/底部部分的大小将减小。
上面的代码有这个输出
[1, [2, 3], [3, 4], [4, 5, 6], [5, 6, 7, 8], [6, 7, 8, 9], [7, 8, 9], [8, 9], [9], []]
Run Code Online (Sandbox Code Playgroud)
一些观察结果:
输出中的字符串数量(包括填充“E”字符串)始终是完全平方数(1、4、9、16、25...等)
为了知道需要添加多少个“E”字符串,我们需要知道哪个是不小于输入大小的最小完美平方。
输出中最长(中间)子数组的大小是该完美平方的平方根。
子数组的数量是该数字的两倍减 1。
这导致以下实现:
function diamond(array) {
// Get least perfect square that is not less than the array length
const sqrt = Math.ceil(Math.sqrt(array.length));
const size = sqrt ** 2;
// Pad the array with "E" strings so to reach that perfect square size
const all = [...array, ..."E".repeat(size - array.length)];
const length = 2 * sqrt;
return Array.from({length}, (_, width) => {
return all.splice(0, Math.min(width, length - width));
}).slice(1); // Skip the first subarray that was produced (empty array)
}
// Demo using the two provided examples:
var array = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p'];
console.log(diamond(array));
var array = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t'];
console.log(diamond(array));Run Code Online (Sandbox Code Playgroud)