{ "name": "Coding Interview Algorithm Questions", "order": 10, "time": "50 hours", "helpRoom": "HelpJavaScript", "challenges": [ { "id": "aff0395860f5d3034dc0bfc9", "title": "Validate US Telephone Numbers", "description": [ "Return true if the passed string looks like a valid US phone number.", "The user may fill out the form field any way they choose as long as it has the format of a valid US number. The following are examples of valid formats for US numbers (refer to the tests below for other variants):", "
555-555-5555\n(555)555-5555\n(555) 555-5555\n555 555 5555\n5555555555\n1 555 555 5555
", "For this challenge you will be presented with a string such as 800-692-7753 or 8oo-six427676;laskdjf. Your job is to validate or reject the US phone number based on any combination of the formats provided above. The area code is required. If the country code is provided, you must confirm that the country code is 1. Return true if the string is a valid US phone number; otherwise return false.", "Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code." ], "challengeSeed": [ "function telephoneCheck(str) {", " // Good luck!", " return true;", "}", "", "", "", "telephoneCheck(\"555-555-5555\");" ], "solutions": [ "var re = /^([+]?1[\\s]?)?((?:[(](?:[2-9]1[02-9]|[2-9][02-8][0-9])[)][\\s]?)|(?:(?:[2-9]1[02-9]|[2-9][02-8][0-9])[\\s.-]?)){1}([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2}[\\s.-]?){1}([0-9]{4}){1}$/;\n\nfunction telephoneCheck(str) {\n return re.test(str);\n}\n\ntelephoneCheck(\"555-555-5555\");" ], "tests": [ "assert(typeof telephoneCheck(\"555-555-5555\") === \"boolean\", 'message: telephoneCheck(\"555-555-5555\") should return a boolean.');", "assert(telephoneCheck(\"1 555-555-5555\") === true, 'message: telephoneCheck(\"1 555-555-5555\") should return true.');", "assert(telephoneCheck(\"1 (555) 555-5555\") === true, 'message: telephoneCheck(\"1 (555) 555-5555\") should return true.');", "assert(telephoneCheck(\"5555555555\") === true, 'message: telephoneCheck(\"5555555555\") should return true.');", "assert(telephoneCheck(\"555-555-5555\") === true, 'message: telephoneCheck(\"555-555-5555\") should return true.');", "assert(telephoneCheck(\"(555)555-5555\") === true, 'message: telephoneCheck(\"(555)555-5555\") should return true.');", "assert(telephoneCheck(\"1(555)555-5555\") === true, 'message: telephoneCheck(\"1(555)555-5555\") should return true.');", "assert(telephoneCheck(\"555-5555\") === false, 'message: telephoneCheck(\"555-5555\") should return false.');", "assert(telephoneCheck(\"5555555\") === false, 'message: telephoneCheck(\"5555555\") should return false.');", "assert(telephoneCheck(\"1 555)555-5555\") === false, 'message: telephoneCheck(\"1 555)555-5555\") should return false.');", "assert(telephoneCheck(\"1 555 555 5555\") === true, 'message: telephoneCheck(\"1 555 555 5555\") should return true.');", "assert(telephoneCheck(\"1 456 789 4444\") === true, 'message: telephoneCheck(\"1 456 789 4444\") should return true.');", "assert(telephoneCheck(\"123**&!!asdf#\") === false, 'message: telephoneCheck(\"123**&!!asdf#\") should return false.');", "assert(telephoneCheck(\"55555555\") === false, 'message: telephoneCheck(\"55555555\") should return false.');", "assert(telephoneCheck(\"(6054756961)\") === false, 'message: telephoneCheck(\"(6054756961)\") should return false');", "assert(telephoneCheck(\"2 (757) 622-7382\") === false, 'message: telephoneCheck(\"2 (757) 622-7382\") should return false.');", "assert(telephoneCheck(\"0 (757) 622-7382\") === false, 'message: telephoneCheck(\"0 (757) 622-7382\") should return false.');", "assert(telephoneCheck(\"-1 (757) 622-7382\") === false, 'message: telephoneCheck(\"-1 (757) 622-7382\") should return false');", "assert(telephoneCheck(\"2 757 622-7382\") === false, 'message: telephoneCheck(\"2 757 622-7382\") should return false.');", "assert(telephoneCheck(\"10 (757) 622-7382\") === false, 'message: telephoneCheck(\"10 (757) 622-7382\") should return false.');", "assert(telephoneCheck(\"27576227382\") === false, 'message: telephoneCheck(\"27576227382\") should return false.');", "assert(telephoneCheck(\"(275)76227382\") === false, 'message: telephoneCheck(\"(275)76227382\") should return false.');", "assert(telephoneCheck(\"2(757)6227382\") === false, 'message: telephoneCheck(\"2(757)6227382\") should return false.');", "assert(telephoneCheck(\"2(757)622-7382\") === false, 'message: telephoneCheck(\"2(757)622-7382\") should return false.');", "assert(telephoneCheck(\"555)-555-5555\") === false, 'message: telephoneCheck(\"555)-555-5555\") should return false.');", "assert(telephoneCheck(\"(555-555-5555\") === false, 'message: telephoneCheck(\"(555-555-5555\") should return false.');", "assert(telephoneCheck(\"(555)5(55?)-5555\") === false, 'message: telephoneCheck(\"(555)5(55?)-5555\") should return false.');" ], "type": "bonfire", "MDNlinks": [ "RegExp" ], "challengeType": 5, "translations": { "es": { "title": "Valida Números Telefónicos de los EEUU", "description": [ "Haz que la función devuelva true (verdadero) si el texto introducido parece un número válido en los EEUU.", "El usuario debe llenar el campo del formulario de la forma que desee siempre y cuando tenga el formato de un número válido en los EEUU. Los números mostrados a continuación tienen formatos válidos en los EEUU:", "
555-555-5555\n(555)555-5555\n(555) 555-5555\n555 555 5555\n5555555555\n1 555 555 5555
", "Para esta prueba se te presentará una cadena de texto como por ejemplo: 800-692-7753 o 8oo-six427676;laskdjf. Tu trabajo consiste en validar o rechazar el número telefónico tomando como base cualquier combinación de los formatos anteriormente presentados. El código de área es requrido. Si el código de país es provisto, debes confirmar que este es 1. La función debe devolver true si la cadena de texto es un número telefónico válido en los EEUU; de lo contrario, debe devolver false.", "Recuerda utilizar Read-Search-Ask si te sientes atascado. Intenta programar en pareja. Escribe tu propio código." ] }, "it": { "title": "Verifica i numeri telefonici degli Stati Uniti", "description": [ "Ritorna true se la stringa passata come argomento è un numero valido negli Stati Uniti.", "L'utente può digitare qualunque stringa nel campo di inserimento, purchè sia un numero di telefono valido negli Stati Uniti. Qui sotto alcuni esempi di numeri di telefono validi negli Stati Uniti (fai riferimento ai test per le altre varianti):", "
555-555-5555\n(555)555-5555\n(555) 555-5555\n555 555 5555\n5555555555\n1 555 555 5555
", "In questo problema ti saranno presentate delle stringe come 800-692-7753 o 8oo-six427676;laskdjf. Il tuo obiettivo è di validare o rigettare il numero di telefono basato su una qualunque combinazione dei formati specificati sopra. Il prefisso di zona è obbligatorio. Se il prefisso nazionale è presente, devi confermare che corrisponda a 1. Ritorna true se la stringa è un numero di telefono valido negli Stati Uniti; altrimenti ritorna false.", "Ricorda di usare Leggi-Cerca-Chiedi se rimani bloccato. Prova a programmare in coppia. Scrivi il codice da te." ] }, "pt-br": { "title": "Valida números telefônicos dos EUA", "description": [ "Retorna true se a string passada é um número telefônico válido nos EUA.", "O usuário pode preencher o campo de qualquer maneira com tanto que seja um número válido nos EUA. Os seguintes exemplos são formatos válidos para números de telefone nos EUA (baseie-se nos testes abaixo para outras variações):", "
555-555-5555\n(555)555-5555\n(555) 555-5555\n555 555 5555\n5555555555\n1 555 555 5555
", "Para esse desafio será dado a você uma string como 800-692-7753 ou 8oo-six427676;laskdjf. Seu trabalho é validar ou rejeitar o número de telefone dos EUA baseado nos exmplos de formatos fornecidos acima. O código de área é obrigatório. Se o código do país for fornecido, você deve confirmar que o código do país é 1. Retorne true se a string é um número válido nos EUA; caso contrário retorne false.", "Lembre-se de usar Ler-Procurar-Perguntar se você ficar preso. Tente programar em par. Escreva seu próprio código." ] } } }, { "id": "a3f503de51cf954ede28891d", "title": "Symmetric Difference", "description": [ "Create a function that takes two or more arrays and returns an array of the symmetric difference ( or ) of the provided arrays.", "Given two sets (for example set A = {1, 2, 3} and set B = {2, 3, 4}), the mathematical term \"symmetric difference\" of two sets is the set of elements which are in either of the two sets, but not in both (A △ B = C = {1, 4}). For every additional symmetric difference you take (say on a set D = {2, 3}), you should get the set with elements which are in either of the two the sets but not both (C △ D = {1, 4} △ {2, 3} = {1, 2, 3, 4}). The resulting array must contain only unique values (no duplicates).", "Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code." ], "challengeSeed": [ "function sym(args) {", " return args;", "}", "", "sym([1, 2, 3], [5, 2, 1, 4]);" ], "solutions": [ "function sym() {\n var arrays = [].slice.call(arguments);\n return arrays.reduce(function (symDiff, arr) {\n return symDiff.concat(arr).filter(function (val, idx, theArr) {\n return theArr.indexOf(val) === idx \n && (symDiff.indexOf(val) === -1 || arr.indexOf(val) === -1);\n });\n });\n}\nsym([1, 2, 3], [5, 2, 1, 4]);\n" ], "tests": [ "assert.sameMembers(sym([1, 2, 3], [5, 2, 1, 4]), [3, 4, 5], 'message: sym([1, 2, 3], [5, 2, 1, 4]) should return [3, 4, 5].');", "assert.equal(sym([1, 2, 3], [5, 2, 1, 4]).length, 3, 'message: sym([1, 2, 3], [5, 2, 1, 4]) should contain only three elements.');", "assert.sameMembers(sym([1, 2, 3, 3], [5, 2, 1, 4]), [3, 4, 5], 'message: sym([1, 2, 3, 3], [5, 2, 1, 4]) should return [3, 4, 5].');", "assert.equal(sym([1, 2, 3, 3], [5, 2, 1, 4]).length, 3, 'message: sym([1, 2, 3, 3], [5, 2, 1, 4]) should contain only three elements.');", "assert.sameMembers(sym([1, 2, 3], [5, 2, 1, 4, 5]), [3, 4, 5], 'message: sym([1, 2, 3], [5, 2, 1, 4, 5]) should return [3, 4, 5].');", "assert.equal(sym([1, 2, 3], [5, 2, 1, 4, 5]).length, 3, 'message: sym([1, 2, 3], [5, 2, 1, 4, 5]) should contain only three elements.');", "assert.sameMembers(sym([1, 2, 5], [2, 3, 5], [3, 4, 5]), [1, 4, 5], 'message: sym([1, 2, 5], [2, 3, 5], [3, 4, 5]) should return [1, 4, 5]');", "assert.equal(sym([1, 2, 5], [2, 3, 5], [3, 4, 5]).length, 3, 'message: sym([1, 2, 5], [2, 3, 5], [3, 4, 5]) should contain only three elements.');", "assert.sameMembers(sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5]), [1, 4, 5], 'message: sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5]) should return [1, 4, 5].');", "assert.equal(sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5]).length, 3, 'message: sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5]) should contain only three elements.');", "assert.sameMembers(sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3]), [2, 3, 4, 6, 7], 'message: sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3]) should return [2, 3, 4, 6, 7].');", "assert.equal(sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3]).length, 5, 'message: sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3]) should contain only five elements.');", "assert.sameMembers(sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1]), [1, 2, 4, 5, 6, 7, 8, 9], 'message: sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1]) should return [1, 2, 4, 5, 6, 7, 8, 9].');", "assert.equal(sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1]).length, 8, 'message: sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1]) should contain only eight elements.');" ], "type": "bonfire", "MDNlinks": [ "Array.prototype.reduce()", "Symmetric Difference" ], "challengeType": 5, "translations": { "es": { "title": "Diferencia Simétrica", "description": [ "Crea una función que acepte dos o más arreglos y que devuelva un arreglo conteniendo la diferenia simétrica entre ambos", "En Matemáticas, el término 'diferencia simétrica' se refiere a los elementos en dos conjuntos que están en el primer conjunto o en el segundo, pero no en ambos.", "Recuerda utilizar Read-Search-Ask si te sientes atascado. Intenta programar en pareja. Escribe tu propio código." ] }, "it": { "title": "Differenza Simmetrica", "description": [ "Crea una funzione che accetti due o più array e che ritorni un array contenente la differenza simmetrica ( o ) degli stessi.", "Dati due insiemi (per esempio l'insieme A = {1, 2, 3} e l'insieme B = {2, 3, 4}, il termine matematico \"differenza simmetrica\" di due insiemi è l'insieme degli elementi che sono in almeno uno dei due insiemi, ma non in entrambi (A △ B = C = {1, 4}). Per ogni differenza simmetrica aggiuntiva che fai (per esempio su un insieme D = {2, 3}), devi prendere l'insieme degli elementi che sono in almeno uno dei due insiemi ma non in entrambi (C △ D = {1, 4} △ {2, 3} = {1, 2, 3, 4}).", "Ricorda di usare Leggi-Cerca-Chiedi se rimani bloccato. Prova a programmare in coppia. Scrivi il codice da te." ] }, "pt-br": { "title": "Diferença Simétrica", "description": [ "Crie uma função que recebe duas ou mais matrizes e retorna a matriz diferença simétrica ( ou ) das matrizes fornecidas.", "Dado dois conjuntos (por exemplo conjunto A = {1, 2, 3} e conjunto B = {2, 3, 4}), o termo matemático \"diferença simétrica\" dos dois cojuntos é o conjunto dos elementos que estão em um dos conjuntos, mas não nos dois (A △ B = C = {1, 4}). Para cada diferença simétrica adicional que você faz (digamos em um terceiro conjunto D = {2, 3}), voce deve retornar o conjunto no qual os elementos estão em um dos conjuntos mas não nos dois (C △ D = {1, 4} △ {2, 3} = {1, 2, 3, 4}). O conjunto final deve ter somentes valores únicos (sem números repetidos).", "Lembre-se de usar Ler-Procurar-Perguntar se você ficar preso. Tente programar em par. Escreva seu próprio código." ] } } }, { "id": "aa2e6f85cab2ab736c9a9b24", "title": "Exact Change", "description": [ "Design a cash register drawer function checkCashRegister() that accepts purchase price as the first argument (price), payment as the second argument (cash), and cash-in-drawer (cid) as the third argument.", "cid is a 2D array listing available currency.", "Return the string \"Insufficient Funds\" if cash-in-drawer is less than the change due or if you cannot return the exact change. Return the string \"Closed\" if cash-in-drawer is equal to the change due.", "Otherwise, return change in coin and bills, sorted in highest to lowest order.", "Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code.", "
Currency UnitAmount
Penny$0.01 (PENNY)
Nickel$0.05 (NICKEL)
Dime$0.1 (DIME)
Quarter$0.25 (QUARTER)
Dollar$1 (DOLLAR)
Five Dollars$5 (FIVE)
Ten Dollars$10 (TEN)
Twenty Dollars$20 (TWENTY)
One-hundred Dollars$100 (ONE HUNDRED)
" ], "challengeSeed": [ "function checkCashRegister(price, cash, cid) {", " var change;", " // Here is your change, ma'am.", " return change;", "}", "", "// Example cash-in-drawer array:", "// [[\"PENNY\", 1.01],", "// [\"NICKEL\", 2.05],", "// [\"DIME\", 3.1],", "// [\"QUARTER\", 4.25],", "// [\"ONE\", 90],", "// [\"FIVE\", 55],", "// [\"TEN\", 20],", "// [\"TWENTY\", 60],", "// [\"ONE HUNDRED\", 100]]", "", "checkCashRegister(19.5, 20, [[\"PENNY\", 1.01], [\"NICKEL\", 2.05], [\"DIME\", 3.1], [\"QUARTER\", 4.25], [\"ONE\", 90], [\"FIVE\", 55], [\"TEN\", 20], [\"TWENTY\", 60], [\"ONE HUNDRED\", 100]]);" ], "solutions": [ "var denom = [\n\t{ name: 'ONE HUNDRED', val: 100},\n\t{ name: 'TWENTY', val: 20},\n\t{ name: 'TEN', val: 10},\n\t{ name: 'FIVE', val: 5},\n\t{ name: 'ONE', val: 1},\n\t{ name: 'QUARTER', val: 0.25},\n\t{ name: 'DIME', val: 0.1},\n\t{ name: 'NICKEL', val: 0.05},\n\t{ name: 'PENNY', val: 0.01}\n];\n\nfunction checkCashRegister(price, cash, cid) {\n var change = cash - price;\n var register = cid.reduce(function(acc, curr) {\n acc.total += curr[1];\n acc[curr[0]] = curr[1];\n return acc;\n }, {total: 0});\n if(register.total === change) {\n return 'Closed';\n }\n if(register.total < change) {\n return 'Insufficient Funds';\n }\n var change_arr = denom.reduce(function(acc, curr) {\n var value = 0;\n while(register[curr.name] > 0 && change >= curr.val) {\n change -= curr.val;\n register[curr.name] -= curr.val;\n value += curr.val;\n change = Math.round(change * 100) / 100;\n }\n if(value > 0) {\n acc.push([ curr.name, value ]);\n }\n return acc;\n }, []);\n if(change_arr.length < 1 || change > 0) {\n return \"Insufficient Funds\";\n }\n return change_arr;\n}" ], "tests": [ "assert.isArray(checkCashRegister(19.5, 20, [[\"PENNY\", 1.01], [\"NICKEL\", 2.05], [\"DIME\", 3.1], [\"QUARTER\", 4.25], [\"ONE\", 90], [\"FIVE\", 55], [\"TEN\", 20], [\"TWENTY\", 60], [\"ONE HUNDRED\", 100]]), 'message: checkCashRegister(19.5, 20, [[\"PENNY\", 1.01], [\"NICKEL\", 2.05], [\"DIME\", 3.1], [\"QUARTER\", 4.25], [\"ONE\", 90], [\"FIVE\", 55], [\"TEN\", 20], [\"TWENTY\", 60], [\"ONE HUNDRED\", 100]]) should return an array.');", "assert.isString(checkCashRegister(19.5, 20, [[\"PENNY\", 0.01], [\"NICKEL\", 0], [\"DIME\", 0], [\"QUARTER\", 0], [\"ONE\", 0], [\"FIVE\", 0], [\"TEN\", 0], [\"TWENTY\", 0], [\"ONE HUNDRED\", 0]]), 'message: checkCashRegister(19.5, 20, [[\"PENNY\", 0.01], [\"NICKEL\", 0], [\"DIME\", 0], [\"QUARTER\", 0], [\"ONE\", 0], [\"FIVE\", 0], [\"TEN\", 0], [\"TWENTY\", 0], [\"ONE HUNDRED\", 0]]) should return a string.');", "assert.isString(checkCashRegister(19.5, 20, [[\"PENNY\", 0.5], [\"NICKEL\", 0], [\"DIME\", 0], [\"QUARTER\", 0], [\"ONE\", 0], [\"FIVE\", 0], [\"TEN\", 0], [\"TWENTY\", 0], [\"ONE HUNDRED\", 0]]), 'message: checkCashRegister(19.5, 20, [[\"PENNY\", 0.5], [\"NICKEL\", 0], [\"DIME\", 0], [\"QUARTER\", 0], [\"ONE\", 0], [\"FIVE\", 0], [\"TEN\", 0], [\"TWENTY\", 0], [\"ONE HUNDRED\", 0]]) should return a string.');", "assert.deepEqual(checkCashRegister(19.5, 20, [[\"PENNY\", 1.01], [\"NICKEL\", 2.05], [\"DIME\", 3.1], [\"QUARTER\", 4.25], [\"ONE\", 90], [\"FIVE\", 55], [\"TEN\", 20], [\"TWENTY\", 60], [\"ONE HUNDRED\", 100]]), [[\"QUARTER\", 0.5]], 'message: checkCashRegister(19.5, 20, [[\"PENNY\", 1.01], [\"NICKEL\", 2.05], [\"DIME\", 3.1], [\"QUARTER\", 4.25], [\"ONE\", 90], [\"FIVE\", 55], [\"TEN\", 20], [\"TWENTY\", 60], [\"ONE HUNDRED\", 100]]) should return [[\"QUARTER\", 0.5]].');", "assert.deepEqual(checkCashRegister(3.26, 100, [[\"PENNY\", 1.01], [\"NICKEL\", 2.05], [\"DIME\", 3.1], [\"QUARTER\", 4.25], [\"ONE\", 90], [\"FIVE\", 55], [\"TEN\", 20], [\"TWENTY\", 60], [\"ONE HUNDRED\", 100]]), [[\"TWENTY\", 60], [\"TEN\", 20], [\"FIVE\", 15], [\"ONE\", 1], [\"QUARTER\", 0.5], [\"DIME\", 0.2], [\"PENNY\", 0.04]], 'message: checkCashRegister(3.26, 100, [[\"PENNY\", 1.01], [\"NICKEL\", 2.05], [\"DIME\", 3.1], [\"QUARTER\", 4.25], [\"ONE\", 90], [\"FIVE\", 55], [\"TEN\", 20], [\"TWENTY\", 60], [\"ONE HUNDRED\", 100]]) should return [[\"TWENTY\", 60], [\"TEN\", 20], [\"FIVE\", 15], [\"ONE\", 1], [\"QUARTER\", 0.5], [\"DIME\", 0.2], [\"PENNY\", 0.04]].');", "assert.deepEqual(checkCashRegister(19.5, 20, [[\"PENNY\", 0.01], [\"NICKEL\", 0], [\"DIME\", 0], [\"QUARTER\", 0], [\"ONE\", 0], [\"FIVE\", 0], [\"TEN\", 0], [\"TWENTY\", 0], [\"ONE HUNDRED\", 0]]), \"Insufficient Funds\", 'message: checkCashRegister(19.5, 20, [[\"PENNY\", 0.01], [\"NICKEL\", 0], [\"DIME\", 0], [\"QUARTER\", 0], [\"ONE\", 0], [\"FIVE\", 0], [\"TEN\", 0], [\"TWENTY\", 0], [\"ONE HUNDRED\", 0]]) should return \"Insufficient Funds\".');", "assert.deepEqual(checkCashRegister(19.5, 20, [[\"PENNY\", 0.01], [\"NICKEL\", 0], [\"DIME\", 0], [\"QUARTER\", 0], [\"ONE\", 1], [\"FIVE\", 0], [\"TEN\", 0], [\"TWENTY\", 0], [\"ONE HUNDRED\", 0]]), \"Insufficient Funds\", 'message: checkCashRegister(19.5, 20, [[\"PENNY\", 0.01], [\"NICKEL\", 0], [\"DIME\", 0], [\"QUARTER\", 0], [\"ONE\", 1], [\"FIVE\", 0], [\"TEN\", 0], [\"TWENTY\", 0], [\"ONE HUNDRED\", 0]]) should return \"Insufficient Funds\".');", "assert.deepEqual(checkCashRegister(19.5, 20, [[\"PENNY\", 0.5], [\"NICKEL\", 0], [\"DIME\", 0], [\"QUARTER\", 0], [\"ONE\", 0], [\"FIVE\", 0], [\"TEN\", 0], [\"TWENTY\", 0], [\"ONE HUNDRED\", 0]]), \"Closed\", 'message: checkCashRegister(19.5, 20, [[\"PENNY\", 0.5], [\"NICKEL\", 0], [\"DIME\", 0], [\"QUARTER\", 0], [\"ONE\", 0], [\"FIVE\", 0], [\"TEN\", 0], [\"TWENTY\", 0], [\"ONE HUNDRED\", 0]]) should return \"Closed\".');" ], "type": "bonfire", "MDNlinks": [ "Global Object", "Floating Point Guide" ], "challengeType": 5, "translations": { "es": { "title": "Cambio Exacto", "description": [ "Crea una función que simule una caja registradora que acepte el precio de compra como el primer argumento, la cantidad recibida como el segundo argumento, y la cantidad de dinero disponible en la registradora (cid) como tercer argumento", "cid es un arreglo bidimensional que lista la cantidad de dinero disponible", "La función debe devolver la cadena de texto \"Insufficient Funds\" si el cid es menor al cambio requerido. También debe devolver \"Closed\" si el cid es igual al cambio", "De no ser el caso, devuelve el cambio en monedas y billetes, ordenados de mayor a menor denominación.", "Recuerda utilizar Read-Search-Ask si te sientes atascado. Intenta programar en pareja. Escribe tu propio código." ] }, "it": { "title": "Cambio Esatto", "description": [ "Scrivi una funzione che simuli un registro di cassa chiamata checkCashRegister() che accetti il prezzo degli articoli come primo argomento (price), la somma pagata (cash), e la somma disponibile nel registratore di cassa (cid) come terzo argomento.", "cid è un array a due dimensioni che contiene la quantità di monete e banconote disponibili.", "Ritorna la stringa \"Insufficient Funds\" se la quantità di denaro disponibile nel registratore di cassa non è abbastanza per restituire il resto. Ritorna la stringa \"Closed\" se il denaro disponibile è esattamente uguale al resto.", "Altrimenti, ritorna il resto in monete e banconote, ordinate da quelle con valore maggiore a quelle con valore minore.", "Ricorda di usare Leggi-Cerca-Chiedi se rimani bloccato. Prova a programmare in coppia. Scrivi il codice da te." ] }, "pt-br": { "title": "Troco Exato", "description": [ "Crie uma função que simula uma caixa registradora chamada checkCashRegister() e aceita o valor da compra como primeiro argumento (price), pagamento como segundo argumento (cash), e o dinheiro na caixa registradora (cid) como terceiro argumento.", "cid é uma matriz bidimensional que lista o dinheiro disponível.", "Retorne a string \"Insufficient Funds\" se o dinheiro na caixa registradora é menor do que o troco ou se não é possível retornar o troco exato. Retorne a string \"Closed\" se o dinheiro na caixa é igual ao troco.", "Case cotrário, retorne o troco em moedas e notas, ordenado do maior para menor.", "Lembre-se de usar Ler-Procurar-Perguntar se você ficar preso. Tente programar em par. Escreva seu próprio código.", "
Currency UnitAmount
Penny$0.01 (PENNY)
Nickel$0.05 (NICKEL)
Dime$0.1 (DIME)
Quarter$0.25 (QUARTER)
Dollar$1 (DOLLAR)
Five Dollars$5 (FIVE)
Ten Dollars$10 (TEN)
Twenty Dollars$20 (TWENTY)
One-hundred Dollars$100 (ONE HUNDRED)
" ] } } }, { "id": "a56138aff60341a09ed6c480", "title": "Inventory Update", "description": [ "Compare and update the inventory stored in a 2D array against a second 2D array of a fresh delivery. Update the current existing inventory item quantities (in arr1). If an item cannot be found, add the new item and quantity into the inventory array. The returned inventory array should be in alphabetical order by item.", "Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code." ], "challengeSeed": [ "function updateInventory(arr1, arr2) {", " // All inventory must be accounted for or you're fired!", " return arr1;", "}", "", "// Example inventory lists", "var curInv = [", " [21, \"Bowling Ball\"],", " [2, \"Dirty Sock\"],", " [1, \"Hair Pin\"],", " [5, \"Microphone\"]", "];", "", "var newInv = [", " [2, \"Hair Pin\"],", " [3, \"Half-Eaten Apple\"],", " [67, \"Bowling Ball\"],", " [7, \"Toothpaste\"]", "];", "", "updateInventory(curInv, newInv);" ], "solutions": [ "function updateInventory(arr1, arr2) {\n arr2.forEach(function(item) {\n createOrUpdate(arr1, item);\n });\n // All inventory must be accounted for or you're fired!\n return arr1;\n}\n\nfunction createOrUpdate(arr1, item) {\n var index = -1;\n while (++index < arr1.length) {\n if (arr1[index][1] === item[1]) {\n arr1[index][0] += item[0];\n return;\n }\n if (arr1[index][1] > item[1]) {\n break;\n }\n }\n arr1.splice(index, 0, item);\n}\n\n// Example inventory lists\nvar curInv = [\n [21, 'Bowling Ball'],\n [2, 'Dirty Sock'],\n [1, 'Hair Pin'],\n [5, 'Microphone']\n];\n\nvar newInv = [\n [2, 'Hair Pin'],\n [3, 'Half-Eaten Apple'],\n [67, 'Bowling Ball'],\n [7, 'Toothpaste']\n];\n\nupdateInventory(curInv, newInv);\n" ], "tests": [ "assert.isArray(updateInventory([[21, \"Bowling Ball\"], [2, \"Dirty Sock\"], [1, \"Hair Pin\"], [5, \"Microphone\"]], [[2, \"Hair Pin\"], [3, \"Half-Eaten Apple\"], [67, \"Bowling Ball\"], [7, \"Toothpaste\"]]), 'message: The function updateInventory should return an array.');", "assert.equal(updateInventory([[21, \"Bowling Ball\"], [2, \"Dirty Sock\"], [1, \"Hair Pin\"], [5, \"Microphone\"]], [[2, \"Hair Pin\"], [3, \"Half-Eaten Apple\"], [67, \"Bowling Ball\"], [7, \"Toothpaste\"]]).length, 6, 'message: updateInventory([[21, \"Bowling Ball\"], [2, \"Dirty Sock\"], [1, \"Hair Pin\"], [5, \"Microphone\"]], [[2, \"Hair Pin\"], [3, \"Half-Eaten Apple\"], [67, \"Bowling Ball\"], [7, \"Toothpaste\"]]) should return an array with a length of 6.');", "assert.deepEqual(updateInventory([[21, \"Bowling Ball\"], [2, \"Dirty Sock\"], [1, \"Hair Pin\"], [5, \"Microphone\"]], [[2, \"Hair Pin\"], [3, \"Half-Eaten Apple\"], [67, \"Bowling Ball\"], [7, \"Toothpaste\"]]), [[88, \"Bowling Ball\"], [2, \"Dirty Sock\"], [3, \"Hair Pin\"], [3, \"Half-Eaten Apple\"], [5, \"Microphone\"], [7, \"Toothpaste\"]], 'message: updateInventory([[21, \"Bowling Ball\"], [2, \"Dirty Sock\"], [1, \"Hair Pin\"], [5, \"Microphone\"]], [[2, \"Hair Pin\"], [3, \"Half-Eaten Apple\"], [67, \"Bowling Ball\"], [7, \"Toothpaste\"]]) should return [[88, \"Bowling Ball\"], [2, \"Dirty Sock\"], [3, \"Hair Pin\"], [3, \"Half-Eaten Apple\"], [5, \"Microphone\"], [7, \"Toothpaste\"]].');", "assert.deepEqual(updateInventory([[21, \"Bowling Ball\"], [2, \"Dirty Sock\"], [1, \"Hair Pin\"], [5, \"Microphone\"]], []), [[21, \"Bowling Ball\"], [2, \"Dirty Sock\"], [1, \"Hair Pin\"], [5, \"Microphone\"]], 'message: updateInventory([[21, \"Bowling Ball\"], [2, \"Dirty Sock\"], [1, \"Hair Pin\"], [5, \"Microphone\"]], []) should return [[21, \"Bowling Ball\"], [2, \"Dirty Sock\"], [1, \"Hair Pin\"], [5, \"Microphone\"]].');", "assert.deepEqual(updateInventory([], [[2, \"Hair Pin\"], [3, \"Half-Eaten Apple\"], [67, \"Bowling Ball\"], [7, \"Toothpaste\"]]), [[67, \"Bowling Ball\"], [2, \"Hair Pin\"], [3, \"Half-Eaten Apple\"], [7, \"Toothpaste\"]], 'message: updateInventory([], [[2, \"Hair Pin\"], [3, \"Half-Eaten Apple\"], [67, \"Bowling Ball\"], [7, \"Toothpaste\"]]) should return [[67, \"Bowling Ball\"], [2, \"Hair Pin\"], [3, \"Half-Eaten Apple\"], [7, \"Toothpaste\"]].');", "assert.deepEqual(updateInventory([[0, \"Bowling Ball\"], [0, \"Dirty Sock\"], [0, \"Hair Pin\"], [0, \"Microphone\"]], [[1, \"Hair Pin\"], [1, \"Half-Eaten Apple\"], [1, \"Bowling Ball\"], [1, \"Toothpaste\"]]), [[1, \"Bowling Ball\"], [0, \"Dirty Sock\"], [1, \"Hair Pin\"], [1, \"Half-Eaten Apple\"], [0, \"Microphone\"], [1, \"Toothpaste\"]], 'message: updateInventory([[0, \"Bowling Ball\"], [0, \"Dirty Sock\"], [0, \"Hair Pin\"], [0, \"Microphone\"]], [[1, \"Hair Pin\"], [1, \"Half-Eaten Apple\"], [1, \"Bowling Ball\"], [1, \"Toothpaste\"]]) should return [[1, \"Bowling Ball\"], [0, \"Dirty Sock\"], [1, \"Hair Pin\"], [1, \"Half-Eaten Apple\"], [0, \"Microphone\"], [1, \"Toothpaste\"]].');" ], "type": "bonfire", "MDNlinks": [ "Global Array Object" ], "challengeType": 5, "translations": { "es": { "title": "Actualizando el Inventario", "description": [ "Compara y actualiza el inventario actual, almacenado en un arreglo bidimensional, contra otro arreglo bidimensional de inventario nuevo. Actualiza las cantidades en el inventario actual y, en caso de recibir una nueva mercancía, añade su nombre y la cantidad recibida al arreglo del inventario en orden alfabético.", "Recuerda utilizar Read-Search-Ask si te sientes atascado. Intenta programar en pareja. Escribe tu propio código." ] }, "it": { "title": "Aggiornamento dell'Inventario", "description": [ "Confronta e aggiorna l'inventario, contenuto in un array bidimensionale, con un secondo array bidimensionale relativo ad una nuova consegna. Aggiorna le quantità disponibili in inventario (dentro arr1). Se uno degli articoli non è presente nell'inventario, aggiungi allo stesso il nuovo articolo e la sua quantità. Ritorna un array con l'inventario aggiornato, che deve essere ordinato alfabeticamente per articolo.", "Ricorda di usare Leggi-Cerca-Chiedi se rimani bloccato. Prova a programmare in coppia. Scrivi il codice da te." ] }, "pt-br": { "title": "Atualizando Inventário", "description": [ "Compare e atualize o inventário armazenado em um matriz 2D contra uma segunda matriz 2D de uma entrega recente. Atualize a quantidade de itens no inventário atual (em arr1). Se um item não pode ser encontrado, adicione um novo item e a sua quantidade na matriz do inventário. O inventário retornado deve estar em ordem alfabética por item.", "Lembre-se de usar Ler-Procurar-Perguntar se você ficar preso. Tente programar em par. Escreva seu próprio código." ] } } }, { "id": "a7bf700cd123b9a54eef01d5", "title": "No Repeats Please", "description": [ "Return the number of total permutations of the provided string that don't have repeated consecutive letters. Assume that all characters in the provided string are each unique.", "For example, aab should return 2 because it has 6 total permutations (aab, aab, aba, aba, baa, baa), but only 2 of them (aba and aba) don't have the same letter (in this case a) repeating.", "Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code." ], "challengeSeed": [ "function permAlone(str) {", " return str;", "}", "", "permAlone('aab');" ], "solutions": [ "function permAlone(str) {\n return permutor(str).filter(function(perm) {\n return !perm.match(/(.)\\1/g);\n }).length;\n}\n\nfunction permutor(str) {\n // http://staff.roguecc.edu/JMiller/JavaScript/permute.html\n //permArr: Global array which holds the list of permutations\n //usedChars: Global utility array which holds a list of \"currently-in-use\" characters\n var permArr = [], usedChars = [];\n function permute(input) {\n //convert input into a char array (one element for each character)\n var i, ch, chars = input.split(\"\");\n for (i = 0; i < chars.length; i++) {\n //get and remove character at index \"i\" from char array\n ch = chars.splice(i, 1);\n //add removed character to the end of used characters\n usedChars.push(ch);\n //when there are no more characters left in char array to add, add used chars to list of permutations\n if (chars.length === 0) permArr[permArr.length] = usedChars.join(\"\");\n //send characters (minus the removed one from above) from char array to be permuted\n permute(chars.join(\"\"));\n //add removed character back into char array in original position\n chars.splice(i, 0, ch);\n //remove the last character used off the end of used characters array\n usedChars.pop();\n }\n }\n permute(str);\n return permArr;\n}\n\npermAlone('aab');\n" ], "tests": [ "assert.isNumber(permAlone('aab'), 'message: permAlone(\"aab\") should return a number.');", "assert.strictEqual(permAlone('aab'), 2, 'message: permAlone(\"aab\") should return 2.');", "assert.strictEqual(permAlone('aaa'), 0, 'message: permAlone(\"aaa\") should return 0.');", "assert.strictEqual(permAlone('aabb'), 8, 'message: permAlone(\"aabb\") should return 8.');", "assert.strictEqual(permAlone('abcdefa'), 3600, 'message: permAlone(\"abcdefa\") should return 3600.');", "assert.strictEqual(permAlone('abfdefa'), 2640, 'message: permAlone(\"abfdefa\") should return 2640.');", "assert.strictEqual(permAlone('zzzzzzzz'), 0, 'message: permAlone(\"zzzzzzzz\") should return 0.');", "assert.strictEqual(permAlone('a'), 1, 'message: permAlone(\"a\") should return 1.');", "assert.strictEqual(permAlone('aaab'), 0, 'message: permAlone(\"aaab\") should return 0.');", "assert.strictEqual(permAlone('aaabb'), 12, 'message: permAlone(\"aaabb\") should return 12.');" ], "type": "bonfire", "MDNlinks": [ "Permutations", "RegExp" ], "challengeType": 5, "translations": { "es": { "title": "Sin Repeticiones, por Favor", "description": [ "Crea una función que devuelva el número total de permutaciones de las letras en la cadena de texto provista, en las cuales no haya letras consecutivas repetidas", "Por ejemplo, 'aab' debe retornar 2 porque, del total de 6 permutaciones posibles, solo 2 de ellas no tienen repetida la misma letra (en este caso 'a').", "Recuerda utilizar Read-Search-Ask si te sientes atascado. Intenta programar en pareja. Escribe tu propio código." ] }, "it": { "title": "Niente Ripetizioni, per Favore", "description": [ "Ritorna il numero totale di permutazioni della stringa passata che non hanno lettere consecutive riptetute. Assumi che tutti i caratteri nella stringa passata siano unici.", "Per esempio, aab deve ritornare 2, perchè la stringa ha 6 permutazioni possibili in totale (aab, aab, aba, aba, baa, baa), ma solo 2 di loro (aba e aba) non contengono la stessa lettera (in questo caso a ripetuta).", "Ricorda di usare Leggi-Cerca-Chiedi se rimani bloccato. Prova a programmare in coppia. Scrivi il codice da te." ] }, "pt-br": { "title": "Sem repetição, por favor", "description": [ "Retorne o número total de permutações da string fornecida que não tem letras consecutivas repetidas. Assuma que todos os caracteres na string fornecida são únicos.", "Por exemplo, aab deve retornar 2 porque tem um total de 6 permutações (aab, aab, aba, aba, baa, baa), mas somente duas delas (aba and aba) não tem a mesma letra (nesse caso a) se repetindo.", "Lembre-se de usar Ler-Procurar-Perguntar se você ficar preso. Tente programar em par. Escreva seu próprio código." ] } } }, { "id": "a3f503de51cfab748ff001aa", "title": "Pairwise", "description": [ "Given an array arr, find element pairs whose sum equal the second argument arg and return the sum of their indices.", "You may use multiple pairs that have the same numeric elements but different indices. Each pair should use the lowest possible available indices. Once an element has been used it cannot be reused to pair with another element.", "For example pairwise([7, 9, 11, 13, 15], 20) returns 6. The pairs that sum to 20 are [7, 13] and [9, 11]. We can then write out the array with their indices and values.", "
Index01234
Value79111315
", "Below we'll take their corresponding indices and add them.", "7 + 13 = 20 → Indices 0 + 3 = 3
9 + 11 = 20 → Indices 1 + 2 = 3
3 + 3 = 6 → Return 6", "Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code." ], "challengeSeed": [ "function pairwise(arr, arg) {", " return arg;", "}", "", "pairwise([1,4,2,3,0,5], 7);" ], "solutions": [ "function pairwise(arr, arg) {\n var sum = 0;\n arr.forEach(function(e, i, a) {\n if (e != null) { \n var diff = arg-e;\n a[i] = null;\n var dix = a.indexOf(diff);\n if (dix !== -1) {\n sum += dix;\n sum += i;\n a[dix] = null;\n } \n }\n });\n return sum;\n}\n\npairwise([1,4,2,3,0,5], 7);\n" ], "tests": [ "assert.deepEqual(pairwise([1, 4, 2, 3, 0, 5], 7), 11, 'message: pairwise([1, 4, 2, 3, 0, 5], 7) should return 11.');", "assert.deepEqual(pairwise([1, 3, 2, 4], 4), 1, 'message: pairwise([1, 3, 2, 4], 4) should return 1.');", "assert.deepEqual(pairwise([1, 1, 1], 2), 1, 'message: pairwise([1, 1, 1], 2) should return 1.');", "assert.deepEqual(pairwise([0, 0, 0, 0, 1, 1], 1), 10, 'message: pairwise([0, 0, 0, 0, 1, 1], 1) should return 10.');", "assert.deepEqual(pairwise([], 100), 0, 'message: pairwise([], 100) should return 0.');" ], "type": "bonfire", "MDNlinks": [ "Array.prototype.reduce()" ], "challengeType": 5, "translations": { "es": { "title": "En Parejas", "description": [ "Crea una función que devuelva la suma de todos los índices de los elementos de 'arr' que pueden ser emparejados con otro elemento de tal forma que la suma de ambos equivalga al valor del segundo argumento, 'arg'. Si varias combinaciones son posibles, devuelve la menor suma de índices. Una vez un elemento ha sido usado, no puede ser usado de nuevo para emparejarlo con otro elemento.", "Por ejemplo, pairwise([1, 4, 2, 3, 0, 5], 7) debe devolver 11 porque 4, 2, 3 y 5 pueden ser emparejados para obtener una suma de 7", "pairwise([1, 3, 2, 4], 4) devolvería el valor de 1, porque solo los primeros dos elementos pueden ser emparejados para sumar 4. ¡Recuerda que el primer elemento tiene un índice de 0!", "Recuerda utilizar Read-Search-Ask si te sientes atascado. Intenta programar en pareja. Escribe tu propio código." ] }, "it": { "title": "A Coppie", "description": [ "Dato un array arr, trova le coppie di elementi la cui somma è uguale al secondo argomento passato arg. Ritorna quindi la somma dei loro indici.", "Se ci sono più coppie possibili che hanno lo stesso valore numerico ma indici differenti, ritorna la somma degli indici minore. Una volta usato un elemento, lo stesso non può essere riutilizzato per essere accoppiato con un altro.", "Per esempio pairwise([7, 9, 11, 13, 15], 20) ritorna 6. Le coppia la cui somma è 20 sono [7, 13] e [9, 11]. Possiamo quindi osservare l'array con i loro indici e valori.", "
Indice01234
Valore79111315
", "Qui sotto prendiamo gli indici corrispondenti e li sommiamo.", "7 + 13 = 20 → Indici 0 + 3 = 3
9 + 11 = 20 → Indici 1 + 2 = 3
3 + 3 = 6 → Ritorna 6", "Ricorda di usare Leggi-Cerca-Chiedi se rimani bloccato. Prova a programmare in coppia. Scrivi il codice da te." ] }, "pt-br": { "title": "Emparelhados", "description": [ "Dado uma matriz arr, encontre pares de elementos no qual a soma é igual ao segundo argumento arg e retorne a soma dos seus indices.", "Se multiplos pares tem o mesmo elemento numérico mas indices diferentes, retorne a soma dos menores indices. Uma vez que um elemento é usado, este não pode ser emparelhado novamente com outro elemento.", "Por exemplo pairwise([7, 9, 11, 13, 15], 20) retorna 6. Os pares que somam 20 são [7, 13] e [9, 11]. Nós podemos então criar a matriz com seus indices e valores.", "
Index01234
Value79111315
", "Abaixo nós pegamos os índices correspondentes e somá-los.", "7 + 13 = 20 → Indices 0 + 3 = 3
9 + 11 = 20 → Indices 1 + 2 = 3
3 + 3 = 6 → Retorna 6", "Lembre-se de usar Ler-Procurar-Perguntar se você ficar preso. Tente programar em par. Escreva seu próprio código." ] } } }, { "id": "8d5123c8c441eddfaeb5bdef", "title": "Implement Bubble Sort", "description": [ "This is the first of several challenges on sorting algorithms. Given an array of unsorted items, we want to be able to return a sorted array. We will see several different methods to do this and learn some tradeoffs between these different approaches. While most modern languages have built-in sorting methods for operations like this, it is still important to understand some of the common basic approaches and learn how they can be implemented.", "Here we will see bubble sort. The bubble sort method starts at the beginning of an unsorted array and 'bubbles up' unsorted values towards the end, iterating through the array until it is completely sorted. It does this by comparing adjacent items and swapping them if they are out of order. The method continues looping through the array until no swaps occur at which point the array is sorted.", "This method requires multiple iterations through the array and for average and worst cases has quadratic time complexity. While simple, it is usually impractical in most situations.", "Instructions: Write a function bubbleSort which takes an array of integers as input and returns an array of these integers in sorted order. We've provided a helper method to generate a random array of integer values." ], "challengeSeed": [ "// helper function to generate a randomly filled array", "var array = [];", "(function createArray(size) {", " array.push(+(Math.random() * 100).toFixed(0));", " return (size > 1) ? createArray(size - 1) : undefined;", "})(12);", "", "function bubbleSort(array) {", " // change code below this line", "", " // change code above this line", " return array;", "}" ], "tail": [ "function isSorted(arr) {", " var check = (i) => (i == arr.length - 1) ? true : (arr[i] > arr[i + 1]) ? false : check(i + 1);", " return check(0);", "};" ], "tests": [ "assert(typeof bubbleSort == 'function', 'message: bubbleSort is a function.');", "assert(isSorted(bubbleSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92])), 'message: bubbleSort returns a sorted array.');" ], "type": "waypoint", "solutions": [], "challengeType": 1, "translations": {} }, { "id": "587d8259367417b2b2512c85", "title": "Implement Selection Sort", "description": [ "Here we will implement selection sort. Selection sort works by selecting the minimum value in a list and swapping it with the first value in the list. It then starts at the second position, selects the smallest value in the remaining list, and swaps it with the second element. It continues iterating through the list and swapping elements until it reaches the end of the list. Now the list is sorted. Selection sort has quadratic time complexity in all cases.", "Instructions: Write a function selectionSort which takes an array of integers as input and returns an array of these integers in sorted order." ], "challengeSeed": [ "// helper function to generate a randomly filled array", "var array = [];", "(function createArray(size) {", " array.push(+(Math.random() * 100).toFixed(0));", " return (size > 1) ? createArray(size - 1) : undefined;", "})(12);", "", "function selectionSort(array) {", " // change code below this line", "", " // change code above this line", " return array;", "}" ], "tail": [ "function isSorted(arr) {", " var check = (i) => (i == arr.length - 1) ? true : (arr[i] > arr[i + 1]) ? false : check(i + 1);", " return check(0);", "};" ], "tests": [ "assert(typeof selectionSort == 'function', 'message: selectionSort is a function.');", "assert(isSorted(selectionSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92])), 'message: selectionSort returns a sorted array.');" ], "type": "waypoint", "solutions": [], "challengeType": 1, "translations": {} }, { "id": "587d8259367417b2b2512c86", "title": "Implement Insertion Sort", "description": [ "The next sorting method we'll look at is insertion sort. This method works by building up a sorted array at the beginning of the list. It begins the sorted array with the first element. Then it inspects the next element and swaps it backwards into the sorted array until it is in sorted position. It continues iterating through the list and swapping new items backwards into the sorted portion until it reaches the end. This algorithm has quadratic time complexity in the average and worst cases.", "Instructions: Write a function insertionSort which takes an array of integers as input and returns an array of these integers in sorted order." ], "challengeSeed": [ "// helper function to generate a randomly filled array", "var array = [];", "(function createArray(size) {", " array.push(+(Math.random() * 100).toFixed(0));", " return (size > 1) ? createArray(size - 1) : undefined;", "})(12);", "", "function insertionSort(array) {", " // change code below this line", "", " // change code above this line", " return array;", "}" ], "tail": [ "function isSorted(arr) {", " var check = (i) => (i == arr.length - 1) ? true : (arr[i] > arr[i + 1]) ? false : check(i + 1);", " return check(0);", "};" ], "tests": [ "assert(typeof insertionSort == 'function', 'message: insertionSort is a function.');", "assert(isSorted(insertionSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92])), 'message: insertionSort returns a sorted array.');" ], "type": "waypoint", "solutions": [], "challengeType": 1, "translations": {} }, { "id": "587d825a367417b2b2512c89", "title": "Implement Quick Sort", "description": [ "Here we will move on to an intermediate sorting algorithm: quick sort. Quick sort is an efficient, recursive divide-and-conquer approach to sorting an array. In this method, a pivot value is chosen in the original array. The array is then partitioned into two subarrays of values less than and greater than the pivot value. We then combine the result of recursively calling the quick sort algorithm on both sub-arrays. This continues until the base case of an empty or single-item array is reached, which we return. The unwinding of the recursive calls return us the sorted array.", "Quick sort is a very efficient sorting method, providing O(nlog(n)) performance on average. It is also relatively easy to implement. These attributes make it a popular and useful sorting method.", "Instructions: Write a function quickSort which takes an array of integers as input and returns an array of these integers in sorted order. While the choice of the pivot value is important, any pivot will do for our purposes here. For simplicity, the first or last element could be used." ], "challengeSeed": [ "// helper function generate a randomly filled array", "var array = [];", "(function createArray(size) {", " array.push(+(Math.random() * 100).toFixed(0));", " return (size > 1) ? createArray(size - 1) : undefined;", "})(12);", "", "function quickSort(array) {", " // change code below this line", "", " // change code above this line", " return array;", "}" ], "tests": [ "assert(typeof quickSort == 'function', 'message: quickSort is a function.');", "assert(isSorted(quickSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92])), 'message: quickSort returns a sorted array.');" ], "tail": [ "function isSorted(arr) {", " var check = (i) => (i == arr.length - 1) ? true : (arr[i] > arr[i + 1]) ? false : check(i + 1);", " return check(0);", "};" ], "type": "waypoint", "solutions": [], "challengeType": 1, "translations": {} }, { "id": "587d825c367417b2b2512c8f", "title": "Implement Merge Sort", "description": [ "Another intermediate sorting algorithm that is very common is merge sort. Like quick sort, merge sort also uses a divide-and-conquer, recursive methodology to sort an array. It takes advantage of the fact that it is relatively easy to sort two arrays as long as each is sorted in the first place. But we'll start with only one array as input, so how do we get to two sorted arrays from that? Well, we can recursively divide the original input in two until we reach the base case of an array with one item. A single-item array is naturally sorted, so then we can start combining. This combination will unwind the recursive calls that split the original array, eventually producing a final sorted array of all the elements. The steps of merge sort, then, are:", "1) Recursively split the input array in half until a sub-array with only one element is produced.", "2) Merge each sorted sub-array together to produce the final sorted array.", "Merge sort is an efficient sorting method, with time complexity of O(nlog(n)). This algorithm is popular because it is performant and relatively easy to implement.", "As an aside, this will be the last sorting algorithm we cover here. However, later in the section on tree data structures we will describe heap sort, another efficient sorting method that requires a binary heap in its implementation.", "Instructions: Write a function mergeSort which takes an array of integers as input and returns an array of these integers in sorted order. A good way to implement this is to write one function, for instance merge, which is responsible for merging two sorted arrays, and another function, for instance mergeSort, which is responsible for the recursion that produces single-item arrays to feed into merge. Good luck!" ], "challengeSeed": [ "// helper function generate a randomly filled array", "var array = [];", "(function createArray(size) {", " array.push(+(Math.random() * 100).toFixed(0));", " return (size > 1) ? createArray(size - 1) : undefined;", "})(25);", "", "function mergeSort(array) {", " // change code below this line", "", " // change code above this line", " return array;", "}" ], "tests": [ "assert(typeof mergeSort == 'function', 'message: mergeSort is a function.');", "assert(isSorted(mergeSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92])), 'message: mergeSort returns a sorted array.');" ], "tail": [ "function isSorted(arr) {", " var check = (i) => (i == arr.length - 1) ? true : (arr[i] > arr[i + 1]) ? false : check(i + 1);", " return check(0);", "};" ], "type": "waypoint", "solutions": [], "challengeType": 1, "translations": {} } ] }