cards = ['杰克', 8, 2, 6, '国王', 5, 3, '皇后', "杰克", "皇后", "国王"] 使用通用方法根据纸牌游戏规则对数组进行排序。
一种方法是使用所有卡片按正确顺序排列的数组作为参考,并根据参考数组中的索引对每张卡片进行排名。
let cards = ['Jack', 8, 2, 6, 'King', 5, 3, 'Queen',"Jack","Queen","King"];
// change this to match the rules of card game
let theRightOrder = ["Ace", 2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King"];
cards.sort((a, b) => theRightOrder.indexOf(a) - theRightOrder.indexOf(b));
console.log(cards);
此问题所需的输出必须按升序显示。其他大于 10 的物品(Jack、Queen、King)是有限的,因此我们可以为每个物品附加一个重量。
let cards = ['Jack', 8, 2, 6, 'King', 5, 3,"Queen"];
// change this to match the rules of card game
const otherItems = {
'Jack': 11,
'Queen': 12
'King': 13
}
cards.sort((a, b) => {
if(isNaN(a)) a = otherItems[a];
if(isNaN(b)) b = otherItems[b];
return a-b;
});
console.log(cards);
权重大于 10 的项目可以在
looked up
上
otherItems
,而不是在数组中查找索引
let cards = ['Jack', 8, 2, 6, 'King', 5, 3, 'Queen', "Jack",
"Queen","King"]
const otherItems = {
'Ace':1,
'Jack': 11,
'Queen': 12,
'King': 13
}
const solutionTwo= (someArray)=>{
someArray.sort((a,b)=>{
a= isNaN(a)? otherItems[a]:a;
b= isNaN(b)? otherItems[b]:b;
return a-b;
});
console.log("Solution Two array", someArray);
}
solutionTwo(cards);
这是不相关的语言,但如果有人想使用 python 解决这个问题,这是我在采访中提出的代码,要求使用 3 个不同的测试用例提供相同的解决方案。
def test_case(cards):
int_list = sorted([x for x in cards if type(x) == int])
str_list = sorted([x for x in cards if type(x) == str])
for x in str_list:
if x == "King":
str_list.remove(x)
str_list.append(x)
sorted_cards = int_list + str_list
print(f"TEST CASE = {sorted_cards}")
test_case(['Jack', 8, 2, 6, 'King', 5, 3, 'Queen'])
test_case(['Jack', 8, 2, 6, 'King', 5, 3, 'Queen', 'Jack', 'King', 'Queen', 'Queen', 'King', 'Jack'])
test_case(['Jack', 8, 2, 6, 5, 3])
func run() -> Bool {
var cards: [Any] = ["Jack", 8, 2, 6, "King", 5, 3, "Queen","Queen","king"]
let otherItems: [String: Int] = [
"Jack": 11,
"Queen": 12,
"King": 13
]
cards.sort { a, b in
var aValue = a
var bValue = b
if let aString = a as? String, let value = otherItems[aString] {
aValue = value
}
if let bString = b as? String, let value = otherItems[bString] {
bValue = value
}
if let aValue = aValue as? Int, let bValue = bValue as? Int {
return aValue < bValue
}
return false
}
return false
}
此解决方案避免了改变原始数组,而是按排序顺序提供了卡片的浅表副本。它允许使用参数来调用来指示是否:
a.
Ace
为低(默认)或高
b.需要删除重复项(默认)或保留
c.排序后的数组需要升序(默认)或降序
const handleDupes = (fl, ar) => (fl ? [...new Set(ar)] : ar);
const sortCards = (arr, aceHigh = false, removeDupes = false, descending = false) => {
const sorted = [...Array(9)].map(
(x, i) => (i + 2)
).concat(
"Jack, Queen, King".split(', ')
);
if (aceHigh) sorted.push("Ace");
else sorted.splice(0, 1, "Ace");
return handleDupes(
removeDupes,
[...arr]
.sort(
(a, b) => (
sorted.indexOf(a) > sorted.indexOf(b)
? descending ? -1 : 1
: descending ? 1 : -1
)
)
);
};
const unsorted = ['Jack', 8, 2, 6, 'King', 5, 3, 'Queen', "Jack", "Queen", "King"];
console.log(sortCards(unsorted, true, true));