。
const Table = [
[
{
"id"。"258ce34d-cba6-44a8-bdb9-e436d18701aa",
"座位": 1,
"組": 1.
},
{
"id": "60adc321-c7e3-4d34-963a-e09dc53345d0",
"座位": 2,
"組": 1.
}
],
[
{
"座位"。"空",
"組": 0.
},
{
"座位": "空",
"組": 0.
}
],
[
{
"id": "c8c3c973-351b-4314-8096-a6d12c7b01fb",
"座位": 5,
"組": 3.
},
{
"id": "1c256b45-b3f3-49cc-b7e4-29967594c4fb",
"座位"。6,
"組": 3.
}
],
[
{
"座位": "空",
"組": "empty", "group".
},
{
"座位": 0,
"組": 0.
}
],
[
{
"id": "63469f95-7deb-483c-ad7d-cf0cbdc191b1",
"座位": 9,
"組": 5.
},
{
"id": "e77c8fb3-2e0b-43f7-a9ca-1bbd8143ba59",
"座位"。10,
"組": 5.
}
]
]
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
這是一個陣列,代表餐廳中的一張桌子。在這個陣列中,還有其他陣列代表客人組。
正如你所看到的,桌子上有兩個空閑的位置。
現在的任務是讓我們來看看這個陣列。
現在的任務是撰寫一個函式,計算出一排有多少個空位。輸入是這個陣列,輸出應該是一個數字。所以在這種情況下,MaxFreeSeatsinRow(Table) => 2
例如,如果一個4人小組到達,有足夠的座位,但不是在一排。
有人知道如何計算嗎?謝謝你的幫助!
uj5u.com熱心網友回復:
如果我沒有理解錯的話,你想知道每個嵌套陣列的免費座位數?
如果是這樣的話,我想用函式式的方法可以很直接地實作:
。
const freeSeats = Table.map(row => /span> {
return row.filter(place =>/span> place. seat === "empty").length.
})
// freeSeats = [0, 2, 0, 2, 0]
那么就很容易得到最大的分組座位:
Math.max( ...freeSeats)
uj5u.com熱心網友回復:
根據你的評論,這實際上只是一個將結構扁平化為座位陣列的問題,然后找到最長的空座位連線。
我們可以撰寫一個通用的 longestStreak 函式,它接受一個謂詞函式并回傳一個接受元素串列的函式,然后根據該謂詞測驗每個元素,當它匹配時,更新當前條紋的長度和可能的最大值,當它不匹配時,將當前條紋重置為零。
我們的主函式,canSeat接受一個表,并向longestStreak提供一個謂詞,測驗一個座位的值是否為0或"空"(注:你真的想支持兩者嗎),然后向結果函式提供一個表的提取物,選擇其中的所有座位。
const longestStreak = (pred) => (xs) =>
xs .reduce (
({max, curr}, x) => pred (x)
? {max: curr >= max ? curr 1 : max, curr: curr 1} 。
: {max, curr: 0} : {max, curr: 0
, {max: 0, curr: 0}。
) .最大
const canSeat = (table)=> longestStreak
(s =>s ==0 || s =="empty")
(table .flatMap (groups => groups . map (span class="hljs-params">g => g .seat))
const Table = [[{id: "258ce34d-cba6-44a8-bdb9-e436d18701aa", seat: 1, group: 1}, {id: "60adc321-c7e3-4d34-963a-e09dc53345d0", seat: 2, group: 1}], [{Seat: "empty", group: 0}, {seat: "空", 組: 0}], [{id: "c8c3c973-351b-4314-8096-a6d12c7b01fb", seat: 5, group: 3}, {id: "1c256b45-b3f3-49cc-b7e4-29967594c4fb", seat: 6, group: 3}], [{seat: "empty", group: "empty"}, {Seat: 0, group: 0}], [{id: "63469f95-7deb-483c-ad7d-cf0cbdc191b1", seat: 9, group: 5}, {id: "e77c8fb3-2e0b-43f7-a9ca-1bbd8143ba59", seat: 10, group: 5}] []
console .log (canSeat (Table))/code>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/308805.html
標籤:
上一篇:翻轉或旋轉一維陣列
