给定一个数组,能组成三角形返回最大周长,否则返回0(不可重复取值)
const arr = [2, 3, 4, 5, 10]
function solve(arr) {
const len = arr.length
let tri_len
let longest
let rest_len
let result = 0
for (let i = 0; i < len; i++) {
for (let j = i +1; j < len; j++) {
for (let k = j + 1; k < len; k++) {
tri_len = arr[i] + arr[j] + arr[k]
longest = Math.max(arr[i], arr[j], arr[k])
rest_len = tri_len - longest
if (longest < rest_len) {
result = Math.max(result, tri_len)
}
}
}
}
console.log(result)
return result
}
solve(arr)
简单记录一下问题
要求
let arr = [1, 2, 3, 4, 5, 6]
arr.mul()
// [ 1, 2, 3, 4, 5, 6, 1, 4, 9, 16, 25, 36 ]
console.log(arr)
要点有要在数组原型上添加方法,要改变this
AArray.prototype.mul = function() {
this.push(...this.map(e => e * e))
}
Array.prototype.mul = function() {
this.forEach( e => this.push(e ** 2))
}
蚂蚁问题
Ants
const arr = [2, 6, 7]
const L = 10
function solve(arr, L) {
let min = 0
let max = 0
const len = arr.length
for (let i = 0; i < arr.length; i++) {
min = Math.max(min, Math.min(arr[i], L - arr[i]))
max = Math.max(max, Math.max(arr[i], L - arr[i]))
}
return [min, max]
}
console.log(solve(arr, L))