【发布时间】:2015-09-11 12:31:51
【问题描述】:
使用 reduce 计算数组中最大矩形的面积 矩形。每个矩形都有宽度和高度属性,如果 r 是一个矩形,面积是
r.width * r.height如果没有矩形,则返回 0,因此基本情况为 0。在 在线指令示例,reduce() 用于在 a 上形成总和 一组项目。在这种情况下,您将希望将最大值超过 一组项目(使用 JavaScript 的 Math.max(a, b) 函数。)
您必须使用一个名为 area 的函数来计算并返回一个区域的面积 长方形。它有一个参数是一个矩形对象。
你还必须定义一个函数来传递给 reduce,类似于 “The Real Reduce”子课程中的 sum_value 函数 “背包:表示”课。你必须命名这个函数 最大的。
下面的代码是课程练习的解决方案。
要完成这个练习,你应该修改窗口中的代码 以下。进行以下更改:
- 定义 area(rect) 以计算并返回矩形对象的面积。
- 将最大定义为要减少的第三个参数(已定义)。
- 使用 reduce 调用完成计算的定义。
<html>
<head>
<title>Using Reduce</title>
<link rel="stylesheet" href="../css/exercise.css"></link>
<script>
function reduce(a, base, f) {
var result = base;
for (var i = 0; i < a.length; i++)
result = f(result, a[i]);
return result;
}
// these are the rectangles to consider
r1 = {width: 9, height: 34}; // area is 306
r2 = {width: 10, height: 31}; // area is 310
r3 = {width: 11, height: 28}; // area is 308
r4 = {width: 12, height: 25}; // area is 300
r5 = {width: 13, height: 24}; // area is 312
r6 = {width: 14, height: 22}; // area is 308
r7 = {width: 15, height: 20}; // 300
r8 = {width: 16, height: 19}; // 304
r9 = {width: 17, height: 18}; // 306
r10 = {width: 18, height: 17}; // 306
r11 = {width: 19, height: 16}; // 304
r12 = {width: 20, height: 15}; // 300
r13 = {width: 22, height: 14}; // 308
r14 = {width: 24, height: 12}; // 288
r15 = {width: 28, height: 11}; // 308
// form an array of all the rectangles
rectangles = [r1, r2, r3, r4, r5, r6, r7, r8,
r9, r10, r11, r12, r13, r14, r15];
// define the function named area here:
function area(r){
return r.width * r.height;
}
// define the function named biggest here:
function biggest(biggestYet, newRect){
biggestYet = Math.max (biggestYet, newRect)
return biggestYet;
}
// complete the definition using a call to reduce:
function compute() {
// return -23; // replace with code to return the area of
// the largest rectangle in rectangles
var biggestYet = 0;
for (x = 0 ; x < rectangles.length ; x++)
{
var rArea = area ( rectangles[x]);
console.log ( "area "+ x+ "," + rArea );
biggestYet = biggest (biggestYet, rArea);
console.log ( "biggest "+ x +","+ biggestYet);
}
return biggestYet;
}
</script>
</head>
<body>
<!-- the output is displayed using HTML -->
<p>The area of the largest rectangle is:
<!-- the ? will be replaced with the answer -->
<div id = "answer">?</div></p>
<br>
<!-- a button runs compute and puts the answer into the HTML -->
<button id = "computeButton"
onclick = "x = compute();
<!-- find the document element named 'answer' -->
where = document.getElementById('answer');
<!-- insert result x as text into the HTML -->
where.innerHTML = x.toString();">Run compute()
to compute the largest rectangle.</button>
</body>
</html>
【问题讨论】:
-
有人可以帮我检查一下我的代码哪里出错了,因为我尝试了很多次,但无法让最大的功能测试正常工作吗?
-
我还是不明白你的意思?对于矩形区域,我知道功能部分是正确的。可能你能帮助我理解如何使用计算函数中的 reduce 来计算最大的函数测试吗?非常感谢。
-
rectangles.map(area).reduce(biggest, -1);
标签: javascript