cartas = ['Jota', 8, 2, 6, 'Rey', 5, 3, 'Reina', "Jota", "Reina", "Rey"] <!- Salida requerida = [2,3,5, 6,8,'Jota','Reina','Rey'] Pregunta: Ordene la matriz según las reglas del juego de cartas usando un método genérico.
Un enfoque es usar una matriz con todas las tarjetas en el orden correcto como referencia y clasificar cada tarjeta ordenada por su índice en la matriz de referencia.
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);Este es un lenguaje no relacionado, pero si alguien quiere resolver esto usando Python, aquí está el código que se me ocurrió durante una entrevista que pedía la misma solución con 3 casos de prueba diferentes.
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])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 ab; }); console.log("Solution Two array", someArray); } solutionTwo(cards);